Defer compililng external-formats until warm load
[sbcl.git] / src / code / cold-init.lisp
blobfd1d81fe282bd89931cee015f26d2aa432be1600
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 ;;;; putting ourselves out of our misery when things become too much to bear
17 (declaim (ftype (function (simple-string) nil) !cold-lose))
18 (defun !cold-lose (msg)
19 (%primitive print msg)
20 (%primitive print "too early in cold init to recover from errors")
21 (%halt))
23 ;;; last-ditch error reporting for things which should never happen
24 ;;; and which, if they do happen, are sufficiently likely to torpedo
25 ;;; the normal error-handling system that we want to bypass it
26 (declaim (ftype (function (simple-string) nil) critically-unreachable))
27 (defun critically-unreachable (where)
28 (%primitive print "internal error: Control should never reach here, i.e.")
29 (%primitive print where)
30 (%halt))
32 ;;;; !COLD-INIT
34 ;;; a list of toplevel things set by GENESIS
35 (defvar *!cold-toplevels*) ; except for DEFUNs and SETF macros
36 (defvar *!cold-setf-macros*) ; just SETF macros
37 (defvar *!cold-defconstants*) ; just DEFCONSTANT-EQXs
38 (defvar *!cold-defuns*) ; just DEFUNs
40 ;;; a SIMPLE-VECTOR set by GENESIS
41 (defvar *!load-time-values*)
43 (eval-when (:compile-toplevel :execute)
44 ;; FIXME: Perhaps we should make SHOW-AND-CALL-AND-FMAKUNBOUND, too,
45 ;; and use it for most of the cold-init functions. (Just be careful
46 ;; not to use it for the COLD-INIT-OR-REINIT functions.)
47 (sb!xc:defmacro show-and-call (name)
48 `(progn
49 (/primitive-print ,(symbol-name name))
50 (,name))))
52 (defun !encapsulate-stuff-for-cold-init (&aux names)
53 (flet ((encapsulate-1 (name handler)
54 (encapsulate name '!cold-init handler)
55 (push name names)))
56 (encapsulate-1 '%failed-aver
57 (lambda (f expr)
58 ;; output the message before signaling error,
59 ;; as it may be this is too early in the cold init.
60 (fresh-line)
61 (write-line "failed AVER:")
62 (write expr)
63 (terpri)
64 (funcall f expr)))
66 (encapsulate-1
67 'find-package
68 (lambda (f designator)
69 (cond ((packagep designator) designator)
70 (t (funcall f (let ((s (string designator)))
71 (if (eql (mismatch s "SB!") 3)
72 (concatenate 'string "SB-" (subseq s 3))
73 s))))))))
74 names)
76 (defmacro !with-init-wrappers (&rest forms)
77 `(let ((wrapped-functions (!encapsulate-stuff-for-cold-init)))
78 ,@forms
79 (dolist (f wrapped-functions) (unencapsulate f '!cold-init))))
81 ;;; called when a cold system starts up
82 (defun !cold-init (&aux real-choose-symbol-out-fun)
83 "Give the world a shove and hope it spins."
85 #!+sb-show
86 (sb!int::cannot-/show "Test of CANNOT-/SHOW [don't worry - this is expected]")
87 (/show0 "entering !COLD-INIT")
88 (setq *readtable* (make-readtable)
89 *print-length* 6 *print-level* 3)
90 (setq *error-output* (!make-cold-stderr-stream)
91 *standard-output* *error-output*
92 *trace-output* *error-output*)
93 (write-string "COLD-INIT... ")
95 ;; Assert that FBOUNDP doesn't choke when its answer is NIL.
96 ;; It was fine if T because in that case the legality of the arg is certain.
97 ;; And be extra paranoid - ensure that it really gets called.
98 (locally (declare (notinline fboundp)) (fboundp '(setf !zzzzzz)))
100 ;; Ensure that *CURRENT-THREAD* and *HANDLER-CLUSTERS* have sane values.
101 ;; create_thread_struct() assigned NIL/unbound-marker respectively.
102 (sb!thread::init-initial-thread)
103 (show-and-call sb!kernel::!target-error-cold-init)
105 ;; Putting data in a synchronized hashtable (*PACKAGE-NAMES*)
106 ;; requires that the main thread be properly initialized.
107 (show-and-call thread-init-or-reinit)
108 ;; Printing of symbols requires that packages be filled in, because
109 ;; OUTPUT-SYMBOL calls FIND-SYMBOL to determine accessibility.
110 (show-and-call !package-cold-init)
111 ;; Fill in the printer's character attribute tables now.
112 ;; If Genesis could write constant arrays into a target core,
113 ;; that would be nice, and would tidy up some other things too.
114 (show-and-call !printer-cold-init)
115 ;; Because L-T-V forms have not executed, CHOOSE-SYMBOL-OUT-FUN doesn't work.
116 (setf real-choose-symbol-out-fun #'choose-symbol-out-fun)
117 (setf (symbol-function 'choose-symbol-out-fun)
118 (lambda (&rest args) (declare (ignore args)) #'output-preserve-symbol))
120 ;; *RAW-SLOT-DATA* is essentially a compile-time constant
121 ;; but isn't dumpable as such because it has functions in it.
122 (show-and-call sb!kernel::!raw-slot-data-init)
124 ;; Anyone might call RANDOM to initialize a hash value or something;
125 ;; and there's nothing which needs to be initialized in order for
126 ;; this to be initialized, so we initialize it right away.
127 (show-and-call !random-cold-init)
129 ;; Must be done before any non-opencoded array references are made.
130 (show-and-call !hairy-data-vector-reffer-init)
132 (show-and-call !character-database-cold-init)
133 (show-and-call !character-name-database-cold-init)
134 (show-and-call sb!unicode::!unicode-properties-cold-init)
136 ;; All sorts of things need INFO and/or (SETF INFO).
137 (/show0 "about to SHOW-AND-CALL !GLOBALDB-COLD-INIT")
138 (show-and-call !globaldb-cold-init)
140 ;; Various toplevel forms call MAKE-ARRAY, which calls SUBTYPEP, so
141 ;; the basic type machinery needs to be initialized before toplevel
142 ;; forms run.
143 (show-and-call !type-class-cold-init)
144 ;; cold-init-wrappers are closures. Installing a closure as a
145 ;; named function requires consing immobile space code.
146 #!+immobile-code (setq sb!vm::*immobile-space-mutex*
147 (sb!thread:make-mutex :name "Immobile space"))
148 (!with-init-wrappers (show-and-call sb!kernel::!primordial-type-cold-init))
149 (show-and-call !world-lock-cold-init)
150 (show-and-call !classes-cold-init)
151 (show-and-call !early-type-cold-init)
152 (show-and-call !late-type-cold-init)
153 (show-and-call !alien-type-cold-init)
154 (show-and-call !target-type-cold-init)
155 ;; FIXME: It would be tidy to make sure that that these cold init
156 ;; functions are called in the same relative order as the toplevel
157 ;; forms of the corresponding source files.
159 (show-and-call !policy-cold-init-or-resanify)
160 (/show0 "back from !POLICY-COLD-INIT-OR-RESANIFY")
162 ;; Must be done before toplevel forms are invoked
163 ;; because a toplevel defstruct will need to add itself
164 ;; to the subclasses of STRUCTURE-OBJECT.
165 (show-and-call sb!kernel::!set-up-structure-object-class)
167 (dolist (x *!cold-defconstants*)
168 (destructuring-bind (name source-loc &optional docstring) x
169 (setf (info :variable :kind name) :constant)
170 (when source-loc (setf (info :source-location :constant name) source-loc))
171 (when docstring (setf (fdocumentation name 'variable) docstring))))
172 (!with-init-wrappers
173 (dolist (x *!cold-defuns*)
174 (destructuring-bind (name . inline-expansion) x
175 (%defun name (fdefinition name) nil inline-expansion))))
177 ;; KLUDGE: Why are fixups mixed up with toplevel forms? Couldn't
178 ;; fixups be done separately? Wouldn't that be clearer and better?
179 ;; -- WHN 19991204
180 (/show0 "doing cold toplevel forms and fixups")
181 (progn (write `("Length(TLFs)= " ,(length *!cold-toplevels*)))
182 (terpri))
183 ;; only the basic external formats are present at this point.
184 (setq sb!impl::*default-external-format* :latin-1)
186 (!with-init-wrappers
187 (loop for index-in-cold-toplevels from 0
188 for toplevel-thing in (prog1 *!cold-toplevels*
189 (makunbound '*!cold-toplevels*))
191 #!+sb-show
192 (when (zerop (mod index-in-cold-toplevels 1024))
193 (/show0 "INDEX-IN-COLD-TOPLEVELS=..")
194 (/hexstr index-in-cold-toplevels))
195 (typecase toplevel-thing
196 (function
197 (funcall toplevel-thing))
198 ((cons (eql :load-time-value))
199 (setf (svref *!load-time-values* (third toplevel-thing))
200 (funcall (second toplevel-thing))))
201 ((cons (eql :load-time-value-fixup))
202 (setf (sap-ref-word (int-sap (get-lisp-obj-address (second toplevel-thing)))
203 (third toplevel-thing))
204 (get-lisp-obj-address
205 (svref *!load-time-values* (fourth toplevel-thing)))))
206 ((cons (eql defstruct))
207 (apply 'sb!kernel::%defstruct (cdr toplevel-thing)))
209 (!cold-lose "bogus operation in *!COLD-TOPLEVELS*")))))
210 (/show0 "done with loop over cold toplevel forms and fixups")
212 ;; Precise GC seems to think these symbols are live during the final GC
213 ;; which in turn enlivens a bunch of other "*!foo*" symbols.
214 ;; Setting them to NIL helps a little bit.
215 (setq *!cold-defuns* nil *!cold-defconstants* nil *!cold-toplevels* nil)
217 ;; Now that L-T-V forms have executed, the symbol output chooser works.
218 (setf (symbol-function 'choose-symbol-out-fun) real-choose-symbol-out-fun)
220 (show-and-call time-reinit)
222 ;; Set sane values again, so that the user sees sane values instead
223 ;; of whatever is left over from the last DECLAIM/PROCLAIM.
224 (show-and-call !policy-cold-init-or-resanify)
226 ;; Only do this after toplevel forms have run, 'cause that's where
227 ;; DEFTYPEs are.
228 (setf *type-system-initialized* t)
230 ;; now that the type system is definitely initialized, fixup UNKNOWN
231 ;; types that have crept in.
232 (show-and-call !fixup-type-cold-init)
233 ;; run the PROCLAIMs.
234 (show-and-call !late-proclaim-cold-init)
236 (show-and-call os-cold-init-or-reinit)
237 (show-and-call !pathname-cold-init)
239 (show-and-call stream-cold-init-or-reset)
240 (show-and-call !loader-cold-init)
241 (show-and-call !foreign-cold-init)
242 #!-(and win32 (not sb-thread))
243 (show-and-call signal-cold-init-or-reinit)
245 (show-and-call float-cold-init-or-reinit)
247 (show-and-call !class-finalize)
249 ;; Install closures as guards on some early PRINT-OBJECT methods so that
250 ;; THREAD and RESTART print nicely prior to the real methods being installed.
251 (dovector (method (cdr (assoc 'print-object sb!pcl::*!trivial-methods*)))
252 (unless (car method)
253 (let ((classoid (find-classoid (third method))))
254 (rplaca method
255 (lambda (x) (classoid-typep (layout-of x) classoid x))))))
257 ;; The reader and printer are initialized very late, so that they
258 ;; can do hairy things like invoking the compiler as part of their
259 ;; initialization.
260 (let ((*readtable* (make-readtable)))
261 (show-and-call !reader-cold-init)
262 (show-and-call !sharpm-cold-init)
263 (show-and-call !backq-cold-init)
264 ;; The *STANDARD-READTABLE* is assigned at last because the above
265 ;; functions would operate on the standard readtable otherwise---
266 ;; which would result in an error.
267 (setf *standard-readtable* *readtable*))
268 (setf *readtable* (copy-readtable *standard-readtable*))
269 (setf sb!debug:*debug-readtable* (copy-readtable *standard-readtable*))
270 (sb!pretty:!pprint-cold-init)
271 (setq *print-level* nil *print-length* nil) ; restore defaults
273 ;; the ANSI-specified initial value of *PACKAGE*
274 (setf *package* (find-package "COMMON-LISP-USER"))
276 ;; Enable normal (post-cold-init) behavior of INFINITE-ERROR-PROTECT.
277 (setf sb!kernel::*maximum-error-depth* 10)
278 (/show0 "enabling internal errors")
279 (setf (extern-alien "internal_errors_enabled" int) 1)
281 ;; Toggle some readonly bits
282 (dovector (sc sb!c:*backend-sc-numbers*)
283 (when sc
284 (logically-readonlyize (sb!c::sc-move-funs sc))
285 (logically-readonlyize (sb!c::sc-load-costs sc))
286 (logically-readonlyize (sb!c::sc-move-vops sc))
287 (logically-readonlyize (sb!c::sc-move-costs sc))))
289 ; hppa heap is segmented, lisp and c uses a stub to call eachother
290 #!+hpux (%primitive sb!vm::setup-return-from-lisp-stub)
291 ;; The system is finally ready for GC.
292 (/show0 "enabling GC")
293 (setq *gc-inhibit* nil)
294 (/show0 "doing first GC")
295 (gc :full t)
296 (/show0 "back from first GC")
298 ;; The show is on.
299 (terpri)
300 (/show0 "going into toplevel loop")
301 (handling-end-of-the-world
302 (toplevel-init)
303 (critically-unreachable "after TOPLEVEL-INIT")))
305 (define-deprecated-function :early "1.0.56.55" quit (exit sb!thread:abort-thread)
306 (&key recklessly-p (unix-status 0))
307 (if (or recklessly-p (sb!thread:main-thread-p))
308 (exit :code unix-status :abort recklessly-p)
309 (sb!thread:abort-thread))
310 (critically-unreachable "after trying to die in QUIT"))
312 (declaim (ftype (sfunction (&key (:code (or null exit-code))
313 (:timeout (or null real))
314 (:abort t))
315 nil)
316 exit))
317 (defun exit (&key code abort (timeout *exit-timeout*))
318 "Terminates the process, causing SBCL to exit with CODE. CODE
319 defaults to 0 when ABORT is false, and 1 when it is true.
321 When ABORT is false (the default), current thread is first unwound,
322 *EXIT-HOOKS* are run, other threads are terminated, and standard
323 output streams are flushed before SBCL calls exit(3) -- at which point
324 atexit(3) functions will run. If multiple threads call EXIT with ABORT
325 being false, the first one to call it will complete the protocol.
327 When ABORT is true, SBCL exits immediately by calling _exit(2) without
328 unwinding stack, or calling exit hooks. Note that _exit(2) does not
329 call atexit(3) functions unlike exit(3).
331 Recursive calls to EXIT cause EXIT to behave as if ABORT was true.
333 TIMEOUT controls waiting for other threads to terminate when ABORT is
334 NIL. Once current thread has been unwound and *EXIT-HOOKS* have been
335 run, spawning new threads is prevented and all other threads are
336 terminated by calling TERMINATE-THREAD on them. The system then waits
337 for them to finish using JOIN-THREAD, waiting at most a total TIMEOUT
338 seconds for all threads to join. Those threads that do not finish
339 in time are simply ignored while the exit protocol continues. TIMEOUT
340 defaults to *EXIT-TIMEOUT*, which in turn defaults to 60. TIMEOUT NIL
341 means to wait indefinitely.
343 Note that TIMEOUT applies only to JOIN-THREAD, not *EXIT-HOOKS*. Since
344 TERMINATE-THREAD is asynchronous, getting multithreaded application
345 termination with complex cleanups right using it can be tricky. To
346 perform an orderly synchronous shutdown use an exit hook instead of
347 relying on implicit thread termination.
349 Consequences are unspecified if serious conditions occur during EXIT
350 excepting errors from *EXIT-HOOKS*, which cause warnings and stop
351 execution of the hook that signaled, but otherwise allow the exit
352 process to continue normally."
353 (if (or abort *exit-in-process*)
354 (os-exit (or code 1) :abort t)
355 (let ((code (or code 0)))
356 (with-deadline (:seconds nil :override t)
357 (sb!thread:grab-mutex *exit-lock*))
358 (setf *exit-in-process* code
359 *exit-timeout* timeout)
360 (throw '%end-of-the-world t)))
361 (critically-unreachable "After trying to die in EXIT."))
363 ;;;; initialization functions
365 (defun thread-init-or-reinit ()
366 (sb!thread::init-job-control)
367 (sb!thread::get-foreground))
369 (defun reinit ()
370 #!+win32
371 (setf sb!win32::*ansi-codepage* nil)
372 (setf *default-external-format* nil)
373 (setf sb!alien::*default-c-string-external-format* nil)
374 ;; WITHOUT-GCING implies WITHOUT-INTERRUPTS.
375 (without-gcing
376 ;; Create *CURRENT-THREAD* first, since initializing a stream calls
377 ;; ALLOC-BUFFER which calls FINALIZE which acquires **FINALIZER-STORE-LOCK**
378 ;; which needs a valid thread in order to grab a mutex.
379 (sb!thread::init-initial-thread)
380 ;; Initialize streams first, so that any errors can be printed later
381 (stream-reinit t)
382 (os-cold-init-or-reinit)
383 (thread-init-or-reinit)
384 #!-(and win32 (not sb-thread))
385 (signal-cold-init-or-reinit)
386 (setf (extern-alien "internal_errors_enabled" int) 1)
387 (float-cold-init-or-reinit))
388 (gc-reinit)
389 (foreign-reinit)
390 (time-reinit)
391 ;; If the debugger was disabled in the saved core, we need to
392 ;; re-disable ldb again.
393 (when (eq *invoke-debugger-hook* 'sb!debug::debugger-disabled-hook)
394 (sb!debug::disable-debugger))
395 (call-hooks "initialization" *init-hooks*))
397 ;;;; some support for any hapless wretches who end up debugging cold
398 ;;;; init code
400 ;;; Decode THING into hexadecimal notation using only machinery
401 ;;; available early in cold init.
402 #!+sb-show
403 (defun hexstr (thing)
404 (/noshow0 "entering HEXSTR")
405 (let* ((addr (get-lisp-obj-address thing))
406 (nchars (* sb!vm:n-word-bytes 2))
407 (str (make-string (+ nchars 2) :element-type 'base-char)))
408 (/noshow0 "ADDR and STR calculated")
409 (setf (char str 0) #\0
410 (char str 1) #\x)
411 (/noshow0 "CHARs 0 and 1 set")
412 (dotimes (i nchars)
413 (/noshow0 "at head of DOTIMES loop")
414 (let* ((nibble (ldb (byte 4 0) addr))
415 (chr (char "0123456789abcdef" nibble)))
416 (declare (type (unsigned-byte 4) nibble)
417 (base-char chr))
418 (/noshow0 "NIBBLE and CHR calculated")
419 (setf (char str (- (1+ nchars) i)) chr
420 addr (ash addr -4))))
421 str))
423 ;; But: you almost never need this. Just use WRITE in all its glory.
424 #!+sb-show
425 (defun cold-print (x)
426 (labels ((%cold-print (obj depthoid)
427 (if (> depthoid 4)
428 (%primitive print "...")
429 (typecase obj
430 (simple-string
431 (%primitive print obj))
432 (symbol
433 (%primitive print (symbol-name obj)))
434 (cons
435 (%primitive print "cons:")
436 (let ((d (1+ depthoid)))
437 (%cold-print (car obj) d)
438 (%cold-print (cdr obj) d)))
440 (%primitive print (hexstr obj)))))))
441 (%cold-print x 0))
442 (values))
444 (in-package "SB!INT")
445 (defun !unintern-symbols ()
446 ;; For some reason uninterning these:
447 ;; DEF!TYPE DEF!CONSTANT DEF!STRUCT
448 ;; does not work, they stick around as uninterned symbols.
449 ;; Some other macros must expand into them. Ugh.
450 '("SB-INT"
451 defenum defun-cached with-globaldb-name
453 #!+sb-show ()
454 #!-sb-show (/hexstr /nohexstr /noshow /noshow0 /noxhow
455 /primitive-print /show /show0 /xhow)))