0.6.11.45:
[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")
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-functions* (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 (function-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 ;;; :FUNCTION-END breakpoint used for TRACE'ing, we look for the
95 ;;; FUNCTION-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     (if (sb-eval:interpreted-function-p res)
129         (values res named-p (if (sb-eval:interpreted-function-closure res)
130                                 :interpreted-closure :interpreted))
131         (case (sb-kernel:get-type res)
132           (#.sb-vm:closure-header-type
133            (values (sb-kernel:%closure-function res)
134                    named-p
135                    :compiled-closure))
136           (#.sb-vm:funcallable-instance-header-type
137            (values res named-p :funcallable-instance))
138           (t (values res named-p :compiled))))))
139
140 ;;; When a function name is redefined, and we were tracing that name,
141 ;;; then untrace the old definition and trace the new one.
142 (defun trace-redefined-update (fname new-value)
143   (when (fboundp fname)
144     (let* ((fun (trace-fdefinition fname))
145            (info (gethash fun *traced-functions*)))
146       (when (and info (trace-info-named info))
147         (untrace-1 fname)
148         (trace-1 fname info new-value)))))
149 (push #'trace-redefined-update *setf-fdefinition-hook*)
150
151 ;;; Annotate some forms to evaluate with pre-converted functions. Each
152 ;;; form is really a cons (exp . function). Loc is the code location
153 ;;; to use for the lexical environment. If Loc is NIL, evaluate in the
154 ;;; null environment. If Form is NIL, just return NIL.
155 (defun coerce-form (form loc)
156   (when form
157     (let ((exp (car form)))
158       (if (sb-di:code-location-p loc)
159           (let ((fun (sb-di:preprocess-for-eval exp loc)))
160             (cons exp
161                   #'(lambda (frame)
162                       (let ((*current-frame* frame))
163                         (funcall fun frame)))))
164           (let* ((bod (ecase loc
165                         ((nil) exp)
166                         (:encapsulated
167                          `(flet ((sb-debug:arg (n)
168                                    (declare (special argument-list))
169                                    (elt argument-list n)))
170                             (declare (ignorable #'sb-debug:arg))
171                             ,exp))))
172                  (fun (coerce `(lambda () ,bod) 'function)))
173             (cons exp
174                   #'(lambda (frame)
175                       (declare (ignore frame))
176                       (let ((*current-frame* nil))
177                         (funcall fun)))))))))
178 (defun coerce-form-list (forms loc)
179   (mapcar #'(lambda (x) (coerce-form x loc)) forms))
180
181 ;;; Print indentation according to the number of trace entries.
182 ;;; Entries whose condition was false don't count.
183 (defun print-trace-indentation ()
184   (let ((depth 0))
185     (dolist (entry *traced-entries*)
186       (when (cdr entry) (incf depth)))
187     (format t
188             "~@V,0T~D: "
189             (+ (mod (* depth *trace-indentation-step*)
190                     (- *max-trace-indentation* *trace-indentation-step*))
191                *trace-indentation-step*)
192             depth)))
193
194 ;;; Return true if one of the Names appears on the stack below Frame.
195 (defun trace-wherein-p (frame names)
196   (do ((frame (sb-di:frame-down frame) (sb-di:frame-down frame)))
197       ((not frame) nil)
198     (when (member (sb-di:debug-function-name (sb-di:frame-debug-function
199                                               frame))
200                   names
201                   :test #'equal)
202       (return t))))
203
204 ;;; Handle print and print-after options.
205 (defun trace-print (frame forms)
206   (dolist (ele forms)
207     (fresh-line)
208     (print-trace-indentation)
209     (format t "~S = ~S" (car ele) (funcall (cdr ele) frame))))
210
211 ;;; Test a break option, and break if true.
212 (defun trace-maybe-break (info break where frame)
213   (when (and break (funcall (cdr break) frame))
214     (sb-di:flush-frames-above frame)
215     (let ((*stack-top-hint* frame))
216       (break "breaking ~A traced call to ~S:"
217              where
218              (trace-info-what info)))))
219
220 ;;; This function discards any invalid cookies on our simulated stack.
221 ;;; Encapsulated entries are always valid, since we bind
222 ;;; *TRACED-ENTRIES* in the encapsulation.
223 (defun discard-invalid-entries (frame)
224   (loop
225     (when (or (null *traced-entries*)
226               (let ((cookie (caar *traced-entries*)))
227                 (or (not cookie)
228                     (sb-di:function-end-cookie-valid-p frame cookie))))
229       (return))
230     (pop *traced-entries*)))
231 \f
232 ;;;; hook functions
233
234 ;;; Return a closure that can be used for a function start breakpoint
235 ;;; hook function and a closure that can be used as the
236 ;;; FUNCTION-END-COOKIE function. The first communicates the sense of
237 ;;; the Condition to the second via a closure variable.
238 (defun trace-start-breakpoint-fun (info)
239   (let (conditionp)
240     (values
241      #'(lambda (frame bpt)
242          (declare (ignore bpt))
243          (discard-invalid-entries frame)
244          (let ((condition (trace-info-condition info))
245                (wherein (trace-info-wherein info)))
246            (setq conditionp
247                  (and (not *in-trace*)
248                       (or (not condition)
249                           (funcall (cdr condition) frame))
250                       (or (not wherein)
251                           (trace-wherein-p frame wherein)))))
252
253          (when conditionp
254            (let ((sb-kernel:*current-level* 0)
255                  (*standard-output* *trace-output*)
256                  (*in-trace* t))
257              (fresh-line)
258              (print-trace-indentation)
259              (if (trace-info-encapsulated info)
260                  (locally (declare (special basic-definition argument-list))
261                    (prin1 `(,(trace-info-what info) ,@argument-list)))
262                  (print-frame-call frame))
263              (terpri)
264              (trace-print frame (trace-info-print info)))
265            (trace-maybe-break info (trace-info-break info) "before" frame)))
266
267      #'(lambda (frame cookie)
268          (declare (ignore frame))
269          (push (cons cookie conditionp) *traced-entries*)))))
270
271 ;;; This prints a representation of the return values delivered.
272 ;;; First, this checks to see that cookie is at the top of
273 ;;; *TRACED-ENTRIES*; if it is not, then we need to adjust this list
274 ;;; to determine the correct indentation for output. We then check to
275 ;;; see whether the function is still traced and that the condition
276 ;;; succeeded before printing anything.
277 (defun trace-end-breakpoint-fun (info)
278   #'(lambda (frame bpt *trace-values* cookie)
279       (declare (ignore bpt))
280       (unless (eq cookie (caar *traced-entries*))
281         (setf *traced-entries*
282               (member cookie *traced-entries* :key #'car)))
283
284       (let ((entry (pop *traced-entries*)))
285         (when (and (not (trace-info-untraced info))
286                    (or (cdr entry)
287                        (let ((cond (trace-info-condition-after info)))
288                          (and cond (funcall (cdr cond) frame)))))
289           (let ((sb-kernel:*current-level* 0)
290                 (*standard-output* *trace-output*)
291                 (*in-trace* t))
292             (fresh-line)
293             (pprint-logical-block (*standard-output* nil)
294               (print-trace-indentation)
295               (pprint-indent :current 2)
296               (format t "~S returned" (trace-info-what info))
297               (dolist (v *trace-values*)
298                 (write-char #\space)
299                 (pprint-newline :linear)
300                 (prin1 v)))
301             (terpri)
302             (trace-print frame (trace-info-print-after info)))
303           (trace-maybe-break info
304                              (trace-info-break-after info)
305                              "after"
306                              frame)))))
307 \f
308 ;;; This function is called by the trace encapsulation. It calls the
309 ;;; breakpoint hook functions with NIL for the breakpoint and cookie, which
310 ;;; we have cleverly contrived to work for our hook functions.
311 (defun trace-call (info)
312   (multiple-value-bind (start cookie) (trace-start-breakpoint-fun info)
313     (let ((frame (sb-di:frame-down (sb-di:top-frame))))
314       (funcall start frame nil)
315       (let ((*traced-entries* *traced-entries*))
316         (declare (special basic-definition argument-list))
317         (funcall cookie frame nil)
318         (let ((vals
319                (multiple-value-list
320                 (apply basic-definition argument-list))))
321           (funcall (trace-end-breakpoint-fun info) frame nil vals nil)
322           (values-list vals))))))
323 \f
324 ;;; Trace one function according to the specified options. We copy the
325 ;;; trace info (it was a quoted constant), fill in the functions, and
326 ;;; then install the breakpoints or encapsulation.
327 ;;;
328 ;;; If non-null, DEFINITION is the new definition of a function that
329 ;;; we are automatically retracing.
330 (defun trace-1 (function-or-name info &optional definition)
331   (multiple-value-bind (fun named kind)
332       (if definition
333           (values definition t
334                   (nth-value 2 (trace-fdefinition definition)))
335           (trace-fdefinition function-or-name))
336     (when (gethash fun *traced-functions*)
337       (warn "~S is already TRACE'd, untracing it." function-or-name)
338       (untrace-1 fun))
339
340     (let* ((debug-fun (sb-di:function-debug-function fun))
341            (encapsulated
342             (if (eq (trace-info-encapsulated info) :default)
343                 (ecase kind
344                   (:compiled nil)
345                   (:compiled-closure
346                    (unless (functionp function-or-name)
347                      (warn "Tracing shared code for ~S:~%  ~S"
348                            function-or-name
349                            fun))
350                    nil)
351                   ((:interpreted :interpreted-closure :funcallable-instance)
352                    t))
353                 (trace-info-encapsulated info)))
354            (loc (if encapsulated
355                     :encapsulated
356                     (sb-di:debug-function-start-location debug-fun)))
357            (info (make-trace-info
358                   :what function-or-name
359                   :named named
360                   :encapsulated encapsulated
361                   :wherein (trace-info-wherein info)
362                   :condition (coerce-form (trace-info-condition info) loc)
363                   :break (coerce-form (trace-info-break info) loc)
364                   :print (coerce-form-list (trace-info-print info) loc)
365                   :break-after (coerce-form (trace-info-break-after info) nil)
366                   :condition-after
367                   (coerce-form (trace-info-condition-after info) nil)
368                   :print-after
369                   (coerce-form-list (trace-info-print-after info) nil))))
370
371       (dolist (wherein (trace-info-wherein info))
372         (unless (or (stringp wherein)
373                     (fboundp wherein))
374           (warn ":WHEREIN name ~S is not a defined global function."
375                 wherein)))
376
377       (cond
378        (encapsulated
379         (unless named
380           (error "can't use encapsulation to trace anonymous function ~S"
381                  fun))
382         (encapsulate function-or-name 'trace `(trace-call ',info)))
383        (t
384         (multiple-value-bind (start-fun cookie-fun)
385             (trace-start-breakpoint-fun info)
386           (let ((start (sb-di:make-breakpoint start-fun debug-fun
387                                               :kind :function-start))
388                 (end (sb-di:make-breakpoint
389                       (trace-end-breakpoint-fun info)
390                       debug-fun :kind :function-end
391                       :function-end-cookie cookie-fun)))
392             (setf (trace-info-start-breakpoint info) start)
393             (setf (trace-info-end-breakpoint info) end)
394             ;; The next two forms must be in the order in which they
395             ;; appear, since the start breakpoint must run before the
396             ;; function-end breakpoint's start helper (which calls the
397             ;; cookie function.) One reason is that cookie function
398             ;; requires that the CONDITIONP shared closure variable be
399             ;; initialized.
400             (sb-di:activate-breakpoint start)
401             (sb-di:activate-breakpoint end)))))
402
403       (setf (gethash fun *traced-functions*) info)))
404
405   function-or-name)
406 \f
407 ;;;; the TRACE macro
408
409 ;;; Parse leading trace options off of SPECS, modifying INFO
410 ;;; accordingly. The remaining portion of the list is returned when we
411 ;;; encounter a plausible function name.
412 (defun parse-trace-options (specs info)
413   (let ((current specs))
414     (loop
415       (when (endp current) (return))
416       (let ((option (first current))
417             (value (cons (second current) nil)))
418         (case option
419           (:report (error "stub: The :REPORT option is not yet implemented."))
420           (:condition (setf (trace-info-condition info) value))
421           (:condition-after
422            (setf (trace-info-condition info) (cons nil nil))
423            (setf (trace-info-condition-after info) value))
424           (:condition-all
425            (setf (trace-info-condition info) value)
426            (setf (trace-info-condition-after info) value))
427           (:wherein
428            (setf (trace-info-wherein info)
429                  (if (listp (car value)) (car value) value)))
430           (:encapsulate
431            (setf (trace-info-encapsulated info) (car value)))
432           (:break (setf (trace-info-break info) value))
433           (:break-after (setf (trace-info-break-after info) value))
434           (:break-all
435            (setf (trace-info-break info) value)
436            (setf (trace-info-break-after info) value))
437           (:print
438            (setf (trace-info-print info)
439                  (append (trace-info-print info) (list value))))
440           (:print-after
441            (setf (trace-info-print-after info)
442                  (append (trace-info-print-after info) (list value))))
443           (:print-all
444            (setf (trace-info-print info)
445                  (append (trace-info-print info) (list value)))
446            (setf (trace-info-print-after info)
447                  (append (trace-info-print-after info) (list value))))
448           (t (return)))
449         (pop current)
450         (unless current
451           (error "missing argument to ~S TRACE option" option))
452         (pop current)))
453     current))
454
455 ;;; Compute the expansion of TRACE in the non-trivial case (arguments
456 ;;; specified.) If there are no :FUNCTION specs, then don't use a LET.
457 ;;; This allows TRACE to be used without the full interpreter.
458 (defun expand-trace (specs)
459   (collect ((binds)
460             (forms))
461     (let* ((global-options (make-trace-info))
462            (current (parse-trace-options specs global-options)))
463       (loop
464         (when (endp current) (return))
465         (let ((name (pop current))
466               (options (copy-trace-info global-options)))
467           (cond
468            ((eq name :function)
469             (let ((temp (gensym)))
470               (binds `(,temp ,(pop current)))
471               (forms `(trace-1 ,temp ',options))))
472            ((and (keywordp name)
473                  (not (or (fboundp name) (macro-function name))))
474             (error "unknown TRACE option: ~S" name))
475            (t
476             (forms `(trace-1 ',name ',options))))
477           (setq current (parse-trace-options current options)))))
478
479     (if (binds)
480         `(let ,(binds) (list ,@(forms)))
481         `(list ,@(forms)))))
482
483 (defun %list-traced-functions ()
484   (loop for x being each hash-value in *traced-functions*
485         collect (trace-info-what x)))
486
487 (defmacro trace (&rest specs)
488   #+sb-doc
489   "TRACE {Option Global-Value}* {Name {Option Value}*}*
490    TRACE is a debugging tool that provides information when specified functions
491    are called. In its simplest form:
492        (trace Name-1 Name-2 ...)
493    (The Names are not evaluated.)
494
495    Options allow modification of the default behavior. Each option is a pair
496    of an option keyword and a value form. Global options are specified before
497    the first name, and affect all functions traced by a given use of TRACE.
498    Options may also be interspersed with function names, in which case they
499    act as local options, only affecting tracing of the immediately preceding
500    function name. Local options override global options.
501
502    By default, TRACE causes a printout on *TRACE-OUTPUT* each time that
503    one of the named functions is entered or returns. (This is the
504    basic, ANSI Common Lisp behavior of TRACE.) As an SBCL extension, the
505    :REPORT SB-EXT:PROFILE option can be used to instead cause information
506    to be silently recorded to be inspected later using the SB-EXT:PROFILE
507    function.
508
509    The following options are defined:
510
511    :REPORT Report-Type
512        If Report-Type is TRACE (the default) then information is reported
513        by printing immediately. If Report-Type is SB-EXT:PROFILE, information
514        is recorded for later summary by calls to SB-EXT:PROFILE. If
515        Report-Type is NIL, then the only effect of the trace is to execute
516        other options (e.g. PRINT or BREAK).
517
518    :CONDITION Form
519    :CONDITION-AFTER Form
520    :CONDITION-ALL Form
521        If :CONDITION is specified, then TRACE does nothing unless Form
522        evaluates to true at the time of the call. :CONDITION-AFTER is
523        similar, but suppresses the initial printout, and is tested when the
524        function returns. :CONDITION-ALL tries both before and after.
525
526    :BREAK Form
527    :BREAK-AFTER Form
528    :BREAK-ALL Form
529        If specified, and Form evaluates to true, then the debugger is invoked
530        at the start of the function, at the end of the function, or both,
531        according to the respective option. 
532
533    :PRINT Form
534    :PRINT-AFTER Form
535    :PRINT-ALL Form
536        In addition to the usual printout, the result of evaluating Form is
537        printed at the start of the function, at the end of the function, or
538        both, according to the respective option. Multiple print options cause
539        multiple values to be printed.
540
541    :WHEREIN Names
542        If specified, Names is a function name or list of names. TRACE does
543        nothing unless a call to one of those functions encloses the call to
544        this function (i.e. it would appear in a backtrace.)  Anonymous
545        functions have string names like \"DEFUN FOO\". 
546
547    :ENCAPSULATE {:DEFAULT | T | NIL}
548        If T, the tracing is done via encapsulation (redefining the function
549        name) rather than by modifying the function. :DEFAULT is the default,
550        and means to use encapsulation for interpreted functions and funcallable
551        instances, breakpoints otherwise. When encapsulation is used, forms are
552        *not* evaluated in the function's lexical environment, but SB-DEBUG:ARG
553        can still be used.
554
555    :FUNCTION Function-Form
556        This is a not really an option, but rather another way of specifying
557        what function to trace. The Function-Form is evaluated immediately,
558        and the resulting function is traced.
559
560    :CONDITION, :BREAK and :PRINT forms are evaluated in the lexical environment
561    of the called function; SB-DEBUG:VAR and SB-DEBUG:ARG can be used. The
562    -AFTER and -ALL forms are evaluated in the null environment."
563   (if specs
564       (expand-trace specs)
565       '(%list-traced-functions)))
566 \f
567 ;;;; untracing
568
569 ;;; Untrace one function.
570 (defun untrace-1 (function-or-name)
571   (let* ((fun (trace-fdefinition function-or-name))
572          (info (gethash fun *traced-functions*)))
573     (cond
574      ((not info)
575       (warn "Function is not TRACEd: ~S" function-or-name))
576      (t
577       (cond
578        ((trace-info-encapsulated info)
579         (unencapsulate (trace-info-what info) 'trace))
580        (t
581         (sb-di:delete-breakpoint (trace-info-start-breakpoint info))
582         (sb-di:delete-breakpoint (trace-info-end-breakpoint info))))
583       (setf (trace-info-untraced info) t)
584       (remhash fun *traced-functions*)))))
585
586 ;;; Untrace all traced functions.
587 (defun untrace-all ()
588   (dolist (fun (%list-traced-functions))
589     (untrace-1 fun))
590   t)
591
592 (defmacro untrace (&rest specs)
593   #+sb-doc
594   "Remove tracing from the specified functions. With no args, untrace all
595    functions."
596   (if specs
597       (collect ((res))
598         (let ((current specs))
599           (loop
600             (unless current (return))
601             (let ((name (pop current)))
602               (res (if (eq name :function)
603                        `(untrace-1 ,(pop current))
604                        `(untrace-1 ',name)))))
605           `(progn ,@(res) t)))
606       '(untrace-all)))