Implement UTF16" to store UEFI-compatible string
[rrq/jonasforth.git] / README.md
1 # Building and running
2
3 You can run Jonasforth inside QEMU or on real hardware. If you want to run
4 inside QEMU, you should have the following dependencies installed (assuming
5 Arch Linux):
6
7     $ pacman -S fasm qemu edk2-ovmf
8
9 Then, to run a UEFI shell inside QEMU, run:
10
11     $ make qemu
12
13 JONASFORTH will be available as `main` on `FS0:`. Thus, to run it, you can run
14 the following command inside the UEFI shell:
15
16     Shell> fs0:main
17     Ready.
18     S" Hello, World!" TELL
19     Hello World!
20
21 (Try typing in the code in `example.f` for something a little more
22 interesting.)
23
24 ## Running on real hardware
25
26 Making the program run on physical hardware is pretty easy. Just create a
27 FAT32-formatted USB drive, and copy `out/main` to it. Then, you can execute the
28 program in the same way that you did from inside QEMU, assuming your system
29 comes with a UEFI shell built-in.
30
31 If your system doesn't have a UEFI shell, then you can copy the executable to
32 `\EFI\BOOT\BOOTx64.EFI` on the USB drive. Then, the system should be able to
33 boot from the USB drive and directly into JONASFORTH. The way to do this is a
34 little bit different depending on the exact firmware, but most firmwares will
35 have some way to enter a boot menu where you can select the USB drive. You may
36 need to disable Secure Boot first.
37
38 To format a USB drive as FAT32, you can run
39
40     # mkfs.vfat -F32 /dev/sdx
41
42 with `/dev/sdx` replaced by the path of your USB drive. Then mount the drive,
43 and copy `out/main` to `\EFI\BOOT\BOOTx64.EFI`:
44
45     $ mkdir mnt
46     # mount /dev/sdx mnt
47     $ mkdir -p mnt/EFI/BOOT
48     $ make out/main
49     $ cp out/main mnt/EFI/BOOT/BOOTx64.EFI
50
51 Now you should be able to boot directly from the USB drive.
52
53 # Notes on implementation
54
55 The implementation is based on
56 [JONESFORTH](https://raw.githubusercontent.com/nornagon/jonesforth/master/jonesforth.S).
57 This is my summary of the most important parts.
58
59 ## Dictionary
60
61 In Forth, words are stored in a dictionary. The dictionary is a linked list
62 whose entries look like this:
63
64     +------------------------+--------+---------- - - - - +----------- - - - -
65     | LINK POINTER           | LENGTH/| NAME              | DEFINITION
66     |                        | FLAGS  |                   |
67     +--- (4 bytes) ----------+- byte -+- n bytes  - - - - +----------- - - - -
68
69 For example, DOUBLE and QUADRUPLE may be stored like this:
70
71       pointer to previous word
72        ^
73        |
74     +--|------+---+---+---+---+---+---+---+---+------------- - - - -
75     | LINK    | 6 | D | O | U | B | L | E | 0 | (definition ...)
76     +---------+---+---+---+---+---+---+---+---+------------- - - - -
77        ^       len                         padding
78        |
79     +--|------+---+---+---+---+---+---+---+---+---+---+---+---+------------- - - - -
80     | LINK    | 9 | Q | U | A | D | R | U | P | L | E | 0 | 0 | (definition ...)
81     +---------+---+---+---+---+---+---+---+---+---+---+---+---+------------- - - - -
82        ^       len                                     padding
83        |
84        |
85     LATEST
86
87 The Forth variable LATEST contains a pointer to the most recently defined word.
88
89 ## Threaded code
90
91 In a typical Forth interpreter, code is stored in an unusual format that makes it
92 easy to implement an interpreter, and which was also motivated by space
93 constraints on early systems.
94
95 The definition of a word is stored as a sequence of memory adresses of each of
96 the words making up that definition. (At the end of a compiled definition, there
97 is also some extra code that causes execution to continue in the correct way.)
98
99 We use a register (RSI) to store a reference to the next index of the
100 word (inside a definition) that we are executing. Then, in order to execute a
101 word, we just jump to whatever address is pointed to by RSI. The code for
102 updating RSI and continuing execution is stored at the end of each subroutine.
103
104 Of course, this approach only works if each of the words that we are executing
105 is defined in assembly, but we also want to be able to execute Forth words!
106
107 We get around this problem by adding a "codeword" to the beginning of any
108 compiled subroutine. This codeword is a pointer to the intrepreter to run the
109 given function. In order to run such functions, we actually need two jumps when
110 executing: In order to execute a word, we jump to the address at the location
111 pointed to by the address in RSI.
112
113 ## Definitions
114
115 What does the codeword of a Forth word contain? It needs to save the old value
116 of RSI (so that we can resume execution of whatever outer definition we are
117 executing at the time) and set the new version of RSI to point to the first word
118 in the inner definition.
119
120 The stack where the values of RSI are stored is called the "return stack". We
121 will use RBP for the return stack.
122
123 Whenever we finish executing a Forth word, we will need to continue execution
124 somewhere else. When the word being executed is itself written in Forth, we need
125 to pop the old value of RSI that we saved at the beginning of the definition
126 before doing this.
127
128 Thus, the actual data for a word in a dictionary will look something like this:
129
130       pointer to previous word
131        ^
132        |
133     +--|------+---+---+---+---+---+---+---+---+------------+------------+------------+------------+
134     | LINK    | 6 | D | O | U | B | L | E | 0 | DOCOL      | DUP        | +          | EXIT       |
135     +---------+---+---+---+---+---+---+---+---+------------+--|---------+------------+------------+
136        ^       len                         pad  codeword      |
137        |                                                      V
138       LINK in next word                            points to codeword of DUP
139
140 Here, DOCOL (the codeword) is address of the simple interpreter described above,
141 while EXIT a word (implemented in assembly) that takes care of popping RSI and
142 continuing execution. Note that DOCOL, DUP, + and EXIT are all stored as
143 addresses which point to codewords.
144
145 ## Literals
146
147 Literals are handled in a special way. There is a word in Forth, called LIT,
148 implemented in assembly. When executed, this word looks at the next Forth
149 instruction (i.e. the value of RSI), and places that on the stack as a literal,
150 and then manipulates RSI to skip over the literal value.
151
152 When compiling a word, we need to handle the input specially such that literals
153 are compiled as `LIT x`.
154
155 ## Built-in variables
156
157 - **STATE** -- Is the interpreter executing code (0) or compiling a word (non-zero)?
158 - **LATEST** -- Points to the latest (most recently defined) word in the dictionary.
159 - **HERE** -- Points to the next free byte of memory. When compiling, compiled words go here.
160 - **S0** -- Stores the address of the top of the parameter stack.
161 - **BASE** -- The current base (radix) for printing and reading numbers.
162
163 ## Input and lookup
164
165 `WORD` reads a word from standard input and pushes a string (in the form of an
166 address followed by the length of the string) to the stack. The buffer is only
167 valid until the next call to `WORD`.
168
169 `FIND` takes a word (as parsed by `WORD`) and looks it up in the dictionary. It
170 returns the address of the dictionary header of that word if it is found.
171 Otherwise, it returns 0.
172
173 `>CFA` turns a dictionary pointer into a codeword pointer. This is used when
174 compiling.
175
176 ## Compilation
177
178 The Forth word `INTERPRET` runs in a loop, reading in words (with `WORD`),
179 looking them up (with `FIND`), turning them into codeword pointers (with `>CFA`)
180 and then deciding what to do with them.
181
182 In immediate mode (when `STATE` is zero), the word is simply executed
183 immediately.
184
185 In compilation mode, `INTERPRET` appends the codeword pointer to user memory
186 (which is at HERE). However, if a word has the immediate flag set, then it is run
187 immediately, even in compile mode.
188
189 ### Definition of `:` and `;`
190
191 The word `:` starts by reading in the new word. Then it creates a new entry for
192 that word in the dictoinary, updating the contents of `LATEST`, to which it
193 appends the word `DOCOL`. Then, it switches to compile mode.
194
195 The word `;` simply appends `EXIT` to the currently compiling definition and
196 then switches back to immediate mode.
197
198 These words rely on `,` to append words to the currently compiling definition.
199 This word simply appends some literal value to `HERE` and moves the `HERE`
200 pointer forward.
201
202 # Notes on UEFI
203
204 Jonasforth runs without an underlying operating system, instead using the
205 facilities provided by UEFI by running as a UEFI application. This section
206 contains some notes about how this functionality is implemented.
207
208 I also wrote an entire tutorial that descirbes how to write and compile a
209 "Hello, World!" UEFI application, including how to run it on real hardware,
210 which you can find here: [Getting started with bare-metal
211 assembly](https://johv.dk/blog/bare-metal-assembly-tutorial.html).
212
213 ## Packaging and testing the image
214
215 UEFI expects a UEFI application to be stored in a FAT32 file system on a
216 GPT-partitioned disk.
217
218 Luckily, QEMU has a convenient way of making a subdirectory availabe as a
219 FAT-formatted disk (see [the relevant section in the QEMU User
220 Documentation](https://qemu.weilnetz.de/doc/qemu-doc.html#disk_005fimages_005ffat_005fimages)
221 for more information):
222
223     $ qemu-sytem-x86_64 ... -hda fat:/some/directory
224
225 We use this to easily test the image in QEMU; see the Makefile for more
226 information, or just run the `qemu` target to run the program inside of QEMU
227 (of course, you must have QEMU installed for this to work):
228
229     $ make qemu
230
231 ## Interfacing with UEFI
232
233 From [OSDev Wiki](https://wiki.osdev.org/UEFI#How_to_use_UEFI):
234
235 > Traditional operating systems like Windows and Linux have an existing software
236 > architecture and a large code base to perform system configuration and device
237 > discovery. With their sophisticated layers of abstraction they don't directly
238 > benefit from UEFI. As a result, their UEFI bootloaders do little but prepare
239 > the environment for them to run.
240 >
241 > An independent developer may find more value in using UEFI to write
242 > feature-full UEFI applications, rather than viewing UEFI as a temporary
243 > start-up environment to be jettisoned during the boot process. Unlike legacy
244 > bootloaders, which typically interact with BIOS only enough to bring up the OS,
245 > a UEFI application can implement sophisticated behavior with the help of UEFI.
246 > In other words, an independent developer shouldn't be in a rush to leave
247 > "UEFI-land".
248
249 For `JONASFORTH`, I have decided to run as a UEFI application, taking advantage
250 of UEFI's features, including its text I/O features and general graphical device
251 drivers. Eventually, we would like to add some basic graphical drawing
252 capabilities to `JONASFORTH`, and it's my impression that this would be possible
253 using what is provided to us by UEFI.
254
255 A UEFI images is basically a windows EXE without symbol tables. There are three
256 types of UEFI images; we use the EFI application, which has subsystem `10`. It
257 is an x68-64 image, which has value `0x8664`.
258
259 UEFI applications use [Microsoft's 64-bit calling
260 convention](https://en.wikipedia.org/wiki/X86_calling_conventions#Microsoft_x64_calling_convention)
261 for x68-64 functions. See the linked article for a full description. Here is
262 the short version:
263
264 - Integer or pointer arguments are given in RCX, RDX, R8 and R9.
265 - Additional arguments are pushed onto the stack from right to left.
266 - Integer or pointer values are returned in RAX.
267 - An integer-sized struct is passed directly; non-integer-sized structs are passed as pointers.
268 - The caller must allocate 32 bytes of "shadow space" on the stack immediately
269   before calling the function, regardless of the number of parameters used, and
270   the caller is responsible for popping the stack afterwards.
271 - The following registers are volatile (caller-saved): RAX, RCX, RDX, R8, R9, R10, R11
272 - The following registers are nonvolatile (callee-saved): RBX, RBP, RDI, RSI, RSP, R12, R13, R14, R15
273
274 When the application is loaded, RCX contains a firmware allocated `EFI_HANDLE`
275 for the UEFI image, RDX contains a `EFI_SYSTEM_TABLE*` pointer to the EFI system
276 table and RSP contains the return address. For more infromation about how a UEFI
277 application is entered, see "4 - EFI System Table" in [the latest UEFI
278 specification as of March 2020 (PDF)](https://uefi.org/sites/default/files/resources/UEFI_Spec_2_8_A_Feb14.pdf).
279
280 **Sources:**
281
282 - [UEFI applications in detail - OSDev Wiki](https://wiki.osdev.org/UEFI#UEFI_applications_in_detail)
283 - [Microsoft x64 calling convention](https://en.wikipedia.org/wiki/X86_calling_conventions#Microsoft_x64_calling_convention)
284 - [UEFI Specifications](https://uefi.org/specifications)
285
286 ### UEFI with FASM
287
288 We might want to consider using something like this: https://wiki.osdev.org/Uefi.inc)
289
290 FASM can generate UEFI application binaries by default. Use the following
291 template to output a 64-bit UEFI application:
292
293     format pe64 dll efi
294     entry main
295
296     section '.text' code executable readable
297
298     main:
299        ;; ...
300        ret
301
302     section '.data' data readable writable
303
304     ;; ...
305
306 Use `objdump -x` to inspect the assembled application binary.
307
308 ### UEFI documentation
309
310 - [Latest specification as of March 2020 (PDF)](https://uefi.org/sites/default/files/resources/UEFI_Spec_2_8_A_Feb14.pdf)
311
312 Notable sections:
313
314 - 2\. Overview (14)
315 - 4\. EFI System Table (89)
316 - 7\. Services - Boot Services (140)
317 - 8\. Services - Runtime Services (228)
318 - 12\. Protocols - Console Support (429)
319 - 13\. Protocols - Media Access (493)
320 - Appendix B - Console (2201)
321 - Appendix D - Status Codes (2211)
322
323 ## Resources
324
325 - [UEFI - OSDev Wiki](https://wiki.osdev.org/UEFI)
326 - [Unified Extensible Firmware Interface (Wikipedia)](https://en.wikipedia.org/wiki/Unified_Extensible_Firmware_Interface)
327 - [UEFI Specifications](https://uefi.org/specifications)