mirror of
https://github.com/Alvin-Zilverstand/bob16.git
synced 2026-11-21 12:52:59 +01:00
e
This commit is contained in:
1 parent
78dd619293
commit
6dc841f956
109 files changed
+18192
-1907
No files matched your search
@@ -0,0 +1,395 @@
|
||||
# bob64 migration status
|
||||
|
||||
This document tracks the separate x86-64 OS target. `bob16` and `bob32` are
|
||||
software-emulated custom instruction sets; the current `bob32` kernel is not an
|
||||
x86 kernel and cannot be promoted to x86-64 by changing C integer widths. The
|
||||
new target starts as an x64 UEFI application. Its opt-in handoff now takes
|
||||
ownership of paging, early memory allocation, display output and a minimal shell;
|
||||
the existing emulator/build outputs stay separate.
|
||||
|
||||
## Implemented stages
|
||||
|
||||
- `bob64/types.h` defines fixed-width scalar types and pointer/size types from
|
||||
compiler-provided x86-64 definitions, with compile-time width checks.
|
||||
- `bob64/boot.c` builds as a PE32+ AMD64 EFI application at the standard
|
||||
removable-media path `EFI/BOOT/BOOTX64.EFI`. The image includes a PE base
|
||||
relocation directory and `DYNAMIC_BASE`, so firmware may load it away from its
|
||||
preferred `0x100000` image base.
|
||||
- x64 UEFI transfers control in 64-bit long mode with its x64 ABI, stack and
|
||||
page tables. The entry checks the maximum CPUID leaves before reading feature
|
||||
bits, requires PAE and long-mode support, and confirms `EFER.LMA` before it
|
||||
prints `bob64!` through UEFI text output. `bob64/cpu.c` also decodes NX
|
||||
support and the CPU's physical-address width for paging setup. The safe probe
|
||||
returns through firmware; the handoff variant switches to bob64-owned tables
|
||||
and exits Boot Services.
|
||||
- The boot entry reads the UEFI memory map through the x64 Boot Services table.
|
||||
`bob64/memory.c` parses the firmware-provided descriptor stride and seeds a
|
||||
sorted, coalesced first-fit allocator of 4 KiB conventional physical pages,
|
||||
keeping physical addresses in `u64`, clipping ranges to the detected CPU
|
||||
physical-address width, and reserving the first MiB. Allocation
|
||||
records make invalid and double frees fail; the independent live-allocation
|
||||
ledger supports up to 16,384 ranges, while free extents have a separate
|
||||
128-range limit. Boot reserves the replacement stack and table pool from this
|
||||
allocator, and the kernel continues allocating from the preserved state.
|
||||
- The x64 UEFI ABI is Microsoft's x64 ABI: integer/pointer arguments use
|
||||
`RCX`, `RDX`, `R8`, and `R9`; integer/pointer returns use `RAX`; `RSP` is
|
||||
16-byte aligned at call sites with 32 bytes of caller-provided shadow space.
|
||||
The compiler data model is LLP64 (`char` 8, `short` 16, `int` 32, `long` 32,
|
||||
`long long` 64, pointer/`size_t` 64). bob64 code should use `u64`/`s64` and
|
||||
`usize`/`isize` for explicit widths rather than assuming `long` is 64-bit.
|
||||
- `bob64/paging.c` builds four-level x86-64 page tables with 4 KiB
|
||||
leaves. Allocate/access callbacks keep physical page addresses distinct from
|
||||
currently accessible pointers; the builder enforces the CPUID-reported
|
||||
physical-address width. `bob64_page_map_range` validates canonical spans and
|
||||
maps byte ranges while preserving partial-page offsets. `bob64_page_protect`
|
||||
tightens leaf permissions and `bob64_page_unmap` returns the removed physical
|
||||
frame and flags; callers invalidate the TLB for live edits. The host suite
|
||||
walks low and upper canonical virtual addresses and physical/table addresses
|
||||
above 4 GiB, and verifies writable pages can become read-only/NX, be unmapped,
|
||||
and be mapped again. The handoff activates the root after enabling `EFER.NXE`
|
||||
when supported; host tests cover mapping logic, while the privileged switch
|
||||
still needs UEFI runtime verification.
|
||||
- `bob64/bootstrap.c` composes that mapper into a bootstrap identity address
|
||||
space for the loaded EFI image, a replacement stack, and a pre-reserved
|
||||
contiguous page-table pool. It marks stack/pool pages NX when supported and
|
||||
rejects overlapping ranges or an undersized pool. Tests verify translation
|
||||
and permissions for all three regions. The EFI entry obtains the loaded-image
|
||||
protocol and uses its full-width image base and size to prepare and verify
|
||||
identity mappings for the actual image, an 8-page replacement stack, and a
|
||||
128-page table pool. The handoff also maps its memory-map buffer and supported
|
||||
GOP framebuffer. It builds the kernel GDT and exception IDT while the image
|
||||
is mapped. The default `--bob64` image still returns safely to firmware after
|
||||
preparation.
|
||||
- `bob64/descriptors.c` builds kernel and DPL3 user code/data GDT entries, a
|
||||
full-width 64-bit TSS descriptor, the packed 10-byte GDTR/IDTR operand, and
|
||||
16-byte x86-64 IDT gates with split 64-bit handler addresses. Boot sets TSS
|
||||
`RSP0` to the initial kernel stack, and the handoff loads the task register.
|
||||
After heap startup, the kernel changes `RSP0` to a separate supervisor-only
|
||||
privilege-transition stack so user interrupts will not overwrite the paused
|
||||
kernel call stack. Each shell-launched application now gets its own zeroed
|
||||
16 KiB privilege stack; the previous TSS stack is restored before that
|
||||
allocation is released. Tests verify selector values, TSS offsets/base/limit,
|
||||
full-width stack replacement, alignment, DPL3 gates, IST, and gate type.
|
||||
- `bob64/interrupts.S` contains 64-bit stubs for CPU exception vectors 0-31,
|
||||
normalizing hardware error-code and no-error-code frames before saving all
|
||||
general-purpose registers and calling the Microsoft x64 C dispatcher. The
|
||||
common path restores registers and uses `iretq`. `interrupts.c` wires an IDT
|
||||
to those stubs and a fatal fallback, and prints full 64-bit register values
|
||||
over COM1 and the framebuffer before halting. The opt-in handoff loads the
|
||||
IDT. The DPL3 vector `0x80` enters a dedicated syscall stub; runtime
|
||||
exception and syscall delivery still need firmware/emulator testing.
|
||||
- `bob64/kernel.c` is the first kernel-owned C entry point. It checks the
|
||||
boot-information structure, active CR3, memory-map range, and stack, then
|
||||
reports the 64-bit root and map details, checks the growable kernel heap, then
|
||||
starts the polled shell. The filesystem and shell are still bring-up services,
|
||||
not yet a general-purpose OS.
|
||||
- `bob64/handoff.S` provides the Microsoft x64 ABI entry bridge: interrupts are
|
||||
disabled, the kernel GDT is loaded and CS reloaded, the IDT is loaded, NXE
|
||||
and CR0.WP are enabled when supported, the TSS is loaded, CR3 is switched, and execution moves
|
||||
to the replacement stack before calling the kernel. The EFI boot path calls
|
||||
`ExitBootServices` using a freshly acquired map key, retrying a stale key up
|
||||
to three times.
|
||||
- The handoff is opt-in so the original EFI probe stays available:
|
||||
`build-tool --bob64-handoff` emits a distinct image and
|
||||
`build-tool --bob64-handoff-test` runs host PE checks against it. Those checks
|
||||
cannot prove the privileged transition works on real firmware.
|
||||
- The handoff queries UEFI GOP and maps a supported RGB/BGR framebuffer into
|
||||
the new address space as writable, non-executable, uncached memory. The
|
||||
kernel's `bob64/console.c` draws a compact 5x7 text font, wraps and scrolls,
|
||||
and mirrors output to COM1. Unsupported or invalid GOP modes retain the serial
|
||||
console fallback. Host tests exercise format encoding, glyph output, and
|
||||
invalid framebuffer bounds; actual display output still needs UEFI testing.
|
||||
- `bob64/heap.c` provides a 16-byte-aligned, coalescing kernel heap with
|
||||
`alloc`, `calloc`, and `free`. Kernel entry adopts the page allocator and
|
||||
page-table pool seeded by boot, then grows the heap by mapping physical 4 KiB
|
||||
pages into a 64 MiB high-half range at `0xffff900000000000`. New pages are
|
||||
zeroed before use. Kernel entry smoke-tests multi-page allocations, alignment,
|
||||
zeroing, writes, frees, and double-free rejection. Host tests cover splitting,
|
||||
coalescing, overflow, and invalid frees. This early heap is single-core and
|
||||
does not reclaim empty pages yet.
|
||||
- `bob64/keyboard.c` decodes PS/2 set-1 input, including shift, caps lock,
|
||||
editing keys, and Pause/extended sequences. IRQ1 now feeds a bounded 64-event
|
||||
queue used by the shell and app event service after the kernel remaps the PIC;
|
||||
the kernel keeps polling as a fallback if the controller is unavailable.
|
||||
IRQ12 feeds a bounded mouse-event queue through the same app event service;
|
||||
COM1 remains polled. Unit tests cover scan-code state, keyboard/mouse queue
|
||||
behavior, and shell command/edit behavior. A 100 Hz PIT IRQ now supplies a
|
||||
monotonic tick counter through the versioned syscall ABI. USB keyboards,
|
||||
history and completion remain future work.
|
||||
- `bob64/filesystem.c` adds a flat, volatile binary-safe filesystem backed by the
|
||||
kernel heap. It supports 64-bit lengths, case-sensitive names, atomic file
|
||||
replacement, listing, reads, and deletion; names reject path separators and
|
||||
characters outside the safe filename set. The shell exposes `ls`, `cat NAME`,
|
||||
`write NAME TEXT`, and `rm NAME`. Host tests cover replacement, invalid names,
|
||||
binary NUL round-trips, and shell workflows.
|
||||
- `bob64/snapshot.c` defines B64S version 1 as a pointer-free little-endian
|
||||
format with 64-bit total/data lengths and a CRC-32. Restore validates version,
|
||||
size, checksum, record bounds, names, and duplicate files before replacing
|
||||
the live filesystem. The shell's `save` and `restore` commands keep one
|
||||
checkpoint in the kernel heap for the current boot session; it is lost on
|
||||
reboot. Host tests cover round-trip, empty files, replace-on-restore,
|
||||
truncation, unsupported versions, checksum errors, and unchanged state after
|
||||
rejected input. Disk persistence and directories remain future stages; the
|
||||
app filesystem ABI supports bounded whole-file operations and ABI v10 streaming
|
||||
handles with 64-bit seek positions and bounded reads/writes; hardware-backed
|
||||
persistence remains outstanding.
|
||||
- `bob64/exec.c` defines B64E version 1, a flat position-independent 64-bit
|
||||
executable image with a versioned ABI, exact payload length, 64-bit memory
|
||||
size and entry offset, page-aligned code/data boundary, payload CRC-32, and
|
||||
zero-required reserved fields. The shared parser rejects malformed/truncated
|
||||
images before returning a view; a contiguous copy helper preflights capacity
|
||||
and address overflow, copies the image, clears the memory-only tail, and
|
||||
preserves entry addresses above 4 GiB. Mapped application loading is provided
|
||||
separately by `process.c`. A synthetic B64E app now runs at CPL3, writes
|
||||
`bob!` through syscall v2, performs a bounded RAM-file round trip, and exits
|
||||
back to the saved kernel stack.
|
||||
- `bob64/abi.h` starts application ABI v1 on the same Microsoft x64 calling
|
||||
convention used by the UEFI kernel: integer/pointer arguments in RCX, RDX,
|
||||
R8, and R9; scalar status in RAX; 32-byte shadow space; 16-byte call-site
|
||||
stack alignment; and no red zone. Entry receives one pointer to a fixed
|
||||
32-byte startup record containing a 64-bit argument count and argv pointer.
|
||||
The record and its strings are app-space data, so the contract does not pass
|
||||
kernel pointers. Tests check the record layout, entry call, nested calls, and
|
||||
stack-passed arguments. Syscall ABI v10 defines an ABI query, character and
|
||||
bounded buffer output, file reads and writes, pixel-display query/present,
|
||||
blocking keyboard and PS/2 mouse events, and process exit through interrupt
|
||||
vector `0x80`; user pointers are validated
|
||||
against the active process root before buffer reads or writes. Display apps
|
||||
submit a packed 0x00RRGGBB frame matching GOP dimensions; the kernel copies
|
||||
bounded chunks into the device surface without exposing its address. Tests
|
||||
cover the syscall and both GOP channel formats.
|
||||
`apps/bob64_display.c` exercises the app-facing wrapper and is packaged as a
|
||||
B64E image with a bounded 1024x768 static surface; runtime execution awaits
|
||||
UEFI verification.
|
||||
- `bob64/window.h` ports the reusable window-manager behavior to app-owned
|
||||
fixed-capacity 64-bit state: nonzero 64-bit handles, full-width context
|
||||
pointers, visibility, focus, z-order, hit testing, title-bar dragging,
|
||||
clamping, dirty redraws, and keyboard/mouse event routing to window-local
|
||||
coordinates. Host tests exercise overlap redraw, wheel routing, focus and
|
||||
pointer values above 4 GiB. `apps/bob64_gui.c` is the first native desktop
|
||||
on this manager. It opens a named RAM text file (or `notes.txt` by default),
|
||||
lists RAM files in a separate window, supports selection/open/refresh and
|
||||
confirmed deletion, plus insertion, line breaks, cursor movement, click
|
||||
placement, scrolling, Ctrl+S save and an unsaved-exit prompt. It validates flat
|
||||
filenames and protects an existing file over the current 4 KiB syscall limit
|
||||
from accidental overwrite. The shell launches it with
|
||||
`run desktop.b64e [filename]`; host tests cover the editor buffer, packaged
|
||||
UI strings, file ABI and window manager. The full existing bob GUI, a file
|
||||
picker and real UEFI interaction remain to be ported/verified.
|
||||
- `bob64/ABI.md` records the register-preservation rules, stack alignment and
|
||||
shadow-space contract, pointer ownership, and application entry shape. The
|
||||
compiler's aggregate behavior follows the Microsoft x64 ABI; aggregate
|
||||
returns are not part of the application-entry contract. `bob64/app.h` exposes
|
||||
syscall wrappers for native C apps without kernel-internal types. The small
|
||||
`bob64/libc.c` runtime provides memory and string operations with 64-bit sizes.
|
||||
- `bob64/compiler.c` is the first resident x86-64 code-generation stage. The
|
||||
shell exposes `cc bob.c [OUTPUT]`, which packages the accepted source directly
|
||||
as B64E; `run app.b64e` launches it. The current syntax accepts `int` or
|
||||
`long`, `long long`, or `int main(void)`, initialized `int`/`long`/`long long`
|
||||
locals and assignments,
|
||||
bounded `bob64_app_write` calls with string literals, and 64-bit integer
|
||||
return expressions with parentheses, unary minus, addition, subtraction, and
|
||||
multiplication. Its frame and entry wrapper follow the Microsoft x64 stack
|
||||
contract; syscall ABI v10 provides exit, graphics output, whole-file and
|
||||
streaming file I/O/list/delete,
|
||||
and input.
|
||||
The compiler recognizes `usize`/`uintptr_t` as unsigned 64-bit scalar types
|
||||
and `isize`/`intptr_t` as signed 64-bit scalar types in declarations and
|
||||
function signatures. These are built-in type names; typedefs and header
|
||||
inclusion remain unsupported. `usize *`, `uintptr_t *`, `isize *`,
|
||||
`intptr_t *`, and `long long *` map to signed/unsigned wide-pointer types with
|
||||
eight-byte loads, stores, indexing and scaled pointer arithmetic. They work as local,
|
||||
parameter, return, global, and struct-field types; global pointers may target
|
||||
matching scalar objects. Fixed-size signed and unsigned 64-bit arrays now
|
||||
support local and global storage, initialization, indexing, mutation, array
|
||||
parameter decay, and eight-byte element addressing. Local arrays are limited
|
||||
to 16 elements by the fixed function frame; global arrays share the 4 KiB data
|
||||
page.
|
||||
Function declarations and definitions can return `char *`, `short *`, `int *`,
|
||||
and pointers to declared structs. Returned pointers keep all 64 bits; return
|
||||
expressions must match the declared pointee type. Returning a pointer through
|
||||
`long long`/`usize` remains accepted for the compiler's existing raw-address
|
||||
tests. Host execution tests cover pointer identity through a prototype and a
|
||||
returned string literal used by the caller.
|
||||
- `bob64/process.c` adds a callback-backed B64E loader core. It reparses the
|
||||
exact file before allocation, maps up to 16 MiB of app memory at
|
||||
`0x0000004000000000`, keeps code user-readable/executable and read-only, and
|
||||
maps data, BSS, and a 64 KiB stack writable/user/NX. It leaves an unmapped
|
||||
guard page below the stack, builds a 64-bit argv array and startup record in
|
||||
app memory, and prepares an ABI-aligned entry stack with shadow space. Failed
|
||||
loads roll back mappings and frames; unload removes each mapping before
|
||||
returning its physical frame. Host tests use physical frames above 4 GiB and
|
||||
verify argument contents, permissions, zero-filled BSS, guard placement, and
|
||||
rollback. The kernel wires these callbacks to its real page allocator and a
|
||||
private cloned root with a 34 MiB isolated app arena. At boot, the synthetic
|
||||
user app prints `bob!` and exits through the controlled syscall path.
|
||||
The shell's `run NAME [ARG ...]` command now reads B64E files from the RAM
|
||||
filesystem and launches them with app-owned arguments; `bob.b64e` is seeded
|
||||
as an example. General app services and persistent storage remain ahead.
|
||||
- `build-tool --bob64` builds only the new EFI image. `build-tool --bob64-test`
|
||||
also validates the PE machine, PE32+ header, EFI application subsystem,
|
||||
64-bit type sizes, synthetic pointer arithmetic above 4 GiB, and the presence
|
||||
of base relocations for firmware-selected load addresses. It also exercises
|
||||
four-level mapping, translation, permissions, canonical-address checks,
|
||||
physical-width limits in both allocator and page tables, multi-page range
|
||||
mapping, protect/unmap/remap behavior, duplicate-map rejection, bootstrap identity mappings, synthetic
|
||||
CPUID feature decoding, 64-bit GDT/IDT layouts, and exception-stub wiring.
|
||||
|
||||
## Still required by the migration goal
|
||||
|
||||
- [x] Boot the handoff image under x64 UEFI emulation. QEMU/OVMF verified the
|
||||
long-mode entry, `ExitBootServices`, owned CR3, kernel heap, framebuffer
|
||||
console, COM1 diagnostics, ring-3 smoke app, and shell. A runtime script
|
||||
repeats the boot and checks its serial milestones.
|
||||
- [x] Exercise ring-3 syscalls and user exception recovery after loading the
|
||||
GDT/IDT and new CR3. A deliberate invalid opcode was diagnosed with the full
|
||||
register frame and returned to the kernel; the corrected smoke app now exits
|
||||
normally. The IDT now also contains PIT, PS/2 keyboard, and PS/2 mouse IRQ
|
||||
handlers; runtime IRQ-path verification remains pending below.
|
||||
- [x] Verify actual ring-3 text protection and data NX behavior. QEMU runtime
|
||||
probes attempt to write the read-only executable page and execute the NX data
|
||||
page; both receive the expected user page-fault error bits and return to the
|
||||
kernel. The kernel also checks that the stack guard is unmapped.
|
||||
- [ ] Add dynamic page-table-pool growth, heap locking, and reclamation of empty
|
||||
heap pages. The bootstrap identity map favors bring-up simplicity.
|
||||
- [x] Verify GOP, COM1, PS/2 keyboard, and mouse input under UEFI emulation.
|
||||
QEMU showed mouse movement and a click selecting a file-list row; keyboard
|
||||
input launched/closed the desktop and created a third window.
|
||||
- [ ] Verify the new IRQ1 keyboard and IRQ12 mouse paths under UEFI emulation.
|
||||
Host tests cover the IDT gates and bounded event queues; QEMU verification is
|
||||
pending.
|
||||
- [x] Add a 100 Hz PIT timer IRQ, tick counter, and user tick query. The timer
|
||||
tick path is covered by host syscall tests; runtime QEMU verification remains
|
||||
pending alongside keyboard/mouse IRQ checks.
|
||||
- [ ] Add USB keyboard support and command history/completion. COM1 remains
|
||||
polled.
|
||||
- [ ] Add persistent storage for B64S snapshots. ABI v10 now supplies bounded
|
||||
handle-based streaming reads/writes, 64-bit absolute seeks, create/truncate/
|
||||
append modes, and per-app handle cleanup; physical persistence remains open.
|
||||
- [ ] Port remaining device services and add USB keyboard support.
|
||||
- [x] Add typed pointer returns to the resident x86-64 compiler for
|
||||
`char *`, `short *`, `int *`, and declared struct pointers. Tests cover
|
||||
prototype calls, string literal and struct pointer returns, and rejection of
|
||||
incompatible pointee types.
|
||||
- [x] Add `void` helper functions and scalar `char` returns to the resident
|
||||
compiler. Void helpers accept explicit `return;` or fall through, can be called
|
||||
as statements, and are rejected in value contexts. Scalar `char` returns
|
||||
sign-extend from eight bits; main remains required to return a value.
|
||||
- [x] Add typed pointers to `usize`/`uintptr_t` and `isize`/`intptr_t` values.
|
||||
Local/global/struct-field storage, parameters, returns, dereference, indexing,
|
||||
assignment, and 8-byte-scaled arithmetic are covered, including synthetic
|
||||
pointer values above 4 GiB.
|
||||
- [x] Add fixed signed and unsigned 64-bit arrays with local/global storage,
|
||||
initialization, indexed reads/writes, and array-parameter decay. Local arrays
|
||||
are bounded to 16 elements and global data to the existing 4 KiB page.
|
||||
File-scope `short`, `int`, `long`, `char`, and `long long` scalars plus bounded
|
||||
fixed `short`/`int`/`char` arrays now use initialized writable B64E data and
|
||||
RIP-relative x64 access across functions. Global `short *`/`int *`/`char *`
|
||||
initializers may target
|
||||
previously declared arrays or string literals. Named structs define aligned
|
||||
scalar/pointer layouts and support local/global instances plus `.`/`->` field
|
||||
loads/stores. Struct arrays, nested structs, typedefs, and multiple translation
|
||||
units remain unsupported. Limits are 8 struct types, 16 fields per type, 16
|
||||
global objects, and the single 4 KiB data page.
|
||||
Local fixed `short`/`int` arrays, `short *`/`int *` locals,
|
||||
dereference/indexing, scaled pointer arithmetic and pointer differences, and
|
||||
local brace initializers are
|
||||
implemented. `short` (16-bit), `int`/`long` (32-bit), and `long long`
|
||||
(64-bit) helper functions and matching prototypes before or after `main`
|
||||
support nested/forward
|
||||
calls with up to sixteen scalar, `short *`/array, `int *`/array, `char *`,
|
||||
`usize *`, `isize *`, or struct-pointer parameters, following the Microsoft
|
||||
x64 register and stack argument layout.
|
||||
Compound blocks and `for` initializers now have lexical local scopes with
|
||||
shadowing and stack-slot reuse after scope exit.
|
||||
NUL-terminated string
|
||||
literals, signed 8-bit `char` locals/parameters, escaped character constants,
|
||||
byte-scaled `char *` indexing, stores, dereference, and arithmetic, plus local
|
||||
`char` arrays with string or brace initializers, now support resident C string
|
||||
traversal and mutable text buffers. Struct pointer parameters can be passed
|
||||
through helper calls using the Microsoft x64 argument ABI; helpers can read
|
||||
and write fields through `->`.
|
||||
`if`/`else` and `while` support signed
|
||||
relational/equality comparisons, and expressions support unary `!` plus
|
||||
short-circuit `&&`/`||`. Basic `for` loops now emit initialization, condition,
|
||||
body, and scalar assignment update code. `break` and `continue` patch to the
|
||||
nearest loop; `for` continue enters its update clause. Early `return`
|
||||
statements work inside branches and loops; the subset still requires a final
|
||||
return at the end of each function.
|
||||
- [x] Add a kernel-owned per-app window manager and port the desktop's file and
|
||||
editor windows to its surfaces. Syscall ABI v10 creates, focuses, destroys,
|
||||
validates and copies app surfaces, composites z-order, routes input with
|
||||
64-bit handles and local/screen coordinates, and releases the session on app
|
||||
exit. Concurrent apps are still not displayed together.
|
||||
- [x] Run the native desktop under QEMU/OVMF at 1280x800. Both managed windows
|
||||
rendered; keyboard input created a third window, Escape returned to the
|
||||
shell, and Ctrl+S saved editor text through the file syscall. The full screen
|
||||
and B64S shell commands were also exercised in the same UEFI session.
|
||||
- [ ] Port the remaining applications to the kernel window API. Syscall ABI v10
|
||||
also provides bounded file reads/writes/list/delete, console I/O,
|
||||
full-screen presentation, blocking PS/2 keyboard/mouse events, ABI query, and
|
||||
process exit. The host `bob64cc`
|
||||
bridge continues to package the broader C subset supported by GCC.
|
||||
- [ ] Port the remaining existing applications and full GUI/widget behavior;
|
||||
the current native text editor is an initial, limited desktop milestone.
|
||||
- [x] Run the kernel-generated ring-3 `bob!` app under x64 UEFI emulation. The
|
||||
resident compiler also compiled and launched `bob.c`; B64S `save`/`restore`
|
||||
recovered a deleted file, and the native GUI opened and saved an editor file.
|
||||
- [ ] Complete the full acceptance flow and add runtime tests for broader
|
||||
calling-convention/stack cases, hardware interrupts, mouse input, and
|
||||
persistent B64S storage. The ring-3 app image runs at a virtual address above
|
||||
4 GiB; host tests also cover synthetic high addresses and broad ABI/memory
|
||||
cases.
|
||||
- [x] Verify bob64 boots in x64 UEFI emulation and performs its own kernel
|
||||
initialization without executing 32-bit kernel or app code. The broader
|
||||
migration remains active: the resident C subset, devices, persistence, and
|
||||
existing application ports still need work.
|
||||
|
||||
## Build and test
|
||||
|
||||
```text
|
||||
build-tool --bob64
|
||||
build-tool --bob64-test
|
||||
build-tool --bob64-handoff
|
||||
build-tool --bob64-handoff-test
|
||||
tools/test_bob64_qemu.ps1 -QemuPath <qemu-system-x86_64.exe> -OvmfCodePath <edk2-x86_64-code.fd>
|
||||
```
|
||||
|
||||
The safe output goes to `build/bob64/EFI/BOOT/BOOTX64.EFI`; the opt-in handoff
|
||||
image goes to `build/bob64-handoff/EFI/BOOT/BOOTX64.EFI`. Host tests validate
|
||||
the PE/COFF architecture and subsystem, 64-bit pointers, synthetic addresses
|
||||
above 4 GiB, memory-map descriptor strides, page allocation/coalescing,
|
||||
allocation-ledger capacity, invalid free handling and overflow checks. The
|
||||
PowerShell QEMU test performs a real OVMF boot of the handoff image and checks
|
||||
serial markers through the kernel shell; it needs the QEMU executable and
|
||||
`edk2-x86_64-code.fd` paths supplied by the caller. The full script does not
|
||||
replace testing on physical UEFI hardware.
|
||||
|
||||
## Memory layout boundary
|
||||
|
||||
The current owned paging stage uses four-level tables. The image, bootstrap
|
||||
stack, table pool, memory map, and supported GOP framebuffer are mapped at
|
||||
identity addresses in the lower canonical half. Physical addresses below 1 MiB
|
||||
remain reserved. The early heap occupies a 64 MiB window beginning at
|
||||
`0xffff900000000000`. The B64E loader reserves a lower-half user image arena of
|
||||
16 MiB beginning at `0x0000004000000000`; its 64 KiB user stack begins at
|
||||
`0x0000004002001000`, with an unmapped guard page at `0x0000004002000000`.
|
||||
The kernel smoke test clones the active root, privately copies the page-table
|
||||
branch covering a 34 MiB image-and-stack arena, clears stale mappings in that
|
||||
arena, and switches CR3 before loading and unloading a synthetic app. Other
|
||||
kernel mappings remain shared. The kernel enters the synthetic app at CPL3
|
||||
using an `iretq` frame. The app can query the syscall ABI, print characters
|
||||
through `int 0x80`, and exit through a controlled return to the saved kernel
|
||||
stack. The user-entry bridge enables interrupts for apps and restores the
|
||||
caller's prior IF state when the app exits. The boot smoke app checks that the
|
||||
keyboard IRQ path remains enabled after a user process returns. The versioned
|
||||
syscall ABI also includes file handles and window services.
|
||||
The fallback kernel privilege stack and each app's dedicated 16 KiB interrupt
|
||||
stack are allocated from the supervisor-only heap. App runs also push a bounded
|
||||
syscall context that preserves the parent's callbacks, user page table, scratch
|
||||
buffers, and file handles; each app owns a separately allocated window-server
|
||||
session. The user-entry return bridge still uses singleton state, so nested app
|
||||
execution is not enabled yet.
|
||||
The volatile
|
||||
filesystem and B64S checkpoint live in the kernel heap; there is no full
|
||||
physical direct map or filesystem mapping.
|
||||
@@ -583,3 +583,55 @@ The bob32 resident compiler now accepts one-dimensional array parameters, adjust
|
||||
Started the app-side standard library with `kernel/bob_string.h`: basic string operations, whitespace detection, overflow-checked signed decimal/hex parsing, bounded integer formatting and quote-aware in-place tokenization. Runtime tests exercise edge cases in bob32, and a compiled app using the header is imported, launched, snapshotted, restored and run again from the bob32 filesystem. Full suites: CPU 203, OS/compiler 1,840, console 28.
|
||||
|
||||
Native bob32 apps can now use `int main(int argc, char **argv)`. The OS shell accepts quoted arguments after an imported app name, preserves empty strings and backslash escapes, and supplies the guest filename as `argv[0]`. A compiled app checks its argument count and values—including a word with spaces and an empty argument—through the real import/run path. Full suites: CPU 203, OS/compiler 1,844, console 28.
|
||||
|
||||
Added a version 1 native OS service through `bob_fs.h` for filesystem metadata and text operations, plus basic memory/filesystem system information. Added native `echo`, `ls`, `cat`, `sysinfo`, and `notes` examples. Integration tests exercise the utilities, create a note, save a B32S snapshot, restore it in a new emulator process, then read and delete it. Full suites: CPU 203, OS/compiler 1,874, console 28.
|
||||
|
||||
Added a version 1 graphics and input boundary through `bob_gfx.h` and `bob_event.h`. The terminal backend provides an 80x25 double-buffered character-cell surface with colors, pixels, rectangles, lines, text and transparent bitmap-cell blits. Blocking event wait delivers typed characters and special key presses, with release/mouse event types reserved. The graphics demo draws, waits for a test key, leaves graphics mode and returns to the shell. Full suites: CPU 203, OS/compiler 1,880, console 28.
|
||||
|
||||
## bob64 user pixel-surface milestone
|
||||
|
||||
bob64 syscall ABI v3 adds a display query and a protected full-screen surface present call. Apps submit packed 0x00RRGGBB pixels; the kernel validates the entire range in the isolated user page table, then copies in 1024-pixel chunks and converts channels for GOP RGB/BGR modes without exposing the device pointer. bob64_app_get_display and bob64_app_present wrap the services. The new apps/bob64_display.c demo paints a bounded 1024x768 gradient and writes bob!; build/test parses its B64E image. Tests verify dimensions, both GOP channel layouts, invalid mappings and size mismatches. build-tool --bob64-test and --bob64-handoff-test both pass. Actual display presentation remains unverified until UEFI runtime testing.
|
||||
## bob64 app input-event milestone
|
||||
|
||||
Syscall ABI v5 defines a fixed 44-byte BOB64_EVENT and blocking app-owned input delivery. The PS/2 set-1 decoder emits key-down/up events, ASCII characters, Shift/Caps/Control/Alt state and extended key identities while preserving shell input. A bounded PS/2 mouse driver decodes movement, button transitions, IntelliMouse wheel packets and extended buttons, clamps coordinates to the framebuffer, and routes events through the same validated app buffer. apps/bob64_display.c stays on screen until Escape. Host tests cover keyboard modifiers, mouse packet signs/clamping/buttons/wheel, syscall delivery and invalid user pointers. Both bob64 host suites pass; UEFI device execution remains unverified.
|
||||
|
||||
## bob64 user-space window-manager milestone
|
||||
|
||||
Added bob64/window.h as a 64-bit-clean app-owned port of the existing fixed-capacity window manager. It stores 64-bit handles and context pointers, preserves focus/z-order/visibility and dirty-redraw behavior, hit-tests and clamps windows, supports title-bar dragging, and routes keyboard, mouse, and wheel events in local coordinates. Tests exercise overlapping redraws, hidden-window focus, drag/release behavior, wheel routing, stale handles, and synthetic app pointers/handles above 4 GiB. bob64 graphics and handoff test suites both pass and print bob!. The existing desktop application and widget drawing layer still need porting and UEFI runtime verification.
|
||||
|
||||
## bob64 native desktop editor milestone
|
||||
|
||||
Expanded `apps/bob64_gui.c` from a windowing demo into a small usable desktop app. It launches from the shell as `run desktop.b64e [filename]`, defaults to `notes.txt`, and supports mouse cursor placement, keyboard insertion, Backspace/Delete, arrow-key movement, newline insertion, viewport scrolling, Ctrl+S saves and a two-Escape unsaved-exit prompt through syscall ABI v5. Filenames are validated against the flat filesystem's allowed set. Raised the bounded whole-file console/file syscall buffer to 4 KiB and moved its transfer scratch into kernel static storage to keep the 16 KiB privilege stack clear. Added `bob64/editor.h` for a bounded 4 KiB editing buffer and host regression tests for 4 KiB syscall read/write across page boundaries, user-range validation, insertion, deletion, movement, wrapping and line handling. Files over the current syscall buffer limit cannot be overwritten by this app. The generated app is embedded in the UEFI image and installed as `desktop.b64e`; both `--bob64-test` and `--bob64-handoff-test` pass and print `bob!`. Actual UEFI input/display and the full existing GUI port remain unverified.
|
||||
|
||||
The resident bob64 compiler now supports fixed local `int` arrays, `int *`
|
||||
locals, array decay, address-of/dereference, indexed loads/stores, and scaled
|
||||
pointer addition/subtraction. It rejects pointer multiplication and mismatched
|
||||
pointer assignments/initializers. Runtime tests execute generated code for
|
||||
array indexing, both pointer-addition operand orders, 4-byte element scaling,
|
||||
pointer differences and a stack pointer above 4 GiB; negative tests check
|
||||
invalid pointer arithmetic and assignment. Local arrays also accept scalar
|
||||
brace initializers with trailing commas and zero-fill for omitted elements;
|
||||
excess elements are rejected. Integer and `long long` helper functions may
|
||||
appear before or after `main`, with forward and nested calls using up to eight
|
||||
parameters. The first four use Microsoft x64 argument registers and later ones
|
||||
use the caller's stack area; scalar and `int *`/array parameters are stored in
|
||||
function-local stack slots, and array parameters support indexing. Tests cover
|
||||
generated-code execution for pre-main definitions, 64-bit helper returns, array
|
||||
parameters, nested calls, all four argument registers, stack-passed scalar and
|
||||
pointer arguments, argument-count rejection, and the established `bob!` smoke
|
||||
path. Function prototypes now contribute signatures during a top-level pass;
|
||||
definitions must match their return type and parameter count/types, and calls
|
||||
to declarations without definitions are rejected. Tests cover unnamed prototype
|
||||
parameters, 64-bit prototype returns, and prototype/definition conflicts. The
|
||||
statement parser now emits tested
|
||||
`if`/`else` and `while` branches, and signed integer comparisons for `==`, `!=`,
|
||||
`<`, `<=`, `>`, and `>=`; braced blocks share one function namespace. Unary
|
||||
`!` and short-circuit `&&`/`||` are supported, with regression tests proving
|
||||
skipped branches do not execute pointer-mutating calls. Lexical scopes and
|
||||
return types other than `int` or `long long` remain unsupported.
|
||||
C-style `for` loops now support optional
|
||||
initialization/condition clauses and a scalar assignment update. Nested loop
|
||||
contexts patch `break` to the nearest exit and `continue` to the while condition
|
||||
or for-update block; tests exercise nested targets and reject either statement
|
||||
outside a loop. Conditional early returns emit the function epilogue and
|
||||
are tested with a signed absolute-value helper.
|
||||
@@ -47,6 +47,85 @@ name and `argc` includes it. Pass arguments with `run myapp first "two words"`;
|
||||
quotes group spaces and backslash escapes the next character. Empty quoted
|
||||
arguments are preserved. This applies to imported guest files; direct host-path
|
||||
`run32` launches currently start without command-line arguments.
|
||||
|
||||
Native applications can use `bob_fs.h` for guest RAM files. Its version 1
|
||||
service supports listing names/kinds/sizes, direct kind lookup by filename,
|
||||
reading and writing text files and
|
||||
raw bob16/bob32 program words, and deleting files. Text writes are bounded to
|
||||
the text-file limit; binary writes accept only program kinds. Native B32K apps
|
||||
must enter storage through validated import. The OS keeps filesystem tables
|
||||
private to the kernel. See [the native app examples](apps/README.md)
|
||||
for `echo`, `ls`, `cat`, `sysinfo`, and the snapshot-friendly `notes` app.
|
||||
`launcher` lists stored native bob32 applications and runs one with arguments;
|
||||
native apps can use `bob_process.h` to launch another stored app and receive its
|
||||
exit code. The emulator preserves the suspended app's memory while a child runs.
|
||||
|
||||
`bob_memory.h` provides a small caller-owned word arena for temporary app data.
|
||||
Give it an integer buffer, allocate in target words, inspect used/remaining space,
|
||||
and reset it for reuse. Allocation returns null for invalid requests or when the
|
||||
buffer is full; it reserves no global OS heap.
|
||||
|
||||
Native apps can include `bob_time.h` to read UTC seconds through the versioned
|
||||
OS-service boundary. The result is returned as low and high 32-bit words.
|
||||
`bob_system.h` reports the system-service version, cell-framebuffer presence
|
||||
and size, and whether keyboard and mouse input are available. `sysinfo` displays
|
||||
these device capabilities alongside the filesystem and application-memory
|
||||
usage.
|
||||
For convenience, `bob_native.h` includes the common string, memory, filesystem,
|
||||
process, time, system-capability, and input-event APIs. Add `bob_gfx.h` and
|
||||
`bob_gui.h` separately when building graphical apps.
|
||||
|
||||
`bob_gfx.h` provides the first graphics abstraction: apps draw into an 80x25
|
||||
cell framebuffer, then present it through the emulator’s terminal backend.
|
||||
The API includes resolution, pixels, rectangles, lines, text, transparent
|
||||
bitmap cells with per-cell foreground colors, clear, present and leave.
|
||||
`bob_font.h` adds a 5x7 bitmap text renderer for uppercase letters, digits,
|
||||
space, and common punctuation.
|
||||
`apps/graphics_demo.c` draws a sample
|
||||
screen, waits for a key through `bob_event_wait`, and returns to the shell.
|
||||
The GUI demo's Window B includes a keyboard- and mouse-driven native app
|
||||
launcher; it runs stored apps through `bob_process.h` and shows their exit status.
|
||||
Press `?` for a bitmap-font help panel; Escape or its Close button returns to
|
||||
the desktop.
|
||||
Event version 1 delivers character and special-key down/up events. On Windows
|
||||
console input it also delivers mouse movement and button transitions with
|
||||
screen-cell coordinates, plus signed mouse-wheel deltas. `bob_event_wait`
|
||||
blocks; `bob_event_poll` checks the console queue without blocking. Redirected
|
||||
input remains character based and is consumed by the blocking path. This
|
||||
cell-based backend establishes the app boundary before adding a true pixel
|
||||
surface.
|
||||
`bob_event_queue.h` provides a caller-owned FIFO for buffering these events;
|
||||
overflow is reported without overwriting queued input.
|
||||
`bob_wm.h` provides the reusable bob32 window manager. Applications give it fixed
|
||||
arrays for window records and stacking order; it owns allocation, visibility,
|
||||
focus, z-order, hit testing, title-bar dragging, event routing, and dirty-window
|
||||
tracking. `bob_wm_dispatch` returns the window ID for an event, routes keyboard
|
||||
input only to the focused visible window, and rewrites mouse coordinates to be
|
||||
relative to the recipient. `bob_wm_begin_draw` and `bob_wm_next_dirty` return
|
||||
visible dirty windows in stacking order; moving, hiding, raising, or destroying
|
||||
a window requests a safe full redraw, while content invalidation marks the
|
||||
affected window and overlaps. `bob_gui.h` adds reusable window, button,
|
||||
popup-menu, single-line text-field, and multiline text-area widgets.
|
||||
`apps/gui_demo.c` uses the manager for its editor and file-browser windows and
|
||||
draws only the dirty windows during normal interaction; modal help, launcher,
|
||||
and menu panels use full redraws. It draws a desktop
|
||||
with a multiline text editor and file browser. The editor starts with `new.txt`
|
||||
and `bob!`, supports mouse caret placement, insertion, deletion, Enter for new
|
||||
lines, arrow/Home/End navigation, vertical movement, mouse-wheel scrolling,
|
||||
and horizontal scrolling for long lines. Tab cycles through the filename field,
|
||||
text area, and file browser; Ctrl+S saves the current text file. Press `e` in
|
||||
the file browser to load the selected text file into the editor, then Ctrl+S to
|
||||
save changes. The browser immediately lists the saved file and can preview or
|
||||
delete text files with confirmation. Clicking a window raises it, dragging its
|
||||
title bar moves it, and Escape returns to the
|
||||
shell. Dragging is clamped to
|
||||
the screen edges. A clickable button in Window A focuses Window B. Window B lists guest filesystem entries and previews selected text files; use
|
||||
`n`/`p` or the mouse to change selection and Up/Down or `u`/`d` to scroll the
|
||||
preview. Press `x` to show Yes/Cancel controls; click one or press `y`/`n`.
|
||||
Window B also has a File popup opened with `m` or by clicking its title area;
|
||||
the menu supports keyboard and mouse selection to open or delete the selected
|
||||
text file, or close the popup. It follows Window B when dragged and clamps to
|
||||
the screen edges.
|
||||
Set `BOB16_TRACE_FAULT=1` before launching the emulator to log the address and
|
||||
instruction when a supervised application faults.
|
||||
The updated emulator also accepts `bob.exe --os` from that directory to boot
|
||||
@@ -119,14 +198,15 @@ In a native Windows console, the shell supplies editing and redraw itself:
|
||||
| Ctrl+D / Ctrl+Z | End input |
|
||||
|
||||
Completion operates on the word at the end of the line. Type more characters
|
||||
when matches are ambiguous. History is session-only, includes failed commands,
|
||||
when matches are ambiguous. The `history` builtin lists the same four recent
|
||||
commands. History is session-only, includes failed commands,
|
||||
and skips consecutive duplicates. `edit` opens its own full-screen view in a
|
||||
Windows console. Redirected input emits no
|
||||
redraw or candidate lists. Other terminals use ordinary input; full interactive
|
||||
key handling currently targets the native Windows console.
|
||||
|
||||
The RAM filesystem has eight slots and names up to 23 characters. bob16 keeps
|
||||
eight fixed 511-word slots. bob32 packs files into 4,096 words total; text and
|
||||
eight fixed 511-word slots. bob32 packs files into 8,192 words total; text and
|
||||
resident programs remain limited to 511 words, while native apps use six
|
||||
metadata words plus payload and a terminator, sharing space with other files.
|
||||
A character occupies one word. `bob.c` occupies one slot initially. Unsaved
|
||||
@@ -168,6 +248,8 @@ the parent directory must already exist. Messages mention this override.
|
||||
Restoring replaces **all** RAM files; use `save` first if current files matter.
|
||||
An invalid, truncated, corrupt or unreadable snapshot leaves RAM unchanged.
|
||||
The snapshot includes text and program files, not heap allocations or history.
|
||||
Current bob32 snapshots use B32S v3 for the 8,192-word filesystem; B32S v1
|
||||
fixed-slot and v2 packed snapshots remain readable and migrate on restore.
|
||||
|
||||
Native programs contain kernel helper addresses. If the kernel image differs
|
||||
from the one used to save, restore keeps text and omits binary programs.
|
||||
@@ -330,7 +412,7 @@ console/arithmetic routines and belong to the kernel build that compiled them.
|
||||
In bob32 mode the same syntax emits native 32-bit instructions and kind-2 RAM
|
||||
program files, which can be run with `run` and retained in B32S snapshots. B32
|
||||
resident programs start at `0x20000` and use variables at `0xF0000..0xF000F`;
|
||||
their output can use the remaining shared 4,096-word filesystem space. Source
|
||||
their output can use the remaining shared 8,192-word filesystem space. Source
|
||||
text files remain limited to 511 words. In bob16 mode files remain kind 1 and
|
||||
use 16-bit integers and the `0xA000` program region. The bob32 shell also runs
|
||||
kind-1 legacy programs at `0xC200`, clear of the expanded kernel image.
|
||||
@@ -376,8 +458,9 @@ what fits in a single command line; use the resident compiler for larger program
|
||||
| `0xA000..0xCFFF` | Loaded bob16 compatibility program at `0xC200..0xCFFF` |
|
||||
| `0xD000..0xDFFF` | bob32 heap and compatibility stack region |
|
||||
| `0xE000..0xEFFF` | Editor/compiler scratch, history and shell stack |
|
||||
| `0xF000..0xFFFF` | Packed bob32 RAM filesystem contents |
|
||||
| `0x10000..0x1FFFF` | Native bob32 kernel code, globals and strings |
|
||||
| `0xF000..0xFFFF` | bob16 file contents; bob32 scratch space |
|
||||
| `0x10000..0x1DFFF` | Native bob32 kernel code, globals and strings |
|
||||
| `0x1E000..0x1FFFF` | Protected packed bob32 filesystem contents |
|
||||
| `0x20000..0xEFFFF` | Supervised native bob32 program entry/code region |
|
||||
| `0xF0000..0xFFFFF` | Native app data and compiler variables; stack starts at `0x100000` |
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
CC ?= gcc
|
||||
BOB64_CC ?= x86_64-w64-mingw32-gcc
|
||||
CFLAGS ?= -std=gnu11 -O2 -Wall -Wextra -Werror
|
||||
.PHONY: all c-os test
|
||||
.PHONY: all c-os test bob64 bob64-test bob64-handoff bob64-handoff-test bob64cc bob64-app-test
|
||||
|
||||
all:
|
||||
$(CC) $(CFLAGS) tools/build.c -o build-tool
|
||||
@@ -11,3 +12,27 @@ c-os: all
|
||||
|
||||
test: all
|
||||
./build-tool --test
|
||||
|
||||
# x86-64 UEFI build, isolated from the bob16/bob32 emulator targets.
|
||||
bob64:
|
||||
$(CC) $(CFLAGS) tools/build.c -o build-tool
|
||||
BOB64_CC="$(BOB64_CC)" ./build-tool --bob64
|
||||
|
||||
bob64-test: bob64
|
||||
BOB64_CC="$(BOB64_CC)" ./build-tool --bob64-test
|
||||
|
||||
# Opt-in destructive-to-firmware-services kernel handoff build.
|
||||
bob64-handoff:
|
||||
$(CC) $(CFLAGS) tools/build.c -o build-tool
|
||||
BOB64_CC="$(BOB64_CC)" ./build-tool --bob64-handoff
|
||||
|
||||
bob64-handoff-test:
|
||||
$(CC) $(CFLAGS) tools/build.c -o build-tool
|
||||
BOB64_CC="$(BOB64_CC)" ./build-tool --bob64-handoff-test
|
||||
|
||||
bob64cc:
|
||||
$(CC) $(CFLAGS) tools/bob64cc.c -o bob64cc
|
||||
|
||||
bob64-app-test: bob64-test bob64cc
|
||||
BOB64_CC="$(BOB64_CC)" ./bob64cc apps/bob64_smoke.c build/bob64-app/smoke.b64e
|
||||
./build/test_bob64 build/bob64/EFI/BOOT/BOOTX64.EFI build/bob64-app/smoke.b64e
|
||||
@@ -6,6 +6,10 @@ regenerate BASM after editing the C kernel, or build the binary boot workflow.
|
||||
The OS has a shell, RAM files, allocation, program loading, and a resident C
|
||||
compiler. Its tools are written in C; no Python is required.
|
||||
|
||||
An experimental x86-64 UEFI target is built separately with `build-tool --bob64`;
|
||||
see [the bob64 migration status](BOB64_MIGRATION.md). It does not replace the
|
||||
existing custom-CPU bob16/bob32 emulator.
|
||||
|
||||
extremely simple custom 16 bit cpu emulator and assembler as seen on youtube: https://youtu.be/tlIqosU75CQ?is=ZAVWsYRDMPrUKOej \
|
||||
use at your own risk! code is thoroughly untested so if you find any bugs let me know asap so i can fix them asap
|
||||
|
||||
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
# Native bob32 applications
|
||||
|
||||
Build an application from the repository root:
|
||||
|
||||
```text
|
||||
gcc -E -P -nostdinc -undef -I kernel apps/notes.c -o build/notes.i
|
||||
build/bobcc build/notes.i build/notes.basm build/notes.b32 --wide-app
|
||||
```
|
||||
|
||||
Use the same two build commands with `apps/graphics_demo.c` and the
|
||||
`build/graphics_demo` output names to build the interactive canvas example.
|
||||
Import it once as `graphics`, then run `run graphics`; it waits for a key and
|
||||
returns to the shell.
|
||||
|
||||
Build `apps/gui_demo.c` the same way to try the desktop prototype. The larger
|
||||
editor starts with `new.txt` and `bob!` in a filename field and multiline text
|
||||
area. Click either field to place the caret, or use Tab to cycle through the
|
||||
filename, text-area, and file-browser focus. In the browser, select a text file
|
||||
and press `e` to load it; Ctrl+S saves the text back to the guest filesystem.
|
||||
Enter inserts a newline. Escape returns to the shell. On a Windows console,
|
||||
click a window to raise and focus it or drag its title bar to move it.
|
||||
`kernel/bob_wm.h` is the shared window manager used by the GUI demo. It owns
|
||||
fixed-capacity window records, focus, stacking, hit testing, title-bar drag
|
||||
capture, event routing, screen clamping, and dirty redraw tracking. Apps provide
|
||||
the manager's fixed storage arrays and use `bob_wm_dispatch` to route an event;
|
||||
the returned window ID identifies its recipient, and mouse coordinates in the
|
||||
routed event are window-local. Call `bob_wm_invalidate` when application content
|
||||
changes, then draw IDs returned by `bob_wm_next_dirty` in stacking order.
|
||||
`kernel/bob_gui.h` contains reusable window-frame, button, menu, single-line
|
||||
text-field, and multiline text-area widgets. Drawn windows have framed borders
|
||||
and a distinct title strip.
|
||||
The `bob_gui_button_draw` and `bob_gui_button_event` helpers provide a reusable
|
||||
clickable button with hover and pressed states. The demo button focuses Window
|
||||
B on a left click, and the bob32 test suite exercises hit-testing, dragging,
|
||||
left-button activation, and release-outside behavior with synthetic events.
|
||||
Overlapping-window hit-testing and raising are also tested.
|
||||
The text-field helpers support click-to-position, insertion, Backspace/Delete,
|
||||
arrow/Home/End navigation, caret drawing, and horizontal scrolling. The text
|
||||
area supports multiline insertion, vertical movement with column preservation,
|
||||
click-to-position, caret visibility, and mouse-wheel scrolling. Native bob32
|
||||
fixtures check text and cursor state, including wheel-scroll bounds.
|
||||
The popup menu has fixed-stride labels, keyboard selection, Enter/Escape, and
|
||||
mouse hover/click activation. Window B opens it from the File title area or
|
||||
with `m`; its actions open the selected text file, start delete confirmation,
|
||||
or close the menu. Popup placement follows Window B when it is dragged and
|
||||
clamps the menu inside the 80x25 screen; widget tests cover edge and invalid
|
||||
screen placements.
|
||||
Window B lists guest filesystem entries and previews the selected text file;
|
||||
`n`/`p` and mouse clicks change the selection, while Up/Down or `u`/`d` scroll
|
||||
the preview. On Windows, the mouse wheel scrolls the editor or preview and
|
||||
changes file selection when over the list. Press `x` to open an
|
||||
on-screen Yes/Cancel prompt; click a button
|
||||
or press `y`/`n` to confirm or cancel.
|
||||
The GUI integration test creates a long `gui.txt`, scrolls beyond the initial
|
||||
preview, checks a unique trailing marker, confirms deletion, and verifies the
|
||||
file can no longer be read. It also creates `new.txt` from the GUI, snapshots
|
||||
the guest filesystem, restores it in a second emulator process, and reads the
|
||||
saved contents with `cat`. A separate integration test loads a two-line text
|
||||
file, edits and saves it through the GUI, then checks the saved newline and text
|
||||
with `cat`.
|
||||
|
||||
Start the bob32 OS, import the image, and use it from the guest filesystem:
|
||||
|
||||
```text
|
||||
import32 build/notes.b32 notes
|
||||
run notes put journal "bob! a saved note"
|
||||
run notes edit journal "bob! updated note"
|
||||
run notes add journal "another line"
|
||||
run notes show journal
|
||||
ls
|
||||
save
|
||||
```
|
||||
|
||||
`notes edit NAME [TEXT]` creates or replaces a text note, while
|
||||
`notes add NAME [TEXT]` appends a line (or prompts for one). `notes` protects
|
||||
binary and executable files from note-specific commands. It also supports
|
||||
`run notes delete journal`. The `echo` app prints its
|
||||
arguments, `ls` lists guest files and their kinds/sizes, and `cat FILE` displays
|
||||
a text file. `sysinfo` reports application memory, filesystem usage, display
|
||||
dimensions, and keyboard/mouse availability. Import
|
||||
each image once; the application and its data are preserved by B32S snapshots.
|
||||
`cat FILE` preserves existing trailing newlines and only adds a line break when
|
||||
nonempty file contents have no final newline.
|
||||
|
||||
Build `apps/launcher.c` with the same commands to list stored native apps or
|
||||
start one with arguments. For example, `run launcher echo "a saved note"`
|
||||
starts `echo` as a child app and reports its exit code. Native apps can call
|
||||
`bob_app_run(name, arguments, &exit_code)` from `bob_process.h` directly.
|
||||
The GUI demo also has a small application-launcher panel: focus Window B and
|
||||
press `a`, choose a stored app with `n`/`p` or the arrow keys, and press `r` or
|
||||
click Launch. The desktop resumes and displays the child exit status.
|
||||
Press `?` for a bitmap-font help overlay with the desktop shortcuts; Escape or
|
||||
its Close button returns to the desktop. Launcher and help panels clear the
|
||||
desktop canvas behind them so their contents remain readable.
|
||||
|
||||
`graphics_demo` uses the version 1 `bob_gfx.h` canvas API. Its first backend is
|
||||
an 80x25 character-cell framebuffer with colors, filled rectangles, lines,
|
||||
text, transparent bitmap cells (including per-cell colors), and explicit presentation. The same app can
|
||||
later target a pixel renderer without changing its draw calls.
|
||||
Include `bob_font.h` when an app needs the opt-in 5x7 bitmap text renderer.
|
||||
The demo waits through `bob_event.h`, a blocking event interface that currently
|
||||
normalizes typed characters, special-key presses/releases, mouse movement, and
|
||||
mouse-button transitions when the Windows console provides those records.
|
||||
|
||||
Apps use `bob_fs.h` for guest file operations and `bob_string.h` for string and
|
||||
number helpers. The filesystem service has a versioned request protocol and
|
||||
keeps guest RAM tables private from application code.
|
||||
`bob_event.h` provides blocking wait and nonblocking poll operations, while
|
||||
`bob_event_queue.h` provides an optional caller-owned FIFO when an app needs to
|
||||
buffer or defer events. A full queue reports overflow without dropping an
|
||||
earlier event.
|
||||
@@ -0,0 +1,4 @@
|
||||
int main(void) {
|
||||
bob64_app_write("bob!", 4);
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
#include "../bob64/app.h"
|
||||
|
||||
#define DISPLAY_LIMIT_WIDTH 1024u
|
||||
#define DISPLAY_LIMIT_HEIGHT 768u
|
||||
|
||||
static u32 pixels[DISPLAY_LIMIT_WIDTH*DISPLAY_LIMIT_HEIGHT];
|
||||
|
||||
s64 bob64_app_main(const BOB64_APP_STARTUP *startup) {
|
||||
u32 width,height;
|
||||
BOB64_EVENT event;
|
||||
if(!startup||startup->AbiVersion!=BOB64_APP_ABI_VERSION||
|
||||
bob64_app_query_abi()!=BOB64_SYSCALL_ABI_VERSION||
|
||||
bob64_app_get_display(&width,&height))return -1;
|
||||
if(!width||!height||width>DISPLAY_LIMIT_WIDTH||height>DISPLAY_LIMIT_HEIGHT)
|
||||
return -2;
|
||||
for(u32 y=0;y<height;y++)for(u32 x=0;x<width;x++) {
|
||||
u32 red=(x*180u)/width;
|
||||
u32 green=(y*120u)/height;
|
||||
pixels[(usize)y*width+x]=(red<<16)|(green<<8)|32u;
|
||||
}
|
||||
if(bob64_app_present(pixels,width,height)!=(s64)((u64)width*height))return -3;
|
||||
if(bob64_app_write("bob!",4)!=4)return -4;
|
||||
for(;;) {
|
||||
if(bob64_app_wait_event(&event))return -5;
|
||||
if(event.Type==BOB64_EVENT_KEY_DOWN&&event.Character==0x1b)break;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,521 @@
|
||||
#include "../bob64/app.h"
|
||||
#include "../bob64/editor.h"
|
||||
#include "../bob64/gfx.h"
|
||||
#include "../bob64/window.h"
|
||||
|
||||
#define BOB64_GUI_MAX_WIDTH 1280u
|
||||
#define BOB64_GUI_MAX_HEIGHT 800u
|
||||
#define BOB64_GUI_MAX_WINDOWS 4u
|
||||
#define BOB64_GUI_FILENAME_CAPACITY 64u
|
||||
#define BOB64_GUI_SURFACE_PIXEL_CAPACITY 1048576u
|
||||
|
||||
static u32 pixels[BOB64_GUI_SURFACE_PIXEL_CAPACITY];
|
||||
static BOB64_GFX graphics[BOB64_GUI_MAX_WINDOWS];
|
||||
static struct {usize Offset,Bytes;u8 Used;} surface_allocations[BOB64_GUI_MAX_WINDOWS];
|
||||
static BOB64_WINDOW_MANAGER manager;
|
||||
static BOB64_WINDOW windows[BOB64_GUI_MAX_WINDOWS];
|
||||
static BOB64_WINDOW_HANDLE order[BOB64_GUI_MAX_WINDOWS];
|
||||
static char titles[BOB64_GUI_MAX_WINDOWS][16]={"Files","Editor","Window 3","Window 4"};
|
||||
static char filename[BOB64_GUI_FILENAME_CAPACITY];
|
||||
static char editor_status[32];
|
||||
static BOB64_EDITOR editor;
|
||||
static BOB64_WINDOW_HANDLE editor_window;
|
||||
static BOB64_WINDOW_HANDLE files_window;
|
||||
static u32 screen_width,screen_height;
|
||||
static BOB64_FILE_INFO file_entries[BOB64_SYSCALL_MAX_FILES];
|
||||
static u32 file_count,selected_file,file_scroll;
|
||||
static int editor_save_allowed;
|
||||
static int editor_exit_armed;
|
||||
static int editor_open_armed;
|
||||
static int file_delete_armed;
|
||||
|
||||
static usize gui_length(const char *text,usize limit) {
|
||||
usize length=0;
|
||||
if(!text)return limit;
|
||||
while(length<limit&&text[length])length++;
|
||||
return length;
|
||||
}
|
||||
|
||||
static void gui_copy(char *destination,const char *source,usize length) {
|
||||
for(usize i=0;i<length;i++)destination[i]=source[i];
|
||||
destination[length]=0;
|
||||
}
|
||||
|
||||
static BOB64_GFX *gui_graphics_for_handle(BOB64_WINDOW_HANDLE handle) {
|
||||
for(u32 i=0;i<BOB64_GUI_MAX_WINDOWS;i++)
|
||||
if(windows[i].Handle==handle)return &graphics[i];
|
||||
return 0;
|
||||
}
|
||||
|
||||
static u32 *gui_surface_allocate(u32 slot,u32 width,u32 height) {
|
||||
usize bytes,candidate=0;
|
||||
if(slot>=BOB64_GUI_MAX_WINDOWS||surface_allocations[slot].Used||!width||!height||
|
||||
(u64)width*height>BOB64_GUI_SURFACE_PIXEL_CAPACITY)return 0;
|
||||
bytes=(usize)width*height*sizeof(u32);
|
||||
for(;;) {
|
||||
usize next=sizeof(pixels);
|
||||
int next_slot=-1;
|
||||
for(u32 i=0;i<BOB64_GUI_MAX_WINDOWS;i++)
|
||||
if(surface_allocations[i].Used&&surface_allocations[i].Offset>=candidate&&
|
||||
surface_allocations[i].Offset<next) {
|
||||
next=surface_allocations[i].Offset;next_slot=(int)i;
|
||||
}
|
||||
if(bytes<=next-candidate)break;
|
||||
if(next_slot<0)return 0;
|
||||
candidate=surface_allocations[next_slot].Offset+
|
||||
surface_allocations[next_slot].Bytes;
|
||||
if(candidate>=sizeof(pixels))return 0;
|
||||
}
|
||||
if(candidate>sizeof(pixels)||bytes>sizeof(pixels)-candidate)return 0;
|
||||
surface_allocations[slot].Offset=candidate;
|
||||
surface_allocations[slot].Bytes=bytes;
|
||||
surface_allocations[slot].Used=1;
|
||||
return pixels+candidate/sizeof(u32);
|
||||
}
|
||||
|
||||
static void gui_surface_release(u32 slot) {
|
||||
if(slot>=BOB64_GUI_MAX_WINDOWS)return;
|
||||
surface_allocations[slot].Offset=0;surface_allocations[slot].Bytes=0;
|
||||
surface_allocations[slot].Used=0;
|
||||
}
|
||||
|
||||
static BOB64_WINDOW_HANDLE gui_create_window(s32 x,s32 y,u32 width,u32 height,
|
||||
const char *title) {
|
||||
BOB64_WINDOW_HANDLE kernel_handle;
|
||||
BOB64_WINDOW_HANDLE app_handle;
|
||||
BOB64_WINDOW *window;
|
||||
u32 slot=0;
|
||||
u32 *surface;
|
||||
while(slot<BOB64_GUI_MAX_WINDOWS&&windows[slot].Handle)slot++;
|
||||
if(slot>=BOB64_GUI_MAX_WINDOWS||!(surface=gui_surface_allocate(slot,width,height)))
|
||||
return 0;
|
||||
kernel_handle=bob64_app_window_create(x,y,width,height);
|
||||
if(!kernel_handle||(s64)kernel_handle<0) {
|
||||
gui_surface_release(slot);return 0;
|
||||
}
|
||||
manager.NextHandle=kernel_handle;
|
||||
app_handle=bob64_wm_create(&manager,x,y,width,height,(void *)title);
|
||||
if(app_handle!=kernel_handle) {
|
||||
if(app_handle)bob64_wm_destroy(&manager,app_handle);
|
||||
bob64_app_window_destroy(kernel_handle);gui_surface_release(slot);return 0;
|
||||
}
|
||||
window=bob64_wm_find(&manager,app_handle);
|
||||
slot=(u32)(window-windows);
|
||||
graphics[slot].Pixels=surface;graphics[slot].Width=width;
|
||||
graphics[slot].Height=height;
|
||||
graphics[slot].Capacity=(usize)BOB64_GUI_MAX_WIDTH*BOB64_GUI_MAX_HEIGHT;
|
||||
return app_handle;
|
||||
}
|
||||
|
||||
static int gui_destroy_window(BOB64_WINDOW_HANDLE handle) {
|
||||
u32 slot=0;
|
||||
while(slot<BOB64_GUI_MAX_WINDOWS&&windows[slot].Handle!=handle)slot++;
|
||||
if(slot>=BOB64_GUI_MAX_WINDOWS)return -1;
|
||||
if(bob64_app_window_destroy(handle))return -1;
|
||||
if(bob64_wm_destroy(&manager,handle))return -1;
|
||||
gui_surface_release(slot);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void gui_focus_window(BOB64_WINDOW_HANDLE handle) {
|
||||
if(bob64_wm_focus(&manager,handle)||bob64_app_window_focus(handle))
|
||||
gui_copy(editor_status,"FOCUS FAILED",sizeof("FOCUS FAILED"));
|
||||
}
|
||||
|
||||
static int gui_load_file(const BOB64_APP_STARTUP *startup) {
|
||||
const char *requested="notes.txt";
|
||||
usize length=sizeof("notes.txt")-1;
|
||||
s64 result;
|
||||
if(startup->ArgumentCount>1) {
|
||||
requested=startup->Arguments[1];
|
||||
length=gui_length(requested,BOB64_GUI_FILENAME_CAPACITY);
|
||||
if(!length||length>=BOB64_GUI_FILENAME_CAPACITY)return -1;
|
||||
}
|
||||
for(usize i=0;i<length;i++) {
|
||||
char value=requested[i];
|
||||
if(!((value>='a'&&value<='z')||(value>='A'&&value<='Z')||
|
||||
(value>='0'&&value<='9')||value=='.'||value=='_'||value=='-'))return -1;
|
||||
}
|
||||
gui_copy(filename,requested,length);
|
||||
result=bob64_app_read_file(filename,length,editor.Text,BOB64_EDITOR_CAPACITY);
|
||||
if(result==-2) {
|
||||
bob64_editor_init(&editor,0,0);
|
||||
gui_copy(editor_status,"NEW FILE",sizeof("NEW FILE"));
|
||||
editor_save_allowed=1;
|
||||
} else if(result==-28) {
|
||||
bob64_editor_init(&editor,0,0);
|
||||
gui_copy(editor_status,"FILE TOO LARGE",sizeof("FILE TOO LARGE"));
|
||||
editor_save_allowed=0;
|
||||
} else if(result<0) {
|
||||
return -1;
|
||||
} else {
|
||||
bob64_editor_init(&editor,editor.Text,(u32)result);
|
||||
gui_copy(editor_status,"LOADED",sizeof("LOADED"));
|
||||
editor_save_allowed=1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void gui_refresh_files(void) {
|
||||
s64 result=bob64_app_list_files(file_entries,BOB64_SYSCALL_MAX_FILES);
|
||||
if(result<0) {
|
||||
file_count=0;
|
||||
gui_copy(editor_status,result==-28?"TOO MANY FILES":"LIST FAILED",
|
||||
result==-28?sizeof("TOO MANY FILES"):sizeof("LIST FAILED"));
|
||||
return;
|
||||
}
|
||||
file_count=(u32)result;
|
||||
if(selected_file>=file_count)selected_file=file_count?file_count-1:0;
|
||||
if(file_scroll>=file_count)file_scroll=file_count?file_count-1:0;
|
||||
}
|
||||
|
||||
static void gui_reveal_selected_file(void) {
|
||||
BOB64_WINDOW *window=bob64_wm_find(&manager,files_window);
|
||||
u32 rows=window&&window->Height>58?(window->Height-58)/14:1;
|
||||
if(!rows)rows=1;
|
||||
if(selected_file<file_scroll)file_scroll=selected_file;
|
||||
else if(selected_file>=file_scroll+rows)file_scroll=selected_file-rows+1;
|
||||
}
|
||||
|
||||
static int gui_name_equal(const char *left,const char *right) {
|
||||
while(*left&&*right&&*left==*right){left++;right++;}
|
||||
return !*left&&!*right;
|
||||
}
|
||||
|
||||
static void gui_open_selected_file(void) {
|
||||
s64 result;
|
||||
if(selected_file>=file_count) {
|
||||
gui_copy(editor_status,"NO FILE SELECTED",sizeof("NO FILE SELECTED"));return;
|
||||
}
|
||||
const char *name=file_entries[selected_file].Name;
|
||||
if(editor.Dirty&&!editor_open_armed) {
|
||||
gui_copy(editor_status,"OPEN AGAIN TO DISCARD",sizeof("OPEN AGAIN TO DISCARD"));
|
||||
editor_open_armed=1;return;
|
||||
}
|
||||
if(gui_name_equal(name,filename)) {
|
||||
gui_focus_window(editor_window);
|
||||
gui_copy(editor_status,"CURRENT FILE",sizeof("CURRENT FILE"));
|
||||
editor_open_armed=0;return;
|
||||
}
|
||||
result=bob64_app_read_file(name,gui_length(name,BOB64_GUI_FILENAME_CAPACITY),
|
||||
editor.Text,BOB64_EDITOR_CAPACITY);
|
||||
if(result==-28) {
|
||||
gui_copy(editor_status,"FILE TOO LARGE",sizeof("FILE TOO LARGE"));
|
||||
editor_save_allowed=0;return;
|
||||
}
|
||||
if(result<0) {
|
||||
gui_copy(editor_status,"OPEN FAILED",sizeof("OPEN FAILED"));return;
|
||||
}
|
||||
gui_copy(filename,name,gui_length(name,BOB64_GUI_FILENAME_CAPACITY));
|
||||
bob64_editor_init(&editor,editor.Text,(u32)result);
|
||||
editor_save_allowed=1;editor_open_armed=0;
|
||||
gui_copy(editor_status,"LOADED",sizeof("LOADED"));
|
||||
gui_focus_window(editor_window);
|
||||
}
|
||||
|
||||
static void gui_delete_selected_file(void) {
|
||||
const char *name;
|
||||
s64 result;
|
||||
if(selected_file>=file_count) {
|
||||
gui_copy(editor_status,"NO FILE SELECTED",sizeof("NO FILE SELECTED"));return;
|
||||
}
|
||||
name=file_entries[selected_file].Name;
|
||||
if(gui_name_equal(name,filename)) {
|
||||
file_delete_armed=0;
|
||||
gui_copy(editor_status,"SAVE OR OPEN OTHER FILE",sizeof("SAVE OR OPEN OTHER FILE"));
|
||||
return;
|
||||
}
|
||||
if(!file_delete_armed) {
|
||||
file_delete_armed=1;
|
||||
gui_copy(editor_status,"D AGAIN TO DELETE",sizeof("D AGAIN TO DELETE"));
|
||||
return;
|
||||
}
|
||||
result=bob64_app_delete_file(name,gui_length(name,BOB64_GUI_FILENAME_CAPACITY));
|
||||
file_delete_armed=0;
|
||||
if(result)gui_copy(editor_status,"DELETE FAILED",sizeof("DELETE FAILED"));
|
||||
else {gui_refresh_files();gui_copy(editor_status,"DELETED",sizeof("DELETED"));}
|
||||
}
|
||||
|
||||
static void gui_draw_window(const BOB64_WINDOW *window,int focused) {
|
||||
BOB64_WINDOW local=*window;
|
||||
BOB64_GFX *graphics;
|
||||
local.X=0;local.Y=0;window=&local;
|
||||
graphics=gui_graphics_for_handle(window->Handle);
|
||||
if(!graphics)return;
|
||||
const char *title=(const char *)window->Context;
|
||||
u32 border=focused?0x00a4c8ffu:0x006d8095u;
|
||||
u32 title_bar=focused?0x00335d8cu:0x00334050u;
|
||||
bob64_gfx_fill_rect(graphics,window->X,window->Y,window->Width,
|
||||
window->Height,0x0009111bu);
|
||||
bob64_gfx_fill_rect(graphics,window->X+2,window->Y+2,window->Width-4,
|
||||
window->Height-4,0x001a2a3cu);
|
||||
bob64_gfx_fill_rect(graphics,window->X,window->Y,window->Width,
|
||||
BOB64_WINDOW_TITLE_BAR_HEIGHT,title_bar);
|
||||
bob64_gfx_line(graphics,window->X,window->Y,
|
||||
window->X+(s32)window->Width-1,window->Y,border);
|
||||
bob64_gfx_line(graphics,window->X,window->Y+(s32)window->Height-1,
|
||||
window->X+(s32)window->Width-1,
|
||||
window->Y+(s32)window->Height-1,border);
|
||||
bob64_gfx_line(graphics,window->X,window->Y,window->X,
|
||||
window->Y+(s32)window->Height-1,border);
|
||||
bob64_gfx_line(graphics,window->X+(s32)window->Width-1,window->Y,
|
||||
window->X+(s32)window->Width-1,
|
||||
window->Y+(s32)window->Height-1,border);
|
||||
bob64_gfx_text(graphics,window->X+12,window->Y+8,title,0x00ffffffu,1);
|
||||
if(window->Handle==editor_window) {
|
||||
u32 columns=(window->Width-24)/6;
|
||||
u32 rows=(window->Height-76)/10;
|
||||
u32 column=0,row=0;
|
||||
u32 cursor_row,cursor_column;
|
||||
s32 text_x=window->X+12,text_y=window->Y+46;
|
||||
int caret_visible=0;
|
||||
if(columns==0)columns=1;
|
||||
bob64_editor_visual_position(&editor,columns,&cursor_row,&cursor_column);
|
||||
(void)cursor_column;
|
||||
if(cursor_row<editor.ScrollRow)editor.ScrollRow=cursor_row;
|
||||
else if(rows&&cursor_row>=editor.ScrollRow+rows)
|
||||
editor.ScrollRow=cursor_row-rows+1;
|
||||
bob64_gfx_text(graphics,window->X+12,window->Y+30,filename,
|
||||
0x009eb3c7u,1);
|
||||
for(u32 i=0;i<=editor.Length;i++) {
|
||||
if(column>=columns&&(i==editor.Length||editor.Text[i]!='\n')) {
|
||||
row++;column=0;
|
||||
}
|
||||
if(i==editor.Cursor) {
|
||||
s32 caret_x=text_x+(s32)(column*6);
|
||||
s32 caret_y=text_y+(s32)((row-editor.ScrollRow)*10);
|
||||
if(row>=editor.ScrollRow&&row<editor.ScrollRow+rows)
|
||||
bob64_gfx_line(graphics,caret_x,caret_y,
|
||||
caret_x,caret_y+7,0x00ffffffu);
|
||||
caret_visible=1;
|
||||
}
|
||||
if(i==editor.Length)break;
|
||||
if(editor.Text[i]=='\n') {
|
||||
row++;column=0;
|
||||
continue;
|
||||
}
|
||||
if(row>=editor.ScrollRow&&row<editor.ScrollRow+rows) {
|
||||
char character[2]={editor.Text[i],0};
|
||||
bob64_gfx_text(graphics,text_x+(s32)(column*6),
|
||||
text_y+(s32)((row-editor.ScrollRow)*10),character,
|
||||
0x00e2ebf5u,1);
|
||||
}
|
||||
column++;
|
||||
}
|
||||
if(!caret_visible&&row>=editor.ScrollRow&&row<editor.ScrollRow+rows)
|
||||
bob64_gfx_line(graphics,text_x+(s32)(column*6),
|
||||
text_y+(s32)((row-editor.ScrollRow)*10),
|
||||
text_x+(s32)(column*6),text_y+(s32)((row-editor.ScrollRow)*10)+7,
|
||||
0x00ffffffu);
|
||||
bob64_gfx_line(graphics,window->X+8,
|
||||
window->Y+(s32)window->Height-22,
|
||||
window->X+(s32)window->Width-8,
|
||||
window->Y+(s32)window->Height-22,0x0044576au);
|
||||
bob64_gfx_text(graphics,window->X+12,
|
||||
window->Y+(s32)window->Height-16,editor_status,0x008fc8ffu,1);
|
||||
bob64_gfx_text(graphics,window->X+(s32)window->Width/2,
|
||||
window->Y+(s32)window->Height-16,"CTRL S SAVE",0x009eb3c7u,1);
|
||||
} else if(window->Handle==files_window) {
|
||||
u32 rows=window->Height>58?(window->Height-58)/14:0;
|
||||
bob64_gfx_text(graphics,window->X+10,window->Y+31,
|
||||
"UP DOWN OPEN R REFRESH",0x009eb3c7u,1);
|
||||
bob64_gfx_text(graphics,window->X+10,window->Y+41,
|
||||
"D TWICE DELETE",0x009eb3c7u,1);
|
||||
bob64_gfx_text(graphics,window->X+10,window->Y+49,editor_status,
|
||||
0x008fc8ffu,1);
|
||||
for(u32 row=0;row<rows&&file_scroll+row<file_count;row++) {
|
||||
u32 index=file_scroll+row;
|
||||
s32 y=window->Y+56+(s32)(row*14);
|
||||
if(index==selected_file)
|
||||
bob64_gfx_fill_rect(graphics,window->X+6,y-2,
|
||||
window->Width-12,12,0x00335d8cu);
|
||||
bob64_gfx_text(graphics,window->X+10,y,
|
||||
file_entries[index].Name,index==selected_file?
|
||||
0x00ffffffu:0x00dbe8f4u,1);
|
||||
}
|
||||
if(!file_count)bob64_gfx_text(graphics,window->X+10,window->Y+60,
|
||||
"NO FILES",0x008fc8ffu,1);
|
||||
} else if(window->Handle==manager.Focused) {
|
||||
bob64_gfx_text(graphics,window->X+14,window->Y+46,
|
||||
"BOB64 DESKTOP",0x007ed6ffu,1);
|
||||
bob64_gfx_text(graphics,window->X+14,window->Y+66,
|
||||
"RUN DESKTOP B64E FILE",0x00dbe8f4u,1);
|
||||
bob64_gfx_text(graphics,window->X+14,window->Y+84,
|
||||
"TAB SWITCH WINDOWS",0x00dbe8f4u,1);
|
||||
bob64_gfx_text(graphics,window->X+14,window->Y+102,
|
||||
"ESC RETURN TO SHELL",0x00dbe8f4u,1);
|
||||
bob64_gfx_text(graphics,window->X+14,window->Y+120,
|
||||
"N NEW X CLOSE OTHER",0x00dbe8f4u,1);
|
||||
} else {
|
||||
bob64_gfx_text(graphics,window->X+14,window->Y+46,
|
||||
"DRAG WINDOW TITLE",0x00dbe8f4u,1);
|
||||
}
|
||||
}
|
||||
|
||||
static int gui_draw(s32 cursor_x,s32 cursor_y) {
|
||||
for(u32 i=0;i<manager.Count;i++) {
|
||||
BOB64_WINDOW *window=bob64_wm_find(&manager,manager.ZOrder[i]);
|
||||
BOB64_GFX *surface;
|
||||
if(!window||!(window->Flags&BOB64_WINDOW_VISIBLE))continue;
|
||||
surface=gui_graphics_for_handle(window->Handle);
|
||||
if(!surface)continue;
|
||||
bob64_gfx_fill_rect(surface,0,0,surface->Width,surface->Height,
|
||||
0x000d1723u);
|
||||
for(u32 y=0;y<surface->Height;y+=4)
|
||||
bob64_gfx_line(surface,0,(s32)y,(s32)surface->Width-1,(s32)y,
|
||||
0x00132130u);
|
||||
gui_draw_window(window,window->Handle==manager.Focused);
|
||||
if(cursor_x>=window->X&&cursor_y>=window->Y&&
|
||||
(u32)(cursor_x-window->X)<window->Width&&
|
||||
(u32)(cursor_y-window->Y)<window->Height) {
|
||||
s32 x=cursor_x-window->X,y=cursor_y-window->Y;
|
||||
bob64_gfx_line(surface,x-5,y,x+5,y,0x00000000u);
|
||||
bob64_gfx_line(surface,x,y-5,x,y+5,0x00000000u);
|
||||
bob64_gfx_line(surface,x-3,y,x+3,y,0x00ffffffu);
|
||||
bob64_gfx_line(surface,x,y-3,x,y+3,0x00ffffffu);
|
||||
}
|
||||
if(bob64_app_window_present(window->Handle,surface->Pixels,
|
||||
surface->Width,surface->Height)!=(s64)((u64)surface->Width*surface->Height))
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void gui_save_editor(void) {
|
||||
if(!editor_save_allowed) {
|
||||
gui_copy(editor_status,"FILE TOO LARGE",sizeof("FILE TOO LARGE"));
|
||||
return;
|
||||
}
|
||||
s64 result=bob64_app_write_file(filename,gui_length(filename,
|
||||
BOB64_GUI_FILENAME_CAPACITY),editor.Text,editor.Length);
|
||||
if(result==(s64)editor.Length) {
|
||||
editor.Dirty=0;gui_copy(editor_status,"SAVED",sizeof("SAVED"));
|
||||
} else gui_copy(editor_status,"SAVE FAILED",sizeof("SAVE FAILED"));
|
||||
}
|
||||
|
||||
static void gui_editor_place_cursor(u32 target_row,u32 target_column,u32 columns) {
|
||||
u32 row=0,column=0;
|
||||
if(!columns)columns=1;
|
||||
target_row+=editor.ScrollRow;
|
||||
for(u32 i=0;i<=editor.Length;i++) {
|
||||
if(column>=columns&&(i==editor.Length||editor.Text[i]!='\n')) {
|
||||
row++;column=0;
|
||||
}
|
||||
if(row==target_row&&column>=target_column) {
|
||||
editor.Cursor=i;return;
|
||||
}
|
||||
if(i==editor.Length)break;
|
||||
if(editor.Text[i]=='\n') {
|
||||
if(row==target_row){editor.Cursor=i;return;}
|
||||
row++;column=0;continue;
|
||||
}
|
||||
column++;
|
||||
}
|
||||
editor.Cursor=editor.Length;
|
||||
}
|
||||
|
||||
static void gui_focus_next(void) {
|
||||
if(!manager.Count)return;
|
||||
u32 start=0;
|
||||
for(u32 i=0;i<manager.Count;i++)if(manager.ZOrder[i]==manager.Focused) {
|
||||
start=i+1;break;
|
||||
}
|
||||
for(u32 offset=0;offset<manager.Count;offset++) {
|
||||
BOB64_WINDOW_HANDLE handle=manager.ZOrder[(start+offset)%manager.Count];
|
||||
BOB64_WINDOW *window=bob64_wm_find(&manager,handle);
|
||||
if(window&&(window->Flags&BOB64_WINDOW_VISIBLE)) {
|
||||
gui_focus_window(handle);return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void gui_key(const BOB64_EVENT *event) {
|
||||
if(event->Type!=BOB64_EVENT_KEY_DOWN)return;
|
||||
if(event->Character=='\t')gui_focus_next();
|
||||
else if(manager.Focused==files_window) {
|
||||
if(event->Key==(BOB64_EVENT_KEY_EXTENDED|0x48)) {
|
||||
if(selected_file)selected_file--;
|
||||
gui_reveal_selected_file();
|
||||
file_delete_armed=editor_open_armed=0;
|
||||
} else if(event->Key==(BOB64_EVENT_KEY_EXTENDED|0x50)) {
|
||||
if(selected_file+1<file_count)selected_file++;
|
||||
gui_reveal_selected_file();
|
||||
file_delete_armed=editor_open_armed=0;
|
||||
} else if(event->Character=='r'||event->Character=='R') {
|
||||
gui_refresh_files();file_delete_armed=editor_open_armed=0;
|
||||
} else if(event->Character=='o'||event->Character=='O'||
|
||||
event->Character=='\n')gui_open_selected_file();
|
||||
else if(event->Character=='d'||event->Character=='D')gui_delete_selected_file();
|
||||
else file_delete_armed=editor_open_armed=0;
|
||||
}
|
||||
else if(event->Character=='n'&&manager.Count<BOB64_GUI_MAX_WINDOWS) {
|
||||
u32 index=manager.Count;
|
||||
BOB64_WINDOW_HANDLE handle=gui_create_window(
|
||||
(s32)(screen_width/5+index*24),(s32)(screen_height/5+index*20),
|
||||
screen_width/3,screen_height/3,titles[index]);
|
||||
if(!handle)gui_copy(editor_status,"WINDOW CREATE FAILED",
|
||||
sizeof("WINDOW CREATE FAILED"));
|
||||
} else if(event->Character=='x'&&manager.Count>1&&manager.Focused!=editor_window) {
|
||||
if(gui_destroy_window(manager.Focused))
|
||||
gui_copy(editor_status,"WINDOW CLOSE FAILED",sizeof("WINDOW CLOSE FAILED"));
|
||||
}
|
||||
else if(manager.Focused==editor_window) {
|
||||
if((event->Modifiers&BOB64_EVENT_MOD_CONTROL)&&
|
||||
(event->Character=='s'||event->Character=='S'))gui_save_editor();
|
||||
else bob64_editor_handle_key(&editor,event);
|
||||
}
|
||||
}
|
||||
|
||||
s64 bob64_app_main(const BOB64_APP_STARTUP *startup) {
|
||||
BOB64_EVENT event;
|
||||
BOB64_EVENT routed;
|
||||
BOB64_EVENT screen_event;
|
||||
s32 cursor_x,cursor_y;
|
||||
if(!startup||startup->AbiVersion!=BOB64_APP_ABI_VERSION||
|
||||
bob64_app_query_abi()!=BOB64_SYSCALL_ABI_VERSION)return -1;
|
||||
if(bob64_app_write("bob!",4)!=4)return -3;
|
||||
if(bob64_app_get_display(&screen_width,&screen_height))return -6;
|
||||
if(screen_width<480||screen_height<300||screen_width>BOB64_GUI_MAX_WIDTH||
|
||||
screen_height>BOB64_GUI_MAX_HEIGHT)return -7;
|
||||
if(bob64_wm_init(&manager,windows,BOB64_GUI_MAX_WINDOWS,order,
|
||||
screen_width,screen_height))return -8;
|
||||
if(gui_load_file(startup))return -9;
|
||||
gui_refresh_files();
|
||||
cursor_x=(s32)(screen_width/2);cursor_y=(s32)(screen_height/2);
|
||||
if(!gui_create_window(8,24,screen_width/3,screen_height-32,titles[0])||
|
||||
!gui_create_window((s32)(screen_width/3+16),24,
|
||||
screen_width-screen_width/3-24,screen_height-32,titles[1]))return -2;
|
||||
files_window=manager.ZOrder[0];
|
||||
editor_window=manager.Focused;
|
||||
for(;;) {
|
||||
if(gui_draw(cursor_x,cursor_y))return -4;
|
||||
if(bob64_app_wait_event(&event))return -5;
|
||||
if(event.Type==BOB64_EVENT_KEY_DOWN&&event.Character==0x1b) {
|
||||
if(editor.Dirty&&!editor_exit_armed) {
|
||||
gui_copy(editor_status,"ESC AGAIN TO QUIT",sizeof("ESC AGAIN TO QUIT"));
|
||||
editor_exit_armed=1;continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
if(event.Type==BOB64_EVENT_KEY_DOWN)editor_exit_armed=0;
|
||||
if(event.Type==BOB64_EVENT_MOUSE_MOVE||event.Type==BOB64_EVENT_MOUSE_BUTTON||
|
||||
event.Type==BOB64_EVENT_MOUSE_WHEEL)
|
||||
cursor_x=event.ScreenX,cursor_y=event.ScreenY;
|
||||
screen_event=event;screen_event.X=event.ScreenX;screen_event.Y=event.ScreenY;
|
||||
bob64_wm_dispatch(&manager,&screen_event,&routed);
|
||||
if(event.Type==BOB64_EVENT_MOUSE_BUTTON&&(event.Buttons&1u)&&
|
||||
manager.Focused==files_window&&routed.X>=8&&routed.Y>=56) {
|
||||
u32 row=(u32)(routed.Y-56)/14;
|
||||
if(file_scroll+row<file_count)selected_file=file_scroll+row;
|
||||
}
|
||||
if(event.Type==BOB64_EVENT_MOUSE_BUTTON&&(event.Buttons&1u)&&
|
||||
manager.Focused==editor_window&&routed.X>=12&&routed.Y>=46) {
|
||||
BOB64_WINDOW *window=bob64_wm_find(&manager,editor_window);
|
||||
if(window)gui_editor_place_cursor((u32)(routed.Y-46)/10,
|
||||
(u32)(routed.X-12)/6,(window->Width-24)/6);
|
||||
}
|
||||
gui_key(&event);
|
||||
if(editor.Dirty)gui_copy(editor_status,"UNSAVED",sizeof("UNSAVED"));
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
#include "../bob64/app.h"
|
||||
#include "../bob64/libc.h"
|
||||
|
||||
s64 bob64_app_main(const BOB64_APP_STARTUP *startup) {
|
||||
static const char message[]="bob!";
|
||||
static const char file_name[]="bob-app.txt";
|
||||
static const char stream_name[]="bob-stream.txt";
|
||||
static const char file_data[]="written by a C app";
|
||||
char file_copy[32];
|
||||
if(!startup||startup->AbiVersion!=BOB64_APP_ABI_VERSION)return -1;
|
||||
if(bob64_app_query_abi()!=BOB64_SYSCALL_ABI_VERSION)return -2;
|
||||
u64 ticks_before=bob64_app_ticks();
|
||||
if(bob64_app_write(message,sizeof(message)-1)!=(s64)(sizeof(message)-1))return -3;
|
||||
if(bob64_app_write_file(file_name,sizeof(file_name)-1,file_data,
|
||||
sizeof(file_data)-1)!=(s64)(sizeof(file_data)-1))return -4;
|
||||
s64 copied=bob64_app_read_file(file_name,sizeof(file_name)-1,file_copy,
|
||||
sizeof(file_copy));
|
||||
if(copied!=(s64)(sizeof(file_data)-1))return -5;
|
||||
if(bob64_memcmp(file_copy,file_data,sizeof(file_data)-1))return -6;
|
||||
s64 handle=bob64_app_file_open(stream_name,sizeof(stream_name)-1,
|
||||
BOB64_FILE_OPEN_READ|BOB64_FILE_OPEN_WRITE|BOB64_FILE_OPEN_CREATE|
|
||||
BOB64_FILE_OPEN_TRUNCATE);
|
||||
if(handle<=0)return -7;
|
||||
if(bob64_app_file_write(handle,file_data,sizeof(file_data)-1)!=
|
||||
(s64)(sizeof(file_data)-1))return -8;
|
||||
if(bob64_app_file_seek(handle,0)!=0)return -9;
|
||||
copied=bob64_app_file_read(handle,file_copy,sizeof(file_copy));
|
||||
if(copied!=(s64)(sizeof(file_data)-1)||
|
||||
bob64_memcmp(file_copy,file_data,sizeof(file_data)-1))return -10;
|
||||
if(bob64_app_file_close(handle))return -11;
|
||||
if(bob64_app_ticks()<ticks_before)return -12;
|
||||
return 0;
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
#include "bob.h"
|
||||
#include "bob_fs.h"
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
char text[512];
|
||||
int length;
|
||||
int i;
|
||||
if (argc != 2) { bob_puts("Usage: cat FILE"); return 1; }
|
||||
length = bob_file_read(argv[1], text, 512);
|
||||
if (length < 0) { bob_puts("Cannot read text file."); return 1; }
|
||||
for (i = 0; i < length; i++) bob_putc(text[i]);
|
||||
if(length>0&&text[length-1]!='\n')bob_putc('\n');
|
||||
return 0;
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
#include "bob.h"
|
||||
|
||||
static void write_text(const char *text) {
|
||||
while (*text) bob_putc(*text++);
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
int i;
|
||||
for (i = 1; i < argc; i++) {
|
||||
if (i > 1) bob_putc(' ');
|
||||
write_text(argv[i]);
|
||||
}
|
||||
bob_putc('\n');
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
#include "bob.h"
|
||||
#include "bob_gfx.h"
|
||||
#include "bob_event.h"
|
||||
|
||||
int main(void) {
|
||||
int resolution[2];
|
||||
int event[4];
|
||||
char bitmap[8] = {'/', '-', '\\', '|', '\\', '-', '/', '|'};
|
||||
if (bob_gfx_enter()) return 1;
|
||||
if (bob_gfx_resolution(resolution) != 2 || resolution[0] != 80 || resolution[1] != 25) {
|
||||
bob_gfx_leave();
|
||||
return 2;
|
||||
}
|
||||
bob_gfx_clear(' ', 0);
|
||||
bob_gfx_fill_rect(1, 1, 78, 23, '.', 1);
|
||||
bob_gfx_fill_rect(2, 2, 76, 3, ' ', 4);
|
||||
bob_gfx_text(4, 3, "BOB32 GRAPHICS DEMO", 15);
|
||||
bob_gfx_line(3, 7, 76, 7, '=', 14);
|
||||
bob_gfx_pixel(40, 16, '*', 10);
|
||||
bob_gfx_fill_rect(8, 10, 12, 5, '#', 2);
|
||||
bob_gfx_blit(28, 10, 4, 2, bitmap, 12);
|
||||
bob_gfx_text(4, 19, "Press any key to return to the shell", 15);
|
||||
if (bob_gfx_present()) { bob_gfx_leave(); return 3; }
|
||||
if (bob_event_wait(event) != 1 || event[0] != BOB_EVENT_CHAR || event[1] != 'x') {
|
||||
bob_gfx_leave();
|
||||
return 4;
|
||||
}
|
||||
if (bob_gfx_leave()) return 5;
|
||||
bob_puts("bob!");
|
||||
return 0;
|
||||
}
|
||||
+462
@@ -0,0 +1,462 @@
|
||||
#include "bob.h"
|
||||
#include "bob_gfx.h"
|
||||
#include "bob_font.h"
|
||||
#include "bob_event.h"
|
||||
#include "bob_gui.h"
|
||||
#include "bob_fs.h"
|
||||
#include "bob_process.h"
|
||||
#include "bob_string.h"
|
||||
|
||||
static void gui_select_file(int row,const int *slots,int count,int *selected,
|
||||
char *status,char *preview,int *preview_length,int *preview_scroll) {
|
||||
int size,kind;char name[24],size_text[12];
|
||||
if(row<0||row>=count)return;
|
||||
*selected=row;
|
||||
kind=bob_file_list(slots[row],name,24,&size);
|
||||
bob_format_int(size,size_text,12);
|
||||
bob_strcpy(status,name);bob_strcat(status," ");bob_strcat(status,size_text);
|
||||
preview[0]=0;*preview_length=-1;*preview_scroll=0;
|
||||
if(kind==0)*preview_length=bob_file_read(name,preview,512);
|
||||
}
|
||||
|
||||
static int gui_preview_offset(const char *preview,int length,int lines) {
|
||||
int position=0,column;
|
||||
while(lines>0&&position<length) {
|
||||
column=0;
|
||||
while(column<34&&position<length&&preview[position]!='\n'){position++;column++;}
|
||||
if(position<length&&preview[position]=='\n')position++;
|
||||
lines--;
|
||||
}
|
||||
return position;
|
||||
}
|
||||
|
||||
static int gui_delete_selected(int row,const int *slots,int count,char *name) {
|
||||
int size,kind;
|
||||
if(row<0||row>=count)return -1;
|
||||
kind=bob_file_list(slots[row],name,24,&size);
|
||||
if(kind!=0)return -1;
|
||||
return bob_file_delete(name);
|
||||
}
|
||||
|
||||
static void gui_wm_sync_rects(int *rects,const int *managed) {
|
||||
for(int id=0;id<2;id++)for(int i=0;i<4;i++)
|
||||
rects[id*4+i]=managed[id*BOB_WM_WINDOW_WORDS+i];
|
||||
}
|
||||
|
||||
static void gui_place_editor_widgets(int *windows,int *name_field,int *text_area,int *button) {
|
||||
int *rect=windows;
|
||||
name_field[0]=rect[0]+2;name_field[1]=rect[1]+5;
|
||||
text_area[0]=rect[0]+2;text_area[1]=rect[1]+9;
|
||||
button[0]=rect[0]+3;button[1]=rect[1]+16;
|
||||
}
|
||||
|
||||
static int gui_open_selected_text(int row,const int *slots,int count,char *name,
|
||||
char *filename,char *text,int *text_state,const int *text_area,
|
||||
int *wm_state,int *wm_windows,int *wm_order,char *status) {
|
||||
int size,kind,length;
|
||||
if(row<0||row>=count){bob_strcpy(status,"Select a text file.");return 0;}
|
||||
kind=bob_file_list(slots[row],name,24,&size);
|
||||
if(kind!=BOB_FILE_KIND_TEXT){bob_strcpy(status,"Text files only.");return 0;}
|
||||
length=bob_file_read(name,text,512);
|
||||
if(length<0){bob_strcpy(status,"Could not read file.");return 0;}
|
||||
bob_strcpy(filename,name);
|
||||
bob_gui_text_area_init(text,text_state,512);
|
||||
bob_gui_text_area_reveal(text,text_state,text_area);
|
||||
text_state[0]=1;bob_wm_focus(wm_state,wm_windows,wm_order,0);
|
||||
bob_strcpy(status,"Editing selected file.");
|
||||
return 1;
|
||||
}
|
||||
|
||||
static void gui_launch_app(int row,const char *names,int count,char *message) {
|
||||
char number[12];
|
||||
int child_status=-1,status;
|
||||
if(row<0||row>=count){bob_strcpy(message,"No app selected.");return;}
|
||||
status=bob_app_run(names+row*24,"",&child_status);
|
||||
if(status==-1)bob_strcpy(message,"App not found.");
|
||||
else if(status==-2)bob_strcpy(message,"Not a native app.");
|
||||
else if(status==-4)bob_strcpy(message,"Invalid app image.");
|
||||
else if(status==-5)bob_strcpy(message,"Not enough memory.");
|
||||
else if(status<0)bob_strcpy(message,"App launch failed.");
|
||||
else {
|
||||
bob_strcpy(message,"App exit ");bob_format_int(child_status,number,12);
|
||||
bob_strcat(message,number);
|
||||
}
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
int event[4];
|
||||
int mouse_x=-1;
|
||||
int mouse_y=-1;
|
||||
int wm_state[10];
|
||||
int wm_windows[14];
|
||||
int wm_order[2];
|
||||
int routed_event[4];
|
||||
int target_window=-1;
|
||||
int redraw_full=0;
|
||||
int overlay_was_open=0;
|
||||
int draw_id=-1;
|
||||
int windows[8];
|
||||
int button[4]={6,19,31,3};
|
||||
int button_state[2]={0,0};
|
||||
int delete_yes[4]={43,17,13,3};
|
||||
int delete_no[4]={59,17,13,3};
|
||||
int delete_yes_state[2]={0,0};
|
||||
int delete_no_state[2]={0,0};
|
||||
int name_field[4]={5,8,33,3};
|
||||
int text_area[4]={5,12,33,7};
|
||||
int name_state[3];
|
||||
int text_state[4];
|
||||
int length_b=0;
|
||||
int file_slots[8];
|
||||
char app_names[192];
|
||||
int app_count=0;
|
||||
int app_selected=0;
|
||||
int launcher_open=0;
|
||||
int help_open=0;
|
||||
int help_close[4]={32,18,16,3};
|
||||
int help_close_state[2]={0,0};
|
||||
int launch_button[4]={42,18,16,3};
|
||||
int close_button[4]={22,18,14,3};
|
||||
int launch_button_state[2]={0,0};
|
||||
int close_button_state[2]={0,0};
|
||||
int file_count=0;
|
||||
int selected_file=-1;
|
||||
int selection_initialized=0;
|
||||
int file_scroll=0;
|
||||
int delete_confirm=0;
|
||||
int menu_open=0;
|
||||
int menu_rect[4]={43,7,30,5};
|
||||
int menu_state[2]={0,-1};
|
||||
int file_size;
|
||||
int file_kind;
|
||||
int preview_length=-1;
|
||||
int preview_scroll=0;
|
||||
int preview_row,preview_column,preview_position;
|
||||
char preview[512];
|
||||
char preview_line[35];
|
||||
char file_name[24];
|
||||
char file_name_text[24]="new.txt";
|
||||
char file_text[512]="bob!";
|
||||
char message_b[32]="";
|
||||
char menu_items[72];
|
||||
int running=1;
|
||||
bob_strcpy(message_b,"N/P select; E edit; X delete");
|
||||
bob_strcpy(menu_items,"Open selected text");
|
||||
bob_strcpy(menu_items+24,"Delete selected");
|
||||
bob_strcpy(menu_items+48,"Close menu");
|
||||
bob_gui_text_field_init(file_name_text,name_state,24);
|
||||
bob_gui_text_area_init(file_text,text_state,512);
|
||||
name_state[0]=1;
|
||||
if(bob_wm_init(wm_state,wm_windows,wm_order,2,80,25))return 1;
|
||||
if(bob_wm_create(wm_state,wm_windows,wm_order,3,3,37,20)!=0||
|
||||
bob_wm_create(wm_state,wm_windows,wm_order,41,3,37,20)!=1)return 1;
|
||||
bob_wm_focus(wm_state,wm_windows,wm_order,0);
|
||||
if(bob_gfx_enter())return 1;
|
||||
while(running) {
|
||||
gui_wm_sync_rects(windows,wm_windows);
|
||||
gui_place_editor_widgets(windows,name_field,text_area,button);
|
||||
bob_gui_menu_place(menu_rect,windows[4]+2,windows[5]+4,30,3,80,25);
|
||||
file_count=0;
|
||||
app_count=0;
|
||||
for(int i=0;i<8;i++) {
|
||||
file_kind=bob_file_list(i,file_name,24,&file_size);
|
||||
if(file_kind>=0)file_slots[file_count++]=i;
|
||||
if(file_kind==BOB_FILE_KIND_NATIVE_APP) {
|
||||
bob_strcpy(app_names+app_count*24,file_name);app_count++;
|
||||
}
|
||||
}
|
||||
if(app_selected>=app_count)app_selected=app_count?app_count-1:0;
|
||||
if(!selection_initialized&&file_count>0) {
|
||||
gui_select_file(0,file_slots,file_count,&selected_file,message_b,preview,&preview_length,&preview_scroll);
|
||||
selection_initialized=1;
|
||||
}
|
||||
if(selected_file>=file_count) {
|
||||
selected_file=-1;preview_length=-1;preview_scroll=0;delete_confirm=0;
|
||||
bob_strcpy(message_b,"Selection changed.");
|
||||
}
|
||||
if(file_scroll>file_count-6)file_scroll=file_count>6?file_count-6:0;
|
||||
if(selected_file>=0) {
|
||||
if(selected_file<file_scroll)file_scroll=selected_file;
|
||||
if(selected_file>=file_scroll+6)file_scroll=selected_file-5;
|
||||
}
|
||||
if(menu_open||launcher_open||help_open||overlay_was_open)wm_state[8]=1;
|
||||
redraw_full=wm_state[8];
|
||||
bob_wm_begin_draw(wm_state,wm_windows,wm_order);
|
||||
if(redraw_full) {
|
||||
bob_gfx_clear('.',1);
|
||||
bob_gfx_text(2,0,"BOB32 DESKTOP ?: HELP TAB: FOCUS CTRL+S: SAVE ESC: EXIT",15);
|
||||
}
|
||||
while((draw_id=bob_wm_next_dirty(wm_state,wm_windows,wm_order))>=0) {
|
||||
int id=draw_id;int *rect=windows+id*4;
|
||||
if(id==0)bob_gui_window(rect[0],rect[1],rect[2],rect[3],"Text editor",
|
||||
"E opens text. Tab changes focus.","Ctrl+S saves; Enter starts a new line.",wm_state[2]==0);
|
||||
else {
|
||||
bob_gui_window(rect[0],rect[1],rect[2],rect[3],"Window B","File menu: M or click File",message_b,wm_state[2]==1);
|
||||
for(int row=0;row<6&&file_scroll+row<file_count;row++) {
|
||||
int slot=file_slots[file_scroll+row];
|
||||
bob_file_list(slot,file_name,24,&file_size);
|
||||
bob_gfx_text(rect[0]+2,rect[1]+4+row,
|
||||
file_scroll+row==selected_file?"> ":" ",wm_state[2]==1?15:8);
|
||||
bob_gfx_text(rect[0]+4,rect[1]+4+row,file_name,wm_state[2]==1?15:7);
|
||||
}
|
||||
if(delete_confirm) {
|
||||
bob_gfx_text(rect[0]+2,rect[1]+11,"Delete selected text file?",wm_state[2]==1?14:8);
|
||||
delete_yes[0]=rect[0]+2;delete_yes[1]=rect[1]+14;
|
||||
delete_no[0]=rect[0]+19;delete_no[1]=rect[1]+14;
|
||||
bob_gui_button_draw(delete_yes[0],delete_yes[1],delete_yes[2],delete_yes[3],"Yes, delete",delete_yes_state[0],delete_yes_state[1]);
|
||||
bob_gui_button_draw(delete_no[0],delete_no[1],delete_no[2],delete_no[3],"Cancel",delete_no_state[0],delete_no_state[1]);
|
||||
} else {
|
||||
bob_gfx_text(rect[0]+2,rect[1]+11,"Preview:",wm_state[2]==1?14:8);
|
||||
if(preview_length<0)bob_gfx_text(rect[0]+2,rect[1]+12,"No text preview.",wm_state[2]==1?7:8);
|
||||
preview_position=gui_preview_offset(preview,preview_length,preview_scroll);
|
||||
for(preview_row=0;preview_row<6&&preview_position<preview_length;preview_row++) {
|
||||
preview_column=0;
|
||||
while(preview_column<34&&preview_position<preview_length&&preview[preview_position]!='\n')
|
||||
preview_line[preview_column++]=preview[preview_position++];
|
||||
if(preview_position<preview_length&&preview[preview_position]=='\n')preview_position++;
|
||||
preview_line[preview_column]=0;
|
||||
bob_gfx_text(rect[0]+2,rect[1]+12+preview_row,preview_line,wm_state[2]==1?15:7);
|
||||
}
|
||||
}
|
||||
}
|
||||
if(id==0) {
|
||||
gui_place_editor_widgets(windows,name_field,text_area,button);
|
||||
bob_gfx_text(rect[0]+2,rect[1]+4,"File name",wm_state[2]==0?14:8);
|
||||
bob_gui_text_field_draw(name_field,file_name_text,name_state);
|
||||
bob_gfx_text(rect[0]+2,rect[1]+8,"Text",wm_state[2]==0?14:8);
|
||||
bob_gui_text_area_draw(text_area,file_text,text_state);
|
||||
bob_gui_button_draw(button[0],button[1],button[2],button[3],"Save file",button_state[0],button_state[1]);
|
||||
}
|
||||
}
|
||||
if(menu_open)bob_gui_menu_draw(menu_rect,menu_items,3,24,menu_state[0]);
|
||||
if(launcher_open||help_open)bob_gfx_fill_rect(0,1,80,24,'.',1);
|
||||
if(launcher_open) {
|
||||
bob_gui_window(18,3,44,19,"Application launcher",
|
||||
"N/P or arrows select; R runs; Esc closes.","",1);
|
||||
for(int row=0;row<app_count&&row<8;row++) {
|
||||
int icon='A'+((row%14+1)<<8);
|
||||
if(row==app_selected)bob_gfx_fill_rect(21,7+row,38,1,' ',1);
|
||||
bob_gfx_blit_color(22,7+row,1,1,&icon);
|
||||
bob_gfx_text(25,7+row,app_names+row*24,row==app_selected?15:7);
|
||||
}
|
||||
bob_gui_button_draw(close_button[0],close_button[1],close_button[2],close_button[3],"Close",close_button_state[0],close_button_state[1]);
|
||||
bob_gui_button_draw(launch_button[0],launch_button[1],launch_button[2],launch_button[3],"Launch",launch_button_state[0],launch_button_state[1]);
|
||||
}
|
||||
if(help_open) {
|
||||
bob_gui_window(18,3,44,19,"Desktop help","","",1);
|
||||
bob_gfx_bitmap_text(28,6,"HELP",14);
|
||||
bob_gfx_text(23,14,"Tab moves through fields and files.",15);
|
||||
bob_gfx_text(23,15,"E edits a selected text file; X deletes.",15);
|
||||
bob_gfx_text(23,16,"Ctrl+S saves; Esc closes this help.",15);
|
||||
bob_gfx_text(23,17,"Wheel scrolls text; list wheel selects.",15);
|
||||
bob_gui_button_draw(help_close[0],help_close[1],help_close[2],help_close[3],"Close",help_close_state[0],help_close_state[1]);
|
||||
}
|
||||
overlay_was_open=menu_open||launcher_open||help_open;
|
||||
bob_gfx_present();
|
||||
if(bob_event_wait(event)!=1)break;
|
||||
if(menu_open) {
|
||||
int action=bob_gui_menu_event(menu_rect,3,menu_state,event);
|
||||
if(action==-2)menu_open=0;
|
||||
else if(event[0]==BOB_EVENT_MOUSE_BUTTON_DOWN&&
|
||||
!bob_gui_window_hit(event[2],event[3],menu_rect))menu_open=0;
|
||||
else if(action==0) {
|
||||
gui_open_selected_text(selected_file,file_slots,file_count,file_name,
|
||||
file_name_text,file_text,text_state,text_area,wm_state,wm_windows,wm_order,message_b);
|
||||
menu_open=0;
|
||||
} else if(action==1) {
|
||||
int size,kind;
|
||||
if(selected_file>=0&&selected_file<file_count) {
|
||||
kind=bob_file_list(file_slots[selected_file],file_name,24,&size);
|
||||
if(kind==BOB_FILE_KIND_TEXT){delete_confirm=1;bob_strcpy(message_b,"Delete? Y/N");}
|
||||
else bob_strcpy(message_b,"Text files only.");
|
||||
} else bob_strcpy(message_b,"No file selected.");
|
||||
menu_open=0;
|
||||
} else if(action==2)menu_open=0;
|
||||
continue;
|
||||
}
|
||||
if(help_open) {
|
||||
if(event[0]==BOB_EVENT_MOUSE_MOVE)bob_gui_button_event(help_close,help_close_state,event);
|
||||
else if(event[0]==BOB_EVENT_MOUSE_BUTTON_DOWN)bob_gui_button_event(help_close,help_close_state,event);
|
||||
else if(event[0]==BOB_EVENT_MOUSE_BUTTON_UP) {
|
||||
if(bob_gui_button_event(help_close,help_close_state,event))help_open=0;
|
||||
} else if(event[0]==BOB_EVENT_CHAR||event[0]==BOB_EVENT_KEY_DOWN)help_open=0;
|
||||
continue;
|
||||
}
|
||||
if(launcher_open) {
|
||||
if(event[0]==BOB_EVENT_MOUSE_MOVE) {
|
||||
bob_gui_button_event(close_button,close_button_state,event);
|
||||
bob_gui_button_event(launch_button,launch_button_state,event);
|
||||
} else if(event[0]==BOB_EVENT_MOUSE_BUTTON_DOWN) {
|
||||
int row=event[3]-7;
|
||||
if(event[2]>=21&&event[2]<59&&row>=0&&row<app_count&&row<8)app_selected=row;
|
||||
bob_gui_button_event(close_button,close_button_state,event);
|
||||
bob_gui_button_event(launch_button,launch_button_state,event);
|
||||
} else if(event[0]==BOB_EVENT_MOUSE_BUTTON_UP) {
|
||||
int close=bob_gui_button_event(close_button,close_button_state,event);
|
||||
int launch=bob_gui_button_event(launch_button,launch_button_state,event);
|
||||
if(close)launcher_open=0;
|
||||
else if(launch){gui_launch_app(app_selected,app_names,app_count,message_b);launcher_open=0;}
|
||||
} else if(event[0]==BOB_EVENT_KEY_DOWN) {
|
||||
if(event[1]==256&&app_selected>0)app_selected--;
|
||||
else if(event[1]==257&&app_selected+1<app_count&&app_selected<7)app_selected++;
|
||||
} else if(event[0]==BOB_EVENT_CHAR) {
|
||||
if(event[1]==27)launcher_open=0;
|
||||
else if((event[1]=='n'||event[1]=='j')&&app_selected+1<app_count&&app_selected<7)app_selected++;
|
||||
else if((event[1]=='p'||event[1]=='k')&&app_selected>0)app_selected--;
|
||||
else if(event[1]=='r'){gui_launch_app(app_selected,app_names,app_count,message_b);launcher_open=0;}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if(event[0]==BOB_EVENT_CHAR&&event[1]==27){running=0;break;}
|
||||
target_window=bob_wm_dispatch(wm_state,wm_windows,wm_order,event,routed_event);
|
||||
if(target_window<0)continue;
|
||||
for(int i=0;i<4;i++)event[i]=routed_event[i];
|
||||
gui_wm_sync_rects(windows,wm_windows);
|
||||
gui_place_editor_widgets(windows,name_field,text_area,button);
|
||||
bob_wm_invalidate(wm_state,wm_windows,wm_order,target_window);
|
||||
if(event[0]==BOB_EVENT_MOUSE_MOVE||event[0]==BOB_EVENT_MOUSE_BUTTON_DOWN||
|
||||
event[0]==BOB_EVENT_MOUSE_BUTTON_UP||event[0]==BOB_EVENT_MOUSE_WHEEL) {
|
||||
event[2]+=windows[target_window*4];event[3]+=windows[target_window*4+1];
|
||||
}
|
||||
if(event[0]==BOB_EVENT_MOUSE_MOVE) {
|
||||
mouse_x=event[2];mouse_y=event[3];
|
||||
if(wm_state[2]==0)bob_gui_button_event(button,button_state,event);
|
||||
else button_state[0]=0;
|
||||
if(wm_state[2]==1&&delete_confirm) {
|
||||
bob_gui_button_event(delete_yes,delete_yes_state,event);
|
||||
bob_gui_button_event(delete_no,delete_no_state,event);
|
||||
} else {delete_yes_state[0]=0;delete_no_state[0]=0;}
|
||||
continue;
|
||||
}
|
||||
if(event[0]==BOB_EVENT_MOUSE_WHEEL) {
|
||||
mouse_x=event[2];mouse_y=event[3];
|
||||
if(wm_state[2]==0&&bob_gui_window_hit(mouse_x,mouse_y,text_area)) {
|
||||
name_state[0]=0;bob_wm_focus(wm_state,wm_windows,wm_order,0);
|
||||
bob_gui_text_area_event(text_area,file_text,text_state,512,event);
|
||||
} else if(wm_state[2]==1&&bob_gui_window_hit(mouse_x,mouse_y,windows+4)) {
|
||||
if(mouse_y>=windows[5]+4&&mouse_y<windows[5]+10) {
|
||||
int row=event[1]>0?selected_file-1:selected_file+1;
|
||||
if(row>=0&&row<file_count)
|
||||
gui_select_file(row,file_slots,file_count,&selected_file,message_b,preview,&preview_length,&preview_scroll);
|
||||
} else if(!delete_confirm&&mouse_y>=windows[5]+11&&mouse_y<windows[5]+18) {
|
||||
if(event[1]>0&&preview_scroll>0)preview_scroll--;
|
||||
else if(event[1]<0&&gui_preview_offset(preview,preview_length,preview_scroll+1)<preview_length)preview_scroll++;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if(event[0]==BOB_EVENT_MOUSE_BUTTON_DOWN) {
|
||||
int hit=target_window;
|
||||
mouse_x=event[2];mouse_y=event[3];
|
||||
if(hit==1&&mouse_y==windows[5]+3&&mouse_x>=windows[4]+2&&mouse_x<windows[4]+6) {
|
||||
menu_open=1;menu_state[0]=0;menu_state[1]=-1;continue;
|
||||
}
|
||||
if(hit==1&&mouse_y>=windows[5]+4&&mouse_y<windows[5]+10) {
|
||||
int row=file_scroll+mouse_y-(windows[5]+4);
|
||||
if(row<file_count) {
|
||||
delete_confirm=0;
|
||||
gui_select_file(row,file_slots,file_count,&selected_file,message_b,preview,&preview_length,&preview_scroll);
|
||||
}
|
||||
}
|
||||
if(wm_state[2]==1&&delete_confirm) {
|
||||
bob_gui_button_event(delete_yes,delete_yes_state,event);
|
||||
bob_gui_button_event(delete_no,delete_no_state,event);
|
||||
}
|
||||
if(wm_state[2]==0) {
|
||||
bob_gui_button_event(button,button_state,event);
|
||||
bob_gui_text_field_event(name_field,file_name_text,name_state,24,event);
|
||||
bob_gui_text_area_event(text_area,file_text,text_state,512,event);
|
||||
} else {button_state[0]=0;button_state[1]=0;name_state[0]=0;text_state[0]=0;}
|
||||
continue;
|
||||
}
|
||||
if(event[0]==BOB_EVENT_MOUSE_BUTTON_UP) {
|
||||
if(delete_confirm&&wm_state[2]==1&&bob_gui_button_event(delete_yes,delete_yes_state,event)) {
|
||||
if(gui_delete_selected(selected_file,file_slots,file_count,file_name)==0) {
|
||||
selected_file=-1;selection_initialized=1;preview_length=-1;preview_scroll=0;
|
||||
bob_strcpy(message_b,"Deleted.");
|
||||
} else bob_strcpy(message_b,"Delete failed.");
|
||||
delete_confirm=0;
|
||||
} else if(delete_confirm&&wm_state[2]==1&&bob_gui_button_event(delete_no,delete_no_state,event)) {
|
||||
delete_confirm=0;
|
||||
if(selected_file>=0)gui_select_file(selected_file,file_slots,file_count,&selected_file,message_b,preview,&preview_length,&preview_scroll);
|
||||
}
|
||||
if(wm_state[2]==0&&bob_gui_button_event(button,button_state,event)) {
|
||||
if(bob_file_write(file_name_text,file_text,bob_strlen(file_text))==0) {
|
||||
bob_strcpy(message_b,"Saved file.");selected_file=-1;selection_initialized=0;
|
||||
} else bob_strcpy(message_b,"Save failed; check name.");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if(event[0]==BOB_EVENT_KEY_DOWN) {
|
||||
if(wm_state[2]==0) {
|
||||
if(name_state[0])bob_gui_text_field_event(name_field,file_name_text,name_state,24,event);
|
||||
else if(text_state[0])bob_gui_text_area_event(text_area,file_text,text_state,512,event);
|
||||
}
|
||||
else if(event[1]==256&&preview_scroll>0)preview_scroll--;
|
||||
else if(event[1]==257&&gui_preview_offset(preview,preview_length,preview_scroll+1)<preview_length)preview_scroll++;
|
||||
continue;
|
||||
}
|
||||
if(event[0]!=BOB_EVENT_CHAR)continue;
|
||||
if(event[1]==27)running=0;
|
||||
else if(event[1]=='\t') {
|
||||
if(wm_state[2]==0&&name_state[0]){name_state[0]=0;text_state[0]=1;text_state[1]=bob_strlen(file_text);}
|
||||
else if(wm_state[2]==0&&text_state[0]){text_state[0]=0;bob_wm_focus(wm_state,wm_windows,wm_order,1);}
|
||||
else {bob_wm_focus(wm_state,wm_windows,wm_order,0);name_state[0]=1;name_state[1]=bob_strlen(file_name_text);text_state[0]=0;}
|
||||
}
|
||||
else if(event[1]=='?') {
|
||||
help_open=1;help_close_state[0]=0;help_close_state[1]=0;
|
||||
}
|
||||
else if(wm_state[2]==1&&event[1]=='a') {
|
||||
launcher_open=1;app_selected=0;launch_button_state[0]=0;launch_button_state[1]=0;
|
||||
close_button_state[0]=0;close_button_state[1]=0;
|
||||
bob_strcpy(message_b,app_count?"Choose an app.":"No stored apps.");
|
||||
}
|
||||
else if(wm_state[2]==1&&event[1]=='m') {menu_open=1;menu_state[0]=0;menu_state[1]=-1;}
|
||||
else if(event[1]==19) {
|
||||
if(bob_file_write(file_name_text,file_text,bob_strlen(file_text))==0) {
|
||||
bob_strcpy(message_b,"Saved file.");selected_file=-1;selection_initialized=0;
|
||||
} else bob_strcpy(message_b,"Save failed; check name.");
|
||||
}
|
||||
else if(wm_state[2]==1&&event[1]=='e') {
|
||||
gui_open_selected_text(selected_file,file_slots,file_count,file_name,
|
||||
file_name_text,file_text,text_state,text_area,wm_state,wm_windows,wm_order,message_b);
|
||||
}
|
||||
else if(wm_state[2]==1&&delete_confirm&&event[1]=='y') {
|
||||
if(gui_delete_selected(selected_file,file_slots,file_count,file_name)==0) {
|
||||
selected_file=-1;selection_initialized=1;preview_length=-1;preview_scroll=0;
|
||||
bob_strcpy(message_b,"Deleted.");
|
||||
} else bob_strcpy(message_b,"Delete failed.");
|
||||
delete_confirm=0;
|
||||
} else if(wm_state[2]==1&&delete_confirm&&event[1]=='n') {
|
||||
delete_confirm=0;
|
||||
if(selected_file>=0)gui_select_file(selected_file,file_slots,file_count,&selected_file,message_b,preview,&preview_length,&preview_scroll);
|
||||
bob_strcpy(message_b,"Delete cancelled.");
|
||||
} else if(wm_state[2]==1&&delete_confirm) {
|
||||
}
|
||||
else if(wm_state[2]==1&&event[1]=='n'&&selected_file+1<file_count) {
|
||||
gui_select_file(selected_file+1,file_slots,file_count,&selected_file,message_b,preview,&preview_length,&preview_scroll);
|
||||
} else if(wm_state[2]==1&&event[1]=='p'&&selected_file>0) {
|
||||
gui_select_file(selected_file-1,file_slots,file_count,&selected_file,message_b,preview,&preview_length,&preview_scroll);
|
||||
} else if(wm_state[2]==1&&event[1]=='x'&&selected_file>=0) {
|
||||
int selected_size,selected_kind;
|
||||
selected_kind=bob_file_list(file_slots[selected_file],file_name,24,&selected_size);
|
||||
if(selected_kind==0){delete_confirm=1;delete_yes_state[0]=0;delete_yes_state[1]=0;delete_no_state[0]=0;delete_no_state[1]=0;bob_strcpy(message_b,"Delete? Y/N");}
|
||||
else bob_strcpy(message_b,"Text files only.");
|
||||
} else if(wm_state[2]==1&&event[1]=='u'&&preview_scroll>0)preview_scroll--;
|
||||
else if(wm_state[2]==1&&event[1]=='d'&&gui_preview_offset(preview,preview_length,preview_scroll+1)<preview_length)preview_scroll++;
|
||||
else if(wm_state[2]==0) {
|
||||
if(name_state[0])bob_gui_text_field_event(name_field,file_name_text,name_state,24,event);
|
||||
else bob_gui_text_area_event(text_area,file_text,text_state,512,event);
|
||||
}
|
||||
else if(event[1]==8||event[1]==127) {
|
||||
if(wm_state[2]==1&&length_b>0)message_b[--length_b]=0;
|
||||
} else if(event[1]>=32&&event[1]<127) {
|
||||
if(wm_state[2]==1&&length_b<30) {
|
||||
message_b[length_b++]=event[1];message_b[length_b]=0;
|
||||
}
|
||||
}
|
||||
}
|
||||
if(bob_gfx_leave())return 2;
|
||||
bob_puts("bob!");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
#include "bob.h"
|
||||
#include "bob_fs.h"
|
||||
#include "bob_process.h"
|
||||
#include "bob_string.h"
|
||||
|
||||
static int append(char *buffer,int *length,char value) {
|
||||
if(*length>=126)return 0;
|
||||
buffer[(*length)++]=value;buffer[*length]=0;return 1;
|
||||
}
|
||||
|
||||
static void print_number(int value) {
|
||||
char digits[12];int count=0;
|
||||
if(value<0){bob_putc('-');value=-value;}
|
||||
do {digits[count++]=(char)('0'+value%10);value/=10;} while(value&&count<11);
|
||||
while(count)bob_putc(digits[--count]);
|
||||
bob_putc('\n');
|
||||
}
|
||||
|
||||
int main(int argc,char **argv) {
|
||||
int i,size,kind,length=0,status,child_status=-1;
|
||||
char name[24],arguments[128];
|
||||
arguments[0]=0;
|
||||
if(argc<2) {
|
||||
bob_puts("Native apps:");
|
||||
for(i=0;i<8;i++) {
|
||||
kind=bob_file_list(i,name,24,&size);
|
||||
if(kind==3){bob_puts(name);bob_putc('\n');}
|
||||
}
|
||||
bob_puts("Usage: run launcher APP [ARG ...]");
|
||||
return 0;
|
||||
}
|
||||
for(i=2;i<argc;i++) {
|
||||
int j;
|
||||
if(i>2&&!append(arguments,&length,' '))return 1;
|
||||
if(!append(arguments,&length,'"'))return 1;
|
||||
for(j=0;argv[i][j];j++) {
|
||||
if((argv[i][j]=='"'||argv[i][j]=='\\')&&!append(arguments,&length,'\\'))return 1;
|
||||
if(!append(arguments,&length,argv[i][j]))return 1;
|
||||
}
|
||||
if(!append(arguments,&length,'"'))return 1;
|
||||
}
|
||||
status=bob_app_run(argv[1],arguments,&child_status);
|
||||
if(status==-1)bob_puts("App not found.");
|
||||
else if(status==-2)bob_puts("File is not a native bob32 app.");
|
||||
else if(status==-4)bob_puts("Invalid app or arguments.");
|
||||
else if(status==-5)bob_puts("Not enough emulator memory to launch app.");
|
||||
else if(status==-3)bob_puts("App timed out.");
|
||||
else if(status<-5)bob_puts("App could not be launched.");
|
||||
else {bob_puts("Child exit:");print_number(child_status);}
|
||||
return status<0?1:child_status;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
#include "bob.h"
|
||||
#include "bob_fs.h"
|
||||
#include "bob_string.h"
|
||||
|
||||
static void write_text(const char *text) {
|
||||
while (*text) bob_putc(*text++);
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
char name[24];
|
||||
char number[12];
|
||||
int size;
|
||||
int kind;
|
||||
int i;
|
||||
for (i = 0; i < 8; i++) {
|
||||
kind = bob_file_list(i, name, 24, &size);
|
||||
if (kind < 0) continue;
|
||||
write_text(name);
|
||||
bob_putc(' ');
|
||||
bob_format_int(size, number, 12);
|
||||
write_text(number);
|
||||
bob_putc(' ');
|
||||
if (kind == 0) write_text("text");
|
||||
else if (kind == 3) write_text("native app");
|
||||
else write_text("program");
|
||||
bob_putc('\n');
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
#include "bob.h"
|
||||
#include "bob_fs.h"
|
||||
|
||||
static int same_text(const char *left,const char *right) {
|
||||
int i=0;while(left[i]&&left[i]==right[i])i++;
|
||||
return left[i]==right[i];
|
||||
}
|
||||
|
||||
/* 1=text note, 0=missing, -1=name belongs to a non-text file. */
|
||||
static int note_kind(const char *wanted) {
|
||||
int kind=bob_file_kind(wanted);
|
||||
if(kind<0)return 0;
|
||||
return kind==BOB_FILE_KIND_TEXT?1:-1;
|
||||
}
|
||||
|
||||
static int join_arguments(char *text,int *length,int argc,char **argv,int start) {
|
||||
*length=0;
|
||||
for(int i=start;i<argc;i++) {
|
||||
if(i>start) {
|
||||
if(*length>=511)return 0;
|
||||
text[(*length)++]=' ';
|
||||
}
|
||||
for(int j=0;argv[i][j];j++) {
|
||||
if(*length>=511)return 0;
|
||||
text[(*length)++]=argv[i][j];
|
||||
}
|
||||
}
|
||||
text[*length]=0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
char text[512];
|
||||
int length;
|
||||
int i;
|
||||
if (argc < 2) {
|
||||
bob_puts("Usage: notes show NAME | put/edit NAME [TEXT] | add NAME [TEXT] | delete NAME");
|
||||
return 1;
|
||||
}
|
||||
if (same_text(argv[1], "show") && argc == 3) {
|
||||
if(note_kind(argv[2])<0){bob_puts("Not a text note.");return 1;}
|
||||
length = bob_file_read(argv[2], text, 512);
|
||||
if (length < 0) { bob_puts("Note not found."); return 1; }
|
||||
for (i = 0; i < length; i++) bob_putc(text[i]);
|
||||
bob_putc('\n');
|
||||
return 0;
|
||||
}
|
||||
if ((same_text(argv[1], "put")||same_text(argv[1], "edit")) && argc >= 3) {
|
||||
if(note_kind(argv[2])<0){bob_puts("Not a text note.");return 1;}
|
||||
if (argc == 3) {
|
||||
bob_puts("Note text:");
|
||||
bob_gets(text, 512);
|
||||
length=0;while(text[length])length++;
|
||||
} else if(!join_arguments(text,&length,argc,argv,3)) {
|
||||
bob_puts("Note is too long (511 characters maximum).");return 1;
|
||||
}
|
||||
if (bob_file_write(argv[2], text, length)) { bob_puts("Cannot save note."); return 1; }
|
||||
bob_puts("Saved.");
|
||||
return 0;
|
||||
}
|
||||
if (same_text(argv[1], "add") && argc >= 3) {
|
||||
int kind=note_kind(argv[2]);
|
||||
if(kind<0){bob_puts("Not a text note.");return 1;}
|
||||
if(kind) {
|
||||
length=bob_file_read(argv[2],text,512);
|
||||
if(length<0){bob_puts("Cannot read note.");return 1;}
|
||||
} else {length=0;text[0]=0;}
|
||||
if(argc==3) {
|
||||
if(length&&text[length-1]!='\n') {
|
||||
if(length>=511){bob_puts("Note is too long (511 characters maximum).");return 1;}
|
||||
text[length++]='\n';
|
||||
}
|
||||
bob_puts("Add text:");bob_gets(text+length,512-length);
|
||||
while(text[length])length++;
|
||||
} else {
|
||||
if(length&&text[length-1]!='\n') {
|
||||
if(length>=511){bob_puts("Note is too long (511 characters maximum).");return 1;}
|
||||
text[length++]='\n';
|
||||
}
|
||||
for(i=3;i<argc;i++) {
|
||||
if(i>3) {
|
||||
if(length>=511){bob_puts("Note is too long (511 characters maximum).");return 1;}
|
||||
text[length++]=' ';
|
||||
}
|
||||
for(int j=0;argv[i][j];j++) {
|
||||
if(length>=511){bob_puts("Note is too long (511 characters maximum).");return 1;}
|
||||
text[length++]=argv[i][j];
|
||||
}
|
||||
}
|
||||
text[length]=0;
|
||||
}
|
||||
if(bob_file_write(argv[2],text,length)){bob_puts("Cannot save note.");return 1;}
|
||||
bob_puts("Saved.");return 0;
|
||||
}
|
||||
if (same_text(argv[1], "delete") && argc == 3) {
|
||||
if(note_kind(argv[2])!=1){bob_puts("Not a text note.");return 1;}
|
||||
if (bob_file_delete(argv[2])) { bob_puts("Note not found."); return 1; }
|
||||
bob_puts("Deleted.");
|
||||
return 0;
|
||||
}
|
||||
bob_puts("Usage: notes show NAME | put/edit NAME [TEXT] | add NAME [TEXT] | delete NAME");
|
||||
return 1;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
#include "bob.h"
|
||||
#include "bob_fs.h"
|
||||
#include "bob_system.h"
|
||||
#include "bob_string.h"
|
||||
|
||||
static void write_text(const char *text) {
|
||||
while (*text) bob_putc(*text++);
|
||||
}
|
||||
|
||||
static void show_value(const char *label, int value) {
|
||||
char number[12];
|
||||
write_text(label);
|
||||
bob_format_int(value, number, 12);
|
||||
write_text(number);
|
||||
bob_putc('\n');
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
int info[6];
|
||||
int capabilities[5];
|
||||
if (bob_system_info(info, 6) != 6 || info[0] != BOB_FS_API_VERSION) {
|
||||
bob_puts("System information service unavailable.");
|
||||
return 1;
|
||||
}
|
||||
if (bob_system_capabilities(capabilities, 4) != -1) {
|
||||
bob_puts("System capability validation failed.");
|
||||
return 2;
|
||||
}
|
||||
if (bob_system_capabilities(capabilities, 5) != 5 ||
|
||||
capabilities[0] != BOB_SYSTEM_API_VERSION) {
|
||||
bob_puts("System capabilities unavailable.");
|
||||
return 3;
|
||||
}
|
||||
bob_puts("bob32 system information");
|
||||
show_value("System API version: ", capabilities[0]);
|
||||
bob_puts((capabilities[1] & BOB_SYSTEM_DEVICE_CELL_FRAMEBUFFER) ?
|
||||
"Cell framebuffer: available" : "Cell framebuffer: unavailable");
|
||||
show_value("Display width (cells): ", capabilities[2]);
|
||||
show_value("Display height (cells): ", capabilities[3]);
|
||||
bob_puts((capabilities[4] & BOB_SYSTEM_INPUT_KEYBOARD) ?
|
||||
"Keyboard input: available" : "Keyboard input: unavailable");
|
||||
bob_puts((capabilities[4] & BOB_SYSTEM_INPUT_MOUSE) ?
|
||||
"Mouse input: available" : "Mouse input: unavailable");
|
||||
show_value("Application address space (words): ", info[1]);
|
||||
show_value("Mapped application pages: ", info[2]);
|
||||
show_value("Guest files: ", info[3]);
|
||||
show_value("Filesystem words used: ", info[4]);
|
||||
show_value("Filesystem words free: ", info[5]);
|
||||
return 0;
|
||||
}
|
||||
Binary file not shown.
+124
@@ -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
@@ -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
@@ -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
@@ -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
|
||||
@@ -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
@@ -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
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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
File diff suppressed because it is too large.
Load diff
@@ -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
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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
@@ -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
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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
@@ -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
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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
|
||||
@@ -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
@@ -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
|
||||
@@ -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
@@ -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,®ion,&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;
|
||||
}
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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
@@ -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;
|
||||
}
|
||||
@@ -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
@@ -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);
|
||||
}
|
||||
@@ -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
@@ -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;
|
||||
}
|
||||
@@ -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
@@ -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;
|
||||
}
|
||||
@@ -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
|
||||
@@ -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
@@ -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);
|
||||
}
|
||||
@@ -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
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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
@@ -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;
|
||||
}
|
||||
@@ -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
|
||||
@@ -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
@@ -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
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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
|
||||
Binary file not shown.
+2229
-1786
File diff suppressed because it is too large.
Load diff
+80
-7
@@ -29,7 +29,8 @@ unbuffered keys, converts Enter to newline, and treats Ctrl+D as EOF.
|
||||
Ctrl+Z is an ordinary control character: shell EOF, full-screen editor undo.
|
||||
Redirected input uses getchar. `bob_terminal()` (trap 9) returns 1 only when
|
||||
both input/output are native Windows console handles; otherwise 0. Shell
|
||||
history, completion and editing are guest code in `kernel/input.c`. ANSI key
|
||||
history, completion and editing are guest code in `kernel/input.c`; the shell's
|
||||
`history` command lists the same four recent entries. ANSI key
|
||||
sequences in redirected regression fixtures exercise the same guest actions.
|
||||
`bob_columns()` (trap 10) reports the console buffer width, or 80 as fallback.
|
||||
The shell scrolls a long input line horizontally to keep redraw within it.
|
||||
@@ -74,9 +75,10 @@ returning its slot or -1 for a bad name, length or a full table. Kind 0 is text;
|
||||
kind 1 is machine code, kind 2 is resident bob32 C code, and kind 3 is a packed
|
||||
native B32K v2 image. Its copy appends a zero word, which is not part of length.
|
||||
Names hold at most 23 characters. bob16 retains eight fixed 511-word slots;
|
||||
bob32 packs files into a shared 4,096-word content region. Text files remain
|
||||
limited to 511 words; resident programs and native images can use the remaining
|
||||
shared capacity (up to 4,095 words per file). Valid slot indices are 0..7.
|
||||
bob32 packs files into a protected 8,192-word content region at `0x1E000`,
|
||||
between the kernel and supervised-app regions. Text files remain limited to 511
|
||||
words; resident programs and native images can use the remaining shared capacity
|
||||
(up to 8,191 words per file). Valid slot indices are 0..7.
|
||||
These are internal kernel APIs.
|
||||
|
||||
Failed size/name validation does not overwrite an existing file. Edits start
|
||||
@@ -131,16 +133,87 @@ kernel code; ordinary shell programs use bob_run for recovery and write checks.
|
||||
See [the OS guide](../C_OS.md) for commands, examples and C subset limits.
|
||||
|
||||
In bob32 mode, `import32 HOST_PATH NAME` validates and packs a B32K v2 image
|
||||
into a guest RAM file; `run NAME` loads and executes it. B32S version 2
|
||||
snapshots preserve packed files; version 1 fixed-slot snapshots remain readable
|
||||
and are converted to the packed layout on restore. `run32 HOST_PATH` remains
|
||||
into a guest RAM file; `run NAME` loads and executes it. B32S version 3
|
||||
snapshots preserve the expanded filesystem; versions 1 and 2 remain readable
|
||||
and are migrated to the current storage layout on restore. `run32 HOST_PATH` remains
|
||||
available for direct host-path launches.
|
||||
|
||||
Native C applications can include `bob_string.h` for small app-side string
|
||||
and parsing helpers. It provides bounded integer formatting, status-returning
|
||||
decimal/hex parsing, and in-place quoted tokenization without depending on the
|
||||
kernel's private runtime functions.
|
||||
`bob_native.h` is an optional convenience include for the common native API
|
||||
surface: core `bob.h` calls, strings, app-managed memory, filesystem, process,
|
||||
time, and input events. Graphics and GUI remain opt-in via `bob_gfx.h` and
|
||||
`bob_gui.h` so text-only apps do not pull in widget code.
|
||||
`bob_memory.h` provides a caller-owned word arena. Keep an integer buffer and a
|
||||
used-word counter, request word counts with `bob_arena_alloc`, inspect
|
||||
used/remaining capacity, and reset the counter when its allocations are no longer
|
||||
needed. Exhaustion and invalid sizes return null; no OS-global heap is reserved.
|
||||
Native apps may define `main(int argc, char **argv)`; when launched by guest
|
||||
filename, `argv[0]` is that filename and `argc` includes it. `run app first
|
||||
"two words"` groups quoted words; backslash escapes the following character
|
||||
and `""` supplies an empty argument.
|
||||
|
||||
`bob_fs.h` exposes the version 1 native-app filesystem service through
|
||||
`bob_file_list`, `bob_file_read`, `bob_file_write`, `bob_file_delete`,
|
||||
`bob_file_read_words`, `bob_file_write_words`, and `bob_file_kind`. Listing
|
||||
returns kind and word-size metadata; `bob_file_kind` queries the kind directly
|
||||
by name. Text reads/writes handle up to 511 characters. Word-file
|
||||
helpers preserve binary values for bob16 and bob32 program kinds. Native B32K
|
||||
images can be read as words, but must use the validated `import32` path to enter
|
||||
the filesystem as runnable apps. Applications pass buffers in their own memory,
|
||||
while the emulator validates and copies data to keep kernel tables private.
|
||||
Files remain in the guest RAM filesystem and follow the normal B32S save/restore
|
||||
flow. B32S v3 stores the expanded payload; v1 fixed-slot and v2 packed snapshots
|
||||
remain readable.
|
||||
`bob_system_info` reports the service version, app address-space size, mapped
|
||||
pages, and filesystem slot/word usage through the same versioned boundary.
|
||||
|
||||
`bob_process.h` adds `bob_app_run(name, arguments, &exit_code)` through version 1
|
||||
service operation 6. It launches a stored kind-3 B32K image with shell-style
|
||||
quoted arguments, preserves the suspended caller's sparse application memory,
|
||||
and separates launch errors from the child's exit code. Nested launches are
|
||||
limited to eight active app frames. The API returns -1 when the app name is
|
||||
missing, -2 for a non-native file, -4 for invalid data, and -5 when memory is
|
||||
unavailable. The `launcher` app lists stored native images and can run one with
|
||||
`run launcher APP [ARG ...]`.
|
||||
|
||||
`bob_time.h` exposes version 1 time operation 7. `bob_time_utc_seconds(words)`
|
||||
fills two 32-bit words with the low and high halves of UTC seconds since the
|
||||
Unix epoch and returns 2. It returns a negative status for an invalid request.
|
||||
|
||||
`bob_gfx.h` uses that OS boundary for an 80x25 cell framebuffer: enter/query,
|
||||
clear, pixel, filled rectangle, line, text, transparent bitmap blit, present,
|
||||
and leave. Each cell carries a 16-color foreground. Draw calls update a back
|
||||
buffer; present renders it, and supervised app exit closes an unclosed canvas.
|
||||
`bob_gfx_blit_color` accepts transparent row-major cells with an ASCII character
|
||||
in bits 0..7 and a foreground color in bits 8..11; invalid cell values reject
|
||||
the whole call before drawing.
|
||||
`bob_font.h` adds an opt-in 5x7 bitmap font helper. `bob_gfx_bitmap_text`
|
||||
rasterizes uppercase letters, digits, space, and common punctuation into the
|
||||
canvas via the colored bitmap service; lowercase letters map to uppercase and
|
||||
unsupported characters use `?`.
|
||||
`bob_event.h` provides `bob_event_wait` and nonblocking `bob_event_poll` with
|
||||
four-word events. Poll returns 1 for an event or 0 when the console queue is
|
||||
empty; redirected input is left for the blocking wait and is not peeked.
|
||||
Version 1 reports typed characters, special-key presses, key releases, mouse
|
||||
movement and mouse button transitions when the Windows console provides those
|
||||
records. Mouse coordinates are console-cell coordinates; redirected input
|
||||
remains character based.
|
||||
`bob_event_queue.h` adds an app-owned FIFO for those same four-word events.
|
||||
Initialize a two-word `{head,count}` state, allocate four storage words per
|
||||
queue slot, then use `bob_event_queue_push`/`pop`; push returns 0 when full
|
||||
without overwriting older events, and pop returns 0 when empty. Invalid
|
||||
capacity/state returns -1. The queue is optional and requires no OS memory.
|
||||
`bob_wm.h` adds a small reusable window manager over caller-provided fixed
|
||||
arrays. Initialize it with a window limit and screen size, then use create,
|
||||
destroy, focus, raise, move, show/hide, and invalidate operations. Dispatch
|
||||
returns a recipient ID, routes keys to the focused visible window, raises the
|
||||
topmost clicked window, captures title-bar drags, and supplies window-local
|
||||
mouse coordinates. `bob_wm_begin_draw` starts a redraw pass and repeated
|
||||
`bob_wm_next_dirty` calls yield visible windows bottom-to-top; geometry and
|
||||
stacking changes request a full redraw, while invalidation also marks any
|
||||
overlapping windows so they repaint correctly. The manager stores no app-specific
|
||||
titles or callbacks; applications keep their own state and draw their own
|
||||
contents through `bob_gui.h` and `bob_gfx.h`.
|
||||
@@ -10,6 +10,8 @@ int bob_run(int entry);
|
||||
int bob_run_image(const char *path);
|
||||
int bob_import_image(int *descriptor);
|
||||
int bob_run_native(const int *descriptor);
|
||||
int bob_os_service(int *request);
|
||||
int bob_fs_register(int *descriptor);
|
||||
int bob_snapshot(int *descriptor, int operation);
|
||||
int bob_key(void);
|
||||
int bob_terminal(void);
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
#ifndef BOB_EVENT_H
|
||||
#define BOB_EVENT_H
|
||||
|
||||
#include "bob.h"
|
||||
|
||||
#define BOB_EVENT_API_VERSION 1
|
||||
#define BOB_EVENT_KEY_DOWN 1
|
||||
#define BOB_EVENT_CHAR 2
|
||||
#define BOB_EVENT_KEY_UP 3
|
||||
#define BOB_EVENT_MOUSE_MOVE 4
|
||||
#define BOB_EVENT_MOUSE_BUTTON_DOWN 5
|
||||
#define BOB_EVENT_MOUSE_BUTTON_UP 6
|
||||
#define BOB_EVENT_MOUSE_WHEEL 7
|
||||
#define BOB_EVENT_POLL 28
|
||||
#define BOB_MOUSE_BUTTON_LEFT 1
|
||||
#define BOB_MOUSE_BUTTON_RIGHT 2
|
||||
#define BOB_MOUSE_BUTTON_MIDDLE 4
|
||||
|
||||
/* Four words: type, key/character/buttons/wheel delta, x, y. Blocks until input or EOF. */
|
||||
int bob_event_wait(int *event) {
|
||||
int request[7];
|
||||
request[0]=(BOB_EVENT_API_VERSION << 16) | 26;
|
||||
request[1]=(int)event;request[2]=4;
|
||||
request[3]=0;request[4]=0;request[5]=0;request[6]=0;
|
||||
return bob_os_service(request);
|
||||
}
|
||||
|
||||
/* Returns 1 with an event, 0 when no console event is available, negative on bad input. */
|
||||
int bob_event_poll(int *event) {
|
||||
int request[7];
|
||||
request[0]=(BOB_EVENT_API_VERSION << 16) | BOB_EVENT_POLL;
|
||||
request[1]=(int)event;request[2]=4;
|
||||
request[3]=0;request[4]=0;request[5]=0;request[6]=0;
|
||||
return bob_os_service(request);
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,36 @@
|
||||
#ifndef BOB_EVENT_QUEUE_H
|
||||
#define BOB_EVENT_QUEUE_H
|
||||
|
||||
#include "bob_event.h"
|
||||
|
||||
/* Caller-owned FIFO state is head,count; storage holds capacity four-word events. */
|
||||
void bob_event_queue_init(int *state) {
|
||||
if(!state)return;
|
||||
state[0]=0;state[1]=0;
|
||||
}
|
||||
|
||||
/* Push returns 1 on success, 0 if full, and -1 for invalid state or arguments. */
|
||||
int bob_event_queue_push(int *state,int *storage,int capacity,const int *event) {
|
||||
int tail;
|
||||
if(!state||!storage||!event||capacity<1||state[0]<0||state[0]>=capacity||
|
||||
state[1]<0||state[1]>capacity)return -1;
|
||||
if(state[1]==capacity)return 0;
|
||||
tail=(state[0]+state[1])%capacity;
|
||||
for(int i=0;i<4;i++)storage[tail*4+i]=event[i];
|
||||
state[1]++;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Pop returns 1 with an event, 0 when empty, and -1 for invalid state or arguments. */
|
||||
int bob_event_queue_pop(int *state,int *storage,int capacity,int *event) {
|
||||
int head;
|
||||
if(!state||!storage||!event||capacity<1||state[0]<0||state[0]>=capacity||
|
||||
state[1]<0||state[1]>capacity)return -1;
|
||||
if(!state[1])return 0;
|
||||
head=state[0];
|
||||
for(int i=0;i<4;i++)event[i]=storage[head*4+i];
|
||||
state[0]=(head+1)%capacity;state[1]--;
|
||||
return 1;
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,59 @@
|
||||
#ifndef BOB_FONT_H
|
||||
#define BOB_FONT_H
|
||||
|
||||
#include "bob_gfx.h"
|
||||
|
||||
/* 5x7 column bitmaps: blank, A-Z, 0-9, ?, !, -, .; lowercase maps to uppercase. */
|
||||
static int bob_font5x7[41][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}
|
||||
};
|
||||
|
||||
/* Draws uppercase 5x7 glyphs at cell-pixel resolution; clips at the right edge. */
|
||||
int bob_gfx_bitmap_text(int x,int y,const char *text,int color) {
|
||||
int bitmap[560];
|
||||
int length=0,width,max_chars,character,glyph,cell;
|
||||
if(x<0||y<0||x>=80||y+7>25||color<0||color>15)return -1;
|
||||
max_chars=(80-x+1)/6;
|
||||
while(text[length]&&length<max_chars)length++;
|
||||
if(!length)return 0;
|
||||
width=length*6-1;
|
||||
for(int i=0;i<width*7;i++)bitmap[i]=0;
|
||||
for(int i=0;i<length;i++) {
|
||||
character=text[i];
|
||||
if(character>='a'&&character<='z')character-=32;
|
||||
if(character==' ')glyph=0;
|
||||
else if(character>='A'&&character<='Z')glyph=1+character-'A';
|
||||
else if(character>='0'&&character<='9')glyph=27+character-'0';
|
||||
else if(character=='!')glyph=38;
|
||||
else if(character=='-')glyph=39;
|
||||
else if(character=='.')glyph=40;
|
||||
else glyph=37;
|
||||
for(int column=0;column<5;column++)for(int row=0;row<7;row++) {
|
||||
cell=(bob_font5x7[glyph][column]&(1<<row))?('#'|(color<<8)):0;
|
||||
bitmap[row*width+i*6+column]=cell;
|
||||
}
|
||||
}
|
||||
return bob_gfx_blit_color(x,y,width,7,bitmap);
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,88 @@
|
||||
#ifndef BOB_FS_H
|
||||
#define BOB_FS_H
|
||||
|
||||
#include "bob.h"
|
||||
|
||||
/* Stable request protocol used by the bob32 filesystem service (trap 15). */
|
||||
#define BOB_FS_LIST 1
|
||||
#define BOB_FS_READ 2
|
||||
#define BOB_FS_WRITE 3
|
||||
#define BOB_FS_DELETE 4
|
||||
#define BOB_FS_SYSTEM_INFO 5
|
||||
#define BOB_FS_RUN_APP 6
|
||||
#define BOB_FS_WRITE_WORDS 8
|
||||
#define BOB_FS_READ_WORDS 9
|
||||
#define BOB_FS_KIND 10
|
||||
#define BOB_FS_API_VERSION 1
|
||||
#define BOB_FS_REQUEST(operation) ((BOB_FS_API_VERSION << 16) | (operation))
|
||||
#define BOB_FILE_KIND_TEXT 0
|
||||
#define BOB_FILE_KIND_BOB16_PROGRAM 1
|
||||
#define BOB_FILE_KIND_BOB32_PROGRAM 2
|
||||
#define BOB_FILE_KIND_NATIVE_APP 3
|
||||
|
||||
/* LIST returns the file kind (0..3), or -1 at end. length receives word size. */
|
||||
int bob_file_list(int index, char *name, int capacity, int *length) {
|
||||
int request[7];
|
||||
request[0]=BOB_FS_REQUEST(BOB_FS_LIST);request[1]=index;request[2]=(int)name;
|
||||
request[3]=capacity;request[4]=(int)length;request[5]=0;request[6]=0;
|
||||
return bob_os_service(request)-1;
|
||||
}
|
||||
|
||||
/* READ returns text length, or a negative value for missing/invalid input. */
|
||||
int bob_file_read(const char *name, char *buffer, int capacity) {
|
||||
int request[7];
|
||||
request[0]=BOB_FS_REQUEST(BOB_FS_READ);request[1]=(int)name;request[2]=(int)buffer;
|
||||
request[3]=capacity;request[4]=0;request[5]=0;request[6]=0;
|
||||
return bob_os_service(request);
|
||||
}
|
||||
|
||||
/* WRITE creates/replaces a text file. Length is measured in characters. */
|
||||
int bob_file_write(const char *name, const char *text, int length) {
|
||||
int request[7];
|
||||
request[0]=BOB_FS_REQUEST(BOB_FS_WRITE);request[1]=(int)name;request[2]=(int)text;
|
||||
request[3]=length;request[4]=0;request[5]=0;request[6]=0;
|
||||
return bob_os_service(request);
|
||||
}
|
||||
|
||||
/* Store raw bob16/bob32 program words (kinds 1/2); native images require import. */
|
||||
int bob_file_write_words(const char *name, int *words, int length, int kind) {
|
||||
int request[7];
|
||||
request[0]=BOB_FS_REQUEST(BOB_FS_WRITE_WORDS);request[1]=(int)name;
|
||||
request[2]=(int)words;request[3]=length;request[4]=kind;
|
||||
request[5]=0;request[6]=0;
|
||||
return bob_os_service(request);
|
||||
}
|
||||
|
||||
/* Read raw program/native image words into an application-owned buffer. */
|
||||
int bob_file_read_words(const char *name, int *words, int capacity) {
|
||||
int request[7];
|
||||
request[0]=BOB_FS_REQUEST(BOB_FS_READ_WORDS);request[1]=(int)name;
|
||||
request[2]=(int)words;request[3]=capacity;request[4]=0;
|
||||
request[5]=0;request[6]=0;
|
||||
return bob_os_service(request);
|
||||
}
|
||||
|
||||
/* Return a file kind (0..3) by name, or -1 when it does not exist. */
|
||||
int bob_file_kind(const char *name) {
|
||||
int request[7];
|
||||
request[0]=BOB_FS_REQUEST(BOB_FS_KIND);request[1]=(int)name;
|
||||
request[2]=0;request[3]=0;request[4]=0;request[5]=0;request[6]=0;
|
||||
return bob_os_service(request);
|
||||
}
|
||||
|
||||
int bob_file_delete(const char *name) {
|
||||
int request[7];
|
||||
request[0]=BOB_FS_REQUEST(BOB_FS_DELETE);request[1]=(int)name;request[2]=0;
|
||||
request[3]=0;request[4]=0;request[5]=0;request[6]=0;
|
||||
return bob_os_service(request);
|
||||
}
|
||||
|
||||
/* Fills version, app-address-space size, mapped pages and filesystem usage. */
|
||||
int bob_system_info(int *values, int capacity) {
|
||||
int request[7];
|
||||
request[0]=BOB_FS_REQUEST(BOB_FS_SYSTEM_INFO);request[1]=(int)values;
|
||||
request[2]=capacity;request[3]=0;request[4]=0;request[5]=0;request[6]=0;
|
||||
return bob_os_service(request);
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,89 @@
|
||||
#ifndef BOB_GFX_H
|
||||
#define BOB_GFX_H
|
||||
|
||||
#include "bob.h"
|
||||
|
||||
/* Version 1 is an 80x25 character-cell canvas; one cell is one pixel. */
|
||||
#define BOB_GFX_VERSION 1
|
||||
#define BOB_GFX_REQUEST(operation) ((BOB_GFX_VERSION << 16) | (operation))
|
||||
|
||||
int bob_gfx_enter(void) {
|
||||
int request[7];
|
||||
request[0]=BOB_GFX_REQUEST(16);
|
||||
request[1]=0;request[2]=0;request[3]=0;request[4]=0;request[5]=0;request[6]=0;
|
||||
return bob_os_service(request);
|
||||
}
|
||||
|
||||
int bob_gfx_resolution(int *values) {
|
||||
int request[7];
|
||||
request[0]=BOB_GFX_REQUEST(17);request[1]=(int)values;request[2]=2;
|
||||
request[3]=0;request[4]=0;request[5]=0;request[6]=0;
|
||||
return bob_os_service(request);
|
||||
}
|
||||
|
||||
int bob_gfx_pixel(int x,int y,int character,int color) {
|
||||
int request[7];
|
||||
request[0]=BOB_GFX_REQUEST(18);request[1]=x;request[2]=y;
|
||||
request[3]=character;request[4]=color;request[5]=0;request[6]=0;
|
||||
return bob_os_service(request);
|
||||
}
|
||||
|
||||
int bob_gfx_fill_rect(int x,int y,int width,int height,int character,int color) {
|
||||
int request[7];
|
||||
request[0]=BOB_GFX_REQUEST(19);request[1]=x;request[2]=y;
|
||||
request[3]=width;request[4]=height;request[5]=character;request[6]=color;
|
||||
return bob_os_service(request);
|
||||
}
|
||||
|
||||
int bob_gfx_line(int x0,int y0,int x1,int y1,int character,int color) {
|
||||
int request[7];
|
||||
request[0]=BOB_GFX_REQUEST(20);request[1]=x0;request[2]=y0;
|
||||
request[3]=x1;request[4]=y1;request[5]=character;request[6]=color;
|
||||
return bob_os_service(request);
|
||||
}
|
||||
|
||||
int bob_gfx_text(int x,int y,const char *text,int color) {
|
||||
int request[7];
|
||||
request[0]=BOB_GFX_REQUEST(21);request[1]=x;request[2]=y;
|
||||
request[3]=(int)text;request[4]=color;request[5]=0;request[6]=0;
|
||||
return bob_os_service(request);
|
||||
}
|
||||
|
||||
/* Bitmap cells are zero-transparent ASCII characters, row-major. */
|
||||
int bob_gfx_blit(int x,int y,int width,int height,const char *bitmap,int color) {
|
||||
int request[7];
|
||||
request[0]=BOB_GFX_REQUEST(22);request[1]=x;request[2]=y;
|
||||
request[3]=width;request[4]=height;request[5]=(int)bitmap;request[6]=color;
|
||||
return bob_os_service(request);
|
||||
}
|
||||
|
||||
/* Each word stores character in bits 0..7 and color in bits 8..11; zero is transparent. */
|
||||
int bob_gfx_blit_color(int x,int y,int width,int height,const int *bitmap) {
|
||||
int request[7];
|
||||
request[0]=BOB_GFX_REQUEST(27);request[1]=x;request[2]=y;
|
||||
request[3]=width;request[4]=height;request[5]=(int)bitmap;request[6]=0;
|
||||
return bob_os_service(request);
|
||||
}
|
||||
|
||||
int bob_gfx_clear(int character,int color) {
|
||||
int request[7];
|
||||
request[0]=BOB_GFX_REQUEST(23);request[1]=character;request[2]=color;
|
||||
request[3]=0;request[4]=0;request[5]=0;request[6]=0;
|
||||
return bob_os_service(request);
|
||||
}
|
||||
|
||||
int bob_gfx_present(void) {
|
||||
int request[7];
|
||||
request[0]=BOB_GFX_REQUEST(24);
|
||||
request[1]=0;request[2]=0;request[3]=0;request[4]=0;request[5]=0;request[6]=0;
|
||||
return bob_os_service(request);
|
||||
}
|
||||
|
||||
int bob_gfx_leave(void) {
|
||||
int request[7];
|
||||
request[0]=BOB_GFX_REQUEST(25);
|
||||
request[1]=0;request[2]=0;request[3]=0;request[4]=0;request[5]=0;request[6]=0;
|
||||
return bob_os_service(request);
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,352 @@
|
||||
#ifndef BOB_GUI_H
|
||||
#define BOB_GUI_H
|
||||
|
||||
#include "bob_gfx.h"
|
||||
#include "bob_event.h"
|
||||
#include "bob_wm.h"
|
||||
|
||||
/* Rectangles are x, y, width, height; drag state is active, offset-x, offset-y. */
|
||||
int bob_gui_window_hit(int x,int y,const int *rect) {
|
||||
return x>=rect[0]&&y>=rect[1]&&x<rect[0]+rect[2]&&y<rect[1]+rect[3];
|
||||
}
|
||||
|
||||
/* Rectangles are packed x,y,width,height; order is bottom-to-top window IDs. */
|
||||
int bob_gui_window_at(int x,int y,const int *rectangles,const int *order,int count) {
|
||||
for(int i=count-1;i>=0;i--) {
|
||||
int id=order[i];
|
||||
if(id>=0&&id<count&&bob_gui_window_hit(x,y,rectangles+id*4))return id;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
int bob_gui_raise_window(int *order,int count,int id) {
|
||||
int index=-1;
|
||||
for(int i=0;i<count;i++)if(order[i]==id){index=i;break;}
|
||||
if(index<0)return 0;
|
||||
for(int i=index;i<count-1;i++)order[i]=order[i+1];
|
||||
order[count-1]=id;return 1;
|
||||
}
|
||||
|
||||
int bob_gui_drag_start(const int *rect,int *drag,int x,int y) {
|
||||
if(x<rect[0]||x>=rect[0]+rect[2]||y!=rect[1])return 0;
|
||||
drag[0]=1;drag[1]=x-rect[0];drag[2]=y-rect[1];return 1;
|
||||
}
|
||||
|
||||
int bob_gui_drag_update(int *rect,int *drag,int x,int y,int screen_width,int screen_height) {
|
||||
int max_x,max_y;
|
||||
if(!drag[0])return 0;
|
||||
max_x=screen_width-rect[2];max_y=screen_height-rect[3];
|
||||
if(max_x<0)max_x=0;if(max_y<0)max_y=0;
|
||||
rect[0]=x-drag[1];rect[1]=y-drag[2];
|
||||
if(rect[0]<0)rect[0]=0;if(rect[0]>max_x)rect[0]=max_x;
|
||||
if(rect[1]<0)rect[1]=0;if(rect[1]>max_y)rect[1]=max_y;
|
||||
return 1;
|
||||
}
|
||||
|
||||
int bob_gui_drag_stop(int *drag) {
|
||||
int was_dragging=drag[0];drag[0]=0;return was_dragging;
|
||||
}
|
||||
|
||||
/* Button state is hovered, pressed; returns one only for an inside release. */
|
||||
int bob_gui_button_event(const int *rect,int *state,const int *event) {
|
||||
int inside=bob_gui_window_hit(event[2],event[3],rect);
|
||||
if(event[0]==BOB_EVENT_MOUSE_MOVE)state[0]=inside;
|
||||
else if(event[0]==BOB_EVENT_MOUSE_BUTTON_DOWN) {
|
||||
state[0]=inside;state[1]=inside&&((event[1]&BOB_MOUSE_BUTTON_LEFT)!=0);
|
||||
} else if(event[0]==BOB_EVENT_MOUSE_BUTTON_UP) {
|
||||
state[0]=inside;
|
||||
if(state[1]&&inside&&!(event[1]&BOB_MOUSE_BUTTON_LEFT)){state[1]=0;return 1;}
|
||||
state[1]=0;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int bob_gui_button_draw(int x,int y,int width,int height,const char *label,
|
||||
int hovered,int pressed) {
|
||||
int color=pressed?14:(hovered?11:7);
|
||||
int label_length=0,label_start=0,label_x,label_width;
|
||||
if(width<3||height<3)return -1;
|
||||
while(label[label_length])label_length++;
|
||||
bob_gfx_fill_rect(x,y,width,height,' ',color);
|
||||
bob_gfx_line(x+1,y,x+width-2,y,pressed?'=':'-',color);
|
||||
bob_gfx_line(x+1,y+height-1,x+width-2,y+height-1,pressed?'=':'-',color);
|
||||
bob_gfx_line(x,y+1,x,y+height-2,'|',color);
|
||||
bob_gfx_line(x+width-1,y+1,x+width-1,y+height-2,'|',color);
|
||||
bob_gfx_pixel(x,y,'+',color);bob_gfx_pixel(x+width-1,y,'+',color);
|
||||
bob_gfx_pixel(x,y+height-1,'+',color);bob_gfx_pixel(x+width-1,y+height-1,'+',color);
|
||||
label_width=width-2;
|
||||
if(label_length>label_width){label_start=(label_length-label_width)/2;label_length=label_width;}
|
||||
label_x=x+1+(label_width-label_length)/2;
|
||||
for(int i=0;i<label_length;i++)bob_gfx_pixel(label_x+i,y+height/2,label[label_start+i],15);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Draws a one-row-per-item popup; items is a fixed-stride label array. */
|
||||
int bob_gui_menu_draw(const int *rect,const char *items,int count,int stride,int selected) {
|
||||
int label_width=rect[2]-4;
|
||||
char label[80];
|
||||
if(count<1||stride<1||rect[2]<6||rect[2]>80||rect[3]!=count+2||
|
||||
rect[0]<0||rect[1]<0||rect[0]+rect[2]>80||rect[1]+rect[3]>25)return -1;
|
||||
bob_gfx_fill_rect(rect[0],rect[1],rect[2],rect[3],' ',7);
|
||||
bob_gfx_line(rect[0]+1,rect[1],rect[0]+rect[2]-2,rect[1],'-',7);
|
||||
bob_gfx_line(rect[0]+1,rect[1]+rect[3]-1,rect[0]+rect[2]-2,rect[1]+rect[3]-1,'-',7);
|
||||
bob_gfx_line(rect[0],rect[1]+1,rect[0],rect[1]+rect[3]-2,'|',7);
|
||||
bob_gfx_line(rect[0]+rect[2]-1,rect[1]+1,rect[0]+rect[2]-1,rect[1]+rect[3]-2,'|',7);
|
||||
bob_gfx_pixel(rect[0],rect[1],'+',7);bob_gfx_pixel(rect[0]+rect[2]-1,rect[1],'+',7);
|
||||
bob_gfx_pixel(rect[0],rect[1]+rect[3]-1,'+',7);bob_gfx_pixel(rect[0]+rect[2]-1,rect[1]+rect[3]-1,'+',7);
|
||||
for(int row=0;row<count;row++) {
|
||||
int color=row==selected?4:7;int length=0;const char *source=items+row*stride;
|
||||
bob_gfx_fill_rect(rect[0]+1,rect[1]+1+row,rect[2]-2,1,' ',color);
|
||||
bob_gfx_pixel(rect[0]+1,rect[1]+1+row,row==selected?'>':' ',color);
|
||||
while(length<label_width&&length<stride&&source[length]){label[length]=source[length];length++;}
|
||||
label[length]=0;bob_gfx_text(rect[0]+2,rect[1]+1+row,label,row==selected?15:8);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Places a popup below its anchor and clamps it inside the screen rectangle. */
|
||||
int bob_gui_menu_place(int *rect,int anchor_x,int anchor_y,int width,int count,
|
||||
int screen_width,int screen_height) {
|
||||
int height=count+2;
|
||||
if(width<6||count<1||screen_width<width||screen_height<height)return -1;
|
||||
rect[0]=anchor_x;rect[1]=anchor_y;rect[2]=width;rect[3]=height;
|
||||
if(rect[0]+width>screen_width)rect[0]=screen_width-width;
|
||||
if(rect[0]<0)rect[0]=0;
|
||||
if(rect[1]+height>screen_height)rect[1]=screen_height-height;
|
||||
if(rect[1]<0)rect[1]=0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Returns the activated row, -1 for no action, or -2 when Escape closes it. */
|
||||
int bob_gui_menu_event(const int *rect,int count,int *state,const int *event) {
|
||||
int row=-1;
|
||||
if(count<1||rect[3]!=count+2)return -1;
|
||||
if(event[2]>=rect[0]+1&&event[2]<rect[0]+rect[2]-1&&
|
||||
event[3]>=rect[1]+1&&event[3]<rect[1]+1+count)row=event[3]-rect[1]-1;
|
||||
if(event[0]==BOB_EVENT_MOUSE_MOVE)state[0]=row;
|
||||
else if(event[0]==BOB_EVENT_MOUSE_BUTTON_DOWN) {
|
||||
state[0]=row;state[1]=row>=0&&(event[1]&BOB_MOUSE_BUTTON_LEFT)?row:-1;
|
||||
} else if(event[0]==BOB_EVENT_MOUSE_BUTTON_UP) {
|
||||
int activated=row>=0&&state[1]==row&&!(event[1]&BOB_MOUSE_BUTTON_LEFT)?row:-1;
|
||||
state[0]=row;state[1]=-1;return activated;
|
||||
} else if(event[0]==BOB_EVENT_KEY_DOWN) {
|
||||
if(event[1]==256)state[0]=state[0]<=0?count-1:state[0]-1;
|
||||
else if(event[1]==257)state[0]=state[0<0||state[0]>=count-1?0:state[0]+1];
|
||||
} else if(event[0]==BOB_EVENT_CHAR) {
|
||||
if(event[1]==27)return -2;
|
||||
if((event[1]==10||event[1]==13)&&state[0]>=0&&state[0]<count)return state[0];
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Text state is focused, caret index, horizontal scroll offset. */
|
||||
int bob_gui_text_field_init(char *buffer,int *state,int capacity) {
|
||||
int length=0;
|
||||
if(capacity<1)return -1;
|
||||
while(length<capacity-1&&buffer[length])length++;
|
||||
state[0]=0;state[1]=length;state[2]=0;return length;
|
||||
}
|
||||
|
||||
int bob_gui_text_field_event(const int *rect,char *buffer,int *state,int capacity,const int *event) {
|
||||
int length=0,visible,changed=0;
|
||||
while(length<capacity-1&&buffer[length])length++;
|
||||
visible=rect[2]-2;
|
||||
if(visible<1||capacity<1)return 0;
|
||||
if(event[0]==BOB_EVENT_MOUSE_BUTTON_DOWN) {
|
||||
state[0]=bob_gui_window_hit(event[2],event[3],rect);
|
||||
if(state[0]) {
|
||||
state[1]=state[2]+event[2]-rect[0]-1;
|
||||
if(state[1]<0)state[1]=0;if(state[1]>length)state[1]=length;
|
||||
}
|
||||
} else if(state[0]&&event[0]==BOB_EVENT_CHAR) {
|
||||
if(event[1]>=32&&event[1]<127&&length<capacity-1) {
|
||||
for(int i=length;i>state[1];i--)buffer[i]=buffer[i-1];
|
||||
buffer[state[1]++]=event[1];buffer[++length]=0;changed=1;
|
||||
} else if((event[1]==8||event[1]==127)&&state[1]>0) {
|
||||
for(int i=state[1]-1;i<length;i++)buffer[i]=buffer[i+1];
|
||||
state[1]--;length--;changed=1;
|
||||
}
|
||||
} else if(state[0]&&event[0]==BOB_EVENT_KEY_DOWN) {
|
||||
if(event[1]==258&&state[1]>0)state[1]--;
|
||||
else if(event[1]==259&&state[1]<length)state[1]++;
|
||||
else if(event[1]==260)state[1]=0;
|
||||
else if(event[1]==261)state[1]=length;
|
||||
else if(event[1]==262&&state[1]<length) {
|
||||
for(int i=state[1];i<length;i++)buffer[i]=buffer[i+1];
|
||||
length--;changed=1;
|
||||
}
|
||||
}
|
||||
if(state[1]<state[2])state[2]=state[1];
|
||||
if(state[1]>=state[2]+visible)state[2]=state[1]-visible+1;
|
||||
return changed;
|
||||
}
|
||||
|
||||
int bob_gui_text_field_draw(const int *rect,const char *buffer,const int *state) {
|
||||
int visible=rect[2]-2;
|
||||
char shown[80];
|
||||
int i=0;
|
||||
if(rect[2]<3||rect[2]>80||rect[3]<3)return -1;
|
||||
bob_gfx_fill_rect(rect[0],rect[1],rect[2],rect[3],' ',state[0]?15:8);
|
||||
bob_gfx_line(rect[0]+1,rect[1],rect[0]+rect[2]-2,rect[1],'-',state[0]?15:8);
|
||||
bob_gfx_line(rect[0]+1,rect[1]+rect[3]-1,rect[0]+rect[2]-2,rect[1]+rect[3]-1,'-',state[0]?15:8);
|
||||
bob_gfx_line(rect[0],rect[1]+1,rect[0],rect[1]+rect[3]-2,'|',state[0]?15:8);
|
||||
bob_gfx_line(rect[0]+rect[2]-1,rect[1]+1,rect[0]+rect[2]-1,rect[1]+rect[3]-2,'|',state[0]?15:8);
|
||||
for(i=0;i<visible&&buffer[state[2]+i];i++)shown[i]=buffer[state[2]+i];
|
||||
shown[i]=0;bob_gfx_text(rect[0]+1,rect[1]+1,shown,15);
|
||||
if(state[0]&&state[1]-state[2]>=0&&state[1]-state[2]<visible)
|
||||
bob_gfx_pixel(rect[0]+1+state[1]-state[2],rect[1]+1,'|',14);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Text-area state is focused, byte cursor, first visible line, reserved. */
|
||||
int bob_gui_text_area_init(char *buffer,int *state,int capacity) {
|
||||
int length=0;
|
||||
if(capacity<1)return -1;
|
||||
while(length<capacity-1&&buffer[length]) {
|
||||
length++;
|
||||
}
|
||||
state[0]=0;state[1]=length;state[2]=0;state[3]=0;
|
||||
return length;
|
||||
}
|
||||
|
||||
static int bob_gui_text_area_insert(char *buffer,int *length,int *cursor,int capacity,char value) {
|
||||
if(*length>=capacity-1)return 0;
|
||||
for(int i=*length;i>*cursor;i--)buffer[i]=buffer[i-1];
|
||||
buffer[*cursor]=value;(*cursor)++;(*length)++;buffer[*length]=0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
static void bob_gui_text_area_position(const char *buffer,int cursor,int *line,int *column) {
|
||||
*line=0;*column=0;
|
||||
for(int i=0;i<cursor;i++) {
|
||||
if(buffer[i]=='\n'){(*line)++;*column=0;}
|
||||
else (*column)++;
|
||||
}
|
||||
}
|
||||
|
||||
static void bob_gui_text_area_scroll(const char *buffer,int cursor,int *state,const int *rect) {
|
||||
int line,column,visible=rect[3]-2;
|
||||
bob_gui_text_area_position(buffer,cursor,&line,&column);
|
||||
if(line<state[2])state[2]=line;
|
||||
if(line>=state[2]+visible)state[2]=line-visible+1;
|
||||
}
|
||||
|
||||
int bob_gui_text_area_reveal(const char *buffer,int *state,const int *rect) {
|
||||
bob_gui_text_area_scroll(buffer,state[1],state,rect);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int bob_gui_text_area_event(const int *rect,char *buffer,int *state,int capacity,const int *event) {
|
||||
int length=0,changed=0,line,column,start,end,next_start,next_end,target,visible,total_lines,max_scroll,old_scroll;
|
||||
while(length<capacity-1&&buffer[length])length++;
|
||||
if(capacity<1||rect[2]<3||rect[3]<3)return 0;
|
||||
if(event[0]==BOB_EVENT_MOUSE_WHEEL&&bob_gui_window_hit(event[2],event[3],rect)) {
|
||||
state[0]=1;old_scroll=state[2];visible=rect[3]-2;total_lines=1;
|
||||
for(int i=0;i<length;i++)if(buffer[i]=='\n')total_lines++;
|
||||
max_scroll=total_lines-visible;if(max_scroll<0)max_scroll=0;
|
||||
if(event[1]>0&&state[2]>0)state[2]--;
|
||||
else if(event[1]<0&&state[2]<max_scroll)state[2]++;
|
||||
return state[2]!=old_scroll;
|
||||
} else if(event[0]==BOB_EVENT_MOUSE_BUTTON_DOWN) {
|
||||
state[0]=bob_gui_window_hit(event[2],event[3],rect);
|
||||
if(state[0]) {
|
||||
target=state[2]+event[3]-rect[1]-1;
|
||||
column=event[2]-rect[0]-1;
|
||||
start=0;line=0;
|
||||
while(start<length&&line<target)if(buffer[start++]=='\n')line++;
|
||||
while(start<length&&buffer[start]!='\n'&&column>0){start++;column--;}
|
||||
state[1]=start;
|
||||
}
|
||||
} else if(state[0]&&event[0]==BOB_EVENT_CHAR) {
|
||||
if(event[1]==8||event[1]==127) {
|
||||
if(state[1]>0) {
|
||||
for(int i=state[1]-1;i<length;i++)buffer[i]=buffer[i+1];
|
||||
state[1]--;length--;changed=1;
|
||||
}
|
||||
} else if(event[1]==10||event[1]==13) {
|
||||
changed=bob_gui_text_area_insert(buffer,&length,&state[1],capacity,'\n');
|
||||
} else if(event[1]>=32&&event[1]<127) {
|
||||
changed=bob_gui_text_area_insert(buffer,&length,&state[1],capacity,(char)event[1]);
|
||||
}
|
||||
} else if(state[0]&&event[0]==BOB_EVENT_KEY_DOWN) {
|
||||
bob_gui_text_area_position(buffer,state[1],&line,&column);
|
||||
if(event[1]==258&&state[1]>0)state[1]--;
|
||||
else if(event[1]==259&&state[1]<length)state[1]++;
|
||||
else if(event[1]==260) {
|
||||
start=state[1];while(start>0&&buffer[start-1]!='\n')start--;state[1]=start;
|
||||
} else if(event[1]==261) {
|
||||
end=state[1];while(end<length&&buffer[end]!='\n')end++;state[1]=end;
|
||||
} else if(event[1]==262&&state[1]<length) {
|
||||
for(int i=state[1];i<length;i++)buffer[i]=buffer[i+1];
|
||||
length--;changed=1;
|
||||
} else if(event[1]==256||event[1]==257) {
|
||||
start=state[1];while(start>0&&buffer[start-1]!='\n')start--;
|
||||
end=state[1];while(end<length&&buffer[end]!='\n')end++;
|
||||
if(event[1]==256&&start>0) {
|
||||
next_end=start-1;next_start=next_end;
|
||||
while(next_start>0&&buffer[next_start-1]!='\n')next_start--;
|
||||
target=next_start+column;if(target>next_end)target=next_end;state[1]=target;
|
||||
} else if(event[1]==257&&end<length) {
|
||||
next_start=end+1;next_end=next_start;
|
||||
while(next_end<length&&buffer[next_end]!='\n')next_end++;
|
||||
target=next_start+column;if(target>next_end)target=next_end;state[1]=target;
|
||||
}
|
||||
}
|
||||
}
|
||||
bob_gui_text_area_scroll(buffer,state[1],state,rect);
|
||||
return changed;
|
||||
}
|
||||
|
||||
int bob_gui_text_area_draw(const int *rect,const char *buffer,const int *state) {
|
||||
int width=rect[2]-2,height=rect[3]-2,length=0,line=0,column=0;
|
||||
int position=0,row,row_start,row_end,offset,shown_length,cursor_line,cursor_column;
|
||||
char shown[80];
|
||||
if(rect[2]<3||rect[2]>80||rect[3]<3)return -1;
|
||||
while(buffer[length])length++;
|
||||
bob_gfx_fill_rect(rect[0],rect[1],rect[2],rect[3],' ',state[0]?15:8);
|
||||
bob_gfx_line(rect[0]+1,rect[1],rect[0]+rect[2]-2,rect[1],'-',state[0]?15:8);
|
||||
bob_gfx_line(rect[0]+1,rect[1]+rect[3]-1,rect[0]+rect[2]-2,rect[1]+rect[3]-1,'-',state[0]?15:8);
|
||||
bob_gfx_line(rect[0],rect[1]+1,rect[0],rect[1]+rect[3]-2,'|',state[0]?15:8);
|
||||
bob_gfx_line(rect[0]+rect[2]-1,rect[1]+1,rect[0]+rect[2]-1,rect[1]+rect[3]-2,'|',state[0]?15:8);
|
||||
bob_gui_text_area_position(buffer,state[1],&cursor_line,&cursor_column);
|
||||
while(position<length&&line<state[2])if(buffer[position++]=='\n')line++;
|
||||
for(row=0;row<height&&position<=length;row++) {
|
||||
row_start=position;row_end=position;
|
||||
while(row_end<length&&buffer[row_end]!='\n')row_end++;
|
||||
offset=0;
|
||||
if(line==cursor_line&&cursor_column>=width)offset=cursor_column-width+1;
|
||||
shown_length=0;
|
||||
while(shown_length<width&&row_start+offset+shown_length<row_end) {
|
||||
shown[shown_length]=buffer[row_start+offset+shown_length];shown_length++;
|
||||
}
|
||||
shown[shown_length]=0;
|
||||
bob_gfx_text(rect[0]+1,rect[1]+1+row,shown,15);
|
||||
if(state[0]&&line==cursor_line&&cursor_column>=offset&&cursor_column-offset<width)
|
||||
bob_gfx_pixel(rect[0]+1+cursor_column-offset,rect[1]+1+row,'|',14);
|
||||
if(row_end>=length)break;
|
||||
position=row_end+1;line++;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Reusable character-cell window frame and content area. */
|
||||
int bob_gui_window(int x,int y,int width,int height,const char *title,
|
||||
const char *body,const char *message,int focused) {
|
||||
int edge=focused?14:8;
|
||||
int title_color=focused?15:7;
|
||||
if(width<4||height<4)return -1;
|
||||
bob_gfx_fill_rect(x,y,width,height,' ',edge);
|
||||
bob_gfx_line(x+1,y,x+width-2,y,'-',edge);
|
||||
bob_gfx_line(x+1,y+height-1,x+width-2,y+height-1,'-',edge);
|
||||
bob_gfx_line(x,y+1,x,y+height-2,'|',edge);
|
||||
bob_gfx_line(x+width-1,y+1,x+width-1,y+height-2,'|',edge);
|
||||
bob_gfx_pixel(x,y,'+',edge);bob_gfx_pixel(x+width-1,y,'+',edge);
|
||||
bob_gfx_pixel(x,y+height-1,'+',edge);bob_gfx_pixel(x+width-1,y+height-1,'+',edge);
|
||||
bob_gfx_fill_rect(x+1,y+1,width-2,1,' ',focused?4:8);
|
||||
bob_gfx_text(x+2,y+1,title,title_color);
|
||||
bob_gfx_text(x+2,y+3,body,edge);
|
||||
if(message)bob_gfx_text(x+2,y+height-2,message,focused?10:7);
|
||||
return 0;
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,18 @@
|
||||
#ifndef BOB_MEMORY_H
|
||||
#define BOB_MEMORY_H
|
||||
|
||||
/* Caller-owned word arena; allocation sizes are target words, not host bytes. */
|
||||
int bob_arena_reset(int *used) { if(!used)return -1;*used=0;return 0; }
|
||||
int *bob_arena_alloc(int *storage,int capacity,int *used,int words) {
|
||||
int *result;
|
||||
if(!storage||!used||capacity<=0||words<=0||*used<0||*used>capacity)return 0;
|
||||
if(words>capacity-*used)return 0;
|
||||
result=storage+*used;*used+=words;return result;
|
||||
}
|
||||
int bob_arena_used(int *used) { if(!used||*used<0)return -1;return *used; }
|
||||
int bob_arena_remaining(int capacity,int *used) {
|
||||
if(!used||capacity<0||*used<0||*used>capacity)return -1;
|
||||
return capacity-*used;
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,15 @@
|
||||
#ifndef BOB_NATIVE_H
|
||||
#define BOB_NATIVE_H
|
||||
|
||||
/* Common bob32 application APIs. Include bob_gfx.h/bob_gui.h only when needed. */
|
||||
#include "bob.h"
|
||||
#include "bob_string.h"
|
||||
#include "bob_memory.h"
|
||||
#include "bob_fs.h"
|
||||
#include "bob_system.h"
|
||||
#include "bob_process.h"
|
||||
#include "bob_time.h"
|
||||
#include "bob_event.h"
|
||||
#include "bob_event_queue.h"
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,14 @@
|
||||
#ifndef BOB_PROCESS_H
|
||||
#define BOB_PROCESS_H
|
||||
|
||||
#include "bob_fs.h"
|
||||
|
||||
/* Run a stored native bob32 app; returns service status and writes child status. */
|
||||
int bob_app_run(const char *name,const char *arguments,int *exit_code) {
|
||||
int request[7];
|
||||
request[0]=BOB_FS_REQUEST(BOB_FS_RUN_APP);request[1]=(int)name;request[2]=(int)arguments;
|
||||
request[3]=(int)exit_code;request[4]=0;request[5]=0;request[6]=0;
|
||||
return bob_os_service(request);
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,21 @@
|
||||
#ifndef BOB_SYSTEM_H
|
||||
#define BOB_SYSTEM_H
|
||||
|
||||
#include "bob.h"
|
||||
|
||||
#define BOB_SYSTEM_API_VERSION 1
|
||||
#define BOB_SYSTEM_CAPABILITIES 11
|
||||
#define BOB_SYSTEM_DEVICE_CELL_FRAMEBUFFER 1
|
||||
#define BOB_SYSTEM_INPUT_KEYBOARD 1
|
||||
#define BOB_SYSTEM_INPUT_MOUSE 2
|
||||
|
||||
/* Returns version, device flags, cell width/height, and input flags. */
|
||||
int bob_system_capabilities(int *values,int capacity) {
|
||||
int request[7];
|
||||
request[0]=(BOB_SYSTEM_API_VERSION << 16) | BOB_SYSTEM_CAPABILITIES;
|
||||
request[1]=(int)values;request[2]=capacity;
|
||||
request[3]=0;request[4]=0;request[5]=0;request[6]=0;
|
||||
return bob_os_service(request);
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,18 @@
|
||||
#ifndef BOB_TIME_H
|
||||
#define BOB_TIME_H
|
||||
|
||||
#include "bob.h"
|
||||
|
||||
#define BOB_TIME_API_VERSION 1
|
||||
#define BOB_TIME_GET_UTC_SECONDS 7
|
||||
|
||||
/* Writes low/high 32-bit words of UTC seconds since 1970-01-01. */
|
||||
int bob_time_utc_seconds(int *words) {
|
||||
int request[7];
|
||||
request[0]=(BOB_TIME_API_VERSION << 16) | BOB_TIME_GET_UTC_SECONDS;
|
||||
request[1]=(int)words;request[2]=2;request[3]=0;request[4]=0;
|
||||
request[5]=0;request[6]=0;
|
||||
return bob_os_service(request);
|
||||
}
|
||||
|
||||
#endif
|
||||
+193
@@ -0,0 +1,193 @@
|
||||
#ifndef BOB_WM_H
|
||||
#define BOB_WM_H
|
||||
|
||||
#include "bob_event.h"
|
||||
|
||||
/* App-owned window records contain x,y,w,h,visible,dirty,allocated. */
|
||||
#define BOB_WM_MAX_WINDOWS 8
|
||||
#define BOB_WM_WINDOW_WORDS 7
|
||||
#define BOB_WM_STATE_WORDS 10
|
||||
|
||||
/* State contains max,count,focus,drag,offset-x,offset-y,screen-w,screen-h,
|
||||
full-dirty,draw-cursor. Z-order is an app-owned bottom-to-top ID array. */
|
||||
static int bob_wm_window_valid(const int *state,const int *windows,int id) {
|
||||
return state&&windows&&id>=0&&id<state[0]&&windows[id*BOB_WM_WINDOW_WORDS+6];
|
||||
}
|
||||
|
||||
static int bob_wm_intersects(const int *a,const int *b) {
|
||||
return a[0]<b[0]+b[2]&&b[0]<a[0]+a[2]&&a[1]<b[1]+b[3]&&b[1]<a[1]+a[3];
|
||||
}
|
||||
|
||||
static void bob_wm_clamp(int *window,const int *state) {
|
||||
int max_x=state[6]-window[2],max_y=state[7]-window[3];
|
||||
if(max_x<0)max_x=0;if(max_y<0)max_y=0;
|
||||
if(window[0]<0)window[0]=0;if(window[0]>max_x)window[0]=max_x;
|
||||
if(window[1]<0)window[1]=0;if(window[1]>max_y)window[1]=max_y;
|
||||
}
|
||||
|
||||
int bob_wm_init(int *state,int *windows,int *order,int maximum,int screen_width,int screen_height) {
|
||||
if(!state||!windows||!order||maximum<1||maximum>BOB_WM_MAX_WINDOWS||
|
||||
screen_width<1||screen_height<1)return -1;
|
||||
for(int i=0;i<BOB_WM_STATE_WORDS;i++)state[i]=0;
|
||||
state[0]=maximum;state[2]=-1;state[3]=-1;state[6]=screen_width;state[7]=screen_height;state[8]=1;
|
||||
for(int i=0;i<maximum*BOB_WM_WINDOW_WORDS;i++)windows[i]=0;
|
||||
for(int i=0;i<maximum;i++)order[i]=-1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void bob_wm_mark_all(int *state,int *windows,const int *order) {
|
||||
for(int i=0;i<state[1];i++) {
|
||||
int id=order[i];
|
||||
if(bob_wm_window_valid(state,windows,id)&&windows[id*BOB_WM_WINDOW_WORDS+4])
|
||||
windows[id*BOB_WM_WINDOW_WORDS+5]=1;
|
||||
}
|
||||
state[8]=1;
|
||||
}
|
||||
|
||||
int bob_wm_create(int *state,int *windows,int *order,int x,int y,int width,int height) {
|
||||
int id=-1;
|
||||
if(!state||!windows||!order||width<4||height<3||width>state[6]||height>state[7])return -1;
|
||||
for(int i=0;i<state[0];i++)if(!windows[i*BOB_WM_WINDOW_WORDS+6]){id=i;break;}
|
||||
if(id<0||state[1]>=state[0])return -1;
|
||||
int *window=windows+id*BOB_WM_WINDOW_WORDS;
|
||||
window[0]=x;window[1]=y;window[2]=width;window[3]=height;
|
||||
window[4]=1;window[5]=1;window[6]=1;bob_wm_clamp(window,state);
|
||||
order[state[1]++]=id;state[2]=id;state[3]=-1;
|
||||
for(int i=0;i<state[1]-1;i++)windows[order[i]*BOB_WM_WINDOW_WORDS+5]=1;
|
||||
state[8]=1;return id;
|
||||
}
|
||||
|
||||
int bob_wm_raise(int *state,int *windows,int *order,int id) {
|
||||
int index=-1;
|
||||
if(!bob_wm_window_valid(state,windows,id)||!windows[id*BOB_WM_WINDOW_WORDS+4])return -1;
|
||||
for(int i=0;i<state[1];i++)if(order[i]==id){index=i;break;}
|
||||
if(index<0)return -1;
|
||||
if(index==state[1]-1)return 0;
|
||||
for(int i=index;i<state[1]-1;i++)order[i]=order[i+1];
|
||||
order[state[1]-1]=id;bob_wm_mark_all(state,windows,order);return 1;
|
||||
}
|
||||
|
||||
int bob_wm_focus(int *state,int *windows,int *order,int id) {
|
||||
int old;
|
||||
if(!bob_wm_window_valid(state,windows,id)||!windows[id*BOB_WM_WINDOW_WORDS+4])return -1;
|
||||
old=state[2];
|
||||
bob_wm_raise(state,windows,order,id);
|
||||
if(old>=0&&old<state[0])windows[old*BOB_WM_WINDOW_WORDS+5]=1;
|
||||
state[2]=id;windows[id*BOB_WM_WINDOW_WORDS+5]=1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int bob_wm_move(int *state,int *windows,const int *order,int id,int x,int y) {
|
||||
int *window;
|
||||
if(!bob_wm_window_valid(state,windows,id))return -1;
|
||||
window=windows+id*BOB_WM_WINDOW_WORDS;
|
||||
window[0]=x;window[1]=y;bob_wm_clamp(window,state);
|
||||
bob_wm_mark_all(state,windows,order);return 0;
|
||||
}
|
||||
|
||||
int bob_wm_show(int *state,int *windows,int *order,int id,int visible) {
|
||||
int *window;
|
||||
if(!bob_wm_window_valid(state,windows,id))return -1;
|
||||
window=windows+id*BOB_WM_WINDOW_WORDS;visible=visible!=0;
|
||||
if(window[4]==visible)return 0;
|
||||
window[4]=visible;
|
||||
if(visible)bob_wm_focus(state,windows,order,id);
|
||||
else if(state[3]==id)state[3]=-1;
|
||||
else if(state[2]==id) {
|
||||
state[2]=-1;
|
||||
for(int i=state[1]-1;i>=0;i--)if(windows[order[i]*BOB_WM_WINDOW_WORDS+4]){state[2]=order[i];break;}
|
||||
if(state[2]>=0)windows[state[2]*BOB_WM_WINDOW_WORDS+5]=1;
|
||||
}
|
||||
bob_wm_mark_all(state,windows,order);return 1;
|
||||
}
|
||||
|
||||
int bob_wm_destroy(int *state,int *windows,int *order,int id) {
|
||||
int index=-1,was_focused;
|
||||
if(!bob_wm_window_valid(state,windows,id))return -1;
|
||||
for(int i=0;i<state[1];i++)if(order[i]==id){index=i;break;}
|
||||
if(index<0)return -1;
|
||||
was_focused=state[2]==id;
|
||||
if(state[3]==id)state[3]=-1;
|
||||
for(int i=index;i<state[1]-1;i++)order[i]=order[i+1];
|
||||
order[--state[1]]=-1;
|
||||
for(int i=0;i<BOB_WM_WINDOW_WORDS;i++)windows[id*BOB_WM_WINDOW_WORDS+i]=0;
|
||||
if(was_focused) {
|
||||
state[2]=-1;
|
||||
for(int i=state[1]-1;i>=0;i--)if(windows[order[i]*BOB_WM_WINDOW_WORDS+4]){state[2]=order[i];break;}
|
||||
}
|
||||
if(state[2]>=0)windows[state[2]*BOB_WM_WINDOW_WORDS+5]=1;
|
||||
bob_wm_mark_all(state,windows,order);return 0;
|
||||
}
|
||||
|
||||
int bob_wm_window_at(const int *state,const int *windows,const int *order,int x,int y) {
|
||||
if(!state||!windows||!order)return -1;
|
||||
for(int i=state[1]-1;i>=0;i--) {
|
||||
int id=order[i];int *window=(int *)(windows+id*BOB_WM_WINDOW_WORDS);
|
||||
if(bob_wm_window_valid(state,windows,id)&&window[4]&&
|
||||
x>=window[0]&&y>=window[1]&&x<window[0]+window[2]&&y<window[1]+window[3])return id;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Returns a recipient ID or -1; routed mouse coordinates become window-local. */
|
||||
int bob_wm_dispatch(int *state,int *windows,int *order,const int *event,int *routed) {
|
||||
int type,target=-1,x,y;
|
||||
if(!state||!windows||!order||!event||!routed)return -1;
|
||||
type=event[0];for(int i=0;i<4;i++)routed[i]=event[i];
|
||||
if(type==BOB_EVENT_KEY_DOWN||type==BOB_EVENT_KEY_UP||type==BOB_EVENT_CHAR) {
|
||||
target=state[2];
|
||||
if(!bob_wm_window_valid(state,windows,target)||!windows[target*BOB_WM_WINDOW_WORDS+4])return -1;
|
||||
return target;
|
||||
}
|
||||
if(type!=BOB_EVENT_MOUSE_MOVE&&type!=BOB_EVENT_MOUSE_BUTTON_DOWN&&
|
||||
type!=BOB_EVENT_MOUSE_BUTTON_UP&&type!=BOB_EVENT_MOUSE_WHEEL)return -1;
|
||||
x=event[2];y=event[3];
|
||||
if(type==BOB_EVENT_MOUSE_MOVE&&bob_wm_window_valid(state,windows,state[3])) {
|
||||
target=state[3];bob_wm_move(state,windows,order,target,x-state[4],y-state[5]);
|
||||
} else if(type==BOB_EVENT_MOUSE_BUTTON_UP&&bob_wm_window_valid(state,windows,state[3])) {
|
||||
target=state[3];bob_wm_move(state,windows,order,target,x-state[4],y-state[5]);state[3]=-1;
|
||||
} else {
|
||||
target=bob_wm_window_at(state,windows,order,x,y);
|
||||
if(type==BOB_EVENT_MOUSE_BUTTON_DOWN&&target>=0) {
|
||||
bob_wm_focus(state,windows,order,target);
|
||||
int *window=windows+target*BOB_WM_WINDOW_WORDS;
|
||||
if((event[1]&BOB_MOUSE_BUTTON_LEFT)&&y==window[1]) {
|
||||
state[3]=target;state[4]=x-window[0];state[5]=y-window[1];
|
||||
}
|
||||
}
|
||||
}
|
||||
if(target<0)return -1;
|
||||
routed[2]=x-windows[target*BOB_WM_WINDOW_WORDS];
|
||||
routed[3]=y-windows[target*BOB_WM_WINDOW_WORDS+1];
|
||||
return target;
|
||||
}
|
||||
|
||||
void bob_wm_invalidate(int *state,int *windows,int *order,int id) {
|
||||
if(!bob_wm_window_valid(state,windows,id))return;
|
||||
windows[id*BOB_WM_WINDOW_WORDS+5]=1;
|
||||
for(int i=0;i<state[1];i++) {
|
||||
int other=order[i];
|
||||
if(other==id)continue;
|
||||
if(bob_wm_window_valid(state,windows,other)&&windows[other*BOB_WM_WINDOW_WORDS+4]&&
|
||||
bob_wm_intersects(windows+id*BOB_WM_WINDOW_WORDS,windows+other*BOB_WM_WINDOW_WORDS))
|
||||
windows[other*BOB_WM_WINDOW_WORDS+5]=1;
|
||||
}
|
||||
}
|
||||
|
||||
/* Prepare a redraw pass and return dirty visible IDs in bottom-to-top order. */
|
||||
int bob_wm_begin_draw(int *state,int *windows,const int *order) {
|
||||
if(!state||!windows||!order)return -1;
|
||||
if(state[8])bob_wm_mark_all(state,windows,order);
|
||||
state[8]=0;state[9]=0;return 0;
|
||||
}
|
||||
|
||||
int bob_wm_next_dirty(int *state,int *windows,const int *order) {
|
||||
if(!state||!windows||!order)return -1;
|
||||
while(state[9]<state[1]) {
|
||||
int id=order[state[9]++];int *window=windows+id*BOB_WM_WINDOW_WORDS;
|
||||
if(bob_wm_window_valid(state,windows,id)&&window[4]&&window[5]){window[5]=0;return id;}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
#endif
|
||||
+17
-10
@@ -3,6 +3,14 @@ int file_lengths[8];
|
||||
int file_kinds[8];
|
||||
int file_used[8];
|
||||
|
||||
void file_service_register(void) {
|
||||
int descriptor[5];
|
||||
descriptor[0] = 0; descriptor[1] = (int)file_names;
|
||||
descriptor[2] = (int)file_lengths; descriptor[3] = (int)file_kinds;
|
||||
descriptor[4] = (int)file_used;
|
||||
bob_fs_register(descriptor);
|
||||
}
|
||||
|
||||
void file_snapshot(int operation) {
|
||||
int descriptor[4]; int result;
|
||||
descriptor[0] = (int)file_names; descriptor[1] = (int)file_lengths;
|
||||
@@ -26,14 +34,13 @@ void file_snapshot(int operation) {
|
||||
}
|
||||
|
||||
char *file_name(int slot) { return file_names + slot * NAME_WORDS; }
|
||||
/* The upper 4096 words are reserved for file contents, above the kernel stack.
|
||||
Supervised programs cannot write this region. */
|
||||
/* Native files occupy protected memory between the kernel and app regions. */
|
||||
int *file_content(int slot) {
|
||||
#ifdef BOBC_WIDE
|
||||
int i; int offset;
|
||||
offset = 0;
|
||||
for (i = 0; i < slot; i++) if (file_used[i]) offset += file_lengths[i] + 1;
|
||||
return (int *)0xf000 + offset;
|
||||
return (int *)WIDE_FILE_BASE + offset;
|
||||
#else
|
||||
return (int *)0xf000 + slot * FILE_WORDS;
|
||||
#endif
|
||||
@@ -101,7 +108,7 @@ int file_write(char *name, void *data, int length, int kind) {
|
||||
/* Compact first so variable-sized files never leave unusable gaps. */
|
||||
for (i = 0; i < FILE_COUNT; i++) if (file_used[i] && i != slot) {
|
||||
int *source; int *destination; int j;
|
||||
source = (int *)0xf000; destination = (int *)0xf000;
|
||||
source = (int *)WIDE_FILE_BASE; destination = (int *)WIDE_FILE_BASE;
|
||||
for (j = 0; j < i; j++) if (file_used[j] && j != slot) destination += file_lengths[j] + 1;
|
||||
for (j = 0; j < i; j++) if (file_used[j]) source += file_lengths[j] + 1;
|
||||
if (source != destination && destination < source)
|
||||
@@ -112,15 +119,15 @@ int file_write(char *name, void *data, int length, int kind) {
|
||||
for (i = 0; i < slot; i++) if (file_used[i] && i != slot) targetOffset += file_lengths[i] + 1;
|
||||
{ int total = 0;
|
||||
for (i = 0; i < FILE_COUNT; i++) if (file_used[i] && i != slot) total += file_lengths[i] + 1;
|
||||
for (i = total - 1; i >= targetOffset; i--) ((int *)0xf000)[i + length + 1] = ((int *)0xf000)[i];
|
||||
for (i = total - 1; i >= targetOffset; i--) ((int *)WIDE_FILE_BASE)[i + length + 1] = ((int *)WIDE_FILE_BASE)[i];
|
||||
if (sourceSlot >= 0) {
|
||||
int sourceOffset = 0;
|
||||
for (i = 0; i < sourceSlot; i++) if (file_used[i] && i != slot) sourceOffset += file_lengths[i] + 1;
|
||||
if (sourceSlot > slot) sourceOffset += length + 1;
|
||||
data = (int *)0xf000 + sourceOffset;
|
||||
data = (int *)WIDE_FILE_BASE + sourceOffset;
|
||||
}
|
||||
memcpy((int *)0xf000 + targetOffset, data, length);
|
||||
((int *)0xf000)[targetOffset + length] = 0;
|
||||
memcpy((int *)WIDE_FILE_BASE + targetOffset, data, length);
|
||||
((int *)WIDE_FILE_BASE)[targetOffset + length] = 0;
|
||||
file_lengths[slot] = length; file_kinds[slot] = kind;
|
||||
}
|
||||
return slot;
|
||||
@@ -150,7 +157,7 @@ void file_list(void) {
|
||||
if (!count) println("No files.");
|
||||
print("Used "); print_dec(count);
|
||||
#ifdef BOBC_WIDE
|
||||
println("/8 slots; shared 4096-word storage. Text/resident files max 511; native apps use remaining space.");
|
||||
println("/8 slots; shared 8192-word storage. Text files max 511; native apps use remaining space.");
|
||||
#else
|
||||
println("/8 slots; limit 511 words per file. delete frees a slot.");
|
||||
#endif
|
||||
@@ -167,7 +174,7 @@ void file_manage(char *operation, char *name, char *destination) {
|
||||
for (i = 0; i < FILE_COUNT; i++) if (file_used[i]) {
|
||||
if (i == slot) { sourceOffset += file_lengths[i] + 1; continue; }
|
||||
if (sourceOffset != destinationOffset)
|
||||
for (j = 0; j <= file_lengths[i]; j++) ((int *)0xf000)[destinationOffset + j] = ((int *)0xf000)[sourceOffset + j];
|
||||
for (j = 0; j <= file_lengths[i]; j++) ((int *)WIDE_FILE_BASE)[destinationOffset + j] = ((int *)WIDE_FILE_BASE)[sourceOffset + j];
|
||||
sourceOffset += file_lengths[i] + 1; destinationOffset += file_lengths[i] + 1;
|
||||
}
|
||||
#endif
|
||||
|
||||
+19
-7
@@ -1,10 +1,20 @@
|
||||
/* Native shell editing; history is stored before command tokenization. */
|
||||
#define shell_history ((char *)0xe400)
|
||||
#define SHELL_HISTORY_LIMIT 4
|
||||
#define SHELL_HISTORY_ENTRY_SIZE 128
|
||||
int history_count;
|
||||
int input_length;
|
||||
int input_cursor;
|
||||
int input_echo;
|
||||
|
||||
void shell_history_list(void) {
|
||||
int i;
|
||||
for (i = 0; i < history_count; i++) {
|
||||
print_dec(i + 1); print(" ");
|
||||
println(shell_history + i * SHELL_HISTORY_ENTRY_SIZE);
|
||||
}
|
||||
}
|
||||
|
||||
void input_redraw(void) {
|
||||
int i; int width; int start; int end;
|
||||
if (!input_echo) return;
|
||||
@@ -45,9 +55,9 @@ void input_complete(void) {
|
||||
if (input_cursor != input_length) return;
|
||||
if (!start) {
|
||||
#ifdef BOBC_WIDE
|
||||
words = "help echo clear mem halt list ls dir read write edit load run run32 cc go copy rename delete alloc peek poke save restore";
|
||||
words = "help echo clear mem halt history list ls dir read write edit load run run32 cc go copy rename delete alloc peek poke save restore";
|
||||
#else
|
||||
words = "help echo clear mem halt list ls dir read write edit load run cc go copy rename delete alloc peek poke save restore";
|
||||
words = "help echo clear mem halt history list ls dir read write edit load run cc go copy rename delete alloc peek poke save restore";
|
||||
#endif
|
||||
while (*words) {
|
||||
length = 0;
|
||||
@@ -90,7 +100,8 @@ int shell_read_line(void) {
|
||||
if (key == 256 && browsing) browsing--;
|
||||
if (key == 257 && browsing < history_count) browsing++;
|
||||
if (browsing == history_count) memcpy(command_line, draft, strlen(draft) + 1);
|
||||
else memcpy(command_line, shell_history + browsing * 128, strlen(shell_history + browsing * 128) + 1);
|
||||
else memcpy(command_line, shell_history + browsing * SHELL_HISTORY_ENTRY_SIZE,
|
||||
strlen(shell_history + browsing * SHELL_HISTORY_ENTRY_SIZE) + 1);
|
||||
input_length = strlen(command_line); input_cursor = input_length;
|
||||
} else if (key == 258) { if (input_cursor) input_cursor--; }
|
||||
else if (key == 259) { if (input_cursor < input_length) input_cursor++; }
|
||||
@@ -118,11 +129,12 @@ int shell_read_line(void) {
|
||||
if (truncated) return -1;
|
||||
if (key == -1 && !input_length) return -2;
|
||||
if (input_length && (history_count == 0 || strcmp(command_line, shell_history + (history_count - 1) * 128))) {
|
||||
if (history_count == 4) {
|
||||
for (i = 0; i < 384; i++) shell_history[i] = shell_history[i + 128];
|
||||
history_count = 3;
|
||||
if (history_count == SHELL_HISTORY_LIMIT) {
|
||||
for (i = 0; i < (SHELL_HISTORY_LIMIT - 1) * SHELL_HISTORY_ENTRY_SIZE; i++)
|
||||
shell_history[i] = shell_history[i + SHELL_HISTORY_ENTRY_SIZE];
|
||||
history_count = SHELL_HISTORY_LIMIT - 1;
|
||||
}
|
||||
memcpy(shell_history + history_count * 128, command_line, input_length + 1); history_count++;
|
||||
memcpy(shell_history + history_count * SHELL_HISTORY_ENTRY_SIZE, command_line, input_length + 1); history_count++;
|
||||
}
|
||||
return input_length;
|
||||
}
|
||||
@@ -8,6 +8,9 @@
|
||||
|
||||
int main(void) {
|
||||
int length; char *sample;
|
||||
#ifdef BOBC_WIDE
|
||||
file_service_register();
|
||||
#endif
|
||||
println("bob!");
|
||||
#ifdef BOBC_WIDE
|
||||
println("bob32 OS: help COMMAND for usage; go bob.c runs the example.");
|
||||
|
||||
+4
-1
@@ -14,10 +14,12 @@
|
||||
#endif
|
||||
#define WIDE_PROGRAM_BASE 0x20000
|
||||
#define WIDE_VARIABLE_BASE 0xf0000
|
||||
#define WIDE_FILE_BASE 0x1e000
|
||||
#define WIDE_FILE_WORDS 8192
|
||||
#define FILE_COUNT 8
|
||||
#define TEXT_WORDS 512
|
||||
#if BOBC_WIDE
|
||||
#define FILE_WORDS 4096
|
||||
#define FILE_WORDS WIDE_FILE_WORDS
|
||||
#else
|
||||
#define FILE_WORDS 512
|
||||
#endif
|
||||
@@ -28,6 +30,7 @@ int file_find(char *name);
|
||||
int file_prepare_native(char *name);
|
||||
char *file_name(int slot);
|
||||
int *file_content(int slot);
|
||||
void file_service_register(void);
|
||||
#if BOBC_WIDE
|
||||
void memcpy(void *dst, void *src, int count);
|
||||
void memset(void *dst, int value, int count);
|
||||
|
||||
+7
-2
@@ -7,6 +7,7 @@ int editor_undo_length;
|
||||
int editor_has_undo;
|
||||
char *arguments;
|
||||
void nano_edit(char *name);
|
||||
void shell_history_list(void);
|
||||
|
||||
char *next_arg(void) {
|
||||
char *start;
|
||||
@@ -270,7 +271,7 @@ void memory_status(void) {
|
||||
print("Programs "); print_hex(PROGRAM_BASE); print(".."); print_hex(0xbfff); println("");
|
||||
#endif
|
||||
#ifdef BOBC_WIDE
|
||||
println("Files: 8 slots, 4096 words total; text files up to 511 words; native apps share remaining space.");
|
||||
println("Files: 8 slots, 8192 words total; text files up to 511 words; native apps share remaining space.");
|
||||
#else
|
||||
println("Files: 8 slots, 511 words each; stack above 0xE600.");
|
||||
#endif
|
||||
@@ -309,6 +310,7 @@ void command_help(char *name) {
|
||||
else if (strcmp(name, "alloc") == 0 || strcmp(name, "mem") == 0)
|
||||
println("alloc WORDS: allocate/zero heap words, print start address; no free. Example: alloc 16. mem shows remaining heap and memory regions.");
|
||||
else if (strcmp(name, "echo") == 0) println("echo TEXT: print text. Example: echo bob!");
|
||||
else if (strcmp(name, "history") == 0) println("history: list the four most recent nonempty shell commands from this session.");
|
||||
else if (strcmp(name, "clear") == 0) println("clear: clear an ANSI-capable terminal; does not remove files.");
|
||||
else if (strcmp(name, "halt") == 0) println("halt: stop emulator. Unsaved RAM files and allocations are lost; use save before quitting.");
|
||||
else if (strcmp(name, "help") == 0) println("help: list commands. help COMMAND: show usage and an example. Try help edit or help go.");
|
||||
@@ -326,7 +328,7 @@ void SHELL_COMMAND_BODY(char *line) {
|
||||
if (strcmp(command, "help") == 0) {
|
||||
name = next_arg();
|
||||
if (*name) { command_help(name); return; }
|
||||
println("help | echo TEXT | clear | mem | halt");
|
||||
println("help | echo TEXT | history | clear | mem | halt");
|
||||
println("peek ADDRESS | poke ADDRESS VALUE | alloc WORDS");
|
||||
println("list / ls / dir | read NAME | write NAME TEXT | edit NAME");
|
||||
println("copy OLD NEW | rename OLD NEW | delete NAME (permanent in RAM)");
|
||||
@@ -396,6 +398,9 @@ void SHELL_COMMAND_BODY(char *line) {
|
||||
*pointer = value;
|
||||
}
|
||||
print_hex(address); print(": "); print_hex(*pointer); print(" ("); print_dec(*pointer); println(")");
|
||||
} else if (strcmp(command, "history") == 0) {
|
||||
if (*next_arg()) println("Usage: history");
|
||||
else shell_history_list();
|
||||
} else println("Unknown command. Type help.");
|
||||
}
|
||||
#ifdef BOBC_WIDE
|
||||
|
||||
@@ -107,6 +107,7 @@
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdint.h>
|
||||
#include <time.h>
|
||||
#include <stdbool.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
@@ -124,6 +125,50 @@ static bool application32;
|
||||
static uint32_t applicationArgc;
|
||||
static uint32_t applicationArgv;
|
||||
static bool applicationEntryArguments;
|
||||
static bool filesystemRegistered;
|
||||
static uint32_t filesystemNames;
|
||||
static uint32_t filesystemLengths;
|
||||
static uint32_t filesystemKinds;
|
||||
static uint32_t filesystemUsed;
|
||||
enum { GRAPHICS_WIDTH=80, GRAPHICS_HEIGHT=25, GRAPHICS_CELLS=GRAPHICS_WIDTH*GRAPHICS_HEIGHT };
|
||||
enum { SYSTEM_API_VERSION=1, SYSTEM_DEVICE_CELL_FRAMEBUFFER=1, SYSTEM_INPUT_KEYBOARD=1, SYSTEM_INPUT_MOUSE=2 };
|
||||
enum { WIDE_FILE_BASE=0x1e000, WIDE_FILE_WORDS=8192 };
|
||||
static unsigned char graphicsCharacters[GRAPHICS_CELLS];
|
||||
static unsigned char graphicsColors[GRAPHICS_CELLS];
|
||||
static bool graphicsActive;
|
||||
static int terminalAvailable(void);
|
||||
|
||||
static void graphicsReset(void) {
|
||||
for(unsigned i=0;i<GRAPHICS_CELLS;i++){graphicsCharacters[i]=' ';graphicsColors[i]=7;}
|
||||
}
|
||||
static void graphicsPixel(int x,int y,unsigned char character,unsigned char color) {
|
||||
if(x<0 || y<0 || x>=GRAPHICS_WIDTH || y>=GRAPHICS_HEIGHT)return;
|
||||
unsigned index=(unsigned)y*GRAPHICS_WIDTH+(unsigned)x;
|
||||
graphicsCharacters[index]=character?character:' ';graphicsColors[index]=color&15;
|
||||
}
|
||||
static void graphicsPresent(void) {
|
||||
int ansi=terminalAvailable(),lastColor=-1;
|
||||
if(ansi)printf("\033[2J\033[H");
|
||||
for(int y=0;y<GRAPHICS_HEIGHT;y++) {
|
||||
for(int x=0;x<GRAPHICS_WIDTH;x++) {
|
||||
unsigned index=(unsigned)y*GRAPHICS_WIDTH+(unsigned)x;
|
||||
int color=graphicsColors[index];
|
||||
if(ansi && color!=lastColor) {
|
||||
int code=(color&8)?90+(color&7):30+(color&7);
|
||||
printf("\033[%dm",code);lastColor=color;
|
||||
}
|
||||
putchar(graphicsCharacters[index]);
|
||||
}
|
||||
if(ansi)printf("\033[0m");
|
||||
putchar('\n');lastColor=-1;
|
||||
}
|
||||
fflush(stdout);
|
||||
}
|
||||
static void graphicsClose(void) {
|
||||
graphicsActive=false;
|
||||
if(terminalAvailable())printf("\033[0m\033[2J\033[H");
|
||||
fflush(stdout);
|
||||
}
|
||||
static uint32_t bootWords;
|
||||
static uint32_t bootOrigin;
|
||||
static bool bootWideHeader;
|
||||
@@ -136,12 +181,13 @@ static uint32_t assembledWords;
|
||||
static uint32_t assembledOrigin;
|
||||
static uint32_t currentInstructionAddress;
|
||||
static uint16_t currentInstruction;
|
||||
static jmp_buf programFault;
|
||||
static jmp_buf programFaultStack[8];
|
||||
static unsigned programDepth;
|
||||
static void machineFault(void) {
|
||||
if (programMode) {
|
||||
if (getenv("BOB16_TRACE_FAULT"))
|
||||
fprintf(stderr,"Program fault at 0x%08X (instruction 0x%04X)\n",currentInstructionAddress,currentInstruction);
|
||||
longjmp(programFault, 1);
|
||||
longjmp(programFaultStack[programDepth-1], 1);
|
||||
}
|
||||
exit(1);
|
||||
}
|
||||
@@ -202,6 +248,100 @@ static int terminalKey(void) {
|
||||
#endif
|
||||
return getchar();
|
||||
}
|
||||
static unsigned terminalMouseButtons;
|
||||
enum { OS_EVENT_KEY_DOWN=1,OS_EVENT_CHAR=2,OS_EVENT_KEY_UP=3,OS_EVENT_MOUSE_MOVE=4,OS_EVENT_MOUSE_BUTTON_DOWN=5,OS_EVENT_MOUSE_BUTTON_UP=6,OS_EVENT_MOUSE_WHEEL=7 };
|
||||
static int terminalEventDecode(int kind,int isDown,int character,int virtualKey,int x,int y,
|
||||
unsigned buttons,unsigned *buttonState,
|
||||
int *type,int *value,int *outX,int *outY) {
|
||||
if(kind==1) {
|
||||
int code=character;
|
||||
if(!code)switch(virtualKey) {
|
||||
case 38:code=256;break;case 40:code=257;break;
|
||||
case 37:code=258;break;case 39:code=259;break;
|
||||
case 36:code=260;break;case 35:code=261;break;
|
||||
case 46:code=262;break;default:code=512+virtualKey;break;
|
||||
}
|
||||
*type=isDown?(code<256?OS_EVENT_CHAR:OS_EVENT_KEY_DOWN):OS_EVENT_KEY_UP;
|
||||
*value=code;*outX=0;*outY=0;return 1;
|
||||
}
|
||||
if(kind==2) {
|
||||
*outX=x;*outY=y;*value=(int)buttons;
|
||||
if(isDown==1)*type=OS_EVENT_MOUSE_MOVE;
|
||||
else if(character==4) {
|
||||
int delta=(int)(int16_t)(buttons>>16);
|
||||
if(!delta)return 0;
|
||||
*type=OS_EVENT_MOUSE_WHEEL;*value=delta;
|
||||
}
|
||||
else if(buttons!=*buttonState) {
|
||||
*type=(buttons&~*buttonState)?OS_EVENT_MOUSE_BUTTON_DOWN:OS_EVENT_MOUSE_BUTTON_UP;
|
||||
*buttonState=buttons;
|
||||
} else return 0;
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
static int terminalEvent(int *type,int *value,int *x,int *y) {
|
||||
fflush(stdout);
|
||||
#ifdef _WIN32
|
||||
if(terminalAvailable()) {
|
||||
HANDLE input=GetStdHandle(STD_INPUT_HANDLE);DWORD mode,count;INPUT_RECORD record;
|
||||
if(!GetConsoleMode(input,&mode))return 0;
|
||||
DWORD originalMode=mode;
|
||||
mode=(mode&~ENABLE_PROCESSED_INPUT)|ENABLE_MOUSE_INPUT|ENABLE_EXTENDED_FLAGS;
|
||||
if(!SetConsoleMode(input,mode))return 0;
|
||||
if(!rawInputStarted){originalInputMode=originalMode;rawInputStarted=true;atexit(restoreInputMode);}
|
||||
while(ReadConsoleInputA(input,&record,1,&count) && count) {
|
||||
if(record.EventType==KEY_EVENT) {
|
||||
KEY_EVENT_RECORD key=record.Event.KeyEvent;
|
||||
if(terminalEventDecode(1,key.bKeyDown,(unsigned char)key.uChar.AsciiChar,
|
||||
key.wVirtualKeyCode,0,0,0,&terminalMouseButtons,type,value,x,y))return 1;
|
||||
}
|
||||
if(record.EventType==MOUSE_EVENT) {
|
||||
MOUSE_EVENT_RECORD mouse=record.Event.MouseEvent;
|
||||
unsigned buttons=mouse.dwButtonState;
|
||||
int moving=mouse.dwEventFlags==MOUSE_MOVED;
|
||||
if(terminalEventDecode(2,moving,(int)mouse.dwEventFlags,0,
|
||||
mouse.dwMousePosition.X,mouse.dwMousePosition.Y,buttons,
|
||||
&terminalMouseButtons,type,value,x,y))return 1;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
#endif
|
||||
int key=getchar();if(key==EOF)return 0;if(key=='\r')key='\n';
|
||||
return terminalEventDecode(1,1,key,0,0,0,0,&terminalMouseButtons,type,value,x,y);
|
||||
}
|
||||
static int terminalEventPoll(int *type,int *value,int *x,int *y) {
|
||||
#ifdef _WIN32
|
||||
if(terminalAvailable()) {
|
||||
HANDLE input=GetStdHandle(STD_INPUT_HANDLE);DWORD mode,count;INPUT_RECORD record;
|
||||
if(!GetConsoleMode(input,&mode))return 0;
|
||||
DWORD originalMode=mode;
|
||||
mode=(mode&~ENABLE_PROCESSED_INPUT)|ENABLE_MOUSE_INPUT|ENABLE_EXTENDED_FLAGS;
|
||||
if(!SetConsoleMode(input,mode))return 0;
|
||||
if(!rawInputStarted){originalInputMode=originalMode;rawInputStarted=true;atexit(restoreInputMode);}
|
||||
for(;;) {
|
||||
if(!PeekConsoleInputA(input,&record,1,&count)||!count)return 0;
|
||||
if(!ReadConsoleInputA(input,&record,1,&count)||!count)return 0;
|
||||
if(record.EventType==KEY_EVENT) {
|
||||
KEY_EVENT_RECORD key=record.Event.KeyEvent;
|
||||
if(terminalEventDecode(1,key.bKeyDown,(unsigned char)key.uChar.AsciiChar,
|
||||
key.wVirtualKeyCode,0,0,0,&terminalMouseButtons,type,value,x,y))return 1;
|
||||
} else if(record.EventType==MOUSE_EVENT) {
|
||||
MOUSE_EVENT_RECORD mouse=record.Event.MouseEvent;
|
||||
unsigned buttons=mouse.dwButtonState;
|
||||
int moving=mouse.dwEventFlags==MOUSE_MOVED;
|
||||
if(terminalEventDecode(2,moving,(int)mouse.dwEventFlags,0,
|
||||
mouse.dwMousePosition.X,mouse.dwMousePosition.Y,buttons,
|
||||
&terminalMouseButtons,type,value,x,y))return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
#else
|
||||
(void)type;(void)value;(void)x;(void)y;
|
||||
#endif
|
||||
return 0;
|
||||
}
|
||||
|
||||
typedef uint32_t ureg_t;
|
||||
typedef uint16_t instruction_t;
|
||||
@@ -314,14 +454,310 @@ static void memoryReset(void) {
|
||||
memset(sparseMemory,0,sizeof(sparseMemory));
|
||||
}
|
||||
|
||||
typedef struct {uint32_t number;int32_t *words;} SavedSparsePage;
|
||||
static SavedSparsePage *sparseMemorySave(unsigned *count) {
|
||||
unsigned used=0,out=0;
|
||||
for(unsigned i=0;i<MEMORY_PAGE_SLOTS;i++)if(sparseMemory[i].used&&sparseMemory[i].number>=0x20&&sparseMemory[i].number<0x100)used++;
|
||||
*count=used;
|
||||
SavedSparsePage *saved=used?calloc(used,sizeof(*saved)):NULL;
|
||||
if(used&&!saved)return NULL;
|
||||
for(unsigned i=0;i<MEMORY_PAGE_SLOTS;i++)if(sparseMemory[i].used&&sparseMemory[i].number>=0x20&&sparseMemory[i].number<0x100) {
|
||||
saved[out].number=sparseMemory[i].number;
|
||||
saved[out].words=malloc(MEMORY_PAGE_WORDS*sizeof(int32_t));
|
||||
if(!saved[out].words) {
|
||||
for(unsigned j=0;j<out;j++)free(saved[j].words);
|
||||
free(saved);return NULL;
|
||||
}
|
||||
memcpy(saved[out].words,sparseMemory[i].words,MEMORY_PAGE_WORDS*sizeof(int32_t));out++;
|
||||
}
|
||||
*count=used;return saved;
|
||||
}
|
||||
static void sparseMemoryRestore(SavedSparsePage *saved,unsigned count) {
|
||||
for(unsigned i=0;i<MEMORY_PAGE_SLOTS;i++)if(sparseMemory[i].used&&sparseMemory[i].number>=0x20&&sparseMemory[i].number<0x100) {
|
||||
free(sparseMemory[i].words);sparseMemory[i].used=0;sparseMemory[i].words=NULL;
|
||||
}
|
||||
for(unsigned i=0;i<count;i++)memoryPageInstall(saved[i].number,saved[i].words);
|
||||
free(saved);
|
||||
}
|
||||
|
||||
static int runWidePackedFromGuest(uint32_t descriptor,int *started);
|
||||
|
||||
static int filesystemService(uint32_t request) {
|
||||
if(!programMode && (request<0x100 || request>0xf000-4))return -1;
|
||||
if(programMode && (request<0x20000 || request>0xffff9))return -1;
|
||||
uint32_t op=(uint32_t)memoryRead(request);
|
||||
if(!programMode) {
|
||||
if(op!=0 || !cpu32)return -1;
|
||||
filesystemNames=(uint32_t)memoryRead(request+1);
|
||||
filesystemLengths=(uint32_t)memoryRead(request+2);
|
||||
filesystemKinds=(uint32_t)memoryRead(request+3);
|
||||
filesystemUsed=(uint32_t)memoryRead(request+4);
|
||||
uint64_t imageEnd=(uint64_t)bootOrigin+bootWords;
|
||||
if(imageEnd>WIDE_FILE_BASE)return -1;
|
||||
if(filesystemNames<bootOrigin || (uint64_t)filesystemNames+192>imageEnd ||
|
||||
filesystemLengths<bootOrigin || (uint64_t)filesystemLengths+8>imageEnd ||
|
||||
filesystemKinds<bootOrigin || (uint64_t)filesystemKinds+8>imageEnd ||
|
||||
filesystemUsed<bootOrigin || (uint64_t)filesystemUsed+8>imageEnd)return -1;
|
||||
filesystemRegistered=true;return 0;
|
||||
}
|
||||
if(!application32 || !filesystemRegistered)return -1;
|
||||
if((op>>16)!=1)return -4;
|
||||
op&=0xffffu;
|
||||
uint32_t a=(uint32_t)memoryRead(request+1),b=(uint32_t)memoryRead(request+2),c=(uint32_t)memoryRead(request+3),d=(uint32_t)memoryRead(request+4);
|
||||
uint32_t e=(uint32_t)memoryRead(request+5),f=(uint32_t)memoryRead(request+6);
|
||||
#define APP_RANGE(p,n) ((p)>=0x20000u && (uint64_t)(p)+(uint64_t)(n)<=0x100000u)
|
||||
char name[24];unsigned nameLength=0;
|
||||
if((op>=2 && op<=4) || op==8 || op==9 || op==10) {
|
||||
if(!APP_RANGE(a,1))return -1;
|
||||
while(nameLength<sizeof(name)-1 && APP_RANGE(a+nameLength,1)) {
|
||||
uint32_t ch=(uint32_t)memoryRead(a+nameLength);
|
||||
if(!ch)break;
|
||||
if(ch<33 || ch>126)return -1;
|
||||
name[nameLength++]=(char)ch;
|
||||
}
|
||||
if(!nameLength || nameLength==sizeof(name)-1 || nameLength>=24 || (uint32_t)memoryRead(a+nameLength)!=0)return -1;
|
||||
name[nameLength]=0;
|
||||
}
|
||||
int slot=-1;
|
||||
if((op>=2 && op<=4) || op==8 || op==9 || op==10)for(int i=0;i<8;i++) {
|
||||
if(!memoryRead(filesystemUsed+i))continue;
|
||||
unsigned j=0;while(j<23 && (uint32_t)memoryRead(filesystemNames+i*24+j)==(unsigned char)name[j] && name[j])j++;
|
||||
if(j==nameLength && !name[j]){slot=i;break;}
|
||||
}
|
||||
if(op==1) {
|
||||
uint32_t index=a,buffer=b,capacity=c,lengthAddress=d;
|
||||
if(index>=8)return 0;
|
||||
if(!APP_RANGE(buffer,capacity) || !capacity || !APP_RANGE(lengthAddress,1))return -1;
|
||||
if(!memoryRead(filesystemUsed+index))return 0;
|
||||
unsigned n=0;while(n<23 && memoryRead(filesystemNames+index*24+n))n++;
|
||||
if(capacity<=n)return -2;
|
||||
for(unsigned i=0;i<n;i++)memoryWrite(buffer+i,memoryRead(filesystemNames+index*24+i));
|
||||
memoryWrite(buffer+n,0);memoryWrite(lengthAddress,memoryRead(filesystemLengths+index));
|
||||
return (int)memoryRead(filesystemKinds+index)+1;
|
||||
}
|
||||
if(op==2) {
|
||||
uint32_t buffer=b,capacity=c;
|
||||
if(slot<0 || memoryRead(filesystemKinds+slot)!=0)return -1;
|
||||
uint32_t length=(uint32_t)memoryRead(filesystemLengths+slot);
|
||||
if(!APP_RANGE(buffer,capacity) || capacity<=length)return -2;
|
||||
uint32_t offset=0;for(int i=0;i<slot;i++)if(memoryRead(filesystemUsed+i))offset+=(uint32_t)memoryRead(filesystemLengths+i)+1;
|
||||
for(uint32_t i=0;i<length;i++)memoryWrite(buffer+i,memoryRead(WIDE_FILE_BASE+offset+i));
|
||||
memoryWrite(buffer+length,0);return (int)length;
|
||||
}
|
||||
if(op==9) {
|
||||
uint32_t buffer=b,capacity=c;
|
||||
if(slot<0 || memoryRead(filesystemKinds+slot)==0)return -1;
|
||||
uint32_t length=(uint32_t)memoryRead(filesystemLengths+slot);
|
||||
if(!APP_RANGE(buffer,capacity) || capacity<length)return -2;
|
||||
uint32_t offset=0;for(int i=0;i<slot;i++)if(memoryRead(filesystemUsed+i))offset+=(uint32_t)memoryRead(filesystemLengths+i)+1;
|
||||
for(uint32_t i=0;i<length;i++)memoryWrite(buffer+i,memoryRead(WIDE_FILE_BASE+offset+i));
|
||||
return (int)length;
|
||||
}
|
||||
if(op==10)return slot<0?-1:(int)memoryRead(filesystemKinds+slot);
|
||||
if(op==3 || op==8) {
|
||||
uint32_t buffer=b,length=c;
|
||||
uint32_t kind=op==3?0:d;
|
||||
if((op==3 && d!=0) || (op==8 && (kind<1 || kind>2)) ||
|
||||
(!kind && length>=512) || !APP_RANGE(buffer,length))return -1;
|
||||
if(slot<0)for(int i=0;i<8;i++)if(!memoryRead(filesystemUsed+i)){slot=i;break;}
|
||||
if(slot<0)return -1;
|
||||
uint32_t total=length+1;
|
||||
for(int i=0;i<8;i++)if(i!=slot && memoryRead(filesystemUsed+i))total+=(uint32_t)memoryRead(filesystemLengths+i)+1;
|
||||
if(total>WIDE_FILE_WORDS)return -1;
|
||||
if(!kind)for(uint32_t i=0;i<length;i++){uint32_t ch=(uint32_t)memoryRead(buffer+i);if(!ch || ch>255)return -1;}
|
||||
int32_t packed[WIDE_FILE_WORDS];uint32_t out=0;int newLengths[8],newKinds[8],newUsed[8];char newNames[8][24];
|
||||
for(int i=0;i<8;i++) {
|
||||
newUsed[i]=i==slot?1:(int)memoryRead(filesystemUsed+i);
|
||||
if(!newUsed[i]){newLengths[i]=0;newKinds[i]=0;memset(newNames[i],0,24);continue;}
|
||||
uint32_t oldName=filesystemNames+i*24;for(int j=0;j<24;j++)newNames[i][j]=(char)memoryRead(oldName+j);
|
||||
if(i==slot){for(int j=0;j<24;j++)newNames[i][j]=j<(int)nameLength?name[j]:0;newLengths[i]=(int)length;newKinds[i]=(int)kind;
|
||||
for(uint32_t j=0;j<length;j++)packed[out++]=(int32_t)memoryRead(buffer+j);
|
||||
packed[out++]=0;
|
||||
} else {
|
||||
newLengths[i]=(int)memoryRead(filesystemLengths+i);newKinds[i]=(int)memoryRead(filesystemKinds+i);
|
||||
uint32_t offset=0;for(int j=0;j<i;j++)if(memoryRead(filesystemUsed+j))offset+=(uint32_t)memoryRead(filesystemLengths+j)+1;
|
||||
for(int j=0;j<=newLengths[i];j++)packed[out++]=(int32_t)memoryRead(WIDE_FILE_BASE+offset+(uint32_t)j);
|
||||
}
|
||||
}
|
||||
for(uint32_t i=0;i<out;i++)memoryWrite(WIDE_FILE_BASE+i,packed[i]);
|
||||
for(int i=0;i<8;i++) {for(int j=0;j<24;j++)memoryWrite(filesystemNames+i*24+j,(unsigned char)newNames[i][j]);memoryWrite(filesystemLengths+i,newLengths[i]);memoryWrite(filesystemKinds+i,newKinds[i]);memoryWrite(filesystemUsed+i,newUsed[i]);}
|
||||
return 0;
|
||||
}
|
||||
if(op==4) {
|
||||
if(slot<0)return -1;
|
||||
int32_t packed[WIDE_FILE_WORDS];uint32_t out=0;
|
||||
for(int i=0;i<8;i++)if(memoryRead(filesystemUsed+i) && i!=slot) {
|
||||
uint32_t offset=0;for(int j=0;j<i;j++)if(memoryRead(filesystemUsed+j))offset+=(uint32_t)memoryRead(filesystemLengths+j)+1;
|
||||
uint32_t length=(uint32_t)memoryRead(filesystemLengths+i);
|
||||
for(uint32_t j=0;j<=length;j++)packed[out++]=(int32_t)memoryRead(WIDE_FILE_BASE+offset+j);
|
||||
}
|
||||
for(uint32_t i=0;i<out;i++)memoryWrite(WIDE_FILE_BASE+i,packed[i]);
|
||||
uint32_t removedName=filesystemNames+(uint32_t)slot*24;
|
||||
for(int j=0;j<24;j++)memoryWrite(removedName+j,0);
|
||||
memoryWrite(filesystemLengths+slot,0);memoryWrite(filesystemKinds+slot,0);memoryWrite(filesystemUsed+slot,0);
|
||||
return 0;
|
||||
}
|
||||
if(op==5) {
|
||||
uint32_t values=a,capacity=b;
|
||||
if(!APP_RANGE(values,capacity) || capacity<6)return -1;
|
||||
uint32_t appPages=0,files=0,fileWords=0;
|
||||
for(uint32_t page=0x20;page<0x100;page++)if(memoryPage(page,0))appPages++;
|
||||
for(int i=0;i<8;i++)if(memoryRead(filesystemUsed+i)) {files++;fileWords+=(uint32_t)memoryRead(filesystemLengths+i)+1;}
|
||||
memoryWrite(values,1);memoryWrite(values+1,0xE0000);memoryWrite(values+2,appPages);
|
||||
memoryWrite(values+3,files);memoryWrite(values+4,fileWords);memoryWrite(values+5,WIDE_FILE_WORDS-fileWords);
|
||||
return 6;
|
||||
}
|
||||
if(op==11) {
|
||||
uint32_t values=a,capacity=b,inputFlags=SYSTEM_INPUT_KEYBOARD;
|
||||
if(!APP_RANGE(values,capacity)||capacity<5)return -1;
|
||||
#ifdef _WIN32
|
||||
if(terminalAvailable())inputFlags|=SYSTEM_INPUT_MOUSE;
|
||||
#endif
|
||||
memoryWrite(values,SYSTEM_API_VERSION);
|
||||
memoryWrite(values+1,SYSTEM_DEVICE_CELL_FRAMEBUFFER);
|
||||
memoryWrite(values+2,GRAPHICS_WIDTH);memoryWrite(values+3,GRAPHICS_HEIGHT);
|
||||
memoryWrite(values+4,inputFlags);return 5;
|
||||
}
|
||||
if(op==6) {
|
||||
uint32_t nameAddress=a,argumentAddress=b,offset=0;char name[24],arguments[128];
|
||||
unsigned nameLength=0,argumentLength=0;int target=-1,kind,started=0,childStatus;
|
||||
if(!APP_RANGE(c,1))return -1;
|
||||
while(nameLength<sizeof(name)-1&&APP_RANGE(nameAddress+nameLength,1)) {
|
||||
uint32_t ch=(uint32_t)memoryRead(nameAddress+nameLength);
|
||||
if(!ch)break;
|
||||
if(ch<33||ch>126)return -1;
|
||||
name[nameLength++]=(char)ch;
|
||||
}
|
||||
if(!nameLength||nameLength>=sizeof(name)-1||!APP_RANGE(nameAddress+nameLength,1)||memoryRead(nameAddress+nameLength))return -1;
|
||||
name[nameLength]=0;
|
||||
if(argumentAddress) {
|
||||
while(argumentLength<sizeof(arguments)-1&&APP_RANGE(argumentAddress+argumentLength,1)) {
|
||||
uint32_t ch=(uint32_t)memoryRead(argumentAddress+argumentLength);
|
||||
if(ch>255)return -1;
|
||||
arguments[argumentLength++]=(char)ch;
|
||||
if(!ch)break;
|
||||
}
|
||||
if(!argumentLength||arguments[argumentLength-1])return -1;
|
||||
} else arguments[argumentLength++]=0;
|
||||
for(int i=0;i<8;i++)if(memoryRead(filesystemUsed+i)) {
|
||||
unsigned j=0;while(j<23&&(uint32_t)memoryRead(filesystemNames+i*24+j)==(unsigned char)name[j]&&name[j])j++;
|
||||
if(j==nameLength&&!name[j]){target=i;break;}
|
||||
}
|
||||
if(target<0)return -1;
|
||||
kind=(int)memoryRead(filesystemKinds+target);
|
||||
if(kind!=3)return -2;
|
||||
for(int i=0;i<target;i++)if(memoryRead(filesystemUsed+i))offset+=(uint32_t)memoryRead(filesystemLengths+i)+1;
|
||||
memoryWrite(0xe000,WIDE_FILE_BASE+offset);memoryWrite(0xe001,memoryRead(filesystemLengths+target));
|
||||
for(unsigned i=0;i<argumentLength;i++)memoryWrite(0xe100+i,(unsigned char)arguments[i]);
|
||||
for(unsigned i=0;i<=nameLength;i++)memoryWrite(0xe200+i,(unsigned char)name[i]);
|
||||
memoryWrite(0xe002,0xe100);memoryWrite(0xe003,0xe200);
|
||||
childStatus=runWidePackedFromGuest(0xe000,&started);
|
||||
if(!started)return childStatus;
|
||||
memoryWrite(c,childStatus);return 0;
|
||||
}
|
||||
if(op==7) {
|
||||
uint32_t words=a,capacity=b;
|
||||
time_t now=time(NULL);
|
||||
if(!APP_RANGE(words,capacity) || capacity<2 || now<0)return -1;
|
||||
uint64_t seconds=(uint64_t)now;
|
||||
memoryWrite(words,(int32_t)(uint32_t)seconds);
|
||||
memoryWrite(words+1,(int32_t)(uint32_t)(seconds>>32));
|
||||
return 2;
|
||||
}
|
||||
if(op==16) { graphicsReset();graphicsActive=true;return 0; }
|
||||
if(op==17) {
|
||||
if(!graphicsActive || !APP_RANGE(a,b) || b<2)return -1;
|
||||
memoryWrite(a,GRAPHICS_WIDTH);memoryWrite(a+1,GRAPHICS_HEIGHT);return 2;
|
||||
}
|
||||
if(op==18) {
|
||||
if(!graphicsActive || (int32_t)a<0 || (int32_t)b<0 || a>=GRAPHICS_WIDTH || b>=GRAPHICS_HEIGHT || c>255 || d>15)return -1;
|
||||
graphicsPixel((int)a,(int)b,(unsigned char)c,(unsigned char)d);return 0;
|
||||
}
|
||||
if(op==19) {
|
||||
int x=(int32_t)a,y=(int32_t)b,w=(int32_t)c,h=(int32_t)d;
|
||||
if(!graphicsActive || w<=0 || h<=0 || w>GRAPHICS_WIDTH*2 || h>GRAPHICS_HEIGHT*2 || e>255 || f>15)return -1;
|
||||
int64_t endX=(int64_t)x+w,endY=(int64_t)y+h;
|
||||
int startX=x<0?0:x,startY=y<0?0:y;
|
||||
int clippedX=endX>GRAPHICS_WIDTH?GRAPHICS_WIDTH:(int)endX;
|
||||
int clippedY=endY>GRAPHICS_HEIGHT?GRAPHICS_HEIGHT:(int)endY;
|
||||
for(int py=startY;py<clippedY;py++)for(int px=startX;px<clippedX;px++)graphicsPixel(px,py,(unsigned char)e,(unsigned char)f);
|
||||
return 0;
|
||||
}
|
||||
if(op==20) {
|
||||
int x0=(int32_t)a,y0=(int32_t)b,x1=(int32_t)c,y1=(int32_t)d;
|
||||
if(!graphicsActive || x0<0 || x0>=GRAPHICS_WIDTH || x1<0 || x1>=GRAPHICS_WIDTH || y0<0 || y0>=GRAPHICS_HEIGHT || y1<0 || y1>=GRAPHICS_HEIGHT || e>255 || f>15)return -1;
|
||||
int dx=abs(x1-x0),sx=x0<x1?1:-1,dy=-abs(y1-y0),sy=y0<y1?1:-1,error=dx+dy;
|
||||
for(;;){graphicsPixel(x0,y0,(unsigned char)e,(unsigned char)f);if(x0==x1 && y0==y1)break;int twice=2*error;if(twice>=dy){error+=dy;x0+=sx;}if(twice<=dx){error+=dx;y0+=sy;}}
|
||||
return 0;
|
||||
}
|
||||
if(op==21) {
|
||||
int x=(int32_t)a,y=(int32_t)b,startX=x;uint32_t text=c,color=d;
|
||||
if(!graphicsActive || (int32_t)x<0 || x>=GRAPHICS_WIDTH || y<0 || y>=GRAPHICS_HEIGHT || !APP_RANGE(text,1) || color>15)return -1;
|
||||
for(unsigned i=0;i<GRAPHICS_CELLS && APP_RANGE(text+i,1);i++) {
|
||||
uint32_t ch=(uint32_t)memoryRead(text+i);if(!ch)break;
|
||||
if(ch=='\n'){x=startX;y++;if(y>=GRAPHICS_HEIGHT)break;continue;}
|
||||
graphicsPixel(x++,y,(unsigned char)(ch<=255?ch:'?'),(unsigned char)color);
|
||||
if(x>=GRAPHICS_WIDTH)break;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if(op==22) {
|
||||
int x=(int32_t)a,y=(int32_t)b,w=(int32_t)c,h=(int32_t)d;uint32_t bitmap=e,color=f;
|
||||
if(!graphicsActive || x<0 || y<0 || x>=GRAPHICS_WIDTH || y>=GRAPHICS_HEIGHT || w<=0 || h<=0 || w>GRAPHICS_WIDTH-x || h>GRAPHICS_HEIGHT-y || (uint64_t)w*h>GRAPHICS_CELLS || !APP_RANGE(bitmap,(uint64_t)w*h) || color>15)return -1;
|
||||
for(int py=0;py<h;py++)for(int px=0;px<w;px++) {
|
||||
uint32_t ch=(uint32_t)memoryRead(bitmap+(uint32_t)py*w+(uint32_t)px);
|
||||
if(ch>255)return -1;
|
||||
if(ch)graphicsPixel(x+px,y+py,(unsigned char)ch,(unsigned char)color);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if(op==27) {
|
||||
int x=(int32_t)a,y=(int32_t)b,w=(int32_t)c,h=(int32_t)d;uint32_t bitmap=e;
|
||||
if(!graphicsActive || x<0 || y<0 || x>=GRAPHICS_WIDTH || y>=GRAPHICS_HEIGHT || w<=0 || h<=0 || w>GRAPHICS_WIDTH-x || h>GRAPHICS_HEIGHT-y || (uint64_t)w*h>GRAPHICS_CELLS || !APP_RANGE(bitmap,(uint64_t)w*h))return -1;
|
||||
for(int i=0;i<w*h;i++)if((uint32_t)memoryRead(bitmap+(uint32_t)i)>0xfffu)return -1;
|
||||
for(int py=0;py<h;py++)for(int px=0;px<w;px++) {
|
||||
uint32_t cell=(uint32_t)memoryRead(bitmap+(uint32_t)py*w+(uint32_t)px);
|
||||
uint32_t ch=cell&255u,color=(cell>>8)&15u;
|
||||
if(ch)graphicsPixel(x+px,y+py,(unsigned char)ch,(unsigned char)color);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if(op==23) {
|
||||
if(!graphicsActive || a>255 || b>15)return -1;
|
||||
for(unsigned i=0;i<GRAPHICS_CELLS;i++){graphicsCharacters[i]=(unsigned char)(a?a:' ');graphicsColors[i]=(unsigned char)b;}
|
||||
return 0;
|
||||
}
|
||||
if(op==24) {if(!graphicsActive)return -1;graphicsPresent();return 0;}
|
||||
if(op==25) {if(!graphicsActive)return -1;graphicsClose();return 0;}
|
||||
if(op==26) {
|
||||
uint32_t event=a,capacity=b;
|
||||
if(!APP_RANGE(event,capacity) || capacity<4)return -1;
|
||||
int type,value,x,y;
|
||||
if(!terminalEvent(&type,&value,&x,&y))return 0;
|
||||
memoryWrite(event,type);memoryWrite(event+1,value);
|
||||
memoryWrite(event+2,x);memoryWrite(event+3,y);return 1;
|
||||
}
|
||||
if(op==28) {
|
||||
uint32_t event=a,capacity=b;
|
||||
if(!APP_RANGE(event,capacity) || capacity<4)return -1;
|
||||
int type,value,x,y;
|
||||
if(!terminalEventPoll(&type,&value,&x,&y))return 0;
|
||||
memoryWrite(event,type);memoryWrite(event+1,value);
|
||||
memoryWrite(event+2,x);memoryWrite(event+3,y);return 1;
|
||||
}
|
||||
#undef APP_RANGE
|
||||
return -1;
|
||||
}
|
||||
|
||||
void cpuCycle(void);
|
||||
|
||||
static int runProgram(uint32_t entry) {
|
||||
bool savedCpu32=cpu32;
|
||||
bool savedLegacyProgram32=legacyProgram32;
|
||||
bool savedProgramMode=programMode,savedProgramDone=programDone;
|
||||
volatile uint32_t legacyBase=savedCpu32?0xc200u:0xa000u;
|
||||
volatile uint32_t legacyEnd=savedCpu32?0xd000u:0xbe00u;
|
||||
if (programMode || (application32 ? (entry < 0x20000 || entry >= 0xf0000) : (entry < legacyBase || entry >= legacyEnd))) return -1;
|
||||
if (programDepth>=8 || (application32 ? (entry < 0x20000 || entry >= 0xf0000) : (entry < legacyBase || entry >= legacyEnd))) return -1;
|
||||
struct cpu_t saved = cpu;
|
||||
ureg_t savedMar = ram.mar;
|
||||
reg_t savedMdr = ram.mdr;
|
||||
@@ -330,7 +766,8 @@ static int runProgram(uint32_t entry) {
|
||||
programMode = true;
|
||||
programDone = false;
|
||||
bool savedApplicationEntryArguments=applicationEntryArguments;
|
||||
if (setjmp(programFault) == 0) {
|
||||
unsigned frame=programDepth++;
|
||||
if (setjmp(programFaultStack[frame]) == 0) {
|
||||
if(!application32)cpu32=false;
|
||||
cpu.pc = addressValue(entry);
|
||||
cpu.regFile[6] = wordValue(application32?0x100000u:(savedCpu32?0xd000u:0xc000u));
|
||||
@@ -345,7 +782,9 @@ static int runProgram(uint32_t entry) {
|
||||
}
|
||||
status = cycles == 5000000 ? -3 : (int32_t)(uint32_t)cpu.regFile[0];
|
||||
}
|
||||
programMode = false;
|
||||
programDepth--;
|
||||
programMode = savedProgramMode;
|
||||
if(application32 && graphicsActive)graphicsClose();
|
||||
if(savedCpu32 && !application32 && bootWideHeader) {
|
||||
uint64_t imageEnd=(uint64_t)bootOrigin+bootWords;
|
||||
uint32_t restoreStart=bootOrigin>legacyBase?bootOrigin:legacyBase;
|
||||
@@ -355,13 +794,14 @@ static int runProgram(uint32_t entry) {
|
||||
cpu32=savedCpu32;
|
||||
legacyProgram32=savedLegacyProgram32;
|
||||
applicationEntryArguments=savedApplicationEntryArguments;
|
||||
programDone=savedProgramDone;
|
||||
cpu = saved;
|
||||
ram.mar = savedMar;
|
||||
ram.mdr = savedMdr;
|
||||
return status;
|
||||
}
|
||||
static int runWideImageFromGuest(uint32_t pathAddress);
|
||||
static int runWidePackedFromGuest(uint32_t descriptor);
|
||||
static int runWidePackedFromGuest(uint32_t descriptor,int *started);
|
||||
static int importWideImageFromGuest(uint32_t descriptor);
|
||||
|
||||
int sext(int16_t val, uint16_t length) {
|
||||
@@ -643,13 +1083,17 @@ void execute() {
|
||||
else cpu.regFile[0]=wordValue((uint32_t)runWideImageFromGuest((uint32_t)cpu.regFile[0]));
|
||||
break;
|
||||
case 13:
|
||||
if(programMode || !cpu32)cpu.regFile[0]=-4;
|
||||
else cpu.regFile[0]=wordValue((uint32_t)runWidePackedFromGuest((uint32_t)cpu.regFile[0]));
|
||||
if(!cpu32)cpu.regFile[0]=-4;
|
||||
else cpu.regFile[0]=wordValue((uint32_t)runWidePackedFromGuest((uint32_t)cpu.regFile[0],NULL));
|
||||
break;
|
||||
case 14:
|
||||
if(programMode || !cpu32)cpu.regFile[0]=-4;
|
||||
else cpu.regFile[0]=wordValue((uint32_t)importWideImageFromGuest((uint32_t)cpu.regFile[0]));
|
||||
break;
|
||||
case 15:
|
||||
if(!cpu32)cpu.regFile[0]=-4;
|
||||
else cpu.regFile[0]=wordValue((uint32_t)filesystemService((uint32_t)cpu.regFile[0]));
|
||||
break;
|
||||
default:
|
||||
machineFault();
|
||||
}
|
||||
@@ -1312,6 +1756,8 @@ static int assembleSource(FILE *file) {
|
||||
}
|
||||
|
||||
static void bootImage(const char *path) {
|
||||
filesystemRegistered=false;
|
||||
graphicsActive=false;graphicsReset();
|
||||
FILE *file = fopen(path, "rb");
|
||||
if (!file) { perror(path); exit(1); }
|
||||
char magic[4];
|
||||
@@ -1393,11 +1839,13 @@ static int prepareApplicationArguments(const char *programName,const char *text)
|
||||
storage[write++]=storage[scan++];
|
||||
}
|
||||
if(quote)return -4;
|
||||
storage[write]=0;scan++;
|
||||
int separated=storage[scan]!=0;
|
||||
storage[write]=0;if(separated)scan++;
|
||||
}
|
||||
for(unsigned i=0;i<nameLength;i++)memoryWrite(0xF0000u+i,(unsigned char)programName[i]);
|
||||
memoryWrite(0xF0000u+nameLength,0);
|
||||
for(unsigned i=0;i<length;i++)memoryWrite(0xF0000u+nameLength+1+i,(unsigned char)storage[i]);
|
||||
memoryWrite(0xF0000u+nameLength+1+length,0);
|
||||
pointers[0]=0xF0000u;
|
||||
uint32_t argv=0xF0000u+nameLength+length+2;
|
||||
for(unsigned i=0;i<argc;i++)memoryWrite(argv+i,pointers[i]);
|
||||
@@ -1466,7 +1914,8 @@ static int runWideImageFromGuest(uint32_t pathAddress) {
|
||||
return status;
|
||||
}
|
||||
|
||||
static int runWidePackedFromGuest(uint32_t descriptor) {
|
||||
static int runWidePackedFromGuest(uint32_t descriptor,int *started) {
|
||||
if(started)*started=0;
|
||||
if(descriptor<0x300 || descriptor>0xf000-4)return -4;
|
||||
uint32_t address=(uint32_t)memoryRead(descriptor),length=(uint32_t)memoryRead(descriptor+1);
|
||||
uint32_t argumentAddress=(uint32_t)memoryRead(descriptor+2);
|
||||
@@ -1497,7 +1946,9 @@ static int runWidePackedFromGuest(uint32_t descriptor) {
|
||||
}
|
||||
if(!i || programNameBuffer[i-1])return -4;
|
||||
} else programNameBuffer[0]=0;
|
||||
if(address<0xf000 || address>=0x10000 || !length || length>4096 || address+length>0x10000)return -4;
|
||||
int oldStorage=address>=0xf000&&address<0x10000&&length<=4096&&address+length<=0x10000;
|
||||
int wideStorage=address>=WIDE_FILE_BASE&&address<WIDE_FILE_BASE+WIDE_FILE_WORDS&&length<=WIDE_FILE_WORDS&&address+length<=WIDE_FILE_BASE+WIDE_FILE_WORDS;
|
||||
if((!oldStorage&&!wideStorage)||!length)return -4;
|
||||
if((uint32_t)memoryRead(address)!=0x4233324bu || (uint32_t)memoryRead(address+1)!=0x00180002u)return -4;
|
||||
uint32_t origin=(uint32_t)memoryRead(address+2),entry=(uint32_t)memoryRead(address+3);
|
||||
uint32_t count=(uint32_t)memoryRead(address+4),checksum=(uint32_t)memoryRead(address+5);
|
||||
@@ -1519,21 +1970,38 @@ static int runWidePackedFromGuest(uint32_t descriptor) {
|
||||
if(!pending[pendingCount].words) {for(unsigned i=0;i<pendingCount;i++)free(pending[i].words);free(pending);return -5;}
|
||||
pendingCount++;
|
||||
}
|
||||
bool nested=programMode;
|
||||
unsigned savedPageCount=0;
|
||||
SavedSparsePage *savedPages=nested?sparseMemorySave(&savedPageCount):NULL;
|
||||
if(nested&&savedPageCount&&!savedPages) {for(unsigned i=0;i<pendingCount;i++)free(pending[i].words);free(pending);return -5;}
|
||||
bool savedApplication32=application32,savedEntryArguments=applicationEntryArguments,savedGraphicsActive=graphicsActive;
|
||||
uint32_t savedArgc=applicationArgc,savedArgv=applicationArgv;
|
||||
unsigned char savedGraphicsCharacters[GRAPHICS_CELLS],savedGraphicsColors[GRAPHICS_CELLS];
|
||||
if(nested){memcpy(savedGraphicsCharacters,graphicsCharacters,sizeof(graphicsCharacters));memcpy(savedGraphicsColors,graphicsColors,sizeof(graphicsColors));}
|
||||
for(unsigned i=0;i<pendingCount;i++)memoryPageInstall(pending[i].number,pending[i].words);
|
||||
free(pending);
|
||||
if(needsArgumentPage && !memoryPage(argumentPage,1))return -5;
|
||||
if(needsArgumentPage && !memoryPage(argumentPage,1)) {if(nested)sparseMemoryRestore(savedPages,savedPageCount);return -5;}
|
||||
for(uint32_t i=0;i<count;i++)memoryWrite(origin+i,wordValue((uint32_t)memoryRead(address+6+i)));
|
||||
application32=true;applicationEntryArguments=programNameAddress!=0;
|
||||
int prepared=programNameAddress?prepareApplicationArguments(programNameBuffer,arguments):0;
|
||||
if(!prepared&&started)*started=1;
|
||||
int status=prepared?prepared:runProgram(entry);
|
||||
application32=false;applicationEntryArguments=false;applicationArgc=0;applicationArgv=0;return status;
|
||||
if(nested) {
|
||||
sparseMemoryRestore(savedPages,savedPageCount);
|
||||
memcpy(graphicsCharacters,savedGraphicsCharacters,sizeof(graphicsCharacters));
|
||||
memcpy(graphicsColors,savedGraphicsColors,sizeof(graphicsColors));graphicsActive=savedGraphicsActive;
|
||||
application32=savedApplication32;applicationEntryArguments=savedEntryArguments;applicationArgc=savedArgc;applicationArgv=savedArgv;
|
||||
} else {application32=false;applicationEntryArguments=false;applicationArgc=0;applicationArgv=0;}
|
||||
return status;
|
||||
}
|
||||
|
||||
static int importWideImageFromGuest(uint32_t descriptor) {
|
||||
if(descriptor<0x300 || descriptor>0xf000-3)return -4;
|
||||
uint32_t pathAddress=(uint32_t)memoryRead(descriptor),destination=(uint32_t)memoryRead(descriptor+1),capacity=(uint32_t)memoryRead(descriptor+2);
|
||||
if(pathAddress<0x100 || pathAddress>=0xf000)return -4;
|
||||
if(destination<0xf000 || destination>=0x10000 || capacity>0x10000-destination || capacity<7)return -4;
|
||||
int oldStorage=destination>=0xf000&&destination<0x10000&&capacity<=0x10000-destination;
|
||||
int wideStorage=destination>=WIDE_FILE_BASE&&destination<WIDE_FILE_BASE+WIDE_FILE_WORDS&&capacity<=WIDE_FILE_BASE+WIDE_FILE_WORDS-destination;
|
||||
if((!oldStorage&&!wideStorage)||capacity<7)return -4;
|
||||
char path[512];unsigned pathLength=0;
|
||||
while(pathLength<sizeof(path)-1 && pathAddress+pathLength<0xf000) {uint32_t c=(uint32_t)memoryRead(pathAddress+pathLength);if(!c)break;if(c>255)return -4;path[pathLength++]=(char)c;}
|
||||
if(!pathLength || pathLength==sizeof(path)-1)return -4;
|
||||
|
||||
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user