1.0.47.3: better DEFSTRUCT constructor type declarations
[sbcl.git] / src / code / ntrace.lisp
1 ;;;; a tracing facility
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* t
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 :synchronized t))
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   ;; should we trace methods given a generic function to trace?
64   (methods nil)
65
66   ;; The following slots represent the forms that we are supposed to
67   ;; evaluate on each iteration. Each form is represented by a cons
68   ;; (Form . Function), where the Function is the cached result of
69   ;; coercing Form to a function. Forms which use the current
70   ;; environment are converted with PREPROCESS-FOR-EVAL, which gives
71   ;; us a one-arg function. Null environment forms also have one-arg
72   ;; functions, but the argument is ignored. NIL means unspecified
73   ;; (the default.)
74
75   ;; current environment forms
76   (condition nil)
77   (break nil)
78   ;; List of current environment forms
79   (print () :type list)
80   ;; null environment forms
81   (condition-after nil)
82   (break-after nil)
83   ;; list of null environment forms
84   (print-after () :type list))
85
86 ;;; This is a list of conses (fun-end-cookie . condition-satisfied),
87 ;;; which we use to note distinct dynamic entries into functions. When
88 ;;; we enter a traced function, we add a entry to this list holding
89 ;;; the new end-cookie and whether the trace condition was satisfied.
90 ;;; We must save the trace condition so that the after breakpoint
91 ;;; knows whether to print. The length of this list tells us the
92 ;;; indentation to use for printing TRACE messages.
93 ;;;
94 ;;; This list also helps us synchronize the TRACE facility dynamically
95 ;;; for detecting non-local flow of control. Whenever execution hits a
96 ;;; :FUN-END breakpoint used for TRACE'ing, we look for the
97 ;;; FUN-END-COOKIE at the top of *TRACED-ENTRIES*. If it is not
98 ;;; there, we discard any entries that come before our cookie.
99 ;;;
100 ;;; When we trace using encapsulation, we bind this variable and add
101 ;;; (NIL . CONDITION-SATISFIED), so a NIL "cookie" marks an
102 ;;; encapsulated tracing.
103 (defvar *traced-entries* ())
104 (declaim (list *traced-entries*))
105
106 ;;; This variable is used to discourage infinite recursions when some
107 ;;; trace action invokes a function that is itself traced. In this
108 ;;; case, we quietly ignore the inner tracing.
109 (defvar *in-trace* nil)
110 \f
111 ;;;; utilities
112
113 ;;; Given a function name, a function or a macro name, return the raw
114 ;;; definition and some information. "Raw" means that if the result is
115 ;;; a closure, we strip off the closure and return the bare code. The
116 ;;; second value is T if the argument was a function name. The third
117 ;;; value is one of :COMPILED, :COMPILED-CLOSURE, :INTERPRETED,
118 ;;; :INTERPRETED-CLOSURE and :FUNCALLABLE-INSTANCE.
119 (defun trace-fdefinition (x)
120   (flet ((get-def ()
121            (if (valid-function-name-p x)
122                (if (fboundp x)
123                    (fdefinition x)
124                    (warn "~/sb-impl::print-symbol-with-prefix/ is ~
125                           undefined, not tracing." x))
126                (warn "~S is not a valid function name, not tracing." x))))
127     (multiple-value-bind (res named-p)
128         (typecase x
129          (symbol
130           (cond ((special-operator-p x)
131                  (warn "~S is a special operator, not tracing." x))
132                 ((macro-function x))
133                 (t
134                  (values (get-def) t))))
135          (function
136           x)
137          (t
138           (values (get-def) t)))
139      (typecase res
140        (closure
141         (values (sb-kernel:%closure-fun res)
142                 named-p
143                 :compiled-closure))
144        (funcallable-instance
145         (values res named-p :funcallable-instance))
146        ;; FIXME: What about SB!EVAL:INTERPRETED-FUNCTION -- it gets picked off
147        ;; by the FIN above, is that right?
148        (t
149         (values res named-p :compiled))))))
150
151 ;;; When a function name is redefined, and we were tracing that name,
152 ;;; then untrace the old definition and trace the new one.
153 (defun trace-redefined-update (fname new-value)
154   (when (fboundp fname)
155     (let* ((fun (trace-fdefinition fname))
156            (info (gethash fun *traced-funs*)))
157       (when (and info (trace-info-named info))
158         (untrace-1 fname)
159         (trace-1 fname info new-value)))))
160 (push #'trace-redefined-update *setf-fdefinition-hook*)
161
162 ;;; Annotate a FORM to evaluate with pre-converted functions. FORM is
163 ;;; really a cons (EXP . FUNCTION). LOC is the code location to use
164 ;;; for the lexical environment. If LOC is NIL, evaluate in the null
165 ;;; environment. If FORM is NIL, just return NIL.
166 (defun coerce-form (form loc)
167   (when form
168     (let ((exp (car form)))
169       (if (sb-di:code-location-p loc)
170           (let ((fun (sb-di:preprocess-for-eval exp loc)))
171             (declare (type function fun))
172             (cons exp
173                   (lambda (frame)
174                     (let ((*current-frame* frame))
175                       (funcall fun frame)))))
176           (let* ((bod (ecase loc
177                         ((nil) exp)
178                         (:encapsulated
179                          `(locally (declare (disable-package-locks sb-debug:arg arg-list))
180                            (flet ((sb-debug:arg (n)
181                                     (declare (special arg-list))
182                                     (elt arg-list n)))
183                              (declare (ignorable #'sb-debug:arg)
184                                       (enable-package-locks sb-debug:arg arg-list))
185                              ,exp)))))
186                  (fun (coerce `(lambda () ,bod) 'function)))
187             (cons exp
188                   (lambda (frame)
189                     (declare (ignore frame))
190                     (let ((*current-frame* nil))
191                       (funcall fun)))))))))
192
193 (defun coerce-form-list (forms loc)
194   (mapcar (lambda (x) (coerce-form x loc)) forms))
195
196 ;;; Print indentation according to the number of trace entries.
197 ;;; Entries whose condition was false don't count.
198 (defun print-trace-indentation ()
199   (let ((depth 0))
200     (dolist (entry *traced-entries*)
201       (when (cdr entry) (incf depth)))
202     (format t
203             "~V,0@T~W: "
204             (+ (mod (* depth *trace-indentation-step*)
205                     (- *max-trace-indentation* *trace-indentation-step*))
206                *trace-indentation-step*)
207             depth)))
208
209 ;;; Return true if any of the NAMES appears on the stack below FRAME.
210 (defun trace-wherein-p (frame names)
211   (do ((frame (sb-di:frame-down frame) (sb-di:frame-down frame)))
212       ((not frame) nil)
213     (when (member (sb-di:debug-fun-name (sb-di:frame-debug-fun frame))
214                   names
215                   :test #'equal)
216       (return t))))
217
218 ;;; Handle PRINT and PRINT-AFTER options.
219 (defun trace-print (frame forms)
220   (dolist (ele forms)
221     (fresh-line)
222     (print-trace-indentation)
223     (format t "~@<~S ~_= ~S~:>" (car ele) (funcall (cdr ele) frame))
224     (terpri)))
225
226 ;;; Test a BREAK option, and if true, break.
227 (defun trace-maybe-break (info break where frame)
228   (when (and break (funcall (cdr break) frame))
229     (sb-di:flush-frames-above frame)
230     (let ((*stack-top-hint* frame))
231       (break "breaking ~A traced call to ~S:"
232              where
233              (trace-info-what info)))))
234
235 ;;; Discard any invalid cookies on our simulated stack. Encapsulated
236 ;;; entries are always valid, since we bind *TRACED-ENTRIES* in the
237 ;;; encapsulation.
238 (defun discard-invalid-entries (frame)
239   (loop
240     (when (or (null *traced-entries*)
241               (let ((cookie (caar *traced-entries*)))
242                 (or (not cookie)
243                     (sb-di:fun-end-cookie-valid-p frame cookie))))
244       (return))
245     (pop *traced-entries*)))
246 \f
247 ;;;; hook functions
248
249 ;;; Return a closure that can be used for a function start breakpoint
250 ;;; hook function and a closure that can be used as the FUN-END-COOKIE
251 ;;; function. The first communicates the sense of the
252 ;;; TRACE-INFO-CONDITION to the second via a closure variable.
253 (defun trace-start-breakpoint-fun (info)
254   (let (conditionp)
255     (values
256
257      (lambda (frame bpt)
258        (declare (ignore bpt))
259        (discard-invalid-entries frame)
260        (let ((condition (trace-info-condition info))
261              (wherein (trace-info-wherein info)))
262          (setq conditionp
263                (and (not *in-trace*)
264                     (or (not condition)
265                         (funcall (cdr condition) frame))
266                     (or (not wherein)
267                         (trace-wherein-p frame wherein)))))
268        (when conditionp
269          (let ((sb-kernel:*current-level-in-print* 0)
270                (*standard-output* (make-string-output-stream))
271                (*in-trace* t))
272            (fresh-line)
273            (print-trace-indentation)
274            (if (trace-info-encapsulated info)
275                ;; FIXME: These special variables should be given
276                ;; *FOO*-style names, and probably declared globally
277                ;; with DEFVAR.
278                (locally
279                  (declare (special basic-definition arg-list))
280                  (prin1 `(,(trace-info-what info)
281                           ,@(mapcar #'ensure-printable-object arg-list))))
282                (print-frame-call frame *standard-output*))
283            (terpri)
284            (trace-print frame (trace-info-print info))
285            (write-sequence (get-output-stream-string *standard-output*)
286                            *trace-output*)
287            (finish-output *trace-output*))
288          (trace-maybe-break info (trace-info-break info) "before" frame)))
289
290      (lambda (frame cookie)
291        (declare (ignore frame))
292        (push (cons cookie conditionp) *traced-entries*)))))
293
294 ;;; This prints a representation of the return values delivered.
295 ;;; First, this checks to see that cookie is at the top of
296 ;;; *TRACED-ENTRIES*; if it is not, then we need to adjust this list
297 ;;; to determine the correct indentation for output. We then check to
298 ;;; see whether the function is still traced and that the condition
299 ;;; succeeded before printing anything.
300 (declaim (ftype (function (trace-info) function) trace-end-breakpoint-fun))
301 (defun trace-end-breakpoint-fun (info)
302   (lambda (frame bpt *trace-values* cookie)
303     (declare (ignore bpt))
304     (unless (eq cookie (caar *traced-entries*))
305       (setf *traced-entries*
306             (member cookie *traced-entries* :key #'car)))
307
308     (let ((entry (pop *traced-entries*)))
309       (when (and (not (trace-info-untraced info))
310                  (or (cdr entry)
311                      (let ((cond (trace-info-condition-after info)))
312                        (and cond (funcall (cdr cond) frame)))))
313         (let ((sb-kernel:*current-level-in-print* 0)
314               (*standard-output* (make-string-output-stream))
315               (*in-trace* t))
316           (fresh-line)
317           (let ((*print-pretty* t))
318             (pprint-logical-block (*standard-output* nil)
319               (print-trace-indentation)
320               (pprint-indent :current 2)
321               (format t "~S returned" (trace-info-what info))
322               (dolist (v *trace-values*)
323                 (write-char #\space)
324                 (pprint-newline :linear)
325                 (prin1 (ensure-printable-object v))))
326             (terpri))
327           (trace-print frame (trace-info-print-after info))
328           (write-sequence (get-output-stream-string *standard-output*)
329                           *trace-output*)
330           (finish-output *trace-output*))
331         (trace-maybe-break info
332                            (trace-info-break-after info)
333                            "after"
334                            frame)))))
335 \f
336 ;;; This function is called by the trace encapsulation. It calls the
337 ;;; breakpoint hook functions with NIL for the breakpoint and cookie,
338 ;;; which we have cleverly contrived to work for our hook functions.
339 (defun trace-call (info)
340   (multiple-value-bind (start cookie) (trace-start-breakpoint-fun info)
341     (declare (type function start cookie))
342     (let ((frame (sb-di:frame-down (sb-di:top-frame))))
343       (funcall start frame nil)
344       (let ((*traced-entries* *traced-entries*))
345         (declare (special basic-definition arg-list))
346         (funcall cookie frame nil)
347         (let ((vals
348                (multiple-value-list
349                 (apply basic-definition arg-list))))
350           (funcall (trace-end-breakpoint-fun info) frame nil vals nil)
351           (values-list vals))))))
352 \f
353 ;;; Trace one function according to the specified options. We copy the
354 ;;; trace info (it was a quoted constant), fill in the functions, and
355 ;;; then install the breakpoints or encapsulation.
356 ;;;
357 ;;; If non-null, DEFINITION is the new definition of a function that
358 ;;; we are automatically retracing.
359 (defun trace-1 (function-or-name info &optional definition)
360   (multiple-value-bind (fun named kind)
361       (if definition
362           (values definition t
363                   (nth-value 2 (trace-fdefinition definition)))
364           (trace-fdefinition function-or-name))
365     (when fun
366       (when (gethash fun *traced-funs*)
367         (warn "~S is already TRACE'd, untracing it first." function-or-name)
368         (untrace-1 fun))
369       (let* ((debug-fun (sb-di:fun-debug-fun fun))
370              (encapsulated
371               (if (eq (trace-info-encapsulated info) :default)
372                   (ecase kind
373                     (:compiled nil)
374                     (:compiled-closure
375                      (unless (functionp function-or-name)
376                        (warn "tracing shared code for ~S:~%  ~S"
377                              function-or-name
378                              fun))
379                      nil)
380                     ((:interpreted :interpreted-closure :funcallable-instance)
381                      t))
382                   (trace-info-encapsulated info)))
383              (loc (if encapsulated
384                       :encapsulated
385                       (sb-di:debug-fun-start-location debug-fun)))
386              (info (make-trace-info
387                     :what function-or-name
388                     :named named
389                     :encapsulated encapsulated
390                     :wherein (trace-info-wherein info)
391                     :methods (trace-info-methods info)
392                     :condition (coerce-form (trace-info-condition info) loc)
393                     :break (coerce-form (trace-info-break info) loc)
394                     :print (coerce-form-list (trace-info-print info) loc)
395                     :break-after (coerce-form (trace-info-break-after info) nil)
396                     :condition-after
397                     (coerce-form (trace-info-condition-after info) nil)
398                     :print-after
399                     (coerce-form-list (trace-info-print-after info) nil))))
400
401         (dolist (wherein (trace-info-wherein info))
402           (unless (or (stringp wherein)
403                       (fboundp wherein))
404             (warn ":WHEREIN name ~S is not a defined global function."
405                   wherein)))
406
407         (cond
408           (encapsulated
409            (unless named
410              (error "can't use encapsulation to trace anonymous function ~S"
411                     fun))
412            (encapsulate function-or-name 'trace `(trace-call ',info)))
413           (t
414            (multiple-value-bind (start-fun cookie-fun)
415                (trace-start-breakpoint-fun info)
416              (let ((start (sb-di:make-breakpoint start-fun debug-fun
417                                                  :kind :fun-start))
418                    (end (sb-di:make-breakpoint
419                          (trace-end-breakpoint-fun info)
420                          debug-fun :kind :fun-end
421                          :fun-end-cookie cookie-fun)))
422                (setf (trace-info-start-breakpoint info) start)
423                (setf (trace-info-end-breakpoint info) end)
424                ;; The next two forms must be in the order in which they
425                ;; appear, since the start breakpoint must run before the
426                ;; fun-end breakpoint's start helper (which calls the
427                ;; cookie function.) One reason is that cookie function
428                ;; requires that the CONDITIONP shared closure variable be
429                ;; initialized.
430                (sb-di:activate-breakpoint start)
431                (sb-di:activate-breakpoint end)))))
432
433         (setf (gethash fun *traced-funs*) info))
434
435       (when (and (typep fun 'generic-function)
436                  (trace-info-methods info)
437                  ;; we are going to trace the method functions directly.
438                  (not (trace-info-encapsulated info)))
439         (dolist (method (sb-mop:generic-function-methods fun))
440           (let ((mf (sb-mop:method-function method)))
441             ;; NOTE: this direct style of tracing methods -- tracing the
442             ;; pcl-internal method functions -- is only one possible
443             ;; alternative.  It fails (a) when encapulation is
444             ;; requested, because the function objects themselves are
445             ;; stored in the method object; (b) when the method in
446             ;; question is particularly simple, when the method
447             ;; functionality is in the dfun.  See src/pcl/env.lisp for a
448             ;; stub implementation of encapsulating through a
449             ;; traced-method class.
450             (trace-1 mf info)
451             (when (typep mf 'sb-pcl::%method-function)
452               (trace-1 (sb-pcl::%method-function-fast-function mf) info)))))
453
454       function-or-name)))
455 \f
456 ;;;; the TRACE macro
457
458 ;;; Parse leading trace options off of SPECS, modifying INFO
459 ;;; accordingly. The remaining portion of the list is returned when we
460 ;;; encounter a plausible function name.
461 (defun parse-trace-options (specs info)
462   (let ((current specs))
463     (loop
464       (when (endp current) (return))
465       (let ((option (first current))
466             (value (cons (second current) nil)))
467         (case option
468           (:report (error "stub: The :REPORT option is not yet implemented."))
469           (:condition (setf (trace-info-condition info) value))
470           (:condition-after
471            (setf (trace-info-condition info) (cons nil nil))
472            (setf (trace-info-condition-after info) value))
473           (:condition-all
474            (setf (trace-info-condition info) value)
475            (setf (trace-info-condition-after info) value))
476           (:wherein
477            (setf (trace-info-wherein info)
478                  (if (listp (car value)) (car value) value)))
479           (:encapsulate
480            (setf (trace-info-encapsulated info) (car value)))
481           (:methods
482            (setf (trace-info-methods info) (car value)))
483           (:break (setf (trace-info-break info) value))
484           (:break-after (setf (trace-info-break-after info) value))
485           (:break-all
486            (setf (trace-info-break info) value)
487            (setf (trace-info-break-after info) value))
488           (:print
489            (setf (trace-info-print info)
490                  (append (trace-info-print info) (list value))))
491           (:print-after
492            (setf (trace-info-print-after info)
493                  (append (trace-info-print-after info) (list value))))
494           (:print-all
495            (setf (trace-info-print info)
496                  (append (trace-info-print info) (list value)))
497            (setf (trace-info-print-after info)
498                  (append (trace-info-print-after info) (list value))))
499           (t (return)))
500         (pop current)
501         (unless current
502           (error "missing argument to ~S TRACE option" option))
503         (pop current)))
504     current))
505
506 ;;; Compute the expansion of TRACE in the non-trivial case (arguments
507 ;;; specified.)
508 (defun expand-trace (specs)
509   (collect ((binds)
510             (forms))
511     (let* ((global-options (make-trace-info))
512            (current (parse-trace-options specs global-options)))
513       (loop
514         (when (endp current) (return))
515         (let ((name (pop current))
516               (options (copy-trace-info global-options)))
517           (cond
518            ((eq name :function)
519             (let ((temp (gensym)))
520               (binds `(,temp ,(pop current)))
521               (forms `(trace-1 ,temp ',options))))
522            ((and (keywordp name)
523                  (not (or (fboundp name) (macro-function name))))
524             (error "unknown TRACE option: ~S" name))
525            ((stringp name)
526             (let ((package (find-undeleted-package-or-lose name)))
527               (do-all-symbols (symbol (find-package name))
528                 (when (eql package (symbol-package symbol))
529                   (when (and (fboundp symbol)
530                              (not (macro-function symbol))
531                              (not (special-operator-p symbol)))
532                     (forms `(trace-1 ',symbol ',options)))
533                   (let ((setf-name `(setf ,symbol)))
534                     (when (fboundp setf-name)
535                       (forms `(trace-1 ',setf-name ',options))))))))
536            ;; special-case METHOD: it itself is not a general function
537            ;; name symbol, but it (at least here) designates one of a
538            ;; pair of such.
539            ((and (consp name) (eq (car name) 'method))
540             (when (fboundp (list* 'sb-pcl::slow-method (cdr name)))
541               (forms `(trace-1 ',(list* 'sb-pcl::slow-method (cdr name))
542                                ',options)))
543             (when (fboundp (list* 'sb-pcl::fast-method (cdr name)))
544               (forms `(trace-1 ',(list* 'sb-pcl::fast-method (cdr name))
545                                ',options))))
546            (t
547             (forms `(trace-1 ',name ',options))))
548           (setq current (parse-trace-options current options)))))
549
550     `(let ,(binds)
551        (remove nil (list ,@(forms))))))
552
553 (defun %list-traced-funs ()
554   (loop for x being each hash-value in *traced-funs*
555         collect (trace-info-what x)))
556
557 (defmacro trace (&rest specs)
558   #+sb-doc
559   "TRACE {Option Global-Value}* {Name {Option Value}*}*
560
561 TRACE is a debugging tool that provides information when specified
562 functions are called. In its simplest form:
563
564        (TRACE NAME-1 NAME-2 ...)
565
566 The NAMEs are not evaluated. Each may be a symbol, denoting an
567 individual function, or a string, denoting all functions fbound to
568 symbols whose home package is the package with the given name.
569
570 Options allow modification of the default behavior. Each option is a
571 pair of an option keyword and a value form. Global options are
572 specified before the first name, and affect all functions traced by a
573 given use of TRACE. Options may also be interspersed with function
574 names, in which case they act as local options, only affecting tracing
575 of the immediately preceding function name. Local options override
576 global options.
577
578 By default, TRACE causes a printout on *TRACE-OUTPUT* each time that
579 one of the named functions is entered or returns. (This is the basic,
580 ANSI Common Lisp behavior of TRACE.) As an SBCL extension, the
581 :REPORT SB-EXT:PROFILE option can be used to instead cause information
582 to be silently recorded to be inspected later using the SB-EXT:PROFILE
583 function.
584
585 The following options are defined:
586
587    :REPORT Report-Type
588        If Report-Type is TRACE (the default) then information is reported
589        by printing immediately. If Report-Type is SB-EXT:PROFILE, information
590        is recorded for later summary by calls to SB-EXT:PROFILE. If
591        Report-Type is NIL, then the only effect of the trace is to execute
592        other options (e.g. PRINT or BREAK).
593
594    :CONDITION Form
595    :CONDITION-AFTER Form
596    :CONDITION-ALL Form
597        If :CONDITION is specified, then TRACE does nothing unless Form
598        evaluates to true at the time of the call. :CONDITION-AFTER is
599        similar, but suppresses the initial printout, and is tested when the
600        function returns. :CONDITION-ALL tries both before and after.
601        This option is not supported with :REPORT PROFILE.
602
603    :BREAK Form
604    :BREAK-AFTER Form
605    :BREAK-ALL Form
606        If specified, and Form evaluates to true, then the debugger is invoked
607        at the start of the function, at the end of the function, or both,
608        according to the respective option.
609
610    :PRINT Form
611    :PRINT-AFTER Form
612    :PRINT-ALL Form
613        In addition to the usual printout, the result of evaluating Form is
614        printed at the start of the function, at the end of the function, or
615        both, according to the respective option. Multiple print options cause
616        multiple values to be printed.
617
618    :WHEREIN Names
619        If specified, Names is a function name or list of names. TRACE does
620        nothing unless a call to one of those functions encloses the call to
621        this function (i.e. it would appear in a backtrace.)  Anonymous
622        functions have string names like \"DEFUN FOO\". This option is not
623        supported with :REPORT PROFILE.
624
625    :ENCAPSULATE {:DEFAULT | T | NIL}
626        If T, the tracing is done via encapsulation (redefining the function
627        name) rather than by modifying the function. :DEFAULT is the default,
628        and means to use encapsulation for interpreted functions and funcallable
629        instances, breakpoints otherwise. When encapsulation is used, forms are
630        *not* evaluated in the function's lexical environment, but SB-DEBUG:ARG
631        can still be used.
632
633    :METHODS {T | NIL}
634        If T, any function argument naming a generic function will have its
635        methods traced in addition to the generic function itself.
636
637    :FUNCTION Function-Form
638        This is a not really an option, but rather another way of specifying
639        what function to trace. The Function-Form is evaluated immediately,
640        and the resulting function is instrumented, i.e. traced or profiled
641        as specified in REPORT.
642
643 :CONDITION, :BREAK and :PRINT forms are evaluated in a context which
644 mocks up the lexical environment of the called function, so that
645 SB-DEBUG:VAR and SB-DEBUG:ARG can be used. The -AFTER and -ALL forms
646 are evaluated in the null environment."
647   (if specs
648       (expand-trace specs)
649       '(%list-traced-funs)))
650 \f
651 ;;;; untracing
652
653 ;;; Untrace one function.
654 (defun untrace-1 (function-or-name)
655   (let* ((fun (trace-fdefinition function-or-name))
656          (info (when fun (gethash fun *traced-funs*))))
657     (cond
658       ((and fun (not info))
659        (warn "Function is not TRACEd: ~S" function-or-name))
660       ((not fun)
661        ;; Someone has FMAKUNBOUND it.
662        (let ((table *traced-funs*))
663          (with-locked-hash-table (table)
664            (maphash (lambda (fun info)
665                       (when (equal function-or-name (trace-info-what info))
666                         (remhash fun table)))
667                     table))))
668       (t
669        (cond
670          ((trace-info-encapsulated info)
671           (unencapsulate (trace-info-what info) 'trace))
672          (t
673           (sb-di:delete-breakpoint (trace-info-start-breakpoint info))
674           (sb-di:delete-breakpoint (trace-info-end-breakpoint info))))
675        (setf (trace-info-untraced info) t)
676        (remhash fun *traced-funs*)))))
677
678 ;;; Untrace all traced functions.
679 (defun untrace-all ()
680   (dolist (fun (%list-traced-funs))
681     (untrace-1 fun))
682   t)
683
684 (defun untrace-package (name)
685   (let ((package (find-package name)))
686     (when package
687       (dolist (fun (%list-traced-funs))
688         (cond ((and (symbolp fun) (eq package (symbol-package fun)))
689                (untrace-1 fun))
690               ((and (consp fun) (eq 'setf (car fun))
691                     (symbolp (second fun))
692                     (eq package (symbol-package (second fun))))
693                (untrace-1 fun)))))))
694
695 (defmacro untrace (&rest specs)
696   #+sb-doc
697   "Remove tracing from the specified functions. Untraces all
698 functions when called with no arguments."
699   (if specs
700       `(progn
701          ,@(loop while specs
702                  for name = (pop specs)
703                  collect (cond ((eq name :function)
704                                 `(untrace-1 ,(pop specs)))
705                                ((stringp name)
706                                 `(untrace-package ,name))
707                                (t
708                                 `(untrace-1 ',name))))
709          t)
710       '(untrace-all)))