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
28 (defvar *current-catch-block*)
29 (defvar *current-unwind-protect-block*)
30 (defvar *free-interrupt-context-index*))
32 ;;; specials initialized by !COLD-INIT
34 ;;; FIXME: These could be converted to DEFVARs, and the stuff shared
35 ;;; in both #!+GENGC and #!-GENGC (actually everything in #!+GENGC)
36 ;;; could be made non-conditional.
39 (special *gc-inhibit* *already-maybe-gcing*
40 *need-to-collect-garbage*
42 *before-gc-hooks* *after-gc-hooks*
43 #!+x86 *pseudo-atomic-atomic*
44 #!+x86 *pseudo-atomic-interrupted*
45 sb!unix::*interrupts-enabled*
46 sb!unix::*interrupt-pending*
47 *type-system-initialized*)
49 (special *before-gc-hooks* *after-gc-hooks*
51 *type-system-initialized*))
53 (defvar *cold-init-complete-p*)
55 ;;; counts of nested errors (with internal errors double-counted)
56 (defvar *maximum-error-depth*)
57 (defvar *current-error-depth*)
59 ;;;; miscellaneous utilities for working with with TOPLEVEL
61 ;;; Execute BODY in a context where any %END-OF-THE-WORLD (thrown e.g.
62 ;;; by QUIT) is caught and any final processing and return codes are
63 ;;; handled appropriately.
64 (defmacro handling-end-of-the-world (&body body)
65 (let ((caught (gensym "CAUGHT")))
66 `(let ((,caught (catch '%end-of-the-world
67 (/show0 "inside CATCH '%END-OF-THE-WORLD")
69 (/show0 "back from CATCH '%END-OF-THE-WORLD, flushing output")
70 (flush-standard-output-streams)
71 (/show0 "calling UNIX-EXIT")
72 (sb!unix:unix-exit ,caught))))
74 ;;;; working with *CURRENT-ERROR-DEPTH* and *MAXIMUM-ERROR-DEPTH*
76 ;;; INFINITE-ERROR-PROTECT is used by ERROR and friends to keep us out of
78 (defmacro infinite-error-protect (&rest forms)
79 `(unless (infinite-error-protector)
80 (let ((*current-error-depth* (1+ *current-error-depth*)))
83 ;;; a helper function for INFINITE-ERROR-PROTECT
84 (defun infinite-error-protector ()
85 (cond ((not *cold-init-complete-p*)
86 (%primitive print "Argh! error in cold init, halting")
87 (%primitive sb!c:halt))
88 ((or (not (boundp '*current-error-depth*))
89 (not (realp *current-error-depth*))
90 (not (boundp '*maximum-error-depth*))
91 (not (realp *maximum-error-depth*)))
92 (%primitive print "Argh! corrupted error depth, halting")
93 (%primitive sb!c:halt))
94 ((> *current-error-depth* *maximum-error-depth*)
95 (/show0 "in INFINITE-ERROR-PROTECTOR, calling ERROR-ERROR")
99 "KERNEL:*MAXIMUM-ERROR-DEPTH* exceeded.")
104 ;;; FIXME: I had a badly broken version of INFINITE-ERROR-PROTECTOR at
105 ;;; one point (shown below), and SBCL cross-compiled it without
106 ;;; warning about FORMS being undefined. Check whether that problem
107 ;;; (missing warning) is repeatable in the final system and if so, fix
110 (defun infinite-error-protector ()
111 `(cond ((not *cold-init-complete-p*)
112 (%primitive print "Argh! error in cold init, halting")
113 (%primitive sb!c:halt))
114 ((or (not (boundp '*current-error-depth*))
115 (not (realp *current-error-depth*))
116 (not (boundp '*maximum-error-depth*))
117 (not (realp *maximum-error-depth*)))
118 (%primitive print "Argh! corrupted error depth, halting")
119 (%primitive sb!c:halt))
120 ((> *current-error-depth* *maximum-error-depth*)
121 (/show0 "in INFINITE-ERROR-PROTECTOR, calling ERROR-ERROR")
122 (error-error "Help! "
123 *current-error-depth*
125 "KERNEL:*MAXIMUM-ERROR-DEPTH* exceeded.")
129 (/show0 "in INFINITE-ERROR-PROTECTOR, returning normally")
133 ;;;; miscellaneous external functions
135 #!-mp ; The multi-processing version is defined in multi-proc.lisp.
138 "This function causes execution to be suspended for N seconds. N may
139 be any non-negative, non-complex number."
140 (when (or (not (realp n))
142 (error "Invalid argument to SLEEP: ~S.~%~
143 Must be a non-negative, non-complex number."
145 (multiple-value-bind (sec usec)
148 (multiple-value-bind (sec frac)
150 (values sec(truncate frac 1e-6))))
151 (sb!unix:unix-select 0 0 0 0 sec usec))
154 ;;;; SCRUB-CONTROL-STACK
156 (defconstant bytes-per-scrub-unit 2048)
158 (defun scrub-control-stack ()
160 "Zero the unused portion of the control stack so that old objects are not
161 kept alive because of uninitialized stack variables."
162 ;; FIXME: Why do we need to do this instead of just letting GC read
163 ;; the stack pointer and avoid messing with the unused portion of
164 ;; the control stack? (Is this a multithreading thing where there's
165 ;; one control stack and stack pointer per thread, and it might not
166 ;; be easy to tell what a thread's stack pointer value is when
167 ;; looking in from another thread?)
168 (declare (optimize (speed 3) (safety 0))
169 (values (unsigned-byte 20))) ; FIXME: DECLARE VALUES?
171 #!-x86 ; machines where stack grows upwards (I guess) -- WHN 19990906
173 ((scrub (ptr offset count)
174 (declare (type system-area-pointer ptr)
175 (type (unsigned-byte 16) offset)
176 (type (unsigned-byte 20) count)
177 (values (unsigned-byte 20)))
178 (cond ((= offset bytes-per-scrub-unit)
179 (look (sap+ ptr bytes-per-scrub-unit) 0 count))
181 (setf (sap-ref-32 ptr offset) 0)
182 (scrub ptr (+ offset sb!vm:word-bytes) count))))
183 (look (ptr offset count)
184 (declare (type system-area-pointer ptr)
185 (type (unsigned-byte 16) offset)
186 (type (unsigned-byte 20) count)
187 (values (unsigned-byte 20)))
188 (cond ((= offset bytes-per-scrub-unit)
190 ((zerop (sap-ref-32 ptr offset))
191 (look ptr (+ offset sb!vm:word-bytes) count))
193 (scrub ptr offset (+ count sb!vm:word-bytes))))))
194 (let* ((csp (sap-int (sb!c::control-stack-pointer-sap)))
195 (initial-offset (logand csp (1- bytes-per-scrub-unit))))
196 (declare (type (unsigned-byte 32) csp))
197 (scrub (int-sap (- csp initial-offset))
198 (* (floor initial-offset sb!vm:word-bytes) sb!vm:word-bytes)
201 #!+x86 ;; (Stack grows downwards.)
203 ((scrub (ptr offset count)
204 (declare (type system-area-pointer ptr)
205 (type (unsigned-byte 16) offset)
206 (type (unsigned-byte 20) count)
207 (values (unsigned-byte 20)))
208 (let ((loc (int-sap (- (sap-int ptr) (+ offset sb!vm:word-bytes)))))
209 (cond ((= offset bytes-per-scrub-unit)
210 (look (int-sap (- (sap-int ptr) bytes-per-scrub-unit))
212 (t ;; need to fix bug in %SET-STACK-REF
213 (setf (sap-ref-32 loc 0) 0)
214 (scrub ptr (+ offset sb!vm:word-bytes) count)))))
215 (look (ptr offset count)
216 (declare (type system-area-pointer ptr)
217 (type (unsigned-byte 16) offset)
218 (type (unsigned-byte 20) count)
219 (values (unsigned-byte 20)))
220 (let ((loc (int-sap (- (sap-int ptr) offset))))
221 (cond ((= offset bytes-per-scrub-unit)
223 ((zerop (sb!kernel::get-lisp-obj-address (stack-ref loc 0)))
224 (look ptr (+ offset sb!vm:word-bytes) count))
226 (scrub ptr offset (+ count sb!vm:word-bytes)))))))
227 (let* ((csp (sap-int (sb!c::control-stack-pointer-sap)))
228 (initial-offset (logand csp (1- bytes-per-scrub-unit))))
229 (declare (type (unsigned-byte 32) csp))
230 (scrub (int-sap (+ csp initial-offset))
231 (* (floor initial-offset sb!vm:word-bytes) sb!vm:word-bytes)
234 ;;;; the default toplevel function
236 ;;; FIXME: Most stuff below here can probably be byte-compiled.
240 "a list of all the values returned by the most recent top-level EVAL")
241 (defvar // nil #!+sb-doc "the previous value of /")
242 (defvar /// nil #!+sb-doc "the previous value of //")
243 (defvar * nil #!+sb-doc "the value of the most recent top-level EVAL")
244 (defvar ** nil #!+sb-doc "the previous value of *")
245 (defvar *** nil #!+sb-doc "the previous value of **")
246 (defvar + nil #!+sb-doc "the value of the most recent top-level READ")
247 (defvar ++ nil #!+sb-doc "the previous value of +")
248 (defvar +++ nil #!+sb-doc "the previous value of ++")
249 (defvar - nil #!+sb-doc "the form currently being evaluated")
250 (defvar *prompt* "* "
252 "The top-level prompt string. This also may be a function of no arguments
253 that returns a simple-string.")
255 (defun interactive-eval (form)
256 "Evaluate FORM, returning whatever it returns and adjusting ***, **, *,
257 +++, ++, +, ///, //, /, and -."
259 (let ((results (multiple-value-list (eval form))))
270 ;; The bogon returned an unbound marker.
271 ;; FIXME: It would be safer to check every one of the values in RESULTS,
272 ;; instead of just the first one.
274 (cerror "Go on with * set to NIL."
275 "EVAL returned an unbound marker."))
278 ;;; Flush anything waiting on one of the ANSI Common Lisp standard
279 ;;; output streams before proceeding.
280 (defun flush-standard-output-streams ()
281 (dolist (name '(*debug-io*
286 (finish-output (symbol-value name)))
289 ;;; the default system top-level function
290 (defun toplevel-init ()
292 (/show0 "entering TOPLEVEL-INIT")
294 (let ((sysinit nil) ; value of --sysinit option
295 (userinit nil) ; value of --userinit option
296 (reversed-evals nil) ; values of --eval options, in reverse order
297 (noprint nil) ; Has a --noprint option been seen?
298 (noprogrammer nil) ; Has a --noprogammer option been seen?
299 (options (rest *posix-argv*))) ; skipping program name
301 (/show0 "done with outer LET in TOPLEVEL-INIT")
303 ;; FIXME: There are lots of ways for errors to happen around here
304 ;; (e.g. bad command line syntax, or READ-ERROR while trying to
305 ;; READ an --eval string). Make sure that they're handled
306 ;; reasonably. Also, perhaps all errors while parsing the command
307 ;; line should cause the system to QUIT, instead of trying to go
308 ;; into the Lisp debugger.
310 ;; Parse command line options.
311 (loop while options do
312 (/show0 "at head of LOOP WHILE OPTIONS DO in TOPLEVEL-INIT")
313 (let ((option (first options)))
314 (flet ((pop-option ()
317 (error "unexpected end of command line options"))))
318 (cond ((string= option "--sysinit")
321 (error "multiple --sysinit options")
322 (setf sysinit (pop-option))))
323 ((string= option "--userinit")
326 (error "multiple --userinit options")
327 (setf userinit (pop-option))))
328 ((string= option "--eval")
330 (let ((eval-as-string (pop-option)))
331 (with-input-from-string (eval-stream eval-as-string)
332 (let* ((eof-marker (cons :eof :eof))
333 (eval (read eval-stream nil eof-marker))
334 (eof (read eval-stream nil eof-marker)))
335 (cond ((eq eval eof-marker)
336 (error "unable to parse ~S"
338 ((not (eq eof eof-marker))
339 (error "more than one expression in ~S"
342 (push eval reversed-evals)))))))
343 ((string= option "--noprint")
346 ((string= option "--noprogrammer")
348 (setf noprogrammer t))
349 ((string= option "--end-toplevel-options")
353 ;; Anything we don't recognize as a toplevel
354 ;; option must be the start of user-level
355 ;; options.. except that if we encounter
356 ;; "--end-toplevel-options" after we gave up
357 ;; because we didn't recognize an option as a
358 ;; toplevel option, then the option we gave up on
359 ;; must have been an error. (E.g. in
360 ;; "sbcl --eval '(a)' --eval'(b)' --end-toplevel-options"
361 ;; this test will let us detect that the string
362 ;; "--eval(b)" is an error.)
363 (if (find "--end-toplevel-options" options
365 (error "bad toplevel option: ~S" (first options))
367 (/show0 "done with LOOP WHILE OPTIONS DO in TOPLEVEL-INIT")
369 ;; Excise all the options that we processed, so that only
370 ;; user-level options are left visible to user code.
371 (setf (rest *posix-argv*) options)
373 ;; Handle --noprogrammer option. We intentionally do this
374 ;; early so that it will affect the handling of initialization
375 ;; files and --eval options.
376 (/show0 "handling --noprogrammer option in TOPLEVEL-INIT")
378 (setf *debugger-hook* 'noprogrammer-debugger-hook-fun
379 *debug-io* *error-output*))
381 ;; FIXME: Verify that errors in init files and/or --eval operations
382 ;; lead to reasonable behavior.
384 ;; Handle initialization files.
385 (/show0 "handling initialization files in TOPLEVEL-INIT")
386 (flet (;; If any of POSSIBLE-INIT-FILE-NAMES names a real file,
387 ;; return its truename.
388 (probe-init-files (&rest possible-init-file-names)
389 (/show0 "entering PROBE-INIT-FILES")
392 (and (stringp x) (probe-file x)))
393 possible-init-file-names)
394 (/show0 "leaving PROBE-INIT-FILES"))))
395 (let* ((sbcl-home (posix-getenv "SBCL_HOME"))
396 (sysinit-truename (if sbcl-home
397 (probe-init-files sysinit
402 (probe-init-files sysinit
404 "/usr/local/etc/sbclrc")))
405 (user-home (or (posix-getenv "HOME")
406 (error "The HOME environment variable is unbound, ~
407 so user init file can't be found.")))
408 (userinit-truename (probe-init-files userinit
413 (/show0 "assigned SYSINIT-TRUENAME and USERINIT-TRUENAME")
416 ;; We wrap all the pre-REPL user/system customized startup code
419 ;; (Why not wrap everything, even the stuff above, in this
420 ;; restart? Errors above here are basically command line or
421 ;; Unix environment errors, e.g. a missing file or a typo on
422 ;; the Unix command line, and you don't need to get into Lisp
423 ;; to debug them, you should just start over and do it right
424 ;; at the Unix level. Errors below here are usually errors in
425 ;; user Lisp code, and it might be helpful to let the user
426 ;; reach the REPL in order to help figure out what's going on.)
428 (flet ((process-init-file (truename)
430 (unless (load truename)
431 (error "~S was not successfully loaded." truename))
432 (flush-standard-output-streams))))
433 (process-init-file sysinit-truename)
434 (process-init-file userinit-truename)
436 ;; Process --eval options.
437 (/show0 "handling --eval options in TOPLEVEL-INIT")
438 (dolist (eval (reverse reversed-evals))
439 (/show0 "handling one --eval option in TOPLEVEL-INIT")
441 (flush-standard-output-streams)))
443 :report "Continue anyway (skipping to toplevel read/eval/print loop)."
444 (values)) ; (no-op, just fall through)
446 :report "Quit SBCL (calling #'QUIT, killing the process)."
449 ;; one more time for good measure, in case we fell out of the
450 ;; RESTART-CASE above before one of the flushes in the ordinary
451 ;; flow of control had a chance to operate
452 (flush-standard-output-streams)
454 (/show0 "falling into TOPLEVEL-REPL from TOPLEVEL-INIT")
455 (toplevel-repl noprint))))
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 (eof-marker (cons :eof nil)))
466 (/show0 "at head of outer LOOP in TOPLEVEL-REPL")
467 ;; There should only be one TOPLEVEL restart, and it's here, so
468 ;; restarting at TOPLEVEL always bounces you all the way out here.
469 (with-simple-restart (toplevel
470 "Restart at toplevel READ/EVAL/PRINT loop.")
471 ;; We add a new ABORT restart for every debugger level, so
472 ;; restarting at ABORT in a nested debugger gets you out to the
473 ;; innermost enclosing debugger, and only when you're in the
474 ;; outermost, unnested debugger level does restarting at ABORT
475 ;; get you out to here.
476 (with-simple-restart (abort
477 "Reduce debugger level (leaving debugger).")
478 (catch 'top-level-catcher
479 (sb!unix:unix-sigsetmask 0) ; FIXME: What is this for?
480 (/show0 "about to enter inner LOOP in TOPLEVEL-REPL")
481 (loop ; FIXME: Do we need this inner LOOP?
482 ;; FIXME: It seems bad to have GC behavior depend on scrubbing
483 ;; the control stack before each interactive command. Isn't
484 ;; there some way we can convince the GC to just ignore
485 ;; dead areas of the control stack, so that we don't need to
486 ;; rely on this half-measure?
487 (scrub-control-stack)
490 (princ (if (functionp *prompt*)
493 (flush-standard-output-streams))
494 (let ((form (read *standard-input* nil eof-marker)))
495 (if (eq form eof-marker)
498 (multiple-value-list (interactive-eval form))))
500 (dolist (result results)
502 (prin1 result)))))))))))))
504 (defun noprogrammer-debugger-hook-fun (condition old-debugger-hook)
505 (declare (ignore old-debugger-hook))
506 (flet ((failure-quit (&key recklessly-p)
507 (quit :unix-status 1 :recklessly-p recklessly-p)))
508 ;; This HANDLER-CASE is here mostly to stop output immediately
509 ;; (and fall through to QUIT) when there's an I/O error. Thus,
510 ;; when we're run under a shell script or something, we can die
511 ;; cleanly when the script dies (and our pipes are cut), instead
512 ;; of falling into ldb or something messy like that.
515 (format *error-output*
516 "~@<unhandled condition (of type ~S): ~2I~_~A~:>~2%"
519 ;; Flush *ERROR-OUTPUT* even before the BACKTRACE, so that
520 ;; even if we hit an error within BACKTRACE we'll at least
521 ;; have the CONDITION printed out before we die.
522 (finish-output *error-output*)
523 ;; (Where to truncate the BACKTRACE is of course arbitrary, but
524 ;; it seems as though we should at least truncate it somewhere.)
525 (sb!debug:backtrace 128 *error-output*)
526 (format *error-output*
527 "~%unhandled condition in --noprogrammer mode, quitting~%")
528 (finish-output *error-output*)
531 ;; We IGNORE-ERRORS here because even %PRIMITIVE PRINT can
532 ;; fail when our output streams are blown away, as e.g. when
533 ;; we're running under a Unix shell script and it dies somehow
534 ;; (e.g. because of a SIGINT). In that case, we might as well
535 ;; just give it up for a bad job, and stop trying to notify
536 ;; the user of anything.
538 ;; Actually, the only way I've run across to exercise the
539 ;; problem is to have more than one layer of shell script.
540 ;; I have a shell script which does
541 ;; time nice -10 sh make.sh "$1" 2>&1 | tee make.tmp
542 ;; and the problem occurs when I interrupt this with Ctrl-C
543 ;; under Linux 2.2.14-5.0 and GNU bash, version 1.14.7(1).
544 ;; I haven't figured out whether it's bash, time, tee, Linux, or
545 ;; what that is responsible, but that it's possible at all
546 ;; means that we should IGNORE-ERRORS here. -- WHN 2001-04-24
548 (%primitive print "Argh! error within --noprogrammer error handling"))
549 (failure-quit :recklessly-p t)))))
551 ;;; a convenient way to get into the assembly-level debugger
553 (%primitive sb!c:halt))