Previously missed whitespace canonicalizations
[sbcl.git] / src / code / cold-init.lisp
blobc67b07aeb99534dd96fd68ae53853f55462c0a7f
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 ;; DEF!METHOD need no longer be accessible,
38 ;; but *DELAYED-DEF!METHOD-ARGS* remains,
39 ;; due to a reference from pcl/methods.lisp.
40 ;; It would be nice to fix that.
41 '(def!method
42 sb!c::sb!pcl sb!c::sb!impl sb!c::sb!kernel
43 sb!c::sb!c sb!c::sb!int))))))
44 ;; A structure constructor name, in particular !MAKE-SAETP,
45 ;; can't be uninterned if referenced by a defstruct-description.
46 ;; So loop over all structure classoids and clobber any
47 ;; symbol that should be uninternable.
48 (maphash (lambda (classoid layout)
49 (when (structure-classoid-p classoid)
50 (let ((dd (layout-info layout)))
51 (setf (dd-constructors dd)
52 (delete-if (lambda (x)
53 (and (consp x) (uninternable-p (car x))))
54 (dd-constructors dd))))))
55 (classoid-subclasses (find-classoid t)))
56 ;; Todo: perform one pass, then a full GC, then a final pass to confirm
57 ;; it worked. It shoud be an error if any uninternable symbols remain,
58 ;; but at present there are about 13 other "!" symbols with referers.
59 (with-package-iterator (iter (list-all-packages) :internal :external)
60 (loop (multiple-value-bind (winp symbol accessibility package) (iter)
61 (declare (ignore accessibility))
62 (unless winp
63 (return))
64 (when (uninternable-p symbol)
65 ;; Uninternable symbols which are referenced by other stuff
66 ;; can't disappear from the image, but we don't need to preserve
67 ;; their functions, so FMAKUNBOUND them. This doesn't have
68 ;; the intended effect if the function shares a code-component
69 ;; with non-cold-init lambdas. Though the cold-init function is
70 ;; never called post-build, it is not discarded. Also, I suspect
71 ;; that the following loop should print nothing, but it does:
73 (sb-vm::map-allocated-objects
74 (lambda (obj type size)
75 (declare (ignore size))
76 (when (= type sb-vm:code-header-widetag)
77 (let ((name (sb-c::debug-info-name
78 (sb-kernel:%code-debug-info obj))))
79 (when (and (stringp name) (search "COLD-INIT-FORMS" name))
80 (print obj)))))
81 :dynamic)
83 (fmakunbound symbol)
84 (unintern symbol package)))))))
86 ;;;; putting ourselves out of our misery when things become too much to bear
88 (declaim (ftype (function (simple-string) nil) !cold-lose))
89 (defun !cold-lose (msg)
90 (%primitive print msg)
91 (%primitive print "too early in cold init to recover from errors")
92 (%halt))
94 ;;; last-ditch error reporting for things which should never happen
95 ;;; and which, if they do happen, are sufficiently likely to torpedo
96 ;;; the normal error-handling system that we want to bypass it
97 (declaim (ftype (function (simple-string) nil) critically-unreachable))
98 (defun critically-unreachable (where)
99 (%primitive print "internal error: Control should never reach here, i.e.")
100 (%primitive print where)
101 (%halt))
103 ;;;; !COLD-INIT
105 ;;; a list of toplevel things set by GENESIS
106 (defvar *!cold-toplevels*) ; except for DEFUNs and SETF macros
107 (defvar *!cold-setf-macros*) ; just SETF macros
108 (defvar *!cold-defconstants*) ; just DEFCONSTANT-EQXs
109 (defvar *!cold-defuns*) ; just DEFUNs
111 ;;; a SIMPLE-VECTOR set by GENESIS
112 (defvar *!load-time-values*)
114 (eval-when (:compile-toplevel :execute)
115 ;; FIXME: Perhaps we should make SHOW-AND-CALL-AND-FMAKUNBOUND, too,
116 ;; and use it for most of the cold-init functions. (Just be careful
117 ;; not to use it for the COLD-INIT-OR-REINIT functions.)
118 (sb!xc:defmacro show-and-call (name)
119 `(progn
120 (/primitive-print ,(symbol-name name))
121 (,name))))
123 (defun !encapsulate-stuff-for-cold-init (&aux names)
124 (flet ((encapsulate-1 (name handler)
125 (encapsulate name '!cold-init handler)
126 (push name names)))
127 (encapsulate-1 '%failed-aver
128 (lambda (f expr)
129 ;; output the message before signaling error,
130 ;; as it may be this is too early in the cold init.
131 (fresh-line)
132 (write-line "failed AVER:")
133 (write expr)
134 (terpri)
135 (funcall f expr)))
137 (encapsulate-1
138 'find-package
139 (lambda (f designator)
140 (cond ((packagep designator) designator)
141 (t (funcall f (let ((s (string designator)))
142 (if (eql (mismatch s "SB!") 3)
143 (concatenate 'string "SB-" (subseq s 3))
144 s)))))))
146 ;; %DEFSETF ',FN warns when #'(SETF fn) also has a function binding.
147 ;; There's no way to suppress that warning in cold-init.
148 ;; HANDLER-BIND can't be used, since condition classoids don't exist yet.
149 (encapsulate-1
150 '%defsetf
151 (lambda (f &rest args)
152 (encapsulate 'style-warn '!cold-init ; Make STYLE-WARN into a no-op.
153 (lambda (&rest l) (declare (ignore l))))
154 (apply f args)
155 (unencapsulate 'style-warn '!cold-init)))) ; Now fatal again.
156 names)
158 ;;; called when a cold system starts up
159 (defun !cold-init ()
160 #!+sb-doc "Give the world a shove and hope it spins."
162 #!+sb-show
163 (sb!int::cannot-/show "Test of CANNOT-/SHOW [don't worry - this is expected]")
164 (/show0 "entering !COLD-INIT")
165 (setq *readtable* (make-readtable)
166 *previous-case* nil
167 *previous-readtable-case* nil
168 *print-length* 6 *print-level* 3)
169 #!-win32
170 (write-string "COLD-INIT... "
171 (setq *error-output* (!make-cold-stderr-stream)
172 *standard-output* *error-output*
173 *trace-output* *error-output*))
175 ;; Assert that FBOUNDP doesn't choke when its answer is NIL.
176 ;; It was fine if T because in that case the legality of the arg is certain.
177 ;; And be extra paranoid - ensure that it really gets called.
178 (locally (declare (notinline fboundp)) (fboundp '(setf !zzzzzz)))
180 ;; Putting data in a synchronized hashtable (*PACKAGE-NAMES*)
181 ;; requires that the main thread be properly initialized.
182 (show-and-call thread-init-or-reinit)
183 ;; Printing of symbols requires that packages be filled in, because
184 ;; OUTPUT-SYMBOL calls FIND-SYMBOL to determine accessibility.
185 (show-and-call !package-cold-init)
186 ;; Fill in the printer's character attribute tables now.
187 ;; If Genesis could write constant arrays into a target core,
188 ;; that would be nice, and would tidy up some other things too.
189 (show-and-call !printer-cold-init)
190 #!-win32
191 (progn (prin1 `(package = ,(package-name *package*)))
192 (terpri))
194 ;; *RAW-SLOT-DATA* is essentially a compile-time constant
195 ;; but isn't dumpable as such because it has functions in it.
196 (show-and-call sb!kernel::!raw-slot-data-init)
198 ;; Anyone might call RANDOM to initialize a hash value or something;
199 ;; and there's nothing which needs to be initialized in order for
200 ;; this to be initialized, so we initialize it right away.
201 (show-and-call !random-cold-init)
203 ;; Must be done before any non-opencoded array references are made.
204 (show-and-call !hairy-data-vector-reffer-init)
206 (show-and-call !character-database-cold-init)
207 (show-and-call !character-name-database-cold-init)
208 (show-and-call sb!unicode::!unicode-properties-cold-init)
210 ;; All sorts of things need INFO and/or (SETF INFO).
211 (/show0 "about to SHOW-AND-CALL !GLOBALDB-COLD-INIT")
212 (show-and-call !globaldb-cold-init)
214 ;; Various toplevel forms call MAKE-ARRAY, which calls SUBTYPEP, so
215 ;; the basic type machinery needs to be initialized before toplevel
216 ;; forms run.
217 (show-and-call !type-class-cold-init)
218 (show-and-call sb!kernel::!primordial-type-cold-init)
219 (show-and-call !world-lock-cold-init)
220 (show-and-call !classes-cold-init)
221 (show-and-call !early-type-cold-init)
222 (show-and-call !late-type-cold-init)
223 (show-and-call !alien-type-cold-init)
224 (show-and-call !target-type-cold-init)
225 ;; FIXME: It would be tidy to make sure that that these cold init
226 ;; functions are called in the same relative order as the toplevel
227 ;; forms of the corresponding source files.
229 (show-and-call !policy-cold-init-or-resanify)
230 (/show0 "back from !POLICY-COLD-INIT-OR-RESANIFY")
232 ;; Must be done before toplevel forms are invoked
233 ;; because a toplevel defstruct will need to add itself
234 ;; to the subclasses of STRUCTURE-OBJECT.
235 (show-and-call sb!kernel::!set-up-structure-object-class)
237 (dolist (x *!cold-defconstants*)
238 (destructuring-bind (name source-loc &optional docstring) x
239 (setf (info :variable :kind name) :constant)
240 (when source-loc (setf (info :source-location :constant name) source-loc))
241 (when docstring (setf (fdocumentation name 'variable) docstring))))
242 (dolist (x *!cold-defuns*)
243 (destructuring-bind (name . inline-expansion) x
244 (!%quietly-defun name inline-expansion)))
246 ;; KLUDGE: Why are fixups mixed up with toplevel forms? Couldn't
247 ;; fixups be done separately? Wouldn't that be clearer and better?
248 ;; -- WHN 19991204
249 (/show0 "doing cold toplevel forms and fixups")
250 #!-win32
251 (progn (write `("Length(TLFs)= " ,(length *!cold-toplevels*)))
252 (terpri))
254 (loop with wrapped-functions = (!encapsulate-stuff-for-cold-init)
255 for index-in-cold-toplevels from 0
256 for toplevel-thing in (prog1 *!cold-toplevels*
257 (makunbound '*!cold-toplevels*))
259 #!+sb-show
260 (when (zerop (mod index-in-cold-toplevels 1024))
261 (/show0 "INDEX-IN-COLD-TOPLEVELS=..")
262 (/hexstr index-in-cold-toplevels))
263 (typecase toplevel-thing
264 (function
265 (funcall toplevel-thing))
266 ((cons (eql :load-time-value))
267 (setf (svref *!load-time-values* (third toplevel-thing))
268 (funcall (second toplevel-thing))))
269 ((cons (eql :load-time-value-fixup))
270 (setf (sap-ref-word (int-sap (get-lisp-obj-address (second toplevel-thing)))
271 (third toplevel-thing))
272 (get-lisp-obj-address
273 (svref *!load-time-values* (fourth toplevel-thing)))))
274 ((cons (eql defstruct))
275 (apply 'sb!kernel::%defstruct (cdr toplevel-thing)))
277 (!cold-lose "bogus operation in *!COLD-TOPLEVELS*")))
278 finally (dolist (f wrapped-functions) (unencapsulate f '!cold-init)))
279 (/show0 "done with loop over cold toplevel forms and fixups")
281 (show-and-call time-reinit)
283 ;; Set sane values again, so that the user sees sane values instead
284 ;; of whatever is left over from the last DECLAIM/PROCLAIM.
285 (show-and-call !policy-cold-init-or-resanify)
287 ;; Only do this after toplevel forms have run, 'cause that's where
288 ;; DEFTYPEs are.
289 (setf *type-system-initialized* t)
291 ;; now that the type system is definitely initialized, fixup UNKNOWN
292 ;; types that have crept in.
293 (show-and-call !fixup-type-cold-init)
294 ;; run the PROCLAIMs.
295 (show-and-call !late-proclaim-cold-init)
297 (show-and-call os-cold-init-or-reinit)
298 (show-and-call !pathname-cold-init)
299 (show-and-call !debug-info-cold-init)
301 (show-and-call stream-cold-init-or-reset)
302 (show-and-call !loader-cold-init)
303 (show-and-call !foreign-cold-init)
304 #!-(and win32 (not sb-thread))
305 (show-and-call signal-cold-init-or-reinit)
307 (show-and-call float-cold-init-or-reinit)
309 (show-and-call !class-finalize)
311 ;; The reader and printer are initialized very late, so that they
312 ;; can do hairy things like invoking the compiler as part of their
313 ;; initialization.
314 (let ((*readtable* (make-readtable)))
315 (show-and-call !reader-cold-init)
316 (show-and-call !sharpm-cold-init)
317 (show-and-call !backq-cold-init)
318 ;; The *STANDARD-READTABLE* is assigned at last because the above
319 ;; functions would operate on the standard readtable otherwise---
320 ;; which would result in an error.
321 (setf *standard-readtable* *readtable*))
322 (setf *readtable* (copy-readtable *standard-readtable*))
323 (setf sb!debug:*debug-readtable* (copy-readtable *standard-readtable*))
324 (sb!pretty:!pprint-cold-init)
325 (setq *print-level* nil *print-length* nil) ; restore defaults
327 ;; the ANSI-specified initial value of *PACKAGE*
328 (setf *package* (find-package "COMMON-LISP-USER"))
330 ;; Enable normal (post-cold-init) behavior of INFINITE-ERROR-PROTECT.
331 (setf sb!kernel::*maximum-error-depth* 10)
332 (/show0 "enabling internal errors")
333 (setf (extern-alien "internal_errors_enabled" int) 1)
336 ; hppa heap is segmented, lisp and c uses a stub to call eachother
337 #!+hpux (%primitive sb!vm::setup-return-from-lisp-stub)
338 ;; The system is finally ready for GC.
339 (/show0 "enabling GC")
340 (setq *gc-inhibit* nil)
341 (/show0 "doing first GC")
342 (gc :full t)
343 (/show0 "back from first GC")
345 ;; The show is on.
346 (terpri)
347 (/show0 "going into toplevel loop")
348 (handling-end-of-the-world
349 (toplevel-init)
350 (critically-unreachable "after TOPLEVEL-INIT")))
352 (define-deprecated-function :early "1.0.56.55" quit (exit sb!thread:abort-thread)
353 (&key recklessly-p (unix-status 0))
354 (if (or recklessly-p (sb!thread:main-thread-p))
355 (exit :code unix-status :abort recklessly-p)
356 (sb!thread:abort-thread))
357 (critically-unreachable "after trying to die in QUIT"))
359 (declaim (ftype (sfunction (&key (:code (or null exit-code))
360 (:timeout (or null real))
361 (:abort t))
362 nil)
363 exit))
364 (defun exit (&key code abort (timeout *exit-timeout*))
365 #!+sb-doc
366 "Terminates the process, causing SBCL to exit with CODE. CODE
367 defaults to 0 when ABORT is false, and 1 when it is true.
369 When ABORT is false (the default), current thread is first unwound,
370 *EXIT-HOOKS* are run, other threads are terminated, and standard
371 output streams are flushed before SBCL calls exit(3) -- at which point
372 atexit(3) functions will run. If multiple threads call EXIT with ABORT
373 being false, the first one to call it will complete the protocol.
375 When ABORT is true, SBCL exits immediately by calling _exit(2) without
376 unwinding stack, or calling exit hooks. Note that _exit(2) does not
377 call atexit(3) functions unlike exit(3).
379 Recursive calls to EXIT cause EXIT to behave as it ABORT was true.
381 TIMEOUT controls waiting for other threads to terminate when ABORT is
382 NIL. Once current thread has been unwound and *EXIT-HOOKS* have been
383 run, spawning new threads is prevented and all other threads are
384 terminated by calling TERMINATE-THREAD on them. The system then waits
385 for them to finish using JOIN-THREAD, waiting at most a total TIMEOUT
386 seconds for all threads to join. Those threads that do not finish
387 in time are simply ignored while the exit protocol continues. TIMEOUT
388 defaults to *EXIT-TIMEOUT*, which in turn defaults to 60. TIMEOUT NIL
389 means to wait indefinitely.
391 Note that TIMEOUT applies only to JOIN-THREAD, not *EXIT-HOOKS*. Since
392 TERMINATE-THREAD is asynchronous, getting multithreaded application
393 termination with complex cleanups right using it can be tricky. To
394 perform an orderly synchronous shutdown use an exit hook instead of
395 relying on implicit thread termination.
397 Consequences are unspecified if serious conditions occur during EXIT
398 excepting errors from *EXIT-HOOKS*, which cause warnings and stop
399 execution of the hook that signaled, but otherwise allow the exit
400 process to continue normally."
401 (if (or abort *exit-in-process*)
402 (os-exit (or code 1) :abort t)
403 (let ((code (or code 0)))
404 (with-deadline (:seconds nil :override t)
405 (sb!thread:grab-mutex *exit-lock*))
406 (setf *exit-in-process* code
407 *exit-timeout* timeout)
408 (throw '%end-of-the-world t)))
409 (critically-unreachable "After trying to die in EXIT."))
411 ;;;; initialization functions
413 (defun thread-init-or-reinit ()
414 (sb!thread::init-initial-thread)
415 (sb!thread::init-job-control)
416 (sb!thread::get-foreground))
418 (defun reinit ()
419 #!+win32
420 (setf sb!win32::*ansi-codepage* nil)
421 (setf *default-external-format* nil)
422 (setf sb!alien::*default-c-string-external-format* nil)
423 ;; WITHOUT-GCING implies WITHOUT-INTERRUPTS.
424 (without-gcing
425 ;; Initialize streams first, so that any errors can be printed later
426 (stream-reinit t)
427 (os-cold-init-or-reinit)
428 (thread-init-or-reinit)
429 #!-(and win32 (not sb-thread))
430 (signal-cold-init-or-reinit)
431 (setf (extern-alien "internal_errors_enabled" int) 1)
432 (float-cold-init-or-reinit))
433 (gc-reinit)
434 (foreign-reinit)
435 (time-reinit)
436 ;; If the debugger was disabled in the saved core, we need to
437 ;; re-disable ldb again.
438 (when (eq *invoke-debugger-hook* 'sb!debug::debugger-disabled-hook)
439 (sb!debug::disable-debugger))
440 (call-hooks "initialization" *init-hooks*))
442 ;;;; some support for any hapless wretches who end up debugging cold
443 ;;;; init code
445 ;;; Decode THING into hexadecimal notation using only machinery
446 ;;; available early in cold init.
447 #!+sb-show
448 (defun hexstr (thing)
449 (/noshow0 "entering HEXSTR")
450 (let* ((addr (get-lisp-obj-address thing))
451 (nchars (* sb!vm:n-word-bytes 2))
452 (str (make-string (+ nchars 2) :element-type 'base-char)))
453 (/noshow0 "ADDR and STR calculated")
454 (setf (char str 0) #\0
455 (char str 1) #\x)
456 (/noshow0 "CHARs 0 and 1 set")
457 (dotimes (i nchars)
458 (/noshow0 "at head of DOTIMES loop")
459 (let* ((nibble (ldb (byte 4 0) addr))
460 (chr (char "0123456789abcdef" nibble)))
461 (declare (type (unsigned-byte 4) nibble)
462 (base-char chr))
463 (/noshow0 "NIBBLE and CHR calculated")
464 (setf (char str (- (1+ nchars) i)) chr
465 addr (ash addr -4))))
466 str))
468 ;; But: you almost never need this. Just use WRITE in all its glory.
469 #!+sb-show
470 (defun cold-print (x)
471 (labels ((%cold-print (obj depthoid)
472 (if (> depthoid 4)
473 (%primitive print "...")
474 (typecase obj
475 (simple-string
476 (%primitive print obj))
477 (symbol
478 (%primitive print (symbol-name obj)))
479 (cons
480 (%primitive print "cons:")
481 (let ((d (1+ depthoid)))
482 (%cold-print (car obj) d)
483 (%cold-print (cdr obj) d)))
485 (%primitive print (hexstr obj)))))))
486 (%cold-print x 0))
487 (values))
489 (in-package "SB!INT")
490 (defun unintern-init-only-stuff ()
491 (let ((this-package (find-package "SB-INT")))
492 ;; For some reason uninterning these:
493 ;; DEF!TYPE DEF!CONSTANT DEF!MACRO DEF!STRUCT
494 ;; does not work, they stick around as uninterned symbols.
495 ;; Some other macros must expand into them. Ugh.
496 (dolist (s '(defenum defmacro-mundanely defun-cached
497 with-globaldb-name
499 #!+sb-show ()
500 #!-sb-show (/hexstr /nohexstr /noshow /noshow0 /noxhow
501 /primitive-print /show /show0 /xhow)))
502 (unintern s this-package))))