This commit is contained in:
Alvin-Zilverstand committed 2026-10-08 01:02:30 +02:00
1 parent 96cd1ac97d
commit 6dfe517094
33 files changed
+9970 -3177

No files matched your search

+229
View File
@@ -0,0 +1,229 @@
# bob32 migration and source audit
The active scope includes completing feasible C support, reviewing every source
file for bugs, and migrating the emulator/toolchain/applications to 32 bits.
These tasks are incomplete. This file tracks actual migration boundaries.
## Current execution modes
The emulator uses 32-bit general registers, accumulator and memory words.
B16K images and existing BASM run with 16-bit normalization and condition flags.
B32K images select native 32-bit word arithmetic and load/store behavior.
Both bob.exe and bob32.exe use this implementation.
Instruction encoding remains 16-bit, while native-mode program counters and
effective addresses are 32-bit word addresses. The original 65,536-word region
uses the existing RAM array; higher addresses use lazily allocated sparse pages
(up to 4,096 resident pages of 4,096 words each). B32K version 2 images can load
and start anywhere in the 32-bit address space. Their payload is currently
limited to 65,536 words by the boot-disk buffer. Version 1 images and supervised
program entry points retain their legacy low-memory bounds. The host C compiler
emits B32K v2 images with `--wide`, and the build generates a B32K kernel image.
Its shell, editor, filesystem and resident compiler run; supervised legacy apps
execute with 16-bit arithmetic compatibility. In B32 mode, resident `cc` and
`go` emit native kind-2 programs with 32-bit `int`, stored in the guest RAM
filesystem and preserved by B32S snapshots. The resident compiler remains a
small C subset, with fixed-size one-dimensional local `int` arrays in bob32.
The host compiler's `--wide-app` mode emits larger B32K v2 images at the
supervised app origin. `import32 HOST_PATH NAME` validates and stores one in the
guest RAM filesystem; `run NAME` loads and executes it from there. `run32 PATH`
remains available for direct host-path execution. The 4,096-word guest file
region is shared by eight slots, so an imported image occupies six metadata
words, its payload and a terminator, less space already used by other files.
The loader validates the header, checksum, exact file size, entry and app-region
bounds, then preflights sparse memory before loading. B32S version 2 snapshots
preserve packed native files. Version 1 fixed-slot B32S snapshots remain
readable and are converted during restore; compatibility mode continues to use
B16S.
The bob32 kernel is loaded at `0x10000`, above the 64K-word compatibility RAM;
the current image ends at `0x1D115`, leaving a gap before the native app origin.
Resident kind-2 programs and imported B32K v2 apps run from `0x20000`; resident
compiler output can use remaining packed filesystem capacity (up to 4,095
words for one file), while source text remains limited to 511 words. Legacy kind-1 apps load at
`0xC200..0xCFFF` and keep 16-bit arithmetic compatibility. The 4,096-word B32 heap is
at `0xD000..0xDFFF`; the bob16 heap remains `0xC000..0xDFFF`. Legacy
applications retain access to their shared heap while their downward stack
starts at `0xD000`.
The bob16 OS loads kind-1 programs at `0xA000` to leave room for kernel growth.
Native B32 apps
use a separate high-memory range.
The bob32 resident C compiler supports local pointers to integer-returning
functions with integer parameters. A pointer can be initialized from a declared
function and invoked indirectly; function-pointer parameters, return values,
globals and pointer arithmetic remain unsupported. This feature is not enabled
in the bob16 resident compiler.
Resident prototypes distinguish `int f(void)` from `int f()`. The latter keeps
unspecified parameter status, while this compiler requires calls to match the
eventual definition's arity so its stack-based calling convention stays sound.
## Wide image format
B32K version 1 retains the original 16-byte header and low-memory bounds. Version
2 uses a 24-byte little-endian header: magic, 16-bit version, 16-bit header size
(24), 32-bit origin, entry, word count and additive checksum, followed by
32-bit little-endian payload words. The loader validates address overflow,
entry range, payload limit, checksum and exact file length before changing RAM.
It loads the payload directly and starts at the 32-bit entry address. Instruction
words still use the low-16-bit encoding and require zero upper bits; data words
retain all 32 bits. Run `bob32.exe --boot PATH` to load a B32K image. B32
applications compiled with `--wide-app` use origin `0x20000`, and `run32` limits
their payload and entry to the supervised region below `0x100000`. B16K and
`--os` continue selecting the existing compatible kernel.
## Audit evidence and remaining coverage
Initial review covered the CPU state, fetch/address/ALU/store paths and image
loader in main.c, plus the snapshot width boundary in storage.c. It found and
fixed undefined negative left shifts in sign extension. Addition now uses
unsigned wraparound, and effective register-relative addresses use unsigned
arithmetic before address truncation, avoiding signed overflow in wide mode.
tests/test_cpu.c exercises the actual CPU implementation: immediate sign
extension, both word-width boundaries/flags, wide memory loads/stores, wide
image reading, guest boot-disk transfer and execution, and mode selection.
The OS/compiler and native console suites also run against the migrated CPU.
### Trap and return-register review
The JSR/PUTS/GETS return-address assignments now apply the selected word-width
normalization, preserving signed bob16 register values above address 0x7fff.
PUTS no longer uses the instruction register as a string temporary; it compares
the complete data word with zero before emitting its low byte. This fixes early
termination of a wide string word such as 0x00010000 and preserves the decoded
trap instruction. GETS computes its input length once rather than repeatedly
scanning the entire string while copying it.
The direct CPU suite now passes 47 checks, including both return-address widths,
wide supervised program results/parent restoration, instruction-state preservation
and full-width string termination. The compatibility suites pass 915 OS/compiler
checks and 28 native console checks. These are targeted findings from the current
review, not proof that every trap edge case or source line has been reviewed.
### Image loader and cycle-limit argument review
The --max-cycles parser previously accepted partial numbers and silently disabled
the limit for zero or invalid text. It now accepts only positive decimal values
within unsigned long range, rejecting signs, whitespace, trailing text and
overflow. Omitting the option still selects unlimited execution.
The direct suite passes 65 checks, adding malformed wide-image subprocess cases
for short headers/payloads, wrong checksum, trailing bytes, invalid entry and
version, plus cycle-limit boundary/invalid values and an actual limited emulator
run with exit status 2. The 915 OS/compiler and 28 native console checks also
pass. Loader validation and argument parsing have been reviewed; wider addresses,
format evolution and the remaining source audit are still unfinished.
### Assembler input and data directive review
Source parsing now closes the input file through one wrapper on both success and
failure. Physical source lines above 255 characters reject rather than becoming
multiple instructions. CRLF characters are token separators. .fill requires one
complete unsigned hexadecimal word and rejects trailing garbage or truncation.
.stringz now checks remaining memory before writing, fixing a possible host
out-of-bounds write. It emits exactly one terminator instead of appending a second
zero through the common instruction path. Following data therefore starts one
word earlier than with that bug; hand-counted offsets relying on the extra padding
need adjustment. The repository demo and compatibility suites still pass.
Assembly can use all 65,536 slots, with the next word rejected before writing.
The direct suite now passes 73 checks, including exact-capacity assembly and a
near-end string overflow attempt. The 915 OS/compiler and 28 console checks pass.
Instruction operand parsing/encoding, especially atoi conversions and register
validation, still needs review; this is not a complete assembler or repository
audit.
### Assembler numeric operands and branch flags
All fourteen atoi operand conversions now use a complete signed-decimal parser
with host-int range checks. Invalid register-shaped tokens cannot silently become
immediate zero; missing digits, trailing text and overflowing numbers reject.
Valid operands still clamp to the existing instruction field widths. Branch
conditions reject unknown letters instead of silently omitting those flags.
The documented NOP instruction now assembles as zero and rejects extra operands.
The direct suite passes 94 checks, including every numeric operand path,
malformed branch flags, preserved signed clamping/JSR/JSRR encodings and NOP.
The 915 OS/compiler and 28 console checks also pass. More encoding/decoder
round-trip checks and the other source files remain to audit; the full bob32
compiler/kernel migration is still incomplete.
### Storage service source review
storage.c has been read through for hashing, metadata validation, descriptor
ranges, save replacement/error cleanup, and restore validation/commit ordering.
The descriptor upper bound now uses subtraction rather than descriptor+4,
preventing unsigned overflow in the internal service API. The guest trap already
narrows its argument, but direct service callers must also be safe. Restore now
checks stream errors and close failure before committing any buffered words.
New direct cases validate empty/used snapshots and reject excessive lengths,
invalid kind/used flags, embedded text zeroes, missing terminators, duplicate
names, overflowing descriptors and wide-mode format use. The direct suite passes
105 checks; compatibility/persistence and console suites pass 915 and 28 checks.
This review does not establish power-loss durability. B32S now preserves full-width data; the remaining migration/audit areas stay open.
### Native instruction word boundary
Wide instruction fetch now rejects nonzero reserved upper bits rather than
silently truncating a 32-bit data word into a different instruction. The native
boot ROM stores zero-extended instruction words; legacy ROM/assembly words still
use signed 16-bit normalization. A supervised malformed wide instruction must
fault and restore parent CPU state, while legacy sign-extended RET remains valid.
The direct suite passes 107 checks, and 915 OS/compiler plus 28 console checks
passed at that stage. The instruction encoding remains compact; B32K v2 later
extends image addresses without changing instruction words. A native 32-bit
compiler/kernel remains unfinished.
### Register-controlled address boundary
JMP, JSRR, RET and PUTS consume register-held addresses. In native mode these
paths preserve the complete address; previously values such as 0x10000 aliased
address zero. Compatibility mode retains its existing 16-bit wrapping. CPU
checks cover all four transfers, sparse high-memory loads/stores, indirect
loads/stores, high-address console/input/disk buffers, supervised high-data
access, B32K v2 high-origin boot, top-of-address-space loading, and malformed
header rejection. Version 1 image loading remains low-memory compatible.
The entire repository has NOT yet been audited line by line. Remaining review
includes assembler/tokenization/error paths, all trap edge cases, image/storage
malformed input, compiler parsing/type checking/emission, arithmetic helpers,
kernel runtime/files/compiler/shell/input/editor, build code and test coverage.
Generated kernel.basm needs generator/round-trip validation rather than merely
assuming generated instructions are correct. Documentation examples and saved
formats also need migration checks.
## Remaining migration requirements
- [x] Define the 32-bit instruction/address ABI and emulator/image limits.
- [x] Add a 32-bit C compiler target and native arithmetic/runtime services.
- [x] Port the kernel, resident compiler, editor, memory allocator and filesystem.
- [x] Version persistent storage and verify compatibility/migration of saved files.
- Verify existing BASM, C applications and snapshots against compatibility mode;
verify rebuilt applications against the new ABI.
- Complete the whole-source audit and repair findings with targeted tests.
- Complete the remaining full-C implementation documented in C_IMPLEMENTATION.md.
Native snapshot update: B32S version 1 used fixed 512-word file slots. Version 2 retains the 16-byte header and 4,312-word payload size, but packs bob32 file contents by length so native apps can exceed 511 words. Both use little-endian 32-bit words and a checksum over all four bytes. Version 1 snapshots are repacked during restore; version 2 is written going forward.
Native filesystem app workflow: `import32 HOST_PATH NAME` validates B32K v2 images and packs their origin, entry, word count, checksum and payload into a guest file. `run NAME` validates the packed image, reserves all sparse pages before loading, runs the app and reports format, storage, memory, fault and timeout failures. `save` and `restore yes` persist the app through B32S. Integration coverage imports and runs a 629-word image through both `run` and `run32` guest-name commands, snapshots/restores it, and runs it again; direct checks cover checksum corruption and sparse-allocation failure. The current suites pass 203 CPU checks, 1,813 OS/compiler checks and 28 console checks.
Storage address audit: native trap 7 preserves full-width descriptor and table addresses, allowing the relocated bob32 kernel's globals while checking that each table lies in low kernel RAM or the loaded kernel image. Out-of-range descriptors reject rather than alias. Legacy mode retains the signed 16-bit address representation. Native restore checks also verify changed-kernel handling: binary slots are omitted while source text survives.
Decoder reserved-bit audit: NOP and RET require zero low 12 bits, register JSR requires zero low 8 bits, and in-place NOT requires zero low 8 bits. These fields were ignored previously. Malformed encodings now fault in both execution modes; valid instruction encodings remain covered by OS/application checks.
Native trap argument audit: trap 3 accepts a full-width buffer address but keeps its capacity limited to 16 bits; trap 6 remains constrained to the supervised low-memory entry region. Legacy word-address representations remain accepted. Other trap/address paths still require complete review.
Native disk trap boundary: trap 4 rejects upper bits in its destination, offset and count before narrowing or transferring words. Valid current-range native boot reads and legacy mode remain covered. This closes another argument-aliasing gap; full-width address and image ABI work is still unfinished.
Assembler source lines now use a bounded byte reader that rejects embedded NULs rather than silently truncating them through C-string tokenization. It preserves the 255-character limit, CRLF handling and acceptance of a final unterminated line. The direct CPU/assembler suite passes 138 checks, including a binary fixture with an embedded zero; 1,568 OS/compiler checks also pass.
Assembler `not` now requires exactly one destination register or a destination/source register pair. It no longer accepts extra operands or treats an invalid second register as the one-operand form. The direct suite covers those malformed forms and passes 141 checks; the OS/compiler suite passes 1,568 checks.
All load/store register operands now reject every negative parse result, including malformed names and out-of-range register numbers. Previously those handlers rejected only missing tokens; invalid registers could flow into negative shifts and malformed encodings. Direct tests cover both `r8` and malformed names in each affected field. The suite passes 150 CPU checks; 1,568 OS/compiler checks pass.
Assembler trap validation now matches the emulator's implemented vector table (0 through 11). Vectors 12 through 15 previously assembled successfully but faulted when executed. New rejection cases cover 12 and 15. Direct decoder tests also confirm reserved register-form ADD/AND bits fault in legacy and wide modes. The direct suite passes 156 CPU checks, and the OS/compiler suite passes 1,568.
+372 -1
View File
@@ -11,7 +11,9 @@ the goal complete. Existing programs and the nano-like editor must keep working.
unsigned conversions/promotions, pointer arithmetic, alignment, aggregate
layouts, calling conventions, floating-point and wider integer representations.
- Expand declarations: complete declarators, typedefs, qualifiers, storage
classes, lexical scopes/shadowing, prototypes, function pointers and variadics.
classes, lexical scopes/shadowing, prototypes, complete function-pointer support
and variadics. Typed function pointers and indirect calls now work in the host
compiler; return types and variadic function-pointer cases remain open.
- Expand types: unsigned/signed integer variants, enums, structs/unions, nested
arrays/pointers and supported floating-point types with software operations.
- Expand expressions: sizeof, conditional/comma operators, full lvalue/type
@@ -210,3 +212,372 @@ to 16. Function declarator suffixes still use the earlier direct-function parser
function pointers and functions returning array pointers remain to implement.
Qualifier semantics, compatible incomplete-type merging, the resident compiler
architecture, remaining C types and the standard library are also incomplete.
## Shift assignments and integer operand constraints
The host lexer recognizes <<= and >>= before their two-character prefixes.
They parse as right-associative assignments and use the existing native shift
helpers, retaining single evaluation of the destination address. Tests cover
indexed destinations with side effects, chained assignment, expression precedence,
zero shifts and signed right shifts. Integer-only binary operators and unary
plus/minus/complement reject pointer operands, including unevaluated sizeof
expressions. This does not yet implement the full arithmetic conversion model.
All 615 regression checks pass. These changes are in the host compiler; the
resident compiler's corresponding operators and broader C implementation remain
unfinished.
## Composite function declaration types
Function declaration checks now recursively form composite pointer/array types.
An unspecified array bound can match a known bound through additional pointer
levels, retaining the known bound. Conflicting known bounds, element types and
pointer depths still reject. Native tests cover forward declarations with
incomplete row types followed by complete definitions; rejection tests also
cover an incomplete declaration followed by two conflicting completions.
All 631 regression checks pass and the kernel rebuild remains 36,009 words.
Qualifier and old-style promotion compatibility, object redeclarations and the
remaining function declarator forms still require implementation.
## Compound assignment and unevaluated constraints
Compound assignments share an operator mapping and operand checks across native
emission and sizeof type inference. Pointer compound assignments allow only
integer addition/subtraction offsets with complete pointees; pointer subtraction
from another pointer remains a binary expression yielding an integer, not an
assignable pointer offset. Integer compound assignments reject pointer operands.
Assignment and increment checks inside sizeof require a modifiable scalar lvalue,
rejecting arrays, void objects and literal targets without evaluating operands.
Native tests verify valid row-pointer offsets and sizeof suppression of indexed
and increment side effects. Rejection tests cover pointer differences in compound
assignments, pointer shifts, array/literal modification and void pointer offsets.
All 671 checks pass; kernel compilation stays at 36,009 words. Const semantics,
simple-assignment conversions and the remaining full expression/type checker
still need implementation, along with the resident compiler expansion.
## File-scope object declarations and tentative definitions
Global objects are registered by name and compatible declarations form a composite
type. Repeated tentative definitions share one allocation. One initialized
definition may replace the tentative zero initialization; a second initializer
rejects. File-scope extern declarations, including function declarations, parse
without creating storage for declaration-only objects. Referenced undefined
objects fail relocation resolution, while unused extern declarations are accepted.
Incomplete array bounds can be completed by another declaration, and a remaining
tentative array definition reserves one element at translation-unit completion.
Native tests combine extern/tentative/initialized scalars, pointer relocations,
completed multidimensional arrays and an uncompleted tentative array. Rejections
cover conflicting object types/bounds, duplicate initialized definitions,
unresolved references and sizeof an uncompleted extern array. All 695 regression
checks pass; the kernel rebuild remains 36,009 words.
This does not implement block-scope extern/static storage, internal linkage,
separate compilation or declaration-point-sensitive global visibility. Global
resolution still uses the complete source unit. Those semantics, the resident
compiler expansion and the remaining full-C roadmap stay unfinished.
## Block-scope extern objects
Block extern object declarations register compatible external types without
allocating local frame slots. Native emission activates a scoped alias to the
global storage; nested aliases can shadow outer automatic locals and repeated
compatible extern declarations in the same scope share the alias. Extern-only
names are withheld from the ordinary file-scope lookup, preventing them from
escaping their declaring block or appearing in another function without a
declaration. Referenced missing definitions still reject at relocation time.
Native tests verify global writes through a nested alias, preservation of an
outer local, completed array types and repeated extern declarations. Rejection
tests cover unresolved objects, conflicting local/types, block initializers and
names escaping their block/function. All 727 checks pass and the kernel rebuild
remains 36,009 words. Block function declarations, static storage, full linkage
rules and separate compilation remain unfinished; these additions remain in
the host compiler rather than the resident compiler.
## Function-local static storage
Block static objects receive unique private data symbols and scoped aliases,
avoiding stack allocation and per-call initialization. Their native data is
initialized once at image load, with zero initialization for omitted values.
Static initializer references resolve against the declaring scope and retain
private symbols in pointer relocations; references to automatic storage reject.
Objects with equal names in different blocks/functions remain independent.
Native tests exercise persistent counters, pointer access to another local static,
arrays, strings and independent same-name objects. Rejections cover automatic
values/addresses, runtime calls, duplicate declarations, escaped names and
uninitialized unsized arrays. All 755 regression checks pass; the kernel rebuild
remains 36,009 words. File-scope internal linkage, additional constant expression
forms and the resident compiler expansion remain incomplete.
## File-scope static declarations and linkage checks
File-scope objects/functions now parse static storage declarations and retain
linkage metadata. Repeated internal object declarations share one allocation;
subsequent extern declarations inherit existing linkage. Objects cannot switch
between external and internal linkage, and a static function declaration cannot
follow an external declaration. A function definition without a storage class
can follow its earlier static prototype. Incomplete internal tentative arrays
reject instead of silently receiving the external tentative-array completion.
Native tests combine internal objects, arrays, relocated pointers, static
function prototypes and later extern declarations. Negative tests exercise both
object linkage conflict directions, conflicting function declarations and
incomplete internal arrays. All 783 checks pass; the kernel rebuild remains
36,009 words. This remains a single-unit compiler: separate compilation, linker
exports and cross-unit isolation still require implementation, as does the
resident compiler expansion.
## Sizeof in constant initialization
The constant evaluator now handles sizeof expressions using their inferred type.
Literal/type-based sizeof can be used in bounds and case labels, and global
initializers can use sizeof registered global objects. Local static initializer
sizeof operands are folded while their lexical bindings are active, allowing
sizes of automatic arrays without treating them as runtime values or addresses.
Unevaluated side effects remain suppressed.
Native tests cover string/type bounds, global scalar/list initialization, local
static sizes of automatic objects and a sizeof case label. All 787 regression
checks pass and the kernel rebuild remains 36,009 words. Bounds and case labels
are still parsed before runtime symbols are registered, so sizeof a named object
in those contexts requires the remaining declaration-point symbol/type work.
The full-C goal and resident compiler expansion remain incomplete.
## Parser type bindings for constant sizeof
The parser retains object type bindings at declaration points, updates inferred
array types after initialization and restores bindings at block/for/function
boundaries. Parameter arrays expose their adjusted pointer type. Constant sizeof
in bounds, designators and case labels can therefore query declared object types
without depending on the later code-generation symbol table. Compatible repeated
file declarations retain a completed array bound in these parser bindings.
Native tests verify named global/local/parameter sizes, nested shadowing and
restoration, loop scope and named sizeof case labels. Negative tests reject
forward, escaped block/loop and undeclared self references in bounds. All 807
checks pass and the kernel rebuild remains 36,009 words. Parser type bindings
are limited to 4096 active declarations. This improves constant-expression
contexts; declaration-point visibility in ordinary generated expressions,
typedefs and the remaining full-C/resident work still require implementation.
## Scoped typedef names
Parser bindings distinguish objects, functions and typedef names in the ordinary
identifier namespace. Typedef declarations reuse the recursive declarator parser
for the currently supported scalar, pointer and array types, with comma-separated
aliases and identical same-scope redeclarations. Aliases work in declarations,
parameters, casts, sizeof and other aliases. A sole unnamed void alias parameter
specifies no arguments. Scope tracking restores outer aliases after a nested block
or loop and lets inner objects hide outer typedef names.
Native tests combine scalar/pointer/row/incomplete-character-array aliases,
adjusted array parameters, casts, nested alias/object shadowing, loop declarations
and void aliases. Rejections cover incompatible aliases, object/function namespace
collisions, parameter collisions, escaped aliases and void objects. All 843 checks
pass; the kernel rebuild remains 36,009 words. Function-type aliases, qualifiers,
remaining C types and resident compiler support remain incomplete.
## Enum types and scoped enumerators
The host parser supports tagged/anonymous enum definitions, explicit integer
constant values and automatic increments. Enumerators share the ordinary
identifier namespace and become constant AST values at use sites. A separate
scoped tag table permits nested tag shadowing without conflating tag and object
names. Enum descriptors retain distinct identities and use the target's signed
16-bit int representation; declaration composites permit compatibility with that
chosen integer type while rejecting different enum identities.
Native tests cover negative/automatic values, expressions referring to earlier
enumerators, typedef enum aliases, global objects, function parameters, array
bounds, case labels and nested block/loop shadowing. Rejections cover duplicate
tags/constants, namespace collisions, automatic signed overflow, escaped bindings,
constant assignment and conflicting enum parameter types. All 887 regression
checks pass; the kernel rebuild remains 36,009 words. Tags must already be defined
when referenced; incomplete enum extensions and unsigned/wider representations
remain unsupported. Resident enum parsing is still unfinished.
## Boolean type and conversions
The host type parser supports _Bool and aliases of it as a distinct one-word
primitive. Native conversion to 0/1 occurs at explicit casts, scalar/array
initialization, assignment, function arguments/returns and increment/decrement.
Static data initialization and constant casts use the equivalent host folding.
Function parameter emission applies the definition's boolean parameter type,
and declaration compatibility distinguishes bool from int.
Native tests cover nonzero/zero global/local/static initialization, nested arrays,
integer/pointer casts, arguments, return values, compound assignments and prefix/
postfix modification. Rejections cover incompatible boolean object/parameter
redeclarations. All 899 regression checks pass; the kernel rebuild remains
36,009 words. The standard stdbool header, complete arithmetic conversion rules,
other numeric types and resident boolean support still need implementation.
## Unsigned int arithmetic foundation
The host compiler supports explicit unsigned/unsigned int declarations and U/u
literal suffixes as a distinct 16-bit type. Expression inference propagates the
unsigned arithmetic result for current word-width int operands; comparisons,
division/remainder and right shifts select unsigned native operations. Constant
evaluation applies the corresponding unsigned behavior. Existing wraparound
addition/subtraction/multiplication use the same word instructions.
tools/unsigned.c provides native unsigned comparisons, fixed-16-step division,
remainder and logical right shift. It is parsed only for a source unit using
explicit unsigned types/literals, preserving the existing kernel layout.
Native tests cover high-bit ordering, mixed signed operands, division/remainder
across the signed boundary, logical shifts, compound shifts and wraparound.
Conflicting parameter/object types and pointer division reject. All 915 checks
pass and the kernel rebuild remains 36,009 words.
This is not the complete integer conversion model. Unsuffixed literal typing
retains prior behavior, other unsigned/wider integer types and all specifier
orderings are unfinished, and runtime shift/divide exceptional cases retain
the existing helper policy. Resident unsigned parsing/code generation remains
unfinished. Full C stays an active objective.
Host declaration specifiers: signed and signed int now use the existing signed-int type, and int signed / int unsigned are accepted in either order. This applies to globals, locals, typedefs, parameters, return types, casts and sizeof type names. Duplicate int and repeated/conflicting sign specifiers fail compilation. Wider integer types, signed/unsigned char, qualifier enforcement and the resident compiler remain separate work.
Host literal audit: all simple C escape sequences are now recognized, including \a, \f, \v and \?. Character and string escapes accept byte values 0..255. Hexadecimal accumulation checks the range before multiplication, preventing signed host overflow; out-of-range octal/hexadecimal escapes fail. A trailing backslash is rejected before advancing past the source terminator. This byte-literal extension does not provide wide literals, Unicode conversion or the remaining integer-width/type-selection work.
Host input audit: binary zero bytes in preprocessed source are rejected instead of silently truncating the translation unit. Input seeks, reads, stream error and close are checked. Raw newline characters inside ordinary literals and malformed integer token tails now produce lexer errors. This does not expand target integer widths or floating-point support.
Host relational pointer comparisons now use unsigned target address order, including across 0x8000, while signed integer comparisons retain signed order. Compatible pointer types use composite type checks, including pointers to arrays with known/incomplete bounds. Pointer/integer, incompatible pointee and void-pointer relational comparisons are rejected in evaluated expressions and sizeof operands. Full qualifier and aggregate compatibility remain unfinished.
Host output audit: assembly, binary and map output streams now check write/close failures, and missing map output is a compilation failure. Derived map extensions apply only to the filename, preserving dotted parent directories. Input/output and map path collisions are rejected before writing; Windows checks normalize absolute paths and case. Hard-link/symlink aliases and atomic publication of all three files remain unresolved, and an I/O failure after publication starts can still leave partial outputs.
Host void-expression constraints: arithmetic/comparison and logical operands, unary value operators, assignment sources, casts to value types and control-flow conditions now reject void results. Conditional expressions require both branches to be void when either is void. Equivalent checks apply inside sizeof without evaluating its operand. Discarded void calls, casts to void, comma expressions and two-void-branch conditionals remain valid. Other conversion, qualifier and aggregate constraints remain unfinished.
Host return/argument constraints now reject return expressions in void functions, bare return statements in value-returning functions, void results returned as values, and void arguments to ordinary or trap-backed functions. Full assignment-compatible conversion checking remains incomplete.
Host switch constraints: controlling expressions and case-label expressions must have an integer type. Pointer/array/void conditions and pointer/void labels are rejected. Unsigned integer, enum and _Bool switches remain supported. Complete integer-constant-expression rules and the remaining type conversion constraints still need review.
Host const syntax: const can precede or follow scalar, typedef and enum specifiers, appear between signed/unsigned/int specifiers, and repeat at base or pointer levels. Direct const scalar objects, const array elements, scalar parameters, scalar globals, and const pointer objects (including pointer typedef aliases) reject assignment and increment. Address-of preserves const qualification; writes through const-qualified pointers reject, adding const in pointer assignments is allowed, and dropping it is rejected through nested pointer levels and conditional expressions. `bob_puts` accepts a const string. Function redeclarations now require matching pointed-to qualifiers while ignoring top-level parameter qualifiers. Some nested qualified-declarator forms and full C qualifier compatibility remain unfinished.
Host pointer subtraction now checks composite type compatibility, including the target enum's compatible signed-int type and corresponding array rows. Both pointed-to types must have complete storage sizes. Different enum tags, different known row extents and incomplete element types remain rejected.
Host conditional pointer types now combine compatible pointee types, preserve known array bounds, select void pointer for object/void pointer combinations, and permit arithmetic integer constant zero as a null branch. Incompatible pointer branches, nonzero integers and nonconstant integer branches are rejected, including inside sizeof. Null-constant recognition still requires review for all permitted unevaluated-expression cases; qualifier merging remains incomplete.
Native bob16 multiplication now uses a sixteen-step bit-mask algorithm instead of operand-sized repeated addition. It computes the same low 16-bit product for signed and unsigned operands, including INT_MIN, without a sign-normalization branch. The host compiler arithmetic library and rebuilt kernel use it. The resident compiler also receives this improvement through its cc_multiply wrapper, which calls the shared runtime helper. Kernel size is now 36,005 words.
Resident numeric lexer now treats leading-zero integer spellings as octal, accepts octal word values through 0177777, and rejects digits outside the base or values exceeding one word. Decimal range rules remain unchanged. Error handling sets EOF centrally, and the general compile-error message is shorter. Kernel size is 36,092 words, leaving four words below the current kernel/program boundary; increasing usable kernel capacity remains necessary for further resident features.
Host code generation now omits zero-argument call cleanup and zero-sized function-frame allocation. Numeric constants normalize to their target 16-bit bit pattern before choosing short literal instructions, so values such as 0xffff can use the short -1 encoding. The rebuilt kernel is 35,909 words, saving 183 words and leaving 187 words below the current boundary. This creates some immediate room but does not replace the required memory-layout/bob32 work.
Resident literal support now includes all simple C escapes, adding \r, \b, \a, \f, \v and \? to the existing newline/tab/quote/backslash forms. Numeric escapes and embedded string zero bytes remain unfinished. Host code generation collapses !!value to one boolean comparison while evaluating the operand once. Kernel size is 36,096 words: exactly the current reserved region, with no remaining growth space.
Host frame generation now omits frame-pointer save/setup/restore for functions with no parameters and no automatic local storage. Return addresses remain saved, including recursive calls. Functions needing parameter/local addressing retain the existing frame layout. Kernel size is now 36,054 words, leaving 42 words below the boundary.
Resident lexer now rejects raw LF/CR inside character and string literals while retaining escaped controls. Host code generation folds unary minus, complement and logical negation directly on numeric literals into target-word constants; runtime operands retain normal evaluation. Kernel size is 36,041 words, leaving 55 words of current-region capacity.
Resident primary expressions now concatenate adjacent string literal tokens, including intervening comments/newlines and empty pieces. Each piece retains the lexer token limit; combined data goes through the existing bounded code emitter and receives one trailing zero. Numeric escapes and embedded zero bytes remain incomplete. Kernel size is 36,071 words, leaving 25 words below the current boundary.
Resident code emission now stops after the first compiler error instead of continuing writes to its bounded scratch buffer. The existing 511-word capacity guard remains. Kernel size is 36,080 words, leaving 16 words below the current boundary.
Native signed division now bypasses repeated subtraction when the normalized divisor is -1, covering original divisors 1 and -1. Sign detection uses the sign of the XOR of operands. Other divisors retain the existing subtraction algorithm. Host code generation also folds numeric-literal addition/subtraction/multiplication with the existing target-word constant evaluator. Kernel size is 36,093 words, leaving three words.
Host constant evaluation now validates cast, unary, binary and conditional expression types before folding or selecting short-circuit branches. This prevents invalid void operand combinations from being accepted only in static initializers. The broader integer-constant-expression grammar still needs review.
Host pointer equality now requires compatible pointer types, permits object/void pointer combinations, and requires an integer operand to be a recognized null constant. The checks apply in evaluated expressions and sizeof. Qualifier-aware pointer compatibility and complete null-constant grammar remain unfinished.
Host simple assignment expressions now check pointer compatibility and null integer constants, rejecting implicit pointer-to-integer assignments except _Bool conversion. Equivalent validation applies inside sizeof. Declaration initializers and parameter/return conversion compatibility still require integration; qualifiers remain incomplete. Kernel source explicitly casts file_content's int-word storage to char source text, preserving existing machine output.
Host return expressions now receive supported assignment-compatible conversion checks: pointer types must be compatible or object/void combinations, integer-to-pointer returns require a recognized null constant, and pointer-to-integer returns require an explicit cast except _Bool. Existing boolean return normalization remains. Argument/initializer compatibility, qualifications and aggregate conversions remain incomplete.
Ordinary host-compiled function calls now enforce assignment-compatible argument conversions: compatible object pointers, object/void pointer conversions, integer constant zero and pointer-to-_Bool are accepted; incompatible pointers and implicit pointer/integer conversions are rejected. Trap intrinsic conversions and declaration initializer constraints still need further work. Kernel word-copy/fill and file-write APIs accept generic data pointers; text uses explicit casts where file buffers are word pointers. The regenerated 36,093-word kernel image is unchanged.
Host scalar declaration initializers now enforce assignment-compatible conversions for automatic variables, global/static objects and individual array elements. Invalid nonzero integer-to-pointer, incompatible pointer, implicit pointer-to-integer and void-value initializers are rejected. Valid object/void pointer conversions, integer constant zero and pointer-to-_Bool conversions remain supported. Trap intrinsic conversion rules, qualifiers and other C constraints remain incomplete. Regenerating the kernel produces the identical binary.
Emitted trap-backed calls now validate argument conversions against the intrinsic ABI: bob_puts/bob_gets require character pointers, bob_snapshot requires an integer descriptor pointer, and capacities, operations, characters and entry addresses require integer arguments. Object/void pointer conversions and integer null constants follow the same rules as ordinary calls. bob_call also rejects implicit pointer entry arguments. Unevaluated call validation and intrinsic declaration consistency still require review. The regenerated kernel binary is unchanged.
Calls examined during expression type analysis now validate parameter counts and assignment-compatible argument types, including inside sizeof. Declaration selection prefers a function definition or a parameter-bearing prototype so an earlier empty parameter list cannot mask known parameters. A sizeof runtime fixture verifies arguments with increments remain unevaluated. Intrinsic declaration consistency, bob_address special cases and complete source-order declaration semantics remain open. The regenerated kernel binary is unchanged.
Host subscript type analysis now rejects void-valued index operands in either order and requires a complete element type for the pointer operand. This also applies to unevaluated address-of/subscript expressions inside sizeof. Reversed indexing and unsigned indexes into multidimensional arrays remain supported. Kernel regeneration produces the identical 36,093-word image.
Nested sizeof expressions now recursively validate their operands while remaining unevaluated. Address-of type checks reject numeric constants, arithmetic results, casts and increment results even inside sizeof. Address generation now supports pointers to complete string-literal arrays (for example char (*p)[5] = &"bob!"). Function pointers, full qualifier rules and several other lvalue constraints remain incomplete.
Static address relocation now supports addresses of whole string-literal arrays, including global and block-static pointer-to-array initializers and scaled constant offsets. Existing string-element address initializers continue to work. This closes the storage-duration gap left by automatic address generation support; other static initializer forms remain incomplete.
Static pointer initializer relocation now handles conditional expressions with constant conditions, including nested selections of object or string addresses. Full conditional type analysis runs before selecting a branch, preserving rejection of incompatible pointer types. Nonconstant conditions remain invalid for static initialization. Null-selected branches use the existing constant initializer path.
Constant folding of numeric guest pointer arithmetic now scales offsets by complete element size, matching runtime arithmetic for pointer-to-array values. Pointer-plus-integer, integer-plus-pointer, pointer-minus-integer and pointer difference use the same word-based guest layout. Numeric address casts and static pointer differences are implementation extensions; this is not a claim of full standard constant-expression support.
Unary code generation now performs expression type validation before emitting instructions, including optimized numeric unary operations. This closes a path that allowed increment/decrement of void lvalues to emit loads/stores even though the type-analysis path rejected them. Array increment remains invalid. Existing unary runtime tests continue to cover valid integer, pointer and Boolean operations.
Static Boolean initializers now convert resolvable object/string addresses to one, including explicit _Bool casts, arrays and block-static objects. Numeric null pointers still convert to zero through constant evaluation. This implements the existing scalar-to-Boolean conversion consistently across automatic and static storage; full standard constant-expression and qualifier constraints remain incomplete.
Relocation emission now validates both code and relocation capacities before writing either array. Literal-address and static-pointer emission share this checked path. Previously the relocation record was inserted before emit checked code capacity; now rejected oversized programs cannot grow relocation state past the emission boundary.
Host literal lexing now grows checked heap storage as needed rather than rejecting strings above 8,190 characters. Character literal temporary storage is freed; string tokens retain their allocated bytes and explicit length, including embedded NULs. Overall source, object and emitted-code limits remain in force. This host change does not enlarge the resident compiler's token or file limits.
Adjacent host string literals now concatenate with one sized allocation and one copy of each piece. The previous repeated-prefix allocations consumed quadratic time and retained quadratic storage for long runs of adjacent literals. Explicit byte lengths still preserve embedded NULs. Length is bounded by the existing source/token limits before parsing.
Array bounds, array designator indexes and explicit enum values now require an integer expression type before constant evaluation. Pointer- and void-valued expressions are rejected in these contexts. Existing integer constant folding and enum/sizeof behavior remain supported; full standard integer-constant-expression grammar restrictions are still incomplete.
Jump bookkeeping now routes all host call and branch jump records through a checked helper before appending to the fixed jump table. This makes the 65,536-entry jump limit explicit and keeps long-control-flow failure paths deterministic. Token and code limits normally trigger first, but the table itself is now guarded.
Generated host labels now stop at an explicit 65,535-label serial limit, preventing signed counter overflow on unusually large generated control flow. The earlier emitted-code cap normally rejects first; this guard keeps the label namespace safe independently.
Switch parsing now rejects case/default labels outside any switch before code generation and bounds nested switch parsing to 64 levels. This closes a validation gap where generation might fail later or skip malformed code. The host OS/compiler suite passes 1,540 checks, including file-scope and function-scope cases; the 256-labels-per-switch and 64-level boundaries remain explicit.
Compile-time integer contexts now share one syntax check: array bounds, enum values, array designators and switch labels reject calls, assignments and increments, while integer operators, casts, conditional expressions and unevaluated sizeof expressions remain accepted. The host OS/compiler suite passes 1,556 checks, and the kernel remains 36,093 words.
Integer constant expression validation now also checks operand types through nested casts and sizeof. Void and pointer expressions cannot be hidden inside an integer cast, unary/binary operation or conditional; regression cases cover sizeof of a void-valued cast in array and enum contexts. All 1,564 OS/compiler checks pass, with the kernel image unchanged.
Explicit enum values now reject unsigned results outside the documented signed 16-bit int range instead of silently wrapping; signed boundary values remain valid. The OS/compiler suite passes 1,568 checks, with the generated kernel unchanged.
Host expression parsing now caps recursive nesting at 256 levels, preventing deeply nested parentheses, unary operators or right-associative expressions from exhausting the host compiler stack. A generated 400-level array-bound fixture checks the diagnostic. All 1,573 OS/compiler checks pass; the 36,093-word kernel image hash is unchanged.
B32 resident expression support now includes the right-associative conditional operator ?:. Code generation branches around the unselected expression, and nesting shares the existing 32-frame parser guard. Runtime coverage checks nested associativity and confirms skipped side effects. Kept B32-only because the bob16 kernel image remains at its 36,093-word size limit. The full suite passes: CPU 179, OS/compiler 1,745, native console 28.
B32 resident control flow now supports do/while loops. Continue chains patch to the trailing condition, while break chains patch after the loop; regression covers first-iteration behavior, continue, break and a zero condition. The bob16 compiler remains unchanged due to the kernel image limit. Full suite: CPU 179, OS/compiler 1,745, console 28.
B32 resident C now parses right-associative simple/compound assignment expressions, preserving the assigned value in the surrounding expression. Added <<= and >>= tokenization and code generation. A B32 shell regression checks chained assignment, assignment under comparison, and both compound shifts; it asserts all nine successful shell programs to avoid false positives from skipped/overlong input. Bob16 image remains 36,093 words. Full suite: CPU 189, OS/compiler 1,746, console 28.
B32 resident C now supports multiple integer functions with stack-based parameters and locals, forward references, nested calls and recursion, including calls used as expression statements. A no-argument output helper, a two-argument helper and recursive factorial exercise the calling convention from the shell. Forward-call patch chains now store relative offsets until the callee definition is known; applying the program base twice previously made the call jump into unmapped memory. The end-to-end workflow checks all nine successful B32 shell programs. Current suite: CPU 189, OS/compiler 1,746, native console 28.
B32 local declarations now follow lexical block scopes, including legal shadowing and for-initializer scope; stack slots remain unique even after a name leaves scope. Regression coverage also found that the expanded B32 kernel overlaps the old `0x9000` legacy-app base. Kind-1 applications now execute at `0xB000..0xBFFF` in the bob32 OS while bob16 remains at `0x9000`; B32 snapshot descriptors may reside up to that boundary. Removing the unnecessary post-run kernel restore preserves the RAM file table. The end-to-end tests cover recursive resident functions, block shadowing, a legacy `LEA/PUTS/HALT` binary, file listing after execution, and snapshot save/restore. Current CPU suite: 189; OS/compiler: 1,746; console: 28.
The resident B32 compiler now rejects a 33rd cumulative local stack slot across lexical scopes. Its LDR/STR frame displacements are signed six-bit fields; silently masking larger negative offsets could bind locals to the wrong frame word. A generated 33-block regression confirms the source is rejected cleanly. The rebuilt B32 kernel is 43,113 words; OS/compiler suite: 1,749 checks passed.
Resident bob32 C now supports fixed-size one-dimensional local `int` arrays within the 32-slot frame budget. Array declarations reserve contiguous slots and zero them; `array[index]` emits a frame-relative load, while indexed assignment statements preserve the computed address across right-hand-side calls. A shell program fills and sums four elements in loops and prints `bob!`. Array initialization, parameter arrays, multidimensional arrays, and bob16 resident array support remain open. The regenerated B32 kernel is 44,250 words, ending 70 words below the then-current `0xB000` legacy-app boundary; OS/compiler suite: 1,752 checks passed.
To preserve space for further C support, the B32 legacy kind-1 region now starts at `0xB800` and reserves 2,048 words through `0xBFFF`; the largest RAM-file app is 511 words. The emulator, kernel loader, snapshot descriptor boundary, CPU regression and user-facing maps were updated together. The current 44,250-word kernel ends at `0xAFBA`, 2,118 words below the new window. CPU boundary fixtures verify writes at `0xB800` and rejection below it. Full suites: CPU 191, OS/compiler 1,752, console 28.
Supervised-store review found a range hole: native apps faulted in 0x100000..0x10FFFF but could write again at 0x110000 and above. Store validation now uses the documented half-open application range and denies all other addresses. CPU regressions cover the last valid word, both sides of the boundary, arbitrary high sparse memory and UINT32_MAX. Full suite: CPU 185, OS/compiler 1,746, console 28.
B32 external application loading now reserves every missing sparse page before installing pages or copying image words. Sparse-page allocation failure returns the loader error without exiting the emulator or modifying the target region. A BOB_TESTING-only allocator fault regression verifies the failure path. The full suite passes: CPU 186, OS/compiler 1,746, console 28.
Guest trap-6 audit found that a nested run attempt returned the intended -1 but then reset the outer B32 application's mode flag, causing later valid stores to fault. Nested calls now return before touching that flag. A CPU regression verifies the app continues, writes within high memory and exits. The full suite passes: CPU 187, OS/compiler 1,746, console 28.
Resident bob32 array statements now support indexed postfix increment/decrement and all compound assignments, including shifts implemented through helper calls. The regression fills an array, applies `++`, `+=` and `<<=`, then checks the summed result; indexed addresses remain protected across RHS evaluation and helper calls. The 44,833-word kernel ends at `0xB221`, leaving 1,503 words before the `0xB800` app boundary. Full suites: CPU 191, OS/compiler 1,752, console 28.
Resident bob32 fixed-size local arrays now accept scalar brace initializers with an optional trailing comma. The compiler retains zero-filled omitted elements and rejects excess elements; an end-to-end program verifies initialized values and zero padding before performing array updates, and a negative program verifies excess-element rejection. B32 kernel: 45,070 words, ending at `0xB30E` with 1,266 words before the `0xB800` legacy window. OS/compiler suite: 1,753 checks passed.
Resident bob32 array prefix/postfix increment and decrement now compose with expressions: postfix returns the old element after storing the updated value, and prefix returns the updated value. A separate end-to-end app checks both semantics while staying within the 511-word file cap. The kernel is 45,299 words, ending at `0xB3F3` with 1,037 words before the legacy window. OS/compiler suite: 1,754 checks passed.
Resident bob32 local declarations now accept comma-separated scalar and fixed-array declarators with per-declarator initializers. This includes declarations that initialize a scalar from an array postfix expression. The updated 45,331-word kernel ends at `0xB413`, leaving 1,005 words before the legacy window. OS/compiler suite: 1,754 checks passed.
Resident bob32 now parses integer function prototypes with optional parameter names. Prototypes set/check call arity, may precede a later definition, and may remain unused without definitions; unresolved calls and conflicting signatures fail. Runtime coverage checks a prototype-declared forward function call, unused unnamed-parameter declaration and conflicting prototypes. The 45,486-word kernel ends at `0xB4AE`, with 850 words before the `0xB800` legacy window. OS/compiler suite: 1,758 checks passed.
Resident bob32 prototypes now distinguish `int f()` from `int f(void)`. An empty parameter list keeps unspecified status and can be refined by a typed declaration or definition; calls made through it must match the eventual definition's arity to preserve the current stack ABI. End-to-end coverage verifies the valid and mismatched cases. The regenerated B32 kernel is 48,185 words and ends at `0xBF38`, leaving 199 words before the compatibility-app region. CPU 194, OS/compiler 1,764, and console 28 checks pass.
## Recent bob32 and header additions
The bob32 resident compiler now recognizes `print`, `println`, `print_dec` and `print_hex` as one-argument kernel built-ins without source prototypes. A regression runs `write bobs.c int main(void){println("Bob!");return 0;}` followed by `go bobs.c` and verifies the exact `Bob!` output and exit 0. The kernel grew into the old bob32 compatibility-app range, so that range now begins at `0xC200`; the emulator checks its entry and write bounds, and memory-map documentation reflects the relocation. Current B32 image: 48,645 words, ending at `0xC164`.
Added the standard `<stdbool.h>` header for the host-compiled C workflow, mapping `bool`, `true` and `false` to the existing `_Bool` implementation. B16 and B32 runtime fixtures verify true/false conversion and print `bob!`. Static analysis with GCC `-fanalyzer` reported no diagnostics for the emulator, host compiler or test harness. Full suite at that point: CPU 194, OS/compiler 1,769, console 28.
Added `<stddef.h>` with target-width `size_t` and `ptrdiff_t` plus `NULL`. Corrected `sizeof` expressions and type-name forms to have unsigned `size_t` type, so arithmetic such as `sizeof(int)-2` follows unsigned conversion rules. B16 and B32 runtime tests check array sizes, pointer differences, null pointers and unsigned wraparound. Full suite: CPU 194, OS/compiler 1,773, console 28.
The host compiler now parses typed function-pointer declarators, including nested pointer parameters, and type-checks their assignments and calls. Function designators and `&function` relocate to code labels; local/global pointer objects and indirect calls use the B16/B32 call ABI. Calls through an empty `()` signature use unspecified argument checking, while calls through prototypes enforce arity and compatible parameter types. Regression apps cover global initialization, local assignment/copy, direct and parenthesized indirect calls, nested function-pointer parameters, and the unspecified form on both targets; negative cases cover signature, arity, object/function pointer mismatches, and invalid object/function pointer casts. Function-pointer return types remain unsupported. Full suite at that stage: CPU 194, OS/compiler 1,793, console 28.
Resident bob32 syntax diagnostics now include the current token text with the existing character offset and line/column. The source regression checks token context. The packed native application workflow and current verification totals are recorded in `tests/AUDIT.md` and `BOB32_MIGRATION.md`.
The bob32 resident compiler now emits into the native app staging region and saves generated programs against the remaining 4,096-word packed filesystem capacity; bob16 keeps its 511-word output limit. A short resident C source generates a 1,289-word app, prints `bob!`, survives a B32S snapshot and restore, then runs again from guest storage. Full suites: CPU 203, OS/compiler 1,822, console 28.
The bob32 resident compiler now accepts one-dimensional array parameters, adjusting them to pointer-valued stack arguments. It derives addresses for local array arguments, loads and indexes parameter pointers in the callee, and preserves mutation visibility through the caller's array. Prototype/definition signatures retain array-versus-scalar parameter shape, and calls reject known mismatches. Tests cover `sum(values,length)`, indexed iteration, mutation, a nested forwarding call, repeated helper calls, conflicting/multidimensional declarations, and existing local-array behavior. Full suites: CPU 203, OS/compiler 1,825, console 28.
Started the app-side standard library with `kernel/bob_string.h`: basic string operations, whitespace detection, overflow-checked signed decimal/hex parsing, bounded integer formatting and quote-aware in-place tokenization. Runtime tests exercise edge cases in bob32, and a compiled app using the header is imported, launched, snapshotted, restored and run again from the bob32 filesystem. Full suites: CPU 203, OS/compiler 1,840, console 28.
+203 -26
View File
@@ -12,9 +12,55 @@ The supplied emulator has been rebuilt for the new kernel services; older
executables lack the character-input and supervised-program traps.
Alternatively run `bob.exe --boot build/kernel.b16` from the repository root.
To build and boot the native 32-bit kernel, close the current emulator session
and run `build.exe --run32`. The build also creates `build/kernel32.b32`, which
can be started directly with `bob32.exe --boot build/kernel32.b32`. The native
kernel supports the shell, RAM files, editor, resident C compiler, supervised
bob16 applications and B32S snapshots. In B32 mode, `cc` and `go` compile the
resident C subset to native bob32 programs with 32-bit `int`; kind-1 bob16 apps
still run with 16-bit arithmetic compatibility. The host `bobcc --wide` option
also emits native bob32 application images for direct boot.
The host compiler also emits a runnable bob32 BASM listing; start it with
`bob32.exe --asm32 build/program.basm`.
To build a native bob32 application for the running bob32 OS, preprocess the C
source and compile it with `--wide-app`:
```text
gcc -E -P -nostdinc -undef -I kernel app.c -o build/app.i
build/bobcc build/app.i build/app.basm build/app.b32 --wide-app
```
Then start the B32 OS with `build.exe --run32` and enter `run32 build/app.b32`.
The application uses the supervised high-memory region and its own 32-bit
stack. `run32` validates the B32K v2 header, range, checksum and file length
before loading it. The image limit is 65,536 words. Apps load from the emulator
host's working directory and are not stored in the guest snapshot. To keep an
image in the guest filesystem, use `import32 build/app.b32 myapp`, then launch
it with `run myapp`. `save` includes imported applications in the B32S snapshot;
after `restore yes`, run them again without re-importing. `run32` remains
available for direct host-path launches.
Set `BOB16_TRACE_FAULT=1` before launching the emulator to log the address and
instruction when a supervised application faults.
The updated emulator also accepts `bob.exe --os` from that directory to boot
the supplied image directly. The welcome message points to `help` and `go bob.c`.
## Small application string library
Native C applications may include `bob_string.h` along with `bob.h`. The string
header supplies word-addressed `bob_strlen`, `bob_strcpy`, `bob_strcmp`,
`bob_strcat`, and `bob_strchr`, plus `bob_isspace`, `bob_parse_int`,
`bob_format_int`, and `bob_token_next`. It is included in the app translation
unit, so the compiler emits only helpers reachable from that app; no separate
library link step is needed. The caller provides enough space for copy/append
destinations. `bob_parse_int` accepts signed decimal or `0x` hexadecimal with
surrounding whitespace and reports validity through its second argument.
`bob_format_int` returns the character count or -1 when the output buffer is
too small. `bob_token_next` edits a writable command buffer in place, groups
single- or double-quoted text, honors backslash escapes, and returns 1 for a
token, 0 at end, or -1 for an unclosed quote.
## Commands
| Command | Behavior |
@@ -24,7 +70,7 @@ the supplied image directly. The welcome message points to `help` and `go bob.c`
| `clear` | Clear an ANSI-capable terminal |
| `mem` | Show heap usage and memory regions |
| `peek 0xC000` | Read a word |
| `poke 0xC000 98` | Write a word in heap RAM only |
| `poke 0xC000 98` | Write a word in the heap (bob16 mode) |
| `alloc 32` | Allocate and zero 32 words; print their address |
| `list` | List RAM files, lengths and kinds |
| `ls` / `dir` | Aliases for list, with the same RAM-file view |
@@ -42,6 +88,8 @@ the supplied image directly. The welcome message points to `help` and `go bob.c`
| `restore yes` | Validate/load that snapshot, replacing the RAM files |
| `load name 0x4001 ...` | Store raw bob16 machine words as a program file |
| `run name` | Load a binary program into reserved RAM, execute, return |
| `run32 path` | Load and run a native B32K v2 image from a host path or guest filename |
| `import32 path name` | Import a host B32K v2 image into bob32 RAM files |
| `halt` | Stop the emulator |
Command lines hold up to 127 characters. Longer lines are completely consumed
@@ -71,9 +119,12 @@ Windows console. Redirected input emits no
redraw or candidate lists. Other terminals use ordinary input; full interactive
key handling currently targets the native Windows console.
The RAM filesystem has eight slots, names up to 23 characters and content up
to 511 words per file. A character occupies one word. `bob.c` occupies one slot
initially. Unsaved files and allocations are lost on exit. Use `save` to retain
The RAM filesystem has eight slots and names up to 23 characters. bob16 keeps
eight fixed 511-word slots. bob32 packs files into 4,096 words total; text and
resident programs remain limited to 511 words, while native apps use six
metadata words plus payload and a terminator, sharing space with other files.
A character occupies one word. `bob.c` occupies one slot initially. Unsaved
files and allocations are lost on exit. Use `save` to retain
files between sessions. Allocation is a zeroing bump allocator with no freeing. `poke` is
restricted to heap RAM so it cannot corrupt the shell.
@@ -207,36 +258,95 @@ int main(void) {
Enter `.` on its own line, followed by `cc count.c count` and `run count`.
The resident compiler supports one `int main(void)` or `int main()` function,
up to 16 integer variables, assignments and compound assignments, decimal/hex/
character/string literals, parentheses, unary `+ - ! ~`, prefix/postfix increment
The resident compiler supports one zero-argument `int main(void)` plus up to
15 additional `int` functions with integer parameters. Calls may be forward,
nested or recursive, and may be used as expression statements; each function
gets its own parameter/local stack frame.
The compiler supports up to 16 functions, 16 parameters per function and 16
simultaneously visible local/parameter names. B32 stack frames can reserve up
to 32 local slots across nested scopes; a further declaration is rejected
because frame loads/stores use signed six-bit offsets. It also supports
assignments and compound
assignments, decimal/hex/character/string literals, parentheses, unary `+ - ! ~`, prefix/postfix increment
and decrement, arithmetic, bitwise operators, shifts, short-circuit `&&`/`||`,
comparisons with C operator precedence, blocks, `if`/`else`, `while`, `for`,
`break`, `continue`, and `return`. For-loop initialization can declare an int;
its increment can assign, compound-assign or increment/decrement a variable.
It supports `print`, `println`, `print_dec`, `print_hex`
and `bob_putc` calls with one argument, comments and common string escapes.
Variables have a flat function scope; declare names once (including for-loop
variables). Compound assignments support `+= -= *= /= %= &= |= ^=`; shift
assignments and assignments inside expressions are unsupported. Strings hold up to
Variables follow block scope, including declarations in `for` initializers;
inner blocks may shadow outer names, while duplicate names in one block are
rejected. Compound assignments support `+= -= *= /= %= &= |= ^=`; shift
assignments and assignments inside expressions are unsupported in bob16. Strings hold up to
63 characters and nesting is bounded at 32 parser frames. Both source and
output must fit RAM-file limits. Invalid or unsupported syntax reports an error
without replacing the output file.
The bob32 resident compiler additionally supports C's right-associative `?:`
conditional expression, including evaluation of only the selected branch. This
operator is not enabled in bob16 because its kernel image is at the address
limit; bob16's compiler behavior is unchanged. B32 resident C also supports
`do/while`, including `break` and `continue` (which proceeds to the condition),
assignment expressions (including right-associative chains), and `<<=`/`>>=`.
Both resident compilers provide `print`, `println`, `print_dec`, and `print_hex`
as one-argument built-ins; bob32 source can call them without a prior prototype.
This is a small C subset, not a complete C implementation. Resident includes,
macros, arrays, pointers, additional functions, structs, floating point
and a standard library are unsupported. Programs call the current kernel's
macros, pointers, globals, structs, floating point and a standard library are
unsupported. The bob32 resident compiler supports `int` function prototypes
with integer parameters (prototype parameter names are optional); incompatible
parameter counts are rejected, and a referenced function still needs a
definition. Empty `f()` declarations retain unspecified-parameter status and
may be followed by a typed declaration or definition; calls made through that
declaration must match the eventual definition's arity. bob16 resident
prototypes remain unsupported. The bob32 resident
compiler supports fixed-size,
one-dimensional local `int` arrays with indexed reads and assignment statements;
their elements use the function's 32-word stack-slot budget. Indexed prefix and
postfix increment/decrement work in expressions; indexed compound assignments
work in statements.
Brace initializer lists accept scalar expressions and a trailing comma; omitted
elements are zero-filled and excess elements are rejected. The bob32 resident
compiler accepts one-dimensional `int` array parameters as `values[]` or with a
fixed bound, passing the word-addressed pointer through the ordinary argument
stack. Helpers can index or modify the caller's elements and forward the array
to another helper. Nested/multidimensional arrays and bob16 resident array
parameters remain unsupported.
Local `int` declarations may contain comma-separated scalar and fixed-array
declarators, each with its own initializer.
The bob32 resident compiler also supports local pointers to integer-returning
functions with integer parameters. Initialize or assign one from a previously
declared matching function, copy it to a compatible local pointer, or assign
null (`0`), then call indirectly. Mismatched signatures and integer values are
rejected. Function-pointer parameters, returns, globals, pointer arithmetic
and bob16 resident function pointers remain unsupported.
Programs call the current kernel's
console/arithmetic routines and belong to the kernel build that compiled them.
In bob32 mode the same syntax emits native 32-bit instructions and kind-2 RAM
program files, which can be run with `run` and retained in B32S snapshots. B32
resident programs start at `0x20000` and use variables at `0xF0000..0xF000F`;
their output can use the remaining shared 4,096-word filesystem space. Source
text files remain limited to 511 words. In bob16 mode files remain kind 1 and
use 16-bit integers and the `0xA000` program region. The bob32 shell also runs
kind-1 legacy programs at `0xC200`, clear of the expanded kernel image.
## Native programs and recovery
`run` clears the program region and copies in the binary RAM file at `0x9000`.
`run` clears the program region and copies in the binary RAM file at `0xA000`
in bob16 mode or `0xC200` in bob32 mode.
`RET` (`0xE000`) returns to the shell with r0 as the exit status. `TRAP 0` also
ends the running program without ending the shell. The emulator saves/restores
the shell's CPU state, supplies a separate program stack, stops execution after
five million cycles, and rejects writes outside `0x9000..0xDFFF`. Invalid
five million cycles, and rejects writes outside the legacy app/heap range
(`0xA000..0xDFFF` in bob16, `0xC200..0xDFFF` for bob32 compatibility apps).
Native bob32 apps write only their supervised application and stack region.
Invalid
instructions and forbidden services return a program fault.
In bob32 mode `run` also accepts resident kind-2 programs, loading them at
`0x20000` with 32-bit arithmetic. Their compiler variables occupy
`0xF0000..0xF000F`; the host `run32 PATH` command remains available for larger
external B32K images.
Programs can write their program region and the shared heap. This is not process
isolation, and input services can wait for input. The raw `load` command accepts
what fits in a single command line; use the resident compiler for larger programs.
@@ -254,13 +364,16 @@ what fits in a single command line; use the resident compiler for larger program
| --- | --- |
| `0x0000..0x00FF` | Boot ROM and reserved return sentinel |
| `0x0100..0x01FF` | Shell and fallback editor input buffers |
| `0x0300..0x8FFF` | Kernel code, globals and strings |
| `0x9000..0xBFFF` | Loaded program, variables and downward program stack |
| `0xC000..0xDFFF` | 8,192-word heap |
| `0xE000..0xE3FF` | Shared editor/compiler scratch (never used concurrently) |
| `0xE400..0xE5FF` | Four-command shell history |
| `0xE600..0xEFFF` | Kernel stack, growing down from `0xF000` |
| `0xF000..0xFFFF` | Eight file-content buffers; protected from program writes |
| `0x0300..0x9FFF` | Kernel code, globals and strings in bob16; current image ends at `0x90E4` |
| `0xA000..0xBFFF` | Loaded program, variables and downward program stack in bob16 |
| `0x0300..0x9FFF` | bob32 low-memory shell data and compatibility space |
| `0xA000..0xCFFF` | Loaded bob16 compatibility program at `0xC200..0xCFFF` |
| `0xD000..0xDFFF` | bob32 heap and compatibility stack region |
| `0xE000..0xEFFF` | Editor/compiler scratch, history and shell stack |
| `0xF000..0xFFFF` | Packed bob32 RAM filesystem contents |
| `0x10000..0x1FFFF` | Native bob32 kernel code, globals and strings |
| `0x20000..0xEFFFF` | Supervised native bob32 program entry/code region |
| `0xF0000..0xFFFFF` | Native app data and compiler variables; stack starts at `0x100000` |
There are no interrupts, multitasking or hardware memory protection. The write
checks and cycle limits are emulator services. Keep kernel recursion within its
@@ -284,9 +397,11 @@ it does not preserve the volatile RAM files from a previous session.
./build.exe --test
```
The C build utility detects MSYS2 GCC on Windows. It builds `bob.exe` and
`build/bobcc.exe`, preprocesses guest C with GCC, and generates `kernel.basm`,
`build/kernel.b16` and `build/kernel.map`. `./build.exe --run` builds and boots.
The C build utility detects MSYS2 GCC on Windows. It builds `bob.exe`,
`bob32.exe` and `build/bobcc.exe`, preprocesses guest C with GCC, and generates
both `kernel.basm`/`build/kernel.b16` and `build/kernel32.basm`/
`build/kernel32.b32`. `./build.exe --run` boots bob16; `./build.exe --run32`
boots bob32.
On Linux/macOS compile the utility as `build-tool`, then run `./build-tool`.
GCC builds host executables and preprocesses guest C only; `tools/bobcc.c` does
@@ -294,6 +409,7 @@ the bob16 code generation. The host compiler supports a broader subset:
signed ints/chars, word pointers and casts, fixed arrays, constant global
initialization, functions and recursion, assignments/compound assignments,
arithmetic/bitwise/shift operators, short-circuit logic, comparisons,
including all arithmetic/bitwise compound assignments and `<<=`/`>>=`,
increment/decrement, if, while, do/while, for, break, continue, function-scoped
labels/goto and returns. Blocks permit shadowing; for-loop declarations have
loop scope. Duplicate declarations in the same scope are rejected.
@@ -312,6 +428,12 @@ adjust to pointers to their element or row type; the outer bound may be omitted.
Unused prototypes need no definition. Pointer descriptors distinguish current
pointee kinds and indirection depth in prototype checks. Qualifier compatibility,
complete expression checking and linking external definitions remain incomplete.
Repeated function declarations merge compatible incomplete/complete array bounds
through pointer types; differing known bounds, element types or depths reject.
Compound assignments validate pointer offsets and integer operands, including
within sizeof. Assignment/increment operands in sizeof must be modifiable scalar
lvalues; their side effects remain unevaluated. Const enforcement and full
assignment conversion checks remain incomplete.
Multidimensional arrays support indexing, row pointers, scaled pointer arithmetic,
increments and pointer differences. Objects are limited to 4096 words and 16
dimensions. Global/local initializer lists accept nested braces and brace
@@ -329,8 +451,28 @@ embedded zero characters, including their contribution to sizeof.
Conditional `?:` and comma expressions preserve branch/sequence behavior.
`sizeof` handles the current word-sized scalar/pointer types, declared arrays
and string literals without evaluating its operand; void operands are rejected.
Structs, typedefs, unsigned types, floating point, function pointers,
Variadics and standard headers are unsupported. `sizeof` tracks array/pointer
Typedef declarations support current scalar, pointer and array types at file and
block scope. Aliases work in parameters, casts, sizeof and further declarations;
void aliases can specify a no-argument function. Compatible identical typedef
redeclarations are accepted; namespace conflicts reject. Inner objects or aliases
can shadow an outer alias, which is restored when the inner scope ends.
Structs, short integer types and floating point remain unsupported. The host
compiler accepts typed function pointers in local and file-scope objects,
function-pointer parameters, address-of function designators and indirect calls
on both targets. Function-pointer/object-pointer conversions and mismatched
signatures are rejected. Returning function pointers and variadic function
pointers are unsupported. The host compiler's bob32 `--wide` target accepts `long` and
`long long` as 32-bit aliases of `int`, consistent with the word-addressed ABI;
`sizeof` reports addressable words (one byte per word). Enums support tagged/anonymous definitions, explicit constant
values, automatic increments, typedef aliases and block/loop tag shadowing.
Enumerators are scoped integer constants usable in bounds, case labels and
initializers. Enum objects use signed 16-bit int storage; distinct enum types
remain distinct in declaration checks and are compatible with this chosen int
representation. Automatic values exceeding 32767 reject. Enum tags must already
be defined when referenced; incomplete enum extensions are unsupported.
Variadics and most standard headers are unsupported; the host C workflow provides
`<stdbool.h>` and `<stddef.h>` with `_Bool`, `size_t`, `ptrdiff_t` and `NULL`.
`sizeof` has the unsigned `size_t` type and tracks array/pointer
expression types, including *&array and array decay in comma/conditional
expressions. Recursive object declarators support grouped names, pointers to
arrays such as `int (*rows)[3]`, and arrays of those pointers. Abstract declarators
@@ -340,6 +482,41 @@ pointee has no size for sizeof or arithmetic. Declarators have limits of 32
parenthesis levels and 64 derived types. Function pointer declarators, functions
returning pointers to arrays, and complete C type checking remain unsupported.
Host tools themselves use ordinary host C types.
The host compiler supports `_Bool` as a one-word type. Initializers, assignment,
casts, returns and arguments to boolean parameters convert zero to 0 and nonzero
to 1. Boolean arrays, typedef aliases and static objects use the same conversion;
increment/decrement and compound assignments preserve normalized storage. The
host workflow includes `<stdbool.h>` with `bool`, `true` and `false` definitions.
Unsigned 16-bit int is available as `unsigned` or `unsigned int`, with `u`/`U`
literal suffixes. Mixed int/unsigned arithmetic uses unsigned comparisons,
division and remainder; right shifts of unsigned values fill with zeros.
Arithmetic storage wraps modulo 65536. Unsigned helpers are included only when
explicit unsigned types/literals are used. Unsuffixed literal selection retains
the earlier compiler behavior; full C literal selection, unsigned char/short/long
and all declaration-specifier orderings remain incomplete.
Sizeof is accepted in constant initialization; local static initializers may
query automatic-object types without evaluating their values. Type/literal sizeof
works in bounds and case labels. Named-object sizeof in those contexts uses
parser type bindings with block/for scope and parameter array adjustment.
Objects must already be declared and complete; later or escaped bindings reject.
File-scope object declarations support `extern`, compatible repeated tentative
definitions and a single initialized definition. Incomplete array declarations
merge with known bounds; an uncompleted tentative array reserves one element.
Unused extern objects need no definition, while referenced ones must be defined
in this source unit. Block-scope extern object declarations refer to that same
storage without allocating stack slots. They can shadow an outer local, and
names introduced only in a block do not escape it. Block extern initializers
and conflicts with a local in the same scope reject. Block function declarations,
separate-unit linking remain unsupported. File-scope static objects/functions
use internal linkage within the current source unit. Later extern declarations
inherit prior internal linkage; conflicting external/internal declarations
reject. Function declarations without a storage class retain an earlier static
declaration's linkage. Internal tentative arrays need a complete bound.
Block-scope static objects have private persistent storage initialized once,
including arrays and pointers to other static objects. Initializers must use
supported constant expressions or static addresses; automatic-object addresses
and runtime calls are rejected. Equal names in different blocks/functions remain
independent, and a static object's name is scoped to its declaring block.
To compile another standalone guest source from the repository root:
+9
View File
@@ -100,3 +100,12 @@ condition codes are set after instructions with *, so if the result of an instru
negative -> n bit is set\
zero -> z bit is set\
positive -> p bit is set
# bob32 migration status
`bob32.exe` supports 32-bit words and addresses, including high-origin B32K v2
images. `build.exe --run32` builds and boots the B32 kernel, with its shell,
editor, filesystem, B32S snapshots, and compatibility for supervised bob16
applications. Native B32K apps can be imported into guest RAM files with
`import32`, launched by guest filename, and preserved in B32S snapshots. The
resident C compiler and full C conformance remain in progress. See [BOB32_MIGRATION.md](BOB32_MIGRATION.md) for image
details, verified behavior and remaining migration requirements.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
+4616 -2713
View File
File diff suppressed because it is too large. Load diff
+47 -20
View File
@@ -40,7 +40,9 @@ The kernel-only `bob_snapshot(int *descriptor, int operation)` is trap 7.
Operation 0 saves; 1 restores. The four-word descriptor contains pointers to
the 192-word names table, then eight-word length, kind and used tables. File
contents occupy the fixed `0xF000..0xFFFF` region. Descriptors can be on the
kernel stack; tables must be disjoint and below `0x9000`. The host validates
kernel stack; tables must be disjoint and below `0xA000` in bob16 mode. In
bob32 mode they may be in low kernel RAM or in the loaded kernel image, which
now resides above `0x10000`. The host validates
metadata, payload checksum and complete file length before committing a restore.
Returns 0 on success, 1 when restored binaries were omitted because the kernel
changed, -1 for storage errors, -2 for invalid data and -3 for invalid arguments.
@@ -52,14 +54,16 @@ user-facing save/restore workflow.
| --- | --- |
| `int strlen(char *text)` | Count words before the zero terminator |
| `int strcmp(char *a, char *b)` | Negative, zero or positive according to the first differing ASCII character |
| `void memcpy(int *dst, int *src, int count)` | Copy count words forward; source and destination must not overlap |
| `void memset(int *dst, int value, int count)` | Fill count words with a 16-bit value |
| `void memcpy(void *dst, void *src, int count)` | Copy count words forward; source and destination must not overlap |
| `void memset(void *dst, int value, int count)` | Fill count words with a 16-bit value |
| `int *alloc(int words)` | Return a zeroed heap block, or null for an invalid size or exhaustion |
String routines require terminated strings. Memory routines require valid
regions; they do not perform bounds checks for kernel callers. Counts are words,
not host bytes. Allocation reserves from 0xC000 upward, with 8,192 total words.
The heap is shared with loaded programs. There is no free or reset operation.
not host bytes. The bob16 heap reserves 8,192 words from 0xC000; bob32 reserves
4,096 words from 0xD000 so the enlarged kernel and compatibility-program stack
fit below it. The heap is shared with loaded programs. There is no free or reset
operation.
## RAM filesystem
@@ -67,9 +71,13 @@ The heap is shared with loaded programs. There is no free or reset operation.
`file_content(slot)` return addresses into the filesystem buffers.
`file_write(name, data, length, kind)` copies data and creates/replaces a file,
returning its slot or -1 for a bad name, length or a full table. Kind 0 is text;
kind 1 is machine code. Its copy appends a zero word, which is not part of length.
Names hold at most 23 characters and data at most 511 words. Valid slot indices
are 0..7. These routines are internal kernel APIs; callers must check slots.
kind 1 is machine code, kind 2 is resident bob32 C code, and kind 3 is a packed
native B32K v2 image. Its copy appends a zero word, which is not part of length.
Names hold at most 23 characters. bob16 retains eight fixed 511-word slots;
bob32 packs files into a shared 4,096-word content region. Text files remain
limited to 511 words; resident programs and native images can use the remaining
shared capacity (up to 4,095 words per file). Valid slot indices are 0..7.
These are internal kernel APIs.
Failed size/name validation does not overwrite an existing file. Edits start
with the existing file contents in a scratch buffer and commit on :w, :wq or a
@@ -89,27 +97,46 @@ kernel stack reserved at `0xE600..0xEFFF`. Input buffers are `0x0100..0x01FF`.
## Program execution
`bob_run(entry)` invokes emulator trap 6. Valid entries are 0x9000..0xBDFF.
The shell's run_file copies a binary RAM file to 0x9000 after clearing the
12,288-word program region. Entry 0x9000 executes with r6=0xC000, r5=0, and
r7 pointing to the reserved return sentinel. The shell CPU state is restored
on completion. RET or TRAP 0 ends the program.
`bob_run(entry)` invokes emulator trap 6. In bob16 mode valid entries are
0xA000..0xBDFF. In bob32 mode kind-1 legacy entries are 0xC200..0xCFFF and
kind-2 native entries are 0x20000..0xEFFFF when the caller explicitly supplies
a wide entry. The shell places legacy programs at 0xC200 in bob32 mode to avoid
overwriting the bob32 kernel image, and native bob32 files at 0x20000. The entry executes
with r6 at the top of its protected stack region, r5=0, and r7 pointing to the
reserved return sentinel. In bob32 mode kind-1 apps use `0xC200..0xCFFF` because
the expanded kernel occupies the old bob16 program window. Compatibility apps
retain access to the shared `0xD000..0xDFFF` heap. The shell CPU state is
restored on completion. RET or TRAP 0 ends the program.
Return values -1, -2 and -3 are reserved for invalid entry/nested execution,
program fault, and timeout. Otherwise r0 is the program's exit status. A program
returning one of those reserved values is indistinguishable from that service
status. Five million cycles is the per-run limit. Programs may write only
0x9000..0xDFFF; kernel code, RAM files and the shell stack are protected from
their stores. Program and heap contents themselves are not private or restored.
their application and stack regions; bob16 and compatibility applications may
also write the shared heap. Kernel code, RAM files and the shell stack
are protected from their stores. Program and heap contents themselves are not
private or restored.
The resident compiler uses variable words at 0x9800..0x980F and inline string
data in its program image. Its files can contain at most 511 code/data words,
so these variable words do not overlap its code. Its console/helper calls use
the separate program stack. Compiled resident programs depend on addresses in
the current kernel and should not be reused with a different kernel build.
The resident compiler uses variable words at 0x9800..0x980F in bob16 mode and
0xF0000..0xF000F in bob32 mode; string data is inline in the program image.
In bob16 its files can contain at most 511 code/data words; bob32 compiler output
uses the available packed filesystem capacity. Console and arithmetic calls
use the separate program stack. Compiled resident programs depend on addresses
in the current kernel and should not be reused with a different kernel build.
`bob_address(function_name)` is a host-compiler intrinsic that inserts a kernel
function address. `bob_call(entry)` is an unchecked direct call for trusted
kernel code; ordinary shell programs use bob_run for recovery and write checks.
See [the OS guide](../C_OS.md) for commands, examples and C subset limits.
In bob32 mode, `import32 HOST_PATH NAME` validates and packs a B32K v2 image
into a guest RAM file; `run NAME` loads and executes it. B32S version 2
snapshots preserve packed files; version 1 fixed-slot snapshots remain readable
and are converted to the packed layout on restore. `run32 HOST_PATH` remains
available for direct host-path launches.
Native C applications can include `bob_string.h` for small app-side string
and parsing helpers. It provides bounded integer formatting, status-returning
decimal/hex parsing, and in-place quoted tokenization without depending on the
kernel's private runtime functions.
+4 -1
View File
@@ -2,11 +2,14 @@
#define BOB_KERNEL_H
/* Guest services. bob16 int, char and pointers occupy one 16-bit word. */
void bob_putc(int character);
void bob_puts(char *text);
void bob_puts(const char *text);
void bob_gets(char *buffer, int capacity);
void bob_halt(void);
int bob_getc(void);
int bob_run(int entry);
int bob_run_image(const char *path);
int bob_import_image(int *descriptor);
int bob_run_native(const int *descriptor);
int bob_snapshot(int *descriptor, int operation);
int bob_key(void);
int bob_terminal(void);
+125
View File
@@ -0,0 +1,125 @@
#ifndef BOB_STRING_H
#define BOB_STRING_H
/* Small word-addressed string helpers for native bob applications. */
int bob_strlen(const char *text) {
int length; length = 0;
while (text[length]) length++;
return length;
}
char *bob_strcpy(char *destination, const char *source) {
int i; i = 0;
while (source[i]) { destination[i] = source[i]; i++; }
destination[i] = 0;
return destination;
}
int bob_strcmp(const char *left, const char *right) {
int i; i = 0;
while (left[i] && left[i] == right[i]) i++;
return left[i] - right[i];
}
char *bob_strcat(char *destination, const char *source) {
int i; int j;
i = bob_strlen(destination); j = 0;
while (source[j]) destination[i++] = source[j++];
destination[i] = 0;
return destination;
}
char *bob_strchr(const char *text, int character) {
while (*text && *text != character) text++;
if (*text == character) return (char *)text;
return 0;
}
int bob_isspace(int character) {
return character == ' ' || character == '\t' || character == '\n' ||
character == '\r' || character == '\v' || character == '\f';
}
/* Decimal and 0x-prefixed signed integers. valid is cleared on any error. */
int bob_parse_int(const char *text, int *valid) {
int negative; int base; int digit; int digits;
unsigned int value; unsigned int limit; unsigned int radix;
const char *cursor;
*valid = 0; cursor = text; negative = 0; base = 10; digits = 0; value = 0;
while (bob_isspace(*cursor)) cursor++;
if (*cursor == '+' || *cursor == '-') {
negative = *cursor == '-'; cursor++;
}
if (cursor[0] == '0' && (cursor[1] == 'x' || cursor[1] == 'X')) {
base = 16; cursor += 2;
}
radix = (unsigned int)base;
limit = negative ? 0x80000000U : 0x7fffffffU;
while (*cursor) {
if (bob_isspace(*cursor)) break;
digit = *cursor;
if (digit >= '0' && digit <= '9') digit -= '0';
else if (digit >= 'a' && digit <= 'f') digit = digit - 'a' + 10;
else if (digit >= 'A' && digit <= 'F') digit = digit - 'A' + 10;
else return 0;
if (digit >= base || value > limit / radix ||
(value == limit / radix && (unsigned int)digit > limit % radix)) return 0;
value = value * radix + (unsigned int)digit;
digits++; cursor++;
}
while (bob_isspace(*cursor)) cursor++;
if (!digits || *cursor) return 0;
*valid = 1;
if (!negative) return (int)value;
if (value == 0x80000000U) return -2147483647 - 1;
return -(int)value;
}
/* Returns the character count, or -1 when the destination is too small. */
int bob_format_int(int value, char *destination, int capacity) {
char reverse[11];
unsigned int magnitude; int negative; int count; int i;
if (capacity < 1) return -1;
negative = value < 0;
magnitude = negative ? 0U - (unsigned int)value : (unsigned int)value;
count = 0;
do {
reverse[count++] = (char)('0' + magnitude % 10U);
magnitude /= 10U;
} while (magnitude);
if (count + negative + 1 > capacity) return -1;
i = 0;
if (negative) destination[i++] = '-';
while (count) destination[i++] = reverse[--count];
destination[i] = 0;
return i;
}
/* In-place shell-like token reader: whitespace separates, quotes group, and
backslash quotes the next character. Returns 1/token, 0/end, or -1/bad quote. */
int bob_token_next(char **cursor, char **token) {
char *scan; char *write; int quote; int character;
if (!cursor || !token || !*cursor) return -1;
scan = *cursor;
while (bob_isspace(*scan)) scan++;
if (!*scan) { *cursor = scan; *token = 0; return 0; }
write = scan; *token = write; quote = 0;
while (*scan) {
character = *scan;
if (quote) {
if (character == quote) { quote = 0; scan++; continue; }
if (character == '\\' && scan[1]) scan++;
} else {
if (bob_isspace(character)) break;
if (character == '"' || character == '\'') { quote = character; scan++; continue; }
if (character == '\\' && scan[1]) scan++;
}
*write++ = *scan++;
}
if (quote) { *token = 0; *cursor = scan; return -1; }
while (bob_isspace(*scan)) scan++;
*write = 0; *cursor = scan;
return 1;
}
#endif
+733 -40
View File
File diff suppressed because it is too large. Load diff
+102 -7
View File
@@ -8,9 +8,17 @@ void file_snapshot(int operation) {
descriptor[0] = (int)file_names; descriptor[1] = (int)file_lengths;
descriptor[2] = (int)file_kinds; descriptor[3] = (int)file_used;
result = bob_snapshot(descriptor, operation);
#ifdef BOBC_WIDE
if (result == -1) println("Storage unavailable. Check bob-files.b32 location/permissions (or BOB16_STORAGE).");
#else
if (result == -1) println("Storage unavailable. Check bob-files.b16 location/permissions (or BOB16_STORAGE).");
#endif
else if (result < 0) println("Invalid saved files; RAM files unchanged.");
#ifdef BOBC_WIDE
else if (operation == 0) println("Files saved to bob-files.b32 (or BOB16_STORAGE).");
#else
else if (operation == 0) println("Files saved to bob-files.b16 (or BOB16_STORAGE).");
#endif
else {
println("Files restored; previous RAM files replaced.");
if (result == 1) println("Kernel changed: old programs omitted. Compile restored C sources again.");
@@ -20,7 +28,16 @@ void file_snapshot(int operation) {
char *file_name(int slot) { return file_names + slot * NAME_WORDS; }
/* The upper 4096 words are reserved for file contents, above the kernel stack.
Supervised programs cannot write this region. */
int *file_content(int slot) { return (int *)0xf000 + slot * FILE_WORDS; }
int *file_content(int slot) {
#ifdef BOBC_WIDE
int i; int offset;
offset = 0;
for (i = 0; i < slot; i++) if (file_used[i]) offset += file_lengths[i] + 1;
return (int *)0xf000 + offset;
#else
return (int *)0xf000 + slot * FILE_WORDS;
#endif
}
int file_find(char *name) {
int i;
for (i = 0; i < FILE_COUNT; i++)
@@ -44,16 +61,79 @@ int file_slot(char *name) {
}
return -1;
}
int file_write(char *name, int *data, int length, int kind) {
int file_prepare_native(char *name) {
int i; int count; int length;
length = strlen(name);
if (!length || length >= NAME_WORDS || file_find(name) >= 0) return -1;
for (i = 0; i < length; i++) if (name[i] < 33 || name[i] > 126) return -1;
count = 0;
for (i = 0; i < FILE_COUNT; i++) if (file_used[i]) {
if (i != count) {
memcpy(file_name(count), file_name(i), NAME_WORDS);
file_lengths[count] = file_lengths[i]; file_kinds[count] = file_kinds[i]; file_used[count] = 1;
file_used[i] = 0;
}
count++;
}
if (count == FILE_COUNT) return -1;
memset(file_name(count), 0, NAME_WORDS); memcpy(file_name(count), name, length);
file_lengths[count] = 0; file_kinds[count] = 3; file_used[count] = 1;
return count;
}
int file_write(char *name, void *data, int length, int kind) {
#ifdef BOBC_WIDE
int slot; int i; int used; int available; int targetOffset; int sourceSlot;
if (length < 0 || length >= FILE_WORDS || (!kind && length >= TEXT_WORDS)) return -1;
if (!kind) for (i = 0; i < length; i++) if (!((int *)data)[i] || ((int *)data)[i] > 255) return -1;
int oldSlot = file_find(name);
slot = file_slot(name);
if (slot < 0) return -1;
sourceSlot = -1;
for (i = 0; i < FILE_COUNT; i++) if (file_used[i] && data == file_content(i)) sourceSlot = i;
used = 0;
for (i = 0; i < FILE_COUNT; i++) if (file_used[i] && i != slot) used += file_lengths[i] + 1;
available = FILE_WORDS - used;
if (length + 1 > available) {
if (oldSlot < 0) { file_used[slot] = 0; file_lengths[slot] = 0; file_kinds[slot] = 0; memset(file_name(slot), 0, NAME_WORDS); }
return -1;
}
if (sourceSlot == slot) return slot;
/* Compact first so variable-sized files never leave unusable gaps. */
for (i = 0; i < FILE_COUNT; i++) if (file_used[i] && i != slot) {
int *source; int *destination; int j;
source = (int *)0xf000; destination = (int *)0xf000;
for (j = 0; j < i; j++) if (file_used[j] && j != slot) destination += file_lengths[j] + 1;
for (j = 0; j < i; j++) if (file_used[j]) source += file_lengths[j] + 1;
if (source != destination && destination < source)
for (j = 0; j <= file_lengths[i]; j++) destination[j] = source[j];
}
/* Insert the rewritten target at its slot-ordered offset. */
targetOffset = 0;
for (i = 0; i < slot; i++) if (file_used[i] && i != slot) targetOffset += file_lengths[i] + 1;
{ int total = 0;
for (i = 0; i < FILE_COUNT; i++) if (file_used[i] && i != slot) total += file_lengths[i] + 1;
for (i = total - 1; i >= targetOffset; i--) ((int *)0xf000)[i + length + 1] = ((int *)0xf000)[i];
if (sourceSlot >= 0) {
int sourceOffset = 0;
for (i = 0; i < sourceSlot; i++) if (file_used[i] && i != slot) sourceOffset += file_lengths[i] + 1;
if (sourceSlot > slot) sourceOffset += length + 1;
data = (int *)0xf000 + sourceOffset;
}
memcpy((int *)0xf000 + targetOffset, data, length);
((int *)0xf000)[targetOffset + length] = 0;
file_lengths[slot] = length; file_kinds[slot] = kind;
}
return slot;
#else
int slot;
if (length < 0 || length >= FILE_WORDS) return -1;
slot = file_slot(name);
if (slot < 0) return -1;
memcpy(file_content(slot), data, length);
file_content(slot)[length] = 0;
file_lengths[slot] = length;
file_kinds[slot] = kind;
file_lengths[slot] = length; file_kinds[slot] = kind;
return slot;
#endif
}
void file_list(void) {
int i; int count;
@@ -61,13 +141,19 @@ void file_list(void) {
for (i = 0; i < FILE_COUNT; i++) {
if (file_used[i]) {
print(file_name(i)); print(" "); print_dec(file_lengths[i]);
if (file_kinds[i]) println(" words (program)");
if (file_kinds[i] == 3) println(" words (native bob32 image)");
else if (file_kinds[i]) println(" words (program)");
else println(" chars (text)");
count++;
}
}
if (!count) println("No files.");
print("Used "); print_dec(count); println("/8 slots; limit 511 words per file. delete frees a slot.");
print("Used "); print_dec(count);
#ifdef BOBC_WIDE
println("/8 slots; shared 4096-word storage. Text/resident files max 511; native apps use remaining space.");
#else
println("/8 slots; limit 511 words per file. delete frees a slot.");
#endif
}
void file_manage(char *operation, char *name, char *destination) {
int slot; int target;
@@ -75,9 +161,18 @@ void file_manage(char *operation, char *name, char *destination) {
slot = file_find(name);
if (slot < 0) { println("File not found. Use ls to see names."); return; }
if (strcmp(operation, "delete") == 0) {
#ifdef BOBC_WIDE
int sourceOffset; int destinationOffset; int i; int j;
sourceOffset = 0; destinationOffset = 0;
for (i = 0; i < FILE_COUNT; i++) if (file_used[i]) {
if (i == slot) { sourceOffset += file_lengths[i] + 1; continue; }
if (sourceOffset != destinationOffset)
for (j = 0; j <= file_lengths[i]; j++) ((int *)0xf000)[destinationOffset + j] = ((int *)0xf000)[sourceOffset + j];
sourceOffset += file_lengths[i] + 1; destinationOffset += file_lengths[i] + 1;
}
#endif
file_used[slot] = 0; file_lengths[slot] = 0; file_kinds[slot] = 0;
memset(file_name(slot), 0, NAME_WORDS);
memset(file_content(slot), 0, FILE_WORDS);
println("Deleted."); return;
}
if (!*destination || strlen(destination) >= NAME_WORDS) {
+4
View File
@@ -44,7 +44,11 @@ void input_complete(void) {
count = input_cursor - start; matches = 0;
if (input_cursor != input_length) return;
if (!start) {
#ifdef BOBC_WIDE
words = "help echo clear mem halt list ls dir read write edit load run run32 cc go copy rename delete alloc peek poke save restore";
#else
words = "help echo clear mem halt list ls dir read write edit load run cc go copy rename delete alloc peek poke save restore";
#endif
while (*words) {
length = 0;
while (*words && *words != ' ') candidate[length++] = *words++;
+4
View File
@@ -9,7 +9,11 @@
int main(void) {
int length; char *sample;
println("bob!");
#ifdef BOBC_WIDE
println("bob32 OS: help COMMAND for usage; go bob.c runs the example.");
#else
println("bob16 OS: help COMMAND for usage; go bob.c runs the example.");
#endif
println("Files are in RAM; halt exits. Type help to get started.");
sample = "int main(void) { println(\"bob!\"); return 0; }";
file_write("bob.c", sample, strlen(sample), 0);
+20 -2
View File
@@ -1,5 +1,10 @@
int heap_used;
#ifdef BOBC_WIDE
int bit_masks[32] = {(-2147483647-1),1073741824,536870912,268435456,134217728,67108864,33554432,16777216,
8388608,4194304,2097152,1048576,524288,262144,131072,65536,32768,16384,8192,4096,2048,1024,512,256,128,64,32,16,8,4,2,1};
#else
int bit_masks[16] = {-32768,16384,8192,4096,2048,1024,512,256,128,64,32,16,8,4,2,1};
#endif
int bit_weights[4] = {8,4,2,1};
int strlen(char *text) { int n; n = 0; while (text[n]) n++; return n; }
@@ -8,12 +13,21 @@ int strcmp(char *a, char *b) {
while (a[i] && a[i] == b[i]) i++;
return a[i] - b[i];
}
void memcpy(int *dst, int *src, int count) {
#ifdef BOBC_WIDE
void memcpy(void *dst, void *src, int count) {
int i; for (i = 0; i < count; i++) ((int *)dst)[i] = ((int *)src)[i];
}
void memset(void *dst, int value, int count) {
int i; for (i = 0; i < count; i++) ((int *)dst)[i] = value;
}
#else
void word_copy(int *dst, int *src, int count) {
int i; for (i = 0; i < count; i++) dst[i] = src[i];
}
void memset(int *dst, int value, int count) {
void word_fill(int *dst, int value, int count) {
int i; for (i = 0; i < count; i++) dst[i] = value;
}
#endif
void print(char *text) { int i; i = 0; while (text[i]) { bob_putc(text[i]); i++; } }
void println(char *text) { print(text); bob_putc('\n'); }
void decimal_negative(int number) {
@@ -31,7 +45,11 @@ void print_dec(int number) {
void print_hex(int number) {
int nibble; int bit; int digit;
print("0x");
#ifdef BOBC_WIDE
for (nibble = 0; nibble < 8; nibble++) {
#else
for (nibble = 0; nibble < 4; nibble++) {
#endif
digit = 0;
for (bit = 0; bit < 4; bit++) {
if (number & bit_masks[nibble * 4 + bit]) digit = digit + bit_weights[bit];
+29 -4
View File
@@ -1,17 +1,42 @@
#ifndef BOB_RUNTIME_H
#define BOB_RUNTIME_H
#include "bob.h"
#if BOBC_WIDE
#define HEAP_BASE 0xd000
#define HEAP_WORDS 4096
#define PROGRAM_BASE 0xc200
#define PROGRAM_WORDS 3584
#else
#define HEAP_BASE 0xc000
#define HEAP_WORDS 8192
#define PROGRAM_BASE 0x9000
#define PROGRAM_WORDS 12288
#define PROGRAM_BASE 0xa000
#define PROGRAM_WORDS 8192
#endif
#define WIDE_PROGRAM_BASE 0x20000
#define WIDE_VARIABLE_BASE 0xf0000
#define FILE_COUNT 8
#define TEXT_WORDS 512
#if BOBC_WIDE
#define FILE_WORDS 4096
#else
#define FILE_WORDS 512
#endif
#define NAME_WORDS 24
int strlen(char *text);
int strcmp(char *a, char *b);
void memcpy(int *dst, int *src, int count);
void memset(int *dst, int value, int count);
int file_find(char *name);
int file_prepare_native(char *name);
char *file_name(int slot);
int *file_content(int slot);
#if BOBC_WIDE
void memcpy(void *dst, void *src, int count);
void memset(void *dst, int value, int count);
#else
void word_copy(int *dst, int *src, int count);
void word_fill(int *dst, int value, int count);
#define memcpy(dst, src, count) word_copy((int *)(dst), (int *)(src), (count))
#define memset(dst, value, count) word_fill((int *)(dst), (value), (count))
#endif
void print(char *text);
void println(char *text);
void print_dec(int number);
+117 -17
View File
@@ -80,13 +80,13 @@ int editor_changed(char *name) {
int slot;
slot = file_find(name);
if (slot < 0) return editor_length != 0;
return strcmp(edit_buffer, file_content(slot)) != 0;
return strcmp(edit_buffer, (char *)file_content(slot)) != 0;
}
int editor_replace(int start, int end, char *text, int newline) {
int added; int delta; int i;
added = strlen(text) + newline;
delta = added - (end - start);
if (editor_length + delta >= FILE_WORDS) { println("File too large; change rejected."); return 0; }
if (editor_length + delta >= TEXT_WORDS) { println("File too large; change rejected."); return 0; }
memcpy(edit_undo, edit_buffer, editor_length + 1);
editor_undo_length = editor_length; editor_has_undo = 1;
if (delta > 0) {
@@ -195,10 +195,36 @@ void load_words(char *name) {
if (slot < 0) println("Cannot create program file.");
else println("Loaded.");
}
void run_file(char *name) {
void run_file(char *name, char *app_arguments) {
int slot; int status; int *program;
slot = file_find(name);
if (slot < 0 || !file_kinds[slot]) { println("Program not found. Use cc or load first."); return; }
if (slot < 0 || !file_kinds[slot]) { println("Program not found. Use cc, load, or import32 first."); return; }
#ifdef BOBC_WIDE
if (file_kinds[slot] == 3) {
int descriptor[4];
descriptor[0] = (int)file_content(slot); descriptor[1] = file_lengths[slot];
descriptor[2] = (int)app_arguments;
descriptor[3] = (int)name;
status = bob_run_native(descriptor);
if (status == -4) println("Invalid or unsupported native bob32 image.");
else if (status == -5) println("Not enough emulator memory to load this app.");
else if (status == -2) println("Program fault; shell restored.");
else if (status == -3) println("Program timed out; shell restored.");
else { print("Exit "); print_dec(status); bob_putc('\n'); }
return;
}
if (file_kinds[slot] == 2) {
program = (int *)WIDE_PROGRAM_BASE;
memset(program, 0, file_lengths[slot] + 1);
memcpy(program, file_content(slot), file_lengths[slot]);
memset((int *)WIDE_VARIABLE_BASE, 0, 16);
status = bob_run(WIDE_PROGRAM_BASE);
if (status == -2) println("Program fault; shell restored.");
else if (status == -3) println("Program timed out; shell restored.");
else { print("Exit "); print_dec(status); bob_putc('\n'); }
return;
}
#endif
program = (int *)PROGRAM_BASE;
memset(program, 0, PROGRAM_WORDS);
memcpy(program, file_content(slot), file_lengths[slot]);
@@ -207,19 +233,65 @@ void run_file(char *name) {
else if (status == -3) println("Program timed out; shell restored.");
else { print("Exit "); print_dec(status); bob_putc('\n'); }
}
void import_wide_image(char *path, char *name) {
int slot; int descriptor[3]; int result; int i; int used;
slot = file_prepare_native(name);
if (slot < 0) { println("Cannot import: invalid name, duplicate file, or all 8 slots are used."); return; }
used = 0; for (i = 0; i < FILE_COUNT; i++) if (file_used[i] && i != slot) used += file_lengths[i] + 1;
descriptor[0] = (int)path; descriptor[1] = (int)file_content(slot); descriptor[2] = FILE_WORDS - used;
result = bob_import_image(descriptor);
if (result < 0) {
file_used[slot] = 0; file_lengths[slot] = 0; file_kinds[slot] = 0; memset(file_name(slot), 0, NAME_WORDS);
if (result == -1) println("Cannot read host app image path.");
else if (result == -5) println("Not enough RAM filesystem space for this app image.");
else println("Invalid, truncated, corrupt, or unsupported B32K app image.");
return;
}
file_content(slot)[result] = 0; file_lengths[slot] = result; file_kinds[slot] = 3;
print("Imported native app as "); print(name); print(". Run it with: run "); println(name);
}
#ifdef BOBC_WIDE
void run_wide_image(char *path) {
int status;
status = bob_run_image(path);
if (status == -5) println("Cannot read B32 app image.");
else if (status == -4) println("Invalid B32 app image or unsupported address range.");
else if (status == -2) println("Program fault; shell restored.");
else if (status == -3) println("Program timed out; shell restored.");
else { print("Exit "); print_dec(status); bob_putc('\n'); }
}
#endif
void memory_status(void) {
print("Heap "); print_hex(HEAP_BASE); print(".."); print_hex(0xdfff);
print("Heap "); print_hex(HEAP_BASE); print(".."); print_hex(HEAP_BASE + HEAP_WORDS - 1);
print("; free "); print_dec(HEAP_WORDS - heap_used); println(" words");
#ifdef BOBC_WIDE
print("bob16 programs 0x0000A000..0x0000BDFF; bob32 legacy programs "); print_hex(PROGRAM_BASE); print("..0x0000CFFF; native bob32 programs "); print_hex(WIDE_PROGRAM_BASE); print("..0x000EFFFF"); println("");
#else
print("Programs "); print_hex(PROGRAM_BASE); print(".."); print_hex(0xbfff); println("");
#endif
#ifdef BOBC_WIDE
println("Files: 8 slots, 4096 words total; text files up to 511 words; native apps share remaining space.");
#else
println("Files: 8 slots, 511 words each; stack above 0xE600.");
#endif
}
void command_help(char *name) {
if (strcmp(name, "save") == 0 || strcmp(name, "restore") == 0) {
println("save: snapshot all files to bob-files.b16 in the working directory (or BOB16_STORAGE). restore yes: replace RAM files with that snapshot. Save current work first. Changed kernels restore text only; recompile programs."); return;
#ifdef BOBC_WIDE
println("save: snapshot all files to bob-files.b32 in the working directory (or BOB16_STORAGE). restore yes: replace RAM files with that snapshot. Save current work first. Changed kernels restore text only; recompile programs.");
#else
println("save: snapshot all files to bob-files.b16 in the working directory (or BOB16_STORAGE). restore yes: replace RAM files with that snapshot. Save current work first. Changed kernels restore text only; recompile programs.");
#endif
return;
}
if (strcmp(name, "edit") == 0) println("edit NAME: type/arrows; Ctrl+O saves, Ctrl+X exits, Ctrl+Z undo/redo. Unsaved exit asks Y/N. Redirected input uses the line editor; see C_OS.md.");
else if (strcmp(name, "cc") == 0 || strcmp(name, "go") == 0)
else if (strcmp(name, "cc") == 0 || strcmp(name, "go") == 0) {
#ifdef BOBC_WIDE
println("cc SOURCE [OUTPUT]: compile a native 32-bit C program; output defaults to app. Code can use available RAM filesystem space. go also runs it. 32-bit int; ?:, do/while, arrays; one main; no includes.");
#else
println("cc SOURCE [OUTPUT]: compile C; output defaults to app. go SOURCE [OUTPUT] also runs on success. Example: go bob.c. One int main(void); no includes. Use edit SOURCE to fix errors.");
#endif
}
else if (strcmp(name, "write") == 0) println("write NAME TEXT: create/replace a text file. Example: write note bob! Names: 1..23 characters without spaces; 8 file slots, 511 words each. Use edit for multiple lines.");
else if (strcmp(name, "read") == 0) println("read NAME: print text. Example: read bob.c. Use ls to see names; run executes program files.");
else if (strcmp(name, "ls") == 0 || strcmp(name, "dir") == 0 || strcmp(name, "list") == 0)
@@ -227,18 +299,27 @@ void command_help(char *name) {
else if (strcmp(name, "copy") == 0 || strcmp(name, "rename") == 0 || strcmp(name, "delete") == 0)
println("copy OLD NEW | rename OLD NEW | delete NAME. Example: copy bob.c backup.c. Destinations must be new. Copy needs a free slot; rename does not. Delete is permanent.");
else if (strcmp(name, "run") == 0) println("run NAME: execute a compiled/loaded program. Example: cc bob.c bob, then run bob. Exit shows return value; faults/timeouts restore the shell.");
#ifdef BOBC_WIDE
else if (strcmp(name, "run32") == 0) println("run32 PATH: load and run a B32K v2 application image in the bob32 OS. Example: run32 build/wide-app.b32. Compile with bobcc --wide-app.");
else if (strcmp(name, "import32") == 0) println("import32 HOST_PATH GUEST_NAME: import a B32K v2 image into RAM files; then run GUEST_NAME and save to keep it in B32S.");
#endif
else if (strcmp(name, "load") == 0) println("load NAME 0xWORD ...: store machine words. Example: load empty 0x2180 0xE000, then run empty. RET 0xE000 returns; use cc for C source.");
else if (strcmp(name, "peek") == 0 || strcmp(name, "poke") == 0)
println("peek ADDRESS | poke ADDRESS VALUE: word addresses, hex 0x0000..0xFFFF or signed decimal. Example: poke 0xC000 98. Writes allowed only at 0xC000..0xDFFF. peek also shows signed value.");
println("peek ADDRESS | poke ADDRESS VALUE: word addresses, hex 0x0000..0xFFFF or signed decimal. Example: poke 0xD000 98. Writes allowed only in heap RAM. peek also shows signed value.");
else if (strcmp(name, "alloc") == 0 || strcmp(name, "mem") == 0)
println("alloc WORDS: allocate/zero 1..8192 heap words, print start address; no free. Example: alloc 16. mem shows remaining heap and memory regions.");
println("alloc WORDS: allocate/zero heap words, print start address; no free. Example: alloc 16. mem shows remaining heap and memory regions.");
else if (strcmp(name, "echo") == 0) println("echo TEXT: print text. Example: echo bob!");
else if (strcmp(name, "clear") == 0) println("clear: clear an ANSI-capable terminal; does not remove files.");
else if (strcmp(name, "halt") == 0) println("halt: stop emulator. Unsaved RAM files and allocations are lost; use save before quitting.");
else if (strcmp(name, "help") == 0) println("help: list commands. help COMMAND: show usage and an example. Try help edit or help go.");
else println("No help for that command. Type help for available names.");
}
void shell_command(char *line) {
#ifdef BOBC_WIDE
#define SHELL_COMMAND_BODY shell_command_normal
#else
#define SHELL_COMMAND_BODY shell_command
#endif
void SHELL_COMMAND_BODY(char *line) {
char *command; char *name; char *text; int value; int address; int *pointer;
arguments = line; command = next_arg();
if (!*command) return;
@@ -250,6 +331,10 @@ void shell_command(char *line) {
println("list / ls / dir | read NAME | write NAME TEXT | edit NAME");
println("copy OLD NEW | rename OLD NEW | delete NAME (permanent in RAM)");
println("load NAME 0xWORD ... | run NAME | cc SOURCE [OUTPUT] | go SOURCE [OUTPUT]");
#ifdef BOBC_WIDE
println("run32 PATH: run a native bob32 B32K v2 application image.");
println("import32 HOST_PATH GUEST_NAME: import once, then run the guest filename.");
#endif
println("cc/go default output: app. Try go bob.c to compile and print bob!");
println("Use hex addresses. poke is limited to heap RAM.");
println("Type help COMMAND for usage/examples. Try help edit or help go.");
@@ -276,23 +361,23 @@ void shell_command(char *line) {
value = file_find(next_arg());
if (value < 0) println("File not found.");
else if (file_kinds[value]) println("Binary program; use run.");
else println(file_content(value));
else println((char *)file_content(value));
} else if (strcmp(command, "write") == 0) {
name = next_arg(); text = remaining_args();
if (file_write(name, text, strlen(text), 0) < 0) println("Cannot write file. Names: 1..23 printable characters; 8 slots. Use ls or help write.");
else println("Saved.");
} else if (strcmp(command, "edit") == 0) edit_file(next_arg());
else if (strcmp(command, "load") == 0) { name = next_arg(); load_words(name); }
else if (strcmp(command, "run") == 0) run_file(next_arg());
else if (strcmp(command, "run") == 0) { name = next_arg(); run_file(name, remaining_args()); }
else if (strcmp(command, "cc") == 0 || strcmp(command, "go") == 0) {
name = next_arg(); text = next_arg();
if (!*name || *next_arg()) { println("Usage: cc SOURCE [OUTPUT] | go SOURCE [OUTPUT]"); return; }
if (!*text) text = "app";
value = compile_command(name, text);
if (value && strcmp(command, "go") == 0) run_file(text);
if (value && strcmp(command, "go") == 0) run_file(text, "");
} else if (strcmp(command, "alloc") == 0) {
value = parse_number(next_arg());
if (!number_ok) { println("Invalid allocation size. Use 1..8192 words; mem shows available space."); return; }
if (!number_ok) { println("Invalid allocation size. Use a positive word count; mem shows available space."); return; }
pointer = alloc(value);
if (!pointer) println("Allocation failed. Use a positive size within free space; see mem. No free command.");
else { print_hex((int)pointer); bob_putc('\n'); }
@@ -303,11 +388,26 @@ void shell_command(char *line) {
if (strcmp(command, "poke") == 0) {
value = parse_number(next_arg());
if (!number_ok) { println("Invalid value. Use -32768..65535 or 0x0000..0xFFFF."); return; }
if (address >= 0 || address < -16384 || address >= -8192) {
println("poke is limited to 0xC000..0xDFFF."); return;
}
#ifdef BOBC_WIDE
if (address < 0xd000 || address > 0xdfff) { println("poke is limited to heap RAM."); return; }
#else
if (address >= 0 || address < -16384 || address >= -8192) { println("poke is limited to 0xC000..0xDFFF."); return; }
#endif
*pointer = value;
}
print_hex(address); print(": "); print_hex(*pointer); print(" ("); print_dec(*pointer); println(")");
} else println("Unknown command. Type help.");
}
#ifdef BOBC_WIDE
void shell_command(char *line) {
if(line[0]=='r' && line[1]=='u' && line[2]=='n' && line[3]=='3' && line[4]=='2' && (!line[5] || line[5]==' ')) {
arguments=line+5;char *path=next_arg();int slot;
if(!*path)println("Usage: run32 PATH [ARG ...]");
else {slot=file_find(path);if(slot>=0 && file_kinds[slot]==3)run_file(path,remaining_args());else if(*remaining_args())println("Arguments require an imported native app.");else run_wide_image(path);}
} else if(line[0]=='i' && line[1]=='m' && line[2]=='p' && line[3]=='o' && line[4]=='r' && line[5]=='t' && line[6]=='3' && line[7]=='2' && (!line[8] || line[8]==' ')) {
arguments=line+8;char *path=next_arg();char *name=next_arg();
if(!*path || !*name || *next_arg())println("Usage: import32 HOST_PATH GUEST_NAME");
else import_wide_image(path,name);
} else shell_command_normal(line);
}
#endif
+9
View File
@@ -0,0 +1,9 @@
#ifndef BOB_STDBOOL_H
#define BOB_STDBOOL_H
#define bool _Bool
#define true 1
#define false 0
#define __bool_true_false_are_defined 1
#endif
+11
View File
@@ -0,0 +1,11 @@
#ifndef BOB_STDDEF_H
#define BOB_STDDEF_H
typedef unsigned int size_t;
typedef int ptrdiff_t;
#ifndef NULL
#define NULL ((void *)0)
#endif
#endif
BIN
View File
Binary file not shown.
+594 -132
View File
File diff suppressed because it is too large. Load diff
+58 -23
View File
@@ -1,52 +1,65 @@
/* Included by main.c after ram is defined. Durable file device; guest owns shell. */
enum { SNAP_WORDS = 4312 };
static uint32_t kernelIdentity;
static uint32_t snapshotHash(const uint16_t *words, unsigned count) {
static uint32_t snapshotHash(const uint32_t *words, unsigned count) {
uint32_t hash=2166136261u;
for(unsigned i=0;i<count;i++) {
hash=(hash^(words[i]&255))*16777619u;
hash=(hash^(words[i]>>8))*16777619u;
hash=(hash^((words[i]>>8)&255))*16777619u;
if(cpu32) { hash=(hash^((words[i]>>16)&255))*16777619u; hash=(hash^(words[i]>>24))*16777619u; }
}
return hash;
}
static int snapshotValid(const uint16_t *words) {
static int snapshotValidFormat(const uint32_t *words, int packed) {
unsigned packedOffset=0;
for(unsigned i=0;i<8;i++) {
unsigned length=words[192+i],kind=words[200+i],used=words[208+i];
if(used>1 || kind>1 || length>511)return 0;
if(used>1 || kind>(cpu32?(packed?3u:2u):1u) || length>=(packed?4096u:512u))return 0;
if(!used)continue;
const uint16_t *name=words+i*24;unsigned n=0;
const uint32_t *name=words+i*24;unsigned n=0;
while(n<24 && name[n]) {if(name[n]<33 || name[n]>126)return 0;n++;}
if(!n || n==24 || words[216+i*512+length])return 0;
if(!kind)for(unsigned k=0;k<length;k++)if(!words[216+i*512+k] || words[216+i*512+k]>255)return 0;
unsigned contentOffset=packed?packedOffset:i*512;
if(!n || n==24 || words[216+contentOffset+length])return 0;
if(!kind)for(unsigned k=0;k<length;k++)if(!words[216+contentOffset+k] || words[216+contentOffset+k]>255)return 0;
if(packed)packedOffset+=length+1;
for(unsigned j=0;j<i;j++)if(words[208+j]) {
unsigned k=0;while(k<24 && name[k]==words[j*24+k] && name[k])k++;
if(k<24 && name[k]==words[j*24+k])return 0;
}
}
if(packed && packedOffset>4096)return 0;
return 1;
}
static int snapshotValid(const uint32_t *words) { return snapshotValidFormat(words,cpu32); }
static int snapshotService(unsigned descriptor, int operation) {
if(programMode || descriptor<0x300 || descriptor+4>0xf000)return -3;
if(programMode || descriptor<0x300 || descriptor>0xf000-4)return -3;
unsigned addresses[4],sizes[4]={192,8,8,8};
for(unsigned i=0;i<4;i++) {
addresses[i]=(uint16_t)ram.memory[descriptor+i];
if(addresses[i]<0x300 || addresses[i]+sizes[i]>0x9000)return -3;
addresses[i]=cpu32?(uint32_t)memoryRead(descriptor+i):(uint16_t)ram.memory[descriptor+i];
uint64_t end=(uint64_t)addresses[i]+sizes[i];
int lowArray=addresses[i]>=0x300 && end<=(cpu32?0xc000u:0xa000u);
uint32_t kernelStart=bootMode?bootOrigin:(assembledWide?assembledOrigin:0);
uint64_t kernelEnd=bootMode?(uint64_t)bootOrigin+bootWords:(assembledWide?(uint64_t)assembledOrigin+assembledWords:0);
int kernelArray=cpu32 && addresses[i]>=kernelStart && end<=kernelEnd;
if(!lowArray && !kernelArray)return -3;
for(unsigned j=0;j<i;j++)if(addresses[i]<addresses[j]+sizes[j] && addresses[j]<addresses[i]+sizes[i])return -3;
}
const char *path=getenv("BOB16_STORAGE");if(!path || !*path)path="bob-files.b16";
uint16_t words[SNAP_WORDS];unsigned position=0;
const char *path=getenv("BOB16_STORAGE");if(!path || !*path)path=cpu32?"bob-files.b32":"bob-files.b16";
uint32_t words[SNAP_WORDS];unsigned position=0;
if(operation==0) {
for(unsigned i=0;i<4;i++)for(unsigned j=0;j<sizes[i];j++)words[position++]=(uint16_t)ram.memory[addresses[i]+j];
for(unsigned i=0;i<4096;i++)words[position++]=(uint16_t)ram.memory[0xf000+i];
for(unsigned i=0;i<4;i++)for(unsigned j=0;j<sizes[i];j++)words[position++]=(uint32_t)wordValue(memoryRead(addresses[i]+j));
for(unsigned i=0;i<4096;i++)words[position++]=(uint32_t)wordValue(ram.memory[0xf000+i]);
if(!cpu32)for(unsigned i=0;i<SNAP_WORDS;i++)words[i]&=65535u;
if(!snapshotValid(words))return -2;
size_t size=strlen(path)+5;char *temporary=malloc(size);if(!temporary)return -1;
snprintf(temporary,size,"%s.tmp",path);
FILE *file=fopen(temporary,"wb");if(!file){free(temporary);return -1;}
uint32_t hash=snapshotHash(words,SNAP_WORDS);
unsigned char header[16]={'B','1','6','S',1,0,0,0};
if(cpu32){header[1]='3';header[2]='2';header[4]=2;}
for(unsigned i=0;i<4;i++){header[8+i]=(unsigned char)(kernelIdentity>>(8*i));header[12+i]=(unsigned char)(hash>>(8*i));}
int okay=fwrite(header,1,16,file)==16;
for(unsigned i=0;i<SNAP_WORDS;i++)if(fputc(words[i]&255,file)==EOF || fputc(words[i]>>8,file)==EOF)okay=0;
for(unsigned i=0;i<SNAP_WORDS;i++)for(unsigned b=0;b<(cpu32?4u:2u);b++)if(fputc((words[i]>>(8*b))&255,file)==EOF)okay=0;
if(fclose(file))okay=0;
if(okay) {
#ifdef _WIN32
@@ -62,19 +75,41 @@ static int snapshotService(unsigned descriptor, int operation) {
FILE *file=fopen(path,"rb");if(!file)return -1;
unsigned char header[16];int valid=fread(header,1,16,file)==16;
for(unsigned i=0;i<SNAP_WORDS;i++) {
int lo=fgetc(file),hi=fgetc(file);if(lo==EOF || hi==EOF){valid=0;break;}
words[i]=(uint16_t)(lo|(hi<<8));
words[i]=0; for(unsigned b=0;b<(cpu32?4u:2u);b++){int byte=fgetc(file);if(byte==EOF){valid=0;break;}words[i]|=(uint32_t)byte<<(8*b);}
if(!valid)break;
}
if(fgetc(file)!=EOF)valid=0;
fclose(file);
if(!valid || memcmp(header,"B16S\1\0\0\0",8))return -2;
if(ferror(file))valid=0;
if(fclose(file))valid=0;
int oldWide=cpu32 && !memcmp(header,"B32S\1\0\0\0",8);
int currentFormat=cpu32 && !memcmp(header,"B32S\2\0\0\0",8);
if(!valid || (!oldWide && !currentFormat && memcmp(header,"B16S\1\0\0\0",8)))return -2;
uint32_t identity=0,hash=0;
for(unsigned i=0;i<4;i++){identity|=(uint32_t)header[8+i]<<(8*i);hash|=(uint32_t)header[12+i]<<(8*i);}
if(hash!=snapshotHash(words,SNAP_WORDS) || !snapshotValid(words))return -2;
if(hash!=snapshotHash(words,SNAP_WORDS) || !snapshotValidFormat(words,currentFormat || (!cpu32 && 0)))return -2;
int changed=identity!=kernelIdentity;
if(changed)for(unsigned i=0;i<8;i++)if(words[200+i])words[208+i]=0;
if(cpu32 && oldWide) {
unsigned destinationOffset=0;
for(unsigned i=0;i<8;i++)if(words[208+i]) {
unsigned length=words[192+i];
for(unsigned j=0;j<=length;j++)words[216+destinationOffset+j]=words[216+i*512+j];
destinationOffset+=length+1;
}
}
if(changed && cpu32) {
unsigned sourceOffset=0,destinationOffset=0;
for(unsigned i=0;i<8;i++)if(words[208+i]) {
unsigned length=words[192+i];
if(words[200+i])words[208+i]=0;
else {
for(unsigned j=0;j<=length;j++)words[216+destinationOffset+j]=words[216+sourceOffset+j];
destinationOffset+=length+1;
}
sourceOffset+=length+1;
}
} else if(changed)for(unsigned i=0;i<8;i++)if(words[200+i])words[208+i]=0;
position=0;
for(unsigned i=0;i<4;i++)for(unsigned j=0;j<sizes[i];j++)ram.memory[addresses[i]+j]=(int16_t)words[position++];
for(unsigned i=0;i<4096;i++)ram.memory[0xf000+i]=(int16_t)words[position++];
for(unsigned i=0;i<4;i++)for(unsigned j=0;j<sizes[i];j++)memoryWrite(addresses[i]+j,wordValue(words[position++]));
for(unsigned i=0;i<4096;i++)ram.memory[0xf000+i]=wordValue(words[position++]);
return changed?1:0;
}
+289
View File
@@ -92,3 +92,292 @@ exercise pointer-to-array parameters/globals/locals, arrays of row pointers,
grouped names, casts and sizeof array type names. Rejections verify incomplete
pointee sizing/arithmetic, arrays of void, invalid casts and incompatible row
pointer declarations. Kernel compilation still produces 36,009 words.
Shift assignments and pointer/integer operator constraints bring the suite to
615 checks. Native execution covers destination side effects, chained assignment,
precedence and signed/zero shifts. Negative cases cover evaluated and sizeof
pointer operands for integer operators.
Composite function declaration types bring the suite to 631 checks. Native
programs combine incomplete and complete row-pointer declarations, including
additional indirection. Negative cases verify conflicting completions, element
types and pointer depths remain rejected.
Compound-assignment and unevaluated operand checks bring the suite to 671 checks.
Native tests retain row-pointer offset scaling and verify sizeof suppresses
side effects. Negative cases reject pointer difference/shift assignments and
array, literal or void targets in unevaluated modification expressions.
File-scope extern/tentative object declarations bring the suite to 695 checks.
Native tests verify one shared allocation, initialized values and relocated
pointers, completed arrays and zero-filled tentative storage. Negative tests
verify conflicting declarations, duplicate definitions and unresolved extern
references reject while preserving prior output files.
Block-scope extern objects bring the suite to 727 checks. Native execution
verifies scoped global aliases, shadowing without altering an outer local,
repeated declarations and completed array types. Rejections verify names do not
escape their declaring block/function and that conflicting/initialized block
extern declarations fail. The kernel remains 36,009 words.
Function-local static storage brings the suite to 755 checks. Native programs
verify persistence, private same-name objects, arrays/strings and static pointer
relocations. Negative cases reject runtime initializers, automatic addresses,
duplicate declarations and names escaping their declaring scope.
File-scope static declarations bring the suite to 783 checks. Native programs
combine internal objects/functions, relocated pointers and extern inheritance;
negative tests reject linkage conflicts and incomplete internal tentative arrays.
Constant sizeof initialization brings the suite to 787 checks. Native tests
exercise type/literal bounds and case labels, global initialized sizes and local
static sizeof automatic arrays and side-effect expressions without evaluation.
Parser type binding tests bring the suite to 807 checks. Native execution verifies
named sizeof bounds/case labels, array parameter adjustment, shadowing and block/
loop scope restoration. Rejection tests cover later, escaped and undeclared
bindings. Kernel compilation still produces 36,009 words.
Scoped typedef tests bring the suite to 843 checks. Native execution covers
scalar/pointer/array aliases, casts/parameters/sizeof, nested alias and object
shadowing, scope restoration and void aliases for no-argument functions.
Rejection tests verify ordinary-namespace conflicts and escaped/invalid aliases.
Enum tests bring the suite to 887 checks. Native programs cover distinct enum
objects, scoped constants/tags, explicit/automatic values, aliases, bounds and
switch labels. Negative cases verify namespace/type conflicts, invalid values
and out-of-scope or nonmodifiable constants reject.
Boolean type tests bring the suite to 899 checks. Native execution verifies
normalized storage across initialization, arrays, casts, calls, assignments and
modification; negative cases reject conflicting object/parameter declarations.
Unsigned int tests bring the suite to 915 checks. Native execution covers
high-bit comparisons, mixed signed operands, division/remainder, logical shifts,
casts and wraparound. Negative cases reject conflicting declarations and pointer
division. Conditional helper inclusion keeps the kernel at 36,009 words.
## Initial bob32 CPU migration
The widened emulator passes 42 direct CPU checks, 915 OS/compiler checks and
28 native console checks. CPU cases cover immediate sign extension, legacy and
wide overflow/flags, 32-bit load/store, B32K loading, guest boot transfer and
execution, and B16K compatibility selection. This does not establish a complete
bob32 ABI or whole-repository audit; see BOB32_MIGRATION.md for remaining work.
Trap/return-register audit fixes bring the direct CPU suite to 47 checks. New
cases verify signed compatibility return addresses, native wide return addresses,
supervised wide result preservation and a string word whose low 16 bits are zero.
The string case also requires the trap instruction register to remain intact.
The OS/compiler and console suites remain at 915 and 28 checks respectively.
Image/argument audit cases bring the direct suite to 65 checks. Subprocesses
require malformed B32K images to reject; numeric argument tests cover boundaries,
overflow and malformed strings, and a limited emulator run must return status 2.
Compatibility suites still pass 915 OS/compiler and 28 console checks.
Assembler input/data audit cases bring the direct suite to 73 checks. Cases cover
one string terminator, CRLF registers, complete/range-checked fill words, oversized
physical lines, all 65,536 slots and string overflow rejection before memory writes.
The repository demo plus 915 OS/compiler and 28 console checks pass.
Assembler operand tests bring the direct suite to 94 checks. Every immediate
operand family rejects malformed decimal text, invalid register-shaped tokens
and overflow. Positive tests preserve field clamping, relative/indirect calls
and the documented NOP encoding. Compatibility suites remain at 915 and 28.
Storage metadata/service tests bring the direct suite to 105 checks. Cases cover
descriptor arithmetic boundaries, wide-mode rejection, valid empty/text metadata,
invalid flags/kinds/lengths, content terminators and duplicate names. Existing
persistence cases retain failed-restore RAM preservation; 915 OS/compiler and
28 native console checks pass.
Wide instruction-boundary checks bring the direct suite to 107 checks. Reserved
upper bits must fault under supervision with parent state restored; sign-extended
legacy instructions remain accepted. Native ROM execution and compatibility
suites continue to pass (915 OS/compiler, 28 console).
Native storage verification: B32S round-trip preserves 0x12345678; upper-byte checksum corruption and cross-mode restore reject without changing RAM. Legacy OS save/restore remains covered by 915 OS/compiler checks. All 111 CPU/storage/assembler and 28 native console checks passed.
Host specifier audit: runtime coverage exercises typedefs, reordered function declarations/definitions, signed arrays, unsigned division and unsigned casts/right shifts. Six invalid specifier combinations are rejected while preserving existing output files. All 943 OS/compiler checks passed; regenerating the 36,009-word kernel produced the identical B16K image.
Host escape audit: runtime checks cover missing simple escapes, hexadecimal/octal 255, array length and terminator. Rejection coverage includes hexadecimal 256, a long overflowing hexadecimal sequence, octal 256, and direct unterminated string/character escapes bypassing preprocessing. Lexer failures preserve both prior output artifacts. Kernel rebuild remains byte-for-byte identical.
Storage address validation: direct service and actual trap execution reject native high-bit descriptor addresses. Changed-kernel B32S restore preserves text and marks binaries unused. All 115 CPU/storage/assembler, 967 OS/compiler and 28 native console checks passed.
Host input/lexer verification: direct malformed-source fixtures cover newline-containing string/character literals, 08, 1u2, 1_foo and a zero byte followed by otherwise ignored source. Existing assembly and binary outputs survive input failures. The full OS/compiler suite passed 981 checks, and the regenerated 36,009-word kernel matches the previous image.
Pointer ordering verification: one 4,096-element array crosses 0x8000, and all four relational operators compare its first/last elements and equality boundaries correctly. Additional runtime coverage compares compatible row pointers with incomplete/complete bounds. Invalid relational operand types, including sizeof, are rejected. All 1,005 OS/compiler checks passed; the 36,009-word kernel image remains unchanged.
Compiler output audit: seven collision cases verify preservation of the input, BASM, B16K and map, including Windows case and relative-path aliases. All 1,040 OS/compiler checks passed. An extensionless binary in build/output.audit produces image.map in that directory; the regenerated kernel image remains identical.
Void-expression verification: a runtime fixture counts effects through discarded calls, casts, comma and void conditionals. Fifteen invalid contexts cover operators, assignment, casts, sizeof, conditionals and all loop/if conditions. All 1,104 OS/compiler checks passed; the regenerated kernel image remains unchanged.
Return/argument verification: six invalid programs cover void/value return mismatches and ordinary/trap function arguments. All 1,128 OS/compiler checks passed; kernel regeneration produced the identical 36,009-word image.
Switch type verification: five invalid programs cover pointer, array and void conditions plus pointer/void labels. Runtime coverage verifies unsigned 65535, enum and _Bool dispatch. All 1,152 OS/compiler checks passed; the rebuilt 36,009-word kernel image is unchanged.
Const spelling verification: runtime fixture covers qualified globals, parameters, typedefs, enums, byte arrays, pointer qualifiers, repeated qualifiers and sizeof spellings. All 1,156 OS/compiler checks passed; the rebuilt kernel image is unchanged. These checks do not establish qualifier enforcement.
Build-tool audit: read tools/build.c in full, checked command status propagation and platform path handling, and added checked build-directory creation/type and Windows compiler PATH updates. A regular-file build entry fails before compiler invocation. Full build --test passed 115 CPU/storage/assembler, 1,156 OS/compiler and 28 native console checks. CPU snapshot tests now use a platform-specific environment helper rather than unconditional Windows calls; the POSIX branch remains unverified on a POSIX host.
Decoder verification: eight mode/instruction combinations check malformed NOP, NOT, JSRR and RET and parent register/PC restoration. All 123 CPU/storage/assembler, 1,156 OS/compiler and 28 native console checks passed.
Pointer subtraction verification: runtime cases compare enum/int element pointers and row pointers in both directions and inside sizeof. Three invalid cases reject distinct enum tags, incompatible row extents and incomplete row types. All 1,172 OS/compiler checks passed; the rebuilt 36,009-word kernel image is unchanged.
Conditional pointer verification: runtime cases verify complete/incomplete array composite sizes, zero/null branches, arithmetic zero and object/void pointer combinations. Four invalid programs reject incompatible pointers, nonzero/nonconstant integer branches and invalid sizeof operands. All 1,192 OS/compiler checks passed; the rebuilt 36,009-word kernel is unchanged.
Arithmetic helper review: multiplication replaced with a bounded word-mask loop. Runtime verification repeats 32767 squared and INT_MIN times 32767 sixty-four times, and covers zero, negative operands, INT_MIN wrap and unsigned 65535 squared. All 1,196 OS/compiler and 28 native console checks passed with the rebuilt 36,005-word kernel.
Resident multiplication verification: go product.c compiles and runs sixty-four repeated large products, including the signed minimum value expressed as -32767-1, plus negative and wrapping products. No compile error or supervised timeout occurs, and output is bob! with Exit 0. All 1,200 OS/compiler checks passed. cc_multiply is a wrapper around the shared host-generated helper, so the prior claim of a separate unchanged resident implementation has been corrected. The resident lexer still rejects decimal 32768, including the literal in -32768; broader literal typing remains open.
Resident octal verification: go accepts 010, 077 and 0177777 with expected values and prints bob!. Invalid 09 and overflowing 0200000 are followed by a successful go bob.c recovery. Existing malformed-source cases cover consolidated cc_fail handling. All 1,206 OS/compiler and 28 native console checks passed with the rebuilt 36,092-word kernel.
Code generation verification: the complete 1,206 OS/compiler checks and 28 native console checks passed after removing empty stack adjustments and compacting target-equivalent literals. The rebuilt 35,909-word kernel executes resident compilation, arithmetic, editor and storage paths successfully.
Resident escape and double-negation verification: go escapes.c checks all six additional spellings and prints bob!. Host runtime checks cover double negation of zero, pointers, negative/high-bit values and increments without duplicate effects. All 1,213 OS/compiler and 28 native console checks passed with the 36,096-word kernel.
Frame omission verification: recursion through no-parameter/no-local functions returns the expected result while a caller's automatic local remains intact. All 1,217 OS/compiler checks passed; 28 native console checks passed against the same rebuilt 36,054-word kernel.
Resident line-break verification: malformed multiline string and character literals both fail, then go bob.c succeeds. Existing literal/arithmetic cases exercise unary numeric folding. All 1,220 OS/compiler checks and 28 native console checks passed with the 36,041-word kernel.
Resident concatenation verification: go joined.c merges literals separated by a comment, an empty piece and a newline into bob!, then exits successfully. All 1,223 OS/compiler and 28 native console checks passed with the 36,071-word kernel.
Resident code limit verification: a source that fits the RAM text file but emits more than 511 words fails compilation into an existing output name. The previous executable runs without fault, and a subsequent go bob.c succeeds. All 1,227 OS/compiler checks and 28 native console checks passed with the 36,080-word kernel.
Signed division verification: repeated INT_MIN/1, INT_MAX/1 and INT_MAX/-1 calculations complete; all operand sign combinations and remainder signs are checked. All 1,231 OS/compiler checks and 28 native console checks passed with the 36,093-word kernel.
Assembly prompt audit: oversized filename input now drains through its line ending before retrying, rather than treating the leftover text as another filename. A 300-character input followed by valid BASM recovers and prints bob!. All 125 CPU/storage/assembler, 1,231 OS/compiler and 28 native console checks passed.
Constant type verification: four static initializers reject void/value conditional branches, void logical operands despite short-circuiting, and casts from void to a value. All 1,247 OS/compiler checks passed, and kernel regeneration matches the current 36,093-word image.
Native input/run boundary verification: actual trap execution rejects a high-bit entry address, and supervised input calls reject high-bit address/capacity arguments without modifying the destination. All 128 CPU/storage/assembler, 1,247 OS/compiler and 28 native console checks passed.
Image/source I/O review: readWord now distinguishes read error from truncated input. bootImage checks stream error and close status after checksum/exact-length validation; assemble checks close failures before announcing execution. Diagnostics identify both word-width formats. Existing truncated/corrupt image and assembly checks, plus all 128 CPU/storage/assembler, 1,247 OS/compiler and 28 native console checks, passed. Read/close failures have not been fault-injected.
Native disk argument verification: subprocess fixtures individually set upper bits in destination, offset and count and fail at trap execution. Existing B32K boot/transfer checks still pass. All 131 CPU/storage/assembler, 1,247 OS/compiler and 28 native console checks passed.
Windows console input audit: terminalKey now checks GetConsoleMode and SetConsoleMode results before using the mode, and returns EOF rather than zero when ReadConsoleInput stops without a key. This avoids an uninitialized mode and ambiguous failed-read result. All 28 native console and 1,247 OS/compiler checks passed; Windows API failure paths have not been fault-injected.
Boundary evidence refinement: native disk argument subprocess cases now verify the intended fault diagnostic, excluding unrelated process failures. Assembly filename handling accepts a full 255-character name followed by CRLF; an adjacent oversized line is still consumed before valid BASM execution. All 135 CPU/storage/assembler, 1,247 OS/compiler and 28 native console checks passed. CRLF tests ran on Windows; untranslated POSIX input remains unverified on its native host.
Assembly source boundary audit: a 255-character source line followed by CRLF is accepted without losing the following .fill instruction. A 256-character line still fails. All 137 CPU/storage/assembler, 1,247 OS/compiler and 28 native console checks passed.
Pointer equality verification: runtime coverage checks symmetric object/void and null comparisons, arithmetic zero, sizeof and self equality. Four invalid programs reject nonzero integers, ordinary zero-valued variables, incompatible pointers and invalid sizeof operands. All 1,267 OS/compiler checks passed; the regenerated 36,093-word kernel image is unchanged.
Assignment compatibility verification: runtime cases check object/void pointer assignments, null arithmetic constants, _Bool normalization and sizeof. Four invalid assignments are rejected. Kernel source conversion is explicit and regeneration matches the current image. All 1,287 OS/compiler checks passed.
Return conversion verification: runtime cases check object/void pointer returns, arithmetic null returns and pointer-to-_Bool normalization. Three invalid programs reject nonzero integer, incompatible pointer and implicit pointer-to-integer returns. All 1,303 OS/compiler checks passed; the regenerated kernel image is unchanged.
Function argument conversion verification: a runtime program checks compatible object/void pointers, arithmetic null constants and pointer-to-_Bool normalization. Three invalid programs reject nonzero integer-to-pointer, incompatible pointer and pointer-to-integer arguments. All 137 CPU/storage/assembler, 1,319 OS/compiler and 28 native console checks passed. Kernel binary hash is unchanged after generic memory API signatures and explicit text casts.
Initializer conversion verification: nine invalid programs cover automatic and global pointers, pointer arrays, block-static objects, pointer-to-integer initialization and void-valued initialization. A runtime fixture covers valid local/global/array/static object pointers, object/void conversions, null constants and pointer-to-_Bool normalization. All 1,359 OS/compiler checks passed. The rebuilt kernel binary hash matches the existing 36,093-word image.
Trap argument conversion verification: seven invalid sources reject nonzero integer text pointers, incompatible text/descriptor pointers, pointer capacities, pointer characters and implicit pointer entry addresses. A runtime fixture passes a void pointer to bob_puts and prints bob!. All 1,391 OS/compiler checks passed; regenerated kernel hash matches the existing image.
Unevaluated call verification: five negative sources reject wrong parameter counts, nonzero integer pointers, incompatible pointers and invalid declared trap arguments inside sizeof. A runtime fixture verifies valid object/void pointer arguments and increment expressions are not evaluated. Existing early empty-list/later definition cases still pass. All 1,415 OS/compiler checks passed, and the regenerated 36,093-word kernel hash is unchanged.
Subscript constraint verification: four invalid programs reject void-valued index operands in both orders and indexing through void or incomplete-array element pointers inside sizeof. A runtime fixture verifies unsigned reversed indexing, row size and scalar element size in multidimensional arrays. All 1,435 OS/compiler checks passed; regenerated kernel binary hash is unchanged.
Nested sizeof/address verification: eight invalid programs cover inner void size, invalid call arguments, invalid indexing/assignments, and address-of constants, arithmetic, increments and casts. Runtime fixtures verify nested sizeof suppresses increments and pointers to string-literal arrays preserve full array size and contents. All 1,475 OS/compiler checks passed. The regenerated kernel hash is unchanged at 36,093 words.
Static string address verification: a runtime fixture checks global and block-static pointers to whole literal arrays, their complete sizes and terminators, a string-element address, and scaled one-past pointer arithmetic. All 1,479 OS/compiler checks passed. Kernel regeneration produces the same 36,093-word binary hash.
Conditional static relocation verification: runtime cases cover true/false object address selection, null selection, sizeof-based string selection and nested block-static pointer selection. Negative sources reject variable conditions and incompatible pointer branches. All 1,491 OS/compiler checks passed. Kernel binary regeneration matches the existing 36,093-word image.
Numeric pointer constant verification: a runtime fixture compares initialized pointer-to-array values against runtime arithmetic for forward/reversed addition, subtraction and pointer difference at guest addresses above 0x8000. All 1,495 OS/compiler checks passed. The regenerated 36,093-word kernel binary hash is unchanged.
Unary code-generation verification: three negative programs reject prefix/postfix increments of void lvalues and array increment. Existing runtime fixtures for numeric unary operators, pointer/Boolean increments and literal-array addresses still pass. All 1,507 OS/compiler checks passed. The regenerated 36,093-word kernel hash is unchanged.
Static Boolean address verification: a runtime fixture checks implicit object/string addresses, explicit Boolean address casts, null pointers, Boolean arrays and block-static address initialization. All 1,511 OS/compiler checks passed; regenerated kernel hash matches the existing 36,093-word image.
Relocation boundary verification: a generated source with large static arrays reaches the 65,536-word emission limit while adding pointer relocations. Compilation rejects with the intended code/relocation diagnostic and preserves existing BASM and binary outputs. All 1,516 OS/compiler checks passed. Kernel regeneration matches the existing 36,093-word binary hash. The fixture exercises code-capacity rejection through relocation emission; independent relocation-capacity saturation is not claimed.
Long literal verification: a generated guest program compiles a single 9,000-character literal and checks its last character and terminator before printing bob!. Existing escape, embedded-NUL, malformed literal and code-limit fixtures still pass. All 1,520 OS/compiler checks passed; regenerated kernel hash matches the existing 36,093-word binary. Allocation failure is checked in code but was not fault-injected.
Adjacent literal scaling verification: a generated program joins 9,000 adjacent one-character literals and verifies the final character and terminator before printing bob!. Existing embedded-NUL and ordinary concatenation fixtures remain passing. All 1,524 OS/compiler checks passed. The kernel binary hash is unchanged at 36,093 words. Linear allocation/copy behavior follows from the implementation; no host peak-memory benchmark was recorded.
Integer constant expression type verification: three invalid sources reject pointer-valued expressions used as array bounds, explicit enum values and array designator indexes. All 1,536 OS/compiler checks passed. Kernel regeneration matches the existing 36,093-word image.
Jump bookkeeping verification: host compiler rebuild and kernel regeneration pass after routing jump records through a checked append helper. All 1,536 OS/compiler checks passed; regenerated kernel hash matches the existing 36,093-word image. The explicit jump-table overflow guard is defensive because token/code limits generally fire earlier.
Generated-label bookkeeping now checks the signed serial before incrementing, so future larger outputs fail with a defined diagnostic instead of overflowing label names. The existing 65,536-word code capacity generally rejects first; a dedicated serial-saturation fixture would require constructing a larger-than-emittable AST and was not added.
Switch-context validation now rejects case/default labels outside switches during parsing and caps nested switches at 64 before recursive parsing. File-scope and function-scope invalid labels are covered. All 1,540 OS/compiler checks pass; legal labels later in a switch body remain accepted regardless of earlier break statements.
Integer constant expression syntax is now enforced for array bounds, enumerators, designator indexes and case labels. New negative inputs cover calls and side effects in bounds, designators and cases. The host OS/compiler suite passes all 1,556 checks, and the compiled kernel remains 36,093 words.
ICE type validation now walks casts, unary/binary operands and conditional operands, preventing void or pointer operands from being laundered through sizeof or an integer cast. Added array-bound and enumerator regressions for sizeof of a void cast. The full OS/compiler suite passes 1,564 checks; kernel image size and hash remain unchanged.
Explicit unsigned enum values whose result is outside signed 16-bit int range now fail instead of wrapping into a negative enumerator. The suite includes the 32768U rejection; existing negative and positive signed boundary enums continue to compile. All 1,568 OS/compiler checks pass, and the kernel image is unchanged.
Assembler input now reads bounded physical lines byte by byte and rejects embedded NUL bytes, which fgets/C-string parsing previously treated as end-of-line. CRLF, exact 255-character lines, final lines without newline, and overlong lines remain covered. The direct CPU/assembler suite passes 138 checks, including an embedded-NUL input; OS/compiler suite passes 1,568.
The assembler's `not` instruction now validates exact arity and requires a valid register in the two-register form. Previously `not r0 r8` silently encoded as `not r0`, and a fourth token was ignored. New cases cover invalid/missing/extra operands. Direct suite: 141 checks passed; OS/compiler suite: 1,568 passed.
Load/store register validation now rejects all negative `parseReg` results, not only the missing-token sentinel. Invalid register names previously reached negative shifts and malformed encodings. Added malformed-name and out-of-range cases for LD/LDI/LDR/ST/STI/STR operands. Direct CPU suite: 150 checks passed; OS/compiler suite: 1,568 passed.
The assembler now rejects trap vectors above 11, matching the emulator's implemented trap table; values 12–15 previously assembled and then faulted at runtime. Direct tests cover vectors 12 and 15. Reserved register-form ADD/AND bits also fault in both CPU modes. CPU suite: 156 passed; OS/compiler suite: 1,568 passed.
Host expression parsing now rejects nesting beyond 256 calls, protecting the compiler process from deeply nested parentheses/unary/right-associative expressions exhausting its C stack. A generated 400-level array-bound source verifies the diagnostic. OS/compiler suite: 1,573 checks passed. Recompiled kernel remains 36,093 words and matches SHA-256 F4B1175B84A8BFE2ABFB192D51CBA1E000D7EDDB52B9CECC2C4306E74BF0A4AF.
Host const scalar enforcement now tracks const declarations and typedef aliases through locals, globals and scalar parameters. Assignments and increments reject modification, including within sizeof and array-bound constant-expression parsing. Pointer, array and pointee qualification still need full type-system support. The suite passes 1,601 checks; regenerated kernel remains 36,093 words.
Direct const pointer declarators and top-level const pointer typedef aliases now retain their object qualifier, so pointer assignment and increment reject for globals, locals and parameters. `typedef const int *P` remains assignable as a pointer, confirming the pointee qualifier is distinct; enforcing pointee and array-element const remains incomplete. The OS/compiler suite passes 1,629 checks.
Pointer types and array types now retain const qualification. Assignments/increments through `*p` and `p[i]` reject for const pointees/elements; adding const to a pointer conversion is allowed, while dropping it rejects recursively through pointer levels, address-of, and conditional expressions. `bob_puts` now correctly accepts a const string. Function redeclaration checks preserve pointed-to qualifiers while ignoring top-level parameter qualifiers. Some nested qualified-declarator forms remain unfinished. OS/compiler suite: 1,697 checks passed.
Native program counters and effective addresses now retain 32 bits, with lazy sparse pages above the existing 64K-word low-memory array. JMP/JSRR/RET/PUTS preserve high addresses; LDR/STR and LDI/STI operate there, supervised programs can read/write high data, and GETS/boot-disk writes accept high destinations. B16 mode still wraps at 16 bits. B32K v2 adds 32-bit image origin, entry, length and checksum fields and can boot at any address, including the top two addressable words. Version 1 and B16 images retain their old format. Tests cover malformed v2 headers, payload checksums and command-line high-origin boot. CPU suite: 178 checks; OS/compiler: 1,697; console: 28. The current image payload remains limited to 65,536 words, and the C compiler/OS still target bob16.
The host C compiler now accepts `--wide` to emit native bob32 instructions as B32K v2 images. Wide mode supports 32-bit integer literals, data, arithmetic helpers for multiply/divide/modulo, signed and unsigned comparisons, shifts and bitwise operations, and accepts long/long long as 32-bit aliases with standard integer literal suffix order validation. The word-addressed target uses one C byte per word, so sizeof reports words and remains consistent with current array and pointer layout. Default bob16 output retains its old format. Wide output emits only functions reachable from main, following explicit calls, operator helper dependencies, array indexing, and bob_address references. A helper-free guest compiles to 23 words. `--wide-app` emits B32K v2 images at the supervised app origin, and the bob32 shell's `run32 PATH` validates the image before loading it into high memory; sparse pages are preflighted so allocation failure leaves the app region untouched. A compatibility audit found that bob16 apps can overwrite the tail of the low-address B32 kernel; supervised return now restores any overlapping kernel image words. The B32 resident compiler also emits kind-2 native programs at `0x10000`, using 32-bit literals and arithmetic, and B32S snapshots preserve these program files. It supports right-associative `?:` with selected-branch-only evaluation and `do/while` with `break`/`continue`; resident regressions check nested conditionals, skipped side effects, first-iteration behavior, early exits and continue-to-condition behavior. The bob16 compiler retains its previous behavior because its kernel image is already at the memory limit. Regression coverage also compiles and runs addition, multiplication, division, remainder and local-variable arithmetic, retains the legacy kind-1 bob16 execution path, and snapshots native files. End-to-end tests cover direct `.org` BASM execution, missing-image recovery, B32S save/restore, shell editing and 8-digit hex output. Full C conformance remains incomplete. Current suite: CPU 179, OS/compiler 1,745, console 28.
Resident B32 assignment expressions: right-associative chained assignment returns the stored value, compound assignment works inside expressions, and `<<=`/`>>=` are recognized and executed. Shell integration uses short editor input lines (below the command limit), frees source slots after each run, and asserts all nine successful B32 shell programs. bob16 image remains 36,093 words. Full suite: CPU 189, OS/compiler 1,746, native console 28.
Supervised-store boundary audit found that the B32 condition rejected writes in `0x100000..0x10FFFF` but accidentally allowed all later sparse-memory addresses. The guard now enforces `[0x10000,0x100000)` for native apps and `[0x9000,0xE000)` for B16 legacy apps. B32 legacy apps use `[0xB000,0xE000)`. Direct CPU regressions accept the final B32 app word and reject below-range, end, former-hole, arbitrary-high and maximum addresses without modifying them. Suite: CPU 189, OS/compiler 1,746, console 28.
B32 external-image allocation is now transactional: missing sparse pages are allocated into temporary buffers before any are installed or image words are copied. Allocation failure returns the documented loader error rather than taking the emulator's non-program machine-fault exit. A test-only allocator fault forces this failure and confirms the target page remains absent and unchanged. Suite: CPU 187, OS/compiler 1,746, native console 28.
Nested trap-6 audit found that a rejected recursive run cleared `application32` while the outer native app kept running. The trap now returns `-1` before changing execution mode. A CPU fixture executes nested trap 6, then stores to valid high app memory and exits successfully. Suite: CPU 187, OS/compiler 1,746, console 28.
The expanded bob32 kernel overlapped the legacy program region at `0x9000`. The bob32 OS now loads kind-1 legacy apps at `0xB000..0xBFFF`, leaves the 16-bit bob16 location unchanged, and rejects a legacy run if the active B32 kernel occupies that window. This also removes the old post-run image restore that reset RAM filesystem metadata. Snapshot descriptor validation now allows B32 kernel tables below `0xB000` while retaining the old bob16 ceiling. CPU fixtures run a 16-bit `LEA/PUTS/HALT` program and reject a low legacy entry; OS integration checks `bob!`/exit 33, file listing after execution, and snapshot save/restore. Suite: CPU 189, OS/compiler 1,746, console 28.
Resident B32 functions now use per-call stack frames, parameter offsets, local slots, forward-call patch chains, and a common return epilogue. The shell regression calls a later-defined no-argument function as a statement, calls a two-argument function for its value, and computes factorial recursively; it prints `bob!` and returns 0. The test runner counts all nine successful B32 shell programs. Suite: CPU 189, OS/compiler 1,746, console 28.
Resident B32 frame-offset audit found that local slot numbers were masked to six bits when encoded in LDR/STR instructions. A sufficiently large function with many sequential inner-scope declarations could silently access the wrong stack word after slot 32. The compiler now rejects a 33rd local slot, and a shell regression generates 33 block-scoped declarations to verify rejection. B32 kernel rebuild: 43,113 words; OS/compiler suite: 1,749 checks passed.
The B32 kernel had only 70 words of headroom before the legacy-app region after adding local arrays. Since RAM files are limited to 511 words, the kind-1 B32 legacy window moved to `0xB800..0xBFFF` and was reduced to 2,048 reserved words, still leaving over three times the largest file size. The emulator's entry/store/GETS bounds, OS program loading, snapshot table ceiling, direct CPU fixture and memory-map docs now agree. The kernel ends at `0xAFBA`, leaving 2,118 words before the B32 legacy window. CPU boundary fixtures verify writes at `0xB800` and rejection below it. Full suites: CPU 191, OS/compiler 1,752, console 28.
Resident bob32 local arrays are fixed-size, one-dimensional `int` objects within the 32-slot frame budget. The compiler zero-initializes elements, emits indexed loads, and supports indexed assignment statements. A shell regression fills and sums an array in loops and verifies `bob!`/exit 0. At that stage array parameters, explicit initializers, multidimensional arrays and bob16 resident arrays remained unsupported. Full suites: CPU 191, OS/compiler 1,752, console 28.
Indexed bob32 array statements now also support postfix increment/decrement and compound assignments, including shifts implemented through helper calls. The regression increments element zero, adds to element one and shifts element two before summing. The B32 kernel is 44,833 words, ending at `0xB221` with 1,503 words before the `0xB800` legacy-app region. Full suites: CPU 191, OS/compiler 1,752, console 28.
Fixed-size bob32 local arrays now accept brace initializer lists containing scalar expressions and an optional trailing comma. Omitted elements retain the zero fill emitted for automatic arrays; an excess element triggers a compile error. The shell fixture validates explicit values and zero-filled tail elements before exercising indexed mutation, then confirms an oversized initializer is rejected. The rebuilt B32 kernel is 45,070 words and ends at `0xB30E`, leaving 1,266 words before the legacy-app region. OS/compiler suite: 1,753 checks passed.
Indexed bob32 array prefix/postfix increment and decrement now work inside expressions. The generated code preserves the old value for postfix, stores the updated element, then returns the old value; prefix returns the new value. A separate compiled app verifies both value rules at runtime. It is kept separate from the larger array loop test so both remain below the 511-word RAM-file cap. The kernel is 45,299 words, ending at `0xB3F3` with 1,037 words before the legacy window. OS/compiler suite: 1,754 checks passed.
The bob32 resident parser now accepts comma-separated local scalar and fixed-array declarators, each with its own initializer. Runtime coverage combines an initialized array and scalar, and initializes a scalar from an array postfix expression in the same declaration. The 45,331-word kernel ends at `0xB413`, leaving 1,005 words before the `0xB800` legacy window. OS/compiler suite: 1,754 checks passed.
The bob32 resident parser now accepts `int` function prototypes with named or unnamed integer parameters, permits unused declarations without definitions, and checks prototype/definition and prototype/call argument counts. A shell integration compiles a prototype-before-definition call and an unused unnamed-parameter declaration, runs it, and rejects conflicting prototypes. The 45,486-word kernel ends at `0xB4AE`, leaving 850 words before the `0xB800` legacy window. OS/compiler suite: 1,758 checks passed.
Resident bob32 C now supports local function pointers returning `int` and accepting integer arguments. A pointer can be initialized from a function declared by prototype and called indirectly; the integration fixture checks the result, `bob!` output and exit code. The kind-1 compatibility window moved to `0xBA00..0xBFFF` because the kernel reached 46,733 words (`0xB98D` end), leaving 115 words for growth. Emulator bounds, guest loader, storage limit, CPU fixtures and memory-map docs were updated together. Suites: CPU 191, OS/compiler 1,761, console 28.
Function-pointer initialization and assignment now require a previously declared function with a matching argument count; compatible local function pointers can be copied, and null `0` is supported. Mismatched signatures and integer values are rejected. Kernel growth required moving bob32 compatibility apps to `0xC000..0xCFFF` and the B32 heap to `0xD000..0xDFFF`; bob16 applications move to `0xA000` so its enlarged kernel still fits, with only its dedicated `0x9800..0x980F` compiler-variable area additionally writable by supervised apps. B16 image limits, storage descriptor checks, shell heap bounds, docs and CPU/OS regressions were aligned. Current images: B16 36,325 words (ends `0x90E4`); B32 48,185 words (ends `0xBF38`). Suites: CPU 194, OS/compiler 1,764; console: 28 checks passed.
Resident bob32 now distinguishes `int f()` from the zero-argument prototype `int f(void)`. A no-prototype declaration can be refined by a typed declaration or later definition; calls before that definition are checked against its eventual parameter count to preserve this calling convention. End-to-end tests cover a valid call through `int loose()` and rejection when a one-argument call precedes a two-argument definition. B32 image: 48,185 words, ending at `0xBF38` with 199 words before the compatibility window. Full suites: CPU 194, OS/compiler 1,764, console 28.
The bob32 resident compiler now recognizes `print`, `println`, `print_dec` and `print_hex` as kernel functions without requiring source prototypes. A regression runs `write bobs.c int main(void){println("Bob!");return 0;}` followed by `go bobs.c` and verifies `Bob!` with exit status 0. This kernel growth moves the bob32 compatibility-app window to `0xC200..0xCFFF`; the emulator protects that window from writes below it. Current B32 image: 48,645 words, ending at `0xC164`.
The bob32 resident compiler now stages generated code at the native application origin and can save output up to the available packed filesystem capacity; bob16 retains its 511-word code limit. A shell integration compiles a compact source into a 1,289-word resident app, runs it to print `bob!`, snapshots the filesystem, restores the snapshot, and runs the stored app again. Full suites: CPU 203, OS/compiler 1,822, console 28.
The bob32 resident compiler now adjusts one-dimensional `int values[]` (and fixed-bound parameter spellings) to a single word-addressed pointer argument using the existing stack ABI. Helpers can index and mutate caller arrays, forward an array to nested helper calls, and combine it with scalar parameters. Regression coverage computes a sum, increments elements in a second helper, calls the sum helper repeatedly, and prints `bob!`; negative cases reject scalar/array argument mismatches, conflicting prototypes, and multidimensional parameter syntax. Full suites: CPU 203, OS/compiler 1,825, console 28.
Added app-side `bob_string.h` helpers for length/copy/compare/concatenate/search, whitespace checks, signed decimal and hexadecimal parsing with overflow reporting, integer formatting with capacity checks, and in-place quoted command tokenization. A bob32 runtime fixture covers integer limits, malformed input, quoting and escapes; a compact native app imports into bob32 RAM files, prints `bob!`, survives a B32S snapshot restore, and runs again. Full suites: CPU 203, OS/compiler 1,840, console 28.
The host-compiled C workflow now includes `<stdbool.h>` backed by the tested `_Bool` type. B16 and B32 guest fixtures verify `bool`, `true` and `false` at runtime and print `bob!`. GCC `-fanalyzer` reported no diagnostics in the emulator, compiler or test sources. At this point suites were CPU 194, OS/compiler 1,769, console 28.
Added `<stddef.h>` with width-matched `size_t`/`ptrdiff_t` and `NULL`. `sizeof` now has unsigned type in expression and type-name forms. Native B16/B32 fixtures verify array size, pointer subtraction, null initialization and unsigned `sizeof` arithmetic. Full suite: CPU 194, OS/compiler 1,773, console 28.
Host C now supports typed function-pointer declarations and calls, including local/file-scope pointers, nested pointer parameters, function-address relocations, copying, and parenthesized indirect calls. Empty `()` signatures accept unspecified call arguments; typed signatures enforce argument count and compatibility. B16/B32 positive and negative regressions cover these behaviors, including invalid casts between function and object pointers. Full suite: CPU 194, OS/compiler 1,793, console 28.
Native bob32 application workflow: the RAM filesystem packs eight file slots into 4,096 words, allowing validated B32K v2 images larger than 511 words. `import32 HOST_PATH NAME` stores an image, `run NAME` or `run32 NAME` executes it from guest RAM, and B32S v2 snapshots preserve it; B32S v1 fixed-slot snapshots convert on restore. Integration tests import a 629-word image, execute it through both guest-name commands, save/restore, and execute again. Failure coverage checks missing, invalid and truncated images, storage-capacity exhaustion, checksum corruption and sparse-memory allocation failure. The expanded bob32 kernel now runs at `0x10000..0x1D115`, with native applications starting at `0x20000`. Resident compiler diagnostics include token context with the existing source location. Full suite: CPU 203, OS/compiler 1,813, console 28.
+380
View File
@@ -0,0 +1,380 @@
/* CPU migration checks; include the real implementation rather than a model. */
#ifndef _WIN32
#define _POSIX_C_SOURCE 200809L
#endif
#define BOB_TESTING
#define main bob_emulator_main
#include "../main.c"
#undef main
#include <limits.h>
#define TEST_APP_BASE 0x20000u
static int checks;
static int storage_path(const char *path) {
#ifdef _WIN32
return _putenv_s("BOB16_STORAGE",path);
#else
return *path?setenv("BOB16_STORAGE",path,1):unsetenv("BOB16_STORAGE");
#endif
}
static void verify(int okay,const char *what) {
checks++;if(!okay){fprintf(stderr,"CPU check failed: %s\n",what);exit(1);}
}
static void reset_cpu(int wide) {memoryReset();memset(&cpu,0,sizeof(cpu));memset(&ram,0,sizeof(ram));cpu32=wide;programMode=false;application32=false;legacyProgram32=false;}
static void step(unsigned instruction) {ram.memory[cpu.pc]=instruction;cpuCycle();}
static void put16(FILE *f,unsigned value) {fputc(value&255,f);fputc((value>>8)&255,f);}
static void put32(FILE *f,uint32_t value) {put16(f,value);put16(f,value>>16);}
static int assembly_text(const char *text) {
FILE *f=tmpfile();if(!f)exit(1);fputs(text,f);rewind(f);
reset_cpu(0);int result=assembleSource(f);fclose(f);return result;
}
static int assembly_bytes(const unsigned char *data,size_t length) {
FILE *f=tmpfile();if(!f)exit(1);
if(fwrite(data,1,length,f)!=length){fclose(f);exit(1);}
rewind(f);reset_cpu(0);int result=assembleSource(f);fclose(f);return result;
}
static void bad_image(const char *executable,const unsigned char *bytes,size_t length) {
FILE *f=fopen("build/cpu-bad.b32","wb");if(!f)exit(1);
if(fwrite(bytes,1,length,f)!=length || fclose(f))exit(1);
char command[4096];snprintf(command,sizeof(command),"\"%s\" --load-fixture build/cpu-bad.b32 > build/cpu-bad.out 2>&1",executable);
verify(system(command)!=0,"invalid wide image rejected");
}
int main(int argc,char **argv) {
if(argc>1 && !strcmp(argv[1],"--emulator"))return bob_emulator_main(argc-1,argv+1);
if(argc==3 && !strcmp(argv[1],"--load-fixture")){bootImage(argv[2]);return 0;}
if(argc==3 && !strcmp(argv[1],"--disk-argument-fixture")) {
int argument=argv[2][0]-'0';if(argument<0 || argument>2)return 2;
reset_cpu(1);bootMode=true;bootWords=1;bootDisk[0]=42;
cpu.regFile[0]=argument==0?0x10000:0x300;cpu.regFile[1]=0;cpu.regFile[2]=1;
cpu.regFile[argument]|=0x10000;step(0xf400);
return argument==0 && memoryRead(0x10000)!=42?1:0;
}
if(argc==2 && !strcmp(argv[1],"--puts-fixture")) {
reset_cpu(1);cpu.regFile[0]=0x10000;
memoryWrite(0x10000,0x10000);memoryWrite(0x10001,'b');memoryWrite(0x10002,'o');
memoryWrite(0x10003,'b');memoryWrite(0x10004,'!');step(0xf200);
return cpu.ir==0xf200?0:1;
}
for(unsigned bits=1;bits<=16;bits++) {
verify(sext((int16_t)((1u<<bits)-1),bits)==-1,"negative immediate");
verify(sext((int16_t)((1u<<(bits-1))-1),bits)==(int)((1u<<(bits-1))-1),"positive immediate");
}
unsigned long limit=123;
const char *invalid_limits[]={"","0","-1","+1"," 1","1 ","1x","999999999999999999999999999999999999999999"};
for(unsigned i=0;i<sizeof(invalid_limits)/sizeof(invalid_limits[0]);i++) {
verify(!parseCycleLimit(invalid_limits[i],&limit) && limit==123,"invalid cycle limit leaves output intact");
}
verify(parseCycleLimit("1",&limit) && limit==1,"minimum cycle limit");
char maximum[64];snprintf(maximum,sizeof(maximum),"%lu",ULONG_MAX);
verify(parseCycleLimit(maximum,&limit) && limit==ULONG_MAX,"maximum cycle limit");
reset_cpu(0);verify(snapshotService(UINT_MAX,1)==-3,"snapshot descriptor rejects unsigned overflow");
verify(snapshotService(0xf000-3,1)==-3,"snapshot descriptor end bound");
reset_cpu(1);
ram.memory[0x300]=0x400;ram.memory[0x301]=0x500;ram.memory[0x302]=0x510;ram.memory[0x303]=0x520;
ram.memory[0x300]=0x1000400;
verify(snapshotService(0x300,0)==-3,"wide snapshot rejects truncated address in descriptor");
ram.memory[0x300]=0x400;
cpu.regFile[0]=0x1000300;cpu.regFile[1]=0;step(0xf700);
verify(cpu.regFile[0]==-3,"wide storage trap rejects truncated descriptor address");
ram.memory[0x400]='b';ram.memory[0x401]='o';ram.memory[0x402]='b';ram.memory[0x403]='!';
ram.memory[0x500]=1;ram.memory[0x510]=1;ram.memory[0x520]=1;ram.memory[0xf000]=0x12345678;ram.memory[0xf001]=0;
const char *source_name="bobs.c",*source_text="bob!";
for(unsigned i=0;source_name[i];i++)ram.memory[0x418+i]=source_name[i];
ram.memory[0x501]=4;ram.memory[0x521]=1;
for(unsigned i=0;source_text[i];i++)ram.memory[0xf002+i]=source_text[i];
ram.memory[0xf006]=0;
if(storage_path("build/cpu-snapshot.b32"))return 1;
verify(snapshotService(0x300,0)==0,"wide snapshot save");
ram.memory[0xf000]=0;
verify(snapshotService(0x300,1)==0 && ram.memory[0xf000]==0x12345678,"wide snapshot restores all 32 bits");
FILE *saved=fopen("build/cpu-snapshot.b32","r+b");if(!saved)return 1;
if(fseek(saved,16+216*4+3,SEEK_SET))return 1;
if(fputc(0x13,saved)==EOF || fclose(saved))return 1;
ram.memory[0xf000]=42;
verify(snapshotService(0x300,1)==-2 && ram.memory[0xf000]==42,"wide snapshot checksum protects upper byte and RAM");
ram.memory[0xf000]=0x12345678;
verify(snapshotService(0x300,0)==0,"wide snapshot resave");
FILE *old_snapshot=fopen("build/cpu-snapshot.b32","r+b");if(!old_snapshot)return 1;
uint32_t old_words[SNAP_WORDS];if(fseek(old_snapshot,16,SEEK_SET))return 1;
for(unsigned i=0;i<SNAP_WORDS;i++){unsigned char b[4];if(fread(b,1,4,old_snapshot)!=4)return 1;old_words[i]=(uint32_t)b[0]|((uint32_t)b[1]<<8)|((uint32_t)b[2]<<16)|((uint32_t)b[3]<<24);}
for(unsigned i=0;i<=4;i++)old_words[216+512+i]=old_words[218+i];
uint32_t old_hash=snapshotHash(old_words,SNAP_WORDS);if(fseek(old_snapshot,4,SEEK_SET)||fputc(1,old_snapshot)==EOF||fseek(old_snapshot,12,SEEK_SET))return 1;
for(unsigned i=0;i<4;i++)if(fputc((old_hash>>(8*i))&255,old_snapshot)==EOF)return 1;
if(fseek(old_snapshot,16,SEEK_SET))return 1;
for(unsigned i=0;i<SNAP_WORDS;i++)for(unsigned b=0;b<4;b++)if(fputc((old_words[i]>>(8*b))&255,old_snapshot)==EOF)return 1;
if(fclose(old_snapshot))return 1;
ram.memory[0xf000]=0;ram.memory[0xf002]=0;
verify(snapshotService(0x300,1)==0 && ram.memory[0xf000]==0x12345678 && ram.memory[0xf002]=='b',"legacy fixed-slot B32S snapshot converts to packed filesystem layout");
cpu32=false;ram.memory[0xf000]=42;
verify(snapshotService(0x300,1)==-2 && ram.memory[0xf000]==42,"legacy rejects wide snapshot without modifying RAM");
cpu32=true;kernelIdentity++;
verify(snapshotService(0x300,1)==1,"wide snapshot reports changed kernel identity");
verify(ram.memory[0x520]==0 && ram.memory[0x521]==1 && ram.memory[0xf000]=='b' && ram.memory[0xf003]=='!',"wide kernel change drops binaries and preserves text");
kernelIdentity--;
if(storage_path(""))return 1;
uint32_t snapshot[SNAP_WORDS]={0};
verify(snapshotValid(snapshot),"empty snapshot metadata");
snapshot[0]='b';snapshot[1]='o';snapshot[2]='b';snapshot[3]='!';snapshot[192]=4;snapshot[208]=1;
snapshot[216]='b';snapshot[217]='o';snapshot[218]='b';snapshot[219]='!';
verify(snapshotValid(snapshot),"valid text snapshot metadata");
snapshot[218]=0;verify(!snapshotValid(snapshot),"text snapshot rejects embedded terminator");snapshot[218]='b';
snapshot[220]=1;verify(!snapshotValid(snapshot),"snapshot rejects missing content terminator");snapshot[220]=0;
snapshot[192]=512;verify(!snapshotValid(snapshot),"snapshot rejects excessive length");snapshot[192]=4;
snapshot[208]=2;verify(!snapshotValid(snapshot),"snapshot rejects invalid used flag");snapshot[208]=1;
snapshot[200]=2;verify(snapshotValid(snapshot),"bob32 snapshots accept native program files");
snapshot[200]=4;verify(!snapshotValid(snapshot),"snapshot rejects invalid kind");snapshot[200]=0;
memcpy(snapshot+24,snapshot,24*sizeof(uint32_t));snapshot[209]=1;
verify(!snapshotValid(snapshot),"snapshot rejects duplicate names");snapshot[209]=0;
verify(assembly_text(".stringz bob!\n.fill 1234\n")==0 && ram.memory[4]==0 && ram.memory[5]==0x1234,"string directive emits exactly one terminator");
verify(assembly_text("add r0 r1 r2\r\n.fill ffff\r\n")==0 && ram.memory[1]==0xffff,"CRLF token separation");
verify(assembly_text(".fill ffffg\n")<0,"fill rejects trailing text");
const unsigned char embedded_nul[]={'.','f','i','l','l',' ','1',0,' ','x','\n'};
verify(assembly_bytes(embedded_nul,sizeof(embedded_nul))<0,"assembly rejects embedded zero byte");
verify(assembly_text(".fill 10000\n")<0,"fill rejects truncation");
verify(assembly_text(".fill -1\n")<0,"fill rejects signed text");
verify(assembly_text("nop\n.fill 1234\n")==0 && ram.memory[0]==0 && ram.memory[1]==0x1234,"documented nop assembles");
verify(assembly_text("nop r0\n")<0,"nop rejects operands");
char boundary_source[300];memset(boundary_source,' ',252);strcpy(boundary_source+252,"nop\r\n.fill 1234\n");
verify(assembly_text(boundary_source)==0 && ram.memory[0]==0 && ram.memory[1]==0x1234,"exact-limit CRLF source line keeps following instruction");
memset(boundary_source,' ',253);strcpy(boundary_source+253,"nop\r\n.fill 1234\n");
verify(assembly_text(boundary_source)<0,"source line over the limit remains rejected");
const char *bad_operands[]={"add r0 r1 r8\n","add r0 bogus\n","and r0 r1 1x\n","and r0 r9\n",
"not r0 r8\n","not r0 r1 ignored\n","not\n","ld r0 bogus\n","ld r8 0\n","ld xx 0\n",
"ldi r8 0\n","ldr r0 r8 0\n","ldr r8 r0 0\n","ldr r0 r1 --1\n",
"st r8 0\n","st xx 0\n","st r0 1x\n","sti r8 0\n","sti r0 bogus\n",
"str r8 r0 0\n","str r0 r8 0\n","str r0 r1 r8\n","br np 1x\n","jsr bogus\n","lea r0 bogus\n",
"trap nonsense\n","trap 12\n","trap 15\n",
"br nx 1\n","add r0 999999999999999999999\n"};
for(unsigned i=0;i<sizeof(bad_operands)/sizeof(bad_operands[0]);i++)verify(assembly_text(bad_operands[i])<0,"invalid instruction operand rejected");
verify(assembly_text("add r0 100\nadd r0 -100\njsr -1\njsrr r3\n")==0 && ram.memory[0]==0x11bf && ram.memory[1]==0x11c0 && ram.memory[2]==0xcfff && ram.memory[3]==0xc300,"decimal clamping and call encodings preserved");
int immediate=7;
verify(parseImmediate("+123",&immediate) && immediate==123,"signed decimal operand");
verify(!parseImmediate("-",&immediate) && immediate==123,"missing digits reject without modifying result");
char oversized[300];memset(oversized,' ',sizeof(oversized));memcpy(oversized,".fill 1",7);oversized[298]='\n';oversized[299]=0;
verify(assembly_text(oversized)<0,"oversized physical line rejects before splitting");
FILE *full=tmpfile();if(!full)return 1;
for(unsigned i=0;i<65536;i++)fputs(".fill 0\n",full);
rewind(full);reset_cpu(0);verify(assembleSource(full)==0,"full address-space assembly fits exactly");fclose(full);
full=tmpfile();if(!full)return 1;
for(unsigned i=0;i<65535;i++)fputs(".fill 0\n",full);
fputs(".stringz bob!\n",full);rewind(full);reset_cpu(0);
verify(assembleSource(full)==-7 && ram.memory[65535]==0,"oversized string rejected before writing");fclose(full);
reset_cpu(0);cpu.regFile[0]=32767;step(0x1181);
verify(cpu.regFile[0]==-32768 && cpu.cc[N],"bob16 wrap and negative flag");
reset_cpu(1);cpu.regFile[0]=32767;step(0x1181);
verify(cpu.regFile[0]==32768 && cpu.cc[P],"bob32 crosses 16-bit boundary");
cpu.regFile[0]=INT32_MAX;step(0x1181);
verify(cpu.regFile[0]==INT32_MIN && cpu.cc[N],"bob32 wraps at 32 bits");
cpu.regFile[0]=-1;step(0x1181);
verify(cpu.regFile[0]==0 && cpu.cc[Z],"32-bit zero flag");
cpu.regFile[0]=0x12345678;cpu.regFile[1]=100;step(0x9040);
verify(ram.memory[100]==0x12345678,"wide store");step(0x6440);
verify(cpu.regFile[2]==0x12345678,"wide load");
reset_cpu(0);cpu.pc=0x8000;step(0xc800);
verify(cpu.regFile[7]==(int16_t)0x8001,"legacy signed return-address register");
reset_cpu(1);cpu.pc=0x8000;step(0xc800);
verify(cpu.regFile[7]==0x8001,"wide return-address register");
reset_cpu(1);memoryWrite(TEST_APP_BASE,0x4001);memoryWrite(TEST_APP_BASE+1,0xe000);memoryWrite(TEST_APP_BASE+2,0x12345678);
cpu.regFile[0]=TEST_APP_BASE;step(0xf600);
verify(cpu.regFile[0]==0x12345678 && cpu.pc==1 && !programMode,"wide supervised return and parent restoration");
reset_cpu(1);memoryWrite(TEST_APP_BASE,0x1000f000);application32=1;
cpu.regFile[2]=42;
verify(runProgram(TEST_APP_BASE)==-2 && cpu.regFile[2]==42 && cpu.pc==0 && !programMode,"wide instruction upper bits fault and restore parent");
application32=0;
reset_cpu(0);ram.memory[0xa000]=(int16_t)0xe000;
verify(runProgram(0xa000)==0,"legacy signed instruction representation remains valid");
reset_cpu(0);memoryWrite(0xa000,0x9200);memoryWrite(0xa001,0xf000);cpu.regFile[0]=0x9800;cpu.regFile[1]=42;
verify(runProgram(0xa000)==0x9800 && memoryRead(0x9800)==42,"bob16 applications retain access to resident compiler variable slots");
reset_cpu(0);memoryWrite(0xa000,0x9200);memoryWrite(0xa001,0xf000);cpu.regFile[0]=0x9810;cpu.regFile[1]=42;
verify(runProgram(0xa000)==-2 && memoryRead(0x9810)!=42,"bob16 applications cannot write kernel memory around compiler slots");
const unsigned malformed[]={0x0001,0x1001,0x2001,0x3120,0xc001,0xe001};
reset_cpu(1);cpu.regFile[0]=0x1009000;cpu.regFile[2]=42;memoryWrite(0x10000,0xf600);cpu.pc=0x10000;cpuCycle();
verify(cpu.regFile[0]==-2 && cpu.regFile[2]==42 && !programMode,"wide run trap rejects truncated entry address");
for(unsigned argument=1;argument<2;argument++) {
reset_cpu(1);memoryWrite(TEST_APP_BASE,0xf300);memoryWrite(TEST_APP_BASE+1,0xe000);memoryWrite(0x10010,77);application32=1;
cpu.regFile[0]=0x10010;cpu.regFile[1]=2;cpu.regFile[argument]|=0x10000;
verify(runProgram(TEST_APP_BASE)==-2 && memoryRead(0x10010)==77 && !programMode,"wide input trap rejects truncated arguments before writing");
application32=0;
}
reset_cpu(1);memoryWrite(TEST_APP_BASE,0xf300);memoryWrite(TEST_APP_BASE+1,0xf000);application32=1;
cpu.regFile[0]=TEST_APP_BASE;cpu.regFile[1]=2;
int input_status=runProgram(TEST_APP_BASE);
verify(input_status==TEST_APP_BASE && memoryRead(TEST_APP_BASE)==0,"wide input trap writes to full-width guest address");
application32=0;
reset_cpu(1);cpu.regFile[0]=0x10000;step(0xb000);
verify(cpu.pc==0x10000,"wide JMP preserves 32-bit address");
reset_cpu(1);cpu.regFile[0]=0x10000;step(0xc000);
verify(cpu.pc==0x10000 && cpu.regFile[7]==1,"wide JSRR preserves 32-bit address");
reset_cpu(1);cpu.regFile[7]=0x10000;step(0xe000);
verify(cpu.pc==0x10000,"wide RET preserves 32-bit address");
reset_cpu(1);cpu.regFile[0]=0x12345000;cpu.regFile[1]=0x12345678;step(0x9200);
verify(memoryRead(0x12345000)==0x12345678,"wide STR writes above 64K words");
step(0x6400);verify(cpu.regFile[2]==0x12345678,"wide LDR reads above 64K words");
reset_cpu(1);memoryWrite(0x10000,0x12345678);memoryWrite(0x10100,0x5400);memoryWrite(0x10101,0x10000);
cpu.pc=0x10100;cpuCycle();verify(cpu.regFile[2]==0x12345678,"wide LDI follows full-width pointer");
memoryWrite(0x10200,0x8200);memoryWrite(0x10201,0x10000);cpu.regFile[1]=0x87654321;cpu.pc=0x10200;cpuCycle();
verify(memoryRead(0x10000)==(int32_t)0x87654321u,"wide STI follows full-width pointer");
reset_cpu(1);memoryWrite(TEST_APP_BASE,0x9200);memoryWrite(TEST_APP_BASE+1,0x6400);
memoryWrite(TEST_APP_BASE+2,0x10a0);memoryWrite(TEST_APP_BASE+3,0xf000);
cpu.regFile[0]=0x22345;cpu.regFile[1]=0x12345678;
application32=1;
verify(runProgram(TEST_APP_BASE)==0x12345678 && memoryRead(0x22345)==0x12345678,
"supervised bob32 program reads and writes full-width data addresses");
reset_cpu(1);memoryWrite(TEST_APP_BASE,0xf600);memoryWrite(TEST_APP_BASE+1,0x400e);
memoryWrite(TEST_APP_BASE+2,0x9200);memoryWrite(TEST_APP_BASE+3,0xf000);
memoryWrite(TEST_APP_BASE+0x10,TEST_APP_BASE+0x20);cpu.regFile[0]=TEST_APP_BASE;cpu.regFile[1]=42;application32=1;
int nested_status=runProgram(TEST_APP_BASE);
verify(nested_status==TEST_APP_BASE+0x20 && memoryRead(TEST_APP_BASE+0x20)==42,
"rejected nested run leaves native application memory mode intact");
application32=0;
reset_cpu(1);memoryWrite(TEST_APP_BASE,0x9200);memoryWrite(TEST_APP_BASE+1,0xf000);
cpu.regFile[0]=0xfffff;cpu.regFile[1]=0x12345678;application32=1;
verify(runProgram(TEST_APP_BASE)==0xfffff && memoryRead(0xfffff)==0x12345678,
"supervised bob32 program may write the last word in its region");
const uint32_t forbidden_app_addresses[]={0xffff,0x10000,0x1ffff,0x100000,0x110000,0x12345000,UINT32_MAX};
for(unsigned i=0;i<sizeof(forbidden_app_addresses)/sizeof(forbidden_app_addresses[0]);i++) {
reset_cpu(1);memoryWrite(TEST_APP_BASE,0x9200);memoryWrite(TEST_APP_BASE+1,0xf000);
cpu.regFile[0]=(int32_t)forbidden_app_addresses[i];cpu.regFile[1]=0x76543210;application32=1;
verify(runProgram(TEST_APP_BASE)==-2 && memoryRead(forbidden_app_addresses[i])!=0x76543210,
"supervised bob32 store rejects addresses outside app and stack region");
}
application32=0;
reset_cpu(1);bootWideHeader=false;bootOrigin=0;bootWords=0;memoryWrite(0xc200,0xd002);memoryWrite(0xc201,0xf200);memoryWrite(0xc202,0xf000);
memoryWrite(0xc203,'b');memoryWrite(0xc204,'o');memoryWrite(0xc205,'b');memoryWrite(0xc206,'!');memoryWrite(0xc207,0);
verify(runProgram(0xc200)==33 && !programMode,"bob32 kernel runs a legacy 16-bit program outside its image");
verify(runProgram(0x9000)==-1 && runProgram(0xb000)==-1 && runProgram(0xb800)==-1,"bob32 kernel rejects legacy entries that overlap kernel image or reserved gap");
reset_cpu(1);bootWideHeader=false;bootOrigin=0;bootWords=0;memoryWrite(0xc200,0x9200);memoryWrite(0xc201,0xf000);
cpu.regFile[0]=0xc200;cpu.regFile[1]=0x1234;
verify(runProgram(0xc200)==0xc200 && memoryRead(0xc200)==0x1234,"bob32 legacy app may store at the first reserved program word");
reset_cpu(1);memoryWrite(0xc200,0x9200);memoryWrite(0xc201,0xf000);cpu.regFile[0]=0xc1ff;cpu.regFile[1]=0x5678;
verify(runProgram(0xc200)==-2 && memoryRead(0xc1ff)!=0x5678,"bob32 legacy app cannot write below its relocated region");
reset_cpu(1);memoryWrite(0xc200,0x9200);memoryWrite(0xc201,0xf000);cpu.regFile[0]=0xd000;cpu.regFile[1]=0x5678;
verify(runProgram(0xc200)==0xd000 && memoryRead(0xd000)==0x5678,"bob32 legacy app retains shared heap data access");
reset_cpu(0);cpu.regFile[0]=0x10000;cpu.regFile[1]=42;step(0x9200);
verify(ram.memory[0]==42,"legacy STR retains 16-bit address wrapping");
for(unsigned wide=0;wide<2;wide++)for(unsigned i=0;i<sizeof(malformed)/sizeof(malformed[0]);i++) {
reset_cpu(wide);if(wide)application32=1;cpu.regFile[2]=42;uint32_t entry=wide?TEST_APP_BASE:0xa000;memoryWrite(entry,wordValue(malformed[i]));
verify(runProgram(entry)==-2 && cpu.regFile[2]==42 && cpu.pc==0 && !programMode,"reserved instruction bits fault and restore parent");
application32=0;
}
char command[4096];
snprintf(command,sizeof(command),"\"%s\" --disk-argument-fixture 0 > build/cpu-disk-argument.out 2>&1",argv[0]);
verify(system(command)==0,"wide boot disk trap writes to full-width destination");
for(unsigned argument=1;argument<3;argument++) {
snprintf(command,sizeof(command),"\"%s\" --disk-argument-fixture %u > build/cpu-disk-argument.out 2>&1",argv[0],argument);
verify(system(command)!=0,"wide boot disk trap rejects truncated arguments");
FILE *fault=fopen("build/cpu-disk-argument.out","rb");if(!fault)return 1;
char diagnostic[256];size_t used=fread(diagnostic,1,sizeof(diagnostic)-1,fault);fclose(fault);diagnostic[used]=0;
verify(strstr(diagnostic,"Invalid boot disk argument")!=NULL,"disk argument fixture reaches the intended trap fault");
}
snprintf(command,sizeof(command),"\"%s\" --puts-fixture > build/cpu-puts.out",argv[0]);
verify(system(command)==0,"wide string trap preserves instruction state");
FILE *output=fopen("build/cpu-puts.out","rb");if(!output)return 1;
unsigned char bytes[7];size_t length=fread(bytes,1,sizeof(bytes),output);fclose(output);
#ifdef _WIN32
verify(length==7 && !memcmp(bytes,"\0bob!\r\n",7),"wide string terminator compares entire word");
#else
verify(length==6 && !memcmp(bytes,"\0bob!\n",6),"wide string terminator compares entire word");
#endif
FILE *f=fopen("build/cpu-wide.b32","wb");if(!f)return 1;
uint32_t words[]={0x4001,0,0x12345678};unsigned sum=0;
for(unsigned i=0;i<3;i++)sum+=words[i];
fwrite("B32K",1,4,f);put16(f,1);put16(f,0x300);put16(f,0x300);put16(f,3);put16(f,sum);put16(f,sum>>16);
for(unsigned i=0;i<3;i++){put16(f,words[i]);put16(f,words[i]>>16);}fclose(f);
unsigned char image[29];f=fopen("build/cpu-wide.b32","rb");if(!f)return 1;
verify(fread(image,1,28,f)==28,"wide fixture length");fclose(f);
bad_image(argv[0],image,14);bad_image(argv[0],image,27);
image[12]^=1;bad_image(argv[0],image,28);image[12]^=1;
image[28]=0;bad_image(argv[0],image,29);
unsigned char entry=image[8];image[8]=0xff;image[9]=0xff;bad_image(argv[0],image,28);image[8]=entry;image[9]=3;
image[4]=2;bad_image(argv[0],image,28);image[4]=1;
bootImage("build/cpu-wide.b32");
verify(cpu32 && bootDisk[2]==0x12345678,"wide image loader");
for(unsigned i=0;i<6;i++)cpuCycle();
verify(cpu.pc==0x300 && ram.memory[0x302]==0x12345678,"wide guest boot disk transfer");
cpuCycle();verify(cpu.regFile[0]==0x12345678,"wide image native execution");
f=fopen("build/cpu-wide-v2.b32","wb");if(!f)return 1;
uint32_t wide_words[]={0x1080,0x12345678};uint32_t wide_sum=wide_words[0]+wide_words[1];
fwrite("B32K",1,4,f);put16(f,2);put16(f,24);put32(f,0x10000);put32(f,0x10000);
put32(f,2);put32(f,wide_sum);put32(f,wide_words[0]);put32(f,wide_words[1]);fclose(f);
bootImage("build/cpu-wide-v2.b32");
verify(cpu32 && cpu.pc==0x10000 && memoryRead(0x10001)==0x12345678,"B32K v2 loads at a 32-bit origin and entry");
cpuCycle();verify(cpu.pc==0x10001 && cpu.regFile[0]==0,"B32K v2 executes at a high address");
unsigned char v2_image[33];f=fopen("build/cpu-wide-v2.b32","rb");if(!f)return 1;
verify(fread(v2_image,1,32,f)==32,"B32K v2 fixture length");fclose(f);v2_image[32]=0;
bad_image(argv[0],v2_image,23);
v2_image[4]=3;bad_image(argv[0],v2_image,32);v2_image[4]=2;
v2_image[6]=22;bad_image(argv[0],v2_image,32);v2_image[6]=24;
for(unsigned i=8;i<16;i++)v2_image[i]=0xff;
bad_image(argv[0],v2_image,32);
v2_image[8]=0;v2_image[9]=0;v2_image[10]=1;v2_image[11]=0;
v2_image[12]=0;v2_image[13]=0;v2_image[14]=1;v2_image[15]=0;
v2_image[12]=0;v2_image[13]=0;v2_image[14]=2;v2_image[15]=0;bad_image(argv[0],v2_image,32);v2_image[12]=0;v2_image[13]=0;v2_image[14]=1;v2_image[15]=0;
v2_image[16]=1;v2_image[17]=0;v2_image[18]=1;v2_image[19]=0;bad_image(argv[0],v2_image,32);v2_image[16]=2;v2_image[17]=0;v2_image[18]=0;v2_image[19]=0;
v2_image[31]^=1;bad_image(argv[0],v2_image,32);v2_image[31]^=1;
bad_image(argv[0],v2_image,33);
for(unsigned i=8;i<16;i++)v2_image[i]=0xff;
v2_image[8]=0xfe;v2_image[12]=0xfe;
f=fopen("build/cpu-wide-v2-edge.b32","wb");if(!f)return 1;
if(fwrite(v2_image,1,32,f)!=32 || fclose(f))return 1;
bootImage("build/cpu-wide-v2-edge.b32");
verify(cpu.pc==0xfffffffeu && memoryRead(0xffffffffu)==0x12345678,"B32K v2 accepts the final two addressable words");
cpuCycle();verify(cpu.pc==0xffffffffu,"B32K v2 executes across the top of the address space");
snprintf(command,sizeof(command),"\"%s\" --emulator --boot build/cpu-wide-v2-edge.b32 --max-cycles 1 > build/cpu-v2-limit.out 2>&1",argv[0]);
#ifdef _WIN32
verify(system(command)==2,"command-line B32K v2 boot honors cycle limit");
#else
verify(system(command)==512,"command-line B32K v2 boot honors cycle limit");
#endif
snprintf(command,sizeof(command),"\"%s\" --emulator --boot build/cpu-wide.b32 --max-cycles 1 > build/cpu-limit.out 2>&1",argv[0]);
#ifdef _WIN32
verify(system(command)==2,"command-line cycle limit exit status");
#else
verify(system(command)==512,"command-line cycle limit exit status");
#endif
f=fopen("build/cpu-page-fail.b32","wb");if(!f)return 1;
fwrite("B32K",1,4,f);put16(f,2);put16(f,24);put32(f,0x20000);put32(f,0x20000);
put32(f,1);put32(f,0xf000);put32(f,0xf000);if(fclose(f))return 1;
reset_cpu(1);const char *page_fail_path="build/cpu-page-fail.b32";
for(unsigned i=0;page_fail_path[i];i++)memoryWrite(0x100+i,page_fail_path[i]);
failNextSparsePageAllocation=1;
verify(runWideImageFromGuest(0x100)==-5 && memoryPage(0x20,0)==NULL && memoryRead(0x20000)==0,
"B32 app image allocation failure leaves its sparse region untouched");
reset_cpu(1);ram.memory[0x300]=0xf000;ram.memory[0x301]=7;
ram.memory[0xf000]=0x4233324b;ram.memory[0xf001]=0x00180002;ram.memory[0xf002]=0x20000;ram.memory[0xf003]=0x20000;
ram.memory[0xf004]=1;ram.memory[0xf005]=0xe000;ram.memory[0xf006]=0xe000;
verify(runWidePackedFromGuest(0x300)==0,"native app loads and executes from packed guest RAM image");
reset_cpu(1);ram.memory[0x300]=0xf000;ram.memory[0x301]=7;
ram.memory[0xf000]=0x4233324b;ram.memory[0xf001]=0x00180002;ram.memory[0xf002]=0x20000;ram.memory[0xf003]=0x20000;
ram.memory[0xf004]=1;ram.memory[0xf005]=0xe000;ram.memory[0xf006]=0;
verify(runWidePackedFromGuest(0x300)==-4,"native app checksum corruption rejected before execution");
reset_cpu(1);ram.memory[0x300]=0xf000;ram.memory[0x301]=7;
ram.memory[0xf000]=0x4233324b;ram.memory[0xf001]=0x00180002;ram.memory[0xf002]=0x20000;ram.memory[0xf003]=0x20000;
ram.memory[0xf004]=1;ram.memory[0xf005]=0xe000;ram.memory[0xf006]=0xe000;failNextSparsePageAllocation=1;
verify(runWidePackedFromGuest(0x300)==-5 && memoryPage(0x10,0)==NULL,"native app reports insufficient sparse memory without partial load");
f=fopen("build/cpu-import.b32","wb");if(!f)return 1;
fwrite("B32K",1,4,f);put16(f,2);put16(f,24);put32(f,0x20000);put32(f,0x20000);put32(f,1);put32(f,0xe000);put32(f,0xe000);if(fclose(f))return 1;
reset_cpu(1);const char *import_path="build/cpu-import.b32";
for(unsigned i=0;import_path[i];i++)ram.memory[0x100+i]=import_path[i];
ram.memory[0x300]=0x100;ram.memory[0x301]=0xf000;ram.memory[0x302]=7;ram.memory[0xf000]=99;
verify(importWideImageFromGuest(0x300)==-5 && ram.memory[0xf000]==99,"native image import reports insufficient filesystem capacity without overwriting it");
ram.memory[0x302]=8;
verify(importWideImageFromGuest(0x300)==7 && ram.memory[0xf006]==0xe000,"native image import validates and packs a B32K v2 image");
ram.memory[0x310]=0xf000;ram.memory[0x311]=7;
verify(runWidePackedFromGuest(0x310)==0,"imported native image executes from packed filesystem storage");
bootImage("build/kernel.b16");verify(!cpu32,"legacy image selects compatibility mode");
f=fopen("build/cpu-input.basm","w");if(!f)return 1;
fputs("lea r0 2\ntrap 2\ntrap 0\n.stringz bob!\n",f);fclose(f);
f=fopen("build/cpu-input.in","wb");if(!f)return 1;
for(int i=0;i<255;i++)fputc('x',f);
fputs("\r\n",f);
for(int i=0;i<300;i++)fputc('x',f);
fputs("\nbuild/cpu-input.basm\n",f);fclose(f);
snprintf(command,sizeof(command),"\"%s\" --emulator < build/cpu-input.in > build/cpu-input.out 2>&1",argv[0]);
verify(system(command)==0,"assembly prompt recovers after oversized file name");
f=fopen("build/cpu-input.out","rb");if(!f)return 1;
char prompt_output[4096];size_t prompt_length=fread(prompt_output,1,sizeof(prompt_output)-1,f);fclose(f);prompt_output[prompt_length]=0;
verify(strstr(prompt_output,"Source file name exceeds 255 characters!") && strstr(prompt_output,"Starting execution!") && strstr(prompt_output,"bob!"),"oversized file name is consumed before next input");
char *first_long=strstr(prompt_output,"Source file name exceeds 255 characters!");
verify(first_long && !strstr(first_long+1,"Source file name exceeds 255 characters!"),"exact-limit CRLF filename is not reported as oversized");
puts("bob!");printf("%d CPU checks passed.\n",checks);return 0;
}
+892 -4
View File
@@ -9,12 +9,19 @@
#else
#define BOB "bob.exe"
#endif
#ifdef BOB_VERIFY
#define BOB32 "build\\bob32-next.exe"
#else
#define BOB32 "bob32.exe"
#endif
#define COMPILER "build\\bobcc.exe"
#else
#define BOB "./bob"
#define BOB32 "./bob32"
#define COMPILER "./build/bobcc"
#endif
static int checks;
static void storage_path(const char *path);
static void fail(const char *message) { fprintf(stderr,"Check failed: %s\n",message);exit(1); }
static void check(int condition,const char *message) { checks++;if(!condition)fail(message); }
static void write_text(const char *path,const char *text) {
@@ -43,6 +50,139 @@ static void guest(const char *source) {
check(system(BOB " --boot build/check.b16 --max-cycles 50000000 < build/check.in > build/check.out 2> build/check.err")==0,"guest execution");
char *output=read_text("build/check.out");check(!strcmp(output,"bob!\n"),"guest success marker");free(output);
}
static void guest32(const char *source) {
write_text("build/wide-lib.c",source);
check(system("gcc -E -P -nostdinc -undef -DBOBC_LEGACY=0 -I kernel build/wide-lib.c -o build/wide-lib.i > build/compiler.log 2>&1")==0,"bob32 library guest preprocessing");
check(system(COMPILER " build/wide-lib.i build/wide-lib.basm build/wide-lib.b32 --wide > build/compiler.log 2>&1")==0,"bob32 library guest compilation");
write_text("build/check.in","");
check(system(BOB32 " --boot build/wide-lib.b32 --max-cycles 50000000 < build/check.in > build/check.out 2> build/check.err")==0,"bob32 library guest execution");
char *output=read_text("build/check.out");check(!strcmp(output,"bob!\n"),"bob32 library success marker");free(output);
}
static void native_string_library(void) {
guest32(
"#include \"bob.h\"\n"
"#include \"bob_string.h\"\n"
"int main(void){\n"
"char text[64]=\"Bob\";char output[16];char command[64]=\"notes \\\"my note\\\" escaped\\\\ token\";\n"
"char malformed[24]=\"broken \\\"quote\";char *found;char *cursor;char *token;int valid;int parsed;\n"
"if(bob_strlen(text)!=3||bob_strcpy(text,\"Bob\")!=text)return 1;\n"
"if(bob_strcat(text,\"!\")!=text||bob_strcmp(text,\"Bob!\"))return 2;\n"
"found=bob_strchr(text,'!');if(!found||found-text!=3)return 3;\n"
"if(!bob_isspace('\\t')||bob_isspace('x'))return 4;\n"
"parsed=bob_parse_int(\" \\t-2147483648 \",&valid);if(!valid||parsed!=(-2147483647-1))return 5;\n"
"if(bob_format_int(parsed,output,16)!=11||bob_strcmp(output,\"-2147483648\"))return 6;\n"
"if(bob_format_int(-42,output,3)!=-1)return 7;\n"
"if(bob_parse_int(\"0x2a\",&valid)!=42||!valid)return 8;\n"
"bob_parse_int(\"2147483648\",&valid);if(valid)return 9;\n"
"bob_parse_int(\"12x\",&valid);if(valid)return 10;\n"
"cursor=command;if(bob_token_next(&cursor,&token)!=1||bob_strcmp(token,\"notes\"))return 11;\n"
"if(bob_token_next(&cursor,&token)!=1||bob_strcmp(token,\"my note\"))return 12;\n"
"if(bob_token_next(&cursor,&token)!=1||bob_strcmp(token,\"escaped token\"))return 13;\n"
"if(bob_token_next(&cursor,&token)!=0)return 14;\n"
"cursor=malformed;if(bob_token_next(&cursor,&token)!=1)return 15;\n"
"if(bob_token_next(&cursor,&token)!=-1)return 16;\n"
"bob_puts(\"bob!\");return 0;}\n");
write_text("build/string-app.c",
"#include \"bob.h\"\n#include \"bob_string.h\"\n"
"int main(void){char text[16]=\"Bob\";bob_strcat(text,\"!\");"
"if(bob_strlen(text)==4&&!bob_strcmp(text,\"Bob!\")){bob_puts(\"bob!\");return 0;}return 1;}\n");
check(system("gcc -E -P -nostdinc -undef -DBOBC_LEGACY=0 -I kernel build/string-app.c -o build/string-app.i > build/compiler.log 2>&1")==0,"bob32 string app preprocessing");
check(system(COMPILER " build/string-app.i build/string-app.basm build/string-app.b32 --wide-app > build/compiler.log 2>&1")==0,"bob32 string app compilation");
storage_path("build/string-library-snapshot.b32");
write_text("build/check.in","import32 build/string-app.b32 stringlib\nrun stringlib\nsave\nhalt\n");
check(system(BOB32 " --boot build/kernel32.b32 --max-cycles 50000000 < build/check.in > build/check.out 2> build/check.err")==0,"bob32 stores and runs a native string-library app");
char *output=read_text("build/check.out");contains(output,"Imported native app as stringlib");contains(output,"bob> bob!\nExit 0");contains(output,"Files saved to bob-files.b32");free(output);
write_text("build/check.in","restore yes\nrun stringlib\nhalt\n");
check(system(BOB32 " --boot build/kernel32.b32 --max-cycles 50000000 < build/check.in > build/check.out 2> build/check.err")==0,"bob32 string-library app survives snapshot restore");
output=read_text("build/check.out");contains(output,"Files restored;");contains(output,"bob> bob!\nExit 0");free(output);
write_text("build/argv-app.c",
"#include \"bob.h\"\n#include \"bob_string.h\"\n"
"int main(int argc,char **argv){if(argc!=5)return argc;"
"if(bob_strcmp(argv[1],\"Bob OS\")||bob_strcmp(argv[2],\"escaped token\")||bob_strcmp(argv[3],\"\"))return 2;"
"bob_puts(\"bob!\");return 0;}\n");
check(system("gcc -E -P -nostdinc -undef -DBOBC_LEGACY=0 -I kernel build/argv-app.c -o build/argv-app.i > build/compiler.log 2>&1")==0,"bob32 argv app preprocessing");
check(system(COMPILER " build/argv-app.i build/argv-app.basm build/argv-app.b32 --wide-app > build/compiler.log 2>&1")==0,"bob32 argv app compilation");
write_text("build/check.in","import32 build/argv-app.b32 argvapp\nrun argvapp \"Bob OS\" escaped\\ token \"\"\nhalt\n");
check(system(BOB32 " --boot build/kernel32.b32 --max-cycles 50000000 < build/check.in > build/check.out 2> build/check.err")==0,"bob32 passes quoted arguments to native apps");
output=read_text("build/check.out");contains(output,"bob> bob!\nExit 0");free(output);
storage_path("build/snapshot.b16");
}
static void wide_guest(void) {
write_text("build/wide-check.c",
"#include \"bob.h\"\n"
"#include <stdbool.h>\n"
"#include <stddef.h>\n"
"int combine_values(int a,int b){return a+b;}\n"
"int double_value(int value){return value*2;}\n"
"int (*combine)(int,int)=combine_values;\n"
"int apply_value(int (*operation)(int),int value){return operation(value);}\n"
"int main(void) { int x=0x12345678; if(x+1!=0x12345679)return 1; "
"bool enabled=true; if(!enabled || false)return 10; enabled=false; if(enabled)return 11; "
"int values[3];size_t words=sizeof values;ptrdiff_t distance=&values[2]-&values[0];int *empty=NULL; "
"if(words!=3 || distance!=2 || empty!=NULL || (sizeof(int)-2)!=(size_t)-1)return 12; "
"if(combine(4,5)!=9)return 13; "
"int (*scale)(int (*)(int),int)=apply_value; if(scale(double_value,7)!=14)return 14; "
"if(-x!=-305419896)return 2; if((0x70000000+0x70000000)!=0xe0000000)return 3; "
"if(0x70000000*2!=0xe0000000)return 4; "
"if(0x70000000/7!=0x10000000 || 0x70000000%7)return 5; "
"if(-123456789/12345!=-10000 || -123456789%12345!=-6789)return 6; "
"if(0xf0000000u/3u!=0x50000000u || 0xf0000000u%3u)return 7; "
"if(0x80000000u>>1!=0x40000000u || (-8>>2)!=-2)return 8; "
"if((0xf0000000u>0x10000000u)==0)return 9; "
"bob_puts(\"bob!\"); return 0; }\n");
check(system("gcc -E -P -nostdinc -undef -DBOBC_LEGACY=0 -I kernel build/wide-check.c -o build/wide-check.i > build/compiler.log 2>&1")==0,"wide guest preprocessing");
check(system(COMPILER " build/wide-check.i build/wide-check.basm build/wide-check.b32 --wide > build/compiler.log 2>&1")==0,"wide guest compilation");
FILE *image=fopen("build/wide-check.b32","rb");if(!image)fail("cannot read wide image");
char magic[4];check(fread(magic,1,4,image)==4 && !memcmp(magic,"B32K",4),"wide compiler emits B32K");
check(fgetc(image)==2 && fgetc(image)==0,"wide compiler emits B32K v2");fclose(image);
write_text("build/check.in","");
check(system(BOB " --boot build/wide-check.b32 --max-cycles 50000000 < build/check.in > build/check.out 2> build/check.err")==0,"wide guest execution");
char *output=read_text("build/check.out");check(!strcmp(output,"bob!\n"),"wide guest success marker");free(output);
write_text("build/wide-small.c","#include \"bob.h\"\nint main(void){bob_puts(\"bob!\");return 0;}\n");
check(system("gcc -E -P -nostdinc -undef -DBOBC_LEGACY=0 -I kernel build/wide-small.c -o build/wide-small.i > build/compiler.log 2>&1")==0,"small wide guest preprocessing");
check(system(COMPILER " build/wide-small.i build/wide-small.basm build/wide-small.b32 --wide > build/compiler.log 2>&1")==0,"small wide guest compilation");
image=fopen("build/wide-small.b32","rb");if(!image)fail("cannot read small wide image");
check(fseek(image,0,SEEK_END)==0 && ftell(image)<=24+511*4,"reachable helpers keep small bob32 app within one OS file");fclose(image);
check(system(BOB " --boot build/wide-small.b32 --max-cycles 50000000 < build/check.in > build/check.out 2> build/check.err")==0,"small wide guest execution");
output=read_text("build/check.out");check(!strcmp(output,"bob!\n"),"small wide guest success marker");free(output);
check(system(BOB32 " --asm32 build/wide-small.basm < build/check.in > build/check.out 2> build/check.err")==0,"wide BASM direct assembly and execution");
output=read_text("build/check.out");check(!strcmp(output,"bob!\n"),"wide BASM success marker");free(output);
write_text("build/wide-types.c",
"#include \"bob.h\"\n"
"int main(void){long a=7L;unsigned long b=0xffffffffUL;long long c=3LL;"
"if(sizeof(long)!=1 || sizeof(a)!=1 || sizeof(unsigned long*)!=1 || sizeof(char)!=1 || sizeof(int[3])!=3)return 1;"
"if(a+c!=10 || b>>1!=0x7fffffffUL)return 2;bob_puts(\"bob!\");return 0;}\n");
check(system("gcc -E -P -nostdinc -undef -DBOBC_LEGACY=0 -I kernel build/wide-types.c -o build/wide-types.i > build/compiler.log 2>&1")==0,"wide type guest preprocessing");
check(system(COMPILER " build/wide-types.i build/wide-types.basm build/wide-types.b32 --wide > build/compiler.log 2>&1")==0,"wide long type compilation");
check(system(BOB " --boot build/wide-types.b32 --max-cycles 50000000 < build/check.in > build/check.out 2> build/check.err")==0,"wide type guest execution");
output=read_text("build/check.out");check(!strcmp(output,"bob!\n"),"wide long and sizeof semantics");free(output);
write_text("build/wide-bad.c","int main(void){return 1lul;}\n");
check(system("gcc -E -P -nostdinc -undef build/wide-bad.c -o build/wide-bad.i > build/compiler.log 2>&1")==0,"invalid wide suffix preprocessing");
check(system(COMPILER " build/wide-bad.i build/wide-bad.basm build/wide-bad.b32 --wide > build/compiler.log 2>&1")!=0,"invalid mixed integer suffix rejected");
output=read_text("build/compiler.log");contains(output,"invalid integer suffix");free(output);
write_text("build/wide-app.c","#include \"bob.h\"\nint main(void){bob_puts(\"bob!\");return 0;}\n");
check(system("gcc -E -P -nostdinc -undef -DBOBC_LEGACY=0 -I kernel build/wide-app.c -o build/wide-app.i > build/compiler.log 2>&1")==0,"wide OS app preprocessing");
check(system(COMPILER " build/wide-app.i build/wide-app.basm build/wide-app.b32 --wide-app > build/compiler.log 2>&1")==0,"wide OS app compilation");
image=fopen("build/wide-app.b32","rb");if(!image)fail("cannot read wide OS app image");
unsigned char app_header[24];check(fread(app_header,1,sizeof(app_header),image)==sizeof(app_header),"wide OS app header read");fclose(image);
check(!memcmp(app_header,"B32K",4) && app_header[8]==0 && app_header[9]==0 && app_header[10]==2 && app_header[11]==0,"wide OS app uses supervised high-memory origin");
image=fopen("build/wide-app.b32","rb");if(!image)fail("cannot reopen wide app image");
fseek(image,0,SEEK_END);long image_size=ftell(image);rewind(image);unsigned char *image_bytes=malloc((size_t)image_size);if(!image_bytes)fail("wide app allocation");
check(fread(image_bytes,1,(size_t)image_size,image)==(size_t)image_size,"read wide app for large fixture");fclose(image);
uint32_t image_words=(uint32_t)image_bytes[16]|((uint32_t)image_bytes[17]<<8)|((uint32_t)image_bytes[18]<<16)|((uint32_t)image_bytes[19]<<24);
image_words+=600;for(int i=0;i<4;i++)image_bytes[16+i]=(unsigned char)(image_words>>(8*i));
check(image_words>511,"native B32 fixture exceeds the former per-file limit");
image=fopen("build/wide-large.b32","wb");if(!image)fail("create large B32 image");
check(fwrite(image_bytes,1,(size_t)image_size,image)==(size_t)image_size,"write large image prefix");
unsigned char zeros[2400]={0};check(fwrite(zeros,1,sizeof(zeros),image)==sizeof(zeros),"append large image payload");fclose(image);free(image_bytes);
image=fopen("build/wide-large.b32","rb");if(!image)fail("open large B32 image for truncated fixture");
unsigned char short_header[24];check(fread(short_header,1,sizeof(short_header),image)==sizeof(short_header),"read truncated image header");fclose(image);
image=fopen("build/wide-truncated.b32","wb");if(!image)fail("create truncated B32 image");
check(fwrite(short_header,1,sizeof(short_header),image)==sizeof(short_header),"write truncated image header");fclose(image);
write_text("build/check.in","");
check(system(BOB32 " --asm32 build/wide-app.basm < build/check.in > build/check.out 2> build/check.err")==0,"wide .org BASM assembly and direct application execution");
output=read_text("build/check.out");check(!strcmp(output,"bob!\n"),"wide-origin BASM application output");free(output);
}
static void console_and_commands(void) {
char *output=shell("help\necho bob!\nclear\nmem\nalloc 4\npoke 0xc000 -32768\npeek 0xc000\npoke 0 1\nhalt\n");
contains(output,"bob!\nbob16 OS:");contains(output,"help | echo TEXT");contains(output,"bob> bob!\n");
@@ -77,12 +217,34 @@ static void allocator_and_files(void) {
output=shell(large);contains(output,"full 511 chars (text)");free(output);
}
static void resident_compiler(void) {
char oversized[2048];strcpy(oversized,"cc bob.c keep\nedit large.c\nint main(void){\n");
for(int i=0;i<28;i++)strcat(oversized,"println(\"bob!\");\n");
strcat(oversized,"return 0;}\n.\ncc large.c keep\nrun keep\ngo bob.c\nhalt\n");
char *bounded=shell(oversized);contains(bounded,"C compile error near character");
contains(bounded,"bob!\nExit 0");not_contains(bounded,"Program fault");free(bounded);
char *joined=shell("edit joined.c\nint main(void){println(\"bo\" /* join */ \"b\" \"\"\n\"!\");return 0;}\n.\ngo joined.c\nhalt\n");
not_contains(joined,"compile error");contains(joined,"bob!\nExit 0");free(joined);
char *broken=shell("edit broken.c\nint main(void){println(\"bob!\n\");return 0;}\n.\ngo broken.c\n"
"edit broken.c\n:r 1 int main(void){int x='\n:r 2 ';return 0;}\n.\ngo broken.c\ngo bob.c\nhalt\n");
int errors=0;const char *error=broken;while((error=strstr(error,"C compile error near character"))){errors++;error++;}
check(errors==2,"resident rejects literal line breaks");contains(broken,"bob!\nExit 0");free(broken);
char *escapes=shell("edit escapes.c\nint main(void){if('\\a'!=7 || '\\b'!=8 || '\\f'!=12)return 1;\n"
"if('\\r'!=13 || '\\v'!=11 || '\\?'!=63)return 2;println(\"bob!\");return 0;}\n.\ngo escapes.c\nhalt\n");
not_contains(escapes,"compile error");contains(escapes,"bob!\nExit 0");free(escapes);
char *octal=shell("write octal.c int main(void){if(010!=8 || 077!=63 || 0177777!=0xffff)return 1;println(\"bob!\");return 0;}\ngo octal.c\nhalt\n");
not_contains(octal,"compile error");contains(octal,"bob!\nExit 0");free(octal);
octal=shell("write bad.c int main(void){return 09;}\ngo bad.c\nwrite bad.c int main(void){return 0200000;}\ngo bad.c\ngo bob.c\nhalt\n");
contains(octal,"C compile error near character");contains(octal,"bob!\nExit 0");free(octal);
char *output=shell("cc bob.c bob\nrun bob\necho bob!\nhalt\n");
contains(output,"Compiled 42 words.");contains(output,"bob> bob!\nExit 0\nbob> bob!\n");free(output);
output=shell("edit calc.c\nint main(void) { int n = 0; while (n < 3) { n = n + 1; }\nif (n == 3) { println(\"bob!\"); } else { return 1; } return 0; }\n.\ncc calc.c calc\nrun calc\nhalt\n");
not_contains(output,"compile error");contains(output,"bob> bob!\nExit 0");free(output);
output=shell("write math.c int main(void) { int a = 6 * 7; if (a / 2 == 21) println(\"bob!\"); return a % 7; }\ncc math.c math\nrun math\nhalt\n");
not_contains(output,"compile error");contains(output,"bob> bob!\nExit 0");free(output);
output=shell("edit product.c\nint main(void){int high=32767;int low=-32767-1;int i=0;\n"
"while(i<64){if(high*high!=1)return 1;if(low*high!=low)return 2;i++;}\n"
"if(low*2!=0 || (-7)*9!=-63)return 3;println(\"bob!\");return 0;}\n.\ngo product.c\nhalt\n");
not_contains(output,"compile error");not_contains(output,"Program timed out");contains(output,"bob!\nExit 0");free(output);
output=shell("write bad.c int main(void) { int a = ; }\ncc bad.c bad\nrun bad\ncc bob.c bob\nrun bob\nhalt\n");
contains(output,"C compile error near character");contains(output,"Program not found.");contains(output,"bob> bob!\nExit 0");free(output);
/* Verify both APIs and signed numeric formatting in resident-generated code. */
@@ -125,7 +287,7 @@ static void program_loading_and_recovery(void) {
contains(output,"Command too long.");contains(output,"Program not found.");free(output);
output=shell("load raw 0x4001 0xae01 98 0xf100 0x4001 0xae01 111 0xf100 0x4001 0xae01 98 0xf100 0x4001 0xae01 33 0xf100 0xe000\nrun raw\nhalt\n");
contains(output,"Loaded.");contains(output,"bob> bob!Exit 33");free(output);
output=shell("load bad 0x1001\nrun bad\nload spin 0x4601 0xb600 0x9000\nrun spin\necho bob!\nhalt\n");
output=shell("load bad 0x1001\nrun bad\nload spin 0x4601 0xb600 0xa000\nrun spin\necho bob!\nhalt\n");
contains(output,"Program fault; shell restored.");contains(output,"Program timed out; shell restored.");contains(output,"bob> bob!\n");free(output);
/* Load a program that tries to store to kernel address zero. */
output=shell("load guard 0x4201 0xae01 0 0x9040 0xe000\nrun guard\ncc bob.c bob\nrun bob\nhalt\n");
@@ -135,6 +297,236 @@ static void program_loading_and_recovery(void) {
contains(output,"Program fault; shell restored.");contains(output,"bob> bob!\n");free(output);
}
static void host_compiler_and_runtime(void) {
guest("#include <stdbool.h>\n#include \"bob.h\"\nint main(void){bool enabled=true;if(!enabled||false)return 1;enabled=false;if(enabled)return 2;bob_puts(\"bob!\");return 0;}");
guest("#include <stddef.h>\n#include \"bob.h\"\nint main(void){int values[3];size_t words=sizeof values;ptrdiff_t distance=&values[2]-&values[0];int *empty=NULL;if(words!=3||distance!=2||empty!=NULL||(sizeof(int)-2)!=(size_t)-1)return 1;bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\nint sum(int a,int b){return a+b;}int (*combine)(int,int)=sum;int twice(int n){return n*2;}int apply(int (*fn)(int),int n){return fn(n);}int main(void){int (*operation)(int,int)=&sum;int (*scale)(int)=twice;int (*oldstyle)()=twice;if(combine(4,5)!=9||operation(2,3)!=5||scale(6)!=12||(*scale)(8)!=16||apply(*scale,7)!=14||oldstyle(5)!=10)return 1;operation=combine;if(operation(7,8)!=15)return 2;bob_puts(\"bob!\");return 0;}");
char *joined_literal=malloc(40000);if(!joined_literal)fail("allocate joined literal fixture");
char *joined_cursor=joined_literal;joined_cursor+=sprintf(joined_cursor,"#include \"bob.h\"\nchar *text=");
for(int i=0;i<9000;i++){memcpy(joined_cursor,"\"b\"",3);joined_cursor+=3;}
strcpy(joined_cursor,";int main(void){if(text[8999]!='b' || text[9000]!=0)return 1;bob_puts(\"bob!\");return 0;}");
guest(joined_literal);free(joined_literal);
char *large_literal=malloc(10000);if(!large_literal)fail("allocate large literal fixture");
char *literal_cursor=large_literal;literal_cursor+=sprintf(literal_cursor,"#include \"bob.h\"\nchar *text=\"");
memset(literal_cursor,'b',9000);literal_cursor+=9000;
strcpy(literal_cursor,"\";int main(void){if(text[8999]!='b' || text[9000]!=0)return 1;bob_puts(\"bob!\");return 0;}");
guest(large_literal);free(large_literal);
guest("#include \"bob.h\"\nint x;_Bool a=&x,b=\"bob!\",c=(_Bool)&x,d=(int*)0; "
"_Bool values[2]={&x,(void*)0};int main(void){static _Bool s=&x; "
"if(!a || !b || !c || d || !values[0] || values[1] || !s)return 1;bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\nint (*p)[3]=(int (*)[3])0xc000+2; "
"int (*q)[3]=2+(int (*)[3])0xc000;int (*r)[3]=(int (*)[3])0xc009-1; "
"int distance=(int (*)[3])0xc009-(int (*)[3])0xc000; "
"int main(void){int (*base)[3]=(int (*)[3])0xc000; "
"if(p!=base+2 || q!=p || r!=p || distance!=3)return 1;bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\nint a=7,b=9;int *p=1?&a:&b;int *q=0?&a:&b; "
"int *nil=0?&a:0;char *text=sizeof(a)==1?\"bob!\":\"bad\"; "
"int main(void){static int *s=1?(0?&b:&a):0; "
"if(*p!=7 || *q!=9 || nil!=0 || *s!=7)return 1;bob_puts(text);return 0;}");
guest("#include \"bob.h\"\nchar (*word)[5]=&\"bob!\";char (*end)[5]=&\"bob!\"+1; "
"char *last=&\"bob!\"[3];int main(void){static char (*saved)[5]=&\"bob!\"; "
"if(sizeof(*word)!=5 || (*word)[4]!=0 || (*saved)[3]!='!' || *last!='!')return 1; "
"if((*(end-1))[0]!='b')return 2;bob_puts(*saved);return 0;}");
guest("#include \"bob.h\"\nint main(void){char (*p)[5]=&\"bob!\";int a[2]; "
"if(sizeof(&a)!=1 || sizeof(*p)!=5 || (*p)[3]!='!')return 1;bob_puts(*p);return 0;}");
guest("#include \"bob.h\"\nint main(void){int x=0;int a[3]; "
"if(sizeof(sizeof(x++))!=1 || sizeof(sizeof(a))!=1 || x!=0)return 1;bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\nint main(void){int a[2][3]={{1,2,3},{4,5,6}};unsigned int i=1; "
"if(i[a][2]!=6 || sizeof(i[a])!=3 || sizeof(2[a[0]])!=1)return 1;bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\nint count;int f(int *p,int x){count++;return x;} "
"int main(void){int x;void *p=&x;if(sizeof(f(p,count++))!=1 || count!=0)return 1; "
"if(sizeof(bob_run(count++))!=1 || count!=0)return 2;bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\nint main(void){char word[]=\"bob!\";void *p=word;bob_puts(p);return 0;}");
guest("#include \"bob.h\"\nint value=7;void *shared=&value;int *items[]={&value,1-1}; "
"int main(void){void *v=&value;int *p=v;_Bool b=p;int *a[2]={p,0}; "
"static int *saved=&value;if(*p!=7 || !b || a[1]!=0 || *saved!=7)return 1; "
"if(shared!=p || items[0]!=p || items[1]!=0)return 2;bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\nint read(int *p){return *p;}int null(int *p){return p==0;} "
"int generic(void *p){return read(p);}_Bool truth(_Bool b){return b;} "
"int main(void){int x=7;void *v=&x;if(read(v)!=7 || generic(&x)!=7 || !null(1-1))return 1; "
"if(!truth(&x) || truth((int*)0))return 2;bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\nint value=7;void *generic(void){return &value;} "
"int *returned(void){return generic();}int *empty(void){return 1-1;} "
"_Bool truth(void){return &value;}_Bool zero(void){return (int*)0;} "
"int main(void){if(*returned()!=7 || empty()!=0 || truth()!=1 || zero()!=0)return 1;bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\nint main(void){int x=7;int *p;void *v;_Bool flag; "
"p=&x;v=p;p=v;flag=p;if(*p!=7 || flag!=1)return 1; "
"p=1-1;flag=p;if(p!=0 || flag!=0 || sizeof(p=0)!=1)return 2; "
"bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\nint main(void){int x=7;int *p=&x,*empty=0;void *v=p; "
"if(p!=v || v!=p || p==0 || 0==p || empty!=1-1)return 1; "
"if(sizeof(p==v)!=1 || p!=p || empty!=(void*)0)return 2;bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\nint main(void){int low=-32768,high=32767,one=1,minus=-1; "
"for(int i=0;i<64;i++){if(low/one!=low || high/one!=high || high/minus!=-32767)return 1;} "
"if(-43/7!=-6 || 43/-7!=-6 || -43/-7!=6 || 43/7!=6)return 2; "
"if(-43%7!=-1 || 43%-7!=1 || -43%-7!=-1 || low%one!=0)return 3; "
"bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\nint depth=5;int leaf(void){return 7;} "
"int recurse(void){if(depth==0)return leaf();depth--;return recurse()+1;} "
"int main(void){int saved=42;int result=recurse(); "
"if(result!=12 || saved!=42 || leaf()!=7)return 1;bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\nint main(void){int n=0;int *p=&n; "
"if(!!n!=0 || !!p!=1 || !!(-32768)!=1 || !!0xffff!=1)return 1; "
"if(!!n++!=0 || n!=1 || !!n++!=1 || n!=2)return 2;bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\nint main(void){int high=32767,low=-32768;unsigned all=65535U; "
"for(int i=0;i<64;i++){if(high*high!=1 || low*high!=-32768)return 1;} "
"if(low*2!=0 || low*(-1)!=low || all*all!=1U || (-7)*9!=-63)return 2; "
"if(high*0!=0 || 0*high!=0 || (-1)*(-1)!=1)return 3;bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\nint main(void){int rows[2][2];int (*p)[]=&rows[0];int (*q)[2]=&rows[1]; "
"if(sizeof(*(1?p:q))!=2 || sizeof(*(0?q:p))!=2)return 1; "
"int x=7;int *v=1?&x:1-1;int *w=0?0:&x;void *generic=0?(void*)0:v; "
"if(*v!=7 || *w!=7 || generic!=v || (1?0:v)!=0)return 2;bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\nenum E{ZERO,ONE};int main(void){enum E rows[2][2]; "
"enum E (*first)[2]=&rows[0];int (*last)[2]=(int (*)[2])&rows[1]; "
"if(last-first!=1 || first-last!=-1 || sizeof(last-first)!=1)return 1; "
"enum E *a=&rows[0][0];int *b=(int*)&rows[0][1]; "
"if(b-a!=1 || a-b!=-1)return 2;bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\ntypedef int Word;enum E{ITEM=3};int const global=7; "
"unsigned const int high=65535U;char const message[]=\"bob!\"; "
"int inspect(int const value){Word const local=value;enum E const e=ITEM; "
"const const int *const const p=&global;return local+e+*p;} "
"int main(void){if(inspect(2)!=12 || high/3U!=21845U || sizeof(int const)!=1)return 1; "
"if(sizeof(unsigned const int)!=1 || sizeof(Word const)!=1)return 2; "
"bob_puts(message);return 0;}");
guest("#include \"bob.h\"\nenum Choice{FIRST=1,SECOND=2};int main(void){unsigned value=65535U;int score=0; "
"switch(value){case 65535U:score++;break;default:return 1;} "
"enum Choice choice=SECOND;switch(choice){case FIRST:return 2;case SECOND:score++;break;} "
"_Bool flag=7;switch(flag){case 0:return 3;case 1:score++;break;} "
"if(score!=3)return 4;bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\ntypedef const int ReadOnly;const int global=7; "
"int inspect(ReadOnly value){ReadOnly local=value;return local+global;} "
"int main(void){if(inspect(2)!=9)return 1;bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\nint value=7;int * const pointer=&value; "
"int main(void){*pointer=8;if(value!=8)return 1;bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\ntypedef const int *ReadPointer;int first=7,second=8; "
"int main(void){ReadPointer pointer=&first;pointer=&second;if(*pointer!=8)return 1; "
"bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\nint value=7;int main(void){int *writable=&value;const int *read_only=writable; "
"read_only=&value;if(*read_only!=7)return 1;bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\nint main(void){const int values[2]={4,5};const int matrix[2][2]={{1,2},{3,4}}; "
"if(values[1]!=5 || matrix[1][0]!=3)return 1;bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\nint inspect(int * const value);int inspect(int *value){return *value;} "
"int main(void){int value=7;if(inspect(&value)!=7)return 1;bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\nint calls;void visit(void){calls++;} "
"int main(void){(void)42;visit();1?visit():visit();0?(void)7:visit(); "
"if((visit(),calls)!=4)return 1;bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\nint main(void){int rows[2][2];int (*p)[]=&rows[0];int (*q)[2]=&rows[1]; "
"if(!(p<q) || !(q>p) || p>=q || q<=p || sizeof(p<q)!=1)return 1; "
"bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\nint pad0[4096],pad1[4096],pad2[4096],pad3[4096],pad4[4096],pad5[4096],pad6[4096];int data[4096]; "
"int main(void){int *low=&data[0],*high=&data[4095]; "
"if((int)low<0 || (int)high>=0)return 1; "
"if(!(low<high) || !(high>low) || !(low<=high) || !(high>=low))return 2; "
"if(high<low || low>high || !(low<=low) || !(high>=high))return 3; "
"bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\nchar bytes[]=\"\\a\\f\\v\\?\\xff\\377\"; "
"int main(void){if(sizeof(bytes)!=7 || bytes[0]!=7 || bytes[1]!=12 || bytes[2]!=11 || bytes[3]!='?')return 1; "
"if(bytes[4]!=255 || bytes[5]!=255 || '\\xff'!=255 || '\\377'!=255)return 2; "
"bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\ntypedef int unsigned Word;typedef signed Integer; "
"signed int echo(int signed value);int signed echo(signed value){return value;} "
"int unsigned divide(unsigned int a,int unsigned b){return a/b;} "
"int main(void){Integer negative=-3;Word high=65535U;int signed a[2]={-1,-2}; "
"if(echo(negative)!=-3 || divide(high,3U)!=21845U || a[1]!=-2)return 1; "
"if(sizeof(signed)!=1 || sizeof(int unsigned)!=1 || ((int unsigned)-1>>15)!=1U)return 2; "
"bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\nunsigned int constant=65535U/3U;unsigned folded=65535U>>15; "
"unsigned mixed=((-1)<1U);typedef unsigned Word; "
"Word divide(Word a,Word b){return a/b;} "
"int main(void){Word high=65535U,low=3U;int negative=-1; "
"if(high<low || !(high>low) || high<=low || !(high>=low) || !(low<high))return 1; "
"if(negative<1U || mixed!=0 || constant!=21845U || folded!=1U)return 2; "
"if(divide(high,low)!=21845U || high%low!=0U || divide(32768U,65535U)!=0U)return 3; "
"if(divide(65535U,32768U)!=1U || 65535U%32768U!=32767U)return 4; "
"Word shift=32769U;if((shift>>1)!=16384U)return 5;shift>>=15;if(shift!=1U)return 6; "
"high++;if(high!=0U)return 7;high--;if(high!=65535U || sizeof(Word)!=1)return 8; "
"if((Word)-1!=65535U || ((Word)negative/3U)!=21845U)return 9;bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\ntypedef _Bool Flag;Flag truth=42,zero=0,table[2][2]={{-2,0},{7,0}}; "
"Flag argument(Flag a,Flag b){return a==1 && b==0;}Flag returned(void){return -9;} "
"int main(void){Flag local=-7;Flag a[3]={3,0,-1};static Flag stored=99; "
"if(truth!=1 || zero!=0 || table[1][0]!=1 || table[0][1]!=0 || local!=1 || stored!=1)return 1; "
"if(a[0]!=1 || a[1]!=0 || a[2]!=1 || argument(42,0)!=1 || returned()!=1)return 2; "
"if((_Bool)-8!=1 || (_Bool)0!=0 || (_Bool)&local!=1 || sizeof(Flag)!=1)return 3; "
"if((local=17)!=1 || (local*=3)!=1 || (local-=1)!=0)return 4; "
"if(local++!=0 || local!=1 || ++local!=1 || local--!=1 || local!=0)return 5; "
"if(--local!=1 || local!=1)return 6;bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\nenum Mode{FIRST=-2,SECOND,WIDTH=3,LAST=WIDTH+2}; "
"typedef enum Mode Mode;enum Mode selected=LAST;int values[WIDTH]={1,2,3}; "
"int identify(Mode m){return m;} "
"int main(void){Mode m=FIRST;if(m!=-2 || SECOND!=-1 || LAST!=5 || sizeof(Mode)!=1)return 1; "
"if(identify(selected)!=5 || sizeof(values)!=3)return 2; "
"{enum Mode{FIRST=7,WIDTH=2};enum Mode local=FIRST;int a[WIDTH];if(local!=7 || sizeof(a)!=2)return 3;} "
"if(FIRST!=-2 || WIDTH!=3)return 4; "
"for(enum {BOUND=2} i=0;i<BOUND;i++){enum {INNER=BOUND+1};int a[INNER];if(sizeof(a)!=3)return 5;} "
"switch(selected){case LAST:bob_puts(\"bob!\");break;default:return 6;}return 0;}");
guest("#include \"bob.h\"\ntypedef int Word,*Pointer,Row[3];typedef int Word; "
"typedef Row *Rows;typedef char Text[];typedef void Nothing;Word answer(Nothing);Word answer(Nothing){return 1;}Row matrix[2]={{1,2,3},{4,5,6}}; "
"Rows rows=matrix;Text message=\"bob!\"; "
"Word sum(Row p[]){return p[0][0]+p[1][2];} "
"int main(void){Word n=7;Pointer p=&n; "
"if(sizeof(Row)!=3 || sizeof(Rows)!=1 || sum(rows)!=7 || *p!=7)return 1; "
"{typedef char Word;Word local[2];if(sizeof(local)!=2)return 2;} "
"{int Word=9;if(Word!=9 || sizeof(Word)!=1)return 3;} "
"Word restored=8;for(Word i=0;i<1;i++){typedef Row Block;Block a={1,2,3};if(a[2]!=3)return 4;} "
"if(restored!=8 || ((Rows)matrix)[1][1]!=5 || answer()!=1)return 5;bob_puts(message);return 0;}");
guest("#include \"bob.h\"\nint original[3];extern int original[];int copy[sizeof(original)]; "
"int f(int p[][3]){int a[sizeof(*p)];return sizeof(a);} "
"int main(void){int a[4];int b[sizeof(a)+1]; "
"{char a[2];int inner[sizeof(a)];if(sizeof(inner)!=2)return 1;} "
"int c[sizeof(a)];if(sizeof(copy)!=3 || sizeof(b)!=5 || sizeof(c)!=4)return 2; "
"for(int a[2]={0,0};a[0]<1;a[0]++){int d[sizeof(a)];if(sizeof(d)!=2)return 3;} "
"switch(4){case sizeof(a):if(f((int (*)[3])original)!=3)return 4;bob_puts(\"bob!\");break;default:return 5;}return 0;}");
guest("#include \"bob.h\"\nint a[sizeof(\"bob!\")];int length=sizeof(a); "
"int constants[]={sizeof(\"bob!\"),sizeof(1+2),sizeof(int[2][3])}; "
"int main(void){int local[3];int side=0; "
"static int count=sizeof(local),quiet=sizeof(side++),zero[sizeof(\"bob!\")]; "
"if(length!=5 || constants[0]!=5 || constants[1]!=1 || constants[2]!=6)return 1; "
"if(count!=3 || quiet!=1 || side!=0 || sizeof(zero)!=5 || zero[4]!=0)return 2; "
"switch(5){case sizeof(\"bob!\"):bob_puts(\"bob!\");break;default:return 3;}return 0;}");
guest("#include \"bob.h\"\nstatic int count;extern int count;static int count; "
"static int values[2]={3,4},*pointer=values; "
"static int next(void);extern int next(void);int next(void){return ++count;} "
"static int read(void){extern int count;return count+pointer[1];} "
"int main(void){if(next()!=1 || next()!=2 || read()!=6)return 1; "
"bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\nint next(void){static int count=3;static int *p=&count;return (*p)++;} "
"int other(void){static int count;return ++count;} "
"int array(void){static int a[][2]={{1,2},{3,4}};static char word[]=\"bob!\"; "
"a[1][1]++;if(a[1][1]==6)bob_puts(word);return a[1][1];} "
"int main(void){if(next()!=3 || next()!=4 || other()!=1 || other()!=2)return 1; "
"if(array()!=5 || array()!=6)return 2; "
"{static int count=7;if(count++!=7)return 3;}{static int count=9;if(count!=9)return 4;}return 0;}");
guest("#include \"bob.h\"\nint value=7;int rows[2][3]={{1,2,3},{4,5,6}}; "
"int change(void){int value=99;{extern int value;extern int value;value=8; "
"extern int rows[][3];if(sizeof(rows)!=6 || rows[1][2]!=6)return 100;} "
"if(value!=99)return 101;return 0;} "
"int main(void){extern int value;extern int unused; "
"if(change()!=0 || value!=8)return 1; "
"{extern int rows[2][3];int (*p)[3]=rows;p[1][2]=9;} "
"if(rows[1][2]!=9)return 2;bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\nextern int value;int value;int value=7;extern int value; "
"extern int rows[][3];int rows[2][3]={{1,2,3},{4,5,6}};int rows[][3]; "
"int zeros[];int zeros[];extern int unused;extern int incomplete[]; "
"extern int *pointer;int *pointer=&value;extern int *pointer; "
"extern int helper(void);int helper(void){return *pointer;} "
"int main(void){if(value!=7 || helper()!=7 || sizeof(rows)!=6 || rows[1][2]!=6)return 1; "
"if(sizeof(zeros)!=1 || zeros[0]!=0)return 2;*pointer=8;if(value!=8)return 3; "
"bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\nint main(void){int a[2][3];int (*p)[3]=a;int i=0; "
"if(sizeof(p+=1)!=1 || sizeof(p-=1)!=1 || sizeof(a[i++][0]+=2)!=1 || sizeof(++i)!=1)return 1; "
"if(p!=a || i!=0)return 2;p+=1;if(p-a!=1)return 3; "
"p-=1;(*p)[0]=7;if(a[0][0]!=7)return 4;bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\nint first(int (*)[]);int first(int (*)[3]); "
"int first(int (*p)[3]){return (*p)[2];} "
"int inspect(int (**)[3]);int inspect(int (**)[]); "
"int inspect(int (**p)[3]){return (**p)[1];} "
"int main(void){int rows[1][3]={{1,2,3}};int (*p)[3]=rows; "
"if(first(rows)!=3 || inspect(&p)!=2)return 1;bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\nint main(void){int a[3]={3,-16,0};int i=0,n=2,x=1,y=2; "
"if((a[i++]<<=n++)!=12 || i!=1 || n!=3 || a[0]!=12)return 1; "
"if((a[i++]>>=2)!=-4 || i!=2 || a[1]!=-4)return 2; "
"x<<=y<<=1;if(x!=16 || y!=4)return 3; "
"x>>=1+1;if(x!=4)return 4;x<<=0;if(x!=4)return 5; "
"bob_puts(\"bob!\");return 0;}");
guest("#include \"bob.h\"\nint matrix[2][3]={{1,2,3},{4,5,6}}; "
"int (*rows)[3]=matrix;int (*whole)[2][3]=&matrix;int (*incomplete)[]=(int (*)[])matrix; "
"int (*selected[2])[3]={&matrix[1],matrix}; "
@@ -316,6 +708,7 @@ static void compile_workflow(void) {
contains(output,"C source file not found.");
contains(output,"Usage: cc SOURCE [OUTPUT] | go SOURCE [OUTPUT]");
contains(output,"broken.c: line 2, column");
contains(output,"near token '@'.");
contains(output,"Use edit to fix the source.");
/* Four successful runs above; neither failed go may execute stale app. */
int exits=0;for(char *p=output;(p=strstr(p,"Exit 0"))!=NULL;p+=6)exits++;
@@ -341,6 +734,229 @@ static void storage_path(const char *path) {
check(setenv("BOB16_STORAGE",path,1)==0,"set snapshot fixture path");
#endif
}
static void wide_kernel_workflow(void) {
storage_path("build/wide-snapshot.b32");remove("build/wide-snapshot.b32");
write_text("build/check.in","mem\nalloc 4\npoke 0xd000 77\npeek 0xd000\npoke 0xc000 88\npeek 0xc000\ngo bob.c\nedit compat.c\nint main(void) {\nint n=0x12345678;\nif(n+1!=0x12345679 || n*2!=0x2468ACF0 || n/3!=101806632 || n%3)return 1;\nprintln(\"bob!\");\nreturn 0;\n}\n.\ngo compat.c\ndelete compat.c\nedit tern.c\nint main(void) {\nint a=0;\nint b=1?2:3;\nint c=0?4:1?5:6;\nint d=1?7:a++;\nif(b==2&&c==5&&d==7&&a==0)println(\"bob!\");\nreturn 0;\n}\n.\ngo tern.c\ndelete tern.c\nedit loops.c\nint main(void) {\nint i=0;\nint calls=0;\ndo { i++; if(i==2)continue; calls++; if(i==4)break; } while(i<10);\ndo { calls++; } while(0);\nif(calls==4)println(\"bob!\");\nreturn 0;\n}\n.\ngo loops.c\ndelete loops.c\nedit assign.c\nint main(void) {\nint a=0; int b=1; int i=0;\nint x=(a=b=3);\na+=2; b<<=2; b>>=1;\nif(x==3&&a==5&&b==6&&((i=i+1)==1))println(\"bob!\");\nreturn 0;\n}\n.\ngo assign.c\ndelete assign.c\nedit funcs.c\nint main(void) {\nannounce();\nif(add(fact(5),2)==122)println(\"bob!\");\nreturn 0;\n}\nint announce(void) {\nprintln(\"bob!\");\nreturn 0;\n}\nint fact(int n) {\nif(n<2)return 1;\nreturn n*fact(n-1);\n}\nint add(int x,int y) {\nint value=x+y;\nreturn value;\n}\n.\ngo funcs.c\ndelete funcs.c\nedit scope.c\nint main(void) {\nint value=3;\n{int value=8;if(value!=8)return 1;}\n{int value=9;if(value!=9)return 2;}\nint count=99;\nfor(int count=0;count<2;count++){int inner=count;if(inner!=count)return 3;}\nif(value==3&&count==99)println(\"bob!\");\nreturn 0;\n}\n.\ngo scope.c\ndelete scope.c\nwrite hex.c int main(void){print_hex(4660);println(\"bob!\");return 0;}\ngo hex.c\nload old 0xD002 0xF200 0xF000 0x0062 0x006F 0x0062 0x0021 0x0000\nrun old\nedit note\nbob!\n.\nread note\nls\ncc bob.c app\nrun app\nsave\nhalt\n");
check(system(BOB32 " --boot build/kernel32.b32 --max-cycles 50000000 < build/check.in > build/check.out 2> build/check.err")==0,"bob32 OS shell workflow");
char *output=read_text("build/check.out");int successful_apps=0;const char *success_cursor=output;
while((success_cursor=strstr(success_cursor,"bob!\nExit 0"))){successful_apps++;success_cursor+=11;}
check(successful_apps==9,"B32 resident programs all complete successfully");
contains(output,"bob32 OS:");contains(output,"Compiled 45 words.\nbob!\nExit 0");
contains(output,"bob!\nExit 0");
contains(output,"0x00001234bob!\nExit 0");
contains(output,"Loaded.\nbob> bob!\nExit 33");
contains(output,"0x0000D000: 0x0000004D (77)");contains(output,"poke is limited to heap RAM.");
contains(output,"bob!\n\n");contains(output,"Files saved to bob-files.b32");free(output);
FILE *snapshot=fopen("build/wide-snapshot.b32","rb");if(!snapshot)fail("bob32 snapshot missing");
char magic[4];check(fread(magic,1,4,snapshot)==4 && !memcmp(magic,"B32S",4),"bob32 OS writes native snapshot format");fclose(snapshot);
write_text("build/check.in","restore yes\nread note\nrun app\nhalt\n");
check(system(BOB32 " --boot build/kernel32.b32 --max-cycles 50000000 < build/check.in > build/check.out 2> build/check.err")==0,"bob32 snapshot restore workflow");
output=read_text("build/check.out");contains(output,"Files restored;");contains(output,"bob!\n");contains(output,"bob> bob!\nExit 0");free(output);
write_text("build/check.in","go bob.c\nhalt\n");
check(system(BOB32 " --asm32 build/kernel32.basm < build/check.in > build/check.out 2> build/check.err")==0,"full bob32 kernel BASM assembly and execution");
output=read_text("build/check.out");contains(output,"bob32 OS:");contains(output,"Compiled 45 words.\nbob!\nExit 0");free(output);
write_text("build/check.in","run32 build/wide-app.b32\nrun32 build/missing-app.b32\ngo bob.c\nhalt\n");
check(system(BOB32 " --boot build/kernel32.b32 --max-cycles 50000000 < build/check.in > build/check.out 2> build/check.err")==0,"bob32 OS runs a native wide C application");
output=read_text("build/check.out");contains(output,"bob> bob!\nExit 0");contains(output,"Cannot read B32 app image.");contains(output,"bob!\nExit 0");free(output);
write_text("build/check.in","import32 build/wide-large.b32 native\nls\nrun native\nrun32 native\nsave\nhalt\n");
check(system(BOB32 " --boot build/kernel32.b32 --max-cycles 50000000 < build/check.in > build/check.out 2> build/check.err")==0,"import, run and snapshot a native app from bob32 RAM files");
output=read_text("build/check.out");contains(output,"Imported native app as native");contains(output,"native ");contains(output,"words (native bob32 image)");check(strstr(output,"bob> bob!\nExit 0") && strstr(strstr(output,"bob> bob!\nExit 0")+1,"bob!\nExit 0"),"run and run32 accept native guest filenames");contains(output,"Files saved to bob-files.b32");free(output);
write_text("build/check.in","restore yes\nrun native\nhalt\n");
check(system(BOB32 " --boot build/kernel32.b32 --max-cycles 50000000 < build/check.in > build/check.out 2> build/check.err")==0,"restore and run native app stored in B32S");
output=read_text("build/check.out");contains(output,"Files restored;");contains(output,"bob> bob!\nExit 0");free(output);
write_text("build/check.in","import32 build/missing.b32 missing\nimport32 build/wide-bad.b32 corrupt\nimport32 build/wide-truncated.b32 short\nrun absent\nhalt\n");
write_text("build/wide-bad.b32","not a B32 image");
check(system(BOB32 " --boot build/kernel32.b32 --max-cycles 50000000 < build/check.in > build/check.out 2> build/check.err")==0,"native image import errors preserve the shell");
output=read_text("build/check.out");contains(output,"Cannot read host app image path.");contains(output,"Invalid, truncated, corrupt, or unsupported B32K app image.");contains(output,"Program not found.");free(output);
storage_path("build/snapshot.b16");
}
static void wide_local_offset_limit(void) {
char source[4096] = "int main(void){";
char input[8192] = "edit offsets.c\n";
char piece[80];
for (int i = 0; i < 33; i++) {
snprintf(piece, sizeof(piece), "{int v%d=%d;}\n", i, i);
strcat(source, piece);
}
strcat(source, "return 0;}\n");
strcat(input, source);
strcat(input, ".\ncc offsets.c rejected\nhalt\n");
write_text("build/check.in", input);
check(system(BOB32 " --boot build/kernel32.b32 --max-cycles 50000000 < build/check.in > build/check.out 2> build/check.err")==0,"B32 local offset limit shell workflow");
char *output = read_text("build/check.out");
contains(output, "C compile error");
check(strstr(output, "Compiled ") == NULL, "B32 local frame offset overflow rejected");
free(output);
}
static void wide_local_arrays(void) {
write_text("build/check.in",
"edit array.c\n"
"int main(void) {\n"
"int values[4]={1,2,},sum=0;\n"
"if(values[0]!=1||values[2]!=0)return 2;\n"
"for(int i=0;i<4;i++)values[i]=i+1;\n"
"values[0]++;\n"
"values[1]+=2;\n"
"values[2]<<=1;\n"
"for(int i=0;i<4;i++)sum+=values[i];\n"
"if(sum==16)println(\"bob!\");\n"
"return 0;\n"
"}\n"
".\ncc array.c array\nrun array\n"
"edit inc.c\n"
"int main(void) {\n"
"int a[2]={4,7},old=a[0]++;\n"
"if(old!=4||a[0]!=5)return 1;\n"
"if(++a[1]!=8)return 2;\n"
"int down=a[1]--;\n"
"if(down!=8||a[1]!=7)return 3;\n"
"if(--a[1]!=6)return 4;\n"
"println(\"bob!\");\n"
"return 0;\n"
"}\n"
".\ncc inc.c inc\nrun inc\n"
"edit excess.c\n"
"int main(void){int a[2]={1,2,3};return 0;}\n"
".\ncc excess.c rejected\nhalt\n");
check(system(BOB32 " --boot build/kernel32.b32 --max-cycles 50000000 < build/check.in > build/check.out 2> build/check.err")==0,"B32 local array shell workflow");
char *output=read_text("build/check.out");
contains(output,"Compiled ");contains(output,"bob!\nExit 0");
char *first_success=strstr(output,"bob!\nExit 0");
check(first_success && strstr(first_success+1,"bob!\nExit 0"),"B32 array prefix and postfix increment expressions execute");
contains(output,"C compile error");free(output);
}
static void wide_array_parameters(void) {
write_text("build/check.in",
"edit arrays.c\n"
"int sum(int values[],int length);\n"
"int bump(int values[],int length);\n"
"int main(void){int values[3]={1,2,3};\n"
"int first=sum(values,3);\n"
"int next=bump(values,3);\n"
"if(first==6&&next==9&&sum(values,3)==9)println(\"bob!\");\n"
"return 0;}\n"
"int sum(int values[],int length){\n"
"int total=0;for(int i=0;i<length;i++)total+=values[i];\n"
"return total;}\n"
"int bump(int values[],int length){\n"
"for(int i=0;i<length;i++)values[i]++;\n"
"return sum(values,length);}\n"
".\ncc arrays.c arrays\nrun arrays\n"
"edit scalar_to_array.c\n"
"int read(int values[],int length);\n"
"int read(int values[],int length){return values[0];}\n"
"int main(void){int value=4;return read(value,1);}\n"
".\ncc scalar_to_array.c rejected1\n"
"edit array_to_scalar.c\n"
"int identity(int value);\n"
"int identity(int value){return value;}\n"
"int main(void){int values[2];return identity(values);}\n"
".\ncc array_to_scalar.c rejected2\n"
"edit conflicting_array.c\n"
"int f(int values[]);\n"
"int f(int values);\n"
"int main(void){return 0;}\n"
".\ncc conflicting_array.c rejected3\n"
"edit multidimensional.c\n"
"int bad(int values[][]);\n"
"int main(void){return 0;}\n"
".\ncc multidimensional.c rejected4\nhalt\n");
check(system(BOB32 " --boot build/kernel32.b32 --max-cycles 50000000 < build/check.in > build/check.out 2> build/check.err")==0,"B32 array parameter shell workflow");
char *output=read_text("build/check.out");
contains(output,"bob> bob!\nExit 0");
char *error=strstr(output,"C compile error");
check(error && strstr(error+1,"C compile error") && strstr(strstr(error+1,"C compile error")+1,"C compile error") &&
strstr(strstr(strstr(error+1,"C compile error")+1,"C compile error")+1,"C compile error"),
"B32 rejects array argument and declaration mismatches");
free(output);
}
static void wide_resident_large_output(void) {
char input[8192] = "edit large.c\nint main(void){int a[1]={0};";
for (int i = 0; i < 60; i++) {
strcat(input, "a[0]++;");
if ((i == 6) || (i > 6 && (i - 6) % 9 == 8 && i < 59)) strcat(input, "\n");
}
strcat(input, "\n");
strcat(input, "if(a[0]==60)println(\"bob!\");return 0;}\n.\ncc large.c large\nrun large\nsave\nhalt\n");
storage_path("build/wide-resident-large.b32");remove("build/wide-resident-large.b32");
write_text("build/check.in", input);
check(system(BOB32 " --boot build/kernel32.b32 --max-cycles 50000000 < build/check.in > build/check.out 2> build/check.err")==0,"B32 resident compiler creates and snapshots large app");
char *output=read_text("build/check.out");
char *compiled=strstr(output,"Compiled ");
check(compiled && atoi(compiled+9)>511,"B32 resident compiler output exceeds 511 words");
contains(output,"bob> bob!\nExit 0");contains(output,"Files saved to bob-files.b32");free(output);
write_text("build/check.in","restore yes\nrun large\nhalt\n");
check(system(BOB32 " --boot build/kernel32.b32 --max-cycles 50000000 < build/check.in > build/check.out 2> build/check.err")==0,"B32 large resident app restores and runs from snapshot");
output=read_text("build/check.out");contains(output,"Files restored;");contains(output,"bob> bob!\nExit 0");free(output);
storage_path("build/snapshot.b16");
}
static void wide_function_prototypes(void) {
write_text("build/check.in",
"write bobs.c int main(void){println(\"Bob!\");return 0;}\n"
"go bobs.c\n"
"edit proto.c\n"
"int add(int a,int b);\n"
"int loose();\n"
"int unused(int);\n"
"int main(void){if(add(2,3)==5&&loose(4,5)==9)println(\"bob!\");return 0;}\n"
"int add(int a,int b){return a+b;}\n"
"int loose(int a,int b){return a+b;}\n"
".\ncc proto.c proto\nrun proto\n"
"edit mismatch.c\n"
"int f(int a);\n"
"int f(int a,int b);\n"
"int main(void){return 0;}\n"
".\ncc mismatch.c rejected\n"
"edit oldstyle_mismatch.c\n"
"int sum();\n"
"int main(void){return sum(1);}\n"
"int sum(int a,int b){return a+b;}\n"
".\ncc oldstyle_mismatch.c rejected\nhalt\n");
check(system(BOB32 " --boot build/kernel32.b32 --max-cycles 50000000 < build/check.in > build/check.out 2> build/check.err")==0,"B32 function prototype shell workflow");
char *output=read_text("build/check.out");
contains(output,"Compiled ");contains(output,"Bob!\nExit 0");contains(output,"bob!\nExit 0");
char *errors=strstr(output,"C compile error");
check(errors && strstr(errors+1,"C compile error"),"B32 no-prototype declaration checks eventual definition arity");
free(output);
}
static void wide_function_pointers(void) {
write_text("build/check.in",
"edit pointer.c\n"
"int sum(int a,int b);\n"
"int main(void) {\n"
"int (*operation)(int,int)=sum;\n"
"int (*other)(int,int)=0;\n"
"other=operation;\n"
"operation=other;\n"
"if(operation(4,5)==9)println(\"bob!\");\n"
"return 0;\n"
"}\n"
"int sum(int a,int b){return a+b;}\n"
".\ncc pointer.c pointer\nrun pointer\n"
"edit mismatch.c\n"
"int one(int a);\n"
"int two(int a,int b);\n"
"int main(void){int (*operation)(int)=two;return 0;}\n"
".\ncc mismatch.c rejected\n"
"edit integer.c\n"
"int main(void){int value=7;int (*operation)(int)=value;return 0;}\n"
".\ncc integer.c rejected\n"
"edit mismatch_assign.c\n"
"int one(int a);int two(int a,int b);\n"
"int main(void){int (*operation)(int)=one;operation=two;return 0;}\n"
".\ncc mismatch_assign.c rejected\n"
"edit integer_assign.c\n"
"int main(void){int value=7;int (*operation)(int)=0;operation=value;return 0;}\n"
".\ncc integer_assign.c rejected\nhalt\n");
check(system(BOB32 " --boot build/kernel32.b32 --max-cycles 50000000 < build/check.in > build/check.out 2> build/check.err")==0,"B32 function pointer shell workflow");
char *output=read_text("build/check.out");
contains(output,"Compiled ");contains(output,"bob!\nExit 0");
char *errors=strstr(output,"C compile error");
int error_count=0;
while(errors){error_count++;errors=strstr(errors+1,"C compile error");}
check(error_count==4,"B32 function pointer rejects incompatible and non-function initializers and assignments");
free(output);
}
static void snapshot_mutate(int offset, int rehash) {
FILE *file=fopen("build/snapshot.b16","rb");if(!file)fail("snapshot missing");
unsigned char bytes[8640];size_t count=fread(bytes,1,sizeof(bytes),file);fclose(file);
@@ -405,7 +1021,271 @@ static void shell_editing(void) {
contains(output,"Allocation failed. Use a positive size");contains(output,"Used 1/8 slots");free(output);
}
static void host_language_rejections(void) {
write_text("build/check.i","int main(void){return 0;}");
write_text("build/check.basm","bob!\n");write_text("build/check.b16","bob!\n");write_text("build/check.map","bob!\n");
const char *collisions[]={
COMPILER " build/check.i build/check.b16 build/check.b16",
COMPILER " build/check.i build/check.map build/check.b16",
COMPILER " build/check.i build/check.basm build/check.map",
COMPILER " build/check.i build/check.i build/check.b16",
COMPILER " build/check.i build/check.basm build/check.i"
#ifdef _WIN32
,COMPILER " build/check.i build/./check.b16 build/check.b16"
,COMPILER " build/check.i build/CHECK.B16 build/check.b16"
#endif
};
for(unsigned i=0;i<sizeof(collisions)/sizeof(collisions[0]);i++) {
check(system(collisions[i])!=0,"colliding output paths rejected");
char *text=read_text("build/check.i");check(!strcmp(text,"int main(void){return 0;}"),"path rejection preserves source");free(text);
text=read_text("build/check.basm");check(!strcmp(text,"bob!\n"),"path rejection preserves assembly");free(text);
text=read_text("build/check.b16");check(!strcmp(text,"bob!\n"),"path rejection preserves binary");free(text);
text=read_text("build/check.map");check(!strcmp(text,"bob!\n"),"path rejection preserves map");free(text);
}
/* Feed malformed lexer input directly: a preprocessor would reject it first. */
const char *unterminated[]={"char *p=\"bob!\\", "int x='\\"};
for(unsigned i=0;i<sizeof(unterminated)/sizeof(unterminated[0]);i++) {
write_text("build/check.i",unterminated[i]);
write_text("build/check.basm","bob!\n");write_text("build/check.b16","bob!\n");
check(system(COMPILER " build/check.i build/check.basm build/check.b16 > build/compiler.log 2>&1")!=0,"unterminated escape rejected");
char *log=read_text("build/compiler.log");contains(log,"unterminated escape");free(log);
char *prior=read_text("build/check.basm");check(!strcmp(prior,"bob!\n"),"lexer failure preserves assembly");free(prior);
prior=read_text("build/check.b16");check(!strcmp(prior,"bob!\n"),"lexer failure preserves binary");free(prior);
}
const char *lexical[]={"char *p=\"bob!\n\";", "int x='\n';", "int x=08;", "int x=1u2;", "int x=1_foo;"};
const char *diagnostics[]={"newline in literal", "newline in literal", "malformed integer literal", "malformed integer literal", "malformed integer literal"};
for(unsigned i=0;i<sizeof(lexical)/sizeof(lexical[0]);i++) {
write_text("build/check.i",lexical[i]);
check(system(COMPILER " build/check.i build/check.basm build/check.b16 > build/compiler.log 2>&1")!=0,"malformed literal rejected");
char *log=read_text("build/compiler.log");contains(log,diagnostics[i]);free(log);
}
FILE *input=fopen("build/check.i","wb");if(!input)fail("cannot create zero-byte source");
fputs("int main(void){return 0;}",input);fputc(0,input);fputs("invalid trailing source",input);fclose(input);
check(system(COMPILER " build/check.i build/check.basm build/check.b16 > build/compiler.log 2>&1")!=0,"source zero byte rejects silent truncation");
char *log=read_text("build/compiler.log");contains(log,"zero byte in source");free(log);
char *prior=read_text("build/check.basm");check(!strcmp(prior,"bob!\n"),"input failures preserve assembly");free(prior);
prior=read_text("build/check.b16");check(!strcmp(prior,"bob!\n"),"input failures preserve binary");free(prior);
char *relocation_limit=malloc(20000);if(!relocation_limit)fail("allocate relocation limit fixture");
char *cursor=relocation_limit;cursor+=sprintf(cursor,"int x;");
for(int i=0;i<15;i++)cursor+=sprintf(cursor,"int a%d[4096];",i);
cursor+=sprintf(cursor,"int *p[4096]={");
for(int i=0;i<4096;i++){memcpy(cursor,"&x,",3);cursor+=3;}
strcpy(cursor,"};int main(void){return 0;}");
char *deep_expression=malloc(1024);if(!deep_expression)fail("allocate expression nesting fixture");
cursor=deep_expression;cursor+=sprintf(cursor,"int a[");
for(int i=0;i<400;i++)*cursor++='(';
*cursor++='1';
for(int i=0;i<400;i++)*cursor++=')';
strcpy(cursor,"];int main(void){return 0;}");
const char *sources[]={
relocation_limit,
deep_expression,
"int a[(int*)3];int main(void){return 0;}",
"int main(void){const int value=1;value=2;return 0;}",
"int main(void){const int value=1;value++;return 0;}",
"typedef const int ReadOnly;int main(void){ReadOnly value=1;value=2;return 0;}",
"int main(void){const int value=1;return sizeof(value=2);}",
"int update(const int value){value=2;return value;}int main(void){return 0;}",
"const int value=1;int main(void){value=2;return 0;}",
"int main(void){int value=1,other=2;int * const pointer=&value;pointer=&other;return 0;}",
"int main(void){int value=1;int * const pointer=&value;pointer++;return 0;}",
"int update(int * const pointer){int value=1;pointer=&value;return 0;}int main(void){return 0;}",
"typedef int * const Pointer;int main(void){int value=1,other=2;Pointer pointer=&value;pointer=&other;return 0;}",
"typedef int * Pointer;int main(void){int value=1,other=2;const Pointer pointer=&value;pointer=&other;return 0;}",
"int main(void){int value=1;const int *pointer=&value;*pointer=2;return 0;}",
"int main(void){int value=1;const int *pointer=&value;pointer[0]++;return 0;}",
"int main(void){int value=1;const int *pointer=&value;int *writable=pointer;return 0;}",
"int main(void){int value=1;const int **pointer=0;int **writable=pointer;return value;}",
"int inspect(int *value);int inspect(const int *value);int main(void){return 0;}",
"int *inspect(void);const int *inspect(void);int main(void){return 0;}",
"int main(void){const int values[2]={1,2};values[1]=3;return 0;}",
"int main(void){const int values[2]={1,2};values[1]++;return 0;}",
"int main(void){const int values[2]={1,2};int *writable=values;return 0;}",
"int main(void){const int values[2]={1,2};return sizeof(values[1]=3);}",
"const int value=1;int *writable=&value;int main(void){return 0;}",
"int main(void){const int value=1;int *writable=&value;return 0;}",
"int main(void){int * const pointer=0;int **writable=&pointer;return 0;}",
"int main(void){int value=1;const int *readonly=&value;int *writable=1?readonly:&value;return 0;}",
"enum E{value=(int*)3};int main(void){return 0;}",
"enum E{value=32768U};int main(void){return 0;}",
"int a[3]={[ (int*)1 ]=7};int main(void){return 0;}",
"int value(void);int a[value()];int main(void){return 0;}",
"int a[sizeof((int)(void)0)];int main(void){return 0;}",
"enum E{value=sizeof((int)(void)0)};int main(void){return 0;}",
"int main(void){int value=0;int a[2]={[value++]=1};return 0;}",
"int value(void);int main(void){switch(1){case value():return 0;}}",
"int main(void){int value=0;switch(1){case value++:return 0;}}",
"int main(void){void *p=(void*)0xc000;++*p;return 0;}",
"int main(void){void *p=(void*)0xc000;(*p)++;return 0;}",
"int main(void){int a[2];++a;return 0;}",
"int x=1,a;int *p=x?&a:0;int main(void){return 0;}",
"int a;char b;int *p=1?&a:&b;int main(void){return 0;}",
"int main(void){return sizeof(&1);}",
"int main(void){int x;return sizeof(&(x+1));}",
"int main(void){int x;return sizeof(&x++);}",
"int main(void){int x;return sizeof(&(int)x);}",
"int main(void){return sizeof(sizeof((void)0));}",
"int f(int x){return x;}int main(void){return sizeof(sizeof(f()));}",
"int main(void){void *p=0;return sizeof(sizeof(&p[0]));}",
"int main(void){int *p;return sizeof(sizeof(p=7));}",
"void f(void){}int main(void){int a[2];return sizeof(a[f()]);}",
"void f(void){}int main(void){int a[2];return sizeof(f()[a]);}",
"int main(void){void *p=0;return sizeof(&p[0]);}",
"int main(void){int (*p)[]=0;return sizeof(&p[0]);}",
"int f(int *p){return 0;}int main(void){return sizeof(f(7));}",
"int f(int x){return x;}int main(void){return sizeof(f());}",
"int f(void){return 0;}int main(void){return sizeof(f(1));}",
"int f(int *p){return 0;}int main(void){char x;return sizeof(f(&x));}",
"#include \"bob.h\"\nint main(void){int x;return sizeof(bob_run(&x));}",
"int main(void){bob_puts(7);return 0;}",
"int main(void){int x;bob_puts(&x);return 0;}",
"int main(void){char a[2];bob_gets(a,a);return 0;}",
"int main(void){char a[2];bob_snapshot(a,0);return 0;}",
"int main(void){int x;bob_putc(&x);return 0;}",
"int main(void){int x;return bob_run(&x);}",
"int main(void){int x;return bob_call(&x);}",
"int main(void){int *p=7;return 0;}",
"int main(void){int x;char *p=&x;return 0;}",
"int main(void){int x;int n=&x;return 0;}",
"int main(void){int *p[2]={0,7};return 0;}",
"int *p=7;int main(void){return 0;}",
"int x;char *p=&x;int main(void){return 0;}",
"int *p[2]={0,7};int main(void){return 0;}",
"int main(void){static int *p=7;return 0;}",
"void f(void){}int main(void){int x=f();return 0;}",
"int f(int *p){return 0;}int main(void){return f(7);}",
"int f(char *p){return 0;}int main(void){int x;return f(&x);}",
"int f(int n){return n;}int main(void){int x;return f(&x);}",
"int *f(void){return 7;}int main(void){return 0;}",
"int value;char *f(void){return &value;}int main(void){return 0;}",
"int value;int f(void){return &value;}int main(void){return 0;}",
"int main(void){int *p;p=7;return 0;}",
"int main(void){int *p;char *q;p=q;return 0;}",
"int main(void){int *p;int x;x=p;return 0;}",
"int main(void){int *p;return sizeof(p=7);}",
"int main(void){int *p;return p==7;}",
"int main(void){int *p;int zero=0;return p!=zero;}",
"int main(void){int *p;char *q;return p==q;}",
"int main(void){int *p;return sizeof(p==7);}",
"int x=1?1:(void)0;int main(void){return 0;}",
"int x=1||(void)0;int main(void){return 0;}",
"int x=0&&(void)0;int main(void){return 0;}",
"int x=(int)(void)0;int main(void){return 0;}",
"int main(void){int *p;char *q;1?p:q;return 0;}",
"int main(void){int *p;1?p:7;return 0;}",
"int main(void){int *p;int zero=0;1?p:zero;return 0;}",
"int main(void){int *p;char *q;return sizeof(1?p:q);}",
"enum A{X};enum B{Y};int main(void){enum A *a;enum B *b;return a-b;}",
"int main(void){int (*a)[2];int (*b)[3];return a-b;}",
"int main(void){int (*a)[2];int (*b)[];return a-b;}",
"int main(void){int *p;switch(p){}return 0;}",
"int main(void){int a[2];switch(a){}return 0;}",
"void f(void){}int main(void){switch(f()){}return 0;}",
"int main(void){switch(1){case (int*)0:break;}return 0;}",
"int main(void){switch(1){case (void)0:break;}return 0;}",
"void f(void){return 1;}int main(void){return 0;}",
"void f(void){}void g(void){return f();}int main(void){return 0;}",
"int f(void){return;}int main(void){return 0;}",
"void f(void){}int main(void){return f();}",
"void f(void){}int g(int x){return x;}int main(void){return g(f());}",
"void f(void){}void bob_putc(int);int main(void){bob_putc(f());return 0;}",
"void f(void){}int main(void){return f()+1;}",
"void f(void){}int main(void){return (int)f();}",
"void f(void){}int main(void){return sizeof((int)f());}",
"void f(void){}int main(void){return !f();}",
"void f(void){}int main(void){return f()&&1;}",
"void f(void){}int main(void){return 1||f();}",
"void f(void){}int main(void){int x;x=f();return 0;}",
"void f(void){}int main(void){int x;return sizeof(x=f());}",
"void f(void){}int main(void){return sizeof(f()+1);}",
"void f(void){}int main(void){1?f():1;return 0;}",
"void f(void){}int main(void){f()?1:2;return 0;}",
"void f(void){}int main(void){if(f())return 1;return 0;}",
"void f(void){}int main(void){while(f()){}return 0;}",
"void f(void){}int main(void){do{}while(f());return 0;}",
"void f(void){}int main(void){for(;f();){}return 0;}",
"int main(void){int *p;return p<1;}",
"int main(void){int *p;char *q;return p<q;}",
"int main(void){void *p,*q;return p<q;}",
"int main(void){int *p;return sizeof(p<1);}",
"char *p=\"\\x100\";int main(void){return 0;}",
"char *p=\"\\x100000000000000000000000000000\";int main(void){return 0;}",
"char *p=\"\\400\";int main(void){return 0;}",
"int int x;int main(void){return 0;}",
"unsigned unsigned x;int main(void){return 0;}",
"signed unsigned x;int main(void){return 0;}",
"unsigned signed x;int main(void){return 0;}",
"int signed int x;int main(void){return 0;}",
"int void x;int main(void){return 0;}",
"unsigned f(unsigned);unsigned f(int x){return x;}int main(void){return 0;}",
"unsigned x;int x;int main(void){return 0;}",
"int main(void){int *p;return (int)(p/2U);}",
"_Bool f(_Bool);_Bool f(int x){return x;}int main(void){return 0;}",
"_Bool x;int x;int main(void){return 0;}",
"enum E{A,A};int main(void){return 0;}",
"enum E{A};enum E{B};int main(void){return 0;}",
"enum E{};int main(void){return 0;}",
"enum E{A=32767,B};int main(void){return 0;}",
"enum E{A};int A;int main(void){return 0;}",
"int A;enum E{A};int main(void){return 0;}",
"int main(void){{enum E{A};}int a[A];return 0;}",
"int main(void){{enum E{A};}enum E e;return 0;}",
"enum E{A};int main(void){A=1;return 0;}",
"enum E{A};enum F{B};int f(enum E);int f(enum F x){return 0;}int main(void){return 0;}",
"typedef int T;typedef char T;int main(void){return 0;}",
"typedef int T;int T;int main(void){return 0;}",
"int T;typedef int T;int main(void){return 0;}",
"typedef int T;int T(void){return 0;}int main(void){return 0;}",
"int f(void);typedef int f;int main(void){return 0;}",
"int f(int x){typedef int x;return 0;}int main(void){return 0;}",
"int main(void){{typedef int Gone;}Gone x;return 0;}",
"typedef void Nothing;int main(void){Nothing x;return 0;}",
"int a[sizeof(later)];int later[3];int main(void){return 0;}",
"int main(void){{int hidden[3];}int a[sizeof(hidden)];return 0;}",
"int main(void){for(int hidden[2];0;){}int a[sizeof(hidden)];return 0;}",
"int main(void){int a[sizeof(a)];return 0;}",
"int x;static int x;int main(void){return 0;}",
"static int x;int x;int main(void){return 0;}",
"extern int x;static int x;int main(void){return 0;}",
"int f(void);static int f(void){return 0;}int main(void){return 0;}",
"extern int f(void);static int f(void);int main(void){return 0;}",
"static int a[];int main(void){return 0;}",
"int main(void){int x=1;static int y=x;return 0;}",
"int main(void){int x;static int *p=&x;return 0;}",
"int f(void){return 1;}int main(void){static int x=f();return 0;}",
"int main(void){static int x;static int x;return 0;}",
"int main(void){{static int hidden;}return hidden;}",
"int main(void){static int a[];return 0;}",
"int main(void){extern int missing;return missing;}",
"int x;int main(void){extern char x;return 0;}",
"int x;int main(void){int x;extern int x;return 0;}",
"int x;int main(void){extern int x;int x;return 0;}",
"int main(void){extern int x=1;return 0;}",
"int main(void){{extern int hidden;}return hidden;}",
"int main(void){extern int hidden;return 0;}int f(void){return hidden;}",
"extern int x;char x;int main(void){return 0;}",
"int x;int x=1;int x=2;int main(void){return 0;}",
"extern int x;int main(void){return x;}",
"extern int a[];int main(void){return sizeof(a);}",
"int a[2];extern int a[3];int main(void){return 0;}",
"int main(void){int *p,*q;p-=q;return 0;}",
"int main(void){int *p;int x=0;x+=p;return 0;}",
"int main(void){int *p,*q;return sizeof(p-=q);}",
"int main(void){int *p;return sizeof(p<<=1);}",
"int main(void){int a[2];return sizeof(a=0);}",
"int main(void){int a[2];return sizeof(a++);}",
"int main(void){return sizeof(1=2);}",
"int main(void){return sizeof(++1);}",
"int main(void){void *p;return sizeof(p+=1);}",
"int f(int (*)[]);int f(int (*)[2]);int f(int (*)[3]);int main(void){return 0;}",
"int f(int (*)[]);int f(char (*)[]);int main(void){return 0;}",
"int f(int (**)[]);int f(int (*)[]);int main(void){return 0;}",
"int main(void){int *p;p<<=1;return 0;}",
"int main(void){int *p;p>>=1;return 0;}",
"int main(void){int *p;return (int)(p<<1);}",
"int main(void){int *p;return sizeof(p>>1);}",
"int main(void){int *p;return (int)(p*2);}",
"int main(void){int *p;return sizeof(p|1);}",
"int main(void){int *p;return sizeof(~p);}",
"void a[2];int main(void){return 0;}",
"int a[2][];int main(void){return 0;}",
"int main(void){return sizeof(int[]);}",
@@ -443,6 +1323,7 @@ static void host_language_rejections(void) {
"int f(int x,int x){return x;}int main(void){return f(1,2);}",
"int main(void){switch(1){case 1:;case 1:return 0;}}",
"int main(void){switch(1){default:;default:return 0;}}",
"case 1:return 0;",
"int main(void){case 1:return 0;}",
"int main(void){switch(1){default:continue;}return 0;}",
"int a[1/0];int main(void){return 0;}",
@@ -475,16 +1356,23 @@ static void host_language_rejections(void) {
"int main(void){int a[4096][4096];return 0;}",
"int main(void){int a[2],b[2];return sizeof(a+b);}",
"int main(void){void *p;return sizeof(p+1);}",
"int main(void){int a[2];return sizeof(a[a]);}"
"int main(void){int a[2];return sizeof(a[a]);}",
"int one(int x){return x;}int two(int x,int y){return x+y;}int main(void){int (*p)(int)=two;return 0;}",
"int one(int x){return x;}int main(void){int (*p)(int)=one;return p(1,2);}",
"int main(void){int x=1;int (*p)(int)=&x;return 0;}",
"int main(void){int x;int (*p)(int)=(int (*)(int))&x;return 0;}"
};
for(unsigned i=0;i<sizeof(sources)/sizeof(sources[0]);i++) {
write_text("build/check.c",sources[i]);
write_text("build/check.basm","bob!\n");write_text("build/check.b16","bob!\n");
check(system("gcc -E -P -nostdinc -undef -I kernel build/check.c -o build/check.i > build/compiler.log 2>&1")==0,"language rejection preprocessing");
check(system(COMPILER " build/check.i build/check.basm build/check.b16 > build/compiler.log 2>&1")!=0,"invalid C must fail compilation");
if(i==0){char *diagnostic=read_text("build/compiler.log");contains(diagnostic,"code/relocation limit exceeded");free(diagnostic);}
if(i==1){char *diagnostic=read_text("build/compiler.log");contains(diagnostic,"expression nesting exceeds 256 levels");free(diagnostic);}
char *prior=read_text("build/check.basm");check(!strcmp(prior,"bob!\n"),"failed compile preserves BASM output");free(prior);
prior=read_text("build/check.b16");check(!strcmp(prior,"bob!\n"),"failed compile preserves binary output");free(prior);
}
free(deep_expression);free(relocation_limit);
}
static void image_validation(void) {
FILE *in=fopen("build/kernel.b16","rb");if(!in)fail("kernel image missing");
@@ -503,7 +1391,7 @@ static void basm_route(void) {
}
int main(void) {
console_and_commands();input_bounds();allocator_and_files();resident_compiler();
compiler_extensions();editor_and_aliases();
program_loading_and_recovery();host_compiler_and_runtime();host_language_rejections();file_management();compile_workflow();usability();persistence();shell_editing();image_validation();basm_route();
compiler_extensions();wide_guest();editor_and_aliases();
program_loading_and_recovery();native_string_library();host_compiler_and_runtime();host_language_rejections();file_management();compile_workflow();usability();persistence();shell_editing();image_validation();basm_route();wide_kernel_workflow();wide_local_arrays();wide_array_parameters();wide_resident_large_output();wide_function_prototypes();wide_function_pointers();wide_local_offset_limit();
printf("bob!\n%d checks passed.\n",checks);return 0;
}
+9 -5
View File
@@ -5,13 +5,17 @@ int __cmp_ge(int a, int b) { return a >= b; }
int __cmp_eq(int a, int b) { return a == b; }
int __cmp_ne(int a, int b) { return a != b; }
int __mul(int a, int b) {
int result; result = 0;
if (b > 0) b = -b;
else a = -a;
while (b < 0) { result = result + a; b++; }
int result; int bit; result = 0; bit = 1;
/* The guest uses wrapping 16-bit words. Each bit contributes its shifted
multiplicand; the mask wraps to zero after exactly sixteen steps. */
while (bit) {
if (b & bit) result = result + a;
a = a + a; bit = bit + bit;
}
return result;
}
int __divneg(int a, int b) {
if(b == -1)return -a;
int q; q = 0;
while (a <= b) { a = a - b; q++; }
return q;
@@ -19,7 +23,7 @@ int __divneg(int a, int b) {
int __div(int a, int b) {
int negative; int q;
if (b == 0) return 0;
negative = (a < 0) != (b < 0);
negative = (a ^ b) < 0;
if (a > 0) a = -a;
if (b > 0) b = -b;
q = __divneg(a, b);
+75
View File
@@ -0,0 +1,75 @@
/* bob32 arithmetic helpers. All results use native 32-bit wraparound. */
int __cmp_lt(int a, int b) { return a < b; }
int __cmp_gt(int a, int b) { return a > b; }
int __cmp_le(int a, int b) { return a <= b; }
int __cmp_ge(int a, int b) { return a >= b; }
int __cmp_eq(int a, int b) { return a == b; }
int __cmp_ne(int a, int b) { return a != b; }
int __mul(int a, int b) {
int result=0, bit=1, i=0;
while(i<32) {
if(b & bit) result=result+a;
a=a+a; bit=bit+bit; i++;
}
return result;
}
int __u_lt(int a, int b) {
if(a<0) { if(b>=0) return 0; }
else if(b<0) return 1;
return a<b;
}
int __u_gt(int a, int b) { return __u_lt(b,a); }
int __u_le(int a, int b) { return !__u_lt(b,a); }
int __u_ge(int a, int b) { return !__u_lt(a,b); }
int __u_div(int a, int b) {
int q=0, r=0, i=0, carry, bit;
if(b==0) return 0;
while(i<32) {
carry=r<0; bit=a<0;
r=r+r+bit; a=a+a; q=q+q;
if(carry || !__u_lt(r,b)) { r=r-b; q++; }
i++;
}
return q;
}
int __u_mod(int a, int b) {
if(b==0) return 0;
return a-__mul(__u_div(a,b),b);
}
int __div(int a, int b) {
int negative=(a<0)!=(b<0), ua, ub, q;
if(b==0) return 0;
ua=a<0?0-a:a; ub=b<0?0-b:b;
q=__u_div(ua,ub);
return negative?0-q:q;
}
int __mod(int a, int b) {
int ua, ub, r;
if(b==0) return 0;
ua=a<0?0-a:a; ub=b<0?0-b:b;
r=__u_mod(ua,ub);
return a<0?0-r:r;
}
int __or(int a, int b) { return ~(~a & ~b); }
int __xor(int a, int b) { return __or(a,b) & ~(a & b); }
int __shl(int a, int b) {
if(b<0 || b>31) return 0;
while(b>0) { a=a+a; b--; }
return a;
}
int __shr(int a, int b) {
int low;
if(b<0 || b>31) return 0;
while(b>0) {
low=a&1;
if(a<0) a=-1073741824+((a&2147483647)-low)/2;
else a=(a-low)/2;
b--;
}
return a;
}
int __u_shr(int a, int b) {
if(b<0 || b>31) return 0;
while(b>0) { a=__shr(a,1)&2147483647; b--; }
return a;
}
+987 -173
View File
File diff suppressed because it is too large. Load diff
+26 -9
View File
@@ -2,44 +2,61 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
#ifdef _WIN32
#include <direct.h>
#define EXE ".exe"
#define BUILD_DIR "build\\"
#define BOB_COMMAND "bob.exe"
#define BOB32_COMMAND "bob32.exe"
#else
#include <sys/stat.h>
#define EXE ""
#define BUILD_DIR "./build/"
#define BOB_COMMAND "./bob"
#define BOB32_COMMAND "./bob32"
#endif
static void run(const char *command) {
if(system(command)!=0){fprintf(stderr,"Build failed: %s\n",command);exit(1);}
}
int main(int argc,char **argv) {
if(argc>2||(argc==2&&strcmp(argv[1],"--run")&&strcmp(argv[1],"--test"))) {
fprintf(stderr,"Usage: build [--run | --test] (from repository root)\n");return 1;
if(argc>2||(argc==2&&strcmp(argv[1],"--run")&&strcmp(argv[1],"--run32")&&strcmp(argv[1],"--test"))) {
fprintf(stderr,"Usage: build [--run | --run32 | --test] (from repository root)\n");return 1;
}
#ifdef _WIN32
_mkdir("build");
FILE *gcc=fopen("C:/msys64/ucrt64/bin/gcc.exe","rb");
if(gcc){fclose(gcc);const char *path=getenv("PATH");size_t size=(path?strlen(path):0)+64;
char *value=malloc(size);if(!value)return 1;snprintf(value,size,"C:/msys64/ucrt64/bin;%s",path?path:"");_putenv_s("PATH",value);free(value);}
int directory_result=_mkdir("build");
#else
mkdir("build",0777);
int directory_result=mkdir("build",0777);
#endif
if(directory_result && errno!=EEXIST){perror("build");return 1;}
struct stat directory;
if(stat("build",&directory)) {perror("build");return 1;}
#ifdef _WIN32
int is_directory=(directory.st_mode&_S_IFMT)==_S_IFDIR;
#else
int is_directory=S_ISDIR(directory.st_mode);
#endif
if(!is_directory){
fprintf(stderr,"build must be a directory\n");return 1;
}
run("gcc -std=gnu11 -O2 -Wall -Wextra -Werror main.c -o bob" EXE);
run("gcc -std=gnu11 -O2 -Wall -Wextra -Werror main.c -o bob32" EXE);
run("gcc -std=c11 -O2 -Wall -Wextra -Werror tools/bobcc.c -o build/bobcc" EXE);
run("gcc -E -P -nostdinc -undef -DBOBC_LEGACY=0 -I kernel kernel/kernel.c -o build/kernel.i");
run(BUILD_DIR "bobcc" EXE " build/kernel.i kernel.basm build/kernel.b16");
run("gcc -E -P -nostdinc -undef -DBOBC_LEGACY=0 -DBOBC_WIDE=1 -I kernel kernel/kernel.c -o build/kernel32.i");
run(BUILD_DIR "bobcc" EXE " build/kernel32.i build/kernel32.basm build/kernel32.b32 --wide-kernel");
if(argc==2&&!strcmp(argv[1],"--test")) {
run("gcc -std=c11 -O2 -Wall -Wextra -Werror tests/test_cpu.c -o build/test_cpu" EXE);
run(BUILD_DIR "test_cpu" EXE);
run("gcc -std=c11 -O2 -Wall -Wextra -Werror tests/test_os.c -o build/test_os" EXE);
run(BUILD_DIR "test_os" EXE);
#ifdef _WIN32
run("gcc -std=c11 -O2 -Wall -Wextra -Werror tests/test_console.c -o build/test_console.exe");
run("build\\test_console.exe");
#endif
} else if(argc==2) run(BOB_COMMAND " --boot build/kernel.b16");
} else if(argc==2&&!strcmp(argv[1],"--run32")) run(BOB32_COMMAND " --boot build/kernel32.b32");
else if(argc==2) run(BOB_COMMAND " --boot build/kernel.b16");
return 0;
}
+26
View File
@@ -0,0 +1,26 @@
/* Native 16-bit unsigned operations, expressed in the signed C foundation. */
int __u_lt(int a, int b) {
if (a < 0) { if (b >= 0) return 0; }
else if (b < 0) return 1;
return a < b;
}
int __u_gt(int a, int b) { return __u_lt(b, a); }
int __u_le(int a, int b) { return !__u_lt(b, a); }
int __u_ge(int a, int b) { return !__u_lt(a, b); }
int __u_div(int a, int b) {
int q = 0, r = 0, i = 0, carry, bit;
if (b == 0) return 0;
while (i < 16) {
carry = r < 0; bit = a < 0;
r = r + r + bit; a = a + a; q = q + q;
if (carry || !__u_lt(r, b)) { r = r - b; q++; }
i++;
}
return q;
}
int __u_mod(int a, int b) { if (b == 0) return 0; return a - __mul(__u_div(a, b), b); }
int __u_shr(int a, int b) {
if (b < 0 || b > 15) return 0;
while (b > 0) { a = __shr(a, 1) & 32767; b--; }
return a;
}