This commit is contained in:
Alvin-Zilverstand committed 2026-10-06 22:05:14 +02:00
1 parent 74bda7d8b2
commit 472df35261
23 files changed
+32910 -42

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
build/
__pycache__/
+245
View File
@@ -0,0 +1,245 @@
# bob16 OS
The kernel, shell and resident C compiler run as native bob16 instructions.
All project code is C or BASM. No Python or Python packages are used.
## Run now
Start the supplied `bob.exe`, then enter `kernel.basm` at its source-file prompt.
The kernel prints `bob!` and opens `bob>`. Type `help` for commands.
If the emulator starts in another directory, enter the full path to `kernel.basm`.
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.
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`.
## Commands
| Command | Behavior |
| --- | --- |
| `help` / `help COMMAND` | Show commands or detailed usage and examples |
| `echo bob!` | Print text |
| `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 |
| `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 |
| `copy old new` | Copy text or program contents to a new name |
| `rename old new` | Change a name, including when all slots are full |
| `delete name` | Permanently remove a RAM file and free its slot |
| `read name` | Print a text file |
| `write name bob!` | Create or replace a one-line text file |
| `edit name` | Open an existing text file or create one in the line editor |
| `cc bob.c bob` | Compile a C source file inside the emulator |
| `cc bob.c` | Compile to the default program file `app` |
| `go bob.c` | Compile to `app` and run only if compilation succeeds |
| `go bob.c bob` | Compile and run with an explicit output name |
| `load name 0x4001 ...` | Store raw bob16 machine words as a program file |
| `run name` | Load a binary program into reserved RAM, execute, return |
| `halt` | Stop the emulator |
Command lines hold up to 127 characters. Longer lines are completely consumed
and rejected so their tail cannot become another command. Input is terminated
and handles CRLF, backspace and EOF. Decimal values are signed 16-bit; hex values
cover all 16-bit bit patterns. Addresses are word addresses.
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. Files and allocations are lost on exit; disk persistence is not
implemented. Allocation is a zeroing bump allocator with no freeing. `poke` is
restricted to heap RAM so it cannot corrupt the shell.
Copy and rename refuse to overwrite an existing destination. Choose a new
name or explicitly delete the destination first. Delete has no undo. Names
cannot contain spaces. Both commands preserve whether a file is text or a
program; copying requires a free slot, while renaming does not.
To try the supplied example, enter `go bob.c`; its output is `bob!`, followed
by `Exit 0`. The compiler refuses to replace its own source. On failure it
leaves an existing output intact and `go` does not run that old program.
Diagnostics report the first detected error's character offset, line and
column (one based); the location can be just after the token that caused it.
## Edit existing files
`edit name` loads the current text, displays numbered lines and opens `edit>`.
Typing ordinary text appends a line; existing content is retained. The editor
uses a scratch buffer, so opening a file does not immediately change it.
| Editor command | Effect |
| --- | --- |
| `:p` | Show all lines with numbers |
| `:p N` | Show only line N for easier navigation |
| `:a TEXT` | Append a line, including text beginning with a colon |
| `:i N TEXT` | Insert a line before line N; a final empty line position allows appending |
| `:r N TEXT` | Replace line N |
| `:d N` | Delete line N |
| `:u` | Toggle undo/redo of the most recent successful text change |
| `:w` | Save while continuing to edit |
| `:wq` or `.` | Save and return to bob> |
| `:q` | Quit if unchanged; otherwise explain how to save or discard |
| `:q!` | Explicitly discard changes since the last save and return to bob> |
For example, `edit bob.c`, `:r 1 int main(void) { println("bob!"); return 0; }`,
then `:wq` changes the existing source rather than recreating it from scratch.
Each edit line has the same 127-character input limit as the shell. Oversize
changes and invalid line numbers are rejected while the editor remains open.
EOF discards unsaved changes. Binary program files cannot be opened as text.
The editor is a line editor, not a full-screen terminal application.
## Compile C inside bob16
The initial RAM file `bob.c` contains:
```c
int main(void) { println("bob!"); return 0; }
```
At `bob>` enter:
```text
cc bob.c bob
run bob
```
The program prints `bob!`, reports `Exit 0` and returns to the shell. No host
compiler is involved: the resident compiler parses C and generates bob16
machine words in RAM, rather than interpreting the source.
To write another program, enter `edit count.c`, then:
```c
int main(void) {
int n = 0;
while (n < 3) { n = n + 1; }
if (n == 3) println("bob!");
return 0;
}
```
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
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
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.
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
console/arithmetic routines and belong to the kernel build that compiled them.
## Native programs and recovery
`run` clears the program region and copies in the binary RAM file at `0x9000`.
`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
instructions and forbidden services return a program fault.
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.
## Kernel routines and memory
- `kernel/runtime.c`: print, println, signed decimal/four-digit hex printing,
bounded line input, strlen, strcmp, word-based memcpy/memset and alloc.
- `kernel/files.c`: RAM filesystem.
- `kernel/compiler.c`: resident C compiler.
- `kernel/shell.c`: commands.
- `kernel/kernel.c`: includes these as one translation unit and runs the shell.
| Word addresses | Use |
| --- | --- |
| `0x0000..0x00FF` | Boot ROM and reserved return sentinel |
| `0x0300..0x8FFF` | Kernel code, globals, strings and editor/compiler buffers |
| `0x9000..0xBFFF` | Loaded program, variables and downward program stack |
| `0xC000..0xDFFF` | 8,192-word heap |
| `0xE000..0xEFFF` | Kernel stack, growing down from `0xF000` |
| `0xF000..0xFFFF` | Eight file-content buffers; protected from program writes |
There are no interrupts, multitasking or hardware memory protection. The write
checks and cycle limits are emulator services. Keep kernel recursion within its
reserved stack. Each guest int, char and pointer occupies one 16-bit word;
strings are unpacked ASCII. Arithmetic wraps to 16 bits, division truncates
toward zero and right shift is arithmetic. Arithmetic helpers return zero for
division by zero or invalid shift counts.
## Rebuild using C and GCC
The supplied `bob.exe` and `kernel.basm` require no build step. To edit and
rebuild the kernel, use GCC from the repository root:
Close running `bob.exe` sessions before rebuilding: Windows locks executable
files while they are running. Rebuilding replaces `bob.exe` and `kernel.basm`;
it does not preserve the volatile RAM files from a previous session.
```powershell
& 'C:\msys64\ucrt64\bin\gcc.exe' -std=c11 -O2 tools/build.c -o build.exe
./build.exe
./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.
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
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,
increment/decrement, if, while, for, break, continue and returns.
Shadowing, structs, typedefs, unsigned types, floating point, function pointers,
sizeof, variadics, local array initialization and standard headers are unsupported.
Host tools themselves use ordinary host C types.
To compile another standalone guest source from the repository root:
```powershell
gcc -E -P -nostdinc -undef -DBOBC_LEGACY=0 -I kernel my_program.c -o build/program.i
./build/bobcc.exe build/program.i program.basm build/program.b16
```
Host-compiled BASM starts at address zero as a standalone guest. It is not a
RAM file for the shell's run command, whose programs use a different load
address. Host arithmetic helpers are in `tools/arithmetic.c`, also written
in the supported guest C subset.
`tests/test_os.c` checks console/commands, input bounds, memory/string routines,
heap exhaustion, file limits, resident compilation/execution, raw programs,
fault/time-limit recovery, host compilation, binary-image validation and the
interactive BASM route. Successful guest examples print `bob!`.
Function contracts and execution status codes are documented in
[the kernel API](kernel/API.md).
## Emulator services and boot image
Traps 0-3 retain halt, character output, string output and bounded string input.
Trap 4 reads the simulated boot disk; trap 5 returns a character or -1 at EOF;
trap 6 runs a loaded guest. The compiler exposes them through `bob.h`.
A binary kernel contains `B16K` and five little-endian 16-bit fields: version 1,
origin, entry, word count and sum of payload words modulo 65536, then the payload.
The host validates it and installs the boot ROM, which loads it through trap 4
and jumps to startup. Startup initializes the stack and calls main. The BASM
route loads the same instructions through `.fill` and a startup jump.
+12 -2
View File
@@ -1,3 +1,13 @@
CC ?= gcc
CFLAGS ?= -std=gnu11 -O2 -Wall -Wextra -Werror
.PHONY: all c-os test
all:
gcc main.c -o main.exe
./main.exe
$(CC) $(CFLAGS) tools/build.c -o build-tool
./build-tool
c-os: all
./bob --boot build/kernel.b16
test: all
./build-tool --test
+12 -5
View File
@@ -1,4 +1,11 @@
# bob16
To boot a kernel written in C **inside bob16**, see [C kernel and bootloader](C_OS.md).
To run immediately, start the supplied `bob.exe` and enter `kernel.basm` at its
assembly-file prompt. No build is needed. The documentation explains how to
regenerate BASM after editing the C kernel, or build the binary boot workflow.
The OS has a shell, RAM files, allocation, program loading, and a resident C
compiler. Its tools are written in C; no Python is required.
extremely simple custom 16 bit cpu emulator and assembler as seen on youtube: https://youtu.be/tlIqosU75CQ?is=ZAVWsYRDMPrUKOej \
use at your own risk! code is thoroughly untested so if you find any bugs let me know asap so i can fix them asap
@@ -32,10 +39,10 @@ ex. and r0 r1
*AND (in place immediate): r[dst] &= imm[7]\
ex. and r0 4
*NOT (normal): r[dst] = !r[src]\
*NOT (normal): r[dst] = ~r[src]\
ex. not r0 r1
*NOT (immediate): !r[dst]\
*NOT (in place): r[dst] = ~r[dst]\
ex. not r1
*LD: r[dst] <= memory[pc + imm[9]]\
@@ -69,8 +76,8 @@ ex. jsr 50
JSRR: r[7] = pc, pc = r[src]\
ex. jsrr r0
*LEA: r[src] = pc\
ex. lea r0
*LEA: r[dst] = pc + signed imm[9]\
ex. lea r0 0
RET: pc = r[7]\
ex. ret
@@ -83,7 +90,7 @@ TRAP (vector 3): r[7] = pc, pc = r[0], gets user inputted string with max length
ex. trap 0
**** NOTES ****
any immediate values in assembly will clamp to be within bounds, e.g. for ADD normal immediate, if you put 60 as the immediate value it will clamp to 15\
any immediate values in assembly will clamp to be within bounds, e.g. for ADD normal immediate, if you put 60 as the immediate value it will clamp to 7\
any unused bits in a machine code instruction will be set to 0\
strings are NOT packed!!!\
pc is *always* incremented at the start of execution, so instructions that change or use pc such as jmp will use the incremented pc as the base\
BIN
View File
Binary file not shown.
+14
View File
@@ -0,0 +1,14 @@
; Reference source for the ROM installed by bootImage() in main.c.
; The emulator fills the three metadata words from the validated B16K header.
ld r0 7
ld r1 7
ld r2 7
trap 4
ld r3 6
jmp r3
trap 0
.fill 0
.fill 0300
.fill 0
.fill 0
.fill 0300
BIN
View File
Binary file not shown.
+1 -1
View File
@@ -2,4 +2,4 @@ ld r0 2
trap 2
trap 0
.fill 0x0004
.stringz bob
.stringz bob!
+30629
View File
File diff suppressed because it is too large. Load diff
+83
View File
@@ -0,0 +1,83 @@
# Kernel API
Include `runtime.h` in guest kernel source. The host bob16 compiler treats each
int, char and pointer as a single 16-bit word. These are guest routines, not the
host C library. Headers and source are compiled together by `kernel/kernel.c`.
## Console
| Function | Contract |
| --- | --- |
| `void print(char *text)` | Print an unpacked ASCII string up to its zero terminator |
| `void println(char *text)` | Print the string and one newline |
| `void print_dec(int number)` | Print a signed value, including -32768, without a newline |
| `void print_hex(int number)` | Print its raw 16 bits as `0x` and four uppercase hex digits |
| `int read_line(char *buffer, int capacity)` | Read/terminate a line; length on success, -1 for truncation/invalid capacity, -2 for EOF with no characters |
The caller must supply a writable buffer of at least capacity words. At most
capacity-1 characters are stored. Excess characters are consumed until newline,
so they do not leak into the next command. Newline/CR are not stored. Backspace
removes a stored character. A partial final line at EOF is returned normally;
the next read reports EOF. The host terminal supplies line editing and echo.
The low-level `bob_putc(int)` sends the low eight bits to stdout. `bob_getc()`
returns 0..255 or -1 at EOF. `bob_puts()` adds a newline; use print for prompts.
## Strings, memory and allocation
| Function | Contract |
| --- | --- |
| `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 |
| `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.
## RAM filesystem
`file_find(name)` returns a slot or -1. `file_name(slot)` and
`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.
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
single dot line. :q or EOF discards changes since the most recent save. Oversize
changes are rejected without modifying the current buffer.
Resident compilation similarly commits output only after successful parsing and
code generation. Storage is volatile and disappears when bob.exe stops.
## 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.
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.
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.
`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.
+10
View File
@@ -0,0 +1,10 @@
#ifndef BOB_KERNEL_H
#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_gets(char *buffer, int capacity);
void bob_halt(void);
int bob_getc(void);
int bob_run(int entry);
#endif
+418
View File
@@ -0,0 +1,418 @@
/* Resident recursive-descent compiler. It emits bob16 machine words in RAM. */
#define TOKEN_ID 256
#define TOKEN_NUMBER 257
#define TOKEN_STRING 258
#define TOKEN_EQ 259
#define TOKEN_NE 260
#define TOKEN_LE 261
#define TOKEN_GE 262
#define TOKEN_AND 263
#define TOKEN_OR 264
#define TOKEN_INC 265
#define TOKEN_DEC 266
#define TOKEN_SHL 267
#define TOKEN_SHR 268
#define TOKEN_ADD_ASSIGN 269
#define TOKEN_SUB_ASSIGN 270
#define TOKEN_MUL_ASSIGN 271
#define TOKEN_DIV_ASSIGN 272
#define TOKEN_MOD_ASSIGN 273
#define TOKEN_AND_ASSIGN 274
#define TOKEN_OR_ASSIGN 275
#define TOKEN_XOR_ASSIGN 276
#if BOBC_LEGACY
#define CALL_R3 0xcb00
#else
#define CALL_R3 0xc300
#endif
char *cc_source;
int cc_token;
int cc_value;
char cc_text[64];
int cc_error;
int cc_position;
int cc_code[511];
char cc_names[384];
int cc_variables;
int cc_error_offset;
int cc_depth;
char *cc_begin;
int cc_alpha(int ch) { return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == '_'; }
int cc_digit(int ch) { return ch >= '0' && ch <= '9'; }
void cc_fail(void) {
if (!cc_error) cc_error_offset = (int)(cc_source - cc_begin);
cc_error = 1;
}
void cc_next(void) {
int ch; int count; int digit; int base;
while (1) {
while (*cc_source == ' ' || *cc_source == '\t' || *cc_source == '\n' || *cc_source == '\r') cc_source++;
if (cc_source[0] == '/' && cc_source[1] == '/') {
while (*cc_source && *cc_source != '\n') cc_source++;
} else if (cc_source[0] == '/' && cc_source[1] == '*') {
cc_source = cc_source + 2;
while (*cc_source && !(cc_source[0] == '*' && cc_source[1] == '/')) cc_source++;
if (!*cc_source) { cc_fail(); cc_token = 0; return; }
cc_source = cc_source + 2;
} else break;
}
ch = *cc_source; cc_text[0] = 0;
if (ch == 0) { cc_token = 0; return; }
if (cc_alpha(ch)) {
count = 0;
while (cc_alpha(*cc_source) || cc_digit(*cc_source)) {
if (count == 63) { cc_fail(); cc_token = 0; return; }
cc_text[count++] = *cc_source++;
}
cc_text[count] = 0; cc_token = TOKEN_ID; return;
}
if (cc_digit(ch)) {
cc_value = 0; count = 0; base = 10;
if (cc_source[0] == '0' && (cc_source[1] == 'x' || cc_source[1] == 'X')) { base = 16; cc_source = cc_source + 2; }
while (1) {
digit = *cc_source;
if (cc_digit(digit)) digit = digit - '0';
else if (base == 16 && digit >= 'a' && digit <= 'f') digit = digit - 'a' + 10;
else if (base == 16 && digit >= 'A' && digit <= 'F') digit = digit - 'A' + 10;
else break;
if ((base == 10 && (cc_value > 3276 || (cc_value == 3276 && digit > 7))) ||
(base == 16 && count == 4)) { cc_fail(); cc_token = 0; return; }
cc_value = cc_value * base + digit; cc_source++; count++;
}
if (!count) cc_fail();
cc_token = TOKEN_NUMBER; return;
}
if (ch == '"' || ch == '\'') {
cc_source++; count = 0;
while (*cc_source && *cc_source != ch) {
digit = *cc_source++;
if (digit == '\\') {
if (!*cc_source) { cc_fail(); break; }
digit = *cc_source++;
if (digit == 'n') digit = '\n';
else if (digit == 't') digit = '\t';
else if (digit != '\\' && digit != '"' && digit != '\'') { cc_fail(); break; }
}
if (count == 63 || digit == 0) { cc_fail(); break; }
cc_text[count++] = digit;
}
if (*cc_source != ch) cc_fail(); else cc_source++;
cc_text[count] = 0;
if (ch == '\'') { if (count != 1) cc_fail(); cc_value = cc_text[0]; cc_token = TOKEN_NUMBER; }
else cc_token = TOKEN_STRING;
return;
}
cc_source++; cc_token = ch;
if (*cc_source == ch) {
if (ch == '&') cc_token = TOKEN_AND;
else if (ch == '|') cc_token = TOKEN_OR;
else if (ch == '+') cc_token = TOKEN_INC;
else if (ch == '-') cc_token = TOKEN_DEC;
else if (ch == '<') cc_token = TOKEN_SHL;
else if (ch == '>') cc_token = TOKEN_SHR;
else if (ch != '=') return;
if (ch != '=') { cc_source++; return; }
}
if (*cc_source == '=') {
if (ch == '=') cc_token = TOKEN_EQ;
else if (ch == '!') cc_token = TOKEN_NE;
else if (ch == '<') cc_token = TOKEN_LE;
else if (ch == '>') cc_token = TOKEN_GE;
else if (ch == '+') cc_token = TOKEN_ADD_ASSIGN;
else if (ch == '-') cc_token = TOKEN_SUB_ASSIGN;
else if (ch == '*') cc_token = TOKEN_MUL_ASSIGN;
else if (ch == '/') cc_token = TOKEN_DIV_ASSIGN;
else if (ch == '%') cc_token = TOKEN_MOD_ASSIGN;
else if (ch == '&') cc_token = TOKEN_AND_ASSIGN;
else if (ch == '|') cc_token = TOKEN_OR_ASSIGN;
else if (ch == '^') cc_token = TOKEN_XOR_ASSIGN;
else return;
cc_source++;
}
}
int cc_is(char *name) { return cc_token == TOKEN_ID && strcmp(cc_text, name) == 0; }
void cc_expect(int token) { if (cc_token != token) { cc_fail(); return; } cc_next(); }
void cg_emit(int word) {
if (cc_position >= 511) { cc_fail(); return; }
cc_code[cc_position++] = word;
}
void cg_literal(int reg, int value) { cg_emit(0x4001 + reg * 512); cg_emit(0xae01); cg_emit(value); }
void cg_push(void) { cg_emit(0x1dff); cg_emit(0x9180); }
void cg_pop(void) { cg_emit(0x6380); cg_emit(0x1d81); }
int cg_jump(int target) {
int patch; patch = cc_position + 2;
cg_literal(3, PROGRAM_BASE + target); cg_emit(0xb600); return patch;
}
void cg_patch(int patch) { if (!cc_error) cc_code[patch] = PROGRAM_BASE + cc_position; }
void cg_call(int address, int args) {
cg_literal(3, address); cg_emit(CALL_R3); cg_emit(0x1d80 + args);
}
int cg_if_zero(void) { cg_emit(0x1080); cg_emit(0xaa04); return cg_jump(0); }
int cc_variable(char *name) {
int i;
for (i = 0; i < cc_variables; i++) if (strcmp(cc_names + i * NAME_WORDS, name) == 0) return i;
return -1;
}
int cc_less(int a, int b) { return a < b; }
int cc_greater(int a, int b) { return a > b; }
int cc_less_equal(int a, int b) { return a <= b; }
int cc_greater_equal(int a, int b) { return a >= b; }
int cc_equal(int a, int b) { return a == b; }
int cc_not_equal(int a, int b) { return a != b; }
int cc_multiply(int a, int b) { return a * b; }
int cc_divide(int a, int b) { return a / b; }
int cc_modulo(int a, int b) { return a % b; }
int cc_negate(int a) { return -a; }
int cc_not(int a) { return !a; }
int cc_bit_or(int a, int b) { return a | b; }
int cc_bit_xor(int a, int b) { return a ^ b; }
int cc_shift_left(int a, int b) { return a << b; }
int cc_shift_right(int a, int b) { return a >> b; }
int cc_truth(int a) { return !!a; }
int cc_loop_depth;
int cc_break_chain[16];
int cc_continue_chain[16];
int cc_precedence(int op) {
if (op == TOKEN_OR) return 1;
if (op == TOKEN_AND) return 2;
if (op == '|') return 3;
if (op == '^') return 4;
if (op == '&') return 5;
if (op == TOKEN_EQ || op == TOKEN_NE) return 6;
if (op == '<' || op == '>' || op == TOKEN_LE || op == TOKEN_GE) return 7;
if (op == TOKEN_SHL || op == TOKEN_SHR) return 8;
if (op == '+' || op == '-') return 9;
if (op == '*' || op == '/' || op == '%') return 10;
return 0;
}
void cc_operation(int op) {
int address;
if (op == '+' || op == '-') {
if (op == '-') { cg_emit(0x3100); cg_emit(0x1181); }
cg_emit(0x1010); return;
}
if (op == '&') { cg_emit(0x2010); return; }
cg_push(); cg_emit(0x1dff); cg_emit(0x9380);
if (op == '*') address = bob_address(cc_multiply);
else if (op == '/') address = bob_address(cc_divide);
else if (op == '%') address = bob_address(cc_modulo);
else if (op == '|') address = bob_address(cc_bit_or);
else if (op == '^') address = bob_address(cc_bit_xor);
else if (op == TOKEN_SHL) address = bob_address(cc_shift_left);
else if (op == TOKEN_SHR) address = bob_address(cc_shift_right);
else if (op == TOKEN_EQ) address = bob_address(cc_equal);
else if (op == TOKEN_NE) address = bob_address(cc_not_equal);
else if (op == '<') address = bob_address(cc_less);
else if (op == '>') address = bob_address(cc_greater);
else if (op == TOKEN_LE) address = bob_address(cc_less_equal);
else address = bob_address(cc_greater_equal);
cg_call(address, 2);
}
void cc_expression(void);
void cc_primary(void) {
int variable; int patch; int start; int count; int op;
if (cc_error) return;
cc_depth++;
if (cc_depth > 32) { cc_fail(); return; }
if (cc_token == TOKEN_NUMBER) { cg_literal(0, cc_value); cc_next(); }
else if (cc_token == TOKEN_STRING) {
count = strlen(cc_text);
/* Inline string data is skipped by an absolute jump. */
patch = cg_jump(0); start = cc_position;
for (variable = 0; variable <= count; variable++) cg_emit(cc_text[variable]);
cg_patch(patch); cg_literal(0, PROGRAM_BASE + start); cc_next();
} else if (cc_token == '(') { cc_next(); cc_expression(); cc_expect(')'); }
else if (cc_token == '-' || cc_token == '!' || cc_token == '+' || cc_token == '~') {
op = cc_token; cc_next(); cc_primary(); cg_push();
if (op == '-') cg_call(bob_address(cc_negate), 1);
else if (op == '!') cg_call(bob_address(cc_not), 1);
else { cg_emit(0x6180); cg_emit(0x1d81); if (op == '~') cg_emit(0x3100); }
} else if (cc_token == TOKEN_INC || cc_token == TOKEN_DEC) {
op = cc_token; cc_next(); variable = cc_variable(cc_text);
if (cc_token != TOKEN_ID || variable < 0) { cc_fail(); return; }
cc_next(); cg_literal(0, 0x9800 + variable); cg_emit(0x6000);
if (op == TOKEN_INC) cg_emit(0x1181); else cg_emit(0x11ff);
cg_literal(1, 0x9800 + variable); cg_emit(0x9040);
} else if (cc_token == TOKEN_ID) {
variable = cc_variable(cc_text);
if (variable < 0) { cc_fail(); return; }
cg_literal(0, 0x9800 + variable); cg_emit(0x6000); cc_next();
if (cc_token == TOKEN_INC || cc_token == TOKEN_DEC) {
op = cc_token; cc_next(); cg_push();
if (op == TOKEN_INC) cg_emit(0x1181); else cg_emit(0x11ff);
cg_literal(1, 0x9800 + variable); cg_emit(0x9040);
cg_emit(0x6180); cg_emit(0x1d81);
}
} else cc_fail();
cc_depth--;
}
void cc_binary(int minimum) {
int op; int level; int shortcut; int end;
cc_primary(); level = cc_precedence(cc_token);
while (!cc_error && level >= minimum && level) {
op = cc_token; cc_next();
if (op == TOKEN_AND || op == TOKEN_OR) {
cg_emit(0x1080);
if (op == TOKEN_AND) cg_emit(0xaa04); else cg_emit(0xa404);
shortcut = cg_jump(0); cc_binary(level + 1);
cg_push(); cg_call(bob_address(cc_truth), 1); end = cg_jump(0);
cg_patch(shortcut); cg_literal(0, op == TOKEN_OR); cg_patch(end);
} else {
cg_push(); cc_binary(level + 1); cg_pop(); cc_operation(op);
}
level = cc_precedence(cc_token);
}
}
void cc_expression(void) { cc_binary(1); }
void cc_patch_chain(int chain, int target) {
int next;
while (chain >= 0 && !cc_error) {
next = cc_code[chain]; cc_code[chain] = PROGRAM_BASE + target; chain = next;
}
}
void cc_simple(void) {
char name[24]; int variable; int address; int op;
if (cc_token == TOKEN_INC || cc_token == TOKEN_DEC) { cc_primary(); return; }
if (cc_token != TOKEN_ID || strlen(cc_text) >= NAME_WORDS) { cc_fail(); return; }
memcpy(name, cc_text, strlen(cc_text) + 1); cc_next(); op = cc_token;
if (op == TOKEN_INC || op == TOKEN_DEC) {
variable = cc_variable(name); if (variable < 0) { cc_fail(); return; }
cc_next(); cg_literal(0, 0x9800 + variable); cg_emit(0x6000);
if (op == TOKEN_INC) cg_emit(0x1181); else cg_emit(0x11ff);
cg_literal(1, 0x9800 + variable); cg_emit(0x9040);
} else if (op == '=' || (op >= TOKEN_ADD_ASSIGN && op <= TOKEN_XOR_ASSIGN)) {
variable = cc_variable(name); if (variable < 0) { cc_fail(); return; }
if (op != '=') { cg_literal(0, 0x9800 + variable); cg_emit(0x6000); cg_push(); }
cc_next(); cc_expression();
if (op != '=') {
cg_pop();
if (op == TOKEN_ADD_ASSIGN) op = '+';
else if (op == TOKEN_SUB_ASSIGN) op = '-';
else if (op == TOKEN_MUL_ASSIGN) op = '*';
else if (op == TOKEN_DIV_ASSIGN) op = '/';
else if (op == TOKEN_MOD_ASSIGN) op = '%';
else if (op == TOKEN_AND_ASSIGN) op = '&';
else if (op == TOKEN_OR_ASSIGN) op = '|';
else op = '^';
cc_operation(op);
}
cg_literal(1, 0x9800 + variable); cg_emit(0x9040);
} else if (op == '(') {
address = 0;
if (strcmp(name, "print") == 0) address = bob_address(print);
else if (strcmp(name, "println") == 0) address = bob_address(println);
else if (strcmp(name, "print_dec") == 0) address = bob_address(print_dec);
else if (strcmp(name, "print_hex") == 0) address = bob_address(print_hex);
else if (strcmp(name, "bob_putc") == 0) address = 1;
if (!address) { cc_fail(); return; }
cc_next(); cc_expression(); cc_expect(')');
if (address == 1) cg_emit(0xf100);
else { cg_push(); cg_call(address, 1); }
} else cc_fail();
}
void cc_statement(void) {
int variable; int start; int patch; int end; int step; int body;
if (cc_error) return;
cc_depth++;
if (cc_depth > 32) { cc_fail(); return; }
if (cc_token == '{') {
cc_next();
while (!cc_error && cc_token && cc_token != '}') cc_statement();
cc_expect('}');
} else if (cc_is("int")) {
cc_next();
if (cc_token != TOKEN_ID || strlen(cc_text) >= NAME_WORDS || cc_variables == 16 || cc_variable(cc_text) >= 0) { cc_fail(); return; }
variable = cc_variables++; memcpy(cc_names + variable * NAME_WORDS, cc_text, strlen(cc_text) + 1);
cc_next();
if (cc_token == '=') { cc_next(); cc_expression(); }
else cg_literal(0, 0);
cg_literal(1, 0x9800 + variable); cg_emit(0x9040); cc_expect(';');
} else if (cc_is("return")) {
cc_next();
if (cc_token == ';') cg_literal(0, 0); else cc_expression();
cg_emit(0x1cd0); cg_emit(0x6b80); cg_emit(0x1d81); cg_emit(0x6f80); cg_emit(0x1d81); cg_emit(0xe000);
cc_expect(';');
} else if (cc_is("break") || cc_is("continue")) {
variable = cc_is("continue");
if (!cc_loop_depth) { cc_fail(); return; }
cc_next(); patch = cg_jump(0);
if (variable) {
cc_code[patch] = cc_continue_chain[cc_loop_depth - 1]; cc_continue_chain[cc_loop_depth - 1] = patch;
} else {
cc_code[patch] = cc_break_chain[cc_loop_depth - 1]; cc_break_chain[cc_loop_depth - 1] = patch;
}
cc_expect(';');
} else if (cc_is("for")) {
if (cc_loop_depth == 16) { cc_fail(); return; }
cc_next(); cc_expect('(');
if (cc_token == ';') cc_next(); else cc_statement();
start = cc_position;
if (cc_token == ';') cg_literal(0, 1); else cc_expression();
cc_expect(';'); patch = cg_if_zero(); body = cg_jump(0); step = cc_position;
if (cc_token != ')') cc_simple();
cc_expect(')'); cg_jump(start); cg_patch(body);
cc_break_chain[cc_loop_depth] = -1; cc_continue_chain[cc_loop_depth] = -1; cc_loop_depth++;
cc_statement(); cc_loop_depth--; cg_jump(step); cg_patch(patch);
cc_patch_chain(cc_break_chain[cc_loop_depth], cc_position);
cc_patch_chain(cc_continue_chain[cc_loop_depth], step);
} else if (cc_is("if") || cc_is("while")) {
variable = cc_is("while"); cc_next(); cc_expect('(');
start = cc_position; cc_expression(); cc_expect(')');
patch = cg_if_zero();
if (variable) {
if (cc_loop_depth == 16) { cc_fail(); return; }
cc_break_chain[cc_loop_depth] = -1; cc_continue_chain[cc_loop_depth] = -1; cc_loop_depth++;
}
cc_statement();
if (variable) {
cc_loop_depth--; cg_jump(start); cg_patch(patch);
cc_patch_chain(cc_break_chain[cc_loop_depth], cc_position);
cc_patch_chain(cc_continue_chain[cc_loop_depth], start);
}
else if (cc_is("else")) { end = cg_jump(0); cg_patch(patch); cc_next(); cc_statement(); cg_patch(end); }
else cg_patch(patch);
} else if (cc_token == TOKEN_ID || cc_token == TOKEN_INC || cc_token == TOKEN_DEC) {
cc_simple(); cc_expect(';');
} else if (cc_token == ';') cc_next();
else cc_fail();
cc_depth--;
}
int compile_command(char *source_name, char *output_name) {
int slot; int result; int i; int line; int column;
slot = file_find(source_name);
if (slot < 0 || file_kinds[slot]) { println("C source file not found."); return 0; }
if (!*output_name || strlen(output_name) >= NAME_WORDS) { println("Usage: cc SOURCE OUTPUT"); return 0; }
if (strcmp(source_name, output_name) == 0) { println("Output must differ from source; choose another name."); return 0; }
cc_source = file_content(slot); cc_begin = cc_source;
cc_error = 0; cc_position = 0; cc_variables = 0; cc_error_offset = 0; cc_depth = 0; cc_loop_depth = 0;
memset(cc_names, 0, 384); cc_next();
if (!cc_is("int")) cc_fail(); else cc_next();
if (!cc_is("main")) cc_fail(); else cc_next();
cc_expect('('); if (cc_is("void")) cc_next(); cc_expect(')');
if (cc_token != '{') cc_fail();
/* Preserve the return address and caller frame; runProgram provides a stack. */
cg_emit(0x1dff); cg_emit(0x9f80); cg_emit(0x1dff); cg_emit(0x9b80); cg_emit(0x1ae0);
cc_statement();
if (cc_token) cc_fail();
cg_literal(0, 0);
cg_emit(0x1cd0); cg_emit(0x6b80); cg_emit(0x1d81); cg_emit(0x6f80); cg_emit(0x1d81); cg_emit(0xe000);
if (cc_error) {
print("C compile error near character "); print_dec(cc_error_offset);
println(". Unsupported syntax or source/code/nesting limit exceeded.");
line = 1; column = 1;
for (i = 0; i < cc_error_offset; i++) {
if (cc_begin[i] == '\n') { line++; column = 1; }
else column++;
}
print(source_name); print(": line "); print_dec(line);
print(", column "); print_dec(column); println(". Use edit to fix the source.");
return 0;
}
result = file_write(output_name, cc_code, cc_position, 1);
if (result < 0) println("Cannot save compiled program (max 511 words).");
else { print("Compiled "); print_dec(cc_position); println(" words."); }
return result >= 0;
}
+81
View File
@@ -0,0 +1,81 @@
char file_names[192];
int file_lengths[8];
int file_kinds[8];
int file_used[8];
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_find(char *name) {
int i;
for (i = 0; i < FILE_COUNT; i++)
if (file_used[i] && strcmp(file_name(i), name) == 0) return i;
return -1;
}
int file_slot(char *name) {
int slot; int length;
length = strlen(name);
if (length == 0 || length >= NAME_WORDS) return -1;
slot = file_find(name);
if (slot >= 0) return slot;
for (slot = 0; slot < FILE_COUNT; slot++) {
if (!file_used[slot]) {
memset(file_name(slot), 0, NAME_WORDS);
memcpy(file_name(slot), name, length);
file_used[slot] = 1;
return slot;
}
}
return -1;
}
int file_write(char *name, int *data, int length, int kind) {
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;
return slot;
}
void file_list(void) {
int i; int count;
count = 0;
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)");
else println(" chars (text)");
count++;
}
}
if (!count) println("No files.");
}
void file_manage(char *operation, char *name, char *destination) {
int slot; int target;
if (!*name) { println("Usage: copy OLD NEW | rename OLD NEW | delete NAME"); return; }
slot = file_find(name);
if (slot < 0) { println("File not found. Use ls to see names."); return; }
if (strcmp(operation, "delete") == 0) {
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) {
println("Destination needs 1..23 characters."); return;
}
if (file_find(destination) >= 0) {
println("Destination exists; choose another name or delete it first."); return;
}
if (strcmp(operation, "rename") == 0) {
memset(file_name(slot), 0, NAME_WORDS);
memcpy(file_name(slot), destination, strlen(destination));
println("Renamed."); return;
}
target = file_write(destination, file_content(slot), file_lengths[slot], file_kinds[slot]);
if (target < 0) println("File slots full (8). Delete a file and retry.");
else println("Copied.");
}
+22
View File
@@ -0,0 +1,22 @@
#include "runtime.h"
#include "runtime.c"
#include "files.c"
#include "compiler.c"
#include "shell.c"
int main(void) {
int length; char *sample;
println("bob!");
println("bob16 OS: help COMMAND for usage; go bob.c runs the example.");
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);
while (1) {
print("bob> ");
length = read_line(command_line, 128);
if (length == -2) { bob_putc('\n'); return 0; }
if (length < 0) println("Command too long.");
else shell_command(command_line);
}
return 0;
}
+69
View File
@@ -0,0 +1,69 @@
int heap_used;
int bit_masks[16] = {-32768,16384,8192,4096,2048,1024,512,256,128,64,32,16,8,4,2,1};
int bit_weights[4] = {8,4,2,1};
int strlen(char *text) { int n; n = 0; while (text[n]) n++; return n; }
int strcmp(char *a, char *b) {
int i; i = 0;
while (a[i] && a[i] == b[i]) i++;
return a[i] - b[i];
}
void memcpy(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) {
int i; for (i = 0; i < count; i++) dst[i] = value;
}
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) {
int quotient; int digit;
quotient = number / 10;
digit = -(number - quotient * 10);
if (quotient) decimal_negative(quotient);
bob_putc('0' + digit);
}
void print_dec(int number) {
if (number < 0) bob_putc('-');
else number = -number;
decimal_negative(number);
}
void print_hex(int number) {
int nibble; int bit; int digit;
print("0x");
for (nibble = 0; nibble < 4; nibble++) {
digit = 0;
for (bit = 0; bit < 4; bit++) {
if (number & bit_masks[nibble * 4 + bit]) digit = digit + bit_weights[bit];
}
if (digit < 10) bob_putc('0' + digit);
else bob_putc('A' + digit - 10);
}
}
/* Consume the complete line, even when the destination fills. -2 means EOF. */
int read_line(char *buffer, int capacity) {
int length; int character; int truncated;
if (capacity < 1) return -1;
length = 0; truncated = 0;
while (1) {
character = bob_getc();
if (character == -1 || character == '\n') break;
if (character == '\b' || character == 127) { if (length) length--; }
else if (character != '\r') {
if (length < capacity - 1) buffer[length++] = character;
else truncated = 1;
}
}
buffer[length] = 0;
if (truncated) return -1;
if (character == -1 && length == 0) return -2;
return length;
}
int *alloc(int words) {
int *address;
if (words < 1 || words > HEAP_WORDS - heap_used) return 0;
address = (int *)(HEAP_BASE + heap_used);
heap_used = heap_used + words;
memset(address, 0, words);
return address;
}
+23
View File
@@ -0,0 +1,23 @@
#ifndef BOB_RUNTIME_H
#define BOB_RUNTIME_H
#include "bob.h"
#define HEAP_BASE 0xc000
#define HEAP_WORDS 8192
#define PROGRAM_BASE 0x9000
#define PROGRAM_WORDS 12288
#define FILE_COUNT 8
#define FILE_WORDS 512
#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);
void print(char *text);
void println(char *text);
void print_dec(int number);
void print_hex(int number);
int read_line(char *buffer, int capacity);
int *alloc(int words);
int bob_address(int function);
int bob_call(int entry);
#endif
+299
View File
@@ -0,0 +1,299 @@
char command_line[128];
char edit_line[128];
char edit_buffer[512];
char edit_undo[512];
int editor_length;
int editor_undo_length;
int editor_has_undo;
char *arguments;
int program_length;
char *next_arg(void) {
char *start;
while (*arguments == ' ') arguments++;
start = arguments;
while (*arguments && *arguments != ' ') arguments++;
if (*arguments) { *arguments = 0; arguments++; }
return start;
}
char *remaining_args(void) { while (*arguments == ' ') arguments++; return arguments; }
int number_ok;
int parse_number(char *text) {
int negative; int base; int digit; int number; int digits; int limit;
number_ok = 0; negative = 0; base = 10; number = 0; digits = 0;
if (*text == '-') { negative = 1; text++; }
if (text[0] == '0' && (text[1] == 'x' || text[1] == 'X')) { base = 16; text = text + 2; }
while (*text) {
digit = *text;
if (digit >= '0' && digit <= '9') digit = 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) return 0;
if (base == 16) {
if (digits == 4) return 0;
number = number * 16 + digit;
} else {
limit = 7; if (negative) limit = 8;
if (number < -3276 || (number == -3276 && digit > limit)) return 0;
number = number * 10 - digit;
}
digits++; text++;
}
if (!digits) return 0;
number_ok = 1;
if (base == 16) { if (negative) return -number; return number; }
if (negative) return number;
return -number;
}
int editor_line(int line) {
int i; int current;
if (line < 1) return -1;
current = 1; i = 0;
while (i < editor_length && current < line) {
if (edit_buffer[i] == '\n') current++;
i++;
}
if (current == line) return i;
return -1;
}
int editor_end(int position) {
while (position < editor_length && edit_buffer[position] != '\n') position++;
if (position < editor_length) position++;
return position;
}
void editor_show(void) {
int i; int line;
i = 0; line = 1;
while (i < editor_length) {
print_dec(line); print(": ");
while (i < editor_length && edit_buffer[i] != '\n') bob_putc(edit_buffer[i++]);
if (i < editor_length) i++;
bob_putc('\n'); line++;
}
if (!editor_length) println("(empty)");
}
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;
}
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; }
memcpy(edit_undo, edit_buffer, editor_length + 1);
editor_undo_length = editor_length; editor_has_undo = 1;
if (delta > 0) {
for (i = editor_length; i >= end; i--) edit_buffer[i + delta] = edit_buffer[i];
} else {
for (i = end; i <= editor_length; i++) edit_buffer[i + delta] = edit_buffer[i];
}
memcpy(edit_buffer + start, text, added - newline);
if (newline) edit_buffer[start + added - 1] = '\n';
editor_length = editor_length + delta;
return 1;
}
int editor_save(char *name) {
if (file_write(name, edit_buffer, editor_length, 0) < 0) { println("Cannot save file."); return 0; }
println("Saved."); return 1;
}
void editor_append_line(char *text) {
char joined[129]; int length;
length = strlen(text);
if (editor_length && edit_buffer[editor_length - 1] != '\n') {
joined[0] = '\n'; memcpy(joined + 1, text, length + 1);
editor_replace(editor_length, editor_length, joined, 1);
} else editor_replace(editor_length, editor_length, text, 1);
}
void edit_file(char *name) {
int n; int slot; int line; int start; int end; int i; int temporary; char *command; char *text;
if (!*name || strlen(name) >= NAME_WORDS) { println("Invalid file name."); return; }
slot = file_find(name);
if (slot >= 0 && file_kinds[slot]) { println("Cannot edit a binary program."); return; }
editor_length = 0; editor_has_undo = 0;
if (slot >= 0) {
editor_length = file_lengths[slot];
memcpy(edit_buffer, file_content(slot), editor_length);
}
edit_buffer[editor_length] = 0;
println("Editor: text appends; :p lists; :i N TEXT inserts; :r N TEXT replaces.");
println(":d N deletes; :u undo/redo; :w saves; :q quits; :q! discards; . saves/quits.");
println(":p N shows one line. :q protects unsaved edits; :wq also saves/quits.");
editor_show();
while (1) {
print("edit> ");
n = read_line(edit_line, 128);
if (n == -2) { println("Edit cancelled at EOF."); return; }
if (n < 0) { println("Line too long; change rejected."); continue; }
if (strcmp(edit_line, ".") == 0 || strcmp(edit_line, ":wq") == 0) {
if (editor_save(name)) return;
} else if (strcmp(edit_line, ":q!") == 0) { println("Discarded unsaved changes."); return; }
else if (strcmp(edit_line, ":q") == 0) {
if (editor_changed(name)) println("Unsaved changes. Use :wq to save or :q! to discard.");
else return;
}
else if (strcmp(edit_line, ":p") == 0) editor_show();
else if (strcmp(edit_line, ":w") == 0) editor_save(name);
else if (strcmp(edit_line, ":u") == 0) {
if (!editor_has_undo) println("Nothing to undo.");
else {
end = editor_length; if (editor_undo_length > end) end = editor_undo_length;
for (i = 0; i <= end; i++) {
temporary = edit_buffer[i]; edit_buffer[i] = edit_undo[i]; edit_undo[i] = temporary;
}
temporary = editor_length; editor_length = editor_undo_length; editor_undo_length = temporary;
println("Undo/redo applied. Use :p to inspect.");
}
} else if (edit_line[0] == ':') {
arguments = edit_line; command = next_arg();
if (strcmp(command, ":p") == 0) {
line = parse_number(next_arg()); start = editor_line(line);
if (!number_ok || start < 0 || start == editor_length || *next_arg()) {
println("Usage: :p LINE (existing line number)"); continue;
}
print_dec(line); print(": "); end = editor_end(start);
for (i = start; i < end; i++) bob_putc(edit_buffer[i]);
if (end && edit_buffer[end - 1] != '\n') bob_putc('\n');
continue;
}
if (strcmp(command, ":a") == 0) { editor_append_line(remaining_args()); continue; }
if (strcmp(command, ":i") && strcmp(command, ":r") && strcmp(command, ":d")) {
println("Unknown editor command."); continue;
}
line = parse_number(next_arg()); text = remaining_args();
start = editor_line(line);
if (!number_ok || start < 0 || (start == editor_length && strcmp(command, ":i"))) {
println("Invalid line number."); continue;
}
end = start;
if (strcmp(command, ":i")) end = editor_end(start);
if (strcmp(command, ":d") == 0) editor_replace(start, end, "", 0);
else editor_replace(start, end, text, 1);
} else {
editor_append_line(edit_line);
}
}
}
void load_words(char *name) {
int slot; int count; int value; int words[511]; char *token;
count = 0;
while (1) {
token = next_arg(); if (!*token) break;
value = parse_number(token);
if (!number_ok || count == 511) { println("Invalid machine words."); return; }
words[count++] = value;
}
if (!count) { println("Usage: load name 0xWORD ... (finish with RET 0xE000)"); return; }
slot = file_write(name, words, count, 1);
if (slot < 0) println("Cannot create program file.");
else println("Loaded.");
}
void run_file(char *name) {
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; }
program = (int *)PROGRAM_BASE;
memset(program, 0, PROGRAM_WORDS);
memcpy(program, file_content(slot), file_lengths[slot]);
program_length = file_lengths[slot];
status = bob_run(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'); }
}
void memory_status(void) {
print("Heap "); print_hex(HEAP_BASE); print(".."); print_hex(0xdfff);
print("; free "); print_dec(HEAP_WORDS - heap_used); println(" words");
print("Programs "); print_hex(PROGRAM_BASE); print(".."); print_hex(0xbfff); println("");
println("Files: 8 slots, 511 words each; stack above 0xE000.");
}
void command_help(char *name) {
if (strcmp(name, "edit") == 0) println("edit NAME: open text; ordinary lines append. :p or :p N views; :i N TEXT inserts; :r N TEXT replaces; :d N deletes; :u undo/redo; :w saves; :q quits safely; :q! discards; . saves/quits.");
else if (strcmp(name, "cc") == 0 || strcmp(name, "go") == 0)
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.");
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)
println("ls / dir / list: show names, lengths and text/program kinds. Files are in RAM and lost on exit.");
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.");
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.");
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.");
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. RAM files and allocations are lost; read important files 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) {
char *command; char *name; char *text; int value; int address; int *pointer;
arguments = line; command = next_arg();
if (!*command) return;
if (strcmp(command, "help") == 0) {
name = next_arg();
if (*name) { command_help(name); return; }
println("help | echo TEXT | clear | mem | halt");
println("peek ADDRESS | poke ADDRESS VALUE | alloc WORDS");
println("list / ls / dir | read NAME | write NAME TEXT | edit NAME");
println("copy OLD NEW | rename OLD NEW | delete NAME (permanent in RAM)");
println("load NAME 0xWORD ... | run NAME | cc SOURCE [OUTPUT] | go SOURCE [OUTPUT]");
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.");
} else if (strcmp(command, "echo") == 0) println(remaining_args());
else if (strcmp(command, "clear") == 0) print("\033[2J\033[H");
else if (strcmp(command, "mem") == 0) memory_status();
else if (strcmp(command, "halt") == 0) bob_halt();
else if (strcmp(command, "list") == 0 || strcmp(command, "ls") == 0 || strcmp(command, "dir") == 0) file_list();
else if (strcmp(command, "copy") == 0 || strcmp(command, "rename") == 0 || strcmp(command, "delete") == 0) {
name = next_arg(); text = next_arg();
if (*next_arg() || (strcmp(command, "delete") == 0 && *text)) {
println("Usage: copy OLD NEW | rename OLD NEW | delete NAME"); return;
}
file_manage(command, name, text);
} else if (strcmp(command, "read") == 0) {
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 if (strcmp(command, "write") == 0) {
name = next_arg(); text = remaining_args();
if (file_write(name, text, strlen(text), 0) < 0) println("Cannot write file.");
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, "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);
} else if (strcmp(command, "alloc") == 0) {
value = parse_number(next_arg());
if (!number_ok) { println("Invalid allocation size."); return; }
pointer = alloc(value);
if (!pointer) println("Allocation failed.");
else { print_hex((int)pointer); bob_putc('\n'); }
} else if (strcmp(command, "peek") == 0 || strcmp(command, "poke") == 0) {
address = parse_number(next_arg());
if (!number_ok) { println("Invalid address."); return; }
pointer = (int *)address;
if (strcmp(command, "poke") == 0) {
value = parse_number(next_arg());
if (!number_ok) { println("Invalid value."); return; }
if (address >= 0 || address < -16384 || address >= -8192) {
println("poke is limited to 0xC000..0xDFFF."); return;
}
*pointer = value;
}
print_hex(address); print(": "); print_hex(*pointer); print(" ("); print_dec(*pointer); println(")");
} else println("Unknown command. Type help.");
}
+181 -34
View File
@@ -110,6 +110,34 @@
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <setjmp.h>
#ifdef _WIN32
#include <windows.h>
#endif
/* Kernel disk exposed to the guest boot ROM through trap 4. */
static uint16_t bootDisk[0x10000];
static uint16_t bootWords;
static bool bootMode;
static bool programMode;
static bool programDone;
static jmp_buf programFault;
static void machineFault(void) {
if (programMode) longjmp(programFault, 1);
exit(1);
}
static unsigned readWord(FILE *file) {
int lo = fgetc(file), hi = fgetc(file);
if (lo == EOF || hi == EOF) {
fprintf(stderr, "Truncated bob16 kernel image\n");
exit(1);
}
return (unsigned)lo | ((unsigned)hi << 8);
}
static void bootImage(const char *path);
typedef uint16_t ureg_t;
typedef int16_t reg_t;
@@ -164,6 +192,35 @@ struct ram_t {
reg_t mdr;
} ram;
void cpuCycle(void);
static int runProgram(uint16_t entry) {
if (programMode || entry < 0x9000 || entry >= 0xbe00) return -1;
struct cpu_t saved = cpu;
ureg_t savedMar = ram.mar;
reg_t savedMdr = ram.mdr;
volatile int status = -2;
programMode = true;
programDone = false;
if (setjmp(programFault) == 0) {
cpu.pc = entry;
cpu.regFile[6] = (int16_t)0xc000;
cpu.regFile[5] = 0;
cpu.regFile[7] = 0x80;
unsigned cycles = 0;
while (!programDone && cpu.pc != 0x80 && cycles < 5000000) {
cpuCycle();
++cycles;
}
status = cycles == 5000000 ? -3 : cpu.regFile[0];
}
programMode = false;
cpu = saved;
ram.mar = savedMar;
ram.mdr = savedMdr;
return status;
}
int sext(int16_t val, uint16_t length) {
int n = 16 - length;
return (int16_t)((val << n)) >> n;
@@ -210,8 +267,8 @@ void execute() {
switch ((cpu.ir >> 7) & 0x3) {
case 0:
if (cpu.ir & 0b1) {
printf("bad instruction: %X\n at memory address %X\n", cpu.ir, ram.memory[cpu.pc - 1]);
exit(-1);
printf("bad instruction: %X\n at memory address %X\n", cpu.ir, (uint16_t)(cpu.pc - 1));
machineFault();
}
cpu.alu.accumulator = cpu.regFile[(cpu.ir >> 4) & 0x7] + cpu.regFile[(cpu.ir >> 1) & 0x7];
@@ -221,8 +278,8 @@ void execute() {
break;
case 2:
if (cpu.ir & 0xF) {
printf("bad instruction: %X\n at memory address %X\n", cpu.ir, ram.memory[cpu.pc - 1]);
exit(-1);
printf("bad instruction: %X\n at memory address %X\n", cpu.ir, (uint16_t)(cpu.pc - 1));
machineFault();
}
cpu.alu.accumulator = cpu.regFile[(cpu.ir >> 9) & 0x7] + cpu.regFile[(cpu.ir >> 4) & 0x7];
@@ -237,8 +294,8 @@ void execute() {
switch ((cpu.ir >> 7) & 0x3) {
case 0:
if (cpu.ir & 0x1) {
printf("bad instruction: %X\n at memory address %X\n", cpu.ir, ram.memory[cpu.pc - 1]);
exit(-1);
printf("bad instruction: %X\n at memory address %X\n", cpu.ir, (uint16_t)(cpu.pc - 1));
machineFault();
}
cpu.alu.accumulator = cpu.regFile[(cpu.ir >> 4) & 0x7] & cpu.regFile[(cpu.ir >> 1) & 0x7];
@@ -247,9 +304,9 @@ void execute() {
cpu.alu.accumulator = cpu.regFile[(cpu.ir >> 4) & 0x7] & sext(cpu.ir & 0xF, 4);
break;
case 2:
if (cpu.ir & 0x1F) {
printf("bad instruction: %X\n at memory address %X\n", cpu.ir, ram.memory[cpu.pc - 1]);
exit(-1);
if (cpu.ir & 0xF) {
printf("bad instruction: %X\n at memory address %X\n", cpu.ir, (uint16_t)(cpu.pc - 1));
machineFault();
}
cpu.alu.accumulator = cpu.regFile[(cpu.ir >> 9) & 0x7] & cpu.regFile[(cpu.ir >> 4) & 0x7];
@@ -262,8 +319,8 @@ void execute() {
break;
case NOT:
if (cpu.ir & 0x1F) {
printf("bad instruction: %X\n at memory address %X\n", cpu.ir, ram.memory[cpu.pc - 1]);
exit(-1);
printf("bad instruction: %X\n at memory address %X\n", cpu.ir, (uint16_t)(cpu.pc - 1));
machineFault();
}
if (cpu.ir & 0x100) {
@@ -297,21 +354,24 @@ void execute() {
break;
case JMP:
if (cpu.ir & 0x1FF) {
printf("bad instruction: %X\n at memory address %X\n", cpu.ir, ram.memory[cpu.pc - 1]);
exit(-1);
printf("bad instruction: %X\n at memory address %X\n", cpu.ir, (uint16_t)(cpu.pc - 1));
machineFault();
}
cpu.pc = cpu.regFile[(cpu.ir >> 9) & 0x7];
break;
case JSR:
{
ureg_t target = (ureg_t)cpu.regFile[(cpu.ir >> 8) & 0x7];
cpu.regFile[7] = cpu.pc;
if (!(cpu.ir & 0x800)) {
if (cpu.ir & 0x800) {
cpu.pc += sext(cpu.ir & 0x7FF, 11);
} else {
cpu.pc = cpu.regFile[(cpu.ir >> 8) & 0x7];
cpu.pc = target;
}
break;
}
case LEA:
break;
case RET:
@@ -319,22 +379,27 @@ void execute() {
break;
case TRAP:
if (cpu.ir & 0xFF) {
printf("bad instruction: %X\n at memory address %X\n", cpu.ir, ram.memory[cpu.pc - 1]);
exit(-1);
printf("bad instruction: %X\n at memory address %X\n", cpu.ir, (uint16_t)(cpu.pc - 1));
machineFault();
}
switch ((cpu.ir >> 8) & 0xF) {
case HALT:
if (programMode) { programDone = true; break; }
exit(0);
break;
case PUTC:
putchar(cpu.regFile[0] & 0xFF);
break;
case PUTS:
{
unsigned remaining = 0x10000;
cpu.regFile[7] = cpu.pc;
cpu.pc = cpu.regFile[0];
while (cpu.ir != 0) {
if (!remaining--) machineFault();
cpu.ir = ram.memory[cpu.pc];
if (cpu.ir == 0) break;
cpu.regFile[0] = cpu.ir;
putchar(cpu.regFile[0] & 0xFF);
cpu.pc++;
@@ -344,17 +409,49 @@ void execute() {
cpu.pc = cpu.regFile[7];
break;
}
case GETS:
int n = cpu.regFile[1];
{
int n = (uint16_t)cpu.regFile[1];
cpu.regFile[7] = cpu.pc;
char buf[n];
fgets(buf, n, stdin);
for (int i = 0; i < strlen(buf); i++) {
ram.memory[cpu.regFile[0] + i] = buf[i] & 0xFF;
unsigned address = (uint16_t)cpu.regFile[0];
if (n < 2 || address + (unsigned)n > 0x10000 ||
(programMode && (address < 0x9000 || address + (unsigned)n > 0xe000))) {
fprintf(stderr, "Invalid input buffer\n"); machineFault();
}
char *buf = calloc((size_t)n, 1);
if (!buf) machineFault();
if (!fgets(buf, n, stdin)) buf[0] = '\0';
for (size_t i = 0; i <= strlen(buf); i++) {
ram.memory[address + i] = buf[i] & 0xFF;
}
free(buf);
cpu.pc = cpu.regFile[7];
break;
}
case 4: /* disk_read(dst=r0, word_offset=r1, count=r2) */
{
unsigned dst = (uint16_t)cpu.regFile[0];
unsigned offset = (uint16_t)cpu.regFile[1];
unsigned count = (uint16_t)cpu.regFile[2];
if (programMode || !bootMode || offset + count > bootWords ||
dst < 0x100 || dst + count > 0xf000) {
fprintf(stderr, "Invalid boot disk read\n"); machineFault();
}
for (unsigned i = 0; i < count; ++i)
ram.memory[dst + i] = (int16_t)bootDisk[offset + i];
cpu.regFile[0] = (int16_t)count;
break;
}
case 5:
cpu.regFile[0] = (int16_t)getchar();
break;
case 6:
cpu.regFile[0] = (int16_t)runProgram((uint16_t)cpu.regFile[0]);
break;
default:
machineFault();
}
break;
@@ -368,6 +465,7 @@ void storeResult() {
cpu.regFile[dest] = ram.mdr;
updateCC(cpu.regFile[dest]);
} else if (opcode == ST || opcode == STI || opcode == STR) {
if (programMode && (ram.mar < 0x9000 || ram.mar >= 0xe000)) machineFault();
ram.memory[ram.mar] = cpu.regFile[dest];
} else if (opcode == ADD || opcode == AND || opcode == NOT) {
cpu.regFile[dest] = cpu.alu.accumulator;
@@ -392,7 +490,7 @@ int parseReg(const char* s) {
return -1;
}
if (strlen(s) != 2 || s[0] != 'R' && s[0] != 'r') {
if (strlen(s) != 2 || (s[0] != 'R' && s[0] != 'r')) {
//incorrect format
return -2;
}
@@ -413,7 +511,7 @@ int assemble() {
setbuf(stdout, NULL);
printf("Enter source assembly file name: \n");
fgets(fileName, 256, stdin);
if (!fgets(fileName, 256, stdin)) return -8;
fileName[strcspn(fileName, "\n")] = '\0';
file = fopen(fileName, "r");
if (!file) {
@@ -470,7 +568,7 @@ int assemble() {
return -4;
}
for (int i = 0; i < strlen(tokens[1]); i++) {
for (size_t i = 0; i < strlen(tokens[1]); i++) {
ram.memory[instructionCount] = tokens[1][i] & 0x00FF;
instructionCount++;
}
@@ -489,14 +587,14 @@ int assemble() {
int dst = parseReg(tokens[1]);
int src0 = parseReg(tokens[2]);
int src1 = parseReg(tokens[3]);
if (dst < 0 || src1 < 0) {
if (dst < 0 || src0 < 0) {
printf("Wrong tokens on line %d!\n", lineCount);
return -3;
}
instruction += (dst << 9);
instruction += (src0 << 4);
if (src0 < 0) { //imm
if (src1 < 0) { //imm
instruction += (1 << 7);
int imm = atoi(tokens[3]);
if (imm > 7) {
@@ -522,7 +620,7 @@ int assemble() {
instruction += (dst << 9);
if (src < 0) { //imm
instruction += (4 << 7);
instruction += (3 << 7);
int imm = atoi(tokens[2]);
if (imm > 63) {
imm = 63;
@@ -534,7 +632,7 @@ int assemble() {
instruction += imm & 0x7F;
} else { //normal
instruction += (3 << 7);
instruction += (2 << 7);
instruction += (src << 4);
}
@@ -581,9 +679,9 @@ int assemble() {
return -3;
}
instruction += (r0 << 7);
instruction += (r0 << 9);
if (r1 < 0) { //imm
instruction += (4 << 10);
instruction += (3 << 7);
int imm = atoi(tokens[2]);
if (imm > 63) {
imm = 63;
@@ -595,7 +693,7 @@ int assemble() {
instruction += imm & 0x7F;
} else { //normal
instruction += (3 << 7);
instruction += (2 << 7);
instruction += (r1 << 4);
}
@@ -790,7 +888,7 @@ int assemble() {
}
int conditionCodes = 0;
for (int i = 0; i < l; i++) {
for (size_t i = 0; i < l; i++) {
if (tokens[1][i] == 'n') {
conditionCodes |= 0b100;
} else if (tokens[1][i] == 'z') {
@@ -857,7 +955,7 @@ int assemble() {
return -4;
}
int r0 = parseReg(tokens[2]);
int r0 = parseReg(tokens[1]);
if (r0 < 0) {
printf("Wrong tokens on line %d!\n", lineCount);
return -3;
@@ -931,16 +1029,65 @@ int assemble() {
}
printf("Starting execution!\n");
fclose(file);
return 0;
}
static void bootImage(const char *path) {
FILE *file = fopen(path, "rb");
if (!file) { perror(path); exit(1); }
char magic[4];
if (fread(magic, 1, 4, file) != 4 || memcmp(magic, "B16K", 4)) {
fprintf(stderr, "Not a bob16 kernel image\n"); exit(1);
}
unsigned version = readWord(file), origin = readWord(file);
unsigned entry = readWord(file), words = readWord(file), checksum = readWord(file);
if (version != 1 || !words || origin < 0x100 || origin + words > 0x9000 ||
entry < origin || entry >= origin + words) {
fprintf(stderr, "Invalid bob16 kernel header\n"); exit(1);
}
unsigned sum = 0;
for (unsigned i = 0; i < words; ++i) { bootDisk[i] = readWord(file); sum += bootDisk[i]; }
if ((sum & 0xffff) != checksum || fgetc(file) != EOF) {
fprintf(stderr, "Invalid kernel checksum or length\n"); exit(1);
}
fclose(file);
bootWords = (uint16_t)words;
bootMode = true;
memset(&cpu, 0, sizeof(cpu));
memset(&ram, 0, sizeof(ram));
/* Real guest instructions: load disk parameters, read kernel, jump to entry. */
uint16_t rom[] = {0x4007, 0x4207, 0x4407, 0xf400, 0x4606, 0xb600,
0xf000, 0, (uint16_t)origin, 0, (uint16_t)words, (uint16_t)entry};
for (unsigned i = 0; i < sizeof(rom) / sizeof(rom[0]); ++i) ram.memory[i] = (int16_t)rom[i];
updateCC(0);
}
int main(int argc, char** argv) {
#ifdef _WIN32
HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
DWORD mode;
if (GetConsoleMode(console, &mode)) SetConsoleMode(console, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
#endif
unsigned long maxCycles = 0;
if (argc == 2 && strcmp(argv[1], "--os") == 0) {
bootImage("build/kernel.b16");
} else if (argc >= 3 && strcmp(argv[1], "--boot") == 0) {
if (argc == 5 && strcmp(argv[3], "--max-cycles") == 0) maxCycles = strtoul(argv[4], NULL, 10);
else if (argc != 3) { fprintf(stderr, "Usage: %s --boot kernel.b16 [--max-cycles N]\n", argv[0]); return 1; }
bootImage(argv[2]);
} else {
if (argc != 1) { fprintf(stderr, "Usage: %s [--os | --boot kernel.b16 [--max-cycles N]]\n", argv[0]); return 1; }
int assembleReturn = -1;
while (assembleReturn < 0) {
assembleReturn = assemble();
if (assembleReturn == -8) return 1;
}
}
unsigned long cycles = 0;
while (true) {
if (maxCycles && cycles++ >= maxCycles) { fprintf(stderr, "CPU cycle limit reached\n"); return 2; }
cpuCycle();
}
+35
View File
@@ -0,0 +1,35 @@
# OS completion checks
The C test runner is `tests/test_os.c`. Compile it with GCC and run it from the
repository root, or use `build.exe --test` with the emulator closed. Its current
suite prints `bob!` and its assertion count when all pass. Guest output is
captured for assertions; no guest examples print hello world.
| Requested feature | Implementation | Runtime evidence |
| --- | --- | --- |
| Console print/println, decimal/hex, bounded input | `kernel/runtime.c` | `console_and_commands`, `input_bounds`, exact -32768/32767/zero/0xFFFF checks in `host_compiler_and_runtime` |
| strlen/strcmp/memcpy/memset | `kernel/runtime.c` | Empty/equal/differing strings, filled/copied arrays, mutation and pointer access in `host_compiler_and_runtime` |
| Repeating bob> command loop | `kernel/kernel.c` | Multiple commands and prompts across all shell cases; EOF exits cleanly |
| help/echo/clear/mem/peek/poke/halt | `kernel/shell.c` | `console_and_commands` checks help, echo, ANSI clear, memory totals, reads/writes, protected addresses and successful halt |
| Reserved heap and allocation | `kernel/runtime.c` | `allocator_and_files` checks zeroing previously nonzero RAM, consecutive addresses, free counts, invalid sizes and complete exhaustion |
| RAM files with list/read/write | `kernel/files.c` | `allocator_and_files` checks create/replace/read/list, table exhaustion, name limits, exact 511-character capacity and cancelled overlong edits |
| Program load/run/return | `kernel/shell.c`, trap 6 in `main.c` | `program_loading_and_recovery` checks raw native words, return value, halt returning to shell, illegal instructions, protected writes, rejected input/disk services, and infinite-loop timeout |
| C code running inside emulator | `kernel/compiler.c` | `resident_compiler` invokes shell cc then run, verifies bob!, variables, arithmetic, while, if/else, comments, malformed input, depth bounds, preservation of an existing output and numeric APIs |
| Rebuilt emulator and required features | `main.c`, `bob.exe` | The supplied executable passes the suite; traps 5/6 supply EOF input and supervised execution |
| Only C/BASM tooling | `tools/build.c`, `tools/bobcc.c`, `tools/arithmetic.c`, `tests/test_os.c` | GCC builds tools and emulator; C compiler emits both BASM and binary images; Python sources/dependencies removed |
| Markdown documentation | `C_OS.md`, `kernel/API.md` | Run/build instructions, command reference, resident C examples, supported language limits, memory map, filesystem/allocator lifetime and execution statuses |
| Expanded resident C syntax | `kernel/compiler.c` | `compiler_extensions` checks for, break/continue, increments, compound assignment, bitwise/shift operations, short-circuit side effects and precedence |
| Editing existing files | `kernel/shell.c` | `editor_and_aliases` checks opening existing content, insert/replace/delete, numbered display, undo, save/discard, invalid lines and refusal to edit binary programs |
| ls/dir aliases | `kernel/shell.c` | `editor_and_aliases` lists existing RAM files through both aliases |
| File copy/rename/delete | `kernel/files.c` | `file_management` checks text and native programs, destination collision protection, full storage, slot reuse, names and malformed arguments |
| Compile and run workflow | `kernel/compiler.c`, `kernel/shell.c` | `compile_workflow` checks default/explicit outputs, source preservation, line diagnostics and no stale execution on errors |
| Startup/help/editor usability | `main.c`, `kernel/kernel.c`, `kernel/shell.c` | `usability` boots via --os, runs bob.c, exercises per-command help, unsaved quit protection, explicit discard, line navigation and undo/redo |
`basm_route` additionally starts the supplied emulator at its ordinary filename
prompt, passes `kernel.basm`, compiles/runs bob.c and checks return to the shell.
It also checks the original `demo.basm`. `image_validation` corrupts/truncates
binary images and verifies rejection before boot.
These checks establish this starter's functionality, not conformance to all of C
or isolation between processes. The resident compiler is a documented subset;
RAM storage is volatile, allocation has no free, and multitasking is absent.
+224
View File
@@ -0,0 +1,224 @@
/* End-to-end tests implemented in C. Success prints bob!, never hello world. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#ifdef _WIN32
#ifdef BOB_VERIFY
#define BOB "build\\bob-next.exe"
#else
#define BOB "bob.exe"
#endif
#define COMPILER "build\\bobcc.exe"
#else
#define BOB "./bob"
#define COMPILER "./build/bobcc"
#endif
static int checks;
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) {
FILE *f=fopen(path,"wb");if(!f)fail("cannot create fixture");fputs(text,f);fclose(f);
}
static char *read_text(const char *path) {
FILE *f=fopen(path,"rb");if(!f)fail("cannot read result");fseek(f,0,SEEK_END);long size=ftell(f);rewind(f);
if(size<0||size>2000000)fail("invalid result size");
char *text=calloc((size_t)size+1,1);if(!text)fail("out of memory");
size_t n=fread(text,1,(size_t)size,f);fclose(f);
/* Normalize console CRLF so assertions work on Windows and Linux. */
size_t out=0;for(size_t i=0;i<n;i++)if(text[i]!='\r')text[out++]=text[i];text[out]=0;return text;
}
static char *shell(const char *commands) {
write_text("build/check.in",commands);
int status=system(BOB " --boot build/kernel.b16 --max-cycles 50000000 < build/check.in > build/check.out 2> build/check.err");
check(status==0,"shell must halt cleanly");return read_text("build/check.out");
}
static void contains(const char *output,const char *expected) { check(strstr(output,expected)!=NULL,expected); }
static void not_contains(const char *output,const char *unexpected) { check(strstr(output,unexpected)==NULL,unexpected); }
static void guest(const char *source) {
write_text("build/check.c",source);
check(system("gcc -E -P -nostdinc -undef -DBOBC_LEGACY=0 -I kernel build/check.c -o build/check.i > build/compiler.log 2>&1")==0,"guest preprocessing");
check(system(COMPILER " build/check.i build/check.basm build/check.b16 > build/compiler.log 2>&1")==0,"guest compilation");
write_text("build/check.in","");
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 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");
contains(output,"\033[2J\033[H");contains(output,"free 8192 words");contains(output,"bob> 0xC000\n");
contains(output,"0xC000: 0x8000 (-32768)");contains(output,"poke is limited to 0xC000..0xDFFF.");free(output);
}
static void input_bounds(void) {
char commands[400];memset(commands,'x',200);strcpy(commands+200,"\necho bob!\nhalt\n");
char *output=shell(commands);contains(output,"Command too long.");contains(output,"bob> bob!\n");
not_contains(output,"Unknown command");free(output);
output=shell("");check(!strcmp(output,"bob!\nbob16 OS: help COMMAND for usage; go bob.c runs the example.\nFiles are in RAM; halt exits. Type help to get started.\nbob> \n"),"EOF exits shell");free(output);
output=shell("echo bxo\b\bbob!\nhalt\n");contains(output,"bob> bbob!\n");free(output);
}
static void allocator_and_files(void) {
char *output=shell("alloc 0\nalloc -1\nalloc 8192\nalloc 1\nmem\nwrite note bob!\nread note\nwrite note bob!\nlist\nwrite a bob!\nwrite b bob!\nwrite c bob!\nwrite d bob!\nwrite e bob!\nwrite f bob!\nwrite g bob!\nread missing\nhalt\n");
contains(output,"Allocation failed.");contains(output,"free 0 words");contains(output,"note 4 chars (text)");
contains(output,"bob> bob!\n");contains(output,"Cannot write file.");contains(output,"File not found.");free(output);
output=shell("edit note\nbob!\n.\nread note\nlist\nhalt\n");
contains(output,"Saved.");contains(output,"bob!\n\n");contains(output,"note 5 chars (text)");free(output);
output=shell("poke 0xc000 33\nalloc 4\npeek 0xc000\nalloc 4\nmem\nhalt\n");
contains(output,"0xC000: 0x0000 (0)");contains(output,"bob> 0xC004\n");contains(output,"free 8184 words");free(output);
output=shell("write abcdefghijklmnopqrstuvwx bob!\nalloc 32768\npoke 0xdfff 0xffff\npeek 0xdfff\nhalt\n");
contains(output,"Cannot write file.");contains(output,"Invalid allocation size.");contains(output,"0xDFFF: 0xFFFF (-1)");free(output);
char large[800];strcpy(large,"write note bob!\nedit note\n");
size_t n=strlen(large);
for(int i=0;i<5;i++){memset(large+n,'b',120);n+=120;large[n++]='\n';}
strcpy(large+n,".\nread note\nhalt\n");
output=shell(large);contains(output,"File too large; change rejected.");free(output);
strcpy(large,"edit full\n");n=strlen(large);
for(int i=0;i<4;i++){memset(large+n,'b',126);n+=126;large[n++]='\n';}
strcpy(large+n,"bb\n.\nlist\nhalt\n");
output=shell(large);contains(output,"full 511 chars (text)");free(output);
}
static void resident_compiler(void) {
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("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. */
output=shell("write num.c int main(void) { print(\"bob!\"); print_dec(-32767); print_hex(0xffff); return 0; }\ncc num.c num\nrun num\nhalt\n");
contains(output,"bob> bob!-327670xFFFFExit 0");free(output);
output=shell("cc bob.c bob\nwrite bad.c int main(void) { @ }\ncc bad.c bob\nrun bob\nhalt\n");
contains(output,"C compile error near character");contains(output,"bob> bob!\nExit 0");free(output);
output=shell("write bad.c int main(void) println(\"bob!\");\ncc bad.c bad\nwrite ok.c int main() { /* bob! */ println(\"bob!\"); return -1; }\ncc ok.c ok\nrun ok\nhalt\n");
contains(output,"C compile error near character");contains(output,"bob> bob!\nExit -1");free(output);
char nested[500];strcpy(nested,"write deep.c int main(void) { return ");
size_t n=strlen(nested);for(int i=0;i<35;i++)nested[n++]='(';
nested[n++]='0';for(int i=0;i<35;i++)nested[n++]=')';
strcpy(nested+n,"; }\ncc deep.c deep\ncc bob.c bob\nrun bob\nhalt\n");
output=shell(nested);contains(output,"C compile error near character");contains(output,"bob> bob!\nExit 0");free(output);
}
static void compiler_extensions(void) {
char *output=shell("edit loop.c\nint main(void) { int s=0; for(int i=0; i<4; i++) {\nif(i==1) continue; if(i==3) break; s+=i; }\nif(s==2 && (3<<2)==12) println(\"bob!\"); return 0; }\n.\ncc loop.c loop\nrun loop\nhalt\n");
not_contains(output,"compile error");contains(output,"bob> bob!\nExit 0");free(output);
output=shell("edit bits.c\nint main(void) { int a=5; a|=2; a^=1; a&=6;\nif(a==6 && (~0 & 1)==1 && (-8>>2)==-2) println(\"bob!\"); return 0; }\n.\ncc bits.c bits\nrun bits\nhalt\n");
not_contains(output,"compile error");contains(output,"bob> bob!\nExit 0");free(output);
output=shell("edit short.c\nint main(void) { int a=0; int b=1; if(0 && a++) return 1;\nif(1 || a++) { ++b; } if(a==0 && b==2) println(\"bob!\"); return 0; }\n.\ncc short.c short\nrun short\nhalt\n");
not_contains(output,"compile error");contains(output,"bob> bob!\nExit 0");free(output);
output=shell("edit cmp.c\nint main(void) { if(1==2<3) println(\"bob!\"); return 0; }\n.\ncc cmp.c cmp\nrun cmp\nhalt\n");
contains(output,"bob> bob!\nExit 0");free(output);
output=shell("write bad.c int main(void) { break; }\ncc bad.c bad\ncc bob.c bob\nrun bob\nhalt\n");
contains(output,"C compile error near character");contains(output,"bob> bob!\nExit 0");free(output);
}
static void editor_and_aliases(void) {
char *output=shell("write note bob!\nls\ndir\nedit note\n:r 1 bob!\n:i 1 bob!\n:d 2\n:p\n:wq\nread note\nlist\nhalt\n");
contains(output,"note 4 chars (text)");contains(output,"1: bob!");contains(output,"note 5 chars (text)");free(output);
output=shell("write note bob!\nedit note\n:a bob!\n:u\n:wq\nlist\nedit note\n:r 1 discard\n:q!\nread note\nhalt\n");
contains(output,"note 4 chars (text)");contains(output,"Discarded unsaved changes.");contains(output,"bob> bob!\n");free(output);
output=shell("edit note\n:i 1 bob!\n:r 20 bob!\n:d -1\n:u\n:p\n:q\ncc bob.c bob\nedit bob\nhalt\n");
contains(output,"Invalid line number.");contains(output,"(empty)");contains(output,"Cannot edit a binary program.");free(output);
}
static void program_loading_and_recovery(void) {
/* Native bob16: load each character, trap 1, then return through r7. */
char *output=shell("load raw 0x4001 0xae01 98 0xf100 0x4001 0xae01 111 0xf100 0x4001 0xae01 98 0xf100 0x4001 0xae01 33 0xf100 0x4001 0xae01 10 0xf100 0x4001 0xae01 0 0xe000\nrun raw\nhalt\n");
/* This intentionally exceeds a shell line: it must reject, not partly load. */
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");
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");
contains(output,"Program fault; shell restored.");contains(output,"bob> bob!\nExit 0");free(output);
output=shell("load stop 0xf000\nrun stop\necho bob!\nhalt\n");contains(output,"bob> bob!\n");free(output);
output=shell("load inputfault 0xf300\nrun inputfault\nload diskfault 0xf400\nrun diskfault\necho bob!\nhalt\n");
contains(output,"Program fault; shell restored.");contains(output,"bob> bob!\n");free(output);
}
static void host_compiler_and_runtime(void) {
guest("#include \"runtime.h\"\n#include \"runtime.c\"\n"
"int sum(int n) { if (n == 0) return 0; return n + sum(n - 1); }\n"
"int main(void) { int data[4]; int other[4]; int *p; int i; "
"memset(data, 7, 4); memcpy(other, data, 4); p = &other[0]; "
"if (*p != 7 || sum(3) != 6 || strlen(\"bob!\") != 4 || strcmp(\"bob!\",\"bob!\")) return 1; "
"if(strlen(\"\") != 0 || strcmp(\"bob\",\"bob!\") >= 0 || strcmp(\"bob!\",\"bob\") <= 0) return 1; "
"for(i=0;i<4;i++){ if(data[i] != 7 || other[i] != 7) return 1; } "
"for(i = 0; i < 4; i++) { other[i] += i; } if(other[3] != 10) return 1; println(\"bob!\"); return 0; }");
guest("#include \"bob.h\"\nint main(void) { int a; int b; a=-32768; b=32767; "
"if(!(a < b) || !(b > a) || a != a || !(a <= a) || !(b >= b)) return 1; "
"if(6*7 != 42 || -43/7 != -6 || -43%7 != -1) return 1; "
"if((5|2) != 7 || (5^3) != 6 || (3<<4) != 48 || (-8>>2) != -2) return 1; "
"bob_puts(\"bob!\"); return 0; }");
write_text("build/check.c","struct nope { int x; }; int main(void) { return 0; }");
check(system("gcc -E -P -nostdinc -undef -I kernel build/check.c -o build/check.i > build/compiler.log 2>&1")==0,"bad source preprocessing");
check(system(COMPILER " build/check.i build/check.basm build/check.b16 > build/compiler.log 2>&1")!=0,"unsupported source rejected");
/* Exact signed decimal/hex console output, including the minimum value. */
write_text("build/check.c","#include \"runtime.h\"\n#include \"runtime.c\"\nint main(void) { print(\"bob!\"); print_dec(-32768); print_dec(32767); print_dec(0); print_hex(0xffff); return 0; }");
check(system("gcc -E -P -nostdinc -undef -I kernel build/check.c -o build/check.i > build/compiler.log 2>&1")==0,"numeric preprocessing");
check(system(COMPILER " build/check.i build/check.basm build/check.b16 > build/compiler.log 2>&1")==0,"numeric compilation");
check(system(BOB " --boot build/check.b16 --max-cycles 50000000 < build/check.in > build/check.out 2> build/check.err")==0,"numeric execution");
char *output=read_text("build/check.out");check(!strcmp(output,"bob!-327683276700xFFFF"),"exact decimal/hex output");free(output);
}
static void file_management(void) {
char *output=shell("write note bob!\ncopy note backup\nrename backup saved\nread saved\ncopy note saved\nrename note saved\nread note\ndelete saved\nread saved\ncopy missing new\ncopy note\ndelete note extra\nread note\nhalt\n");
contains(output,"Copied.");contains(output,"Renamed.");
contains(output,"Destination exists; choose another name or delete it first.");
contains(output,"Deleted.");contains(output,"File not found. Use ls to see names.");
contains(output,"Destination needs 1..23 characters.");
contains(output,"Usage: copy OLD NEW | rename OLD NEW | delete NAME");
contains(output,"bob> bob!\n");free(output);
output=shell("cc bob.c bob\ncopy bob spare\nrename spare renamed\nrun renamed\nwrite a bob!\nwrite b bob!\nwrite c bob!\nwrite d bob!\nwrite e bob!\ncopy bob another\nrename bob original\nrun original\ndelete a\ncopy original another\nrun another\nhalt\n");
contains(output,"File slots full (8). Delete a file and retry.");
contains(output,"Renamed.");contains(output,"Deleted.");
contains(output,"bob> bob!\nExit 0");free(output);
output=shell("write note bob!\ncopy note abcdefghijklmnopqrstuvwx\ncopy note note\ndelete note\nwrite note bob!\nls\nhalt\n");
contains(output,"Destination needs 1..23 characters.");
contains(output,"Destination exists; choose another name or delete it first.");
contains(output,"note 4 chars (text)");free(output);
}
static void compile_workflow(void) {
char *output=shell("go bob.c\ncc bob.c\nrun app\ngo bob.c named\nrun named\ncc bob.c bob.c\nread bob.c\ngo missing\ngo bob.c named extra\nedit broken.c\nint main(void) {\nreturn @;\n}\n.\ngo broken.c\necho bob!\nhalt\n");
contains(output,"bob> bob!\nExit 0");
contains(output,"Output must differ from source; choose another name.");
contains(output,"int main(void) { println(\"bob!\"); return 0; }");
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,"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++;
check(exits==4,"go failure must not execute old output");free(output);
}
static void usability(void) {
char *output=shell("help edit\nhelp go\nhelp write\nhelp read\nhelp ls\nhelp copy\nhelp run\nhelp load\nhelp poke\nhelp alloc\nhelp echo\nhelp clear\nhelp halt\nhelp help\nhelp unknown\nwrite note bob!\nedit note\n:r 1 bob!bob!\n:q\n:p 1\n:u\n:p 1\n:u\n:p 1\n:w\n:q\nread note\nedit note\n:r 1 discarded\n:q!\nread note\nhalt\n");
contains(output,"help COMMAND for usage");contains(output,"go SOURCE [OUTPUT]");
contains(output,"No help for that command.");
contains(output,"Unsaved changes. Use :wq to save or :q! to discard.");
contains(output,"1: bob!bob!\n");contains(output,"1: bob!\n");
contains(output,"Undo/redo applied.");contains(output,"bob> bob!bob!\n\n");
not_contains(output,"bob> discarded");free(output);
write_text("build/check.in","go bob.c\nhalt\n");
check(system(BOB " --os < build/check.in > build/check.out 2> build/check.err")==0,"easy OS startup");
output=read_text("build/check.out");contains(output,"bob16 OS:");contains(output,"bob!\nExit 0");
not_contains(output,"Enter filename");free(output);
}
static void image_validation(void) {
FILE *in=fopen("build/kernel.b16","rb");if(!in)fail("kernel image missing");
FILE *out=fopen("build/bad.b16","wb");if(!out)fail("bad image fixture");int ch;long count=0;
while((ch=fgetc(in))!=EOF){if(count==14)ch^=1;fputc(ch,out);count++;}fclose(in);fclose(out);
check(system(BOB " --boot build/bad.b16 > build/check.out 2> build/check.err")!=0,"checksum corruption rejected");
write_text("build/bad.b16","B16K");check(system(BOB " --boot build/bad.b16 > build/check.out 2> build/check.err")!=0,"truncated image rejected");
}
static void basm_route(void) {
write_text("build/check.in","kernel.basm\ncc bob.c bob\nrun bob\nhalt\n");
check(system(BOB " < build/check.in > build/check.out 2> build/check.err")==0,"interactive BASM route");
char *output=read_text("build/check.out");contains(output,"Starting execution!\nbob!\nbob16 OS:");contains(output,"bob> bob!\nExit 0");free(output);
write_text("build/check.in","demo.basm\n");
check(system(BOB " < build/check.in > build/check.out 2> build/check.err")==0,"original BASM demo");
output=read_text("build/check.out");contains(output,"bob!\n");free(output);
}
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();file_management();compile_workflow();usability();image_validation();basm_route();
printf("bob!\n%d checks passed.\n",checks);return 0;
}
+43
View File
@@ -0,0 +1,43 @@
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; result = 0;
if (b > 0) b = -b;
else a = -a;
while (b < 0) { result = result + a; b++; }
return result;
}
int __divneg(int a, int b) {
int q; q = 0;
while (a <= b) { a = a - b; q++; }
return q;
}
int __div(int a, int b) {
int negative; int q;
if (b == 0) return 0;
negative = (a < 0) != (b < 0);
if (a > 0) a = -a;
if (b > 0) b = -b;
q = __divneg(a, b);
if (negative) return -q;
return q;
}
int __mod(int a, int b) { if (b == 0) return 0; return a - __mul(__div(a, b), b); }
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 > 15) return 0; while (b > 0) { a = a + a; b--; } return a; }
int __shr(int a, int b) {
int low;
if (b < 0 || b > 15) return 0;
while (b > 0) {
low = a & 1;
if (a < 0) a = -16384 + ((a & 32767) - low) / 2;
else a = (a - low) / 2;
b--;
}
return a;
}
+466
View File
@@ -0,0 +1,466 @@
/* BOB-16 C subset compiler. Host tool, written entirely in C.
Input is C preprocessed by GCC; output is native bob16 BASM and B16K. */
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <ctype.h>
#include <stdarg.h>
enum { T_ID=256, T_NUM, T_STR, T_EQ, T_NE, T_LE, T_GE, T_AND, T_OR,
T_INC, T_DEC, T_SHL, T_SHR, T_ADDEQ, T_SUBEQ, T_MULEQ, T_DIVEQ,
T_MODEQ, T_ANDEQ, T_OREQ, T_XOREQ };
enum { N_NUM=1, N_STR, N_ID, N_BINARY, N_UNARY, N_ASSIGN, N_CALL, N_INDEX,
N_BLOCK, N_DECL, N_IF, N_WHILE, N_FOR, N_RETURN, N_BREAK, N_CONTINUE,
N_EMPTY, N_CAST, N_FUNCTION };
typedef struct Node Node;
struct Node { int kind, op, value, type, count; char *name; Node *a,*b,*c,*d,*next; };
typedef struct { int type, number, line; char *text; } Token;
static Token tokens[65536];
static int ntokens, at;
static Node *top, **top_tail=&top;
static uint16_t code[65536];
static int ncode, legacy, serial, return_label;
enum { ORIGIN=0x300, MAX_SYMBOLS=4096 };
typedef struct { char *name; int address; } Label;
static Label labels[MAX_SYMBOLS];
static int nlabels;
typedef struct { int index; char *name; } Fixup;
static Fixup fixups[65536];
static int nfixups;
typedef struct { int index, length, flags; char *target; } Jump;
static Jump jumps[65536];
static int njumps;
typedef struct { char *name; int type,count,offset; Node *init; } Variable;
static Variable globals[MAX_SYMBOLS], locals[MAX_SYMBOLS];
static int nglobals, nlocals;
typedef struct { char *name; Node *node; int nargs; } Function;
static Function functions[MAX_SYMBOLS];
static int nfunctions;
typedef struct { char *name; char *value; } String;
static String strings[4096];
static int nstrings;
static int loop_step[64], loop_end[64], loop_depth;
static int compiling_compare_helper;
static void error(const char *fmt, ...) {
va_list args; fprintf(stderr,"bobcc: line %d: ", tokens[at].line);
va_start(args,fmt); vfprintf(stderr,fmt,args); va_end(args);
fputc('\n',stderr); exit(1);
}
static void *allocate(size_t size) { void *p=calloc(1,size); if(!p) error("out of memory"); return p; }
static char *copy(const char *s) { char *p=allocate(strlen(s)+1); strcpy(p,s); return p; }
static char *named(const char *prefix,const char *name) {
char *s=allocate(strlen(prefix)+strlen(name)+1); strcpy(s,prefix); strcat(s,name); return s;
}
static char *label_name(int id) { char s[32]; snprintf(s,sizeof(s),".L%d",id); return copy(s); }
static Node *node(int kind,Node *a,Node *b) { Node *n=allocate(sizeof(*n)); n->kind=kind;n->a=a;n->b=b;return n; }
static int escaped(const char **p) {
int ch=(unsigned char)*(*p)++;
if(ch!='\\') return ch;
ch=(unsigned char)*(*p)++;
if(ch=='n') return '\n';
if(ch=='r') return '\r';
if(ch=='t') return '\t';
if(ch=='b') return '\b';
if(ch>='0'&&ch<='7') {
int value=ch-'0'; for(int i=0;i<2&&**p>='0'&&**p<='7';i++) value=value*8+(*(*p)++-'0'); return value;
}
if(ch=='x') { int value=0, digits=0; while(isxdigit((unsigned char)**p)) {
int c=tolower((unsigned char)*(*p)++);value=value*16+(isdigit(c)?c-'0':c-'a'+10);digits++;
} if(!digits) error("invalid escape");return value; }
if(ch=='\\'||ch=='\''||ch=='"') return ch;
error("unsupported escape"); return 0;
}
static void lex(const char *source) {
const char *p=source; int line=1;
while(*p) {
if(isspace((unsigned char)*p)) { if(*p=='\n')line++;p++;continue; }
if(p[0]=='/'&&p[1]=='/') { while(*p&&*p!='\n')p++;continue; }
if(p[0]=='/'&&p[1]=='*') { p+=2;while(*p&&!(p[0]=='*'&&p[1]=='/')) { if(*p=='\n')line++;p++; }
if(!*p)error("unterminated comment");
p+=2;continue; }
if(ntokens>=65534)error("too many tokens");
Token *t=&tokens[ntokens++]; t->line=line;
if(isalpha((unsigned char)*p)||*p=='_') {
const char *start=p++;while(isalnum((unsigned char)*p)||*p=='_')p++;
t->text=allocate((size_t)(p-start)+1);memcpy(t->text,start,(size_t)(p-start));t->type=T_ID;
} else if(isdigit((unsigned char)*p)) {
char *end; unsigned long value=strtoul(p,&end,0);
if(end==p||value>65535)error("integer outside 16-bit range");
p=end;t->type=T_NUM;t->number=(int)value;
if(isalpha((unsigned char)*p)) error("integer suffixes unsupported");
} else if(*p=='"'||*p=='\'') {
int quote=*p++, count=0; char buffer[8192];
while(*p&&*p!=quote) { if(count>=8190)error("string too long");int ch=escaped(&p);
if(ch<0||ch>127)error("only ASCII strings supported");
buffer[count++]=(char)ch; }
if(*p!=quote)error("unterminated string");
p++;buffer[count]=0;
if(quote=='\'') { if(count!=1)error("character literal must contain one character");t->type=T_NUM;t->number=(unsigned char)buffer[0]; }
else { t->type=T_STR;t->text=copy(buffer); }
} else {
const char *pairs[]={"==","!=","<=",">=","&&","||","++","--","<<",">>","+=","-=","*=","/=","%=","&=","|=","^="};
int kinds[]={T_EQ,T_NE,T_LE,T_GE,T_AND,T_OR,T_INC,T_DEC,T_SHL,T_SHR,T_ADDEQ,T_SUBEQ,T_MULEQ,T_DIVEQ,T_MODEQ,T_ANDEQ,T_OREQ,T_XOREQ};
int matched=0;for(int i=0;i<18;i++)if(p[0]==pairs[i][0]&&p[1]==pairs[i][1]) { t->type=kinds[i];p+=2;matched=1;break; }
if(!matched)t->type=(unsigned char)*p++;
}
}
tokens[ntokens].line=line;
}
static int tok(void) { return tokens[at].type; }
static int is(const char *s) { return tok()==T_ID&&!strcmp(tokens[at].text,s); }
static int take(int t) { if(tok()!=t)return 0;at++;return 1; }
static void expect(int t) { if(!take(t))error("expected token %d, got %d",t,tok()); }
static char *identifier(void) { if(tok()!=T_ID)error("expected identifier");return tokens[at++].text; }
static int type_start(void) { return is("int")||is("char")||is("void")||is("const"); }
static int parse_type(void) {
if(is("const"))at++;
if(!is("int")&&!is("char")&&!is("void"))error("only int, char, void and pointers supported");
int result=is("void")?3:0;at++;
while(take('*')) { result=1;if(is("const"))at++; }
return result;
}
static Node *expression(int minimum);
static Node *statement(void);
static Node *primary(void) {
Node *n;
if(tok()==T_NUM) { n=node(N_NUM,NULL,NULL);n->value=tokens[at++].number; }
else if(tok()==T_STR) { n=node(N_STR,NULL,NULL);n->name=tokens[at++].text;
while(tok()==T_STR) { size_t a=strlen(n->name),b=strlen(tokens[at].text);char *s=allocate(a+b+1);
memcpy(s,n->name,a);memcpy(s+a,tokens[at++].text,b+1);n->name=s; } }
else if(tok()==T_ID) { n=node(N_ID,NULL,NULL);n->name=identifier(); }
else if(take('(')) {
if(type_start()) { int type=parse_type();expect(')');n=node(N_CAST,expression(13),NULL);n->type=type; }
else { n=expression(1);expect(')'); }
} else if(tok()=='-'||tok()=='+'||tok()=='!'||tok()=='~'||tok()=='&'||tok()=='*'||tok()==T_INC||tok()==T_DEC) {
int op=tokens[at++].type;n=node(N_UNARY,expression(13),NULL);n->op=op;
} else { error("expected expression");return NULL; }
while(1) {
if(take('[')) { n=node(N_INDEX,n,expression(1));expect(']'); }
else if(take('(')) {
if(n->kind!=N_ID)error("function pointers unsupported");
Node *call=node(N_CALL,NULL,NULL);call->name=n->name;
Node **tail=&call->a;if(tok()!=')')do { *tail=expression(1);tail=&(*tail)->next; }while(take(','));
expect(')');n=call;
} else if(tok()==T_INC||tok()==T_DEC) { int op=tokens[at++].type;n=node(N_UNARY,n,NULL);n->op=op;n->value=1; }
else break;
}
return n;
}
static int precedence(int op) {
switch(op) {
case '=':case T_ADDEQ:case T_SUBEQ:case T_MULEQ:case T_DIVEQ:case T_MODEQ:case T_ANDEQ:case T_OREQ:case T_XOREQ:return 1;
case T_OR:return 2;case T_AND:return 3;case '|':return 4;case '^':return 5;case '&':return 6;
case T_EQ:case T_NE:return 7;case '<':case '>':case T_LE:case T_GE:return 8;
case T_SHL:case T_SHR:return 9;case '+':case '-':return 10;case '*':case '/':case '%':return 11;
default:return 0;
}
}
static Node *expression(int minimum) {
Node *left=primary();int op,level;
while((level=precedence(op=tok()))>=minimum&&level) {
at++;Node *right=expression(level+(level==1?0:1));Node *n=node(level==1?N_ASSIGN:N_BINARY,left,right);n->op=op;left=n;
}
return left;
}
static int constant(Node *n) {
if(n->kind==N_NUM)return n->value;
if(n->kind==N_UNARY&&n->op=='-')return -constant(n->a);
error("initializer/array size must be constant");return 0;
}
static Node *declaration(int type,char *name) {
Node *n=node(N_DECL,NULL,NULL);n->name=name;n->type=type;n->count=1;
if(take('[')) { n->count=constant(expression(1));expect(']');n->type=2;
if(n->count<1||n->count>4096)error("array length must be 1..4096"); }
if(type==3)error("void variable");
if(take('=')) {
if(take('{')) { Node **tail=&n->a;do { *tail=expression(1);tail=&(*tail)->next; }while(take(',')&&tok()!='}');expect('}'); }
else n->a=expression(1);
}
return n;
}
static Node *statement(void) {
if(take('{')) { Node *n=node(N_BLOCK,NULL,NULL);Node **tail=&n->a;
while(tok()&&tok()!='}') { *tail=statement();tail=&(*tail)->next; }expect('}');return n; }
if(is("if")) { at++;expect('(');Node *n=node(N_IF,expression(1),NULL);expect(')');n->b=statement();if(is("else")){at++;n->c=statement();}return n; }
if(is("while")) { at++;expect('(');Node *n=node(N_WHILE,expression(1),NULL);expect(')');n->b=statement();return n; }
if(is("for")) {
at++;expect('(');Node *n=node(N_FOR,NULL,NULL);
if(type_start()) { int t=parse_type();n->a=declaration(t,identifier()); }
else if(tok()!=';')n->a=expression(1);
expect(';');
if(tok()!=';')n->b=expression(1);
expect(';');
if(tok()!=')')n->c=expression(1);
expect(')');n->d=statement();return n;
}
if(is("return")) { at++;Node *n=node(N_RETURN,NULL,NULL);if(tok()!=';')n->a=expression(1);expect(';');return n; }
if(is("break")||is("continue")) { int kind=is("break")?N_BREAK:N_CONTINUE;at++;expect(';');return node(kind,NULL,NULL); }
if(type_start()) { int t=parse_type();Node *n=declaration(t,identifier());expect(';');return n; }
if(take(';'))return node(N_EMPTY,NULL,NULL);
Node *n=expression(1);expect(';');return n;
}
static void parse(void) {
while(tok()) {
int type=parse_type();char *name=identifier();Node *n;
if(take('(')) {
n=node(N_FUNCTION,NULL,NULL);n->name=name;n->type=type;Node **tail=&n->a;
if(is("void")&&tokens[at+1].type==')')at++;
else if(tok()!=')')do { int t=parse_type();char *p=tok()==T_ID?identifier():copy("");
*tail=declaration(t,p);tail=&(*tail)->next; }while(take(','));
expect(')');if(take(';'))continue;n->b=statement();if(n->b->kind!=N_BLOCK)error("expected function body");
} else { n=declaration(type,name);expect(';'); }
*top_tail=n;top_tail=&n->next;
}
}
static void emit(int value) { if(ncode>=65536)error("code too large");code[ncode++]=(uint16_t)value; }
static void define(const char *name) {
for(int i=0;i<nlabels;i++)if(!strcmp(labels[i].name,name))error("duplicate label %s",name);
if(nlabels==MAX_SYMBOLS)error("too many labels");
labels[nlabels++]=(Label){copy(name),ORIGIN+ncode};
}
static void mark(int id) { define(label_name(id)); }
static void literal(int reg,int value,const char *name) {
if(!name && value>=-64 && value<=63) {
emit(0x2180|reg<<9);
if(value)emit(0x1180|reg<<9|(value&127));
return;
}
emit(0x4001|reg<<9);emit(0xae01);
if(name) { fixups[nfixups++]=(Fixup){ncode,copy(name)};emit(0); }else emit(value);
}
static void move(int dst,int src) { emit(0x1080|dst<<9|src<<4); }
static void addi(int reg,int value) {
if(value>=-64&&value<=63)emit(0x1180|reg<<9|(value&127));
else { literal(2,value,NULL);emit(0x1000|reg<<9|reg<<4|2<<1); }
}
static void push(int reg) { addi(6,-1);emit(0x9000|reg<<9|6<<6); }
static void pop(int reg) { emit(0x6000|reg<<9|6<<6);addi(6,1); }
static void jump(int id) {
jumps[njumps++]=(Jump){ncode,4,7,copy(label_name(id))};
literal(3,0,label_name(id));emit(0xb600);
}
static void branch(int flags,int id) {
int start=ncode;
emit(0xa000|((flags^7)<<9)|4);jump(id);
jumps[njumps-1].index=start;jumps[njumps-1].length=5;jumps[njumps-1].flags=flags;
}
static void call(const char *name) {
jumps[njumps++]=(Jump){ncode,4,8,copy(name)};
literal(3,0,name);emit(legacy?0xcb00:0xc300);
}
static int symbol_address(const char *name) {
for(int i=0;i<nlabels;i++)if(!strcmp(name,labels[i].name))return labels[i].address;
error("unresolved symbol %s",name);return 0;
}
static void compact_jumps(void) {
int changed;
do {
changed=0;
for(int i=0;i<njumps;i++) {
Jump *j=&jumps[i];if(j->length==1)continue;
int start=j->index,old=j->length,removed=old-1;
int target=symbol_address(j->target)-ORIGIN;
if(target>start)target-=removed;
int offset=target-start-1;
int range=j->flags==8?1024:256;
if(offset < -range || offset >= range)continue;
memmove(code+start+1,code+start+old,(size_t)(ncode-start-old)*sizeof(*code));
ncode-=removed;
for(int k=0;k<nlabels;k++)if(labels[k].address>ORIGIN+start)labels[k].address-=removed;
int out=0;
for(int k=0;k<nfixups;k++) {
Fixup f=fixups[k];
if(f.index>=start && f.index<start+old)continue;
if(f.index>start)f.index-=removed;
fixups[out++]=f;
}
nfixups=out;j->length=1;
for(int k=0;k<njumps;k++)if(jumps[k].index>start)jumps[k].index-=removed;
changed=1;
}
} while(changed);
for(int i=0;i<njumps;i++)if(jumps[i].length==1) {
Jump *j=&jumps[i];int offset=symbol_address(j->target)-ORIGIN-j->index-1;
int range=j->flags==8?1024:256;
if(offset < -range || offset >= range)error("relative transfer out of range");
if(j->flags==8)code[j->index]=(uint16_t)((legacy?0xc000:0xc800)|(offset&2047));
else code[j->index]=(uint16_t)(0xa000|j->flags<<9|(offset&511));
}
}
static void negate(int reg) { emit(0x3100|reg<<9);addi(reg,1); }
static int fresh(void) { return ++serial; }
static Variable *variable(const char *name,int *global) {
for(int i=0;i<nlocals;i++)if(!strcmp(locals[i].name,name)){*global=0;return &locals[i];}
for(int i=0;i<nglobals;i++)if(!strcmp(globals[i].name,name)){*global=1;return &globals[i];}
error("unknown variable %s",name);return NULL;
}
static Function *function(const char *name) {
for(int i=0;i<nfunctions;i++)if(!strcmp(functions[i].name,name))return &functions[i];
error("undefined function %s",name);return NULL;
}
static void expr(Node *n);
static void address(Node *n) {
if(n->kind==N_ID) { int global;Variable *v=variable(n->name,&global);
if(global)literal(0,0,named("g.",n->name));else { move(0,5);addi(0,v->offset); } }
else if(n->kind==N_INDEX) { expr(n->a);push(0);expr(n->b);pop(1);emit(0x1010); }
else if(n->kind==N_UNARY&&n->op=='*')expr(n->a);
else error("expected assignable variable or pointer");
}
static void compare(int op) {
int yes=fresh(),end=fresh();
if(op==T_EQ||op==T_NE) { negate(0);emit(0x1010);branch(op==T_EQ?2:5,yes); }
else {
int negative=fresh(),same=fresh(),opposite=fresh(),nonnegative=fresh();
move(1,1);branch(4,negative);move(0,0);branch(4,opposite);jump(same);
mark(negative);move(0,0);branch(3,nonnegative);jump(same);mark(opposite);
if(op=='>'||op==T_GE)jump(yes);else {literal(0,0,NULL);jump(end);}
mark(nonnegative);if(op=='<'||op==T_LE)jump(yes);else {literal(0,0,NULL);jump(end);}
mark(same);negate(0);emit(0x1010);branch(op=='<'?4:op==T_LE?6:op=='>'?1:3,yes);
}
literal(0,0,NULL);jump(end);mark(yes);literal(0,1,NULL);mark(end);
}
static const char *helper(int op) {
switch(op){case '*':return "__mul";case '/':return "__div";case '%':return "__mod";
case '|':return "__or";case '^':return "__xor";case T_SHL:return "__shl";case T_SHR:return "__shr";default:return NULL;}
}
static void binary(int op) {
if(op=='+')emit(0x1010);else if(op=='-'){negate(0);emit(0x1010);}
else if(op=='&')emit(0x2010);
else if(helper(op)) { push(0);push(1);call(named("fn.",helper(op)));addi(6,2); }
else if(!compiling_compare_helper) {
push(0);push(1);
const char *name=op=='<'?"__cmp_lt":op=='>'?"__cmp_gt":op==T_LE?"__cmp_le":op==T_GE?"__cmp_ge":op==T_EQ?"__cmp_eq":"__cmp_ne";
call(named("fn.",name));addi(6,2);
} else compare(op);
}
static void args_reverse(Node *arg) { if(!arg)return;args_reverse(arg->next);expr(arg);push(0); }
static void expr(Node *n) {
if(!n)error("missing expression");
switch(n->kind) {
case N_NUM:literal(0,n->value,NULL);break;
case N_STR: {
int existing=-1;for(int i=0;i<nstrings;i++)if(!strcmp(strings[i].value,n->name)){existing=i;break;}
if(existing>=0){literal(0,0,strings[existing].name);break;}
if(nstrings==4096)error("too many strings");
char *name=label_name(fresh());strings[nstrings++]=(String){name,n->name};literal(0,0,name);break; }
case N_ID: { int global;Variable *v=variable(n->name,&global);address(n);if(v->type!=2)emit(0x6000);break; }
case N_INDEX:address(n);emit(0x6000);break;
case N_CAST:expr(n->a);break;
case N_UNARY:
if(n->op=='&')address(n->a);
else if(n->op==T_INC||n->op==T_DEC) {address(n->a);push(0);emit(0x6000);if(n->value)move(4,0);
addi(0,n->op==T_INC?1:-1);pop(1);emit(0x9040);if(n->value)move(0,4);}
else {expr(n->a);if(n->op=='*')emit(0x6000);else if(n->op=='-')negate(0);else if(n->op=='~')emit(0x3100);
else if(n->op=='!'){literal(1,0,NULL);compare(T_EQ);}else if(n->op!='+')error("unsupported unary operator");}
break;
case N_BINARY:
if(n->op==T_AND||n->op==T_OR) {int shortcut=fresh(),end=fresh();expr(n->a);move(0,0);branch(n->op==T_AND?2:5,shortcut);
expr(n->b);literal(1,0,NULL);compare(T_NE);jump(end);mark(shortcut);literal(0,n->op==T_OR,NULL);mark(end);}
else {expr(n->a);push(0);expr(n->b);pop(1);binary(n->op);}break;
case N_ASSIGN: {
address(n->a);push(0);
if(n->op!='='){emit(0x6000);push(0);}
expr(n->b);
if(n->op!='=') { pop(1);int op=n->op==T_ADDEQ?'+':n->op==T_SUBEQ?'-':n->op==T_MULEQ?'*':n->op==T_DIVEQ?'/':n->op==T_MODEQ?'%':n->op==T_ANDEQ?'&':n->op==T_OREQ?'|':'^';binary(op); }
pop(1);emit(0x9040);break; }
case N_CALL: {
int count=0;for(Node *a=n->a;a;a=a->next)count++;
if(!strcmp(n->name,"bob_address")){if(count!=1||n->a->kind!=N_ID)error("bob_address requires a function name");function(n->a->name);literal(0,0,named("fn.",n->a->name));break;}
if(!strcmp(n->name,"bob_call")){if(count!=1)error("bob_call needs one argument");expr(n->a);move(3,0);emit(legacy?0xcb00:0xc300);break;}
int vector=-1,expected=0;
if(!strcmp(n->name,"bob_halt"))vector=0;
else if(!strcmp(n->name,"bob_putc")){vector=1;expected=1;}
else if(!strcmp(n->name,"bob_puts")){vector=2;expected=1;}
else if(!strcmp(n->name,"bob_gets")){vector=3;expected=2;}
else if(!strcmp(n->name,"bob_getc"))vector=5;
else if(!strcmp(n->name,"bob_run")){vector=6;expected=1;}
if(vector>=0) {if(count!=expected)error("wrong argument count for %s",n->name);
if(vector==3){expr(n->a->next);push(0);expr(n->a);pop(1);}else if(count)expr(n->a);
emit(0xf000|vector<<8);break;}
Function *f=function(n->name);if(count!=f->nargs)error("wrong argument count for %s",n->name);
args_reverse(n->a);call(named("fn.",n->name));addi(6,count);break; }
default:error("unsupported expression kind %d",n->kind);
}
}
static void stmt(Node *n) {
if(!n)return;
switch(n->kind) {
case N_BLOCK:for(Node *s=n->a;s;s=s->next)stmt(s);break;
case N_DECL:if(n->a){if(n->type==2)error("local array initializers unsupported");Node v={0};v.kind=N_ID;v.name=n->name;address(&v);push(0);expr(n->a);pop(1);emit(0x9040);}break;
case N_RETURN:if(n->a)expr(n->a);else literal(0,0,NULL);jump(return_label);break;
case N_IF:{int other=fresh(),end=fresh();expr(n->a);move(0,0);branch(2,other);stmt(n->b);jump(end);mark(other);stmt(n->c);mark(end);break;}
case N_WHILE:case N_FOR:{int start=fresh(),step=fresh(),end=fresh();
if(n->kind==N_FOR)stmt(n->a);
mark(start);Node *condition=n->kind==N_FOR?n->b:n->a;
if(condition){expr(condition);move(0,0);branch(2,end);}if(loop_depth==64)error("loops nested too deeply");
loop_step[loop_depth]=step;loop_end[loop_depth++]=end;stmt(n->kind==N_FOR?n->d:n->b);loop_depth--;
mark(step);if(n->kind==N_FOR&&n->c)expr(n->c);jump(start);mark(end);break;}
case N_BREAK:case N_CONTINUE:if(!loop_depth)error("break/continue outside loop");jump(n->kind==N_BREAK?loop_end[loop_depth-1]:loop_step[loop_depth-1]);break;
case N_EMPTY:break;
default:expr(n);
}
}
static int frame_slots;
static void collect(Node *n) {
if(!n)return;
if(n->kind==N_DECL){for(int i=0;i<nlocals;i++)if(!strcmp(locals[i].name,n->name))error("shadowing/duplicate local %s",n->name);
if(nlocals==MAX_SYMBOLS)error("too many locals");
frame_slots+=n->count;locals[nlocals++]=(Variable){n->name,n->type,n->count,-frame_slots,n->a};}
collect(n->a);collect(n->b);collect(n->c);collect(n->d);collect(n->next);
}
static void generate(void) {
for(Node *n=top;n;n=n->next) {
if(n->kind==N_FUNCTION){if(nfunctions==MAX_SYMBOLS)error("too many functions");int count=0;for(Node *a=n->a;a;a=a->next)count++;
for(int i=0;i<nfunctions;i++)if(!strcmp(functions[i].name,n->name))error("duplicate function %s",n->name);
functions[nfunctions++]=(Function){n->name,n,count};}
else {if(nglobals==MAX_SYMBOLS)error("too many globals");for(int i=0;i<nglobals;i++)if(!strcmp(globals[i].name,n->name))error("duplicate global %s",n->name);
globals[nglobals++]=(Variable){n->name,n->type,n->count,0,n->a};}
}
if(function("main")->nargs)error("main must take no arguments");
define("entry");literal(6,0xf000,NULL);literal(5,0,NULL);call("fn.main");emit(0xf000);
for(int i=0;i<nfunctions;i++) {
Function *f=&functions[i];nlocals=0;frame_slots=0;int arg=0;
compiling_compare_helper=!strncmp(f->name,"__cmp_",6);
for(Node *a=f->node->a;a;a=a->next){if(!*a->name||a->type==2)error("named scalar/pointer parameters required");locals[nlocals++]=(Variable){a->name,a->type,1,2+arg++,NULL};}
collect(f->node->b);if(frame_slots>4096)error("frame too large");return_label=fresh();define(named("fn.",f->name));
push(7);push(5);move(5,6);addi(6,-frame_slots);stmt(f->node->b);literal(0,0,NULL);mark(return_label);move(6,5);pop(5);pop(7);emit(0xe000);
}
for(int i=0;i<nglobals;i++){Variable *g=&globals[i];define(named("g.",g->name));Node *init=g->init;
for(int j=0;j<g->count;j++){emit(init?constant(init):0);if(init)init=init->next;}if(init)error("too many initializers for %s",g->name);}
for(int i=0;i<nstrings;i++){define(strings[i].name);for(char *p=strings[i].value;*p;p++)emit((unsigned char)*p);emit(0);}
compact_jumps();
if(ORIGIN+ncode>0x9000)error("kernel exceeds 0x9000 (code + data is %d words)",ncode);
for(int i=0;i<nfixups;i++){int found=0;for(int j=0;j<nlabels;j++)if(!strcmp(fixups[i].name,labels[j].name)) {code[fixups[i].index]=(uint16_t)labels[j].address;found=1;break;}
if(!found)error("unresolved symbol %s",fixups[i].name);}
}
static char *read_file(const char *path) {
FILE *f=fopen(path,"rb");if(!f){perror(path);exit(1);}fseek(f,0,SEEK_END);long length=ftell(f);rewind(f);
if(length<0||length>4000000)error("input too large");
char *s=allocate((size_t)length+1);
if(fread(s,1,(size_t)length,f)!=(size_t)length)error("read failure");
fclose(f);return s;
}
static void word(FILE *f,int value) { fputc(value&255,f);fputc((value>>8)&255,f); }
int main(int argc,char **argv) {
if(argc<4||argc>5){fprintf(stderr,"Usage: bobcc input.i output.basm output.b16 [--legacy]\n");return 1;}
if(argc==5){if(strcmp(argv[4],"--legacy"))error("unknown option");legacy=1;}
lex(read_file(argv[1]));parse();
/* Parse helper bodies in a second token buffer, preserving the AST. */
memset(tokens,0,sizeof(tokens));ntokens=at=0;lex(read_file("tools/arithmetic.c"));parse();generate();
FILE *basm=fopen(argv[2],"wb");if(!basm){perror(argv[2]);return 1;}
fprintf(basm,"; bob16 C kernel, generated by tools/bobcc.c\n.fill 4601\n.fill b600\n.fill 0300\n");
for(int i=3;i<ORIGIN;i++)fprintf(basm,".fill 0000\n");
for(int i=0;i<ncode;i++)fprintf(basm,".fill %04x\n",code[i]);
fclose(basm);FILE *binary=fopen(argv[3],"wb");if(!binary){perror(argv[3]);return 1;}
unsigned sum=0;for(int i=0;i<ncode;i++)sum+=code[i];fwrite("B16K",1,4,binary);word(binary,1);word(binary,ORIGIN);word(binary,ORIGIN);word(binary,ncode);word(binary,(int)sum);
for(int i=0;i<ncode;i++)word(binary,code[i]);
fclose(binary);
char map_path[4096];
if(strlen(argv[3])+5>=sizeof(map_path))error("output path too long");
strcpy(map_path,argv[3]);char *extension=strrchr(map_path,'.');
if(extension)strcpy(extension,".map");else strcat(map_path,".map");
FILE *map=fopen(map_path,"w");if(map){for(int i=0;i<nlabels;i++)fprintf(map,"%04x %s\n",labels[i].address,labels[i].name);fclose(map);}
printf("Compiled %d bob16 words.\n",ncode);return 0;
}
+41
View File
@@ -0,0 +1,41 @@
/* Run from the repository root. Build tools, emulator and guest without Python. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
#include <direct.h>
#define EXE ".exe"
#define BUILD_DIR "build\\"
#define BOB_COMMAND "bob.exe"
#else
#include <sys/stat.h>
#define EXE ""
#define BUILD_DIR "./build/"
#define BOB_COMMAND "./bob"
#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;
}
#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);}
#else
mkdir("build",0777);
#endif
run("gcc -std=gnu11 -O2 -Wall -Wextra -Werror main.c -o bob" 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");
if(argc==2&&!strcmp(argv[1],"--test")) {
run("gcc -std=c11 -O2 -Wall -Wextra -Werror tests/test_os.c -o build/test_os" EXE);
run(BUILD_DIR "test_os" EXE);
} else if(argc==2) run(BOB_COMMAND " --boot build/kernel.b16");
return 0;
}