This commit is contained in:
Alvin-Zilverstand committed 2026-10-08 23:36:34 +02:00
1 parent 78dd619293
commit 6dc841f956
109 files changed
+18192 -1907

No files matched your search

+124
View File
@@ -0,0 +1,124 @@
# bob64 application ABI v1 / syscall ABI v10
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
application-entry structure. B64E's ABI field must match
`BOB64_APP_ABI_VERSION`.
## Calls
- Integer and pointer arguments occupy positional slots in `RCX`, `RDX`, `R8`,
and `R9`; later arguments are passed on the stack. Floating-point arguments
use the corresponding `XMM0` through `XMM3` slots.
- Integer and pointer results use `RAX`; floating-point results use `XMM0`.
- Caller-saved registers are `RAX`, `RCX`, `RDX`, `R8`–`R11`, and `XMM0`–`XMM5`.
Callee-saved registers are `RBX`, `RBP`, `RSI`, `RDI`, `RSP`, `R12`–`R15`,
and `XMM6`–`XMM15`.
- The stack grows toward lower addresses. A caller aligns `RSP` to 16 bytes
before `call` and reserves 32 bytes of shadow space. On function entry, the
return address makes `RSP` 8 bytes off a 16-byte boundary. There is no red
zone; native code must not use memory below `RSP` without allocating it.
- The fifth and later integer arguments follow the 32-byte shadow area; the
fifth argument is at `[RSP+40]` on callee entry.
- Eligible plain C structs of 1, 2, 4, or 8 bytes return in `RAX`. Other
aggregate return sizes use caller-provided storage passed as a hidden first
argument. The app entry itself returns only a signed 64-bit status, so it
has no hidden return pointer.
## Application entry
The entry point has the type:
```c
s64 bob64_app_main(const BOB64_APP_STARTUP *startup);
```
The pointer is passed in `RCX`; the signed exit status returns in `RAX`. The
32-byte startup record contains its size and ABI version, a 64-bit argument
count, a pointer to a null-terminated argv pointer array, and zeroed flags.
The record, pointer array, and strings belong to the application's address
space. The ABI never passes kernel pointers to an application.
The loader validates the record size/version, creates the stack and argument
storage in the application's address space, aligns the entry stack, and
provides the shadow area. `bob64_enter_user` enters at CPL3 with the startup
record in `RCX`; it preserves the kernel's nonvolatile registers and restores
the caller's interrupt-enable state when the app exits. User entry enables
interrupts so configured devices can deliver input. Returning from the entry
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
`RAX`; a returning call writes its result to `RAX`. The available services are:
| Number | Name | Argument | Result |
| --- | --- | --- | --- |
| 0 | Query ABI | ignored | `BOB64_SYSCALL_ABI_VERSION` |
| 1 | Write character | low byte of `RCX` | `0` on success |
| 2 | Write buffer | user pointer in `RCX`, byte length in `RDX` | bytes written or `-14` |
| 3 | Exit | signed status in `RCX` | returns to the kernel |
| 4 | Read file | name pointer in `RCX`, name length in `RDX`, writable app buffer in `R8`, capacity in `R9` | bytes read or negative error |
| 5 | Write file | name pointer in `RCX`, name length in `RDX`, app buffer in `R8`, byte length in `R9` | bytes written or negative error |
| 6 | Get display | ignored | pixel width in `RAX`, pixel height in `RDX`, or `-19` if unavailable |
| 7 | Present surface | packed pixel pointer in `RCX`, width in `RDX`, height in `R8` | number of pixels presented or negative error |
| 8 | Wait event | writable app pointer to `BOB64_EVENT` in `RCX` | `0` after keyboard or mouse input, negative error |
| 9 | List files | writable `BOB64_FILE_INFO` array pointer in `RCX`, entry capacity in `RDX` | entry count or negative error |
| 10 | Delete file | name pointer in `RCX`, name length in `RDX` | `0` or negative error |
| 11 | Create window | signed x in `RCX`, signed y in `RDX`, width in `R8`, height in `R9` | nonzero 64-bit handle or negative error |
| 12 | Destroy window | handle in `RCX` | `0` or negative error |
| 13 | Present window | handle in `RCX`, pixel pointer in `RDX`, width in `R8`, height in `R9` | number of pixels presented or negative error |
| 14 | Focus window | handle in `RCX` | `0` or negative error |
| 15 | Open file | name pointer in `RCX`, length in `RDX`, flags in `R8` | 64-bit handle or negative error |
| 16 | Read handle | handle in `RCX`, writable buffer in `RDX`, capacity in `R8` | bytes read, `0` at EOF, or negative error |
| 17 | Write handle | handle in `RCX`, buffer in `RDX`, length in `R8` | bytes written or negative error |
| 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 |
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
limited to 4096 bytes; names are limited to 63 bytes. The legacy whole-file
calls remain available. Streaming opens accept `BOB64_FILE_OPEN_READ`,
`WRITE`, `CREATE`, `TRUNCATE`, and `APPEND`; at least read or write is required,
and truncate/append require write. Create initializes a missing file. Handles
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
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.
File deletion uses the same validated 1-to-63-byte safe filenames as reads and
writes and returns `-2` if the file does not exist. Display surfaces must match the current
GOP resolution and contain packed row-major `0x00RRGGBB` pixels; at most 16 MiB
may be presented per call. The kernel validates every covered user page before
copying pixels in small chunks, and converts channels to the firmware's GOP
format without exposing the framebuffer pointer. File reads require writable
user pages. `BOB64_EVENT` is a fixed 56-byte record with type, set-1 key code,
ASCII character, modifiers, window-local pointer position and movement, button
state, wheel delta, a 64-bit window handle, and screen coordinates. Whole-screen
events use a zero window handle. Extended set-1 keys set bit `0x100` in the key code; key-up events
have no character. Mouse buttons use the low three bits for standard buttons;
IntelliMouse IDs 3 and 4 add signed wheel input, with ID 4 adding buttons four
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
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
window has an opaque 64-bit handle and a retained kernel surface; presentation
must match the dimensions used at creation. The kernel composites up to 16
windows in z-order with an aggregate 16 MiB surface limit, routes input to the
focused window, and destroys the session when the app exits. Nonzero event
window handles identify the target; mouse coordinates are local to that window
and `ScreenX`/`ScreenY` retain absolute coordinates.
Only one app runs at a time, so cross-process desktop composition is still a
future step. Floating-point language types,
variadic calls across the kernel boundary, and aggregate application entry
results are not defined yet.
+234
View File
@@ -0,0 +1,234 @@
# bob64 boot milestone
`make bob64` creates a standalone x86-64 UEFI application at
`build/bob64/EFI/BOOT/BOOTX64.EFI`. Copy the `EFI` directory to the root of a
FAT32 USB drive, boot a machine with x64 UEFI, and select the USB device. From a
UEFI shell, the same image can be started with:
```text
fs0:\EFI\BOOT\BOOTX64.EFI
```
UEFI's x64 application contract transfers control in 64-bit long mode with the
Microsoft x64 calling convention, a valid stack, and firmware page tables. The
first bob64 entry checks CPUID long-mode support and `EFER.LMA`, then prints
`bob64!` through the firmware console. It reads the UEFI memory map and seeds a
64-bit first-fit allocator for conventional 4 KiB physical pages. The PE image
has a base-relocation directory, allowing firmware to load it away from its
preferred address. A tested bootstrap mapper can build identity mappings for
the image, a replacement stack, and its page-table pool. The EFI entry now
allocates those regions and verifies their mappings. The default build remains
a safe probe that returns to firmware. The opt-in `make bob64-handoff` build
exits Boot Services, maps a supported GOP framebuffer, installs the kernel
GDT/IDT and page-table root, switches to a replacement stack, and enters a tiny
C kernel. The kernel checks the boot information and active CR3, prints
`bob64!` and address-space details to the framebuffer and COM1, then checks its
heap and opens a command shell. Unsupported GOP modes fall back to COM1. The
handoff has been booted under QEMU with x64 OVMF firmware; the kernel reaches its
shell after switching to its own page tables, and the GOP framebuffer has been
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.
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.
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.
`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
entry-offset fields. The host-tested parser validates exact lengths, reserved
fields, and a payload CRC before exposing the image; the loading primitive
preserves addresses above 4 GiB and zeroes the memory-only tail. `bob64/abi.h`
defines the matching Microsoft x64 app entry call and a 32-byte startup record
whose arguments live in app memory. `bob64/process.c` has a callback-backed
loader core that validates B64E again, prepares user code/data/stack mappings,
builds the app-owned argv/startup record, and rolls back mapped frames on
failure. Host tests use synthetic pages above 4 GiB. The kernel smoke test
clones its active page-table root, isolates a 34 MiB app image/stack arena, and
switches CR3 while it loads a synthetic app. The shell can run B64E files with
`run NAME [ARG ...]`; the kernel seeds `bob.b64e` as a ready-to-run example.
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,
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
`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
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.
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
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,
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
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.
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
checks exercise the ring-3 smoke app, syscalls,
application loader, shell, and desktop.
The bob64 build compiles this C smoke app and embeds its B64E file in the kernel
image. The shell's `run bob.b64e` command exercises the C compiler bridge,
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
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
`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`
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
supports `void` helper functions with explicit `return;` or fallthrough, and
scalar `char` returns with signed 8-bit extension. Void calls work as statements
and are rejected when used as values. The resident subset recognizes
`usize`/`uintptr_t` as unsigned 64-bit integers and
`isize`/`intptr_t` as signed 64-bit integers, including function parameters,
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
`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.
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
`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
`short *`, `int *`, and `char *` values can point to
previously declared arrays or string literals, and global pointers to named
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
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,
array-to-pointer decay, address-of and dereference, indexed loads/stores, and
scaled pointer addition and subtraction, including element-count pointer
differences. String literals
are NUL-terminated `char *` values; `char *` locals and parameters, byte-indexed
reads and stores, byte dereference, byte-scaled pointer arithmetic, signed
8-bit `char` locals/parameters, and escaped character constants including
`'\\0'` are supported. Local `char` arrays can be initialized from string
literals or scalar brace lists, decay to `char *` arguments, and be indexed or
updated byte by byte. Host tests execute string traversal and mutable text
buffers. It rejects
pointer multiplication and incompatible pointer initializers/assignments. Local
array brace initializers support scalar expressions, trailing commas, omitted
element zero-fill, and excess-element rejection. Integer helper functions may
follow `main`; calls can be forward or nested and pass up to sixteen `short`,
`int`, `long`, `char`, `short *`/array, `int *`/array, `char *`, or struct-pointer
arguments through the
Microsoft x64 ABI, using RCX/RDX/R8/R9 and the caller's stack argument area.
Function definitions may appear before or after `main`; matching prototypes
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,
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
function's required final return for the current subset.
`make bob64cc` builds a host-side C-to-B64E bridge using the configured
x86-64 GCC toolchain. For example, `bob64cc apps/bob64_smoke.c
build/bob64-app/smoke.b64e` compiles C that uses `bob64/app.h`, links it at the
process image base, and packages the executable sections into a checksummed
B64E file. The entry wrapper converts a normal C return into the process-exit
syscall, and `bob64/libc.c` supplies 64-bit-length memory and string operations.
`make bob64-app-test` validates this generated file with the B64E parser. The
resident backend now exists for the small `bob.c` demo; the host bridge still
supports the broader C source accepted by GCC while the resident backend grows.
Run `make bob64-handoff-test` for host-side PE checks. They validate the image
format and relocation directory, but do not execute privileged CPU
instructions or prove `ExitBootServices` succeeds on a given firmware.
To boot the interactive shell, copy `build/bob64-handoff/EFI` to the FAT32
drive's root so firmware starts its `EFI/BOOT/BOOTX64.EFI` image. A PS/2
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.
## UEFI runtime test
Build the handoff image with `build-tool --bob64-handoff-test`, then run the
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
```
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.
+79
View File
@@ -0,0 +1,79 @@
#ifndef BOB64_ABI_H
#define BOB64_ABI_H
#include "types.h"
#define BOB64_APP_ABI_VERSION 1u
#define BOB64_SYSCALL_ABI_VERSION 10u
#define BOB64_SYSCALL_QUERY_ABI 0u
#define BOB64_SYSCALL_WRITE_CHAR 1u
#define BOB64_SYSCALL_WRITE_BUFFER 2u
#define BOB64_SYSCALL_EXIT 3u
#define BOB64_SYSCALL_READ_FILE 4u
#define BOB64_SYSCALL_WRITE_FILE 5u
#define BOB64_SYSCALL_GET_DISPLAY 6u
#define BOB64_SYSCALL_PRESENT 7u
#define BOB64_SYSCALL_WAIT_EVENT 8u
#define BOB64_SYSCALL_LIST_FILES 9u
#define BOB64_SYSCALL_DELETE_FILE 10u
#define BOB64_SYSCALL_CREATE_WINDOW 11u
#define BOB64_SYSCALL_DESTROY_WINDOW 12u
#define BOB64_SYSCALL_PRESENT_WINDOW 13u
#define BOB64_SYSCALL_FOCUS_WINDOW 14u
#define BOB64_SYSCALL_OPEN_FILE 15u
#define BOB64_SYSCALL_READ_HANDLE 16u
#define BOB64_SYSCALL_WRITE_HANDLE 17u
#define BOB64_SYSCALL_SEEK_HANDLE 18u
#define BOB64_SYSCALL_CLOSE_HANDLE 19u
#define BOB64_SYSCALL_GET_TICKS 20u
#define BOB64_FILE_OPEN_READ 0x01u
#define BOB64_FILE_OPEN_WRITE 0x02u
#define BOB64_FILE_OPEN_CREATE 0x04u
#define BOB64_FILE_OPEN_TRUNCATE 0x08u
#define BOB64_FILE_OPEN_APPEND 0x10u
#define BOB64_FILE_OPEN_FLAGS 0x1fu
#define BOB64_SYSCALL_MAX_BUFFER 4096u
#define BOB64_SYSCALL_MAX_FILES 32u
#define BOB64_SYSCALL_MAX_SURFACE_BYTES (16u*1024u*1024u)
#define BOB64_SYSCALL_COPY_CHUNK_BYTES 4096u
#define BOB64_SYSCALL_MAX_FILENAME 63u
_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,
"syscall copy chunk is a whole number of pixels");
typedef struct {
char Name[64];
u64 Size;
} BOB64_FILE_INFO;
_Static_assert(sizeof(BOB64_FILE_INFO)==72,"bob64 file-info ABI size");
/* The application startup block and argv strings live in the app address space. */
typedef struct {
u32 StructSize;
u32 AbiVersion;
u64 ArgumentCount;
const char *const *Arguments;
u64 Flags;
} BOB64_APP_STARTUP;
_Static_assert(sizeof(BOB64_APP_STARTUP)==32,"bob64 application startup ABI size");
_Static_assert(__builtin_offsetof(BOB64_APP_STARTUP,ArgumentCount)==8,
"bob64 startup argument-count offset");
_Static_assert(__builtin_offsetof(BOB64_APP_STARTUP,Arguments)==16,
"bob64 startup argv offset");
_Static_assert(__builtin_offsetof(BOB64_APP_STARTUP,Flags)==24,
"bob64 startup flags offset");
/* GCC on non-Windows x86-64 hosts needs an explicit attribute to test the ABI. */
#if defined(__x86_64__) && !defined(_WIN32) && defined(__GNUC__)
#define BOB64_MS_ABI __attribute__((ms_abi))
#else
#define BOB64_MS_ABI
#endif
/* Entry receives the app-owned startup block in RCX and returns status in RAX. */
typedef s64 (BOB64_MS_ABI *BOB64_APP_ENTRY)(const BOB64_APP_STARTUP *startup);
#endif
+192
View File
@@ -0,0 +1,192 @@
#ifndef BOB64_APP_H
#define BOB64_APP_H
#include "abi.h"
#include "event.h"
/* Native apps use int 0x80; only RAX is changed by a returning service. */
static inline s64 bob64_app_query_abi(void) {
register u64 rax __asm__("rax")=BOB64_SYSCALL_QUERY_ABI;
__asm__ volatile("int $0x80":"+a"(rax)::"memory","cc");
return (s64)rax;
}
/* Number of 100 Hz PIT ticks since kernel initialization. */
static inline u64 bob64_app_ticks(void) {
register u64 rax __asm__("rax")=BOB64_SYSCALL_GET_TICKS;
__asm__ volatile("int $0x80":"+a"(rax)::"memory","cc");
return rax;
}
/* Display size is returned as width in RAX and height in RDX. */
static inline s64 bob64_app_get_display(u32 *width,u32 *height) {
register u64 rax __asm__("rax")=BOB64_SYSCALL_GET_DISPLAY;
register u64 rdx __asm__("rdx");
__asm__ volatile("int $0x80":"+a"(rax),"=d"(rdx)::"memory","cc");
if((s64)rax<0)return (s64)rax;
if(!width||!height)return -22;
*width=(u32)rax;*height=(u32)rdx;
return 0;
}
/* Present one packed 0x00RRGGBB pixel for every display pixel. */
static inline s64 bob64_app_present(const u32 *pixels,u32 width,u32 height) {
register u64 rax __asm__("rax")=BOB64_SYSCALL_PRESENT;
register u64 rcx __asm__("rcx")=(u64)(uintptr_t)pixels;
register u64 rdx __asm__("rdx")=width;
register u64 r8 __asm__("r8")=height;
__asm__ volatile("int $0x80":"+a"(rax):"c"(rcx),"d"(rdx),"r"(r8):"memory","cc");
return (s64)rax;
}
/* Wait for the next key press or release; the event is app-owned. */
static inline s64 bob64_app_wait_event(BOB64_EVENT *event) {
register u64 rax __asm__("rax")=BOB64_SYSCALL_WAIT_EVENT;
register u64 rcx __asm__("rcx")=(u64)(uintptr_t)event;
__asm__ volatile("int $0x80":"+a"(rax):"c"(rcx):"memory","cc");
return (s64)rax;
}
static inline s64 bob64_app_write_char(u8 character) {
register u64 rax __asm__("rax")=BOB64_SYSCALL_WRITE_CHAR;
register u64 rcx __asm__("rcx")=character;
__asm__ volatile("int $0x80":"+a"(rax):"c"(rcx):"memory","cc");
return (s64)rax;
}
static inline s64 bob64_app_write(const void *buffer,usize length) {
register u64 rax __asm__("rax")=BOB64_SYSCALL_WRITE_BUFFER;
register u64 rcx __asm__("rcx")=(u64)(uintptr_t)buffer;
register u64 rdx __asm__("rdx")=(u64)length;
__asm__ volatile("int $0x80":"+a"(rax):"c"(rcx),"d"(rdx):"memory","cc");
return (s64)rax;
}
/* File services use a bounded name (1..63 bytes) and at most 4096 data bytes. */
static inline s64 bob64_app_read_file(const char *name,usize name_length,
void *buffer,usize capacity) {
register u64 rax __asm__("rax")=BOB64_SYSCALL_READ_FILE;
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)buffer;
register u64 r9 __asm__("r9")=(u64)capacity;
__asm__ volatile("int $0x80":"+a"(rax):"c"(rcx),"d"(rdx),"r"(r8),"r"(r9):"memory","cc");
return (s64)rax;
}
static inline s64 bob64_app_write_file(const char *name,usize name_length,
const void *buffer,usize length) {
register u64 rax __asm__("rax")=BOB64_SYSCALL_WRITE_FILE;
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)buffer;
register u64 r9 __asm__("r9")=(u64)length;
__asm__ volatile("int $0x80":"+a"(rax):"c"(rcx),"d"(rdx),"r"(r8),"r"(r9):"memory","cc");
return (s64)rax;
}
/* List at most 32 files into an app-owned array of fixed-width records. */
static inline s64 bob64_app_list_files(BOB64_FILE_INFO *entries,usize capacity) {
register u64 rax __asm__("rax")=BOB64_SYSCALL_LIST_FILES;
register u64 rcx __asm__("rcx")=(u64)(uintptr_t)entries;
register u64 rdx __asm__("rdx")=(u64)capacity;
__asm__ volatile("int $0x80":"+a"(rax):"c"(rcx),"d"(rdx):"memory","cc");
return (s64)rax;
}
static inline s64 bob64_app_delete_file(const char *name,usize name_length) {
register u64 rax __asm__("rax")=BOB64_SYSCALL_DELETE_FILE;
register u64 rcx __asm__("rcx")=(u64)(uintptr_t)name;
register u64 rdx __asm__("rdx")=(u64)name_length;
__asm__ volatile("int $0x80":"+a"(rax):"c"(rcx),"d"(rdx):"memory","cc");
return (s64)rax;
}
/* Streaming file handles keep a 64-bit position and transfer at most 4096 bytes per call. */
static inline s64 bob64_app_file_open(const char *name,usize name_length,u32 flags) {
register u64 rax __asm__("rax")=BOB64_SYSCALL_OPEN_FILE;
register u64 rcx __asm__("rcx")=(u64)(uintptr_t)name;
register u64 rdx __asm__("rdx")=(u64)name_length;
register u64 r8 __asm__("r8")=flags;
__asm__ volatile("int $0x80":"+a"(rax):"c"(rcx),"d"(rdx),"r"(r8):"memory","cc");
return (s64)rax;
}
static inline s64 bob64_app_file_read(s64 handle,void *buffer,usize capacity) {
register u64 rax __asm__("rax")=BOB64_SYSCALL_READ_HANDLE;
register u64 rcx __asm__("rcx")=(u64)handle;
register u64 rdx __asm__("rdx")=(u64)(uintptr_t)buffer;
register u64 r8 __asm__("r8")=(u64)capacity;
__asm__ volatile("int $0x80":"+a"(rax):"c"(rcx),"d"(rdx),"r"(r8):"memory","cc");
return (s64)rax;
}
static inline s64 bob64_app_file_write(s64 handle,const void *buffer,usize length) {
register u64 rax __asm__("rax")=BOB64_SYSCALL_WRITE_HANDLE;
register u64 rcx __asm__("rcx")=(u64)handle;
register u64 rdx __asm__("rdx")=(u64)(uintptr_t)buffer;
register u64 r8 __asm__("r8")=(u64)length;
__asm__ volatile("int $0x80":"+a"(rax):"c"(rcx),"d"(rdx),"r"(r8):"memory","cc");
return (s64)rax;
}
static inline s64 bob64_app_file_seek(s64 handle,u64 offset) {
register u64 rax __asm__("rax")=BOB64_SYSCALL_SEEK_HANDLE;
register u64 rcx __asm__("rcx")=(u64)handle;
register u64 rdx __asm__("rdx")=offset;
__asm__ volatile("int $0x80":"+a"(rax):"c"(rcx),"d"(rdx):"memory","cc");
return (s64)rax;
}
static inline s64 bob64_app_file_close(s64 handle) {
register u64 rax __asm__("rax")=BOB64_SYSCALL_CLOSE_HANDLE;
register u64 rcx __asm__("rcx")=(u64)handle;
__asm__ volatile("int $0x80":"+a"(rax):"c"(rcx):"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;
register u64 rcx __asm__("rcx")=(u64)(s64)x;
register u64 rdx __asm__("rdx")=(u64)(s64)y;
register u64 r8 __asm__("r8")=width;
register u64 r9 __asm__("r9")=height;
__asm__ volatile("int $0x80":"+a"(rax):"c"(rcx),"d"(rdx),"r"(r8),"r"(r9):"memory","cc");
return rax;
}
static inline s64 bob64_app_window_destroy(u64 handle) {
register u64 rax __asm__("rax")=BOB64_SYSCALL_DESTROY_WINDOW;
register u64 rcx __asm__("rcx")=handle;
__asm__ volatile("int $0x80":"+a"(rax):"c"(rcx):"memory","cc");
return (s64)rax;
}
static inline s64 bob64_app_window_focus(u64 handle) {
register u64 rax __asm__("rax")=BOB64_SYSCALL_FOCUS_WINDOW;
register u64 rcx __asm__("rcx")=handle;
__asm__ volatile("int $0x80":"+a"(rax):"c"(rcx):"memory","cc");
return (s64)rax;
}
static inline s64 bob64_app_window_present(u64 handle,const u32 *pixels,
u32 width,u32 height) {
register u64 rax __asm__("rax")=BOB64_SYSCALL_PRESENT_WINDOW;
register u64 rcx __asm__("rcx")=handle;
register u64 rdx __asm__("rdx")=(u64)(uintptr_t)pixels;
register u64 r8 __asm__("r8")=width;
register u64 r9 __asm__("r9")=height;
__asm__ volatile("int $0x80":"+a"(rax):"c"(rcx),"d"(rdx),"r"(r8),"r"(r9):"memory","cc");
return (s64)rax;
}
/* Exit transfers control to the kernel; it does not return to this caller. */
static inline __attribute__((noreturn)) void bob64_app_exit(s64 status) {
register u64 rax __asm__("rax")=BOB64_SYSCALL_EXIT;
register u64 rcx __asm__("rcx")=(u64)status;
__asm__ volatile("int $0x80":"+a"(rax):"c"(rcx):"memory","cc");
__builtin_unreachable();
}
#endif
+15
View File
@@ -0,0 +1,15 @@
.intel_syntax noprefix
.text
.globl bob64_app_entry
bob64_app_entry:
/* RSP enters at 8 mod 16; reserve shadow space and align before the call. */
sub rsp,40
call bob64_app_main
mov rcx,rax
mov eax,3 /* BOB64_SYSCALL_EXIT in ABI v1 */
int 0x80
ud2
#ifndef __MINGW32__
.section .note.GNU-stack,"",@progbits
#endif
+213
View File
@@ -0,0 +1,213 @@
#include "efi.h"
#include "memory.h"
#include "cpu.h"
#include "bootstrap.h"
#include "descriptors.h"
#include "interrupts.h"
#include "kernel.h"
#define BOB64_MEMORY_MAP_CAPACITY 131072
#define BOB64_BOOT_STACK_PAGES 8
#define BOB64_TABLE_POOL_PAGES 128
#define BOB64_FRAMEBUFFER_MAP_LIMIT (64ULL*1024ULL*1024ULL)
static u8 memory_map[BOB64_MEMORY_MAP_CAPACITY] __attribute__((aligned(16)));
BOB64_PAGE_EXTENT bob64_boot_page_extents[BOB64_PAGE_EXTENT_LIMIT];
BOB64_PAGE_ALLOCATOR bob64_boot_page_allocator;
BOB64_BOOTSTRAP_SPACE bob64_bootstrap_space;
static u64 kernel_gdt[BOB64_GDT_ENTRY_COUNT];
BOB64_TSS bob64_kernel_tss;
static BOB64_IDT_GATE kernel_idt[BOB64_IDT_ENTRIES];
static BOB64_DESCRIPTOR_TABLE_POINTER kernel_gdtr,kernel_idtr;
#ifdef BOB64_ENABLE_HANDOFF
static BOB64_KERNEL_BOOT_INFO kernel_boot_info;
#endif
static const EFI_GUID loaded_image_guid={0x5b1b31a1u,0x9562u,0x11d2u,
{0x8e,0x3f,0x00,0xa0,0xc9,0x69,0x72,0x3b}};
#ifdef BOB64_ENABLE_HANDOFF
static const EFI_GUID graphics_output_guid={0x9042a9deu,0x23dcu,0x4a38u,
{0x96,0xfb,0x7a,0xde,0xd0,0x80,0x51,0x6a}};
#endif
static u64 *physical_identity_access(void *context,u64 physical_address) {
(void)context;
return (u64 *)(uintptr_t)physical_address;
}
static EFI_STATUS efi_print(EFI_SYSTEM_TABLE *system,const CHAR16 *text) {
if(!system || !system->ConOut || !system->ConOut->OutputString)
return EFI_UNSUPPORTED;
return system->ConOut->OutputString(system->ConOut,text);
}
EFI_STATUS EFIAPI efi_main(EFI_HANDLE image,EFI_SYSTEM_TABLE *system) {
static const CHAR16 active[]={'b','o','b','6','4',':',' ','l','o','n','g',' ' ,
'm','o','d','e',' ','a','c','t','i','v','e','\r','\n',0};
static const CHAR16 unsupported[]={'b','o','b','6','4',':',' ','x','8','6','-','6','4',
' ','l','o','n','g',' ','m','o','d','e',' ','r','e','q','u','i','r','e','d','\r','\n',0};
#ifndef BOB64_ENABLE_HANDOFF
static const CHAR16 prepared[]={'b','o','b','6','4',':',' ','b','o','o','t','s','t','r','a','p',
' ','p','a','g','i','n','g',' ','p','r','e','p','a','r','e','d','\r','\n',0};
#endif
#ifdef BOB64_ENABLE_HANDOFF
static const CHAR16 handoff[]={'b','o','b','6','4',':',' ','e','x','i','t','i','n','g',' ' ,
'U','E','F','I',' ','b','o','o','t',' ','s','e','r','v','i','c','e','s','\r','\n',0};
#endif
static const CHAR16 marker[]={'b','o','b','6','4','!','\r','\n',0};
/* This image-base-relative pointer must be repaired if firmware relocates the PE image. */
static const CHAR16 * volatile relocated_marker=marker;
UINTN map_capacity=sizeof(memory_map),map_size=sizeof(memory_map),map_key=0,descriptor_size=0;
u32 descriptor_version=0;
EFI_STATUS status;
EFI_MEMORY_DESCRIPTOR *map=(EFI_MEMORY_DESCRIPTOR *)memory_map;
BOB64_CPU_FEATURES cpu;
EFI_LOADED_IMAGE_PROTOCOL *loaded_image;
void *loaded_image_interface=0;
#ifdef BOB64_ENABLE_HANDOFF
EFI_GRAPHICS_OUTPUT_PROTOCOL *graphics=0;
EFI_GRAPHICS_OUTPUT_PROTOCOL_MODE *graphics_mode=0;
EFI_GRAPHICS_OUTPUT_MODE_INFORMATION *graphics_info=0;
int framebuffer_valid=0;
u64 framebuffer_map_size=0;
#endif
u64 stack_base,table_pool_base,translated;
u64 probe_page;
BOB64_PAGE_EXTENT *active_page_extents=bob64_boot_page_extents;
BOB64_PAGE_ALLOCATOR *active_page_allocator=&bob64_boot_page_allocator;
BOB64_BOOTSTRAP_SPACE *active_bootstrap_space=&bob64_bootstrap_space;
if(!system)return EFI_UNSUPPORTED;
if(bob64_cpu_detect(&cpu)||!cpu.PAE||!cpu.LongMode||
!bob64_cpu_long_mode_active(&cpu)) {
efi_print(system,unsupported);
return EFI_UNSUPPORTED;
}
#ifdef BOB64_ENABLE_HANDOFF
if(!bob64_cpu_four_level_paging_active()) {
efi_print(system,unsupported);
return EFI_UNSUPPORTED;
}
#endif
if(EFI_ERROR(efi_print(system,active)))return EFI_UNSUPPORTED;
if(EFI_ERROR(efi_print(system,relocated_marker)))return EFI_UNSUPPORTED;
if(!system->BootServices||!system->BootServices->GetMemoryMap||
!system->BootServices->HandleProtocol)return EFI_UNSUPPORTED;
status=system->BootServices->HandleProtocol(image,&loaded_image_guid,&loaded_image_interface);
if(EFI_ERROR(status))return status;
if(!loaded_image_interface)return EFI_UNSUPPORTED;
loaded_image=(EFI_LOADED_IMAGE_PROTOCOL *)loaded_image_interface;
if(!loaded_image->ImageBase||!loaded_image->ImageSize)return EFI_UNSUPPORTED;
#ifdef BOB64_ENABLE_HANDOFF
if(system->BootServices->LocateProtocol&&
!EFI_ERROR(system->BootServices->LocateProtocol(&graphics_output_guid,0,
(void **)&graphics))&&
graphics&&graphics->Mode&&(graphics_mode=graphics->Mode)&&
graphics_mode->Info&&(graphics_info=graphics_mode->Info)&&
(graphics_info->PixelFormat==0||graphics_info->PixelFormat==1)&&
graphics_mode->FrameBufferBase&&graphics_mode->FrameBufferSize&&
graphics_info->HorizontalResolution>=6&&graphics_info->VerticalResolution>=8&&
graphics_info->PixelsPerScanLine>=graphics_info->HorizontalResolution&&
(u64)graphics_info->PixelsPerScanLine<=~(u64)0/graphics_info->VerticalResolution) {
u64 pixels=(u64)graphics_info->PixelsPerScanLine*graphics_info->VerticalResolution;
if(pixels<=~(u64)0/4) {
framebuffer_map_size=pixels*4;
framebuffer_valid=framebuffer_map_size<=graphics_mode->FrameBufferSize&&
framebuffer_map_size<=BOB64_FRAMEBUFFER_MAP_LIMIT;
}
}
#endif
status=system->BootServices->GetMemoryMap(&map_size,map,&map_key,&descriptor_size,&descriptor_version);
if(status==EFI_BUFFER_TOO_SMALL) {
if(!system->BootServices->AllocatePool)return status;
UINTN slack=(descriptor_size?descriptor_size:sizeof(EFI_MEMORY_DESCRIPTOR))*2;
if(map_size>(~(UINTN)0)-slack)return EFI_UNSUPPORTED;
UINTN required=map_size+slack;
status=system->BootServices->AllocatePool(EFI_MEMORY_LOADER_DATA,required,(void **)&map);
if(EFI_ERROR(status))return status;
map_capacity=required;map_size=required;
status=system->BootServices->GetMemoryMap(&map_size,map,&map_key,&descriptor_size,&descriptor_version);
}
if(EFI_ERROR(status))return status;
if(descriptor_version!=1||bob64_page_allocator_init(active_page_allocator,active_page_extents,
BOB64_PAGE_EXTENT_LIMIT,cpu.PhysicalAddressBits,map,(usize)map_size,
(usize)descriptor_size)<0)
return EFI_UNSUPPORTED;
probe_page=bob64_page_alloc(active_page_allocator,1);
if(!probe_page||bob64_page_free(active_page_allocator,probe_page,1))return EFI_UNSUPPORTED;
stack_base=bob64_page_alloc(active_page_allocator,BOB64_BOOT_STACK_PAGES);
table_pool_base=bob64_page_alloc(active_page_allocator,BOB64_TABLE_POOL_PAGES);
if(!stack_base||!table_pool_base)return EFI_UNSUPPORTED;
volatile u64 *stack_words=(volatile u64 *)(uintptr_t)stack_base;
for(usize i=0;i<BOB64_BOOT_STACK_PAGES*EFI_PAGE_SIZE/sizeof(u64);i++)stack_words[i]=0;
if(bob64_tss_init(&bob64_kernel_tss,
stack_base+BOB64_BOOT_STACK_PAGES*EFI_PAGE_SIZE))
return EFI_UNSUPPORTED;
bob64_gdt_init(kernel_gdt,&kernel_gdtr,&bob64_kernel_tss);
bob64_idt_pointer(&kernel_idtr,kernel_idt);
if(bob64_interrupts_build_idt(kernel_idt,BOB64_GDT_KERNEL_CODE_SELECTOR))
return EFI_UNSUPPORTED;
bob64_idt_pointer(&kernel_idtr,kernel_idt);
if(bob64_bootstrap_space_init(active_bootstrap_space,cpu.PhysicalAddressBits,
physical_identity_access,0,table_pool_base,BOB64_TABLE_POOL_PAGES,
(u64)(uintptr_t)loaded_image->ImageBase,loaded_image->ImageSize,
stack_base,BOB64_BOOT_STACK_PAGES*EFI_PAGE_SIZE,cpu.NX)<0)
return EFI_UNSUPPORTED;
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&&
(u64)map_capacity<=loaded_image->ImageSize-(map_base-image_base);
if(!map_is_in_image&&bob64_page_map_range(&active_bootstrap_space->PageTable,map_base,map_base,
(u64)map_capacity,BOB64_PAGE_WRITE|(cpu.NX?BOB64_PAGE_NX:0)))
return EFI_UNSUPPORTED;
#ifdef BOB64_ENABLE_HANDOFF
if(framebuffer_valid&&bob64_page_map_range(&active_bootstrap_space->PageTable,
graphics_mode->FrameBufferBase,graphics_mode->FrameBufferBase,
framebuffer_map_size,BOB64_PAGE_WRITE|BOB64_PAGE_PCD|BOB64_PAGE_PWT|
(cpu.NX?BOB64_PAGE_NX:0)))framebuffer_valid=0;
#endif
if(bob64_page_translate(&active_bootstrap_space->PageTable,
(u64)(uintptr_t)loaded_image->ImageBase,&translated,0)!=1||
translated!=(u64)(uintptr_t)loaded_image->ImageBase||
bob64_page_translate(&active_bootstrap_space->PageTable,
stack_base+BOB64_BOOT_STACK_PAGES*EFI_PAGE_SIZE-1,&translated,0)!=1||
translated!=stack_base+BOB64_BOOT_STACK_PAGES*EFI_PAGE_SIZE-1)
return EFI_UNSUPPORTED;
#ifdef BOB64_ENABLE_HANDOFF
if(!system->BootServices->ExitBootServices)return EFI_UNSUPPORTED;
if(EFI_ERROR(efi_print(system,handoff)))return EFI_UNSUPPORTED;
kernel_boot_info.PageTableRoot=active_bootstrap_space->PageTable.RootPhysical;
kernel_boot_info.MemoryMapAddress=map_base;
kernel_boot_info.MemoryDescriptorSize=descriptor_size;
kernel_boot_info.StackBase=stack_base;
kernel_boot_info.StackSize=BOB64_BOOT_STACK_PAGES*EFI_PAGE_SIZE;
kernel_boot_info.PhysicalAddressBits=cpu.PhysicalAddressBits;
kernel_boot_info.NxSupported=cpu.NX;
if(framebuffer_valid) {
kernel_boot_info.FramebufferBase=graphics_mode->FrameBufferBase;
kernel_boot_info.FramebufferSize=framebuffer_map_size;
kernel_boot_info.FramebufferWidth=graphics_info->HorizontalResolution;
kernel_boot_info.FramebufferHeight=graphics_info->VerticalResolution;
kernel_boot_info.FramebufferPixelsPerScanLine=graphics_info->PixelsPerScanLine;
kernel_boot_info.FramebufferPixelFormat=graphics_info->PixelFormat;
kernel_boot_info.HasFramebuffer=1;
}
for(u32 attempt=0;attempt<3;attempt++) {
map_size=map_capacity;
status=system->BootServices->GetMemoryMap(&map_size,map,&map_key,&descriptor_size,
&descriptor_version);
if(EFI_ERROR(status))return status;
if(descriptor_version!=1||!descriptor_size||map_size>map_capacity)return EFI_UNSUPPORTED;
kernel_boot_info.MemoryMapSize=map_size;
kernel_boot_info.MemoryDescriptorSize=descriptor_size;
status=system->BootServices->ExitBootServices(image,map_key);
if(!EFI_ERROR(status))
bob64_enter_kernel(kernel_boot_info.PageTableRoot,
stack_base+BOB64_BOOT_STACK_PAGES*EFI_PAGE_SIZE,&kernel_gdtr,&kernel_idtr,
&kernel_boot_info);
if(status!=EFI_INVALID_PARAMETER)return status;
}
return status;
#else
if(EFI_ERROR(efi_print(system,prepared)))return EFI_UNSUPPORTED;
return EFI_SUCCESS;
#endif
}
+47
View File
@@ -0,0 +1,47 @@
#include "bootstrap.h"
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;
}
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);
}
int bob64_bootstrap_space_init(BOB64_BOOTSTRAP_SPACE *space,u8 physical_address_bits,
BOB64_TABLE_ACCESS access,void *access_context,
u64 table_pool_base,u64 table_pool_pages,
u64 image_base,u64 image_size,
u64 stack_base,u64 stack_size,u8 nx_supported) {
u64 pool_bytes;
u64 writable_nx=BOB64_PAGE_WRITE|(nx_supported?BOB64_PAGE_NX:0);
int result;
if(!space||!access||!table_pool_pages||
table_pool_base&(BOB64_PAGE_SIZE-1)||
table_pool_pages>(~(u64)0)/BOB64_PAGE_SIZE||
!image_size||!stack_size||nx_supported>1)return BOB64_PAGING_INVALID;
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->TablePoolUsed=0;space->Access=access;space->AccessContext=access_context;
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;
result=bob64_page_map_range(&space->PageTable,image_base,image_base,image_size,
BOB64_PAGE_WRITE);
if(result)return result;
result=bob64_page_map_range(&space->PageTable,stack_base,stack_base,stack_size,
writable_nx);
if(result)return result;
result=bob64_page_map_range(&space->PageTable,table_pool_base,table_pool_base,
pool_bytes,writable_nx);
if(result)return result;
return 0;
}
+23
View File
@@ -0,0 +1,23 @@
#ifndef BOB64_BOOTSTRAP_H
#define BOB64_BOOTSTRAP_H
#include "paging.h"
typedef struct {
BOB64_PAGE_TABLE PageTable;
u64 TablePoolBase;
u64 TablePoolPages;
u64 TablePoolUsed;
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,
BOB64_TABLE_ACCESS access,void *access_context,
u64 table_pool_base,u64 table_pool_pages,
u64 image_base,u64 image_size,
u64 stack_base,u64 stack_size,u8 nx_supported);
#endif
+2255
View File
File diff suppressed because it is too large. Load diff
+15
View File
@@ -0,0 +1,15 @@
#ifndef BOB64_COMPILER_H
#define BOB64_COMPILER_H
#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)
/* Compile bob64's initial 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);
#endif
+140
View File
@@ -0,0 +1,140 @@
#include "console.h"
#include "font.h"
typedef struct {
volatile u32 *Pixels;
u64 SizeBytes;
u32 Width,Height,Stride,Format,Column,Row;
u8 Ready;
} BOB64_FRAMEBUFFER;
static BOB64_FRAMEBUFFER framebuffer;
static u32 color(u8 red,u8 green,u8 blue) {
if(framebuffer.Format==0)return (u32)red|((u32)green<<8)|((u32)blue<<16);
return (u32)blue|((u32)green<<8)|((u32)red<<16);
}
static void pixel(u32 x,u32 y,u32 value) {
if(x<framebuffer.Width&&y<framebuffer.Height)
framebuffer.Pixels[(u64)y*framebuffer.Stride+x]=value;
}
static void clear_row(u32 y) {
u32 background=color(12,18,28);
for(u32 x=0;x<framebuffer.Width;x++)pixel(x,y,background);
}
void bob64_framebuffer_clear(void) {
if(!framebuffer.Ready)return;
for(u32 y=0;y<framebuffer.Height;y++)clear_row(y);
framebuffer.Column=0;framebuffer.Row=0;
}
static void scroll(void) {
u32 lines=framebuffer.Height>8?framebuffer.Height-8:0;
for(u32 y=0;y<lines;y++) {
volatile u32 *destination=framebuffer.Pixels+(u64)y*framebuffer.Stride;
volatile u32 *source=destination+(u64)8*framebuffer.Stride;
for(u32 x=0;x<framebuffer.Width;x++)destination[x]=source[x];
}
for(u32 y=lines;y<framebuffer.Height;y++)clear_row(y);
framebuffer.Row=framebuffer.Height/8?framebuffer.Height/8-1:0;
}
static u32 glyph_index(u8 value) {
if(value>='a'&&value<='z')value=(u8)(value-'a'+'A');
if(value==' ')return 0;
if(value>='A'&&value<='Z')return 1u+(u32)(value-'A');
if(value>='0'&&value<='9')return 27u+(u32)(value-'0');
if(value=='!')return 38;
if(value=='-')return 39;
if(value=='.')return 40;
if(value==':')return 41;
if(value=='=')return 42;
if(value=='>')return 43;
return 37;
}
static void draw_character(u8 value) {
u32 foreground=color(228,238,248),background=color(12,18,28);
u32 glyph=glyph_index(value),origin_x=framebuffer.Column*6,origin_y=framebuffer.Row*8;
for(u32 y=0;y<8;y++)for(u32 x=0;x<6;x++) {
u32 on=x<5&&y<7&&(bob64_font5x7[glyph][x]&(1u<<y));
pixel(origin_x+x,origin_y+y,on?foreground:background);
}
framebuffer.Column++;
if(framebuffer.Column>=framebuffer.Width/6) {
framebuffer.Column=0;
framebuffer.Row++;
}
if(framebuffer.Row>=framebuffer.Height/8)scroll();
}
static void erase_previous_character(void) {
u32 columns=framebuffer.Width/6;
if(framebuffer.Column)framebuffer.Column--;
else if(framebuffer.Row) {
framebuffer.Row--;
framebuffer.Column=columns-1;
} else return;
u32 origin_x=framebuffer.Column*6,origin_y=framebuffer.Row*8;
for(u32 y=0;y<8;y++)for(u32 x=0;x<6;x++)
pixel(origin_x+x,origin_y+y,color(12,18,28));
}
int bob64_framebuffer_init(u64 base,u64 size,u32 width,u32 height,
u32 pixels_per_scan_line,u32 pixel_format) {
u64 pixels,required;
if(!base||!size||width<6||height<8||pixels_per_scan_line<width||
(pixel_format!=0&&pixel_format!=1)||
(u64)pixels_per_scan_line>~(u64)0/height)return -1;
pixels=(u64)pixels_per_scan_line*height;
if(pixels>~(u64)0/sizeof(u32))return -1;
required=pixels*sizeof(u32);
if(required>size)return -1;
framebuffer.Pixels=(volatile u32 *)(uintptr_t)base;
framebuffer.SizeBytes=size;
framebuffer.Width=width;framebuffer.Height=height;
framebuffer.Stride=pixels_per_scan_line;framebuffer.Format=pixel_format;
framebuffer.Column=0;framebuffer.Row=0;framebuffer.Ready=1;
for(u32 y=0;y<height;y++)clear_row(y);
return 0;
}
int bob64_framebuffer_available(void) {
return framebuffer.Ready!=0;
}
int bob64_framebuffer_resolution(u32 *width,u32 *height) {
if(!framebuffer.Ready||!width||!height)return -1;
*width=framebuffer.Width;*height=framebuffer.Height;
return 0;
}
int bob64_framebuffer_write_pixels(u64 first_pixel,const u32 *pixels,u32 count) {
u64 total;
if(!framebuffer.Ready||(!pixels&&count))return -1;
total=(u64)framebuffer.Width*framebuffer.Height;
if(first_pixel>total||(u64)count>total-first_pixel)return -1;
for(u32 i=0;i<count;i++) {
u64 index=first_pixel+i;
u32 red=(pixels[i]>>16)&0xff,green=(pixels[i]>>8)&0xff,blue=pixels[i]&0xff;
pixel((u32)(index%framebuffer.Width),(u32)(index/framebuffer.Width),
color((u8)red,(u8)green,(u8)blue));
}
return 0;
}
void bob64_framebuffer_write(const char *text) {
if(!framebuffer.Ready||!text)return;
while(*text) {
u8 value=(u8)*text++;
if(value=='\r')framebuffer.Column=0;
else if(value=='\n') {
framebuffer.Column=0;framebuffer.Row++;
if(framebuffer.Row>=framebuffer.Height/8)scroll();
} else if(value=='\b')erase_previous_character();
else draw_character(value);
}
}
+16
View File
@@ -0,0 +1,16 @@
#ifndef BOB64_CONSOLE_H
#define BOB64_CONSOLE_H
#include "types.h"
/* UEFI GOP pixel formats 0 and 1; returns nonzero when unsupported/invalid. */
int bob64_framebuffer_init(u64 base,u64 size,u32 width,u32 height,
u32 pixels_per_scan_line,u32 pixel_format);
int bob64_framebuffer_available(void);
int bob64_framebuffer_resolution(u32 *width,u32 *height);
/* App surfaces use packed 0x00RRGGBB pixels in row-major order. */
int bob64_framebuffer_write_pixels(u64 first_pixel,const u32 *pixels,u32 count);
void bob64_framebuffer_clear(void);
void bob64_framebuffer_write(const char *text);
#endif
+58
View File
@@ -0,0 +1,58 @@
#include "cpu.h"
#define CPUID_PAE (1u<<6)
#define CPUID_LONG_MODE (1u<<29)
#define CPUID_NX (1u<<20)
int bob64_cpu_decode_features(u32 max_basic_leaf,u32 max_extended_leaf,
u32 basic_leaf1_edx,u32 extended_leaf1_edx,
u32 extended_leaf8_eax,BOB64_CPU_FEATURES *features) {
u32 physical_bits;
if(!features)return -1;
features->PAE=(u8)(max_basic_leaf>=1&&(basic_leaf1_edx&CPUID_PAE)!=0);
features->LongMode=(u8)(max_extended_leaf>=0x80000001u&&
(extended_leaf1_edx&CPUID_LONG_MODE)!=0);
features->NX=(u8)(max_extended_leaf>=0x80000001u&&
(extended_leaf1_edx&CPUID_NX)!=0);
if(max_extended_leaf>=0x80000008u) {
physical_bits=extended_leaf8_eax&0xffu;
if(physical_bits<36||physical_bits>52)return -1;
} else physical_bits=36;
features->PhysicalAddressBits=(u8)physical_bits;
return 0;
}
static void cpuid(u32 leaf,u32 *eax,u32 *ebx,u32 *ecx,u32 *edx) {
u32 a=leaf,b=0,c=0,d=0;
__asm__ volatile("cpuid":"+a"(a),"=b"(b),"=c"(c),"=d"(d));
if(eax)*eax=a;
if(ebx)*ebx=b;
if(ecx)*ecx=c;
if(edx)*edx=d;
}
int bob64_cpu_detect(BOB64_CPU_FEATURES *features) {
u32 max_basic=0,max_extended=0,leaf1_edx=0,extended1_edx=0,extended8_eax=0;
cpuid(0,&max_basic,0,0,0);
cpuid(0x80000000u,&max_extended,0,0,0);
if(max_basic>=1)cpuid(1,0,0,0,&leaf1_edx);
if(max_extended>=0x80000001u)cpuid(0x80000001u,0,0,0,&extended1_edx);
if(max_extended>=0x80000008u)cpuid(0x80000008u,&extended8_eax,0,0,0);
return bob64_cpu_decode_features(max_basic,max_extended,leaf1_edx,
extended1_edx,extended8_eax,features);
}
int bob64_cpu_long_mode_active(const BOB64_CPU_FEATURES *features) {
u32 efer_low,efer_high;
u32 ecx=0xc0000080u;
if(!features||!features->PAE||!features->LongMode)return 0;
__asm__ volatile("rdmsr":"=a"(efer_low),"=d"(efer_high):"c"(ecx));
(void)efer_high;
return (efer_low&(1u<<10))!=0;
}
int bob64_cpu_four_level_paging_active(void) {
u64 cr4;
__asm__ volatile("mov %%cr4,%0":"=r"(cr4));
return (cr4&(1ULL<<5))!=0&&!(cr4&(1ULL<<12)); /* PAE set, LA57 clear. */
}
+20
View File
@@ -0,0 +1,20 @@
#ifndef BOB64_CPU_H
#define BOB64_CPU_H
#include "types.h"
typedef struct {
u8 PAE;
u8 LongMode;
u8 NX;
u8 PhysicalAddressBits;
} BOB64_CPU_FEATURES;
int bob64_cpu_decode_features(u32 max_basic_leaf,u32 max_extended_leaf,
u32 basic_leaf1_edx,u32 extended_leaf1_edx,
u32 extended_leaf8_eax,BOB64_CPU_FEATURES *features);
int bob64_cpu_detect(BOB64_CPU_FEATURES *features);
int bob64_cpu_long_mode_active(const BOB64_CPU_FEATURES *features);
int bob64_cpu_four_level_paging_active(void);
#endif
+71
View File
@@ -0,0 +1,71 @@
#include "descriptors.h"
#define BOB64_GDT_CODE 0x00af9a000000ffffULL
#define BOB64_GDT_DATA 0x00cf92000000ffffULL
#define BOB64_GDT_USER_CODE 0x00affa000000ffffULL
#define BOB64_GDT_USER_DATA 0x00cff2000000ffffULL
#define BOB64_GDT_TSS_ACCESS 0x89u
#define BOB64_IDT_PRESENT 0x80u
int bob64_tss_init(BOB64_TSS *tss,u64 ring0_stack_top) {
if(!tss||!ring0_stack_top||(ring0_stack_top&15))return -1;
for(usize i=0;i<sizeof(*tss);i++)((u8 *)tss)[i]=0;
tss->Rsp0=ring0_stack_top;
tss->IoMapBase=(u16)sizeof(*tss);
return 0;
}
int bob64_tss_set_rsp0(BOB64_TSS *tss,u64 ring0_stack_top) {
if(!tss||!ring0_stack_top||(ring0_stack_top&15))return -1;
tss->Rsp0=ring0_stack_top;
return 0;
}
void bob64_gdt_init(u64 entries[BOB64_GDT_ENTRY_COUNT],
BOB64_DESCRIPTOR_TABLE_POINTER *pointer,const BOB64_TSS *tss) {
u64 base,limit,descriptor;
if(!entries||!pointer||!tss)return;
base=(u64)(uintptr_t)tss;limit=sizeof(*tss)-1;
entries[0]=0;
entries[1]=BOB64_GDT_CODE;
entries[2]=BOB64_GDT_DATA;
entries[3]=BOB64_GDT_USER_DATA;
entries[4]=BOB64_GDT_USER_CODE;
descriptor=(limit&0xffffULL)|((base&0xffffffULL)<<16)|
((u64)BOB64_GDT_TSS_ACCESS<<40)|
((limit&0xf0000ULL)<<32)|((base&0xff000000ULL)<<32);
entries[5]=descriptor;entries[6]=base>>32;
pointer->Limit=(u16)(BOB64_GDT_ENTRY_COUNT*sizeof(entries[0])-1);
pointer->Base=(u64)(uintptr_t)entries;
}
int bob64_idt_set_gate(BOB64_IDT_GATE *gate,u64 handler,u16 selector,u8 ist,
u8 dpl,u8 gate_type) {
if(!gate||!handler||!selector||ist>7||dpl>3||
(gate_type!=BOB64_IDT_INTERRUPT_GATE&&gate_type!=BOB64_IDT_TRAP_GATE))
return -1;
gate->OffsetLow=(u16)handler;
gate->Selector=selector;
gate->Ist=ist;
gate->TypeAttributes=(u8)(BOB64_IDT_PRESENT|(dpl<<5)|gate_type);
gate->OffsetMiddle=(u16)(handler>>16);
gate->OffsetHigh=(u32)(handler>>32);
gate->Reserved=0;
return 0;
}
int bob64_idt_init(BOB64_IDT_GATE entries[BOB64_IDT_ENTRIES],u64 default_handler,
u16 selector,u8 ist) {
BOB64_IDT_GATE default_gate;
if(!entries||bob64_idt_set_gate(&default_gate,default_handler,selector,ist,0,
BOB64_IDT_INTERRUPT_GATE))return -1;
for(usize i=0;i<BOB64_IDT_ENTRIES;i++)entries[i]=default_gate;
return 0;
}
void bob64_idt_pointer(BOB64_DESCRIPTOR_TABLE_POINTER *pointer,
const BOB64_IDT_GATE entries[BOB64_IDT_ENTRIES]) {
if(!pointer||!entries)return;
pointer->Limit=(u16)(BOB64_IDT_ENTRIES*sizeof(entries[0])-1);
pointer->Base=(u64)(uintptr_t)entries;
}
+59
View File
@@ -0,0 +1,59 @@
#ifndef BOB64_DESCRIPTORS_H
#define BOB64_DESCRIPTORS_H
#include "types.h"
#define BOB64_GDT_KERNEL_CODE_SELECTOR 0x08u
#define BOB64_GDT_KERNEL_DATA_SELECTOR 0x10u
#define BOB64_GDT_USER_DATA_SELECTOR 0x1bu
#define BOB64_GDT_USER_CODE_SELECTOR 0x23u
#define BOB64_GDT_TSS_SELECTOR 0x28u
#define BOB64_GDT_ENTRY_COUNT 7u
#define BOB64_IDT_ENTRIES 256
#define BOB64_IDT_INTERRUPT_GATE 0x0eu
#define BOB64_IDT_TRAP_GATE 0x0fu
typedef struct __attribute__((packed)) {
u16 Limit;
u64 Base;
} BOB64_DESCRIPTOR_TABLE_POINTER;
typedef struct __attribute__((packed)) {
u16 OffsetLow;
u16 Selector;
u8 Ist;
u8 TypeAttributes;
u16 OffsetMiddle;
u32 OffsetHigh;
u32 Reserved;
} BOB64_IDT_GATE;
typedef struct __attribute__((packed)) {
u32 Reserved0;
u64 Rsp0,Rsp1,Rsp2;
u64 Reserved1;
u64 Ist1,Ist2,Ist3,Ist4,Ist5,Ist6,Ist7;
u64 Reserved2;
u16 Reserved3;
u16 IoMapBase;
} BOB64_TSS;
_Static_assert(sizeof(BOB64_DESCRIPTOR_TABLE_POINTER)==10,"x86-64 GDTR/IDTR layout");
_Static_assert(sizeof(BOB64_IDT_GATE)==16,"x86-64 IDT gate layout");
_Static_assert(sizeof(BOB64_TSS)==104,"x86-64 TSS layout");
_Static_assert(__builtin_offsetof(BOB64_TSS,Rsp0)==4,"x86-64 TSS RSP0 offset");
_Static_assert(__builtin_offsetof(BOB64_TSS,Ist1)==36,"x86-64 TSS IST offset");
_Static_assert(__builtin_offsetof(BOB64_TSS,IoMapBase)==102,"x86-64 TSS I/O map offset");
int bob64_tss_init(BOB64_TSS *tss,u64 ring0_stack_top);
int bob64_tss_set_rsp0(BOB64_TSS *tss,u64 ring0_stack_top);
void bob64_gdt_init(u64 entries[BOB64_GDT_ENTRY_COUNT],
BOB64_DESCRIPTOR_TABLE_POINTER *pointer,const BOB64_TSS *tss);
int bob64_idt_set_gate(BOB64_IDT_GATE *gate,u64 handler,u16 selector,u8 ist,
u8 dpl,u8 gate_type);
int bob64_idt_init(BOB64_IDT_GATE entries[BOB64_IDT_ENTRIES],u64 default_handler,
u16 selector,u8 ist);
void bob64_idt_pointer(BOB64_DESCRIPTOR_TABLE_POINTER *pointer,
const BOB64_IDT_GATE entries[BOB64_IDT_ENTRIES]);
#endif
+104
View File
@@ -0,0 +1,104 @@
#ifndef BOB64_EDITOR_H
#define BOB64_EDITOR_H
#include "abi.h"
#define BOB64_EDITOR_CAPACITY BOB64_SYSCALL_MAX_BUFFER
typedef struct {
char Text[BOB64_EDITOR_CAPACITY+1];
u32 Length;
u32 Cursor;
u32 ScrollRow;
u8 Dirty;
} BOB64_EDITOR;
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;
for(u32 i=0;i<length;i++)editor->Text[i]=text?text[i]:0;
editor->Text[length]=0;editor->Length=length;editor->Cursor=length;
editor->ScrollRow=0;editor->Dirty=0;
}
static inline int bob64_editor_insert(BOB64_EDITOR *editor,char character) {
if(!editor||editor->Length>=BOB64_EDITOR_CAPACITY||
!((character>=32&&character<=126)||character=='\n'))return -1;
for(u32 i=editor->Length;i>editor->Cursor;i--)editor->Text[i]=editor->Text[i-1];
editor->Text[editor->Cursor++]=character;
editor->Length++;editor->Text[editor->Length]=0;editor->Dirty=1;
return 0;
}
static inline int bob64_editor_backspace(BOB64_EDITOR *editor) {
if(!editor||!editor->Cursor)return -1;
for(u32 i=editor->Cursor-1;i<editor->Length-1;i++)editor->Text[i]=editor->Text[i+1];
editor->Cursor--;editor->Length--;editor->Text[editor->Length]=0;editor->Dirty=1;
return 0;
}
static inline int bob64_editor_delete(BOB64_EDITOR *editor) {
if(!editor||editor->Cursor>=editor->Length)return -1;
for(u32 i=editor->Cursor;i<editor->Length-1;i++)editor->Text[i]=editor->Text[i+1];
editor->Length--;editor->Text[editor->Length]=0;editor->Dirty=1;
return 0;
}
static inline void bob64_editor_move(BOB64_EDITOR *editor,s32 direction) {
if(!editor)return;
if(direction<0&&editor->Cursor)editor->Cursor--;
else if(direction>0&&editor->Cursor<editor->Length)editor->Cursor++;
}
static inline void bob64_editor_move_vertical(BOB64_EDITOR *editor,s32 direction) {
u32 line_start=0,column=0,target_start,target_end,target_column;
if(!editor||!direction)return;
for(u32 i=0;i<editor->Cursor;i++) {
if(editor->Text[i]=='\n'){line_start=i+1;column=0;}else column++;
}
if(direction<0) {
if(!line_start)return;
target_start=0;
for(u32 i=0;i<line_start-1;i++)if(editor->Text[i]=='\n')target_start=i+1;
target_end=line_start-1;
} else {
target_start=editor->Cursor;
while(target_start<editor->Length&&editor->Text[target_start]!='\n')target_start++;
if(target_start==editor->Length)return;
target_start++;
target_end=target_start;
while(target_end<editor->Length&&editor->Text[target_end]!='\n')target_end++;
}
target_column=column;
if(target_column>target_end-target_start)target_column=target_end-target_start;
editor->Cursor=target_start+target_column;
}
static inline void bob64_editor_visual_position(const BOB64_EDITOR *editor,
u32 columns,u32 *row_out,u32 *column_out) {
u32 row=0,column=0;
if(!editor||!row_out||!column_out)return;
if(!columns)columns=1;
for(u32 i=0;i<editor->Cursor;i++) {
if(column>=columns&&editor->Text[i]!='\n'){row++;column=0;}
if(editor->Text[i]=='\n'){row++;column=0;}
else column++;
}
if(column>=columns){row++;column=0;}
*row_out=row;*column_out=column;
}
static inline void bob64_editor_handle_key(BOB64_EDITOR *editor,const BOB64_EVENT *event) {
if(!editor||!event||event->Type!=BOB64_EVENT_KEY_DOWN)return;
if(event->Key==(BOB64_EVENT_KEY_EXTENDED|0x4b))bob64_editor_move(editor,-1);
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|0x53))bob64_editor_delete(editor);
else if(event->Character=='\b')bob64_editor_backspace(editor);
else if(event->Character=='\n')bob64_editor_insert(editor,'\n');
else if(event->Character>=32&&event->Character<=126)
bob64_editor_insert(editor,(char)event->Character);
}
#endif
+200
View File
@@ -0,0 +1,200 @@
#ifndef BOB64_EFI_H
#define BOB64_EFI_H
#include "types.h"
#define EFIAPI __attribute__((ms_abi))
typedef u16 CHAR16;
typedef uintptr_t UINTN;
typedef u64 EFI_STATUS;
typedef void *EFI_HANDLE;
#define EFI_SUCCESS 0ULL
#define EFI_INVALID_PARAMETER 0x8000000000000002ULL
#define EFI_BUFFER_TOO_SMALL 0x8000000000000005ULL
#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_PAGE_SIZE 4096ULL
typedef struct {
u64 Signature;
u32 Revision;
u32 HeaderSize;
u32 CRC32;
u32 Reserved;
} EFI_TABLE_HEADER;
typedef struct {
u32 Type;
u32 Pad;
u64 PhysicalStart;
u64 VirtualStart;
u64 NumberOfPages;
u64 Attribute;
} EFI_MEMORY_DESCRIPTOR;
typedef EFI_STATUS (EFIAPI *EFI_GET_MEMORY_MAP)(UINTN *,EFI_MEMORY_DESCRIPTOR *,
UINTN *,UINTN *,u32 *);
typedef EFI_STATUS (EFIAPI *EFI_ALLOCATE_POOL)(u32,UINTN,void **);
typedef struct {
u32 Data1;
u16 Data2;
u16 Data3;
u8 Data4[8];
} EFI_GUID;
typedef EFI_STATUS (EFIAPI *EFI_HANDLE_PROTOCOL)(EFI_HANDLE,const EFI_GUID *,void **);
typedef EFI_STATUS (EFIAPI *EFI_EXIT_BOOT_SERVICES)(EFI_HANDLE,UINTN);
typedef EFI_STATUS (EFIAPI *EFI_LOCATE_PROTOCOL)(const EFI_GUID *,void *,void **);
typedef struct {
EFI_TABLE_HEADER Hdr;
void *RaiseTPL;
void *RestoreTPL;
void *AllocatePages;
void *FreePages;
EFI_GET_MEMORY_MAP GetMemoryMap;
EFI_ALLOCATE_POOL AllocatePool;
void *FreePool;
void *CreateEvent;
void *SetTimer;
void *WaitForEvent;
void *SignalEvent;
void *CloseEvent;
void *CheckEvent;
void *InstallProtocolInterface;
void *ReinstallProtocolInterface;
void *UninstallProtocolInterface;
EFI_HANDLE_PROTOCOL HandleProtocol;
void *Reserved;
void *RegisterProtocolNotify;
void *LocateHandle;
void *LocateDevicePath;
void *InstallConfigurationTable;
void *LoadImage;
void *StartImage;
void *Exit;
void *UnloadImage;
EFI_EXIT_BOOT_SERVICES ExitBootServices;
void *GetNextMonotonicCount;
void *Stall;
void *SetWatchdogTimer;
void *ConnectController;
void *DisconnectController;
void *OpenProtocol;
void *CloseProtocol;
void *OpenProtocolInformation;
void *ProtocolsPerHandle;
void *LocateHandleBuffer;
EFI_LOCATE_PROTOCOL LocateProtocol;
} EFI_BOOT_SERVICES;
typedef struct {
u32 Version;
u32 HorizontalResolution;
u32 VerticalResolution;
u32 PixelFormat;
u32 PixelInformation[4];
u32 PixelsPerScanLine;
} EFI_GRAPHICS_OUTPUT_MODE_INFORMATION;
typedef struct {
u32 MaxMode;
u32 Mode;
EFI_GRAPHICS_OUTPUT_MODE_INFORMATION *Info;
UINTN SizeOfInfo;
u64 FrameBufferBase;
UINTN FrameBufferSize;
} EFI_GRAPHICS_OUTPUT_PROTOCOL_MODE;
typedef struct {
void *QueryMode;
void *SetMode;
void *Blt;
EFI_GRAPHICS_OUTPUT_PROTOCOL_MODE *Mode;
} EFI_GRAPHICS_OUTPUT_PROTOCOL;
typedef struct EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL;
typedef EFI_STATUS (EFIAPI *EFI_TEXT_RESET)(EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *, u8);
typedef EFI_STATUS (EFIAPI *EFI_TEXT_OUTPUT_STRING)(EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *, const CHAR16 *);
struct EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL {
EFI_TEXT_RESET Reset;
EFI_TEXT_OUTPUT_STRING OutputString;
void *TestString;
void *QueryMode;
void *SetMode;
void *SetAttribute;
void *ClearScreen;
void *SetCursorPosition;
void *EnableCursor;
void *Mode;
};
typedef struct {
EFI_TABLE_HEADER Hdr;
CHAR16 *FirmwareVendor;
u32 FirmwareRevision;
EFI_HANDLE ConsoleInHandle;
void *ConIn;
EFI_HANDLE ConsoleOutHandle;
EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *ConOut;
EFI_HANDLE StandardErrorHandle;
EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *StdErr;
void *RuntimeServices;
EFI_BOOT_SERVICES *BootServices;
UINTN NumberOfTableEntries;
void *ConfigurationTable;
} EFI_SYSTEM_TABLE;
typedef struct {
u32 Revision;
EFI_HANDLE ParentHandle;
EFI_SYSTEM_TABLE *SystemTable;
EFI_HANDLE DeviceHandle;
void *FilePath;
void *Reserved;
u32 LoadOptionsSize;
void *LoadOptions;
void *ImageBase;
u64 ImageSize;
u32 ImageCodeType;
u32 ImageDataType;
void *UnloadImage;
} EFI_LOADED_IMAGE_PROTOCOL;
_Static_assert(sizeof(uintptr_t)==sizeof(EFI_STATUS),"EFI x64 status width mismatch");
_Static_assert(__builtin_offsetof(EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL,OutputString)==8,
"UEFI text protocol layout mismatch");
_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(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");
_Static_assert(__builtin_offsetof(EFI_BOOT_SERVICES,AllocatePool)==64,
"UEFI x64 allocation service layout mismatch");
_Static_assert(__builtin_offsetof(EFI_BOOT_SERVICES,HandleProtocol)==152,
"UEFI x64 HandleProtocol table offset mismatch");
_Static_assert(__builtin_offsetof(EFI_BOOT_SERVICES,ExitBootServices)==232,
"UEFI x64 ExitBootServices table offset mismatch");
_Static_assert(__builtin_offsetof(EFI_BOOT_SERVICES,LocateProtocol)==320,
"UEFI x64 LocateProtocol table offset mismatch");
_Static_assert(sizeof(EFI_GRAPHICS_OUTPUT_MODE_INFORMATION)==36,
"UEFI GOP mode information layout mismatch");
_Static_assert(__builtin_offsetof(EFI_GRAPHICS_OUTPUT_PROTOCOL,Mode)==24,
"UEFI GOP protocol mode pointer offset mismatch");
_Static_assert(__builtin_offsetof(EFI_GRAPHICS_OUTPUT_PROTOCOL_MODE,FrameBufferBase)==24,
"UEFI GOP framebuffer base offset mismatch");
_Static_assert(__builtin_offsetof(EFI_GRAPHICS_OUTPUT_PROTOCOL_MODE,FrameBufferSize)==32&&
sizeof(EFI_GRAPHICS_OUTPUT_PROTOCOL_MODE)==40,
"UEFI GOP mode layout mismatch");
_Static_assert(__builtin_offsetof(EFI_LOADED_IMAGE_PROTOCOL,ImageBase)==64,
"UEFI loaded image base offset mismatch");
_Static_assert(__builtin_offsetof(EFI_LOADED_IMAGE_PROTOCOL,ImageSize)==72,
"UEFI loaded image size offset mismatch");
_Static_assert(sizeof(EFI_LOADED_IMAGE_PROTOCOL)==96,
"UEFI x64 loaded image protocol size mismatch");
#endif
+28
View File
@@ -0,0 +1,28 @@
.intel_syntax noprefix
#ifdef __MINGW32__
.section .rdata,"dr"
#else
.section .rodata
#endif
.balign 16
.globl bob64_embedded_app
.globl bob64_embedded_app_end
bob64_embedded_app:
.incbin "build/bob64-app/smoke.b64e"
bob64_embedded_app_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_source
.globl bob64_embedded_source_end
bob64_embedded_source:
.incbin "apps/bob64_demo.c"
bob64_embedded_source_end:
#ifndef __MINGW32__
.section .note.GNU-stack,"",@progbits
#endif
+33
View File
@@ -0,0 +1,33 @@
#ifndef BOB64_EVENT_H
#define BOB64_EVENT_H
#include "types.h"
#define BOB64_EVENT_KEY_DOWN 1u
#define BOB64_EVENT_KEY_UP 2u
#define BOB64_EVENT_MOUSE_MOVE 3u
#define BOB64_EVENT_MOUSE_BUTTON 4u
#define BOB64_EVENT_MOUSE_WHEEL 5u
#define BOB64_EVENT_MOD_SHIFT 1u
#define BOB64_EVENT_MOD_CAPS_LOCK 2u
#define BOB64_EVENT_MOD_CONTROL 4u
#define BOB64_EVENT_MOD_ALT 8u
#define BOB64_EVENT_KEY_EXTENDED 0x100u
/* Set-1 scan codes; extended keys set BOB64_EVENT_KEY_EXTENDED. */
typedef struct {
u32 Type;
u32 Key;
u32 Character;
u32 Modifiers;
s32 X,Y;
s32 DeltaX,DeltaY;
u32 Buttons;
s32 Wheel;
u64 WindowHandle;
s32 ScreenX,ScreenY;
} BOB64_EVENT;
_Static_assert(sizeof(BOB64_EVENT)==56,"bob64 input-event ABI size");
#endif
+66
View File
@@ -0,0 +1,66 @@
#include "exec.h"
#include "paging.h"
static u16 read16(const u8 *bytes) {
return (u16)((u16)bytes[0]|((u16)bytes[1]<<8));
}
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 payload_checksum(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;
}
int bob64_exec_parse(const void *file,usize file_size,BOB64_EXEC_IMAGE *image) {
const u8 *bytes=(const u8 *)file;
u64 payload_size,memory_size,entry_offset,code_size;
if(!bytes||!image||file_size<BOB64_EXEC_HEADER_SIZE||
bytes[0]!='B'||bytes[1]!='6'||bytes[2]!='4'||bytes[3]!='E'||
read16(bytes+4)!=BOB64_EXEC_VERSION||
read16(bytes+6)!=BOB64_EXEC_HEADER_SIZE||
read32(bytes+8)!=BOB64_EXEC_ABI_VERSION||read32(bytes+12)!=0)
return -1;
payload_size=read64(bytes+16);memory_size=read64(bytes+24);
entry_offset=read64(bytes+32);code_size=read64(bytes+40);
if(payload_size!=(u64)(file_size-BOB64_EXEC_HEADER_SIZE)||!code_size||
(code_size&(BOB64_PAGE_SIZE-1))||
code_size>payload_size||memory_size<payload_size||entry_offset>=code_size||
read32(bytes+48)!=payload_checksum(bytes+BOB64_EXEC_HEADER_SIZE,
file_size-BOB64_EXEC_HEADER_SIZE))
return -1;
for(usize i=52;i<BOB64_EXEC_HEADER_SIZE;i++)if(bytes[i])return -1;
image->Image=bytes+BOB64_EXEC_HEADER_SIZE;
image->FileSize=payload_size;image->MemorySize=memory_size;
image->EntryOffset=entry_offset;image->CodeSize=code_size;
image->AbiVersion=BOB64_EXEC_ABI_VERSION;image->Flags=0;
return 0;
}
int bob64_exec_load(const BOB64_EXEC_IMAGE *image,u64 load_address,
void *destination,usize destination_capacity,
u64 *entry_address) {
u8 *output=(u8 *)destination;
if(!image||!image->Image||!output||!entry_address||
image->AbiVersion!=BOB64_EXEC_ABI_VERSION||image->Flags||
!image->CodeSize||image->CodeSize>image->FileSize||
image->FileSize>image->MemorySize||image->EntryOffset>=image->CodeSize||
image->MemorySize>(u64)destination_capacity||
image->MemorySize>~(u64)0-load_address||
image->EntryOffset>~(u64)0-load_address)
return -1;
for(u64 i=0;i<image->FileSize;i++)output[(usize)i]=image->Image[(usize)i];
for(u64 i=image->FileSize;i<image->MemorySize;i++)output[(usize)i]=0;
*entry_address=load_address+image->EntryOffset;
return 0;
}
+29
View File
@@ -0,0 +1,29 @@
#ifndef BOB64_EXEC_H
#define BOB64_EXEC_H
#include "abi.h"
/* B64E is flat/PIC; code ends on a 4 KiB boundary. Offsets are bytes. */
#define BOB64_EXEC_VERSION 1u
#define BOB64_EXEC_ABI_VERSION BOB64_APP_ABI_VERSION
#define BOB64_EXEC_HEADER_SIZE 64u
typedef struct {
const u8 *Image;
u64 FileSize;
u64 MemorySize;
u64 EntryOffset;
u64 CodeSize;
u32 AbiVersion;
u32 Flags;
} BOB64_EXEC_IMAGE;
/* Parse and validate an exact B64E file. No allocations or state changes. */
int bob64_exec_parse(const void *file,usize file_size,BOB64_EXEC_IMAGE *image);
/* Copy a validated image, zero its memory tail, and return its full-width entry. */
int bob64_exec_load(const BOB64_EXEC_IMAGE *image,u64 load_address,
void *destination,usize destination_capacity,
u64 *entry_address);
#endif
+169
View File
@@ -0,0 +1,169 @@
#include "filesystem.h"
static usize string_length(const char *text) {
usize length=0;
while(text[length])length++;
return length;
}
static int valid_name(const char *name,usize *length) {
usize size;
if(!name)return 0;
size=string_length(name);
if(!size||size>=BOB64_FS_NAME_CAPACITY)return 0;
for(usize i=0;i<size;i++) {
char value=name[i];
if(!((value>='a'&&value<='z')||(value>='A'&&value<='Z')||
(value>='0'&&value<='9')||value=='.'||value=='_'||value=='-'))return 0;
}
if(length)*length=size;
return 1;
}
static BOB64_FS_FILE *find_file(const BOB64_FILESYSTEM *filesystem,const char *name,
BOB64_FS_FILE **previous) {
BOB64_FS_FILE *before=0;
if(!filesystem||!name)return 0;
for(BOB64_FS_FILE *file=filesystem->First;file;file=file->Next) {
const char *left=file->Name,*right=name;
while(*left&&*right&&*left==*right){left++;right++;}
if(!*left&&!*right) {
if(previous)*previous=before;
return file;
}
before=file;
}
if(previous)*previous=before;
return 0;
}
int bob64_fs_init(BOB64_FILESYSTEM *filesystem,BOB64_HEAP *heap) {
if(!filesystem||!heap)return -1;
filesystem->First=0;filesystem->Heap=heap;
filesystem->FileCount=0;filesystem->BytesUsed=0;
return 0;
}
int bob64_fs_write(BOB64_FILESYSTEM *filesystem,const char *name,
const void *data,usize length) {
usize name_length;
BOB64_FS_FILE *file;
char *new_data,*new_name=0;
if(!filesystem||!filesystem->Heap||!valid_name(name,&name_length)||
(!data&&length)||length==~(usize)0)return -1;
const u8 *source=(const u8 *)data;
file=find_file(filesystem,name,0);
new_data=(char *)bob64_heap_alloc(filesystem->Heap,length+1);
if(!new_data)return -1;
for(usize i=0;i<length;i++)new_data[i]=(char)source[i];
new_data[length]=0;
if(!file) {
file=(BOB64_FS_FILE *)bob64_heap_calloc(filesystem->Heap,1,sizeof(*file));
new_name=(char *)bob64_heap_alloc(filesystem->Heap,name_length+1);
if(!file||!new_name) {
if(file)bob64_heap_free(filesystem->Heap,file);
if(new_name)bob64_heap_free(filesystem->Heap,new_name);
bob64_heap_free(filesystem->Heap,new_data);
return -1;
}
for(usize i=0;i<name_length;i++)new_name[i]=name[i];
new_name[name_length]=0;
file->Name=new_name;file->Next=filesystem->First;
filesystem->First=file;filesystem->FileCount++;
} else {
filesystem->BytesUsed-=file->Length;
bob64_heap_free(filesystem->Heap,file->Data);
}
file->Data=new_data;file->Length=length;
filesystem->BytesUsed+=length;
return 0;
}
int bob64_fs_read(const BOB64_FILESYSTEM *filesystem,const char *name,
const char **data,usize *length) {
BOB64_FS_FILE *file;
if(!filesystem||!data||!length||!valid_name(name,0))return -1;
file=find_file(filesystem,name,0);
if(!file)return -1;
*data=file->Data;*length=file->Length;
return 0;
}
int bob64_fs_read_at(const BOB64_FILESYSTEM *filesystem,const char *name,
u64 offset,void *buffer,usize capacity,usize *read_count) {
BOB64_FS_FILE *file;
usize count;
if(!filesystem||!read_count||(!buffer&&capacity)||!valid_name(name,0))return -1;
file=find_file(filesystem,name,0);
if(!file)return -1;
if(offset>=file->Length){*read_count=0;return 0;}
count=file->Length-(usize)offset;
if(count>capacity)count=capacity;
for(usize i=0;i<count;i++)((u8 *)buffer)[i]=(u8)file->Data[(usize)offset+i];
*read_count=count;
return 0;
}
int bob64_fs_write_at(BOB64_FILESYSTEM *filesystem,const char *name,
u64 offset,const void *buffer,usize length) {
BOB64_FS_FILE *file;
usize end,new_length;
char *replacement;
if(!filesystem||!filesystem->Heap||(!buffer&&length)||
offset>(u64)(~(usize)0)||length>(usize)(~(usize)0)-(usize)offset||
!valid_name(name,0))return -1;
end=(usize)offset+length;
file=find_file(filesystem,name,0);
if(!file) {
if(offset)return -1;
return bob64_fs_write(filesystem,name,buffer,length);
}
new_length=file->Length>end?file->Length:end;
if(new_length==~(usize)0)return -1;
replacement=(char *)bob64_heap_alloc(filesystem->Heap,new_length+1);
if(!replacement)return -1;
for(usize i=0;i<new_length;i++)replacement[i]=i<file->Length?file->Data[i]:0;
for(usize i=0;i<length;i++)replacement[(usize)offset+i]=((const char *)buffer)[i];
replacement[new_length]=0;
filesystem->BytesUsed-=file->Length;
filesystem->BytesUsed+=new_length;
bob64_heap_free(filesystem->Heap,file->Data);
file->Data=replacement;file->Length=new_length;
return 0;
}
int bob64_fs_delete(BOB64_FILESYSTEM *filesystem,const char *name) {
BOB64_FS_FILE *previous=0,*file;
if(!filesystem||!filesystem->Heap||!valid_name(name,0))return -1;
file=find_file(filesystem,name,&previous);
if(!file)return -1;
if(previous)previous->Next=file->Next;
else filesystem->First=file->Next;
filesystem->BytesUsed-=file->Length;filesystem->FileCount--;
bob64_heap_free(filesystem->Heap,file->Name);
bob64_heap_free(filesystem->Heap,file->Data);
bob64_heap_free(filesystem->Heap,file);
return 0;
}
void bob64_fs_clear(BOB64_FILESYSTEM *filesystem) {
if(!filesystem)return;
while(filesystem->First) {
char name[BOB64_FS_NAME_CAPACITY];
usize length=string_length(filesystem->First->Name);
for(usize i=0;i<length;i++)name[i]=filesystem->First->Name[i];
name[length]=0;
if(bob64_fs_delete(filesystem,name))return;
}
}
usize bob64_fs_list(const BOB64_FILESYSTEM *filesystem,
BOB64_FS_LIST_CALLBACK callback,void *context) {
usize count=0;
if(!filesystem)return 0;
for(BOB64_FS_FILE *file=filesystem->First;file;file=file->Next) {
count++;
if(callback&&callback(context,file->Name,file->Length))break;
}
return count;
}
+40
View File
@@ -0,0 +1,40 @@
#ifndef BOB64_FILESYSTEM_H
#define BOB64_FILESYSTEM_H
#include "heap.h"
#include "memory.h"
#define BOB64_FS_NAME_CAPACITY 64
typedef struct BOB64_FS_FILE BOB64_FS_FILE;
struct BOB64_FS_FILE {
BOB64_FS_FILE *Next;
char *Name;
char *Data;
usize Length;
};
typedef struct {
BOB64_FS_FILE *First;
BOB64_HEAP *Heap;
usize FileCount,BytesUsed;
} BOB64_FILESYSTEM;
typedef int (*BOB64_FS_LIST_CALLBACK)(void *context,const char *name,usize length);
int bob64_fs_init(BOB64_FILESYSTEM *filesystem,BOB64_HEAP *heap);
/* File contents are length-delimited and may contain any byte value. */
int bob64_fs_write(BOB64_FILESYSTEM *filesystem,const char *name,
const void *data,usize length);
int bob64_fs_read(const BOB64_FILESYSTEM *filesystem,const char *name,
const char **data,usize *length);
int bob64_fs_read_at(const BOB64_FILESYSTEM *filesystem,const char *name,
u64 offset,void *buffer,usize capacity,usize *read_count);
int bob64_fs_write_at(BOB64_FILESYSTEM *filesystem,const char *name,
u64 offset,const void *buffer,usize length);
int bob64_fs_delete(BOB64_FILESYSTEM *filesystem,const char *name);
void bob64_fs_clear(BOB64_FILESYSTEM *filesystem);
usize bob64_fs_list(const BOB64_FILESYSTEM *filesystem,
BOB64_FS_LIST_CALLBACK callback,void *context);
#endif
+31
View File
@@ -0,0 +1,31 @@
#ifndef BOB64_FONT_H
#define BOB64_FONT_H
/* Compact 5x7 font: blank, A-Z, 0-9, ?, !, -, period, colon, equals, >. */
static const u8 bob64_font5x7[44][5]={
{0,0,0,0,0},
{0x7e,0x11,0x11,0x11,0x7e},{0x7f,0x49,0x49,0x49,0x36},
{0x3e,0x41,0x41,0x41,0x22},{0x7f,0x41,0x41,0x22,0x1c},
{0x7f,0x49,0x49,0x49,0x41},{0x7f,0x09,0x09,0x09,0x01},
{0x3e,0x41,0x49,0x49,0x7a},{0x7f,0x08,0x08,0x08,0x7f},
{0x00,0x41,0x7f,0x41,0x00},{0x20,0x40,0x41,0x3f,0x01},
{0x7f,0x08,0x14,0x22,0x41},{0x7f,0x40,0x40,0x40,0x40},
{0x7f,0x02,0x0c,0x02,0x7f},{0x7f,0x04,0x08,0x10,0x7f},
{0x3e,0x41,0x41,0x41,0x3e},{0x7f,0x09,0x09,0x09,0x06},
{0x3e,0x41,0x51,0x21,0x5e},{0x7f,0x09,0x19,0x29,0x46},
{0x46,0x49,0x49,0x49,0x31},{0x01,0x01,0x7f,0x01,0x01},
{0x3f,0x40,0x40,0x40,0x3f},{0x1f,0x20,0x40,0x20,0x1f},
{0x3f,0x40,0x38,0x40,0x3f},{0x63,0x14,0x08,0x14,0x63},
{0x07,0x08,0x70,0x08,0x07},{0x61,0x51,0x49,0x45,0x43},
{0x3e,0x51,0x49,0x45,0x3e},{0x00,0x42,0x7f,0x40,0x00},
{0x62,0x51,0x49,0x49,0x46},{0x22,0x41,0x49,0x49,0x36},
{0x18,0x14,0x12,0x7f,0x10},{0x2f,0x49,0x49,0x49,0x31},
{0x3e,0x49,0x49,0x49,0x32},{0x01,0x71,0x09,0x05,0x03},
{0x36,0x49,0x49,0x49,0x36},{0x26,0x49,0x49,0x49,0x3e},
{0x02,0x01,0x51,0x09,0x06},{0x00,0x00,0x5f,0x00,0x00},
{0x08,0x08,0x08,0x08,0x08},{0x00,0x60,0x60,0x00,0x00},
{0x00,0x36,0x36,0x00,0x00},{0x14,0x14,0x14,0x14,0x14},
{0x41,0x22,0x14,0x08,0x00}
};
#endif
+82
View File
@@ -0,0 +1,82 @@
#ifndef BOB64_GFX_H
#define BOB64_GFX_H
#include "app.h"
#include "font.h"
typedef struct {
u32 *Pixels;
u32 Width,Height;
usize Capacity;
} BOB64_GFX;
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;
graphics->Pixels=pixels;graphics->Width=width;graphics->Height=height;
graphics->Capacity=capacity;
return 0;
}
static inline void bob64_gfx_pixel(BOB64_GFX *graphics,s32 x,s32 y,u32 color) {
if(graphics&&x>=0&&y>=0&&(u32)x<graphics->Width&&(u32)y<graphics->Height)
graphics->Pixels[(usize)(u32)y*graphics->Width+(u32)x]=color&0x00ffffffu;
}
static inline void bob64_gfx_fill_rect(BOB64_GFX *graphics,s32 x,s32 y,
u32 width,u32 height,u32 color) {
if(!graphics)return;
for(u32 row=0;row<height;row++)for(u32 column=0;column<width;column++)
bob64_gfx_pixel(graphics,x+(s32)column,y+(s32)row,color);
}
static inline void bob64_gfx_line(BOB64_GFX *graphics,s32 x0,s32 y0,s32 x1,s32 y1,
u32 color) {
s32 dx=x1>x0?x1-x0:x0-x1,sx=x0<x1?1:-1;
s32 dy=y1>y0?y0-y1:y1-y0,sy=y0<y1?1:-1;
s32 error=dx+dy;
for(;;) {
bob64_gfx_pixel(graphics,x0,y0,color);
if(x0==x1&&y0==y1)break;
s32 twice=error*2;
if(twice>=dy){error+=dy;x0+=sx;}
if(twice<=dx){error+=dx;y0+=sy;}
}
}
static inline u32 bob64_gfx_glyph(u8 value) {
if(value>='a'&&value<='z')value=(u8)(value-'a'+'A');
if(value==' ')return 0;
if(value>='A'&&value<='Z')return 1u+(u32)(value-'A');
if(value>='0'&&value<='9')return 27u+(u32)(value-'0');
if(value=='?')return 37;
if(value=='!')return 38;
if(value=='-')return 39;
if(value=='.')return 40;
if(value==':')return 41;
if(value=='=')return 42;
if(value=='>')return 43;
return 37;
}
static inline void bob64_gfx_text(BOB64_GFX *graphics,s32 x,s32 y,
const char *text,u32 color,u32 scale) {
if(!graphics||!text||!scale)return;
while(*text) {
u32 glyph=bob64_gfx_glyph((u8)*text++);
for(u32 column=0;column<5;column++)for(u32 row=0;row<7;row++)
if(bob64_font5x7[glyph][column]&(1u<<row))
bob64_gfx_fill_rect(graphics,x+(s32)(column*scale),
y+(s32)(row*scale),scale,scale,color);
x+=(s32)(6*scale);
}
}
static inline int bob64_gfx_present(BOB64_GFX *graphics) {
if(!graphics||!graphics->Pixels)return -1;
return bob64_app_present(graphics->Pixels,graphics->Width,graphics->Height)==
(s64)((u64)graphics->Width*graphics->Height)?0:-1;
}
#endif
+48
View File
@@ -0,0 +1,48 @@
.intel_syntax noprefix
.text
.globl bob64_enter_kernel
bob64_enter_kernel:
/* Microsoft x64 ABI: fifth argument is above the 32-byte shadow area. */
mov r10,rcx
mov r11,rdx
mov r13,QWORD PTR [rsp+40]
cli
lgdt [r8]
push 0x08
lea rax,[rip+.Lbob64_reload_cs]
push rax
retfq
.Lbob64_reload_cs:
mov ax,0x28
ltr ax
lidt [r9]
mov ax,0x10
mov ds,ax
mov es,ax
mov ss,ax
cmp BYTE PTR [r13+81],0
je .Lbob64_nx_ready
mov ecx,0xc0000080
rdmsr
or eax,0x800
wrmsr
.Lbob64_nx_ready:
mov rax,cr0
or rax,0x10000
and rax,0xfffffffffffffffb
or rax,0x2
mov cr0,rax
mov rax,cr4
or rax,0x600
mov cr4,rax
mov cr3,r10
mov rsp,r11
and rsp,-16
sub rsp,32
mov rcx,r13
call bob64_kernel_main
.Lbob64_unexpected_return:
cli
hlt
jmp .Lbob64_unexpected_return
+128
View File
@@ -0,0 +1,128 @@
#include "heap.h"
#define BOB64_HEAP_BLOCK_MAGIC 0xB064B10Cu
#define BOB64_HEAP_ALIGNMENT 16u
#define BOB64_HEAP_MINIMUM_REGION 4096u
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);
return 1;
}
static BOB64_HEAP_BLOCK *block_at(void *address,usize bytes) {
BOB64_HEAP_BLOCK *block;
if(bytes<sizeof(*block)+BOB64_HEAP_ALIGNMENT||
(uintptr_t)address&(BOB64_HEAP_ALIGNMENT-1))return 0;
block=(BOB64_HEAP_BLOCK *)address;
block->Size=bytes-sizeof(*block);
block->Previous=0;block->Next=0;block->Magic=BOB64_HEAP_BLOCK_MAGIC;
block->Free=1;block->Reserved[0]=block->Reserved[1]=block->Reserved[2]=0;
return block;
}
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->Base=0;heap->MappedBytes=0;heap->MaximumBytes=maximum_bytes;
return 0;
}
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)
return block;
return 0;
}
static int grow_heap(BOB64_HEAP *heap) {
void *region=0;
usize bytes=0;
if(heap->MappedBytes>=heap->MaximumBytes||!heap->Grow(heap->Context,&region,&bytes)||
!region||!bytes||(bytes&(BOB64_HEAP_ALIGNMENT-1))||
bytes>heap->MaximumBytes-heap->MappedBytes||
((uintptr_t)region&(BOB64_HEAP_ALIGNMENT-1))||
heap->MappedBytes>~(uintptr_t)0-(uintptr_t)region)return -1;
if(heap->Base&&(u8 *)region!=(u8 *)heap->Base+heap->MappedBytes)return -1;
BOB64_HEAP_BLOCK *block=block_at(region,bytes);
if(!block)return -1;
if(!heap->Base)heap->Base=region;
heap->MappedBytes+=bytes;
if(heap->Last&&heap->Last->Free) {
heap->Last->Size+=sizeof(*block)+block->Size;
heap->Last->Next=0;
} else {
block->Previous=heap->Last;
if(heap->Last)heap->Last->Next=block;
else heap->First=block;
heap->Last=block;
}
return 0;
}
void *bob64_heap_alloc(BOB64_HEAP *heap,usize size) {
usize aligned;
if(!heap||!heap->Grow||!size||!align_size(size,&aligned))return 0;
BOB64_HEAP_BLOCK *block;
while(!(block=find_block(heap,aligned)))if(grow_heap(heap))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);
remainder->Size=block->Size-aligned-sizeof(*remainder);
remainder->Previous=block;remainder->Next=block->Next;
remainder->Magic=BOB64_HEAP_BLOCK_MAGIC;remainder->Free=1;
remainder->Reserved[0]=remainder->Reserved[1]=remainder->Reserved[2]=0;
if(remainder->Next)remainder->Next->Previous=remainder;
else heap->Last=remainder;
block->Next=remainder;block->Size=aligned;
}
block->Free=0;
return block+1;
}
void *bob64_heap_calloc(BOB64_HEAP *heap,usize count,usize size) {
usize bytes;
if(!count||!size||size>~(usize)0/count)return 0;
bytes=count*size;
void *pointer=bob64_heap_alloc(heap,bytes);
if(pointer) {
u8 *destination=(u8 *)pointer;
for(usize i=0;i<bytes;i++)destination[i]=0;
}
return pointer;
}
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;
base=(uintptr_t)heap->Base;
if(heap->MappedBytes>~(uintptr_t)0-base)return -1;
end=base+heap->MappedBytes;
if(address<base+sizeof(*block)||address>=end)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->Free=1;
if(block->Next&&block->Next->Magic==BOB64_HEAP_BLOCK_MAGIC&&block->Next->Free) {
BOB64_HEAP_BLOCK *next=block->Next;
block->Size+=sizeof(*next)+next->Size;block->Next=next->Next;
if(block->Next)block->Next->Previous=block;
else heap->Last=block;
next->Magic=0;
}
if(block->Previous&&block->Previous->Magic==BOB64_HEAP_BLOCK_MAGIC&&block->Previous->Free) {
BOB64_HEAP_BLOCK *previous=block->Previous;
previous->Size+=sizeof(*block)+block->Size;previous->Next=block->Next;
if(previous->Next)previous->Next->Previous=previous;
else heap->Last=previous;
block->Magic=0;
}
return 0;
}
usize bob64_heap_mapped_bytes(const BOB64_HEAP *heap) {
return heap?heap->MappedBytes:0;
}
+34
View File
@@ -0,0 +1,34 @@
#ifndef BOB64_HEAP_H
#define BOB64_HEAP_H
#include "types.h"
typedef int (*BOB64_HEAP_GROW)(void *context,void **region,usize *region_size);
typedef struct BOB64_HEAP_BLOCK BOB64_HEAP_BLOCK;
struct BOB64_HEAP_BLOCK {
usize Size;
BOB64_HEAP_BLOCK *Previous,*Next;
u32 Magic;
u8 Free;
u8 Reserved[3];
};
typedef struct {
BOB64_HEAP_BLOCK *First,*Last;
BOB64_HEAP_GROW Grow;
void *Context;
void *Base;
usize MappedBytes,MaximumBytes;
} BOB64_HEAP;
int bob64_heap_init(BOB64_HEAP *heap,usize maximum_bytes,
BOB64_HEAP_GROW grow,void *context);
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);
usize bob64_heap_mapped_bytes(const BOB64_HEAP *heap);
_Static_assert(sizeof(BOB64_HEAP_BLOCK)==32,"bob64 heap block ABI alignment");
#endif
+420
View File
@@ -0,0 +1,420 @@
.intel_syntax noprefix
.text
.macro BOB64_EXCEPTION_NO_ERROR number
.globl bob64_exception_\number
bob64_exception_\number:
push 0
push \number
jmp bob64_exception_common
.endm
.macro BOB64_EXCEPTION_ERROR number
.globl bob64_exception_\number
bob64_exception_\number:
push \number
jmp bob64_exception_common
.endm
BOB64_EXCEPTION_NO_ERROR 0
BOB64_EXCEPTION_NO_ERROR 1
BOB64_EXCEPTION_NO_ERROR 2
BOB64_EXCEPTION_NO_ERROR 3
BOB64_EXCEPTION_NO_ERROR 4
BOB64_EXCEPTION_NO_ERROR 5
BOB64_EXCEPTION_NO_ERROR 6
BOB64_EXCEPTION_NO_ERROR 7
BOB64_EXCEPTION_ERROR 8
BOB64_EXCEPTION_NO_ERROR 9
BOB64_EXCEPTION_ERROR 10
BOB64_EXCEPTION_ERROR 11
BOB64_EXCEPTION_ERROR 12
BOB64_EXCEPTION_ERROR 13
BOB64_EXCEPTION_ERROR 14
BOB64_EXCEPTION_NO_ERROR 15
BOB64_EXCEPTION_NO_ERROR 16
BOB64_EXCEPTION_ERROR 17
BOB64_EXCEPTION_NO_ERROR 18
BOB64_EXCEPTION_NO_ERROR 19
BOB64_EXCEPTION_NO_ERROR 20
BOB64_EXCEPTION_ERROR 21
BOB64_EXCEPTION_NO_ERROR 22
BOB64_EXCEPTION_NO_ERROR 23
BOB64_EXCEPTION_NO_ERROR 24
BOB64_EXCEPTION_NO_ERROR 25
BOB64_EXCEPTION_NO_ERROR 26
BOB64_EXCEPTION_NO_ERROR 27
BOB64_EXCEPTION_NO_ERROR 28
BOB64_EXCEPTION_ERROR 29
BOB64_EXCEPTION_ERROR 30
BOB64_EXCEPTION_NO_ERROR 31
.globl bob64_irq0_entry
bob64_irq0_entry:
push 0
push 32
push rax
push rbx
push rcx
push rdx
push rbp
push rsi
push rdi
push r8
push r9
push r10
push r11
push r12
push r13
push r14
push r15
mov r12,rsp
cld
and rsp,-16
sub rsp,32
mov rcx,r12
call bob64_irq_dispatch
mov rsp,r12
pop r15
pop r14
pop r13
pop r12
pop r11
pop r10
pop r9
pop r8
pop rdi
pop rsi
pop rbp
pop rdx
pop rcx
pop rbx
pop rax
add rsp,16
iretq
.globl bob64_irq1_entry
bob64_irq1_entry:
push 0
push 33
push rax
push rbx
push rcx
push rdx
push rbp
push rsi
push rdi
push r8
push r9
push r10
push r11
push r12
push r13
push r14
push r15
mov r12,rsp
cld
and rsp,-16
sub rsp,32
mov rcx,r12
call bob64_irq_dispatch
mov rsp,r12
pop r15
pop r14
pop r13
pop r12
pop r11
pop r10
pop r9
pop r8
pop rdi
pop rsi
pop rbp
pop rdx
pop rcx
pop rbx
pop rax
add rsp,16
iretq
.globl bob64_irq12_entry
bob64_irq12_entry:
push 0
push 44
push rax
push rbx
push rcx
push rdx
push rbp
push rsi
push rdi
push r8
push r9
push r10
push r11
push r12
push r13
push r14
push r15
mov r12,rsp
cld
and rsp,-16
sub rsp,32
mov rcx,r12
call bob64_irq_dispatch
mov rsp,r12
pop r15
pop r14
pop r13
pop r12
pop r11
pop r10
pop r9
pop r8
pop rdi
pop rsi
pop rbp
pop rdx
pop rcx
pop rbx
pop rax
add rsp,16
iretq
.globl bob64_unhandled_interrupt
bob64_unhandled_interrupt:
push 0
push 255
jmp bob64_exception_common
.globl bob64_exception_common
bob64_exception_common:
push rax
push rbx
push rcx
push rdx
push rbp
push rsi
push rdi
push r8
push r9
push r10
push r11
push r12
push r13
push r14
push r15
mov r12,rsp
cld
and rsp,-16
sub rsp,32
mov rcx,r12
call bob64_exception_dispatch
test rax,rax
jnz .Lbob64_user_abort_return
mov rsp,r12
pop r15
pop r14
pop r13
pop r12
pop r11
pop r10
pop r9
pop r8
pop rdi
pop rsi
pop rbp
pop rdx
pop rcx
pop rbx
pop rax
add rsp,16
iretq
.globl bob64_enter_user
bob64_enter_user:
/* Preserve the kernel ABI's nonvolatile registers across the privilege change. */
push rbx
push rbp
push rdi
push rsi
push r12
push r13
push r14
push r15
sub rsp,168
movdqa XMMWORD PTR [rsp],xmm6
movdqa XMMWORD PTR [rsp+16],xmm7
movdqa XMMWORD PTR [rsp+32],xmm8
movdqa XMMWORD PTR [rsp+48],xmm9
movdqa XMMWORD PTR [rsp+64],xmm10
movdqa XMMWORD PTR [rsp+80],xmm11
movdqa XMMWORD PTR [rsp+96],xmm12
movdqa XMMWORD PTR [rsp+112],xmm13
movdqa XMMWORD PTR [rsp+128],xmm14
movdqa XMMWORD PTR [rsp+144],xmm15
mov r10,QWORD PTR [rip+bob64_user_depth]
cmp r10,8
jae .Lbob64_user_depth_full
lea r11,[rip+bob64_user_return_frames]
lea r12,[r10+r10*4]
shl r12,3
add r11,r12
mov QWORD PTR [r11],rsp
mov QWORD PTR [r11+8],0
mov rax,QWORD PTR [rip+bob64_user_return_value]
mov QWORD PTR [r11+16],rax
pushfq
pop rax
and rax,0x200
mov QWORD PTR [r11+24],rax
mov rax,QWORD PTR [rip+bob64_user_active]
mov QWORD PTR [r11+32],rax
inc r10
mov QWORD PTR [rip+bob64_user_depth],r10
mov QWORD PTR [rip+bob64_user_return_value],0
mov QWORD PTR [rip+bob64_user_active],1
mov rax,rcx
mov rcx,rdx
/* User mode accepts IRQs; bob64_enter_user restores the caller's IF on return. */
push 0x1b
push r8
push 0x202
push 0x23
push rax
iretq
.Lbob64_user_depth_full:
mov rax,-1
movdqa xmm6,XMMWORD PTR [rsp]
movdqa xmm7,XMMWORD PTR [rsp+16]
movdqa xmm8,XMMWORD PTR [rsp+32]
movdqa xmm9,XMMWORD PTR [rsp+48]
movdqa xmm10,XMMWORD PTR [rsp+64]
movdqa xmm11,XMMWORD PTR [rsp+80]
movdqa xmm12,XMMWORD PTR [rsp+96]
movdqa xmm13,XMMWORD PTR [rsp+112]
movdqa xmm14,XMMWORD PTR [rsp+128]
movdqa xmm15,XMMWORD PTR [rsp+144]
add rsp,168
pop r15
pop r14
pop r13
pop r12
pop rsi
pop rdi
pop rbp
pop rbx
ret
.globl bob64_syscall_entry
bob64_syscall_entry:
push 0
push 128
push rax
push rbx
push rcx
push rdx
push rbp
push rsi
push rdi
push r8
push r9
push r10
push r11
push r12
push r13
push r14
push r15
mov r12,rsp
cld
and rsp,-16
sub rsp,32
mov rcx,r12
call bob64_syscall_dispatch
test rax,rax
jnz .Lbob64_user_abort_return
mov rsp,r12
pop r15
pop r14
pop r13
pop r12
pop r11
pop r10
pop r9
pop r8
pop rdi
pop rsi
pop rbp
pop rdx
pop rcx
pop rbx
pop rax
add rsp,16
iretq
.Lbob64_user_abort_return:
mov r10,QWORD PTR [rip+bob64_user_depth]
test r10,r10
jz .Lbob64_user_return_corrupt
dec r10
lea r11,[rip+bob64_user_return_frames]
lea r12,[r10+r10*4]
shl r12,3
add r11,r12
mov rsp,QWORD PTR [r11]
mov rax,QWORD PTR [r11+8]
mov r9,QWORD PTR [r11+24]
mov r8,QWORD PTR [r11+32]
mov rdx,QWORD PTR [r11+16]
movdqa xmm6,XMMWORD PTR [rsp]
movdqa xmm7,XMMWORD PTR [rsp+16]
movdqa xmm8,XMMWORD PTR [rsp+32]
movdqa xmm9,XMMWORD PTR [rsp+48]
movdqa xmm10,XMMWORD PTR [rsp+64]
movdqa xmm11,XMMWORD PTR [rsp+80]
movdqa xmm12,XMMWORD PTR [rsp+96]
movdqa xmm13,XMMWORD PTR [rsp+112]
movdqa xmm14,XMMWORD PTR [rsp+128]
movdqa xmm15,XMMWORD PTR [rsp+144]
add rsp,168
pop r15
pop r14
pop r13
pop r12
pop rsi
pop rdi
pop rbp
pop rbx
mov QWORD PTR [rip+bob64_user_depth],r10
mov QWORD PTR [rip+bob64_user_active],r8
mov QWORD PTR [rip+bob64_user_return_value],rdx
test r9,r9
jz .Lbob64_return_without_if
sti
.Lbob64_return_without_if:
ret
.Lbob64_user_return_corrupt:
cli
.Lbob64_user_return_halt:
hlt
jmp .Lbob64_user_return_halt
#ifdef __MINGW32__
.section .rdata,"dr"
#else
.section .rodata
#endif
.align 8
.globl bob64_exception_stub_table
bob64_exception_stub_table:
.quad bob64_exception_0,bob64_exception_1,bob64_exception_2,bob64_exception_3
.quad bob64_exception_4,bob64_exception_5,bob64_exception_6,bob64_exception_7
.quad bob64_exception_8,bob64_exception_9,bob64_exception_10,bob64_exception_11
.quad bob64_exception_12,bob64_exception_13,bob64_exception_14,bob64_exception_15
.quad bob64_exception_16,bob64_exception_17,bob64_exception_18,bob64_exception_19
.quad bob64_exception_20,bob64_exception_21,bob64_exception_22,bob64_exception_23
.quad bob64_exception_24,bob64_exception_25,bob64_exception_26,bob64_exception_27
.quad bob64_exception_28,bob64_exception_29,bob64_exception_30,bob64_exception_31
#ifndef __MINGW32__
.section .note.GNU-stack,"",@progbits
#endif
+259
View File
@@ -0,0 +1,259 @@
#include "interrupts.h"
#include "console.h"
#include "syscall.h"
#include "keyboard.h"
#include "mouse.h"
#define BOB64_COM1 0x3f8u
static int serial_available;
static u8 pic_ready;
static u8 pic_master_mask=0xff,pic_slave_mask=0xff;
static volatile u64 timer_tick_count;
volatile u64 bob64_user_exception_vector=~(u64)0;
volatile u64 bob64_user_exception_error=~(u64)0;
volatile u64 bob64_user_exception_rip=~(u64)0;
volatile u64 bob64_user_expected_exception_vector=~(u64)0;
volatile u64 bob64_user_expected_exception_error_mask;
volatile u64 bob64_user_expected_exception_error_value;
static void port_out8(u16 port,u8 value) {
__asm__ volatile("outb %0, %1"::"a"(value),"Nd"(port));
}
static u8 port_in8(u16 port) {
u8 value;
__asm__ volatile("inb %1, %0":"=a"(value):"Nd"(port));
return value;
}
static void serial_init(void) {
port_out8(BOB64_COM1+1,0x00);
port_out8(BOB64_COM1+3,0x80);
port_out8(BOB64_COM1+0,0x01);
port_out8(BOB64_COM1+1,0x00);
port_out8(BOB64_COM1+3,0x03);
port_out8(BOB64_COM1+2,0xc7);
port_out8(BOB64_COM1+4,0x0b);
serial_available=port_in8(BOB64_COM1+5)!=0xff;
}
static void serial_char(char value) {
if(!serial_available)return;
for(u32 timeout=0;timeout<100000;timeout++) {
if(port_in8(BOB64_COM1+5)&0x20) {
port_out8(BOB64_COM1,(u8)value);
return;
}
}
}
static void serial_text(const char *text) {
while(*text)serial_char(*text++);
}
static void diagnostic_text(const char *text) {
serial_text(text);
bob64_framebuffer_write(text);
}
static void serial_hex64(u64 value) {
static const char digits[]="0123456789abcdef";
for(int shift=60;shift>=0;shift-=4)serial_char(digits[(value>>shift)&15]);
}
void bob64_early_console_init(void) {
serial_init();
}
void bob64_early_console_write(const char *text) {
if(text)serial_text(text);
}
void bob64_early_console_hex64(u64 value) {
serial_hex64(value);
}
int bob64_early_console_try_read(void) {
if(!serial_available||(port_in8(BOB64_COM1+5)&1)==0)return -1;
return port_in8(BOB64_COM1);
}
static void diagnostic_register(const char *name,u64 value) {
static const char digits[]="0123456789abcdef";
char line[17];
diagnostic_text(name);diagnostic_text("=0x");
for(int i=0;i<16;i++)line[i]=digits[(value>>(60-i*4))&15];
line[16]=0;
diagnostic_text(line);diagnostic_text("\r\n");
}
int bob64_interrupts_build_idt(BOB64_IDT_GATE entries[BOB64_IDT_ENTRIES],u16 selector) {
if(!entries||bob64_idt_init(entries,(u64)(uintptr_t)bob64_unhandled_interrupt,
selector,0))return -1;
for(usize vector=0;vector<32;vector++) {
u64 handler=(u64)(uintptr_t)bob64_exception_stub_table[vector];
if(bob64_idt_set_gate(&entries[vector],handler,selector,0,0,
BOB64_IDT_INTERRUPT_GATE))return -1;
}
if(bob64_idt_set_gate(&entries[0x20],(u64)(uintptr_t)bob64_irq0_entry,
selector,0,0,BOB64_IDT_INTERRUPT_GATE))return -1;
if(bob64_idt_set_gate(&entries[0x80],(u64)(uintptr_t)bob64_syscall_entry,
selector,0,3,BOB64_IDT_INTERRUPT_GATE))return -1;
if(bob64_idt_set_gate(&entries[0x21],(u64)(uintptr_t)bob64_irq1_entry,
selector,0,0,BOB64_IDT_INTERRUPT_GATE))return -1;
if(bob64_idt_set_gate(&entries[0x2c],(u64)(uintptr_t)bob64_irq12_entry,
selector,0,0,BOB64_IDT_INTERRUPT_GATE))return -1;
return 0;
}
static int pic_initialize(void) {
if(pic_ready)return 0;
pic_master_mask=pic_slave_mask=0xff;
port_out8(0x21,pic_master_mask);port_out8(0xa1,pic_slave_mask);
port_out8(0x20,0x11);port_out8(0x80,0);
port_out8(0xa0,0x11);port_out8(0x80,0);
port_out8(0x21,0x20);port_out8(0x80,0);
port_out8(0xa1,0x28);port_out8(0x80,0);
port_out8(0x21,0x04);port_out8(0x80,0);
port_out8(0xa1,0x02);port_out8(0x80,0);
port_out8(0x21,0x01);port_out8(0x80,0);
port_out8(0xa1,0x01);port_out8(0x80,0);
pic_ready=1;
return 0;
}
static void pic_unmask(u8 irq) {
if(irq<8)pic_master_mask=(u8)(pic_master_mask&~(1u<<irq));
else {
pic_slave_mask=(u8)(pic_slave_mask&~(1u<<(irq-8)));
pic_master_mask=(u8)(pic_master_mask&~(1u<<2));
}
port_out8(0xa1,pic_slave_mask);port_out8(0x21,pic_master_mask);
}
void bob64_timer_irq_tick(void) { timer_tick_count++; }
u64 bob64_timer_ticks(void) { return timer_tick_count; }
int bob64_interrupts_enable_timer(void) {
u16 divisor=(u16)(1193182u/100u);
if(pic_initialize())return -1;
timer_tick_count=0;
port_out8(0x43,0x36);
port_out8(0x40,(u8)divisor);port_out8(0x40,(u8)(divisor>>8));
pic_unmask(0);
__asm__ volatile("sti":::"memory");
return 0;
}
static int wait_keyboard_controller(u8 mask,u8 expected) {
for(u32 i=0;i<100000;i++) {
u8 status=port_in8(0x64);
if(status==0xff)return -1;
if((status&mask)==expected)return 0;
}
return -1;
}
int bob64_interrupts_enable_keyboard(void) {
u8 command;
if(pic_initialize())return -1;
for(u32 i=0;i<32;i++) {
u8 status=port_in8(0x64);
if(status==0xff)return -1;
if(!(status&1))break;
if(status&0x20)return -1;
(void)port_in8(0x60);
}
if(wait_keyboard_controller(0,0))return -1;
port_out8(0x64,0x20);
if(wait_keyboard_controller(1,1))return -1;
if(port_in8(0x64)&0x20)return -1;
command=port_in8(0x60);
command=(u8)((command|1)&~0x10u); /* enable keyboard IRQ and clock */
if(wait_keyboard_controller(2,0))return -1;
port_out8(0x64,0x60);
if(wait_keyboard_controller(2,0))return -1;
port_out8(0x60,command);
bob64_keyboard_reset();
bob64_keyboard_irq_set_active(1);
pic_unmask(1);
__asm__ volatile("sti":::"memory");
return 0;
}
int bob64_interrupts_enable_mouse(void) {
u64 saved_flags;
u8 command;
__asm__ volatile("pushfq; pop %0; cli":"=r"(saved_flags)::"memory");
for(u32 i=0;i<32;i++) {
u8 status=port_in8(0x64);
if(status==0xff)goto failed;
if(!(status&1))break;
if(!(status&0x20))goto failed;
(void)port_in8(0x60);
}
if(wait_keyboard_controller(0,0))goto failed;
port_out8(0x64,0x20);
if(wait_keyboard_controller(1,1)||(port_in8(0x64)&0x20))goto failed;
command=port_in8(0x60);
command=(u8)((command|2)&~0x20u); /* enable mouse IRQ and clock */
if(wait_keyboard_controller(2,0))goto failed;
port_out8(0x64,0x60);
if(wait_keyboard_controller(2,0))goto failed;
port_out8(0x60,command);
bob64_mouse_irq_set_active(1);
pic_unmask(12);
__asm__ volatile("sti":::"memory");
return 0;
failed:
if(saved_flags&0x200)__asm__ volatile("sti":::"memory");
return -1;
}
void BOB64_MS_ABI bob64_irq_dispatch(const BOB64_INTERRUPT_FRAME *frame) {
if(frame&&frame->Vector==0x20) bob64_timer_irq_tick();
else if(frame&&frame->Vector==0x21) (void)bob64_keyboard_irq_service();
else if(frame&&frame->Vector==0x2c) {
(void)bob64_mouse_irq_service();
port_out8(0xa0,0x20);
}
/* IRQ1 is on the master; IRQ12 also needs the slave and cascade EOIs. */
port_out8(0x20,0x20);
}
u64 BOB64_MS_ABI bob64_exception_dispatch(const BOB64_INTERRUPT_FRAME *frame) {
__asm__ volatile("cli");
bob64_early_console_init();
int from_user=frame&&(frame->CS&3)==3&&bob64_user_active;
int expected_user_fault=from_user&&
frame->Vector==bob64_user_expected_exception_vector&&
(frame->ErrorCode&bob64_user_expected_exception_error_mask)==
bob64_user_expected_exception_error_value;
if(!expected_user_fault)
diagnostic_text(from_user?"bob64 user exception\r\n":"bob64 exception\r\n");
if(frame&&!expected_user_fault) {
diagnostic_register("vector",frame->Vector);
diagnostic_register("error",frame->ErrorCode);
diagnostic_register("rip",frame->RIP);
diagnostic_register("cs",frame->CS);
diagnostic_register("rflags",frame->RFLAGS);
diagnostic_register("rax",frame->RAX);diagnostic_register("rbx",frame->RBX);
diagnostic_register("rcx",frame->RCX);diagnostic_register("rdx",frame->RDX);
diagnostic_register("rbp",frame->RBP);diagnostic_register("rsi",frame->RSI);
diagnostic_register("rdi",frame->RDI);diagnostic_register("r8",frame->R8);
diagnostic_register("r9",frame->R9);diagnostic_register("r10",frame->R10);
diagnostic_register("r11",frame->R11);diagnostic_register("r12",frame->R12);
diagnostic_register("r13",frame->R13);diagnostic_register("r14",frame->R14);
diagnostic_register("r15",frame->R15);
}
if(from_user) {
bob64_user_exception_vector=frame->Vector;
bob64_user_exception_error=frame->ErrorCode;
bob64_user_exception_rip=frame->RIP;
bob64_user_expected_exception_vector=~(u64)0;
bob64_user_request_return(-(s64)(128+frame->Vector));
return 1;
}
diagnostic_text("system halted\r\n");
for(;;)__asm__ volatile("cli\n\thlt");
}
+45
View File
@@ -0,0 +1,45 @@
#ifndef BOB64_INTERRUPTS_H
#define BOB64_INTERRUPTS_H
#include "descriptors.h"
#include "abi.h"
typedef struct {
u64 R15,R14,R13,R12,R11,R10,R9,R8;
u64 RDI,RSI,RBP,RDX,RCX,RBX,RAX;
u64 Vector,ErrorCode,RIP,CS,RFLAGS;
} BOB64_INTERRUPT_FRAME;
_Static_assert(__builtin_offsetof(BOB64_INTERRUPT_FRAME,Vector)==120,
"interrupt stub register save layout");
_Static_assert(__builtin_offsetof(BOB64_INTERRUPT_FRAME,RIP)==136,
"interrupt hardware frame layout");
_Static_assert(sizeof(BOB64_INTERRUPT_FRAME)==160,
"interrupt frame fixed prefix size");
extern void (*bob64_exception_stub_table[32])(void);
extern void bob64_irq0_entry(void);
extern void bob64_syscall_entry(void);
extern void bob64_irq1_entry(void);
extern void bob64_irq12_entry(void);
extern volatile u64 bob64_user_exception_vector;
extern volatile u64 bob64_user_exception_error;
extern volatile u64 bob64_user_exception_rip;
extern volatile u64 bob64_user_expected_exception_vector;
extern volatile u64 bob64_user_expected_exception_error_mask;
extern volatile u64 bob64_user_expected_exception_error_value;
void bob64_unhandled_interrupt(void);
int bob64_interrupts_build_idt(BOB64_IDT_GATE entries[BOB64_IDT_ENTRIES],u16 selector);
void bob64_early_console_init(void);
int bob64_interrupts_enable_keyboard(void);
int bob64_interrupts_enable_mouse(void);
int bob64_interrupts_enable_timer(void);
void bob64_timer_irq_tick(void);
u64 bob64_timer_ticks(void);
void bob64_early_console_write(const char *text);
void bob64_early_console_hex64(u64 value);
int bob64_early_console_try_read(void);
u64 BOB64_MS_ABI bob64_exception_dispatch(const BOB64_INTERRUPT_FRAME *frame);
void BOB64_MS_ABI bob64_irq_dispatch(const BOB64_INTERRUPT_FRAME *frame);
#endif
+788
View File
@@ -0,0 +1,788 @@
#include "kernel.h"
#include "interrupts.h"
#include "paging.h"
#include "console.h"
#include "heap.h"
#include "runtime.h"
#include "keyboard.h"
#include "mouse.h"
#include "shell.h"
#include "filesystem.h"
#include "exec.h"
#include "process.h"
#include "syscall.h"
#include "compiler.h"
#define BOB64_KERNEL_HEAP_BASE 0xffff900000000000ULL
#define BOB64_KERNEL_HEAP_LIMIT (64ULL*1024ULL*1024ULL)
#define BOB64_KERNEL_PRIVILEGE_STACK_SIZE (16ULL*1024ULL)
static BOB64_HEAP kernel_heap;
static BOB64_FILESYSTEM kernel_filesystem;
static u64 kernel_next_window_owner=1;
static BOB64_SHELL kernel_shell;
typedef struct {
BOB64_FILESYSTEM *Filesystem;
u8 NxSupported,PhysicalAddressBits;
} KERNEL_APP_CONTEXT;
static KERNEL_APP_CONTEXT kernel_app_context;
static usize kernel_heap_mapped;
static void *kernel_privilege_stack;
static char kernel_user_output[5];
static usize kernel_user_output_length;
static u8 kernel_compiler_output[BOB64_COMPILER_IMAGE_LIMIT];
static void kernel_write(const char *text);
static int kernel_interrupts_enabled(void) {
u64 flags;
__asm__ volatile("pushfq; pop %0":"=r"(flags));
return (flags&0x200)!=0;
}
static void kernel_user_write_character(void *context,u8 character);
static int kernel_copy_user_bytes(void *context,u64 address,void *destination,
usize length);
static int kernel_process_fault_smoke_test(BOB64_PROCESS *process,
BOB64_PAGE_TABLE *process_table,const BOB64_PROCESS_OPERATIONS *operations,
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);
extern const u8 bob64_embedded_app[];
extern const u8 bob64_embedded_app_end[];
extern const u8 bob64_embedded_gui[];
extern const u8 bob64_embedded_gui_end[];
extern const u8 bob64_embedded_source[];
extern const u8 bob64_embedded_source_end[];
typedef struct {
BOB64_PAGE_TABLE *PageTable;
} KERNEL_PROCESS_CONTEXT;
static u64 read_cr3(void);
static u64 process_allocate_page(void *context) {
(void)context;
return bob64_page_alloc(&bob64_boot_page_allocator,1);
}
static int process_free_page(void *context,u64 physical_address) {
(void)context;
return bob64_page_free(&bob64_boot_page_allocator,physical_address,1);
}
static int process_map_page(void *context,u64 virtual_address,u64 physical_address,
u64 flags,u8 **writable_address) {
KERNEL_PROCESS_CONTEXT *process=(KERNEL_PROCESS_CONTEXT *)context;
if(!process||!process->PageTable||!writable_address||
bob64_page_map(process->PageTable,
virtual_address,physical_address,flags))return -1;
__asm__ volatile("invlpg (%0)"::"r"((void *)(uintptr_t)virtual_address):"memory");
*writable_address=(u8 *)(uintptr_t)virtual_address;
return 0;
}
static int process_protect_page(void *context,u64 virtual_address,u64 flags) {
KERNEL_PROCESS_CONTEXT *process=(KERNEL_PROCESS_CONTEXT *)context;
if(!process||!process->PageTable||
bob64_page_protect(process->PageTable,virtual_address,flags))return -1;
__asm__ volatile("invlpg (%0)"::"r"((void *)(uintptr_t)virtual_address):"memory");
return 0;
}
static int process_unmap_page(void *context,u64 virtual_address) {
KERNEL_PROCESS_CONTEXT *process=(KERNEL_PROCESS_CONTEXT *)context;
if(!process||!process->PageTable||
bob64_page_unmap(process->PageTable,virtual_address,0,0))return -1;
__asm__ volatile("invlpg (%0)"::"r"((void *)(uintptr_t)virtual_address):"memory");
return 0;
}
static void kernel_write16(u8 *bytes,u16 value) {
bytes[0]=(u8)value;bytes[1]=(u8)(value>>8);
}
static void kernel_write32(u8 *bytes,u32 value) {
for(u32 i=0;i<4;i++)bytes[i]=(u8)(value>>(i*8));
}
static void kernel_write64(u8 *bytes,u64 value) {
kernel_write32(bytes,(u32)value);kernel_write32(bytes+4,(u32)(value>>32));
}
static usize kernel_emit_test_syscall(u8 *code,usize offset,u32 number,u32 argument) {
code[offset++]=0xb8;kernel_write32(code+offset,number);offset+=4;
code[offset++]=0xb9;kernel_write32(code+offset,argument);offset+=4;
code[offset++]=0xcd;code[offset++]=0x80;
return offset;
}
static usize kernel_emit_test_buffer_syscall(u8 *code,usize offset,
const char *text,usize length) {
usize instruction_start=offset,lea_end,buffer_offset;
code[offset++]=0xb8;kernel_write32(code+offset,BOB64_SYSCALL_WRITE_BUFFER);offset+=4;
code[offset++]=0x48;code[offset++]=0x8d;code[offset++]=0x0d;
lea_end=offset+4;
buffer_offset=instruction_start+24;
kernel_write32(code+offset,(u32)(buffer_offset-lea_end));offset+=4;
code[offset++]=0xba;kernel_write32(code+offset,(u32)length);offset+=4;
code[offset++]=0xcd;code[offset++]=0x80;
code[offset++]=0xe9;
kernel_write32(code+offset,(u32)length);offset+=4;
for(usize i=0;i<length;i++)code[offset++]=(u8)text[i];
return offset;
}
static u32 kernel_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 int kernel_bytes_equal(const char *left,const char *right) {
while(*left&&*left==*right){left++;right++;}
return *left==*right;
}
static void kernel_build_bob_application(u8 *executable) {
static const char text[]="bob!";
usize code_size=0;
for(usize i=0;i<BOB64_EXEC_HEADER_SIZE+BOB64_PAGE_SIZE;i++)executable[i]=0;
executable[0]='B';executable[1]='6';executable[2]='4';executable[3]='E';
kernel_write16(executable+4,BOB64_EXEC_VERSION);
kernel_write16(executable+6,BOB64_EXEC_HEADER_SIZE);
kernel_write32(executable+8,BOB64_APP_ABI_VERSION);
kernel_write64(executable+16,BOB64_PAGE_SIZE);
kernel_write64(executable+24,2*BOB64_PAGE_SIZE);
kernel_write64(executable+32,0);
kernel_write64(executable+40,BOB64_PAGE_SIZE);
for(usize i=0;i<BOB64_PAGE_SIZE;i++)
executable[BOB64_EXEC_HEADER_SIZE+i]=0x90;
code_size=kernel_emit_test_syscall(executable+BOB64_EXEC_HEADER_SIZE,
code_size,BOB64_SYSCALL_QUERY_ABI,0);
code_size=kernel_emit_test_buffer_syscall(executable+BOB64_EXEC_HEADER_SIZE,
code_size,text,sizeof(text)-1);
(void)kernel_emit_test_syscall(executable+BOB64_EXEC_HEADER_SIZE,
code_size,BOB64_SYSCALL_EXIT,0);
kernel_write32(executable+48,kernel_crc32(executable+BOB64_EXEC_HEADER_SIZE,
(usize)BOB64_PAGE_SIZE));
}
static void kernel_build_code_write_fault_application(u8 *executable) {
static const char text[]="bob!";
u8 *code=executable+BOB64_EXEC_HEADER_SIZE;
usize offset;
kernel_build_bob_application(executable);
offset=kernel_emit_test_buffer_syscall(code,0,text,sizeof(text)-1);
code[offset++]=0xc6;code[offset++]=0x05;
kernel_write32(code+offset,(u32)(0-(offset+5)));offset+=4;
code[offset++]=0x90;
(void)offset;
kernel_write32(executable+48,kernel_crc32(executable+BOB64_EXEC_HEADER_SIZE,
(usize)BOB64_PAGE_SIZE));
}
static void kernel_build_nx_fault_application(u8 *executable) {
u8 *code=executable+BOB64_EXEC_HEADER_SIZE;
usize offset;
kernel_build_bob_application(executable);
offset=kernel_emit_test_buffer_syscall(code,0,"bob!",4);
code[offset++]=0xe9;
kernel_write32(code+offset,(u32)((u64)BOB64_PAGE_SIZE-(offset+4)));offset+=4;
executable[BOB64_EXEC_HEADER_SIZE+BOB64_PAGE_SIZE]=0x0f;
executable[BOB64_EXEC_HEADER_SIZE+BOB64_PAGE_SIZE+1]=0x0b;
kernel_write64(executable+16,2*BOB64_PAGE_SIZE);
kernel_write64(executable+24,2*BOB64_PAGE_SIZE);
kernel_write32(executable+48,kernel_crc32(executable+BOB64_EXEC_HEADER_SIZE,
(usize)(2*BOB64_PAGE_SIZE)));
}
static int kernel_install_bob_application(BOB64_FILESYSTEM *filesystem) {
usize length=(usize)(bob64_embedded_app_end-bob64_embedded_app);
if(length<BOB64_EXEC_HEADER_SIZE)return -1;
return bob64_fs_write(filesystem,"bob.b64e",bob64_embedded_app,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_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);
}
static int kernel_process_smoke_test(const BOB64_KERNEL_BOOT_INFO *info) {
static const char *arguments[]={"bob!"};
static u8 executable[BOB64_EXEC_HEADER_SIZE+BOB64_PAGE_SIZE];
static u8 nx_executable[BOB64_EXEC_HEADER_SIZE+2*BOB64_PAGE_SIZE];
BOB64_PAGE_TABLE process_table;
KERNEL_PROCESS_CONTEXT process_context={&process_table};
BOB64_PROCESS_OPERATIONS operations={process_allocate_page,process_free_page,
process_map_page,process_protect_page,process_unmap_page,&process_context,0};
BOB64_PROCESS process;
BOB64_PROCESS_PAGE *pages;
BOB64_APP_STARTUP *startup;
u64 physical,flags,kernel_root,table_checkpoint;
usize allocated_before;
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;
allocated_before=bob64_boot_page_allocator.AllocatedCount;
operations.NxSupported=info->NxSupported;
if(bob64_process_init(&process,pages,(usize)BOB64_PROCESS_PAGE_LIMIT,&operations)) {
bob64_heap_free(&kernel_heap,pages);return -1;
}
if(bob64_page_table_init(&process_table,info->PhysicalAddressBits,
bob64_bootstrap_space.PageTable.Allocate,bob64_bootstrap_space.PageTable.Access,
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;
bob64_heap_free(&kernel_heap,pages);return -1;
}
__asm__ volatile("mov %0,%%cr3"::"r"(process_table.RootPhysical):"memory");
kernel_build_bob_application(executable);
int result=bob64_process_load(&process,executable,sizeof(executable),1,arguments);
if(result) {
bob64_process_unload(&process);
__asm__ volatile("mov %0,%%cr3"::"r"(kernel_root):"memory");
bob64_bootstrap_space.TablePoolUsed=table_checkpoint;
bob64_heap_free(&kernel_heap,pages);return -1;
}
startup=(BOB64_APP_STARTUP *)(uintptr_t)process.StartupAddress;
result=process.EntryAddress==BOB64_PROCESS_IMAGE_BASE&&
startup->AbiVersion==BOB64_APP_ABI_VERSION&&startup->ArgumentCount==1&&
startup->Arguments&&kernel_bytes_equal(startup->Arguments[0],"bob!")&&
bob64_page_translate(&process_table,
BOB64_PROCESS_IMAGE_BASE,&physical,&flags)==1&&physical&&
(flags&BOB64_PAGE_USER)&&!(flags&BOB64_PAGE_WRITE)&&!(flags&BOB64_PAGE_NX)&&
bob64_page_translate(&process_table,
BOB64_PROCESS_IMAGE_BASE+BOB64_PAGE_SIZE,&physical,&flags)==1&&
(flags&BOB64_PAGE_USER)&&(flags&BOB64_PAGE_WRITE)&&(flags&BOB64_PAGE_NX)&&
bob64_page_translate(&process_table,
BOB64_PROCESS_STACK_GUARD,&physical,&flags)==0;
if(result) {
kernel_user_output_length=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);
bob64_syscall_set_wait_event(kernel_wait_for_input_event,0);
s64 app_status=bob64_enter_user(process.EntryAddress,process.StartupAddress,
process.InitialStackPointer);
bob64_syscall_set_wait_event(0,0);
bob64_syscall_set_write(0,0);
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||
!kernel_bytes_equal(kernel_user_output,"bob!"))result=0;
else kernel_write("\r\n");
}
int unload_result=bob64_process_unload(&process);
if(unload_result||process.PageCount||process.Loaded||
bob64_boot_page_allocator.AllocatedCount!=allocated_before)result=-1;
else result=result?0:-1;
if(!result) {
kernel_build_code_write_fault_application(executable);
if(kernel_process_fault_smoke_test(&process,&process_table,&operations,
executable,sizeof(executable),BOB64_PROCESS_IMAGE_BASE+28,0x7,0x7,
"bob64 kernel: read-only code protection passed\r\n"))result=-1;
}
if(!result) {
kernel_build_nx_fault_application(nx_executable);
if(kernel_process_fault_smoke_test(&process,&process_table,&operations,
nx_executable,sizeof(nx_executable),
BOB64_PROCESS_IMAGE_BASE+BOB64_PAGE_SIZE,0x15,0x15,
"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(bob64_boot_page_allocator.AllocatedCount!=allocated_before)result=-1;
if(bob64_heap_free(&kernel_heap,pages))result=-1;
return result;
}
static u64 read_cr3(void) {
u64 value;
__asm__ volatile("mov %%cr3,%0":"=r"(value));
return value&BOB64_PAGE_ADDRESS_MASK;
}
static __attribute__((noreturn)) void kernel_halt(void) {
__asm__ volatile("cli");
for(;;)__asm__ volatile("hlt");
}
static void kernel_write(const char *text) {
bob64_early_console_write(text);
bob64_framebuffer_write(text);
}
static void kernel_user_write_character(void *context,u8 character) {
char text[2]={(char)character,0};
(void)context;
if(kernel_user_output_length+1<sizeof(kernel_user_output))
kernel_user_output[kernel_user_output_length++]=(char)character;
kernel_write(text);
}
static int kernel_copy_user_bytes(void *context,u64 address,void *destination,
usize length) {
const volatile u8 *source=(const volatile u8 *)(uintptr_t)address;
u8 *target=(u8 *)destination;
(void)context;
if((!source&&length)||(!target&&length)||
length>BOB64_SYSCALL_COPY_CHUNK_BYTES)
return -1;
for(usize i=0;i<length;i++)target[i]=source[i];
return 0;
}
static int kernel_process_fault_smoke_test(BOB64_PROCESS *process,
BOB64_PAGE_TABLE *process_table,const BOB64_PROCESS_OPERATIONS *operations,
const u8 *executable,usize executable_size,u64 expected_rip,u64 error_mask,
u64 error_value,const char *success_message) {
static const char *arguments[]={"bob!"};
s64 status;
int passed;
if(bob64_process_init(process,process->Pages,process->PageCapacity,operations)||
bob64_process_load(process,executable,executable_size,1,arguments)) {
(void)bob64_process_unload(process);
return -1;
}
kernel_user_output_length=0;
bob64_user_exception_vector=~(u64)0;
bob64_user_exception_error=~(u64)0;
bob64_user_exception_rip=~(u64)0;
bob64_user_expected_exception_vector=14;
bob64_user_expected_exception_error_mask=error_mask;
bob64_user_expected_exception_error_value=error_value;
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);
status=bob64_enter_user(process->EntryAddress,process->StartupAddress,
process->InitialStackPointer);
bob64_user_expected_exception_vector=~(u64)0;
bob64_syscall_set_write(0,0);
bob64_syscall_set_read_user(0,0);
bob64_syscall_set_address_space(0);
kernel_user_output[kernel_user_output_length]=0;
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_bytes_equal(kernel_user_output,"bob!");
if(bob64_process_unload(process))return -1;
if(!passed)return -1;
kernel_write(success_message);
return 0;
}
static int kernel_wait_for_input_event(void *context,BOB64_EVENT *event) {
(void)context;
if(!event)return -1;
for(;;) {
if(!bob64_mouse_poll_event(event)||!bob64_keyboard_poll_event(event))return 0;
__asm__ volatile("pause");
}
}
static int kernel_write_user_bytes(void *context,u64 address,const void *source,
usize length) {
volatile u8 *target=(volatile u8 *)(uintptr_t)address;
const u8 *bytes=(const u8 *)source;
(void)context;
if((!target&&length)||(!bytes&&length)||length>BOB64_SYSCALL_MAX_BUFFER)
return -1;
for(usize i=0;i<length;i++)target[i]=bytes[i];
return 0;
}
static s64 kernel_app_read_file(void *context,const char *name,u8 *buffer,
usize capacity) {
KERNEL_APP_CONTEXT *app=(KERNEL_APP_CONTEXT *)context;
const char *data;
usize length;
if(!app||!app->Filesystem||!name||(!buffer&&capacity))return -22;
if(bob64_fs_read(app->Filesystem,name,&data,&length))return -2;
if(length>capacity)return -28;
for(usize i=0;i<length;i++)buffer[i]=(u8)data[i];
return (s64)length;
}
static s64 kernel_app_write_file(void *context,const char *name,const u8 *buffer,
usize length) {
KERNEL_APP_CONTEXT *app=(KERNEL_APP_CONTEXT *)context;
if(!app||!app->Filesystem||!name||(!buffer&&length))return -22;
if(bob64_fs_write(app->Filesystem,name,buffer,length))return -28;
return (s64)length;
}
static s64 kernel_app_open_stream(void *context,const char *name,u32 flags) {
KERNEL_APP_CONTEXT *app=(KERNEL_APP_CONTEXT *)context;
const char *data;usize length;
if(!app||!app->Filesystem||!name)return -22;
if(bob64_fs_read(app->Filesystem,name,&data,&length)) {
if(!(flags&BOB64_FILE_OPEN_CREATE))return -2;
if(bob64_fs_write(app->Filesystem,name,0,0))return -28;
length=0;
} else if(flags&BOB64_FILE_OPEN_TRUNCATE) {
if(bob64_fs_write(app->Filesystem,name,0,0))return -28;
length=0;
}
if(length>0x7fffffffffffffffULL)return -75;
return (s64)length;
}
static s64 kernel_app_read_stream(void *context,const char *name,u64 offset,
u8 *buffer,usize capacity) {
KERNEL_APP_CONTEXT *app=(KERNEL_APP_CONTEXT *)context;
usize count=0;
if(!app||!app->Filesystem||!name||(!buffer&&capacity))return -22;
if(bob64_fs_read_at(app->Filesystem,name,offset,buffer,capacity,&count))return -2;
return (s64)count;
}
static s64 kernel_app_write_stream(void *context,const char *name,u64 offset,
const u8 *buffer,usize length) {
KERNEL_APP_CONTEXT *app=(KERNEL_APP_CONTEXT *)context;
if(!app||!app->Filesystem||!name||(!buffer&&length))return -22;
if(bob64_fs_write_at(app->Filesystem,name,offset,buffer,length))return -28;
return (s64)length;
}
typedef struct {
BOB64_FILE_INFO *Entries;
usize Capacity,Count;
int Full;
} KERNEL_FILE_LIST_CONTEXT;
static int kernel_app_list_file(void *context,const char *name,usize size) {
KERNEL_FILE_LIST_CONTEXT *list=(KERNEL_FILE_LIST_CONTEXT *)context;
usize length=0;
BOB64_FILE_INFO *entry;
while(name[length]&&length<sizeof(list->Entries[0].Name)-1)length++;
if(name[length]||list->Count>=list->Capacity) {
list->Full=1;return 1;
}
entry=&list->Entries[list->Count++];
for(usize i=0;i<sizeof(*entry);i++)((u8 *)entry)[i]=0;
for(usize i=0;i<length;i++)entry->Name[i]=name[i];
entry->Size=(u64)size;
return 0;
}
static s64 kernel_app_list_files(void *context,BOB64_FILE_INFO *entries,
usize capacity) {
KERNEL_APP_CONTEXT *app=(KERNEL_APP_CONTEXT *)context;
KERNEL_FILE_LIST_CONTEXT list={entries,capacity,0,0};
if(!app||!app->Filesystem||!entries||!capacity)return -22;
bob64_fs_list(app->Filesystem,kernel_app_list_file,&list);
return list.Full?-28:(s64)list.Count;
}
static s64 kernel_app_delete_file(void *context,const char *name) {
KERNEL_APP_CONTEXT *app=(KERNEL_APP_CONTEXT *)context;
if(!app||!app->Filesystem||!name)return -22;
return bob64_fs_delete(app->Filesystem,name)?-2:0;
}
static s64 kernel_run_application(void *context,const char *name,usize argument_count,
const char *const *arguments,int *started) {
BOB64_PAGE_TABLE process_table;
KERNEL_PROCESS_CONTEXT process_context={&process_table};
BOB64_PROCESS_OPERATIONS operations;
BOB64_PROCESS process;
BOB64_PROCESS_PAGE *pages;
const char *image;
usize image_size;
u64 kernel_root,table_checkpoint;
s64 status=-1;
KERNEL_APP_CONTEXT *app=(KERNEL_APP_CONTEXT *)context;
void *application_privilege_stack=0;
BOB64_WINDOW_SERVER *window_server=0;
u64 previous_privilege_stack=bob64_kernel_tss.Rsp0;
int entered=0,cleanup_error=0,syscall_context_saved=0;
int window_server_ready=0;
u64 window_owner=0;
if(started)*started=0;
if(!app||!app->Filesystem||!app->NxSupported||!started||
!app->PhysicalAddressBits||
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,
app->NxSupported};
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;
if(bob64_process_init(&process,pages,(usize)BOB64_PROCESS_PAGE_LIMIT,&operations))
goto done;
if(bob64_page_table_init(&process_table,app->PhysicalAddressBits,
bob64_bootstrap_space.PageTable.Allocate,bob64_bootstrap_space.PageTable.Access,
bob64_bootstrap_space.PageTable.Context))goto done;
if(bob64_page_table_clone_isolated(&process_table,&bob64_bootstrap_space.PageTable,
BOB64_PROCESS_IMAGE_BASE,BOB64_PROCESS_ISOLATED_SIZE))goto done;
__asm__ volatile("mov %0,%%cr3"::"r"(process_table.RootPhysical):"memory");
if(bob64_process_load(&process,image,image_size,argument_count,arguments))goto restore;
application_privilege_stack=bob64_heap_alloc(&kernel_heap,
(usize)BOB64_KERNEL_PRIVILEGE_STACK_SIZE);
if(!application_privilege_stack) {
if(bob64_process_unload(&process))cleanup_error=1;
goto restore;
}
for(usize i=0;i<(usize)BOB64_KERNEL_PRIVILEGE_STACK_SIZE;i++)
((u8 *)application_privilege_stack)[i]=0;
u64 application_stack_top=(u64)(uintptr_t)application_privilege_stack+
BOB64_KERNEL_PRIVILEGE_STACK_SIZE;
if(bob64_tss_set_rsp0(&bob64_kernel_tss,application_stack_top)||
bob64_kernel_tss.Rsp0!=application_stack_top) {
if(bob64_process_unload(&process))cleanup_error=1;
goto restore;
}
if(bob64_syscall_context_push()) {
if(bob64_process_unload(&process))cleanup_error=1;
goto restore;
}
syscall_context_saved=1;
kernel_user_output_length=0;
u32 display_width,display_height;
if(!bob64_framebuffer_resolution(&display_width,&display_height)) {
window_owner=kernel_next_window_owner++;
if(!window_owner)window_owner=kernel_next_window_owner++;
window_server=(BOB64_WINDOW_SERVER *)bob64_heap_calloc(&kernel_heap,1,
sizeof(*window_server));
if(window_server&&!bob64_window_server_init(window_server,&kernel_heap,
window_owner,display_width,display_height))window_server_ready=1;
else if(window_server) {
bob64_window_server_close(window_server);
if(bob64_heap_free(&kernel_heap,window_server))cleanup_error=1;
window_server=0;
}
}
bob64_syscall_set_address_space(&process_table);
bob64_syscall_set_read_user(kernel_copy_user_bytes,0);
bob64_syscall_set_write_user(kernel_write_user_bytes,0);
bob64_syscall_set_filesystem(kernel_app_read_file,kernel_app_write_file,app);
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_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,
window_owner);
*started=1;entered=1;
status=bob64_enter_user(process.EntryAddress,process.StartupAddress,
process.InitialStackPointer);
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;
application_privilege_stack=0;
if(window_server_ready)bob64_window_server_close(window_server);
if(window_server&&bob64_heap_free(&kernel_heap,window_server))cleanup_error=1;
if(syscall_context_saved&&bob64_syscall_context_pop())cleanup_error=1;
kernel_write("\r\n");
if(bob64_process_unload(&process))cleanup_error=1;
restore:
if(application_privilege_stack) {
if(bob64_tss_set_rsp0(&bob64_kernel_tss,previous_privilege_stack))
cleanup_error=1;
if(bob64_heap_free(&kernel_heap,application_privilege_stack))cleanup_error=1;
application_privilege_stack=0;
}
__asm__ volatile("mov %0,%%cr3"::"r"(kernel_root):"memory");
done:
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_compile_application(void *context,const char *source_name,
const char *output_name,usize *error_offset) {
KERNEL_APP_CONTEXT *app=(KERNEL_APP_CONTEXT *)context;
const char *source;
usize source_length,output_length;
int result;
if(!app||!app->Filesystem||!source_name||!output_name||
bob64_fs_read(app->Filesystem,source_name,&source,&source_length))return -1;
result=bob64_compile_c(source,source_length,kernel_compiler_output,
sizeof(kernel_compiler_output),&output_length,error_offset);
if(result)return result;
if(bob64_fs_write(app->Filesystem,output_name,kernel_compiler_output,output_length))
return -1;
return 0;
}
static void kernel_hex64(u64 value) {
static const char digits[]="0123456789abcdef";
char text[17];
for(u32 i=0;i<16;i++)text[i]=digits[(value>>(60-i*4))&15];
text[16]=0;
kernel_write(text);
}
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;
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;
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))) {
bob64_page_free(&bob64_boot_page_allocator,physical,1);
return 0;
}
__asm__ volatile("invlpg (%0)"::"r"((void *)(uintptr_t)virtual_address):"memory");
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;
*region=(void *)(uintptr_t)virtual_address;
*region_size=(usize)EFI_PAGE_SIZE;
return 1;
}
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;
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);
if(!first||!large||!zero||((uintptr_t)first&15)||((uintptr_t)large&15)||
((uintptr_t)zero&15)||!((uintptr_t)first>=BOB64_KERNEL_HEAP_BASE))return -1;
first[0]='b';first[1]='o';first[2]='b';first[3]=0;
large[0]='6';large[1]='4';large[4999]='!';
for(usize i=0;i<64;i++)if(zero[i])return -1;
if(first[0]!='b'||first[1]!='o'||first[2]!='b'||large[0]!='6'||
large[1]!='4'||large[4999]!='!')return -1;
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;
return 0;
}
static int kernel_privilege_stack_init(void) {
kernel_privilege_stack=bob64_heap_alloc(&kernel_heap,
(usize)BOB64_KERNEL_PRIVILEGE_STACK_SIZE);
if(!kernel_privilege_stack)return -1;
for(usize i=0;i<(usize)BOB64_KERNEL_PRIVILEGE_STACK_SIZE;i++)
((u8 *)kernel_privilege_stack)[i]=0;
return bob64_tss_set_rsp0(&bob64_kernel_tss,
(u64)(uintptr_t)kernel_privilege_stack+
BOB64_KERNEL_PRIVILEGE_STACK_SIZE);
}
static void shell_write(void *context,const char *text) {
(void)context;
kernel_write(text);
}
static void shell_clear(void *context) {
(void)context;
bob64_framebuffer_clear();
bob64_early_console_write("\x1b[2J\x1b[H");
}
__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,
info->FramebufferSize,info->FramebufferWidth,info->FramebufferHeight,
info->FramebufferPixelsPerScanLine,info->FramebufferPixelFormat))
bob64_early_console_write("bob64 kernel: framebuffer rejected\r\n");
kernel_write("bob64!\r\nbob64 kernel: long mode entry\r\n");
if(!info||sizeof(void *)!=8||read_cr3()!=info->PageTableRoot||
!info->MemoryMapAddress||!info->MemoryMapSize||
info->MemoryDescriptorSize<40||!info->StackBase||!info->StackSize||
info->PhysicalAddressBits<36||info->PhysicalAddressBits>52||
info->NxSupported>1||info->HasFramebuffer>1) {
kernel_write("bob64 kernel: invalid boot information\r\n");
kernel_halt();
}
if(kernel_heap_smoke_test(info)) {
kernel_write("bob64 kernel: heap initialization failed\r\n");
kernel_halt();
}
if(kernel_privilege_stack_init()) {
kernel_write("bob64 kernel: privilege stack initialization failed\r\n");
kernel_halt();
}
int process_test=kernel_process_smoke_test(info);
if(process_test<0) {
kernel_write("bob64 kernel: application loader smoke test failed\r\n");
kernel_halt();
}
if(!process_test)kernel_write("bob64 kernel: ring-3 bob! app passed\r\n");
else kernel_write("bob64 kernel: app test skipped (NX unavailable)\r\n");
if(bob64_fs_init(&kernel_filesystem,&kernel_heap)) {
kernel_write("bob64 kernel: filesystem initialization failed\r\n");
kernel_halt();
}
if(info->NxSupported&&kernel_install_bob_application(&kernel_filesystem))
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(kernel_install_bob_source(&kernel_filesystem))
kernel_write("bob64 kernel: C demo source install failed\r\n");
kernel_app_context.Filesystem=&kernel_filesystem;
kernel_app_context.NxSupported=info->NxSupported;
kernel_app_context.PhysicalAddressBits=info->PhysicalAddressBits;
kernel_write("CR3=0x");kernel_hex64(info->PageTableRoot);
kernel_write(" memory-map=0x");kernel_hex64(info->MemoryMapAddress);
kernel_write(" bytes=0x");kernel_hex64(info->MemoryMapSize);
kernel_write(" heap=0x");kernel_hex64(BOB64_KERNEL_HEAP_BASE);
kernel_write(" mapped=0x");kernel_hex64((u64)bob64_heap_mapped_bytes(&kernel_heap));
kernel_write("\r\n");
kernel_write("bob64 kernel: memory checks passed\r\n");
if(bob64_interrupts_enable_timer()) {
kernel_write("bob64 kernel: timer IRQ unavailable\r\n");
kernel_halt();
}
kernel_write("bob64 kernel: timer IRQ enabled\r\n");
bob64_keyboard_reset();
int keyboard_irq_enabled=bob64_interrupts_enable_keyboard()==0;
if(!keyboard_irq_enabled)
kernel_write("bob64 kernel: keyboard IRQ unavailable; using polling\r\n");
else kernel_write("bob64 kernel: keyboard IRQ enabled\r\n");
if(info->NxSupported) {
int started=0;
s64 status=kernel_run_application(&kernel_app_context,"bob.b64e",0,0,&started);
if(!started||status||(keyboard_irq_enabled&&!kernel_interrupts_enabled())) {
kernel_write("bob64 kernel: native streaming app test failed\r\n");
kernel_halt();
}
kernel_write("bob64 kernel: native streaming app passed\r\n");
}
u32 display_width,display_height;
if(!bob64_framebuffer_resolution(&display_width,&display_height)) {
if(bob64_mouse_init(display_width,display_height))
kernel_write("bob64 kernel: PS/2 mouse unavailable\r\n");
else if(bob64_interrupts_enable_mouse())
kernel_write("bob64 kernel: mouse IRQ unavailable; using polling\r\n");
else kernel_write("bob64 kernel: PS/2 mouse IRQ enabled\r\n");
}
if(bob64_shell_init(&kernel_shell,&bob64_boot_page_allocator,&kernel_heap,
&kernel_filesystem,
shell_write,shell_clear,&kernel_app_context)) {
kernel_write("bob64 kernel: shell initialization failed\r\n");
kernel_halt();
}
bob64_shell_set_runner(&kernel_shell,kernel_run_application);
bob64_shell_set_compiler(&kernel_shell,kernel_compile_application);
for(;;) {
int character=bob64_keyboard_poll();
if(character<0)character=bob64_early_console_try_read();
if(character>=0)bob64_shell_input(&kernel_shell,character);
else __asm__ volatile("pause");
}
}
+37
View File
@@ -0,0 +1,37 @@
#ifndef BOB64_KERNEL_H
#define BOB64_KERNEL_H
#include "types.h"
#include "descriptors.h"
typedef struct {
u64 PageTableRoot;
u64 MemoryMapAddress;
u64 MemoryMapSize;
u64 MemoryDescriptorSize;
u64 StackBase;
u64 StackSize;
u64 FramebufferBase;
u64 FramebufferSize;
u32 FramebufferWidth;
u32 FramebufferHeight;
u32 FramebufferPixelsPerScanLine;
u32 FramebufferPixelFormat;
u8 PhysicalAddressBits;
u8 NxSupported;
u8 HasFramebuffer;
u8 Reserved[5];
} BOB64_KERNEL_BOOT_INFO;
_Static_assert(sizeof(BOB64_KERNEL_BOOT_INFO)==88,"bob64 kernel boot information ABI");
_Static_assert(__builtin_offsetof(BOB64_KERNEL_BOOT_INFO,NxSupported)==81,
"handoff assembly NX-support offset mismatch");
__attribute__((noreturn)) void bob64_kernel_main(const BOB64_KERNEL_BOOT_INFO *info);
__attribute__((noreturn)) void bob64_enter_kernel(
u64 page_table_root,u64 stack_top,
const BOB64_DESCRIPTOR_TABLE_POINTER *gdtr,
const BOB64_DESCRIPTOR_TABLE_POINTER *idtr,
const BOB64_KERNEL_BOOT_INFO *info);
#endif
+150
View File
@@ -0,0 +1,150 @@
#include "keyboard.h"
static BOB64_KEYBOARD_STATE keyboard_state;
#define KEYBOARD_EVENT_QUEUE_SIZE 64u
static BOB64_EVENT keyboard_event_queue[KEYBOARD_EVENT_QUEUE_SIZE];
static volatile u32 keyboard_event_head,keyboard_event_tail;
static volatile u8 keyboard_irq_active;
static const u8 unshifted[128]={
[0x02]='1',[0x03]='2',[0x04]='3',[0x05]='4',[0x06]='5',
[0x07]='6',[0x08]='7',[0x09]='8',[0x0a]='9',[0x0b]='0',
[0x0c]='-',[0x0d]='=',[0x0e]='\b',[0x0f]='\t',
[0x10]='q',[0x11]='w',[0x12]='e',[0x13]='r',[0x14]='t',
[0x15]='y',[0x16]='u',[0x17]='i',[0x18]='o',[0x19]='p',
[0x1a]='[',[0x1b]=']',[0x1c]='\n',[0x1e]='a',[0x1f]='s',
[0x20]='d',[0x21]='f',[0x22]='g',[0x23]='h',[0x24]='j',
[0x25]='k',[0x26]='l',[0x27]=';',[0x28]='\'',[0x29]='`',
[0x2b]='\\',[0x2c]='z',[0x2d]='x',[0x2e]='c',[0x2f]='v',
[0x30]='b',[0x31]='n',[0x32]='m',[0x33]=',',[0x34]='.',
[0x35]='/',[0x39]=' '
};
static const u8 shifted[128]={
[0x02]='!',[0x03]='@',[0x04]='#',[0x05]='$',[0x06]='%',
[0x07]='^',[0x08]='&',[0x09]='*',[0x0a]='(',[0x0b]=')',
[0x0c]='_',[0x0d]='+',[0x10]='Q',[0x11]='W',[0x12]='E',
[0x13]='R',[0x14]='T',[0x15]='Y',[0x16]='U',[0x17]='I',
[0x18]='O',[0x19]='P',[0x1a]='{',[0x1b]='}',[0x1e]='A',
[0x1f]='S',[0x20]='D',[0x21]='F',[0x22]='G',[0x23]='H',
[0x24]='J',[0x25]='K',[0x26]='L',[0x27]=':',[0x28]='"',
[0x29]='~',[0x2b]='|',[0x2c]='Z',[0x2d]='X',[0x2e]='C',
[0x2f]='V',[0x30]='B',[0x31]='N',[0x32]='M',[0x33]='<',
[0x34]='>',[0x35]='?'
};
void bob64_keyboard_reset(void) {
keyboard_state.LeftShift=0;keyboard_state.RightShift=0;
keyboard_state.LeftControl=0;keyboard_state.RightControl=0;
keyboard_state.LeftAlt=0;keyboard_state.RightAlt=0;
keyboard_state.CapsLock=0;keyboard_state.Extended=0;
keyboard_state.PauseRemaining=0;
keyboard_event_head=keyboard_event_tail=0;
}
void bob64_keyboard_irq_set_active(int active) {
keyboard_event_head=keyboard_event_tail=0;
keyboard_irq_active=(u8)(active!=0);
}
int bob64_keyboard_irq_capture(u8 scancode) {
BOB64_EVENT event;
u32 head=keyboard_event_head,tail=keyboard_event_tail;
if(bob64_keyboard_decode_event(&keyboard_state,scancode,&event))return -1;
if((u32)(head-tail)>=KEYBOARD_EVENT_QUEUE_SIZE)return -1;
keyboard_event_queue[head&(KEYBOARD_EVENT_QUEUE_SIZE-1)]=event;
__asm__ volatile("":::"memory");
keyboard_event_head=head+1;
return 0;
}
int bob64_keyboard_irq_pop_event(BOB64_EVENT *event) {
u32 tail=keyboard_event_tail,head=keyboard_event_head;
if(!event||tail==head)return -1;
__asm__ volatile("":::"memory");
*event=keyboard_event_queue[tail&(KEYBOARD_EVENT_QUEUE_SIZE-1)];
__asm__ volatile("":::"memory");
keyboard_event_tail=tail+1;
return 0;
}
int bob64_keyboard_irq_service(void) {
u8 status,scancode;
__asm__ volatile("inb $0x64,%0":"=a"(status));
if(status==0xff||!(status&1)||(status&0x20))return -1;
__asm__ volatile("inb $0x60,%0":"=a"(scancode));
return bob64_keyboard_irq_capture(scancode);
}
int bob64_keyboard_decode_event(BOB64_KEYBOARD_STATE *state,u8 scancode,
BOB64_EVENT *event) {
u8 released,code,letter,extended;
int character=0;
if(!state||!event)return -1;
if(state->PauseRemaining) { state->PauseRemaining--;return -1; }
if(scancode==0xe1) { state->PauseRemaining=5;state->Extended=0;return -1; }
if(scancode==0xe0) { state->Extended=1;return -1; }
extended=state->Extended;state->Extended=0;
released=(u8)(scancode&0x80);code=(u8)(scancode&0x7f);
if(!extended&&(code==0x2a||code==0x36)) {
u8 *shift=code==0x2a?&state->LeftShift:&state->RightShift;
*shift=(u8)!released;
} else if(code==0x1d) {
u8 *control=extended?&state->RightControl:&state->LeftControl;
*control=(u8)!released;
} else if(code==0x38) {
u8 *alt=extended?&state->RightAlt:&state->LeftAlt;
*alt=(u8)!released;
} else if(code==0x3a&&!released)state->CapsLock^=1;
else if(!released&&!extended) {
letter=(u8)(code>=0x10&&code<=0x32&&unshifted[code]>='a'&&unshifted[code]<='z');
u8 shift=(u8)(state->LeftShift||state->RightShift);
character=letter?((shift^state->CapsLock)?shifted[code]:unshifted[code]):
(shift&&shifted[code]?shifted[code]:unshifted[code]);
if(code==0x01)character=0x1b;
}
event->Type=released?BOB64_EVENT_KEY_UP:BOB64_EVENT_KEY_DOWN;
event->Key=(extended?BOB64_EVENT_KEY_EXTENDED:0u)|code;
event->Character=(u32)character;
event->Modifiers=(state->LeftShift||state->RightShift?BOB64_EVENT_MOD_SHIFT:0u)|
(state->CapsLock?BOB64_EVENT_MOD_CAPS_LOCK:0u)|
(state->LeftControl||state->RightControl?BOB64_EVENT_MOD_CONTROL:0u)|
(state->LeftAlt||state->RightAlt?BOB64_EVENT_MOD_ALT:0u);
event->X=0;event->Y=0;event->DeltaX=0;event->DeltaY=0;
event->Buttons=0;event->Wheel=0;event->WindowHandle=0;
event->ScreenX=0;event->ScreenY=0;
return 0;
}
int bob64_keyboard_decode(BOB64_KEYBOARD_STATE *state,u8 scancode) {
BOB64_EVENT event;
if(bob64_keyboard_decode_event(state,scancode,&event)||
event.Type!=BOB64_EVENT_KEY_DOWN||!event.Character)return -1;
return (int)event.Character;
}
int bob64_keyboard_poll(void) {
u8 status,scancode;
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;
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);
}
int bob64_keyboard_poll_event(BOB64_EVENT *event) {
u8 status,scancode;
if(!event)return -1;
if(keyboard_irq_active)return bob64_keyboard_irq_pop_event(event);
__asm__ volatile("inb $0x64,%0":"=a"(status));
if(status==0xff||!(status&1)||(status&0x20))return -1;
__asm__ volatile("inb $0x60,%0":"=a"(scancode));
return bob64_keyboard_decode_event(&keyboard_state,scancode,event);
}
+24
View File
@@ -0,0 +1,24 @@
#ifndef BOB64_KEYBOARD_H
#define BOB64_KEYBOARD_H
#include "types.h"
#include "event.h"
typedef struct {
u8 LeftShift,RightShift,LeftControl,RightControl,LeftAlt,RightAlt;
u8 CapsLock,Extended,PauseRemaining;
} BOB64_KEYBOARD_STATE;
void bob64_keyboard_reset(void);
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_poll_event(BOB64_EVENT *event);
/* IRQ producer and foreground consumer; the queue drops new events when full. */
int bob64_keyboard_irq_capture(u8 scancode);
int bob64_keyboard_irq_service(void);
int bob64_keyboard_irq_pop_event(BOB64_EVENT *event);
void bob64_keyboard_irq_set_active(int active);
#endif
+40
View File
@@ -0,0 +1,40 @@
#include "libc.h"
void *bob64_memcpy(void *destination,const void *source,usize length) {
u8 *out=(u8 *)destination;
const u8 *in=(const u8 *)source;
for(usize i=0;i<length;i++)out[i]=in[i];
return destination;
}
void *bob64_memmove(void *destination,const void *source,usize length) {
u8 *out=(u8 *)destination;
const u8 *in=(const u8 *)source;
if((uintptr_t)out<(uintptr_t)in)for(usize i=0;i<length;i++)out[i]=in[i];
else if((uintptr_t)out>(uintptr_t)in)
for(usize i=length;i;i--)out[i-1]=in[i-1];
return destination;
}
void *bob64_memset(void *destination,int value,usize length) {
u8 *out=(u8 *)destination;
for(usize i=0;i<length;i++)out[i]=(u8)value;
return destination;
}
int bob64_memcmp(const void *left,const void *right,usize length) {
const u8 *a=(const u8 *)left,*b=(const u8 *)right;
for(usize i=0;i<length;i++)if(a[i]!=b[i])return a[i]<b[i]?-1:1;
return 0;
}
usize bob64_strlen(const char *text) {
usize length=0;
while(text[length])length++;
return length;
}
int bob64_strcmp(const char *left,const char *right) {
while(*left&&*left==*right){left++;right++;}
return (u8)*left<(u8)*right?-1:(u8)*left>(u8)*right?1:0;
}
+13
View File
@@ -0,0 +1,13 @@
#ifndef BOB64_LIBC_H
#define BOB64_LIBC_H
#include "types.h"
void *bob64_memcpy(void *destination,const void *source,usize length);
void *bob64_memmove(void *destination,const void *source,usize length);
void *bob64_memset(void *destination,int value,usize length);
int bob64_memcmp(const void *left,const void *right,usize length);
usize bob64_strlen(const char *text);
int bob64_strcmp(const char *left,const char *right);
#endif
+116
View File
@@ -0,0 +1,116 @@
#include "memory.h"
#define BOB64_LOW_MEMORY_LIMIT 0x100000ULL
#define BOB64_U64_MAX (~(u64)0)
static int extent_end(u64 base,u64 pages,u64 *end) {
if(!pages||pages>(BOB64_U64_MAX-base)/EFI_PAGE_SIZE)return 0;
*end=base+pages*EFI_PAGE_SIZE;
return 1;
}
static void remove_extent(BOB64_PAGE_ALLOCATOR *allocator,usize index) {
for(usize i=index;i+1<allocator->Count;i++)allocator->Extents[i]=allocator->Extents[i+1];
allocator->Count--;
}
static int add_extent(BOB64_PAGE_ALLOCATOR *allocator,u64 base,u64 pages) {
usize index=0;
u64 end,next_end;
if(!pages)return 0;
if((base&(EFI_PAGE_SIZE-1))||!extent_end(base,pages,&end))return BOB64_PAGE_ALLOC_INVALID;
while(index<allocator->Count&&allocator->Extents[index].Base<base)index++;
if(index>0) {
BOB64_PAGE_EXTENT *previous=&allocator->Extents[index-1];
if(!extent_end(previous->Base,previous->Pages,&next_end)||next_end>base)
return BOB64_PAGE_ALLOC_INVALID;
}
if(index<allocator->Count&&end>allocator->Extents[index].Base)
return BOB64_PAGE_ALLOC_INVALID;
if(index>0) {
BOB64_PAGE_EXTENT *previous=&allocator->Extents[index-1];
if(previous->Base+previous->Pages*EFI_PAGE_SIZE==base) {
previous->Pages+=pages;
if(index<allocator->Count&&end==allocator->Extents[index].Base) {
previous->Pages+=allocator->Extents[index].Pages;
remove_extent(allocator,index);
}
return 0;
}
}
if(index<allocator->Count&&end==allocator->Extents[index].Base) {
allocator->Extents[index].Base=base;
allocator->Extents[index].Pages+=pages;
return 0;
}
if(allocator->Count>=allocator->Capacity)return BOB64_PAGE_ALLOC_FULL;
for(usize i=allocator->Count;i>index;i--)allocator->Extents[i]=allocator->Extents[i-1];
allocator->Extents[index].Base=base;
allocator->Extents[index].Pages=pages;
allocator->Count++;
return 0;
}
int bob64_page_allocator_init(BOB64_PAGE_ALLOCATOR *allocator,
BOB64_PAGE_EXTENT *storage,usize capacity,
u8 physical_address_bits,
const void *memory_map,usize memory_map_size,
usize descriptor_size) {
const u8 *bytes=(const u8 *)memory_map;
u64 physical_limit;
if(!allocator||!storage||!capacity||capacity>BOB64_PAGE_EXTENT_LIMIT||
physical_address_bits<36||physical_address_bits>52||
!memory_map||descriptor_size<sizeof(EFI_MEMORY_DESCRIPTOR)||
!memory_map_size||memory_map_size%descriptor_size)return BOB64_PAGE_ALLOC_INVALID;
physical_limit=1ULL<<physical_address_bits;
allocator->Count=0;allocator->Capacity=capacity;allocator->Extents=storage;
allocator->AllocatedCount=0;
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,end;
if(descriptor->Type!=EFI_MEMORY_CONVENTIONAL||!pages)continue;
if(!extent_end(base,pages,&end))return BOB64_PAGE_ALLOC_INVALID;
if(base>=physical_limit)continue;
if(end>physical_limit)pages=(physical_limit-base)/EFI_PAGE_SIZE;
if(base<BOB64_LOW_MEMORY_LIMIT) {
u64 skipped=(BOB64_LOW_MEMORY_LIMIT-base+EFI_PAGE_SIZE-1)/EFI_PAGE_SIZE;
if(skipped>=pages)continue;
base+=skipped*EFI_PAGE_SIZE;
pages-=skipped;
}
int result=add_extent(allocator,base,pages);
if(result)return result;
}
return (int)allocator->Count;
}
u64 bob64_page_alloc(BOB64_PAGE_ALLOCATOR *allocator,u64 pages) {
if(!allocator||!allocator->Extents||!pages||
allocator->AllocatedCount==BOB64_PAGE_ALLOCATION_LIMIT)return 0;
for(usize i=0;i<allocator->Count;i++)if(allocator->Extents[i].Pages>=pages) {
u64 address=allocator->Extents[i].Base;
allocator->Extents[i].Base+=pages*EFI_PAGE_SIZE;
allocator->Extents[i].Pages-=pages;
if(!allocator->Extents[i].Pages)remove_extent(allocator,i);
allocator->Allocated[allocator->AllocatedCount].Base=address;
allocator->Allocated[allocator->AllocatedCount].Pages=pages;
allocator->AllocatedCount++;
return address;
}
return 0;
}
int bob64_page_free(BOB64_PAGE_ALLOCATOR *allocator,u64 address,u64 pages) {
usize index=0;
int result;
if(!allocator||!allocator->Extents||address<BOB64_LOW_MEMORY_LIMIT||
(address&(EFI_PAGE_SIZE-1))||!pages)return BOB64_PAGE_ALLOC_INVALID;
while(index<allocator->AllocatedCount&&
(allocator->Allocated[index].Base!=address||allocator->Allocated[index].Pages!=pages))index++;
if(index==allocator->AllocatedCount)return BOB64_PAGE_ALLOC_INVALID;
result=add_extent(allocator,address,pages);
if(result)return result;
for(usize i=index;i+1<allocator->AllocatedCount;i++)allocator->Allocated[i]=allocator->Allocated[i+1];
allocator->AllocatedCount--;
return 0;
}
+33
View File
@@ -0,0 +1,33 @@
#ifndef BOB64_MEMORY_H
#define BOB64_MEMORY_H
#include "efi.h"
#define BOB64_PAGE_EXTENT_LIMIT 128
#define BOB64_PAGE_ALLOCATION_LIMIT 16384
#define BOB64_PAGE_ALLOC_INVALID (-1)
#define BOB64_PAGE_ALLOC_FULL (-2)
typedef struct {
u64 Base;
u64 Pages;
} BOB64_PAGE_EXTENT;
/* Sorted, non-overlapping runs of currently available physical 4 KiB pages. */
typedef struct {
usize Count;
usize Capacity;
BOB64_PAGE_EXTENT *Extents;
usize AllocatedCount;
BOB64_PAGE_EXTENT Allocated[BOB64_PAGE_ALLOCATION_LIMIT];
} BOB64_PAGE_ALLOCATOR;
int bob64_page_allocator_init(BOB64_PAGE_ALLOCATOR *allocator,
BOB64_PAGE_EXTENT *storage,usize capacity,
u8 physical_address_bits,
const void *memory_map,usize memory_map_size,
usize descriptor_size);
u64 bob64_page_alloc(BOB64_PAGE_ALLOCATOR *allocator,u64 pages);
int bob64_page_free(BOB64_PAGE_ALLOCATOR *allocator,u64 address,u64 pages);
#endif
+171
View File
@@ -0,0 +1,171 @@
#include "mouse.h"
static BOB64_MOUSE_STATE mouse_state;
#define MOUSE_EVENT_QUEUE_SIZE 64u
static BOB64_EVENT mouse_event_queue[MOUSE_EVENT_QUEUE_SIZE];
static volatile u32 mouse_event_head,mouse_event_tail;
static volatile u8 mouse_irq_active;
static void out8(u16 port,u8 value) {
__asm__ volatile("outb %0,%1"::"a"(value),"Nd"(port));
}
static u8 in8(u16 port) {
u8 value;
__asm__ volatile("inb %1,%0":"=a"(value):"Nd"(port));
return value;
}
static int wait_input_empty(void) {
for(u32 i=0;i<100000;i++) {
u8 status=in8(0x64);
if(status==0xff)return -1;
if(!(status&2))return 0;
}
return -1;
}
static int send_mouse_byte(u8 command) {
if(wait_input_empty())return -1;
out8(0x64,0xd4);
if(wait_input_empty())return -1;
out8(0x60,command);
for(u32 i=0;i<100000;i++) {
u8 status=in8(0x64);
if(status==0xff)return -1;
if((status&0x21)==0x21)return in8(0x60)==0xfa?0:-1;
}
return -1;
}
static int read_mouse_response(u8 *value) {
if(!value)return -1;
for(u32 i=0;i<100000;i++) {
u8 status=in8(0x64);
if(status==0xff)return -1;
if((status&0x21)==0x21) {*value=in8(0x60);return 0;}
}
return -1;
}
static int set_sample_rate(u8 rate) {
return send_mouse_byte(0xf3)||send_mouse_byte(rate)?-1:0;
}
int bob64_mouse_reset(BOB64_MOUSE_STATE *state,u32 width,u32 height) {
if(!state||!width||!height||width>0x7fffffffU||height>0x7fffffffU)return -1;
state->Width=width;state->Height=height;
state->X=(s32)(width/2);state->Y=(s32)(height/2);
state->Packet[0]=state->Packet[1]=state->Packet[2]=state->Packet[3]=0;
state->PacketLength=0;state->PacketSize=3;state->Buttons=0;
state->DeviceId=0;state->Enabled=0;
return 0;
}
int bob64_mouse_irq_queue_init(u32 width,u32 height) {
if(bob64_mouse_reset(&mouse_state,width,height))return -1;
mouse_event_head=mouse_event_tail=0;mouse_irq_active=0;
return 0;
}
void bob64_mouse_irq_set_active(int active) {
mouse_event_head=mouse_event_tail=0;
mouse_irq_active=(u8)(active!=0);
}
int bob64_mouse_irq_capture(u8 value) {
BOB64_EVENT event;
u32 head=mouse_event_head,tail=mouse_event_tail;
if(bob64_mouse_decode(&mouse_state,value,&event))return -1;
if((u32)(head-tail)>=MOUSE_EVENT_QUEUE_SIZE)return -1;
mouse_event_queue[head&(MOUSE_EVENT_QUEUE_SIZE-1)]=event;
__asm__ volatile("":::"memory");
mouse_event_head=head+1;
return 0;
}
int bob64_mouse_irq_pop_event(BOB64_EVENT *event) {
u32 tail=mouse_event_tail,head=mouse_event_head;
if(!event||tail==head)return -1;
__asm__ volatile("":::"memory");
*event=mouse_event_queue[tail&(MOUSE_EVENT_QUEUE_SIZE-1)];
__asm__ volatile("":::"memory");
mouse_event_tail=tail+1;
return 0;
}
int bob64_mouse_irq_service(void) {
u8 status,value;
__asm__ volatile("inb $0x64,%0":"=a"(status));
if(status==0xff||!(status&1)||!(status&0x20))return -1;
__asm__ volatile("inb $0x60,%0":"=a"(value));
return bob64_mouse_irq_capture(value);
}
static s32 signed_byte(u8 value) {
return value<128?(s32)value:(s32)value-256;
}
int bob64_mouse_decode(BOB64_MOUSE_STATE *state,u8 value,BOB64_EVENT *event) {
u8 flags,buttons;
s32 dx,dy,wheel=0,old_x,old_y,new_x,new_y;
s64 proposed_x,proposed_y;
if(!state||!event||!state->Width||!state->Height)return -1;
if(!state->PacketLength&&!(value&8))return -1;
if(state->PacketSize!=3&&state->PacketSize!=4)return -1;
state->Packet[state->PacketLength++]=value;
if(state->PacketLength<state->PacketSize)return -1;
state->PacketLength=0;
flags=state->Packet[0];buttons=(u8)(flags&7);
if(state->PacketSize==4) {
u8 wheel_nibble=(u8)(state->Packet[3]&15);
wheel=(wheel_nibble&8)?(s32)wheel_nibble-16:(s32)wheel_nibble;
if(state->DeviceId==4)buttons|=(u8)((state->Packet[3]&0x30)>>1);
}
dx=(flags&0x40)?0:signed_byte(state->Packet[1]);
dy=(flags&0x80)?0:-signed_byte(state->Packet[2]);
old_x=state->X;old_y=state->Y;
proposed_x=(s64)old_x+dx;proposed_y=(s64)old_y+dy;
if(proposed_x<0)proposed_x=0;
if(proposed_y<0)proposed_y=0;
if((u64)proposed_x>=state->Width)proposed_x=(s64)state->Width-1;
if((u64)proposed_y>=state->Height)proposed_y=(s64)state->Height-1;
new_x=(s32)proposed_x;new_y=(s32)proposed_y;
state->X=new_x;state->Y=new_y;
if(new_x==old_x&&new_y==old_y&&buttons==state->Buttons&&!wheel)return -1;
event->Type=buttons!=state->Buttons?BOB64_EVENT_MOUSE_BUTTON:
wheel?BOB64_EVENT_MOUSE_WHEEL:BOB64_EVENT_MOUSE_MOVE;
event->Key=0;event->Character=0;event->Modifiers=0;
event->X=new_x;event->Y=new_y;
event->DeltaX=new_x-old_x;event->DeltaY=new_y-old_y;
event->Buttons=buttons;event->Wheel=wheel;event->WindowHandle=0;
event->ScreenX=state->X;event->ScreenY=state->Y;
state->Buttons=buttons;
return 0;
}
int bob64_mouse_init(u32 width,u32 height) {
u8 device_id;
if(bob64_mouse_irq_queue_init(width,height))return -1;
if(wait_input_empty())return -1;
out8(0x64,0xa8);
if(send_mouse_byte(0xf4))return -1;
mouse_state.Enabled=1;
if(!set_sample_rate(200)&&!set_sample_rate(100)&&!set_sample_rate(80)&&
!send_mouse_byte(0xf2)&&!read_mouse_response(&device_id)&&
(device_id==3||device_id==4)) {
mouse_state.DeviceId=device_id;
mouse_state.PacketSize=4;
}
return 0;
}
int bob64_mouse_poll_event(BOB64_EVENT *event) {
u8 status,value;
if(!event||!mouse_state.Enabled)return -1;
if(mouse_irq_active)return bob64_mouse_irq_pop_event(event);
status=in8(0x64);
if(status==0xff||!(status&1)||!(status&0x20))return -1;
value=in8(0x60);
return bob64_mouse_decode(&mouse_state,value,event);
}
+23
View File
@@ -0,0 +1,23 @@
#ifndef BOB64_MOUSE_H
#define BOB64_MOUSE_H
#include "event.h"
typedef struct {
u32 Width,Height;
s32 X,Y;
u8 Packet[4];
u8 PacketLength,PacketSize,Buttons,DeviceId,Enabled;
} BOB64_MOUSE_STATE;
int bob64_mouse_reset(BOB64_MOUSE_STATE *state,u32 width,u32 height);
int bob64_mouse_decode(BOB64_MOUSE_STATE *state,u8 value,BOB64_EVENT *event);
int bob64_mouse_init(u32 width,u32 height);
int bob64_mouse_poll_event(BOB64_EVENT *event);
int bob64_mouse_irq_queue_init(u32 width,u32 height);
int bob64_mouse_irq_capture(u8 value);
int bob64_mouse_irq_service(void);
int bob64_mouse_irq_pop_event(BOB64_EVENT *event);
void bob64_mouse_irq_set_active(int active);
#endif
+272
View File
@@ -0,0 +1,272 @@
#include "paging.h"
#define BOB64_PAGE_LARGE 0x080ULL
#define BOB64_U64_MAX (~(u64)0)
static int canonical_address(u64 address) {
u64 top=address>>48;
return ((address>>47)&1)?top==0xffffULL:top==0;
}
static u64 physical_address_mask(u8 bits) {
return ((1ULL<<bits)-1)&BOB64_PAGE_ADDRESS_MASK;
}
static int physical_page_valid(u64 address,u8 bits) {
u64 mask;
if(bits<36||bits>52)return 0;
mask=physical_address_mask(bits);
return !(address&(BOB64_PAGE_SIZE-1))&&!(address&~mask);
}
static u64 *table_entries(const BOB64_PAGE_TABLE *table,u64 physical) {
if(!table||!table->Access||!physical_page_valid(physical,table->PhysicalAddressBits))return 0;
return table->Access(table->Context,physical);
}
int bob64_page_table_init(BOB64_PAGE_TABLE *table,u8 physical_address_bits,
BOB64_TABLE_ALLOCATE allocate,BOB64_TABLE_ACCESS access,
void *context) {
u64 root;
u64 *entries;
if(!table||!allocate||!access||physical_address_bits<36||physical_address_bits>52)
return BOB64_PAGING_INVALID;
root=allocate(context);
if(!root||!physical_page_valid(root,physical_address_bits))return BOB64_PAGING_NO_MEMORY;
entries=access(context,root);
if(!entries)return BOB64_PAGING_INVALID;
for(usize i=0;i<512;i++)entries[i]=0;
table->RootPhysical=root;table->PhysicalAddressBits=physical_address_bits;
table->Allocate=allocate;table->Access=access;
table->Context=context;
return 0;
}
static int copy_table_page(BOB64_PAGE_TABLE *destination,
const BOB64_PAGE_TABLE *source,u64 source_physical,
u64 *destination_physical) {
u64 physical=destination->Allocate(destination->Context);
u64 *target;
if(!physical||!physical_page_valid(physical,destination->PhysicalAddressBits))
return BOB64_PAGING_NO_MEMORY;
target=destination->Access(destination->Context,physical);
if(!target)return BOB64_PAGING_NO_MEMORY;
if(source_physical) {
u64 *original=table_entries(source,source_physical);
if(!original)return BOB64_PAGING_INVALID;
for(usize i=0;i<512;i++)target[i]=original[i];
} else for(usize i=0;i<512;i++)target[i]=0;
*destination_physical=physical;
return 0;
}
int bob64_page_table_clone_isolated(BOB64_PAGE_TABLE *destination,
const BOB64_PAGE_TABLE *source,
u64 isolated_base,u64 isolated_size) {
u64 *source_root,*destination_root,*source_pdpt,*destination_pdpt;
u64 *destination_pd,source_entry,new_pdpt,new_pd;
u64 end,last,base_page,end_page;
usize pml4_index,pdpt_index,first_pd,last_pd;
int result;
if(!destination||!source||!destination->RootPhysical||!source->RootPhysical||
destination->RootPhysical==source->RootPhysical||!isolated_size||
(isolated_base&((1ULL<<21)-1))||
(isolated_size&((1ULL<<21)-1))||isolated_size>BOB64_U64_MAX-isolated_base)
return BOB64_PAGING_INVALID;
end=isolated_base+isolated_size;last=end-1;
if(!canonical_address(isolated_base)||!canonical_address(last)||
(((isolated_base>>47)&1)!=((last>>47)&1))||
((isolated_base>>39)&0x1ff)!=((last>>39)&0x1ff)||
((isolated_base>>30)&0x1ff)!=((last>>30)&0x1ff))
return BOB64_PAGING_INVALID;
source_root=table_entries(source,source->RootPhysical);
destination_root=table_entries(destination,destination->RootPhysical);
if(!source_root||!destination_root)return BOB64_PAGING_INVALID;
for(usize i=0;i<512;i++)destination_root[i]=source_root[i];
pml4_index=(usize)((isolated_base>>39)&0x1ff);
pdpt_index=(usize)((isolated_base>>30)&0x1ff);
source_entry=source_root[pml4_index];
result=copy_table_page(destination,source,
(source_entry&BOB64_PAGE_PRESENT)?source_entry&BOB64_PAGE_ADDRESS_MASK:0,
&new_pdpt);
if(result)return result;
destination_root[pml4_index]=new_pdpt|
((source_entry&~BOB64_PAGE_ADDRESS_MASK)|BOB64_PAGE_PRESENT|
BOB64_PAGE_WRITE|BOB64_PAGE_USER);
destination_pdpt=destination->Access(destination->Context,new_pdpt);
if(!destination_pdpt)return BOB64_PAGING_INVALID;
source_pdpt=(source_entry&BOB64_PAGE_PRESENT)?
table_entries(source,source_entry&BOB64_PAGE_ADDRESS_MASK):0;
if((source_entry&BOB64_PAGE_PRESENT)&&!source_pdpt)return BOB64_PAGING_INVALID;
source_entry=source_pdpt?source_pdpt[pdpt_index]:0;
if((source_entry&BOB64_PAGE_PRESENT)&&(source_entry&BOB64_PAGE_LARGE))
return BOB64_PAGING_INVALID;
result=copy_table_page(destination,source,
(source_entry&BOB64_PAGE_PRESENT)?source_entry&BOB64_PAGE_ADDRESS_MASK:0,
&new_pd);
if(result)return result;
destination_pdpt[pdpt_index]=new_pd|
((source_entry&~BOB64_PAGE_ADDRESS_MASK)|BOB64_PAGE_PRESENT|
BOB64_PAGE_WRITE|BOB64_PAGE_USER);
destination_pd=destination->Access(destination->Context,new_pd);
if(!destination_pd)return BOB64_PAGING_INVALID;
if(source_entry&BOB64_PAGE_PRESENT) {
u64 *source_pd=table_entries(source,source_entry&BOB64_PAGE_ADDRESS_MASK);
if(!source_pd)return BOB64_PAGING_INVALID;
}
base_page=isolated_base>>21;end_page=end>>21;
first_pd=(usize)(base_page&0x1ff);last_pd=(usize)((end_page-1)&0x1ff);
if(first_pd>last_pd)return BOB64_PAGING_INVALID;
for(usize i=first_pd;i<=last_pd;i++)destination_pd[i]=0;
return 0;
}
static int next_level(BOB64_PAGE_TABLE *table,u64 *parent,usize index,u64 **child) {
u64 entry=parent[index],physical;
if(entry&BOB64_PAGE_PRESENT) {
if(entry&BOB64_PAGE_LARGE)return BOB64_PAGING_INVALID;
physical=entry&BOB64_PAGE_ADDRESS_MASK;
*child=table_entries(table,physical);
return *child?0:BOB64_PAGING_INVALID;
}
physical=table->Allocate(table->Context);
if(!physical||!physical_page_valid(physical,table->PhysicalAddressBits))
return BOB64_PAGING_NO_MEMORY;
*child=table_entries(table,physical);
if(!*child)return BOB64_PAGING_INVALID;
for(usize i=0;i<512;i++)(*child)[i]=0;
/* Parent permissions are permissive; leaf PTEs enforce user/write policy. */
parent[index]=physical|BOB64_PAGE_PRESENT|BOB64_PAGE_WRITE|BOB64_PAGE_USER;
return 0;
}
int bob64_page_map(BOB64_PAGE_TABLE *table,u64 virtual_address,u64 physical_address,
u64 flags) {
u64 *level,*next;
int result;
if(!table||!table->RootPhysical||!table->Allocate||!table->Access||
!canonical_address(virtual_address)||
(virtual_address&(BOB64_PAGE_SIZE-1))||
!physical_page_valid(physical_address,table->PhysicalAddressBits)||
(flags&~BOB64_PAGE_ALLOWED_FLAGS))return BOB64_PAGING_INVALID;
level=table_entries(table,table->RootPhysical);
if(!level)return BOB64_PAGING_INVALID;
result=next_level(table,level,(usize)((virtual_address>>39)&0x1ff),&next);
if(result)return result;
level=next;
result=next_level(table,level,(usize)((virtual_address>>30)&0x1ff),&next);
if(result)return result;
level=next;
result=next_level(table,level,(usize)((virtual_address>>21)&0x1ff),&next);
if(result)return result;
level=next;
usize index=(usize)((virtual_address>>12)&0x1ff);
if(level[index]&BOB64_PAGE_PRESENT)return BOB64_PAGING_ALREADY_MAPPED;
level[index]=physical_address|BOB64_PAGE_PRESENT|flags;
return 0;
}
int bob64_page_map_range(BOB64_PAGE_TABLE *table,u64 virtual_address,
u64 physical_address,u64 byte_size,u64 flags) {
u64 offset,pages,span,last_delta,last_virtual,last_physical;
u64 virtual_page,physical_page;
if(!table||!byte_size)return BOB64_PAGING_INVALID;
offset=virtual_address&(BOB64_PAGE_SIZE-1);
if((physical_address&(BOB64_PAGE_SIZE-1))!=offset||
byte_size>BOB64_U64_MAX-offset)return BOB64_PAGING_INVALID;
span=byte_size+offset;
if(span>BOB64_U64_MAX-(BOB64_PAGE_SIZE-1))return BOB64_PAGING_INVALID;
pages=(span+BOB64_PAGE_SIZE-1)/BOB64_PAGE_SIZE;
last_delta=(pages-1)*BOB64_PAGE_SIZE;
virtual_page=virtual_address&~(BOB64_PAGE_SIZE-1);
physical_page=physical_address&~(BOB64_PAGE_SIZE-1);
if(virtual_page>BOB64_U64_MAX-last_delta||physical_page>BOB64_U64_MAX-last_delta)
return BOB64_PAGING_INVALID;
last_virtual=virtual_page+last_delta;
last_physical=physical_page+last_delta;
if(!canonical_address(virtual_page)||!canonical_address(last_virtual)||
(((virtual_page>>47)&1)!=((last_virtual>>47)&1))||
!physical_page_valid(physical_page,table->PhysicalAddressBits)||
!physical_page_valid(last_physical,table->PhysicalAddressBits))
return BOB64_PAGING_INVALID;
for(u64 i=0;i<pages;i++) {
int result=bob64_page_map(table,virtual_page+i*BOB64_PAGE_SIZE,
physical_page+i*BOB64_PAGE_SIZE,flags);
if(result)return result;
}
return 0;
}
static int locate_leaf(const BOB64_PAGE_TABLE *table,u64 virtual_address,u64 **leaf) {
static const u8 shifts[]={39,30,21};
u64 physical,*level;
if(!table||!table->RootPhysical||!table->Access||!leaf||
!canonical_address(virtual_address)||
(virtual_address&(BOB64_PAGE_SIZE-1)))return BOB64_PAGING_INVALID;
physical=table->RootPhysical;
for(usize depth=0;depth<3;depth++) {
level=table_entries(table,physical);
if(!level)return BOB64_PAGING_INVALID;
u64 entry=level[(virtual_address>>shifts[depth])&0x1ff];
if(!(entry&BOB64_PAGE_PRESENT))return BOB64_PAGING_NOT_MAPPED;
if(entry&BOB64_PAGE_LARGE)return BOB64_PAGING_INVALID;
physical=entry&BOB64_PAGE_ADDRESS_MASK;
}
level=table_entries(table,physical);
if(!level)return BOB64_PAGING_INVALID;
*leaf=&level[(virtual_address>>12)&0x1ff];
if(!(**leaf&BOB64_PAGE_PRESENT))return BOB64_PAGING_NOT_MAPPED;
return 0;
}
/* Caller invalidates the TLB entry when changing a live address space. */
int bob64_page_protect(BOB64_PAGE_TABLE *table,u64 virtual_address,u64 flags) {
u64 *leaf;
int result;
if(flags&~BOB64_PAGE_ALLOWED_FLAGS)return BOB64_PAGING_INVALID;
result=locate_leaf(table,virtual_address,&leaf);
if(result)return result;
*leaf=(*leaf&BOB64_PAGE_ADDRESS_MASK)|BOB64_PAGE_PRESENT|flags;
return 0;
}
/* Caller invalidates the TLB entry when removing a live mapping. */
int bob64_page_unmap(BOB64_PAGE_TABLE *table,u64 virtual_address,
u64 *physical_address,u64 *previous_flags) {
u64 *leaf,entry;
int result=locate_leaf(table,virtual_address,&leaf);
if(result)return result;
entry=*leaf;*leaf=0;
if(physical_address)*physical_address=entry&BOB64_PAGE_ADDRESS_MASK;
if(previous_flags)*previous_flags=entry&~BOB64_PAGE_ADDRESS_MASK;
return 0;
}
int bob64_page_translate(const BOB64_PAGE_TABLE *table,u64 virtual_address,
u64 *physical_address,u64 *flags) {
static const u8 shifts[]={39,30,21,12};
u64 physical,entry,*level;
int effective_user=1,effective_write=1,effective_nx=0;
if(!table||!table->RootPhysical||!physical_address||!canonical_address(virtual_address))
return BOB64_PAGING_INVALID;
physical=table->RootPhysical;
for(usize depth=0;depth<4;depth++) {
level=table_entries(table,physical);
if(!level)return BOB64_PAGING_INVALID;
entry=level[(virtual_address>>shifts[depth])&0x1ff];
if(!(entry&BOB64_PAGE_PRESENT))return 0;
if(depth<3&&(entry&BOB64_PAGE_LARGE))return BOB64_PAGING_INVALID;
if(!(entry&BOB64_PAGE_USER))effective_user=0;
if(!(entry&BOB64_PAGE_WRITE))effective_write=0;
if(entry&BOB64_PAGE_NX)effective_nx=1;
physical=entry&BOB64_PAGE_ADDRESS_MASK;
}
*physical_address=physical|(virtual_address&(BOB64_PAGE_SIZE-1));
if(flags) {
*flags=entry&~BOB64_PAGE_ADDRESS_MASK;
if(!effective_user)*flags&=~BOB64_PAGE_USER;
if(!effective_write)*flags&=~BOB64_PAGE_WRITE;
if(effective_nx)*flags|=BOB64_PAGE_NX;
}
return 1;
}
+51
View File
@@ -0,0 +1,51 @@
#ifndef BOB64_PAGING_H
#define BOB64_PAGING_H
#include "types.h"
#define BOB64_PAGE_SIZE 4096ULL
#define BOB64_PAGE_PRESENT 0x001ULL
#define BOB64_PAGE_WRITE 0x002ULL
#define BOB64_PAGE_USER 0x004ULL
#define BOB64_PAGE_PWT 0x008ULL
#define BOB64_PAGE_PCD 0x010ULL
#define BOB64_PAGE_GLOBAL 0x100ULL
#define BOB64_PAGE_NX (1ULL<<63)
#define BOB64_PAGE_ADDRESS_MASK 0x000ffffffffff000ULL
#define BOB64_PAGE_ALLOWED_FLAGS (BOB64_PAGE_WRITE|BOB64_PAGE_USER|BOB64_PAGE_PWT|\
BOB64_PAGE_PCD|BOB64_PAGE_GLOBAL|BOB64_PAGE_NX)
#define BOB64_PAGING_INVALID (-1)
#define BOB64_PAGING_NO_MEMORY (-2)
#define BOB64_PAGING_ALREADY_MAPPED (-3)
#define BOB64_PAGING_NOT_MAPPED (-4)
/* Allocate returns a physical page; map returns its currently accessible address. */
typedef u64 (*BOB64_TABLE_ALLOCATE)(void *context);
typedef u64 *(*BOB64_TABLE_ACCESS)(void *context,u64 physical_address);
typedef struct {
u64 RootPhysical;
u8 PhysicalAddressBits;
BOB64_TABLE_ALLOCATE Allocate;
BOB64_TABLE_ACCESS Access;
void *Context;
} BOB64_PAGE_TABLE;
int bob64_page_table_init(BOB64_PAGE_TABLE *table,u8 physical_address_bits,
BOB64_TABLE_ALLOCATE allocate,BOB64_TABLE_ACCESS access,
void *context);
/* Clone shared kernel mappings while replacing a 2 MiB-aligned user arena. */
int bob64_page_table_clone_isolated(BOB64_PAGE_TABLE *destination,
const BOB64_PAGE_TABLE *source,
u64 isolated_base,u64 isolated_size);
int bob64_page_map(BOB64_PAGE_TABLE *table,u64 virtual_address,u64 physical_address,
u64 flags);
int bob64_page_map_range(BOB64_PAGE_TABLE *table,u64 virtual_address,
u64 physical_address,u64 byte_size,u64 flags);
int bob64_page_protect(BOB64_PAGE_TABLE *table,u64 virtual_address,u64 flags);
int bob64_page_unmap(BOB64_PAGE_TABLE *table,u64 virtual_address,
u64 *physical_address,u64 *previous_flags);
int bob64_page_translate(const BOB64_PAGE_TABLE *table,u64 virtual_address,
u64 *physical_address,u64 *flags);
#endif
+188
View File
@@ -0,0 +1,188 @@
#include "process.h"
static usize bounded_length(const char *text,usize limit) {
usize length=0;
if(!text)return limit;
while(length<limit&&text[length])length++;
return length;
}
static void copy_bytes(u8 *destination,const u8 *source,usize length) {
for(usize i=0;i<length;i++)destination[i]=source[i];
}
static void clear_bytes(u8 *destination,usize length) {
for(usize i=0;i<length;i++)destination[i]=0;
}
int bob64_process_init(BOB64_PROCESS *process,BOB64_PROCESS_PAGE *page_storage,
usize page_capacity,const BOB64_PROCESS_OPERATIONS *operations) {
if(!process||!page_storage||!operations||!operations->AllocatePage||
!operations->FreePage||!operations->MapPage||!operations->ProtectPage||
!operations->UnmapPage||
page_capacity>BOB64_PROCESS_PAGE_LIMIT)return -1;
process->Pages=page_storage;process->PageCapacity=page_capacity;process->PageCount=0;
process->Operations=*operations;process->EntryAddress=0;process->StartupAddress=0;
process->InitialStackPointer=0;process->Loaded=0;
return 0;
}
static int map_page(BOB64_PROCESS *process,u64 virtual_address,u64 flags) {
u64 physical;
u8 *writable=0;
BOB64_PROCESS_PAGE *page;
if(process->PageCount>=process->PageCapacity)return -1;
physical=process->Operations.AllocatePage(process->Operations.Context);
if(!physical)return -1;
page=process->Pages+process->PageCount++;
page->VirtualAddress=virtual_address;page->PhysicalAddress=physical;page->Flags=flags;
page->WritableAddress=0;page->Allocated=1;page->Mapped=0;
if(process->Operations.MapPage(process->Operations.Context,virtual_address,
physical,flags,&writable))return -1;
page->WritableAddress=writable;page->Mapped=1;
if(!writable)return -1;
clear_bytes(writable,(usize)BOB64_PAGE_SIZE);
return 0;
}
static BOB64_PROCESS_PAGE *find_page(BOB64_PROCESS *process,u64 virtual_address) {
u64 page_address=virtual_address&~(BOB64_PAGE_SIZE-1);
for(usize i=0;i<process->PageCount;i++)
if(process->Pages[i].Mapped&&process->Pages[i].VirtualAddress==page_address)
return process->Pages+i;
return 0;
}
static int write_virtual(BOB64_PROCESS *process,u64 address,const void *source,
usize length) {
const u8 *bytes=(const u8 *)source;
while(length) {
BOB64_PROCESS_PAGE *page=find_page(process,address);
usize offset=(usize)(address&(BOB64_PAGE_SIZE-1));
usize part=(usize)BOB64_PAGE_SIZE-offset;
if(!page)return -1;
if(part>length)part=length;
copy_bytes(page->WritableAddress+offset,bytes,part);
bytes+=part;length-=part;address+=part;
}
return 0;
}
static int prepare_arguments(BOB64_PROCESS *process,usize argument_count,
const char *const *arguments) {
u64 string_addresses[BOB64_PROCESS_MAX_ARGUMENTS];
u64 cursor=BOB64_PROCESS_STACK_BASE+BOB64_PROCESS_STACK_SIZE;
u64 argv_address,startup_address,initial_rsp;
BOB64_APP_STARTUP startup;
u64 zero=0;
if(argument_count>BOB64_PROCESS_MAX_ARGUMENTS||
(argument_count&&!arguments))return -1;
for(usize i=argument_count;i>0;i--) {
usize length=bounded_length(arguments[i-1],(usize)BOB64_PROCESS_STACK_SIZE);
if(length==(usize)BOB64_PROCESS_STACK_SIZE||
(u64)length+1>cursor-BOB64_PROCESS_STACK_BASE)return -1;
cursor-=(u64)length+1;string_addresses[i-1]=cursor;
if(write_virtual(process,cursor,arguments[i-1],length)||
write_virtual(process,cursor+length,"",1))return -1;
}
cursor&=~7ULL;
if((u64)(argument_count+1)*sizeof(u64)>cursor-BOB64_PROCESS_STACK_BASE)return -1;
cursor-=(u64)(argument_count+1)*sizeof(u64);argv_address=cursor;
for(usize i=0;i<argument_count;i++)
if(write_virtual(process,argv_address+i*sizeof(u64),&string_addresses[i],sizeof(u64)))return -1;
if(write_virtual(process,argv_address+argument_count*sizeof(u64),&zero,sizeof(zero)))return -1;
cursor&=~7ULL;
if(sizeof(startup)>cursor-BOB64_PROCESS_STACK_BASE)return -1;
cursor-=sizeof(startup);startup_address=cursor;
startup.StructSize=(u32)sizeof(startup);startup.AbiVersion=BOB64_APP_ABI_VERSION;
startup.ArgumentCount=(u64)argument_count;
startup.Arguments=(const char *const *)(uintptr_t)argv_address;
startup.Flags=0;
if(write_virtual(process,startup_address,&startup,sizeof(startup)))return -1;
cursor&=~15ULL;
if(cursor<BOB64_PROCESS_STACK_BASE+40)return -1;
initial_rsp=cursor-40;
if(write_virtual(process,initial_rsp,&zero,sizeof(zero)))return -1;
process->StartupAddress=startup_address;process->InitialStackPointer=initial_rsp;
return 0;
}
int bob64_process_load(BOB64_PROCESS *process,const void *file,usize file_size,
usize argument_count,const char *const *arguments) {
BOB64_EXEC_IMAGE parsed;
const BOB64_EXEC_IMAGE *image=&parsed;
usize image_pages;
if(!process||process->Loaded||process->PageCount||
!process->Pages||!process->Operations.NxSupported||
bob64_exec_parse(file,file_size,&parsed)||
!image->Image||image->AbiVersion!=BOB64_APP_ABI_VERSION||image->Flags||
!image->CodeSize||(image->CodeSize&(BOB64_PAGE_SIZE-1))||
image->CodeSize>image->FileSize||image->FileSize>image->MemorySize||
!image->MemorySize||image->MemorySize>BOB64_PROCESS_IMAGE_LIMIT||
image->EntryOffset>=image->CodeSize||
image->MemorySize>~(u64)0-BOB64_PROCESS_IMAGE_BASE||
argument_count>BOB64_PROCESS_MAX_ARGUMENTS||
process->PageCapacity<BOB64_PROCESS_STACK_SIZE/BOB64_PAGE_SIZE+
(image->MemorySize+BOB64_PAGE_SIZE-1)/BOB64_PAGE_SIZE)
return -1;
image_pages=(usize)((image->MemorySize+BOB64_PAGE_SIZE-1)/BOB64_PAGE_SIZE);
for(usize page=0;page<image_pages;page++) {
u64 address=BOB64_PROCESS_IMAGE_BASE+(u64)page*BOB64_PAGE_SIZE;
u64 flags=BOB64_PAGE_USER|BOB64_PAGE_WRITE|BOB64_PAGE_NX;
if(map_page(process,address,flags))goto fail;
}
for(u64 offset=0;offset<image->FileSize;) {
usize page=(usize)(offset/BOB64_PAGE_SIZE);
usize in_page=(usize)(offset&(BOB64_PAGE_SIZE-1));
usize part=(usize)BOB64_PAGE_SIZE-in_page;
if((u64)part>image->FileSize-offset)part=(usize)(image->FileSize-offset);
copy_bytes(process->Pages[page].WritableAddress+in_page,image->Image+(usize)offset,part);
offset+=part;
}
for(usize page=0;page<(usize)(image->CodeSize/BOB64_PAGE_SIZE);page++) {
BOB64_PROCESS_PAGE *record=process->Pages+page;
if(process->Operations.ProtectPage(process->Operations.Context,
record->VirtualAddress,BOB64_PAGE_USER))goto fail;
record->Flags=BOB64_PAGE_USER;
}
for(usize page=0;page<BOB64_PROCESS_STACK_SIZE/BOB64_PAGE_SIZE;page++)
if(map_page(process,BOB64_PROCESS_STACK_BASE+(u64)page*BOB64_PAGE_SIZE,
BOB64_PAGE_USER|BOB64_PAGE_WRITE|BOB64_PAGE_NX))goto fail;
if(prepare_arguments(process,argument_count,arguments))goto fail;
process->EntryAddress=BOB64_PROCESS_IMAGE_BASE+image->EntryOffset;
process->Loaded=1;
return 0;
fail:
bob64_process_unload(process);
return -1;
}
int bob64_process_unload(BOB64_PROCESS *process) {
int result=0;
if(!process||!process->Pages)return -1;
for(usize i=process->PageCount;i>0;i--) {
BOB64_PROCESS_PAGE *page=process->Pages+(i-1);
if(page->Mapped) {
if(process->Operations.UnmapPage(process->Operations.Context,page->VirtualAddress)) {
result=-1;continue;
}
page->Mapped=0;page->WritableAddress=0;
}
if(page->Allocated) {
if(process->Operations.FreePage(process->Operations.Context,page->PhysicalAddress)) {
result=-1;continue;
}
page->Allocated=0;
}
}
usize remaining=0;
for(usize i=0;i<process->PageCount;i++)
if(process->Pages[i].Mapped||process->Pages[i].Allocated)
process->Pages[remaining++]=process->Pages[i];
process->PageCount=remaining;
if(!remaining) {
process->Loaded=0;process->EntryAddress=0;process->StartupAddress=0;
process->InitialStackPointer=0;
}
return result;
}
+63
View File
@@ -0,0 +1,63 @@
#ifndef BOB64_PROCESS_H
#define BOB64_PROCESS_H
#include "abi.h"
#include "exec.h"
#include "paging.h"
#define BOB64_PROCESS_IMAGE_BASE 0x0000004000000000ULL
#define BOB64_PROCESS_IMAGE_LIMIT (16ULL*1024ULL*1024ULL)
#define BOB64_PROCESS_STACK_GUARD (BOB64_PROCESS_IMAGE_BASE+0x02000000ULL)
#define BOB64_PROCESS_STACK_BASE (BOB64_PROCESS_STACK_GUARD+BOB64_PAGE_SIZE)
#define BOB64_PROCESS_STACK_SIZE (64ULL*1024ULL)
#define BOB64_PROCESS_ISOLATED_SIZE (34ULL*1024ULL*1024ULL)
#define BOB64_PROCESS_PAGE_LIMIT ((BOB64_PROCESS_IMAGE_LIMIT/BOB64_PAGE_SIZE)+\
(BOB64_PROCESS_STACK_SIZE/BOB64_PAGE_SIZE))
#define BOB64_PROCESS_MAX_ARGUMENTS 128
typedef u64 (*BOB64_PROCESS_ALLOCATE_PAGE)(void *context);
typedef int (*BOB64_PROCESS_FREE_PAGE)(void *context,u64 physical_address);
/* Map failure must leave the VA unmapped; writable_address is a kernel alias. */
typedef int (*BOB64_PROCESS_MAP_PAGE)(void *context,u64 virtual_address,
u64 physical_address,u64 flags,
u8 **writable_address);
/* Protect/unmap callbacks invalidate the active address-space TLB entry. */
typedef int (*BOB64_PROCESS_PROTECT_PAGE)(void *context,u64 virtual_address,u64 flags);
typedef int (*BOB64_PROCESS_UNMAP_PAGE)(void *context,u64 virtual_address);
typedef struct {
BOB64_PROCESS_ALLOCATE_PAGE AllocatePage;
BOB64_PROCESS_FREE_PAGE FreePage;
BOB64_PROCESS_MAP_PAGE MapPage;
BOB64_PROCESS_PROTECT_PAGE ProtectPage;
BOB64_PROCESS_UNMAP_PAGE UnmapPage;
void *Context;
u8 NxSupported;
} BOB64_PROCESS_OPERATIONS;
typedef struct {
u64 VirtualAddress;
u64 PhysicalAddress;
u64 Flags;
u8 *WritableAddress;
u8 Allocated;
u8 Mapped;
u8 Reserved[6];
} BOB64_PROCESS_PAGE;
typedef struct {
BOB64_PROCESS_PAGE *Pages;
usize PageCapacity,PageCount;
BOB64_PROCESS_OPERATIONS Operations;
u64 EntryAddress,StartupAddress,InitialStackPointer;
u8 Loaded;
} BOB64_PROCESS;
int bob64_process_init(BOB64_PROCESS *process,BOB64_PROCESS_PAGE *page_storage,
usize page_capacity,const BOB64_PROCESS_OPERATIONS *operations);
/* Parse an untrusted B64E file before allocating any application pages. */
int bob64_process_load(BOB64_PROCESS *process,const void *file,usize file_size,
usize argument_count,const char *const *arguments);
int bob64_process_unload(BOB64_PROCESS *process);
#endif
+14
View File
@@ -0,0 +1,14 @@
#ifndef BOB64_RUNTIME_H
#define BOB64_RUNTIME_H
#include "memory.h"
#include "bootstrap.h"
#include "descriptors.h"
/* Boot-owned state remains in the mapped EFI image and is adopted after EBS. */
extern BOB64_PAGE_EXTENT bob64_boot_page_extents[BOB64_PAGE_EXTENT_LIMIT];
extern BOB64_PAGE_ALLOCATOR bob64_boot_page_allocator;
extern BOB64_BOOTSTRAP_SPACE bob64_bootstrap_space;
extern BOB64_TSS bob64_kernel_tss;
#endif
+286
View File
@@ -0,0 +1,286 @@
#include "shell.h"
static void output(BOB64_SHELL *shell,const char *text) {
shell->Write(shell->Context,text);
}
static char lower_ascii(char value) {
if(value>='A'&&value<='Z')return (char)(value-'A'+'a');
return value;
}
static int equals(const char *left,const char *right) {
while(*left&&*right&&lower_ascii(*left)==*right){left++;right++;}
return !*left&&!*right;
}
static void print_hex64(BOB64_SHELL *shell,u64 value) {
static const char digits[]="0123456789abcdef";
char text[17];
for(u32 i=0;i<16;i++)text[i]=digits[(value>>(60-i*4))&15];
text[16]=0;output(shell,text);
}
static void print_decimal(BOB64_SHELL *shell,usize value) {
char text[21];usize length=0;
do {text[length++]=(char)('0'+value%10);value/=10;} while(value&&length<sizeof(text));
while(length) {char digit[2]={text[--length],0};output(shell,digit);}
}
static void print_memory(BOB64_SHELL *shell) {
u64 free_pages=0,allocated_pages=0;
BOB64_PAGE_ALLOCATOR *allocator=shell->PageAllocator;
if(allocator) {
for(usize i=0;i<allocator->Count;i++)free_pages+=allocator->Extents[i].Pages;
for(usize i=0;i<allocator->AllocatedCount;i++)
allocated_pages+=allocator->Allocated[i].Pages;
}
output(shell,"free pages=0x");print_hex64(shell,free_pages);output(shell,"\r\n");
output(shell,"allocated pages=0x");print_hex64(shell,allocated_pages);output(shell,"\r\n");
output(shell,"heap mapped=0x");
print_hex64(shell,(u64)bob64_heap_mapped_bytes(shell->Heap));output(shell," bytes\r\n");
}
static void print_file_data(BOB64_SHELL *shell,const char *data,usize length) {
static const char digits[]="0123456789abcdef";
char character[2]={0,0},escaped[5]={'\\','x','0','0',0};
for(usize i=0;i<length;i++) {
u8 value=(u8)data[i];
if((value>=32&&value<=126)||value=='\r'||value=='\n'||value=='\t') {
character[0]=(char)value;output(shell,character);
} else {
escaped[2]=digits[value>>4];escaped[3]=digits[value&15];
output(shell,escaped);
}
}
}
static void run_file_command(BOB64_SHELL *shell,char *arguments) {
char *argv[BOB64_SHELL_ARGUMENT_LIMIT];
usize argc=0;
char *cursor=arguments;
int started=0;
if(!shell->Run) {output(shell,"app execution unavailable\r\n");return;}
while(*cursor==' ')cursor++;
if(!*cursor) {output(shell,"usage: run NAME [ARG ...]\r\n");return;}
while(*cursor) {
if(argc==BOB64_SHELL_ARGUMENT_LIMIT) {
output(shell,"too many arguments\r\n");return;
}
argv[argc++]=cursor;
while(*cursor&&*cursor!=' ')cursor++;
if(*cursor)*cursor++=0;
while(*cursor==' ')cursor++;
}
s64 status=shell->Run(shell->Context,argv[0],argc,
(const char *const *)argv,&started);
if(!started) {output(shell,"unable to start application\r\n");return;}
output(shell,"application exit status=0x");
print_hex64(shell,(u64)status);output(shell,"\r\n");
}
static void compile_file_command(BOB64_SHELL *shell,char *arguments) {
char source[BOB64_FS_NAME_CAPACITY],destination[BOB64_FS_NAME_CAPACITY];
usize source_length=0,destination_length=0,error_offset=0;
char *cursor=arguments;
int result;
while(*cursor==' ')cursor++;
while(cursor[source_length]&&cursor[source_length]!=' '&&
source_length<sizeof(source)-1)source_length++;
if(!source_length||(cursor[source_length]&&cursor[source_length]!=' ')) {
output(shell,"usage: cc SOURCE [OUTPUT]\r\n");return;
}
for(usize i=0;i<source_length;i++)source[i]=cursor[i];
source[source_length]=0;cursor+=source_length;
while(*cursor==' ')cursor++;
if(!*cursor) {
static const char default_output[]="app.b64e";
destination_length=sizeof(default_output)-1;
for(usize i=0;i<destination_length;i++)destination[i]=default_output[i];
} else {
while(cursor[destination_length]&&cursor[destination_length]!=' '&&
destination_length<sizeof(destination)-1)destination_length++;
if(!destination_length||(cursor[destination_length]&&cursor[destination_length]!=' ')) {
output(shell,"usage: cc SOURCE [OUTPUT]\r\n");return;
}
for(usize i=0;i<destination_length;i++)destination[i]=cursor[i];
cursor+=destination_length;while(*cursor==' ')cursor++;
if(*cursor) {output(shell,"usage: cc SOURCE [OUTPUT]\r\n");return;}
}
destination[destination_length]=0;
if(equals(source,destination)) {output(shell,"source and output must differ\r\n");return;}
if(!shell->Compile) {output(shell,"C compiler unavailable\r\n");return;}
result=shell->Compile(shell->Context,source,destination,&error_offset);
if(result==-2) {
output(shell,"C compile error near character ");print_decimal(shell,error_offset);
output(shell,". Supports int main(void), helper calls, void/char returns, pointers, and bob64_app_write.\r\n");
} else if(result)output(shell,"C compile failed; check source and free filesystem space\r\n");
else {output(shell,"compiled to ");output(shell,destination);output(shell,"\r\n");}
}
static int list_file(void *context,const char *name,usize length) {
BOB64_SHELL *shell=(BOB64_SHELL *)context;
output(shell,name);output(shell," 0x");print_hex64(shell,(u64)length);
output(shell," bytes\r\n");
return 0;
}
static usize text_length(const char *text) {
usize length=0;
while(text[length])length++;
return length;
}
static void execute_file_command(BOB64_SHELL *shell,u8 operation,char *arguments) {
BOB64_FILESYSTEM *filesystem=shell->Filesystem;
char *name=arguments,*separator=arguments,*contents_argument;
const char *contents;
usize length;
if(!filesystem) { output(shell,"filesystem unavailable\r\n");return; }
if(operation==0) {
if(!bob64_fs_list(filesystem,list_file,shell))output(shell,"no files\r\n");
return;
}
while(*name==' ')name++;
separator=name;
while(*separator&&*separator!=' ')separator++;
contents_argument=separator;
if(*separator) {
*separator++=0;
while(*separator==' ')separator++;
}
if(!*name||((operation==1||operation==3)&&*contents_argument)) {
output(shell,"usage: cat NAME | write NAME TEXT | rm NAME\r\n");return;
}
if(operation==1) {
if(bob64_fs_read(filesystem,name,&contents,&length)) {
output(shell,"file not found\r\n");return;
}
print_file_data(shell,contents,length);output(shell,"\r\n");return;
}
if(operation==2) {
if(bob64_fs_write(filesystem,name,separator,text_length(separator)))
output(shell,"write failed (name/data invalid or heap full)\r\n");
else output(shell,"saved\r\n");
return;
}
if(bob64_fs_delete(filesystem,name))output(shell,"file not found\r\n");
else output(shell,"deleted\r\n");
}
static void execute(BOB64_SHELL *shell) {
char *line=shell->Line;
if(!shell->Length)return;
line[shell->Length]=0;
if(equals(line,"help")) {
output(shell,"help show commands\r\nclear clear screen\r\nmem physical memory and heap\r\n");
output(shell,"heap heap usage\r\nls list files\r\ncat NAME read a file\r\n");
output(shell,"write NAME TEXT save text\r\nrm NAME delete a file\r\n");
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,"echo print text\r\nversion show kernel version\r\n");
} else if(equals(line,"clear")) {
if(shell->Clear)shell->Clear(shell->Context);
output(shell,"bob64! kernel shell\r\n");
} else if(equals(line,"mem"))print_memory(shell);
else if(equals(line,"heap")) {
output(shell,"heap mapped=0x");
print_hex64(shell,(u64)bob64_heap_mapped_bytes(shell->Heap));
output(shell," bytes\r\n");
} else if(equals(line,"version"))output(shell,"bob64 kernel 0.1\r\n");
else if(equals(line,"save")) {
usize size,written;
if(bob64_fs_snapshot_size(shell->Filesystem,&size)) {
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)bob64_heap_free(shell->Heap,snapshot);
output(shell,"snapshot save failed (heap full)\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");
} else if(equals(line,"restore")) {
if(!shell->Snapshot||bob64_fs_snapshot_restore(shell->Filesystem,
shell->Snapshot,shell->SnapshotSize)) {
output(shell,"restore failed; files unchanged\r\n");return;
}
output(shell,"restored B64S v1 checkpoint\r\n");
}
else if(equals(line,"ls"))execute_file_command(shell,0,line+2);
else if(shell->Length>4&&lower_ascii(line[0])=='c'&&
lower_ascii(line[1])=='a'&&lower_ascii(line[2])=='t'&&line[3]==' ')
execute_file_command(shell,1,line+4);
else if(shell->Length>6&&lower_ascii(line[0])=='w'&&
lower_ascii(line[1])=='r'&&lower_ascii(line[2])=='i'&&
lower_ascii(line[3])=='t'&&lower_ascii(line[4])=='e'&&line[5]==' ')
execute_file_command(shell,2,line+6);
else if(shell->Length>3&&lower_ascii(line[0])=='r'&&
lower_ascii(line[1])=='m'&&line[2]==' ')
execute_file_command(shell,3,line+3);
else if(shell->Length>4&&lower_ascii(line[0])=='r'&&
lower_ascii(line[1])=='u'&&lower_ascii(line[2])=='n'&&line[3]==' ')
run_file_command(shell,line+4);
else if(shell->Length>3&&lower_ascii(line[0])=='c'&&
lower_ascii(line[1])=='c'&&line[2]==' ')
compile_file_command(shell,line+3);
else if(shell->Length>=5&&lower_ascii(line[0])=='e'&&
lower_ascii(line[1])=='c'&&lower_ascii(line[2])=='h'&&
lower_ascii(line[3])=='o'&&line[4]==' ') {
output(shell,line+5);output(shell,"\r\n");
} else {
output(shell,"unknown command: ");output(shell,line);output(shell,"\r\n");
}
}
static void prompt(BOB64_SHELL *shell) {
output(shell,"bob64> ");
}
int bob64_shell_init(BOB64_SHELL *shell,BOB64_PAGE_ALLOCATOR *allocator,
BOB64_HEAP *heap,BOB64_FILESYSTEM *filesystem,
BOB64_SHELL_WRITE write,
BOB64_SHELL_CLEAR clear,void *context) {
if(!shell||!write)return -1;
shell->Length=0;shell->IgnoreLineFeed=0;shell->Line[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;
shell->Run=0;
shell->Compile=0;
output(shell,"bob64! kernel shell; type help\r\n");prompt(shell);
return 0;
}
void bob64_shell_set_runner(BOB64_SHELL *shell,BOB64_SHELL_RUN run) {
if(shell)shell->Run=run;
}
void bob64_shell_set_compiler(BOB64_SHELL *shell,BOB64_SHELL_COMPILE compile) {
if(shell)shell->Compile=compile;
}
void bob64_shell_input(BOB64_SHELL *shell,int character) {
char echo[2];
if(!shell||!shell->Write||character<0)return;
if(character=='\n'&&shell->IgnoreLineFeed) { shell->IgnoreLineFeed=0;return; }
shell->IgnoreLineFeed=(u8)(character=='\r');
if(character=='\r'||character=='\n') {
output(shell,"\r\n");execute(shell);shell->Length=0;shell->Line[0]=0;
prompt(shell);return;
}
if(character=='\b'||character==0x7f) {
if(shell->Length) {
shell->Length--;shell->Line[shell->Length]=0;
output(shell,"\b \b");
}
return;
}
if(character<32||character>126||shell->Length>=BOB64_SHELL_LINE_CAPACITY-1)return;
shell->Line[shell->Length++]=(char)character;
shell->Line[shell->Length]=0;
echo[0]=(char)character;echo[1]=0;output(shell,echo);
}
+40
View File
@@ -0,0 +1,40 @@
#ifndef BOB64_SHELL_H
#define BOB64_SHELL_H
#include "filesystem.h"
#include "snapshot.h"
#define BOB64_SHELL_LINE_CAPACITY 128
#define BOB64_SHELL_ARGUMENT_LIMIT 16
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 struct {
char Line[BOB64_SHELL_LINE_CAPACITY];
usize Length;
u8 IgnoreLineFeed;
BOB64_PAGE_ALLOCATOR *PageAllocator;
BOB64_HEAP *Heap;
BOB64_FILESYSTEM *Filesystem;
void *Snapshot;
usize SnapshotSize;
BOB64_SHELL_WRITE Write;
BOB64_SHELL_CLEAR Clear;
BOB64_SHELL_RUN Run;
BOB64_SHELL_COMPILE Compile;
void *Context;
} BOB64_SHELL;
int bob64_shell_init(BOB64_SHELL *shell,BOB64_PAGE_ALLOCATOR *allocator,
BOB64_HEAP *heap,BOB64_FILESYSTEM *filesystem,
BOB64_SHELL_WRITE write,
BOB64_SHELL_CLEAR clear,void *context);
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);
#endif
+147
View File
@@ -0,0 +1,147 @@
#include "snapshot.h"
#define BOB64_SNAPSHOT_RECORD_HEADER_SIZE 12u
#define BOB64_SNAPSHOT_CHECKSUM_OFFSET 20u
static u16 read16(const u8 *bytes) {
return (u16)((u16)bytes[0]|((u16)bytes[1]<<8));
}
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 void write16(u8 *bytes,u16 value) {
bytes[0]=(u8)value;bytes[1]=(u8)(value>>8);
}
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 usize name_length(const char *name) {
usize length=0;
while(name[length])length++;
return length;
}
static u32 snapshot_checksum(const u8 *bytes,usize length) {
u32 value=0xffffffffu;
for(usize i=0;i<length;i++) {
u8 byte=(i>=BOB64_SNAPSHOT_CHECKSUM_OFFSET&&
i<BOB64_SNAPSHOT_CHECKSUM_OFFSET+4)?0:bytes[i];
value^=byte;
for(u32 bit=0;bit<8;bit++)value=(value>>1)^(0xedb88320u&-(value&1u));
}
return ~value;
}
int bob64_fs_snapshot_size(const BOB64_FILESYSTEM *filesystem,usize *size) {
usize total=BOB64_SNAPSHOT_HEADER_SIZE,count=0;
if(!filesystem||!size)return -1;
for(BOB64_FS_FILE *file=filesystem->First;file;file=file->Next) {
usize name_size=name_length(file->Name);
if(!name_size||name_size>=BOB64_FS_NAME_CAPACITY||
total>~(usize)0-BOB64_SNAPSHOT_RECORD_HEADER_SIZE-name_size||
file->Length>~(usize)0-total-BOB64_SNAPSHOT_RECORD_HEADER_SIZE-name_size)
return -1;
total+=BOB64_SNAPSHOT_RECORD_HEADER_SIZE+name_size+file->Length;
if(count==0xffffffffu)return -1;
count++;
}
if(count!=filesystem->FileCount)return -1;
*size=total;
return 0;
}
int bob64_fs_snapshot_write(const BOB64_FILESYSTEM *filesystem,
void *output,usize capacity,usize *written) {
usize required,offset=BOB64_SNAPSHOT_HEADER_SIZE;
u8 *bytes=(u8 *)output;
if(!output||!written||bob64_fs_snapshot_size(filesystem,&required)||capacity<required)
return -1;
bytes[0]='B';bytes[1]='6';bytes[2]='4';bytes[3]='S';
write16(bytes+4,BOB64_SNAPSHOT_VERSION);write16(bytes+6,BOB64_SNAPSHOT_HEADER_SIZE);
write64(bytes+8,(u64)required);write32(bytes+16,(u32)filesystem->FileCount);
write32(bytes+BOB64_SNAPSHOT_CHECKSUM_OFFSET,0);
for(BOB64_FS_FILE *file=filesystem->First;file;file=file->Next) {
usize name_size=name_length(file->Name);
write16(bytes+offset,(u16)name_size);write16(bytes+offset+2,0);
write64(bytes+offset+4,(u64)file->Length);offset+=BOB64_SNAPSHOT_RECORD_HEADER_SIZE;
for(usize i=0;i<name_size;i++)bytes[offset+i]=(u8)file->Name[i];
offset+=name_size;
for(usize i=0;i<file->Length;i++)bytes[offset+i]=(u8)file->Data[i];
offset+=file->Length;
}
if(offset!=required)return -1;
write32(bytes+BOB64_SNAPSHOT_CHECKSUM_OFFSET,snapshot_checksum(bytes,required));
*written=required;
return 0;
}
static int clear_filesystem(BOB64_FILESYSTEM *filesystem) {
while(filesystem->First) {
char name[BOB64_FS_NAME_CAPACITY];
usize length=name_length(filesystem->First->Name);
if(!length||length>=sizeof(name))return -1;
for(usize i=0;i<length;i++)name[i]=filesystem->First->Name[i];
name[length]=0;
if(bob64_fs_delete(filesystem,name))return -1;
}
return 0;
}
int bob64_fs_snapshot_restore(BOB64_FILESYSTEM *filesystem,
const void *snapshot,usize snapshot_size) {
const u8 *bytes=(const u8 *)snapshot;
BOB64_FILESYSTEM replacement,old;
usize offset=BOB64_SNAPSHOT_HEADER_SIZE;
u32 file_count;
if(!filesystem||!filesystem->Heap||!bytes||snapshot_size<BOB64_SNAPSHOT_HEADER_SIZE||
bytes[0]!='B'||bytes[1]!='6'||bytes[2]!='4'||bytes[3]!='S'||
read16(bytes+4)!=BOB64_SNAPSHOT_VERSION||
read16(bytes+6)!=BOB64_SNAPSHOT_HEADER_SIZE||
read64(bytes+8)!=(u64)snapshot_size||
read32(bytes+BOB64_SNAPSHOT_CHECKSUM_OFFSET)!=snapshot_checksum(bytes,snapshot_size))
return -1;
file_count=read32(bytes+16);
if((u64)file_count>((u64)snapshot_size-BOB64_SNAPSHOT_HEADER_SIZE)/
BOB64_SNAPSHOT_RECORD_HEADER_SIZE||bob64_fs_init(&replacement,filesystem->Heap))
return -1;
for(u32 i=0;i<file_count;i++) {
u16 name_size;
u64 data_size;
char name[BOB64_FS_NAME_CAPACITY];
if(offset>snapshot_size||snapshot_size-offset<BOB64_SNAPSHOT_RECORD_HEADER_SIZE)
goto invalid;
name_size=read16(bytes+offset);
if(read16(bytes+offset+2)!=0||!name_size||name_size>=sizeof(name))goto invalid;
data_size=read64(bytes+offset+4);offset+=BOB64_SNAPSHOT_RECORD_HEADER_SIZE;
if((u64)name_size>(u64)snapshot_size-offset)goto invalid;
for(usize n=0;n<name_size;n++) {
if(!bytes[offset+n])goto invalid;
name[n]=(char)bytes[offset+n];
}
name[name_size]=0;offset+=name_size;
if(data_size>(u64)snapshot_size-offset)goto invalid;
usize previous_count=replacement.FileCount;
if(bob64_fs_write(&replacement,name,bytes+offset,(usize)data_size)||
replacement.FileCount!=previous_count+1)goto invalid;
offset+=(usize)data_size;
}
if(offset!=snapshot_size)goto invalid;
old=*filesystem;*filesystem=replacement;
if(clear_filesystem(&old))return -1;
return 0;
invalid:
clear_filesystem(&replacement);
return -1;
}
+15
View File
@@ -0,0 +1,15 @@
#ifndef BOB64_SNAPSHOT_H
#define BOB64_SNAPSHOT_H
#include "filesystem.h"
#define BOB64_SNAPSHOT_VERSION 1
#define BOB64_SNAPSHOT_HEADER_SIZE 24
int bob64_fs_snapshot_size(const BOB64_FILESYSTEM *filesystem,usize *size);
int bob64_fs_snapshot_write(const BOB64_FILESYSTEM *filesystem,
void *output,usize capacity,usize *written);
int bob64_fs_snapshot_restore(BOB64_FILESYSTEM *filesystem,
const void *snapshot,usize snapshot_size);
#endif
+545
View File
@@ -0,0 +1,545 @@
#include "syscall.h"
#include "process.h"
#include "console.h"
volatile u64 bob64_user_active;
volatile u64 bob64_user_depth;
BOB64_USER_RETURN_FRAME bob64_user_return_frames[BOB64_USER_ENTRY_MAX_DEPTH];
volatile s64 bob64_user_return_value;
#define BOB64_SYSCALL_OPEN_HANDLES 16
#define BOB64_SYSCALL_CONTEXT_DEPTH BOB64_SYSCALL_CONTEXT_MAX_DEPTH
typedef struct {
u64 Id,Position;
u32 Flags;
char Name[BOB64_SYSCALL_MAX_FILENAME+1];
} BOB64_SYSCALL_HANDLE;
typedef struct {
BOB64_SYSCALL_WRITE WriteCharacter;
void *WriteContext;
BOB64_SYSCALL_READ_USER ReadUser;
void *ReadUserContext;
BOB64_SYSCALL_WRITE_USER WriteUser;
void *WriteUserContext;
BOB64_SYSCALL_FILE_READ FileRead;
BOB64_SYSCALL_FILE_WRITE FileWrite;
void *FilesystemContext;
BOB64_SYSCALL_FILE_LIST FileList;
BOB64_SYSCALL_FILE_DELETE FileDelete;
void *FileManagerContext;
BOB64_SYSCALL_FILE_OPEN FileOpen;
BOB64_SYSCALL_FILE_READ_AT FileReadAt;
BOB64_SYSCALL_FILE_WRITE_AT FileWriteAt;
void *FileStreamContext;
BOB64_SYSCALL_EVENT_WAIT WaitEvent;
void *WaitEventContext;
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];
BOB64_FILE_INFO FileEntries[BOB64_SYSCALL_MAX_FILES];
BOB64_SYSCALL_HANDLE Handles[BOB64_SYSCALL_OPEN_HANDLES];
u64 NextHandle;
} BOB64_SYSCALL_CONTEXT;
/* Keep per-app dispatch state, scratch buffers, and streaming handles together. */
static BOB64_SYSCALL_CONTEXT syscall_context={.NextHandle=1};
static BOB64_SYSCALL_CONTEXT syscall_context_stack[BOB64_SYSCALL_CONTEXT_DEPTH];
static u32 syscall_context_depth;
#define syscall_write_character syscall_context.WriteCharacter
#define syscall_write_context syscall_context.WriteContext
#define syscall_read_user syscall_context.ReadUser
#define syscall_read_user_context syscall_context.ReadUserContext
#define syscall_write_user syscall_context.WriteUser
#define syscall_write_user_context syscall_context.WriteUserContext
#define syscall_file_read syscall_context.FileRead
#define syscall_file_write syscall_context.FileWrite
#define syscall_filesystem_context syscall_context.FilesystemContext
#define syscall_file_list syscall_context.FileList
#define syscall_file_delete syscall_context.FileDelete
#define syscall_file_manager_context syscall_context.FileManagerContext
#define syscall_file_open syscall_context.FileOpen
#define syscall_file_read_at syscall_context.FileReadAt
#define syscall_file_write_at syscall_context.FileWriteAt
#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_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_file_entries syscall_context.FileEntries
#define syscall_handles syscall_context.Handles
#define syscall_next_handle syscall_context.NextHandle
static void copy_context(BOB64_SYSCALL_CONTEXT *destination,
const BOB64_SYSCALL_CONTEXT *source) {
u8 *out=(u8 *)destination;
const u8 *in=(const u8 *)source;
for(usize i=0;i<sizeof(*destination);i++)out[i]=in[i];
}
int bob64_syscall_context_push(void) {
if(syscall_context_depth>=BOB64_SYSCALL_CONTEXT_DEPTH)return -1;
copy_context(&syscall_context_stack[syscall_context_depth],&syscall_context);
syscall_context_depth++;
return 0;
}
int bob64_syscall_context_pop(void) {
if(!syscall_context_depth)return -1;
syscall_context_depth--;
copy_context(&syscall_context,
&syscall_context_stack[syscall_context_depth]);
return 0;
}
void bob64_user_request_return(s64 value) {
if(bob64_user_depth&&bob64_user_depth<=BOB64_USER_ENTRY_MAX_DEPTH)
bob64_user_return_frames[bob64_user_depth-1].ReturnValue=value;
bob64_user_return_value=value;
bob64_user_active=0;
}
static BOB64_SYSCALL_HANDLE *find_handle(u64 id) {
if(!id)return 0;
for(usize i=0;i<BOB64_SYSCALL_OPEN_HANDLES;i++)
if(syscall_handles[i].Id==id)return &syscall_handles[i];
return 0;
}
void bob64_syscall_set_write(BOB64_SYSCALL_WRITE write_character,void *context) {
syscall_write_character=write_character;
syscall_write_context=context;
}
void bob64_syscall_set_read_user(BOB64_SYSCALL_READ_USER read_user,void *context) {
syscall_read_user=read_user;
syscall_read_user_context=context;
}
void bob64_syscall_set_write_user(BOB64_SYSCALL_WRITE_USER write_user,void *context) {
syscall_write_user=write_user;
syscall_write_user_context=context;
}
void bob64_syscall_set_filesystem(BOB64_SYSCALL_FILE_READ read_file,
BOB64_SYSCALL_FILE_WRITE write_file,void *context) {
syscall_file_read=read_file;
syscall_file_write=write_file;
syscall_filesystem_context=context;
}
void bob64_syscall_set_file_manager(BOB64_SYSCALL_FILE_LIST list_files,
BOB64_SYSCALL_FILE_DELETE delete_file,
void *context) {
syscall_file_list=list_files;
syscall_file_delete=delete_file;
syscall_file_manager_context=context;
}
void bob64_syscall_set_file_stream(BOB64_SYSCALL_FILE_OPEN open_file,
BOB64_SYSCALL_FILE_READ_AT read_at,
BOB64_SYSCALL_FILE_WRITE_AT write_at,
void *context) {
syscall_file_open=open_file;syscall_file_read_at=read_at;
syscall_file_write_at=write_at;syscall_file_stream_context=context;
for(usize i=0;i<BOB64_SYSCALL_OPEN_HANDLES;i++)syscall_handles[i].Id=0;
}
void bob64_syscall_set_wait_event(BOB64_SYSCALL_EVENT_WAIT wait_event,void *context) {
syscall_wait_event=wait_event;
syscall_wait_event_context=context;
}
void bob64_syscall_set_window_server(BOB64_WINDOW_SERVER *server,u64 owner) {
syscall_window_server=server;
syscall_window_owner=server?owner:0;
}
void bob64_syscall_set_address_space(const BOB64_PAGE_TABLE *page_table) {
syscall_page_table=page_table;
}
static int syscall_validate_user_range(const BOB64_PAGE_TABLE *page_table,
u64 address,u64 length,u64 required_flags,
u64 maximum_length) {
u64 arena_end=BOB64_PROCESS_IMAGE_BASE+BOB64_PROCESS_ISOLATED_SIZE;
u64 end,first_page,last_page,physical,flags;
if(!page_table||length>maximum_length||
address<BOB64_PROCESS_IMAGE_BASE||address>=arena_end||
length>arena_end-address)return -1;
if(!length)return 0;
end=address+length-1;
first_page=address&~(BOB64_PAGE_SIZE-1);
last_page=end&~(BOB64_PAGE_SIZE-1);
for(u64 page=first_page;;page+=BOB64_PAGE_SIZE) {
if(bob64_page_translate(page_table,page,&physical,&flags)!=1||
(flags&required_flags)!=required_flags)return -1;
if(page==last_page)break;
}
return 0;
}
int bob64_syscall_validate_user_range(const BOB64_PAGE_TABLE *page_table,
u64 address,u64 length) {
return syscall_validate_user_range(page_table,address,length,BOB64_PAGE_USER,
BOB64_SYSCALL_MAX_BUFFER);
}
u64 BOB64_MS_ABI bob64_syscall_dispatch(BOB64_INTERRUPT_FRAME *frame) {
if(!frame)return 0;
if((frame->CS&3)!=3||!bob64_user_active) {
frame->RAX=(u64)-1;
return 0;
}
if(frame->RAX==BOB64_SYSCALL_QUERY_ABI) {
frame->RAX=BOB64_SYSCALL_ABI_VERSION;
return 0;
}
if(frame->RAX==BOB64_SYSCALL_GET_TICKS) {
frame->RAX=bob64_timer_ticks();
return 0;
}
if(frame->RAX==BOB64_SYSCALL_WRITE_CHAR) {
if(!syscall_write_character) {
frame->RAX=(u64)-1;
return 0;
}
syscall_write_character(syscall_write_context,(u8)frame->RCX);
frame->RAX=0;
return 0;
}
if(frame->RAX==BOB64_SYSCALL_WRITE_BUFFER) {
u64 address=frame->RCX,length=frame->RDX;
if(!syscall_write_character||!syscall_read_user||
bob64_syscall_validate_user_range(syscall_page_table,address,length)||
syscall_read_user(syscall_read_user_context,address,syscall_buffer,(usize)length)) {
frame->RAX=(u64)-14;
return 0;
}
for(u64 i=0;i<length;i++)
syscall_write_character(syscall_write_context,syscall_buffer[(usize)i]);
frame->RAX=length;
return 0;
}
if(frame->RAX==BOB64_SYSCALL_GET_DISPLAY) {
u32 width,height;
if(bob64_framebuffer_resolution(&width,&height)) {
frame->RAX=(u64)-19;frame->RDX=0;
} else {
frame->RAX=width;frame->RDX=height;
}
return 0;
}
if(frame->RAX==BOB64_SYSCALL_PRESENT) {
u64 address=frame->RCX,width=frame->RDX,height=frame->R8;
u32 display_width,display_height;
u64 pixels,bytes,offset=0;
if(bob64_framebuffer_resolution(&display_width,&display_height)) {
frame->RAX=(u64)-19;return 0;
}
if(width!=display_width||height!=display_height||!height||
width>~(u64)0/height||
(pixels=width*height)>~(u64)0/sizeof(u32)||
(bytes=pixels*sizeof(u32))>BOB64_SYSCALL_MAX_SURFACE_BYTES||
syscall_validate_user_range(syscall_page_table,address,bytes,
BOB64_PAGE_USER,BOB64_SYSCALL_MAX_SURFACE_BYTES)||!syscall_read_user) {
frame->RAX=(u64)-14;return 0;
}
while(offset<pixels) {
u32 count=(u32)(pixels-offset>
sizeof(syscall_surface_chunk)/sizeof(syscall_surface_chunk[0])?
sizeof(syscall_surface_chunk)/sizeof(syscall_surface_chunk[0]):
pixels-offset);
if(syscall_read_user(syscall_read_user_context,address+offset*sizeof(u32),
syscall_surface_chunk,(usize)count*sizeof(u32))||
bob64_framebuffer_write_pixels(offset,syscall_surface_chunk,count)) {
frame->RAX=(u64)-14;return 0;
}
offset+=count;
}
frame->RAX=pixels;return 0;
}
if(frame->RAX==BOB64_SYSCALL_WAIT_EVENT) {
BOB64_EVENT event;
BOB64_EVENT routed;
u64 address=frame->RCX;
if(!syscall_wait_event||!syscall_write_user||
syscall_validate_user_range(syscall_page_table,address,sizeof(event),
BOB64_PAGE_USER|BOB64_PAGE_WRITE,sizeof(event))||
syscall_wait_event(syscall_wait_event_context,&event)) {
frame->RAX=(u64)-14;
return 0;
}
if(syscall_window_server) {
if(bob64_window_server_route_event(syscall_window_server,
syscall_window_owner,&event,&routed)<0) {
frame->RAX=(u64)-14;return 0;
}
event=routed;
}
if(syscall_write_user(syscall_write_user_context,address,&event,sizeof(event)))
frame->RAX=(u64)-14;
else frame->RAX=0;
return 0;
}
if(frame->RAX==BOB64_SYSCALL_LIST_FILES) {
u64 address=frame->RCX,capacity=frame->RDX;
u64 bytes;
s64 count;
if(!capacity||capacity>BOB64_SYSCALL_MAX_FILES||
capacity>~(u64)0/sizeof(BOB64_FILE_INFO)) {
frame->RAX=(u64)-22;return 0;
}
bytes=capacity*sizeof(BOB64_FILE_INFO);
if(syscall_validate_user_range(syscall_page_table,address,bytes,
BOB64_PAGE_USER|BOB64_PAGE_WRITE,BOB64_SYSCALL_MAX_FILES*sizeof(BOB64_FILE_INFO))) {
frame->RAX=(u64)-14;return 0;
}
if(!syscall_file_list||!syscall_write_user) {
frame->RAX=(u64)-38;return 0;
}
for(usize i=0;i<(usize)capacity;i++)
for(usize j=0;j<sizeof(syscall_file_entries[i]);j++)
((u8 *)&syscall_file_entries[i])[j]=0;
count=syscall_file_list(syscall_file_manager_context,syscall_file_entries,
(usize)capacity);
if(count<0||(u64)count>capacity) {
frame->RAX=(u64)(count<0?count:-5);return 0;
}
bytes=(u64)count*sizeof(BOB64_FILE_INFO);
if(bytes&&syscall_write_user(syscall_write_user_context,address,
syscall_file_entries,(usize)bytes)) {
frame->RAX=(u64)-14;return 0;
}
frame->RAX=(u64)count;return 0;
}
if(frame->RAX==BOB64_SYSCALL_DELETE_FILE) {
u64 name_address=frame->RCX,name_length=frame->RDX;
char name[BOB64_SYSCALL_MAX_FILENAME+1];
if(!name_length||name_length>BOB64_SYSCALL_MAX_FILENAME) {
frame->RAX=(u64)-22;return 0;
}
if(bob64_syscall_validate_user_range(syscall_page_table,name_address,name_length)||
!syscall_read_user||syscall_read_user(syscall_read_user_context,name_address,
name,(usize)name_length)) {
frame->RAX=(u64)-14;return 0;
}
for(u64 i=0;i<name_length;i++)if(!name[i]) {
frame->RAX=(u64)-22;return 0;
}
name[name_length]=0;
if(!syscall_file_delete)frame->RAX=(u64)-38;
else {
s64 result=syscall_file_delete(syscall_file_manager_context,name);
if(!result)for(usize i=0;i<BOB64_SYSCALL_OPEN_HANDLES;i++)
if(syscall_handles[i].Id) {
usize j=0;while(syscall_handles[i].Name[j]&&syscall_handles[i].Name[j]==name[j])j++;
if(!syscall_handles[i].Name[j]&&!name[j])syscall_handles[i].Id=0;
}
frame->RAX=(u64)result;
}
return 0;
}
if(frame->RAX==BOB64_SYSCALL_CREATE_WINDOW) {
s64 x=(s64)frame->RCX,y=(s64)frame->RDX;
if(!syscall_window_server||x<(-2147483647LL-1)||x>2147483647LL||
y<(-2147483647LL-1)||y>2147483647LL||
frame->R8>0xffffffffULL||frame->R9>0xffffffffULL||!frame->R8||!frame->R9) {
frame->RAX=(u64)-22;return 0;
}
BOB64_WINDOW_HANDLE handle=bob64_window_server_create(syscall_window_server,
syscall_window_owner,(s32)x,(s32)y,(u32)frame->R8,(u32)frame->R9);
frame->RAX=handle?handle:(u64)-12;
return 0;
}
if(frame->RAX==BOB64_SYSCALL_DESTROY_WINDOW) {
if(!syscall_window_server||bob64_window_server_destroy(syscall_window_server,
syscall_window_owner,frame->RCX))frame->RAX=(u64)-22;
else frame->RAX=0;
return 0;
}
if(frame->RAX==BOB64_SYSCALL_FOCUS_WINDOW) {
if(!syscall_window_server||bob64_window_server_focus(syscall_window_server,
syscall_window_owner,frame->RCX))frame->RAX=(u64)-22;
else frame->RAX=0;
return 0;
}
if(frame->RAX==BOB64_SYSCALL_PRESENT_WINDOW) {
u64 handle=frame->RCX,address=frame->RDX,width=frame->R8,height=frame->R9;
u32 expected_width,expected_height;
u64 pixels,bytes,offset=0;
if(!syscall_window_server||width>0xffffffffULL||height>0xffffffffULL||
!width||!height||width>~(u64)0/height||
(pixels=width*height)>~(u64)0/sizeof(u32)||
(bytes=pixels*sizeof(u32))>BOB64_WINDOW_SERVER_SURFACE_LIMIT||
bob64_window_server_surface_size(syscall_window_server,syscall_window_owner,
handle,&expected_width,&expected_height)||
width!=expected_width||height!=expected_height||
syscall_validate_user_range(syscall_page_table,address,bytes,
BOB64_PAGE_USER,BOB64_WINDOW_SERVER_SURFACE_LIMIT)||!syscall_read_user) {
frame->RAX=(u64)-14;return 0;
}
while(offset<pixels) {
u32 count=(u32)(pixels-offset>
sizeof(syscall_surface_chunk)/sizeof(syscall_surface_chunk[0])?
sizeof(syscall_surface_chunk)/sizeof(syscall_surface_chunk[0]):
pixels-offset);
if(syscall_read_user(syscall_read_user_context,address+offset*sizeof(u32),
syscall_surface_chunk,(usize)count*sizeof(u32))||
bob64_window_server_write_pixels(syscall_window_server,
syscall_window_owner,handle,offset,syscall_surface_chunk,count)) {
frame->RAX=(u64)-14;return 0;
}
offset+=count;
}
frame->RAX=bob64_window_server_present(syscall_window_server,
syscall_window_owner,handle)?(u64)-14:pixels;
return 0;
}
if(frame->RAX==BOB64_SYSCALL_READ_FILE||
frame->RAX==BOB64_SYSCALL_WRITE_FILE) {
u64 name_address=frame->RCX,name_length=frame->RDX;
u64 buffer_address=frame->R8,buffer_length=frame->R9;
char name[BOB64_SYSCALL_MAX_FILENAME+1];
s64 result;
if(!name_length||name_length>BOB64_SYSCALL_MAX_FILENAME||
buffer_length>BOB64_SYSCALL_MAX_BUFFER) {
frame->RAX=(u64)-22;
return 0;
}
if(bob64_syscall_validate_user_range(syscall_page_table,name_address,name_length)||
syscall_validate_user_range(syscall_page_table,buffer_address,buffer_length,
BOB64_PAGE_USER|(frame->RAX==BOB64_SYSCALL_READ_FILE?BOB64_PAGE_WRITE:0),
BOB64_SYSCALL_MAX_BUFFER)||
!syscall_read_user||
syscall_read_user(syscall_read_user_context,name_address,name,(usize)name_length)) {
frame->RAX=(u64)-14;
return 0;
}
for(u64 i=0;i<name_length;i++)if(!name[i]) {
frame->RAX=(u64)-22;
return 0;
}
name[name_length]=0;
if(frame->RAX==BOB64_SYSCALL_WRITE_FILE) {
if(!syscall_file_write)result=-38;
else if(syscall_read_user(syscall_read_user_context,buffer_address,
syscall_buffer,(usize)buffer_length))result=-14;
else result=syscall_file_write(syscall_filesystem_context,name,syscall_buffer,
(usize)buffer_length);
} else if(!syscall_file_read)result=-38;
else {
result=syscall_file_read(syscall_filesystem_context,name,syscall_buffer,
(usize)buffer_length);
if(result>=0&&((u64)result>buffer_length||(result&&(!syscall_write_user||
syscall_write_user(syscall_write_user_context,buffer_address,syscall_buffer,
(usize)result)))))result=-14;
}
frame->RAX=(u64)result;
return 0;
}
if(frame->RAX==BOB64_SYSCALL_OPEN_FILE) {
u64 name_address=frame->RCX,name_length=frame->RDX;
u32 flags=(u32)frame->R8;
char name[BOB64_SYSCALL_MAX_FILENAME+1];
BOB64_SYSCALL_HANDLE *slot=0;
s64 size;u64 new_id=0;
if(!name_length||name_length>BOB64_SYSCALL_MAX_FILENAME||
frame->R8>BOB64_FILE_OPEN_FLAGS||!(flags&(BOB64_FILE_OPEN_READ|BOB64_FILE_OPEN_WRITE))||
((flags&BOB64_FILE_OPEN_TRUNCATE)&&!(flags&BOB64_FILE_OPEN_WRITE))||
((flags&BOB64_FILE_OPEN_APPEND)&&!(flags&BOB64_FILE_OPEN_WRITE))) {
frame->RAX=(u64)-22;return 0;
}
if(bob64_syscall_validate_user_range(syscall_page_table,name_address,name_length)||
!syscall_read_user||syscall_read_user(syscall_read_user_context,name_address,
name,(usize)name_length)) {
frame->RAX=(u64)-14;return 0;
}
for(u64 i=0;i<name_length;i++)if(!name[i]) {frame->RAX=(u64)-22;return 0;}
name[name_length]=0;
if(!syscall_file_open) {frame->RAX=(u64)-38;return 0;}
for(usize i=0;i<BOB64_SYSCALL_OPEN_HANDLES;i++)
if(!syscall_handles[i].Id){slot=&syscall_handles[i];break;}
if(!slot) {frame->RAX=(u64)-24;return 0;}
size=syscall_file_open(syscall_file_stream_context,name,flags);
if(size<0) {frame->RAX=(u64)size;return 0;}
for(usize attempt=0;attempt<=BOB64_SYSCALL_OPEN_HANDLES;attempt++) {
u64 candidate=syscall_next_handle++;
if(candidate&&!find_handle(candidate)){new_id=candidate;break;}
}
if(!new_id){frame->RAX=(u64)-24;return 0;}
slot->Id=new_id;
slot->Flags=flags;slot->Position=(flags&BOB64_FILE_OPEN_APPEND)?(u64)size:0;
for(usize i=0;i<=name_length;i++)slot->Name[i]=name[i];
frame->RAX=slot->Id;return 0;
}
if(frame->RAX==BOB64_SYSCALL_READ_HANDLE||
frame->RAX==BOB64_SYSCALL_WRITE_HANDLE) {
u64 id=frame->RCX,address=frame->RDX,length=frame->R8;
BOB64_SYSCALL_HANDLE *handle=find_handle(id);
s64 result;
int writing=frame->RAX==BOB64_SYSCALL_WRITE_HANDLE;
if(length>BOB64_SYSCALL_MAX_BUFFER) {frame->RAX=(u64)-22;return 0;}
if(!handle||!(handle->Flags&(writing?BOB64_FILE_OPEN_WRITE:BOB64_FILE_OPEN_READ))) {
frame->RAX=(u64)-9;return 0;
}
if(syscall_validate_user_range(syscall_page_table,address,length,
BOB64_PAGE_USER|(writing?0:BOB64_PAGE_WRITE),BOB64_SYSCALL_MAX_BUFFER)||
(length&&!syscall_read_user)) {frame->RAX=(u64)-14;return 0;}
if(writing) {
if(!syscall_file_write_at) {frame->RAX=(u64)-38;return 0;}
if(handle->Flags&BOB64_FILE_OPEN_APPEND) {
s64 end=syscall_file_open(syscall_file_stream_context,handle->Name,
handle->Flags&(BOB64_FILE_OPEN_READ|BOB64_FILE_OPEN_WRITE));
if(end<0) {frame->RAX=(u64)end;return 0;}
handle->Position=(u64)end;
}
if(handle->Position>0x7fffffffffffffffULL||
length>0x7fffffffffffffffULL-handle->Position) {
frame->RAX=(u64)-75;return 0;
}
if(length&&syscall_read_user(syscall_read_user_context,address,syscall_buffer,
(usize)length)) {
frame->RAX=(u64)-14;return 0;
}
result=syscall_file_write_at(syscall_file_stream_context,handle->Name,
handle->Position,syscall_buffer,(usize)length);
if(result>=0&&(u64)result<=length&&
(u64)result<=0x7fffffffffffffffULL-handle->Position)
handle->Position+=(u64)result;
else if(result>=0)result=-5;
} else {
if(!syscall_file_read_at||!syscall_write_user) {frame->RAX=(u64)-38;return 0;}
if(handle->Position>0x7fffffffffffffffULL||
length>0x7fffffffffffffffULL-handle->Position) {
frame->RAX=(u64)-75;return 0;
}
result=syscall_file_read_at(syscall_file_stream_context,handle->Name,
handle->Position,syscall_buffer,(usize)length);
if(result>=0&&(u64)result<=length) {
if(result&&syscall_write_user(syscall_write_user_context,address,
syscall_buffer,(usize)result))result=-14;
else handle->Position+=(u64)result;
} else if(result>=0)result=-5;
}
frame->RAX=(u64)result;return 0;
}
if(frame->RAX==BOB64_SYSCALL_SEEK_HANDLE) {
BOB64_SYSCALL_HANDLE *handle=find_handle(frame->RCX);
if(!handle)frame->RAX=(u64)-9;
else {handle->Position=frame->RDX;frame->RAX=handle->Position;}
return 0;
}
if(frame->RAX==BOB64_SYSCALL_CLOSE_HANDLE) {
BOB64_SYSCALL_HANDLE *handle=find_handle(frame->RCX);
if(!handle)frame->RAX=(u64)-9;
else {handle->Id=0;frame->RAX=0;}
return 0;
}
if(frame->RAX==BOB64_SYSCALL_EXIT)bob64_user_request_return((s64)frame->RCX);
else bob64_user_request_return(-38);
return 1;
}
+73
View File
@@ -0,0 +1,73 @@
#ifndef BOB64_SYSCALL_H
#define BOB64_SYSCALL_H
#include "abi.h"
#include "interrupts.h"
#include "paging.h"
#include "event.h"
#include "window_server.h"
#define BOB64_SYSCALL_CONTEXT_MAX_DEPTH 8u
#define BOB64_USER_ENTRY_MAX_DEPTH 8u
typedef struct {
u64 KernelRsp;
s64 ReturnValue;
s64 PreviousReturnValue;
u64 PreviousInterruptState;
u64 PreviousActive;
} BOB64_USER_RETURN_FRAME;
_Static_assert(sizeof(BOB64_USER_RETURN_FRAME)==40,
"assembly user-return frame layout");
typedef void (*BOB64_SYSCALL_WRITE)(void *context,u8 character);
typedef int (*BOB64_SYSCALL_READ_USER)(void *context,u64 address,
void *destination,usize length);
typedef int (*BOB64_SYSCALL_WRITE_USER)(void *context,u64 address,
const void *source,usize length);
typedef s64 (*BOB64_SYSCALL_FILE_READ)(void *context,const char *name,
u8 *buffer,usize capacity);
typedef s64 (*BOB64_SYSCALL_FILE_WRITE)(void *context,const char *name,
const u8 *buffer,usize length);
typedef s64 (*BOB64_SYSCALL_FILE_LIST)(void *context,BOB64_FILE_INFO *entries,
usize capacity);
typedef s64 (*BOB64_SYSCALL_FILE_DELETE)(void *context,const char *name);
typedef s64 (*BOB64_SYSCALL_FILE_OPEN)(void *context,const char *name,u32 flags);
typedef s64 (*BOB64_SYSCALL_FILE_READ_AT)(void *context,const char *name,u64 offset,
u8 *buffer,usize capacity);
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);
extern volatile u64 bob64_user_active;
extern volatile u64 bob64_user_depth;
extern BOB64_USER_RETURN_FRAME bob64_user_return_frames[BOB64_USER_ENTRY_MAX_DEPTH];
extern volatile s64 bob64_user_return_value;
void bob64_syscall_set_write(BOB64_SYSCALL_WRITE write_character,void *context);
void bob64_syscall_set_read_user(BOB64_SYSCALL_READ_USER read_user,void *context);
void bob64_syscall_set_write_user(BOB64_SYSCALL_WRITE_USER write_user,void *context);
void bob64_syscall_set_filesystem(BOB64_SYSCALL_FILE_READ read_file,
BOB64_SYSCALL_FILE_WRITE write_file,void *context);
void bob64_syscall_set_file_manager(BOB64_SYSCALL_FILE_LIST list_files,
BOB64_SYSCALL_FILE_DELETE delete_file,
void *context);
void bob64_syscall_set_file_stream(BOB64_SYSCALL_FILE_OPEN open_file,
BOB64_SYSCALL_FILE_READ_AT read_at,
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_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. */
int bob64_syscall_context_push(void);
int bob64_syscall_context_pop(void);
void bob64_user_request_return(s64 value);
int bob64_syscall_validate_user_range(const BOB64_PAGE_TABLE *page_table,
u64 address,u64 length);
/* Returns zero to resume the app, one to return from bob64_enter_user. */
u64 BOB64_MS_ABI bob64_syscall_dispatch(BOB64_INTERRUPT_FRAME *frame);
s64 BOB64_MS_ABI bob64_enter_user(u64 entry,u64 startup,u64 stack);
#endif
+28
View File
@@ -0,0 +1,28 @@
#ifndef BOB64_TYPES_H
#define BOB64_TYPES_H
/* bob64's freestanding C types. Addresses and pointers are always 64-bit. */
typedef unsigned char u8;
typedef signed char s8;
typedef unsigned short u16;
typedef signed short s16;
typedef unsigned int u32;
typedef signed int s32;
typedef unsigned long long u64;
typedef signed long long s64;
typedef __UINTPTR_TYPE__ uintptr_t;
typedef __INTPTR_TYPE__ intptr_t;
typedef __SIZE_TYPE__ usize;
typedef __PTRDIFF_TYPE__ isize;
_Static_assert(sizeof(u8)==1,"u8 must be 8 bits");
_Static_assert(sizeof(u16)==2,"u16 must be 16 bits");
_Static_assert(sizeof(u32)==4,"u32 must be 32 bits");
_Static_assert(sizeof(u64)==8,"u64 must be 64 bits");
_Static_assert(sizeof(uintptr_t)==8,"bob64 requires 64-bit pointers");
_Static_assert(sizeof(usize)==8,"bob64 requires 64-bit sizes");
#ifdef BOB64_UEFI_ABI
_Static_assert(sizeof(long)==4,"x64 UEFI target uses the LLP64 data model");
#endif
#endif
+270
View File
@@ -0,0 +1,270 @@
#ifndef BOB64_WINDOW_H
#define BOB64_WINDOW_H
#include "event.h"
typedef u64 BOB64_WINDOW_HANDLE;
#define BOB64_WINDOW_VISIBLE 1u
#define BOB64_WINDOW_DIRTY 2u
#define BOB64_WINDOW_TITLE_BAR_HEIGHT 24u
/* App-owned state. Context is a full-width app pointer and is never a kernel pointer. */
typedef struct {
BOB64_WINDOW_HANDLE Handle;
void *Context;
s32 X,Y;
u32 Width,Height,Flags;
} BOB64_WINDOW;
typedef struct {
BOB64_WINDOW *Windows;
BOB64_WINDOW_HANDLE *ZOrder;
u32 Capacity,Count,ScreenWidth,ScreenHeight,LastButtons;
BOB64_WINDOW_HANDLE Focused,Dragging,NextHandle;
s32 DragOffsetX,DragOffsetY;
u32 FullDirty,DrawIndex;
} BOB64_WINDOW_MANAGER;
static inline BOB64_WINDOW *bob64_wm_find(BOB64_WINDOW_MANAGER *manager,
BOB64_WINDOW_HANDLE handle) {
if(!manager||!handle)return 0;
for(u32 i=0;i<manager->Capacity;i++)
if(manager->Windows[i].Handle==handle)return &manager->Windows[i];
return 0;
}
static inline int bob64_wm_intersects(const BOB64_WINDOW *a,const BOB64_WINDOW *b) {
return (s64)a->X+a->Width>b->X&&(s64)b->X+b->Width>a->X&&
(s64)a->Y+a->Height>b->Y&&(s64)b->Y+b->Height>a->Y;
}
static inline void bob64_wm_clamp(BOB64_WINDOW_MANAGER *manager,BOB64_WINDOW *window) {
s32 max_x=(s32)(manager->ScreenWidth-window->Width);
s32 max_y=(s32)(manager->ScreenHeight-window->Height);
if(window->X<0)window->X=0;
if(window->Y<0)window->Y=0;
if(window->X>max_x)window->X=max_x;
if(window->Y>max_y)window->Y=max_y;
}
static inline void bob64_wm_dirty_all(BOB64_WINDOW_MANAGER *manager) {
for(u32 i=0;i<manager->Count;i++) {
BOB64_WINDOW *window=bob64_wm_find(manager,manager->ZOrder[i]);
if(window&&(window->Flags&BOB64_WINDOW_VISIBLE))window->Flags|=BOB64_WINDOW_DIRTY;
}
manager->FullDirty=1;
}
static inline int bob64_wm_init(BOB64_WINDOW_MANAGER *manager,
BOB64_WINDOW *windows,u32 capacity,
BOB64_WINDOW_HANDLE *z_order,
u32 screen_width,u32 screen_height) {
if(!manager||!windows||!z_order||!capacity||capacity>64||!screen_width||
!screen_height||screen_width>0x7fffffffu||screen_height>0x7fffffffu)return -1;
manager->Windows=windows;manager->ZOrder=z_order;
manager->Capacity=capacity;manager->Count=0;
manager->ScreenWidth=screen_width;manager->ScreenHeight=screen_height;
manager->LastButtons=0;manager->Focused=0;manager->Dragging=0;
manager->NextHandle=1;manager->DragOffsetX=0;manager->DragOffsetY=0;
manager->FullDirty=1;manager->DrawIndex=0;
for(u32 i=0;i<capacity;i++) {
windows[i].Handle=0;windows[i].Context=0;
windows[i].X=windows[i].Y=0;windows[i].Width=windows[i].Height=0;
windows[i].Flags=0;z_order[i]=0;
}
return 0;
}
static inline int bob64_wm_raise(BOB64_WINDOW_MANAGER *manager,
BOB64_WINDOW_HANDLE handle) {
u32 index=manager?manager->Count:0;
if(!manager||!bob64_wm_find(manager,handle))return -1;
for(u32 i=0;i<manager->Count;i++)if(manager->ZOrder[i]==handle){index=i;break;}
if(index==manager->Count)return -1;
if(index+1==manager->Count)return 0;
for(u32 i=index;i+1<manager->Count;i++)manager->ZOrder[i]=manager->ZOrder[i+1];
manager->ZOrder[manager->Count-1]=handle;
bob64_wm_dirty_all(manager);
return 1;
}
static inline int bob64_wm_focus(BOB64_WINDOW_MANAGER *manager,
BOB64_WINDOW_HANDLE handle) {
BOB64_WINDOW *window=bob64_wm_find(manager,handle);
if(!window||!(window->Flags&BOB64_WINDOW_VISIBLE))return -1;
bob64_wm_raise(manager,handle);
manager->Focused=handle;window->Flags|=BOB64_WINDOW_DIRTY;
return 0;
}
static inline BOB64_WINDOW_HANDLE bob64_wm_create(BOB64_WINDOW_MANAGER *manager,
s32 x,s32 y,u32 width,u32 height,void *context) {
BOB64_WINDOW *window=0;
if(!manager||!width||!height||width>manager->ScreenWidth||
height>manager->ScreenHeight||manager->Count>=manager->Capacity||
!manager->NextHandle||manager->NextHandle>0x7fffffffffffffffULL)return 0;
for(u32 i=0;i<manager->Capacity;i++)if(!manager->Windows[i].Handle) {
window=&manager->Windows[i];break;
}
if(!window)return 0;
window->Handle=manager->NextHandle++;
window->Context=context;window->X=x;window->Y=y;
window->Width=width;window->Height=height;
window->Flags=BOB64_WINDOW_VISIBLE|BOB64_WINDOW_DIRTY;
bob64_wm_clamp(manager,window);
manager->ZOrder[manager->Count++]=window->Handle;
manager->Focused=window->Handle;manager->Dragging=0;
bob64_wm_dirty_all(manager);
return window->Handle;
}
static inline int bob64_wm_move(BOB64_WINDOW_MANAGER *manager,
BOB64_WINDOW_HANDLE handle,s32 x,s32 y) {
BOB64_WINDOW *window=bob64_wm_find(manager,handle);
if(!window)return -1;
window->X=x;window->Y=y;bob64_wm_clamp(manager,window);
bob64_wm_dirty_all(manager);
return 0;
}
static inline int bob64_wm_show(BOB64_WINDOW_MANAGER *manager,
BOB64_WINDOW_HANDLE handle,int visible) {
BOB64_WINDOW *window=bob64_wm_find(manager,handle);
if(!window)return -1;
visible=visible!=0;
if(((window->Flags&BOB64_WINDOW_VISIBLE)!=0)==visible)return 0;
if(visible) {
window->Flags|=BOB64_WINDOW_VISIBLE;
bob64_wm_focus(manager,handle);
} else {
window->Flags&=~BOB64_WINDOW_VISIBLE;
if(manager->Dragging==handle)manager->Dragging=0;
if(manager->Focused==handle) {
manager->Focused=0;
for(u32 i=manager->Count;i>0;i--) {
BOB64_WINDOW *candidate=bob64_wm_find(manager,manager->ZOrder[i-1]);
if(candidate&&(candidate->Flags&BOB64_WINDOW_VISIBLE)) {
manager->Focused=candidate->Handle;break;
}
}
}
}
bob64_wm_dirty_all(manager);
return 1;
}
static inline int bob64_wm_destroy(BOB64_WINDOW_MANAGER *manager,
BOB64_WINDOW_HANDLE handle) {
BOB64_WINDOW *window=bob64_wm_find(manager,handle);
u32 index;
if(!window)return -1;
for(index=0;index<manager->Count;index++)if(manager->ZOrder[index]==handle)break;
if(index==manager->Count)return -1;
for(u32 i=index;i+1<manager->Count;i++)manager->ZOrder[i]=manager->ZOrder[i+1];
manager->ZOrder[--manager->Count]=0;
if(manager->Focused==handle)manager->Focused=0;
if(manager->Dragging==handle)manager->Dragging=0;
window->Handle=0;window->Context=0;window->Flags=0;
window->X=window->Y=0;window->Width=window->Height=0;
if(!manager->Focused)for(u32 i=manager->Count;i>0;i--) {
BOB64_WINDOW *candidate=bob64_wm_find(manager,manager->ZOrder[i-1]);
if(candidate&&(candidate->Flags&BOB64_WINDOW_VISIBLE)) {
manager->Focused=candidate->Handle;break;
}
}
bob64_wm_dirty_all(manager);
return 0;
}
static inline void bob64_wm_invalidate(BOB64_WINDOW_MANAGER *manager,
BOB64_WINDOW_HANDLE handle) {
BOB64_WINDOW *window=bob64_wm_find(manager,handle);
if(!window)return;
window->Flags|=BOB64_WINDOW_DIRTY;
for(u32 i=0;i<manager->Count;i++) {
BOB64_WINDOW *other=bob64_wm_find(manager,manager->ZOrder[i]);
if(other&&other!=window&&(other->Flags&BOB64_WINDOW_VISIBLE)&&
bob64_wm_intersects(window,other))other->Flags|=BOB64_WINDOW_DIRTY;
}
}
static inline int bob64_wm_begin_draw(BOB64_WINDOW_MANAGER *manager) {
if(!manager)return -1;
if(manager->FullDirty)bob64_wm_dirty_all(manager);
manager->FullDirty=0;manager->DrawIndex=0;
return 0;
}
static inline BOB64_WINDOW_HANDLE bob64_wm_next_dirty(BOB64_WINDOW_MANAGER *manager) {
if(!manager)return 0;
while(manager->DrawIndex<manager->Count) {
BOB64_WINDOW_HANDLE handle=manager->ZOrder[manager->DrawIndex++];
BOB64_WINDOW *window=bob64_wm_find(manager,handle);
if(window&&(window->Flags&BOB64_WINDOW_VISIBLE)&&
(window->Flags&BOB64_WINDOW_DIRTY)) {
window->Flags&=~BOB64_WINDOW_DIRTY;return handle;
}
}
return 0;
}
static inline BOB64_WINDOW_HANDLE bob64_wm_hit_test(const BOB64_WINDOW_MANAGER *manager,
s32 x,s32 y) {
if(!manager)return 0;
for(u32 i=manager->Count;i>0;i--) {
BOB64_WINDOW *window=bob64_wm_find((BOB64_WINDOW_MANAGER *)manager,
manager->ZOrder[i-1]);
if(window&&(window->Flags&BOB64_WINDOW_VISIBLE)&&x>=window->X&&y>=window->Y&&
(s64)x<=(s64)window->X+window->Width-1&&
(s64)y<=(s64)window->Y+window->Height-1)return window->Handle;
}
return 0;
}
/* Returns the target handle, zero for unhandled input, or -1 for invalid arguments. */
static inline s64 bob64_wm_dispatch(BOB64_WINDOW_MANAGER *manager,
const BOB64_EVENT *event,BOB64_EVENT *routed) {
BOB64_WINDOW_HANDLE target=0;
u32 pressed,released;
if(!manager||!event||!routed)return -1;
*routed=*event;
pressed=event->Buttons&~manager->LastButtons;
released=manager->LastButtons&~event->Buttons;
if(event->Type==BOB64_EVENT_KEY_DOWN||event->Type==BOB64_EVENT_KEY_UP) {
BOB64_WINDOW *focused=bob64_wm_find(manager,manager->Focused);
if(focused&&(focused->Flags&BOB64_WINDOW_VISIBLE))target=focused->Handle;
} else if(event->Type==BOB64_EVENT_MOUSE_MOVE||
event->Type==BOB64_EVENT_MOUSE_BUTTON||
event->Type==BOB64_EVENT_MOUSE_WHEEL) {
if(manager->Dragging)target=manager->Dragging;
else target=bob64_wm_hit_test(manager,event->X,event->Y);
BOB64_WINDOW *window=bob64_wm_find(manager,target);
if(window) {
if(event->Type==BOB64_EVENT_MOUSE_BUTTON&&pressed) {
bob64_wm_focus(manager,target);window=bob64_wm_find(manager,target);
if((pressed&1u)&&event->Y>=window->Y&&
(u32)(event->Y-window->Y)<BOB64_WINDOW_TITLE_BAR_HEIGHT) {
manager->Dragging=target;
manager->DragOffsetX=event->X-window->X;
manager->DragOffsetY=event->Y-window->Y;
}
}
if(manager->Dragging&&
(event->Type==BOB64_EVENT_MOUSE_MOVE||event->Type==BOB64_EVENT_MOUSE_BUTTON)) {
if((event->Type==BOB64_EVENT_MOUSE_MOVE&&(event->Buttons&1u))||
event->Type==BOB64_EVENT_MOUSE_BUTTON)
bob64_wm_move(manager,target,event->X-manager->DragOffsetX,
event->Y-manager->DragOffsetY);
if(released&1u)manager->Dragging=0;
window=bob64_wm_find(manager,target);
}
routed->X=event->X-window->X;routed->Y=event->Y-window->Y;
}
}
if(event->Type==BOB64_EVENT_MOUSE_MOVE||event->Type==BOB64_EVENT_MOUSE_BUTTON||
event->Type==BOB64_EVENT_MOUSE_WHEEL)manager->LastButtons=event->Buttons;
return (s64)target;
}
#endif
+176
View File
@@ -0,0 +1,176 @@
#include "window_server.h"
/* The compositor runs on the single kernel CPU with interrupts disabled. */
static u32 server_composite_chunk[1024];
static int server_has_owner(const BOB64_WINDOW_SERVER *server,u64 owner) {
return server&&server->Active&&owner&&owner==server->Owner;
}
static int server_slot(const BOB64_WINDOW_SERVER *server,
BOB64_WINDOW_HANDLE handle) {
if(!server||!handle)return -1;
for(u32 i=0;i<BOB64_WINDOW_SERVER_CAPACITY;i++)
if(server->Windows[i].Handle==handle)return (int)i;
return -1;
}
static u32 server_pixel(const BOB64_WINDOW_SERVER *server,u32 x,u32 y) {
for(u32 i=server->Manager.Count;i>0;i--) {
BOB64_WINDOW_HANDLE handle=server->Manager.ZOrder[i-1];
BOB64_WINDOW *window=bob64_wm_find((BOB64_WINDOW_MANAGER *)&server->Manager,
handle);
if(window&&(window->Flags&BOB64_WINDOW_VISIBLE)&&x>=(u32)window->X&&
y>=(u32)window->Y&&x-(u32)window->X<window->Width&&
y-(u32)window->Y<window->Height) {
const u32 *surface=(const u32 *)window->Context;
return surface[(usize)(y-(u32)window->Y)*window->Width+
(x-(u32)window->X)];
}
}
return 0x000d1723u;
}
static int server_composite(BOB64_WINDOW_SERVER *server) {
u32 width,height;
u64 total,offset=0;
if(!server||bob64_framebuffer_resolution(&width,&height))return -1;
total=(u64)width*height;
while(offset<total) {
u32 count=(u32)(total-offset>
sizeof(server_composite_chunk)/sizeof(server_composite_chunk[0])?
sizeof(server_composite_chunk)/sizeof(server_composite_chunk[0]):total-offset);
for(u32 i=0;i<count;i++) {
u64 index=offset+i;
server_composite_chunk[i]=server_pixel(server,(u32)(index%width),
(u32)(index/width));
}
if(bob64_framebuffer_write_pixels(offset,server_composite_chunk,count))return -1;
offset+=count;
}
return 0;
}
int bob64_window_server_init(BOB64_WINDOW_SERVER *server,BOB64_HEAP *heap,
u64 owner,u32 screen_width,u32 screen_height) {
if(!server||!heap||!owner||!bob64_framebuffer_available())return -1;
for(usize i=0;i<sizeof(*server);i++)((u8 *)server)[i]=0;
if(bob64_wm_init(&server->Manager,server->Windows,
BOB64_WINDOW_SERVER_CAPACITY,server->ZOrder,screen_width,screen_height))return -1;
server->Heap=heap;server->Owner=owner;server->Active=1;
return server_composite(server);
}
void bob64_window_server_close(BOB64_WINDOW_SERVER *server) {
if(!server||!server->Active)return;
while(server->Manager.Count) {
BOB64_WINDOW_HANDLE handle=server->Manager.ZOrder[server->Manager.Count-1];
if(bob64_window_server_destroy(server,server->Owner,handle))break;
}
server->Active=0;server->Owner=0;server->BytesAllocated=0;
}
BOB64_WINDOW_HANDLE bob64_window_server_create(BOB64_WINDOW_SERVER *server,
u64 owner,s32 x,s32 y,u32 width,u32 height) {
u64 pixels,bytes;
u32 *surface;
BOB64_WINDOW_HANDLE handle;
int slot;
if(!server_has_owner(server,owner)||!width||!height||
(u64)width>~(u64)0/height)return 0;
pixels=(u64)width*height;
if(pixels>~(u64)0/sizeof(u32))return 0;
bytes=pixels*sizeof(u32);
if(bytes>BOB64_WINDOW_SERVER_SURFACE_LIMIT-server->BytesAllocated||
bytes>(u64)~(usize)0)return 0;
surface=(u32 *)bob64_heap_calloc(server->Heap,1,(usize)bytes);
if(!surface)return 0;
handle=bob64_wm_create(&server->Manager,x,y,width,height,surface);
slot=server_slot(server,handle);
if(!handle||slot<0) {
bob64_heap_free(server->Heap,surface);return 0;
}
server->Owners[slot]=owner;server->SurfaceBytes[slot]=(usize)bytes;
server->BytesAllocated+=bytes;
if(server_composite(server)) {
bob64_window_server_destroy(server,owner,handle);return 0;
}
return handle;
}
int bob64_window_server_destroy(BOB64_WINDOW_SERVER *server,u64 owner,
BOB64_WINDOW_HANDLE handle) {
int slot;
u32 *surface;
if(!server_has_owner(server,owner)||(slot=server_slot(server,handle))<0||
server->Owners[slot]!=owner)return -1;
surface=(u32 *)server->Windows[slot].Context;
if(bob64_wm_destroy(&server->Manager,handle))return -1;
if(surface) {
server->BytesAllocated-=server->SurfaceBytes[slot];
if(bob64_heap_free(server->Heap,surface))return -1;
}
server->Owners[slot]=0;server->SurfaceBytes[slot]=0;
return server_composite(server);
}
int bob64_window_server_move(BOB64_WINDOW_SERVER *server,u64 owner,
BOB64_WINDOW_HANDLE handle,s32 x,s32 y) {
int slot=server_slot(server,handle);
if(!server_has_owner(server,owner)||slot<0||server->Owners[slot]!=owner||
bob64_wm_move(&server->Manager,handle,x,y))return -1;
return server_composite(server);
}
int bob64_window_server_focus(BOB64_WINDOW_SERVER *server,u64 owner,
BOB64_WINDOW_HANDLE handle) {
int slot=server_slot(server,handle);
if(!server_has_owner(server,owner)||slot<0||server->Owners[slot]!=owner||
bob64_wm_focus(&server->Manager,handle))return -1;
return server_composite(server);
}
int bob64_window_server_write_pixels(BOB64_WINDOW_SERVER *server,u64 owner,
BOB64_WINDOW_HANDLE handle,u64 first_pixel,const u32 *pixels,u32 count) {
int slot=server_slot(server,handle);
u64 total;
u32 *surface;
if(!server_has_owner(server,owner)||slot<0||server->Owners[slot]!=owner||
(!pixels&&count))return -1;
BOB64_WINDOW *window=&server->Windows[slot];
total=(u64)window->Width*window->Height;
if(first_pixel>total||(u64)count>total-first_pixel)return -1;
surface=(u32 *)window->Context;
for(u32 i=0;i<count;i++)surface[first_pixel+i]=pixels[i]&0x00ffffffu;
return 0;
}
int bob64_window_server_surface_size(const BOB64_WINDOW_SERVER *server,u64 owner,
BOB64_WINDOW_HANDLE handle,u32 *width,u32 *height) {
int slot=server_slot(server,handle);
if(!server_has_owner(server,owner)||slot<0||server->Owners[slot]!=owner||
!width||!height)return -1;
*width=server->Windows[slot].Width;*height=server->Windows[slot].Height;
return 0;
}
int bob64_window_server_present(BOB64_WINDOW_SERVER *server,u64 owner,
BOB64_WINDOW_HANDLE handle) {
int slot=server_slot(server,handle);
if(!server_has_owner(server,owner)||slot<0||server->Owners[slot]!=owner)return -1;
return server_composite(server);
}
s64 bob64_window_server_route_event(BOB64_WINDOW_SERVER *server,u64 owner,
const BOB64_EVENT *event,BOB64_EVENT *routed) {
s64 target;
if(!server_has_owner(server,owner)||!event||!routed)return -1;
target=bob64_wm_dispatch(&server->Manager,event,routed);
if(target<0)return target;
routed->WindowHandle=(u64)target;
routed->ScreenX=event->X;routed->ScreenY=event->Y;
if(event->Type==BOB64_EVENT_MOUSE_MOVE||event->Type==BOB64_EVENT_MOUSE_BUTTON||
event->Type==BOB64_EVENT_MOUSE_WHEEL)
if(server_composite(server))return -1;
return target;
}
+43
View File
@@ -0,0 +1,43 @@
#ifndef BOB64_WINDOW_SERVER_H
#define BOB64_WINDOW_SERVER_H
#include "window.h"
#include "heap.h"
#include "console.h"
#define BOB64_WINDOW_SERVER_CAPACITY 16u
#define BOB64_WINDOW_SERVER_SURFACE_LIMIT (16u*1024u*1024u)
typedef struct {
BOB64_HEAP *Heap;
BOB64_WINDOW_MANAGER Manager;
BOB64_WINDOW Windows[BOB64_WINDOW_SERVER_CAPACITY];
BOB64_WINDOW_HANDLE ZOrder[BOB64_WINDOW_SERVER_CAPACITY];
u64 Owners[BOB64_WINDOW_SERVER_CAPACITY];
usize SurfaceBytes[BOB64_WINDOW_SERVER_CAPACITY];
u64 Owner;
u64 BytesAllocated;
u8 Active;
} BOB64_WINDOW_SERVER;
int bob64_window_server_init(BOB64_WINDOW_SERVER *server,BOB64_HEAP *heap,
u64 owner,u32 screen_width,u32 screen_height);
void bob64_window_server_close(BOB64_WINDOW_SERVER *server);
BOB64_WINDOW_HANDLE bob64_window_server_create(BOB64_WINDOW_SERVER *server,
u64 owner,s32 x,s32 y,u32 width,u32 height);
int bob64_window_server_destroy(BOB64_WINDOW_SERVER *server,u64 owner,
BOB64_WINDOW_HANDLE handle);
int bob64_window_server_move(BOB64_WINDOW_SERVER *server,u64 owner,
BOB64_WINDOW_HANDLE handle,s32 x,s32 y);
int bob64_window_server_focus(BOB64_WINDOW_SERVER *server,u64 owner,
BOB64_WINDOW_HANDLE handle);
int bob64_window_server_write_pixels(BOB64_WINDOW_SERVER *server,u64 owner,
BOB64_WINDOW_HANDLE handle,u64 first_pixel,const u32 *pixels,u32 count);
int bob64_window_server_surface_size(const BOB64_WINDOW_SERVER *server,u64 owner,
BOB64_WINDOW_HANDLE handle,u32 *width,u32 *height);
int bob64_window_server_present(BOB64_WINDOW_SERVER *server,u64 owner,
BOB64_WINDOW_HANDLE handle);
s64 bob64_window_server_route_event(BOB64_WINDOW_SERVER *server,u64 owner,
const BOB64_EVENT *event,BOB64_EVENT *routed);
#endif