From 57787bfc7f1ed63c5810fe2c6e51f759dfc92ee1 Mon Sep 17 00:00:00 2001 From: Alvin Date: Fri, 9 Oct 2026 20:06:51 +0200 Subject: [PATCH] d d --- BOB64_MIGRATION.md | 410 +++++- Makefile | 12 +- apps/bob64_cat.c | 181 +++ apps/bob64_demo.c | 115 +- apps/bob64_display.c | 18 +- apps/bob64_echo.c | 135 ++ apps/bob64_gui.c | 49 +- apps/bob64_info.c | 140 +- apps/bob64_ls.c | 248 ++++ apps/bob64_mouse_smoke.c | 97 +- apps/bob64_smoke.c | 18 +- bob.exe | Bin 93959 -> 93959 bytes bob32.exe | Bin 93959 -> 93959 bytes bob64/FONT_LICENSE.md | 21 + bob64/README.md | 271 +++- bob64/app.h | 11 + bob64/block_device.c | 45 + bob64/block_device.h | 33 + bob64/compiler.c | 634 ++++++++- bob64/console.c | 99 +- bob64/disk_store.c | 241 ++++ bob64/disk_store.h | 17 + bob64/firmware_store.c | 16 +- bob64/firmware_store.h | 2 +- bob64/font.h | 41 + bob64/font8x16.h | 114 ++ bob64/gfx.h | 116 +- bob64/interrupts.S | 44 + bob64/interrupts.c | 70 + bob64/interrupts.h | 22 +- bob64/kernel.c | 2448 ++++++++++++++++++++++++++++++++++- bob64/keyboard.c | 153 ++- bob64/keyboard.h | 10 + bob64/libc.c | 266 ++++ bob64/libc.h | 11 + bob64/mouse.c | 116 +- bob64/mouse.h | 9 + bob64/paging.c | 9 +- bob64/paging.h | 1 + bob64/partition.c | 111 ++ bob64/partition.h | 23 + bob64/pci.c | 180 +++ bob64/pci.h | 38 + bob64/shell.c | 28 +- bob64/syscall.c | 1 + bob64/usb.c | 323 +++++ bob64/usb.h | 82 ++ bob64/widgets.h | 92 +- bob64/window.h | 14 +- bob64/window_server.c | 108 +- bob64/window_server.h | 2 + bob64/xhci.c | 43 + bob64/xhci.h | 19 + build-tool.exe | Bin 48240 -> 49264 bytes tests/test_bob64.c | 1295 +++++++++++++++++- tools/build.c | 58 +- tools/new_bob64_disk.ps1 | 127 ++ tools/test_bob64_qemu.ps1 | 1456 ++++++++++++++++++++- tools/test_bob64_serial.ps1 | 134 ++ 59 files changed, 9967 insertions(+), 410 deletions(-) create mode 100644 bob64/FONT_LICENSE.md create mode 100644 bob64/block_device.c create mode 100644 bob64/block_device.h create mode 100644 bob64/disk_store.c create mode 100644 bob64/disk_store.h create mode 100644 bob64/font8x16.h create mode 100644 bob64/partition.c create mode 100644 bob64/partition.h create mode 100644 bob64/pci.c create mode 100644 bob64/pci.h create mode 100644 bob64/usb.c create mode 100644 bob64/usb.h create mode 100644 bob64/xhci.c create mode 100644 bob64/xhci.h create mode 100644 tools/new_bob64_disk.ps1 create mode 100644 tools/test_bob64_serial.ps1 diff --git a/BOB64_MIGRATION.md b/BOB64_MIGRATION.md index 9ca4596..fcf1048 100644 --- a/BOB64_MIGRATION.md +++ b/BOB64_MIGRATION.md @@ -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 -OvmfCodePath -OvmfVarsPath +tools/test_bob64_qemu.ps1 -QemuPath -OvmfCodePath -OvmfVarsPath -ImageRoot build/bob64-handoff-storage-active-test -ProbeOnly -ProbeDevice storage-active-disconnect +tools/test_bob64_qemu.ps1 -QemuPath -OvmfCodePath -OvmfVarsPath -ImageRoot build/bob64-handoff-storage64-test -ProbeOnly -ProbeDevice storage64 +tools/test_bob64_qemu.ps1 -QemuPath -OvmfCodePath -OvmfVarsPath -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 diff --git a/Makefile b/Makefile index 37b88f4..4dda564 100644 --- a/Makefile +++ b/Makefile @@ -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 diff --git a/apps/bob64_cat.c b/apps/bob64_cat.c index 18e642b..9ab7a90 100644 --- a/apps/bob64_cat.c +++ b/apps/bob64_cat.c @@ -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=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=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+10)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"); diff --git a/apps/bob64_demo.c b/apps/bob64_demo.c index 37650ce..24c011f 100644 --- a/apps/bob64_demo.c +++ b/apps/bob64_demo.c @@ -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; } diff --git a/apps/bob64_display.c b/apps/bob64_display.c index b4055e8..aa7087c 100644 --- a/apps/bob64_display.c +++ b/apps/bob64_display.c @@ -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; diff --git a/apps/bob64_echo.c b/apps/bob64_echo.c index 56a0ca7..d9c2917 100644 --- a/apps/bob64_echo.c +++ b/apps/bob64_echo.c @@ -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)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;iArgumentCount;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;rowECHO_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;iArgumentCount;i++) { const char *argument=startup->Arguments[i]; if(i>1&&bob64_app_write_char(' ')<0)return -2; diff --git a/apps/bob64_gui.c b/apps/bob64_gui.c index fa5e153..8190133 100644 --- a/apps/bob64_gui.c +++ b/apps/bob64_gui.c @@ -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_fileCharacter=='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; diff --git a/apps/bob64_info.c b/apps/bob64_info.c index 69208eb..5d5d962 100644 --- a/apps/bob64_info.c +++ b/apps/bob64_info.c @@ -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&&countBOB64_SYSCALL_MAX_FILES)return -1; + gui_total_bytes=0; + for(s64 i=0;iStructSize!=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; diff --git a/apps/bob64_ls.c b/apps/bob64_ls.c index b41b2bd..c0f5c59 100644 --- a/apps/bob64_ls.c +++ b/apps/bob64_ls.c @@ -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&&count5&&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+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_widthArgumentCount==3&&startup->Arguments[2]) { + int found=0; + for(u32 i=0;iArguments[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=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+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_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=70) { + u32 row=(u32)(routed.Y-70)/18; + u32 index=gui_scroll+row; + if(indexStructSize!=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"); diff --git a/apps/bob64_mouse_smoke.c b/apps/bob64_mouse_smoke.c index 0ecbeb3..82131b7 100644 --- a/apps/bob64_mouse_smoke.c +++ b/apps/bob64_mouse_smoke.c @@ -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=(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; } diff --git a/apps/bob64_smoke.c b/apps/bob64_smoke.c index 9d3439b..ff725c3 100644 --- a/apps/bob64_smoke.c +++ b/apps/bob64_smoke.c @@ -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();M1& delta 24 gcmZp_$J&06bwUTz9j=L8eoQxBH{RNMi%~ZZ0FN{ai2wiq diff --git a/bob32.exe b/bob32.exe index 63144f3db39df904ec21f8fa1bda0827ed1e1f6e..9cba03b180dd3a686f62b4750b85499f769a7474 100644 GIT binary patch delta 24 gcmZp_$J&06bwUS|<^73WeoSTu8gFgA#i*MH0E$Bj?f?J) delta 24 gcmZp_$J&06bwUTzU9O2;eoQxCH{RNMi%~ZZ0FO)yivR!s diff --git a/bob64/FONT_LICENSE.md b/bob64/FONT_LICENSE.md new file mode 100644 index 0000000..2cdfbdf --- /dev/null +++ b/bob64/FONT_LICENSE.md @@ -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. diff --git a/bob64/README.md b/bob64/README.md index f8a4cc2..ec4329f 100644 --- a/bob64/README.md +++ b/bob64/README.md @@ -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. diff --git a/bob64/app.h b/bob64/app.h index d49bc47..ac97d29 100644 --- a/bob64/app.h +++ b/bob64/app.h @@ -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; diff --git a/bob64/block_device.c b/bob64/block_device.c new file mode 100644 index 0000000..8a37e1b --- /dev/null +++ b/bob64/block_device.c @@ -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; +} diff --git a/bob64/block_device.h b/bob64/block_device.h new file mode 100644 index 0000000..f9f486f --- /dev/null +++ b/bob64/block_device.h @@ -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 diff --git a/bob64/compiler.c b/bob64/compiler.c index 5f43891..7df66c9 100644 --- a/bob64/compiler.c +++ b/bob64/compiler.c @@ -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&& typePosition; + 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;iTypedefCount;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;iEnumCount;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;iEnumConstantCount;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&& typeCOMPILER_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(positionLength&&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;iBreakCount;i++) if(!compiler_patch_branch(compiler,loop->BreakBranches[i],break_target))return 0; for(u32 i=0;iContinueCount;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;iBreakCount;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;iCaseCount;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;iCaseCount;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;argumentArgumentCount;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=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;byteData[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;i8?framebuffer.Height-8:0; + u32 lines=framebuffer.Height>LINE_HEIGHT? + framebuffer.Height-LINE_HEIGHT:0; for(u32 y=0;y='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=0&&x+(s64)dx=0&&y+(s64)dy=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~(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=framebuffer.Height/8)scroll(); + if(framebuffer.Row>=rows())scroll(); } else if(value=='\b')erase_previous_character(); else draw_character(value); } + draw_cursor(); } diff --git a/bob64/disk_store.c b/bob64/disk_store.c new file mode 100644 index 0000000..b69cd91 --- /dev/null +++ b/bob64/disk_store.c @@ -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>1)^(0xedb88320u&-(crc&1u)); + } + return crc; +} + +static u32 header_crc(const u8 *header) { + u8 copy[DISK_STORE_HEADER_SIZE]; + for(u32 i=0;i=DISK_STORE_HEADER_CRC_OFFSET&& + iBlockSize|| + 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;iTypeGuid[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=remainingBlockSize-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=remainingReadOnly||!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;iBlockSize;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~(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; +} diff --git a/bob64/disk_store.h b/bob64/disk_store.h new file mode 100644 index 0000000..0f623dd --- /dev/null +++ b/bob64/disk_store.h @@ -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 diff --git a/bob64/firmware_store.c b/bob64/firmware_store.c index bea9851..7f2cc93 100644 --- a/bob64/firmware_store.c +++ b/bob64/firmware_store.c @@ -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 diff --git a/bob64/firmware_store.h b/bob64/firmware_store.h index 981d9ee..43ec125 100644 --- a/bob64/firmware_store.h +++ b/bob64/firmware_store.h @@ -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 diff --git a/bob64/font.h b/bob64/font.h index dca39b7..39c18ac 100644 --- a/bob64/font.h +++ b/bob64/font.h @@ -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<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;rowHeight;row++)for(u32 column=0;columnWidth;column++) + if(bob64_font_sample(font,glyph,column,row)) + plot(context,x+(s64)column*scale,y+(s64)row*scale,scale,color); +} + #endif diff --git a/bob64/font8x16.h b/bob64/font8x16.h new file mode 100644 index 0000000..d2e5b2a --- /dev/null +++ b/bob64/font8x16.h @@ -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 diff --git a/bob64/gfx.h b/bob64/gfx.h index 8c7dfaf..4c5e303 100644 --- a/bob64/gfx.h +++ b/bob64/gfx.h @@ -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)xWidth&&(u32)yHeight) - 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)xWidth&&(u32)yHeight) { + usize index=(usize)(u32)y*graphics->Width+(u32)x; + if((u64)graphics->Width*graphics->Height<=graphics->Capacity&& + indexCapacity) + 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;rowPixels||!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;rowPixels[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=x0y0?y0-y1:y1-y0,sy=y0Pixels||!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=axay?ay-by:by-ay,sy=ay=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<=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; diff --git a/bob64/interrupts.h b/bob64/interrupts.h index 97ba9f0..c7e997a 100644 --- a/bob64/interrupts.h +++ b/bob64/interrupts.h @@ -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); diff --git a/bob64/kernel.c b/bob64/kernel.c index c2c5f6f..a2b3bd2 100644 --- a/bob64/kernel.c +++ b/bob64/kernel.c @@ -13,15 +13,42 @@ #include "syscall.h" #include "compiler.h" #include "firmware_store.h" +#include "pci.h" +#include "xhci.h" +#include "usb.h" +#include "block_device.h" +#include "partition.h" +#include "disk_store.h" #define BOB64_KERNEL_HEAP_BASE 0xffff900000000000ULL #define BOB64_KERNEL_HEAP_LIMIT (64ULL*1024ULL*1024ULL) #define BOB64_KERNEL_PRIVILEGE_STACK_SIZE (16ULL*1024ULL) +#define BOB64_XHCI_MMIO_MAP_SIZE (4ULL*BOB64_PAGE_SIZE) +#define BOB64_XHCI_RING_TRBS 256u +#define BOB64_XHCI_MAX_SCRATCHPADS 1023u +#define BOB64_XHCI_USBCMD_RUN 0x00000001u +#define BOB64_XHCI_USBSTS_HALTED 0x00000001u +#define BOB64_XHCI_USBSTS_NOT_READY 0x00000800u +#define BOB64_XHCI_TRB_TYPE_SHIFT 10u +#define BOB64_XHCI_TRB_TYPE_LINK 6u +#define BOB64_XHCI_TRB_TYPE_ENABLE_SLOT 9u +#define BOB64_XHCI_TRB_TYPE_DISABLE_SLOT 10u +#define BOB64_XHCI_TRB_TYPE_NOOP_COMMAND 23u +#define BOB64_XHCI_TRB_TYPE_COMMAND_COMPLETION 33u +#define BOB64_XHCI_TRB_TYPE_PORT_STATUS_CHANGE 34u +#define BOB64_XHCI_TRB_TYPE_TRANSFER_EVENT 32u +#define BOB64_XHCI_TRB_COMPLETION_SUCCESS 1u +#define KERNEL_XHCI_STORAGE_DEVICE_LIMIT 8u static BOB64_HEAP kernel_heap; static BOB64_FILESYSTEM kernel_filesystem; static u64 kernel_next_window_owner=1; static BOB64_SHELL kernel_shell; +static BOB64_PCI_DEVICE kernel_xhci_device; +static int kernel_xhci_found; +#define KERNEL_XHCI_HID_DEVICE_LIMIT BOB64_USB_INPUT_DEVICE_LIMIT +static u8 kernel_xhci_connected_ports[KERNEL_XHCI_HID_DEVICE_LIMIT]; +static u8 kernel_xhci_connected_speeds[KERNEL_XHCI_HID_DEVICE_LIMIT]; typedef struct { BOB64_FILESYSTEM *Filesystem; u8 NxSupported,PhysicalAddressBits; @@ -37,6 +64,2288 @@ static u8 kernel_compiler_output[BOB64_COMPILER_IMAGE_LIMIT]; static void kernel_write(const char *text); static void kernel_hex64(u64 value); +static int kernel_pci_read_config(void *context,u8 bus,u8 device, + u8 function,u8 offset,u32 *value) { + (void)context; + return bob64_pci_read_config32(bus,device,function,offset,value); +} + +typedef struct { + volatile u8 *Base; + usize Size; + u8 CapabilityLength; +} KERNEL_XHCI_MMIO; + +typedef struct { + u64 Parameter; + u32 Status; + u32 Control; +} KERNEL_XHCI_TRB; + +typedef struct { + u64 RingBase; + u32 RingSize; + u32 Reserved; +} KERNEL_XHCI_ERST_ENTRY; + +typedef struct { + volatile KERNEL_XHCI_TRB *CommandRing; + volatile KERNEL_XHCI_TRB *EventRing; + volatile u64 *DeviceContextArray; + u64 CommandPhysical,EventPhysical; + u32 CommandIndex,EventIndex; + u8 EventCycle; + KERNEL_XHCI_TRB DeferredEvents[32]; + u8 DeferredHead,DeferredCount; +} KERNEL_XHCI_RINGS; + +static KERNEL_XHCI_RINGS kernel_xhci_rings; +static KERNEL_XHCI_MMIO kernel_xhci_live_mmio; +static BOB64_XHCI_CAPABILITIES kernel_xhci_live_capabilities; +typedef struct { + u32 RouteString; + u8 RootPort,ParentSlot,ParentPort,Speed,Depth,TtHubSlot,TtPort; +} KERNEL_XHCI_TOPOLOGY; + +static KERNEL_XHCI_TOPOLOGY kernel_xhci_hub_children[32]; +static u8 kernel_xhci_hub_child_count; + +typedef struct { + volatile KERNEL_XHCI_TRB *Ring; + volatile u8 *Report; + u64 RingPhysical,ReportPhysical; + u32 NextIndex,PendingIndex; + u8 Slot,Dci,Kind,ReportLength,Cycle,Active,Pending,TransferErrors,RootPort; + u8 LoggedReport,LoggedInput,LoggedWheel; + BOB64_KEYBOARD_HID_STATE KeyboardState; + KERNEL_XHCI_TOPOLOGY Topology; +} KERNEL_XHCI_HID_DEVICE; + +typedef struct { + volatile KERNEL_XHCI_TRB *Ring; + volatile u8 *Report; + volatile KERNEL_XHCI_TRB *ControlRing; + volatile u8 *ControlBuffer; + u64 RingPhysical,ReportPhysical; + u64 ControlRingPhysical,ControlBufferPhysical; + u32 NextIndex,PendingIndex,ControlNextIndex; + u8 Slot,Dci,ReportLength,Cycle,Active,Pending,TransferErrors,RootPort; + u8 LoggedChange,ControlCycle,PortCount; + KERNEL_XHCI_TOPOLOGY Topology; +} KERNEL_XHCI_HUB_DEVICE; + +typedef struct { + volatile KERNEL_XHCI_TRB *BulkInRing,*BulkOutRing; + volatile u8 *Scratch; + u64 BulkInRingPhysical,BulkOutRingPhysical; + u64 ScratchPhysical,BlockCount; + u16 BulkInMaxPacketSize,BulkOutMaxPacketSize; + u32 BulkInNext,BulkOutNext,NextTag,BlockSize; + u8 Slot,BulkInDci,BulkOutDci,BulkInCycle,BulkOutCycle,Active; + KERNEL_XHCI_TOPOLOGY Topology; + BOB64_BLOCK_DEVICE BlockDevice; + BOB64_PARTITION DataPartition; + u8 HasDataPartition,DisconnectTestReadPending; +} KERNEL_XHCI_STORAGE_DEVICE; + +static KERNEL_XHCI_HID_DEVICE kernel_xhci_hid_devices[KERNEL_XHCI_HID_DEVICE_LIMIT]; +static u8 kernel_xhci_hid_device_count; +static KERNEL_XHCI_HUB_DEVICE kernel_xhci_hub_devices[KERNEL_XHCI_HID_DEVICE_LIMIT]; +static u8 kernel_xhci_hub_device_count; +static KERNEL_XHCI_STORAGE_DEVICE + kernel_xhci_storage_devices[KERNEL_XHCI_STORAGE_DEVICE_LIMIT]; +static u8 kernel_xhci_storage_device_count; +static int kernel_xhci_storage_probe(KERNEL_XHCI_STORAGE_DEVICE *device); +static int kernel_xhci_hub_status_submit(KERNEL_XHCI_HUB_DEVICE *device); +static int kernel_xhci_delay_ticks(u64 ticks); +static void kernel_xhci_hub_process_changes(KERNEL_XHCI_HUB_DEVICE *hub); +static void kernel_xhci_address_hub_children(KERNEL_XHCI_MMIO *mmio, + const BOB64_XHCI_CAPABILITIES *capabilities,u32 start_index); +static void kernel_xhci_hid_reconnect(u8 port); + +_Static_assert(sizeof(KERNEL_XHCI_TRB)==16,"xHCI TRB is 16 bytes"); +_Static_assert(sizeof(KERNEL_XHCI_ERST_ENTRY)==16,"xHCI ERST entry is 16 bytes"); + +static int kernel_xhci_read32(void *opaque,u32 offset,u32 *value) { + KERNEL_XHCI_MMIO *mmio=(KERNEL_XHCI_MMIO *)opaque; + if(!mmio||!value||(offset&3u)||offset>mmio->Size|| + mmio->Size-offsetBase+offset); + return 0; +} + +static int kernel_xhci_write32(void *opaque,u32 offset,u32 value) { + KERNEL_XHCI_MMIO *mmio=(KERNEL_XHCI_MMIO *)opaque; + if(!mmio||(offset&3u)||offset>mmio->Size|| + mmio->Size-offsetBase+offset)=value; + return 0; +} + +static int kernel_xhci_dma_alloc(u64 pages,u64 *physical,volatile u8 **virtual) { + u64 bytes; + u64 base; + u64 flags=BOB64_PAGE_WRITE; + if(!pages||!physical||!virtual||pages>~(u64)0/BOB64_PAGE_SIZE)return -1; + bytes=pages*BOB64_PAGE_SIZE; + base=bob64_page_alloc(&bob64_boot_page_allocator,pages); + if(!base||base>=0x0000800000000000ULL|| + bytes>0x0000800000000000ULL-base)return -1; + if(bob64_bootstrap_space.NxSupported)flags|=BOB64_PAGE_NX; + for(u64 offset=0;offsetmmio->Size|| + mmio->Size-offset>32)))return -1; + return 0; +} + +static int kernel_xhci_advance_event(KERNEL_XHCI_MMIO *mmio, + const BOB64_XHCI_CAPABILITIES *capabilities) { + u32 runtime_offset; + if(!mmio||!capabilities||kernel_xhci_rings.EventIndex>= + BOB64_XHCI_RING_TRBS)return -1; + kernel_xhci_rings.EventIndex++; + if(kernel_xhci_rings.EventIndex==BOB64_XHCI_RING_TRBS) { + kernel_xhci_rings.EventIndex=0; + kernel_xhci_rings.EventCycle^=1u; + } + runtime_offset=capabilities->RuntimeOffset-mmio->CapabilityLength; + return kernel_xhci_write64(mmio,runtime_offset+0x38, + kernel_xhci_rings.EventPhysical+ + kernel_xhci_rings.EventIndex*sizeof(KERNEL_XHCI_TRB)+8u); +} + +static int kernel_xhci_event_take(KERNEL_XHCI_MMIO *mmio, + const BOB64_XHCI_CAPABILITIES *capabilities,u32 expected_type, + KERNEL_XHCI_TRB *result) { + if(!mmio||!capabilities||!result||!kernel_xhci_rings.EventRing)return -1; + for(u32 offset=0;offsetControl>>BOB64_XHCI_TRB_TYPE_SHIFT)&0x3fu; + if(!expected_type||type==expected_type) { + *result=*queued; + for(u32 move=offset;move+1Control; + if((control&1u)!=kernel_xhci_rings.EventCycle)return 0; + result->Parameter=event->Parameter; + result->Status=event->Status; + result->Control=control; + if(kernel_xhci_advance_event(mmio,capabilities))return -2; + u32 type=(control>>BOB64_XHCI_TRB_TYPE_SHIFT)&0x3fu; + if(!expected_type||type==expected_type)return 1; + if(kernel_xhci_rings.DeferredCount>=32u)return -3; + u32 tail=(kernel_xhci_rings.DeferredHead+ + kernel_xhci_rings.DeferredCount)%32u; + kernel_xhci_rings.DeferredEvents[tail]=*result; + kernel_xhci_rings.DeferredCount++; + return 0; +} + +static int kernel_xhci_wait_event(KERNEL_XHCI_MMIO *mmio, + const BOB64_XHCI_CAPABILITIES *capabilities,u32 expected_type, + u32 poll_limit,KERNEL_XHCI_TRB *result) { + if(!mmio||!capabilities||!expected_type||!poll_limit||!result|| + !kernel_xhci_rings.EventRing)return -1; + for(u32 wait=0;wait31u||!poll_limit|| + !completion||!kernel_xhci_rings.EventRing)return -1; +#ifdef BOB64_STORAGE_ACTIVE_DISCONNECT_TEST + if(!active_disconnect_test_armed) { + for(u32 i=0;iControl; + if((control&1u)!=kernel_xhci_rings.EventCycle) { + __asm__ volatile("pause"); + continue; + } + KERNEL_XHCI_TRB current={event->Parameter,event->Status,control}; + if(kernel_xhci_advance_event(mmio,capabilities))break; + u32 type=(control>>BOB64_XHCI_TRB_TYPE_SHIFT)&0x3fu; + if(type==BOB64_XHCI_TRB_TYPE_TRANSFER_EVENT&& + (u8)(control>>24)==slot&&((control>>16)&0x1fu)==dci&& + current.Parameter==trb_physical) { + *completion=current; + found=1; + break; + } + if(type==BOB64_XHCI_TRB_TYPE_PORT_STATUS_CHANGE) { + u8 port=(u8)(current.Parameter>>24); + u32 port_status=0; + for(u32 i=0;iActive&&device->Slot==slot&& + device->Topology.RootPort==port&&port&& + port<=capabilities->MaxPorts&& + !kernel_xhci_read32(mmio,0x400u+((u32)port-1u)*0x10u, + &port_status)&&!(port_status&1u)) { + storage_removed=1; + break; + } + } + if(storage_removed) { + kernel_write("bob64 kernel: USB MSC transfer aborted after disconnect\r\n"); + if(deferred_count>=32u)break; + deferred[deferred_count++]=current; + break; + } + } + if(deferred_count>=32u)break; + deferred[deferred_count++]=current; + } + for(u32 i=0;i=32u)return -2; + u32 tail=(kernel_xhci_rings.DeferredHead+ + kernel_xhci_rings.DeferredCount)%32u; + kernel_xhci_rings.DeferredEvents[tail]=deferred[i]; + kernel_xhci_rings.DeferredCount++; + } + return found?0:(storage_removed?-4:-3); +} + +static int kernel_xhci_disable_slot(u8 slot_id) { + if(!slot_id||!kernel_xhci_rings.CommandRing|| + kernel_xhci_rings.CommandIndex>=BOB64_XHCI_RING_TRBS-1)return -1; + u32 command_index=kernel_xhci_rings.CommandIndex; + volatile KERNEL_XHCI_TRB *command= + &kernel_xhci_rings.CommandRing[command_index]; + KERNEL_XHCI_TRB completion; + command->Parameter=0; + command->Status=0; + command->Control=(BOB64_XHCI_TRB_TYPE_DISABLE_SLOT<< + BOB64_XHCI_TRB_TYPE_SHIFT)|((u32)slot_id<<24)|1u; + __asm__ volatile("sfence" ::: "memory"); + u32 doorbell=kernel_xhci_live_capabilities.DoorbellOffset- + kernel_xhci_live_mmio.CapabilityLength; + if(kernel_xhci_write32(&kernel_xhci_live_mmio,doorbell,0))return -2; + int result=kernel_xhci_wait_event(&kernel_xhci_live_mmio, + &kernel_xhci_live_capabilities, + BOB64_XHCI_TRB_TYPE_COMMAND_COMPLETION,10000000u,&completion); + if(result)return -3+result; + if(completion.Parameter!=kernel_xhci_rings.CommandPhysical+ + command_index*sizeof(KERNEL_XHCI_TRB)|| + (completion.Status>>24)!=BOB64_XHCI_TRB_COMPLETION_SUCCESS|| + (u8)(completion.Control>>24)!=slot_id)return -4; + kernel_xhci_rings.CommandIndex++; + if(kernel_xhci_rings.DeviceContextArray) + kernel_xhci_rings.DeviceContextArray[slot_id]=0; + return 0; +} + +static int kernel_xhci_usb_hid_submit(KERNEL_XHCI_HID_DEVICE *device) { + if(!device||!device->Active||device->Pending||!device->Ring)return -1; + for(u32 i=0;iReportLength;i++)device->Report[i]=0; + if(device->NextIndex==BOB64_XHCI_RING_TRBS-1) { + volatile KERNEL_XHCI_TRB *link= + &device->Ring[BOB64_XHCI_RING_TRBS-1]; + link->Parameter=device->RingPhysical;link->Status=0; + link->Control=(BOB64_XHCI_TRB_TYPE_LINK<Cycle; + device->NextIndex=0;device->Cycle^=1u; + } + u32 index=device->NextIndex++; + volatile KERNEL_XHCI_TRB *transfer=&device->Ring[index]; + transfer->Parameter=device->ReportPhysical; + transfer->Status=device->ReportLength; + transfer->Control=(1u<Cycle; + __asm__ volatile("sfence":::"memory"); + u32 doorbell=kernel_xhci_live_capabilities.DoorbellOffset- + kernel_xhci_live_mmio.CapabilityLength+(u32)device->Slot*4u; + if(kernel_xhci_write32(&kernel_xhci_live_mmio,doorbell,device->Dci))return -2; + device->PendingIndex=index;device->Pending=1; + return 0; +} + +static int kernel_xhci_hub_status_submit(KERNEL_XHCI_HUB_DEVICE *device) { + if(!device||!device->Active||device->Pending||!device->Ring)return -1; + for(u32 i=0;iReportLength;i++)device->Report[i]=0; + if(device->NextIndex==BOB64_XHCI_RING_TRBS-1) { + volatile KERNEL_XHCI_TRB *link= + &device->Ring[BOB64_XHCI_RING_TRBS-1]; + link->Parameter=device->RingPhysical;link->Status=0; + link->Control=(BOB64_XHCI_TRB_TYPE_LINK<Cycle; + device->NextIndex=0;device->Cycle^=1u; + } + u32 index=device->NextIndex++; + volatile KERNEL_XHCI_TRB *transfer=&device->Ring[index]; + transfer->Parameter=device->ReportPhysical; + transfer->Status=device->ReportLength; + transfer->Control=(1u<Cycle; + __asm__ volatile("sfence" ::: "memory"); + u32 doorbell=kernel_xhci_live_capabilities.DoorbellOffset- + kernel_xhci_live_mmio.CapabilityLength+(u32)device->Slot*4u; + if(kernel_xhci_write32(&kernel_xhci_live_mmio,doorbell,device->Dci))return -2; + device->PendingIndex=index;device->Pending=1; + return 0; +} + +static void kernel_xhci_hid_disconnect(KERNEL_XHCI_HID_DEVICE *device,u32 index) { + static const u8 released_report[8]={0}; + if(!device||!device->Active)return; + device->Active=0;device->Pending=0; + if(device->Kind==1) + (void)bob64_keyboard_hid_report_device(&device->KeyboardState, + released_report); + else if(device->Kind==2) + (void)bob64_mouse_usb_report_device(index,0,0,0,0); + if(kernel_xhci_disable_slot(device->Slot)) + kernel_write("bob64 kernel: USB HID slot disable failed\r\n"); + kernel_write("bob64 kernel: USB HID transfer stopped; held input released\r\n"); +} + +static void kernel_xhci_usb_hid_poll(void) { + if((!kernel_xhci_hid_device_count&&!kernel_xhci_hub_device_count&& + !kernel_xhci_storage_device_count)|| + !kernel_xhci_rings.EventRing)return; + for(u32 count=0;count<8;count++) { + KERNEL_XHCI_TRB event; + int taken=kernel_xhci_event_take(&kernel_xhci_live_mmio, + &kernel_xhci_live_capabilities,0,&event); + if(taken<=0)return; + u32 type=(event.Control>>BOB64_XHCI_TRB_TYPE_SHIFT)&0x3fu; + if(type==BOB64_XHCI_TRB_TYPE_PORT_STATUS_CHANGE) { + u8 port=(u8)(event.Parameter>>24); + u32 port_status=0; + if(port&&port<=kernel_xhci_live_capabilities.MaxPorts&& + !kernel_xhci_read32(&kernel_xhci_live_mmio, + 0x400u+((u32)port-1u)*0x10u,&port_status)) { + if(port_status&1u)kernel_xhci_hid_reconnect(port); + else { + for(u32 i=0;iActive&&hub->RootPort==port) { + hub->Active=0;hub->Pending=0; + (void)kernel_xhci_disable_slot(hub->Slot); + } + } + for(u32 i=0;iActive&&storage->Topology.RootPort==port) { + storage->Active=0; + (void)kernel_xhci_disable_slot(storage->Slot); + kernel_write("bob64 kernel: USB mass-storage device disconnected\r\n"); + } + } + } + } + } else if(type==BOB64_XHCI_TRB_TYPE_TRANSFER_EVENT) { + u32 completion=(event.Status>>24)&0xffu; + for(u32 i=0;iPending|| + (u8)(event.Control>>24)!=device->Slot|| + ((event.Control>>16)&0x1fu)!=device->Dci|| + event.Parameter!=device->RingPhysical+ + device->PendingIndex*sizeof(KERNEL_XHCI_TRB))continue; + device->Pending=0; + if(completion==BOB64_XHCI_TRB_COMPLETION_SUCCESS||completion==13u) { + device->TransferErrors=0; + u8 report[8]={0}; + for(u32 j=0;jReportLength&&jReport[j]; + if(!device->LoggedReport) { + device->LoggedReport=1; + kernel_write("bob64 kernel: USB HID transfer report received\r\n"); + } + if(device->Kind==1) { + int has_key=0; + (void)bob64_keyboard_hid_report_device( + &device->KeyboardState,report); + for(u32 j=2;jLoggedInput) { + device->LoggedInput=1; + kernel_write("bob64 kernel: USB HID keyboard input queued\r\n"); + } + } else if(device->Kind==2) { + s8 wheel=device->ReportLength>=4?(s8)report[3]:0; + int mouse_result=bob64_mouse_usb_report_device(i,report[0], + (s8)report[1],(s8)report[2],wheel); + if(!mouse_result&&!device->LoggedInput) { + device->LoggedInput=1; + kernel_write("bob64 kernel: USB HID mouse input queued\r\n"); + } + if(!mouse_result&&wheel&&!device->LoggedWheel) { + device->LoggedWheel=1; + kernel_write("bob64 kernel: USB HID mouse wheel input queued\r\n"); + } + } + (void)kernel_xhci_usb_hid_submit(device); + } else if(++device->TransferErrors>=3u) { + kernel_xhci_hid_disconnect(device,i); + } else { + (void)kernel_xhci_usb_hid_submit(device); + } + break; + } + for(u32 i=0;iActive||!hub->Pending|| + (u8)(event.Control>>24)!=hub->Slot|| + ((event.Control>>16)&0x1fu)!=hub->Dci|| + event.Parameter!=hub->RingPhysical+ + hub->PendingIndex*sizeof(KERNEL_XHCI_TRB))continue; + hub->Pending=0; + if(completion==BOB64_XHCI_TRB_COMPLETION_SUCCESS||completion==13u) { + int changed=0; + hub->TransferErrors=0; + for(u32 byte=0;byteReportLength;byte++) + if(hub->Report[byte])changed=1; + if(changed&&!hub->LoggedChange) { + hub->LoggedChange=1; + kernel_write("bob64 kernel: USB hub downstream change report received slot="); + kernel_hex64(hub->Slot);kernel_write(" bitmap="); + for(u32 byte=0;byteReportLength;byte++) { + kernel_hex64(hub->Report[byte]);kernel_write(" "); + } + kernel_write("\r\n"); + } + if(changed)kernel_xhci_hub_process_changes(hub); + (void)kernel_xhci_hub_status_submit(hub); + } else if(++hub->TransferErrors<3u) + (void)kernel_xhci_hub_status_submit(hub); + else hub->Active=0; + break; + } + } + } +} + +static int kernel_xhci_start_command_ring(KERNEL_XHCI_MMIO *mmio, + const BOB64_XHCI_CAPABILITIES *capabilities) { + u64 dcbaa_physical,command_physical,event_physical,erst_physical; + u64 scratch_array_physical=0; + u64 scratchpad_physical; + volatile u8 *dcbaa_bytes,*command_bytes,*event_bytes,*erst_bytes; + u64 scratch_array_pages; + u32 status,pagesize,command; + if(!mmio||!capabilities||capabilities->MaxScratchpadBuffers> + BOB64_XHCI_MAX_SCRATCHPADS)return -1; + if(kernel_xhci_read32(mmio,8,&pagesize)||!(pagesize&1u))return -2; + if(kernel_xhci_dma_alloc(1,&dcbaa_physical,&dcbaa_bytes)|| + kernel_xhci_dma_alloc(1,&command_physical,&command_bytes)|| + kernel_xhci_dma_alloc(1,&event_physical,&event_bytes)|| + kernel_xhci_dma_alloc(1,&erst_physical,&erst_bytes))return -3; + if(capabilities->MaxScratchpadBuffers) { + scratch_array_pages=(capabilities->MaxScratchpadBuffers*sizeof(u64)+ + BOB64_PAGE_SIZE-1)/BOB64_PAGE_SIZE; + volatile u8 *scratch_array_bytes; + if(kernel_xhci_dma_alloc(scratch_array_pages,&scratch_array_physical, + &scratch_array_bytes))return -4; + volatile u64 *scratch_array=(volatile u64 *)(volatile void *)scratch_array_bytes; + for(u32 i=0;iMaxScratchpadBuffers;i++) { + volatile u8 *scratch_bytes; + if(kernel_xhci_dma_alloc(1,&scratchpad_physical,&scratch_bytes)) + return -5; + scratch_array[i]=scratchpad_physical; + } + *(volatile u64 *)(volatile void *)dcbaa_bytes=scratch_array_physical; + } + volatile KERNEL_XHCI_TRB *command_ring= + (volatile KERNEL_XHCI_TRB *)(volatile void *)command_bytes; + volatile KERNEL_XHCI_TRB *event_ring= + (volatile KERNEL_XHCI_TRB *)(volatile void *)event_bytes; + volatile KERNEL_XHCI_ERST_ENTRY *erst= + (volatile KERNEL_XHCI_ERST_ENTRY *)(volatile void *)erst_bytes; + kernel_xhci_rings.CommandRing=command_ring; + kernel_xhci_rings.EventRing=event_ring; + kernel_xhci_rings.CommandPhysical=command_physical; + kernel_xhci_rings.EventPhysical=event_physical; + kernel_xhci_rings.DeviceContextArray= + (volatile u64 *)(volatile void *)dcbaa_bytes; + kernel_xhci_rings.CommandIndex=0; + kernel_xhci_rings.EventIndex=0; + kernel_xhci_rings.EventCycle=1; + command_ring[BOB64_XHCI_RING_TRBS-1].Parameter=command_physical; + command_ring[BOB64_XHCI_RING_TRBS-1].Status=0; + command_ring[BOB64_XHCI_RING_TRBS-1].Control= + (BOB64_XHCI_TRB_TYPE_LINK<RuntimeOffset-mmio->CapabilityLength; + if(runtime_offset>mmio->Size||mmio->Size-runtime_offset<0x40)return -8; + if(kernel_xhci_write32(mmio,runtime_offset+0x28,1u)|| + kernel_xhci_write64(mmio,runtime_offset+0x30,erst_physical)|| + kernel_xhci_write64(mmio,runtime_offset+0x38,event_physical))return -9; + __asm__ volatile("sfence" ::: "memory"); + if(kernel_xhci_read32(mmio,0,&command)|| + kernel_xhci_write32(mmio,0,command|BOB64_XHCI_USBCMD_RUN))return -10; + for(u32 i=0;i<1000000u;i++) { + if(kernel_xhci_read32(mmio,4,&status))return -11; + if(!(status&BOB64_XHCI_USBSTS_NOT_READY)&& + !(status&BOB64_XHCI_USBSTS_HALTED))break; + if(i==999999u)return -12; + } + u32 doorbell_offset=capabilities->DoorbellOffset-mmio->CapabilityLength; + if(kernel_xhci_write32(mmio,doorbell_offset,0))return -16; + KERNEL_XHCI_TRB completion; + if(kernel_xhci_wait_event(mmio,capabilities, + BOB64_XHCI_TRB_TYPE_COMMAND_COMPLETION,1000000u,&completion))return -15; + if(completion.Parameter!=command_physical|| + (completion.Status>>24)!=BOB64_XHCI_TRB_COMPLETION_SUCCESS)return -13; + kernel_xhci_rings.CommandIndex=1; + return 0; +} + +static int kernel_xhci_enable_slot(KERNEL_XHCI_MMIO *mmio, + const BOB64_XHCI_CAPABILITIES *capabilities,u8 *slot_id) { + u32 doorbell_offset; + if(!mmio||!capabilities||!slot_id|| + !kernel_xhci_rings.CommandRing||!kernel_xhci_rings.EventRing|| + kernel_xhci_rings.CommandIndex>=BOB64_XHCI_RING_TRBS-1|| + kernel_xhci_rings.EventIndex>=BOB64_XHCI_RING_TRBS)return -1; + u32 command_index=kernel_xhci_rings.CommandIndex; + volatile KERNEL_XHCI_TRB *command=&kernel_xhci_rings.CommandRing[command_index]; + KERNEL_XHCI_TRB completion; + command->Parameter=0; + command->Status=0; + command->Control=(BOB64_XHCI_TRB_TYPE_ENABLE_SLOT<< + BOB64_XHCI_TRB_TYPE_SHIFT)|1u; + __asm__ volatile("sfence" ::: "memory"); + doorbell_offset=capabilities->DoorbellOffset-mmio->CapabilityLength; + if(kernel_xhci_write32(mmio,doorbell_offset,0))return -2; + int result=kernel_xhci_wait_event(mmio,capabilities, + BOB64_XHCI_TRB_TYPE_COMMAND_COMPLETION,10000000u,&completion); + if(result)return -5+result; + u8 result_slot=(u8)(completion.Control>>24); + if(completion.Parameter!=kernel_xhci_rings.CommandPhysical+ + command_index*sizeof(KERNEL_XHCI_TRB)|| + (completion.Status>>24)!=BOB64_XHCI_TRB_COMPLETION_SUCCESS|| + !result_slot||result_slot>capabilities->MaxSlots)return -3; + *slot_id=result_slot; + kernel_xhci_rings.CommandIndex++; + return 0; +} + +static int kernel_xhci_control_in_data(KERNEL_XHCI_MMIO *mmio, + const BOB64_XHCI_CAPABILITIES *capabilities,u8 slot_id, + volatile KERNEL_XHCI_TRB *transfer_ring,u64 transfer_ring_physical, + u64 buffer_physical,u8 request_type,u8 request,u16 value,u16 index, + u16 length,u32 ring_index) { + u32 doorbell_offset; + KERNEL_XHCI_TRB completion; + if(!mmio||!capabilities||!slot_id||!transfer_ring||!length|| + ring_index+2>=BOB64_XHCI_RING_TRBS-1)return -1; + transfer_ring[ring_index].Parameter=bob64_usb_control_setup( + request_type,request,value,index,length); + transfer_ring[ring_index].Status=8; + transfer_ring[ring_index].Control=(2u<DoorbellOffset-mmio->CapabilityLength+ + (u32)slot_id*4u; + if(kernel_xhci_write32(mmio,doorbell_offset,1u))return -2; + int result=kernel_xhci_wait_event(mmio,capabilities, + BOB64_XHCI_TRB_TYPE_TRANSFER_EVENT,10000000u,&completion); + if(result)return -3+result; + if((completion.Status>>24)!=BOB64_XHCI_TRB_COMPLETION_SUCCESS|| + (u8)(completion.Control>>24)!=slot_id|| + ((completion.Control>>16)&0x1fu)!=1u|| + completion.Parameter!=transfer_ring_physical+ + (ring_index+2)*sizeof(KERNEL_XHCI_TRB))return -4; + return 0; +} + +static int kernel_xhci_get_descriptor(KERNEL_XHCI_MMIO *mmio, + const BOB64_XHCI_CAPABILITIES *capabilities,u8 slot_id, + volatile KERNEL_XHCI_TRB *transfer_ring,u64 transfer_ring_physical, + u64 buffer_physical,u8 descriptor_type,u16 length,u32 ring_index) { + return kernel_xhci_control_in_data(mmio,capabilities,slot_id, + transfer_ring,transfer_ring_physical,buffer_physical,0x80,6, + (u16)((u16)descriptor_type<<8),0,length,ring_index); +} + +static int kernel_xhci_control_no_data(KERNEL_XHCI_MMIO *mmio, + const BOB64_XHCI_CAPABILITIES *capabilities,u8 slot_id, + volatile KERNEL_XHCI_TRB *transfer_ring,u64 transfer_ring_physical, + u32 ring_index,u8 request_type,u8 request,u16 value,u16 index) { + KERNEL_XHCI_TRB completion; + if(!mmio||!capabilities||!slot_id||!transfer_ring|| + ring_index+1>=BOB64_XHCI_RING_TRBS-1)return -1; + transfer_ring[ring_index].Parameter=bob64_usb_control_setup( + request_type,request,value,index,0); + transfer_ring[ring_index].Status=8; + transfer_ring[ring_index].Control=(2u<DoorbellOffset-mmio->CapabilityLength+ + (u32)slot_id*4u; + if(kernel_xhci_write32(mmio,doorbell_offset,1u))return -2; + int result=kernel_xhci_wait_event(mmio,capabilities, + BOB64_XHCI_TRB_TYPE_TRANSFER_EVENT,10000000u,&completion); + if(result)return -3+result; + if((completion.Status>>24)!=BOB64_XHCI_TRB_COMPLETION_SUCCESS|| + (u8)(completion.Control>>24)!=slot_id|| + ((completion.Control>>16)&0x1fu)!=1u|| + completion.Parameter!=transfer_ring_physical+ + (ring_index+1)*sizeof(KERNEL_XHCI_TRB))return -4; + return 0; +} + +static int kernel_xhci_delay_ticks(u64 ticks) { + u64 start=bob64_timer_ticks(); + if(!ticks)return 0; + for(u32 wait=0;wait<200000000u;wait++) { + if(bob64_timer_ticks()-start>=ticks)return 0; + __asm__ volatile("pause"); + } + return -1; +} + +static int kernel_xhci_update_hub_context(KERNEL_XHCI_MMIO *mmio, + const BOB64_XHCI_CAPABILITIES *capabilities,u8 slot_id, + volatile u8 *device_context_bytes,u32 context_size,u8 port_count, + u8 tt_think_time) { + u64 input_context_physical; + volatile u8 *input_context_bytes; + KERNEL_XHCI_TRB completion; + u32 command_index=kernel_xhci_rings.CommandIndex; + if(!mmio||!capabilities||!slot_id||!device_context_bytes|| + !context_size||!port_count||command_index>=BOB64_XHCI_RING_TRBS-1) + return -1; + if(kernel_xhci_dma_alloc(1,&input_context_physical, + &input_context_bytes))return -2; + volatile u32 *input=(volatile u32 *)(volatile void *)input_context_bytes; + volatile u32 *slot=(volatile u32 *)(volatile void *)(input_context_bytes+ + context_size); + volatile u32 *live_slot=(volatile u32 *)(volatile void *)device_context_bytes; + input[1]=1u; /* Update the Slot Context. */ + for(u32 word=0;word>20)&0xfu; + slot[2]=(slot[2]&~(3u<<16))| + (speed==3u?((u32)(tt_think_time&3u)<<16):0u); + volatile KERNEL_XHCI_TRB *command= + &kernel_xhci_rings.CommandRing[command_index]; + command->Parameter=input_context_physical; + command->Status=0; + command->Control=(12u<DoorbellOffset-mmio->CapabilityLength; + if(kernel_xhci_write32(mmio,doorbell_offset,0))return -3; + int result=kernel_xhci_wait_event(mmio,capabilities, + BOB64_XHCI_TRB_TYPE_COMMAND_COMPLETION,10000000u,&completion); + if(result)return -4+result; + if(completion.Parameter!=kernel_xhci_rings.CommandPhysical+ + command_index*sizeof(KERNEL_XHCI_TRB)|| + (completion.Status>>24)!=BOB64_XHCI_TRB_COMPLETION_SUCCESS|| + (u8)(completion.Control>>24)!=slot_id)return -5; + kernel_xhci_rings.CommandIndex++; + return 0; +} + +static int kernel_xhci_configure_usb2_hub(KERNEL_XHCI_MMIO *mmio, + const BOB64_XHCI_CAPABILITIES *capabilities,u8 slot_id, + const KERNEL_XHCI_TOPOLOGY *topology, + volatile KERNEL_XHCI_TRB *transfer_ring,u64 transfer_ring_physical, + u64 descriptor_physical,volatile u8 *descriptor_bytes, + volatile u8 *device_context_bytes,u32 context_size,u8 configuration, + u8 *port_count_out,u32 *control_index_out) { + BOB64_USB_HUB_DESCRIPTOR hub; + u32 connected=0,reset=0,control_index=20; + if(!mmio||!capabilities||!slot_id||!topology||!transfer_ring|| + !port_count_out||!control_index_out|| + !descriptor_bytes) + return -1; + int result=kernel_xhci_control_no_data(mmio,capabilities,slot_id, + transfer_ring,transfer_ring_physical,12,0x00,9,configuration,0); + if(result)return -2+result; + result=kernel_xhci_control_in_data(mmio,capabilities,slot_id, + transfer_ring,transfer_ring_physical,descriptor_physical,0xa0,6, + 0x2900,0,7,14); + if(result)return -6+result; + if(descriptor_bytes[0]<7||descriptor_bytes[1]!=0x29)return -10; + result=kernel_xhci_control_in_data(mmio,capabilities,slot_id, + transfer_ring,transfer_ring_physical,descriptor_physical,0xa0,6, + 0x2900,0,descriptor_bytes[0],17); + if(result)return -11+result; + if(bob64_usb_parse_hub_descriptor((const void *)(uintptr_t)descriptor_bytes, + descriptor_bytes[0],&hub)) { + kernel_write("bob64 kernel: invalid USB hub descriptor len="); + kernel_hex64(descriptor_bytes[0]);kernel_write(" type="); + kernel_hex64(descriptor_bytes[1]);kernel_write(" ports="); + kernel_hex64(descriptor_bytes[2]);kernel_write(" raw="); + for(u32 i=0;i<12&&i16)return -16; + *port_count_out=hub.PortCount; + result=kernel_xhci_update_hub_context(mmio,capabilities,slot_id, + device_context_bytes,context_size,hub.PortCount, + (u8)((hub.Characteristics>>5)&3u)); + if(result)return -20+result; + if((hub.Characteristics&3u)<2u) { + for(u32 port=1;port<=hub.PortCount;port++) { + result=kernel_xhci_control_no_data(mmio,capabilities,slot_id, + transfer_ring,transfer_ring_physical,control_index,0x23,3,8, + (u16)port); + if(result)return -25+result; + control_index+=2; + } + u64 delay_ms=(u64)hub.PowerOnToGood*2u; + u64 delay_ticks=(delay_ms+9u)/10u; + if(kernel_xhci_delay_ticks(delay_ticks))return -26; + } + control_index=20u+((hub.Characteristics&3u)<2u? + (u32)hub.PortCount*2u:0u); + for(u32 port=1;port<=hub.PortCount;port++) { + result=kernel_xhci_control_in_data(mmio,capabilities,slot_id, + transfer_ring,transfer_ring_physical,descriptor_physical,0xa3,0, + 0,(u16)port,4,control_index); + if(result)return -30+result; + u16 port_status=(u16)(descriptor_bytes[0]|((u16)descriptor_bytes[1]<<8)); + control_index+=3; + if(port_status&1u) { + u16 port_change=(u16)(descriptor_bytes[2]|((u16)descriptor_bytes[3]<<8)); + connected++; + result=kernel_xhci_control_no_data(mmio,capabilities,slot_id, + transfer_ring,transfer_ring_physical,control_index,0x23,3,4, + (u16)port); + if(result)return -31+result; + control_index+=2; + if(kernel_xhci_delay_ticks(2))return -32; + result=kernel_xhci_control_in_data(mmio,capabilities,slot_id, + transfer_ring,transfer_ring_physical,descriptor_physical, + 0xa3,0,0,(u16)port,4,control_index); + if(result)return -33+result; + port_status=(u16)(descriptor_bytes[0]|((u16)descriptor_bytes[1]<<8)); + port_change=(u16)(descriptor_bytes[2]|((u16)descriptor_bytes[3]<<8)); + control_index+=3; + if((port_status&(1u<<4))||!(port_status&(1u<<1)))return -34; + reset++; + if(port_change&1u) { + result=kernel_xhci_control_no_data(mmio,capabilities,slot_id, + transfer_ring,transfer_ring_physical,control_index, + 0x23,1,16,(u16)port); + if(result)return -35+result; + control_index+=2; + } + if(port_change&(1u<<4)) { + result=kernel_xhci_control_no_data(mmio,capabilities,slot_id, + transfer_ring,transfer_ring_physical,control_index, + 0x23,1,20,(u16)port); + if(result)return -36+result; + control_index+=2; + } + if(kernel_xhci_hub_child_count< + sizeof(kernel_xhci_hub_children)/ + sizeof(kernel_xhci_hub_children[0])&& + topology->Depth<5u) { + u32 route=0; + u16 port_speed_bits=(u16)((port_status>>9)&3u); + u8 child_speed=port_speed_bits==2u?3u: + port_speed_bits==1u?2u:1u; + if(!bob64_usb_route_string_append(topology->RouteString, + topology->Depth,(u8)port,&route)) { + KERNEL_XHCI_TOPOLOGY *child= + &kernel_xhci_hub_children[ + kernel_xhci_hub_child_count++]; + child->RouteString=route; + child->RootPort=topology->RootPort; + child->ParentSlot=slot_id; + child->ParentPort=(u8)port; + child->Speed=child_speed; + child->Depth=(u8)(topology->Depth+1u); + child->TtHubSlot=topology->TtHubSlot; + child->TtPort=topology->TtPort; + if(topology->Speed==3u&&child_speed<3u) { + child->TtHubSlot=slot_id; + child->TtPort=(u8)port; + } + } + } + } + } + kernel_write("bob64 kernel: USB 2 hub configured ports="); + kernel_hex64(hub.PortCount);kernel_write(" connected="); + kernel_hex64(connected);kernel_write(" reset=");kernel_hex64(reset); + kernel_write("\r\n"); + *control_index_out=control_index; + return 0; +} + +static int kernel_xhci_configure_hub_status_endpoint(KERNEL_XHCI_MMIO *mmio, + const BOB64_XHCI_CAPABILITIES *capabilities,u8 slot_id, + const KERNEL_XHCI_TOPOLOGY *topology, + const BOB64_USB_HUB_INTERFACE *hub_interface,u8 port_count, + volatile u8 *device_context_bytes,u32 context_size, + volatile KERNEL_XHCI_TRB *control_ring,u64 control_ring_physical, + volatile u8 *control_buffer,u64 control_buffer_physical, + u32 control_next_index) { + KERNEL_XHCI_HUB_DEVICE *hub=0; + u64 ring_physical,report_physical,input_physical; + volatile u8 *ring_bytes,*report_bytes,*input_bytes; + u32 dci,report_length,interval,command_index,doorbell_offset; + KERNEL_XHCI_TRB completion; + if(!mmio||!capabilities||!slot_id||!topology||!hub_interface|| + !port_count||!device_context_bytes||!context_size||!control_ring|| + !control_buffer||!control_buffer_physical|| + !(hub_interface->EndpointAddress&0x80u)|| + (hub_interface->EndpointAttributes&3u)!=3u)return -1; + dci=((hub_interface->EndpointAddress&0x0fu)<<1)|1u; + report_length=((u32)port_count+1u+7u)/8u; + if(dci<2u||dci>31u||!report_length||report_length>16u|| + report_length>hub_interface->EndpointMaxPacketSize)return -2; + for(u32 i=0;iSpeed>=3u) + interval=hub_interface->EndpointInterval? + (u32)hub_interface->EndpointInterval-1u:0u; + else { + u32 period=hub_interface->EndpointInterval? + hub_interface->EndpointInterval:1u; + interval=3u; + while(period>1u&&interval<15u) { period=(period+1u)>>1;interval++; } + } + endpoint[0]=interval<<16; + endpoint[1]=(3u<<1)|(7u<<3)| + ((u32)hub_interface->EndpointMaxPacketSize<<16); + endpoint[2]=(u32)(ring_physical|1u); + endpoint[3]=(u32)(ring_physical>>32); + endpoint[4]=report_length|((u32)hub_interface->EndpointMaxPacketSize<<16); + command_index=kernel_xhci_rings.CommandIndex; + if(command_index>=BOB64_XHCI_RING_TRBS-1)return -5; + volatile KERNEL_XHCI_TRB *command= + &kernel_xhci_rings.CommandRing[command_index]; + command->Parameter=input_physical;command->Status=0; + command->Control=(12u<DoorbellOffset-mmio->CapabilityLength; + if(kernel_xhci_write32(mmio,doorbell_offset,0))return -6; + int result=kernel_xhci_wait_event(mmio,capabilities, + BOB64_XHCI_TRB_TYPE_COMMAND_COMPLETION,10000000u,&completion); + if(result)return -7+result; + if(completion.Parameter!=kernel_xhci_rings.CommandPhysical+ + command_index*sizeof(KERNEL_XHCI_TRB)|| + (completion.Status>>24)!=BOB64_XHCI_TRB_COMPLETION_SUCCESS|| + (u8)(completion.Control>>24)!=slot_id)return -8; + kernel_xhci_rings.CommandIndex++; + hub->Ring=ring;hub->RingPhysical=ring_physical; + hub->Report=report_bytes;hub->ReportPhysical=report_physical; + hub->NextIndex=0;hub->PendingIndex=0;hub->Slot=slot_id;hub->Dci=(u8)dci; + hub->ReportLength=(u8)report_length;hub->Cycle=1;hub->Pending=0; + hub->TransferErrors=0;hub->RootPort=topology->RootPort; + hub->Topology=*topology;hub->LoggedChange=0;hub->Active=1; + hub->PortCount=port_count; + hub->ControlRing=control_ring; + hub->ControlRingPhysical=control_ring_physical; + hub->ControlBuffer=control_buffer; + hub->ControlBufferPhysical=control_buffer_physical; + hub->ControlNextIndex=control_next_index; + hub->ControlCycle=1; + kernel_write("bob64 kernel: USB hub status endpoint configured; monitoring port changes\r\n"); + return kernel_xhci_hub_status_submit(hub); +} + +static int kernel_xhci_configure_storage_endpoints(KERNEL_XHCI_MMIO *mmio, + const BOB64_XHCI_CAPABILITIES *capabilities,u8 slot_id, + const KERNEL_XHCI_TOPOLOGY *topology, + const BOB64_USB_MASS_STORAGE *storage, + volatile u8 *device_context_bytes,u32 context_size) { + KERNEL_XHCI_STORAGE_DEVICE *device=0; + u64 input_physical,in_ring_physical,out_ring_physical,scratch_physical; + volatile u8 *input_bytes,*in_ring_bytes,*out_ring_bytes,*scratch_bytes; + KERNEL_XHCI_TRB completion; + u8 in_dci,out_dci; + u32 command_index,doorbell_offset; + if(!mmio||!capabilities||!slot_id||!topology||!storage|| + !device_context_bytes||(context_size!=32u&&context_size!=64u)|| + !(storage->BulkInEndpoint&0x80u)|| + (storage->BulkOutEndpoint&0x80u)|| + !storage->BulkInMaxPacketSize||!storage->BulkOutMaxPacketSize) + return -1; + in_dci=(u8)(((storage->BulkInEndpoint&0x0fu)<<1)|1u); + out_dci=(u8)((storage->BulkOutEndpoint&0x0fu)<<1); + if(in_dci<2u||out_dci<2u||in_dci>31u||out_dci>31u||in_dci==out_dci) + return -2; + for(u32 i=0;iout_dci?in_dci:out_dci; + slot[0]=(slot[0]&~(31u<<27))|(max_dci<<27); + in_endpoint[1]=(3u<<1)|(6u<<3)| + ((u32)storage->BulkInMaxPacketSize<<16); + in_endpoint[2]=(u32)(in_ring_physical|1u); + in_endpoint[3]=(u32)(in_ring_physical>>32); + in_endpoint[4]=1024u; + out_endpoint[1]=(3u<<1)|(2u<<3)| + ((u32)storage->BulkOutMaxPacketSize<<16); + out_endpoint[2]=(u32)(out_ring_physical|1u); + out_endpoint[3]=(u32)(out_ring_physical>>32); + out_endpoint[4]=1024u; + command_index=kernel_xhci_rings.CommandIndex; + if(command_index>=BOB64_XHCI_RING_TRBS-1)return -5; + volatile KERNEL_XHCI_TRB *command= + &kernel_xhci_rings.CommandRing[command_index]; + command->Parameter=input_physical;command->Status=0; + command->Control=(12u<DoorbellOffset-mmio->CapabilityLength; + if(kernel_xhci_write32(mmio,doorbell_offset,0))return -6; + int result=kernel_xhci_wait_event(mmio,capabilities, + BOB64_XHCI_TRB_TYPE_COMMAND_COMPLETION,10000000u,&completion); + if(result)return -7+result; + if(completion.Parameter!=kernel_xhci_rings.CommandPhysical+ + command_index*sizeof(KERNEL_XHCI_TRB)|| + (completion.Status>>24)!=BOB64_XHCI_TRB_COMPLETION_SUCCESS|| + (u8)(completion.Control>>24)!=slot_id)return -8; + kernel_xhci_rings.CommandIndex++; + device->BulkInRing=in_ring;device->BulkOutRing=out_ring; + device->BulkInRingPhysical=in_ring_physical; + device->BulkOutRingPhysical=out_ring_physical; + device->BulkInMaxPacketSize=storage->BulkInMaxPacketSize; + device->BulkOutMaxPacketSize=storage->BulkOutMaxPacketSize; + device->Slot=slot_id;device->BulkInDci=in_dci;device->BulkOutDci=out_dci; + device->BulkInNext=0;device->BulkOutNext=0; + device->BulkInCycle=1;device->BulkOutCycle=1;device->NextTag=0; + device->Scratch=scratch_bytes;device->ScratchPhysical=scratch_physical; + device->BlockSize=0;device->BlockCount=0;device->HasDataPartition=0; + device->Topology=*topology;device->Active=1; + kernel_write("bob64 kernel: USB mass-storage bulk endpoints configured slot="); + kernel_hex64(slot_id);kernel_write(" in=0x"); + kernel_hex64(storage->BulkInEndpoint);kernel_write(" out=0x"); + kernel_hex64(storage->BulkOutEndpoint);kernel_write(" packet="); + kernel_hex64(storage->BulkInMaxPacketSize);kernel_write("\r\n"); + int probe_result=kernel_xhci_storage_probe(device); + if(probe_result) { + kernel_write("bob64 kernel: USB MSC command probe failed result="); + kernel_hex64((u64)(s64)probe_result);kernel_write("\r\n"); + } + return 0; +} + +static int kernel_xhci_storage_bulk(KERNEL_XHCI_STORAGE_DEVICE *device, + int input,u64 buffer_physical,u32 length,u32 *actual_length) { + volatile KERNEL_XHCI_TRB *ring; + u64 ring_physical; + u32 *next; + u8 *cycle; + u8 dci; + if(!device||!device->Active||!length||length>BOB64_PAGE_SIZE|| + !actual_length)return -1; + if(input) { + ring=device->BulkInRing;ring_physical=device->BulkInRingPhysical; + next=&device->BulkInNext;cycle=&device->BulkInCycle;dci=device->BulkInDci; + } else { + ring=device->BulkOutRing;ring_physical=device->BulkOutRingPhysical; + next=&device->BulkOutNext;cycle=&device->BulkOutCycle;dci=device->BulkOutDci; + } + if(!ring||!ring_physical||*next>=BOB64_XHCI_RING_TRBS)return -2; + if(*next==BOB64_XHCI_RING_TRBS-1u) { + volatile KERNEL_XHCI_TRB *link=&ring[*next]; + link->Parameter=ring_physical;link->Status=0; + link->Control=(BOB64_XHCI_TRB_TYPE_LINK<Parameter=buffer_physical; + transfer->Status=length; + transfer->Control=(1u<Slot*4u; + if(kernel_xhci_write32(&kernel_xhci_live_mmio,doorbell,dci))return -3; + KERNEL_XHCI_TRB completion; + int result=kernel_xhci_wait_transfer(&kernel_xhci_live_mmio, + &kernel_xhci_live_capabilities,device->Slot,dci, + ring_physical+(u64)index*sizeof(KERNEL_XHCI_TRB),10000000u, + &completion); + if(result)return -4+result; + u32 code=completion.Status>>24; + u32 residual=completion.Status&0x00ffffffu; + if((code!=BOB64_XHCI_TRB_COMPLETION_SUCCESS&&code!=13u)|| + residual>length)return -8; + *actual_length=length-residual; + return 0; +} + +static int kernel_xhci_storage_command_internal( + KERNEL_XHCI_STORAGE_DEVICE *device, + const u8 *cdb,u8 cdb_length,int device_to_host,u32 data_length, + void *data,u32 *actual_data,int allow_check_condition_recovery); + +static int kernel_xhci_storage_command_internal( + KERNEL_XHCI_STORAGE_DEVICE *device, + const u8 *cdb,u8 cdb_length,int device_to_host,u32 data_length, + void *data,u32 *actual_data,int allow_check_condition_recovery) { + if(!device||!device->Active||!device->Scratch||!device->ScratchPhysical|| + !cdb||!data||!actual_data||data_length>BOB64_PAGE_SIZE)return -1; + volatile u8 *scratch=device->Scratch; + u32 tag=++device->NextTag; + if(!tag)tag=++device->NextTag; + if(bob64_usb_msc_build_cbw((void *)(uintptr_t)scratch, + BOB64_USB_MSC_CBW_SIZE,tag,data_length,device_to_host,0,cdb,cdb_length)) + return -2; + u32 actual=0,data_actual=0; + int result=kernel_xhci_storage_bulk(device,0,device->ScratchPhysical, + BOB64_USB_MSC_CBW_SIZE,&actual); + if(result||actual!=BOB64_USB_MSC_CBW_SIZE) { + kernel_write("bob64 kernel: USB MSC CBW transfer failed result="); + kernel_hex64((u64)(s64)result);kernel_write(" bytes="); + kernel_hex64(actual);kernel_write("\r\n"); + return -3; + } + if(data_length) { + if(!device_to_host) + for(u32 i=0;iBlockSize) + device->DisconnectTestReadPending=1; +#endif + result=kernel_xhci_storage_bulk(device,device_to_host, + device->ScratchPhysical,data_length,&actual); +#ifdef BOB64_STORAGE_ACTIVE_DISCONNECT_TEST + device->DisconnectTestReadPending=0; +#endif + if(result) { + kernel_write("bob64 kernel: USB MSC data transfer failed result="); + kernel_hex64((u64)(s64)result);kernel_write(" input="); + kernel_hex64((u64)(device_to_host!=0));kernel_write("\r\n"); + return -4; + } + data_actual=actual; + } + actual=0; + result=kernel_xhci_storage_bulk(device,1, + device->ScratchPhysical+BOB64_PAGE_SIZE,BOB64_USB_MSC_CSW_SIZE,&actual); + if(result||actual!=BOB64_USB_MSC_CSW_SIZE) { + kernel_write("bob64 kernel: USB MSC CSW transfer failed result="); + kernel_hex64((u64)(s64)result);kernel_write(" bytes="); + kernel_hex64(actual);kernel_write("\r\n"); + return -5; + } + u32 residue=0; + u8 status=0xff; + if(bob64_usb_msc_parse_csw((const void *)(uintptr_t) + (scratch+BOB64_PAGE_SIZE),BOB64_USB_MSC_CSW_SIZE,tag,data_length, + &residue,&status)) { + kernel_write("bob64 kernel: USB MSC CSW validation failed tag="); + kernel_hex64(tag);kernel_write(" status=");kernel_hex64(status); + kernel_write(" residue=");kernel_hex64(residue);kernel_write("\r\n"); + return -6; + } + if(status!=0) { + kernel_write("bob64 kernel: USB MSC SCSI command status="); + kernel_hex64(status);kernel_write(" opcode="); + kernel_hex64(cdb[0]);kernel_write(" residue="); + kernel_hex64(residue);kernel_write("\r\n"); + if(status==1u&&allow_check_condition_recovery&&cdb[0]!=0x03u) { + u8 sense_cdb[6]={0x03,0,0,0,18,0}; + u8 sense[18]={0}; + u32 sense_actual=0; + int sense_result=kernel_xhci_storage_command_internal(device, + sense_cdb,sizeof(sense_cdb),1,sizeof(sense),sense, + &sense_actual,0); + if(sense_result||sense_actual<14u) { + kernel_write("bob64 kernel: USB MSC REQUEST SENSE failed result="); + kernel_hex64((u64)(s64)sense_result);kernel_write(" bytes="); + kernel_hex64(sense_actual);kernel_write("\r\n"); + return -6; + } + kernel_write("bob64 kernel: USB MSC sense key="); + kernel_hex64(sense[2]&0x0fu);kernel_write(" asc="); + kernel_hex64(sense[12]);kernel_write(" ascq="); + kernel_hex64(sense[13]);kernel_write("; retrying once\r\n"); + return kernel_xhci_storage_command_internal(device,cdb,cdb_length, + device_to_host,data_length,data,actual_data,0); + } + return -6; + } + if(data_length&&data_actual+residue!=data_length) { + kernel_write("bob64 kernel: USB MSC data residue mismatch actual="); + kernel_hex64(data_actual);kernel_write(" residue="); + kernel_hex64(residue);kernel_write(" expected="); + kernel_hex64(data_length);kernel_write("\r\n"); + return -7; + } + if(data_length&&device_to_host) { + for(u32 i=0;iBlockSize||!block_count||!buffer|| + (u64)block_count*device->BlockSize>BOB64_PAGE_SIZE|| + lba>=device->BlockCount||block_count>device->BlockCount-lba|| + bob64_scsi_build_read_write_cdb(lba,block_count,0,cdb,&cdb_length)) + return -1; + length=(u32)block_count*device->BlockSize; + int result=kernel_xhci_storage_command(device,cdb,cdb_length,1, + length,buffer,&actual); + return result?result:(actual==length?0:-2); +} + +static int kernel_xhci_storage_write_blocks_raw(KERNEL_XHCI_STORAGE_DEVICE *device, + u64 lba,u32 block_count,void *buffer) { + u8 cdb[16],cdb_length=0; + u32 length,actual=0; + if(!device||!device->BlockSize||!block_count||!buffer|| + (u64)block_count*device->BlockSize>BOB64_PAGE_SIZE|| + lba>=device->BlockCount||block_count>device->BlockCount-lba|| + bob64_scsi_build_read_write_cdb(lba,block_count,1,cdb,&cdb_length)) + return -1; + length=(u32)block_count*device->BlockSize; + int result=kernel_xhci_storage_command(device,cdb,cdb_length,0, + length,buffer,&actual); + return result?result:(actual==length?0:-2); +} + +static int kernel_xhci_storage_sync_raw(KERNEL_XHCI_STORAGE_DEVICE *device) { + u8 cdb[10]={0x35}; + u8 no_data=0; + u32 actual=0; + if(!device||!device->Active)return -1; + return kernel_xhci_storage_command(device,cdb,sizeof(cdb),1,0, + &no_data,&actual); +} + +static int kernel_xhci_storage_block_read(void *context,u64 lba,u32 count, + void *buffer) { + KERNEL_XHCI_STORAGE_DEVICE *device=(KERNEL_XHCI_STORAGE_DEVICE *)context; + return kernel_xhci_storage_read_blocks_raw(device,lba,count,buffer); +} + +static int kernel_xhci_storage_block_write(void *context,u64 lba,u32 count, + const void *buffer) { + KERNEL_XHCI_STORAGE_DEVICE *device=(KERNEL_XHCI_STORAGE_DEVICE *)context; + return kernel_xhci_storage_write_blocks_raw(device,lba,count,(void *)buffer); +} + +static int kernel_xhci_storage_block_flush(void *context) { + return kernel_xhci_storage_sync_raw( + (KERNEL_XHCI_STORAGE_DEVICE *)context); +} + +static int kernel_xhci_storage_probe(KERNEL_XHCI_STORAGE_DEVICE *device) { + u8 inquiry_cdb[6]={0x12,0,0,0,36,0}; + u8 capacity_cdb[16]={0x25}; + u8 inquiry[36],capacity[32]; + u64 block_count=0; + u32 block_size=0; + int needs_capacity16=0; + u32 actual=0; + if(!device||!device->Active||device->BlockSize)return -1; + int result=kernel_xhci_storage_command(device,inquiry_cdb,sizeof(inquiry_cdb), + 1,sizeof(inquiry),inquiry,&actual); + if(result||actual!=sizeof(inquiry))return -2; + result=kernel_xhci_storage_command(device,capacity_cdb,10,1,8,capacity, + &actual); + if(result||actual!=8)return -3; + if(bob64_scsi_parse_read_capacity10(capacity,8,&block_count,&block_size, + &needs_capacity16))return -4; + if(needs_capacity16) { + bob64_scsi_build_read_capacity16_cdb(capacity_cdb); + result=kernel_xhci_storage_command(device,capacity_cdb,16,1,32, + capacity,&actual); + if(result||actual!=32||bob64_scsi_parse_read_capacity16(capacity,32, + &block_count,&block_size))return -3; + } + if(!block_size||block_size>BOB64_PAGE_SIZE)return -4; + device->BlockSize=block_size;device->BlockCount=block_count; +#ifdef BOB64_STORAGE_WRITE_TEST + int initial_read_only=0; +#else + int initial_read_only=1; +#endif + if(bob64_block_device_init(&device->BlockDevice,device,device->BlockCount, + block_size,initial_read_only,kernel_xhci_storage_block_read, + kernel_xhci_storage_block_write,kernel_xhci_storage_block_flush)) + return -4; + kernel_write("bob64 kernel: USB block device registered sectors="); + kernel_hex64(device->BlockCount);kernel_write(" sector-bytes="); + kernel_hex64(device->BlockSize);kernel_write(" access="); + kernel_write(device->BlockDevice.ReadOnly?"read-only\r\n":"read-write\r\n"); + BOB64_PARTITION partition; + int partition_result=bob64_gpt_find_partition(&device->BlockDevice, + bob64_gpt_bob_data_type_guid,&partition); + if(!partition_result) { + device->DataPartition=partition;device->HasDataPartition=1; + if(bob64_block_device_init(&device->BlockDevice,device, + device->BlockCount,block_size,0,kernel_xhci_storage_block_read, + kernel_xhci_storage_block_write,kernel_xhci_storage_block_flush)) + return -4; + kernel_write("bob64 kernel: dedicated data partition enables writes\r\n"); + kernel_write("bob64 kernel: GPT bob64 data partition found first-lba="); + kernel_hex64(partition.FirstLba);kernel_write(" blocks="); + kernel_hex64(partition.BlockCount);kernel_write("\r\n"); + } else if(partition_result==1) { + kernel_write("bob64 kernel: GPT bob64 data partition absent\r\n"); + } else { + kernel_write("bob64 kernel: GPT data partition table invalid result="); + kernel_hex64((u64)(s64)partition_result);kernel_write("\r\n"); + } + if(bob64_block_read(&device->BlockDevice,device->BlockCount,1, + (void *)(uintptr_t)device->Scratch)!=-1)return -5; + result=bob64_block_read(&device->BlockDevice,0,1, + (void *)(uintptr_t)device->Scratch); + if(result)return -6; + actual=block_size; + kernel_write("bob64 kernel: USB MSC READ CAPACITY passed blocks="); + kernel_hex64(device->BlockCount);kernel_write(" sector-bytes="); + kernel_hex64(device->BlockSize);kernel_write("\r\n"); + kernel_write("bob64 kernel: USB MSC sector-read passed lba=0 bytes="); + kernel_hex64(actual);kernel_write("\r\n"); +#ifdef BOB64_STORAGE_LBA64_TEST + if(device->BlockCount<=0x100000000ULL)return -13; + result=bob64_block_read(&device->BlockDevice,0x100000000ULL,1, + (void *)(uintptr_t)device->Scratch); + if(result)return -14; + for(u32 i=0;iScratch[i]!=(u8)(i*53u+0xa7u))return -15; + kernel_write("bob64 kernel: USB MSC high-LBA READ(16) passed lba=0000000100000000\r\n"); +#endif +#ifdef BOB64_STORAGE_WRITE_TEST + if(device->BlockCount<2u||block_size>BOB64_PAGE_SIZE)return -7; + volatile u8 *write_buffer=device->Scratch+BOB64_PAGE_SIZE; + volatile u8 *read_buffer=device->Scratch; + for(u32 i=0;iBlockDevice,1,1, + (void *)(uintptr_t)write_buffer); + if(result)return -8; + result=bob64_block_flush(&device->BlockDevice); + if(result)return -12; + if(bob64_block_write(&device->BlockDevice,device->BlockCount,1, + (void *)(uintptr_t)write_buffer)!=-1)return -11; + result=bob64_block_read(&device->BlockDevice,1,1, + (void *)(uintptr_t)read_buffer); + if(result)return -9; + for(u32 i=0;iControlRing||trb_count>3u|| + hub->ControlNextIndex>=BOB64_XHCI_RING_TRBS)return 0xffffffffu; + if(hub->ControlNextIndex+trb_count>BOB64_XHCI_RING_TRBS-1u) { + volatile KERNEL_XHCI_TRB *link= + &hub->ControlRing[hub->ControlNextIndex]; + link->Parameter=hub->ControlRingPhysical;link->Status=0; + link->Control=(BOB64_XHCI_TRB_TYPE_LINK<ControlCycle; + hub->ControlNextIndex=0; + hub->ControlCycle^=1u; + } + u32 index=hub->ControlNextIndex; + hub->ControlNextIndex+=trb_count; + return index; +} + +static int kernel_xhci_hub_control_in(KERNEL_XHCI_HUB_DEVICE *hub, + u8 request_type,u8 request,u16 value,u16 index,u16 length) { + KERNEL_XHCI_TRB completion; + if(!hub||!hub->Active||!length||length>BOB64_PAGE_SIZE)return -1; + u32 ring_index=kernel_xhci_hub_control_reserve(hub,3u); + if(ring_index==0xffffffffu)return -2; + u32 cycle=hub->ControlCycle; + volatile KERNEL_XHCI_TRB *ring=hub->ControlRing; + ring[ring_index].Parameter=bob64_usb_control_setup(request_type,request, + value,index,length); + ring[ring_index].Status=8; + ring[ring_index].Control=(2u<ControlBufferPhysical; + ring[ring_index+1].Status=length; + ring[ring_index+1].Control=(3u<Slot*4u; + if(kernel_xhci_write32(&kernel_xhci_live_mmio,doorbell,1u))return -3; + int result=kernel_xhci_wait_event(&kernel_xhci_live_mmio, + &kernel_xhci_live_capabilities,BOB64_XHCI_TRB_TYPE_TRANSFER_EVENT, + 10000000u,&completion); + if(result)return -4+result; + if((completion.Status>>24)!=BOB64_XHCI_TRB_COMPLETION_SUCCESS|| + (u8)(completion.Control>>24)!=hub->Slot|| + ((completion.Control>>16)&0x1fu)!=1u|| + completion.Parameter!=hub->ControlRingPhysical+ + (ring_index+2u)*sizeof(KERNEL_XHCI_TRB))return -8; + return 0; +} + +static int kernel_xhci_hub_control_no_data(KERNEL_XHCI_HUB_DEVICE *hub, + u8 request_type,u8 request,u16 value,u16 index) { + KERNEL_XHCI_TRB completion; + if(!hub||!hub->Active)return -1; + u32 ring_index=kernel_xhci_hub_control_reserve(hub,2u); + if(ring_index==0xffffffffu)return -2; + u32 cycle=hub->ControlCycle; + volatile KERNEL_XHCI_TRB *ring=hub->ControlRing; + ring[ring_index].Parameter=bob64_usb_control_setup(request_type,request, + value,index,0); + ring[ring_index].Status=8; + ring[ring_index].Control=(2u<Slot*4u; + if(kernel_xhci_write32(&kernel_xhci_live_mmio,doorbell,1u))return -3; + int result=kernel_xhci_wait_event(&kernel_xhci_live_mmio, + &kernel_xhci_live_capabilities,BOB64_XHCI_TRB_TYPE_TRANSFER_EVENT, + 10000000u,&completion); + if(result)return -4+result; + if((completion.Status>>24)!=BOB64_XHCI_TRB_COMPLETION_SUCCESS|| + (u8)(completion.Control>>24)!=hub->Slot|| + ((completion.Control>>16)&0x1fu)!=1u|| + completion.Parameter!=hub->ControlRingPhysical+ + (ring_index+1u)*sizeof(KERNEL_XHCI_TRB))return -8; + return 0; +} + +static int kernel_xhci_address_and_read_descriptor(KERNEL_XHCI_MMIO *mmio, + const BOB64_XHCI_CAPABILITIES *capabilities,u8 slot_id, + const KERNEL_XHCI_TOPOLOGY *topology) { + u64 device_context_physical,input_context_physical; + u64 transfer_ring_physical,descriptor_physical; + volatile u8 *device_context_bytes,*input_context_bytes; + volatile u8 *transfer_ring_bytes,*descriptor_bytes; + KERNEL_XHCI_HID_DEVICE *hid_device; + u32 context_size=(capabilities->HccParameters1&(1u<<2))?64u:32u; + u32 command_index=kernel_xhci_rings.CommandIndex; + u32 doorbell_offset; + u16 max_packet; + u8 hub_port_count=0; + u32 hub_control_index=0; + KERNEL_XHCI_TRB completion; + if(!mmio||!capabilities||!slot_id||!topology||!topology->RootPort|| + topology->Speed<1||topology->Speed>5|| + !kernel_xhci_rings.DeviceContextArray|| + command_index>=BOB64_XHCI_RING_TRBS-1)return -1; + if(topology->Speed==1)max_packet=8; + else if(topology->Speed==2)max_packet=8; + else if(topology->Speed==3)max_packet=64; + else max_packet=512; + if(kernel_xhci_dma_alloc(1,&device_context_physical, + &device_context_bytes)|| + kernel_xhci_dma_alloc(1,&input_context_physical, + &input_context_bytes)|| + kernel_xhci_dma_alloc(1,&transfer_ring_physical, + &transfer_ring_bytes)|| + kernel_xhci_dma_alloc(1,&descriptor_physical,&descriptor_bytes))return -2; + kernel_xhci_rings.DeviceContextArray[slot_id]=device_context_physical; + volatile u32 *input=(volatile u32 *)(volatile void *)input_context_bytes; + volatile u32 *slot=(volatile u32 *)(volatile void *)(input_context_bytes+ + context_size); + volatile u32 *endpoint0=(volatile u32 *)(volatile void *)(input_context_bytes+ + 2u*context_size); + input[1]=(1u<<0)|(1u<<1); /* Add the Slot and Endpoint 0 contexts. */ + slot[0]=(topology->RouteString&0x000fffffu)| + ((u32)topology->Speed<<20)|(1u<<27); + slot[1]=(u32)topology->RootPort<<16; + if(topology->TtHubSlot&&topology->TtPort&&topology->Speed<3u) { + slot[2]=(u32)topology->TtHubSlot| + ((u32)topology->TtPort<<8); + } + endpoint0[1]=(3u<<1)|(4u<<3)|((u32)max_packet<<16); + endpoint0[2]=(u32)(transfer_ring_physical|1u); + endpoint0[3]=(u32)(transfer_ring_physical>>32); + endpoint0[4]=8u; + volatile KERNEL_XHCI_TRB *command= + &kernel_xhci_rings.CommandRing[command_index]; + command->Parameter=input_context_physical; + command->Status=0; + command->Control=(11u<DoorbellOffset-mmio->CapabilityLength; + if(kernel_xhci_write32(mmio,doorbell_offset,0))return -3; + int result=kernel_xhci_wait_event(mmio,capabilities, + BOB64_XHCI_TRB_TYPE_COMMAND_COMPLETION,10000000u,&completion); + if(result)return -4+result; + if(completion.Parameter!=kernel_xhci_rings.CommandPhysical+ + command_index*sizeof(KERNEL_XHCI_TRB)|| + (completion.Status>>24)!=BOB64_XHCI_TRB_COMPLETION_SUCCESS|| + (u8)(completion.Control>>24)!=slot_id)return -5; + kernel_xhci_rings.CommandIndex++; + volatile KERNEL_XHCI_TRB *transfer_ring= + (volatile KERNEL_XHCI_TRB *)(volatile void *)transfer_ring_bytes; + transfer_ring[BOB64_XHCI_RING_TRBS-1].Parameter=transfer_ring_physical; + transfer_ring[BOB64_XHCI_RING_TRBS-1].Status=0; + transfer_ring[BOB64_XHCI_RING_TRBS-1].Control= + (BOB64_XHCI_TRB_TYPE_LINK<>24)!=BOB64_XHCI_TRB_COMPLETION_SUCCESS|| + (u8)(completion.Control>>24)!=slot_id|| + ((completion.Control>>16)&0x1fu)!=1u|| + completion.Parameter!=transfer_ring_physical+ + 2u*sizeof(KERNEL_XHCI_TRB))return -8; + if(descriptor_bytes[0]<8||descriptor_bytes[1]!=1|| + descriptor_bytes[7]!=(topology->Speed>=4u?9u:max_packet))return -9; + transfer_ring[3].Parameter=0x0012000001000680ULL; + transfer_ring[3].Status=8u; + transfer_ring[3].Control=(2u<>24)!=BOB64_XHCI_TRB_COMPLETION_SUCCESS|| + (u8)(completion.Control>>24)!=slot_id|| + ((completion.Control>>16)&0x1fu)!=1u|| + completion.Parameter!=transfer_ring_physical+ + 5u*sizeof(KERNEL_XHCI_TRB))return -12; + if(descriptor_bytes[0]!=18||descriptor_bytes[1]!=1|| + descriptor_bytes[7]!=(topology->Speed>=4u?9u:max_packet))return -13; + u16 vendor_id=(u16)(descriptor_bytes[8]|((u16)descriptor_bytes[9]<<8)); + u16 product_id=(u16)(descriptor_bytes[10]|((u16)descriptor_bytes[11]<<8)); + kernel_write("bob64 kernel: USB device addressed; descriptor type="); + kernel_hex64(descriptor_bytes[1]);kernel_write(" EP0 packet="); + kernel_hex64(descriptor_bytes[7]);kernel_write(" VID=0x"); + kernel_hex64(vendor_id); + kernel_write(" PID=0x"); + kernel_hex64(product_id); + kernel_write("\r\n"); + result=kernel_xhci_get_descriptor(mmio,capabilities,slot_id,transfer_ring, + transfer_ring_physical,descriptor_physical,2,9,6); + if(result)return -14+result; + if(descriptor_bytes[0]<9||descriptor_bytes[1]!=2)return -18; + u16 configuration_length=(u16)(descriptor_bytes[2]|((u16)descriptor_bytes[3]<<8)); + if(configuration_length<9||configuration_length>BOB64_PAGE_SIZE)return -19; + result=kernel_xhci_get_descriptor(mmio,capabilities,slot_id,transfer_ring, + transfer_ring_physical,descriptor_physical,2,configuration_length,9); + if(result)return -20+result; + BOB64_USB_HUB_INTERFACE hub_interface; + result=bob64_usb_find_hub_interface( + (const void *)(uintptr_t)descriptor_bytes,configuration_length, + &hub_interface); + if(result<0)return -21+result; + if(!result) { + u8 child_count_before=kernel_xhci_hub_child_count; + result=kernel_xhci_configure_usb2_hub(mmio,capabilities,slot_id, + topology,transfer_ring,transfer_ring_physical,descriptor_physical, + descriptor_bytes,device_context_bytes,context_size, + hub_interface.ConfigurationValue,&hub_port_count, + &hub_control_index); + if(result) { + kernel_xhci_hub_child_count=child_count_before; + kernel_write("bob64 kernel: USB hub initialization failed result="); + kernel_hex64((u64)(s64)result);kernel_write("\r\n"); + } else { + result=kernel_xhci_configure_hub_status_endpoint(mmio,capabilities, + slot_id,topology,&hub_interface,hub_port_count, + device_context_bytes,context_size,transfer_ring, + transfer_ring_physical,descriptor_bytes,descriptor_physical, + hub_control_index); + if(result) { + kernel_write("bob64 kernel: USB hub change monitoring unavailable result="); + kernel_hex64((u64)(s64)result);kernel_write("\r\n"); + } + } + return 0; + } + BOB64_USB_MASS_STORAGE storage; + result=bob64_usb_find_mass_storage( + (const void *)(uintptr_t)descriptor_bytes,configuration_length, + &storage); + if(result<0)return -23+result; + if(!result) { + kernel_write("bob64 kernel: USB mass-storage BOT interface found config="); + kernel_hex64(storage.ConfigurationValue);kernel_write(" interface="); + kernel_hex64(storage.InterfaceNumber);kernel_write(" in=0x"); + kernel_hex64(storage.BulkInEndpoint);kernel_write(" out=0x"); + kernel_hex64(storage.BulkOutEndpoint);kernel_write("\r\n"); + result=kernel_xhci_control_no_data(mmio,capabilities,slot_id, + transfer_ring,transfer_ring_physical,12,0x00,9, + storage.ConfigurationValue,0); + if(result) { + kernel_write("bob64 kernel: USB storage SET_CONFIGURATION failed result="); + kernel_hex64((u64)(s64)result);kernel_write("\r\n"); + return -24+result; + } + result=kernel_xhci_configure_storage_endpoints(mmio,capabilities, + slot_id,topology,&storage,device_context_bytes,context_size); + if(result) { + kernel_write("bob64 kernel: USB storage endpoint setup failed result="); + kernel_hex64((u64)(s64)result);kernel_write("\r\n"); + return -25+result; + } + return 0; + } + BOB64_USB_HID_BOOT_DEVICE hid; + u8 endpoint_dci,hid_kind,report_length; + result=bob64_usb_find_hid_boot_keyboard( + (const void *)(uintptr_t)descriptor_bytes,configuration_length,&hid); + if(result<0)return -25+result; + if(!result) { hid_kind=1;report_length=8; } + else { + result=bob64_usb_find_hid_boot_mouse( + (const void *)(uintptr_t)descriptor_bytes,configuration_length,&hid); + if(result)return -27+result; + hid_kind=2; + report_length=hid.EndpointMaxPacketSize>=4?4:3; + } + u32 hid_device_index=kernel_xhci_hid_device_count; + for(u32 i=0;i=KERNEL_XHCI_HID_DEVICE_LIMIT)return -28; + hid_device=&kernel_xhci_hid_devices[hid_device_index]; + endpoint_dci=(u8)(((hid.EndpointAddress&0x0fu)<<1)| + ((hid.EndpointAddress&0x80u)?1u:0u)); + if(endpoint_dci<2||endpoint_dci>31)return -26; + kernel_write("bob64 kernel: USB HID boot "); + kernel_write(hid_kind==1?"keyboard":"mouse"); + kernel_write(" endpoint found address=0x"); + kernel_hex64(hid.EndpointAddress);kernel_write(" packet="); + kernel_hex64(hid.EndpointMaxPacketSize);kernel_write(" interval="); + kernel_hex64(hid.EndpointInterval);kernel_write(" config="); + kernel_hex64(hid.ConfigurationValue);kernel_write("\r\n"); + /* Select the USB configuration and ask the HID interface for boot reports. */ + result=kernel_xhci_control_no_data(mmio,capabilities,slot_id,transfer_ring, + transfer_ring_physical,12,0x00,9,hid.ConfigurationValue,0); + if(result) { + kernel_write("bob64 kernel: USB SET_CONFIGURATION failed result="); + kernel_hex64((u64)(s64)result);kernel_write("\r\n"); + return -30+result; + } + result=kernel_xhci_control_no_data(mmio,capabilities,slot_id,transfer_ring, + transfer_ring_physical,14,0x21,0x0b,0,hid.InterfaceNumber); + if(result) { + kernel_write("bob64 kernel: USB HID SET_PROTOCOL failed result="); + kernel_hex64((u64)(s64)result);kernel_write("\r\n"); + return -35+result; + } + + /* Add the interrupt-IN endpoint (EP1 IN is DCI 3) to the live device. */ + u64 endpoint_ring_physical; + volatile u8 *endpoint_ring_bytes; + if(kernel_xhci_dma_alloc(1,&endpoint_ring_physical,&endpoint_ring_bytes)) + return -40; + volatile KERNEL_XHCI_TRB *endpoint_ring= + (volatile KERNEL_XHCI_TRB *)(volatile void *)endpoint_ring_bytes; + endpoint_ring[BOB64_XHCI_RING_TRBS-1].Parameter=endpoint_ring_physical; + endpoint_ring[BOB64_XHCI_RING_TRBS-1].Status=0; + endpoint_ring[BOB64_XHCI_RING_TRBS-1].Control= + (BOB64_XHCI_TRB_TYPE_LINK<Speed>=3)interval=hid.EndpointInterval? + (u32)hid.EndpointInterval-1u:0u; + else { + u32 period=hid.EndpointInterval?hid.EndpointInterval:1u; + interval=3; + while(period>1u&&interval<15u) { period=(period+1u)>>1;interval++; } + } + endpoint[0]=interval<<16; + endpoint[1]=(3u<<1)|(7u<<3)| + ((u32)hid.EndpointMaxPacketSize<<16); + endpoint[2]=(u32)(endpoint_ring_physical|1u); + endpoint[3]=(u32)(endpoint_ring_physical>>32); + endpoint[4]=(u32)report_length|((u32)hid.EndpointMaxPacketSize<<16); + command_index=kernel_xhci_rings.CommandIndex; + if(command_index>=BOB64_XHCI_RING_TRBS-1)return -42; + command=&kernel_xhci_rings.CommandRing[command_index]; + command->Parameter=input_context_physical; + command->Status=0; + command->Control=(12u<DoorbellOffset-mmio->CapabilityLength; + if(kernel_xhci_write32(mmio,doorbell_offset,0))return -43; + result=kernel_xhci_wait_event(mmio,capabilities, + BOB64_XHCI_TRB_TYPE_COMMAND_COMPLETION,10000000u,&completion); + if(result)return -44+result; + if(completion.Parameter!=kernel_xhci_rings.CommandPhysical+ + command_index*sizeof(KERNEL_XHCI_TRB)|| + (completion.Status>>24)!=BOB64_XHCI_TRB_COMPLETION_SUCCESS|| + (u8)(completion.Control>>24)!=slot_id)return -45; + kernel_xhci_rings.CommandIndex++; + u64 report_physical; + volatile u8 *report_bytes; + if(kernel_xhci_dma_alloc(1,&report_physical,&report_bytes))return -46; + hid_device->Ring=endpoint_ring; + hid_device->RingPhysical=endpoint_ring_physical; + hid_device->Report=report_bytes; + hid_device->ReportPhysical=report_physical; + hid_device->Slot=slot_id;hid_device->Dci=endpoint_dci; + hid_device->Kind=hid_kind;hid_device->ReportLength=report_length; + hid_device->Cycle=1;hid_device->NextIndex=0; + hid_device->Pending=0;hid_device->Active=1; + hid_device->TransferErrors=0; + hid_device->RootPort=topology->RootPort; + hid_device->Topology=*topology; + hid_device->LoggedReport=hid_device->LoggedInput=hid_device->LoggedWheel=0; + hid_device->KeyboardState=(BOB64_KEYBOARD_HID_STATE){0}; + if(kernel_xhci_hid_device_count<=hid_device_index) + kernel_xhci_hid_device_count=(u8)(hid_device_index+1u); + kernel_write("bob64 kernel: USB HID boot "); + kernel_write(hid_kind==1?"keyboard":"mouse"); + kernel_write(" endpoint configured; waiting for input report\r\n"); + return 0; +} + +static void kernel_xhci_address_hub_children( + KERNEL_XHCI_MMIO *mmio, + const BOB64_XHCI_CAPABILITIES *capabilities,u32 start_index) { + u32 index=start_index,limit=capabilities->MaxSlots; + if(limit>KERNEL_XHCI_HID_DEVICE_LIMIT)limit=KERNEL_XHCI_HID_DEVICE_LIMIT; + while(index5u||topology->RootPort!=root_port|| + topology->DepthRouteString&mask)==route; +} + +static void kernel_xhci_hub_remove_subtree(KERNEL_XHCI_HUB_DEVICE *parent, + u32 route,u8 depth) { + if(!parent)return; + for(u32 i=0;iActive&&kernel_xhci_topology_in_subtree(&device->Topology, + parent->RootPort,route,depth)) + kernel_xhci_hid_disconnect(device,i); + } + for(u32 i=0;iActive&&kernel_xhci_topology_in_subtree(&hub->Topology, + parent->RootPort,route,depth)) { + hub->Active=0;hub->Pending=0; + (void)kernel_xhci_disable_slot(hub->Slot); + } + } + for(u32 i=0;iRootPort,route,depth)) + kernel_xhci_hub_children[i].RootPort=0; +} + +static void kernel_xhci_hub_process_changes(KERNEL_XHCI_HUB_DEVICE *hub) { + if(!hub||!hub->Active)return; + for(u32 port=1;port<=hub->PortCount;port++) { + u32 byte=port>>3,bit=port&7u; + if(byte>=hub->ReportLength||!(hub->Report[byte]&(1u<ControlBuffer[0]|((u16)hub->ControlBuffer[1]<<8)); + u16 change=(u16)(hub->ControlBuffer[2]|((u16)hub->ControlBuffer[3]<<8)); + if(change) { + kernel_write("bob64 kernel: USB hub changed port=");kernel_hex64(port); + kernel_write(" status=0x");kernel_hex64(status); + kernel_write(" change=0x");kernel_hex64(change);kernel_write("\r\n"); + } + u32 child_route=0; + u8 child_depth=(u8)(hub->Topology.Depth+1u); + if((change&1u)&&!bob64_usb_route_string_append(hub->Topology.RouteString, + hub->Topology.Depth,(u8)port,&child_route)) { + kernel_xhci_hub_remove_subtree(hub,child_route,child_depth); + if(status&1u) { + result=kernel_xhci_hub_control_no_data(hub,0x23,3,4,(u16)port); + if(!result)result=kernel_xhci_delay_ticks(2); + if(!result)result=kernel_xhci_hub_control_in(hub, + 0xa3,0,0,(u16)port,4); + if(result) { + kernel_write("bob64 kernel: USB hub port reset failed port="); + kernel_hex64(port);kernel_write(" result="); + kernel_hex64((u64)(s64)result);kernel_write("\r\n"); + } else { + status=(u16)(hub->ControlBuffer[0]| + ((u16)hub->ControlBuffer[1]<<8)); + change|=(u16)(hub->ControlBuffer[2]| + ((u16)hub->ControlBuffer[3]<<8)); + if(!(status&(1u<<1))) { + kernel_write("bob64 kernel: USB hub port did not enable after reset port="); + kernel_hex64(port);kernel_write("\r\n"); + } else { + u16 speed_bits=(u16)((status>>9)&3u); + KERNEL_XHCI_TOPOLOGY child={0}; + child.RootPort=hub->RootPort; + child.ParentSlot=hub->Slot; + child.ParentPort=(u8)port; + child.RouteString=child_route; + child.Depth=child_depth; + child.Speed=speed_bits==2u?3u: + speed_bits==1u?2u:1u; + child.TtHubSlot=hub->Topology.TtHubSlot; + child.TtPort=hub->Topology.TtPort; + if(hub->Topology.Speed==3u&&child.Speed<3u) { + child.TtHubSlot=hub->Slot; + child.TtPort=(u8)port; + } + u32 queue_start=kernel_xhci_hub_child_count; + u8 slot_id=0; + result=kernel_xhci_enable_slot(&kernel_xhci_live_mmio, + &kernel_xhci_live_capabilities,&slot_id); + if(!result)result=kernel_xhci_address_and_read_descriptor( + &kernel_xhci_live_mmio,&kernel_xhci_live_capabilities, + slot_id,&child); + if(result) { + if(slot_id)(void)kernel_xhci_disable_slot(slot_id); + kernel_write("bob64 kernel: USB hub hotplug enumeration failed port="); + kernel_hex64(port);kernel_write(" result="); + kernel_hex64((u64)(s64)result);kernel_write("\r\n"); + } else { + kernel_xhci_address_hub_children( + &kernel_xhci_live_mmio, + &kernel_xhci_live_capabilities,queue_start); + for(u32 i=0;iMaxPorts;port++) { + u32 port_status; + u32 offset=0x400u+port*0x10u; + if(kernel_xhci_read32(mmio,offset,&port_status))return -2; + if(port_status&1u) { + connected++; + if(connected<=KERNEL_XHCI_HID_DEVICE_LIMIT) { + kernel_xhci_connected_ports[connected-1]=(u8)(port+1); + kernel_xhci_connected_speeds[connected-1]= + (u8)((port_status>>10)&0xfu); + } + kernel_write("bob64 kernel: xHCI connected root port "); + kernel_hex64(port+1);kernel_write(" status=0x"); + kernel_hex64(port_status);kernel_write("\r\n"); + if(!(port_status&port_enabled)) { + u32 speed=(port_status>>10)&0xfu; + if(speed>=4u) { + if(port_status&port_warm_reset_change) + (void)kernel_xhci_write32(mmio,offset, + (port_status&port_power)|port_warm_reset_change); + if(kernel_xhci_write32(mmio,offset, + (port_status&port_power)|port_warm_reset))return -4; + int warm_completed=0; + for(u32 wait=0;wait<20000000u;wait++) { + if(kernel_xhci_read32(mmio,offset,&port_status))return -5; + if(port_status&port_warm_reset_change) { + if(!(port_status&port_enabled))return -6; + (void)kernel_xhci_write32(mmio,offset, + (port_status&port_power)| + (port_status&port_change_mask)); + warm_completed=1; + break; + } + __asm__ volatile("pause"); + } + if(!warm_completed)return -7; + reset++; + kernel_write("bob64 kernel: xHCI root port warm reset passed "); + kernel_hex64(port+1);kernel_write("\r\n"); + continue; + } + if(kernel_xhci_write32(mmio,offset, + (port_status&port_power)|port_reset))return -8; + int completed=0; + for(u32 wait=0;wait<20000000u;wait++) { + if(kernel_xhci_read32(mmio,offset,&port_status))return -9; + if(!(port_status&port_reset)) { + if(!(port_status&port_enabled))return -10; + completed=1; + break; + } + __asm__ volatile("pause"); + } + if(!completed)return -11; + if(port_status&port_reset_change) + (void)kernel_xhci_write32(mmio,offset, + (port_status&port_power)| + (port_status&port_change_mask)); + reset++; + kernel_write("bob64 kernel: xHCI root port reset passed "); + kernel_hex64(port+1);kernel_write("\r\n"); + } + } + } + *connected_count=connected; + if(reset) { + kernel_write("bob64 kernel: xHCI root-port resets="); + kernel_hex64(reset);kernel_write("\r\n"); + } + return 0; +} + +static void kernel_xhci_hid_reconnect(u8 port) { + u32 port_status; + const u32 port_enabled=1u<<1; + const u32 port_power=1u<<9; + const u32 port_change_mask=0x00fe0000u; + if(!port||port>kernel_xhci_live_capabilities.MaxPorts)return; + for(u32 i=0;i>10)&0xfu; + u32 reset_request=speed>=4u?(1u<<31):(1u<<4); + u32 reset_change=speed>=4u?(1u<<19):(1u<<21); + if(kernel_xhci_write32(&kernel_xhci_live_mmio, + 0x400u+((u32)port-1u)*0x10u, + (port_status&port_power)|reset_request| + (port_status&port_change_mask))) { + kernel_write("bob64 kernel: USB reconnect port reset request failed\r\n"); + return; + } + int reset_completed=0; + for(u32 wait=0;wait<20000000u;wait++) { + if(kernel_xhci_read32(&kernel_xhci_live_mmio, + 0x400u+((u32)port-1u)*0x10u,&port_status))return; + if(port_status&reset_change) { + if(!(port_status&port_enabled))break; + (void)kernel_xhci_write32(&kernel_xhci_live_mmio, + 0x400u+((u32)port-1u)*0x10u, + (port_status&port_power)| + (port_status&port_change_mask)); + reset_completed=1; + break; + } + } + if(!reset_completed) { + kernel_write("bob64 kernel: USB reconnect port reset timed out\r\n"); + return; + } + } + u32 connected=0; + if(kernel_xhci_scan_connected_ports(&kernel_xhci_live_mmio, + &kernel_xhci_live_capabilities,&connected)) { + kernel_write("bob64 kernel: USB reconnect port reset failed\r\n"); + return; + } + if(kernel_xhci_read32(&kernel_xhci_live_mmio, + 0x400u+((u32)port-1u)*0x10u,&port_status)||!(port_status&1u))return; + u8 speed=(u8)((port_status>>10)&0xfu),slot_id=0; + if(speed<1u||speed>5u||kernel_xhci_enable_slot( + &kernel_xhci_live_mmio,&kernel_xhci_live_capabilities,&slot_id)) { + kernel_write("bob64 kernel: USB reconnect slot allocation failed\r\n"); + return; + } + KERNEL_XHCI_TOPOLOGY topology={0}; + topology.RootPort=port;topology.Speed=speed; + int result=kernel_xhci_address_and_read_descriptor( + &kernel_xhci_live_mmio,&kernel_xhci_live_capabilities,slot_id, + &topology); + if(result) { + (void)kernel_xhci_disable_slot(slot_id); + kernel_write("bob64 kernel: USB reconnect device unsupported result="); + kernel_hex64((u64)(s64)result);kernel_write("\r\n"); + return; + } + kernel_xhci_hub_child_count=0; + kernel_xhci_address_hub_children(&kernel_xhci_live_mmio, + &kernel_xhci_live_capabilities,0); + for(u32 i=0;iBus<<16)|((u64)device->Device<<8)| + device->Function); + kernel_write(" vendor=0x");kernel_hex64(device->VendorId); + kernel_write(" device=0x");kernel_hex64(device->DeviceId); + kernel_write(" BAR0=0x");kernel_hex64(device->Bar[0]); + kernel_write("\r\n"); + if(bob64_pci_is_xhci_controller(device)) { + kernel_xhci_device=*device;kernel_xhci_found=1; + } +} + +static int kernel_xhci_probe_capabilities(const BOB64_KERNEL_BOOT_INFO *info) { + const u64 virtual_address=0xffffa00000000000ULL; + BOB64_XHCI_CAPABILITIES capabilities; + KERNEL_XHCI_MMIO mmio; + u64 physical; + int result; + if(!kernel_xhci_found||!info||!kernel_xhci_device.BarValid[0]|| + kernel_xhci_device.BarIsIo[0])return -10; + if(bob64_pci_enable_memory(&kernel_xhci_device))return -12; + physical=kernel_xhci_device.Bar[0]; + if(physical&(BOB64_PAGE_SIZE-1))return -11; + result=bob64_page_map_range(&bob64_bootstrap_space.PageTable,virtual_address, + physical,BOB64_XHCI_MMIO_MAP_SIZE,BOB64_PAGE_WRITE|BOB64_PAGE_PCD| + BOB64_PAGE_PWT|(info->NxSupported?BOB64_PAGE_NX:0)); + if(result)return -100+result; + for(u64 offset=0;offsetKERNEL_XHCI_HID_DEVICE_LIMIT) + device_limit=KERNEL_XHCI_HID_DEVICE_LIMIT; + if(!device_limit)return -59; + result=kernel_xhci_scan_connected_ports(&mmio,&capabilities, + &connected_ports); + if(result)return -60+result; + kernel_write("bob64 kernel: xHCI connected ports="); + kernel_hex64(connected_ports);kernel_write("\r\n"); + kernel_xhci_hid_device_count=0; + kernel_xhci_hub_device_count=0; + kernel_xhci_hub_child_count=0; + for(u32 port_index=0;port_indexHasDataPartition||device->BlockDevice.ReadOnly)continue; + int disk_result=bob64_disk_store_save(&device->BlockDevice, + &device->DataPartition,&kernel_filesystem,&kernel_heap); + if(!disk_result) { + kernel_write("bob64 kernel: disk B64S snapshot saved\r\n"); + return 0; + } + kernel_write("bob64 kernel: disk B64S snapshot save failed result="); + kernel_hex64((u64)(s64)disk_result);kernel_write("\r\n"); + return result?disk_result:0; + } return result; } static int kernel_snapshot_restore(void *context,BOB64_FILESYSTEM *filesystem) { const BOB64_KERNEL_BOOT_INFO *info=(const BOB64_KERNEL_BOOT_INFO *)context; EFI_RUNTIME_SERVICES *services=kernel_runtime_services(info); - return services?bob64_firmware_snapshot_restore(services,filesystem): - BOB64_FIRMWARE_SNAPSHOT_NOT_FOUND; + int disk_error=0; + for(u32 i=0;iHasDataPartition)continue; + int disk_result=bob64_disk_store_restore(&device->BlockDevice, + &device->DataPartition,filesystem,&kernel_heap); + if(!disk_result) { + kernel_write("bob64 kernel: disk B64S snapshot restored\r\n"); + return 0; + } + if(disk_result<0)disk_error=disk_result; + } + int firmware_result=services?bob64_firmware_snapshot_restore(services, + filesystem):BOB64_FIRMWARE_SNAPSHOT_NOT_FOUND; + if(!firmware_result)return 0; + return disk_error?disk_error:firmware_result; } __attribute__((noreturn)) void bob64_kernel_main(const BOB64_KERNEL_BOOT_INFO *info) { @@ -958,6 +3321,35 @@ __attribute__((noreturn)) void bob64_kernel_main(const BOB64_KERNEL_BOOT_INFO *i kernel_write("bob64 kernel: page-table pool growth failed\r\n"); kernel_halt(); } + if(bob64_interrupts_enable_timer()) { + kernel_write("bob64 kernel: timer IRQ unavailable\r\n"); + kernel_halt(); + } + kernel_write("bob64 kernel: timer IRQ enabled\r\n"); + u64 initial_timer_ticks=bob64_timer_ticks(); + for(volatile u32 timer_wait=0; + timer_wait<100000000u&&bob64_timer_ticks()==initial_timer_ticks; + timer_wait++) + __asm__ volatile("pause"); + if(bob64_timer_ticks()==initial_timer_ticks) { + kernel_write("bob64 kernel: timer tick test failed\r\n"); + kernel_halt(); + } + kernel_write("bob64 kernel: timer tick passed\r\n"); + u32 pci_device_count=0; + if(!bob64_pci_enumerate(kernel_pci_read_config,0, + kernel_pci_report_usb,0,&pci_device_count)) { + kernel_write("bob64 kernel: PCI enumeration passed, devices="); + kernel_hex64(pci_device_count);kernel_write("\r\n"); + if(kernel_xhci_found) { + int xhci_result=kernel_xhci_probe_capabilities(info); + if(xhci_result) { + kernel_write("bob64 kernel: xHCI capability probe failed, result=0x"); + kernel_hex64((u64)(s64)xhci_result);kernel_write(" phys-bits="); + kernel_hex64(info->PhysicalAddressBits);kernel_write("\r\n"); + } + } + } else kernel_write("bob64 kernel: PCI enumeration unavailable\r\n"); kernel_write("bob64 kernel: dynamic page-table pool passed\r\n"); if(kernel_privilege_stack_init()) { kernel_write("bob64 kernel: privilege stack initialization failed\r\n"); @@ -1008,21 +3400,10 @@ __attribute__((noreturn)) void bob64_kernel_main(const BOB64_KERNEL_BOOT_INFO *i kernel_write(" mapped=0x");kernel_hex64((u64)bob64_heap_mapped_bytes(&kernel_heap)); kernel_write("\r\n"); kernel_write("bob64 kernel: memory checks passed\r\n"); - if(bob64_interrupts_enable_timer()) { - kernel_write("bob64 kernel: timer IRQ unavailable\r\n"); - kernel_halt(); - } - kernel_write("bob64 kernel: timer IRQ enabled\r\n"); - u64 initial_timer_ticks=bob64_timer_ticks(); - for(volatile u32 timer_wait=0; - timer_wait<100000000u&&bob64_timer_ticks()==initial_timer_ticks; - timer_wait++) - __asm__ volatile("pause"); - if(bob64_timer_ticks()==initial_timer_ticks) { - kernel_write("bob64 kernel: timer tick test failed\r\n"); - kernel_halt(); - } - kernel_write("bob64 kernel: timer tick passed\r\n"); + if(!bob64_interrupts_enable_serial()) + kernel_write("bob64 kernel: serial RX IRQ enabled\r\n"); + else + kernel_write("bob64 kernel: serial RX polling fallback\r\n"); bob64_keyboard_reset(); int keyboard_irq_enabled=bob64_interrupts_enable_keyboard()==0; if(!keyboard_irq_enabled) @@ -1099,9 +3480,11 @@ __attribute__((noreturn)) void bob64_kernel_main(const BOB64_KERNEL_BOOT_INFO *i started=0; status=kernel_run_application(&kernel_app_context,"notes.b64e",4, notes_put_arguments,&started); - if(!started||status||kernel_app_read_file(&kernel_app_context, - "notes-smoke.txt",note_fixture_check,sizeof(note_fixture_check))!=4|| - !kernel_bytes_equal((const char *)note_fixture_check,"bob!")|| + s64 note_read_result=kernel_app_read_file(&kernel_app_context, + "notes-smoke.txt",note_fixture_check,sizeof(note_fixture_check)); + if(!started||status||note_read_result!=4|| + note_fixture_check[0]!='b'||note_fixture_check[1]!='o'|| + note_fixture_check[2]!='b'||note_fixture_check[3]!='!'|| (keyboard_irq_enabled&&!kernel_interrupts_enabled())) { kernel_write("bob64 kernel: native notes write test failed\r\n"); kernel_halt(); @@ -1175,10 +3558,8 @@ __attribute__((noreturn)) void bob64_kernel_main(const BOB64_KERNEL_BOOT_INFO *i } kernel_write("bob64 kernel: native info app passed\r\n"); } - EFI_RUNTIME_SERVICES *runtime_services=kernel_runtime_services(info); - int snapshot_restore=runtime_services?bob64_firmware_snapshot_restore( - runtime_services,&kernel_filesystem): - BOB64_FIRMWARE_SNAPSHOT_NOT_FOUND; + int snapshot_restore=kernel_snapshot_restore((void *)info, + &kernel_filesystem); if(!snapshot_restore) { kernel_write("bob64 kernel: persistent B64S snapshot restored\r\n"); const char *persisted_contents; @@ -1208,6 +3589,7 @@ __attribute__((noreturn)) void bob64_kernel_main(const BOB64_KERNEL_BOOT_INFO *i bob64_shell_set_snapshot_storage(&kernel_shell,kernel_snapshot_save, kernel_snapshot_restore,(void *)info); for(;;) { + kernel_xhci_usb_hid_poll(); int character=bob64_keyboard_poll(); if(character<0)character=bob64_early_console_try_read(); if(character>=0)bob64_shell_input(&kernel_shell,character); diff --git a/bob64/keyboard.c b/bob64/keyboard.c index b27602b..8f608bd 100644 --- a/bob64/keyboard.c +++ b/bob64/keyboard.c @@ -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<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)); diff --git a/bob64/keyboard.h b/bob64/keyboard.h index b0de5bc..6511241 100644 --- a/bob64/keyboard.h +++ b/bob64/keyboard.h @@ -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 diff --git a/bob64/libc.c b/bob64/libc.c index e11ca96..6288136 100644 --- a/bob64/libc.c +++ b/bob64/libc.c @@ -1,4 +1,5 @@ #include "libc.h" +#include 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(u8)*right?1:0; } + +int bob64_strncmp(const char *left,const char *right,usize limit) { + for(usize i=0;iFailed)return; + if(writer->Length==(usize)-1) {writer->Failed=1;return;} + if(writer->Capacity&&writer->LengthCapacity-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->LengthCapacity-1) { + writable=writer->Capacity-1-writer->Length; + if(writable>count)writable=count; + for(usize i=0;iBuffer[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;idigit_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='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(usize)0x7fffffff)return -1; + return (int)writer.Length; +} diff --git a/bob64/libc.h b/bob64/libc.h index 75e956a..4a57044 100644 --- a/bob64/libc.h +++ b/bob64/libc.h @@ -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 diff --git a/bob64/mouse.c b/bob64/mouse.c index f098386..18efb8b 100644 --- a/bob64/mouse.c +++ b/bob64/mouse.c @@ -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=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;iWidth||!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->PacketLengthPacketSize)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->PacketLengthPacketSize)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); diff --git a/bob64/mouse.h b/bob64/mouse.h index cb384e7..0d0ef43 100644 --- a/bob64/mouse.h +++ b/bob64/mouse.h @@ -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 diff --git a/bob64/paging.c b/bob64/paging.c index d996173..2c8fc1c 100644 --- a/bob64/paging.c +++ b/bob64/paging.c @@ -192,7 +192,14 @@ int bob64_page_map_range(BOB64_PAGE_TABLE *table,u64 virtual_address, for(u64 i=0;i>1)^(0xedb88320u&-(crc&1u)); + } + return crc; +} + +static int guid_is_zero(const u8 *guid) { + for(u32 i=0;iBlockSize<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_sizedevice->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_sizeGPT_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;blockBlockSize); + 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(firstlast||last>last_usable)return -10; + if(guid_is_zero(entry+16))return -12; + for(u32 previous=0;previous=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=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>16)&0x80u)?PCI_FUNCTION_LIMIT:1u; + for(u32 fn=0;fn>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->DoorbellOffsetCapabilityLength|| + capabilities->RuntimeOffsetCapabilityLength) + return -1; + return 0; +} diff --git a/bob64/pci.h b/bob64/pci.h new file mode 100644 index 0000000..de315fd --- /dev/null +++ b/bob64/pci.h @@ -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 diff --git a/bob64/shell.c b/bob64/shell.c index 3deeeae..005631f 100644 --- a/bob64/shell.c +++ b/bob64/shell.c @@ -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, diff --git a/bob64/syscall.c b/bob64/syscall.c index abc6e3d..2f9bb23 100644 --- a/bob64/syscall.c +++ b/bob64/syscall.c @@ -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; } diff --git a/bob64/usb.c b/bob64/usb.c new file mode 100644 index 0000000..2de9cfd --- /dev/null +++ b/bob64/usb.c @@ -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(totallength)return -1; + candidate.ConfigurationValue=bytes[5]; + for(offset=bytes[0];offsettotal-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(totallength)return -1; + candidate.ConfigurationValue=bytes[5]; + for(offset=bytes[0];offsettotal-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||capacity16||lun>15|| + (device_to_host!=0&&device_to_host!=1))return -1; + for(usize i=0;iexpected_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]length)return -1; + candidate.ConfigurationValue=bytes[5]; + for(offset=bytes[0];offsettotal-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<0x000fffffu)return -1; + route_port=port>14u?15u:port; + *result=route|((u32)route_port<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+1Selected++; + } 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(rowSelected=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->HeightWidth<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;iY+(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->CursorScroll)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; diff --git a/bob64/window.h b/bob64/window.h index 15c9770..d84c6be 100644 --- a/bob64/window.h +++ b/bob64/window.h @@ -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;iCount;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|| diff --git a/bob64/window_server.c b/bob64/window_server.c index c066df5..321fd82 100644 --- a/bob64/window_server.c +++ b/bob64/window_server.c @@ -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)leftDamageLeft)server->DamageLeft=(u32)left; + if((u32)topDamageTop)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 - sizeof(server_composite_chunk)/sizeof(server_composite_chunk[0])? - sizeof(server_composite_chunk)/sizeof(server_composite_chunk[0]):total-offset); - for(u32 i=0;iDamaged||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;yDamageBottom;y++) { + for(u32 x=server->DamageLeft;xDamageRight;) { + 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;iDamaged=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;iWidth); + 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; } diff --git a/bob64/window_server.h b/bob64/window_server.h index f021579..bdf183d 100644 --- a/bob64/window_server.h +++ b/bob64/window_server.h @@ -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, diff --git a/bob64/xhci.c b/bob64/xhci.c new file mode 100644 index 0000000..eed7718 --- /dev/null +++ b/bob64/xhci.c @@ -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;iG8CMEU2f$s%d$RSM^Dkh@-Qnf`aJ!wF zNI|f^+3C=9mLMKyUx*?KVNoVT&R4?0=n4!jrl6n&mXKm-XT7jN5DL45A|927*_`1S zIsX$@ok?uED|RFFx}vOFr&jG3c>8jYAYj<80gQmzk|IIakt1q4%3%V1tI~ICI^JDkUEzNOaW2pb5j?iDR@F@{rv4yZ@&}L=b_L7bg@#huT4>NYLpAJUb4ypspivOI z7l?B075UsBMmQTNd1U$=fkV3YujcvkjyJ`UuF|guov|1pcW)MD>o?9Z5SLgB|2iml zI@&Is3FfJ-i4X+M#6rxJ*UY(-o*S7t^9uTi?IegZ3kICmkl}($0S49?(EZ)*KI6v6 zxgD~B*O5@9{9~v%Z4@4yVmXP#o(W}hb|9?E7jSZhtH^l}3|qb85IOl~jv!nTIK>00 z-@4tJi9&sSs%Byb7#u+0ZxuOr1|t4RJ}@6vZ9^Z#fE5-7ZqS+FJi`KZ$(Eh>vD%Q? zrSguOI@$V`^PUJA7m{en4f85~$+6iAmKQ85C||Z>`BHiN&2;3*`YtRNrXT^@Cyidz}StN0bhQ7Zn3agd6qqypboS7a6A&sDsa z@gG%up7F0${I!KUSJlq6G~lx;Zee^97?YgIlRSl7DwA{r@MIG(Swy~@6-(4X)^y-m zD((jUGyw|lutE}B`pSGA{aLIOrz&lnW>QLpP7T(w<1rPqIXKIMnlq1 z1gwGFU1~@#wXQYjO1lFWuz@7h*DUu)6z|^m5Rjta905Z%dHV%kwpA6CYYJ8utSP8C z52qVBh~p?+UY@0Dt~!}#v4IJNSFtt&tq@?HewC!GQ^eh1tx#f1ISGuV{D@hFYV0p? z=9YL&imJ(R_kfqDTKt49PEz^LvhHM+f1L4H6+bt%0!n{ZeT-DgV-k=11LVq%bjS8R ziqbosfJy#@>lv}`na=z8ob%04Z|UZa^4khF)OZs1&&Q+b%&7QL7e@<%`#tnuA5DK8 zHASNPX;fIU7)Uu`QzIW-$481e=)AHiF9jA;YgoaU+*$Bc8}PU+_PP5t6Wie!o+s#X z>7B3?>1r;08#ZI%Q}!fm5y_DU>o}Tn1NL!gT%0@hARUR& zi3vOswC_Hep#4}MU(4ZX_O!60u36*SaFt!h3F$io zMKVMhq-!-aFLH)7ZD#L|$aqm|&7mJe-9K5%fs0E;gKXV-__k8Xr)B`}1Li7NiPR-h zaP)opfhr{X!U(lau77lX=->o`R!I)kMQ@X?%%G2>Q>CY7^v1?ih*1p@g5XnyRzo&* z#_FYuS@dG;7R#oMY|fqNrDHw)|0|tmQtkbl)ROpbD*i9^yvcVbzSP124fVh8*SEM6 z8~qsW#Mw%Jh>rF2z4Xgwb%tL0o~QqYho1D%V;;I+q22%rRt&qHcHFeAx4tD?f8{)N z%kAFrH%ZgMb)eZBjN2!}QIv6`D8rrM#=9Z8DC4uDjIU6`JK}K?#O{Pqer-Gnb>2ql zkTgKzT!y{Lg57NA$AyOM`b5E1KTF8hbdH13qRtzdP746^LviU?oZT*^85uT87*C8ml=tz=9p$;@P;E&x7vRJsz`9C}K^=OqIQr z*%r)ln}?sE@|!*C>pX0}T0Qqj#|FMfK7n`dJu(l6o!0K81i+Y=G4~%-wrt%uQ(bz%+XbkqbPQi&yjYm;iWpK82zpD zCx3Iht(Vv=pL!7Vcmzj1g0?c0+%2x4iJ!xS1QUf_r504S)mdo0U5G@?g#c;p_(X{} zd^21+|MHpJjW>(gg3;fb!j%(z{}X&kH>cwmJmAUrDIteRPcU=2Ti2R^;&$Dl8y zbg93B=H^m=?&$0Ey_?2g5o1zX%`Ka%*VUy|*P0t1s!K7~wVJ6c zDHf-`KxOf9^HU0EFPfd5S-G@)(UO9>MU@3}%1f3PRTh>kowI1+!lF6lmE}cC%XNZK z)7D^IySk>OCOb1_eRcENmil_Had5nL*=E6=HcMw0z=OvQNBl2r`7Gg3VPli-G`3<% zNqNz5V>Bx%37WG5*|I>9i7^ImV8dsfR#aS)Hha;caz#y5jPojbX5iC-mAJ4wweR(6 zD>3?Xg>|*Hf||rRbJVG+-)U;Hs!gWe*C#C)fj_7@jepZ_PYG`9}E! z!>7d~#{0|-TV;;V>o3}?Fl?T*Bylo4_8y7Pl$M!l8&Yd^O1x>C*AMHowbu9qHO7|O zrpmQ-4>i=*`Ix5aP38u3Lrb%dv$mnNsglc%F6&N{Wm2M2YY5Zgjl!2dAtmL1EGR`m znYZwrD#NC#Xnuz&ZxSJXjpOV@8^yDex|68(iY09M06q*#@J0)pLP_I2TSsc6TyxX0N_RBZi?$w}1w8zj& z&-Z?wwqKm?sPI2WkV?OEBjX3m|?9W}678xQ$ia}y%dPr5UX=GWDBcM;}7X(ooB52X}b_DeW^h++x#+3V*crtH%M3UE|Kx$VI85UJYS_KAugB(<;aEyqsRmeY! z^)b{-uF*U=s1=-iRd^84p~C+FJP}9jWqL_FM$x+tPQNPr3b03oVK|p;aim?mM-s+R z&*IyZzroOZc8N};j%EW%5`kHb3(gWzdWl40o#X#}P4WgFL zEsv#@%XQ>fei!Xo9w7-F>)4RW$_>>Gc$hk%kR@q@X>fU?*Z~s>v~z`loTdqs_P|Jb zcZEUhr?gcGbk|Cm;-65tkFQj@bLsPy2Dpi{`IslG0=8^cua`gNegwj_f)1ityDP85> zuHY~xRyIjhD&t3$ikhiBhMbiVQduZ546B+hI_UnYEJ>#>`m0!w^f;`x9>afD)g+nj zqN&w-@iZ-{o-5f@Tc@iHQk4cvA46YO>!cor2zW~{O|1*1{F<6TCl)l2?q4~Y&ekML z4s}>WtwB1WAzfuLJp$+&M?JO0%wa>{)<&pMF(jU#w6#srEj8z7*BT_W&k3vO@Ud*KJEhwyb#oWynWIf6|KMLCzLbFV@ zVlG0TE2YOHb9Cd8Y?{4MrkY2y$+6K!{f~yw1Dk%1{~<(fX`%zIMj+9=l`0;~rq|3e zeE>SWO{NF8X447KYoMtQ$+Uc1HoXk`OVFtg%e2IjP4Obgqy=~>XXLB~ES)4c83bO`h^=v|M=;-I2=;4zu@JRU+XcBN3%R#^ak*7Ib!5WO7;6kwNV^Ep}&92k3!4*(7b3DQa&v zwS(^3mreiJZlkyN8|n7rMmkPLdT)o3Wq@^+kePFuKhBt{=Si}9Ww0SDN|+_=k;jU zR`HNxrF^#yM*>?Z>ox+hm83n4*vHj9vS?S3yw`?(#d?J{Bhah1-{6~d&hC@3!x`o7 zw_zu-P7WD?*p~LdF@={x{Ri@-DqeZ?&pnYvo1c)y%RpPPF5EXiDT~(>^d%5ZQ1DC# zZ74GF&~KFQMw;`~KFKj!IepsKMJUW#KK5`iFu(q3J^m{-t64ew?N293m*a85-$f=< z0JT4@o{lyy&~X&`%$OJ#ejdS*CE&)uXBPhYaKuyIGmX-9*i6fpp~}(s@Sj0jJ+{HL3QV0mtFz;T3T5eRe8q>ozx-F)E5r5Vo_f&Rp00 z5FSB(mfyyxD*ExW4@kiiDeAC3TJV|Ru%8^sH`m<52{G+{!!Co5dtuvQJ&!wfSf5zt z8@HiuL#=5G%=$*O)|nrwX{#45)4<_`64}RR4=KU;!uxD!`g!1_`>eHYX*Jhvz=`1- zwV~RGKQ!>-qh&|3BqVkB5gd1M^vff~Gfw!l*tR(YQTQy?*Bjef*CPSGl(0@WbS~54 z=MrN0pO!;WdS6YOJfnvrp*raoFi~=-`nw@90WS!SSPw5-x1* zF};Lk$vmb{?D2CoA{>uYzn~|9W1~lpCGd^kgK@BO;aDa=t6qj-HBexqIi$K|KjokQsH0;@pn*;lcETTGwmlc{*j+=$bW{cCp(r_3=3O_wEgY)BWe%JI}M`{jK+V zz3W|TZ-yS*fSy~Dqb}s}GxVi?7H$zm*R^$HO+w9hL_ik?Xyd&Nk;GwFs`+Njw&LCC1re6mIm>V41QJHsx> z^+CsgoDb4`O{(;xj-JyzAg_Vq>`A9nk9Z;6r1P@6L-;52Yh_4MNHV9i4Jgu5=6c8pM5 zJV86A1`JL>vsjVyq}%U*$-94IU;Q8CfE^aPzo(;vl1sN&%ht1x+3oh+FMoUGzqjN?>%f^npZe`6e?;_KHn52H)NP%-xp98r4ch4G?7qqrec?;xdx(zcKwQ4D_YJiaO;q_pX4GgS#|;? zx)%-I2sQF8#v@cL#Rye`^AUBD7Q+rzyqR%=ir-^AR>fBtk5cgjuA{$-^BHSYyqEE9 z^e6(KVSHW1_ZWYt;y5njUl~_5_-^3IX;pBW@z(qBIu-we`9%s2x)-ICD;QPlK8u*j z$#Dfeumxx2NI1&yKKC7>UqSPvqy0ZZmDFCGjAlc}q6MSS-m`Jv(#WBqLm~iN=fMdL zrWr#Ykjnl*r9-2|BHA}}od5eP_{^7kpHNOsr{)lSF*J2V=z|DR;Ps>|o^y3+$Jh`N zAx8;G6yqBswI)%n@03S3O%a5j_V!Cp^Zcp)`F_m1%g{C2F)3_)o96}n^W!|vQo3qX zU=n@jn=Hj7QJ7y+;M2tjXaBVJrgmpA9|@dgviN055yf=eFWUdNBF<*M2?s4BIM@~R z8{P9Wihrgs?Sv)IvdlhrP`dpq*`B3y1?||#3#@q06;uL*x@94({bOf2YRidDy4fAZ zIn--%U|PQj7ozX2M1Drh3J!KY%DZm=8oZN<)T$jndLWe0zJap++LC2?sky03QaG~K6>xgmoohKz z{j?`4@T|FrE6jaMEvFiPlay3It^QM_A&Kpm{YQ&ZRy+*|oF4g~li{^<_AU1AeCZB6 zH2CfX&$%0z`yd<3s-=~Ie=w#mN3l;1Q17&hmrwNHY}_&Rnz8Zpm%we(>yv4=euA`V za(jh-nHX@|PY~Ry&`OV^D?vu-)k)+tY*W?wb?nX+(MLD;&i}u()vEgYCuvp0KdJbC z)axt0D`K#cQ2+euT28QUUge57H`XI=eqW0<36+p!Qv}W!(k(cvrVM9GIqY@khi=ha z1nj-+r=TLKN47(^@3Nl;ZNBXP4eH%L@LkamRMj1(M4xogxe;u{-E*S*UcZ-LR|Y5vjb9zy4eWC;4zP z>3a8W)I-@VrHtKAVru`&8Sr0RZ*9#qC12l>i0(Z0Gk6!v%i!iyJk3zcH^J!+QB`#C z4Ay>T4OCe#ar@PQ0gG=LZ&C5}s707q)kzGuT%n2+7-y?kY0(Ve?)Q1e8hlTglmHJh z>ou_W8tne`x(a&l#P;2xI#Dv`(3z>D$q*WAw1o*NBI?oiar|!H5!Svw^t4DXj9D~v zML~fu;^&nie&KY*D7*{EAhULP7bSn7=kZF+OIw z6?cu${+Z#C0hD11qf}EMtu+iDa-R+ji-@EtW2gH~juT>H%8Sa%m4v8vY$+`qm(=bU zw^&59742=&mEHqmV%ArnjoKfW93zGt?sU0wF@F8T<=O(e1LH*uOK1C<_(m}K?sH=7{nKvOWT0oy>^F?xVIK!=A3 z!d+kkXd%W>JPxg(l^DUmXd|H>Ba|PLpvN!_z#X7tjG=-M#R43PZz7QZ9Cd+S!AM$1 zH>7!uDGNsWcnLn@Kv9Yn&EjBhVQ`~&tj6qR9grz?wAZ9;5h+vDzdIw;FUs0%Yj!j@ zHMcc)G@onkYVK(kT68Ujme`h*mdqA&i?zkp;%Jdu+aJ$-o2`5s=XFUvfz*>Vx-rX3 z67-D7l(kH9C`|9$0`gJe2odX26ukM5*i42-$*Ky=!0AxobATzT-oF6G>d7|WC^=Nl zMR3e2ya{Mf;ZO-B){}0*PRXXHrUiGTCOvg6GPWOEXb`1yjNj#qQVK(;Ypai+mmt7c z7$9DPVG@15;6b{VJ%RKK18Mr=1Zl5scbJ~cFMCaN1omlW;2kI(HlCl4U~dLXgE2sa zSrDCH93=@s9Gynzn54FWh^nXT9D^v(@th#qnd2wfc%>med3mdsufkz7Ly*9lw{l8E zD_vY3PERc{NwKPzvr9~(jV9)W)397wG6#`4H%(#8p`UY2l0(%>T*_LIksMqTFD?}cdQpVioB#u*qYPey)Op`&0St9wdv@{a-+BdtC}O(RR3xDNZW^E z^P*{AezMf2a_{7G8em%s45OiiaiW=~7bZweYO}n9ZD|X{ zmK$OFQDLdn<4@y?jA9EtQZz@>4OiB4qzJzeXqA2VrN|(qFyuxUge{p;T&lUiJ4n-W zhtsj*XemWC@>^k&GPPtVNTbbw*5TB&B8@q`op)FGsZe#3NfTEhZMEFTR+^+H)ra>g zlVnzXtOq>D+;I9}RX7&$?W%C8OZ669;wR~J?xf5#x1?0_y*sJo#e?YU5-cIOvD7#u zMc3Doar92^2{QAsIp{;tweDK=Q`Jc~)P>5zOhSuM$uIhfikY0T+cxQ#}xF4gpS z#AscOdI!_F)oD_PTa)3`H6_wrfex>MAeeeU4E}wd=%F=(sc>z+W++aST13wG>RPl{ zFzKvml2z4RZw*0jH&{!>V4Ai*oI=-`==p^vDqM$DS!J~Mah%I@%4Sl|+QIbox_mJd zx^w8#A`=~6kL=uGvD-J+mr9v|w5-f18fbgj9J;gEMAypD>uxQEiRC3?6dfp^L#<0j z(c9Srp)FP>(2NQhd`2A=4l$M<-|!{A{kN9Vo{bhDv2v@Jq{#nRDT^rzirXaPS3|aG z1Ikp;gw3*;t)Mr7%nBO!geSoPx@N~vXw1;~Hvm-uE6qqoUorGj1r!m|v# zkSdv;sYs-KpqU$dsJp6ywpAw59-B;eK?AnSw0Tn^IY4iL`aLPrhRunz1N2wW!PPRY ze=8|C?%`i0>o1J84LYwdm>$Z#(_$*?1y>_5X+A3u+W7k6Up4*pmWvi z_uo-Tmc;MknjYA-l^(50r1=g9eO9B!&D?E4by+8>krBr|(T9!MC@}Abw>HRTO zxu19C`2MZ*$7cd4^LY#Ee|&!e{qnp_;~JP_BI^qd>S-|1-52Lj>5HqWX_pWAyqHfj zU)s&r65mC(QommI62ANJm|#iq%SN=zwDlvIclhNfNe;ms4~udyvc0Takrc3W6#2h0 zLT|;(HSR3|4-b5%;o*@ILdma`NZBFO`bs>~`u3G@lwv?rLY1JuUw5rHPDlV>0ES-c zo#5DdpHiy77r;sJi10Qz9neu@<`ooGuEIN@&FyDJQF+mt4T6xZ`04Zf8LZ6or>4bH zT?hpnFa~m%{;d+CI*(vbxWY~7V$aV)07$eTP?N%49F0gLGn%x#{2^mRibtpczNnx_ z(qZ7l(i4Zm`I+AYJ9s&HD4t)S?i?!7w|SW7`w7C~0IGcL-6VsDAWDmRy6cvgSGg*0 zId{hWl}v=rsQ}79Y}EHJ6RHKQis1VW$8!^%J)EuAc@!=j55Y`5J@k5--s%x`KLkj3 z&+A61BY=*)-V}MnEic}fql4|>)VX!a%GXH&`u_n%bp~Ys diff --git a/tests/test_bob64.c b/tests/test_bob64.c index 04e55e6..c958654 100644 --- a/tests/test_bob64.c +++ b/tests/test_bob64.c @@ -9,6 +9,12 @@ #include "../bob64/heap.h" #include "../bob64/keyboard.h" #include "../bob64/mouse.h" +#include "../bob64/pci.h" +#include "../bob64/xhci.h" +#include "../bob64/usb.h" +#include "../bob64/block_device.h" +#include "../bob64/partition.h" +#include "../bob64/disk_store.h" #include "../bob64/window.h" #include "../bob64/window_server.h" #include "../bob64/editor.h" @@ -42,7 +48,7 @@ typedef struct { } HEAP_TEST_ARENA; typedef struct { - _Alignas(16) u8 Bytes[256*4096]; + _Alignas(16) u8 Bytes[512*4096]; usize PagesUsed; } HEAP_STRESS_ARENA; @@ -165,6 +171,233 @@ static EFI_STATUS EFIAPI firmware_test_query_variable_info(u32 attributes, #define CHECK(expression,message) do { if(!(expression)){fprintf(stderr,"bob64 check failed: %s\n",message);return 1;} } while(0) +typedef struct { + u8 Data[16u*512u]; + u32 Reads,Writes,Flushes; +} BLOCK_TEST_DISK; + +static int block_test_read(void *context,u64 lba,u32 count,void *buffer) { + BLOCK_TEST_DISK *disk=(BLOCK_TEST_DISK *)context; + usize offset=(usize)lba*512u,length=(usize)count*512u; + if(!disk||!buffer||lba>=16u||count>16u-lba)return -1; + memcpy(buffer,disk->Data+offset,length);disk->Reads++;return 0; +} + +static int block_test_write(void *context,u64 lba,u32 count, + const void *buffer) { + BLOCK_TEST_DISK *disk=(BLOCK_TEST_DISK *)context; + usize offset=(usize)lba*512u,length=(usize)count*512u; + if(!disk||!buffer||lba>=16u||count>16u-lba)return -1; + memcpy(disk->Data+offset,buffer,length);disk->Writes++;return 0; +} + +static int block_test_flush(void *context) { + BLOCK_TEST_DISK *disk=(BLOCK_TEST_DISK *)context; + if(!disk)return -1; + disk->Flushes++;return 0; +} + +static int block_device_tests(void) { + BLOCK_TEST_DISK disk={0}; + BOB64_BLOCK_DEVICE read_only={0},writable={0},invalid={0}; + u8 source[4096],target[4096]; + for(u32 i=0;i=64u||count>64u-lba)return -1; + memcpy(buffer,disk->Data+(usize)lba*512u,(usize)count*512u); + disk->Reads++;return 0; +} + +static int gpt_test_write(void *context,u64 lba,u32 count,const void *buffer) { + GPT_TEST_DISK *disk=(GPT_TEST_DISK *)context; + if(!disk||!buffer||lba>=64u||count>64u-lba)return -1; + if(disk->FailWriteAt&&disk->Writes+1u==disk->FailWriteAt)return -2; + memcpy(disk->Data+(usize)lba*512u,buffer,(usize)count*512u); + disk->Writes++;return 0; +} + +static int gpt_test_flush(void *context) { + GPT_TEST_DISK *disk=(GPT_TEST_DISK *)context; + if(!disk)return -1; + disk->Flushes++;return 0; +} + +static u32 gpt_test_crc32(const u8 *bytes,usize length) { + u32 value=0xffffffffu; + for(usize i=0;i>1)^(0xedb88320u&-(value&1u)); + } + return ~value; +} + +static void gpt_test_build(GPT_TEST_DISK *disk) { + u8 *header=disk->Data+512u,*entries=disk->Data+1024u; + for(u32 i=0;i<8;i++)header[i]=(u8)"EFI PART"[i]; + firmware_test_write32(header+8,0x00010000u); + firmware_test_write32(header+12,92); + firmware_test_write64(header+24,1); + firmware_test_write64(header+32,63); + firmware_test_write64(header+40,34); + firmware_test_write64(header+48,62); + firmware_test_write64(header+72,2); + firmware_test_write32(header+80,4); + firmware_test_write32(header+84,128); + for(u32 i=0;iData+512u; + firmware_test_write32(header+88,gpt_test_crc32(disk->Data+1024u,512)); + firmware_test_write32(header+16,0); + firmware_test_write32(header+16,gpt_test_crc32(header,92)); +} + +static int partition_tests(void) { + GPT_TEST_DISK disk={0}; + BOB64_BLOCK_DEVICE device={0}; + BOB64_PARTITION partition={0}; + u8 unknown_guid[BOB64_GPT_GUID_SIZE]={1}; + CHECK(!bob64_block_device_init(&device,&disk,64,512,1,gpt_test_read,0,0), + "initialize the GPT test disk as read-only"); + CHECK(bob64_gpt_find_partition(&device,bob64_gpt_bob_data_type_guid, + &partition)==1,"ignore an unformatted disk without a GPT signature"); + gpt_test_build(&disk); + int find_result=bob64_gpt_find_partition(&device, + bob64_gpt_bob_data_type_guid,&partition); + CHECK(!find_result&&partition.FirstLba==34&&partition.BlockCount==17&& + !memcmp(partition.TypeGuid,bob64_gpt_bob_data_type_guid,16)&& + partition.UniqueGuid[0]==1&&disk.Reads>1, + "find the bounded bob64 GPT data partition and verify both CRCs"); + CHECK(bob64_gpt_find_partition(&device,unknown_guid,&partition)==1, + "ignore valid GPT partitions with another type GUID"); + gpt_test_build(&disk);disk.Data[512u+40u]^=1; + CHECK(bob64_gpt_find_partition(&device,bob64_gpt_bob_data_type_guid, + &partition)<0,"reject a GPT header with a bad CRC"); + gpt_test_build(&disk);disk.Data[1024u+127u]^=1; + CHECK(bob64_gpt_find_partition(&device,bob64_gpt_bob_data_type_guid, + &partition)==-14,"reject a GPT entry array with a bad CRC"); + gpt_test_build(&disk);firmware_test_write64(disk.Data+1024u+40u,63); + gpt_test_rechecksum(&disk); + CHECK(bob64_gpt_find_partition(&device,bob64_gpt_bob_data_type_guid, + &partition)==-10,"reject partitions outside the usable GPT range"); + gpt_test_build(&disk);disk.Data[1024u+128u]=0x55; + disk.Data[1024u+128u+16u]=1; + firmware_test_write64(disk.Data+1024u+128u+32u,45); + firmware_test_write64(disk.Data+1024u+128u+40u,55); + gpt_test_rechecksum(&disk); + CHECK(bob64_gpt_find_partition(&device,bob64_gpt_bob_data_type_guid, + &partition)==-15,"reject overlapping GPT partitions"); + gpt_test_build(&disk);firmware_test_write32(disk.Data+512u+80u,129); + firmware_test_write32(disk.Data+512u+16u,0); + firmware_test_write32(disk.Data+512u+16u,gpt_test_crc32(disk.Data+512u,92)); + CHECK(bob64_gpt_find_partition(&device,bob64_gpt_bob_data_type_guid, + &partition)==-6,"reject unsupported GPT entry-array sizes"); + return 0; +} + +static int disk_store_tests(void) { + GPT_TEST_DISK disk={0}; + HEAP_TEST_ARENA arena={0}; + BOB64_HEAP heap; + BOB64_BLOCK_DEVICE device={0}; + BOB64_PARTITION partition={0}; + BOB64_FILESYSTEM source,target; + const char *contents=0; + usize length=0; + CHECK(!bob64_heap_init(&heap,sizeof(arena.Bytes),heap_test_grow,&arena)&& + !bob64_block_device_init(&device,&disk,64,512,0,gpt_test_read, + gpt_test_write,gpt_test_flush)&& + !bob64_fs_init(&source,&heap)&&!bob64_fs_init(&target,&heap), + "initialize filesystems and a writable partition-backed test device"); + partition.FirstLba=4;partition.BlockCount=60; + for(u32 i=0;i0, "measure and compare NUL-terminated strings"); + CHECK(bob64_memchr(source,'6',sizeof(source))==source+3&& + bob64_memchr(high_bytes,0xff,sizeof(high_bytes))==high_bytes+2&& + !bob64_memchr(source,'x',sizeof(source))&& + bob64_strnlen("bob",2)==2&&bob64_strnlen("bob",8)==3, + "search byte ranges and measure bounded strings"); + CHECK(bob64_strncmp("bob64!","bob",3)==0&& + bob64_strncmp("bob","bob64!",5)<0&& + bob64_strncmp("\xff","\1",1)>0&& + bob64_strncmp("a","b",0)==0, + "compare bounded strings with unsigned-byte ordering"); + CHECK(bob64_strcpy(text,"bob")==text&& + bob64_strcat(text,"64!")==text&&!bob64_strcmp(text,"bob64!")&& + bob64_strncat(text,"ignored",0)==text&&!bob64_strcmp(text,"bob64!")&& + bob64_strncat(text,"xyz",2)==text&&!bob64_strcmp(text,"bob64!xy"), + "copy and append complete or bounded strings"); + CHECK(bob64_strncpy(padded,"xy",sizeof(padded))==padded&& + padded[0]=='x'&&padded[1]=='y'&&padded[2]==0&&padded[7]==0&& + bob64_strncpy(truncated,"long",sizeof(truncated))==truncated&& + !bob64_memcmp(truncated,"lon",sizeof(truncated)), + "copy bounded strings with padding and no forced terminator"); + CHECK(bob64_strchr(source,'6')==source+3&& + bob64_strchr(source,0)==source+sizeof(source)-1&& + !bob64_strchr(source,'x')&&bob64_strrchr(reverse,'b')==reverse+2&& + bob64_strrchr(reverse,0)==reverse+3, + "find first and last character occurrences including NUL"); + CHECK(bob64_strstr(haystack,"64 k")==haystack+3&& + bob64_strstr(haystack,"missing")==0&& + bob64_strstr(haystack,empty_needle)==haystack, + "find bounded substrings and handle the empty needle"); + static const char format_expected[]="bob!:-0007:0x2a:3:te :%"; + CHECK(bob64_snprintf(formatted,sizeof(formatted), + "%s:%+05d:%#llx:%zu:%-4.2s:%%","bob!",-7, + (unsigned long long)42,(usize)3,"text")== + (int)(sizeof(format_expected)-1)&& + !bob64_strcmp(formatted,format_expected), + "format strings, signed values, widths, precision, and LLP64 sizes"); + CHECK(bob64_snprintf(minimum_integer,sizeof(minimum_integer),"%lld", + (long long)(-9223372036854775807LL-1))==20&& + !bob64_strcmp(minimum_integer,"-9223372036854775808")&& + bob64_snprintf(small_output,sizeof(small_output),"%s","bob64!")==6&& + !bob64_strcmp(small_output,"bob6")&& + bob64_snprintf(one_byte_output,sizeof(one_byte_output),"bob!")==4&& + !one_byte_output[0]&& + bob64_snprintf(0,0,"abc")==3, + "format minimum signed 64-bit values and safely truncate output"); + CHECK(bob64_snprintf(formatted,sizeof(formatted), + "%#06o:%#.0x:%*.*s:%p",8u,0u,-5,2,"hello", + (void *)(uintptr_t)0x123456789abcULL)==28&& + !bob64_strcmp(formatted,"000010::he :0x123456789abc"), + "format alternate bases, zero precision, star widths, and 64-bit pointers"); + CHECK(bob64_snprintf(bad_format,sizeof(bad_format),"%f",1.0)==-1&& + bad_format[0]==0, + "reject unsupported floating-point format specifiers cleanly"); return 0; } @@ -389,6 +679,14 @@ static int compiler_arithmetic_tests(void) { static const char unsigned_division_source[]= "usize main(void) { usize value=0x100000001ULL; " "return value / 10 + value % 10; }"; + static const char unsigned_long_long_source[]= + "typedef unsigned long long uint64_value; " + "uint64_value add(uint64_value value, unsigned long long int amount) { " + "return value + amount; } " + "int main(void) { uint64_value value=0xffffffffffffffffULL; " + "if(sizeof(unsigned long long)!=8 || sizeof(unsigned long long int)!=8 || " + "add(value, 1ULL)!=0 || !(value > 0x7fffffffffffffffULL)) return -1; " + "return 42; }"; static const char bitwise_source[]= "int main(void) { usize value=0x100000001ULL; " "if ((value >> 32) != 1 || (value & 15) != 1 || " @@ -397,6 +695,43 @@ static int compiler_arithmetic_tests(void) { "((-8 >> 2) != -2) || (2 == 1 < 3) || " "!(value >= 0x100000001ULL && value <= 0x100000001ULL)) " "return -1; return 1; }"; + static const char sizeof_source[]= + "typedef long long wide_t; " + "struct SizeProbe { char tag; long value; long long wide; }; " + "int main(void) { " + "if(sizeof(char)!=1 || sizeof(short)!=2 || sizeof(int)!=4 || " + "sizeof(long)!=4 || sizeof(long long)!=8 || sizeof(usize)!=8 || " + "sizeof(void *)!=8 || sizeof(char *)!=8 || sizeof(int *)!=8 || " + "sizeof(wide_t)!=8 || " + "sizeof(int[3])!=12 || sizeof(short[5])!=10 || " + "sizeof(usize[2])!=16 || sizeof(struct SizeProbe)!=16) return -1; " + "return 42; }"; + static const char sizeof_expression_source[]= + "int calls=0; int side_effect(void) { calls=calls+1; return 42; } " + "int main(void) { int value=42; int *pointer=&value; int values[3]; " + "if(sizeof(value)!=4 || sizeof(pointer)!=8 || sizeof(values)!=12 || " + "sizeof(values[0])!=4 || sizeof(\"bob!\")!=5 || " + "sizeof(side_effect())!=4 || calls!=0) return -1; return 42; }"; + static const char void_pointer_source[]= + "void *identity(int, void *); " + "void *identity(int tag, void *value) { int *typed=value; " + "if(tag!=7) *typed=-1; return value; } " + "int main(void) { int number=42; void *opaque=&number; " + "int *typed=identity(7,opaque); if(opaque!=typed) return -1; " + "return *typed; }"; + static const char void_pointer_dereference_source[]= + "int main(void) { int number=42; void *opaque=&number; " + "return *opaque; }"; + static const char void_pointer_arithmetic_source[]= + "int main(void) { int number=42; void *opaque=&number; " + "opaque=opaque+1; return 0; }"; + static const char cast_source[]= + "int scalar=42; int main(void) { uintptr_t raw=(uintptr_t)&scalar; " + "void *opaque=(void *)raw; int *typed=(int *)opaque; " + "long long wide=(long long)typed; int *again=(int *)wide; " + "short narrowed=(short)0x11234; short negative=(short)0xffff; " + "int narrowed_int=(int)0x10000002aULL; char letter=(char)0x142; " + "return *again+narrowed+negative+narrowed_int+letter; }"; u8 file[BOB64_COMPILER_IMAGE_LIMIT];usize length,error_offset; BOB64_EXEC_IMAGE image; CHECK(!bob64_compile_c(source,sizeof(source)-1,file,sizeof(file),&length, @@ -432,10 +767,55 @@ static int compiler_arithmetic_tests(void) { &error_offset)&&!bob64_exec_parse(file,length,&image)&& !execute_compiled_main(&image,&result)&&result==429496736LL, "execute unsigned division and remainder without truncating high bits"); + CHECK(!bob64_compile_c(unsigned_long_long_source, + sizeof(unsigned_long_long_source)-1,file,sizeof(file),&length, + &error_offset)&&!bob64_exec_parse(file,length,&image)&& + !execute_compiled_main(&image,&result)&&result==42, + "compile and execute unsigned long long aliases, calls, width, and high-bit comparisons"); CHECK(!bob64_compile_c(bitwise_source,sizeof(bitwise_source)-1,file, sizeof(file),&length,&error_offset)&&!bob64_exec_parse(file,length,&image)&& !execute_compiled_main(&image,&result)&&result==1, "execute C bitwise precedence, 64-bit shifts, and signed right shift"); + CHECK(!bob64_compile_c(sizeof_source,sizeof(sizeof_source)-1,file,sizeof(file), + &length,&error_offset)&&!bob64_exec_parse(file,length,&image)&& + !execute_compiled_main(&image,&result)&&result==42, + "execute sizeof for LLP64 scalars, 64-bit pointers, arrays, typedefs, and structs"); + CHECK(!bob64_compile_c(sizeof_expression_source, + sizeof(sizeof_expression_source)-1,file,sizeof(file),&length, + &error_offset)&&!bob64_exec_parse(file,length,&image)&& + !execute_compiled_main(&image,&result)&&result==42, + "execute sizeof expressions without evaluating calls or decaying arrays"); + int void_pointer_compile_status=bob64_compile_c(void_pointer_source, + sizeof(void_pointer_source)-1,file,sizeof(file),&length,&error_offset); + int void_pointer_parse_status=void_pointer_compile_status?1: + bob64_exec_parse(file,length,&image); + int void_pointer_execute_status=void_pointer_parse_status?1: + execute_compiled_main(&image,&result); + if(void_pointer_compile_status||void_pointer_parse_status|| + void_pointer_execute_status||result!=42) + fprintf(stderr,"void pointer statuses compile=%d parse=%d execute=%d result=%lld offset=%zu\n", + void_pointer_compile_status,void_pointer_parse_status, + void_pointer_execute_status,(long long)result,error_offset); + CHECK(!void_pointer_compile_status&&!void_pointer_parse_status&& + !void_pointer_execute_status&&result==42, + "execute opaque 64-bit void pointers through assignment, calls, returns, and typed conversion"); + int cast_compile=bob64_compile_c(cast_source,sizeof(cast_source)-1,file, + sizeof(file),&length,&error_offset); + int cast_parse=cast_compile?1:bob64_exec_parse(file,length,&image); + int cast_execute=cast_parse?1:execute_compiled_main(&image,&result); + if(cast_compile||cast_parse||cast_execute||result!=4809) + fprintf(stderr,"cast statuses compile=%d parse=%d execute=%d result=%lld offset=%zu\n", + cast_compile,cast_parse,cast_execute,(long long)result,error_offset); + CHECK(!cast_compile&&!cast_parse&&!cast_execute&&result==4809, + "execute explicit LLP64 scalar and 64-bit pointer casts"); + CHECK(bob64_compile_c(void_pointer_dereference_source, + sizeof(void_pointer_dereference_source)-1,file,sizeof(file),&length, + &error_offset)!=0, + "reject dereferencing an opaque void pointer"); + CHECK(bob64_compile_c(void_pointer_arithmetic_source, + sizeof(void_pointer_arithmetic_source)-1,file,sizeof(file),&length, + &error_offset)!=0, + "reject arithmetic on an opaque void pointer"); return 0; } @@ -456,6 +836,35 @@ static int compiler_local_tests(void) { s64 result=0; CHECK(!execute_compiled_main(&image,&result)&&result==0x300000009LL, "execute generated local loads/stores and the 64-bit function frame"); + static const char delayed_initialization_source[]= + "int main(void) { char c; short s; long n; long long wide; usize bits; " + "int values[2]; char *text; c = 'b'; s = 2; n = 4; " + "wide = 0x100000003ULL; bits = (usize)wide; values[0] = 20; " + "values[1] = s; text = \"bob!\"; " + "return values[0] + values[1] + c + (int)(bits >> 32) + text[0] + n; }"; + CHECK(!bob64_compile_c(delayed_initialization_source, + sizeof(delayed_initialization_source)-1,file,sizeof(file),&length, + &error_offset)&&!bob64_exec_parse(file,length,&image), + "compile uninitialized scalar and pointer locals before assignment"); + CHECK(!execute_compiled_main(&image,&result)&&result==223, + "execute delayed assignments to char, short, long, wide, pointer, and array locals"); + static const char increment_source[]= + "int main(void) { int i = 4; int old = i++; int newest = ++i; " + "int down = i--; ++i; short s = 1; int old_s = s++; ++s; " + "char c = 127; int wrapped = ++c; int values[3] = {10, 20, 30}; " + "int *p = values; int *old_p = p++; int total = 0; " + "for (int j = 3; j > 0; j--) total = total + values[j - 1]; " + "int *high = (int *)(usize)0x100000000ULL; int *high_old = high++; " + "if (down != 6 || i != 6 || old != 4 || newest != 6 || s != 3 || " + "old_s != 1 || wrapped != -128 || c != -128 || old_p[0] != 10 || " + "p[0] != 20 || total != 60 || (usize)high != 0x100000004ULL || " + "(usize)high_old != 0x100000000ULL) return 1; " + "return i + old + newest + s + old_s + total + old_p[0] + p[0] + (p - values); }"; + CHECK(!bob64_compile_c(increment_source,sizeof(increment_source)-1,file, + sizeof(file),&length,&error_offset)&&!bob64_exec_parse(file,length,&image), + "compile prefix/postfix increment and decrement with scalar and pointer operands"); + CHECK(!execute_compiled_main(&image,&result)&&result==111, + "execute C increment semantics, scaled pointer steps above 4 GiB, and decrementing for loops"); static const char string_pointer_source[]= "int main(void) { char *text = \"bob!\"; return length(text); } " "int length(char *text) { int n = 0; " @@ -546,6 +955,18 @@ static int compiler_local_tests(void) { !bob64_exec_parse(file,length,&image)&& !execute_compiled_main(&image,&result)&&result=='O'+42+'g', "initialize global pointers to arrays and strings without fixed-address relocations"); + static const char global_void_pointer_source[]= + "int scalar=42; int values[2]={40,2}; " + "void *scalar_address=&scalar; void *array_address=values; " + "void *string_address=\"bob!\"; " + "int main(void) { int *scalar_pointer=scalar_address; " + "int *array_pointer=array_address; char *string_pointer=string_address; " + "return *scalar_pointer+array_pointer[1]+string_pointer[0]; }"; + CHECK(!bob64_compile_c(global_void_pointer_source, + sizeof(global_void_pointer_source)-1,file,sizeof(file),&length, + &error_offset)&&!bob64_exec_parse(file,length,&image)&& + !execute_compiled_main(&image,&result)&&result==42+2+'b', + "initialize global void pointers to scalar objects, arrays, and strings"); static const char struct_member_source[]= "struct Record { int value; char mark; long long count; char *text; }; " "struct Record shared; " @@ -670,6 +1091,18 @@ static int compiler_local_tests(void) { "compile int-pointer difference as an element count"); CHECK(!execute_compiled_main(&image,&result)&&result==2, "execute pointer difference in int elements"); + static const char high_pointer_arithmetic_source[]= + "long long main(void) { uintptr_t base = 0x1234567887654320ULL; " + "int *pointer = (int *)base; " + "uintptr_t advanced = (uintptr_t)(pointer + 3); " + "return (long long)(advanced - base) - 12; }"; + CHECK(!bob64_compile_c(high_pointer_arithmetic_source, + sizeof(high_pointer_arithmetic_source)-1,file, + sizeof(file),&length,&error_offset)&& + !bob64_exec_parse(file,length,&image), + "compile scaled pointer arithmetic from an address above 4 GiB"); + CHECK(!execute_compiled_main(&image,&result)&&result==0, + "preserve all high address bits in pointer addition and integer casts"); static const char array_initializer_source[]= "int main(void) { int seed = 40; int values[4] = {seed, 2,}; " "return values[0] + values[1] + values[2] + values[3]; }"; @@ -898,6 +1331,20 @@ static int compiler_local_tests(void) { "compile a pointer passed in the fifth argument slot"); CHECK(!execute_compiled_main(&image,&result)&&result==42, "preserve a 64-bit pointer through stack argument passing"); + static const char mixed_stack_pointer_source[]= + "int main(void) { int values[2]={40,2}; void *opaque=values; " + "return inspect(1,2,3,4,values,5," + "identity(1,2,3,4,opaque,42),6); } " + "void *identity(int a,int b,int c,int d,void *value,int tag) { " + "int *typed=value; if(a+b+c+d!=10||tag!=42) typed[0]=-1; " + "return value; } " + "int inspect(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; }"; + CHECK(!bob64_compile_c(mixed_stack_pointer_source, + sizeof(mixed_stack_pointer_source)-1,file,sizeof(file),&length, + &error_offset)&&!bob64_exec_parse(file,length,&image)&& + !execute_compiled_main(&image,&result)&&result==63, + "execute mixed register/stack pointer arguments across a nested call"); static const char bad_call_arity[]= "int main(void) { return add(1); } " "int add(int left, int right) { return left + right; }"; @@ -953,6 +1400,146 @@ static int compiler_local_tests(void) { CHECK(!execute_compiled_main(&image,&result), "execute nested loop control flow"); CHECK(result==4,"route break and continue to the nearest nested loop"); + static const char do_while_source[]= + "int main(void) { int count = 0; do { count = count + 1; } " + "while (0); return count; }"; + CHECK(!bob64_compile_c(do_while_source,sizeof(do_while_source)-1,file, + sizeof(file),&length,&error_offset)&& + !bob64_exec_parse(file,length,&image), + "compile a do-while loop with a false first condition"); + CHECK(!execute_compiled_main(&image,&result)&&result==1, + "execute a do-while body at least once"); + static const char do_while_continue_source[]= + "int main(void) { int count = 0; int total = 0; do { " + "count = count + 1; if (count == 2) continue; " + "total = total + count; } while (count < 4); return total; }"; + CHECK(!bob64_compile_c(do_while_continue_source, + sizeof(do_while_continue_source)-1,file,sizeof(file),&length, + &error_offset)&&!bob64_exec_parse(file,length,&image), + "compile continue in do-while condition flow"); + CHECK(!execute_compiled_main(&image,&result)&&result==8, + "route do-while continue through the loop condition"); + static const char switch_fallthrough_source[]= + "int main(void) { int value = 2; int total = 0; switch (value) { " + "case 1: total = 10; break; case 2: total = 20; " + "case 3: total = total + 3; break; default: total = 99; } " + "return total; }"; + CHECK(!bob64_compile_c(switch_fallthrough_source, + sizeof(switch_fallthrough_source)-1,file,sizeof(file),&length, + &error_offset)&&!bob64_exec_parse(file,length,&image), + "compile switch cases, default, fallthrough, and break"); + CHECK(!execute_compiled_main(&image,&result)&&result==23, + "dispatch to the matching case and preserve lexical fallthrough"); + static const char switch_signed_source[]= + "int main(void) { int value = -1; int total = 0; switch (value) { " + "case 1: total = 1; break; case -1: total = 42; break; " + "default: total = 0; } return total; }"; + int switch_signed_compile=bob64_compile_c(switch_signed_source, + sizeof(switch_signed_source)-1,file,sizeof(file),&length,&error_offset); + CHECK(!switch_signed_compile&& + !bob64_exec_parse(file,length,&image), + "compile signed switch values and negative case constants"); + CHECK(!execute_compiled_main(&image,&result)&&result==42, + "sign-extend signed switch values and match negative case constants"); + static const char switch_character_source[]= + "int main(void) { char value = 'B'; int result = 0; switch (value) { " + "case 'A': result = 1; break; case 'B': result = 42; break; " + "default: result = 0; } return result; }"; + CHECK(!bob64_compile_c(switch_character_source, + sizeof(switch_character_source)-1,file,sizeof(file),&length, + &error_offset)&&!bob64_exec_parse(file,length,&image)&& + !execute_compiled_main(&image,&result)&&result==42, + "dispatch signed char values using character case constants"); + static const char enum_switch_source[]= + "enum Color { RED, GREEN = 4, BLUE, }; typedef enum Color Color; " + "int choose(Color color) { switch (color) { case RED: return 1; " + "case BLUE: return 42; default: return 0; } return 0; } " + "int main(void) { enum Color first = GREEN; Color second = BLUE; " + "return choose(second) + first; }"; + CHECK(!bob64_compile_c(enum_switch_source,sizeof(enum_switch_source)-1, + file,sizeof(file),&length,&error_offset)&& + !bob64_exec_parse(file,length,&image), + "compile named enums, implicit values, typedefs, and enum switch labels"); + CHECK(!execute_compiled_main(&image,&result)&&result==46, + "execute enum constants as values and dispatch enum switch cases"); + static const char enum_global_initializer_source[]= + "enum Color { RED, GREEN = 4, BLUE }; enum Color selected = BLUE; " + "int palette[2] = { GREEN, BLUE }; " + "int main(void) { return selected + palette[0] + palette[1]; }"; + CHECK(!bob64_compile_c(enum_global_initializer_source, + sizeof(enum_global_initializer_source)-1,file,sizeof(file),&length, + &error_offset)&&!bob64_exec_parse(file,length,&image)&& + !execute_compiled_main(&image,&result)&&result==14, + "initialize global enum scalars and arrays with enum constants"); + static const char duplicate_enum_value_source[]= + "enum Bad { SAME, SAME }; int main(void) { return SAME; }"; + CHECK(bob64_compile_c(duplicate_enum_value_source, + sizeof(duplicate_enum_value_source)-1,file,sizeof(file),&length, + &error_offset),"reject duplicate enum constant identifiers"); + static const char unknown_enum_tag_source[]= + "enum Missing value; int main(void) { return 0; }"; + CHECK(bob64_compile_c(unknown_enum_tag_source, + sizeof(unknown_enum_tag_source)-1,file,sizeof(file),&length, + &error_offset),"reject use of an undeclared enum tag"); + static const char switch_wide_source[]= + "int main(void) { long long value = 0x100000001ULL; int result = 0; " + "switch (value) { case 1: result = 1; break; " + "case 0x100000001ULL: result = 42; break; " + "default: result = 0; } return result; }"; + CHECK(!bob64_compile_c(switch_wide_source,sizeof(switch_wide_source)-1, + file,sizeof(file),&length,&error_offset)&& + !bob64_exec_parse(file,length,&image)&& + !execute_compiled_main(&image,&result)&&result==42, + "preserve 64-bit values when dispatching switch cases above 4 GiB"); + static const char switch_continue_source[]= + "int main(void) { int total = 0; for (int i = 0; i < 5; i++) { " + "switch (i) { case 2: continue; case 4: break; " + "default: total = total + i; } total = total + 10; } return total; }"; + CHECK(!bob64_compile_c(switch_continue_source, + sizeof(switch_continue_source)-1,file,sizeof(file),&length, + &error_offset)&&!bob64_exec_parse(file,length,&image), + "compile switch continue and break nested inside a for loop"); + CHECK(!execute_compiled_main(&image,&result)&&result==44, + "continue skips the loop body while switch break exits only the switch"); + static const char switch_nested_break_source[]= + "int main(void) { int i = 0; int total = 0; while (i < 3) { i++; " + "switch (i) { case 1: switch (i) { case 1: total = total + 2; " + "break; default: total = 99; } total = total + 3; break; " + "case 2: total = total + 5; break; default: break; } " + "total = total + 1; } return total; }"; + CHECK(!bob64_compile_c(switch_nested_break_source, + sizeof(switch_nested_break_source)-1,file,sizeof(file),&length, + &error_offset)&&!bob64_exec_parse(file,length,&image), + "compile nested switches and loops with nearest-break semantics"); + CHECK(!execute_compiled_main(&image,&result)&&result==13, + "route nested switch and loop breaks to their own continuations"); + static const char duplicate_switch_case_source[]= + "int main(void) { switch (1) { case 1: break; case 1: break; } return 0; }"; + CHECK(bob64_compile_c(duplicate_switch_case_source, + sizeof(duplicate_switch_case_source)-1,file,sizeof(file),&length, + &error_offset),"reject duplicate switch case values"); + static const char switch_continue_outside_loop_source[]= + "int main(void) { switch (1) { case 1: continue; } return 0; }"; + CHECK(bob64_compile_c(switch_continue_outside_loop_source, + sizeof(switch_continue_outside_loop_source)-1,file,sizeof(file), + &length,&error_offset),"reject continue outside a loop inside switch"); + static const char nested_do_while_source[]= + "int main(void) { int outer = 0; int total = 0; do { outer = outer + 1; " + "int inner = 0; do { inner = inner + 1; if (inner == 2) continue; " + "if (outer == 2) break; total = total + 1; } while (inner < 3); " + "} while (outer < 3); return total; }"; + CHECK(!bob64_compile_c(nested_do_while_source, + sizeof(nested_do_while_source)-1,file,sizeof(file),&length, + &error_offset)&&!bob64_exec_parse(file,length,&image), + "compile nested do-while loops with local break/continue targets"); + CHECK(!execute_compiled_main(&image,&result)&&result==4, + "route nested do-while break and continue to the correct loop"); + static const char missing_do_while_semicolon[]= + "int main(void) { int count = 0; do { count = count + 1; } " + "while (count < 2) return count; }"; + CHECK(bob64_compile_c(missing_do_while_semicolon, + sizeof(missing_do_while_semicolon)-1,file,sizeof(file),&length, + &error_offset),"reject a do-while loop without its trailing semicolon"); static const char early_return_source[]= "int main(void) { return absolute(-42); } " "int absolute(int value) { if (value < 0) return -value; return value; }"; @@ -1257,6 +1844,26 @@ static int paging_tests(void) { "reuse a virtual page after removing its previous mapping"); CHECK(bob64_page_map(&table,0x0000000100000000ULL,0x1000,0)== BOB64_PAGING_ALREADY_MAPPED,"reject accidental remapping"); + CHECK(bob64_page_map_range(&table,0x6000,0x8000,0x4000,0)== + BOB64_PAGING_ALREADY_MAPPED&& + bob64_page_translate(&table,0x6000,&physical,&flags)==0&& + bob64_page_translate(&table,0x8000,&physical,&flags)==0&& + bob64_page_translate(&table,0x9000,&physical,&flags)==1&& + physical==0xb000, + "roll back new page mappings when a later range page collides"); + CHECK(!bob64_page_map(&table,0x1fd000,0xc000,0)&& + !bob64_page_unmap(&table,0x1fd000,0,0), + "prepare an empty page-table branch for an allocation-failure rollback"); + usize saved_table_capacity=storage.Capacity; + storage.Capacity=storage.Used; + int allocation_rollback_result=bob64_page_map_range(&table,0x1fe000, + 0x8000,0x3000,0); + storage.Capacity=saved_table_capacity; + CHECK(allocation_rollback_result==BOB64_PAGING_NO_MEMORY&& + bob64_page_translate(&table,0x1fe000,&physical,&flags)==0&& + bob64_page_translate(&table,0x1ff000,&physical,&flags)==0&& + bob64_page_translate(&table,0x200000,&physical,&flags)==0, + "roll back a range when page-table allocation fails after earlier pages map"); CHECK(!bob64_page_map_range(&table,0x400123,0x500123,0x2200, BOB64_PAGE_WRITE|BOB64_PAGE_NX), "identity-map a byte range spanning partial first and last pages"); @@ -1417,6 +2024,7 @@ static int descriptor_tests(void) { BOB64_TSS tss; BOB64_IDT_GATE idt[BOB64_IDT_ENTRIES]; BOB64_DESCRIPTOR_TABLE_POINTER pointer; + BOB64_INTERRUPT_FRAME interrupt_frame={0}; const u64 handler=0x1234567887654321ULL; CHECK(!bob64_tss_init(&tss,0x1234567887654000ULL)&&tss.Rsp0==0x1234567887654000ULL&& tss.IoMapBase==sizeof(tss)&&tss.Reserved0==0&& @@ -1429,6 +2037,17 @@ static int descriptor_tests(void) { tss.Rsp0==0xabcdef0087654000ULL, "switch the TSS privilege stack without truncating its 64-bit address"); CHECK(!bob64_tss_init(&tss,0x1234567887654000ULL),"restore a valid TSS after bad input"); + interrupt_frame.CS=BOB64_GDT_KERNEL_CODE_SELECTOR; + CHECK(bob64_interrupt_frame_rsp(&interrupt_frame)== + (u64)(uintptr_t)&interrupt_frame+ + __builtin_offsetof(BOB64_INTERRUPT_FRAME,UserRSP), + "derive interrupted kernel RSP from the same-privilege exception frame"); + interrupt_frame.CS=BOB64_GDT_USER_CODE_SELECTOR; + interrupt_frame.UserRSP=0x123456789abcdef0ULL; + interrupt_frame.UserSS=BOB64_GDT_USER_DATA_SELECTOR; + CHECK(bob64_interrupt_frame_rsp(&interrupt_frame)==0x123456789abcdef0ULL&& + interrupt_frame.UserSS==BOB64_GDT_USER_DATA_SELECTOR, + "preserve the full user RSP and SS from a privilege-change exception frame"); bob64_gdt_init(gdt,&pointer,&tss); CHECK(gdt[0]==0&&gdt[1]==0x00af9a000000ffffULL&& gdt[2]==0x00cf92000000ffffULL&&gdt[3]==0x00cff2000000ffffULL&& @@ -1476,6 +2095,9 @@ static int descriptor_tests(void) { CHECK(idt[0x80].OffsetLow==(u16)(uintptr_t)bob64_syscall_entry&& idt[0x80].TypeAttributes==0xee, "install the user-callable DPL3 syscall gate"); + CHECK(idt[0x24].OffsetLow==(u16)(uintptr_t)bob64_irq4_entry&& + idt[0x24].TypeAttributes==0x8e, + "install the kernel-only COM1 serial IRQ gate"); CHECK(idt[0x21].OffsetLow==(u16)(uintptr_t)bob64_irq1_entry&& idt[0x21].TypeAttributes==0x8e, "install the kernel-only keyboard IRQ gate"); @@ -1804,6 +2426,9 @@ static int syscall_tests(void) { if(bob64_syscall_dispatch(&frame)!=0||frame.RAX!=0x100000123ULL)return -1; frame.RAX=BOB64_SYSCALL_SEEK_HANDLE;frame.RCX=stream_handle;frame.RDX=2; if(bob64_syscall_dispatch(&frame)!=0||frame.RAX!=2)return -1; + frame.RAX=BOB64_SYSCALL_SEEK_HANDLE;frame.RCX=stream_handle; + frame.RDX=0x8000000000000000ULL; + if(bob64_syscall_dispatch(&frame)!=0||(s64)frame.RAX!=-22)return -1; frame.RAX=BOB64_SYSCALL_WRITE_HANDLE;frame.RCX=stream_handle; frame.RDX=first+48;frame.R8=2; if(bob64_syscall_dispatch(&frame)!=0||frame.RAX!=2|| @@ -2117,7 +2742,7 @@ static int heap_test_shrink(void *context,void *region,usize region_size) { static int heap_stress_grow(void *context,void **region,usize *region_size) { HEAP_STRESS_ARENA *arena=(HEAP_STRESS_ARENA *)context; - if(arena->PagesUsed>=128)return 0; + if(arena->PagesUsed>=256)return 0; *region=arena->Bytes+arena->PagesUsed*4096; *region_size=4096; arena->PagesUsed++; @@ -2294,7 +2919,7 @@ static int snapshot_tests(void) { static int firmware_store_tests(void) { static HEAP_STRESS_ARENA arena; - static u8 large_payload[40000]; + static u8 large_payload[100000]; BOB64_HEAP heap; BOB64_FILESYSTEM source,target; EFI_RUNTIME_SERVICES services={0}; @@ -2306,6 +2931,7 @@ static int firmware_store_tests(void) { static const CHAR16 manifest_a[]={'B','o','b','6','4','S','l','o','t','A',0}; static const CHAR16 manifest_b[]={'B','o','b','6','4','S','l','o','t','B',0}; static const CHAR16 chunk_a0[]={'B','o','b','6','4','D','a','t','a','A','0',0}; + static const CHAR16 chunk_a3[]={'B','o','b','6','4','D','a','t','a','A','3',0}; static const CHAR16 chunk_b0[]={'B','o','b','6','4','D','a','t','a','B','0',0}; memset(firmware_test_variables,0,sizeof(firmware_test_variables)); firmware_test_query_unsupported=0; @@ -2361,10 +2987,11 @@ static int firmware_store_tests(void) { large_snapshot_size,&firmware_status,&maximum_variable_size, &remaining_storage_size)&&firmware_status==EFI_SUCCESS&& firmware_test_find(manifest_a)>=0&&firmware_test_find(chunk_a0)>=0&& + firmware_test_find(chunk_a3)>=0&& !bob64_firmware_snapshot_restore(&services,&target)&& !bob64_fs_read(&target,"large.bin",&contents,&length)&& length==sizeof(large_payload)&&!memcmp(contents,large_payload,length), - "split a large snapshot across EFI variables and restore every chunk"); + "split a 100 KiB B64S snapshot across at least four EFI variables and restore every chunk"); bob64_heap_free(&heap,large_snapshot); CHECK(!bob64_fs_write(&target,"keep.txt","still here",10), "seed live state before testing active-slot fallback"); @@ -2727,6 +3354,388 @@ static int executable_tests(void) { return 0; } +static int serial_input_tests(void) { + u8 character=0; + bob64_serial_irq_reset(); + CHECK(bob64_serial_irq_pop(&character)<0, + "report an empty COM1 receive queue"); + for(u32 i=0;i<128;i++) + CHECK(!bob64_serial_irq_capture((u8)i), + "enqueue COM1 input from its interrupt producer"); + CHECK(bob64_serial_irq_capture(0xff)<0, + "drop new COM1 input when the bounded receive queue is full"); + for(u32 i=0;i<128;i++) + CHECK(!bob64_serial_irq_pop(&character)&&character==(u8)i, + "consume COM1 input in FIFO order"); + CHECK(bob64_serial_irq_pop(&character)<0, + "drain the COM1 receive queue completely"); + CHECK(!bob64_serial_irq_capture('b')&&!bob64_serial_irq_pop(&character)&& + character=='b'&&!bob64_serial_irq_capture('o')&& + !bob64_serial_irq_pop(&character)&&character=='o', + "reuse wrapped COM1 queue slots after draining"); + return 0; +} + +typedef struct { + u8 Bus,Device,Function; + u32 Config[16]; +} PCI_TEST_FUNCTION; + +typedef struct { + PCI_TEST_FUNCTION Functions[4]; + u32 FunctionCount; + BOB64_PCI_DEVICE Devices[8]; + u32 DeviceCount; +} PCI_TEST_CONTEXT; + +static int pci_test_read(void *opaque,u8 bus,u8 device,u8 function, + u8 offset,u32 *value) { + PCI_TEST_CONTEXT *context=(PCI_TEST_CONTEXT *)opaque; + if(!context||!value||(offset&3u)||offset>0x3cu)return -1; + *value=0xffffffffu; + for(u32 i=0;iFunctionCount;i++) { + PCI_TEST_FUNCTION *entry=&context->Functions[i]; + if(entry->Bus==bus&&entry->Device==device&&entry->Function==function) { + *value=entry->Config[offset/4];break; + } + } + return 0; +} + +static void pci_test_visit(void *opaque,const BOB64_PCI_DEVICE *device) { + PCI_TEST_CONTEXT *context=(PCI_TEST_CONTEXT *)opaque; + if(context->DeviceCount<8) + context->Devices[context->DeviceCount++]=*device; +} + +static void pci_test_store32(u8 *bytes,u32 offset,u32 value) { + for(u32 i=0;i<4;i++)bytes[offset+i]=(u8)(value>>(i*8)); +} + +static int pci_tests(void) { + PCI_TEST_CONTEXT context={0}; + u32 count=0; + PCI_TEST_FUNCTION *ethernet=&context.Functions[context.FunctionCount++]; + ethernet->Bus=0;ethernet->Device=1; + ethernet->Config[0]=0x100e8086u; + ethernet->Config[2]=0x02000001u; + PCI_TEST_FUNCTION *bridge=&context.Functions[context.FunctionCount++]; + bridge->Bus=0;bridge->Device=2; + bridge->Config[0]=0x244e8086u; + bridge->Config[2]=0x06040000u; + bridge->Config[3]=1u<<16; + bridge->Config[6]=0x00020200u; + PCI_TEST_FUNCTION *xhci=&context.Functions[context.FunctionCount++]; + xhci->Bus=2;xhci->Device=5; + xhci->Config[0]=0x1e318086u; + xhci->Config[2]=0x0c033001u; + xhci->Config[4]=0x80000004u; + xhci->Config[5]=0x000000feu; + xhci->Config[6]=0x0000c001u; + xhci->Config[8]=0xfebc0000u; + CHECK(!bob64_pci_enumerate(pci_test_read,&context,pci_test_visit, + &context,&count)&&count==3&& + context.DeviceCount==3, + "enumerate PCI functions across secondary buses behind bridges"); + CHECK(context.Devices[0].VendorId==0x8086&& + context.Devices[0].ClassCode==0x02&& + context.Devices[1].ClassCode==0x06&& + context.Devices[2].Bus==2&&context.Devices[2].Device==5&& + bob64_pci_is_usb_controller(&context.Devices[2])&& + bob64_pci_is_xhci_controller(&context.Devices[2]), + "decode PCI IDs and identify xHCI USB host controllers"); + CHECK(context.Devices[2].BarValid[0]&&!context.Devices[2].BarIsIo[0]&& + context.Devices[2].Bar[0]==0x000000fe80000000ULL&& + context.Devices[2].BarValid[2]&&context.Devices[2].BarIsIo[2]&& + context.Devices[2].Bar[2]==0xc000&& + context.Devices[2].BarValid[4]&&!context.Devices[2].BarIsIo[4]&& + context.Devices[2].Bar[4]==0xfebc0000u, + "decode 64-bit memory, 32-bit memory, and I/O BAR addresses"); + CHECK(bob64_pci_enumerate(0,0,0,0,&count)<0&& + bob64_pci_enumerate(pci_test_read,&context,0,0,0)<0, + "reject incomplete PCI enumerator arguments"); + u8 xhci_registers[32]={0}; + BOB64_XHCI_CAPABILITIES capabilities={0}; + xhci_registers[0]=0x20;xhci_registers[2]=0;xhci_registers[3]=1; + pci_test_store32(xhci_registers,4,32u|(8u<<8)|(8u<<24)); + pci_test_store32(xhci_registers,0x08,(2u<<27)|(3u<<21)); + pci_test_store32(xhci_registers,0x10,1u); + pci_test_store32(xhci_registers,0x14,0x103u); + pci_test_store32(xhci_registers,0x18,0x21fu); + CHECK(!bob64_xhci_parse_capabilities(xhci_registers, + sizeof(xhci_registers),&capabilities)&& + capabilities.Version==0x0100&&capabilities.CapabilityLength==0x20&& + capabilities.MaxSlots==32&&capabilities.MaxInterrupters==8&& + capabilities.MaxPorts==8&&capabilities.HccParameters1==1&& + capabilities.HcsParameters2==((2u<<27)|(3u<<21))&& + capabilities.MaxScratchpadBuffers==67&& + capabilities.DoorbellOffset==0x100&& + capabilities.RuntimeOffset==0x200, + "parse xHCI version, controller limits, and register offsets"); + xhci_registers[0]=0x10; + CHECK(bob64_xhci_parse_capabilities(xhci_registers, + sizeof(xhci_registers),&capabilities)<0, + "reject malformed xHCI capability lengths"); + CHECK(bob64_usb_control_setup(0xa3,0,0,4,4)==0x00040004000000a3ULL&& + bob64_usb_control_setup(0x23,3,8,3,0)==0x0000000300080323ULL, + "pack USB hub port-status and port-power setup requests little-endian"); + u8 keyboard_configuration[]={ + 9,2,34,0,1,1,0,50,0, + 9,4,0,0,1,3,1,1,0, + 9,0x21,0x11,0x01,0,1,0x22,63,0, + 7,5,0x81,3,8,0,10 + }; + BOB64_USB_HID_BOOT_KEYBOARD keyboard={0}; + BOB64_USB_HID_BOOT_DEVICE usb_mouse={0}; + CHECK(!bob64_usb_find_hid_boot_keyboard(keyboard_configuration, + sizeof(keyboard_configuration),&keyboard)&& + keyboard.ConfigurationValue==1&&keyboard.InterfaceNumber==0&& + keyboard.AlternateSetting==0&&keyboard.InterfaceProtocol==1&& + keyboard.EndpointAddress==0x81&& + keyboard.EndpointAttributes==3&& + keyboard.EndpointMaxPacketSize==8&&keyboard.EndpointInterval==10, + "find a HID boot-keyboard interrupt-IN endpoint"); + keyboard_configuration[16]=2;keyboard_configuration[31]=3; + CHECK(!bob64_usb_find_hid_boot_mouse(keyboard_configuration, + sizeof(keyboard_configuration),&usb_mouse)&& + usb_mouse.InterfaceProtocol==2&&usb_mouse.EndpointAddress==0x81&& + usb_mouse.EndpointMaxPacketSize==3, + "find a HID boot-mouse interface and interrupt-IN endpoint"); + keyboard_configuration[31]=2; + CHECK(bob64_usb_find_hid_boot_mouse(keyboard_configuration, + sizeof(keyboard_configuration),&usb_mouse)==1, + "ignore USB mouse endpoints too small for the three-byte boot report"); + keyboard_configuration[31]=8;keyboard_configuration[16]=1; + keyboard_configuration[30]=0x02; + CHECK(bob64_usb_find_hid_boot_keyboard(keyboard_configuration, + sizeof(keyboard_configuration),&keyboard)==1, + "ignore a non-interrupt HID keyboard endpoint"); + keyboard_configuration[30]=0x03;keyboard_configuration[31]=7; + CHECK(bob64_usb_find_hid_boot_keyboard(keyboard_configuration, + sizeof(keyboard_configuration),&keyboard)==1, + "ignore HID keyboard endpoints too small for an eight-byte boot report"); + keyboard_configuration[31]=8; + keyboard_configuration[27]=0; + CHECK(bob64_usb_find_hid_boot_keyboard(keyboard_configuration, + sizeof(keyboard_configuration),&keyboard)<0, + "reject malformed USB configuration descriptor bounds"); + u8 storage_configuration[]={ + 9,2,32,0,1,2,0,0x80,50, + 9,4,3,0,2,8,6,0x50,0, + 7,5,0x02,2,0x00,0x02,0, + 7,5,0x81,2,0x00,0x02,0 + }; + BOB64_USB_MASS_STORAGE storage={0}; + CHECK(!bob64_usb_find_mass_storage(storage_configuration, + sizeof(storage_configuration),&storage)&& + storage.ConfigurationValue==2&&storage.InterfaceNumber==3&& + storage.AlternateSetting==0&&storage.BulkOutEndpoint==2&& + storage.BulkInEndpoint==0x81&& + storage.BulkOutMaxPacketSize==512&& + storage.BulkInMaxPacketSize==512, + "find USB SCSI Bulk-Only storage interfaces and bulk endpoints"); + storage_configuration[16]=0x62; + CHECK(bob64_usb_find_mass_storage(storage_configuration, + sizeof(storage_configuration),&storage)==1, + "ignore USB storage interfaces with a non-Bulk-Only protocol"); + storage_configuration[16]=0x50; + storage_configuration[27]=0x01; + CHECK(bob64_usb_find_mass_storage(storage_configuration, + sizeof(storage_configuration),&storage)==1, + "ignore USB storage configurations without a bulk-IN endpoint"); + storage_configuration[27]=0x81; + storage_configuration[25]=1; + CHECK(bob64_usb_find_mass_storage(storage_configuration, + sizeof(storage_configuration),&storage)<0, + "reject malformed USB mass-storage endpoint descriptors"); + u8 msc_cbw[BOB64_USB_MSC_CBW_SIZE],capacity_cdb[10]={0x25}; + u8 msc_csw[BOB64_USB_MSC_CSW_SIZE]={0x55,0x53,0x42,0x53, + 0x78,0x56,0x34,0x12,0x08,0,0,0,0}; + u32 msc_residue=0xffffffffu; + u8 msc_status=0xff; + CHECK(!bob64_usb_msc_build_cbw(msc_cbw,sizeof(msc_cbw),0x12345678u, + 0x10203040u,1,2,capacity_cdb,sizeof(capacity_cdb))&& + msc_cbw[0]=='U'&&msc_cbw[1]=='S'&&msc_cbw[2]=='B'&& + msc_cbw[3]=='C'&&msc_cbw[4]==0x78&&msc_cbw[7]==0x12&& + msc_cbw[8]==0x40&&msc_cbw[11]==0x10&&msc_cbw[12]==0x80&& + msc_cbw[13]==2&&msc_cbw[14]==10&&msc_cbw[15]==0x25&& + msc_cbw[25]==0, + "encode a USB Mass Storage BOT command block with 64-bit-safe fields"); + CHECK(!bob64_usb_msc_parse_csw(msc_csw,sizeof(msc_csw),0x12345678u, + 0x10203040u,&msc_residue,&msc_status)&&msc_residue==8&& + msc_status==0, + "validate a matching BOT command status and transfer residue"); + msc_residue=0xabcdef01u;msc_status=0x7f; + CHECK(bob64_usb_msc_parse_csw(msc_csw,sizeof(msc_csw),7, + 0x10203040u,&msc_residue,&msc_status)<0&& + msc_residue==0xabcdef01u&&msc_status==0x7f&& + bob64_usb_msc_parse_csw(msc_csw,12,0x12345678u, + 0x10203040u,&msc_residue,&msc_status)<0, + "reject mismatched or truncated BOT status without changing outputs"); + msc_csw[8]=0x41;msc_csw[9]=0x30;msc_csw[10]=0x20;msc_csw[11]=0x10; + CHECK(bob64_usb_msc_parse_csw(msc_csw,sizeof(msc_csw),0x12345678u, + 0x10203040u,&msc_residue,&msc_status)<0, + "reject BOT status residues larger than the requested transfer"); + msc_csw[8]=0;msc_csw[9]=0;msc_csw[10]=0;msc_csw[11]=0;msc_csw[12]=3; + CHECK(bob64_usb_msc_parse_csw(msc_csw,sizeof(msc_csw),0x12345678u, + 0x10203040u,&msc_residue,&msc_status)<0&& + bob64_usb_msc_build_cbw(msc_cbw,30,0x12345678u,0,0,0, + capacity_cdb,sizeof(capacity_cdb))<0, + "reject invalid BOT status codes and undersized command buffers"); + u8 rw_cdb[16],rw_cdb_length=0; + CHECK(!bob64_scsi_build_read_write_cdb(0x12345678u,3,0,rw_cdb, + &rw_cdb_length)&&rw_cdb_length==10&&rw_cdb[0]==0x28&& + rw_cdb[2]==0x12&&rw_cdb[5]==0x78&&rw_cdb[8]==3&& + !bob64_scsi_build_read_write_cdb(0x100000000ULL,3,1,rw_cdb, + &rw_cdb_length)&&rw_cdb_length==16&&rw_cdb[0]==0x8a&& + rw_cdb[5]==1&&rw_cdb[9]==0&&rw_cdb[13]==3, + "encode SCSI 10-byte and 16-byte reads and writes across the 32-bit LBA boundary"); + CHECK(!bob64_scsi_build_read_write_cdb(0xffffffffULL,2,0,rw_cdb, + &rw_cdb_length)&&rw_cdb_length==16&&rw_cdb[0]==0x88&& + bob64_scsi_build_read_write_cdb(0,0,0,rw_cdb,&rw_cdb_length)<0&& + bob64_scsi_build_read_write_cdb(~(u64)0,2,0,rw_cdb, + &rw_cdb_length)<0, + "select 16-byte SCSI commands when a range crosses 4 GiB and reject invalid ranges"); + u8 capacity10_response[8]={0xff,0xff,0xff,0xff,0,0,2,0}; + u8 capacity16_response[32]={0,0,0,1,0,0,0,0,0,0,2,0}; + u8 capacity16_cdb[16];u64 capacity_blocks=0;u32 capacity_block_size=0; + int needs_capacity16=0; + CHECK(!bob64_scsi_parse_read_capacity10(capacity10_response,8, + &capacity_blocks,&capacity_block_size,&needs_capacity16)&& + needs_capacity16&&capacity_blocks==0&&capacity_block_size==512&& + !bob64_scsi_build_read_capacity16_cdb(capacity16_cdb)&& + capacity16_cdb[0]==0x9e&&capacity16_cdb[1]==0x10&& + capacity16_cdb[13]==32&& + !bob64_scsi_parse_read_capacity16(capacity16_response,32, + &capacity_blocks,&capacity_block_size)&& + capacity_blocks==0x100000001ULL&&capacity_block_size==512, + "probe and parse SCSI READ CAPACITY(16) for disks larger than 2 TiB"); + u8 hub_descriptor[]={9,0x29,2,0x09,0x00,5,25,0x05,0x03}; + BOB64_USB_HUB_DESCRIPTOR hub={0}; + CHECK(!bob64_usb_parse_hub_descriptor(hub_descriptor, + sizeof(hub_descriptor),&hub)&&hub.PortCount==2&& + hub.Characteristics==9&&hub.PowerOnToGood==5&& + hub.ControllerCurrent==25&&hub.DeviceRemovable[0]==5&& + hub.PortPowerControlMask[0]==3, + "parse USB 2 hub characteristics and port bitmaps"); + u8 eight_port_hub_descriptor[]={10,0x29,8,0x0a,0,0,1,0,0,0xff}; + CHECK(!bob64_usb_parse_hub_descriptor(eight_port_hub_descriptor, + sizeof(eight_port_hub_descriptor),&hub)&&hub.PortCount==8&& + hub.DeviceRemovable[1]==0&& + hub.PortPowerControlMask[0]==0xff, + "parse distinct removable and power-mask bitmap sizes for eight ports"); + u8 largest_hub_descriptor[39]={39,0x29,127,0x34,0x12,10,50}; + largest_hub_descriptor[22]=0xa5; + largest_hub_descriptor[38]=0x5a; + CHECK(!bob64_usb_parse_hub_descriptor(largest_hub_descriptor, + sizeof(largest_hub_descriptor),&hub)&&hub.PortCount==127&& + hub.DeviceRemovable[15]==0xa5&& + hub.PortPowerControlMask[15]==0x5a, + "parse the maximum supported USB hub port bitmap"); + hub_descriptor[1]=2; + CHECK(bob64_usb_parse_hub_descriptor(hub_descriptor, + sizeof(hub_descriptor),&hub)<0, + "reject a non-hub USB descriptor"); + hub_descriptor[1]=0x29;hub_descriptor[2]=0; + CHECK(bob64_usb_parse_hub_descriptor(hub_descriptor, + sizeof(hub_descriptor),&hub)<0, + "reject a USB hub with no ports"); + hub_descriptor[2]=3;hub_descriptor[0]=8; + CHECK(bob64_usb_parse_hub_descriptor(hub_descriptor, + sizeof(hub_descriptor),&hub)<0, + "reject a USB hub descriptor truncated before both bitmaps"); + hub_descriptor[0]=9;hub_descriptor[2]=2; + CHECK(bob64_usb_parse_hub_descriptor(hub_descriptor,8,&hub)<0&& + bob64_usb_parse_hub_descriptor(hub_descriptor, + sizeof(hub_descriptor),0)<0, + "reject truncated hub input and missing parser output"); + u8 hub_configuration[]={ + 9,2,25,0,1,1,0,0x80,50, + 9,4,0,0,1,9,0,0,0, + 7,5,0x81,3,1,0,12 + }; + BOB64_USB_HUB_INTERFACE hub_interface={0}; + CHECK(!bob64_usb_find_hub_interface(hub_configuration, + sizeof(hub_configuration),&hub_interface)&& + hub_interface.ConfigurationValue==1&& + hub_interface.InterfaceNumber==0&& + hub_interface.EndpointAddress==0x81&& + hub_interface.EndpointAttributes==3&& + hub_interface.EndpointMaxPacketSize==1&& + hub_interface.EndpointInterval==12, + "find the hub-class interface status interrupt endpoint"); + hub_configuration[21]=2; + CHECK(bob64_usb_find_hub_interface(hub_configuration, + sizeof(hub_configuration),&hub_interface)==1, + "ignore hub interfaces without an interrupt-IN status endpoint"); + hub_configuration[21]=3;hub_configuration[18]=6; + CHECK(bob64_usb_find_hub_interface(hub_configuration, + sizeof(hub_configuration),&hub_interface)<0, + "reject malformed hub endpoint descriptors"); + u32 route=0; + CHECK(!bob64_usb_route_string_append(0,0,3,&route)&&route==3&& + !bob64_usb_route_string_append(route,1,7,&route)&&route==0x73&& + !bob64_usb_route_string_append(route,2,16,&route)&&route==0xf73&& + bob64_usb_route_string_append(route,3,0,&route)<0&& + bob64_usb_route_string_append(0,5,1,&route)<0&& + bob64_usb_route_string_append(0x10,1,1,&route)<0, + "append validated USB port hops to five-level xHCI route strings"); + return 0; +} + +typedef struct { + u32 Command,Status; + int ResetCompletes; +} XHCI_TEST_REGISTERS; + +static int xhci_test_read(void *opaque,u32 offset,u32 *value) { + XHCI_TEST_REGISTERS *registers=(XHCI_TEST_REGISTERS *)opaque; + if(!registers||!value)return -1; + if(offset==0)*value=registers->Command; + else if(offset==4)*value=registers->Status; + else return -1; + return 0; +} + +static int xhci_test_write(void *opaque,u32 offset,u32 value) { + XHCI_TEST_REGISTERS *registers=(XHCI_TEST_REGISTERS *)opaque; + if(!registers||offset)return -1; + registers->Command=value; + if(value&BOB64_XHCI_USBCMD_RESET) { + if(registers->ResetCompletes) { + registers->Command&=~BOB64_XHCI_USBCMD_RESET; + registers->Status=BOB64_XHCI_USBSTS_HALTED; + } + } else if(value&BOB64_XHCI_USBCMD_RUN) + registers->Status&=~BOB64_XHCI_USBSTS_HALTED; + else registers->Status|=BOB64_XHCI_USBSTS_HALTED; + return 0; +} + +static int xhci_tests(void) { + XHCI_TEST_REGISTERS registers={BOB64_XHCI_USBCMD_RUN,0,1}; + u32 final_status=0; + CHECK(!bob64_xhci_halt_reset(xhci_test_read,xhci_test_write,®isters, + 8,&final_status)&& + !(registers.Command&(BOB64_XHCI_USBCMD_RUN| + BOB64_XHCI_USBCMD_RESET))&& + (final_status&BOB64_XHCI_USBSTS_HALTED), + "halt a running xHCI controller and wait for reset completion"); + registers=(XHCI_TEST_REGISTERS){0,BOB64_XHCI_USBSTS_HALTED,1}; + CHECK(!bob64_xhci_halt_reset(xhci_test_read,xhci_test_write,®isters, + 8,&final_status), + "reset an xHCI controller that is already halted"); + registers=(XHCI_TEST_REGISTERS){0,BOB64_XHCI_USBSTS_HALTED,0}; + CHECK(bob64_xhci_halt_reset(xhci_test_read,xhci_test_write,®isters, + 3,&final_status)==-2, + "time out when an xHCI controller does not finish reset"); + registers=(XHCI_TEST_REGISTERS){0,BOB64_XHCI_USBSTS_NOT_READY,1}; + CHECK(bob64_xhci_halt_reset(xhci_test_read,xhci_test_write,®isters, + 3,&final_status)==-2, + "wait for xHCI controller-not-ready state to clear"); + return 0; +} + static int keyboard_tests(void) { BOB64_KEYBOARD_STATE state={0}; BOB64_EVENT event; @@ -2802,6 +3811,65 @@ static int keyboard_tests(void) { !bob64_keyboard_irq_pop_event(&event)&&event.Character=='a', "drop new keyboard events when the IRQ queue is full"); bob64_keyboard_irq_set_active(0); + bob64_keyboard_reset();bob64_keyboard_irq_set_active(1); + u8 hid_report[8]={0,0,4,0,0,0,0,0}; + CHECK(!bob64_keyboard_hid_report(hid_report)&& + !bob64_keyboard_irq_pop_event(&event)&& + event.Type==BOB64_EVENT_KEY_DOWN&&event.Key==0x1e&& + event.Character=='a', + "translate a USB HID boot report into the shared lowercase key event"); + hid_report[0]=2;hid_report[2]=0; + CHECK(!bob64_keyboard_hid_report(hid_report)&& + !bob64_keyboard_irq_pop_event(&event)&&event.Key==0x2a&& + event.Type==BOB64_EVENT_KEY_DOWN&& + !bob64_keyboard_irq_pop_event(&event)&&event.Key==0x1e&& + event.Type==BOB64_EVENT_KEY_UP, + "translate USB modifier changes and release a held key"); + hid_report[2]=4; + CHECK(!bob64_keyboard_hid_report(hid_report)&& + !bob64_keyboard_irq_pop_event(&event)&&event.Key==0x1e&& + event.Type==BOB64_EVENT_KEY_DOWN&&event.Character=='A', + "translate USB modifier state before producing shifted text"); + hid_report[0]=0;hid_report[2]=0; + CHECK(!bob64_keyboard_hid_report(hid_report)&& + !bob64_keyboard_irq_pop_event(&event)&&event.Key==0x2a&& + event.Type==BOB64_EVENT_KEY_UP&& + !bob64_keyboard_irq_pop_event(&event)&&event.Key==0x1e&& + event.Type==BOB64_EVENT_KEY_UP, + "emit USB modifier and key releases through the shared event queue"); + hid_report[2]=1; + CHECK(bob64_keyboard_hid_report(hid_report)<0&& + bob64_keyboard_irq_pop_event(&event)<0, + "ignore USB HID rollover reports without fabricating releases"); + bob64_keyboard_reset();bob64_keyboard_irq_set_active(0); + { + BOB64_KEYBOARD_HID_STATE first_keyboard={0},second_keyboard={0}; + u8 first_report[8]={0,0,4,0,0,0,0,0}; + u8 second_report[8]={0,0,5,0,0,0,0,0}; + u8 empty_report[8]={0}; + bob64_keyboard_reset();bob64_keyboard_irq_set_active(1); + CHECK(!bob64_keyboard_hid_report_device(&first_keyboard,first_report)&& + !bob64_keyboard_irq_pop_event(&event)&&event.Key==0x1e&& + event.Type==BOB64_EVENT_KEY_DOWN&&event.Character=='a', + "translate a key held on the first independent USB keyboard"); + CHECK(!bob64_keyboard_hid_report_device(&second_keyboard,second_report)&& + !bob64_keyboard_irq_pop_event(&event)&&event.Key==0x30&& + event.Type==BOB64_EVENT_KEY_DOWN&&event.Character=='b', + "preserve separate held-key state for a second USB keyboard"); + CHECK(!bob64_keyboard_hid_report_device(&first_keyboard,empty_report)&& + !bob64_keyboard_irq_pop_event(&event)&&event.Key==0x1e&& + event.Type==BOB64_EVENT_KEY_UP&& + !bob64_keyboard_hid_report_device(&second_keyboard,empty_report)&& + !bob64_keyboard_irq_pop_event(&event)&&event.Key==0x30&& + event.Type==BOB64_EVENT_KEY_UP, + "release keys independently when multiple USB keyboards are attached"); + bob64_keyboard_reset();bob64_keyboard_irq_set_active(0); + } + hid_report[0]=0;hid_report[2]=4; + CHECK(!bob64_keyboard_hid_report(hid_report)&& + bob64_keyboard_poll()=='a', + "deliver queued USB keyboard text while PS/2 input is polling-only"); + bob64_keyboard_irq_set_active(0); return 0; } @@ -2859,6 +3927,64 @@ static int mouse_tests(void) { "decode extended mouse buttons alongside wheel movement"); CHECK(!bob64_mouse_irq_queue_init(100,80), "initialize the IRQ mouse packet decoder and event queue"); + CHECK(!bob64_mouse_usb_report(0,4,3,0)&& + !bob64_mouse_poll_event(&event)&& + event.Type==BOB64_EVENT_MOUSE_MOVE&&event.X==54&&event.Y==43&& + event.DeltaX==4&&event.DeltaY==3, + "route USB mouse movement through the shared pointer event queue"); + CHECK(!bob64_mouse_usb_report(1,0,0,0)&& + !bob64_mouse_poll_event(&event)&& + event.Type==BOB64_EVENT_MOUSE_BUTTON&&event.Buttons==1&& + event.X==54&&event.Y==43, + "route USB mouse button transitions through the shared event queue"); + CHECK(!bob64_mouse_usb_report(0,-4,-3,0)&& + !bob64_mouse_poll_event(&event)&&!event.Buttons&& + event.X==50&&event.Y==40, + "release USB mouse buttons and preserve signed movement"); + CHECK(!bob64_mouse_usb_report(0,0,0,-1)&& + !bob64_mouse_poll_event(&event)&& + event.Type==BOB64_EVENT_MOUSE_WHEEL&&event.Wheel==-1&& + event.X==50&&event.Y==40, + "route signed USB mouse wheel reports through the shared event queue"); + CHECK(!bob64_mouse_irq_queue_init(100,80)&& + !bob64_mouse_usb_report_device(0,1,0,0,0)&& + !bob64_mouse_poll_event(&event)&&event.Buttons==1&& + !bob64_mouse_usb_report_device(1,2,0,0,0)&& + !bob64_mouse_poll_event(&event)&&event.Buttons==3&& + !bob64_mouse_usb_report_device(0,0,0,0,0)&& + !bob64_mouse_poll_event(&event)&&event.Buttons==2&& + !bob64_mouse_usb_report_device(1,0,0,0,0)&& + !bob64_mouse_poll_event(&event)&&event.Buttons==0&& + bob64_mouse_usb_report_device(BOB64_MOUSE_USB_DEVICE_LIMIT, + 0,0,0,0)<0, + "aggregate independent button holds and releases from multiple USB mice"); + CHECK(!bob64_mouse_irq_queue_init(100,80)&& + !bob64_mouse_usb_report_device(8,1,0,0,0)&& + !bob64_mouse_poll_event(&event)&&event.Buttons==1&& + !bob64_mouse_usb_report_device(31,2,0,0,0)&& + !bob64_mouse_poll_event(&event)&&event.Buttons==3&& + !bob64_mouse_usb_report_device(8,0,0,0,0)&& + !bob64_mouse_poll_event(&event)&&event.Buttons==2&& + !bob64_mouse_usb_report_device(31,0,0,0,0)&& + !bob64_mouse_poll_event(&event)&&event.Buttons==0&& + bob64_mouse_usb_report_device(32,1,0,0,0)<0, + "aggregate independent USB mouse holds above the former eight-device limit"); + CHECK(!bob64_mouse_irq_queue_init(100,80)&& + !bob64_mouse_usb_report_device(2,2,0,0,0)&& + !bob64_mouse_poll_event(&event)&&event.Buttons==2&& + bob64_mouse_irq_capture(0x09)<0&& + bob64_mouse_irq_capture(0)<0&& + !bob64_mouse_irq_capture(0)&& + !bob64_mouse_poll_event(&event)&&event.Buttons==3&& + !bob64_mouse_usb_report_device(2,0,0,0,0)&& + !bob64_mouse_poll_event(&event)&&event.Buttons==1&& + bob64_mouse_irq_capture(0x08)<0&& + bob64_mouse_irq_capture(0)<0&& + !bob64_mouse_irq_capture(0)&& + !bob64_mouse_poll_event(&event)&&event.Buttons==0, + "combine USB and PS/2 mouse buttons without losing another device's hold"); + CHECK(!bob64_mouse_irq_queue_init(100,80), + "reset pointer state before testing PS/2 mouse IRQ packets"); bob64_mouse_irq_set_active(1); CHECK(bob64_mouse_irq_capture(0x08)<0&&bob64_mouse_irq_capture(1)<0&& !bob64_mouse_irq_capture(0)&&!bob64_mouse_irq_pop_event(&event)&& @@ -2906,6 +4032,21 @@ static int window_manager_tests(void) { CHECK(bob64_wm_dispatch(&manager,&event,&routed)==(s64)second&& !manager.Dragging&&windows[1].X==95&&windows[1].Y==100, "apply final pointer movement before ending a drag"); + event=(BOB64_EVENT){0};event.Type=BOB64_EVENT_MOUSE_BUTTON; + event.Buttons=1;event.X=100;event.Y=110; + CHECK(bob64_wm_dispatch(&manager,&event,&routed)==(s64)second&& + manager.Dragging==second, + "begin another window drag before testing extreme pointer coordinates"); + event=(BOB64_EVENT){0};event.Type=BOB64_EVENT_MOUSE_MOVE; + event.Buttons=1;event.X=(-2147483647-1);event.Y=2147483647; + CHECK(bob64_wm_dispatch(&manager,&event,&routed)==(s64)second&& + windows[1].X==0&&windows[1].Y==330&& + routed.X==(-2147483647-1)&&routed.Y==2147483317, + "safely clamp a dragged window and local pointer at signed-coordinate limits"); + event.Type=BOB64_EVENT_MOUSE_BUTTON;event.Buttons=0; + CHECK(bob64_wm_dispatch(&manager,&event,&routed)==(s64)second&& + !manager.Dragging, + "release a window drag after an out-of-range pointer event"); CHECK(!bob64_wm_move(&manager,second,1000,1000)&& windows[1].X==440&&windows[1].Y==330, "clamp moved windows to the screen edges"); @@ -2935,6 +4076,20 @@ static int window_manager_tests(void) { CHECK(!bob64_wm_destroy(&manager,wide_handle)&& bob64_wm_destroy(&manager,wide_handle)<0, "destroy window handles without leaving stale slots"); + CHECK(!bob64_wm_init(&manager,windows,4,order,100,80), + "initialize a small window manager for USB wheel routing"); + first=bob64_wm_create(&manager,10,10,80,60,0); + CHECK(first,"create a GUI window for USB wheel routing"); + CHECK(!bob64_mouse_irq_queue_init(100,80), + "initialize the pointer before testing USB wheel routing"); + CHECK(!bob64_mouse_usb_report(0,0,0,-1), + "enqueue USB wheel input before GUI routing"); + CHECK(!bob64_mouse_poll_event(&event)&& + event.Type==BOB64_EVENT_MOUSE_WHEEL&&event.Wheel==-1, + "read the USB wheel event from the shared mouse queue"); + CHECK(bob64_wm_dispatch(&manager,&event,&routed)==(s64)first&& + routed.X==40&&routed.Y==30&&routed.Wheel==-1, + "route a USB wheel event from the shared mouse queue into the managed GUI window"); return 0; } @@ -2949,6 +4104,39 @@ static int gui_widget_tests(void) { bob64_rect_contains(&(BOB64_RECT){0x7ffffff0,0,64,8}, 0x7ffffff0,1), "hit-test 64-bit GUI widget rectangles without signed endpoint overflow"); + bob64_gfx_fill_rect(&graphics,-4,0,8,1,0x00123456u); + CHECK(pixels[0]==0x00123456u&&pixels[3]==0x00123456u&&pixels[4]==0, + "clip partially off-screen GUI rectangles to the framebuffer"); + bob64_gfx_fill_rect(&graphics,(-2147483647-1),1,0xffffffffu,1, + 0x00654321u); + CHECK(pixels[24]==0x00654321u&&pixels[47]==0x00654321u, + "clip full-width GUI rectangles without overflowing or walking off-screen pixels"); + for(u32 i=0;i<24;i++)pixels[10*24+i]=0; + bob64_gfx_line(&graphics,(-2147483647-1),10,2147483647,10, + 0x00abcdefu); + CHECK(pixels[10*24]==0x00abcdefu&&pixels[10*24+23]==0x00abcdefu, + "clip a full-range horizontal line before rasterizing it"); + bob64_gfx_line(&graphics,(-2147483647-1),(-2147483647-1), + 2147483647,2147483647,0x00010203u); + CHECK(pixels[0]==0x00010203u&&pixels[19*24+19]==0x00010203u, + "clip a full-range diagonal line without signed arithmetic overflow"); + u32 undersized_pixels[1]={0}; + BOB64_GFX undersized_graphics={undersized_pixels,24,20,1}; + bob64_gfx_pixel(&undersized_graphics,0,0,0x00ffffffu); + CHECK(undersized_pixels[0]==0, + "reject framebuffer writes when the pixel capacity is too small"); + u32 scaled_text_pixels[16]={0}; + BOB64_GFX scaled_text_graphics={scaled_text_pixels,4,4,16}; + bob64_gfx_text(&scaled_text_graphics,(-2147483647-1),0,"A", + 0x00ffffffu,0x80000000u); + CHECK(scaled_text_pixels[0]==0x00ffffffu&& + scaled_text_pixels[15]==0x00ffffffu, + "clip a maximum-scale glyph using widened text coordinates"); + for(u32 i=0;i<16;i++)scaled_text_pixels[i]=0; + bob64_gfx_text(&scaled_text_graphics,2147483647,2147483647,"A", + 0x00ffffffu,0xffffffffu); + for(u32 i=0;i<16;i++)CHECK(scaled_text_pixels[i]==0, + "keep extreme off-screen glyph placement outside the framebuffer"); event.Type=BOB64_EVENT_MOUSE_MOVE;event.X=4;event.Y=5; CHECK(!bob64_button_event(&rect,&state,&event)&&state.Hovered&&!state.Pressed&& !bob64_button_draw(&graphics,&rect,"OK",&state)&& @@ -2975,6 +4163,50 @@ static int gui_widget_tests(void) { bob64_button_draw(&graphics,&rect, "THIS LABEL DOES NOT FIT",&state)<0, "reject overflowing or unclipped native GUI button geometry"); + u32 menu_pixels[96*48]={0}; + BOB64_GFX menu_graphics={menu_pixels,96,48,96*48}; + BOB64_RECT menu_rect={4,4,84,36}; + const char *const menu_items[]={"OPEN FILE","DELETE FILE"}; + const char *const wide_menu_items[]={"OPEN","DELETE","CLOSE"}; + BOB64_MENU_STATE menu_state={0,-1,1}; + CHECK(!bob64_menu_draw(&menu_graphics,&menu_rect,menu_items,2,18, + &menu_state)&& + menu_pixels[5*96+5]==0x00335d8cu, + "draw a selected item in the reusable popup menu"); + event=(BOB64_EVENT){0};event.Type=BOB64_EVENT_MOUSE_MOVE; + event.X=12;event.Y=25; + CHECK(bob64_menu_event(&menu_rect,menu_items,2,18,&menu_state,&event)==-1&& + menu_state.Selected==1, + "move popup selection with mouse hover"); + event.Type=BOB64_EVENT_MOUSE_BUTTON;event.Buttons=BOB64_BUTTON_LEFT; + CHECK(bob64_menu_event(&menu_rect,menu_items,2,18,&menu_state,&event)==-1&& + menu_state.Pressed==1, + "arm a popup action on left-button press"); + event.Buttons=0; + CHECK(bob64_menu_event(&menu_rect,menu_items,2,18,&menu_state,&event)==1&& + !menu_state.Open&&menu_state.Pressed==-1, + "activate a popup action only after release inside its row"); + menu_state=(BOB64_MENU_STATE){0,-1,1}; + event=(BOB64_EVENT){0};event.Type=BOB64_EVENT_KEY_DOWN; + event.Key=BOB64_EVENT_KEY_EXTENDED|0x50; + CHECK(bob64_menu_event(&menu_rect,menu_items,2,18,&menu_state,&event)==-1&& + menu_state.Selected==1, + "navigate popup menu items with the Down key"); + event.Key=0;event.Character='\n'; + CHECK(bob64_menu_event(&menu_rect,menu_items,2,18,&menu_state,&event)==1&& + !menu_state.Open, + "activate the selected popup item with Enter"); + menu_state=(BOB64_MENU_STATE){0,-1,1};event.Character=0x1b; + CHECK(bob64_menu_event(&menu_rect,menu_items,2,18,&menu_state,&event)==-2&& + !menu_state.Open, + "dismiss a popup menu with Escape"); + menu_state=(BOB64_MENU_STATE){0,-1,1}; + menu_rect=(BOB64_RECT){0,-2147483647-1,1,0xffffffffu}; + event=(BOB64_EVENT){0};event.Type=BOB64_EVENT_MOUSE_MOVE; + event.X=0;event.Y=2147483646; + CHECK(bob64_menu_event(&menu_rect,wide_menu_items,3,2147483647u, + &menu_state,&event)==-1&&menu_state.Selected==2, + "compute popup rows safely across the full signed-coordinate range"); u32 field_pixels[96*24]={0}; char text[16]="notes.txt"; BOB64_GFX field_graphics={field_pixels,96,24,96*24}; @@ -2983,6 +4215,14 @@ static int gui_widget_tests(void) { CHECK(!bob64_text_field_init(&field,text,sizeof(text))&& field.Length==9&&field.Cursor==9, "initialize a bounded native filename text field"); + field_rect=(BOB64_RECT){-2147483647-1,-2147483647-1,0xffffffffu, + 0xffffffffu}; + event=(BOB64_EVENT){0};event.Type=BOB64_EVENT_MOUSE_BUTTON; + event.Buttons=BOB64_BUTTON_LEFT;event.X=2147483646;event.Y=0; + CHECK(!bob64_text_field_event(&field,&field_rect,&event)&&field.Focused&& + field.Cursor==field.Length, + "place a text-field caret without overflowing signed coordinates"); + field_rect=(BOB64_RECT){2,2,72,16}; event=(BOB64_EVENT){0};event.Type=BOB64_EVENT_MOUSE_BUTTON; event.Buttons=BOB64_BUTTON_LEFT;event.X=field_rect.X+3+5*6; event.Y=field_rect.Y+6; @@ -3039,17 +4279,28 @@ static int window_server_tests(void) { 8,8,8,0)&& !bob64_window_server_init(&server,&heap,owner,8,8), "initialize a kernel-owned compositor for one 64-bit app owner"); + CHECK(!server.Damaged&&server.BytesAllocated==0, + "clear initial full-screen damage after compositor setup"); first=bob64_window_server_create(&server,owner,1,1,3,3); CHECK(first&&bob64_window_server_write_pixels(&server,owner,first,0,red,9)==0&& !bob64_window_server_present(&server,owner,first)&& - framebuffer[1*8+1]==0x000000ffu&&framebuffer[0]!=0x000000ffu, - "composite an app surface without exposing its kernel window record"); + framebuffer[1*8+1]==0x000000ffu&&framebuffer[0]!=0x000000ffu&& + !server.Damaged, + "composite and retire damage for an app surface"); second=bob64_window_server_create(&server,owner,2,2,3,3); CHECK(second&&second!=first&& bob64_window_server_write_pixels(&server,owner,second,0,green,9)==0&& !bob64_window_server_present(&server,owner,second)&& - framebuffer[2*8+2]==0x0000ff00u&&framebuffer[1*8+1]==0x000000ffu, + framebuffer[2*8+2]==0x0000ff00u&&framebuffer[1*8+1]==0x000000ffu&& + !server.Damaged, "compose overlapping surfaces in z-order while preserving visible pixels"); + u32 yellow=0x00ffff00u; + CHECK(!bob64_window_server_write_pixels(&server,owner,second,4,&yellow,1)&& + server.Damaged&&server.DamageLeft==3&&server.DamageTop==3&& + server.DamageRight==4&&server.DamageBottom==4&& + !bob64_window_server_present(&server,owner,second)&& + framebuffer[3*8+3]==0x0000ffffu&&!server.Damaged, + "composite a single changed surface pixel without repainting the screen"); CHECK(bob64_window_server_present(&server,owner+1,second)<0&& bob64_window_server_move(&server,owner+1,second,4,4)<0&& bob64_window_server_destroy(&server,owner+1,second)<0, @@ -3060,6 +4311,12 @@ static int window_server_tests(void) { routed.ScreenX==3&&routed.ScreenY==3&&server.Manager.Focused==second&& server.Manager.Dragging==second, "route mouse focus and title-bar dragging through kernel window state"); + event.Type=BOB64_EVENT_MOUSE_MOVE;event.Buttons=1;event.X=3;event.Y=3; + CHECK(bob64_window_server_route_event(&server,owner,&event,&routed)==(s64)second&& + !server.Damaged, + "skip framebuffer composition for a mouse move that changes no pixels"); + event.Type=BOB64_EVENT_MOUSE_BUTTON;event.Buttons=0;event.X=3;event.Y=3; + (void)bob64_window_server_route_event(&server,owner,&event,&routed); CHECK(!bob64_window_server_move(&server,owner,second,4,4)&& framebuffer[2*8+2]==0x000000ffu&&framebuffer[4*8+4]==0x0000ff00u, "redraw exposed surfaces after a window moves"); @@ -3307,7 +4564,7 @@ static int shell_tests(void) { "clear command resets the display"); shell_test_command(&shell,"help"); CHECK(strstr(output.Text,"version show kernel version")!=0&& - strstr(output.Text,"restore restore firmware or RAM checkpoint")!=0&& + strstr(output.Text,"restore restore persistent or RAM checkpoint")!=0&& strstr(output.Text,"cc SOURCE [OUTPUT]")!=0&& strstr(output.Text,"desktop.b64e [FILE]")!=0&& strstr(output.Text,"Up/Down command history")!=0, @@ -3383,6 +4640,9 @@ int main(int argc,char **argv) { CHECK(memory_tests()==0,"physical page allocator regression tests"); CHECK(console_tests()==0,"GOP framebuffer console regression tests"); CHECK(compression_tests()==0,"bounded LZ4 snapshot compression regression tests"); + CHECK(block_device_tests()==0,"bounded block-device read/write/flush regression tests"); + CHECK(partition_tests()==0,"CRC-checked GPT bob64 data-partition discovery tests"); + CHECK(disk_store_tests()==0,"transactional block-backed B64S snapshot persistence tests"); CHECK(heap_tests()==0,"64-bit heap allocator regression tests"); CHECK(snapshot_tests()==0,"versioned B64S snapshot regression tests"); CHECK(firmware_store_tests()==0, @@ -3393,6 +4653,9 @@ int main(int argc,char **argv) { CHECK(compiler_process_tests(resident_compiler_image, resident_compiler_image_length)==0, "resident compiler output integration with the process loader"); + CHECK(serial_input_tests()==0,"COM1 interrupt receive-queue regression tests"); + CHECK(pci_tests()==0,"PCI bus and USB host-controller enumeration tests"); + CHECK(xhci_tests()==0,"xHCI halt/reset state-machine tests"); CHECK(keyboard_tests()==0,"PS/2 keyboard scan-code regression tests"); CHECK(mouse_tests()==0,"PS/2 mouse packet and pointer regression tests"); CHECK(window_manager_tests()==0,"64-bit GUI window-manager regression tests"); @@ -3463,7 +4726,8 @@ int main(int argc,char **argv) { CHECK(app_file,"read compiler-produced B64E application"); CHECK(!bob64_exec_parse(app_file,app_size,&app)&& app.AbiVersion==BOB64_APP_ABI_VERSION&&app.EntryOffset>0&& - app.CodeSize==BOB64_PAGE_SIZE&&app.FileSize>app.CodeSize&& + app.CodeSize>=BOB64_PAGE_SIZE&&app.CodeSize%BOB64_PAGE_SIZE==0&& + app.FileSize>app.CodeSize&& app.MemorySize>=app.FileSize&&app.MemorySize<=BOB64_PROCESS_IMAGE_LIMIT, "parse compiler-produced B64E metadata and bounded memory layout"); CHECK(app.Image[app.EntryOffset]==0x48&&app.Image[app.EntryOffset+1]==0x83&& @@ -3519,6 +4783,9 @@ int main(int argc,char **argv) { contains_bytes(app.Image,(usize)app.FileSize, "UP DOWN WHEEL ENTER RUN",23)&& contains_bytes(app.Image,(usize)app.FileSize,"WHEEL MOVE",10)&& + contains_bytes(app.Image,(usize)app.FileSize,"M:MENU",6)&& + contains_bytes(app.Image,(usize)app.FileSize,"OPEN SELECTED",13)&& + contains_bytes(app.Image,(usize)app.FileSize,"DELETE FILE",11)&& contains_bytes(app.Image,(usize)app.FileSize,"APPS",4)&& contains_bytes(app.Image,(usize)app.FileSize,"X CLOSE",7)&& contains_bytes(app.Image,(usize)app.FileSize, @@ -3693,8 +4960,12 @@ int main(int argc,char **argv) { app.AbiVersion==BOB64_APP_ABI_VERSION&&app.EntryOffset>0&& app.MemorySize>=app.FileSize&&app.CodeSize>0&& contains_bytes(app.Image,(usize)app.FileSize, - "bob64 live mouse event passed",29), - "package the live mouse IRQ test as a valid B64E app"); + "bob! live mouse move passed", + sizeof("bob! live mouse move passed")-1)&& + contains_bytes(app.Image,(usize)app.FileSize, + "bob! live mouse wheel passed", + sizeof("bob! live mouse wheel passed")-1), + "package the live mouse movement and wheel IRQ test as a valid B64E app"); free(app_file); } diff --git a/tools/build.c b/tools/build.c index 7efa9c3..6fb1ea8 100644 --- a/tools/build.c +++ b/tools/build.c @@ -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"); } diff --git a/tools/new_bob64_disk.ps1 b/tools/new_bob64_disk.ps1 new file mode 100644 index 0000000..fc6eade --- /dev/null +++ b/tools/new_bob64_disk.ps1 @@ -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.' diff --git a/tools/test_bob64_qemu.ps1 b/tools/test_bob64_qemu.ps1 index c7e9689..e5c4030 100644 --- a/tools/test_bob64_qemu.ps1 +++ b/tools/test_bob64_qemu.ps1 @@ -5,10 +5,20 @@ param( [string]$OvmfCodePath, [string]$OvmfVarsPath, [string]$ImageRoot = (Join-Path (Split-Path -Parent $PSScriptRoot) 'build\bob64-handoff'), - [int]$TimeoutSeconds = 45 + [int]$TimeoutSeconds = 45, + [switch]$ProbeOnly, + [switch]$DiskSnapshotTest, + [switch]$LargeLbaDiskSnapshotTest, + [switch]$ExpectStorageWrite, + [ValidateSet('keyboard','mouse','both','many','disconnect','hub','storage','storage-hotplug','storage-active-disconnect','storage64')] + [string]$ProbeDevice = 'keyboard' ) $ErrorActionPreference = 'Stop' +if ($DiskSnapshotTest -and $LargeLbaDiskSnapshotTest) { + throw 'Choose either -DiskSnapshotTest or -LargeLbaDiskSnapshotTest.' +} +if ($LargeLbaDiskSnapshotTest) { $DiskSnapshotTest = $true } $requiredMarkers = @( 'bob64: long mode active', 'bob64: exiting UEFI boot services', @@ -22,17 +32,30 @@ $requiredMarkers = @( 'bob64 kernel: large notes streaming copy passed', 'bob64 kernel: native notes app passed', 'bob64 kernel: native info app passed', + 'bob64 kernel: full-width user exception diagnostics passed', + 'r15=0x1234567887654321', + 'rsp=0x0000004002', + 'ss=0x000000000000001b', + 'cr2=0x0000004000000000', 'bob64 kernel: read-only code protection passed', 'bob64 kernel: non-executable data protection passed', 'bob64 kernel: memory checks passed', + 'bob64 kernel: xHCI PCI controller found at', + 'bob64 kernel: PCI enumeration passed', + 'bob64 kernel: xHCI capabilities mapped, version=', + 'bob64 kernel: xHCI controller halted and reset', + 'bob64 kernel: xHCI command ring completion passed', 'bob64 kernel: timer IRQ enabled', 'bob64 kernel: timer tick passed', + 'bob64 kernel: serial RX IRQ enabled', 'bob64 kernel: keyboard IRQ enabled', 'bob64 kernel: PS/2 mouse IRQ enabled', 'bob64! kernel shell; type help' ) $persistentMarker = 'bob64 kernel: persistent B64S smoke file passed' -$mouseMarker = 'bob64 live mouse event passed' +$mouseMarker = 'bob! live mouse move passed' +$mouseWheelMarker = 'bob! live mouse wheel passed' +$mouseButtonMarker = 'bob! live mouse button passed' $shellMarker = 'bob64! kernel shell; type help' $shellPromptMarker = 'bob64> ' @@ -82,15 +105,60 @@ if ([string]::IsNullOrWhiteSpace($OvmfVarsPath) -or } $varsTemplatePath = (Resolve-Path -LiteralPath $OvmfVarsPath).Path $serialPath = Join-Path ([IO.Path]::GetTempPath()) ("bob64-qemu-{0}.log" -f [guid]::NewGuid()) +$framebufferPath = Join-Path ([IO.Path]::GetTempPath()) ("bob64-framebuffer-{0}.ppm" -f [guid]::NewGuid()) $varsCopyPath = Join-Path ([IO.Path]::GetTempPath()) ("bob64-ovmf-vars-{0}.fd" -f [guid]::NewGuid()) +$storageImagePath = Join-Path ([IO.Path]::GetTempPath()) ("bob64-usb-storage-{0}.img" -f [guid]::NewGuid()) +$storageReconnectImagePath = Join-Path ([IO.Path]::GetTempPath()) ("bob64-usb-storage-reconnect-{0}.img" -f [guid]::NewGuid()) +$diskSnapshotImagePath = Join-Path ([IO.Path]::GetTempPath()) ("bob64-disk-snapshot-{0}.img" -f [guid]::NewGuid()) Copy-Item -LiteralPath $varsTemplatePath -Destination $varsCopyPath +if ($DiskSnapshotTest) { + if ($ProbeOnly) { throw '-DiskSnapshotTest requires the full shell regression run.' } + if ($LargeLbaDiskSnapshotTest) { + & (Join-Path $PSScriptRoot 'new_bob64_disk.ps1') ` + -Path $diskSnapshotImagePath -SizeMiB 2097154 ` + -FirstPartitionLba 4294969344 -Sparse | Out-Null + } else { + & (Join-Path $PSScriptRoot 'new_bob64_disk.ps1') ` + -Path $diskSnapshotImagePath -SizeMiB 64 | Out-Null + } +} +if ($ProbeOnly -and $ProbeDevice -eq 'storage64') { + [IO.File]::Open($storageImagePath,[IO.FileMode]::CreateNew).Dispose() + & fsutil.exe sparse setflag $storageImagePath | Out-Null + if ($LASTEXITCODE -ne 0) { + throw 'Could not mark the temporary large-LBA test image as sparse.' + } + $storageImage = [IO.File]::Open($storageImagePath,[IO.FileMode]::Open, + [IO.FileAccess]::ReadWrite,[IO.FileShare]::None) + try { + $highLba = [long]4294967296 + $storageImage.SetLength(($highLba + 8) * 512) + $storageImage.Position = $highLba * 512 + $highLbaPattern = [byte[]]::new(512) + for ($index=0; $index -lt $highLbaPattern.Length; $index++) { + $highLbaPattern[$index] = [byte](($index * 53 + 0xa7) -band 0xff) + } + $storageImage.Write($highLbaPattern,0,$highLbaPattern.Length) + $storageImage.Flush($true) + } + finally { $storageImage.Dispose() } +} elseif ($ProbeOnly -and $ProbeDevice -in @('storage','storage-hotplug','storage-active-disconnect')) { + $storageImage = [IO.File]::Open($storageImagePath,[IO.FileMode]::CreateNew) + try { $storageImage.SetLength(16MB) } + finally { $storageImage.Dispose() } + if ($ProbeDevice -eq 'storage-hotplug') { + $storageReconnectImage = [IO.File]::Open($storageReconnectImagePath,[IO.FileMode]::CreateNew) + try { $storageReconnectImage.SetLength(16MB) } + finally { $storageReconnectImage.Dispose() } + } +} $portProbe = [Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback, 0) $portProbe.Start() $monitorPort = ([Net.IPEndPoint]$portProbe.LocalEndpoint).Port $portProbe.Stop() -function Send-MonitorCommand([string]$command) { +function Send-MonitorCommand([string]$command,[switch]$Capture) { $client = [Net.Sockets.TcpClient]::new() try { $client.Connect('127.0.0.1', $monitorPort) @@ -112,13 +180,14 @@ function Send-MonitorCommand([string]$command) { if ($count -le 0) { break } [void]$response.Append([Text.Encoding]::ASCII.GetString($buffer, 0, $count)) } + if ($Capture) { return $response.ToString() } } finally { $client.Dispose() } } -function Send-GuestText([string]$text) { +function Send-GuestText([string]$text,[int]$delayMilliseconds=125) { $client = [Net.Sockets.TcpClient]::new() try { $client.Connect('127.0.0.1', $monitorPort) @@ -130,7 +199,7 @@ function Send-GuestText([string]$text) { $bytes = [Text.Encoding]::ASCII.GetBytes("sendkey $key`n") $stream.Write($bytes, 0, $bytes.Length) $stream.Flush() - Start-Sleep -Milliseconds 125 + Start-Sleep -Milliseconds $delayMilliseconds } $bytes = [Text.Encoding]::ASCII.GetBytes("sendkey ret`n") $stream.Write($bytes, 0, $bytes.Length) @@ -142,14 +211,122 @@ function Send-GuestText([string]$text) { } } +function Stop-QemuForStorageCheck { + if ($process -and -not $process.HasExited) { + $process.Kill() + $process.WaitForExit() + } +} + +function Assert-StorageTestPattern([string]$path) { + $stream = [IO.File]::OpenRead($path) + try { + if ($stream.Length -lt 1024) { + throw "QEMU storage test image is too short: $path" + } + [void]$stream.Seek(512,[IO.SeekOrigin]::Begin) + for ($index=0; $index -lt 512; $index++) { + $expected = ($index * 37 + 0x5a) -band 0xff + if ($stream.ReadByte() -ne $expected) { + throw "SYNCHRONIZE CACHE did not persist the expected bytes at LBA 1 in $path (byte $index)." + } + } + } + finally { + $stream.Dispose() + } +} + +function Assert-FramebufferRendered([string]$path) { + $qemuPath = $path.Replace('\', '/') + $response = Send-MonitorCommand "screendump $qemuPath" -Capture + if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { + throw "QEMU did not produce the framebuffer screenshot. Monitor response: $response" + } + $bytes = [IO.File]::ReadAllBytes($path) + $headerLength = [Math]::Min($bytes.Length, 128) + $headerText = [Text.Encoding]::ASCII.GetString($bytes, 0, $headerLength) + $header = [regex]::Match($headerText, '^P6\s+(\d+)\s+(\d+)\s+(\d+)\s') + if (-not $header.Success) { + throw 'QEMU framebuffer screenshot did not contain a valid binary PPM header.' + } + $width = [int]$header.Groups[1].Value + $height = [int]$header.Groups[2].Value + $maximum = [int]$header.Groups[3].Value + $dataOffset = $header.Length + if ($width -lt 320 -or $height -lt 200 -or $maximum -ne 255 -or + $bytes.Length - $dataOffset -ne $width * $height * 3) { + throw "QEMU framebuffer screenshot has invalid dimensions or pixel data ($width x $height, max $maximum)." + } + $colors = [Collections.Generic.HashSet[int]]::new() + $pixelCount = $width * $height + for ($pixel = 0; $pixel -lt $pixelCount; $pixel += 97) { + $offset = $dataOffset + $pixel * 3 + $color = ([int]$bytes[$offset] -shl 16) -bor + ([int]$bytes[$offset + 1] -shl 8) -bor + [int]$bytes[$offset + 2] + [void]$colors.Add($color) + } + if ($colors.Count -lt 8) { + throw "QEMU framebuffer is blank or nearly uniform ($($colors.Count) sampled colors)." + } + Write-Output " framebuffer: $width x $height, $($colors.Count) sampled colors" +} + +$machine = 'q35' +if ($ProbeOnly) { $machine = 'q35,i8042=off' } +$xhciDevice = 'qemu-xhci,id=usb-controller' +if ($ProbeOnly -and $ProbeDevice -eq 'many') { + $xhciDevice = 'qemu-xhci,id=usb-controller,p2=15,p3=15' +} $arguments = @( - '-machine', 'q35', '-m', '512M', '-cpu', 'max', '-L', $shareDirectory, + '-machine', $machine, '-m', '512M', '-cpu', 'max', '-L', $shareDirectory, + '-device', $xhciDevice, '-drive', "if=pflash,format=raw,unit=0,file=$firmwarePath,readonly=on", '-drive', "if=pflash,format=raw,unit=1,file=$varsCopyPath", '-drive', "format=raw,file=fat:rw:$imagePath", '-boot', 'order=c', '-display', 'none', '-serial', "file:$serialPath", '-monitor', "tcp:127.0.0.1:$monitorPort,server=on,wait=off" ) +if ($DiskSnapshotTest) { + $diskSnapshotQemuPath = $diskSnapshotImagePath.Replace('\','/') + $arguments += @('-drive', "if=none,id=bob64-snapshot-disk,format=raw,file=$diskSnapshotQemuPath", + '-device', 'usb-storage,id=bob64-snapshot-storage,bus=usb-controller.0,port=1,drive=bob64-snapshot-disk') +} +if ($ProbeOnly) { + if ($ProbeDevice -in @('storage','storage-hotplug','storage-active-disconnect','storage64')) { + $storageImageQemuPath = $storageImagePath.Replace('\','/') + if ($ProbeDevice -eq 'storage-active-disconnect') { + $arguments += @('-drive', "if=none,id=usbdrive,format=raw,file=$storageImageQemuPath,bps=128") + } else { + $arguments += @('-drive', "if=none,id=usbdrive,format=raw,file=$storageImageQemuPath") + } + if ($ProbeDevice -eq 'storage-hotplug') { + $storageReconnectImageQemuPath = $storageReconnectImagePath.Replace('\','/') + $arguments += @('-drive', "if=none,id=usbdrive-reconnect,format=raw,file=$storageReconnectImageQemuPath") + } + if ($ProbeDevice -ne 'storage-active-disconnect') { + $arguments += @('-device', 'usb-storage,id=probe-storage,bus=usb-controller.0,port=1,drive=usbdrive') + } + } elseif ($ProbeDevice -eq 'hub') { + $arguments += @( + '-device', 'usb-hub,id=probe-hub,bus=usb-controller.0,port=1', + '-device', 'usb-kbd,id=probe-hub-keyboard,bus=usb-controller.0,port=1.1', + '-device', 'usb-mouse,bus=usb-controller.0,port=1.2' + ) + } else { + $probeQemuDevices = if ($ProbeDevice -eq 'both') { + @('usb-kbd','usb-mouse') + } elseif ($ProbeDevice -eq 'many') { + @('usb-kbd') + (@('usb-mouse') * 8) + } elseif ($ProbeDevice -eq 'disconnect') { + @('usb-kbd,id=probe-keyboard') + } elseif ($ProbeDevice -eq 'mouse') { @('usb-mouse') } else { @('usb-kbd') } + foreach ($probeQemuDevice in $probeQemuDevices) { + $arguments += @('-device', "$probeQemuDevice,bus=usb-controller.0") + } + } +} $startInfo = [Diagnostics.ProcessStartInfo]::new() $startInfo.FileName = (Resolve-Path -LiteralPath $QemuPath).Path @@ -161,8 +338,476 @@ $startInfo.Arguments = (($arguments | ForEach-Object { $process = $null try { + $serialText = '' $process = [Diagnostics.Process]::Start($startInfo) - $deadline = [DateTime]::UtcNow.AddSeconds($TimeoutSeconds) + if ($ProbeOnly) { + $probeDeadline = [DateTime]::UtcNow.AddSeconds($TimeoutSeconds) + $inputMarker = if ($ProbeDevice -eq 'mouse') { + 'bob64 kernel: USB HID mouse input queued' + } else { 'bob64 kernel: USB HID keyboard input queued' } + $usbWheelMarker = 'bob64 kernel: USB HID mouse wheel input queued' + $keyboardConfiguredMarker = 'bob64 kernel: USB HID boot keyboard endpoint configured; waiting for input report' + $mouseConfiguredMarker = 'bob64 kernel: USB HID boot mouse endpoint configured; waiting for input report' + $storageConfiguredMarker = 'bob64 kernel: USB mass-storage bulk endpoints configured slot=' + $storageCapacityMarker = 'bob64 kernel: USB MSC READ CAPACITY passed blocks=0000000000008000 sector-bytes=0000000000000200' + $storageReadMarker = 'bob64 kernel: USB MSC sector-read passed lba=0 bytes=0000000000000200' + $storage64Marker = 'bob64 kernel: USB MSC high-LBA READ(16) passed lba=0000000100000000' + $storageWriteMarker = 'bob64 kernel: USB MSC sector-write/flush/readback passed lba=1 bytes=0000000000000200' + $storageDisconnectedMarker = 'bob64 kernel: USB mass-storage device disconnected' + $storageTransferArmedMarker = 'bob64 kernel: USB MSC READ(10) data transfer in flight' + $storageTransferAbortedMarker = 'bob64 kernel: USB MSC transfer aborted after disconnect' + $storageHotplugPhase = 0 + $storageActiveRemovalSent = $false + $storageActiveAttached = $false + $storageActiveAttachMarker = 'bob64: exiting UEFI boot services' + $hubScannedMarker = 'bob64 kernel: USB 2 hub configured ports=' + $hubScanVerified = $false + $hidConfiguredSeen = $false + $testInputSent = $false + $hidShellTested = $false + $shellReadyMarker = 'bob64! kernel shell; type help' + $keyboardShellMarker = 'bob64 kernel 0.1' + $failureMarker = 'bob64 kernel: xHCI capability probe failed, result=' + while ([DateTime]::UtcNow -lt $probeDeadline) { + if (Test-Path -LiteralPath $serialPath) { + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + if ($ProbeDevice -eq 'storage-active-disconnect' -and + -not $storageActiveAttached -and $serialText -and + $serialText.Contains($storageActiveAttachMarker)) { + $response=Send-MonitorCommand 'device_add usb-storage,id=probe-storage,bus=usb-controller.0,port=1,drive=usbdrive' -Capture + if ($response -match 'Error') { + throw "QEMU could not attach the throttled storage test device: $response" + } + $storageActiveAttached=$true + } + if ($ProbeDevice -eq 'storage-active-disconnect' -and + -not $storageActiveRemovalSent -and $serialText -and + $serialText.Contains($storageTransferArmedMarker)) { + $response=Send-MonitorCommand 'device_del probe-storage' -Capture + if ($response -match 'Error') { + throw "QEMU could not remove storage during the active transfer: $response" + } + $storageActiveRemovalSent=$true + } + if ($ProbeDevice -eq 'storage-active-disconnect' -and + $storageActiveRemovalSent -and $serialText -and + $serialText.Contains($storageTransferAbortedMarker) -and + $serialText.Contains($storageDisconnectedMarker)) { + Write-Output 'QEMU USB mass-storage removal during an outstanding xHCI transfer aborted the request and completed device teardown.' + return + } + $storageCapacityPassed = if ($ProbeDevice -eq 'storage64') { + $serialText -and $serialText.Contains($storage64Marker) + } else { $serialText -and $serialText.Contains($storageCapacityMarker) } + if ($ProbeDevice -in @('storage','storage-hotplug','storage64') -and $serialText -and + $serialText.Contains($storageConfiguredMarker) -and + $storageCapacityPassed -and + $serialText.Contains($storageReadMarker) -and + (-not $ExpectStorageWrite -or + $serialText.Contains($storageWriteMarker)) -and + $serialText.Contains($shellReadyMarker)) { + if ($ProbeDevice -eq 'storage') { + $storageStart = $serialText.IndexOf($storageConfiguredMarker) + Write-Output $serialText.Substring($storageStart, + [Math]::Min(500,$serialText.Length-$storageStart)) + Write-Output 'QEMU USB mass-storage INQUIRY, READ CAPACITY, and READ(10) passed over xHCI bulk endpoints.' + if ($ExpectStorageWrite) { + Stop-QemuForStorageCheck + Assert-StorageTestPattern $storageImagePath + Write-Output 'QEMU USB mass-storage WRITE(10), SYNCHRONIZE CACHE, readback, bounds check, and post-shutdown persistence passed.' + } + return + } + if ($ProbeDevice -eq 'storage64') { + $storageStart = $serialText.IndexOf($storageConfiguredMarker) + Write-Output $serialText.Substring($storageStart, + [Math]::Min(700,$serialText.Length-$storageStart)) + Write-Output 'QEMU USB mass storage passed READ CAPACITY(16) and read verified data above the 32-bit LBA boundary with READ(16).' + return + } + if ($storageHotplugPhase -eq 0) { + $response=Send-MonitorCommand 'device_del probe-storage' -Capture + if ($response -match 'Error') { + throw "QEMU could not remove the temporary USB storage device: $response" + } + $storageHotplugPhase=1 + } elseif ($storageHotplugPhase -eq 1 -and + $serialText.Contains($storageDisconnectedMarker)) { + $response=Send-MonitorCommand 'device_add usb-storage,id=probe-storage-reconnected,bus=usb-controller.0,port=1,drive=usbdrive-reconnect' -Capture + if ($response -match 'Error') { + throw "QEMU could not re-add the temporary USB storage device: $response" + } + $storageHotplugPhase=2 + } elseif ($storageHotplugPhase -eq 2 -and + [regex]::Matches($serialText, + [regex]::Escape($storageReadMarker)).Count -ge 2 -and + (-not $ExpectStorageWrite -or + [regex]::Matches($serialText, + [regex]::Escape($storageWriteMarker)).Count -ge 2)) { + Write-Output 'QEMU USB mass-storage INQUIRY, READ CAPACITY, and READ(10) passed before and after hotplug.' + if ($ExpectStorageWrite) { + Stop-QemuForStorageCheck + Assert-StorageTestPattern $storageImagePath + Assert-StorageTestPattern $storageReconnectImagePath + Write-Output 'QEMU USB mass-storage WRITE(10), SYNCHRONIZE CACHE, readback, and post-shutdown persistence passed before and after hotplug.' + } + return + } + if ($ProbeDevice -eq 'storage-hotplug') { continue } + } + if ($serialText -and $serialText.Contains($failureMarker)) { + Write-Output (Send-MonitorCommand 'info pci' -Capture) + Write-Output (Send-MonitorCommand 'xp /8wx 0xc000000000' -Capture) + throw "The xHCI MMIO capability probe failed.`n$serialText" + } + if ($ProbeDevice -eq 'hub' -and -not $hubScanVerified -and $serialText -and + $serialText.Contains($hubScannedMarker)) { + $hubScanLine = ($serialText -split "`r?`n" | + Where-Object { $_.Contains($hubScannedMarker) } | + Select-Object -Last 1) + if ($hubScanLine -notmatch 'configured ports=([0-9a-f]+) connected=([0-9a-f]+) reset=([0-9a-f]+)') { + throw "The USB hub scan marker was malformed.`n$hubScanLine" + } + $hubPortCount = [Convert]::ToInt32($Matches[1],16) + $hubConnectedCount = [Convert]::ToInt32($Matches[2],16) + $hubResetCount = [Convert]::ToInt32($Matches[3],16) + if ($hubPortCount -ne 8 -or $hubConnectedCount -lt 2 -or + $hubResetCount -lt 2) { + throw "The USB hub did not report both attached downstream devices.`n$hubScanLine" + } + Write-Output "QEMU USB 2 hub configured $hubPortCount ports, detected $hubConnectedCount children and reset $hubResetCount ports." + $hubScanVerified = $true + } + $allConfigured = $serialText -and + (($ProbeDevice -eq 'keyboard' -and $serialText.Contains($keyboardConfiguredMarker)) -or + ($ProbeDevice -eq 'mouse' -and $serialText.Contains($mouseConfiguredMarker)) -or + ($ProbeDevice -eq 'disconnect' -and $serialText.Contains($keyboardConfiguredMarker)) -or + ($ProbeDevice -eq 'both' -and $serialText.Contains($keyboardConfiguredMarker) -and + $serialText.Contains($mouseConfiguredMarker)) -or + ($ProbeDevice -eq 'many' -and + [regex]::Matches($serialText,[regex]::Escape($keyboardConfiguredMarker)).Count -ge 1 -and + [regex]::Matches($serialText,[regex]::Escape($mouseConfiguredMarker)).Count -ge 8) -or + ($ProbeDevice -eq 'hub' -and $hubScanVerified -and + $serialText.Contains($keyboardConfiguredMarker) -and + $serialText.Contains($mouseConfiguredMarker))) + if ($allConfigured -and + -not $hidConfiguredSeen) { + Write-Output ($serialText.Substring( + $serialText.IndexOf('bob64 kernel: xHCI PCI controller found at'), + [Math]::Min(1600,$serialText.Length- + $serialText.IndexOf('bob64 kernel: xHCI PCI controller found at')))) + $hidConfiguredSeen = $true + } + if (-not $testInputSent -and $serialText -and + $serialText.Contains($shellReadyMarker)) { + if ($ProbeDevice -eq 'mouse') { + Send-MonitorCommand 'mouse_move 16 0' + } else { + Send-GuestText 'version' + } + $testInputSent = $true + } + if ($testInputSent -and -not $hidShellTested) { + $shellInputDeadline = [DateTime]::UtcNow.AddSeconds(8) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + } while ([DateTime]::UtcNow -lt $shellInputDeadline -and + (-not $serialText.Contains($inputMarker) -or + ($ProbeDevice -ne 'mouse' -and + -not $serialText.Contains($keyboardShellMarker)))) + if (-not $serialText.Contains($inputMarker) -or + ($ProbeDevice -ne 'mouse' -and + -not $serialText.Contains($keyboardShellMarker))) { + throw "USB $ProbeDevice input did not reach the Bob input path.`n$serialText" + } + Write-Output "USB HID $ProbeDevice input reached Bob64 with i8042 disabled." + if ($ProbeDevice -eq 'hub') { + $hubChangeMarker = 'bob64 kernel: USB hub downstream change report received slot=' + $hubAddResponse = Send-MonitorCommand 'device_add usb-kbd,id=hub-hotplug,bus=usb-controller.0,port=1.3' -Capture + if ($hubAddResponse -match '(?i)error|failed|not found') { + $hubTree = Send-MonitorCommand 'info qtree' -Capture + $hubBuses = ($hubTree -split "`r?`n" | + Where-Object { $_ -match '(?i)usb|hub' }) -join "`n" + throw "QEMU could not add the USB hub child: $hubAddResponse`n$hubBuses" + } + $hubChangeDeadline = [DateTime]::UtcNow.AddSeconds(8) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + } while ([DateTime]::UtcNow -lt $hubChangeDeadline -and + -not $serialText.Contains($hubChangeMarker)) + if (-not $serialText.Contains($hubChangeMarker)) { + throw "The USB hub did not report the downstream hotplug change.`n$serialText" + } + $hubEnumerationMarker = 'bob64 kernel: USB hub hotplug device enumerated port=0000000000000003' + $hubEnumerationDeadline = [DateTime]::UtcNow.AddSeconds(8) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + } while ([DateTime]::UtcNow -lt $hubEnumerationDeadline -and + -not $serialText.Contains($hubEnumerationMarker)) + if (-not $serialText.Contains($hubEnumerationMarker)) { + throw "The hub reported hotplug but bob64 did not enumerate the downstream device.`n$serialText" + } + Write-Output 'USB hub hotplug status was read and the downstream keyboard was enumerated.' + Send-MonitorCommand 'device_del probe-hub-keyboard' + $hubReleaseMarker = 'bob64 kernel: USB HID transfer stopped; held input released' + $hubInitialReleaseDeadline = [DateTime]::UtcNow.AddSeconds(8) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + } while ([DateTime]::UtcNow -lt $hubInitialReleaseDeadline -and + -not $serialText.Contains($hubReleaseMarker)) + if (-not $serialText.Contains($hubReleaseMarker)) { + throw "Removing the original hub keyboard did not disconnect its HID child.`n$serialText" + } + $versionMarkerCount = [regex]::Matches($serialText, + [regex]::Escape($keyboardShellMarker)).Count + Send-GuestText 'version' + $hotplugInputDeadline = [DateTime]::UtcNow.AddSeconds(8) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + $newVersionMarkerCount = [regex]::Matches($serialText, + [regex]::Escape($keyboardShellMarker)).Count + } while ([DateTime]::UtcNow -lt $hotplugInputDeadline -and + $newVersionMarkerCount -le $versionMarkerCount) + if ($newVersionMarkerCount -le $versionMarkerCount) { + throw "The newly enumerated hub keyboard could not type into the shell.`n$serialText" + } + Write-Output 'USB hub hotplug keyboard input worked after removing the original keyboard.' + Send-MonitorCommand 'sendkey a 1000' + $heldKeyDeadline = [DateTime]::UtcNow.AddSeconds(5) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + } while ([DateTime]::UtcNow -lt $heldKeyDeadline -and + -not $serialText.Contains('bob64> a')) + if (-not $serialText.Contains('bob64> a')) { + throw "The hub-connected keyboard did not report the held key before removal.`n$serialText" + } + Send-MonitorCommand 'device_del hub-hotplug' + $hubHotplugReleaseDeadline = [DateTime]::UtcNow.AddSeconds(8) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + } while ([DateTime]::UtcNow -lt $hubHotplugReleaseDeadline -and + -not $serialText.Contains($hubReleaseMarker)) + if (-not $serialText.Contains($hubReleaseMarker)) { + throw "Removing the hub-connected keyboard did not release its held input.`n$serialText" + } + Write-Output 'USB hub child removal released the held keyboard input.' + $hubReconnectMarker = 'bob64 kernel: USB hub hotplug device enumerated port=0000000000000001' + Send-MonitorCommand 'device_add usb-kbd,id=probe-hub-keyboard,bus=usb-controller.0,port=1.1' + $hubReconnectDeadline = [DateTime]::UtcNow.AddSeconds(12) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + } while ([DateTime]::UtcNow -lt $hubReconnectDeadline -and + -not $serialText.Contains($hubReconnectMarker)) + if (-not $serialText.Contains($hubReconnectMarker)) { + throw "The hub keyboard did not re-enumerate after reconnect.`n$serialText" + } + $promptCountBeforeLineCleanup = [regex]::Matches($serialText, + [regex]::Escape($shellPromptMarker)).Count + Send-MonitorCommand 'sendkey backspace' + Send-MonitorCommand 'sendkey ret' + $cleanupDeadline = [DateTime]::UtcNow.AddSeconds(5) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + $promptCountAfterLineCleanup = [regex]::Matches($serialText, + [regex]::Escape($shellPromptMarker)).Count + } while ([DateTime]::UtcNow -lt $cleanupDeadline -and + $promptCountAfterLineCleanup -le $promptCountBeforeLineCleanup) + if ($promptCountAfterLineCleanup -le $promptCountBeforeLineCleanup) { + throw "The shell input line did not recover after hub keyboard reconnection.`n$serialText" + } + Write-Output 'USB hub keyboard reconnected and the shell input line recovered.' + } + if ($ProbeDevice -eq 'disconnect') { + Send-MonitorCommand 'sendkey a 1000' + $heldKeyDeadline = [DateTime]::UtcNow.AddSeconds(3) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + } while ([DateTime]::UtcNow -lt $heldKeyDeadline -and + -not $serialText.Contains('bob64> a')) + if (-not $serialText.Contains('bob64> a')) { + throw "USB keyboard did not report the held key before disconnect.`n$serialText" + } + Send-MonitorCommand 'device_del probe-keyboard' + $releaseMarker = 'bob64 kernel: USB HID transfer stopped; held input released' + $releaseDeadline = [DateTime]::UtcNow.AddSeconds(8) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + } while ([DateTime]::UtcNow -lt $releaseDeadline -and + -not $serialText.Contains($releaseMarker)) + if (-not $serialText.Contains($releaseMarker)) { + throw "Disconnecting the USB keyboard did not release its held input state.`n$serialText" + } + Write-Output 'USB keyboard hot-unplug released its held key state.' + $reconnectedMarker = 'bob64 kernel: USB HID device reconnected on root port ' + Send-MonitorCommand 'device_add usb-kbd,id=probe-keyboard,bus=usb-controller.0' + $reconnectDeadline = [DateTime]::UtcNow.AddSeconds(12) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + } while ([DateTime]::UtcNow -lt $reconnectDeadline -and + -not $serialText.Contains($reconnectedMarker)) + if (-not $serialText.Contains($reconnectedMarker)) { + throw "USB keyboard did not reconnect and enumerate after device_add.`n$serialText" + } + Send-MonitorCommand 'sendkey b' + Start-Sleep -Milliseconds 150 + Send-MonitorCommand 'sendkey ret' + $inputDeadline = [DateTime]::UtcNow.AddSeconds(8) + $reportMarker = 'bob64 kernel: USB HID transfer report received' + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + } while ([DateTime]::UtcNow -lt $inputDeadline -and + [regex]::Matches($serialText,[regex]::Escape($reportMarker)).Count -lt 2) + if ([regex]::Matches($serialText, + [regex]::Escape($reportMarker)).Count -lt 2) { + throw "USB keyboard re-enumerated but its interrupt endpoint did not return a report.`n$serialText" + } + Write-Output 'USB keyboard hot-replug re-enumerated and returned an interrupt report.' + return + } + if ($ProbeDevice -eq 'both' -or $ProbeDevice -eq 'many' -or + $ProbeDevice -eq 'hub') { + Send-MonitorCommand 'mouse_move 16 0' + $mouseInputMarker = 'bob64 kernel: USB HID mouse input queued' + $mouseInputDeadline = [DateTime]::UtcNow.AddSeconds(8) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + } while ([DateTime]::UtcNow -lt $mouseInputDeadline -and + -not $serialText.Contains($mouseInputMarker)) + if (-not $serialText.Contains($mouseInputMarker)) { + throw "The USB mouse did not deliver pointer input beside the USB keyboard.`n$serialText" + } + $shellMarker = 'bob64> ' + $shellCountBeforeMouseApp = [regex]::Matches($serialText, + [regex]::Escape($shellMarker)).Count + Send-GuestText 'run mousesmoke.b64e' + $mouseAppStartDeadline = [DateTime]::UtcNow.AddSeconds(8) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + } while ([DateTime]::UtcNow -lt $mouseAppStartDeadline -and + -not $serialText.Contains($mouseMarker)) + if (-not $serialText.Contains($mouseMarker)) { + throw "USB mouse movement was not routed into the managed window.`n$serialText" + } + Send-MonitorCommand 'mouse_move 0 0 -1' + $mouseAppWheelDeadline = [DateTime]::UtcNow.AddSeconds(8) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + } while ([DateTime]::UtcNow -lt $mouseAppWheelDeadline -and + -not $serialText.Contains($mouseWheelMarker)) + if (-not $serialText.Contains($mouseWheelMarker)) { + throw "USB mouse wheel was not routed into the managed window.`n$serialText" + } + Send-MonitorCommand 'mouse_move 0 10' + Start-Sleep -Milliseconds 100 + Send-MonitorCommand 'mouse_button 1' + Start-Sleep -Milliseconds 100 + Send-MonitorCommand 'mouse_button 0' + $mouseAppButtonDeadline = [DateTime]::UtcNow.AddSeconds(8) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + } while ([DateTime]::UtcNow -lt $mouseAppButtonDeadline -and + -not $serialText.Contains($mouseButtonMarker)) + if (-not $serialText.Contains($mouseButtonMarker)) { + throw "USB mouse button input was not routed into the managed window.`n$serialText" + } + $mouseExitDeadline = [DateTime]::UtcNow.AddSeconds(8) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + } while ([DateTime]::UtcNow -lt $mouseExitDeadline -and + [regex]::Matches($serialText, + [regex]::Escape($shellMarker)).Count -le $shellCountBeforeMouseApp) + if ([regex]::Matches($serialText, + [regex]::Escape($shellMarker)).Count -le $shellCountBeforeMouseApp) { + throw "The managed mouse smoke app did not return to the shell.`n$serialText" + } + $bobCountBeforeDesktop = [regex]::Matches($serialText, + [regex]::Escape('bob!')).Count + $shellCountBeforeDesktop = [regex]::Matches($serialText, + [regex]::Escape($shellMarker)).Count + Send-GuestText 'run desktop.b64e' + $desktopStartDeadline = [DateTime]::UtcNow.AddSeconds(8) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + } while ([DateTime]::UtcNow -lt $desktopStartDeadline -and + [regex]::Matches($serialText,[regex]::Escape('bob!')).Count -le + $bobCountBeforeDesktop) + if ([regex]::Matches($serialText, + [regex]::Escape('bob!')).Count -le $bobCountBeforeDesktop) { + throw "The USB keyboard could not launch the Bob desktop.`n$serialText" + } + Start-Sleep -Milliseconds 500 + Send-MonitorCommand 'sendkey tab' + Start-Sleep -Milliseconds 120 + Send-MonitorCommand 'sendkey h' + Start-Sleep -Milliseconds 120 + Send-MonitorCommand 'sendkey esc' + Start-Sleep -Milliseconds 120 + Send-MonitorCommand 'sendkey esc' + $desktopExitDeadline = [DateTime]::UtcNow.AddSeconds(8) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + } while ([DateTime]::UtcNow -lt $desktopExitDeadline -and + [regex]::Matches($serialText, + [regex]::Escape($shellMarker)).Count -le $shellCountBeforeDesktop) + if ([regex]::Matches($serialText, + [regex]::Escape($shellMarker)).Count -le $shellCountBeforeDesktop) { + throw "The USB keyboard could not close desktop Help and return to the shell.`n$serialText" + } + Write-Output 'USB keyboard launched the shell app; USB mouse move and wheel reached its managed window.' + Write-Output 'USB keyboard launched the desktop, opened and closed Help, and returned to the shell.' + } + if ($ProbeDevice -eq 'mouse') { + Send-MonitorCommand 'mouse_move 0 0 -1' + $wheelDeadline = [DateTime]::UtcNow.AddSeconds(8) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + } while ([DateTime]::UtcNow -lt $wheelDeadline -and + -not $serialText.Contains($usbWheelMarker)) + if (-not $serialText.Contains($usbWheelMarker)) { + throw "USB mouse wheel input did not reach Bob64.`n$serialText" + } + Write-Output 'USB HID mouse wheel input reached Bob64 with i8042 disabled.' + } + if (-not $hidConfiguredSeen) { + throw "USB $ProbeDevice input worked, but the expected HID devices were not all configured.`n$serialText" + } + $hidShellTested = $true + if ($ProbeDevice -eq 'many') { + Write-Output 'Nine directly connected USB HID devices configured with independent xHCI slots and rings.' + } + return + } + } + if ($process.HasExited) { + throw "QEMU exited before the USB $ProbeDevice probe completed.`n$serialText" + } + Start-Sleep -Milliseconds 100 + } + throw "Timed out waiting for the USB $ProbeDevice probe.`n$serialText" + } + $overallTimeout = [Math]::Max($TimeoutSeconds,180) + $deadline = [DateTime]::UtcNow.AddSeconds($overallTimeout) $serialText = '' $mouseSmokeStarted = $false $graphicsSmokeStarted = $false @@ -185,6 +830,10 @@ try { } } if ($allPresent -and -not $mouseSmokeStarted) { + $shellMarkerCountBeforeMouse = [regex]::Matches($serialText, + [regex]::Escape($shellPromptMarker)).Count + $exitMarkerCountBeforeMouse = [regex]::Matches($serialText, + [regex]::Escape('application exit status=0x0000000000000000')).Count Send-MonitorCommand 'mouse_move 32 0' Send-GuestText 'run mousesmoke.b64e' $mouseDeadline = [DateTime]::UtcNow.AddSeconds(10) @@ -196,6 +845,46 @@ try { if (-not $serialText.Contains($mouseMarker)) { throw "The live mouse IRQ smoke app did not receive a mouse-move event.`n$serialText" } + Send-MonitorCommand 'mouse_move 0 0 -1' + $mouseWheelDeadline = [DateTime]::UtcNow.AddSeconds(10) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + } while ([DateTime]::UtcNow -lt $mouseWheelDeadline -and + -not $serialText.Contains($mouseWheelMarker)) + if (-not $serialText.Contains($mouseWheelMarker)) { + throw "The live mouse IRQ smoke app did not receive a wheel event.`n$serialText" + } + Send-MonitorCommand 'mouse_move 0 10' + Start-Sleep -Milliseconds 100 + Send-MonitorCommand 'mouse_button 1' + Start-Sleep -Milliseconds 100 + Send-MonitorCommand 'mouse_button 0' + $mouseButtonDeadline = [DateTime]::UtcNow.AddSeconds(10) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + } while ([DateTime]::UtcNow -lt $mouseButtonDeadline -and + -not $serialText.Contains($mouseButtonMarker)) + if (-not $serialText.Contains($mouseButtonMarker)) { + throw "The live mouse app did not activate its managed-window button.`n$serialText" + } + Send-MonitorCommand 'mouse_move 0 -10' + $mouseExitDeadline = [DateTime]::UtcNow.AddSeconds(10) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + $shellMarkerCount = [regex]::Matches($serialText, + [regex]::Escape($shellPromptMarker)).Count + $exitMarkerCount = [regex]::Matches($serialText, + [regex]::Escape('application exit status=0x0000000000000000')).Count + } while ([DateTime]::UtcNow -lt $mouseExitDeadline -and + ($shellMarkerCount -le $shellMarkerCountBeforeMouse -or + $exitMarkerCount -le $exitMarkerCountBeforeMouse)) + if ($shellMarkerCount -le $shellMarkerCountBeforeMouse -or + $exitMarkerCount -le $exitMarkerCountBeforeMouse) { + throw "The mouse window app did not exit cleanly to the shell.`n$serialText" + } $mouseSmokeStarted = $true } if ($allPresent -and $mouseSmokeStarted -and -not $graphicsSmokeStarted) { @@ -217,7 +906,28 @@ try { if ($bobMarkerCount -le $bobMarkerCountBeforeGraphics) { throw "The native graphics demo did not present its surface and print bob!.`n$serialText" } - Send-MonitorCommand 'sendkey x' + # mousesmoke leaves the pointer at (672, 400). Drag the + # centered window by (80, 40) using a title-bar point away + # from the app's Close button, then click Close at its moved + # screen position (988, 259). + Send-MonitorCommand 'mouse_move -16 -95' + Start-Sleep -Milliseconds 80 + Send-MonitorCommand 'mouse_move -16 -95' + Start-Sleep -Milliseconds 80 + Send-MonitorCommand 'mouse_button 1' + Start-Sleep -Milliseconds 100 + Send-MonitorCommand 'mouse_move 80 40' + Start-Sleep -Milliseconds 100 + Send-MonitorCommand 'mouse_button 0' + Send-MonitorCommand 'mouse_move 90 3' + Start-Sleep -Milliseconds 80 + Send-MonitorCommand 'mouse_move 90 3' + Start-Sleep -Milliseconds 80 + Send-MonitorCommand 'mouse_move 88 3' + Start-Sleep -Milliseconds 100 + Send-MonitorCommand 'mouse_button 1' + Start-Sleep -Milliseconds 100 + Send-MonitorCommand 'mouse_button 0' $graphicsExitDeadline = [DateTime]::UtcNow.AddSeconds(10) do { Start-Sleep -Milliseconds 100 @@ -231,8 +941,14 @@ try { $exitMarkerCount -le $exitMarkerCountBeforeGraphics)) if ($shellMarkerCount -le $shellMarkerCountBeforeGraphics -or $exitMarkerCount -le $exitMarkerCountBeforeGraphics) { - throw "The native graphics demo did not return cleanly to the shell on X.`n$serialText" + throw "The dragged native graphics window did not close back to the shell.`n$serialText" } + # Return the pointer to (672, 400) for later mouse tests. + Send-MonitorCommand 'mouse_move -106 47' + Start-Sleep -Milliseconds 80 + Send-MonitorCommand 'mouse_move -105 47' + Start-Sleep -Milliseconds 80 + Send-MonitorCommand 'mouse_move -105 47' $graphicsSmokeStarted = $true } if ($allPresent -and $graphicsSmokeStarted -and @@ -270,13 +986,29 @@ try { if ($bobMarkerCount -le $bobMarkerCountBeforeNativeLauncher+1) { throw "The native windowed launcher did not run its selected bob! app.`n$serialText" } - # The first installed app is the interactive graphics demo; - # Escape closes that child, then a second Escape closes the - # launcher after its parent context resumes. + # Escape closes the child and returns to the launcher. A + # press on Close released outside must cancel; a full click + # inside the button must then close the launcher. Start-Sleep -Milliseconds 300 Send-MonitorCommand 'sendkey esc' Start-Sleep -Milliseconds 300 - Send-MonitorCommand 'sendkey esc' + Send-MonitorCommand 'mouse_move -42 -47' + Send-MonitorCommand 'mouse_move -42 -47' + Send-MonitorCommand 'mouse_button 1' + Send-MonitorCommand 'mouse_move 65 50' + Send-MonitorCommand 'mouse_button 0' + Start-Sleep -Milliseconds 300 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + $shellMarkerCount = [regex]::Matches($serialText, + [regex]::Escape($shellPromptMarker)).Count + if ($shellMarkerCount -gt $shellMarkerCountBeforeNativeLauncher) { + throw "The launcher closed after a press was released outside its Close button.`n$serialText" + } + Send-MonitorCommand 'mouse_move -65 -50' + Send-MonitorCommand 'mouse_button 1' + Send-MonitorCommand 'mouse_button 0' + Send-MonitorCommand 'mouse_move 42 47' + Send-MonitorCommand 'mouse_move 42 47' $nativeLauncherExitDeadline = [DateTime]::UtcNow.AddSeconds(10) do { Start-Sleep -Milliseconds 100 @@ -290,7 +1022,7 @@ try { $exitMarkerCount -le $exitMarkerCountBeforeNativeLauncher)) if ($shellMarkerCount -le $shellMarkerCountBeforeNativeLauncher -or $exitMarkerCount -le $exitMarkerCountBeforeNativeLauncher) { - throw "The native windowed launcher did not close cleanly on Escape.`n$serialText" + throw "The native windowed launcher did not close after a complete mouse click inside Close.`n$serialText" } $bobMarkerCountBeforeForwardedArgs = $bobMarkerCount $shellMarkerCountBeforeForwardedArgs = $shellMarkerCount @@ -319,6 +1051,195 @@ try { $exitMarkerCount -le $exitMarkerCountBeforeForwardedArgs) { throw "The launcher did not forward argv to echo.b64e and return to the shell.`n$serialText" } + $bobMarkerCountBeforeGuiLs = $bobMarkerCount + $shellMarkerCountBeforeGuiLs = $shellMarkerCount + $exitMarkerCountBeforeGuiLs = $exitMarkerCount + Send-GuestText 'run ls.b64e gui bob.c' + $guiLsDeadline = [DateTime]::UtcNow.AddSeconds(10) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + $bobMarkerCount = [regex]::Matches($serialText, + [regex]::Escape('bob!')).Count + } while ([DateTime]::UtcNow -lt $guiLsDeadline -and + $bobMarkerCount -le $bobMarkerCountBeforeGuiLs) + if ($bobMarkerCount -le $bobMarkerCountBeforeGuiLs) { + throw "ls.b64e gui did not open its windowed file list.`n$serialText" + } + $bobMarkerCountBeforeGuiLsOpen = $bobMarkerCount + Start-Sleep -Milliseconds 300 + # bob.c is preselected at row 9 in the current RAM listing. + # On the 1280x800 display, the centered Files window puts that + # row near (440, 442). + # The pointer starts at (672, 400); double-click the row. + Send-MonitorCommand 'mouse_move -77 14' + Send-MonitorCommand 'mouse_move -77 14' + Send-MonitorCommand 'mouse_move -78 14' + Send-MonitorCommand 'mouse_button 1' + Start-Sleep -Milliseconds 100 + Send-MonitorCommand 'mouse_button 0' + Start-Sleep -Milliseconds 100 + Send-MonitorCommand 'mouse_button 1' + Start-Sleep -Milliseconds 100 + Send-MonitorCommand 'mouse_button 0' + $guiLsOpenDeadline = [DateTime]::UtcNow.AddSeconds(10) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + $bobMarkerCount = [regex]::Matches($serialText, + [regex]::Escape('bob!')).Count + } while ([DateTime]::UtcNow -lt $guiLsOpenDeadline -and + $bobMarkerCount -le $bobMarkerCountBeforeGuiLsOpen) + if ($bobMarkerCount -le $bobMarkerCountBeforeGuiLsOpen) { + throw "A double-click in ls.b64e gui did not open bob.c in cat's windowed viewer.`n$serialText" + } + Start-Sleep -Milliseconds 300 + Send-MonitorCommand 'sendkey esc' + Start-Sleep -Milliseconds 300 + Send-MonitorCommand 'sendkey esc' + # Restore the pointer position expected by subsequent tests. + Send-MonitorCommand 'mouse_move 77 -14' + Send-MonitorCommand 'mouse_move 77 -14' + Send-MonitorCommand 'mouse_move 78 -14' + $guiLsExitDeadline = [DateTime]::UtcNow.AddSeconds(10) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + $shellMarkerCount = [regex]::Matches($serialText, + [regex]::Escape($shellPromptMarker)).Count + $exitMarkerCount = [regex]::Matches($serialText, + [regex]::Escape('application exit status=0x0000000000000000')).Count + } while ([DateTime]::UtcNow -lt $guiLsExitDeadline -and + ($shellMarkerCount -le $shellMarkerCountBeforeGuiLs -or + $exitMarkerCount -le $exitMarkerCountBeforeGuiLs)) + if ($shellMarkerCount -le $shellMarkerCountBeforeGuiLs -or + $exitMarkerCount -le $exitMarkerCountBeforeGuiLs) { + throw "The windowed ls app did not close back to the shell on Escape.`n$serialText" + } + $bobMarkerCountBeforeGuiCat = [regex]::Matches($serialText, + [regex]::Escape('bob!')).Count + $shellMarkerCountBeforeGuiCat = $shellMarkerCount + $exitMarkerCountBeforeGuiCat = $exitMarkerCount + Send-GuestText 'run cat.b64e gui bob.c' + $guiCatDeadline = [DateTime]::UtcNow.AddSeconds(10) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + $bobMarkerCount = [regex]::Matches($serialText, + [regex]::Escape('bob!')).Count + } while ([DateTime]::UtcNow -lt $guiCatDeadline -and + $bobMarkerCount -le $bobMarkerCountBeforeGuiCat) + if ($bobMarkerCount -le $bobMarkerCountBeforeGuiCat) { + throw "cat.b64e gui did not open the requested text file in a window.`n$serialText" + } + Start-Sleep -Milliseconds 300 + Send-MonitorCommand 'sendkey down' + Send-MonitorCommand 'sendkey pgdn' + Send-MonitorCommand 'sendkey esc' + $guiCatExitDeadline = [DateTime]::UtcNow.AddSeconds(10) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + $shellMarkerCount = [regex]::Matches($serialText, + [regex]::Escape($shellPromptMarker)).Count + $exitMarkerCount = [regex]::Matches($serialText, + [regex]::Escape('application exit status=0x0000000000000000')).Count + } while ([DateTime]::UtcNow -lt $guiCatExitDeadline -and + ($shellMarkerCount -le $shellMarkerCountBeforeGuiCat -or + $exitMarkerCount -le $exitMarkerCountBeforeGuiCat)) + if ($shellMarkerCount -le $shellMarkerCountBeforeGuiCat -or + $exitMarkerCount -le $exitMarkerCountBeforeGuiCat) { + throw "The text viewer did not return to the shell on Escape.`n$serialText" + } + $bobMarkerCountBeforeGuiInfo = [regex]::Matches($serialText, + [regex]::Escape('bob!')).Count + $shellMarkerCountBeforeGuiInfo = $shellMarkerCount + $exitMarkerCountBeforeGuiInfo = $exitMarkerCount + Send-GuestText 'run info.b64e gui' + $guiInfoDeadline = [DateTime]::UtcNow.AddSeconds(10) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + $bobMarkerCount = [regex]::Matches($serialText, + [regex]::Escape('bob!')).Count + } while ([DateTime]::UtcNow -lt $guiInfoDeadline -and + $bobMarkerCount -le $bobMarkerCountBeforeGuiInfo) + if ($bobMarkerCount -le $bobMarkerCountBeforeGuiInfo) { + throw "info.b64e gui did not open its managed system-information window.`n$serialText" + } + Start-Sleep -Milliseconds 300 + Send-MonitorCommand 'sendkey r' + Send-MonitorCommand 'sendkey esc' + $guiInfoExitDeadline = [DateTime]::UtcNow.AddSeconds(10) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + $shellMarkerCount = [regex]::Matches($serialText, + [regex]::Escape($shellPromptMarker)).Count + $exitMarkerCount = [regex]::Matches($serialText, + [regex]::Escape('application exit status=0x0000000000000000')).Count + } while ([DateTime]::UtcNow -lt $guiInfoExitDeadline -and + ($shellMarkerCount -le $shellMarkerCountBeforeGuiInfo -or + $exitMarkerCount -le $exitMarkerCountBeforeGuiInfo)) + if ($shellMarkerCount -le $shellMarkerCountBeforeGuiInfo -or + $exitMarkerCount -le $exitMarkerCountBeforeGuiInfo) { + throw "The system-information window did not close back to the shell.`n$serialText" + } + $bobMarkerCountBeforeGuiEcho = [regex]::Matches($serialText, + [regex]::Escape('bob!')).Count + $shellMarkerCountBeforeGuiEcho = $shellMarkerCount + $exitMarkerCountBeforeGuiEcho = $exitMarkerCount + $echoGuiArguments = ('argument123 ' * 18).TrimEnd() + Send-GuestText "run echo.b64e gui $echoGuiArguments" + $guiEchoDeadline = [DateTime]::UtcNow.AddSeconds(10) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + $bobMarkerCount = [regex]::Matches($serialText, + [regex]::Escape('bob!')).Count + } while ([DateTime]::UtcNow -lt $guiEchoDeadline -and + $bobMarkerCount -le $bobMarkerCountBeforeGuiEcho) + if ($bobMarkerCount -le $bobMarkerCountBeforeGuiEcho) { + throw "echo.b64e gui did not create its managed argument window.`n$serialText" + } + Start-Sleep -Milliseconds 300 + Send-MonitorCommand 'sendkey down' + Start-Sleep -Milliseconds 100 + Send-MonitorCommand 'sendkey pgdn' + Start-Sleep -Milliseconds 100 + # The pointer is at (672, 400); click the echo window's Close + # control at (908, 213) after its wrapped text is presented. + Send-MonitorCommand 'mouse_move 79 -62' + Start-Sleep -Milliseconds 80 + Send-MonitorCommand 'mouse_move 79 -62' + Start-Sleep -Milliseconds 80 + Send-MonitorCommand 'mouse_move 78 -62' + Start-Sleep -Milliseconds 100 + Send-MonitorCommand 'mouse_button 1' + Start-Sleep -Milliseconds 100 + Send-MonitorCommand 'mouse_button 0' + # Restore the pointer expected by later runtime interactions. + Send-MonitorCommand 'mouse_move -79 62' + Start-Sleep -Milliseconds 80 + Send-MonitorCommand 'mouse_move -79 62' + Start-Sleep -Milliseconds 80 + Send-MonitorCommand 'mouse_move -78 62' + $guiEchoExitDeadline = [DateTime]::UtcNow.AddSeconds(10) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + $shellMarkerCount = [regex]::Matches($serialText, + [regex]::Escape($shellPromptMarker)).Count + $exitMarkerCount = [regex]::Matches($serialText, + [regex]::Escape('application exit status=0x0000000000000000')).Count + } while ([DateTime]::UtcNow -lt $guiEchoExitDeadline -and + ($shellMarkerCount -le $shellMarkerCountBeforeGuiEcho -or + $exitMarkerCount -le $exitMarkerCountBeforeGuiEcho)) + if ($shellMarkerCount -le $shellMarkerCountBeforeGuiEcho -or + $exitMarkerCount -le $exitMarkerCountBeforeGuiEcho) { + throw "The echo argument window did not handle its input and return to the shell.`n$serialText" + } + Write-Output ' echo GUI: wrapped managed argv text, handled scroll keys, and closed through the mouse button' $nativeLauncherSmokeStarted = $true } if ($allPresent -and $graphicsSmokeStarted -and -not $compilerSmokeStarted) { @@ -371,23 +1292,79 @@ try { throw "The native desktop did not start for the launcher smoke test.`n$serialText" } Start-Sleep -Milliseconds 500 + Assert-FramebufferRendered $framebufferPath + # Tab focuses the Files window. Its first row is bob.b64e; + # Enter should run it and restore the still-open desktop. + $bobMarkerCountBeforeEnterRun = [regex]::Matches($serialText, + [regex]::Escape('bob!')).Count + Send-MonitorCommand 'sendkey tab' + Start-Sleep -Milliseconds 150 + Send-MonitorCommand 'sendkey ret' + $enterRunDeadline = [DateTime]::UtcNow.AddSeconds(10) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + $bobMarkerCount = [regex]::Matches($serialText, + [regex]::Escape('bob!')).Count + } while ([DateTime]::UtcNow -lt $enterRunDeadline -and + $bobMarkerCount -le $bobMarkerCountBeforeEnterRun) + if ($bobMarkerCount -le $bobMarkerCountBeforeEnterRun) { + throw "Enter did not run the selected bob.b64e app from the desktop file browser.`n$serialText" + } + Start-Sleep -Milliseconds 300 # The PS/2 pointer is at (672, 400). Click the editor's name # field at (512, 60), replace its filename, and save as. Send-MonitorCommand 'mouse_move -53 -113' + Start-Sleep -Milliseconds 50 Send-MonitorCommand 'mouse_move -53 -113' + Start-Sleep -Milliseconds 50 Send-MonitorCommand 'mouse_move -54 -114' + Start-Sleep -Milliseconds 100 Send-MonitorCommand 'mouse_button 1' Start-Sleep -Milliseconds 100 Send-MonitorCommand 'mouse_button 0' + Send-MonitorCommand 'sendkey home' + Start-Sleep -Milliseconds 100 + Send-MonitorCommand 'sendkey right' + Send-MonitorCommand 'sendkey right' + Send-MonitorCommand 'sendkey x' + Start-Sleep -Milliseconds 100 + Send-MonitorCommand 'sendkey backspace' + Start-Sleep -Milliseconds 100 + Send-MonitorCommand 'sendkey home' + Send-MonitorCommand 'sendkey right' + Send-MonitorCommand 'sendkey delete' + Send-MonitorCommand 'sendkey o' + Start-Sleep -Milliseconds 100 Send-MonitorCommand 'sendkey end' + Start-Sleep -Milliseconds 350 foreach ($index in 1..9) { Send-MonitorCommand 'sendkey backspace' + Start-Sleep -Milliseconds 350 } - Send-GuestText 'saved.txt' + Send-GuestText 'saved.txt' -delayMilliseconds 350 Send-MonitorCommand 'sendkey ctrl-s' - Send-MonitorCommand 'sendkey tab' - Start-Sleep -Milliseconds 200 - Send-GuestText 'pa' + Start-Sleep -Milliseconds 500 + # The pointer is on the filename field at (512, 60). Click + # APPS, run the selected app, then close the launcher by mouse. + foreach ($step in 1..4) { + Send-MonitorCommand 'mouse_move -97 0' + Start-Sleep -Milliseconds 50 + } + Send-MonitorCommand 'mouse_move -2 10' + Send-MonitorCommand 'mouse_button 1' + Start-Sleep -Milliseconds 100 + Send-MonitorCommand 'mouse_button 0' + Start-Sleep -Milliseconds 250 + # Launcher Run App is centered at (1006, 78). + foreach ($step in 1..9) { + Send-MonitorCommand 'mouse_move 98 0' + Start-Sleep -Milliseconds 50 + } + Send-MonitorCommand 'mouse_move 2 8' + Send-MonitorCommand 'mouse_button 1' + Start-Sleep -Milliseconds 100 + Send-MonitorCommand 'mouse_button 0' $launcherDeadline = [DateTime]::UtcNow.AddSeconds(10) do { Start-Sleep -Milliseconds 100 @@ -400,6 +1377,12 @@ try { throw "The desktop Applications launcher did not run its selected bob! app.`n$serialText" } Start-Sleep -Milliseconds 500 + # Close the Applications window through its X CLOSE button. + Send-MonitorCommand 'mouse_move 72 0' + Send-MonitorCommand 'mouse_button 1' + Start-Sleep -Milliseconds 100 + Send-MonitorCommand 'mouse_button 0' + Start-Sleep -Milliseconds 200 Send-MonitorCommand 'sendkey esc' $desktopExitDeadline = [DateTime]::UtcNow.AddSeconds(2) do { @@ -451,9 +1434,340 @@ try { if (-not $serialText.Contains('deleted')) { throw "The Save As QEMU fixture could not be removed.`n$serialText" } + $guiDeleteFixture = 'guideletefixture.txt' + Send-GuestText "write $guiDeleteFixture survivescancel" + Start-Sleep -Milliseconds 200 + Send-GuestText "cat $guiDeleteFixture" + $guiDeleteFixtureDeadline = [DateTime]::UtcNow.AddSeconds(5) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + } while ([DateTime]::UtcNow -lt $guiDeleteFixtureDeadline -and + -not $serialText.Contains('survivescancel')) + if (-not $serialText.Contains('survivescancel')) { + throw "The GUI delete test fixture could not be created and read back.`n$serialText" + } + $shellMarkerCountBeforeGuiCancel = [regex]::Matches($serialText, + [regex]::Escape($shellPromptMarker)).Count + $exitMarkerCountBeforeGuiCancel = [regex]::Matches($serialText, + [regex]::Escape('application exit status=0x0000000000000000')).Count + Send-GuestText 'run desktop.b64e' + $guiCancelStartDeadline = [DateTime]::UtcNow.AddSeconds(10) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + $bobMarkerCount = [regex]::Matches($serialText, + [regex]::Escape('bob!')).Count + } while ([DateTime]::UtcNow -lt $guiCancelStartDeadline -and + $bobMarkerCount -le $bobMarkerCountBeforeDesktop+2) + if ($bobMarkerCount -le $bobMarkerCountBeforeDesktop+2) { + throw "The desktop did not reopen for Help and delete-dialog tests.`n$serialText" + } + Start-Sleep -Milliseconds 300 + # Focus Files, test popup dismissal, close Help, then click + # Cancel in the delete dialog for the fixture. + Send-MonitorCommand 'sendkey tab' + Start-Sleep -Milliseconds 120 + Send-MonitorCommand 'sendkey m' + Start-Sleep -Milliseconds 100 + Send-MonitorCommand 'sendkey down' + Start-Sleep -Milliseconds 100 + # The pointer is at (1078, 78). Click outside the popup at + # (200, 400) to dismiss it after keyboard navigation. + foreach ($step in 1..8) { + Send-MonitorCommand 'mouse_move -100 40' + Start-Sleep -Milliseconds 60 + } + Send-MonitorCommand 'mouse_move -78 2' + Send-MonitorCommand 'mouse_button 1' + Start-Sleep -Milliseconds 100 + Send-MonitorCommand 'mouse_button 0' + Start-Sleep -Milliseconds 100 + # Reopen the popup and activate Close Menu with a mouse + # press/release inside its fourth row. + Send-MonitorCommand 'sendkey m' + Start-Sleep -Milliseconds 150 + # From (200, 400), the fourth row is centered at (30, 157). + Send-MonitorCommand 'mouse_move -170 -243' + Start-Sleep -Milliseconds 300 + Send-MonitorCommand 'mouse_button 1' + Start-Sleep -Milliseconds 100 + Send-MonitorCommand 'mouse_button 0' + Start-Sleep -Milliseconds 150 + Send-MonitorCommand 'sendkey h' + Start-Sleep -Milliseconds 350 + Send-MonitorCommand 'sendkey h' + Start-Sleep -Milliseconds 350 + Send-MonitorCommand 'sendkey d' + Start-Sleep -Milliseconds 500 + # The pointer is at (30, 157); Cancel is centered at (684, 431). + Send-MonitorCommand 'mouse_move 654 274' + Start-Sleep -Milliseconds 300 + Send-MonitorCommand 'mouse_button 1' + Start-Sleep -Milliseconds 100 + Send-MonitorCommand 'mouse_button 0' + Start-Sleep -Milliseconds 150 + Send-MonitorCommand 'sendkey esc' + $guiCancelExitDeadline = [DateTime]::UtcNow.AddSeconds(10) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + $shellMarkerCount = [regex]::Matches($serialText, + [regex]::Escape($shellPromptMarker)).Count + $exitMarkerCount = [regex]::Matches($serialText, + [regex]::Escape('application exit status=0x0000000000000000')).Count + } while ([DateTime]::UtcNow -lt $guiCancelExitDeadline -and + ($shellMarkerCount -le $shellMarkerCountBeforeGuiCancel -or + $exitMarkerCount -le $exitMarkerCountBeforeGuiCancel)) + if ($shellMarkerCount -le $shellMarkerCountBeforeGuiCancel -or + $exitMarkerCount -le $exitMarkerCountBeforeGuiCancel) { + throw "Help dismissal or delete cancellation left the desktop in an unexpected state.`n$serialText" + } + $fixtureReadCountBeforeCancelCheck = [regex]::Matches($serialText, + [regex]::Escape('survivescancel')).Count + Send-GuestText "cat $guiDeleteFixture" + $guiCancelCheckDeadline = [DateTime]::UtcNow.AddSeconds(5) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + $fixtureReadCount = [regex]::Matches($serialText, + [regex]::Escape('survivescancel')).Count + } while ([DateTime]::UtcNow -lt $guiCancelCheckDeadline -and + $fixtureReadCount -le $fixtureReadCountBeforeCancelCheck) + if ($fixtureReadCount -le $fixtureReadCountBeforeCancelCheck) { + throw "Cancelling the GUI delete dialog did not preserve its file.`n$serialText" + } + $shellMarkerCountBeforeGuiDelete = [regex]::Matches($serialText, + [regex]::Escape($shellPromptMarker)).Count + $exitMarkerCountBeforeGuiDelete = [regex]::Matches($serialText, + [regex]::Escape('application exit status=0x0000000000000000')).Count + Send-GuestText 'run desktop.b64e' + $guiDeleteStartDeadline = [DateTime]::UtcNow.AddSeconds(10) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + $bobMarkerCount = [regex]::Matches($serialText, + [regex]::Escape('bob!')).Count + } while ([DateTime]::UtcNow -lt $guiDeleteStartDeadline -and + $bobMarkerCount -le $bobMarkerCountBeforeDesktop+3) + if ($bobMarkerCount -le $bobMarkerCountBeforeDesktop+3) { + throw "The desktop did not reopen for the confirmed-delete test.`n$serialText" + } + Start-Sleep -Milliseconds 300 + Send-MonitorCommand 'sendkey tab' + Start-Sleep -Milliseconds 120 + Send-MonitorCommand 'sendkey d' + Start-Sleep -Milliseconds 500 + Send-MonitorCommand 'sendkey y' + Start-Sleep -Milliseconds 150 + Send-MonitorCommand 'sendkey esc' + $guiDeleteExitDeadline = [DateTime]::UtcNow.AddSeconds(10) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + $shellMarkerCount = [regex]::Matches($serialText, + [regex]::Escape($shellPromptMarker)).Count + $exitMarkerCount = [regex]::Matches($serialText, + [regex]::Escape('application exit status=0x0000000000000000')).Count + } while ([DateTime]::UtcNow -lt $guiDeleteExitDeadline -and + ($shellMarkerCount -le $shellMarkerCountBeforeGuiDelete -or + $exitMarkerCount -le $exitMarkerCountBeforeGuiDelete)) + if ($shellMarkerCount -le $shellMarkerCountBeforeGuiDelete -or + $exitMarkerCount -le $exitMarkerCountBeforeGuiDelete) { + throw "The desktop did not return after confirming the GUI delete dialog.`n$serialText" + } + $fileNotFoundCountBeforeDeleteCheck = [regex]::Matches($serialText, + [regex]::Escape('file not found')).Count + Send-GuestText "cat $guiDeleteFixture" + $guiDeleteCheckDeadline = [DateTime]::UtcNow.AddSeconds(5) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + $fileNotFoundCount = [regex]::Matches($serialText, + [regex]::Escape('file not found')).Count + } while ([DateTime]::UtcNow -lt $guiDeleteCheckDeadline -and + $fileNotFoundCount -le $fileNotFoundCountBeforeDeleteCheck) + if ($fileNotFoundCount -le $fileNotFoundCountBeforeDeleteCheck) { + throw "Confirming the GUI delete dialog did not remove its selected fixture.`n$serialText" + } + Write-Output ' desktop popup outside dismissal and mouse-selected Close Menu, delete Cancel mouse click, and Yes keyboard confirmation passed' + $guiUnsavedFixture = 'guiunsavedfixture.txt' + Send-GuestText "write $guiUnsavedFixture preserved" + $unsavedCreateDeadline = [DateTime]::UtcNow.AddSeconds(5) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + } while ([DateTime]::UtcNow -lt $unsavedCreateDeadline -and + -not $serialText.Contains("write $guiUnsavedFixture preserved")) + if (-not $serialText.Contains("write $guiUnsavedFixture preserved")) { + throw "The unsaved-edit test fixture could not be created.`n$serialText" + } + $shellMarkerCountBeforeUnsavedEditor = [regex]::Matches($serialText, + [regex]::Escape($shellPromptMarker)).Count + $exitMarkerCountBeforeUnsavedEditor = [regex]::Matches($serialText, + [regex]::Escape('application exit status=0x0000000000000000')).Count + $bobMarkerCountBeforeUnsavedEditor = [regex]::Matches($serialText, + [regex]::Escape('bob!')).Count + Send-GuestText "run desktop.b64e $guiUnsavedFixture" + $unsavedEditorDeadline = [DateTime]::UtcNow.AddSeconds(10) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + $bobMarkerCount = [regex]::Matches($serialText, + [regex]::Escape('bob!')).Count + } while ([DateTime]::UtcNow -lt $unsavedEditorDeadline -and + $bobMarkerCount -le $bobMarkerCountBeforeUnsavedEditor) + if ($bobMarkerCount -le $bobMarkerCountBeforeUnsavedEditor) { + throw "The desktop could not open the unsaved-edit fixture.`n$serialText" + } + Send-MonitorCommand 'sendkey end' + Send-MonitorCommand 'sendkey x' + Start-Sleep -Milliseconds 150 + Send-MonitorCommand 'sendkey esc' + Start-Sleep -Milliseconds 250 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + $shellMarkerCount = [regex]::Matches($serialText, + [regex]::Escape($shellPromptMarker)).Count + $exitMarkerCount = [regex]::Matches($serialText, + [regex]::Escape('application exit status=0x0000000000000000')).Count + if ($shellMarkerCount -gt $shellMarkerCountBeforeUnsavedEditor -or + $exitMarkerCount -gt $exitMarkerCountBeforeUnsavedEditor) { + throw "One Escape discarded a dirty editor and closed the desktop without warning.`n$serialText" + } + Send-MonitorCommand 'sendkey down' + Start-Sleep -Milliseconds 100 + Send-MonitorCommand 'sendkey esc' + Start-Sleep -Milliseconds 250 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + $shellMarkerCount = [regex]::Matches($serialText, + [regex]::Escape($shellPromptMarker)).Count + $exitMarkerCount = [regex]::Matches($serialText, + [regex]::Escape('application exit status=0x0000000000000000')).Count + if ($shellMarkerCount -gt $shellMarkerCountBeforeUnsavedEditor -or + $exitMarkerCount -gt $exitMarkerCountBeforeUnsavedEditor) { + throw "A non-Escape key failed to cancel the dirty-editor close warning.`n$serialText" + } + Send-MonitorCommand 'sendkey esc' + Start-Sleep -Milliseconds 120 + Send-MonitorCommand 'sendkey esc' + $unsavedExitDeadline = [DateTime]::UtcNow.AddSeconds(10) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + $shellMarkerCount = [regex]::Matches($serialText, + [regex]::Escape($shellPromptMarker)).Count + $exitMarkerCount = [regex]::Matches($serialText, + [regex]::Escape('application exit status=0x0000000000000000')).Count + } while ([DateTime]::UtcNow -lt $unsavedExitDeadline -and + ($shellMarkerCount -le $shellMarkerCountBeforeUnsavedEditor -or + $exitMarkerCount -le $exitMarkerCountBeforeUnsavedEditor)) + if ($shellMarkerCount -le $shellMarkerCountBeforeUnsavedEditor -or + $exitMarkerCount -le $exitMarkerCountBeforeUnsavedEditor) { + throw "The second Escape did not close the dirty editor and return to the shell.`n$serialText" + } + Send-GuestText "cat $guiUnsavedFixture" + $unsavedVerifyDeadline = [DateTime]::UtcNow.AddSeconds(5) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + } while ([DateTime]::UtcNow -lt $unsavedVerifyDeadline -and + $serialText -notmatch '(?m)^preserved\r?$') + if ($serialText -notmatch '(?m)^preserved\r?$') { + throw "Closing the dirty editor changed or lost the saved file contents.`n$serialText" + } + Send-GuestText "rm $guiUnsavedFixture" + $unsavedCleanupDeadline = [DateTime]::UtcNow.AddSeconds(5) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + } while ([DateTime]::UtcNow -lt $unsavedCleanupDeadline -and + -not $serialText.Contains('deleted')) + if (-not $serialText.Contains('deleted')) { + throw "The unsaved-editor fixture could not be cleaned up.`n$serialText" + } + Write-Output ' dirty editor: one Escape warns, other keys cancel, second Escape exits without saving' + $guiEditFixture = 'guieditfixture.txt' + Send-GuestText "write $guiEditFixture editable" + $editCreateDeadline = [DateTime]::UtcNow.AddSeconds(5) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + } while ([DateTime]::UtcNow -lt $editCreateDeadline -and + -not $serialText.Contains("write $guiEditFixture editable")) + if (-not $serialText.Contains("write $guiEditFixture editable")) { + throw "The editor-save test fixture could not be created.`n$serialText" + } + $shellMarkerCountBeforeEditorSave = [regex]::Matches($serialText, + [regex]::Escape($shellPromptMarker)).Count + $exitMarkerCountBeforeEditorSave = [regex]::Matches($serialText, + [regex]::Escape('application exit status=0x0000000000000000')).Count + $bobMarkerCountBeforeEditorSave = [regex]::Matches($serialText, + [regex]::Escape('bob!')).Count + Send-GuestText "run desktop.b64e $guiEditFixture" + $editDesktopDeadline = [DateTime]::UtcNow.AddSeconds(10) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + $bobMarkerCount = [regex]::Matches($serialText, + [regex]::Escape('bob!')).Count + } while ([DateTime]::UtcNow -lt $editDesktopDeadline -and + $bobMarkerCount -le $bobMarkerCountBeforeEditorSave) + if ($bobMarkerCount -le $bobMarkerCountBeforeEditorSave) { + throw "The desktop could not open the editor-save fixture.`n$serialText" + } + Start-Sleep -Milliseconds 250 + Send-MonitorCommand 'sendkey end' + Send-MonitorCommand 'sendkey spc' + foreach ($key in @('s','a','v','e','d')) { + Send-MonitorCommand "sendkey $key" + } + Send-MonitorCommand 'sendkey ctrl-s' + Start-Sleep -Milliseconds 150 + Send-MonitorCommand 'sendkey esc' + $editorSaveExitDeadline = [DateTime]::UtcNow.AddSeconds(10) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + $shellMarkerCount = [regex]::Matches($serialText, + [regex]::Escape($shellPromptMarker)).Count + $exitMarkerCount = [regex]::Matches($serialText, + [regex]::Escape('application exit status=0x0000000000000000')).Count + } while ([DateTime]::UtcNow -lt $editorSaveExitDeadline -and + ($shellMarkerCount -le $shellMarkerCountBeforeEditorSave -or + $exitMarkerCount -le $exitMarkerCountBeforeEditorSave)) + if ($shellMarkerCount -le $shellMarkerCountBeforeEditorSave -or + $exitMarkerCount -le $exitMarkerCountBeforeEditorSave) { + throw "Ctrl+S did not clear the editor's dirty state before Escape.`n$serialText" + } + Send-GuestText "cat $guiEditFixture" + $editorSaveVerifyDeadline = [DateTime]::UtcNow.AddSeconds(5) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + } while ([DateTime]::UtcNow -lt $editorSaveVerifyDeadline -and + $serialText -notmatch '(?m)^editable saved\r?$') + if ($serialText -notmatch '(?m)^editable saved\r?$') { + throw "The editor did not save the exact edited text.`n$serialText" + } + Send-GuestText "rm $guiEditFixture" + $editorSaveCleanupDeadline = [DateTime]::UtcNow.AddSeconds(5) + do { + Start-Sleep -Milliseconds 100 + $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) + } while ([DateTime]::UtcNow -lt $editorSaveCleanupDeadline -and + -not $serialText.Contains('deleted')) + if (-not $serialText.Contains('deleted')) { + throw "The editor-save fixture could not be cleaned up.`n$serialText" + } + Write-Output ' desktop editor: text insertion, Ctrl+S, clean Escape exit, and exact shell readback passed' $launcherSmokeStarted = $true } if ($allPresent -and -not $snapshotSaved) { + if ($DiskSnapshotTest -and + (-not $serialText.Contains('GPT bob64 data partition found') -or + -not $serialText.Contains('dedicated data partition enables writes'))) { + throw "The kernel did not enable the prepared bob64 GPT partition.`n$serialText" + } Send-GuestText 'write persist.txt survived' $writeDeadline = [DateTime]::UtcNow.AddSeconds(5) do { @@ -465,14 +1779,19 @@ try { throw "Could not enter the persistence smoke file through the QEMU monitor.`n$serialText" } Send-GuestText 'save' - $saveDeadline = [DateTime]::UtcNow.AddSeconds(10) + $saveTimeout = if ($DiskSnapshotTest) { 90 } else { 10 } + $saveDeadline = [DateTime]::UtcNow.AddSeconds($saveTimeout) do { Start-Sleep -Milliseconds 100 $serialText = [string](Get-Content -LiteralPath $serialPath -Raw) } while ([DateTime]::UtcNow -lt $saveDeadline -and - -not $serialText.Contains('saved B64S v1 checkpoint to firmware storage and RAM')) - if (-not $serialText.Contains('saved B64S v1 checkpoint to firmware storage and RAM')) { - throw "Firmware snapshot save failed in the guest.`n$serialText" + -not $serialText.Contains('saved B64S v1 checkpoint to persistent storage and RAM')) + if (-not $serialText.Contains('saved B64S v1 checkpoint to persistent storage and RAM')) { + throw "Persistent snapshot save failed in the guest.`n$serialText" + } + if ($DiskSnapshotTest -and + -not $serialText.Contains('disk B64S snapshot saved')) { + throw "The shell save did not commit a disk-backed B64S snapshot.`n$serialText" } $persistentMarkerCountBeforeReset = [regex]::Matches($serialText, [regex]::Escape($persistentMarker)).Count @@ -486,6 +1805,10 @@ try { if ($snapshotSaved -and $persistentMarkerCount -gt $persistentMarkerCountBeforeReset -and -not $restoredCompiledAppChecked) { + if ($DiskSnapshotTest -and + -not $serialText.Contains('disk B64S snapshot restored')) { + throw "The reboot did not restore B64S from the USB GPT partition.`n$serialText" + } $restoredShellDeadline = [DateTime]::UtcNow.AddSeconds(10) do { Start-Sleep -Milliseconds 100 @@ -536,17 +1859,8 @@ try { throw "The GUI did not launch after B64S restore.`n$serialText" } Start-Sleep -Milliseconds 500 - Send-GuestText 'p' - Start-Sleep -Milliseconds 300 - # The mouse smoke app moved the PS/2 pointer 32 pixels from - # center. Move from that known position to Run App in the - # launcher at screen (994, 79), then click and release. - Send-MonitorCommand 'mouse_move 107 -107' - Send-MonitorCommand 'mouse_move 107 -107' - Send-MonitorCommand 'mouse_move 108 -107' - Send-MonitorCommand 'mouse_button 1' - Start-Sleep -Milliseconds 100 - Send-MonitorCommand 'mouse_button 0' + Send-MonitorCommand 'sendkey p' + Send-MonitorCommand 'sendkey a' $restoredLauncherDeadline = [DateTime]::UtcNow.AddSeconds(10) do { Start-Sleep -Milliseconds 100 @@ -558,12 +1872,10 @@ try { if ($bobMarkerCount -le $bobMarkerCountBeforeRestoredDesktop+1) { throw "The restored desktop launcher did not run its selected bob! app.`n$serialText" } - # The pointer remains at Run App after the child returns. The - # adjacent X CLOSE control is 80 pixels to its right. - Send-MonitorCommand 'mouse_move 80 0' - Send-MonitorCommand 'mouse_button 1' - Start-Sleep -Milliseconds 100 - Send-MonitorCommand 'mouse_button 0' + Send-MonitorCommand 'sendkey esc' + Start-Sleep -Milliseconds 200 + Send-MonitorCommand 'sendkey esc' + Start-Sleep -Milliseconds 200 Send-MonitorCommand 'sendkey esc' $restoredDesktopExitDeadline = [DateTime]::UtcNow.AddSeconds(10) do { @@ -591,15 +1903,52 @@ try { Write-Output " $marker" } Write-Output " $persistentMarker" - Write-Output " $mouseMarker" - Write-Output ' native graphics demo: surface presented, bob!, X returned to shell' - Write-Output ' native windowed launcher: ran the selected bob! app and Escape returned to shell' + Write-Output ' bob! live mouse move, wheel, and managed-button events passed' + Write-Output ' native graphics demo: title-bar drag moved the window; mouse Close returned to shell' + Write-Output ' native windowed launcher: outside release cancelled Close; inside click closed it after bob! child' Write-Output ' launcher command: forwarded argv to echo.b64e and returned to shell' - Write-Output ' resident C compile/run: bob!, exit 0; typedefs, division, bitwise/shift precedence, 16-argument call and large local frame passed' + Write-Output ' ls gui: double-click opened bob.c in cat and returned through both windows' + Write-Output ' cat gui: opened bob.c, accepted scroll keys and returned to shell' + Write-Output ' info gui: refreshed system stats and Escape returned to shell' + Write-Output ' exception diagnostics: 64-bit R15, RSP, SS and high CR2 printed; user faults recovered' + Write-Output ' resident C compile/run: bob!, exit 0; unsigned long long aliases/calls/comparisons, switch/case fallthrough, do-while/continue, delayed local initialization, prefix/postfix increment and decrement, typed pointer steps, typedefs, scalar/pointer casts, division, bitwise/shift precedence, void-pointer conversions, 16-argument call, mixed register/stack pointer args with nested call, and large local frame passed' Write-Output ' desktop Applications launcher: child bob! returned to shell' - Write-Output ' desktop filename field: mouse caret, keyboard edit, Ctrl+S Save As, shell file verification passed' + Write-Output ' desktop filename field: mouse caret, Home/Right/End/Delete/Backspace, Ctrl+S Save As, shell file verification passed' + Write-Output ' desktop file browser: Enter ran bob.b64e and returned to the open desktop' Write-Output ' post-restore compiled app launch: bob! and exit status 0' - Write-Output ' post-restore desktop: mouse ran bob! and clicked X CLOSE; Escape returned to shell' + Write-Output ' post-restore desktop: launcher ran bob!, child and windows closed, Escape returned to shell' + if ($DiskSnapshotTest) { + Stop-QemuForStorageCheck + $stream = [IO.File]::OpenRead($diskSnapshotImagePath) + try { + $snapshotPartitionFirstLba = if ($LargeLbaDiskSnapshotTest) { + [long]4294969344 + } else { [long]2048 } + [void]$stream.Seek($snapshotPartitionFirstLba * 512L, + [IO.SeekOrigin]::Begin) + $slotHeader = New-Object byte[] 512 + if ($stream.Read($slotHeader,0,$slotHeader.Length) -ne $slotHeader.Length -or + [Text.Encoding]::ASCII.GetString($slotHeader,0,4) -ne 'B64D') { + throw 'The raw disk image does not contain a committed B64D slot header.' + } + [void]$stream.Seek(($snapshotPartitionFirstLba + 1L) * 512L, + [IO.SeekOrigin]::Begin) + $snapshotHeader = New-Object byte[] 4 + if ($stream.Read($snapshotHeader,0,4) -ne 4 -or + [Text.Encoding]::ASCII.GetString($snapshotHeader,0,4) -ne 'B64S') { + throw 'The raw disk image does not contain a B64S snapshot payload.' + } + } finally { $stream.Dispose() } + if ($LargeLbaDiskSnapshotTest) { + Write-Output ' USB GPT B64S persistence above 2 TiB: save, reboot restore, and raw-image verification passed' + } else { + Write-Output ' USB GPT B64S persistence: save, reboot restore, and raw-image verification passed' + } + } + & (Join-Path $PSScriptRoot 'test_bob64_serial.ps1') ` + -QemuPath $QemuPath -OvmfCodePath $OvmfCodePath ` + -OvmfVarsPath $varsTemplatePath -ImageRoot $ImageRoot ` + -TimeoutSeconds $TimeoutSeconds exit 0 } } @@ -610,6 +1959,11 @@ try { } throw "Timed out waiting for the UEFI kernel smoke checks.`n$serialText" } +catch { + Write-Output $_.InvocationInfo.PositionMessage + Write-Output $_.ScriptStackTrace + throw +} finally { if ($process -and -not $process.HasExited) { $process.Kill() @@ -618,7 +1972,19 @@ finally { if (Test-Path -LiteralPath $serialPath) { Remove-Item -LiteralPath $serialPath -Force } + if (Test-Path -LiteralPath $framebufferPath) { + Remove-Item -LiteralPath $framebufferPath -Force + } if (Test-Path -LiteralPath $varsCopyPath) { Remove-Item -LiteralPath $varsCopyPath -Force } + if (Test-Path -LiteralPath $storageImagePath) { + Remove-Item -LiteralPath $storageImagePath -Force + } + if (Test-Path -LiteralPath $storageReconnectImagePath) { + Remove-Item -LiteralPath $storageReconnectImagePath -Force + } + if (Test-Path -LiteralPath $diskSnapshotImagePath) { + Remove-Item -LiteralPath $diskSnapshotImagePath -Force + } } diff --git a/tools/test_bob64_serial.ps1 b/tools/test_bob64_serial.ps1 new file mode 100644 index 0000000..5e51aab --- /dev/null +++ b/tools/test_bob64_serial.ps1 @@ -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 + } +}