summary refs log tree commit diff
path: root/quine.asm
blob: 7e15a519e142c0cb68d47064a7795a5b89b11d46 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
;;; QUINE
;;;
;;; This file is formatted to be read at 80-columns or wider.


;;;;;;;;;;;;;;;;;;;;;
;;; Workflow tips ;;;
;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Currently, this is not yet fully self-hosting; it is based on
;;; flatassembler[1]. A minimal command to build and run it is:
;;;
;;; fasmg quine.asm quine && chmod 755 quine && ./quine; echo $?
;;;
;;; A workflow you may wish to use for debugging is:
;;;
;;; rm quine2; fasmg quine.asm quine && ./quine > quine2; echo "exit code:" $?; echo; hexdump -C quine; echo; hexdump -C quine2; echo; cmp quine quine2 ; echo cmp: $?
;;;
;;; The reason this removes the old one first is that otherwise, there's a
;;; risk the error message will be scrolled off the top of the screen and
;;; you'll see stale output and not realize.
;;;
;;; You may also wish to do:
;;;
;;; objdump --disassemble quine
;;; ZydisDisasm -64 quine
;;;
;;; This relies on GNU binutils, and on zydis, respectively.
;;;
;;; [1] https://flatassembler.net/


;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Assembly language ;;;
;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Before doing any actual code, we define macros for writing x86-64 assembly
;;; language. This is built from scratch, relying only on flatassembler's
;;; built-in semantics. No include files of any kind are used for it.

macro rex.0
  db 0x40
end macro

macro rex.w
  db 0x48
end macro

macro rex.xb
  db 0x43
end macro

macro modrm mod, reg, rm
  assert mod >= 0 & mod < 4
  assert reg >= 0 & reg < 8
  assert rm >= 0 & rm < 8
  db (mod shl 6) or (reg shl 3) or rm
end macro

macro sib scale, index, base
  assert scale >= 0 & scale < 4
  assert index >= 0 & index < 8
  assert base >= 0 & index < 8
  db (scale shl 6) or (index shl 3) or base
end macro

macro opcodereg opcode, reg
  assert opcode >= 0 & opcode < 256 & opcode and 7 = 0
  assert reg >= 0 & reg < 8
  db opcode or reg
end macro

macro qwordreg result, register
  match =rax?, register
    result = 0
  else match =rcx?, regiser
    result = 1
  else match =rdx?, register
    result = 2
  else match =rbx?, register
    result = 3
  else match =rsp?, register
    result = 4
  else match =rbp?, register
    result = 5
  else match =rsi?, register
    result = 6
  else match =rdi?, register
    result = 7
  else
    assert 0
  end match
end macro


; TODO what register size does this use?
macro mov.b target, source
  match =rax?, target
    db 0xB8
    dd source
  else match =rdi?, target
    db 0xBF
    dd source
  else
    assert 0
  end match
end macro


; TODO what register size does this use?
macro mov.dreg.dimm target, source
  rex.w
  db 0xC7
  qwordreg reg, target
  modrm 3, 0, reg
  dd source
end macro


macro mov.qreg.qimm target, source
  rex.w
  qwordreg treg, target
  opcodereg 0xB8, treg
  dq source
end macro


macro mov.qreg.qreg target, source
  qwordreg treg, target
  qwordreg sreg, source
  rex.w
  db 0x89
  modrm 3, sreg, treg
end macro


; Take a 64-bit source register, treat it as an address and look up the 64-bit
; value it points to, store that into a 64-bit target register. The only modes
; available also have displacement; we use an 8-bit one and set it to zero.
;
; In understanding this, pay close attention to the Op/En column in the opcode
; table. The "RM" variant means the ModRM byte's R/M field (the third one)
; is the source, while its reg field (the middle one) is the target. This is
; what we want, because the R/M field is the one that gets indirection applied
; to it. Opcode 0x8B with an REX.W prefix is the all-64-bit RM variant.
; [Intel] volume 2B, chapter 3, section 3-4.3, "MOV".
;
; For the indirection modes, don't be confused by the many similar tables.
; 64-bit mode is encoded the same as 32-bit mode except for adding a REX.W
; prefix, as per 2.2.1.1, so you want table 2-2 to understand the ModRM byte.
; The presence or absence of an SIB byte is determined by where in that table
; we fall, and we aren't using a mode that has one. [Intel] volume 2A,
; chapter 2, section 2-1.5, table 2-2.
;
; We disallow rsp as a source because that's the mode that would want an SIB.
macro mov.qreg.indirect.qreg target, source
  match =rsp, source
    assert 0
  else
    qwordreg sreg, source
    qwordreg treg, target
    rex.w
    rb 0x8B
    modrm 1, treg, sreg
    db 0
  end match
end macro


; Take a 64-bit source register, store its value into the address pointed to
; by a 64-bit target register. The only modes available also have
; displacement; we use an 8-bit one and set it to zero.
;
; In understanding this, pay close attention to the Op/En column in the opcode
; table. The "MR" variant means the ModRM byte's reg field (the middle one)
; is the source, while its R/M field (the third one) is the target. This is
; what we want, because the R/M field is the one that gets indirection applied
; to it. Opcode 0x89 with an REX.W prefix is the all-64-bit MR variant.
; [Intel] volume 2B, chapter 3, section 3-4.3, "MOV".
;
; For the indirection modes, don't be confused by the many similar tables.
; 64-bit mode is encoded the same as 32-bit mode except for adding a REX.W
; prefix, as per 2.2.1.1, so you want table 2-2 to understand the ModRM byte.
; The presence or absence of an SIB byte is determined by where in that table
; we fall, and we aren't using a mode that has one. [Intel] volume 2A,
; chapter 2, section 2-1.5, table 2-2.
;
; We disallow rsp as a target because that's the mode that would want an SIB.
macro mov.indirect.qreg.qreg target, source
  match =rsp, target
    assert 0
  else
    qwordreg sreg, source
    qwordreg treg, target
    rex.w
    rb 0x89
    modrm 1, sreg, treg
    db 0
  end match
end macro


macro add.qreg.qreg target, source
  qwordreg treg, target
  qwordreg sreg, source
  rex.w
  db 0x01
  modrm 3, sreg, treg
end macro


; This adds a signed 8-bit immediate value to a 64-bit register, in place.
;
; Notice the use of 3 as the addressing mode. This says to use the register
; itself. The 0 in the reg field is part of the opcode.
macro add.qreg.bimm target, source
  qwordreg treg, target
  rex.w
  db 0x83
  modrm 3, 0, treg
  db source
end macro

; This adds a signed 32-bit immediate value to a 64-bit register, in place.
;
; Notice the use of 3 as the addressing mode. This says to use the register
; itself. The 0 in the reg field is part of the opcode.
macro add.qreg.dimm target, source
  qwordreg treg, target
  rex.w
  db 0x81
  modrm 3, 0, treg
  dd source
end macro

; This subtracts a signed 8-bit immediate value from a 64-bit register, in
; place.
;
; Notice the use of 3 as the addressing mode. This says to use the register
; itself. The 5 in the reg field is part of the opcode.
macro sub.qreg.bimm target, source
  qwordreg treg, target
  rex.w
  db 0x83
  modrm 3, 5, treg
  db source
end macro

; This subtracts a signed 32-bit immediate value from a 64-bit register, in
; place.
;
; Notice the use of 3 as the addressing mode. This says to use the register
; itself. The 5 in th reg field is part of the opcode.
macro sub.qreg.dimm target, source
  qwordreg treg, target
  rex.w
  db 0x81
  modrm 3, 5, treg
  dd source
end macro

; Move from an 8-bit immediate value, to a location relative to a 64-bit
; register, with an 8-bit displacement and no indexing.
;
; This uses opcode 0xC6, which has w = 0. Since we run in 64-bit mode, that
; makes the operand size 8 bits, regardless of the current operand-size
; attribute. [Intel] volume 2D, appendix B, section B-1.4.3, table B-6.
;
; TODO this should be mov.(something).disp8
macro mov.rel.b target, offset, source
  match =rsp, target
    db 0xC6
    modrm 1, 0, 4
    sib 0, 0, 4
    db offset
    db source
  else
    assert 0
  end match
end macro

; Move from a 16-bit immediate value, to a location relative to a 64-bit
; register, with an 8-bit displacement and no indexing.
;
; This uses opcode 0xC7, which has w = 1. We run in 64-bit mode, so that gives
; us an operand size of 32 bits by default. [Intel] volume 1, section 3.6.1,
; table 3-4. We want a 16-bit operand, so we use the operand-size prefix,
; 0x66, and we leave REX.W unset.
macro mov.rel.w target, offset, source
  match =rsp, target
    db 0x66
    db 0xC7
    modrm 1, 0, 4
    sib 0, 4, 4
    db offset
    dw source
  else
    assert 0
  end match
end macro

; Move from a 32-bit immediate value, to a location relative to a 64-bit
; register, with an 8-bit displacement and no indexing.
;
; This uses opcode 0x67, which has w = 1. We run in 64-bit mode, so that gives
; us an operand size of 32 by default. [Intel] volume 2D, section B.1.43,
; table B-6. This is what we want, so we leave it.
macro mov.rel.d target, offset, source
  match =rsp, target
    db 0xC7
    modrm 1, 0, 4
    sib 0, 4, 4
    db offset
    dd source
  else
    assert 0
  end match
end macro

; Move from a 64-bit register, to a 64-bit location relative to a 64-bit
; register, with an 8-bit displacement and no indexing.
;
; This uses opcode 0x89.
macro mov.rel.q target, offset, source
  match =rsp, target
    qwordreg sreg, source
    rex.w
    db 0x89
    modrm 1, sreg, 4
    sib 0, 4, 4
    db offset
  else
    assert 0
  end match
end macro

; Move from a 32-bit immediate value, to a 64-bit location relative to a
; 64-bit register, with an 8-bit displacement and no indexing.
;
; Note that there is no instruction to move a 64-bit immediate to memory.
;
; This uses opcode 0xC7, which has w = 1. We run in 64-bit mode, so that
; gives us an operand size of 32 by default. [Intel] volume 2D,
; section B.1.43, table B-6. We want a 64-bit operand, so we use the REX.W
; prefix, 0x48.
macro mov.rel.q.d target, offset, source
  match =rsp, target
    rex.w
    db 0xC7
    modrm 1, 0, 4
    sib 0, 4, 4
    db offset
    dd source
  else
    assert 0
  end match
end macro

; "Load effective address". Compute a 64-bit address as you would for
;  indexed addressing, with an 8-bit displacement and no indexing, but instead
; of doing anything with the memory, just store the address itself into a
; register.
macro lea.qreg.qreg.disp8 target, offset, source
  rex.w
  db 0x8D
  qwordreg treg, target
  qwordreg sreg, source
  modrm 1, treg, sreg
  db offset
end macro

; Clear the DF flag. This makes string instructions increment RSI.
macro cld
  db 0xFC
end macro

; Load 64 bits from the address in RSI into RAX. Then, increment or decrement
; RSI by 8 bytes, depending on the value of the DF flag.
macro lodsq
  rex.w
  db 0xAD
end macro

; Do an absolute indirect jump with a 64-bit register operand. That is: given
; a register which holds a pointer, read another address from the pointed-to
; memory and jump to it.
;
; Technically this is a "near" jump in x86 terms, but we just pretend far
; jumps and segments don't exist. They are still a thing in 64-bit mode, we
; just don't use them.
macro jmp.abs.indirect.qreg location
  db 0xFF
  qwordreg lreg, location
  modrm 0, lreg, 4
end macro

; Invoke a system call provided by the kernel. On Linux, the System V ABI
; describes the semantics of such calls (at least, on x86).
macro syscall
  db 0x0F, 0x05
end macro



;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Executable file format ;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Before we get into the body of the program, we do a lot of ELF-specific
;;; stuff to ensure that our output is in a format Linux knows how to run.
;;;
;;; First, we set the origin to load at. This is arbitrary, but it can't be
;;; zero. We tell flatassembler about it because it's used in label
;;; calculations; we can reference it as $$ any time we need it in future.
org 0x08000000

;;;
;;; Second, we output ELF's top-level file header.
;;;
elf_header:
  ; * denotes mandatory fields according to breadbox
  db 0x7F, "ELF"                 ; *magic number
  db 2                           ; 64-bit
  db 1                           ; little-endian
  db 1                           ; ELF header format version 1
  db 0                           ; System-V ABI
  db 8 dup 0                     ; (padding)

  dw 2                           ; *executable
  dw 0x3E                        ; *Intel x86-64
  dd 1                           ; ELF format version

  dq _start                      ; *entry point
  dq program_header - $$         ; *program header offset
  dq 0                           ; section header offset
  dd 0                           ; processor flags
  dw elf_header_size
  dw program_header_entry_size   ; *
  dw 1                           ; *number of program header entries
  dw 0                           ; section header entry size
  dw 0                           ; number of section header entries
  dw 0                           ; section name string table index
; Save a copy of the size of this chunk for our future reference, by comparing
; the current posiion to the label above.
elf_header_size = $ - elf_header

;;;
;;; Third, immediately after the ELF file header, we output ELF's program
;;; header, which lists the memory regions ("segments") we want to have and
;;; where we want them to come from. We list just a single region, which is
;;; the entire contents of the ELF file from disk.
;;;
;;; It would be more typical to have separate code and data segments, and
;;; perhaps a stack or heap, but this keeps things simple. We do have a little
;;; stack space available, though we don't explicitily request any; the kernel
;;; allocates it for us as part of exec() so that it can pass us argc and argv
;;; (which we ignore). That stack space will be at a random address, different
;;; every time, because of ASLR; that's a neat security feature, so we leave
;;; it as-is.
;;;
program_header:
  dd 1                           ; *"loadable" segment type
  dd 0x05                        ; *read+execute permission
  dq 0                           ; *offset in file
  dq $$                          ; *virtual address
                                 ;   required, but can be anything, subject to
                                 ;   alignment
  dq 0                           ; physical address (ignored)
  dq file_size                   ; *size in file
  dq file_size                   ; *size in memory
  dq 0                           ; segment alignment
                                 ;   for relocation - will we be ASLR'd?
; Save the size of this chunk, as well.
program_header_entry_size = $ - program_header


;;;;;;;;;;;;;;;;;;;;;;;
;;; Execution model ;;;
;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;;   We use Forth-style dual stacks, one for values and one for control. We
;;; use rsp for values, just like C does. We use rbp for the control stack,
;;; which is a special Forth-y stack: These are pointers into the bodies of
;;; Forth words, not return addresses.
;;;
;;;   The choice of rsp and rbp for the stack pointers imitates Jonesforth;
;;; I'm hopeful that it gives us convenient addressing modes, and will report
;;; back about that when I feel that I understand the implications.
;;;
;;;   In Forth, everything is a "word", including mutable variables.
;;; Conceptually, a word is a unit of execution, which may be implemented
;;; either in machine code or as an array of pointer to other words.
;;;
;;;   This polymorphism is implemented by having each word's contents begin
;;; with a "codeword", which is a pointer to machine code that "interprets"
;;; the rest of the contents. In the case of words implemented in machine
;;; code, the codeword points directly to that code, which is normally right
;;; next to it.
;;;
;;;   Variables, to Forth, are simply one more thing that can be executed; the
;;; effect of executing a variable is to push its address onto the value
;;; stack.
;;;
;;;   We adopt this model of words, codewords, and variables-as-words. It's
;;; nice for us because it works without a heap.
;;;
;;;   One way in which we differ from Forth is that we don't have a
;;; dictionary, and our words don't have names. Nothing would prevent this,
;;; it just isn't useful to this single-purpose program. The Forth dictionary
;;; is usually a linked list of every word that has ever been defined, with
;;; the newest at the head; the names of words are stored in string fields as
;;; part of every word's internal header. Our header has neither the pointer
;;; field for the dictionary, nor the string; the only header we have is the
;;; the codeword.
;;;
;;;   We specifically implement a version of calling and returning that Forth
;;; calls indirect threaded code: The control stack is a stack of pointers
;;; into the middle of interpreted words. The interpreter snippet, called
;;; DOCOL, implements calling.  Each word is responsible for making sure
;;; returning works properly. Interpreted words accomplish this by ending with
;;; the word EXIT, while machine-code words accomplish it by ending with a
;;; verbatim snippet called NEXT.
;;;
;;;   Conceptually, NEXT returns, but more specifically it accomplishes this
;;; by doing the caller's next dispatch for it; thus control never actually
;;; goes back to the caller's interpreter after initial setup. For performance
;;; reasons, NEXT is always inlined, so we define it as a macro.
;;;
;;;   DOCOL is just ordinary code, not a macro. It's defined later in this
;;; file, as a label.
;;;
;;;
;;;
;;; --------------------------------------------------------------------------
;;;  Quick Reference
;;; --------------------------------------------------------------------------
;;;
;;; The layout of an interpreted word:
;;;
;;;     0x00 - 0x08                     Codeword (address of DOCOL snippet)
;;;     0x08 - ???? (8-byte chunks)     Addresses of other words
;;;       ... (end)                     Address of EXIT word
;;;
;;; The layout of a machine-code word:
;;;
;;;     0x00 - 0x08                     Addresss of immediately following byte
;;;     0x08 - ????                     Arbitrary machine code
;;;       ... (end)                     Inlined implementation of NEXT
;;;
;;;
;;; REGISTER usage conventions:
;;;
;;; * rsi is the "instruction pointer" for the "interpreter".
;;;     That is, it points to some word-pointer inside an array of
;;;   word-pointers inside the content of the word they're part of. It always
;;;   points to the next word that should be executed, whose execution hasn't
;;;   begun yet.
;;;
;;; * rbp points to the top of the control stack
;;;     These are former values of rsi, to eventually be returned to, from
;;;   successively older callers as you look further up the stack. The stack
;;;   grows downwards in memory. Since values are kept separately, the only
;;;   thing on the control stack is return addresses, one per layer of call.
;;;
;;; * esp points to the top of the value stack
;;;     The value stack has no specific format, but it grows downwards in
;;;   memory. In particular there's no concept of stack frames, because items
;;;   on the stack don't belong to any particular word; the value stack in
;;;   Forth is in part a mechanism for passing values between words.
;;;
;;; Additionally, immediately after beginning execution of a word:
;;;
;;; * rax points to the address being executed
;;;     The value of rax is purely for the callee's benefit, and does not need
;;;   to be preserved.
;;;
;;;   Other registers are purely discretionary, and are not preserved across
;;; calls.
;;;
;;;
;;; FLAG usage:
;;;
;;; * DF should be 0
;;;   We use lodsq extensively and that makes it increment rsi after using it.
;;;
;;; --------------------------------------------------------------------------

;;;
;;; Macro NEXT
;;; ----------
;;;
;;;   Include this inline at the end of a word implemented in machine-code.
;;; Conceptually, it returns. What it actually does is do the next thing the
;;; caller would do, which is call the next word from the caller's array of
;;; word pointers.
;;;
;;; Registers in:
;;;
;;; * rsi points to the address of the word to execute
;;;
;;; Registers out:
;;;
;;; * rax points to the codeword in the contents of the word that was executed
;;; * rsi points to the next word-address after this one
;;;
;;; Flags
;;; * DF = 0 is required
;;;
macro NEXT
  ; Copy the next word's address from *rsi into rax. Increment the stack
  ; pointer (as per the DF flag).
  lodsq

  ; Load the codeword from the word's contents, and jump to the interpreter it
  ; points to.
  jmp.abs.indirect.qreg rax
end macro

;;;
;;; Macros PUSHCONTROL
;;;        POPCONTROL
;;; ------------------
;;;
;;;   Include these inline to push an address onto the control stack, or pop
;;; one off of it. You will recall the control stack is kept in rbp. The
;;; parameter is given in a user-specified register.
;;;
;;;   Jonesforth's analogous macros are called PUSHRSP and POPRSP but I think
;;; that's super confusing, since rsp is also the name of a register, but a
;;; different one. I guess it was less confusing in 32-bit, since esp doesn't
;;; start with an "r". Anyway, this has to be named something that
;;; distinguishes it from Intel's PUSH and POP opcodes, so...
;;;
;;;   "Load effective address" is just a cute way to do arithmetic on a
;;; register, here. To push or pop we decrement or increment rbp by 8. To
;;; actually interact with the space in the stack, we indirect through rbp.
;;;
;;; Registers in and out:
;;;
;;; * rbp points to the top of the control stack.
;;;
macro PUSHCONTROL source
  lea.qreg.qreg.disp8 rbp, -8, rbp
  mov.indirect.qreg.qreg rbp, source
end macro

macro POPCONTROL target
  mov.qreg.indirect.qreg target, rbp
  lea.qreg.qreg.disp8 rbp, 8, rbp
end macro

;;;
;;; Routine DOCOL
;;; -------------
;;;
;;;   Reference this via its label as the codeword of a word to make it an
;;; "interpreted" word. Concretely, it saves rsi (the "instruction pointer")
;;; to the control stack, takes the address of the codeword from rax and
;;; increments it in-place to form the new instruction pointer, and copies
;;; that to rsi.
;;;
;;;   Having then done this, we're now in the state that normal execution
;;; expects, so DOCOL ends by it using NEXT to begin the callee's execution,
;;; kicking off a nested call.
;;;
;;;   The name is said to be short for "do colon", because Forth high-level
;;; code begins word definitions with a colon.
;;;
;;; Registers in:
;;;
;;; * rsi is the caller's instruction pointer
;;; * rbp is the control stack pointer
;;; * rax is the address of the callee's codeword
;;;
;;; Registers out:
;;;
;;; * rsi is the callee's instruction pointer
;;; * rbp is the control stack pointer
DOCOL:
  PUSHCONTROL rsi
  add.qreg.bimm rax, 8
  mov.qreg.qreg rsi, rax
  NEXT

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Implementation strategy ;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;;   We assemble the entire file contents in a stack-allocated buffer.
;;; We avoid using the stack for any other purpose. When the file is fully
;;; assembled, we output it.
;;;
;;;   The assembly proceeds in several chunks - ELF header, program header,
;;; etc. Each chunk extends the buffer as per its own needs, by adjusting
;;; the stack pointer. All chunks also update a running total file size,
;;; which refers to how many bytes have actually been populated, not to the
;;; size of the buffer.
;;;
;;; Register usage:
;;;
;;; * rdx holds the total used file size so far. During hand-off between
;;;   chunks, this size must be equal to the buffer size; within a chunk it
;;;   may be less.
;;;
;;; * rsp points to the bottom of the buffer.
;;;
_start:
  ;;;
  ;;; Initialize registers
  ;;;
  cld                                      ; clear the DF flag
  mov.dreg.dimm rdx, 0                     ; store running file size here
  sub.qreg.bimm rsp, 0xFF                  ; reserve stack space

  ;;;
  ;;; ELF header
  ;;;
  mov.rel.d rsp, 0x00, 0x7F bappend "ELF"  ; magic number
  mov.rel.b rsp, 0x04, 2                   ; 64-bit
  mov.rel.b rsp, 0x05, 1                   ; little-endian
  mov.rel.b rsp, 0x06, 1                   ; ELF header format version 1
  mov.rel.b rsp, 0x07, 0                   ; System-V ABI
  mov.rel.q.d rsp, 0x08, 0                 ; (padding)

  mov.rel.w rsp, 0x10, 2                   ; executable
  mov.rel.w rsp, 0x12, 0x3E                ; Intel x86-64
  mov.rel.d rsp, 0x14, 1                   ; ELF format version

  ; Compute the entry pointer.
  mov.qreg.qimm rax, $$                    ; the memory origin
  add.qreg.bimm rax, 0x78                  ; the size of the headers
  add.qreg.dimm rax, 155                   ; the offset of _start
  mov.rel.q rsp, 0x18, rax                 ; entry point

  mov.rel.q.d rsp, 0x20, 64                ; program header offset
    ; We place the program header immediately after the ELF header. This
    ; offset is from the start of the file.
  mov.rel.q.d rsp, 0x28, 0                 ; section header offset
  mov.rel.d rsp, 0x30, 0                   ; processor flags
  mov.rel.w rsp, 0x34, 64                  ; ELF header size
  mov.rel.w rsp, 0x36, 56                  ; program header entry size
  mov.rel.w rsp, 0x38, 1                   ; number of program header entries
  mov.rel.w rsp, 0x3a, 0                   ; section header entry size
  mov.rel.w rsp, 0x3c, 0                   ; number of section header entries
  mov.rel.w rsp, 0x3e, 0                   ; section name string table index

  ; Add the size of the ELF header to the running total
  mov.dreg.dimm rax, 0x40
  add.qreg.qreg rdx, rax

  ;;;
  ;;; Program header
  ;;;
  mov.rel.d rsp, 0x40, 1                   ; "loadable" segment type
  mov.rel.d rsp, 0x44, 0x05                ; read+execute permission
  mov.rel.q.d rsp, 0x48, 0                 ; offset in file
  mov.rel.q.d rsp, 0x50, $$                ; virtual address
    ; required, but can be anything, subject to alignment
  mov.rel.q.d rsp, 0x58, 0                 ; physical address (ignored)

  ; Fill in 0 as the file size for now, to avoid unitialized memory.
  mov.rel.q.d rsp, 0x60, 0                 ; size in file
  mov.rel.q.d rsp, 0x68, 0                 ; size in memory

  mov.rel.q.d rsp, 0x70, 0                 ; segment alignment
    ;   for relocation - will we be ASLR'd?

  ; Add the size of the program header to the running total
  mov.dreg.dimm rax, 0x38
  add.qreg.qreg rdx, rax

  ;;; Hardcode the size of the actual code chunk, since we don't yet have a
  ;;; way to generate it.
  ;;;
  ;;; TODO of course, really we want to for-real track this
  mov.qreg.qimm rax, 0x200
  add.qreg.qreg rdx, rax

  ;;;
  ;;; Go back and fill in the file size now that we know it.
  ;;;
  mov.rel.q rsp, 0x60, rdx                 ; size in file
  mov.rel.q rsp, 0x68, rdx                 ; size in memory

  ;;;
  ;;; The buffer is ready; output the file.
  ;;;

  ; write() from stack-allocated buffer
  mov.b rax,1
  mov.qreg.qimm rdi, 1
  mov.qreg.qreg rsi, rsp
  mov.qreg.qimm rdx, 0x78
  syscall

  ; write() the machine code by using self-reference
  ;
  ; TODO do this in a "real" quine way
  mov.b rax, 1
  mov.qreg.qimm rdi, 1
  mov.qreg.qimm rsi, elf_header + 0x78
  mov.qreg.qimm rdx, file_size - 0x78
  syscall

  ;;;
  ;;; Clean up.
  ;;;

  ; exit()
  mov.b rax, 60
  mov.b rdi, 0
  syscall

file_size = $ - $$