The kernel shell (kernel/shell/)¶
Source: kernel/shell/
A command line inside the kernel: type ls /disk0, md 0xb8000 64 or
tasks on the keyboard or a serial terminal, and the kernel answers. It runs
in the boot flow (task 0) once everything is set up. When it starts it clears
the screen (the serial log keeps the boot messages) and prints the banner,
the version, the free memory and the mounted disks. Every line it prints fits
80 columns, the VGA screen's width.
atlOS:/disk0> help
general help clear echo version uptime
files pwd cd ls cat touch mkdir rm rmdir mount
memory mem md mw vmmap pt
...
atlOS:/disk0> help md
md addr [len] memory dump (hex and text), len up to 4096
What is it for?¶
A shell turns text into actions: it reads a line, splits it into words, finds
the command named by the first word and runs it with the rest. In a normal OS
it is a user program that starts other programs (fork + exec in Unix).
atlOS has no user mode yet, so its shell is part of the kernel and its
commands are kernel functions. That makes it a tool for looking inside the
running kernel: memory, page tables, tasks, files.
How could it be designed?¶
| Question | Options |
|---|---|
| Where does it run? | in the kernel (debug consoles, early OSes, many embedded systems) · a user program (sh, bash, cmd.exe) |
| How are commands found? | a table of (name, function) · a class per command behind an interface · programs on disk (/bin/ls) |
| Line editing | none (the terminal's cooked mode does it) · backspace + history · full editing (readline: cursor movement, completion) |
| Input | one queue fed by every input device · one shell per device |
How atlOS does it¶
keyboard IRQ ─┐ ┌─> VGA text screen
├─> CharacterQueue ─> LineEditor ─> Interpreter ─> printf ─> TeeSink
COM1 IRQ ──┘ (semaphore) (echo, history) (commands) └─> COM1
- Input (
drivers/character_queue.hpp): the keyboard and the serial port's IRQ handlers push into oneCharacterQueue; its semaphore lets the shell sleep inread()until a key arrives (seekernel/sync/README.md). The keyboard driver turns the arrow keys into the ANSI sequences a serial terminal sends (ESC [ Afor up), so both inputs look the same. - Output:
printfgoes to the console; with a COM1 present the console is aTeeSinkthat writes to the screen and the serial port. The serial port turns"\n"into"\r\n", what terminals expect. LineEditor(line_editor.cpp): echoes printable characters, handles Backspace (\bor DEL 0x7F), Enter (\r,\n, or\r\nas one), Ctrl+C (drop the line) and Up/Down (a 16 line history). Erasing on screen is "back, space, back" (\b \b), which works on the VGA console and on terminals alike.splitWords(parser.cpp): words are separated by spaces or tabs,"double quotes"keep spaces; changes the line in place, no allocation.parseNumberreads0x...hex or decimal.Interpreter(interpreter.cpp): the prompt loop, the current directory (resolvePathmakes paths absolute and resolves.and..), and the dispatch through the command table.- Commands (
commands.cpp): one function per command,void(Interpreter&, int argc, char** argv), listed in one table with its group;helpprints one line per group,help groupandhelp commandthe usage. What the commands work on (PMM, address space, scheduler, VFS) comes in aContextfromkernelMain; no globals.
The commands¶
| Group | Commands |
|---|---|
| general | help, clear, echo [words] [> \| >> file], version, uptime |
| files | pwd, cd, ls, cat, touch, mkdir, rm, rmdir, mount |
| memory | mem, md addr [len], mw addr value [1\|2\|4\|8], vmmap, pt addr |
| tasks | tasks, ps, sched, top [ms], run [-heap MB] program.elf [args] |
| cpu | cpuinfo, cr, rdmsr msr, wrmsr msr value, gdt, idt [vector] |
| devices | in port [b\|w\|l], out port value [b\|w\|l], irq, disk [read lba [count] [device]], lspci [bus:dev.fn], acpi [SIGNATURE], apic, smbios [type], int vector |
| system | panic [message], fault, reboot |
Looking at memory safely¶
md and mw take any virtual address. Reading an unmapped one would page
fault and halt the kernel, so they first ask the page tables
(AddressSpace::translate, one check per 4 KB page) and refuse with
not mapped:
atlOS:/> md 0x7000 32
0000000000007000 41 00 00 00 00 00 00 00 88 77 66 55 44 33 22 11 |A........wfUD3".|
atlOS:/> md 0xdead0000
0x00000000dead0000: not mapped
translate differs from virtToPhys in one way: "not mapped" is not
confused with "mapped at physical 0" (the first megabytes are identity
mapped). Physical memory itself can be looked at through the physmap:
md 0xffff800000007000 shows physical address 0x7000.
vmmap walks the active tables (AddressSpace::forEachMapping) and joins
neighbouring pages with the same flags into one line:
virtual physical size access pages
0000000000000000-0000000000e00000 0000000000 14 MB rw kernel 7x2M identity map of boot
ffff800000000000-ffff801000000000 0000000000 64 GB rw kernel 32768x2M the physmap
ffffffff80000000-ffffffff80e00000 0000000000 14 MB rw kernel 7x2M the higher half kernel
mw writes 1, 2, 4 or 8 bytes. It is a sharp tool: writing over kernel data
or page tables breaks the kernel. 0x7000 (low memory the PMM never hands
out) or 0xb8000 (the VGA text buffer: a character appears top left) are
harmless places to try.
tasks lists the scheduler's threads: the thread id as pid.number (0.x
are kernel threads, process 0), name, state, time left for sleepers, the
stack, and rsp (for the running task: the current frame). ps lists the
processes: process 0 (the kernel) and the programs, with how many threads
have not ended, their user stack pages, open files and whether they are
running or dying. sched shows each thread's CPU time since boot, top
[ms] over the next ms milliseconds (see CPU time in
kernel/sched/README.md).
atlOS:/> tasks
tid name state wakes in stack rsp
*0.0 kernel running - boot stack 0000000000412da0
0.1 idle ready - ffffffff81400000 ffffffff815fff20
2 task(s), * = running (this shell); tid = pid.number
atlOS:/> ps
pid name threads stacks files state
0 kernel 2 - - running
threads: not yet ended; stacks: 2 MB user stack pages (one per thread not yet waited for)
Looking at the hardware¶
The shell runs in ring 0 and can reach everything the CPU has:
atlOS:/> cr
cr0 0x0000000080000011 PE ET PG
cr3 0x0000000000408000 the PML4 (physical)
cr4 0x0000000000000030 PSE PAE
efer 0x0000000000000500 LME LMA
atlOS:/> pt 0xffffffff80400000
PML4[511] = 0x000000000040a023 P W A
PDPT[510] = 0x000000000040b023 P W A
PD[2] = 0x00000000004000a3 P W A PS
2 MB page, physical 0x400000
atlOS:/> irq
vec count what
36 14 IRQ 4 COM1
64 16545 APIC timer
crdecodes CR0, CR4 and EFER bit by bit; CR2 holds the last page fault address, CR3 the active PML4.pt addrwalks the active tables for one address (AddressSpace::walk) and names the bits of every entry it reads (P, W, U, A, D, PS, G, NX and atlOS'sowned).gdtreads the GDT throughsgdtand decodes code, data and the TSS descriptor (two slots in long mode);idtshows the gates of the exceptions, the ISA IRQs, the APIC timer, the system call and the APIC's spurious vector (handler, interrupt or trap gate, DPL, IST),idt nany one.inandoutreach any I/O port, a byte by default (w16,l32 bit):in 0x21is the 8259 PIC's interrupt mask (0xff: every line masked, the APIC delivers the IRQs),in 0x64the keyboard controller's status. Writing to a port changes the device:out 0x80 0x42is harmless (the POST code port), others are not.rdmsrandwrmsrreach the model specific registers. An MSR the CPU does not have raises #GP on a real CPU; the exception table (seekernel/arch/x86_64/idt/README.md) turns that into "not readable", the kernel goes on. QEMU's emulator returns 0 for MSRs it does not know.irqcounts what arrived on every vector since boot: timer ticks, keyboard and serial interrupts, system calls, faults.int vectorraises any vector in software:int 0x40runs the APIC timer's handler (one tick;int 0x20without ACPI, where the PIT ticks),int 0x30reaches a vector without a handler,int 3is a breakpoint (the registers and a backtrace, then the shell goes on), any other exception (int 0,int 14, ...) reports and halts like the real fault.
Looking at a disk¶
disk lists the block devices found at boot (Fs::BlockDeviceList, filled
by mountAtaDisks): the whole disks and their partitions. disk read lba
dumps sectors of one, the first disk by default; the left column is the
byte offset on that device:
atlOS:/> disk
ata0 65536 sectors 32 MB
ata0p1 63488 sectors 31 MB
atlOS:/> disk read 0
ata0 sector 0
0000000000000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................|
...
00000000000001b0 00 00 00 00 00 00 00 00 cf 33 1b 84 00 00 00 20 |.........3..... |
00000000000001c0 21 00 06 14 10 04 00 08 00 00 00 f8 00 00 00 00 |!...............|
...
00000000000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 55 aa |..............U.|
Sector 0 of ata0 is the MBR: the partition table at offset 0x1be and
the signature 55 aa at the end. The first entry (type 06, FAT16)
starts at sector 0x800 (00 08 00 00, little endian) and has 0xf800
sectors. disk read 0 1 ata0p1 is the FAT boot
sector of the first partition, disk read 1 2 ata0p1 the first FAT.
Looking at PCI¶
lspci scans every bus (Drivers::scanPci, see kernel/drivers/pci/README.md)
and prints a line per function: its address, vendor and device id, class and
subclass, and their names. lspci bus:dev.fn decodes one function's header:
the command bits, the BARs, the interrupt pin, the capability list (a PCIe
device has PCI Express in it), then the first 64 bytes as they are.
atlOS:/> lspci
00:00.0 8086:1237 0600 Intel Host bridge
00:01.1 8086:7010 0101 Intel IDE controller
...
atlOS:/> lspci 00:01.1
00:01.1 IDE controller
...
BAR4 I/O ports at 0xc040
Looking at ACPI and the APIC¶
acpi lists the tables the root table (XSDT or RSDT) points at, see
kernel/firmware/acpi/README.md. acpi SIG shows one table's header,
decodes it if atlOS reads it (the MADT: processors, I/O APICs, overrides,
NMI pins) and dumps its first 512 bytes, labeled with physical addresses.
apic reads the hardware itself (kernel/drivers/apic/README.md): the local
APIC's registers and local vector table, the timer's frequency and count, and
for every ISA IRQ its GSI, I/O APIC pin and redirection entry.
atlOS:/> acpi APIC
APIC interrupt controllers (MADT)
at 0x1ffe182d, 120 bytes, revision 1, checksum valid
...
local APIC at 0xfee00000, 8259 PICs too
processor 0 APIC id 0
I/O APIC id 0 at 0xfec00000, from GSI 0
override IRQ 0 -> GSI 2, bus polarity, bus trigger
override IRQ 9 -> GSI 9, active high, level
...
atlOS:/> apic
local APIC id 0, version 0x14, 6 LVT entries, at 0xfee00000
...
timer: periodic, 63198300 Hz (bus clock / 16), count 33484 of 63198
I/O APIC id 0, version 0x20, 24 pins (GSI 0 .. 23), at 0xfec00000
IRQ GSI pin entry vector trigger polarity to APIC
0 2 2 0x0000000000010020 0x20 edge high 0 masked
1 1 1 0x0000000000000021 0x21 edge high 0
...
IRQ 1 (the keyboard) and IRQ 4 (COM1) are unmasked: their drivers asked for them. IRQ 0 is masked because the scheduler ticks on the APIC timer.
Looking at SMBIOS¶
smbios lists the structures of the firmware's SMBIOS 2.x table (see
kernel/firmware/smbios/README.md): handle, type, length, the number of
strings. smbios type shows every structure of one type: types 0 (BIOS),
1 (system), 2 (baseboard), 4 (processor) and 17 (memory device) decoded
field by field, any type with its strings and its formatted area dumped.
atlOS:/> smbios 17
handle 0x1100, type 17 Memory device, 40 bytes
locator DIMM 0
size 512 MB
type 0x07 RAM, form factor 0x09, width unknown
manufacturer QEMU
strings: 1 "DIMM 0" 2 "QEMU"
0000000000000000 11 28 00 11 00 10 fe ff ff ff ff ff 00 02 09 00 |.(..............|
...
Running a program¶
run program.elf [args] starts the program (Runtime::spawn) with
argv = { the program's path, args... } and sleeps until it exits
(Runtime::wait). Meanwhile the keys go to the program, which reads
them with read(0, ...); Ctrl+C ends a program that reads. See
kernel/proc/README.md.
Deliberately not done¶
- No pipes, no general redirection: only
echowrites to files (>,>>), and>removes and recreates the file (there is no truncate yet). - No cursor movement inside the line (left/right are ignored), no tab completion, no scrolling back.
- No programs: commands are compiled into the kernel.
- A command that hangs hangs the shell: nothing preempts it.
Flow: one command¶
sequenceDiagram
participant K as keyboard / COM1 IRQ
participant Q as CharacterQueue
participant E as LineEditor
participant I as Interpreter
participant C as cmdLs
I->>Q: read() (sleeps, CPU in hlt)
K->>Q: push('l'), push('s'), ...
Q-->>E: feed('l') -> echo "l"
Q-->>E: feed('\r') -> Done, "ls /disk0" into the history
E-->>I: line
I->>I: splitWords -> ["ls", "/disk0"], table lookup
I->>C: cmdLs(shell, 2, words)
C->>C: vfs.listDirectory -> printf
I->>I: prompt again
Tests¶
- Self tests (
kernel/tests/selftest.cpp): Shell parser (spaces, quotes, limits, numbers and overflow), Shell line editor (echo, Backspace, DEL,\r\n, Ctrl+C, skipped escape sequences, history order, duplicates, a full history, the length limit), Shell commands (every command against a FAT16 volume in RAM with the output captured: paths, files,echo >/>>,md/mwon a buffer of the test, refusing unmapped memory,helpby group,disk readof the RAM disk's boot sector,lspcion a made up bus (BARs, capabilities, bad addresses),acpion made up tables (the list, the decoded MADT, a wrong checksum),apicwithout an APIC,smbioson a made up table (the list, types 1, 4 and 17, errors),tasks(thread ids),ps,schedandtopwith a sleeping thread), VMM translate and mappings. - End to end (
scripts/run-shelltest.py,scripts/build.sh shelltest, CI): boots the normal kernel with COM1 on a TCP socket and types commands the way a terminal does (\r, DEL,ESC [ A, Ctrl+C), checking the answers, and finallyfault, whose page fault report must appear.
References¶
- Operating Systems: Three Easy Pieces: "Interlude: Process API" (what a
real shell does with
fork,exec,wait) - ECMA-48 / VT100: the escape sequences (
ESC [ A,ESC [ 2 J) - OSDev Wiki: Creating A Shell, Terminals
- xv6:
user/sh.c(a small Unix shell with pipes and redirection)