# CosmOS ## Overview: CosmOS is a small, single-tasking disk operating environment for the SplitBit 8-bit computer. It boots the machine, finds and mounts an SBFS filesystem, provides a command line and memory monitor, loads applications from disk, and takes control back when they finish. CosmOS is written entirely in SplitBit assembly. It is closer in scale and purpose to a resident monitor or an early disk operating system than to a modern multitasking OS: one program owns the machine at a time, there is no privilege boundary, and applications are assembled for fixed regions of memory. What it provides is a stable home from which those programs can be found, run, and given services without each one having to boot the machine for itself. ### Features: - Interactive Shell: Read commands from the SplitBit console and continue until `exit` or the end of input. - SBFS Filesystem: Mount, list, read, write, delete, and rename files on a SplitBit disk. - Paths: Anywhere a filename is taken, a path may be given instead - names with `/` between them, with `.` and `..`. Directories are read but not yet made; the host tool makes them. - Working Directory: `cd` moves the machine, `dir` lists where it is, and the prompt says where that is once it is not the root. A program may move too, and the shell puts the working directory back when the program stops. - Making Directories: `mkdir` and `rmdir` on the machine, and files written where their path says, so a disk can be organised without the host tool. - Loadable Applications: Validate SBEX files, copy their Program and Data segments into the addresses for which they were assembled, and start them at their declared entry point. - Invocation By Name: A word the shell has no command for is looked for on the disk as `.sbx`, and loaded and started if it is there. Built-in commands are tried first. - Resident Services: Applications can print strings and numbers, read lines, receive their command arguments, read and write files, and return to the shell through named software interrupts. - Application Vectors: Install interrupt vectors carried by a loadable program and restore whatever they replaced when the program exits. - Stack Reclamation: Save the system Stack before launching an application and take it back on exit, so an application need not unwind itself before returning. - Memory Monitor: Inspect and modify Program Memory, Data Memory, and registered device-memory banks through the SplitBit memory controller, disassemble instructions, and begin execution at an address. - Hardware Discovery: Mount the disk through the device registry rather than assuming that one is present at a particular controller bank. - Native Applications: Includes demonstrations, mathematical programs, interactive programs, a game, and a line-oriented text editor. - Reproducible Disk Image: The makefile assembles the system and every application, then constructs a fresh SBFS image containing the resulting executables. ## Building and Running: CosmOS currently lives inside the SplitBit Emulator repository and uses its assembler, emulator, and disk-image tool. From the repository root, build those tools first: ```sh make ``` That builds CosmOS, all of its applications, and a disk to boot them from - one makefile covers the machine and the system. To rebuild only part of it: ```sh make cosmos make disk ``` To boot CosmOS with that disk attached: ```sh make run-cosmos ``` Or on the Voyager, which is the same machine with a screen and a speaker instead of a terminal: ```sh make run-voyager ``` Both depend on the disk rather than merely using it, which is worth knowing: **what is on a disk is whatever was built when the disk was made.** A machine whose console has changed will start an old image quite happily and its programs will draw whatever the old way now means, which is a confusing thing to debug and an easy thing to avoid. The generated files are kept under `Programs/build/`: - `CosmOS/Source/cosmos.bin` is the bootable CosmOS image. - `CosmOS/Apps/*.sbx` are loadable application images. - `cosmos.img` is the SBFS disk containing those applications. **The disk carries every source in `Programs/`, mirrored.** Not a list kept in the makefile - a list goes stale the moment somebody adds a program and forgets to name it, and what they forgot is invisible until they go looking for it on the machine. Putting a file where the others live is the whole of putting it on the disk. That matters most for the things nobody thought worth shipping a binary of. A demo that is not interesting enough to build by default is still worth having the source of, because the machine can build it: ``` > cd /Source/Examples /Source/Examples> Asm colours.asm wrote colours.bin: program 114, data 86, labels 8 ``` Two things are left behind. `build`, because what a project builds is not what it wrote. And anything whose name is longer than a directory entry holds, which is **refused rather than skipped**: a disk quietly missing a file is exactly the failure a mirror exists to prevent, so the build stops and says which name to shorten. `/Lib` still holds the library sources separately, because that is where an `#Include` looks after looking beside the file that asked. The same files therefore appear twice - once as what a program includes, once as part of the source tree - and that is the difference between an installed library and a copy of the source. The disk is rebuilt from scratch when its applications change, so its contents describe the current source tree rather than accumulating files left by older builds. ## Shell Commands: CosmOS currently provides these built-in commands: | Command | Description | | -- | -- | | `dir` | List the files on the mounted disk and their sizes. | | `load ` | Read and validate an SBEX application, then place its code and data where its header requests. | | `run [words]` | Start the loaded application and make the rest of the line available to it as an argument. | | `cd [path]` | Go to a directory, or to the root with nothing after it. | | `mkdir ` | Make a directory. | | `rmdir ` | Remove one, if it is empty. | | ` [words]` | Any word the shell does not recognise is looked for on the disk as `.sbx`, and loaded and started if it is there. | | `delete ` | Remove a file from the filesystem and release its blocks. | | `rename ` | Give a file a different name without moving its contents. | | `monitor` | Enter monitor mode, in which the prompt becomes `*` and the commands below are also available. | | `help` | Show the built-in command summary. | | `exit` | Leave monitor mode if in it, and otherwise halt the machine. | Monitor mode adds the following. It is a mode rather than a separate program because a loaded application occupies the one region a loaded application is given, so a monitor which was itself an application could never examine another one. The mode persists: an application started with `g` which returns through `osExit` arrives back at the monitor prompt rather than at the shell. | Command | Description | | -- | -- | | `x [address]` | Display 64 bytes as hexadecimal and as characters. | | `d [address]` | Disassemble eight instructions. | | `a
` | Assemble instructions into memory until a line containing only a dot. | | `s
...` | Write bytes into the bank being examined, including Program Memory. | | `b ` | Select a memory space or a registered bank number. | | `g
` | Begin execution at an address. | `x` and `d` share a position, and each leaves it after what it displayed, so either may be given without an address to continue from where the last one stopped. For example: ```text > dir > load Snake.sbx > run ``` Or, equivalently: ```text > Snake ``` Loading and running remain separate operations, and both of them remain. A loaded program may be run again without being read from disk again, which is useful both as a monitor facility and as a test that CosmOS correctly restores its Stack and vector table after every run; and `load` is how the monitor puts an arbitrary file in front of itself, which is a thing typing a name deliberately cannot do. ### Paths: Everywhere CosmOS takes a filename it will take a path: names with `/` between them, walked from the root, with `.` meaning where you are and `..` meaning the directory above. `..` from the root is the root. A bare name is a path of one name, so nothing written before directories existed had to change. ```text > load /Apps/Snake.sbx > Type /Notes/today.txt ``` **Programs did not have to be taught any of this.** Path resolution lives inside `sbfsFind`, below the services, so `osFileInfo`, `osFileBlock`, `osFileSave`, `osFileDelete` and `osFileRename` all still take a pointer to a name - and a path is simply a longer name. `Type`, `More`, `Edit` and the assembler gained subdirectories without a line being changed in any of them. Each *name* along a path is still the 22 characters a directory entry holds, and a longer one is refused rather than cut short, because a name cut to 22 characters is a different name that might well be some other file's. ### What It Costs: **The assembler is superlinear in what it reads**, and that is worth knowing before reaching for it on something large. Cycles per byte of source climb with the size of the source: | Source | Bytes | Cycles a byte | | --- | --- | --- | | `colours.asm` | 4,299 | 1,383 | | `Edit.asm` | 16,778 | about 3,000 | | `cosmos.asm` | about 104,000 | 6,290 | So assembling the operating system is 654 million cycles, which is eleven minutes at a megahertz. **It is not the disk**: the same build costs 654 million on a disk carrying the whole source tree and 653 million on a flat one with a sixth as many files. The suspected cause is looking a label up by walking the whole table, of which there are about nine hundred, once for every reference - suspected rather than measured. Nothing is being done about it, deliberately. Development happens with the host assembler, which is where the tooling is, and the machine assembling itself is a demonstration that it can rather than the way anybody works. But faster hardware buys a constant factor and does not change the shape of the curve, so the program that eventually forces this is not CosmOS - it is the first one twice its size. ### The Working Directory: `cd` moves the machine. A path beginning with `/` is measured from the root and anything else from where you are, so a bare name means a file in the current directory - which is the whole of what a working directory is, and no program had to be told. ```text > cd /Apps /Apps> dir /Apps> cd Deep /Apps/Deep> cd .. /Apps> cd > ``` `cd` with nothing after it goes to the root, which is the only place always there. **The prompt says where you are, but only when that is not the root**, so a machine nobody has moved about on looks exactly as it always did. Nothing stores the path: the working directory is an entry index and two bytes, and the text on the prompt is worked out again each time by walking the chain of parents upward. That walk goes from where you are up to the root, so the names arrive deepest first and are written into the buffer **backwards, from its end**. When they do not all fit, what is already down is the deep end of the path, which is the end worth keeping - so the prompt is cut at the front and says so: ``` ...opqrst03/abcdefghijklmnopqrst04/.../abcdefghijklmnopqrst08> ``` **Three limits, and the smallest is not the one you would guess.** A path handed to any one operation is capped at 95 characters up to the last separator plus a name of 22; the host tool carries 512, which only means it can build a tree CosmOS cannot name in one piece. Neither of those binds anything: the longest path on a full install is 21 characters. What binds is the prompt's 127 bytes - and **nothing caps how deep the directories go**, because `mkdir a` and `cd a` are each well inside every limit and can be typed all day. Before the walk was bounded it wrote past the front of that buffer and into whatever the assembler had put below it, which was the shell's own command names. Six directories of 22 characters was enough. The first five bytes to go were the word `exit`, so the shell stopped recognising the command for leaving - a fault with no plausible connection to the directory you happened to be standing in. `dir` lists the directory you are in rather than the whole disk. A program can move too, with `osChangeDir`, and **the shell puts the working directory back when the program stops** - the same discipline it already applies to the Stack and to the vector table, and for the same reason. A program is entitled to move about; the shell is entitled to find itself where it left off. Whenever what a relative path means changes - a `cd`, a program calling `osChangeDir`, a program exiting - CosmOS forgets the file it was remembering. That cache is keyed on the path as it was typed, so `notes.txt` is the same key in two directories and nothing about the entry it holds would look wrong. It is the kind of stale that gets believed rather than noticed. ### Making And Removing Directories: `mkdir` and `rmdir` are the machine's own, so a disk can be organised without the host tool. A file a program writes goes where its path says, and a bare name means the directory you are in. **A directory costs one entry and no blocks at all.** Its start, block count and tail are all zero, which is what keeps the flat array of entries the whole allocation map - with files laid down contiguously, every block is inside some entry's range or it is not, and an entry with no range is in nobody's way. Making the first directory on a disk is what raises it from version one to version two, because it is the only thing that makes the difference between them real. A disk stays readable by anything that has never heard of a directory right up until it actually has one. **A disk may have at most 8,191 directory blocks**, which is 65,528 entries, and that number comes from the parent field rather than from anything about size. A parent is an index *plus one* in two bytes, so entry 65,535 has no parent number at all: adding one wraps to zero, and zero means the root. The failure is worth describing, because it is the shape of failure this format has to watch for. Such an entry does not refuse what is put inside it. It writes a parent of zero and the thing lands in **the root**, while whatever asked is told it went where it asked for. Looking in that directory afterwards finds nothing, because the search is for a parent the entry does not carry - so the same create succeeds again, and again, filling the root with entries of one name. Two entries of one name in one directory is precisely what `rename` refuses on the grounds that a search answers with whichever it meets first and the rest can never be reached again; this made them by the handful, one per attempt. Both implementations refuse to format past the bound, and refuse to read a disk that claims it - because a disk claiming it was made by something that never checked. Four things are refused, and each refusal is the reason a separate command exists: **`rmdir` will not take a file and `delete` will not take a directory.** Neither can be the one that removed more than was asked for. **A directory with anything in it is refused.** This is not politeness. A parent is an entry *index*, and a freed index is handed to the next thing created - so the children of a directory removed from under them would turn up inside whatever took its place. Nothing points downward, so there would be no way to find them afterwards and no way to notice. **A name already used in that directory is refused.** Two entries with one name in one place is a directory that cannot be searched sensibly: a search answers with whichever it meets first, and the other becomes unreachable without ever having been deleted. The same name in a *different* directory is fine, and is the point of the exercise. **`rename` will not move anything.** Only the twenty two bytes of the name change and the parent is not among them, so `rename a/x b/y` would be a lie the disk went along with. `Tests/agree.sh` builds the same disk twice, once with SplitDisk and once with CosmOS, and compares the images byte for byte. Every field one writes and the other only reads is checked there and nowhere else: which entry a thing lands in, which block, what a directory's unused fields hold, the version, the free count. ### Starting An Application By Name: A word the shell has no command for is not immediately an error. Before saying so, the shell adds `.sbx` to it unless it is already there, looks for a file of that name, and if one is there loads it and starts it exactly as `load` and `run` would. Whatever followed the word reaches the program through `osArgument`, the same way and by the same route as whatever follows `run`. Three properties of this are deliberate: **Built-in commands are tried first and always win.** The search happens only after the whole dispatch chain has failed to match, so a file named `dir.sbx` cannot become `dir`. The commands that are worth trusting when the disk is the thing being doubted stay trustworthy. **The extension is what makes a file reachable by name.** Typing `notes` looks for `notes.sbx`, and typing `notes.txt` looks for `notes.txt.sbx`. A text file therefore cannot be started by typing what it is called, whatever happens to be inside it. Only `load` reaches a file by its literal name. A path works here too, so `/Apps/Say hello` starts `/Apps/Say.sbx` and gives it `hello`. **Two places are tried, in order: where you are, and then `/Apps`.** The first is what makes a program you are working on the one that runs; the second is what lets `Snake` work from anywhere without a copy of it in every directory. A word that already begins with `/` has said where to look, so only that place is tried. Neither is stored anywhere, so there is nothing to configure and nothing to go stale - a search path somebody could set would need somewhere to live between one boot and the next, and there is no such place yet. **A file that is found but is broken says so.** If `notes.sbx` exists and is not an SBEX program, typing `notes` reports `not a program` rather than `I do not know: notes`. Reporting an unknown command about a file that is sitting on the disk would send somebody looking in the wrong place. Names are matched exactly, including case, because every other name on the filesystem is. What limits the typed word is the buffer it is built in rather than the format: each name along a path is still twenty two characters, and the path walker refuses a longer one rather than cutting it down. A word that will not fit is reported as unknown, which is the truth, since nothing the shell can reach is called that. CosmOS also boots without a disk. It reports that no filesystem was found, leaves the shell and memory monitor available, and refuses commands that require a mounted disk without stopping the machine. ## What Is On The Disk: `make disk` builds the disk this system is meant to be met on, and it is laid out in three directories: | Where | What | | -- | -- | | `/Apps` | The programs. The second place the shell looks for a word it does not recognise, so anything here starts by name from anywhere on the disk. | | `/Source` | The things you name to the assembler: CosmOS itself, the assembler itself, and small programs to read. | | `/Lib` | The things those include. Everything here is named by an `#Include` somewhere and by nothing else, which is what makes it a library rather than a source. | The split is by role rather than by which directory the host keeps a file in, and it only works because **an include is looked for where you are and then in `/Lib`** - the same rule the shell uses for programs, applied to the assembler. Without that search every source that calls a service would have to sit beside `services.asm`, and there would be nothing to organise. So the machine rebuilds itself from its own disk: ```text > cd /Source /Source> Asm cosmos.asm wrote cosmos.bin: program 9778, data 3346, labels 648 /Source> Asm Asm.asm wrote Asm.sbx: program 7570, data 4114, labels 562 ``` Both come out byte for byte what the host assembler makes from the same source. ## Included Applications: `Programs/CosmOS/Apps` holds what the shell can load, and the application disk is built from every assembly file in it. Several are old programs written for the bare machine that needed five edits each to become loadable ones - the Fibonacci and sieve programs, `greet`, and `hello`. The rest were written for the system as it is now, and each of those exists to show one thing working: | Program | What it is for | | --- | --- | | Life | Conway's Game of Life, which had to be taught to stop, since a program that never ends takes the shell with it. Polls the console between generations. | | Snake | A game. Draws a whole screen with cursor addressing and steers with single keys, asking the console once a frame and never waiting. | | Keys | The console interrupting rather than being asked. The only one that brings a vector of its own, which is what the version two format exists for. | | Say | Prints whatever it was told, which is the shortest thing that shows osArgument working. | | Reboot | Starts the machine again, in 45 bytes. Writes a port rather than asking the system, because a reset has to work when the system does not. | | Once | Asks the loader to start something else on the next start, and only that one, in 569 bytes. | | Status | Says what the last program made of what it was asked to do, in 222 bytes. The shell keeps the number and does not print it; this is how a person looks. | | Settle | Says how the last start went and tells the machine to stop falling back, in 353 bytes. A program rather than a shell word, because the shell is for what cannot be done without it. | | Files | Writes a file, reads it back, renames it and deletes it, in 675 bytes, including nothing but the service names. It is what says a program does not need a filesystem inside it. | | Break | Stops itself twice with SWI osBreak, so that the registers can be seen changing between one stop and the next. | | Edit | A line editor. | | Stream | Reads an 84,000 byte file through a buffer of 256, which is what says a file bigger than Data Memory can be read at all. | | Type | Prints a named text file a block at a time, including one too large to fit in Data Memory. | | Pour | Writes a file a block at a time, never holding more than one block of it. Each block is filled with a byte naming itself, so a block written to the wrong place shows up as content rather than as a length. | | Copy | Copies one path to another a block at a time, including an empty file or one larger than Data Memory. | | Compare | Compares two files a block at a time, stopping at their real tails rather than comparing unused bytes in the final disk blocks. | | Wander | Goes to the directory it is given and reads a file there by a bare name. The only thing that moves the machine from inside a program, and so the only thing that can check the shell puts the working directory back afterwards. | | More | A forward-only pager. Space advances a screen, Return one line, and q stops. | ### The Monitor: The monitor is **part of the shell**, not a program the shell loads, and that is the whole reason it works. A loaded program occupies the one place a loaded program goes, so a monitor that was an application could never look at any other application: loading the thing you wanted to inspect would replace the thing doing the inspecting. `monitor` turns it on and the prompt changes from `>` to `*`. It is **a mode, not a detour** - the shell's own commands still work, and the mode persists until you say otherwise: ``` > load Snake.sbx > monitor * d 2000 2000 47 00 11 00 SETD.0 1100 * b data bank 01 * x 1000 * exit > ``` **A program giving the machine back lands at the prompt it was started from**, so `g` into something, letting it run, and having it exit puts you back at `*` rather than at the shell. That falls out of the mode being a variable the prompt reads rather than a second loop: every way back to the prompt goes through one place, including `osExit`. Looking at a program and running it therefore do not interrupt each other, which is the thing a monitor is for. `exit` leaves whatever you are in - the monitor if you are in it, the machine if you are not. | | | | --- | --- | | `x [addr]` | Sixty-four bytes, as hex and as characters | | `d [addr]` | Eight instructions, disassembled | | `a addr` | Assemble instructions, until a line that is just a dot | | `s addr b b ...` | Put those bytes there | | `b program\|data\|n` | Which bank to look at | | `g addr` | Go there | `a` writes the assembler's own syntax: a selector rides on the mnemonic as `LDA.0` or `LDD.0.1`, and leaving one off means Data Pointer 0 exactly as it does in a source file, so nothing learned at the monitor has to be unlearned when writing a program. Case does not matter, and the whole line is refused before anything is written, so a mistyped instruction leaves no half of itself behind. ``` * b data * s 8100 68 65 6C 6C 6F 2C 20 74 79 70 65 64 0A 00 * b program * a 8200 8200: SETD.0 8100 8204: SWI 10 8206: SWI 12 8208: . * g 8200 hello, typed ``` A program and its data, both entered by hand, calling a system service and returning to the prompt they were written at. Note the two banks: instructions go into Program Memory and the string into Data Memory, because that is what a Harvard machine means and the monitor will not guess for you. **Numbers here are hexadecimal and bare.** A source file writes `0x2000` or `0d16` because it has both and must say which; the monitor has one and says so once. **What cannot be written is a label**, and that is the whole difference between this and the assembler proper. A label is a promise to fill an address in later, and later is what a line at a time does not have. It is also why the same instruction table serves both directions here: what `a` writes, `d` reads back, and neither can drift from the other or from the assembler they were generated from. `x` and `d` share one cursor and each leaves it past what it showed, so without an address either carries on - reading through memory is one letter at a time, and you can switch between bytes and instructions without retyping where you are. `s` deliberately does not move it. Everything else here does something; the monitor looks at what the others did. It shows memory as hex and as characters, disassembles it, writes bytes into it, and jumps to an address - all through the memory controller, which is the only thing that can reach Program Memory. That is why a monitor is worth more on this machine than on most. Data Memory a program can already read for itself with a Data Pointer. The half it cannot see is Program Memory, and that is the half its bugs are in. **Its instruction table is generated from the assembler's**, by `Tests/instructiontable.py`, and checked against it by `Tests/docs.sh` - along with a second check that the lengths that table implies are the ones the manual's own Bytes column prints. Both matter for the same reason: a disassembler that disagreed about how long an instruction is would not print one line wrong, it would lose its place and print everything after it wrong. Which is what a disassembler does anyway when it starts in the middle of an instruction, and is worth seeing once so it is recognised later. **Where to put something you typed in yourself** is a question the monitor answers, because the answer moves every time the monitor is rebuilt. `m` says where its own two segments end, and those are the first free addresses: ``` > m code from 2000, free from 2607 data from 1000, free from 1367 up to the stack ``` Which is what makes the monitor's real trick possible - a program that no assembler ever saw: ``` > s 8000 26 48 D1 00 26 49 D1 00 26 0A D1 00 18 12 > d 8000 8000 26 48 INIA 48 8002 D1 00 OUTA 00 8004 26 49 INIA 49 ... 800C 18 12 SWI 12 > g 8000 HI ``` Typed in as bytes, checked by disassembling it back, and run. It ends with `SWI osExit`, which is how it gives the machine to the shell rather than to nothing. `g` does not come back: what it runs has to give the machine to the shell itself, which `SWI osExit` is how a program does. Breakpoints are not the monitor's - they are `SWI osBreak`, written into the program rather than poked over it, and described under Stopping To Look. ### The Editor: `Edit` is the first program on this machine that makes a file a person typed - every byte on every disk before it was put there by the host tool. It is line oriented in the manner of `ed`: `l` lists, `a` adds at the end, `i` and `c` and `d` take a line number, `w` writes and `q` stops. It includes nothing but `services.asm` and `text.asm`: the filesystem and the console are the system's, asked for rather than carried. That is what brought `Edit` down from 4,941 bytes to 2,243 bytes without a line of its own logic changing - and the way that was checked is worth knowing, because the recorded output of the `cosmosEdit` test did not move by a single byte across the rewrite. **A line it reads in is at most 128 characters**, the same length a line is everywhere else on this machine, and a file with a longer one is refused rather than opened. Refused rather than shortened, because this is an editor: a line cut on the way in would be written back cut, and the file damaged by having been looked at. That limit was not there at all until a source file found it. The buffer is followed in memory by the head of the document and the pointer the line allocator hands out, so a 94 character line wrote characters over both - a 31 line file opened as 3, and opening it a second time walked a list that led back into itself for ever, with the emulator still running and the machine never answering again. Typing a long line was always safe, because `osReadLine` is told how much room there is; only the file being read went unchecked, which is why a new document behaved and a source file did not. It keeps the document as a **linked list of lines** rather than one buffer with newlines in it. Each line says where the next one is, how long it is, and then its bytes. Inserting is two pointers changed and nothing moved; with a flat buffer it would mean shifting every byte after the edit, on a machine whose only block move is a device asked politely. The price is that deleted lines are not reused, so a heavy session uses more room than the document needs and writing it out is what tidies up. Saving goes through `sbfsSaveFile`, so a document that has grown is written somewhere else and the original is only let go of once the new one is safely down. That is the whole reason the editor was written: not because the machine needed an editor, but because every tool that produces a file needs the same four operations, and building them for one imaginary tool is how they end up wrong. These are ordinary SBEX files on SBFS. None of them is built into the operating system, and a disk can be filled from either side: the host tool puts files on, and so does the machine, which assembles its own now. ### A Clean Install: `make disk` lays down a disk the machine can start itself from, and `make run-cosmos` starts it - with no boot image named, so the emulator shadows its ROM and reads the disk for everything else. ``` / Apps Source Lib System /Apps what you run, and the second place the shell looks for a word /Source what you assemble, including stage1.asm and stage2.asm /Lib what those include /System/Boot cosmos.bin, and the slots the loader lives in ``` **The loader's own source is on the disk**, which means the machine can rebuild what starts it: `Asm stage2.asm` produces the bytes that go in a boot slot, and everything stage two includes is already in `/Lib`. Stage one is the exception and always will be - it is the ROM, and the one part of this a disk cannot replace. No `boot.cfg` is written. Stage two falls back to `/System/Boot/cosmos.bin` when there is none, and a clean install having nothing to configure is the right default. `make run-cosmos-direct` hands the system over the old way instead, memory placed from outside with nothing on the disk consulted. That is what a debugger does, and it is what to use when the thing being debugged is the boot chain, since it skips the boot chain. ## The Application Model: CosmOS divides the two SplitBit address spaces by convention: | Memory | CosmOS | Loaded application | | -- | -- | -- | | Program Memory | `0x0000` through `0x3FFF` | `0x4000` and above | | Data Memory | `0x0000` through `0x1FFF` | `0x2000` and above | Both of CosmOS's halves were doubled once it outgrew the first ones. **The division is a convention and nothing enforced it**, so CosmOS quietly grew past `0x1FFF` and the next program loaded landed on top of its own code - which does not fail where it happens, it fails later, in whatever part of the shell the program happened to cover. `make test` now measures both segments against the numbers in this table, so the table is checked rather than merely written down. **The table is checked against itself as well.** The first version of that check read only the CosmOS column, and so it passed a table whose Data row gave the system `0x3FFF` and an application `0x2000` - two columns that cannot both be true, sitting next to each other. Measuring one number against the code and never against the number beside it is how a specification contradicts itself in public. Applications state their actual Program and Data addresses with `#Base`. The SplitBit assembler then writes an SBEX loadable image containing those addresses, the entry point, the segment lengths, and any vectors the application needs. CosmOS does not relocate code: the addresses in the file must be the addresses for which it was assembled. This division is an ABI convention rather than protection. An application owns the machine while it runs and may address hardware or CosmOS memory directly. The convention keeps independently assembled software out of the system's way; it is not a security boundary. ### System Services: Applications include `Source/services.asm` to obtain stable names and vector numbers for the services CosmOS provides. Neither side ever types a number: the file both of them include is the only place any of them is written down. What each service is and what it answers in is set out under "What A Program May Ask The System For". The largest application CosmOS has is the assembler in `Programs/CosmOS/Assembler/`. It travels with CosmOS rather than with the emulator, for the same reason the C assembler travels with the emulator: it is part of the system it was written for. A minimal CosmOS application therefore looks like this: ```asm #Include services.asm #Program #Base 0x4000 start: SETD.0 Message SWI osPrintString SWI osExit #Data #Base 0x2000 Message: "Hello from CosmOS." ``` An application may also include its own libraries or access hardware ports directly. The services are an interface offered by the system, not the only way software is allowed to use the computer. ## What A Program May Ask The System For: A loaded program is on its own hardware and can do anything the machine can do - it is a fence, not a wall. But the things it usually wants are things the system is already doing, and asking is both shorter and the only way to reach code that was assembled separately. `CALL` needs a label, and a label has to be in the same assembly; `SWI` needs only a number both sides agree on. Those numbers are written down once, in `Programs/CosmOS/Source/services.asm`, which both the system and the program include. Neither side ever types a number. | Service | Does | | --- | --- | | osPrintString | DP0 names a string ending in a zero byte. Prints it. | | osReadLine | DP0 names somewhere to put a line, B says how much room there is. Reads one from the console. Q comes back holding how long it was. | | osExit | Gives the machine back. Does not return. | | osArgument | DP0 names somewhere to put whatever followed the run command, B says how much room there is. | | osFileRead | DP0 names a file, DP1 says where to put it. Q is zero if it read, and DP3 comes back holding how many bytes there were. | | osFileSave | DP0 names a file, DP1 is the bytes, A and B together are how many. Q is zero if it saved, whether or not it was there before. | | osFileDelete | DP0 names a file. Q is zero if it went. | | osFileRename | DP0 is the name a file has, DP1 the name it should have. Q is zero if it moved. | | osFileInfo | DP0 names a file. Q is zero if it is there, and DP3 comes back holding how many blocks it occupies. | | osFileBlock | DP0 names a file, DP1 says where to put a block of it, A and B together are which block counting from zero. Q is zero if it read, and DP3 comes back holding how many of the block's bytes belong to the file. | | osChangeDir | DP0 names a directory. Q is zero if the machine is now in it. What a program changes here, the shell puts back when the program stops. | | osFileStart | DP0 names a file, DP3 is how many whole blocks and A is the bytes left over in the last one. Q is zero if a write is now open. Nothing already on the disk is touched. | | osFileWrite | DP1 is a block, A and B together are which block of the file it is, counting from zero. Q is zero if it was written. An index past the end of the file is refused. | | osFileDone | DP3 is how many whole blocks it came to and A the bytes left over. The old file goes and what was written takes its name, at that size. Q is zero if it was committed. | | osFileFetch | DP1 is where a block should go, A and B together are which block. Reads back a block of the file being written. | | osPrintNumber | A and B together are a number. Prints it in decimal, without leading zeroes. | | osBreak | Stops the program, shows every register as it had them, waits for a key, and carries on. | | osLastStatus | Q answers what the last program exited with: 0 it did what it was asked, 1 it did not, 2 it was asked wrongly. A program may give its own meanings if it says so. | | osBootState | Q answers how the last start went: 0 settled, 1 trying, 2 fell back. A machine with no disk answers settled, because there is nothing there to be unsettled about. | | osBootSettle | Puts it back to settled, which is how a machine that fell back is told the situation has changed. Q is zero if the disk took it. **Settling is the only write a program gets** - marking a start as trying or fallen back is the loader's business, and a service that let a program claim either would let it lie about something the loader cannot check. | ``` #Include services.asm ... SETD.0 Message SWI osPrintString ``` ### Stopping To Look: `SWI osBreak` is a breakpoint. It shows every register as the program had them, waits for a key, and returns as though nothing happened. ``` break at 200E A 11 B 22 Q 00 status 00 DP0 1030 DP1 05EF DP2 039A DP3 2000 SP FFFF press a key ``` Every value comes out of the interrupt frame rather than out of the registers, because by the time the handler runs the registers belong to the handler. The frame is what the program had and what RETI is about to give back, so what is shown is what will be resumed with. The address is two before where it resumes: the `SWI` and the vector it names. **The Stack Pointer is the exception, because it is not in the frame** - the frame is *where* the Stack Pointer is. What the program had is fourteen bytes above the frame, that being what entering an interrupt puts down, so it is worked out rather than read. Breaking inside a subroutine shows it ten lower than breaking outside one, which is the size of a CALL frame and a quick way to see how deep you are. The status byte is shown as a number and then as the bits that are up - `carry`, `fault`, `interrupts` - because a dump that makes you look the number up is only half a dump. **Nothing is overwritten, and that is the whole of why it is simple.** A breakpoint poked into a running program has to replace an instruction, and putting that instruction back in order to continue is the same act as disarming the breakpoint. Firing a second time would mean stepping over the restored instruction and putting the breakpoint back behind it, and this machine has no way to step a single instruction. Two bytes of `SWI` cost a little space and fire for ever, because there was never anything to restore. The price is that a breakpoint is part of the program. A build with breakpoints in it has different addresses from a build without - the same bargain every machine makes that has a break instruction. ### The Disk Without A Filesystem: A program that wants a file does not need to know what a filesystem is. Before these existed it had to include the whole of `sbfs.asm` - two and a half kilobytes of a private copy of code the system already had running - and then mount a disk that was already mounted. There is no service to mount one, and that is not an omission. The system mounts the disk before it reads its first prompt, and there is one disk with one buffer registered as one bank; a program mounting it again was only ever an artefact of owning a second copy of the library. That call disappears rather than moving. Sizes fit the registers exactly, in both directions. A file that can be read into Data Memory is under 64K by definition, so its length is sixteen bits: coming back it is DP3, and going out it is A and B together. Neither direction needs a record in memory whose shape both sides have to agree on. A file of 256 blocks or more is refused by `osFileRead` rather than partly read, because 64K will not fit in Data Memory and its length will not fit in the pointer that reports it. A length that lies would be worse than a file that will not open. ### Reading A File That Will Not Fit: `osFileRead` hands over a whole file, which settles the question for anything under 64K and settles nothing above it. CosmOS's own source is above it: the sources together are a hundred kilobytes and Data Memory is sixty four. A machine that assembles itself has to be able to read a file bigger than its memory, and this is what that stands on. So there is a second way to ask. `osFileInfo` says how big something is and `osFileBlock` hands over one block of it, and between them a program reads a file of any size through a buffer of 256 bytes. ``` SETD.0 Name SWI osFileInfo ; DP3 is how many blocks, Q is zero if it is there. BNQ noSuchFile readLoop: SETD.0 Name SETD.1 Block SETD.2 Index LDA.2 INCD.2 LDB.2 ; Which block, most significant first. SWI osFileBlock BNQ readDone ; Three when there are no more. ... ; DP3 is how many of its bytes are the file's. ``` **There is no open and no close.** Every call names the file and says which block it wants, so nothing is held between them: a program that stops halfway leaves nothing behind, and there is no handle to run out of. The system does remember where the last file it was asked about lives, so reading four hundred blocks searches the directory once rather than four hundred times - but that is a speed and not a promise, and a caller never has to know about it. `osFileInfo` answers in **blocks rather than bytes**, and that is forced rather than chosen. A file on a sixteen megabyte disk can be twenty four bits long and a Data Pointer holds sixteen. Blocks fit; the bytes in the last one come back from `osFileBlock` when the reader gets there. `osFileBlock` answers a count in DP3 rather than in a register for the same kind of reason: every block but a short last one holds a whole **256** bytes, and 256 does not fit in a byte. A count that reported a full block as zero would make every reader treat the end of a file as a special case. **These two say why when the answer is no**, which the other services do not. Everywhere else the only useful thing to do about a failure is to give up, so one value is enough. These exist to be asked questions with, and the difference between the answers is the answer: | Q | Means | | --- | --- | | 0 | it worked | | 1 | there is no disk | | 2 | there is no file of that name | | 3 | that block is past the end of the file | | 4 | the disk would not read it | Running off the end is how a reader finds out it has finished, so it gets an answer of its own rather than being reported as a disk that failed. `Programs/CosmOS/Apps/Stream.asm` reads an 84,000 byte file through a 256 byte buffer, then reads a small file both ways - whole with `osFileRead` and streamed - and checks that the two agree. `Programs/CosmOS/Apps/Files.asm` does the whole round trip - write, read, report, rename, delete - in 675 bytes, and includes nothing but the service names. `osArgument` is how a program is told what it is for. Everything written before it did the same thing however it was started, which is fine for a program that greets you and no use to one that edits a named document. What arrives is the whole rest of the line, spaces and all, rather than a list of words: what counts as an argument is the program's business, and handing over what was typed is the system's. A handler is entered with the caller's registers exactly as they were, because an interrupt frame is pushed rather than cleared. That is why a service can be given a pointer in DP0 and a count in B without any of it being copied anywhere first. ## The Filesystem Library: The disk knows blocks and nothing else, so a filesystem is software. Programs/CosmOS/Source/sbfs.asm is one. | Routine | Does | | --- | --- | | sbfsMount | Registers the disk's buffer as bank 3, reads the superblock, and checks the disk is one of ours. Q is zero if it is. | | sbfsFind | DP0 names a file, ending in a zero byte. Q is zero if it was found, and then SbfsFileStart, SbfsFileBlocks and SbfsFileTail describe it. | | sbfsRead | Reads the file that was found into Data Memory at DP1. Q is zero if it worked. | | sbfsFirst | Starts a walk through the directory. Q is zero if there is an entry, and then SbfsName holds its name and the SbfsFile fields describe it. | | sbfsNext | Steps the walk to the next entry in use. Q is zero if there was one. | | sbfsCreate | Makes a file. DP0 names it, and SbfsFileBlocks with SbfsFileTail say how big it is. Q is zero if it was made, and then SbfsFileStart says where it went. | | sbfsWriteFile | Writes the file that was made, from Data Memory at DP1. | | sbfsDelete | DP0 names a file. Frees its entry and its blocks. Q is zero if it went. | | sbfsRename | DP0 is the name a file has, DP1 the name it should have. Q is zero if it was renamed. Refused if something already answers to the new name. | | sbfsSaveFile | DP0 names the file, DP1 is the data, and SbfsFileBlocks with SbfsFileTail say how big it now is. Writes it whether or not it was there before, and whatever size it used to be. | Finding a file and listing what is there are different jobs. sbfsFind searches for one name; sbfsFirst and sbfsNext walk the whole directory, stopping on each entry that is in use and stepping over the free ones. A walk keeps a directory block in SbfsBuffer between calls, so anything else that goes to the disk in the middle of one ends it: take what is wanted out of an entry before asking the disk for anything else. A file's size is settled when it is made, because nothing can grow one afterwards. Files are laid down contiguously, so the block after a file usually belongs to somebody else. A program that does not know how much it will write has to guess high and accept the slack, or build its output elsewhere and make the file once the size is known. ### Writing A File Too Big To Hold: `osFileSave` is handed a whole document at once, which is what a text editor has. A program that produces its output a piece at a time - an assembler, say - would have to hold all of it first, and the largest thing on this machine would then be limited by memory rather than by the disk. So there is the other half of the streaming pair. `osFileInfo` and `osFileBlock` read a file a block at a time; `osFileStart`, `osFileWrite` and `osFileDone` write one. ```text SETD.0 Name SETD.3 0x00 0x06 ; six whole blocks INIA 0d40 ; and forty bytes after them SWI osFileStart ...for each block: DP1 the bytes, A and B which block... SWI osFileWrite SETD.3 0x00 0x06 ; and what it came to, which need not be INIA 0d40 ; what was asked for SWI osFileDone ``` **One write is open at a time, and the system holds it rather than the program.** Reading needs no state - a name and an index are the whole question - but writing safely does, because the new file has to exist before the old one is thrown away and something has to remember which temporary belongs to which name. Keeping that here means the careful order is written once instead of in every program that streams. **Nothing already on the disk is touched until `osFileDone`.** The room for the whole file is taken at the start, so a disk that cannot hold it says so while the old one is still there. That is stronger than `osFileSave` can manage, where the size is only known once the caller already has every byte in hand. **The size asked for need not be the size it comes to.** Some sizes are not knowable until the last byte is out - the assembler cannot say how many vectors a program installs until it has resolved them, and by then the file it is writing into has to exist. So the room is taken generously at the start, where running out costs nothing, and `osFileDone` is told the truth. The blocks that were asked for and not used go back. `osFileFetch` reads a block of the file back, which is what lets a program keep only one block of it in hand. Anything producing two parts of a file at once - source that says `#Program` and `#Data` in whatever order it likes - has to be able to put a block down, go and write somewhere else, and pick it up again where it left off. Two limits differ between the two. `osFileSave` is handed a byte count in two registers and so cannot write more than 65,535 bytes; `osFileStart` is told blocks and a tail, the way an entry holds a size, and reaches the whole disk. And `osFileWrite` refuses an index past the end of the file - files are contiguous, so block nine of a three block file is a real block belonging to something else, and writing it would put one file's bytes inside another with nothing anywhere saying so. ### Reading Ahead: A file is read front to back, so when a program asks for a block, the one after it is almost certainly wanted next. `sbfsReadOne` asks the disk for it straight away and hands the caller the block it wanted - so the transfer happens while the program is busy with what it already has, and the wait is mostly gone by the time it comes back. Nothing is done differently and nothing is done out of order. The machine simply stops standing still. **It is not done for directory searches, and that is not an oversight.** A scan stops the moment it matches, so the next block is one nobody will ever look at: it costs a transfer to fetch and another wait to throw away. Tried there, it was nineteen per cent *slower*. Read ahead is a bet that the next block is wanted, and a search is exactly the case that hopes it is not. What it is worth, printing a fourteen kilobyte file: | Cycles a block | Without | With | | -- | -- | -- | | 0 | 936,626 | 962,959 | | 2,000 | 1,064,498 | 976,882 | | 10,000 | 1,576,562 | 1,032,889 | The second column barely moves. From an instant disk to a slow one the cost rises seven per cent, where without it the same change costs sixty eight - which is the point: **a machine that reads ahead stops caring very much how fast its disk is.** The three per cent it costs at zero is the bookkeeping, paid when there is nothing to hide behind it. ### And Waiting For What Is Left: Read ahead hides most of the wait and cannot hide all of it. What remained was a loop asking the disk's status port over and over, which is work the machine is doing and memory it is touching to find out that nothing has happened yet. `sbfsWaitDisk` uses `WAIT` now. It tests the status port, and only if the disk is still busy does it stop - the CPU is put down until a device raises a line, and the disk raises one when it finishes. **Asking first is what makes it safe:** if the disk finished in the gap between the test and the `WAIT`, its line is already standing and the `WAIT` does nothing rather than sleeping through the answer. There is no handler and no vector. The shell keeps the Interrupt Flag down, and a `WAIT` wakes on a line whether or not anybody intends to answer it, taking it down on the way past. Printing the same fourteen kilobyte file: | Cycles a block | Total | Of that, the bus | Waiting | | -- | -- | -- | -- | | 0 | 922,570 | 922,570 | 0 | | 2,000 | 946,474 | 922,702 | 23,772 | | 10,000 | 1,042,474 | 922,702 | 119,772 | **The middle column stops moving.** What the program costs in memory is now the same whatever the disk does, and the difference is time spent with the bus quiet. On this emulator that changes nothing anybody can see; on hardware it is the difference between a CPU contending for memory with everything else and a CPU standing out of the way. ### Saving Something Twice: Which is why saving a document is not the same as writing a file, and why sbfsSaveFile exists rather than each tool doing it. A file that has grown will usually not fit where it was, so saving it means putting it somewhere else and letting go of where it was - and **the obvious order is a trap**: ``` delete the old one make a new one <- refused, and the old one is already gone write it ``` A create can be refused for want of a run long enough even on a disk with plenty of free blocks, because free blocks are only useful to a contiguous file when they are next to each other. Done in that order, the first fragmented disk somebody meets eats their work. sbfsSaveFile does it the other way round: ``` make a temporary nothing is lost if there is nowhere to put it write it delete the original only now, once the new one is safely down rename the temporary ``` **That is what renaming is for.** It looks like a convenience and it is the safety mechanism: it is the only one of the three operations that moves no data - a name lives in the directory entry, so renaming writes twenty two bytes into one block - which makes it the only one that can be left until last and relied on not to fail. #### Exactly what that promises: The ordering protects the original against **every way a save can fail while it is running**, and it is worth naming those, because they are the ones that actually happen: there is no run of free blocks long enough, or none at all; the disk refuses a block write; the name turns out to belong to a directory; the writer gives up part way through. In all of them the file that was already there is untouched, and what is lost is the temporary, which nothing had come to depend on yet. It is **not** power-loss atomic, and nothing about SBFS claims it is. The commit is two block writes - delete the old entry, then give the temporary its name - and a machine that stops between them leaves the old file gone and the new one under the temporary's name. Both writes are to the directory, so `sbfs.part` or `sbfs.out` is sitting there holding every byte of the work; the data survives and the name does not, and putting it right is one `rename` typed by hand. `dir` marks it `` so that it can be found, which is the whole of the recovery this format offers. Closing that window means a journal or a second copy of the directory, and both are a great deal of machinery to buy back a two-write gap on a machine with no power failures to speak of. The honest description is the one to write down: **safe against the failures of ordinary operation, not against the machine stopping.** #### What tells a temporary from a file: While the save runs the temporary is an ordinary entry in every way that matters - it holds real blocks and answers to a name - and the only thing that makes it different is that nobody has committed it yet. That is **not a property of its contents.** The same bytes become the finished file the instant the rename lands, so there is nothing to put inside it that would be true. It belongs in the entry, which is the thing the commit changes, and it is **flag bit `0x04`**. It used to be told apart by being *called* `sbfs.part` or `sbfs.out`, and those are names anybody is entitled to give a file of their own. Starting a save deleted whatever answered to one, as stale scratch - so saving anything at all in a directory destroyed your file of that name there, silently, and the first you would know of it is going to look for it. A file that does not carry the flag now belongs to somebody, and the save is **refused** rather than helping itself to the name. The same bit is what makes an interrupted save recoverable. Both listings show an unfinished write rather than sizing it, because the size in the entry is the room it asked for and not what was written into it: ``` > dir stranded.txt ``` Rename it to keep the data, delete it to give the blocks back. Nothing reclaims it on its own; a boot-time consistency check could, and this is the field it would read. **A committed file never carries the bit**, so a disk this writes is byte for byte the disk the older code wrote - the agreement tests compare whole images and say so. Only the wreckage of a save that stopped looks different, and code that has never heard of the flag reads that as an ordinary file, which is exactly what it did before. Finding room is a walk through the directory rather than a lookup, because there is no allocation table. With files laid down contiguously the directory already says which blocks are spoken for, and a second copy of that would be a second thing to keep right. The free count in the superblock is kept up to date but it is a note rather than the truth: it can be worked out again from the directory, and the directory is the one to believe. A file's length is its block count times 256 plus its tail, which is the same as putting the block count in the high byte and the tail in the low one. Nothing pads a file out, so the bytes after the end of one are whatever else happened to be in that block, and it is the reading program's business to stop where the tail says. The other implementation of this format is SplitDisk, on the host. Nothing is shared between the two but the specification, so a change to either has to be a change to both. ### What A Program Made Of It: `SWI osExit` takes a status **in A**: zero if the program did what it was asked, one if it did not, two if it was asked wrongly. A program may give its own meanings if it says so, and `Compare` does - one there means the files differ, which is a result rather than a failure. **In A rather than Q**, which is not a departure from the rule that a service answers in Q. This one *takes an argument*, the way `osPrintNumber` takes A and B, and it never returns to answer anything. A is free precisely because a return would have put it back - and Q is the ALU's output, so setting it to a small number costs four instructions where A costs one. **The shell keeps the number and does not print it.** A program that failed has already said so in words, and a number beside that would be noise. `osLastStatus` hands it back and `Status` is the program that shows it. The indirection is the point: this number is for the thing that cannot read words - whatever comes to run programs in sequence and has to decide whether to run the next one. Marking all fifty eight exits found a defect on its first run. `Type` and `More` printed why they had failed and then **fell through into the success exit**, reporting that all was well. Nobody had noticed, because while the only reader was a person, the person could see both. ### How A Service Answers: A handler arrives with the caller's registers pushed rather than cleared, and **`RETI` restores every one of them** - which is what makes an interrupt safe to arrive at an arbitrary moment, since the interrupted code cannot tell it happened. A service is not arbitrary. It was asked for, and it has something to say. It says it with `SRET`, which is `RET` adapted to an interrupt frame: **A, B and Data Pointers 0 through 2 come back, the saved Q and Data Pointer 3 are dropped, and the Interrupt Flag is put back from the frame.** So a service answers in exactly the registers a subroutine answers in, and there is one rule on this machine rather than two. Before it existed, a handler with an answer wrote into its own frame: ```asm MVSD.2 DPUP.2 0d02 ; the saved Q, by an offset it had to know STA.2 RETI ``` Thirty places did that, each knowing the frame's layout by heart, and all thirty would have gone quietly wrong the day the frame gained a field. None of them knows it now. `RETI` is still right for a **hardware** handler, which has nothing to say and must leave no trace. The two returns are not a choice of style: one says *I was never here* and the other says *here is your answer*. ### What A Subroutine Can And Cannot Hand Back: This is the thing that catches people, including whoever wrote the last three pieces of system code, so it is worth stating once and plainly. CALL saves **A, B, and Data Pointers 0, 1 and 2**, and RET puts all five back. So a subroutine cannot return anything in any of them: whatever it puts there is undone by its own return, silently, and the caller carries on with its old values as though the subroutine had never run. What comes back is **Q**, which is one byte, and **Data Pointer 3**, which is two. That is the whole of it, and it is why DP3 is not preserved. The same rule catches a loop that steps a pointer inside a subroutine. The step is thrown away every time round, so the loop reads the same byte forever and the fault is a wrong answer rather than a crash. If two bytes have to come back and DP3 is spoken for, the honest answers are to write them into Data Memory, or to do the work in the caller rather than in a routine. A short sequence written out twice is better than a subroutine that quietly does nothing. The same rule cuts the other way, which is easier to miss. Because DP3 is not put back, **a routine you call may leave something of its own in it**. It is where a routine hands a pointer out, so it is not a safe place to leave one of your own across a call to anything that might use it. The Stack is: push it before the call and pop it after, and it will be exactly as it was. A label may only be defined once across a program and everything it includes, so a routine in one library cannot use a name that another has already taken. ## The Console Library: Programs/CosmOS/Source/console.asm is the console library. It replaces print.asm, which was written for a machine with one Data Pointer and no vector table, and which is still there because the programs that include it still work. | Routine | Does | | --- | --- | | newLine | Prints a line feed. | | printString | DP0 names a string ending in a zero byte. Prints it. | | printSpaces | A holds how many spaces to print. None is a fair answer, and prints nothing. | | printByteHex | A holds a byte. Prints it as two hexadecimal digits. | | printWordHex | DP0 names two bytes, most significant first. Prints them as four hexadecimal digits. | | printHexDigit | A holds a nybble. Prints the one character that stands for it. | | printDecimalDigit | A holds a digit from zero to nine. Prints it. | | printByteDecimal | A holds a byte. Prints it in decimal, without leading zeroes. | | printWordDecimal | DP0 names two bytes, most significant first. Prints them in decimal, without leading zeroes. | | readLine | DP0 names a buffer and B says how many characters it holds. Reads a line into it. Q is how long the line turned out to be. | Two things about it are different from the old library, and both are deliberate. There is no branch at the top. print.asm begins with a BRI to a label called start, so that a program including it arrives at its own entry point rather than falling into the library. That was the only way to do it before the Vector Table existed, and it is why print.asm cannot be assembled on its own: the label it branches to is one only the including program defines. A program including console.asm says where it begins in its own Vector Segment instead, with a Boot line, and the library assembles by itself. Every routine names the Data Pointer it works through rather than assuming there is only one. A pointer handed in is DP0, and nothing in the library disturbs DP3. readLine cuts a line short if it is longer than the buffer, and then reads the rest of it and throws it away, so that what is left over does not turn up as the next line. ConsoleEndOfInput is set if the console ran out instead of ending a line, and it is cleared at the start of every call, so it always describes the last line read. That is a different thing from an empty line, and a program reading until there is no more has to be able to tell the two apart. ## Source Layout: - `Source/cosmos.asm`: Boot process, shell, loader, monitor, system services, and application lifecycle. - `Source/console.asm`: Console input, strings, hexadecimal and decimal output, and line handling. - `Source/text.asm`: String comparison, splitting, and hexadecimal text conversion used by the shell. - `Source/sbfs.asm`: Target-side implementation of the SplitBit filesystem. - `Source/services.asm`: The shared names and stable vector numbers used by CosmOS and separately assembled applications. - `Apps/`: Loadable programs packaged onto the CosmOS disk image. ## Tests: CosmOS is exercised as part of the SplitBit repository's normal test suite: ```sh make test ``` The tests boot the system with and without a disk and drive the shell through recorded console input. They cover directory traversal, every loader refusal, repeated application runs, memory inspection, vector installation and restoration, command arguments, filesystem deletion and renaming, interactive applications, and editing a file followed by reading the saved result back in a second editor session. Individual CosmOS tests can be run from the repository root, for example: ```sh ./Tests/run.sh cosmos cosmosRun cosmosEdit ``` Test disks are constructed with the host-side `SplitDisk` tool. CosmOS is therefore reading filesystems written by an independent implementation of the same format rather than merely checking its filesystem code against itself. ## Current Scope: CosmOS is early software for an experimental computer. It runs one application at a time, has no privilege levels or process isolation, does not relocate applications, and has no linker. Its purpose is to make SplitBit usable from inside the machine: inspect it, manage persistent files, load programs, provide common services, and return reliably to a command prompt. **Self-hosting is done.** `Assembler/` reads source off a SplitBit disk and writes a boot image or a loadable program back to it, byte for byte what the host assembler builds from the same source. It assembles CosmOS, and it assembles itself, and the CosmOS it built assembles CosmOS again to the same bytes. What is left of that milestone is a linker, and editing source under CosmOS comfortably enough to want to: `Edit` is line oriented and knows nothing about assembly. ## Additional Information: The SplitBit Programming Manual describes the machine underneath: the CPU, the vector table and interrupt model, devices, the memory controller, the console, and storage as a block device. The SplitBit Assembler Manual documents the assembly language, the segment bases and vector declarations, and the SBEX loadable program format. What a program may ask CosmOS for is documented here rather than in either of those, because the services are this system's and not the machine's. ## License: CosmOS is part of the SplitBit Emulator project and is licensed under the Apache License, Version 2.0. See the repository's top-level `LICENSE` file for the full license text.