1.0.33.23: nuke trailing newline from error string
[sbcl.git] / contrib / sb-introspect / introspect.lisp
1 ;;; introspection library
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 ;;; For the avoidance of doubt, the exported interface is the supported
13 ;;; interface. Anything else is internal, though you're welcome to argue a
14 ;;; case for exporting it.
15
16 ;;; If you steal the code from this file to cut and paste into your
17 ;;; own project, there will be much wailing and gnashing of teeth.
18 ;;; Your teeth.  If need be, we'll kick them for you.  This is a
19 ;;; contrib, we're allowed to look in internals.  You're an
20 ;;; application programmer, and are not.
21
22 ;;; TODO
23 ;;; 1) structs don't have within-file location info.  problem for the
24 ;;;   structure itself, accessors and the predicate
25 ;;; 3) error handling.  Signal random errors, or handle and resignal 'our'
26 ;;;   error, or return NIL?
27 ;;; 4) FIXMEs
28
29 (defpackage :sb-introspect
30   (:use "CL")
31   (:export "ALLOCATION-INFORMATION"
32            "FUNCTION-ARGLIST"
33            "FUNCTION-LAMBDA-LIST"
34            "DEFTYPE-LAMBDA-LIST"
35            "VALID-FUNCTION-NAME-P"
36            "FIND-DEFINITION-SOURCE"
37            "FIND-DEFINITION-SOURCES-BY-NAME"
38            "DEFINITION-SOURCE"
39            "DEFINITION-SOURCE-PATHNAME"
40            "DEFINITION-SOURCE-FORM-PATH"
41            "DEFINITION-SOURCE-CHARACTER-OFFSET"
42            "DEFINITION-SOURCE-FILE-WRITE-DATE"
43            "DEFINITION-SOURCE-PLIST"
44            "DEFINITION-NOT-FOUND" "DEFINITION-NAME"
45            "FIND-FUNCTION-CALLEES"
46            "FIND-FUNCTION-CALLERS"
47            "WHO-BINDS"
48            "WHO-CALLS"
49            "WHO-REFERENCES"
50            "WHO-SETS"
51            "WHO-MACROEXPANDS"
52            "WHO-SPECIALIZES-DIRECTLY"
53            "WHO-SPECIALIZES-GENERALLY"))
54
55 (in-package :sb-introspect)
56
57 ;;;; Internal interface for SBCL debug info
58
59 ;;; Here are some tutorial-style type definitions to help understand
60 ;;; the internal SBCL debugging data structures we're using. The
61 ;;; commentary is based on CMUCL's debug internals manual.
62 ;;;
63 (deftype debug-info ()
64   "Structure containing all the debug information related to a function.
65 Function objects reference debug-infos which in turn reference
66 debug-sources and so on."
67   'sb-c::compiled-debug-info)
68
69 (deftype debug-source ()
70   "Debug sources describe where to find source code.
71 For example, the debug source for a function compiled from a file will
72 include the pathname of the file and the position of the definition."
73   'sb-c::debug-source)
74
75 (deftype debug-function ()
76   "Debug function represent static compile-time information about a function."
77   'sb-c::compiled-debug-fun)
78
79 (declaim (ftype (function (function) debug-info) function-debug-info))
80 (defun function-debug-info (function)
81   (let* ((function-object (sb-kernel::%fun-fun function))
82          (function-header (sb-kernel:fun-code-header function-object)))
83     (sb-kernel:%code-debug-info function-header)))
84
85 (declaim (ftype (function (function) debug-source) function-debug-source))
86 (defun function-debug-source (function)
87   (debug-info-source (function-debug-info function)))
88
89 (declaim (ftype (function (debug-info) debug-source) debug-info-source))
90 (defun debug-info-source (debug-info)
91   (sb-c::debug-info-source debug-info))
92
93 (declaim (ftype (function (debug-info) debug-function) debug-info-debug-function))
94 (defun debug-info-debug-function (debug-info)
95   (elt (sb-c::compiled-debug-info-fun-map debug-info) 0))
96
97 (defun valid-function-name-p (name)
98   "True if NAME denotes a function name that can be passed to MACRO-FUNCTION or FDEFINITION "
99   (and (sb-int:valid-function-name-p name) t))
100
101 ;;;; Finding definitions
102
103 (defstruct definition-source
104   ;; Pathname of the source file that the definition was compiled from.
105   ;; This is null if the definition was not compiled from a file.
106   (pathname nil :type (or null pathname))
107   ;; Source-path of the definition within the file.
108   ;; This may be incomplete depending on the debug level at which the
109   ;; source was compiled.
110   (form-path '() :type list)
111   ;; Character offset of the top-level-form containing the definition.
112   ;; This corresponds to the first element of form-path.
113   (character-offset nil :type (or null integer))
114   ;; File-write-date of the source file when compiled.
115   ;; Null if not compiled from a file.
116   (file-write-date nil :type (or null integer))
117   ;; plist from WITH-COMPILATION-UNIT
118   (plist nil)
119   ;; Any extra metadata that the caller might be interested in. For
120   ;; example the specializers of the method whose definition-source this
121   ;; is.
122   (description nil :type list))
123
124 (defun find-definition-sources-by-name (name type)
125   "Returns a list of DEFINITION-SOURCEs for the objects of type TYPE
126 defined with name NAME. NAME may be a symbol or a extended function
127 name. Type can currently be one of the following:
128
129    (Public)
130    :CLASS
131    :COMPILER-MACRO
132    :CONDITION
133    :CONSTANT
134    :FUNCTION
135    :GENERIC-FUNCTION
136    :MACRO
137    :METHOD
138    :METHOD-COMBINATION
139    :PACKAGE
140    :SETF-EXPANDER
141    :STRUCTURE
142    :SYMBOL-MACRO
143    :TYPE
144    :VARIABLE
145
146    (Internal)
147    :OPTIMIZER
148    :SOURCE-TRANSFORM
149    :TRANSFORM
150    :VOP
151
152 If an unsupported TYPE is requested, the function will return NIL.
153 "
154   (flet ((listify (x)
155            (if (listp x)
156                x
157                (list x)))
158          (get-class (name)
159            (and (symbolp name)
160                 (find-class name nil)))
161          (real-fdefinition (name)
162            ;; for getting the real function object, even if the
163            ;; function is being profiled
164            (let ((profile-info (gethash name sb-profile::*profiled-fun-name->info*)))
165              (if profile-info
166                  (sb-profile::profile-info-encapsulated-fun profile-info)
167                  (fdefinition name)))))
168     (listify
169      (case type
170        ((:variable)
171         (when (and (symbolp name)
172                    (eq (sb-int:info :variable :kind name) :special))
173           (translate-source-location (sb-int:info :source-location type name))))
174        ((:constant)
175         (when (and (symbolp name)
176                    (eq (sb-int:info :variable :kind name) :constant))
177           (translate-source-location (sb-int:info :source-location type name))))
178        ((:symbol-macro)
179         (when (and (symbolp name)
180                    (eq (sb-int:info :variable :kind name) :macro))
181           (translate-source-location (sb-int:info :source-location type name))))
182        ((:macro)
183         (when (and (symbolp name)
184                    (macro-function name))
185           (find-definition-source (macro-function name))))
186        ((:compiler-macro)
187         (when (compiler-macro-function name)
188           (find-definition-source (compiler-macro-function name))))
189        ((:function :generic-function)
190         (when (and (fboundp name)
191                    (or (not (symbolp name))
192                        (not (macro-function name))))
193           (let ((fun (real-fdefinition name)))
194             (when (eq (not (typep fun 'generic-function))
195                       (not (eq type :generic-function)))
196               (find-definition-source fun)))))
197        ((:type)
198         ;; Source locations for types are saved separately when the expander
199         ;; is a closure without a good source-location.
200         (let ((loc (sb-int:info :type :source-location name)))
201           (if loc
202               (translate-source-location loc)
203               (let ((expander-fun (sb-int:info :type :expander name)))
204                 (when expander-fun
205                   (find-definition-source expander-fun))))))
206        ((:method)
207         (when (fboundp name)
208           (let ((fun (real-fdefinition name)))
209            (when (typep fun 'generic-function)
210              (loop for method in (sb-mop::generic-function-methods
211                                   fun)
212                 for source = (find-definition-source method)
213                 when source collect source)))))
214        ((:setf-expander)
215         (when (and (consp name)
216                    (eq (car name) 'setf))
217           (setf name (cadr name)))
218         (let ((expander (or (sb-int:info :setf :inverse name)
219                             (sb-int:info :setf :expander name))))
220           (when expander
221             (sb-introspect:find-definition-source (if (symbolp expander)
222                                                       (symbol-function expander)
223                                                       expander)))))
224        ((:structure)
225         (let ((class (get-class name)))
226           (if class
227               (when (typep class 'sb-pcl::structure-class)
228                 (find-definition-source class))
229               (when (sb-int:info :typed-structure :info name)
230                 (translate-source-location
231                  (sb-int:info :source-location :typed-structure name))))))
232        ((:condition :class)
233         (let ((class (get-class name)))
234           (when (and class
235                      (not (typep class 'sb-pcl::structure-class)))
236             (when (eq (not (typep class 'sb-pcl::condition-class))
237                       (not (eq type :condition)))
238               (find-definition-source class)))))
239        ((:method-combination)
240         (let ((combination-fun
241                (find-method #'sb-mop:find-method-combination
242                             nil
243                             (list (find-class 'generic-function)
244                                   (list 'eql name)
245                                   t)
246                             nil)))
247           (when combination-fun
248             (find-definition-source combination-fun))))
249        ((:package)
250         (when (symbolp name)
251           (let ((package (find-package name)))
252             (when package
253               (find-definition-source package)))))
254        ;; TRANSFORM and OPTIMIZER handling from swank-sbcl
255        ((:transform)
256         (when (symbolp name)
257           (let ((fun-info (sb-int:info :function :info name)))
258             (when fun-info
259               (loop for xform in (sb-c::fun-info-transforms fun-info)
260                     for source = (find-definition-source
261                                   (sb-c::transform-function xform))
262                     for typespec = (sb-kernel:type-specifier
263                                     (sb-c::transform-type xform))
264                     for note = (sb-c::transform-note xform)
265                     do (setf (definition-source-description source)
266                              (if (consp typespec)
267                                  (list (second typespec) note)
268                                  (list note)))
269                     collect source)))))
270        ((:optimizer)
271         (when (symbolp name)
272           (let ((fun-info (sb-int:info :function :info name)))
273             (when fun-info
274               (let ((otypes '((sb-c::fun-info-derive-type . sb-c:derive-type)
275                               (sb-c::fun-info-ltn-annotate . sb-c:ltn-annotate)
276                               (sb-c::fun-info-ltn-annotate . sb-c:ltn-annotate)
277                               (sb-c::fun-info-optimizer . sb-c:optimizer))))
278                 (loop for (reader . name) in otypes
279                       for fn = (funcall reader fun-info)
280                       when fn collect
281                       (let ((source (find-definition-source fn)))
282                         (setf (definition-source-description source)
283                               (list name))
284                         source)))))))
285        ((:vop)
286         (when (symbolp name)
287           (let ((fun-info (sb-int:info :function :info name)))
288             (when fun-info
289               (loop for vop in (sb-c::fun-info-templates fun-info)
290                     for source = (find-definition-source
291                                   (sb-c::vop-info-generator-function vop))
292                     do (setf (definition-source-description source)
293                              (list (sb-c::template-name vop)
294                                    (sb-c::template-note vop)))
295                     collect source)))))
296        ((:source-transform)
297         (when (symbolp name)
298           (let ((transform-fun (sb-int:info :function :source-transform name)))
299             (when transform-fun
300               (sb-introspect:find-definition-source transform-fun)))))
301        (t
302         nil)))))
303
304 (defun find-definition-source (object)
305   (typecase object
306     ((or sb-pcl::condition-class sb-pcl::structure-class)
307      (let ((classoid (sb-impl::find-classoid (class-name object))))
308        (when classoid
309          (let ((layout (sb-impl::classoid-layout classoid)))
310            (when layout
311              (translate-source-location
312               (sb-kernel::layout-source-location layout)))))))
313     (method-combination
314      (car
315       (find-definition-sources-by-name
316        (sb-pcl::method-combination-type-name object) :method-combination)))
317     (package
318      (translate-source-location (sb-impl::package-source-location object)))
319     (class
320      (translate-source-location (sb-pcl::definition-source object)))
321     ;; Use the PCL definition location information instead of the function
322     ;; debug-info for methods and generic functions. Sometimes the
323     ;; debug-info would point into PCL internals instead of the proper
324     ;; location.
325     (generic-function
326      (let ((source (translate-source-location
327                     (sb-pcl::definition-source object))))
328        (when source
329          (setf (definition-source-description source)
330                (list (sb-mop:generic-function-lambda-list object))))
331        source))
332     (method
333      (let ((source (translate-source-location
334                     (sb-pcl::definition-source object))))
335        (when source
336          (setf (definition-source-description source)
337                (append (method-qualifiers object)
338                        (if (sb-mop:method-generic-function object)
339                            (sb-pcl::unparse-specializers
340                             (sb-mop:method-generic-function object)
341                             (sb-mop:method-specializers object))
342                            (sb-mop:method-specializers object)))))
343        source))
344     #+sb-eval
345     (sb-eval:interpreted-function
346      (let ((source (translate-source-location
347                     (sb-eval:interpreted-function-source-location object))))
348        source))
349     (function
350      (cond ((struct-accessor-p object)
351             (find-definition-source
352              (struct-accessor-structure-class object)))
353            ((struct-predicate-p object)
354             (find-definition-source
355              (struct-predicate-structure-class object)))
356            (t
357             (find-function-definition-source object))))
358     ((or condition standard-object structure-object)
359      (find-definition-source (class-of object)))
360     (t
361      (error "Don't know how to retrieve source location for a ~S"
362             (type-of object)))))
363
364 (defun find-function-definition-source (function)
365   (let* ((debug-info (function-debug-info function))
366          (debug-source (debug-info-source debug-info))
367          (debug-fun (debug-info-debug-function debug-info))
368          (tlf (if debug-fun (sb-c::compiled-debug-fun-tlf-number debug-fun))))
369     (make-definition-source
370      :pathname
371      ;; KLUDGE: at the moment, we don't record the correct toplevel
372      ;; form number for forms processed by EVAL (including EVAL-WHEN
373      ;; :COMPILE-TOPLEVEL).  Until that's fixed, don't return a
374      ;; DEFINITION-SOURCE with a pathname.  (When that's fixed, take
375      ;; out the (not (debug-source-form ...)) test.
376      (if (and (sb-c::debug-source-namestring debug-source)
377               (not (sb-c::debug-source-form debug-source)))
378          (parse-namestring (sb-c::debug-source-namestring debug-source)))
379      :character-offset
380      (if tlf
381          (elt (sb-c::debug-source-start-positions debug-source) tlf))
382      ;; Unfortunately there is no proper source path available in the
383      ;; debug-source. FIXME: We could use sb-di:code-locations to get
384      ;; a full source path. -luke (12/Mar/2005)
385      :form-path (if tlf (list tlf))
386      :file-write-date (sb-c::debug-source-created debug-source)
387      :plist (sb-c::debug-source-plist debug-source))))
388
389 (defun translate-source-location (location)
390   (if location
391       (make-definition-source
392        :pathname (let ((n (sb-c:definition-source-location-namestring location)))
393                    (when n
394                      (parse-namestring n)))
395        :form-path
396        (let ((number (sb-c:definition-source-location-toplevel-form-number
397                          location)))
398          (when number
399            (list number)))
400        :plist (sb-c:definition-source-location-plist location))
401       (make-definition-source)))
402
403 ;;; This is kludgey.  We expect these functions (the underlying functions,
404 ;;; not the closures) to be in static space and so not move ever.
405 ;;; FIXME It's also possibly wrong: not all structures use these vanilla
406 ;;; accessors, e.g. when the :type option is used
407 (defvar *struct-slotplace-reader*
408   (sb-vm::%simple-fun-self #'definition-source-pathname))
409 (defvar *struct-slotplace-writer*
410   (sb-vm::%simple-fun-self #'(setf definition-source-pathname)))
411 (defvar *struct-predicate*
412   (sb-vm::%simple-fun-self #'definition-source-p))
413
414 (defun struct-accessor-p (function)
415   (let ((self (sb-vm::%simple-fun-self function)))
416     ;; FIXME there are other kinds of struct accessor.  Fill out this list
417     (member self (list *struct-slotplace-reader*
418                        *struct-slotplace-writer*))))
419
420 (defun struct-predicate-p (function)
421   (let ((self (sb-vm::%simple-fun-self function)))
422     ;; FIXME there may be other structure predicate functions
423     (member self (list *struct-predicate*))))
424
425 (defun function-arglist (function)
426   "Deprecated alias for FUNCTION-LAMBDA-LIST."
427   (function-lambda-list function))
428
429 (define-compiler-macro function-arglist (function)
430   (sb-int:deprecation-warning 'function-arglist 'function-lambda-list)
431   `(function-lambda-list ,function))
432
433 (defun function-lambda-list (function)
434   "Describe the lambda list for the extended function designator FUNCTION.
435 Works for special-operators, macros, simple functions, interpreted functions,
436 and generic functions. Signals an error if FUNCTION is not a valid extended
437 function designator."
438   (cond ((valid-function-name-p function)
439          (function-lambda-list (or (and (symbolp function)
440                                         (macro-function function))
441                                    (fdefinition function))))
442         ((typep function 'generic-function)
443          (sb-pcl::generic-function-pretty-arglist function))
444         #+sb-eval
445         ((typep function 'sb-eval:interpreted-function)
446          (sb-eval:interpreted-function-lambda-list function))
447         (t
448          (sb-kernel:%simple-fun-arglist (sb-kernel:%fun-fun function)))))
449
450 (defun deftype-lambda-list (typespec-operator)
451   "Returns the lambda list of TYPESPEC-OPERATOR as first return
452 value, and a flag whether the arglist could be found as second
453 value."
454   (check-type typespec-operator symbol)
455   (case (sb-int:info :type :kind typespec-operator)
456     (:defined
457      (sb-int:info :type :lambda-list typespec-operator))
458     (:primitive
459      (let ((translator-fun (sb-int:info :type :translator typespec-operator)))
460        (if translator-fun
461            (values (sb-kernel:%fun-lambda-list translator-fun) t)
462            ;; Some builtin types (e.g. STRING) do not have a
463            ;; translator, but they were actually defined via DEFTYPE
464            ;; in src/code/deftypes-for-target.lisp.
465            (sb-int:info :type :lambda-list typespec-operator))))
466     (t (values nil nil))))
467
468 (defun struct-accessor-structure-class (function)
469   (let ((self (sb-vm::%simple-fun-self function)))
470     (cond
471       ((member self (list *struct-slotplace-reader* *struct-slotplace-writer*))
472        (find-class
473         (sb-kernel::classoid-name
474          (sb-kernel::layout-classoid
475           (sb-kernel:%closure-index-ref function 1)))))
476       )))
477
478 (defun struct-predicate-structure-class (function)
479   (let ((self (sb-vm::%simple-fun-self function)))
480     (cond
481       ((member self (list *struct-predicate*))
482        (find-class
483         (sb-kernel::classoid-name
484          (sb-kernel::layout-classoid
485           (sb-kernel:%closure-index-ref function 0)))))
486       )))
487
488 ;;;; find callers/callees, liberated from Helmut Eller's code in SLIME
489
490 ;;; This interface is trmendously experimental.
491
492 ;;; For the moment I'm taking the view that FDEFN is an internal
493 ;;; object (one out of one CMUCL developer surveyed didn't know what
494 ;;; they were for), so these routines deal in FUNCTIONs
495
496 ;;; Find callers and callees by looking at the constant pool of
497 ;;; compiled code objects.  We assume every fdefn object in the
498 ;;; constant pool corresponds to a call to that function.  A better
499 ;;; strategy would be to use the disassembler to find actual
500 ;;; call-sites.
501
502 (defun find-function-callees (function)
503   "Return functions called by FUNCTION."
504   (let ((callees '()))
505     (map-code-constants
506      (sb-kernel:fun-code-header function)
507      (lambda (obj)
508        (when (sb-kernel:fdefn-p obj)
509          (push (sb-kernel:fdefn-fun obj)
510                callees))))
511     callees))
512
513
514 (defun find-function-callers (function &optional (spaces '(:read-only :static
515                                                            :dynamic)))
516   "Return functions which call FUNCTION, by searching SPACES for code objects"
517   (let ((referrers '()))
518     (map-caller-code-components
519      function
520      spaces
521      (lambda (code)
522        (let ((entry (sb-kernel:%code-entry-points  code)))
523          (cond ((not entry)
524                 (push (princ-to-string code) referrers))
525                (t
526                 (loop for e = entry then (sb-kernel::%simple-fun-next e)
527                       while e
528                       do (pushnew e referrers)))))))
529     referrers))
530
531 (declaim (inline map-code-constants))
532 (defun map-code-constants (code fn)
533   "Call FN for each constant in CODE's constant pool."
534   (check-type code sb-kernel:code-component)
535   (loop for i from sb-vm:code-constants-offset below
536         (sb-kernel:get-header-data code)
537         do (funcall fn (sb-kernel:code-header-ref code i))))
538
539 (declaim (inline map-allocated-code-components))
540 (defun map-allocated-code-components (spaces fn)
541   "Call FN for each allocated code component in one of SPACES.  FN
542 receives the object and its size as arguments.  SPACES should be a
543 list of the symbols :dynamic, :static, or :read-only."
544   (dolist (space spaces)
545     (sb-vm::map-allocated-objects
546      (lambda (obj header size)
547        (when (= sb-vm:code-header-widetag header)
548          (funcall fn obj size)))
549      space
550      t)))
551
552 (declaim (inline map-caller-code-components))
553 (defun map-caller-code-components (function spaces fn)
554   "Call FN for each code component with a fdefn for FUNCTION in its
555 constant pool."
556   (let ((function (coerce function 'function)))
557     (map-allocated-code-components
558      spaces
559      (lambda (obj size)
560        (declare (ignore size))
561        (map-code-constants
562         obj
563         (lambda (constant)
564           (when (and (sb-kernel:fdefn-p constant)
565                      (eq (sb-kernel:fdefn-fun constant)
566                          function))
567             (funcall fn obj))))))))
568
569 ;;; XREF facility
570
571 (defun get-simple-fun (functoid)
572   (etypecase functoid
573     (sb-kernel::fdefn
574      (get-simple-fun (sb-vm::fdefn-fun functoid)))
575     ((or null sb-impl::funcallable-instance)
576      nil)
577     (function
578      (sb-kernel::%fun-fun functoid))))
579
580 (defun collect-xref (kind-index wanted-name)
581   (let ((ret nil))
582     (dolist (env sb-c::*info-environment* ret)
583       ;; Loop through the infodb ...
584       (sb-c::do-info (env :class class :type type :name info-name
585                           :value value)
586         ;; ... looking for function or macro definitions
587         (when (and (eql class :function)
588                    (or (eql type :macro-function)
589                        (eql type :definition)))
590           ;; Get a simple-fun for the definition, and an xref array
591           ;; from the table if available.
592           (let* ((simple-fun (get-simple-fun value))
593                  (xrefs (when simple-fun
594                           (sb-kernel:%simple-fun-xrefs simple-fun)))
595                  (array (when xrefs
596                           (aref xrefs kind-index))))
597             ;; Loop through the name/path xref entries in the table
598             (loop for i from 0 below (length array) by 2
599                   for xref-name = (aref array i)
600                   for xref-path = (aref array (1+ i))
601                   do (when (eql xref-name wanted-name)
602                        (let ((source-location
603                               (find-function-definition-source simple-fun)))
604                          ;; Use the more accurate source path from
605                          ;; the xref entry.
606                          (setf (definition-source-form-path source-location)
607                                xref-path)
608                          (push (cons info-name source-location)
609                                ret))))))))))
610
611 (defun who-calls (function-name)
612   "Use the xref facility to search for source locations where the
613 global function named FUNCTION-NAME is called. Returns a list of
614 function name, definition-source pairs."
615   (collect-xref #.(position :calls sb-c::*xref-kinds*) function-name))
616
617 (defun who-binds (symbol)
618   "Use the xref facility to search for source locations where the
619 special variable SYMBOL is rebound. Returns a list of function name,
620 definition-source pairs."
621   (collect-xref #.(position :binds sb-c::*xref-kinds*) symbol))
622
623 (defun who-references (symbol)
624   "Use the xref facility to search for source locations where the
625 special variable or constant SYMBOL is read. Returns a list of function
626 name, definition-source pairs."
627   (collect-xref #.(position :references sb-c::*xref-kinds*) symbol))
628
629 (defun who-sets (symbol)
630   "Use the xref facility to search for source locations where the
631 special variable SYMBOL is written to. Returns a list of function name,
632 definition-source pairs."
633   (collect-xref #.(position :sets sb-c::*xref-kinds*) symbol))
634
635 (defun who-macroexpands (macro-name)
636   "Use the xref facility to search for source locations where the
637 macro MACRO-NAME is expanded. Returns a list of function name,
638 definition-source pairs."
639   (collect-xref #.(position :macroexpands sb-c::*xref-kinds*) macro-name))
640
641 (defun who-specializes-directly (class-designator)
642   "Search for source locations of methods directly specializing on
643 CLASS-DESIGNATOR. Returns an alist of method name, definition-source
644 pairs.
645
646 A method matches the criterion either if it specializes on the same
647 class as CLASS-DESIGNATOR designates (this includes CLASS-EQ
648 specializers), or if it eql-specializes on an instance of the
649 designated class.
650
651 Experimental.
652 "
653   (let ((class (canonicalize-class-designator class-designator)))
654     (unless class
655       (return-from who-specializes-directly nil))
656     (let ((result (collect-specializing-methods
657                    #'(lambda (specl)
658                        ;; Does SPECL specialize on CLASS directly?
659                        (typecase specl
660                          (sb-pcl::class-eq-specializer
661                           (eq (sb-pcl::specializer-object specl) class))
662                          (sb-pcl::eql-specializer
663                           (let ((obj (sb-mop:eql-specializer-object specl)))
664                             (eq (class-of obj) class)))
665                          ((not sb-pcl::standard-specializer)
666                           nil)
667                          (t
668                           (eq specl class)))))))
669       (map-into result #'(lambda (m)
670                            (cons `(method ,(method-generic-function-name m))
671                                  (find-definition-source m)))
672                 result))))
673
674 (defun who-specializes-generally (class-designator)
675   "Search for source locations of methods specializing on
676 CLASS-DESIGNATOR, or a subclass of it. Returns an alist of method
677 name, definition-source pairs.
678
679 A method matches the criterion either if it specializes on the
680 designated class itself or a subclass of it (this includes CLASS-EQ
681 specializers), or if it eql-specializes on an instance of the
682 designated class or a subclass of it.
683
684 Experimental.
685 "
686   (let ((class (canonicalize-class-designator class-designator)))
687     (unless class
688       (return-from who-specializes-generally nil))
689     (let ((result (collect-specializing-methods
690                    #'(lambda (specl)
691                        ;; Does SPECL specialize on CLASS or a subclass
692                        ;; of it?
693                        (typecase specl
694                          (sb-pcl::class-eq-specializer
695                           (subtypep (sb-pcl::specializer-object specl) class))
696                          (sb-pcl::eql-specializer
697                           (typep (sb-mop:eql-specializer-object specl) class))
698                          ((not sb-pcl::standard-specializer)
699                           nil)
700                          (t
701                           (subtypep specl class)))))))
702       (map-into result #'(lambda (m)
703                            (cons `(method ,(method-generic-function-name m))
704                                  (find-definition-source m)))
705                 result))))
706
707 (defun canonicalize-class-designator (class-designator)
708   (typecase class-designator
709     (symbol (find-class class-designator nil))
710     (class  class-designator)
711     (t nil)))
712
713 (defun method-generic-function-name (method)
714   (sb-mop:generic-function-name (sb-mop:method-generic-function method)))
715
716 (defun collect-specializing-methods (predicate)
717   (let ((result '()))
718     (sb-pcl::map-specializers
719      #'(lambda (specl)
720          (when (funcall predicate specl)
721            (let ((methods (sb-mop:specializer-direct-methods specl)))
722              (setf result (append methods result))))))
723     (delete-duplicates result)))
724
725
726 ;;;; ALLOCATION INTROSPECTION
727
728 (defun allocation-information (object)
729   #+sb-doc
730   "Returns information about the allocation of OBJECT. Primary return value
731 indicates the general type of allocation: :IMMEDIATE, :HEAP, :STACK,
732 or :FOREIGN.
733
734 Possible secondary return value provides additional information about the
735 allocation.
736
737 For :HEAP objects the secondary value is a plist:
738
739   :SPACE
740     Inficates the heap segment the object is allocated in.
741
742   :GENERATION
743     Is the current generation of the object: 0 for nursery, 6 for pseudo-static
744     generation loaded from core. (GENCGC and :SPACE :DYNAMIC only.)
745
746   :LARGE
747     Indicates a \"large\" object subject to non-copying
748     promotion. (GENCGC and :SPACE :DYNAMIC only.)
749
750   :BOXED
751     Indicates that the object is allocated in a boxed region. Unboxed
752     allocation is used for eg. specialized arrays after they have survived one
753     collection. (GENCGC and :SPACE :DYNAMIC only.)
754
755   :PINNED
756     Indicates that the page(s) on which the object resides are kept live due
757     to conservative references. Note that object may reside on a pinned page
758     even if :PINNED in NIL if the GC has not had the need to mark the the page
759     as pinned. (GENCGC and :SPACE :DYNAMIC only.)
760
761 For :STACK objects secondary value is the thread on whose stack the object is
762 allocated.
763
764 Expected use-cases include introspection to gain insight into allocation and
765 GC behaviour and restricting memoization to heap-allocated arguments.
766
767 Experimental: interface subject to change."
768   ;; FIXME: Would be nice to provide the size of the object as well, though
769   ;; maybe that should be a separate function, and something like MAP-PARTS
770   ;; for mapping over parts of arbitrary objects so users can get "deep sizes"
771   ;; as well if they want to.
772   ;;
773   ;; FIXME: For the memoization use-case possibly we should also provide a
774   ;; simpler HEAP-ALLOCATED-P, since that doesn't require disabling the GC
775   ;; scanning threads for negative answers? Similarly, STACK-ALLOCATED-P for
776   ;; checking if an object has been stack-allocated by a given thread for
777   ;; testing purposes might not come amiss.
778   (if (typep object '(or fixnum character))
779       (values :immediate nil)
780       (let ((plist
781              (sb-sys:without-gcing
782                ;; Disable GC so the object cannot move to another page while
783                ;; we have the address.
784                (let* ((addr (sb-kernel:get-lisp-obj-address object))
785                       (space
786                        (cond ((< sb-vm:read-only-space-start addr
787                                  (* sb-vm:*read-only-space-free-pointer*
788                                     sb-vm:n-word-bytes))
789                               :read-only)
790                              ((< sb-vm:static-space-start addr
791                                  (* sb-vm:*static-space-free-pointer*
792                                     sb-vm:n-word-bytes))
793                               :static)
794                              ((< (sb-kernel:current-dynamic-space-start) addr
795                                  (sb-sys:sap-int (sb-kernel:dynamic-space-free-pointer)))
796                               :dynamic))))
797                  (when space
798                    #+gencgc
799                    (if (eq :dynamic space)
800                        (let ((index (sb-vm::find-page-index addr)))
801                          (symbol-macrolet ((page (sb-alien:deref sb-vm::page-table index)))
802                            (let ((flags (sb-alien:slot page 'sb-vm::flags)))
803                              (list :space space
804                                    :generation (sb-alien:slot page 'sb-vm::gen)
805                                    :write-protected (logbitp 0 flags)
806                                    :boxed (logbitp 2 flags)
807                                    :pinned (logbitp 5 flags)
808                                    :large (logbitp 6 flags)))))
809                        (list :space space))
810                    #-gencgc
811                    (list :space space))))))
812         (cond (plist
813                (values :heap plist))
814               (t
815                (let ((sap (sb-sys:int-sap (sb-kernel:get-lisp-obj-address object))))
816                  ;; FIXME: Check other stacks as well.
817                  #+sb-thread
818                  (dolist (thread (sb-thread:list-all-threads))
819                    (let ((c-start (sb-di::descriptor-sap
820                                    (sb-thread::%symbol-value-in-thread
821                                     'sb-vm:*control-stack-start*
822                                     thread)))
823                          (c-end (sb-di::descriptor-sap
824                                  (sb-thread::%symbol-value-in-thread
825                                   'sb-vm:*control-stack-end*
826                                   thread))))
827                      (when (and c-start c-end)
828                        (when (and (sb-sys:sap<= c-start sap)
829                                   (sb-sys:sap< sap c-end))
830                          (return-from allocation-information
831                            (values :stack thread))))))
832                  #-sb-thread
833                  (when (sb-vm:control-stack-pointer-valid-p sap nil)
834                    (return-from allocation-information
835                      (values :stack sb-thread::*current-thread*))))
836                :foreign)))))
837