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