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