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 (defconstant most-positive-fixnum #.sb!vm:*target-most-positive-fixnum*
18 "the fixnum closest in value to positive infinity")
20 (defconstant most-negative-fixnum #.sb!vm:*target-most-negative-fixnum*
22 "the fixnum closest in value to negative infinity")
24 ;;;; magic specials initialized by GENESIS
26 ;;; FIXME: The DEFVAR here is redundant with the (DECLAIM (SPECIAL ..))
27 ;;; of all static symbols in early-impl.lisp.
29 (defvar *current-catch-block*)
30 (defvar *current-unwind-protect-block*)
31 (defvar *free-interrupt-context-index*))
33 ;;; specials initialized by !COLD-INIT
35 ;;; FIXME: These could be converted to DEFVARs.
36 (declaim (special *gc-inhibit* *already-maybe-gcing*
37 *need-to-collect-garbage*
39 *before-gc-hooks* *after-gc-hooks*
40 #!+x86 *pseudo-atomic-atomic*
41 #!+x86 *pseudo-atomic-interrupted*
42 sb!unix::*interrupts-enabled*
43 sb!unix::*interrupt-pending*
44 *type-system-initialized*))
46 (defvar *cold-init-complete-p*)
48 ;;; counts of nested errors (with internal errors double-counted)
49 (defvar *maximum-error-depth*)
50 (defvar *current-error-depth*)
52 ;;;; miscellaneous utilities for working with with TOPLEVEL
54 ;;; Execute BODY in a context where any %END-OF-THE-WORLD (thrown e.g.
55 ;;; by QUIT) is caught and any final processing and return codes are
56 ;;; handled appropriately.
57 (defmacro handling-end-of-the-world (&body body)
58 (let ((caught (gensym "CAUGHT")))
59 `(let ((,caught (catch '%end-of-the-world
60 (/show0 "inside CATCH '%END-OF-THE-WORLD")
62 (/show0 "back from CATCH '%END-OF-THE-WORLD, flushing output")
63 (flush-standard-output-streams)
64 (/show0 "calling UNIX-EXIT")
65 (sb!unix:unix-exit ,caught))))
67 ;;;; working with *CURRENT-ERROR-DEPTH* and *MAXIMUM-ERROR-DEPTH*
69 ;;; INFINITE-ERROR-PROTECT is used by ERROR and friends to keep us out
71 (defmacro infinite-error-protect (&rest forms)
72 `(unless (infinite-error-protector)
73 (/show0 "back from INFINITE-ERROR-PROTECTOR")
74 (let ((*current-error-depth* (1+ *current-error-depth*)))
75 (/show0 "in INFINITE-ERROR-PROTECT, incremented error depth")
76 #+sb-show (sb-debug:backtrace)
79 ;;; a helper function for INFINITE-ERROR-PROTECT
80 (defun infinite-error-protector ()
81 (/show0 "entering INFINITE-ERROR-PROTECTOR, *CURRENT-ERROR-DEPTH*=..")
82 (/hexstr *current-error-depth*)
83 (cond ((not *cold-init-complete-p*)
84 (%primitive print "Argh! error in cold init, halting")
85 (%primitive sb!c:halt))
86 ((or (not (boundp '*current-error-depth*))
87 (not (realp *current-error-depth*))
88 (not (boundp '*maximum-error-depth*))
89 (not (realp *maximum-error-depth*)))
90 (%primitive print "Argh! corrupted error depth, halting")
91 (%primitive sb!c:halt))
92 ((> *current-error-depth* *maximum-error-depth*)
93 (/show0 "*MAXIMUM-ERROR-DEPTH*=..")
94 (/hexstr *maximum-error-depth*)
95 (/show0 "in INFINITE-ERROR-PROTECTOR, calling ERROR-ERROR")
99 "KERNEL:*MAXIMUM-ERROR-DEPTH* exceeded.")
102 (/show0 "returning normally from INFINITE-ERROR-PROTECTOR")
105 ;;; FIXME: I had a badly broken version of INFINITE-ERROR-PROTECTOR at
106 ;;; one point (shown below), and SBCL cross-compiled it without
107 ;;; warning about FORMS being undefined. Check whether that problem
108 ;;; (missing warning) is repeatable in the final system and if so, fix
111 (defun infinite-error-protector ()
112 `(cond ((not *cold-init-complete-p*)
113 (%primitive print "Argh! error in cold init, halting")
114 (%primitive sb!c:halt))
115 ((or (not (boundp '*current-error-depth*))
116 (not (realp *current-error-depth*))
117 (not (boundp '*maximum-error-depth*))
118 (not (realp *maximum-error-depth*)))
119 (%primitive print "Argh! corrupted error depth, halting")
120 (%primitive sb!c:halt))
121 ((> *current-error-depth* *maximum-error-depth*)
122 (/show0 "in INFINITE-ERROR-PROTECTOR, calling ERROR-ERROR")
123 (error-error "Help! "
124 *current-error-depth*
126 "KERNEL:*MAXIMUM-ERROR-DEPTH* exceeded.")
130 (/show0 "in INFINITE-ERROR-PROTECTOR, returning normally")
134 ;;;; miscellaneous external functions
136 #!-mp ; The multi-processing version is defined in multi-proc.lisp.
139 "This function causes execution to be suspended for N seconds. N may
140 be any non-negative, non-complex number."
141 (when (or (not (realp n))
143 (error 'simple-type-error
144 :format-control "invalid argument to SLEEP: ~S"
145 :format-arguments (list n)
147 :expected-type '(real 0)))
148 (multiple-value-bind (sec usec)
151 (multiple-value-bind (sec frac)
153 (values sec (truncate frac 1e-6))))
154 (sb!unix:unix-select 0 0 0 0 sec usec))
157 ;;;; SCRUB-CONTROL-STACK
159 (defconstant bytes-per-scrub-unit 2048)
161 ;;; Zero the unused portion of the control stack so that old objects
162 ;;; are not kept alive because of uninitialized stack variables.
164 ;;; FIXME: Why do we need to do this instead of just letting GC read
165 ;;; the stack pointer and avoid messing with the unused portion of
166 ;;; the control stack? (Is this a multithreading thing where there's
167 ;;; one control stack and stack pointer per thread, and it might not
168 ;;; be easy to tell what a thread's stack pointer value is when
169 ;;; looking in from another thread?)
170 (defun scrub-control-stack ()
171 (declare (optimize (speed 3) (safety 0))
172 (values (unsigned-byte 20))) ; FIXME: DECLARE VALUES?
174 #!-x86 ; machines where stack grows upwards (I guess) -- WHN 19990906
176 ((scrub (ptr offset count)
177 (declare (type system-area-pointer ptr)
178 (type (unsigned-byte 16) offset)
179 (type (unsigned-byte 20) count)
180 (values (unsigned-byte 20)))
181 (cond ((= offset bytes-per-scrub-unit)
182 (look (sap+ ptr bytes-per-scrub-unit) 0 count))
184 (setf (sap-ref-32 ptr offset) 0)
185 (scrub ptr (+ offset sb!vm:n-word-bytes) count))))
186 (look (ptr offset count)
187 (declare (type system-area-pointer ptr)
188 (type (unsigned-byte 16) offset)
189 (type (unsigned-byte 20) count)
190 (values (unsigned-byte 20)))
191 (cond ((= offset bytes-per-scrub-unit)
193 ((zerop (sap-ref-32 ptr offset))
194 (look ptr (+ offset sb!vm:n-word-bytes) count))
196 (scrub ptr offset (+ count sb!vm:n-word-bytes))))))
197 (let* ((csp (sap-int (sb!c::control-stack-pointer-sap)))
198 (initial-offset (logand csp (1- bytes-per-scrub-unit))))
199 (declare (type (unsigned-byte 32) csp))
200 (scrub (int-sap (- csp initial-offset))
201 (* (floor initial-offset sb!vm:n-word-bytes) sb!vm:n-word-bytes)
204 #!+x86 ;; (Stack grows downwards.)
206 ((scrub (ptr offset count)
207 (declare (type system-area-pointer ptr)
208 (type (unsigned-byte 16) offset)
209 (type (unsigned-byte 20) count)
210 (values (unsigned-byte 20)))
211 (let ((loc (int-sap (- (sap-int ptr) (+ offset sb!vm:n-word-bytes)))))
212 (cond ((= offset bytes-per-scrub-unit)
213 (look (int-sap (- (sap-int ptr) bytes-per-scrub-unit))
215 (t ;; need to fix bug in %SET-STACK-REF
216 (setf (sap-ref-32 loc 0) 0)
217 (scrub ptr (+ offset sb!vm:n-word-bytes) count)))))
218 (look (ptr offset count)
219 (declare (type system-area-pointer ptr)
220 (type (unsigned-byte 16) offset)
221 (type (unsigned-byte 20) count)
222 (values (unsigned-byte 20)))
223 (let ((loc (int-sap (- (sap-int ptr) offset))))
224 (cond ((= offset bytes-per-scrub-unit)
226 ((zerop (sb!kernel::get-lisp-obj-address (stack-ref loc 0)))
227 (look ptr (+ offset sb!vm:n-word-bytes) count))
229 (scrub ptr offset (+ count sb!vm:n-word-bytes)))))))
230 (let* ((csp (sap-int (sb!c::control-stack-pointer-sap)))
231 (initial-offset (logand csp (1- bytes-per-scrub-unit))))
232 (declare (type (unsigned-byte 32) csp))
233 (scrub (int-sap (+ csp initial-offset))
234 (* (floor initial-offset sb!vm:n-word-bytes) sb!vm:n-word-bytes)
237 ;;;; the default toplevel function
241 "a list of all the values returned by the most recent top level EVAL")
242 (defvar // nil #!+sb-doc "the previous value of /")
243 (defvar /// nil #!+sb-doc "the previous value of //")
244 (defvar * nil #!+sb-doc "the value of the most recent top level EVAL")
245 (defvar ** nil #!+sb-doc "the previous value of *")
246 (defvar *** nil #!+sb-doc "the previous value of **")
247 (defvar + nil #!+sb-doc "the value of the most recent top level READ")
248 (defvar ++ nil #!+sb-doc "the previous value of +")
249 (defvar +++ nil #!+sb-doc "the previous value of ++")
250 (defvar - nil #!+sb-doc "the form currently being evaluated")
252 (defun interactive-eval (form)
253 "Evaluate FORM, returning whatever it returns and adjusting ***, **, *,
254 +++, ++, +, ///, //, /, and -."
256 (let ((results (multiple-value-list (eval form))))
267 ;; The bogon returned an unbound marker.
268 ;; FIXME: It would be safer to check every one of the values in RESULTS,
269 ;; instead of just the first one.
271 (cerror "Go on with * set to NIL."
272 "EVAL returned an unbound marker."))
275 ;;; Flush anything waiting on one of the ANSI Common Lisp standard
276 ;;; output streams before proceeding.
277 (defun flush-standard-output-streams ()
278 (dolist (name '(*debug-io*
283 (finish-output (symbol-value name)))
286 ;;; the default system top level function
287 (defun toplevel-init ()
289 (/show0 "entering TOPLEVEL-INIT")
291 (let ((sysinit nil) ; value of --sysinit option
292 (userinit nil) ; value of --userinit option
293 (reversed-evals nil) ; values of --eval options, in reverse order
294 (noprint nil) ; Has a --noprint option been seen?
295 (noprogrammer nil) ; Has a --noprogammer option been seen?
296 (options (rest *posix-argv*))) ; skipping program name
298 (/show0 "done with outer LET in TOPLEVEL-INIT")
300 ;; FIXME: There are lots of ways for errors to happen around here
301 ;; (e.g. bad command line syntax, or READ-ERROR while trying to
302 ;; READ an --eval string). Make sure that they're handled
303 ;; reasonably. Also, perhaps all errors while parsing the command
304 ;; line should cause the system to QUIT, instead of trying to go
305 ;; into the Lisp debugger.
307 ;; Parse command line options.
308 (loop while options do
309 (/show0 "at head of LOOP WHILE OPTIONS DO in TOPLEVEL-INIT")
310 (let ((option (first options)))
311 (flet ((pop-option ()
314 (error "unexpected end of command line options"))))
315 (cond ((string= option "--sysinit")
318 (error "multiple --sysinit options")
319 (setf sysinit (pop-option))))
320 ((string= option "--userinit")
323 (error "multiple --userinit options")
324 (setf userinit (pop-option))))
325 ((string= option "--eval")
327 (let ((eval-as-string (pop-option)))
328 (with-input-from-string (eval-stream eval-as-string)
329 (let* ((eof-marker (cons :eof :eof))
330 (eval (read eval-stream nil eof-marker))
331 (eof (read eval-stream nil eof-marker)))
332 (cond ((eq eval eof-marker)
333 (error "unable to parse ~S"
335 ((not (eq eof eof-marker))
336 (error "more than one expression in ~S"
339 (push eval reversed-evals)))))))
340 ((string= option "--noprint")
343 ((string= option "--noprogrammer")
345 (setf noprogrammer t))
346 ((string= option "--end-toplevel-options")
350 ;; Anything we don't recognize as a toplevel
351 ;; option must be the start of user-level
352 ;; options.. except that if we encounter
353 ;; "--end-toplevel-options" after we gave up
354 ;; because we didn't recognize an option as a
355 ;; toplevel option, then the option we gave up on
356 ;; must have been an error. (E.g. in
357 ;; "sbcl --eval '(a)' --eval'(b)' --end-toplevel-options"
358 ;; this test will let us detect that the string
359 ;; "--eval(b)" is an error.)
360 (if (find "--end-toplevel-options" options
362 (error "bad toplevel option: ~S" (first options))
364 (/show0 "done with LOOP WHILE OPTIONS DO in TOPLEVEL-INIT")
366 ;; Excise all the options that we processed, so that only
367 ;; user-level options are left visible to user code.
368 (setf (rest *posix-argv*) options)
370 ;; Handle --noprogrammer option. We intentionally do this
371 ;; early so that it will affect the handling of initialization
372 ;; files and --eval options.
373 (/show0 "handling --noprogrammer option in TOPLEVEL-INIT")
375 (setf *debugger-hook* 'noprogrammer-debugger-hook-fun
376 *debug-io* *error-output*))
378 ;; FIXME: Verify that errors in init files and/or --eval operations
379 ;; lead to reasonable behavior.
381 ;; Handle initialization files.
382 (/show0 "handling initialization files in TOPLEVEL-INIT")
383 (flet (;; If any of POSSIBLE-INIT-FILE-NAMES names a real file,
384 ;; return its truename.
385 (probe-init-files (&rest possible-init-file-names)
386 (/show0 "entering PROBE-INIT-FILES")
389 (and (stringp x) (probe-file x)))
390 possible-init-file-names)
391 (/show0 "leaving PROBE-INIT-FILES"))))
392 (let* ((sbcl-home (posix-getenv "SBCL_HOME"))
393 (sysinit-truename (if sbcl-home
394 (probe-init-files sysinit
399 (probe-init-files sysinit
401 "/usr/local/etc/sbclrc")))
402 (user-home (or (posix-getenv "HOME")
403 (error "The HOME environment variable is unbound, ~
404 so user init file can't be found.")))
405 (userinit-truename (probe-init-files userinit
411 ;; We wrap all the pre-REPL user/system customized startup code
414 ;; (Why not wrap everything, even the stuff above, in this
415 ;; restart? Errors above here are basically command line or
416 ;; Unix environment errors, e.g. a missing file or a typo on
417 ;; the Unix command line, and you don't need to get into Lisp
418 ;; to debug them, you should just start over and do it right
419 ;; at the Unix level. Errors below here are usually errors in
420 ;; user Lisp code, and it might be helpful to let the user
421 ;; reach the REPL in order to help figure out what's going on.)
423 (flet ((process-init-file (truename)
425 (unless (load truename)
426 (error "~S was not successfully loaded." truename))
427 (flush-standard-output-streams))))
428 (process-init-file sysinit-truename)
429 (process-init-file userinit-truename)
431 ;; Process --eval options.
432 (/show0 "handling --eval options in TOPLEVEL-INIT")
433 (dolist (eval (reverse reversed-evals))
434 (/show0 "handling one --eval option in TOPLEVEL-INIT")
436 (flush-standard-output-streams)))
439 "Continue anyway (skipping to toplevel read/eval/print loop)."
440 (/show0 "CONTINUEing from pre-REPL RESTART-CASE")
441 (values)) ; (no-op, just fall through)
443 :report "Quit SBCL (calling #'QUIT, killing the process)."
444 (/show0 "falling through to QUIT from pre-REPL RESTART-CASE")
447 ;; one more time for good measure, in case we fell out of the
448 ;; RESTART-CASE above before one of the flushes in the ordinary
449 ;; flow of control had a chance to operate
450 (flush-standard-output-streams)
452 (/show0 "falling into TOPLEVEL-REPL from TOPLEVEL-INIT")
453 (toplevel-repl noprint)
454 ;; (classic CMU CL error message: "You're certainly a clever child.":-)
455 (critically-unreachable "after TOPLEVEL-REPL"))))
457 ;;; read-eval-print loop for the default system toplevel
458 (defun toplevel-repl (noprint)
459 (/show0 "entering TOPLEVEL-REPL")
460 (let ((* nil) (** nil) (*** nil)
462 (+ nil) (++ nil) (+++ nil)
463 (/// nil) (// nil) (/ nil))
464 ;; WITH-SIMPLE-RESTART doesn't actually restart its body as some
465 ;; (like WHN for an embarrassingly long time ca. 2001-12-07) might
466 ;; think, but instead drops control back out at the end. So when a
467 ;; TOPLEVEL or outermost-ABORT restart happens, we need this outer
468 ;; LOOP wrapper to grab control and start over again. (And it also
469 ;; wraps CATCH 'TOPLEVEL-CATCHER for similar reasons.)
471 (/show0 "about to set up restarts in TOPLEVEL-REPL")
472 ;; There should only be one TOPLEVEL restart, and it's here, so
473 ;; restarting at TOPLEVEL always bounces you all the way out here.
474 (with-simple-restart (toplevel
475 "Restart at toplevel READ/EVAL/PRINT loop.")
476 ;; We add a new ABORT restart for every debugger level, so
477 ;; restarting at ABORT in a nested debugger gets you out to the
478 ;; innermost enclosing debugger, and only when you're in the
479 ;; outermost, unnested debugger level does restarting at ABORT
480 ;; get you out to here.
483 "Reduce debugger level (leaving debugger, returning to toplevel).")
484 (catch 'toplevel-catcher
485 (sb!unix:unix-sigsetmask 0) ; FIXME: What is this for?
487 (critically-unreachable "after REPL")))))))
489 (defun repl (noprint)
490 (/show0 "entering REPL")
491 (let ((eof-marker (cons :eof nil)))
493 ;; FIXME: It seems bad to have GC behavior depend on scrubbing the
494 ;; control stack before each interactive command. Isn't there some
495 ;; way we can convince the GC to just ignore dead areas of the
496 ;; control stack, so that we don't need to rely on this half-measure?
497 (scrub-control-stack)
500 (write-string "* ") ; arbitrary but customary REPL prompt
501 (flush-standard-output-streams))
502 (let ((form (read *standard-input* nil eof-marker)))
503 (cond ((eq form eof-marker)
504 (/show0 "doing QUIT for EOF in REPL")
507 (let ((results (multiple-value-list (interactive-eval form))))
509 (dolist (result results)
511 (prin1 result))))))))))
513 (defun noprogrammer-debugger-hook-fun (condition old-debugger-hook)
514 (declare (ignore old-debugger-hook))
515 (flet ((failure-quit (&key recklessly-p)
516 (/show0 "in FAILURE-QUIT (in noprogrammer debugger hook)")
517 (quit :unix-status 1 :recklessly-p recklessly-p)))
518 ;; This HANDLER-CASE is here mostly to stop output immediately
519 ;; (and fall through to QUIT) when there's an I/O error. Thus,
520 ;; when we're run under a shell script or something, we can die
521 ;; cleanly when the script dies (and our pipes are cut), instead
522 ;; of falling into ldb or something messy like that.
525 (format *error-output*
526 "~&~@<unhandled condition (of type ~S): ~2I~_~A~:>~2%"
529 ;; Flush *ERROR-OUTPUT* even before the BACKTRACE, so that
530 ;; even if we hit an error within BACKTRACE (e.g. a bug in
531 ;; the debugger's own frame-walking code, or a bug in a user
532 ;; PRINT-OBJECT method) we'll at least have the CONDITION
533 ;; printed out before we die.
534 (finish-output *error-output*)
535 ;; (Where to truncate the BACKTRACE is of course arbitrary, but
536 ;; it seems as though we should at least truncate it somewhere.)
537 (sb!debug:backtrace 128 *error-output*)
538 (format *error-output*
539 "~%unhandled condition in --noprogrammer mode, quitting~%")
540 (finish-output *error-output*)
543 ;; We IGNORE-ERRORS here because even %PRIMITIVE PRINT can
544 ;; fail when our output streams are blown away, as e.g. when
545 ;; we're running under a Unix shell script and it dies somehow
546 ;; (e.g. because of a SIGINT). In that case, we might as well
547 ;; just give it up for a bad job, and stop trying to notify
548 ;; the user of anything.
550 ;; Actually, the only way I've run across to exercise the
551 ;; problem is to have more than one layer of shell script.
552 ;; I have a shell script which does
553 ;; time nice -10 sh make.sh "$1" 2>&1 | tee make.tmp
554 ;; and the problem occurs when I interrupt this with Ctrl-C
555 ;; under Linux 2.2.14-5.0 and GNU bash, version 1.14.7(1).
556 ;; I haven't figured out whether it's bash, time, tee, Linux, or
557 ;; what that is responsible, but that it's possible at all
558 ;; means that we should IGNORE-ERRORS here. -- WHN 2001-04-24
560 (%primitive print "Argh! error within --noprogrammer error handling"))
561 (failure-quit :recklessly-p t)))))
563 ;;; a convenient way to get into the assembly-level debugger
565 (%primitive sb!c:halt))