Writing user programs for atlOS (user/)¶
Source: user/
User programs are small C++17 programs that atlOS loads from its disk and
runs in ring 3, in an address space of their own: they can not touch the
kernel, and when they crash, only they end. A program can run several
threads. This directory has everything needed to
write one; how the kernel side works is in kernel/proc/README.md.
atlOS:/> run /disk0/BIN/COUNT.ELF
1 2 3 4 5
[pid 1 COUNT.ELF exited with 15]
atlOS:/>
What is here¶
user/
CMakeLists.txt builds every program: atlos_user_program(name)
user.ld linker script: where code, data and the entry point go
lib/crt0.S _start: hands the start stack to atlos_start
lib/start.cpp atlos_start: reads the auxv, sets up the heap, runs the global
constructors and main(), ends the process
lib/malloc.cpp malloc, calloc, realloc, free, new, delete (the heap in common/heap/)
lib/thread.cpp User::Threading::Thread and the trampoline new threads start in
lib/string.cpp memcpy, memmove, memset, memcmp (the compiler may call them)
lib/atlos.hpp the system calls, the heap, threads and a few helpers
programs/ the programs, one .cpp file each
hello.cpp prints, exits with 0
count.cpp the example below
fault.cpp writes to address 0: ends with a page fault
badptr.cpp hands the kernel pointers it must refuse
break.cpp stops at a breakpoint, then goes on
ask.cpp reads a line from the keyboard (read, echo, Backspace)
clock.cpp uptime, sleep and yield
files.cpp open, read, write, close and their errors
args.cpp prints argc and argv, and where they are
cat.cpp prints the files named in its arguments
malloc.cpp the heap: a linked list, the largest block that fits
threads.cpp threads: a shared counter, exit codes, ids, stacks
threxit.cpp how a program with several threads ends
overflow.cpp a thread runs off its stack into the guard page
Arguments¶
int main(int argc, char** argv)
{
for (int i = 1; i < argc; i++) { // argv[0] is the program itself
print(argv[i]);
print("\n");
}
return 0;
}
atlOS:/> run /disk0/BIN/ARGS.ELF one "two words"
argc = 3
argv[0] = "/disk0/BIN/ARGS.ELF" at 0x00007fffffffffce
argv[1] = "one" at 0x00007fffffffffe2
argv[2] = "two words" at 0x00007fffffffffe6
argv[argc] = NULL
[pid 1 ARGS.ELF exited with 3]
The shell does not resolve paths in the arguments, and a program has no
current directory: pass paths from the root (run /disk0/BIN/CAT.ELF
/disk0/HELLO.TXT). How the kernel puts the arguments on the stack:
kernel/proc/README.md.
The environment¶
What a program can count on, and what it can not (yet):
| Language | C++17, freestanding (-ffreestanding -nostdlib, no exceptions, no RTTI), built with the kernel's cross compiler x86_64-elf-g++ |
| Library | no libc, no C++ library: no printf, no std::. atlos.hpp has the system calls, malloc/new, threads, print, printNumber, printHex, strlen |
| Names | the file and console calls keep their standard C names (read, write, open, close, malloc, free, strlen); what is atlOS's own is in namespace User, with the kernel's names (User::Threading::Thread, User::Process::exitProcess). Programs say using namespace User; |
| Start | _start (crt0) runs the global constructors, then int main(int argc, char** argv) (or int main()); its return value becomes the exit code. No environment variables. Global destructors do not run |
| Arguments | run /disk0/BIN/P.ELF a "b c": argv[0] the program's path, then the words; argv[argc] is NULL. Up to 16, 1024 bytes in all |
| Registers at start | all zero; rsp 16 byte aligned, pointing at argc (the System V start stack) |
| Floating point | none: the kernel does not save SSE state, programs are built with -mno-sse; using float/double fails to compile (SSE register return with SSE disabled) |
| Input | read(STDIN, ...): the keys, raw (see below) |
| Files | open, read, write, close; paths from the root (/disk0/NOTE.TXT), 8.3 names, up to 8 open at once |
| Time | uptime() (milliseconds since boot), Threading::sleep(ms), Threading::yield() |
| Threads | Threading::Thread: as many as memory allows, each with its own 2 MB stack (see below) |
| Several programs | up to 64 at once, each in its own address space at the same addresses |
Memory¶
Every program gets the same layout (2 MB pages, see user.ld):
| Address | What | Access |
|---|---|---|
0x0000008000000000 |
code (.text, .rodata), starting right after the ELF headers |
read, execute |
| next 2 MB page | data (.data, .bss) |
read, write |
| next page | the heap: 2 MB, or what run -heap MB asks (0 .. 64) |
read, write |
0x00007FFFFFE00000 .. 0x00007FFFFFFFFFF0 |
the main thread's stack: one 2 MB page; at its top the argument strings and argv[], rsp starts just below |
read, write |
0x00007FFFFFC00000 |
guard: not mapped | none |
0x00007FFFFFA00000, then every 4 MB lower |
the other threads' stacks, each 2 MB with a 2 MB guard below it | read, write |
Every page is zeroed before the program starts, so .bss and unused stack
are 0. A stack that runs off its bottom hits the guard below it: a page
fault, and the kernel says which thread's stack overflowed.
The heap¶
malloc, calloc, realloc and free work as in C, on the heap the
kernel mapped behind the data. The size is fixed when the program starts:
when it is full, malloc returns NULL. Every block is 16 byte aligned and
has a 16 byte header, and so has each run of pages, so a heap of n MB never
fits a block of n MB. free of a pointer malloc did not return, or a
second free, ends the program with exit code 134.
auto* node = static_cast<Node*>(malloc(sizeof(Node)));
if (!node)
return 1; // the heap is full: malloc says so
...
free(node);
Node* other = new Node; // new: a full heap ends the program (exit code 134)
delete other;
atlOS:/> run -heap 8 /disk0/BIN/MALLOC.ELF 100000
heap: 8192 KB at 0x0000008000400000
list of 100000 numbers, sum 5000050000
with the list: 1600016 bytes in use
after free: 0 bytes in use
largest block: 7 MB
[pid 1 MALLOC.ELF exited with 0]
heapInfo(&base, &size, &inUse) says where the heap is, how large, and how
much is in use. All threads of a program share the one heap. It has no lock
and needs none: malloc never calls the kernel, so with a cooperative
scheduler no other thread runs in the middle of it. The
heap is the kernel's own allocator, built into the program; how it works is
in common/heap/README.md.
Everything else faults: the kernel half, and the first megabytes (identity
mapped for the kernel only), so dereferencing NULL is a page fault, as it
should be.
Cooperative scheduling: give the CPU back¶
atlOS has no preemption. A thread keeps the CPU until it ends, or until it
calls Threading::yield, Threading::sleep, waits for another thread, or
does a read that has to wait for a key; the other system calls return to
it right away. A thread that loops forever without one of those freezes
the whole machine, the shell included. Keep programs short, and make sure
their threads end or wait. The same rule is why threads of one program need
no locks between them: another thread only runs where this one calls one of
those.
run waits until the program exits, then the shell prompts again.
Threads¶
A program starts with one thread, the main thread, which runs main.
More threads run in the same program: they share its memory, its heap and
its open files, and each has its own stack. User::Threading::Thread is
the same class, with the same names, as the kernel's Threading::Thread:
#include "atlos.hpp"
using namespace User;
static int s_counter; // shared: every thread sees the same variable
// The thread's code: arg is what it was started with, the return value its exit code
static int64_t worker(void* arg)
{
int64_t rounds = reinterpret_cast<int64_t>(arg);
for (int64_t i = 0; i < rounds; i++) {
s_counter++;
Threading::yield(); // let the others run
}
return rounds * 10;
}
int main()
{
Threading::Thread a(worker, reinterpret_cast<void*>(3)); // starts at once
Threading::Thread b(worker, reinterpret_cast<void*>(5));
int64_t codeA = a.wait(); // 30, once a has returned
int64_t codeB = b.wait(); // 50
printNumber(s_counter); // 8
return 0;
} // ~Thread waits for a thread nobody has waited for
Threading::Thread t(entry, arg) |
starts entry(arg) in a new thread; t.id() is 0 if it could not start (no memory) |
t.wait() |
sleeps until the thread has ended, then its exit code (again: the same code at once) |
~Thread() |
waits for the thread if nobody has; there is no detach |
Threading::exitThread(code) |
ends the calling thread; returning from entry does the same |
Threading::currentThread() |
the calling thread's id |
Process::exitProcess(code) |
ends the program, every thread of it |
Process::currentProcess() |
the program's process id |
Thread ids are 64 bits: the process id in the upper half, the thread's
number below. The main thread is number 0, the others count up from 1 and
numbers are not reused while the program runs:
Abi::makeThreadId(pid, number), Abi::processOf(tid),
Abi::numberOf(tid). The shell's tasks shows them as pid.number.
How a program ends. When the main thread ends (main returns, or it
calls exitThread), the whole program ends with its code, even if other
threads still run. exitProcess from any thread and a fault in any thread
end it too. The other threads stop the next time they call the kernel (a
sleeping one is woken for it); one waiting for a key stops at the next key.
THREXIT.ELF shows both ways:
atlOS:/> run /disk0/BIN/THREXIT.ELF main
threxit: main returns, two threads still running
[pid 1 THREXIT.ELF exited with 3]
Stacks. Each thread's stack is a 2 MB page with an unmapped guard page below it. Endless recursion faults instead of overwriting another stack:
atlOS:/> run /disk0/BIN/OVERFLOW.ELF
overflow: a thread recurses without end
==== EXCEPTION 14: Page fault (in user mode) ====
...
(stack overflow: thread 1 of pid 1 ran into its guard page)
[pid 1 OVERFLOW.ELF exited with 142]
A program can not start or wait for another program; only the shell does
(run). How the kernel does all this: kernel/proc/README.md.
System calls¶
int $0x80, the call number in rax, arguments in rdi, rsi, rdx, the
result in rax; a negative result is an error. The numbers are in
common/abi/abi.hpp, the same header the kernel
uses; atlos.hpp wraps them:
| rax | Call | Wrapper | Result |
|---|---|---|---|
| 0 | exitProcess | Process::exitProcess(code) |
does not return |
| 1 | write | write(fd, buffer, size) |
bytes written; -EBADF (not open for writing), -EINVAL above 4096 bytes, -EFAULT if the buffer is not the program's own memory |
| 2 | read | read(fd, buffer, size) |
bytes read, 0 at the end of a file; the same errors |
| 3 | open | open(path, flags) |
a file descriptor, 3 and up; -ENOENT, -EISDIR, -EMFILE (8 open already), -EFAULT |
| 4 | close | close(fd) |
0, or -EBADF |
| 5 | yield | Threading::yield() |
the other threads run first |
| 6 | sleep | Threading::sleep(ms) |
at least ms milliseconds later |
| 7 | currentProcess | Process::currentProcess() |
the process id (the shell's [pid 3 ...]) |
| 8 | uptime | uptime() |
milliseconds since boot |
| 9 | startThread | Threading::Thread(entry, arg) |
the thread's id; -ENOMEM |
| 10 | exitThread | Threading::exitThread(code) |
does not return |
| 11 | waitThread | Thread::wait() |
the thread's exit code; -ESRCH (not a thread of this program), -EDEADLK (itself), -EINVAL (the main thread, or already waited for) |
| 12 | currentThread | Threading::currentThread() |
the calling thread's id |
| other | systemCall(n, a, b, c) |
-ENOSYS |
The errors are the Linux numbers, negated: if (fd == -ENOENT). File
descriptors 0, 1 and 2 are STDIN, STDOUT and STDERR. open takes one
of O_RDONLY, O_WRONLY, O_RDWR, and any of O_CREAT (create the file),
O_TRUNC (empty it), O_APPEND (write at the end):
long fd = open("/disk0/NOTE.TXT", O_WRONLY | O_CREAT | O_TRUNC);
write(fd, "hello\n", 6);
close(fd);
Reading the keyboard¶
read(STDIN, buffer, size) waits for a key, then returns it and the keys
typed after it, at least one. Nothing is echoed and there is no line
editing: the program sees every key as it comes and prints what it wants
(ask.cpp echoes the keys and handles Backspace). Enter arrives as '\n',
Backspace as 0x7f (a terminal) or '\b'. Ctrl+C ends the program
with exit code 130.
print(text) is write(STDOUT, text, strlen(text)), printNumber(n)
prints a number in decimal, printHex(n) in hex. breakpoint() executes
int3: the kernel prints the program's registers and the program goes on
(BREAK.ELF).
The kernel checks every pointer it is given: the buffer of write must lie
in the program's own mapped pages. Passing a kernel address does not leak
kernel memory, it returns -EFAULT (badptr.cpp tries several such pointers).
Exit codes¶
The shell shows how a program ended: [pid 2 FAULT.ELF exited with 142].
| Exit code | Meaning |
|---|---|
what main returned, or the argument of exitProcess (or of the main thread's exitThread) |
normal end |
| 128 + exception vector | the program faulted and the kernel ended it |
| 130 | Ctrl+C while the program read the keyboard |
| 134 | free of a pointer malloc did not return, new on a full heap, a pure virtual call |
| 128 (#DE) | division by zero |
| 134 (#UD) | invalid instruction |
| 141 (#GP) | general protection: a privileged instruction (cli, hlt, in/out, mov cr3), int with another vector than 0x80, a non canonical address |
| 142 (#PF) | page fault: NULL, kernel memory, writing to code, beyond the stack (a thread's guard page) |
Your first program¶
- Write
programs/count.cpp:
#include "atlos.hpp"
using namespace User;
static long s_sum; // .bss: starts at 0
// No printf: turn a number into text by hand
static void printDecimal(long value)
{
char text[24];
int length = 0;
do {
text[length++] = static_cast<char>('0' + value % 10);
value /= 10;
} while (value);
char reversed[24];
for (int i = 0; i < length; i++)
reversed[i] = text[length - 1 - i];
write(1, reversed, length);
}
int main()
{
for (long i = 1; i <= 5; i++) {
printDecimal(i);
print(i < 5 ? " " : "\n");
s_sum += i;
}
return s_sum; // 15: shown as "exited with 15"
}
- Add it to
CMakeLists.txt(both lines):
atlos_user_program(count)
set(ATLOS_USER_TARGETS hello fault badptr count break ask clock files args cat malloc threads threxit overflow PARENT_SCOPE)
The target name becomes the file name on the disk, in upper case:
count → /BIN/COUNT.ELF. FAT16 names are 8.3, so keep it to 8
characters.
- Build the kernel, the programs and the test disk, and boot it:
scripts/build.sh all
cmake --build --preset default --target disk-image # build/default/disk.img
scripts/build.sh run # QEMU, the shell on this terminal
scripts/build.sh run attaches the disk. The program itself is
build/default/user/count.elf.
- Run it in the shell:
atlOS:/> ls /disk0/BIN
HELLO.ELF ...
FAULT.ELF ...
BADPTR.ELF ...
COUNT.ELF ...
atlOS:/> run /disk0/BIN/COUNT.ELF
When it crashes¶
A fault in a program prints the CPU's report, then ends the program:
==== EXCEPTION 14: Page fault (in user mode) ====
error code 0x7
CR2=0x0000000000000000 (user write, protection violation)
...
RIP=0x00000080000000c4 CS=0x001b RFLAGS=0x0000000000000246
[pid 2 FAULT.ELF exited with 142]
CR2is the address the program touched (page faults only), and the decoded error code says how: a user write, to a page that is mapped but not the program's (protection violation) or to no page at all (page not present).RIPis the instruction. Turn it into a source line with the program's ELF file (programs are built with-g), feeding it the serial log or the pasted report:
scripts/symbolize.sh build/default/user/fault.elf build/default/shelltest.log
RIP 0x00000080000000c4 main at user/programs/fault.cpp:14
or by hand: x86_64-elf-addr2line -f -e build/default/user/fault.elf 0x80000000c4.
- To see the instructions: x86_64-elf-objdump -d build/default/user/fault.elf.
- To see the segments the kernel loads: x86_64-elf-readelf -l build/default/user/fault.elf.
A program that the kernel refuses to load says why, for example
... two segments share a 2 MB page (link with -z max-page-size=0x200000)
or ... a segment is outside the user address range.
Rules for the build¶
Keep these when changing CMakeLists.txt or user.ld; the loader
(kernel/proc/elf.cpp) refuses files that break them:
- static ELF64 executables (
-static -nostdlib, no PIE), for x86_64; - every loaded segment inside
0x0000008000000000..0x0000800000000000; - code and data in different 2 MB pages: protection is per page. The
linker script starts data on the next page, and
-z max-page-size=0x200000keeps the file small (the offsets inside the file match the addresses modulo 2 MB); - no SSE (
-mno-sse -mno-sse2 -mno-mmx),-mcmodel=large(the code is far above 2 GB); - no libc: what a program needs comes from
lib/, in C++ without exceptions and RTTI. The global constructors go to.ctors(this cross compiler) or.init_array;user.ldcollects both between__init_array_startand__init_array_end, andatlos_startcalls them after setting up the heap (a constructor may usenew).
Testing a program¶
- The shell test (
scripts/build.sh shelltest,scripts/run-shelltest.py) boots the kernel, typesrun /disk0/BIN/...and checks the output; add a step there for a program whose output matters. - The self tests (
kernel/tests/selftest.cpp, User programs) run programs from the test disk withrunProgram(runtime, scheduler, path)and check exit codes and output; they also check that every page comes back.
References¶
kernel/proc/README.md: loading, ring 3, system calls, processes and threads, from the kernel's side- System V ABI, x86-64 supplement: calling convention, process start
- OSDev Wiki: ELF, System Calls