1 ;;;; stuff related to the toplevel read-eval-print loop, plus some
2 ;;;; other miscellaneous functions that we don't have any better place
5 ;;;; This software is part of the SBCL system. See the README file for
8 ;;;; This software is derived from the CMU CL system, which was
9 ;;;; written at Carnegie Mellon University and released into the
10 ;;;; public domain. The software is in the public domain and is
11 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
12 ;;;; files for more information.
14 (in-package "SB!IMPL")
16 ;;;; magic specials initialized by GENESIS
18 ;;; FIXME: The DEFVAR here is redundant with the (DECLAIM (SPECIAL ..))
19 ;;; of all static symbols in early-impl.lisp.
21 (defvar *current-catch-block*)
22 (defvar *current-unwind-protect-block*)
23 (defvar *free-interrupt-context-index*))
25 ;;; specials initialized by !COLD-INIT
27 ;;; FIXME: These could be converted to DEFVARs.
28 (declaim (special *gc-inhibit* *already-maybe-gcing*
29 *need-to-collect-garbage*
31 *before-gc-hooks* *after-gc-hooks*
32 #!+x86 *pseudo-atomic-atomic*
33 #!+x86 *pseudo-atomic-interrupted*
34 sb!unix::*interrupts-enabled*
35 sb!unix::*interrupt-pending*
36 *type-system-initialized*))
38 (defvar *cold-init-complete-p*)
40 ;;; counts of nested errors (with internal errors double-counted)
41 (defvar *maximum-error-depth*)
42 (defvar *current-error-depth*)
44 ;;;; miscellaneous utilities for working with with TOPLEVEL
46 ;;; Execute BODY in a context where any %END-OF-THE-WORLD (thrown e.g.
47 ;;; by QUIT) is caught and any final processing and return codes are
48 ;;; handled appropriately.
49 (defmacro handling-end-of-the-world (&body body)
50 (let ((caught (gensym "CAUGHT")))
51 `(let ((,caught (catch '%end-of-the-world
52 (/show0 "inside CATCH '%END-OF-THE-WORLD")
54 (/show0 "back from CATCH '%END-OF-THE-WORLD, flushing output")
55 (flush-standard-output-streams)
56 (/show0 "calling UNIX-EXIT")
57 (sb!unix:unix-exit ,caught))))
59 ;;;; working with *CURRENT-ERROR-DEPTH* and *MAXIMUM-ERROR-DEPTH*
61 ;;; INFINITE-ERROR-PROTECT is used by ERROR and friends to keep us out
63 (defmacro infinite-error-protect (&rest forms)
64 `(unless (infinite-error-protector)
65 (/show0 "back from INFINITE-ERROR-PROTECTOR")
66 (let ((*current-error-depth* (1+ *current-error-depth*)))
67 (/show0 "in INFINITE-ERROR-PROTECT, incremented error depth")
68 ;; arbitrary truncation
69 #!+sb-show (sb!debug:backtrace 8)
72 ;;; a helper function for INFINITE-ERROR-PROTECT
73 (defun infinite-error-protector ()
74 (/show0 "entering INFINITE-ERROR-PROTECTOR, *CURRENT-ERROR-DEPTH*=..")
75 (/hexstr *current-error-depth*)
76 (cond ((not *cold-init-complete-p*)
77 (%primitive print "Argh! error in cold init, halting")
78 (%primitive sb!c:halt))
79 ((or (not (boundp '*current-error-depth*))
80 (not (realp *current-error-depth*))
81 (not (boundp '*maximum-error-depth*))
82 (not (realp *maximum-error-depth*)))
83 (%primitive print "Argh! corrupted error depth, halting")
84 (%primitive sb!c:halt))
85 ((> *current-error-depth* *maximum-error-depth*)
86 (/show0 "*MAXIMUM-ERROR-DEPTH*=..")
87 (/hexstr *maximum-error-depth*)
88 (/show0 "in INFINITE-ERROR-PROTECTOR, calling ERROR-ERROR")
92 "KERNEL:*MAXIMUM-ERROR-DEPTH* exceeded.")
95 (/show0 "returning normally from INFINITE-ERROR-PROTECTOR")
98 ;;; FIXME: I had a badly broken version of INFINITE-ERROR-PROTECTOR at
99 ;;; one point (shown below), and SBCL cross-compiled it without
100 ;;; warning about FORMS being undefined. Check whether that problem
101 ;;; (missing warning) is repeatable in the final system and if so, fix
104 (defun infinite-error-protector ()
105 `(cond ((not *cold-init-complete-p*)
106 (%primitive print "Argh! error in cold init, halting")
107 (%primitive sb!c:halt))
108 ((or (not (boundp '*current-error-depth*))
109 (not (realp *current-error-depth*))
110 (not (boundp '*maximum-error-depth*))
111 (not (realp *maximum-error-depth*)))
112 (%primitive print "Argh! corrupted error depth, halting")
113 (%primitive sb!c:halt))
114 ((> *current-error-depth* *maximum-error-depth*)
115 (/show0 "in INFINITE-ERROR-PROTECTOR, calling ERROR-ERROR")
116 (error-error "Help! "
117 *current-error-depth*
119 "KERNEL:*MAXIMUM-ERROR-DEPTH* exceeded.")
123 (/show0 "in INFINITE-ERROR-PROTECTOR, returning normally")
127 ;;;; miscellaneous external functions
129 #!-mp ; The multi-processing version is defined in multi-proc.lisp.
132 "This function causes execution to be suspended for N seconds. N may
133 be any non-negative, non-complex number."
134 (when (or (not (realp n))
136 (error 'simple-type-error
137 :format-control "invalid argument to SLEEP: ~S"
138 :format-arguments (list n)
140 :expected-type '(real 0)))
141 (multiple-value-bind (sec usec)
144 (multiple-value-bind (sec frac)
146 (values sec (truncate frac 1e-6))))
147 (sb!unix:unix-select 0 0 0 0 sec usec))
150 ;;;; SCRUB-CONTROL-STACK
152 (defconstant bytes-per-scrub-unit 2048)
154 ;;; Zero the unused portion of the control stack so that old objects
155 ;;; are not kept alive because of uninitialized stack variables.
157 ;;; "To summarize the problem, since not all allocated stack frame
158 ;;; slots are guaranteed to be written by the time you call an another
159 ;;; function or GC, there may be garbage pointers retained in your
160 ;;; dead stack locations. The stack scrubbing only affects the part
161 ;;; of the stack from the SP to the end of the allocated stack."
162 ;;; - ram, on cmucl-imp, Tue, 25 Sep 2001
164 ;;; So, as an (admittedly lame) workaround, from time to time we call
165 ;;; scrub-control-stack to zero out all the unused portion. This is
166 ;;; supposed to happen when the stack is mostly empty, so that we have
167 ;;; a chance of clearing more of it: callers are currently (2002.07.18)
170 (defun scrub-control-stack ()
171 (declare (optimize (speed 3) (safety 0))
172 (values (unsigned-byte 20))) ; FIXME: DECLARE VALUES?
174 #!-stack-grows-downward-not-upward
175 (let* ((csp (sap-int (sb!c::control-stack-pointer-sap)))
176 (initial-offset (logand csp (1- bytes-per-scrub-unit)))
178 (- sb!vm:control-stack-end sb!c:*backend-page-size*)))
180 ((scrub (ptr offset count)
181 (declare (type system-area-pointer ptr)
182 (type (unsigned-byte 16) offset)
183 (type (unsigned-byte 20) count)
184 (values (unsigned-byte 20)))
185 (cond ((>= (sap-int ptr) end-of-stack) 0)
186 ((= offset bytes-per-scrub-unit)
187 (look (sap+ ptr bytes-per-scrub-unit) 0 count))
189 (setf (sap-ref-32 ptr offset) 0)
190 (scrub ptr (+ offset sb!vm:n-word-bytes) count))))
191 (look (ptr offset count)
192 (declare (type system-area-pointer ptr)
193 (type (unsigned-byte 16) offset)
194 (type (unsigned-byte 20) count)
195 (values (unsigned-byte 20)))
196 (cond ((>= (sap-int ptr) end-of-stack) 0)
197 ((= offset bytes-per-scrub-unit)
199 ((zerop (sap-ref-32 ptr offset))
200 (look ptr (+ offset sb!vm:n-word-bytes) count))
202 (scrub ptr offset (+ count sb!vm:n-word-bytes))))))
203 (declare (type (unsigned-byte 32) csp))
204 (scrub (int-sap (- csp initial-offset))
205 (* (floor initial-offset sb!vm:n-word-bytes) sb!vm:n-word-bytes)
208 #!+stack-grows-downward-not-upward
209 (let* ((csp (sap-int (sb!c::control-stack-pointer-sap)))
210 (end-of-stack (+ sb!vm:control-stack-start sb!c:*backend-page-size*))
211 (initial-offset (logand csp (1- bytes-per-scrub-unit))))
213 ((scrub (ptr offset count)
214 (declare (type system-area-pointer ptr)
215 (type (unsigned-byte 16) offset)
216 (type (unsigned-byte 20) count)
217 (values (unsigned-byte 20)))
218 (let ((loc (int-sap (- (sap-int ptr) (+ offset sb!vm:n-word-bytes)))))
219 (cond ((< (sap-int loc) end-of-stack) 0)
220 ((= offset bytes-per-scrub-unit)
221 (look (int-sap (- (sap-int ptr) bytes-per-scrub-unit))
223 (t ;; need to fix bug in %SET-STACK-REF
224 (setf (sap-ref-32 loc 0) 0)
225 (scrub ptr (+ offset sb!vm:n-word-bytes) count)))))
226 (look (ptr offset count)
227 (declare (type system-area-pointer ptr)
228 (type (unsigned-byte 16) offset)
229 (type (unsigned-byte 20) count)
230 (values (unsigned-byte 20)))
231 (let ((loc (int-sap (- (sap-int ptr) offset))))
232 (cond ((< (sap-int loc) end-of-stack) 0)
233 ((= offset bytes-per-scrub-unit)
235 ((zerop (sb!kernel::get-lisp-obj-address (stack-ref loc 0)))
236 (look ptr (+ offset sb!vm:n-word-bytes) count))
238 (scrub ptr offset (+ count sb!vm:n-word-bytes)))))))
239 (declare (type (unsigned-byte 32) csp))
240 (scrub (int-sap (+ csp initial-offset))
241 (* (floor initial-offset sb!vm:n-word-bytes) sb!vm:n-word-bytes)
244 ;;;; the default toplevel function
248 "a list of all the values returned by the most recent top level EVAL")
249 (defvar // nil #!+sb-doc "the previous value of /")
250 (defvar /// nil #!+sb-doc "the previous value of //")
251 (defvar * nil #!+sb-doc "the value of the most recent top level EVAL")
252 (defvar ** nil #!+sb-doc "the previous value of *")
253 (defvar *** nil #!+sb-doc "the previous value of **")
254 (defvar + nil #!+sb-doc "the value of the most recent top level READ")
255 (defvar ++ nil #!+sb-doc "the previous value of +")
256 (defvar +++ nil #!+sb-doc "the previous value of ++")
257 (defvar - nil #!+sb-doc "the form currently being evaluated")
259 (defun interactive-eval (form)
260 "Evaluate FORM, returning whatever it returns and adjusting ***, **, *,
261 +++, ++, +, ///, //, /, and -."
266 (make-null-interactive-lexenv)))))
277 ;; The bogon returned an unbound marker.
278 ;; FIXME: It would be safer to check every one of the values in RESULTS,
279 ;; instead of just the first one.
281 (cerror "Go on with * set to NIL."
282 "EVAL returned an unbound marker."))
285 ;;; Flush anything waiting on one of the ANSI Common Lisp standard
286 ;;; output streams before proceeding.
287 (defun flush-standard-output-streams ()
288 (dolist (name '(*debug-io*
293 (finish-output (symbol-value name)))
296 ;;; the default system top level function
297 (defun toplevel-init ()
299 (/show0 "entering TOPLEVEL-INIT")
301 (let ((sysinit nil) ; value of --sysinit option
302 (userinit nil) ; value of --userinit option
303 (reversed-evals nil) ; values of --eval options, in reverse order; and
304 ; also --load options, translated into --eval
305 (noprint nil) ; Has a --noprint option been seen?
306 (options (rest *posix-argv*))) ; skipping program name
308 (/show0 "done with outer LET in TOPLEVEL-INIT")
310 ;; FIXME: There are lots of ways for errors to happen around here
311 ;; (e.g. bad command line syntax, or READ-ERROR while trying to
312 ;; READ an --eval string). Make sure that they're handled
313 ;; reasonably. Also, perhaps all errors while parsing the command
314 ;; line should cause the system to QUIT, instead of trying to go
315 ;; into the Lisp debugger, since trying to go into the debugger
316 ;; gets into various annoying issues of where we should go after
317 ;; the user tries to return from the debugger.
319 ;; Parse command line options.
320 (loop while options do
321 (/show0 "at head of LOOP WHILE OPTIONS DO in TOPLEVEL-INIT")
322 (let ((option (first options)))
323 (flet ((pop-option ()
326 (error "unexpected end of command line options"))))
327 (cond ((string= option "--sysinit")
330 (error "multiple --sysinit options")
331 (setf sysinit (pop-option))))
332 ((string= option "--userinit")
335 (error "multiple --userinit options")
336 (setf userinit (pop-option))))
337 ((string= option "--eval")
339 (let ((eval-as-string (pop-option)))
340 (with-input-from-string (eval-stream eval-as-string)
341 (let* ((eof-marker (cons :eof :eof))
342 (eval (read eval-stream nil eof-marker))
343 (eof (read eval-stream nil eof-marker)))
344 (cond ((eq eval eof-marker)
345 (error "unable to parse ~S"
347 ((not (eq eof eof-marker))
348 (error "more than one expression in ~S"
351 (push eval reversed-evals)))))))
352 ((string= option "--load")
354 (push `(load ,(pop-option)) reversed-evals))
355 ((string= option "--noprint")
358 ;; FIXME: --noprogrammer was deprecated in 0.7.5, and
359 ;; in a year or so this backwards compatibility can
361 ((string= option "--noprogrammer")
362 (warn "treating deprecated --noprogrammer as --disable-debugger")
364 (push '(disable-debugger) reversed-evals))
365 ((string= option "--disable-debugger")
367 (push '(disable-debugger) reversed-evals))
368 ((string= option "--end-toplevel-options")
372 ;; Anything we don't recognize as a toplevel
373 ;; option must be the start of user-level
374 ;; options.. except that if we encounter
375 ;; "--end-toplevel-options" after we gave up
376 ;; because we didn't recognize an option as a
377 ;; toplevel option, then the option we gave up on
378 ;; must have been an error. (E.g. in
379 ;; "sbcl --eval '(a)' --eval'(b)' --end-toplevel-options"
380 ;; this test will let us detect that the string
381 ;; "--eval(b)" is an error.)
382 (if (find "--end-toplevel-options" options
384 (error "bad toplevel option: ~S" (first options))
386 (/show0 "done with LOOP WHILE OPTIONS DO in TOPLEVEL-INIT")
388 ;; Excise all the options that we processed, so that only
389 ;; user-level options are left visible to user code.
390 (setf (rest *posix-argv*) options)
392 ;; Handle initialization files.
393 (/show0 "handling initialization files in TOPLEVEL-INIT")
394 (flet (;; If any of POSSIBLE-INIT-FILE-NAMES names a real file,
395 ;; return its truename.
396 (probe-init-files (&rest possible-init-file-names)
397 (/show0 "entering PROBE-INIT-FILES")
400 (and (stringp x) (probe-file x)))
401 possible-init-file-names)
402 (/show0 "leaving PROBE-INIT-FILES"))))
403 (let* ((sbcl-home (posix-getenv "SBCL_HOME"))
404 (sysinit-truename (if sbcl-home
405 (probe-init-files sysinit
409 (probe-init-files sysinit
411 "/usr/local/etc/sbclrc")))
412 (user-home (or (posix-getenv "HOME")
413 (error "The HOME environment variable is unbound, ~
414 so user init file can't be found.")))
415 (userinit-truename (probe-init-files userinit
420 ;; We wrap all the pre-REPL user/system customized startup code
423 ;; (Why not wrap everything, even the stuff above, in this
424 ;; restart? Errors above here are basically command line or
425 ;; Unix environment errors, e.g. a missing file or a typo on
426 ;; the Unix command line, and you don't need to get into Lisp
427 ;; to debug them, you should just start over and do it right
428 ;; at the Unix level. Errors below here are generally errors
429 ;; in user Lisp code, and it might be helpful to let the user
430 ;; reach the REPL in order to help figure out what's going
434 (flet ((process-init-file (truename)
436 (unless (load truename)
437 (error "~S was not successfully loaded." truename))
438 (flush-standard-output-streams))))
439 (process-init-file sysinit-truename)
440 (process-init-file userinit-truename))
442 ;; Process --eval options.
443 (/show0 "handling --eval options in TOPLEVEL-INIT")
444 (dolist (eval (reverse reversed-evals))
445 (/show0 "handling one --eval option in TOPLEVEL-INIT")
447 (flush-standard-output-streams)))
450 "Continue anyway (skipping to toplevel read/eval/print loop)."
451 (/show0 "CONTINUEing from pre-REPL RESTART-CASE")
452 (values)) ; (no-op, just fall through)
454 :report "Quit SBCL (calling #'QUIT, killing the process)."
455 (/show0 "falling through to QUIT from pre-REPL RESTART-CASE")
458 ;; one more time for good measure, in case we fell out of the
459 ;; RESTART-CASE above before one of the flushes in the ordinary
460 ;; flow of control had a chance to operate
461 (flush-standard-output-streams)
463 (/show0 "falling into TOPLEVEL-REPL from TOPLEVEL-INIT")
464 (toplevel-repl noprint)
465 ;; (classic CMU CL error message: "You're certainly a clever child.":-)
466 (critically-unreachable "after TOPLEVEL-REPL"))))
468 ;;; halt-on-failures and prompt-on-failures modes, suitable for
469 ;;; noninteractive and interactive use respectively
470 (defun disable-debugger ()
471 (setf *debugger-hook* 'noprogrammer-debugger-hook-fun
472 *debug-io* *error-output*))
473 (defun enable-debugger ()
474 (setf *debugger-hook* nil
475 *debug-io* *query-io*))
477 ;;; read-eval-print loop for the default system toplevel
478 (defun toplevel-repl (noprint)
479 (/show0 "entering TOPLEVEL-REPL")
480 (let ((* nil) (** nil) (*** nil)
482 (+ nil) (++ nil) (+++ nil)
483 (/// nil) (// nil) (/ nil))
484 ;; WITH-SIMPLE-RESTART doesn't actually restart its body as some
485 ;; (like WHN for an embarrassingly long time ca. 2001-12-07) might
486 ;; think, but instead drops control back out at the end. So when a
487 ;; TOPLEVEL or outermost-ABORT restart happens, we need this outer
488 ;; LOOP wrapper to grab control and start over again. (And it also
489 ;; wraps CATCH 'TOPLEVEL-CATCHER for similar reasons.)
491 (/show0 "about to set up restarts in TOPLEVEL-REPL")
492 ;; There should only be one TOPLEVEL restart, and it's here, so
493 ;; restarting at TOPLEVEL always bounces you all the way out here.
494 (with-simple-restart (toplevel
495 "Restart at toplevel READ/EVAL/PRINT loop.")
496 ;; We add a new ABORT restart for every debugger level, so
497 ;; restarting at ABORT in a nested debugger gets you out to the
498 ;; innermost enclosing debugger, and only when you're in the
499 ;; outermost, unnested debugger level does restarting at ABORT
500 ;; get you out to here.
503 "~@<Reduce debugger level (leaving debugger, returning to toplevel).~@:>")
504 (catch 'toplevel-catcher
505 #!-sunos (sb!unix:unix-sigsetmask 0) ; FIXME: What is this for?
506 ;; in the event of a control-stack-exhausted-error, we should
507 ;; have unwound enough stack by the time we get here that this
509 (sb!kernel::protect-control-stack-guard-page 1)
511 (critically-unreachable "after REPL")))))))
513 (defun repl (noprint)
514 (/show0 "entering REPL")
515 (let ((eof-marker (cons :eof nil)))
517 ;; see comment preceding definition of SCRUB-CONTROL-STACK
518 (scrub-control-stack)
521 (write-string "* ") ; arbitrary but customary REPL prompt
522 (flush-standard-output-streams))
523 (let ((form (read *standard-input* nil eof-marker)))
524 (cond ((eq form eof-marker)
525 (/show0 "doing QUIT for EOF in REPL")
528 (let ((results (multiple-value-list (interactive-eval form))))
530 (dolist (result results)
532 (prin1 result))))))))))
534 ;;; suitable value for *DEBUGGER-HOOK* for a noninteractive Unix-y program
535 (defun noprogrammer-debugger-hook-fun (condition old-debugger-hook)
536 (declare (ignore old-debugger-hook))
537 (flet ((failure-quit (&key recklessly-p)
538 (/show0 "in FAILURE-QUIT (in --disable-debugger debugger hook)")
539 (quit :unix-status 1 :recklessly-p recklessly-p)))
540 ;; This HANDLER-CASE is here mostly to stop output immediately
541 ;; (and fall through to QUIT) when there's an I/O error. Thus,
542 ;; when we're run under a shell script or something, we can die
543 ;; cleanly when the script dies (and our pipes are cut), instead
544 ;; of falling into ldb or something messy like that.
547 (format *error-output*
548 "~&~@<unhandled condition (of type ~S): ~2I~_~A~:>~2%"
551 ;; Flush *ERROR-OUTPUT* even before the BACKTRACE, so that
552 ;; even if we hit an error within BACKTRACE (e.g. a bug in
553 ;; the debugger's own frame-walking code, or a bug in a user
554 ;; PRINT-OBJECT method) we'll at least have the CONDITION
555 ;; printed out before we die.
556 (finish-output *error-output*)
557 ;; (Where to truncate the BACKTRACE is of course arbitrary, but
558 ;; it seems as though we should at least truncate it somewhere.)
559 (sb!debug:backtrace 128 *error-output*)
562 "~%unhandled condition in --disable-debugger mode, quitting~%")
563 (finish-output *error-output*)
566 ;; We IGNORE-ERRORS here because even %PRIMITIVE PRINT can
567 ;; fail when our output streams are blown away, as e.g. when
568 ;; we're running under a Unix shell script and it dies somehow
569 ;; (e.g. because of a SIGINT). In that case, we might as well
570 ;; just give it up for a bad job, and stop trying to notify
571 ;; the user of anything.
573 ;; Actually, the only way I've run across to exercise the
574 ;; problem is to have more than one layer of shell script.
575 ;; I have a shell script which does
576 ;; time nice -10 sh make.sh "$1" 2>&1 | tee make.tmp
577 ;; and the problem occurs when I interrupt this with Ctrl-C
578 ;; under Linux 2.2.14-5.0 and GNU bash, version 1.14.7(1).
579 ;; I haven't figured out whether it's bash, time, tee, Linux, or
580 ;; what that is responsible, but that it's possible at all
581 ;; means that we should IGNORE-ERRORS here. -- WHN 2001-04-24
584 "Argh! error within --disable-debugger error handling"))
585 (failure-quit :recklessly-p t)))))
587 ;;; a convenient way to get into the assembly-level debugger
589 (%primitive sb!c:halt))