1.0.17.24: refactor handling of constants in the compiler
[sbcl.git] / src / compiler / generic / genesis.lisp
1 ;;;; "cold" core image builder: This is how we create a target Lisp
2 ;;;; system from scratch, by converting from fasl files to an image
3 ;;;; file in the cross-compilation host, without the help of the
4 ;;;; target Lisp system.
5 ;;;;
6 ;;;; As explained by Rob MacLachlan on the CMU CL mailing list Wed, 06
7 ;;;; Jan 1999 11:05:02 -0500, this cold load generator more or less
8 ;;;; fakes up static function linking. I.e. it makes sure that all the
9 ;;;; DEFUN-defined functions in the fasl files it reads are bound to the
10 ;;;; corresponding symbols before execution starts. It doesn't do
11 ;;;; anything to initialize variable values; instead it just arranges
12 ;;;; for !COLD-INIT to be called at cold load time. !COLD-INIT is
13 ;;;; responsible for explicitly initializing anything which has to be
14 ;;;; initialized early before it transfers control to the ordinary
15 ;;;; top level forms.
16 ;;;;
17 ;;;; (In CMU CL, and in SBCL as of 0.6.9 anyway, functions not defined
18 ;;;; by DEFUN aren't set up specially by GENESIS. In particular,
19 ;;;; structure slot accessors are not set up. Slot accessors are
20 ;;;; available at cold init time because they're usually compiled
21 ;;;; inline. They're not available as out-of-line functions until the
22 ;;;; toplevel forms installing them have run.)
23
24 ;;;; This software is part of the SBCL system. See the README file for
25 ;;;; more information.
26 ;;;;
27 ;;;; This software is derived from the CMU CL system, which was
28 ;;;; written at Carnegie Mellon University and released into the
29 ;;;; public domain. The software is in the public domain and is
30 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
31 ;;;; files for more information.
32
33 (in-package "SB!FASL")
34
35 ;;; a magic number used to identify our core files
36 (defconstant core-magic
37   (logior (ash (sb!xc:char-code #\S) 24)
38           (ash (sb!xc:char-code #\B) 16)
39           (ash (sb!xc:char-code #\C) 8)
40           (sb!xc:char-code #\L)))
41
42 ;;; the current version of SBCL core files
43 ;;;
44 ;;; FIXME: This is left over from CMU CL, and not well thought out.
45 ;;; It's good to make sure that the runtime doesn't try to run core
46 ;;; files from the wrong version, but a single number is not the ideal
47 ;;; way to do this in high level data like this (as opposed to e.g. in
48 ;;; IP packets), and in fact the CMU CL version number never ended up
49 ;;; being incremented past 0. A better approach might be to use a
50 ;;; string which is set from CVS data. (Though now as of sbcl-0.7.8 or
51 ;;; so, we have another problem that the core incompatibility
52 ;;; detection mechanisms are on such a hair trigger -- with even
53 ;;; different builds from the same sources being considered
54 ;;; incompatible -- that any coarser-grained versioning mechanisms
55 ;;; like this are largely irrelevant as long as the hair-triggering
56 ;;; persists.)
57 ;;;
58 ;;; 0: inherited from CMU CL
59 ;;; 1: rearranged static symbols for sbcl-0.6.8
60 ;;; 2: eliminated non-ANSI %DEFCONSTANT/%%DEFCONSTANT support,
61 ;;;    deleted a slot from DEBUG-SOURCE structure
62 ;;; 3: added build ID to cores to discourage sbcl/.core mismatch
63 ;;; 4: added gc page table data
64 (defconstant sbcl-core-version-integer 4)
65
66 (defun round-up (number size)
67   #!+sb-doc
68   "Round NUMBER up to be an integral multiple of SIZE."
69   (* size (ceiling number size)))
70 \f
71 ;;;; implementing the concept of "vector" in (almost) portable
72 ;;;; Common Lisp
73 ;;;;
74 ;;;; "If you only need to do such simple things, it doesn't really
75 ;;;; matter which language you use." -- _ANSI Common Lisp_, p. 1, Paul
76 ;;;; Graham (evidently not considering the abstraction "vector" to be
77 ;;;; such a simple thing:-)
78
79 (eval-when (:compile-toplevel :load-toplevel :execute)
80   (defconstant +smallvec-length+
81     (expt 2 16)))
82
83 ;;; an element of a BIGVEC -- a vector small enough that we have
84 ;;; a good chance of it being portable to other Common Lisps
85 (deftype smallvec ()
86   `(simple-array (unsigned-byte 8) (,+smallvec-length+)))
87
88 (defun make-smallvec ()
89   (make-array +smallvec-length+ :element-type '(unsigned-byte 8)))
90
91 ;;; a big vector, implemented as a vector of SMALLVECs
92 ;;;
93 ;;; KLUDGE: This implementation seems portable enough for our
94 ;;; purposes, since realistically every modern implementation is
95 ;;; likely to support vectors of at least 2^16 elements. But if you're
96 ;;; masochistic enough to read this far into the contortions imposed
97 ;;; on us by ANSI and the Lisp community, for daring to use the
98 ;;; abstraction of a large linearly addressable memory space, which is
99 ;;; after all only directly supported by the underlying hardware of at
100 ;;; least 99% of the general-purpose computers in use today, then you
101 ;;; may be titillated to hear that in fact this code isn't really
102 ;;; portable, because as of sbcl-0.7.4 we need somewhat more than
103 ;;; 16Mbytes to represent a core, and ANSI only guarantees that
104 ;;; ARRAY-DIMENSION-LIMIT is not less than 1024. -- WHN 2002-06-13
105 (defstruct bigvec
106   (outer-vector (vector (make-smallvec)) :type (vector smallvec)))
107
108 ;;; analogous to SVREF, but into a BIGVEC
109 (defun bvref (bigvec index)
110   (multiple-value-bind (outer-index inner-index)
111       (floor index +smallvec-length+)
112     (aref (the smallvec
113             (svref (bigvec-outer-vector bigvec) outer-index))
114           inner-index)))
115 (defun (setf bvref) (new-value bigvec index)
116   (multiple-value-bind (outer-index inner-index)
117       (floor index +smallvec-length+)
118     (setf (aref (the smallvec
119                   (svref (bigvec-outer-vector bigvec) outer-index))
120                 inner-index)
121           new-value)))
122
123 ;;; analogous to LENGTH, but for a BIGVEC
124 ;;;
125 ;;; the length of BIGVEC, measured in the number of BVREFable bytes it
126 ;;; can hold
127 (defun bvlength (bigvec)
128   (* (length (bigvec-outer-vector bigvec))
129      +smallvec-length+))
130
131 ;;; analogous to WRITE-SEQUENCE, but for a BIGVEC
132 (defun write-bigvec-as-sequence (bigvec stream &key (start 0) end)
133   (loop for i of-type index from start below (or end (bvlength bigvec)) do
134         (write-byte (bvref bigvec i)
135                     stream)))
136
137 ;;; analogous to READ-SEQUENCE-OR-DIE, but for a BIGVEC
138 (defun read-bigvec-as-sequence-or-die (bigvec stream &key (start 0) end)
139   (loop for i of-type index from start below (or end (bvlength bigvec)) do
140         (setf (bvref bigvec i)
141               (read-byte stream))))
142
143 ;;; Grow BIGVEC (exponentially, so that large increases in size have
144 ;;; asymptotic logarithmic cost per byte).
145 (defun expand-bigvec (bigvec)
146   (let* ((old-outer-vector (bigvec-outer-vector bigvec))
147          (length-old-outer-vector (length old-outer-vector))
148          (new-outer-vector (make-array (* 2 length-old-outer-vector))))
149     (dotimes (i length-old-outer-vector)
150       (setf (svref new-outer-vector i)
151             (svref old-outer-vector i)))
152     (loop for i from length-old-outer-vector below (length new-outer-vector) do
153           (setf (svref new-outer-vector i)
154                 (make-smallvec)))
155     (setf (bigvec-outer-vector bigvec)
156           new-outer-vector))
157   bigvec)
158 \f
159 ;;;; looking up bytes and multi-byte values in a BIGVEC (considering
160 ;;;; it as an image of machine memory on the cross-compilation target)
161
162 ;;; BVREF-32 and friends. These are like SAP-REF-n, except that
163 ;;; instead of a SAP we use a BIGVEC.
164 (macrolet ((make-bvref-n
165             (n)
166             (let* ((name (intern (format nil "BVREF-~A" n)))
167                    (number-octets (/ n 8))
168                    (ash-list-le
169                     (loop for i from 0 to (1- number-octets)
170                           collect `(ash (bvref bigvec (+ byte-index ,i))
171                                         ,(* i 8))))
172                    (ash-list-be
173                     (loop for i from 0 to (1- number-octets)
174                           collect `(ash (bvref bigvec
175                                                (+ byte-index
176                                                   ,(- number-octets 1 i)))
177                                         ,(* i 8))))
178                    (setf-list-le
179                     (loop for i from 0 to (1- number-octets)
180                           append
181                           `((bvref bigvec (+ byte-index ,i))
182                             (ldb (byte 8 ,(* i 8)) new-value))))
183                    (setf-list-be
184                     (loop for i from 0 to (1- number-octets)
185                           append
186                           `((bvref bigvec (+ byte-index ,i))
187                             (ldb (byte 8 ,(- n 8 (* i 8))) new-value)))))
188               `(progn
189                  (defun ,name (bigvec byte-index)
190                    (logior ,@(ecase sb!c:*backend-byte-order*
191                                (:little-endian ash-list-le)
192                                (:big-endian ash-list-be))))
193                  (defun (setf ,name) (new-value bigvec byte-index)
194                    (setf ,@(ecase sb!c:*backend-byte-order*
195                              (:little-endian setf-list-le)
196                              (:big-endian setf-list-be))))))))
197   (make-bvref-n 8)
198   (make-bvref-n 16)
199   (make-bvref-n 32)
200   (make-bvref-n 64))
201
202 ;; lispobj-sized word, whatever that may be
203 ;; hopefully nobody ever wants a 128-bit SBCL...
204 #!+#.(cl:if (cl:= 64 sb!vm:n-word-bits) '(and) '(or))
205 (progn
206 (defun bvref-word (bytes index)
207   (bvref-64 bytes index))
208 (defun (setf bvref-word) (new-val bytes index)
209   (setf (bvref-64 bytes index) new-val)))
210
211 #!+#.(cl:if (cl:= 32 sb!vm:n-word-bits) '(and) '(or))
212 (progn
213 (defun bvref-word (bytes index)
214   (bvref-32 bytes index))
215 (defun (setf bvref-word) (new-val bytes index)
216   (setf (bvref-32 bytes index) new-val)))
217
218 \f
219 ;;;; representation of spaces in the core
220
221 ;;; If there is more than one dynamic space in memory (i.e., if a
222 ;;; copying GC is in use), then only the active dynamic space gets
223 ;;; dumped to core.
224 (defvar *dynamic*)
225 (defconstant dynamic-core-space-id 1)
226
227 (defvar *static*)
228 (defconstant static-core-space-id 2)
229
230 (defvar *read-only*)
231 (defconstant read-only-core-space-id 3)
232
233 (defconstant descriptor-low-bits 16
234   "the number of bits in the low half of the descriptor")
235 (defconstant target-space-alignment (ash 1 descriptor-low-bits)
236   "the alignment requirement for spaces in the target.
237   Must be at least (ASH 1 DESCRIPTOR-LOW-BITS)")
238
239 ;;; a GENESIS-time representation of a memory space (e.g. read-only
240 ;;; space, dynamic space, or static space)
241 (defstruct (gspace (:constructor %make-gspace)
242                    (:copier nil))
243   ;; name and identifier for this GSPACE
244   (name (missing-arg) :type symbol :read-only t)
245   (identifier (missing-arg) :type fixnum :read-only t)
246   ;; the word address where the data will be loaded
247   (word-address (missing-arg) :type unsigned-byte :read-only t)
248   ;; the data themselves. (Note that in CMU CL this was a pair of
249   ;; fields SAP and WORDS-ALLOCATED, but that wasn't very portable.)
250   ;; (And then in SBCL this was a VECTOR, but turned out to be
251   ;; unportable too, since ANSI doesn't think that arrays longer than
252   ;; 1024 (!) should needed by portable CL code...)
253   (bytes (make-bigvec) :read-only t)
254   ;; the index of the next unwritten word (i.e. chunk of
255   ;; SB!VM:N-WORD-BYTES bytes) in BYTES, or equivalently the number of
256   ;; words actually written in BYTES. In order to convert to an actual
257   ;; index into BYTES, thus must be multiplied by SB!VM:N-WORD-BYTES.
258   (free-word-index 0))
259
260 (defun gspace-byte-address (gspace)
261   (ash (gspace-word-address gspace) sb!vm:word-shift))
262
263 (def!method print-object ((gspace gspace) stream)
264   (print-unreadable-object (gspace stream :type t)
265     (format stream "~S" (gspace-name gspace))))
266
267 (defun make-gspace (name identifier byte-address)
268   (unless (zerop (rem byte-address target-space-alignment))
269     (error "The byte address #X~X is not aligned on a #X~X-byte boundary."
270            byte-address
271            target-space-alignment))
272   (%make-gspace :name name
273                 :identifier identifier
274                 :word-address (ash byte-address (- sb!vm:word-shift))))
275 \f
276 ;;;; representation of descriptors
277
278 (defstruct (descriptor
279             (:constructor make-descriptor
280                           (high low &optional gspace word-offset))
281             (:copier nil))
282   ;; the GSPACE that this descriptor is allocated in, or NIL if not set yet.
283   (gspace nil :type (or gspace null))
284   ;; the offset in words from the start of GSPACE, or NIL if not set yet
285   (word-offset nil :type (or sb!vm:word null))
286   ;; the high and low halves of the descriptor
287   ;;
288   ;; KLUDGE: Judging from the comments in genesis.lisp of the CMU CL
289   ;; old-rt compiler, this split dates back from a very early version
290   ;; of genesis where 32-bit integers were represented as conses of
291   ;; two 16-bit integers. In any system with nice (UNSIGNED-BYTE 32)
292   ;; structure slots, like CMU CL >= 17 or any version of SBCL, there
293   ;; seems to be no reason to persist in this. -- WHN 19990917
294   high
295   low)
296 (def!method print-object ((des descriptor) stream)
297   (let ((lowtag (descriptor-lowtag des)))
298     (print-unreadable-object (des stream :type t)
299       (cond ((or (= lowtag sb!vm:even-fixnum-lowtag)
300                  (= lowtag sb!vm:odd-fixnum-lowtag))
301              (let ((unsigned (logior (ash (descriptor-high des)
302                                           (1+ (- descriptor-low-bits
303                                                  sb!vm:n-lowtag-bits)))
304                                      (ash (descriptor-low des)
305                                           (- 1 sb!vm:n-lowtag-bits)))))
306                (format stream
307                        "for fixnum: ~W"
308                        (if (> unsigned #x1FFFFFFF)
309                            (- unsigned #x40000000)
310                            unsigned))))
311             ((or (= lowtag sb!vm:other-immediate-0-lowtag)
312                  (= lowtag sb!vm:other-immediate-1-lowtag)
313                  #!+#.(cl:if (cl:= 64 sb!vm:n-word-bits) '(and) '(or))
314                  (= lowtag sb!vm:other-immediate-2-lowtag)
315                  #!+#.(cl:if (cl:= 64 sb!vm:n-word-bits) '(and) '(or))
316                  (= lowtag sb!vm:other-immediate-3-lowtag))
317              (format stream
318                      "for other immediate: #X~X, type #b~8,'0B"
319                      (ash (descriptor-bits des) (- sb!vm:n-widetag-bits))
320                      (logand (descriptor-low des) sb!vm:widetag-mask)))
321             (t
322              (format stream
323                      "for pointer: #X~X, lowtag #b~3,'0B, ~A"
324                      (logior (ash (descriptor-high des) descriptor-low-bits)
325                              (logandc2 (descriptor-low des) sb!vm:lowtag-mask))
326                      lowtag
327                      (let ((gspace (descriptor-gspace des)))
328                        (if gspace
329                            (gspace-name gspace)
330                            "unknown"))))))))
331
332 ;;; Return a descriptor for a block of LENGTH bytes out of GSPACE. The
333 ;;; free word index is boosted as necessary, and if additional memory
334 ;;; is needed, we grow the GSPACE. The descriptor returned is a
335 ;;; pointer of type LOWTAG.
336 (defun allocate-cold-descriptor (gspace length lowtag)
337   (let* ((bytes (round-up length (ash 1 sb!vm:n-lowtag-bits)))
338          (old-free-word-index (gspace-free-word-index gspace))
339          (new-free-word-index (+ old-free-word-index
340                                  (ash bytes (- sb!vm:word-shift)))))
341     ;; Grow GSPACE as necessary until it's big enough to handle
342     ;; NEW-FREE-WORD-INDEX.
343     (do ()
344         ((>= (bvlength (gspace-bytes gspace))
345              (* new-free-word-index sb!vm:n-word-bytes)))
346       (expand-bigvec (gspace-bytes gspace)))
347     ;; Now that GSPACE is big enough, we can meaningfully grab a chunk of it.
348     (setf (gspace-free-word-index gspace) new-free-word-index)
349     (let ((ptr (+ (gspace-word-address gspace) old-free-word-index)))
350       (make-descriptor (ash ptr (- sb!vm:word-shift descriptor-low-bits))
351                        (logior (ash (logand ptr
352                                             (1- (ash 1
353                                                      (- descriptor-low-bits
354                                                         sb!vm:word-shift))))
355                                     sb!vm:word-shift)
356                                lowtag)
357                        gspace
358                        old-free-word-index))))
359
360 (defun descriptor-lowtag (des)
361   #!+sb-doc
362   "the lowtag bits for DES"
363   (logand (descriptor-low des) sb!vm:lowtag-mask))
364
365 (defun descriptor-bits (des)
366   (logior (ash (descriptor-high des) descriptor-low-bits)
367           (descriptor-low des)))
368
369 (defun descriptor-fixnum (des)
370   (let ((bits (descriptor-bits des)))
371     (if (logbitp (1- sb!vm:n-word-bits) bits)
372         ;; KLUDGE: The (- SB!VM:N-WORD-BITS 2) term here looks right to
373         ;; me, and it works, but in CMU CL it was (1- SB!VM:N-WORD-BITS),
374         ;; and although that doesn't make sense for me, or work for me,
375         ;; it's hard to see how it could have been wrong, since CMU CL
376         ;; genesis worked. It would be nice to understand how this came
377         ;; to be.. -- WHN 19990901
378         (logior (ash bits (- 1 sb!vm:n-lowtag-bits))
379                 (ash -1 (1+ sb!vm:n-positive-fixnum-bits)))
380         (ash bits (- 1 sb!vm:n-lowtag-bits)))))
381
382 (defun descriptor-word-sized-integer (des)
383   ;; Extract an (unsigned-byte 32), from either its fixnum or bignum
384   ;; representation.
385   (let ((lowtag (descriptor-lowtag des)))
386     (if (or (= lowtag sb!vm:even-fixnum-lowtag)
387             (= lowtag sb!vm:odd-fixnum-lowtag))
388         (make-random-descriptor (descriptor-fixnum des))
389         (read-wordindexed des 1))))
390
391 ;;; common idioms
392 (defun descriptor-bytes (des)
393   (gspace-bytes (descriptor-intuit-gspace des)))
394 (defun descriptor-byte-offset (des)
395   (ash (descriptor-word-offset des) sb!vm:word-shift))
396
397 ;;; If DESCRIPTOR-GSPACE is already set, just return that. Otherwise,
398 ;;; figure out a GSPACE which corresponds to DES, set it into
399 ;;; (DESCRIPTOR-GSPACE DES), set a consistent value into
400 ;;; (DESCRIPTOR-WORD-OFFSET DES), and return the GSPACE.
401 (declaim (ftype (function (descriptor) gspace) descriptor-intuit-gspace))
402 (defun descriptor-intuit-gspace (des)
403   (if (descriptor-gspace des)
404     (descriptor-gspace des)
405     ;; KLUDGE: It's not completely clear to me what's going on here;
406     ;; this is a literal translation from of some rather mysterious
407     ;; code from CMU CL's DESCRIPTOR-SAP function. Some explanation
408     ;; would be nice. -- WHN 19990817
409     (let ((lowtag (descriptor-lowtag des))
410           (high (descriptor-high des))
411           (low (descriptor-low des)))
412       (if (or (eql lowtag sb!vm:fun-pointer-lowtag)
413               (eql lowtag sb!vm:instance-pointer-lowtag)
414               (eql lowtag sb!vm:list-pointer-lowtag)
415               (eql lowtag sb!vm:other-pointer-lowtag))
416         (dolist (gspace (list *dynamic* *static* *read-only*)
417                         (error "couldn't find a GSPACE for ~S" des))
418           ;; This code relies on the fact that GSPACEs are aligned
419           ;; such that the descriptor-low-bits low bits are zero.
420           (when (and (>= high (ash (gspace-word-address gspace)
421                                    (- sb!vm:word-shift descriptor-low-bits)))
422                      (<= high (ash (+ (gspace-word-address gspace)
423                                       (gspace-free-word-index gspace))
424                                    (- sb!vm:word-shift descriptor-low-bits))))
425             (setf (descriptor-gspace des) gspace)
426             (setf (descriptor-word-offset des)
427                   (+ (ash (- high (ash (gspace-word-address gspace)
428                                        (- sb!vm:word-shift
429                                           descriptor-low-bits)))
430                           (- descriptor-low-bits sb!vm:word-shift))
431                      (ash (logandc2 low sb!vm:lowtag-mask)
432                           (- sb!vm:word-shift))))
433             (return gspace)))
434         (error "don't even know how to look for a GSPACE for ~S" des)))))
435
436 (defun make-random-descriptor (value)
437   (make-descriptor (logand (ash value (- descriptor-low-bits))
438                            (1- (ash 1
439                                     (- sb!vm:n-word-bits
440                                        descriptor-low-bits))))
441                    (logand value (1- (ash 1 descriptor-low-bits)))))
442
443 (defun make-fixnum-descriptor (num)
444   (when (>= (integer-length num)
445             (1+ (- sb!vm:n-word-bits sb!vm:n-lowtag-bits)))
446     (error "~W is too big for a fixnum." num))
447   (make-random-descriptor (ash num (1- sb!vm:n-lowtag-bits))))
448
449 (defun make-other-immediate-descriptor (data type)
450   (make-descriptor (ash data (- sb!vm:n-widetag-bits descriptor-low-bits))
451                    (logior (logand (ash data (- descriptor-low-bits
452                                                 sb!vm:n-widetag-bits))
453                                    (1- (ash 1 descriptor-low-bits)))
454                            type)))
455
456 (defun make-character-descriptor (data)
457   (make-other-immediate-descriptor data sb!vm:character-widetag))
458
459 (defun descriptor-beyond (des offset type)
460   (let* ((low (logior (+ (logandc2 (descriptor-low des) sb!vm:lowtag-mask)
461                          offset)
462                       type))
463          (high (+ (descriptor-high des)
464                   (ash low (- descriptor-low-bits)))))
465     (make-descriptor high (logand low (1- (ash 1 descriptor-low-bits))))))
466 \f
467 ;;;; miscellaneous variables and other noise
468
469 ;;; a numeric value to be returned for undefined foreign symbols, or NIL if
470 ;;; undefined foreign symbols are to be treated as an error.
471 ;;; (In the first pass of GENESIS, needed to create a header file before
472 ;;; the C runtime can be built, various foreign symbols will necessarily
473 ;;; be undefined, but we don't need actual values for them anyway, and
474 ;;; we can just use 0 or some other placeholder. In the second pass of
475 ;;; GENESIS, all foreign symbols should be defined, so any undefined
476 ;;; foreign symbol is a problem.)
477 ;;;
478 ;;; KLUDGE: It would probably be cleaner to rewrite GENESIS so that it
479 ;;; never tries to look up foreign symbols in the first place unless
480 ;;; it's actually creating a core file (as in the second pass) instead
481 ;;; of using this hack to allow it to go through the motions without
482 ;;; causing an error. -- WHN 20000825
483 (defvar *foreign-symbol-placeholder-value*)
484
485 ;;; a handle on the trap object
486 (defvar *unbound-marker*)
487 ;; was:  (make-other-immediate-descriptor 0 sb!vm:unbound-marker-widetag)
488
489 ;;; a handle on the NIL object
490 (defvar *nil-descriptor*)
491
492 ;;; the head of a list of TOPLEVEL-THINGs describing stuff to be done
493 ;;; when the target Lisp starts up
494 ;;;
495 ;;; Each TOPLEVEL-THING can be a function to be executed or a fixup or
496 ;;; loadtime value, represented by (CONS KEYWORD ..). The FILENAME
497 ;;; tells which fasl file each list element came from, for debugging
498 ;;; purposes.
499 (defvar *current-reversed-cold-toplevels*)
500
501 ;;; the name of the object file currently being cold loaded (as a string, not a
502 ;;; pathname), or NIL if we're not currently cold loading any object file
503 (defvar *cold-load-filename* nil)
504 (declaim (type (or string null) *cold-load-filename*))
505 \f
506 ;;;; miscellaneous stuff to read and write the core memory
507
508 ;;; FIXME: should be DEFINE-MODIFY-MACRO
509 (defmacro cold-push (thing list)
510   #!+sb-doc
511   "Push THING onto the given cold-load LIST."
512   `(setq ,list (cold-cons ,thing ,list)))
513
514 (declaim (ftype (function (descriptor sb!vm:word) descriptor) read-wordindexed))
515 (defun read-wordindexed (address index)
516   #!+sb-doc
517   "Return the value which is displaced by INDEX words from ADDRESS."
518   (let* ((gspace (descriptor-intuit-gspace address))
519          (bytes (gspace-bytes gspace))
520          (byte-index (ash (+ index (descriptor-word-offset address))
521                           sb!vm:word-shift))
522          (value (bvref-word bytes byte-index)))
523     (make-random-descriptor value)))
524
525 (declaim (ftype (function (descriptor) descriptor) read-memory))
526 (defun read-memory (address)
527   #!+sb-doc
528   "Return the value at ADDRESS."
529   (read-wordindexed address 0))
530
531 ;;; (Note: In CMU CL, this function expected a SAP-typed ADDRESS
532 ;;; value, instead of the SAP-INT we use here.)
533 (declaim (ftype (function (sb!vm:word descriptor) (values))
534                 note-load-time-value-reference))
535 (defun note-load-time-value-reference (address marker)
536   (cold-push (cold-cons
537               (cold-intern :load-time-value-fixup)
538               (cold-cons (sap-int-to-core address)
539                          (cold-cons
540                           (number-to-core (descriptor-word-offset marker))
541                           *nil-descriptor*)))
542              *current-reversed-cold-toplevels*)
543   (values))
544
545 (declaim (ftype (function (descriptor sb!vm:word descriptor)) write-wordindexed))
546 (defun write-wordindexed (address index value)
547   #!+sb-doc
548   "Write VALUE displaced INDEX words from ADDRESS."
549   ;; KLUDGE: There is an algorithm (used in DESCRIPTOR-INTUIT-GSPACE)
550   ;; for calculating the value of the GSPACE slot from scratch. It
551   ;; doesn't work for all values, only some of them, but mightn't it
552   ;; be reasonable to see whether it works on VALUE before we give up
553   ;; because (DESCRIPTOR-GSPACE VALUE) isn't set? (Or failing that,
554   ;; perhaps write a comment somewhere explaining why it's not a good
555   ;; idea?) -- WHN 19990817
556   (if (and (null (descriptor-gspace value))
557            (not (null (descriptor-word-offset value))))
558     (note-load-time-value-reference (+ (logandc2 (descriptor-bits address)
559                                                  sb!vm:lowtag-mask)
560                                        (ash index sb!vm:word-shift))
561                                     value)
562     (let* ((bytes (gspace-bytes (descriptor-intuit-gspace address)))
563            (byte-index (ash (+ index (descriptor-word-offset address))
564                                sb!vm:word-shift)))
565       (setf (bvref-word bytes byte-index)
566             (descriptor-bits value)))))
567
568 (declaim (ftype (function (descriptor descriptor)) write-memory))
569 (defun write-memory (address value)
570   #!+sb-doc
571   "Write VALUE (a DESCRIPTOR) at ADDRESS (also a DESCRIPTOR)."
572   (write-wordindexed address 0 value))
573 \f
574 ;;;; allocating images of primitive objects in the cold core
575
576 ;;; There are three kinds of blocks of memory in the type system:
577 ;;; * Boxed objects (cons cells, structures, etc): These objects have no
578 ;;;   header as all slots are descriptors.
579 ;;; * Unboxed objects (bignums): There is a single header word that contains
580 ;;;   the length.
581 ;;; * Vector objects: There is a header word with the type, then a word for
582 ;;;   the length, then the data.
583 (defun allocate-boxed-object (gspace length lowtag)
584   #!+sb-doc
585   "Allocate LENGTH words in GSPACE and return a new descriptor of type LOWTAG
586   pointing to them."
587   (allocate-cold-descriptor gspace (ash length sb!vm:word-shift) lowtag))
588 (defun allocate-unboxed-object (gspace element-bits length type)
589   #!+sb-doc
590   "Allocate LENGTH units of ELEMENT-BITS bits plus a header word in GSPACE and
591   return an ``other-pointer'' descriptor to them. Initialize the header word
592   with the resultant length and TYPE."
593   (let* ((bytes (/ (* element-bits length) sb!vm:n-byte-bits))
594          (des (allocate-cold-descriptor gspace
595                                         (+ bytes sb!vm:n-word-bytes)
596                                         sb!vm:other-pointer-lowtag)))
597     (write-memory des
598                   (make-other-immediate-descriptor (ash bytes
599                                                         (- sb!vm:word-shift))
600                                                    type))
601     des))
602 (defun allocate-vector-object (gspace element-bits length type)
603   #!+sb-doc
604   "Allocate LENGTH units of ELEMENT-BITS size plus a header plus a length slot in
605   GSPACE and return an ``other-pointer'' descriptor to them. Initialize the
606   header word with TYPE and the length slot with LENGTH."
607   ;; FIXME: Here and in ALLOCATE-UNBOXED-OBJECT, BYTES is calculated using
608   ;; #'/ instead of #'CEILING, which seems wrong.
609   (let* ((bytes (/ (* element-bits length) sb!vm:n-byte-bits))
610          (des (allocate-cold-descriptor gspace
611                                         (+ bytes (* 2 sb!vm:n-word-bytes))
612                                         sb!vm:other-pointer-lowtag)))
613     (write-memory des (make-other-immediate-descriptor 0 type))
614     (write-wordindexed des
615                        sb!vm:vector-length-slot
616                        (make-fixnum-descriptor length))
617     des))
618 \f
619 ;;;; copying simple objects into the cold core
620
621 (defun base-string-to-core (string &optional (gspace *dynamic*))
622   #!+sb-doc
623   "Copy STRING (which must only contain STANDARD-CHARs) into the cold
624 core and return a descriptor to it."
625   ;; (Remember that the system convention for storage of strings leaves an
626   ;; extra null byte at the end to aid in call-out to C.)
627   (let* ((length (length string))
628          (des (allocate-vector-object gspace
629                                       sb!vm:n-byte-bits
630                                       (1+ length)
631                                       sb!vm:simple-base-string-widetag))
632          (bytes (gspace-bytes gspace))
633          (offset (+ (* sb!vm:vector-data-offset sb!vm:n-word-bytes)
634                     (descriptor-byte-offset des))))
635     (write-wordindexed des
636                        sb!vm:vector-length-slot
637                        (make-fixnum-descriptor length))
638     (dotimes (i length)
639       (setf (bvref bytes (+ offset i))
640             (sb!xc:char-code (aref string i))))
641     (setf (bvref bytes (+ offset length))
642           0) ; null string-termination character for C
643     des))
644
645 (defun bignum-to-core (n)
646   #!+sb-doc
647   "Copy a bignum to the cold core."
648   (let* ((words (ceiling (1+ (integer-length n)) sb!vm:n-word-bits))
649          (handle (allocate-unboxed-object *dynamic*
650                                           sb!vm:n-word-bits
651                                           words
652                                           sb!vm:bignum-widetag)))
653     (declare (fixnum words))
654     (do ((index 1 (1+ index))
655          (remainder n (ash remainder (- sb!vm:n-word-bits))))
656         ((> index words)
657          (unless (zerop (integer-length remainder))
658            ;; FIXME: Shouldn't this be a fatal error?
659            (warn "~W words of ~W were written, but ~W bits were left over."
660                  words n remainder)))
661       (let ((word (ldb (byte sb!vm:n-word-bits 0) remainder)))
662         (write-wordindexed handle index
663                            (make-descriptor (ash word (- descriptor-low-bits))
664                                             (ldb (byte descriptor-low-bits 0)
665                                                  word)))))
666     handle))
667
668 (defun number-pair-to-core (first second type)
669   #!+sb-doc
670   "Makes a number pair of TYPE (ratio or complex) and fills it in."
671   (let ((des (allocate-unboxed-object *dynamic* sb!vm:n-word-bits 2 type)))
672     (write-wordindexed des 1 first)
673     (write-wordindexed des 2 second)
674     des))
675
676 (defun write-double-float-bits (address index x)
677   (let ((hi (double-float-high-bits x))
678         (lo (double-float-low-bits x)))
679     (ecase sb!vm::n-word-bits
680       (32
681        (let ((high-bits (make-random-descriptor hi))
682              (low-bits (make-random-descriptor lo)))
683          (ecase sb!c:*backend-byte-order*
684            (:little-endian
685             (write-wordindexed address index low-bits)
686             (write-wordindexed address (1+ index) high-bits))
687            (:big-endian
688             (write-wordindexed address index high-bits)
689             (write-wordindexed address (1+ index) low-bits)))))
690       (64
691        (let ((bits (make-random-descriptor
692                     (ecase sb!c:*backend-byte-order*
693                       (:little-endian (logior lo (ash hi 32)))
694                       ;; Just guessing.
695                       #+nil (:big-endian (logior (logand hi #xffffffff)
696                                                  (ash lo 32)))))))
697          (write-wordindexed address index bits))))
698     address))
699
700 (defun float-to-core (x)
701   (etypecase x
702     (single-float
703      ;; 64-bit platforms have immediate single-floats.
704      #!+#.(cl:if (cl:= sb!vm:n-word-bits 64) '(and) '(or))
705      (make-random-descriptor (logior (ash (single-float-bits x) 32)
706                                      sb!vm::single-float-widetag))
707      #!-#.(cl:if (cl:= sb!vm:n-word-bits 64) '(and) '(or))
708      (let ((des (allocate-unboxed-object *dynamic*
709                                          sb!vm:n-word-bits
710                                          (1- sb!vm:single-float-size)
711                                          sb!vm:single-float-widetag)))
712        (write-wordindexed des
713                           sb!vm:single-float-value-slot
714                           (make-random-descriptor (single-float-bits x)))
715        des))
716     (double-float
717      (let ((des (allocate-unboxed-object *dynamic*
718                                          sb!vm:n-word-bits
719                                          (1- sb!vm:double-float-size)
720                                          sb!vm:double-float-widetag)))
721        (write-double-float-bits des sb!vm:double-float-value-slot x)))))
722
723 (defun complex-single-float-to-core (num)
724   (declare (type (complex single-float) num))
725   (let ((des (allocate-unboxed-object *dynamic* sb!vm:n-word-bits
726                                       (1- sb!vm:complex-single-float-size)
727                                       sb!vm:complex-single-float-widetag)))
728     (write-wordindexed des sb!vm:complex-single-float-real-slot
729                    (make-random-descriptor (single-float-bits (realpart num))))
730     (write-wordindexed des sb!vm:complex-single-float-imag-slot
731                    (make-random-descriptor (single-float-bits (imagpart num))))
732     des))
733
734 (defun complex-double-float-to-core (num)
735   (declare (type (complex double-float) num))
736   (let ((des (allocate-unboxed-object *dynamic* sb!vm:n-word-bits
737                                       (1- sb!vm:complex-double-float-size)
738                                       sb!vm:complex-double-float-widetag)))
739     (write-double-float-bits des sb!vm:complex-double-float-real-slot
740                              (realpart num))
741     (write-double-float-bits des sb!vm:complex-double-float-imag-slot
742                              (imagpart num))))
743
744 ;;; Copy the given number to the core.
745 (defun number-to-core (number)
746   (typecase number
747     (integer (if (< (integer-length number)
748                     (- (1+ sb!vm:n-word-bits) sb!vm:n-lowtag-bits))
749                  (make-fixnum-descriptor number)
750                  (bignum-to-core number)))
751     (ratio (number-pair-to-core (number-to-core (numerator number))
752                                 (number-to-core (denominator number))
753                                 sb!vm:ratio-widetag))
754     ((complex single-float) (complex-single-float-to-core number))
755     ((complex double-float) (complex-double-float-to-core number))
756     #!+long-float
757     ((complex long-float)
758      (error "~S isn't a cold-loadable number at all!" number))
759     (complex (number-pair-to-core (number-to-core (realpart number))
760                                   (number-to-core (imagpart number))
761                                   sb!vm:complex-widetag))
762     (float (float-to-core number))
763     (t (error "~S isn't a cold-loadable number at all!" number))))
764
765 (declaim (ftype (function (sb!vm:word) descriptor) sap-int-to-core))
766 (defun sap-int-to-core (sap-int)
767   (let ((des (allocate-unboxed-object *dynamic*
768                                       sb!vm:n-word-bits
769                                       (1- sb!vm:sap-size)
770                                       sb!vm:sap-widetag)))
771     (write-wordindexed des
772                        sb!vm:sap-pointer-slot
773                        (make-random-descriptor sap-int))
774     des))
775
776 ;;; Allocate a cons cell in GSPACE and fill it in with CAR and CDR.
777 (defun cold-cons (car cdr &optional (gspace *dynamic*))
778   (let ((dest (allocate-boxed-object gspace 2 sb!vm:list-pointer-lowtag)))
779     (write-memory dest car)
780     (write-wordindexed dest 1 cdr)
781     dest))
782
783 ;;; Make a simple-vector on the target that holds the specified
784 ;;; OBJECTS, and return its descriptor.
785 (defun vector-in-core (&rest objects)
786   (let* ((size (length objects))
787          (result (allocate-vector-object *dynamic* sb!vm:n-word-bits size
788                                          sb!vm:simple-vector-widetag)))
789     (dotimes (index size)
790       (write-wordindexed result (+ index sb!vm:vector-data-offset)
791                          (pop objects)))
792     result))
793 \f
794 ;;;; symbol magic
795
796 ;;; FIXME: This should be a &KEY argument of ALLOCATE-SYMBOL.
797 (defvar *cold-symbol-allocation-gspace* nil)
798
799 ;;; Allocate (and initialize) a symbol.
800 (defun allocate-symbol (name)
801   (declare (simple-string name))
802   (let ((symbol (allocate-unboxed-object (or *cold-symbol-allocation-gspace*
803                                              *dynamic*)
804                                          sb!vm:n-word-bits
805                                          (1- sb!vm:symbol-size)
806                                          sb!vm:symbol-header-widetag)))
807     (write-wordindexed symbol sb!vm:symbol-value-slot *unbound-marker*)
808     (write-wordindexed symbol
809                        sb!vm:symbol-hash-slot
810                        (make-fixnum-descriptor 0))
811     (write-wordindexed symbol sb!vm:symbol-plist-slot *nil-descriptor*)
812     (write-wordindexed symbol sb!vm:symbol-name-slot
813                        (base-string-to-core name *dynamic*))
814     (write-wordindexed symbol sb!vm:symbol-package-slot *nil-descriptor*)
815     symbol))
816
817 ;;; Set the cold symbol value of SYMBOL-OR-SYMBOL-DES, which can be either a
818 ;;; descriptor of a cold symbol or (in an abbreviation for the
819 ;;; most common usage pattern) an ordinary symbol, which will be
820 ;;; automatically cold-interned.
821 (declaim (ftype (function ((or descriptor symbol) descriptor)) cold-set))
822 (defun cold-set (symbol-or-symbol-des value)
823   (let ((symbol-des (etypecase symbol-or-symbol-des
824                       (descriptor symbol-or-symbol-des)
825                       (symbol (cold-intern symbol-or-symbol-des)))))
826     (write-wordindexed symbol-des sb!vm:symbol-value-slot value)))
827 \f
828 ;;;; layouts and type system pre-initialization
829
830 ;;; Since we want to be able to dump structure constants and
831 ;;; predicates with reference layouts, we need to create layouts at
832 ;;; cold-load time. We use the name to intern layouts by, and dump a
833 ;;; list of all cold layouts in *!INITIAL-LAYOUTS* so that type system
834 ;;; initialization can find them. The only thing that's tricky [sic --
835 ;;; WHN 19990816] is initializing layout's layout, which must point to
836 ;;; itself.
837
838 ;;; a map from class names to lists of
839 ;;;    `(,descriptor ,name ,length ,inherits ,depth)
840 ;;; KLUDGE: It would be more understandable and maintainable to use
841 ;;; DEFSTRUCT (:TYPE LIST) here. -- WHN 19990823
842 (defvar *cold-layouts* (make-hash-table :test 'equal))
843
844 ;;; a map from DESCRIPTOR-BITS of cold layouts to the name, for inverting
845 ;;; mapping
846 (defvar *cold-layout-names* (make-hash-table :test 'eql))
847
848 ;;; FIXME: *COLD-LAYOUTS* and *COLD-LAYOUT-NAMES* should be
849 ;;; initialized by binding in GENESIS.
850
851 ;;; the descriptor for layout's layout (needed when making layouts)
852 (defvar *layout-layout*)
853
854 (defconstant target-layout-length
855   (layout-length (find-layout 'layout)))
856
857 (defun target-layout-index (slot-name)
858   ;; KLUDGE: this is a little bit sleazy, but the tricky thing is that
859   ;; structure slots don't have a terribly firm idea of their names.
860   ;; At least here if we change LAYOUT's package of definition, we
861   ;; only have to change one thing...
862   (let* ((name (find-symbol (symbol-name slot-name) "SB!KERNEL"))
863          (layout (find-layout 'layout))
864          (dd (layout-info layout))
865          (slots (dd-slots dd))
866          (dsd (find name slots :key #'dsd-name)))
867     (aver dsd)
868     (dsd-index dsd)))
869
870 (defun cold-set-layout-slot (cold-layout slot-name value)
871   (write-wordindexed
872    cold-layout
873    (+ sb!vm:instance-slots-offset (target-layout-index slot-name))
874    value))
875
876 ;;; Return a list of names created from the cold layout INHERITS data
877 ;;; in X.
878 (defun listify-cold-inherits (x)
879   (let ((len (descriptor-fixnum (read-wordindexed x
880                                                   sb!vm:vector-length-slot))))
881     (collect ((res))
882       (dotimes (index len)
883         (let* ((des (read-wordindexed x (+ sb!vm:vector-data-offset index)))
884                (found (gethash (descriptor-bits des) *cold-layout-names*)))
885           (if found
886             (res found)
887             (error "unknown descriptor at index ~S (bits = ~8,'0X)"
888                    index
889                    (descriptor-bits des)))))
890       (res))))
891
892 (declaim (ftype (function (symbol descriptor descriptor descriptor descriptor)
893                           descriptor)
894                 make-cold-layout))
895 (defun make-cold-layout (name length inherits depthoid nuntagged)
896   (let ((result (allocate-boxed-object *dynamic*
897                                        ;; KLUDGE: Why 1+? -- WHN 19990901
898                                        ;; header word? -- CSR 20051204
899                                        (1+ target-layout-length)
900                                        sb!vm:instance-pointer-lowtag)))
901     (write-memory result
902                   (make-other-immediate-descriptor
903                    target-layout-length sb!vm:instance-header-widetag))
904
905     ;; KLUDGE: The offsets into LAYOUT below should probably be pulled out
906     ;; of the cross-compiler's tables at genesis time instead of inserted
907     ;; by hand as bare numeric constants. -- WHN ca. 19990901
908
909     ;; Set slot 0 = the layout of the layout.
910     (write-wordindexed result sb!vm:instance-slots-offset *layout-layout*)
911
912     ;; Set the CLOS hash value.
913     ;;
914     ;; Note: CMU CL didn't set these in genesis, but instead arranged
915     ;; for them to be set at cold init time. That resulted in slightly
916     ;; kludgy-looking code, but there were at least two things to be
917     ;; said for it:
918     ;;   1. It put the hash values under the control of the target Lisp's
919     ;;      RANDOM function, so that CLOS behavior would be nearly
920     ;;      deterministic (instead of depending on the implementation of
921     ;;      RANDOM in the cross-compilation host, and the state of its
922     ;;      RNG when genesis begins).
923     ;;   2. It automatically ensured that all hash values in the target Lisp
924     ;;      were part of the same sequence, so that we didn't have to worry
925     ;;      about the possibility of the first hash value set in genesis
926     ;;      being precisely equal to the some hash value set in cold init time
927     ;;      (because the target Lisp RNG has advanced to precisely the same
928     ;;      state that the host Lisp RNG was in earlier).
929     ;; Point 1 should not be an issue in practice because of the way we do our
930     ;; build procedure in two steps, so that the SBCL that we end up with has
931     ;; been created by another SBCL (whose RNG is under our control).
932     ;; Point 2 is more of an issue. If ANSI had provided a way to feed
933     ;; entropy into an RNG, we would have no problem: we'd just feed
934     ;; some specialized genesis-time-only pattern into the RNG state
935     ;; before using it. However, they didn't, so we have a slight
936     ;; problem. We address it by generating the hash values using a
937     ;; different algorithm than we use in ordinary operation.
938     (let (;; The expression here is pretty arbitrary, we just want
939           ;; to make sure that it's not something which is (1)
940           ;; evenly distributed and (2) not foreordained to arise in
941           ;; the target Lisp's (RANDOM-LAYOUT-CLOS-HASH) sequence
942           ;; and show up as the CLOS-HASH value of some other
943           ;; LAYOUT.
944           (hash-value
945            (1+ (mod (logxor (logand   (random-layout-clos-hash) 15253)
946                             (logandc2 (random-layout-clos-hash) 15253)
947                             1)
948                     (1- sb!kernel:layout-clos-hash-limit)))))
949       (cold-set-layout-slot result 'clos-hash
950                             (make-fixnum-descriptor hash-value)))
951
952     ;; Set other slot values.
953     ;;
954     ;; leave CLASSOID uninitialized for now
955     (cold-set-layout-slot result 'invalid *nil-descriptor*)
956     (cold-set-layout-slot result 'inherits inherits)
957     (cold-set-layout-slot result 'depthoid depthoid)
958     (cold-set-layout-slot result 'length length)
959     (cold-set-layout-slot result 'info *nil-descriptor*)
960     (cold-set-layout-slot result 'pure *nil-descriptor*)
961     (cold-set-layout-slot result 'n-untagged-slots nuntagged)
962     (cold-set-layout-slot result 'for-std-class-p *nil-descriptor*)
963
964     (setf (gethash name *cold-layouts*)
965           (list result
966                 name
967                 (descriptor-fixnum length)
968                 (listify-cold-inherits inherits)
969                 (descriptor-fixnum depthoid)
970                 (descriptor-fixnum nuntagged)))
971     (setf (gethash (descriptor-bits result) *cold-layout-names*) name)
972
973     result))
974
975 (defun initialize-layouts ()
976
977   (clrhash *cold-layouts*)
978
979   ;; We initially create the layout of LAYOUT itself with NIL as the LAYOUT and
980   ;; #() as INHERITS,
981   (setq *layout-layout* *nil-descriptor*)
982   (let ((xlayout-layout (find-layout 'layout)))
983     (aver (= 0 (layout-n-untagged-slots xlayout-layout)))
984     (setq *layout-layout*
985           (make-cold-layout 'layout
986                             (number-to-core target-layout-length)
987                             (vector-in-core)
988                             (number-to-core (layout-depthoid xlayout-layout))
989                             (number-to-core 0)))
990   (write-wordindexed
991    *layout-layout* sb!vm:instance-slots-offset *layout-layout*)
992
993   ;; Then we create the layouts that we'll need to make a correct INHERITS
994   ;; vector for the layout of LAYOUT itself..
995   ;;
996   ;; FIXME: The various LENGTH and DEPTHOID numbers should be taken from
997   ;; the compiler's tables, not set by hand.
998   (let* ((t-layout
999           (make-cold-layout 't
1000                             (number-to-core 0)
1001                             (vector-in-core)
1002                             (number-to-core 0)
1003                             (number-to-core 0)))
1004          (so-layout
1005           (make-cold-layout 'structure-object
1006                             (number-to-core 1)
1007                             (vector-in-core t-layout)
1008                             (number-to-core 1)
1009                             (number-to-core 0)))
1010          (bso-layout
1011           (make-cold-layout 'structure!object
1012                             (number-to-core 1)
1013                             (vector-in-core t-layout so-layout)
1014                             (number-to-core 2)
1015                             (number-to-core 0)))
1016          (layout-inherits (vector-in-core t-layout
1017                                           so-layout
1018                                           bso-layout)))
1019
1020     ;; ..and return to backpatch the layout of LAYOUT.
1021     (setf (fourth (gethash 'layout *cold-layouts*))
1022           (listify-cold-inherits layout-inherits))
1023     (cold-set-layout-slot *layout-layout* 'inherits layout-inherits))))
1024 \f
1025 ;;;; interning symbols in the cold image
1026
1027 ;;; In order to avoid having to know about the package format, we
1028 ;;; build a data structure in *COLD-PACKAGE-SYMBOLS* that holds all
1029 ;;; interned symbols along with info about their packages. The data
1030 ;;; structure is a list of sublists, where the sublists have the
1031 ;;; following format:
1032 ;;;   (<make-package-arglist>
1033 ;;;    <internal-symbols>
1034 ;;;    <external-symbols>
1035 ;;;    <imported-internal-symbols>
1036 ;;;    <imported-external-symbols>
1037 ;;;    <shadowing-symbols>
1038 ;;;    <package-documentation>)
1039 ;;;
1040 ;;; KLUDGE: It would be nice to implement the sublists as instances of
1041 ;;; a DEFSTRUCT (:TYPE LIST). (They'd still be lists, but at least we'd be
1042 ;;; using mnemonically-named operators to access them, instead of trying
1043 ;;; to remember what THIRD and FIFTH mean, and hoping that we never
1044 ;;; need to change the list layout..) -- WHN 19990825
1045
1046 ;;; an alist from packages to lists of that package's symbols to be dumped
1047 (defvar *cold-package-symbols*)
1048 (declaim (type list *cold-package-symbols*))
1049
1050 ;;; a map from descriptors to symbols, so that we can back up. The key
1051 ;;; is the address in the target core.
1052 (defvar *cold-symbols*)
1053 (declaim (type hash-table *cold-symbols*))
1054
1055 ;;; sanity check for a symbol we're about to create on the target
1056 ;;;
1057 ;;; Make sure that the symbol has an appropriate package. In
1058 ;;; particular, catch the so-easy-to-make error of typing something
1059 ;;; like SB-KERNEL:%BYTE-BLT in cold sources when what you really
1060 ;;; need is SB!KERNEL:%BYTE-BLT.
1061 (defun package-ok-for-target-symbol-p (package)
1062   (let ((package-name (package-name package)))
1063     (or
1064      ;; Cold interning things in these standard packages is OK. (Cold
1065      ;; interning things in the other standard package, CL-USER, isn't
1066      ;; OK. We just use CL-USER to expose symbols whose homes are in
1067      ;; other packages. Thus, trying to cold intern a symbol whose
1068      ;; home package is CL-USER probably means that a coding error has
1069      ;; been made somewhere.)
1070      (find package-name '("COMMON-LISP" "KEYWORD") :test #'string=)
1071      ;; Cold interning something in one of our target-code packages,
1072      ;; which are ever-so-rigorously-and-elegantly distinguished by
1073      ;; this prefix on their names, is OK too.
1074      (string= package-name "SB!" :end1 3 :end2 3)
1075      ;; This one is OK too, since it ends up being COMMON-LISP on the
1076      ;; target.
1077      (string= package-name "SB-XC")
1078      ;; Anything else looks bad. (maybe COMMON-LISP-USER? maybe an extension
1079      ;; package in the xc host? something we can't think of
1080      ;; a valid reason to cold intern, anyway...)
1081      )))
1082
1083 ;;; like SYMBOL-PACKAGE, but safe for symbols which end up on the target
1084 ;;;
1085 ;;; Most host symbols we dump onto the target are created by SBCL
1086 ;;; itself, so that as long as we avoid gratuitously
1087 ;;; cross-compilation-unfriendly hacks, it just happens that their
1088 ;;; SYMBOL-PACKAGE in the host system corresponds to their
1089 ;;; SYMBOL-PACKAGE in the target system. However, that's not the case
1090 ;;; in the COMMON-LISP package, where we don't get to create the
1091 ;;; symbols but instead have to use the ones that the xc host created.
1092 ;;; In particular, while ANSI specifies which symbols are exported
1093 ;;; from COMMON-LISP, it doesn't specify that their home packages are
1094 ;;; COMMON-LISP, so the xc host can keep them in random packages which
1095 ;;; don't exist on the target (e.g. CLISP keeping some CL-exported
1096 ;;; symbols in the CLOS package).
1097 (defun symbol-package-for-target-symbol (symbol)
1098   ;; We want to catch weird symbols like CLISP's
1099   ;; CL:FIND-METHOD=CLOS::FIND-METHOD, but we don't want to get
1100   ;; sidetracked by ordinary symbols like :CHARACTER which happen to
1101   ;; have the same SYMBOL-NAME as exports from COMMON-LISP.
1102   (multiple-value-bind (cl-symbol cl-status)
1103       (find-symbol (symbol-name symbol) *cl-package*)
1104     (if (and (eq symbol cl-symbol)
1105              (eq cl-status :external))
1106         ;; special case, to work around possible xc host weirdness
1107         ;; in COMMON-LISP package
1108         *cl-package*
1109         ;; ordinary case
1110         (let ((result (symbol-package symbol)))
1111           (unless (package-ok-for-target-symbol-p result)
1112             (bug "~A in bad package for target: ~A" symbol result))
1113           result))))
1114
1115 ;;; Return a handle on an interned symbol. If necessary allocate the
1116 ;;; symbol and record which package the symbol was referenced in. When
1117 ;;; we allocate the symbol, make sure we record a reference to the
1118 ;;; symbol in the home package so that the package gets set.
1119 (defun cold-intern (symbol
1120                     &optional
1121                     (package (symbol-package-for-target-symbol symbol)))
1122
1123   (aver (package-ok-for-target-symbol-p package))
1124
1125   ;; Anything on the cross-compilation host which refers to the target
1126   ;; machinery through the host SB-XC package should be translated to
1127   ;; something on the target which refers to the same machinery
1128   ;; through the target COMMON-LISP package.
1129   (let ((p (find-package "SB-XC")))
1130     (when (eq package p)
1131       (setf package *cl-package*))
1132     (when (eq (symbol-package symbol) p)
1133       (setf symbol (intern (symbol-name symbol) *cl-package*))))
1134
1135   (let (;; Information about each cold-interned symbol is stored
1136         ;; in COLD-INTERN-INFO.
1137         ;;   (CAR COLD-INTERN-INFO) = descriptor of symbol
1138         ;;   (CDR COLD-INTERN-INFO) = list of packages, other than symbol's
1139         ;;                            own package, referring to symbol
1140         ;; (*COLD-PACKAGE-SYMBOLS* and *COLD-SYMBOLS* store basically the
1141         ;; same information, but with the mapping running the opposite way.)
1142         (cold-intern-info (get symbol 'cold-intern-info)))
1143     (unless cold-intern-info
1144       (cond ((eq (symbol-package-for-target-symbol symbol) package)
1145              (let ((handle (allocate-symbol (symbol-name symbol))))
1146                (setf (gethash (descriptor-bits handle) *cold-symbols*) symbol)
1147                (when (eq package *keyword-package*)
1148                  (cold-set handle handle))
1149                (setq cold-intern-info
1150                      (setf (get symbol 'cold-intern-info) (cons handle nil)))))
1151             (t
1152              (cold-intern symbol)
1153              (setq cold-intern-info (get symbol 'cold-intern-info)))))
1154     (unless (or (null package)
1155                 (member package (cdr cold-intern-info)))
1156       (push package (cdr cold-intern-info))
1157       (let* ((old-cps-entry (assoc package *cold-package-symbols*))
1158              (cps-entry (or old-cps-entry
1159                             (car (push (list package)
1160                                        *cold-package-symbols*)))))
1161         (unless old-cps-entry
1162           (/show "created *COLD-PACKAGE-SYMBOLS* entry for" package symbol))
1163         (push symbol (rest cps-entry))))
1164     (car cold-intern-info)))
1165
1166 ;;; Construct and return a value for use as *NIL-DESCRIPTOR*.
1167 (defun make-nil-descriptor ()
1168   (let* ((des (allocate-unboxed-object
1169                *static*
1170                sb!vm:n-word-bits
1171                sb!vm:symbol-size
1172                0))
1173          (result (make-descriptor (descriptor-high des)
1174                                   (+ (descriptor-low des)
1175                                      (* 2 sb!vm:n-word-bytes)
1176                                      (- sb!vm:list-pointer-lowtag
1177                                         sb!vm:other-pointer-lowtag)))))
1178     (write-wordindexed des
1179                        1
1180                        (make-other-immediate-descriptor
1181                         0
1182                         sb!vm:symbol-header-widetag))
1183     (write-wordindexed des
1184                        (+ 1 sb!vm:symbol-value-slot)
1185                        result)
1186     (write-wordindexed des
1187                        (+ 2 sb!vm:symbol-value-slot)
1188                        result)
1189     (write-wordindexed des
1190                        (+ 1 sb!vm:symbol-plist-slot)
1191                        result)
1192     (write-wordindexed des
1193                        (+ 1 sb!vm:symbol-name-slot)
1194                        ;; This is *DYNAMIC*, and DES is *STATIC*,
1195                        ;; because that's the way CMU CL did it; I'm
1196                        ;; not sure whether there's an underlying
1197                        ;; reason. -- WHN 1990826
1198                        (base-string-to-core "NIL" *dynamic*))
1199     (write-wordindexed des
1200                        (+ 1 sb!vm:symbol-package-slot)
1201                        result)
1202     (setf (get nil 'cold-intern-info)
1203           (cons result nil))
1204     (cold-intern nil)
1205     result))
1206
1207 ;;; Since the initial symbols must be allocated before we can intern
1208 ;;; anything else, we intern those here. We also set the value of T.
1209 (defun initialize-non-nil-symbols ()
1210   #!+sb-doc
1211   "Initialize the cold load symbol-hacking data structures."
1212   (let ((*cold-symbol-allocation-gspace* *static*))
1213     ;; Intern the others.
1214     (dolist (symbol sb!vm:*static-symbols*)
1215       (let* ((des (cold-intern symbol))
1216              (offset-wanted (sb!vm:static-symbol-offset symbol))
1217              (offset-found (- (descriptor-low des)
1218                               (descriptor-low *nil-descriptor*))))
1219         (unless (= offset-wanted offset-found)
1220           ;; FIXME: should be fatal
1221           (warn "Offset from ~S to ~S is ~W, not ~W"
1222                 symbol
1223                 nil
1224                 offset-found
1225                 offset-wanted))))
1226     ;; Establish the value of T.
1227     (let ((t-symbol (cold-intern t)))
1228       (cold-set t-symbol t-symbol))
1229     ;; Establish the value of *PSEUDO-ATOMIC-BITS* so that the
1230     ;; allocation sequences that expect it to be zero upon entrance
1231     ;; actually find it to be so.
1232     #!+(or x86-64 x86)
1233     (let ((p-a-a-symbol (cold-intern 'sb!kernel:*pseudo-atomic-bits*)))
1234       (cold-set p-a-a-symbol (make-fixnum-descriptor 0)))))
1235
1236 ;;; a helper function for FINISH-SYMBOLS: Return a cold alist suitable
1237 ;;; to be stored in *!INITIAL-LAYOUTS*.
1238 (defun cold-list-all-layouts ()
1239   (let ((result *nil-descriptor*))
1240     (maphash (lambda (key stuff)
1241                (cold-push (cold-cons (cold-intern key)
1242                                      (first stuff))
1243                           result))
1244              *cold-layouts*)
1245     result))
1246
1247 ;;; Establish initial values for magic symbols.
1248 ;;;
1249 ;;; Scan over all the symbols referenced in each package in
1250 ;;; *COLD-PACKAGE-SYMBOLS* making that for each one there's an
1251 ;;; appropriate entry in the *!INITIAL-SYMBOLS* data structure to
1252 ;;; intern it.
1253 (defun finish-symbols ()
1254
1255   ;; I think the point of setting these functions into SYMBOL-VALUEs
1256   ;; here, instead of using SYMBOL-FUNCTION, is that in CMU CL
1257   ;; SYMBOL-FUNCTION reduces to FDEFINITION, which is a pretty
1258   ;; hairy operation (involving globaldb.lisp etc.) which we don't
1259   ;; want to invoke early in cold init. -- WHN 2001-12-05
1260   ;;
1261   ;; FIXME: So OK, that's a reasonable reason to do something weird like
1262   ;; this, but this is still a weird thing to do, and we should change
1263   ;; the names to highlight that something weird is going on. Perhaps
1264   ;; *MAYBE-GC-FUN*, *INTERNAL-ERROR-FUN*, *HANDLE-BREAKPOINT-FUN*,
1265   ;; and *HANDLE-FUN-END-BREAKPOINT-FUN*...
1266   (dolist (symbol sb!vm::*c-callable-static-symbols*)
1267     (cold-set symbol (cold-fdefinition-object (cold-intern symbol))))
1268
1269   (cold-set 'sb!vm::*current-catch-block*          (make-fixnum-descriptor 0))
1270   (cold-set 'sb!vm::*current-unwind-protect-block* (make-fixnum-descriptor 0))
1271
1272   (cold-set '*free-interrupt-context-index* (make-fixnum-descriptor 0))
1273
1274   (cold-set '*!initial-layouts* (cold-list-all-layouts))
1275
1276   (/show "dumping packages" (mapcar #'car *cold-package-symbols*))
1277   (let ((initial-symbols *nil-descriptor*))
1278     (dolist (cold-package-symbols-entry *cold-package-symbols*)
1279       (let* ((cold-package (car cold-package-symbols-entry))
1280              (symbols (cdr cold-package-symbols-entry))
1281              (shadows (package-shadowing-symbols cold-package))
1282              (documentation (base-string-to-core (documentation cold-package t)))
1283              (internal-count 0)
1284              (external-count 0)
1285              (internal *nil-descriptor*)
1286              (external *nil-descriptor*)
1287              (imported-internal *nil-descriptor*)
1288              (imported-external *nil-descriptor*)
1289              (shadowing *nil-descriptor*))
1290         (declare (type package cold-package)) ; i.e. not a target descriptor
1291         (/show "dumping" cold-package symbols)
1292
1293         ;; FIXME: Add assertions here to make sure that inappropriate stuff
1294         ;; isn't being dumped:
1295         ;;   * the CL-USER package
1296         ;;   * the SB-COLD package
1297         ;;   * any internal symbols in the CL package
1298         ;;   * basically any package other than CL, KEYWORD, or the packages
1299         ;;     in package-data-list.lisp-expr
1300         ;; and that the structure of the KEYWORD package (e.g. whether
1301         ;; any symbols are internal to it) matches what we want in the
1302         ;; target SBCL.
1303
1304         ;; FIXME: It seems possible that by looking at the contents of
1305         ;; packages in the target SBCL we could find which symbols in
1306         ;; package-data-lisp.lisp-expr are now obsolete. (If I
1307         ;; understand correctly, only symbols which actually have
1308         ;; definitions or which are otherwise referred to actually end
1309         ;; up in the target packages.)
1310
1311         (dolist (symbol symbols)
1312           (let ((handle (car (get symbol 'cold-intern-info)))
1313                 (imported-p (not (eq (symbol-package-for-target-symbol symbol)
1314                                      cold-package))))
1315             (multiple-value-bind (found where)
1316                 (find-symbol (symbol-name symbol) cold-package)
1317               (unless (and where (eq found symbol))
1318                 (error "The symbol ~S is not available in ~S."
1319                        symbol
1320                        cold-package))
1321               (when (memq symbol shadows)
1322                 (cold-push handle shadowing))
1323               (case where
1324                 (:internal (if imported-p
1325                                (cold-push handle imported-internal)
1326                                (progn
1327                                  (cold-push handle internal)
1328                                  (incf internal-count))))
1329                 (:external (if imported-p
1330                                (cold-push handle imported-external)
1331                                (progn
1332                                  (cold-push handle external)
1333                                  (incf external-count))))))))
1334         (let ((r *nil-descriptor*))
1335           (cold-push documentation r)
1336           (cold-push shadowing r)
1337           (cold-push imported-external r)
1338           (cold-push imported-internal r)
1339           (cold-push external r)
1340           (cold-push internal r)
1341           (cold-push (make-make-package-args cold-package
1342                                              internal-count
1343                                              external-count)
1344                      r)
1345           ;; FIXME: It would be more space-efficient to use vectors
1346           ;; instead of lists here, and space-efficiency here would be
1347           ;; nice, since it would reduce the peak memory usage in
1348           ;; genesis and cold init.
1349           (cold-push r initial-symbols))))
1350     (cold-set '*!initial-symbols* initial-symbols))
1351
1352   (cold-set '*!initial-fdefn-objects* (list-all-fdefn-objects))
1353
1354   (cold-set '*!reversed-cold-toplevels* *current-reversed-cold-toplevels*)
1355
1356   #!+(or x86 x86-64)
1357   (progn
1358     (cold-set 'sb!vm::*fp-constant-0d0* (number-to-core 0d0))
1359     (cold-set 'sb!vm::*fp-constant-1d0* (number-to-core 1d0))
1360     (cold-set 'sb!vm::*fp-constant-0f0* (number-to-core 0f0))
1361     (cold-set 'sb!vm::*fp-constant-1f0* (number-to-core 1f0))))
1362
1363 ;;; Make a cold list that can be used as the arg list to MAKE-PACKAGE in
1364 ;;; order to make a package that is similar to PKG.
1365 (defun make-make-package-args (pkg internal-count external-count)
1366   (let* ((use *nil-descriptor*)
1367          (cold-nicknames *nil-descriptor*)
1368          (res *nil-descriptor*))
1369     (dolist (u (package-use-list pkg))
1370       (when (assoc u *cold-package-symbols*)
1371         (cold-push (base-string-to-core (package-name u)) use)))
1372     (let* ((pkg-name (package-name pkg))
1373            ;; Make the package nickname lists for the standard packages
1374            ;; be the minimum specified by ANSI, regardless of what value
1375            ;; the cross-compilation host happens to use.
1376            (warm-nicknames (cond ((string= pkg-name "COMMON-LISP")
1377                                   '("CL"))
1378                                  ((string= pkg-name "COMMON-LISP-USER")
1379                                   '("CL-USER"))
1380                                  ((string= pkg-name "KEYWORD")
1381                                   '())
1382                                  ;; For packages other than the
1383                                  ;; standard packages, the nickname
1384                                  ;; list was specified by our package
1385                                  ;; setup code, not by properties of
1386                                  ;; what cross-compilation host we
1387                                  ;; happened to use, and we can just
1388                                  ;; propagate it into the target.
1389                                  (t
1390                                   (package-nicknames pkg)))))
1391       (dolist (warm-nickname warm-nicknames)
1392         (cold-push (base-string-to-core warm-nickname) cold-nicknames)))
1393
1394     ;; INTERNAL-COUNT and EXTERNAL-COUNT are the number of symbols that
1395     ;; the package contains in the core. We arrange for the package
1396     ;; symbol tables to be created somewhat larger so that they don't
1397     ;; need to be rehashed so easily when additional symbols are
1398     ;; interned during the warm build.
1399     (cold-push (number-to-core (truncate internal-count 0.8)) res)
1400     (cold-push (cold-intern :internal-symbols) res)
1401     (cold-push (number-to-core (truncate external-count 0.8)) res)
1402     (cold-push (cold-intern :external-symbols) res)
1403
1404     (cold-push cold-nicknames res)
1405     (cold-push (cold-intern :nicknames) res)
1406
1407     (cold-push use res)
1408     (cold-push (cold-intern :use) res)
1409
1410     (cold-push (base-string-to-core (package-name pkg)) res)
1411     res))
1412 \f
1413 ;;;; functions and fdefinition objects
1414
1415 ;;; a hash table mapping from fdefinition names to descriptors of cold
1416 ;;; objects
1417 ;;;
1418 ;;; Note: Since fdefinition names can be lists like '(SETF FOO), and
1419 ;;; we want to have only one entry per name, this must be an 'EQUAL
1420 ;;; hash table, not the default 'EQL.
1421 (defvar *cold-fdefn-objects*)
1422
1423 (defvar *cold-fdefn-gspace* nil)
1424
1425 ;;; Given a cold representation of a symbol, return a warm
1426 ;;; representation.
1427 (defun warm-symbol (des)
1428   ;; Note that COLD-INTERN is responsible for keeping the
1429   ;; *COLD-SYMBOLS* table up to date, so if DES happens to refer to an
1430   ;; uninterned symbol, the code below will fail. But as long as we
1431   ;; don't need to look up uninterned symbols during bootstrapping,
1432   ;; that's OK..
1433   (multiple-value-bind (symbol found-p)
1434       (gethash (descriptor-bits des) *cold-symbols*)
1435     (declare (type symbol symbol))
1436     (unless found-p
1437       (error "no warm symbol"))
1438     symbol))
1439
1440 ;;; like CL:CAR, CL:CDR, and CL:NULL but for cold values
1441 (defun cold-car (des)
1442   (aver (= (descriptor-lowtag des) sb!vm:list-pointer-lowtag))
1443   (read-wordindexed des sb!vm:cons-car-slot))
1444 (defun cold-cdr (des)
1445   (aver (= (descriptor-lowtag des) sb!vm:list-pointer-lowtag))
1446   (read-wordindexed des sb!vm:cons-cdr-slot))
1447 (defun cold-null (des)
1448   (= (descriptor-bits des)
1449      (descriptor-bits *nil-descriptor*)))
1450
1451 ;;; Given a cold representation of a function name, return a warm
1452 ;;; representation.
1453 (declaim (ftype (function (descriptor) (or symbol list)) warm-fun-name))
1454 (defun warm-fun-name (des)
1455   (let ((result
1456          (ecase (descriptor-lowtag des)
1457            (#.sb!vm:list-pointer-lowtag
1458             (aver (not (cold-null des))) ; function named NIL? please no..
1459             ;; Do cold (DESTRUCTURING-BIND (COLD-CAR COLD-CADR) DES ..).
1460             (let* ((car-des (cold-car des))
1461                    (cdr-des (cold-cdr des))
1462                    (cadr-des (cold-car cdr-des))
1463                    (cddr-des (cold-cdr cdr-des)))
1464               (aver (cold-null cddr-des))
1465               (list (warm-symbol car-des)
1466                     (warm-symbol cadr-des))))
1467            (#.sb!vm:other-pointer-lowtag
1468             (warm-symbol des)))))
1469     (legal-fun-name-or-type-error result)
1470     result))
1471
1472 (defun cold-fdefinition-object (cold-name &optional leave-fn-raw)
1473   (declare (type descriptor cold-name))
1474   (/show0 "/cold-fdefinition-object")
1475   (let ((warm-name (warm-fun-name cold-name)))
1476     (or (gethash warm-name *cold-fdefn-objects*)
1477         (let ((fdefn (allocate-boxed-object (or *cold-fdefn-gspace* *dynamic*)
1478                                             (1- sb!vm:fdefn-size)
1479                                             sb!vm:other-pointer-lowtag)))
1480
1481           (setf (gethash warm-name *cold-fdefn-objects*) fdefn)
1482           (write-memory fdefn (make-other-immediate-descriptor
1483                                (1- sb!vm:fdefn-size) sb!vm:fdefn-widetag))
1484           (write-wordindexed fdefn sb!vm:fdefn-name-slot cold-name)
1485           (unless leave-fn-raw
1486             (write-wordindexed fdefn sb!vm:fdefn-fun-slot
1487                                *nil-descriptor*)
1488             (write-wordindexed fdefn
1489                                sb!vm:fdefn-raw-addr-slot
1490                                (make-random-descriptor
1491                                 (cold-foreign-symbol-address "undefined_tramp"))))
1492           fdefn))))
1493
1494 ;;; Handle the at-cold-init-time, fset-for-static-linkage operation
1495 ;;; requested by FOP-FSET.
1496 (defun static-fset (cold-name defn)
1497   (declare (type descriptor cold-name))
1498   (let ((fdefn (cold-fdefinition-object cold-name t))
1499         (type (logand (descriptor-low (read-memory defn)) sb!vm:widetag-mask)))
1500     (write-wordindexed fdefn sb!vm:fdefn-fun-slot defn)
1501     (write-wordindexed fdefn
1502                        sb!vm:fdefn-raw-addr-slot
1503                        (ecase type
1504                          (#.sb!vm:simple-fun-header-widetag
1505                           (/show0 "static-fset (simple-fun)")
1506                           #!+sparc
1507                           defn
1508                           #!-sparc
1509                           (make-random-descriptor
1510                            (+ (logandc2 (descriptor-bits defn)
1511                                         sb!vm:lowtag-mask)
1512                               (ash sb!vm:simple-fun-code-offset
1513                                    sb!vm:word-shift))))
1514                          (#.sb!vm:closure-header-widetag
1515                           (/show0 "/static-fset (closure)")
1516                           (make-random-descriptor
1517                            (cold-foreign-symbol-address "closure_tramp")))))
1518     fdefn))
1519
1520 (defun initialize-static-fns ()
1521   (let ((*cold-fdefn-gspace* *static*))
1522     (dolist (sym sb!vm:*static-funs*)
1523       (let* ((fdefn (cold-fdefinition-object (cold-intern sym)))
1524              (offset (- (+ (- (descriptor-low fdefn)
1525                               sb!vm:other-pointer-lowtag)
1526                            (* sb!vm:fdefn-raw-addr-slot sb!vm:n-word-bytes))
1527                         (descriptor-low *nil-descriptor*)))
1528              (desired (sb!vm:static-fun-offset sym)))
1529         (unless (= offset desired)
1530           ;; FIXME: should be fatal
1531           (error "Offset from FDEFN ~S to ~S is ~W, not ~W."
1532                  sym nil offset desired))))))
1533
1534 (defun list-all-fdefn-objects ()
1535   (let ((result *nil-descriptor*))
1536     (maphash (lambda (key value)
1537                (declare (ignore key))
1538                (cold-push value result))
1539              *cold-fdefn-objects*)
1540     result))
1541 \f
1542 ;;;; fixups and related stuff
1543
1544 ;;; an EQUAL hash table
1545 (defvar *cold-foreign-symbol-table*)
1546 (declaim (type hash-table *cold-foreign-symbol-table*))
1547
1548 ;; Read the sbcl.nm file to find the addresses for foreign-symbols in
1549 ;; the C runtime.
1550 (defun load-cold-foreign-symbol-table (filename)
1551   (/show "load-cold-foreign-symbol-table" filename)
1552   (with-open-file (file filename)
1553     (loop for line = (read-line file nil nil)
1554           while line do
1555           ;; UNIX symbol tables might have tabs in them, and tabs are
1556           ;; not in Common Lisp STANDARD-CHAR, so there seems to be no
1557           ;; nice portable way to deal with them within Lisp, alas.
1558           ;; Fortunately, it's easy to use UNIX command line tools like
1559           ;; sed to remove the problem, so it's not too painful for us
1560           ;; to push responsibility for converting tabs to spaces out to
1561           ;; the caller.
1562           ;;
1563           ;; Other non-STANDARD-CHARs are problematic for the same reason.
1564           ;; Make sure that there aren't any..
1565           (let ((ch (find-if (lambda (char)
1566                                (not (typep char 'standard-char)))
1567                              line)))
1568             (when ch
1569               (error "non-STANDARD-CHAR ~S found in foreign symbol table:~%~S"
1570                      ch
1571                      line)))
1572           (setf line (string-trim '(#\space) line))
1573           (let ((p1 (position #\space line :from-end nil))
1574                 (p2 (position #\space line :from-end t)))
1575             (if (not (and p1 p2 (< p1 p2)))
1576                 ;; KLUDGE: It's too messy to try to understand all
1577                 ;; possible output from nm, so we just punt the lines we
1578                 ;; don't recognize. We realize that there's some chance
1579                 ;; that might get us in trouble someday, so we warn
1580                 ;; about it.
1581                 (warn "ignoring unrecognized line ~S in ~A" line filename)
1582                 (multiple-value-bind (value name)
1583                     (if (string= "0x" line :end2 2)
1584                         (values (parse-integer line :start 2 :end p1 :radix 16)
1585                                 (subseq line (1+ p2)))
1586                         (values (parse-integer line :end p1 :radix 16)
1587                                 (subseq line (1+ p2))))
1588                   (multiple-value-bind (old-value found)
1589                       (gethash name *cold-foreign-symbol-table*)
1590                     (when (and found
1591                                (not (= old-value value)))
1592                       (warn "redefining ~S from #X~X to #X~X"
1593                             name old-value value)))
1594                   (/show "adding to *cold-foreign-symbol-table*:" name value)
1595                   (setf (gethash name *cold-foreign-symbol-table*) value))))))
1596   (values))     ;; PROGN
1597
1598 (defun cold-foreign-symbol-address (name)
1599   (or (find-foreign-symbol-in-table name *cold-foreign-symbol-table*)
1600       *foreign-symbol-placeholder-value*
1601       (progn
1602         (format *error-output* "~&The foreign symbol table is:~%")
1603         (maphash (lambda (k v)
1604                    (format *error-output* "~&~S = #X~8X~%" k v))
1605                  *cold-foreign-symbol-table*)
1606         (error "The foreign symbol ~S is undefined." name))))
1607
1608 (defvar *cold-assembler-routines*)
1609
1610 (defvar *cold-assembler-fixups*)
1611
1612 (defun record-cold-assembler-routine (name address)
1613   (/xhow "in RECORD-COLD-ASSEMBLER-ROUTINE" name address)
1614   (push (cons name address)
1615         *cold-assembler-routines*))
1616
1617 (defun record-cold-assembler-fixup (routine
1618                                     code-object
1619                                     offset
1620                                     &optional
1621                                     (kind :both))
1622   (push (list routine code-object offset kind)
1623         *cold-assembler-fixups*))
1624
1625 (defun lookup-assembler-reference (symbol)
1626   (let ((value (cdr (assoc symbol *cold-assembler-routines*))))
1627     ;; FIXME: Should this be ERROR instead of WARN?
1628     (unless value
1629       (warn "Assembler routine ~S not defined." symbol))
1630     value))
1631
1632 ;;; The x86 port needs to store code fixups along with code objects if
1633 ;;; they are to be moved, so fixups for code objects in the dynamic
1634 ;;; heap need to be noted.
1635 #!+(or x86 x86-64)
1636 (defvar *load-time-code-fixups*)
1637
1638 #!+(or x86 x86-64)
1639 (defun note-load-time-code-fixup (code-object offset value kind)
1640   ;; If CODE-OBJECT might be moved
1641   (when (= (gspace-identifier (descriptor-intuit-gspace code-object))
1642            dynamic-core-space-id)
1643     ;; FIXME: pushed thing should be a structure, not just a list
1644     (push (list code-object offset value kind) *load-time-code-fixups*))
1645   (values))
1646
1647 #!+(or x86 x86-64)
1648 (defun output-load-time-code-fixups ()
1649   (dolist (fixups *load-time-code-fixups*)
1650     (let ((code-object (first fixups))
1651           (offset (second fixups))
1652           (value (third fixups))
1653           (kind (fourth fixups)))
1654       (cold-push (cold-cons
1655                   (cold-intern :load-time-code-fixup)
1656                   (cold-cons
1657                    code-object
1658                    (cold-cons
1659                     (number-to-core offset)
1660                     (cold-cons
1661                      (number-to-core value)
1662                      (cold-cons
1663                       (cold-intern kind)
1664                       *nil-descriptor*)))))
1665                  *current-reversed-cold-toplevels*))))
1666
1667 ;;; Given a pointer to a code object and an offset relative to the
1668 ;;; tail of the code object's header, return an offset relative to the
1669 ;;; (beginning of the) code object.
1670 ;;;
1671 ;;; FIXME: It might be clearer to reexpress
1672 ;;;    (LET ((X (CALC-OFFSET CODE-OBJECT OFFSET0))) ..)
1673 ;;; as
1674 ;;;    (LET ((X (+ OFFSET0 (CODE-OBJECT-HEADER-N-BYTES CODE-OBJECT)))) ..).
1675 (declaim (ftype (function (descriptor sb!vm:word)) calc-offset))
1676 (defun calc-offset (code-object offset-from-tail-of-header)
1677   (let* ((header (read-memory code-object))
1678          (header-n-words (ash (descriptor-bits header)
1679                               (- sb!vm:n-widetag-bits)))
1680          (header-n-bytes (ash header-n-words sb!vm:word-shift))
1681          (result (+ offset-from-tail-of-header header-n-bytes)))
1682     result))
1683
1684 (declaim (ftype (function (descriptor sb!vm:word sb!vm:word keyword))
1685                 do-cold-fixup))
1686 (defun do-cold-fixup (code-object after-header value kind)
1687   (let* ((offset-within-code-object (calc-offset code-object after-header))
1688          (gspace-bytes (descriptor-bytes code-object))
1689          (gspace-byte-offset (+ (descriptor-byte-offset code-object)
1690                                 offset-within-code-object))
1691          (gspace-byte-address (gspace-byte-address
1692                                (descriptor-gspace code-object))))
1693     (ecase +backend-fasl-file-implementation+
1694       ;; See CMU CL source for other formerly-supported architectures
1695       ;; (and note that you have to rewrite them to use BVREF-X
1696       ;; instead of SAP-REF).
1697       (:alpha
1698          (ecase kind
1699          (:jmp-hint
1700           (assert (zerop (ldb (byte 2 0) value))))
1701          (:bits-63-48
1702           (let* ((value (if (logbitp 15 value) (+ value (ash 1 16)) value))
1703                  (value (if (logbitp 31 value) (+ value (ash 1 32)) value))
1704                  (value (if (logbitp 47 value) (+ value (ash 1 48)) value)))
1705             (setf (bvref-8 gspace-bytes gspace-byte-offset)
1706                   (ldb (byte 8 48) value)
1707                   (bvref-8 gspace-bytes (1+ gspace-byte-offset))
1708                   (ldb (byte 8 56) value))))
1709          (:bits-47-32
1710           (let* ((value (if (logbitp 15 value) (+ value (ash 1 16)) value))
1711                  (value (if (logbitp 31 value) (+ value (ash 1 32)) value)))
1712             (setf (bvref-8 gspace-bytes gspace-byte-offset)
1713                   (ldb (byte 8 32) value)
1714                   (bvref-8 gspace-bytes (1+ gspace-byte-offset))
1715                   (ldb (byte 8 40) value))))
1716          (:ldah
1717           (let ((value (if (logbitp 15 value) (+ value (ash 1 16)) value)))
1718             (setf (bvref-8 gspace-bytes gspace-byte-offset)
1719                   (ldb (byte 8 16) value)
1720                   (bvref-8 gspace-bytes (1+ gspace-byte-offset))
1721                   (ldb (byte 8 24) value))))
1722          (:lda
1723           (setf (bvref-8 gspace-bytes gspace-byte-offset)
1724                 (ldb (byte 8 0) value)
1725                 (bvref-8 gspace-bytes (1+ gspace-byte-offset))
1726                 (ldb (byte 8 8) value)))))
1727       (:hppa
1728        (ecase kind
1729          (:load
1730           (setf (bvref-32 gspace-bytes gspace-byte-offset)
1731                 (logior (ash (ldb (byte 11 0) value) 1)
1732                         (logand (bvref-32 gspace-bytes gspace-byte-offset)
1733                                 #xffffc000))))
1734          (:load-short
1735           (let ((low-bits (ldb (byte 11 0) value)))
1736             (assert (<= 0 low-bits (1- (ash 1 4))))
1737             (setf (bvref-32 gspace-bytes gspace-byte-offset)
1738                   (logior (ash low-bits 17)
1739                           (logand (bvref-32 gspace-bytes gspace-byte-offset)
1740                                   #xffe0ffff)))))
1741          (:hi
1742           (setf (bvref-32 gspace-bytes gspace-byte-offset)
1743                 (logior (ash (ldb (byte 5 13) value) 16)
1744                         (ash (ldb (byte 2 18) value) 14)
1745                         (ash (ldb (byte 2 11) value) 12)
1746                         (ash (ldb (byte 11 20) value) 1)
1747                         (ldb (byte 1 31) value)
1748                         (logand (bvref-32 gspace-bytes gspace-byte-offset)
1749                                 #xffe00000))))
1750          (:branch
1751           (let ((bits (ldb (byte 9 2) value)))
1752             (assert (zerop (ldb (byte 2 0) value)))
1753             (setf (bvref-32 gspace-bytes gspace-byte-offset)
1754                   (logior (ash bits 3)
1755                           (logand (bvref-32 gspace-bytes gspace-byte-offset)
1756                                   #xffe0e002)))))))
1757       (:mips
1758        (ecase kind
1759          (:jump
1760           (assert (zerop (ash value -28)))
1761           (setf (ldb (byte 26 0)
1762                      (bvref-32 gspace-bytes gspace-byte-offset))
1763                 (ash value -2)))
1764          (:lui
1765           (setf (bvref-32 gspace-bytes gspace-byte-offset)
1766                 (logior (mask-field (byte 16 16)
1767                                     (bvref-32 gspace-bytes gspace-byte-offset))
1768                         (ash (1+ (ldb (byte 17 15) value)) -1))))
1769          (:addi
1770           (setf (bvref-32 gspace-bytes gspace-byte-offset)
1771                 (logior (mask-field (byte 16 16)
1772                                     (bvref-32 gspace-bytes gspace-byte-offset))
1773                         (ldb (byte 16 0) value))))))
1774        ;; FIXME: PowerPC Fixups are not fully implemented. The bit
1775        ;; here starts to set things up to work properly, but there
1776        ;; needs to be corresponding code in ppc-vm.lisp
1777        (:ppc
1778         (ecase kind
1779           (:ba
1780            (setf (bvref-32 gspace-bytes gspace-byte-offset)
1781                  (dpb (ash value -2) (byte 24 2)
1782                       (bvref-32 gspace-bytes gspace-byte-offset))))
1783           (:ha
1784            (let* ((un-fixed-up (bvref-16 gspace-bytes
1785                                          (+ gspace-byte-offset 2)))
1786                   (fixed-up (+ un-fixed-up value))
1787                   (h (ldb (byte 16 16) fixed-up))
1788                   (l (ldb (byte 16 0) fixed-up)))
1789              (setf (bvref-16 gspace-bytes (+ gspace-byte-offset 2))
1790                    (if (logbitp 15 l) (ldb (byte 16 0) (1+ h)) h))))
1791           (:l
1792            (let* ((un-fixed-up (bvref-16 gspace-bytes
1793                                          (+ gspace-byte-offset 2)))
1794                   (fixed-up (+ un-fixed-up value)))
1795              (setf (bvref-16 gspace-bytes (+ gspace-byte-offset 2))
1796                    (ldb (byte 16 0) fixed-up))))))
1797       (:sparc
1798        (ecase kind
1799          (:call
1800           (error "can't deal with call fixups yet"))
1801          (:sethi
1802           (setf (bvref-32 gspace-bytes gspace-byte-offset)
1803                 (dpb (ldb (byte 22 10) value)
1804                      (byte 22 0)
1805                      (bvref-32 gspace-bytes gspace-byte-offset))))
1806          (:add
1807           (setf (bvref-32 gspace-bytes gspace-byte-offset)
1808                 (dpb (ldb (byte 10 0) value)
1809                      (byte 10 0)
1810                      (bvref-32 gspace-bytes gspace-byte-offset))))))
1811       ((:x86 :x86-64)
1812        (let* ((un-fixed-up (bvref-word gspace-bytes
1813                                                gspace-byte-offset))
1814               (code-object-start-addr (logandc2 (descriptor-bits code-object)
1815                                                 sb!vm:lowtag-mask)))
1816          (assert (= code-object-start-addr
1817                   (+ gspace-byte-address
1818                      (descriptor-byte-offset code-object))))
1819          (ecase kind
1820            (:absolute
1821             (let ((fixed-up (+ value un-fixed-up)))
1822               (setf (bvref-32 gspace-bytes gspace-byte-offset)
1823                     fixed-up)
1824               ;; comment from CMU CL sources:
1825               ;;
1826               ;; Note absolute fixups that point within the object.
1827               ;; KLUDGE: There seems to be an implicit assumption in
1828               ;; the old CMU CL code here, that if it doesn't point
1829               ;; before the object, it must point within the object
1830               ;; (not beyond it). It would be good to add an
1831               ;; explanation of why that's true, or an assertion that
1832               ;; it's really true, or both.
1833               (unless (< fixed-up code-object-start-addr)
1834                 (note-load-time-code-fixup code-object
1835                                            after-header
1836                                            value
1837                                            kind))))
1838            (:relative ; (used for arguments to X86 relative CALL instruction)
1839             (let ((fixed-up (- (+ value un-fixed-up)
1840                                gspace-byte-address
1841                                gspace-byte-offset
1842                                4))) ; "length of CALL argument"
1843               (setf (bvref-32 gspace-bytes gspace-byte-offset)
1844                     fixed-up)
1845               ;; Note relative fixups that point outside the code
1846               ;; object, which is to say all relative fixups, since
1847               ;; relative addressing within a code object never needs
1848               ;; a fixup.
1849               (note-load-time-code-fixup code-object
1850                                          after-header
1851                                          value
1852                                          kind))))))))
1853   (values))
1854
1855 (defun resolve-assembler-fixups ()
1856   (dolist (fixup *cold-assembler-fixups*)
1857     (let* ((routine (car fixup))
1858            (value (lookup-assembler-reference routine)))
1859       (when value
1860         (do-cold-fixup (second fixup) (third fixup) value (fourth fixup))))))
1861
1862 ;;; *COLD-FOREIGN-SYMBOL-TABLE* becomes *!INITIAL-FOREIGN-SYMBOLS* in
1863 ;;; the core. When the core is loaded, !LOADER-COLD-INIT uses this to
1864 ;;; create *STATIC-FOREIGN-SYMBOLS*, which the code in
1865 ;;; target-load.lisp refers to.
1866 (defun foreign-symbols-to-core ()
1867   (let ((result *nil-descriptor*))
1868     (maphash (lambda (symbol value)
1869                (cold-push (cold-cons (base-string-to-core symbol)
1870                                      (number-to-core value))
1871                           result))
1872              *cold-foreign-symbol-table*)
1873     (cold-set (cold-intern 'sb!kernel:*!initial-foreign-symbols*) result))
1874   (let ((result *nil-descriptor*))
1875     (dolist (rtn *cold-assembler-routines*)
1876       (cold-push (cold-cons (cold-intern (car rtn))
1877                             (number-to-core (cdr rtn)))
1878                  result))
1879     (cold-set (cold-intern '*!initial-assembler-routines*) result)))
1880
1881 \f
1882 ;;;; general machinery for cold-loading FASL files
1883
1884 ;;; FOP functions for cold loading
1885 (defvar *cold-fop-funs*
1886   ;; We start out with a copy of the ordinary *FOP-FUNS*. The ones
1887   ;; which aren't appropriate for cold load will be destructively
1888   ;; modified.
1889   (copy-seq *fop-funs*))
1890
1891 (defvar *normal-fop-funs*)
1892
1893 ;;; Cause a fop to have a special definition for cold load.
1894 ;;;
1895 ;;; This is similar to DEFINE-FOP, but unlike DEFINE-FOP, this version
1896 ;;;   (1) looks up the code for this name (created by a previous
1897 ;;        DEFINE-FOP) instead of creating a code, and
1898 ;;;   (2) stores its definition in the *COLD-FOP-FUNS* vector,
1899 ;;;       instead of storing in the *FOP-FUNS* vector.
1900 (defmacro define-cold-fop ((name &key (pushp t) (stackp t)) &rest forms)
1901   (aver (member pushp '(nil t)))
1902   (aver (member stackp '(nil t)))
1903   (let ((code (get name 'fop-code))
1904         (fname (symbolicate "COLD-" name)))
1905     (unless code
1906       (error "~S is not a defined FOP." name))
1907     `(progn
1908        (defun ,fname ()
1909          ,@(if stackp
1910                `((with-fop-stack ,pushp ,@forms))
1911                forms))
1912        (setf (svref *cold-fop-funs* ,code) #',fname))))
1913
1914 (defmacro clone-cold-fop ((name &key (pushp t) (stackp t))
1915                           (small-name)
1916                           &rest forms)
1917   (aver (member pushp '(nil t)))
1918   (aver (member stackp '(nil t)))
1919   `(progn
1920     (macrolet ((clone-arg () '(read-word-arg)))
1921       (define-cold-fop (,name :pushp ,pushp :stackp ,stackp) ,@forms))
1922     (macrolet ((clone-arg () '(read-byte-arg)))
1923       (define-cold-fop (,small-name :pushp ,pushp :stackp ,stackp) ,@forms))))
1924
1925 ;;; Cause a fop to be undefined in cold load.
1926 (defmacro not-cold-fop (name)
1927   `(define-cold-fop (,name)
1928      (error "The fop ~S is not supported in cold load." ',name)))
1929
1930 ;;; COLD-LOAD loads stuff into the core image being built by calling
1931 ;;; LOAD-AS-FASL with the fop function table rebound to a table of cold
1932 ;;; loading functions.
1933 (defun cold-load (filename)
1934   #!+sb-doc
1935   "Load the file named by FILENAME into the cold load image being built."
1936   (let* ((*normal-fop-funs* *fop-funs*)
1937          (*fop-funs* *cold-fop-funs*)
1938          (*cold-load-filename* (etypecase filename
1939                                  (string filename)
1940                                  (pathname (namestring filename)))))
1941     (with-open-file (s filename :element-type '(unsigned-byte 8))
1942       (load-as-fasl s nil nil))))
1943 \f
1944 ;;;; miscellaneous cold fops
1945
1946 (define-cold-fop (fop-misc-trap) *unbound-marker*)
1947
1948 (define-cold-fop (fop-short-character)
1949   (make-character-descriptor (read-byte-arg)))
1950
1951 (define-cold-fop (fop-empty-list) *nil-descriptor*)
1952 (define-cold-fop (fop-truth) (cold-intern t))
1953
1954 (define-cold-fop (fop-normal-load :stackp nil)
1955   (setq *fop-funs* *normal-fop-funs*))
1956
1957 (define-fop (fop-maybe-cold-load 82 :stackp nil)
1958   (when *cold-load-filename*
1959     (setq *fop-funs* *cold-fop-funs*)))
1960
1961 (define-cold-fop (fop-maybe-cold-load :stackp nil))
1962
1963 (clone-cold-fop (fop-struct)
1964                 (fop-small-struct)
1965   (let* ((size (clone-arg))
1966          (result (allocate-boxed-object *dynamic*
1967                                         (1+ size)
1968                                         sb!vm:instance-pointer-lowtag))
1969          (layout (pop-stack))
1970          (nuntagged
1971           (descriptor-fixnum
1972            (read-wordindexed
1973             layout
1974             (+ sb!vm:instance-slots-offset
1975                (target-layout-index 'n-untagged-slots)))))
1976          (ntagged (- size nuntagged)))
1977     (write-memory result (make-other-immediate-descriptor
1978                           size sb!vm:instance-header-widetag))
1979     (write-wordindexed result sb!vm:instance-slots-offset layout)
1980     (do ((index 1 (1+ index)))
1981         ((eql index size))
1982       (declare (fixnum index))
1983       (write-wordindexed result
1984                          (+ index sb!vm:instance-slots-offset)
1985                          (if (>= index ntagged)
1986                              (descriptor-word-sized-integer (pop-stack))
1987                              (pop-stack))))
1988     result))
1989
1990 (define-cold-fop (fop-layout)
1991   (let* ((nuntagged-des (pop-stack))
1992          (length-des (pop-stack))
1993          (depthoid-des (pop-stack))
1994          (cold-inherits (pop-stack))
1995          (name (pop-stack))
1996          (old (gethash name *cold-layouts*)))
1997     (declare (type descriptor length-des depthoid-des cold-inherits))
1998     (declare (type symbol name))
1999     ;; If a layout of this name has been defined already
2000     (if old
2001       ;; Enforce consistency between the previous definition and the
2002       ;; current definition, then return the previous definition.
2003       (destructuring-bind
2004           ;; FIXME: This would be more maintainable if we used
2005           ;; DEFSTRUCT (:TYPE LIST) to define COLD-LAYOUT. -- WHN 19990825
2006           (old-layout-descriptor
2007            old-name
2008            old-length
2009            old-inherits-list
2010            old-depthoid
2011            old-nuntagged)
2012           old
2013         (declare (type descriptor old-layout-descriptor))
2014         (declare (type index old-length old-nuntagged))
2015         (declare (type fixnum old-depthoid))
2016         (declare (type list old-inherits-list))
2017         (aver (eq name old-name))
2018         (let ((length (descriptor-fixnum length-des))
2019               (inherits-list (listify-cold-inherits cold-inherits))
2020               (depthoid (descriptor-fixnum depthoid-des))
2021               (nuntagged (descriptor-fixnum nuntagged-des)))
2022           (unless (= length old-length)
2023             (error "cold loading a reference to class ~S when the compile~%~
2024                     time length was ~S and current length is ~S"
2025                    name
2026                    length
2027                    old-length))
2028           (unless (equal inherits-list old-inherits-list)
2029             (error "cold loading a reference to class ~S when the compile~%~
2030                     time inherits were ~S~%~
2031                     and current inherits are ~S"
2032                    name
2033                    inherits-list
2034                    old-inherits-list))
2035           (unless (= depthoid old-depthoid)
2036             (error "cold loading a reference to class ~S when the compile~%~
2037                     time inheritance depthoid was ~S and current inheritance~%~
2038                     depthoid is ~S"
2039                    name
2040                    depthoid
2041                    old-depthoid))
2042           (unless (= nuntagged old-nuntagged)
2043             (error "cold loading a reference to class ~S when the compile~%~
2044                     time number of untagged slots was ~S and is currently ~S"
2045                    name
2046                    nuntagged
2047                    old-nuntagged)))
2048         old-layout-descriptor)
2049       ;; Make a new definition from scratch.
2050       (make-cold-layout name length-des cold-inherits depthoid-des
2051                         nuntagged-des))))
2052 \f
2053 ;;;; cold fops for loading symbols
2054
2055 ;;; Load a symbol SIZE characters long from *FASL-INPUT-STREAM* and
2056 ;;; intern that symbol in PACKAGE.
2057 (defun cold-load-symbol (size package)
2058   (let ((string (make-string size)))
2059     (read-string-as-bytes *fasl-input-stream* string)
2060     (cold-intern (intern string package))))
2061
2062 (macrolet ((frob (name pname-len package-len)
2063              `(define-cold-fop (,name)
2064                 (let ((index (read-arg ,package-len)))
2065                   (push-fop-table
2066                    (cold-load-symbol (read-arg ,pname-len)
2067                                      (svref *current-fop-table* index)))))))
2068   (frob fop-symbol-in-package-save #.sb!vm:n-word-bytes #.sb!vm:n-word-bytes)
2069   (frob fop-small-symbol-in-package-save 1 #.sb!vm:n-word-bytes)
2070   (frob fop-symbol-in-byte-package-save #.sb!vm:n-word-bytes 1)
2071   (frob fop-small-symbol-in-byte-package-save 1 1))
2072
2073 (clone-cold-fop (fop-lisp-symbol-save)
2074                 (fop-lisp-small-symbol-save)
2075   (push-fop-table (cold-load-symbol (clone-arg) *cl-package*)))
2076
2077 (clone-cold-fop (fop-keyword-symbol-save)
2078                 (fop-keyword-small-symbol-save)
2079   (push-fop-table (cold-load-symbol (clone-arg) *keyword-package*)))
2080
2081 (clone-cold-fop (fop-uninterned-symbol-save)
2082                 (fop-uninterned-small-symbol-save)
2083   (let* ((size (clone-arg))
2084          (name (make-string size)))
2085     (read-string-as-bytes *fasl-input-stream* name)
2086     (let ((symbol-des (allocate-symbol name)))
2087       (push-fop-table symbol-des))))
2088 \f
2089 ;;;; cold fops for loading lists
2090
2091 ;;; Make a list of the top LENGTH things on the fop stack. The last
2092 ;;; cdr of the list is set to LAST.
2093 (defmacro cold-stack-list (length last)
2094   `(do* ((index ,length (1- index))
2095          (result ,last (cold-cons (pop-stack) result)))
2096         ((= index 0) result)
2097      (declare (fixnum index))))
2098
2099 (define-cold-fop (fop-list)
2100   (cold-stack-list (read-byte-arg) *nil-descriptor*))
2101 (define-cold-fop (fop-list*)
2102   (cold-stack-list (read-byte-arg) (pop-stack)))
2103 (define-cold-fop (fop-list-1)
2104   (cold-stack-list 1 *nil-descriptor*))
2105 (define-cold-fop (fop-list-2)
2106   (cold-stack-list 2 *nil-descriptor*))
2107 (define-cold-fop (fop-list-3)
2108   (cold-stack-list 3 *nil-descriptor*))
2109 (define-cold-fop (fop-list-4)
2110   (cold-stack-list 4 *nil-descriptor*))
2111 (define-cold-fop (fop-list-5)
2112   (cold-stack-list 5 *nil-descriptor*))
2113 (define-cold-fop (fop-list-6)
2114   (cold-stack-list 6 *nil-descriptor*))
2115 (define-cold-fop (fop-list-7)
2116   (cold-stack-list 7 *nil-descriptor*))
2117 (define-cold-fop (fop-list-8)
2118   (cold-stack-list 8 *nil-descriptor*))
2119 (define-cold-fop (fop-list*-1)
2120   (cold-stack-list 1 (pop-stack)))
2121 (define-cold-fop (fop-list*-2)
2122   (cold-stack-list 2 (pop-stack)))
2123 (define-cold-fop (fop-list*-3)
2124   (cold-stack-list 3 (pop-stack)))
2125 (define-cold-fop (fop-list*-4)
2126   (cold-stack-list 4 (pop-stack)))
2127 (define-cold-fop (fop-list*-5)
2128   (cold-stack-list 5 (pop-stack)))
2129 (define-cold-fop (fop-list*-6)
2130   (cold-stack-list 6 (pop-stack)))
2131 (define-cold-fop (fop-list*-7)
2132   (cold-stack-list 7 (pop-stack)))
2133 (define-cold-fop (fop-list*-8)
2134   (cold-stack-list 8 (pop-stack)))
2135 \f
2136 ;;;; cold fops for loading vectors
2137
2138 (clone-cold-fop (fop-base-string)
2139                 (fop-small-base-string)
2140   (let* ((len (clone-arg))
2141          (string (make-string len)))
2142     (read-string-as-bytes *fasl-input-stream* string)
2143     (base-string-to-core string)))
2144
2145 #!+sb-unicode
2146 (clone-cold-fop (fop-character-string)
2147                 (fop-small-character-string)
2148   (bug "CHARACTER-STRING dumped by cross-compiler."))
2149
2150 (clone-cold-fop (fop-vector)
2151                 (fop-small-vector)
2152   (let* ((size (clone-arg))
2153          (result (allocate-vector-object *dynamic*
2154                                          sb!vm:n-word-bits
2155                                          size
2156                                          sb!vm:simple-vector-widetag)))
2157     (do ((index (1- size) (1- index)))
2158         ((minusp index))
2159       (declare (fixnum index))
2160       (write-wordindexed result
2161                          (+ index sb!vm:vector-data-offset)
2162                          (pop-stack)))
2163     result))
2164
2165 (define-cold-fop (fop-int-vector)
2166   (let* ((len (read-word-arg))
2167          (sizebits (read-byte-arg))
2168          (type (case sizebits
2169                  (0 sb!vm:simple-array-nil-widetag)
2170                  (1 sb!vm:simple-bit-vector-widetag)
2171                  (2 sb!vm:simple-array-unsigned-byte-2-widetag)
2172                  (4 sb!vm:simple-array-unsigned-byte-4-widetag)
2173                  (7 (prog1 sb!vm:simple-array-unsigned-byte-7-widetag
2174                       (setf sizebits 8)))
2175                  (8 sb!vm:simple-array-unsigned-byte-8-widetag)
2176                  (15 (prog1 sb!vm:simple-array-unsigned-byte-15-widetag
2177                        (setf sizebits 16)))
2178                  (16 sb!vm:simple-array-unsigned-byte-16-widetag)
2179                  (31 (prog1 sb!vm:simple-array-unsigned-byte-31-widetag
2180                        (setf sizebits 32)))
2181                  (32 sb!vm:simple-array-unsigned-byte-32-widetag)
2182                  #!+#.(cl:if (cl:= 64 sb!vm:n-word-bits) '(and) '(or))
2183                  (63 (prog1 sb!vm:simple-array-unsigned-byte-63-widetag
2184                        (setf sizebits 64)))
2185                  #!+#.(cl:if (cl:= 64 sb!vm:n-word-bits) '(and) '(or))
2186                  (64 sb!vm:simple-array-unsigned-byte-64-widetag)
2187                  (t (error "losing element size: ~W" sizebits))))
2188          (result (allocate-vector-object *dynamic* sizebits len type))
2189          (start (+ (descriptor-byte-offset result)
2190                    (ash sb!vm:vector-data-offset sb!vm:word-shift)))
2191          (end (+ start
2192                  (ceiling (* len sizebits)
2193                           sb!vm:n-byte-bits))))
2194     (read-bigvec-as-sequence-or-die (descriptor-bytes result)
2195                                     *fasl-input-stream*
2196                                     :start start
2197                                     :end end)
2198     result))
2199
2200 (define-cold-fop (fop-single-float-vector)
2201   (let* ((len (read-word-arg))
2202          (result (allocate-vector-object
2203                   *dynamic*
2204                   sb!vm:n-word-bits
2205                   len
2206                   sb!vm:simple-array-single-float-widetag))
2207          (start (+ (descriptor-byte-offset result)
2208                    (ash sb!vm:vector-data-offset sb!vm:word-shift)))
2209          (end (+ start (* len 4))))
2210     (read-bigvec-as-sequence-or-die (descriptor-bytes result)
2211                                     *fasl-input-stream*
2212                                     :start start
2213                                     :end end)
2214     result))
2215
2216 (not-cold-fop fop-double-float-vector)
2217 #!+long-float (not-cold-fop fop-long-float-vector)
2218 (not-cold-fop fop-complex-single-float-vector)
2219 (not-cold-fop fop-complex-double-float-vector)
2220 #!+long-float (not-cold-fop fop-complex-long-float-vector)
2221
2222 (define-cold-fop (fop-array)
2223   (let* ((rank (read-word-arg))
2224          (data-vector (pop-stack))
2225          (result (allocate-boxed-object *dynamic*
2226                                         (+ sb!vm:array-dimensions-offset rank)
2227                                         sb!vm:other-pointer-lowtag)))
2228     (write-memory result
2229                   (make-other-immediate-descriptor rank
2230                                                    sb!vm:simple-array-widetag))
2231     (write-wordindexed result sb!vm:array-fill-pointer-slot *nil-descriptor*)
2232     (write-wordindexed result sb!vm:array-data-slot data-vector)
2233     (write-wordindexed result sb!vm:array-displacement-slot *nil-descriptor*)
2234     (write-wordindexed result sb!vm:array-displaced-p-slot *nil-descriptor*)
2235     (let ((total-elements 1))
2236       (dotimes (axis rank)
2237         (let ((dim (pop-stack)))
2238           (unless (or (= (descriptor-lowtag dim) sb!vm:even-fixnum-lowtag)
2239                       (= (descriptor-lowtag dim) sb!vm:odd-fixnum-lowtag))
2240             (error "non-fixnum dimension? (~S)" dim))
2241           (setf total-elements
2242                 (* total-elements
2243                    (logior (ash (descriptor-high dim)
2244                                 (- descriptor-low-bits
2245                                    (1- sb!vm:n-lowtag-bits)))
2246                            (ash (descriptor-low dim)
2247                                 (- 1 sb!vm:n-lowtag-bits)))))
2248           (write-wordindexed result
2249                              (+ sb!vm:array-dimensions-offset axis)
2250                              dim)))
2251       (write-wordindexed result
2252                          sb!vm:array-elements-slot
2253                          (make-fixnum-descriptor total-elements)))
2254     result))
2255
2256 \f
2257 ;;;; cold fops for loading numbers
2258
2259 (defmacro define-cold-number-fop (fop)
2260   `(define-cold-fop (,fop :stackp nil)
2261      ;; Invoke the ordinary warm version of this fop to push the
2262      ;; number.
2263      (,fop)
2264      ;; Replace the warm fop result with the cold image of the warm
2265      ;; fop result.
2266      (with-fop-stack t
2267        (let ((number (pop-stack)))
2268          (number-to-core number)))))
2269
2270 (define-cold-number-fop fop-single-float)
2271 (define-cold-number-fop fop-double-float)
2272 (define-cold-number-fop fop-integer)
2273 (define-cold-number-fop fop-small-integer)
2274 (define-cold-number-fop fop-word-integer)
2275 (define-cold-number-fop fop-byte-integer)
2276 (define-cold-number-fop fop-complex-single-float)
2277 (define-cold-number-fop fop-complex-double-float)
2278
2279 (define-cold-fop (fop-ratio)
2280   (let ((den (pop-stack)))
2281     (number-pair-to-core (pop-stack) den sb!vm:ratio-widetag)))
2282
2283 (define-cold-fop (fop-complex)
2284   (let ((im (pop-stack)))
2285     (number-pair-to-core (pop-stack) im sb!vm:complex-widetag)))
2286 \f
2287 ;;;; cold fops for calling (or not calling)
2288
2289 (not-cold-fop fop-eval)
2290 (not-cold-fop fop-eval-for-effect)
2291
2292 (defvar *load-time-value-counter*)
2293
2294 (define-cold-fop (fop-funcall)
2295   (unless (= (read-byte-arg) 0)
2296     (error "You can't FOP-FUNCALL arbitrary stuff in cold load."))
2297   (let ((counter *load-time-value-counter*))
2298     (cold-push (cold-cons
2299                 (cold-intern :load-time-value)
2300                 (cold-cons
2301                  (pop-stack)
2302                  (cold-cons
2303                   (number-to-core counter)
2304                   *nil-descriptor*)))
2305                *current-reversed-cold-toplevels*)
2306     (setf *load-time-value-counter* (1+ counter))
2307     (make-descriptor 0 0 nil counter)))
2308
2309 (defun finalize-load-time-value-noise ()
2310   (cold-set (cold-intern '*!load-time-values*)
2311             (allocate-vector-object *dynamic*
2312                                     sb!vm:n-word-bits
2313                                     *load-time-value-counter*
2314                                     sb!vm:simple-vector-widetag)))
2315
2316 (define-cold-fop (fop-funcall-for-effect :pushp nil)
2317   (if (= (read-byte-arg) 0)
2318       (cold-push (pop-stack)
2319                  *current-reversed-cold-toplevels*)
2320       (error "You can't FOP-FUNCALL arbitrary stuff in cold load.")))
2321 \f
2322 ;;;; cold fops for fixing up circularities
2323
2324 (define-cold-fop (fop-rplaca :pushp nil)
2325   (let ((obj (svref *current-fop-table* (read-word-arg)))
2326         (idx (read-word-arg)))
2327     (write-memory (cold-nthcdr idx obj) (pop-stack))))
2328
2329 (define-cold-fop (fop-rplacd :pushp nil)
2330   (let ((obj (svref *current-fop-table* (read-word-arg)))
2331         (idx (read-word-arg)))
2332     (write-wordindexed (cold-nthcdr idx obj) 1 (pop-stack))))
2333
2334 (define-cold-fop (fop-svset :pushp nil)
2335   (let ((obj (svref *current-fop-table* (read-word-arg)))
2336         (idx (read-word-arg)))
2337     (write-wordindexed obj
2338                    (+ idx
2339                       (ecase (descriptor-lowtag obj)
2340                         (#.sb!vm:instance-pointer-lowtag 1)
2341                         (#.sb!vm:other-pointer-lowtag 2)))
2342                    (pop-stack))))
2343
2344 (define-cold-fop (fop-structset :pushp nil)
2345   (let ((obj (svref *current-fop-table* (read-word-arg)))
2346         (idx (read-word-arg)))
2347     (write-wordindexed obj (1+ idx) (pop-stack))))
2348
2349 ;;; In the original CMUCL code, this actually explicitly declared PUSHP
2350 ;;; to be T, even though that's what it defaults to in DEFINE-COLD-FOP.
2351 (define-cold-fop (fop-nthcdr)
2352   (cold-nthcdr (read-word-arg) (pop-stack)))
2353
2354 (defun cold-nthcdr (index obj)
2355   (dotimes (i index)
2356     (setq obj (read-wordindexed obj 1)))
2357   obj)
2358 \f
2359 ;;;; cold fops for loading code objects and functions
2360
2361 ;;; the names of things which have had COLD-FSET used on them already
2362 ;;; (used to make sure that we don't try to statically link a name to
2363 ;;; more than one definition)
2364 (defparameter *cold-fset-warm-names*
2365   ;; This can't be an EQL hash table because names can be conses, e.g.
2366   ;; (SETF CAR).
2367   (make-hash-table :test 'equal))
2368
2369 (define-cold-fop (fop-fset :pushp nil)
2370   (let* ((fn (pop-stack))
2371          (cold-name (pop-stack))
2372          (warm-name (warm-fun-name cold-name)))
2373     (if (gethash warm-name *cold-fset-warm-names*)
2374         (error "duplicate COLD-FSET for ~S" warm-name)
2375         (setf (gethash warm-name *cold-fset-warm-names*) t))
2376     (static-fset cold-name fn)))
2377
2378 (define-cold-fop (fop-fdefinition)
2379   (cold-fdefinition-object (pop-stack)))
2380
2381 (define-cold-fop (fop-sanctify-for-execution)
2382   (pop-stack))
2383
2384 ;;; Setting this variable shows what code looks like before any
2385 ;;; fixups (or function headers) are applied.
2386 #!+sb-show (defvar *show-pre-fixup-code-p* nil)
2387
2388 ;;; FIXME: The logic here should be converted into a function
2389 ;;; COLD-CODE-FOP-GUTS (NCONST CODE-SIZE) called by DEFINE-COLD-FOP
2390 ;;; FOP-CODE and DEFINE-COLD-FOP FOP-SMALL-CODE, so that
2391 ;;; variable-capture nastiness like (LET ((NCONST ,NCONST) ..) ..)
2392 ;;; doesn't keep me awake at night.
2393 (defmacro define-cold-code-fop (name nconst code-size)
2394   `(define-cold-fop (,name)
2395      (let* ((nconst ,nconst)
2396             (code-size ,code-size)
2397             (raw-header-n-words (+ sb!vm:code-trace-table-offset-slot nconst))
2398             (header-n-words
2399              ;; Note: we round the number of constants up to ensure
2400              ;; that the code vector will be properly aligned.
2401              (round-up raw-header-n-words 2))
2402             (des (allocate-cold-descriptor *dynamic*
2403                                            (+ (ash header-n-words
2404                                                    sb!vm:word-shift)
2405                                               code-size)
2406                                            sb!vm:other-pointer-lowtag)))
2407        (write-memory des
2408                      (make-other-immediate-descriptor
2409                       header-n-words sb!vm:code-header-widetag))
2410        (write-wordindexed des
2411                           sb!vm:code-code-size-slot
2412                           (make-fixnum-descriptor
2413                            (ash (+ code-size (1- (ash 1 sb!vm:word-shift)))
2414                                 (- sb!vm:word-shift))))
2415        (write-wordindexed des sb!vm:code-entry-points-slot *nil-descriptor*)
2416        (write-wordindexed des sb!vm:code-debug-info-slot (pop-stack))
2417        (when (oddp raw-header-n-words)
2418          (write-wordindexed des
2419                             raw-header-n-words
2420                             (make-random-descriptor 0)))
2421        (do ((index (1- raw-header-n-words) (1- index)))
2422            ((< index sb!vm:code-trace-table-offset-slot))
2423          (write-wordindexed des index (pop-stack)))
2424        (let* ((start (+ (descriptor-byte-offset des)
2425                         (ash header-n-words sb!vm:word-shift)))
2426               (end (+ start code-size)))
2427          (read-bigvec-as-sequence-or-die (descriptor-bytes des)
2428                                          *fasl-input-stream*
2429                                          :start start
2430                                          :end end)
2431          #!+sb-show
2432          (when *show-pre-fixup-code-p*
2433            (format *trace-output*
2434                    "~&/raw code from code-fop ~W ~W:~%"
2435                    nconst
2436                    code-size)
2437            (do ((i start (+ i sb!vm:n-word-bytes)))
2438                ((>= i end))
2439              (format *trace-output*
2440                      "/#X~8,'0x: #X~8,'0x~%"
2441                      (+ i (gspace-byte-address (descriptor-gspace des)))
2442                      (bvref-32 (descriptor-bytes des) i)))))
2443        des)))
2444
2445 (define-cold-code-fop fop-code (read-word-arg) (read-word-arg))
2446
2447 (define-cold-code-fop fop-small-code (read-byte-arg) (read-halfword-arg))
2448
2449 (clone-cold-fop (fop-alter-code :pushp nil)
2450                 (fop-byte-alter-code)
2451   (let ((slot (clone-arg))
2452         (value (pop-stack))
2453         (code (pop-stack)))
2454     (write-wordindexed code slot value)))
2455
2456 (define-cold-fop (fop-fun-entry)
2457   (let* ((xrefs (pop-stack))
2458          (type (pop-stack))
2459          (arglist (pop-stack))
2460          (name (pop-stack))
2461          (code-object (pop-stack))
2462          (offset (calc-offset code-object (read-word-arg)))
2463          (fn (descriptor-beyond code-object
2464                                 offset
2465                                 sb!vm:fun-pointer-lowtag))
2466          (next (read-wordindexed code-object sb!vm:code-entry-points-slot)))
2467     (unless (zerop (logand offset sb!vm:lowtag-mask))
2468       (error "unaligned function entry: ~S at #X~X" name offset))
2469     (write-wordindexed code-object sb!vm:code-entry-points-slot fn)
2470     (write-memory fn
2471                   (make-other-immediate-descriptor
2472                    (ash offset (- sb!vm:word-shift))
2473                    sb!vm:simple-fun-header-widetag))
2474     (write-wordindexed fn
2475                        sb!vm:simple-fun-self-slot
2476                        ;; KLUDGE: Wiring decisions like this in at
2477                        ;; this level ("if it's an x86") instead of a
2478                        ;; higher level of abstraction ("if it has such
2479                        ;; and such relocation peculiarities (which
2480                        ;; happen to be confined to the x86)") is bad.
2481                        ;; It would be nice if the code were instead
2482                        ;; conditional on some more descriptive
2483                        ;; feature, :STICKY-CODE or
2484                        ;; :LOAD-GC-INTERACTION or something.
2485                        ;;
2486                        ;; FIXME: The X86 definition of the function
2487                        ;; self slot breaks everything object.tex says
2488                        ;; about it. (As far as I can tell, the X86
2489                        ;; definition makes it a pointer to the actual
2490                        ;; code instead of a pointer back to the object
2491                        ;; itself.) Ask on the mailing list whether
2492                        ;; this is documented somewhere, and if not,
2493                        ;; try to reverse engineer some documentation.
2494                        #!-(or x86 x86-64)
2495                        ;; a pointer back to the function object, as
2496                        ;; described in CMU CL
2497                        ;; src/docs/internals/object.tex
2498                        fn
2499                        #!+(or x86 x86-64)
2500                        ;; KLUDGE: a pointer to the actual code of the
2501                        ;; object, as described nowhere that I can find
2502                        ;; -- WHN 19990907
2503                        (make-random-descriptor
2504                         (+ (descriptor-bits fn)
2505                            (- (ash sb!vm:simple-fun-code-offset
2506                                    sb!vm:word-shift)
2507                               ;; FIXME: We should mask out the type
2508                               ;; bits, not assume we know what they
2509                               ;; are and subtract them out this way.
2510                               sb!vm:fun-pointer-lowtag))))
2511     (write-wordindexed fn sb!vm:simple-fun-next-slot next)
2512     (write-wordindexed fn sb!vm:simple-fun-name-slot name)
2513     (write-wordindexed fn sb!vm:simple-fun-arglist-slot arglist)
2514     (write-wordindexed fn sb!vm:simple-fun-type-slot type)
2515     (write-wordindexed fn sb!vm::simple-fun-xrefs-slot xrefs)
2516     fn))
2517
2518 (define-cold-fop (fop-foreign-fixup)
2519   (let* ((kind (pop-stack))
2520          (code-object (pop-stack))
2521          (len (read-byte-arg))
2522          (sym (make-string len)))
2523     (read-string-as-bytes *fasl-input-stream* sym)
2524     (let ((offset (read-word-arg))
2525           (value (cold-foreign-symbol-address sym)))
2526       (do-cold-fixup code-object offset value kind))
2527    code-object))
2528
2529 #!+linkage-table
2530 (define-cold-fop (fop-foreign-dataref-fixup)
2531   (let* ((kind (pop-stack))
2532          (code-object (pop-stack))
2533          (len (read-byte-arg))
2534          (sym (make-string len)))
2535     (read-string-as-bytes *fasl-input-stream* sym)
2536     (maphash (lambda (k v)
2537                (format *error-output* "~&~S = #X~8X~%" k v))
2538              *cold-foreign-symbol-table*)
2539     (error "shared foreign symbol in cold load: ~S (~S)" sym kind)))
2540
2541 (define-cold-fop (fop-assembler-code)
2542   (let* ((length (read-word-arg))
2543          (header-n-words
2544           ;; Note: we round the number of constants up to ensure that
2545           ;; the code vector will be properly aligned.
2546           (round-up sb!vm:code-constants-offset 2))
2547          (des (allocate-cold-descriptor *read-only*
2548                                         (+ (ash header-n-words
2549                                                 sb!vm:word-shift)
2550                                            length)
2551                                         sb!vm:other-pointer-lowtag)))
2552     (write-memory des
2553                   (make-other-immediate-descriptor
2554                    header-n-words sb!vm:code-header-widetag))
2555     (write-wordindexed des
2556                        sb!vm:code-code-size-slot
2557                        (make-fixnum-descriptor
2558                         (ash (+ length (1- (ash 1 sb!vm:word-shift)))
2559                              (- sb!vm:word-shift))))
2560     (write-wordindexed des sb!vm:code-entry-points-slot *nil-descriptor*)
2561     (write-wordindexed des sb!vm:code-debug-info-slot *nil-descriptor*)
2562
2563     (let* ((start (+ (descriptor-byte-offset des)
2564                      (ash header-n-words sb!vm:word-shift)))
2565            (end (+ start length)))
2566       (read-bigvec-as-sequence-or-die (descriptor-bytes des)
2567                                       *fasl-input-stream*
2568                                       :start start
2569                                       :end end))
2570     des))
2571
2572 (define-cold-fop (fop-assembler-routine)
2573   (let* ((routine (pop-stack))
2574          (des (pop-stack))
2575          (offset (calc-offset des (read-word-arg))))
2576     (record-cold-assembler-routine
2577      routine
2578      (+ (logandc2 (descriptor-bits des) sb!vm:lowtag-mask) offset))
2579     des))
2580
2581 (define-cold-fop (fop-assembler-fixup)
2582   (let* ((routine (pop-stack))
2583          (kind (pop-stack))
2584          (code-object (pop-stack))
2585          (offset (read-word-arg)))
2586     (record-cold-assembler-fixup routine code-object offset kind)
2587     code-object))
2588
2589 (define-cold-fop (fop-code-object-fixup)
2590   (let* ((kind (pop-stack))
2591          (code-object (pop-stack))
2592          (offset (read-word-arg))
2593          (value (descriptor-bits code-object)))
2594     (do-cold-fixup code-object offset value kind)
2595     code-object))
2596 \f
2597 ;;;; emitting C header file
2598
2599 (defun tailwise-equal (string tail)
2600   (and (>= (length string) (length tail))
2601        (string= string tail :start1 (- (length string) (length tail)))))
2602
2603 (defun write-boilerplate ()
2604   (format t "/*~%")
2605   (dolist (line
2606            '("This is a machine-generated file. Please do not edit it by hand."
2607              "(As of sbcl-0.8.14, it came from WRITE-CONFIG-H in genesis.lisp.)"
2608              nil
2609              "This file contains low-level information about the"
2610              "internals of a particular version and configuration"
2611              "of SBCL. It is used by the C compiler to create a runtime"
2612              "support environment, an executable program in the host"
2613              "operating system's native format, which can then be used to"
2614              "load and run 'core' files, which are basically programs"
2615              "in SBCL's own format."))
2616     (format t " *~@[ ~A~]~%" line))
2617   (format t " */~%"))
2618
2619 (defun c-name (string &optional strip)
2620   (delete #\+
2621           (substitute-if #\_ (lambda (c) (member c '(#\- #\/ #\%)))
2622                          (remove-if (lambda (c) (position c strip))
2623                                     string))))
2624
2625 (defun c-symbol-name (symbol &optional strip)
2626   (c-name (symbol-name symbol) strip))
2627
2628 (defun write-makefile-features ()
2629   ;; propagating *SHEBANG-FEATURES* into the Makefiles
2630   (dolist (shebang-feature-name (sort (mapcar #'c-symbol-name
2631                                               sb-cold:*shebang-features*)
2632                                       #'string<))
2633     (format t "LISP_FEATURE_~A=1~%" shebang-feature-name)))
2634
2635 (defun write-config-h ()
2636   ;; propagating *SHEBANG-FEATURES* into C-level #define's
2637   (dolist (shebang-feature-name (sort (mapcar #'c-symbol-name
2638                                               sb-cold:*shebang-features*)
2639                                       #'string<))
2640     (format t "#define LISP_FEATURE_~A~%" shebang-feature-name))
2641   (terpri)
2642   ;; and miscellaneous constants
2643   (format t "#define SBCL_CORE_VERSION_INTEGER ~D~%" sbcl-core-version-integer)
2644   (format t
2645           "#define SBCL_VERSION_STRING ~S~%"
2646           (sb!xc:lisp-implementation-version))
2647   (format t "#define CORE_MAGIC 0x~X~%" core-magic)
2648   (format t "#ifndef LANGUAGE_ASSEMBLY~2%")
2649   (format t "#define LISPOBJ(x) ((lispobj)x)~2%")
2650   (format t "#else /* LANGUAGE_ASSEMBLY */~2%")
2651   (format t "#define LISPOBJ(thing) thing~2%")
2652   (format t "#endif /* LANGUAGE_ASSEMBLY */~2%")
2653   (terpri))
2654
2655 (defun write-constants-h ()
2656   ;; writing entire families of named constants
2657   (let ((constants nil))
2658     (dolist (package-name '( ;; Even in CMU CL, constants from VM
2659                             ;; were automatically propagated
2660                             ;; into the runtime.
2661                             "SB!VM"
2662                             ;; In SBCL, we also propagate various
2663                             ;; magic numbers related to file format,
2664                             ;; which live here instead of SB!VM.
2665                             "SB!FASL"))
2666       (do-external-symbols (symbol (find-package package-name))
2667         (when (constantp symbol)
2668           (let ((name (symbol-name symbol)))
2669             (labels ( ;; shared machinery
2670                      (record (string priority)
2671                        (push (list string
2672                                    priority
2673                                    (symbol-value symbol)
2674                                    (documentation symbol 'variable))
2675                              constants))
2676                      ;; machinery for old-style CMU CL Lisp-to-C
2677                      ;; arbitrary renaming, being phased out in favor of
2678                      ;; the newer systematic RECORD-WITH-TRANSLATED-NAME
2679                      ;; renaming
2680                      (record-with-munged-name (prefix string priority)
2681                        (record (concatenate
2682                                 'simple-string
2683                                 prefix
2684                                 (delete #\- (string-capitalize string)))
2685                                priority))
2686                      (maybe-record-with-munged-name (tail prefix priority)
2687                        (when (tailwise-equal name tail)
2688                          (record-with-munged-name prefix
2689                                                   (subseq name 0
2690                                                           (- (length name)
2691                                                              (length tail)))
2692                                                   priority)))
2693                      ;; machinery for new-style SBCL Lisp-to-C naming
2694                      (record-with-translated-name (priority)
2695                        (record (c-name name) priority))
2696                      (maybe-record-with-translated-name (suffixes priority)
2697                        (when (some (lambda (suffix)
2698                                      (tailwise-equal name suffix))
2699                                    suffixes)
2700                          (record-with-translated-name priority))))
2701
2702               (maybe-record-with-translated-name '("-LOWTAG") 0)
2703               (maybe-record-with-translated-name '("-WIDETAG") 1)
2704               (maybe-record-with-munged-name "-FLAG" "flag_" 2)
2705               (maybe-record-with-munged-name "-TRAP" "trap_" 3)
2706               (maybe-record-with-munged-name "-SUBTYPE" "subtype_" 4)
2707               (maybe-record-with-munged-name "-SC-NUMBER" "sc_" 5)
2708               (maybe-record-with-translated-name '("-START" "-END" "-SIZE") 6)
2709               (maybe-record-with-translated-name '("-CORE-ENTRY-TYPE-CODE") 7)
2710               (maybe-record-with-translated-name '("-CORE-SPACE-ID") 8))))))
2711     ;; KLUDGE: these constants are sort of important, but there's no
2712     ;; pleasing way to inform the code above about them.  So we fake
2713     ;; it for now.  nikodemus on #lisp (2004-08-09) suggested simply
2714     ;; exporting every numeric constant from SB!VM; that would work,
2715     ;; but the C runtime would have to be altered to use Lisp-like names
2716     ;; rather than the munged names currently exported.  --njf, 2004-08-09
2717     (dolist (c '(sb!vm:n-word-bits sb!vm:n-word-bytes
2718                  sb!vm:n-lowtag-bits sb!vm:lowtag-mask
2719                  sb!vm:n-widetag-bits sb!vm:widetag-mask
2720                  sb!vm:n-fixnum-tag-bits sb!vm:fixnum-tag-mask))
2721       (push (list (c-symbol-name c)
2722                   -1                    ; invent a new priority
2723                   (symbol-value c)
2724                   nil)
2725             constants))
2726     ;; One more symbol that doesn't fit into the code above.
2727     (let ((c 'sb!impl::+magic-hash-vector-value+))
2728       (push (list (c-symbol-name c)
2729                   9
2730                   (symbol-value c)
2731                   nil)
2732             constants))
2733     (setf constants
2734           (sort constants
2735                 (lambda (const1 const2)
2736                   (if (= (second const1) (second const2))
2737                       (< (third const1) (third const2))
2738                       (< (second const1) (second const2))))))
2739     (let ((prev-priority (second (car constants))))
2740       (dolist (const constants)
2741         (destructuring-bind (name priority value doc) const
2742           (unless (= prev-priority priority)
2743             (terpri)
2744             (setf prev-priority priority))
2745           (format t "#define ~A " name)
2746           (format t
2747                   ;; KLUDGE: We're dumping two different kinds of
2748                   ;; values here, (1) small codes and (2) machine
2749                   ;; addresses. The small codes can be dumped as bare
2750                   ;; integer values. The large machine addresses might
2751                   ;; cause problems if they're large and represented
2752                   ;; as (signed) C integers, so we want to force them
2753                   ;; to be unsigned by appending an U to the
2754                   ;; literal. We can't dump all the values using the
2755                   ;; literal-U syntax, since the assembler doesn't
2756                   ;; support that syntax and some of the small
2757                   ;; constants can be used in assembler files.
2758                   (let ( ;; cutoff for treatment as a small code
2759                         (cutoff (expt 2 16)))
2760                     (cond ((minusp value)
2761                            (error "stub: negative values unsupported"))
2762                           ((< value cutoff)
2763                            "~D")
2764                           (t
2765                            "~DU")))
2766                   value)
2767           (format t " /* 0x~X */~@[  /* ~A */~]~%" value doc))))
2768     (terpri))
2769
2770   ;; writing information about internal errors
2771   (let ((internal-errors sb!c:*backend-internal-errors*))
2772     (dotimes (i (length internal-errors))
2773       (let ((current-error (aref internal-errors i)))
2774         ;; FIXME: this UNLESS should go away (see also FIXME in
2775         ;; interr.lisp) -- APD, 2002-03-05
2776         (unless (eq nil (car current-error))
2777           (format t "#define ~A ~D~%"
2778                   (c-symbol-name (car current-error))
2779                   i)))))
2780   (terpri)
2781
2782   ;; I'm not really sure why this is in SB!C, since it seems
2783   ;; conceptually like something that belongs to SB!VM. In any case,
2784   ;; it's needed C-side.
2785   (format t "#define BACKEND_PAGE_SIZE ~DU~%" sb!c:*backend-page-size*)
2786
2787   (terpri)
2788
2789   ;; FIXME: The SPARC has a PSEUDO-ATOMIC-TRAP that differs between
2790   ;; platforms. If we export this from the SB!VM package, it gets
2791   ;; written out as #define trap_PseudoAtomic, which is confusing as
2792   ;; the runtime treats trap_ as the prefix for illegal instruction
2793   ;; type things. We therefore don't export it, but instead do
2794   #!+sparc
2795   (when (boundp 'sb!vm::pseudo-atomic-trap)
2796     (format t
2797             "#define PSEUDO_ATOMIC_TRAP ~D /* 0x~:*~X */~%"
2798             sb!vm::pseudo-atomic-trap)
2799     (terpri))
2800   ;; possibly this is another candidate for a rename (to
2801   ;; pseudo-atomic-trap-number or pseudo-atomic-magic-constant
2802   ;; [possibly applicable to other platforms])
2803
2804   (dolist (symbol '(sb!vm::float-traps-byte
2805                     sb!vm::float-exceptions-byte
2806                     sb!vm::float-sticky-bits
2807                     sb!vm::float-rounding-mode))
2808     (format t "#define ~A_POSITION ~A /* ~:*0x~X */~%"
2809             (c-symbol-name symbol)
2810             (sb!xc:byte-position (symbol-value symbol)))
2811     (format t "#define ~A_MASK 0x~X /* ~:*~A */~%"
2812             (c-symbol-name symbol)
2813             (sb!xc:mask-field (symbol-value symbol) -1))))
2814
2815
2816
2817 (defun write-primitive-object (obj)
2818   ;; writing primitive object layouts
2819   (format t "#ifndef LANGUAGE_ASSEMBLY~2%")
2820   (format t
2821           "struct ~A {~%"
2822           (c-name (string-downcase (string (sb!vm:primitive-object-name obj)))))
2823   (when (sb!vm:primitive-object-widetag obj)
2824     (format t "    lispobj header;~%"))
2825   (dolist (slot (sb!vm:primitive-object-slots obj))
2826     (format t "    ~A ~A~@[[1]~];~%"
2827             (getf (sb!vm:slot-options slot) :c-type "lispobj")
2828             (c-name (string-downcase (string (sb!vm:slot-name slot))))
2829             (sb!vm:slot-rest-p slot)))
2830   (format t "};~2%")
2831   (format t "#else /* LANGUAGE_ASSEMBLY */~2%")
2832   (format t "/* These offsets are SLOT-OFFSET * N-WORD-BYTES - LOWTAG~%")
2833   (format t " * so they work directly on tagged addresses. */~2%")
2834   (let ((name (sb!vm:primitive-object-name obj))
2835         (lowtag (eval (sb!vm:primitive-object-lowtag obj))))
2836     (when lowtag
2837       (dolist (slot (sb!vm:primitive-object-slots obj))
2838         (format t "#define ~A_~A_OFFSET ~D~%"
2839                 (c-symbol-name name)
2840                 (c-symbol-name (sb!vm:slot-name slot))
2841                 (- (* (sb!vm:slot-offset slot) sb!vm:n-word-bytes) lowtag)))
2842       (terpri)))
2843   (format t "#endif /* LANGUAGE_ASSEMBLY */~2%"))
2844
2845 (defun write-structure-object (dd)
2846   (flet ((cstring (designator)
2847            (c-name (string-downcase (string designator)))))
2848     (format t "#ifndef LANGUAGE_ASSEMBLY~2%")
2849     (format t "struct ~A {~%" (cstring (dd-name dd)))
2850     (format t "    lispobj header;~%")
2851     (format t "    lispobj layout;~%")
2852     (dolist (slot (dd-slots dd))
2853       (when (eq t (dsd-raw-type slot))
2854         (format t "    lispobj ~A;~%" (cstring (dsd-name slot)))))
2855     (unless (oddp (+ (dd-length dd) (dd-raw-length dd)))
2856       (format t "    lispobj raw_slot_padding;~%"))
2857     (dotimes (n (dd-raw-length dd))
2858       (format t "    lispobj raw~D;~%" (- (dd-raw-length dd) n 1)))
2859     (format t "};~2%")
2860     (format t "#endif /* LANGUAGE_ASSEMBLY */~2%")))
2861
2862 (defun write-static-symbols ()
2863   (dolist (symbol (cons nil sb!vm:*static-symbols*))
2864     ;; FIXME: It would be nice to use longer names than NIL and
2865     ;; (particularly) T in #define statements.
2866     (format t "#define ~A LISPOBJ(0x~X)~%"
2867             ;; FIXME: It would be nice not to need to strip anything
2868             ;; that doesn't get stripped always by C-SYMBOL-NAME.
2869             (c-symbol-name symbol "%*.!")
2870             (if *static*                ; if we ran GENESIS
2871               ;; We actually ran GENESIS, use the real value.
2872               (descriptor-bits (cold-intern symbol))
2873               ;; We didn't run GENESIS, so guess at the address.
2874               (+ sb!vm:static-space-start
2875                  sb!vm:n-word-bytes
2876                  sb!vm:other-pointer-lowtag
2877                    (if symbol (sb!vm:static-symbol-offset symbol) 0))))))
2878
2879 \f
2880 ;;;; writing map file
2881
2882 ;;; Write a map file describing the cold load. Some of this
2883 ;;; information is subject to change due to relocating GC, but even so
2884 ;;; it can be very handy when attempting to troubleshoot the early
2885 ;;; stages of cold load.
2886 (defun write-map ()
2887   (let ((*print-pretty* nil)
2888         (*print-case* :upcase))
2889     (format t "assembler routines defined in core image:~2%")
2890     (dolist (routine (sort (copy-list *cold-assembler-routines*) #'<
2891                            :key #'cdr))
2892       (format t "#X~8,'0X: ~S~%" (cdr routine) (car routine)))
2893     (let ((funs nil)
2894           (undefs nil))
2895       (maphash (lambda (name fdefn)
2896                  (let ((fun (read-wordindexed fdefn
2897                                               sb!vm:fdefn-fun-slot)))
2898                    (if (= (descriptor-bits fun)
2899                           (descriptor-bits *nil-descriptor*))
2900                        (push name undefs)
2901                        (let ((addr (read-wordindexed
2902                                     fdefn sb!vm:fdefn-raw-addr-slot)))
2903                          (push (cons name (descriptor-bits addr))
2904                                funs)))))
2905                *cold-fdefn-objects*)
2906       (format t "~%~|~%initially defined functions:~2%")
2907       (setf funs (sort funs #'< :key #'cdr))
2908       (dolist (info funs)
2909         (format t "0x~8,'0X: ~S   #X~8,'0X~%" (cdr info) (car info)
2910                 (- (cdr info) #x17)))
2911       (format t
2912 "~%~|
2913 (a note about initially undefined function references: These functions
2914 are referred to by code which is installed by GENESIS, but they are not
2915 installed by GENESIS. This is not necessarily a problem; functions can
2916 be defined later, by cold init toplevel forms, or in files compiled and
2917 loaded at warm init, or elsewhere. As long as they are defined before
2918 they are called, everything should be OK. Things are also OK if the
2919 cross-compiler knew their inline definition and used that everywhere
2920 that they were called before the out-of-line definition is installed,
2921 as is fairly common for structure accessors.)
2922 initially undefined function references:~2%")
2923
2924       (setf undefs (sort undefs #'string< :key #'fun-name-block-name))
2925       (dolist (name undefs)
2926         (format t "~S~%" name)))
2927
2928     (format t "~%~|~%layout names:~2%")
2929     (collect ((stuff))
2930       (maphash (lambda (name gorp)
2931                  (declare (ignore name))
2932                  (stuff (cons (descriptor-bits (car gorp))
2933                               (cdr gorp))))
2934                *cold-layouts*)
2935       (dolist (x (sort (stuff) #'< :key #'car))
2936         (apply #'format t "~8,'0X: ~S[~D]~%~10T~S~%" x))))
2937
2938   (values))
2939 \f
2940 ;;;; writing core file
2941
2942 (defvar *core-file*)
2943 (defvar *data-page*)
2944
2945 ;;; magic numbers to identify entries in a core file
2946 ;;;
2947 ;;; (In case you were wondering: No, AFAIK there's no special magic about
2948 ;;; these which requires them to be in the 38xx range. They're just
2949 ;;; arbitrary words, tested not for being in a particular range but just
2950 ;;; for equality. However, if you ever need to look at a .core file and
2951 ;;; figure out what's going on, it's slightly convenient that they're
2952 ;;; all in an easily recognizable range, and displacing the range away from
2953 ;;; zero seems likely to reduce the chance that random garbage will be
2954 ;;; misinterpreted as a .core file.)
2955 (defconstant version-core-entry-type-code 3860)
2956 (defconstant build-id-core-entry-type-code 3899)
2957 (defconstant new-directory-core-entry-type-code 3861)
2958 (defconstant initial-fun-core-entry-type-code 3863)
2959 (defconstant page-table-core-entry-type-code 3880)
2960 #!+(and sb-lutex sb-thread)
2961 (defconstant lutex-table-core-entry-type-code 3887)
2962 (defconstant end-core-entry-type-code 3840)
2963
2964 (declaim (ftype (function (sb!vm:word) sb!vm:word) write-word))
2965 (defun write-word (num)
2966   (ecase sb!c:*backend-byte-order*
2967     (:little-endian
2968      (dotimes (i sb!vm:n-word-bytes)
2969        (write-byte (ldb (byte 8 (* i 8)) num) *core-file*)))
2970     (:big-endian
2971      (dotimes (i sb!vm:n-word-bytes)
2972        (write-byte (ldb (byte 8 (* (- (1- sb!vm:n-word-bytes) i) 8)) num)
2973                    *core-file*))))
2974   num)
2975
2976 (defun advance-to-page ()
2977   (force-output *core-file*)
2978   (file-position *core-file*
2979                  (round-up (file-position *core-file*)
2980                            sb!c:*backend-page-size*)))
2981
2982 (defun output-gspace (gspace)
2983   (force-output *core-file*)
2984   (let* ((posn (file-position *core-file*))
2985          (bytes (* (gspace-free-word-index gspace) sb!vm:n-word-bytes))
2986          (pages (ceiling bytes sb!c:*backend-page-size*))
2987          (total-bytes (* pages sb!c:*backend-page-size*)))
2988
2989     (file-position *core-file*
2990                    (* sb!c:*backend-page-size* (1+ *data-page*)))
2991     (format t
2992             "writing ~S byte~:P [~S page~:P] from ~S~%"
2993             total-bytes
2994             pages
2995             gspace)
2996     (force-output)
2997
2998     ;; Note: It is assumed that the GSPACE allocation routines always
2999     ;; allocate whole pages (of size *target-page-size*) and that any
3000     ;; empty gspace between the free pointer and the end of page will
3001     ;; be zero-filled. This will always be true under Mach on machines
3002     ;; where the page size is equal. (RT is 4K, PMAX is 4K, Sun 3 is
3003     ;; 8K).
3004     (write-bigvec-as-sequence (gspace-bytes gspace)
3005                               *core-file*
3006                               :end total-bytes)
3007     (force-output *core-file*)
3008     (file-position *core-file* posn)
3009
3010     ;; Write part of a (new) directory entry which looks like this:
3011     ;;   GSPACE IDENTIFIER
3012     ;;   WORD COUNT
3013     ;;   DATA PAGE
3014     ;;   ADDRESS
3015     ;;   PAGE COUNT
3016     (write-word (gspace-identifier gspace))
3017     (write-word (gspace-free-word-index gspace))
3018     (write-word *data-page*)
3019     (multiple-value-bind (floor rem)
3020         (floor (gspace-byte-address gspace) sb!c:*backend-page-size*)
3021       (aver (zerop rem))
3022       (write-word floor))
3023     (write-word pages)
3024
3025     (incf *data-page* pages)))
3026
3027 ;;; Create a core file created from the cold loaded image. (This is
3028 ;;; the "initial core file" because core files could be created later
3029 ;;; by executing SAVE-LISP in a running system, perhaps after we've
3030 ;;; added some functionality to the system.)
3031 (declaim (ftype (function (string)) write-initial-core-file))
3032 (defun write-initial-core-file (filename)
3033
3034   (let ((filenamestring (namestring filename))
3035         (*data-page* 0))
3036
3037     (format t
3038             "[building initial core file in ~S: ~%"
3039             filenamestring)
3040     (force-output)
3041
3042     (with-open-file (*core-file* filenamestring
3043                                  :direction :output
3044                                  :element-type '(unsigned-byte 8)
3045                                  :if-exists :rename-and-delete)
3046
3047       ;; Write the magic number.
3048       (write-word core-magic)
3049
3050       ;; Write the Version entry.
3051       (write-word version-core-entry-type-code)
3052       (write-word 3)
3053       (write-word sbcl-core-version-integer)
3054
3055       ;; Write the build ID.
3056       (write-word build-id-core-entry-type-code)
3057       (let ((build-id (with-open-file (s "output/build-id.tmp"
3058                                          :direction :input)
3059                         (read s))))
3060         (declare (type simple-string build-id))
3061         (/show build-id (length build-id))
3062         ;; Write length of build ID record: BUILD-ID-CORE-ENTRY-TYPE-CODE
3063         ;; word, this length word, and one word for each char of BUILD-ID.
3064         (write-word (+ 2 (length build-id)))
3065         (dovector (char build-id)
3066           ;; (We write each character as a word in order to avoid
3067           ;; having to think about word alignment issues in the
3068           ;; sbcl-0.7.8 version of coreparse.c.)
3069           (write-word (sb!xc:char-code char))))
3070
3071       ;; Write the New Directory entry header.
3072       (write-word new-directory-core-entry-type-code)
3073       (write-word 17) ; length = (5 words/space) * 3 spaces + 2 for header.
3074
3075       (output-gspace *read-only*)
3076       (output-gspace *static*)
3077       (output-gspace *dynamic*)
3078
3079       ;; Write the initial function.
3080       (write-word initial-fun-core-entry-type-code)
3081       (write-word 3)
3082       (let* ((cold-name (cold-intern '!cold-init))
3083              (cold-fdefn (cold-fdefinition-object cold-name))
3084              (initial-fun (read-wordindexed cold-fdefn
3085                                             sb!vm:fdefn-fun-slot)))
3086         (format t
3087                 "~&/(DESCRIPTOR-BITS INITIAL-FUN)=#X~X~%"
3088                 (descriptor-bits initial-fun))
3089         (write-word (descriptor-bits initial-fun)))
3090
3091       ;; Write the End entry.
3092       (write-word end-core-entry-type-code)
3093       (write-word 2)))
3094
3095   (format t "done]~%")
3096   (force-output)
3097   (/show "leaving WRITE-INITIAL-CORE-FILE")
3098   (values))
3099 \f
3100 ;;;; the actual GENESIS function
3101
3102 ;;; Read the FASL files in OBJECT-FILE-NAMES and produce a Lisp core,
3103 ;;; and/or information about a Lisp core, therefrom.
3104 ;;;
3105 ;;; input file arguments:
3106 ;;;   SYMBOL-TABLE-FILE-NAME names a UNIX-style .nm file *with* *any*
3107 ;;;     *tab* *characters* *converted* *to* *spaces*. (We push
3108 ;;;     responsibility for removing tabs out to the caller it's
3109 ;;;     trivial to remove them using UNIX command line tools like
3110 ;;;     sed, whereas it's a headache to do it portably in Lisp because
3111 ;;;     #\TAB is not a STANDARD-CHAR.) If this file is not supplied,
3112 ;;;     a core file cannot be built (but a C header file can be).
3113 ;;;
3114 ;;; output files arguments (any of which may be NIL to suppress output):
3115 ;;;   CORE-FILE-NAME gets a Lisp core.
3116 ;;;   C-HEADER-FILE-NAME gets a C header file, traditionally called
3117 ;;;     internals.h, which is used by the C compiler when constructing
3118 ;;;     the executable which will load the core.
3119 ;;;   MAP-FILE-NAME gets (?) a map file. (dunno about this -- WHN 19990815)
3120 ;;;
3121 ;;; FIXME: GENESIS doesn't belong in SB!VM. Perhaps in %KERNEL for now,
3122 ;;; perhaps eventually in SB-LD or SB-BOOT.
3123 (defun sb!vm:genesis (&key
3124                       object-file-names
3125                       symbol-table-file-name
3126                       core-file-name
3127                       map-file-name
3128                       c-header-dir-name)
3129
3130   (format t
3131           "~&beginning GENESIS, ~A~%"
3132           (if core-file-name
3133             ;; Note: This output summarizing what we're doing is
3134             ;; somewhat telegraphic in style, not meant to imply that
3135             ;; we're not e.g. also creating a header file when we
3136             ;; create a core.
3137             (format nil "creating core ~S" core-file-name)
3138             (format nil "creating headers in ~S" c-header-dir-name)))
3139
3140   (let ((*cold-foreign-symbol-table* (make-hash-table :test 'equal)))
3141
3142     (when core-file-name
3143       (if symbol-table-file-name
3144           (load-cold-foreign-symbol-table symbol-table-file-name)
3145           (error "can't output a core file without symbol table file input")))
3146
3147     ;; Now that we've successfully read our only input file (by
3148     ;; loading the symbol table, if any), it's a good time to ensure
3149     ;; that there'll be someplace for our output files to go when
3150     ;; we're done.
3151     (flet ((frob (filename)
3152              (when filename
3153                (ensure-directories-exist filename :verbose t))))
3154       (frob core-file-name)
3155       (frob map-file-name))
3156
3157     ;; (This shouldn't matter in normal use, since GENESIS normally
3158     ;; only runs once in any given Lisp image, but it could reduce
3159     ;; confusion if we ever experiment with running, tweaking, and
3160     ;; rerunning genesis interactively.)
3161     (do-all-symbols (sym)
3162       (remprop sym 'cold-intern-info))
3163
3164     (let* ((*foreign-symbol-placeholder-value* (if core-file-name nil 0))
3165            (*load-time-value-counter* 0)
3166            (*cold-fdefn-objects* (make-hash-table :test 'equal))
3167            (*cold-symbols* (make-hash-table :test 'equal))
3168            (*cold-package-symbols* nil)
3169            (*read-only* (make-gspace :read-only
3170                                      read-only-core-space-id
3171                                      sb!vm:read-only-space-start))
3172            (*static*    (make-gspace :static
3173                                      static-core-space-id
3174                                      sb!vm:static-space-start))
3175            (*dynamic*   (make-gspace :dynamic
3176                                      dynamic-core-space-id
3177                                      #!+gencgc sb!vm:dynamic-space-start
3178                                      #!-gencgc sb!vm:dynamic-0-space-start))
3179            (*nil-descriptor* (make-nil-descriptor))
3180            (*current-reversed-cold-toplevels* *nil-descriptor*)
3181            (*unbound-marker* (make-other-immediate-descriptor
3182                               0
3183                               sb!vm:unbound-marker-widetag))
3184            *cold-assembler-fixups*
3185            *cold-assembler-routines*
3186            #!+(or x86 x86-64) *load-time-code-fixups*)
3187
3188       ;; Prepare for cold load.
3189       (initialize-non-nil-symbols)
3190       (initialize-layouts)
3191       (initialize-static-fns)
3192
3193       ;; Initialize the *COLD-SYMBOLS* system with the information
3194       ;; from package-data-list.lisp-expr and
3195       ;; common-lisp-exports.lisp-expr.
3196       ;;
3197       ;; Why do things this way? Historically, the *COLD-SYMBOLS*
3198       ;; machinery was designed and implemented in CMU CL long before
3199       ;; I (WHN) ever heard of CMU CL. It dumped symbols and packages
3200       ;; iff they were used in the cold image. When I added the
3201       ;; package-data-list.lisp-expr mechanism, the idea was to
3202       ;; centralize all information about packages and exports. Thus,
3203       ;; it was the natural place for information even about packages
3204       ;; (such as SB!PCL and SB!WALKER) which aren't used much until
3205       ;; after cold load. This didn't quite match the CMU CL approach
3206       ;; of filling *COLD-SYMBOLS* with symbols which appear in the
3207       ;; cold image and then dumping only those symbols. By explicitly
3208       ;; putting all the symbols from package-data-list.lisp-expr and
3209       ;; from common-lisp-exports.lisp-expr into *COLD-SYMBOLS* here,
3210       ;; we feed our centralized symbol information into the old CMU
3211       ;; CL code without having to change the old CMU CL code too
3212       ;; much. (And the old CMU CL code is still useful for making
3213       ;; sure that the appropriate keywords and internal symbols end
3214       ;; up interned in the target Lisp, which is good, e.g. in order
3215       ;; to make &KEY arguments work right and in order to make
3216       ;; BACKTRACEs into target Lisp system code be legible.)
3217       (dolist (exported-name
3218                (sb-cold:read-from-file "common-lisp-exports.lisp-expr"))
3219         (cold-intern (intern exported-name *cl-package*)))
3220       (dolist (pd (sb-cold:read-from-file "package-data-list.lisp-expr"))
3221         (declare (type sb-cold:package-data pd))
3222         (let ((package (find-package (sb-cold:package-data-name pd))))
3223           (labels (;; Call FN on every node of the TREE.
3224                    (mapc-on-tree (fn tree)
3225                                  (declare (type function fn))
3226                                  (typecase tree
3227                                    (cons (mapc-on-tree fn (car tree))
3228                                          (mapc-on-tree fn (cdr tree)))
3229                                    (t (funcall fn tree)
3230                                       (values))))
3231                    ;; Make sure that information about the association
3232                    ;; between PACKAGE and the symbol named NAME gets
3233                    ;; recorded in the cold-intern system or (as a
3234                    ;; convenience when dealing with the tree structure
3235                    ;; allowed in the PACKAGE-DATA-EXPORTS slot) do
3236                    ;; nothing if NAME is NIL.
3237                    (chill (name)
3238                      (when name
3239                        (cold-intern (intern name package) package))))
3240             (mapc-on-tree #'chill (sb-cold:package-data-export pd))
3241             (mapc #'chill (sb-cold:package-data-reexport pd))
3242             (dolist (sublist (sb-cold:package-data-import-from pd))
3243               (destructuring-bind (package-name &rest symbol-names) sublist
3244                 (declare (ignore package-name))
3245                 (mapc #'chill symbol-names))))))
3246
3247       ;; Cold load.
3248       (dolist (file-name object-file-names)
3249         (write-line (namestring file-name))
3250         (cold-load file-name))
3251
3252       ;; Tidy up loose ends left by cold loading. ("Postpare from cold load?")
3253       (resolve-assembler-fixups)
3254       #!+(or x86 x86-64) (output-load-time-code-fixups)
3255       (foreign-symbols-to-core)
3256       (finish-symbols)
3257       (/show "back from FINISH-SYMBOLS")
3258       (finalize-load-time-value-noise)
3259
3260       ;; Tell the target Lisp how much stuff we've allocated.
3261       (cold-set 'sb!vm:*read-only-space-free-pointer*
3262                 (allocate-cold-descriptor *read-only*
3263                                           0
3264                                           sb!vm:even-fixnum-lowtag))
3265       (cold-set 'sb!vm:*static-space-free-pointer*
3266                 (allocate-cold-descriptor *static*
3267                                           0
3268                                           sb!vm:even-fixnum-lowtag))
3269       (/show "done setting free pointers")
3270
3271       ;; Write results to files.
3272       ;;
3273       ;; FIXME: I dislike this approach of redefining
3274       ;; *STANDARD-OUTPUT* instead of putting the new stream in a
3275       ;; lexical variable, and it's annoying to have WRITE-MAP (to
3276       ;; *STANDARD-OUTPUT*) not be parallel to WRITE-INITIAL-CORE-FILE
3277       ;; (to a stream explicitly passed as an argument).
3278       (macrolet ((out-to (name &body body)
3279                    `(let ((fn (format nil "~A/~A.h" c-header-dir-name ,name)))
3280                      (ensure-directories-exist fn)
3281                      (with-open-file (*standard-output* fn
3282                                       :if-exists :supersede :direction :output)
3283                        (write-boilerplate)
3284                        (let ((n (c-name (string-upcase ,name))))
3285                          (format
3286                           t
3287                           "#ifndef SBCL_GENESIS_~A~%#define SBCL_GENESIS_~A 1~%"
3288                           n n))
3289                        ,@body
3290                        (format t
3291                         "#endif /* SBCL_GENESIS_~A */~%"
3292                         (string-upcase ,name))))))
3293         (when map-file-name
3294           (with-open-file (*standard-output* map-file-name
3295                                              :direction :output
3296                                              :if-exists :supersede)
3297             (write-map)))
3298         (out-to "config" (write-config-h))
3299         (out-to "constants" (write-constants-h))
3300         (let ((structs (sort (copy-list sb!vm:*primitive-objects*) #'string<
3301                              :key (lambda (obj)
3302                                     (symbol-name
3303                                      (sb!vm:primitive-object-name obj))))))
3304           (dolist (obj structs)
3305             (out-to
3306              (string-downcase (string (sb!vm:primitive-object-name obj)))
3307              (write-primitive-object obj)))
3308           (out-to "primitive-objects"
3309                   (dolist (obj structs)
3310                     (format t "~&#include \"~A.h\"~%"
3311                             (string-downcase
3312                              (string (sb!vm:primitive-object-name obj)))))))
3313         (dolist (class '(hash-table
3314                          layout
3315                          sb!c::compiled-debug-info
3316                          sb!c::compiled-debug-fun
3317                          sb!xc:package))
3318           (out-to
3319            (string-downcase (string class))
3320            (write-structure-object
3321             (sb!kernel:layout-info (sb!kernel:find-layout class)))))
3322         (out-to "static-symbols" (write-static-symbols))
3323
3324         (let ((fn (format nil "~A/Makefile.features" c-header-dir-name)))
3325           (ensure-directories-exist fn)
3326           (with-open-file (*standard-output* fn :if-exists :supersede
3327                                              :direction :output)
3328             (write-makefile-features)))
3329
3330         (when core-file-name
3331           (write-initial-core-file core-file-name))))))
3332
3333