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

+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