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