0.pre7.127:
[sbcl.git] / src / code / ntrace.lisp
1 ;;;; a tracing facility based on breakpoints
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
11
12 (in-package "SB-DEBUG") ; (SB-, not SB!, since we're built in warm load.)
13
14 ;;; FIXME: Why, oh why, doesn't the SB-DEBUG package use the SB-DI
15 ;;; package? That would let us get rid of a whole lot of stupid
16 ;;; prefixes..
17
18 (defvar *trace-values* nil
19   #+sb-doc
20   "This is bound to the returned values when evaluating :BREAK-AFTER and
21    :PRINT-AFTER forms.")
22
23 (defvar *trace-indentation-step* 2
24   #+sb-doc
25   "the increase in trace indentation at each call level")
26
27 (defvar *max-trace-indentation* 40
28   #+sb-doc
29   "If the trace indentation exceeds this value, then indentation restarts at
30    0.")
31
32 (defvar *trace-encapsulate-default* :default
33   #+sb-doc
34   "the default value for the :ENCAPSULATE option to TRACE")
35 \f
36 ;;;; internal state
37
38 ;;; a hash table that maps each traced function to the TRACE-INFO. The
39 ;;; entry for a closure is the shared function-entry object.
40 (defvar *traced-funs* (make-hash-table :test 'eq))
41
42 ;;; A TRACE-INFO object represents all the information we need to
43 ;;; trace a given function.
44 (def!struct (trace-info
45              (:make-load-form-fun sb-kernel:just-dump-it-normally)
46              (:print-object (lambda (x stream)
47                               (print-unreadable-object (x stream :type t)
48                                 (prin1 (trace-info-what x) stream)))))
49   ;; the original representation of the thing traced
50   (what nil :type (or function cons symbol))
51   ;; Is WHAT a function name whose definition we should track?
52   (named nil)
53   ;; Is tracing to be done by encapsulation rather than breakpoints?
54   ;; T implies NAMED.
55   (encapsulated *trace-encapsulate-default*)
56   ;; Has this trace been untraced?
57   (untraced nil)
58   ;; breakpoints we set up to trigger tracing
59   (start-breakpoint nil :type (or sb-di:breakpoint null))
60   (end-breakpoint nil :type (or sb-di:breakpoint null))
61   ;; the list of function names for WHEREIN, or NIL if unspecified
62   (wherein nil :type list)
63
64   ;; The following slots represent the forms that we are supposed to
65   ;; evaluate on each iteration. Each form is represented by a cons
66   ;; (Form . Function), where the Function is the cached result of
67   ;; coercing Form to a function. Forms which use the current
68   ;; environment are converted with PREPROCESS-FOR-EVAL, which gives
69   ;; us a one-arg function. Null environment forms also have one-arg
70   ;; functions, but the argument is ignored. NIL means unspecified
71   ;; (the default.)
72
73   ;; current environment forms
74   (condition nil)
75   (break nil)
76   ;; List of current environment forms
77   (print () :type list)
78   ;; null environment forms
79   (condition-after nil)
80   (break-after nil)
81   ;; list of null environment forms
82   (print-after () :type list))
83
84 ;;; This is a list of conses (fun-end-cookie . condition-satisfied),
85 ;;; which we use to note distinct dynamic entries into functions. When
86 ;;; we enter a traced function, we add a entry to this list holding
87 ;;; the new end-cookie and whether the trace condition was satisfied.
88 ;;; We must save the trace condition so that the after breakpoint
89 ;;; knows whether to print. The length of this list tells us the
90 ;;; indentation to use for printing TRACE messages.
91 ;;;
92 ;;; This list also helps us synchronize the TRACE facility dynamically
93 ;;; for detecting non-local flow of control. Whenever execution hits a
94 ;;; :FUN-END breakpoint used for TRACE'ing, we look for the
95 ;;; FUN-END-COOKIE at the top of *TRACED-ENTRIES*. If it is not
96 ;;; there, we discard any entries that come before our cookie.
97 ;;;
98 ;;; When we trace using encapsulation, we bind this variable and add
99 ;;; (NIL . CONDITION-SATISFIED), so a NIL "cookie" marks an
100 ;;; encapsulated tracing.
101 (defvar *traced-entries* ())
102 (declaim (list *traced-entries*))
103
104 ;;; This variable is used to discourage infinite recursions when some
105 ;;; trace action invokes a function that is itself traced. In this
106 ;;; case, we quietly ignore the inner tracing.
107 (defvar *in-trace* nil)
108 \f
109 ;;;; utilities
110
111 ;;; Given a function name, a function or a macro name, return the raw
112 ;;; definition and some information. "Raw" means that if the result is
113 ;;; a closure, we strip off the closure and return the bare code. The
114 ;;; second value is T if the argument was a function name. The third
115 ;;; value is one of :COMPILED, :COMPILED-CLOSURE, :INTERPRETED,
116 ;;; :INTERPRETED-CLOSURE and :FUNCALLABLE-INSTANCE.
117 (defun trace-fdefinition (x)
118   (multiple-value-bind (res named-p)
119       (typecase x
120         (symbol
121          (cond ((special-operator-p x)
122                 (error "can't trace special form ~S" x))
123                ((macro-function x))
124                (t
125                 (values (fdefinition x) t))))
126         (function x)
127         (t (values (fdefinition x) t)))
128     (case (sb-kernel:widetag-of res)
129       (#.sb-vm:closure-header-widetag
130        (values (sb-kernel:%closure-fun res)
131                named-p
132                :compiled-closure))
133       (#.sb-vm:funcallable-instance-header-widetag
134        (values res named-p :funcallable-instance))
135       (t (values res named-p :compiled)))))
136
137 ;;; When a function name is redefined, and we were tracing that name,
138 ;;; then untrace the old definition and trace the new one.
139 (defun trace-redefined-update (fname new-value)
140   (when (fboundp fname)
141     (let* ((fun (trace-fdefinition fname))
142            (info (gethash fun *traced-funs*)))
143       (when (and info (trace-info-named info))
144         (untrace-1 fname)
145         (trace-1 fname info new-value)))))
146 (push #'trace-redefined-update *setf-fdefinition-hook*)
147
148 ;;; Annotate a FORM to evaluate with pre-converted functions. FORM is
149 ;;; really a cons (EXP . FUNCTION). LOC is the code location to use
150 ;;; for the lexical environment. If LOC is NIL, evaluate in the null
151 ;;; environment. If FORM is NIL, just return NIL.
152 (defun coerce-form (form loc)
153   (when form
154     (let ((exp (car form)))
155       (if (sb-di:code-location-p loc)
156           (let ((fun (sb-di:preprocess-for-eval exp loc)))
157             (cons exp
158                   (lambda (frame)
159                     (let ((*current-frame* frame))
160                       (funcall fun frame)))))
161           (let* ((bod (ecase loc
162                         ((nil) exp)
163                         (:encapsulated
164                          `(flet ((sb-debug:arg (n)
165                                    (declare (special argument-list))
166                                    (elt argument-list n)))
167                             (declare (ignorable #'sb-debug:arg))
168                             ,exp))))
169                  (fun (coerce `(lambda () ,bod) 'function)))
170             (cons exp
171                   (lambda (frame)
172                     (declare (ignore frame))
173                     (let ((*current-frame* nil))
174                       (funcall fun)))))))))
175
176 (defun coerce-form-list (forms loc)
177   (mapcar (lambda (x) (coerce-form x loc)) forms))
178
179 ;;; Print indentation according to the number of trace entries.
180 ;;; Entries whose condition was false don't count.
181 (defun print-trace-indentation ()
182   (let ((depth 0))
183     (dolist (entry *traced-entries*)
184       (when (cdr entry) (incf depth)))
185     (format t
186             "~@V,0T~W: "
187             (+ (mod (* depth *trace-indentation-step*)
188                     (- *max-trace-indentation* *trace-indentation-step*))
189                *trace-indentation-step*)
190             depth)))
191
192 ;;; Return true if any of the NAMES appears on the stack below FRAME.
193 (defun trace-wherein-p (frame names)
194   (do ((frame (sb-di:frame-down frame) (sb-di:frame-down frame)))
195       ((not frame) nil)
196     (when (member (sb-di:debug-fun-name (sb-di:frame-debug-fun frame))
197                   names
198                   :test #'equal)
199       (return t))))
200
201 ;;; Handle PRINT and PRINT-AFTER options.
202 (defun trace-print (frame forms)
203   (dolist (ele forms)
204     (fresh-line)
205     (print-trace-indentation)
206     (format t "~@<~S ~_= ~S~:>" (car ele) (funcall (cdr ele) frame))))
207
208 ;;; Test a BREAK option, and break if true.
209 (defun trace-maybe-break (info break where frame)
210   (when (and break (funcall (cdr break) frame))
211     (sb-di:flush-frames-above frame)
212     (let ((*stack-top-hint* frame))
213       (break "breaking ~A traced call to ~S:"
214              where
215              (trace-info-what info)))))
216
217 ;;; Discard any invalid cookies on our simulated stack. Encapsulated
218 ;;; entries are always valid, since we bind *TRACED-ENTRIES* in the
219 ;;; encapsulation.
220 (defun discard-invalid-entries (frame)
221   (loop
222     (when (or (null *traced-entries*)
223               (let ((cookie (caar *traced-entries*)))
224                 (or (not cookie)
225                     (sb-di:fun-end-cookie-valid-p frame cookie))))
226       (return))
227     (pop *traced-entries*)))
228 \f
229 ;;;; hook functions
230
231 ;;; Return a closure that can be used for a function start breakpoint
232 ;;; hook function and a closure that can be used as the
233 ;;; FUN-END-COOKIE function. The first communicates the sense of
234 ;;; the Condition to the second via a closure variable.
235 (defun trace-start-breakpoint-fun (info)
236   (let (conditionp)
237     (values
238
239      (lambda (frame bpt)
240        (declare (ignore bpt))
241        (discard-invalid-entries frame)
242        (let ((condition (trace-info-condition info))
243              (wherein (trace-info-wherein info)))
244          (setq conditionp
245                (and (not *in-trace*)
246                     (or (not condition)
247                         (funcall (cdr condition) frame))
248                     (or (not wherein)
249                         (trace-wherein-p frame wherein)))))
250        (when conditionp
251          (let ((sb-kernel:*current-level* 0)
252                (*standard-output* *trace-output*)
253                (*in-trace* t))
254            (fresh-line)
255            (print-trace-indentation)
256            (if (trace-info-encapsulated info)
257                (locally (declare (special basic-definition argument-list))
258                         (prin1 `(,(trace-info-what info) ,@argument-list)))
259                (print-frame-call frame))
260            (terpri)
261            (trace-print frame (trace-info-print info)))
262          (trace-maybe-break info (trace-info-break info) "before" frame)))
263
264      (lambda (frame cookie)
265        (declare (ignore frame))
266        (push (cons cookie conditionp) *traced-entries*)))))
267
268 ;;; This prints a representation of the return values delivered.
269 ;;; First, this checks to see that cookie is at the top of
270 ;;; *TRACED-ENTRIES*; if it is not, then we need to adjust this list
271 ;;; to determine the correct indentation for output. We then check to
272 ;;; see whether the function is still traced and that the condition
273 ;;; succeeded before printing anything.
274 (defun trace-end-breakpoint-fun (info)
275   (lambda (frame bpt *trace-values* cookie)
276     (declare (ignore bpt))
277     (unless (eq cookie (caar *traced-entries*))
278       (setf *traced-entries*
279             (member cookie *traced-entries* :key #'car)))
280
281     (let ((entry (pop *traced-entries*)))
282       (when (and (not (trace-info-untraced info))
283                  (or (cdr entry)
284                      (let ((cond (trace-info-condition-after info)))
285                        (and cond (funcall (cdr cond) frame)))))
286         (let ((sb-kernel:*current-level* 0)
287               (*standard-output* *trace-output*)
288               (*in-trace* t))
289           (fresh-line)
290           (pprint-logical-block (*standard-output* nil)
291             (print-trace-indentation)
292             (pprint-indent :current 2)
293             (format t "~S returned" (trace-info-what info))
294             (dolist (v *trace-values*)
295               (write-char #\space)
296               (pprint-newline :linear)
297               (prin1 v)))
298           (terpri)
299           (trace-print frame (trace-info-print-after info)))
300         (trace-maybe-break info
301                            (trace-info-break-after info)
302                            "after"
303                            frame)))))
304 \f
305 ;;; This function is called by the trace encapsulation. It calls the
306 ;;; breakpoint hook functions with NIL for the breakpoint and cookie,
307 ;;; which we have cleverly contrived to work for our hook functions.
308 (defun trace-call (info)
309   (multiple-value-bind (start cookie) (trace-start-breakpoint-fun info)
310     (let ((frame (sb-di:frame-down (sb-di:top-frame))))
311       (funcall start frame nil)
312       (let ((*traced-entries* *traced-entries*))
313         (declare (special basic-definition argument-list))
314         (funcall cookie frame nil)
315         (let ((vals
316                (multiple-value-list
317                 (apply basic-definition argument-list))))
318           (funcall (trace-end-breakpoint-fun info) frame nil vals nil)
319           (values-list vals))))))
320 \f
321 ;;; Trace one function according to the specified options. We copy the
322 ;;; trace info (it was a quoted constant), fill in the functions, and
323 ;;; then install the breakpoints or encapsulation.
324 ;;;
325 ;;; If non-null, DEFINITION is the new definition of a function that
326 ;;; we are automatically retracing.
327 (defun trace-1 (function-or-name info &optional definition)
328   (multiple-value-bind (fun named kind)
329       (if definition
330           (values definition t
331                   (nth-value 2 (trace-fdefinition definition)))
332           (trace-fdefinition function-or-name))
333     (when (gethash fun *traced-funs*)
334       (warn "~S is already TRACE'd, untracing it." function-or-name)
335       (untrace-1 fun))
336
337     (let* ((debug-fun (sb-di:fun-debug-fun fun))
338            (encapsulated
339             (if (eq (trace-info-encapsulated info) :default)
340                 (ecase kind
341                   (:compiled nil)
342                   (:compiled-closure
343                    (unless (functionp function-or-name)
344                      (warn "tracing shared code for ~S:~%  ~S"
345                            function-or-name
346                            fun))
347                    nil)
348                   ((:interpreted :interpreted-closure :funcallable-instance)
349                    t))
350                 (trace-info-encapsulated info)))
351            (loc (if encapsulated
352                     :encapsulated
353                     (sb-di:debug-fun-start-location debug-fun)))
354            (info (make-trace-info
355                   :what function-or-name
356                   :named named
357                   :encapsulated encapsulated
358                   :wherein (trace-info-wherein info)
359                   :condition (coerce-form (trace-info-condition info) loc)
360                   :break (coerce-form (trace-info-break info) loc)
361                   :print (coerce-form-list (trace-info-print info) loc)
362                   :break-after (coerce-form (trace-info-break-after info) nil)
363                   :condition-after
364                   (coerce-form (trace-info-condition-after info) nil)
365                   :print-after
366                   (coerce-form-list (trace-info-print-after info) nil))))
367
368       (dolist (wherein (trace-info-wherein info))
369         (unless (or (stringp wherein)
370                     (fboundp wherein))
371           (warn ":WHEREIN name ~S is not a defined global function."
372                 wherein)))
373
374       (cond
375        (encapsulated
376         (unless named
377           (error "can't use encapsulation to trace anonymous function ~S"
378                  fun))
379         (encapsulate function-or-name 'trace `(trace-call ',info)))
380        (t
381         (multiple-value-bind (start-fun cookie-fun)
382             (trace-start-breakpoint-fun info)
383           (let ((start (sb-di:make-breakpoint start-fun debug-fun
384                                               :kind :fun-start))
385                 (end (sb-di:make-breakpoint
386                       (trace-end-breakpoint-fun info)
387                       debug-fun :kind :fun-end
388                       :fun-end-cookie cookie-fun)))
389             (setf (trace-info-start-breakpoint info) start)
390             (setf (trace-info-end-breakpoint info) end)
391             ;; The next two forms must be in the order in which they
392             ;; appear, since the start breakpoint must run before the
393             ;; fun-end breakpoint's start helper (which calls the
394             ;; cookie function.) One reason is that cookie function
395             ;; requires that the CONDITIONP shared closure variable be
396             ;; initialized.
397             (sb-di:activate-breakpoint start)
398             (sb-di:activate-breakpoint end)))))
399
400       (setf (gethash fun *traced-funs*) info)))
401
402   function-or-name)
403 \f
404 ;;;; the TRACE macro
405
406 ;;; Parse leading trace options off of SPECS, modifying INFO
407 ;;; accordingly. The remaining portion of the list is returned when we
408 ;;; encounter a plausible function name.
409 (defun parse-trace-options (specs info)
410   (let ((current specs))
411     (loop
412       (when (endp current) (return))
413       (let ((option (first current))
414             (value (cons (second current) nil)))
415         (case option
416           (:report (error "stub: The :REPORT option is not yet implemented."))
417           (:condition (setf (trace-info-condition info) value))
418           (:condition-after
419            (setf (trace-info-condition info) (cons nil nil))
420            (setf (trace-info-condition-after info) value))
421           (:condition-all
422            (setf (trace-info-condition info) value)
423            (setf (trace-info-condition-after info) value))
424           (:wherein
425            (setf (trace-info-wherein info)
426                  (if (listp (car value)) (car value) value)))
427           (:encapsulate
428            (setf (trace-info-encapsulated info) (car value)))
429           (:break (setf (trace-info-break info) value))
430           (:break-after (setf (trace-info-break-after info) value))
431           (:break-all
432            (setf (trace-info-break info) value)
433            (setf (trace-info-break-after info) value))
434           (:print
435            (setf (trace-info-print info)
436                  (append (trace-info-print info) (list value))))
437           (:print-after
438            (setf (trace-info-print-after info)
439                  (append (trace-info-print-after info) (list value))))
440           (:print-all
441            (setf (trace-info-print info)
442                  (append (trace-info-print info) (list value)))
443            (setf (trace-info-print-after info)
444                  (append (trace-info-print-after info) (list value))))
445           (t (return)))
446         (pop current)
447         (unless current
448           (error "missing argument to ~S TRACE option" option))
449         (pop current)))
450     current))
451
452 ;;; Compute the expansion of TRACE in the non-trivial case (arguments
453 ;;; specified.) If there are no :FUNCTION specs, then don't use a LET.
454 ;;; This allows TRACE to be used without the full interpreter.
455 (defun expand-trace (specs)
456   (collect ((binds)
457             (forms))
458     (let* ((global-options (make-trace-info))
459            (current (parse-trace-options specs global-options)))
460       (loop
461         (when (endp current) (return))
462         (let ((name (pop current))
463               (options (copy-trace-info global-options)))
464           (cond
465            ((eq name :function)
466             (let ((temp (gensym)))
467               (binds `(,temp ,(pop current)))
468               (forms `(trace-1 ,temp ',options))))
469            ((and (keywordp name)
470                  (not (or (fboundp name) (macro-function name))))
471             (error "unknown TRACE option: ~S" name))
472            (t
473             (forms `(trace-1 ',name ',options))))
474           (setq current (parse-trace-options current options)))))
475
476     (if (binds)
477         `(let ,(binds) (list ,@(forms)))
478         `(list ,@(forms)))))
479
480 (defun %list-traced-funs ()
481   (loop for x being each hash-value in *traced-funs*
482         collect (trace-info-what x)))
483
484 (defmacro trace (&rest specs)
485   #+sb-doc
486   "TRACE {Option Global-Value}* {Name {Option Value}*}*
487    TRACE is a debugging tool that provides information when specified functions
488    are called. In its simplest form:
489        (trace Name-1 Name-2 ...)
490    (The Names are not evaluated.)
491
492    Options allow modification of the default behavior. Each option is a pair
493    of an option keyword and a value form. Global options are specified before
494    the first name, and affect all functions traced by a given use of TRACE.
495    Options may also be interspersed with function names, in which case they
496    act as local options, only affecting tracing of the immediately preceding
497    function name. Local options override global options.
498
499    By default, TRACE causes a printout on *TRACE-OUTPUT* each time that
500    one of the named functions is entered or returns. (This is the
501    basic, ANSI Common Lisp behavior of TRACE.) As an SBCL extension, the
502    :REPORT SB-EXT:PROFILE option can be used to instead cause information
503    to be silently recorded to be inspected later using the SB-EXT:PROFILE
504    function.
505
506    The following options are defined:
507
508    :REPORT Report-Type
509        If Report-Type is TRACE (the default) then information is reported
510        by printing immediately. If Report-Type is SB-EXT:PROFILE, information
511        is recorded for later summary by calls to SB-EXT:PROFILE. If
512        Report-Type is NIL, then the only effect of the trace is to execute
513        other options (e.g. PRINT or BREAK).
514
515    :CONDITION Form
516    :CONDITION-AFTER Form
517    :CONDITION-ALL Form
518        If :CONDITION is specified, then TRACE does nothing unless Form
519        evaluates to true at the time of the call. :CONDITION-AFTER is
520        similar, but suppresses the initial printout, and is tested when the
521        function returns. :CONDITION-ALL tries both before and after.
522
523    :BREAK Form
524    :BREAK-AFTER Form
525    :BREAK-ALL Form
526        If specified, and Form evaluates to true, then the debugger is invoked
527        at the start of the function, at the end of the function, or both,
528        according to the respective option. 
529
530    :PRINT Form
531    :PRINT-AFTER Form
532    :PRINT-ALL Form
533        In addition to the usual printout, the result of evaluating Form is
534        printed at the start of the function, at the end of the function, or
535        both, according to the respective option. Multiple print options cause
536        multiple values to be printed.
537
538    :WHEREIN Names
539        If specified, Names is a function name or list of names. TRACE does
540        nothing unless a call to one of those functions encloses the call to
541        this function (i.e. it would appear in a backtrace.)  Anonymous
542        functions have string names like \"DEFUN FOO\". 
543
544    :ENCAPSULATE {:DEFAULT | T | NIL}
545        If T, the tracing is done via encapsulation (redefining the function
546        name) rather than by modifying the function. :DEFAULT is the default,
547        and means to use encapsulation for interpreted functions and funcallable
548        instances, breakpoints otherwise. When encapsulation is used, forms are
549        *not* evaluated in the function's lexical environment, but SB-DEBUG:ARG
550        can still be used.
551
552    :FUNCTION Function-Form
553        This is a not really an option, but rather another way of specifying
554        what function to trace. The Function-Form is evaluated immediately,
555        and the resulting function is traced.
556
557    :CONDITION, :BREAK and :PRINT forms are evaluated in the lexical environment
558    of the called function; SB-DEBUG:VAR and SB-DEBUG:ARG can be used. The
559    -AFTER and -ALL forms are evaluated in the null environment."
560   (if specs
561       (expand-trace specs)
562       '(%list-traced-funs)))
563 \f
564 ;;;; untracing
565
566 ;;; Untrace one function.
567 (defun untrace-1 (function-or-name)
568   (let* ((fun (trace-fdefinition function-or-name))
569          (info (gethash fun *traced-funs*)))
570     (cond
571      ((not info)
572       (warn "Function is not TRACEd: ~S" function-or-name))
573      (t
574       (cond
575        ((trace-info-encapsulated info)
576         (unencapsulate (trace-info-what info) 'trace))
577        (t
578         (sb-di:delete-breakpoint (trace-info-start-breakpoint info))
579         (sb-di:delete-breakpoint (trace-info-end-breakpoint info))))
580       (setf (trace-info-untraced info) t)
581       (remhash fun *traced-funs*)))))
582
583 ;;; Untrace all traced functions.
584 (defun untrace-all ()
585   (dolist (fun (%list-traced-funs))
586     (untrace-1 fun))
587   t)
588
589 (defmacro untrace (&rest specs)
590   #+sb-doc
591   "Remove tracing from the specified functions. With no args, untrace all
592    functions."
593   (if specs
594       (collect ((res))
595         (let ((current specs))
596           (loop
597             (unless current (return))
598             (let ((name (pop current)))
599               (res (if (eq name :function)
600                        `(untrace-1 ,(pop current))
601                        `(untrace-1 ',name)))))
602           `(progn ,@(res) t)))
603       '(untrace-all)))