Better range checks in the assembler
[bpt/guile.git] / module / system / vm / assembler.scm
1 ;;; Guile RTL assembler
2
3 ;;; Copyright (C) 2001, 2009, 2010, 2012, 2013 Free Software Foundation, Inc.
4 ;;;
5 ;;; This library is free software; you can redistribute it and/or
6 ;;; modify it under the terms of the GNU Lesser General Public
7 ;;; License as published by the Free Software Foundation; either
8 ;;; version 3 of the License, or (at your option) any later version.
9 ;;;
10 ;;; This library is distributed in the hope that it will be useful,
11 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 ;;; Lesser General Public License for more details.
14 ;;;
15 ;;; You should have received a copy of the GNU Lesser General Public
16 ;;; License along with this library; if not, write to the Free Software
17 ;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
19 ;;; Commentary:
20 ;;;
21 ;;; This module implements an assembler that creates an ELF image from
22 ;;; RTL assembly and macro-assembly. The input can be given in
23 ;;; s-expression form, like ((OP ARG ...) ...). Internally there is a
24 ;;; procedural interface, the emit-OP procedures, but that is not
25 ;;; currently exported.
26 ;;;
27 ;;; "Primitive instructions" correspond to RTL VM operations.
28 ;;; Assemblers for primitive instructions are generated programmatically
29 ;;; from (rtl-instruction-list), which itself is derived from the VM
30 ;;; sources. There are also "macro-instructions" like "label" or
31 ;;; "load-constant" that expand to 0 or more primitive instructions.
32 ;;;
33 ;;; The assembler also handles some higher-level tasks, like creating
34 ;;; the symbol table, other metadata sections, creating a constant table
35 ;;; for the whole compilation unit, and writing the dynamic section of
36 ;;; the ELF file along with the appropriate initialization routines.
37 ;;;
38 ;;; Most compilers will want to use the trio of make-assembler,
39 ;;; emit-text, and link-assembly. That will result in the creation of
40 ;;; an ELF image as a bytevector, which can then be loaded using
41 ;;; load-thunk-from-memory, or written to disk as a .go file.
42 ;;;
43 ;;; Code:
44
45 (define-module (system vm assembler)
46 #:use-module (system base target)
47 #:use-module (system vm instruction)
48 #:use-module (system vm dwarf)
49 #:use-module (system vm elf)
50 #:use-module (system vm linker)
51 #:use-module (system vm objcode)
52 #:use-module (rnrs bytevectors)
53 #:use-module (ice-9 binary-ports)
54 #:use-module (ice-9 vlist)
55 #:use-module (ice-9 match)
56 #:use-module (srfi srfi-1)
57 #:use-module (srfi srfi-4)
58 #:use-module (srfi srfi-9)
59 #:use-module (srfi srfi-11)
60 #:export (make-assembler
61 emit-text
62 link-assembly
63 assemble-program))
64
65
66 \f
67
68 ;;; RTL code consists of 32-bit units, often subdivided in some way.
69 ;;; These helpers create one 32-bit unit from multiple components.
70
71 (define-inlinable (pack-u8-u24 x y)
72 (unless (<= 0 x 255)
73 (error "out of range" x))
74 (logior x (ash y 8)))
75
76 (define-inlinable (pack-u8-s24 x y)
77 (unless (<= 0 x 255)
78 (error "out of range" x))
79 (logior x (ash (cond
80 ((< 0 (- y) #x800000)
81 (+ y #x1000000))
82 ((<= 0 y #xffffff)
83 y)
84 (else (error "out of range" y)))
85 8)))
86
87 (define-inlinable (pack-u1-u7-u24 x y z)
88 (unless (<= 0 x 1)
89 (error "out of range" x))
90 (unless (<= 0 y 127)
91 (error "out of range" y))
92 (logior x (ash y 1) (ash z 8)))
93
94 (define-inlinable (pack-u8-u12-u12 x y z)
95 (unless (<= 0 x 255)
96 (error "out of range" x))
97 (unless (<= 0 y 4095)
98 (error "out of range" y))
99 (logior x (ash y 8) (ash z 20)))
100
101 (define-inlinable (pack-u8-u8-u16 x y z)
102 (unless (<= 0 x 255)
103 (error "out of range" x))
104 (unless (<= 0 y 255)
105 (error "out of range" y))
106 (logior x (ash y 8) (ash z 16)))
107
108 (define-inlinable (pack-u8-u8-u8-u8 x y z w)
109 (unless (<= 0 x 255)
110 (error "out of range" x))
111 (unless (<= 0 y 255)
112 (error "out of range" y))
113 (unless (<= 0 z 255)
114 (error "out of range" z))
115 (logior x (ash y 8) (ash z 16) (ash w 24)))
116
117 (define-syntax pack-flags
118 (syntax-rules ()
119 ;; Add clauses as needed.
120 ((pack-flags f1 f2) (logior (if f1 (ash 1 0) 0)
121 (if f2 (ash 2 0) 0)))))
122
123 ;;; Helpers to read and write 32-bit units in a buffer.
124
125 (define-syntax-rule (u32-ref buf n)
126 (bytevector-u32-native-ref buf (* n 4)))
127
128 (define-syntax-rule (u32-set! buf n val)
129 (bytevector-u32-native-set! buf (* n 4) val))
130
131 (define-syntax-rule (s32-ref buf n)
132 (bytevector-s32-native-ref buf (* n 4)))
133
134 (define-syntax-rule (s32-set! buf n val)
135 (bytevector-s32-native-set! buf (* n 4) val))
136
137
138 \f
139
140 ;;; A <meta> entry collects metadata for one procedure. Procedures are
141 ;;; written as contiguous ranges of RTL code.
142 ;;;
143 (define-syntax-rule (assert-match arg pattern kind)
144 (let ((x arg))
145 (unless (match x (pattern #t) (_ #f))
146 (error (string-append "expected " kind) x))))
147
148 (define-record-type <meta>
149 (%make-meta label properties low-pc high-pc arities)
150 meta?
151 (label meta-label)
152 (properties meta-properties set-meta-properties!)
153 (low-pc meta-low-pc)
154 (high-pc meta-high-pc set-meta-high-pc!)
155 (arities meta-arities set-meta-arities!))
156
157 (define (make-meta label properties low-pc)
158 (assert-match label (? symbol?) "symbol")
159 (assert-match properties (((? symbol?) . _) ...) "alist with symbolic keys")
160 (%make-meta label properties low-pc #f '()))
161
162 (define (meta-name meta)
163 (assq-ref (meta-properties meta) 'name))
164
165 ;; Metadata for one <lambda-case>.
166 (define-record-type <arity>
167 (make-arity req opt rest kw-indices allow-other-keys?
168 low-pc high-pc)
169 arity?
170 (req arity-req)
171 (opt arity-opt)
172 (rest arity-rest)
173 (kw-indices arity-kw-indices)
174 (allow-other-keys? arity-allow-other-keys?)
175 (low-pc arity-low-pc)
176 (high-pc arity-high-pc set-arity-high-pc!))
177
178 (define-syntax *block-size* (identifier-syntax 32))
179
180 ;;; An assembler collects all of the words emitted during assembly, and
181 ;;; also maintains ancillary information such as the constant table, a
182 ;;; relocation list, and so on.
183 ;;;
184 ;;; RTL code consists of 32-bit units. We emit RTL code using native
185 ;;; endianness. If we're targeting a foreign endianness, we byte-swap
186 ;;; the bytevector as a whole instead of conditionalizing each access.
187 ;;;
188 (define-record-type <asm>
189 (make-asm cur idx start prev written
190 labels relocs
191 word-size endianness
192 constants inits
193 shstrtab next-section-number
194 meta sources)
195 asm?
196
197 ;; We write RTL code into what is logically a growable vector,
198 ;; implemented as a list of blocks. asm-cur is the current block, and
199 ;; asm-idx is the current index into that block, in 32-bit units.
200 ;;
201 (cur asm-cur set-asm-cur!)
202 (idx asm-idx set-asm-idx!)
203
204 ;; asm-start is an absolute position, indicating the offset of the
205 ;; beginning of an instruction (in u32 units). It is updated after
206 ;; writing all the words for one primitive instruction. It models the
207 ;; position of the instruction pointer during execution, given that
208 ;; the RTL VM updates the IP only at the end of executing the
209 ;; instruction, and is thus useful for computing offsets between two
210 ;; points in a program.
211 ;;
212 (start asm-start set-asm-start!)
213
214 ;; The list of previously written blocks.
215 ;;
216 (prev asm-prev set-asm-prev!)
217
218 ;; The number of u32 words written in asm-prev, which is the same as
219 ;; the offset of the current block.
220 ;;
221 (written asm-written set-asm-written!)
222
223 ;; An alist of symbol -> position pairs, indicating the labels defined
224 ;; in this compilation unit.
225 ;;
226 (labels asm-labels set-asm-labels!)
227
228 ;; A list of relocations needed by the program text. We use an
229 ;; internal representation for relocations, and handle textualn
230 ;; relative relocations in the assembler. Other kinds of relocations
231 ;; are later reified as linker relocations and resolved by the linker.
232 ;;
233 (relocs asm-relocs set-asm-relocs!)
234
235 ;; Target information.
236 ;;
237 (word-size asm-word-size)
238 (endianness asm-endianness)
239
240 ;; The constant table, as a vhash of object -> label. All constants
241 ;; get de-duplicated and written into separate sections -- either the
242 ;; .rodata section, for read-only data, or .data, for constants that
243 ;; need initialization at load-time (like symbols). Constants can
244 ;; depend on other constants (e.g. a symbol depending on a stringbuf),
245 ;; so order in this table is important.
246 ;;
247 (constants asm-constants set-asm-constants!)
248
249 ;; A list of RTL instructions needed to initialize the constants.
250 ;; Will run in a thunk with 2 local variables.
251 ;;
252 (inits asm-inits set-asm-inits!)
253
254 ;; The shstrtab, for section names.
255 ;;
256 (shstrtab asm-shstrtab set-asm-shstrtab!)
257
258 ;; The section number for the next section to be written.
259 ;;
260 (next-section-number asm-next-section-number set-asm-next-section-number!)
261
262 ;; A list of <meta>, corresponding to procedure metadata.
263 ;;
264 (meta asm-meta set-asm-meta!)
265
266 ;; A list of (pos . source) pairs, indicating source information. POS
267 ;; is relative to the beginning of the text section, and SOURCE is in
268 ;; the same format that source-properties returns.
269 ;;
270 (sources asm-sources set-asm-sources!))
271
272 (define-inlinable (fresh-block)
273 (make-u32vector *block-size*))
274
275 (define* (make-assembler #:key (word-size (target-word-size))
276 (endianness (target-endianness)))
277 "Create an assembler for a given target @var{word-size} and
278 @var{endianness}, falling back to appropriate values for the configured
279 target."
280 (make-asm (fresh-block) 0 0 '() 0
281 '() '()
282 word-size endianness
283 vlist-null '()
284 (make-string-table) 1
285 '() '()))
286
287 (define (intern-section-name! asm string)
288 "Add a string to the section name table (shstrtab)."
289 (string-table-intern! (asm-shstrtab asm) string))
290
291 (define-inlinable (asm-pos asm)
292 "The offset of the next word to be written into the code buffer, in
293 32-bit units."
294 (+ (asm-idx asm) (asm-written asm)))
295
296 (define (allocate-new-block asm)
297 "Close off the current block, and arrange for the next word to be
298 written to a fresh block."
299 (let ((new (fresh-block)))
300 (set-asm-prev! asm (cons (asm-cur asm) (asm-prev asm)))
301 (set-asm-written! asm (asm-pos asm))
302 (set-asm-cur! asm new)
303 (set-asm-idx! asm 0)))
304
305 (define-inlinable (emit asm u32)
306 "Emit one 32-bit word into the instruction stream. Assumes that there
307 is space for the word, and ensures that there is space for the next
308 word."
309 (u32-set! (asm-cur asm) (asm-idx asm) u32)
310 (set-asm-idx! asm (1+ (asm-idx asm)))
311 (if (= (asm-idx asm) *block-size*)
312 (allocate-new-block asm)))
313
314 (define-inlinable (make-reloc type label base word)
315 "Make an internal relocation of type @var{type} referencing symbol
316 @var{label}, @var{word} words after position @var{start}. @var{type}
317 may be x8-s24, indicating a 24-bit relative label reference that can be
318 fixed up by the assembler, or s32, indicating a 32-bit relative
319 reference that needs to be fixed up by the linker."
320 (list type label base word))
321
322 (define-inlinable (reset-asm-start! asm)
323 "Reset the asm-start after writing the words for one instruction."
324 (set-asm-start! asm (asm-pos asm)))
325
326 (define (emit-exported-label asm label)
327 "Define a linker symbol associating @var{label} with the current
328 asm-start."
329 (set-asm-labels! asm (acons label (asm-start asm) (asm-labels asm))))
330
331 (define (record-label-reference asm label)
332 "Record an x8-s24 local label reference. This value will get patched
333 up later by the assembler."
334 (let* ((start (asm-start asm))
335 (pos (asm-pos asm))
336 (reloc (make-reloc 'x8-s24 label start (- pos start))))
337 (set-asm-relocs! asm (cons reloc (asm-relocs asm)))))
338
339 (define* (record-far-label-reference asm label #:optional (offset 0))
340 "Record an s32 far label reference. This value will get patched up
341 later by the linker."
342 (let* ((start (- (asm-start asm) offset))
343 (pos (asm-pos asm))
344 (reloc (make-reloc 's32 label start (- pos start))))
345 (set-asm-relocs! asm (cons reloc (asm-relocs asm)))))
346
347
348 \f
349
350 ;;;
351 ;;; Primitive assemblers are defined by expanding `assembler' for each
352 ;;; opcode in `(rtl-instruction-list)'.
353 ;;;
354
355 (eval-when (expand compile load eval)
356 (define (id-append ctx a b)
357 (datum->syntax ctx (symbol-append (syntax->datum a) (syntax->datum b)))))
358
359 (define-syntax assembler
360 (lambda (x)
361 (define-syntax op-case
362 (lambda (x)
363 (syntax-case x ()
364 ((_ asm name ((type arg ...) code ...) clause ...)
365 #`(if (eq? name 'type)
366 (with-syntax (((arg ...) (generate-temporaries #'(arg ...))))
367 #'((arg ...)
368 code ...))
369 (op-case asm name clause ...)))
370 ((_ asm name)
371 #'(error "unmatched name" name)))))
372
373 (define (pack-first-word asm opcode type)
374 (with-syntax ((opcode opcode))
375 (op-case
376 asm type
377 ((U8_X24)
378 (emit asm opcode))
379 ((U8_U24 arg)
380 (emit asm (pack-u8-u24 opcode arg)))
381 ((U8_L24 label)
382 (record-label-reference asm label)
383 (emit asm opcode))
384 ((U8_U8_I16 a imm)
385 (emit asm (pack-u8-u8-u16 opcode a (object-address imm))))
386 ((U8_U12_U12 a b)
387 (emit asm (pack-u8-u12-u12 opcode a b)))
388 ((U8_U8_U8_U8 a b c)
389 (emit asm (pack-u8-u8-u8-u8 opcode a b c))))))
390
391 (define (pack-tail-word asm type)
392 (op-case
393 asm type
394 ((U8_U24 a b)
395 (emit asm (pack-u8-u24 a b)))
396 ((U8_L24 a label)
397 (record-label-reference asm label)
398 (emit asm a))
399 ((U8_U8_I16 a b imm)
400 (emit asm (pack-u8-u8-u16 a b (object-address imm))))
401 ((U8_U12_U12 a b)
402 (emit asm (pack-u8-u12-u12 a b c)))
403 ((U8_U8_U8_U8 a b c d)
404 (emit asm (pack-u8-u8-u8-u8 a b c d)))
405 ((U32 a)
406 (emit asm a))
407 ((I32 imm)
408 (let ((val (object-address imm)))
409 (unless (zero? (ash val -32))
410 (error "FIXME: enable truncation of negative fixnums when cross-compiling"))
411 (emit asm val)))
412 ((A32 imm)
413 (unless (= (asm-word-size asm) 8)
414 (error "make-long-immediate unavailable for this target"))
415 (emit asm (ash (object-address imm) -32))
416 (emit asm (logand (object-address imm) (1- (ash 1 32)))))
417 ((B32))
418 ((N32 label)
419 (record-far-label-reference asm label)
420 (emit asm 0))
421 ((S32 label)
422 (record-far-label-reference asm label)
423 (emit asm 0))
424 ((L32 label)
425 (record-far-label-reference asm label)
426 (emit asm 0))
427 ((LO32 label offset)
428 (record-far-label-reference asm label
429 (* offset (/ (asm-word-size asm) 4)))
430 (emit asm 0))
431 ((X8_U24 a)
432 (emit asm (pack-u8-u24 0 a)))
433 ((X8_U12_U12 a b)
434 (emit asm (pack-u8-u12-u12 0 a b)))
435 ((X8_L24 label)
436 (record-label-reference asm label)
437 (emit asm 0))
438 ((B1_X7_L24 a label)
439 (record-label-reference asm label)
440 (emit asm (pack-u1-u7-u24 (if a 1 0) 0 0)))
441 ((B1_U7_L24 a b label)
442 (record-label-reference asm label)
443 (emit asm (pack-u1-u7-u24 (if a 1 0) b 0)))
444 ((B1_X31 a)
445 (emit asm (pack-u1-u7-u24 (if a 1 0) 0 0)))
446 ((B1_X7_U24 a b)
447 (emit asm (pack-u1-u7-u24 (if a 1 0) 0 b)))))
448
449 (syntax-case x ()
450 ((_ name opcode word0 word* ...)
451 (with-syntax ((((formal0 ...)
452 code0 ...)
453 (pack-first-word #'asm
454 (syntax->datum #'opcode)
455 (syntax->datum #'word0)))
456 ((((formal* ...)
457 code* ...) ...)
458 (map (lambda (word) (pack-tail-word #'asm word))
459 (syntax->datum #'(word* ...)))))
460 #'(lambda (asm formal0 ... formal* ... ...)
461 (unless (asm? asm) (error "not an asm"))
462 code0 ...
463 code* ... ...
464 (reset-asm-start! asm)))))))
465
466 (define assemblers (make-hash-table))
467
468 (define-syntax define-assembler
469 (lambda (x)
470 (syntax-case x ()
471 ((_ name opcode kind arg ...)
472 (with-syntax ((emit (id-append #'name #'emit- #'name)))
473 #'(begin
474 (define emit
475 (let ((emit (assembler name opcode arg ...)))
476 (hashq-set! assemblers 'name emit)
477 emit))
478 (export emit)))))))
479
480 (define-syntax visit-opcodes
481 (lambda (x)
482 (syntax-case x ()
483 ((visit-opcodes macro arg ...)
484 (with-syntax (((inst ...)
485 (map (lambda (x) (datum->syntax #'macro x))
486 (rtl-instruction-list))))
487 #'(begin
488 (macro arg ... . inst)
489 ...))))))
490
491 (visit-opcodes define-assembler)
492
493 (define (emit-text asm instructions)
494 "Assemble @var{instructions} using the assembler @var{asm}.
495 @var{instructions} is a sequence of RTL instructions, expressed as a
496 list of lists. This procedure can be called many times before calling
497 @code{link-assembly}."
498 (for-each (lambda (inst)
499 (apply (or (hashq-ref assemblers (car inst))
500 (error 'bad-instruction inst))
501 asm
502 (cdr inst)))
503 instructions))
504
505 \f
506
507 ;;;
508 ;;; The constant table records a topologically sorted set of literal
509 ;;; constants used by a program. For example, a pair uses its car and
510 ;;; cdr, a string uses its stringbuf, etc.
511 ;;;
512 ;;; Some things we want to add to the constant table are not actually
513 ;;; Scheme objects: for example, stringbufs, cache cells for toplevel
514 ;;; references, or cache cells for non-closure procedures. For these we
515 ;;; define special record types and add instances of those record types
516 ;;; to the table.
517 ;;;
518
519 (define-inlinable (immediate? x)
520 "Return @code{#t} if @var{x} is immediate, and @code{#f} otherwise."
521 (not (zero? (logand (object-address x) 6))))
522
523 (define-record-type <stringbuf>
524 (make-stringbuf string)
525 stringbuf?
526 (string stringbuf-string))
527
528 (define-record-type <static-procedure>
529 (make-static-procedure code)
530 static-procedure?
531 (code static-procedure-code))
532
533 (define-record-type <uniform-vector-backing-store>
534 (make-uniform-vector-backing-store bytes)
535 uniform-vector-backing-store?
536 (bytes uniform-vector-backing-store-bytes))
537
538 (define-record-type <cache-cell>
539 (make-cache-cell scope key)
540 cache-cell?
541 (scope cache-cell-scope)
542 (key cache-cell-key))
543
544 (define (simple-vector? obj)
545 (and (vector? obj)
546 (equal? (array-shape obj) (list (list 0 (1- (vector-length obj)))))))
547
548 (define (simple-uniform-vector? obj)
549 (and (array? obj)
550 (symbol? (array-type obj))
551 (equal? (array-shape obj) (list (list 0 (1- (array-length obj)))))))
552
553 (define (statically-allocatable? x)
554 "Return @code{#t} if a non-immediate constant can be allocated
555 statically, and @code{#f} if it would need some kind of runtime
556 allocation."
557 (or (pair? x) (string? x) (stringbuf? x) (static-procedure? x) (array? x)))
558
559 (define (intern-constant asm obj)
560 "Add an object to the constant table, and return a label that can be
561 used to reference it. If the object is already present in the constant
562 table, its existing label is used directly."
563 (define (recur obj)
564 (intern-constant asm obj))
565 (define (field dst n obj)
566 (let ((src (recur obj)))
567 (if src
568 (if (statically-allocatable? obj)
569 `((static-patch! ,dst ,n ,src))
570 `((static-ref 1 ,src)
571 (static-set! 1 ,dst ,n)))
572 '())))
573 (define (intern obj label)
574 (cond
575 ((pair? obj)
576 (append (field label 0 (car obj))
577 (field label 1 (cdr obj))))
578 ((simple-vector? obj)
579 (let lp ((i 0) (inits '()))
580 (if (< i (vector-length obj))
581 (lp (1+ i)
582 (append-reverse (field label (1+ i) (vector-ref obj i))
583 inits))
584 (reverse inits))))
585 ((stringbuf? obj) '())
586 ((static-procedure? obj)
587 `((static-patch! ,label 1 ,(static-procedure-code obj))))
588 ((cache-cell? obj) '())
589 ((symbol? obj)
590 `((make-non-immediate 1 ,(recur (symbol->string obj)))
591 (string->symbol 1 1)
592 (static-set! 1 ,label 0)))
593 ((string? obj)
594 `((static-patch! ,label 1 ,(recur (make-stringbuf obj)))))
595 ((keyword? obj)
596 `((static-ref 1 ,(recur (keyword->symbol obj)))
597 (symbol->keyword 1 1)
598 (static-set! 1 ,label 0)))
599 ((number? obj)
600 `((make-non-immediate 1 ,(recur (number->string obj)))
601 (string->number 1 1)
602 (static-set! 1 ,label 0)))
603 ((uniform-vector-backing-store? obj) '())
604 ((simple-uniform-vector? obj)
605 `((static-patch! ,label 2
606 ,(recur (make-uniform-vector-backing-store obj)))))
607 (else
608 (error "don't know how to intern" obj))))
609 (cond
610 ((immediate? obj) #f)
611 ((vhash-assoc obj (asm-constants asm)) => cdr)
612 (else
613 ;; Note that calling intern may mutate asm-constants and
614 ;; asm-constant-inits.
615 (let* ((label (gensym "constant"))
616 (inits (intern obj label)))
617 (set-asm-constants! asm (vhash-cons obj label (asm-constants asm)))
618 (set-asm-inits! asm (append-reverse inits (asm-inits asm)))
619 label))))
620
621 (define (intern-non-immediate asm obj)
622 "Intern a non-immediate into the constant table, and return its
623 label."
624 (when (immediate? obj)
625 (error "expected a non-immediate" obj))
626 (intern-constant asm obj))
627
628 (define (intern-cache-cell asm scope key)
629 "Intern a cache cell into the constant table, and return its label.
630 If there is already a cache cell with the given scope and key, it is
631 returned instead."
632 (intern-constant asm (make-cache-cell scope key)))
633
634 ;; Return the label of the cell that holds the module for a scope.
635 (define (intern-module-cache-cell asm scope)
636 "Intern a cache cell for a module, and return its label."
637 (intern-cache-cell asm scope #t))
638
639
640 \f
641
642 ;;;
643 ;;; Macro assemblers bridge the gap between primitive instructions and
644 ;;; some higher-level operations.
645 ;;;
646
647 (define-syntax define-macro-assembler
648 (lambda (x)
649 (syntax-case x ()
650 ((_ (name arg ...) body body* ...)
651 (with-syntax ((emit (id-append #'name #'emit- #'name)))
652 #'(begin
653 (define emit
654 (let ((emit (lambda (arg ...) body body* ...)))
655 (hashq-set! assemblers 'name emit)
656 emit))
657 (export emit)))))))
658
659 (define-macro-assembler (load-constant asm dst obj)
660 (cond
661 ((immediate? obj)
662 (let ((bits (object-address obj)))
663 (cond
664 ((and (< dst 256) (zero? (ash bits -16)))
665 (emit-make-short-immediate asm dst obj))
666 ((zero? (ash bits -32))
667 (emit-make-long-immediate asm dst obj))
668 (else
669 (emit-make-long-long-immediate asm dst obj)))))
670 ((statically-allocatable? obj)
671 (emit-make-non-immediate asm dst (intern-non-immediate asm obj)))
672 (else
673 (emit-static-ref asm dst (intern-non-immediate asm obj)))))
674
675 (define-macro-assembler (load-static-procedure asm dst label)
676 (let ((loc (intern-constant asm (make-static-procedure label))))
677 (emit-make-non-immediate asm dst loc)))
678
679 (define-syntax-rule (define-tc7-macro-assembler name tc7)
680 (define-macro-assembler (name asm slot invert? label)
681 (emit-br-if-tc7 asm slot invert? tc7 label)))
682
683 ;; Keep in sync with tags.h. Part of Guile's ABI. Currently unused
684 ;; macro assemblers are commented out. See also
685 ;; *branching-primcall-arities* in (language cps primitives), the set of
686 ;; macro-instructions in assembly.scm, and
687 ;; disassembler.scm:code-annotation.
688 ;;
689 ;; FIXME: Define all tc7 values in Scheme in one place, derived from
690 ;; tags.h.
691 (define-tc7-macro-assembler br-if-symbol 5)
692 (define-tc7-macro-assembler br-if-variable 7)
693 (define-tc7-macro-assembler br-if-vector 13)
694 ;(define-tc7-macro-assembler br-if-weak-vector 13)
695 (define-tc7-macro-assembler br-if-string 21)
696 ;(define-tc7-macro-assembler br-if-heap-number 23)
697 ;(define-tc7-macro-assembler br-if-stringbuf 39)
698 (define-tc7-macro-assembler br-if-bytevector 77)
699 ;(define-tc7-macro-assembler br-if-pointer 31)
700 ;(define-tc7-macro-assembler br-if-hashtable 29)
701 ;(define-tc7-macro-assembler br-if-fluid 37)
702 ;(define-tc7-macro-assembler br-if-dynamic-state 45)
703 ;(define-tc7-macro-assembler br-if-frame 47)
704 ;(define-tc7-macro-assembler br-if-objcode 53)
705 ;(define-tc7-macro-assembler br-if-vm 55)
706 ;(define-tc7-macro-assembler br-if-vm-cont 71)
707 ;(define-tc7-macro-assembler br-if-rtl-program 69)
708 ;(define-tc7-macro-assembler br-if-program 79)
709 ;(define-tc7-macro-assembler br-if-weak-set 85)
710 ;(define-tc7-macro-assembler br-if-weak-table 87)
711 ;(define-tc7-macro-assembler br-if-array 93)
712 ;(define-tc7-macro-assembler br-if-bitvector 95)
713 ;(define-tc7-macro-assembler br-if-port 125)
714 ;(define-tc7-macro-assembler br-if-smob 127)
715
716 (define-macro-assembler (begin-program asm label properties)
717 (emit-label asm label)
718 (let ((meta (make-meta label properties (asm-start asm))))
719 (set-asm-meta! asm (cons meta (asm-meta asm)))))
720
721 (define-macro-assembler (end-program asm)
722 (let ((meta (car (asm-meta asm))))
723 (set-meta-high-pc! meta (asm-start asm))
724 (set-meta-arities! meta (reverse (meta-arities meta)))))
725
726 (define-macro-assembler (begin-standard-arity asm req nlocals alternate)
727 (emit-begin-opt-arity asm req '() #f nlocals alternate))
728
729 (define-macro-assembler (begin-opt-arity asm req opt rest nlocals alternate)
730 (emit-begin-kw-arity asm req opt rest '() #f nlocals alternate))
731
732 (define-macro-assembler (begin-kw-arity asm req opt rest kw-indices
733 allow-other-keys? nlocals alternate)
734 (assert-match req ((? symbol?) ...) "list of symbols")
735 (assert-match opt ((? symbol?) ...) "list of symbols")
736 (assert-match rest (or #f (? symbol?)) "#f or symbol")
737 (assert-match kw-indices (((? keyword?) . (? integer?)) ...)
738 "alist of keyword -> integer")
739 (assert-match allow-other-keys? (? boolean?) "boolean")
740 (assert-match nlocals (? integer?) "integer")
741 (assert-match alternate (or #f (? symbol?)) "#f or symbol")
742 (let* ((meta (car (asm-meta asm)))
743 (arity (make-arity req opt rest kw-indices allow-other-keys?
744 (asm-start asm) #f))
745 ;; The procedure itself is in slot 0, in the standard calling
746 ;; convention. For procedure prologues, nreq includes the
747 ;; procedure, so here we add 1.
748 (nreq (1+ (length req)))
749 (nopt (length opt))
750 (rest? (->bool rest)))
751 (set-meta-arities! meta (cons arity (meta-arities meta)))
752 (cond
753 ((or allow-other-keys? (pair? kw-indices))
754 (emit-kw-prelude asm nreq nopt rest? kw-indices allow-other-keys?
755 nlocals alternate))
756 ((or rest? (pair? opt))
757 (emit-opt-prelude asm nreq nopt rest? nlocals alternate))
758 (else
759 (emit-standard-prelude asm nreq nlocals alternate)))))
760
761 (define-macro-assembler (end-arity asm)
762 (let ((arity (car (meta-arities (car (asm-meta asm))))))
763 (set-arity-high-pc! arity (asm-start asm))))
764
765 (define-macro-assembler (standard-prelude asm nreq nlocals alternate)
766 (cond
767 (alternate
768 (emit-br-if-nargs-ne asm nreq alternate)
769 (emit-alloc-frame asm nlocals))
770 ((and (< nreq (ash 1 12)) (< (- nlocals nreq) (ash 1 12)))
771 (emit-assert-nargs-ee/locals asm nreq (- nlocals nreq)))
772 (else
773 (emit-assert-nargs-ee asm nreq)
774 (emit-alloc-frame asm nlocals))))
775
776 (define-macro-assembler (opt-prelude asm nreq nopt rest? nlocals alternate)
777 (if alternate
778 (emit-br-if-nargs-lt asm nreq alternate)
779 (emit-assert-nargs-ge asm nreq))
780 (cond
781 (rest?
782 (emit-bind-rest asm (+ nreq nopt)))
783 (alternate
784 (emit-br-if-nargs-gt asm (+ nreq nopt) alternate))
785 (else
786 (emit-assert-nargs-le asm (+ nreq nopt))))
787 (emit-alloc-frame asm nlocals))
788
789 (define-macro-assembler (kw-prelude asm nreq nopt rest? kw-indices
790 allow-other-keys? nlocals alternate)
791 (if alternate
792 (emit-br-if-nargs-lt asm nreq alternate)
793 (emit-assert-nargs-ge asm nreq))
794 (let ((ntotal (fold (lambda (kw ntotal)
795 (match kw
796 (((? keyword?) . idx)
797 (max (1+ idx) ntotal))))
798 (+ nreq nopt) kw-indices)))
799 ;; FIXME: port 581f410f
800 (emit-bind-kwargs asm nreq
801 (pack-flags allow-other-keys? rest?)
802 (+ nreq nopt)
803 ntotal
804 (intern-constant asm kw-indices))
805 (emit-alloc-frame asm nlocals)))
806
807 (define-macro-assembler (label asm sym)
808 (set-asm-labels! asm (acons sym (asm-start asm) (asm-labels asm))))
809
810 (define-macro-assembler (source asm source)
811 (set-asm-sources! asm (acons (asm-start asm) source (asm-sources asm))))
812
813 (define-macro-assembler (cache-current-module! asm module scope)
814 (let ((mod-label (intern-module-cache-cell asm scope)))
815 (emit-static-set! asm module mod-label 0)))
816
817 (define-macro-assembler (cached-toplevel-box asm dst scope sym bound?)
818 (let ((sym-label (intern-non-immediate asm sym))
819 (mod-label (intern-module-cache-cell asm scope))
820 (cell-label (intern-cache-cell asm scope sym)))
821 (emit-toplevel-box asm dst cell-label mod-label sym-label bound?)))
822
823 (define-macro-assembler (cached-module-box asm dst module-name sym public? bound?)
824 (let* ((sym-label (intern-non-immediate asm sym))
825 (key (cons public? module-name))
826 (mod-name-label (intern-constant asm key))
827 (cell-label (intern-cache-cell asm key sym)))
828 (emit-module-box asm dst cell-label mod-name-label sym-label bound?)))
829
830
831 \f
832
833 ;;;
834 ;;; Helper for linking objects.
835 ;;;
836
837 (define (make-object asm name bv relocs labels . kwargs)
838 "Make a linker object. This helper handles interning the name in the
839 shstrtab, assigning the size, allocating a fresh index, and defining a
840 corresponding linker symbol for the start of the section."
841 (let ((name-idx (intern-section-name! asm (symbol->string name)))
842 (index (asm-next-section-number asm)))
843 (set-asm-next-section-number! asm (1+ index))
844 (make-linker-object (apply make-elf-section
845 #:index index
846 #:name name-idx
847 #:size (bytevector-length bv)
848 kwargs)
849 bv relocs
850 (cons (make-linker-symbol name 0) labels))))
851
852
853 \f
854
855 ;;;
856 ;;; Linking the constant table. This code is somewhat intertwingled
857 ;;; with the intern-constant code above, as that procedure also
858 ;;; residualizes instructions to initialize constants at load time.
859 ;;;
860
861 (define (write-immediate asm buf pos x)
862 (let ((val (object-address x))
863 (endianness (asm-endianness asm)))
864 (case (asm-word-size asm)
865 ((4) (bytevector-u32-set! buf pos val endianness))
866 ((8) (bytevector-u64-set! buf pos val endianness))
867 (else (error "bad word size" asm)))))
868
869 (define (emit-init-constants asm)
870 "If there is writable data that needs initialization at runtime, emit
871 a procedure to do that and return its label. Otherwise return
872 @code{#f}."
873 (let ((inits (asm-inits asm)))
874 (and (not (null? inits))
875 (let ((label (gensym "init-constants")))
876 (emit-text asm
877 `((begin-program ,label ())
878 (assert-nargs-ee/locals 1 1)
879 ,@(reverse inits)
880 (load-constant 1 ,*unspecified*)
881 (return 1)
882 (end-program)))
883 label))))
884
885 (define (link-data asm data name)
886 "Link the static data for a program into the @var{name} section (which
887 should be .data or .rodata), and return the resulting linker object.
888 @var{data} should be a vhash mapping objects to labels."
889 (define (align address alignment)
890 (+ address
891 (modulo (- alignment (modulo address alignment)) alignment)))
892
893 (define tc7-vector 13)
894 (define stringbuf-shared-flag #x100)
895 (define stringbuf-wide-flag #x400)
896 (define tc7-stringbuf 39)
897 (define tc7-narrow-stringbuf
898 (+ tc7-stringbuf stringbuf-shared-flag))
899 (define tc7-wide-stringbuf
900 (+ tc7-stringbuf stringbuf-shared-flag stringbuf-wide-flag))
901 (define tc7-ro-string (+ 21 #x200))
902 (define tc7-rtl-program 69)
903 (define tc7-bytevector 77)
904
905 (let ((word-size (asm-word-size asm))
906 (endianness (asm-endianness asm)))
907 (define (byte-length x)
908 (cond
909 ((stringbuf? x)
910 (let ((x (stringbuf-string x)))
911 (+ (* 2 word-size)
912 (case (string-bytes-per-char x)
913 ((1) (1+ (string-length x)))
914 ((4) (* (1+ (string-length x)) 4))
915 (else (error "bad string bytes per char" x))))))
916 ((static-procedure? x)
917 (* 2 word-size))
918 ((string? x)
919 (* 4 word-size))
920 ((pair? x)
921 (* 2 word-size))
922 ((simple-vector? x)
923 (* (1+ (vector-length x)) word-size))
924 ((simple-uniform-vector? x)
925 (* 4 word-size))
926 ((uniform-vector-backing-store? x)
927 (bytevector-length (uniform-vector-backing-store-bytes x)))
928 (else
929 word-size)))
930
931 (define (write-constant-reference buf pos x)
932 ;; The asm-inits will fix up any reference to a non-immediate.
933 (write-immediate asm buf pos (if (immediate? x) x #f)))
934
935 (define (write buf pos obj)
936 (cond
937 ((stringbuf? obj)
938 (let* ((x (stringbuf-string obj))
939 (len (string-length x))
940 (tag (if (= (string-bytes-per-char x) 1)
941 tc7-narrow-stringbuf
942 tc7-wide-stringbuf)))
943 (case word-size
944 ((4)
945 (bytevector-u32-set! buf pos tag endianness)
946 (bytevector-u32-set! buf (+ pos 4) len endianness))
947 ((8)
948 (bytevector-u64-set! buf pos tag endianness)
949 (bytevector-u64-set! buf (+ pos 8) len endianness))
950 (else
951 (error "bad word size" asm)))
952 (let ((pos (+ pos (* word-size 2))))
953 (case (string-bytes-per-char x)
954 ((1)
955 (let lp ((i 0))
956 (if (< i len)
957 (let ((u8 (char->integer (string-ref x i))))
958 (bytevector-u8-set! buf (+ pos i) u8)
959 (lp (1+ i)))
960 (bytevector-u8-set! buf (+ pos i) 0))))
961 ((4)
962 (let lp ((i 0))
963 (if (< i len)
964 (let ((u32 (char->integer (string-ref x i))))
965 (bytevector-u32-set! buf (+ pos (* i 4)) u32 endianness)
966 (lp (1+ i)))
967 (bytevector-u32-set! buf (+ pos (* i 4)) 0 endianness))))
968 (else (error "bad string bytes per char" x))))))
969
970 ((static-procedure? obj)
971 (case word-size
972 ((4)
973 (bytevector-u32-set! buf pos tc7-rtl-program endianness)
974 (bytevector-u32-set! buf (+ pos 4) 0 endianness))
975 ((8)
976 (bytevector-u64-set! buf pos tc7-rtl-program endianness)
977 (bytevector-u64-set! buf (+ pos 8) 0 endianness))
978 (else (error "bad word size"))))
979
980 ((cache-cell? obj)
981 (write-immediate asm buf pos #f))
982
983 ((string? obj)
984 (let ((tag (logior tc7-ro-string (ash (string-length obj) 8))))
985 (case word-size
986 ((4)
987 (bytevector-u32-set! buf pos tc7-ro-string endianness)
988 (write-immediate asm buf (+ pos 4) #f) ; stringbuf
989 (bytevector-u32-set! buf (+ pos 8) 0 endianness)
990 (bytevector-u32-set! buf (+ pos 12) (string-length obj) endianness))
991 ((8)
992 (bytevector-u64-set! buf pos tc7-ro-string endianness)
993 (write-immediate asm buf (+ pos 8) #f) ; stringbuf
994 (bytevector-u64-set! buf (+ pos 16) 0 endianness)
995 (bytevector-u64-set! buf (+ pos 24) (string-length obj) endianness))
996 (else (error "bad word size")))))
997
998 ((pair? obj)
999 (write-constant-reference buf pos (car obj))
1000 (write-constant-reference buf (+ pos word-size) (cdr obj)))
1001
1002 ((simple-vector? obj)
1003 (let* ((len (vector-length obj))
1004 (tag (logior tc7-vector (ash len 8))))
1005 (case word-size
1006 ((4) (bytevector-u32-set! buf pos tag endianness))
1007 ((8) (bytevector-u64-set! buf pos tag endianness))
1008 (else (error "bad word size")))
1009 (let lp ((i 0))
1010 (when (< i (vector-length obj))
1011 (let ((pos (+ pos word-size (* i word-size)))
1012 (elt (vector-ref obj i)))
1013 (write-constant-reference buf pos elt)
1014 (lp (1+ i)))))))
1015
1016 ((symbol? obj)
1017 (write-immediate asm buf pos #f))
1018
1019 ((keyword? obj)
1020 (write-immediate asm buf pos #f))
1021
1022 ((number? obj)
1023 (write-immediate asm buf pos #f))
1024
1025 ((simple-uniform-vector? obj)
1026 (let ((tag (logior tc7-bytevector
1027 (ash (uniform-vector-element-type-code obj) 7))))
1028 (case word-size
1029 ((4)
1030 (bytevector-u32-set! buf pos tag endianness)
1031 (bytevector-u32-set! buf (+ pos 4) (bytevector-length obj)
1032 endianness) ; length
1033 (bytevector-u32-set! buf (+ pos 8) 0 endianness) ; pointer
1034 (write-immediate asm buf (+ pos 12) #f)) ; owner
1035 ((8)
1036 (bytevector-u64-set! buf pos tag endianness)
1037 (bytevector-u64-set! buf (+ pos 8) (bytevector-length obj)
1038 endianness) ; length
1039 (bytevector-u64-set! buf (+ pos 16) 0 endianness) ; pointer
1040 (write-immediate asm buf (+ pos 24) #f)) ; owner
1041 (else (error "bad word size")))))
1042
1043 ((uniform-vector-backing-store? obj)
1044 (let ((bv (uniform-vector-backing-store-bytes obj)))
1045 (bytevector-copy! bv 0 buf pos (bytevector-length bv))
1046 (unless (or (= 1 (uniform-vector-element-size bv))
1047 (eq? endianness (native-endianness)))
1048 ;; Need to swap units of element-size bytes
1049 (error "FIXME: Implement byte order swap"))))
1050
1051 (else
1052 (error "unrecognized object" obj))))
1053
1054 (cond
1055 ((vlist-null? data) #f)
1056 (else
1057 (let* ((byte-len (vhash-fold (lambda (k v len)
1058 (+ (byte-length k) (align len 8)))
1059 0 data))
1060 (buf (make-bytevector byte-len 0)))
1061 (let lp ((i 0) (pos 0) (labels '()))
1062 (if (< i (vlist-length data))
1063 (let* ((pair (vlist-ref data i))
1064 (obj (car pair))
1065 (obj-label (cdr pair)))
1066 (write buf pos obj)
1067 (lp (1+ i)
1068 (align (+ (byte-length obj) pos) 8)
1069 (cons (make-linker-symbol obj-label pos) labels)))
1070 (make-object asm name buf '() labels
1071 #:flags (match name
1072 ('.data (logior SHF_ALLOC SHF_WRITE))
1073 ('.rodata SHF_ALLOC))))))))))
1074
1075 (define (link-constants asm)
1076 "Link sections to hold constants needed by the program text emitted
1077 using @var{asm}.
1078
1079 Returns three values: an object for the .rodata section, an object for
1080 the .data section, and a label for an initialization procedure. Any of
1081 these may be @code{#f}."
1082 (define (shareable? x)
1083 (cond
1084 ((stringbuf? x) #t)
1085 ((pair? x)
1086 (and (immediate? (car x)) (immediate? (cdr x))))
1087 ((simple-vector? x)
1088 (let lp ((i 0))
1089 (or (= i (vector-length x))
1090 (and (immediate? (vector-ref x i))
1091 (lp (1+ i))))))
1092 ((uniform-vector-backing-store? x) #t)
1093 (else #f)))
1094 (let* ((constants (asm-constants asm))
1095 (len (vlist-length constants)))
1096 (let lp ((i 0)
1097 (ro vlist-null)
1098 (rw vlist-null))
1099 (if (= i len)
1100 (values (link-data asm ro '.rodata)
1101 (link-data asm rw '.data)
1102 (emit-init-constants asm))
1103 (let ((pair (vlist-ref constants i)))
1104 (if (shareable? (car pair))
1105 (lp (1+ i) (vhash-consq (car pair) (cdr pair) ro) rw)
1106 (lp (1+ i) ro (vhash-consq (car pair) (cdr pair) rw))))))))
1107
1108 \f
1109
1110 ;;;
1111 ;;; Linking program text.
1112 ;;;
1113
1114 (define (process-relocs buf relocs labels)
1115 "Patch up internal x8-s24 relocations, and any s32 relocations that
1116 reference symbols in the text section. Return a list of linker
1117 relocations for references to symbols defined outside the text section."
1118 (fold
1119 (lambda (reloc tail)
1120 (match reloc
1121 ((type label base word)
1122 (let ((abs (assq-ref labels label))
1123 (dst (+ base word)))
1124 (case type
1125 ((s32)
1126 (if abs
1127 (let ((rel (- abs base)))
1128 (s32-set! buf dst rel)
1129 tail)
1130 (cons (make-linker-reloc 'rel32/4 (* dst 4) word label)
1131 tail)))
1132 ((x8-s24)
1133 (unless abs
1134 (error "unbound near relocation" reloc))
1135 (let ((rel (- abs base))
1136 (u32 (u32-ref buf dst)))
1137 (u32-set! buf dst (pack-u8-s24 (logand u32 #xff) rel))
1138 tail))
1139 (else (error "bad relocation kind" reloc)))))))
1140 '()
1141 relocs))
1142
1143 (define (process-labels labels)
1144 "Define linker symbols for the label-offset pairs in @var{labels}.
1145 The offsets are expected to be expressed in words."
1146 (map (lambda (pair)
1147 (make-linker-symbol (car pair) (* (cdr pair) 4)))
1148 labels))
1149
1150 (define (swap-bytes! buf)
1151 "Patch up the text buffer @var{buf}, swapping the endianness of each
1152 32-bit unit."
1153 (unless (zero? (modulo (bytevector-length buf) 4))
1154 (error "unexpected length"))
1155 (let ((byte-len (bytevector-length buf)))
1156 (let lp ((pos 0))
1157 (unless (= pos byte-len)
1158 (bytevector-u32-set!
1159 buf pos
1160 (bytevector-u32-ref buf pos (endianness big))
1161 (endianness little))
1162 (lp (+ pos 4))))))
1163
1164 (define (link-text-object asm)
1165 "Link the .rtl-text section, swapping the endianness of the bytes if
1166 needed."
1167 (let ((buf (make-u32vector (asm-pos asm))))
1168 (let lp ((pos 0) (prev (reverse (asm-prev asm))))
1169 (if (null? prev)
1170 (let ((byte-size (* (asm-idx asm) 4)))
1171 (bytevector-copy! (asm-cur asm) 0 buf pos byte-size)
1172 (unless (eq? (asm-endianness asm) (native-endianness))
1173 (swap-bytes! buf))
1174 (make-object asm '.rtl-text
1175 buf
1176 (process-relocs buf (asm-relocs asm)
1177 (asm-labels asm))
1178 (process-labels (asm-labels asm))))
1179 (let ((len (* *block-size* 4)))
1180 (bytevector-copy! (car prev) 0 buf pos len)
1181 (lp (+ pos len) (cdr prev)))))))
1182
1183
1184 \f
1185
1186 ;;;
1187 ;;; Linking other sections of the ELF file, like the dynamic segment,
1188 ;;; the symbol table, etc.
1189 ;;;
1190
1191 (define (link-dynamic-section asm text rw rw-init)
1192 "Link the dynamic section for an ELF image with RTL text, given the
1193 writable data section @var{rw} needing fixup from the procedure with
1194 label @var{rw-init}. @var{rw-init} may be false. If @var{rw} is true,
1195 it will be added to the GC roots at runtime."
1196 (define-syntax-rule (emit-dynamic-section word-size %set-uword! reloc-type)
1197 (let* ((endianness (asm-endianness asm))
1198 (bv (make-bytevector (* word-size (if rw (if rw-init 12 10) 6)) 0))
1199 (set-uword!
1200 (lambda (i uword)
1201 (%set-uword! bv (* i word-size) uword endianness)))
1202 (relocs '())
1203 (set-label!
1204 (lambda (i label)
1205 (set! relocs (cons (make-linker-reloc 'reloc-type
1206 (* i word-size) 0 label)
1207 relocs))
1208 (%set-uword! bv (* i word-size) 0 endianness))))
1209 (set-uword! 0 DT_GUILE_RTL_VERSION)
1210 (set-uword! 1 #x02020000)
1211 (set-uword! 2 DT_GUILE_ENTRY)
1212 (set-label! 3 '.rtl-text)
1213 (cond
1214 (rw
1215 ;; Add roots to GC.
1216 (set-uword! 4 DT_GUILE_GC_ROOT)
1217 (set-label! 5 '.data)
1218 (set-uword! 6 DT_GUILE_GC_ROOT_SZ)
1219 (set-uword! 7 (bytevector-length (linker-object-bv rw)))
1220 (cond
1221 (rw-init
1222 (set-uword! 8 DT_INIT) ; constants
1223 (set-label! 9 rw-init)
1224 (set-uword! 10 DT_NULL)
1225 (set-uword! 11 0))
1226 (else
1227 (set-uword! 8 DT_NULL)
1228 (set-uword! 9 0))))
1229 (else
1230 (set-uword! 4 DT_NULL)
1231 (set-uword! 5 0)))
1232 (make-object asm '.dynamic bv relocs '()
1233 #:type SHT_DYNAMIC #:flags SHF_ALLOC)))
1234 (case (asm-word-size asm)
1235 ((4) (emit-dynamic-section 4 bytevector-u32-set! abs32/1))
1236 ((8) (emit-dynamic-section 8 bytevector-u64-set! abs64/1))
1237 (else (error "bad word size" asm))))
1238
1239 (define (link-shstrtab asm)
1240 "Link the string table for the section headers."
1241 (intern-section-name! asm ".shstrtab")
1242 (make-object asm '.shstrtab
1243 (link-string-table! (asm-shstrtab asm))
1244 '() '()
1245 #:type SHT_STRTAB #:flags 0))
1246
1247 (define (link-symtab text-section asm)
1248 (let* ((endianness (asm-endianness asm))
1249 (word-size (asm-word-size asm))
1250 (size (elf-symbol-len word-size))
1251 (meta (reverse (asm-meta asm)))
1252 (n (length meta))
1253 (strtab (make-string-table))
1254 (bv (make-bytevector (* n size) 0)))
1255 (define (intern-string! name)
1256 (string-table-intern! strtab (if name (symbol->string name) "")))
1257 (for-each
1258 (lambda (meta n)
1259 (let ((name (intern-string! (meta-name meta))))
1260 (write-elf-symbol bv (* n size) endianness word-size
1261 (make-elf-symbol
1262 #:name name
1263 ;; Symbol value and size are measured in
1264 ;; bytes, not u32s.
1265 #:value (* 4 (meta-low-pc meta))
1266 #:size (* 4 (- (meta-high-pc meta)
1267 (meta-low-pc meta)))
1268 #:type STT_FUNC
1269 #:visibility STV_HIDDEN
1270 #:shndx (elf-section-index text-section)))))
1271 meta (iota n))
1272 (let ((strtab (make-object asm '.strtab
1273 (link-string-table! strtab)
1274 '() '()
1275 #:type SHT_STRTAB #:flags 0)))
1276 (values (make-object asm '.symtab
1277 bv
1278 '() '()
1279 #:type SHT_SYMTAB #:flags 0 #:entsize size
1280 #:link (elf-section-index
1281 (linker-object-section strtab)))
1282 strtab))))
1283
1284 ;;; The .guile.arities section describes the arities that a function can
1285 ;;; have. It is in two parts: a sorted array of headers describing
1286 ;;; basic arities, and an array of links out to a string table (and in
1287 ;;; the case of keyword arguments, to the data section) for argument
1288 ;;; names. The whole thing is prefixed by a uint32 indicating the
1289 ;;; offset of the end of the headers array.
1290 ;;;
1291 ;;; The arity headers array is a packed array of structures of the form:
1292 ;;;
1293 ;;; struct arity_header {
1294 ;;; uint32_t low_pc;
1295 ;;; uint32_t high_pc;
1296 ;;; uint32_t offset;
1297 ;;; uint32_t flags;
1298 ;;; uint32_t nreq;
1299 ;;; uint32_t nopt;
1300 ;;; }
1301 ;;;
1302 ;;; All of the offsets and addresses are 32 bits. We can expand in the
1303 ;;; future to use 64-bit offsets if appropriate, but there are other
1304 ;;; aspects of RTL that constrain us to a total image that fits in 32
1305 ;;; bits, so for the moment we'll simplify the problem space.
1306 ;;;
1307 ;;; The following flags values are defined:
1308 ;;;
1309 ;;; #x1: has-rest?
1310 ;;; #x2: allow-other-keys?
1311 ;;; #x4: has-keyword-args?
1312 ;;; #x8: is-case-lambda?
1313 ;;;
1314 ;;; Functions with a single arity specify their number of required and
1315 ;;; optional arguments in nreq and nopt, and do not have the
1316 ;;; is-case-lambda? flag set. Their "offset" member links to an array
1317 ;;; of pointers into the associated .guile.arities.strtab string table,
1318 ;;; identifying the argument names. This offset is relative to the
1319 ;;; start of the .guile.arities section. Links for required arguments
1320 ;;; are first, in order, as uint32 values. Next follow the optionals,
1321 ;;; then the rest link if has-rest? is set, then a link to the "keyword
1322 ;;; indices" literal if has-keyword-args? is set. Unlike the other
1323 ;;; links, the kw-indices link points into the data section, and is
1324 ;;; relative to the ELF image as a whole.
1325 ;;;
1326 ;;; Functions with no arities have no arities information present in the
1327 ;;; .guile.arities section.
1328 ;;;
1329 ;;; Functions with multiple arities are preceded by a header with
1330 ;;; is-case-lambda? set. All other fields are 0, except low-pc and
1331 ;;; high-pc which should be the bounds of the whole function. Headers
1332 ;;; for the individual arities follow. In this way the whole headers
1333 ;;; array is sorted in increasing low-pc order, and case-lambda clauses
1334 ;;; are contained within the [low-pc, high-pc] of the case-lambda
1335 ;;; header.
1336
1337 ;; Length of the prefix to the arities section, in bytes.
1338 (define arities-prefix-len 4)
1339
1340 ;; Length of an arity header, in bytes.
1341 (define arity-header-len (* 6 4))
1342
1343 ;; The offset of "offset" within arity header, in bytes.
1344 (define arity-header-offset-offset (* 2 4))
1345
1346 (define-syntax-rule (pack-arity-flags has-rest? allow-other-keys?
1347 has-keyword-args? is-case-lambda?)
1348 (logior (if has-rest? (ash 1 0) 0)
1349 (if allow-other-keys? (ash 1 1) 0)
1350 (if has-keyword-args? (ash 1 2) 0)
1351 (if is-case-lambda? (ash 1 3) 0)))
1352
1353 (define (meta-arities-size meta)
1354 (define (lambda-size arity)
1355 (+ arity-header-len
1356 (* 4 ;; name pointers
1357 (+ (length (arity-req arity))
1358 (length (arity-opt arity))
1359 (if (arity-rest arity) 1 0)
1360 (if (pair? (arity-kw-indices arity)) 1 0)))))
1361 (define (case-lambda-size arities)
1362 (fold +
1363 arity-header-len ;; case-lambda header
1364 (map lambda-size arities))) ;; the cases
1365 (match (meta-arities meta)
1366 (() 0)
1367 ((arity) (lambda-size arity))
1368 (arities (case-lambda-size arities))))
1369
1370 (define (write-arity-headers metas bv endianness)
1371 (define (write-arity-header* pos low-pc high-pc flags nreq nopt)
1372 (bytevector-u32-set! bv pos low-pc endianness)
1373 (bytevector-u32-set! bv (+ pos 4) high-pc endianness)
1374 (bytevector-u32-set! bv (+ pos 8) 0 endianness) ; offset
1375 (bytevector-u32-set! bv (+ pos 12) flags endianness)
1376 (bytevector-u32-set! bv (+ pos 16) nreq endianness)
1377 (bytevector-u32-set! bv (+ pos 20) nopt endianness))
1378 (define (write-arity-header pos arity)
1379 (write-arity-header* pos (arity-low-pc arity)
1380 (arity-high-pc arity)
1381 (pack-arity-flags (arity-rest arity)
1382 (arity-allow-other-keys? arity)
1383 (pair? (arity-kw-indices arity))
1384 #f)
1385 (length (arity-req arity))
1386 (length (arity-opt arity))))
1387 (let lp ((metas metas) (pos arities-prefix-len) (offsets '()))
1388 (match metas
1389 (()
1390 ;; Fill in the prefix.
1391 (bytevector-u32-set! bv 0 pos endianness)
1392 (values pos (reverse offsets)))
1393 ((meta . metas)
1394 (match (meta-arities meta)
1395 (() (lp metas pos offsets))
1396 ((arity)
1397 (write-arity-header pos arity)
1398 (lp metas
1399 (+ pos arity-header-len)
1400 (acons arity (+ pos arity-header-offset-offset) offsets)))
1401 (arities
1402 ;; Write a case-lambda header, then individual arities.
1403 ;; The case-lambda header's offset link is 0.
1404 (write-arity-header* pos (meta-low-pc meta) (meta-high-pc meta)
1405 (pack-arity-flags #f #f #f #t) 0 0)
1406 (let lp* ((arities arities) (pos (+ pos arity-header-len))
1407 (offsets offsets))
1408 (match arities
1409 (() (lp metas pos offsets))
1410 ((arity . arities)
1411 (write-arity-header pos arity)
1412 (lp* arities
1413 (+ pos arity-header-len)
1414 (acons arity
1415 (+ pos arity-header-offset-offset)
1416 offsets)))))))))))
1417
1418 (define (write-arity-links asm bv pos arity-offset-pairs strtab)
1419 (define (write-symbol sym pos)
1420 (bytevector-u32-set! bv pos
1421 (string-table-intern! strtab (symbol->string sym))
1422 (asm-endianness asm))
1423 (+ pos 4))
1424 (define (write-kw-indices pos kw-indices)
1425 ;; FIXME: Assert that kw-indices is already interned.
1426 (make-linker-reloc 'abs32/1 pos 0
1427 (intern-constant asm kw-indices)))
1428 (let lp ((pos pos) (pairs arity-offset-pairs) (relocs '()))
1429 (match pairs
1430 (()
1431 (unless (= pos (bytevector-length bv))
1432 (error "expected to fully fill the bytevector"
1433 pos (bytevector-length bv)))
1434 relocs)
1435 (((arity . offset) . pairs)
1436 (bytevector-u32-set! bv offset pos (asm-endianness asm))
1437 (let ((pos (fold write-symbol
1438 pos
1439 (append (arity-req arity)
1440 (arity-opt arity)
1441 (cond
1442 ((arity-rest arity) => list)
1443 (else '()))))))
1444 (match (arity-kw-indices arity)
1445 (() (lp pos pairs relocs))
1446 (kw-indices
1447 (lp (+ pos 4)
1448 pairs
1449 (cons (write-kw-indices pos kw-indices) relocs)))))))))
1450
1451 (define (link-arities asm)
1452 (let* ((endianness (asm-endianness asm))
1453 (metas (reverse (asm-meta asm)))
1454 (size (fold (lambda (meta size)
1455 (+ size (meta-arities-size meta)))
1456 arities-prefix-len
1457 metas))
1458 (strtab (make-string-table))
1459 (bv (make-bytevector size 0)))
1460 (let ((kw-indices-relocs
1461 (call-with-values
1462 (lambda ()
1463 (write-arity-headers metas bv endianness))
1464 (lambda (pos arity-offset-pairs)
1465 (write-arity-links asm bv pos arity-offset-pairs strtab)))))
1466 (let ((strtab (make-object asm '.guile.arities.strtab
1467 (link-string-table! strtab)
1468 '() '()
1469 #:type SHT_STRTAB #:flags 0)))
1470 (values (make-object asm '.guile.arities
1471 bv
1472 kw-indices-relocs '()
1473 #:type SHT_PROGBITS #:flags 0
1474 #:link (elf-section-index
1475 (linker-object-section strtab)))
1476 strtab)))))
1477
1478 ;;;
1479 ;;; The .guile.docstrs section is a packed, sorted array of (pc, str)
1480 ;;; values. Pc and str are both 32 bits wide. (Either could change to
1481 ;;; 64 bits if appropriate in the future.) Pc is the address of the
1482 ;;; entry to a program, relative to the start of the text section, and
1483 ;;; str is an index into the associated .guile.docstrs.strtab string
1484 ;;; table section.
1485 ;;;
1486
1487 ;; The size of a docstrs entry, in bytes.
1488 (define docstr-size 8)
1489
1490 (define (link-docstrs asm)
1491 (define (find-docstrings)
1492 (filter-map (lambda (meta)
1493 (define (is-documentation? pair)
1494 (eq? (car pair) 'documentation))
1495 (let* ((props (meta-properties meta))
1496 (tail (find-tail is-documentation? props)))
1497 (and tail
1498 (not (find-tail is-documentation? (cdr tail)))
1499 (string? (cdar tail))
1500 (cons (meta-low-pc meta) (cdar tail)))))
1501 (reverse (asm-meta asm))))
1502 (let* ((endianness (asm-endianness asm))
1503 (docstrings (find-docstrings))
1504 (strtab (make-string-table))
1505 (bv (make-bytevector (* (length docstrings) docstr-size) 0)))
1506 (fold (lambda (pair pos)
1507 (match pair
1508 ((pc . string)
1509 (bytevector-u32-set! bv pos pc endianness)
1510 (bytevector-u32-set! bv (+ pos 4)
1511 (string-table-intern! strtab string)
1512 endianness)
1513 (+ pos docstr-size))))
1514 0
1515 docstrings)
1516 (let ((strtab (make-object asm '.guile.docstrs.strtab
1517 (link-string-table! strtab)
1518 '() '()
1519 #:type SHT_STRTAB #:flags 0)))
1520 (values (make-object asm '.guile.docstrs
1521 bv
1522 '() '()
1523 #:type SHT_PROGBITS #:flags 0
1524 #:link (elf-section-index
1525 (linker-object-section strtab)))
1526 strtab))))
1527
1528 ;;;
1529 ;;; The .guile.procprops section is a packed, sorted array of (pc, addr)
1530 ;;; values. Pc and addr are both 32 bits wide. (Either could change to
1531 ;;; 64 bits if appropriate in the future.) Pc is the address of the
1532 ;;; entry to a program, relative to the start of the text section, and
1533 ;;; addr is the address of the associated properties alist, relative to
1534 ;;; the start of the ELF image.
1535 ;;;
1536 ;;; Since procedure properties are stored in the data sections, we need
1537 ;;; to link the procedures property section first. (Note that this
1538 ;;; constraint does not apply to the arities section, which may
1539 ;;; reference the data sections via the kw-indices literal, because
1540 ;;; assembling the text section already makes sure that the kw-indices
1541 ;;; are interned.)
1542 ;;;
1543
1544 ;; The size of a procprops entry, in bytes.
1545 (define procprops-size 8)
1546
1547 (define (link-procprops asm)
1548 (define (assoc-remove-one alist key value-pred)
1549 (match alist
1550 (() '())
1551 ((((? (lambda (x) (eq? x key))) . value) . alist)
1552 (if (value-pred value)
1553 alist
1554 (acons key value alist)))
1555 (((k . v) . alist)
1556 (acons k v (assoc-remove-one alist key value-pred)))))
1557 (define (props-without-name-or-docstring meta)
1558 (assoc-remove-one
1559 (assoc-remove-one (meta-properties meta) 'name (lambda (x) #t))
1560 'documentation
1561 string?))
1562 (define (find-procprops)
1563 (filter-map (lambda (meta)
1564 (let ((props (props-without-name-or-docstring meta)))
1565 (and (pair? props)
1566 (cons (meta-low-pc meta) props))))
1567 (reverse (asm-meta asm))))
1568 (let* ((endianness (asm-endianness asm))
1569 (procprops (find-procprops))
1570 (bv (make-bytevector (* (length procprops) procprops-size) 0)))
1571 (let lp ((procprops procprops) (pos 0) (relocs '()))
1572 (match procprops
1573 (()
1574 (make-object asm '.guile.procprops
1575 bv
1576 relocs '()
1577 #:type SHT_PROGBITS #:flags 0))
1578 (((pc . props) . procprops)
1579 (bytevector-u32-set! bv pos pc endianness)
1580 (lp procprops
1581 (+ pos procprops-size)
1582 (cons (make-linker-reloc 'abs32/1 (+ pos 4) 0
1583 (intern-constant asm props))
1584 relocs)))))))
1585
1586 ;;;
1587 ;;; The DWARF .debug_info, .debug_abbrev, .debug_str, and .debug_loc
1588 ;;; sections provide line number and local variable liveness
1589 ;;; information. Their format is defined by the DWARF
1590 ;;; specifications.
1591 ;;;
1592
1593 (define (asm-language asm)
1594 ;; FIXME: Plumb language through to the assembler.
1595 'scheme)
1596
1597 ;; -> 5 values: .debug_info, .debug_abbrev, .debug_str, .debug_loc, .debug_lines
1598 (define (link-debug asm)
1599 (define (put-s8 port val)
1600 (let ((bv (make-bytevector 1)))
1601 (bytevector-s8-set! bv 0 val)
1602 (put-bytevector port bv)))
1603
1604 (define (put-u16 port val)
1605 (let ((bv (make-bytevector 2)))
1606 (bytevector-u16-set! bv 0 val (asm-endianness asm))
1607 (put-bytevector port bv)))
1608
1609 (define (put-u32 port val)
1610 (let ((bv (make-bytevector 4)))
1611 (bytevector-u32-set! bv 0 val (asm-endianness asm))
1612 (put-bytevector port bv)))
1613
1614 (define (put-u64 port val)
1615 (let ((bv (make-bytevector 8)))
1616 (bytevector-u64-set! bv 0 val (asm-endianness asm))
1617 (put-bytevector port bv)))
1618
1619 (define (put-uleb128 port val)
1620 (let lp ((val val))
1621 (let ((next (ash val -7)))
1622 (if (zero? next)
1623 (put-u8 port val)
1624 (begin
1625 (put-u8 port (logior #x80 (logand val #x7f)))
1626 (lp next))))))
1627
1628 (define (put-sleb128 port val)
1629 (let lp ((val val))
1630 (if (<= 0 (+ val 64) 128)
1631 (put-u8 port (logand val #x7f))
1632 (begin
1633 (put-u8 port (logior #x80 (logand val #x7f)))
1634 (lp (ash val -7))))))
1635
1636 (define (port-position port)
1637 (seek port 0 SEEK_CUR))
1638
1639 (define (meta->subprogram-die meta)
1640 `(subprogram
1641 (@ ,@(cond
1642 ((meta-name meta)
1643 => (lambda (name) `((name ,(symbol->string name)))))
1644 (else
1645 '()))
1646 (low-pc ,(meta-label meta))
1647 (high-pc ,(* 4 (- (meta-high-pc meta) (meta-low-pc meta)))))))
1648
1649 (define (make-compile-unit-die asm)
1650 `(compile-unit
1651 (@ (producer ,(string-append "Guile " (version)))
1652 (language ,(asm-language asm))
1653 (low-pc .rtl-text)
1654 (high-pc ,(* 4 (asm-pos asm)))
1655 (stmt-list 0))
1656 ,@(map meta->subprogram-die (reverse (asm-meta asm)))))
1657
1658 (let-values (((die-port get-die-bv) (open-bytevector-output-port))
1659 ((die-relocs) '())
1660 ((abbrev-port get-abbrev-bv) (open-bytevector-output-port))
1661 ;; (tag has-kids? attrs forms) -> code
1662 ((abbrevs) vlist-null)
1663 ((strtab) (make-string-table))
1664 ((line-port get-line-bv) (open-bytevector-output-port))
1665 ((line-relocs) '())
1666 ;; file -> code
1667 ((files) vlist-null))
1668
1669 (define (write-abbrev code tag has-children? attrs forms)
1670 (put-uleb128 abbrev-port code)
1671 (put-uleb128 abbrev-port (tag-name->code tag))
1672 (put-u8 abbrev-port (children-name->code (if has-children? 'yes 'no)))
1673 (for-each (lambda (attr form)
1674 (put-uleb128 abbrev-port (attribute-name->code attr))
1675 (put-uleb128 abbrev-port (form-name->code form)))
1676 attrs forms)
1677 (put-uleb128 abbrev-port 0)
1678 (put-uleb128 abbrev-port 0))
1679
1680 (define (intern-abbrev tag has-children? attrs forms)
1681 (let ((key (list tag has-children? attrs forms)))
1682 (match (vhash-assoc key abbrevs)
1683 ((_ . code) code)
1684 (#f (let ((code (1+ (vlist-length abbrevs))))
1685 (set! abbrevs (vhash-cons key code abbrevs))
1686 (write-abbrev code tag has-children? attrs forms)
1687 code)))))
1688
1689 (define (intern-file file)
1690 (match (vhash-assoc file files)
1691 ((_ . code) code)
1692 (#f (let ((code (1+ (vlist-length files))))
1693 (set! files (vhash-cons file code files))
1694 code))))
1695
1696 (define (write-sources)
1697 ;; Choose line base and line range values that will allow for an
1698 ;; address advance range of 16 words. The special opcode range is
1699 ;; from 10 to 255, so 246 values.
1700 (define base -4)
1701 (define range 15)
1702
1703 (let lp ((sources (asm-sources asm)) (out '()))
1704 (match sources
1705 (((pc . s) . sources)
1706 (let ((file (assq-ref s 'filename))
1707 (line (assq-ref s 'line))
1708 (col (assq-ref s 'column)))
1709 (lp sources
1710 ;; Guile line and column numbers are 0-indexed, but
1711 ;; they are 1-indexed for DWARF.
1712 (cons (list pc
1713 (if file (intern-file file) 0)
1714 (if line (1+ line))
1715 (if col (1+ col)))
1716 out))))
1717 (()
1718 ;; Compilation unit header for .debug_line. We write in
1719 ;; DWARF 2 format because more tools understand it than DWARF
1720 ;; 4, which incompatibly adds another field to this header.
1721
1722 (put-u32 line-port 0) ; Length; will patch later.
1723 (put-u16 line-port 2) ; DWARF 2 format.
1724 (put-u32 line-port 0) ; Prologue length; will patch later.
1725 (put-u8 line-port 4) ; Minimum instruction length: 4 bytes.
1726 (put-u8 line-port 1) ; Default is-stmt: true.
1727
1728 (put-s8 line-port base) ; Line base. See the DWARF standard.
1729 (put-u8 line-port range) ; Line range. See the DWARF standard.
1730 (put-u8 line-port 10) ; Opcode base: the first "special" opcode.
1731
1732 ;; A table of the number of uleb128 arguments taken by each
1733 ;; of the standard opcodes.
1734 (put-u8 line-port 0) ; 1: copy
1735 (put-u8 line-port 1) ; 2: advance-pc
1736 (put-u8 line-port 1) ; 3: advance-line
1737 (put-u8 line-port 1) ; 4: set-file
1738 (put-u8 line-port 1) ; 5: set-column
1739 (put-u8 line-port 0) ; 6: negate-stmt
1740 (put-u8 line-port 0) ; 7: set-basic-block
1741 (put-u8 line-port 0) ; 8: const-add-pc
1742 (put-u8 line-port 1) ; 9: fixed-advance-pc
1743
1744 ;; Include directories, as a zero-terminated sequence of
1745 ;; nul-terminated strings. Nothing, for the moment.
1746 (put-u8 line-port 0)
1747
1748 ;; File table. For each file that contributes to this
1749 ;; compilation unit, a nul-terminated file name string, and a
1750 ;; uleb128 for each of directory the file was found in, the
1751 ;; modification time, and the file's size in bytes. We pass
1752 ;; zero for the latter three fields.
1753 (vlist-for-each (match-lambda
1754 ((file . code)
1755 (put-bytevector line-port (string->utf8 file))
1756 (put-u8 line-port 0)
1757 (put-uleb128 line-port 0) ; directory
1758 (put-uleb128 line-port 0) ; mtime
1759 (put-uleb128 line-port 0) ; size
1760 ))
1761 files)
1762 (put-u8 line-port 0) ; 0 byte terminating file list.
1763
1764 ;; Patch prologue length.
1765 (let ((offset (port-position line-port)))
1766 (seek line-port 6 SEEK_SET)
1767 (put-u32 line-port (- offset 10))
1768 (seek line-port offset SEEK_SET))
1769
1770 ;; Now write the statement program.
1771 (let ()
1772 (define (extended-op opcode payload-len)
1773 (put-u8 line-port 0) ; extended op
1774 (put-uleb128 line-port (1+ payload-len)) ; payload-len + opcode
1775 (put-uleb128 line-port opcode))
1776 (define (set-address sym)
1777 (define (add-reloc! kind)
1778 (set! line-relocs
1779 (cons (make-linker-reloc kind
1780 (port-position line-port)
1781 0
1782 sym)
1783 line-relocs)))
1784 (match (asm-word-size asm)
1785 (4
1786 (extended-op 2 4)
1787 (add-reloc! 'abs32/1)
1788 (put-u32 line-port 0))
1789 (8
1790 (extended-op 2 8)
1791 (add-reloc! 'abs64/1)
1792 (put-u64 line-port 0))))
1793 (define (end-sequence pc)
1794 (let ((pc-inc (- (asm-pos asm) pc)))
1795 (put-u8 line-port 2) ; advance-pc
1796 (put-uleb128 line-port pc-inc))
1797 (extended-op 1 0))
1798 (define (advance-pc pc-inc line-inc)
1799 (let ((spec (+ (- line-inc base) (* pc-inc range) 10)))
1800 (cond
1801 ((or (< line-inc base) (>= line-inc (+ base range)))
1802 (advance-line line-inc)
1803 (advance-pc pc-inc 0))
1804 ((<= spec 255)
1805 (put-u8 line-port spec))
1806 ((< spec 500)
1807 (put-u8 line-port 8) ; const-advance-pc
1808 (advance-pc (- pc-inc (floor/ (- 255 10) range))
1809 line-inc))
1810 (else
1811 (put-u8 line-port 2) ; advance-pc
1812 (put-uleb128 line-port pc-inc)
1813 (advance-pc 0 line-inc)))))
1814 (define (advance-line inc)
1815 (put-u8 line-port 3)
1816 (put-sleb128 line-port inc))
1817 (define (set-file file)
1818 (put-u8 line-port 4)
1819 (put-uleb128 line-port file))
1820 (define (set-column col)
1821 (put-u8 line-port 5)
1822 (put-uleb128 line-port col))
1823
1824 (set-address '.rtl-text)
1825
1826 (let lp ((in out) (pc 0) (file 1) (line 1) (col 0))
1827 (match in
1828 (()
1829 (when (null? out)
1830 ;; There was no source info in the first place. Set
1831 ;; file register to 0 before adding final row.
1832 (set-file 0))
1833 (end-sequence pc))
1834 (((pc* file* line* col*) . in*)
1835 (cond
1836 ((and (eqv? file file*) (eqv? line line*) (eqv? col col*))
1837 (lp in* pc file line col))
1838 (else
1839 (unless (eqv? col col*)
1840 (set-column col*))
1841 (unless (eqv? file file*)
1842 (set-file file*))
1843 (advance-pc (- pc* pc) (- line* line))
1844 (lp in* pc* file* line* col*)))))))))))
1845
1846 (define (compute-code attr val)
1847 (match attr
1848 ('name (string-table-intern! strtab val))
1849 ('low-pc val)
1850 ('high-pc val)
1851 ('producer (string-table-intern! strtab val))
1852 ('language (language-name->code val))
1853 ('stmt-list val)))
1854
1855 (define (exact-integer? val)
1856 (and (number? val) (integer? val) (exact? val)))
1857
1858 (define (choose-form attr val code)
1859 (cond
1860 ((string? val) 'strp)
1861 ((eq? attr 'stmt-list) 'sec-offset)
1862 ((exact-integer? code)
1863 (cond
1864 ((< code 0) 'sleb128)
1865 ((<= code #xff) 'data1)
1866 ((<= code #xffff) 'data2)
1867 ((<= code #xffffffff) 'data4)
1868 ((<= code #xffffffffffffffff) 'data8)
1869 (else 'uleb128)))
1870 ((symbol? val) 'addr)
1871 (else (error "unhandled case" attr val code))))
1872
1873 (define (add-die-relocation! kind sym)
1874 (set! die-relocs
1875 (cons (make-linker-reloc kind (port-position die-port) 0 sym)
1876 die-relocs)))
1877
1878 (define (write-value code form)
1879 (match form
1880 ('data1 (put-u8 die-port code))
1881 ('data2 (put-u16 die-port code))
1882 ('data4 (put-u32 die-port code))
1883 ('data8 (put-u64 die-port code))
1884 ('uleb128 (put-uleb128 die-port code))
1885 ('sleb128 (put-sleb128 die-port code))
1886 ('addr
1887 (match (asm-word-size asm)
1888 (4
1889 (add-die-relocation! 'abs32/1 code)
1890 (put-u32 die-port 0))
1891 (8
1892 (add-die-relocation! 'abs64/1 code)
1893 (put-u64 die-port 0))))
1894 ('sec-offset (put-u32 die-port code))
1895 ('strp (put-u32 die-port code))))
1896
1897 (define (write-die die)
1898 (match die
1899 ((tag ('@ (attrs vals) ...) children ...)
1900 (let* ((codes (map compute-code attrs vals))
1901 (forms (map choose-form attrs vals codes))
1902 (has-children? (not (null? children)))
1903 (abbrev-code (intern-abbrev tag has-children? attrs forms)))
1904 (put-uleb128 die-port abbrev-code)
1905 (for-each write-value codes forms)
1906 (when has-children?
1907 (for-each write-die children)
1908 (put-uleb128 die-port 0))))))
1909
1910 ;; Compilation unit header.
1911 (put-u32 die-port 0) ; Length; will patch later.
1912 (put-u16 die-port 4) ; DWARF 4.
1913 (put-u32 die-port 0) ; Abbrevs offset.
1914 (put-u8 die-port (asm-word-size asm)) ; Address size.
1915
1916 (write-die (make-compile-unit-die asm))
1917
1918 ;; Terminate the abbrevs list.
1919 (put-uleb128 abbrev-port 0)
1920
1921 (write-sources)
1922
1923 (values (let ((bv (get-die-bv)))
1924 ;; Patch DWARF32 length.
1925 (bytevector-u32-set! bv 0 (- (bytevector-length bv) 4)
1926 (asm-endianness asm))
1927 (make-object asm '.debug_info bv die-relocs '()
1928 #:type SHT_PROGBITS #:flags 0))
1929 (make-object asm '.debug_abbrev (get-abbrev-bv) '() '()
1930 #:type SHT_PROGBITS #:flags 0)
1931 (make-object asm '.debug_str (link-string-table! strtab) '() '()
1932 #:type SHT_PROGBITS #:flags 0)
1933 (make-object asm '.debug_loc #vu8() '() '()
1934 #:type SHT_PROGBITS #:flags 0)
1935 (let ((bv (get-line-bv)))
1936 ;; Patch DWARF32 length.
1937 (bytevector-u32-set! bv 0 (- (bytevector-length bv) 4)
1938 (asm-endianness asm))
1939 (make-object asm '.debug_line bv line-relocs '()
1940 #:type SHT_PROGBITS #:flags 0)))))
1941
1942 (define (link-objects asm)
1943 (let*-values (;; Link procprops before constants, because it probably
1944 ;; interns more constants.
1945 ((procprops) (link-procprops asm))
1946 ((ro rw rw-init) (link-constants asm))
1947 ;; Link text object after constants, so that the
1948 ;; constants initializer gets included.
1949 ((text) (link-text-object asm))
1950 ((dt) (link-dynamic-section asm text rw rw-init))
1951 ((symtab strtab) (link-symtab (linker-object-section text) asm))
1952 ((arities arities-strtab) (link-arities asm))
1953 ((docstrs docstrs-strtab) (link-docstrs asm))
1954 ((dinfo dabbrev dstrtab dloc dline) (link-debug asm))
1955 ;; This needs to be linked last, because linking other
1956 ;; sections adds entries to the string table.
1957 ((shstrtab) (link-shstrtab asm)))
1958 (filter identity
1959 (list text ro rw dt symtab strtab arities arities-strtab
1960 docstrs docstrs-strtab procprops
1961 dinfo dabbrev dstrtab dloc dline
1962 shstrtab))))
1963
1964
1965 \f
1966
1967 ;;;
1968 ;;; High-level public interfaces.
1969 ;;;
1970
1971 (define* (link-assembly asm #:key (page-aligned? #t))
1972 "Produce an ELF image from the code and data emitted into @var{asm}.
1973 The result is a bytevector, by default linked so that read-only and
1974 writable data are on separate pages. Pass @code{#:page-aligned? #f} to
1975 disable this behavior."
1976 (link-elf (link-objects asm) #:page-aligned? page-aligned?))
1977
1978 (define (assemble-program instructions)
1979 "Take the sequence of instructions @var{instructions}, assemble them
1980 into RTL code, link an image, and load that image from memory. Returns
1981 a procedure."
1982 (let ((asm (make-assembler)))
1983 (emit-text asm instructions)
1984 (load-thunk-from-memory (link-assembly asm #:page-aligned? #f))))