commit c4d808833a86603be5d950d91a270899800eeb5e Author: Mid <> Date: Thu May 22 22:16:46 2025 +0300 Move to git diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b09434d --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +bx_enh_dbg.ini +*.bin +*.o +*.elf +*.mod +bootfs/* +partuuid.txt +*.a diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..d8ff2db --- /dev/null +++ b/Makefile @@ -0,0 +1,46 @@ +rwildcard=$(foreach d,$(wildcard $(1:=/*)),$(call rwildcard,$d,$2) $(filter $(subst *,%,$2),$d)) + +HEADERS := $(call rwildcard,src/kernel,*.h) +SOURCEC := $(call rwildcard,src/kernel,*.c) +SOURCEA := $(call rwildcard,src/kernel,*.asm) +OBJECTS := $(patsubst src/%.c, build/%.o, $(SOURCEC)) $(patsubst src/%.asm, build/%.o, $(SOURCEA)) + +drive.bin: Makefile partuuid.txt mod.ld elftomod.py bootfs/luma_vid.mod bootfs/luma_hda.mod bootfs/luma_fs.mod bootfs/luma_wm.mod bootfs/luma_uhci.mod bootfs/luma_ps2.mod boot0.bin boot1.bin $(OBJECTS) + i386-elf-ld -pie -T mod.ld -no-dynamic-linker -nostdlib -o kernel.elf $(OBJECTS) $(LDFLAGS) + ./elftomod.py kernel.elf bootfs/krnl.mod ppm_Bitmap:0 vpm_init:1 vpm_map:2 canal_init:3 pci_init:4 scheduler_init:5 scheduler_spawn:6 scheduler_start:7 + + dd if=/dev/zero of=drive.bin bs=1024 count=10240 + /bin/echo -e "mklabel msdos\nmkpart primary 8192b -1s\nquit\n" | parted drive.bin + mkdir -p mnt + /bin/echo -e "512\n20464\n0\n0\n0\n0\n" | leanfuse -O8192 -I`cat partuuid.txt` -Cdrive.bin + ./leanfuse mnt drive.bin -O8192 + cp -r bootfs/* ./mnt/ + fusermount -u ./mnt + + dd if=boot0.bin of=drive.bin bs=1 count=446 seek=0 conv=notrunc + dd if=boot1.bin of=drive.bin bs=1 seek=512 conv=notrunc + + cp drive.bin drive2.bin + +bootfs/luma_%.mod: + $(MAKE) -C luma/$* mod + +boot0.bin: src/boot0.asm boot1.bin + nasm -DBOOT1_SIZE=`stat -c %s boot1.bin` -fbin -o $@ $< + +boot1.bin: src/boot1.asm partuuid.txt + nasm -DPARTUUID=`cat partuuid.txt` -fbin -o $@ $< + +build/kernel/%.o: src/kernel/%.c + mkdir -p $(@D) + i386-elf-gcc -march=i386 -Isrc -Os -pie -nodefaultlibs -nostdlib -nostartfiles -fomit-frame-pointer -c -o $@ -ffreestanding -mgeneral-regs-only -std=gnu99 -Wall $< + +build/kernel/%.o: src/kernel/%.asm + mkdir -p $(@D) + nasm -felf32 -o $@ $< + +partuuid.txt: + openssl rand -hex 16 > partuuid.txt + +qemu: + qemu-system-i386 -m 32 -drive if=none,id=driev,format=raw,file=drive.bin -usb -debugcon stdio -soundhw hda -device usb-storage,bus=usb-bus.0,drive=driev diff --git a/README.md b/README.md new file mode 100644 index 0000000..c13b71f --- /dev/null +++ b/README.md @@ -0,0 +1,41 @@ +# Luma + +This is a PC operating system mostly for my own learning and enjoyment, but also I like the idea of giving new life to old hardware that is slowly being abandoned by the masses. It has been in development since around 2022. + +In order to work in the absence of virtual memory, all software on Luma, including the Luma kernel itself, is forced to be at least relocatable if not position-independent. Because of this Luma, unlike other kernels, does not require to be higher-half. + +Luma as a microkernel enforces only a few things, such as process scheduling or hardware access. + +Supported hardware: + +1. Minimum 80386+ +2. VGA graphics, using k-means clustering for maximal color depth +3. Intel High Definition Audio +4. Universal Host Controller Interface +5. USB BBB MSD +6. PS/2 keyboard +7. Filesystem driver for MeanFS (based on LeanFS) + +Note: though the drivers themselves work, they're limited in functionality API-wise and are mostly useless for user-space. Also, the original 80386 processors have too many bugs for Luma to feasibly work on real hardware. + +Incomplete list of planned features: + +1. Fix remaining undefined behavior before continuing +2. Rewrite the window manager to use k3Menu +3. Create a user interface for audio output +4. Kernel-level RNG +5. Support more than 16MB of RAM +6. Intel GM45 graphics for 2D +7. Intel GM45 graphics for 3D :) + +# Building + +Simply run `make` (GNU Make is required). + +Building requires an i386-elf-gcc toolchain. Clang *does not work* for reasons I have not figured out. + +Also required is the `meanfuse` program, which is a MeanFS user-space driver for Linux. + +# Boot logic + +In the interest of minimal RAM usage, Luma uses a custom bootloader (src/boot{0,1}.asm) which first initializes Luma to a valid state before handing off execution. This includes setting up the segments, the bitmap of physical memory, the initial page tables, loading the first kernel modules among other things. Slightly breaking the microkernel abstraction, this also includes setting up Mode X graphics through the 16-bit BIOS, because changing modes manually is painful. After this is done, the bootloader jumps to the Luma scheduler. diff --git a/elftoexe.py b/elftoexe.py new file mode 100755 index 0000000..ff6005a --- /dev/null +++ b/elftoexe.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python3 + +from elftools.elf.elffile import ELFFile +from elftools.elf.relocation import RelocationSection +import struct, sys, itertools +from dataclasses import dataclass +from collections import namedtuple + +def bitsize(i): + return max(len(bin(i)[2:]), 1) + +@dataclass +class X: + id: int + children: "any type" + +def dump(x): + data = b''.join(dump(c) for c in x.children) if type(x.children) == list else x.children + l = len(data) + l = l | (1 << ((bitsize(l) + 6) // 7 * 7)) + return x.id.to_bytes(length = (bitsize(x.id) + 7) // 8) + l.to_bytes(length = (bitsize(l) + 7) // 8) + data + +ARGS = {} + +for s in sys.argv[3:]: + k, v = s.split("=", 1) + ARGS[k] = v + +SYMTRANSLATION = {} + +HEADER = X(0x1A45DFA3, [X(0x4282, b'BDexeF')]) +OUTPUT = X(0x10000000, []) + +@dataclass +class ELFReloc: + offset: int + reference: int + +@dataclass +class ELFSegment: + data: bytearray + vaddr: int + relocations: list[ELFReloc] + +with open(sys.argv[1], "rb") as inp, open(sys.argv[2], "wb") as outp: + elf = ELFFile(inp) + + segments = [] + + sections_base = min([sec["sh_offset"] for sec in elf.iter_sections() if sec.name]) + + base_vaddr = min([seg["p_vaddr"] for seg in elf.iter_segments()]) + + for seg in elf.iter_segments(): + if seg["p_type"] != "PT_LOAD": + continue + + # If no section is in the segment, then ignore it + if seg["p_offset"] < sections_base and seg["p_offset"] + seg["p_filesz"] < sections_base: + continue + + inp.seek(seg["p_offset"]) + + segments.append(ELFSegment(vaddr = seg["p_vaddr"], data = bytearray(inp.read(seg["p_filesz"]) + b'\0' * (seg["p_memsz"] - seg["p_filesz"])), relocations = [])) + + rel_section = elf.get_section_by_name(".rel.dyn") + + if rel_section: + for rel in rel_section.iter_relocations(): + assert rel["r_info"] % 256 == 8 + + # The segment in which the relocation is found/required + seg_in = next((s for s in reversed(segments) if s.vaddr <= rel["r_offset"]), None) + + offset = rel["r_offset"] - seg_in.vaddr + + val = struct.unpack("I", seg_in.data[offset : offset + 4])[0] + + # The segment pointed to by the relocation + seg_ref = next((s for s in reversed(segments) if s.vaddr <= val), None) + + seg_in.data[offset : offset + 4] = struct.pack("I", val - seg_ref.vaddr) + + seg_in.relocations.append(ELFReloc(offset = rel["r_offset"] - seg_in.vaddr, reference = segments.index(seg_ref))) + + for seg in segments: + OUTPUT.children.append(X(0x6200, [ #Segment + X(0x6201, seg.data), #Segment data + X(0x6202, b''.join(struct.pack("IB", rel.offset, rel.reference) for rel in seg.relocations)) #Segment relocations + ])) + + for pub, sym in [(False, s) for s in elf.get_section_by_name(".symtab").iter_symbols()] + [(True, s) for s in elf.get_section_by_name(".dynsym").iter_symbols()]: + if not sym.name: + continue + + seg = next((s for s in reversed(segments) if s.vaddr <= sym["st_value"]), None) + + if not seg: + continue + + OUTPUT.children.append(X(0xC0, [ + X(0xC1, sym.name.encode()), + X(0xC2, struct.pack("IB", sym["st_value"] - seg.vaddr, segments.index(seg) | (128 if pub else 0))) + ])) + + outp.write(dump(HEADER)) + outp.write(dump(OUTPUT)) diff --git a/elftomod.py b/elftomod.py new file mode 100755 index 0000000..08eeb7c --- /dev/null +++ b/elftomod.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python3 + +from elftools.elf.elffile import ELFFile +from elftools.elf.relocation import RelocationSection +import sys, struct, itertools, re, os + +SYMTRANSLATION = {key: int(value) for key, value in [z.split(":") for z in sys.argv[3:]]} + +print(f"Converting {os.path.realpath(sys.argv[1])} to {os.path.realpath(sys.argv[2])}...") + +with open(sys.argv[1], "rb") as inp, open(sys.argv[2], "wb") as outp: + elf = ELFFile(inp) + loadhdr = next(elf.get_segment(i) for i in itertools.count() if elf.get_segment(i)["p_type"] == "PT_LOAD") + + relsec = elf.get_section_by_name(".rel.dyn") + datasec = elf.get_section_by_name(".text") + + data = bytearray(datasec.data()) + data += bytearray(loadhdr["p_memsz"] - len(data)) #Make space to fit .bss + + outp.write(b"MOD\0") + + syms = [s for s in elf.get_section_by_name(".symtab").iter_symbols() if s.name in SYMTRANSLATION] + syms.sort(key = lambda s: SYMTRANSLATION[s.name]) + + relocs = [r for r in relsec.iter_relocations()] if relsec else [] + + outp.write(struct.pack("H", len(syms))) + outp.write(struct.pack("H", len(relocs))) + outp.write(struct.pack("I", len(data))) + + for i, s in enumerate(syms): + outp.write(struct.pack("H", i)) #struct.pack emits 8 bytes when you put HI directly + outp.write(struct.pack("I", s.entry["st_value"] - datasec["sh_addr"])) + + for r in relocs: + assert(r["r_info"] % 256 == 8) + + idx = r["r_offset"] - datasec["sh_addr"] + data[idx:idx + 4] = struct.pack("I", struct.unpack("I", data[idx:idx + 4])[0] - datasec["sh_addr"]) + + outp.write(struct.pack("I", idx)) + + # Align to 16 + if outp.tell() % 16 != 0: + outp.write(b"\0" * (16 - outp.tell() % 16)) + + outp.write(data) diff --git a/exe.ld b/exe.ld new file mode 100644 index 0000000..fe54f81 --- /dev/null +++ b/exe.ld @@ -0,0 +1,20 @@ +SECTIONS +{ + /* Linkers like to insert the ELF headers into the segments themselves + Page-aligning the base address minimzies the likelihood of this happening */ + . = 0x10000; + .text : ALIGN(0x1000) { *(.text) *(.rodata) } + .data : ALIGN(0x1000) { *(.data) *(.bss) } + + /DISCARD/ : { + *(.note.GNU-stack) + *(.gnu_debuglink) + *(.gnu.lto_*) + *(.note.gnu.build-id) + *(.eh_frame_hdr) + *(.eh_frame_entry .eh_frame_entry.*) + *(.eh_frame) + *(.eh_frame.*) + *(.interp) + } +} diff --git a/luma/ata/dio.h b/luma/ata/dio.h new file mode 100644 index 0000000..3ca34b8 --- /dev/null +++ b/luma/ata/dio.h @@ -0,0 +1,17 @@ +#ifndef _LUMA_DIO +#define _LUMA_DIO + +typedef enum { + LUMA_DIO_COMMAND_READ +} LumaDIOCommandOp; + +typedef union { + uint8_t op; + struct { + uint8_t op; + uint32_t lba; + uint32_t count; + } read; +} LumaDIOCommand; + +#endif \ No newline at end of file diff --git a/luma/ata/main.c b/luma/ata/main.c new file mode 100644 index 0000000..979c204 --- /dev/null +++ b/luma/ata/main.c @@ -0,0 +1,85 @@ +#include +#include +#include"../sys.h" +#include"dio.h" + +#define IO_BASE 0x1F0 +#define REG_DATA 0 +#define REG_RERROR_WFEATURES 1 +#define REG_SECTOR_COUNT 2 +#define REG_LBA_LOW 3 +#define REG_LBA_MIDDLE 4 +#define REG_LBA_HIGH 5 +#define REG_DRIVE 6 +#define REG_RSTATUS_WCOMMAND 7 + +char stack[768]; +uint16_t data[256]; + +static void waitUntilReady() { + while((inb(IO_BASE + REG_RSTATUS_WCOMMAND) & 128) == 128) { + } + while((inb(IO_BASE + REG_RSTATUS_WCOMMAND) & 8) == 0) { + } +} + +static void wait400() { + inb(0x3F6); + inb(0x3F6); + inb(0x3F6); + inb(0x3F6); +} + +void startc() { + outb(IO_BASE + REG_DRIVE, 0xA0); + outb(IO_BASE + REG_SECTOR_COUNT, 0); + outb(IO_BASE + REG_LBA_LOW, 0); + outb(IO_BASE + REG_LBA_MIDDLE, 0); + outb(IO_BASE + REG_LBA_HIGH, 0); + outb(IO_BASE + REG_RSTATUS_WCOMMAND, 0xEC); + + waitUntilReady(); + + /* IDENTIFY data, which we don't need (yet). */ + for(int i = 0; i < 256; i++) { + inw(IO_BASE + REG_DATA); + } + + uint32_t canalID = sys_canal_create(0x42444844, 0x00000000); + + uint16_t *buf = (void*) -1; + do { + buf = sys_canal_accept(canalID); + } while(buf == (void*) -1); + + while(1) { + memory_barrier(); + sys_signal_wait(SYS_SIGNAL_WAIT_ANY); + + LumaDIOCommand *cmd = (void*) buf; + if(cmd->op == LUMA_DIO_COMMAND_READ) { + uint8_t count = cmd->read.count; + + outb(IO_BASE + REG_DRIVE, 0xE0); + outb(IO_BASE + REG_RERROR_WFEATURES, 0x00); + outb(IO_BASE + REG_SECTOR_COUNT, count); + outb(IO_BASE + REG_LBA_LOW, (cmd->read.lba >> 0) & 0xFF); + outb(IO_BASE + REG_LBA_MIDDLE, (cmd->read.lba >> 8) & 0xFF); + outb(IO_BASE + REG_LBA_HIGH, (cmd->read.lba >> 16) & 0xFF); + outb(IO_BASE + REG_RSTATUS_WCOMMAND, 0x20); + + int w = 0; + while(count--) { + waitUntilReady(); + for(int i = 0; i < 256; i++) { + buf[w++] = inw(IO_BASE + REG_DATA); + } + } + + wait400(); + } + + memory_barrier(); + sys_signal_send(buf); + } +} \ No newline at end of file diff --git a/luma/cardistry/main.c b/luma/cardistry/main.c new file mode 100644 index 0000000..6cc5b23 --- /dev/null +++ b/luma/cardistry/main.c @@ -0,0 +1,21 @@ +#include"../sys.h" + +#include"../wm/api.h" + +void giveup() { + for(int i = 0; i < 15; i++) { + asm("outb %%al, $0xE9" :: "a"('A') :); + asm("outb %%al, $0xE9" :: "a"('\n') :); + } + while(1); +} + +__attribute__((noreturn)) void ProgramEntry() { + LumaWMClient wmcli; + + if(luma_wm_client(&wmcli) == 0) { + giveup(); + } + + while(1); +} diff --git a/luma/fs/Makefile b/luma/fs/Makefile new file mode 100644 index 0000000..fca01d4 --- /dev/null +++ b/luma/fs/Makefile @@ -0,0 +1,13 @@ +rwildcard=$(foreach d,$(wildcard $(1:=/*)),$(call rwildcard,$d,$2) $(filter $(subst *,%,$2),$d)) + +HEADERS := $(call rwildcard,.,*.h) +SOURCEC := $(call rwildcard,.,*.c) +OBJECTS := $(patsubst %.c, ../../build/lean/%.o, $(SOURCEC)) + +mod: $(OBJECTS) + i386-elf-gcc -pie -T ../../mod.ld -Wl,-no-dynamic-linker -nostdlib -o main.elf $(OBJECTS) -lgcc + ../../elftomod.py main.elf ../../bootfs/luma_fs.mod modentry:0 + +../../build/lean/%.o: %.c + mkdir -p $(@D) + i386-elf-gcc -march=i386 -Isrc -Os -pie -nodefaultlibs -nostdlib -nostartfiles -fomit-frame-pointer -c -o $@ -ffreestanding -mgeneral-regs-only -std=gnu99 -Wall $< diff --git a/luma/fs/fs.h b/luma/fs/fs.h new file mode 100644 index 0000000..03977f9 --- /dev/null +++ b/luma/fs/fs.h @@ -0,0 +1,39 @@ +#ifndef _LUMA_FS_H +#define _LUMA_FS_H + +#include"../std.h" + +// Paths are not handled as strings, but rather as packed arrays of strings +// This way there is no need for escaping, separators, etc. + +typedef enum { + LUMA_FS_COMMAND_READ, LUMA_FS_COMMAND_INFO, LUMA_FS_COMMAND_TRAVERSE +} LumaFSCommandOp; + +typedef union { + uint8_t op; + struct { + uint8_t op; + uint64_t offset; + uint32_t bytes; + uint8_t path[]; //Packed array of Str16 + } read; + struct { + uint8_t op; + uint64_t fileSize; + uint8_t path[]; //Packed array of Str16 + } info; + struct { + uint8_t op; + uint8_t path[]; // Packed array of Str16 + } traverse; +} LumaFSCommand; + +#define LUMA_FS_DIR_ENTRY_ISDIR 2 +#define LUMA_FS_DIR_ENTRY_LAST 1 +typedef struct { + uint16_t type; + Str16 name; +} LumaFSDirectoryEntry; + +#endif \ No newline at end of file diff --git a/luma/fs/main.c b/luma/fs/main.c new file mode 100644 index 0000000..37e8067 --- /dev/null +++ b/luma/fs/main.c @@ -0,0 +1,475 @@ +#include"../sys.h" + +#include +#include +#include"../std.h" +#include"fs.h" + +asm("modentry:\n" +"mov $stack + 2048, %esp\n" +"call startc"); + +char stack[3072]; + +// Should be renamed. This *isn't* LeanFS, however inspired it may be. + +#define EXTENTS_PER_INODE 6 + +#define INODE_ftRegular 1 +#define INODE_ftDirectory 2 +#define INODE_ftMask 7 + +#define INODE_ATTRIBUTE_iaInlineExtAttr (1 << 19) +#define INODE_ATTRIBUTE_iaFmtRegular (1 << 29) +#define INODE_ATTRIBUTE_iaFmtDirectory (2 << 29) +#define INODE_ATTRIBUTE_iaFmtMask (7 << 29) + + +struct Superblock { + uint32_t checksum; + uint32_t magic; + uint16_t fsVersion; + uint8_t preallocCount; + uint8_t logBlocksPerBand; + uint32_t state; + uint8_t uuid[16]; + char volumeLabel[64]; + uint64_t blockCount; + uint64_t freeBlockCount; + uint64_t primarySuper; + uint64_t backupSuper; + uint64_t bitmapStart; + uint64_t rootInode; + uint64_t badInode; + uint64_t journalInode; + uint8_t logBlockSize; + uint8_t reserved0[7]; +} __attribute__((packed, aligned(4))); + +struct INode { + uint32_t checksum; + uint32_t magic; + uint8_t extentCount; + uint8_t reserved[3]; + uint32_t indirectCount; + uint32_t linkCount; + uint32_t uid; + uint32_t gid; + uint32_t attributes; + uint64_t fileSize; + uint64_t blockCount; + int64_t accessTime; + int64_t statusChangeTime; + int64_t modificationTime; + int64_t creationTime; + uint64_t firstIndirect; + uint64_t lastIndirect; + uint64_t fork; + uint64_t extentStarts[EXTENTS_PER_INODE]; + uint32_t extentSizes[EXTENTS_PER_INODE]; +} __attribute__((packed)); + +struct DirectoryEntry { + uint64_t inode; + uint8_t type; + uint8_t recLen; + uint16_t nameLen; + uint8_t name[]; +} __attribute__((packed)); + +uint8_t *diskWindow = (uint8_t*) -1; + +size_t volumeStartLBA, superblockLBA; +struct Superblock superblock; + +void read(size_t start, size_t length) { + ((uint64_t*) diskWindow)[0] = start; + ((uint32_t*) diskWindow)[2] = length; + + memory_barrier(); + sys_signal_send(diskWindow, 0); + + sys_signal_wait(diskWindow, NULL); +} + +static uint32_t lean_compute_checksum(const uint32_t *buf, size_t dwordLength, size_t dwordPadTo) { + uint32_t sum = 0; + + size_t i = 1; + for(; i < dwordLength; i++) { + sum = (sum << 31) + (sum >> 1); + sum += buf[i]; + } + + for(; i < dwordPadTo; i++) { + sum = (sum << 31) + (sum >> 1); + } + + return sum; +} + +int parse_inode(size_t id) { + read(volumeStartLBA * 512 + (id << superblock.logBlockSize), 1 << superblock.logBlockSize); + + struct INode *test = (struct INode*) diskWindow; + + if(test->magic != 0x45444F4E) { + return 0; + } + + // Driver has outdated checksums +#if 0 + if(lean_compute_checksum((uint32_t*) test, (sizeof(struct INode)) >> 2, (sizeof(struct INode)) >> 2) != test->checksum) { + return 0; + } +#endif + + return 1; +} + +size_t lean_read_inode(const struct INode *inode, size_t off, size_t len, uint8_t *ret) { + if(off + len > inode->fileSize) { + len = inode->fileSize - off; + } + + if(inode->attributes & INODE_ATTRIBUTE_iaInlineExtAttr) { + off += 1 << superblock.logBlockSize; + } else { + off += sizeof(struct INode); + } + + size_t startBlk = off >> superblock.logBlockSize; + size_t endBlk = (off + len - 1) >> superblock.logBlockSize; + + uint32_t b = 0; + uint32_t ei, eb; + for(ei = 0; ei < EXTENTS_PER_INODE; ei++) { + for(eb = 0; eb < inode->extentSizes[ei]; eb++) { + if(b == startBlk) { + goto foundStart; + } + + b++; + } + } + + // Not found. Corruption? + return 0; + +foundStart: + + while(1) { + read(volumeStartLBA * 512 + ((inode->extentStarts[ei] + eb) << superblock.logBlockSize), 1 << superblock.logBlockSize); + + if(b == startBlk && b == endBlk) { + std_copy(ret, diskWindow + off, len); + + break; + } else if(b == startBlk) { + uint16_t mod = off % (1 << superblock.logBlockSize); + + std_copy(ret, diskWindow + mod, (1 << superblock.logBlockSize) - mod); + + ret += (1 << superblock.logBlockSize) - mod; + } else if(b == endBlk) { + uint16_t mod = (off + len - 1) % (1 << superblock.logBlockSize); + + std_copy(ret, diskWindow, mod + 1); + + break; + } else { + std_copy(ret, diskWindow, 1 << superblock.logBlockSize); + + ret += 1 << superblock.logBlockSize; + } + + eb++, b++; + + if(eb == inode->extentSizes[ei]) { + eb = 0; + ei++; + + if(ei == EXTENTS_PER_INODE) { + // Stop. Indirect blocks not yet supported. + return 0; + } + } + } + + return len; +} + +static inline void pr(int c) { + asm volatile("outb %%al, $0xE9" :: "a"(c) :); +} + +static inline void pri(size_t num) { + char buf[16] = {}; + int i = 16; + + do { + buf[--i] = num % 10; + num /= 10; + } while(num); + + for(; i < 16; i++) { + pr(buf[i] + '0'); + } +} + +static inline void prs(const Str16 *str) { + for(int i = 0; i < str->len; i++) { + pr(str->data[i]); + } +} + +static inline void prcs(const char *str) { + while(*str) { + pr(*str); + str++; + } +} + +// I don't like this. +// Biggest ugly by far is how it operates in 512-byte chunks, even though lean_read_inode already handles unaligned access +uint64_t find_child(const struct INode *node, const Str16 *name) { + uint8_t buf[512] __attribute__((aligned(16))); + + size_t offset = 0; + lean_read_inode(node, offset, sizeof(buf), buf); + + struct DirectoryEntry *e = (struct DirectoryEntry*) buf; + while(1) { + if(offset + ((uintptr_t) e - (uintptr_t) buf) >= node->fileSize) { + // Reached EOF. + return 0; + } else while((uintptr_t) e >= (uintptr_t) buf + sizeof(buf)) { + offset += sizeof(buf); + lean_read_inode(node, offset, sizeof(buf), buf); + e = (struct DirectoryEntry*) (((uintptr_t) e - (uintptr_t) buf) % sizeof(buf) + (uintptr_t) buf); + } + + if(e->nameLen != name->len) { + uintptr_t after = (uintptr_t) e + 16 * e->recLen; + + e = (struct DirectoryEntry*) after; + + goto next; + } + + // Must be saved, as `e` becomes invalid in the following for loop + uint64_t childinode = e->inode; + size_t nameLen = e->nameLen; + uint8_t *testname = e->name; + for(uint16_t i = 0; i < nameLen; i++) { + if(testname - buf == sizeof(buf)) { + offset += sizeof(buf); + lean_read_inode(node, offset, sizeof(buf), buf); + testname = buf; + } + if(*testname != name->data[i]) { + testname += nameLen - i; + + e = (struct DirectoryEntry*) ((((uintptr_t) testname) + 15) & ~15); + + goto next; + } + testname++; + } + + return childinode; + +next: + } +} + +uint64_t get_inode_from_str16_path(const Str16 *path, struct INode *data) { + uint64_t child = superblock.rootInode; + if(!parse_inode(child)) { + return 0; + } + std_copy(data, diskWindow, sizeof(*data)); + + while(path->len) { + child = find_child(data, path); + + if(!child) { + return 0; + } + + if(!parse_inode(child)) { + return 0; + } + std_copy(data, diskWindow, sizeof(*data)); + + path = (const Str16*) ((uintptr_t) path + sizeof(*path) + path->len); + } + + return child; +} + +void startc() { + do { + diskWindow = sys_link_create('STRG', 'UD\0\0', 4096); + } while(diskWindow == (void*) -1); + + read(0, 512); + volumeStartLBA = *(uint32_t*) &diskWindow[0x1C6]; + + int found = 0; + for(size_t superblockLBA = 0; superblockLBA < 256; superblockLBA++) { + read((volumeStartLBA + superblockLBA) * 512, 512); + + struct Superblock *candidate = (struct Superblock*) diskWindow; + + if(candidate->magic == 0x4E41454C && lean_compute_checksum((uint32_t*) diskWindow, sizeof(struct Superblock) >> 2, (1 << candidate->logBlockSize) >> 2) == candidate->checksum) { + superblock = *(struct Superblock*) diskWindow; + found = 1; + break; + } + } + + if(found) { + uint32_t canalID = sys_canal_create('FS\0\0', 'ROOT'); + while(1) { + sys_canal_accept(canalID); + + uint8_t *fsBuf = sys_signal_wait(SYS_SIGNAL_WAIT_ANY, NULL); + memory_barrier(); + + LumaFSCommand *cmd = (void*) fsBuf; + if(cmd->op == LUMA_FS_COMMAND_READ) { + struct INode data; + uint64_t inode = get_inode_from_str16_path((Str16*) cmd->read.path, &data); + + if(inode) { + size_t offset = cmd->read.offset; + uint32_t left = cmd->read.bytes; + + if(left) { + while(1) { + size_t amount = left > 4096 ? 4096 : left; + + size_t actuallyRead = lean_read_inode(&data, offset, amount, fsBuf); + if(actuallyRead < amount) { + amount = actuallyRead; + left = actuallyRead; + } + + memory_barrier(); + sys_signal_send(fsBuf, amount); + + if(left == 4096) { + sys_signal_wait(fsBuf, NULL); + sys_signal_send(fsBuf, 0); + break; + } else { + offset += amount; + left -= amount; + + if(left == 0) { + break; + } else { + sys_signal_wait(fsBuf, NULL); + } + } + } + } + } else { + memory_barrier(); + sys_signal_send(fsBuf, 0); + } + } else if(cmd->op == LUMA_FS_COMMAND_INFO) { + struct INode data; + uint64_t inode = get_inode_from_str16_path((Str16*) cmd->info.path, &data); + + prcs("Requesting info "); + prs(cmd->info.path); + pr('\n'); + + prcs("Got inode "); + pri(inode); + pr('\n'); + + if(inode) { + prcs("Size "); + pri(data.fileSize); + pr('\n'); + + prcs("magic "); + pri(data.magic); + pr('\n'); + + cmd->info.fileSize = data.fileSize; + + memory_barrier(); + sys_signal_send(fsBuf, 1); + } else { + memory_barrier(); + sys_signal_send(fsBuf, 0); + } + } else if(cmd->op == LUMA_FS_COMMAND_TRAVERSE) { + struct INode data; + uint64_t inode = get_inode_from_str16_path((Str16*) cmd->traverse.path, &data); + + if(inode) { + size_t offset = 0, left = data.fileSize; + uint8_t buf[512] __attribute__((aligned(16))); + + lean_read_inode(&data, offset, sizeof(buf), buf); + + struct DirectoryEntry *in = (struct DirectoryEntry*) buf; + + LumaFSDirectoryEntry *out = (LumaFSDirectoryEntry*) fsBuf; + + while(1) { + size_t len = in->nameLen > 255 ? 255 : in->nameLen; + + if((uintptr_t) out + sizeof(*buf) + len > (uintptr_t) fsBuf + 4096) { + memory_barrier(); + sys_signal_send(fsBuf, 2); + sys_signal_wait(fsBuf, NULL); + } + + out->type = ((in->type & INODE_ftMask) == INODE_ftDirectory) ? LUMA_FS_DIR_ENTRY_ISDIR : 0; + out->name.len = len; + uint8_t *nameIn = in->name; + for(size_t n = 0; n < out->name.len; n++) { + out->name.data[n] = *(nameIn++); + if((uintptr_t) nameIn == (uintptr_t) buf + sizeof(buf)) { + offset += sizeof(buf); + left -= sizeof(buf); + lean_read_inode(&data, offset, sizeof(buf), buf); + nameIn = buf; + } + } + + in = (struct DirectoryEntry*) (((uintptr_t) nameIn + 15) & ~15); + if(offset + ((uintptr_t) in - (uintptr_t) buf) == data.fileSize) { + out->type |= LUMA_FS_DIR_ENTRY_LAST; + break; + } else if((uintptr_t) in == (uintptr_t) in + sizeof(buf)) { + offset += sizeof(buf); + left -= sizeof(buf); + lean_read_inode(&data, offset, sizeof(buf), buf); + in = (struct DirectoryEntry*) buf; + } + + out = (LumaFSDirectoryEntry*) ((uintptr_t) out + sizeof(*out) + len); + } + + memory_barrier(); + sys_signal_send(fsBuf, 1); + } else { + memory_barrier(); + sys_signal_send(fsBuf, 0); + } + } else { + memory_barrier(); + sys_signal_send(fsBuf, 0); + } + } + } else { + while(1) { sys_signal_wait(SYS_SIGNAL_WAIT_ANY, NULL); } + } +} diff --git a/luma/hda/Makefile b/luma/hda/Makefile new file mode 100644 index 0000000..122a724 --- /dev/null +++ b/luma/hda/Makefile @@ -0,0 +1,13 @@ +rwildcard=$(foreach d,$(wildcard $(1:=/*)),$(call rwildcard,$d,$2) $(filter $(subst *,%,$2),$d)) + +HEADERS := $(call rwildcard,.,*.h) +SOURCEC := $(call rwildcard,.,*.c) +OBJECTS := $(patsubst %.c, ../../build/hda/%.o, $(SOURCEC)) + +mod: $(OBJECTS) + i386-elf-gcc -pie -T ../../mod.ld -Wl,-no-dynamic-linker -nostdlib -o main.elf $(OBJECTS) -lgcc + ../../elftomod.py main.elf ../../bootfs/luma_hda.mod modentry:0 + +../../build/hda/%.o: %.c + mkdir -p $(@D) + i386-elf-gcc -march=i386 -Isrc -Os -pie -nodefaultlibs -nostdlib -nostartfiles -fomit-frame-pointer -c -o $@ -ffreestanding -mgeneral-regs-only -std=gnu99 -Wall $< diff --git a/luma/hda/main.c b/luma/hda/main.c new file mode 100644 index 0000000..769c2b9 --- /dev/null +++ b/luma/hda/main.c @@ -0,0 +1,304 @@ +#include"../sys.h" + +asm("modentry:\n" +"mov $stack + 1536, %esp\n" +"call startc"); + +#include"../std.h" + +char stack[2048]; + +#define FORMAT_CHANNELS(n) ((n) - 1) +#define FORMAT_16BPS (1 << 4) +#define FORMAT_RATE_MUL_1 0 +#define FORMAT_RATE_DIV_1 0 +#define FORMAT_PCM (0 << 15) +#define FORMAT_48KHZ (0 << 14) + +#define STANDARD_48KHZ_16BPS (FORMAT_CHANNELS(1) | FORMAT_PCM | FORMAT_48KHZ | FORMAT_RATE_MUL_1 | FORMAT_RATE_DIV_1 | FORMAT_16BPS) + +#define STREAM_RUN_BIT 2 +#define STREAM_NO(n) ((n) << 20) + +struct BufDescEntry { + uint64_t addr; + uint32_t length; + uint32_t flags; +}; +static struct BufDescEntry *bufDesc; + +volatile uint32_t *HDA; + +#define WIDGET_TYPE(w) (((w)->cap >> 20) & 15) +#define WIDGET_AMP_OVERRIDE(w) (((w)->cap >> 3) & 1) +struct Widget { + uint32_t cap; + uint8_t connectionCount; + uint8_t queued; //Used for BFS + uint8_t parent; +}; +static uint8_t WidgetCount, WidgetsStart; + +static uint8_t TheCodec, ThePin; +static uint32_t DefaultAFGInAmpCaps; +static uint32_t DefaultAFGOutAmpCaps; + +static struct Widget widgets[64]; + +static uint32_t cmd(uint8_t codec, uint8_t node, uint32_t c) { + HDA[26] = 2; + HDA[24] = (codec << 28) | (node << 20) | c; + HDA[26] = 1; + while((HDA[26] & 3) != 2); + return HDA[25]; +} +static uint32_t verb(uint8_t codec, uint8_t node, uint16_t v, uint8_t payload) { + return cmd(codec, node, (v << 8) | payload); +} + +static uint32_t verb16(uint8_t codec, uint8_t node, uint16_t v, uint16_t payload) { + return cmd(codec, node, (v << 16) | payload); +} + +static void unmute(uint8_t widget, int output, int from, int to) { + uint32_t ampcap; + if(WIDGET_AMP_OVERRIDE(widgets + widget - WidgetsStart)) { + ampcap = verb(TheCodec, widget, 0xF00, 0xD + 5 * output); + } else { + ampcap = output ? DefaultAFGOutAmpCaps : DefaultAFGInAmpCaps; + } + for(int i = from; i <= to; i++) { + verb16(TheCodec, widget, 0x3, (ampcap & 127) | (i << 8) | (3 << 12) | ((1 + output) << 14)); + } +} + +static void klogc(int c) { + asm volatile("outb %%al, $0xE9"::"a"(c):); +} +static void klogp(void *p) { + static char hex[16]="0123456789ABCDEF"; + + uintptr_t i = (uintptr_t) p; + klogc(hex[(i >> 28) & 0xF]); + klogc(hex[(i >> 24) & 0xF]); + klogc(hex[(i >> 20) & 0xF]); + klogc(hex[(i >> 16) & 0xF]); + klogc(hex[(i >> 12) & 0xF]); + klogc(hex[(i >> 8) & 0xF]); + klogc(hex[(i >> 4) & 0xF]); + klogc(hex[(i >> 0) & 0xF]); +} + +void startc() { + uint32_t hcId = sys_pci_claim(0x04030000); + if(hcId == (uint32_t) -1) { + while(1) sys_signal_wait(SYS_SIGNAL_WAIT_ANY, NULL); + } + + // Clear TCSEL + sys_pci_write_1(hcId, 0x44, sys_pci_read(hcId, 0x44) & ~7); + + // Enable busmastering + sys_pci_write_2(hcId, 0x04, sys_pci_read(hcId, 0x04) | 7); + + HDA = sys_vpm_map(SYS_MAP_VIRT_ANY, (void*) (sys_pci_read(hcId, 0x10) & 0xFFFFFFF0), 4096); + + // Start reset. + HDA[2] = 0; + while((HDA[2] & 1) != 0); + sys_sleep(50); + + // Finish reset. + HDA[2] = 1; + while((HDA[2] & 1) == 0); + sys_sleep(10); + + int16_t *audbuf = sys_vpm_map(SYS_MAP_VIRT_ANY, SYS_MAP_PHYS_ANY, 8192 * sizeof(*audbuf)); + for(int i = 0; i < 8192; i++) { + //// 2 buffers of square wave + audbuf[i] = i % 128 < 64 ? 10000 : -10000; + //audbuf[i] = 0; + } + + bufDesc = sys_vpm_map(SYS_MAP_VIRT_ANY, SYS_MAP_PHYS_ANY, 4096); + + bufDesc[0].addr = (uintptr_t) sys_vpm_get_phys(&audbuf[0]); + bufDesc[0].length = 8192; + bufDesc[0].flags = 1; + + bufDesc[1].addr = (uintptr_t) sys_vpm_get_phys(&audbuf[4096]); + bufDesc[1].length = 8192; + bufDesc[1].flags = 1; + + uint32_t *dmapos = (uint32_t*) &bufDesc[8]; + HDA[28] = 1 | (uintptr_t) sys_vpm_get_phys(dmapos); + HDA[29] = 0; + + uint16_t gcap = *(volatile uint16_t*) HDA; + uint8_t inputStreamCount = (gcap >> 8) & 15; + + volatile uint32_t *outStream = HDA + 0x20 + 8 * inputStreamCount; + outStream[0] &= ~2; // Disable run + + // Reset. + outStream[0] |= 1; + int timeout = 500; + while((outStream[0] & 1) == 0 && timeout--); + + // Unreset. + outStream[0] &= ~1; + timeout = 500; + while((outStream[0] & 1) != 0 && timeout--); + + outStream[0] = STREAM_NO(1); + outStream[2] = 16384; + ((volatile uint16_t*) outStream)[9] = STANDARD_48KHZ_16BPS; + ((volatile uint16_t*) outStream)[6] = 1; + outStream[6] = (uintptr_t) sys_vpm_get_phys(bufDesc); + outStream[7] = 0; + + sys_sleep(10); + + uint16_t statests = ((volatile uint16_t*) HDA)[7]; + for(int codec = 0; codec < 15; codec++) { + if(statests & (1 << codec)) { + TheCodec = codec; + break; + } + } + + // Get subordinate nodes + uint32_t boob = verb(TheCodec, 0, 0xF00, 4); + + uint8_t startIdx = (boob >> 16) & 0xFF; + uint8_t endIdx = startIdx + (boob & 0xFF); + for(int idx = startIdx; idx < endIdx; idx++) { + // Get function group type + uint32_t type = verb(TheCodec, idx, 0xF00, 5); + + if((type & 127) == 1) { + // Is audio function group + + // Power + verb(TheCodec, idx, 0x705, 0); + + sys_sleep(200); + + DefaultAFGInAmpCaps = verb(TheCodec, idx, 0xF00, 0xD); + DefaultAFGOutAmpCaps = verb(TheCodec, idx, 0xF00, 0x12); + + // Get subordinate nodes + uint32_t tit = verb(TheCodec, idx, 0xF00, 4); + + // Iterate over widgets + uint8_t wIdxStart = (tit >> 16) & 0xFF; + uint8_t wIdxEnd = wIdxStart + (tit & 0xFF); + + int outPinWPriority = 0; + int outPinWIdx = -1; + + WidgetsStart = wIdxStart; + + // We'll play audio through one pin with highest priority (headphones) + for(int w = wIdxStart; w < wIdxEnd; w++) { + struct Widget *wstruc = &widgets[WidgetCount]; + + wstruc->cap = verb(TheCodec, w, 0xF00, 9); + + if(WIDGET_TYPE(wstruc) == 4) { //pin + uint32_t confdef = verb(TheCodec, w, 0xF1C, 0); + + uint8_t dev = (confdef >> 20) & 15; + + int priority; + if(dev == 2) { + // headphone + priority = 3; + } else if(dev == 1) { + // speaker + priority = 2; + } else if(dev == 0) { + // line out + priority = 1; + outPinWIdx = WidgetCount; + } + + if(priority > outPinWPriority) { + outPinWPriority = priority; + outPinWIdx = WidgetCount; + } + } + + wstruc->connectionCount = verb(TheCodec, w, 0xF00, 14); + + WidgetCount++; + + // power on + verb(TheCodec, w, 0x705, 0); + } + + ThePin = outPinWIdx; + + break; + } + } + + // Hardcoded path + unmute(0x11, 0, 0, 0); + unmute(0x11, 1, 0, 0); + verb(TheCodec, 0x11, 0x70C, 2); //eapd on + verb(TheCodec, 0x11, 0x707, (1 << 6) | (1 << 7)); // pin out + + unmute(0x07, 0, 0, 15); + unmute(0x07, 1, 0, 15); + + unmute(0x22, 1, 0, 0); + verb(TheCodec, 0x22, 0x701, 0); + + unmute(0x03, 1, 0, 0); + verb16(TheCodec, 0x03, 0x2, STANDARD_48KHZ_16BPS); + verb(TheCodec, 0x03, 0x706, (1 << 4) | (0 << 0)); + + HDA[13] = 0xFFFFFFFF; + HDA[14] = 0xFFFFFFFF; + + sys_sleep(10); + + memory_barrier(); + outStream[0] |= STREAM_RUN_BIT; + + while((outStream[0] & (1 << 29)) == 0) memory_barrier(); + + sys_sleep(10); + + HDA[13] = 0; + HDA[14] = 0; + + // Create canal + uint32_t canalID = sys_canal_create('AUD\0', 'HDA0'); + uint8_t *AudioLink = (void*) -1; + do { + AudioLink = sys_canal_accept(canalID); + } while(AudioLink == (void*) -1); + + sys_signal_send(AudioLink, 0); + + while(1) { + sys_signal_wait(AudioLink, NULL); + memory_barrier(); + + while((outStream[0] & (1 << 26)) == 0); + outStream[0] |= 1 << 26; + + //int buf = (outStream[1] / 8192) ^ 1; + static int buf = 0; + + std_copy(audbuf + buf * 4096, AudioLink, 8192); + buf ^= 1; + + memory_barrier(); + sys_signal_send(AudioLink, 0); + } + + while(1) sys_signal_wait(SYS_SIGNAL_WAIT_ANY, NULL); +} diff --git a/luma/ps2/Makefile b/luma/ps2/Makefile new file mode 100644 index 0000000..fdccc6f --- /dev/null +++ b/luma/ps2/Makefile @@ -0,0 +1,13 @@ +rwildcard=$(foreach d,$(wildcard $(1:=/*)),$(call rwildcard,$d,$2) $(filter $(subst *,%,$2),$d)) + +HEADERS := $(call rwildcard,.,*.h) +SOURCEC := $(call rwildcard,.,*.c) +OBJECTS := $(patsubst %.c, ../../build/ps2/%.o, $(SOURCEC)) + +mod: $(OBJECTS) + i386-elf-gcc -pie -T ../../mod.ld -Wl,-no-dynamic-linker -nostdlib -o main.elf $(OBJECTS) -lgcc + ../../elftomod.py main.elf ../../bootfs/luma_ps2.mod modentry:0 + +../../build/ps2/%.o: %.c + mkdir -p $(@D) + i386-elf-gcc -march=i386 -Isrc -Os -pie -nodefaultlibs -nostdlib -nostartfiles -fomit-frame-pointer -c -o $@ -ffreestanding -mgeneral-regs-only -std=gnu99 -Wall $< diff --git a/luma/ps2/api.h b/luma/ps2/api.h new file mode 100644 index 0000000..33d7854 --- /dev/null +++ b/luma/ps2/api.h @@ -0,0 +1,97 @@ +#ifndef _LUMA_KBD_H +#define _LUMA_KBD_H + +enum LumaKbdScancode { + LK_INVALID, + LK_0, + LK_1, + LK_2, + LK_3, + LK_4, + LK_5, + LK_6, + LK_7, + LK_8, + LK_9, + LK_F1, + LK_F2, + LK_F3, + LK_F4, + LK_F5, + LK_F6, + LK_F7, + LK_F8, + LK_F9, + LK_F10, + LK_F11, + LK_F12, + LK_PAUSE, + LK_LEFT_ALT, + LK_RIGHT_ALT, + LK_LEFT_SHIFT, + LK_RIGHT_SHIFT, + LK_LEFT_CTRL, + LK_RIGHT_CTRL, + LK_LEFT_SYS, + LK_RIGHT_SYS, + LK_BACKSPACE, + LK_A, + LK_B, + LK_C, + LK_D, + LK_E, + LK_F, + LK_G, + LK_H, + LK_I, + LK_J, + LK_K, + LK_L, + LK_M, + LK_N, + LK_O, + LK_P, + LK_Q, + LK_R, + LK_S, + LK_T, + LK_U, + LK_V, + LK_W, + LK_X, + LK_Y, + LK_Z, + LK_SPACE, + LK_SLASH, + LK_COMMA, + LK_PERIOD, + LK_SOLIDUS, + LK_SEMICOLON, + LK_SQUOTE, + LK_DQUOTE, + LK_S_BRACKET_L, + LK_S_BRACKET_R, + LK_R_BRACKET_L, + LK_R_BRACKET_R, + LK_DASH, + LK_EQUALS, + LK_ENTER, + LK_ESCAPE, + LK_UP, + LK_DOWN, + LK_LEFT, + LK_RIGHT, +}; + +#define KEYEV_FLAG_FREE 0 +#define KEYEV_FLAG_PRESS 1 +#define KEYEV_FLAG_RELEASE 2 +struct LumaKbdEvent { + uint8_t scancode; + uint8_t flag; +} __attribute__((packed)); + +#define KEYBUF_SIZE 4096 +#define KEYBUF_MAX (4096 / sizeof(struct LumaKbdEvent)) + +#endif \ No newline at end of file diff --git a/luma/ps2/main.c b/luma/ps2/main.c new file mode 100644 index 0000000..f07cea8 --- /dev/null +++ b/luma/ps2/main.c @@ -0,0 +1,254 @@ +#include"../sys.h" + +asm("modentry:\n" +"mov $stack + 768, %esp\n" +"call startc"); + +#include"api.h" +#include"../std.h" + +char stack[768]; + +struct LumaKbdEvent *KeyBuf = (void*) -1; +size_t KeyBufIndex = 0; + +void __attribute__((naked)) irq() { + asm( + "call irqc\n" + "movl $15, %eax\n" + "movl $1, %edi\n" + "int $0xEC" + ); +} + +static void pushev(struct LumaKbdEvent ev) { + if(KeyBuf[KeyBufIndex].flag != KEYEV_FLAG_FREE) { + return; + } else { + KeyBuf[KeyBufIndex++] = ev; + if(KeyBufIndex == KEYBUF_MAX) KeyBufIndex = 0; + sys_signal_send(KeyBuf, KeyBufIndex); + } +} + +void irqc() { + static const uint8_t ss21blchars1[] = {LK_Q, LK_1, 0, 0, 0, LK_Z, LK_S, LK_A, LK_W, LK_2, 0, 0, LK_C, LK_X, LK_D, LK_E, LK_4, LK_3, 0, 0, LK_SPACE, LK_V, LK_F, LK_T, LK_R, LK_5, 0, 0, LK_N, LK_B, LK_H, LK_G, LK_Y, LK_6, 0, 0, 0, LK_M, LK_J, LK_U, LK_7, LK_8, 0, 0, LK_COMMA, LK_K, LK_I, LK_O, LK_0, LK_9, 0, 0, LK_PERIOD, LK_SOLIDUS, LK_L, LK_SEMICOLON, LK_P, LK_DASH, 0, 0, 0, 0, LK_SQUOTE, 0, LK_S_BRACKET_L, LK_EQUALS}; + + static int stateLen = 0; + static uint8_t state[8]; // max 8 bytes per event + + state[stateLen++] = inb(0x60); + + if(stateLen == 8) { // Pause key, and state[0] should be 0xE1, but even if it isn't do this so as to reset state just in case + stateLen = 0; + pushev((struct LumaKbdEvent) {.scancode = LK_PAUSE, .flag = KEYEV_FLAG_PRESS}); + pushev((struct LumaKbdEvent) {.scancode = LK_PAUSE, .flag = KEYEV_FLAG_RELEASE}); + } else if(stateLen == 1 && state[0] != 0xE0 && state[0] != 0xE1 && state[0] != 0xF0) { + stateLen = 0; + struct LumaKbdEvent ev = {.flag = KEYEV_FLAG_PRESS}; + if(state[0] >= 0x15 && state[0] <= 0x55) { + if((ev.scancode = ss21blchars1[state[0] - 0x15])) { + pushev(ev); + } + } else { + if(state[0] == 0x12) { + ev.scancode = LK_LEFT_SHIFT; + } else if(state[0] == 0x59) { + ev.scancode = LK_RIGHT_SHIFT; + } else if(state[0] == 0x66) { + ev.scancode = LK_BACKSPACE; + } else if(state[0] == 0x5A) { + ev.scancode = LK_ENTER; + } else if(state[0] == 0x11) { + ev.scancode = LK_LEFT_ALT; + } else if(state[0] == 0x76) { + ev.scancode = LK_ESCAPE; + } + pushev(ev); + } + } else if(stateLen == 2 && state[0] == 0xE0 && state[1] == 0x1F) { + stateLen = 0; + struct LumaKbdEvent ev = {.flag = KEYEV_FLAG_PRESS, .scancode = LK_LEFT_SYS}; + pushev(ev); + } else if(stateLen == 2 && state[0] == 0xE0 && state[1] == 0x6B) { + stateLen = 0; + struct LumaKbdEvent ev = {.flag = KEYEV_FLAG_PRESS, .scancode = LK_LEFT}; + pushev(ev); + } else if(stateLen == 2 && state[0] == 0xE0 && state[1] == 0x74) { + stateLen = 0; + struct LumaKbdEvent ev = {.flag = KEYEV_FLAG_PRESS, .scancode = LK_RIGHT}; + pushev(ev); + } else if(stateLen == 2 && state[0] == 0xE0 && state[1] == 0x75) { + stateLen = 0; + struct LumaKbdEvent ev = {.flag = KEYEV_FLAG_PRESS, .scancode = LK_UP}; + pushev(ev); + } else if(stateLen == 2 && state[0] == 0xE0 && state[1] == 0x72) { + stateLen = 0; + struct LumaKbdEvent ev = {.flag = KEYEV_FLAG_PRESS, .scancode = LK_DOWN}; + pushev(ev); + } else if(stateLen == 2 && state[0] == 0xE0 && state[1] != 0xF0 && state[1] != 0x12) { + stateLen = 0; + struct LumaKbdEvent ev = {.flag = KEYEV_FLAG_PRESS}; + pushev(ev); + } else if(stateLen == 4 && state[0] == 0xE0 && state[1] == 0x12 && state[2] == 0xE0 && state[3] == 0x7C) { // Print screen pressed + stateLen = 0; + struct LumaKbdEvent ev = {.flag = KEYEV_FLAG_PRESS}; + pushev(ev); + } else if(stateLen == 6 && state[0] == 0xE0 && state[1] == 0xF0 && state[2] == 0x7C && state[3] == 0xE0 && state[4] == 0xF0 && state[5] == 0x12) { // Print screen released + stateLen = 0; + struct LumaKbdEvent ev = {.flag = KEYEV_FLAG_RELEASE}; + pushev(ev); + } else if(stateLen == 2 && state[0] == 0xF0) { + stateLen = 0; + struct LumaKbdEvent ev = {.flag = KEYEV_FLAG_RELEASE}; + if(state[1] >= 0x15 && state[1] <= 0x55) { + if((ev.scancode = ss21blchars1[state[1] - 0x15])) { + pushev(ev); + } + } else { + if(state[1] == 0x12) { + ev.scancode = LK_LEFT_SHIFT; + } else if(state[1] == 0x59) { + ev.scancode = LK_RIGHT_SHIFT; + } else if(state[1] == 0x66) { + ev.scancode = LK_BACKSPACE; + } else if(state[0] == 0x5A) { + ev.scancode = LK_ENTER; + } else if(state[1] == 0x11) { + ev.scancode = LK_LEFT_ALT; + } else if(state[1] == 0x76) { + ev.scancode = LK_ESCAPE; + } + pushev(ev); + } + } else if(stateLen == 3 && state[0] == 0xE0 && state[1] == 0xF0 && state[2] == 0x1F) { + stateLen = 0; + struct LumaKbdEvent ev = {.flag = KEYEV_FLAG_RELEASE, .scancode = LK_LEFT_SYS}; + pushev(ev); + } else if(stateLen == 3 && state[0] == 0xE0 && state[1] == 0xF0 && state[2] == 0x6B) { + stateLen = 0; + struct LumaKbdEvent ev = {.flag = KEYEV_FLAG_RELEASE, .scancode = LK_LEFT}; + pushev(ev); + } else if(stateLen == 3 && state[0] == 0xE0 && state[1] == 0xF0 && state[2] == 0x74) { + stateLen = 0; + struct LumaKbdEvent ev = {.flag = KEYEV_FLAG_RELEASE, .scancode = LK_RIGHT}; + pushev(ev); + } else if(stateLen == 3 && state[0] == 0xE0 && state[1] == 0xF0 && state[2] == 0x75) { + stateLen = 0; + struct LumaKbdEvent ev = {.flag = KEYEV_FLAG_RELEASE, .scancode = LK_UP}; + pushev(ev); + } else if(stateLen == 3 && state[0] == 0xE0 && state[1] == 0xF0 && state[2] == 0x72) { + stateLen = 0; + struct LumaKbdEvent ev = {.flag = KEYEV_FLAG_RELEASE, .scancode = LK_DOWN}; + pushev(ev); + } else if(stateLen == 3 && state[0] == 0xE0 && state[1] == 0xF0 && state[2] != 0x7C) { + stateLen = 0; + struct LumaKbdEvent ev = {.flag = KEYEV_FLAG_RELEASE}; + pushev(ev); + }; +} + +static volatile uint8_t *Framebuffer; +static void dbg(int j, uint8_t b) { + for(int i = 0; i < 8; i++) { + Framebuffer[j * 9 + 7 - i] = (b & (1 << i)) ? 80 : 0; + } +} + +void startc() { + Framebuffer = sys_vpm_map(SYS_MAP_VIRT_ANY, (void*) 0xA0000, 32000); + for(int try = 0; try < 50; try++) { + Framebuffer[try] = 50; + sys_sleep(500); + if(sys_link_create('USB\0', 'UHCI', 4096) != (void*) -1) { + goto done; + } + } + while(1); +done: + while(inb(0x64) & 2); + outb(0x64, 0xAD); + while(inb(0x64) & 2); + outb(0x64, 0xA7); + inb(0x60); + while(inb(0x64) & 2); + outb(0x64, 0x20); + while((inb(0x64) & 1) == 0); + uint8_t c = inb(0x60); + while(inb(0x64) & 2); + outb(0x64, 0x60); + while(inb(0x64) & 2); + outb(0x60, c & ~67); + + /* Enable */ + while(inb(0x64) & 2); + outb(0x64, 0xAE); + + while(inb(0x64) & 2); + outb(0x60, 0xFF); + while((inb(0x64) & 1) == 0); + if(inb(0x60) != 0xFA) while(1); + while((inb(0x64) & 1) == 0); + if(inb(0x60) != 0xAA) while(1); + + do { + while(inb(0x64) & 2); + outb(0x60, 0xF5); + while((inb(0x64) & 1) == 0); + } while(inb(0x60) != 0xFA); + + do { + while(inb(0x64) & 2); + outb(0x60, 0xF2); + while((inb(0x64) & 1) == 0); + } while(inb(0x60) != 0xFA); + + while((inb(0x64) & 1) == 0); + + uint8_t b1 = inb(0x60); + + sys_sleep(50); + + if(inb(0x64) & 1) { + uint8_t b2 = inb(0x60); + if(b1 != 0xAB) { + for(int i = 0; i < 15; i++) { + Framebuffer[i] = 90; + } + while(1); + } + } else while(1); + + do { + KeyBuf = sys_link_create('LUMA', 'WM\0\0', 4096); + } while(KeyBuf == (void*) -1); + memory_barrier(); + std_w8(KeyBuf, 0, 4096); + + // Send type "input device" + sys_signal_send(KeyBuf, 0); + sys_signal_wait(KeyBuf, NULL); + + sys_irq_claim(1, &irq); + + while(inb(0x64) & 2); + outb(0x64, 0x20); + while((inb(0x64) & 1) == 0); + c = inb(0x60); + while(inb(0x64) & 2); + outb(0x64, 0x60); + while(inb(0x64) & 2); + outb(0x60, c | 1); // enable interrupt + + inb(0x60); + + do { + while(inb(0x64) & 2); + outb(0x60, 0xF4); + while((inb(0x64) & 1) == 0); + } while(inb(0x60) != 0xFA); + + sys_wait_for_irq(1); + + while(1) sys_signal_wait(SYS_SIGNAL_WAIT_ANY, NULL); +} diff --git a/luma/std.h b/luma/std.h new file mode 100644 index 0000000..a28b6ce --- /dev/null +++ b/luma/std.h @@ -0,0 +1,79 @@ +#ifndef LUMA_STD_H +#define LUMA_STD_H + +#include +#include + +#if defined(__has_builtin) && __has_builtin(__builtin_memcpy) +#define std_copy __builtin_memcpy +#else +static inline void std_copy(void *dst, const void *src, size_t len) { + char *d = dst; + const char *s = src; + while(len--) { + *(d++) = *(s++); + } +} +#endif + +static inline void std_move(void *dst, const void *src, size_t len) { + if(src > dst) { + char *d = dst; + const char *s = src; + while(len--) { + *(d++) = *(s++); + } + } else { + char *d = dst + len; + const char *s = src + len; + while(len--) { + *(--d) = *(--s); + } + } +} + +static inline void std_w8(uint8_t *dst, uint8_t b, size_t len) { + while(len--) { + *dst = b; + dst++; + } +} + +typedef struct { + uint16_t len; + uint8_t data[]; +} Str16; +#define WALK_STR16(x) ((Str16*)((uintptr_t)(x)+sizeof(Str16)+((Str16*)(x))->len)) + +typedef struct { + uint16_t cap; + uint16_t len; + uint8_t data[]; +} DynStr16; +#define DYN16_TO_ST(x) ((Str16*)((uintptr_t) x + offsetof(DynStr16, len))) + +static inline char* std_bytefind(size_t len, const char *data, const char what) { + while(len--) { + if(*data == what) { + return (char*) data; + } + data++; + } + return NULL; +} + +static inline unsigned char std_bytecomp(size_t len, const void *one_, const void *two_) { + const char *one = one_, *two = two_; + while(len--) { + unsigned char asdf = *(one++) - *(two++); + if(asdf) return asdf; + } + return 0; +} + +#define std_min(a, b) ({__typeof__(a) _a = (a); __typeof__(b) _b = (b); _a<_b?_a:_b;}) +#define std_max(a, b) ({__typeof__(a) _a = (a); __typeof__(b) _b = (b); _a>_b?_a:_b;}) + +//#define S16_ARG(str) ((Str16*) &(struct {uint16_t len; char content[sizeof(str) - 1]}) {sizeof(str) - 1, (str)}) + +#endif diff --git a/luma/sys.h b/luma/sys.h new file mode 100644 index 0000000..cbb14e5 --- /dev/null +++ b/luma/sys.h @@ -0,0 +1,185 @@ +#ifndef _LUMA_SYS_H +#define _LUMA_SYS_H + +#include +#include + +#define memory_barrier() asm volatile("" : : : "memory") +#define STRINGIFY2(v) #v +#define STRINGIFY(v) STRINGIFY2(v) + +static __attribute__((always_inline)) inline uint32_t syscall1(uint32_t eax, uint32_t edi, uint32_t esi, uint32_t edx) { + uint32_t ret; + asm volatile("int $0xEC" : "=a"(ret) : "a"(eax), "S"(esi), "D"(edi), "d"(edx)); + return ret; +} + +static __attribute__((always_inline)) inline uint32_t sys5call1(uint32_t eax, uint32_t edi, uint32_t esi, uint32_t edx, uint32_t ecx, uint32_t ebx) { + uint32_t ret; + asm volatile("int $0xEC" : "=a"(ret) : "a"(eax), "S"(esi), "D"(edi), "d"(edx), "c"(ecx), "b"(ebx)); + return ret; +} + +#define SYS_MAP_PHYS_ANY ((void*)-1) +#define SYS_MAP_PHYS_CONTIGUOUS ((void*)-2) +#define SYS_MAP_VIRT_ANY ((void*)-1) +static __attribute__((always_inline)) inline void *sys_vpm_map(void *virt, void *phys, size_t length) { + return (void*) syscall1(0, (uint32_t) virt, (uint32_t) phys, length); +} + +static __attribute__((always_inline)) inline uint32_t sys_canal_create(uint32_t nameLow, uint32_t nameHigh) { + return syscall1(1, nameLow, nameHigh, 0); +} + +static __attribute__((always_inline)) inline void *sys_link_create(uint32_t nameLow, uint32_t nameHigh, size_t areaSize) { + return (void*) syscall1(2, nameLow, nameHigh, areaSize); +} + +#define SYS_CANAL_ACCEPT_ANY ((uint32_t)-1) +static __attribute__((always_inline)) inline void *sys_canal_accept(uint32_t canalId) { + return (void*) syscall1(3, canalId, 0, 0); +} + +static __attribute__((always_inline)) inline void sys_signal_send(void *area, uint32_t meta) { + syscall1(4, (uint32_t) area, meta, 0); +} + +#define SYS_SIGNAL_WAIT_ANY ((void*)-1) +static __attribute__((always_inline)) inline void *sys_signal_wait(void *area, uint32_t *meta) { + uint32_t eax, edx; + asm volatile("int $0xEC" : "=a"(eax), "=d"(edx) : "a"(5), "D"(area) : "ebx"); + if(meta) *meta = edx; + return (void*) eax; +} +static __attribute__((always_inline)) inline void *sys_signal_wait3(void *area, uint32_t *meta, uint32_t *canalId) { + uint32_t eax, edx, ebx; + asm volatile("int $0xEC" : "=a"(eax), "=d"(edx), "=b"(ebx) : "a"(5), "D"(area)); + if(meta) *meta = edx; + if(canalId) *canalId = ebx; + return (void*) eax; +} + +static __attribute__((always_inline)) inline uint32_t sys_pci_claim(uint32_t cscp) { + return syscall1(6, cscp, 0, 0); +} + +static __attribute__((always_inline)) inline uint32_t sys_pci_read(uint32_t id, uint8_t offset) { + return syscall1(7, id, offset, 0); +} + +static __attribute__((always_inline)) inline void sys_vpm_unmap(void *virt, size_t length) { + syscall1(8, (uint32_t) virt, length, 0); +} + +static __attribute__((always_inline)) inline void *sys_vpm_get_phys(void *virt) { + return (void*) syscall1(9, (uint32_t) virt, 0, 0); +} + +static __attribute__((always_inline)) inline void sys_sleep(uint32_t millis) { + syscall1(10, millis, 0, 0); +} + +static __attribute__((always_inline)) inline void sys_pci_write_1(uint32_t id, uint8_t offset, uint8_t val) { + syscall1(11, id, offset, val); +} + +static __attribute__((always_inline)) inline void sys_pci_write_2(uint32_t id, uint8_t offset, uint16_t val) { + syscall1(12, id, offset, val); +} + +static __attribute__((always_inline)) inline void sys_pci_write_4(uint32_t id, uint8_t offset, uint32_t val) { + syscall1(13, id, offset, val); +} + +static __attribute__((always_inline)) inline void sys_irq_claim(uint32_t irq, void(*handler)()) { + syscall1(14, irq, (uintptr_t) handler, 0); +} + +static __attribute__((always_inline)) inline void sys_wait_for_irq(uint32_t i) { + syscall1(15, i, 0, 0); +} + +static __attribute__((always_inline)) inline void sys_create_thread(void *cod) { + syscall1(16, (uintptr_t) cod, 0, 0); +} + +static __attribute__((always_inline)) inline size_t sys_spawn() { + return syscall1(17, 0, 0, 0); +} + +static __attribute__((always_inline)) inline uintptr_t sys_abuse_map(size_t handle, void **virtMy, void **virtTheir, void *phys, size_t length) { + memory_barrier(); + return sys5call1(18, handle, (uintptr_t) virtMy, (uintptr_t) virtTheir, (uintptr_t) phys, length); +} + +static __attribute__((always_inline)) inline int sys_release(size_t handle) { + return syscall1(19, handle, 0, 0); +} + +#define SYS_STATE_X86_EIP 0 +static __attribute__((always_inline)) inline int sys_abuse_state(size_t handle, uintmax_t type, uintmax_t val) { + return syscall1(20, handle, type, (uintptr_t) val); +} + +static __attribute__((always_inline)) inline int sys_exit() { + return syscall1(21, 0, 0, 0); +} + +#define KEV_TYPE_NONE 0 +#define KEV_TYPE_LINK_REQUEST 1 +#define KEV_TYPE_LINK_SIGNAL 2 +#define KEV_TYPE_LINK_CLOSE 3 +typedef struct __attribute__((packed)) { + uint8_t type; + uint32_t canalId; + void *area; + uint32_t meta; +} KEvent; + +static __attribute__((always_inline)) inline int sys_event_wait(KEvent *kev) { + int ret = syscall1(22, (uintptr_t) (void*) kev, 0, 0); + memory_barrier(); + return ret; +} + +static __attribute__((always_inline)) inline uint32_t ind(uint32_t p) { + uint32_t ret; + asm volatile("inl %%dx, %%eax" : "=a"(ret) : "d"(p)); + return ret; +} + +static __attribute__((always_inline)) inline uint16_t inw(uint32_t p) { + uint16_t ret; + asm volatile("inw %%dx, %%ax" : "=a"(ret) : "d"(p)); + return ret; +} + +static __attribute__((always_inline)) inline uint8_t inb(uint32_t p) { + uint8_t ret; + asm volatile("inb %%dx, %%al" : "=a"(ret) : "d"(p)); + return ret; +} + +static __attribute__((always_inline)) inline void outb(uint32_t p, uint8_t v) { + asm volatile("outb %%al, %%dx" : : "d"(p), "a"(v)); +} + +static __attribute__((always_inline)) inline void outw(uint32_t p, uint16_t v) { + asm volatile("outw %%ax, %%dx" : : "d"(p), "a"(v)); +} + +static __attribute__((always_inline)) inline void outd(uint32_t p, uint32_t v) { + asm volatile("outl %%eax, %%dx" : : "d"(p), "a"(v)); +} + +#if __BYTE_ORDER == __LITTLE_ENDIAN +#define BIG_TO_HOST_ENDIAN32(x) __builtin_bswap32(x) +#define BIG_TO_HOST_ENDIAN16(x) __builtin_bswap16(x) +#elif __BYTE_ORDER == __BIG_ENDIAN +#define BIG_TO_HOST_ENDIAN32(x) (x) +#define BIG_TO_HOST_ENDIAN16(x) (x) +#else +#error "PDP??" +#endif + +#endif diff --git a/luma/uhci/Makefile b/luma/uhci/Makefile new file mode 100644 index 0000000..ce1116d --- /dev/null +++ b/luma/uhci/Makefile @@ -0,0 +1,13 @@ +rwildcard=$(foreach d,$(wildcard $(1:=/*)),$(call rwildcard,$d,$2) $(filter $(subst *,%,$2),$d)) + +HEADERS := $(call rwildcard,.,*.h) +SOURCEC := $(call rwildcard,.,*.c) +OBJECTS := $(patsubst %.c, ../../build/uhci/%.o, $(SOURCEC)) + +mod: $(OBJECTS) + i386-elf-gcc -pie -T ../../mod.ld -Wl,-no-dynamic-linker -nostdlib -o main.elf $(OBJECTS) -lgcc + ../../elftomod.py main.elf ../../bootfs/luma_uhci.mod modentry:0 + +../../build/uhci/%.o: %.c + mkdir -p $(@D) + i386-elf-gcc -march=i386 -Isrc -Os -pie -nodefaultlibs -nostdlib -nostartfiles -fomit-frame-pointer -c -o $@ -ffreestanding -mgeneral-regs-only -std=gnu99 -Wall $< diff --git a/luma/uhci/bbb.c b/luma/uhci/bbb.c new file mode 100644 index 0000000..54ded7e --- /dev/null +++ b/luma/uhci/bbb.c @@ -0,0 +1,293 @@ +#include"bbb.h" + +#include +#include"host.h" +#include"../sys.h" +#include"../std.h" + +#define SCSI_OP_INQUIRY 0x12 +#define SCSI_OP_TEST_UNIT_READY 0x00 +#define SCSI_OP_REQUEST_SENSE 0x03 +#define SCSI_OP_READ_CAPACITY_10 0x25 +#define SCSI_OP_READ_10 0x28 +#define SCSI_OP_MODE_SENSE_6 0x1A + +typedef struct __attribute__((packed)) { + uint8_t op; + union __attribute__((packed)) { + struct __attribute__((packed)) { + uint8_t lun5; + uint8_t page; + uint8_t reserved; + uint8_t dataSz; + uint8_t control; + } inquiry; + struct __attribute__((packed)) { + uint8_t res0; + uint8_t res1; + uint8_t res2; + uint8_t res3; + uint8_t control; + } testUnitReady; + struct __attribute__((packed)) { + uint8_t desc; + uint8_t res0; + uint8_t res1; + uint8_t dataSz; + uint8_t control; + } requestSense; + struct __attribute__((packed)) { + uint8_t res0; + uint8_t res1; + uint8_t res2; + uint8_t res3; + uint8_t res4; + uint8_t res5; + uint8_t res6; + uint8_t res7; + uint8_t control; + } readCapacity10; + struct __attribute__((packed)) { + uint8_t flags; + uint32_t lba; + uint8_t group; + uint16_t lbaCount; + uint8_t control; + } read10; + struct __attribute__((packed)) { + uint8_t flags; + uint8_t pageCode; + uint8_t subpageCode; + uint8_t allocationSz; + uint8_t control; + } modeSense6; + }; +} SCSICommand; + +#define CBW_SIGN 0x43425355 +#define CBW_FLAG_IN 0x80 +#define CBW_FLAG_OUT 0x00 +typedef struct __attribute__((packed)) { + uint32_t signature; + uint32_t tag; + uint32_t dataSz; + uint8_t flags; + uint8_t lun; + uint8_t cmdSz; + union { + SCSICommand cmd; + uint8_t padding[16]; + }; +} CBW; + +#define CSW_SIGN 0x53425355 +typedef struct __attribute__((packed)) { + uint32_t signature; + uint32_t tag; + uint32_t residue; + uint8_t status; +} CSW; + +void dbg(int j, uint8_t b); +extern uint32_t asdfasdf; + +static int BBBRequest(USBDevice *dev, CBW cbw, void *buf, size_t len, CSW *ret) { + if(HostSendBulk(dev, dev->bbb.maxPacketSize, &dev->bbb.toggleOut, dev->bbb.endpOut, &cbw, sizeof(cbw)) == 0) { + if(BBBReset(dev) == 0) { + return 0; + } + if(HostSendBulk(dev, dev->bbb.maxPacketSize, &dev->bbb.toggleOut, dev->bbb.endpOut, &cbw, sizeof(cbw)) == 0) { + return 0; + } + } + + sys_sleep(10); + + if(len) { + HostSendBulk(dev, dev->bbb.maxPacketSize, + (cbw.flags & CBW_FLAG_IN) ? &dev->bbb.toggleIn : &dev->bbb.toggleOut, + (cbw.flags & CBW_FLAG_IN) ? dev->bbb.endpIn : dev->bbb.endpOut, + buf, len); + } + + return HostSendBulk(dev, dev->bbb.maxPacketSize, &dev->bbb.toggleIn, dev->bbb.endpIn, ret, sizeof(*ret)); +} + +int BBBReset(USBDevice *dev) { + if(!HostSendRequest(dev, NULL, (USBStandardRequest) { + .requestType = 0x21, + .request = 0xFF, // mass storage reset + .value = 0, + .index = 0, + .length = 0 + })) return 0; + sys_sleep(150); + if(!HostSendRequest(dev, NULL, (USBStandardRequest) { + .requestType = 2, // endpoint + .request = 1, // clear feature + .value = 0, // halt + .index = dev->bbb.endpIn, + .length = 0 + })) return 0; + sys_sleep(150); + if(!HostSendRequest(dev, NULL, (USBStandardRequest) { + .requestType = 2, // endpoint + .request = 1, // clear feature + .value = 0, // halt + .index = dev->bbb.endpOut, + .length = 0 + })) return 0; + sys_sleep(150); + dev->bbb.toggleIn = dev->bbb.toggleOut = 0; + return 1; +} + +int BBBInquiry(USBDevice *dev) { + uint8_t inquiry[36]; + + CSW csw; + + return BBBRequest(dev, (CBW) { + .signature = CBW_SIGN, + .tag = 0, + .dataSz = 36, + .flags = CBW_FLAG_IN, + .lun = 0, + .cmdSz = 6, + .cmd = { + .op = SCSI_OP_INQUIRY, + .inquiry = { + .lun5 = 0, + .page = 0, + .reserved = 0, + .dataSz = 36, + .control = 0 + } + } + }, inquiry, 36, &csw) && csw.status == 0; +} + +int BBBTestUnitReady(USBDevice *dev) { + CSW csw; + + return BBBRequest(dev, (CBW) { + .signature = CBW_SIGN, + .tag = 0, + .dataSz = 0, + .flags = CBW_FLAG_OUT, + .lun = 0, + .cmdSz = 6, + .cmd = { + .op = SCSI_OP_TEST_UNIT_READY, + .testUnitReady = {} + } + }, NULL, 0, &csw) && csw.status == 0; +} + +int BBBRequestSense(USBDevice *dev) { + uint8_t data[18]; + + CSW csw; + + return BBBRequest(dev, (CBW) { + .signature = CBW_SIGN, + .tag = 0, + .dataSz = 18, + .flags = CBW_FLAG_IN, + .lun = 0, + .cmdSz = 6, + .cmd = { + .op = SCSI_OP_REQUEST_SENSE, + .requestSense = {.dataSz = 18} + } + }, data, 18, &csw) && csw.status == 0; +} + +int BBBReadCapacity10(USBDevice *dev) { + uint32_t data[2]; + CSW csw; + if(!BBBRequest(dev, (CBW) { + .signature = CBW_SIGN, + .tag = 0, + .dataSz = sizeof(data), + .flags = CBW_FLAG_IN, + .lun = 0, + .cmdSz = 10, + .cmd = { + .op = SCSI_OP_READ_CAPACITY_10, + .readCapacity10 = {} + } + }, data, sizeof(data), &csw)) return 0; + + if(csw.status) return 0; + + dev->bbb.sectorSize = BIG_TO_HOST_ENDIAN32(data[1]); + + //dbg(asdfasdf + 2, csw.status); + //dbg(asdfasdf + 3, dev->bbb.maxPacketSize); + //dbg(asdfasdf + 4, dev->bbb.sectorSize >> 9); + + return 1; +} + +int BBBRead10(USBDevice *dev, uint32_t lbaStart, void *buf, uint16_t lbaCount) { + CSW csw; + if(!BBBRequest(dev, (CBW) { + .signature = CBW_SIGN, + .tag = 0, + .dataSz = lbaCount * dev->bbb.sectorSize, + .flags = CBW_FLAG_IN, + .lun = 0, + .cmdSz = 10, + .cmd = { + .op = SCSI_OP_READ_10, + .read10 = {.lba = BIG_TO_HOST_ENDIAN32(lbaStart), .lbaCount = BIG_TO_HOST_ENDIAN16(lbaCount)} + } + }, buf, lbaCount * dev->bbb.sectorSize, &csw)) return 0; + + return csw.status == 0; +} + +int BBBDeviceResponse(USBDevice *dev, void *area, uint32_t meta) { + uint64_t start = ((uint64_t*) area)[0]; + uint32_t length = ((uint32_t*) area)[2]; + + uint32_t startLBA = start / dev->bbb.sectorSize; + uint32_t endLBA = (start + length - 1) / dev->bbb.sectorSize; + + dbg(asdfasdf + 10, startLBA & 0xFF); + dbg(asdfasdf + 11, endLBA & 0xFF); + + if(!BBBRead10(dev, startLBA, area, endLBA - startLBA + 1)) { + dbg(asdfasdf + 12, 0xFF); + sys_signal_send(area, 0); + } else { + dbg(asdfasdf + 12, 0x00); + std_move(&area[0], &area[start % dev->bbb.sectorSize], length); + sys_signal_send(area, 1); + } + + return 1; +} + +int BBBModeSense(USBDevice *dev) { + uint8_t data[192]; + + CSW csw; + + return BBBRequest(dev, (CBW) { + .signature = CBW_SIGN, + .tag = 0, + .dataSz = 192, + .flags = CBW_FLAG_IN, + .lun = 0, + .cmdSz = 6, + .cmd = { + .op = SCSI_OP_MODE_SENSE_6, + .modeSense6 = { + .pageCode = 0x3F, + .allocationSz = 192 + } + } + }, data, 192, &csw) && csw.status == 0; +} diff --git a/luma/uhci/bbb.h b/luma/uhci/bbb.h new file mode 100644 index 0000000..62d36cc --- /dev/null +++ b/luma/uhci/bbb.h @@ -0,0 +1,12 @@ +#pragma once + +#include"usb.h" + +int BBBReset(USBDevice *dev); +int BBBInquiry(USBDevice *dev); +int BBBTestUnitReady(USBDevice *dev); +int BBBRequestSense(USBDevice *dev); +int BBBReadCapacity10(USBDevice *dev); +int BBBRead10(USBDevice *dev, uint32_t lbaStart, void *buf, uint16_t lbaCount); +int BBBDeviceResponse(USBDevice *dev, void *area, uint32_t meta); +int BBBModeSense(USBDevice *dev); diff --git a/luma/uhci/host.h b/luma/uhci/host.h new file mode 100644 index 0000000..d8cefe6 --- /dev/null +++ b/luma/uhci/host.h @@ -0,0 +1,26 @@ +#pragma once + +#include"usb.h" +#include +#include + +typedef struct { + uint32_t link; + uint32_t control; + uint32_t token; + uint32_t buffer; +} TD; + +typedef struct { + uint32_t link; + uint32_t element; +} QH; + +typedef struct { + QH masterQueue; + uint32_t io; + uint32_t *frameList; +} __attribute__((aligned(16))) HC; + +int HostSendBulk(USBDevice *dev, size_t maxPacketSize, int *toggle, int endpoint, void *buf, size_t len); +int HostSendRequest(USBDevice *dev, void *buf, USBStandardRequest req); \ No newline at end of file diff --git a/luma/uhci/main.c b/luma/uhci/main.c new file mode 100644 index 0000000..3349869 --- /dev/null +++ b/luma/uhci/main.c @@ -0,0 +1,306 @@ +#include"../sys.h" + +// Currently, the driver waits for any requests and performs them +// This method fails for active USB devices (rather than passive) +// +// Should either poll for signals or switch to multithreading, once +// it becomes a need. + +asm("modentry:\n" +"mov $stack + 4096, %esp\n" +"call startc"); + +#include"host.h" + +#define TD_ACTIVE (1 << 23) +#define TD_MAXERRS(x) ((x) << 27) +#define TD_TOGGLE(x) ((!!(x)) << 19) +#define TD_MAXLEN(sz) (((sz) - 1) << 21) +#define TD_MAXLEN_0 (0x7FF << 21) +#define TD_DEVADDR(i) ((i) << 8) +#define TD_DEVENDP(i) ((i) << 15) +#define TD_LSD (1 << 26) +#define TD_SPD (1 << 29) +#define TD_IOC (1 << 24) +#define TD_DEPTH_FIRST (4) + +char __attribute__((aligned(16))) stack[4096]; + +size_t hcCount = 0; +HC __attribute__((aligned(16))) hcs[4]; + +size_t deviceCount = 0; +USBDevice *devices; + +// FOR DEBUG PURPOSES { +static volatile uint8_t *Framebuffer; +uint32_t asdfasdf = 28; +void dbg(int j, uint8_t b) { + for(int i = 0; i < 8; i++) { + Framebuffer[j * 9 + 10 - i] = (b & (1 << i)) ? 85 : 40; + } + Framebuffer[j * 9 + 11] = 0; +} +// } + +int HostSendBulk(USBDevice *dev, size_t maxPacketSize, int *toggle, int endpoint, void *buf, size_t len) { + size_t sz = len; + int num = (sz + maxPacketSize - 1) / maxPacketSize; + + TD tds[num] __attribute__((aligned(16))); + + for(int i = 0;; i++, sz -= maxPacketSize) { + tds[i] = (TD) { + .link = (i == num - 1 ? 1 : ((uintptr_t) sys_vpm_get_phys(&tds[i + 1]))) | TD_DEPTH_FIRST, + .control = TD_ACTIVE | TD_MAXERRS(3) | ((endpoint & 128) ? TD_SPD : 0) | (i == num - 1 ? TD_IOC : 0), + .token = TD_MAXLEN(sz > maxPacketSize ? maxPacketSize : sz) | TD_TOGGLE(*toggle) | TD_DEVADDR(dev->id) | TD_DEVENDP(endpoint & 0x0F) | ((endpoint & 128) ? IN : OUT), + .buffer = (uintptr_t) sys_vpm_get_phys(&buf[i * maxPacketSize]) + }; + *toggle ^= 1; + if(sz <= maxPacketSize) break; + } + + while(inw(hcs[dev->hc].io + 2) & 3) { + outw(hcs[dev->hc].io + 2, 3); // clear usbint + } + + QH *masterQ = &hcs[dev->hc].masterQueue; + + QH qh __attribute__((aligned(16))); + qh.link = 1; + + memory_barrier(); + + qh.element = (uint32_t) sys_vpm_get_phys(&tds[0]); + masterQ->element = ((uint32_t) sys_vpm_get_phys(&qh)) | 2; + + // Wait until complete. + // Polling doesn't seem to work reliably. Sometimes USBINT just isn't set. + // From iPXE source, though can't find a relation: + /* UHCI defers interrupts (including short packet detection) + * until the end of the frame. This can result in bulk IN + * endpoints remaining halted for much of the time, waiting + * for software action to reset the data toggles. We + * therefore ignore USBSTS and unconditionally poll all + * endpoints for completed transfer descriptors. + * + * As with EHCI, we trust that completion handlers are minimal + * and will not do anything that could plausibly affect the + * endpoint list itself. + */ + for(int i = 0; i < num; i++) { + while(tds[i].control & TD_ACTIVE) memory_barrier(); + + if(tds[i].control & 0x00FF0000) { + return 0; //fail + } + } + + return 1; +} + +/* buf must be physically contiguous */ +int HostSendRequest(USBDevice *dev, void *buf, USBStandardRequest req) { + size_t sz = req.length; + int num = 2 + (sz + dev->maxPacketSize - 1) / dev->maxPacketSize; + + TD tds[num] __attribute__((aligned(16))); + + tds[0] = (TD) { + .link = (sz == 0 ? 1 : (uintptr_t) sys_vpm_get_phys(&tds[1])) | TD_DEPTH_FIRST, + .control = TD_ACTIVE | TD_MAXERRS(3) | (sz == 0 ? TD_IOC : 0), + .token = TD_MAXLEN(8) | TD_TOGGLE(0) | TD_DEVADDR(dev->id) | SETUP, + .buffer = (uintptr_t) sys_vpm_get_phys(&req) + }; + + for(int i = 1;; i++, sz -= dev->maxPacketSize) { + tds[i] = (TD) { + .link = (i == num - 2 ? 1 : ((uintptr_t) sys_vpm_get_phys(&tds[i + 1]))) | TD_DEPTH_FIRST, + .control = TD_ACTIVE | TD_MAXERRS(3) | ((req.requestType & 128) ? TD_SPD : 0) | (i == num - 2 ? TD_IOC : 0), + .token = TD_MAXLEN(sz > dev->maxPacketSize ? dev->maxPacketSize : sz) | TD_TOGGLE(i & 1) | TD_DEVADDR(dev->id) | ((req.requestType & 128) ? IN : OUT), + .buffer = (uintptr_t) sys_vpm_get_phys(&buf[(i - 1) * dev->maxPacketSize]) + }; + if(sz <= dev->maxPacketSize) break; + } + + tds[num - 1] = (TD) { + .link = 1, + .control = TD_ACTIVE | TD_MAXERRS(3), + .token = TD_MAXLEN_0 | TD_TOGGLE(1) | TD_DEVADDR(dev->id) | ((req.requestType & 128) ? OUT : IN), + .buffer = 0 + }; + + while(inw(hcs[dev->hc].io + 2) & 1) { + outw(hcs[dev->hc].io + 2, 3); // clear usbint + } + + QH *masterQ = &hcs[dev->hc].masterQueue; + + QH qh __attribute__((aligned(16))); + qh.link = 1; + + memory_barrier(); + + qh.element = (uint32_t) sys_vpm_get_phys(&tds[0]); + masterQ->element = ((uint32_t) sys_vpm_get_phys(&qh)) | 2; + + sys_sleep(15); + + // Wait for usbint + memory_barrier(); + while((inw(hcs[dev->hc].io + 2) & 1) == 0); + + outw(hcs[dev->hc].io + 2, 3); // clear usbint + + qh.element = (uint32_t) sys_vpm_get_phys(&tds[num - 1]); + masterQ->element = ((uint32_t) sys_vpm_get_phys(&qh)) | 2; + + // Wait until status packet becomes inactive + do { + memory_barrier(); + } while(tds[num - 1].control & TD_ACTIVE); + + // Return whether success + return (tds[num - 1].control & (0xFF0000)) == 0; +} + +static int HCsInit() { + // Go through all EHCIs and disable them + while(1) { + uint32_t hcId = sys_pci_claim(0x0C032000); + + if(hcId == -1) { + break; + } + + volatile uint32_t *usbbase = sys_vpm_map(SYS_MAP_VIRT_ANY, (void*) (sys_pci_read(hcId, 16) & ~15), 4096); + volatile uint32_t *opregs = (uint32_t*) ((uintptr_t) usbbase + (usbbase[0] & 0xFF)); + + uint8_t caps = (usbbase[2] & 0xFF00) >> 8; + if(caps < 0x40) { + return 0; + } else { + sys_pci_write_1(hcId, caps + 3, 1); + while((sys_pci_read(hcId, caps) & (1 << 16)) != 0); + while((sys_pci_read(hcId, caps) & (1 << 24)) == 0); + sys_pci_write_4(hcId, caps + 4, 0); + } + + opregs[0] &= ~1; + + do { + memory_barrier(); + } while((opregs[1] & 4096) == 0); + + opregs[0] |= 2; + + do { + memory_barrier(); + } while(opregs[0] & 2); + + opregs[1] = opregs[1]; + opregs[2] = 0; + opregs[4] = 0; + opregs[0] = 0x80000; + opregs[16] = 0; + + sys_vpm_unmap(usbbase, 4096); + } + + int success = 1; + + // Go through all UHCIs + while(1) { + uint32_t hcId = sys_pci_claim(0x0C030000); + + if(hcId == -1) { + break; + } + + HC *hc = &hcs[hcCount]; + hc->io = sys_pci_read(hcId, 0x20) & ~3; + hc->frameList = sys_vpm_map(SYS_MAP_VIRT_ANY, SYS_MAP_PHYS_ANY, 4096); + hc->masterQueue = (QH) {1, 1}; + for(int i = 0; i < 1024; i++) { + hc->frameList[i] = ((uint32_t) sys_vpm_get_phys(&hc->masterQueue)) | 2; + } + + sys_pci_write_2(hcId, 0xC0, 0x8F00); + + outw(hc->io + 0, 2); + while(inw(hc->io + 2) & 2); + + outw(hc->io + 4, 0); + outw(hc->io + 0, 0); + outw(hc->io + 2, 0xFFFF); + outb(hc->io + 12, 64); + outd(hc->io + 8, (uint32_t) sys_vpm_get_phys(hc->frameList)); + outw(hc->io + 6, 0); + outw(hc->io + 0, 1 | 128); + + for(int p = 0; p < 2; p++) { + outw(hc->io + 16 + p+p, 512); + sys_sleep(80); + outw(hc->io + 16 + p+p, 0); + + for(int try = 0; try < 10; try++) { + sys_sleep(10); + uint16_t sc = inw(hc->io + 16 + p+p); + //if((sc & 1) == 0) break; + if(sc & (2 | 8)) outw(hc->io + 16 + p+p, sc); + if(sc & 4) break; + outw(hc->io + 16 + p+p, sc | 4); + } + + sys_sleep(100); + + if(inw(hc->io + 16 + p+p) & 1) { + dbg(asdfasdf++, 2 * hcCount + p + 128); + + USBDevice *dev = &devices[deviceCount]; + dev->hc = hcCount; + dev->id = deviceCount + 1; + dev->maxPacketSize = 8; + if(USBDeviceDiscover(dev) == 0) { /* The rest of the fields are filled here */ + success = 0; + } + deviceCount++; + } + } + + hcCount++; + } + + return success; +} + +void startc() { + devices = sys_vpm_map(SYS_MAP_VIRT_ANY, SYS_MAP_PHYS_ANY, 4096); + + Framebuffer = sys_vpm_map(SYS_MAP_VIRT_ANY, (void*) 0xA0000, 32000); + + if(HCsInit()) { + // Let other drivers know we exist + sys_canal_create('USB\0', 'UHCI'); + + // Main loop + while(1) { + sys_canal_accept(SYS_CANAL_ACCEPT_ANY); + + uint32_t meta, canal; + void* area = sys_signal_wait3(SYS_SIGNAL_WAIT_ANY, &meta, &canal); + for(int i = 0; i < deviceCount; i++) { + if(devices[i].canal == canal) { + if(devices[i].respond) { + devices[i].respond(&devices[i], area, meta); + } + break; + } + } + } + } else { + while(1) { + sys_signal_wait(SYS_SIGNAL_WAIT_ANY, NULL); + } + } +} diff --git a/luma/uhci/usb.c b/luma/uhci/usb.c new file mode 100644 index 0000000..8546a65 --- /dev/null +++ b/luma/uhci/usb.c @@ -0,0 +1,153 @@ +#include"usb.h" + +#include"host.h" +#include"bbb.h" +#include"../sys.h" + +void dbg(int j, uint8_t b); +extern uint32_t asdfasdf; + +int USBDeviceDiscover(USBDevice *dev) { + uint8_t tmp = dev->id; + dev->id = 0; // 0 is the correct device ID as far as USB is concerned + if(!HostSendRequest(dev, NULL, (USBStandardRequest) { + .requestType = 0x00, + .request = 5, // SET_ADDRESS + .value = tmp, + .index = 0, + .length = 0 + })) { + dev->id = tmp; + return 0; + } + dev->id = tmp; + + USBDeviceDescriptor ddesc; + if(!HostSendRequest(dev, &ddesc, (USBStandardRequest) { + .requestType = 0x80, + .request = 6, // GET_DESCRIPTOR + .value = 1 << 8, // device + .index = 0, + .length = 8 + })) return 0; + + dev->maxPacketSize = ddesc.maxPacketSize; + + if(ddesc.clazz == 0 && ddesc.subclazz == 0 && ddesc.protocol == 0) { + uint8_t buf[64]; + if(HostSendRequest(dev, buf, (USBStandardRequest) { + .requestType = 0x80, + .request = 6, // GET_DESCRIPTOR + .value = 2 << 8, // configuration + .index = 0, + .length = sizeof(buf) + })) { + USBConfigurationDescriptor *conf = (void*) buf; + + if(HostSendRequest(dev, NULL, (USBStandardRequest) { + .requestType = 0x00, + .request = 9, + .value = conf->id, + .index = 0, + .length = 0 + })) { + if(conf->interfaceCount == 1) { + USBInterfaceDescriptor *interf = (USBInterfaceDescriptor*) ((uintptr_t) conf + conf->sz); + + if(HostSendRequest(dev, NULL, (USBStandardRequest) { + .requestType = 0x01, + .request = 11, + .value = interf->alternate, + .index = interf->interface, + .length = 0 + })) { + if(interf->clazz == 0x08 && interf->subclazz == 0x06 && interf->protocol == 0x50) { + USBEndpointDescriptor *endp0 = (USBEndpointDescriptor*) ((uintptr_t) interf + interf->sz); + USBEndpointDescriptor *endp1 = (USBEndpointDescriptor*) ((uintptr_t) endp0 + endp0->sz); + + dev->bbb.maxPacketSize = endp0->maxPacketSize; + dev->bbb.toggleIn = dev->bbb.toggleOut = 0; + + if(endp0->endpoint & 0x80) { + dev->bbb.endpIn = endp0->endpoint; + dev->bbb.endpOut = endp1->endpoint; + } else { + dev->bbb.endpIn = endp1->endpoint; + dev->bbb.endpOut = endp0->endpoint; + } + + uint8_t lun; + if(!HostSendRequest(dev, &lun, (USBStandardRequest) { + .requestType = 0xA1, + .request = 0xFE, // get max lun + .value = 0, + .index = 0, + .length = sizeof(lun) + })) lun = 0; + + // (Almost) initialization procedure laid out by Doug Brown + + int attempts; + + attempts = 100; + + while(attempts-- > 0) { + + int success = 1; + + if(!BBBTestUnitReady(dev)) { + success = 0; + } + + if(!BBBInquiry(dev)) { + success = 0; + } + + if(success) { + break; + } + + } + + if(attempts > 0) { + + attempts = 100; + + while(attempts-- > 0) { + if(BBBReadCapacity10(dev)) { + break; + } + } + + if(attempts > 0) { + + //BBBModeSense(dev); + + // One flash drive doesn't work at all without this Read(10) + uint8_t lolibuf[dev->bbb.sectorSize]; + BBBRead10(dev, 0, lolibuf, 1); + + for(uint32_t try = 0; try <= 0xFFFF; try++) { + if((dev->canal = sys_canal_create('STRG', 'UD\0\0' | try)) < (uint32_t) -256) { + break; + } + } + + if(dev->canal >= (uint32_t) -256) { + return 0; + } + + dev->respond = BBBDeviceResponse; + + } + + } + } + } + } + } + } + } + + return 1; +} diff --git a/luma/uhci/usb.h b/luma/uhci/usb.h new file mode 100644 index 0000000..0b28a57 --- /dev/null +++ b/luma/uhci/usb.h @@ -0,0 +1,86 @@ +#pragma once + +#include + +typedef enum { + SETUP = 0x2D, IN = 0x69, OUT = 0xE1 +} PacketType; + +typedef struct USBDevice { + uint8_t hc; + uint8_t addr; + uint8_t speedy; + uint8_t id; + uint8_t maxPacketSize; + uint32_t canal; + union { + struct { + int endpIn; + int endpOut; + int maxPacketSize; + int toggleIn; + int toggleOut; + uint16_t sectorSize; + } bbb; + }; + int(*respond)(struct USBDevice *dev, void *area, uint32_t meta); +} USBDevice; + +typedef struct __attribute((packed)) { + uint8_t requestType; + uint8_t request; + uint16_t value; + uint16_t index; + uint16_t length; +} USBStandardRequest; + +typedef struct { + uint8_t sz; + uint8_t type; + uint16_t usbVer; + uint8_t clazz; + uint8_t subclazz; + uint8_t protocol; + uint8_t maxPacketSize; + uint16_t idVendor; + uint16_t idProduct; + uint16_t devVer; + uint8_t stringManufacturer; + uint8_t stringProduct; + uint8_t stringSerial; + uint8_t configurationCount; +} USBDeviceDescriptor; + +typedef struct { + uint8_t sz; + uint8_t type; + uint16_t szTotal; + uint8_t interfaceCount; + uint8_t id; + uint8_t string; + uint8_t attributes; + uint8_t maxPower; +} USBConfigurationDescriptor; + +typedef struct { + uint8_t sz; + uint8_t type; + uint8_t interface; + uint8_t alternate; + uint8_t endpointCount; + uint8_t clazz; + uint8_t subclazz; + uint8_t protocol; + uint8_t string; +} USBInterfaceDescriptor; + +typedef struct { + uint8_t sz; + uint8_t type; + uint8_t endpoint; + uint8_t attributes; + uint16_t maxPacketSize; + uint8_t interval; +} USBEndpointDescriptor; + +int USBDeviceDiscover(USBDevice*); \ No newline at end of file diff --git a/luma/vid/Makefile b/luma/vid/Makefile new file mode 100644 index 0000000..2ace22f --- /dev/null +++ b/luma/vid/Makefile @@ -0,0 +1,13 @@ +rwildcard=$(foreach d,$(wildcard $(1:=/*)),$(call rwildcard,$d,$2) $(filter $(subst *,%,$2),$d)) + +HEADERS := $(call rwildcard,.,*.h) +SOURCEC := $(call rwildcard,.,*.c) +OBJECTS := $(patsubst %.c, ../../build/vid/%.o, $(SOURCEC)) + +mod: $(OBJECTS) + i386-elf-gcc -pie -T ../../mod.ld -Wl,-no-dynamic-linker -nostdlib -o main.elf $(OBJECTS) -lgcc + ../../elftomod.py main.elf ../../bootfs/luma_vid.mod modentry:0 + +../../build/vid/%.o: %.c + mkdir -p $(@D) + i386-elf-gcc -march=i386 -Isrc -Os -pie -nodefaultlibs -nostdlib -nostartfiles -fomit-frame-pointer -c -o $@ -ffreestanding -mgeneral-regs-only -std=gnu99 -Wall $< diff --git a/luma/vid/api.h b/luma/vid/api.h new file mode 100644 index 0000000..c4b4460 --- /dev/null +++ b/luma/vid/api.h @@ -0,0 +1,88 @@ +#ifndef _LUMA_VBE_VBE_H +#define _LUMA_VBE_VBE_H + +#include + +typedef enum { + LUMA_VID_COMMAND_END = 0, LUMA_VID_COMMAND_CLEAR = 1, LUMA_VID_COMMAND_RECT = 2, LUMA_VID_COMMAND_IMAGE = 3, LUMA_VID_COMMAND_IMAGE_NEW = 4, LUMA_VID_COMMAND_SET_COLOR_FLAT = 5, + LUMA_VID_COMMAND_SET_COLOR_GRAD = 6, LUMA_VID_COMMAND_IMAGE_DEL = 7, LUMA_VID_COMMAND_TEXT = 8, LUMA_VID_COMMAND_NEW_COLOR_FLAT = 9, LUMA_VID_COMMAND_NEW_COLOR_GRAD = 10, LUMA_VID_COMMAND_IMAGE_WRITE = 11, +} LumaVidCommandOp; + +typedef enum { + LUMA_VID_IMAGE_FORMAT_RAW = 0, LUMA_VID_IMAGE_FORMAT_R8G8B8 = 1, LUMA_VID_IMAGE_FORMAT_BLALPHA = 2 +} LumaVidImageDescriptionFormat; + +typedef enum { + LUMA_VID_ALIGN_TOP_LEFT = 0, + LUMA_VID_ALIGN_TOP_RIGHT = 1, + LUMA_VID_ALIGN_BOTTOM_LEFT = 2, + LUMA_VID_ALIGN_BOTTOM_RIGHT = 3, +} LumaVidAlign; + +typedef union { + uint8_t op; + struct { + uint8_t op; + } __attribute__((packed)) clear; + struct { + uint8_t op; + uint16_t y2; + uint16_t x2; + uint16_t y1; + uint16_t x1; + } __attribute__((packed)) rect; + struct { + uint8_t op; + uint16_t y; + uint16_t x; + uint16_t subY; + uint16_t subX; + uint16_t width; + uint16_t height; + uint32_t name; + } __attribute__((packed)) image; + struct { + uint8_t op; + uint32_t name; + uint16_t width; + uint16_t height; + uint8_t format; + } __attribute__((packed)) imageNew; + struct { + uint8_t op; + uint8_t r; + uint8_t g; + uint8_t b; + } __attribute__((packed)) colorFlat; + struct { + uint8_t op; + uint8_t r1; + uint8_t r2; + uint8_t g1; + uint8_t g2; + uint8_t b1; + uint8_t b2; + } __attribute__((packed)) colorGrad; + struct { + uint8_t op; + uint32_t name; + } __attribute__((packed)) imageDel; + struct { + uint8_t op; + uint16_t y; + uint16_t x; + uint16_t len; + uint16_t wall; + uint8_t data[]; + } __attribute__((packed)) text; + struct { + uint8_t op; + uint32_t name; + uint16_t y; + uint16_t x; + uint16_t len; + uint8_t data[]; + } __attribute__((packed)) imageWrite; +} __attribute__((packed)) LumaVidCommand; + +#endif \ No newline at end of file diff --git a/luma/vid/kmeans.c b/luma/vid/kmeans.c new file mode 100644 index 0000000..065ba3c --- /dev/null +++ b/luma/vid/kmeans.c @@ -0,0 +1,101 @@ +#include"kmeans.h" + +#include"../sys.h" + +#define RED(c) (c >> 11) +#define GRN(c) ((c >> 5) & 63) +#define BLU(c) (c & 31) + +#define CLUSTERS 256 +struct { + MiniCol averages[CLUSTERS]; +} Cluster; + +typedef struct { + uint8_t cluster; + MiniCol color; +} __attribute__((packed)) Datapoint; + +struct { + size_t sz; + Datapoint *buf; +} Dataset = {}; + +__attribute__((optimize("Ofast"))) static uint32_t coldist(MiniCol a, MiniCol b) { + uint16_t dr = RED(a) - RED(b); + uint16_t dg = GRN(a) - GRN(b); + uint16_t db = BLU(a) - BLU(b); + return (uint16_t) (dr * dr) + (uint16_t) (dg * dg) + (uint16_t) (db * db); +} + +void q_reavg() { + if(Dataset.sz < CLUSTERS) { + for(size_t i = 0; i < Dataset.sz; i++) { + MiniCol c = Dataset.buf[i].color; + Cluster.averages[Dataset.buf[i].cluster = i] = c; + } + } else { + uint16_t counts[CLUSTERS] = {}; + uint16_t avgRed[CLUSTERS] = {}; + uint32_t avgGreen[CLUSTERS] = {}; + uint16_t avgBlue[CLUSTERS] = {}; + for(size_t i = 0; i < Dataset.sz; i++) { + counts[Dataset.buf[i].cluster]++; + avgRed[Dataset.buf[i].cluster] += RED(Dataset.buf[i].color); + avgGreen[Dataset.buf[i].cluster] += GRN(Dataset.buf[i].color); + avgBlue[Dataset.buf[i].cluster] += BLU(Dataset.buf[i].color); + } + + for(int i = 0; i < CLUSTERS; i++) { + if(counts[i] == 0) continue; + + avgRed[i] /= counts[i]; + avgGreen[i] /= counts[i]; + avgBlue[i] /= counts[i]; + + Cluster.averages[i] = (avgRed[i] << 11) | (avgGreen[i] << 5) | avgBlue[i]; + } + } + + for(size_t i = 0; i < Dataset.sz; i++) { + Dataset.buf[i].cluster = q_p2c(Dataset.buf[i].color); + } +} + +__attribute__((optimize("Ofast"))) int q_p2c(MiniCol col) { + int clu = 0; + uint32_t dist = coldist(col, Cluster.averages[clu]); + + for(int i = 1; i < CLUSTERS; i++) { + uint32_t d = coldist(col, Cluster.averages[i]); + if(dist > d) { + dist = d; + clu = i; + } + } + + return clu; +} + +void q_reassign() { + asm("out %%al, %%dx" : : "a"(0), "d"(0x3C8)); + size_t bound = Dataset.sz < CLUSTERS ? Dataset.sz : CLUSTERS; + for(size_t i = 0; i < bound; i++) { + MiniCol c = Cluster.averages[i]; + asm("out %%al, %%dx" : : "a"((c >> 10) & ~1), "d"(0x3C9)); + asm("out %%al, %%dx" : : "a"((c >> 5) & 63), "d"(0x3C9)); + asm("out %%al, %%dx" : : "a"((c & 31) << 1), "d"(0x3C9)); + } +} + +void q_addp(MiniCol col) { + if(Dataset.sz == 4096 / sizeof(Datapoint)) { + return; + } + + Dataset.buf[Dataset.sz++] = (Datapoint) {.cluster = q_p2c(col), .color = col}; +} + +void q_init() { + Dataset.buf = sys_vpm_map(SYS_MAP_VIRT_ANY, SYS_MAP_PHYS_ANY, 4096); +} \ No newline at end of file diff --git a/luma/vid/kmeans.c.test b/luma/vid/kmeans.c.test new file mode 100644 index 0000000..355e4ce --- /dev/null +++ b/luma/vid/kmeans.c.test @@ -0,0 +1,13 @@ +#include +#include + +#define sys_vpm_map(x,y,z) malloc(z) +#include"kmeans.c" + +int main() { + q_init(); + + MiniCol c = 30 | (30 << 5) | (30 << 11); + q_addp(c); + q_p2c(); +} \ No newline at end of file diff --git a/luma/vid/kmeans.h b/luma/vid/kmeans.h new file mode 100644 index 0000000..d81a34a --- /dev/null +++ b/luma/vid/kmeans.h @@ -0,0 +1,15 @@ +#ifndef KMEANS_H +#define KMEANS_H + +#include +#include + +typedef uint16_t MiniCol; + +void q_init(); +void q_reavg(); +void q_reassign(); +int q_p2c(MiniCol col); +void q_addp(MiniCol col); + +#endif \ No newline at end of file diff --git a/luma/vid/main.c b/luma/vid/main.c new file mode 100644 index 0000000..34a1dab --- /dev/null +++ b/luma/vid/main.c @@ -0,0 +1,497 @@ +#include +#include +#include"../sys.h" +#include"../std.h" +#include"api.h" +#include"kmeans.h" + +asm("modentry:\n" +"mov $stack + 2816, %esp\n" +"call startc"); + +static uint8_t *FrameBuffer; + +typedef struct { + uint32_t name; + uint32_t len; + uint8_t code[]; +} DL; + +static struct { + size_t idx; + uint8_t *buf; +} DLs; + +typedef struct { + uint16_t w, h; + uint8_t format; + uint8_t data[]; +} Image; + +static struct { + size_t idx; + Image **handles; +} Images; + +char stack[2816]; + +static uint8_t(*colorFunc)(uint16_t x, uint16_t y); + +static uint8_t color_flat[] = {0xB8, 0x78, 0x56, 0x34, 0x12, 0xC3}; + +static uint8_t gradCols[16]; +__attribute__((optimize("Ofast"))) static uint8_t color_grad(uint16_t x, uint16_t y) { + static uint8_t matrix[16][16] = {{0, 64, 16, 80, 4, 68, 20, 84, 1, 65, 17, 81, 5, 69, 21, 85}, {192, 128, 208, 144, 196, 132, 212, 148, 193, 129, 209, 145, 197, 133, 213, 149}, {48, 112, 32, 96, 52, 116, 36, 100, 49, 113, 33, 97, 53, 117, 37, 101}, {240, 176, 224, 160, 244, 180, 228, 164, 241, 177, 225, 161, 245, 181, 229, 165}, {12, 76, 28, 92, 8, 72, 24, 88, 13, 77, 29, 93, 9, 73, 25, 89}, {204, 140, 220, 156, 200, 136, 216, 152, 205, 141, 221, 157, 201, 137, 217, 153}, {60, 124, 44, 108, 56, 120, 40, 104, 61, 125, 45, 109, 57, 121, 41, 105}, {252, 188, 236, 172, 248, 184, 232, 168, 253, 189, 237, 173, 249, 185, 233, 169}, {3, 67, 19, 83, 7, 71, 23, 87, 2, 66, 18, 82, 6, 70, 22, 86}, {195, 131, 211, 147, 199, 135, 215, 151, 194, 130, 210, 146, 198, 134, 214, 150}, {51, 115, 35, 99, 55, 119, 39, 103, 50, 114, 34, 98, 54, 118, 38, 102}, {243, 179, 227, 163, 247, 183, 231, 167, 242, 178, 226, 162, 246, 182, 230, 166}, {15, 79, 31, 95, 11, 75, 27, 91, 14, 78, 30, 94, 10, 74, 26, 90}, {207, 143, 223, 159, 203, 139, 219, 155, 206, 142, 222, 158, 202, 138, 218, 154}, {63, 127, 47, 111, 59, 123, 43, 107, 62, 126, 46, 110, 58, 122, 42, 106}, {255, 191, 239, 175, 251, 187, 235, 171, 254, 190, 238, 174, 250, 186, 234, 170}}; + + int i = x * 256 / 320; + i += matrix[x % 16][y % 16] / 16; + i /= 16; + if(i > 15) i = 15; + + return gradCols[i]; +} + +__attribute__((optimize("Ofast"))) static void select_planes(int planes) { + asm("out %%al, %%dx" : : "a"(2), "d"(0x3C4)); + asm("out %%al, %%dx" : : "a"(planes), "d"(0x3C5)); +} + +__attribute__((optimize("Ofast"))) static void clear() { + if((uintptr_t) colorFunc == (uintptr_t) color_flat) { + uint8_t col = colorFunc(0, 0); + + select_planes(15); + for(int i = 0; i < 4800; i++) { + ((uint32_t*) FrameBuffer)[i] = col | (col << 8) | (col << 16) | (col << 24); + } + } else { + for(int p = 0; p < 4; p++) { + select_planes(1 << p); + for(int y = 0; y < 240; y++) { + for(int x = 0; x < 80; x++) { + FrameBuffer[80 * y + x] = colorFunc(x * 4 + p, y); + } + } + } + } +} + +__attribute__((optimize("Ofast"))) static void rect(int x1, int y1, int x2, int y2) { + select_planes(1 << ((x1 + 0) & 3)); + for(int y = y1; y <= y2; y++) { + for(int x = x1 + 0; x <= x2; x += 4) { + FrameBuffer[80 * y + x / 4] = colorFunc(x, y); + } + } + select_planes(1 << ((x1 + 1) & 3)); + for(int y = y1; y <= y2; y++) { + for(int x = x1 + 1; x <= x2; x += 4) { + FrameBuffer[80 * y + x / 4] = colorFunc(x, y); + } + } + select_planes(1 << ((x1 + 2) & 3)); + for(int y = y1; y <= y2; y++) { + for(int x = x1 + 2; x <= x2; x += 4) { + FrameBuffer[80 * y + x / 4] = colorFunc(x, y); + } + } + select_planes(1 << ((x1 + 3) & 3)); + for(int y = y1; y <= y2; y++) { + for(int x = x1 + 3; x <= x2; x += 4) { + FrameBuffer[80 * y + x / 4] = colorFunc(x, y); + } + } +} + +__attribute__((optimize("Ofast"))) static void image(Image *img, uint16_t subX, uint16_t subY, uint16_t x, uint16_t y, uint16_t width, uint16_t height) { + if(img->format == LUMA_VID_IMAGE_FORMAT_BLALPHA) { + uint8_t c = colorFunc(0, 0); + for(int ix = 0; ix < width; ix++) { + select_planes(1 << ((x + ix) & 3)); + for(int iy = 0; iy < height; iy++) { + uint8_t v = img->data[(iy * img->w + ix) / 8]; + if(v & (1 << (ix % 8))) { + FrameBuffer[80 * (iy + y) + (ix + x) / 4] = c; + } + } + } + } else if(img->format == LUMA_VID_IMAGE_FORMAT_R8G8B8) { + for(int plane = 0; plane < 4; plane++) { + select_planes(1 << ((x + plane) & 3)); + + for(int iy = 0; iy < height; iy++) { + uint8_t *dst = FrameBuffer + 80 * (iy + y) + x / 4; + for(int ix = plane; ix < width; ix += 4) { + *(dst++) = q_p2c(*(MiniCol*) &img->data[((iy + subY) * img->w + ix + subX) * 2]); + } + } + } + } +} + +__attribute__((optimize("Ofast"))) static void text(const char *str, size_t len, uint16_t x, uint16_t y, uint16_t wall) { + if(wall <= x) wall = 320; + + static const uint8_t font[] = { + 0x20, 0x31, 0x95, 0x00, 0x21, 0x17, 0x15, 0x5f, 0x22, 0x32, 0x15, 0x2d, + 0x23, 0x47, 0x15, 0xaa, 0xaf, 0x5f, 0x05, 0x24, 0x48, 0x15, 0x5e, 0x65, + 0xcc, 0x47, 0x25, 0x57, 0x15, 0x6b, 0x1d, 0xc2, 0xb5, 0x06, 0x26, 0x57, + 0x15, 0x44, 0x19, 0x9b, 0x92, 0x05, 0x27, 0x12, 0x15, 0x03, 0x28, 0x28, + 0x15, 0x56, 0x95, 0x29, 0x28, 0x15, 0xa9, 0x6a, 0x2a, 0x34, 0x15, 0xfa, + 0x05, 0x2b, 0x55, 0x35, 0x84, 0x7c, 0x42, 0x00, 0x2c, 0x22, 0x75, 0x06, + 0x2d, 0x31, 0x55, 0x07, 0x2e, 0x11, 0x75, 0x01, 0x2f, 0x37, 0x15, 0xa4, + 0xa4, 0x04, 0x30, 0x47, 0x15, 0x96, 0xb9, 0x99, 0x06, 0x31, 0x37, 0x15, + 0x93, 0x24, 0x1d, 0x32, 0x47, 0x15, 0x87, 0x48, 0x12, 0x0f, 0x33, 0x47, + 0x15, 0x87, 0x68, 0x88, 0x07, 0x34, 0x57, 0x15, 0x8c, 0xa9, 0xf4, 0x11, + 0x02, 0x35, 0x47, 0x15, 0x1f, 0x71, 0x88, 0x07, 0x36, 0x47, 0x15, 0x1e, + 0x71, 0x99, 0x06, 0x37, 0x47, 0x15, 0x8f, 0x44, 0x22, 0x01, 0x38, 0x47, + 0x15, 0x96, 0x69, 0x99, 0x06, 0x39, 0x47, 0x15, 0x96, 0xe9, 0x88, 0x07, + 0x3a, 0x15, 0x35, 0x11, 0x3b, 0x26, 0x35, 0x02, 0x06, 0x3c, 0x35, 0x25, + 0x54, 0x44, 0x3d, 0x43, 0x45, 0x0f, 0x0f, 0x3e, 0x35, 0x25, 0x11, 0x15, + 0x3f, 0x37, 0x15, 0x2a, 0x25, 0x08, 0x40, 0x57, 0x15, 0x2e, 0xf6, 0xde, + 0x82, 0x03, 0x41, 0x57, 0x15, 0x84, 0x28, 0xe5, 0x62, 0x04, 0x42, 0x47, + 0x15, 0x97, 0x79, 0x99, 0x07, 0x43, 0x47, 0x15, 0x1e, 0x11, 0x11, 0x0e, + 0x44, 0x47, 0x15, 0x97, 0x99, 0x99, 0x07, 0x45, 0x47, 0x15, 0x1f, 0xf1, + 0x11, 0x0f, 0x46, 0x47, 0x15, 0x1f, 0xf1, 0x11, 0x01, 0x47, 0x47, 0x15, + 0x1e, 0x11, 0x9d, 0x0e, 0x48, 0x47, 0x15, 0x99, 0xf9, 0x99, 0x09, 0x49, + 0x37, 0x15, 0x97, 0x24, 0x1d, 0x4a, 0x37, 0x15, 0x24, 0x49, 0x0e, 0x4b, + 0x57, 0x15, 0x31, 0x95, 0x93, 0x52, 0x04, 0x4c, 0x47, 0x15, 0x11, 0x11, + 0x11, 0x0f, 0x4d, 0x47, 0x15, 0xb9, 0xbf, 0x99, 0x09, 0x4e, 0x47, 0x15, + 0xb9, 0xbb, 0xdd, 0x09, 0x4f, 0x47, 0x15, 0x96, 0x99, 0x99, 0x06, 0x50, + 0x47, 0x15, 0x97, 0x79, 0x11, 0x01, 0x51, 0x48, 0x15, 0x96, 0x99, 0x99, + 0x86, 0x52, 0x57, 0x15, 0x27, 0xa5, 0x53, 0x52, 0x04, 0x53, 0x47, 0x15, + 0x1e, 0x61, 0x88, 0x07, 0x54, 0x57, 0x15, 0x9f, 0x10, 0x42, 0x08, 0x01, + 0x55, 0x47, 0x15, 0x99, 0x99, 0x99, 0x06, 0x56, 0x57, 0x15, 0x31, 0x2a, + 0xa5, 0x08, 0x01, 0x57, 0x57, 0x15, 0x31, 0xd6, 0xba, 0x94, 0x02, 0x58, + 0x47, 0x15, 0x99, 0x66, 0x96, 0x09, 0x59, 0x57, 0x15, 0x51, 0x29, 0x42, + 0x08, 0x01, 0x5a, 0x47, 0x15, 0x8f, 0x24, 0x12, 0x0f, 0x5b, 0x28, 0x15, + 0x57, 0xd5, 0x5c, 0x37, 0x15, 0x89, 0x24, 0x12, 0x5d, 0x28, 0x15, 0xab, + 0xea, 0x5e, 0x53, 0x25, 0x44, 0x45, 0x5f, 0x51, 0x95, 0x1f, 0x60, 0x22, + 0x15, 0x09, 0x61, 0x45, 0x35, 0x87, 0x9e, 0x0e, 0x62, 0x47, 0x15, 0x11, + 0x97, 0x99, 0x07, 0x63, 0x45, 0x35, 0x1e, 0x11, 0x0e, 0x64, 0x47, 0x15, + 0x88, 0x9e, 0x99, 0x0e, 0x65, 0x45, 0x35, 0x96, 0x1f, 0x0e, 0x66, 0x47, + 0x15, 0x2c, 0x2f, 0x22, 0x02, 0x67, 0x47, 0x35, 0x5e, 0x12, 0x9f, 0x06, + 0x68, 0x47, 0x15, 0x11, 0xb5, 0x99, 0x09, 0x69, 0x27, 0x15, 0xb2, 0x2a, + 0x6a, 0x39, 0x15, 0x84, 0x49, 0x92, 0x03, 0x6b, 0x57, 0x15, 0x21, 0xa4, + 0x72, 0x52, 0x04, 0x6c, 0x37, 0x15, 0x93, 0x24, 0x19, 0x6d, 0x55, 0x35, + 0xab, 0xd6, 0x5a, 0x01, 0x6e, 0x45, 0x35, 0xb5, 0x99, 0x09, 0x6f, 0x45, + 0x35, 0x96, 0x99, 0x06, 0x70, 0x47, 0x35, 0x97, 0x99, 0x17, 0x01, 0x71, + 0x47, 0x35, 0x9e, 0x99, 0x8e, 0x08, 0x72, 0x35, 0x35, 0x4f, 0x12, 0x73, + 0x45, 0x35, 0x1f, 0x86, 0x07, 0x74, 0x46, 0x25, 0xf2, 0x22, 0xc2, 0x75, + 0x45, 0x35, 0x99, 0x99, 0x0e, 0x76, 0x45, 0x35, 0xa9, 0x4a, 0x04, 0x77, + 0x55, 0x35, 0xb1, 0x56, 0xa5, 0x00, 0x78, 0x45, 0x35, 0x69, 0x66, 0x09, + 0x79, 0x47, 0x35, 0xa9, 0x4a, 0x44, 0x03, 0x7a, 0x45, 0x35, 0x4f, 0x12, + 0x0f, 0x7b, 0x39, 0x15, 0x94, 0x14, 0x49, 0x04, 0x7c, 0x18, 0x15, 0xff, + 0x7d, 0x39, 0x15, 0x91, 0x44, 0x49, 0x01, 0x7e, 0x52, 0x45, 0x36, 0x01 + }; + + const uint8_t *find(char c) { + const uint8_t *a = font; + while(a - font < sizeof(font)) { + if(*a == c) { + return a; + } else { + a += 3 + ((a[1] & 15) * (a[1] >> 4) + 7) / 8; + } + } + return NULL; + } + + uint16_t startX = x; + + int col = colorFunc(0, 0); + while(len--) { + if(*str == 10) { + str++; + x = startX; + y += 13; + continue; + } + + const uint8_t *data = find(*(str++)); + + if(data == NULL) continue; + + uint16_t cx = 0, cy = data[2] >> 4; + + uint8_t width = data[2] & 0x0F; + if(x + width >= wall) { + x = startX; + y += 13; + } + + for(int ix = 0; ix < (data[1] >> 4); ix++) { + select_planes(1 << ((x + ix) & 3)); + for(int iy = 0; iy < (data[1] & 15); iy++) { + uint8_t v = data[3 + (iy * (data[1] >> 4) + ix) / 8]; + if(v & (1 << ((iy * (data[1] >> 4) + ix) % 8))) { + FrameBuffer[80 * (iy + y + cy) + (ix + x + cx) / 4] = col; + } + } + } + + x += width; + } +} + +static void compileCommandList(uint8_t *src, uint8_t *dst) { + size_t len = 0; + while(1) { + LumaVidCommand *cmd = (void*) src; + + if(cmd->op == LUMA_VID_COMMAND_CLEAR) { + dst[len++] = 0xE8; /* call rel32 */ + *((uint32_t*) &dst[len]) = (uint32_t) &clear - (uint32_t) &dst[len + 4]; + len += 4; + src += sizeof(cmd->clear); + } else if(cmd->op == LUMA_VID_COMMAND_END) { + dst[len++] = 0xC3; /* ret */ + break; + } else if(cmd->op == LUMA_VID_COMMAND_RECT) { + dst[len++] = 0x68; /* push imm32 */ + dst[len++] = cmd->rect.y2 & 0xFF; + dst[len++] = cmd->rect.y2 >> 8; + dst[len++] = 0; + dst[len++] = 0; + dst[len++] = 0x68; /* push imm32 */ + dst[len++] = cmd->rect.x2 & 0xFF; + dst[len++] = cmd->rect.x2 >> 8; + dst[len++] = 0; + dst[len++] = 0; + dst[len++] = 0x68; /* push imm32 */ + dst[len++] = cmd->rect.y1 & 0xFF; + dst[len++] = cmd->rect.y1 >> 8; + dst[len++] = 0; + dst[len++] = 0; + dst[len++] = 0x68; /* push imm32 */ + dst[len++] = cmd->rect.x1 & 0xFF; + dst[len++] = cmd->rect.x1 >> 8; + dst[len++] = 0; + dst[len++] = 0; + dst[len++] = 0xE8; /* call rel32 */ + *((uint32_t*) &dst[len]) = (uint32_t) &rect - (uint32_t) &dst[len + 4]; + len += 4; + dst[len++] = 0x83; /* add */ + dst[len++] = 0xC4; /* esp */ + dst[len++] = 16; + src += sizeof(cmd->rect); + } else if(cmd->op == LUMA_VID_COMMAND_IMAGE) { + dst[len++] = 0x68; /* push imm32 */ + dst[len++] = cmd->image.height & 0xFF; + dst[len++] = cmd->image.height >> 8; + dst[len++] = 0; + dst[len++] = 0; + dst[len++] = 0x68; /* push imm32 */ + dst[len++] = cmd->image.width & 0xFF; + dst[len++] = cmd->image.width >> 8; + dst[len++] = 0; + dst[len++] = 0; + dst[len++] = 0x68; /* push imm32 */ + dst[len++] = cmd->image.y & 0xFF; + dst[len++] = cmd->image.y >> 8; + dst[len++] = 0; + dst[len++] = 0; + dst[len++] = 0x68; /* push imm32 */ + dst[len++] = cmd->image.x & 0xFF; + dst[len++] = cmd->image.x >> 8; + dst[len++] = 0; + dst[len++] = 0; + dst[len++] = 0x68; /* push imm32 */ + dst[len++] = cmd->image.subY & 0xFF; + dst[len++] = cmd->image.subY >> 8; + dst[len++] = 0; + dst[len++] = 0; + dst[len++] = 0x68; /* push imm32 */ + dst[len++] = cmd->image.subX & 0xFF; + dst[len++] = cmd->image.subX >> 8; + dst[len++] = 0; + dst[len++] = 0; + dst[len++] = 0x68; /* push imm32 */ + Image *img = Images.handles[cmd->image.name]; + dst[len++] = ((uint32_t) img >> 0) & 0xFF; + dst[len++] = ((uint32_t) img >> 8) & 0xFF; + dst[len++] = ((uint32_t) img >> 16) & 0xFF; + dst[len++] = ((uint32_t) img >> 24) & 0xFF; + dst[len++] = 0xE8; /* call rel32 */ + *((uint32_t*) &dst[len]) = (uint32_t) &image - (uint32_t) &dst[len + 4]; + len += 4; + dst[len++] = 0x83; /* add */ + dst[len++] = 0xC4; /* esp */ + dst[len++] = 28; + src += sizeof(cmd->image); + } else if(cmd->op == LUMA_VID_COMMAND_IMAGE_NEW) { + Image *img = NULL; + if(cmd->imageNew.format == LUMA_VID_IMAGE_FORMAT_BLALPHA) { + img = sys_vpm_map(SYS_MAP_VIRT_ANY, SYS_MAP_PHYS_ANY, sizeof(Image) + (cmd->imageNew.width * cmd->imageNew.height + 7) / 8); + } else if(cmd->imageNew.format == LUMA_VID_IMAGE_FORMAT_R8G8B8) { + img = sys_vpm_map(SYS_MAP_VIRT_ANY, SYS_MAP_PHYS_ANY, sizeof(Image) + cmd->imageNew.width * cmd->imageNew.height * 2); + } + if(img) { + img->w = cmd->imageNew.width; + img->h = cmd->imageNew.height; + img->format = cmd->imageNew.format; + } + Images.handles[cmd->imageNew.name] = img; + + src += sizeof(cmd->imageNew); + } else if(cmd->op == LUMA_VID_COMMAND_IMAGE_WRITE) { + Image *img = Images.handles[cmd->imageWrite.name]; + if(img->format == LUMA_VID_IMAGE_FORMAT_BLALPHA) { + // Copy data + std_copy(img->data + cmd->imageWrite.y * img->w + cmd->imageWrite.x, cmd->imageWrite.data, cmd->imageWrite.len); + } else if(img->format == LUMA_VID_IMAGE_FORMAT_R8G8B8) { + // Copy data and reformat + MiniCol *dst = (MiniCol*) img->data + cmd->imageWrite.y * img->w + cmd->imageWrite.x; + for(size_t i = 0; i < cmd->imageWrite.len; i += 3) { + *(dst++) = ((cmd->imageWrite.data[i + 0] & ~7) << 8) | ((cmd->imageWrite.data[i + 1] & ~3) << 3) | (cmd->imageWrite.data[i + 2] >> 3); + } + } + src += sizeof(cmd->imageWrite) + cmd->imageWrite.len; + } else if(cmd->op == LUMA_VID_COMMAND_SET_COLOR_FLAT) { + MiniCol minicol = ((cmd->colorFlat.r & ~7) << 8) | ((cmd->colorFlat.g & ~3) << 3) | (cmd->colorFlat.b >> 3); + + dst[len++] = 0xC7; /* mov [abs], imm */ + dst[len++] = 0x05; + *((uint32_t*) &dst[len]) = (uint32_t) &colorFunc; + len += 4; + *((uint32_t*) &dst[len]) = (uint32_t) color_flat; + len += 4; + dst[len++] = 0x68; /* push imm32 */ + *((uint32_t*) &dst[len]) = minicol; + len += 4; + dst[len++] = 0xE8; /* call rel32 */ + *((uint32_t*) &dst[len]) = (uint32_t) &q_p2c - (uint32_t) &dst[len + 4]; + len += 4; + dst[len++] = 0x83; /* add */ + dst[len++] = 0xC4; /* esp */ + dst[len++] = 4; + dst[len++] = 0xA3; /* mov [abs], eax */ + *((uint32_t*) &dst[len]) = (uint32_t) color_flat + 1; + len += 4; + src += sizeof(cmd->colorFlat); + } else if(cmd->op == LUMA_VID_COMMAND_SET_COLOR_GRAD) { + MiniCol cols[16]; + for(int i = 15; i >= 0; i--) { + unsigned int r = (cmd->colorGrad.r1 * (15 - i) + cmd->colorGrad.r2 * i) / 15; + unsigned int g = (cmd->colorGrad.g1 * (15 - i) + cmd->colorGrad.g2 * i) / 15; + unsigned int b = (cmd->colorGrad.b1 * (15 - i) + cmd->colorGrad.b2 * i) / 15; + cols[i] = ((r & ~7) << 8) | ((g & ~3) << 3) | (b >> 3); + } + + dst[len++] = 0xC7; /* mov [abs], imm32 */ + dst[len++] = 0x05; + *((uint32_t*) &dst[len]) = (uint32_t) &colorFunc; + len += 4; + *((uint32_t*) &dst[len]) = (uint32_t) &color_grad; + len += 4; + dst[len++] = 0x83; /* sub esp, imm8 */ + dst[len++] = 0xEC; + dst[len++] = 0x04; + for(int i = 0; i < 16; i++) { + dst[len++] = 0x66; /* mov [esp], imm16 */ + dst[len++] = 0xC7; + dst[len++] = 0x04; + dst[len++] = 0x24; + *((uint16_t*) &dst[len]) = cols[i]; + len += 2; + + dst[len++] = 0xE8; /* call rel32 */ + *((uint32_t*) &dst[len]) = (uint32_t) &q_p2c - (uint32_t) &dst[len + 4]; + len += 4; + + dst[len++] = 0xA2; /* mov [abs], al */ + *((uint32_t*) &dst[len]) = (uint32_t) &gradCols[i]; + len += 4; + } + dst[len++] = 0x83; /* add esp, imm8 */ + dst[len++] = 0xC4; + dst[len++] = 0x04; + src += sizeof(cmd->colorGrad); + } else if(cmd->op == LUMA_VID_COMMAND_IMAGE_DEL) { + src += sizeof(cmd->imageDel); + } else if(cmd->op == LUMA_VID_COMMAND_TEXT) { + dst[len++] = 0x68; + *((uint32_t*) &dst[len]) = cmd->text.wall; + len += 4; + dst[len++] = 0x68; + *((uint32_t*) &dst[len]) = cmd->text.y; + len += 4; + dst[len++] = 0x68; + *((uint32_t*) &dst[len]) = cmd->text.x; + len += 4; + dst[len++] = 0x68; + *((uint32_t*) &dst[len]) = cmd->text.len; + len += 4; + dst[len++] = 0x68; + *((uint32_t*) &dst[len]) = (uint32_t) &dst[len + 14]; + len += 4; + dst[len++] = 0x68; + *((uint32_t*) &dst[len]) = (uint32_t) &dst[len + 9 + cmd->text.len]; + len += 4; + dst[len++] = 0xE9; + *((uint32_t*) &dst[len]) = (uint32_t) &text - (uint32_t) &dst[len + 4]; + len += 4; + std_copy(&dst[len], cmd->text.data, cmd->text.len); + len += cmd->text.len; + dst[len++] = 0x83; /* add esp, imm8 */ + dst[len++] = 0xC4; + dst[len++] = 0x14; + src += sizeof(cmd->text) + cmd->text.len; + } else if(cmd->op == LUMA_VID_COMMAND_NEW_COLOR_FLAT) { + MiniCol minicol = ((cmd->colorFlat.r & ~7) << 8) | ((cmd->colorFlat.g & ~3) << 3) | (cmd->colorFlat.b >> 3); + q_addp(minicol); + q_reavg(); + src += sizeof(cmd->colorFlat); + } else if(cmd->op == LUMA_VID_COMMAND_NEW_COLOR_GRAD) { + MiniCol cols[16]; + for(int i = 15; i >= 0; i--) { + unsigned int r = (cmd->colorGrad.r1 * (15 - i) + cmd->colorGrad.r2 * i) / 15; + unsigned int g = (cmd->colorGrad.g1 * (15 - i) + cmd->colorGrad.g2 * i) / 15; + unsigned int b = (cmd->colorGrad.b1 * (15 - i) + cmd->colorGrad.b2 * i) / 15; + q_addp(cols[i] = ((r & ~7) << 8) | ((g & ~3) << 3) | (b >> 2)); + } + q_reavg(); + src += sizeof(cmd->colorGrad); + } + } +} + +static void removeDL(DL *dl) { + /*size_t sz = sizeof(*dl) + dl->len; + std_move(dl, (void*) ((uintptr_t) dl + sz), (uintptr_t) dl + DLs.idx - (uintptr_t) DLs.buf - sz); + memory_barrier(); + DLs.idx -= sz;*/ + /* TODO: relocate */ +} + +void startc() { + FrameBuffer = sys_vpm_map(SYS_MAP_VIRT_ANY, (void*) 0xA0000, 32000); + DLs.buf = sys_vpm_map(SYS_MAP_VIRT_ANY, SYS_MAP_PHYS_ANY, 4096); + Images.handles = sys_vpm_map(SYS_MAP_VIRT_ANY, SYS_MAP_PHYS_ANY, 4096); + + q_init(); + + uint32_t canalID = sys_canal_create('LUMA', 'VID\0'); + + uint8_t *buf = (void*) -1; + do { + buf = sys_canal_accept(canalID); + } while(buf == (void*) -1); + + while(1) { + uint32_t meta; + sys_signal_wait(SYS_SIGNAL_WAIT_ANY, &meta); + memory_barrier(); + + if(meta == 0xFFFFFFFF) { + void *f = sys_vpm_map(SYS_MAP_VIRT_ANY, SYS_MAP_PHYS_ANY, 4096); + compileCommandList(buf, f); + q_reassign(); + ((void(*)()) f)(); + sys_vpm_unmap(f, 4096); + } + + memory_barrier(); + sys_signal_send(buf, 1); + } +} diff --git a/luma/wm/Makefile b/luma/wm/Makefile new file mode 100644 index 0000000..473225c --- /dev/null +++ b/luma/wm/Makefile @@ -0,0 +1,13 @@ +rwildcard=$(foreach d,$(wildcard $(1:=/*)),$(call rwildcard,$d,$2) $(filter $(subst *,%,$2),$d)) + +HEADERS := $(call rwildcard,.,*.h) +SOURCEC := $(call rwildcard,.,*.c) +OBJECTS := $(patsubst %.c, ../../build/wm/%.o, $(SOURCEC)) + +mod: $(OBJECTS) + i386-elf-ld -pie -T ../../mod.ld -no-dynamic-linker -nostdlib -o main.elf $(OBJECTS) -L./ -lz + ../../elftomod.py main.elf ../../bootfs/luma_wm.mod modentry:0 + +../../build/wm/%.o: %.c + mkdir -p $(@D) + i386-elf-gcc -march=i386 -Isrc -Os -pie -nodefaultlibs -nostdlib -nostartfiles -DEEBIE_MEMSET=__builtin_memset -fms-extensions -fomit-frame-pointer -c -o $@ -ffreestanding -mgeneral-regs-only -std=gnu11 -Wall $< diff --git a/luma/wm/api.h b/luma/wm/api.h new file mode 100644 index 0000000..ba17979 --- /dev/null +++ b/luma/wm/api.h @@ -0,0 +1,49 @@ +#pragma once + +#include +#include + +typedef uint32_t LumaWMObjID; +typedef uint16_t LumaWMObjKind; +typedef uint32_t LumaWMObjProperty; + +#define LUMA_WM_KIND_CONTAINER 1 +#define LUMA_WM_KIND_LABEL 2 + +#define LUMA_WM_PROP_TEXT 1 +#define LUMA_WM_PROP_CONTAINER_ORDER 2 + +typedef struct { + void *area; +} LumaWMClient; + +typedef struct { + uint16_t cmd; + uint16_t sz; +} LumaWMCmdHeader; + +typedef struct __attribute__((packed)) { + LumaWMObjID id; + LumaWMObjKind kind; +} LumaWMObjDesc; + +typedef struct __attribute__((packed)) { + LumaWMCmdHeader header; + + LumaWMObjDesc descs[]; +} LumaWMRegisterObjects; + +typedef struct __attribute__((packed)) { + LumaWMCmdHeader header; + + LumaWMObjID object; + + LumaWMObjProperty property; + + uint8_t data[]; +} LumaWMSetProperty; + +int luma_wm_client(LumaWMClient*); +int luma_wm_window_create(LumaWMClient*); +int luma_wm_register_objects(LumaWMClient*, LumaWMObjDesc*, size_t count); +int luma_wm_set_property(LumaWMClient*, LumaWMObjID object, LumaWMObjProperty prop, void *data, size_t length); diff --git a/luma/wm/chars/trans.py b/luma/wm/chars/trans.py new file mode 100755 index 0000000..33ae907 --- /dev/null +++ b/luma/wm/chars/trans.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python3 + +import PIL.Image, struct, bitstring, xml.etree.ElementTree + +o = open("../chars.bin", "wb") + +xml = xml.etree.ElementTree.parse("l.fnt") +img = PIL.Image.open("l_0.tga") + +for ch in xml.getroot().find("chars").findall("char"): + assert int(ch.attrib["width"]) < 16 or int(ch.attrib["height"]) < 16, "Image too big: " + ch.attrib["id"] + o.write(struct.pack("BBB", + int(ch.attrib["id"]), + (int(ch.attrib["width"]) << 4) | int(ch.attrib["height"]), + (int(ch.attrib["yoffset"]) << 4) | int(ch.attrib["xadvance"]) + )) + a = [] + for y in range(0, int(ch.attrib["height"])): + for x in range(0, int(ch.attrib["width"])): + a += [img.getpixel((int(ch.attrib["x"]) + x, int(ch.attrib["y"]) + y)) // 255] + a = [a[i * 8 : (i + 1) * 8] for i in range((len(a) + 7) // 8)] + while len(a[-1]) < 8: + a[-1] += [0] + for l in a: l.reverse() + a = sum(a, []) + bitstring.BitArray(a).tofile(o) + +o.close() \ No newline at end of file diff --git a/luma/wm/eebie/ebml.h b/luma/wm/eebie/ebml.h new file mode 100644 index 0000000..5b764e1 --- /dev/null +++ b/luma/wm/eebie/ebml.h @@ -0,0 +1,28 @@ +#ifndef EEBIE_H +#define EEBIE_H + +#include + +typedef enum EBMLElementType { + EBML_SIGNED_INTEGER, + EBML_UNSIGNED_INTEGER, + EBML_FLOAT4, + EBML_FLOAT8, + EBML_STRING, + EBML_UTF8, + EBML_DATE, + EBML_TREE, + EBML_BINARY, +} EBMLElementType; + +typedef union EBMLPrimitive { + int64_t sInt; + uint64_t uInt; + float flt4; + double flt8; + const char *string; + const uint8_t *binary; + uint64_t date; +} EBMLPrimitive; + +#endif diff --git a/luma/wm/eebie/reader.c b/luma/wm/eebie/reader.c new file mode 100644 index 0000000..a2148b7 --- /dev/null +++ b/luma/wm/eebie/reader.c @@ -0,0 +1,203 @@ +#include +#include + +#include"ebml.h" + +#include"reader.h" + +void ebml_reader_init(EBMLReader *this) { + EEBIE_MEMSET(this, 0, sizeof(*this)); + this->state = EBMLRS_WAITING_FOR_ELEMENT_ID; + this->currentDepth = 0; +} + +static uint64_t VARINT_MASKS[] = {0, 0x80L, 0xC000L, 0xE00000L, 0xF0000000L, 0xF800000000L, 0xFC0000000000L, 0xFE000000000000L, 0L}; + +#include"../../std.h" +static inline void pr(int c) { + asm volatile("outb %%al, $0xE9" :: "a"(c) :); +} + +static inline void pri(size_t num) { + char buf[25] = {}; + int i = 16; + + do { + buf[--i] = num % 10; + num /= 10; + } while(num); + + for(; i < 16; i++) { + pr(buf[i] + '0'); + } +} + +static inline void prs(const Str16 *str) { + for(int i = 0; i < str->len; i++) { + pr(str->data[i]); + } +} + +static inline void prcs(const char *str) { + while(*str) { + pr(*str); + str++; + } +} + +#define I(x) ((uint64_t)(x)) +static int read_varint(const uint8_t *data, size_t length, uint64_t *result) { + if(data[0] & 0x80) { + *result = data[0]; + + return 1; + } else if(data[0] & 0xC0) { + if(length < 2) { + return 0; + } + + *result = (I(data[0]) << 8) | data[1]; + + return 2; + } else if(data[0] & 0xE0) { + if(length < 3) { + return 0; + } + + *result = (I(data[0]) << 16) | (I(data[1]) << 8) | data[2]; + + return 3; + } else if(data[0] & 0xF0) { + if(length < 4) { + return 0; + } + + *result = (I(data[0]) << 24) | (I(data[1]) << 16) | (I(data[2]) << 8) | data[3]; + + return 4; + } else if(data[0] & 0xF8) { + if(length < 5) { + return 0; + } + + *result = (I(data[0]) << 32) | (I(data[1]) << 24) | (I(data[2]) << 16) | (I(data[3]) << 8) | data[4]; + + return 5; + } else if(data[0] & 0xFC) { + if(length < 6) { + return 0; + } + + *result = (I(data[0]) << 40) | (I(data[1]) << 32) | (I(data[2]) << 24) | (I(data[3]) << 16) | (I(data[4]) << 8) | data[5]; + + return 6; + } else if(data[0] & 0xFE) { + if(length < 7) { + return 0; + } + + *result = (I(data[0]) << 48) | (I(data[1]) << 40) | (I(data[2]) << 32) | (I(data[3]) << 24) | (I(data[4]) << 16) | (I(data[5]) << 8) | data[6]; + + return 7; + } else if(data[0] == 0x01) { + if(length < 8) { + return 0; + } + + *result = (I(data[1]) << 48) | (I(data[2]) << 40) | (I(data[3]) << 32) | (I(data[4]) << 24) | (I(data[5]) << 16) | (I(data[6]) << 8) | data[7]; + + return 8; + } + + return -1; +} + +static int get_varint(const uint8_t *data, size_t length, uint64_t *result) { + int ret = read_varint(data, length, result); + + if(ret >= 0) { + *result &= ~VARINT_MASKS[ret]; + } + + return ret; +} + +int ebml_reader_feed(EBMLReader *this, const uint8_t *data, size_t length) { + if(length == 0) { + return 0; + } + + size_t eaten = -1; + + if(this->state == EBMLRS_WAITING_FOR_ELEMENT_ID) { + + uint64_t elId; + + int status = read_varint(data, length, &elId); + + if(status <= 0) { + return status; + } + + this->state = EBMLRS_WAITING_FOR_ELEMENT_LENGTH; + this->inside.id = elId; + + eaten = status; + + } else if(this->state == EBMLRS_WAITING_FOR_ELEMENT_LENGTH) { + + uint64_t elLength; + + int status = get_varint(data, length, &elLength); + + if(status <= 0) { + return status; + } + + this->inside.type = this->eventEnterElement(this, this->inside.id, elLength); + + if(this->inside.type == EBML_TREE) { + this->state = EBMLRS_WAITING_FOR_ELEMENT_ID; + } else { + this->state = EBMLRS_WAITING_FOR_ELEMENT_DATA; + + this->inside.length = elLength; + } + + this->idStack[this->currentDepth] = this->inside.id; + this->stack[this->currentDepth] = elLength + status; + + this->currentDepth++; + + eaten = status; + + } else if(this->state == EBMLRS_WAITING_FOR_ELEMENT_DATA) { + + size_t realLen = this->stack[this->currentDepth - 1] < length ? this->stack[this->currentDepth - 1] : length; + + if(this->eventDataChunk) { + this->eventDataChunk(this, data, realLen); + } + + eaten = realLen; + + } + + for(int i = 0; i < this->currentDepth; i++) { + this->stack[i] -= eaten; + } + + while(this->currentDepth > 0 && this->stack[this->currentDepth - 1] == 0) { + + if(this->eventExitElement) { + this->eventExitElement(this); + } + + this->currentDepth--; + + this->state = EBMLRS_WAITING_FOR_ELEMENT_ID; + + } + + return eaten; +} diff --git a/luma/wm/eebie/reader.h b/luma/wm/eebie/reader.h new file mode 100644 index 0000000..51b8474 --- /dev/null +++ b/luma/wm/eebie/reader.h @@ -0,0 +1,48 @@ +#ifndef EEBIE_READER_H +#define EEBIE_READER_H + +#define EBML_READ_MAXIMUM_DEPTH 128 + +#include"ebml.h" + +#include +#include + +enum EBMLReaderState { + EBMLRS_WAITING_FOR_ELEMENT_ID, + EBMLRS_WAITING_FOR_ELEMENT_LENGTH, + EBMLRS_WAITING_FOR_ELEMENT_DATA, +}; + +struct EBMLReader; + +typedef EBMLElementType(*EBMLEventEnterElement)(struct EBMLReader*, uint64_t id, uint64_t length); +typedef void(*EBMLEventDataChunk)(struct EBMLReader*, const uint8_t *data, size_t length); +typedef void(*EBMLEventExitElement)(struct EBMLReader*); + +typedef struct EBMLReader { + enum EBMLReaderState state; + union { + struct { + uint64_t id; + uint64_t length; + + EBMLElementType type; + } inside; + }; + + int currentDepth; + uint64_t stack[EBML_READ_MAXIMUM_DEPTH]; + uint64_t idStack[EBML_READ_MAXIMUM_DEPTH]; + + EBMLEventEnterElement eventEnterElement; + EBMLEventDataChunk eventDataChunk; + EBMLEventExitElement eventExitElement; + + void *ud; +} EBMLReader; + +void ebml_reader_init(EBMLReader *this); +int ebml_reader_feed(EBMLReader *this, const uint8_t *data, size_t length); + +#endif diff --git a/luma/wm/fileswindow.c b/luma/wm/fileswindow.c new file mode 100644 index 0000000..af25f64 --- /dev/null +++ b/luma/wm/fileswindow.c @@ -0,0 +1,219 @@ +#include"fileswindow.h" + +#include"../std.h" +#include"../sys.h" +#include"../fs/fs.h" +#include"wm.h" +#include"tiny.h" + +#define dynstr16_ends_with(ds16, cstr) (((ds16)->len < sizeof(cstr) - 1) ? 0 : !std_bytecomp(sizeof(cstr) - 1, (cstr), (ds16)->data + (ds16)->len - sizeof(cstr) + 1)) + +struct Ctx { + Str16 *cd; + size_t cdSize; +} ; + +void __attribute__((naked)) audio_thread() { + asm( + "movl %eax, %ebp\n" + "movl $0, %eax\n" + "movl $-1, %edi\n" + "movl $-1, %esi\n" + "movl $4096, %edx\n" + "int $0xEC\n" + "leal 4096(%eax), %esp\n" + "pushl %ebp\n" + "call caudio_thread\n" + ); +} +void caudio_thread(void*) { + void *FSLink = sys_link_create('FS\0\0', 'ROOT', 4096); + + LumaFSCommand *cmd = FSLink; + cmd->op = LUMA_FS_COMMAND_READ; + cmd->read.offset = 44; + cmd->read.bytes = 1024 * 1024; + Str16 *path = (Str16*) cmd->read.path; + std_copy(path->data, "duane.wav", path->len = 9); + WALK_STR16(path)->len = 0; //terminator + + uint8_t *wavebuffer = sys_vpm_map(SYS_MAP_VIRT_ANY, SYS_MAP_PHYS_ANY, 1024 * 1024); + size_t wavebufferoffset = 0; + while(1) { + memory_barrier(); + sys_signal_send(FSLink, 1); + + uint32_t dasize; + sys_signal_wait(FSLink, &dasize); + + std_copy(wavebuffer + wavebufferoffset, FSLink, dasize); + wavebufferoffset += dasize; + + if(dasize != 4096) break; + } + + wavebufferoffset = 0; + + uint8_t *AudLink = sys_link_create('AUD\0', 'HDA0', 8192); + + while(1) { + if(wavebufferoffset == 1024 * 1024) wavebufferoffset = 0; + + sys_signal_wait(AudLink, NULL); + std_copy(AudLink, wavebuffer + wavebufferoffset, 8192); + wavebufferoffset += 8192; + sys_signal_send(AudLink, 0); + } +} + +static void update_listing(struct GWindow *w) { + struct Ctx *ctx = w->ud; + + struct GList *list = (struct GList*) w->child; + + glist_clear(list); + + LumaFSCommand *cmd = FSLink; + cmd->op = LUMA_FS_COMMAND_TRAVERSE; + + std_copy(cmd->traverse.path, ctx->cd, ctx->cdSize); + + sys_signal_send(FSLink, 0); + sys_signal_wait(FSLink, NULL); + + for(LumaFSDirectoryEntry *e = FSLink;; e = (LumaFSDirectoryEntry*) ((uintptr_t) e + sizeof(*e) + e->name.len)) { + glist_add(list, g_dynstr16_new(e->name.len, e->name.len, e->name.data), (void*) (uintptr_t) e->type); + + if(e->type & LUMA_FS_DIR_ENTRY_LAST) { + break; + } + } +} + +static int files_window_view_cmd(void *ud, const DynStr16 *cmdline) { + if(!is_free_space()) return 0; + + struct GWindow *w = ud; + + struct GList *list = (struct GList*) w->child; + + struct Ctx *ctx = w->ud; + + if(list->cursor >= list->childCount) return 0; + + if(((uintptr_t) (list->children[list->cursor].ud)) & LUMA_FS_DIR_ENTRY_ISDIR) { + Str16 *newud = tiny_realloc(ctx->cd, ctx->cdSize + sizeof(*newud) + list->children[list->cursor].text->len); + + if(newud) { + ctx->cd = newud; + + Str16 *end = (void*) ((uintptr_t) ctx->cd + ctx->cdSize - sizeof(*end)); + + end->len = list->children[list->cursor].text->len; + std_copy(end->data, list->children[list->cursor].text->data, end->len); + + // Terminator. + WALK_STR16(end)->len = 0; + + ctx->cdSize += sizeof(*newud) + list->children[list->cursor].text->len; + + update_listing(w); + } else { + // TODO: log + } + } else if(dynstr16_ends_with(list->children[list->cursor].text, ".txt")) { + size_t amount = 100; + + Str16 *newterm = DYN16_TO_ST(list->children[list->cursor].text); + + LumaFSCommand *cmd = FSLink; + cmd->op = LUMA_FS_COMMAND_READ; + cmd->read.offset = 0; + cmd->read.bytes = amount; + std_copy(cmd->read.path, ctx->cd, ctx->cdSize - sizeof(*newterm)); + std_copy(cmd->read.path + ctx->cdSize - sizeof(*newterm), newterm, sizeof(*newterm) + newterm->len); + WALK_STR16(cmd->read.path + ctx->cdSize - sizeof(*newterm))->len = 0; //terminator + + memory_barrier(); + sys_signal_send(FSLink, 0); + + uint32_t dasize; + sys_signal_wait(FSLink, &dasize); + + memory_barrier(); + + DynStr16 *str = g_dynstr16_new(512, dasize, FSLink); + + struct GText *bigtxt = gtext_new(0, 0, 0, 0, NULL, str); + + static const char name[] = "Viewer"; + struct GWindow *viewwnd = gwindow_new(0, 0, 0, 0, g_dynstr16_new(sizeof(name) - 1, sizeof(name) - 1, name), (struct GObj*) bigtxt, 0); + + add_window(viewwnd); + + return 1; + } else if(dynstr16_ends_with(list->children[list->cursor].text, ".wav")) { + static const char name[] = "Audio Player"; + struct GWindow *playerwnd = gwindow_new(0, 0, 0, 0, g_dynstr16_new(sizeof(name) - 1, sizeof(name) - 1, name), NULL, 0); + + add_window(playerwnd); + + sys_create_thread(audio_thread); + + return 1; + } + + return 0; +} + +static int files_window_back_cmd(void *ud, const DynStr16 *cmdline) { + struct GWindow *w = ud; + + struct Ctx *ctx = w->ud; + + Str16 *pathPrev = NULL; + Str16 *path = ctx->cd; + + if(path->len == 0) { + return 0; + } + + while(path->len) { + pathPrev = path; + path = WALK_STR16(path); + } + + // Turn term into terminator. + ctx->cdSize -= pathPrev->len; + pathPrev->len = 0; + + update_listing(w); + + return 1; +} + +void FilesWindowCreate() { + if(!is_free_space()) return; + + struct GList *list = glist_new(0, 0, 0, 0); + + static const char name[] = "File Explorer"; + struct GWindow *w = gwindow_new(0, 0, 0, 0, g_dynstr16_new(sizeof(name) - 1, sizeof(name) - 1, name), (struct GObj*) list, 0); + + struct Ctx *ctx = tiny_malloc(sizeof(*ctx)); + + ctx->cd = tiny_malloc(ctx->cdSize = sizeof(*ctx->cd)); + ctx->cd->len = 0; // root + + w->ud = ctx; + + update_listing(w); + + static const char viewcmd[] = "open"; + gwindow_regcmd(w, g_str16_new(sizeof(viewcmd) - 1, viewcmd), w, files_window_view_cmd); + + static const char backcmd[] = "back"; + gwindow_regcmd(w, g_str16_new(sizeof(backcmd) - 1, backcmd), w, files_window_back_cmd); + + add_window(w); +} diff --git a/luma/wm/fileswindow.h b/luma/wm/fileswindow.h new file mode 100644 index 0000000..ba70fd2 --- /dev/null +++ b/luma/wm/fileswindow.h @@ -0,0 +1,3 @@ +#pragma once + +void FilesWindowCreate(); diff --git a/luma/wm/io.h b/luma/wm/io.h new file mode 100644 index 0000000..c6f9725 --- /dev/null +++ b/luma/wm/io.h @@ -0,0 +1,6 @@ +#ifndef LUMA_WM_IO_H +#define LUMA_WM_IO_H + +uint8_t *get_file_from_path(Str16 *name, size_t *len); + +#endif diff --git a/luma/wm/logotrans.py b/luma/wm/logotrans.py new file mode 100755 index 0000000..0b14df5 --- /dev/null +++ b/luma/wm/logotrans.py @@ -0,0 +1,14 @@ +#!/usr/bin/env python3 + +import PIL +import PIL.Image +import bitstring, os + +for +i = PIL.Image.open("logo.png") + +o = bitstring.BitArray() +for y in range(0, i.height): + for x in range(0, i.width): + o += [i.getpixel((x // 8 * 8 + 7 - x % 8, y))] +o.tofile(open("logo.bin", "wb")) \ No newline at end of file diff --git a/luma/wm/logserver.c b/luma/wm/logserver.c new file mode 100644 index 0000000..64d8553 --- /dev/null +++ b/luma/wm/logserver.c @@ -0,0 +1,27 @@ +#include"logserver.h" + +#include"../sys.h" + +DynStr16 *the; + +void log_init() { + the = sys_vpm_map(SYS_MAP_VIRT_ANY, SYS_MAP_PHYS_ANY, 4096); + the->len = 0; + the->cap = 4096 - sizeof(*the); +} + +void log_update(Str16 *next) { + if(the->len + next->len > the->cap) { + size_t fit = the->len + next->len - the->cap; + std_move(the->data, the->data + fit, the->len - fit); + the->len -= fit; + } + + std_copy(the->data + the->len, next->data, next->len); + + the->len += next->len; +} + +DynStr16 *log_get() { + return the; +} diff --git a/luma/wm/logserver.h b/luma/wm/logserver.h new file mode 100644 index 0000000..96a81be --- /dev/null +++ b/luma/wm/logserver.h @@ -0,0 +1,7 @@ +#pragma once + +#include"../std.h" + +void log_init(); +void log_update(Str16*); +DynStr16 *log_get(); diff --git a/luma/wm/main.c b/luma/wm/main.c new file mode 100644 index 0000000..b311cb4 --- /dev/null +++ b/luma/wm/main.c @@ -0,0 +1,978 @@ +#include +#include +#include"../sys.h" +#include"../std.h" +#include"../vid/api.h" +#include"../ps2/api.h" +#include"ui.h" +#include"perform.h" +#include"wm.h" +#include"../fs/fs.h" +#include"zlib.h" +#include"logserver.h" +#include"progdb.h" +#include"io.h" + +asm("modentry:\n" +"mov $stack + 2048, %esp\n" +"call startc"); + +#include"tiny.h" + +char stack[2048]; + +void *VidLink; +void *FSLink; + +static inline void pr(int c) { + asm volatile("outb %%al, $0xE9" :: "a"(c) :); +} + +static inline void pri(size_t num) { + char buf[16] = {}; + int i = 16; + + do { + buf[--i] = num % 10; + num /= 10; + } while(num); + + for(; i < 16; i++) { + pr(buf[i] + '0'); + } +} + +static inline void prs(const Str16 *str) { + for(int i = 0; i < str->len; i++) { + pr(str->data[i]); + } +} + +static inline void prcs(const char *str) { + while(*str) { + pr(*str); + str++; + } +} + +void initvid(int col) { + static uint8_t logo[] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0x07, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, + 0x07, 0x00, 0xf0, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0xe0, 0x1f, 0x00, 0xf8, 0x1f, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x1c, 0x00, 0x00, 0xf0, 0x1f, 0x00, 0xf8, 0x3f, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0xf8, + 0x3c, 0x00, 0x78, 0x3e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x78, 0x38, 0x00, 0x78, 0x7c, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x38, 0x00, 0x00, 0x3c, 0x78, 0x00, 0x7c, 0x78, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x00, 0x00, 0x1c, + 0x78, 0x00, 0x7c, 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x70, 0x00, 0x00, 0x1c, 0x78, 0x00, 0x7c, 0x7c, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xf0, 0x00, 0x00, 0x0e, 0x70, 0x00, 0x7c, 0x3c, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x00, 0x00, 0x0e, + 0x70, 0x00, 0x78, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0xe0, 0x01, 0x00, 0x0c, 0x70, 0x00, 0x78, 0x3c, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xe0, 0x01, 0x00, 0x1c, 0x78, 0x00, 0x78, 0x1e, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x03, 0x00, 0x1c, + 0x78, 0x00, 0x78, 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0xc0, 0x03, 0x00, 0x1c, 0x3c, 0x00, 0x78, 0x1f, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xc0, 0x03, 0x00, 0x38, 0x3e, 0x00, 0xf8, 0x0f, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x07, 0x00, 0x38, + 0x1e, 0x00, 0xf8, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x80, 0x07, 0x00, 0x38, 0x0f, 0x00, 0xf0, 0x07, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x80, 0x07, 0x00, 0xb0, 0x0f, 0x00, 0xf0, 0x07, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x00, 0xf0, + 0x07, 0x00, 0xf0, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x00, 0xf0, 0x03, 0x00, 0xf0, 0x03, + 0x00, 0xe0, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x0f, 0x00, 0xf0, 0x03, 0x00, 0xf0, 0x01, 0x00, 0xe0, 0x01, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x00, 0xf0, + 0x01, 0x00, 0xf0, 0x01, 0x00, 0xe0, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x1e, 0x00, 0xf0, 0x00, 0x00, 0xf0, 0x01, + 0x00, 0xe0, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x1e, 0x00, 0xf8, 0x00, 0x00, 0xf8, 0x01, 0x00, 0xe0, 0x01, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1e, 0x00, 0xfc, + 0x00, 0x00, 0xfc, 0x01, 0x00, 0xe0, 0x01, 0x00, 0x1c, 0x80, 0x83, 0x71, + 0x78, 0x00, 0xfc, 0x01, 0x00, 0x1e, 0x00, 0xfe, 0x01, 0x00, 0xfc, 0x03, + 0x00, 0xe0, 0x01, 0x00, 0x1c, 0x80, 0x83, 0xfd, 0xfc, 0x00, 0xff, 0x07, + 0x00, 0x3e, 0x00, 0xdf, 0x01, 0x00, 0xfe, 0x03, 0x00, 0xe0, 0x01, 0x00, + 0x1c, 0x80, 0x83, 0xc7, 0xe7, 0x81, 0x07, 0x0f, 0x00, 0x3c, 0x00, 0xcf, + 0x01, 0x00, 0xdf, 0x03, 0x00, 0xe0, 0x01, 0x00, 0x1c, 0x80, 0x83, 0xc7, + 0xc3, 0xc1, 0x03, 0x0e, 0x00, 0x3c, 0x80, 0xcf, 0x01, 0x00, 0xcf, 0x03, + 0x00, 0xe0, 0x01, 0x00, 0x1c, 0x80, 0x83, 0xc3, 0xc3, 0xc1, 0x03, 0x1c, + 0x00, 0x3c, 0xc0, 0x87, 0x03, 0x80, 0xcf, 0x03, 0x00, 0xe0, 0x01, 0x00, + 0x1c, 0x80, 0x83, 0xc3, 0xc3, 0x01, 0x00, 0x1c, 0x00, 0x3c, 0xe0, 0x83, + 0x03, 0xc0, 0x87, 0x07, 0x00, 0xe0, 0x01, 0x00, 0x1c, 0x80, 0x83, 0x83, + 0xc3, 0x01, 0x00, 0x1c, 0x00, 0x3c, 0xf0, 0x81, 0x03, 0xc0, 0x83, 0x07, + 0x00, 0xe0, 0x01, 0x00, 0x1c, 0x80, 0x83, 0x83, 0xc1, 0x01, 0xfc, 0x1f, + 0x00, 0x7c, 0xf8, 0x80, 0x03, 0xe0, 0x81, 0x07, 0x00, 0xe0, 0x01, 0x00, + 0x1c, 0x80, 0x83, 0x83, 0xc1, 0x01, 0xff, 0x1f, 0x00, 0x78, 0xf8, 0x00, + 0x03, 0xf0, 0x81, 0x07, 0x00, 0xe0, 0x01, 0x00, 0x1c, 0x80, 0x83, 0x83, + 0xc1, 0xc1, 0x07, 0x1c, 0x00, 0x78, 0x7c, 0x00, 0x07, 0xf8, 0x80, 0x07, + 0x00, 0xe0, 0x01, 0x00, 0x1c, 0x80, 0x83, 0x83, 0xc1, 0xc1, 0x03, 0x1c, + 0x00, 0x78, 0x3e, 0x00, 0x07, 0x78, 0x00, 0x07, 0x00, 0xe0, 0x01, 0x00, + 0x1c, 0x80, 0x83, 0x83, 0xc1, 0xe1, 0x01, 0x1c, 0x00, 0x78, 0x1f, 0x00, + 0x07, 0x3c, 0x00, 0x0f, 0x00, 0xe0, 0x01, 0x00, 0x1c, 0xc0, 0x83, 0x83, + 0xc1, 0xe1, 0x01, 0x1e, 0x00, 0xf8, 0x0f, 0x00, 0x06, 0x3e, 0x00, 0x0f, + 0x00, 0xe0, 0x01, 0x00, 0x3c, 0xc0, 0x83, 0x83, 0xc1, 0xe1, 0x01, 0x1e, + 0x00, 0xf8, 0x07, 0x00, 0x0e, 0x1f, 0x00, 0x0f, 0x00, 0xe0, 0x01, 0x00, + 0x3c, 0xc0, 0x83, 0x83, 0xc1, 0xe1, 0x01, 0x1f, 0x00, 0xf8, 0x03, 0x00, + 0x8e, 0x0f, 0x00, 0x0f, 0x00, 0xe0, 0x01, 0x00, 0x38, 0xe0, 0x83, 0x83, + 0xc1, 0xc1, 0x01, 0x1d, 0x00, 0xf8, 0x03, 0x00, 0xce, 0x07, 0x00, 0x0e, + 0x00, 0xe0, 0x01, 0x00, 0x78, 0xb0, 0x83, 0x83, 0xc1, 0xc1, 0xc3, 0x1d, + 0x00, 0xf8, 0x01, 0x00, 0xee, 0x03, 0x00, 0x0e, 0x00, 0xe0, 0xff, 0x1f, + 0xf0, 0x9f, 0x83, 0x83, 0xc1, 0x81, 0xff, 0xfc, 0x00, 0xf8, 0x00, 0x00, + 0xfc, 0x01, 0x00, 0x0e, 0x00, 0xe0, 0xff, 0x1f, 0xe0, 0x87, 0x83, 0x83, + 0xc1, 0x01, 0x3f, 0xf8, 0x00, 0x7c, 0x00, 0x00, 0xfc, 0x00, 0x00, 0x1e, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0xfe, 0x00, 0x00, 0x7c, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, + 0x3e, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x80, 0xff, 0x00, 0x80, 0x1f, 0x00, 0x00, 0x1c, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xc0, 0x7f, 0x00, 0xc0, 0x1f, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0x7f, 0x00, 0xf0, + 0x1f, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0xf0, 0x7b, 0x00, 0xf8, 0x19, 0x00, 0x00, 0x1c, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xf8, 0x79, 0x00, 0x7c, 0x18, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0x78, 0x00, 0x3e, + 0x38, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x7c, 0x78, 0x00, 0x0f, 0x38, 0x00, 0x00, 0x18, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x3e, 0x78, 0x00, 0x07, 0x38, 0x00, 0x00, 0x38, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1e, 0x7c, 0x80, 0x07, + 0x38, 0x00, 0x00, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x1f, 0x3c, 0x80, 0x03, 0x38, 0x00, 0x00, 0x38, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x0f, 0x3c, 0x80, 0x03, 0x38, 0x00, 0x00, 0x38, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x3e, 0x80, 0x03, + 0x18, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x0f, 0x3e, 0x80, 0x03, 0x1c, 0x00, 0x00, 0x10, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x1f, 0x1f, 0x80, 0x07, 0x1c, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x1f, 0x00, 0x0f, + 0x1e, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0xfe, 0x0f, 0x00, 0x1f, 0x0f, 0x00, 0x00, 0x10, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xfc, 0x07, 0x00, 0xfe, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x03, 0x00, 0xfc, + 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0xf0, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 + }; + + do { + VidLink = sys_link_create('LUMA', 'VID\0', 4096); + } while(VidLink == (void*) -1); + + LumaVidCommand *cmd = VidLink; + cmd->op = LUMA_VID_COMMAND_IMAGE_NEW; + cmd->imageNew.width = 160; + cmd->imageNew.height = 66; + cmd->imageNew.format = LUMA_VID_IMAGE_FORMAT_BLALPHA; + cmd->imageNew.name = 0; + cmd = (LumaVidCommand*) ((uintptr_t) cmd + sizeof(cmd->imageNew)); + cmd->op = LUMA_VID_COMMAND_IMAGE_WRITE; + cmd->imageWrite.name = 0; + cmd->imageWrite.x = 0; + cmd->imageWrite.y = 0; + cmd->imageWrite.len = sizeof(logo); + std_copy(cmd->imageWrite.data, logo, cmd->imageWrite.len); + cmd = (LumaVidCommand*) ((uintptr_t) cmd + sizeof(cmd->imageWrite) + cmd->imageWrite.len); + cmd->op = LUMA_VID_COMMAND_NEW_COLOR_GRAD; + cmd->colorGrad.r1 = 135; + cmd->colorGrad.g1 = 214; + cmd->colorGrad.b1 = 255; + cmd->colorGrad.r2 = 255; + cmd->colorGrad.g2 = 252; + cmd->colorGrad.b2 = 135; + cmd = (LumaVidCommand*) ((uintptr_t) cmd + sizeof(cmd->colorGrad)); + cmd->op = LUMA_VID_COMMAND_NEW_COLOR_FLAT; + cmd->colorFlat.r = 0x80; + cmd->colorFlat.g = 0x80; + cmd->colorFlat.b = 0x80; + cmd = (LumaVidCommand*) ((uintptr_t) cmd + sizeof(cmd->colorFlat)); + cmd->op = LUMA_VID_COMMAND_NEW_COLOR_FLAT; + cmd->colorFlat.r = 0xF0; + cmd->colorFlat.g = 0xF0; + cmd->colorFlat.b = 0xF0; + cmd = (LumaVidCommand*) ((uintptr_t) cmd + sizeof(cmd->colorFlat)); + cmd->op = LUMA_VID_COMMAND_NEW_COLOR_FLAT; + cmd->colorFlat.r = 0x00; + cmd->colorFlat.g = 0x00; + cmd->colorFlat.b = 0x00; + cmd = (LumaVidCommand*) ((uintptr_t) cmd + sizeof(cmd->colorFlat)); + cmd->op = LUMA_VID_COMMAND_NEW_COLOR_FLAT; + cmd->colorFlat.r = 0x85; + cmd->colorFlat.g = 0x98; + cmd->colorFlat.b = 0x17; + cmd = (LumaVidCommand*) ((uintptr_t) cmd + sizeof(cmd->colorFlat)); + cmd->op = LUMA_VID_COMMAND_END; + + memory_barrier(); + sys_signal_send(VidLink, -1); + sys_signal_wait(VidLink, NULL); + + cmd = VidLink; + cmd->op = LUMA_VID_COMMAND_SET_COLOR_GRAD; + cmd->colorGrad.r1 = 135; + cmd->colorGrad.g1 = 214; + cmd->colorGrad.b1 = 255; + cmd->colorGrad.r2 = 255; + cmd->colorGrad.g2 = 252; + cmd->colorGrad.b2 = 135; + cmd = (LumaVidCommand*) ((uintptr_t) cmd + sizeof(cmd->colorGrad)); + cmd->op = LUMA_VID_COMMAND_CLEAR; + cmd = (LumaVidCommand*) ((uintptr_t) cmd + sizeof(cmd->clear)); + cmd->op = LUMA_VID_COMMAND_IMAGE; + cmd->image.name = 0; + cmd->image.x = 80; + cmd->image.y = 80; + cmd->image.width = 160; + cmd->image.height = 66; + cmd->image.subX = cmd->image.subY = 0; + cmd = (LumaVidCommand*) ((uintptr_t) cmd + sizeof(cmd->image)); + cmd->op = LUMA_VID_COMMAND_SET_COLOR_FLAT; + cmd->colorFlat.r = 0xF0; + cmd->colorFlat.g = 0xF0; + cmd->colorFlat.b = 0xF0; + cmd = (LumaVidCommand*) ((uintptr_t) cmd + sizeof(cmd->colorFlat)); + cmd->op = LUMA_VID_COMMAND_TEXT; + static const char a[] = "Press any key to continue..."; + std_copy(cmd->text.data, a, cmd->text.len = sizeof(a) - 1); + cmd->text.x = 0; + cmd->text.y = 0; + cmd->text.wall = 0; + cmd = (LumaVidCommand*) ((uintptr_t) cmd + sizeof(cmd->text) + cmd->text.len); + cmd->op = LUMA_VID_COMMAND_END; + + memory_barrier(); + sys_signal_send(VidLink, -1); + sys_signal_wait(VidLink, NULL); +} + +void drawdesk(int x, int y, int w, int h) { + LumaVidCommand *cmd = VidLink; + cmd->op = LUMA_VID_COMMAND_IMAGE; + cmd->image.name = 1; + cmd->image.y = cmd->image.subY = y; + cmd->image.x = cmd->image.subX = x; + cmd->image.height = h; + cmd->image.width = w; + cmd = (LumaVidCommand*) ((uintptr_t) cmd + sizeof(cmd->image)); + cmd->op = LUMA_VID_COMMAND_END; + + memory_barrier(); + sys_signal_send(VidLink, -1); + sys_signal_wait(VidLink, NULL); +} + +struct GContainer *ui; + +struct GObj *windowTree; +struct WTreeNode *windowTreeRoot; +struct WTreeNode *windowTreeFocus; + +struct GText *cmdline; + +static void focus_next() { + if(windowTreeFocus->window) { + windowTreeFocus->window->focus = 0; + } + + if(windowTreeFocus->parent) { + if(windowTreeFocus->parent->first == windowTreeFocus) { + windowTreeFocus = windowTreeFocus->parent->second; + } else if(windowTreeFocus->parent->second == windowTreeFocus) { + if(windowTreeFocus->parent->parent) { + windowTreeFocus = windowTreeFocus->parent->parent->second; + } else { + windowTreeFocus = windowTreeRoot; + } + while(!windowTreeFocus->window) { + windowTreeFocus = windowTreeFocus->first; + } + } + } + + if(windowTreeFocus->window) { + windowTreeFocus->window->focus = 1; + } +} + +static KeyReactFunc baseinputonkey; +static void inputonkey(struct GObj *_, struct GKeyEvent ev) { + if(ev.scancode == LK_ENTER) { + struct GText *t = (void*) _; + + perform(t->data); + + t->data->len = 0; + + cmdline->focus ^= 1; + windowTree->focus ^= 1; + + dirty_obj(_); + } else { + baseinputonkey(_, ev); + } +} + +static void wtree_render_recur(struct WTreeNode *node) { + if(node->window) { + if(node->window->onRender) { + node->window->onRender((struct GObj*) node->window); + } + } else { + if(node->first) wtree_render_recur(node->first); + if(node->second) wtree_render_recur(node->second); + } +} +static void wtree_render(struct GObj *this) { + wtree_render_recur(windowTreeRoot); +} +static void wtree_key(struct GObj *this, struct GKeyEvent ev) { + if(this->focus == 0) return; + + if(windowTreeFocus && windowTreeFocus->window && windowTreeFocus->window->onKey) { + windowTreeFocus->window->onKey((struct GObj*) windowTreeFocus->window, ev); + } +} +static void wtree_fitter_recur(struct WTreeNode *node, uint16_t x, uint16_t y, uint16_t w, uint16_t h) { + if(node->window) { + node->window->x = x; + node->window->y = y; + node->window->w = w; + node->window->h = h; + node->window->fitter((struct GObj*) node->window); + } else { + if(node->vertical) { + if(node->first) { + wtree_fitter_recur(node->first, x, y, w, h / 2); + } + if(node->second) { + wtree_fitter_recur(node->second, x, y + h / 2, w, h / 2); + } + } else { + if(node->first) { + wtree_fitter_recur(node->first, x, y, w / 2, h); + } + if(node->second) { + wtree_fitter_recur(node->second, x + w / 2, y, w / 2, h); + } + } + } +} +static void wtree_fitter(struct GObj *_) { + wtree_fitter_recur(windowTreeRoot, windowTree->x, windowTree->y, windowTree->w, windowTree->h); +} +static void wtree_destroy_recur(struct WTreeNode *node) { + if(node->window) node->window->destroy((struct GObj*) node->window); + else { + if(node->first) wtree_destroy_recur(node->first); + if(node->second) wtree_destroy_recur(node->second); + } +} +static void wtree_destroy(struct GObj *_) { + wtree_destroy_recur(windowTreeRoot); + tiny_free(_); +} +static void init_ui() { + // Contains window tree and command bar + ui = gcont_new(0, 0, 320, 240, NULL); + + // Contains windows + windowTree = tiny_calloc(sizeof(*windowTree), 1); + windowTree->onRender = wtree_render; + windowTree->onKey = wtree_key; + windowTree->destroy = wtree_destroy; + windowTree->fitter = wtree_fitter; + windowTree->x = windowTree->y = 0; + windowTree->w = 320; + windowTree->h = 226; + windowTree->focus = 0; + + windowTreeRoot = tiny_calloc(sizeof(*windowTreeRoot), 1); + windowTreeRoot->vertical = 0; + windowTreeRoot->window = NULL; + windowTreeRoot->parent = NULL; + windowTreeRoot->first = NULL; + windowTreeRoot->second = NULL; + windowTreeFocus = windowTreeRoot; + + gcont_add(ui, 0, (struct GObj*) windowTree); + + static const char asdf[] = "Enter command, e.g. help"; + cmdline = gtext_new(0, 226, 320, 14, g_dynstr16_new(sizeof(asdf) - 1, sizeof(asdf) - 1, asdf), NULL); + baseinputonkey = cmdline->onKey; + cmdline->onKey = inputonkey; + cmdline->focus = 1; + + gcont_add(ui, 0, (struct GObj*) cmdline); + + ui->focus = 1; +} + +int add_window(struct GWindow *w) { + if(!windowTreeFocus) { + return 0; + } + + if(windowTreeFocus && windowTreeFocus->window) { + windowTreeFocus->window->focus = 0; + } + + if(!windowTreeFocus->window) { + windowTreeFocus->window = w; + } else { + struct WTreeNode *top = tiny_calloc(sizeof(*top), 1); + struct WTreeNode *second = tiny_calloc(sizeof(*second), 1); + + top->vertical = windowTreeFocus->parent ? !windowTreeFocus->parent->vertical : 0; + top->window = NULL; + top->parent = windowTreeFocus->parent; + top->first = windowTreeFocus; + top->second = second; + + second->window = w; + second->parent = top; + + windowTreeFocus->parent = top; + + if(top->parent) { + if(top->parent->first == windowTreeFocus) { + top->parent->first = top; + } else if(top->parent->second == windowTreeFocus) { + top->parent->second = top; + } else { + // wtf + } + } else { + windowTreeRoot = top; + } + + windowTreeFocus = second; + } + + windowTreeFocus->window->focus = 1; + + windowTree->fitter(windowTree); + + return 1; +} +int is_free_space() { + return 1; +} + +static void destroy_window() { + if(!windowTreeFocus) return; + + if(windowTreeFocus->window) { + windowTreeFocus->window->focus = 0; + + windowTreeFocus->window->destroy((struct GObj*) windowTreeFocus->window); + windowTreeFocus->window = NULL; + if(windowTreeFocus->parent) { + struct WTreeNode *parent = windowTreeFocus->parent; + + struct WTreeNode *other = NULL; + if(parent->first == windowTreeFocus) { + other = parent->second; + } else if(parent->second == windowTreeFocus) { + other = parent->first; + } + + other->parent = parent->parent; + + std_copy(parent, other, sizeof(struct WTreeNode)); + + tiny_free(windowTreeFocus); + + windowTreeFocus = parent; + } + } + + if(windowTreeFocus->window) { + windowTreeFocus->window->focus = 1; + } + + windowTree->fitter(windowTree); +} + +// Next lexicographical permutation of windows +static void permute() { + // TODO. +} + +static size_t path_size(Str16 *p) { + size_t ret = 0; + + while(p->len) { + ret += sizeof(*p) + p->len; + p = WALK_STR16(p); + } + + ret += sizeof(*p) + p->len; + + return ret; +} + +uint8_t *get_file_from_path(Str16 *path, size_t *filelen) { + LumaFSCommand *fscmd = FSLink; + + fscmd->op = LUMA_FS_COMMAND_INFO; + std_copy(fscmd->info.path, path, path_size(path)); + + memory_barrier(); + sys_signal_send(FSLink, 1); + sys_signal_wait(FSLink, NULL); + + prcs("Getting "); + prs(path); + pr('\n'); + + size_t fileSize = fscmd->info.fileSize; + uint8_t *ret = sys_vpm_map(SYS_MAP_VIRT_ANY, SYS_MAP_PHYS_ANY, (fileSize + 4095) & ~4095); + + prcs("Size: "); + pri(fileSize); + pr('\n'); + + *filelen = fileSize; + + fscmd->op = LUMA_FS_COMMAND_READ; + fscmd->read.offset = 0; + fscmd->read.bytes = fileSize; + std_copy(fscmd->read.path, path, path_size(path)); + + for(size_t i = 0; i < fileSize; i += 4096) { + memory_barrier(); + sys_signal_send(FSLink, 1); + + uint32_t meta; + sys_signal_wait(FSLink, &meta); + + std_copy(ret + i, FSLink, meta); + + if(meta != 4096) break; + } + + return ret; +} + +static void *thezalloc(void *_, unsigned int items, unsigned int size) { + return tiny_calloc(items, size); +} +static void thezfree(void *_, void *addr) { + tiny_free(addr); +} +int load_wallpaper() { + Str16 *path = __builtin_alloca(sizeof(*path) + 9 + sizeof(*path)); + std_copy(path->data, "Wallpaper", 9); + path->len = 9; + WALK_STR16(path)->len = 0; // Terminator. + + size_t pngsize; + uint8_t *png = get_file_from_path(path, &pngsize); + + if(png[0] != 0x89 || png[1] != 'P' || png[2] != 'N' || png[3] != 'G') { + return 0; + } + + png += 8; + + uint32_t width = 0, height = 0; + + uint8_t *palette = NULL; + + z_stream zstrm; + zstrm.zalloc = thezalloc; + zstrm.zfree = thezfree; + zstrm.opaque = NULL; + zstrm.avail_in = 0; + zstrm.next_in = NULL; + if(inflateInit(&zstrm) != Z_OK) { + return 0; + } + + uint8_t *rawimg = NULL; + + while(1) { + uint32_t length = BIG_TO_HOST_ENDIAN32(*(uint32_t*) &png[0]); + uint8_t *type = &png[4]; + uint8_t *data = &png[8]; + + if(type[0] == 'I' && type[1] == 'H' && type[2] == 'D' && type[3] == 'R') { + if(length != 13) return 0; + + uint8_t depth = data[8]; + uint8_t color = data[9]; + uint8_t interlace = data[12]; + + if(depth != 8) return 0; + if(color != 3) return 0; // Must be palette + if(interlace != 0) return 0; + + width = BIG_TO_HOST_ENDIAN32(*(uint32_t*) &data[0]); + height = BIG_TO_HOST_ENDIAN32(*(uint32_t*) &data[4]); + + rawimg = tiny_malloc((width + 1) * height); // +1 because of filter byte in each row + + zstrm.avail_out = (width + 1) * height; + zstrm.next_out = rawimg; + + LumaVidCommand *cmd = VidLink; + cmd->op = LUMA_VID_COMMAND_IMAGE_NEW; + cmd->imageNew.name = 1; + cmd->imageNew.width = width; + cmd->imageNew.height = height; + cmd->imageNew.format = LUMA_VID_IMAGE_FORMAT_R8G8B8; + cmd = (LumaVidCommand*) ((uintptr_t) cmd + sizeof(cmd->imageNew)); + cmd->op = LUMA_VID_COMMAND_END; + + sys_signal_send(VidLink, -1); + sys_signal_wait(VidLink, NULL); + } else if(type[0] == 'P' && type[1] == 'L' && type[2] == 'T' && type[3] == 'E') { + if(length % 3 != 0) return 0; + + palette = data; + + LumaVidCommand *cmd = VidLink; + for(size_t i = 0; i < length; i += 3) { + cmd->op = LUMA_VID_COMMAND_NEW_COLOR_FLAT; + cmd->colorFlat.r = data[i + 0]; + cmd->colorFlat.g = data[i + 1]; + cmd->colorFlat.b = data[i + 2]; + cmd = (LumaVidCommand*) ((uintptr_t) cmd + sizeof(cmd->colorFlat)); + } + cmd->op = LUMA_VID_COMMAND_END; + + sys_signal_send(VidLink, -1); + sys_signal_wait(VidLink, NULL); + } else if(type[0] == 'I' && type[1] == 'D' && type[2] == 'A' && type[3] == 'T') { + zstrm.avail_in = length; + zstrm.next_in = data; + inflate(&zstrm, Z_NO_FLUSH); + } else if(type[0] == 'I' && type[1] == 'E' && type[2] == 'N' && type[3] == 'D') { + break; + } + + png += 8 + length + 4; + } + + inflateEnd(&zstrm); + + uint8_t *ptr = rawimg; + + for(size_t y = 0; y < height; y++) { + LumaVidCommand *cmd = VidLink; + cmd->op = LUMA_VID_COMMAND_IMAGE_WRITE; + cmd->imageWrite.y = y; + cmd->imageWrite.x = 0; + cmd->imageWrite.name = 1; + cmd->imageWrite.len = width * 3; + + uint8_t filter = *(ptr++); + + if(filter == 0) { // None + for(size_t x = 0; x < width; x++) { + uint8_t *col = &palette[3 * *ptr]; + + cmd->imageWrite.data[x * 3 + 0] = col[0]; + cmd->imageWrite.data[x * 3 + 1] = col[1]; + cmd->imageWrite.data[x * 3 + 2] = col[2]; + + ptr++; + } + } else if(filter == 1) { // Sub + for(size_t x = 0; x < width; x++) { + if(x > 0) { + ptr[0] += ptr[-1]; + } + + uint8_t *col = &palette[3 * *ptr]; + + cmd->imageWrite.data[x * 3 + 0] = col[0]; + cmd->imageWrite.data[x * 3 + 1] = col[1]; + cmd->imageWrite.data[x * 3 + 2] = col[2]; + + ptr++; + } + } else if(filter == 2) { // Up + for(size_t x = 0; x < width; x++) { + if(y > 0) { + ptr[0] += ptr[-width - 1]; + } + + uint8_t *col = &palette[3 * *ptr]; + + cmd->imageWrite.data[x * 3 + 0] = col[0]; + cmd->imageWrite.data[x * 3 + 1] = col[1]; + cmd->imageWrite.data[x * 3 + 2] = col[2]; + + ptr++; + } + } else if(filter == 3) { // Average + for(size_t x = 0; x < width; x++) { + uint16_t off = 0; + if(x > 0) { + off += ptr[-1]; + } + if(y > 0) { + off += ptr[-width - 1]; + } + *ptr += off >> 1; + + uint8_t *col = &palette[3 * *ptr]; + + cmd->imageWrite.data[x * 3 + 0] = col[0]; + cmd->imageWrite.data[x * 3 + 1] = col[1]; + cmd->imageWrite.data[x * 3 + 2] = col[2]; + + ptr++; + } + } else if(filter == 4) { // Paeth prediction + for(size_t x = 0; x < width; x++) { + // Predict + uint8_t a = x == 0 ? 0 : *(ptr - 1); // left + uint8_t b = y == 0 ? 0 : *(ptr - width - 1); // up + uint8_t c = (x == 0 || y == 0) ? 0 : *(ptr - width - 2); // up-left + + uint16_t p = a + b - c; + + // Absolute differences + uint16_t pa = p > a ? p - a : a - p; + uint16_t pb = p > b ? p - b : b - p; + uint16_t pc = p > c ? p - c : c - p; + + if(pa <= pb && pa <= pc) { + *ptr = a; + } else if(pb <= pc) { + *ptr = b; + } else { + *ptr = c; + } + + uint8_t *col = &palette[3 * *ptr]; + + cmd->imageWrite.data[x * 3 + 0] = col[0]; + cmd->imageWrite.data[x * 3 + 1] = col[1]; + cmd->imageWrite.data[x * 3 + 2] = col[2]; + + ptr++; + } + } + + sys_signal_send(VidLink, -1); + sys_signal_wait(VidLink, NULL); + } + + tiny_free(rawimg); + + return 1; +} + +struct ProgramDB ProgramDB; + +static void load_programs() { + Str16 *path = __builtin_alloca(sizeof(*path) + 8 + sizeof(*path)); + std_copy(path->data, "Programs", 8); + path->len = 8; + WALK_STR16(path)->len = 0; // Terminator. + + size_t filelen; + uint8_t *png = get_file_from_path(path, &filelen); + + uint8_t *start = png; + while(start < png + filelen) { + uint8_t *end = std_bytefind(filelen - (start - png), start, '\n'); + + size_t len = end - png; + + ProgramDB.names = tiny_realloc(ProgramDB.names, sizeof(*ProgramDB.names) * (ProgramDB.count + 1)); + + Str16 *name = tiny_malloc(sizeof(*name) + len); + name->len = len; + std_copy(name->data, png, len); + + ProgramDB.names[ProgramDB.count++] = name; + + start = end + 1; + } + + tiny_free(png); +} + +static int dirtyX1 = INT32_MAX; +static int dirtyX2 = INT32_MIN; +static int dirtyY1 = INT32_MAX; +static int dirtyY2 = INT32_MIN; +void dirty(int x1, int y1, int w, int h) { + int x2 = x1 + w; + int y2 = y1 + h; + + if(dirtyX1 > x1) { + dirtyX1 = x1; + } + + if(dirtyX2 < x2) { + dirtyX2 = x2; + } + + if(dirtyY1 > y1) { + dirtyY1 = y1; + } + + if(dirtyY2 < y2) { + dirtyY2 = y2; + } +} + +void dirty_obj(struct GObj *o) { + dirty(o->x, o->y, o->w, o->h); +} + +void startc() { + int connected = 0; + for(int try = 0; try < 50; try++) { + sys_sleep(1000); + if((FSLink = sys_link_create('FS\0\0', 'ROOT', 4096)) != (void*) -1) { + connected = 1; + break; + } + } + + #define ALLOC_AREA_SZ (128 * 1024) + tiny_init(sys_vpm_map(SYS_MAP_VIRT_ANY, SYS_MAP_PHYS_ANY, ALLOC_AREA_SZ), ALLOC_AREA_SZ); + + initvid(connected); + + if(connected == 0) { + while(1) { + sys_signal_wait(SYS_SIGNAL_WAIT_ANY, NULL); + } + } + + load_wallpaper(); + + load_programs(); + + uint32_t wmCanal = sys_canal_create('LUMA', 'WM\0\0'); + + struct LumaKbdEvent *keyBuf = NULL; + size_t keyBufIndex = 1; + int shift = 0, alt = 0, sys = 0, sysNothingElseWasPressed; + + init_ui(); + + log_init(); + + drawdesk(0, 0, 320, 240); + + ui->onRender((struct GObj*) ui); + + while(1) { + KEvent kev; + sys_event_wait(&kev); + + if(kev.type == KEV_TYPE_LINK_REQUEST && kev.canalId == wmCanal) { + void *area = sys_canal_accept(wmCanal); + + uint32_t type; + sys_signal_wait(area, &type); + + // Acknowledge + sys_signal_send(area, 0); + + if(type == 0) { + if(keyBuf) { + //sys_canal_close(wmCanal); + } else { + keyBuf = area; + keyBuf[0].flag = KEYEV_FLAG_FREE; + } + } + } else if(kev.type == KEV_TYPE_LINK_SIGNAL) { + uint32_t meta = kev.meta; + + if(kev.area == keyBuf) { + int doRedraw = 0; + + for(; keyBufIndex != meta; keyBufIndex = (keyBufIndex + 1) % KEYBUF_MAX) { + if(keyBuf[keyBufIndex].scancode) { + doRedraw = 1; + + if(alt && keyBuf[keyBufIndex].flag == KEYEV_FLAG_PRESS) { + if(keyBuf[keyBufIndex].scancode == LK_P) { + permute(); + } else if(keyBuf[keyBufIndex].scancode == LK_ESCAPE) { + destroy_window(); + } else if(keyBuf[keyBufIndex].scancode == LK_RIGHT) { + focus_next(); + } + } else { + ui->onKey((struct GObj*) ui, (struct GKeyEvent) {.scancode = keyBuf[keyBufIndex].scancode, .press = keyBuf[keyBufIndex].flag == KEYEV_FLAG_PRESS, .shift = shift, .alt = alt}); + } + + if(keyBuf[keyBufIndex].scancode == LK_LEFT_SHIFT) { + if(keyBuf[keyBufIndex].flag == KEYEV_FLAG_PRESS) { + shift |= SHIFT_LEFT; + } else { + shift &= ~SHIFT_LEFT; + } + } else if(keyBuf[keyBufIndex].scancode == LK_RIGHT_SHIFT) { + if(keyBuf[keyBufIndex].flag == KEYEV_FLAG_PRESS) { + shift |= SHIFT_RIGHT; + } else { + shift &= ~SHIFT_RIGHT; + } + } else if(keyBuf[keyBufIndex].scancode == LK_LEFT_ALT) { + if(keyBuf[keyBufIndex].flag == KEYEV_FLAG_PRESS) { + alt |= ALT_LEFT; + + sysNothingElseWasPressed = 1; + } else { + alt &= ~ALT_LEFT; + + if(sysNothingElseWasPressed) { + cmdline->focus ^= 1; + windowTree->focus ^= 1; + } + } + } else if(keyBuf[keyBufIndex].scancode == LK_LEFT_SYS) { + if(keyBuf[keyBufIndex].flag == KEYEV_FLAG_PRESS) { + sys |= SYS_LEFT; + } else { + sys &= ~SYS_LEFT; + } + } + } + + // Mark as received. + keyBuf[keyBufIndex].flag = KEYEV_FLAG_FREE; + } + + if(doRedraw) { + if(dirtyX1 < dirtyX2 && dirtyY1 < dirtyY2) { + drawdesk(dirtyX1, dirtyY1, dirtyX2 - dirtyX1, dirtyY2 - dirtyY1); + dirtyX1 = INT32_MAX; + dirtyX2 = INT32_MIN; + dirtyY1 = INT32_MAX; + dirtyY2 = INT32_MIN; + } + ui->onRender((struct GObj*) ui); + } + + memory_barrier(); + } + } + } +} diff --git a/luma/wm/perform.c b/luma/wm/perform.c new file mode 100644 index 0000000..9749340 --- /dev/null +++ b/luma/wm/perform.c @@ -0,0 +1,324 @@ +#include"perform.h" + +#include"../fs/fs.h" +#include"wm.h" +#include"../sys.h" +#include"logserver.h" +#include"progdb.h" +#include"eebie/reader.h" +#include"tiny.h" +#include"io.h" +#include"fileswindow.h" + +static inline void pr(int c) { + asm volatile("outb %%al, $0xE9" :: "a"(c) :); +} + +static inline void pri(size_t num) { + char buf[16] = {}; + int i = 16; + + do { + buf[--i] = num % 10; + num /= 10; + } while(num); + + for(; i < 16; i++) { + pr(buf[i] + '0'); + } +} + +static inline void prs(const Str16 *str) { + for(int i = 0; i < str->len; i++) { + pr(str->data[i]); + } +} + +static inline void prcs(const char *str) { + while(*str) { + pr(*str); + str++; + } +} + +__attribute__((optimize("Ofast"))) static void b2hex(uint8_t b, char *ret) { + uint8_t top = b >> 4; + uint8_t bottom = b & 0x0F; + + ret[0] = top < 0xA ? (top + '0' - 0) : (top + 'A' - 0xA); + ret[1] = bottom < 0xA ? (bottom + '0' - 0) : (bottom + 'A' - 0xA); +} + +static void show_help_window() { + if(!is_free_space()) return; + + static const char txt[] = "Luma's interface is designed around the keyboard. In fact, you are unlikely to find any use for a mouse except in niche cases.\n\nTurn to the command bar below by pressing the System (Sys) key. Start off by exploring Luma's software by entering \"list\" or your filesystem with \"files\".\n\nSys+H and Sys+V split the desktop to fit more windows. Use Sys+Escape to close windows or remove free space. Sys+P moves windows around."; + struct GLabel *l = glabel_new(0, 0, 0, 0, g_dynstr16_new(sizeof(txt) - 1, sizeof(txt) - 1, txt), 1); + + static const char name[] = "Welcome to Luma"; + struct GWindow *w = gwindow_new(0, 0, 0, 0, g_dynstr16_new(sizeof(name) - 1, sizeof(name) - 1, name), (struct GObj*) l, 0); + + add_window(w); +} + +static void show_log_window() { + if(!is_free_space()) return; + + struct GLabel *l = glabel_new(0, 0, 0, 0, log_get(), 0); + + static const char name[] = "System Logs"; + struct GWindow *w = gwindow_new(0, 0, 0, 0, g_dynstr16_new(sizeof(name) - 1, sizeof(name) - 1, name), (struct GObj*) l, 0); + + add_window(w); +} + +static void e9(const char *buf, size_t len) { + while(len--) { + asm volatile("out %%al, $0xE9" :: "a"(*buf) :); + buf++; + } +} + +static void create_process_from_file(const uint8_t *exefile, size_t exesize) { + size_t childHandle = sys_spawn(); + + EBMLReader *rdr = tiny_malloc(sizeof(*rdr)); + ebml_reader_init(rdr); + + struct Section { + uint8_t *data; + size_t dataSz; + + uint8_t *their; + + uint8_t *relocs; + size_t relocsSz; + }; + + struct Ctx { + uint8_t *buf; + size_t size; + + struct Section section[4]; + int sIdx; + + int currentSymbolIsEntry; + + int entrySection; + size_t entryOffset; + } ctx = {}; + + ctx.entrySection = -1; // i.e. no entry symbol + + rdr->ud = &ctx; + + EBMLElementType eventer(EBMLReader *rdr, uint64_t id, uint64_t length) { + struct Ctx *ctx = rdr->ud; + + ctx->buf = NULL; + ctx->size = 0; + + if(id == 0x10000000 || id == 0x6200 || id == 0xC0) { + return EBML_TREE; + } + + return EBML_BINARY; + } + void evchu(EBMLReader *rdr, const uint8_t *data, size_t length) { + struct Ctx *ctx = rdr->ud; + + ctx->buf = tiny_realloc(ctx->buf, ctx->size + length); + std_copy(ctx->buf + ctx->size, data, length); + ctx->size += length; + } + void evexit(EBMLReader *rdr) { + struct Ctx *ctx = rdr->ud; + + size_t exitingId = rdr->idStack[rdr->currentDepth - 1]; + + if(exitingId == 0x6201) { + ctx->section[ctx->sIdx].data = ctx->buf; + ctx->section[ctx->sIdx].dataSz = ctx->size; + + ctx->buf = NULL; + } else if(exitingId == 0x6202) { + ctx->section[ctx->sIdx].relocs = ctx->buf; + ctx->section[ctx->sIdx].relocsSz = ctx->size; + + ctx->buf = NULL; + } else if(exitingId == 0x6200) { + uint8_t *my = SYS_MAP_VIRT_ANY; + uint8_t *their = SYS_MAP_VIRT_ANY; + + sys_abuse_map(childHandle, &my, &their, SYS_MAP_PHYS_ANY, ctx->section[ctx->sIdx].dataSz); + + std_copy(my, ctx->section[ctx->sIdx].data, ctx->section[ctx->sIdx].dataSz); + + tiny_free(ctx->section[ctx->sIdx].data); + + ctx->section[ctx->sIdx].data = my; + ctx->section[ctx->sIdx].their = their; + + ctx->sIdx++; + } + + if(exitingId == 0xC0) { + ctx->currentSymbolIsEntry = 0; + } else if(exitingId == 0xC1) { + if(ctx->size == 12) { + if(ctx->buf[0] == 'P' && ctx->buf[1] == 'r' && ctx->buf[2] == 'o' && ctx->buf[3] == 'g' && ctx->buf[4] == 'r' && ctx->buf[5] == 'a' && ctx->buf[6] == 'm' && ctx->buf[7] == 'E' && ctx->buf[8] == 'n' && ctx->buf[9] == 't' + && ctx->buf[10] == 'r' && ctx->buf[11] == 'y') { + + ctx->currentSymbolIsEntry = 1; + } + } + } else if(exitingId == 0xC2) { + if(ctx->currentSymbolIsEntry) { + ctx->entryOffset = *(uint32_t*) &ctx->buf[0]; + ctx->entrySection = *(uint8_t*) &ctx->buf[4]; + } + } + + if(ctx->buf) { + tiny_free(ctx->buf); + } + } + + rdr->eventEnterElement = eventer; + rdr->eventDataChunk = evchu; + rdr->eventExitElement = evexit; + + uint8_t *exefilestart = exefile; + + while(1) { + int readCount = ebml_reader_feed(rdr, exefile, exesize); + + if(readCount <= 0) { + break; + } + + exefile += readCount; + exesize -= readCount; + } + + // Perform relocations + for(int s = 0; s < ctx.sIdx; s++) { + for(int r = 0; r < ctx.section[s].relocsSz / 5; r++) { + size_t offset = *(uint32_t*) &ctx.section[s].relocs[r * 5 + 0]; + int refSec = *(uint8_t*) &ctx.section[s].relocs[r * 5 + 4]; + + *(uint32_t*) &ctx.section[s].data[offset] += (uint32_t) ctx.section[refSec].their; + } + + tiny_free(ctx.section[s].relocs); + ctx.section[s].relocs = NULL; + + sys_vpm_unmap(ctx.section[s].data, ctx.section[s].dataSz); // I'm scared this will break + } + + sys_abuse_state(childHandle, SYS_STATE_X86_EIP, ctx.section[ctx.entrySection].their + ctx.entryOffset); + + sys_release(childHandle); + + tiny_free(rdr); +} + +static void attempt_program_launch(const uint8_t *str, size_t len) { + size_t p; + + for(p = 0; p < ProgramDB.count; p++) { + Str16 *name = ProgramDB.names[p]; + + uint8_t *displayname = name->data; + uint8_t *codename = std_bytefind(name->len, name->data, ';') + 1; + + size_t testlen = name->len - (codename - displayname); + if(testlen > len) { + testlen = len; + } + + if(std_bytecomp(testlen, codename, str) == 0) { + break; + } + } + + if(p == ProgramDB.count) { + return; + } + + size_t exesize; + uint8_t *exefile; + { + Str16 *name = ProgramDB.names[p]; + + uint8_t *displayname = name->data; + uint8_t *term = std_bytefind(name->len, name->data, ';'); + + Str16 *directory = __builtin_alloca(sizeof(*directory) + (term - displayname) + sizeof(*directory) + 7 + sizeof(*directory)); + std_copy(directory->data, displayname, term - displayname); + directory->len = term - displayname; + + Str16 *fn = WALK_STR16(directory); + fn->len = 7; + fn->data[0] = 'P'; + fn->data[1] = 'r'; + fn->data[2] = 'o'; + fn->data[3] = 'g'; + fn->data[4] = 'r'; + fn->data[5] = 'a'; + fn->data[6] = 'm'; + + // Terminator. + WALK_STR16(fn)->len = 0; + + exefile = get_file_from_path(directory, &exesize); + } + + create_process_from_file(exefile, exesize); + + tiny_free(exefile); + + /*size_t handle = sys_spawn(); + + uint8_t *code = sys_abuse_map(handle, SYS_MAP_VIRT_ANY, 0x40000000, SYS_MAP_PHYS_ANY, 4096); + code[0] = 0x66; + code[1] = 0x87; + code[2] = 0xDB; + code[3] = 0xEB; + code[4] = 0xFB; + + sys_abuse_state(handle, SYS_STATE_X86_EIP, 0x40000000); + + sys_release(handle);*/ +} + +void perform(DynStr16 *cmd) { + if(cmd->len == 4 && cmd->data[0] == 'h' && cmd->data[1] == 'e' && cmd->data[2] == 'l' && cmd->data[3] == 'p') { + show_help_window(); + } else if(cmd->len == 5 && cmd->data[0] == 'f' && cmd->data[1] == 'i' && cmd->data[2] == 'l' && cmd->data[3] == 'e' && cmd->data[4] == 's') { + FilesWindowCreate(); + } else if(cmd->len == 4 && cmd->data[0] == 'l' && cmd->data[1] == 'o' && cmd->data[2] == 'g' && cmd->data[3] == 's') { + show_log_window(); + } else if(cmd->len > 2 && cmd->data[0] == 'g' && cmd->data[1] == 'o' && cmd->data[2] == ' ') { + attempt_program_launch(cmd->data + 3, cmd->len - 3); + } else if(windowTreeFocus && windowTreeFocus->window) { + uint8_t *space = (uint8_t*) std_bytefind(cmd->len, (char*) cmd->data, ' '); + + size_t end = space ? space - cmd->data : cmd->len; + for(size_t i = 0; i < windowTreeFocus->window->cmds.count; i++) { + if(windowTreeFocus->window->cmds.array[i].name->len != end) { + continue; + } + + if(std_bytecomp(end, cmd->data, windowTreeFocus->window->cmds.array[i].name->data) != 0) { + continue; + } + + windowTreeFocus->window->cmds.array[i].run(windowTreeFocus->window->cmds.array[i].ud, cmd); + + break; + } + } else { + // Failed. + } +} diff --git a/luma/wm/perform.h b/luma/wm/perform.h new file mode 100644 index 0000000..3839122 --- /dev/null +++ b/luma/wm/perform.h @@ -0,0 +1,5 @@ +#pragma once + +#include"../std.h" + +void perform(DynStr16*); \ No newline at end of file diff --git a/luma/wm/progdb.h b/luma/wm/progdb.h new file mode 100644 index 0000000..b8644b2 --- /dev/null +++ b/luma/wm/progdb.h @@ -0,0 +1,8 @@ +#pragma once + +#include"../std.h" + +extern struct ProgramDB { + size_t count; + Str16 **names; +} ProgramDB; diff --git a/luma/wm/tiny.c b/luma/wm/tiny.c new file mode 100644 index 0000000..9dd972f --- /dev/null +++ b/luma/wm/tiny.c @@ -0,0 +1,367 @@ +#include "tiny.h" +#include +#include"../std.h" + +// Casts a size_t to its closest aligned size +#define ALIGN_SIZE(size) ((size + ALIGNMENT - 1) & ~(ALIGNMENT - 1)) + +// Casts an unsigned char * to its closest aligned pointer +#define ALIGN_PTR(ptr) (unsigned char *)(((uintptr_t)ptr + ALIGNMENT - 1) & ~(ALIGNMENT - 1)) + +#ifdef TINY_ALIGNMENT +// Alignment is provided manually +struct tiny_max_align{ char c; TINY_ALIGNMENT align; }; +#else +// Alignment is automatically calculated (requires max_align_t) +#define TINY_ALIGNMENT max_align_t +struct tiny_max_align{ char c; max_align_t align; }; +#endif +enum { ALIGNMENT = offsetof(struct tiny_max_align, align) }; + +#define EXPAND1(X) #X +#define EXPAND2(X) EXPAND1(X) +#define ALIGNED_TYPE EXPAND2(TINY_ALIGNMENT) + +// Defines how many blocks a size_t takes +enum { HEADER_BLOCKS = ALIGN_SIZE(sizeof(size_t)) / ALIGNMENT }; + +// Defines the upper bit of the header as a the taken flag +#define TAKEN_BIT ((size_t)-1 ^ (((size_t)-1)>>1)) + +// Defines blocks as arrays with ALIGNMENT bytes +typedef unsigned char tiny_block[ALIGNMENT]; + +#ifdef TINY_BUFFER +// Statically declares and initialises a buffer. This allows the library to be +// used before `tiny_init()` is called. + +// Defines an union padded at the end to fit alignment that can hold a size_t +union tiny_padded_size { size_t size; tiny_block padding[HEADER_BLOCKS]; }; + +// Defines an union that contains the buffer and is aligned to alignof(TINY_ALIGN) +static union tiny_aligned_buffer { + // Splits the buffer into header, content and footer + struct tiny_main_layout { + union tiny_padded_size header; + union tiny_padded_size content[TINY_BUFFER / ALIGNMENT / HEADER_BLOCKS - 2]; + union tiny_padded_size footer; + } layout; + + // Taking the address of this member allows to read the layout as an array + union tiny_padded_size buffer; + + // Aligns the buffer to the boundary defined by alignof(TINY_ALIGN) + TINY_ALIGNMENT align; +} tiny_buffer = { { + { (size_t)(TINY_BUFFER / ALIGNMENT - 2 * HEADER_BLOCKS) }, + { { 0 } }, + { (size_t)TAKEN_BIT } +} }; + +// Initialises the library with the statically allocated buffer +#define TINY_INITIAL { \ + (tiny_block *)&tiny_buffer.buffer, \ + (TINY_BUFFER / ALIGNMENT - 2 * HEADER_BLOCKS), \ + false, \ + { \ + TINY_LOAD, \ + true, \ + (TINY_BUFFER / ALIGNMENT - 2 * HEADER_BLOCKS) \ + } \ +} +#else +// Initialised the library with no allocated buffer. +#define TINY_INITIAL { NULL, 0, false, { TINY_LOAD, true, 0 } } +#endif + + +// Describes a section of the buffer that may or may not be taken +typedef struct tiny_block_section { + bool taken; // Marks if this section is currently in use by the programmer + size_t size; // Specifies how many blocks are there in this section + tiny_block *header; // The address of the section header + void *data; // The address of the section data +} tiny_block_section; + +// The main library context +static struct tiny { + tiny_block *buffer; // The buffer to operate on + size_t size; // The minimum amount of blocks available for allocation + bool out_of_memory; // Whether should the library fake an out-of-memory situation + tiny_operation last_operation; // Stores the last operation executed +} tiny = TINY_INITIAL; + +// Writes a header size and availability +static void write_header(tiny_block *header, size_t size, bool taken) { + *(size_t *)header = taken ? TAKEN_BIT | size : size; +} + +// Parses a header and returns the parsed information +static tiny_block_section read_header(tiny_block *header) { + size_t header_value = *(size_t *)header; + tiny_block_section section = { + header_value & TAKEN_BIT, + header_value & ~TAKEN_BIT, + header, + (void *)(header + HEADER_BLOCKS) + }; + return section; +} + +// Allocates some blocks of memory in the provided section. +// If the section is bigger than necessary, it may be split and a new section +// with the remaining space may be created. +static void allocate_at(tiny_block_section section, size_t block_count) { + size_t remaining_space = + section.size - block_count; + + if(remaining_space <= HEADER_BLOCKS) { + write_header(section.header, section.size, true); + } else { + write_header(section.header, block_count, true); + write_header( + section.header + block_count + HEADER_BLOCKS, + remaining_space - HEADER_BLOCKS, + false + ); + } +} + +// Returns the address of the next section +static tiny_block *next_section(tiny_block *header) { + tiny_block_section info = read_header(header); + return header + info.size + HEADER_BLOCKS; +} + +// Stores the last operation performed by the library into the main context +static void store_operation(enum tiny_function function, bool success, size_t size) { + tiny_operation op = { function, success, size }; + tiny.last_operation = op; +} + +// Initialises the library with a buffer. +// This will partition the buffer accordingly and allow allocating and +// deallocating memory from it. +void tiny_init(unsigned char *buffer, size_t size) { + unsigned char *aligned = ALIGN_PTR(buffer); + size_t lost_alignment = aligned - buffer; + + if(lost_alignment + (2 * HEADER_BLOCKS + 1) * ALIGNMENT >= size) { + store_operation(TINY_INIT, false, size); + return; + } + + tiny.buffer = (tiny_block *)aligned; + tiny.size = (size - lost_alignment) / ALIGNMENT - 2 * HEADER_BLOCKS; + + write_header(&tiny.buffer[0], tiny.size, false); + write_header(&tiny.buffer[tiny.size + HEADER_BLOCKS], 0, true); + store_operation(TINY_INIT, true, size); +} + +// Clears the library buffer +void tiny_clear() { + tiny.buffer = NULL; + tiny.size = 0; + store_operation(TINY_CLEAR, true, 0); +} + +// Resets the library buffer to its initial value +void tiny_reset() { + #ifdef TINY_BUFFER + tiny.buffer = (tiny_block *)&tiny_buffer.buffer; + tiny.size = (TINY_BUFFER / ALIGNMENT - 2 * HEADER_BLOCKS); + #else + tiny.buffer = NULL; + tiny.size = 0; + #endif + store_operation(TINY_RESET, true, tiny.size); +} + +// Sets the out-of-memory flag status. If set, calls to `malloc` and similar will +// return NULL always. +void tiny_out_of_memory(bool out_of_memory) { + tiny.out_of_memory = out_of_memory; +} + +// Returns the last operation performed by the library. +tiny_operation tiny_last_operation() { + return tiny.last_operation; +} + +// Gets the size of each block in the buffer (also, the library alignment) +size_t tiny_block_size() { return ALIGNMENT; } + + +// Prints a summary of the library +void tiny_print(bool summary, bool last_op, bool heap) { +} + + +tiny_summary tiny_inspect() { + #ifdef TINY_BUFFER + void *static_buffer = (void *)&tiny_buffer; + size_t static_buffer_size = TINY_BUFFER; + #else + void *static_buffer = NULL; + size_t static_buffer_size = 0; + #endif + + size_t free_blocks = 0, taken_blocks = 0; + size_t total_sections = 0, free_sections = 0, taken_sections = 0; + + tiny_block *header = &tiny.buffer[0]; + if(header) { + tiny_block_section section = read_header(header); + while(section.size > 0) { + total_sections++; + if(section.taken) { + taken_sections++; + taken_blocks += section.size; + } else { + free_sections++; + free_blocks += section.size; + } + header = next_section(header); + section = read_header(header); + } + } + + tiny_summary summ = { + ALIGNMENT, + ALIGNED_TYPE, + static_buffer, + static_buffer_size, + tiny.out_of_memory, + tiny.buffer, + { tiny.size, tiny.size * ALIGNMENT }, + { free_blocks, free_blocks * ALIGNMENT }, + { taken_blocks, taken_blocks * ALIGNMENT }, + { total_sections, free_sections, taken_sections } + }; + return summ; +} + + +tiny_section tiny_next_section(void *previous_header) { + if(tiny.buffer == NULL) { + tiny_section info = { false, NULL, NULL, { 0, 0 } }; + return info; + } + + tiny_block *header = previous_header ? + next_section(previous_header) : + &tiny.buffer[0]; + tiny_block_section section = read_header(header); + tiny_section info = { + section.taken, + section.size != 0 ? (void *)header : NULL, + section.size != 0 ? (void *)(header + HEADER_BLOCKS) : NULL, + { section.size, section.size * ALIGNMENT } + }; + return info; +} + +void *tiny_malloc(size_t size) { + if(tiny.out_of_memory || tiny.buffer == NULL || size == 0) { + store_operation(TINY_MALLOC, false, size); + return NULL; + } + + size_t aligned_size = ALIGN_SIZE(size); + if(aligned_size < size) { + store_operation(TINY_MALLOC, false, size); + return NULL; + } + + size_t blocks_required = aligned_size / ALIGNMENT; + tiny_block *header = &tiny.buffer[0]; + tiny_block_section section = read_header(header); + while(section.size > 0) { + if(!section.taken && section.size >= blocks_required) { + allocate_at(section, blocks_required); + store_operation(TINY_MALLOC, true, size); + return section.data; + } + header = next_section(header); + section = read_header(header); + } + store_operation(TINY_MALLOC, false, size); + return NULL; +} + +void *tiny_realloc(void *ptr, size_t size) { + if(ptr == NULL) { + void *data = tiny_malloc(size); + store_operation(TINY_REALLOC, data != NULL, size); + return data; + } + if(tiny.out_of_memory || tiny.buffer == NULL || size == 0) { + store_operation(TINY_REALLOC, false, size); + return NULL; + } + + size_t blocks_required = ALIGN_SIZE(size) / ALIGNMENT; + tiny_block *header = (tiny_block *)ptr - HEADER_BLOCKS; + tiny_block_section section = read_header(header); + tiny_block *next = next_section(header); + tiny_block_section next_section = read_header(next); + + if(!next_section.taken && next_section.size >= blocks_required - section.size + HEADER_BLOCKS) { + write_header(header, section.size + next_section.size + HEADER_BLOCKS, true); + allocate_at(read_header(header), blocks_required); + store_operation(TINY_REALLOC, true, size); + return ptr; + } else { + void *new_block = tiny_malloc(size); + if(new_block) { + std_copy(new_block, section.data, section.size * ALIGNMENT); + tiny_free(ptr); + } + store_operation(TINY_REALLOC, new_block != NULL, size); + return new_block; + } +} + +void *tiny_calloc(size_t num, size_t size) { + size_t full_size = num * size; + if(size == 0 || num == 0 || full_size / num != size) { + store_operation(TINY_CALLOC, false, size); + return NULL; + } + void *data = tiny_malloc(full_size); + if(data != NULL) { + std_w8(data, 0, full_size); + } + store_operation(TINY_CALLOC, data != NULL, num * size); + return data; +} + +void tiny_free(void *ptr) { + if(ptr == NULL || tiny.buffer == NULL) { + store_operation(TINY_FREE, false, 0); + return; + } + + tiny_block *current = (tiny_block *)ptr - HEADER_BLOCKS; + tiny_block_section current_section = read_header(current); + write_header(current, current_section.size, false); + + tiny_block *header = &tiny.buffer[0]; + tiny_block_section section = read_header(header); + while(section.size > 0) { + tiny_block *next = next_section(header); + if(!section.taken) { + tiny_block_section next_section = read_header(next); + if(!next_section.taken) { + write_header(header, section.size + next_section.size + HEADER_BLOCKS, false); + section = read_header(header); + continue; + } + } + + header = next; + section = read_header(header); + } + store_operation(TINY_FREE, true, current_section.size); +} diff --git a/luma/wm/tiny.h b/luma/wm/tiny.h new file mode 100644 index 0000000..d68fa35 --- /dev/null +++ b/luma/wm/tiny.h @@ -0,0 +1,65 @@ +#ifndef TINY_H +#define TINY_H + +#include +#include + +typedef struct tiny_operation { + enum tiny_function { + TINY_LOAD, + TINY_INIT, + TINY_CLEAR, + TINY_RESET, + TINY_MALLOC, + TINY_REALLOC, + TINY_CALLOC, + TINY_FREE + } function; + bool success; + size_t size; +} tiny_operation; + +typedef struct tiny_size { + size_t blocks; + size_t bytes; +} tiny_size; + +typedef struct tiny_summary { + size_t alignment; + char *aligned_type; + void *static_buffer; + size_t static_buffer_size; + bool out_of_memory; + void *buffer; + tiny_size total; + tiny_size free; + tiny_size taken; + struct tiny_sections { + size_t total; + size_t free; + size_t taken; + } sections; +} tiny_summary; + +typedef struct tiny_section { + bool taken; + void *header; + void *data; + tiny_size size; +} tiny_section; + +void tiny_init(unsigned char *buffer, size_t size); +void tiny_clear(void); +void tiny_reset(void); +void tiny_out_of_memory(bool status); +tiny_operation tiny_last_operation(void); +size_t tiny_block_size(void); +void tiny_print(bool summary, bool last_op, bool heap); +tiny_summary tiny_inspect(void); +tiny_section tiny_next_section(void *previous_header); +void *tiny_malloc(size_t size); +void *tiny_realloc(void *ptr, size_t size); +void *tiny_calloc(size_t num, size_t size); +void tiny_free(void *ptr); + +#endif /* end of guard: TINY_H */ \ No newline at end of file diff --git a/luma/wm/ui.c b/luma/wm/ui.c new file mode 100644 index 0000000..e15b20d --- /dev/null +++ b/luma/wm/ui.c @@ -0,0 +1,475 @@ +#include"ui.h" + +#include"tiny.h" +#include"../vid/api.h" +#include"../sys.h" +#include"wm.h" + +#include"logserver.h" + +static void gtext_render(struct GObj *_) { + struct GText *this = (void*) _; + + LumaVidCommand *cmd = VidLink; + cmd->op = LUMA_VID_COMMAND_SET_COLOR_FLAT; + cmd->colorFlat.r = 0xF0; + cmd->colorFlat.g = 0xF0; + cmd->colorFlat.b = 0xF0; + cmd = (LumaVidCommand*) ((uintptr_t) cmd + sizeof(cmd->colorFlat)); + cmd->op = LUMA_VID_COMMAND_RECT; + cmd->rect.x1 = this->x; + cmd->rect.x2 = this->x + this->w - 1; + cmd->rect.y1 = this->y; + cmd->rect.y2 = this->y + this->h - 1; + cmd = (LumaVidCommand*) ((uintptr_t) cmd + sizeof(cmd->rect)); + cmd->op = LUMA_VID_COMMAND_SET_COLOR_FLAT; + cmd->colorFlat.r = 0x00; + cmd->colorFlat.g = 0x00; + cmd->colorFlat.b = 0x00; + cmd = (LumaVidCommand*) ((uintptr_t) cmd + sizeof(cmd->colorFlat)); + DynStr16 *txt = this->data; + if(!txt || !txt->len) txt = this->placeholder; + if(txt) { + cmd->op = LUMA_VID_COMMAND_TEXT; + cmd->text.x = this->x + 5; + cmd->text.y = this->y + 2; + cmd->text.wall = this->x + this->w; + std_copy(cmd->text.data, txt->data, cmd->text.len = txt->len); + cmd = (LumaVidCommand*) ((uintptr_t) cmd + sizeof(cmd->text) + cmd->text.len); + } + cmd->op = LUMA_VID_COMMAND_END; + + memory_barrier(); + sys_signal_send(VidLink, -1); + sys_signal_wait(VidLink, NULL); +} +static void gtext_key(struct GObj *_, struct GKeyEvent ev) { + if(_->focus == 0) return; + + struct GText *this = (void*) _; + + if(ev.press) { + if(!this->data) { + this->data = g_dynstr16_new(8, 0, NULL); + } + + if(ev.scancode == LK_BACKSPACE) { + if(this->data->len) { + this->data->len--; + } + } else { + uint8_t newCh = 0; + + if(ev.scancode >= LK_A && ev.scancode <= LK_Z) { + newCh = ev.scancode - LK_A; + newCh += ev.shift ? 'A' : 'a'; + } else if(ev.scancode == LK_SPACE) { + newCh = ' '; + } + + if(newCh) this->data = g_dynstr16_append(this->data, 1, &newCh); + } + } +} +static void gtext_destroy(struct GObj *_) { + struct GText *this = (void*) _; + + if(this->data) g_dynstr16_free(this->data); + + if(this->placeholder) g_dynstr16_free(this->placeholder); + + tiny_free(this); +} +struct GText *gtext_new(Coord x, Coord y, Coord w, Coord h, DynStr16 *placeholder, DynStr16 *str) { + struct GText *ret = tiny_calloc(sizeof(*ret), 1); + ret->onRender = gtext_render; + ret->onKey = gtext_key; + ret->destroy = gtext_destroy; + ret->x = x; + ret->y = y; + ret->w = w; + ret->h = h; + ret->placeholder = placeholder; + ret->data = str; + return ret; +} + +static void gcont_render(struct GObj *_) { + struct GContainer *this = (void*) _; + for(size_t i = 0; i < this->childCount; i++) { + if(this->children[i].obj && this->children[i].obj->onRender) { + this->children[i].obj->onRender(this->children[i].obj); + } + } +} +static void gcont_key(struct GObj *_, struct GKeyEvent ev) { + if(_->focus == 0) return; + + struct GContainer *this = (void*) _; + for(size_t i = 0; i < this->childCount; i++) { + if(this->children[i].obj && this->children[i].obj->onKey) { + this->children[i].obj->onKey(this->children[i].obj, ev); + } + } +} +static void gcont_destroy(struct GObj *_) { + struct GContainer *this = (void*) _; + + for(size_t i = 0; i < this->childCount; i++) { + if(this->children[i].obj) { + this->children[i].obj->destroy(this->children[i].obj); + } + } + + tiny_free(this->children); + + tiny_free(this); +} +struct GContainer *gcont_new(Coord x, Coord y, Coord w, Coord h, FitterFunc fitter) { + struct GContainer *ret = tiny_calloc(sizeof(*ret), 1); + ret->onRender = gcont_render; + ret->onKey = gcont_key; + ret->destroy = gcont_destroy; + ret->x = x; + ret->y = y; + ret->w = w; + ret->h = h; + ret->fitter = fitter; + return ret; +} +int gcont_add(struct GContainer *this, GContainerChildMeta meta, struct GObj* child) { + struct GContainerChild *newchildren = tiny_realloc(this->children, sizeof(*this->children) * (this->childCount + 1)); + if(newchildren) { + this->children = newchildren; + this->children[this->childCount].meta = meta; + this->children[this->childCount].obj = child; + this->childCount++; + if(this->fitter) this->fitter((struct GObj*) this); + return 1; + } else { + return 0; + } +} +void gcont_set(struct GContainer *this, size_t index, GContainerChildMeta meta, struct GObj *obj) { + this->children[index] = (struct GContainerChild) { + .meta = meta, + .obj = obj, + }; + if(this->fitter) this->fitter((struct GObj*) this); +} +void gcont_del(struct GContainer *this, size_t index) { + std_move(&this->children[index], &this->children[index + 1], sizeof(*this->children) * (this->childCount - index - 1)); + this->children = tiny_realloc(this->children, sizeof(*this->children) * (--this->childCount)); +} + +void gcont_splitter_v(struct GObj *_) { + struct GContainer *c = (void*) _; + + struct GContainerChild *o = c->children; + for(size_t i = 0; i < c->childCount; i++, o++) { + if(o[0].obj) { + o[0].obj->x = c->x; + o[0].obj->y = c->y + c->h * i / c->childCount; + o[0].obj->w = c->w; + o[0].obj->h = c->h / c->childCount; + + if(o[0].obj->fitter) o[0].obj->fitter(o[0].obj); + } + } +} + +void gcont_splitter_h(struct GObj *_) { + struct GContainer *c = (void*) _; + + struct GContainerChild *o = c->children; + for(size_t i = 0; i < c->childCount; i++, o++) { + if(o[0].obj) { + o[0].obj->x = c->x + c->w * i / c->childCount; + o[0].obj->y = c->y; + o[0].obj->w = c->w / c->childCount; + o[0].obj->h = c->h; + + if(o[0].obj->fitter) o[0].obj->fitter(o[0].obj); + } + } +} + +static void gwindow_render(struct GObj *_) { + struct GWindow *this = (void*) _; + + LumaVidCommand *cmd = VidLink; + cmd->op = LUMA_VID_COMMAND_SET_COLOR_FLAT; + if(this->focus) { + cmd->colorFlat.r = 0xF0; + cmd->colorFlat.g = 0xF0; + cmd->colorFlat.b = 0xF0; + } else { + cmd->colorFlat.r = 0x80; + cmd->colorFlat.g = 0x80; + cmd->colorFlat.b = 0x80; + } + cmd = (LumaVidCommand*) ((uintptr_t) cmd + sizeof(cmd->colorFlat)); + cmd->op = LUMA_VID_COMMAND_RECT; + cmd->rect.x1 = this->x; + cmd->rect.x2 = this->x + this->w - 1; + cmd->rect.y1 = this->y; + cmd->rect.y2 = this->y + 11; + cmd = (LumaVidCommand*) ((uintptr_t) cmd + sizeof(cmd->rect)); + cmd->op = LUMA_VID_COMMAND_SET_COLOR_FLAT; + cmd->colorFlat.r = 0x00; + cmd->colorFlat.g = 0x00; + cmd->colorFlat.b = 0x00; + cmd = (LumaVidCommand*) ((uintptr_t) cmd + sizeof(cmd->colorFlat)); + cmd->op = LUMA_VID_COMMAND_TEXT; + cmd->text.x = this->x + 3; + cmd->text.y = this->y + 1; + std_copy(cmd->text.data, this->name->data, cmd->text.len = this->name->len); + cmd = (LumaVidCommand*) ((uintptr_t) cmd + sizeof(cmd->text) + cmd->text.len); + cmd->op = LUMA_VID_COMMAND_END; + + memory_barrier(); + sys_signal_send(VidLink, -1); + sys_signal_wait(VidLink, NULL); + + if(this->child) { + if(this->child->onRender) this->child->onRender(this->child); + } +} +static void gwindow_key(struct GObj *_, struct GKeyEvent ev) { + if(_->focus == 0) return; + + struct GWindow *this = (void*) _; + if(this->child) { + if(this->child->onKey) this->child->onKey(this->child, ev); + } +} +static void gwindow_fitter(struct GObj *_) { + struct GWindow *this = (void*) _; + if(this->child) { + this->child->x = this->x; + this->child->y = this->y + 12; + this->child->w = this->w; + this->child->h = this->h - 12; + if(this->child->fitter) this->child->fitter(this->child); + } +} +static void gwindow_destroy(struct GObj *_) { + struct GWindow *this = (void*) _; + if(this->child) { + this->child->destroy(this->child); + } + if(this->name) { + g_dynstr16_free(this->name); + } + tiny_free(this); +} +struct GWindow *gwindow_new(Coord x, Coord y, Coord w, Coord h, DynStr16 *name, struct GObj *child, size_t owner) { + struct GWindow *ret = tiny_calloc(sizeof(*ret), 1); + ret->onRender = gwindow_render; + ret->onKey = gwindow_key; + ret->fitter = gwindow_fitter; + ret->destroy = gwindow_destroy; + ret->x = x; + ret->y = y; + ret->w = w; + ret->h = h; + ret->name = name; + ret->child = child; + ret->owner = owner; + return ret; +} +int gwindow_regcmd(struct GWindow *this, Str16 *name, void *ud, GCMDFunc handler) { + struct Command *newarray = tiny_realloc(this->cmds.array, sizeof(*this->cmds.array) * (this->cmds.count + 1)); + if(!newarray) { + return 0; + } + + newarray[this->cmds.count] = (struct Command) { + .name = name, + .ud = ud, + .run = handler + }; + this->cmds.array = newarray; + + this->cmds.count++; + + return 1; +} + +static void glabel_render(struct GObj *_) { + struct GLabel *this = (void*) _; + + LumaVidCommand *cmd = VidLink; + cmd->op = LUMA_VID_COMMAND_SET_COLOR_FLAT; + cmd->colorFlat.r = 0x00; + cmd->colorFlat.g = 0x00; + cmd->colorFlat.b = 0x00; + cmd = (LumaVidCommand*) ((uintptr_t) cmd + sizeof(cmd->colorFlat)); + if(this->data) { + cmd->op = LUMA_VID_COMMAND_TEXT; + cmd->text.x = this->x; + cmd->text.y = this->y; + cmd->text.wall = this->x + this->w; + std_copy(cmd->text.data, this->data->data, cmd->text.len = this->data->len); + cmd = (LumaVidCommand*) ((uintptr_t) cmd + sizeof(cmd->text) + cmd->text.len); + } + cmd->op = LUMA_VID_COMMAND_END; + + memory_barrier(); + sys_signal_send(VidLink, -1); + sys_signal_wait(VidLink, NULL); +} +static void glabel_destroy(struct GObj *_) { + struct GLabel *this = (void*) _; + + if(this->data && this->owned) { + g_dynstr16_free(this->data); + } + + tiny_free(this); +} +struct GLabel *glabel_new(Coord x, Coord y, Coord w, Coord h, DynStr16 *data, int owned) { + struct GLabel *ret = tiny_calloc(sizeof(*ret), 1); + ret->onRender = glabel_render; + ret->onKey = NULL; + ret->fitter = NULL; + ret->destroy = glabel_destroy; + ret->x = x; + ret->y = y; + ret->w = w; + ret->h = h; + ret->data = data; + ret->owned = owned; + return ret; +} + +static void glist_render(struct GObj *_) { + struct GList *this = (void*) _; + + for(size_t i = 0; i < this->childCount; i++) { + LumaVidCommand *cmd = VidLink; + cmd->op = LUMA_VID_COMMAND_SET_COLOR_FLAT; + if(this->children[i].selected) { + cmd->colorFlat.r = 0xFF; + cmd->colorFlat.g = 0xFF; + cmd->colorFlat.b = 0xFF; + } else if(i == this->cursor) { + cmd->colorFlat.r = 0x80; + cmd->colorFlat.g = 0x80; + cmd->colorFlat.b = 0x80; + } else { + cmd->colorFlat.r = 0x00; + cmd->colorFlat.g = 0x00; + cmd->colorFlat.b = 0x00; + } + cmd = (LumaVidCommand*) ((uintptr_t) cmd + sizeof(cmd->colorFlat)); + cmd->op = LUMA_VID_COMMAND_TEXT; + cmd->text.x = this->x; + cmd->text.y = this->y + 13 * i; + cmd->text.wall = this->x + this->w; + std_copy(cmd->text.data, this->children[i].text->data, cmd->text.len = this->children[i].text->len); + cmd = (LumaVidCommand*) ((uintptr_t) cmd + sizeof(cmd->text) + cmd->text.len); + cmd->op = LUMA_VID_COMMAND_END; + memory_barrier(); + sys_signal_send(VidLink, -1); + sys_signal_wait(VidLink, NULL); + } +} +static void glist_key(struct GObj *_, struct GKeyEvent ev) { + struct GList *this = (void*) _; + if(!ev.press) return; + + if(ev.scancode == LK_DOWN) { + if(this->childCount) { + this->cursor = (this->cursor + 1) % this->childCount; + } else { + this->cursor = 0; + } + + dirty_obj(_); + } else if(ev.scancode == LK_UP) { + if(this->childCount) { + this->cursor = (this->cursor - 1 + this->childCount) % this->childCount; + } else { + this->cursor = 0; + } + + dirty_obj(_); + } else if(ev.scancode == LK_SPACE) { + if(this->cursor < this->childCount) { + this->children[this->cursor].selected ^= 1; + } + + dirty_obj(_); + } +} +static void glist_destroy(struct GObj *_) { + struct GList *this = (void*) _; + + for(size_t i = 0; i < this->childCount; i++) { + g_dynstr16_free(this->children[i].text); + } + + tiny_free(this->children); +} +struct GList *glist_new(Coord x, Coord y, Coord w, Coord h) { + struct GList *ret = tiny_calloc(sizeof(*ret), 1); + ret->onRender = glist_render; + ret->onKey = glist_key; + ret->fitter = NULL; + ret->destroy = glist_destroy; + ret->x = x; + ret->y = y; + ret->w = w; + ret->h = h; + ret->childCount = 0; + ret->children = NULL; + return ret; +} +int glist_add(struct GList *this, DynStr16 *str, void *ud) { + struct GListChild *newchildren = tiny_realloc(this->children, sizeof(*this->children) * (this->childCount + 1)); + if(newchildren) { + newchildren[this->childCount++] = (struct GListChild) { + .text = str, + .selected = 0, + .ud = ud, + }; + this->children = newchildren; + return 1; + } + return 0; +} +void glist_clear(struct GList *this) { + this->childCount = 0; + tiny_free(this->children); + this->children = NULL; + this->cursor = 0; +} + +DynStr16 *g_dynstr16_new(uint16_t cap, uint16_t len, const void *data) { + DynStr16 *ret = tiny_malloc(sizeof(*ret) + cap); + ret->cap = cap; + ret->len = len; + if(data) { + std_copy(ret->data, data, len); + } + return ret; +} +DynStr16 *g_dynstr16_append(DynStr16 *this, uint16_t len, const void *data) { + if(this->len + len > this->cap) { + this = tiny_realloc(this, sizeof(*this) + (this->cap = this->len + len)); + } + std_copy(this->data + this->len, data, len); + this->len += len; + return this; +} +void g_dynstr16_free(DynStr16 *this) { + tiny_free(this); +} + +Str16 *g_str16_new(uint16_t len, const void *data) { + Str16 *ret = tiny_malloc(sizeof(*ret) + len); + ret->len = len; + std_copy(ret->data, data, len); + return ret; +} diff --git a/luma/wm/ui.h b/luma/wm/ui.h new file mode 100644 index 0000000..3dc34c4 --- /dev/null +++ b/luma/wm/ui.h @@ -0,0 +1,124 @@ +#pragma once + +#include"../std.h" +#include"../ps2/api.h" + +typedef uint16_t Coord; + +struct GObj; +struct GContainer; + +#define SHIFT_LEFT 1 +#define SHIFT_RIGHT 2 +#define ALT_LEFT 1 +#define ALT_RIGHT 2 +#define SYS_LEFT 1 +#define SYS_RIGHT 2 +struct GKeyEvent { + uint8_t scancode; + uint8_t press; + uint8_t shift; + uint8_t alt; + uint8_t sys; +}; + +typedef void(*RenderFunc)(struct GObj*); +typedef void(*KeyReactFunc)(struct GObj*, struct GKeyEvent); +typedef void(*FitterFunc)(struct GObj*); +typedef void(*DestroyFunc)(struct GObj*); + +struct GObj { + RenderFunc onRender; + KeyReactFunc onKey; + DestroyFunc destroy; + FitterFunc fitter; + Coord x, y; + Coord w, h; + uint8_t focus; + void *ud; +}; + +struct GText { + struct GObj; + + DynStr16 *placeholder; + DynStr16 *data; +}; +struct GText *gtext_new(Coord x, Coord y, Coord w, Coord h, DynStr16 *placeholder, DynStr16 *str); + +typedef uint8_t GContainerChildMeta; +struct GContainerChild { + GContainerChildMeta meta; + struct GObj *obj; +}; +struct GContainer { + struct GObj; + + size_t childCount; + struct GContainerChild *children; + + uint8_t meta; +}; +struct GContainer *gcont_new(Coord x, Coord y, Coord w, Coord h, FitterFunc fitter); +int gcont_add(struct GContainer*, GContainerChildMeta, struct GObj*); +void gcont_set(struct GContainer*, size_t index, GContainerChildMeta, struct GObj*); +void gcont_del(struct GContainer*, size_t index); + +void gcont_splitter_v(struct GObj*); +void gcont_splitter_h(struct GObj*); + +typedef int(*GCMDFunc)(void*, const DynStr16 *line); +struct Command { + Str16 *name; + void *ud; + GCMDFunc run; +}; +struct CommandList { + size_t count; + struct Command *array; +}; + +struct GWindow { + struct GObj; + + DynStr16 *name; + + struct GObj *child; + + size_t owner; + + struct CommandList cmds; +}; +struct GWindow *gwindow_new(Coord x, Coord y, Coord w, Coord h, DynStr16 *name, struct GObj *child, size_t owner); +int gwindow_regcmd(struct GWindow*, Str16 *cmd, void *ud, GCMDFunc handler); + +struct GLabel { + struct GObj; + + DynStr16 *data; + int owned; +}; +struct GLabel *glabel_new(Coord x, Coord y, Coord w, Coord h, DynStr16 *data, int owned); + +struct GListChild { + DynStr16 *text; + void *ud; + uint8_t selected; +}; +struct GList { + struct GObj; + + size_t childCount; + struct GListChild *children; + + size_t cursor; +}; +struct GList *glist_new(Coord x, Coord y, Coord w, Coord h); +int glist_add(struct GList*, DynStr16*, void *ud); +void glist_clear(struct GList*); + +DynStr16 *g_dynstr16_new(uint16_t cap, uint16_t len, const void *data); +DynStr16 *g_dynstr16_append(DynStr16*, uint16_t len, const void *data); +void g_dynstr16_free(DynStr16*); + +Str16 *g_str16_new(uint16_t len, const void *data); diff --git a/luma/wm/wm.h b/luma/wm/wm.h new file mode 100644 index 0000000..122519b --- /dev/null +++ b/luma/wm/wm.h @@ -0,0 +1,21 @@ +#pragma once + +#include"ui.h" + +extern void *FSLink; +extern void *VidLink; + +struct WTreeNode { + char vertical; + struct GWindow *window; + struct WTreeNode *parent; + struct WTreeNode *first; + struct WTreeNode *second; +}; +extern struct WTreeNode *windowTreeFocus; + +int add_window(struct GWindow *w); +int is_free_space(); + +void dirty(int x, int y, int w, int h); +void dirty_obj(struct GObj*); diff --git a/luma/wm/zconf.h b/luma/wm/zconf.h new file mode 100644 index 0000000..893810a --- /dev/null +++ b/luma/wm/zconf.h @@ -0,0 +1,548 @@ +/* zconf.h -- configuration of the zlib compression library + * Copyright (C) 1995-2016 Jean-loup Gailly, Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#ifndef ZCONF_H +#define ZCONF_H +#define Z_SOLO + +/* + * If you *really* need a unique prefix for all types and library functions, + * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. + * Even better than compiling with -DZ_PREFIX would be to use configure to set + * this permanently in zconf.h using "./configure --zprefix". + */ +#if 1 /* was set to #if 1 by ./configure */ +# define Z_PREFIX_SET + +/* all linked symbols and init macros */ +# define _dist_code z__dist_code +# define _length_code z__length_code +# define _tr_align z__tr_align +# define _tr_flush_bits z__tr_flush_bits +# define _tr_flush_block z__tr_flush_block +# define _tr_init z__tr_init +# define _tr_stored_block z__tr_stored_block +# define _tr_tally z__tr_tally +# define adler32 z_adler32 +# define adler32_combine z_adler32_combine +# define adler32_combine64 z_adler32_combine64 +# define adler32_z z_adler32_z +# ifndef Z_SOLO +# define compress z_compress +# define compress2 z_compress2 +# define compressBound z_compressBound +# endif +# define crc32 z_crc32 +# define crc32_combine z_crc32_combine +# define crc32_combine64 z_crc32_combine64 +# define crc32_combine_gen z_crc32_combine_gen +# define crc32_combine_gen64 z_crc32_combine_gen64 +# define crc32_combine_op z_crc32_combine_op +# define crc32_z z_crc32_z +# define deflate z_deflate +# define deflateBound z_deflateBound +# define deflateCopy z_deflateCopy +# define deflateEnd z_deflateEnd +# define deflateGetDictionary z_deflateGetDictionary +# define deflateInit z_deflateInit +# define deflateInit2 z_deflateInit2 +# define deflateInit2_ z_deflateInit2_ +# define deflateInit_ z_deflateInit_ +# define deflateParams z_deflateParams +# define deflatePending z_deflatePending +# define deflatePrime z_deflatePrime +# define deflateReset z_deflateReset +# define deflateResetKeep z_deflateResetKeep +# define deflateSetDictionary z_deflateSetDictionary +# define deflateSetHeader z_deflateSetHeader +# define deflateTune z_deflateTune +# define deflate_copyright z_deflate_copyright +# define get_crc_table z_get_crc_table +# ifndef Z_SOLO +# define gz_error z_gz_error +# define gz_intmax z_gz_intmax +# define gz_strwinerror z_gz_strwinerror +# define gzbuffer z_gzbuffer +# define gzclearerr z_gzclearerr +# define gzclose z_gzclose +# define gzclose_r z_gzclose_r +# define gzclose_w z_gzclose_w +# define gzdirect z_gzdirect +# define gzdopen z_gzdopen +# define gzeof z_gzeof +# define gzerror z_gzerror +# define gzflush z_gzflush +# define gzfread z_gzfread +# define gzfwrite z_gzfwrite +# define gzgetc z_gzgetc +# define gzgetc_ z_gzgetc_ +# define gzgets z_gzgets +# define gzoffset z_gzoffset +# define gzoffset64 z_gzoffset64 +# define gzopen z_gzopen +# define gzopen64 z_gzopen64 +# ifdef _WIN32 +# define gzopen_w z_gzopen_w +# endif +# define gzprintf z_gzprintf +# define gzputc z_gzputc +# define gzputs z_gzputs +# define gzread z_gzread +# define gzrewind z_gzrewind +# define gzseek z_gzseek +# define gzseek64 z_gzseek64 +# define gzsetparams z_gzsetparams +# define gztell z_gztell +# define gztell64 z_gztell64 +# define gzungetc z_gzungetc +# define gzvprintf z_gzvprintf +# define gzwrite z_gzwrite +# endif +# define inflate z_inflate +# define inflateBack z_inflateBack +# define inflateBackEnd z_inflateBackEnd +# define inflateBackInit z_inflateBackInit +# define inflateBackInit_ z_inflateBackInit_ +# define inflateCodesUsed z_inflateCodesUsed +# define inflateCopy z_inflateCopy +# define inflateEnd z_inflateEnd +# define inflateGetDictionary z_inflateGetDictionary +# define inflateGetHeader z_inflateGetHeader +# define inflateInit z_inflateInit +# define inflateInit2 z_inflateInit2 +# define inflateInit2_ z_inflateInit2_ +# define inflateInit_ z_inflateInit_ +# define inflateMark z_inflateMark +# define inflatePrime z_inflatePrime +# define inflateReset z_inflateReset +# define inflateReset2 z_inflateReset2 +# define inflateResetKeep z_inflateResetKeep +# define inflateSetDictionary z_inflateSetDictionary +# define inflateSync z_inflateSync +# define inflateSyncPoint z_inflateSyncPoint +# define inflateUndermine z_inflateUndermine +# define inflateValidate z_inflateValidate +# define inflate_copyright z_inflate_copyright +# define inflate_fast z_inflate_fast +# define inflate_table z_inflate_table +# ifndef Z_SOLO +# define uncompress z_uncompress +# define uncompress2 z_uncompress2 +# endif +# define zError z_zError +# ifndef Z_SOLO +# define zcalloc z_zcalloc +# define zcfree z_zcfree +# endif +# define zlibCompileFlags z_zlibCompileFlags +# define zlibVersion z_zlibVersion + +/* all zlib typedefs in zlib.h and zconf.h */ +# define Byte z_Byte +# define Bytef z_Bytef +# define alloc_func z_alloc_func +# define charf z_charf +# define free_func z_free_func +# ifndef Z_SOLO +# define gzFile z_gzFile +# endif +# define gz_header z_gz_header +# define gz_headerp z_gz_headerp +# define in_func z_in_func +# define intf z_intf +# define out_func z_out_func +# define uInt z_uInt +# define uIntf z_uIntf +# define uLong z_uLong +# define uLongf z_uLongf +# define voidp z_voidp +# define voidpc z_voidpc +# define voidpf z_voidpf + +/* all zlib structs in zlib.h and zconf.h */ +# define gz_header_s z_gz_header_s +# define internal_state z_internal_state + +#endif + +#if defined(__MSDOS__) && !defined(MSDOS) +# define MSDOS +#endif +#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) +# define OS2 +#endif +#if defined(_WINDOWS) && !defined(WINDOWS) +# define WINDOWS +#endif +#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__) +# ifndef WIN32 +# define WIN32 +# endif +#endif +#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) +# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) +# ifndef SYS16BIT +# define SYS16BIT +# endif +# endif +#endif + +/* + * Compile with -DMAXSEG_64K if the alloc function cannot allocate more + * than 64k bytes at a time (needed on systems with 16-bit int). + */ +#ifdef SYS16BIT +# define MAXSEG_64K +#endif +#ifdef MSDOS +# define UNALIGNED_OK +#endif + +#ifdef __STDC_VERSION__ +# ifndef STDC +# define STDC +# endif +# if __STDC_VERSION__ >= 199901L +# ifndef STDC99 +# define STDC99 +# endif +# endif +#endif +#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) +# define STDC +#endif +#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) +# define STDC +#endif +#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) +# define STDC +#endif +#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) +# define STDC +#endif + +#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ +# define STDC +#endif + +#ifndef STDC +# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ +# define const /* note: need a more gentle solution here */ +# endif +#endif + +#if defined(ZLIB_CONST) && !defined(z_const) +# define z_const const +#else +# define z_const +#endif + +#ifdef Z_SOLO + typedef unsigned long z_size_t; +#else +# define z_longlong long long +# if defined(NO_SIZE_T) + typedef unsigned NO_SIZE_T z_size_t; +# elif defined(STDC) +# include + typedef size_t z_size_t; +# else + typedef unsigned long z_size_t; +# endif +# undef z_longlong +#endif + +/* Maximum value for memLevel in deflateInit2 */ +#ifndef MAX_MEM_LEVEL +# ifdef MAXSEG_64K +# define MAX_MEM_LEVEL 8 +# else +# define MAX_MEM_LEVEL 9 +# endif +#endif + +/* Maximum value for windowBits in deflateInit2 and inflateInit2. + * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files + * created by gzip. (Files created by minigzip can still be extracted by + * gzip.) + */ +#ifndef MAX_WBITS +# define MAX_WBITS 15 /* 32K LZ77 window */ +#endif + +/* The memory requirements for deflate are (in bytes): + (1 << (windowBits+2)) + (1 << (memLevel+9)) + that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) + plus a few kilobytes for small objects. For example, if you want to reduce + the default memory requirements from 256K to 128K, compile with + make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" + Of course this will generally degrade compression (there's no free lunch). + + The memory requirements for inflate are (in bytes) 1 << windowBits + that is, 32K for windowBits=15 (default value) plus about 7 kilobytes + for small objects. +*/ + + /* Type declarations */ + +#ifndef OF /* function prototypes */ +# ifdef STDC +# define OF(args) args +# else +# define OF(args) () +# endif +#endif + +#ifndef Z_ARG /* function prototypes for stdarg */ +# if defined(STDC) || defined(Z_HAVE_STDARG_H) +# define Z_ARG(args) args +# else +# define Z_ARG(args) () +# endif +#endif + +/* The following definitions for FAR are needed only for MSDOS mixed + * model programming (small or medium model with some far allocations). + * This was tested only with MSC; for other MSDOS compilers you may have + * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, + * just define FAR to be empty. + */ +#ifdef SYS16BIT +# if defined(M_I86SM) || defined(M_I86MM) + /* MSC small or medium model */ +# define SMALL_MEDIUM +# ifdef _MSC_VER +# define FAR _far +# else +# define FAR far +# endif +# endif +# if (defined(__SMALL__) || defined(__MEDIUM__)) + /* Turbo C small or medium model */ +# define SMALL_MEDIUM +# ifdef __BORLANDC__ +# define FAR _far +# else +# define FAR far +# endif +# endif +#endif + +#if defined(WINDOWS) || defined(WIN32) + /* If building or using zlib as a DLL, define ZLIB_DLL. + * This is not mandatory, but it offers a little performance increase. + */ +# ifdef ZLIB_DLL +# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) +# ifdef ZLIB_INTERNAL +# define ZEXTERN extern __declspec(dllexport) +# else +# define ZEXTERN extern __declspec(dllimport) +# endif +# endif +# endif /* ZLIB_DLL */ + /* If building or using zlib with the WINAPI/WINAPIV calling convention, + * define ZLIB_WINAPI. + * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. + */ +# ifdef ZLIB_WINAPI +# ifdef FAR +# undef FAR +# endif +# ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN +# endif +# include + /* No need for _export, use ZLIB.DEF instead. */ + /* For complete Windows compatibility, use WINAPI, not __stdcall. */ +# define ZEXPORT WINAPI +# ifdef WIN32 +# define ZEXPORTVA WINAPIV +# else +# define ZEXPORTVA FAR CDECL +# endif +# endif +#endif + +#if defined (__BEOS__) +# ifdef ZLIB_DLL +# ifdef ZLIB_INTERNAL +# define ZEXPORT __declspec(dllexport) +# define ZEXPORTVA __declspec(dllexport) +# else +# define ZEXPORT __declspec(dllimport) +# define ZEXPORTVA __declspec(dllimport) +# endif +# endif +#endif + +#ifndef ZEXTERN +# define ZEXTERN extern +#endif +#ifndef ZEXPORT +# define ZEXPORT +#endif +#ifndef ZEXPORTVA +# define ZEXPORTVA +#endif + +#ifndef FAR +# define FAR +#endif + +#if !defined(__MACTYPES__) +typedef unsigned char Byte; /* 8 bits */ +#endif +typedef unsigned int uInt; /* 16 bits or more */ +typedef unsigned long uLong; /* 32 bits or more */ + +#ifdef SMALL_MEDIUM + /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ +# define Bytef Byte FAR +#else + typedef Byte FAR Bytef; +#endif +typedef char FAR charf; +typedef int FAR intf; +typedef uInt FAR uIntf; +typedef uLong FAR uLongf; + +#ifdef STDC + typedef void const *voidpc; + typedef void FAR *voidpf; + typedef void *voidp; +#else + typedef Byte const *voidpc; + typedef Byte FAR *voidpf; + typedef Byte *voidp; +#endif + +#if !defined(Z_U4) && !defined(Z_SOLO) && defined(STDC) +# include +# if (UINT_MAX == 0xffffffffUL) +# define Z_U4 unsigned +# elif (ULONG_MAX == 0xffffffffUL) +# define Z_U4 unsigned long +# elif (USHRT_MAX == 0xffffffffUL) +# define Z_U4 unsigned short +# endif +#endif + +#ifdef Z_U4 + typedef Z_U4 z_crc_t; +#else + typedef unsigned long z_crc_t; +#endif + +#ifdef HAVE_UNISTD_H /* may be set to #if 1 by ./configure */ +# define Z_HAVE_UNISTD_H +#endif + +#if 1 /* was set to #if 1 by ./configure */ +# define Z_HAVE_STDARG_H +#endif + +#ifdef STDC +# ifndef Z_SOLO +# include /* for off_t */ +# endif +#endif + +#if defined(STDC) || defined(Z_HAVE_STDARG_H) +# ifndef Z_SOLO +# include /* for va_list */ +# endif +#endif + +#ifdef _WIN32 +# ifndef Z_SOLO +# include /* for wchar_t */ +# endif +#endif + +/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and + * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even + * though the former does not conform to the LFS document), but considering + * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as + * equivalently requesting no 64-bit operations + */ +#if defined(_LARGEFILE64_SOURCE) && -_LARGEFILE64_SOURCE - -1 == 1 +# undef _LARGEFILE64_SOURCE +#endif + +#ifndef Z_HAVE_UNISTD_H +# ifdef __WATCOMC__ +# define Z_HAVE_UNISTD_H +# endif +#endif +#ifndef Z_HAVE_UNISTD_H +# if defined(_LARGEFILE64_SOURCE) && !defined(_WIN32) +# define Z_HAVE_UNISTD_H +# endif +#endif +#ifndef Z_SOLO +# if defined(Z_HAVE_UNISTD_H) +# include /* for SEEK_*, off_t, and _LFS64_LARGEFILE */ +# ifdef VMS +# include /* for off_t */ +# endif +# ifndef z_off_t +# define z_off_t off_t +# endif +# endif +#endif + +#if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0 +# define Z_LFS64 +#endif + +#if defined(_LARGEFILE64_SOURCE) && defined(Z_LFS64) +# define Z_LARGE64 +#endif + +#if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS-0 == 64 && defined(Z_LFS64) +# define Z_WANT64 +#endif + +#if !defined(SEEK_SET) && !defined(Z_SOLO) +# define SEEK_SET 0 /* Seek from beginning of file. */ +# define SEEK_CUR 1 /* Seek from current position. */ +# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ +#endif + +#ifndef z_off_t +# define z_off_t long +#endif + +#if !defined(_WIN32) && defined(Z_LARGE64) +# define z_off64_t off64_t +#else +# if defined(_WIN32) && !defined(__GNUC__) && !defined(Z_SOLO) +# define z_off64_t __int64 +# else +# define z_off64_t z_off_t +# endif +#endif + +/* MVS linker does not support external names larger than 8 bytes */ +#if defined(__MVS__) + #pragma map(deflateInit_,"DEIN") + #pragma map(deflateInit2_,"DEIN2") + #pragma map(deflateEnd,"DEEND") + #pragma map(deflateBound,"DEBND") + #pragma map(inflateInit_,"ININ") + #pragma map(inflateInit2_,"ININ2") + #pragma map(inflateEnd,"INEND") + #pragma map(inflateSync,"INSY") + #pragma map(inflateSetDictionary,"INSEDI") + #pragma map(compressBound,"CMBND") + #pragma map(inflate_table,"INTABL") + #pragma map(inflate_fast,"INFA") + #pragma map(inflate_copyright,"INCOPY") +#endif + +#endif /* ZCONF_H */ diff --git a/luma/wm/zlib.h b/luma/wm/zlib.h new file mode 100644 index 0000000..953cb50 --- /dev/null +++ b/luma/wm/zlib.h @@ -0,0 +1,1935 @@ +/* zlib.h -- interface of the 'zlib' general purpose compression library + version 1.2.13, October 13th, 2022 + + Copyright (C) 1995-2022 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + + + The data format used by the zlib library is described by RFCs (Request for + Comments) 1950 to 1952 in the files http://tools.ietf.org/html/rfc1950 + (zlib format), rfc1951 (deflate format) and rfc1952 (gzip format). +*/ + +#ifndef ZLIB_H +#define ZLIB_H + +#include "zconf.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ZLIB_VERSION "1.2.13" +#define ZLIB_VERNUM 0x12d0 +#define ZLIB_VER_MAJOR 1 +#define ZLIB_VER_MINOR 2 +#define ZLIB_VER_REVISION 13 +#define ZLIB_VER_SUBREVISION 0 + +/* + The 'zlib' compression library provides in-memory compression and + decompression functions, including integrity checks of the uncompressed data. + This version of the library supports only one compression method (deflation) + but other algorithms will be added later and will have the same stream + interface. + + Compression can be done in a single step if the buffers are large enough, + or can be done by repeated calls of the compression function. In the latter + case, the application must provide more input and/or consume the output + (providing more output space) before each call. + + The compressed data format used by default by the in-memory functions is + the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped + around a deflate stream, which is itself documented in RFC 1951. + + The library also supports reading and writing files in gzip (.gz) format + with an interface similar to that of stdio using the functions that start + with "gz". The gzip format is different from the zlib format. gzip is a + gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. + + This library can optionally read and write gzip and raw deflate streams in + memory as well. + + The zlib format was designed to be compact and fast for use in memory + and on communications channels. The gzip format was designed for single- + file compression on file systems, has a larger header than zlib to maintain + directory information, and uses a different, slower check method than zlib. + + The library does not install any signal handler. The decoder checks + the consistency of the compressed data, so the library should never crash + even in the case of corrupted input. +*/ + +typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size)); +typedef void (*free_func) OF((voidpf opaque, voidpf address)); + +struct internal_state; + +typedef struct z_stream_s { + z_const Bytef *next_in; /* next input byte */ + uInt avail_in; /* number of bytes available at next_in */ + uLong total_in; /* total number of input bytes read so far */ + + Bytef *next_out; /* next output byte will go here */ + uInt avail_out; /* remaining free space at next_out */ + uLong total_out; /* total number of bytes output so far */ + + z_const char *msg; /* last error message, NULL if no error */ + struct internal_state FAR *state; /* not visible by applications */ + + alloc_func zalloc; /* used to allocate the internal state */ + free_func zfree; /* used to free the internal state */ + voidpf opaque; /* private data object passed to zalloc and zfree */ + + int data_type; /* best guess about the data type: binary or text + for deflate, or the decoding state for inflate */ + uLong adler; /* Adler-32 or CRC-32 value of the uncompressed data */ + uLong reserved; /* reserved for future use */ +} z_stream; + +typedef z_stream FAR *z_streamp; + +/* + gzip header information passed to and from zlib routines. See RFC 1952 + for more details on the meanings of these fields. +*/ +typedef struct gz_header_s { + int text; /* true if compressed data believed to be text */ + uLong time; /* modification time */ + int xflags; /* extra flags (not used when writing a gzip file) */ + int os; /* operating system */ + Bytef *extra; /* pointer to extra field or Z_NULL if none */ + uInt extra_len; /* extra field length (valid if extra != Z_NULL) */ + uInt extra_max; /* space at extra (only when reading header) */ + Bytef *name; /* pointer to zero-terminated file name or Z_NULL */ + uInt name_max; /* space at name (only when reading header) */ + Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */ + uInt comm_max; /* space at comment (only when reading header) */ + int hcrc; /* true if there was or will be a header crc */ + int done; /* true when done reading gzip header (not used + when writing a gzip file) */ +} gz_header; + +typedef gz_header FAR *gz_headerp; + +/* + The application must update next_in and avail_in when avail_in has dropped + to zero. It must update next_out and avail_out when avail_out has dropped + to zero. The application must initialize zalloc, zfree and opaque before + calling the init function. All other fields are set by the compression + library and must not be updated by the application. + + The opaque value provided by the application will be passed as the first + parameter for calls of zalloc and zfree. This can be useful for custom + memory management. The compression library attaches no meaning to the + opaque value. + + zalloc must return Z_NULL if there is not enough memory for the object. + If zlib is used in a multi-threaded application, zalloc and zfree must be + thread safe. In that case, zlib is thread-safe. When zalloc and zfree are + Z_NULL on entry to the initialization function, they are set to internal + routines that use the standard library functions malloc() and free(). + + On 16-bit systems, the functions zalloc and zfree must be able to allocate + exactly 65536 bytes, but will not be required to allocate more than this if + the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, pointers + returned by zalloc for objects of exactly 65536 bytes *must* have their + offset normalized to zero. The default allocation function provided by this + library ensures this (see zutil.c). To reduce memory requirements and avoid + any allocation of 64K objects, at the expense of compression ratio, compile + the library with -DMAX_WBITS=14 (see zconf.h). + + The fields total_in and total_out can be used for statistics or progress + reports. After compression, total_in holds the total size of the + uncompressed data and may be saved for use by the decompressor (particularly + if the decompressor wants to decompress everything in a single step). +*/ + + /* constants */ + +#define Z_NO_FLUSH 0 +#define Z_PARTIAL_FLUSH 1 +#define Z_SYNC_FLUSH 2 +#define Z_FULL_FLUSH 3 +#define Z_FINISH 4 +#define Z_BLOCK 5 +#define Z_TREES 6 +/* Allowed flush values; see deflate() and inflate() below for details */ + +#define Z_OK 0 +#define Z_STREAM_END 1 +#define Z_NEED_DICT 2 +#define Z_ERRNO (-1) +#define Z_STREAM_ERROR (-2) +#define Z_DATA_ERROR (-3) +#define Z_MEM_ERROR (-4) +#define Z_BUF_ERROR (-5) +#define Z_VERSION_ERROR (-6) +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + +#define Z_NO_COMPRESSION 0 +#define Z_BEST_SPEED 1 +#define Z_BEST_COMPRESSION 9 +#define Z_DEFAULT_COMPRESSION (-1) +/* compression levels */ + +#define Z_FILTERED 1 +#define Z_HUFFMAN_ONLY 2 +#define Z_RLE 3 +#define Z_FIXED 4 +#define Z_DEFAULT_STRATEGY 0 +/* compression strategy; see deflateInit2() below for details */ + +#define Z_BINARY 0 +#define Z_TEXT 1 +#define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */ +#define Z_UNKNOWN 2 +/* Possible values of the data_type field for deflate() */ + +#define Z_DEFLATED 8 +/* The deflate compression method (the only one supported in this version) */ + +#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ + +#define zlib_version zlibVersion() +/* for compatibility with versions < 1.0.2 */ + + + /* basic functions */ + +ZEXTERN const char * ZEXPORT zlibVersion OF((void)); +/* The application can compare zlibVersion and ZLIB_VERSION for consistency. + If the first character differs, the library code actually used is not + compatible with the zlib.h header file used by the application. This check + is automatically made by deflateInit and inflateInit. + */ + +/* +ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); + + Initializes the internal stream state for compression. The fields + zalloc, zfree and opaque must be initialized before by the caller. If + zalloc and zfree are set to Z_NULL, deflateInit updates them to use default + allocation functions. + + The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: + 1 gives best speed, 9 gives best compression, 0 gives no compression at all + (the input data is simply copied a block at a time). Z_DEFAULT_COMPRESSION + requests a default compromise between speed and compression (currently + equivalent to level 6). + + deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_STREAM_ERROR if level is not a valid compression level, or + Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible + with the version assumed by the caller (ZLIB_VERSION). msg is set to null + if there is no error message. deflateInit does not perform any compression: + this will be done by deflate(). +*/ + + +ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); +/* + deflate compresses as much data as possible, and stops when the input + buffer becomes empty or the output buffer becomes full. It may introduce + some output latency (reading input without producing any output) except when + forced to flush. + + The detailed semantics are as follows. deflate performs one or both of the + following actions: + + - Compress more input starting at next_in and update next_in and avail_in + accordingly. If not all input can be processed (because there is not + enough room in the output buffer), next_in and avail_in are updated and + processing will resume at this point for the next call of deflate(). + + - Generate more output starting at next_out and update next_out and avail_out + accordingly. This action is forced if the parameter flush is non zero. + Forcing flush frequently degrades the compression ratio, so this parameter + should be set only when necessary. Some output may be provided even if + flush is zero. + + Before the call of deflate(), the application should ensure that at least + one of the actions is possible, by providing more input and/or consuming more + output, and updating avail_in or avail_out accordingly; avail_out should + never be zero before the call. The application can consume the compressed + output when it wants, for example when the output buffer is full (avail_out + == 0), or after each call of deflate(). If deflate returns Z_OK and with + zero avail_out, it must be called again after making room in the output + buffer because there might be more output pending. See deflatePending(), + which can be used if desired to determine whether or not there is more output + in that case. + + Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to + decide how much data to accumulate before producing output, in order to + maximize compression. + + If the parameter flush is set to Z_SYNC_FLUSH, all pending output is + flushed to the output buffer and the output is aligned on a byte boundary, so + that the decompressor can get all input data available so far. (In + particular avail_in is zero after the call if enough output space has been + provided before the call.) Flushing may degrade compression for some + compression algorithms and so it should be used only when necessary. This + completes the current deflate block and follows it with an empty stored block + that is three bits plus filler bits to the next byte, followed by four bytes + (00 00 ff ff). + + If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the + output buffer, but the output is not aligned to a byte boundary. All of the + input data so far will be available to the decompressor, as for Z_SYNC_FLUSH. + This completes the current deflate block and follows it with an empty fixed + codes block that is 10 bits long. This assures that enough bytes are output + in order for the decompressor to finish the block before the empty fixed + codes block. + + If flush is set to Z_BLOCK, a deflate block is completed and emitted, as + for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to + seven bits of the current block are held to be written as the next byte after + the next deflate block is completed. In this case, the decompressor may not + be provided enough bits at this point in order to complete decompression of + the data provided so far to the compressor. It may need to wait for the next + block to be emitted. This is for advanced applications that need to control + the emission of deflate blocks. + + If flush is set to Z_FULL_FLUSH, all output is flushed as with + Z_SYNC_FLUSH, and the compression state is reset so that decompression can + restart from this point if previous compressed data has been damaged or if + random access is desired. Using Z_FULL_FLUSH too often can seriously degrade + compression. + + If deflate returns with avail_out == 0, this function must be called again + with the same value of the flush parameter and more output space (updated + avail_out), until the flush is complete (deflate returns with non-zero + avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that + avail_out is greater than six to avoid repeated flush markers due to + avail_out == 0 on return. + + If the parameter flush is set to Z_FINISH, pending input is processed, + pending output is flushed and deflate returns with Z_STREAM_END if there was + enough output space. If deflate returns with Z_OK or Z_BUF_ERROR, this + function must be called again with Z_FINISH and more output space (updated + avail_out) but no more input data, until it returns with Z_STREAM_END or an + error. After deflate has returned Z_STREAM_END, the only possible operations + on the stream are deflateReset or deflateEnd. + + Z_FINISH can be used in the first deflate call after deflateInit if all the + compression is to be done in a single step. In order to complete in one + call, avail_out must be at least the value returned by deflateBound (see + below). Then deflate is guaranteed to return Z_STREAM_END. If not enough + output space is provided, deflate will not return Z_STREAM_END, and it must + be called again as described above. + + deflate() sets strm->adler to the Adler-32 checksum of all input read + so far (that is, total_in bytes). If a gzip stream is being generated, then + strm->adler will be the CRC-32 checksum of the input read so far. (See + deflateInit2 below.) + + deflate() may update strm->data_type if it can make a good guess about + the input data type (Z_BINARY or Z_TEXT). If in doubt, the data is + considered binary. This field is only for information purposes and does not + affect the compression algorithm in any manner. + + deflate() returns Z_OK if some progress has been made (more input + processed or more output produced), Z_STREAM_END if all input has been + consumed and all output has been produced (only when flush is set to + Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example + if next_in or next_out was Z_NULL or the state was inadvertently written over + by the application), or Z_BUF_ERROR if no progress is possible (for example + avail_in or avail_out was zero). Note that Z_BUF_ERROR is not fatal, and + deflate() can be called again with more input and more output space to + continue compressing. +*/ + + +ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm)); +/* + All dynamically allocated data structures for this stream are freed. + This function discards any unprocessed input and does not flush any pending + output. + + deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the + stream state was inconsistent, Z_DATA_ERROR if the stream was freed + prematurely (some input or output was discarded). In the error case, msg + may be set but then points to a static string (which must not be + deallocated). +*/ + + +/* +ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); + + Initializes the internal stream state for decompression. The fields + next_in, avail_in, zalloc, zfree and opaque must be initialized before by + the caller. In the current version of inflate, the provided input is not + read or consumed. The allocation of a sliding window will be deferred to + the first call of inflate (if the decompression does not complete on the + first call). If zalloc and zfree are set to Z_NULL, inflateInit updates + them to use default allocation functions. + + inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_VERSION_ERROR if the zlib library version is incompatible with the + version assumed by the caller, or Z_STREAM_ERROR if the parameters are + invalid, such as a null pointer to the structure. msg is set to null if + there is no error message. inflateInit does not perform any decompression. + Actual decompression will be done by inflate(). So next_in, and avail_in, + next_out, and avail_out are unused and unchanged. The current + implementation of inflateInit() does not process any header information -- + that is deferred until inflate() is called. +*/ + + +ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); +/* + inflate decompresses as much data as possible, and stops when the input + buffer becomes empty or the output buffer becomes full. It may introduce + some output latency (reading input without producing any output) except when + forced to flush. + + The detailed semantics are as follows. inflate performs one or both of the + following actions: + + - Decompress more input starting at next_in and update next_in and avail_in + accordingly. If not all input can be processed (because there is not + enough room in the output buffer), then next_in and avail_in are updated + accordingly, and processing will resume at this point for the next call of + inflate(). + + - Generate more output starting at next_out and update next_out and avail_out + accordingly. inflate() provides as much output as possible, until there is + no more input data or no more space in the output buffer (see below about + the flush parameter). + + Before the call of inflate(), the application should ensure that at least + one of the actions is possible, by providing more input and/or consuming more + output, and updating the next_* and avail_* values accordingly. If the + caller of inflate() does not provide both available input and available + output space, it is possible that there will be no progress made. The + application can consume the uncompressed output when it wants, for example + when the output buffer is full (avail_out == 0), or after each call of + inflate(). If inflate returns Z_OK and with zero avail_out, it must be + called again after making room in the output buffer because there might be + more output pending. + + The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH, + Z_BLOCK, or Z_TREES. Z_SYNC_FLUSH requests that inflate() flush as much + output as possible to the output buffer. Z_BLOCK requests that inflate() + stop if and when it gets to the next deflate block boundary. When decoding + the zlib or gzip format, this will cause inflate() to return immediately + after the header and before the first block. When doing a raw inflate, + inflate() will go ahead and process the first block, and will return when it + gets to the end of that block, or when it runs out of data. + + The Z_BLOCK option assists in appending to or combining deflate streams. + To assist in this, on return inflate() always sets strm->data_type to the + number of unused bits in the last byte taken from strm->next_in, plus 64 if + inflate() is currently decoding the last block in the deflate stream, plus + 128 if inflate() returned immediately after decoding an end-of-block code or + decoding the complete header up to just before the first byte of the deflate + stream. The end-of-block will not be indicated until all of the uncompressed + data from that block has been written to strm->next_out. The number of + unused bits may in general be greater than seven, except when bit 7 of + data_type is set, in which case the number of unused bits will be less than + eight. data_type is set as noted here every time inflate() returns for all + flush options, and so can be used to determine the amount of currently + consumed input in bits. + + The Z_TREES option behaves as Z_BLOCK does, but it also returns when the + end of each deflate block header is reached, before any actual data in that + block is decoded. This allows the caller to determine the length of the + deflate block header for later use in random access within a deflate block. + 256 is added to the value of strm->data_type when inflate() returns + immediately after reaching the end of the deflate block header. + + inflate() should normally be called until it returns Z_STREAM_END or an + error. However if all decompression is to be performed in a single step (a + single call of inflate), the parameter flush should be set to Z_FINISH. In + this case all pending input is processed and all pending output is flushed; + avail_out must be large enough to hold all of the uncompressed data for the + operation to complete. (The size of the uncompressed data may have been + saved by the compressor for this purpose.) The use of Z_FINISH is not + required to perform an inflation in one step. However it may be used to + inform inflate that a faster approach can be used for the single inflate() + call. Z_FINISH also informs inflate to not maintain a sliding window if the + stream completes, which reduces inflate's memory footprint. If the stream + does not complete, either because not all of the stream is provided or not + enough output space is provided, then a sliding window will be allocated and + inflate() can be called again to continue the operation as if Z_NO_FLUSH had + been used. + + In this implementation, inflate() always flushes as much output as + possible to the output buffer, and always uses the faster approach on the + first call. So the effects of the flush parameter in this implementation are + on the return value of inflate() as noted below, when inflate() returns early + when Z_BLOCK or Z_TREES is used, and when inflate() avoids the allocation of + memory for a sliding window when Z_FINISH is used. + + If a preset dictionary is needed after this call (see inflateSetDictionary + below), inflate sets strm->adler to the Adler-32 checksum of the dictionary + chosen by the compressor and returns Z_NEED_DICT; otherwise it sets + strm->adler to the Adler-32 checksum of all output produced so far (that is, + total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described + below. At the end of the stream, inflate() checks that its computed Adler-32 + checksum is equal to that saved by the compressor and returns Z_STREAM_END + only if the checksum is correct. + + inflate() can decompress and check either zlib-wrapped or gzip-wrapped + deflate data. The header type is detected automatically, if requested when + initializing with inflateInit2(). Any information contained in the gzip + header is not retained unless inflateGetHeader() is used. When processing + gzip-wrapped deflate data, strm->adler32 is set to the CRC-32 of the output + produced so far. The CRC-32 is checked against the gzip trailer, as is the + uncompressed length, modulo 2^32. + + inflate() returns Z_OK if some progress has been made (more input processed + or more output produced), Z_STREAM_END if the end of the compressed data has + been reached and all uncompressed output has been produced, Z_NEED_DICT if a + preset dictionary is needed at this point, Z_DATA_ERROR if the input data was + corrupted (input stream not conforming to the zlib format or incorrect check + value, in which case strm->msg points to a string with a more specific + error), Z_STREAM_ERROR if the stream structure was inconsistent (for example + next_in or next_out was Z_NULL, or the state was inadvertently written over + by the application), Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR + if no progress was possible or if there was not enough room in the output + buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and + inflate() can be called again with more input and more output space to + continue decompressing. If Z_DATA_ERROR is returned, the application may + then call inflateSync() to look for a good compression block if a partial + recovery of the data is to be attempted. +*/ + + +ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm)); +/* + All dynamically allocated data structures for this stream are freed. + This function discards any unprocessed input and does not flush any pending + output. + + inflateEnd returns Z_OK if success, or Z_STREAM_ERROR if the stream state + was inconsistent. +*/ + + + /* Advanced functions */ + +/* + The following functions are needed only in some special applications. +*/ + +/* +ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, + int level, + int method, + int windowBits, + int memLevel, + int strategy)); + + This is another version of deflateInit with more compression options. The + fields zalloc, zfree and opaque must be initialized before by the caller. + + The method parameter is the compression method. It must be Z_DEFLATED in + this version of the library. + + The windowBits parameter is the base two logarithm of the window size + (the size of the history buffer). It should be in the range 8..15 for this + version of the library. Larger values of this parameter result in better + compression at the expense of memory usage. The default value is 15 if + deflateInit is used instead. + + For the current implementation of deflate(), a windowBits value of 8 (a + window size of 256 bytes) is not supported. As a result, a request for 8 + will result in 9 (a 512-byte window). In that case, providing 8 to + inflateInit2() will result in an error when the zlib header with 9 is + checked against the initialization of inflate(). The remedy is to not use 8 + with deflateInit2() with this initialization, or at least in that case use 9 + with inflateInit2(). + + windowBits can also be -8..-15 for raw deflate. In this case, -windowBits + determines the window size. deflate() will then generate raw deflate data + with no zlib header or trailer, and will not compute a check value. + + windowBits can also be greater than 15 for optional gzip encoding. Add + 16 to windowBits to write a simple gzip header and trailer around the + compressed data instead of a zlib wrapper. The gzip header will have no + file name, no extra data, no comment, no modification time (set to zero), no + header crc, and the operating system will be set to the appropriate value, + if the operating system was determined at compile time. If a gzip stream is + being written, strm->adler is a CRC-32 instead of an Adler-32. + + For raw deflate or gzip encoding, a request for a 256-byte window is + rejected as invalid, since only the zlib header provides a means of + transmitting the window size to the decompressor. + + The memLevel parameter specifies how much memory should be allocated + for the internal compression state. memLevel=1 uses minimum memory but is + slow and reduces compression ratio; memLevel=9 uses maximum memory for + optimal speed. The default value is 8. See zconf.h for total memory usage + as a function of windowBits and memLevel. + + The strategy parameter is used to tune the compression algorithm. Use the + value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a + filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no + string match), or Z_RLE to limit match distances to one (run-length + encoding). Filtered data consists mostly of small values with a somewhat + random distribution. In this case, the compression algorithm is tuned to + compress them better. The effect of Z_FILTERED is to force more Huffman + coding and less string matching; it is somewhat intermediate between + Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as + fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data. The + strategy parameter only affects the compression ratio but not the + correctness of the compressed output even if it is not set appropriately. + Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler + decoder for special applications. + + deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid + method), or Z_VERSION_ERROR if the zlib library version (zlib_version) is + incompatible with the version assumed by the caller (ZLIB_VERSION). msg is + set to null if there is no error message. deflateInit2 does not perform any + compression: this will be done by deflate(). +*/ + +ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, + const Bytef *dictionary, + uInt dictLength)); +/* + Initializes the compression dictionary from the given byte sequence + without producing any compressed output. When using the zlib format, this + function must be called immediately after deflateInit, deflateInit2 or + deflateReset, and before any call of deflate. When doing raw deflate, this + function must be called either before any call of deflate, or immediately + after the completion of a deflate block, i.e. after all input has been + consumed and all output has been delivered when using any of the flush + options Z_BLOCK, Z_PARTIAL_FLUSH, Z_SYNC_FLUSH, or Z_FULL_FLUSH. The + compressor and decompressor must use exactly the same dictionary (see + inflateSetDictionary). + + The dictionary should consist of strings (byte sequences) that are likely + to be encountered later in the data to be compressed, with the most commonly + used strings preferably put towards the end of the dictionary. Using a + dictionary is most useful when the data to be compressed is short and can be + predicted with good accuracy; the data can then be compressed better than + with the default empty dictionary. + + Depending on the size of the compression data structures selected by + deflateInit or deflateInit2, a part of the dictionary may in effect be + discarded, for example if the dictionary is larger than the window size + provided in deflateInit or deflateInit2. Thus the strings most likely to be + useful should be put at the end of the dictionary, not at the front. In + addition, the current implementation of deflate will use at most the window + size minus 262 bytes of the provided dictionary. + + Upon return of this function, strm->adler is set to the Adler-32 value + of the dictionary; the decompressor may later use this value to determine + which dictionary has been used by the compressor. (The Adler-32 value + applies to the whole dictionary even if only a subset of the dictionary is + actually used by the compressor.) If a raw deflate was requested, then the + Adler-32 value is not computed and strm->adler is not set. + + deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a + parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is + inconsistent (for example if deflate has already been called for this stream + or if not at a block boundary for raw deflate). deflateSetDictionary does + not perform any compression: this will be done by deflate(). +*/ + +ZEXTERN int ZEXPORT deflateGetDictionary OF((z_streamp strm, + Bytef *dictionary, + uInt *dictLength)); +/* + Returns the sliding dictionary being maintained by deflate. dictLength is + set to the number of bytes in the dictionary, and that many bytes are copied + to dictionary. dictionary must have enough space, where 32768 bytes is + always enough. If deflateGetDictionary() is called with dictionary equal to + Z_NULL, then only the dictionary length is returned, and nothing is copied. + Similarly, if dictLength is Z_NULL, then it is not set. + + deflateGetDictionary() may return a length less than the window size, even + when more than the window size in input has been provided. It may return up + to 258 bytes less in that case, due to how zlib's implementation of deflate + manages the sliding window and lookahead for matches, where matches can be + up to 258 bytes long. If the application needs the last window-size bytes of + input, then that would need to be saved by the application outside of zlib. + + deflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the + stream state is inconsistent. +*/ + +ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, + z_streamp source)); +/* + Sets the destination stream as a complete copy of the source stream. + + This function can be useful when several compression strategies will be + tried, for example when there are several ways of pre-processing the input + data with a filter. The streams that will be discarded should then be freed + by calling deflateEnd. Note that deflateCopy duplicates the internal + compression state which can be quite large, so this strategy is slow and can + consume lots of memory. + + deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + (such as zalloc being Z_NULL). msg is left unchanged in both source and + destination. +*/ + +ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm)); +/* + This function is equivalent to deflateEnd followed by deflateInit, but + does not free and reallocate the internal compression state. The stream + will leave the compression level and any other attributes that may have been + set unchanged. + + deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL). +*/ + +ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, + int level, + int strategy)); +/* + Dynamically update the compression level and compression strategy. The + interpretation of level and strategy is as in deflateInit2(). This can be + used to switch between compression and straight copy of the input data, or + to switch to a different kind of input data requiring a different strategy. + If the compression approach (which is a function of the level) or the + strategy is changed, and if there have been any deflate() calls since the + state was initialized or reset, then the input available so far is + compressed with the old level and strategy using deflate(strm, Z_BLOCK). + There are three approaches for the compression levels 0, 1..3, and 4..9 + respectively. The new level and strategy will take effect at the next call + of deflate(). + + If a deflate(strm, Z_BLOCK) is performed by deflateParams(), and it does + not have enough output space to complete, then the parameter change will not + take effect. In this case, deflateParams() can be called again with the + same parameters and more output space to try again. + + In order to assure a change in the parameters on the first try, the + deflate stream should be flushed using deflate() with Z_BLOCK or other flush + request until strm.avail_out is not zero, before calling deflateParams(). + Then no more input data should be provided before the deflateParams() call. + If this is done, the old level and strategy will be applied to the data + compressed before deflateParams(), and the new level and strategy will be + applied to the the data compressed after deflateParams(). + + deflateParams returns Z_OK on success, Z_STREAM_ERROR if the source stream + state was inconsistent or if a parameter was invalid, or Z_BUF_ERROR if + there was not enough output space to complete the compression of the + available input data before a change in the strategy or approach. Note that + in the case of a Z_BUF_ERROR, the parameters are not changed. A return + value of Z_BUF_ERROR is not fatal, in which case deflateParams() can be + retried with more output space. +*/ + +ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm, + int good_length, + int max_lazy, + int nice_length, + int max_chain)); +/* + Fine tune deflate's internal compression parameters. This should only be + used by someone who understands the algorithm used by zlib's deflate for + searching for the best matching string, and even then only by the most + fanatic optimizer trying to squeeze out the last compressed bit for their + specific input data. Read the deflate.c source code for the meaning of the + max_lazy, good_length, nice_length, and max_chain parameters. + + deflateTune() can be called after deflateInit() or deflateInit2(), and + returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream. + */ + +ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm, + uLong sourceLen)); +/* + deflateBound() returns an upper bound on the compressed size after + deflation of sourceLen bytes. It must be called after deflateInit() or + deflateInit2(), and after deflateSetHeader(), if used. This would be used + to allocate an output buffer for deflation in a single pass, and so would be + called before deflate(). If that first deflate() call is provided the + sourceLen input bytes, an output buffer allocated to the size returned by + deflateBound(), and the flush value Z_FINISH, then deflate() is guaranteed + to return Z_STREAM_END. Note that it is possible for the compressed size to + be larger than the value returned by deflateBound() if flush options other + than Z_FINISH or Z_NO_FLUSH are used. +*/ + +ZEXTERN int ZEXPORT deflatePending OF((z_streamp strm, + unsigned *pending, + int *bits)); +/* + deflatePending() returns the number of bytes and bits of output that have + been generated, but not yet provided in the available output. The bytes not + provided would be due to the available output space having being consumed. + The number of bits of output not provided are between 0 and 7, where they + await more bits to join them in order to fill out a full byte. If pending + or bits are Z_NULL, then those values are not set. + + deflatePending returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. + */ + +ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, + int bits, + int value)); +/* + deflatePrime() inserts bits in the deflate output stream. The intent + is that this function is used to start off the deflate output with the bits + leftover from a previous deflate stream when appending to it. As such, this + function can only be used for raw deflate, and must be used before the first + deflate() call after a deflateInit2() or deflateReset(). bits must be less + than or equal to 16, and that many of the least significant bits of value + will be inserted in the output. + + deflatePrime returns Z_OK if success, Z_BUF_ERROR if there was not enough + room in the internal buffer to insert the bits, or Z_STREAM_ERROR if the + source stream state was inconsistent. +*/ + +ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm, + gz_headerp head)); +/* + deflateSetHeader() provides gzip header information for when a gzip + stream is requested by deflateInit2(). deflateSetHeader() may be called + after deflateInit2() or deflateReset() and before the first call of + deflate(). The text, time, os, extra field, name, and comment information + in the provided gz_header structure are written to the gzip header (xflag is + ignored -- the extra flags are set according to the compression level). The + caller must assure that, if not Z_NULL, name and comment are terminated with + a zero byte, and that if extra is not Z_NULL, that extra_len bytes are + available there. If hcrc is true, a gzip header crc is included. Note that + the current versions of the command-line version of gzip (up through version + 1.3.x) do not support header crc's, and will report that it is a "multi-part + gzip file" and give up. + + If deflateSetHeader is not used, the default gzip header has text false, + the time set to zero, and os set to 255, with no extra, name, or comment + fields. The gzip header is returned to the default state by deflateReset(). + + deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +/* +ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, + int windowBits)); + + This is another version of inflateInit with an extra parameter. The + fields next_in, avail_in, zalloc, zfree and opaque must be initialized + before by the caller. + + The windowBits parameter is the base two logarithm of the maximum window + size (the size of the history buffer). It should be in the range 8..15 for + this version of the library. The default value is 15 if inflateInit is used + instead. windowBits must be greater than or equal to the windowBits value + provided to deflateInit2() while compressing, or it must be equal to 15 if + deflateInit2() was not used. If a compressed stream with a larger window + size is given as input, inflate() will return with the error code + Z_DATA_ERROR instead of trying to allocate a larger window. + + windowBits can also be zero to request that inflate use the window size in + the zlib header of the compressed stream. + + windowBits can also be -8..-15 for raw inflate. In this case, -windowBits + determines the window size. inflate() will then process raw deflate data, + not looking for a zlib or gzip header, not generating a check value, and not + looking for any check values for comparison at the end of the stream. This + is for use with other formats that use the deflate compressed data format + such as zip. Those formats provide their own check values. If a custom + format is developed using the raw deflate format for compressed data, it is + recommended that a check value such as an Adler-32 or a CRC-32 be applied to + the uncompressed data as is done in the zlib, gzip, and zip formats. For + most applications, the zlib format should be used as is. Note that comments + above on the use in deflateInit2() applies to the magnitude of windowBits. + + windowBits can also be greater than 15 for optional gzip decoding. Add + 32 to windowBits to enable zlib and gzip decoding with automatic header + detection, or add 16 to decode only the gzip format (the zlib format will + return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is a + CRC-32 instead of an Adler-32. Unlike the gunzip utility and gzread() (see + below), inflate() will *not* automatically decode concatenated gzip members. + inflate() will return Z_STREAM_END at the end of the gzip member. The state + would need to be reset to continue decoding a subsequent gzip member. This + *must* be done if there is more data after a gzip member, in order for the + decompression to be compliant with the gzip standard (RFC 1952). + + inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_VERSION_ERROR if the zlib library version is incompatible with the + version assumed by the caller, or Z_STREAM_ERROR if the parameters are + invalid, such as a null pointer to the structure. msg is set to null if + there is no error message. inflateInit2 does not perform any decompression + apart from possibly reading the zlib header if present: actual decompression + will be done by inflate(). (So next_in and avail_in may be modified, but + next_out and avail_out are unused and unchanged.) The current implementation + of inflateInit2() does not process any header information -- that is + deferred until inflate() is called. +*/ + +ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, + const Bytef *dictionary, + uInt dictLength)); +/* + Initializes the decompression dictionary from the given uncompressed byte + sequence. This function must be called immediately after a call of inflate, + if that call returned Z_NEED_DICT. The dictionary chosen by the compressor + can be determined from the Adler-32 value returned by that call of inflate. + The compressor and decompressor must use exactly the same dictionary (see + deflateSetDictionary). For raw inflate, this function can be called at any + time to set the dictionary. If the provided dictionary is smaller than the + window and there is already data in the window, then the provided dictionary + will amend what's there. The application must insure that the dictionary + that was used for compression is provided. + + inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a + parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is + inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the + expected one (incorrect Adler-32 value). inflateSetDictionary does not + perform any decompression: this will be done by subsequent calls of + inflate(). +*/ + +ZEXTERN int ZEXPORT inflateGetDictionary OF((z_streamp strm, + Bytef *dictionary, + uInt *dictLength)); +/* + Returns the sliding dictionary being maintained by inflate. dictLength is + set to the number of bytes in the dictionary, and that many bytes are copied + to dictionary. dictionary must have enough space, where 32768 bytes is + always enough. If inflateGetDictionary() is called with dictionary equal to + Z_NULL, then only the dictionary length is returned, and nothing is copied. + Similarly, if dictLength is Z_NULL, then it is not set. + + inflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the + stream state is inconsistent. +*/ + +ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); +/* + Skips invalid compressed data until a possible full flush point (see above + for the description of deflate with Z_FULL_FLUSH) can be found, or until all + available input is skipped. No output is provided. + + inflateSync searches for a 00 00 FF FF pattern in the compressed data. + All full flush points have this pattern, but not all occurrences of this + pattern are full flush points. + + inflateSync returns Z_OK if a possible full flush point has been found, + Z_BUF_ERROR if no more input was provided, Z_DATA_ERROR if no flush point + has been found, or Z_STREAM_ERROR if the stream structure was inconsistent. + In the success case, the application may save the current current value of + total_in which indicates where valid compressed data was found. In the + error case, the application may repeatedly call inflateSync, providing more + input each time, until success or end of the input data. +*/ + +ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest, + z_streamp source)); +/* + Sets the destination stream as a complete copy of the source stream. + + This function can be useful when randomly accessing a large stream. The + first pass through the stream can periodically record the inflate state, + allowing restarting inflate at those points when randomly accessing the + stream. + + inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + (such as zalloc being Z_NULL). msg is left unchanged in both source and + destination. +*/ + +ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm)); +/* + This function is equivalent to inflateEnd followed by inflateInit, + but does not free and reallocate the internal decompression state. The + stream will keep attributes that may have been set by inflateInit2. + + inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL). +*/ + +ZEXTERN int ZEXPORT inflateReset2 OF((z_streamp strm, + int windowBits)); +/* + This function is the same as inflateReset, but it also permits changing + the wrap and window size requests. The windowBits parameter is interpreted + the same as it is for inflateInit2. If the window size is changed, then the + memory allocated for the window is freed, and the window will be reallocated + by inflate() if needed. + + inflateReset2 returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL), or if + the windowBits parameter is invalid. +*/ + +ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm, + int bits, + int value)); +/* + This function inserts bits in the inflate input stream. The intent is + that this function is used to start inflating at a bit position in the + middle of a byte. The provided bits will be used before any bytes are used + from next_in. This function should only be used with raw inflate, and + should be used before the first inflate() call after inflateInit2() or + inflateReset(). bits must be less than or equal to 16, and that many of the + least significant bits of value will be inserted in the input. + + If bits is negative, then the input stream bit buffer is emptied. Then + inflatePrime() can be called again to put bits in the buffer. This is used + to clear out bits leftover after feeding inflate a block description prior + to feeding inflate codes. + + inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +ZEXTERN long ZEXPORT inflateMark OF((z_streamp strm)); +/* + This function returns two values, one in the lower 16 bits of the return + value, and the other in the remaining upper bits, obtained by shifting the + return value down 16 bits. If the upper value is -1 and the lower value is + zero, then inflate() is currently decoding information outside of a block. + If the upper value is -1 and the lower value is non-zero, then inflate is in + the middle of a stored block, with the lower value equaling the number of + bytes from the input remaining to copy. If the upper value is not -1, then + it is the number of bits back from the current bit position in the input of + the code (literal or length/distance pair) currently being processed. In + that case the lower value is the number of bytes already emitted for that + code. + + A code is being processed if inflate is waiting for more input to complete + decoding of the code, or if it has completed decoding but is waiting for + more output space to write the literal or match data. + + inflateMark() is used to mark locations in the input data for random + access, which may be at bit positions, and to note those cases where the + output of a code may span boundaries of random access blocks. The current + location in the input stream can be determined from avail_in and data_type + as noted in the description for the Z_BLOCK flush parameter for inflate. + + inflateMark returns the value noted above, or -65536 if the provided + source stream state was inconsistent. +*/ + +ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm, + gz_headerp head)); +/* + inflateGetHeader() requests that gzip header information be stored in the + provided gz_header structure. inflateGetHeader() may be called after + inflateInit2() or inflateReset(), and before the first call of inflate(). + As inflate() processes the gzip stream, head->done is zero until the header + is completed, at which time head->done is set to one. If a zlib stream is + being decoded, then head->done is set to -1 to indicate that there will be + no gzip header information forthcoming. Note that Z_BLOCK or Z_TREES can be + used to force inflate() to return immediately after header processing is + complete and before any actual data is decompressed. + + The text, time, xflags, and os fields are filled in with the gzip header + contents. hcrc is set to true if there is a header CRC. (The header CRC + was valid if done is set to one.) If extra is not Z_NULL, then extra_max + contains the maximum number of bytes to write to extra. Once done is true, + extra_len contains the actual extra field length, and extra contains the + extra field, or that field truncated if extra_max is less than extra_len. + If name is not Z_NULL, then up to name_max characters are written there, + terminated with a zero unless the length is greater than name_max. If + comment is not Z_NULL, then up to comm_max characters are written there, + terminated with a zero unless the length is greater than comm_max. When any + of extra, name, or comment are not Z_NULL and the respective field is not + present in the header, then that field is set to Z_NULL to signal its + absence. This allows the use of deflateSetHeader() with the returned + structure to duplicate the header. However if those fields are set to + allocated memory, then the application will need to save those pointers + elsewhere so that they can be eventually freed. + + If inflateGetHeader is not used, then the header information is simply + discarded. The header is always checked for validity, including the header + CRC if present. inflateReset() will reset the process to discard the header + information. The application would need to call inflateGetHeader() again to + retrieve the header from the next gzip stream. + + inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +/* +ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits, + unsigned char FAR *window)); + + Initialize the internal stream state for decompression using inflateBack() + calls. The fields zalloc, zfree and opaque in strm must be initialized + before the call. If zalloc and zfree are Z_NULL, then the default library- + derived memory allocation routines are used. windowBits is the base two + logarithm of the window size, in the range 8..15. window is a caller + supplied buffer of that size. Except for special applications where it is + assured that deflate was used with small window sizes, windowBits must be 15 + and a 32K byte window must be supplied to be able to decompress general + deflate streams. + + See inflateBack() for the usage of these routines. + + inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of + the parameters are invalid, Z_MEM_ERROR if the internal state could not be + allocated, or Z_VERSION_ERROR if the version of the library does not match + the version of the header file. +*/ + +typedef unsigned (*in_func) OF((void FAR *, + z_const unsigned char FAR * FAR *)); +typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned)); + +ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm, + in_func in, void FAR *in_desc, + out_func out, void FAR *out_desc)); +/* + inflateBack() does a raw inflate with a single call using a call-back + interface for input and output. This is potentially more efficient than + inflate() for file i/o applications, in that it avoids copying between the + output and the sliding window by simply making the window itself the output + buffer. inflate() can be faster on modern CPUs when used with large + buffers. inflateBack() trusts the application to not change the output + buffer passed by the output function, at least until inflateBack() returns. + + inflateBackInit() must be called first to allocate the internal state + and to initialize the state with the user-provided window buffer. + inflateBack() may then be used multiple times to inflate a complete, raw + deflate stream with each call. inflateBackEnd() is then called to free the + allocated state. + + A raw deflate stream is one with no zlib or gzip header or trailer. + This routine would normally be used in a utility that reads zip or gzip + files and writes out uncompressed files. The utility would decode the + header and process the trailer on its own, hence this routine expects only + the raw deflate stream to decompress. This is different from the default + behavior of inflate(), which expects a zlib header and trailer around the + deflate stream. + + inflateBack() uses two subroutines supplied by the caller that are then + called by inflateBack() for input and output. inflateBack() calls those + routines until it reads a complete deflate stream and writes out all of the + uncompressed data, or until it encounters an error. The function's + parameters and return types are defined above in the in_func and out_func + typedefs. inflateBack() will call in(in_desc, &buf) which should return the + number of bytes of provided input, and a pointer to that input in buf. If + there is no input available, in() must return zero -- buf is ignored in that + case -- and inflateBack() will return a buffer error. inflateBack() will + call out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. + out() should return zero on success, or non-zero on failure. If out() + returns non-zero, inflateBack() will return with an error. Neither in() nor + out() are permitted to change the contents of the window provided to + inflateBackInit(), which is also the buffer that out() uses to write from. + The length written by out() will be at most the window size. Any non-zero + amount of input may be provided by in(). + + For convenience, inflateBack() can be provided input on the first call by + setting strm->next_in and strm->avail_in. If that input is exhausted, then + in() will be called. Therefore strm->next_in must be initialized before + calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called + immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in + must also be initialized, and then if strm->avail_in is not zero, input will + initially be taken from strm->next_in[0 .. strm->avail_in - 1]. + + The in_desc and out_desc parameters of inflateBack() is passed as the + first parameter of in() and out() respectively when they are called. These + descriptors can be optionally used to pass any information that the caller- + supplied in() and out() functions need to do their job. + + On return, inflateBack() will set strm->next_in and strm->avail_in to + pass back any unused input that was provided by the last in() call. The + return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR + if in() or out() returned an error, Z_DATA_ERROR if there was a format error + in the deflate stream (in which case strm->msg is set to indicate the nature + of the error), or Z_STREAM_ERROR if the stream was not properly initialized. + In the case of Z_BUF_ERROR, an input or output error can be distinguished + using strm->next_in which will be Z_NULL only if in() returned an error. If + strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning + non-zero. (in() will always be called before out(), so strm->next_in is + assured to be defined if out() returns non-zero.) Note that inflateBack() + cannot return Z_OK. +*/ + +ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm)); +/* + All memory allocated by inflateBackInit() is freed. + + inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream + state was inconsistent. +*/ + +ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void)); +/* Return flags indicating compile-time options. + + Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: + 1.0: size of uInt + 3.2: size of uLong + 5.4: size of voidpf (pointer) + 7.6: size of z_off_t + + Compiler, assembler, and debug options: + 8: ZLIB_DEBUG + 9: ASMV or ASMINF -- use ASM code + 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention + 11: 0 (reserved) + + One-time table building (smaller code, but not thread-safe if true): + 12: BUILDFIXED -- build static block decoding tables when needed + 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed + 14,15: 0 (reserved) + + Library content (indicates missing functionality): + 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking + deflate code when not needed) + 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect + and decode gzip streams (to avoid linking crc code) + 18-19: 0 (reserved) + + Operation variations (changes in library functionality): + 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate + 21: FASTEST -- deflate algorithm with only one, lowest compression level + 22,23: 0 (reserved) + + The sprintf variant used by gzprintf (zero is best): + 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format + 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure! + 26: 0 = returns value, 1 = void -- 1 means inferred string length returned + + Remainder: + 27-31: 0 (reserved) + */ + +#ifndef Z_SOLO + + /* utility functions */ + +/* + The following utility functions are implemented on top of the basic + stream-oriented functions. To simplify the interface, some default options + are assumed (compression level and memory usage, standard memory allocation + functions). The source code of these utility functions can be modified if + you need special options. +*/ + +ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen)); +/* + Compresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total size + of the destination buffer, which must be at least the value returned by + compressBound(sourceLen). Upon exit, destLen is the actual size of the + compressed data. compress() is equivalent to compress2() with a level + parameter of Z_DEFAULT_COMPRESSION. + + compress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer. +*/ + +ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen, + int level)); +/* + Compresses the source buffer into the destination buffer. The level + parameter has the same meaning as in deflateInit. sourceLen is the byte + length of the source buffer. Upon entry, destLen is the total size of the + destination buffer, which must be at least the value returned by + compressBound(sourceLen). Upon exit, destLen is the actual size of the + compressed data. + + compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_BUF_ERROR if there was not enough room in the output buffer, + Z_STREAM_ERROR if the level parameter is invalid. +*/ + +ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen)); +/* + compressBound() returns an upper bound on the compressed size after + compress() or compress2() on sourceLen bytes. It would be used before a + compress() or compress2() call to allocate the destination buffer. +*/ + +ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen)); +/* + Decompresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total size + of the destination buffer, which must be large enough to hold the entire + uncompressed data. (The size of the uncompressed data must have been saved + previously by the compressor and transmitted to the decompressor by some + mechanism outside the scope of this compression library.) Upon exit, destLen + is the actual size of the uncompressed data. + + uncompress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. In + the case where there is not enough room, uncompress() will fill the output + buffer with the uncompressed data up to that point. +*/ + +ZEXTERN int ZEXPORT uncompress2 OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong *sourceLen)); +/* + Same as uncompress, except that sourceLen is a pointer, where the + length of the source is *sourceLen. On return, *sourceLen is the number of + source bytes consumed. +*/ + + /* gzip file access functions */ + +/* + This library supports reading and writing files in gzip (.gz) format with + an interface similar to that of stdio, using the functions that start with + "gz". The gzip format is different from the zlib format. gzip is a gzip + wrapper, documented in RFC 1952, wrapped around a deflate stream. +*/ + +typedef struct gzFile_s *gzFile; /* semi-opaque gzip file descriptor */ + +/* +ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); + + Open the gzip (.gz) file at path for reading and decompressing, or + compressing and writing. The mode parameter is as in fopen ("rb" or "wb") + but can also include a compression level ("wb9") or a strategy: 'f' for + filtered data as in "wb6f", 'h' for Huffman-only compression as in "wb1h", + 'R' for run-length encoding as in "wb1R", or 'F' for fixed code compression + as in "wb9F". (See the description of deflateInit2 for more information + about the strategy parameter.) 'T' will request transparent writing or + appending with no compression and not using the gzip format. + + "a" can be used instead of "w" to request that the gzip stream that will + be written be appended to the file. "+" will result in an error, since + reading and writing to the same gzip file is not supported. The addition of + "x" when writing will create the file exclusively, which fails if the file + already exists. On systems that support it, the addition of "e" when + reading or writing will set the flag to close the file on an execve() call. + + These functions, as well as gzip, will read and decode a sequence of gzip + streams in a file. The append function of gzopen() can be used to create + such a file. (Also see gzflush() for another way to do this.) When + appending, gzopen does not test whether the file begins with a gzip stream, + nor does it look for the end of the gzip streams to begin appending. gzopen + will simply append a gzip stream to the existing file. + + gzopen can be used to read a file which is not in gzip format; in this + case gzread will directly read from the file without decompression. When + reading, this will be detected automatically by looking for the magic two- + byte gzip header. + + gzopen returns NULL if the file could not be opened, if there was + insufficient memory to allocate the gzFile state, or if an invalid mode was + specified (an 'r', 'w', or 'a' was not provided, or '+' was provided). + errno can be checked to determine if the reason gzopen failed was that the + file could not be opened. +*/ + +ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); +/* + Associate a gzFile with the file descriptor fd. File descriptors are + obtained from calls like open, dup, creat, pipe or fileno (if the file has + been previously opened with fopen). The mode parameter is as in gzopen. + + The next call of gzclose on the returned gzFile will also close the file + descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor + fd. If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd, + mode);. The duplicated descriptor should be saved to avoid a leak, since + gzdopen does not close fd if it fails. If you are using fileno() to get the + file descriptor from a FILE *, then you will have to use dup() to avoid + double-close()ing the file descriptor. Both gzclose() and fclose() will + close the associated file descriptor, so they need to have different file + descriptors. + + gzdopen returns NULL if there was insufficient memory to allocate the + gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not + provided, or '+' was provided), or if fd is -1. The file descriptor is not + used until the next gz* read, write, seek, or close operation, so gzdopen + will not detect if fd is invalid (unless fd is -1). +*/ + +ZEXTERN int ZEXPORT gzbuffer OF((gzFile file, unsigned size)); +/* + Set the internal buffer size used by this library's functions for file to + size. The default buffer size is 8192 bytes. This function must be called + after gzopen() or gzdopen(), and before any other calls that read or write + the file. The buffer memory allocation is always deferred to the first read + or write. Three times that size in buffer space is allocated. A larger + buffer size of, for example, 64K or 128K bytes will noticeably increase the + speed of decompression (reading). + + The new buffer size also affects the maximum length for gzprintf(). + + gzbuffer() returns 0 on success, or -1 on failure, such as being called + too late. +*/ + +ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy)); +/* + Dynamically update the compression level and strategy for file. See the + description of deflateInit2 for the meaning of these parameters. Previously + provided data is flushed before applying the parameter changes. + + gzsetparams returns Z_OK if success, Z_STREAM_ERROR if the file was not + opened for writing, Z_ERRNO if there is an error writing the flushed data, + or Z_MEM_ERROR if there is a memory allocation error. +*/ + +ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len)); +/* + Read and decompress up to len uncompressed bytes from file into buf. If + the input file is not in gzip format, gzread copies the given number of + bytes into the buffer directly from the file. + + After reaching the end of a gzip stream in the input, gzread will continue + to read, looking for another gzip stream. Any number of gzip streams may be + concatenated in the input file, and will all be decompressed by gzread(). + If something other than a gzip stream is encountered after a gzip stream, + that remaining trailing garbage is ignored (and no error is returned). + + gzread can be used to read a gzip file that is being concurrently written. + Upon reaching the end of the input, gzread will return with the available + data. If the error code returned by gzerror is Z_OK or Z_BUF_ERROR, then + gzclearerr can be used to clear the end of file indicator in order to permit + gzread to be tried again. Z_OK indicates that a gzip stream was completed + on the last gzread. Z_BUF_ERROR indicates that the input file ended in the + middle of a gzip stream. Note that gzread does not return -1 in the event + of an incomplete gzip stream. This error is deferred until gzclose(), which + will return Z_BUF_ERROR if the last gzread ended in the middle of a gzip + stream. Alternatively, gzerror can be used before gzclose to detect this + case. + + gzread returns the number of uncompressed bytes actually read, less than + len for end of file, or -1 for error. If len is too large to fit in an int, + then nothing is read, -1 is returned, and the error state is set to + Z_STREAM_ERROR. +*/ + +ZEXTERN z_size_t ZEXPORT gzfread OF((voidp buf, z_size_t size, z_size_t nitems, + gzFile file)); +/* + Read and decompress up to nitems items of size size from file into buf, + otherwise operating as gzread() does. This duplicates the interface of + stdio's fread(), with size_t request and return types. If the library + defines size_t, then z_size_t is identical to size_t. If not, then z_size_t + is an unsigned integer type that can contain a pointer. + + gzfread() returns the number of full items read of size size, or zero if + the end of the file was reached and a full item could not be read, or if + there was an error. gzerror() must be consulted if zero is returned in + order to determine if there was an error. If the multiplication of size and + nitems overflows, i.e. the product does not fit in a z_size_t, then nothing + is read, zero is returned, and the error state is set to Z_STREAM_ERROR. + + In the event that the end of file is reached and only a partial item is + available at the end, i.e. the remaining uncompressed data length is not a + multiple of size, then the final partial item is nevertheless read into buf + and the end-of-file flag is set. The length of the partial item read is not + provided, but could be inferred from the result of gztell(). This behavior + is the same as the behavior of fread() implementations in common libraries, + but it prevents the direct use of gzfread() to read a concurrently written + file, resetting and retrying on end-of-file, when size is not 1. +*/ + +ZEXTERN int ZEXPORT gzwrite OF((gzFile file, voidpc buf, unsigned len)); +/* + Compress and write the len uncompressed bytes at buf to file. gzwrite + returns the number of uncompressed bytes written or 0 in case of error. +*/ + +ZEXTERN z_size_t ZEXPORT gzfwrite OF((voidpc buf, z_size_t size, + z_size_t nitems, gzFile file)); +/* + Compress and write nitems items of size size from buf to file, duplicating + the interface of stdio's fwrite(), with size_t request and return types. If + the library defines size_t, then z_size_t is identical to size_t. If not, + then z_size_t is an unsigned integer type that can contain a pointer. + + gzfwrite() returns the number of full items written of size size, or zero + if there was an error. If the multiplication of size and nitems overflows, + i.e. the product does not fit in a z_size_t, then nothing is written, zero + is returned, and the error state is set to Z_STREAM_ERROR. +*/ + +ZEXTERN int ZEXPORTVA gzprintf Z_ARG((gzFile file, const char *format, ...)); +/* + Convert, format, compress, and write the arguments (...) to file under + control of the string format, as in fprintf. gzprintf returns the number of + uncompressed bytes actually written, or a negative zlib error code in case + of error. The number of uncompressed bytes written is limited to 8191, or + one less than the buffer size given to gzbuffer(). The caller should assure + that this limit is not exceeded. If it is exceeded, then gzprintf() will + return an error (0) with nothing written. In this case, there may also be a + buffer overflow with unpredictable consequences, which is possible only if + zlib was compiled with the insecure functions sprintf() or vsprintf(), + because the secure snprintf() or vsnprintf() functions were not available. + This can be determined using zlibCompileFlags(). +*/ + +ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s)); +/* + Compress and write the given null-terminated string s to file, excluding + the terminating null character. + + gzputs returns the number of characters written, or -1 in case of error. +*/ + +ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len)); +/* + Read and decompress bytes from file into buf, until len-1 characters are + read, or until a newline character is read and transferred to buf, or an + end-of-file condition is encountered. If any characters are read or if len + is one, the string is terminated with a null character. If no characters + are read due to an end-of-file or len is less than one, then the buffer is + left untouched. + + gzgets returns buf which is a null-terminated string, or it returns NULL + for end-of-file or in case of error. If there was an error, the contents at + buf are indeterminate. +*/ + +ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c)); +/* + Compress and write c, converted to an unsigned char, into file. gzputc + returns the value that was written, or -1 in case of error. +*/ + +ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); +/* + Read and decompress one byte from file. gzgetc returns this byte or -1 + in case of end of file or error. This is implemented as a macro for speed. + As such, it does not do all of the checking the other functions do. I.e. + it does not check to see if file is NULL, nor whether the structure file + points to has been clobbered or not. +*/ + +ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file)); +/* + Push c back onto the stream for file to be read as the first character on + the next read. At least one character of push-back is always allowed. + gzungetc() returns the character pushed, or -1 on failure. gzungetc() will + fail if c is -1, and may fail if a character has been pushed but not read + yet. If gzungetc is used immediately after gzopen or gzdopen, at least the + output buffer size of pushed characters is allowed. (See gzbuffer above.) + The pushed character will be discarded if the stream is repositioned with + gzseek() or gzrewind(). +*/ + +ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush)); +/* + Flush all pending output to file. The parameter flush is as in the + deflate() function. The return value is the zlib error number (see function + gzerror below). gzflush is only permitted when writing. + + If the flush parameter is Z_FINISH, the remaining data is written and the + gzip stream is completed in the output. If gzwrite() is called again, a new + gzip stream will be started in the output. gzread() is able to read such + concatenated gzip streams. + + gzflush should be called only when strictly necessary because it will + degrade compression if called too often. +*/ + +/* +ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file, + z_off_t offset, int whence)); + + Set the starting position to offset relative to whence for the next gzread + or gzwrite on file. The offset represents a number of bytes in the + uncompressed data stream. The whence parameter is defined as in lseek(2); + the value SEEK_END is not supported. + + If the file is opened for reading, this function is emulated but can be + extremely slow. If the file is opened for writing, only forward seeks are + supported; gzseek then compresses a sequence of zeroes up to the new + starting position. + + gzseek returns the resulting offset location as measured in bytes from + the beginning of the uncompressed stream, or -1 in case of error, in + particular if the file is opened for writing and the new starting position + would be before the current position. +*/ + +ZEXTERN int ZEXPORT gzrewind OF((gzFile file)); +/* + Rewind file. This function is supported only for reading. + + gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET). +*/ + +/* +ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file)); + + Return the starting position for the next gzread or gzwrite on file. + This position represents a number of bytes in the uncompressed data stream, + and is zero when starting, even if appending or reading a gzip stream from + the middle of a file using gzdopen(). + + gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) +*/ + +/* +ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile file)); + + Return the current compressed (actual) read or write offset of file. This + offset includes the count of bytes that precede the gzip stream, for example + when appending or when using gzdopen() for reading. When reading, the + offset does not include as yet unused buffered input. This information can + be used for a progress indicator. On error, gzoffset() returns -1. +*/ + +ZEXTERN int ZEXPORT gzeof OF((gzFile file)); +/* + Return true (1) if the end-of-file indicator for file has been set while + reading, false (0) otherwise. Note that the end-of-file indicator is set + only if the read tried to go past the end of the input, but came up short. + Therefore, just like feof(), gzeof() may return false even if there is no + more data to read, in the event that the last read request was for the exact + number of bytes remaining in the input file. This will happen if the input + file size is an exact multiple of the buffer size. + + If gzeof() returns true, then the read functions will return no more data, + unless the end-of-file indicator is reset by gzclearerr() and the input file + has grown since the previous end of file was detected. +*/ + +ZEXTERN int ZEXPORT gzdirect OF((gzFile file)); +/* + Return true (1) if file is being copied directly while reading, or false + (0) if file is a gzip stream being decompressed. + + If the input file is empty, gzdirect() will return true, since the input + does not contain a gzip stream. + + If gzdirect() is used immediately after gzopen() or gzdopen() it will + cause buffers to be allocated to allow reading the file to determine if it + is a gzip file. Therefore if gzbuffer() is used, it should be called before + gzdirect(). + + When writing, gzdirect() returns true (1) if transparent writing was + requested ("wT" for the gzopen() mode), or false (0) otherwise. (Note: + gzdirect() is not needed when writing. Transparent writing must be + explicitly requested, so the application already knows the answer. When + linking statically, using gzdirect() will include all of the zlib code for + gzip file reading and decompression, which may not be desired.) +*/ + +ZEXTERN int ZEXPORT gzclose OF((gzFile file)); +/* + Flush all pending output for file, if necessary, close file and + deallocate the (de)compression state. Note that once file is closed, you + cannot call gzerror with file, since its structures have been deallocated. + gzclose must not be called more than once on the same file, just as free + must not be called more than once on the same allocation. + + gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a + file operation error, Z_MEM_ERROR if out of memory, Z_BUF_ERROR if the + last read ended in the middle of a gzip stream, or Z_OK on success. +*/ + +ZEXTERN int ZEXPORT gzclose_r OF((gzFile file)); +ZEXTERN int ZEXPORT gzclose_w OF((gzFile file)); +/* + Same as gzclose(), but gzclose_r() is only for use when reading, and + gzclose_w() is only for use when writing or appending. The advantage to + using these instead of gzclose() is that they avoid linking in zlib + compression or decompression code that is not used when only reading or only + writing respectively. If gzclose() is used, then both compression and + decompression code will be included the application when linking to a static + zlib library. +*/ + +ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum)); +/* + Return the error message for the last error which occurred on file. + errnum is set to zlib error number. If an error occurred in the file system + and not in the compression library, errnum is set to Z_ERRNO and the + application may consult errno to get the exact error code. + + The application must not modify the returned string. Future calls to + this function may invalidate the previously returned string. If file is + closed, then the string previously returned by gzerror will no longer be + available. + + gzerror() should be used to distinguish errors from end-of-file for those + functions above that do not distinguish those cases in their return values. +*/ + +ZEXTERN void ZEXPORT gzclearerr OF((gzFile file)); +/* + Clear the error and end-of-file flags for file. This is analogous to the + clearerr() function in stdio. This is useful for continuing to read a gzip + file that is being written concurrently. +*/ + +#endif /* !Z_SOLO */ + + /* checksum functions */ + +/* + These functions are not related to compression but are exported + anyway because they might be useful in applications using the compression + library. +*/ + +ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); +/* + Update a running Adler-32 checksum with the bytes buf[0..len-1] and + return the updated checksum. An Adler-32 value is in the range of a 32-bit + unsigned integer. If buf is Z_NULL, this function returns the required + initial value for the checksum. + + An Adler-32 checksum is almost as reliable as a CRC-32 but can be computed + much faster. + + Usage example: + + uLong adler = adler32(0L, Z_NULL, 0); + + while (read_buffer(buffer, length) != EOF) { + adler = adler32(adler, buffer, length); + } + if (adler != original_adler) error(); +*/ + +ZEXTERN uLong ZEXPORT adler32_z OF((uLong adler, const Bytef *buf, + z_size_t len)); +/* + Same as adler32(), but with a size_t length. +*/ + +/* +ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2, + z_off_t len2)); + + Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 + and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for + each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of + seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. Note + that the z_off_t type (like off_t) is a signed integer. If len2 is + negative, the result has no meaning or utility. +*/ + +ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); +/* + Update a running CRC-32 with the bytes buf[0..len-1] and return the + updated CRC-32. A CRC-32 value is in the range of a 32-bit unsigned integer. + If buf is Z_NULL, this function returns the required initial value for the + crc. Pre- and post-conditioning (one's complement) is performed within this + function so it shouldn't be done by the application. + + Usage example: + + uLong crc = crc32(0L, Z_NULL, 0); + + while (read_buffer(buffer, length) != EOF) { + crc = crc32(crc, buffer, length); + } + if (crc != original_crc) error(); +*/ + +ZEXTERN uLong ZEXPORT crc32_z OF((uLong crc, const Bytef *buf, + z_size_t len)); +/* + Same as crc32(), but with a size_t length. +*/ + +/* +ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2)); + + Combine two CRC-32 check values into one. For two sequences of bytes, + seq1 and seq2 with lengths len1 and len2, CRC-32 check values were + calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 + check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and + len2. +*/ + +/* +ZEXTERN uLong ZEXPORT crc32_combine_gen OF((z_off_t len2)); + + Return the operator corresponding to length len2, to be used with + crc32_combine_op(). +*/ + +ZEXTERN uLong ZEXPORT crc32_combine_op OF((uLong crc1, uLong crc2, uLong op)); +/* + Give the same result as crc32_combine(), using op in place of len2. op is + is generated from len2 by crc32_combine_gen(). This will be faster than + crc32_combine() if the generated op is used more than once. +*/ + + + /* various hacks, don't look :) */ + +/* deflateInit and inflateInit are macros to allow checking the zlib version + * and the compiler's view of z_stream: + */ +ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method, + int windowBits, int memLevel, + int strategy, const char *version, + int stream_size)); +ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, + unsigned char FAR *window, + const char *version, + int stream_size)); +#ifdef Z_PREFIX_SET +# define z_deflateInit(strm, level) \ + deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream)) +# define z_inflateInit(strm) \ + inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream)) +# define z_deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ + deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ + (strategy), ZLIB_VERSION, (int)sizeof(z_stream)) +# define z_inflateInit2(strm, windowBits) \ + inflateInit2_((strm), (windowBits), ZLIB_VERSION, \ + (int)sizeof(z_stream)) +# define z_inflateBackInit(strm, windowBits, window) \ + inflateBackInit_((strm), (windowBits), (window), \ + ZLIB_VERSION, (int)sizeof(z_stream)) +#else +# define deflateInit(strm, level) \ + deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream)) +# define inflateInit(strm) \ + inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream)) +# define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ + deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ + (strategy), ZLIB_VERSION, (int)sizeof(z_stream)) +# define inflateInit2(strm, windowBits) \ + inflateInit2_((strm), (windowBits), ZLIB_VERSION, \ + (int)sizeof(z_stream)) +# define inflateBackInit(strm, windowBits, window) \ + inflateBackInit_((strm), (windowBits), (window), \ + ZLIB_VERSION, (int)sizeof(z_stream)) +#endif + +#ifndef Z_SOLO + +/* gzgetc() macro and its supporting function and exposed data structure. Note + * that the real internal state is much larger than the exposed structure. + * This abbreviated structure exposes just enough for the gzgetc() macro. The + * user should not mess with these exposed elements, since their names or + * behavior could change in the future, perhaps even capriciously. They can + * only be used by the gzgetc() macro. You have been warned. + */ +struct gzFile_s { + unsigned have; + unsigned char *next; + z_off64_t pos; +}; +ZEXTERN int ZEXPORT gzgetc_ OF((gzFile file)); /* backward compatibility */ +#ifdef Z_PREFIX_SET +# undef z_gzgetc +# define z_gzgetc(g) \ + ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g)) +#else +# define gzgetc(g) \ + ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g)) +#endif + +/* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or + * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if + * both are true, the application gets the *64 functions, and the regular + * functions are changed to 64 bits) -- in case these are set on systems + * without large file support, _LFS64_LARGEFILE must also be true + */ +#ifdef Z_LARGE64 + ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); + ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int)); + ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile)); + ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile)); + ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off64_t)); + ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off64_t)); + ZEXTERN uLong ZEXPORT crc32_combine_gen64 OF((z_off64_t)); +#endif + +#if !defined(ZLIB_INTERNAL) && defined(Z_WANT64) +# ifdef Z_PREFIX_SET +# define z_gzopen z_gzopen64 +# define z_gzseek z_gzseek64 +# define z_gztell z_gztell64 +# define z_gzoffset z_gzoffset64 +# define z_adler32_combine z_adler32_combine64 +# define z_crc32_combine z_crc32_combine64 +# define z_crc32_combine_gen z_crc32_combine_gen64 +# else +# define gzopen gzopen64 +# define gzseek gzseek64 +# define gztell gztell64 +# define gzoffset gzoffset64 +# define adler32_combine adler32_combine64 +# define crc32_combine crc32_combine64 +# define crc32_combine_gen crc32_combine_gen64 +# endif +# ifndef Z_LARGE64 + ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); + ZEXTERN z_off_t ZEXPORT gzseek64 OF((gzFile, z_off_t, int)); + ZEXTERN z_off_t ZEXPORT gztell64 OF((gzFile)); + ZEXTERN z_off_t ZEXPORT gzoffset64 OF((gzFile)); + ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine_gen64 OF((z_off_t)); +# endif +#else + ZEXTERN gzFile ZEXPORT gzopen OF((const char *, const char *)); + ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile, z_off_t, int)); + ZEXTERN z_off_t ZEXPORT gztell OF((gzFile)); + ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile)); + ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine_gen OF((z_off_t)); +#endif + +#else /* Z_SOLO */ + + ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine_gen OF((z_off_t)); + +#endif /* !Z_SOLO */ + +/* undocumented functions */ +ZEXTERN const char * ZEXPORT zError OF((int)); +ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp)); +ZEXTERN const z_crc_t FAR * ZEXPORT get_crc_table OF((void)); +ZEXTERN int ZEXPORT inflateUndermine OF((z_streamp, int)); +ZEXTERN int ZEXPORT inflateValidate OF((z_streamp, int)); +ZEXTERN unsigned long ZEXPORT inflateCodesUsed OF((z_streamp)); +ZEXTERN int ZEXPORT inflateResetKeep OF((z_streamp)); +ZEXTERN int ZEXPORT deflateResetKeep OF((z_streamp)); +#if defined(_WIN32) && !defined(Z_SOLO) +ZEXTERN gzFile ZEXPORT gzopen_w OF((const wchar_t *path, + const char *mode)); +#endif +#if defined(STDC) || defined(Z_HAVE_STDARG_H) +# ifndef Z_SOLO +ZEXTERN int ZEXPORTVA gzvprintf Z_ARG((gzFile file, + const char *format, + va_list va)); +# endif +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* ZLIB_H */ diff --git a/mod.ld b/mod.ld new file mode 100644 index 0000000..88f2619 --- /dev/null +++ b/mod.ld @@ -0,0 +1,20 @@ +OUTPUT_FORMAT("elf32-i386") +OUTPUT_ARCH(i386) + +ENTRY(kmain) + +SECTIONS +{ + . = 0; + .text ALIGN(16) : { + *(.text) + . = ALIGN(16); + *(.data) + . = ALIGN(16); + *(.rodata*) + . = ALIGN(16); + *(.bss) + } + /*. += 512; /*Something to try if we get spooky memory corruption*/ + _kernel_end = .; +} \ No newline at end of file diff --git a/src/boot0.asm b/src/boot0.asm new file mode 100644 index 0000000..9b01148 --- /dev/null +++ b/src/boot0.asm @@ -0,0 +1,41 @@ +cpu 386 + +bits 16 +org 0x7C00 + +start: + jmp 0:cseg +cseg: + cld + + mov ax, 0xB800 + mov fs, ax + + mov ax, 0x3000 + mov es, ax + + mov ax, 0x0200 | ((BOOT1_SIZE + 511) / 512) + mov cx, 0x0002 + mov dh, 0 + mov bx, 0 + int 0x13 + + setc al + add al, '0' + mov [fs:0], al + + xor ax, ax + mov es, ax + + mov ax, 0x3000 + mov ds, ax + + mov ax, 0x4000 ;Apparently Bochs' BIOS bugs out if below 0x7C00 linear + mov ss, ax + xor sp, sp + + jmp 0x3000:0 + +db "Yo waddup" + +times 446 - ($ - $$) db 0 diff --git a/src/boot1.asm b/src/boot1.asm new file mode 100644 index 0000000..b98ac4e --- /dev/null +++ b/src/boot1.asm @@ -0,0 +1,864 @@ +cpu 386 + +bits 16 +org 0 + +%define BIT_READWRITE (1 << 1) +%define BIT_EXECUTABLE (1 << 3) +%define BIT_ISCODEORDATA (1 << 4) +%define BIT_PRESENT (1 << 7) + +%define PBIT_PRESENT 1 +%define PBIT_WRITABLE 2 +%define PBIT_USERLEVEL 4 +%define PBIT_WRITETHROUGH 8 +%define PBIT_CACHEDISABLE 16 +%define PBIT_ACCESSED 32 + +MALLOC_MEM equ 0x520 + +BOOT1_SEGMENT equ 0x3000 +BOOT1_ADDR equ (BOOT1_SEGMENT * 0x10) + +start: + mov [ld_lba.drive + 1], dl + + mov ah, 8 + mov di, 0 + int 0x13 + mov dl, dh + mov dh, 0 + inc dx + mov [lba2chs.numheads + 1], dx + and cl, 0x3F + mov ch, 0 + mov [lba2chs.spt + 1], cx + + mov eax, [es:0x7C00 + 0x1BE + 8] + mov [get_inode.abs1], eax + mov [read_inode.abs1], eax + + mov ecx, 40 * 25 + mov edi, 0 +.lup: + mov [fs:edi + ecx * 4 - 4], dword 0x0F000F00 + dec ecx + jnz .lup + + mov si, MSG_START + mov ax, MSG_START.end - MSG_START + call print16 + + mov edi, MALLOC_MEM ;Bump allocator pointer + + add edi, 4096 + mov [TSS.esp0], edi ;End of stack ~ beginning of memory map!! + +a20: + cli + call .waito + mov al, 0xAD + out 0x64, al + call .waito + mov al, 0xD0 + out 0x64, al +.waiti: + in al, 0x64 + test al, 1 + jz .waiti + in al, 0x60 + push ax + call .waito + mov al, 0xD1 + out 0x64, al + call .waito + pop ax + or al, 2 + out 0x60, al + call .waito + mov al, 0xAE + out 0x64, al + call .waito + sti + jmp ramdetect +.waito: + in al, 0x64 + test al, 2 + jnz .waito + ret + +ramdetect: ;Currently only detects RAM below 16MB, which will be enough for a while. + clc + int 0x12 + jc .fail + mov [es:di + 0], dword 0 + mov [es:di + 4], dword 0 + movzx ecx, ax + shr cx, 2 + mov [es:di + 8], ecx + mov [es:di + 12], byte 0 + add di, 13 + mov al, 0 + add cx, 7 + shr cx, 3 + rep stosb + + xor cx, cx + xor dx, dx + mov ax, 0xE801 + int 0x15 + jc .fail + cmp ah, 0x86 + je .fail + cmp ah, 0x80 + je .fail + jcxz .useax + mov ax, cx + mov bx, dx +.useax: + mov [es:di + 0], dword 0x100000 + mov [es:di + 4], dword 0 + movzx ecx, ax + shr ecx, 2 + mov [es:di + 8], ecx + mov [es:di + 12], byte 0 + add di, 13 + mov al, 0 + shr ecx, 3 + rep stosb + jmp .foundMMap + +.fail: + mov si, MSG_FAIL + mov ax, MSG_FAIL.end - MSG_FAIL + call print16 + + jmp $ +.foundMMap: + mov si, MSG_DETECTED_MEMORY_MAP + mov ax, MSG_DETECTED_MEMORY_MAP.end - MSG_DETECTED_MEMORY_MAP + call print16 + +pg: + ; Create page directory + add edi, 4095 + and edi, ~4095 + mov cr3, edi ;In advance + lea eax, [edi + 4096] + or eax, PBIT_PRESENT | PBIT_WRITABLE + mov [es:edi], eax + add edi, 4 + mov eax, 0 + mov ecx, 1023 + rep stosd + + mov ecx, 192 + mov edx, PBIT_PRESENT | PBIT_WRITABLE +.lup: + mov [es:edi], edx + add edi, 4 + add edx, 4096 + dec ecx + jnz .lup + + mov ecx, 1024 - 192 + mov eax, 0 + rep stosd + + mov eax, cr3 ;Back to the page directory + mov [es:eax + 4092], edi + or dword [es:eax + 4092], PBIT_PRESENT | PBIT_WRITABLE + mov [es:edi + 4092], edi + or dword [es:edi + 4092], PBIT_PRESENT | PBIT_WRITABLE + add edi, 4096 + + mov esi, MSG_STEP3s + mov eax, MSG_STEP3s.end - MSG_STEP3s + call print16 + +loadkernel: + mov eax, 2 ;root + call get_inode + mov bx, di + call read_inode + mov eax, edi + mov esi, KERNEL_FILE + mov ecx, KERNEL_FILE.end - KERNEL_FILE + call find_in_dirnode + test eax, eax + jnz .found + + mov si, MSG_STEP5f + mov ax, MSG_STEP5f.end - MSG_STEP5f + call print16 + jmp $ +.found: + call get_inode + mov bx, di + call read_inode + ; Now edi is kernel location, ebx is after kernel. + call fix_module_addresses + mov [inPE.KERNEL_START], edi + mov edi, ebx ;Allocate modules after kernel + ;~ mov [inPE.MODULES_START], edi + +loadmods: + mov eax, 2 + call get_inode + mov esi, [endSector + 32] ;filesize + push es + push ds + pop es + mov bx, endSector + 0x200 ;Will break if root directory is larger than 1KB. + call read_inode + pop es + mov eax, endSector + 0x200 +.lup: ;Loop over files, the names of which end with ".mod" + movzx ecx, word [eax + 10] ;Length of name + lea edx, [eax + 12] ;Get name string + cmp ecx, 4 ;Test if shorter than 4 characters + jb .cont +.testext: + cmp [eax + ecx + 12 - 4], dword ".mod" + jne .cont +.testkrnl: + cmp [eax + 12], dword "krnl" + je .cont +.ismod: + inc dword [inPE.MOD_COUNT] + push eax + mov eax, [eax] ;inode + call get_inode + call page_align_es_edi + push esi + mov esi, cr3 + mov cx, 1024 + push ds + push word 0 + pop ds + rep movsd ;Copy page directory to one local to process + pop ds + pop esi + mov bx, di + call read_inode ;edi = start, ebx = end + mov di, bx + pop eax +.cont: + movzx ecx, byte [eax + 9] + shl cx, 4 + add eax, ecx + sub esi, ecx + jnz .lup +.end: + mov di, es + shl edi, 4 + add edi, 4095 + and edi, ~4095 + mov [inPE.IMPORTANT_MEM_END], edi + xor ax, ax + mov es, ax + + add ebx, edi +fixmmap: ; Make all module memories "used" + lea ecx, [es:ebx + 4095] + shr ecx, 12 + mov ebx, ecx + and ebx, 7 + shr ecx, 3 + mov edi, [TSS.esp0] + add edi, 13 + push edi + mov al, -1 + rep stosb + mov ecx, ebx + mov al, 1 + shl al, cl + dec al + mov [es:edi], al + pop edi + or [es:edi + (BOOT1_ADDR / 4096 / 8)], byte 3 ; TODO: Let boot1 get overwritten after load + +modex: + mov ax, 0x13 + int 0x10 + + mov dx, 0x3C4 + mov al, 4 + out dx, al + + inc dx + mov al, 6 + out dx, al + + mov dx, 0x3D4 + mov al, 0x14 + out dx, al + + inc dx + xor al, al + out dx, al + + dec dx + mov al, 0x17 + out dx, al + + inc dx + mov al, 0xE3 + out dx, al + + dec dx + mov al, 0x11 + out dx, al + + inc dx + mov al, 0x2C + out dx, al + + dec dx + mov al, 0x06 + out dx, al + + inc dx + mov al, 0x0D + out dx, al + + dec dx + mov al, 0x07 + out dx, al + + inc dx + mov al, 0x3E + out dx, al + + dec dx + mov al, 0x10 + out dx, al + + inc dx + mov al, 0xEA + out dx, al + + dec dx + mov al, 0x11 + out dx, al + + inc dx + mov al, 0xAC + out dx, al + + dec dx + mov al, 0x12 + out dx, al + + inc dx + mov al, 0xDF + out dx, al + + dec dx + mov al, 0x15 + out dx, al + + inc dx + mov al, 0xE7 + out dx, al + + dec dx + mov al, 0x16 + out dx, al + + inc dx + mov al, 0x06 + out dx, al + + ; ESP should be zero here. + push strict dword BOOT1_ADDR + inPE + mov esp, BOOT1_ADDR + 0x10000 + 0xFFFC + jmp enterPM + +enterPM: + cli + or [GDT.R0CSLIMFLAGS], byte 64 ;Make 32-bit + lgdt [GDT] + mov eax, cr0 + or eax, 1 | (1 << 31) + mov cr0, eax + jmp 8:dword BOOT1_ADDR + .inPM +.inPM: +bits 32 + mov eax, 0x23 + mov ds, ax + mov es, ax + mov fs, ax + mov gs, ax + mov al, 0x10 + mov ss, ax + ret + +enterRM: + and [GDT.R0CSLIMFLAGS], byte ~64 ;Make 16-bit + lgdt [GDT] + jmp 8:.in16 +.in16: +bits 16 + mov eax, cr0 + and eax, ~(1 | (1 << 31)) + mov cr0, eax + jmp 0:.inRM +.inRM: + mov ax, 0 + mov ds, ax + mov es, ax + mov fs, ax + mov gs, ax + mov ss, ax + sti + ret + +; Makes es:edi a normalized far pointer +normalize_es_edi: + push eax + push edi + mov ax, es + shr di, 4 + add ax, di + mov es, ax + pop edi + and edi, 15 + pop eax + ret + +page_align_es_edi: + push eax + xor eax, eax + mov ax, es + shl eax, 4 + add eax, edi + add eax, 4095 + and eax, ~4095 + shr eax, 4 + mov es, ax + pop eax + xor edi, edi + ret + +print16: + push di + push cx + push ax +.ind: + mov di, 0 + mov cx, ax +.lup: + mov al, [ds:si] + mov [fs:di], al + inc si + inc di + inc di + dec cx + jnz .lup + mov [.ind + 1], di ;SMC + pop ax + pop cx + pop di + ret + +ld_lba: + pushad + call lba2chs + mov ch, al + mov dh, dl +.drive: + mov dl, 0 + mov ah, 2 + mov al, 1 + int 0x13 + popad + ret + +; In: AX = lba +; Out: CX = sector, AX = cylinder, DX = head +lba2chs: + push bx +.spt: + mov bx, 0xF157 + xor dx, dx + div bx + mov cx, dx + inc cx +.numheads: + mov bx, 0x9001 + xor dx, dx + div bx + pop bx + ret + +; In: EAX = inode +; Out: *BOOT1_SEGMENT:endSector = inode struct +get_inode: + push eax + push ebx +.abs1 equ ($ + 2) + add eax, strict dword 0xABCDEF42 + push es + push ds + pop es + mov bx, endSector + call ld_lba + pop es + pop ebx + pop eax + ret + +; In: *BOOT1_SEGMENT:endSector = inode struct +; Out: *ES:BX = data +read_inode: + push edx + push ecx + push eax + push esi + push edi + push ebx + + mov dl, [endSector + 8] ;extent count + mov ecx, endSector + 104 ;extent starts + +.lup: + mov eax, [ecx] ;start + mov esi, [ecx + 48] ;size of extent +.abs1 equ ($ + 2) + add eax, strict dword 0x12345678 + +.lup2: + call ld_lba + add bx, 512 + inc eax + dec esi + jnz .lup2 + + add ecx, 8 + dec dl + jnz .lup + + mov edi, [esp] ;dest address + lea esi, [edi + 176] + test dword [endSector + 28], 1 << 19 + jz .doesntHaveInline + add esi, 512 - 176 +.doesntHaveInline: + mov ecx, [endSector + 32] ;filesize + push ds + push es + pop ds + rep movsb + pop ds + + add esp, 4 ;ignore old ebx, because read_inode should return the addr after + pop edi + pop esi + pop eax + pop ecx + pop edx + ret + +; In: *ES:EAX = directory content buffer, *ESI = name to test, ECX = name length +; Out: EAX = inode or 0 if not found +find_in_dirnode: + push ebx + push edx + push edi + + mov edi, [endSector + 32] ;filesize +.lup: + movzx edx, word [es:eax + 10] ;record name length + cmp dx, cx +.lup2: + dec dx + mov bl, [es:eax + 12 + edx] + cmp bl, [esi + edx] + jne .next + test dx, dx + jnz .lup2 + jmp .found +.next: + movzx edx, byte [es:eax + 9] ;record length + shl dx, 4 + add eax, edx + sub edi, edx + jnz .lup + + mov eax, 0 + jmp .end +.found: + mov eax, [es:eax] +.end: + pop edi + pop edx + pop ebx + ret + +fix_module_addresses: + push esi + push ecx + push eax + push ebx + + movzx ecx, word [es:edi + 4] ;amount of syms + lea esi, [es:edi + 12 + ecx * 4] + lea esi, [es:esi + ecx * 2] + movzx ecx, word [es:edi + 6] ;amount of relocs + mov eax, esi ;ptr to relocs + lea esi, [esi + ecx * 4] ;ptr to data + add esi, 15 + and esi, ~15 + mov [es:edi], esi ;Replace the MOD\0 magic header with the base address + test ecx, ecx ;If none, end + jz .end +.lup: + ; Apply relocation + mov ebx, [es:eax] + add ebx, esi + add [es:ebx], esi + + add eax, 4 + dec ecx + jnz .lup +.end: + + pop ebx + pop eax + pop ecx + pop esi + ret + +bits 32 + +inPE: + mov [BOOT1_ADDR + TSS.ss0], dword 0x10 + mov esp, [BOOT1_ADDR + TSS.esp0] + + mov eax, 40 + ltr ax + + mov ax, [BOOT1_ADDR + print16.ind + 1] + mov [BOOT1_ADDR + print32.LAST], ax + + mov esi, BOOT1_ADDR + MSG_STEP2s + mov eax, MSG_STEP2s.end - MSG_STEP2s + call print32 + +.KERNEL_START equ ($ + 1) + mov edi, strict dword 0 + lea ebx, [edi + 14] + ; Sym 0: ppm_Bitmap + mov eax, [ebx] + add eax, [edi] ;Base address that used to be magic header + push dword [BOOT1_ADDR + TSS.esp0] ;As said before, end of stack ~ beginning of mmap! + pop dword [eax] + add ebx, 6 + ; Sym 1: vpm_init + mov eax, [ebx] + add eax, [edi] +.IMPORTANT_MEM_END equ ($ + 1) + push strict dword 0 + call eax + add esp, 4 + add ebx, 6 + ; Sym 2: vpm_map + mov eax, [ebx] + add eax, [edi] + mov [BOOT1_ADDR + .VPM_MAP_ENTRY], eax + add ebx, 6 + ; Sym 3: canal_init + mov eax, [ebx] + add eax, [edi] + call eax + add ebx, 6 + ; Sym 4: pci_init + mov eax, [ebx] + add eax, [edi] + call eax + add ebx, 6 + ; Sym 5: scheduler_init + mov eax, [ebx] + add eax, [edi] + call eax + add ebx, 6 + ; Sym 6: scheduler_spawn + mov eax, [ebx] + add eax, [edi] + mov [BOOT1_ADDR + .SCHEDULER_SPAWN_ENTRY], eax + add ebx, 6 + ; Sym 7: scheduler_start + mov eax, [ebx] + add eax, [edi] + mov [BOOT1_ADDR + .SCHEDULER_START_ENTRY], eax + +.MOD_COUNT equ ($ + 1) + mov ebp, strict dword 0 +.modspawnlup: + ; Find next module + movzx ecx, word [edi + 4] + lea eax, [edi + ecx * 4] + lea eax, [eax + ecx * 2] + movzx ecx, word [edi + 6] + lea eax, [eax + ecx * 4] + add eax, 15 + and eax, ~15 + mov ecx, [edi + 8] + lea eax, [eax + ecx] + add eax, 4096 + 4095 + and eax, ~4095 + mov edi, eax + mov ebx, 0x40000000 + call rebase_module32 + sub edx, edi + + push strict dword edx + push strict dword edi + push strict dword 0x40000000 + push strict dword 1 ;user + lea eax, [edi - 4096] ; cr3 + push eax +.VPM_MAP_ENTRY equ ($ + 1) + mov eax, strict dword 0 + call eax + add esp, 20 + + push strict dword 0 +.SCHEDULER_SPAWN_ENTRY equ ($ + 1) + mov eax, strict dword 0 + call eax + add esp, 4 + lea ebx, [edi - 4096] + mov [eax + 46], ebx ;cr3 + mov ebx, [edi + 14] ;get sym 0 (modentry) + add ebx, [edi] ;add data offset + mov [eax + 34], ebx ;eip + + dec ebp + jnz .modspawnlup + +.SCHEDULER_START_ENTRY equ ($ + 1) + mov eax, strict dword 0 + jmp eax + +print32: + push ebx + push eax + push ecx + movzx ebx, word [BOOT1_ADDR + .LAST] + mov ecx, eax +.lup: + mov al, [esi] + mov [0xB8000 + ebx], al + inc esi + inc ebx + inc ebx + dec ecx + jnz .lup + mov [BOOT1_ADDR + .LAST], bx + pop ecx + pop eax + pop ebx + ret +.LAST: dw 0 + +; In: EDI = module pointer, EBX = rebase address +; Out: EDX = physical module end +rebase_module32: + push ecx + push eax + push ebx + push ebp + movzx ecx, word [edi + 4] + lea eax, [edi + 12 + ecx * 2] + lea eax, [eax + ecx * 4] ; eax = relocations pointer + movzx ecx, word [edi + 6] ;ecx = amount of relocations + lea edx, [eax + ecx * 4] ; edx = data pointer + add edx, 15 + and edx, ~15 + mov [edi], edx ;Store offset of data buffer in + sub [edi], edi ;file in place of magic header + add [edi], ebx ; + mov ebx, [edi] + test ecx, ecx + jz .end +.lup: + mov ebp, [eax] + add [edx + ebp], ebx + add eax, 4 + dec ecx + jnz .lup +.end: + add edx, [edi + 8] + pop ebp + pop ebx + pop eax + pop ecx + ret + +MSG_FAIL: db "Failed to detect memory map. " +.end: + +MSG_START: db "Starting eklernel. " +.end: + +MSG_DETECTED_MEMORY_MAP: db "Found memory map. " +.end: + +MSG_STEP2s: db "Entered protected mode. " +.end: + +MSG_STEP3s: db "Generated paging structures. " +.end: + +MSG_STEP4f: db "Boot filesystem must have block size of 1024. " +.end: + +KERNEL_FILE: db "krnl.mod" +.end: + +MSG_STEP5f: db "Kernel not found; aborting boot. " +.end: + +GDT: + dw (GDT.END - GDT) - 1 ;GDT descriptor in the null entry + dd BOOT1_ADDR + GDT + dw 0 + + dw 0xFFFF, 0x0000 + db 0x00, BIT_READWRITE | BIT_EXECUTABLE | BIT_ISCODEORDATA | BIT_PRESENT | (0 << 5) +.R0CSLIMFLAGS: + db (128 | 64) | 0xF + db 0 + + dw 0xFFFF, 0x0000 + db 0x00, BIT_READWRITE | BIT_ISCODEORDATA | BIT_PRESENT | (0 << 5) + db (128 | 64) | 0xF + db 0 + + dw 0xFFFF, 0x0000 + db 0x00, BIT_READWRITE | BIT_EXECUTABLE | BIT_ISCODEORDATA | BIT_PRESENT | (3 << 5) + db (128 | 64) | 0xF + db 0 + + dw 0xFFFF, 0x0000 + db 0x00, BIT_READWRITE | BIT_ISCODEORDATA | BIT_PRESENT | (3 << 5) + db (128 | 64) | 0xF + db 0 + + dw (TSS.END - TSS) - 1 + dw TSS + db BOOT1_ADDR / 0x10000, 1 | 8 | 128 + db 0, 0 +.END: +TSS: + dd 0 +.esp0: dd 0 +.ss0: dd 0 + times 23 dd 0 +.END: + +end: +times (end - start + 511) / 512 * 512 - ($ - $$) db 0 +endSector: diff --git a/src/kernel/arch/x86/canal.c b/src/kernel/arch/x86/canal.c new file mode 100644 index 0000000..e3d9b72 --- /dev/null +++ b/src/kernel/arch/x86/canal.c @@ -0,0 +1,181 @@ +#include"canal.h" + +#include"vpm.h" +#include"mem.h" +#include"scheduler.h" +#include"ppm.h" + +static inline void pr(int c) { + asm volatile("outb %%al, $0xE9" :: "a"(c) :); +} + +static inline void pri(size_t num) { + char buf[16] = {}; + int i = 16; + + do { + buf[--i] = num % 10; + num /= 10; + } while(num); + + for(; i < 16; i++) { + pr(buf[i] + '0'); + } +} + +static inline void prcs(const char *str) { + while(*str) { + pr(*str); + str++; + } +} + +static Canal *canals = 0; +static Link *links = 0; + +void canal_init() { + uint32_t cr3; + asm volatile("movl %%cr3, %0" : "=r"(cr3) :); + + canals = vpm_map(cr3, VPM_KERNEL, -1, -1, 4096); + kmemw1(canals, 0, 4096); + + links = vpm_map(cr3, VPM_KERNEL, -1, -1, 4096); + kmemw1(links, 0xFF, 4096); +} + +uint32_t canal_create(uint64_t name, uint16_t hostProcessId) { + Process *hostProcess = scheduler_find(hostProcessId); + + for(int i = 0; i < 4096 / sizeof(Canal); i++) { + if(canals[i].name == name) return -2; + + if(canals[i].name == 0) { + canals[i].name = name; + canals[i].hostProcess = hostProcess; + canals[i].links = NULL; + + canals[i].ownedNext = hostProcess->ownedCanal; + hostProcess->ownedCanal = &canals[i]; + + return i; + } + } + return -1; +} + +uint32_t link_create(uint64_t canalName, uint16_t guestProcessId, uint32_t areaSize) { + int canalId = -1; + for(int i = 0; i < 4096 / sizeof(Canal); i++) { + if(canals[i].name == canalName) { + canalId = i; + break; + } + } + + Process *guest = scheduler_find(guestProcessId); + + if(canalId == -1) return -1; + if(canals[canalId].hostProcess == guest) return -1; + + uint32_t hostCR3 = canals[canalId].hostProcess->ctx.cr3; + uint32_t hostAreaVirtAddr = vpm_find_free(hostCR3, VPM_USER, areaSize); + + uint32_t guestCR3 = guest->ctx.cr3; + uint32_t guestAreaVirtAddr = vpm_find_free(guestCR3, VPM_USER, areaSize); + + /* TODO: Fail if areas not found. */ + + for(int i = 0; i < 4096 / sizeof(Link); i++) { + if(links[i].canalId == -1) { + links[i].canalId = canalId; + links[i].guestProcess = guest; + links[i].hostVirtAddr = hostAreaVirtAddr; + links[i].guestVirtAddr = guestAreaVirtAddr; + links[i].flags = 0; + + uint32_t pages = (areaSize + 4095) / 4096; + + uint32_t phys = ppm_alloc(pages); + vpm_map(hostCR3, VPM_USER, hostAreaVirtAddr, phys, areaSize); + vpm_map(guestCR3, VPM_USER, guestAreaVirtAddr, phys, areaSize); + + canals[canalId].hostProcess->eventsRequest++; + + links[i].nextInCanal = canals[canalId].links; + canals[canalId].links = &links[i]; + + links[i].nextGuestLink = guest->guestLinks; + guest->guestLinks = &links[i]; + + return guestAreaVirtAddr; + } + } + + return -1; +} + +uint32_t canal_accept(uint16_t hostProcessId, uint32_t canalId) { + for(int i = 0; i < 4096 / sizeof(Link); i++) { + if(links[i].canalId != -1 && canals[links[i].canalId].hostProcess->id == hostProcessId && (canalId == (uint32_t)-1 || links[i].canalId == canalId) && !(links[i].flags & LINK_FLAG_ACCEPTED)) { + links[i].flags = links[i].flags | LINK_FLAG_ACCEPTED; + prcs("RETURNING "); + pri(links[i].hostVirtAddr); + pr('\n'); + return links[i].hostVirtAddr; + } + } + + return -1; +} + +void link_send_signal_from(uint16_t processId, uint32_t processAreaAddr, uint32_t meta) { + for(int i = 0; i < 4096 / sizeof(Link); i++) { + if(links[i].guestProcess->id == processId && links[i].guestVirtAddr == processAreaAddr) { + if(!(links[i].flags & LINK_FLAG_G2H)) { + canals[links[i].canalId].hostProcess->eventsSignal++; + links[i].flags |= LINK_FLAG_G2H; + } + + links[i].metaG2H = meta; + + return; + } else if(canals[links[i].canalId].hostProcess->id == processId && links[i].hostVirtAddr == processAreaAddr) { + if(!(links[i].flags & LINK_FLAG_H2G)) { + links[i].guestProcess->eventsSignal++; + links[i].flags |= LINK_FLAG_H2G; + } + + links[i].metaH2G = meta; + + return; + } + } +} + +uint32_t is_signal_awaiting_to_concerning_link(uint16_t processId, uint32_t area, uint32_t *metaOut, uint32_t *canalId) { + for(int i = 0; i < 4096 / sizeof(Link); i++) { + if((links[i].guestProcess->id == processId && (area == -1 || links[i].guestVirtAddr == area) && (links[i].flags & LINK_FLAG_H2G)) + || (canals[links[i].canalId].hostProcess->id == processId && (area == -1 || area == links[i].hostVirtAddr) && (links[i].flags & LINK_FLAG_G2H))) { + + *canalId = links[i].canalId; + + return signal_accept(scheduler_find(processId), &links[i], metaOut); + } + } + return -1; +} + +uint32_t signal_accept(Process *p, Link *l, uint32_t *meta) { + p->eventsSignal--; + + if(l->guestProcess == p) { + l->flags &= ~LINK_FLAG_H2G; + *meta = l->metaH2G; + return l->guestVirtAddr; + } else { + l->flags &= ~LINK_FLAG_G2H; + *meta = l->metaG2H; + return l->hostVirtAddr; + } +} diff --git a/src/kernel/arch/x86/canal.h b/src/kernel/arch/x86/canal.h new file mode 100644 index 0000000..37b184d --- /dev/null +++ b/src/kernel/arch/x86/canal.h @@ -0,0 +1,42 @@ +#ifndef _CANAL_H +#define _CANAL_H + +#include + +#define LINK_FLAG_ACCEPTED 1 + +#define LINK_FLAG_G2H 2 +#define LINK_FLAG_H2G 4 + +struct Process; +struct Link; + +typedef struct Canal { + uint64_t name; + struct Process *hostProcess; + struct Canal *ownedNext; + struct Link *links; +} __attribute__((packed)) Canal; + +typedef struct Link { + uint32_t canalId; + uint32_t hostVirtAddr; + struct Process *guestProcess; + uint32_t guestVirtAddr; + uint32_t metaG2H; + uint32_t metaH2G; + uint8_t flags; + struct Link *nextInCanal; + struct Link *nextGuestLink; +} __attribute__((packed)) Link; + +uint32_t canal_create(uint64_t name, uint16_t hostProcessId); +uint32_t link_create(uint64_t canal, uint16_t guestProcessId, uint32_t areaSize); +uint32_t canal_accept(uint16_t hostProcessId, uint32_t canalId); +void link_send_signal_from(uint16_t processId, uint32_t processAreaAddr, uint32_t meta); +uint32_t link_get_oldest_signal_to(uint16_t processId); +uint32_t is_signal_awaiting_to_concerning_link(uint16_t processId, uint32_t area, uint32_t *metaOut, uint32_t *canalId); + +uint32_t signal_accept(struct Process *p, Link *l, uint32_t *meta); + +#endif diff --git a/src/kernel/arch/x86/consts.h b/src/kernel/arch/x86/consts.h new file mode 100644 index 0000000..bd1b97e --- /dev/null +++ b/src/kernel/arch/x86/consts.h @@ -0,0 +1,20 @@ +#ifndef _X86_CONSTS_H +#define _X86_CONSTS_H + +#define EFLAGS_IOPL_0 (0 << 12) +#define EFLAGS_IOPL_1 (1 << 12) +#define EFLAGS_IOPL_2 (2 << 12) +#define EFLAGS_IOPL_3 (3 << 12) +#define EFLAGS_IF (1 << 9) +#define EFLAGS_RESET 2 + +#define RPL_0 0 +#define RPL_1 1 +#define RPL_2 2 +#define RPL_3 3 + +#define PAGE_BIT_PRESENT 1 +#define PAGE_BIT_WRITABLE 2 +#define PAGE_BIT_USER 4 + +#endif \ No newline at end of file diff --git a/src/kernel/arch/x86/interrupt.asm b/src/kernel/arch/x86/interrupt.asm new file mode 100644 index 0000000..242d5bd --- /dev/null +++ b/src/kernel/arch/x86/interrupt.asm @@ -0,0 +1,827 @@ +cpu 386 +bits 32 + +TIMER_FREQUENCY equ 250;Hz + +; TODO: perform IO waits + +section .text + +extern scheduler_switch +extern scheduler_CurrentProcess +pit_handler: +extern scheduler_Tick + inc dword [scheduler_Tick] + push eax + mov al, 0x20 + out 0x20, al + pop eax + +ctx_switch: + push eax + + mov eax, [scheduler_CurrentProcess] + test eax, eax + jnz .a + add esp, 16 + jmp .b +.a: + pop dword [eax + 2] ;eax + pop dword [eax + 34] ;eip + pop dword [eax + 42] ;cs + pop dword [eax + 38] ;eflags + mov [eax + 6], ebx + mov [eax + 10], ecx + mov [eax + 14], edx + mov [eax + 18], esi + mov [eax + 22], edi + mov [eax + 26], ebp + cmp dword [eax + 42], 8 ;CS 8 implies ring 0 + jne .isR3 + mov [eax + 30], esp + jmp .b +.isR3: + pop dword [eax + 30] ;esp + add esp, 4 ;ss +.b: + call scheduler_switch + jmp jump_to_process + +global jump_to_process +jump_to_process: + mov eax, [scheduler_CurrentProcess] + test eax, eax + jnz .c + ; No next process, goto hlt loop. + push dword 0x202 + push dword 8 + push haltLoop + iretd +.c: + mov ebx, [eax + 46] + mov cr3, ebx + mov ebx, [eax + 6] + mov ecx, [eax + 10] + mov edx, [eax + 14] + mov esi, [eax + 18] + mov edi, [eax + 22] + mov ebp, [eax + 26] + cmp dword [eax + 42], 8 + je .isR0 + push dword 32 | 3 + push dword [eax + 30] + jmp .b +.isR0: + mov esp, [eax + 30] +.b: + push dword [eax + 38] ;eflags + push dword [eax + 42] ;cs + push dword [eax + 34] ;eip + mov eax, [eax + 2] + iretd + +set_bit: + push edx + push ebx + push ecx + push eax + + shl ebx, 1 + + mov dx, 0x3C4 + mov al, 2 + out dx, al + + mov ecx, ebx + and ecx, 3 + mov eax, 1 + shl eax, cl + + mov dx, 0x3C5 + out dx, al + + mov ecx, ebx + sar ecx, 2 + + pop eax + + mov [0xA0000 + ecx], byte al + + pop ecx + pop ebx + pop edx + + ret + +write_dword: + push eax + push ecx + + mov ecx, 32 + +.lup: + + rol eax, 1 + + push eax + and eax, 1 + shl eax, 4 + add eax, 20 + call set_bit + pop eax +.nz: + inc ebx + + dec ecx + jnz .lup + + pop ecx + pop eax + + ret + +clear_screen: + push eax + push ecx + push edx + push edi + + mov dx, 0x3C4 + mov al, 2 + out dx, al + + inc dx + mov al, 15 + out dx, al + + mov edi, 0xA0000 + mov ecx, 4800 + mov eax, 0 + rep stosd + + pop edi + pop edx + pop ecx + pop eax + + ret + +pgf_handler: + call clear_screen + + pop eax ;error code + mov ebx, 0 + call write_dword + + inc ebx + + mov eax, cr2 ;accessed address + call write_dword + + inc ebx + + pop eax ;instruction cause of exception + call write_dword + + add ebx, 100 + + mov eax, [eax] ;instruction data + call write_dword +.LOUP: + hlt + jmp .LOUP + +dbf_handler: + add esp, 4 + mov [0xA0000], dword "D_F_" +.LOUP: + hlt + jmp .LOUP + +gpf_handler: + pop eax + movzx ebx, al + and bl, 0xF + mov bl, [.tbl + ebx] + mov [0xB800E], bl + movzx ebx, al + shr bl, 4 + mov bl, [.tbl + ebx] + mov [0xB800C], bl + shr eax, 8 + movzx ebx, al + and bl, 0xF + mov bl, [.tbl + ebx] + mov [0xB800A], bl + movzx ebx, al + shr bl, 4 + mov bl, [.tbl + ebx] + mov [0xB8008], bl + shr eax, 8 + movzx ebx, al + and bl, 0xF + mov bl, [.tbl + ebx] + mov [0xB8006], bl + movzx ebx, al + shr bl, 4 + mov bl, [.tbl + ebx] + mov [0xB8004], bl + shr eax, 8 + movzx ebx, al + and bl, 0xF + mov bl, [.tbl + ebx] + mov [0xB8002], bl + movzx ebx, al + shr bl, 4 + mov bl, [.tbl + ebx] + mov [0xB8000], bl + shr eax, 8 +.LOUP: + hlt + jmp .LOUP +.tbl: db "0123456789ABCDEF" + +spur_handler: + iret + +syscall_int_entry: + cmp eax, (.tblend - .tbl) / 4 + jae .invalid + jmp [.tbl + eax * 4] +.invalid: + mov eax, 0 + iret +.tbl: + dd .sys_vpm_map, .sys_canal_create, .sys_link_create, .sys_canal_accept, .sys_signal_send, .sys_signal_wait, .sys_pci_claim, .sys_pci_read, .sys_vpm_unmap, .sys_vpm_get_phys, .sys_sleep, .sys_pci_write_1, .sys_pci_write_2, .sys_pci_write_4, .sys_irq_claim, .sys_wait_for_irq, .sys_create_thread, .sys_spawn, .sys_abuse_map, .sys_release, .sys_abuse_state, .sys_exit, .sys_event_wait +.tblend: +.sys_vpm_map: + push ecx + push edx + push esi + push edi + push 1 ;USER mapping + mov eax, cr3 + push eax +extern vpm_map + call vpm_map + add esp, 16 + pop edx + pop ecx + iret +.sys_canal_create: + push ecx + push edx + mov eax, [scheduler_CurrentProcess] + movzx eax, word [eax] ;process ID + push eax + push esi + push edi +extern canal_create + call canal_create + add esp, 12 + pop edx + pop ecx + iret +.sys_link_create: + push ecx + push edx + mov eax, [scheduler_CurrentProcess] + movzx eax, word [eax] + push eax + push esi + push edi +extern link_create + call link_create + add esp, 12 + pop edx + pop ecx + iret +.sys_canal_accept: + push ecx + push edx + push edi + mov eax, [scheduler_CurrentProcess] + movzx eax, word [eax] ;id + push eax +extern canal_accept + call canal_accept + add esp, 8 + pop edx + pop ecx + iret +.sys_signal_send: + push ecx + push edx + push esi + push edi + mov eax, [scheduler_CurrentProcess] + movzx eax, word [eax] ;id + push eax +extern link_send_signal_from + call link_send_signal_from + pop eax + add esp, 8 + pop edx + pop ecx + iret +.sys_signal_wait: + push eax + mov eax, [scheduler_CurrentProcess] + mov [eax + 50], byte 1 + mov [eax + 51], edi + pop eax + jmp ctx_switch +.sys_pci_claim: + push ecx + push edx + push edi +extern pci_claim + call pci_claim + pop edx + pop edx + pop ecx + iret +.sys_pci_read: + push ecx + push edx + push esi + push edi +extern pci_read + call pci_read + add esp, 8 + pop edx + pop ecx + iret +.sys_vpm_unmap: + push eax + push ecx + push edx + push esi + push edi + mov eax, cr3 + push eax +extern vpm_unmap + call vpm_unmap + add esp, 12 + pop edx + pop ecx + pop eax + iret +.sys_vpm_get_phys: + push ecx + push edx + push edi + mov eax, cr3 + push eax +extern vpm_get_phys + call vpm_get_phys + add esp, 8 + pop edx + pop ecx + iret +.sys_sleep: + push edx + push ebx + push eax + xor edx, edx + mov eax, edi + mov ebx, 1000 / TIMER_FREQUENCY + div ebx + add eax, [scheduler_Tick] + mov ebx, [scheduler_CurrentProcess] + mov byte [ebx + 50], 2 + mov [ebx + 51], eax + pop eax + pop ebx + pop edx + jmp ctx_switch +.sys_pci_write_1: + push eax + push ecx + push edx + push esi + push edi +extern pci_write_1 + call pci_write_1 + add esp, 8 + pop edx + pop ecx + pop eax + iret +.sys_pci_write_2: + push eax + push ecx + push edx + push esi + push edi +extern pci_write_2 + call pci_write_2 + add esp, 8 + pop edx + pop ecx + pop eax + iret +.sys_pci_write_4: + push eax + push ecx + push edx + push esi + push edi +extern pci_write_4 + call pci_write_4 + add esp, 8 + pop edx + pop ecx + pop eax + iret +.sys_irq_claim: + push ecx + push edx + call irq_claim + pop edx + pop ecx + iret +.sys_wait_for_irq: + push ecx + mov ecx, edi + ; TODO: check privilege + call toggle_irq_mask + mov ecx, [scheduler_CurrentProcess] + mov [ecx + 50], byte 3 ; Wait type IRQ + pop ecx + jmp ctx_switch +.sys_create_thread: + push eax + push ecx + push edx +extern scheduler_spawn + call scheduler_spawn + mov ecx, cr3 + mov [eax + 46], ecx ;cr3 + mov [eax + 34], edi ;eip + pop edx + pop ecx + pop eax + mov eax, 1 + iret +.sys_spawn: + push ecx + push edx + call scheduler_spawn + test eax, eax + jnz .sys_spawn_spawned + pop edx + pop ecx + iret +.sys_spawn_spawned: + push eax + mov eax, [scheduler_CurrentProcess] + movzx eax, word [eax] ;proc ID + push eax +extern scheduler_enslave + call scheduler_enslave + add esp, 8 + pop edx + pop ecx + iret +.sys_abuse_map: + push ecx + push edx + push edi + call scheduler_find + add esp, 4 + pop edx + pop ecx + + test eax, eax + jz .notfound + + push ecx + push edx + push ebx + push ecx + push edx + push esi + push dword [eax + 46] ;cr3 + mov eax, cr3 + push eax +extern vpm_double_map + call vpm_double_map + add esp, 24 + pop edx + pop ecx + + iret +.notfound: + mov eax, -1 + iret +.sys_release: + push ecx + push edx + push edi +extern scheduler_unslave + call scheduler_unslave + pop edi + pop edx + pop ecx + iret +.sys_abuse_state: + push ecx + push edx + push edi + call scheduler_find + add esp, 4 + pop edx + pop ecx + + test eax, eax + jz .notfound2 + + push ecx + push edx + push edx + push esi + push eax +extern process_abuse_state + call process_abuse_state + add esp, 12 + pop edx + pop ecx + + iret +.notfound2: + mov eax, -1 + iret +.sys_exit: + iret +.sys_event_wait: + push eax + push ecx + push edx + push edi + push dword [scheduler_CurrentProcess] +extern process_search_event + call process_search_event + add esp, 8 + pop edx + pop ecx + pop eax + iret + + +global scheduler_start: +scheduler_start: +.pic_init: + mov al, 0x10 | 0x01 + out 0x20, al + out 0xA0, al + + mov al, 32 + out 0x21, al + mov al, 40 + out 0xA1, al + + mov al, 4 + out 0x21, al + mov al, 2 + out 0xA1, al + + mov al, 0x01 + out 0x21, al + out 0xA1, al + +.pic_mask: + mov al, ~1 ;PIT + out 0x21, al + mov al, ~0 + out 0xA1, al + +.idt: + ; Page fault handler + mov eax, pgf_handler + and eax, 0x0000FFFF + or eax, 0x00080000 + mov [idt + 14 * 8], eax + + mov eax, pgf_handler + and eax, 0xFFFF0000 + or eax, (14 << 8) | (1 << 15) + mov [idt + 14 * 8 + 4], eax + + ; Double fault handler + mov eax, dbf_handler + and eax, 0x0000FFFF + or eax, 0x00080000 + mov [idt + 8 * 8], eax + + mov eax, dbf_handler + and eax, 0xFFFF0000 + or eax, (14 << 8) | (1 << 15) + mov [idt + 8 * 8 + 4], eax + + ; General protection fault handler + mov eax, gpf_handler + and eax, 0x0000FFFF + or eax, 0x00080000 + mov [idt + 13 * 8], eax + + mov eax, gpf_handler + and eax, 0xFFFF0000 + or eax, (14 << 8) | (1 << 15) + mov [idt + 13 * 8 + 4], eax + + ; Timer scheduler handler + mov eax, pit_handler + and eax, 0x0000FFFF + or eax, 0x00080000 + mov [idt + 32 * 8], eax + + mov eax, pit_handler + and eax, 0xFFFF0000 + or eax, (14 << 8) | (1 << 15) + mov [idt + 32 * 8 + 4], eax + + ; Spurious interrupt handler + mov eax, spur_handler + and eax, 0x0000FFFF + or eax, 0x00080000 + mov [idt + 39 * 8], eax + + mov eax, spur_handler + and eax, 0xFFFF0000 + or eax, (14 << 8) | (1 << 15) + mov [idt + 39 * 8 + 4], eax + + ; Software interrupt syscall entry point + mov eax, syscall_int_entry + and eax, 0x0000FFFF + or eax, 0x00080000 + mov [idt + 0xEC * 8], eax + + mov eax, syscall_int_entry + and eax, 0xFFFF0000 + or eax, (14 << 8) | (1 << 15) | (3 << 13) + mov [idt + 0xEC * 8 + 4], eax + + push idt + push (idt.end - idt - 1) << 16 + lidt [esp + 2] + add esp, 8 + +.pit: + mov al, (2 << 1) | (2 << 4) + out 0x43, al + + mov al, (1193182 / TIMER_FREQUENCY) % 256 + out 0x40, al + mov al, (1193182 / TIMER_FREQUENCY) / 256 + out 0x40, al + + sti + +haltLoop: + hlt + jmp haltLoop + +; ecx = id +toggle_irq_mask: + push ecx + push ebx + push edx + push eax + mov dx, 0x21 + cmp cl, 8 + jl .lower + sub cl, 8 + mov dx, 0xA1 +.lower: + mov bl, 1 + shl bl, cl + in al, dx + xor al, bl + out dx, al + pop eax + pop edx + pop ebx + pop ecx + ret + +irq_claim: + test edi, edi + jnz .notTimer + xor eax, eax + ret +.notTimer: + mov eax, [scheduler_CurrentProcess] + mov bx, [eax] ;id + lea eax, [edi * 8] + lea eax, [eax * 2 + edi] ;17x + lea eax, [eax + irqhandlers - 17] + mov [eax + 2], esi ;mov edi, handler + mov [eax + 7], bx ;mov esi, process id + mov ecx, edi + mov [eax + 12], cl + + push eax + and eax, 0x0000FFFF + or eax, 0x00080000 + mov [idt + edi * 8 + 256], eax + + pop eax + and eax, 0xFFFF0000 + or eax, (14 << 8) | (1 << 15) + mov [idt + edi * 8 + 256 + 4], eax + + mov eax, 1 + ret + +irqhandlers: + pushad + mov edi, strict dword 0 + mov esi, strict dword 0 + mov cl, strict byte 0 + jmp strict word irqhandler + pushad + mov edi, strict dword 0 + mov esi, strict dword 0 + mov cl, strict byte 0 + jmp strict word irqhandler + pushad + mov edi, strict dword 0 + mov esi, strict dword 0 + mov cl, strict byte 0 + jmp strict word irqhandler + pushad + mov edi, strict dword 0 + mov esi, strict dword 0 + mov cl, strict byte 0 + jmp strict word irqhandler + pushad + mov edi, strict dword 0 + mov esi, strict dword 0 + mov cl, strict byte 0 + jmp strict word irqhandler + pushad + mov edi, strict dword 0 + mov esi, strict dword 0 + mov cl, strict byte 0 + jmp strict word irqhandler + pushad + mov edi, strict dword 0 + mov esi, strict dword 0 + mov cl, strict byte 0 + jmp strict word irqhandler + pushad + mov edi, strict dword 0 + mov esi, strict dword 0 + mov cl, strict byte 0 + jmp strict word irqhandler + pushad + mov edi, strict dword 0 + mov esi, strict dword 0 + mov cl, strict byte 0 + jmp strict word irqhandler + pushad + mov edi, strict dword 0 + mov esi, strict dword 0 + mov cl, strict byte 0 + jmp strict word irqhandler + pushad + mov edi, strict dword 0 + mov esi, strict dword 0 + mov cl, strict byte 0 + jmp strict word irqhandler + pushad + mov edi, strict dword 0 + mov esi, strict dword 0 + mov cl, strict byte 0 + jmp strict word irqhandler + pushad + mov edi, strict dword 0 + mov esi, strict dword 0 + mov cl, strict byte 0 + jmp strict word irqhandler + pushad + mov edi, strict dword 0 + mov esi, strict dword 0 + mov cl, strict byte 0 + jmp strict word irqhandler + pushad + mov edi, strict dword 0 + mov esi, strict dword 0 + mov cl, strict byte 0 +irqhandler: + call toggle_irq_mask + mov al, 0x20 + out 0x20, al + push esi +extern scheduler_find + call scheduler_find + add esp, 4 + mov [eax + 55], edi + popad + iret + +idt: + times 256 dq 0 +.end: diff --git a/src/kernel/arch/x86/log.asm b/src/kernel/arch/x86/log.asm new file mode 100644 index 0000000..986cda0 --- /dev/null +++ b/src/kernel/arch/x86/log.asm @@ -0,0 +1,67 @@ +section .data + +section .text + +global klogc +klogc: + mov eax, [esp + 4] + out 0xE9, al + ret + +global klogs +klogs: + mov ecx, [esp + 4] +.lup: + mov al, [ecx] + test al, al + jz .end + out 0xE9, al + inc ecx + jmp .lup +.end: + ret + +;~ global klogp +;~ klogp: + ;~ push eax + ;~ mov edx, [esp + 12] + ;~ mov eax, edx + ;~ shr eax, 28 + ;~ call .logh + ;~ mov eax, edx + ;~ shr eax, 24 + ;~ and al, 0x0F + ;~ call .logh + ;~ mov eax, edx + ;~ shr eax, 20 + ;~ and al, 0x0F + ;~ call .logh + ;~ mov eax, edx + ;~ shr eax, 16 + ;~ and al, 0x0F + ;~ call .logh + ;~ mov eax, edx + ;~ shr eax, 12 + ;~ and al, 0x0F + ;~ call .logh + ;~ mov eax, edx + ;~ shr eax, 8 + ;~ and al, 0x0F + ;~ call .logh + ;~ mov eax, edx + ;~ shr eax, 4 + ;~ and al, 0x0F + ;~ call .logh + ;~ mov eax, edx + ;~ and al, 0x0F + ;~ call .logh + ;~ pop eax + ;~ ret +;~ .logh: + ;~ add al, '0' + ;~ cmp al, '0' + 9 + ;~ jle .p + ;~ add al, 7 +;~ .p: + ;~ out 0xE9, al + ;~ ret diff --git a/src/kernel/arch/x86/mem.c b/src/kernel/arch/x86/mem.c new file mode 100644 index 0000000..aba16f5 --- /dev/null +++ b/src/kernel/arch/x86/mem.c @@ -0,0 +1,15 @@ +#include"mem.h" + +void kmemw1(void *_ptr, uint8_t val, size_t amount) { + uint8_t *ptr = _ptr; + for(size_t i = 0; i < amount; i++) { + *(ptr++) = val; + } +} + +void kmemw4(void *_ptr, uint32_t val, size_t amount) { + uint32_t *ptr = _ptr; + for(size_t i = 0; i < amount; i++) { + *(ptr++) = val; + } +} \ No newline at end of file diff --git a/src/kernel/arch/x86/mem.h b/src/kernel/arch/x86/mem.h new file mode 100644 index 0000000..231f798 --- /dev/null +++ b/src/kernel/arch/x86/mem.h @@ -0,0 +1,10 @@ +#ifndef _MEM_H +#define _MEM_H + +#include +#include + +void kmemw1(void *ptr, uint8_t val, size_t amount); +void kmemw4(void *ptr, uint32_t val, size_t amount); + +#endif \ No newline at end of file diff --git a/src/kernel/arch/x86/pci.c b/src/kernel/arch/x86/pci.c new file mode 100644 index 0000000..a126f9c --- /dev/null +++ b/src/kernel/arch/x86/pci.c @@ -0,0 +1,60 @@ +#include"pci.h" + +#include +#include"vpm.h" + +size_t claimedCount = 0; +uint32_t *claimed; + +void pci_init() { + uint32_t cr3; + asm volatile("movl %%cr3, %0" : "=r" (cr3) :); + + claimed = vpm_map(cr3, VPM_KERNEL, -1, -1, 4096); +} + +uint32_t pci_claim(uint32_t cscp) { + for(int b = 0; b < 256; b++) { + for(int d = 0; d < 32; d++) { + for(int f = 0; f < 8; f++) { + uint32_t id = (b << 16) | (d << 11) | (f << 8); + if((pci_read(id, 8) & 0xFFFFFF00) == cscp) { + for(size_t i = 0; i < claimedCount; i++) { + if(claimed[i] == id) { + goto cont; + } + } + + claimed[claimedCount++] = id; + return id; + } +cont:; + } + } + } + return -1; +} + +uint32_t pci_read(uint32_t id, uint8_t offset) { + asm volatile("outl %%eax, %%dx" : : "a"(0x80000000 | id | offset), "d"(0xCF8)); + + uint32_t ret; + asm volatile("inl %%dx, %%eax" : "=a"(ret) : "d"(0xCFC)); + + return ret; +} + +void pci_write_1(uint32_t id, uint8_t offset, uint8_t val) { + asm volatile("outl %%eax, %%dx" : : "a"(0x80000000 | id | offset), "d"(0xCF8)); + asm volatile("outb %%al, %%dx" : : "a"(val), "d"(0xCFC + (offset & 3))); +} + +void pci_write_2(uint32_t id, uint8_t offset, uint16_t val) { + asm volatile("outl %%eax, %%dx" : : "a"(0x80000000 | id | offset), "d"(0xCF8)); + asm volatile("outw %%ax, %%dx" : : "a"(val), "d"(0xCFC + (offset & 2))); +} + +void pci_write_4(uint32_t id, uint8_t offset, uint32_t val) { + asm volatile("outl %%eax, %%dx" : : "a"(0x80000000 | id | offset), "d"(0xCF8)); + asm volatile("outl %%eax, %%dx" : : "a"(val), "d"(0xCFC)); +} \ No newline at end of file diff --git a/src/kernel/arch/x86/pci.h b/src/kernel/arch/x86/pci.h new file mode 100644 index 0000000..3422352 --- /dev/null +++ b/src/kernel/arch/x86/pci.h @@ -0,0 +1,13 @@ +#ifndef _PCI_H +#define _PCI_H + +#include + +void pci_init(); +uint32_t pci_claim(uint32_t); +uint32_t pci_read(uint32_t, uint8_t); +void pci_write_1(uint32_t, uint8_t, uint8_t); +void pci_write_2(uint32_t, uint8_t, uint16_t); +void pci_write_4(uint32_t, uint8_t, uint32_t); + +#endif \ No newline at end of file diff --git a/src/kernel/arch/x86/ppm.c b/src/kernel/arch/x86/ppm.c new file mode 100644 index 0000000..6af5056 --- /dev/null +++ b/src/kernel/arch/x86/ppm.c @@ -0,0 +1,64 @@ +#include"ppm.h" + +#include + +typedef struct __attribute__((packed)) { + uint64_t start; + uint32_t length; + uint8_t flags; + uint8_t data[]; +} PPMBitmap; + +PPMBitmap *ppm_Bitmap; + +static int availability_test(PPMBitmap *bm, size_t pg, size_t len) { + if(pg > bm->length - len) { + return 0; + } + + while(len--) { + if(bm->data[pg / 8] & (1 << (pg % 8))) { + return 0; + } + + pg++; + } + + return 1; +} + +static int mark(PPMBitmap *bm, size_t pg, size_t len) { + if(pg > bm->length - len) { + return 0; + } + + while(len--) { + bm->data[pg / 8] |= 1 << (pg % 8); + + pg++; + } + + return 1; +} + +uint64_t ppm_alloc(size_t len) { + PPMBitmap *bm = ppm_Bitmap; + + for(int bmid = 0; bmid < 2; bmid++) { + if(bm->length < len) { + continue; + } + + for(size_t pg = 0; pg <= bm->length - len; pg++) { + if(availability_test(bm, pg, len)) { + if(mark(bm, pg, len)) { + return bm->start + pg * 4096; + } + } + } + + bm = (PPMBitmap*) ((uintptr_t) bm + sizeof(*bm) + (bm->length + 7) / 8); + } + + return 0; +} diff --git a/src/kernel/arch/x86/ppm.h b/src/kernel/arch/x86/ppm.h new file mode 100644 index 0000000..f1bd5d5 --- /dev/null +++ b/src/kernel/arch/x86/ppm.h @@ -0,0 +1,9 @@ +#ifndef _PPM_H +#define _PPM_H + +#include +#include + +uint64_t ppm_alloc(size_t len); + +#endif diff --git a/src/kernel/arch/x86/process.h b/src/kernel/arch/x86/process.h new file mode 100644 index 0000000..efa6a39 --- /dev/null +++ b/src/kernel/arch/x86/process.h @@ -0,0 +1,46 @@ +#ifndef _PROCESS_H +#define _PROCESS_H + +#include + +struct Canal; +struct Link; + +typedef struct __attribute__((packed)) { + uint32_t eax; //0 + uint32_t ebx; //4 + uint32_t ecx; //8 + uint32_t edx; //12 + uint32_t esi; //16 + uint32_t edi; //20 + uint32_t ebp; //24 + uint32_t esp; //28 + uint32_t eip; //32 + uint32_t eflags; //36 + uint32_t cs; //40 + uint32_t cr3; //44 +} Context; + +#define WAIT_TYPE_NONE 0 +#define WAIT_TYPE_SIGNAL 1 +#define WAIT_TYPE_TIME 2 +#define WAIT_TYPE_IRQ 3 +#define WAIT_TYPE_MINOR 4 + +typedef struct __attribute__((packed)) Process { + uint16_t id; + Context ctx; + uint8_t waitType; + uint32_t waitValue; + uint32_t irqWaiting; + uint8_t minipriority; + struct Process *next; + uint16_t ownerId; + uint8_t eventsRequest; + uint8_t eventsSignal; + uint8_t eventsClosed; + struct Canal *ownedCanal; + struct Link *guestLinks; +} Process; + +#endif diff --git a/src/kernel/arch/x86/scheduler.c b/src/kernel/arch/x86/scheduler.c new file mode 100644 index 0000000..dea82e1 --- /dev/null +++ b/src/kernel/arch/x86/scheduler.c @@ -0,0 +1,301 @@ +#include"scheduler.h" + +#include"vpm.h" +#include"mem.h" + +#include + +#include"canal.h" + +#define PROCESS_ZONE_SIZE 4096 +#define HANDLE_ZONE_SIZE 4096 + +Process *scheduler_ProcessZone = 0; +Process *scheduler_ProcessQueues[TOTAL_PRIORITIES]; + +static int scheduler_CurrentPriority; +volatile Process *scheduler_CurrentProcess = 0; + +uint32_t scheduler_Tick; + +void klogs(const char *str); +void klogc(int c); + +static void klogp(void *p) { + static char hex[16]="0123456789ABCDEF"; + + uintptr_t i = (uintptr_t) p; + klogc(hex[(i >> 28) & 0xF]); + klogc(hex[(i >> 24) & 0xF]); + klogc(hex[(i >> 20) & 0xF]); + klogc(hex[(i >> 16) & 0xF]); + klogc(hex[(i >> 12) & 0xF]); + klogc(hex[(i >> 8) & 0xF]); + klogc(hex[(i >> 4) & 0xF]); + klogc(hex[(i >> 0) & 0xF]); +} + +void scheduler_init() { + uint32_t cr3; + asm volatile("movl %%cr3, %0" : "=r" (cr3) :); + + scheduler_ProcessZone = vpm_map(cr3, VPM_KERNEL, -1, -1, PROCESS_ZONE_SIZE); + kmemw1(scheduler_ProcessZone, 0, PROCESS_ZONE_SIZE); +} + +static int consider_switch(Process *p) { + if(p->waitType == WAIT_TYPE_SIGNAL) { + uint32_t meta = 0; + uint32_t canalId = -1; + uint32_t which = is_signal_awaiting_to_concerning_link(p->id, p->waitValue, &meta, &canalId); + if(which != 0xFFFFFFFF) { + p->waitType = WAIT_TYPE_NONE; + p->ctx.eax = which; + p->ctx.edx = meta; + p->ctx.ebx = canalId; + } else return 0; + } else if(p->waitType == WAIT_TYPE_TIME) { + if(p->waitValue <= scheduler_Tick) { + p->waitType = WAIT_TYPE_NONE; + } else return 0; + } else if(p->waitType == WAIT_TYPE_IRQ) { + if(p->irqWaiting) { + p->waitType = WAIT_TYPE_NONE; + p->ctx.eip = p->irqWaiting; + p->irqWaiting = 0; + } else return 0; + } else if(p->waitType == WAIT_TYPE_MINOR) { + //asm("xchg %bx, %bx"); + return 0; + } + + /*static char hex[16]="0123456789ABCDEF"; + klogc('0' + p->id); + klogc(' '); + klogc(hex[p->priority / PRIORITY_UNIT]); + klogc('\n');*/ + + scheduler_CurrentPriority = p->minipriority / PRIORITY_UNIT; + scheduler_CurrentProcess = p; + + return 1; +} + +void scheduler_switch() { + if(scheduler_CurrentProcess == 0) { + for(int p = 0; p < TOTAL_PRIORITIES; p++) { + Process *q = scheduler_ProcessQueues[p]; + while(q) { + if(consider_switch(q)) { + return; + } + q = q->next; + } + } + + scheduler_CurrentProcess = 0; + + return; + } + + for(int p = 0; p < scheduler_CurrentPriority; p++) { + Process *q = scheduler_ProcessQueues[p]; + + while(q) { + if(consider_switch(q)) { + return; + } + q = q->next; + } + } + + Process *p = scheduler_CurrentProcess; + do { + p = p->next; + + if(!p) { + p = scheduler_ProcessQueues[scheduler_CurrentPriority]; + } + + if(consider_switch(p)) { + return; + } + } while(p != scheduler_CurrentProcess); + + for(int p = scheduler_CurrentPriority + 1; p < TOTAL_PRIORITIES; p++) { + Process *q = scheduler_ProcessQueues[p]; + + while(q) { + if(consider_switch(q)) { + return; + } + q = q->next; + } + } + + scheduler_CurrentProcess = 0; +} + +Process *scheduler_find(uint16_t id) { + for(int p = 0; p < TOTAL_PRIORITIES; p++) { + Process *q = scheduler_ProcessQueues[p]; + + while(q) { + if(q->id == id) { + return q; + } + q = q->next; + } + } + + return NULL; +} + +static uint16_t next_free_id() { + for(uint32_t id = 1; id < 65536; id++) { + if(!scheduler_find(id)) { + return id; + } + } + return 0; +} + +Process *scheduler_spawn(int minipriority) { + int found = 0; + Process *p = scheduler_ProcessZone; + + for(size_t i = 0; i < PROCESS_ZONE_SIZE / sizeof(Process); i++) { + if(p->id == 0) { + found = 1; + break; + } + + p++; + } + + if(!found) { + return NULL; + } + + kmemw1(p, 0, sizeof(*p)); + p->id = next_free_id(); + p->ctx.eflags = EFLAGS_RESET | EFLAGS_IF | EFLAGS_IOPL_3; + p->ctx.cs = 24 | RPL_3; + p->waitType = WAIT_TYPE_NONE; + p->irqWaiting = 0; + p->minipriority = minipriority; + p->next = scheduler_ProcessQueues[minipriority / PRIORITY_UNIT]; + p->eventsRequest = 0; + p->eventsSignal = 0; + p->eventsClosed = 0; + p->ownedCanal = NULL; + p->guestLinks = NULL; + + scheduler_ProcessQueues[minipriority / PRIORITY_UNIT] = p; + + return p; +} + +size_t scheduler_enslave(uint16_t ownerId, Process *child) { + child->waitType = WAIT_TYPE_MINOR; + child->ownerId = ownerId; + + // Should not be how it works. + child->ctx.cr3 = vpm_create_space(); + + return child->id; +} + +int scheduler_unslave(size_t handle) { + struct Process *proc = scheduler_find(handle); + if(proc && proc->waitType == WAIT_TYPE_MINOR) { + proc->waitType = WAIT_TYPE_NONE; + return 0; + } + return -1; +} + +#define SYS_STATE_X86_EIP 0 +int process_abuse_state(struct Process *proc, size_t type, uintmax_t val) { + switch(type) { + case SYS_STATE_X86_EIP: + proc->ctx.eip = val; + break; + default: + return -1; + } + return 0; +} + +#define KEV_TYPE_NONE 0 +#define KEV_TYPE_LINK_REQUEST 1 +#define KEV_TYPE_LINK_SIGNAL 2 +#define KEV_TYPE_LINK_CLOSE 3 +typedef struct __attribute__((packed)) { + uint8_t type; + uint32_t canalId; + void *area; + uint32_t meta; +} KEvent; + +int process_search_event(Process *proc, KEvent *kev) { + if(proc->eventsRequest) { + kev->type = KEV_TYPE_LINK_REQUEST; + + Canal *c = proc->ownedCanal; + while(c) { + Link *l = c->links; + + while(l) { + if(!(l->flags & LINK_FLAG_ACCEPTED)) { + kev->canalId = l->canalId; + + return 1; + } + + l = l->nextInCanal; + } + + c = c->ownedNext; + } + } + + if(proc->eventsSignal) { + kev->type = KEV_TYPE_LINK_SIGNAL; + + Link *l = proc->guestLinks; + while(l) { + if(l->flags & LINK_FLAG_H2G) { + kev->area = signal_accept(proc, l, &kev->meta); + + return 1; + } + + l = l->nextGuestLink; + } + } + + if(proc->eventsSignal) { + kev->type = KEV_TYPE_LINK_SIGNAL; + + Canal *c = proc->ownedCanal; + while(c) { + Link *l = c->links; + while(l) { + if(l->flags & LINK_FLAG_G2H) { + kev->area = signal_accept(proc, l, &kev->meta); + + return 1; + } + + l = l->nextInCanal; + } + + c = c->ownedNext; + } + } + + kev->type = KEV_TYPE_NONE; + + return 0; +} diff --git a/src/kernel/arch/x86/scheduler.h b/src/kernel/arch/x86/scheduler.h new file mode 100644 index 0000000..c603c71 --- /dev/null +++ b/src/kernel/arch/x86/scheduler.h @@ -0,0 +1,22 @@ +#ifndef _SCHEDULER_H +#define _SCHEDULER_H + +#include"process.h" +#include + +void scheduler_init(); +void scheduler_switch(); +Process *scheduler_spawn(); +size_t scheduler_create_handle(uint16_t ownerId, Process *child); + +Process *scheduler_find(uint16_t procId); + +#define MAX_MINIPRIORITY 255 +#define TOTAL_PRIORITIES 16 +#define PRIORITY_UNIT ((MAX_MINIPRIORITY + 1) / TOTAL_PRIORITIES) + +//extern size_t scheduler_ProcessCount; +extern Process *scheduler_ProcessZone; +extern Process *scheduler_ProcessQueues[TOTAL_PRIORITIES]; + +#endif diff --git a/src/kernel/arch/x86/vpm.c b/src/kernel/arch/x86/vpm.c new file mode 100644 index 0000000..8b4dcfc --- /dev/null +++ b/src/kernel/arch/x86/vpm.c @@ -0,0 +1,268 @@ +#include"vpm.h" + +#include"ppm.h" +#include"mem.h" + +extern void *_kernel_end; + +void set_temporary_mapping(uint32_t addr) { + if((addr & 0xFFF) != 0) asm volatile("xchgw %bx, %bx"); + + *(volatile uint32_t*) 0xFFFFFFF8 = addr | 3; + asm volatile("invlpg 0xFFFFE000" : : : "memory"); +} + +static uint32_t nextAllocs[2] = {[VPM_KERNEL] = 0, [VPM_USER] = 1 * 1024 * 1024 * 1024}; + +void vpm_init(uint32_t kernelEnd) { + nextAllocs[VPM_KERNEL] = (kernelEnd + 4095) & ~4095; +} + +/* TODO: Make better. */ +uint32_t vpm_find_free(uint32_t addrspace, AllocationOwner owner, size_t lenBytes) { + size_t len = (lenBytes + 4095) / 4096; + + uint32_t ret = nextAllocs[owner]; + for(size_t i = 0; i < len;) { + uint32_t pdeid = (ret + i * 4096) >> 22; + uint32_t pteid = ((ret + i * 4096) >> 12) & 1023; + + set_temporary_mapping(addrspace); + + volatile uint32_t *pde = &((volatile uint32_t*) 0xFFFFE000)[pdeid]; + if((*pde & 1) == 0) { + i += 4096; + } else { + set_temporary_mapping(*pde & ~0xFFF); + + if((((volatile uint32_t*) 0xFFFFE000)[pteid] & 1) == 0) { + i++; + } else { + ret += (i + 1) * 4096; + i = 0; + } + } + } + + return ret; +} + +/* If phys is -1, map to uncontiguous physical pages anywhere, else map contiguous span of physical memory. */ +/* If phys is -2, automatically find contiguous span of physical memory */ +/* If virt is -1, find free space, else overwrite. */ +void *vpm_map(uint32_t addrspace, AllocationOwner owner, uint32_t virt, uint32_t phys, size_t len) { + uint32_t thisspace; + asm volatile("movl %%cr3, %0" : "=r" (thisspace) :); + + //if(len == 32768)asm("xchg %%bx, %%bx":::); + + if(virt == -1) { + virt = vpm_find_free(addrspace, owner, len); + } + + len = (len + 4095) / 4096; + + if(phys == -2) { + phys = ppm_alloc(len); + + if(!phys) { + goto error; + } + } + + for(size_t i = 0; i < len; i++) { + set_temporary_mapping(addrspace); + + uint32_t pdeid = (virt + i * 4096) >> 22; + uint32_t pteid = ((virt + i * 4096) >> 12) & 1023; + + volatile uint32_t *pde = &((volatile uint32_t*) 0xFFFFE000)[pdeid]; + + if((*pde & 1) == 0) { + uint64_t physpag = ppm_alloc(1); + + if(physpag) { + *pde = physpag | 3 | (owner == VPM_USER ? 4 : 0); + } else { + goto error; + } + } + set_temporary_mapping(*pde & ~0xFFF); + + volatile uint32_t *pte = &((volatile uint32_t*) 0xFFFFE000)[pteid]; + if(phys == -1) { + *pte = ppm_alloc(1); + if(!*pte) goto error; + } else { + *pte = phys + i * 4096; + } + *pte |= 3 | (owner == VPM_USER ? 4 : 0); + + if(thisspace == addrspace) { + //~ asm volatile("xchg %bx, %bx"); + asm volatile("invlpg %0" : : "m"(*(char*) (virt + i * 4096)) : "memory"); + } + } + + return (void*) virt; + +error: + // TODO: Deallocate physical pages. + + return 0; +} + +int vpm_double_map(uint32_t cr3a, uint32_t cr3b, uint32_t *va, uint32_t *vb, uintptr_t phys, size_t len) { + uint32_t thisspace; + asm volatile("movl %%cr3, %0" : "=r" (thisspace) :); + + if(*va == -1) { + *va = vpm_find_free(cr3a, VPM_USER, len); + } + if(*vb == -1) { + *vb = vpm_find_free(cr3b, VPM_USER, len); + } + + len = (len + 4095) / 4096; + + if(phys == -2) { + phys = ppm_alloc(len); + } + + for(size_t i = 0; i < len; i++) { + uint32_t backend; + + if(phys == -1) { + backend = ppm_alloc(1); + if(!backend) goto error; + } else { + backend = phys + i * 4096; + } + + { + set_temporary_mapping(cr3a); + + uint32_t pdeid = (*va + i * 4096) >> 22; + uint32_t pteid = ((*va + i * 4096) >> 12) & 1023; + + volatile uint32_t *pde = &((volatile uint32_t*) 0xFFFFE000)[pdeid]; + + if((*pde & 1) == 0) { + uintptr_t physpag = ppm_alloc(1); + + if(physpag) { + *pde = physpag | 3 | 4; + } else { + goto error; + } + } + + set_temporary_mapping(*pde & ~0xFFF); + + volatile uint32_t *pte = &((volatile uint32_t*) 0xFFFFE000)[pteid]; + + *pte = backend | 3 | 4; + + if(thisspace == cr3a) { + asm volatile("invlpg %0" : : "m"(*(char*) (*va + i * 4096)) : "memory"); + } + } + + { + set_temporary_mapping(cr3b); + + uint32_t pdeid = (*vb + i * 4096) >> 22; + uint32_t pteid = ((*vb + i * 4096) >> 12) & 1023; + + volatile uint32_t *pde = &((volatile uint32_t*) 0xFFFFE000)[pdeid]; + + if((*pde & 1) == 0) { + uintptr_t physpag = ppm_alloc(1); + + if(physpag) { + *pde = physpag | 3 | 4; + } else { + goto error; + } + } + + set_temporary_mapping(*pde & ~0xFFF); + + volatile uint32_t *pte = &((volatile uint32_t*) 0xFFFFE000)[pteid]; + + *pte = backend | 3 | 4; + + if(thisspace == cr3b) { + asm volatile("invlpg %0" : : "m"(*(char*) (*vb + i * 4096)) : "memory"); + } + } + } + + return 1; + +error: + return 0; +} + +uint32_t vpm_create_space() { + uint32_t curPD; + asm volatile("movl %%cr3, %0" : "=r"(curPD) :); + set_temporary_mapping(curPD); + + uint32_t pde0000 = *(volatile uint32_t*) 0xFFFFE000; + uint32_t pde1023 = *(volatile uint32_t*) 0xFFFFEFFC; + + uint32_t newPD = ppm_alloc(1); + + set_temporary_mapping(newPD); + + *(volatile uint32_t*) 0xFFFFE000 = pde0000; + kmemw4((void*) 0xFFFFE004, 0, 1022); + *(volatile uint32_t*) 0xFFFFEFFC = pde1023; + + return newPD; +} + +void vpm_set_space(uint32_t cr3) { + asm volatile("movl %0, %%cr3" : : "r"(cr3)); +} + +uint32_t vpm_get_phys(uint32_t cr3, uint32_t v) { + uint32_t offset = v & 4095; + + uint32_t pdeid = v >> 22; + uint32_t pteid = (v >> 12) & 1023; + + set_temporary_mapping(cr3); + set_temporary_mapping(((uint32_t*) 0xFFFFE000)[pdeid] & ~0xFFF); + + return (((uint32_t*) 0xFFFFE000)[pteid] & ~0xFFF) + offset; +} + +void vpm_unmap(uint32_t cr3, uint32_t virt, size_t len) { + uint32_t thisspace; + asm volatile("movl %%cr3, %0" : "=r"(thisspace) :); + + len = (len + 4095) / 4096; + + for(size_t i = 0; i < len; i++) { + set_temporary_mapping(cr3); + + uint32_t pdeid = (virt + i * 4096) >> 22; + uint32_t pteid = ((virt + i * 4096) >> 12) & 1023; + + volatile uint32_t *pde = &((volatile uint32_t*) 0xFFFFE000)[pdeid]; + + if((*pde & 1) == 0) { + continue; + } + + set_temporary_mapping(*pde & ~0xFFF); + + ((volatile uint32_t*) 0xFFFFE000)[pteid] = 0; + + if(thisspace == cr3) { + asm volatile("invlpg %0" : : "m"(*(char*) (virt + i * 4096)) : "memory"); + } + } +} diff --git a/src/kernel/arch/x86/vpm.h b/src/kernel/arch/x86/vpm.h new file mode 100644 index 0000000..63b4816 --- /dev/null +++ b/src/kernel/arch/x86/vpm.h @@ -0,0 +1,24 @@ +#ifndef _VPM_H +#define _VPM_H + +#include +#include + +typedef struct { + uint32_t from, to; +} SharedRange; + +typedef enum { + VPM_KERNEL, VPM_USER +} AllocationOwner; + +void set_temporary_mapping(uint32_t addr); + +uint32_t vpm_find_free(uint32_t addrspace, AllocationOwner owner, size_t len); +void *vpm_map(uint32_t cr3, AllocationOwner owner, uint32_t virt, uint32_t phys, size_t len); +uint32_t vpm_create_space(); +void vpm_set_space(uint32_t cr3); +uint32_t vpm_get_phys(uint32_t cr3, uint32_t); +void vpm_unmap(uint32_t cr3, uint32_t virt, size_t len); + +#endif \ No newline at end of file