d
This commit is contained in:
Alvin-Zilverstand committed 2026-10-09 20:06:51 +02:00
1 parent 3d06f94e48
commit 57787bfc7f
59 files changed
+9967 -410

No files matched your search

+351 -59
View File
@@ -74,10 +74,11 @@ the existing emulator/build outputs stay separate.
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.
to those stubs and a fatal fallback, and prints all saved general registers,
the interrupted 64-bit RSP, and user SS over COM1 and the framebuffer. Page
faults also report the 64-bit CR2 address. The DPL3 vector `0x80` enters a
dedicated syscall stub; QEMU runtime tests exercise syscall delivery and
recover from a user invalid-opcode exception.
- `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
@@ -98,7 +99,9 @@ the existing emulator/build outputs stay separate.
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.
invalid framebuffer bounds. QEMU/OVMF runtime tests capture a PPM screen dump
while the desktop is open and verify its dimensions and sampled color variety;
physical firmware/display combinations still need broader 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
@@ -114,10 +117,51 @@ the existing emulator/build outputs stay separate.
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.
COM1 receive uses a bounded IRQ4 queue when available and falls back to
polling otherwise. Unit tests cover serial/keyboard/mouse queues and shell
command/edit behavior. A 100 Hz PIT IRQ supplies a monotonic tick counter
through the versioned syscall ABI. Shell history and completion are
implemented. USB HID boot-keyboard reports enter the shared key-event queue
and shell input path, while boot-mouse reports update the shared pointer and
mouse-event queue. QEMU verifies both with the 8042 disabled.
- `bob64/pci.c` enumerates PCI functions from bus 0 and follows secondary buses
through PCI-to-PCI bridges. It identifies USB host-controller class codes and
decodes assigned I/O, 32-bit memory, and 64-bit memory BARs. Host tests cover
bridge traversal, xHCI classification, and BAR decoding; QEMU/OVMF adds a
qemu-xhci controller and verifies detection during the kernel's boot. The
kernel enables PCI memory decoding, maps xHCI registers uncached, parses the
version/limits/scratchpad requirement and offsets with aligned MMIO reads,
then halts and resets the controller. It identity-maps DMA pages, initializes
command/event rings and the event-ring segment table, starts the xHC, and
verifies a No Op command completion. Host state-machine tests cover running/
halted, controller-not-ready and reset-timeout paths; QEMU verifies the real
command completion and scans root-port status. The QEMU profile attaches an
emulated USB keyboard and verifies root-port reset, slot assignment, an
Address Device command, and endpoint-0 GET_DESCRIPTOR requests for the device
and configuration descriptors. A bounded descriptor parser locates the HID
boot-keyboard interface and interrupt-IN endpoint. The kernel sends
SET_CONFIGURATION and HID SET_PROTOCOL and configures the interrupt-IN
endpoint. It keeps a report transfer posted, decodes HID key transitions into
the existing queue, and re-arms after each report. Up to 32 directly
connected boot-HID devices have independent slots, rings, report buffers,
and event polling, bounded by the controller's advertised slot count. Each
USB keyboard tracks held keys and modifiers independently, and USB/PS/2 mouse
buttons are aggregated so one device's release preserves another's holds. With
the 8042 disabled, QEMU attaches both a keyboard and mouse,
types `version`, launches the managed mouse smoke app and verifies movement,
wheel, and button activation, then launches the desktop, opens and closes
Help, and returns to the shell. Three-button boot reports are supported.
xHCI root-port disconnect events release held USB keyboard keys/modifiers and
mouse buttons; repeated transfer failures also release the device state.
QEMU hot-unplug testing holds a key, removes the keyboard, and verifies
release. Directly connected HID devices are re-enumerated after a port
reconnect, reusing inactive HID records and disabling the removed xHCI slot;
the QEMU disconnect probe verifies a new interrupt report after re-add.
USB 2 hubs now enumerate boot-HID children and handle downstream HID
hotplug; a separate QEMU hub profile verifies input, held-key release, and
reconnection. A QEMU `many` profile checks nine directly
connected devices (one keyboard and eight mice) and requires every expected
HID endpoint to configure before accepting the shell and GUI input checks.
- `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
@@ -128,19 +172,23 @@ the existing emulator/build outputs stay separate.
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 a RAM
checkpoint and store a compressed B64S copy in a non-volatile UEFI variable
when firmware capacity permits. Startup restores that snapshot after
checkpoint and store a compressed B64S copy in non-volatile UEFI variables
when firmware capacity permits, and can store it in a dedicated GPT partition
on USB mass storage. Startup restores that snapshot after
installing the default apps. Host tests cover round-trip, empty files,
replace-on-restore,
truncation, unsupported versions, checksum errors, and unchanged state after
rejected input. A mock runtime-services suite verifies compressed variable
save/restore, corruption rejection, and missing-variable behavior. QEMU/OVMF
reboot testing saved a shell-created file to writable NVRAM, reset the VM, and
verified the file after automatic restore. Disk-backed
filesystem persistence and directories remain future stages; the
app filesystem ABI supports bounded whole-file operations and ABI v12 streaming
handles with 64-bit seek positions and bounded reads/writes; disk-backed
persistence remains outstanding.
verified the file after automatic restore. The disk store uses two alternating
checksummed B64S generations and is wired into shell save/restore and boot
restore; host tests cover damaged-generation fallback and failed commits.
The opt-in QEMU/OVMF `-DiskSnapshotTest` passed save, reset, disk restore,
continued shell/app/GUI use, and raw-image B64D/B64S verification. Directories
and direct per-file block-backed storage are still future work. The app filesystem ABI supports bounded whole-file
operations and ABI v12 streaming handles with 64-bit seek positions and
bounded reads/writes.
- `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
@@ -170,8 +218,9 @@ the existing emulator/build outputs stay separate.
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.
B64E image with a bounded 1024x768 static surface. QEMU/OVMF verifies its
640x400 managed window, pixel presentation, close controls, and return to the
shell.
- `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,
@@ -185,18 +234,28 @@ the existing emulator/build outputs stay separate.
filenames, streams files in 4 KiB chunks, and supports up to 16 KiB of text,
matching the resident compiler's source limit. The shell launches it with
`run desktop.b64e [filename]`; host tests cover the editor buffer, packaged
UI strings, file ABI and window manager. The full existing bob GUI, a file
picker and real UEFI interaction remain to be ported/verified.
UI strings, file ABI and window manager. QEMU/OVMF verifies the Files,
Editor, Applications, Help and delete-confirmation windows; keyboard and
mouse selection, menus and buttons; editing and Save As; launching child
apps; and returning to the desktop. Independent apps still run synchronously,
so launching one pauses input to the desktop until it exits. A physical UEFI
machine has not been used for validation.
- `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/libc.c` runtime provides memory operations and common string helpers
with 64-bit sizes, plus bounded `bob64_snprintf` formatting for strings,
characters, signed/unsigned integers, pointers, flags, widths, and precision.
Floating-point conversions are rejected because the runtime has no floating-
point formatting support. Host tests cover string edge cases, format
truncation, 64-bit pointers, and integer boundaries; the boot smoke app also
formats and checks output from a packaged ring-3 x86-64 image under QEMU.
- `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`
`long`, `long long`, or `int main(void)`, initialized or uninitialized scalar
locals and assignments,
`bob64_app_write` calls with typed `char *` expressions and scalar length
expressions, and 64-bit integer
@@ -212,9 +271,20 @@ the existing emulator/build outputs stay separate.
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. Bounded file-scope
declarations also accept `unsigned long long` and the equivalent spelling
`unsigned long long int`, backed by the same unsigned 64-bit representation;
the host suite checks `sizeof`, calls, wraparound, and comparisons across bit
63. The embedded `bob.c` demo repeats the type, call, wraparound, and
high-bit comparison checks through the resident compiler under QEMU.
Other unsigned object widths are still unsupported. Bounded file-scope
typedefs alias supported scalar types, scalar pointers, and previously
declared named structs; alias chains work, while typedef arrays, function
pointers, anonymous structs and header inclusion remain unsupported.
Explicit scalar and pointer casts now support integer/pointer round trips and
the LLP64 narrowing/sign-extension rules for `char`, `short`, and `int`;
host compiler execution tests cover truncation at 8, 16, and 32 bits, signed
extension, and preserving 64-bit pointer values. The QEMU resident compile
and run path exercises these casts in the embedded `bob.c` demonstration.
`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,
@@ -229,7 +299,13 @@ the existing emulator/build outputs stay separate.
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.
returned string literal used by the caller. Opaque `void *` values can now be
stored in local/global variables and struct fields, passed and returned,
compared with compatible object pointers, and converted back to a typed
object pointer. Global initializers can point to scalars, arrays, and strings.
`void *` arithmetic, indexing, and dereference remain rejected until a typed
conversion is made. Host runtime tests exercise the Microsoft x64 call ABI
and verify invalid dereference and arithmetic are rejected.
- `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
@@ -251,8 +327,10 @@ the existing emulator/build outputs stay separate.
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.
mapping with rollback on collisions and allocation failure, 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
@@ -261,12 +339,15 @@ the existing emulator/build outputs stay separate.
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
GDT/IDT and new CR3. A deliberate invalid opcode is diagnosed with the full
64-bit GPR frame, interrupted RSP and user SS, then returned to the kernel.
The smoke app sets R15 to a distinctive value above 4 GiB, and QEMU asserts
its exact printed value and the high user stack. A diagnosed protection
fault also reports the exact CR2 address above 4 GiB. The IDT contains PIT,
PS/2 keyboard, and PS/2 mouse IRQ
handlers; PIT tick advancement is now checked at runtime, keyboard IRQ
delivery is exercised by the shell/desktop sessions, and live mouse-event
assertions remain open below.
delivery is exercised by the shell/desktop sessions, and movement plus wheel
events are verified in a focused ring-3 window 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
@@ -304,7 +385,30 @@ the existing emulator/build outputs stay separate.
restored on return. Host syscall tests cover nested context restoration, and
the boot image includes a `bob!` nested-launch smoke app; QEMU runtime testing
confirms the child returns and the parent continues.
- [ ] Add USB keyboard support; COM1 remains polled.
- [x] Buffer COM1 input through a bounded IRQ4 receive queue with polling
fallback. Host tests cover FIFO order, saturation and slot reuse; the QEMU
runtime suite sends `version`, `write`, and `cat` commands through the serial
port and verifies shell output and filesystem round-trip.
- [x] Add PCI configuration-space enumeration as the discovery foundation for
USB support. The kernel follows PCI bridges, reports USB host controllers,
enables its memory decoding, and decodes BAR resources. Unit tests and
QEMU/OVMF verify xHCI capability reads and a completed halt/reset; USB input
is provided by the separate USB HID input milestone below.
- [x] Complete xHCI DMA rings and direct-attach USB HID support for up to
32 devices, bounded by the controller's slot count. Initial
command/event rings, QEMU-verified No Op completion, and connected-root-port
detection, USB2 root-port reset, Enable Slot, Address Device, device and
configuration descriptor reads, and HID boot keyboard/mouse endpoint
discovery are in place. QEMU verifies SET_CONFIGURATION/SET_PROTOCOL,
endpoint configuration, ongoing report re-arming, keyboard shell input, and
mouse events with the 8042 disabled. Three-button reports are supported,
four-byte reports pass signed wheel deltas into the GUI event queue, and
independent keyboard/mouse state is tested. A QEMU `many` profile configures
one keyboard and eight mice together. Root-port hot-unplug releases held input
state, verified by a QEMU device-removal probe. Directly attached HID devices
automatically re-enumerate after reconnect; the QEMU probe verifies a fresh
interrupt report. USB 2 hub child enumeration, hotplug, and reconnection are
covered in the hub milestones below; other USB classes remain open.
- [x] Add an eight-command shell history on Up/Down and Tab completion for
built-in commands plus file arguments to `cat`, `rm`, `run`, and `cc`. Host
tests cover draft restoration, keyboard arrow translation, and unique command
@@ -315,12 +419,61 @@ the existing emulator/build outputs stay separate.
tests cover multi-variable round-trip, corruption fallback, missing storage,
and firmware without `QueryVariableInfo`. QEMU/OVMF runtime testing saved a
file in the shell, reset the VM, restored the snapshot, and verified that
file. Disk-backed filesystem persistence remains open.
- [ ] Port remaining device services and add USB keyboard support.
file. The two-slot USB GPT snapshot store passed both host fallback tests and
the opt-in QEMU/OVMF disk save/reset/restore test.
- [x] Release held USB HID state after root-port removal. The kernel handles
xHCI port-status-change events, releases per-device keyboard modifiers/keys
and aggregated mouse buttons, and stops resubmitting reports after repeated
transfer errors. A QEMU hot-unplug probe holds a key, removes the keyboard,
and verifies the release marker.
- [x] Automatically re-enumerate directly connected USB HID devices after
root-port reconnection. The kernel defers unrelated xHCI events during
synchronous commands, disables the removed slot, reuses an inactive HID
record, and submits a fresh interrupt transfer. QEMU verifies hot-unplug,
held-key release, re-add, re-enumeration, and a returned interrupt report.
- `bob64/usb.c` also locates USB hub-class interfaces and their status interrupt
endpoints, parses USB 2 hub descriptors with bounded 1–127-port bitmaps, and
packs USB control setup packets for xHCI control transfers. Host tests cover
packet encoding, descriptor selection, small and maximum-size hubs, and
malformed/truncated input. At boot, the kernel selects a detected USB 2 hub's
configuration, reads its hub descriptor, marks the xHCI slot as a hub, powers
its downstream ports when switching is supported, waits the advertised
power-good interval, and reads their status. A QEMU profile verifies an
eight-port hub reports both an attached keyboard and mouse, resets both
connected ports, addresses the children with their topology route strings,
configures their HID endpoints, and exercises keyboard and mouse input through
the shell and managed window. It also configures the hub status endpoint;
QEMU hot-adds a keyboard and verifies that the kernel reads the changed port,
resets it, addresses the child, and configures its HID endpoint. The kernel
clears reported port-change features so stale status reports do not repeat.
The one-page control ring currently limits hub support to 16 ports.
- [x] Raise direct-attach HID support beyond eight devices. HID records and the
aggregated mouse-button state now support up to 32 devices, bounded by the
xHCI controller's slot count. QEMU verifies nine directly attached devices.
- [x] Add boot-time USB 2 hub child addressing and HID discovery. The kernel
builds bounded xHCI route strings, carries parent high-speed transaction
translator context through full-speed hubs, configures HID endpoints found
behind hubs, and submits their reports. QEMU verifies keyboard and mouse
input through an eight-port hub.
- [x] Configure USB 2 hub status endpoints and monitor downstream change
reports. QEMU hot-adds a keyboard behind an eight-port hub and confirms the
xHCI interrupt endpoint delivers its status bitmap.
- [x] Read and clear changed hub ports, then reset and enumerate newly attached
devices. QEMU hot-adds a downstream keyboard and verifies enumeration and
continued shell/desktop input. Boot-time scanning is capped at 16 ports and
the child topology queue is bounded to 32 devices.
- [x] Verify hub-child hot-unplug and reconnection. QEMU removes the original
keyboard, confirms the hot-added keyboard can type, holds a key while removing
that keyboard, checks held input is released, then re-adds a keyboard and
verifies shell input recovers.
- [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 opaque 64-bit `void *` storage, assignment, parameter/return passing,
global object/array/string initializers, and object-pointer compatibility.
Runtime tests verify pointer identity through a helper call and typed
conversion; void-pointer arithmetic and dereference remain rejected.
- [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
@@ -362,10 +515,27 @@ the existing emulator/build outputs stay separate.
`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
body, and scalar assignment or increment/decrement update code. Prefix/postfix
increment and decrement work on scalar and typed pointer locals, with pointer
steps scaled by their pointee width. `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.
return at the end of each function. `do`/`while` now emits a post-tested loop;
`continue` targets its condition, and host tests execute nested do-loops,
continue, break, and the mandatory first iteration. The resident QEMU smoke
source also exercises do/while and continue. `switch` now dispatches integer
expressions to integer/character `case` constants, supports one `default`,
fallthrough, and `break`; `continue` skips the switch to its surrounding
loop. Host execution tests cover nested switches and nearest-control break
routing, signed values, and a 64-bit case above 4 GiB; the resident QEMU smoke
source tests case fallthrough.
- The resident compiler now accepts named enum tags, up to 64 enumerators,
explicit literal values and implicit increments, enum-typed locals and
parameters, and `typedef enum Tag Alias;`. Enumerator names are usable in
expressions, global scalar/array initializers, and `switch` labels; duplicate constants and unknown tags fail
compilation. Host execution tests cover explicit and implicit numbering,
typedefs, function arguments, and enum-based switch dispatch. The resident
QEMU demo uses an enum for its switch test.
- [x] Expand the resident compiler's bounded source, machine-code, and global
data capacities from 4 KiB each to 16 KiB each. Host execution tests compile
and run a source file larger than 4 KiB with generated code beyond the old
@@ -375,6 +545,16 @@ the existing emulator/build outputs stay separate.
1 KiB frame and 64 variables. Code generation now uses disp8 or disp32 RBP
operands as needed. Host execution tests cover forty local scalars, a 64-item
local integer array and a 256-byte initialized character array.
- [x] Support scalar local declarations without initializers and later
assignments, matching C's indeterminate-before-store behavior. Host execution
tests cover `char`, `short`, `long`, `long long`, `usize`, and pointer locals;
the QEMU-compiled `bob.c` smoke program declares and assigns locals in
separate statements.
- [x] Add prefix and postfix `++`/`--` for scalar and typed pointer variables,
including scaled pointer steps and use in `for` updates. Host execution tests
cover value preservation, narrow signed wrap, forward/reverse loops, and
pointer arithmetic above 4 GiB; the QEMU-compiled `bob.c` smoke program
exercises both forms and pointer-return side effects.
- [x] Add bounded resident C typedefs for scalar, pointer, and named-struct
aliases. Host execution tests cover aliases in declarations, arrays, struct
fields, pointer parameters/returns, and member access through an aliased
@@ -387,11 +567,20 @@ the existing emulator/build outputs stay separate.
Host execution tests cover operator precedence, signed arithmetic shift, and
unsigned right shift above 4 GiB; the QEMU resident-compiler smoke program
exercises the same operators in the running kernel.
- [x] Add compile-time `sizeof` for supported types and expressions in the
resident compiler. Host execution checks LLP64 scalar widths, 64-bit pointers,
typedefs, struct layout, arrays, strings, indexed elements, and that calls in
sizeof expressions remain unevaluated, including the required
`sizeof(void *) == 8` check. The QEMU-compiled `bob!` program also checks these
sizes in the running kernel.
- [x] Add a kernel-owned per-app window manager and port the desktop's file and
editor windows to its surfaces. Syscall ABI v12 creates, focuses, destroys,
validates and copies app surfaces, composites z-order, routes input with
64-bit handles and local/screen coordinates, and releases the session on app
exit. Concurrent apps are still not displayed together.
exit. The compositor tracks clipped damage from surface writes, focus changes,
moves, and destruction, then recomposes only the affected screen rectangle;
idle pointer motion does no framebuffer work. 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
@@ -406,6 +595,11 @@ the existing emulator/build outputs stay separate.
editor; host packaging tests cover the control strings. QEMU/OVMF now opens
the Applications launcher, starts its selected `bob!` child, and verifies
that the desktop returns to the shell with a zero exit status.
- [x] Make Enter open a selected ordinary file in the editor or run a selected
`.b64e` app, while keeping `O` as an explicit file-open shortcut and `A` / Run
App as explicit app-launch controls. The QEMU desktop smoke test presses Tab
and Enter in the Files window, verifies `bob.b64e` prints `bob!`, and confirms
control returns to the open desktop.
- [x] Port reusable button behavior to the native framebuffer GUI. The
`bob64/widgets.h` button handles hover/pressed states and activates only on
an inside left-button release; the desktop uses it for Run App, APPS and
@@ -420,7 +614,8 @@ the existing emulator/build outputs stay separate.
Yes/Cancel confirmation window. `D` and the file-window Delete button open
the dialog; `Y`/Enter confirms and `N`/Escape cancels. The open editor file
remains protected. The handoff build and full QEMU/OVMF regression pass;
direct QEMU interaction coverage for this dialog remains to be added.
QEMU verifies cancellation preserves a disposable file and confirmation
removes it.
- [x] Port the Bob32 desktop's on-screen help overlay as a managed Bob64 help
window. It is reachable from the Files panel or `H`/`?`, and documents the
native desktop's current navigation, app-launch, delete, save, and focus
@@ -460,17 +655,25 @@ the existing emulator/build outputs stay separate.
their virtual memory sizes. Host packaging tests assert the desktop's
multi-megabyte zero-fill tail is loaded from B64E `MemorySize`, and QEMU
verifies the desktop runs and B64S save/restore still succeeds.
- [ ] Port the remaining applications to the kernel window API. Syscall ABI v11
also provides bounded file reads/writes/list/delete, console I/O,
full-screen presentation, blocking PS/2 keyboard/mouse events, ABI query, and
process exit. The host `bob64cc`
bridge continues to package the broader C subset supported by GCC.
- [ ] Port the remaining existing applications and full GUI/widget behavior;
the current native text editor is an initial, limited desktop milestone.
- [x] Port the existing user-facing Bob32 applications to the Bob64 native
app ABI, retaining their console workflows and providing managed windows for
the desktop, notes, graphics, launcher, file list, text viewer, system info,
and echo output. The native apps are packaged as B64E; host smoke tests cover
the utilities, while QEMU exercises their shell and windowed paths.
- [x] Add a managed-window mode to `echo.b64e` without changing its shell
argument-printing mode. The GUI wraps argument text, supports keyboard and
wheel scrolling, and closes through Escape or its Close button; QEMU verifies
a guest launch, input handling, and clean return to the shell.
- [x] Port Bob32's popup file-action menu as a reusable Bob64 widget. The Files
window opens it with `M`; it supports mouse hover/click, Up/Down, Enter,
Escape, and Open/Run/Delete actions. Host tests cover draw, selection,
activation, and dismissal; the QEMU suite covers its keyboard path.
- [x] Port Bob32's graphics demo as a 640x400 kernel-composited Bob64 window.
The native `display.b64e` app draws colored panels and diagonal lines, prints
`bob!`, and returns to the shell on X or Escape. The QEMU runtime test checks
presentation, clean app exit, and compatibility with snapshot save/restore.
`bob!`, and returns to the shell through a clickable Close button or X/Escape.
QEMU drags the window by its title bar, clicks the moved Close button through
the PS/2 IRQ and app event path, then checks clean app exit and snapshot
compatibility.
- [x] Port the system-information utility as native `info.b64e`. It reports the
syscall ABI, available display resolution, uptime, and RAM filesystem usage;
the kernel embeds and launches it in the application smoke path. The kernel
@@ -482,25 +685,105 @@ the existing emulator/build outputs stay separate.
the B64E image; QEMU opens it, checks `bob!`, and verifies a clean return to
the shell. The shell can also run the launcher with `APP [ARG ...]`; ABI v12
validates and forwards the full argv vector to the selected child.
- [x] Verify the native launcher Close button's mouse press/release contract in
QEMU: pressing inside and releasing outside cancels activation, while a
complete inside click closes the launcher after its child app returns.
- [x] Give `ls.b64e gui [FILE]` a managed file-list window with file names and
sizes, initial file selection, and keyboard/wheel selection. Double-click or
Enter/Open runs an executable or starts the `cat` text viewer with the selected
filename; preserve the existing shell listing. QEMU double-clicks bob.c and
verifies returning through both windows.
- [x] Add `cat.b64e gui FILE` as a managed text viewer with bounded 16 KiB file
loading, wrapped lines, keyboard/page/mouse-wheel scrolling and clean close;
keep the original streaming console `cat FILE` path. QEMU opens `bob.c`, sends
scroll input, and verifies the app returns to the shell.
- [x] Add `info.b64e gui` as a managed system-information window with a refresh
key while preserving the existing console report. QEMU opens it, refreshes
values, and confirms Escape returns to the shell.
- [x] Expand B64S compressed firmware snapshots from two to six bounded data
chunks per slot so the added native GUI apps still fit. Host tests round-trip
a 100 KiB file through at least four chunks; QEMU verifies firmware save,
reboot, restore and app launch.
- [x] Run the kernel-generated ring-3 `bob!` app under x64 UEFI emulation. The
QEMU runtime test also compiles `bob.c` through the resident shell compiler,
launches the resulting B64E app, and checks `bob!` and a zero exit status.
The source exercises local character/integer arrays, helper functions, array
parameters, loops, pointer-based syscall output, computed string length,
forty local variables, a 64-element stack array and a nested call with sixteen
integer arguments (four register-passed and twelve stack-passed).
local/global opaque `void *` conversions to scalar, array and string pointers,
separately declared and then assigned locals, forty local variables, a
64-element stack array and a nested call with
sixteen integer arguments (four register-passed and twelve stack-passed).
It also calls an eight-argument function with direct and opaque pointers on
the stack, where the seventh argument is produced by a nested six-argument
pointer-returning call whose fifth argument is itself stack-passed. Both
callees dereference the pointers and check the original array is intact.
Host compiler execution tests cover the same mixed register/stack pointer
case.
The test saves the compiled app in B64S, resets, and launches it again after
restore, then relaunches the GUI and a child app from the restored system.
- [ ] Complete the full acceptance flow and add runtime tests for broader
calling-convention/stack cases and the remaining widget interactions.
The ring-3 app image runs at a virtual address above
4 GiB; host tests also cover synthetic high addresses and broad ABI/memory
cases.
- [x] Verify live PS/2 mouse movement, wheel, and button delivery through IRQ12
and the app event ABI under QEMU. The ring-3 smoke app creates and focuses a
managed window, verifies the routed handle and window-local coordinates,
activates a managed button, and prints `bob!`; the runtime test injects all
three event types through QEMU's mouse monitor command.
- [x] Complete the end-to-end acceptance flow under QEMU/OVMF: boot to the
shell, access files, resident-compile and launch `bob!`, use the managed GUI,
save and restore B64S, then continue using the restored apps and desktop. The
resident compiler tests also cover sixteen stack/register arguments and
nested mixed register/stack pointer calls in both host execution and the
running guest. The ring-3 image runs above 4 GiB; host tests cover synthetic
high addresses and broad ABI/memory cases.
- [x] Exercise the desktop Help dismissal and file-delete confirmation flow in
QEMU. The runtime test verifies Help closes back to Files, Cancel preserves a
disposable RAM file through a mouse click, and confirmation removes that
exact file through the Yes keyboard shortcut.
- [x] Exercise desktop file-popup mouse dismissal and selection in QEMU. After
keyboard navigation changes the highlighted action, a click outside closes
the popup without activating an item; reopening it and clicking Close Menu
selects the row, and the desktop remains usable through the remaining checks.
- [ ] Complete runtime coverage for the remaining widget interactions and
port outstanding device services beyond the existing HID and USB storage
paths. QEMU verifies editor dirty-state protection, filename editing, popup
dismissal and mouse selection, filename-field Home/Right/End navigation,
insertion, Backspace and forward Delete, button press/release behavior, file
deletion, and exact saved text. The USB MSC driver covers BOT recovery, hotplug,
READ/WRITE(10) and READ/WRITE(16), bounded transfers, and validated GPT
partitions. B64S uses two checksummed generations; the full QEMU snapshot
regression saves, reboots, restores and verifies both a compiled app and the
desktop. A sparse 2 TiB+ GPT disk verifies this flow with its data partition
above the 32-bit LBA boundary and checks the raw B64D/B64S data at those high
offsets. Host regressions also exercise popup row selection, text-field
caret placement, window dragging, and routed local coordinates at the full
signed 32-bit coordinate limits; widget math widens before subtraction to
avoid overflow. The shared renderer clips off-screen rectangles and lines
before drawing and rejects pixel writes when the declared framebuffer
capacity is too small. Text glyph coordinates also use widened arithmetic,
so maximum-scale glyphs clip safely at signed coordinate limits. The window
compositor recomposes only changed surface, focus, and movement regions and
skips idle pointer events. Host tests cover single-pixel damage, overlapping
windows, move exposure, and idle motion; the full QEMU/OVMF desktop regression
passes. Further widget input combinations and additional USB classes remain
to be ported and tested.
- [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, USB and other device
support, disk-backed persistence, and remaining application ports still need
work.
migration remains active: the resident C subset and USB/device support still
need work.
- [x] Remove the 32-bit LBA ceiling from USB mass storage. Probe READ CAPACITY
(10), fall back to READ CAPACITY (16) when the device reports the sentinel
last LBA, and issue READ/WRITE (16) whenever a request cannot fit in the
10-byte CDB form. GPT-backed data partitions can now sit above the 32-bit
LBA boundary (about 2 TiB with 512-byte sectors). Host tests cover command
selection, boundary-crossing requests, capacity parsing above 4 billion
sectors, and malformed ranges; the full host suite passes. A dedicated QEMU
probe boots with a sparse 2 TiB+ USB disk, reads its capacity through READ
CAPACITY (16), and verifies a patterned sector at LBA `0x100000000` through
READ (16).
- [x] Verify GPT discovery and B64S persistence with the bob64 data partition
starting above the 32-bit LBA boundary. The extended snapshot regression
creates a sparse 2 TiB+ GPT image, saves a checkpoint, reboots, restores it,
launches a compiled app and the desktop, then checks the committed B64D
header and B64S payload at their high raw-image offsets. The full regression,
including COM1 runtime checks, passes.
## Build and test
@@ -509,7 +792,13 @@ build-tool --bob64
build-tool --bob64-test
build-tool --bob64-handoff
build-tool --bob64-handoff-test
build-tool --bob64-handoff-storage-test
build-tool --bob64-handoff-storage-active-test
build-tool --bob64-handoff-storage64-test
tools/test_bob64_qemu.ps1 -QemuPath <qemu-system-x86_64.exe> -OvmfCodePath <edk2-x86_64-code.fd> -OvmfVarsPath <edk2-x86_64-vars.fd>
tools/test_bob64_qemu.ps1 -QemuPath <qemu-system-x86_64.exe> -OvmfCodePath <edk2-x86_64-code.fd> -OvmfVarsPath <edk2-i386-vars.fd> -ImageRoot build/bob64-handoff-storage-active-test -ProbeOnly -ProbeDevice storage-active-disconnect
tools/test_bob64_qemu.ps1 -QemuPath <qemu-system-x86_64.exe> -OvmfCodePath <edk2-x86_64-code.fd> -OvmfVarsPath <edk2-i386-vars.fd> -ImageRoot build/bob64-handoff-storage64-test -ProbeOnly -ProbeDevice storage64
tools/test_bob64_qemu.ps1 -QemuPath <qemu-system-x86_64.exe> -OvmfCodePath <edk2-x86_64-code.fd> -OvmfVarsPath <edk2-i386-vars.fd> -LargeLbaDiskSnapshotTest
```
The safe output goes to `build/bob64/EFI/BOOT/BOOTX64.EFI`; the opt-in handoff
@@ -517,10 +806,13 @@ The safe output goes to `build/bob64/EFI/BOOT/BOOTX64.EFI`; the opt-in handoff
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
PowerShell QEMU test performs a real OVMF boot of the handoff image, checks
serial markers through the kernel shell, and captures a desktop framebuffer
image to verify live GOP rendering; 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.
replace testing on physical UEFI hardware. `-ProbeOnly -ProbeDevice disconnect`
holds a USB keyboard key, hot-unplugs it and verifies release, re-adds the
keyboard, and verifies that the new HID endpoint returns an interrupt report.
## Memory layout boundary
+11 -1
View File
@@ -1,7 +1,7 @@
CC ?= gcc
BOB64_CC ?= x86_64-w64-mingw32-gcc
CFLAGS ?= -std=gnu11 -O2 -Wall -Wextra -Werror
.PHONY: all c-os test bob64 bob64-test bob64-handoff bob64-handoff-test bob64cc bob64-app-test
.PHONY: all c-os test bob64 bob64-test bob64-handoff bob64-handoff-test bob64-handoff-storage-test bob64-handoff-storage-active-test bob64cc bob64-app-test
all:
$(CC) $(CFLAGS) tools/build.c -o build-tool
@@ -30,6 +30,16 @@ bob64-handoff-test:
$(CC) $(CFLAGS) tools/build.c -o build-tool
BOB64_CC="$(BOB64_CC)" ./build-tool --bob64-handoff-test
# Isolated opt-in image that writes a patterned sector on its temporary QEMU test disk.
bob64-handoff-storage-test:
$(CC) $(CFLAGS) tools/build.c -o build-tool
BOB64_CC="$(BOB64_CC)" ./build-tool --bob64-handoff-storage-test
# Isolated test image that pauses with an xHCI storage transfer outstanding.
bob64-handoff-storage-active-test:
$(CC) $(CFLAGS) tools/build.c -o build-tool
BOB64_CC="$(BOB64_CC)" ./build-tool --bob64-handoff-storage-active-test
bob64cc:
$(CC) $(CFLAGS) tools/bob64cc.c -o bob64cc
+181
View File
@@ -1,6 +1,25 @@
#include "../bob64/app.h"
#include "../bob64/gfx.h"
#include "../bob64/widgets.h"
#include "../bob64/window.h"
static char file_buffer[BOB64_SYSCALL_MAX_BUFFER];
#define CAT_GUI_WIDTH 720u
#define CAT_GUI_HEIGHT 520u
#define CAT_GUI_COLUMNS 112u
#define CAT_GUI_ROWS 31u
#define CAT_GUI_FILE_CAPACITY (16u*BOB64_SYSCALL_MAX_BUFFER)
static u8 gui_text[CAT_GUI_FILE_CAPACITY+1];
static u32 gui_pixels[CAT_GUI_WIDTH*CAT_GUI_HEIGHT];
static BOB64_GFX gui_graphics;
static BOB64_WINDOW_MANAGER gui_manager;
static BOB64_WINDOW gui_window;
static BOB64_WINDOW_HANDLE gui_order[1];
static BOB64_RECT gui_close_button={12,32,72,18};
static BOB64_BUTTON_STATE gui_close_state;
static const char *gui_filename;
static usize gui_text_length,gui_top_offset;
static char gui_status[32];
static usize text_length(const char *text) {
usize length=0;
@@ -13,6 +32,154 @@ static void write_text(const char *text) {
(void)bob64_app_write(text,text_length(text));
}
static int is_newline(u8 value) {return value=='\n'||value=='\r';}
static usize next_visual_line(usize offset) {
usize column=0;
while(offset<gui_text_length&&column<CAT_GUI_COLUMNS&&
!is_newline(gui_text[offset])) {offset++;column++;}
if(offset<gui_text_length&&is_newline(gui_text[offset])) {
u8 first=gui_text[offset++];
if(offset<gui_text_length&&is_newline(gui_text[offset])&&
gui_text[offset]!=first)offset++;
}
return offset;
}
static usize previous_visual_line(usize offset) {
usize current=0;
if(!offset)return 0;
while(current<offset) {
usize next=next_visual_line(current);
if(next>=offset)return current;
if(next<=current)return current;
current=next;
}
return current;
}
static void scroll_next_line(void) {
if(gui_top_offset>=gui_text_length)return;
usize next=next_visual_line(gui_top_offset);
gui_top_offset=next>=gui_text_length?
previous_visual_line(gui_text_length):next;
}
static void draw_visual_line(usize offset,s32 x,s32 y) {
char line[CAT_GUI_COLUMNS+1];
usize length=0;
while(offset<gui_text_length&&length<CAT_GUI_COLUMNS&&
!is_newline(gui_text[offset])) {
u8 value=gui_text[offset++];
line[length++]=(value>=32&&value<=126)?(char)value:
(value=='\t'?' ':'.');
}
line[length]=0;
bob64_gfx_text(&gui_graphics,x,y,line,0x00e2ebf5u,1);
}
static void set_gui_status(const char *text) {
usize i=0;
while(i+1<sizeof(gui_status)&&text[i]){gui_status[i]=text[i];i++;}
gui_status[i]=0;
}
static s64 gui_view_file(const char *name,usize name_length) {
BOB64_EVENT event,screen_event,routed;
u32 screen_width,screen_height;
s64 result=bob64_app_file_read_all(name,name_length,gui_text,
CAT_GUI_FILE_CAPACITY);
if(result<0)return result;
gui_text_length=(usize)result;gui_text[gui_text_length]=0;
gui_filename=name;gui_top_offset=0;
set_gui_status(gui_text_length?"TEXT FILE":"EMPTY FILE");
if(bob64_app_write("bob!",4)!=4)return -2;
if(bob64_app_get_display(&screen_width,&screen_height)||
screen_width<CAT_GUI_WIDTH||screen_height<CAT_GUI_HEIGHT)return -3;
if(bob64_wm_init(&gui_manager,&gui_window,1,gui_order,
screen_width,screen_height))return -4;
BOB64_WINDOW_HANDLE kernel_handle=bob64_app_window_create(
(s32)(screen_width-CAT_GUI_WIDTH)/2,
(s32)(screen_height-CAT_GUI_HEIGHT)/2,CAT_GUI_WIDTH,CAT_GUI_HEIGHT);
if(!kernel_handle||(s64)kernel_handle<0)return -5;
gui_manager.NextHandle=kernel_handle;
BOB64_WINDOW_HANDLE app_handle=bob64_wm_create(&gui_manager,
(s32)(screen_width-CAT_GUI_WIDTH)/2,
(s32)(screen_height-CAT_GUI_HEIGHT)/2,CAT_GUI_WIDTH,CAT_GUI_HEIGHT,
(void *)"Text viewer");
if(app_handle!=kernel_handle) {
if(app_handle)bob64_wm_destroy(&gui_manager,app_handle);
bob64_app_window_destroy(kernel_handle);return -6;
}
gui_graphics.Pixels=gui_pixels;gui_graphics.Width=CAT_GUI_WIDTH;
gui_graphics.Height=CAT_GUI_HEIGHT;
gui_graphics.Capacity=CAT_GUI_WIDTH*CAT_GUI_HEIGHT;
for(;;) {
bob64_gfx_fill_rect(&gui_graphics,0,0,CAT_GUI_WIDTH,CAT_GUI_HEIGHT,
0x001a2a3cu);
bob64_gfx_fill_rect(&gui_graphics,0,0,CAT_GUI_WIDTH,
BOB64_WINDOW_TITLE_BAR_HEIGHT,0x00335d8cu);
bob64_gfx_text(&gui_graphics,12,8,"TEXT VIEWER",0x00ffffffu,1);
bob64_button_draw(&gui_graphics,&gui_close_button,"CLOSE",
&gui_close_state);
bob64_gfx_text(&gui_graphics,100,38,gui_filename,0x00e2ebf5u,1);
bob64_gfx_text(&gui_graphics,550,38,gui_status,0x009eb3c7u,1);
usize line_offset=gui_top_offset;
for(u32 row=0;row<CAT_GUI_ROWS&&line_offset<gui_text_length;row++) {
draw_visual_line(line_offset,12,62+(s32)(row*14));
usize next=next_visual_line(line_offset);
if(next<=line_offset)break;
line_offset=next;
}
if(bob64_app_window_present(gui_window.Handle,gui_graphics.Pixels,
gui_graphics.Width,gui_graphics.Height)!=
(s64)(CAT_GUI_WIDTH*CAT_GUI_HEIGHT))return -7;
if(bob64_app_wait_event(&event))return -8;
screen_event=event;screen_event.X=event.ScreenX;
screen_event.Y=event.ScreenY;
s64 target=bob64_wm_dispatch(&gui_manager,&screen_event,&routed);
if(event.Type==BOB64_EVENT_KEY_DOWN&&
(event.Character==0x1b||event.Character=='x'||event.Character=='X'))
break;
if(event.Type==BOB64_EVENT_KEY_DOWN&&
event.Key==(BOB64_EVENT_KEY_EXTENDED|0x48))
gui_top_offset=previous_visual_line(gui_top_offset);
else if(event.Type==BOB64_EVENT_KEY_DOWN&&
event.Key==(BOB64_EVENT_KEY_EXTENDED|0x50))
scroll_next_line();
else if(event.Type==BOB64_EVENT_KEY_DOWN&&
event.Key==(BOB64_EVENT_KEY_EXTENDED|0x49)) {
for(u32 row=0;row<CAT_GUI_ROWS-1&&gui_top_offset;row++)
gui_top_offset=previous_visual_line(gui_top_offset);
} else if(event.Type==BOB64_EVENT_KEY_DOWN&&
event.Key==(BOB64_EVENT_KEY_EXTENDED|0x51)) {
for(u32 row=0;row<CAT_GUI_ROWS-1&&gui_top_offset<gui_text_length;row++)
scroll_next_line();
}
if(event.Type==BOB64_EVENT_MOUSE_WHEEL&&event.Wheel&&
target==(s64)gui_window.Handle) {
if(event.Wheel>0)gui_top_offset=previous_visual_line(gui_top_offset);
else scroll_next_line();
}
if(event.Type==BOB64_EVENT_MOUSE_MOVE) {
BOB64_EVENT local=event;local.X=event.ScreenX-gui_window.X;
local.Y=event.ScreenY-gui_window.Y;
bob64_button_event(&gui_close_button,&gui_close_state,&local);
}
if(event.Type==BOB64_EVENT_MOUSE_BUTTON&&
target==(s64)gui_window.Handle) {
BOB64_EVENT local=event;local.X=routed.X;local.Y=routed.Y;
int clicked=bob64_button_event(&gui_close_button,&gui_close_state,
&local);
if(!(event.Buttons&BOB64_BUTTON_LEFT)&&clicked)break;
}
}
bob64_app_window_destroy(gui_window.Handle);
bob64_wm_destroy(&gui_manager,gui_window.Handle);
gui_filename=0;
return 0;
}
s64 bob64_app_main(const BOB64_APP_STARTUP *startup) {
const char *name;
usize name_length;
@@ -21,6 +188,20 @@ s64 bob64_app_main(const BOB64_APP_STARTUP *startup) {
int read_any=0;
if(!startup||startup->StructSize!=sizeof(*startup)||
startup->AbiVersion!=BOB64_APP_ABI_VERSION)return -1;
if(startup->ArgumentCount==3&&startup->Arguments&&
startup->Arguments[1]&&startup->Arguments[2]&&
text_length(startup->Arguments[1])==3&&
startup->Arguments[1][0]=='g'&&startup->Arguments[1][1]=='u'&&
startup->Arguments[1][2]=='i') {
name=startup->Arguments[2];
name_length=text_length(name);
if(!name_length||name_length>BOB64_SYSCALL_MAX_FILENAME)
return -9;
result=gui_view_file(name,name_length);
if(result==-28)write_text("file too large for viewer\n");
else if(result<0)write_text("cannot open viewer file\n");
return result;
}
if(startup->ArgumentCount!=2||!startup->Arguments||
!(name=startup->Arguments[1])||!(name_length=text_length(name))) {
write_text("usage: cat FILE\n");
+107 -8
View File
@@ -1,10 +1,18 @@
typedef int count_t;
typedef char byte_t;
typedef int *int_ptr;
typedef unsigned long long uint64_value;
struct size_probe { char tag; int value; long long wide; };
int global_value = 42;
byte_t global_message[5] = "bob!";
void *global_value_address = &global_value;
void *global_message_address = global_message;
void *global_literal_address = "bob!";
int sum_values(int values[], int count) {
count_t sum = 0;
for (int i = 0; i < count; i = i + 1)
for (int i = 0; i < count; i++)
sum = sum + values[i];
return sum;
}
@@ -12,18 +20,31 @@ int sum_values(int values[], int count) {
count_t text_length(byte_t text[]) {
count_t length = 0;
while (text[length] != '\0')
length = length + 1;
length++;
return length;
}
int_ptr first_value(int_ptr values) {
return values;
int_ptr first = values;
return first++;
}
void *opaque_identity(int marker, void *value) {
int *typed_value = value;
if (marker != 42)
*typed_value = 0;
return value;
}
usize wide_division(usize value) {
return value / 10 + value % 10;
}
uint64_value add_unsigned_wide(uint64_value value,
unsigned long long int amount) {
return value + amount;
}
int sum_sixteen(int a, int b, int c, int d, int e, int f, int g, int h,
int i, int j, int k, int l, int m, int n, int o, int p) {
return a + b + c + d + e + f + g + h + i + j + k + l + m + n + o + p;
@@ -34,11 +55,63 @@ int stack_argument_test(void) {
9, 10, 11, 12, 13, 14, 15, 16);
}
int do_while_test(void) {
int count = 0;
int total = 0;
do {
count++;
if (count == 2) continue;
total = total + count;
} while (count < 4);
return total;
}
enum SwitchValue { SWITCH_ONE = 1, SWITCH_TWO, SWITCH_THREE };
int switch_test(enum SwitchValue value) {
int total = 0;
switch (value) {
case SWITCH_ONE: total = 10; break;
case SWITCH_TWO: total = 20;
case SWITCH_THREE: total = total + 3; break;
default: total = 99;
}
return total;
}
int inspect_mixed_arguments(int a, int b, int c, int d, int *direct,
int e, void *opaque, int f) {
int *converted = opaque;
return direct[0] + converted[1] + a + b + c + d + e + f;
}
void *identity_with_stack_pointer(int a, int b, int c, int d, void *value,
int marker) {
int *typed_value = value;
if (a + b + c + d != 10 || marker != 42)
typed_value[0] = -1;
return value;
}
int main(void) {
count_t values[64];
byte_t message[5] = "bob!";
int_ptr value_pointer = first_value(values);
int v0 = 0;
void *opaque_values = values;
void *opaque_pointer = opaque_identity(42, value_pointer);
int_ptr restored_pointer = opaque_pointer;
uintptr_t raw_global_address = (uintptr_t)&global_value;
void *cast_opaque_address = (void *)raw_global_address;
int *cast_global_pointer = (int *)cast_opaque_address;
short cast_short = (short)0x10034;
char cast_character = (char)0x142;
short cast_negative = (short)0xffff;
int cast_int = (int)0x10000002aULL;
unsigned long long unsigned_wide = 0xffffffffffffffffULL;
int_ptr global_value_pointer = global_value_address;
byte_t *global_message_pointer = global_message_address;
byte_t *global_literal_pointer = global_literal_address;
int v0;
int v1 = 1;
int v2 = 2;
int v3 = 3;
@@ -77,20 +150,46 @@ int main(void) {
int v36 = 36;
int v37 = 37;
int v38 = 38;
int v39 = 39;
int v39;
v0 = 0;
v39 = 39;
v0++;
++v0;
v39--;
++v39;
values[0] = 12;
values[1] = 13;
values[2] = 17;
values[63] = 42;
if (sum_values(values, 3) == 42 && text_length(message) == 4 &&
stack_argument_test() == 136 && values[63] == 42 &&
value_pointer[63] == 42 && v0 + v39 == 39 &&
stack_argument_test() == 136 && do_while_test() == 8 &&
switch_test(2) == 23 &&
inspect_mixed_arguments(1, 2, 3, 4, values, 5,
identity_with_stack_pointer(1, 2, 3, 4,
opaque_values, 42),
6) == 46 &&
values[0] == 12 && values[63] == 42 &&
value_pointer[63] == 42 && restored_pointer[63] == 42 &&
*cast_global_pointer == 42 && cast_short == 0x34 &&
cast_character == 'B' && cast_negative == -1 && cast_int == 42 &&
*global_value_pointer == 42 && global_message_pointer[1] == 'o' &&
global_literal_pointer[0] == 'b' && v0 + v39 == 41 &&
20 / 3 == 6 && 20 % 3 == 2 &&
-20 / 3 == -6 && -20 % 3 == -2 &&
wide_division(0x100000001ULL) == 429496736 &&
sizeof(unsigned long long) == 8 &&
add_unsigned_wide(unsigned_wide, 1ULL) == 0 &&
unsigned_wide > 0x7fffffffffffffffULL &&
(0x100000001ULL >> 32) == 1 &&
((0x5a ^ 0x3c) & 0xff) == 0x66 &&
(1 | 2 ^ 3 & 1) == 3 && (-8 >> 2) == -2) {
(1 | 2 ^ 3 & 1) == 3 && (-8 >> 2) == -2 &&
sizeof(char) == 1 && sizeof(short) == 2 && sizeof(int) == 4 &&
sizeof(long) == 4 && sizeof(long long) == 8 && sizeof(usize) == 8 &&
sizeof(void *) == 8 && sizeof(int *) == 8 &&
sizeof(count_t[64]) == 256 &&
sizeof(struct size_probe) == 16 && sizeof(values) == 256 &&
sizeof(message) == 5 && sizeof(value_pointer) == 8 &&
sizeof(values[0]) == 4 && sizeof(text_length(message)) == 4) {
bob64_app_write(message, text_length(message));
return 0;
}
+16 -2
View File
@@ -1,10 +1,13 @@
#include "../bob64/app.h"
#include "../bob64/gfx.h"
#include "../bob64/widgets.h"
#define DEMO_WIDTH 640u
#define DEMO_HEIGHT 400u
static u32 pixels[DEMO_WIDTH*DEMO_HEIGHT];
static const BOB64_RECT close_button={552,8,72,22};
static BOB64_BUTTON_STATE close_state;
static void draw_demo(BOB64_GFX *graphics) {
u32 width=graphics->Width,height=graphics->Height;
@@ -18,8 +21,9 @@ static void draw_demo(BOB64_GFX *graphics) {
height-(u32)(margin*2),0x1b2b40u);
bob64_gfx_fill_rect(graphics,margin,margin,width-(u32)(margin*2),
(u32)header_height,0x345d89u);
bob64_gfx_text(graphics,margin*2,margin*2,"BOB32 GRAPHICS DEMO",
bob64_gfx_text(graphics,margin*2,margin*2,"BOB64 GRAPHICS DEMO",
0x00ffffffu,3);
(void)bob64_button_draw(graphics,&close_button,"CLOSE",&close_state);
bob64_gfx_line(graphics,margin,header_height+margin*2,
(s32)width-margin,header_height+margin*2,0x00f0c879u);
bob64_gfx_text(graphics,margin*2,panel_y-margin*2,
@@ -39,7 +43,8 @@ static void draw_demo(BOB64_GFX *graphics) {
bob64_gfx_fill_rect(graphics,margin,panel_y+(s32)panel_height+margin,
width-(u32)(margin*2),3,0x006d849fu);
bob64_gfx_text(graphics,margin*2,
(s32)height-margin*6,"PRESS X OR ESCAPE TO RETURN",0x00ffffffu,2);
(s32)height-margin*6,"CLICK CLOSE OR PRESS X / ESCAPE",
0x00ffffffu,2);
}
s64 bob64_app_main(const BOB64_APP_STARTUP *startup) {
@@ -68,6 +73,15 @@ s64 bob64_app_main(const BOB64_APP_STARTUP *startup) {
(event.Character=='x'||event.Character=='X'||event.Character==0x1b)) {
result=0;break;
}
if(event.Type==BOB64_EVENT_MOUSE_MOVE||
event.Type==BOB64_EVENT_MOUSE_BUTTON) {
if(bob64_button_event(&close_button,&close_state,&event)) {
result=0;break;
}
draw_demo(&graphics);
result=bob64_app_window_present(window,pixels,DEMO_WIDTH,DEMO_HEIGHT);
if(result!=(s64)(DEMO_WIDTH*DEMO_HEIGHT))goto cleanup;
}
}
cleanup:
if(bob64_app_window_destroy(window)&&result==0)result=-6;
+135
View File
@@ -1,4 +1,18 @@
#include "../bob64/app.h"
#include "../bob64/gfx.h"
#include "../bob64/widgets.h"
#define ECHO_WINDOW_WIDTH 640u
#define ECHO_WINDOW_HEIGHT 400u
#define ECHO_LINE_CAPACITY 96u
#define ECHO_LINE_LIMIT 48u
#define ECHO_VISIBLE_LINES 26u
static u32 pixels[ECHO_WINDOW_WIDTH*ECHO_WINDOW_HEIGHT];
static char lines[ECHO_LINE_LIMIT][ECHO_LINE_CAPACITY];
static u32 line_count,scroll_offset;
static BOB64_RECT close_button={552,4,72,18};
static BOB64_BUTTON_STATE close_state;
static usize text_length(const char *text) {
usize length=0;
@@ -7,10 +21,131 @@ static usize text_length(const char *text) {
return length;
}
static int text_equals(const char *left,const char *right) {
usize i=0;
if(!left||!right)return 0;
while(left[i]&&right[i]&&left[i]==right[i])i++;
return !left[i]&&!right[i];
}
static void append_new_line(void) {
if(line_count<ECHO_LINE_LIMIT)line_count++;
else {
const char marker[]="...";
for(usize i=0;i<sizeof(marker);i++)
lines[ECHO_LINE_LIMIT-1][i]=marker[i];
}
}
static void append_text(const char *text) {
if(!text)return;
for(usize i=0;text[i];i++) {
if(line_count>=ECHO_LINE_LIMIT)return;
u32 row=line_count-1;
usize column=text_length(lines[row]);
if(text[i]=='\n') {
append_new_line();
} else {
if(column>=ECHO_LINE_CAPACITY-1) {
append_new_line();
if(line_count>=ECHO_LINE_LIMIT)return;
row=line_count-1;column=0;
}
lines[row][column]=text[i];
lines[row][column+1]=0;
}
}
}
static void build_lines(const BOB64_APP_STARTUP *startup) {
line_count=1;scroll_offset=0;
for(u64 i=2;i<startup->ArgumentCount;i++) {
if(i>2)append_text(" ");
append_text(startup->Arguments[i]);
}
}
static void reveal_scroll(void) {
u32 maximum=line_count>ECHO_VISIBLE_LINES?
line_count-ECHO_VISIBLE_LINES:0;
if(scroll_offset>maximum)scroll_offset=maximum;
}
static int draw_window(BOB64_GFX *graphics) {
bob64_gfx_fill_rect(graphics,0,0,ECHO_WINDOW_WIDTH,ECHO_WINDOW_HEIGHT,
0x001a2a3cu);
bob64_gfx_fill_rect(graphics,0,0,ECHO_WINDOW_WIDTH,26,0x00335d8cu);
bob64_gfx_text(graphics,12,8,"BOB64 ECHO",0x00ffffffu,1);
if(bob64_button_draw(graphics,&close_button,"CLOSE",&close_state))return -1;
bob64_gfx_text(graphics,16,34,"ARGUMENTS",0x008fc8ffu,1);
for(u32 row=0;row<ECHO_VISIBLE_LINES&&scroll_offset+row<line_count;row++)
bob64_gfx_text(graphics,16,52+(s32)row*12,
lines[scroll_offset+row],0x00e2ebf5u,1);
bob64_gfx_line(graphics,12,374,628,374,0x006d849fu);
bob64_gfx_text(graphics,16,382,"UP/DOWN OR WHEEL SCROLL ESC CLOSE",
0x009eb3c7u,1);
return 0;
}
static s64 run_gui(const BOB64_APP_STARTUP *startup) {
BOB64_GFX graphics={pixels,ECHO_WINDOW_WIDTH,ECHO_WINDOW_HEIGHT,
ECHO_WINDOW_WIDTH*ECHO_WINDOW_HEIGHT};
BOB64_EVENT event;
u32 screen_width,screen_height;
u64 window;
s64 result=-1;
build_lines(startup);
if(bob64_app_get_display(&screen_width,&screen_height)||
screen_width<ECHO_WINDOW_WIDTH||screen_height<ECHO_WINDOW_HEIGHT)return -2;
window=bob64_app_window_create((s32)(screen_width-ECHO_WINDOW_WIDTH)/2,
(s32)(screen_height-ECHO_WINDOW_HEIGHT)/2,
ECHO_WINDOW_WIDTH,ECHO_WINDOW_HEIGHT);
if(!window||(s64)window<0)return -3;
if(bob64_app_window_focus(window)) {result=-4;goto cleanup;}
if(bob64_app_write("bob!",4)!=4) {result=-5;goto cleanup;}
for(;;) {
reveal_scroll();
if(draw_window(&graphics)) {result=-6;break;}
result=bob64_app_window_present(window,pixels,ECHO_WINDOW_WIDTH,
ECHO_WINDOW_HEIGHT);
if(result!=(s64)(ECHO_WINDOW_WIDTH*ECHO_WINDOW_HEIGHT))break;
if(bob64_app_wait_event(&event)) {result=-7;break;}
if(event.Type==BOB64_EVENT_KEY_DOWN) {
if(event.Character==0x1b||event.Character=='x'||event.Character=='X') {
result=0;break;
}
if(event.Key==(BOB64_EVENT_KEY_EXTENDED|0x48)&&scroll_offset)
scroll_offset--;
else if(event.Key==(BOB64_EVENT_KEY_EXTENDED|0x50))scroll_offset++;
else if(event.Key==(BOB64_EVENT_KEY_EXTENDED|0x49))
scroll_offset=scroll_offset>ECHO_VISIBLE_LINES?
scroll_offset-ECHO_VISIBLE_LINES:0;
else if(event.Key==(BOB64_EVENT_KEY_EXTENDED|0x51))
scroll_offset+=ECHO_VISIBLE_LINES;
else if(event.Key==(BOB64_EVENT_KEY_EXTENDED|0x47))scroll_offset=0;
else if(event.Key==(BOB64_EVENT_KEY_EXTENDED|0x4f))
scroll_offset=line_count;
} else if(event.Type==BOB64_EVENT_MOUSE_WHEEL) {
if(event.Wheel>0&&scroll_offset)scroll_offset--;
else if(event.Wheel<0)scroll_offset++;
} else if(event.Type==BOB64_EVENT_MOUSE_MOVE||
event.Type==BOB64_EVENT_MOUSE_BUTTON) {
if(bob64_button_event(&close_button,&close_state,&event)) {
result=0;break;
}
}
}
cleanup:
if(bob64_app_window_destroy(window)&&result==0)result=-8;
return result;
}
s64 bob64_app_main(const BOB64_APP_STARTUP *startup) {
if(!startup||startup->StructSize!=sizeof(*startup)||
startup->AbiVersion!=BOB64_APP_ABI_VERSION||
(startup->ArgumentCount&&!startup->Arguments))return -1;
if(startup->ArgumentCount>1&&text_equals(startup->Arguments[1],"gui"))
return run_gui(startup);
for(u64 i=1;i<startup->ArgumentCount;i++) {
const char *argument=startup->Arguments[i];
if(i>1&&bob64_app_write_char(' ')<0)return -2;
+43 -6
View File
@@ -47,12 +47,17 @@ static const BOB64_RECT delete_cancel_button={120,82,88,18};
static const BOB64_RECT help_close_button={156,132,68,18};
static const BOB64_RECT applications_run_button={8,38,68,16};
static const BOB64_RECT applications_close_button={82,38,64,16};
static const BOB64_RECT file_menu_rect={8,70,140,72};
static const char *const file_menu_items[]={
"OPEN SELECTED","RUN APP","DELETE FILE","CLOSE MENU"
};
static BOB64_BUTTON_STATE file_run_state,file_apps_state;
static BOB64_BUTTON_STATE file_delete_state;
static BOB64_BUTTON_STATE file_help_state;
static BOB64_BUTTON_STATE applications_run_state,applications_close_state;
static BOB64_BUTTON_STATE delete_yes_state,delete_cancel_state;
static BOB64_BUTTON_STATE help_close_state;
static BOB64_MENU_STATE file_menu_state={0,-1,0};
static BOB64_TEXT_FIELD filename_field;
static u32 file_count,selected_file,file_scroll;
static u32 selected_application,application_scroll;
@@ -608,13 +613,13 @@ static void gui_draw_window(const BOB64_WINDOW *window,int focused) {
u32 list_bottom=window->Height>156?window->Height-156:70;
u32 rows=list_bottom>70?(list_bottom-70)/14:0;
bob64_gfx_text(graphics,window->X+10,window->Y+31,
"UP DOWN / WHEEL MOVE",0x009eb3c7u,1);
"UP/DN WHEEL MOVE M:MENU",0x009eb3c7u,1);
bob64_button_draw(graphics,&file_run_button,"RUN APP",&file_run_state);
bob64_button_draw(graphics,&file_apps_button,"APPS",&file_apps_state);
bob64_button_draw(graphics,&file_delete_button,"DELETE",&file_delete_state);
bob64_button_draw(graphics,&file_help_button,"HELP",&file_help_state);
bob64_gfx_text(graphics,window->X+10,window->Y+52,
"O OPEN R REFRESH D DELETE",0x009eb3c7u,1);
"ENTER OPEN/RUN O OPEN R REFRESH",0x009eb3c7u,1);
bob64_gfx_text(graphics,window->X+10,window->Y+61,editor_status,
0x008fc8ffu,1);
bob64_gfx_text(graphics,window->X+10,
@@ -633,6 +638,10 @@ static void gui_draw_window(const BOB64_WINDOW *window,int focused) {
}
if(!file_count)bob64_gfx_text(graphics,window->X+10,window->Y+72,
"NO FILES",0x008fc8ffu,1);
if(file_menu_state.Open)
bob64_menu_draw(graphics,&file_menu_rect,file_menu_items,
sizeof(file_menu_items)/sizeof(file_menu_items[0]),18,
&file_menu_state);
} else if(window->Handle==delete_window) {
bob64_gfx_text(graphics,window->X+16,window->Y+40,
"DELETE THIS FILE?",0x00ffffffu,1);
@@ -646,13 +655,15 @@ static void gui_draw_window(const BOB64_WINDOW *window,int focused) {
bob64_gfx_text(graphics,window->X+12,window->Y+38,
"FILES: ARROWS/WHEEL SELECT",0x00e2ebf5u,1);
bob64_gfx_text(graphics,window->X+12,window->Y+54,
"O OPENS; A RUNS AN APP",0x00e2ebf5u,1);
"ENTER OPENS FILES OR RUNS APPS",0x00e2ebf5u,1);
bob64_gfx_text(graphics,window->X+12,window->Y+70,
"D OR DELETE ASKS FIRST",0x00e2ebf5u,1);
bob64_gfx_text(graphics,window->X+12,window->Y+86,
"P OPENS THE APP LAUNCHER",0x00e2ebf5u,1);
bob64_gfx_text(graphics,window->X+12,window->Y+102,
"CTRL S SAVES; TAB SWITCHES",0x00e2ebf5u,1);
bob64_gfx_text(graphics,window->X+12,window->Y+118,
"M OPENS FILE ACTION MENU",0x00e2ebf5u,1);
bob64_button_draw(graphics,&help_close_button,"CLOSE",
&help_close_state);
} else if(window->Handle==applications_window) {
@@ -850,7 +861,10 @@ static void gui_key(const BOB64_EVENT *event) {
gui_copy(editor_status,"WINDOW CLOSE FAILED",sizeof("WINDOW CLOSE FAILED"));
}
else if(manager.Focused==files_window) {
if(event->Key==(BOB64_EVENT_KEY_EXTENDED|0x48)) {
if(event->Character=='m'||event->Character=='M') {
file_menu_state.Open=1;file_menu_state.Selected=0;
file_menu_state.Pressed=-1;
} else if(event->Key==(BOB64_EVENT_KEY_EXTENDED|0x48)) {
if(selected_file)selected_file--;
gui_reveal_selected_file();
gui_refresh_file_preview();
@@ -864,8 +878,13 @@ static void gui_key(const BOB64_EVENT *event) {
gui_refresh_files();editor_open_armed=0;
} else if(event->Character=='a'||event->Character=='A') {
gui_run_selected_app();editor_open_armed=0;
} else if(event->Character=='o'||event->Character=='O'||
event->Character=='\n')gui_open_selected_file();
} else if(event->Character=='\n') {
if(selected_file<file_count&&
gui_is_application(file_entries[selected_file].Name))
gui_run_selected_app();
else gui_open_selected_file();
} else if(event->Character=='o'||event->Character=='O')
gui_open_selected_file();
else if(event->Character=='d'||event->Character=='D')gui_delete_selected_file();
else if(event->Character=='h'||event->Character=='H'||
event->Character=='?')gui_open_help();
@@ -915,6 +934,24 @@ s64 bob64_app_main(const BOB64_APP_STARTUP *startup) {
for(;;) {
if(gui_draw(cursor_x,cursor_y))return -4;
if(bob64_app_wait_event(&event))return -5;
if(file_menu_state.Open) {
BOB64_WINDOW *menu_window=bob64_wm_find(&manager,files_window);
BOB64_RECT menu_screen=file_menu_rect;
int action;
screen_event=event;
screen_event.X=event.ScreenX;screen_event.Y=event.ScreenY;
if(menu_window) {
menu_screen.X+=menu_window->X;
menu_screen.Y+=menu_window->Y;
}
action=bob64_menu_event(&menu_screen,file_menu_items,
sizeof(file_menu_items)/sizeof(file_menu_items[0]),18,
&file_menu_state,&screen_event);
if(action==0)gui_open_selected_file();
else if(action==1)gui_run_selected_app();
else if(action==2)gui_delete_selected_file();
continue;
}
if(event.Type==BOB64_EVENT_KEY_DOWN&&event.Character==0x1b&&
manager.Focused==delete_window) {
gui_finish_delete(0);continue;
+139 -1
View File
@@ -1,4 +1,22 @@
#include "../bob64/app.h"
#include "../bob64/gfx.h"
#include "../bob64/widgets.h"
#include "../bob64/window.h"
#define INFO_GUI_WIDTH 520u
#define INFO_GUI_HEIGHT 340u
static u32 gui_pixels[INFO_GUI_WIDTH*INFO_GUI_HEIGHT];
static BOB64_GFX gui_graphics;
static BOB64_WINDOW_MANAGER gui_manager;
static BOB64_WINDOW gui_window;
static BOB64_WINDOW_HANDLE gui_order[1];
static BOB64_RECT gui_close_button={12,34,72,18};
static BOB64_BUTTON_STATE gui_close_state;
static BOB64_FILE_INFO gui_files[BOB64_SYSCALL_MAX_FILES];
static u32 gui_width,gui_height;
static s64 gui_display_status,gui_file_count;
static u64 gui_total_bytes;
static void write_text(const char *text) {
usize length=0;
@@ -6,6 +24,13 @@ static void write_text(const char *text) {
(void)bob64_app_write(text,length);
}
static int text_equals(const char *left,const char *right) {
usize i=0;
if(!left||!right)return 0;
while(left[i]&&right[i]&&left[i]==right[i])i++;
return !left[i]&&!right[i];
}
static void write_number(u64 value) {
char digits[20];
usize count=0;
@@ -22,15 +47,128 @@ static void write_labeled_number(const char *label,u64 value) {
write_text("\n");
}
static void format_number(char *text,u64 value) {
char digits[20];
usize count=0,offset=0;
do {digits[count++]=(char)('0'+value%10);value/=10;}
while(value&&count<sizeof(digits));
while(count)text[offset++]=digits[--count];
text[offset]=0;
}
static int refresh_gui_info(void) {
gui_display_status=bob64_app_get_display(&gui_width,&gui_height);
gui_file_count=bob64_app_list_files(gui_files,BOB64_SYSCALL_MAX_FILES);
if(gui_file_count<0||(u64)gui_file_count>BOB64_SYSCALL_MAX_FILES)return -1;
gui_total_bytes=0;
for(s64 i=0;i<gui_file_count;i++)gui_total_bytes+=gui_files[i].Size;
return 0;
}
static void draw_labeled_number(const char *label,u64 value,s32 y) {
char number[24];
format_number(number,value);
bob64_gfx_text(&gui_graphics,24,y,label,0x00dbe8f4u,1);
bob64_gfx_text(&gui_graphics,256,y,number,0x008fc8ffu,1);
}
static s64 run_gui(void) {
BOB64_EVENT event,screen_event,routed;
u32 screen_width,screen_height;
if(refresh_gui_info())return -3;
if(bob64_app_write("bob!",4)!=4)return -4;
if(bob64_app_get_display(&screen_width,&screen_height)||
screen_width<INFO_GUI_WIDTH||screen_height<INFO_GUI_HEIGHT)return -5;
if(bob64_wm_init(&gui_manager,&gui_window,1,gui_order,
screen_width,screen_height))return -6;
BOB64_WINDOW_HANDLE kernel_handle=bob64_app_window_create(
(s32)(screen_width-INFO_GUI_WIDTH)/2,
(s32)(screen_height-INFO_GUI_HEIGHT)/2,INFO_GUI_WIDTH,INFO_GUI_HEIGHT);
if(!kernel_handle||(s64)kernel_handle<0)return -7;
gui_manager.NextHandle=kernel_handle;
BOB64_WINDOW_HANDLE app_handle=bob64_wm_create(&gui_manager,
(s32)(screen_width-INFO_GUI_WIDTH)/2,
(s32)(screen_height-INFO_GUI_HEIGHT)/2,INFO_GUI_WIDTH,INFO_GUI_HEIGHT,
(void *)"System information");
if(app_handle!=kernel_handle) {
if(app_handle)bob64_wm_destroy(&gui_manager,app_handle);
bob64_app_window_destroy(kernel_handle);return -8;
}
gui_graphics.Pixels=gui_pixels;gui_graphics.Width=INFO_GUI_WIDTH;
gui_graphics.Height=INFO_GUI_HEIGHT;
gui_graphics.Capacity=INFO_GUI_WIDTH*INFO_GUI_HEIGHT;
for(;;) {
bob64_gfx_fill_rect(&gui_graphics,0,0,INFO_GUI_WIDTH,INFO_GUI_HEIGHT,
0x001a2a3cu);
bob64_gfx_fill_rect(&gui_graphics,0,0,INFO_GUI_WIDTH,
BOB64_WINDOW_TITLE_BAR_HEIGHT,0x00335d8cu);
bob64_gfx_text(&gui_graphics,12,8,"BOB64 SYSTEM INFORMATION",
0x00ffffffu,1);
bob64_button_draw(&gui_graphics,&gui_close_button,"CLOSE",
&gui_close_state);
bob64_gfx_text(&gui_graphics,112,39,"R REFRESH",0x009eb3c7u,1);
draw_labeled_number("System call ABI",BOB64_SYSCALL_ABI_VERSION,76);
if(gui_display_status)bob64_gfx_text(&gui_graphics,24,104,
"Display unavailable",0x00dbe8f4u,1);
else {
char resolution[24],height_text[16];
format_number(resolution,gui_width);
format_number(height_text,gui_height);
bob64_gfx_text(&gui_graphics,24,104,"Display",0x00dbe8f4u,1);
bob64_gfx_text(&gui_graphics,256,104,resolution,
0x008fc8ffu,1);
bob64_gfx_text(&gui_graphics,292,104,"x",0x00dbe8f4u,1);
bob64_gfx_text(&gui_graphics,310,104,height_text,
0x008fc8ffu,1);
}
draw_labeled_number("Uptime (seconds)",bob64_app_ticks()/100,132);
draw_labeled_number("RAM files",(u64)gui_file_count,160);
draw_labeled_number("RAM file data (bytes)",gui_total_bytes,188);
bob64_gfx_text(&gui_graphics,24,236,"ESCAPE OR CLOSE RETURNS",
0x009eb3c7u,1);
if(bob64_app_window_present(gui_window.Handle,gui_graphics.Pixels,
gui_graphics.Width,gui_graphics.Height)!=
(s64)(INFO_GUI_WIDTH*INFO_GUI_HEIGHT))return -9;
if(bob64_app_wait_event(&event))return -10;
screen_event=event;screen_event.X=event.ScreenX;
screen_event.Y=event.ScreenY;
s64 target=bob64_wm_dispatch(&gui_manager,&screen_event,&routed);
if(event.Type==BOB64_EVENT_KEY_DOWN&&
(event.Character==0x1b||event.Character=='x'||event.Character=='X'))
break;
if(event.Type==BOB64_EVENT_KEY_DOWN&&
(event.Character=='r'||event.Character=='R'))refresh_gui_info();
if(event.Type==BOB64_EVENT_MOUSE_MOVE) {
BOB64_EVENT local=event;local.X=event.ScreenX-gui_window.X;
local.Y=event.ScreenY-gui_window.Y;
bob64_button_event(&gui_close_button,&gui_close_state,&local);
}
if(event.Type==BOB64_EVENT_MOUSE_BUTTON&&
target==(s64)gui_window.Handle) {
BOB64_EVENT local=event;local.X=routed.X;local.Y=routed.Y;
int clicked=bob64_button_event(&gui_close_button,
&gui_close_state,&local);
if(!(event.Buttons&BOB64_BUTTON_LEFT)&&clicked)break;
}
}
bob64_app_window_destroy(gui_window.Handle);
bob64_wm_destroy(&gui_manager,gui_window.Handle);
return 0;
}
s64 bob64_app_main(const BOB64_APP_STARTUP *startup) {
BOB64_FILE_INFO files[BOB64_SYSCALL_MAX_FILES];
u32 width=0,height=0;
s64 file_count,display_status;
u64 total_bytes=0;
if(!startup||startup->StructSize!=sizeof(*startup)||
startup->AbiVersion!=BOB64_APP_ABI_VERSION||startup->ArgumentCount!=0)
startup->AbiVersion!=BOB64_APP_ABI_VERSION||
startup->ArgumentCount>2||
(startup->ArgumentCount&&!startup->Arguments))
return -1;
if(bob64_app_query_abi()!=BOB64_SYSCALL_ABI_VERSION)return -2;
if(startup->ArgumentCount==2&&startup->Arguments&&
text_equals(startup->Arguments[1],"gui"))return run_gui();
display_status=bob64_app_get_display(&width,&height);
file_count=bob64_app_list_files(files,BOB64_SYSCALL_MAX_FILES);
if(file_count<0||(u64)file_count>BOB64_SYSCALL_MAX_FILES)return -4;
+248
View File
@@ -1,4 +1,32 @@
#include "../bob64/app.h"
#include "../bob64/gfx.h"
#include "../bob64/widgets.h"
#include "../bob64/window.h"
#define LS_GUI_WIDTH 480u
#define LS_GUI_HEIGHT 380u
#define LS_GUI_ROWS 15u
static u32 gui_pixels[LS_GUI_WIDTH*LS_GUI_HEIGHT];
static BOB64_GFX gui_graphics;
static BOB64_WINDOW_MANAGER gui_manager;
static BOB64_WINDOW gui_window;
static BOB64_WINDOW_HANDLE gui_order[1];
static BOB64_FILE_INFO gui_files[BOB64_SYSCALL_MAX_FILES];
static u32 gui_file_count,gui_selected,gui_scroll;
static BOB64_RECT gui_close_button={12,36,72,18};
static BOB64_RECT gui_open_button={92,36,72,18};
static BOB64_BUTTON_STATE gui_close_state;
static BOB64_BUTTON_STATE gui_open_state;
static char gui_status[32];
static u32 gui_last_clicked=BOB64_SYSCALL_MAX_FILES;
static u64 gui_last_click_tick;
static usize text_length(const char *text) {
usize length=0;
if(text)while(text[length])length++;
return length;
}
static void write_text(const char *text) {
usize length=0;
@@ -16,11 +44,231 @@ static void write_size(u64 value) {
while(count)bob64_app_write_char((u8)digits[--count]);
}
static void format_size(char *buffer,u64 value) {
char digits[20];
usize count=0;
do {digits[count++]=(char)('0'+value%10);value/=10;}
while(value&&count<sizeof(digits));
usize offset=0;
while(count)buffer[offset++]=digits[--count];
buffer[offset]=0;
}
static void set_status(const char *text) {
usize i=0;
while(i+1<sizeof(gui_status)&&text[i]){gui_status[i]=text[i];i++;}
gui_status[i]=0;
}
static int executable_name(const char *name) {
usize size=text_length(name);
return size>5&&name[size-5]=='.'&&name[size-4]=='b'&&
name[size-3]=='6'&&name[size-2]=='4'&&name[size-1]=='e';
}
static void reveal_selection(void) {
if(gui_selected<gui_scroll)gui_scroll=gui_selected;
else if(gui_selected>=gui_scroll+LS_GUI_ROWS)
gui_scroll=gui_selected-LS_GUI_ROWS+1;
}
static void open_selected(void) {
if(gui_selected>=gui_file_count) {
set_status("NO FILE SELECTED");return;
}
const char *selected=gui_files[gui_selected].Name;
const char *app_name=selected;
const char *arguments[3];
usize argument_count=1,app_name_length=text_length(selected);
s64 child_status=-1;
if(executable_name(selected))arguments[0]=selected;
else {
app_name="cat.b64e";app_name_length=8;
arguments[0]=app_name;arguments[1]="gui";arguments[2]=selected;
argument_count=3;
}
s64 result=bob64_app_run(app_name,app_name_length,argument_count,
arguments,&child_status);
if(result||child_status)set_status("APP FAILED");
else set_status("OPENED");
s64 count=bob64_app_list_files(gui_files,BOB64_SYSCALL_MAX_FILES);
if(count>=0)gui_file_count=(u32)count;
if(gui_selected>=gui_file_count)
gui_selected=gui_file_count?gui_file_count-1:0;
reveal_selection();
}
static int gui_run(const BOB64_APP_STARTUP *startup) {
BOB64_EVENT event,screen_event,routed;
s64 target;
u32 screen_width,screen_height;
s64 result=bob64_app_get_display(&screen_width,&screen_height);
if(result||screen_width<LS_GUI_WIDTH||screen_height<LS_GUI_HEIGHT)return -2;
if(bob64_wm_init(&gui_manager,&gui_window,1,gui_order,
screen_width,screen_height))return -3;
gui_last_clicked=BOB64_SYSCALL_MAX_FILES;gui_last_click_tick=0;
BOB64_WINDOW_HANDLE kernel_handle=bob64_app_window_create(
(s32)(screen_width-LS_GUI_WIDTH)/2,
(s32)(screen_height-LS_GUI_HEIGHT)/2,LS_GUI_WIDTH,LS_GUI_HEIGHT);
if(!kernel_handle||(s64)kernel_handle<0)return -4;
gui_manager.NextHandle=kernel_handle;
BOB64_WINDOW_HANDLE app_handle=bob64_wm_create(&gui_manager,
(s32)(screen_width-LS_GUI_WIDTH)/2,
(s32)(screen_height-LS_GUI_HEIGHT)/2,LS_GUI_WIDTH,LS_GUI_HEIGHT,
(void *)"Files");
if(app_handle!=kernel_handle) {
if(app_handle)bob64_wm_destroy(&gui_manager,app_handle);
bob64_app_window_destroy(kernel_handle);return -5;
}
gui_graphics.Pixels=gui_pixels;gui_graphics.Width=LS_GUI_WIDTH;
gui_graphics.Height=LS_GUI_HEIGHT;
gui_graphics.Capacity=LS_GUI_WIDTH*LS_GUI_HEIGHT;
s64 count=bob64_app_list_files(gui_files,BOB64_SYSCALL_MAX_FILES);
if(count<0) {
set_status("LIST FAILED");
gui_file_count=0;
} else {
gui_file_count=(u32)count;
set_status("ENTER TO OPEN");
}
if(startup->ArgumentCount==3&&startup->Arguments[2]) {
int found=0;
for(u32 i=0;i<gui_file_count;i++) {
if(text_length(startup->Arguments[2])==
text_length(gui_files[i].Name)) {
usize n=0;
while(startup->Arguments[2][n]&&
startup->Arguments[2][n]==gui_files[i].Name[n])n++;
if(!startup->Arguments[2][n]&&!gui_files[i].Name[n]) {
gui_selected=i;found=1;break;
}
}
}
if(found)reveal_selection();
else set_status("FILE NOT FOUND");
}
for(;;) {
bob64_gfx_fill_rect(&gui_graphics,0,0,LS_GUI_WIDTH,LS_GUI_HEIGHT,
0x001a2a3cu);
bob64_gfx_fill_rect(&gui_graphics,0,0,LS_GUI_WIDTH,
BOB64_WINDOW_TITLE_BAR_HEIGHT,0x00335d8cu);
bob64_gfx_text(&gui_graphics,12,8,"BOB64 FILES",0x00ffffffu,1);
bob64_gfx_text(&gui_graphics,12,26,"DOUBLE-CLICK OR ENTER/OPEN",
0x009eb3c7u,1);
bob64_button_draw(&gui_graphics,&gui_close_button,"CLOSE",
&gui_close_state);
bob64_button_draw(&gui_graphics,&gui_open_button,"OPEN",
&gui_open_state);
bob64_gfx_text(&gui_graphics,180,42,gui_status,0x008fc8ffu,1);
for(u32 row=0;row<LS_GUI_ROWS;row++) {
u32 index=gui_scroll+row;
if(index>=gui_file_count)break;
s32 y=70+(s32)(row*18);
if(index==gui_selected)
bob64_gfx_fill_rect(&gui_graphics,8,y-2,464,16,0x00335d8cu);
bob64_gfx_text(&gui_graphics,14,y,gui_files[index].Name,
index==gui_selected?0x00ffffffu:0x00dbe8f4u,1);
char size_text[24];
format_size(size_text,gui_files[index].Size);
bob64_gfx_text(&gui_graphics,380,y,size_text,0x009eb3c7u,1);
bob64_gfx_text(&gui_graphics,434,y,"B",0x009eb3c7u,1);
}
if(!gui_file_count)bob64_gfx_text(&gui_graphics,14,74,"NO FILES",
0x008fc8ffu,1);
if(bob64_app_window_present(gui_window.Handle,gui_graphics.Pixels,
gui_graphics.Width,gui_graphics.Height)!=
(s64)(LS_GUI_WIDTH*LS_GUI_HEIGHT))return -6;
if(bob64_app_wait_event(&event))return -7;
screen_event=event;screen_event.X=event.ScreenX;
screen_event.Y=event.ScreenY;
target=bob64_wm_dispatch(&gui_manager,&screen_event,&routed);
if(event.Type==BOB64_EVENT_KEY_DOWN&&
(event.Character==0x1b||event.Character=='x'||event.Character=='X'))
break;
if(event.Type==BOB64_EVENT_KEY_DOWN&&
(event.Character=='\n'||event.Character=='o'||event.Character=='O')) {
gui_last_clicked=BOB64_SYSCALL_MAX_FILES;
open_selected();
}
if(event.Type==BOB64_EVENT_KEY_DOWN&&
event.Key==(BOB64_EVENT_KEY_EXTENDED|0x48)) {
gui_last_clicked=BOB64_SYSCALL_MAX_FILES;
if(gui_selected)gui_selected--;
if(gui_selected<gui_scroll)gui_scroll=gui_selected;
} else if(event.Type==BOB64_EVENT_KEY_DOWN&&
event.Key==(BOB64_EVENT_KEY_EXTENDED|0x50)) {
gui_last_clicked=BOB64_SYSCALL_MAX_FILES;
if(gui_selected+1<gui_file_count)gui_selected++;
if(gui_selected>=gui_scroll+LS_GUI_ROWS)
gui_scroll=gui_selected-LS_GUI_ROWS+1;
}
if(event.Type==BOB64_EVENT_MOUSE_WHEEL&&event.Wheel&&
target==(s64)gui_window.Handle) {
gui_last_clicked=BOB64_SYSCALL_MAX_FILES;
if(event.Wheel>0&&gui_selected)gui_selected--;
else if(event.Wheel<0&&gui_selected+1<gui_file_count)gui_selected++;
if(gui_selected<gui_scroll)gui_scroll=gui_selected;
if(gui_selected>=gui_scroll+LS_GUI_ROWS)
gui_scroll=gui_selected-LS_GUI_ROWS+1;
}
if(event.Type==BOB64_EVENT_MOUSE_MOVE) {
BOB64_EVENT local=event;
local.X=event.ScreenX-gui_window.X;
local.Y=event.ScreenY-gui_window.Y;
bob64_button_event(&gui_close_button,&gui_close_state,&local);
bob64_button_event(&gui_open_button,&gui_open_state,&local);
}
if(event.Type==BOB64_EVENT_MOUSE_BUTTON&&target==(s64)gui_window.Handle) {
BOB64_EVENT local=event;local.X=routed.X;local.Y=routed.Y;
int clicked=bob64_button_event(&gui_close_button,
&gui_close_state,&local);
if(!(event.Buttons&BOB64_BUTTON_LEFT)&&clicked)break;
int open=bob64_button_event(&gui_open_button,
&gui_open_state,&local);
if(!(event.Buttons&BOB64_BUTTON_LEFT)&&open)open_selected();
if((event.Buttons&BOB64_BUTTON_LEFT)&&routed.Y>=70) {
u32 row=(u32)(routed.Y-70)/18;
if(gui_scroll+row<gui_file_count) {
gui_selected=gui_scroll+row;
if(gui_last_clicked!=gui_scroll+row)
gui_last_clicked=BOB64_SYSCALL_MAX_FILES;
}
} else if(!(event.Buttons&BOB64_BUTTON_LEFT)&&routed.Y>=70) {
u32 row=(u32)(routed.Y-70)/18;
u32 index=gui_scroll+row;
if(index<gui_file_count) {
u64 now=bob64_app_ticks();
if(gui_last_clicked==index&&now-gui_last_click_tick<=50) {
gui_last_clicked=BOB64_SYSCALL_MAX_FILES;
open_selected();
} else {
gui_last_clicked=index;
gui_last_click_tick=now;
}
}
} else if(!(event.Buttons&BOB64_BUTTON_LEFT)) {
gui_last_clicked=BOB64_SYSCALL_MAX_FILES;
}
}
}
bob64_app_window_destroy(gui_window.Handle);
bob64_wm_destroy(&gui_manager,gui_window.Handle);
return 0;
}
s64 bob64_app_main(const BOB64_APP_STARTUP *startup) {
BOB64_FILE_INFO files[BOB64_SYSCALL_MAX_FILES];
s64 count;
if(!startup||startup->StructSize!=sizeof(*startup)||
startup->AbiVersion!=BOB64_APP_ABI_VERSION)return -1;
if((startup->ArgumentCount==2||startup->ArgumentCount==3)&&
startup->Arguments&&
startup->Arguments[1]&&text_length(startup->Arguments[1])==3&&
startup->Arguments[1][0]=='g'&&startup->Arguments[1][1]=='u'&&
startup->Arguments[1][2]=='i') {
if(bob64_app_write("bob!",4)!=4)return -8;
return gui_run(startup);
}
count=bob64_app_list_files(files,BOB64_SYSCALL_MAX_FILES);
if(count<0) {
write_text("cannot list files\n");
+88 -9
View File
@@ -1,15 +1,94 @@
#include "../bob64/app.h"
#include "../bob64/gfx.h"
#include "../bob64/widgets.h"
/* QEMU injects move, wheel, and button input through the selected mouse. */
#define MOUSE_TEST_WIDTH 160u
#define MOUSE_TEST_HEIGHT 96u
static u32 pixels[MOUSE_TEST_WIDTH*MOUSE_TEST_HEIGHT];
static const BOB64_RECT mouse_test_button={40,55,80,18};
/* The QEMU runtime test injects a mouse move through the emulated PS/2 device. */
s64 bob64_app_main(const BOB64_APP_STARTUP *startup) {
BOB64_EVENT event;
static const char passed[]="bob64 live mouse event passed\n";
BOB64_GFX graphics;
BOB64_BUTTON_STATE button_state={0};
u32 screen_width,screen_height;
u64 window;
static const char move_passed[]="bob! live mouse move passed\n";
static const char wheel_passed[]="bob! live mouse wheel passed\n";
if(!startup||startup->AbiVersion!=BOB64_APP_ABI_VERSION)return -1;
if(bob64_app_wait_event(&event))return -2;
if(event.Type!=BOB64_EVENT_MOUSE_MOVE||
(!event.DeltaX&&!event.DeltaY))
return -3;
if(bob64_app_write(passed,sizeof(passed)-1)!=(s64)(sizeof(passed)-1))
return -4;
return 0;
if(bob64_app_get_display(&screen_width,&screen_height)||
screen_width<MOUSE_TEST_WIDTH||screen_height<MOUSE_TEST_HEIGHT)return -2;
window=bob64_app_window_create((s32)((screen_width-MOUSE_TEST_WIDTH)/2),
(s32)((screen_height-MOUSE_TEST_HEIGHT)/2),MOUSE_TEST_WIDTH,
MOUSE_TEST_HEIGHT);
if(!window||(s64)window<0)return -3;
graphics.Pixels=pixels;graphics.Width=MOUSE_TEST_WIDTH;
graphics.Height=MOUSE_TEST_HEIGHT;
graphics.Capacity=MOUSE_TEST_WIDTH*MOUSE_TEST_HEIGHT;
bob64_gfx_fill_rect(&graphics,0,0,MOUSE_TEST_WIDTH,MOUSE_TEST_HEIGHT,
0x001a2a3cu);
bob64_gfx_fill_rect(&graphics,0,0,MOUSE_TEST_WIDTH,24,0x00335d8cu);
bob64_gfx_text(&graphics,8,8,"bob!",0x00ffffffu,1);
bob64_gfx_text(&graphics,8,38,"MOVE AND WHEEL",0x00e2ebf5u,1);
if(bob64_button_draw(&graphics,&mouse_test_button,"CLICK",&button_state)) {
bob64_app_window_destroy(window);return -12;
}
if(bob64_app_window_present(window,pixels,MOUSE_TEST_WIDTH,
MOUSE_TEST_HEIGHT)!=(s64)(MOUSE_TEST_WIDTH*MOUSE_TEST_HEIGHT)||
bob64_app_window_focus(window)<0) {
bob64_app_window_destroy(window);return -4;
}
for(;;) {
if(bob64_app_wait_event(&event)) {
bob64_app_window_destroy(window);return -5;
}
if(event.Type==BOB64_EVENT_MOUSE_MOVE&&
(event.DeltaX||event.DeltaY))break;
}
if(event.WindowHandle!=window||event.X<0||
event.X>=(s32)MOUSE_TEST_WIDTH||event.Y<0||
event.Y>=(s32)MOUSE_TEST_HEIGHT) {
bob64_app_window_destroy(window);return -6;
}
if(bob64_app_write(move_passed,sizeof(move_passed)-1)!=
(s64)(sizeof(move_passed)-1)) {
bob64_app_window_destroy(window);return -7;
}
for(;;) {
if(bob64_app_wait_event(&event)) {
bob64_app_window_destroy(window);return -8;
}
if(event.Type==BOB64_EVENT_MOUSE_WHEEL&&event.Wheel)break;
}
if(event.WindowHandle!=window||event.X<0||
event.X>=(s32)MOUSE_TEST_WIDTH||event.Y<0||
event.Y>=(s32)MOUSE_TEST_HEIGHT) {
bob64_app_window_destroy(window);return -9;
}
if(bob64_app_write(wheel_passed,sizeof(wheel_passed)-1)!=
(s64)(sizeof(wheel_passed)-1)) {
bob64_app_window_destroy(window);return -10;
}
for(;;) {
int clicked;
if(bob64_app_wait_event(&event)) {
bob64_app_window_destroy(window);return -13;
}
if(event.Type!=BOB64_EVENT_MOUSE_BUTTON)continue;
if(event.WindowHandle!=window||event.X<0||
event.X>=(s32)MOUSE_TEST_WIDTH||event.Y<0||
event.Y>=(s32)MOUSE_TEST_HEIGHT) {
bob64_app_window_destroy(window);return -14;
}
clicked=bob64_button_event(&mouse_test_button,&button_state,&event);
if(clicked)break;
}
static const char button_passed[]="bob! live mouse button passed\n";
if(bob64_app_write(button_passed,sizeof(button_passed)-1)!=
(s64)(sizeof(button_passed)-1)) {
bob64_app_window_destroy(window);return -15;
}
return bob64_app_window_destroy(window)<0?-11:0;
}
+17 -1
View File
@@ -6,7 +6,8 @@ s64 bob64_app_main(const BOB64_APP_STARTUP *startup) {
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];
static const char string_haystack[]="prefix bob64! suffix";
char file_copy[32],string_test[16]="",string_padding[8],formatted[40];
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();
@@ -29,5 +30,20 @@ s64 bob64_app_main(const BOB64_APP_STARTUP *startup) {
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;
if(bob64_strcpy(string_test,"bob")!=string_test||
bob64_strncat(string_test,"64!ignored",3)!=string_test||
bob64_strcmp(string_test,"bob64!")||
bob64_strncmp(string_test,"bob64?",5)||
bob64_strchr(string_test,'6')!=string_test+3||
bob64_strrchr(string_test,'!')!=string_test+5||
bob64_strstr(string_haystack,"bob64!")!=string_haystack+7||
bob64_memchr(string_test,'4',sizeof(string_test))!=string_test+4)
return -13;
if(bob64_strncpy(string_padding,"bob",sizeof(string_padding))!=string_padding||
bob64_strnlen(string_padding,sizeof(string_padding))!=3||
string_padding[3]!=0||string_padding[7]!=0)return -14;
if(bob64_snprintf(formatted,sizeof(formatted),"%s:%+05d:%#llx:%zu",
"bob!",-7,(unsigned long long)42,(usize)3)!=17||
bob64_strcmp(formatted,"bob!:-0007:0x2a:3"))return -15;
return 0;
}
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 Plan C
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+233 -38
View File
@@ -42,16 +42,55 @@ PS/2 polling. COM1 remains polled. The shell provides `help`, `clear`, `mem`, `h
and `rm NAME`; it stores arbitrary file bytes, and its contents disappear on
reboot. Up/Down recalls the last eight shell commands, and Tab completes built-in
commands plus file arguments for `cat`, `rm`, `run`, and `cc`. A 100 Hz PIT IRQ
supplies kernel and app tick counts. USB keyboards, directories, and persistent
storage are still open.
supplies kernel and app tick counts. USB HID boot-keyboard events share the
shell and GUI key-event queue, and boot-mouse events update the shared pointer
queue. Four-byte USB mouse reports also feed wheel events to GUI scrolling.
Directories remain open. The RAM filesystem can be checkpointed to the
dedicated GPT disk store with `save`; direct per-file block-backed storage is
still a future step.
Kernel startup now scans PCI configuration space through mechanism #1, follows
PCI-to-PCI bridges, and reports USB host controllers with their BAR addresses.
It maps the xHCI register area uncached, reads the controller version, limits,
scratchpad requirement, and runtime/doorbell offsets, then halts and resets the
controller. It identity-maps DMA pages, sets up the command and event rings,
starts the controller, and verifies a No Op command completion. It scans root
port status; the QEMU/OVMF profile attaches an emulated USB keyboard and checks
that one connected port is detected and reset, the xHC assigns a device slot,
and endpoint-0 GET_DESCRIPTOR requests read the device and configuration
descriptors. It parses the configuration, selects it, requests HID boot
protocol, and configures a keyboard or mouse interrupt-IN endpoint. It keeps a
transfer posted and re-arms after each report. Up to 32 directly connected
boot-HID devices use independent slots, rings, and report buffers, bounded by
the controller's advertised slot count. Each USB keyboard keeps its own held
keys and modifier state while feeding the common key-event queue. Mouse buttons
are combined across USB and PS/2 devices, while movement and wheel deltas update
the shared pointer and event queue. With the 8042 disabled, QEMU verifies USB shell typing,
mouse movement and wheel events delivered to a managed app window, plus the
keyboard path through launching the desktop and Help, closing Help, and
returning to the shell. The QEMU `many` profile verifies one keyboard and eight
mice configured simultaneously, along with their shared shell and GUI input
paths. A QEMU hot-unplug probe confirms root-port removal releases a held
keyboard key, then re-adds the keyboard and verifies re-enumeration and a new
interrupt report. The kernel also configures USB 2 hubs, marks their xHCI
slots as hubs, powers ports when the hub supports switching, and reads
downstream port status. A QEMU eight-port hub test detects its attached
keyboard and mouse, resets both ports, addresses them through their xHCI
route strings, configures their HID endpoints, and verifies keyboard and mouse
input. QEMU hot-adds a keyboard behind the hub and verifies that the kernel
reads and clears the changed port, resets it, enumerates the keyboard, and
types through it after removing the original keyboard. The test holds a key
during hot-unplug, verifies held input is released, and re-adds a keyboard to
verify shell input recovers. Scanning is capped at 16 ports and 32 queued
children.
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. `save` keeps a RAM checkpoint and writes a compressed copy to UEFI
non-volatile storage in two alternating slots. Each compressed snapshot is
split into bounded variables, and the active-slot record changes only after all
chunks are written; restore falls back to the prior committed slot if the active
one is damaged. Bob64 restores that snapshot on the next boot; if firmware
non-volatile storage in two alternating slots. Each compressed snapshot can
span up to six bounded variables, and the active-slot record changes only after
all chunks are written; restore falls back to the prior committed slot if the
active one is damaged. Bob64 restores that snapshot on the next boot; if firmware
storage is unavailable or full, the RAM checkpoint still works for the current
session. Firmware variable and total-store limits apply. If firmware does not
implement `QueryVariableInfo`, the kernel still attempts the write and reports
@@ -61,15 +100,25 @@ The kernel installs `echo.b64e`, a native 64-bit app that writes its startup
arguments and a newline. `run echo.b64e bob!` exercises the
pointer-width-safe startup record and makes the utility available to the
desktop's Run App action. The UEFI smoke path passes `bob!` through the startup
record and verifies those exact output bytes.
record and verifies those exact output bytes. Run `echo.b64e gui TEXT ...` to
view the arguments in a managed window; use Up/Down or the mouse wheel to
scroll and Escape or **CLOSE** to return.
`ls.b64e` is also installed by default. Run `run ls.b64e` to list RAM files and
their byte sizes through the application-facing file-list syscall. Its boot
smoke check validates a real returned filename in app memory.
smoke check validates a real returned filename in app memory. Run
`run ls.b64e gui [FILE]` for a managed window with file names and sizes. A
double-click, Enter, `O`, or **OPEN** runs a selected `.b64e` app or opens an
ordinary file in `cat`'s text viewer. Up/Down and the mouse wheel change
selection; an optional filename selects the initial row. The original shell
listing remains the default.
`cat.b64e` reads a named file using 4 KiB streaming transfers, preserving its
contents and adding a final newline only when needed. `run cat.b64e FILE` uses
the same file-handle ABI available to other native applications.
the same file-handle ABI available to other native applications. Run
`run cat.b64e gui FILE` to open a managed text-viewer window for files up to
16 KiB; use Up/Down, Page Up/Down, or the mouse wheel to scroll, then Escape or
Close to return.
`notes.b64e` opens an editable Notes window when launched from the desktop.
Use the arrow keys, Home/End, Backspace, and Delete to edit `notes.txt`; Ctrl+S
@@ -84,15 +133,17 @@ refuses to replace or delete binary files. The kernel smoke path copies a
`info.b64e` is the native system-information app. It reports the syscall ABI,
display resolution when GOP is available, uptime in seconds, and the number and
total data size of files in the RAM filesystem. The build embeds it in the
kernel image, and its output ends with `bob!` for smoke testing.
kernel image, and its output ends with `bob!` for smoke testing. Run
`run info.b64e gui` to see those values in a managed window; press `R` to
refresh the file and uptime figures, or Escape/Close to return.
`launcher.b64e` opens a managed native window listing installed `.b64e` apps.
Run `launcher.b64e APP [ARG ...]` from the shell to start an app directly with
its full argument vector; the launcher forwards argv[0] and the remaining args.
Use Up/Down and Enter (or click an app and **RUN APP**) to start a selected app;
Escape, `X`, or **CLOSE** returns to the shell. This standalone launcher starts
apps without command-line arguments; use the shell's `run` command when an app
needs arguments.
the app picker when started without arguments. When given `APP [ARG ...]`, it
launches that app directly and forwards its full argument vector.
`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
@@ -116,6 +167,9 @@ whole-file and handle-based streaming file read/write/list/delete, display dimen
presentation through a kernel compositor, focus control, input events, and
process exit, and synchronous child-app launch with bounded, validated argv
copying and parent-state restoration.
The kernel compositor tracks surface, focus, and movement damage and updates
only the affected screen region; pointer events that change no pixels skip
framebuffer writes.
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
@@ -126,19 +180,56 @@ without exposing kernel-internal types. The C smoke app writes and reads back a
small RAM file before it exits.
`apps/bob64_display.c` ports Bob32's graphics demo as a centered 640x400 native
window. It draws colored panels and diagonal lines, presents them through the
kernel compositor, prints `bob!`, then returns to the shell on X or Escape.
kernel compositor, prints `bob!`, and returns to the shell through its clickable
Close button or the X/Escape shortcuts.
The bob64 build packages it as `build/bob64-app/display.b64e`, installs it in
the RAM filesystem, and QEMU tests the window presentation and clean return.
The smaller app-owned drawing surface also keeps firmware snapshots within
their storage budget. `bob64_app_wait_event` receives typed PS/2 key-down/up
The app-owned drawing surfaces are zero-fill B64E data, so they do not inflate
firmware snapshots. `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.
PIT IRQ0 supplies 100 Hz ticks; keyboard IRQ1, USB HID boot reports and mouse
IRQ12 feed the shared event queues. Mouse position and packet decoding happen
in the IRQ handler. USB support covers directly connected boot-HID keyboards
and mice, plus boot-time and hotplug enumeration of HID devices behind USB 2
hubs. Root-port and hub-child removal release held input, and reconnect triggers
re-enumeration. QEMU verifies both paths. The kernel enumerates a SuperSpeed
USB SCSI Bulk-Only Transport device, configures both bulk endpoints, and issues
INQUIRY, READ CAPACITY, and READ(10) commands. A large-disk probe exercises
READ CAPACITY(16) and reads a verified sector above 2 TiB with READ(16). The
QEMU storage-hotplug probe
removes and re-adds the device, then verifies the same commands succeed after
re-enumeration; a SCSI CHECK CONDITION triggers one REQUEST SENSE and one retry.
A synchronous storage transfer now observes xHCI port-change events while
waiting for its completion; removal of that transfer's root port aborts the
request promptly and leaves the event queued for normal device teardown.
`bob64/block_device.h` defines the shared 64-bit LBA interface with bounded
transfers, read-only enforcement, and backend read/write/flush callbacks; the
xHCI storage driver registers through this interface. The SCSI layer uses
READ/WRITE(10) when the LBA range fits and READ/WRITE(16) otherwise, and falls
back from READ CAPACITY(10) to READ CAPACITY(16) for large disks.
`bob64/partition.c` validates the primary GPT header and entry-array CRCs,
checks usable-LBA bounds, and discovers the dedicated bob64 data partition
type GUID `7b616264-3030-4634-9a21-424f42363401`. The normal handoff build keeps
storage read-only unless this validated partition is present.
The partition stores two checksummed B64S snapshot generations. Save flushes
the payload before committing its header, and restore can fall back to the
previous valid generation. The QEMU snapshot test checks save, reboot, restore,
and the raw disk contents. Its large-LBA variant puts the partition above 2 TiB
and verifies those operations through READ/WRITE(16). The explicit storage
write test also writes a pattern to LBA 1, checks bounds, issues SYNCHRONIZE
CACHE, reads the sector back, and verifies the image after QEMU exits, including
across hotplug. The separate
`bob64-handoff-storage-active-test` image is built with
`build-tool --bob64-handoff-storage-active-test`; its QEMU probe removes a
throttled disk during a pending READ(10) transfer and checks request abortion
and device teardown. Host tests cover USB descriptors and BOT command/status
validation. General filesystem mounting and direct per-file block storage
remain 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 v11 kernel API additionally creates, destroys and composites up to
routing. The v12 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
@@ -149,22 +240,31 @@ launch `run desktop.b64e [filename]` from the shell (the default file is
to select and preview the selected file's first 384 bytes, `O` or Enter to open,
`R` to refresh, and `D` or **DELETE** to open
a Yes/Cancel confirmation. Press `Y` or Enter to confirm, and `N` or Escape to
cancel. Type into the editor, use arrow keys to move, Home/End to jump to the current line edges, Backspace to delete,
cancel. Press `M` from the Files window to open a popup menu with Open, Run,
Delete, and Close actions; use Up/Down and Enter or click an item, and press
Escape or click outside to dismiss it. Type into the editor, use arrow keys to move, Home/End to jump to the current line edges, Backspace to delete,
click in the text to place the cursor, Enter for a new line, and Ctrl+S to save.
The editor scrolls to keep the caret visible. Click the **NAME** field above
the editor to place its caret and edit the destination; Enter or Tab leaves the
field, and Ctrl+S saves the document under that name. Names accept letters,
digits, period, underscore or hyphen; executable names are protected. Escape
returns to the shell; unsaved text or name changes require a second Escape.
Select a `.b64e` file and press `A` or click **Run App** to launch it; the
desktop resumes with the child's exit status when it finishes. Click **APPS**
The QEMU GUI acceptance test verifies that the first Escape leaves a dirty
editor open, another key cancels the warning, and the second Escape exits
without changing the saved file. It also inserts text into a fixture, saves it
with Ctrl+S, and checks the exact saved line through the shell.
Select a file and press Enter to open it in the editor, or run a selected
`.b64e` app; `O` always opens a regular file and `A` or **Run App** launches
the selected app. The desktop resumes with the child's exit status when it
finishes. Click **APPS**
in the file window or press `P` from any desktop window to open the Applications
window. Use Up/Down to select an installed `.b64e` app, press Enter or `A` to
launch it, and click **X CLOSE** or press Escape/`X` to close the launcher.
Click **HELP** or press `H`/`?` from the Files window to view the desktop
shortcuts; Escape, `X`, or **CLOSE** dismisses it.
The desktop buttons share `bob64/widgets.h`, which handles hover and pressed
feedback and activates on a left-button release inside the control.
feedback and activates on a left-button release inside the control. The same
widget header provides the bounded popup menu used by the Files window.
The desktop editor supports text files up to 16 KiB, matching the resident
compiler's source limit. It uses bounded 4 KiB streaming transfers; larger
files are protected from accidental overwrite. Under QEMU/OVMF at
@@ -172,7 +272,7 @@ files are protected from accidental overwrite. Under QEMU/OVMF at
returned to the shell, a mouse click selected a file-list row, and Ctrl+S saved
editor text through the file syscall.
The editor refuses `.b64e` files and text containing binary control bytes;
use the Applications window to run executables.
press Enter or `A` to run executables.
User-origin CPU exceptions return an error status to the kernel. User apps run
with interrupts enabled when the keyboard IRQ path is active, and the loader
restores the caller's interrupt-enable state on return. The desktop editor
@@ -193,8 +293,8 @@ The shell also embeds `bob.c` and supports `cc bob.c` followed by
`run app.b64e`. The resident compiler accepts up to 16 KiB of source and emits
a B64E image with separate read-only executable code and writable/NX data
regions of up to 16 KiB each. Its initial C subset
accepts `int`, `short`, `long`, or `long long` main returns; initialized
`short`, `int`, `long`, and `long long` locals; local assignment; calls to
accepts `int`, `short`, `long`, or `long long` main returns; scalar local
declarations with or without initializers; local assignment; calls to
`bob64_app_write` with typed `char *` expressions and scalar length expressions; and
`return` expressions using 64-bit
integer literals, parentheses, unary minus, addition, subtraction, multiplication,
@@ -206,8 +306,26 @@ C precedence; right shift is arithmetic for signed expressions and logical for
both bind more tightly than bitwise operators; `&&` and `||` retain short-circuit
behavior. The compiler follows LLP64: `short` is 16-bit; `int` and `long`
are 32-bit and sign-extend on return; `long long` is 64-bit and preserves its
full result. Short globals, locals, struct fields, function parameters and
full result. `unsigned long long` (with optional trailing `int`) uses the
unsigned 64-bit `usize` representation, including unsigned comparisons and
calls. Other unsigned object widths are not supported yet. Short globals,
locals, struct fields, function parameters and
returns are sign-extended on load and use 16-bit storage. The resident subset
supports `sizeof(type)` for supported scalar and pointer types, typedef aliases,
named structs, and single-dimension fixed arrays; it yields an unsigned
pointer-sized value and follows the documented LLP64 sizes. `sizeof(void *)`
reports the eight-byte native pointer width. Opaque `void *` values can be
stored in locals, globals and struct fields, assigned, passed and returned,
and compared with object pointers. Global initializers can point to scalar
objects, arrays and strings. Explicit casts support scalar and pointer types,
including integer/pointer round trips. Casts to `char`, `short`, and `int`
truncate to the target width and sign-extend; pointer-sized integer casts
preserve all 64 bits. Dereference, indexing, and arithmetic require a typed
pointer.
`sizeof(expression)`
supports scalar, pointer, array-variable, indexed-element, and string-literal
expressions; expressions remain unevaluated, and arrays and string literals
retain their full size. Incomplete types remain unsupported. 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
@@ -264,23 +382,45 @@ 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`
blocks and `for` initializers have lexical scopes with local shadowing. Helper
functions may return the supported scalar types, `void`, or supported typed
object pointers; `main` must return a value. Only `void` helpers may fall
through without a return statement. Function-pointer and array return types
remain unsupported and report a source offset. `if`/`else` and `while`
support nonzero conditions plus signed or unsigned integer
`==`, `!=`, `<`, `<=`, `>`, and `>=` comparisons, and may use braces. Unary `!`/`~`
and short-circuit `&&`/`||` are supported. Basic `for` loops accept an optional initializer,
condition, and scalar-variable assignment update. `break` and `continue` target
condition, and scalar assignment or prefix/postfix increment/decrement update.
Prefix and postfix `++`/`--` support scalar locals and typed pointer locals;
pointer increments use the pointee size. `break` and `continue` target
the nearest enclosing loop, and `continue` in a `for` loop runs its update.
`do`/`while` loops execute their body once before testing the condition, and
`continue` routes through that condition, including inside nested loops.
Named `enum Tag { ... };` definitions support up to 64 integer or character
enumerators, implicit numbering, literal initializers, enum-typed declarations,
and `typedef enum Tag Alias;`. Enum constants work in expressions, global
scalar and array initializers, and `switch` case labels. Enum types use the compiler's 32-bit `int` representation;
initializer expressions beyond a single signed integer, character, or prior
enumerator are not supported yet. `switch` supports integer expressions, integer,
character, and enum-constant `case` labels, one optional `default`, lexical
fallthrough, and `break`; `continue` still targets the nearest enclosing loop.
Case labels are limited to the switch body's top level in this subset.
`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
x86-64 MinGW GCC toolchain. `bob64/app.h` checks at compile time that native
applications use 64-bit pointers and the same LLP64 scalar widths as the
resident compiler. 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.
syscall, and `bob64/libc.c` supplies 64-bit-length memory operations, bounded
string helpers, and `bob64_snprintf` for strings, characters, signed and
unsigned integers, pointers, flags, widths, and precision. Floating-point
format conversions are rejected. Host tests cover edge behavior, truncation,
integer boundaries, and 64-bit pointers; the boot smoke app runs the helpers and
formatter inside a packaged ring-3 x86-64 application.
`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.
@@ -293,9 +433,28 @@ 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, disk-backed persistence,
additional device coverage, USB input, and porting the rest of the applications.
`bob32.exe`, B16K/B32K images, or the existing resident compiler. B64S snapshots
can be stored in a dedicated GPT bob64 data partition on USB mass storage. The
store alternates between two checksummed slots, keeps the previous generation
until the new snapshot is committed, and falls back to the older slot if the
newer payload is damaged. Boot and the shell restore path prefer this disk store
and retain UEFI-variable snapshots as a fallback. The kernel never formats a
disk: the GPT partition must be created separately, and ordinary disks remain
read-only unless that exact validated partition is present. Remaining migration
work includes growing the resident C subset, directories, additional USB
classes and hub features, and fuller runtime coverage of the ported
applications.
For an emulator disk image, create a blank raw GPT image with the dedicated
partition using:
```powershell
.\tools\new_bob64_disk.ps1 -Path .\build\bob64-data.img -SizeMiB 64
```
The command refuses to overwrite an existing image unless `-Force` is passed.
Attach the raw image as USB mass storage. It contains GPT metadata and an empty
bob64 data partition; it does not create a filesystem or format existing media.
## UEFI runtime test
@@ -313,11 +472,47 @@ memory checks, timer and keyboard IRQs, and the kernel shell. It injects a PS/2
mouse move through QEMU's monitor and verifies that a ring-3 app receives the
event. It compiles `bob.c` with the resident compiler, runs the generated app
and checks its `bob!` output and exit status, then saves a file and the compiled
app into B64S firmware storage, resets the VM, and runs the app again after
app into B64S persistent storage, resets the VM, and runs the app again after
restore. The C sample verifies a 16-argument call, forty local variables, a
64-element stack array, and local accesses outside the 8-bit frame-offset range.
It opens the desktop Applications
launcher while the editor and file-browser windows remain active, runs the
selected `bob!` app, and checks that the desktop returns to the shell. After
restore, it repeats the GUI launch and child-app round trip using a PS/2 mouse
click on Run App. Broader widget interaction still needs runtime coverage.
click on Run App. QEMU verifies button cancellation when release occurs outside
the launcher Close control, followed by a successful inside click. It also
verifies popup dismissal and mouse selection of Close Menu, plus filename-field
Home/Right caret motion, insertion, and Backspace; further widget input
combinations still need broader runtime coverage. To test USB keyboard
removal while a key is held and automatic reconnection, run the same script with
`-ProbeOnly -ProbeDevice disconnect`; the kernel must release held input, then
re-enumerate the keyboard and receive an interrupt report.
Run `-ProbeOnly -ProbeDevice hub` to verify hub setup, downstream keyboard and
mouse input, and hot-add enumeration with an emulated eight-port hub.
To run the full shell, GUI, and snapshot regression with the disk-backed B64S
store, add `-DiskSnapshotTest`. The script creates a temporary raw GPT image,
attaches it as USB storage, verifies save and reboot restore from the partition,
and removes the image afterward:
```powershell
.\tools\test_bob64_qemu.ps1 -QemuPath C:\path\to\qemu-system-x86_64.exe `
-OvmfCodePath C:\path\to\edk2-x86_64-code.fd `
-OvmfVarsPath C:\path\to\edk2-x86_64-vars.fd `
-DiskSnapshotTest -TimeoutSeconds 180
```
To exercise block writes without touching a user's disk, build the isolated
storage-test image with `build-tool --bob64-handoff-storage-test`. Then run:
```powershell
.\tools\test_bob64_qemu.ps1 -QemuPath C:\path\to\qemu-system-x86_64.exe `
-OvmfCodePath C:\path\to\edk2-x86_64-code.fd `
-OvmfVarsPath C:\path\to\edk2-x86_64-vars.fd `
-ImageRoot build\bob64-handoff-storage-test -ProbeOnly `
-ProbeDevice storage-hotplug -ExpectStorageWrite
```
The script creates and removes temporary raw disks for both attachment phases.
The separate storage-test kernel target is opt-in; do not boot it with a disk
containing user data.
+11
View File
@@ -4,6 +4,17 @@
#include "abi.h"
#include "event.h"
/* The resident compiler and native GCC apps share Bob64's LLP64 data model. */
#if defined(__cplusplus)
static_assert(sizeof(void *)==8,"Bob64 apps require 64-bit pointers");
static_assert(sizeof(short)==2&&sizeof(int)==4&&sizeof(long)==4&&
sizeof(long long)==8,"Bob64 apps require the LLP64 data model");
#else
_Static_assert(sizeof(void *)==8,"Bob64 apps require 64-bit pointers");
_Static_assert(sizeof(short)==2&&sizeof(int)==4&&sizeof(long)==4&&
sizeof(long long)==8,"Bob64 apps require the LLP64 data model");
#endif
/* 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;
+45
View File
@@ -0,0 +1,45 @@
#include "block_device.h"
int bob64_block_device_init(BOB64_BLOCK_DEVICE *device,void *context,
u64 block_count,u32 block_size,int read_only,BOB64_BLOCK_READ read,
BOB64_BLOCK_WRITE write,BOB64_BLOCK_FLUSH flush) {
u32 maximum;
if(!device||!block_count||!block_size||
block_size>BOB64_BLOCK_MAX_TRANSFER_BYTES||!read||
(read_only!=0&&read_only!=1)||(!read_only&&!write))return -1;
maximum=BOB64_BLOCK_MAX_TRANSFER_BYTES/block_size;
if(!maximum)return -1;
device->Context=context;device->Read=read;device->Write=write;
device->Flush=flush;device->BlockCount=block_count;
device->BlockSize=block_size;device->MaxTransferBlocks=maximum;
device->ReadOnly=(u8)read_only;
return 0;
}
static int valid_request(const BOB64_BLOCK_DEVICE *device,u64 lba,
u32 block_count,const void *buffer) {
if(!device||!buffer||!block_count||!device->BlockCount||
!device->BlockSize||!device->MaxTransferBlocks||
block_count>device->MaxTransferBlocks||lba>=device->BlockCount||
(u64)block_count>device->BlockCount-lba)return 0;
return 1;
}
int bob64_block_read(BOB64_BLOCK_DEVICE *device,u64 lba,u32 block_count,
void *buffer) {
if(!valid_request(device,lba,block_count,buffer)||!device->Read)return -1;
return device->Read(device->Context,lba,block_count,buffer);
}
int bob64_block_write(BOB64_BLOCK_DEVICE *device,u64 lba,u32 block_count,
const void *buffer) {
if(!valid_request(device,lba,block_count,buffer))return -1;
if(device->ReadOnly||!device->Write)return -2;
return device->Write(device->Context,lba,block_count,buffer);
}
int bob64_block_flush(BOB64_BLOCK_DEVICE *device) {
if(!device)return -1;
if(device->ReadOnly)return -2;
return device->Flush?device->Flush(device->Context):-3;
}
+33
View File
@@ -0,0 +1,33 @@
#ifndef BOB64_BLOCK_DEVICE_H
#define BOB64_BLOCK_DEVICE_H
#include "types.h"
#define BOB64_BLOCK_MAX_TRANSFER_BYTES 4096u
typedef int (*BOB64_BLOCK_READ)(void *context,u64 lba,u32 block_count,
void *buffer);
typedef int (*BOB64_BLOCK_WRITE)(void *context,u64 lba,u32 block_count,
const void *buffer);
typedef int (*BOB64_BLOCK_FLUSH)(void *context);
typedef struct {
void *Context;
BOB64_BLOCK_READ Read;
BOB64_BLOCK_WRITE Write;
BOB64_BLOCK_FLUSH Flush;
u64 BlockCount;
u32 BlockSize,MaxTransferBlocks;
u8 ReadOnly;
} BOB64_BLOCK_DEVICE;
int bob64_block_device_init(BOB64_BLOCK_DEVICE *device,void *context,
u64 block_count,u32 block_size,int read_only,BOB64_BLOCK_READ read,
BOB64_BLOCK_WRITE write,BOB64_BLOCK_FLUSH flush);
int bob64_block_read(BOB64_BLOCK_DEVICE *device,u64 lba,u32 block_count,
void *buffer);
int bob64_block_write(BOB64_BLOCK_DEVICE *device,u64 lba,u32 block_count,
const void *buffer);
int bob64_block_flush(BOB64_BLOCK_DEVICE *device);
#endif
+574 -60
View File
@@ -7,6 +7,8 @@
#define COMPILER_STRUCT_LIMIT 8u
#define COMPILER_FIELD_LIMIT 16u
#define COMPILER_TYPEDEF_LIMIT 32u
#define COMPILER_ENUM_LIMIT 8u
#define COMPILER_ENUM_CONSTANT_LIMIT 64u
#define COMPILER_LOCAL_LIMIT 64u
#define COMPILER_LOCAL_FRAME_SIZE 1024u
@@ -22,10 +24,15 @@ typedef struct {
u8 ArgumentCount,ArgumentTypes[COMPILER_ARGUMENT_LIMIT];
} BOB64_C_CALL;
#define COMPILER_CONTROL_LOOP 1u
#define COMPILER_CONTROL_SWITCH 2u
#define COMPILER_SWITCH_CASE_LIMIT 32u
typedef struct {
u16 ContinueTarget,BreakBranches[32],ContinueBranches[32];
u8 BreakCount,ContinueCount;
} BOB64_C_LOOP;
u16 CaseTargets[COMPILER_SWITCH_CASE_LIMIT],DefaultTarget;
u64 CaseValues[COMPILER_SWITCH_CASE_LIMIT];
u8 Kind,BreakCount,ContinueCount,CaseCount,HasDefault;
} BOB64_C_CONTROL;
typedef struct {
u16 LocalBytes;
@@ -56,6 +63,15 @@ typedef struct {
u8 Type;
} BOB64_C_TYPEDEF;
typedef struct {
char Name[32];
} BOB64_C_ENUM;
typedef struct {
char Name[32];
u64 Value;
} BOB64_C_ENUM_CONSTANT;
typedef struct {
const char *Source;
usize Length,Position,ErrorOffset;
@@ -71,13 +87,16 @@ typedef struct {
BOB64_C_GLOBAL Globals[COMPILER_GLOBAL_LIMIT];
BOB64_C_STRUCT Structs[COMPILER_STRUCT_LIMIT];
BOB64_C_TYPEDEF Typedefs[COMPILER_TYPEDEF_LIMIT];
BOB64_C_ENUM Enums[COMPILER_ENUM_LIMIT];
BOB64_C_ENUM_CONSTANT EnumConstants[COMPILER_ENUM_CONSTANT_LIMIT];
BOB64_C_CALL Calls[COMPILER_CALL_LIMIT];
BOB64_C_LOOP Loops[16];
BOB64_C_CONTROL Controls[16];
BOB64_C_SCOPE Scopes[32];
u16 FunctionSourceStart[COMPILER_FUNCTION_LIMIT];
u16 FunctionSourceEnd[COMPILER_FUNCTION_LIMIT];
u8 FunctionCount,GlobalCount,StructCount,TypedefCount,CallCount,LoopDepth;
u8 FunctionSourceCount,ScopeDepth;
u8 FunctionCount,GlobalCount,StructCount,TypedefCount,EnumCount;
u8 EnumConstantCount,CallCount;
u8 FunctionSourceCount,ScopeDepth,ControlCount;
u64 IntegerValue;
u8 ExpressionType,IntegerType;
u8 ReturnType,Return64,Failed,ControlDepth;
@@ -103,16 +122,29 @@ static int compiler_emit_u32(BOB64_C_COMPILER *compiler,u32 value);
#define COMPILER_TYPE_LONG_LONG_ARRAY 15u
#define COMPILER_TYPE_STRUCT_BASE 16u
#define COMPILER_TYPE_USIZE_ARRAY 24u
#define COMPILER_TYPE_VOID_POINTER 25u
#define COMPILER_TYPE_STRUCT_POINTER_BASE 64u
static int compiler_is_pointer(u8 type) {
return type==COMPILER_TYPE_INT_POINTER||type==COMPILER_TYPE_CHAR_POINTER||
type==COMPILER_TYPE_SHORT_POINTER||type==COMPILER_TYPE_ISIZE_POINTER||
type==COMPILER_TYPE_USIZE_POINTER||
type==COMPILER_TYPE_USIZE_POINTER||type==COMPILER_TYPE_VOID_POINTER||
(type>=COMPILER_TYPE_STRUCT_POINTER_BASE&&
type<COMPILER_TYPE_STRUCT_POINTER_BASE+COMPILER_STRUCT_LIMIT);
}
static int compiler_pointer_types_compatible(u8 left,u8 right) {
return compiler_is_pointer(left)&&compiler_is_pointer(right)&&
(left==right||left==COMPILER_TYPE_VOID_POINTER||
right==COMPILER_TYPE_VOID_POINTER);
}
static int compiler_value_types_compatible(u8 expected,u8 actual) {
if(compiler_is_pointer(expected)||compiler_is_pointer(actual))
return compiler_pointer_types_compatible(expected,actual);
return 1;
}
static int compiler_type_is_struct_pointer(u8 type) {
return type>=COMPILER_TYPE_STRUCT_POINTER_BASE&&
type<COMPILER_TYPE_STRUCT_POINTER_BASE+COMPILER_STRUCT_LIMIT;
@@ -132,6 +164,7 @@ static u32 compiler_array_element_size(u8 type) {
}
static u32 compiler_pointer_scale(BOB64_C_COMPILER *compiler,u8 type) {
if(type==COMPILER_TYPE_VOID_POINTER)return 0u;
if(type==COMPILER_TYPE_CHAR_POINTER)return 1u;
if(type==COMPILER_TYPE_SHORT_POINTER)return 2u;
if(type==COMPILER_TYPE_ISIZE_POINTER||type==COMPILER_TYPE_USIZE_POINTER)return 8u;
@@ -221,6 +254,14 @@ static u8 compiler_long_type(BOB64_C_COMPILER *compiler) {
}
static u8 compiler_integer_type(BOB64_C_COMPILER *compiler) {
usize saved=compiler->Position;
if(compiler_word(compiler,"unsigned")) {
if(compiler_word(compiler,"long")&&compiler_word(compiler,"long")) {
(void)compiler_word(compiler,"int");
return COMPILER_TYPE_USIZE;
}
compiler->Position=saved;
}
if(compiler_word(compiler,"int"))return COMPILER_TYPE_INT;
if(compiler_word(compiler,"short"))return COMPILER_TYPE_SHORT;
if(compiler_word(compiler,"usize")||compiler_word(compiler,"uintptr_t"))
@@ -248,6 +289,8 @@ static int compiler_identifier(BOB64_C_COMPILER *compiler,char *name,usize capac
static int compiler_struct_find(BOB64_C_COMPILER *compiler,const char *name);
static int compiler_type_is_struct(u8 type);
static int compiler_enum_find(BOB64_C_COMPILER *compiler,const char *name);
static int compiler_enum_constant_find(BOB64_C_COMPILER *compiler,const char *name);
static int compiler_typedef_find(BOB64_C_COMPILER *compiler,const char *name) {
for(u32 i=0;i<compiler->TypedefCount;i++) {
@@ -268,6 +311,12 @@ static u8 compiler_type_specifier(BOB64_C_COMPILER *compiler) {
int structure=compiler_struct_find(compiler,name);
return structure<0?0:(u8)(COMPILER_TYPE_STRUCT_BASE+(u32)structure);
}
if(compiler_word(compiler,"enum")) {
char name[32];
if(!compiler_identifier(compiler,name,sizeof(name))||
compiler_enum_find(compiler,name)<0)return 0;
return COMPILER_TYPE_INT;
}
u8 type=compiler_integer_type(compiler);
if(type)return type;
usize saved=compiler->Position;
@@ -280,6 +329,7 @@ static u8 compiler_type_specifier(BOB64_C_COMPILER *compiler) {
static u8 compiler_pointer_to(BOB64_C_COMPILER *compiler,u8 type) {
(void)compiler;
if(type==COMPILER_TYPE_VOID)return COMPILER_TYPE_VOID_POINTER;
if(compiler_type_is_struct(type))
return (u8)(COMPILER_TYPE_STRUCT_POINTER_BASE+type-COMPILER_TYPE_STRUCT_BASE);
if(!type||type==COMPILER_TYPE_VOID||compiler_is_pointer(type))return 0;
@@ -303,25 +353,26 @@ static int compiler_function_signature(BOB64_C_COMPILER *compiler,char *name,
u8 value_type=compiler_type_specifier(compiler);
int struct_type=compiler_type_is_struct(value_type)?
(int)(value_type-COMPILER_TYPE_STRUCT_BASE):-1;
int void_type=value_type==COMPILER_TYPE_VOID;
if(!value_type)return 0;
int return_pointer=compiler_take(compiler,'*');
if((struct_type>=0&&!return_pointer)||(void_type&&return_pointer))return 0;
if(struct_type>=0&&!return_pointer)return 0;
*return_type=return_pointer?compiler_pointer_to(compiler,value_type):value_type;
if(!*return_type)return 0;
if(!compiler_identifier(compiler,name,name_capacity)||!compiler_take(compiler,'('))return 0;
if(!compiler_take(compiler,')')) {
if(compiler_word(compiler,"void")) {
if(!compiler_take(compiler,')'))return 0;
} else {
int pending_void=compiler_word(compiler,"void");
if(!(pending_void&&compiler_take(compiler,')'))) {
for(;;) {
int pointer,has_name;
if(count>=COMPILER_ARGUMENT_LIMIT)return 0;
u8 value_type=compiler_type_specifier(compiler);
u8 value_type=pending_void?COMPILER_TYPE_VOID:
compiler_type_specifier(compiler);
pending_void=0;
int struct_type=compiler_type_is_struct(value_type)?
(int)(value_type-COMPILER_TYPE_STRUCT_BASE):-1;
if(!value_type||value_type==COMPILER_TYPE_VOID)return 0;
if(!value_type)return 0;
pointer=compiler_take(compiler,'*');
if(value_type==COMPILER_TYPE_VOID&&!pointer)return 0;
if(struct_type>=0&&!pointer)return 0;
compiler_skip(compiler);
has_name=compiler_identifier(compiler,parameter_names[count],
@@ -389,6 +440,27 @@ static int compiler_struct_find(BOB64_C_COMPILER *compiler,const char *name) {
return -1;
}
static int compiler_enum_find(BOB64_C_COMPILER *compiler,const char *name) {
for(u32 i=0;i<compiler->EnumCount;i++) {
usize position=0;
while(compiler->Enums[i].Name[position]&&
compiler->Enums[i].Name[position]==name[position])position++;
if(!compiler->Enums[i].Name[position]&&!name[position])return (int)i;
}
return -1;
}
static int compiler_enum_constant_find(BOB64_C_COMPILER *compiler,
const char *name) {
for(u32 i=0;i<compiler->EnumConstantCount;i++) {
usize position=0;
while(compiler->EnumConstants[i].Name[position]&&
compiler->EnumConstants[i].Name[position]==name[position])position++;
if(!compiler->EnumConstants[i].Name[position]&&!name[position])return (int)i;
}
return -1;
}
static int compiler_type_is_struct(u8 type) {
return type>=COMPILER_TYPE_STRUCT_BASE&&
type<COMPILER_TYPE_STRUCT_BASE+COMPILER_STRUCT_LIMIT;
@@ -492,7 +564,8 @@ static int compiler_function_find(BOB64_C_COMPILER *compiler,const char *name) {
static int compiler_function_declare(BOB64_C_COMPILER *compiler,const char *name,
u16 code_offset,u8 return_type,u8 argument_count,
const u8 *argument_types,int defined) {
if(argument_count>COMPILER_ARGUMENT_LIMIT)return 0;
if(argument_count>COMPILER_ARGUMENT_LIMIT||
compiler_enum_constant_find(compiler,name)>=0)return 0;
int existing=compiler_function_find(compiler,name);
if(existing>=0) {
BOB64_C_FUNCTION *function=&compiler->Functions[existing];
@@ -653,7 +726,8 @@ static int compiler_add_variable(BOB64_C_COMPILER *compiler,const char *name,
compiler->VariableNames[i][position]==name[position])position++;
if(!compiler->VariableNames[i][position]&&!name[position])return 0;
}
if(compiler->VariableCount>=COMPILER_LOCAL_LIMIT)return 0;
if(compiler->VariableCount>=COMPILER_LOCAL_LIMIT||
compiler_enum_constant_find(compiler,name)>=0)return 0;
if(type==COMPILER_TYPE_INT_ARRAY) {
if(!array_length||array_length>COMPILER_LOCAL_FRAME_SIZE/4u)return 0;
bytes=array_length*4;
@@ -795,6 +869,79 @@ static int compiler_emit_integer(BOB64_C_COMPILER *compiler,u64 value) {
}
static int compiler_expression(BOB64_C_COMPILER *compiler);
static int compiler_sizeof_type(BOB64_C_COMPILER *compiler,u32 *size_out) {
u8 type=compiler_type_specifier(compiler);
u64 count;
u32 size;
int pointer;
if(!type)return -1;
pointer=compiler_take(compiler,'*');
if(type==COMPILER_TYPE_VOID&&!pointer)return 0;
size=pointer?8u:compiler_type_size(compiler,type);
if(compiler_take(compiler,'[')) {
if(!compiler_integer(compiler,&count)||!count||
!compiler_take(compiler,']')||count>0xffffffffu/size)return 0;
size*=(u32)count;
}
if(!size)return 0;
if(!compiler_take(compiler,')'))return -1;
*size_out=size;
return 1;
}
static int compiler_sizeof_expression(BOB64_C_COMPILER *compiler,
u32 *size_out) {
usize position=compiler->Position;
char name[32];
u32 variable_size;
int variable;
if(compiler_identifier(compiler,name,sizeof(name))&&
compiler_take(compiler,')')) {
variable=compiler_variable_find(compiler,name);
if(variable>=0) {
u8 type=compiler_variable_type(compiler,(u32)variable);
if(compiler_type_is_array(type))
variable_size=compiler_array_element_size(type)*
compiler_variable_array_length(compiler,(u32)variable);
else variable_size=compiler_type_size(compiler,type);
if(variable_size) {*size_out=variable_size;return 1;}
}
compiler->Position=position;
} else compiler->Position=position;
if(position<compiler->Length&&compiler->Source[position]=='"') {
usize old_data_length=compiler->DataLength;
usize string_offset,string_length;
if(compiler_string(compiler,&string_offset,&string_length)&&
compiler_take(compiler,')')&&string_length<0xffffffffu) {
compiler->DataLength=old_data_length;
*size_out=(u32)string_length+1u;
return 1;
}
compiler->DataLength=old_data_length;
compiler->Position=position;
}
usize saved_code=compiler->CodePosition;
usize saved_data=compiler->DataLength;
u8 saved_calls=compiler->CallCount;
u16 saved_stack=compiler->StackBytes;
u8 saved_expression_type=compiler->ExpressionType;
u8 saved_integer_type=compiler->IntegerType;
if(!compiler_expression(compiler)||!compiler_take(compiler,')'))return 0;
u8 type=compiler->ExpressionType;
if(type==COMPILER_TYPE_VOID)return 0;
variable_size=compiler_type_size(compiler,type);
if(!variable_size)return 0;
compiler->CodePosition=saved_code;
compiler->DataLength=saved_data;
compiler->CallCount=saved_calls;
compiler->StackBytes=saved_stack;
compiler->ExpressionType=saved_expression_type;
compiler->IntegerType=saved_integer_type;
*size_out=variable_size;
return 1;
}
static int compiler_shift(BOB64_C_COMPILER *compiler);
static int compiler_relational(BOB64_C_COMPILER *compiler);
static int compiler_equality(BOB64_C_COMPILER *compiler);
@@ -908,6 +1055,52 @@ static int compiler_index_address(BOB64_C_COMPILER *compiler,u32 variable) {
return 1;
}
static int compiler_increment_variable(BOB64_C_COMPILER *compiler,u32 variable,
int postfix,char operation) {
u8 type=compiler_variable_type(compiler,variable);
u32 amount=1;
if(compiler_type_is_array(type)||compiler_type_is_struct(type))return 0;
if(compiler_is_pointer(type)) {
amount=compiler_pointer_scale(compiler,type);
if(!amount)return 0;
} else if(type!=COMPILER_TYPE_CHAR&&type!=COMPILER_TYPE_SHORT&&
type!=COMPILER_TYPE_INT&&type!=COMPILER_TYPE_LONG_LONG&&
type!=COMPILER_TYPE_USIZE)return 0;
if(!compiler_variable_load(compiler,variable))return 0;
if(postfix) {
if(!compiler_emit(compiler,0x50))return 0;
compiler->StackBytes+=8;
}
if(amount==1u) {
if(!compiler_emit(compiler,0x48)||!compiler_emit(compiler,0x83)||
!compiler_emit(compiler,operation=='+'?0xc0:0xe8)||
!compiler_emit(compiler,1))return 0;
} else if(!compiler_emit(compiler,0x48)||
!compiler_emit(compiler,operation=='+'?0x05:0x2d)||
!compiler_emit_u32(compiler,amount))return 0;
if(!compiler_variable_store(compiler,variable))return 0;
if(postfix) {
if(!compiler_emit(compiler,0x58))return 0;
compiler->StackBytes-=8;
} else if(type==COMPILER_TYPE_CHAR||type==COMPILER_TYPE_SHORT) {
if(!compiler_variable_load(compiler,variable))return 0;
}
compiler->ExpressionType=type==COMPILER_TYPE_CHAR||type==COMPILER_TYPE_SHORT?
COMPILER_TYPE_INT:type;
return 1;
}
static int compiler_increment_pair(BOB64_C_COMPILER *compiler,char *operation) {
compiler_skip(compiler);
if(compiler->Position+1>=compiler->Length)return 0;
char first=compiler->Source[compiler->Position];
if((first!='+'&&first!='-')||compiler->Source[compiler->Position+1]!=first)
return 0;
compiler->Position+=2;
if(operation)*operation=first;
return 1;
}
static int compiler_primary(BOB64_C_COMPILER *compiler) {
u64 value;
char name[32];
@@ -946,6 +1139,12 @@ static int compiler_primary(BOB64_C_COMPILER *compiler) {
if(compiler->ExpressionType==COMPILER_TYPE_VOID)return 0;
return 1;
}
int enumerator=compiler_enum_constant_find(compiler,name);
if(enumerator>=0) {
compiler->ExpressionType=COMPILER_TYPE_INT;
return compiler_emit_integer(compiler,
compiler->EnumConstants[enumerator].Value);
}
int variable=compiler_variable_find(compiler,name);
if(variable<0)return 0;
u8 variable_type=compiler_variable_type(compiler,(u32)variable);
@@ -1008,11 +1207,67 @@ static int compiler_primary(BOB64_C_COMPILER *compiler) {
compiler_variable_type(compiler,(u32)variable));
return compiler_variable_address(compiler,(u32)variable,0);
}
char operation;
if(compiler_increment_pair(compiler,&operation))
return compiler_increment_variable(compiler,(u32)variable,1,operation);
compiler->ExpressionType=compiler_variable_type(compiler,(u32)variable);
return compiler_variable_load(compiler,(u32)variable);
}
static int compiler_unary(BOB64_C_COMPILER *compiler) {
{
char operation,name[32];
if(compiler_increment_pair(compiler,&operation)) {
if(!compiler_identifier(compiler,name,sizeof(name)))return 0;
int variable=compiler_variable_find(compiler,name);
if(variable<0||!compiler_increment_variable(compiler,(u32)variable,
0,operation))return 0;
return 1;
}
}
if(compiler_word(compiler,"sizeof")) {
u32 size;
if(!compiler_take(compiler,'('))return 0;
int type_result=compiler_sizeof_type(compiler,&size);
if(!type_result)return 0;
if(type_result<0&&!compiler_sizeof_expression(compiler,&size))return 0;
if(!compiler_emit_integer(compiler,size))return 0;
compiler->ExpressionType=COMPILER_TYPE_USIZE;
return 1;
}
{
usize saved_position=compiler->Position;
if(compiler_take(compiler,'(')) {
u8 value_type=compiler_type_specifier(compiler);
int pointer=compiler_take(compiler,'*');
if(value_type&&compiler_take(compiler,')')) {
u8 target_type=pointer?compiler_pointer_to(compiler,value_type):value_type;
if(!target_type||(compiler_type_is_struct(value_type)&&!pointer)||
(!pointer&&value_type==COMPILER_TYPE_VOID)||
!compiler_unary(compiler)||
compiler->ExpressionType==COMPILER_TYPE_VOID||
compiler_type_is_struct(compiler->ExpressionType))return 0;
if(!pointer) {
if(target_type==COMPILER_TYPE_CHAR) {
if(!compiler_emit(compiler,0x48)||!compiler_emit(compiler,0x0f)||
!compiler_emit(compiler,0xbe)||!compiler_emit(compiler,0xc0))
return 0;
} else if(target_type==COMPILER_TYPE_SHORT) {
if(!compiler_emit(compiler,0x48)||!compiler_emit(compiler,0x0f)||
!compiler_emit(compiler,0xbf)||!compiler_emit(compiler,0xc0))
return 0;
} else if(target_type==COMPILER_TYPE_INT) {
if(!compiler_emit(compiler,0x48)||!compiler_emit(compiler,0x63)||
!compiler_emit(compiler,0xc0))return 0;
} else if(target_type!=COMPILER_TYPE_LONG_LONG&&
target_type!=COMPILER_TYPE_USIZE)return 0;
}
compiler->ExpressionType=target_type;
return 1;
}
compiler->Position=saved_position;
}
}
if(compiler_take(compiler,'&')) {
char name[32];
if(!compiler_identifier(compiler,name,sizeof(name)))return 0;
@@ -1032,6 +1287,7 @@ static int compiler_unary(BOB64_C_COMPILER *compiler) {
}
if(compiler_take(compiler,'*')) {
if(!compiler_unary(compiler)||!compiler_is_pointer(compiler->ExpressionType)||
compiler->ExpressionType==COMPILER_TYPE_VOID_POINTER||
compiler_type_is_struct_pointer(compiler->ExpressionType))
return 0;
if(compiler->ExpressionType==COMPILER_TYPE_CHAR_POINTER) {
@@ -1143,7 +1399,9 @@ static int compiler_additive(BOB64_C_COMPILER *compiler) {
if(!compiler_term(compiler))return 0;
right_type=compiler->ExpressionType;
if(compiler_is_pointer(left_type)&&compiler_is_pointer(right_type)) {
if(left_type!=right_type)return 0;
if(!compiler_pointer_types_compatible(left_type,right_type)||
left_type==COMPILER_TYPE_VOID_POINTER||
right_type==COMPILER_TYPE_VOID_POINTER)return 0;
if(operation!='-'||!compiler_emit(compiler,0x59)||
!compiler_emit(compiler,0x48)||!compiler_emit(compiler,0x29)||
!compiler_emit(compiler,0xc1)||!compiler_emit(compiler,0x48)||
@@ -1163,10 +1421,11 @@ static int compiler_additive(BOB64_C_COMPILER *compiler) {
continue;
}
if(compiler_is_pointer(left_type)) {
if(left_type==COMPILER_TYPE_VOID_POINTER)return 0;
if(!compiler_emit_scale_register(compiler,
compiler_pointer_scale(compiler,left_type),0))return 0;
} else if(compiler_is_pointer(right_type)) {
if(operation!='+'||!compiler_emit(compiler,0x59)||
if(right_type==COMPILER_TYPE_VOID_POINTER||operation!='+'||!compiler_emit(compiler,0x59)||
!compiler_emit_scale_register(compiler,
compiler_pointer_scale(compiler,right_type),1)||
!compiler_emit(compiler,0x48)||!compiler_emit(compiler,0x01)||
@@ -1258,7 +1517,7 @@ static int compiler_compare_level(BOB64_C_COMPILER *compiler,
u8 right_type=compiler->ExpressionType;
int pointer_comparison=compiler_is_pointer(left_type)||
compiler_is_pointer(right_type);
if(pointer_comparison&&(left_type!=right_type||
if(pointer_comparison&&(!compiler_pointer_types_compatible(left_type,right_type)||
!compiler_is_pointer(left_type)||!equality))return 0;
u8 condition=left_type==COMPILER_TYPE_USIZE||right_type==COMPILER_TYPE_USIZE?
operations[operation].UnsignedCondition:operations[operation].SetCondition;
@@ -1489,6 +1748,13 @@ static int compiler_local_statement(BOB64_C_COMPILER *compiler) {
compiler->Position=saved;return 0;
}
u8 variable_type=compiler_variable_type(compiler,(u32)variable);
char increment_operation;
if(compiler_increment_pair(compiler,&increment_operation)) {
if(!compiler_increment_variable(compiler,(u32)variable,1,
increment_operation)||
!compiler_take(compiler,';'))return -1;
return 1;
}
int pointer_member=compiler_type_is_struct_pointer(variable_type);
if(compiler_type_is_struct(variable_type)||pointer_member) {
char field_name[32];
@@ -1511,8 +1777,7 @@ static int compiler_local_statement(BOB64_C_COMPILER *compiler) {
!compiler_emit(compiler,0x50))return -1;
compiler->StackBytes+=8;
if(!compiler_expression(compiler)||
(compiler_is_pointer(field->Type)!=compiler_is_pointer(compiler->ExpressionType))||
(compiler_is_pointer(field->Type)&&field->Type!=compiler->ExpressionType)||
!compiler_value_types_compatible(field->Type,compiler->ExpressionType)||
!compiler_take(compiler,';')||!compiler_emit(compiler,0x59)||
!compiler_member_store(compiler,field->Type))return -1;
compiler->StackBytes-=8;
@@ -1549,19 +1814,18 @@ static int compiler_local_statement(BOB64_C_COMPILER *compiler) {
compiler->Position=saved;return 0;
}
if(!compiler_expression(compiler)||
(compiler_is_pointer(compiler_variable_type(compiler,(u32)variable))!=
compiler_is_pointer(compiler->ExpressionType)||
(compiler_is_pointer(compiler_variable_type(compiler,(u32)variable))&&
compiler_variable_type(compiler,(u32)variable)!=compiler->ExpressionType))||
!compiler_value_types_compatible(
compiler_variable_type(compiler,(u32)variable),
compiler->ExpressionType)||
!compiler_take(compiler,';')||
!compiler_variable_store(compiler,(u32)variable))return -1;
return 1;
}
if(declared_type==COMPILER_TYPE_VOID)return -1;
if(compiler_take(compiler,'*')) {
declared_type=compiler_pointer_to(compiler,declared_type);
if(!declared_type)return -1;
}
if(declared_type==COMPILER_TYPE_VOID)return -1;
is_struct=compiler_type_is_struct(declared_type);
is_pointer=compiler_is_pointer(declared_type);
is_char=declared_type==COMPILER_TYPE_CHAR;
@@ -1591,13 +1855,13 @@ static int compiler_local_statement(BOB64_C_COMPILER *compiler) {
!compiler_array_initializer(compiler,(u32)variable))return -1;
return 1;
}
if(!compiler_take(compiler,'='))return -1;
u8 type=declared_type;
if(!compiler_add_variable(compiler,name,type,0,0))return -1;
variable=compiler_variable_find(compiler,name);
if(compiler_take(compiler,';'))return 1;
if(!compiler_take(compiler,'='))return -1;
if(!compiler_expression(compiler)||
(compiler_is_pointer(type)!=compiler_is_pointer(compiler->ExpressionType)||
(compiler_is_pointer(type)&&type!=compiler->ExpressionType))||
!compiler_value_types_compatible(type,compiler->ExpressionType)||
!compiler_take(compiler,';')||
!compiler_variable_store(compiler,(u32)variable))return -1;
return 1;
@@ -1632,7 +1896,7 @@ static int compiler_return_type_matches(BOB64_C_COMPILER *compiler) {
int result_pointer=compiler_is_pointer(compiler->ReturnType);
int expression_pointer=compiler_is_pointer(compiler->ExpressionType);
if(result_pointer)return expression_pointer&&
compiler->ReturnType==compiler->ExpressionType;
compiler_pointer_types_compatible(compiler->ReturnType,compiler->ExpressionType);
return !expression_pointer||compiler->Return64;
}
@@ -1657,17 +1921,20 @@ static int compiler_patch_branch(BOB64_C_COMPILER *compiler,u16 displacement_off
}
static int compiler_loop_push(BOB64_C_COMPILER *compiler,usize continue_target) {
if(compiler->LoopDepth>=sizeof(compiler->Loops)/sizeof(compiler->Loops[0])||
if(compiler->ControlCount>=sizeof(compiler->Controls)/sizeof(compiler->Controls[0])||
continue_target>0xffffu)return 0;
BOB64_C_LOOP *loop=&compiler->Loops[compiler->LoopDepth++];
BOB64_C_CONTROL *loop=&compiler->Controls[compiler->ControlCount++];
loop->Kind=COMPILER_CONTROL_LOOP;
loop->ContinueTarget=(u16)continue_target;
loop->BreakCount=0;loop->ContinueCount=0;
return 1;
}
static int compiler_loop_finish(BOB64_C_COMPILER *compiler,usize break_target) {
if(!compiler->LoopDepth)return 0;
BOB64_C_LOOP *loop=&compiler->Loops[--compiler->LoopDepth];
if(!compiler->ControlCount||
compiler->Controls[compiler->ControlCount-1].Kind!=COMPILER_CONTROL_LOOP)
return 0;
BOB64_C_CONTROL *loop=&compiler->Controls[--compiler->ControlCount];
for(u32 i=0;i<loop->BreakCount;i++)
if(!compiler_patch_branch(compiler,loop->BreakBranches[i],break_target))return 0;
for(u32 i=0;i<loop->ContinueCount;i++)
@@ -1675,8 +1942,82 @@ static int compiler_loop_finish(BOB64_C_COMPILER *compiler,usize break_target) {
return 1;
}
static int compiler_switch_push(BOB64_C_COMPILER *compiler,
BOB64_C_CONTROL **control) {
if(compiler->ControlCount>=sizeof(compiler->Controls)/sizeof(compiler->Controls[0]))
return 0;
BOB64_C_CONTROL *entry=&compiler->Controls[compiler->ControlCount++];
entry->Kind=COMPILER_CONTROL_SWITCH;entry->BreakCount=0;
entry->ContinueCount=0;entry->CaseCount=0;entry->HasDefault=0;
*control=entry;
return 1;
}
static int compiler_switch_finish(BOB64_C_COMPILER *compiler,
usize break_target) {
if(!compiler->ControlCount||
compiler->Controls[compiler->ControlCount-1].Kind!=COMPILER_CONTROL_SWITCH)
return 0;
BOB64_C_CONTROL *control=&compiler->Controls[--compiler->ControlCount];
for(u32 i=0;i<control->BreakCount;i++)
if(!compiler_patch_branch(compiler,control->BreakBranches[i],break_target))
return 0;
return 1;
}
static int compiler_switch_temporary(BOB64_C_COMPILER *compiler,u8 type,
u32 *variable) {
for(u32 candidate=0;candidate<100;candidate++) {
char name[16]={'_','b','6','4','s','w',
(char)('0'+candidate/10),(char)('0'+candidate%10),0};
if(compiler_variable_find(compiler,name)<0) {
if(!compiler_add_variable(compiler,name,type,0,0))return 0;
int found=compiler_variable_find(compiler,name);
if(found<0||found>=0x8000)return 0;
*variable=(u32)found;
return 1;
}
}
return 0;
}
static int compiler_switch_constant(BOB64_C_COMPILER *compiler,u64 *value) {
int negative=compiler_take(compiler,'-');
if(!negative)compiler_take(compiler,'+');
if(compiler_character(compiler,value)) {
if(negative)*value=0u-*value;
return 1;
}
if(!compiler_integer(compiler,value)) {
char name[32];
if(!compiler_identifier(compiler,name,sizeof(name)))return 0;
int enumerator=compiler_enum_constant_find(compiler,name);
if(enumerator<0)return 0;
*value=compiler->EnumConstants[enumerator].Value;
if(negative)*value=0u-*value;
return 1;
}
if(negative) {
if(*value>0x8000000000000000ULL)return 0;
*value=0u-*value;
}
return 1;
}
static int compiler_statement(BOB64_C_COMPILER *compiler) {
usize saved=compiler->Position;
{
char operation,name[32];
if(compiler_increment_pair(compiler,&operation)) {
if(!compiler_identifier(compiler,name,sizeof(name)))return -1;
int variable=compiler_variable_find(compiler,name);
if(variable<0||!compiler_increment_variable(compiler,(u32)variable,
0,operation)||
!compiler_take(compiler,';'))return -1;
return 1;
}
compiler->Position=saved;
}
if(compiler_word(compiler,"return")) {
if(compiler->ReturnType==COMPILER_TYPE_VOID) {
if(compiler->StackBytes||!compiler_take(compiler,';')||
@@ -1690,18 +2031,25 @@ static int compiler_statement(BOB64_C_COMPILER *compiler) {
}
compiler->Position=saved;
if(compiler_word(compiler,"break")) {
if(!compiler->LoopDepth||!compiler_take(compiler,';'))return -1;
BOB64_C_LOOP *loop=&compiler->Loops[compiler->LoopDepth-1];
if(loop->BreakCount>=sizeof(loop->BreakBranches)/sizeof(loop->BreakBranches[0])||
!compiler_emit_branch(compiler,0xe9,&loop->BreakBranches[loop->BreakCount]))return -1;
loop->BreakCount++;
if(!compiler->ControlCount||!compiler_take(compiler,';'))return -1;
BOB64_C_CONTROL *control=&compiler->Controls[compiler->ControlCount-1];
if(control->BreakCount>=sizeof(control->BreakBranches)/
sizeof(control->BreakBranches[0])||
!compiler_emit_branch(compiler,0xe9,
&control->BreakBranches[control->BreakCount]))return -1;
control->BreakCount++;
return 1;
}
compiler->Position=saved;
if(compiler_word(compiler,"continue")) {
if(!compiler->LoopDepth||!compiler_take(compiler,';'))return -1;
BOB64_C_LOOP *loop=&compiler->Loops[compiler->LoopDepth-1];
if(loop->ContinueCount>=sizeof(loop->ContinueBranches)/sizeof(loop->ContinueBranches[0])||
BOB64_C_CONTROL *loop=0;
for(u32 depth=compiler->ControlCount;depth>0;depth--)
if(compiler->Controls[depth-1].Kind==COMPILER_CONTROL_LOOP) {
loop=&compiler->Controls[depth-1];break;
}
if(!loop||!compiler_take(compiler,';'))return -1;
if(loop->ContinueCount>=sizeof(loop->ContinueBranches)/
sizeof(loop->ContinueBranches[0])||
!compiler_emit_branch(compiler,0xe9,
&loop->ContinueBranches[loop->ContinueCount]))return -1;
loop->ContinueCount++;
@@ -1729,6 +2077,76 @@ static int compiler_statement(BOB64_C_COMPILER *compiler) {
return 1;
}
compiler->Position=saved;
if(compiler_word(compiler,"switch")) {
BOB64_C_CONTROL *control;
u16 enter_dispatch,body_exit,end_branch=0;
u32 value_variable;
if(compiler->ControlDepth>=32||!compiler_scope_push(compiler)||
!compiler_take(compiler,'(')||!compiler_expression(compiler))return -1;
u8 switch_type=compiler->ExpressionType;
if(compiler_is_pointer(switch_type)||compiler_type_is_array(switch_type)||
compiler_type_is_struct(switch_type)||switch_type==COMPILER_TYPE_VOID||
!compiler_switch_temporary(compiler,switch_type,&value_variable)||
!compiler_variable_store(compiler,value_variable)||
!compiler_take(compiler,')')||!compiler_take(compiler,'{')||
!compiler_switch_push(compiler,&control)||
!compiler_emit_branch(compiler,0xe9,&enter_dispatch))return -1;
compiler->ControlDepth++;
for(;;) {
usize statement_start=compiler->Position;
if(compiler_take(compiler,'}'))break;
if(compiler_word(compiler,"case")) {
u64 value;
if(control->CaseCount>=COMPILER_SWITCH_CASE_LIMIT||
!compiler_switch_constant(compiler,&value)||
!compiler_take(compiler,':'))return -1;
for(u32 i=0;i<control->CaseCount;i++)
if(control->CaseValues[i]==value)return -1;
u32 index=control->CaseCount++;
control->CaseValues[index]=value;
control->CaseTargets[index]=(u16)compiler->CodePosition;
continue;
}
compiler->Position=statement_start;
if(compiler_word(compiler,"default")) {
if(control->HasDefault||!compiler_take(compiler,':'))return -1;
control->HasDefault=1;
control->DefaultTarget=(u16)compiler->CodePosition;
continue;
}
compiler->Position=statement_start;
if(compiler_statement(compiler)<=0)return -1;
}
compiler->ControlDepth--;
if(!compiler_emit_branch(compiler,0xe9,&body_exit)||
!compiler_patch_branch(compiler,enter_dispatch,
compiler->CodePosition))return -1;
for(u32 i=0;i<control->CaseCount;i++) {
if(!compiler_variable_load(compiler,value_variable)||
!compiler_emit(compiler,0x48)||!compiler_emit(compiler,0xb9)||
!compiler_emit_u64(compiler,control->CaseValues[i])||
!compiler_emit(compiler,0x48)||!compiler_emit(compiler,0x39)||
!compiler_emit(compiler,0xc8)||!compiler_emit(compiler,0x0f))
return -1;
u16 case_branch;
if(!compiler_emit_branch(compiler,0x84,&case_branch)||
!compiler_patch_branch(compiler,case_branch,
control->CaseTargets[i]))return -1;
}
if(control->HasDefault) {
if(!compiler_emit_branch(compiler,0xe9,&end_branch)||
!compiler_patch_branch(compiler,end_branch,
control->DefaultTarget))return -1;
} else if(!compiler_emit_branch(compiler,0xe9,&end_branch))return -1;
usize switch_end=compiler->CodePosition;
if(!compiler_patch_branch(compiler,body_exit,switch_end)||
(!control->HasDefault&&
!compiler_patch_branch(compiler,end_branch,switch_end))||
!compiler_switch_finish(compiler,switch_end))return -1;
compiler_scope_pop(compiler);
return 1;
}
compiler->Position=saved;
if(compiler_word(compiler,"for")) {
u16 loop_exit,body_branch,loop_back;
usize loop_start,post_start,body_start;
@@ -1766,6 +2184,30 @@ static int compiler_statement(BOB64_C_COMPILER *compiler) {
return 1;
}
compiler->Position=saved;
if(compiler_word(compiler,"do")) {
usize body_start=compiler->CodePosition,condition_start;
u16 loop_back;
if(compiler->ControlDepth>=32||!compiler_loop_push(compiler,0))return -1;
compiler->ControlDepth++;
if(compiler_statement(compiler)<=0)return -1;
compiler->ControlDepth--;
condition_start=compiler->CodePosition;
if(condition_start>0xffffu||!compiler->ControlCount||
compiler->Controls[compiler->ControlCount-1].Kind!=COMPILER_CONTROL_LOOP)
return -1;
compiler->Controls[compiler->ControlCount-1].ContinueTarget=
(u16)condition_start;
if(!compiler_word(compiler,"while")||!compiler_take(compiler,'(')||
!compiler_expression(compiler)||!compiler_take(compiler,')')||
!compiler_take(compiler,';')||!compiler_emit(compiler,0x48)||
!compiler_emit(compiler,0x85)||!compiler_emit(compiler,0xc0)||
!compiler_emit(compiler,0x0f)||
!compiler_emit_branch(compiler,0x85,&loop_back)||
!compiler_patch_branch(compiler,loop_back,body_start)||
!compiler_loop_finish(compiler,compiler->CodePosition))return -1;
return 1;
}
compiler->Position=saved;
if(compiler_word(compiler,"while")) {
usize loop_start=compiler->CodePosition;
u16 loop_exit,loop_back;
@@ -1835,8 +2277,17 @@ static int compiler_statement(BOB64_C_COMPILER *compiler) {
static int compiler_for_post(BOB64_C_COMPILER *compiler) {
char name[32];
char operation;
if(compiler_increment_pair(compiler,&operation)) {
if(!compiler_identifier(compiler,name,sizeof(name)))return 0;
int variable=compiler_variable_find(compiler,name);
return variable>=0&&compiler_increment_variable(compiler,(u32)variable,
0,operation);
}
if(!compiler_identifier(compiler,name,sizeof(name)))return 0;
int variable=compiler_variable_find(compiler,name);
if(variable>=0&&compiler_increment_pair(compiler,&operation))
return compiler_increment_variable(compiler,(u32)variable,1,operation);
if(variable<0||compiler_type_is_array(compiler_variable_type(compiler,(u32)variable))||
!compiler_take(compiler,'=')||!compiler_expression(compiler)||
(compiler_is_pointer(compiler_variable_type(compiler,(u32)variable))!=
@@ -1982,8 +2433,7 @@ static int compiler_resolve_calls(BOB64_C_COMPILER *compiler) {
for(u32 argument=0;argument<call->ArgumentCount;argument++) {
u8 expected=compiler->Functions[function].ArgumentTypes[argument];
u8 actual=call->ArgumentTypes[argument];
if(compiler_is_pointer(expected)!=compiler_is_pointer(actual)||
(compiler_is_pointer(expected)&&expected!=actual))return 0;
if(!compiler_value_types_compatible(expected,actual))return 0;
}
s64 displacement=(s64)compiler->Functions[function].CodeOffset-
(s64)(call->DisplacementOffset+4u);
@@ -2052,7 +2502,9 @@ static int compiler_global_add(BOB64_C_COMPILER *compiler,const char *name,
u8 type,u32 array_length,u32 bytes,u32 *global_index) {
usize name_length=0;
if(compiler->GlobalCount>=COMPILER_GLOBAL_LIMIT||
compiler_variable_find(compiler,name)>=0||bytes>sizeof(compiler->Data)-compiler->DataLength)
compiler_variable_find(compiler,name)>=0||
compiler_enum_constant_find(compiler,name)>=0||
bytes>sizeof(compiler->Data)-compiler->DataLength)
return 0;
u32 alignment=compiler_type_is_struct(type)?compiler_type_alignment(compiler,type):
((type==COMPILER_TYPE_LONG_LONG||type==COMPILER_TYPE_USIZE||
@@ -2097,8 +2549,9 @@ static int compiler_struct_definition(BOB64_C_COMPILER *compiler,const char *nam
u8 base_type=compiler_type_specifier(compiler);
int struct_index=compiler_type_is_struct(base_type)?
(int)(base_type-COMPILER_TYPE_STRUCT_BASE):-1;
if(!base_type||base_type==COMPILER_TYPE_VOID)return 0;
if(!base_type)return 0;
int pointer=compiler_take(compiler,'*');
if(base_type==COMPILER_TYPE_VOID&&!pointer)return 0;
if(struct_index>=0&&!pointer)return 0;
char field_name[32];
if(!compiler_identifier(compiler,field_name,sizeof(field_name))||
@@ -2125,9 +2578,58 @@ static int compiler_struct_definition(BOB64_C_COMPILER *compiler,const char *nam
return compiler_take(compiler,';');
}
/* Returns 1 for a definition, 0 when this is an enum-typed declaration, -1 on error. */
static int compiler_enum_definition(BOB64_C_COMPILER *compiler) {
usize saved=compiler->Position;
char tag[32];
if(!compiler_word(compiler,"enum")||
!compiler_identifier(compiler,tag,sizeof(tag))||
!compiler_take(compiler,'{')) {
compiler->Position=saved;
return 0;
}
if(compiler->EnumCount>=COMPILER_ENUM_LIMIT||
compiler_enum_find(compiler,tag)>=0)return -1;
u32 enum_index=compiler->EnumCount++;
usize tag_length=0;
while(tag[tag_length]) {
compiler->Enums[enum_index].Name[tag_length]=tag[tag_length];
tag_length++;
}
compiler->Enums[enum_index].Name[tag_length]=0;
u64 next_value=0;
u32 count=0;
for(;;) {
char name[32];
if(!compiler_identifier(compiler,name,sizeof(name))||
compiler_enum_constant_find(compiler,name)>=0||
compiler_variable_find(compiler,name)>=0||
compiler_function_find(compiler,name)>=0||
compiler_typedef_find(compiler,name)>=0||
compiler->EnumConstantCount>=COMPILER_ENUM_CONSTANT_LIMIT)return -1;
BOB64_C_ENUM_CONSTANT *constant=
&compiler->EnumConstants[compiler->EnumConstantCount++];
usize length=0;
while(name[length]) {constant->Name[length]=name[length];length++;}
constant->Name[length]=0;
if(compiler_take(compiler,'=')) {
if(!compiler_switch_constant(compiler,&next_value))return -1;
}
constant->Value=next_value;
count++;
if(compiler_take(compiler,'}'))break;
if(!compiler_take(compiler,','))return -1;
if(compiler_take(compiler,'}'))break;
if(next_value==~(u64)0)return -1;
next_value++;
}
if(!count||!compiler_take(compiler,';'))return -1;
return 1;
}
static int compiler_typedef_name_reserved(const char *name) {
static const char *reserved[]={"void","char","short","int","long",
"usize","uintptr_t","isize","intptr_t","struct"};
"usize","uintptr_t","isize","intptr_t","struct","enum"};
for(u32 i=0;i<sizeof(reserved)/sizeof(reserved[0]);i++) {
usize position=0;
while(name[position]&&name[position]==reserved[i][position])position++;
@@ -2140,14 +2642,17 @@ static int compiler_typedef_declaration(BOB64_C_COMPILER *compiler) {
char name[32];
if(!compiler_word(compiler,"typedef"))return 0;
u8 type=compiler_type_specifier(compiler);
if(!type||type==COMPILER_TYPE_VOID)return 0;
if(compiler_take(compiler,'*')) {
if(!type)return 0;
int pointer=compiler_take(compiler,'*');
if(type==COMPILER_TYPE_VOID&&!pointer)return 0;
if(pointer) {
type=compiler_pointer_to(compiler,type);
if(!type)return 0;
}
if(!compiler_identifier(compiler,name,sizeof(name))||
compiler_typedef_name_reserved(name)||
compiler_typedef_find(compiler,name)>=0||
compiler_enum_constant_find(compiler,name)>=0||
compiler->TypedefCount>=COMPILER_TYPEDEF_LIMIT||
!compiler_take(compiler,';'))return 0;
BOB64_C_TYPEDEF *alias=&compiler->Typedefs[compiler->TypedefCount++];
@@ -2171,8 +2676,10 @@ static int compiler_global_declaration(BOB64_C_COMPILER *compiler) {
if(structure<0)return 0;
base_type=(u8)(COMPILER_TYPE_STRUCT_BASE+(u32)structure);
} else base_type=compiler_type_specifier(compiler);
if(!base_type||base_type==COMPILER_TYPE_VOID)return 0;
if(compiler_take(compiler,'*')) {
if(!base_type)return 0;
int pointer=compiler_take(compiler,'*');
if(base_type==COMPILER_TYPE_VOID&&!pointer)return 0;
if(pointer) {
base_type=compiler_pointer_to(compiler,base_type);
if(!base_type)return 0;
}
@@ -2200,7 +2707,8 @@ static int compiler_global_declaration(BOB64_C_COMPILER *compiler) {
if(is_struct)return 0;
if(is_pointer) {
usize string_offset,string_length;
if(type==COMPILER_TYPE_CHAR_POINTER&&
if((type==COMPILER_TYPE_CHAR_POINTER||
type==COMPILER_TYPE_VOID_POINTER)&&
compiler_string(compiler,&string_offset,&string_length)) {
(void)string_length;
global->InitKind=2;
@@ -2222,7 +2730,7 @@ static int compiler_global_declaration(BOB64_C_COMPILER *compiler) {
else if(address)
target_pointer_type=compiler_pointer_type(target_type);
else target_pointer_type=0;
if(target_pointer_type!=type||
if(!compiler_value_types_compatible(type,target_pointer_type)||
(compiler_type_is_struct(target_type)&&!address))return 0;
global->InitKind=1;
global->InitTarget=target_global->DataOffset;
@@ -2244,8 +2752,7 @@ static int compiler_global_declaration(BOB64_C_COMPILER *compiler) {
if(compiler_take(compiler,'}'))break;
u64 value;
if(element>=array_length||
(!compiler_character(compiler,&value)&&
!compiler_integer(compiler,&value)))return 0;
!compiler_switch_constant(compiler,&value))return 0;
compiler->Data[global->DataOffset+element++]=(u8)value;
if(compiler_take(compiler,'}'))break;
if(!compiler_take(compiler,','))return 0;
@@ -2258,8 +2765,7 @@ static int compiler_global_declaration(BOB64_C_COMPILER *compiler) {
if(compiler_take(compiler,'}'))break;
u64 value;
if(element>=array_length||
(!compiler_character(compiler,&value)&&
!compiler_integer(compiler,&value)))return 0;
!compiler_switch_constant(compiler,&value))return 0;
u32 element_size=compiler_array_element_size((u8)type);
u32 offset=global->DataOffset+element++*element_size;
for(u32 byte=0;byte<element_size;byte++)
@@ -2269,8 +2775,7 @@ static int compiler_global_declaration(BOB64_C_COMPILER *compiler) {
}
} else {
u64 value;
if(!compiler_character(compiler,&value)&&
!compiler_integer(compiler,&value))return 0;
if(!compiler_switch_constant(compiler,&value))return 0;
for(u32 byte=0;byte<bytes;byte++)
compiler->Data[global->DataOffset+byte]=(u8)(value>>(byte*8));
}
@@ -2289,6 +2794,15 @@ static int compiler_collect_function_sources(BOB64_C_COMPILER *compiler,
if(compiler->Failed)return 0;
if(compiler->Position>=compiler->Length)break;
usize start=compiler->Position;
if(compiler_word(compiler,"enum")) {
compiler->Position=start;
int enum_result=compiler_enum_definition(compiler);
if(enum_result<0)return 0;
if(enum_result>0) {
scan=compiler->Position;
continue;
}
}
if(compiler_word(compiler,"typedef")) {
compiler->Position=start;
if(!compiler_typedef_declaration(compiler))return 0;
@@ -2367,8 +2881,8 @@ int bob64_compile_c(const char *source,usize source_length,void *output,
compiler.IntegerValue=0;compiler.Return64=0;compiler.Failed=0;
compiler.VariableCount=0;
compiler.FunctionCount=0;compiler.GlobalCount=0;compiler.StructCount=0;
compiler.TypedefCount=0;
compiler.CallCount=0;compiler.LoopDepth=0;
compiler.TypedefCount=0;compiler.EnumCount=0;compiler.EnumConstantCount=0;
compiler.CallCount=0;compiler.ControlCount=0;
compiler.FunctionSourceCount=0;
for(usize i=0;i<sizeof(compiler.Data);i++)compiler.Data[i]=0;
for(usize i=0;i<sizeof(compiler.VariableNames);i++)
+70 -29
View File
@@ -1,11 +1,12 @@
#include "console.h"
#include "font.h"
#include "font8x16.h"
typedef struct {
volatile u32 *Pixels;
u64 SizeBytes;
u32 Width,Height,Stride,Format,Column,Row;
u8 Ready;
u8 Ready,CursorDrawn;
} BOB64_FRAMEBUFFER;
static BOB64_FRAMEBUFFER framebuffer;
@@ -25,68 +26,105 @@ static void clear_row(u32 y) {
for(u32 x=0;x<framebuffer.Width;x++)pixel(x,y,background);
}
static u32 columns(void) {
u32 result=framebuffer.Width/FONT_CELL_WIDTH;
return result?result:1;
}
static u32 rows(void) {
u32 result=framebuffer.Height/LINE_HEIGHT;
return result?result:1;
}
static u32 row_origin(void) {
return framebuffer.Row*LINE_HEIGHT+(LINE_HEIGHT-FONT_HEIGHT)/2;
}
static void erase_cursor(void) {
if(!framebuffer.Ready)return;
u32 x=framebuffer.Column*FONT_CELL_WIDTH;
u32 y=framebuffer.Row*LINE_HEIGHT+LINE_HEIGHT-2;
for(u32 offset=0;offset<FONT_WIDTH;offset++)
pixel(x+offset,y,color(12,18,28));
framebuffer.CursorDrawn=0;
}
static void draw_cursor(void) {
if(!framebuffer.Ready)return;
u32 x=framebuffer.Column*FONT_CELL_WIDTH;
u32 y=framebuffer.Row*LINE_HEIGHT+LINE_HEIGHT-2;
for(u32 offset=0;offset<FONT_WIDTH;offset++)
pixel(x+offset,y,color(148,194,232));
framebuffer.CursorDrawn=1;
}
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;
framebuffer.Column=0;framebuffer.Row=0;framebuffer.CursorDrawn=0;
}
static void scroll(void) {
u32 lines=framebuffer.Height>8?framebuffer.Height-8:0;
u32 lines=framebuffer.Height>LINE_HEIGHT?
framebuffer.Height-LINE_HEIGHT: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;
volatile u32 *source=destination+(u64)LINE_HEIGHT*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;
framebuffer.Row=rows()-1;
}
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;
if(value<' '||value>'~')value='?';
return (u32)(value-' ');
}
static void console_plot_pixel(void *context,s64 x,s64 y,u32 scale,
u32 value) {
(void)context;
for(u32 dy=0;dy<scale;dy++)for(u32 dx=0;dx<scale;dx++)
if(x+(s64)dx>=0&&x+(s64)dx<framebuffer.Width&&
y+(s64)dy>=0&&y+(s64)dy<framebuffer.Height)
pixel((u32)(x+(s64)dx),(u32)(y+(s64)dy),value);
}
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);
}
u32 glyph=glyph_index(value),origin_x=framebuffer.Column*FONT_CELL_WIDTH;
u32 origin_y=row_origin();
for(u32 y=0;y<LINE_HEIGHT;y++)
for(u32 x=0;x<FONT_CELL_WIDTH;x++)pixel(origin_x+x,
framebuffer.Row*LINE_HEIGHT+y,background);
bob64_font_draw_glyph(&bob64_font8x16,glyph,origin_x,origin_y,1,
console_plot_pixel,0,foreground);
framebuffer.Column++;
if(framebuffer.Column>=framebuffer.Width/6) {
if(framebuffer.Column>=columns()) {
framebuffer.Column=0;
framebuffer.Row++;
}
if(framebuffer.Row>=framebuffer.Height/8)scroll();
if(framebuffer.Row>=rows())scroll();
}
static void erase_previous_character(void) {
u32 columns=framebuffer.Width/6;
u32 column_count=columns();
if(framebuffer.Column)framebuffer.Column--;
else if(framebuffer.Row) {
framebuffer.Row--;
framebuffer.Column=columns-1;
framebuffer.Column=column_count-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++)
u32 origin_x=framebuffer.Column*FONT_CELL_WIDTH;
u32 origin_y=framebuffer.Row*LINE_HEIGHT;
for(u32 y=0;y<LINE_HEIGHT;y++)for(u32 x=0;x<FONT_CELL_WIDTH;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||
if(!base||!size||width<FONT_CELL_WIDTH||height<FONT_HEIGHT||
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;
@@ -115,6 +153,7 @@ int bob64_framebuffer_resolution(u32 *width,u32 *height) {
int bob64_framebuffer_write_pixels(u64 first_pixel,const u32 *pixels,u32 count) {
u64 total;
if(!framebuffer.Ready||(!pixels&&count))return -1;
if(count&&framebuffer.CursorDrawn)erase_cursor();
total=(u64)framebuffer.Width*framebuffer.Height;
if(first_pixel>total||(u64)count>total-first_pixel)return -1;
for(u32 i=0;i<count;i++) {
@@ -128,13 +167,15 @@ int bob64_framebuffer_write_pixels(u64 first_pixel,const u32 *pixels,u32 count)
void bob64_framebuffer_write(const char *text) {
if(!framebuffer.Ready||!text)return;
if(framebuffer.CursorDrawn)erase_cursor();
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();
if(framebuffer.Row>=rows())scroll();
} else if(value=='\b')erase_previous_character();
else draw_character(value);
}
draw_cursor();
}
+241
View File
@@ -0,0 +1,241 @@
#include "disk_store.h"
#define DISK_STORE_VERSION 1u
#define DISK_STORE_HEADER_SIZE 40u
#define DISK_STORE_HEADER_CRC_OFFSET 36u
typedef struct {
u64 Generation,PayloadSize;
u32 PayloadCrc;
u8 Valid;
} DISK_STORE_SLOT;
static u8 disk_store_workspace[BOB64_BLOCK_MAX_TRANSFER_BYTES];
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 write32(u8 *bytes,u32 value) {
for(u32 i=0;i<4;i++)bytes[i]=(u8)(value>>(i*8));
}
static void write64(u8 *bytes,u64 value) {
write32(bytes,(u32)value);write32(bytes+4,(u32)(value>>32));
}
static u32 crc32_step(u32 crc,const u8 *bytes,usize length) {
for(usize i=0;i<length;i++) {
crc^=bytes[i];
for(u32 bit=0;bit<8;bit++)
crc=(crc>>1)^(0xedb88320u&-(crc&1u));
}
return crc;
}
static u32 header_crc(const u8 *header) {
u8 copy[DISK_STORE_HEADER_SIZE];
for(u32 i=0;i<sizeof(copy);i++)
copy[i]=(i>=DISK_STORE_HEADER_CRC_OFFSET&&
i<DISK_STORE_HEADER_CRC_OFFSET+4u)?0:header[i];
return crc32_step(0xffffffffu,copy,sizeof(copy))^0xffffffffu;
}
static int valid_partition(BOB64_BLOCK_DEVICE *device,
const BOB64_PARTITION *partition,u64 *slot_blocks) {
if(!device||!partition||!slot_blocks||!device->BlockSize||
device->BlockSize>sizeof(disk_store_workspace)||
partition->BlockCount<4u||partition->FirstLba>=device->BlockCount||
partition->BlockCount>device->BlockCount-partition->FirstLba||
partition->BlockCount-1u>0xffffffffffffffffULL-partition->FirstLba)
return -1;
for(u32 i=0;i<BOB64_GPT_GUID_SIZE;i++)
if(partition->TypeGuid[i]!=bob64_gpt_bob_data_type_guid[i])return -1;
*slot_blocks=partition->BlockCount/2u;
return *slot_blocks>=2u?0:-1;
}
static u64 slot_start(const BOB64_PARTITION *partition,u64 slot_blocks,
u32 slot) {
return partition->FirstLba+(u64)slot*slot_blocks;
}
static int payload_crc(BOB64_BLOCK_DEVICE *device,u64 lba,u64 payload_size,
u32 *result_crc) {
u32 crc=0xffffffffu;
u64 remaining=payload_size;
if(!device||!result_crc||!payload_size)return -1;
while(remaining) {
u64 blocks=(remaining+device->BlockSize-1u)/device->BlockSize;
if(blocks>device->MaxTransferBlocks)blocks=device->MaxTransferBlocks;
if(!blocks||blocks>0xffffffffu||
bob64_block_read(device,lba,(u32)blocks,disk_store_workspace))return -1;
u64 bytes=blocks*(u64)device->BlockSize;
if(bytes>remaining)bytes=remaining;
crc=crc32_step(crc,disk_store_workspace,(usize)bytes);
lba+=blocks;remaining-=bytes;
}
*result_crc=crc^0xffffffffu;
return 0;
}
static int read_slot(BOB64_BLOCK_DEVICE *device,
const BOB64_PARTITION *partition,u64 slot_blocks,u32 index,
DISK_STORE_SLOT *slot) {
u64 start=slot_start(partition,slot_blocks,index);
u64 maximum_payload=(slot_blocks-1u)*(u64)device->BlockSize;
u32 actual_crc;
if(!slot||bob64_block_read(device,start,1,disk_store_workspace))return -1;
slot->Valid=0;slot->Generation=0;slot->PayloadSize=0;slot->PayloadCrc=0;
if(disk_store_workspace[0]!='B'||disk_store_workspace[1]!='6'||
disk_store_workspace[2]!='4'||disk_store_workspace[3]!='D'||
read32(disk_store_workspace+4)!=DISK_STORE_VERSION||
read32(disk_store_workspace+8)!=DISK_STORE_HEADER_SIZE||
read32(disk_store_workspace+12)!=0||
read32(disk_store_workspace+DISK_STORE_HEADER_CRC_OFFSET)!=
header_crc(disk_store_workspace))return 1;
slot->Generation=read64(disk_store_workspace+16);
slot->PayloadSize=read64(disk_store_workspace+24);
slot->PayloadCrc=read32(disk_store_workspace+32);
if(!slot->Generation||!slot->PayloadSize||
slot->PayloadSize>maximum_payload)return 1;
if(payload_crc(device,start+1u,slot->PayloadSize,&actual_crc))return -1;
if(actual_crc!=slot->PayloadCrc)return 1;
slot->Valid=1;
return 0;
}
static int write_payload(BOB64_BLOCK_DEVICE *device,u64 lba,
const u8 *payload,usize payload_size) {
u64 remaining=payload_size;
usize offset=0;
while(remaining) {
u64 blocks=(remaining+device->BlockSize-1u)/device->BlockSize;
if(blocks>device->MaxTransferBlocks)blocks=device->MaxTransferBlocks;
if(!blocks||blocks>0xffffffffu)return -1;
u64 capacity=blocks*(u64)device->BlockSize;
u64 bytes=remaining<capacity?remaining:capacity;
for(usize i=0;i<(usize)capacity;i++)
disk_store_workspace[i]=i<(usize)bytes?payload[offset+i]:0;
if(bob64_block_write(device,lba,(u32)blocks,disk_store_workspace))return -1;
lba+=blocks;offset+=(usize)bytes;remaining-=bytes;
}
return 0;
}
static int read_payload(BOB64_BLOCK_DEVICE *device,u64 lba,
u8 *payload,usize payload_size) {
u64 remaining=payload_size;
usize offset=0;
while(remaining) {
u64 blocks=(remaining+device->BlockSize-1u)/device->BlockSize;
if(blocks>device->MaxTransferBlocks)blocks=device->MaxTransferBlocks;
if(!blocks||blocks>0xffffffffu||
bob64_block_read(device,lba,(u32)blocks,disk_store_workspace))return -1;
u64 capacity=blocks*(u64)device->BlockSize;
u64 bytes=remaining<capacity?remaining:capacity;
for(usize i=0;i<(usize)bytes;i++)payload[offset+i]=disk_store_workspace[i];
lba+=blocks;offset+=(usize)bytes;remaining-=bytes;
}
return 0;
}
static int inspect_slots(BOB64_BLOCK_DEVICE *device,
const BOB64_PARTITION *partition,u64 slot_blocks,
DISK_STORE_SLOT slots[2]) {
for(u32 i=0;i<2;i++) {
int result=read_slot(device,partition,slot_blocks,i,&slots[i]);
if(result<0)return result;
}
return 0;
}
int bob64_disk_store_save(BOB64_BLOCK_DEVICE *device,
const BOB64_PARTITION *partition,BOB64_FILESYSTEM *filesystem,
BOB64_HEAP *heap) {
DISK_STORE_SLOT slots[2]={{0}};
usize snapshot_size=0,written=0;
u8 *snapshot;
u64 slot_blocks,maximum_payload,generation,start;
u32 target;
if(!device||!filesystem||!heap||device->ReadOnly||!device->Write||!device->Flush||
valid_partition(device,partition,&slot_blocks)||
bob64_fs_snapshot_size(filesystem,&snapshot_size)||!snapshot_size)
return -1;
maximum_payload=(slot_blocks-1u)*(u64)device->BlockSize;
if((u64)snapshot_size>maximum_payload)return -2;
if(inspect_slots(device,partition,slot_blocks,slots))return -3;
if(!slots[0].Valid)target=0;
else if(!slots[1].Valid)target=1;
else target=slots[0].Generation<=slots[1].Generation?0u:1u;
generation=1;
if(slots[0].Valid&&slots[0].Generation>=generation) {
if(slots[0].Generation==~(u64)0)return -4;
generation=slots[0].Generation+1u;
}
if(slots[1].Valid&&slots[1].Generation>=generation) {
if(slots[1].Generation==~(u64)0)return -4;
generation=slots[1].Generation+1u;
}
snapshot=(u8 *)bob64_heap_alloc(heap,snapshot_size);
if(!snapshot)return -5;
if(bob64_fs_snapshot_write(filesystem,snapshot,snapshot_size,&written)||
written!=snapshot_size) {
bob64_heap_free(heap,snapshot);return -6;
}
start=slot_start(partition,slot_blocks,target);
if(write_payload(device,start+1u,snapshot,snapshot_size)||
bob64_block_flush(device)) {
bob64_heap_free(heap,snapshot);return -7;
}
u32 checksum=crc32_step(0xffffffffu,snapshot,snapshot_size)^0xffffffffu;
bob64_heap_free(heap,snapshot);
for(u32 i=0;i<device->BlockSize;i++)disk_store_workspace[i]=0;
disk_store_workspace[0]='B';disk_store_workspace[1]='6';
disk_store_workspace[2]='4';disk_store_workspace[3]='D';
write32(disk_store_workspace+4,DISK_STORE_VERSION);
write32(disk_store_workspace+8,DISK_STORE_HEADER_SIZE);
write64(disk_store_workspace+16,generation);
write64(disk_store_workspace+24,snapshot_size);
write32(disk_store_workspace+32,checksum);
write32(disk_store_workspace+DISK_STORE_HEADER_CRC_OFFSET,
header_crc(disk_store_workspace));
if(bob64_block_write(device,start,1,disk_store_workspace)||
bob64_block_flush(device))return -8;
return 0;
}
int bob64_disk_store_restore(BOB64_BLOCK_DEVICE *device,
const BOB64_PARTITION *partition,BOB64_FILESYSTEM *filesystem,
BOB64_HEAP *heap) {
DISK_STORE_SLOT slots[2]={{0}};
u64 slot_blocks;
int order[2],valid_count=0;
if(!filesystem||!heap||valid_partition(device,partition,&slot_blocks))
return -1;
if(inspect_slots(device,partition,slot_blocks,slots))return -2;
for(int i=0;i<2;i++)if(slots[i].Valid)order[valid_count++]=i;
if(!valid_count)return BOB64_DISK_STORE_NOT_FOUND;
if(valid_count==2&&slots[order[1]].Generation>slots[order[0]].Generation) {
int swap=order[0];order[0]=order[1];order[1]=swap;
}
for(int attempt=0;attempt<valid_count;attempt++) {
int index=order[attempt];
if(slots[index].PayloadSize>~(usize)0)continue;
usize size=(usize)slots[index].PayloadSize;
u8 *snapshot=(u8 *)bob64_heap_alloc(heap,size);
if(!snapshot)return -3;
int loaded=read_payload(device,slot_start(partition,slot_blocks,
(u32)index)+1u,snapshot,size);
int restored=loaded?loaded:bob64_fs_snapshot_restore(filesystem,
snapshot,size);
bob64_heap_free(heap,snapshot);
if(!restored)return 0;
}
return -4;
}
+17
View File
@@ -0,0 +1,17 @@
#ifndef BOB64_DISK_STORE_H
#define BOB64_DISK_STORE_H
#include "partition.h"
#include "snapshot.h"
#define BOB64_DISK_STORE_NOT_FOUND 1
/* Two-slot transactional B64S persistence inside the dedicated GPT partition. */
int bob64_disk_store_save(BOB64_BLOCK_DEVICE *device,
const BOB64_PARTITION *partition,BOB64_FILESYSTEM *filesystem,
BOB64_HEAP *heap);
int bob64_disk_store_restore(BOB64_BLOCK_DEVICE *device,
const BOB64_PARTITION *partition,BOB64_FILESYSTEM *filesystem,
BOB64_HEAP *heap);
#endif
+12 -4
View File
@@ -9,7 +9,7 @@
EFI_VARIABLE_BOOTSERVICE_ACCESS|EFI_VARIABLE_RUNTIME_ACCESS)
#define BOB64_FIRMWARE_SNAPSHOT_RAW_LIMIT (32u*1024u*1024u)
#define BOB64_FIRMWARE_CHUNK_SIZE 30720u
#define BOB64_FIRMWARE_CHUNK_COUNT 2u
#define BOB64_FIRMWARE_CHUNK_COUNT 6u
#define BOB64_FIRMWARE_MANIFEST_SIZE 32u
#define BOB64_FIRMWARE_ACTIVE_SIZE 16u
@@ -22,11 +22,19 @@ static const CHAR16 firmware_manifest_names[2][14]={
{'B','o','b','6','4','S','l','o','t','A',0},
{'B','o','b','6','4','S','l','o','t','B',0}
};
static const CHAR16 firmware_chunk_names[2][2][16]={
static const CHAR16 firmware_chunk_names[2][BOB64_FIRMWARE_CHUNK_COUNT][16]={
{{'B','o','b','6','4','D','a','t','a','A','0',0},
{'B','o','b','6','4','D','a','t','a','A','1',0}},
{'B','o','b','6','4','D','a','t','a','A','1',0},
{'B','o','b','6','4','D','a','t','a','A','2',0},
{'B','o','b','6','4','D','a','t','a','A','3',0},
{'B','o','b','6','4','D','a','t','a','A','4',0},
{'B','o','b','6','4','D','a','t','a','A','5',0}},
{{'B','o','b','6','4','D','a','t','a','B','0',0},
{'B','o','b','6','4','D','a','t','a','B','1',0}}
{'B','o','b','6','4','D','a','t','a','B','1',0},
{'B','o','b','6','4','D','a','t','a','B','2',0},
{'B','o','b','6','4','D','a','t','a','B','3',0},
{'B','o','b','6','4','D','a','t','a','B','4',0},
{'B','o','b','6','4','D','a','t','a','B','5',0}}
};
static const CHAR16 firmware_active_name[]={
'B','o','b','6','4','A','c','t','i','v','e',0
+1 -1
View File
@@ -5,7 +5,7 @@
#include "filesystem.h"
#include "heap.h"
#define BOB64_FIRMWARE_SNAPSHOT_LIMIT 61440u
#define BOB64_FIRMWARE_SNAPSHOT_LIMIT (6u*30720u)
#define BOB64_FIRMWARE_SNAPSHOT_HEADER_SIZE 24u
#define BOB64_FIRMWARE_SNAPSHOT_NOT_FOUND 1
+41
View File
@@ -1,6 +1,12 @@
#ifndef BOB64_FONT_H
#define BOB64_FONT_H
#define FONT_WIDTH 8u
#define FONT_HEIGHT 16u
#define LINE_HEIGHT 18u
#define CHAR_SPACING 1u
#define FONT_CELL_WIDTH (FONT_WIDTH+CHAR_SPACING)
/* Compact 5x7 font: blank, A-Z, 0-9, ?, !, -, period, colon, equals, >. */
static const u8 bob64_font5x7[44][5]={
{0,0,0,0,0},
@@ -28,4 +34,39 @@ static const u8 bob64_font5x7[44][5]={
{0x41,0x22,0x14,0x08,0x00}
};
typedef struct {
const u8 *Data;
u8 Width,Height;
u16 GlyphCount;
u8 BytesPerGlyph,ColumnMajor,MostSignificantBitFirst;
} BOB64_BITMAP_FONT;
static const BOB64_BITMAP_FONT bob64_font5x7={
&bob64_font5x7[0][0],5,7,44,5,1,0
};
typedef void (*BOB64_FONT_PLOT_PIXEL)(void *context,s64 x,s64 y,
u32 scale,u32 color);
static inline int bob64_font_sample(const BOB64_BITMAP_FONT *font,u32 glyph,
u32 x,u32 y) {
u32 axis,bit;
if(!font||!font->Data||glyph>=font->GlyphCount||x>=font->Width||
y>=font->Height)return 0;
if(font->ColumnMajor)axis=x,bit=y;
else axis=y,bit=x;
u8 mask=font->MostSignificantBitFirst?
(u8)(0x80u>>bit):(u8)(1u<<bit);
return (font->Data[(usize)glyph*font->BytesPerGlyph+axis]&mask)!=0;
}
static inline void bob64_font_draw_glyph(const BOB64_BITMAP_FONT *font,
u32 glyph,s64 x,s64 y,u32 scale,BOB64_FONT_PLOT_PIXEL plot,
void *context,u32 color) {
if(!font||!plot||!scale||glyph>=font->GlyphCount)return;
for(u32 row=0;row<font->Height;row++)for(u32 column=0;column<font->Width;column++)
if(bob64_font_sample(font,glyph,column,row))
plot(context,x+(s64)column*scale,y+(s64)row*scale,scale,color);
}
#endif
+114
View File
@@ -0,0 +1,114 @@
#ifndef BOB64_FONT8X16_H
#define BOB64_FONT8X16_H
#include "font.h"
/*
* Printable ASCII 8x16 bitmaps adapted from Plan C's font8x16 project:
* https://github.com/hubenchang0515/font8x16
* The upstream MIT license is retained in FONT_LICENSE.md.
* Each byte is one scanline; the high bit is the leftmost pixel.
*/
static const u8 bob64_font8x16_data[95][16]={
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, /* 0x20 space */
{0x00,0x00,0x18,0x3c,0x3c,0x3c,0x18,0x18,0x18,0x00,0x18,0x18,0x00,0x00,0x00,0x00}, /* 0x21 ! */
{0x00,0x66,0x66,0x66,0x24,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, /* 0x22 quote */
{0x00,0x00,0x00,0x6c,0x6c,0xfe,0x6c,0x6c,0x6c,0xfe,0x6c,0x6c,0x00,0x00,0x00,0x00}, /* 0x23 # */
{0x18,0x18,0x7c,0xc6,0xc2,0xc0,0x7c,0x06,0x06,0x86,0xc6,0x7c,0x18,0x18,0x00,0x00}, /* 0x24 $ */
{0x00,0x00,0x00,0x00,0xc2,0xc6,0x0c,0x18,0x30,0x60,0xc6,0x86,0x00,0x00,0x00,0x00}, /* 0x25 % */
{0x00,0x00,0x38,0x6c,0x6c,0x38,0x76,0xdc,0xcc,0xcc,0xcc,0x76,0x00,0x00,0x00,0x00}, /* 0x26 & */
{0x00,0x30,0x30,0x30,0x60,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, /* 0x27 apostrophe */
{0x00,0x00,0x0c,0x18,0x30,0x30,0x30,0x30,0x30,0x30,0x18,0x0c,0x00,0x00,0x00,0x00}, /* 0x28 ( */
{0x00,0x00,0x30,0x18,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x18,0x30,0x00,0x00,0x00,0x00}, /* 0x29 ) */
{0x00,0x00,0x00,0x00,0x00,0x66,0x3c,0xff,0x3c,0x66,0x00,0x00,0x00,0x00,0x00,0x00}, /* 0x2a * */
{0x00,0x00,0x00,0x00,0x00,0x18,0x18,0x7e,0x18,0x18,0x00,0x00,0x00,0x00,0x00,0x00}, /* 0x2b + */
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x18,0x18,0x18,0x30,0x00,0x00,0x00}, /* 0x2c , */
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xfe,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, /* 0x2d - */
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x18,0x18,0x00,0x00,0x00,0x00}, /* 0x2e . */
{0x00,0x00,0x00,0x00,0x02,0x06,0x0c,0x18,0x30,0x60,0xc0,0x80,0x00,0x00,0x00,0x00}, /* 0x2f / */
{0x00,0x00,0x38,0x6c,0xc6,0xc6,0xd6,0xd6,0xc6,0xc6,0x6c,0x38,0x00,0x00,0x00,0x00}, /* 0x30 0 */
{0x00,0x00,0x18,0x38,0x78,0x18,0x18,0x18,0x18,0x18,0x18,0x7e,0x00,0x00,0x00,0x00}, /* 0x31 1 */
{0x00,0x00,0x7c,0xc6,0x06,0x0c,0x18,0x30,0x60,0xc0,0xc6,0xfe,0x00,0x00,0x00,0x00}, /* 0x32 2 */
{0x00,0x00,0x7c,0xc6,0x06,0x06,0x3c,0x06,0x06,0x06,0xc6,0x7c,0x00,0x00,0x00,0x00}, /* 0x33 3 */
{0x00,0x00,0x0c,0x1c,0x3c,0x6c,0xcc,0xfe,0x0c,0x0c,0x0c,0x1e,0x00,0x00,0x00,0x00}, /* 0x34 4 */
{0x00,0x00,0xfe,0xc0,0xc0,0xc0,0xfc,0x06,0x06,0x06,0xc6,0x7c,0x00,0x00,0x00,0x00}, /* 0x35 5 */
{0x00,0x00,0x38,0x60,0xc0,0xc0,0xfc,0xc6,0xc6,0xc6,0xc6,0x7c,0x00,0x00,0x00,0x00}, /* 0x36 6 */
{0x00,0x00,0xfe,0xc6,0x06,0x06,0x0c,0x18,0x30,0x30,0x30,0x30,0x00,0x00,0x00,0x00}, /* 0x37 7 */
{0x00,0x00,0x7c,0xc6,0xc6,0xc6,0x7c,0xc6,0xc6,0xc6,0xc6,0x7c,0x00,0x00,0x00,0x00}, /* 0x38 8 */
{0x00,0x00,0x7c,0xc6,0xc6,0xc6,0x7e,0x06,0x06,0x06,0x0c,0x78,0x00,0x00,0x00,0x00}, /* 0x39 9 */
{0x00,0x00,0x00,0x00,0x18,0x18,0x00,0x00,0x00,0x18,0x18,0x00,0x00,0x00,0x00,0x00}, /* 0x3a : */
{0x00,0x00,0x00,0x00,0x18,0x18,0x00,0x00,0x00,0x18,0x18,0x30,0x00,0x00,0x00,0x00}, /* 0x3b ; */
{0x00,0x00,0x00,0x06,0x0c,0x18,0x30,0x60,0x30,0x18,0x0c,0x06,0x00,0x00,0x00,0x00}, /* 0x3c < */
{0x00,0x00,0x00,0x00,0x00,0x7e,0x00,0x00,0x7e,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, /* 0x3d = */
{0x00,0x00,0x00,0x60,0x30,0x18,0x0c,0x06,0x0c,0x18,0x30,0x60,0x00,0x00,0x00,0x00}, /* 0x3e > */
{0x00,0x00,0x7c,0xc6,0xc6,0x0c,0x18,0x18,0x18,0x00,0x18,0x18,0x00,0x00,0x00,0x00}, /* 0x3f ? */
{0x00,0x00,0x00,0x7c,0xc6,0xc6,0xde,0xde,0xde,0xdc,0xc0,0x7c,0x00,0x00,0x00,0x00}, /* 0x40 @ */
{0x00,0x00,0x10,0x38,0x6c,0xc6,0xc6,0xfe,0xc6,0xc6,0xc6,0xc6,0x00,0x00,0x00,0x00}, /* 0x41 A */
{0x00,0x00,0xfc,0x66,0x66,0x66,0x7c,0x66,0x66,0x66,0x66,0xfc,0x00,0x00,0x00,0x00}, /* 0x42 B */
{0x00,0x00,0x3c,0x66,0xc2,0xc0,0xc0,0xc0,0xc0,0xc2,0x66,0x3c,0x00,0x00,0x00,0x00}, /* 0x43 C */
{0x00,0x00,0xf8,0x6c,0x66,0x66,0x66,0x66,0x66,0x66,0x6c,0xf8,0x00,0x00,0x00,0x00}, /* 0x44 D */
{0x00,0x00,0xfe,0x66,0x62,0x68,0x78,0x68,0x60,0x62,0x66,0xfe,0x00,0x00,0x00,0x00}, /* 0x45 E */
{0x00,0x00,0xfe,0x66,0x62,0x68,0x78,0x68,0x60,0x60,0x60,0xf0,0x00,0x00,0x00,0x00}, /* 0x46 F */
{0x00,0x00,0x3c,0x66,0xc2,0xc0,0xc0,0xde,0xc6,0xc6,0x66,0x3a,0x00,0x00,0x00,0x00}, /* 0x47 G */
{0x00,0x00,0xc6,0xc6,0xc6,0xc6,0xfe,0xc6,0xc6,0xc6,0xc6,0xc6,0x00,0x00,0x00,0x00}, /* 0x48 H */
{0x00,0x00,0x3c,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x3c,0x00,0x00,0x00,0x00}, /* 0x49 I */
{0x00,0x00,0x1e,0x0c,0x0c,0x0c,0x0c,0x0c,0xcc,0xcc,0xcc,0x78,0x00,0x00,0x00,0x00}, /* 0x4a J */
{0x00,0x00,0xe6,0x66,0x66,0x6c,0x78,0x78,0x6c,0x66,0x66,0xe6,0x00,0x00,0x00,0x00}, /* 0x4b K */
{0x00,0x00,0xf0,0x60,0x60,0x60,0x60,0x60,0x60,0x62,0x66,0xfe,0x00,0x00,0x00,0x00}, /* 0x4c L */
{0x00,0x00,0xc6,0xee,0xfe,0xfe,0xd6,0xc6,0xc6,0xc6,0xc6,0xc6,0x00,0x00,0x00,0x00}, /* 0x4d M */
{0x00,0x00,0xc6,0xe6,0xf6,0xfe,0xde,0xce,0xc6,0xc6,0xc6,0xc6,0x00,0x00,0x00,0x00}, /* 0x4e N */
{0x00,0x00,0x7c,0xc6,0xc6,0xc6,0xc6,0xc6,0xc6,0xc6,0xc6,0x7c,0x00,0x00,0x00,0x00}, /* 0x4f O */
{0x00,0x00,0xfc,0x66,0x66,0x66,0x7c,0x60,0x60,0x60,0x60,0xf0,0x00,0x00,0x00,0x00}, /* 0x50 P */
{0x00,0x00,0x7c,0xc6,0xc6,0xc6,0xc6,0xc6,0xc6,0xd6,0xde,0x7c,0x0c,0x0e,0x00,0x00}, /* 0x51 Q */
{0x00,0x00,0xfc,0x66,0x66,0x66,0x7c,0x6c,0x66,0x66,0x66,0xe6,0x00,0x00,0x00,0x00}, /* 0x52 R */
{0x00,0x00,0x7c,0xc6,0xc6,0x60,0x38,0x0c,0x06,0xc6,0xc6,0x7c,0x00,0x00,0x00,0x00}, /* 0x53 S */
{0x00,0x00,0x7e,0x7e,0x5a,0x18,0x18,0x18,0x18,0x18,0x18,0x3c,0x00,0x00,0x00,0x00}, /* 0x54 T */
{0x00,0x00,0xc6,0xc6,0xc6,0xc6,0xc6,0xc6,0xc6,0xc6,0xc6,0x7c,0x00,0x00,0x00,0x00}, /* 0x55 U */
{0x00,0x00,0xc6,0xc6,0xc6,0xc6,0xc6,0xc6,0xc6,0x6c,0x38,0x10,0x00,0x00,0x00,0x00}, /* 0x56 V */
{0x00,0x00,0xc6,0xc6,0xc6,0xc6,0xd6,0xd6,0xd6,0xfe,0xee,0x6c,0x00,0x00,0x00,0x00}, /* 0x57 W */
{0x00,0x00,0xc6,0xc6,0x6c,0x7c,0x38,0x38,0x7c,0x6c,0xc6,0xc6,0x00,0x00,0x00,0x00}, /* 0x58 X */
{0x00,0x00,0x66,0x66,0x66,0x66,0x3c,0x18,0x18,0x18,0x18,0x3c,0x00,0x00,0x00,0x00}, /* 0x59 Y */
{0x00,0x00,0xfe,0xc6,0x86,0x0c,0x18,0x30,0x60,0xc2,0xc6,0xfe,0x00,0x00,0x00,0x00}, /* 0x5a Z */
{0x00,0x00,0x3c,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x3c,0x00,0x00,0x00,0x00}, /* 0x5b [ */
{0x00,0x00,0x00,0x80,0xc0,0xe0,0x70,0x38,0x1c,0x0e,0x06,0x02,0x00,0x00,0x00,0x00}, /* 0x5c backslash */
{0x00,0x00,0x3c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x3c,0x00,0x00,0x00,0x00}, /* 0x5d ] */
{0x10,0x38,0x6c,0xc6,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, /* 0x5e ^ */
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0x00,0x00}, /* 0x5f _ */
{0x30,0x30,0x18,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, /* 0x60 ` */
{0x00,0x00,0x00,0x00,0x00,0x78,0x0c,0x7c,0xcc,0xcc,0xcc,0x76,0x00,0x00,0x00,0x00}, /* 0x61 a */
{0x00,0x00,0xe0,0x60,0x60,0x78,0x6c,0x66,0x66,0x66,0x66,0x7c,0x00,0x00,0x00,0x00}, /* 0x62 b */
{0x00,0x00,0x00,0x00,0x00,0x7c,0xc6,0xc0,0xc0,0xc0,0xc6,0x7c,0x00,0x00,0x00,0x00}, /* 0x63 c */
{0x00,0x00,0x1c,0x0c,0x0c,0x3c,0x6c,0xcc,0xcc,0xcc,0xcc,0x76,0x00,0x00,0x00,0x00}, /* 0x64 d */
{0x00,0x00,0x00,0x00,0x00,0x7c,0xc6,0xfe,0xc0,0xc0,0xc6,0x7c,0x00,0x00,0x00,0x00}, /* 0x65 e */
{0x00,0x00,0x38,0x6c,0x64,0x60,0xf0,0x60,0x60,0x60,0x60,0xf0,0x00,0x00,0x00,0x00}, /* 0x66 f */
{0x00,0x00,0x00,0x00,0x00,0x76,0xcc,0xcc,0xcc,0xcc,0xcc,0x7c,0x0c,0xcc,0x78,0x00}, /* 0x67 g */
{0x00,0x00,0xe0,0x60,0x60,0x6c,0x76,0x66,0x66,0x66,0x66,0xe6,0x00,0x00,0x00,0x00}, /* 0x68 h */
{0x00,0x00,0x18,0x18,0x00,0x38,0x18,0x18,0x18,0x18,0x18,0x3c,0x00,0x00,0x00,0x00}, /* 0x69 i */
{0x00,0x00,0x06,0x06,0x00,0x0e,0x06,0x06,0x06,0x06,0x06,0x06,0x66,0x66,0x3c,0x00}, /* 0x6a j */
{0x00,0x00,0xe0,0x60,0x60,0x66,0x6c,0x78,0x78,0x6c,0x66,0xe6,0x00,0x00,0x00,0x00}, /* 0x6b k */
{0x00,0x00,0x38,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x18,0x3c,0x00,0x00,0x00,0x00}, /* 0x6c l */
{0x00,0x00,0x00,0x00,0x00,0xec,0xfe,0xd6,0xd6,0xd6,0xd6,0xc6,0x00,0x00,0x00,0x00}, /* 0x6d m */
{0x00,0x00,0x00,0x00,0x00,0xdc,0x66,0x66,0x66,0x66,0x66,0x66,0x00,0x00,0x00,0x00}, /* 0x6e n */
{0x00,0x00,0x00,0x00,0x00,0x7c,0xc6,0xc6,0xc6,0xc6,0xc6,0x7c,0x00,0x00,0x00,0x00}, /* 0x6f o */
{0x00,0x00,0x00,0x00,0x00,0xdc,0x66,0x66,0x66,0x66,0x66,0x7c,0x60,0x60,0xf0,0x00}, /* 0x70 p */
{0x00,0x00,0x00,0x00,0x00,0x76,0xcc,0xcc,0xcc,0xcc,0xcc,0x7c,0x0c,0x0c,0x1e,0x00}, /* 0x71 q */
{0x00,0x00,0x00,0x00,0x00,0xdc,0x76,0x66,0x60,0x60,0x60,0xf0,0x00,0x00,0x00,0x00}, /* 0x72 r */
{0x00,0x00,0x00,0x00,0x00,0x7c,0xc6,0x60,0x38,0x0c,0xc6,0x7c,0x00,0x00,0x00,0x00}, /* 0x73 s */
{0x00,0x00,0x10,0x30,0x30,0xfc,0x30,0x30,0x30,0x30,0x36,0x1c,0x00,0x00,0x00,0x00}, /* 0x74 t */
{0x00,0x00,0x00,0x00,0x00,0xcc,0xcc,0xcc,0xcc,0xcc,0xcc,0x76,0x00,0x00,0x00,0x00}, /* 0x75 u */
{0x00,0x00,0x00,0x00,0x00,0x66,0x66,0x66,0x66,0x66,0x3c,0x18,0x00,0x00,0x00,0x00}, /* 0x76 v */
{0x00,0x00,0x00,0x00,0x00,0xc6,0xc6,0xd6,0xd6,0xd6,0xfe,0x6c,0x00,0x00,0x00,0x00}, /* 0x77 w */
{0x00,0x00,0x00,0x00,0x00,0xc6,0x6c,0x38,0x38,0x38,0x6c,0xc6,0x00,0x00,0x00,0x00}, /* 0x78 x */
{0x00,0x00,0x00,0x00,0x00,0xc6,0xc6,0xc6,0xc6,0xc6,0xc6,0x7e,0x06,0x0c,0xf8,0x00}, /* 0x79 y */
{0x00,0x00,0x00,0x00,0x00,0xfe,0xcc,0x18,0x30,0x60,0xc6,0xfe,0x00,0x00,0x00,0x00}, /* 0x7a z */
{0x00,0x00,0x0e,0x18,0x18,0x18,0x70,0x18,0x18,0x18,0x18,0x0e,0x00,0x00,0x00,0x00}, /* 0x7b { */
{0x00,0x00,0x18,0x18,0x18,0x18,0x00,0x18,0x18,0x18,0x18,0x18,0x00,0x00,0x00,0x00}, /* 0x7c | */
{0x00,0x00,0x70,0x18,0x18,0x18,0x0e,0x18,0x18,0x18,0x18,0x70,0x00,0x00,0x00,0x00}, /* 0x7d } */
{0x00,0x00,0x76,0xdc,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, /* 0x7e ~ */
};
static const BOB64_BITMAP_FONT bob64_font8x16={
&bob64_font8x16_data[0][0],8,16,95,16,0,1
};
#endif
+97 -19
View File
@@ -24,28 +24,96 @@ static inline int bob64_gfx_init(BOB64_GFX *graphics,u32 *pixels,usize capacity)
}
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;
if(graphics&&graphics->Pixels&&graphics->Width<=BOB64_GFX_MAX_WIDTH&&
graphics->Height<=BOB64_GFX_MAX_HEIGHT&&x>=0&&y>=0&&
(u32)x<graphics->Width&&(u32)y<graphics->Height) {
usize index=(usize)(u32)y*graphics->Width+(u32)x;
if((u64)graphics->Width*graphics->Height<=graphics->Capacity&&
index<graphics->Capacity)
graphics->Pixels[index]=color&0x00ffffffu;
}
}
static inline void bob64_gfx_fill_rect(BOB64_GFX *graphics,s32 x,s32 y,
static inline void bob64_gfx_fill_rect(BOB64_GFX *graphics,s64 x,s64 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);
s64 left=x,top=y,right=x+(s64)width,bottom=y+(s64)height;
usize row_start,row_end;
if(!graphics||!graphics->Pixels||!width||!height||
graphics->Width>BOB64_GFX_MAX_WIDTH||
graphics->Height>BOB64_GFX_MAX_HEIGHT||
(u64)graphics->Width*graphics->Height>graphics->Capacity)return;
if(left<0)left=0;
if(top<0)top=0;
if(right>graphics->Width)right=graphics->Width;
if(bottom>graphics->Height)bottom=graphics->Height;
if(left>=right||top>=bottom)return;
row_start=(usize)top*graphics->Width+(usize)left;
row_end=row_start+(usize)(right-left);
for(s64 row=top;row<bottom;row++) {
for(usize pixel=row_start;pixel<row_end;pixel++)
graphics->Pixels[pixel]=color&0x00ffffffu;
row_start+=graphics->Width;row_end+=graphics->Width;
}
}
static inline u32 bob64_gfx_line_outcode(s64 x,s64 y,u32 width,u32 height) {
return (x<0?1u:(x>=(s64)width?2u:0u))|
(y<0?4u:(y>=(s64)height?8u:0u));
}
/* Interpolate only between endpoints on the segment; each magnitude is at most
* UINT32_MAX, so the unsigned product fits without requiring a 128-bit type. */
static inline s64 bob64_gfx_line_interpolate(s64 start,s64 end,s64 numerator,
s64 denominator) {
s64 delta=end-start;
u64 delta_magnitude=(u64)(delta<0?-delta:delta);
u64 numerator_magnitude=(u64)(numerator<0?-numerator:numerator);
u64 denominator_magnitude=(u64)(denominator<0?-denominator:denominator);
u64 step=(delta_magnitude*numerator_magnitude)/denominator_magnitude;
int negative=((delta<0)^(numerator<0)^(denominator<0));
return start+(negative?-(s64)step:(s64)step);
}
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;
s64 ax=x0,ay=y0,bx=x1,by=y1;
u32 width,height;
if(!graphics||!graphics->Pixels||!graphics->Width||!graphics->Height||
graphics->Width>BOB64_GFX_MAX_WIDTH||
graphics->Height>BOB64_GFX_MAX_HEIGHT||
(u64)graphics->Width*graphics->Height>graphics->Capacity)return;
width=graphics->Width;height=graphics->Height;
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;}
u32 a=bob64_gfx_line_outcode(ax,ay,width,height);
u32 b=bob64_gfx_line_outcode(bx,by,width,height);
u32 outside;
s64 x,y;
if(!(a|b))break;
if(a&b)return;
outside=a?a:b;
if(outside&4u) {
y=0;x=bob64_gfx_line_interpolate(ax,bx,-ay,by-ay);
} else if(outside&8u) {
y=(s64)height-1;
x=bob64_gfx_line_interpolate(ax,bx,y-ay,by-ay);
} else if(outside&1u) {
x=0;y=bob64_gfx_line_interpolate(ay,by,-ax,bx-ax);
} else {
x=(s64)width-1;
y=bob64_gfx_line_interpolate(ay,by,x-ax,bx-ax);
}
if(outside==a)ax=x,ay=y;
else bx=x,by=y;
}
s64 dx=bx>ax?bx-ax:ax-bx,sx=ax<bx?1:-1;
s64 dy=by>ay?ay-by:by-ay,sy=ay<by?1:-1;
s64 error=dx+dy;
for(;;) {
bob64_gfx_pixel(graphics,(s32)ax,(s32)ay,color);
if(ax==bx&&ay==by)break;
s64 twice=error*2;
if(twice>=dy){error+=dy;ax+=sx;}
if(twice<=dx){error+=dx;ay+=sy;}
}
}
@@ -64,16 +132,26 @@ static inline u32 bob64_gfx_glyph(u8 value) {
return 37;
}
typedef struct {
BOB64_GFX *Graphics;
} BOB64_GFX_FONT_CONTEXT;
static inline void bob64_gfx_font_plot_pixel(void *opaque,s64 x,s64 y,
u32 scale,u32 color) {
BOB64_GFX_FONT_CONTEXT *context=(BOB64_GFX_FONT_CONTEXT *)opaque;
bob64_gfx_fill_rect(context->Graphics,x,y,scale,scale,color);
}
static inline void bob64_gfx_text(BOB64_GFX *graphics,s32 x,s32 y,
const char *text,u32 color,u32 scale) {
s64 cursor_x=x,origin_y=y;
BOB64_GFX_FONT_CONTEXT context={graphics};
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);
bob64_font_draw_glyph(&bob64_font5x7,glyph,cursor_x,origin_y,scale,
bob64_gfx_font_plot_pixel,&context,color);
cursor_x+=(s64)6*scale;
}
}
+44
View File
@@ -137,6 +137,50 @@ bob64_irq1_entry:
add rsp,16
iretq
.globl bob64_irq4_entry
bob64_irq4_entry:
push 0
push 36
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
+70
View File
@@ -5,7 +5,11 @@
#include "mouse.h"
#define BOB64_COM1 0x3f8u
#define BOB64_SERIAL_INPUT_QUEUE_SIZE 128u
static int serial_available;
static volatile u8 serial_irq_active;
static u8 serial_input_queue[BOB64_SERIAL_INPUT_QUEUE_SIZE];
static volatile u32 serial_input_head,serial_input_tail;
static u8 pic_ready;
static u8 pic_master_mask=0xff,pic_slave_mask=0xff;
static volatile u64 timer_tick_count;
@@ -73,7 +77,32 @@ void bob64_early_console_hex64(u64 value) {
serial_hex64(value);
}
void bob64_serial_irq_reset(void) {
serial_input_head=serial_input_tail=0;
}
int bob64_serial_irq_capture(u8 character) {
u32 head=serial_input_head,tail=serial_input_tail;
if((u32)(head-tail)>=BOB64_SERIAL_INPUT_QUEUE_SIZE)return -1;
serial_input_queue[head&(BOB64_SERIAL_INPUT_QUEUE_SIZE-1)]=character;
__asm__ volatile("":::"memory");
serial_input_head=head+1;
return 0;
}
int bob64_serial_irq_pop(u8 *character) {
u32 tail=serial_input_tail,head=serial_input_head;
if(!character||tail==head)return -1;
__asm__ volatile("":::"memory");
*character=serial_input_queue[tail&(BOB64_SERIAL_INPUT_QUEUE_SIZE-1)];
__asm__ volatile("":::"memory");
serial_input_tail=tail+1;
return 0;
}
int bob64_early_console_try_read(void) {
u8 character;
if(serial_irq_active)return bob64_serial_irq_pop(&character)?-1:character;
if(!serial_available||(port_in8(BOB64_COM1+5)&1)==0)return -1;
return port_in8(BOB64_COM1);
}
@@ -97,6 +126,8 @@ int bob64_interrupts_build_idt(BOB64_IDT_GATE entries[BOB64_IDT_ENTRIES],u16 sel
}
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[0x24],(u64)(uintptr_t)bob64_irq4_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,
@@ -131,6 +162,23 @@ static void pic_unmask(u8 irq) {
port_out8(0xa1,pic_slave_mask);port_out8(0x21,pic_master_mask);
}
int bob64_interrupts_enable_serial(void) {
u64 saved_flags;
if(!serial_available)return -1;
__asm__ volatile("pushfq; pop %0; cli":"=r"(saved_flags)::"memory");
if(pic_initialize())goto failed;
bob64_serial_irq_reset();
while(port_in8(BOB64_COM1+5)&1u)(void)port_in8(BOB64_COM1);
port_out8(BOB64_COM1+1,0x01); /* receive-data interrupt only */
serial_irq_active=1;
pic_unmask(4);
if(saved_flags&0x200)__asm__ volatile("sti":::"memory");
return 0;
failed:
if(saved_flags&0x200)__asm__ volatile("sti":::"memory");
return -1;
}
void bob64_timer_irq_tick(void) { timer_tick_count++; }
u64 bob64_timer_ticks(void) { return timer_tick_count; }
@@ -213,6 +261,21 @@ failed:
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==0x24) {
for(u32 pending=0;pending<16;pending++) {
u8 interrupt_id=port_in8(BOB64_COM1+2);
u8 reason=(u8)((interrupt_id>>1)&7u);
if(interrupt_id&1u)break;
if(reason==2||reason==6||reason==3) {
u8 line_status=port_in8(BOB64_COM1+5);
while(line_status&1u) {
(void)bob64_serial_irq_capture(port_in8(BOB64_COM1));
line_status=port_in8(BOB64_COM1+5);
}
} else if(reason==0)(void)port_in8(BOB64_COM1+6);
else break;
}
}
else if(frame&&frame->Vector==0x2c) {
(void)bob64_mouse_irq_service();
port_out8(0xa0,0x20);
@@ -235,7 +298,9 @@ u64 BOB64_MS_ABI bob64_exception_dispatch(const BOB64_INTERRUPT_FRAME *frame) {
diagnostic_register("vector",frame->Vector);
diagnostic_register("error",frame->ErrorCode);
diagnostic_register("rip",frame->RIP);
diagnostic_register("rsp",bob64_interrupt_frame_rsp(frame));
diagnostic_register("cs",frame->CS);
if(from_user)diagnostic_register("ss",frame->UserSS);
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);
@@ -245,6 +310,11 @@ u64 BOB64_MS_ABI bob64_exception_dispatch(const BOB64_INTERRUPT_FRAME *frame) {
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(frame->Vector==14) {
u64 cr2;
__asm__ volatile("mov %%cr2,%0":"=r"(cr2));
diagnostic_register("cr2",cr2);
}
}
if(from_user) {
bob64_user_exception_vector=frame->Vector;
+20 -2
View File
@@ -8,17 +8,31 @@ 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;
/* Present in the hardware frame only when the exception changed CPL. */
u64 UserRSP,UserSS;
} 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");
_Static_assert(__builtin_offsetof(BOB64_INTERRUPT_FRAME,UserRSP)==160,
"privilege-change stack pointer frame offset");
_Static_assert(__builtin_offsetof(BOB64_INTERRUPT_FRAME,UserSS)==168,
"privilege-change stack selector frame offset");
_Static_assert(sizeof(BOB64_INTERRUPT_FRAME)==176,
"interrupt frame maximum size");
static inline u64 bob64_interrupt_frame_rsp(const BOB64_INTERRUPT_FRAME *frame) {
if(!frame)return 0;
if((frame->CS&3u)==3u)return frame->UserRSP;
return (u64)(uintptr_t)frame+
__builtin_offsetof(BOB64_INTERRUPT_FRAME,UserRSP);
}
extern void (*bob64_exception_stub_table[32])(void);
extern void bob64_irq0_entry(void);
extern void bob64_irq4_entry(void);
extern void bob64_syscall_entry(void);
extern void bob64_irq1_entry(void);
extern void bob64_irq12_entry(void);
@@ -32,6 +46,7 @@ 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_serial(void);
int bob64_interrupts_enable_mouse(void);
int bob64_interrupts_enable_timer(void);
void bob64_timer_irq_tick(void);
@@ -39,6 +54,9 @@ 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);
void bob64_serial_irq_reset(void);
int bob64_serial_irq_capture(u8 character);
int bob64_serial_irq_pop(u8 *character);
u64 BOB64_MS_ABI bob64_exception_dispatch(const BOB64_INTERRUPT_FRAME *frame);
void BOB64_MS_ABI bob64_irq_dispatch(const BOB64_INTERRUPT_FRAME *frame);
+2415 -33
View File
File diff suppressed because it is too large. Load diff
+140 -13
View File
@@ -5,6 +5,103 @@ static BOB64_KEYBOARD_STATE keyboard_state;
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 BOB64_KEYBOARD_HID_STATE keyboard_hid_state;
static int keyboard_queue_event(const BOB64_EVENT *event) {
#if defined(BOB64_UEFI_ABI)
u64 flags;
#endif
u32 head,tail;
if(!event)return -1;
#if defined(BOB64_UEFI_ABI)
__asm__ volatile("pushfq; popq %0; cli":"=r"(flags)::"memory");
#endif
head=keyboard_event_head;tail=keyboard_event_tail;
if((u32)(head-tail)>=KEYBOARD_EVENT_QUEUE_SIZE) {
#if defined(BOB64_UEFI_ABI)
if(flags&(1ULL<<9))__asm__ volatile("sti":::"memory");
#endif
return -1;
}
keyboard_event_queue[head&(KEYBOARD_EVENT_QUEUE_SIZE-1)]=*event;
__asm__ volatile("":::"memory");
keyboard_event_head=head+1;
#if defined(BOB64_UEFI_ABI)
if(flags&(1ULL<<9))__asm__ volatile("sti":::"memory");
#endif
return 0;
}
static int keyboard_hid_contains(const u8 keys[6],u8 key) {
for(u32 i=0;i<6;i++)if(keys[i]==key)return 1;
return 0;
}
static int keyboard_hid_scancode(u8 usage,u8 *scancode,u8 *extended) {
static const u8 letter_scan[26]={
0x1e,0x30,0x2e,0x20,0x12,0x21,0x22,0x23,0x17,0x24,0x25,0x26,
0x32,0x31,0x18,0x19,0x10,0x13,0x1f,0x14,0x16,0x2f,0x11,0x2d,
0x15,0x2c
};
if(!scancode||!extended)return -1;
*extended=0;
if(usage>=4&&usage<=29)*scancode=letter_scan[usage-4];
else if(usage>=30&&usage<=38)*scancode=(u8)(0x02+usage-30);
else switch(usage) {
case 39:*scancode=0x0b;break;
case 40:*scancode=0x1c;break;
case 41:*scancode=0x01;break;
case 42:*scancode=0x0e;break;
case 43:*scancode=0x0f;break;
case 44:*scancode=0x39;break;
case 45:*scancode=0x0c;break;
case 46:*scancode=0x0d;break;
case 47:*scancode=0x1a;break;
case 48:*scancode=0x1b;break;
case 49:*scancode=0x2b;break;
case 51:*scancode=0x27;break;
case 52:*scancode=0x28;break;
case 53:*scancode=0x29;break;
case 54:*scancode=0x33;break;
case 55:*scancode=0x34;break;
case 56:*scancode=0x35;break;
case 57:*scancode=0x3a;break;
case 58:case 59:case 60:case 61:case 62:case 63:
case 64:case 65:case 66:case 67:
*scancode=(u8)(0x3b+usage-58);break;
case 68:*scancode=0x57;break;
case 69:*scancode=0x58;break;
case 79:*scancode=0x4d;*extended=1;break;
case 80:*scancode=0x4b;*extended=1;break;
case 81:*scancode=0x50;*extended=1;break;
case 82:*scancode=0x48;*extended=1;break;
case 73:*scancode=0x52;*extended=1;break;
case 74:*scancode=0x47;*extended=1;break;
case 75:*scancode=0x49;*extended=1;break;
case 76:*scancode=0x53;*extended=1;break;
case 77:*scancode=0x4f;*extended=1;break;
case 78:*scancode=0x51;*extended=1;break;
default:return -1;
}
return 0;
}
static int keyboard_hid_emit_scancode(BOB64_KEYBOARD_HID_STATE *state,
u8 scancode,u8 extended,int released) {
BOB64_EVENT event;
if(!state)return -1;
if(extended)(void)bob64_keyboard_decode_event(&state->KeyState,0xe0,&event);
if(bob64_keyboard_decode_event(&state->KeyState,
(u8)(scancode|(released?0x80:0)),&event))return -1;
return keyboard_queue_event(&event);
}
static int keyboard_hid_emit(BOB64_KEYBOARD_HID_STATE *state,u8 usage,
int released) {
u8 scancode,extended;
if(keyboard_hid_scancode(usage,&scancode,&extended))return 0;
return keyboard_hid_emit_scancode(state,scancode,extended,released);
}
static const u8 unshifted[128]={
[0x02]='1',[0x03]='2',[0x04]='3',[0x05]='4',[0x06]='5',
@@ -39,6 +136,7 @@ void bob64_keyboard_reset(void) {
keyboard_state.LeftAlt=0;keyboard_state.RightAlt=0;
keyboard_state.CapsLock=0;keyboard_state.Extended=0;
keyboard_state.PauseRemaining=0;
keyboard_hid_state=(BOB64_KEYBOARD_HID_STATE){0};
keyboard_event_head=keyboard_event_tail=0;
}
@@ -49,13 +147,43 @@ void bob64_keyboard_irq_set_active(int active) {
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;
return keyboard_queue_event(&event);
}
int bob64_keyboard_hid_report_device(BOB64_KEYBOARD_HID_STATE *state,
const u8 report[8]) {
static const u8 modifier_scancodes[8]={0x1d,0x2a,0x38,0,0x1d,0x36,0x38,0};
static const u8 modifier_extended[8]={0,0,0,0,1,0,1,0};
u8 modifiers;
int queued=0;
if(!state||!report)return -1;
modifiers=report[0];
for(u32 i=0;i<6;i++)if(report[i+2]>=1&&report[i+2]<=3)return -1;
for(u32 bit=0;bit<8;bit++) {
u8 mask=(u8)(1u<<bit);
if(!modifier_scancodes[bit]||
((modifiers^state->Modifiers)&mask)==0)continue;
if(keyboard_hid_emit_scancode(state,modifier_scancodes[bit],
modifier_extended[bit],!(modifiers&mask)))queued=-1;
}
for(u32 i=0;i<6;i++) {
u8 old_key=state->Keys[i];
if(old_key&&!keyboard_hid_contains(report+2,old_key)&&
keyboard_hid_emit(state,old_key,1))queued=-1;
}
for(u32 i=0;i<6;i++) {
u8 new_key=report[i+2];
if(new_key&&!keyboard_hid_contains(state->Keys,new_key)&&
keyboard_hid_emit(state,new_key,0))queued=-1;
}
state->Modifiers=modifiers;
for(u32 i=0;i<6;i++)state->Keys[i]=report[i+2];
return queued;
}
int bob64_keyboard_hid_report(const u8 report[8]) {
return bob64_keyboard_hid_report_device(&keyboard_hid_state,report);
}
int bob64_keyboard_irq_pop_event(BOB64_EVENT *event) {
@@ -134,13 +262,11 @@ int bob64_keyboard_event_input(const BOB64_EVENT *event) {
int bob64_keyboard_poll(void) {
BOB64_EVENT event;
if(keyboard_irq_active) {
while(!bob64_keyboard_irq_pop_event(&event)) {
int input=bob64_keyboard_event_input(&event);
if(input>=0)return input;
}
return -1;
while(!bob64_keyboard_irq_pop_event(&event)) {
int input=bob64_keyboard_event_input(&event);
if(input>=0)return input;
}
if(keyboard_irq_active)return -1;
if(bob64_keyboard_poll_event(&event))return -1;
return bob64_keyboard_event_input(&event);
}
@@ -148,7 +274,8 @@ int bob64_keyboard_poll(void) {
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);
if(!bob64_keyboard_irq_pop_event(event))return 0;
if(keyboard_irq_active)return -1;
__asm__ volatile("inb $0x64,%0":"=a"(status));
if(status==0xff||!(status&1)||(status&0x20))return -1;
__asm__ volatile("inb $0x60,%0":"=a"(scancode));
+10
View File
@@ -12,6 +12,11 @@ typedef struct {
u8 CapsLock,Extended,PauseRemaining;
} BOB64_KEYBOARD_STATE;
typedef struct {
BOB64_KEYBOARD_STATE KeyState;
u8 Modifiers,Keys[6];
} BOB64_KEYBOARD_HID_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,
@@ -24,5 +29,10 @@ 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);
/* Convert an 8-byte USB HID boot-keyboard report into shared key events. */
int bob64_keyboard_hid_report(const u8 report[8]);
/* Per-device state lets multiple USB keyboards share the event queue safely. */
int bob64_keyboard_hid_report_device(BOB64_KEYBOARD_HID_STATE *state,
const u8 report[8]);
#endif
+266
View File
@@ -1,4 +1,5 @@
#include "libc.h"
#include <stdarg.h>
void *bob64_memcpy(void *destination,const void *source,usize length) {
u8 *out=(u8 *)destination;
@@ -28,13 +29,278 @@ int bob64_memcmp(const void *left,const void *right,usize length) {
return 0;
}
void *bob64_memchr(const void *memory,int value,usize length) {
const u8 *bytes=(const u8 *)memory;
for(usize i=0;i<length;i++)
if(bytes[i]==(u8)value)return (void *)(uintptr_t)(bytes+i);
return 0;
}
usize bob64_strlen(const char *text) {
usize length=0;
while(text[length])length++;
return length;
}
usize bob64_strnlen(const char *text,usize limit) {
usize length=0;
while(length<limit&&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;
}
int bob64_strncmp(const char *left,const char *right,usize limit) {
for(usize i=0;i<limit;i++) {
u8 a=(u8)left[i],b=(u8)right[i];
if(a!=b)return a<b?-1:1;
if(!a)return 0;
}
return 0;
}
char *bob64_strcpy(char *destination,const char *source) {
char *result=destination;
while((*destination++=*source++)!=0) { }
return result;
}
char *bob64_strncpy(char *destination,const char *source,usize count) {
char *result=destination;
usize i=0;
for(;i<count&&source[i];i++)destination[i]=source[i];
for(;i<count;i++)destination[i]=0;
return result;
}
char *bob64_strcat(char *destination,const char *source) {
char *result=destination;
destination+=bob64_strlen(destination);
while((*destination++=*source++)!=0) { }
return result;
}
char *bob64_strncat(char *destination,const char *source,usize count) {
char *result=destination;
destination+=bob64_strlen(destination);
for(usize i=0;i<count&&source[i];i++)destination[i]=source[i];
usize appended=bob64_strnlen(source,count);
destination[appended]=0;
return result;
}
char *bob64_strchr(const char *text,int character) {
u8 wanted=(u8)character;
for(;;text++) {
if((u8)*text==wanted)return (char *)(uintptr_t)text;
if(!*text)return 0;
}
}
char *bob64_strrchr(const char *text,int character) {
u8 wanted=(u8)character;
const char *match=0;
for(;;text++) {
if((u8)*text==wanted)match=text;
if(!*text)return (char *)(uintptr_t)match;
}
}
char *bob64_strstr(const char *text,const char *needle) {
if(!*needle)return (char *)(uintptr_t)text;
for(;*text;text++) {
usize i=0;
while(needle[i]&&text[i]==needle[i])i++;
if(!needle[i])return (char *)(uintptr_t)text;
}
return 0;
}
typedef struct {
char *Buffer;
usize Capacity,Length;
int Failed;
} BOB64_FORMAT_WRITER;
static void format_put(BOB64_FORMAT_WRITER *writer,char character) {
if(!writer||writer->Failed)return;
if(writer->Length==(usize)-1) {writer->Failed=1;return;}
if(writer->Capacity&&writer->Length<writer->Capacity-1)
writer->Buffer[writer->Length]=character;
writer->Length++;
}
static void format_repeat(BOB64_FORMAT_WRITER *writer,char character,
usize count) {
if(!writer||writer->Failed)return;
if(count>(usize)-1-writer->Length) {writer->Failed=1;return;}
usize writable=0;
if(writer->Capacity&&writer->Length<writer->Capacity-1) {
writable=writer->Capacity-1-writer->Length;
if(writable>count)writable=count;
for(usize i=0;i<writable;i++)writer->Buffer[writer->Length+i]=character;
}
writer->Length+=count;
}
static void format_text(BOB64_FORMAT_WRITER *writer,const char *text,
usize length,usize width,int left) {
usize padding=width>length?width-length:0;
if(!left)format_repeat(writer,' ',padding);
for(usize i=0;i<length;i++)format_put(writer,text[i]);
if(left)format_repeat(writer,' ',padding);
}
static void format_integer(BOB64_FORMAT_WRITER *writer,u64 value,int negative,
u32 base,int uppercase,usize width,int left,int zero,int alternate,
int precision_set,usize precision,int force_pointer_prefix,
int show_plus,int show_space) {
static const char lower_digits[]="0123456789abcdef";
static const char upper_digits[]="0123456789ABCDEF";
const char *digits=uppercase?upper_digits:lower_digits;
char reversed[65];
usize digit_count=0,zero_count=0,sign_count=negative||show_plus||show_space;
const char *prefix="";
usize prefix_length=0,body_length,padding;
if(value||!precision_set||precision) {
do {reversed[digit_count++]=digits[value%base];value/=base;}
while(value);
}
if(precision_set&&precision>digit_count)zero_count=precision-digit_count;
if(force_pointer_prefix||((alternate)&&digit_count&&base==16)) {
prefix=uppercase?"0X":"0x";prefix_length=2;
} else if(alternate&&base==8&&(!digit_count||zero_count==0||
reversed[digit_count-1]!='0')) {
prefix="0";prefix_length=1;
}
body_length=sign_count+prefix_length+zero_count+digit_count;
padding=width>body_length?width-body_length:0;
if(!left&&(!zero||precision_set))format_repeat(writer,' ',padding);
if(negative)format_put(writer,'-');
else if(show_plus)format_put(writer,'+');
else if(show_space)format_put(writer,' ');
for(usize i=0;i<prefix_length;i++)format_put(writer,prefix[i]);
if(!left&&zero&&!precision_set)format_repeat(writer,'0',padding);
format_repeat(writer,'0',zero_count);
while(digit_count)format_put(writer,reversed[--digit_count]);
if(left)format_repeat(writer,' ',padding);
}
static int format_parse_number(const char **format,usize *number) {
usize result=0;
int present=0;
while(**format>='0'&&**format<='9') {
usize digit=(usize)(**format-'0');
if(result>((usize)0x7fffffff-digit)/10)return -1;
result=result*10+digit;(*format)++;present=1;
}
*number=result;
return present;
}
int bob64_snprintf(char *destination,usize capacity,const char *format,...) {
BOB64_FORMAT_WRITER writer={destination,capacity,0,0};
va_list arguments;
if((capacity&&!destination)||!format)return -1;
va_start(arguments,format);
while(*format&&!writer.Failed) {
if(*format!='%') {format_put(&writer,*format++);continue;}
format++;
if(*format=='%') {format_put(&writer,*format++);continue;}
int left=0,plus=0,space=0,alternate=0,zero=0;
int flags=1;
while(flags) {
switch(*format) {
case '-':left=1;format++;break;
case '+':plus=1;format++;break;
case ' ':space=1;format++;break;
case '#':alternate=1;format++;break;
case '0':zero=1;format++;break;
default:flags=0;break;
}
}
usize width=0,precision=0;
int number=format_parse_number(&format,&width);
if(number<0) {writer.Failed=1;break;}
if(*format=='*') {
int requested=va_arg(arguments,int);format++;
if(requested<0) {left=1;width=(usize)(-(s64)requested);}
else width=(usize)requested;
}
int precision_set=0;
if(*format=='.') {
format++;precision_set=1;
number=format_parse_number(&format,&precision);
if(number<0) {writer.Failed=1;break;}
if(*format=='*') {
int requested=va_arg(arguments,int);format++;
if(requested<0)precision_set=0;
else precision=(usize)requested;
}
}
enum { FORMAT_INT,FORMAT_LONG,FORMAT_LLONG,FORMAT_SIZE,
FORMAT_SHORT,FORMAT_CHAR } length=FORMAT_INT;
if(*format=='h') {
format++;length=FORMAT_SHORT;
if(*format=='h') {format++;length=FORMAT_CHAR;}
} else if(*format=='l') {
format++;length=FORMAT_LONG;
if(*format=='l') {format++;length=FORMAT_LLONG;}
} else if(*format=='z'||*format=='t') {
format++;length=FORMAT_SIZE;
} else if(*format=='j') {
format++;length=FORMAT_LLONG;
}
char conversion=*format;
if(!conversion) {writer.Failed=1;break;}
format++;
if(conversion=='s') {
const char *text=va_arg(arguments,const char *);
if(!text)text="(null)";
usize count=precision_set?bob64_strnlen(text,precision):
bob64_strlen(text);
format_text(&writer,text,count,width,left);
} else if(conversion=='c') {
char character=(char)va_arg(arguments,int);
usize padding=width>1?width-1:0;
if(!left)format_repeat(&writer,' ',padding);
format_put(&writer,character);
if(left)format_repeat(&writer,' ',padding);
} else if(conversion=='d'||conversion=='i') {
s64 signed_value;
if(length==FORMAT_LONG)signed_value=(s64)va_arg(arguments,long);
else if(length==FORMAT_LLONG)signed_value=va_arg(arguments,long long);
else if(length==FORMAT_SIZE)signed_value=(s64)va_arg(arguments,isize);
else if(length==FORMAT_SHORT)
signed_value=(short)va_arg(arguments,int);
else if(length==FORMAT_CHAR)
signed_value=(signed char)va_arg(arguments,int);
else signed_value=va_arg(arguments,int);
u64 magnitude=signed_value<0?0-(u64)signed_value:(u64)signed_value;
format_integer(&writer,magnitude,signed_value<0,10,0,width,left,
zero,0,precision_set,precision,0,plus,space);
} else if(conversion=='u'||conversion=='o'||conversion=='x'||
conversion=='X'||conversion=='p') {
u64 value;
u32 base=conversion=='o'?8u:
(conversion=='x'||conversion=='X'||conversion=='p')?16u:10u;
if(conversion=='p')value=(u64)(uintptr_t)va_arg(arguments,void *);
else if(length==FORMAT_LONG)value=(u64)va_arg(arguments,unsigned long);
else if(length==FORMAT_LLONG)value=va_arg(arguments,unsigned long long);
else if(length==FORMAT_SIZE)value=(u64)va_arg(arguments,usize);
else if(length==FORMAT_SHORT)value=(u16)va_arg(arguments,int);
else if(length==FORMAT_CHAR)value=(u8)va_arg(arguments,int);
else value=va_arg(arguments,unsigned int);
format_integer(&writer,value,0,base,conversion=='X',width,left,
zero,alternate||conversion=='p',precision_set,precision,
conversion=='p',0,0);
} else writer.Failed=1;
}
va_end(arguments);
if(capacity)destination[writer.Length<capacity?writer.Length:capacity-1]=0;
if(writer.Failed||writer.Length>(usize)0x7fffffff)return -1;
return (int)writer.Length;
}
+11
View File
@@ -7,7 +7,18 @@ 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);
void *bob64_memchr(const void *memory,int value,usize length);
usize bob64_strlen(const char *text);
usize bob64_strnlen(const char *text,usize limit);
int bob64_strcmp(const char *left,const char *right);
int bob64_strncmp(const char *left,const char *right,usize limit);
char *bob64_strcpy(char *destination,const char *source);
char *bob64_strncpy(char *destination,const char *source,usize count);
char *bob64_strcat(char *destination,const char *source);
char *bob64_strncat(char *destination,const char *source,usize count);
char *bob64_strchr(const char *text,int character);
char *bob64_strrchr(const char *text,int character);
char *bob64_strstr(const char *text,const char *needle);
int bob64_snprintf(char *destination,usize capacity,const char *format,...);
#endif
+91 -25
View File
@@ -1,11 +1,38 @@
#include "mouse.h"
static BOB64_MOUSE_STATE mouse_state;
static u8 mouse_ps2_buttons;
static u8 mouse_usb_buttons[BOB64_MOUSE_USB_DEVICE_LIMIT];
#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 int mouse_queue_event(const BOB64_EVENT *event) {
#if defined(BOB64_UEFI_ABI)
u64 flags;
#endif
u32 head,tail;
if(!event)return -1;
#if defined(BOB64_UEFI_ABI)
__asm__ volatile("pushfq; popq %0; cli":"=r"(flags)::"memory");
#endif
head=mouse_event_head;tail=mouse_event_tail;
if((u32)(head-tail)>=MOUSE_EVENT_QUEUE_SIZE) {
#if defined(BOB64_UEFI_ABI)
if(flags&(1ULL<<9))__asm__ volatile("sti":::"memory");
#endif
return -1;
}
mouse_event_queue[head&(MOUSE_EVENT_QUEUE_SIZE-1)]=*event;
__asm__ volatile("":::"memory");
mouse_event_head=head+1;
#if defined(BOB64_UEFI_ABI)
if(flags&(1ULL<<9))__asm__ volatile("sti":::"memory");
#endif
return 0;
}
static void out8(u16 port,u8 value) {
__asm__ volatile("outb %0,%1"::"a"(value),"Nd"(port));
}
@@ -64,6 +91,8 @@ int bob64_mouse_reset(BOB64_MOUSE_STATE *state,u32 width,u32 height) {
int bob64_mouse_irq_queue_init(u32 width,u32 height) {
if(bob64_mouse_reset(&mouse_state,width,height))return -1;
mouse_ps2_buttons=0;
for(u32 i=0;i<BOB64_MOUSE_USB_DEVICE_LIMIT;i++)mouse_usb_buttons[i]=0;
mouse_event_head=mouse_event_tail=0;mouse_irq_active=0;
return 0;
}
@@ -75,13 +104,8 @@ void bob64_mouse_irq_set_active(int active) {
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;
return mouse_queue_event(&event);
}
int bob64_mouse_irq_pop_event(BOB64_EVENT *event) {
@@ -106,24 +130,18 @@ 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;
static u8 mouse_combined_buttons(void) {
u8 buttons=mouse_ps2_buttons;
for(u32 i=0;i<BOB64_MOUSE_USB_DEVICE_LIMIT;i++)
buttons|=mouse_usb_buttons[i];
return buttons;
}
static int mouse_apply_report(BOB64_MOUSE_STATE *state,u8 buttons,s32 dx,
s32 dy,s32 wheel,BOB64_EVENT *event) {
s32 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;
@@ -139,11 +157,58 @@ int bob64_mouse_decode(BOB64_MOUSE_STATE *state,u8 value,BOB64_EVENT *event) {
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;
event->ScreenX=new_x;event->ScreenY=new_y;
state->Buttons=buttons;
return 0;
}
int bob64_mouse_decode(BOB64_MOUSE_STATE *state,u8 value,BOB64_EVENT *event) {
u8 flags,buttons;
s32 dx,dy,wheel=0;
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]);
if(state==&mouse_state) {
mouse_ps2_buttons=buttons;
buttons=mouse_combined_buttons();
}
return mouse_apply_report(state,buttons,dx,dy,wheel,event);
}
int bob64_mouse_usb_report_device(u32 device_index,u8 buttons,s8 delta_x,
s8 delta_y,s8 wheel) {
BOB64_EVENT event;
int result;
if(device_index>=BOB64_MOUSE_USB_DEVICE_LIMIT)return -1;
#if defined(BOB64_UEFI_ABI)
u64 flags;
__asm__ volatile("pushfq; popq %0; cli":"=r"(flags)::"memory");
#endif
mouse_usb_buttons[device_index]=(u8)(buttons&7u);
result=mouse_apply_report(&mouse_state,mouse_combined_buttons(),
(s32)delta_x,(s32)delta_y,(s32)wheel,&event);
if(!result)result=mouse_queue_event(&event);
#if defined(BOB64_UEFI_ABI)
if(flags&(1ULL<<9))__asm__ volatile("sti":::"memory");
#endif
return result;
}
int bob64_mouse_usb_report(u8 buttons,s8 delta_x,s8 delta_y,s8 wheel) {
return bob64_mouse_usb_report_device(0,buttons,delta_x,delta_y,wheel);
}
int bob64_mouse_init(u32 width,u32 height) {
u8 device_id;
if(bob64_mouse_irq_queue_init(width,height))return -1;
@@ -162,8 +227,9 @@ int bob64_mouse_init(u32 width,u32 height) {
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);
if(!event)return -1;
if(!bob64_mouse_irq_pop_event(event))return 0;
if(mouse_irq_active||!mouse_state.Enabled)return -1;
status=in8(0x64);
if(status==0xff||!(status&1)||!(status&0x20))return -1;
value=in8(0x60);
+9
View File
@@ -3,6 +3,10 @@
#include "event.h"
#define BOB64_USB_INPUT_DEVICE_LIMIT 32u
/* Kept as an alias for callers that track USB mouse button state. */
#define BOB64_MOUSE_USB_DEVICE_LIMIT BOB64_USB_INPUT_DEVICE_LIMIT
typedef struct {
u32 Width,Height;
s32 X,Y;
@@ -19,5 +23,10 @@ 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);
/* Apply a USB HID boot-mouse report to the shared pointer and wheel queue. */
int bob64_mouse_usb_report(u8 buttons,s8 delta_x,s8 delta_y,s8 wheel);
/* Per-device reports preserve button holds across multiple USB mice. */
int bob64_mouse_usb_report_device(u32 device_index,u8 buttons,s8 delta_x,
s8 delta_y,s8 wheel);
#endif
+8 -1
View File
@@ -192,7 +192,14 @@ int bob64_page_map_range(BOB64_PAGE_TABLE *table,u64 virtual_address,
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;
if(result) {
while(i) {
i--;
(void)bob64_page_unmap(table,
virtual_page+i*BOB64_PAGE_SIZE,0,0);
}
return result;
}
}
return 0;
}
+1
View File
@@ -40,6 +40,7 @@ int bob64_page_table_clone_isolated(BOB64_PAGE_TABLE *destination,
u64 isolated_base,u64 isolated_size);
int bob64_page_map(BOB64_PAGE_TABLE *table,u64 virtual_address,u64 physical_address,
u64 flags);
/* A failed range map removes every leaf mapping added by that call. */
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);
+111
View File
@@ -0,0 +1,111 @@
#include "partition.h"
#define GPT_HEADER_MIN_SIZE 92u
#define GPT_ENTRY_MIN_SIZE 128u
#define GPT_ENTRY_MAX_COUNT 128u
#define GPT_ENTRY_MAX_SIZE 512u
const u8 bob64_gpt_bob_data_type_guid[BOB64_GPT_GUID_SIZE]=
BOB64_GPT_BOB_DATA_TYPE_GUID_INITIALIZER;
/* The current kernel enumerates storage synchronously on one CPU. */
static u8 gpt_sector_workspace[BOB64_BLOCK_MAX_TRANSFER_BYTES];
static u32 read32(const u8 *bytes) {
return (u32)bytes[0]|((u32)bytes[1]<<8)|
((u32)bytes[2]<<16)|((u32)bytes[3]<<24);
}
static u64 read64(const u8 *bytes) {
return (u64)read32(bytes)|((u64)read32(bytes+4)<<32);
}
static u32 crc32_step(u32 crc,const u8 *bytes,usize length) {
for(usize i=0;i<length;i++) {
crc^=bytes[i];
for(u32 bit=0;bit<8;bit++)
crc=(crc>>1)^(0xedb88320u&-(crc&1u));
}
return crc;
}
static int guid_is_zero(const u8 *guid) {
for(u32 i=0;i<BOB64_GPT_GUID_SIZE;i++)if(guid[i])return 0;
return 1;
}
static int guid_equal(const u8 *left,const u8 *right) {
for(u32 i=0;i<BOB64_GPT_GUID_SIZE;i++)if(left[i]!=right[i])return 0;
return 1;
}
int bob64_gpt_find_partition(BOB64_BLOCK_DEVICE *device,
const u8 type_guid[BOB64_GPT_GUID_SIZE],BOB64_PARTITION *partition) {
u8 *sector=gpt_sector_workspace;
u64 current_lba,backup_lba,first_usable,last_usable,entries_lba;
u64 table_bytes,table_blocks;
u64 range_first[GPT_ENTRY_MAX_COUNT],range_last[GPT_ENTRY_MAX_COUNT];
u32 header_size,stored_header_crc,entry_count,entry_size,stored_entries_crc;
u32 crc=0xffffffffu,matches=0,range_count=0;
BOB64_PARTITION candidate={0};
if(!device||!type_guid||!partition||device->BlockSize<512u||
device->BlockSize>BOB64_BLOCK_MAX_TRANSFER_BYTES)return -1;
if(bob64_block_read(device,1,1,sector))return -2;
if(sector[0]!='E'||sector[1]!='F'||sector[2]!='I'||sector[3]!=' '||
sector[4]!='P'||sector[5]!='A'||sector[6]!='R'||sector[7]!='T')return 1;
if(read32(sector+8)<0x00010000u)return -3;
header_size=read32(sector+12);
if(header_size<GPT_HEADER_MIN_SIZE||header_size>device->BlockSize||
read32(sector+20)!=0)return -4;
stored_header_crc=read32(sector+16);
sector[16]=sector[17]=sector[18]=sector[19]=0;
crc=crc32_step(0xffffffffu,sector,header_size)^0xffffffffu;
sector[16]=(u8)stored_header_crc;sector[17]=(u8)(stored_header_crc>>8);
sector[18]=(u8)(stored_header_crc>>16);sector[19]=(u8)(stored_header_crc>>24);
if(crc!=stored_header_crc)return -5;
current_lba=read64(sector+24);backup_lba=read64(sector+32);
first_usable=read64(sector+40);last_usable=read64(sector+48);
entries_lba=read64(sector+72);entry_count=read32(sector+80);
entry_size=read32(sector+84);stored_entries_crc=read32(sector+88);
if(current_lba!=1||backup_lba>=device->BlockCount||backup_lba<=last_usable||
first_usable<2||first_usable>last_usable||last_usable>=device->BlockCount||
entries_lba<2||!entry_count||entry_count>GPT_ENTRY_MAX_COUNT||
entry_size<GPT_ENTRY_MIN_SIZE||entry_size>GPT_ENTRY_MAX_SIZE||
entry_size>device->BlockSize||device->BlockSize%entry_size)return -6;
if((u64)entry_count>(~(u64)0)/entry_size)return -7;
table_bytes=(u64)entry_count*entry_size;
table_blocks=(table_bytes+device->BlockSize-1u)/device->BlockSize;
if(entries_lba>=device->BlockCount||table_blocks>device->BlockCount-entries_lba||
entries_lba+table_blocks>first_usable)return -8;
crc=0xffffffffu;
for(u64 block=0;block<table_blocks;block++) {
u64 lba=entries_lba+block;
usize valid=(usize)(table_bytes-block*(u64)device->BlockSize);
if(valid>device->BlockSize)valid=device->BlockSize;
if(bob64_block_read(device,lba,1,sector))return -9;
crc=crc32_step(crc,sector,valid);
for(usize offset=0;offset+entry_size<=valid;offset+=entry_size) {
const u8 *entry=sector+offset;
if(guid_is_zero(entry))continue;
u64 first=read64(entry+32),last=read64(entry+40);
if(first<first_usable||first>last||last>last_usable)return -10;
if(guid_is_zero(entry+16))return -12;
for(u32 previous=0;previous<range_count;previous++)
if(first<=range_last[previous]&&last>=range_first[previous])
return -15;
range_first[range_count]=first;range_last[range_count]=last;
range_count++;
if(!guid_equal(entry,type_guid))continue;
if(matches++)return -11;
candidate.FirstLba=first;candidate.BlockCount=last-first+1u;
for(u32 i=0;i<BOB64_GPT_GUID_SIZE;i++) {
candidate.TypeGuid[i]=entry[i];
candidate.UniqueGuid[i]=entry[16u+i];
}
}
if(valid%entry_size)return -13;
}
if((crc^0xffffffffu)!=stored_entries_crc)return -14;
if(!matches)return 1;
*partition=candidate;
return 0;
}
+23
View File
@@ -0,0 +1,23 @@
#ifndef BOB64_PARTITION_H
#define BOB64_PARTITION_H
#include "block_device.h"
#define BOB64_GPT_GUID_SIZE 16u
#define BOB64_GPT_BOB_DATA_TYPE_GUID_INITIALIZER \
{0x64,0x62,0x61,0x7b,0x30,0x30,0x34,0x30, \
0x9a,0x21,0x42,0x4f,0x42,0x36,0x34,0x01}
typedef struct {
u64 FirstLba,BlockCount;
u8 TypeGuid[BOB64_GPT_GUID_SIZE];
u8 UniqueGuid[BOB64_GPT_GUID_SIZE];
} BOB64_PARTITION;
extern const u8 bob64_gpt_bob_data_type_guid[BOB64_GPT_GUID_SIZE];
/* Returns 0 when found, 1 when absent, and a negative value for invalid GPT. */
int bob64_gpt_find_partition(BOB64_BLOCK_DEVICE *device,
const u8 type_guid[BOB64_GPT_GUID_SIZE],BOB64_PARTITION *partition);
#endif
+180
View File
@@ -0,0 +1,180 @@
#include "pci.h"
#define PCI_CONFIG_ADDRESS 0x0cf8u
#define PCI_CONFIG_DATA 0x0cfcu
#define PCI_DEVICE_LIMIT 32u
#define PCI_FUNCTION_LIMIT 8u
static void pci_out32(u16 port,u32 value) {
__asm__ volatile("outl %0,%1"::"a"(value),"Nd"(port));
}
static u32 pci_in32(u16 port) {
u32 value;
__asm__ volatile("inl %1,%0":"=a"(value):"Nd"(port));
return value;
}
static void pci_out16(u16 port,u16 value) {
__asm__ volatile("outw %0,%1"::"a"(value),"Nd"(port));
}
int bob64_pci_read_config32(u8 bus,u8 device,u8 function,u8 offset,
u32 *value) {
u32 address;
if(!value||device>=PCI_DEVICE_LIMIT||function>=PCI_FUNCTION_LIMIT||
(offset&3u))return -1;
address=0x80000000u|((u32)bus<<16)|((u32)device<<11)|
((u32)function<<8)|offset;
pci_out32(PCI_CONFIG_ADDRESS,address);
*value=pci_in32(PCI_CONFIG_DATA);
return 0;
}
static int pci_visit_function(BOB64_PCI_READ_CONFIG read_config,
void *read_context,u8 bus,u8 device,u8 function,
BOB64_PCI_DEVICE_VISITOR visit,void *visit_context,
BOB64_PCI_DEVICE *result) {
u32 id,class_revision,header,bars[6];
if(read_config(read_context,bus,device,function,0,&id))return -2;
if((u16)id==0xffffu)return -1;
if(read_config(read_context,bus,device,function,8,&class_revision)||
read_config(read_context,bus,device,function,0x0c,&header))return -2;
result->Bus=bus;result->Device=device;result->Function=function;
result->VendorId=(u16)id;result->DeviceId=(u16)(id>>16);
result->Revision=(u8)class_revision;
result->ProgrammingInterface=(u8)(class_revision>>8);
result->Subclass=(u8)(class_revision>>16);
result->ClassCode=(u8)(class_revision>>24);
result->HeaderType=(u8)(header>>16)&0x7fu;
for(u32 i=0;i<6;i++) {
result->Bar[i]=0;result->BarValid[i]=0;result->BarIsIo[i]=0;
bars[i]=0;
}
if(result->HeaderType==0) {
for(u32 i=0;i<6;i++)
if(read_config(read_context,bus,device,function,
(u8)(0x10+i*4),&bars[i]))return -2;
for(u32 i=0;i<6;i++) {
u32 raw=bars[i];
if(raw==0||raw==0xffffffffu)continue;
result->BarValid[i]=1;
if(raw&1u) {
result->BarIsIo[i]=1;
result->Bar[i]=(u64)(raw&~3u);
} else if(((raw>>1)&3u)==2u) {
u32 upper;
if(i==5||read_config(read_context,bus,device,function,
(u8)(0x10+(i+1)*4),&upper))return -2;
result->Bar[i]=((u64)upper<<32)|(u64)(raw&~15u);
result->BarValid[i+1]=0;
i++;
} else result->Bar[i]=(u64)(raw&~15u);
}
}
if(visit)visit(visit_context,result);
return 0;
}
int bob64_pci_enumerate(BOB64_PCI_READ_CONFIG read_config,void *read_context,
BOB64_PCI_DEVICE_VISITOR visit,void *visit_context,
u32 *device_count) {
u8 buses[256]={0};
u8 bus_order[256];
u32 bus_count=1,processed=0,count=0;
if(!read_config||!device_count)return -1;
bus_order[0]=0;buses[0]=1;
while(processed<bus_count) {
u8 bus=bus_order[processed++];
for(u32 dev=0;dev<PCI_DEVICE_LIMIT;dev++) {
u32 id,header;
if(read_config(read_context,bus,(u8)dev,0,0,&id))return -2;
if((u16)id==0xffffu)continue;
if(read_config(read_context,bus,(u8)dev,0,0x0c,&header))return -2;
u32 functions=((header>>16)&0x80u)?PCI_FUNCTION_LIMIT:1u;
for(u32 fn=0;fn<functions;fn++) {
BOB64_PCI_DEVICE found;
int status=pci_visit_function(read_config,read_context,bus,
(u8)dev,(u8)fn,visit,visit_context,&found);
if(status==-1)continue;
if(status)return -2;
if(count==0xffffffffu)return -3;
count++;
if(found.ClassCode==0x06&&found.Subclass==0x04) {
u32 buses_value;
if(read_config(read_context,bus,(u8)dev,(u8)fn,
0x18,&buses_value))return -2;
u8 secondary=(u8)(buses_value>>8);
if(secondary&&!buses[secondary]) {
buses[secondary]=1;bus_order[bus_count++]=secondary;
}
}
}
}
}
*device_count=count;
return 0;
}
int bob64_pci_is_usb_controller(const BOB64_PCI_DEVICE *device) {
return device&&device->ClassCode==0x0c&&device->Subclass==0x03;
}
int bob64_pci_is_xhci_controller(const BOB64_PCI_DEVICE *device) {
return bob64_pci_is_usb_controller(device)&&
device->ProgrammingInterface==0x30;
}
int bob64_pci_enable_memory(const BOB64_PCI_DEVICE *device) {
u32 address,command_status;
u16 command;
if(!device||device->Device>=PCI_DEVICE_LIMIT||
device->Function>=PCI_FUNCTION_LIMIT)return -1;
if(bob64_pci_read_config32(device->Bus,device->Device,device->Function,
4,&command_status))return -1;
command=(u16)command_status;
if(command&2u)return 0;
address=0x80000000u|((u32)device->Bus<<16)|
((u32)device->Device<<11)|((u32)device->Function<<8)|4u;
pci_out32(PCI_CONFIG_ADDRESS,address);
/* A 16-bit write avoids clearing write-one-to-clear status bits. */
pci_out16(PCI_CONFIG_DATA,command|2u);
return 0;
}
static u32 xhci_read32(const volatile u8 *bytes,usize offset) {
const volatile u32 *registers=(const volatile u32 *)(const volatile void *)bytes;
return registers[offset/sizeof(u32)];
}
int bob64_xhci_parse_capabilities(const volatile void *registers,
usize mapped_size,BOB64_XHCI_CAPABILITIES *capabilities) {
const volatile u8 *bytes=(const volatile u8 *)registers;
u32 structural,doorbell,runtime,hcs_parameters2;
if(!bytes||!capabilities||mapped_size<0x20||
((uintptr_t)registers&(sizeof(u32)-1)))return -1;
u32 capability_header=xhci_read32(bytes,0);
capabilities->CapabilityLength=(u8)capability_header;
capabilities->Version=(u16)(capability_header>>16);
structural=xhci_read32(bytes,4);
capabilities->MaxSlots=(u8)structural;
capabilities->MaxInterrupters=(u16)((structural>>8)&0x7ffu);
capabilities->MaxPorts=(u8)(structural>>24);
hcs_parameters2=xhci_read32(bytes,0x08);
capabilities->HcsParameters2=hcs_parameters2;
capabilities->MaxScratchpadBuffers=(u16)(
(((hcs_parameters2>>27)&0x1fu)<<5)|((hcs_parameters2>>21)&0x1fu));
capabilities->HccParameters1=xhci_read32(bytes,0x10);
doorbell=xhci_read32(bytes,0x14);
runtime=xhci_read32(bytes,0x18);
capabilities->DoorbellOffset=doorbell&~3u;
capabilities->RuntimeOffset=runtime&~31u;
if(capabilities->CapabilityLength<0x20||
capabilities->CapabilityLength>mapped_size||
capabilities->Version<0x0100||!capabilities->MaxSlots||
!capabilities->MaxInterrupters||!capabilities->MaxPorts||
capabilities->DoorbellOffset<capabilities->CapabilityLength||
capabilities->RuntimeOffset<capabilities->CapabilityLength)
return -1;
return 0;
}
+38
View File
@@ -0,0 +1,38 @@
#ifndef BOB64_PCI_H
#define BOB64_PCI_H
#include "types.h"
typedef struct {
u8 Bus,Device,Function;
u8 Revision,ProgrammingInterface,Subclass,ClassCode,HeaderType;
u16 VendorId,DeviceId;
u64 Bar[6];
u8 BarValid[6],BarIsIo[6];
} BOB64_PCI_DEVICE;
typedef struct {
u8 CapabilityLength,MaxSlots,MaxPorts;
u16 Version,MaxInterrupters,MaxScratchpadBuffers;
u32 DoorbellOffset,RuntimeOffset,HccParameters1;
u32 HcsParameters2;
} BOB64_XHCI_CAPABILITIES;
typedef int (*BOB64_PCI_READ_CONFIG)(void *context,u8 bus,u8 device,
u8 function,u8 offset,u32 *value);
typedef void (*BOB64_PCI_DEVICE_VISITOR)(void *context,
const BOB64_PCI_DEVICE *device);
/* Enumerates bus 0 and the secondary buses of PCI-to-PCI bridges it finds. */
int bob64_pci_enumerate(BOB64_PCI_READ_CONFIG read_config,void *read_context,
BOB64_PCI_DEVICE_VISITOR visit,void *visit_context,
u32 *device_count);
int bob64_pci_is_usb_controller(const BOB64_PCI_DEVICE *device);
int bob64_pci_is_xhci_controller(const BOB64_PCI_DEVICE *device);
int bob64_pci_enable_memory(const BOB64_PCI_DEVICE *device);
int bob64_xhci_parse_capabilities(const volatile void *registers,
usize mapped_size,BOB64_XHCI_CAPABILITIES *capabilities);
int bob64_pci_read_config32(u8 bus,u8 device,u8 function,u8 offset,
u32 *value);
#endif
+21 -7
View File
@@ -81,6 +81,17 @@ static void run_file_command(BOB64_SHELL *shell,char *arguments) {
print_hex64(shell,(u64)status);output(shell,"\r\n");
}
static void show_font_test(BOB64_SHELL *shell) {
if(shell->Clear)shell->Clear(shell->Context);
output(shell,"ABCDEFGHIJKLMNOPQRSTUVWXYZ\r\n");
output(shell,"abcdefghijklmnopqrstuvwxyz\r\n");
output(shell,"0123456789\r\n\r\n");
output(shell,"0 O\r\n1 l I\r\n5 S\r\n8 B\r\n\r\n");
output(shell,"[] {} () <> / \\ | _ - + = : ; , . ! ?\r\n");
output(shell,"bob64 kernel shell\r\n");
output(shell,"The quick brown fox jumps over the lazy dog.\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;
@@ -227,7 +238,8 @@ static int completion_add_file(void *context,const char *name,usize length) {
static void shell_complete(BOB64_SHELL *shell) {
static const char *commands[]={"help","clear","mem","heap","version",
"save","restore","ls","cat","write","rm","run","cc","echo"};
"save","restore","ls","cat","write","rm","run","cc","echo",
"fonttest"};
BOB64_SHELL_COMPLETIONS matches={0};
const char *prefix=shell->Line;
usize prefix_length=shell->Length;
@@ -333,8 +345,9 @@ static void execute(BOB64_SHELL *shell) {
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,"Up/Down command history; Tab completes commands and files\r\n");
output(shell,"save checkpoint files in RAM and firmware storage\r\n");
output(shell,"restore restore firmware or RAM checkpoint\r\n");
output(shell,"save checkpoint files in RAM and persistent storage\r\n");
output(shell,"restore restore persistent or RAM checkpoint\r\n");
output(shell,"fonttest show the printable ASCII font sample\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);
@@ -345,6 +358,7 @@ static void execute(BOB64_SHELL *shell) {
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,"fonttest"))show_font_test(shell);
else if(equals(line,"save")) {
usize size,written;
if(bob64_fs_snapshot_size(shell->Filesystem,&size)) {
@@ -362,17 +376,17 @@ static void execute(BOB64_SHELL *shell) {
shell->Snapshot=snapshot;shell->SnapshotSize=written;
if(shell->SnapshotSave&&
!shell->SnapshotSave(shell->SnapshotContext,snapshot,written))
output(shell,"saved B64S v1 checkpoint to firmware storage and RAM\r\n");
else output(shell,"saved B64S v1 in RAM; firmware save failed\r\n");
output(shell,"saved B64S v1 checkpoint to persistent storage and RAM\r\n");
else output(shell,"saved B64S v1 in RAM; persistent save failed\r\n");
} else if(equals(line,"restore")) {
if(shell->SnapshotRestore) {
int persistent_result=shell->SnapshotRestore(shell->SnapshotContext,
shell->Filesystem);
if(!persistent_result) {
output(shell,"restored B64S v1 from firmware storage\r\n");return;
output(shell,"restored B64S v1 from persistent storage\r\n");return;
}
if(persistent_result<0) {
output(shell,"firmware snapshot invalid; files unchanged\r\n");return;
output(shell,"persistent snapshot invalid; files unchanged\r\n");return;
}
}
if(!shell->Snapshot||bob64_fs_snapshot_restore(shell->Filesystem,
+1
View File
@@ -607,6 +607,7 @@ u64 BOB64_MS_ABI bob64_syscall_dispatch(BOB64_INTERRUPT_FRAME *frame) {
if(frame->RAX==BOB64_SYSCALL_SEEK_HANDLE) {
BOB64_SYSCALL_HANDLE *handle=find_handle(frame->RCX);
if(!handle)frame->RAX=(u64)-9;
else if(frame->RDX>0x7fffffffffffffffULL)frame->RAX=(u64)-22;
else {handle->Position=frame->RDX;frame->RAX=handle->Position;}
return 0;
}
+323
View File
@@ -0,0 +1,323 @@
#include "usb.h"
static u16 usb_read_le16(const u8 *bytes) {
return (u16)(bytes[0]|((u16)bytes[1]<<8));
}
static u32 usb_read_le32(const u8 *bytes) {
return (u32)bytes[0]|((u32)bytes[1]<<8)|((u32)bytes[2]<<16)|
((u32)bytes[3]<<24);
}
static void usb_write_le32(u8 *bytes,u32 value) {
bytes[0]=(u8)value;bytes[1]=(u8)(value>>8);
bytes[2]=(u8)(value>>16);bytes[3]=(u8)(value>>24);
}
static u32 usb_read_be32(const u8 *bytes) {
return ((u32)bytes[0]<<24)|((u32)bytes[1]<<16)|
((u32)bytes[2]<<8)|bytes[3];
}
static u64 usb_read_be64(const u8 *bytes) {
return ((u64)usb_read_be32(bytes)<<32)|usb_read_be32(bytes+4);
}
static void usb_write_be32(u8 *bytes,u32 value) {
bytes[0]=(u8)(value>>24);bytes[1]=(u8)(value>>16);
bytes[2]=(u8)(value>>8);bytes[3]=(u8)value;
}
static void usb_write_be64(u8 *bytes,u64 value) {
usb_write_be32(bytes,(u32)(value>>32));
usb_write_be32(bytes+4,(u32)value);
}
int bob64_scsi_build_read_write_cdb(u64 lba,u32 blocks,int write,
u8 cdb[16],u8 *cdb_length) {
if(!cdb||!cdb_length||!blocks||(write!=0&&write!=1)||
(u64)blocks-1u>0xffffffffffffffffULL-lba)return -1;
for(u32 i=0;i<16;i++)cdb[i]=0;
if(lba<=0xffffffffULL&&blocks<=0xffffu&&
(u64)blocks<=0x100000000ULL-lba) {
cdb[0]=write?0x2a:0x28;
usb_write_be32(cdb+2,(u32)lba);
cdb[7]=(u8)(blocks>>8);cdb[8]=(u8)blocks;
*cdb_length=10;
} else {
cdb[0]=write?0x8a:0x88;
usb_write_be64(cdb+2,lba);
usb_write_be32(cdb+10,blocks);
*cdb_length=16;
}
return 0;
}
int bob64_scsi_build_read_capacity16_cdb(u8 cdb[16]) {
if(!cdb)return -1;
for(u32 i=0;i<16;i++)cdb[i]=0;
cdb[0]=0x9e;cdb[1]=0x10;
usb_write_be32(cdb+10,32);
return 0;
}
int bob64_scsi_parse_read_capacity10(const void *response,usize length,
u64 *block_count,u32 *block_size,int *needs_capacity16) {
const u8 *bytes=(const u8 *)response;
if(!bytes||length<8||!block_count||!block_size||!needs_capacity16)
return -1;
u32 last=usb_read_be32(bytes),size=usb_read_be32(bytes+4);
if(!size)return -1;
*block_size=size;
*needs_capacity16=last==0xffffffffu;
*block_count=*needs_capacity16?0:(u64)last+1u;
return 0;
}
int bob64_scsi_parse_read_capacity16(const void *response,usize length,
u64 *block_count,u32 *block_size) {
const u8 *bytes=(const u8 *)response;
if(!bytes||length<32||!block_count||!block_size)return -1;
u64 last=usb_read_be64(bytes);
u32 size=usb_read_be32(bytes+8);
if(last==0xffffffffffffffffULL||!size)return -1;
*block_count=last+1u;*block_size=size;
return 0;
}
u64 bob64_usb_control_setup(u8 request_type,u8 request,u16 value,u16 index,
u16 length) {
return (u64)request_type|((u64)request<<8)|((u64)value<<16)|
((u64)index<<32)|((u64)length<<48);
}
static int usb_find_hid_boot_device(const void *configuration,usize length,
u8 protocol,u16 minimum_packet,BOB64_USB_HID_BOOT_DEVICE *device) {
const u8 *bytes=(const u8 *)configuration;
usize total,offset;
int matching_interface=0;
BOB64_USB_HID_BOOT_DEVICE candidate={0};
if(!bytes||!device||length<9||bytes[0]<9||bytes[1]!=2)return -1;
total=usb_read_le16(bytes+2);
if(total<bytes[0]||total>length)return -1;
candidate.ConfigurationValue=bytes[5];
for(offset=bytes[0];offset<total;) {
u8 descriptor_length,descriptor_type;
if(total-offset<2)return -1;
descriptor_length=bytes[offset];
descriptor_type=bytes[offset+1];
if(descriptor_length<2||descriptor_length>total-offset)return -1;
if(descriptor_type==4) {
matching_interface=descriptor_length>=9&&
bytes[offset+3]==0&&bytes[offset+5]==3&&
bytes[offset+6]==1&&bytes[offset+7]==protocol;
if(matching_interface) {
candidate.InterfaceNumber=bytes[offset+2];
candidate.AlternateSetting=bytes[offset+3];
candidate.InterfaceProtocol=bytes[offset+7];
}
} else if(descriptor_type==5&&matching_interface) {
u8 address,attributes;
u16 packet_size;
if(descriptor_length<7)return -1;
address=bytes[offset+2];
attributes=bytes[offset+3];
packet_size=(u16)(usb_read_le16(bytes+offset+4)&0x07ffu);
if((address&0x80u)&&(address&0x0fu)&&
(attributes&3u)==3u&&packet_size>=minimum_packet) {
candidate.EndpointAddress=address;
candidate.EndpointAttributes=attributes;
candidate.EndpointMaxPacketSize=packet_size;
candidate.EndpointInterval=bytes[offset+6];
*device=candidate;
return 0;
}
}
offset+=descriptor_length;
}
return 1;
}
int bob64_usb_find_hid_boot_keyboard(const void *configuration,usize length,
BOB64_USB_HID_BOOT_KEYBOARD *keyboard) {
return usb_find_hid_boot_device(configuration,length,1,8,keyboard);
}
int bob64_usb_find_hid_boot_mouse(const void *configuration,usize length,
BOB64_USB_HID_BOOT_DEVICE *mouse) {
return usb_find_hid_boot_device(configuration,length,2,3,mouse);
}
int bob64_usb_find_mass_storage(const void *configuration,usize length,
BOB64_USB_MASS_STORAGE *storage) {
const u8 *bytes=(const u8 *)configuration;
BOB64_USB_MASS_STORAGE candidate={0};
usize total,offset;
int matching_interface=0;
if(!bytes||!storage||length<9||bytes[0]<9||bytes[1]!=2)return -1;
total=usb_read_le16(bytes+2);
if(total<bytes[0]||total>length)return -1;
candidate.ConfigurationValue=bytes[5];
for(offset=bytes[0];offset<total;) {
u8 descriptor_length,descriptor_type;
if(total-offset<2)return -1;
descriptor_length=bytes[offset];descriptor_type=bytes[offset+1];
if(descriptor_length<2||descriptor_length>total-offset)return -1;
if(descriptor_type==4) {
if(matching_interface&&candidate.BulkInEndpoint&&
candidate.BulkOutEndpoint) {
*storage=candidate;
return 0;
}
matching_interface=descriptor_length>=9&&
bytes[offset+5]==8&&bytes[offset+6]==6&&
bytes[offset+7]==0x50;
candidate.BulkInEndpoint=0;
candidate.BulkOutEndpoint=0;
candidate.BulkInMaxPacketSize=0;
candidate.BulkOutMaxPacketSize=0;
if(matching_interface) {
candidate.InterfaceNumber=bytes[offset+2];
candidate.AlternateSetting=bytes[offset+3];
}
} else if(descriptor_type==5&&matching_interface) {
u8 address,attributes;
u16 packet_size;
if(descriptor_length<7)return -1;
address=bytes[offset+2];attributes=bytes[offset+3];
packet_size=(u16)(usb_read_le16(bytes+offset+4)&0x07ffu);
if(!(address&0x70u)&&(address&0x0fu)!=0&&
(attributes&3u)==2u&&packet_size) {
if(address&0x80u) {
candidate.BulkInEndpoint=address;
candidate.BulkInMaxPacketSize=packet_size;
} else {
candidate.BulkOutEndpoint=address;
candidate.BulkOutMaxPacketSize=packet_size;
}
}
}
offset+=descriptor_length;
}
if(matching_interface&&candidate.BulkInEndpoint&&candidate.BulkOutEndpoint) {
*storage=candidate;
return 0;
}
return 1;
}
int bob64_usb_msc_build_cbw(void *buffer,usize capacity,u32 tag,
u32 transfer_length,int device_to_host,u8 lun,const void *cdb,
u8 cdb_length) {
u8 *bytes=(u8 *)buffer;
const u8 *command=(const u8 *)cdb;
if(!bytes||capacity<BOB64_USB_MSC_CBW_SIZE||!command||
!cdb_length||cdb_length>16||lun>15||
(device_to_host!=0&&device_to_host!=1))return -1;
for(usize i=0;i<BOB64_USB_MSC_CBW_SIZE;i++)bytes[i]=0;
usb_write_le32(bytes,0x43425355u);
usb_write_le32(bytes+4,tag);
usb_write_le32(bytes+8,transfer_length);
bytes[12]=device_to_host?0x80u:0;
bytes[13]=lun;
bytes[14]=cdb_length;
for(u8 i=0;i<cdb_length;i++)bytes[15u+i]=command[i];
return 0;
}
int bob64_usb_msc_parse_csw(const void *buffer,usize length,u32 expected_tag,
u32 expected_transfer_length,u32 *residue,u8 *status) {
const u8 *bytes=(const u8 *)buffer;
u32 parsed_tag,parsed_residue;
u8 parsed_status;
if(!bytes||length<BOB64_USB_MSC_CSW_SIZE||!residue||!status)return -1;
if(usb_read_le32(bytes)!=0x53425355u)return -1;
parsed_tag=usb_read_le32(bytes+4);
parsed_residue=usb_read_le32(bytes+8);
parsed_status=bytes[12];
if(parsed_tag!=expected_tag||parsed_residue>expected_transfer_length||
parsed_status>2u)return -1;
*residue=parsed_residue;
*status=parsed_status;
return 0;
}
int bob64_usb_parse_hub_descriptor(const void *descriptor,usize length,
BOB64_USB_HUB_DESCRIPTOR *hub) {
const u8 *bytes=(const u8 *)descriptor;
BOB64_USB_HUB_DESCRIPTOR candidate={0};
usize removable_bytes,power_mask_bytes,required;
if(!bytes||!hub||length<7||bytes[0]<7||bytes[1]!=0x29||
bytes[0]>length)return -1;
candidate.PortCount=bytes[2];
if(!candidate.PortCount||candidate.PortCount>BOB64_USB_HUB_MAX_PORTS)
return -1;
removable_bytes=((usize)candidate.PortCount+1u+7u)/8u;
power_mask_bytes=((usize)candidate.PortCount+7u)/8u;
required=7u+removable_bytes+power_mask_bytes;
if(bytes[0]<required)return -1;
candidate.Characteristics=usb_read_le16(bytes+3);
candidate.PowerOnToGood=bytes[5];
candidate.ControllerCurrent=bytes[6];
for(usize i=0;i<removable_bytes;i++)
candidate.DeviceRemovable[i]=bytes[7u+i];
for(usize i=0;i<power_mask_bytes;i++)
candidate.PortPowerControlMask[i]=bytes[7u+removable_bytes+i];
*hub=candidate;
return 0;
}
int bob64_usb_find_hub_interface(const void *configuration,usize length,
BOB64_USB_HUB_INTERFACE *hub) {
const u8 *bytes=(const u8 *)configuration;
BOB64_USB_HUB_INTERFACE candidate={0};
usize total,offset;
int matching_interface=0;
if(!bytes||!hub||length<9||bytes[0]<9||bytes[1]!=2)return -1;
total=usb_read_le16(bytes+2);
if(total<bytes[0]||total>length)return -1;
candidate.ConfigurationValue=bytes[5];
for(offset=bytes[0];offset<total;) {
u8 descriptor_length,descriptor_type;
if(total-offset<2)return -1;
descriptor_length=bytes[offset];descriptor_type=bytes[offset+1];
if(descriptor_length<2||descriptor_length>total-offset)return -1;
if(descriptor_type==4) {
matching_interface=descriptor_length>=9&&
bytes[offset+5]==9&&bytes[offset+6]==0;
if(matching_interface) {
candidate.InterfaceNumber=bytes[offset+2];
candidate.AlternateSetting=bytes[offset+3];
}
} else if(descriptor_type==5&&matching_interface) {
u8 address,attributes;
u16 packet_size;
if(descriptor_length<7)return -1;
address=bytes[offset+2];attributes=bytes[offset+3];
packet_size=(u16)(usb_read_le16(bytes+offset+4)&0x07ffu);
if((address&0x80u)&&(address&0x0fu)&&
(attributes&3u)==3u&&packet_size) {
candidate.EndpointAddress=address;
candidate.EndpointAttributes=attributes;
candidate.EndpointMaxPacketSize=packet_size;
candidate.EndpointInterval=bytes[offset+6];
*hub=candidate;
return 0;
}
}
offset+=descriptor_length;
}
return 1;
}
int bob64_usb_route_string_append(u32 route,u8 depth,u8 port,u32 *result) {
u32 preceding_mask,shift;
u8 route_port;
if(!result||!port||depth>=5)return -1;
shift=(u32)depth*4u;
preceding_mask=shift?(1u<<shift)-1u:0;
if((route&~preceding_mask)||route>0x000fffffu)return -1;
route_port=port>14u?15u:port;
*result=route|((u32)route_port<<shift);
return 0;
}
+82
View File
@@ -0,0 +1,82 @@
#ifndef BOB64_USB_H
#define BOB64_USB_H
#include "types.h"
typedef struct {
u8 ConfigurationValue;
u8 InterfaceNumber,AlternateSetting;
u8 InterfaceProtocol;
u8 EndpointAddress,EndpointAttributes,EndpointInterval;
u16 EndpointMaxPacketSize;
} BOB64_USB_HID_BOOT_DEVICE;
typedef BOB64_USB_HID_BOOT_DEVICE BOB64_USB_HID_BOOT_KEYBOARD;
/* USB Mass Storage, SCSI transparent command set, Bulk-Only Transport. */
typedef struct {
u8 ConfigurationValue;
u8 InterfaceNumber,AlternateSetting;
u8 BulkInEndpoint,BulkOutEndpoint;
u16 BulkInMaxPacketSize,BulkOutMaxPacketSize;
} BOB64_USB_MASS_STORAGE;
#define BOB64_USB_HUB_MAX_PORTS 127u
#define BOB64_USB_HUB_BITMAP_BYTES 16u
#define BOB64_USB_MSC_CBW_SIZE 31u
#define BOB64_USB_MSC_CSW_SIZE 13u
/* Parsed USB 2 hub descriptor, including port zero in the bitmap. */
typedef struct {
u8 PortCount;
u16 Characteristics;
u8 PowerOnToGood;
u8 ControllerCurrent;
u8 DeviceRemovable[BOB64_USB_HUB_BITMAP_BYTES];
u8 PortPowerControlMask[BOB64_USB_HUB_BITMAP_BYTES];
} BOB64_USB_HUB_DESCRIPTOR;
typedef struct {
u8 ConfigurationValue;
u8 InterfaceNumber,AlternateSetting;
u8 EndpointAddress,EndpointAttributes,EndpointInterval;
u16 EndpointMaxPacketSize;
} BOB64_USB_HUB_INTERFACE;
/* Packs the eight-byte USB setup packet as a little-endian u64 TRB value. */
u64 bob64_usb_control_setup(u8 request_type,u8 request,u16 value,u16 index,
u16 length);
/* Finds the first HID boot-keyboard interface and interrupt-IN endpoint. */
int bob64_usb_find_hid_boot_keyboard(const void *configuration,usize length,
BOB64_USB_HID_BOOT_KEYBOARD *keyboard);
/* Finds a boot-protocol HID mouse interface with an interrupt-IN endpoint. */
int bob64_usb_find_hid_boot_mouse(const void *configuration,usize length,
BOB64_USB_HID_BOOT_DEVICE *mouse);
/* Finds a SCSI-transparent Bulk-Only Transport interface with both bulk endpoints. */
int bob64_usb_find_mass_storage(const void *configuration,usize length,
BOB64_USB_MASS_STORAGE *storage);
/* Build/validate the fixed-width BOT command and status wrappers. */
int bob64_usb_msc_build_cbw(void *buffer,usize capacity,u32 tag,
u32 transfer_length,int device_to_host,u8 lun,const void *cdb,
u8 cdb_length);
int bob64_usb_msc_parse_csw(const void *buffer,usize length,u32 expected_tag,
u32 expected_transfer_length,u32 *residue,u8 *status);
/* Build SCSI disk commands, using 10-byte forms where the LBA fits. */
int bob64_scsi_build_read_write_cdb(u64 lba,u32 blocks,int write,
u8 cdb[16],u8 *cdb_length);
int bob64_scsi_build_read_capacity16_cdb(u8 cdb[16]);
int bob64_scsi_parse_read_capacity10(const void *response,usize length,
u64 *block_count,u32 *block_size,int *needs_capacity16);
int bob64_scsi_parse_read_capacity16(const void *response,usize length,
u64 *block_count,u32 *block_size);
/* Parses a USB 2 hub descriptor (type 0x29) and validates both port bitmaps. */
int bob64_usb_parse_hub_descriptor(const void *descriptor,usize length,
BOB64_USB_HUB_DESCRIPTOR *hub);
/* Finds a USB hub-class interface and its interrupt-IN status endpoint. */
int bob64_usb_find_hub_interface(const void *configuration,usize length,
BOB64_USB_HUB_INTERFACE *hub);
/* Appends a hub-port nibble to the five-level xHCI route string. */
int bob64_usb_route_string_append(u32 route,u8 depth,u8 port,u32 *result);
#endif
+89 -3
View File
@@ -18,6 +18,12 @@ typedef struct {
u8 Focused,Dirty;
} BOB64_TEXT_FIELD;
typedef struct {
u32 Selected;
s32 Pressed;
u8 Open;
} BOB64_MENU_STATE;
#define BOB64_BUTTON_LEFT 1u
static inline int bob64_rect_contains(const BOB64_RECT *rect,s32 x,s32 y) {
@@ -78,6 +84,86 @@ static inline int bob64_button_draw(BOB64_GFX *graphics,const BOB64_RECT *rect,
return 0;
}
/* A bounded popup menu. Returns the chosen item, -2 when dismissed, or -1. */
static inline int bob64_menu_event(const BOB64_RECT *rect,
const char *const *items,u32 count,u32 row_height,
BOB64_MENU_STATE *state,const BOB64_EVENT *event) {
s32 item=-1;
if(!rect||!items||!count||row_height<10||!state||!event||!state->Open)
return -1;
if(state->Selected>=count)state->Selected=0;
if(event->Type==BOB64_EVENT_KEY_DOWN) {
if(event->Character==0x1b) {
state->Open=0;state->Pressed=-1;return -2;
}
if(event->Key==(BOB64_EVENT_KEY_EXTENDED|0x48)) {
if(state->Selected)state->Selected--;
} else if(event->Key==(BOB64_EVENT_KEY_EXTENDED|0x50)) {
if(state->Selected+1<count)state->Selected++;
} else if(event->Character=='\n'||event->Character=='\r') {
u32 selected=state->Selected;
state->Open=0;state->Pressed=-1;return (int)selected;
}
return -1;
}
if(event->Type!=BOB64_EVENT_MOUSE_MOVE&&
event->Type!=BOB64_EVENT_MOUSE_BUTTON)return -1;
if(bob64_rect_contains(rect,event->X,event->Y)) {
u64 row_offset=(u64)((s64)event->Y-(s64)rect->Y);
u64 row=row_offset/row_height;
if(row<count) {state->Selected=row;item=(s32)row;}
}
if(event->Type==BOB64_EVENT_MOUSE_MOVE)return -1;
if(event->Buttons&BOB64_BUTTON_LEFT) {
state->Pressed=item;return -1;
}
if(state->Pressed>=0&&state->Pressed==item) {
s32 selected=state->Pressed;
state->Open=0;state->Pressed=-1;return selected;
}
state->Pressed=-1;
if(item<0) {state->Open=0;return -2;}
return -1;
}
static inline int bob64_menu_draw(BOB64_GFX *graphics,const BOB64_RECT *rect,
const char *const *items,u32 count,u32 row_height,
const BOB64_MENU_STATE *state) {
if(!graphics||!rect||!items||!count||row_height<10||!state||!state->Open||
count>0x7fffffffu/row_height||rect->Height<count*row_height||
rect->Width<12||rect->Width>0x7fffffffu||
rect->X>0x7fffffff-(s32)(rect->Width-1)||
rect->Y>0x7fffffff-(s32)(rect->Height-1)||
rect->X<0||rect->Y<0||
(u32)rect->X+rect->Width>graphics->Width||
(u32)rect->Y+rect->Height>graphics->Height)return -1;
bob64_gfx_fill_rect(graphics,rect->X,rect->Y,rect->Width,rect->Height,
0x0009111bu);
for(u32 i=0;i<count;i++) {
s32 y=rect->Y+(s32)(i*row_height);
usize length=0;
if(!items[i])return -1;
while(length<=(rect->Width-12)/6&&items[i][length])length++;
if(items[i][length])return -1;
if(i==state->Selected)
bob64_gfx_fill_rect(graphics,rect->X+1,y+1,rect->Width-2,
row_height-2,0x00335d8cu);
bob64_gfx_text(graphics,rect->X+6,y+(s32)(row_height-7)/2,
items[i],0x00ffffffu,1);
}
bob64_gfx_line(graphics,rect->X,rect->Y,rect->X+(s32)rect->Width-1,
rect->Y,0x007fa3c4u);
bob64_gfx_line(graphics,rect->X,rect->Y+(s32)rect->Height-1,
rect->X+(s32)rect->Width-1,
rect->Y+(s32)rect->Height-1,0x007fa3c4u);
bob64_gfx_line(graphics,rect->X,rect->Y,rect->X,
rect->Y+(s32)rect->Height-1,0x007fa3c4u);
bob64_gfx_line(graphics,rect->X+(s32)rect->Width-1,rect->Y,
rect->X+(s32)rect->Width-1,
rect->Y+(s32)rect->Height-1,0x007fa3c4u);
return 0;
}
static inline int bob64_text_field_sync(BOB64_TEXT_FIELD *field) {
usize length=0;
if(!field||!field->Buffer||!field->Capacity)return -1;
@@ -99,7 +185,7 @@ static inline void bob64_text_field_reveal(BOB64_TEXT_FIELD *field,
if(!field)return;
if(!visible_columns)visible_columns=1;
if(field->Cursor<field->Scroll)field->Scroll=field->Cursor;
else if(field->Cursor>=field->Scroll+visible_columns)
else if(field->Cursor-field->Scroll>=visible_columns)
field->Scroll=field->Cursor-visible_columns+1;
}
@@ -112,8 +198,8 @@ static inline int bob64_text_field_event(BOB64_TEXT_FIELD *field,
(event->Buttons&BOB64_BUTTON_LEFT)) {
field->Focused=(u8)bob64_rect_contains(rect,event->X,event->Y);
if(field->Focused) {
usize column=event->X>rect->X+3?
(usize)(event->X-rect->X-3)/6:0;
s64 text_offset=(s64)event->X-(s64)rect->X-3;
usize column=text_offset>0?(usize)((u64)text_offset/6):0;
field->Cursor=field->Scroll+column;
if(field->Cursor>field->Length)field->Cursor=field->Length;
return 0;
+11 -3
View File
@@ -48,6 +48,12 @@ static inline void bob64_wm_clamp(BOB64_WINDOW_MANAGER *manager,BOB64_WINDOW *wi
if(window->Y>max_y)window->Y=max_y;
}
static inline s32 bob64_wm_saturate_s32(s64 value) {
if(value<(-2147483647LL-1))return (-2147483647-1);
if(value>2147483647LL)return 2147483647;
return (s32)value;
}
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]);
@@ -254,12 +260,14 @@ static inline s64 bob64_wm_dispatch(BOB64_WINDOW_MANAGER *manager,
(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);
bob64_wm_move(manager,target,
bob64_wm_saturate_s32((s64)event->X-manager->DragOffsetX),
bob64_wm_saturate_s32((s64)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;
routed->X=bob64_wm_saturate_s32((s64)event->X-window->X);
routed->Y=bob64_wm_saturate_s32((s64)event->Y-window->Y);
}
}
if(event->Type==BOB64_EVENT_MOUSE_MOVE||event->Type==BOB64_EVENT_MOUSE_BUTTON||
+91 -17
View File
@@ -15,6 +15,34 @@ static int server_slot(const BOB64_WINDOW_SERVER *server,
return -1;
}
static void server_damage(BOB64_WINDOW_SERVER *server,s64 left,s64 top,
s64 right,s64 bottom) {
if(!server||left>=right||top>=bottom)return;
if(left<0)left=0;
if(top<0)top=0;
if(right>server->Manager.ScreenWidth)right=server->Manager.ScreenWidth;
if(bottom>server->Manager.ScreenHeight)bottom=server->Manager.ScreenHeight;
if(left>=right||top>=bottom)return;
if(!server->Damaged) {
server->DamageLeft=(u32)left;server->DamageTop=(u32)top;
server->DamageRight=(u32)right;server->DamageBottom=(u32)bottom;
server->Damaged=1;
} else {
if((u32)left<server->DamageLeft)server->DamageLeft=(u32)left;
if((u32)top<server->DamageTop)server->DamageTop=(u32)top;
if((u32)right>server->DamageRight)server->DamageRight=(u32)right;
if((u32)bottom>server->DamageBottom)server->DamageBottom=(u32)bottom;
}
}
static void server_damage_window(BOB64_WINDOW_SERVER *server,
const BOB64_WINDOW *window) {
if(!window)return;
server_damage(server,window->X,window->Y,
(s64)window->X+window->Width,
(s64)window->Y+window->Height);
}
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];
@@ -33,21 +61,25 @@ static u32 server_pixel(const BOB64_WINDOW_SERVER *server,u32 x,u32 y) {
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(!server||!server->Damaged||bob64_framebuffer_resolution(&width,&height))
return server&&!server->Damaged?0:-1;
if(width!=server->Manager.ScreenWidth||height!=server->Manager.ScreenHeight)
return -1;
for(u32 y=server->DamageTop;y<server->DamageBottom;y++) {
for(u32 x=server->DamageLeft;x<server->DamageRight;) {
u32 count=server->DamageRight-x;
if(count>sizeof(server_composite_chunk)/sizeof(server_composite_chunk[0]))
count=sizeof(server_composite_chunk)/sizeof(server_composite_chunk[0]);
for(u32 i=0;i<count;i++)
server_composite_chunk[i]=server_pixel(server,x+i,y);
if(bob64_framebuffer_write_pixels((u64)y*width+x,
server_composite_chunk,count))return -1;
x+=count;
}
if(bob64_framebuffer_write_pixels(offset,server_composite_chunk,count))return -1;
offset+=count;
}
server->Damaged=0;
server->DamageLeft=server->DamageTop=0;
server->DamageRight=server->DamageBottom=0;
return 0;
}
@@ -58,6 +90,7 @@ int bob64_window_server_init(BOB64_WINDOW_SERVER *server,BOB64_HEAP *heap,
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;
server_damage(server,0,0,screen_width,screen_height);
return server_composite(server);
}
@@ -90,6 +123,7 @@ BOB64_WINDOW_HANDLE bob64_window_server_create(BOB64_WINDOW_SERVER *server,
if(!handle||slot<0) {
bob64_heap_free(server->Heap,surface);return 0;
}
server_damage_window(server,&server->Windows[slot]);
server->Owners[slot]=owner;server->SurfaceBytes[slot]=(usize)bytes;
server->BytesAllocated+=bytes;
if(server_composite(server)) {
@@ -104,6 +138,7 @@ int bob64_window_server_destroy(BOB64_WINDOW_SERVER *server,u64 owner,
u32 *surface;
if(!server_has_owner(server,owner)||(slot=server_slot(server,handle))<0||
server->Owners[slot]!=owner)return -1;
server_damage_window(server,&server->Windows[slot]);
surface=(u32 *)server->Windows[slot].Context;
if(bob64_wm_destroy(&server->Manager,handle))return -1;
if(surface) {
@@ -118,7 +153,13 @@ 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;
!server->Windows[slot].Handle)return -1;
BOB64_WINDOW *window=&server->Windows[slot];
s32 old_x=window->X,old_y=window->Y;
if(bob64_wm_move(&server->Manager,handle,x,y))return -1;
server_damage(server,old_x,old_y,(s64)old_x+window->Width,
(s64)old_y+window->Height);
server_damage_window(server,window);
return server_composite(server);
}
@@ -127,6 +168,7 @@ int bob64_window_server_focus(BOB64_WINDOW_SERVER *server,u64 owner,
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;
server_damage_window(server,&server->Windows[slot]);
return server_composite(server);
}
@@ -142,6 +184,20 @@ int bob64_window_server_write_pixels(BOB64_WINDOW_SERVER *server,u64 owner,
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;
if(count) {
u64 last=first_pixel+(u64)count-1;
u32 first_y=(u32)(first_pixel/window->Width);
u32 last_y=(u32)(last/window->Width);
if(first_y==last_y)
server_damage(server,(s64)window->X+first_pixel%window->Width,
(s64)window->Y+first_y,
(s64)window->X+last%window->Width+1,
(s64)window->Y+first_y+1);
else
server_damage(server,window->X,(s64)window->Y+first_y,
(s64)window->X+window->Width,
(s64)window->Y+last_y+1);
}
return 0;
}
@@ -164,13 +220,31 @@ int bob64_window_server_present(BOB64_WINDOW_SERVER *server,u64 owner,
s64 bob64_window_server_route_event(BOB64_WINDOW_SERVER *server,u64 owner,
const BOB64_EVENT *event,BOB64_EVENT *routed) {
s64 target;
BOB64_WINDOW_HANDLE previous_focus;
BOB64_WINDOW *window;
s32 old_x=0,old_y=0;
int had_window=0;
if(!server_has_owner(server,owner)||!event||!routed)return -1;
previous_focus=server->Manager.Focused;
if(event->Type==BOB64_EVENT_MOUSE_MOVE||
event->Type==BOB64_EVENT_MOUSE_BUTTON||
event->Type==BOB64_EVENT_MOUSE_WHEEL) {
if(server->Manager.Dragging)target=(s64)server->Manager.Dragging;
else target=(s64)bob64_wm_hit_test(&server->Manager,event->X,event->Y);
window=bob64_wm_find(&server->Manager,(BOB64_WINDOW_HANDLE)target);
if(window) {old_x=window->X;old_y=window->Y;had_window=1;}
}
target=bob64_wm_dispatch(&server->Manager,event,routed);
if(target<0)return target;
window=bob64_wm_find(&server->Manager,(BOB64_WINDOW_HANDLE)target);
if(had_window&&window&&(old_x!=window->X||old_y!=window->Y))
server_damage(server,old_x,old_y,(s64)old_x+window->Width,
(s64)old_y+window->Height);
if(window&&previous_focus!=window->Handle)server_damage_window(server,window);
if(window&&had_window&&(old_x!=window->X||old_y!=window->Y))
server_damage_window(server,window);
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;
if(server_composite(server))return -1;
return target;
}
+2
View File
@@ -17,7 +17,9 @@ typedef struct {
usize SurfaceBytes[BOB64_WINDOW_SERVER_CAPACITY];
u64 Owner;
u64 BytesAllocated;
u32 DamageLeft,DamageTop,DamageRight,DamageBottom;
u8 Active;
u8 Damaged;
} BOB64_WINDOW_SERVER;
int bob64_window_server_init(BOB64_WINDOW_SERVER *server,BOB64_HEAP *heap,
+43
View File
@@ -0,0 +1,43 @@
#include "xhci.h"
static int xhci_wait_status(BOB64_XHCI_READ32 read_register,void *context,
u32 mask,u32 expected,u32 poll_limit,u32 *status_out) {
for(u32 i=0;i<poll_limit;i++) {
u32 status;
if(read_register(context,4,&status))return -1;
if(status_out)*status_out=status;
if((status&mask)==expected)return 0;
}
return -2;
}
int bob64_xhci_halt_reset(BOB64_XHCI_READ32 read_register,
BOB64_XHCI_WRITE32 write_register,void *context,u32 poll_limit,
u32 *final_status) {
u32 status,command;
int result;
if(!read_register||!write_register||!poll_limit)return -1;
result=xhci_wait_status(read_register,context,
BOB64_XHCI_USBSTS_NOT_READY,0,poll_limit,&status);
if(result)return result;
if(!(status&BOB64_XHCI_USBSTS_HALTED)) {
if(read_register(context,0,&command)||
write_register(context,0,command&~BOB64_XHCI_USBCMD_RUN))return -1;
result=xhci_wait_status(read_register,context,
BOB64_XHCI_USBSTS_HALTED,BOB64_XHCI_USBSTS_HALTED,
poll_limit,&status);
if(result)return result;
}
if(read_register(context,0,&command)||
write_register(context,0,command|BOB64_XHCI_USBCMD_RESET))return -1;
for(u32 i=0;i<poll_limit;i++) {
if(read_register(context,0,&command)||
read_register(context,4,&status))return -1;
if(!(command&BOB64_XHCI_USBCMD_RESET)&&
!(status&BOB64_XHCI_USBSTS_NOT_READY)) {
if(final_status)*final_status=status;
return (status&BOB64_XHCI_USBSTS_HALTED)?0:-3;
}
}
return -2;
}
+19
View File
@@ -0,0 +1,19 @@
#ifndef BOB64_XHCI_H
#define BOB64_XHCI_H
#include "types.h"
#define BOB64_XHCI_USBCMD_RUN 0x00000001u
#define BOB64_XHCI_USBCMD_RESET 0x00000002u
#define BOB64_XHCI_USBSTS_HALTED 0x00000001u
#define BOB64_XHCI_USBSTS_NOT_READY 0x00000800u
typedef int (*BOB64_XHCI_READ32)(void *context,u32 offset,u32 *value);
typedef int (*BOB64_XHCI_WRITE32)(void *context,u32 offset,u32 value);
/* Stops a running xHC if needed, requests reset, and waits for it to settle. */
int bob64_xhci_halt_reset(BOB64_XHCI_READ32 read_register,
BOB64_XHCI_WRITE32 write_register,void *context,u32 poll_limit,
u32 *final_status);
#endif
BIN
View File
Binary file not shown.
+1283 -12
View File
File diff suppressed because it is too large. Load diff
+47 -11
View File
@@ -10,6 +10,9 @@
#define BUILD_DIR "build\\"
#define BOB64_BOOT_PATH "build\\bob64\\EFI\\BOOT\\BOOTX64.EFI"
#define BOB64_HANDOFF_BOOT_PATH "build\\bob64-handoff\\EFI\\BOOT\\BOOTX64.EFI"
#define BOB64_STORAGE_TEST_BOOT_PATH "build\\bob64-handoff-storage-test\\EFI\\BOOT\\BOOTX64.EFI"
#define BOB64_STORAGE_ACTIVE_TEST_BOOT_PATH "build\\bob64-handoff-storage-active-test\\EFI\\BOOT\\BOOTX64.EFI"
#define BOB64_STORAGE64_TEST_BOOT_PATH "build\\bob64-handoff-storage64-test\\EFI\\BOOT\\BOOTX64.EFI"
#define BOB_COMMAND "bob.exe"
#define BOB32_COMMAND "bob32.exe"
#define BOB64_TEST_THREAD_FLAGS ""
@@ -18,6 +21,9 @@
#define BUILD_DIR "./build/"
#define BOB64_BOOT_PATH "build/bob64/EFI/BOOT/BOOTX64.EFI"
#define BOB64_HANDOFF_BOOT_PATH "build/bob64-handoff/EFI/BOOT/BOOTX64.EFI"
#define BOB64_STORAGE_TEST_BOOT_PATH "build/bob64-handoff-storage-test/EFI/BOOT/BOOTX64.EFI"
#define BOB64_STORAGE_ACTIVE_TEST_BOOT_PATH "build/bob64-handoff-storage-active-test/EFI/BOOT/BOOTX64.EFI"
#define BOB64_STORAGE64_TEST_BOOT_PATH "build/bob64-handoff-storage64-test/EFI/BOOT/BOOTX64.EFI"
#define BOB_COMMAND "./bob"
#define BOB32_COMMAND "./bob32"
#define BOB64_TEST_THREAD_FLAGS "-pthread "
@@ -33,10 +39,19 @@ static void ensure_directory(const char *path) {
if(mkdir(path,0777) && errno!=EEXIST){perror(path);exit(1);}
#endif
}
static void build_bob64(int handoff) {
static void build_bob64(int handoff,int storage_write_test,int active_disconnect_test,
int storage_lba64_test) {
const char *compiler=getenv("BOB64_CC");
const char *output_path=handoff?BOB64_HANDOFF_BOOT_PATH:BOB64_BOOT_PATH;
const char *handoff_define=handoff?"-DBOB64_ENABLE_HANDOFF ":"";
const char *output_path=storage_lba64_test?BOB64_STORAGE64_TEST_BOOT_PATH:
(active_disconnect_test?BOB64_STORAGE_ACTIVE_TEST_BOOT_PATH:
(storage_write_test?BOB64_STORAGE_TEST_BOOT_PATH:
(handoff?BOB64_HANDOFF_BOOT_PATH:BOB64_BOOT_PATH)));
const char *handoff_define=storage_lba64_test?
"-DBOB64_ENABLE_HANDOFF -DBOB64_STORAGE_LBA64_TEST ":
(active_disconnect_test?
"-DBOB64_ENABLE_HANDOFF -DBOB64_STORAGE_ACTIVE_DISCONNECT_TEST ":
(storage_write_test?"-DBOB64_ENABLE_HANDOFF -DBOB64_STORAGE_WRITE_TEST ":
(handoff?"-DBOB64_ENABLE_HANDOFF ":"")));
char command[2048];
ensure_directory("build");
ensure_directory("build/bob64-app");
@@ -52,10 +67,27 @@ static void build_bob64(int handoff) {
run(BUILD_DIR "bob64cc" EXE " apps/bob64_info.c build/bob64-app/info.b64e");
run(BUILD_DIR "bob64cc" EXE " apps/bob64_mouse_smoke.c build/bob64-app/mouse-smoke.b64e");
run(BUILD_DIR "bob64cc" EXE " apps/bob64_launcher.c build/bob64-app/launcher.b64e");
ensure_directory(handoff?"build/bob64-handoff":"build/bob64");
ensure_directory(storage_lba64_test?"build/bob64-handoff-storage64-test":
(active_disconnect_test?"build/bob64-handoff-storage-active-test":
(storage_write_test?"build/bob64-handoff-storage-test":
(handoff?"build/bob64-handoff":"build/bob64"))));
if(handoff) {
ensure_directory("build/bob64-handoff/EFI");
ensure_directory("build/bob64-handoff/EFI/BOOT");
const char *image_directory=storage_lba64_test?
"build/bob64-handoff-storage64-test/EFI":
(active_disconnect_test?
"build/bob64-handoff-storage-active-test/EFI":
(storage_write_test?
"build/bob64-handoff-storage-test/EFI":
"build/bob64-handoff/EFI"));
ensure_directory(image_directory);
const char *boot_directory=storage_lba64_test?
"build/bob64-handoff-storage64-test/EFI/BOOT":
(active_disconnect_test?
"build/bob64-handoff-storage-active-test/EFI/BOOT":
(storage_write_test?
"build/bob64-handoff-storage-test/EFI/BOOT":
"build/bob64-handoff/EFI/BOOT"));
ensure_directory(boot_directory);
} else {
ensure_directory("build/bob64/EFI");
ensure_directory("build/bob64/EFI/BOOT");
@@ -67,17 +99,20 @@ static void build_bob64(int handoff) {
compiler="x86_64-w64-mingw32-gcc";
#endif
}
if(snprintf(command,sizeof(command),"%s -std=c11 -O2 -Wall -Wextra -Werror -DBOB64_UEFI_ABI %s-ffreestanding -fno-stack-protector -fno-stack-check -fshort-wchar -mno-red-zone -nostdlib -Wl,--subsystem,10 -Wl,-e,efi_main -Wl,--image-base,0x100000 -Wl,--enable-reloc-section -Wl,--dynamicbase -Wl,--file-alignment,0x200 -Wl,--section-alignment,0x1000 bob64/boot.c bob64/memory.c bob64/paging.c bob64/cpu.c bob64/descriptors.c bob64/interrupts.c bob64/interrupts.S bob64/syscall.c bob64/window_server.c bob64/bootstrap.c bob64/kernel.c bob64/console.c bob64/heap.c bob64/keyboard.c bob64/mouse.c bob64/shell.c bob64/filesystem.c bob64/snapshot.c bob64/lz4.c bob64/firmware_store.c bob64/exec.c bob64/process.c bob64/compiler.c bob64/embedded_app.S bob64/handoff.S -o %s",compiler,handoff_define,output_path)>=(int)sizeof(command)) {
if(snprintf(command,sizeof(command),"%s -std=c11 -O2 -Wall -Wextra -Werror -DBOB64_UEFI_ABI %s-ffreestanding -fno-stack-protector -fno-stack-check -fshort-wchar -mno-red-zone -nostdlib -Wl,--subsystem,10 -Wl,-e,efi_main -Wl,--image-base,0x100000 -Wl,--enable-reloc-section -Wl,--dynamicbase -Wl,--file-alignment,0x200 -Wl,--section-alignment,0x1000 bob64/boot.c bob64/memory.c bob64/paging.c bob64/cpu.c bob64/descriptors.c bob64/interrupts.c bob64/interrupts.S bob64/syscall.c bob64/window_server.c bob64/bootstrap.c bob64/kernel.c bob64/console.c bob64/heap.c bob64/keyboard.c bob64/mouse.c bob64/pci.c bob64/xhci.c bob64/usb.c bob64/block_device.c bob64/partition.c bob64/disk_store.c bob64/shell.c bob64/filesystem.c bob64/snapshot.c bob64/lz4.c bob64/firmware_store.c bob64/exec.c bob64/process.c bob64/compiler.c bob64/embedded_app.S bob64/handoff.S -o %s",compiler,handoff_define,output_path)>=(int)sizeof(command)) {
fprintf(stderr,"bob64 compiler command is too long\n");exit(1);
}
run(command);
}
int main(int argc,char **argv) {
int bob64Handoff=argc==2&&(!strcmp(argv[1],"--bob64-handoff")||!strcmp(argv[1],"--bob64-handoff-test"));
int bob64StorageWriteTest=argc==2&&!strcmp(argv[1],"--bob64-handoff-storage-test");
int bob64StorageActiveTest=argc==2&&!strcmp(argv[1],"--bob64-handoff-storage-active-test");
int bob64StorageLba64Test=argc==2&&!strcmp(argv[1],"--bob64-handoff-storage64-test");
int bob64Handoff=argc==2&&(!strcmp(argv[1],"--bob64-handoff")||!strcmp(argv[1],"--bob64-handoff-test")||bob64StorageWriteTest||bob64StorageActiveTest||bob64StorageLba64Test);
int bob64Only=argc==2&&(!strcmp(argv[1],"--bob64")||!strcmp(argv[1],"--bob64-test")||bob64Handoff);
int bob64Test=argc==2&&(!strcmp(argv[1],"--bob64-test")||!strcmp(argv[1],"--bob64-handoff-test"));
if(argc>2||(argc==2&&!bob64Only&&strcmp(argv[1],"--run")&&strcmp(argv[1],"--run32")&&strcmp(argv[1],"--test"))) {
fprintf(stderr,"Usage: build [--run | --run32 | --test | --bob64 | --bob64-test | --bob64-handoff | --bob64-handoff-test] (from repository root)\n");return 1;
fprintf(stderr,"Usage: build [--run | --run32 | --test | --bob64 | --bob64-test | --bob64-handoff | --bob64-handoff-test | --bob64-handoff-storage-test | --bob64-handoff-storage-active-test | --bob64-handoff-storage64-test] (from repository root)\n");return 1;
}
#ifdef _WIN32
int directory_result=_mkdir("build");
@@ -96,9 +131,10 @@ int main(int argc,char **argv) {
fprintf(stderr,"build must be a directory\n");return 1;
}
if(bob64Only) {
build_bob64(bob64Handoff);
build_bob64(bob64Handoff,bob64StorageWriteTest,bob64StorageActiveTest,
bob64StorageLba64Test);
if(bob64Test) {
run("gcc -std=c11 -O2 -Wall -Wextra -Werror " BOB64_TEST_THREAD_FLAGS "tests/test_bob64.c bob64/libc.c bob64/compiler.c bob64/memory.c bob64/paging.c bob64/cpu.c bob64/descriptors.c bob64/interrupts.c bob64/interrupts.S bob64/syscall.c bob64/window_server.c bob64/bootstrap.c bob64/console.c bob64/lz4.c bob64/firmware_store.c bob64/heap.c bob64/keyboard.c bob64/mouse.c bob64/shell.c bob64/filesystem.c bob64/snapshot.c bob64/exec.c bob64/process.c -o build/test_bob64" EXE);
run("gcc -std=c11 -O2 -Wall -Wextra -Werror " BOB64_TEST_THREAD_FLAGS "tests/test_bob64.c bob64/libc.c bob64/compiler.c bob64/memory.c bob64/paging.c bob64/cpu.c bob64/descriptors.c bob64/interrupts.c bob64/interrupts.S bob64/syscall.c bob64/window_server.c bob64/bootstrap.c bob64/console.c bob64/lz4.c bob64/firmware_store.c bob64/heap.c bob64/keyboard.c bob64/mouse.c bob64/pci.c bob64/xhci.c bob64/usb.c bob64/block_device.c bob64/partition.c bob64/disk_store.c bob64/shell.c bob64/filesystem.c bob64/snapshot.c bob64/exec.c bob64/process.c -o build/test_bob64" EXE);
if(bob64Handoff) run(BUILD_DIR "test_bob64" EXE " " BOB64_HANDOFF_BOOT_PATH " build/bob64-app/smoke.b64e build/bob64-app/display.b64e build/bob64-app/gui.b64e build/bob64-app/nested-smoke.b64e build/bob64-app/echo.b64e build/bob64-app/ls.b64e build/bob64-app/cat.b64e build/bob64-app/notes.b64e build/bob64-app/info.b64e build/bob64-app/mouse-smoke.b64e build/bob64-app/launcher.b64e");
else run(BUILD_DIR "test_bob64" EXE " " BOB64_BOOT_PATH " build/bob64-app/smoke.b64e build/bob64-app/display.b64e build/bob64-app/gui.b64e build/bob64-app/nested-smoke.b64e build/bob64-app/echo.b64e build/bob64-app/ls.b64e build/bob64-app/cat.b64e build/bob64-app/notes.b64e build/bob64-app/info.b64e build/bob64-app/mouse-smoke.b64e build/bob64-app/launcher.b64e");
}
+127
View File
@@ -0,0 +1,127 @@
param(
[Parameter(Mandatory = $true)]
[string]$Path,
[ValidateRange(32, 2097154)]
[int]$SizeMiB = 64,
[long]$FirstPartitionLba = 2048,
[switch]$Sparse,
[switch]$Force
)
$ErrorActionPreference = 'Stop'
$sectorSize = 512
$sectorCount = [uint64]$SizeMiB * 1MB / $sectorSize
$tableBytes = 128 * 128
$tableSectors = [uint64][Math]::Ceiling($tableBytes / $sectorSize)
if ($sectorCount -lt (4096 + 2 * $tableSectors + 2)) {
throw 'The image is too small for the bob64 data partition and GPT metadata.'
}
$fullPath = [IO.Path]::GetFullPath($Path)
if ((Test-Path -LiteralPath $fullPath) -and -not $Force) {
throw "Refusing to overwrite '$fullPath'; pass -Force to replace it."
}
$parent = Split-Path -Parent $fullPath
if (-not (Test-Path -LiteralPath $parent -PathType Container)) {
throw "Output directory does not exist: $parent"
}
function Set-U16([byte[]]$Buffer,[int]$Offset,[uint16]$Value) {
[Buffer]::BlockCopy([BitConverter]::GetBytes($Value),0,$Buffer,$Offset,2)
}
function Set-U32([byte[]]$Buffer,[int]$Offset,[uint32]$Value) {
[Buffer]::BlockCopy([BitConverter]::GetBytes($Value),0,$Buffer,$Offset,4)
}
function Set-U64([byte[]]$Buffer,[int]$Offset,[uint64]$Value) {
[Buffer]::BlockCopy([BitConverter]::GetBytes($Value),0,$Buffer,$Offset,8)
}
function Get-Crc32([byte[]]$Bytes) {
[uint32]$crc = [uint32]::MaxValue
foreach ($value in $Bytes) {
$crc = $crc -bxor [uint32]$value
for ($bit = 0; $bit -lt 8; $bit++) {
if ($crc -band 1) { $crc = ($crc -shr 1) -bxor 0xedb88320 }
else { $crc = $crc -shr 1 }
}
}
return [uint32]($crc -bxor 0xffffffff)
}
function New-GptHeader([uint64]$CurrentLba,[uint64]$BackupLba,
[uint64]$TableLba,[uint64]$FirstUsable,[uint64]$LastUsable,
[byte[]]$DiskGuid,[uint32]$TableCrc) {
$header = [byte[]]::new($sectorSize)
[Text.Encoding]::ASCII.GetBytes('EFI PART').CopyTo($header,0)
Set-U32 $header 8 0x00010000
Set-U32 $header 12 92
Set-U64 $header 24 $CurrentLba
Set-U64 $header 32 $BackupLba
Set-U64 $header 40 $FirstUsable
Set-U64 $header 48 $LastUsable
[Buffer]::BlockCopy($DiskGuid,0,$header,56,16)
Set-U64 $header 72 $TableLba
Set-U32 $header 80 128
Set-U32 $header 84 128
Set-U32 $header 88 $TableCrc
$crcInput = [byte[]]::new(92)
[Buffer]::BlockCopy($header,0,$crcInput,0,92)
Set-U32 $header 16 (Get-Crc32 $crcInput)
return ,$header
}
$table = [byte[]]::new([int]($tableSectors * $sectorSize))
$typeGuid = [byte[]](0x64,0x62,0x61,0x7b,0x30,0x30,0x34,0x30,
0x9a,0x21,0x42,0x4f,0x42,0x36,0x34,0x01)
$uniqueGuid = [Guid]::NewGuid().ToByteArray()
$firstPartitionLba = [uint64]$FirstPartitionLba
$lastUsableLba = $sectorCount - $tableSectors - 2
if ($firstPartitionLba -lt 2048 -or $firstPartitionLba -gt $lastUsableLba) {
throw 'The data partition start must be inside the GPT usable-LBA range.'
}
$lastPartitionLba = $sectorCount - $tableSectors - 2
[Buffer]::BlockCopy($typeGuid,0,$table,0,16)
[Buffer]::BlockCopy($uniqueGuid,0,$table,16,16)
Set-U64 $table 32 $firstPartitionLba
Set-U64 $table 40 $lastPartitionLba
$name = [Text.Encoding]::Unicode.GetBytes('bob64 data')
[Buffer]::BlockCopy($name,0,$table,56,$name.Length)
$tableCrc = Get-Crc32 $table
$diskGuid = [Guid]::NewGuid().ToByteArray()
$primaryHeader = New-GptHeader 1 ($sectorCount - 1) 2 34 $lastUsableLba $diskGuid $tableCrc
$backupTableLba = $sectorCount - $tableSectors - 1
$backupHeader = New-GptHeader ($sectorCount - 1) 1 $backupTableLba 34 $lastUsableLba $diskGuid $tableCrc
$mbr = [byte[]]::new($sectorSize)
$mbr[446 + 4] = 0xee
Set-U32 $mbr (446 + 8) 1
Set-U32 $mbr (446 + 12) ([uint32][Math]::Min([double]($sectorCount - 1),[double][uint32]::MaxValue))
$mbr[510] = 0x55
$mbr[511] = 0xaa
$stream = [IO.File]::Open($fullPath,[IO.FileMode]::Create,
[IO.FileAccess]::ReadWrite,[IO.FileShare]::None)
try {
if ($Sparse) {
$stream.Dispose()
& fsutil.exe sparse setflag $fullPath | Out-Null
if ($LASTEXITCODE -ne 0) {
throw 'Could not mark the GPT disk image as sparse.'
}
$stream = [IO.File]::Open($fullPath,[IO.FileMode]::Open,
[IO.FileAccess]::ReadWrite,[IO.FileShare]::None)
}
$stream.SetLength([long]$sectorCount * $sectorSize)
$stream.Position = 0; $stream.Write($mbr,0,$mbr.Length)
$stream.Position = $sectorSize; $stream.Write($primaryHeader,0,$primaryHeader.Length)
$stream.Position = 2 * $sectorSize; $stream.Write($table,0,$table.Length)
$stream.Position = [long]$backupTableLba * $sectorSize
$stream.Write($table,0,$table.Length)
$stream.Position = [long]($sectorCount - 1) * $sectorSize
$stream.Write($backupHeader,0,$backupHeader.Length)
$stream.Flush($true)
} finally {
if ($stream) { $stream.Dispose() }
}
$partitionBlocks = $lastPartitionLba - $firstPartitionLba + 1
Write-Output "Created bob64 GPT disk image: $fullPath"
Write-Output "Disk size: $SizeMiB MiB; data partition: LBA $firstPartitionLba, $partitionBlocks sectors"
Write-Output 'Attach this raw image to the emulator as a USB mass-storage disk.'
+1411 -45
View File
File diff suppressed because it is too large. Load diff
+134
View File
@@ -0,0 +1,134 @@
param(
[Parameter(Mandatory = $true)]
[string]$QemuPath,
[Parameter(Mandatory = $true)]
[string]$OvmfCodePath,
[Parameter(Mandatory = $true)]
[string]$OvmfVarsPath,
[string]$ImageRoot = (Join-Path (Split-Path -Parent $PSScriptRoot) 'build\bob64-handoff'),
[int]$TimeoutSeconds = 60
)
$ErrorActionPreference = 'Stop'
foreach ($path in @($QemuPath, $OvmfCodePath, $OvmfVarsPath, $ImageRoot)) {
if (-not (Test-Path -LiteralPath $path)) {
throw "Required Bob64 serial test path does not exist: $path"
}
}
$efiPath = Join-Path $ImageRoot 'EFI\BOOT\BOOTX64.EFI'
if (-not (Test-Path -LiteralPath $efiPath)) {
throw "The handoff image is missing: $efiPath"
}
function Get-FreeLoopbackPort {
$listener = [Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback, 0)
$listener.Start()
try { return ([Net.IPEndPoint]$listener.LocalEndpoint).Port }
finally { $listener.Stop() }
}
function Wait-SerialText([Net.Sockets.NetworkStream]$stream,
[string]$needle,[int]$startOffset,[int]$timeoutSeconds) {
$deadline = [DateTime]::UtcNow.AddSeconds($timeoutSeconds)
$buffer = New-Object byte[] 4096
while ([DateTime]::UtcNow -lt $deadline) {
while ($stream.DataAvailable) {
$count = $stream.Read($buffer, 0, $buffer.Length)
if ($count -le 0) { break }
[void]$script:serialTranscript.Append(
[Text.Encoding]::ASCII.GetString($buffer, 0, $count))
}
$text = $script:serialTranscript.ToString()
if ($text.Length -gt $startOffset -and
$text.Substring($startOffset).Contains($needle)) { return $text }
if ($script:qemuProcess.HasExited) {
throw "QEMU exited before COM1 produced '$needle'.`n$text"
}
Start-Sleep -Milliseconds 20
}
throw "Timed out waiting for COM1 output '$needle'.`n$($script:serialTranscript.ToString())"
}
$imagePath = (Resolve-Path -LiteralPath $ImageRoot).Path.Replace('\', '/')
$firmwarePath = (Resolve-Path -LiteralPath $OvmfCodePath).Path
$varsTemplatePath = (Resolve-Path -LiteralPath $OvmfVarsPath).Path
$varsCopyPath = Join-Path ([IO.Path]::GetTempPath()) ("bob64-serial-vars-{0}.fd" -f [guid]::NewGuid())
Copy-Item -LiteralPath $varsTemplatePath -Destination $varsCopyPath
$serialPort = Get-FreeLoopbackPort
$script:serialTranscript = [Text.StringBuilder]::new()
$script:qemuProcess = $null
$serialClient = $null
try {
$qemuArguments = @(
'-machine', 'q35', '-m', '512M', '-cpu', 'max',
'-drive', "if=pflash,format=raw,unit=0,file=$firmwarePath,readonly=on",
'-drive', "if=pflash,format=raw,unit=1,file=$varsCopyPath",
'-drive', "format=raw,file=fat:rw:$imagePath",
'-boot', 'order=c', '-display', 'none',
'-serial', "tcp:127.0.0.1:$serialPort,server=on,wait=on",
'-monitor', 'none'
)
$startInfo = [Diagnostics.ProcessStartInfo]::new()
$startInfo.FileName = (Resolve-Path -LiteralPath $QemuPath).Path
$startInfo.UseShellExecute = $false
$startInfo.CreateNoWindow = $true
$startInfo.Arguments = (($qemuArguments | ForEach-Object {
'"' + ([string]$_).Replace('"', '\"') + '"'
}) -join ' ')
$script:qemuProcess = [Diagnostics.Process]::Start($startInfo)
$serialClient = $null
$connectDeadline = [DateTime]::UtcNow.AddSeconds(10)
while (-not $serialClient -and [DateTime]::UtcNow -lt $connectDeadline) {
$candidate = [Net.Sockets.TcpClient]::new()
try {
$candidate.Connect('127.0.0.1', $serialPort)
$serialClient = $candidate
} catch {
$candidate.Dispose()
Start-Sleep -Milliseconds 100
}
}
if (-not $serialClient) {
throw 'Could not connect to QEMU COM1.'
}
$stream = $serialClient.GetStream()
$stream.ReadTimeout = 100
[void](Wait-SerialText $stream 'bob64> ' 0 $TimeoutSeconds)
if (-not $script:serialTranscript.ToString().Contains(
'bob64 kernel: serial RX IRQ enabled')) {
throw "The kernel did not enable COM1 receive interrupts.`n$($script:serialTranscript.ToString())"
}
$startOffset = $script:serialTranscript.Length
$commandBytes = [Text.Encoding]::ASCII.GetBytes("version`r")
$stream.Write($commandBytes, 0, $commandBytes.Length)
$stream.Flush()
[void](Wait-SerialText $stream 'bob64 kernel 0.1' $startOffset $TimeoutSeconds)
$startOffset = $script:serialTranscript.Length
$commandBytes = [Text.Encoding]::ASCII.GetBytes("write serial.txt bob!`r")
$stream.Write($commandBytes, 0, $commandBytes.Length)
$stream.Flush()
[void](Wait-SerialText $stream 'saved' $startOffset $TimeoutSeconds)
$startOffset = $script:serialTranscript.Length
$commandBytes = [Text.Encoding]::ASCII.GetBytes("cat serial.txt`r")
$stream.Write($commandBytes, 0, $commandBytes.Length)
$stream.Flush()
[void](Wait-SerialText $stream "bob!`r`nbob64> " $startOffset $TimeoutSeconds)
Write-Output 'COM1 IRQ runtime check passed: version, file write, and file read commands completed over serial.'
}
finally {
if ($serialClient) { $serialClient.Dispose() }
if ($script:qemuProcess -and -not $script:qemuProcess.HasExited) {
$script:qemuProcess.Kill()
$script:qemuProcess.WaitForExit()
}
if (Test-Path -LiteralPath $varsCopyPath) {
Remove-Item -LiteralPath $varsCopyPath -Force
}
}