1 ;;; Guile bytecode assembler
3 ;;; Copyright (C) 2001, 2009, 2010, 2012, 2013, 2014 Free Software Foundation, Inc.
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.
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.
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
21 ;;; This module implements an assembler that creates an ELF image from
22 ;;; bytecode 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.
27 ;;; "Primitive instructions" correspond to VM operations. Assemblers
28 ;;; for primitive instructions are generated programmatically from
29 ;;; (instruction-list), which itself is derived from the VM sources.
30 ;;; There are also "macro-instructions" like "label" or "load-constant"
31 ;;; that expand to 0 or more primitive instructions.
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.
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.
45 (define-module (system vm assembler)
46 #:use-module (system base target)
47 #:use-module (system vm dwarf)
48 #:use-module (system vm elf)
49 #:use-module (system vm linker)
50 #:use-module (language bytecode)
51 #:use-module (rnrs bytevectors)
52 #:use-module (ice-9 binary-ports)
53 #:use-module (ice-9 vlist)
54 #:use-module (ice-9 match)
55 #:use-module (srfi srfi-1)
56 #:use-module (srfi srfi-4)
57 #:use-module (srfi srfi-9)
58 #:use-module (srfi srfi-11)
59 #:export (make-assembler
66 ;;; Bytecode consists of 32-bit units, often subdivided in some way.
67 ;;; These helpers create one 32-bit unit from multiple components.
69 (define-inlinable (pack-u8-u24 x y)
71 (error "out of range" x))
74 (define-inlinable (pack-u8-s24 x y)
76 (error "out of range" x))
82 (else (error "out of range" y)))
85 (define-inlinable (pack-u1-u7-u24 x y z)
87 (error "out of range" x))
89 (error "out of range" y))
90 (logior x (ash y 1) (ash z 8)))
92 (define-inlinable (pack-u8-u12-u12 x y z)
94 (error "out of range" x))
96 (error "out of range" y))
97 (logior x (ash y 8) (ash z 20)))
99 (define-inlinable (pack-u8-u8-u16 x y z)
101 (error "out of range" x))
103 (error "out of range" y))
104 (logior x (ash y 8) (ash z 16)))
106 (define-inlinable (pack-u8-u8-u8-u8 x y z w)
108 (error "out of range" x))
110 (error "out of range" y))
112 (error "out of range" z))
113 (logior x (ash y 8) (ash z 16) (ash w 24)))
115 (define-syntax pack-flags
117 ;; Add clauses as needed.
118 ((pack-flags f1 f2) (logior (if f1 (ash 1 0) 0)
119 (if f2 (ash 2 0) 0)))))
121 ;;; Helpers to read and write 32-bit units in a buffer.
123 (define-syntax-rule (u32-ref buf n)
124 (bytevector-u32-native-ref buf (* n 4)))
126 (define-syntax-rule (u32-set! buf n val)
127 (bytevector-u32-native-set! buf (* n 4) val))
129 (define-syntax-rule (s32-ref buf n)
130 (bytevector-s32-native-ref buf (* n 4)))
132 (define-syntax-rule (s32-set! buf n val)
133 (bytevector-s32-native-set! buf (* n 4) val))
138 ;;; A <meta> entry collects metadata for one procedure. Procedures are
139 ;;; written as contiguous ranges of bytecode.
141 (define-syntax-rule (assert-match arg pattern kind)
143 (unless (match x (pattern #t) (_ #f))
144 (error (string-append "expected " kind) x))))
146 (define-record-type <meta>
147 (%make-meta label properties low-pc high-pc arities)
150 (properties meta-properties set-meta-properties!)
152 (high-pc meta-high-pc set-meta-high-pc!)
153 (arities meta-arities set-meta-arities!))
155 (define (make-meta label properties low-pc)
156 (assert-match label (or (? exact-integer?) (? symbol?)) "symbol")
157 (assert-match properties (((? symbol?) . _) ...) "alist with symbolic keys")
158 (%make-meta label properties low-pc #f '()))
160 (define (meta-name meta)
161 (assq-ref (meta-properties meta) 'name))
163 ;; Metadata for one <lambda-case>.
164 (define-record-type <arity>
165 (make-arity req opt rest kw-indices allow-other-keys?
166 low-pc high-pc definitions)
171 (kw-indices arity-kw-indices)
172 (allow-other-keys? arity-allow-other-keys?)
173 (low-pc arity-low-pc)
174 (high-pc arity-high-pc set-arity-high-pc!)
175 (definitions arity-definitions set-arity-definitions!))
177 (define-syntax *block-size* (identifier-syntax 32))
179 ;;; An assembler collects all of the words emitted during assembly, and
180 ;;; also maintains ancillary information such as the constant table, a
181 ;;; relocation list, and so on.
183 ;;; Bytecode consists of 32-bit units. We emit bytecode using native
184 ;;; endianness. If we're targeting a foreign endianness, we byte-swap
185 ;;; the bytevector as a whole instead of conditionalizing each access.
187 (define-record-type <asm>
188 (make-asm cur idx start prev written
192 shstrtab next-section-number
197 ;; We write bytecode 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.
201 (cur asm-cur set-asm-cur!)
202 (idx asm-idx set-asm-idx!)
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 VM updates the IP only at the end of executing the instruction,
209 ;; and is thus useful for computing offsets between two points in a
212 (start asm-start set-asm-start!)
214 ;; The list of previously written blocks.
216 (prev asm-prev set-asm-prev!)
218 ;; The number of u32 words written in asm-prev, which is the same as
219 ;; the offset of the current block.
221 (written asm-written set-asm-written!)
223 ;; An alist of symbol -> position pairs, indicating the labels defined
224 ;; in this compilation unit.
226 (labels asm-labels set-asm-labels!)
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.
233 (relocs asm-relocs set-asm-relocs!)
235 ;; Target information.
237 (word-size asm-word-size)
238 (endianness asm-endianness)
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.
247 (constants asm-constants set-asm-constants!)
249 ;; A list of instructions needed to initialize the constants. Will
250 ;; run in a thunk with 2 local variables.
252 (inits asm-inits set-asm-inits!)
254 ;; The shstrtab, for section names.
256 (shstrtab asm-shstrtab set-asm-shstrtab!)
258 ;; The section number for the next section to be written.
260 (next-section-number asm-next-section-number set-asm-next-section-number!)
262 ;; A list of <meta>, corresponding to procedure metadata.
264 (meta asm-meta set-asm-meta!)
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.
270 (sources asm-sources set-asm-sources!)
272 ;; A list of (pos . dead-slot-map) pairs, indicating dead slot maps.
273 ;; POS is relative to the beginning of the text section.
274 ;; DEAD-SLOT-MAP is a bitfield of slots that are dead at call sites,
277 (dead-slot-maps asm-dead-slot-maps set-asm-dead-slot-maps!))
279 (define-inlinable (fresh-block)
280 (make-u32vector *block-size*))
282 (define* (make-assembler #:key (word-size (target-word-size))
283 (endianness (target-endianness)))
284 "Create an assembler for a given target @var{word-size} and
285 @var{endianness}, falling back to appropriate values for the configured
287 (make-asm (fresh-block) 0 0 '() 0
288 (make-hash-table) '()
291 (make-string-table) 1
294 (define (intern-section-name! asm string)
295 "Add a string to the section name table (shstrtab)."
296 (string-table-intern! (asm-shstrtab asm) string))
298 (define-inlinable (asm-pos asm)
299 "The offset of the next word to be written into the code buffer, in
301 (+ (asm-idx asm) (asm-written asm)))
303 (define (allocate-new-block asm)
304 "Close off the current block, and arrange for the next word to be
305 written to a fresh block."
306 (let ((new (fresh-block)))
307 (set-asm-prev! asm (cons (asm-cur asm) (asm-prev asm)))
308 (set-asm-written! asm (asm-pos asm))
309 (set-asm-cur! asm new)
310 (set-asm-idx! asm 0)))
312 (define-inlinable (emit asm u32)
313 "Emit one 32-bit word into the instruction stream. Assumes that there
314 is space for the word, and ensures that there is space for the next
316 (u32-set! (asm-cur asm) (asm-idx asm) u32)
317 (set-asm-idx! asm (1+ (asm-idx asm)))
318 (if (= (asm-idx asm) *block-size*)
319 (allocate-new-block asm)))
321 (define-inlinable (make-reloc type label base word)
322 "Make an internal relocation of type @var{type} referencing symbol
323 @var{label}, @var{word} words after position @var{start}. @var{type}
324 may be x8-s24, indicating a 24-bit relative label reference that can be
325 fixed up by the assembler, or s32, indicating a 32-bit relative
326 reference that needs to be fixed up by the linker."
327 (list type label base word))
329 (define-inlinable (reset-asm-start! asm)
330 "Reset the asm-start after writing the words for one instruction."
331 (set-asm-start! asm (asm-pos asm)))
333 (define (record-label-reference asm label)
334 "Record an x8-s24 local label reference. This value will get patched
335 up later by the assembler."
336 (let* ((start (asm-start asm))
338 (reloc (make-reloc 'x8-s24 label start (- pos start))))
339 (set-asm-relocs! asm (cons reloc (asm-relocs asm)))))
341 (define* (record-far-label-reference asm label #:optional (offset 0))
342 "Record an s32 far label reference. This value will get patched up
343 later by the linker."
344 (let* ((start (- (asm-start asm) offset))
346 (reloc (make-reloc 's32 label start (- pos start))))
347 (set-asm-relocs! asm (cons reloc (asm-relocs asm)))))
353 ;;; Primitive assemblers are defined by expanding `assembler' for each
354 ;;; opcode in `(instruction-list)'.
357 (eval-when (expand compile load eval)
358 (define (id-append ctx a b)
359 (datum->syntax ctx (symbol-append (syntax->datum a) (syntax->datum b)))))
361 (define-syntax assembler
363 (define-syntax op-case
366 ((_ asm name ((type arg ...) code ...) clause ...)
367 #`(if (eq? name 'type)
368 (with-syntax (((arg ...) (generate-temporaries #'(arg ...))))
371 (op-case asm name clause ...)))
373 #'(error "unmatched name" name)))))
375 (define (pack-first-word asm opcode type)
376 (with-syntax ((opcode opcode))
382 (emit asm (pack-u8-u24 opcode arg)))
384 (record-label-reference asm label)
387 (emit asm (pack-u8-u8-u16 opcode a (object-address imm))))
389 (emit asm (pack-u8-u12-u12 opcode a b)))
391 (emit asm (pack-u8-u8-u8-u8 opcode a b c))))))
393 (define (pack-tail-word asm type)
397 (emit asm (pack-u8-u24 a b)))
399 (record-label-reference asm label)
402 (emit asm (pack-u8-u8-u16 a b (object-address imm))))
404 (emit asm (pack-u8-u12-u12 a b c)))
405 ((U8_U8_U8_U8 a b c d)
406 (emit asm (pack-u8-u8-u8-u8 a b c d)))
410 (let ((val (object-address imm)))
411 (unless (zero? (ash val -32))
412 (error "FIXME: enable truncation of negative fixnums when cross-compiling"))
415 (unless (= (asm-word-size asm) 8)
416 (error "make-long-immediate unavailable for this target"))
417 (emit asm (ash (object-address imm) -32))
418 (emit asm (logand (object-address imm) (1- (ash 1 32)))))
421 (record-far-label-reference asm label)
424 (record-far-label-reference asm label)
427 (record-far-label-reference asm label)
430 (record-far-label-reference asm label
431 (* offset (/ (asm-word-size asm) 4)))
434 (emit asm (pack-u8-u24 0 a)))
436 (emit asm (pack-u8-u12-u12 0 a b)))
438 (record-label-reference asm label)
441 (record-label-reference asm label)
442 (emit asm (pack-u1-u7-u24 (if a 1 0) 0 0)))
443 ((B1_U7_L24 a b label)
444 (record-label-reference asm label)
445 (emit asm (pack-u1-u7-u24 (if a 1 0) b 0)))
447 (emit asm (pack-u1-u7-u24 (if a 1 0) 0 0)))
449 (emit asm (pack-u1-u7-u24 (if a 1 0) 0 b)))))
452 ((_ name opcode word0 word* ...)
453 (with-syntax ((((formal0 ...)
455 (pack-first-word #'asm
456 (syntax->datum #'opcode)
457 (syntax->datum #'word0)))
460 (map (lambda (word) (pack-tail-word #'asm word))
461 (syntax->datum #'(word* ...)))))
462 #'(lambda (asm formal0 ... formal* ... ...)
463 (unless (asm? asm) (error "not an asm"))
466 (reset-asm-start! asm)))))))
468 (define assemblers (make-hash-table))
470 (define-syntax define-assembler
473 ((_ name opcode kind arg ...)
474 (with-syntax ((emit (id-append #'name #'emit- #'name)))
477 (let ((emit (assembler name opcode arg ...)))
478 (hashq-set! assemblers 'name emit)
482 (define-syntax visit-opcodes
485 ((visit-opcodes macro arg ...)
486 (with-syntax (((inst ...)
487 (map (lambda (x) (datum->syntax #'macro x))
488 (instruction-list))))
490 (macro arg ... . inst)
493 (visit-opcodes define-assembler)
495 (define (emit-text asm instructions)
496 "Assemble @var{instructions} using the assembler @var{asm}.
497 @var{instructions} is a sequence of instructions, expressed as a list of
498 lists. This procedure can be called many times before calling
499 @code{link-assembly}."
500 (for-each (lambda (inst)
501 (apply (or (hashq-ref assemblers (car inst))
502 (error 'bad-instruction inst))
510 ;;; The constant table records a topologically sorted set of literal
511 ;;; constants used by a program. For example, a pair uses its car and
512 ;;; cdr, a string uses its stringbuf, etc.
514 ;;; Some things we want to add to the constant table are not actually
515 ;;; Scheme objects: for example, stringbufs, cache cells for toplevel
516 ;;; references, or cache cells for non-closure procedures. For these we
517 ;;; define special record types and add instances of those record types
521 (define-inlinable (immediate? x)
522 "Return @code{#t} if @var{x} is immediate, and @code{#f} otherwise."
523 (not (zero? (logand (object-address x) 6))))
525 (define-record-type <stringbuf>
526 (make-stringbuf string)
528 (string stringbuf-string))
530 (define-record-type <static-procedure>
531 (make-static-procedure code)
533 (code static-procedure-code))
535 (define-record-type <uniform-vector-backing-store>
536 (make-uniform-vector-backing-store bytes element-size)
537 uniform-vector-backing-store?
538 (bytes uniform-vector-backing-store-bytes)
539 (element-size uniform-vector-backing-store-element-size))
541 (define-record-type <cache-cell>
542 (make-cache-cell scope key)
544 (scope cache-cell-scope)
545 (key cache-cell-key))
547 (define (simple-vector? obj)
549 (equal? (array-shape obj) (list (list 0 (1- (vector-length obj)))))))
551 (define (simple-uniform-vector? obj)
553 (symbol? (array-type obj))
554 (equal? (array-shape obj) (list (list 0 (1- (array-length obj)))))))
556 (define (statically-allocatable? x)
557 "Return @code{#t} if a non-immediate constant can be allocated
558 statically, and @code{#f} if it would need some kind of runtime
560 (or (pair? x) (string? x) (stringbuf? x) (static-procedure? x) (array? x)))
562 (define (intern-constant asm obj)
563 "Add an object to the constant table, and return a label that can be
564 used to reference it. If the object is already present in the constant
565 table, its existing label is used directly."
567 (intern-constant asm obj))
568 (define (field dst n obj)
569 (let ((src (recur obj)))
571 (if (statically-allocatable? obj)
572 `((static-patch! ,dst ,n ,src))
573 `((static-ref 1 ,src)
574 (static-set! 1 ,dst ,n)))
576 (define (intern obj label)
579 (append (field label 0 (car obj))
580 (field label 1 (cdr obj))))
581 ((simple-vector? obj)
582 (let lp ((i 0) (inits '()))
583 (if (< i (vector-length obj))
585 (append-reverse (field label (1+ i) (vector-ref obj i))
588 ((stringbuf? obj) '())
589 ((static-procedure? obj)
590 `((static-patch! ,label 1 ,(static-procedure-code obj))))
591 ((cache-cell? obj) '())
593 `((make-non-immediate 1 ,(recur (symbol->string obj)))
595 (static-set! 1 ,label 0)))
597 `((static-patch! ,label 1 ,(recur (make-stringbuf obj)))))
599 `((static-ref 1 ,(recur (keyword->symbol obj)))
600 (symbol->keyword 1 1)
601 (static-set! 1 ,label 0)))
603 `((make-non-immediate 1 ,(recur (number->string obj)))
605 (static-set! 1 ,label 0)))
606 ((uniform-vector-backing-store? obj) '())
607 ((simple-uniform-vector? obj)
608 (let ((width (case (array-type obj)
611 ;; Bitvectors are addressed in 32-bit units.
612 ;; Although a complex number is 8 or 16 bytes wide,
613 ;; it should be byteswapped in 4 or 8 byte units.
614 ((u32 s32 f32 c32 b) 4)
615 ((u64 s64 f64 c64) 8)
617 (error "unhandled array type" obj)))))
618 `((static-patch! ,label 2
619 ,(recur (make-uniform-vector-backing-store
620 (uniform-array->bytevector obj)
623 (error "don't know how to intern" obj))))
625 ((immediate? obj) #f)
626 ((vhash-assoc obj (asm-constants asm)) => cdr)
628 ;; Note that calling intern may mutate asm-constants and
629 ;; asm-constant-inits.
630 (let* ((label (gensym "constant"))
631 (inits (intern obj label)))
632 (set-asm-constants! asm (vhash-cons obj label (asm-constants asm)))
633 (set-asm-inits! asm (append-reverse inits (asm-inits asm)))
636 (define (intern-non-immediate asm obj)
637 "Intern a non-immediate into the constant table, and return its
639 (when (immediate? obj)
640 (error "expected a non-immediate" obj))
641 (intern-constant asm obj))
643 (define (intern-cache-cell asm scope key)
644 "Intern a cache cell into the constant table, and return its label.
645 If there is already a cache cell with the given scope and key, it is
647 (intern-constant asm (make-cache-cell scope key)))
649 ;; Return the label of the cell that holds the module for a scope.
650 (define (intern-module-cache-cell asm scope)
651 "Intern a cache cell for a module, and return its label."
652 (intern-cache-cell asm scope #t))
658 ;;; Macro assemblers bridge the gap between primitive instructions and
659 ;;; some higher-level operations.
662 (define-syntax define-macro-assembler
665 ((_ (name arg ...) body body* ...)
666 (with-syntax ((emit (id-append #'name #'emit- #'name)))
669 (let ((emit (lambda (arg ...) body body* ...)))
670 (hashq-set! assemblers 'name emit)
674 (define-macro-assembler (load-constant asm dst obj)
677 (let ((bits (object-address obj)))
679 ((and (< dst 256) (zero? (ash bits -16)))
680 (emit-make-short-immediate asm dst obj))
681 ((zero? (ash bits -32))
682 (emit-make-long-immediate asm dst obj))
684 (emit-make-long-long-immediate asm dst obj)))))
685 ((statically-allocatable? obj)
686 (emit-make-non-immediate asm dst (intern-non-immediate asm obj)))
688 (emit-static-ref asm dst (intern-non-immediate asm obj)))))
690 (define-macro-assembler (load-static-procedure asm dst label)
691 (let ((loc (intern-constant asm (make-static-procedure label))))
692 (emit-make-non-immediate asm dst loc)))
694 (define-syntax-rule (define-tc7-macro-assembler name tc7)
695 (define-macro-assembler (name asm slot invert? label)
696 (emit-br-if-tc7 asm slot invert? tc7 label)))
698 ;; Keep in sync with tags.h. Part of Guile's ABI. Currently unused
699 ;; macro assemblers are commented out. See also
700 ;; *branching-primcall-arities* in (language cps primitives), the set of
701 ;; macro-instructions in assembly.scm, and
702 ;; disassembler.scm:code-annotation.
704 ;; FIXME: Define all tc7 values in Scheme in one place, derived from
706 (define-tc7-macro-assembler br-if-symbol 5)
707 (define-tc7-macro-assembler br-if-variable 7)
708 (define-tc7-macro-assembler br-if-vector 13)
709 ;(define-tc7-macro-assembler br-if-weak-vector 13)
710 (define-tc7-macro-assembler br-if-string 21)
711 ;(define-tc7-macro-assembler br-if-heap-number 23)
712 ;(define-tc7-macro-assembler br-if-stringbuf 39)
713 (define-tc7-macro-assembler br-if-bytevector 77)
714 ;(define-tc7-macro-assembler br-if-pointer 31)
715 ;(define-tc7-macro-assembler br-if-hashtable 29)
716 ;(define-tc7-macro-assembler br-if-fluid 37)
717 ;(define-tc7-macro-assembler br-if-dynamic-state 45)
718 ;(define-tc7-macro-assembler br-if-frame 47)
719 ;(define-tc7-macro-assembler br-if-vm 55)
720 ;(define-tc7-macro-assembler br-if-vm-cont 71)
721 ;(define-tc7-macro-assembler br-if-rtl-program 69)
722 ;(define-tc7-macro-assembler br-if-weak-set 85)
723 ;(define-tc7-macro-assembler br-if-weak-table 87)
724 ;(define-tc7-macro-assembler br-if-array 93)
725 (define-tc7-macro-assembler br-if-bitvector 95)
726 ;(define-tc7-macro-assembler br-if-port 125)
727 ;(define-tc7-macro-assembler br-if-smob 127)
729 (define-macro-assembler (begin-program asm label properties)
730 (emit-label asm label)
731 (let ((meta (make-meta label properties (asm-start asm))))
732 (set-asm-meta! asm (cons meta (asm-meta asm)))))
734 (define-macro-assembler (end-program asm)
735 (let ((meta (car (asm-meta asm))))
736 (set-meta-high-pc! meta (asm-start asm))
737 (set-meta-arities! meta (reverse (meta-arities meta)))))
739 (define-macro-assembler (begin-standard-arity asm req nlocals alternate)
740 (emit-begin-opt-arity asm req '() #f nlocals alternate))
742 (define-macro-assembler (begin-opt-arity asm req opt rest nlocals alternate)
743 (emit-begin-kw-arity asm req opt rest '() #f nlocals alternate))
745 (define-macro-assembler (begin-kw-arity asm req opt rest kw-indices
746 allow-other-keys? nlocals alternate)
747 (assert-match req ((? symbol?) ...) "list of symbols")
748 (assert-match opt ((? symbol?) ...) "list of symbols")
749 (assert-match rest (or #f (? symbol?)) "#f or symbol")
750 (assert-match kw-indices (((? keyword?) . (? integer?)) ...)
751 "alist of keyword -> integer")
752 (assert-match allow-other-keys? (? boolean?) "boolean")
753 (assert-match nlocals (? integer?) "integer")
754 (assert-match alternate (or #f (? exact-integer?) (? symbol?)) "#f or symbol")
755 (let* ((meta (car (asm-meta asm)))
756 (arity (make-arity req opt rest kw-indices allow-other-keys?
757 (asm-start asm) #f '()))
758 ;; The procedure itself is in slot 0, in the standard calling
759 ;; convention. For procedure prologues, nreq includes the
760 ;; procedure, so here we add 1.
761 (nreq (1+ (length req)))
763 (rest? (->bool rest)))
764 (set-meta-arities! meta (cons arity (meta-arities meta)))
766 ((or allow-other-keys? (pair? kw-indices))
767 (emit-kw-prelude asm nreq nopt rest? kw-indices allow-other-keys?
769 ((or rest? (pair? opt))
770 (emit-opt-prelude asm nreq nopt rest? nlocals alternate))
772 (emit-standard-prelude asm nreq nlocals alternate)))))
774 (define-macro-assembler (end-arity asm)
775 (let ((arity (car (meta-arities (car (asm-meta asm))))))
776 (set-arity-definitions! arity (reverse (arity-definitions arity)))
777 (set-arity-high-pc! arity (asm-start asm))))
779 (define-macro-assembler (standard-prelude asm nreq nlocals alternate)
782 (emit-br-if-nargs-ne asm nreq alternate)
783 (emit-alloc-frame asm nlocals))
784 ((and (< nreq (ash 1 12)) (< (- nlocals nreq) (ash 1 12)))
785 (emit-assert-nargs-ee/locals asm nreq (- nlocals nreq)))
787 (emit-assert-nargs-ee asm nreq)
788 (emit-alloc-frame asm nlocals))))
790 (define-macro-assembler (opt-prelude asm nreq nopt rest? nlocals alternate)
792 (emit-br-if-nargs-lt asm nreq alternate)
793 (emit-assert-nargs-ge asm nreq))
796 (emit-bind-rest asm (+ nreq nopt)))
798 (emit-br-if-nargs-gt asm (+ nreq nopt) alternate))
800 (emit-assert-nargs-le asm (+ nreq nopt))))
801 (emit-alloc-frame asm nlocals))
803 (define-macro-assembler (kw-prelude asm nreq nopt rest? kw-indices
804 allow-other-keys? nlocals alternate)
807 (emit-br-if-nargs-lt asm nreq alternate)
809 (emit-br-if-npos-gt asm nreq (+ nreq nopt) alternate)))
810 (emit-assert-nargs-ge asm nreq))
811 (let ((ntotal (fold (lambda (kw ntotal)
813 (((? keyword?) . idx)
814 (max (1+ idx) ntotal))))
815 (+ nreq nopt) kw-indices)))
816 ;; FIXME: port 581f410f
817 (emit-bind-kwargs asm nreq
818 (pack-flags allow-other-keys? rest?)
821 (intern-constant asm kw-indices))
822 (emit-alloc-frame asm nlocals)))
824 (define-macro-assembler (label asm sym)
825 (hashq-set! (asm-labels asm) sym (asm-start asm)))
827 (define-macro-assembler (source asm source)
828 (set-asm-sources! asm (acons (asm-start asm) source (asm-sources asm))))
830 (define-macro-assembler (definition asm name slot)
831 (let* ((arity (car (meta-arities (car (asm-meta asm)))))
832 (def (vector name slot (- (asm-start asm) (arity-low-pc arity)))))
833 (set-arity-definitions! arity (cons def (arity-definitions arity)))))
835 (define-macro-assembler (cache-current-module! asm module scope)
836 (let ((mod-label (intern-module-cache-cell asm scope)))
837 (emit-static-set! asm module mod-label 0)))
839 (define-macro-assembler (cached-toplevel-box asm dst scope sym bound?)
840 (let ((sym-label (intern-non-immediate asm sym))
841 (mod-label (intern-module-cache-cell asm scope))
842 (cell-label (intern-cache-cell asm scope sym)))
843 (emit-toplevel-box asm dst cell-label mod-label sym-label bound?)))
845 (define-macro-assembler (cached-module-box asm dst module-name sym public? bound?)
846 (let* ((sym-label (intern-non-immediate asm sym))
847 (key (cons public? module-name))
848 (mod-name-label (intern-constant asm key))
849 (cell-label (intern-cache-cell asm key sym)))
850 (emit-module-box asm dst cell-label mod-name-label sym-label bound?)))
852 (define-macro-assembler (dead-slot-map asm proc-slot dead-slot-map)
853 (unless (zero? dead-slot-map)
854 (set-asm-dead-slot-maps! asm
856 (cons* (asm-start asm) proc-slot dead-slot-map)
857 (asm-dead-slot-maps asm)))))
862 ;;; Helper for linking objects.
865 (define (make-object asm name bv relocs labels . kwargs)
866 "Make a linker object. This helper handles interning the name in the
867 shstrtab, assigning the size, allocating a fresh index, and defining a
868 corresponding linker symbol for the start of the section."
869 (let ((name-idx (intern-section-name! asm (symbol->string name)))
870 (index (asm-next-section-number asm)))
871 (set-asm-next-section-number! asm (1+ index))
872 (make-linker-object (apply make-elf-section
875 #:size (bytevector-length bv)
878 (cons (make-linker-symbol name 0) labels))))
884 ;;; Linking the constant table. This code is somewhat intertwingled
885 ;;; with the intern-constant code above, as that procedure also
886 ;;; residualizes instructions to initialize constants at load time.
889 (define (write-immediate asm buf pos x)
890 (let ((val (object-address x))
891 (endianness (asm-endianness asm)))
892 (case (asm-word-size asm)
893 ((4) (bytevector-u32-set! buf pos val endianness))
894 ((8) (bytevector-u64-set! buf pos val endianness))
895 (else (error "bad word size" asm)))))
897 (define (emit-init-constants asm)
898 "If there is writable data that needs initialization at runtime, emit
899 a procedure to do that and return its label. Otherwise return
901 (let ((inits (asm-inits asm)))
902 (and (not (null? inits))
903 (let ((label (gensym "init-constants")))
905 `((begin-program ,label ())
906 (assert-nargs-ee/locals 1 1)
908 (load-constant 1 ,*unspecified*)
913 (define (link-data asm data name)
914 "Link the static data for a program into the @var{name} section (which
915 should be .data or .rodata), and return the resulting linker object.
916 @var{data} should be a vhash mapping objects to labels."
917 (define (align address alignment)
919 (modulo (- alignment (modulo address alignment)) alignment)))
921 (define tc7-vector 13)
922 (define stringbuf-shared-flag #x100)
923 (define stringbuf-wide-flag #x400)
924 (define tc7-stringbuf 39)
925 (define tc7-narrow-stringbuf
926 (+ tc7-stringbuf stringbuf-shared-flag))
927 (define tc7-wide-stringbuf
928 (+ tc7-stringbuf stringbuf-shared-flag stringbuf-wide-flag))
929 (define tc7-ro-string (+ 21 #x200))
930 (define tc7-program 69)
931 (define tc7-bytevector 77)
932 (define tc7-bitvector 95)
934 (let ((word-size (asm-word-size asm))
935 (endianness (asm-endianness asm)))
936 (define (byte-length x)
939 (let ((x (stringbuf-string x)))
941 (case (string-bytes-per-char x)
942 ((1) (1+ (string-length x)))
943 ((4) (* (1+ (string-length x)) 4))
944 (else (error "bad string bytes per char" x))))))
945 ((static-procedure? x)
952 (* (1+ (vector-length x)) word-size))
953 ((simple-uniform-vector? x)
955 ((uniform-vector-backing-store? x)
956 (bytevector-length (uniform-vector-backing-store-bytes x)))
960 (define (write-constant-reference buf pos x)
961 ;; The asm-inits will fix up any reference to a non-immediate.
962 (write-immediate asm buf pos (if (immediate? x) x #f)))
964 (define (write buf pos obj)
967 (let* ((x (stringbuf-string obj))
968 (len (string-length x))
969 (tag (if (= (string-bytes-per-char x) 1)
971 tc7-wide-stringbuf)))
974 (bytevector-u32-set! buf pos tag endianness)
975 (bytevector-u32-set! buf (+ pos 4) len endianness))
977 (bytevector-u64-set! buf pos tag endianness)
978 (bytevector-u64-set! buf (+ pos 8) len endianness))
980 (error "bad word size" asm)))
981 (let ((pos (+ pos (* word-size 2))))
982 (case (string-bytes-per-char x)
986 (let ((u8 (char->integer (string-ref x i))))
987 (bytevector-u8-set! buf (+ pos i) u8)
989 (bytevector-u8-set! buf (+ pos i) 0))))
993 (let ((u32 (char->integer (string-ref x i))))
994 (bytevector-u32-set! buf (+ pos (* i 4)) u32 endianness)
996 (bytevector-u32-set! buf (+ pos (* i 4)) 0 endianness))))
997 (else (error "bad string bytes per char" x))))))
999 ((static-procedure? obj)
1002 (bytevector-u32-set! buf pos tc7-program endianness)
1003 (bytevector-u32-set! buf (+ pos 4) 0 endianness))
1005 (bytevector-u64-set! buf pos tc7-program endianness)
1006 (bytevector-u64-set! buf (+ pos 8) 0 endianness))
1007 (else (error "bad word size"))))
1010 (write-immediate asm buf pos #f))
1013 (let ((tag (logior tc7-ro-string (ash (string-length obj) 8))))
1016 (bytevector-u32-set! buf pos tc7-ro-string endianness)
1017 (write-immediate asm buf (+ pos 4) #f) ; stringbuf
1018 (bytevector-u32-set! buf (+ pos 8) 0 endianness)
1019 (bytevector-u32-set! buf (+ pos 12) (string-length obj) endianness))
1021 (bytevector-u64-set! buf pos tc7-ro-string endianness)
1022 (write-immediate asm buf (+ pos 8) #f) ; stringbuf
1023 (bytevector-u64-set! buf (+ pos 16) 0 endianness)
1024 (bytevector-u64-set! buf (+ pos 24) (string-length obj) endianness))
1025 (else (error "bad word size")))))
1028 (write-constant-reference buf pos (car obj))
1029 (write-constant-reference buf (+ pos word-size) (cdr obj)))
1031 ((simple-vector? obj)
1032 (let* ((len (vector-length obj))
1033 (tag (logior tc7-vector (ash len 8))))
1035 ((4) (bytevector-u32-set! buf pos tag endianness))
1036 ((8) (bytevector-u64-set! buf pos tag endianness))
1037 (else (error "bad word size")))
1039 (when (< i (vector-length obj))
1040 (let ((pos (+ pos word-size (* i word-size)))
1041 (elt (vector-ref obj i)))
1042 (write-constant-reference buf pos elt)
1046 (write-immediate asm buf pos #f))
1049 (write-immediate asm buf pos #f))
1052 (write-immediate asm buf pos #f))
1054 ((simple-uniform-vector? obj)
1055 (let ((tag (if (bitvector? obj)
1057 (let ((type-code (array-type-code obj)))
1058 (logior tc7-bytevector (ash type-code 7))))))
1061 (bytevector-u32-set! buf pos tag endianness)
1062 (bytevector-u32-set! buf (+ pos 4)
1063 (if (bitvector? obj)
1064 (bitvector-length obj)
1065 (bytevector-length obj))
1066 endianness) ; length
1067 (bytevector-u32-set! buf (+ pos 8) 0 endianness) ; pointer
1068 (write-immediate asm buf (+ pos 12) #f)) ; owner
1070 (bytevector-u64-set! buf pos tag endianness)
1071 (bytevector-u64-set! buf (+ pos 8)
1072 (if (bitvector? obj)
1073 (bitvector-length obj)
1074 (bytevector-length obj))
1075 endianness) ; length
1076 (bytevector-u64-set! buf (+ pos 16) 0 endianness) ; pointer
1077 (write-immediate asm buf (+ pos 24) #f)) ; owner
1078 (else (error "bad word size")))))
1080 ((uniform-vector-backing-store? obj)
1081 (let ((bv (uniform-vector-backing-store-bytes obj)))
1082 (bytevector-copy! bv 0 buf pos (bytevector-length bv))
1083 (unless (or (= 1 (uniform-vector-backing-store-element-size obj))
1084 (eq? endianness (native-endianness)))
1085 ;; Need to swap units of element-size bytes
1086 (error "FIXME: Implement byte order swap"))))
1089 (error "unrecognized object" obj))))
1092 ((vlist-null? data) #f)
1094 (let* ((byte-len (vhash-fold (lambda (k v len)
1095 (+ (byte-length k) (align len 8)))
1097 (buf (make-bytevector byte-len 0)))
1098 (let lp ((i 0) (pos 0) (symbols '()))
1099 (if (< i (vlist-length data))
1100 (let* ((pair (vlist-ref data i))
1102 (obj-label (cdr pair)))
1105 (align (+ (byte-length obj) pos) 8)
1106 (cons (make-linker-symbol obj-label pos) symbols)))
1107 (make-object asm name buf '() symbols
1109 ('.data (logior SHF_ALLOC SHF_WRITE))
1110 ('.rodata SHF_ALLOC))))))))))
1112 (define (link-constants asm)
1113 "Link sections to hold constants needed by the program text emitted
1116 Returns three values: an object for the .rodata section, an object for
1117 the .data section, and a label for an initialization procedure. Any of
1118 these may be @code{#f}."
1119 (define (shareable? x)
1123 (and (immediate? (car x)) (immediate? (cdr x))))
1126 (or (= i (vector-length x))
1127 (and (immediate? (vector-ref x i))
1129 ((uniform-vector-backing-store? x) #t)
1131 (let* ((constants (asm-constants asm))
1132 (len (vlist-length constants)))
1137 (values (link-data asm ro '.rodata)
1138 (link-data asm rw '.data)
1139 (emit-init-constants asm))
1140 (let ((pair (vlist-ref constants i)))
1141 (if (shareable? (car pair))
1142 (lp (1+ i) (vhash-consq (car pair) (cdr pair) ro) rw)
1143 (lp (1+ i) ro (vhash-consq (car pair) (cdr pair) rw))))))))
1148 ;;; Linking program text.
1151 (define (process-relocs buf relocs labels)
1152 "Patch up internal x8-s24 relocations, and any s32 relocations that
1153 reference symbols in the text section. Return a list of linker
1154 relocations for references to symbols defined outside the text section."
1156 (lambda (reloc tail)
1158 ((type label base word)
1159 (let ((abs (hashq-ref labels label))
1160 (dst (+ base word)))
1164 (let ((rel (- abs base)))
1165 (s32-set! buf dst rel)
1167 (cons (make-linker-reloc 'rel32/4 (* dst 4) word label)
1171 (error "unbound near relocation" reloc))
1172 (let ((rel (- abs base))
1173 (u32 (u32-ref buf dst)))
1174 (u32-set! buf dst (pack-u8-s24 (logand u32 #xff) rel))
1176 (else (error "bad relocation kind" reloc)))))))
1180 (define (process-labels labels)
1181 "Define linker symbols for the label-offset map in @var{labels}.
1182 The offsets are expected to be expressed in words."
1183 (hash-map->list (lambda (label loc)
1184 (make-linker-symbol label (* loc 4)))
1187 (define (swap-bytes! buf)
1188 "Patch up the text buffer @var{buf}, swapping the endianness of each
1190 (unless (zero? (modulo (bytevector-length buf) 4))
1191 (error "unexpected length"))
1192 (let ((byte-len (bytevector-length buf)))
1194 (unless (= pos byte-len)
1195 (bytevector-u32-set!
1197 (bytevector-u32-ref buf pos (endianness big))
1198 (endianness little))
1201 (define (link-text-object asm)
1202 "Link the .rtl-text section, swapping the endianness of the bytes if
1204 (let ((buf (make-u32vector (asm-pos asm))))
1205 (let lp ((pos 0) (prev (reverse (asm-prev asm))))
1207 (let ((byte-size (* (asm-idx asm) 4)))
1208 (bytevector-copy! (asm-cur asm) 0 buf pos byte-size)
1209 (unless (eq? (asm-endianness asm) (native-endianness))
1211 (make-object asm '.rtl-text
1213 (process-relocs buf (asm-relocs asm)
1215 (process-labels (asm-labels asm))))
1216 (let ((len (* *block-size* 4)))
1217 (bytevector-copy! (car prev) 0 buf pos len)
1218 (lp (+ pos len) (cdr prev)))))))
1224 ;;; Create the frame maps. These maps are used by GC to identify dead
1225 ;;; slots in pending call frames, to avoid marking them. We only do
1226 ;;; this when frame makes a non-tail call, as that is the common case.
1227 ;;; Only the topmost frame will see a GC at any other point, but we mark
1228 ;;; top frames conservatively as serializing live slot maps at every
1229 ;;; instruction would take up too much space in the object file.
1232 ;; The .guile.frame-maps section starts with two packed u32 values: one
1233 ;; indicating the offset of the first byte of the .rtl-text section, and
1234 ;; another indicating the relative offset in bytes of the slots data.
1235 (define frame-maps-prefix-len 8)
1237 ;; Each header is 8 bytes: 4 for the offset from .rtl_text, and 4 for
1238 ;; the offset of the slot map from the beginning of the
1239 ;; .guile.frame-maps section. The length of a frame map depends on the
1240 ;; frame size at the call site, and is not encoded into this section as
1241 ;; it is available at run-time.
1242 (define frame-map-header-len 8)
1244 (define (link-frame-maps asm)
1245 (define (map-byte-length proc-slot)
1246 (ceiling-quotient (- proc-slot 2) 8))
1247 (define (make-frame-maps maps count map-len)
1248 (let* ((endianness (asm-endianness asm))
1249 (header-pos frame-maps-prefix-len)
1250 (map-pos (+ header-pos (* count frame-map-header-len)))
1251 (bv (make-bytevector (+ map-pos map-len) 0)))
1252 (bytevector-u32-set! bv 4 map-pos endianness)
1253 (let lp ((maps maps) (header-pos header-pos) (map-pos map-pos))
1256 (make-object asm '.guile.frame-maps bv
1257 (list (make-linker-reloc 'abs32/1 0 0 '.rtl-text))
1258 '() #:type SHT_PROGBITS #:flags SHF_ALLOC))
1259 (((pos proc-slot . map) . maps)
1260 (bytevector-u32-set! bv header-pos (* pos 4) endianness)
1261 (bytevector-u32-set! bv (+ header-pos 4) map-pos endianness)
1262 (let write-bytes ((map-pos map-pos)
1264 (byte-length (map-byte-length proc-slot)))
1265 (if (zero? byte-length)
1266 (lp maps (+ header-pos frame-map-header-len) map-pos)
1268 (bytevector-u8-set! bv map-pos (logand map #xff))
1269 (write-bytes (1+ map-pos) (ash map -8)
1270 (1- byte-length))))))))))
1271 (match (asm-dead-slot-maps asm)
1274 (let lp ((in in) (out '()) (count 0) (map-len 0))
1276 (() (make-frame-maps out count map-len))
1277 (((and head (pos proc-slot . map)) . in)
1278 (lp in (cons head out)
1280 (+ (map-byte-length proc-slot) map-len))))))))
1285 ;;; Linking other sections of the ELF file, like the dynamic segment,
1286 ;;; the symbol table, etc.
1289 ;; FIXME: Define these somewhere central, shared with C.
1290 (define *bytecode-major-version* #x0202)
1291 (define *bytecode-minor-version* 4)
1293 (define (link-dynamic-section asm text rw rw-init frame-maps)
1294 "Link the dynamic section for an ELF image with bytecode @var{text},
1295 given the writable data section @var{rw} needing fixup from the
1296 procedure with label @var{rw-init}. @var{rw-init} may be false. If
1297 @var{rw} is true, it will be added to the GC roots at runtime."
1298 (define-syntax-rule (emit-dynamic-section word-size %set-uword! reloc-type)
1299 (let* ((endianness (asm-endianness asm))
1301 (words (if rw (+ words 4) words))
1302 (words (if rw-init (+ words 2) words))
1303 (words (if frame-maps (+ words 2) words))
1304 (bv (make-bytevector (* word-size words) 0))
1307 (%set-uword! bv (* i word-size) uword endianness)))
1311 (set! relocs (cons (make-linker-reloc 'reloc-type
1312 (* i word-size) 0 label)
1314 (%set-uword! bv (* i word-size) 0 endianness))))
1315 (set-uword! 0 DT_GUILE_VM_VERSION)
1316 (set-uword! 1 (logior (ash *bytecode-major-version* 16)
1317 *bytecode-minor-version*))
1318 (set-uword! 2 DT_GUILE_ENTRY)
1319 (set-label! 3 '.rtl-text)
1322 (set-uword! 4 DT_GUILE_GC_ROOT)
1323 (set-label! 5 '.data)
1324 (set-uword! 6 DT_GUILE_GC_ROOT_SZ)
1325 (set-uword! 7 (bytevector-length (linker-object-bv rw)))
1327 (set-uword! 8 DT_INIT) ; constants
1328 (set-label! 9 rw-init)))
1330 (set-uword! (- words 4) DT_GUILE_FRAME_MAPS)
1331 (set-label! (- words 3) '.guile.frame-maps))
1332 (set-uword! (- words 2) DT_NULL)
1333 (set-uword! (- words 1) 0)
1334 (make-object asm '.dynamic bv relocs '()
1335 #:type SHT_DYNAMIC #:flags SHF_ALLOC)))
1336 (case (asm-word-size asm)
1337 ((4) (emit-dynamic-section 4 bytevector-u32-set! abs32/1))
1338 ((8) (emit-dynamic-section 8 bytevector-u64-set! abs64/1))
1339 (else (error "bad word size" asm))))
1341 (define (link-shstrtab asm)
1342 "Link the string table for the section headers."
1343 (intern-section-name! asm ".shstrtab")
1344 (make-object asm '.shstrtab
1345 (link-string-table! (asm-shstrtab asm))
1347 #:type SHT_STRTAB #:flags 0))
1349 (define (link-symtab text-section asm)
1350 (let* ((endianness (asm-endianness asm))
1351 (word-size (asm-word-size asm))
1352 (size (elf-symbol-len word-size))
1353 (meta (reverse (asm-meta asm)))
1355 (strtab (make-string-table))
1356 (bv (make-bytevector (* n size) 0)))
1357 (define (intern-string! name)
1358 (string-table-intern! strtab (if name (symbol->string name) "")))
1361 (let ((name (intern-string! (meta-name meta))))
1362 (write-elf-symbol bv (* n size) endianness word-size
1365 ;; Symbol value and size are measured in
1367 #:value (* 4 (meta-low-pc meta))
1368 #:size (* 4 (- (meta-high-pc meta)
1369 (meta-low-pc meta)))
1371 #:visibility STV_HIDDEN
1372 #:shndx (elf-section-index text-section)))))
1374 (let ((strtab (make-object asm '.strtab
1375 (link-string-table! strtab)
1377 #:type SHT_STRTAB #:flags 0)))
1378 (values (make-object asm '.symtab
1381 #:type SHT_SYMTAB #:flags 0 #:entsize size
1382 #:link (elf-section-index
1383 (linker-object-section strtab)))
1386 ;;; The .guile.arities section describes the arities that a function can
1387 ;;; have. It is in two parts: a sorted array of headers describing
1388 ;;; basic arities, and an array of links out to a string table (and in
1389 ;;; the case of keyword arguments, to the data section) for argument
1390 ;;; names. The whole thing is prefixed by a uint32 indicating the
1391 ;;; offset of the end of the headers array.
1393 ;;; The arity headers array is a packed array of structures of the form:
1395 ;;; struct arity_header {
1396 ;;; uint32_t low_pc;
1397 ;;; uint32_t high_pc;
1398 ;;; uint32_t offset;
1404 ;;; All of the offsets and addresses are 32 bits. We can expand in the
1405 ;;; future to use 64-bit offsets if appropriate, but there are other
1406 ;;; aspects of bytecode that constrain us to a total image that fits in
1407 ;;; 32 bits, so for the moment we'll simplify the problem space.
1409 ;;; The following flags values are defined:
1412 ;;; #x2: allow-other-keys?
1413 ;;; #x4: has-keyword-args?
1414 ;;; #x8: is-case-lambda?
1415 ;;; #x10: is-in-case-lambda?
1417 ;;; Functions with a single arity specify their number of required and
1418 ;;; optional arguments in nreq and nopt, and do not have the
1419 ;;; is-case-lambda? flag set. Their "offset" member links to an array
1420 ;;; of pointers into the associated .guile.arities.strtab string table,
1421 ;;; identifying the argument names. This offset is relative to the
1422 ;;; start of the .guile.arities section.
1424 ;;; If the arity has keyword arguments -- if has-keyword-args? is set in
1425 ;;; the flags -- the first uint32 pointed to by offset encodes a link to
1426 ;;; the "keyword indices" literal, in the data section. Then follow
1427 ;;; links for required arguments are first, in order, as uint32 values.
1428 ;;; Next follow the optionals, then the rest link if has-rest? is set.
1429 ;;; Unlike the other links, the kw-indices link points into the data
1430 ;;; section, and is relative to the ELF image as a whole.
1432 ;;; Functions with no arities have no arities information present in the
1433 ;;; .guile.arities section.
1435 ;;; Functions with multiple arities are preceded by a header with
1436 ;;; is-case-lambda? set. All other fields are 0, except low-pc and
1437 ;;; high-pc which should be the bounds of the whole function. Headers
1438 ;;; for the individual arities follow, with the is-in-case-lambda? flag
1439 ;;; set. In this way the whole headers array is sorted in increasing
1440 ;;; low-pc order, and case-lambda clauses are contained within the
1441 ;;; [low-pc, high-pc] of the case-lambda header.
1443 ;; Length of the prefix to the arities section, in bytes.
1444 (define arities-prefix-len 4)
1446 ;; Length of an arity header, in bytes.
1447 (define arity-header-len (* 6 4))
1449 ;; The offset of "offset" within arity header, in bytes.
1450 (define arity-header-offset-offset (* 2 4))
1452 (define-syntax-rule (pack-arity-flags has-rest? allow-other-keys?
1453 has-keyword-args? is-case-lambda?
1455 (logior (if has-rest? (ash 1 0) 0)
1456 (if allow-other-keys? (ash 1 1) 0)
1457 (if has-keyword-args? (ash 1 2) 0)
1458 (if is-case-lambda? (ash 1 3) 0)
1459 (if is-in-case-lambda? (ash 1 4) 0)))
1461 (define (meta-arities-size meta)
1462 (define (lambda-size arity)
1464 (* 4 ;; name pointers
1465 (+ (if (pair? (arity-kw-indices arity)) 1 0)
1466 (length (arity-req arity))
1467 (length (arity-opt arity))
1468 (if (arity-rest arity) 1 0)))))
1469 (define (case-lambda-size arities)
1471 arity-header-len ;; case-lambda header
1472 (map lambda-size arities))) ;; the cases
1473 (match (meta-arities meta)
1475 ((arity) (lambda-size arity))
1476 (arities (case-lambda-size arities))))
1478 (define (write-arity-headers metas bv endianness)
1479 (define (write-arity-header* pos low-pc high-pc flags nreq nopt)
1480 (bytevector-u32-set! bv pos (* low-pc 4) endianness)
1481 (bytevector-u32-set! bv (+ pos 4) (* high-pc 4) endianness)
1482 (bytevector-u32-set! bv (+ pos 8) 0 endianness) ; offset
1483 (bytevector-u32-set! bv (+ pos 12) flags endianness)
1484 (bytevector-u32-set! bv (+ pos 16) nreq endianness)
1485 (bytevector-u32-set! bv (+ pos 20) nopt endianness))
1486 (define (write-arity-header pos arity in-case-lambda?)
1487 (write-arity-header* pos (arity-low-pc arity)
1488 (arity-high-pc arity)
1489 (pack-arity-flags (arity-rest arity)
1490 (arity-allow-other-keys? arity)
1491 (pair? (arity-kw-indices arity))
1494 (length (arity-req arity))
1495 (length (arity-opt arity))))
1496 (let lp ((metas metas) (pos arities-prefix-len) (offsets '()))
1499 ;; Fill in the prefix.
1500 (bytevector-u32-set! bv 0 pos endianness)
1501 (values pos (reverse offsets)))
1503 (match (meta-arities meta)
1504 (() (lp metas pos offsets))
1506 (write-arity-header pos arity #f)
1508 (+ pos arity-header-len)
1509 (acons arity (+ pos arity-header-offset-offset) offsets)))
1511 ;; Write a case-lambda header, then individual arities.
1512 ;; The case-lambda header's offset link is 0.
1513 (write-arity-header* pos (meta-low-pc meta) (meta-high-pc meta)
1514 (pack-arity-flags #f #f #f #t #f) 0 0)
1515 (let lp* ((arities arities) (pos (+ pos arity-header-len))
1518 (() (lp metas pos offsets))
1520 (write-arity-header pos arity #t)
1522 (+ pos arity-header-len)
1524 (+ pos arity-header-offset-offset)
1527 (define (write-arity-links asm bv pos arity-offset-pairs strtab)
1528 (define (write-symbol sym pos)
1529 (bytevector-u32-set! bv pos
1530 (string-table-intern! strtab (symbol->string sym))
1531 (asm-endianness asm))
1533 (define (write-kw-indices pos kw-indices)
1534 ;; FIXME: Assert that kw-indices is already interned.
1535 (make-linker-reloc 'abs32/1 pos 0
1536 (intern-constant asm kw-indices)))
1537 (let lp ((pos pos) (pairs arity-offset-pairs) (relocs '()))
1540 (unless (= pos (bytevector-length bv))
1541 (error "expected to fully fill the bytevector"
1542 pos (bytevector-length bv)))
1544 (((arity . offset) . pairs)
1545 (bytevector-u32-set! bv offset pos (asm-endianness asm))
1548 (match (arity-kw-indices arity)
1549 (() (values pos relocs))
1552 (cons (write-kw-indices pos kw-indices) relocs)))))
1553 (lambda (pos relocs)
1554 (lp (fold write-symbol
1556 (append (arity-req arity)
1559 ((arity-rest arity) => list)
1564 (define (link-arities asm)
1565 (let* ((endianness (asm-endianness asm))
1566 (metas (reverse (asm-meta asm)))
1567 (size (fold (lambda (meta size)
1568 (+ size (meta-arities-size meta)))
1571 (strtab (make-string-table))
1572 (bv (make-bytevector size 0)))
1573 (let ((kw-indices-relocs
1576 (write-arity-headers metas bv endianness))
1577 (lambda (pos arity-offset-pairs)
1578 (write-arity-links asm bv pos arity-offset-pairs strtab)))))
1579 (let ((strtab (make-object asm '.guile.arities.strtab
1580 (link-string-table! strtab)
1582 #:type SHT_STRTAB #:flags 0)))
1583 (values (make-object asm '.guile.arities
1585 kw-indices-relocs '()
1586 #:type SHT_PROGBITS #:flags 0
1587 #:link (elf-section-index
1588 (linker-object-section strtab)))
1592 ;;; The .guile.docstrs section is a packed, sorted array of (pc, str)
1593 ;;; values. Pc and str are both 32 bits wide. (Either could change to
1594 ;;; 64 bits if appropriate in the future.) Pc is the address of the
1595 ;;; entry to a program, relative to the start of the text section, in
1596 ;;; bytes, and str is an index into the associated .guile.docstrs.strtab
1597 ;;; string table section.
1600 ;; The size of a docstrs entry, in bytes.
1601 (define docstr-size 8)
1603 (define (link-docstrs asm)
1604 (define (find-docstrings)
1605 (filter-map (lambda (meta)
1606 (define (is-documentation? pair)
1607 (eq? (car pair) 'documentation))
1608 (let* ((props (meta-properties meta))
1609 (tail (find-tail is-documentation? props)))
1611 (not (find-tail is-documentation? (cdr tail)))
1612 (string? (cdar tail))
1613 (cons (* 4 (meta-low-pc meta)) (cdar tail)))))
1614 (reverse (asm-meta asm))))
1615 (let* ((endianness (asm-endianness asm))
1616 (docstrings (find-docstrings))
1617 (strtab (make-string-table))
1618 (bv (make-bytevector (* (length docstrings) docstr-size) 0)))
1619 (fold (lambda (pair pos)
1622 (bytevector-u32-set! bv pos pc endianness)
1623 (bytevector-u32-set! bv (+ pos 4)
1624 (string-table-intern! strtab string)
1626 (+ pos docstr-size))))
1629 (let ((strtab (make-object asm '.guile.docstrs.strtab
1630 (link-string-table! strtab)
1632 #:type SHT_STRTAB #:flags 0)))
1633 (values (make-object asm '.guile.docstrs
1636 #:type SHT_PROGBITS #:flags 0
1637 #:link (elf-section-index
1638 (linker-object-section strtab)))
1642 ;;; The .guile.procprops section is a packed, sorted array of (pc, addr)
1643 ;;; values. Pc and addr are both 32 bits wide. (Either could change to
1644 ;;; 64 bits if appropriate in the future.) Pc is the address of the
1645 ;;; entry to a program, relative to the start of the text section, and
1646 ;;; addr is the address of the associated properties alist, relative to
1647 ;;; the start of the ELF image.
1649 ;;; Since procedure properties are stored in the data sections, we need
1650 ;;; to link the procedures property section first. (Note that this
1651 ;;; constraint does not apply to the arities section, which may
1652 ;;; reference the data sections via the kw-indices literal, because
1653 ;;; assembling the text section already makes sure that the kw-indices
1657 ;; The size of a procprops entry, in bytes.
1658 (define procprops-size 8)
1660 (define (link-procprops asm)
1661 (define (assoc-remove-one alist key value-pred)
1664 ((((? (lambda (x) (eq? x key))) . value) . alist)
1665 (if (value-pred value)
1667 (acons key value alist)))
1669 (acons k v (assoc-remove-one alist key value-pred)))))
1670 (define (props-without-name-or-docstring meta)
1672 (assoc-remove-one (meta-properties meta) 'name (lambda (x) #t))
1675 (define (find-procprops)
1676 (filter-map (lambda (meta)
1677 (let ((props (props-without-name-or-docstring meta)))
1679 (cons (* 4 (meta-low-pc meta)) props))))
1680 (reverse (asm-meta asm))))
1681 (let* ((endianness (asm-endianness asm))
1682 (procprops (find-procprops))
1683 (bv (make-bytevector (* (length procprops) procprops-size) 0)))
1684 (let lp ((procprops procprops) (pos 0) (relocs '()))
1687 (make-object asm '.guile.procprops
1690 #:type SHT_PROGBITS #:flags 0))
1691 (((pc . props) . procprops)
1692 (bytevector-u32-set! bv pos pc endianness)
1694 (+ pos procprops-size)
1695 (cons (make-linker-reloc 'abs32/1 (+ pos 4) 0
1696 (intern-constant asm props))
1700 ;;; The DWARF .debug_info, .debug_abbrev, .debug_str, and .debug_loc
1701 ;;; sections provide line number and local variable liveness
1702 ;;; information. Their format is defined by the DWARF
1706 (define (asm-language asm)
1707 ;; FIXME: Plumb language through to the assembler.
1710 ;; -> 5 values: .debug_info, .debug_abbrev, .debug_str, .debug_loc, .debug_lines
1711 (define (link-debug asm)
1712 (define (put-s8 port val)
1713 (let ((bv (make-bytevector 1)))
1714 (bytevector-s8-set! bv 0 val)
1715 (put-bytevector port bv)))
1717 (define (put-u16 port val)
1718 (let ((bv (make-bytevector 2)))
1719 (bytevector-u16-set! bv 0 val (asm-endianness asm))
1720 (put-bytevector port bv)))
1722 (define (put-u32 port val)
1723 (let ((bv (make-bytevector 4)))
1724 (bytevector-u32-set! bv 0 val (asm-endianness asm))
1725 (put-bytevector port bv)))
1727 (define (put-u64 port val)
1728 (let ((bv (make-bytevector 8)))
1729 (bytevector-u64-set! bv 0 val (asm-endianness asm))
1730 (put-bytevector port bv)))
1732 (define (put-uleb128 port val)
1734 (let ((next (ash val -7)))
1738 (put-u8 port (logior #x80 (logand val #x7f)))
1741 (define (put-sleb128 port val)
1743 (if (<= 0 (+ val 64) 127)
1744 (put-u8 port (logand val #x7f))
1746 (put-u8 port (logior #x80 (logand val #x7f)))
1747 (lp (ash val -7))))))
1749 (define (port-position port)
1750 (seek port 0 SEEK_CUR))
1752 (define (meta->subprogram-die meta)
1756 => (lambda (name) `((name ,(symbol->string name)))))
1759 (low-pc ,(meta-label meta))
1760 (high-pc ,(* 4 (- (meta-high-pc meta) (meta-low-pc meta)))))))
1762 (define (make-compile-unit-die asm)
1764 (@ (producer ,(string-append "Guile " (version)))
1765 (language ,(asm-language asm))
1767 (high-pc ,(* 4 (asm-pos asm)))
1769 ,@(map meta->subprogram-die (reverse (asm-meta asm)))))
1771 (let-values (((die-port get-die-bv) (open-bytevector-output-port))
1773 ((abbrev-port get-abbrev-bv) (open-bytevector-output-port))
1774 ;; (tag has-kids? attrs forms) -> code
1775 ((abbrevs) vlist-null)
1776 ((strtab) (make-string-table))
1777 ((line-port get-line-bv) (open-bytevector-output-port))
1780 ((files) vlist-null))
1782 (define (write-abbrev code tag has-children? attrs forms)
1783 (put-uleb128 abbrev-port code)
1784 (put-uleb128 abbrev-port (tag-name->code tag))
1785 (put-u8 abbrev-port (children-name->code (if has-children? 'yes 'no)))
1786 (for-each (lambda (attr form)
1787 (put-uleb128 abbrev-port (attribute-name->code attr))
1788 (put-uleb128 abbrev-port (form-name->code form)))
1790 (put-uleb128 abbrev-port 0)
1791 (put-uleb128 abbrev-port 0))
1793 (define (intern-abbrev tag has-children? attrs forms)
1794 (let ((key (list tag has-children? attrs forms)))
1795 (match (vhash-assoc key abbrevs)
1797 (#f (let ((code (1+ (vlist-length abbrevs))))
1798 (set! abbrevs (vhash-cons key code abbrevs))
1799 (write-abbrev code tag has-children? attrs forms)
1802 (define (intern-file file)
1803 (match (vhash-assoc file files)
1805 (#f (let ((code (1+ (vlist-length files))))
1806 (set! files (vhash-cons file code files))
1809 (define (write-sources)
1810 ;; Choose line base and line range values that will allow for an
1811 ;; address advance range of 16 words. The special opcode range is
1812 ;; from 10 to 255, so 246 values.
1816 (let lp ((sources (asm-sources asm)) (out '()))
1818 (((pc . s) . sources)
1819 (let ((file (assq-ref s 'filename))
1820 (line (assq-ref s 'line))
1821 (col (assq-ref s 'column)))
1823 ;; Guile line and column numbers are 0-indexed, but
1824 ;; they are 1-indexed for DWARF.
1826 (if file (intern-file file) 0)
1831 ;; Compilation unit header for .debug_line. We write in
1832 ;; DWARF 2 format because more tools understand it than DWARF
1833 ;; 4, which incompatibly adds another field to this header.
1835 (put-u32 line-port 0) ; Length; will patch later.
1836 (put-u16 line-port 2) ; DWARF 2 format.
1837 (put-u32 line-port 0) ; Prologue length; will patch later.
1838 (put-u8 line-port 4) ; Minimum instruction length: 4 bytes.
1839 (put-u8 line-port 1) ; Default is-stmt: true.
1841 (put-s8 line-port base) ; Line base. See the DWARF standard.
1842 (put-u8 line-port range) ; Line range. See the DWARF standard.
1843 (put-u8 line-port 10) ; Opcode base: the first "special" opcode.
1845 ;; A table of the number of uleb128 arguments taken by each
1846 ;; of the standard opcodes.
1847 (put-u8 line-port 0) ; 1: copy
1848 (put-u8 line-port 1) ; 2: advance-pc
1849 (put-u8 line-port 1) ; 3: advance-line
1850 (put-u8 line-port 1) ; 4: set-file
1851 (put-u8 line-port 1) ; 5: set-column
1852 (put-u8 line-port 0) ; 6: negate-stmt
1853 (put-u8 line-port 0) ; 7: set-basic-block
1854 (put-u8 line-port 0) ; 8: const-add-pc
1855 (put-u8 line-port 1) ; 9: fixed-advance-pc
1857 ;; Include directories, as a zero-terminated sequence of
1858 ;; nul-terminated strings. Nothing, for the moment.
1859 (put-u8 line-port 0)
1861 ;; File table. For each file that contributes to this
1862 ;; compilation unit, a nul-terminated file name string, and a
1863 ;; uleb128 for each of directory the file was found in, the
1864 ;; modification time, and the file's size in bytes. We pass
1865 ;; zero for the latter three fields.
1870 (put-bytevector line-port (string->utf8 file))
1871 (put-u8 line-port 0)
1872 (put-uleb128 line-port 0) ; directory
1873 (put-uleb128 line-port 0) ; mtime
1874 (put-uleb128 line-port 0))) ; size
1878 (put-u8 line-port 0) ; 0 byte terminating file list.
1880 ;; Patch prologue length.
1881 (let ((offset (port-position line-port)))
1882 (seek line-port 6 SEEK_SET)
1883 (put-u32 line-port (- offset 10))
1884 (seek line-port offset SEEK_SET))
1886 ;; Now write the statement program.
1888 (define (extended-op opcode payload-len)
1889 (put-u8 line-port 0) ; extended op
1890 (put-uleb128 line-port (1+ payload-len)) ; payload-len + opcode
1891 (put-uleb128 line-port opcode))
1892 (define (set-address sym)
1893 (define (add-reloc! kind)
1895 (cons (make-linker-reloc kind
1896 (port-position line-port)
1900 (match (asm-word-size asm)
1903 (add-reloc! 'abs32/1)
1904 (put-u32 line-port 0))
1907 (add-reloc! 'abs64/1)
1908 (put-u64 line-port 0))))
1909 (define (end-sequence pc)
1910 (let ((pc-inc (- (asm-pos asm) pc)))
1911 (put-u8 line-port 2) ; advance-pc
1912 (put-uleb128 line-port pc-inc))
1914 (define (advance-pc pc-inc line-inc)
1915 (let ((spec (+ (- line-inc base) (* pc-inc range) 10)))
1917 ((or (< line-inc base) (>= line-inc (+ base range)))
1918 (advance-line line-inc)
1919 (advance-pc pc-inc 0))
1921 (put-u8 line-port spec))
1923 (put-u8 line-port 8) ; const-advance-pc
1924 (advance-pc (- pc-inc (floor/ (- 255 10) range))
1927 (put-u8 line-port 2) ; advance-pc
1928 (put-uleb128 line-port pc-inc)
1929 (advance-pc 0 line-inc)))))
1930 (define (advance-line inc)
1931 (put-u8 line-port 3)
1932 (put-sleb128 line-port inc))
1933 (define (set-file file)
1934 (put-u8 line-port 4)
1935 (put-uleb128 line-port file))
1936 (define (set-column col)
1937 (put-u8 line-port 5)
1938 (put-uleb128 line-port col))
1940 (set-address '.rtl-text)
1942 (let lp ((in out) (pc 0) (file 1) (line 1) (col 0))
1946 ;; There was no source info in the first place. Set
1947 ;; file register to 0 before adding final row.
1950 (((pc* file* line* col*) . in*)
1952 ((and (eqv? file file*) (eqv? line line*) (eqv? col col*))
1953 (lp in* pc file line col))
1955 (unless (eqv? col col*)
1957 (unless (eqv? file file*)
1959 (advance-pc (- pc* pc) (- line* line))
1960 (lp in* pc* file* line* col*)))))))))))
1962 (define (compute-code attr val)
1964 ('name (string-table-intern! strtab val))
1967 ('producer (string-table-intern! strtab val))
1968 ('language (language-name->code val))
1971 (define (choose-form attr val code)
1973 ((string? val) 'strp)
1974 ((eq? attr 'stmt-list) 'sec-offset)
1975 ((eq? attr 'low-pc) 'addr)
1976 ((exact-integer? code)
1978 ((< code 0) 'sleb128)
1979 ((<= code #xff) 'data1)
1980 ((<= code #xffff) 'data2)
1981 ((<= code #xffffffff) 'data4)
1982 ((<= code #xffffffffffffffff) 'data8)
1984 (else (error "unhandled case" attr val code))))
1986 (define (add-die-relocation! kind sym)
1988 (cons (make-linker-reloc kind (port-position die-port) 0 sym)
1991 (define (write-value code form)
1993 ('data1 (put-u8 die-port code))
1994 ('data2 (put-u16 die-port code))
1995 ('data4 (put-u32 die-port code))
1996 ('data8 (put-u64 die-port code))
1997 ('uleb128 (put-uleb128 die-port code))
1998 ('sleb128 (put-sleb128 die-port code))
2000 (match (asm-word-size asm)
2002 (add-die-relocation! 'abs32/1 code)
2003 (put-u32 die-port 0))
2005 (add-die-relocation! 'abs64/1 code)
2006 (put-u64 die-port 0))))
2007 ('sec-offset (put-u32 die-port code))
2008 ('strp (put-u32 die-port code))))
2010 (define (write-die die)
2012 ((tag ('@ (attrs vals) ...) children ...)
2013 (let* ((codes (map compute-code attrs vals))
2014 (forms (map choose-form attrs vals codes))
2015 (has-children? (not (null? children)))
2016 (abbrev-code (intern-abbrev tag has-children? attrs forms)))
2017 (put-uleb128 die-port abbrev-code)
2018 (for-each write-value codes forms)
2020 (for-each write-die children)
2021 (put-uleb128 die-port 0))))))
2023 ;; Compilation unit header.
2024 (put-u32 die-port 0) ; Length; will patch later.
2025 (put-u16 die-port 4) ; DWARF 4.
2026 (put-u32 die-port 0) ; Abbrevs offset.
2027 (put-u8 die-port (asm-word-size asm)) ; Address size.
2029 (write-die (make-compile-unit-die asm))
2031 ;; Terminate the abbrevs list.
2032 (put-uleb128 abbrev-port 0)
2036 (values (let ((bv (get-die-bv)))
2037 ;; Patch DWARF32 length.
2038 (bytevector-u32-set! bv 0 (- (bytevector-length bv) 4)
2039 (asm-endianness asm))
2040 (make-object asm '.debug_info bv die-relocs '()
2041 #:type SHT_PROGBITS #:flags 0))
2042 (make-object asm '.debug_abbrev (get-abbrev-bv) '() '()
2043 #:type SHT_PROGBITS #:flags 0)
2044 (make-object asm '.debug_str (link-string-table! strtab) '() '()
2045 #:type SHT_PROGBITS #:flags 0)
2046 (make-object asm '.debug_loc #vu8() '() '()
2047 #:type SHT_PROGBITS #:flags 0)
2048 (let ((bv (get-line-bv)))
2049 ;; Patch DWARF32 length.
2050 (bytevector-u32-set! bv 0 (- (bytevector-length bv) 4)
2051 (asm-endianness asm))
2052 (make-object asm '.debug_line bv line-relocs '()
2053 #:type SHT_PROGBITS #:flags 0)))))
2055 (define (link-objects asm)
2056 (let*-values (;; Link procprops before constants, because it probably
2057 ;; interns more constants.
2058 ((procprops) (link-procprops asm))
2059 ((ro rw rw-init) (link-constants asm))
2060 ;; Link text object after constants, so that the
2061 ;; constants initializer gets included.
2062 ((text) (link-text-object asm))
2063 ((frame-maps) (link-frame-maps asm))
2064 ((dt) (link-dynamic-section asm text rw rw-init frame-maps))
2065 ((symtab strtab) (link-symtab (linker-object-section text) asm))
2066 ((arities arities-strtab) (link-arities asm))
2067 ((docstrs docstrs-strtab) (link-docstrs asm))
2068 ((dinfo dabbrev dstrtab dloc dline) (link-debug asm))
2069 ;; This needs to be linked last, because linking other
2070 ;; sections adds entries to the string table.
2071 ((shstrtab) (link-shstrtab asm)))
2073 (list text ro frame-maps rw dt symtab strtab
2074 arities arities-strtab
2075 docstrs docstrs-strtab procprops
2076 dinfo dabbrev dstrtab dloc dline
2083 ;;; High-level public interfaces.
2086 (define* (link-assembly asm #:key (page-aligned? #t))
2087 "Produce an ELF image from the code and data emitted into @var{asm}.
2088 The result is a bytevector, by default linked so that read-only and
2089 writable data are on separate pages. Pass @code{#:page-aligned? #f} to
2090 disable this behavior."
2091 (link-elf (link-objects asm) #:page-aligned? page-aligned?))