This commit is contained in:
Alvin-Zilverstand committed 2026-10-09 03:19:53 +02:00
1 parent 6dc841f956
commit 3d06f94e48
46 files changed
+5830 -543

No files matched your search

+210 -53
View File
@@ -47,8 +47,8 @@ the existing emulator/build outputs stay separate.
walks low and upper canonical virtual addresses and physical/table addresses
above 4 GiB, and verifies writable pages can become read-only/NX, be unmapped,
and be mapped again. The handoff activates the root after enabling `EFER.NXE`
when supported; host tests cover mapping logic, while the privileged switch
still needs UEFI runtime verification.
when supported; QEMU runtime smoke tests verify active mappings through the
kernel memory and user-page-protection checks.
- `bob64/bootstrap.c` composes that mapper into a bootstrap identity address
space for the loaded EFI image, a replacement stack, and a pre-reserved
contiguous page-table pool. It marks stack/pool pages NX when supported and
@@ -105,8 +105,10 @@ the existing emulator/build outputs stay separate.
pages into a 64 MiB high-half range at `0xffff900000000000`. New pages are
zeroed before use. Kernel entry smoke-tests multi-page allocations, alignment,
zeroing, writes, frees, and double-free rejection. Host tests cover splitting,
coalescing, overflow, and invalid frees. This early heap is single-core and
does not reclaim empty pages yet.
coalescing, overflow, invalid frees, and four-thread allocation/free stress.
Heap metadata is protected by an atomic lock; kernel builds disable local
interrupts while holding it to avoid same-CPU interrupt deadlocks. SMP is not
enabled in the kernel, so hardware multicore runtime contention is untested.
- `bob64/keyboard.c` decodes PS/2 set-1 input, including shift, caps lock,
editing keys, and Pause/extended sequences. IRQ1 now feeds a bounded 64-event
queue used by the shell and app event service after the kernel remaps the PIC;
@@ -125,13 +127,19 @@ the existing emulator/build outputs stay separate.
- `bob64/snapshot.c` defines B64S version 1 as a pointer-free little-endian
format with 64-bit total/data lengths and a CRC-32. Restore validates version,
size, checksum, record bounds, names, and duplicate files before replacing
the live filesystem. The shell's `save` and `restore` commands keep one
checkpoint in the kernel heap for the current boot session; it is lost on
reboot. Host tests cover round-trip, empty files, replace-on-restore,
the live filesystem. The shell's `save` and `restore` commands keep a RAM
checkpoint and store a compressed B64S copy in a non-volatile UEFI variable
when firmware capacity permits. Startup restores that snapshot after
installing the default apps. Host tests cover round-trip, empty files,
replace-on-restore,
truncation, unsupported versions, checksum errors, and unchanged state after
rejected input. Disk persistence and directories remain future stages; the
app filesystem ABI supports bounded whole-file operations and ABI v10 streaming
handles with 64-bit seek positions and bounded reads/writes; hardware-backed
rejected input. A mock runtime-services suite verifies compressed variable
save/restore, corruption rejection, and missing-variable behavior. QEMU/OVMF
reboot testing saved a shell-created file to writable NVRAM, reset the VM, and
verified the file after automatic restore. Disk-backed
filesystem persistence and directories remain future stages; the
app filesystem ABI supports bounded whole-file operations and ABI v12 streaming
handles with 64-bit seek positions and bounded reads/writes; disk-backed
persistence remains outstanding.
- `bob64/exec.c` defines B64E version 1, a flat position-independent 64-bit
executable image with a versioned ABI, exact payload length, 64-bit memory
@@ -140,7 +148,10 @@ the existing emulator/build outputs stay separate.
images before returning a view; a contiguous copy helper preflights capacity
and address overflow, copies the image, clears the memory-only tail, and
preserves entry addresses above 4 GiB. Mapped application loading is provided
separately by `process.c`. A synthetic B64E app now runs at CPL3, writes
separately by `process.c`. The `bob64cc` packager keeps PE zero-fill data out
of the B64E file while retaining its full 64-bit `MemorySize`; the desktop
image is about 37 KiB on disk and still maps over 4 MiB at runtime. A
synthetic B64E app now runs at CPL3, writes
`bob!` through syscall v2, performs a bounded RAM-file round trip, and exits
back to the saved kernel stack.
- `bob64/abi.h` starts application ABI v1 on the same Microsoft x64 calling
@@ -150,7 +161,7 @@ the existing emulator/build outputs stay separate.
32-byte startup record containing a 64-bit argument count and argv pointer.
The record and its strings are app-space data, so the contract does not pass
kernel pointers. Tests check the record layout, entry call, nested calls, and
stack-passed arguments. Syscall ABI v10 defines an ABI query, character and
stack-passed arguments. Syscall ABI v12 defines an ABI query, character and
bounded buffer output, file reads and writes, pixel-display query/present,
blocking keyboard and PS/2 mouse events, and process exit through interrupt
vector `0x80`; user pointers are validated
@@ -171,8 +182,8 @@ the existing emulator/build outputs stay separate.
lists RAM files in a separate window, supports selection/open/refresh and
confirmed deletion, plus insertion, line breaks, cursor movement, click
placement, scrolling, Ctrl+S save and an unsaved-exit prompt. It validates flat
filenames and protects an existing file over the current 4 KiB syscall limit
from accidental overwrite. The shell launches it with
filenames, streams files in 4 KiB chunks, and supports up to 16 KiB of text,
matching the resident compiler's source limit. The shell launches it with
`run desktop.b64e [filename]`; host tests cover the editor buffer, packaged
UI strings, file ABI and window manager. The full existing bob GUI, a file
picker and real UEFI interaction remain to be ported/verified.
@@ -187,24 +198,32 @@ the existing emulator/build outputs stay separate.
as B64E; `run app.b64e` launches it. The current syntax accepts `int` or
`long`, `long long`, or `int main(void)`, initialized `int`/`long`/`long long`
locals and assignments,
bounded `bob64_app_write` calls with string literals, and 64-bit integer
return expressions with parentheses, unary minus, addition, subtraction, and
multiplication. Its frame and entry wrapper follow the Microsoft x64 stack
contract; syscall ABI v10 provides exit, graphics output, whole-file and
`bob64_app_write` calls with typed `char *` expressions and scalar length
expressions, and 64-bit integer
return expressions with parentheses, unary minus, addition, subtraction,
multiplication, signed division/remainder, and unsigned pointer-sized
division/remainder. Signed division truncates toward zero. Its frame and entry
wrapper follow the Microsoft x64 stack
contract; syscall ABI v12 provides exit, graphics output, whole-file and
streaming file I/O/list/delete,
and input.
and input. Host compiler-model tests execute both 32-bit `long` truncation
and 64-bit pointer-sized values, while the test harness asserts the host and
UEFI targets use the documented LLP64 scalar widths.
The compiler recognizes `usize`/`uintptr_t` as unsigned 64-bit scalar types
and `isize`/`intptr_t` as signed 64-bit scalar types in declarations and
function signatures. These are built-in type names; typedefs and header
inclusion remain unsupported. `usize *`, `uintptr_t *`, `isize *`,
function signatures. These are built-in type names. Bounded file-scope
typedefs alias supported scalar types, scalar pointers, and previously
declared named structs; alias chains work, while typedef arrays, function
pointers, anonymous structs and header inclusion remain unsupported.
`usize *`, `uintptr_t *`, `isize *`,
`intptr_t *`, and `long long *` map to signed/unsigned wide-pointer types with
eight-byte loads, stores, indexing and scaled pointer arithmetic. They work as local,
parameter, return, global, and struct-field types; global pointers may target
matching scalar objects. Fixed-size signed and unsigned 64-bit arrays now
support local and global storage, initialization, indexing, mutation, array
parameter decay, and eight-byte element addressing. Local arrays are limited
to 16 elements by the fixed function frame; global arrays share the 4 KiB data
page.
parameter decay, and eight-byte element addressing. Local automatic storage
is bounded by the function frame; global arrays share the 16 KiB compiler data
region.
Function declarations and definitions can return `char *`, `short *`, `int *`,
and pointers to declared structs. Returned pointers keep all 64 bits; return
expressions must match the declared pointee type. Returning a pointer through
@@ -245,27 +264,58 @@ the existing emulator/build outputs stay separate.
GDT/IDT and new CR3. A deliberate invalid opcode was diagnosed with the full
register frame and returned to the kernel; the corrected smoke app now exits
normally. The IDT now also contains PIT, PS/2 keyboard, and PS/2 mouse IRQ
handlers; runtime IRQ-path verification remains pending below.
handlers; PIT tick advancement is now checked at runtime, keyboard IRQ
delivery is exercised by the shell/desktop sessions, and live mouse-event
assertions remain open below.
- [x] Verify actual ring-3 text protection and data NX behavior. QEMU runtime
probes attempt to write the read-only executable page and execute the NX data
page; both receive the expected user page-fault error bits and return to the
kernel. The kernel also checks that the stack guard is unmapped.
- [ ] Add dynamic page-table-pool growth, heap locking, and reclamation of empty
heap pages. The bootstrap identity map favors bring-up simplicity.
- [x] Grow the page-table pool dynamically in 64-page chunks, triggered while
eight reserve pages remain. New chunks are identity-mapped using the reserve
before becoming allocatable. Host bootstrap tests cover growth beyond the
initial 128 pages, and the kernel now runs a 140-table smoke test.
- [x] Verify the expanded page-table smoke test under QEMU; the runtime script
waits for its `dynamic page-table pool passed` marker.
- [x] Protect heap metadata with an atomic lock and disable local interrupts
while kernel callers hold it. Four-thread host stress covers concurrent
allocation, free, coalescing, and page shrinking. Kernel SMP is not enabled.
- [x] Reclaim full trailing heap pages when the final free block reaches the
heap end. The heap keeps its first page mapped, returns released physical
frames to the allocator, invalidates each removed virtual mapping, and
regrows contiguously when later allocations need the pages again. Host and
kernel smoke tests cover reclaim and regrowth.
- [x] Verify GOP, COM1, PS/2 keyboard, and mouse input under UEFI emulation.
QEMU showed mouse movement and a click selecting a file-list row; keyboard
input launched/closed the desktop and created a third window.
- [ ] Verify the new IRQ1 keyboard and IRQ12 mouse paths under UEFI emulation.
Host tests cover the IDT gates and bounded event queues; QEMU verification is
pending.
- [x] Add a 100 Hz PIT timer IRQ, tick counter, and user tick query. The timer
tick path is covered by host syscall tests; runtime QEMU verification remains
pending alongside keyboard/mouse IRQ checks.
- [ ] Add USB keyboard support and command history/completion. COM1 remains
polled.
- [ ] Add persistent storage for B64S snapshots. ABI v10 now supplies bounded
handle-based streaming reads/writes, 64-bit absolute seeks, create/truncate/
append modes, and per-app handle cleanup; physical persistence remains open.
- [x] Verify live IRQ1 keyboard and IRQ12 mouse input under UEFI emulation.
Host tests cover the IDT gates and bounded queues. Existing desktop runs
exercise keyboard input; the QEMU runner now injects a PS/2 mouse move,
launches a ring-3 event-wait app, and requires its nonzero movement event to
arrive through the syscall ABI.
- [x] Add a 100 Hz PIT timer IRQ, tick counter, and user tick query. Host tests
cover the syscall path, and the UEFI kernel now waits for a real tick before
continuing; QEMU checks the `timer tick passed` marker.
- [x] Add synchronous B64E child launch through syscall ABI v12, with validated
argv copying so native apps can open selected files or pass commands onward.
The user-entry
return bridge keeps eight nested return frames; per-app kernel stacks,
syscall-service contexts, file handles, and window-server sessions are
restored on return. Host syscall tests cover nested context restoration, and
the boot image includes a `bob!` nested-launch smoke app; QEMU runtime testing
confirms the child returns and the parent continues.
- [ ] Add USB keyboard support; COM1 remains polled.
- [x] Add an eight-command shell history on Up/Down and Tab completion for
built-in commands plus file arguments to `cat`, `rm`, `run`, and `cc`. Host
tests cover draft restoration, keyboard arrow translation, and unique command
and filename completion.
- [x] Verify compressed B64S persistence across reboot with writable OVMF
NVRAM. The kernel stores compressed snapshots in two alternating EFI slots,
split across bounded variables, and commits the active-slot record last. Host
tests cover multi-variable round-trip, corruption fallback, missing storage,
and firmware without `QueryVariableInfo`. QEMU/OVMF runtime testing saved a
file in the shell, reset the VM, restored the snapshot, and verified that
file. Disk-backed filesystem persistence remains open.
- [ ] Port remaining device services and add USB keyboard support.
- [x] Add typed pointer returns to the resident x86-64 compiler for
`char *`, `short *`, `int *`, and declared struct pointers. Tests cover
@@ -281,16 +331,16 @@ the existing emulator/build outputs stay separate.
pointer values above 4 GiB.
- [x] Add fixed signed and unsigned 64-bit arrays with local/global storage,
initialization, indexed reads/writes, and array-parameter decay. Local arrays
are bounded to 16 elements and global data to the existing 4 KiB page.
are bounded to 16 elements and global data to the compiler's 16 KiB limit.
File-scope `short`, `int`, `long`, `char`, and `long long` scalars plus bounded
fixed `short`/`int`/`char` arrays now use initialized writable B64E data and
RIP-relative x64 access across functions. Global `short *`/`int *`/`char *`
initializers may target
previously declared arrays or string literals. Named structs define aligned
scalar/pointer layouts and support local/global instances plus `.`/`->` field
loads/stores. Struct arrays, nested structs, typedefs, and multiple translation
loads/stores. Struct arrays, nested structs, and multiple translation
units remain unsupported. Limits are 8 struct types, 16 fields per type, 16
global objects, and the single 4 KiB data page.
global objects, within the compiler's 16 KiB global data limit.
Local fixed `short`/`int` arrays, `short *`/`int *` locals,
dereference/indexing, scaled pointer arithmetic and pointer differences, and
local brace initializers are
@@ -316,34 +366,141 @@ the existing emulator/build outputs stay separate.
nearest loop; `for` continue enters its update clause. Early `return`
statements work inside branches and loops; the subset still requires a final
return at the end of each function.
- [x] Expand the resident compiler's bounded source, machine-code, and global
data capacities from 4 KiB each to 16 KiB each. Host execution tests compile
and run a source file larger than 4 KiB with generated code beyond the old
page limit, and access an 8 KiB global array. B64E still separates read-only
code from writable/NX data pages.
- [x] Expand resident C function frames from 128 bytes and 16 variables to a
1 KiB frame and 64 variables. Code generation now uses disp8 or disp32 RBP
operands as needed. Host execution tests cover forty local scalars, a 64-item
local integer array and a 256-byte initialized character array.
- [x] Add bounded resident C typedefs for scalar, pointer, and named-struct
aliases. Host execution tests cover aliases in declarations, arrays, struct
fields, pointer parameters/returns, and member access through an aliased
struct pointer.
- [x] Add signed division/remainder and unsigned `usize` division/remainder to
resident C integer expressions. Host tests execute negative 64-bit operands
and an unsigned value above 4 GiB; the QEMU resident-compiler smoke program
covers signed truncation/remainder and wide unsigned arithmetic.
- [x] Add C-precedence bitwise complement, AND/XOR/OR, and left/right shifts.
Host execution tests cover operator precedence, signed arithmetic shift, and
unsigned right shift above 4 GiB; the QEMU resident-compiler smoke program
exercises the same operators in the running kernel.
- [x] Add a kernel-owned per-app window manager and port the desktop's file and
editor windows to its surfaces. Syscall ABI v10 creates, focuses, destroys,
editor windows to its surfaces. Syscall ABI v12 creates, focuses, destroys,
validates and copies app surfaces, composites z-order, routes input with
64-bit handles and local/screen coordinates, and releases the session on app
exit. Concurrent apps are still not displayed together.
- [x] Run the native desktop under QEMU/OVMF at 1280x800. Both managed windows
rendered; keyboard input created a third window, Escape returned to the
shell, and Ctrl+S saved editor text through the file syscall. The full screen
and B64S shell commands were also exercised in the same UEFI session.
- [ ] Port the remaining applications to the kernel window API. Syscall ABI v10
and B64S shell commands were also exercised in the same UEFI session. The
automated QEMU pass now opens the Applications window while both desktop
windows remain active, launches a child app, and repeats the GUI/child-app
round trip after B64S restore. The restored run opens the launcher, uses a
PS/2 mouse click on Run App and X CLOSE, then verifies Escape returns to the
shell.
- [x] Add a desktop launcher control for selected `.b64e` files. It runs the
child synchronously and displays its exit status after returning to the
editor; host packaging tests cover the control strings. QEMU/OVMF now opens
the Applications launcher, starts its selected `bob!` child, and verifies
that the desktop returns to the shell with a zero exit status.
- [x] Port reusable button behavior to the native framebuffer GUI. The
`bob64/widgets.h` button handles hover/pressed states and activates only on
an inside left-button release; the desktop uses it for Run App, APPS and
X CLOSE. Host tests cover hit bounds and cancel-on-release-outside; QEMU
verifies mouse launch and close interactions.
- [x] Port bounded single-line text entry to the native GUI and add Save As
through the desktop's filename field. Host tests cover caret placement,
insertion, deletion, horizontal reveal, and capacity bounds. QEMU clicks the
field, edits a filename, saves through the GUI, verifies the file from the
shell, and removes the smoke fixture.
- [x] Replace Bob64's two-press file deletion shortcut with a visible
Yes/Cancel confirmation window. `D` and the file-window Delete button open
the dialog; `Y`/Enter confirms and `N`/Escape cancels. The open editor file
remains protected. The handoff build and full QEMU/OVMF regression pass;
direct QEMU interaction coverage for this dialog remains to be added.
- [x] Port the Bob32 desktop's on-screen help overlay as a managed Bob64 help
window. It is reachable from the Files panel or `H`/`?`, and documents the
native desktop's current navigation, app-launch, delete, save, and focus
shortcuts. Host packaging tests assert the help window's contents.
- [x] Add a bounded file-browser preview to the Bob64 desktop. Selection changes
load up to 384 bytes into a separate scratch buffer, show text, mark truncated
files, and identify executable/binary files without putting them in the editor.
Host package checks assert the preview UI and its app/error states.
- [x] Port the argument-printing `echo` utility to the B64E startup ABI and
install it in the default RAM filesystem. The UEFI smoke path passes a
`bob!` argument and checks the native app output; the QEMU runtime script
verifies the app marker and argument output.
- [x] Port a native `ls.b64e` app over the 64-bit file-list syscall. The kernel
launches it during smoke testing and checks its output begins with the
installed `ls.b64e` filename; QEMU runtime testing confirms the marker.
- [x] Port a native `cat.b64e` app over streaming file handles. The kernel
smoke path reads a `bob!` RAM-file fixture, verifies the output, and removes
the fixture afterward; QEMU runtime testing confirms the marker.
- [x] Port Bob32's notes utility as native `notes.b64e`, with a desktop-editable
notes window and shell `show`, `put` / `edit`, `add`, and `delete` commands
over the 64-bit file ABI. It rejects binary files and is packaged for the
desktop app launcher. The kernel smoke path creates, shows, verifies, and
deletes a `bob!` note; QEMU runtime testing confirms its marker and output.
- [x] Port Bob32's keyboard/mouse application launcher into the Bob64 desktop.
It lists installed `.b64e` files, launches the selected app through the
nested-app ABI, and supports keyboard/mouse selection plus run/close controls.
Host packaging checks verify its visible title and shortcuts.
- [x] Match the text editor's Home/End line navigation from Bob32 and cover it
with native editor unit checks.
- [x] Protect Bob64 editor contents from executable/binary files. The GUI now
uses a scratch buffer, rejects `.b64e` and control-byte content, and leaves
the current document untouched when a binary file is selected.
- [x] Expand the desktop editor and Notes app to 16 KiB using high-level
streaming file helpers over the existing 4 KiB syscall transfers. Editor
unit checks fill the complete buffer and reject the first excess character.
- [x] Keep zero-fill PE sections out of B64E file payloads while preserving
their virtual memory sizes. Host packaging tests assert the desktop's
multi-megabyte zero-fill tail is loaded from B64E `MemorySize`, and QEMU
verifies the desktop runs and B64S save/restore still succeeds.
- [ ] Port the remaining applications to the kernel window API. Syscall ABI v11
also provides bounded file reads/writes/list/delete, console I/O,
full-screen presentation, blocking PS/2 keyboard/mouse events, ABI query, and
process exit. The host `bob64cc`
bridge continues to package the broader C subset supported by GCC.
- [ ] Port the remaining existing applications and full GUI/widget behavior;
the current native text editor is an initial, limited desktop milestone.
- [x] Port Bob32's graphics demo as a 640x400 kernel-composited Bob64 window.
The native `display.b64e` app draws colored panels and diagonal lines, prints
`bob!`, and returns to the shell on X or Escape. The QEMU runtime test checks
presentation, clean app exit, and compatibility with snapshot save/restore.
- [x] Port the system-information utility as native `info.b64e`. It reports the
syscall ABI, available display resolution, uptime, and RAM filesystem usage;
the kernel embeds and launches it in the application smoke path. The kernel
smoke test checks its captured ABI, uptime, filesystem fields, and final
`bob!` output; the QEMU runtime script confirms the marker and output.
- [x] Port the standalone application launcher to a native Bob64 window. It
lists installed `.b64e` apps, launches the selected app through the nested
app-run syscall, and closes on Escape/X/Close. Host packaging checks validate
the B64E image; QEMU opens it, checks `bob!`, and verifies a clean return to
the shell. The shell can also run the launcher with `APP [ARG ...]`; ABI v12
validates and forwards the full argv vector to the selected child.
- [x] Run the kernel-generated ring-3 `bob!` app under x64 UEFI emulation. The
resident compiler also compiled and launched `bob.c`; B64S `save`/`restore`
recovered a deleted file, and the native GUI opened and saved an editor file.
QEMU runtime test also compiles `bob.c` through the resident shell compiler,
launches the resulting B64E app, and checks `bob!` and a zero exit status.
The source exercises local character/integer arrays, helper functions, array
parameters, loops, pointer-based syscall output, computed string length,
forty local variables, a 64-element stack array and a nested call with sixteen
integer arguments (four register-passed and twelve stack-passed).
The test saves the compiled app in B64S, resets, and launches it again after
restore, then relaunches the GUI and a child app from the restored system.
- [ ] Complete the full acceptance flow and add runtime tests for broader
calling-convention/stack cases, hardware interrupts, mouse input, and
persistent B64S storage. The ring-3 app image runs at a virtual address above
calling-convention/stack cases and the remaining widget interactions.
The ring-3 app image runs at a virtual address above
4 GiB; host tests also cover synthetic high addresses and broad ABI/memory
cases.
- [x] Verify bob64 boots in x64 UEFI emulation and performs its own kernel
initialization without executing 32-bit kernel or app code. The broader
migration remains active: the resident C subset, devices, persistence, and
existing application ports still need work.
migration remains active: the resident C subset, USB and other device
support, disk-backed persistence, and remaining application ports still need
work.
## Build and test
@@ -352,7 +509,7 @@ build-tool --bob64
build-tool --bob64-test
build-tool --bob64-handoff
build-tool --bob64-handoff-test
tools/test_bob64_qemu.ps1 -QemuPath <qemu-system-x86_64.exe> -OvmfCodePath <edk2-x86_64-code.fd>
tools/test_bob64_qemu.ps1 -QemuPath <qemu-system-x86_64.exe> -OvmfCodePath <edk2-x86_64-code.fd> -OvmfVarsPath <edk2-x86_64-vars.fd>
```
The safe output goes to `build/bob64/EFI/BOOT/BOOTX64.EFI`; the opt-in handoff
@@ -388,8 +545,8 @@ The fallback kernel privilege stack and each app's dedicated 16 KiB interrupt
stack are allocated from the supervisor-only heap. App runs also push a bounded
syscall context that preserves the parent's callbacks, user page table, scratch
buffers, and file handles; each app owns a separately allocated window-server
session. The user-entry return bridge still uses singleton state, so nested app
execution is not enabled yet.
session. The user-entry return bridge keeps a bounded stack of nested return
frames, allowing synchronous child-app execution while preserving the parent.
The volatile
filesystem and B64S checkpoint live in the kernel heap; there is no full
physical direct map or filesystem mapping.
+43 -38
View File
@@ -1,38 +1,43 @@
CC ?= gcc
BOB64_CC ?= x86_64-w64-mingw32-gcc
CFLAGS ?= -std=gnu11 -O2 -Wall -Wextra -Werror
.PHONY: all c-os test bob64 bob64-test bob64-handoff bob64-handoff-test bob64cc bob64-app-test
all:
$(CC) $(CFLAGS) tools/build.c -o build-tool
./build-tool
c-os: all
./bob --boot build/kernel.b16
test: all
./build-tool --test
# x86-64 UEFI build, isolated from the bob16/bob32 emulator targets.
bob64:
$(CC) $(CFLAGS) tools/build.c -o build-tool
BOB64_CC="$(BOB64_CC)" ./build-tool --bob64
bob64-test: bob64
BOB64_CC="$(BOB64_CC)" ./build-tool --bob64-test
# Opt-in destructive-to-firmware-services kernel handoff build.
bob64-handoff:
$(CC) $(CFLAGS) tools/build.c -o build-tool
BOB64_CC="$(BOB64_CC)" ./build-tool --bob64-handoff
bob64-handoff-test:
$(CC) $(CFLAGS) tools/build.c -o build-tool
BOB64_CC="$(BOB64_CC)" ./build-tool --bob64-handoff-test
bob64cc:
$(CC) $(CFLAGS) tools/bob64cc.c -o bob64cc
bob64-app-test: bob64-test bob64cc
BOB64_CC="$(BOB64_CC)" ./bob64cc apps/bob64_smoke.c build/bob64-app/smoke.b64e
./build/test_bob64 build/bob64/EFI/BOOT/BOOTX64.EFI build/bob64-app/smoke.b64e
CC ?= gcc
BOB64_CC ?= x86_64-w64-mingw32-gcc
CFLAGS ?= -std=gnu11 -O2 -Wall -Wextra -Werror
.PHONY: all c-os test bob64 bob64-test bob64-handoff bob64-handoff-test bob64cc bob64-app-test
all:
$(CC) $(CFLAGS) tools/build.c -o build-tool
./build-tool
c-os: all
./bob --boot build/kernel.b16
test: all
./build-tool --test
# x86-64 UEFI build, isolated from the bob16/bob32 emulator targets.
bob64:
$(CC) $(CFLAGS) tools/build.c -o build-tool
BOB64_CC="$(BOB64_CC)" ./build-tool --bob64
bob64-test: bob64
BOB64_CC="$(BOB64_CC)" ./build-tool --bob64-test
# Opt-in destructive-to-firmware-services kernel handoff build.
bob64-handoff:
$(CC) $(CFLAGS) tools/build.c -o build-tool
BOB64_CC="$(BOB64_CC)" ./build-tool --bob64-handoff
bob64-handoff-test:
$(CC) $(CFLAGS) tools/build.c -o build-tool
BOB64_CC="$(BOB64_CC)" ./build-tool --bob64-handoff-test
bob64cc:
$(CC) $(CFLAGS) tools/bob64cc.c -o bob64cc
bob64-app-test: bob64-test bob64cc
BOB64_CC="$(BOB64_CC)" ./bob64cc apps/bob64_smoke.c build/bob64-app/smoke.b64e
BOB64_CC="$(BOB64_CC)" ./bob64cc apps/bob64_nested_smoke.c build/bob64-app/nested-smoke.b64e
BOB64_CC="$(BOB64_CC)" ./bob64cc apps/bob64_echo.c build/bob64-app/echo.b64e
BOB64_CC="$(BOB64_CC)" ./bob64cc apps/bob64_ls.c build/bob64-app/ls.b64e
BOB64_CC="$(BOB64_CC)" ./bob64cc apps/bob64_cat.c build/bob64-app/cat.b64e
BOB64_CC="$(BOB64_CC)" ./bob64cc apps/bob64_notes.c build/bob64-app/notes.b64e
./build/test_bob64 build/bob64/EFI/BOOT/BOOTX64.EFI build/bob64-app/smoke.b64e build/bob64-app/display.b64e build/bob64-app/gui.b64e build/bob64-app/nested-smoke.b64e build/bob64-app/echo.b64e build/bob64-app/ls.b64e build/bob64-app/cat.b64e build/bob64-app/notes.b64e
+48
View File
@@ -0,0 +1,48 @@
#include "../bob64/app.h"
static char file_buffer[BOB64_SYSCALL_MAX_BUFFER];
static usize text_length(const char *text) {
usize length=0;
if(!text)return 0;
while(text[length])length++;
return length;
}
static void write_text(const char *text) {
(void)bob64_app_write(text,text_length(text));
}
s64 bob64_app_main(const BOB64_APP_STARTUP *startup) {
const char *name;
usize name_length;
s64 handle,result=0;
u8 last_character=0;
int read_any=0;
if(!startup||startup->StructSize!=sizeof(*startup)||
startup->AbiVersion!=BOB64_APP_ABI_VERSION)return -1;
if(startup->ArgumentCount!=2||!startup->Arguments||
!(name=startup->Arguments[1])||!(name_length=text_length(name))) {
write_text("usage: cat FILE\n");
return 1;
}
handle=bob64_app_file_open(name,name_length,BOB64_FILE_OPEN_READ);
if(handle<0) {
write_text("cannot read file\n");
return -2;
}
for(;;) {
s64 count=bob64_app_file_read(handle,file_buffer,sizeof(file_buffer));
if(count<0) {result=-3;break;}
if(!count)break;
if(bob64_app_write(file_buffer,(usize)count)!=count) {
result=-4;break;
}
last_character=(u8)file_buffer[(usize)count-1];
read_any=1;
}
if(bob64_app_file_close(handle)&&!result)result=-5;
if(!result&&read_any&&last_character!='\n'&&
bob64_app_write_char('\n')<0)result=-6;
return result;
}
+97 -3
View File
@@ -1,4 +1,98 @@
int main(void) {
bob64_app_write("bob!", 4);
return 0;
typedef int count_t;
typedef char byte_t;
typedef int *int_ptr;
int sum_values(int values[], int count) {
count_t sum = 0;
for (int i = 0; i < count; i = i + 1)
sum = sum + values[i];
return sum;
}
count_t text_length(byte_t text[]) {
count_t length = 0;
while (text[length] != '\0')
length = length + 1;
return length;
}
int_ptr first_value(int_ptr values) {
return values;
}
usize wide_division(usize value) {
return value / 10 + value % 10;
}
int sum_sixteen(int a, int b, int c, int d, int e, int f, int g, int h,
int i, int j, int k, int l, int m, int n, int o, int p) {
return a + b + c + d + e + f + g + h + i + j + k + l + m + n + o + p;
}
int stack_argument_test(void) {
return sum_sixteen(1, 2, 3, 4, 5, 6, 7, 8,
9, 10, 11, 12, 13, 14, 15, 16);
}
int main(void) {
count_t values[64];
byte_t message[5] = "bob!";
int_ptr value_pointer = first_value(values);
int v0 = 0;
int v1 = 1;
int v2 = 2;
int v3 = 3;
int v4 = 4;
int v5 = 5;
int v6 = 6;
int v7 = 7;
int v8 = 8;
int v9 = 9;
int v10 = 10;
int v11 = 11;
int v12 = 12;
int v13 = 13;
int v14 = 14;
int v15 = 15;
int v16 = 16;
int v17 = 17;
int v18 = 18;
int v19 = 19;
int v20 = 20;
int v21 = 21;
int v22 = 22;
int v23 = 23;
int v24 = 24;
int v25 = 25;
int v26 = 26;
int v27 = 27;
int v28 = 28;
int v29 = 29;
int v30 = 30;
int v31 = 31;
int v32 = 32;
int v33 = 33;
int v34 = 34;
int v35 = 35;
int v36 = 36;
int v37 = 37;
int v38 = 38;
int v39 = 39;
values[0] = 12;
values[1] = 13;
values[2] = 17;
values[63] = 42;
if (sum_values(values, 3) == 42 && text_length(message) == 4 &&
stack_argument_test() == 136 && values[63] == 42 &&
value_pointer[63] == 42 && v0 + v39 == 39 &&
20 / 3 == 6 && 20 % 3 == 2 &&
-20 / 3 == -6 && -20 % 3 == -2 &&
wide_division(0x100000001ULL) == 429496736 &&
(0x100000001ULL >> 32) == 1 &&
((0x5a ^ 0x3c) & 0xff) == 0x66 &&
(1 | 2 ^ 3 & 1) == 3 && (-8 >> 2) == -2) {
bob64_app_write(message, text_length(message));
return 0;
}
return 1;
}
+64 -17
View File
@@ -1,28 +1,75 @@
#include "../bob64/app.h"
#include "../bob64/gfx.h"
#define DISPLAY_LIMIT_WIDTH 1024u
#define DISPLAY_LIMIT_HEIGHT 768u
#define DEMO_WIDTH 640u
#define DEMO_HEIGHT 400u
static u32 pixels[DISPLAY_LIMIT_WIDTH*DISPLAY_LIMIT_HEIGHT];
static u32 pixels[DEMO_WIDTH*DEMO_HEIGHT];
static void draw_demo(BOB64_GFX *graphics) {
u32 width=graphics->Width,height=graphics->Height;
s32 margin=(s32)(width/40u);
s32 header_height=(s32)(height/7u);
s32 panel_y=(s32)(height/3u);
u32 panel_width=(width-(u32)(margin*5))/4u;
u32 panel_height=height/4u;
bob64_gfx_fill_rect(graphics,0,0,width,height,0x101a2au);
bob64_gfx_fill_rect(graphics,margin,margin,width-(u32)(margin*2),
height-(u32)(margin*2),0x1b2b40u);
bob64_gfx_fill_rect(graphics,margin,margin,width-(u32)(margin*2),
(u32)header_height,0x345d89u);
bob64_gfx_text(graphics,margin*2,margin*2,"BOB32 GRAPHICS DEMO",
0x00ffffffu,3);
bob64_gfx_line(graphics,margin,header_height+margin*2,
(s32)width-margin,header_height+margin*2,0x00f0c879u);
bob64_gfx_text(graphics,margin*2,panel_y-margin*2,
"LINES RECTANGLES AND COLORS",0x00d7e5f5u,2);
const u32 colors[]={0x00e85d75u,0x00edaa42u,0x004fc3a1u,0x005e8ee8u};
for(u32 i=0;i<4;i++) {
s32 x=margin+(s32)(i*(panel_width+(u32)margin));
s32 y=panel_y;
bob64_gfx_fill_rect(graphics,x,y,panel_width,panel_height,colors[i]);
bob64_gfx_fill_rect(graphics,x+8,y+8,panel_width-16,
panel_height-16,0x00223248u);
bob64_gfx_line(graphics,x+14,y+panel_height-18,
x+(s32)panel_width-14,y+18,colors[i]);
bob64_gfx_line(graphics,x+14,y+18,
x+(s32)panel_width-14,y+panel_height-18,colors[i]);
}
bob64_gfx_fill_rect(graphics,margin,panel_y+(s32)panel_height+margin,
width-(u32)(margin*2),3,0x006d849fu);
bob64_gfx_text(graphics,margin*2,
(s32)height-margin*6,"PRESS X OR ESCAPE TO RETURN",0x00ffffffu,2);
}
s64 bob64_app_main(const BOB64_APP_STARTUP *startup) {
u32 width,height;
BOB64_GFX graphics;
BOB64_EVENT event;
u32 screen_width,screen_height;
u64 window=0;
s64 result=-1;
if(!startup||startup->AbiVersion!=BOB64_APP_ABI_VERSION||
bob64_app_query_abi()!=BOB64_SYSCALL_ABI_VERSION||
bob64_app_get_display(&width,&height))return -1;
if(!width||!height||width>DISPLAY_LIMIT_WIDTH||height>DISPLAY_LIMIT_HEIGHT)
return -2;
for(u32 y=0;y<height;y++)for(u32 x=0;x<width;x++) {
u32 red=(x*180u)/width;
u32 green=(y*120u)/height;
pixels[(usize)y*width+x]=(red<<16)|(green<<8)|32u;
}
if(bob64_app_present(pixels,width,height)!=(s64)((u64)width*height))return -3;
if(bob64_app_write("bob!",4)!=4)return -4;
bob64_app_get_display(&screen_width,&screen_height)||
screen_width<DEMO_WIDTH||screen_height<DEMO_HEIGHT)return -1;
graphics.Pixels=pixels;graphics.Width=DEMO_WIDTH;graphics.Height=DEMO_HEIGHT;
graphics.Capacity=DEMO_WIDTH*DEMO_HEIGHT;
draw_demo(&graphics);
window=bob64_app_window_create((s32)((screen_width-DEMO_WIDTH)/2u),
(s32)((screen_height-DEMO_HEIGHT)/2u),DEMO_WIDTH,DEMO_HEIGHT);
if(!window||(s64)window<0)return -2;
if(bob64_app_window_focus(window)) {result=-3;goto cleanup;}
result=bob64_app_window_present(window,pixels,DEMO_WIDTH,DEMO_HEIGHT);
if(result!=(s64)(DEMO_WIDTH*DEMO_HEIGHT))goto cleanup;
if(bob64_app_write("bob!",4)!=4) {result=-4;goto cleanup;}
for(;;) {
if(bob64_app_wait_event(&event))return -5;
if(event.Type==BOB64_EVENT_KEY_DOWN&&event.Character==0x1b)break;
if(bob64_app_wait_event(&event)) {result=-5;break;}
if(event.Type==BOB64_EVENT_KEY_DOWN&&
(event.Character=='x'||event.Character=='X'||event.Character==0x1b)) {
result=0;break;
}
}
return 0;
cleanup:
if(bob64_app_window_destroy(window)&&result==0)result=-6;
return result;
}
+21
View File
@@ -0,0 +1,21 @@
#include "../bob64/app.h"
static usize text_length(const char *text) {
usize length=0;
if(!text)return 0;
while(text[length])length++;
return length;
}
s64 bob64_app_main(const BOB64_APP_STARTUP *startup) {
if(!startup||startup->StructSize!=sizeof(*startup)||
startup->AbiVersion!=BOB64_APP_ABI_VERSION||
(startup->ArgumentCount&&!startup->Arguments))return -1;
for(u64 i=1;i<startup->ArgumentCount;i++) {
const char *argument=startup->Arguments[i];
if(i>1&&bob64_app_write_char(' ')<0)return -2;
if(!argument||bob64_app_write(argument,text_length(argument))<0)return -3;
}
if(bob64_app_write_char('\n')<0)return -4;
return 0;
}
+572 -50
View File
@@ -1,13 +1,17 @@
#include "../bob64/app.h"
#include "../bob64/editor.h"
#include "../bob64/gfx.h"
#include "../bob64/widgets.h"
#include "../bob64/window.h"
#define BOB64_GUI_MAX_WIDTH 1280u
#define BOB64_GUI_MAX_HEIGHT 800u
#define BOB64_GUI_MAX_WINDOWS 4u
#define BOB64_GUI_FILENAME_CAPACITY 64u
#define BOB64_GUI_SURFACE_PIXEL_CAPACITY 1048576u
#define BOB64_GUI_PREVIEW_CAPACITY 384u
#define BOB64_GUI_PREVIEW_COLUMNS 64u
#define BOB64_GUI_PREVIEW_ROWS 8u
#define BOB64_GUI_SURFACE_PIXEL_CAPACITY 1114112u
static u32 pixels[BOB64_GUI_SURFACE_PIXEL_CAPACITY];
static BOB64_GFX graphics[BOB64_GUI_MAX_WINDOWS];
@@ -17,17 +21,47 @@ static BOB64_WINDOW windows[BOB64_GUI_MAX_WINDOWS];
static BOB64_WINDOW_HANDLE order[BOB64_GUI_MAX_WINDOWS];
static char titles[BOB64_GUI_MAX_WINDOWS][16]={"Files","Editor","Window 3","Window 4"};
static char filename[BOB64_GUI_FILENAME_CAPACITY];
static char file_preview[BOB64_GUI_PREVIEW_CAPACITY];
static char file_preview_status[28];
static usize file_preview_length;
static int file_preview_truncated;
static char editor_status[32];
static char gui_file_buffer[BOB64_EDITOR_CAPACITY+1];
static const char applications_title[]="Applications";
static const char delete_title[]="Delete file?";
static const char help_title[]="Desktop help";
static BOB64_EDITOR editor;
static BOB64_WINDOW_HANDLE editor_window;
static BOB64_WINDOW_HANDLE files_window;
static BOB64_WINDOW_HANDLE applications_window;
static BOB64_WINDOW_HANDLE delete_window;
static BOB64_WINDOW_HANDLE help_window;
static u32 screen_width,screen_height;
static BOB64_FILE_INFO file_entries[BOB64_SYSCALL_MAX_FILES];
static const BOB64_RECT file_run_button={8,38,68,16};
static const BOB64_RECT file_apps_button={82,38,64,16};
static const BOB64_RECT file_delete_button={152,38,76,16};
static const BOB64_RECT file_help_button={234,38,64,16};
static const BOB64_RECT delete_yes_button={20,82,88,18};
static const BOB64_RECT delete_cancel_button={120,82,88,18};
static const BOB64_RECT help_close_button={156,132,68,18};
static const BOB64_RECT applications_run_button={8,38,68,16};
static const BOB64_RECT applications_close_button={82,38,64,16};
static BOB64_BUTTON_STATE file_run_state,file_apps_state;
static BOB64_BUTTON_STATE file_delete_state;
static BOB64_BUTTON_STATE file_help_state;
static BOB64_BUTTON_STATE applications_run_state,applications_close_state;
static BOB64_BUTTON_STATE delete_yes_state,delete_cancel_state;
static BOB64_BUTTON_STATE help_close_state;
static BOB64_TEXT_FIELD filename_field;
static u32 file_count,selected_file,file_scroll;
static u32 selected_application,application_scroll;
static int editor_save_allowed;
static int editor_exit_armed;
static int editor_open_armed;
static int file_delete_armed;
static char delete_filename[BOB64_GUI_FILENAME_CAPACITY];
static void gui_refresh_files(void);
static usize gui_length(const char *text,usize limit) {
usize length=0;
@@ -41,6 +75,12 @@ static void gui_copy(char *destination,const char *source,usize length) {
destination[length]=0;
}
static BOB64_RECT gui_filename_rect(void) {
BOB64_WINDOW *window=bob64_wm_find(&manager,editor_window);
BOB64_RECT rect={40,28,window&&window->Width>48?window->Width-48:12,16};
return rect;
}
static BOB64_GFX *gui_graphics_for_handle(BOB64_WINDOW_HANDLE handle) {
for(u32 i=0;i<BOB64_GUI_MAX_WINDOWS;i++)
if(windows[i].Handle==handle)return &graphics[i];
@@ -114,6 +154,8 @@ static int gui_destroy_window(BOB64_WINDOW_HANDLE handle) {
if(bob64_app_window_destroy(handle))return -1;
if(bob64_wm_destroy(&manager,handle))return -1;
gui_surface_release(slot);
if(handle==applications_window)applications_window=0;
if(handle==help_window)help_window=0;
return 0;
}
@@ -122,6 +164,138 @@ static void gui_focus_window(BOB64_WINDOW_HANDLE handle) {
gui_copy(editor_status,"FOCUS FAILED",sizeof("FOCUS FAILED"));
}
static int gui_is_application(const char *name) {
usize length=gui_length(name,BOB64_GUI_FILENAME_CAPACITY);
return length>5&&name[length-5]=='.'&&name[length-4]=='b'&&
name[length-3]=='6'&&name[length-2]=='4'&&name[length-1]=='e';
}
static int gui_filename_valid(void) {
if(!filename_field.Length||filename_field.Length>=BOB64_GUI_FILENAME_CAPACITY||
gui_is_application(filename))return 0;
for(usize i=0;i<filename_field.Length;i++) {
char value=filename[i];
if(!((value>='a'&&value<='z')||(value>='A'&&value<='Z')||
(value>='0'&&value<='9')||value=='.'||value=='_'||value=='-'))return 0;
}
return 1;
}
static u32 gui_application_count(void) {
u32 count=0;
for(u32 i=0;i<file_count;i++)if(gui_is_application(file_entries[i].Name))count++;
return count;
}
static int gui_application_file(u32 application,u32 *file_index) {
u32 found=0;
if(!file_index)return -1;
for(u32 i=0;i<file_count;i++)if(gui_is_application(file_entries[i].Name)) {
if(found++==application){*file_index=i;return 0;}
}
return -1;
}
static void gui_open_applications(void) {
if(applications_window&&bob64_wm_find(&manager,applications_window)) {
gui_focus_window(applications_window);return;
}
if(manager.Count>=BOB64_GUI_MAX_WINDOWS) {
gui_copy(editor_status,"NO WINDOW SPACE",sizeof("NO WINDOW SPACE"));return;
}
applications_window=gui_create_window((s32)(screen_width-316),32,300,260,
applications_title);
if(!applications_window) {
gui_copy(editor_status,"LAUNCHER OPEN FAILED",
sizeof("LAUNCHER OPEN FAILED"));return;
}
selected_application=0;application_scroll=0;
gui_refresh_files();
}
static void gui_open_help(void) {
if(help_window&&bob64_wm_find(&manager,help_window)) {
gui_focus_window(help_window);return;
}
if(manager.Count>=BOB64_GUI_MAX_WINDOWS) {
gui_copy(editor_status,"NO WINDOW SPACE",sizeof("NO WINDOW SPACE"));return;
}
help_window=gui_create_window((s32)(screen_width/2)-120,
(s32)(screen_height/2)-82,240,164,help_title);
if(!help_window) {
gui_copy(editor_status,"HELP WINDOW FAILED",
sizeof("HELP WINDOW FAILED"));return;
}
gui_focus_window(help_window);
}
static void gui_reveal_selected_application(void) {
BOB64_WINDOW *window=bob64_wm_find(&manager,applications_window);
u32 rows=window&&window->Height>84?(window->Height-84)/14:1;
if(!rows)rows=1;
if(selected_application<application_scroll)
application_scroll=selected_application;
else if(selected_application>=application_scroll+rows)
application_scroll=selected_application-rows+1;
}
static void gui_refresh_file_preview(void) {
s64 result;
file_preview_length=0;file_preview_truncated=0;
if(selected_file>=file_count) {
gui_copy(file_preview_status,"SELECT A FILE",
sizeof("SELECT A FILE"));return;
}
if(gui_is_application(file_entries[selected_file].Name)) {
gui_copy(file_preview_status,"APP - PRESS A TO RUN",
sizeof("APP - PRESS A TO RUN"));return;
}
result=bob64_app_file_read_all(file_entries[selected_file].Name,
gui_length(file_entries[selected_file].Name,
BOB64_GUI_FILENAME_CAPACITY),file_preview,
sizeof(file_preview));
if(result==-28) {
file_preview_length=sizeof(file_preview);file_preview_truncated=1;
} else if(result<0) {
gui_copy(file_preview_status,"PREVIEW UNAVAILABLE",
sizeof("PREVIEW UNAVAILABLE"));return;
} else file_preview_length=(usize)result;
if(bob64_editor_is_binary_text(file_preview,file_preview_length)) {
file_preview_length=0;
gui_copy(file_preview_status,"BINARY FILE",
sizeof("BINARY FILE"));return;
}
gui_copy(file_preview_status,file_preview_length?"TEXT FILE":"EMPTY FILE",
file_preview_length?sizeof("TEXT FILE"):sizeof("EMPTY FILE"));
}
static void gui_draw_file_preview(BOB64_GFX *graphics,
const BOB64_WINDOW *window) {
usize position=0;
s32 y=window->Y+(s32)window->Height-124;
if(!file_preview_length) {
bob64_gfx_text(graphics,window->X+10,y,file_preview_status,
0x009eb3c7u,1);return;
}
for(u32 row=0;row<BOB64_GUI_PREVIEW_ROWS&&position<file_preview_length;
row++) {
char line[BOB64_GUI_PREVIEW_COLUMNS+1];
u32 column=0;
while(position<file_preview_length&&column<BOB64_GUI_PREVIEW_COLUMNS) {
char value=file_preview[position++];
if(value=='\n')break;
if(value=='\r')continue;
line[column++]=value=='\t'?' ':value;
}
line[column]=0;
bob64_gfx_text(graphics,window->X+10,y+(s32)(row*10),line,
0x00dbe8f4u,1);
}
if(file_preview_truncated||position<file_preview_length)
bob64_gfx_text(graphics,window->X+10,
window->Y+(s32)window->Height-34,"...",0x009eb3c7u,1);
}
static int gui_load_file(const BOB64_APP_STARTUP *startup) {
const char *requested="notes.txt";
usize length=sizeof("notes.txt")-1;
@@ -137,7 +311,15 @@ static int gui_load_file(const BOB64_APP_STARTUP *startup) {
(value>='0'&&value<='9')||value=='.'||value=='_'||value=='-'))return -1;
}
gui_copy(filename,requested,length);
result=bob64_app_read_file(filename,length,editor.Text,BOB64_EDITOR_CAPACITY);
if(bob64_text_field_init(&filename_field,filename,sizeof(filename)))return -1;
if(gui_is_application(filename)) {
bob64_editor_init(&editor,0,0);
gui_copy(editor_status,"USE RUN APP",sizeof("USE RUN APP"));
editor_save_allowed=0;
return 0;
}
result=bob64_app_file_read_all(filename,length,gui_file_buffer,
BOB64_EDITOR_CAPACITY);
if(result==-2) {
bob64_editor_init(&editor,0,0);
gui_copy(editor_status,"NEW FILE",sizeof("NEW FILE"));
@@ -149,9 +331,15 @@ static int gui_load_file(const BOB64_APP_STARTUP *startup) {
} else if(result<0) {
return -1;
} else {
bob64_editor_init(&editor,editor.Text,(u32)result);
gui_copy(editor_status,"LOADED",sizeof("LOADED"));
editor_save_allowed=1;
if(bob64_editor_is_binary_text(gui_file_buffer,(usize)result)) {
bob64_editor_init(&editor,0,0);
gui_copy(editor_status,"BINARY FILE",sizeof("BINARY FILE"));
editor_save_allowed=0;
} else {
bob64_editor_init(&editor,gui_file_buffer,(u32)result);
gui_copy(editor_status,"LOADED",sizeof("LOADED"));
editor_save_allowed=1;
}
}
return 0;
}
@@ -162,21 +350,37 @@ static void gui_refresh_files(void) {
file_count=0;
gui_copy(editor_status,result==-28?"TOO MANY FILES":"LIST FAILED",
result==-28?sizeof("TOO MANY FILES"):sizeof("LIST FAILED"));
gui_refresh_file_preview();
return;
}
file_count=(u32)result;
if(selected_file>=file_count)selected_file=file_count?file_count-1:0;
if(file_scroll>=file_count)file_scroll=file_count?file_count-1:0;
gui_refresh_file_preview();
}
static void gui_reveal_selected_file(void) {
BOB64_WINDOW *window=bob64_wm_find(&manager,files_window);
u32 rows=window&&window->Height>58?(window->Height-58)/14:1;
u32 rows=window&&window->Height>70?(window->Height-70)/14:1;
if(!rows)rows=1;
if(selected_file<file_scroll)file_scroll=selected_file;
else if(selected_file>=file_scroll+rows)file_scroll=selected_file-rows+1;
}
static void gui_scroll_file_selection(s32 wheel) {
if(wheel>0&&selected_file)selected_file--;
else if(wheel<0&&selected_file+1<file_count)selected_file++;
gui_reveal_selected_file();
gui_refresh_file_preview();
}
static void gui_scroll_application_selection(s32 wheel) {
if(wheel>0&&selected_application)selected_application--;
else if(wheel<0&&selected_application+1<gui_application_count())
selected_application++;
gui_reveal_selected_application();
}
static int gui_name_equal(const char *left,const char *right) {
while(*left&&*right&&*left==*right){left++;right++;}
return !*left&&!*right;
@@ -188,7 +392,11 @@ static void gui_open_selected_file(void) {
gui_copy(editor_status,"NO FILE SELECTED",sizeof("NO FILE SELECTED"));return;
}
const char *name=file_entries[selected_file].Name;
if(editor.Dirty&&!editor_open_armed) {
if(gui_is_application(name)) {
gui_copy(editor_status,"USE RUN APP",sizeof("USE RUN APP"));
editor_open_armed=0;return;
}
if((editor.Dirty||filename_field.Dirty)&&!editor_open_armed) {
gui_copy(editor_status,"OPEN AGAIN TO DISCARD",sizeof("OPEN AGAIN TO DISCARD"));
editor_open_armed=1;return;
}
@@ -197,43 +405,122 @@ static void gui_open_selected_file(void) {
gui_copy(editor_status,"CURRENT FILE",sizeof("CURRENT FILE"));
editor_open_armed=0;return;
}
result=bob64_app_read_file(name,gui_length(name,BOB64_GUI_FILENAME_CAPACITY),
editor.Text,BOB64_EDITOR_CAPACITY);
result=bob64_app_file_read_all(name,
gui_length(name,BOB64_GUI_FILENAME_CAPACITY),gui_file_buffer,
BOB64_EDITOR_CAPACITY);
if(result==-28) {
gui_copy(editor_status,"FILE TOO LARGE",sizeof("FILE TOO LARGE"));
editor_save_allowed=0;return;
editor_open_armed=0;return;
}
if(result<0) {
gui_copy(editor_status,"OPEN FAILED",sizeof("OPEN FAILED"));return;
}
if(bob64_editor_is_binary_text(gui_file_buffer,(usize)result)) {
gui_copy(editor_status,"BINARY FILE",sizeof("BINARY FILE"));
editor_open_armed=0;return;
}
gui_copy(filename,name,gui_length(name,BOB64_GUI_FILENAME_CAPACITY));
bob64_editor_init(&editor,editor.Text,(u32)result);
bob64_text_field_sync(&filename_field);
bob64_editor_init(&editor,gui_file_buffer,(u32)result);
editor_save_allowed=1;editor_open_armed=0;
gui_copy(editor_status,"LOADED",sizeof("LOADED"));
gui_focus_window(editor_window);
}
static void gui_delete_selected_file(void) {
const char *name;
s64 result;
BOB64_WINDOW_HANDLE handle;
if(selected_file>=file_count) {
gui_copy(editor_status,"NO FILE SELECTED",sizeof("NO FILE SELECTED"));return;
}
name=file_entries[selected_file].Name;
if(gui_name_equal(name,filename)) {
file_delete_armed=0;
if(gui_name_equal(file_entries[selected_file].Name,filename)) {
gui_copy(editor_status,"SAVE OR OPEN OTHER FILE",sizeof("SAVE OR OPEN OTHER FILE"));
return;
}
if(!file_delete_armed) {
file_delete_armed=1;
gui_copy(editor_status,"D AGAIN TO DELETE",sizeof("D AGAIN TO DELETE"));
if(delete_window&&bob64_wm_find(&manager,delete_window)) {
gui_focus_window(delete_window);return;
}
gui_copy(delete_filename,file_entries[selected_file].Name,
gui_length(file_entries[selected_file].Name,
BOB64_GUI_FILENAME_CAPACITY));
handle=gui_create_window((s32)(screen_width/2)-120,
(s32)(screen_height/2)-60,240,124,delete_title);
if(!handle) {
delete_filename[0]=0;
gui_copy(editor_status,"DELETE DIALOG FAILED",
sizeof("DELETE DIALOG FAILED"));return;
}
delete_window=handle;
gui_focus_window(delete_window);
}
static void gui_finish_delete(int confirm) {
if(!delete_window)return;
if(confirm) {
s64 result=bob64_app_delete_file(delete_filename,
gui_length(delete_filename,BOB64_GUI_FILENAME_CAPACITY));
if(result)gui_copy(editor_status,"DELETE FAILED",sizeof("DELETE FAILED"));
else {gui_refresh_files();gui_copy(editor_status,"DELETED",sizeof("DELETED"));}
} else gui_copy(editor_status,"DELETE CANCELLED",sizeof("DELETE CANCELLED"));
gui_destroy_window(delete_window);
delete_window=0;delete_filename[0]=0;
delete_yes_state.Pressed=delete_cancel_state.Pressed=0;
}
static void gui_set_app_exit_status(s64 status) {
char digits[20];
u64 magnitude;
usize length=0,offset=0;
if(status<0) {
gui_copy(editor_status,"APP EXIT -",10);offset=10;
magnitude=(u64)(-(status+1))+1;
} else {
gui_copy(editor_status,"APP EXIT ",9);offset=9;
magnitude=(u64)status;
}
do {digits[length++]=(char)('0'+magnitude%10);magnitude/=10;}
while(magnitude&&length<sizeof(digits));
while(length)editor_status[offset++]=digits[--length];
editor_status[offset]=0;
}
static void gui_run_application_file(u32 file_index) {
const char *name;
usize length;
s64 exit_status=-1;
s64 result;
if(file_index>=file_count) {
gui_copy(editor_status,"NO FILE SELECTED",sizeof("NO FILE SELECTED"));return;
}
name=file_entries[file_index].Name;
length=gui_length(name,BOB64_GUI_FILENAME_CAPACITY);
if(length>=BOB64_GUI_FILENAME_CAPACITY||!gui_is_application(name)) {
gui_copy(editor_status,"SELECT A .B64E APP",sizeof("SELECT A .B64E APP"));
return;
}
result=bob64_app_delete_file(name,gui_length(name,BOB64_GUI_FILENAME_CAPACITY));
file_delete_armed=0;
if(result)gui_copy(editor_status,"DELETE FAILED",sizeof("DELETE FAILED"));
else {gui_refresh_files();gui_copy(editor_status,"DELETED",sizeof("DELETED"));}
const char *arguments[1]={name};
result=bob64_app_run(name,length,1,arguments,&exit_status);
if(result) {
gui_copy(editor_status,"APP LAUNCH FAILED",sizeof("APP LAUNCH FAILED"));
return;
}
gui_refresh_files();
u32 application_count=gui_application_count();
if(selected_application>=application_count)
selected_application=application_count?application_count-1:0;
gui_reveal_selected_application();
gui_set_app_exit_status(exit_status);
}
static void gui_run_selected_app(void) {
gui_run_application_file(selected_file);
}
static void gui_run_selected_application(void) {
u32 file_index;
if(gui_application_file(selected_application,&file_index)) {
gui_copy(editor_status,"NO APP SELECTED",sizeof("NO APP SELECTED"));return;
}
gui_run_application_file(file_index);
}
static void gui_draw_window(const BOB64_WINDOW *window,int focused) {
@@ -275,8 +562,10 @@ static void gui_draw_window(const BOB64_WINDOW *window,int focused) {
if(cursor_row<editor.ScrollRow)editor.ScrollRow=cursor_row;
else if(rows&&cursor_row>=editor.ScrollRow+rows)
editor.ScrollRow=cursor_row-rows+1;
bob64_gfx_text(graphics,window->X+12,window->Y+30,filename,
BOB64_RECT filename_rect={40,28,window->Width-48,16};
bob64_gfx_text(graphics,window->X+8,window->Y+32,"NAME",
0x009eb3c7u,1);
bob64_text_field_draw(graphics,&filename_rect,&filename_field);
for(u32 i=0;i<=editor.Length;i++) {
if(column>=columns&&(i==editor.Length||editor.Text[i]!='\n')) {
row++;column=0;
@@ -316,16 +605,25 @@ static void gui_draw_window(const BOB64_WINDOW *window,int focused) {
bob64_gfx_text(graphics,window->X+(s32)window->Width/2,
window->Y+(s32)window->Height-16,"CTRL S SAVE",0x009eb3c7u,1);
} else if(window->Handle==files_window) {
u32 rows=window->Height>58?(window->Height-58)/14:0;
u32 list_bottom=window->Height>156?window->Height-156:70;
u32 rows=list_bottom>70?(list_bottom-70)/14:0;
bob64_gfx_text(graphics,window->X+10,window->Y+31,
"UP DOWN OPEN R REFRESH",0x009eb3c7u,1);
bob64_gfx_text(graphics,window->X+10,window->Y+41,
"D TWICE DELETE",0x009eb3c7u,1);
bob64_gfx_text(graphics,window->X+10,window->Y+49,editor_status,
"UP DOWN / WHEEL MOVE",0x009eb3c7u,1);
bob64_button_draw(graphics,&file_run_button,"RUN APP",&file_run_state);
bob64_button_draw(graphics,&file_apps_button,"APPS",&file_apps_state);
bob64_button_draw(graphics,&file_delete_button,"DELETE",&file_delete_state);
bob64_button_draw(graphics,&file_help_button,"HELP",&file_help_state);
bob64_gfx_text(graphics,window->X+10,window->Y+52,
"O OPEN R REFRESH D DELETE",0x009eb3c7u,1);
bob64_gfx_text(graphics,window->X+10,window->Y+61,editor_status,
0x008fc8ffu,1);
bob64_gfx_text(graphics,window->X+10,
window->Y+(s32)window->Height-144,"PREVIEW (ON DISK)",
0x009eb3c7u,1);
gui_draw_file_preview(graphics,window);
for(u32 row=0;row<rows&&file_scroll+row<file_count;row++) {
u32 index=file_scroll+row;
s32 y=window->Y+56+(s32)(row*14);
s32 y=window->Y+70+(s32)(row*14);
if(index==selected_file)
bob64_gfx_fill_rect(graphics,window->X+6,y-2,
window->Width-12,12,0x00335d8cu);
@@ -333,8 +631,54 @@ static void gui_draw_window(const BOB64_WINDOW *window,int focused) {
file_entries[index].Name,index==selected_file?
0x00ffffffu:0x00dbe8f4u,1);
}
if(!file_count)bob64_gfx_text(graphics,window->X+10,window->Y+60,
if(!file_count)bob64_gfx_text(graphics,window->X+10,window->Y+72,
"NO FILES",0x008fc8ffu,1);
} else if(window->Handle==delete_window) {
bob64_gfx_text(graphics,window->X+16,window->Y+40,
"DELETE THIS FILE?",0x00ffffffu,1);
bob64_gfx_text(graphics,window->X+16,window->Y+58,
delete_filename,0x009eb3c7u,1);
bob64_button_draw(graphics,&delete_yes_button,"YES, DELETE",
&delete_yes_state);
bob64_button_draw(graphics,&delete_cancel_button,"CANCEL",
&delete_cancel_state);
} else if(window->Handle==help_window) {
bob64_gfx_text(graphics,window->X+12,window->Y+38,
"FILES: ARROWS/WHEEL SELECT",0x00e2ebf5u,1);
bob64_gfx_text(graphics,window->X+12,window->Y+54,
"O OPENS; A RUNS AN APP",0x00e2ebf5u,1);
bob64_gfx_text(graphics,window->X+12,window->Y+70,
"D OR DELETE ASKS FIRST",0x00e2ebf5u,1);
bob64_gfx_text(graphics,window->X+12,window->Y+86,
"P OPENS THE APP LAUNCHER",0x00e2ebf5u,1);
bob64_gfx_text(graphics,window->X+12,window->Y+102,
"CTRL S SAVES; TAB SWITCHES",0x00e2ebf5u,1);
bob64_button_draw(graphics,&help_close_button,"CLOSE",
&help_close_state);
} else if(window->Handle==applications_window) {
u32 rows=window->Height>80?(window->Height-80)/14:0;
bob64_gfx_text(graphics,window->X+10,window->Y+31,
"UP DOWN WHEEL ENTER RUN",0x009eb3c7u,1);
bob64_button_draw(graphics,&applications_run_button,"RUN APP",
&applications_run_state);
bob64_button_draw(graphics,&applications_close_button,"X CLOSE",
&applications_close_state);
bob64_gfx_text(graphics,window->X+10,window->Y+58,editor_status,
0x008fc8ffu,1);
for(u32 row=0;row<rows;row++) {
u32 app_index=application_scroll+row,file_index;
if(app_index>=gui_application_count())break;
if(gui_application_file(app_index,&file_index))break;
s32 y=window->Y+76+(s32)(row*14);
if(app_index==selected_application)
bob64_gfx_fill_rect(graphics,window->X+6,y-2,
window->Width-12,12,0x00335d8cu);
bob64_gfx_text(graphics,window->X+10,y,
file_entries[file_index].Name,app_index==selected_application?
0x00ffffffu:0x00dbe8f4u,1);
}
if(!gui_application_count())bob64_gfx_text(graphics,window->X+10,
window->Y+80,"NO APPS",0x008fc8ffu,1);
} else if(window->Handle==manager.Focused) {
bob64_gfx_text(graphics,window->X+14,window->Y+46,
"BOB64 DESKTOP",0x007ed6ffu,1);
@@ -381,15 +725,50 @@ static int gui_draw(s32 cursor_x,s32 cursor_y) {
return 0;
}
static void gui_update_button_hover(BOB64_WINDOW_HANDLE handle,s32 screen_x,
s32 screen_y) {
BOB64_WINDOW *window=bob64_wm_find(&manager,handle);
BOB64_EVENT event={0};
if(!window)return;
event.Type=BOB64_EVENT_MOUSE_MOVE;
event.X=screen_x-window->X;event.Y=screen_y-window->Y;
if(handle==files_window) {
bob64_button_event(&file_run_button,&file_run_state,&event);
bob64_button_event(&file_apps_button,&file_apps_state,&event);
bob64_button_event(&file_delete_button,&file_delete_state,&event);
bob64_button_event(&file_help_button,&file_help_state,&event);
} else if(handle==applications_window) {
bob64_button_event(&applications_run_button,&applications_run_state,&event);
bob64_button_event(&applications_close_button,&applications_close_state,&event);
} else if(handle==delete_window) {
bob64_button_event(&delete_yes_button,&delete_yes_state,&event);
bob64_button_event(&delete_cancel_button,&delete_cancel_state,&event);
} else if(handle==help_window) {
bob64_button_event(&help_close_button,&help_close_state,&event);
}
}
static void gui_cancel_button_presses(void) {
file_run_state.Pressed=0;file_apps_state.Pressed=0;
applications_run_state.Pressed=0;applications_close_state.Pressed=0;
file_delete_state.Pressed=0;
file_help_state.Pressed=0;
delete_yes_state.Pressed=delete_cancel_state.Pressed=0;
help_close_state.Pressed=0;
}
static void gui_save_editor(void) {
if(!editor_save_allowed) {
gui_copy(editor_status,"FILE TOO LARGE",sizeof("FILE TOO LARGE"));
if(!editor_save_allowed)return;
if(!gui_filename_valid()) {
gui_copy(editor_status,"INVALID FILE NAME",sizeof("INVALID FILE NAME"));
return;
}
s64 result=bob64_app_write_file(filename,gui_length(filename,
s64 result=bob64_app_file_write_all(filename,gui_length(filename,
BOB64_GUI_FILENAME_CAPACITY),editor.Text,editor.Length);
if(result==(s64)editor.Length) {
editor.Dirty=0;gui_copy(editor_status,"SAVED",sizeof("SAVED"));
editor.Dirty=0;filename_field.Dirty=0;
gui_copy(editor_status,"SAVED",sizeof("SAVED"));
gui_refresh_files();
} else gui_copy(editor_status,"SAVE FAILED",sizeof("SAVE FAILED"));
}
@@ -431,22 +810,66 @@ static void gui_focus_next(void) {
static void gui_key(const BOB64_EVENT *event) {
if(event->Type!=BOB64_EVENT_KEY_DOWN)return;
if(event->Character=='\t')gui_focus_next();
if(manager.Focused==delete_window) {
if(event->Character=='y'||event->Character=='Y'||event->Character=='\n')
gui_finish_delete(1);
else if(event->Character=='n'||event->Character=='N'||
event->Character==0x1b)gui_finish_delete(0);
}
else if(manager.Focused==help_window) {
if(event->Character==0x1b||event->Character=='x'||
event->Character=='X'||event->Character=='h'||
event->Character=='H')gui_destroy_window(help_window);
}
else if(event->Character=='\t') {
if(manager.Focused==editor_window&&filename_field.Focused)
filename_field.Focused=0;
else gui_focus_next();
}
else if(manager.Focused==editor_window&&filename_field.Focused) {
if((event->Modifiers&BOB64_EVENT_MOD_CONTROL)&&
(event->Character=='s'||event->Character=='S'))gui_save_editor();
else if(event->Character=='\n')filename_field.Focused=0;
else {
BOB64_RECT filename_rect=gui_filename_rect();
bob64_text_field_event(&filename_field,&filename_rect,event);
}
}
else if(event->Character=='p'||event->Character=='P')gui_open_applications();
else if(manager.Focused==applications_window) {
if(event->Key==(BOB64_EVENT_KEY_EXTENDED|0x48)) {
if(selected_application)selected_application--;
gui_reveal_selected_application();
} else if(event->Key==(BOB64_EVENT_KEY_EXTENDED|0x50)) {
if(selected_application+1<gui_application_count())selected_application++;
gui_reveal_selected_application();
} else if(event->Character=='\n'||event->Character=='a'||
event->Character=='A')gui_run_selected_application();
else if((event->Character=='x'||event->Character=='X')&&
gui_destroy_window(applications_window))
gui_copy(editor_status,"WINDOW CLOSE FAILED",sizeof("WINDOW CLOSE FAILED"));
}
else if(manager.Focused==files_window) {
if(event->Key==(BOB64_EVENT_KEY_EXTENDED|0x48)) {
if(selected_file)selected_file--;
gui_reveal_selected_file();
file_delete_armed=editor_open_armed=0;
gui_refresh_file_preview();
editor_open_armed=0;
} else if(event->Key==(BOB64_EVENT_KEY_EXTENDED|0x50)) {
if(selected_file+1<file_count)selected_file++;
gui_reveal_selected_file();
file_delete_armed=editor_open_armed=0;
gui_refresh_file_preview();
editor_open_armed=0;
} else if(event->Character=='r'||event->Character=='R') {
gui_refresh_files();file_delete_armed=editor_open_armed=0;
gui_refresh_files();editor_open_armed=0;
} else if(event->Character=='a'||event->Character=='A') {
gui_run_selected_app();editor_open_armed=0;
} else if(event->Character=='o'||event->Character=='O'||
event->Character=='\n')gui_open_selected_file();
else if(event->Character=='d'||event->Character=='D')gui_delete_selected_file();
else file_delete_armed=editor_open_armed=0;
else if(event->Character=='h'||event->Character=='H'||
event->Character=='?')gui_open_help();
else editor_open_armed=0;
}
else if(event->Character=='n'&&manager.Count<BOB64_GUI_MAX_WINDOWS) {
u32 index=manager.Count;
@@ -470,6 +893,8 @@ s64 bob64_app_main(const BOB64_APP_STARTUP *startup) {
BOB64_EVENT event;
BOB64_EVENT routed;
BOB64_EVENT screen_event;
BOB64_EVENT local_event;
s64 event_target;
s32 cursor_x,cursor_y;
if(!startup||startup->AbiVersion!=BOB64_APP_ABI_VERSION||
bob64_app_query_abi()!=BOB64_SYSCALL_ABI_VERSION)return -1;
@@ -490,8 +915,20 @@ s64 bob64_app_main(const BOB64_APP_STARTUP *startup) {
for(;;) {
if(gui_draw(cursor_x,cursor_y))return -4;
if(bob64_app_wait_event(&event))return -5;
if(event.Type==BOB64_EVENT_KEY_DOWN&&event.Character==0x1b&&
manager.Focused==delete_window) {
gui_finish_delete(0);continue;
}
if(event.Type==BOB64_EVENT_KEY_DOWN&&event.Character==0x1b&&
manager.Focused==help_window) {
gui_destroy_window(help_window);continue;
}
if(event.Type==BOB64_EVENT_KEY_DOWN&&event.Character==0x1b&&
manager.Focused==applications_window) {
gui_destroy_window(applications_window);continue;
}
if(event.Type==BOB64_EVENT_KEY_DOWN&&event.Character==0x1b) {
if(editor.Dirty&&!editor_exit_armed) {
if((editor.Dirty||filename_field.Dirty)&&!editor_exit_armed) {
gui_copy(editor_status,"ESC AGAIN TO QUIT",sizeof("ESC AGAIN TO QUIT"));
editor_exit_armed=1;continue;
}
@@ -502,20 +939,105 @@ s64 bob64_app_main(const BOB64_APP_STARTUP *startup) {
event.Type==BOB64_EVENT_MOUSE_WHEEL)
cursor_x=event.ScreenX,cursor_y=event.ScreenY;
screen_event=event;screen_event.X=event.ScreenX;screen_event.Y=event.ScreenY;
bob64_wm_dispatch(&manager,&screen_event,&routed);
if(event.Type==BOB64_EVENT_MOUSE_BUTTON&&(event.Buttons&1u)&&
manager.Focused==files_window&&routed.X>=8&&routed.Y>=56) {
u32 row=(u32)(routed.Y-56)/14;
if(file_scroll+row<file_count)selected_file=file_scroll+row;
event_target=bob64_wm_dispatch(&manager,&screen_event,&routed);
if(manager.Focused!=editor_window)filename_field.Focused=0;
if(event.Type==BOB64_EVENT_MOUSE_MOVE) {
gui_update_button_hover(files_window,event.ScreenX,event.ScreenY);
gui_update_button_hover(applications_window,event.ScreenX,event.ScreenY);
gui_update_button_hover(delete_window,event.ScreenX,event.ScreenY);
gui_update_button_hover(help_window,event.ScreenX,event.ScreenY);
}
if(event.Type==BOB64_EVENT_MOUSE_BUTTON&&(event.Buttons&1u)&&
manager.Focused==editor_window&&routed.X>=12&&routed.Y>=46) {
if(event.Type==BOB64_EVENT_MOUSE_WHEEL) {
if(manager.Focused==files_window&&routed.Y>=70)
gui_scroll_file_selection(event.Wheel);
else if(manager.Focused==applications_window&&routed.Y>=72)
gui_scroll_application_selection(event.Wheel);
}
if(event.Type==BOB64_EVENT_MOUSE_BUTTON&&
event_target==(s64)files_window) {
local_event=event;local_event.X=routed.X;local_event.Y=routed.Y;
int run_clicked=bob64_button_event(&file_run_button,&file_run_state,
&local_event);
int apps_clicked=bob64_button_event(&file_apps_button,&file_apps_state,
&local_event);
int delete_clicked=bob64_button_event(&file_delete_button,
&file_delete_state,&local_event);
int help_clicked=bob64_button_event(&file_help_button,
&file_help_state,&local_event);
if(!(event.Buttons&BOB64_BUTTON_LEFT)&&run_clicked)
gui_run_selected_app();
else if(!(event.Buttons&BOB64_BUTTON_LEFT)&&apps_clicked)
gui_open_applications();
else if(!(event.Buttons&BOB64_BUTTON_LEFT)&&delete_clicked)
gui_delete_selected_file();
else if(!(event.Buttons&BOB64_BUTTON_LEFT)&&help_clicked)
gui_open_help();
else if((event.Buttons&BOB64_BUTTON_LEFT)&&routed.Y>=70&&routed.X>=8) {
u32 row=(u32)(routed.Y-70)/14;
if(file_scroll+row<file_count) {
selected_file=file_scroll+row;
gui_refresh_file_preview();
}
}
}
if(event.Type==BOB64_EVENT_MOUSE_BUTTON&&
event_target==(s64)applications_window) {
local_event=event;local_event.X=routed.X;local_event.Y=routed.Y;
int run_clicked=bob64_button_event(&applications_run_button,
&applications_run_state,&local_event);
int close_clicked=bob64_button_event(&applications_close_button,
&applications_close_state,&local_event);
if(!(event.Buttons&BOB64_BUTTON_LEFT)&&close_clicked)
gui_destroy_window(applications_window);
else if(!(event.Buttons&BOB64_BUTTON_LEFT)&&run_clicked)
gui_run_selected_application();
else if((event.Buttons&BOB64_BUTTON_LEFT)&&routed.Y>=72) {
u32 row=(u32)(routed.Y-72)/14;
u32 app_index=application_scroll+row;
if(app_index<gui_application_count())
selected_application=app_index;
}
}
if(event.Type==BOB64_EVENT_MOUSE_BUTTON&&
event_target==(s64)delete_window) {
local_event=event;local_event.X=routed.X;local_event.Y=routed.Y;
int yes_clicked=bob64_button_event(&delete_yes_button,
&delete_yes_state,&local_event);
int cancel_clicked=bob64_button_event(&delete_cancel_button,
&delete_cancel_state,&local_event);
if(!(event.Buttons&BOB64_BUTTON_LEFT)&&yes_clicked)
gui_finish_delete(1);
else if(!(event.Buttons&BOB64_BUTTON_LEFT)&&cancel_clicked)
gui_finish_delete(0);
}
if(event.Type==BOB64_EVENT_MOUSE_BUTTON&&
event_target==(s64)help_window) {
local_event=event;local_event.X=routed.X;local_event.Y=routed.Y;
if(!(event.Buttons&BOB64_BUTTON_LEFT)&&
bob64_button_event(&help_close_button,&help_close_state,
&local_event))gui_destroy_window(help_window);
}
if(event.Type==BOB64_EVENT_MOUSE_BUTTON&&
!(event.Buttons&BOB64_BUTTON_LEFT)&&
event_target!=(s64)files_window&&
event_target!=(s64)applications_window&&
event_target!=(s64)delete_window&&
event_target!=(s64)help_window)gui_cancel_button_presses();
if(event.Type==BOB64_EVENT_MOUSE_BUTTON&&
event_target==(s64)editor_window) {
local_event=event;local_event.X=routed.X;local_event.Y=routed.Y;
BOB64_RECT filename_rect=gui_filename_rect();
bob64_text_field_event(&filename_field,&filename_rect,&local_event);
}
if(event.Type==BOB64_EVENT_MOUSE_BUTTON&&(event.Buttons&BOB64_BUTTON_LEFT)&&
event_target==(s64)editor_window&&routed.X>=12&&routed.Y>=46) {
BOB64_WINDOW *window=bob64_wm_find(&manager,editor_window);
if(window)gui_editor_place_cursor((u32)(routed.Y-46)/10,
(u32)(routed.X-12)/6,(window->Width-24)/6);
}
gui_key(&event);
if(editor.Dirty)gui_copy(editor_status,"UNSAVED",sizeof("UNSAVED"));
if(editor.Dirty||filename_field.Dirty)
gui_copy(editor_status,"UNSAVED",sizeof("UNSAVED"));
}
return 0;
}
+51
View File
@@ -0,0 +1,51 @@
#include "../bob64/app.h"
static void write_text(const char *text) {
usize length=0;
while(text[length])length++;
(void)bob64_app_write(text,length);
}
static void write_number(u64 value) {
char digits[20];
usize count=0;
do {
digits[count++]=(char)('0'+value%10);
value/=10;
} while(value&&count<sizeof(digits));
while(count)(void)bob64_app_write_char((u8)digits[--count]);
}
static void write_labeled_number(const char *label,u64 value) {
write_text(label);
write_number(value);
write_text("\n");
}
s64 bob64_app_main(const BOB64_APP_STARTUP *startup) {
BOB64_FILE_INFO files[BOB64_SYSCALL_MAX_FILES];
u32 width=0,height=0;
s64 file_count,display_status;
u64 total_bytes=0;
if(!startup||startup->StructSize!=sizeof(*startup)||
startup->AbiVersion!=BOB64_APP_ABI_VERSION||startup->ArgumentCount!=0)
return -1;
if(bob64_app_query_abi()!=BOB64_SYSCALL_ABI_VERSION)return -2;
display_status=bob64_app_get_display(&width,&height);
file_count=bob64_app_list_files(files,BOB64_SYSCALL_MAX_FILES);
if(file_count<0||(u64)file_count>BOB64_SYSCALL_MAX_FILES)return -4;
for(s64 i=0;i<file_count;i++)total_bytes+=files[i].Size;
write_text("bob64 system information\n");
write_labeled_number("System call ABI: ",BOB64_SYSCALL_ABI_VERSION);
if(display_status)write_text("Display: unavailable\n");
else {
write_text("Display: ");write_number(width);write_text(" x ");
write_number(height);write_text(" pixels\n");
}
write_labeled_number("Uptime: ",bob64_app_ticks()/100);
write_labeled_number("RAM files: ",(u64)file_count);
write_labeled_number("RAM file data: ",total_bytes);
write_text("Uptime unit: seconds\n");
write_text("bob!\n");
return 0;
}
+202
View File
@@ -0,0 +1,202 @@
#include "../bob64/app.h"
#include "../bob64/gfx.h"
#include "../bob64/widgets.h"
#include "../bob64/window.h"
#define LAUNCHER_WIDTH 360u
#define LAUNCHER_HEIGHT 280u
#define LAUNCHER_ROWS 9u
static u32 pixels[LAUNCHER_WIDTH*LAUNCHER_HEIGHT];
static BOB64_GFX graphics;
static BOB64_WINDOW_MANAGER manager;
static BOB64_WINDOW window;
static BOB64_WINDOW_HANDLE order[1];
static BOB64_FILE_INFO files[BOB64_SYSCALL_MAX_FILES];
static u32 application_files[BOB64_SYSCALL_MAX_FILES];
static u32 application_count,selected_application,scroll;
static BOB64_RECT run_button={12,36,72,18};
static BOB64_RECT close_button={92,36,72,18};
static BOB64_BUTTON_STATE run_state,close_state;
static char status[32];
static usize length(const char *text) {
usize result=0;
if(text)while(text[result])result++;
return result;
}
static void copy(char *to,const char *from,usize limit) {
usize i=0;
while(i+1<limit&&from[i]){to[i]=from[i];i++;}
to[i]=0;
}
static int app_name(const char *name) {
usize size=length(name);
return size>5&&name[size-5]=='.'&&name[size-4]=='b'&&
name[size-3]=='6'&&name[size-2]=='4'&&name[size-1]=='e';
}
static int self_name(const char *name) {
static const char self[]="launcher.b64e";
usize size=length(name);
if(size!=sizeof(self)-1)return 0;
for(usize i=0;i<size;i++) {
char a=name[i],b=self[i];
if(a>='A'&&a<='Z')a=(char)(a-'A'+'a');
if(a!=b)return 0;
}
return 1;
}
static void refresh(void) {
s64 count=bob64_app_list_files(files,BOB64_SYSCALL_MAX_FILES);
application_count=0;
if(count<0) {
copy(status,"FILE LIST FAILED",sizeof(status));return;
}
for(u32 i=0;i<(u32)count;i++)
if(app_name(files[i].Name)&&!self_name(files[i].Name))
application_files[application_count++]=i;
if(selected_application>=application_count)
selected_application=application_count?application_count-1:0;
if(scroll>selected_application)scroll=selected_application;
copy(status,application_count?"SELECT AN APP":"NO APPS INSTALLED",
sizeof(status));
}
static void reveal_selection(void) {
if(selected_application<scroll)scroll=selected_application;
else if(selected_application>=scroll+LAUNCHER_ROWS)
scroll=selected_application-LAUNCHER_ROWS+1;
}
static void draw(void) {
bob64_gfx_fill_rect(&graphics,0,0,LAUNCHER_WIDTH,LAUNCHER_HEIGHT,
0x001a2a3cu);
bob64_gfx_fill_rect(&graphics,0,0,LAUNCHER_WIDTH,
BOB64_WINDOW_TITLE_BAR_HEIGHT,0x00335d8cu);
bob64_gfx_text(&graphics,12,8,"APPLICATION LAUNCHER",0x00ffffffu,1);
bob64_gfx_text(&graphics,12,28,"SELECT AN APP TO RUN",0x009eb3c7u,1);
bob64_button_draw(&graphics,&run_button,"RUN APP",&run_state);
bob64_button_draw(&graphics,&close_button,"CLOSE",&close_state);
bob64_gfx_text(&graphics,180,42,status,0x008fc8ffu,1);
for(u32 row=0;row<LAUNCHER_ROWS;row++) {
u32 index=scroll+row;
if(index>=application_count)break;
s32 y=68+(s32)(row*20);
if(index==selected_application)
bob64_gfx_fill_rect(&graphics,8,y-3,344,17,0x00335d8cu);
bob64_gfx_text(&graphics,14,y,
files[application_files[index]].Name,
index==selected_application?0x00ffffffu:0x00dbe8f4u,1);
}
if(bob64_app_window_present(window.Handle,graphics.Pixels,
graphics.Width,graphics.Height)!=(s64)(LAUNCHER_WIDTH*LAUNCHER_HEIGHT))
bob64_app_exit(-2);
}
static void launch_selected(void) {
s64 child_status=-1,result;
if(selected_application>=application_count) {
copy(status,"NO APP SELECTED",sizeof(status));return;
}
const char *name=files[application_files[selected_application]].Name;
const char *arguments[1]={name};
result=bob64_app_run(name,length(name),1,arguments,&child_status);
refresh();
if(result||child_status)copy(status,"APP FAILED",sizeof(status));
else copy(status,"APP EXITED OK",sizeof(status));
(void)bob64_app_window_focus(window.Handle);
}
s64 bob64_app_main(const BOB64_APP_STARTUP *startup) {
BOB64_EVENT event,screen_event,routed;
s64 target;
BOB64_WINDOW_HANDLE kernel_handle,app_handle;
if(!startup||startup->StructSize!=sizeof(*startup)||
startup->AbiVersion!=BOB64_APP_ABI_VERSION||
bob64_app_query_abi()!=BOB64_SYSCALL_ABI_VERSION)return -1;
if(bob64_app_write("bob!",4)!=4)return -2;
if(startup->ArgumentCount>1) {
s64 child_status=-1,result;
if(!startup->Arguments||!startup->Arguments[1])return -3;
const char *name=startup->Arguments[1];
result=bob64_app_run(name,length(name),
(usize)(startup->ArgumentCount-1),startup->Arguments+1,
&child_status);
return result?result:child_status;
}
u32 screen_width,screen_height;
if(bob64_app_get_display(&screen_width,&screen_height)||
screen_width<LAUNCHER_WIDTH||screen_height<LAUNCHER_HEIGHT)return -3;
if(bob64_wm_init(&manager,&window,1,order,screen_width,screen_height))return -4;
kernel_handle=bob64_app_window_create(
(s32)(screen_width-LAUNCHER_WIDTH)/2,
(s32)(screen_height-LAUNCHER_HEIGHT)/2,
LAUNCHER_WIDTH,LAUNCHER_HEIGHT);
if(!kernel_handle||(s64)kernel_handle<0)return -5;
manager.NextHandle=kernel_handle;
app_handle=bob64_wm_create(&manager,
(s32)(screen_width-LAUNCHER_WIDTH)/2,
(s32)(screen_height-LAUNCHER_HEIGHT)/2,
LAUNCHER_WIDTH,LAUNCHER_HEIGHT,(void *)"Application launcher");
if(app_handle!=kernel_handle) {
if(app_handle)bob64_wm_destroy(&manager,app_handle);
bob64_app_window_destroy(kernel_handle);return -6;
}
graphics.Pixels=pixels;graphics.Width=LAUNCHER_WIDTH;
graphics.Height=LAUNCHER_HEIGHT;
graphics.Capacity=LAUNCHER_WIDTH*LAUNCHER_HEIGHT;
refresh();
for(;;) {
draw();
if(bob64_app_wait_event(&event))return -7;
if(event.Type==BOB64_EVENT_KEY_DOWN&&event.Character==0x1b)break;
screen_event=event;screen_event.X=event.ScreenX;
screen_event.Y=event.ScreenY;
target=bob64_wm_dispatch(&manager,&screen_event,&routed);
if(event.Type==BOB64_EVENT_MOUSE_MOVE) {
BOB64_EVENT local=event;
local.X=event.ScreenX-window.X;local.Y=event.ScreenY-window.Y;
bob64_button_event(&run_button,&run_state,&local);
bob64_button_event(&close_button,&close_state,&local);
}
if(event.Type==BOB64_EVENT_MOUSE_WHEEL&&
bob64_rect_contains(&(BOB64_RECT){window.X,window.Y+64,
window.Width,window.Height-64},event.ScreenX,event.ScreenY)) {
if(event.Wheel>0&&selected_application)selected_application--;
else if(event.Wheel<0&&selected_application+1<application_count)
selected_application++;
reveal_selection();
}
if(event.Type==BOB64_EVENT_KEY_DOWN) {
if(event.Key==(BOB64_EVENT_KEY_EXTENDED|0x48)) {
if(selected_application)selected_application--;
reveal_selection();
} else if(event.Key==(BOB64_EVENT_KEY_EXTENDED|0x50)) {
if(selected_application+1<application_count)selected_application++;
reveal_selection();
} else if(event.Character=='\n'||event.Character=='a'||
event.Character=='A'||event.Character=='r'||
event.Character=='R')launch_selected();
else if(event.Character=='x'||event.Character=='X')break;
}
if(event.Type==BOB64_EVENT_MOUSE_BUTTON&&target==(s64)window.Handle) {
BOB64_EVENT local=event;local.X=routed.X;local.Y=routed.Y;
int run=bob64_button_event(&run_button,&run_state,&local);
int close=bob64_button_event(&close_button,&close_state,&local);
if(!(event.Buttons&BOB64_BUTTON_LEFT)&&close)break;
if(!(event.Buttons&BOB64_BUTTON_LEFT)&&run)launch_selected();
else if((event.Buttons&BOB64_BUTTON_LEFT)&&routed.Y>=64) {
u32 row=(u32)(routed.Y-68)/20;
if(routed.Y>=68&&scroll+row<application_count)
selected_application=scroll+row;
}
}
}
bob64_app_window_destroy(window.Handle);
bob64_wm_destroy(&manager,window.Handle);
return 0;
}
+37
View File
@@ -0,0 +1,37 @@
#include "../bob64/app.h"
static void write_text(const char *text) {
usize length=0;
while(text[length])length++;
(void)bob64_app_write(text,length);
}
static void write_size(u64 value) {
char digits[20];
usize count=0;
do {
digits[count++]=(char)('0'+value%10);
value/=10;
} while(value&&count<sizeof(digits));
while(count)bob64_app_write_char((u8)digits[--count]);
}
s64 bob64_app_main(const BOB64_APP_STARTUP *startup) {
BOB64_FILE_INFO files[BOB64_SYSCALL_MAX_FILES];
s64 count;
if(!startup||startup->StructSize!=sizeof(*startup)||
startup->AbiVersion!=BOB64_APP_ABI_VERSION)return -1;
count=bob64_app_list_files(files,BOB64_SYSCALL_MAX_FILES);
if(count<0) {
write_text("cannot list files\n");
return count;
}
for(s64 i=0;i<count;i++) {
write_text(files[i].Name);
write_text(" ");
write_size(files[i].Size);
write_text(" bytes\n");
}
if(!count)write_text("no files\n");
return 0;
}
+15
View File
@@ -0,0 +1,15 @@
#include "../bob64/app.h"
/* The QEMU runtime test injects a mouse move through the emulated PS/2 device. */
s64 bob64_app_main(const BOB64_APP_STARTUP *startup) {
BOB64_EVENT event;
static const char passed[]="bob64 live mouse event passed\n";
if(!startup||startup->AbiVersion!=BOB64_APP_ABI_VERSION)return -1;
if(bob64_app_wait_event(&event))return -2;
if(event.Type!=BOB64_EVENT_MOUSE_MOVE||
(!event.DeltaX&&!event.DeltaY))
return -3;
if(bob64_app_write(passed,sizeof(passed)-1)!=(s64)(sizeof(passed)-1))
return -4;
return 0;
}
+10
View File
@@ -0,0 +1,10 @@
#include "../bob64/app.h"
s64 bob64_app_main(const BOB64_APP_STARTUP *startup) {
s64 child_status=-1;
if(!startup||startup->AbiVersion!=BOB64_APP_ABI_VERSION||
bob64_app_run("bob.b64e",8,1,(const char *const[]){"bob.b64e"},
&child_status)||child_status)return -1;
if(bob64_app_write("bob!",4)!=4)return -2;
return 0;
}
+297
View File
@@ -0,0 +1,297 @@
#include "../bob64/app.h"
#include "../bob64/editor.h"
#include "../bob64/gfx.h"
static char note_buffer[BOB64_EDITOR_CAPACITY+1];
static u32 note_pixels[640u*420u];
static BOB64_EDITOR note_editor;
static BOB64_GFX note_graphics;
static char note_status[32]="CTRL S SAVE ESC CLOSE";
static const char note_filename[]="notes.txt";
static usize text_length(const char *text) {
usize length=0;
if(!text)return 0;
while(text[length])length++;
return length;
}
static int same_text(const char *left,const char *right) {
usize i=0;
if(!left||!right)return 0;
while(left[i]&&left[i]==right[i])i++;
return left[i]==right[i];
}
static void write_text(const char *text) {
(void)bob64_app_write(text,text_length(text));
}
static void note_copy(char *destination,const char *source,usize capacity) {
usize i=0;
if(!destination||!capacity)return;
if(source)while(i+1<capacity&&source[i]) {
destination[i]=source[i];i++;
}
destination[i]=0;
}
static s64 read_note(const char *name,usize name_length,usize *length) {
s64 result=bob64_app_file_read_all(name,name_length,note_buffer,
BOB64_EDITOR_CAPACITY);
if(result<0)return result;
if(bob64_editor_is_binary_text(note_buffer,(usize)result))return -84;
*length=(usize)result;
return result;
}
static int append_arguments(const BOB64_APP_STARTUP *startup,u64 first,
usize *length) {
for(u64 i=first;i<startup->ArgumentCount;i++) {
const char *argument=startup->Arguments[i];
usize argument_length=text_length(argument);
usize separator=i>first?1:0;
if(!argument||argument_length>BOB64_EDITOR_CAPACITY-*length||
separator>BOB64_EDITOR_CAPACITY-*length-argument_length)
return -1;
if(separator)note_buffer[(*length)++]=' ';
for(usize j=0;j<argument_length;j++)
note_buffer[(*length)++]=argument[j];
}
note_buffer[*length]=0;
return 0;
}
static int save_note(const char *name,usize name_length,usize length) {
s64 result=bob64_app_file_write_all(name,name_length,note_buffer,length);
if(result!=(s64)length) {
write_text("cannot save note\n");
return -1;
}
write_text("saved\n");
return 0;
}
static void note_gui_draw(void) {
const u32 width=640,height=420;
const u32 columns=96,visible_rows=29;
u32 row=0,column=0,cursor_row,cursor_column;
bob64_gfx_fill_rect(&note_graphics,0,0,width,height,0x0009111bu);
bob64_gfx_fill_rect(&note_graphics,2,2,width-4,height-4,0x001a2a3cu);
bob64_gfx_fill_rect(&note_graphics,0,0,width,26,0x00335d8cu);
bob64_gfx_line(&note_graphics,0,0,width-1,0,0x00a4c8ffu);
bob64_gfx_line(&note_graphics,0,height-1,width-1,height-1,0x00a4c8ffu);
bob64_gfx_line(&note_graphics,0,0,0,height-1,0x00a4c8ffu);
bob64_gfx_line(&note_graphics,width-1,0,width-1,height-1,0x00a4c8ffu);
bob64_gfx_text(&note_graphics,12,8,"NOTES",0x00ffffffu,1);
bob64_gfx_text(&note_graphics,14,36,note_filename,0x009eb3c7u,1);
bob64_editor_visual_position(&note_editor,columns,&cursor_row,&cursor_column);
if(cursor_row<note_editor.ScrollRow)note_editor.ScrollRow=cursor_row;
else if(cursor_row>=note_editor.ScrollRow+visible_rows)
note_editor.ScrollRow=cursor_row-visible_rows+1;
for(u32 i=0;i<=note_editor.Length;i++) {
if(column>=columns&&(i==note_editor.Length||note_editor.Text[i]!='\n')) {
row++;column=0;
}
if(i==note_editor.Cursor) {
if(row>=note_editor.ScrollRow&&row<note_editor.ScrollRow+visible_rows) {
s32 x=14+(s32)(column*6),y=54+(s32)((row-note_editor.ScrollRow)*10);
bob64_gfx_line(&note_graphics,x,y,x,y+7,0x00ffffffu);
}
}
if(i==note_editor.Length)break;
if(note_editor.Text[i]=='\n') {row++;column=0;continue;}
if(row>=note_editor.ScrollRow&&row<note_editor.ScrollRow+visible_rows) {
char character[2]={note_editor.Text[i],0};
bob64_gfx_text(&note_graphics,14+(s32)(column*6),
54+(s32)((row-note_editor.ScrollRow)*10),character,
0x00e2ebf5u,1);
}
column++;
}
(void)cursor_column;
bob64_gfx_line(&note_graphics,8,390,width-8,390,0x0044576au);
bob64_gfx_text(&note_graphics,12,398,note_status,0x008fc8ffu,1);
}
static s64 note_gui_run(void) {
const u32 width=640,height=420;
u32 display_width,display_height;
u64 handle;
usize length=0;
s64 result;
if(bob64_app_get_display(&display_width,&display_height)||
display_width<width||display_height<height) {
write_text("display is too small for notes\n");
return -1;
}
result=read_note(note_filename,sizeof(note_filename)-1,&length);
if(result<0&&result!=-2) {
write_text(result==-84?"notes.txt is not a text file\n":
"cannot open notes.txt\n");
return -1;
}
bob64_editor_init(&note_editor,result>=0?note_buffer:0,(u32)length);
note_graphics.Pixels=note_pixels;
note_graphics.Width=width;note_graphics.Height=height;
note_graphics.Capacity=sizeof(note_pixels)/sizeof(note_pixels[0]);
handle=bob64_app_window_create((s32)((display_width-width)/2),
(s32)((display_height-height)/2),width,height);
if(!handle) {
write_text("cannot open notes window\n");
return -1;
}
for(;;) {
BOB64_EVENT event;
note_gui_draw();
if(bob64_app_window_present(handle,note_pixels,width,height)<0) {
bob64_app_window_destroy(handle);
return -2;
}
if(bob64_app_wait_event(&event)) {
bob64_app_window_destroy(handle);
return -3;
}
if(event.Type!=BOB64_EVENT_KEY_DOWN)continue;
if(event.Key==0x01)break;
if((event.Modifiers&BOB64_EVENT_MOD_CONTROL)&&
(event.Character=='s'||event.Character=='S')) {
usize saved_length=note_editor.Length;
for(usize i=0;i<saved_length;i++)note_buffer[i]=note_editor.Text[i];
if(bob64_app_file_write_all(note_filename,sizeof(note_filename)-1,
note_buffer,saved_length)==(s64)saved_length)
note_copy(note_status,"SAVED",sizeof(note_status));
else note_copy(note_status,"SAVE FAILED",sizeof(note_status));
continue;
}
bob64_editor_handle_key(&note_editor,&event);
note_copy(note_status,"CTRL S SAVE ESC CLOSE",sizeof(note_status));
}
if(bob64_app_window_destroy(handle))return -4;
return 0;
}
s64 bob64_app_main(const BOB64_APP_STARTUP *startup) {
const char *command,*name;
usize name_length,length=0;
s64 result;
if(!startup||startup->StructSize!=sizeof(*startup)||
startup->AbiVersion!=BOB64_APP_ABI_VERSION||
(startup->ArgumentCount&&!startup->Arguments))return -1;
if(!startup->ArgumentCount)return note_gui_run();
if(startup->ArgumentCount<2||!startup->Arguments[1]) {
write_text("usage: notes show NAME | copy SOURCE DEST | put NAME TEXT | add NAME TEXT | delete NAME\n");
return 1;
}
command=startup->Arguments[1];
if(startup->ArgumentCount<3||!startup->Arguments[2]) {
write_text("usage: notes show NAME | copy SOURCE DEST | put NAME TEXT | add NAME TEXT | delete NAME\n");
return 1;
}
name=startup->Arguments[2];
name_length=text_length(name);
if(!name_length||name_length>BOB64_SYSCALL_MAX_FILENAME) {
write_text("invalid note name\n");
return 1;
}
if(same_text(command,"show")&&startup->ArgumentCount==3) {
result=read_note(name,name_length,&length);
if(result<0) {
write_text(result==-84?"not a text note\n":"note not found or too large\n");
return 1;
}
for(usize offset=0;offset<length;) {
usize chunk=length-offset;
if(chunk>BOB64_SYSCALL_MAX_BUFFER)chunk=BOB64_SYSCALL_MAX_BUFFER;
if(bob64_app_write(note_buffer+offset,chunk)!=(s64)chunk)return -2;
offset+=chunk;
}
if(bob64_app_write_char('\n')<0)return -2;
return 0;
}
if(same_text(command,"copy")&&startup->ArgumentCount==4&&
startup->Arguments[3]) {
const char *destination=startup->Arguments[3];
usize destination_length=text_length(destination);
if(!destination_length||destination_length>BOB64_SYSCALL_MAX_FILENAME||
same_text(name,destination)) {
write_text("invalid copy destination\n");
return 1;
}
if(destination_length>=5&&destination[destination_length-5]=='.'&&
destination[destination_length-4]=='b'&&
destination[destination_length-3]=='6'&&
destination[destination_length-2]=='4'&&
destination[destination_length-1]=='e') {
write_text("refusing to overwrite an app\n");
return 1;
}
result=read_note(destination,destination_length,&length);
if(result<0&&result!=-2) {
write_text("destination is not a text note\n");
return 1;
}
result=read_note(name,name_length,&length);
if(result<0) {
write_text(result==-84?"source is not a text note\n":
"source note not found or too large\n");
return 1;
}
result=bob64_app_file_write_all(destination,destination_length,
note_buffer,length);
if(result!=(s64)length) {
write_text("cannot copy note\n");
return 1;
}
write_text("Copied.\n");
return 0;
}
if((same_text(command,"put")||same_text(command,"edit"))&&
startup->ArgumentCount>=4) {
result=read_note(name,name_length,&length);
if(result<0&&result!=-2) {
write_text(result==-84?"not a text note\n":"cannot read note\n");
return 1;
}
length=0;
if(append_arguments(startup,3,&length)) {
write_text("note is too large\n");
return 1;
}
return save_note(name,name_length,length);
}
if(same_text(command,"add")&&startup->ArgumentCount>=4) {
result=read_note(name,name_length,&length);
if(result<0&&result!=-2) {
write_text(result==-84?"not a text note\n":"cannot read note\n");
return 1;
}
if(length&&note_buffer[length-1]!='\n') {
if(length>=BOB64_EDITOR_CAPACITY) {
write_text("note is too large\n");
return 1;
}
note_buffer[length++]='\n';
}
if(append_arguments(startup,3,&length)) {
write_text("note is too large\n");
return 1;
}
return save_note(name,name_length,length);
}
if(same_text(command,"delete")&&startup->ArgumentCount==3) {
result=read_note(name,name_length,&length);
if(result<0) {
write_text(result==-84?"not a text note\n":"note not found\n");
return 1;
}
if(bob64_app_delete_file(name,name_length)) {
write_text("cannot delete note\n");
return 1;
}
write_text("deleted\n");
return 0;
}
write_text("usage: notes show NAME | copy SOURCE DEST | put NAME TEXT | add NAME TEXT | delete NAME\n");
return 1;
}
+15 -6
View File
@@ -1,4 +1,4 @@
# bob64 application ABI v1 / syscall ABI v10
# bob64 application ABI v1 / syscall ABI v12
The kernel and first native applications use the Microsoft x64 ABI, matching
the x64 UEFI toolchain. `bob64/abi.h` is the source for the version and the
@@ -49,7 +49,7 @@ function is not supported: apps must use the exit system call.
## System calls
System-call ABI v10 uses interrupt vector `0x80`. Put the service number in
System-call ABI v12 uses interrupt vector `0x80`. Put the service number in
`RAX`; a returning call writes its result to `RAX`. The available services are:
| Number | Name | Argument | Result |
@@ -75,6 +75,7 @@ System-call ABI v10 uses interrupt vector `0x80`. Put the service number in
| 18 | Seek handle | handle in `RCX`, nonnegative signed 64-bit absolute offset in `RDX` | new offset or negative error |
| 19 | Close handle | handle in `RCX` | `0` or negative error |
| 20 | Get timer ticks | ignored | 64-bit count of 100 Hz PIT ticks since kernel initialization |
| 21 | Run application | name pointer in `RCX`, name length in `RDX`, writable signed 64-bit exit-status pointer in `R8`, argc in `RSI`, argv pointer-vector in `R9` | `0` after child exit, or negative error |
The first kernel smoke app queries the ABI, prints `bob!` one character at a
time, and exits through this path. Console and per-call file buffers are
@@ -86,7 +87,9 @@ belong to the active foreground app and are invalidated when it exits or the
file is deleted. Reads and writes advance a per-handle 64-bit position; seek
sets a nonnegative signed 64-bit absolute position. Append-mode writes target
the current end of file. Reads can be short at EOF, writes past the end
zero-fill the gap, and each transfer is bounded to 4096 bytes. File enumeration accepts
zero-fill the gap, and each transfer is bounded to 4096 bytes. The app header also
provides whole-file read/write helpers that loop over these bounded calls; the
desktop editor uses a 16 KiB text limit across four transfers. File enumeration accepts
capacity 1 through 32 and returns fixed 72-byte `BOB64_FILE_INFO` records
containing a 64-byte zero-terminated name and a 64-bit size; if the complete
directory does not fit, it returns `-28` without copying a partial result.
@@ -106,9 +109,15 @@ and five. `bob64_app_wait_event` blocks while the kernel polls PS/2 devices and
copies the event to writable app memory.
The current flat volatile filesystem stores arbitrary bytes, while names reject
path separators and characters outside its documented safe set.
`bob64/app.h` provides matching
C wrappers. A CPU exception from active user code returns an error status to the
kernel instead of halting the system. `bob64/window.h` provides a reusable
`bob64/app.h` provides matching C wrappers, including `bob64_app_run` for
synchronous child launches. Syscall 21 accepts at most 16 argv strings and
4096 total bytes; `RSI` is argc and `R9` points to the caller-owned pointer
vector. The kernel validates and copies every pointer and string before it
starts the child. The caller supplies the full argv, including argv[0]. The child
exit status is copied to a validated app-owned pointer, and parent syscall and
window state is restored on return. User-entry state supports up to eight
nested app entries. A CPU exception from active user code returns an error
status to the kernel instead of halting the system. `bob64/window.h` provides a reusable
app-owned window manager using 64-bit handles and pointers; it routes the
versioned keyboard/mouse event records without kernel pointers. Syscalls 11-13
create, destroy, and present kernel-owned windows for the foreground app. Each
+142 -53
View File
@@ -31,20 +31,68 @@ visually checked at 1280x800.
Kernel entry also adopts the seeded physical-page allocator and maps pages into
a small coalescing heap in the high canonical address range. Its boot smoke test
checks aligned allocation, zeroing, multi-page growth, writes, and freeing. The
early heap does not yet reclaim empty pages or provide SMP locking.
early heap reclaims full trailing pages when they become unused. The page-table
pool grows in mapped 64-page chunks before its reserve runs out. SMP locking
remains open.
After the memory checks, bob64 opens a shell. When an 8042 controller is
available, keyboard IRQ1 feeds its event queue; otherwise input falls back to
PS/2 polling. COM1 remains polled. The shell provides `help`, `clear`, `mem`, `heap`, `version`, and
`echo`. A heap-backed RAM filesystem adds `ls`, `cat NAME`, `write NAME TEXT`,
and `rm NAME`; it stores arbitrary file bytes, and its contents disappear on
reboot. A 100 Hz PIT IRQ supplies kernel and app tick counts. USB keyboards,
history, completion, directories, and persistent storage are still open.
reboot. Up/Down recalls the last eight shell commands, and Tab completes built-in
commands plus file arguments for `cat`, `rm`, `run`, and `cc`. A 100 Hz PIT IRQ
supplies kernel and app tick counts. USB keyboards, directories, and persistent
storage are still open.
The shell also supports `save` and `restore` using B64S version 1. The format
stores fixed-width lengths and arbitrary file bytes with a CRC-32, never raw
pointers. The current checkpoint lives in the kernel heap and survives
filesystem edits until reboot; it is not written to disk yet.
pointers. `save` keeps a RAM checkpoint and writes a compressed copy to UEFI
non-volatile storage in two alternating slots. Each compressed snapshot is
split into bounded variables, and the active-slot record changes only after all
chunks are written; restore falls back to the prior committed slot if the active
one is damaged. Bob64 restores that snapshot on the next boot; if firmware
storage is unavailable or full, the RAM checkpoint still works for the current
session. Firmware variable and total-store limits apply. If firmware does not
implement `QueryVariableInfo`, the kernel still attempts the write and reports
the firmware's result. The OVMF test script verifies save, reset, and restore.
The kernel installs `echo.b64e`, a native 64-bit app that writes its startup
arguments and a newline. `run echo.b64e bob!` exercises the
pointer-width-safe startup record and makes the utility available to the
desktop's Run App action. The UEFI smoke path passes `bob!` through the startup
record and verifies those exact output bytes.
`ls.b64e` is also installed by default. Run `run ls.b64e` to list RAM files and
their byte sizes through the application-facing file-list syscall. Its boot
smoke check validates a real returned filename in app memory.
`cat.b64e` reads a named file using 4 KiB streaming transfers, preserving its
contents and adding a final newline only when needed. `run cat.b64e FILE` uses
the same file-handle ABI available to other native applications.
`notes.b64e` opens an editable Notes window when launched from the desktop.
Use the arrow keys, Home/End, Backspace, and Delete to edit `notes.txt`; Ctrl+S
saves it and Escape closes the window. The Notes editor supports up to 16 KiB
using 4 KiB streaming transfers. From the shell, use `run notes.b64e copy SOURCE DEST`
to copy text files, or `put NAME TEXT`, `add NAME TEXT`,
`show NAME`, and `delete NAME` (`edit` aliases `put`). Text is passed as
command-line arguments, so spaces between arguments are preserved. The app
refuses to replace or delete binary files. The kernel smoke path copies a
12 KiB text file and verifies every byte.
`info.b64e` is the native system-information app. It reports the syscall ABI,
display resolution when GOP is available, uptime in seconds, and the number and
total data size of files in the RAM filesystem. The build embeds it in the
kernel image, and its output ends with `bob!` for smoke testing.
`launcher.b64e` opens a managed native window listing installed `.b64e` apps.
Run `launcher.b64e APP [ARG ...]` from the shell to start an app directly with
its full argument vector; the launcher forwards argv[0] and the remaining args.
Use Up/Down and Enter (or click an app and **RUN APP**) to start a selected app;
Escape, `X`, or **CLOSE** returns to the shell. This standalone launcher starts
apps without command-line arguments; use the shell's `run` command when an app
needs arguments.
`bob64/exec.h` defines the B64E v1 flat, position-independent native image
format. It carries an explicit ABI version and 64-bit payload, memory, code, and
@@ -62,11 +110,13 @@ switches CR3 while it loads a synthetic app. The shell can run B64E files with
Each launch gets a fresh isolated root, and the kernel frees its app pages and
page tables after the exit. The example app prints `bob!` through the DPL3
`int 0x80` gate and exits back to the kernel.
Syscall ABI v10 exposes an ABI query, character and bounded buffer output,
Syscall ABI v12 exposes an ABI query, character and bounded buffer output,
whole-file and handle-based streaming file read/write/list/delete, display dimensions, full-screen packed
`0x00RRGGBB` surface presentation, app-owned-window creation/destruction and
presentation through a kernel compositor, focus control, input events, and
process exit. Applications can use
process exit, and synchronous child-app launch with bounded, validated argv
copying and parent-state restoration.
Applications can use
`bob64_app_get_display` and `bob64_app_present` from `bob64/app.h`; the kernel
validates the whole user surface, copies it in bounded chunks and converts it
to GOP channel order. Surfaces must match the display resolution and are capped
@@ -74,44 +124,63 @@ at 16 MiB. User buffers are checked against the process page
tables; file reads require writable app pages. `bob64/app.h` provides C wrappers
without exposing kernel-internal types. The C smoke app writes and reads back a
small RAM file before it exits.
`apps/bob64_display.c` is an early native graphics app. It queries GOP
dimensions, draws a packed color surface, presents it, then prints `bob!`.
The bob64 build packages it as `build/bob64-app/display.b64e` and checks its
B64E metadata alongside the file-I/O smoke app. The native desktop runtime test
also exercises GOP-backed window presentation through the kernel compositor.
The demo stays on screen until Escape; `bob64_app_wait_event` receives typed
PS/2 key-down/up events, including Shift, Caps, Control, Alt and extended
arrow-key codes, plus mouse movement, buttons and IntelliMouse wheel events.
`apps/bob64_display.c` ports Bob32's graphics demo as a centered 640x400 native
window. It draws colored panels and diagonal lines, presents them through the
kernel compositor, prints `bob!`, then returns to the shell on X or Escape.
The bob64 build packages it as `build/bob64-app/display.b64e`, installs it in
the RAM filesystem, and QEMU tests the window presentation and clean return.
The smaller app-owned drawing surface also keeps firmware snapshots within
their storage budget. `bob64_app_wait_event` receives typed PS/2 key-down/up
events, including Shift, Caps, Control, Alt and extended arrow-key codes, plus
mouse movement, buttons and IntelliMouse wheel events.
PIT IRQ0 supplies 100 Hz ticks; keyboard IRQ1 and mouse IRQ12 feed event queues
when the 8042 is available. Mouse position and packet decoding happen in the
IRQ handler. USB input remains future work.
`bob64/window.h` provides app-owned windows, 64-bit handles/context pointers,
focus, z-order, title-bar dragging, hit testing, dirty redraws and local event
routing. The v10 kernel API additionally creates, destroys and composites up to
routing. The v11 kernel API additionally creates, destroys and composites up to
16 kernel-owned window surfaces per foreground app, routes events with 64-bit
window handles, and releases surfaces when the app exits. The desktop now draws
its file browser and editor into separate kernel-managed surfaces while keeping
the app-side manager for widget layout and mouse hit testing. Concurrent apps
remain a future step. `apps/bob64_gui.c` is the first interactive desktop:
launch `run desktop.b64e [filename]` from the shell (the default file is
`notes.txt`), browse files in the left window, use Up/Down to select, `O` or
Enter to open, `R` to refresh, and `D` twice to delete a file. Type into the
editor, use arrow keys to move, Backspace to delete,
`notes.txt`), browse files in the left window, use Up/Down or the mouse wheel
to select and preview the selected file's first 384 bytes, `O` or Enter to open,
`R` to refresh, and `D` or **DELETE** to open
a Yes/Cancel confirmation. Press `Y` or Enter to confirm, and `N` or Escape to
cancel. Type into the editor, use arrow keys to move, Home/End to jump to the current line edges, Backspace to delete,
click in the text to place the cursor, Enter for a new line, and Ctrl+S to save.
The editor scrolls to keep the caret visible.
Tab changes focus and Escape returns to the shell; unsaved edits require a
second Escape. Filenames use letters, digits, period, underscore or hyphen.
Files up to 4096 bytes fit in the current app file ABI; a
larger existing file is protected from accidental overwrite. Under QEMU/OVMF at
The editor scrolls to keep the caret visible. Click the **NAME** field above
the editor to place its caret and edit the destination; Enter or Tab leaves the
field, and Ctrl+S saves the document under that name. Names accept letters,
digits, period, underscore or hyphen; executable names are protected. Escape
returns to the shell; unsaved text or name changes require a second Escape.
Select a `.b64e` file and press `A` or click **Run App** to launch it; the
desktop resumes with the child's exit status when it finishes. Click **APPS**
in the file window or press `P` from any desktop window to open the Applications
window. Use Up/Down to select an installed `.b64e` app, press Enter or `A` to
launch it, and click **X CLOSE** or press Escape/`X` to close the launcher.
Click **HELP** or press `H`/`?` from the Files window to view the desktop
shortcuts; Escape, `X`, or **CLOSE** dismisses it.
The desktop buttons share `bob64/widgets.h`, which handles hover and pressed
feedback and activates on a left-button release inside the control.
The desktop editor supports text files up to 16 KiB, matching the resident
compiler's source limit. It uses bounded 4 KiB streaming transfers; larger
files are protected from accidental overwrite. Under QEMU/OVMF at
1280x800, both windows rendered, PS/2 input created an additional window and
returned to the shell, a mouse click selected a file-list row, and Ctrl+S saved
editor text through the file syscall.
The editor refuses `.b64e` files and text containing binary control bytes;
use the Applications window to run executables.
User-origin CPU exceptions return an error status to the kernel. User apps run
with interrupts enabled when the keyboard IRQ path is active, and the loader
restores the caller's interrupt-enable state on return. The desktop editor still uses whole-file calls and
is capped at 4096 bytes; larger files are protected from accidental overwrite.
Other apps can use ABI v10 streaming handles for bounded transfers at 64-bit
offsets. Interactive app management remains future work. QEMU/OVMF runtime
restores the caller's interrupt-enable state on return. The desktop editor
and Notes app use bounded 4 KiB streaming transfers and support up to 16 KiB
of text; larger files are
protected from accidental overwrite. Other apps can use ABI v12 streaming
handles for bounded transfers at 64-bit offsets. The kernel smoke app launches another native app and checks its return
status; simultaneous app management remains future work. QEMU/OVMF runtime
checks exercise the ring-3 smoke app, syscalls,
application loader, shell, and desktop.
@@ -121,14 +190,21 @@ executable loader, user syscall ABI, RAM-file read/write, and process exit path.
The smaller kernel-generated app remains a separate ring-3 boot smoke test.
The shell also embeds `bob.c` and supports `cc bob.c` followed by
`run app.b64e`. The resident compiler emits a B64E image itself, with separate
read-only executable code and writable/NX data pages. Its initial C subset
`run app.b64e`. The resident compiler accepts up to 16 KiB of source and emits
a B64E image with separate read-only executable code and writable/NX data
regions of up to 16 KiB each. Its initial C subset
accepts `int`, `short`, `long`, or `long long` main returns; initialized
`short`, `int`, `long`, and `long long` locals; local assignment; calls to
`bob64_app_write` with string literals and matching constant lengths; and
`bob64_app_write` with typed `char *` expressions and scalar length expressions; and
`return` expressions using 64-bit
integer literals, parentheses, unary minus, addition, subtraction, and
multiplication. The compiler follows LLP64: `short` is 16-bit; `int` and `long`
integer literals, parentheses, unary minus, addition, subtraction, multiplication,
signed division/remainder and unsigned pointer-sized division/remainder. Division
truncates signed results toward zero; division by zero and signed overflow remain
C undefined behavior. Bitwise complement, AND, XOR, OR and left/right shifts use
C precedence; right shift is arithmetic for signed expressions and logical for
`usize`. Relational comparisons bind more tightly than equality comparisons, and
both bind more tightly than bitwise operators; `&&` and `||` retain short-circuit
behavior. The compiler follows LLP64: `short` is 16-bit; `int` and `long`
are 32-bit and sign-extend on return; `long long` is 64-bit and preserves its
full result. Short globals, locals, struct fields, function parameters and
returns are sign-extended on load and use 16-bit storage. The resident subset
@@ -140,17 +216,20 @@ and are rejected when used as values. The resident subset recognizes
returns, and scalar storage. Function prototypes and definitions can also
return `char *`, `short *`, `int *`, or pointers to declared structs, with
matching pointee types enforced at return statements. The pointer-sized integer
names are compiler built-ins because typedefs and header inclusion are not
implemented. `usize *`, `uintptr_t *`, `isize *`, `intptr_t *`, and
names are compiler built-ins. Bounded file-scope typedefs can alias supported
scalar types, scalar pointers, and previously declared named structs, including
alias chains; typedef arrays, function pointers, anonymous structs, and header
inclusion are not implemented. `usize *`, `uintptr_t *`, `isize *`, `intptr_t *`, and
`long long *` support dereference, indexing, assignment, function arguments and
returns, eight-byte scaled arithmetic, and matching global scalar pointers.
Signed and unsigned wide pointers have separate types; `isize *` and
`long long *` are equivalent in this subset. Fixed-size arrays of these wide
scalar types support local and global storage, brace initialization,
indexed reads and writes, and array-parameter decay. Local arrays are limited to
16 elements by the fixed stack frame; global arrays share the 4 KiB data page.
indexed reads and writes, and array-parameter decay. Each function can use up
to 64 locals and 1 KiB of local storage; local arrays can use that frame subject
to element-size and alignment. Global arrays share the 16 KiB data region.
The generated entry shim follows the Microsoft x64 ABI and exits via syscall ABI
v4. There are at most 16 locals in one function. File-scope `short`, `int`, `long`, `char`, and
v4. File-scope `short`, `int`, `long`, `char`, and
`long long` objects use the app's 64-bit-addressed writable data page; scalar
constants and fixed `short`/`int`/`char` arrays can be initialized; fixed
`long long`/`usize` arrays are also supported. Global
@@ -160,12 +239,12 @@ struct objects can use `&object`; `main` initializes them with position-
independent x64 code, without fixed-address relocations. Globals are shared by
all compiled functions. Named structs support aligned `short`, `int`, `long`,
`char`, `long long`, and scalar pointer fields, local/global instances, and
`.`/`->` field reads and writes. Nested structs, struct arrays, typedefs, and multiple translation units
remain unsupported. Limits are 8 struct types, 16 fields per type, 16 global
objects, and one 4 KiB data page. Struct pointers can be passed to helper
`.`/`->` field reads and writes. Nested structs, struct arrays, and multiple translation units
remain unsupported. Limits are 8 struct types, 16 fields per type, 32 typedefs, 16 global
objects, and 16 KiB of global data. Struct pointers can be passed to helper
functions, which can access fields with `->`. The resident
compiler also supports fixed local `short` and `int` arrays (up to 64 short or
32 int elements within a 128-byte frame), `short *`/`int *` locals,
compiler also supports fixed local `short` and `int` arrays (up to 512 short or
256 int elements within the 1 KiB frame), `short *`/`int *` locals,
array-to-pointer decay, address-of and dereference, indexed loads/stores, and
scaled pointer addition and subtraction, including element-count pointer
differences. String literals
@@ -188,9 +267,9 @@ may declare or omit parameter names. Array parameters index as `int *`. Compound
blocks and `for` initializers have lexical scopes with local shadowing. Return
types other than `int`, `short`, `long`, or `long long` remain unsupported and
report a source offset. `if`/`else` and `while`
support nonzero conditions plus signed integer
`==`, `!=`, `<`, `<=`, `>`, and `>=` comparisons, and may use braces. Unary `!` and short-circuit
`&&`/`||` are supported. Basic `for` loops accept an optional initializer,
support nonzero conditions plus signed or unsigned integer
`==`, `!=`, `<`, `<=`, `>`, and `>=` comparisons, and may use braces. Unary `!`/`~`
and short-circuit `&&`/`||` are supported. Basic `for` loops accept an optional initializer,
condition, and scalar-variable assignment update. `break` and `continue` target
the nearest enclosing loop, and `continue` in a `for` loop runs its update.
`return` is also valid inside conditional and loop statements, followed by the
@@ -215,9 +294,8 @@ keyboard or COM1 serial terminal can provide shell input.
The bob64 build uses a separate header and target. It does not change `bob.exe`,
`bob32.exe`, B16K/B32K images, or the existing resident compiler. Remaining
migration work includes growing the resident C subset, persistent storage,
runtime verification of interrupt-driven devices, USB input, and porting the
rest of the applications.
migration work includes growing the resident C subset, disk-backed persistence,
additional device coverage, USB input, and porting the rest of the applications.
## UEFI runtime test
@@ -226,9 +304,20 @@ serial-checked QEMU/OVMF boot test:
```powershell
.\tools\test_bob64_qemu.ps1 -QemuPath C:\path\to\qemu-system-x86_64.exe `
-OvmfCodePath C:\path\to\edk2-x86_64-code.fd
-OvmfCodePath C:\path\to\edk2-x86_64-code.fd `
-OvmfVarsPath C:\path\to\edk2-x86_64-vars.fd
```
The test waits for long-mode entry, `ExitBootServices`, the ring-3 `bob!` app,
heap checks, and the kernel shell. Manual QEMU testing has also exercised the
resident `cc`/`run` path, B64S save/restore, and the desktop editor.
The test waits for long-mode entry, `ExitBootServices`, ring-3 application and
memory checks, timer and keyboard IRQs, and the kernel shell. It injects a PS/2
mouse move through QEMU's monitor and verifies that a ring-3 app receives the
event. It compiles `bob.c` with the resident compiler, runs the generated app
and checks its `bob!` output and exit status, then saves a file and the compiled
app into B64S firmware storage, resets the VM, and runs the app again after
restore. The C sample verifies a 16-argument call, forty local variables, a
64-element stack array, and local accesses outside the 8-bit frame-offset range.
It opens the desktop Applications
launcher while the editor and file-browser windows remain active, runs the
selected `bob!` app, and checks that the desktop returns to the shell. After
restore, it repeats the GUI launch and child-app round trip using a PS/2 mouse
click on Run App. Broader widget interaction still needs runtime coverage.
+4 -1
View File
@@ -4,7 +4,7 @@
#include "types.h"
#define BOB64_APP_ABI_VERSION 1u
#define BOB64_SYSCALL_ABI_VERSION 10u
#define BOB64_SYSCALL_ABI_VERSION 12u
#define BOB64_SYSCALL_QUERY_ABI 0u
#define BOB64_SYSCALL_WRITE_CHAR 1u
#define BOB64_SYSCALL_WRITE_BUFFER 2u
@@ -26,6 +26,7 @@
#define BOB64_SYSCALL_SEEK_HANDLE 18u
#define BOB64_SYSCALL_CLOSE_HANDLE 19u
#define BOB64_SYSCALL_GET_TICKS 20u
#define BOB64_SYSCALL_RUN_APPLICATION 21u
#define BOB64_FILE_OPEN_READ 0x01u
#define BOB64_FILE_OPEN_WRITE 0x02u
#define BOB64_FILE_OPEN_CREATE 0x04u
@@ -37,6 +38,8 @@
#define BOB64_SYSCALL_MAX_SURFACE_BYTES (16u*1024u*1024u)
#define BOB64_SYSCALL_COPY_CHUNK_BYTES 4096u
#define BOB64_SYSCALL_MAX_FILENAME 63u
#define BOB64_SYSCALL_MAX_ARGUMENTS 16u
#define BOB64_SYSCALL_MAX_ARGUMENT_BYTES 4096u
_Static_assert(BOB64_SYSCALL_MAX_SURFACE_BYTES%sizeof(u32)==0,
"pixel-surface size is a whole number of pixels");
_Static_assert(BOB64_SYSCALL_COPY_CHUNK_BYTES%sizeof(u32)==0,
+68
View File
@@ -145,6 +145,74 @@ static inline s64 bob64_app_file_close(s64 handle) {
return (s64)rax;
}
/* Transfer a whole app file with bounded streaming syscalls. */
static inline s64 bob64_app_file_read_all(const char *name,usize name_length,
void *buffer,usize capacity) {
if((!buffer&&capacity)||capacity>0x7fffffffffffffffULL)return -22;
s64 handle=bob64_app_file_open(name,name_length,BOB64_FILE_OPEN_READ);
if(handle<0)return handle;
usize total=0;
s64 result=0;
while(total<capacity) {
usize chunk=capacity-total;
if(chunk>BOB64_SYSCALL_MAX_BUFFER)chunk=BOB64_SYSCALL_MAX_BUFFER;
s64 count=bob64_app_file_read(handle,(u8 *)buffer+total,chunk);
if(count<0) {result=count;goto close_file;}
if(!count) {result=(s64)total;goto close_file;}
if((u64)count>chunk) {result=-5;goto close_file;}
total+=(usize)count;
}
{
u8 extra;
s64 count=bob64_app_file_read(handle,&extra,1);
result=count<0?count:(count?-28:(s64)total);
}
close_file:
if(bob64_app_file_close(handle)<0&&result>=0)result=-5;
return result;
}
static inline s64 bob64_app_file_write_all(const char *name,usize name_length,
const void *buffer,usize length) {
if((!buffer&&length)||length>0x7fffffffffffffffULL)return -22;
if(length<=BOB64_SYSCALL_MAX_BUFFER)
return bob64_app_write_file(name,name_length,buffer,length);
s64 handle=bob64_app_file_open(name,name_length,
BOB64_FILE_OPEN_WRITE|BOB64_FILE_OPEN_CREATE|BOB64_FILE_OPEN_TRUNCATE);
if(handle<0)return handle;
usize total=0;
s64 result=0;
while(total<length) {
usize chunk=length-total;
if(chunk>BOB64_SYSCALL_MAX_BUFFER)chunk=BOB64_SYSCALL_MAX_BUFFER;
s64 count=bob64_app_file_write(handle,(const u8 *)buffer+total,chunk);
if(count<0) {result=count;goto close_file;}
if(!count||(u64)count>chunk) {result=-5;goto close_file;}
total+=(usize)count;
}
result=(s64)total;
close_file:
if(bob64_app_file_close(handle)<0&&result>=0)result=-5;
return result;
}
/* Run a stored B64E app synchronously and restore this app's syscall context. */
static inline s64 bob64_app_run(const char *name,usize name_length,
usize argument_count,
const char *const *arguments,
s64 *exit_status) {
register u64 rax __asm__("rax")=BOB64_SYSCALL_RUN_APPLICATION;
register u64 rcx __asm__("rcx")=(u64)(uintptr_t)name;
register u64 rdx __asm__("rdx")=(u64)name_length;
register u64 r8 __asm__("r8")=(u64)(uintptr_t)exit_status;
register u64 rsi __asm__("rsi")=(u64)argument_count;
register u64 r9 __asm__("r9")=(u64)(uintptr_t)arguments;
__asm__ volatile("int $0x80":"+a"(rax):"c"(rcx),"d"(rdx),"r"(r8),
"S"(rsi),"r"(r9):
"memory","cc");
return (s64)rax;
}
/* Kernel-owned windows composite app-owned packed RGB pixel surfaces. */
static inline u64 bob64_app_window_create(s32 x,s32 y,u32 width,u32 height) {
register u64 rax __asm__("rax")=BOB64_SYSCALL_CREATE_WINDOW;
+40
View File
@@ -22,6 +22,36 @@ static BOB64_DESCRIPTOR_TABLE_POINTER kernel_gdtr,kernel_idtr;
#ifdef BOB64_ENABLE_HANDOFF
static BOB64_KERNEL_BOOT_INFO kernel_boot_info;
#endif
static int boot_grow_table_pool(void *context,BOB64_BOOTSTRAP_SPACE *space,
u64 *base,u64 *pages) {
BOB64_PAGE_ALLOCATOR *allocator=(BOB64_PAGE_ALLOCATOR *)context;
u64 physical,bytes;
const u64 count=BOB64_BOOTSTRAP_TABLE_GROW_PAGES;
if(!allocator||!space||!base||!pages||count>~(u64)0/BOB64_PAGE_SIZE)
return -1;
bytes=count*BOB64_PAGE_SIZE;
physical=bob64_page_alloc(allocator,count);
if(!physical)return -1;
if(physical>=0x0000800000000000ULL||
bytes>0x0000800000000000ULL-physical||
bob64_page_map_range(&space->PageTable,physical,physical,bytes,
BOB64_PAGE_WRITE|(space->NxSupported?BOB64_PAGE_NX:0))) {
for(u64 offset=0;offset<bytes;offset+=BOB64_PAGE_SIZE) {
u64 translated;
if(bob64_page_translate(&space->PageTable,physical+offset,
&translated,0)==1&&translated==physical+offset) {
(void)bob64_page_unmap(&space->PageTable,physical+offset,0,0);
__asm__ volatile("invlpg (%0)"::"r"((void *)(uintptr_t)(physical+offset)):
"memory");
}
}
(void)bob64_page_free(allocator,physical,count);
return -1;
}
*base=physical;*pages=count;
return 0;
}
static const EFI_GUID loaded_image_guid={0x5b1b31a1u,0x9562u,0x11d2u,
{0x8e,0x3f,0x00,0xa0,0xc9,0x69,0x72,0x3b}};
#ifdef BOB64_ENABLE_HANDOFF
@@ -151,6 +181,15 @@ EFI_STATUS EFIAPI efi_main(EFI_HANDLE image,EFI_SYSTEM_TABLE *system) {
(u64)(uintptr_t)loaded_image->ImageBase,loaded_image->ImageSize,
stack_base,BOB64_BOOT_STACK_PAGES*EFI_PAGE_SIZE,cpu.NX)<0)
return EFI_UNSUPPORTED;
bob64_bootstrap_space_set_table_growth(active_bootstrap_space,
boot_grow_table_pool,
active_page_allocator);
#ifdef BOB64_ENABLE_HANDOFF
u64 runtime_services=(u64)(uintptr_t)system->RuntimeServices;
int runtime_services_mapped=!bob64_bootstrap_map_runtime_services(
active_bootstrap_space,map,(usize)map_size,(usize)descriptor_size,
runtime_services);
#endif
u64 image_base=(u64)(uintptr_t)loaded_image->ImageBase;
u64 map_base=(u64)(uintptr_t)map;
int map_is_in_image=map_base>=image_base&&map_base-image_base<=loaded_image->ImageSize&&
@@ -181,6 +220,7 @@ EFI_STATUS EFIAPI efi_main(EFI_HANDLE image,EFI_SYSTEM_TABLE *system) {
kernel_boot_info.StackSize=BOB64_BOOT_STACK_PAGES*EFI_PAGE_SIZE;
kernel_boot_info.PhysicalAddressBits=cpu.PhysicalAddressBits;
kernel_boot_info.NxSupported=cpu.NX;
kernel_boot_info.RuntimeServices=runtime_services_mapped?runtime_services:0;
if(framebuffer_valid) {
kernel_boot_info.FramebufferBase=graphics_mode->FrameBufferBase;
kernel_boot_info.FramebufferSize=framebuffer_map_size;
+110 -7
View File
@@ -2,17 +2,117 @@
static u64 table_pool_allocate(void *context) {
BOB64_BOOTSTRAP_SPACE *space=(BOB64_BOOTSTRAP_SPACE *)context;
if(!space||space->TablePoolUsed>=space->TablePoolPages)return 0;
return space->TablePoolBase+(space->TablePoolUsed++)*BOB64_PAGE_SIZE;
u64 index;
if(!space)return 0;
if(!space->TablePoolGrowing&&space->TablePoolGrow&&
space->TablePoolPages-space->TablePoolUsed<=
BOB64_BOOTSTRAP_TABLE_GROW_RESERVE&&
space->TablePoolChunkCount<BOB64_BOOTSTRAP_TABLE_CHUNK_LIMIT) {
u64 base=0,pages=0;
space->TablePoolGrowing=1;
int result=space->TablePoolGrow(space->TablePoolGrowContext,space,
&base,&pages);
space->TablePoolGrowing=0;
if(!result&&base&&pages&&!(base&(BOB64_PAGE_SIZE-1))&&
pages<=((~(u64)0-base)/BOB64_PAGE_SIZE)&&
pages<=((~(u64)0-space->TablePoolPages))&&
base<=~(u64)0-pages*BOB64_PAGE_SIZE) {
BOB64_BOOTSTRAP_TABLE_CHUNK *chunk=
&space->TablePoolChunks[space->TablePoolChunkCount++];
chunk->Base=base;chunk->Pages=pages;
space->TablePoolPages+=pages;
}
}
if(space->TablePoolUsed>=space->TablePoolPages)return 0;
index=space->TablePoolUsed++;
if(index<space->TablePoolInitialPages)
return space->TablePoolBase+index*BOB64_PAGE_SIZE;
index-=space->TablePoolInitialPages;
for(usize i=0;i<space->TablePoolChunkCount;i++) {
BOB64_BOOTSTRAP_TABLE_CHUNK *chunk=&space->TablePoolChunks[i];
if(index<chunk->Pages)return chunk->Base+index*BOB64_PAGE_SIZE;
index-=chunk->Pages;
}
space->TablePoolUsed--;
return 0;
}
static u64 *table_pool_access(void *context,u64 physical_address) {
BOB64_BOOTSTRAP_SPACE *space=(BOB64_BOOTSTRAP_SPACE *)context;
if(!space||physical_address<space->TablePoolBase||
(physical_address-space->TablePoolBase)%BOB64_PAGE_SIZE||
(physical_address-space->TablePoolBase)/BOB64_PAGE_SIZE>=space->TablePoolUsed)
return 0;
return space->Access(space->AccessContext,physical_address);
if(!space)return 0;
if(physical_address>=space->TablePoolBase&&
(physical_address-space->TablePoolBase)%BOB64_PAGE_SIZE==0) {
u64 index=(physical_address-space->TablePoolBase)/BOB64_PAGE_SIZE;
if(index<space->TablePoolInitialPages&&index<space->TablePoolUsed)
return space->Access(space->AccessContext,physical_address);
}
u64 index=space->TablePoolInitialPages;
for(usize i=0;i<space->TablePoolChunkCount;i++) {
BOB64_BOOTSTRAP_TABLE_CHUNK *chunk=&space->TablePoolChunks[i];
u64 size=chunk->Pages*BOB64_PAGE_SIZE;
if(physical_address>=chunk->Base&&physical_address-chunk->Base<size&&
(physical_address-chunk->Base)%BOB64_PAGE_SIZE==0) {
u64 page=(physical_address-chunk->Base)/BOB64_PAGE_SIZE;
if(index+page<space->TablePoolUsed)
return space->Access(space->AccessContext,physical_address);
return 0;
}
index+=chunk->Pages;
}
return 0;
}
void bob64_bootstrap_space_set_table_growth(BOB64_BOOTSTRAP_SPACE *space,
BOB64_BOOTSTRAP_TABLE_GROW grow,void *context) {
if(!space)return;
space->TablePoolGrow=grow;space->TablePoolGrowContext=context;
}
int bob64_bootstrap_map_runtime_services(BOB64_BOOTSTRAP_SPACE *space,
const void *memory_map,usize memory_map_size,usize descriptor_size,
u64 runtime_services_address) {
const u8 *bytes=(const u8 *)memory_map;
int runtime_table_in_data=0;
if(!space||!memory_map||!memory_map_size||
descriptor_size<sizeof(EFI_MEMORY_DESCRIPTOR)||
memory_map_size%descriptor_size||!runtime_services_address)return -1;
for(usize offset=0;offset<memory_map_size;offset+=descriptor_size) {
const EFI_MEMORY_DESCRIPTOR *descriptor=
(const EFI_MEMORY_DESCRIPTOR *)(bytes+offset);
u64 base=descriptor->PhysicalStart,pages=descriptor->NumberOfPages,size;
u64 flags;
if(!(descriptor->Attribute&EFI_MEMORY_RUNTIME)||!pages)continue;
if(base&(BOB64_PAGE_SIZE-1)||pages>~(u64)0/BOB64_PAGE_SIZE)return -1;
size=pages*BOB64_PAGE_SIZE;
if(base>~(u64)0-size)return -1;
if(descriptor->Type==EFI_RUNTIME_SERVICES_CODE)
flags=0;
else
flags=BOB64_PAGE_WRITE|(space->NxSupported?BOB64_PAGE_NX:0);
if(descriptor->Type==EFI_MEMORY_MAPPED_IO||
descriptor->Attribute&EFI_MEMORY_UC)
flags|=BOB64_PAGE_PCD|BOB64_PAGE_PWT;
else if(descriptor->Attribute&EFI_MEMORY_WT)
flags|=BOB64_PAGE_PWT;
for(u64 page=0;page<size;page+=BOB64_PAGE_SIZE) {
u64 physical;
int translated=bob64_page_translate(&space->PageTable,base+page,
&physical,0);
if(translated==1) {
if(physical!=base+page||bob64_page_protect(&space->PageTable,
base+page,flags))return -1;
} else if(translated||bob64_page_map(&space->PageTable,base+page,
base+page,flags))return -1;
}
if(descriptor->Type==EFI_RUNTIME_SERVICES_DATA&&
runtime_services_address>=base&&
runtime_services_address-base<size)runtime_table_in_data=1;
}
if(!runtime_table_in_data)return -1;
u64 physical;
return bob64_page_translate(&space->PageTable,runtime_services_address,
&physical,0)==1&&
physical==runtime_services_address?0:-1;
}
int bob64_bootstrap_space_init(BOB64_BOOTSTRAP_SPACE *space,u8 physical_address_bits,
@@ -30,7 +130,10 @@ int bob64_bootstrap_space_init(BOB64_BOOTSTRAP_SPACE *space,u8 physical_address_
pool_bytes=table_pool_pages*BOB64_PAGE_SIZE;
if(table_pool_base>(~(u64)0)-pool_bytes)return BOB64_PAGING_INVALID;
space->TablePoolBase=table_pool_base;space->TablePoolPages=table_pool_pages;
space->TablePoolInitialPages=table_pool_pages;
space->TablePoolUsed=0;space->Access=access;space->AccessContext=access_context;
space->TablePoolChunkCount=0;space->TablePoolGrow=0;
space->TablePoolGrowContext=0;space->TablePoolGrowing=0;
space->NxSupported=nx_supported;
if(bob64_page_table_init(&space->PageTable,physical_address_bits,table_pool_allocate,
table_pool_access,space))return BOB64_PAGING_NO_MEMORY;
+26 -1
View File
@@ -2,16 +2,35 @@
#define BOB64_BOOTSTRAP_H
#include "paging.h"
#include "efi.h"
#define BOB64_BOOTSTRAP_TABLE_CHUNK_LIMIT 64u
#define BOB64_BOOTSTRAP_TABLE_GROW_RESERVE 8ULL
#define BOB64_BOOTSTRAP_TABLE_GROW_PAGES 64ULL
typedef struct BOB64_BOOTSTRAP_SPACE BOB64_BOOTSTRAP_SPACE;
typedef int (*BOB64_BOOTSTRAP_TABLE_GROW)(void *context,
BOB64_BOOTSTRAP_SPACE *space,u64 *base,u64 *pages);
typedef struct {
u64 Base,Pages;
} BOB64_BOOTSTRAP_TABLE_CHUNK;
struct BOB64_BOOTSTRAP_SPACE {
BOB64_PAGE_TABLE PageTable;
u64 TablePoolBase;
u64 TablePoolPages;
u64 TablePoolInitialPages;
u64 TablePoolUsed;
BOB64_BOOTSTRAP_TABLE_CHUNK TablePoolChunks[BOB64_BOOTSTRAP_TABLE_CHUNK_LIMIT];
usize TablePoolChunkCount;
BOB64_BOOTSTRAP_TABLE_GROW TablePoolGrow;
void *TablePoolGrowContext;
u8 TablePoolGrowing;
BOB64_TABLE_ACCESS Access;
void *AccessContext;
u8 NxSupported;
} BOB64_BOOTSTRAP_SPACE;
};
/* Builds identity mappings for the EFI image, replacement stack and table pool. */
int bob64_bootstrap_space_init(BOB64_BOOTSTRAP_SPACE *space,u8 physical_address_bits,
@@ -19,5 +38,11 @@ int bob64_bootstrap_space_init(BOB64_BOOTSTRAP_SPACE *space,u8 physical_address_
u64 table_pool_base,u64 table_pool_pages,
u64 image_base,u64 image_size,
u64 stack_base,u64 stack_size,u8 nx_supported);
void bob64_bootstrap_space_set_table_growth(BOB64_BOOTSTRAP_SPACE *space,
BOB64_BOOTSTRAP_TABLE_GROW grow,void *context);
/* Keep UEFI runtime code/data identity-mapped for post-ExitBootServices use. */
int bob64_bootstrap_map_runtime_services(BOB64_BOOTSTRAP_SPACE *space,
const void *memory_map,usize memory_map_size,usize descriptor_size,
u64 runtime_services_address);
#endif
+398 -227
View File
File diff suppressed because it is too large. Load diff
+6 -3
View File
@@ -4,10 +4,13 @@
#include "exec.h"
#include "paging.h"
#define BOB64_COMPILER_SOURCE_LIMIT 4096u
#define BOB64_COMPILER_IMAGE_LIMIT (BOB64_EXEC_HEADER_SIZE+2u*BOB64_PAGE_SIZE)
#define BOB64_COMPILER_SOURCE_LIMIT (4u*BOB64_PAGE_SIZE)
#define BOB64_COMPILER_CODE_CAPACITY (4u*BOB64_PAGE_SIZE)
#define BOB64_COMPILER_DATA_CAPACITY (4u*BOB64_PAGE_SIZE)
#define BOB64_COMPILER_IMAGE_LIMIT (BOB64_EXEC_HEADER_SIZE+\
BOB64_COMPILER_CODE_CAPACITY+BOB64_COMPILER_DATA_CAPACITY)
/* Compile bob64's initial resident C subset directly to a B64E application. */
/* Compile bob64's bounded resident C subset directly to a B64E application. */
int bob64_compile_c(const char *source,usize source_length,void *output,
usize output_capacity,usize *output_length,
usize *error_offset);
+15 -1
View File
@@ -3,7 +3,7 @@
#include "abi.h"
#define BOB64_EDITOR_CAPACITY BOB64_SYSCALL_MAX_BUFFER
#define BOB64_EDITOR_CAPACITY (4u*BOB64_SYSCALL_MAX_BUFFER)
typedef struct {
char Text[BOB64_EDITOR_CAPACITY+1];
@@ -13,6 +13,15 @@ typedef struct {
u8 Dirty;
} BOB64_EDITOR;
static inline int bob64_editor_is_binary_text(const char *text,usize length) {
if(!text&&length)return 1;
for(usize i=0;i<length;i++) {
u8 value=(u8)text[i];
if(!value||(value<32&&value!='\n'&&value!='\r'&&value!='\t'))return 1;
}
return 0;
}
static inline void bob64_editor_init(BOB64_EDITOR *editor,const char *text,u32 length) {
if(!editor)return;
if(length>BOB64_EDITOR_CAPACITY)length=BOB64_EDITOR_CAPACITY;
@@ -94,6 +103,11 @@ static inline void bob64_editor_handle_key(BOB64_EDITOR *editor,const BOB64_EVEN
else if(event->Key==(BOB64_EVENT_KEY_EXTENDED|0x4d))bob64_editor_move(editor,1);
else if(event->Key==(BOB64_EVENT_KEY_EXTENDED|0x48))bob64_editor_move_vertical(editor,-1);
else if(event->Key==(BOB64_EVENT_KEY_EXTENDED|0x50))bob64_editor_move_vertical(editor,1);
else if(event->Key==(BOB64_EVENT_KEY_EXTENDED|0x47))
while(editor->Cursor&&editor->Text[editor->Cursor-1]!='\n')editor->Cursor--;
else if(event->Key==(BOB64_EVENT_KEY_EXTENDED|0x4f))
while(editor->Cursor<editor->Length&&editor->Text[editor->Cursor]!='\n')
editor->Cursor++;
else if(event->Key==(BOB64_EVENT_KEY_EXTENDED|0x53))bob64_editor_delete(editor);
else if(event->Character=='\b')bob64_editor_backspace(editor);
else if(event->Character=='\n')bob64_editor_insert(editor,'\n');
+39
View File
@@ -12,10 +12,21 @@ typedef void *EFI_HANDLE;
#define EFI_SUCCESS 0ULL
#define EFI_INVALID_PARAMETER 0x8000000000000002ULL
#define EFI_BUFFER_TOO_SMALL 0x8000000000000005ULL
#define EFI_NOT_FOUND 0x800000000000000eULL
#define EFI_OUT_OF_RESOURCES 0x8000000000000009ULL
#define EFI_UNSUPPORTED 0x8000000000000003ULL
#define EFI_ERROR(status) (((EFI_STATUS)(status) >> 63) != 0)
#define EFI_MEMORY_CONVENTIONAL 7u
#define EFI_MEMORY_LOADER_DATA 2u
#define EFI_RUNTIME_SERVICES_CODE 5u
#define EFI_RUNTIME_SERVICES_DATA 6u
#define EFI_MEMORY_MAPPED_IO 11u
#define EFI_MEMORY_UC 0x0000000000000001ULL
#define EFI_MEMORY_WT 0x0000000000000004ULL
#define EFI_MEMORY_RUNTIME 0x8000000000000000ULL
#define EFI_VARIABLE_NON_VOLATILE 0x00000001u
#define EFI_VARIABLE_BOOTSERVICE_ACCESS 0x00000002u
#define EFI_VARIABLE_RUNTIME_ACCESS 0x00000004u
#define EFI_PAGE_SIZE 4096ULL
typedef struct {
@@ -48,6 +59,30 @@ typedef EFI_STATUS (EFIAPI *EFI_HANDLE_PROTOCOL)(EFI_HANDLE,const EFI_GUID *,voi
typedef EFI_STATUS (EFIAPI *EFI_EXIT_BOOT_SERVICES)(EFI_HANDLE,UINTN);
typedef EFI_STATUS (EFIAPI *EFI_LOCATE_PROTOCOL)(const EFI_GUID *,void *,void **);
typedef EFI_STATUS (EFIAPI *EFI_GET_VARIABLE)(const CHAR16 *,const EFI_GUID *,
u32 *,UINTN *,void *);
typedef EFI_STATUS (EFIAPI *EFI_SET_VARIABLE)(const CHAR16 *,const EFI_GUID *,
u32,UINTN,const void *);
typedef EFI_STATUS (EFIAPI *EFI_QUERY_VARIABLE_INFO)(u32,UINTN *,UINTN *,UINTN *);
typedef struct {
EFI_TABLE_HEADER Hdr;
void *GetTime;
void *SetTime;
void *GetWakeupTime;
void *SetWakeupTime;
void *SetVirtualAddressMap;
void *ConvertPointer;
EFI_GET_VARIABLE GetVariable;
void *GetNextVariableName;
EFI_SET_VARIABLE SetVariable;
void *GetNextHighMonotonicCount;
void *ResetSystem;
void *UpdateCapsule;
void *QueryCapsuleCapabilities;
EFI_QUERY_VARIABLE_INFO QueryVariableInfo;
} EFI_RUNTIME_SERVICES;
typedef struct {
EFI_TABLE_HEADER Hdr;
void *RaiseTPL;
@@ -170,6 +205,10 @@ _Static_assert(__builtin_offsetof(EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL,OutputString)=
_Static_assert(__builtin_offsetof(EFI_SYSTEM_TABLE,ConOut)==64,
"UEFI x64 system table layout mismatch");
_Static_assert(sizeof(EFI_SYSTEM_TABLE)==120,"UEFI x64 system table size mismatch");
_Static_assert(__builtin_offsetof(EFI_RUNTIME_SERVICES,GetVariable)==72&&
__builtin_offsetof(EFI_RUNTIME_SERVICES,SetVariable)==88&&
sizeof(EFI_RUNTIME_SERVICES)==136,
"UEFI x64 runtime-services table layout mismatch");
_Static_assert(sizeof(EFI_MEMORY_DESCRIPTOR)==40,"UEFI x64 memory descriptor layout mismatch");
_Static_assert(__builtin_offsetof(EFI_BOOT_SERVICES,GetMemoryMap)==56,
"UEFI x64 boot services layout mismatch");
+54
View File
@@ -11,12 +11,66 @@ bob64_embedded_app:
.incbin "build/bob64-app/smoke.b64e"
bob64_embedded_app_end:
.balign 16
.globl bob64_embedded_display
.globl bob64_embedded_display_end
bob64_embedded_display:
.incbin "build/bob64-app/display.b64e"
bob64_embedded_display_end:
.balign 16
.globl bob64_embedded_gui
.globl bob64_embedded_gui_end
bob64_embedded_gui:
.incbin "build/bob64-app/gui.b64e"
bob64_embedded_gui_end:
.balign 16
.globl bob64_embedded_nested_app
.globl bob64_embedded_nested_app_end
bob64_embedded_nested_app:
.incbin "build/bob64-app/nested-smoke.b64e"
bob64_embedded_nested_app_end:
.balign 16
.globl bob64_embedded_echo
.globl bob64_embedded_echo_end
bob64_embedded_echo:
.incbin "build/bob64-app/echo.b64e"
bob64_embedded_echo_end:
.balign 16
.globl bob64_embedded_ls
.globl bob64_embedded_ls_end
bob64_embedded_ls:
.incbin "build/bob64-app/ls.b64e"
bob64_embedded_ls_end:
.balign 16
.globl bob64_embedded_cat
.globl bob64_embedded_cat_end
bob64_embedded_cat:
.incbin "build/bob64-app/cat.b64e"
bob64_embedded_cat_end:
.balign 16
.globl bob64_embedded_notes
.globl bob64_embedded_notes_end
bob64_embedded_notes:
.incbin "build/bob64-app/notes.b64e"
bob64_embedded_notes_end:
.balign 16
.globl bob64_embedded_info
.globl bob64_embedded_info_end
bob64_embedded_info:
.incbin "build/bob64-app/info.b64e"
bob64_embedded_info_end:
.balign 16
.globl bob64_embedded_mouse_smoke
.globl bob64_embedded_mouse_smoke_end
bob64_embedded_mouse_smoke:
.incbin "build/bob64-app/mouse-smoke.b64e"
bob64_embedded_mouse_smoke_end:
.balign 16
.globl bob64_embedded_launcher
.globl bob64_embedded_launcher_end
bob64_embedded_launcher:
.incbin "build/bob64-app/launcher.b64e"
bob64_embedded_launcher_end:
.balign 16
.globl bob64_embedded_source
.globl bob64_embedded_source_end
bob64_embedded_source:
+346
View File
@@ -0,0 +1,346 @@
#include "firmware_store.h"
#include "heap.h"
#include "lz4.h"
#include "snapshot.h"
#define BOB64_FIRMWARE_SNAPSHOT_VERSION 2u
#define BOB64_FIRMWARE_LEGACY_VERSION 1u
#define BOB64_FIRMWARE_SNAPSHOT_ATTRIBUTES (EFI_VARIABLE_NON_VOLATILE|\
EFI_VARIABLE_BOOTSERVICE_ACCESS|EFI_VARIABLE_RUNTIME_ACCESS)
#define BOB64_FIRMWARE_SNAPSHOT_RAW_LIMIT (32u*1024u*1024u)
#define BOB64_FIRMWARE_CHUNK_SIZE 30720u
#define BOB64_FIRMWARE_CHUNK_COUNT 2u
#define BOB64_FIRMWARE_MANIFEST_SIZE 32u
#define BOB64_FIRMWARE_ACTIVE_SIZE 16u
static const EFI_GUID firmware_snapshot_guid={0x8b7a4c21u,0x6c34u,0x4f09u,
{0x92,0x6d,0x42,0x6f,0x62,0x36,0x34,0x01}};
static const CHAR16 firmware_legacy_name[]={
'B','o','b','6','4','S','n','a','p','s','h','o','t',0
};
static const CHAR16 firmware_manifest_names[2][14]={
{'B','o','b','6','4','S','l','o','t','A',0},
{'B','o','b','6','4','S','l','o','t','B',0}
};
static const CHAR16 firmware_chunk_names[2][2][16]={
{{'B','o','b','6','4','D','a','t','a','A','0',0},
{'B','o','b','6','4','D','a','t','a','A','1',0}},
{{'B','o','b','6','4','D','a','t','a','B','0',0},
{'B','o','b','6','4','D','a','t','a','B','1',0}}
};
static const CHAR16 firmware_active_name[]={
'B','o','b','6','4','A','c','t','i','v','e',0
};
static void write32(u8 *bytes,u32 value) {
for(u32 i=0;i<4;i++)bytes[i]=(u8)(value>>(i*8));
}
static void write64(u8 *bytes,u64 value) {
write32(bytes,(u32)value);write32(bytes+4,(u32)(value>>32));
}
static u32 read32(const u8 *bytes) {
return (u32)bytes[0]|((u32)bytes[1]<<8)|((u32)bytes[2]<<16)|
((u32)bytes[3]<<24);
}
static u64 read64(const u8 *bytes) {
return (u64)read32(bytes)|((u64)read32(bytes+4)<<32);
}
static u32 crc32(const u8 *bytes,usize length) {
u32 value=0xffffffffu;
for(usize i=0;i<length;i++) {
value^=bytes[i];
for(u32 bit=0;bit<8;bit++)
value=(value>>1)^(0xedb88320u&-(value&1u));
}
return ~value;
}
static EFI_STATUS call_set_variable(EFI_RUNTIME_SERVICES *services,
const CHAR16 *name,const void *data,usize size,u32 attributes) {
EFI_STATUS status;
#ifdef BOB64_UEFI_ABI
u64 flags;
__asm__ volatile("pushfq; pop %0; cli":"=r"(flags)::"memory");
#endif
status=services->SetVariable(name,&firmware_snapshot_guid,attributes,
(UINTN)size,data);
#ifdef BOB64_UEFI_ABI
if(flags&(1ull<<9))__asm__ volatile("sti" ::: "memory");
#endif
return status;
}
static EFI_STATUS call_get_variable(EFI_RUNTIME_SERVICES *services,
const CHAR16 *name,UINTN *size,void *data,u32 *attributes) {
EFI_STATUS status;
#ifdef BOB64_UEFI_ABI
u64 flags;
__asm__ volatile("pushfq; pop %0; cli":"=r"(flags)::"memory");
#endif
status=services->GetVariable(name,&firmware_snapshot_guid,attributes,size,data);
#ifdef BOB64_UEFI_ABI
if(flags&(1ull<<9))__asm__ volatile("sti" ::: "memory");
#endif
return status;
}
static EFI_STATUS query_variable_capacity(EFI_RUNTIME_SERVICES *services,
UINTN required,UINTN *maximum_variable_size,
UINTN *remaining_storage_size) {
UINTN maximum_storage=0,remaining_storage=0,maximum_variable=0;
EFI_STATUS status;
if(maximum_variable_size)*maximum_variable_size=0;
if(remaining_storage_size)*remaining_storage_size=0;
if(!services->QueryVariableInfo)return EFI_SUCCESS;
#ifdef BOB64_UEFI_ABI
u64 flags;
__asm__ volatile("pushfq; pop %0; cli":"=r"(flags)::"memory");
#endif
status=services->QueryVariableInfo(BOB64_FIRMWARE_SNAPSHOT_ATTRIBUTES,
&maximum_storage,&remaining_storage,&maximum_variable);
#ifdef BOB64_UEFI_ABI
if(flags&(1ull<<9))__asm__ volatile("sti" ::: "memory");
#endif
if(maximum_variable_size)*maximum_variable_size=maximum_variable;
if(remaining_storage_size)*remaining_storage_size=remaining_storage;
(void)maximum_storage;
if(status==EFI_UNSUPPORTED)return EFI_SUCCESS;
if(EFI_ERROR(status))return status;
return required<=maximum_variable?EFI_SUCCESS:EFI_OUT_OF_RESOURCES;
}
static int load_variable(EFI_RUNTIME_SERVICES *services,const CHAR16 *name,
BOB64_HEAP *heap,u8 **data,usize *size) {
UINTN variable_size=0,actual_size;
u32 attributes=0;
u8 *buffer;
EFI_STATUS status;
if(data)*data=0;
if(size)*size=0;
if(!services||!services->GetVariable||!heap||!data||!size)return -1;
status=call_get_variable(services,name,&variable_size,0,&attributes);
if(status==EFI_NOT_FOUND)return BOB64_FIRMWARE_SNAPSHOT_NOT_FOUND;
if(status!=EFI_BUFFER_TOO_SMALL||!variable_size||
variable_size>BOB64_FIRMWARE_SNAPSHOT_LIMIT)return -1;
buffer=(u8 *)bob64_heap_alloc(heap,(usize)variable_size);
if(!buffer)return -1;
actual_size=variable_size;
status=call_get_variable(services,name,&actual_size,buffer,&attributes);
if(EFI_ERROR(status)||actual_size!=variable_size||
(attributes&BOB64_FIRMWARE_SNAPSHOT_ATTRIBUTES)!=
BOB64_FIRMWARE_SNAPSHOT_ATTRIBUTES) {
bob64_heap_free(heap,buffer);return -1;
}
*data=buffer;*size=(usize)variable_size;
return 0;
}
static EFI_STATUS delete_variable(EFI_RUNTIME_SERVICES *services,
const CHAR16 *name) {
EFI_STATUS status=call_set_variable(services,name,0,0,0);
return status==EFI_NOT_FOUND?EFI_SUCCESS:status;
}
static int variable_present(EFI_RUNTIME_SERVICES *services,const CHAR16 *name,
BOB64_HEAP *heap) {
u8 *data=0;usize size=0;
int result=load_variable(services,name,heap,&data,&size);
if(data)bob64_heap_free(heap,data);
return result!=BOB64_FIRMWARE_SNAPSHOT_NOT_FOUND;
}
static int read_active_slot(EFI_RUNTIME_SERVICES *services,BOB64_HEAP *heap,
u32 *slot) {
u8 *data=0;usize size=0;
int result=load_variable(services,firmware_active_name,heap,&data,&size);
if(result==BOB64_FIRMWARE_SNAPSHOT_NOT_FOUND)return 0;
if(result||size!=BOB64_FIRMWARE_ACTIVE_SIZE||data[0]!='B'||data[1]!='6'||
data[2]!='4'||data[3]!='A'||read32(data+4)!=1||
read32(data+8)>1||read32(data+12)!=crc32(data,12))result=-1;
else {*slot=read32(data+8);result=1;}
if(data)bob64_heap_free(heap,data);
return result;
}
static int restore_compressed(BOB64_FILESYSTEM *filesystem,const u8 *compressed,
usize compressed_size,u64 raw_size) {
u8 *raw;
int result=-1;
if(!raw_size||raw_size>BOB64_FIRMWARE_SNAPSHOT_RAW_LIMIT||
raw_size>~(usize)0||compressed_size>~(usize)0)return -1;
raw=(u8 *)bob64_heap_alloc(filesystem->Heap,(usize)raw_size);
if(!raw)return -1;
if(!bob64_lz4_decompress(compressed,compressed_size,raw,(usize)raw_size,
(usize)raw_size)&&
!bob64_fs_snapshot_restore(filesystem,raw,(usize)raw_size))result=0;
bob64_heap_free(filesystem->Heap,raw);
return result;
}
static int restore_slot(EFI_RUNTIME_SERVICES *services,
BOB64_FILESYSTEM *filesystem,u32 slot) {
BOB64_HEAP *heap=filesystem->Heap;
u8 *manifest=0,*compressed=0;
usize manifest_size=0;
u64 raw_size,compressed_size;
u32 chunks,checksum;
usize offset=0;
int loaded=load_variable(services,firmware_manifest_names[slot],heap,
&manifest,&manifest_size);
if(loaded)return loaded;
loaded=-1;
if(manifest_size!=BOB64_FIRMWARE_MANIFEST_SIZE||manifest[0]!='B'||
manifest[1]!='6'||manifest[2]!='4'||manifest[3]!='C'||
read32(manifest+4)!=BOB64_FIRMWARE_SNAPSHOT_VERSION)goto done;
raw_size=read64(manifest+8);compressed_size=read64(manifest+16);
checksum=read32(manifest+24);chunks=read32(manifest+28);
if(!raw_size||raw_size>BOB64_FIRMWARE_SNAPSHOT_RAW_LIMIT||
!compressed_size||compressed_size>BOB64_FIRMWARE_SNAPSHOT_LIMIT||
chunks!=(compressed_size+BOB64_FIRMWARE_CHUNK_SIZE-1)/
BOB64_FIRMWARE_CHUNK_SIZE||
!chunks||chunks>BOB64_FIRMWARE_CHUNK_COUNT||
compressed_size>~(usize)0)goto done;
compressed=(u8 *)bob64_heap_alloc(heap,(usize)compressed_size);
if(!compressed)goto done;
for(u32 i=0;i<chunks;i++) {
u8 *chunk=0;usize chunk_size=0;
usize expected=(usize)compressed_size-offset;
if(expected>BOB64_FIRMWARE_CHUNK_SIZE)
expected=BOB64_FIRMWARE_CHUNK_SIZE;
if(load_variable(services,firmware_chunk_names[slot][i],heap,
&chunk,&chunk_size)||chunk_size!=expected) {
if(chunk)bob64_heap_free(heap,chunk);
goto done;
}
for(usize j=0;j<chunk_size;j++)compressed[offset+j]=chunk[j];
offset+=chunk_size;
bob64_heap_free(heap,chunk);
}
if(offset!=(usize)compressed_size||crc32(compressed,offset)!=checksum)goto done;
loaded=restore_compressed(filesystem,compressed,offset,raw_size);
done:
if(compressed)bob64_heap_free(heap,compressed);
if(manifest)bob64_heap_free(heap,manifest);
return loaded;
}
static int restore_legacy(EFI_RUNTIME_SERVICES *services,
BOB64_FILESYSTEM *filesystem) {
BOB64_HEAP *heap=filesystem->Heap;
u8 *blob=0;
usize blob_size=0;
u64 raw_size,compressed_size;
int result=load_variable(services,firmware_legacy_name,heap,&blob,&blob_size);
if(result)return result;
if(blob_size<24||blob[0]!='B'||blob[1]!='6'||blob[2]!='4'||blob[3]!='C'||
read32(blob+4)!=BOB64_FIRMWARE_LEGACY_VERSION)result=-1;
else {
raw_size=read64(blob+8);compressed_size=read64(blob+16);
if(compressed_size!=blob_size-24||
compressed_size>~(usize)0)result=-1;
else result=restore_compressed(filesystem,blob+24,
(usize)compressed_size,raw_size);
}
bob64_heap_free(heap,blob);
return result;
}
int bob64_firmware_snapshot_save(EFI_RUNTIME_SERVICES *services,
BOB64_HEAP *heap,const void *snapshot,usize snapshot_size,
EFI_STATUS *firmware_status,UINTN *maximum_variable_size,
UINTN *remaining_storage_size) {
usize compressed_capacity,compressed_size=0,offset=0;
const u8 *raw=(const u8 *)snapshot;
u8 *compressed=0,*workspace=0;
u8 manifest[BOB64_FIRMWARE_MANIFEST_SIZE];
u8 active[BOB64_FIRMWARE_ACTIVE_SIZE]={0};
EFI_STATUS status=EFI_INVALID_PARAMETER;
u32 active_slot=0,target_slot,chunks;
int result=-1;
if(firmware_status)*firmware_status=status;
if(maximum_variable_size)*maximum_variable_size=0;
if(remaining_storage_size)*remaining_storage_size=0;
if(!services||!services->SetVariable||!heap||!raw||!snapshot_size||
snapshot_size>BOB64_FIRMWARE_SNAPSHOT_RAW_LIMIT)return -1;
compressed_capacity=bob64_lz4_compress_bound(snapshot_size);
if(!compressed_capacity)return -1;
status=EFI_OUT_OF_RESOURCES;
compressed=(u8 *)bob64_heap_alloc(heap,compressed_capacity);
workspace=(u8 *)bob64_heap_alloc(heap,BOB64_LZ4_WORKSPACE_SIZE);
if(!compressed||!workspace||bob64_lz4_compress(raw,snapshot_size,
compressed,compressed_capacity,&compressed_size,workspace,
BOB64_LZ4_WORKSPACE_SIZE))goto done;
if(!compressed_size||compressed_size>BOB64_FIRMWARE_SNAPSHOT_LIMIT)goto done;
chunks=(u32)((compressed_size+BOB64_FIRMWARE_CHUNK_SIZE-1)/
BOB64_FIRMWARE_CHUNK_SIZE);
if(!chunks||chunks>BOB64_FIRMWARE_CHUNK_COUNT)goto done;
usize largest_chunk=compressed_size>BOB64_FIRMWARE_CHUNK_SIZE?
BOB64_FIRMWARE_CHUNK_SIZE:compressed_size;
status=query_variable_capacity(services,(UINTN)largest_chunk,
maximum_variable_size,remaining_storage_size);
if(EFI_ERROR(status))goto done;
int active_result=read_active_slot(services,heap,&active_slot);
if(active_result==1)target_slot=active_slot^1u;
else target_slot=variable_present(services,firmware_manifest_names[0],heap)?1u:0u;
status=delete_variable(services,firmware_manifest_names[target_slot]);
if(EFI_ERROR(status))goto done;
for(u32 i=0;i<BOB64_FIRMWARE_CHUNK_COUNT;i++) {
status=delete_variable(services,firmware_chunk_names[target_slot][i]);
if(EFI_ERROR(status))goto done;
}
for(u32 i=0;i<chunks;i++) {
usize chunk_size=compressed_size-offset;
if(chunk_size>BOB64_FIRMWARE_CHUNK_SIZE)
chunk_size=BOB64_FIRMWARE_CHUNK_SIZE;
status=call_set_variable(services,firmware_chunk_names[target_slot][i],
compressed+offset,chunk_size,BOB64_FIRMWARE_SNAPSHOT_ATTRIBUTES);
if(EFI_ERROR(status))goto done;
offset+=chunk_size;
}
manifest[0]='B';manifest[1]='6';manifest[2]='4';manifest[3]='C';
write32(manifest+4,BOB64_FIRMWARE_SNAPSHOT_VERSION);
write64(manifest+8,snapshot_size);write64(manifest+16,compressed_size);
write32(manifest+24,crc32(compressed,compressed_size));
write32(manifest+28,chunks);
status=call_set_variable(services,firmware_manifest_names[target_slot],
manifest,sizeof(manifest),BOB64_FIRMWARE_SNAPSHOT_ATTRIBUTES);
if(EFI_ERROR(status))goto done;
active[0]='B';active[1]='6';active[2]='4';active[3]='A';
write32(active+4,1);write32(active+8,target_slot);
write32(active+12,crc32(active,12));
status=call_set_variable(services,firmware_active_name,active,sizeof(active),
BOB64_FIRMWARE_SNAPSHOT_ATTRIBUTES);
if(EFI_ERROR(status))goto done;
/* The new slot is committed; the obsolete v1 variable can now be reclaimed. */
(void)delete_variable(services,firmware_legacy_name);
result=0;
done:
if(firmware_status)*firmware_status=status;
if(workspace)bob64_heap_free(heap,workspace);
if(compressed)bob64_heap_free(heap,compressed);
return result;
}
int bob64_firmware_snapshot_restore(EFI_RUNTIME_SERVICES *services,
BOB64_FILESYSTEM *filesystem) {
u32 active_slot=0;
int active_result,slot_result,present=0;
if(!services||!services->GetVariable)
return BOB64_FIRMWARE_SNAPSHOT_NOT_FOUND;
if(!filesystem||!filesystem->Heap)return -1;
active_result=read_active_slot(services,filesystem->Heap,&active_slot);
for(u32 i=0;i<2;i++) {
u32 slot=active_result==1?(i?active_slot^1u:active_slot):i;
slot_result=restore_slot(services,filesystem,slot);
if(!slot_result)return 0;
if(slot_result!=BOB64_FIRMWARE_SNAPSHOT_NOT_FOUND)present=1;
}
slot_result=restore_legacy(services,filesystem);
if(!slot_result)return 0;
if(slot_result!=BOB64_FIRMWARE_SNAPSHOT_NOT_FOUND)present=1;
return present?-1:BOB64_FIRMWARE_SNAPSHOT_NOT_FOUND;
}
+20
View File
@@ -0,0 +1,20 @@
#ifndef BOB64_FIRMWARE_STORE_H
#define BOB64_FIRMWARE_STORE_H
#include "efi.h"
#include "filesystem.h"
#include "heap.h"
#define BOB64_FIRMWARE_SNAPSHOT_LIMIT 61440u
#define BOB64_FIRMWARE_SNAPSHOT_HEADER_SIZE 24u
#define BOB64_FIRMWARE_SNAPSHOT_NOT_FOUND 1
int bob64_firmware_snapshot_save(EFI_RUNTIME_SERVICES *services,BOB64_HEAP *heap,
const void *snapshot,usize snapshot_size,
EFI_STATUS *firmware_status,
UINTN *maximum_variable_size,
UINTN *remaining_storage_size);
int bob64_firmware_snapshot_restore(EFI_RUNTIME_SERVICES *services,
BOB64_FILESYSTEM *filesystem);
#endif
+5 -1
View File
@@ -10,10 +10,14 @@ typedef struct {
usize Capacity;
} BOB64_GFX;
#define BOB64_GFX_MAX_WIDTH 1280u
#define BOB64_GFX_MAX_HEIGHT 800u
static inline int bob64_gfx_init(BOB64_GFX *graphics,u32 *pixels,usize capacity) {
u32 width,height;
if(!graphics||!pixels||bob64_app_get_display(&width,&height)||!width||!height||
(u64)width*height>capacity||width>1024||height>768)return -1;
(u64)width*height>capacity||width>BOB64_GFX_MAX_WIDTH||
height>BOB64_GFX_MAX_HEIGHT)return -1;
graphics->Pixels=pixels;graphics->Width=width;graphics->Height=height;
graphics->Capacity=capacity;
return 0;
+68 -6
View File
@@ -4,6 +4,25 @@
#define BOB64_HEAP_ALIGNMENT 16u
#define BOB64_HEAP_MINIMUM_REGION 4096u
static u64 heap_lock(BOB64_HEAP *heap) {
u64 flags=0;
#ifdef BOB64_UEFI_ABI
__asm__ volatile("pushfq; pop %0; cli":"=r"(flags)::"memory");
#endif
while(__atomic_exchange_n(&heap->Lock,1,__ATOMIC_ACQUIRE))
__asm__ volatile("pause" ::: "memory");
return flags;
}
static void heap_unlock(BOB64_HEAP *heap,u64 flags) {
__atomic_store_n(&heap->Lock,0,__ATOMIC_RELEASE);
#ifdef BOB64_UEFI_ABI
if(flags&(1ull<<9))__asm__ volatile("sti" ::: "memory");
#else
(void)flags;
#endif
}
static int align_size(usize value,usize *aligned) {
if(value>~(usize)0-(BOB64_HEAP_ALIGNMENT-1))return 0;
*aligned=(value+(BOB64_HEAP_ALIGNMENT-1))&~(usize)(BOB64_HEAP_ALIGNMENT-1);
@@ -25,10 +44,20 @@ int bob64_heap_init(BOB64_HEAP *heap,usize maximum_bytes,
BOB64_HEAP_GROW grow,void *context) {
if(!heap||!grow||maximum_bytes<BOB64_HEAP_MINIMUM_REGION)return -1;
heap->First=0;heap->Last=0;heap->Grow=grow;heap->Context=context;
heap->Shrink=0;
heap->Base=0;heap->MappedBytes=0;heap->MaximumBytes=maximum_bytes;
__atomic_store_n(&heap->Lock,0,__ATOMIC_RELAXED);
return 0;
}
void bob64_heap_set_shrink(BOB64_HEAP *heap,BOB64_HEAP_SHRINK shrink) {
if(heap) {
u64 flags=heap_lock(heap);
heap->Shrink=shrink;
heap_unlock(heap,flags);
}
}
static BOB64_HEAP_BLOCK *find_block(BOB64_HEAP *heap,usize size) {
for(BOB64_HEAP_BLOCK *block=heap->First;block;block=block->Next)
if(block->Magic==BOB64_HEAP_BLOCK_MAGIC&&block->Free&&block->Size>=size)
@@ -61,11 +90,31 @@ static int grow_heap(BOB64_HEAP *heap) {
return 0;
}
static void shrink_heap_tail(BOB64_HEAP *heap) {
usize bytes,maximum;
void *region;
if(!heap||!heap->Shrink||!heap->Last||!heap->Last->Free||
heap->MappedBytes<=BOB64_HEAP_MINIMUM_REGION)return;
bytes=heap->Last->Size&~(usize)(BOB64_HEAP_MINIMUM_REGION-1);
maximum=(heap->MappedBytes-BOB64_HEAP_MINIMUM_REGION)&
~(usize)(BOB64_HEAP_MINIMUM_REGION-1);
if(bytes>maximum)bytes=maximum;
if(!bytes)return;
region=(u8 *)heap->Base+heap->MappedBytes-bytes;
if(heap->Shrink(heap->Context,region,bytes))return;
heap->Last->Size-=bytes;
heap->MappedBytes-=bytes;
}
void *bob64_heap_alloc(BOB64_HEAP *heap,usize size) {
usize aligned;
if(!heap||!heap->Grow||!size||!align_size(size,&aligned))return 0;
u64 flags=heap_lock(heap);
BOB64_HEAP_BLOCK *block;
while(!(block=find_block(heap,aligned)))if(grow_heap(heap))return 0;
while(!(block=find_block(heap,aligned)))if(grow_heap(heap)) {
heap_unlock(heap,flags);
return 0;
}
if(block->Size>=sizeof(*block)+BOB64_HEAP_ALIGNMENT&&
aligned<=block->Size-sizeof(*block)-BOB64_HEAP_ALIGNMENT) {
BOB64_HEAP_BLOCK *remainder=(BOB64_HEAP_BLOCK *)((u8 *)(block+1)+aligned);
@@ -78,6 +127,7 @@ void *bob64_heap_alloc(BOB64_HEAP *heap,usize size) {
block->Next=remainder;block->Size=aligned;
}
block->Free=0;
heap_unlock(heap,flags);
return block+1;
}
@@ -96,15 +146,20 @@ void *bob64_heap_calloc(BOB64_HEAP *heap,usize count,usize size) {
int bob64_heap_free(BOB64_HEAP *heap,void *pointer) {
uintptr_t address=(uintptr_t)pointer,base,end;
BOB64_HEAP_BLOCK *block;
if(!heap||!pointer||!heap->Base||(address&(BOB64_HEAP_ALIGNMENT-1)))return -1;
if(!heap||!pointer||(address&(BOB64_HEAP_ALIGNMENT-1)))return -1;
u64 flags=heap_lock(heap);
if(!heap->Base) {heap_unlock(heap,flags);return -1;}
base=(uintptr_t)heap->Base;
if(heap->MappedBytes>~(uintptr_t)0-base)return -1;
if(heap->MappedBytes>~(uintptr_t)0-base) {heap_unlock(heap,flags);return -1;}
end=base+heap->MappedBytes;
if(address<base+sizeof(*block)||address>=end)return -1;
if(address<base+sizeof(*block)||address>=end) {heap_unlock(heap,flags);return -1;}
block=(BOB64_HEAP_BLOCK *)pointer-1;
if((uintptr_t)block<base||(uintptr_t)block+sizeof(*block)>end||
block->Magic!=BOB64_HEAP_BLOCK_MAGIC||block->Free||
block->Size>(usize)(end-(uintptr_t)(block+1)))return -1;
block->Size>(usize)(end-(uintptr_t)(block+1))) {
heap_unlock(heap,flags);
return -1;
}
block->Free=1;
if(block->Next&&block->Next->Magic==BOB64_HEAP_BLOCK_MAGIC&&block->Next->Free) {
BOB64_HEAP_BLOCK *next=block->Next;
@@ -120,9 +175,16 @@ int bob64_heap_free(BOB64_HEAP *heap,void *pointer) {
else heap->Last=previous;
block->Magic=0;
}
shrink_heap_tail(heap);
heap_unlock(heap,flags);
return 0;
}
usize bob64_heap_mapped_bytes(const BOB64_HEAP *heap) {
return heap?heap->MappedBytes:0;
usize result;
if(!heap)return 0;
u64 flags=heap_lock((BOB64_HEAP *)heap);
result=heap->MappedBytes;
heap_unlock((BOB64_HEAP *)heap,flags);
return result;
}
+5
View File
@@ -4,6 +4,8 @@
#include "types.h"
typedef int (*BOB64_HEAP_GROW)(void *context,void **region,usize *region_size);
/* Release a page-aligned tail region; return zero only after it is unmapped. */
typedef int (*BOB64_HEAP_SHRINK)(void *context,void *region,usize region_size);
typedef struct BOB64_HEAP_BLOCK BOB64_HEAP_BLOCK;
struct BOB64_HEAP_BLOCK {
@@ -17,13 +19,16 @@ struct BOB64_HEAP_BLOCK {
typedef struct {
BOB64_HEAP_BLOCK *First,*Last;
BOB64_HEAP_GROW Grow;
BOB64_HEAP_SHRINK Shrink;
void *Context;
void *Base;
usize MappedBytes,MaximumBytes;
u32 Lock;
} BOB64_HEAP;
int bob64_heap_init(BOB64_HEAP *heap,usize maximum_bytes,
BOB64_HEAP_GROW grow,void *context);
void bob64_heap_set_shrink(BOB64_HEAP *heap,BOB64_HEAP_SHRINK shrink);
void *bob64_heap_alloc(BOB64_HEAP *heap,usize size);
void *bob64_heap_calloc(BOB64_HEAP *heap,usize count,usize size);
int bob64_heap_free(BOB64_HEAP *heap,void *pointer);
+440 -12
View File
@@ -12,6 +12,7 @@
#include "process.h"
#include "syscall.h"
#include "compiler.h"
#include "firmware_store.h"
#define BOB64_KERNEL_HEAP_BASE 0xffff900000000000ULL
#define BOB64_KERNEL_HEAP_LIMIT (64ULL*1024ULL*1024ULL)
@@ -27,11 +28,24 @@ typedef struct {
} KERNEL_APP_CONTEXT;
static KERNEL_APP_CONTEXT kernel_app_context;
static usize kernel_heap_mapped;
static usize kernel_heap_high_water;
static void *kernel_privilege_stack;
static char kernel_user_output[5];
static char kernel_user_output[1024];
static usize kernel_user_output_length;
static u8 kernel_user_output_truncated;
static u8 kernel_compiler_output[BOB64_COMPILER_IMAGE_LIMIT];
static void kernel_write(const char *text);
static void kernel_hex64(u64 value);
static int kernel_text_contains(const char *text,const char *needle) {
if(!text||!needle)return 0;
for(usize i=0;text[i];i++) {
usize j=0;
while(needle[j]&&text[i+j]&&text[i+j]==needle[j])j++;
if(!needle[j])return 1;
}
return 0;
}
static int kernel_interrupts_enabled(void) {
u64 flags;
@@ -39,6 +53,13 @@ static int kernel_interrupts_enabled(void) {
return (flags&0x200)!=0;
}
static void kernel_user_write_character(void *context,u8 character);
static s64 kernel_run_application(void *context,const char *name,
usize argument_count,
const char *const *arguments,int *started);
static int kernel_app_run_application(void *context,const char *name,
usize argument_count,
const char *const *arguments,
s64 *exit_status);
static int kernel_copy_user_bytes(void *context,u64 address,void *destination,
usize length);
static int kernel_process_fault_smoke_test(BOB64_PROCESS *process,
@@ -46,10 +67,31 @@ static int kernel_process_fault_smoke_test(BOB64_PROCESS *process,
const u8 *executable,usize executable_size,u64 expected_rip,u64 error_mask,
u64 error_value,const char *success_message);
static int kernel_wait_for_input_event(void *context,BOB64_EVENT *event);
static int kernel_snapshot_save(void *context,const void *snapshot,
usize snapshot_size);
static int kernel_snapshot_restore(void *context,BOB64_FILESYSTEM *filesystem);
extern const u8 bob64_embedded_app[];
extern const u8 bob64_embedded_app_end[];
extern const u8 bob64_embedded_display[];
extern const u8 bob64_embedded_display_end[];
extern const u8 bob64_embedded_gui[];
extern const u8 bob64_embedded_gui_end[];
extern const u8 bob64_embedded_nested_app[];
extern const u8 bob64_embedded_nested_app_end[];
extern const u8 bob64_embedded_echo[];
extern const u8 bob64_embedded_echo_end[];
extern const u8 bob64_embedded_ls[];
extern const u8 bob64_embedded_ls_end[];
extern const u8 bob64_embedded_cat[];
extern const u8 bob64_embedded_cat_end[];
extern const u8 bob64_embedded_notes[];
extern const u8 bob64_embedded_notes_end[];
extern const u8 bob64_embedded_info[];
extern const u8 bob64_embedded_info_end[];
extern const u8 bob64_embedded_mouse_smoke[];
extern const u8 bob64_embedded_mouse_smoke_end[];
extern const u8 bob64_embedded_launcher[];
extern const u8 bob64_embedded_launcher_end[];
extern const u8 bob64_embedded_source[];
extern const u8 bob64_embedded_source_end[];
@@ -204,12 +246,72 @@ static int kernel_install_bob_application(BOB64_FILESYSTEM *filesystem) {
return bob64_fs_write(filesystem,"bob.b64e",bob64_embedded_app,length);
}
static int kernel_install_display_application(BOB64_FILESYSTEM *filesystem) {
usize length=(usize)(bob64_embedded_display_end-bob64_embedded_display);
if(length<BOB64_EXEC_HEADER_SIZE)return -1;
return bob64_fs_write(filesystem,"display.b64e",bob64_embedded_display,length);
}
static int kernel_install_gui_application(BOB64_FILESYSTEM *filesystem) {
usize length=(usize)(bob64_embedded_gui_end-bob64_embedded_gui);
if(!length)return -1;
return bob64_fs_write(filesystem,"desktop.b64e",bob64_embedded_gui,length);
}
static int kernel_install_nested_application(BOB64_FILESYSTEM *filesystem) {
usize length=(usize)(bob64_embedded_nested_app_end-
bob64_embedded_nested_app);
if(length<BOB64_EXEC_HEADER_SIZE)return -1;
return bob64_fs_write(filesystem,"nested.b64e",bob64_embedded_nested_app,
length);
}
static int kernel_install_echo_application(BOB64_FILESYSTEM *filesystem) {
usize length=(usize)(bob64_embedded_echo_end-bob64_embedded_echo);
if(length<BOB64_EXEC_HEADER_SIZE)return -1;
return bob64_fs_write(filesystem,"echo.b64e",bob64_embedded_echo,length);
}
static int kernel_install_ls_application(BOB64_FILESYSTEM *filesystem) {
usize length=(usize)(bob64_embedded_ls_end-bob64_embedded_ls);
if(length<BOB64_EXEC_HEADER_SIZE)return -1;
return bob64_fs_write(filesystem,"ls.b64e",bob64_embedded_ls,length);
}
static int kernel_install_cat_application(BOB64_FILESYSTEM *filesystem) {
usize length=(usize)(bob64_embedded_cat_end-bob64_embedded_cat);
if(length<BOB64_EXEC_HEADER_SIZE)return -1;
return bob64_fs_write(filesystem,"cat.b64e",bob64_embedded_cat,length);
}
static int kernel_install_notes_application(BOB64_FILESYSTEM *filesystem) {
usize length=(usize)(bob64_embedded_notes_end-bob64_embedded_notes);
if(length<BOB64_EXEC_HEADER_SIZE)return -1;
return bob64_fs_write(filesystem,"notes.b64e",bob64_embedded_notes,length);
}
static int kernel_install_info_application(BOB64_FILESYSTEM *filesystem) {
usize length=(usize)(bob64_embedded_info_end-bob64_embedded_info);
if(length<BOB64_EXEC_HEADER_SIZE)return -1;
return bob64_fs_write(filesystem,"info.b64e",bob64_embedded_info,length);
}
static int kernel_install_mouse_smoke_application(BOB64_FILESYSTEM *filesystem) {
usize length=(usize)(bob64_embedded_mouse_smoke_end-
bob64_embedded_mouse_smoke);
if(length<BOB64_EXEC_HEADER_SIZE)return -1;
return bob64_fs_write(filesystem,"mousesmoke.b64e",
bob64_embedded_mouse_smoke,length);
}
static int kernel_install_launcher_application(BOB64_FILESYSTEM *filesystem) {
usize length=(usize)(bob64_embedded_launcher_end-
bob64_embedded_launcher);
if(length<BOB64_EXEC_HEADER_SIZE)return -1;
return bob64_fs_write(filesystem,"launcher.b64e",bob64_embedded_launcher,
length);
}
static int kernel_install_bob_source(BOB64_FILESYSTEM *filesystem) {
usize length=(usize)(bob64_embedded_source_end-bob64_embedded_source);
return bob64_fs_write(filesystem,"bob.c",bob64_embedded_source,length);
@@ -227,13 +329,14 @@ static int kernel_process_smoke_test(const BOB64_KERNEL_BOOT_INFO *info) {
BOB64_PROCESS_PAGE *pages;
BOB64_APP_STARTUP *startup;
u64 physical,flags,kernel_root,table_checkpoint;
usize allocated_before;
usize allocated_before,heap_checkpoint;
if(!info->NxSupported)return 1;
pages=(BOB64_PROCESS_PAGE *)bob64_heap_calloc(&kernel_heap,
(usize)BOB64_PROCESS_PAGE_LIMIT,sizeof(*pages));
if(!pages)return -1;
kernel_root=read_cr3();
table_checkpoint=bob64_bootstrap_space.TablePoolUsed;
heap_checkpoint=kernel_heap_high_water;
allocated_before=bob64_boot_page_allocator.AllocatedCount;
operations.NxSupported=info->NxSupported;
if(bob64_process_init(&process,pages,(usize)BOB64_PROCESS_PAGE_LIMIT,&operations)) {
@@ -244,7 +347,8 @@ static int kernel_process_smoke_test(const BOB64_KERNEL_BOOT_INFO *info) {
bob64_bootstrap_space.PageTable.Context)||
bob64_page_table_clone_isolated(&process_table,&bob64_bootstrap_space.PageTable,
BOB64_PROCESS_IMAGE_BASE,BOB64_PROCESS_ISOLATED_SIZE)) {
bob64_bootstrap_space.TablePoolUsed=table_checkpoint;
if(kernel_heap_high_water==heap_checkpoint)
bob64_bootstrap_space.TablePoolUsed=table_checkpoint;
bob64_heap_free(&kernel_heap,pages);return -1;
}
__asm__ volatile("mov %0,%%cr3"::"r"(process_table.RootPhysical):"memory");
@@ -253,7 +357,8 @@ static int kernel_process_smoke_test(const BOB64_KERNEL_BOOT_INFO *info) {
if(result) {
bob64_process_unload(&process);
__asm__ volatile("mov %0,%%cr3"::"r"(kernel_root):"memory");
bob64_bootstrap_space.TablePoolUsed=table_checkpoint;
if(kernel_heap_high_water==heap_checkpoint)
bob64_bootstrap_space.TablePoolUsed=table_checkpoint;
bob64_heap_free(&kernel_heap,pages);return -1;
}
startup=(BOB64_APP_STARTUP *)(uintptr_t)process.StartupAddress;
@@ -270,6 +375,7 @@ static int kernel_process_smoke_test(const BOB64_KERNEL_BOOT_INFO *info) {
BOB64_PROCESS_STACK_GUARD,&physical,&flags)==0;
if(result) {
kernel_user_output_length=0;
kernel_user_output_truncated=0;
bob64_syscall_set_address_space(&process_table);
bob64_syscall_set_read_user(kernel_copy_user_bytes,0);
bob64_syscall_set_write(kernel_user_write_character,0);
@@ -281,7 +387,8 @@ static int kernel_process_smoke_test(const BOB64_KERNEL_BOOT_INFO *info) {
bob64_syscall_set_read_user(0,0);
bob64_syscall_set_address_space(0);
kernel_user_output[kernel_user_output_length]=0;
if(app_status||kernel_user_output_length!=sizeof(kernel_user_output)-1||
if(app_status||kernel_user_output_truncated||
kernel_user_output_length!=4||
!kernel_bytes_equal(kernel_user_output,"bob!"))result=0;
else kernel_write("\r\n");
}
@@ -303,7 +410,8 @@ static int kernel_process_smoke_test(const BOB64_KERNEL_BOOT_INFO *info) {
"bob64 kernel: non-executable data protection passed\r\n"))result=-1;
}
__asm__ volatile("mov %0,%%cr3"::"r"(kernel_root):"memory");
bob64_bootstrap_space.TablePoolUsed=table_checkpoint;
if(kernel_heap_high_water==heap_checkpoint)
bob64_bootstrap_space.TablePoolUsed=table_checkpoint;
if(bob64_boot_page_allocator.AllocatedCount!=allocated_before)result=-1;
if(bob64_heap_free(&kernel_heap,pages))result=-1;
return result;
@@ -330,6 +438,7 @@ static void kernel_user_write_character(void *context,u8 character) {
(void)context;
if(kernel_user_output_length+1<sizeof(kernel_user_output))
kernel_user_output[kernel_user_output_length++]=(char)character;
else kernel_user_output_truncated=1;
kernel_write(text);
}
@@ -358,6 +467,7 @@ static int kernel_process_fault_smoke_test(BOB64_PROCESS *process,
return -1;
}
kernel_user_output_length=0;
kernel_user_output_truncated=0;
bob64_user_exception_vector=~(u64)0;
bob64_user_exception_error=~(u64)0;
bob64_user_exception_rip=~(u64)0;
@@ -377,7 +487,7 @@ static int kernel_process_fault_smoke_test(BOB64_PROCESS *process,
passed=status==-142&&bob64_user_exception_vector==14&&
bob64_user_exception_rip==expected_rip&&
(bob64_user_exception_error&error_mask)==error_value&&
kernel_user_output_length==sizeof(kernel_user_output)-1&&
!kernel_user_output_truncated&&kernel_user_output_length==4&&
kernel_bytes_equal(kernel_user_output,"bob!");
if(bob64_process_unload(process))return -1;
if(!passed)return -1;
@@ -388,10 +498,15 @@ static int kernel_process_fault_smoke_test(BOB64_PROCESS *process,
static int kernel_wait_for_input_event(void *context,BOB64_EVENT *event) {
(void)context;
if(!event)return -1;
/* int 0x80 enters through an interrupt gate, which clears IF. */
__asm__ volatile("sti":::"memory");
for(;;) {
if(!bob64_mouse_poll_event(event)||!bob64_keyboard_poll_event(event))return 0;
if(!bob64_mouse_poll_event(event)||!bob64_keyboard_poll_event(event))break;
__asm__ volatile("pause");
}
/* Keep the syscall handler's state until iretq restores the user flags. */
__asm__ volatile("cli":::"memory");
return 0;
}
static int kernel_write_user_bytes(void *context,u64 address,const void *source,
@@ -504,6 +619,7 @@ static s64 kernel_run_application(void *context,const char *name,usize argument_
const char *image;
usize image_size;
u64 kernel_root,table_checkpoint;
usize heap_checkpoint;
s64 status=-1;
KERNEL_APP_CONTEXT *app=(KERNEL_APP_CONTEXT *)context;
void *application_privilege_stack=0;
@@ -515,6 +631,7 @@ static s64 kernel_run_application(void *context,const char *name,usize argument_
if(started)*started=0;
if(!app||!app->Filesystem||!app->NxSupported||!started||
!app->PhysicalAddressBits||
bob64_user_depth>=BOB64_USER_ENTRY_MAX_DEPTH||
bob64_fs_read(app->Filesystem,name,&image,&image_size))return -1;
operations=(BOB64_PROCESS_OPERATIONS){process_allocate_page,process_free_page,
process_map_page,process_protect_page,process_unmap_page,&process_context,
@@ -524,6 +641,7 @@ static s64 kernel_run_application(void *context,const char *name,usize argument_
if(!pages)return -1;
kernel_root=read_cr3();
table_checkpoint=bob64_bootstrap_space.TablePoolUsed;
heap_checkpoint=kernel_heap_high_water;
if(bob64_process_init(&process,pages,(usize)BOB64_PROCESS_PAGE_LIMIT,&operations))
goto done;
if(bob64_page_table_init(&process_table,app->PhysicalAddressBits,
@@ -554,6 +672,7 @@ static s64 kernel_run_application(void *context,const char *name,usize argument_
}
syscall_context_saved=1;
kernel_user_output_length=0;
kernel_user_output_truncated=0;
u32 display_width,display_height;
if(!bob64_framebuffer_resolution(&display_width,&display_height)) {
window_owner=kernel_next_window_owner++;
@@ -575,6 +694,7 @@ static s64 kernel_run_application(void *context,const char *name,usize argument_
bob64_syscall_set_file_stream(kernel_app_open_stream,kernel_app_read_stream,
kernel_app_write_stream,app);
bob64_syscall_set_file_manager(kernel_app_list_files,kernel_app_delete_file,app);
bob64_syscall_set_app_runner(kernel_app_run_application,app);
bob64_syscall_set_write(kernel_user_write_character,0);
bob64_syscall_set_wait_event(kernel_wait_for_input_event,0);
bob64_syscall_set_window_server(window_server_ready?window_server:0,
@@ -582,6 +702,7 @@ static s64 kernel_run_application(void *context,const char *name,usize argument_
*started=1;entered=1;
status=bob64_enter_user(process.EntryAddress,process.StartupAddress,
process.InitialStackPointer);
kernel_user_output[kernel_user_output_length]=0;
if(bob64_tss_set_rsp0(&bob64_kernel_tss,previous_privilege_stack)||
bob64_kernel_tss.Rsp0!=previous_privilege_stack)cleanup_error=1;
if(bob64_heap_free(&kernel_heap,application_privilege_stack))cleanup_error=1;
@@ -600,12 +721,28 @@ restore:
}
__asm__ volatile("mov %0,%%cr3"::"r"(kernel_root):"memory");
done:
bob64_bootstrap_space.TablePoolUsed=table_checkpoint;
/* A heap peak can leave shared page-table levels mapped after the heap
later shrinks. Preserve those table pages across this address space. */
if(kernel_heap_high_water==heap_checkpoint)
bob64_bootstrap_space.TablePoolUsed=table_checkpoint;
if(bob64_heap_free(&kernel_heap,pages)||cleanup_error)status=-1;
if(!entered)*started=0;
return status;
}
static int kernel_app_run_application(void *context,const char *name,
usize argument_count,
const char *const *arguments,
s64 *exit_status) {
int started=0;
s64 status;
if(!exit_status)return -22;
status=kernel_run_application(context,name,argument_count,arguments,&started);
if(!started)return -2;
*exit_status=status;
return 0;
}
static int kernel_compile_application(void *context,const char *source_name,
const char *output_name,usize *error_offset) {
KERNEL_APP_CONTEXT *app=(KERNEL_APP_CONTEXT *)context;
@@ -633,13 +770,23 @@ static void kernel_hex64(u64 value) {
static int kernel_heap_grow(void *context,void **region,usize *region_size) {
const BOB64_KERNEL_BOOT_INFO *info=(const BOB64_KERNEL_BOOT_INFO *)context;
u64 physical,virtual_address;
int map_result;
if(!info||!region||!region_size||kernel_heap_mapped>=BOB64_KERNEL_HEAP_LIMIT)
return 0;
physical=bob64_page_alloc(&bob64_boot_page_allocator,1);
if(!physical)return 0;
if(!physical) {
kernel_write("bob64 kernel: heap physical page allocation failed\r\n");
return 0;
}
virtual_address=BOB64_KERNEL_HEAP_BASE+kernel_heap_mapped;
if(bob64_page_map(&bob64_bootstrap_space.PageTable,virtual_address,physical,
BOB64_PAGE_WRITE|(info->NxSupported?BOB64_PAGE_NX:0))) {
map_result=bob64_page_map(&bob64_bootstrap_space.PageTable,virtual_address,
physical,BOB64_PAGE_WRITE|(info->NxSupported?BOB64_PAGE_NX:0));
if(map_result) {
kernel_write("bob64 kernel: heap page-table mapping failed (result=0x");
kernel_hex64((u64)(s64)map_result);
kernel_write(" tables=0x");kernel_hex64(bob64_bootstrap_space.TablePoolUsed);
kernel_write("/0x");kernel_hex64(bob64_bootstrap_space.TablePoolPages);
kernel_write(")\r\n");
bob64_page_free(&bob64_boot_page_allocator,physical,1);
return 0;
}
@@ -647,15 +794,49 @@ static int kernel_heap_grow(void *context,void **region,usize *region_size) {
volatile u64 *words=(volatile u64 *)(uintptr_t)virtual_address;
for(usize i=0;i<EFI_PAGE_SIZE/sizeof(u64);i++)words[i]=0;
kernel_heap_mapped+=(usize)EFI_PAGE_SIZE;
if(kernel_heap_mapped>kernel_heap_high_water)
kernel_heap_high_water=kernel_heap_mapped;
*region=(void *)(uintptr_t)virtual_address;
*region_size=(usize)EFI_PAGE_SIZE;
return 1;
}
static int kernel_heap_shrink(void *context,void *region,usize region_size) {
const BOB64_KERNEL_BOOT_INFO *info=(const BOB64_KERNEL_BOOT_INFO *)context;
u64 expected;
if(!info||!region||!region_size||
(region_size&(usize)(EFI_PAGE_SIZE-1))||
region_size>kernel_heap_mapped||
region_size>~(u64)0-(u64)(uintptr_t)BOB64_KERNEL_HEAP_BASE)
return -1;
expected=BOB64_KERNEL_HEAP_BASE+kernel_heap_mapped-region_size;
if((u64)(uintptr_t)region!=expected)return -1;
for(usize offset=0;offset<region_size;offset+=(usize)EFI_PAGE_SIZE) {
u64 translated,flags;
if(bob64_page_translate(&bob64_bootstrap_space.PageTable,
expected+offset,&translated,&flags)!=1||
(translated&(EFI_PAGE_SIZE-1))||
(flags&(BOB64_PAGE_PRESENT|BOB64_PAGE_WRITE))!=
(BOB64_PAGE_PRESENT|BOB64_PAGE_WRITE))return -1;
}
for(usize offset=0;offset<region_size;offset+=(usize)EFI_PAGE_SIZE) {
u64 unmapped_physical;
if(bob64_page_unmap(&bob64_bootstrap_space.PageTable,expected+offset,
&unmapped_physical,0))return -1;
__asm__ volatile("invlpg (%0)"::"r"((void *)(uintptr_t)(expected+offset)):
"memory");
if(bob64_page_free(&bob64_boot_page_allocator,unmapped_physical,1))
return -1;
}
kernel_heap_mapped-=region_size;
return 0;
}
static int kernel_heap_smoke_test(const BOB64_KERNEL_BOOT_INFO *info) {
char *first,*large,*zero;
if(bob64_heap_init(&kernel_heap,(usize)BOB64_KERNEL_HEAP_LIMIT,
kernel_heap_grow,(void *)info))return -1;
bob64_heap_set_shrink(&kernel_heap,kernel_heap_shrink);
first=(char *)bob64_heap_alloc(&kernel_heap,64);
large=(char *)bob64_heap_alloc(&kernel_heap,5000);
zero=(char *)bob64_heap_calloc(&kernel_heap,32,2);
@@ -669,9 +850,39 @@ static int kernel_heap_smoke_test(const BOB64_KERNEL_BOOT_INFO *info) {
if(bob64_heap_free(&kernel_heap,large)||bob64_heap_free(&kernel_heap,first)||
bob64_heap_free(&kernel_heap,zero)||bob64_heap_free(&kernel_heap,zero)!=-1)
return -1;
if(bob64_heap_mapped_bytes(&kernel_heap)!=EFI_PAGE_SIZE||
kernel_heap_mapped!=EFI_PAGE_SIZE)return -1;
return 0;
}
static int kernel_table_pool_smoke_test(const BOB64_KERNEL_BOOT_INFO *info) {
BOB64_PAGE_TABLE table;
u64 checkpoint,initial_pages,physical;
if(!info||!bob64_bootstrap_space.TablePoolPages)return -1;
checkpoint=bob64_bootstrap_space.TablePoolUsed;
initial_pages=bob64_bootstrap_space.TablePoolPages;
if(bob64_page_table_init(&table,info->PhysicalAddressBits,
bob64_bootstrap_space.PageTable.Allocate,
bob64_bootstrap_space.PageTable.Access,
bob64_bootstrap_space.PageTable.Context))return -1;
for(u64 i=0;i<140;i++) {
u64 virtual_address=0x0000001000000000ULL+i*(2ULL<<20);
u64 physical_address=0x0000000010000000ULL+i*BOB64_PAGE_SIZE;
if(bob64_page_map(&table,virtual_address,physical_address,
BOB64_PAGE_WRITE|BOB64_PAGE_NX)) {
bob64_bootstrap_space.TablePoolUsed=checkpoint;
return -1;
}
}
int valid=bob64_bootstrap_space.TablePoolPages>initial_pages&&
bob64_bootstrap_space.TablePoolUsed>checkpoint&&
bob64_page_translate(&table,0x0000001000000000ULL+139*(2ULL<<20),
&physical,0)==1&&
physical==0x0000000010000000ULL+139*BOB64_PAGE_SIZE;
bob64_bootstrap_space.TablePoolUsed=checkpoint;
return valid?0:-1;
}
static int kernel_privilege_stack_init(void) {
kernel_privilege_stack=bob64_heap_alloc(&kernel_heap,
(usize)BOB64_KERNEL_PRIVILEGE_STACK_SIZE);
@@ -694,6 +905,36 @@ static void shell_clear(void *context) {
bob64_early_console_write("\x1b[2J\x1b[H");
}
static EFI_RUNTIME_SERVICES *kernel_runtime_services(
const BOB64_KERNEL_BOOT_INFO *info) {
return info&&info->RuntimeServices?
(EFI_RUNTIME_SERVICES *)(uintptr_t)info->RuntimeServices:0;
}
static int kernel_snapshot_save(void *context,const void *snapshot,
usize snapshot_size) {
const BOB64_KERNEL_BOOT_INFO *info=(const BOB64_KERNEL_BOOT_INFO *)context;
EFI_STATUS firmware_status=EFI_SUCCESS;
UINTN maximum_variable_size=0,remaining_storage_size=0;
int result=bob64_firmware_snapshot_save(kernel_runtime_services(info),
&kernel_heap,snapshot,snapshot_size,&firmware_status,
&maximum_variable_size,&remaining_storage_size);
if(result) {
kernel_write("firmware snapshot save failed (EFI 0x");
kernel_hex64(firmware_status);kernel_write(" max=0x");
kernel_hex64(maximum_variable_size);kernel_write(" free=0x");
kernel_hex64(remaining_storage_size);kernel_write(")\r\n");
}
return result;
}
static int kernel_snapshot_restore(void *context,BOB64_FILESYSTEM *filesystem) {
const BOB64_KERNEL_BOOT_INFO *info=(const BOB64_KERNEL_BOOT_INFO *)context;
EFI_RUNTIME_SERVICES *services=kernel_runtime_services(info);
return services?bob64_firmware_snapshot_restore(services,filesystem):
BOB64_FIRMWARE_SNAPSHOT_NOT_FOUND;
}
__attribute__((noreturn)) void bob64_kernel_main(const BOB64_KERNEL_BOOT_INFO *info) {
bob64_early_console_init();
if(info&&info->HasFramebuffer&&bob64_framebuffer_init(info->FramebufferBase,
@@ -713,6 +954,11 @@ __attribute__((noreturn)) void bob64_kernel_main(const BOB64_KERNEL_BOOT_INFO *i
kernel_write("bob64 kernel: heap initialization failed\r\n");
kernel_halt();
}
if(kernel_table_pool_smoke_test(info)) {
kernel_write("bob64 kernel: page-table pool growth failed\r\n");
kernel_halt();
}
kernel_write("bob64 kernel: dynamic page-table pool passed\r\n");
if(kernel_privilege_stack_init()) {
kernel_write("bob64 kernel: privilege stack initialization failed\r\n");
kernel_halt();
@@ -732,8 +978,26 @@ __attribute__((noreturn)) void bob64_kernel_main(const BOB64_KERNEL_BOOT_INFO *i
kernel_write("bob64 kernel: demo app install failed\r\n");
if(info->NxSupported&&kernel_install_gui_application(&kernel_filesystem))
kernel_write("bob64 kernel: desktop app install failed\r\n");
if(info->NxSupported&&kernel_install_nested_application(&kernel_filesystem))
kernel_write("bob64 kernel: nested smoke app install failed\r\n");
if(info->NxSupported&&kernel_install_echo_application(&kernel_filesystem))
kernel_write("bob64 kernel: echo app install failed\r\n");
if(kernel_install_bob_source(&kernel_filesystem))
kernel_write("bob64 kernel: C demo source install failed\r\n");
if(info->NxSupported&&kernel_install_cat_application(&kernel_filesystem))
kernel_write("bob64 kernel: cat app install failed\r\n");
if(info->NxSupported&&kernel_install_ls_application(&kernel_filesystem))
kernel_write("bob64 kernel: ls app install failed\r\n");
if(info->NxSupported&&kernel_install_notes_application(&kernel_filesystem))
kernel_write("bob64 kernel: notes app install failed\r\n");
if(info->NxSupported&&kernel_install_info_application(&kernel_filesystem))
kernel_write("bob64 kernel: info app install failed\r\n");
if(info->NxSupported&&kernel_install_mouse_smoke_application(&kernel_filesystem))
kernel_write("bob64 kernel: mouse smoke app install failed\r\n");
if(info->NxSupported&&kernel_install_launcher_application(&kernel_filesystem))
kernel_write("bob64 kernel: launcher app install failed\r\n");
if(info->NxSupported&&kernel_install_display_application(&kernel_filesystem))
kernel_write("bob64 kernel: graphics demo install failed\r\n");
kernel_app_context.Filesystem=&kernel_filesystem;
kernel_app_context.NxSupported=info->NxSupported;
kernel_app_context.PhysicalAddressBits=info->PhysicalAddressBits;
@@ -749,6 +1013,16 @@ __attribute__((noreturn)) void bob64_kernel_main(const BOB64_KERNEL_BOOT_INFO *i
kernel_halt();
}
kernel_write("bob64 kernel: timer IRQ enabled\r\n");
u64 initial_timer_ticks=bob64_timer_ticks();
for(volatile u32 timer_wait=0;
timer_wait<100000000u&&bob64_timer_ticks()==initial_timer_ticks;
timer_wait++)
__asm__ volatile("pause");
if(bob64_timer_ticks()==initial_timer_ticks) {
kernel_write("bob64 kernel: timer tick test failed\r\n");
kernel_halt();
}
kernel_write("bob64 kernel: timer tick passed\r\n");
bob64_keyboard_reset();
int keyboard_irq_enabled=bob64_interrupts_enable_keyboard()==0;
if(!keyboard_irq_enabled)
@@ -762,7 +1036,159 @@ __attribute__((noreturn)) void bob64_kernel_main(const BOB64_KERNEL_BOOT_INFO *i
kernel_halt();
}
kernel_write("bob64 kernel: native streaming app passed\r\n");
started=0;
status=kernel_run_application(&kernel_app_context,"nested.b64e",0,0,
&started);
if(!started||status||(keyboard_irq_enabled&&!kernel_interrupts_enabled())) {
kernel_write("bob64 kernel: nested app return test failed\r\n");
kernel_halt();
}
kernel_write("bob64 kernel: nested app return passed\r\n");
static const char *echo_arguments[]={"echo.b64e","bob!"};
started=0;
status=kernel_run_application(&kernel_app_context,"echo.b64e",2,
echo_arguments,&started);
if(!started||status||kernel_user_output_length!=5||
!kernel_bytes_equal(kernel_user_output,"bob!\n")||
(keyboard_irq_enabled&&!kernel_interrupts_enabled())) {
kernel_write("bob64 kernel: echo argument test failed\r\n");
kernel_halt();
}
kernel_write("bob64 kernel: native echo arguments passed\r\n");
static const char *cat_arguments[]={"cat.b64e","cat-smoke.txt"};
static const char cat_fixture[]="bob!";
if(bob64_fs_write(&kernel_filesystem,"cat-smoke.txt",cat_fixture,
sizeof(cat_fixture)-1)) {
kernel_write("bob64 kernel: cat fixture setup failed\r\n");
kernel_halt();
}
started=0;
status=kernel_run_application(&kernel_app_context,"cat.b64e",2,
cat_arguments,&started);
int cat_output_ok=kernel_user_output_length==5&&
kernel_bytes_equal(kernel_user_output,"bob!\n");
if(bob64_fs_delete(&kernel_filesystem,"cat-smoke.txt")) {
kernel_write("bob64 kernel: cat fixture cleanup failed\r\n");
kernel_halt();
}
if(!started||status||!cat_output_ok||
(keyboard_irq_enabled&&!kernel_interrupts_enabled())) {
kernel_write("bob64 kernel: native file-read app test failed\r\n");
kernel_halt();
}
kernel_write("bob64 kernel: native file-read app passed\r\n");
started=0;
status=kernel_run_application(&kernel_app_context,"ls.b64e",0,0,
&started);
if(!started||status||kernel_user_output_truncated||
!kernel_text_contains(kernel_user_output,"bob.b64e ")||
(keyboard_irq_enabled&&!kernel_interrupts_enabled())) {
kernel_write("bob64 kernel: native file-list app test failed\r\n");
kernel_halt();
}
kernel_write("bob64 kernel: native file-list app passed\r\n");
static const char *notes_put_arguments[]={"notes.b64e","put",
"notes-smoke.txt","bob!"};
static const char *notes_show_arguments[]={"notes.b64e","show",
"notes-smoke.txt"};
static const char *notes_delete_arguments[]={"notes.b64e","delete",
"notes-smoke.txt"};
static const char *notes_copy_arguments[]={"notes.b64e","copy",
"notes-large-source.txt","notes-large-copy.txt"};
static u8 note_fixture_check[4];
started=0;
status=kernel_run_application(&kernel_app_context,"notes.b64e",4,
notes_put_arguments,&started);
if(!started||status||kernel_app_read_file(&kernel_app_context,
"notes-smoke.txt",note_fixture_check,sizeof(note_fixture_check))!=4||
!kernel_bytes_equal((const char *)note_fixture_check,"bob!")||
(keyboard_irq_enabled&&!kernel_interrupts_enabled())) {
kernel_write("bob64 kernel: native notes write test failed\r\n");
kernel_halt();
}
started=0;
status=kernel_run_application(&kernel_app_context,"notes.b64e",3,
notes_show_arguments,&started);
if(!started||status||kernel_user_output_length!=5||
!kernel_bytes_equal(kernel_user_output,"bob!\n")||
(keyboard_irq_enabled&&!kernel_interrupts_enabled())) {
kernel_write("bob64 kernel: native notes show test failed\r\n");
kernel_halt();
}
started=0;
status=kernel_run_application(&kernel_app_context,"notes.b64e",3,
notes_delete_arguments,&started);
if(!started||status||kernel_app_read_file(&kernel_app_context,
"notes-smoke.txt",note_fixture_check,sizeof(note_fixture_check))!=-2||
(keyboard_irq_enabled&&!kernel_interrupts_enabled())) {
kernel_write("bob64 kernel: native notes delete test failed\r\n");
kernel_halt();
}
static char large_note_fixture[12288];
const char *large_note_copy=0;
usize large_note_copy_length=0;
for(usize i=0;i<sizeof(large_note_fixture);i++)
large_note_fixture[i]=(i%80==79)?'\n':(char)('a'+i%26);
if(bob64_fs_write(&kernel_filesystem,"notes-large-source.txt",
large_note_fixture,sizeof(large_note_fixture))) {
kernel_write("bob64 kernel: large notes fixture setup failed\r\n");
kernel_halt();
}
started=0;
status=kernel_run_application(&kernel_app_context,"notes.b64e",4,
notes_copy_arguments,&started);
int large_note_match=!bob64_fs_read(&kernel_filesystem,
"notes-large-copy.txt",&large_note_copy,&large_note_copy_length)&&
large_note_copy_length==sizeof(large_note_fixture);
for(usize i=0;large_note_match&&i<sizeof(large_note_fixture);i++)
if(large_note_copy[i]!=large_note_fixture[i])large_note_match=0;
if(!started||status||kernel_user_output_length!=8||
!kernel_bytes_equal(kernel_user_output,"Copied.\n")||
kernel_user_output_truncated||!large_note_match||
(keyboard_irq_enabled&&!kernel_interrupts_enabled())) {
kernel_write("bob64 kernel: large notes streaming test failed\r\n");
kernel_halt();
}
kernel_write("bob64 kernel: large notes streaming copy passed\r\n");
if(bob64_fs_delete(&kernel_filesystem,"notes-large-source.txt")||
bob64_fs_delete(&kernel_filesystem,"notes-large-copy.txt")) {
kernel_write("bob64 kernel: large notes fixture cleanup failed\r\n");
kernel_halt();
}
kernel_write("bob64 kernel: native notes app passed\r\n");
started=0;
status=kernel_run_application(&kernel_app_context,"info.b64e",0,0,
&started);
if(!started||status||kernel_user_output_truncated||
!kernel_text_contains(kernel_user_output,
"bob64 system information\n")||
!kernel_text_contains(kernel_user_output,"System call ABI: 12\n")||
!kernel_text_contains(kernel_user_output,"Uptime: ")||
!kernel_text_contains(kernel_user_output,"RAM files: ")||
!kernel_text_contains(kernel_user_output,"RAM file data: ")||
kernel_user_output_length<5||
!kernel_bytes_equal(kernel_user_output+
kernel_user_output_length-5,"bob!\n")||
(keyboard_irq_enabled&&!kernel_interrupts_enabled())) {
kernel_write("bob64 kernel: native info app test failed\r\n");
kernel_halt();
}
kernel_write("bob64 kernel: native info app passed\r\n");
}
EFI_RUNTIME_SERVICES *runtime_services=kernel_runtime_services(info);
int snapshot_restore=runtime_services?bob64_firmware_snapshot_restore(
runtime_services,&kernel_filesystem):
BOB64_FIRMWARE_SNAPSHOT_NOT_FOUND;
if(!snapshot_restore) {
kernel_write("bob64 kernel: persistent B64S snapshot restored\r\n");
const char *persisted_contents;
usize persisted_length;
if(!bob64_fs_read(&kernel_filesystem,"persist.txt",&persisted_contents,
&persisted_length)&&persisted_length==8&&
kernel_bytes_equal(persisted_contents,"survived"))
kernel_write("bob64 kernel: persistent B64S smoke file passed\r\n");
} else if(snapshot_restore<0)
kernel_write("bob64 kernel: persistent B64S snapshot rejected\r\n");
u32 display_width,display_height;
if(!bob64_framebuffer_resolution(&display_width,&display_height)) {
if(bob64_mouse_init(display_width,display_height))
@@ -779,6 +1205,8 @@ __attribute__((noreturn)) void bob64_kernel_main(const BOB64_KERNEL_BOOT_INFO *i
}
bob64_shell_set_runner(&kernel_shell,kernel_run_application);
bob64_shell_set_compiler(&kernel_shell,kernel_compile_application);
bob64_shell_set_snapshot_storage(&kernel_shell,kernel_snapshot_save,
kernel_snapshot_restore,(void *)info);
for(;;) {
int character=bob64_keyboard_poll();
if(character<0)character=bob64_early_console_try_read();
+4 -1
View File
@@ -21,11 +21,14 @@ typedef struct {
u8 NxSupported;
u8 HasFramebuffer;
u8 Reserved[5];
u64 RuntimeServices;
} BOB64_KERNEL_BOOT_INFO;
_Static_assert(sizeof(BOB64_KERNEL_BOOT_INFO)==88,"bob64 kernel boot information ABI");
_Static_assert(sizeof(BOB64_KERNEL_BOOT_INFO)==96,"bob64 kernel boot information ABI");
_Static_assert(__builtin_offsetof(BOB64_KERNEL_BOOT_INFO,NxSupported)==81,
"handoff assembly NX-support offset mismatch");
_Static_assert(__builtin_offsetof(BOB64_KERNEL_BOOT_INFO,RuntimeServices)==88,
"UEFI runtime-service pointer ABI offset");
__attribute__((noreturn)) void bob64_kernel_main(const BOB64_KERNEL_BOOT_INFO *info);
__attribute__((noreturn)) void bob64_enter_kernel(
+16 -10
View File
@@ -123,20 +123,26 @@ int bob64_keyboard_decode(BOB64_KEYBOARD_STATE *state,u8 scancode) {
return (int)event.Character;
}
int bob64_keyboard_event_input(const BOB64_EVENT *event) {
if(!event||event->Type!=BOB64_EVENT_KEY_DOWN)return -1;
if(event->Key==(BOB64_EVENT_KEY_EXTENDED|0x48))
return BOB64_KEYBOARD_INPUT_UP;
if(event->Key==(BOB64_EVENT_KEY_EXTENDED|0x50))
return BOB64_KEYBOARD_INPUT_DOWN;
return event->Character?(int)event->Character:-1;
}
int bob64_keyboard_poll(void) {
u8 status,scancode;
BOB64_EVENT event;
if(keyboard_irq_active) {
BOB64_EVENT event;
while(!bob64_keyboard_irq_pop_event(&event))
if(event.Type==BOB64_EVENT_KEY_DOWN&&event.Character)
return (int)event.Character;
while(!bob64_keyboard_irq_pop_event(&event)) {
int input=bob64_keyboard_event_input(&event);
if(input>=0)return input;
}
return -1;
}
__asm__ volatile("inb $0x64,%0":"=a"(status));
if(status==0xff||!(status&1))return -1;
if(status&0x20) { __asm__ volatile("inb $0x60,%0":"=a"(scancode));return -1; }
__asm__ volatile("inb $0x60,%0":"=a"(scancode));
return bob64_keyboard_decode(&keyboard_state,scancode);
if(bob64_keyboard_poll_event(&event))return -1;
return bob64_keyboard_event_input(&event);
}
int bob64_keyboard_poll_event(BOB64_EVENT *event) {
+4
View File
@@ -4,6 +4,9 @@
#include "types.h"
#include "event.h"
#define BOB64_KEYBOARD_INPUT_UP 0x10000
#define BOB64_KEYBOARD_INPUT_DOWN 0x10001
typedef struct {
u8 LeftShift,RightShift,LeftControl,RightControl,LeftAlt,RightAlt;
u8 CapsLock,Extended,PauseRemaining;
@@ -14,6 +17,7 @@ int bob64_keyboard_decode(BOB64_KEYBOARD_STATE *state,u8 scancode);
int bob64_keyboard_decode_event(BOB64_KEYBOARD_STATE *state,u8 scancode,
BOB64_EVENT *event);
int bob64_keyboard_poll(void);
int bob64_keyboard_event_input(const BOB64_EVENT *event);
int bob64_keyboard_poll_event(BOB64_EVENT *event);
/* IRQ producer and foreground consumer; the queue drops new events when full. */
int bob64_keyboard_irq_capture(u8 scancode);
+142
View File
@@ -0,0 +1,142 @@
#include "lz4.h"
#define LZ4_HASH_BITS 16u
#define LZ4_HASH_SIZE (1u<<LZ4_HASH_BITS)
#define LZ4_MIN_MATCH 4u
#define LZ4_LAST_LITERALS 5u
#define LZ4_MATCH_FIND_LIMIT 12u
static u32 read32le(const u8 *bytes) {
return (u32)bytes[0]|((u32)bytes[1]<<8)|((u32)bytes[2]<<16)|
((u32)bytes[3]<<24);
}
static u32 hash_sequence(u32 sequence) {
return (sequence*2654435761u)>>(32-LZ4_HASH_BITS);
}
usize bob64_lz4_compress_bound(usize input_size) {
usize overhead=input_size/255+16;
return input_size>~(usize)0-overhead?0:input_size+overhead;
}
static int write_length(u8 *output,usize capacity,usize *offset,usize length) {
while(length>=255) {
if(*offset>=capacity)return -1;
output[(*offset)++]=255;
length-=255;
}
if(*offset>=capacity)return -1;
output[(*offset)++]=(u8)length;
return 0;
}
int bob64_lz4_compress(const void *input,usize input_size,void *output,
usize output_capacity,usize *output_size,
void *workspace,usize workspace_size) {
const u8 *source=(const u8 *)input;
u8 *destination=(u8 *)output;
u32 *table=(u32 *)workspace;
usize position=0,anchor=0,written=0;
if(!source||!destination||!output_size||!workspace||
workspace_size<BOB64_LZ4_WORKSPACE_SIZE||
((uintptr_t)workspace&(sizeof(u32)-1))||input_size>0xffffffffu)
return -1;
*output_size=0;
for(u32 i=0;i<LZ4_HASH_SIZE;i++)table[i]=0xffffffffu;
while(position+LZ4_MATCH_FIND_LIMIT<=input_size) {
u32 sequence=read32le(source+position);
u32 hash=hash_sequence(sequence);
u32 reference=table[hash];
table[hash]=(u32)position;
if(reference!=0xffffffffu&&position-reference<=65535u&&
read32le(source+reference)==sequence) {
usize match_start=position;
usize match_length=LZ4_MIN_MATCH;
usize literal_length=match_start-anchor;
usize token_offset=written;
if(written>=output_capacity)return -1;
destination[written++]=0;
if(literal_length>=15&&write_length(destination,output_capacity,
&written,literal_length-15))return -1;
if(literal_length>output_capacity-written)return -1;
for(usize i=0;i<literal_length;i++)
destination[written++]=source[anchor+i];
if(output_capacity-written<2)return -1;
u32 distance=(u32)(match_start-reference);
destination[written++]=(u8)distance;
destination[written++]=(u8)(distance>>8);
while(match_start+match_length<input_size-LZ4_LAST_LITERALS&&
source[reference+match_length]==source[match_start+match_length])
match_length++;
usize encoded_match=match_length-LZ4_MIN_MATCH;
if(encoded_match>=15&&write_length(destination,output_capacity,
&written,encoded_match-15))return -1;
destination[token_offset]=(u8)((literal_length<15?literal_length:15)<<4)|
(u8)(encoded_match<15?encoded_match:15);
position=match_start+match_length;
anchor=position;
usize insert=match_start+1;
while(insert+LZ4_MIN_MATCH<=position&&
insert+LZ4_MIN_MATCH<=input_size) {
table[hash_sequence(read32le(source+insert))]=(u32)insert;
insert++;
}
} else position++;
}
usize literal_length=input_size-anchor;
if(written>=output_capacity)return -1;
usize token_offset=written++;
destination[token_offset]=(u8)((literal_length<15?literal_length:15)<<4);
if(literal_length>=15&&write_length(destination,output_capacity,&written,
literal_length-15))return -1;
if(literal_length>output_capacity-written)return -1;
for(usize i=0;i<literal_length;i++)destination[written++]=source[anchor+i];
*output_size=written;
return 0;
}
static int read_length(const u8 *source,usize source_size,usize *position,
usize *length) {
u8 extension;
do {
if(*position>=source_size)return -1;
extension=source[(*position)++];
if(*length>~(usize)0-extension)return -1;
*length+=extension;
} while(extension==255);
return 0;
}
int bob64_lz4_decompress(const void *input,usize input_size,void *output,
usize output_capacity,usize expected_output_size) {
const u8 *source=(const u8 *)input;
u8 *destination=(u8 *)output;
usize input_position=0,output_position=0;
if((!source&&input_size)||(!destination&&expected_output_size)||
expected_output_size>output_capacity)return -1;
while(input_position<input_size) {
u8 token=source[input_position++];
usize literal_length=token>>4;
if(literal_length==15&&read_length(source,input_size,&input_position,
&literal_length))return -1;
if(literal_length>input_size-input_position||
literal_length>output_capacity-output_position)return -1;
for(usize i=0;i<literal_length;i++)
destination[output_position++]=source[input_position++];
if(input_position==input_size)break;
if(input_size-input_position<2)return -1;
usize distance=(usize)source[input_position]|((usize)source[input_position+1]<<8);
input_position+=2;
if(!distance||distance>output_position)return -1;
usize match_length=(token&15)+LZ4_MIN_MATCH;
if((token&15)==15&&read_length(source,input_size,&input_position,
&match_length))return -1;
if(match_length>output_capacity-output_position)return -1;
for(usize i=0;i<match_length;i++) {
destination[output_position]=destination[output_position-distance];
output_position++;
}
}
return input_position==input_size&&output_position==expected_output_size?0:-1;
}
+14
View File
@@ -0,0 +1,14 @@
#ifndef BOB64_LZ4_H
#define BOB64_LZ4_H
#include "types.h"
#define BOB64_LZ4_WORKSPACE_SIZE (65536u*sizeof(u32))
usize bob64_lz4_compress_bound(usize input_size);
int bob64_lz4_compress(const void *input,usize input_size,void *output,
usize output_capacity,usize *output_size,
void *workspace,usize workspace_size);
int bob64_lz4_decompress(const void *input,usize input_size,void *output,
usize output_capacity,usize expected_output_size);
#endif
+192 -4
View File
@@ -4,6 +4,8 @@ static void output(BOB64_SHELL *shell,const char *text) {
shell->Write(shell->Context,text);
}
static void prompt(BOB64_SHELL *shell);
static char lower_ascii(char value) {
if(value>='A'&&value<='Z')return (char)(value-'A'+'a');
return value;
@@ -131,6 +133,157 @@ static usize text_length(const char *text) {
return length;
}
static void redraw_line(BOB64_SHELL *shell,usize previous_length) {
for(usize i=0;i<previous_length;i++)output(shell,"\b");
output(shell,shell->Line);
for(usize i=shell->Length;i<previous_length;i++)output(shell," \b");
}
static usize copy_text(char *destination,usize capacity,const char *source) {
usize length=0;
if(!destination||!capacity)return 0;
while(source&&length+1<capacity&&source[length]) {
destination[length]=source[length];length++;
}
destination[length]=0;
return length;
}
static void history_store(BOB64_SHELL *shell) {
if(!shell->Length)return;
if(shell->HistoryCount) {
usize i=0;
while(i<shell->Length&&shell->History[shell->HistoryCount-1][i]==
shell->Line[i])i++;
if(i==shell->Length&&shell->History[shell->HistoryCount-1][i]==0)return;
}
if(shell->HistoryCount==BOB64_SHELL_HISTORY_LIMIT) {
for(usize i=1;i<shell->HistoryCount;i++)
copy_text(shell->History[i-1],sizeof(shell->History[i-1]),
shell->History[i]);
shell->HistoryCount--;
}
copy_text(shell->History[shell->HistoryCount],
sizeof(shell->History[shell->HistoryCount]),shell->Line);
shell->HistoryCount++;
}
static void history_load(BOB64_SHELL *shell,const char *line) {
usize previous=shell->Length;
shell->Length=copy_text(shell->Line,sizeof(shell->Line),line);
redraw_line(shell,previous);
}
static void history_up(BOB64_SHELL *shell) {
if(!shell->HistoryCount)return;
if(!shell->HistoryBrowsing) {
shell->HistoryDraftLength=copy_text(shell->HistoryDraft,
sizeof(shell->HistoryDraft),shell->Line);
shell->HistoryBrowsing=1;
shell->HistoryIndex=shell->HistoryCount;
}
if(shell->HistoryIndex)shell->HistoryIndex--;
history_load(shell,shell->History[shell->HistoryIndex]);
}
static void history_down(BOB64_SHELL *shell) {
if(!shell->HistoryBrowsing)return;
if(shell->HistoryIndex+1<shell->HistoryCount) {
shell->HistoryIndex++;
history_load(shell,shell->History[shell->HistoryIndex]);
} else {
shell->HistoryBrowsing=0;
history_load(shell,shell->HistoryDraft);
}
}
typedef struct {
const char *Prefix;
usize PrefixLength,Count;
const char *Names[16];
} BOB64_SHELL_COMPLETIONS;
static int starts_with_case_insensitive(const char *text,const char *prefix,
usize length) {
for(usize i=0;i<length;i++)
if(!text[i]||lower_ascii(text[i])!=lower_ascii(prefix[i]))return 0;
return 1;
}
static void completion_add(BOB64_SHELL_COMPLETIONS *matches,const char *name) {
if(!starts_with_case_insensitive(name,matches->Prefix,matches->PrefixLength))
return;
if(matches->Count<sizeof(matches->Names)/sizeof(matches->Names[0]))
matches->Names[matches->Count]=name;
matches->Count++;
}
static int completion_add_file(void *context,const char *name,usize length) {
BOB64_SHELL_COMPLETIONS *matches=(BOB64_SHELL_COMPLETIONS *)context;
(void)length;
completion_add(matches,name);
return matches->Count>sizeof(matches->Names)/sizeof(matches->Names[0]);
}
static void shell_complete(BOB64_SHELL *shell) {
static const char *commands[]={"help","clear","mem","heap","version",
"save","restore","ls","cat","write","rm","run","cc","echo"};
BOB64_SHELL_COMPLETIONS matches={0};
const char *prefix=shell->Line;
usize prefix_length=shell->Length;
int complete_file=0;
usize command_length=0;
while(command_length<shell->Length&&shell->Line[command_length]!=' ')
command_length++;
if(command_length<shell->Length) {
usize start=command_length;
while(start<shell->Length&&shell->Line[start]==' ')start++;
int file_command=(command_length==3&&lower_ascii(shell->Line[0])=='c'&&
lower_ascii(shell->Line[1])=='a'&&lower_ascii(shell->Line[2])=='t')||
(command_length==2&&lower_ascii(shell->Line[0])=='r'&&
lower_ascii(shell->Line[1])=='m')||
(command_length==3&&lower_ascii(shell->Line[0])=='r'&&
lower_ascii(shell->Line[1])=='u'&&lower_ascii(shell->Line[2])=='n')||
(command_length==2&&lower_ascii(shell->Line[0])=='c'&&
lower_ascii(shell->Line[1])=='c');
if(!file_command)return;
for(usize i=start;i<shell->Length;i++)if(shell->Line[i]==' ')return;
prefix=shell->Line+start;prefix_length=shell->Length-start;
complete_file=1;
}
matches.Prefix=prefix;matches.PrefixLength=prefix_length;
if(complete_file)bob64_fs_list(shell->Filesystem,completion_add_file,&matches);
else if(prefix==shell->Line) {
for(usize i=0;i<sizeof(commands)/sizeof(commands[0]);i++)
completion_add(&matches,commands[i]);
}
if(!matches.Count)return;
if(matches.Count==1) {
const char *name=matches.Names[0];
char suffix[BOB64_SHELL_LINE_CAPACITY];
usize suffix_length=0;
while(name[prefix_length+suffix_length]&&
suffix_length+1<sizeof(suffix)) {
suffix[suffix_length]=name[prefix_length+suffix_length];
suffix_length++;
}
if(suffix_length>BOB64_SHELL_LINE_CAPACITY-1-shell->Length)return;
suffix[suffix_length]=0;
for(usize i=0;i<suffix_length;i++)shell->Line[shell->Length++]=suffix[i];
shell->Line[shell->Length]=0;shell->HistoryBrowsing=0;
output(shell,suffix);
return;
}
output(shell,"\r\n");
usize shown=matches.Count<sizeof(matches.Names)/sizeof(matches.Names[0])?
matches.Count:sizeof(matches.Names)/sizeof(matches.Names[0]);
for(usize i=0;i<shown;i++) {
if(i)output(shell," ");
output(shell,matches.Names[i]);
}
output(shell,"\r\n");prompt(shell);output(shell,shell->Line);
}
static void execute_file_command(BOB64_SHELL *shell,u8 operation,char *arguments) {
BOB64_FILESYSTEM *filesystem=shell->Filesystem;
char *name=arguments,*separator=arguments,*contents_argument;
@@ -179,7 +332,9 @@ static void execute(BOB64_SHELL *shell) {
output(shell,"run NAME [ARG ...] launch a B64E application (try bob.b64e)\r\n");
output(shell,"run desktop.b64e [FILE] edit a RAM text file in the GUI\r\n");
output(shell,"cc SOURCE [OUTPUT] compile supported C to B64E (try bob.c)\r\n");
output(shell,"save checkpoint files in RAM\r\nrestore restore RAM checkpoint\r\n");
output(shell,"Up/Down command history; Tab completes commands and files\r\n");
output(shell,"save checkpoint files in RAM and firmware storage\r\n");
output(shell,"restore restore firmware or RAM checkpoint\r\n");
output(shell,"echo print text\r\nversion show kernel version\r\n");
} else if(equals(line,"clear")) {
if(shell->Clear)shell->Clear(shell->Context);
@@ -196,14 +351,30 @@ static void execute(BOB64_SHELL *shell) {
output(shell,"snapshot size failed\r\n");return;
}
void *snapshot=bob64_heap_alloc(shell->Heap,size);
if(!snapshot||bob64_fs_snapshot_write(shell->Filesystem,snapshot,size,&written)) {
if(!snapshot) {
output(shell,"snapshot allocation failed (heap full)\r\n");return;
}
if(bob64_fs_snapshot_write(shell->Filesystem,snapshot,size,&written)) {
if(snapshot)bob64_heap_free(shell->Heap,snapshot);
output(shell,"snapshot save failed (heap full)\r\n");return;
output(shell,"snapshot serialization failed\r\n");return;
}
if(shell->Snapshot)bob64_heap_free(shell->Heap,shell->Snapshot);
shell->Snapshot=snapshot;shell->SnapshotSize=written;
output(shell,"saved B64S v1 checkpoint in RAM; lost on reboot\r\n");
if(shell->SnapshotSave&&
!shell->SnapshotSave(shell->SnapshotContext,snapshot,written))
output(shell,"saved B64S v1 checkpoint to firmware storage and RAM\r\n");
else output(shell,"saved B64S v1 in RAM; firmware save failed\r\n");
} else if(equals(line,"restore")) {
if(shell->SnapshotRestore) {
int persistent_result=shell->SnapshotRestore(shell->SnapshotContext,
shell->Filesystem);
if(!persistent_result) {
output(shell,"restored B64S v1 from firmware storage\r\n");return;
}
if(persistent_result<0) {
output(shell,"firmware snapshot invalid; files unchanged\r\n");return;
}
}
if(!shell->Snapshot||bob64_fs_snapshot_restore(shell->Filesystem,
shell->Snapshot,shell->SnapshotSize)) {
output(shell,"restore failed; files unchanged\r\n");return;
@@ -246,6 +417,9 @@ int bob64_shell_init(BOB64_SHELL *shell,BOB64_PAGE_ALLOCATOR *allocator,
BOB64_SHELL_CLEAR clear,void *context) {
if(!shell||!write)return -1;
shell->Length=0;shell->IgnoreLineFeed=0;shell->Line[0]=0;
shell->HistoryCount=0;shell->HistoryIndex=0;shell->HistoryDraftLength=0;
shell->HistoryBrowsing=0;shell->HistoryDraft[0]=0;
for(usize i=0;i<BOB64_SHELL_HISTORY_LIMIT;i++)shell->History[i][0]=0;
shell->PageAllocator=allocator;shell->Heap=heap;shell->Filesystem=filesystem;
shell->Snapshot=0;shell->SnapshotSize=0;
shell->Write=write;shell->Clear=clear;shell->Context=context;
@@ -263,16 +437,29 @@ void bob64_shell_set_compiler(BOB64_SHELL *shell,BOB64_SHELL_COMPILE compile) {
if(shell)shell->Compile=compile;
}
void bob64_shell_set_snapshot_storage(BOB64_SHELL *shell,
BOB64_SHELL_SNAPSHOT_SAVE save,BOB64_SHELL_SNAPSHOT_RESTORE restore,
void *context) {
if(!shell)return;
shell->SnapshotSave=save;shell->SnapshotRestore=restore;
shell->SnapshotContext=context;
}
void bob64_shell_input(BOB64_SHELL *shell,int character) {
char echo[2];
if(!shell||!shell->Write||character<0)return;
if(character==BOB64_SHELL_INPUT_UP) {history_up(shell);return;}
if(character==BOB64_SHELL_INPUT_DOWN) {history_down(shell);return;}
if(character=='\t') {shell_complete(shell);return;}
if(character=='\n'&&shell->IgnoreLineFeed) { shell->IgnoreLineFeed=0;return; }
shell->IgnoreLineFeed=(u8)(character=='\r');
if(character=='\r'||character=='\n') {
history_store(shell);shell->HistoryBrowsing=0;
output(shell,"\r\n");execute(shell);shell->Length=0;shell->Line[0]=0;
prompt(shell);return;
}
if(character=='\b'||character==0x7f) {
shell->HistoryBrowsing=0;
if(shell->Length) {
shell->Length--;shell->Line[shell->Length]=0;
output(shell,"\b \b");
@@ -280,6 +467,7 @@ void bob64_shell_input(BOB64_SHELL *shell,int character) {
return;
}
if(character<32||character>126||shell->Length>=BOB64_SHELL_LINE_CAPACITY-1)return;
shell->HistoryBrowsing=0;
shell->Line[shell->Length++]=(char)character;
shell->Line[shell->Length]=0;
echo[0]=(char)character;echo[1]=0;output(shell,echo);
+17
View File
@@ -6,17 +6,28 @@
#define BOB64_SHELL_LINE_CAPACITY 128
#define BOB64_SHELL_ARGUMENT_LIMIT 16
#define BOB64_SHELL_HISTORY_LIMIT 8
#define BOB64_SHELL_INPUT_UP 0x10000
#define BOB64_SHELL_INPUT_DOWN 0x10001
typedef void (*BOB64_SHELL_WRITE)(void *context,const char *text);
typedef void (*BOB64_SHELL_CLEAR)(void *context);
typedef s64 (*BOB64_SHELL_RUN)(void *context,const char *name,usize argument_count,
const char *const *arguments,int *started);
typedef int (*BOB64_SHELL_COMPILE)(void *context,const char *source_name,
const char *output_name,usize *error_offset);
typedef int (*BOB64_SHELL_SNAPSHOT_SAVE)(void *context,const void *snapshot,
usize snapshot_size);
typedef int (*BOB64_SHELL_SNAPSHOT_RESTORE)(void *context,
BOB64_FILESYSTEM *filesystem);
typedef struct {
char Line[BOB64_SHELL_LINE_CAPACITY];
usize Length;
char History[BOB64_SHELL_HISTORY_LIMIT][BOB64_SHELL_LINE_CAPACITY];
char HistoryDraft[BOB64_SHELL_LINE_CAPACITY];
usize HistoryCount,HistoryIndex,HistoryDraftLength;
u8 IgnoreLineFeed;
u8 HistoryBrowsing;
BOB64_PAGE_ALLOCATOR *PageAllocator;
BOB64_HEAP *Heap;
BOB64_FILESYSTEM *Filesystem;
@@ -27,6 +38,9 @@ typedef struct {
BOB64_SHELL_RUN Run;
BOB64_SHELL_COMPILE Compile;
void *Context;
BOB64_SHELL_SNAPSHOT_SAVE SnapshotSave;
BOB64_SHELL_SNAPSHOT_RESTORE SnapshotRestore;
void *SnapshotContext;
} BOB64_SHELL;
int bob64_shell_init(BOB64_SHELL *shell,BOB64_PAGE_ALLOCATOR *allocator,
@@ -36,5 +50,8 @@ int bob64_shell_init(BOB64_SHELL *shell,BOB64_PAGE_ALLOCATOR *allocator,
void bob64_shell_input(BOB64_SHELL *shell,int character);
void bob64_shell_set_runner(BOB64_SHELL *shell,BOB64_SHELL_RUN run);
void bob64_shell_set_compiler(BOB64_SHELL *shell,BOB64_SHELL_COMPILE compile);
void bob64_shell_set_snapshot_storage(BOB64_SHELL *shell,
BOB64_SHELL_SNAPSHOT_SAVE save,BOB64_SHELL_SNAPSHOT_RESTORE restore,
void *context);
#endif
+77
View File
@@ -32,11 +32,15 @@ typedef struct {
void *FileStreamContext;
BOB64_SYSCALL_EVENT_WAIT WaitEvent;
void *WaitEventContext;
BOB64_SYSCALL_APP_RUN RunApplication;
void *AppRunnerContext;
BOB64_WINDOW_SERVER *WindowServer;
u64 WindowOwner;
const BOB64_PAGE_TABLE *PageTable;
u32 SurfaceChunk[BOB64_SYSCALL_COPY_CHUNK_BYTES/sizeof(u32)];
u8 Buffer[BOB64_SYSCALL_MAX_BUFFER];
char ArgumentStorage[BOB64_SYSCALL_MAX_ARGUMENT_BYTES];
char *Arguments[BOB64_SYSCALL_MAX_ARGUMENTS];
BOB64_FILE_INFO FileEntries[BOB64_SYSCALL_MAX_FILES];
BOB64_SYSCALL_HANDLE Handles[BOB64_SYSCALL_OPEN_HANDLES];
u64 NextHandle;
@@ -64,11 +68,15 @@ static u32 syscall_context_depth;
#define syscall_file_stream_context syscall_context.FileStreamContext
#define syscall_wait_event syscall_context.WaitEvent
#define syscall_wait_event_context syscall_context.WaitEventContext
#define syscall_run_application syscall_context.RunApplication
#define syscall_app_runner_context syscall_context.AppRunnerContext
#define syscall_window_server syscall_context.WindowServer
#define syscall_window_owner syscall_context.WindowOwner
#define syscall_page_table syscall_context.PageTable
#define syscall_surface_chunk syscall_context.SurfaceChunk
#define syscall_buffer syscall_context.Buffer
#define syscall_argument_storage syscall_context.ArgumentStorage
#define syscall_arguments syscall_context.Arguments
#define syscall_file_entries syscall_context.FileEntries
#define syscall_handles syscall_context.Handles
#define syscall_next_handle syscall_context.NextHandle
@@ -153,6 +161,12 @@ void bob64_syscall_set_wait_event(BOB64_SYSCALL_EVENT_WAIT wait_event,void *cont
syscall_wait_event_context=context;
}
void bob64_syscall_set_app_runner(BOB64_SYSCALL_APP_RUN run_application,
void *context) {
syscall_run_application=run_application;
syscall_app_runner_context=context;
}
void bob64_syscall_set_window_server(BOB64_WINDOW_SERVER *server,u64 owner) {
syscall_window_server=server;
syscall_window_owner=server?owner:0;
@@ -202,6 +216,69 @@ u64 BOB64_MS_ABI bob64_syscall_dispatch(BOB64_INTERRUPT_FRAME *frame) {
frame->RAX=bob64_timer_ticks();
return 0;
}
if(frame->RAX==BOB64_SYSCALL_RUN_APPLICATION) {
char name[BOB64_SYSCALL_MAX_FILENAME+1];
u64 name_address=frame->RCX,name_length=frame->RDX;
u64 status_address=frame->R8;
u64 argument_count=frame->RSI,argument_vector=frame->R9;
usize argument_bytes=0;
s64 exit_status=0;
if(!syscall_run_application||!syscall_read_user||!syscall_write_user) {
frame->RAX=(u64)-38;return 0;
}
if(!name_length||name_length>BOB64_SYSCALL_MAX_FILENAME) {
frame->RAX=(u64)-22;return 0;
}
if(argument_count>BOB64_SYSCALL_MAX_ARGUMENTS||
(argument_count&&!argument_vector)) {frame->RAX=(u64)-22;return 0;}
if(syscall_validate_user_range(syscall_page_table,name_address,name_length,
BOB64_PAGE_USER,BOB64_SYSCALL_MAX_BUFFER)||
syscall_validate_user_range(syscall_page_table,status_address,
sizeof(exit_status),BOB64_PAGE_USER|BOB64_PAGE_WRITE,
sizeof(exit_status))||
syscall_read_user(syscall_read_user_context,name_address,name,
(usize)name_length)) {
frame->RAX=(u64)-14;return 0;
}
name[name_length]=0;
if(argument_count) {
u64 vector_bytes=argument_count*sizeof(u64);
if(syscall_validate_user_range(syscall_page_table,argument_vector,
vector_bytes,BOB64_PAGE_USER,BOB64_SYSCALL_MAX_ARGUMENT_BYTES)) {
frame->RAX=(u64)-14;return 0;
}
for(usize i=0;i<(usize)argument_count;i++) {
u64 string_address=0;
int terminated=0;
if(syscall_read_user(syscall_read_user_context,
argument_vector+i*sizeof(u64),&string_address,sizeof(u64))||
!string_address) {frame->RAX=(u64)-14;return 0;}
syscall_arguments[i]=syscall_argument_storage+argument_bytes;
while(argument_bytes<sizeof(syscall_context.ArgumentStorage)) {
char character;
if(syscall_validate_user_range(syscall_page_table,
string_address,1,BOB64_PAGE_USER,
BOB64_SYSCALL_MAX_ARGUMENT_BYTES)||
syscall_read_user(syscall_read_user_context,string_address,
&character,1)) {frame->RAX=(u64)-14;return 0;}
string_address++;
syscall_argument_storage[argument_bytes++]=character;
if(!character){terminated=1;break;}
}
if(!terminated) {frame->RAX=(u64)-7;return 0;}
}
}
int result=syscall_run_application(syscall_app_runner_context,name,
(usize)argument_count,
(const char *const *)syscall_arguments,
&exit_status);
if(result) {frame->RAX=(u64)(result<0?result:-5);return 0;}
if(syscall_write_user(syscall_write_user_context,status_address,
&exit_status,sizeof(exit_status))) {
frame->RAX=(u64)-14;return 0;
}
frame->RAX=0;return 0;
}
if(frame->RAX==BOB64_SYSCALL_WRITE_CHAR) {
if(!syscall_write_character) {
frame->RAX=(u64)-1;
+11
View File
@@ -20,6 +20,11 @@ typedef struct {
_Static_assert(sizeof(BOB64_USER_RETURN_FRAME)==40,
"assembly user-return frame layout");
_Static_assert(__builtin_offsetof(BOB64_USER_RETURN_FRAME,ReturnValue)==8&&
__builtin_offsetof(BOB64_USER_RETURN_FRAME,PreviousReturnValue)==16&&
__builtin_offsetof(BOB64_USER_RETURN_FRAME,PreviousInterruptState)==24&&
__builtin_offsetof(BOB64_USER_RETURN_FRAME,PreviousActive)==32,
"assembly user-return frame offsets");
typedef void (*BOB64_SYSCALL_WRITE)(void *context,u8 character);
typedef int (*BOB64_SYSCALL_READ_USER)(void *context,u64 address,
@@ -39,6 +44,10 @@ typedef s64 (*BOB64_SYSCALL_FILE_READ_AT)(void *context,const char *name,u64 off
typedef s64 (*BOB64_SYSCALL_FILE_WRITE_AT)(void *context,const char *name,u64 offset,
const u8 *buffer,usize length);
typedef int (*BOB64_SYSCALL_EVENT_WAIT)(void *context,BOB64_EVENT *event);
typedef int (*BOB64_SYSCALL_APP_RUN)(void *context,const char *name,
usize argument_count,
const char *const *arguments,
s64 *exit_status);
extern volatile u64 bob64_user_active;
extern volatile u64 bob64_user_depth;
@@ -58,6 +67,8 @@ void bob64_syscall_set_file_stream(BOB64_SYSCALL_FILE_OPEN open_file,
BOB64_SYSCALL_FILE_WRITE_AT write_at,
void *context);
void bob64_syscall_set_wait_event(BOB64_SYSCALL_EVENT_WAIT wait_event,void *context);
void bob64_syscall_set_app_runner(BOB64_SYSCALL_APP_RUN run_application,
void *context);
void bob64_syscall_set_window_server(BOB64_WINDOW_SERVER *server,u64 owner);
void bob64_syscall_set_address_space(const BOB64_PAGE_TABLE *page_table);
/* Nested kernel app runs save and restore the complete syscall service state. */
+190
View File
@@ -0,0 +1,190 @@
#ifndef BOB64_WIDGETS_H
#define BOB64_WIDGETS_H
#include "gfx.h"
typedef struct {
s32 X,Y;
u32 Width,Height;
} BOB64_RECT;
typedef struct {
u8 Hovered,Pressed;
} BOB64_BUTTON_STATE;
typedef struct {
char *Buffer;
usize Capacity,Length,Cursor,Scroll;
u8 Focused,Dirty;
} BOB64_TEXT_FIELD;
#define BOB64_BUTTON_LEFT 1u
static inline int bob64_rect_contains(const BOB64_RECT *rect,s32 x,s32 y) {
return rect&&rect->Width&&rect->Height&&x>=rect->X&&y>=rect->Y&&
(s64)x<(s64)rect->X+rect->Width&&
(s64)y<(s64)rect->Y+rect->Height;
}
/* Returns one only when a left-button press is released inside the rectangle. */
static inline int bob64_button_event(const BOB64_RECT *rect,
BOB64_BUTTON_STATE *state,const BOB64_EVENT *event) {
int inside;
if(!rect||!state||!event)return 0;
inside=bob64_rect_contains(rect,event->X,event->Y);
if(event->Type==BOB64_EVENT_MOUSE_MOVE)state->Hovered=(u8)inside;
else if(event->Type==BOB64_EVENT_MOUSE_BUTTON) {
state->Hovered=(u8)inside;
if(event->Buttons&BOB64_BUTTON_LEFT)
state->Pressed=(u8)inside;
else {
int clicked=state->Pressed&&inside;
state->Pressed=0;
return clicked;
}
}
return 0;
}
static inline int bob64_button_draw(BOB64_GFX *graphics,const BOB64_RECT *rect,
const char *label,const BOB64_BUTTON_STATE *state) {
u32 background,border;
usize length=0;
s32 text_x,text_y;
if(!graphics||!rect||!label||!state||rect->Width<8||rect->Height<10||
rect->Width>0x7fffffffu||rect->Height>0x7fffffffu||
rect->X>0x7fffffff-(s32)(rect->Width-1)||
rect->Y>0x7fffffff-(s32)(rect->Height-1))return -1;
background=state->Pressed&&state->Hovered?0x001f4067u:
(state->Hovered?0x004b78a8u:0x00335d8cu);
border=state->Hovered?0x00d6ecffu:0x007fa3c4u;
bob64_gfx_fill_rect(graphics,rect->X,rect->Y,rect->Width,rect->Height,
background);
bob64_gfx_line(graphics,rect->X,rect->Y,
rect->X+(s32)rect->Width-1,rect->Y,border);
bob64_gfx_line(graphics,rect->X,rect->Y+(s32)rect->Height-1,
rect->X+(s32)rect->Width-1,rect->Y+(s32)rect->Height-1,border);
bob64_gfx_line(graphics,rect->X,rect->Y,rect->X,
rect->Y+(s32)rect->Height-1,border);
bob64_gfx_line(graphics,rect->X+(s32)rect->Width-1,rect->Y,
rect->X+(s32)rect->Width-1,rect->Y+(s32)rect->Height-1,border);
while(label[length]&&length<(rect->Width-1)/6)length++;
if(label[length])return -1;
usize text_width=length?length*6-1:0;
if(text_width>rect->Width-2)return -1;
text_x=rect->X+((s32)rect->Width-(s32)text_width)/2;
text_y=rect->Y+((s32)rect->Height-7)/2;
bob64_gfx_text(graphics,text_x,text_y,label,0x00ffffffu,1);
return 0;
}
static inline int bob64_text_field_sync(BOB64_TEXT_FIELD *field) {
usize length=0;
if(!field||!field->Buffer||!field->Capacity)return -1;
while(length<field->Capacity&&field->Buffer[length])length++;
if(length==field->Capacity)return -1;
field->Length=length;field->Cursor=length;field->Scroll=0;field->Dirty=0;
return 0;
}
static inline int bob64_text_field_init(BOB64_TEXT_FIELD *field,char *buffer,
usize capacity) {
if(!field)return -1;
field->Buffer=buffer;field->Capacity=capacity;field->Focused=0;
return bob64_text_field_sync(field);
}
static inline void bob64_text_field_reveal(BOB64_TEXT_FIELD *field,
usize visible_columns) {
if(!field)return;
if(!visible_columns)visible_columns=1;
if(field->Cursor<field->Scroll)field->Scroll=field->Cursor;
else if(field->Cursor>=field->Scroll+visible_columns)
field->Scroll=field->Cursor-visible_columns+1;
}
static inline int bob64_text_field_event(BOB64_TEXT_FIELD *field,
const BOB64_RECT *rect,const BOB64_EVENT *event) {
usize visible_columns;
if(!field||!field->Buffer||!rect||!event)return 0;
visible_columns=rect->Width>6?(rect->Width-6)/6:1;
if(event->Type==BOB64_EVENT_MOUSE_BUTTON&&
(event->Buttons&BOB64_BUTTON_LEFT)) {
field->Focused=(u8)bob64_rect_contains(rect,event->X,event->Y);
if(field->Focused) {
usize column=event->X>rect->X+3?
(usize)(event->X-rect->X-3)/6:0;
field->Cursor=field->Scroll+column;
if(field->Cursor>field->Length)field->Cursor=field->Length;
return 0;
}
return 0;
}
if(event->Type!=BOB64_EVENT_KEY_DOWN||!field->Focused)return 0;
if(event->Key==(BOB64_EVENT_KEY_EXTENDED|0x4b)) {
if(field->Cursor)field->Cursor--;
} else if(event->Key==(BOB64_EVENT_KEY_EXTENDED|0x4d)) {
if(field->Cursor<field->Length)field->Cursor++;
} else if(event->Key==(BOB64_EVENT_KEY_EXTENDED|0x47))field->Cursor=0;
else if(event->Key==(BOB64_EVENT_KEY_EXTENDED|0x4f))field->Cursor=field->Length;
else if(event->Key==(BOB64_EVENT_KEY_EXTENDED|0x53)) {
if(field->Cursor>=field->Length)return 0;
for(usize i=field->Cursor;i<field->Length;i++)
field->Buffer[i]=field->Buffer[i+1];
field->Length--;field->Dirty=1;
} else if(event->Character=='\b') {
if(!field->Cursor)return 0;
for(usize i=field->Cursor-1;i<field->Length;i++)
field->Buffer[i]=field->Buffer[i+1];
field->Cursor--;field->Length--;field->Dirty=1;
} else if(event->Character>=32&&event->Character<=126) {
if(field->Length+1>=field->Capacity)return 0;
for(usize i=field->Length+1;i>field->Cursor;i--)
field->Buffer[i]=field->Buffer[i-1];
field->Buffer[field->Cursor++]=(char)event->Character;
field->Length++;field->Dirty=1;
} else return 0;
field->Buffer[field->Length]=0;
bob64_text_field_reveal(field,visible_columns);
return 1;
}
static inline int bob64_text_field_draw(BOB64_GFX *graphics,
const BOB64_RECT *rect,const BOB64_TEXT_FIELD *field) {
char visible[256];
usize columns,length=0;
u32 border;
if(!graphics||!rect||!field||!field->Buffer||rect->Width<12||
rect->Height<10||rect->Width>sizeof(visible)*6u+6u||
rect->Width>0x7fffffffu||rect->Height>0x7fffffffu||
rect->X>0x7fffffff-(s32)(rect->Width-1)||
rect->Y>0x7fffffff-(s32)(rect->Height-1))return -1;
columns=(rect->Width-6)/6;
if(columns>=sizeof(visible))columns=sizeof(visible)-1;
while(length<columns&&field->Scroll+length<field->Length) {
visible[length]=field->Buffer[field->Scroll+length];length++;
}
visible[length]=0;
border=field->Focused?0x00d6ecffu:0x007fa3c4u;
bob64_gfx_fill_rect(graphics,rect->X,rect->Y,rect->Width,rect->Height,
0x001a2a3cu);
bob64_gfx_line(graphics,rect->X,rect->Y,
rect->X+(s32)rect->Width-1,rect->Y,border);
bob64_gfx_line(graphics,rect->X,rect->Y+(s32)rect->Height-1,
rect->X+(s32)rect->Width-1,rect->Y+(s32)rect->Height-1,border);
bob64_gfx_line(graphics,rect->X,rect->Y,rect->X,
rect->Y+(s32)rect->Height-1,border);
bob64_gfx_line(graphics,rect->X+(s32)rect->Width-1,rect->Y,
rect->X+(s32)rect->Width-1,rect->Y+(s32)rect->Height-1,border);
bob64_gfx_text(graphics,rect->X+3,rect->Y+((s32)rect->Height-7)/2,
visible,0x00e2ebf5u,1);
if(field->Focused&&field->Cursor>=field->Scroll&&
field->Cursor-field->Scroll<=columns) {
s32 cursor_x=rect->X+3+(s32)((field->Cursor-field->Scroll)*6);
bob64_gfx_line(graphics,cursor_x,rect->Y+3,cursor_x,
rect->Y+(s32)rect->Height-4,0x00ffffffu);
}
return 0;
}
#endif
BIN
View File
Binary file not shown.
+1092 -36
View File
File diff suppressed because it is too large. Load diff
+64 -4
View File
@@ -62,6 +62,48 @@ static unsigned char *read_file(const char *path,size_t *length) {
}
*length=(size_t)size;return bytes;
}
/* Put a trailing zero-fill section after PE's final file-backed sections. */
static int bss_layout_arguments(const unsigned char *pe,size_t pe_size,
char *arguments,size_t capacity) {
uint32_t pe_offset,alignment,bss_rva=0,bss_size=0,bss_raw=0;
uint32_t idata_rva=0,idata_size=0,idata_raw=0;
uint16_t section_count,optional_size;
uint64_t image_base,idata_address,bss_address;
size_t section_table;
if(!pe||!arguments||!capacity||pe_size<64||pe[0]!='M'||pe[1]!='Z')return -1;
arguments[0]=0;pe_offset=read32(pe+0x3c);
if((uint64_t)pe_offset+24>pe_size||memcmp(pe+pe_offset,"PE\0\0",4))return -1;
const unsigned char *coff=pe+pe_offset+4;
section_count=read16(coff+2);optional_size=read16(coff+16);
if(!section_count||section_count>32||optional_size<112||
(uint64_t)pe_offset+24+optional_size>pe_size)return -1;
const unsigned char *optional=coff+20;
image_base=read64(optional+24);alignment=read32(optional+32);
if(read16(optional)!=0x20b||!alignment||
(uint64_t)pe_offset+24+optional_size>pe_size)return -1;
section_table=(size_t)pe_offset+24+optional_size;
if(section_count>(pe_size-section_table)/40)return -1;
for(uint16_t i=0;i<section_count;i++) {
const unsigned char *section=pe+section_table+(size_t)i*40;
uint32_t virtual_size=read32(section+8),rva=read32(section+12);
uint32_t raw_size=read32(section+16);
if(!memcmp(section,".bss",4)) {
bss_rva=rva;bss_size=virtual_size;bss_raw=raw_size;
} else if(!memcmp(section,".idata",6)) {
idata_rva=rva;idata_size=virtual_size;idata_raw=raw_size;
}
}
if(!bss_size||bss_raw||!idata_size||idata_rva<=bss_rva)return 0;
if((idata_size>alignment?idata_size:idata_raw)>alignment||
image_base>UINT64_MAX-bss_rva-alignment)return -1;
idata_address=image_base+bss_rva;
bss_address=idata_address+alignment;
int length=snprintf(arguments,capacity,
"-Wl,--section-start,.idata=0x%llx -Wl,--section-start,.bss=0x%llx",
(unsigned long long)idata_address,(unsigned long long)bss_address);
return length<0||(size_t)length>=capacity?-1:1;
}
static int write_b64e(const char *path,const unsigned char *pe,size_t pe_size,
const unsigned char *payload,size_t payload_size) {
uint32_t pe_offset,entry_rva,section_alignment,size_of_image;
@@ -148,7 +190,7 @@ static int quote(char *out,size_t capacity,const char *value) {
int main(int argc,char **argv) {
const char *compiler=getenv("BOB64_CC"),*objcopy=getenv("BOB64_OBJCOPY");
char q_source[4096],q_output[4096];
char command[16384],exe_path[256],bin_path[256];
char command[16384],section_arguments[192],exe_path[256],bin_path[256];
size_t pe_size=0,payload_size=0;
unsigned char *pe=NULL,*payload=NULL;
int result=1;
@@ -174,17 +216,35 @@ int main(int argc,char **argv) {
quote(q_entry,sizeof(q_entry),"bob64/app_entry.S")) {
fprintf(stderr,"bob64cc: temporary path too long\n");return 2;
}
section_arguments[0]=0;
snprintf(command,sizeof(command),
"%s -I. -DBOB64_UEFI_ABI -std=c11 -O2 -Wall -Wextra -Werror -ffreestanding "
"-fno-builtin -fno-stack-protector -fno-stack-check -fno-unwind-tables "
"-fno-asynchronous-unwind-tables -fPIC -mno-red-zone -nostdlib bob64/libc.c %s %s "
"-Wl,--image-base,0x3ffffff000 -Wl,--disable-dynamicbase "
"%s -Wl,--image-base,0x3ffffff000 -Wl,--disable-dynamicbase "
"-Wl,--disable-reloc-section -Wl,-e,bob64_app_entry -o %s",
compiler,q_entry,q_source,q_exe);
compiler,q_entry,q_source,section_arguments,q_exe);
if(system(command)!=0)goto done;
pe=read_file(exe_path,&pe_size);
int layout_result=pe?bss_layout_arguments(pe,pe_size,section_arguments,
sizeof(section_arguments)):-1;
if(layout_result<0)goto done;
if(layout_result>0) {
free(pe);pe=NULL;
snprintf(command,sizeof(command),
"%s -I. -DBOB64_UEFI_ABI -std=c11 -O2 -Wall -Wextra -Werror -ffreestanding "
"-fno-builtin -fno-stack-protector -fno-stack-check -fno-unwind-tables "
"-fno-asynchronous-unwind-tables -fPIC -mno-red-zone -nostdlib bob64/libc.c %s %s "
"%s -Wl,--image-base,0x3ffffff000 -Wl,--disable-dynamicbase "
"-Wl,--disable-reloc-section -Wl,-e,bob64_app_entry -o %s",
compiler,q_entry,q_source,section_arguments,q_exe);
if(system(command)!=0)goto done;
pe=read_file(exe_path,&pe_size);
if(!pe)goto done;
}
snprintf(command,sizeof(command),"%s -O binary %s %s",objcopy,q_exe,q_bin);
if(system(command)!=0)goto done;
pe=read_file(exe_path,&pe_size);payload=read_file(bin_path,&payload_size);
payload=read_file(bin_path,&payload_size);
if(!pe||!payload||write_b64e(argv[2],pe,pe_size,payload,payload_size))goto done;
result=0;
done:
+14 -4
View File
@@ -12,6 +12,7 @@
#define BOB64_HANDOFF_BOOT_PATH "build\\bob64-handoff\\EFI\\BOOT\\BOOTX64.EFI"
#define BOB_COMMAND "bob.exe"
#define BOB32_COMMAND "bob32.exe"
#define BOB64_TEST_THREAD_FLAGS ""
#else
#define EXE ""
#define BUILD_DIR "./build/"
@@ -19,6 +20,7 @@
#define BOB64_HANDOFF_BOOT_PATH "build/bob64-handoff/EFI/BOOT/BOOTX64.EFI"
#define BOB_COMMAND "./bob"
#define BOB32_COMMAND "./bob32"
#define BOB64_TEST_THREAD_FLAGS "-pthread "
#endif
static void run(const char *command) {
@@ -42,6 +44,14 @@ static void build_bob64(int handoff) {
run(BUILD_DIR "bob64cc" EXE " apps/bob64_smoke.c build/bob64-app/smoke.b64e");
run(BUILD_DIR "bob64cc" EXE " apps/bob64_display.c build/bob64-app/display.b64e");
run(BUILD_DIR "bob64cc" EXE " apps/bob64_gui.c build/bob64-app/gui.b64e");
run(BUILD_DIR "bob64cc" EXE " apps/bob64_nested_smoke.c build/bob64-app/nested-smoke.b64e");
run(BUILD_DIR "bob64cc" EXE " apps/bob64_echo.c build/bob64-app/echo.b64e");
run(BUILD_DIR "bob64cc" EXE " apps/bob64_ls.c build/bob64-app/ls.b64e");
run(BUILD_DIR "bob64cc" EXE " apps/bob64_cat.c build/bob64-app/cat.b64e");
run(BUILD_DIR "bob64cc" EXE " apps/bob64_notes.c build/bob64-app/notes.b64e");
run(BUILD_DIR "bob64cc" EXE " apps/bob64_info.c build/bob64-app/info.b64e");
run(BUILD_DIR "bob64cc" EXE " apps/bob64_mouse_smoke.c build/bob64-app/mouse-smoke.b64e");
run(BUILD_DIR "bob64cc" EXE " apps/bob64_launcher.c build/bob64-app/launcher.b64e");
ensure_directory(handoff?"build/bob64-handoff":"build/bob64");
if(handoff) {
ensure_directory("build/bob64-handoff/EFI");
@@ -57,7 +67,7 @@ static void build_bob64(int handoff) {
compiler="x86_64-w64-mingw32-gcc";
#endif
}
if(snprintf(command,sizeof(command),"%s -std=c11 -O2 -Wall -Wextra -Werror -DBOB64_UEFI_ABI %s-ffreestanding -fno-stack-protector -fno-stack-check -fshort-wchar -mno-red-zone -nostdlib -Wl,--subsystem,10 -Wl,-e,efi_main -Wl,--image-base,0x100000 -Wl,--enable-reloc-section -Wl,--dynamicbase -Wl,--file-alignment,0x200 -Wl,--section-alignment,0x1000 bob64/boot.c bob64/memory.c bob64/paging.c bob64/cpu.c bob64/descriptors.c bob64/interrupts.c bob64/interrupts.S bob64/syscall.c bob64/window_server.c bob64/bootstrap.c bob64/kernel.c bob64/console.c bob64/heap.c bob64/keyboard.c bob64/mouse.c bob64/shell.c bob64/filesystem.c bob64/snapshot.c bob64/exec.c bob64/process.c bob64/compiler.c bob64/embedded_app.S bob64/handoff.S -o %s",compiler,handoff_define,output_path)>=(int)sizeof(command)) {
if(snprintf(command,sizeof(command),"%s -std=c11 -O2 -Wall -Wextra -Werror -DBOB64_UEFI_ABI %s-ffreestanding -fno-stack-protector -fno-stack-check -fshort-wchar -mno-red-zone -nostdlib -Wl,--subsystem,10 -Wl,-e,efi_main -Wl,--image-base,0x100000 -Wl,--enable-reloc-section -Wl,--dynamicbase -Wl,--file-alignment,0x200 -Wl,--section-alignment,0x1000 bob64/boot.c bob64/memory.c bob64/paging.c bob64/cpu.c bob64/descriptors.c bob64/interrupts.c bob64/interrupts.S bob64/syscall.c bob64/window_server.c bob64/bootstrap.c bob64/kernel.c bob64/console.c bob64/heap.c bob64/keyboard.c bob64/mouse.c bob64/shell.c bob64/filesystem.c bob64/snapshot.c bob64/lz4.c bob64/firmware_store.c bob64/exec.c bob64/process.c bob64/compiler.c bob64/embedded_app.S bob64/handoff.S -o %s",compiler,handoff_define,output_path)>=(int)sizeof(command)) {
fprintf(stderr,"bob64 compiler command is too long\n");exit(1);
}
run(command);
@@ -88,9 +98,9 @@ int main(int argc,char **argv) {
if(bob64Only) {
build_bob64(bob64Handoff);
if(bob64Test) {
run("gcc -std=c11 -O2 -Wall -Wextra -Werror tests/test_bob64.c bob64/libc.c bob64/compiler.c bob64/memory.c bob64/paging.c bob64/cpu.c bob64/descriptors.c bob64/interrupts.c bob64/interrupts.S bob64/syscall.c bob64/window_server.c bob64/bootstrap.c bob64/console.c bob64/heap.c bob64/keyboard.c bob64/mouse.c bob64/shell.c bob64/filesystem.c bob64/snapshot.c bob64/exec.c bob64/process.c -o build/test_bob64" EXE);
if(bob64Handoff) run(BUILD_DIR "test_bob64" EXE " " BOB64_HANDOFF_BOOT_PATH " build/bob64-app/smoke.b64e build/bob64-app/display.b64e build/bob64-app/gui.b64e");
else run(BUILD_DIR "test_bob64" EXE " " BOB64_BOOT_PATH " build/bob64-app/smoke.b64e build/bob64-app/display.b64e build/bob64-app/gui.b64e");
run("gcc -std=c11 -O2 -Wall -Wextra -Werror " BOB64_TEST_THREAD_FLAGS "tests/test_bob64.c bob64/libc.c bob64/compiler.c bob64/memory.c bob64/paging.c bob64/cpu.c bob64/descriptors.c bob64/interrupts.c bob64/interrupts.S bob64/syscall.c bob64/window_server.c bob64/bootstrap.c bob64/console.c bob64/lz4.c bob64/firmware_store.c bob64/heap.c bob64/keyboard.c bob64/mouse.c bob64/shell.c bob64/filesystem.c bob64/snapshot.c bob64/exec.c bob64/process.c -o build/test_bob64" EXE);
if(bob64Handoff) run(BUILD_DIR "test_bob64" EXE " " BOB64_HANDOFF_BOOT_PATH " build/bob64-app/smoke.b64e build/bob64-app/display.b64e build/bob64-app/gui.b64e build/bob64-app/nested-smoke.b64e build/bob64-app/echo.b64e build/bob64-app/ls.b64e build/bob64-app/cat.b64e build/bob64-app/notes.b64e build/bob64-app/info.b64e build/bob64-app/mouse-smoke.b64e build/bob64-app/launcher.b64e");
else run(BUILD_DIR "test_bob64" EXE " " BOB64_BOOT_PATH " build/bob64-app/smoke.b64e build/bob64-app/display.b64e build/bob64-app/gui.b64e build/bob64-app/nested-smoke.b64e build/bob64-app/echo.b64e build/bob64-app/ls.b64e build/bob64-app/cat.b64e build/bob64-app/notes.b64e build/bob64-app/info.b64e build/bob64-app/mouse-smoke.b64e build/bob64-app/launcher.b64e");
}
return 0;
}
+525 -5
View File
@@ -3,6 +3,7 @@ param(
[string]$QemuPath,
[Parameter(Mandatory = $true)]
[string]$OvmfCodePath,
[string]$OvmfVarsPath,
[string]$ImageRoot = (Join-Path (Split-Path -Parent $PSScriptRoot) 'build\bob64-handoff'),
[int]$TimeoutSeconds = 45
)
@@ -11,16 +12,29 @@ $ErrorActionPreference = 'Stop'
$requiredMarkers = @(
'bob64: long mode active',
'bob64: exiting UEFI boot services',
'bob64 kernel: dynamic page-table pool passed',
'bob64 kernel: ring-3 bob! app passed',
'bob64 kernel: native streaming app passed',
'bob64 kernel: nested app return passed',
'bob64 kernel: native echo arguments passed',
'bob64 kernel: native file-read app passed',
'bob64 kernel: native file-list app passed',
'bob64 kernel: large notes streaming copy passed',
'bob64 kernel: native notes app passed',
'bob64 kernel: native info app passed',
'bob64 kernel: read-only code protection passed',
'bob64 kernel: non-executable data protection passed',
'bob64 kernel: memory checks passed',
'bob64 kernel: timer IRQ enabled',
'bob64 kernel: timer tick passed',
'bob64 kernel: keyboard IRQ enabled',
'bob64 kernel: PS/2 mouse IRQ enabled',
'bob64! kernel shell; type help'
)
$persistentMarker = 'bob64 kernel: persistent B64S smoke file passed'
$mouseMarker = 'bob64 live mouse event passed'
$shellMarker = 'bob64! kernel shell; type help'
$shellPromptMarker = 'bob64> '
foreach ($path in @($QemuPath, $OvmfCodePath, $ImageRoot)) {
if (-not (Test-Path -LiteralPath $path)) {
@@ -34,25 +48,107 @@ if (-not (Test-Path -LiteralPath $efiPath)) {
}
$qemuDirectory = Split-Path -Parent (Resolve-Path -LiteralPath $QemuPath).Path
$shareDirectory = Join-Path $qemuDirectory 'share'
if (-not (Test-Path -LiteralPath $shareDirectory -PathType Container)) {
throw "QEMU's share directory does not exist: $shareDirectory"
$shareCandidates = @(
(Join-Path $qemuDirectory 'share'),
(Join-Path $qemuDirectory '..\share\qemu'),
(Join-Path $qemuDirectory '..\share')
)
$shareDirectory = $null
foreach ($candidate in $shareCandidates) {
if (Test-Path -LiteralPath $candidate -PathType Container) {
$shareDirectory = (Resolve-Path -LiteralPath $candidate).Path
break
}
}
if (-not $shareDirectory) {
throw "QEMU's share directory was not found beside or above its executable: $qemuDirectory"
}
$imagePath = (Resolve-Path -LiteralPath $ImageRoot).Path.Replace('\', '/')
$firmwarePath = (Resolve-Path -LiteralPath $OvmfCodePath).Path
$firmwareDirectory = Split-Path -Parent (Resolve-Path -LiteralPath $OvmfCodePath).Path
if ([string]::IsNullOrWhiteSpace($OvmfVarsPath)) {
foreach ($candidate in @('OVMF_VARS.fd', 'OVMF_VARS_4M.fd',
'edk2-x86_64-vars.fd', 'edk2-i386-vars.fd')) {
$candidatePath = Join-Path $firmwareDirectory $candidate
if (Test-Path -LiteralPath $candidatePath) {
$OvmfVarsPath = $candidatePath
break
}
}
}
if ([string]::IsNullOrWhiteSpace($OvmfVarsPath) -or
-not (Test-Path -LiteralPath $OvmfVarsPath)) {
throw 'A writable OVMF variable-store template is required; pass -OvmfVarsPath.'
}
$varsTemplatePath = (Resolve-Path -LiteralPath $OvmfVarsPath).Path
$serialPath = Join-Path ([IO.Path]::GetTempPath()) ("bob64-qemu-{0}.log" -f [guid]::NewGuid())
$varsCopyPath = Join-Path ([IO.Path]::GetTempPath()) ("bob64-ovmf-vars-{0}.fd" -f [guid]::NewGuid())
Copy-Item -LiteralPath $varsTemplatePath -Destination $varsCopyPath
$portProbe = [Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback, 0)
$portProbe.Start()
$monitorPort = ([Net.IPEndPoint]$portProbe.LocalEndpoint).Port
$portProbe.Stop()
function Send-MonitorCommand([string]$command) {
$client = [Net.Sockets.TcpClient]::new()
try {
$client.Connect('127.0.0.1', $monitorPort)
$stream = $client.GetStream()
$stream.ReadTimeout = 3000
$buffer = New-Object byte[] 1024
$response = [Text.StringBuilder]::new()
while (-not $response.ToString().Contains('(qemu)')) {
$count = $stream.Read($buffer, 0, $buffer.Length)
if ($count -le 0) { break }
[void]$response.Append([Text.Encoding]::ASCII.GetString($buffer, 0, $count))
}
$bytes = [Text.Encoding]::ASCII.GetBytes($command + "`n")
$stream.Write($bytes, 0, $bytes.Length)
$stream.Flush()
$response.Clear() | Out-Null
while (-not $response.ToString().Contains('(qemu)')) {
$count = $stream.Read($buffer, 0, $buffer.Length)
if ($count -le 0) { break }
[void]$response.Append([Text.Encoding]::ASCII.GetString($buffer, 0, $count))
}
}
finally {
$client.Dispose()
}
}
function Send-GuestText([string]$text) {
$client = [Net.Sockets.TcpClient]::new()
try {
$client.Connect('127.0.0.1', $monitorPort)
$stream = $client.GetStream()
foreach ($character in $text.ToCharArray()) {
if ($character -eq ' ') { $key = 'spc' }
elseif ($character -eq '.') { $key = 'dot' }
else { $key = [string]$character }
$bytes = [Text.Encoding]::ASCII.GetBytes("sendkey $key`n")
$stream.Write($bytes, 0, $bytes.Length)
$stream.Flush()
Start-Sleep -Milliseconds 125
}
$bytes = [Text.Encoding]::ASCII.GetBytes("sendkey ret`n")
$stream.Write($bytes, 0, $bytes.Length)
$stream.Flush()
Start-Sleep -Milliseconds 250
}
finally {
$client.Dispose()
}
}
$arguments = @(
'-machine', 'q35', '-m', '512M', '-cpu', 'max', '-L', $shareDirectory,
'-drive', "if=pflash,format=raw,unit=0,file=$firmwarePath,readonly=on",
'-drive', "if=pflash,format=raw,unit=1,file=$varsCopyPath",
'-drive', "format=raw,file=fat:rw:$imagePath",
'-boot', 'order=c', '-display', 'none', '-serial', "file:$serialPath",
'-monitor', "tcp:127.0.0.1:$monitorPort,server=on,wait=off", '-no-reboot'
'-monitor', "tcp:127.0.0.1:$monitorPort,server=on,wait=off"
)
$startInfo = [Diagnostics.ProcessStartInfo]::new()
@@ -68,6 +164,16 @@ try {
$process = [Diagnostics.Process]::Start($startInfo)
$deadline = [DateTime]::UtcNow.AddSeconds($TimeoutSeconds)
$serialText = ''
$mouseSmokeStarted = $false
$graphicsSmokeStarted = $false
$nativeLauncherSmokeStarted = $false
$compilerSmokeStarted = $false
$launcherSmokeStarted = $false
$restoredCompiledAppChecked = $false
$restoredDesktopChecked = $false
$snapshotSaved = $false
$persistentMarkerCountBeforeReset = 0
$shellMarkerCountBeforeReset = 0
while ([DateTime]::UtcNow -lt $deadline) {
if (Test-Path -LiteralPath $serialPath) {
$serialText = [string](Get-Content -LiteralPath $serialPath -Raw)
@@ -78,11 +184,422 @@ try {
break
}
}
if ($allPresent) {
if ($allPresent -and -not $mouseSmokeStarted) {
Send-MonitorCommand 'mouse_move 32 0'
Send-GuestText 'run mousesmoke.b64e'
$mouseDeadline = [DateTime]::UtcNow.AddSeconds(10)
do {
Start-Sleep -Milliseconds 100
$serialText = [string](Get-Content -LiteralPath $serialPath -Raw)
} while ([DateTime]::UtcNow -lt $mouseDeadline -and
-not $serialText.Contains($mouseMarker))
if (-not $serialText.Contains($mouseMarker)) {
throw "The live mouse IRQ smoke app did not receive a mouse-move event.`n$serialText"
}
$mouseSmokeStarted = $true
}
if ($allPresent -and $mouseSmokeStarted -and -not $graphicsSmokeStarted) {
$bobMarkerCountBeforeGraphics =
[regex]::Matches($serialText, [regex]::Escape('bob!')).Count
$shellMarkerCountBeforeGraphics =
[regex]::Matches($serialText, [regex]::Escape($shellPromptMarker)).Count
$exitMarkerCountBeforeGraphics = [regex]::Matches($serialText,
[regex]::Escape('application exit status=0x0000000000000000')).Count
Send-GuestText 'run display.b64e'
$graphicsDeadline = [DateTime]::UtcNow.AddSeconds(15)
do {
Start-Sleep -Milliseconds 100
$serialText = [string](Get-Content -LiteralPath $serialPath -Raw)
$bobMarkerCount =
[regex]::Matches($serialText, [regex]::Escape('bob!')).Count
} while ([DateTime]::UtcNow -lt $graphicsDeadline -and
$bobMarkerCount -le $bobMarkerCountBeforeGraphics)
if ($bobMarkerCount -le $bobMarkerCountBeforeGraphics) {
throw "The native graphics demo did not present its surface and print bob!.`n$serialText"
}
Send-MonitorCommand 'sendkey x'
$graphicsExitDeadline = [DateTime]::UtcNow.AddSeconds(10)
do {
Start-Sleep -Milliseconds 100
$serialText = [string](Get-Content -LiteralPath $serialPath -Raw)
$shellMarkerCount = [regex]::Matches($serialText,
[regex]::Escape($shellPromptMarker)).Count
$exitMarkerCount = [regex]::Matches($serialText,
[regex]::Escape('application exit status=0x0000000000000000')).Count
} while ([DateTime]::UtcNow -lt $graphicsExitDeadline -and
($shellMarkerCount -le $shellMarkerCountBeforeGraphics -or
$exitMarkerCount -le $exitMarkerCountBeforeGraphics))
if ($shellMarkerCount -le $shellMarkerCountBeforeGraphics -or
$exitMarkerCount -le $exitMarkerCountBeforeGraphics) {
throw "The native graphics demo did not return cleanly to the shell on X.`n$serialText"
}
$graphicsSmokeStarted = $true
}
if ($allPresent -and $graphicsSmokeStarted -and
-not $nativeLauncherSmokeStarted) {
$bobMarkerCountBeforeNativeLauncher =
[regex]::Matches($serialText, [regex]::Escape('bob!')).Count
$shellMarkerCountBeforeNativeLauncher =
[regex]::Matches($serialText,
[regex]::Escape($shellPromptMarker)).Count
$exitMarkerCountBeforeNativeLauncher = [regex]::Matches(
$serialText,
[regex]::Escape('application exit status=0x0000000000000000')).Count
Send-GuestText 'run launcher.b64e'
$nativeLauncherDeadline = [DateTime]::UtcNow.AddSeconds(10)
do {
Start-Sleep -Milliseconds 100
$serialText = [string](Get-Content -LiteralPath $serialPath -Raw)
$bobMarkerCount = [regex]::Matches($serialText,
[regex]::Escape('bob!')).Count
} while ([DateTime]::UtcNow -lt $nativeLauncherDeadline -and
$bobMarkerCount -le $bobMarkerCountBeforeNativeLauncher)
if ($bobMarkerCount -le $bobMarkerCountBeforeNativeLauncher) {
throw "The native windowed launcher did not print bob!.`n$serialText"
}
Start-Sleep -Milliseconds 300
Send-MonitorCommand 'sendkey ret'
$nativeLauncherChildDeadline = [DateTime]::UtcNow.AddSeconds(10)
do {
Start-Sleep -Milliseconds 100
$serialText = [string](Get-Content -LiteralPath $serialPath -Raw)
$bobMarkerCount = [regex]::Matches($serialText,
[regex]::Escape('bob!')).Count
} while ([DateTime]::UtcNow -lt $nativeLauncherChildDeadline -and
$bobMarkerCount -le $bobMarkerCountBeforeNativeLauncher+1)
if ($bobMarkerCount -le $bobMarkerCountBeforeNativeLauncher+1) {
throw "The native windowed launcher did not run its selected bob! app.`n$serialText"
}
# The first installed app is the interactive graphics demo;
# Escape closes that child, then a second Escape closes the
# launcher after its parent context resumes.
Start-Sleep -Milliseconds 300
Send-MonitorCommand 'sendkey esc'
Start-Sleep -Milliseconds 300
Send-MonitorCommand 'sendkey esc'
$nativeLauncherExitDeadline = [DateTime]::UtcNow.AddSeconds(10)
do {
Start-Sleep -Milliseconds 100
$serialText = [string](Get-Content -LiteralPath $serialPath -Raw)
$shellMarkerCount = [regex]::Matches($serialText,
[regex]::Escape($shellPromptMarker)).Count
$exitMarkerCount = [regex]::Matches($serialText,
[regex]::Escape('application exit status=0x0000000000000000')).Count
} while ([DateTime]::UtcNow -lt $nativeLauncherExitDeadline -and
($shellMarkerCount -le $shellMarkerCountBeforeNativeLauncher -or
$exitMarkerCount -le $exitMarkerCountBeforeNativeLauncher))
if ($shellMarkerCount -le $shellMarkerCountBeforeNativeLauncher -or
$exitMarkerCount -le $exitMarkerCountBeforeNativeLauncher) {
throw "The native windowed launcher did not close cleanly on Escape.`n$serialText"
}
$bobMarkerCountBeforeForwardedArgs = $bobMarkerCount
$shellMarkerCountBeforeForwardedArgs = $shellMarkerCount
$exitMarkerCountBeforeForwardedArgs = $exitMarkerCount
Send-GuestText 'run launcher.b64e echo.b64e argumentforwarded'
$forwardedArgsDeadline = [DateTime]::UtcNow.AddSeconds(10)
do {
Start-Sleep -Milliseconds 100
$serialText = [string](Get-Content -LiteralPath $serialPath -Raw)
$bobMarkerCount = [regex]::Matches($serialText,
[regex]::Escape('bob!')).Count
$shellMarkerCount = [regex]::Matches($serialText,
[regex]::Escape($shellPromptMarker)).Count
$exitMarkerCount = [regex]::Matches($serialText,
[regex]::Escape('application exit status=0x0000000000000000')).Count
$forwardedArgCount = [regex]::Matches($serialText,
[regex]::Escape('argumentforwarded')).Count
} while ([DateTime]::UtcNow -lt $forwardedArgsDeadline -and
($bobMarkerCount -le $bobMarkerCountBeforeForwardedArgs -or
$forwardedArgCount -lt 2 -or
$shellMarkerCount -le $shellMarkerCountBeforeForwardedArgs -or
$exitMarkerCount -le $exitMarkerCountBeforeForwardedArgs))
if ($bobMarkerCount -le $bobMarkerCountBeforeForwardedArgs -or
$forwardedArgCount -lt 2 -or
$shellMarkerCount -le $shellMarkerCountBeforeForwardedArgs -or
$exitMarkerCount -le $exitMarkerCountBeforeForwardedArgs) {
throw "The launcher did not forward argv to echo.b64e and return to the shell.`n$serialText"
}
$nativeLauncherSmokeStarted = $true
}
if ($allPresent -and $graphicsSmokeStarted -and -not $compilerSmokeStarted) {
Send-GuestText 'cc bob.c compiled.b64e'
$compileDeadline = [DateTime]::UtcNow.AddSeconds(15)
do {
Start-Sleep -Milliseconds 100
$serialText = [string](Get-Content -LiteralPath $serialPath -Raw)
} while ([DateTime]::UtcNow -lt $compileDeadline -and
-not $serialText.Contains('compiled to compiled.b64e'))
if (-not $serialText.Contains('compiled to compiled.b64e')) {
throw "The resident C compiler did not produce a B64E app.`n$serialText"
}
$bobMarkerCountBeforeRun =
[regex]::Matches($serialText, [regex]::Escape('bob!')).Count
Send-GuestText 'run compiled.b64e'
$runDeadline = [DateTime]::UtcNow.AddSeconds(10)
do {
Start-Sleep -Milliseconds 100
$serialText = [string](Get-Content -LiteralPath $serialPath -Raw)
$bobMarkerCount =
[regex]::Matches($serialText, [regex]::Escape('bob!')).Count
} while ([DateTime]::UtcNow -lt $runDeadline -and
(-not $serialText.Contains('application exit status=0x0000000000000000') -or
$bobMarkerCount -le $bobMarkerCountBeforeRun))
if (-not $serialText.Contains('application exit status=0x0000000000000000') -or
$bobMarkerCount -le $bobMarkerCountBeforeRun) {
throw "The compiled C application did not print bob! and exit successfully.`n$serialText"
}
$compilerSmokeStarted = $true
}
if ($allPresent -and $compilerSmokeStarted -and -not $launcherSmokeStarted) {
$bobMarkerCountBeforeDesktop =
[regex]::Matches($serialText, [regex]::Escape('bob!')).Count
$shellMarkerCountBeforeDesktop =
[regex]::Matches($serialText, [regex]::Escape($shellPromptMarker)).Count
$exitMarkerCountBeforeDesktop =
[regex]::Matches($serialText,
[regex]::Escape('application exit status=0x0000000000000000')).Count
Send-GuestText 'run desktop.b64e'
$desktopDeadline = [DateTime]::UtcNow.AddSeconds(10)
do {
Start-Sleep -Milliseconds 100
$serialText = [string](Get-Content -LiteralPath $serialPath -Raw)
$bobMarkerCount =
[regex]::Matches($serialText, [regex]::Escape('bob!')).Count
} while ([DateTime]::UtcNow -lt $desktopDeadline -and
$bobMarkerCount -le $bobMarkerCountBeforeDesktop)
if ($bobMarkerCount -le $bobMarkerCountBeforeDesktop) {
throw "The native desktop did not start for the launcher smoke test.`n$serialText"
}
Start-Sleep -Milliseconds 500
# The PS/2 pointer is at (672, 400). Click the editor's name
# field at (512, 60), replace its filename, and save as.
Send-MonitorCommand 'mouse_move -53 -113'
Send-MonitorCommand 'mouse_move -53 -113'
Send-MonitorCommand 'mouse_move -54 -114'
Send-MonitorCommand 'mouse_button 1'
Start-Sleep -Milliseconds 100
Send-MonitorCommand 'mouse_button 0'
Send-MonitorCommand 'sendkey end'
foreach ($index in 1..9) {
Send-MonitorCommand 'sendkey backspace'
}
Send-GuestText 'saved.txt'
Send-MonitorCommand 'sendkey ctrl-s'
Send-MonitorCommand 'sendkey tab'
Start-Sleep -Milliseconds 200
Send-GuestText 'pa'
$launcherDeadline = [DateTime]::UtcNow.AddSeconds(10)
do {
Start-Sleep -Milliseconds 100
$serialText = [string](Get-Content -LiteralPath $serialPath -Raw)
$bobMarkerCount =
[regex]::Matches($serialText, [regex]::Escape('bob!')).Count
} while ([DateTime]::UtcNow -lt $launcherDeadline -and
$bobMarkerCount -le $bobMarkerCountBeforeDesktop+1)
if ($bobMarkerCount -le $bobMarkerCountBeforeDesktop+1) {
throw "The desktop Applications launcher did not run its selected bob! app.`n$serialText"
}
Start-Sleep -Milliseconds 500
Send-MonitorCommand 'sendkey esc'
$desktopExitDeadline = [DateTime]::UtcNow.AddSeconds(2)
do {
Start-Sleep -Milliseconds 100
$serialText = [string](Get-Content -LiteralPath $serialPath -Raw)
$shellMarkerCount =
[regex]::Matches($serialText, [regex]::Escape($shellPromptMarker)).Count
$exitMarkerCount = [regex]::Matches($serialText,
[regex]::Escape('application exit status=0x0000000000000000')).Count
} while ([DateTime]::UtcNow -lt $desktopExitDeadline -and
($shellMarkerCount -le $shellMarkerCountBeforeDesktop -or
$exitMarkerCount -le $exitMarkerCountBeforeDesktop))
if ($shellMarkerCount -le $shellMarkerCountBeforeDesktop -or
$exitMarkerCount -le $exitMarkerCountBeforeDesktop) {
Send-MonitorCommand 'sendkey esc'
$desktopExitDeadline = [DateTime]::UtcNow.AddSeconds(10)
do {
Start-Sleep -Milliseconds 100
$serialText = [string](Get-Content -LiteralPath $serialPath -Raw)
$shellMarkerCount =
[regex]::Matches($serialText, [regex]::Escape($shellPromptMarker)).Count
$exitMarkerCount = [regex]::Matches($serialText,
[regex]::Escape('application exit status=0x0000000000000000')).Count
} while ([DateTime]::UtcNow -lt $desktopExitDeadline -and
($shellMarkerCount -le $shellMarkerCountBeforeDesktop -or
$exitMarkerCount -le $exitMarkerCountBeforeDesktop))
}
if ($shellMarkerCount -le $shellMarkerCountBeforeDesktop -or
$exitMarkerCount -le $exitMarkerCountBeforeDesktop) {
throw "The desktop did not return successfully to the shell after its child app ran.`n$serialText"
}
Send-GuestText 'ls'
$saveAsDeadline = [DateTime]::UtcNow.AddSeconds(5)
do {
Start-Sleep -Milliseconds 100
$serialText = [string](Get-Content -LiteralPath $serialPath -Raw)
} while ([DateTime]::UtcNow -lt $saveAsDeadline -and
-not $serialText.Contains('saved.txt'))
if (-not $serialText.Contains('saved.txt')) {
throw "The desktop filename field did not save the document as saved.txt.`n$serialText"
}
Send-GuestText 'rm saved.txt'
$saveAsCleanupDeadline = [DateTime]::UtcNow.AddSeconds(5)
do {
Start-Sleep -Milliseconds 100
$serialText = [string](Get-Content -LiteralPath $serialPath -Raw)
} while ([DateTime]::UtcNow -lt $saveAsCleanupDeadline -and
-not $serialText.Contains('deleted'))
if (-not $serialText.Contains('deleted')) {
throw "The Save As QEMU fixture could not be removed.`n$serialText"
}
$launcherSmokeStarted = $true
}
if ($allPresent -and -not $snapshotSaved) {
Send-GuestText 'write persist.txt survived'
$writeDeadline = [DateTime]::UtcNow.AddSeconds(5)
do {
Start-Sleep -Milliseconds 100
$serialText = [string](Get-Content -LiteralPath $serialPath -Raw)
} while ([DateTime]::UtcNow -lt $writeDeadline -and
-not $serialText.Contains('write persist.txt survived'))
if (-not $serialText.Contains('write persist.txt survived')) {
throw "Could not enter the persistence smoke file through the QEMU monitor.`n$serialText"
}
Send-GuestText 'save'
$saveDeadline = [DateTime]::UtcNow.AddSeconds(10)
do {
Start-Sleep -Milliseconds 100
$serialText = [string](Get-Content -LiteralPath $serialPath -Raw)
} while ([DateTime]::UtcNow -lt $saveDeadline -and
-not $serialText.Contains('saved B64S v1 checkpoint to firmware storage and RAM'))
if (-not $serialText.Contains('saved B64S v1 checkpoint to firmware storage and RAM')) {
throw "Firmware snapshot save failed in the guest.`n$serialText"
}
$persistentMarkerCountBeforeReset =
[regex]::Matches($serialText, [regex]::Escape($persistentMarker)).Count
$shellMarkerCountBeforeReset =
[regex]::Matches($serialText, [regex]::Escape($shellMarker)).Count
Send-MonitorCommand 'system_reset'
$snapshotSaved = $true
}
$persistentMarkerCount =
[regex]::Matches($serialText, [regex]::Escape($persistentMarker)).Count
if ($snapshotSaved -and
$persistentMarkerCount -gt $persistentMarkerCountBeforeReset -and
-not $restoredCompiledAppChecked) {
$restoredShellDeadline = [DateTime]::UtcNow.AddSeconds(10)
do {
Start-Sleep -Milliseconds 100
$serialText = [string](Get-Content -LiteralPath $serialPath -Raw)
$shellMarkerCount =
[regex]::Matches($serialText, [regex]::Escape($shellMarker)).Count
} while ([DateTime]::UtcNow -lt $restoredShellDeadline -and
$shellMarkerCount -le $shellMarkerCountBeforeReset)
if ($shellMarkerCount -le $shellMarkerCountBeforeReset) {
throw "The shell did not resume after restoring the B64S snapshot.`n$serialText"
}
$bobMarkerCountBeforeRestoreRun =
[regex]::Matches($serialText, [regex]::Escape('bob!')).Count
Send-GuestText 'run compiled.b64e'
$restoreRunDeadline = [DateTime]::UtcNow.AddSeconds(10)
do {
Start-Sleep -Milliseconds 100
$serialText = [string](Get-Content -LiteralPath $serialPath -Raw)
$bobMarkerCount =
[regex]::Matches($serialText, [regex]::Escape('bob!')).Count
} while ([DateTime]::UtcNow -lt $restoreRunDeadline -and
(-not $serialText.Contains('application exit status=0x0000000000000000') -or
$bobMarkerCount -le $bobMarkerCountBeforeRestoreRun))
if (-not $serialText.Contains('application exit status=0x0000000000000000') -or
$bobMarkerCount -le $bobMarkerCountBeforeRestoreRun) {
throw "The B64S restore did not preserve the compiled C application.`n$serialText"
}
$restoredCompiledAppChecked = $true
}
if ($snapshotSaved -and $restoredCompiledAppChecked -and
-not $restoredDesktopChecked) {
$bobMarkerCountBeforeRestoredDesktop =
[regex]::Matches($serialText, [regex]::Escape('bob!')).Count
$shellMarkerCountBeforeRestoredDesktop =
[regex]::Matches($serialText, [regex]::Escape($shellPromptMarker)).Count
$exitMarkerCountBeforeRestoredDesktop = [regex]::Matches($serialText,
[regex]::Escape('application exit status=0x0000000000000000')).Count
Send-GuestText 'run desktop.b64e'
$restoredDesktopDeadline = [DateTime]::UtcNow.AddSeconds(10)
do {
Start-Sleep -Milliseconds 100
$serialText = [string](Get-Content -LiteralPath $serialPath -Raw)
$bobMarkerCount =
[regex]::Matches($serialText, [regex]::Escape('bob!')).Count
} while ([DateTime]::UtcNow -lt $restoredDesktopDeadline -and
$bobMarkerCount -le $bobMarkerCountBeforeRestoredDesktop)
if ($bobMarkerCount -le $bobMarkerCountBeforeRestoredDesktop) {
throw "The GUI did not launch after B64S restore.`n$serialText"
}
Start-Sleep -Milliseconds 500
Send-GuestText 'p'
Start-Sleep -Milliseconds 300
# The mouse smoke app moved the PS/2 pointer 32 pixels from
# center. Move from that known position to Run App in the
# launcher at screen (994, 79), then click and release.
Send-MonitorCommand 'mouse_move 107 -107'
Send-MonitorCommand 'mouse_move 107 -107'
Send-MonitorCommand 'mouse_move 108 -107'
Send-MonitorCommand 'mouse_button 1'
Start-Sleep -Milliseconds 100
Send-MonitorCommand 'mouse_button 0'
$restoredLauncherDeadline = [DateTime]::UtcNow.AddSeconds(10)
do {
Start-Sleep -Milliseconds 100
$serialText = [string](Get-Content -LiteralPath $serialPath -Raw)
$bobMarkerCount =
[regex]::Matches($serialText, [regex]::Escape('bob!')).Count
} while ([DateTime]::UtcNow -lt $restoredLauncherDeadline -and
$bobMarkerCount -le $bobMarkerCountBeforeRestoredDesktop+1)
if ($bobMarkerCount -le $bobMarkerCountBeforeRestoredDesktop+1) {
throw "The restored desktop launcher did not run its selected bob! app.`n$serialText"
}
# The pointer remains at Run App after the child returns. The
# adjacent X CLOSE control is 80 pixels to its right.
Send-MonitorCommand 'mouse_move 80 0'
Send-MonitorCommand 'mouse_button 1'
Start-Sleep -Milliseconds 100
Send-MonitorCommand 'mouse_button 0'
Send-MonitorCommand 'sendkey esc'
$restoredDesktopExitDeadline = [DateTime]::UtcNow.AddSeconds(10)
do {
Start-Sleep -Milliseconds 100
$serialText = [string](Get-Content -LiteralPath $serialPath -Raw)
$shellMarkerCount = [regex]::Matches($serialText,
[regex]::Escape($shellPromptMarker)).Count
$exitMarkerCount = [regex]::Matches($serialText,
[regex]::Escape('application exit status=0x0000000000000000')).Count
} while ([DateTime]::UtcNow -lt $restoredDesktopExitDeadline -and
($shellMarkerCount -le $shellMarkerCountBeforeRestoredDesktop -or
$exitMarkerCount -le $exitMarkerCountBeforeRestoredDesktop))
if ($shellMarkerCount -le $shellMarkerCountBeforeRestoredDesktop -or
$exitMarkerCount -le $exitMarkerCountBeforeRestoredDesktop) {
throw "The mouse close button did not close the launcher before one Escape returned the desktop to the shell.`n$serialText"
}
$restoredDesktopChecked = $true
}
if ($snapshotSaved -and
$persistentMarkerCount -gt $persistentMarkerCountBeforeReset -and
$restoredCompiledAppChecked -and $restoredDesktopChecked -and
$nativeLauncherSmokeStarted) {
Write-Output 'UEFI runtime checks passed:'
foreach ($marker in $requiredMarkers) {
Write-Output " $marker"
}
Write-Output " $persistentMarker"
Write-Output " $mouseMarker"
Write-Output ' native graphics demo: surface presented, bob!, X returned to shell'
Write-Output ' native windowed launcher: ran the selected bob! app and Escape returned to shell'
Write-Output ' launcher command: forwarded argv to echo.b64e and returned to shell'
Write-Output ' resident C compile/run: bob!, exit 0; typedefs, division, bitwise/shift precedence, 16-argument call and large local frame passed'
Write-Output ' desktop Applications launcher: child bob! returned to shell'
Write-Output ' desktop filename field: mouse caret, keyboard edit, Ctrl+S Save As, shell file verification passed'
Write-Output ' post-restore compiled app launch: bob! and exit status 0'
Write-Output ' post-restore desktop: mouse ran bob! and clicked X CLOSE; Escape returned to shell'
exit 0
}
}
@@ -101,4 +618,7 @@ finally {
if (Test-Path -LiteralPath $serialPath) {
Remove-Item -LiteralPath $serialPath -Force
}
if (Test-Path -LiteralPath $varsCopyPath) {
Remove-Item -LiteralPath $varsCopyPath -Force
}
}