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 sb
!vm
::*current-catch-block
*)
22 (defvar sb
!vm
::*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
* *need-to-collect-garbage
*
29 *before-gc-hooks
* *after-gc-hooks
*
30 #!+x86
*pseudo-atomic-atomic
*
31 #!+x86
*pseudo-atomic-interrupted
*
32 sb
!unix
::*interrupts-enabled
*
33 sb
!unix
::*interrupt-pending
*
34 *type-system-initialized
*))
36 (defvar *cold-init-complete-p
*)
38 ;;; counts of nested errors (with internal errors double-counted)
39 (defvar *maximum-error-depth
*)
40 (defvar *current-error-depth
*)
42 ;;;; miscellaneous utilities for working with with TOPLEVEL
44 ;;; Execute BODY in a context where any %END-OF-THE-WORLD (thrown e.g.
45 ;;; by QUIT) is caught and any final processing and return codes are
46 ;;; handled appropriately.
47 (defmacro handling-end-of-the-world
(&body body
)
48 (with-unique-names (caught)
49 `(let ((,caught
(catch '%end-of-the-world
50 (/show0
"inside CATCH '%END-OF-THE-WORLD")
52 (/show0
"back from CATCH '%END-OF-THE-WORLD, flushing output")
53 (flush-standard-output-streams)
54 (sb!thread
::terminate-session
)
55 (/show0
"calling UNIX-EXIT")
56 (sb!unix
:unix-exit
,caught
))))
58 ;;;; working with *CURRENT-ERROR-DEPTH* and *MAXIMUM-ERROR-DEPTH*
60 ;;; INFINITE-ERROR-PROTECT is used by ERROR and friends to keep us out
62 (defmacro infinite-error-protect
(&rest forms
)
63 `(unless (infinite-error-protector)
64 (/show0
"back from INFINITE-ERROR-PROTECTOR")
65 (let ((*current-error-depth
* (1+ *current-error-depth
*)))
66 (/show0
"in INFINITE-ERROR-PROTECT, incremented error depth")
67 ;; arbitrary truncation
68 #!+sb-show
(sb!debug
:backtrace
8)
71 ;;; a helper function for INFINITE-ERROR-PROTECT
72 (defun infinite-error-protector ()
73 (/show0
"entering INFINITE-ERROR-PROTECTOR, *CURRENT-ERROR-DEPTH*=..")
74 (/hexstr
*current-error-depth
*)
75 (cond ((not *cold-init-complete-p
*)
76 (%primitive print
"Argh! error in cold init, halting")
77 (%primitive sb
!c
:halt
))
78 ((or (not (boundp '*current-error-depth
*))
79 (not (realp *current-error-depth
*))
80 (not (boundp '*maximum-error-depth
*))
81 (not (realp *maximum-error-depth
*)))
82 (%primitive print
"Argh! corrupted error depth, halting")
83 (%primitive sb
!c
:halt
))
84 ((> *current-error-depth
* *maximum-error-depth
*)
85 (/show0
"*MAXIMUM-ERROR-DEPTH*=..")
86 (/hexstr
*maximum-error-depth
*)
87 (/show0
"in INFINITE-ERROR-PROTECTOR, calling ERROR-ERROR")
91 "SB-KERNEL:*MAXIMUM-ERROR-DEPTH* exceeded.")
94 (/show0
"returning normally from INFINITE-ERROR-PROTECTOR")
97 ;;; FIXME: I had a badly broken version of INFINITE-ERROR-PROTECTOR at
98 ;;; one point (shown below), and SBCL cross-compiled it without
99 ;;; warning about FORMS being undefined. Check whether that problem
100 ;;; (missing warning) is repeatable in the final system and if so, fix
103 (defun infinite-error-protector ()
104 `(cond ((not *cold-init-complete-p
*)
105 (%primitive print
"Argh! error in cold init, halting")
106 (%primitive sb
!c
:halt
))
107 ((or (not (boundp '*current-error-depth
*))
108 (not (realp *current-error-depth
*))
109 (not (boundp '*maximum-error-depth
*))
110 (not (realp *maximum-error-depth
*)))
111 (%primitive print
"Argh! corrupted error depth, halting")
112 (%primitive sb
!c
:halt
))
113 ((> *current-error-depth
* *maximum-error-depth
*)
114 (/show0
"in INFINITE-ERROR-PROTECTOR, calling ERROR-ERROR")
115 (error-error "Help! "
116 *current-error-depth
*
118 "SB-KERNEL:*MAXIMUM-ERROR-DEPTH* exceeded.")
122 (/show0
"in INFINITE-ERROR-PROTECTOR, returning normally")
126 ;;;; miscellaneous external functions
130 "This function causes execution to be suspended for N seconds. N may
131 be any non-negative, non-complex number."
132 (when (or (not (realp n
))
134 (error 'simple-type-error
135 :format-control
"invalid argument to SLEEP: ~S"
136 :format-arguments
(list n
)
138 :expected-type
'(real 0)))
139 (multiple-value-bind (sec usec
)
142 (multiple-value-bind (sec frac
)
144 (values sec
(truncate frac
1e-6))))
145 (sb!unix
:unix-select
0 0 0 0 sec usec
))
148 ;;;; SCRUB-CONTROL-STACK
150 (defconstant bytes-per-scrub-unit
2048)
152 ;;; Zero the unused portion of the control stack so that old objects
153 ;;; are not kept alive because of uninitialized stack variables.
155 ;;; "To summarize the problem, since not all allocated stack frame
156 ;;; slots are guaranteed to be written by the time you call an another
157 ;;; function or GC, there may be garbage pointers retained in your
158 ;;; dead stack locations. The stack scrubbing only affects the part
159 ;;; of the stack from the SP to the end of the allocated stack."
160 ;;; - ram, on cmucl-imp, Tue, 25 Sep 2001
162 ;;; So, as an (admittedly lame) workaround, from time to time we call
163 ;;; scrub-control-stack to zero out all the unused portion. This is
164 ;;; supposed to happen when the stack is mostly empty, so that we have
165 ;;; a chance of clearing more of it: callers are currently (2002.07.18)
168 (defun scrub-control-stack ()
169 (declare (optimize (speed 3) (safety 0))
170 (values (unsigned-byte 20))) ; FIXME: DECLARE VALUES?
172 #!-stack-grows-downward-not-upward
173 (let* ((csp (sap-int (sb!c
::control-stack-pointer-sap
)))
174 (initial-offset (logand csp
(1- bytes-per-scrub-unit
)))
176 (- (sb!vm
:fixnumize sb
!vm
:*control-stack-end
*)
177 sb
!c
:*backend-page-size
*)))
179 ((scrub (ptr offset count
)
180 (declare (type system-area-pointer ptr
)
181 (type (unsigned-byte 16) offset
)
182 (type (unsigned-byte 20) count
)
183 (values (unsigned-byte 20)))
184 (cond ((>= (sap-int ptr
) end-of-stack
) 0)
185 ((= offset bytes-per-scrub-unit
)
186 (look (sap+ ptr bytes-per-scrub-unit
) 0 count
))
188 (setf (sap-ref-32 ptr offset
) 0)
189 (scrub ptr
(+ offset sb
!vm
:n-word-bytes
) count
))))
190 (look (ptr offset count
)
191 (declare (type system-area-pointer ptr
)
192 (type (unsigned-byte 16) offset
)
193 (type (unsigned-byte 20) count
)
194 (values (unsigned-byte 20)))
195 (cond ((>= (sap-int ptr
) end-of-stack
) 0)
196 ((= offset bytes-per-scrub-unit
)
198 ((zerop (sap-ref-32 ptr offset
))
199 (look ptr
(+ offset sb
!vm
:n-word-bytes
) count
))
201 (scrub ptr offset
(+ count sb
!vm
:n-word-bytes
))))))
202 (declare (type (unsigned-byte 32) csp
))
203 (scrub (int-sap (- csp initial-offset
))
204 (* (floor initial-offset sb
!vm
:n-word-bytes
) sb
!vm
:n-word-bytes
)
207 #!+stack-grows-downward-not-upward
208 (let* ((csp (sap-int (sb!c
::control-stack-pointer-sap
)))
209 (end-of-stack (+ (sb!vm
:fixnumize sb
!vm
:*control-stack-start
*)
210 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")
300 (sb!thread
::init-job-control
)
301 (sb!thread
::get-foreground
)
302 (let (;; value of --sysinit option
304 ;; value of --userinit option
306 ;; values of --eval options, in reverse order; and also any
307 ;; other options (like --load) which're translated into --eval
309 ;; The values are stored as strings, so that they can be
310 ;; passed to READ only after their predecessors have been
311 ;; EVALed, so that things work when e.g. REQUIRE in one EVAL
312 ;; form creates a package referred to in the next EVAL form.
314 ;; Has a --noprint option been seen?
316 ;; everything in *POSIX-ARGV* except for argv[0]=programname
317 (options (rest *posix-argv
*)))
319 (declare (type list options
))
321 (/show0
"done with outer LET in TOPLEVEL-INIT")
323 ;; FIXME: There are lots of ways for errors to happen around here
324 ;; (e.g. bad command line syntax, or READ-ERROR while trying to
325 ;; READ an --eval string). Make sure that they're handled
328 ;; Process command line options.
329 (flet (;; Errors while processing the command line cause the system
330 ;; to QUIT, instead of trying to go into the Lisp debugger,
331 ;; because trying to go into the Lisp debugger would get
332 ;; into various annoying issues of where we should go after
333 ;; the user tries to return from the debugger.
334 (startup-error (control-string &rest args
)
337 "fatal error before reaching READ-EVAL-PRINT loop: ~% ~?~%"
340 (quit :unix-status
1)))
341 (loop while options do
342 (/show0
"at head of LOOP WHILE OPTIONS DO in TOPLEVEL-INIT")
343 (let ((option (first options
)))
344 (flet ((pop-option ()
348 "unexpected end of command line options"))))
349 (cond ((string= option
"--sysinit")
352 (startup-error "multiple --sysinit options")
353 (setf sysinit
(pop-option))))
354 ((string= option
"--userinit")
357 (startup-error "multiple --userinit options")
358 (setf userinit
(pop-option))))
359 ((string= option
"--eval")
361 (push (pop-option) reversed-evals
))
362 ((string= option
"--load")
365 ;; FIXME: see BUG 296
366 (concatenate 'string
"(|LOAD| \"" (pop-option) "\")")
368 ((string= option
"--noprint")
371 ;; FIXME: --noprogrammer was deprecated in 0.7.5, and
372 ;; in a year or so this backwards compatibility can
374 ((string= option
"--noprogrammer")
375 (warn "treating deprecated --noprogrammer as --disable-debugger")
377 (push "(|DISABLE-DEBUGGER|)" reversed-evals
))
378 ((string= option
"--disable-debugger")
380 (push "(|DISABLE-DEBUGGER|)" reversed-evals
))
381 ((string= option
"--end-toplevel-options")
385 ;; Anything we don't recognize as a toplevel
386 ;; option must be the start of user-level
387 ;; options.. except that if we encounter
388 ;; "--end-toplevel-options" after we gave up
389 ;; because we didn't recognize an option as a
390 ;; toplevel option, then the option we gave up on
391 ;; must have been an error. (E.g. in
392 ;; "sbcl --eval '(a)' --eval'(b)' --end-toplevel-options"
393 ;; this test will let us detect that the string
394 ;; "--eval(b)" is an error.)
395 (if (find "--end-toplevel-options" options
397 (startup-error "bad toplevel option: ~S"
400 (/show0
"done with LOOP WHILE OPTIONS DO in TOPLEVEL-INIT")
402 ;; Delete all the options that we processed, so that only
403 ;; user-level options are left visible to user code.
404 (setf (rest *posix-argv
*) options
)
406 ;; Handle initialization files.
407 (/show0
"handling initialization files in TOPLEVEL-INIT")
408 (flet (;; shared idiom for searching for SYSINITish and
410 (probe-init-files (explicitly-specified-init-file-name
411 &rest default-init-file-names
)
412 (declare (type list default-init-file-names
))
413 (if explicitly-specified-init-file-name
414 (or (probe-file explicitly-specified-init-file-name
)
415 (startup-error "The file ~S was not found."
416 explicitly-specified-init-file-name
))
418 (and (stringp x
) (probe-file x
)))
419 default-init-file-names
)))
420 ;; shared idiom for creating default names for
421 ;; SYSINITish and USERINITish files
422 (init-file-name (maybe-dir-name basename
)
424 (concatenate 'string maybe-dir-name
"/" basename
))))
425 (let ((sysinit-truename
426 (probe-init-files sysinit
427 (init-file-name (posix-getenv "SBCL_HOME")
431 (probe-init-files userinit
432 (init-file-name (posix-getenv "HOME")
435 ;; We wrap all the pre-REPL user/system customized startup code
438 ;; (Why not wrap everything, even the stuff above, in this
439 ;; restart? Errors above here are basically command line or
440 ;; Unix environment errors, e.g. a missing file or a typo on
441 ;; the Unix command line, and you don't need to get into Lisp
442 ;; to debug them, you should just start over and do it right
443 ;; at the Unix level. Errors below here are generally errors
444 ;; in user Lisp code, and it might be helpful to let the user
445 ;; reach the REPL in order to help figure out what's going
449 (flet ((process-init-file (truename)
451 (unless (load truename
)
452 (error "~S was not successfully loaded."
454 (flush-standard-output-streams))))
455 (process-init-file sysinit-truename
)
456 (process-init-file userinit-truename
))
458 ;; Process --eval options.
459 (/show0
"handling --eval options in TOPLEVEL-INIT")
460 (dolist (expr-as-string (reverse reversed-evals
))
461 (/show0
"handling one --eval option in TOPLEVEL-INIT")
462 (let ((expr (with-input-from-string (eval-stream
464 (let* ((eof-marker (cons :eof
:eof
))
465 (result (read eval-stream
468 (eof (read eval-stream nil eof-marker
)))
469 (cond ((eq result eof-marker
)
470 (error "unable to parse ~S"
472 ((not (eq eof eof-marker
))
474 "more than one expression in ~S"
479 (flush-standard-output-streams))))
482 "Continue anyway (skipping to toplevel read/eval/print loop)."
483 (/show0
"CONTINUEing from pre-REPL RESTART-CASE")
484 (values)) ; (no-op, just fall through)
486 :report
"Quit SBCL (calling #'QUIT, killing the process)."
487 (/show0
"falling through to QUIT from pre-REPL RESTART-CASE")
490 ;; one more time for good measure, in case we fell out of the
491 ;; RESTART-CASE above before one of the flushes in the ordinary
492 ;; flow of control had a chance to operate
493 (flush-standard-output-streams)
495 (/show0
"falling into TOPLEVEL-REPL from TOPLEVEL-INIT")
496 (toplevel-repl noprint
)
497 ;; (classic CMU CL error message: "You're certainly a clever child.":-)
498 (critically-unreachable "after TOPLEVEL-REPL")))))
500 ;;; hooks to support customized toplevels like ACL-style toplevel from
501 ;;; KMR on sbcl-devel 2002-12-21. Altered by CSR 2003-11-16 for
502 ;;; threaded operation: altered *REPL-FUN* to *REPL-FUN-GENERATOR*.
503 (defvar *repl-read-form-fun
* #'repl-read-form-fun
504 "a function of two stream arguments IN and OUT for the toplevel REPL to
505 call: Return the next Lisp form to evaluate (possibly handling other
506 magic -- like ACL-style keyword commands -- which precede the next
507 Lisp form). The OUT stream is there to support magic which requires
508 issuing new prompts.")
509 (defvar *repl-prompt-fun
* #'repl-prompt-fun
510 "a function of one argument STREAM for the toplevel REPL to call: Prompt
511 the user for input.")
512 (defvar *repl-fun-generator
* (constantly #'repl-fun
)
513 "a function of no arguments returning a function of one argument
514 NOPRINT that provides the REPL for the system. Assumes that
515 *STANDARD-INPUT* and *STANDARD-OUTPUT* are set up.")
517 ;;; read-eval-print loop for the default system toplevel
518 (defun toplevel-repl (noprint)
519 (/show0
"entering TOPLEVEL-REPL")
520 (let ((* nil
) (** nil
) (*** nil
)
522 (+ nil
) (++ nil
) (+++ nil
)
523 (/// nil
) (// nil
) (/ nil
))
524 (/show0
"about to funcall *REPL-FUN-GENERATOR*")
525 (let ((repl-fun (funcall *repl-fun-generator
*)))
526 ;; Each REPL in a multithreaded world should have bindings of
527 ;; most CL specials (most critically *PACKAGE*).
528 (with-rebound-io-syntax
529 ;; WITH-SIMPLE-RESTART doesn't actually restart its body as
530 ;; some (like WHN for an embarrassingly long time
531 ;; ca. 2001-12-07) might think, but instead drops control back
532 ;; out at the end. So when a TOPLEVEL or outermost-ABORT
533 ;; restart happens, we need this outer LOOP wrapper to grab
534 ;; control and start over again. (And it also wraps CATCH
535 ;; 'TOPLEVEL-CATCHER for similar reasons.)
537 (/show0
"about to set up restarts in TOPLEVEL-REPL")
538 ;; There should only be one TOPLEVEL restart, and it's here,
539 ;; so restarting at TOPLEVEL always bounces you all the way
541 (with-simple-restart (toplevel
542 "Restart at toplevel READ/EVAL/PRINT loop.")
543 ;; We add a new ABORT restart for every debugger level, so
544 ;; restarting at ABORT in a nested debugger gets you out to
545 ;; the innermost enclosing debugger, and only when you're
546 ;; in the outermost, unnested debugger level does
547 ;; restarting at ABORT get you out to here.
550 "~@<Reduce debugger level (leaving debugger, returning to toplevel).~@:>")
551 (catch 'toplevel-catcher
552 (sb!unix
::reset-signal-mask
)
553 ;; In the event of a control-stack-exhausted-error, we
554 ;; should have unwound enough stack by the time we get
555 ;; here that this is now possible.
556 (sb!kernel
::protect-control-stack-guard-page
1)
557 (funcall repl-fun noprint
)
558 (critically-unreachable "after REPL")))))))))
560 ;;; Our default REPL prompt is the minimal traditional one.
561 (defun repl-prompt-fun (stream)
563 (write-string "* " stream
)) ; arbitrary but customary REPL prompt
565 ;;; Our default form reader does relatively little magic, but does
566 ;;; handle the Unix-style EOF-is-end-of-process convention.
567 (defun repl-read-form-fun (in out
)
568 (declare (type stream in out
) (ignore out
))
569 (let* ((eof-marker (cons nil nil
))
570 (form (read in nil eof-marker
)))
571 (if (eq form eof-marker
)
575 (defun repl-fun (noprint)
576 (/show0
"entering REPL")
578 ;; (See comment preceding the definition of SCRUB-CONTROL-STACK.)
579 (scrub-control-stack)
580 (sb!thread
::get-foreground
)
582 (funcall *repl-prompt-fun
* *standard-output
*)
583 ;; (Should *REPL-PROMPT-FUN* be responsible for doing its own
584 ;; FORCE-OUTPUT? I can't imagine a valid reason for it not to
585 ;; be done here, so leaving it up to *REPL-PROMPT-FUN* seems
586 ;; odd. But maybe there *is* a valid reason in some
587 ;; circumstances? perhaps some deadlock issue when being driven
588 ;; by another process or something...)
589 (force-output *standard-output
*))
590 (let* ((form (funcall *repl-read-form-fun
*
593 (results (multiple-value-list (interactive-eval form
))))
595 (dolist (result results
)
599 ;;; a convenient way to get into the assembly-level debugger
601 (%primitive sb
!c
:halt
))