Put symbol immobility (#+immobile-symbols) to some good.
[sbcl.git] / src / code / cold-init.lisp
blob0b1c8804d78f5bfcddc8a49abaf364d546b2a4d1
1 ;;;; cold initialization stuff, plus some other miscellaneous stuff
2 ;;;; that we don't have any better place for
4 ;;;; This software is part of the SBCL system. See the README file for
5 ;;;; more information.
6 ;;;;
7 ;;;; This software is derived from the CMU CL system, which was
8 ;;;; written at Carnegie Mellon University and released into the
9 ;;;; public domain. The software is in the public domain and is
10 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
11 ;;;; files for more information.
13 (in-package "SB!IMPL")
15 ;;;; burning our ships behind us
17 ;;; There's a fair amount of machinery which is needed only at cold
18 ;;; init time, and should be discarded before freezing the final
19 ;;; system. We discard it by uninterning the associated symbols.
20 ;;; Rather than using a special table of symbols to be uninterned,
21 ;;; which might be tedious to maintain, instead we use a hack:
22 ;;; anything whose name matches a magic character pattern is
23 ;;; uninterned.
24 ;;; Additionally, you can specify an arbitrary way to destroy
25 ;;; random bootstrap stuff on per-package basis.
26 (defun !unintern-init-only-stuff ()
27 (dolist (package (list-all-packages))
28 (awhen (find-symbol "UNINTERN-INIT-ONLY-STUFF" package)
29 (format t "~&Calling ~/sb-impl::print-symbol-with-prefix/~%" it)
30 (funcall it)
31 (unintern it package)))
32 (flet ((uninternable-p (symbol)
33 (let ((name (symbol-name symbol)))
34 (or (and (>= (length name) 1) (char= (char name 0) #\!))
35 (and (>= (length name) 2) (string= name "*!" :end1 2))
36 (memq symbol
37 '(sb!c::sb!pcl sb!c::sb!impl sb!c::sb!kernel
38 sb!c::sb!c sb!c::sb!int))))))
39 ;; A structure constructor name, in particular !MAKE-SAETP,
40 ;; can't be uninterned if referenced by a defstruct-description.
41 ;; So loop over all structure classoids and clobber any
42 ;; symbol that should be uninternable.
43 (maphash (lambda (classoid layout)
44 (when (structure-classoid-p classoid)
45 (let ((dd (layout-info layout)))
46 (setf (dd-constructors dd)
47 (delete-if (lambda (x)
48 (and (consp x) (uninternable-p (car x))))
49 (dd-constructors dd))))))
50 (classoid-subclasses (find-classoid t)))
51 ;; Todo: perform one pass, then a full GC, then a final pass to confirm
52 ;; it worked. It shoud be an error if any uninternable symbols remain,
53 ;; but at present there are about 13 other "!" symbols with referers.
54 (with-package-iterator (iter (list-all-packages) :internal :external)
55 (loop (multiple-value-bind (winp symbol accessibility package) (iter)
56 (declare (ignore accessibility))
57 (unless winp
58 (return))
59 (when (uninternable-p symbol)
60 ;; Uninternable symbols which are referenced by other stuff
61 ;; can't disappear from the image, but we don't need to preserve
62 ;; their functions, so FMAKUNBOUND them. This doesn't have
63 ;; the intended effect if the function shares a code-component
64 ;; with non-cold-init lambdas. Though the cold-init function is
65 ;; never called post-build, it is not discarded. Also, I suspect
66 ;; that the following loop should print nothing, but it does:
68 (sb-vm::map-allocated-objects
69 (lambda (obj type size)
70 (declare (ignore size))
71 (when (= type sb-vm:code-header-widetag)
72 (let ((name (sb-c::debug-info-name
73 (sb-kernel:%code-debug-info obj))))
74 (when (and (stringp name) (search "COLD-INIT-FORMS" name))
75 (print obj)))))
76 :dynamic)
78 (fmakunbound symbol)
79 (unintern symbol package)))))))
81 ;;;; putting ourselves out of our misery when things become too much to bear
83 (declaim (ftype (function (simple-string) nil) !cold-lose))
84 (defun !cold-lose (msg)
85 (%primitive print msg)
86 (%primitive print "too early in cold init to recover from errors")
87 (%halt))
89 ;;; last-ditch error reporting for things which should never happen
90 ;;; and which, if they do happen, are sufficiently likely to torpedo
91 ;;; the normal error-handling system that we want to bypass it
92 (declaim (ftype (function (simple-string) nil) critically-unreachable))
93 (defun critically-unreachable (where)
94 (%primitive print "internal error: Control should never reach here, i.e.")
95 (%primitive print where)
96 (%halt))
98 ;;;; !COLD-INIT
100 ;;; a list of toplevel things set by GENESIS
101 (defvar *!cold-toplevels*) ; except for DEFUNs and SETF macros
102 (defvar *!cold-setf-macros*) ; just SETF macros
103 (defvar *!cold-defconstants*) ; just DEFCONSTANT-EQXs
104 (defvar *!cold-defuns*) ; just DEFUNs
106 ;;; a SIMPLE-VECTOR set by GENESIS
107 (defvar *!load-time-values*)
109 (eval-when (:compile-toplevel :execute)
110 ;; FIXME: Perhaps we should make SHOW-AND-CALL-AND-FMAKUNBOUND, too,
111 ;; and use it for most of the cold-init functions. (Just be careful
112 ;; not to use it for the COLD-INIT-OR-REINIT functions.)
113 (sb!xc:defmacro show-and-call (name)
114 `(progn
115 (/primitive-print ,(symbol-name name))
116 (,name))))
118 (defun !encapsulate-stuff-for-cold-init (&aux names)
119 (flet ((encapsulate-1 (name handler)
120 (encapsulate name '!cold-init handler)
121 (push name names)))
122 (encapsulate-1 '%failed-aver
123 (lambda (f expr)
124 ;; output the message before signaling error,
125 ;; as it may be this is too early in the cold init.
126 (fresh-line)
127 (write-line "failed AVER:")
128 (write expr)
129 (terpri)
130 (funcall f expr)))
132 (encapsulate-1
133 'find-package
134 (lambda (f designator)
135 (cond ((packagep designator) designator)
136 (t (funcall f (let ((s (string designator)))
137 (if (eql (mismatch s "SB!") 3)
138 (concatenate 'string "SB-" (subseq s 3))
139 s))))))))
140 names)
142 (defmacro !with-init-wrappers (&rest forms)
143 `(let ((wrapped-functions (!encapsulate-stuff-for-cold-init)))
144 ,@forms
145 (dolist (f wrapped-functions) (unencapsulate f '!cold-init))))
147 ;;; called when a cold system starts up
148 (defun !cold-init (&aux real-choose-symbol-out-fun)
149 #!+sb-doc "Give the world a shove and hope it spins."
151 #!+sb-show
152 (sb!int::cannot-/show "Test of CANNOT-/SHOW [don't worry - this is expected]")
153 (/show0 "entering !COLD-INIT")
154 (setq *readtable* (make-readtable)
155 *print-length* 6 *print-level* 3)
156 (setq *error-output* (!make-cold-stderr-stream)
157 *standard-output* *error-output*
158 *trace-output* *error-output*)
159 (write-string "COLD-INIT... ")
161 ;; Assert that FBOUNDP doesn't choke when its answer is NIL.
162 ;; It was fine if T because in that case the legality of the arg is certain.
163 ;; And be extra paranoid - ensure that it really gets called.
164 (locally (declare (notinline fboundp)) (fboundp '(setf !zzzzzz)))
166 ;; Putting data in a synchronized hashtable (*PACKAGE-NAMES*)
167 ;; requires that the main thread be properly initialized.
168 (show-and-call thread-init-or-reinit)
169 ;; Printing of symbols requires that packages be filled in, because
170 ;; OUTPUT-SYMBOL calls FIND-SYMBOL to determine accessibility.
171 (show-and-call !package-cold-init)
172 ;; Fill in the printer's character attribute tables now.
173 ;; If Genesis could write constant arrays into a target core,
174 ;; that would be nice, and would tidy up some other things too.
175 (show-and-call !printer-cold-init)
176 ;; Because L-T-V forms have not executed, CHOOSE-SYMBOL-OUT-FUN doesn't work.
177 (setf real-choose-symbol-out-fun #'choose-symbol-out-fun)
178 (setf (symbol-function 'choose-symbol-out-fun)
179 (lambda (&rest args) (declare (ignore args)) #'output-preserve-symbol))
181 ;; *RAW-SLOT-DATA* is essentially a compile-time constant
182 ;; but isn't dumpable as such because it has functions in it.
183 (show-and-call sb!kernel::!raw-slot-data-init)
185 ;; Anyone might call RANDOM to initialize a hash value or something;
186 ;; and there's nothing which needs to be initialized in order for
187 ;; this to be initialized, so we initialize it right away.
188 (show-and-call !random-cold-init)
190 ;; Must be done before any non-opencoded array references are made.
191 (show-and-call !hairy-data-vector-reffer-init)
193 (show-and-call !character-database-cold-init)
194 (show-and-call !character-name-database-cold-init)
195 (show-and-call sb!unicode::!unicode-properties-cold-init)
197 ;; All sorts of things need INFO and/or (SETF INFO).
198 (/show0 "about to SHOW-AND-CALL !GLOBALDB-COLD-INIT")
199 (show-and-call !globaldb-cold-init)
201 ;; Various toplevel forms call MAKE-ARRAY, which calls SUBTYPEP, so
202 ;; the basic type machinery needs to be initialized before toplevel
203 ;; forms run.
204 (show-and-call !type-class-cold-init)
205 (!with-init-wrappers (show-and-call sb!kernel::!primordial-type-cold-init))
206 (show-and-call !world-lock-cold-init)
207 (show-and-call !classes-cold-init)
208 (show-and-call !early-type-cold-init)
209 (show-and-call !late-type-cold-init)
210 (show-and-call !alien-type-cold-init)
211 (show-and-call !target-type-cold-init)
212 ;; FIXME: It would be tidy to make sure that that these cold init
213 ;; functions are called in the same relative order as the toplevel
214 ;; forms of the corresponding source files.
216 (show-and-call !policy-cold-init-or-resanify)
217 (/show0 "back from !POLICY-COLD-INIT-OR-RESANIFY")
219 ;; Must be done before toplevel forms are invoked
220 ;; because a toplevel defstruct will need to add itself
221 ;; to the subclasses of STRUCTURE-OBJECT.
222 (show-and-call sb!kernel::!set-up-structure-object-class)
224 (dolist (x *!cold-defconstants*)
225 (destructuring-bind (name source-loc &optional docstring) x
226 (setf (info :variable :kind name) :constant)
227 (when source-loc (setf (info :source-location :constant name) source-loc))
228 (when docstring (setf (fdocumentation name 'variable) docstring))))
229 (!with-init-wrappers
230 (dolist (x *!cold-defuns*)
231 (destructuring-bind (name . inline-expansion) x
232 (%defun name (fdefinition name) nil inline-expansion))))
234 ;; KLUDGE: Why are fixups mixed up with toplevel forms? Couldn't
235 ;; fixups be done separately? Wouldn't that be clearer and better?
236 ;; -- WHN 19991204
237 (/show0 "doing cold toplevel forms and fixups")
238 (progn (write `("Length(TLFs)= " ,(length *!cold-toplevels*)))
239 (terpri))
241 (!with-init-wrappers
242 (loop for index-in-cold-toplevels from 0
243 for toplevel-thing in (prog1 *!cold-toplevels*
244 (makunbound '*!cold-toplevels*))
246 #!+sb-show
247 (when (zerop (mod index-in-cold-toplevels 1024))
248 (/show0 "INDEX-IN-COLD-TOPLEVELS=..")
249 (/hexstr index-in-cold-toplevels))
250 (typecase toplevel-thing
251 (function
252 (funcall toplevel-thing))
253 ((cons (eql :load-time-value))
254 (setf (svref *!load-time-values* (third toplevel-thing))
255 (funcall (second toplevel-thing))))
256 ((cons (eql :load-time-value-fixup))
257 (setf (sap-ref-word (int-sap (get-lisp-obj-address (second toplevel-thing)))
258 (third toplevel-thing))
259 (get-lisp-obj-address
260 (svref *!load-time-values* (fourth toplevel-thing)))))
261 ((cons (eql defstruct))
262 (apply 'sb!kernel::%defstruct (cdr toplevel-thing)))
264 (!cold-lose "bogus operation in *!COLD-TOPLEVELS*")))))
265 (/show0 "done with loop over cold toplevel forms and fixups")
267 ;; ASAP after the toplevel forms have executed,
268 ;; convert code fixup lists into vectors or packed integers.
269 #!+x86
270 (sb!vm::map-allocated-objects
271 (lambda (obj type size)
272 (declare (ignore size))
273 (when (= type sb!vm:code-header-widetag)
274 (let ((fixups (sb!vm::%code-fixups obj)))
275 (when (listp fixups)
276 (setf (sb!vm::%code-fixups obj)
277 (coerce (sort fixups #'<) '(simple-array sb!vm:word (*))))))))
278 :dynamic)
279 #!+x86-64
280 (sb!vm::map-allocated-objects
281 (lambda (obj type size)
282 (declare (ignore size))
283 (when (= type sb!vm:code-header-widetag)
284 (sb!vm::sanctify-for-execution obj)))
285 :all)
287 ;; Now that L-T-V forms have executed, the symbol output chooser works.
288 (setf (symbol-function 'choose-symbol-out-fun) real-choose-symbol-out-fun)
290 (show-and-call time-reinit)
292 ;; Set sane values again, so that the user sees sane values instead
293 ;; of whatever is left over from the last DECLAIM/PROCLAIM.
294 (show-and-call !policy-cold-init-or-resanify)
296 ;; Only do this after toplevel forms have run, 'cause that's where
297 ;; DEFTYPEs are.
298 (setf *type-system-initialized* t)
300 ;; now that the type system is definitely initialized, fixup UNKNOWN
301 ;; types that have crept in.
302 (show-and-call !fixup-type-cold-init)
303 ;; run the PROCLAIMs.
304 (show-and-call !late-proclaim-cold-init)
306 (show-and-call os-cold-init-or-reinit)
307 (show-and-call !pathname-cold-init)
308 (show-and-call !debug-info-cold-init)
310 (show-and-call stream-cold-init-or-reset)
311 (show-and-call !loader-cold-init)
312 (show-and-call !foreign-cold-init)
313 #!-(and win32 (not sb-thread))
314 (show-and-call signal-cold-init-or-reinit)
316 (show-and-call float-cold-init-or-reinit)
318 (show-and-call !class-finalize)
320 ;; Install closures as guards on some early PRINT-OBJECT methods so that
321 ;; THREAD and RESTART print nicely prior to the real methods being installed.
322 (dovector (method (cdr (assoc 'print-object sb!pcl::*!trivial-methods*)))
323 (unless (car method)
324 (let ((classoid (find-classoid (third method))))
325 (rplaca method
326 (lambda (x) (classoid-typep (layout-of x) classoid x))))))
328 ;; The reader and printer are initialized very late, so that they
329 ;; can do hairy things like invoking the compiler as part of their
330 ;; initialization.
331 (let ((*readtable* (make-readtable)))
332 (show-and-call !reader-cold-init)
333 (show-and-call !sharpm-cold-init)
334 (show-and-call !backq-cold-init)
335 ;; The *STANDARD-READTABLE* is assigned at last because the above
336 ;; functions would operate on the standard readtable otherwise---
337 ;; which would result in an error.
338 (setf *standard-readtable* *readtable*))
339 (setf *readtable* (copy-readtable *standard-readtable*))
340 (setf sb!debug:*debug-readtable* (copy-readtable *standard-readtable*))
341 (sb!pretty:!pprint-cold-init)
342 (setq *print-level* nil *print-length* nil) ; restore defaults
344 ;; the ANSI-specified initial value of *PACKAGE*
345 (setf *package* (find-package "COMMON-LISP-USER"))
347 ;; Enable normal (post-cold-init) behavior of INFINITE-ERROR-PROTECT.
348 (setf sb!kernel::*maximum-error-depth* 10)
349 (/show0 "enabling internal errors")
350 (setf (extern-alien "internal_errors_enabled" int) 1)
353 ; hppa heap is segmented, lisp and c uses a stub to call eachother
354 #!+hpux (%primitive sb!vm::setup-return-from-lisp-stub)
355 ;; The system is finally ready for GC.
356 (/show0 "enabling GC")
357 (setq *gc-inhibit* nil)
358 (/show0 "doing first GC")
359 (gc :full t)
360 (/show0 "back from first GC")
362 ;; The show is on.
363 (terpri)
364 (/show0 "going into toplevel loop")
365 (handling-end-of-the-world
366 (toplevel-init)
367 (critically-unreachable "after TOPLEVEL-INIT")))
369 (define-deprecated-function :early "1.0.56.55" quit (exit sb!thread:abort-thread)
370 (&key recklessly-p (unix-status 0))
371 (if (or recklessly-p (sb!thread:main-thread-p))
372 (exit :code unix-status :abort recklessly-p)
373 (sb!thread:abort-thread))
374 (critically-unreachable "after trying to die in QUIT"))
376 (declaim (ftype (sfunction (&key (:code (or null exit-code))
377 (:timeout (or null real))
378 (:abort t))
379 nil)
380 exit))
381 (defun exit (&key code abort (timeout *exit-timeout*))
382 #!+sb-doc
383 "Terminates the process, causing SBCL to exit with CODE. CODE
384 defaults to 0 when ABORT is false, and 1 when it is true.
386 When ABORT is false (the default), current thread is first unwound,
387 *EXIT-HOOKS* are run, other threads are terminated, and standard
388 output streams are flushed before SBCL calls exit(3) -- at which point
389 atexit(3) functions will run. If multiple threads call EXIT with ABORT
390 being false, the first one to call it will complete the protocol.
392 When ABORT is true, SBCL exits immediately by calling _exit(2) without
393 unwinding stack, or calling exit hooks. Note that _exit(2) does not
394 call atexit(3) functions unlike exit(3).
396 Recursive calls to EXIT cause EXIT to behave as it ABORT was true.
398 TIMEOUT controls waiting for other threads to terminate when ABORT is
399 NIL. Once current thread has been unwound and *EXIT-HOOKS* have been
400 run, spawning new threads is prevented and all other threads are
401 terminated by calling TERMINATE-THREAD on them. The system then waits
402 for them to finish using JOIN-THREAD, waiting at most a total TIMEOUT
403 seconds for all threads to join. Those threads that do not finish
404 in time are simply ignored while the exit protocol continues. TIMEOUT
405 defaults to *EXIT-TIMEOUT*, which in turn defaults to 60. TIMEOUT NIL
406 means to wait indefinitely.
408 Note that TIMEOUT applies only to JOIN-THREAD, not *EXIT-HOOKS*. Since
409 TERMINATE-THREAD is asynchronous, getting multithreaded application
410 termination with complex cleanups right using it can be tricky. To
411 perform an orderly synchronous shutdown use an exit hook instead of
412 relying on implicit thread termination.
414 Consequences are unspecified if serious conditions occur during EXIT
415 excepting errors from *EXIT-HOOKS*, which cause warnings and stop
416 execution of the hook that signaled, but otherwise allow the exit
417 process to continue normally."
418 (if (or abort *exit-in-process*)
419 (os-exit (or code 1) :abort t)
420 (let ((code (or code 0)))
421 (with-deadline (:seconds nil :override t)
422 (sb!thread:grab-mutex *exit-lock*))
423 (setf *exit-in-process* code
424 *exit-timeout* timeout)
425 (throw '%end-of-the-world t)))
426 (critically-unreachable "After trying to die in EXIT."))
428 ;;;; initialization functions
430 (defun thread-init-or-reinit ()
431 (sb!thread::init-initial-thread)
432 (sb!thread::init-job-control)
433 (sb!thread::get-foreground))
435 (defun reinit ()
436 #!+win32
437 (setf sb!win32::*ansi-codepage* nil)
438 (setf *default-external-format* nil)
439 (setf sb!alien::*default-c-string-external-format* nil)
440 ;; WITHOUT-GCING implies WITHOUT-INTERRUPTS.
441 (without-gcing
442 ;; Initialize streams first, so that any errors can be printed later
443 (stream-reinit t)
444 (os-cold-init-or-reinit)
445 (thread-init-or-reinit)
446 #!-(and win32 (not sb-thread))
447 (signal-cold-init-or-reinit)
448 (setf (extern-alien "internal_errors_enabled" int) 1)
449 (float-cold-init-or-reinit))
450 (gc-reinit)
451 (foreign-reinit)
452 (time-reinit)
453 ;; If the debugger was disabled in the saved core, we need to
454 ;; re-disable ldb again.
455 (when (eq *invoke-debugger-hook* 'sb!debug::debugger-disabled-hook)
456 (sb!debug::disable-debugger))
457 (call-hooks "initialization" *init-hooks*))
459 ;;;; some support for any hapless wretches who end up debugging cold
460 ;;;; init code
462 ;;; Decode THING into hexadecimal notation using only machinery
463 ;;; available early in cold init.
464 #!+sb-show
465 (defun hexstr (thing)
466 (/noshow0 "entering HEXSTR")
467 (let* ((addr (get-lisp-obj-address thing))
468 (nchars (* sb!vm:n-word-bytes 2))
469 (str (make-string (+ nchars 2) :element-type 'base-char)))
470 (/noshow0 "ADDR and STR calculated")
471 (setf (char str 0) #\0
472 (char str 1) #\x)
473 (/noshow0 "CHARs 0 and 1 set")
474 (dotimes (i nchars)
475 (/noshow0 "at head of DOTIMES loop")
476 (let* ((nibble (ldb (byte 4 0) addr))
477 (chr (char "0123456789abcdef" nibble)))
478 (declare (type (unsigned-byte 4) nibble)
479 (base-char chr))
480 (/noshow0 "NIBBLE and CHR calculated")
481 (setf (char str (- (1+ nchars) i)) chr
482 addr (ash addr -4))))
483 str))
485 ;; But: you almost never need this. Just use WRITE in all its glory.
486 #!+sb-show
487 (defun cold-print (x)
488 (labels ((%cold-print (obj depthoid)
489 (if (> depthoid 4)
490 (%primitive print "...")
491 (typecase obj
492 (simple-string
493 (%primitive print obj))
494 (symbol
495 (%primitive print (symbol-name obj)))
496 (cons
497 (%primitive print "cons:")
498 (let ((d (1+ depthoid)))
499 (%cold-print (car obj) d)
500 (%cold-print (cdr obj) d)))
502 (%primitive print (hexstr obj)))))))
503 (%cold-print x 0))
504 (values))
506 (in-package "SB!INT")
507 (defun unintern-init-only-stuff ()
508 (let ((this-package (find-package "SB-INT")))
509 ;; For some reason uninterning these:
510 ;; DEF!TYPE DEF!CONSTANT DEF!STRUCT
511 ;; does not work, they stick around as uninterned symbols.
512 ;; Some other macros must expand into them. Ugh.
513 (dolist (s '(defenum defun-cached with-globaldb-name
515 #!+sb-show ()
516 #!-sb-show (/hexstr /nohexstr /noshow /noshow0 /noxhow
517 /primitive-print /show /show0 /xhow)))
518 (unintern s this-package))))