2 @c This is part of the GNU Guile Reference Manual.
3 @c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2007, 2010, 2011, 2012, 2013, 2014
4 @c Free Software Foundation, Inc.
5 @c See the file guile.texi for copying conditions.
8 @section Debugging Infrastructure
11 In order to understand Guile's debugging facilities, you first need to
12 understand a little about how Guile represent the Scheme control stack.
13 With that in place we explain the low level trap calls that the virtual
14 machine can be configured to make, and the trap and breakpoint
15 infrastructure that builds on top of those calls.
18 * Evaluation Model:: Evaluation and the Scheme stack.
19 * Source Properties:: From expressions to source locations.
20 * Programmatic Error Handling:: Debugging when an error occurs.
21 * Traps:: Breakpoints, tracepoints, oh my!
22 * GDB Support:: C-level debugging with GDB.
25 @node Evaluation Model
26 @subsection Evaluation and the Scheme Stack
28 The idea of the Scheme stack is central to a lot of debugging. The
29 Scheme stack is a reified representation of the pending function returns
30 in an expression's continuation. As Guile implements function calls
31 using a stack, this reification takes the form of a number of nested
32 stack frames, each of which corresponds to the application of a
33 procedure to a set of arguments.
35 A Scheme stack always exists implicitly, and can be summoned into
36 concrete existence as a first-class Scheme value by the
37 @code{make-stack} call, so that an introspective Scheme program -- such
38 as a debugger -- can present it in some way and allow the user to query
39 its details. The first thing to understand, therefore, is how Guile's
40 function call convention creates the stack.
42 Broadly speaking, Guile represents all control flow on a stack. Calling
43 a function involves pushing an empty frame on the stack, then evaluating
44 the procedure and its arguments, then fixing up the new frame so that it
45 points to the old one. Frames on the stack are thus linked together. A
46 tail call is the same, except it reuses the existing frame instead of
49 In this way, the only frames that are on the stack are ``active''
50 frames, frames which need to do some work before the computation is
51 complete. On the other hand, a function that has tail-called another
52 function will not be on the stack, as it has no work left to do.
54 Therefore, when an error occurs in a running program, or the program
55 hits a breakpoint, or in fact at any point that the programmer chooses,
56 its state at that point can be represented by a @dfn{stack} of all the
57 procedure applications that are logically in progress at that time, each
58 of which is known as a @dfn{frame}. The programmer can learn more about
59 the program's state at that point by inspecting the stack and its
63 * Stack Capture:: Reifying a continuation.
64 * Stacks:: Accessors for the stack data type.
65 * Frames:: Likewise, accessors for stack frames.
69 @subsubsection Stack Capture
71 A Scheme program can use the @code{make-stack} primitive anywhere in its
72 code, with first arg @code{#t}, to construct a Scheme value that
73 describes the Scheme stack at that point.
81 Use @code{start-stack} to limit the stack extent captured by future
82 @code{make-stack} calls.
84 @deffn {Scheme Procedure} make-stack obj arg @dots{}
85 @deffnx {C Function} scm_make_stack (obj, args)
86 Create a new stack. If @var{obj} is @code{#t}, the current
87 evaluation stack is used for creating the stack frames,
88 otherwise the frames are taken from @var{obj} (which must be
89 a continuation or a frame object).
91 @var{arg} @dots{} can be any combination of integer, procedure, prompt
92 tag and @code{#t} values.
94 These values specify various ways of cutting away uninteresting
95 stack frames from the top and bottom of the stack that
96 @code{make-stack} returns. They come in pairs like this:
97 @code{(@var{inner_cut_1} @var{outer_cut_1} @var{inner_cut_2}
98 @var{outer_cut_2} @dots{})}.
100 Each @var{inner_cut_i} can be @code{#t}, an integer, a prompt
101 tag, or a procedure. @code{#t} means to cut away all frames up
102 to but excluding the first user module frame. An integer means
103 to cut away exactly that number of frames. A prompt tag means
104 to cut away all frames that are inside a prompt with the given
105 tag. A procedure means to cut away all frames up to but
106 excluding the application frame whose procedure matches the
109 Each @var{outer_cut_i} can be an integer, a prompt tag, or a
110 procedure. An integer means to cut away that number of frames.
111 A prompt tag means to cut away all frames that are outside a
112 prompt with the given tag. A procedure means to cut away
113 frames down to but excluding the application frame whose
114 procedure matches the specified one.
116 If the @var{outer_cut_i} of the last pair is missing, it is
120 @deffn {Scheme Syntax} start-stack id exp
121 Evaluate @var{exp} on a new calling stack with identity @var{id}. If
122 @var{exp} is interrupted during evaluation, backtraces will not display
123 frames farther back than @var{exp}'s top-level form. This macro is a
124 way of artificially limiting backtraces and stack procedures, largely as
125 a convenience to the user.
130 @subsubsection Stacks
132 @deffn {Scheme Procedure} stack? obj
133 @deffnx {C Function} scm_stack_p (obj)
134 Return @code{#t} if @var{obj} is a calling stack.
137 @deffn {Scheme Procedure} stack-id stack
138 @deffnx {C Function} scm_stack_id (stack)
139 Return the identifier given to @var{stack} by @code{start-stack}.
142 @deffn {Scheme Procedure} stack-length stack
143 @deffnx {C Function} scm_stack_length (stack)
144 Return the length of @var{stack}.
147 @deffn {Scheme Procedure} stack-ref stack index
148 @deffnx {C Function} scm_stack_ref (stack, index)
149 Return the @var{index}'th frame from @var{stack}.
152 @deffn {Scheme Procedure} display-backtrace stack port [first [depth [highlights]]]
153 @deffnx {C Function} scm_display_backtrace_with_highlights (stack, port, first, depth, highlights)
154 @deffnx {C Function} scm_display_backtrace (stack, port, first, depth)
155 Display a backtrace to the output port @var{port}. @var{stack}
156 is the stack to take the backtrace from, @var{first} specifies
157 where in the stack to start and @var{depth} how many frames
158 to display. @var{first} and @var{depth} can be @code{#f},
159 which means that default values will be used.
160 If @var{highlights} is given it should be a list; the elements
161 of this list will be highlighted wherever they appear in the
167 @subsubsection Frames
169 @deffn {Scheme Procedure} frame? obj
170 @deffnx {C Function} scm_frame_p (obj)
171 Return @code{#t} if @var{obj} is a stack frame.
174 @deffn {Scheme Procedure} frame-previous frame
175 @deffnx {C Function} scm_frame_previous (frame)
176 Return the previous frame of @var{frame}, or @code{#f} if
177 @var{frame} is the first frame in its stack.
180 @deffn {Scheme Procedure} frame-procedure frame
181 @deffnx {C Function} scm_frame_procedure (frame)
182 Return the procedure for @var{frame}, or @code{#f} if no
183 procedure is associated with @var{frame}.
186 @deffn {Scheme Procedure} frame-arguments frame
187 @deffnx {C Function} scm_frame_arguments (frame)
188 Return the arguments of @var{frame}.
191 @deffn {Scheme Procedure} frame-address frame
192 @deffnx {Scheme Procedure} frame-instruction-pointer frame
193 @deffnx {Scheme Procedure} frame-stack-pointer frame
194 Accessors for the three VM registers associated with this frame: the
195 frame pointer (fp), instruction pointer (ip), and stack pointer (sp),
196 respectively. @xref{VM Concepts}, for more information.
199 @deffn {Scheme Procedure} frame-dynamic-link frame
200 @deffnx {Scheme Procedure} frame-return-address frame
201 @deffnx {Scheme Procedure} frame-mv-return-address frame
202 Accessors for the three saved VM registers in a frame: the previous
203 frame pointer, the single-value return address, and the multiple-value
204 return address. @xref{Stack Layout}, for more information.
207 @deffn {Scheme Procedure} frame-num-locals frame
208 @deffnx {Scheme Procedure} frame-local-ref frame i
209 @deffnx {Scheme Procedure} frame-local-set! frame i val
210 Accessors for the temporary values corresponding to @var{frame}'s
211 procedure application. The first local is the first argument given to
212 the procedure. After the arguments, there are the local variables, and
213 after that temporary values. @xref{Stack Layout}, for more information.
216 @deffn {Scheme Procedure} display-application frame [port [indent]]
217 @deffnx {C Function} scm_display_application (frame, port, indent)
218 Display a procedure application @var{frame} to the output port
219 @var{port}. @var{indent} specifies the indentation of the
223 Additionally, the @code{(system vm frame)} module defines a number of
224 higher-level introspective procedures, for example to retrieve the names
225 of local variables, and the source location to correspond to a
226 frame. See its source code for more details.
229 @node Source Properties
230 @subsection Source Properties
232 @cindex source properties
233 As Guile reads in Scheme code from file or from standard input, it
234 remembers the file name, line number and column number where each
235 expression begins. These pieces of information are known as the
236 @dfn{source properties} of the expression. Syntax expanders and the
237 compiler propagate these source properties to compiled procedures, so
238 that, if an error occurs when evaluating the transformed expression,
239 Guile's debugger can point back to the file and location where the
240 expression originated.
242 The way that source properties are stored means that Guile cannot
243 associate source properties with individual symbols, keywords,
244 characters, booleans, or small integers. This can be seen by typing
245 @code{(xxx)} and @code{xxx} at the Guile prompt (where the variable
246 @code{xxx} has not been defined):
249 scheme@@(guile-user)> (xxx)
250 <unnamed port>:4:1: In procedure module-lookup:
251 <unnamed port>:4:1: Unbound variable: xxx
253 scheme@@(guile-user)> xxx
254 ERROR: In procedure module-lookup:
255 ERROR: Unbound variable: xxx
259 In the latter case, no source properties were stored, so the error
260 doesn't have any source information.
262 @deffn {Scheme Procedure} supports-source-properties? obj
263 @deffnx {C Function} scm_supports_source_properties_p (obj)
264 Return #t if source properties can be associated with @var{obj},
268 The recording of source properties is controlled by the read option
269 named ``positions'' (@pxref{Scheme Read}). This option is switched
270 @emph{on} by default.
272 The following procedures can be used to access and set the source
273 properties of read expressions.
275 @deffn {Scheme Procedure} set-source-properties! obj alist
276 @deffnx {C Function} scm_set_source_properties_x (obj, alist)
277 Install the association list @var{alist} as the source property
281 @deffn {Scheme Procedure} set-source-property! obj key datum
282 @deffnx {C Function} scm_set_source_property_x (obj, key, datum)
283 Set the source property of object @var{obj}, which is specified by
284 @var{key} to @var{datum}. Normally, the key will be a symbol.
287 @deffn {Scheme Procedure} source-properties obj
288 @deffnx {C Function} scm_source_properties (obj)
289 Return the source property association list of @var{obj}.
292 @deffn {Scheme Procedure} source-property obj key
293 @deffnx {C Function} scm_source_property (obj, key)
294 Return the property specified by @var{key} from @var{obj}'s source
298 If the @code{positions} reader option is enabled, supported expressions
299 will have values set for the @code{filename}, @code{line} and
300 @code{column} properties.
302 Source properties are also associated with syntax objects. Procedural
303 macros can get at the source location of their input using the
304 @code{syntax-source} accessor. @xref{Syntax Transformer Helpers}, for
307 Guile also defines a couple of convenience macros built on
308 @code{syntax-source}:
310 @deffn {Scheme Syntax} current-source-location
311 Expands to the source properties corresponding to the location of the
312 @code{(current-source-location)} form.
315 @deffn {Scheme Syntax} current-filename
316 Expands to the current filename: the filename that the
317 @code{(current-filename)} form appears in. Expands to @code{#f} if this
318 information is unavailable.
321 If you're stuck with defmacros (@pxref{Defmacros}), and want to preserve
322 source information, the following helper function might be useful to
325 @deffn {Scheme Procedure} cons-source xorig x y
326 @deffnx {C Function} scm_cons_source (xorig, x, y)
327 Create and return a new pair whose car and cdr are @var{x} and @var{y}.
328 Any source properties associated with @var{xorig} are also associated
333 @node Programmatic Error Handling
334 @subsection Programmatic Error Handling
336 For better or for worse, all programs have bugs, and dealing with bugs
337 is part of programming. This section deals with that class of bugs that
338 causes an exception to be raised -- from your own code, from within a
339 library, or from Guile itself.
342 * Catching Exceptions:: Handling errors after the stack is unwound.
343 * Capturing Stacks:: Capturing the stack at the time of error.
344 * Pre-Unwind Debugging:: Debugging before the exception is thrown.
345 * Debug Options:: A historical interface to debugging.
348 @node Catching Exceptions
349 @subsubsection Catching Exceptions
351 A common requirement is to be able to show as much useful context as
352 possible when a Scheme program hits an error. The most immediate
353 information about an error is the kind of error that it is -- such as
354 ``division by zero'' -- and any parameters that the code which signalled
355 the error chose explicitly to provide. This information originates with
356 the @code{error} or @code{throw} call (or their C code equivalents, if
357 the error is detected by C code) that signals the error, and is passed
358 automatically to the handler procedure of the innermost applicable
359 @code{catch} or @code{with-throw-handler} expression.
361 Therefore, to catch errors that occur within a chunk of Scheme code, and
362 to intercept basic information about those errors, you need to execute
363 that code inside the dynamic context of a @code{catch} or
364 @code{with-throw-handler} expression, or the equivalent in C. In Scheme,
365 this means you need something like this:
370 ;; Execute the code in which
371 ;; you want to catch errors here.
373 (lambda (key . parameters)
374 ;; Put the code which you want
375 ;; to handle an error here.
380 The @code{catch} here can also be @code{with-throw-handler}; see
381 @ref{Throw Handlers} for information on the when you might want to use
382 @code{with-throw-handler} instead of @code{catch}.
384 For example, to print out a message and return #f when an error occurs,
388 (define (catch-all thunk)
391 (lambda (key . parameters)
392 (format (current-error-port)
393 "Uncaught throw to '~a: ~a\n" key parameters)
397 (lambda () (error "Not a vegetable: tomato")))
398 @print{} Uncaught throw to 'misc-error: (#f ~A (Not a vegetable: tomato) #f)
402 The @code{#t} means that the catch is applicable to all kinds of error.
403 If you want to restrict your catch to just one kind of error, you can
404 put the symbol for that kind of error instead of @code{#t}. The
405 equivalent to this in C would be something like this:
408 SCM my_body_proc (void *body_data)
410 /* Execute the code in which
411 you want to catch errors here. */
415 SCM my_handler_proc (void *handler_data,
419 /* Put the code which you want
420 to handle an error here. */
426 scm_c_catch (SCM_BOOL_T,
427 my_body_proc, body_data,
428 my_handler_proc, handler_data,
435 Again, as with the Scheme version, @code{scm_c_catch} could be replaced
436 by @code{scm_c_with_throw_handler}, and @code{SCM_BOOL_T} could instead
437 be the symbol for a particular kind of error.
439 @node Capturing Stacks
440 @subsubsection Capturing the full error stack
442 The other interesting information about an error is the full Scheme
443 stack at the point where the error occurred; in other words what
444 innermost expression was being evaluated, what was the expression that
445 called that one, and so on. If you want to write your code so that it
446 captures and can display this information as well, there are a couple
447 important things to understand.
449 Firstly, the stack at the point of the error needs to be explicitly
450 captured by a @code{make-stack} call (or the C equivalent
451 @code{scm_make_stack}). The Guile library does not do this
452 ``automatically'' for you, so you will need to write code with a
453 @code{make-stack} or @code{scm_make_stack} call yourself. (We emphasise
454 this point because some people are misled by the fact that the Guile
455 interactive REPL code @emph{does} capture and display the stack
456 automatically. But the Guile interactive REPL is itself a Scheme
457 program@footnote{In effect, it is the default program which is run when
458 no commands or script file are specified on the Guile command line.}
459 running on top of the Guile library, and which uses @code{catch} and
460 @code{make-stack} in the way we are about to describe to capture the
461 stack when an error occurs.)
463 And secondly, in order to capture the stack effectively at the point
464 where the error occurred, the @code{make-stack} call must be made before
465 Guile unwinds the stack back to the location of the prevailing catch
466 expression. This means that the @code{make-stack} call must be made
467 within the handler of a @code{with-throw-handler} expression, or the
468 optional "pre-unwind" handler of a @code{catch}. (For the full story of
469 how these alternatives differ from each other, see @ref{Exceptions}. The
470 main difference is that @code{catch} terminates the error, whereas
471 @code{with-throw-handler} only intercepts it temporarily and then allow
472 it to continue propagating up to the next innermost handler.)
474 So, here are some examples of how to do all this in Scheme and in C.
475 For the purpose of these examples we assume that the captured stack
476 should be stored in a variable, so that it can be displayed or
477 arbitrarily processed later on. In Scheme:
480 (let ((captured-stack #f))
483 ;; Execute the code in which
484 ;; you want to catch errors here.
486 (lambda (key . parameters)
487 ;; Put the code which you want
488 ;; to handle an error after the
489 ;; stack has been unwound here.
491 (lambda (key . parameters)
492 ;; Capture the stack here:
493 (set! captured-stack (make-stack #t))))
497 ;; Display or process the captured stack.
506 SCM my_body_proc (void *body_data)
508 /* Execute the code in which
509 you want to catch errors here. */
513 SCM my_handler_proc (void *handler_data,
517 /* Put the code which you want
518 to handle an error after the
519 stack has been unwound here. */
523 SCM my_preunwind_proc (void *handler_data,
527 /* Capture the stack here: */
528 *(SCM *)handler_data = scm_make_stack (SCM_BOOL_T, SCM_EOL);
532 SCM captured_stack = SCM_BOOL_F;
534 scm_c_catch (SCM_BOOL_T,
535 my_body_proc, body_data,
536 my_handler_proc, handler_data,
537 my_preunwind_proc, &captured_stack);
539 if (captured_stack != SCM_BOOL_F)
541 /* Display or process the captured stack. */
548 Once you have a captured stack, you can interrogate and display its
549 details in any way that you want, using the @code{stack-@dots{}} and
550 @code{frame-@dots{}} API described in @ref{Stacks} and
553 If you want to print out a backtrace in the same format that the Guile
554 REPL does, you can use the @code{display-backtrace} procedure to do so.
555 You can also use @code{display-application} to display an individual
556 frame in the Guile REPL format.
558 @node Pre-Unwind Debugging
559 @subsubsection Pre-Unwind Debugging
561 Instead of saving a stack away and waiting for the @code{catch} to
562 return, you can handle errors directly, from within the pre-unwind
565 For example, to show a backtrace when an error is thrown, you might want
566 to use a procedure like this:
569 (define (with-backtrace thunk)
570 (with-throw-handler #t
572 (lambda args (backtrace))))
573 (with-backtrace (lambda () (error "Not a vegetable: tomato")))
576 Since we used @code{with-throw-handler} here, we didn't actually catch
577 the error. @xref{Throw Handlers}, for more information. However, we did
578 print out a context at the time of the error, using the built-in
579 procedure, @code{backtrace}.
581 @deffn {Scheme Procedure} backtrace [highlights]
582 @deffnx {C Function} scm_backtrace_with_highlights (highlights)
583 @deffnx {C Function} scm_backtrace ()
584 Display a backtrace of the current stack to the current output port. If
585 @var{highlights} is given it should be a list; the elements of this list
586 will be highlighted wherever they appear in the backtrace.
589 The Guile REPL code (in @file{system/repl/repl.scm} and related files)
590 uses a @code{catch} with a pre-unwind handler to capture the stack when
591 an error occurs in an expression that was typed into the REPL, and debug
592 that stack interactively in the context of the error.
594 These procedures are available for use by user programs, in the
595 @code{(system repl error-handling)} module.
598 (use-modules (system repl error-handling))
601 @deffn {Scheme Procedure} call-with-error-handling thunk @
602 [#:on-error on-error='debug] [#:post-error post-error='catch] @
603 [#:pass-keys pass-keys='(quit)] [#:trap-handler trap-handler='debug]
604 Call a thunk in a context in which errors are handled.
606 There are four keyword arguments:
610 Specifies what to do before the stack is unwound.
612 Valid options are @code{debug} (the default), which will enter a
613 debugger; @code{pass}, in which case nothing is done, and the exception
614 is rethrown; or a procedure, which will be the pre-unwind handler.
617 Specifies what to do after the stack is unwound.
619 Valid options are @code{catch} (the default), which will silently catch
620 errors, returning the unspecified value; @code{report}, which prints out
621 a description of the error (via @code{display-error}), and then returns
622 the unspecified value; or a procedure, which will be the catch handler.
625 Specifies a trap handler: what to do when a breakpoint is hit.
627 Valid options are @code{debug}, which will enter the debugger;
628 @code{pass}, which does nothing; or @code{disabled}, which disables
629 traps entirely. @xref{Traps}, for more information.
632 A set of keys to ignore, as a list.
637 @subsubsection Debug options
639 The behavior of the @code{backtrace} procedure and of the default error
640 handler can be parameterized via the debug options.
642 @cindex options - debug
643 @cindex debug options
644 @deffn {Scheme Procedure} debug-options [setting]
645 Display the current settings of the debug options. If @var{setting} is
646 omitted, only a short form of the current read options is printed.
647 Otherwise if @var{setting} is the symbol @code{help}, a complete options
648 description is displayed.
651 The set of available options, and their default values, may be had by
652 invoking @code{debug-options} at the prompt.
655 scheme@@(guile-user)>
656 backwards no Display backtrace in anti-chronological order.
657 width 79 Maximal width of backtrace.
658 depth 20 Maximal length of printed backtrace.
659 backtrace yes Show backtrace on error.
660 stack 1048576 Stack size limit (measured in words;
662 show-file-name #t Show file names and line numbers in backtraces
663 when not `#f'. A value of `base' displays only
664 base names, while `#t' displays full names.
665 warn-deprecated no Warn when deprecated features are used.
668 The boolean options may be toggled with @code{debug-enable} and
669 @code{debug-disable}. The non-boolean @code{keywords} option must be set
670 using @code{debug-set!}.
672 @deffn {Scheme Procedure} debug-enable option-name
673 @deffnx {Scheme Procedure} debug-disable option-name
674 @deffnx {Scheme Syntax} debug-set! option-name value
675 Modify the debug options. @code{debug-enable} should be used with boolean
676 options and switches them on, @code{debug-disable} switches them off.
678 @code{debug-set!} can be used to set an option to a specific value. Due
679 to historical oddities, it is a macro that expects an unquoted option
683 @subsubheading Stack overflow
685 @cindex overflow, stack
686 @cindex stack overflow
687 Stack overflow errors are caused by a computation trying to use more
688 stack space than has been enabled by the @code{stack} option. There are
689 actually two kinds of stack that can overflow, the C stack and the
692 Scheme stack overflows can occur if Scheme procedures recurse too far
693 deeply. An example would be the following recursive loop:
696 scheme@@(guile-user)> (let lp () (+ 1 (lp)))
697 <unnamed port>:8:17: In procedure vm-run:
698 <unnamed port>:8:17: VM: Stack overflow
701 The default stack size should allow for about 10000 frames or so, so one
702 usually doesn't hit this level of recursion. Unfortunately there is no
703 way currently to make a VM with a bigger stack. If you are in this
704 unfortunate situation, please file a bug, and in the meantime, rewrite
705 your code to be tail-recursive (@pxref{Tail Calls}).
707 The other limit you might hit would be C stack overflows. If you call a
708 primitive procedure which then calls a Scheme procedure in a loop, you
709 will consume C stack space. Guile tries to detect excessive consumption
710 of C stack space, throwing an error when you have hit 80% of the
711 process' available stack (as allocated by the operating system), or 160
712 kilowords in the absence of a strict limit.
714 For example, looping through @code{call-with-vm}, a primitive that calls
715 a thunk, gives us the following:
718 scheme@@(guile-user)> (use-modules (system vm vm))
719 scheme@@(guile-user)> (debug-set! stack 10000)
720 scheme@@(guile-user)> (let lp () (call-with-vm (the-vm) lp))
721 ERROR: In procedure call-with-vm:
722 ERROR: Stack overflow
725 If you get an error like this, you can either try rewriting your code to
726 use less stack space, or increase the maximum stack size. To increase
727 the maximum stack size, use @code{debug-set!}, for example:
730 (debug-set! stack 200000)
733 But of course it's better to have your code operate without so much
734 resource consumption, avoiding loops through C trampolines.
745 @cindex Code coverage
747 Guile's virtual machine can be configured to call out at key points to
748 arbitrary user-specified procedures.
750 In principle, these @dfn{hooks} allow Scheme code to implement any model
751 it chooses for examining the evaluation stack as program execution
752 proceeds, and for suspending execution to be resumed later.
754 VM hooks are very low-level, though, and so Guile also has a library of
755 higher-level @dfn{traps} on top of the VM hooks. A trap is an execution
756 condition that, when fulfilled, will fire a handler. For example, Guile
757 defines a trap that fires when control reaches a certain source
760 Finally, Guile also defines a third level of abstractions: per-thread
761 @dfn{trap states}. A trap state exists to give names to traps, and to
762 hold on to the set of traps so that they can be enabled, disabled, or
763 removed. The trap state infrastructure defines the most useful
764 abstractions for most cases. For example, Guile's REPL uses trap state
765 functions to set breakpoints and tracepoints.
767 The following subsections describe all this in detail, for both the
768 user wanting to use traps, and the developer interested in
769 understanding how the interface hangs together.
773 * VM Hooks:: Modifying Guile's virtual machine.
774 * Trap Interface:: Traps are on or off.
775 * Low-Level Traps:: The various kinds of low-level traps.
776 * Tracing Traps:: Traps to trace procedure calls and returns.
777 * Trap States:: One state (per thread) to bind them.
778 * High-Level Traps:: The highest-level trap interface. Use this.
783 @subsubsection VM Hooks
785 Everything that runs in Guile runs on its virtual machine, a C program
786 that defines a number of operations that Scheme programs can
789 Note that there are multiple VM ``engines'' for Guile. Only some of them
790 have support for hooks compiled in. Normally the deal is that you get
791 hooks if you are running interactively, and otherwise they are disabled,
792 as they do have some overhead (about 10 or 20 percent).
794 To ensure that you are running with hooks, pass @code{--debug} to Guile
795 when running your program, or otherwise use the @code{call-with-vm} and
796 @code{set-vm-engine!} procedures to ensure that you are running in a VM
797 with the @code{debug} engine.
799 To digress, Guile's VM has 6 different hooks (@pxref{Hooks}) that can be
800 fired at different times, which may be accessed with the following
803 All hooks are called with one argument, the frame in
804 question. @xref{Frames}. Since these hooks may be fired very
805 frequently, Guile does a terrible thing: it allocates the frames on the
806 C stack instead of the garbage-collected heap.
808 The upshot here is that the frames are only valid within the dynamic
809 extent of the call to the hook. If a hook procedure keeps a reference to
810 the frame outside the extent of the hook, bad things will happen.
812 The interface to hooks is provided by the @code{(system vm vm)} module:
815 (use-modules (system vm vm))
819 The result of calling @code{the-vm} is usually passed as the @var{vm}
820 argument to all of these procedures.
822 @deffn {Scheme Procedure} vm-next-hook vm
823 The hook that will be fired before an instruction is retired (and
827 @deffn {Scheme Procedure} vm-push-continuation-hook vm
828 The hook that will be fired after preparing a new frame. Fires just
829 before applying a procedure in a non-tail context, just before the
830 corresponding apply-hook.
833 @deffn {Scheme Procedure} vm-pop-continuation-hook vm
834 The hook that will be fired before returning from a frame.
836 This hook is a bit trickier than the rest, in that there is a particular
837 interpretation of the values on the stack. Specifically, the top value
838 on the stack is the number of values being returned, and the next
839 @var{n} values are the actual values being returned, with the last value
840 highest on the stack.
843 @deffn {Scheme Procedure} vm-apply-hook vm
844 The hook that will be fired before a procedure is applied. The frame's
845 procedure will have already been set to the new procedure.
847 Note that procedure application is somewhat orthogonal to continuation
848 pushes and pops. A non-tail call to a procedure will result first in a
849 firing of the push-continuation hook, then this application hook,
850 whereas a tail call will run without having fired a push-continuation
854 @deffn {Scheme Procedure} vm-abort-continuation-hook vm
855 The hook that will be called after aborting to a
856 prompt. @xref{Prompts}. The stack will be in the same state as for
857 @code{vm-pop-continuation-hook}.
860 @deffn {Scheme Procedure} vm-restore-continuation-hook vm
861 The hook that will be called after restoring an undelimited
862 continuation. Unfortunately it's not currently possible to introspect on
863 the values that were given to the continuation.
866 @cindex VM trace level
867 These hooks do impose a performance penalty, if they are on. Obviously,
868 the @code{vm-next-hook} has quite an impact, performance-wise. Therefore
869 Guile exposes a single, heavy-handed knob to turn hooks on or off, the
870 @dfn{VM trace level}. If the trace level is positive, hooks run;
871 otherwise they don't.
873 For convenience, when the VM fires a hook, it does so with the trap
874 level temporarily set to 0. That way the hooks don't fire while you're
875 handling a hook. The trace level is restored to whatever it was once the hook
878 @deffn {Scheme Procedure} vm-trace-level vm
879 Retrieve the ``trace level'' of the VM. If positive, the trace hooks
880 associated with @var{vm} will be run. The initial trace level is 0.
883 @deffn {Scheme Procedure} set-vm-trace-level! vm level
884 Set the ``trace level'' of the VM.
887 @xref{A Virtual Machine for Guile}, for more information on Guile's
891 @subsubsection Trap Interface
893 The capabilities provided by hooks are great, but hooks alone rarely
894 correspond to what users want to do.
896 For example, if a user wants to break when and if control reaches a
897 certain source location, how do you do it? If you install a ``next''
898 hook, you get unacceptable overhead for the execution of the entire
899 program. It would be possible to install an ``apply'' hook, then if the
900 procedure encompasses those source locations, install a ``next'' hook,
901 but already you're talking about one concept that might be implemented
902 by a varying number of lower-level concepts.
904 It's best to be clear about things and define one abstraction for all
905 such conditions: the @dfn{trap}.
907 Considering the myriad capabilities offered by the hooks though, there
908 is only a minimum of functionality shared by all traps. Guile's current
909 take is to reduce this to the absolute minimum, and have the only
910 standard interface of a trap be ``turn yourself on'' or ``turn yourself
913 This interface sounds a bit strange, but it is useful to procedurally
914 compose higher-level traps from lower-level building blocks. For
915 example, Guile defines a trap that calls one handler when control enters
916 a procedure, and another when control leaves the procedure. Given that
917 trap, one can define a trap that adds to the next-hook only when within
918 a given procedure. Building further, one can define a trap that fires
919 when control reaches particular instructions within a procedure.
921 Or of course you can stop at any of these intermediate levels. For
922 example, one might only be interested in calls to a given procedure. But
923 the point is that a simple enable/disable interface is all the
924 commonality that exists between the various kinds of traps, and
925 furthermore that such an interface serves to allow ``higher-level''
926 traps to be composed from more primitive ones.
928 Specifically, a trap, in Guile, is a procedure. When a trap is created,
929 by convention the trap is enabled; therefore, the procedure that is the
930 trap will, when called, disable the trap, and return a procedure that
931 will enable the trap, and so on.
933 Trap procedures take one optional argument: the current frame. (A trap
934 may want to add to different sets of hooks depending on the frame that
935 is current at enable-time.)
937 If this all sounds very complicated, it's because it is. Some of it is
938 essential, but probably most of it is not. The advantage of using this
939 minimal interface is that composability is more lexically apparent than
940 when, for example, using a stateful interface based on GOOPS. But
941 perhaps this reflects the cognitive limitations of the programmer who
942 made the current interface more than anything else.
944 @node Low-Level Traps
945 @subsubsection Low-Level Traps
947 To summarize the last sections, traps are enabled or disabled, and when
948 they are enabled, they add to various VM hooks.
950 Note, however, that @emph{traps do not increase the VM trace level}. So
951 if you create a trap, it will be enabled, but unless something else
952 increases the VM's trace level (@pxref{VM Hooks}), the trap will not
953 fire. It turns out that getting the VM trace level right is tricky
954 without a global view of what traps are enabled. @xref{Trap States},
955 for Guile's answer to this problem.
957 Traps are created by calling procedures. Most of these procedures share
958 a set of common keyword arguments, so rather than document them
959 separately, we discuss them all together here:
963 The VM to instrument. Defaults to the current thread's VM.
965 For traps that depend on the current frame's procedure, this argument
966 specifies whether to trap on the only the specific procedure given, or
967 on any closure that has the given procedure's code. Defaults to
969 @item #:current-frame
970 For traps that enable more hooks depending on their dynamic context,
971 this argument gives the current frame that the trap is running in.
972 Defaults to @code{#f}.
975 To have access to these procedures, you'll need to have imported the
976 @code{(system vm traps)} module:
979 (use-modules (system vm traps))
982 @deffn {Scheme Procedure} trap-at-procedure-call proc handler @
984 A trap that calls @var{handler} when @var{proc} is applied.
987 @deffn {Scheme Procedure} trap-in-procedure proc @
988 enter-handler exit-handler [#:current-frame] [#:vm] [#:closure?]
989 A trap that calls @var{enter-handler} when control enters @var{proc},
990 and @var{exit-handler} when control leaves @var{proc}.
992 Control can enter a procedure via:
997 A return to a procedure's frame on the stack.
999 A continuation returning directly to an application of this procedure.
1002 Control can leave a procedure via:
1005 A normal return from the procedure.
1007 An application of another procedure.
1009 An invocation of a continuation.
1015 @deffn {Scheme Procedure} trap-instructions-in-procedure proc @
1016 next-handler exit-handler [#:current-frame] [#:vm] [#:closure?]
1017 A trap that calls @var{next-handler} for every instruction executed in
1018 @var{proc}, and @var{exit-handler} when execution leaves @var{proc}.
1021 @deffn {Scheme Procedure} trap-at-procedure-ip-in-range proc range @
1022 handler [#:current-frame] [#:vm] [#:closure?]
1023 A trap that calls @var{handler} when execution enters a range of
1024 instructions in @var{proc}. @var{range} is a simple of pairs,
1025 @code{((@var{start} . @var{end}) ...)}. The @var{start} addresses are
1026 inclusive, and @var{end} addresses are exclusive.
1029 @deffn {Scheme Procedure} trap-at-source-location file user-line handler @
1030 [#:current-frame] [#:vm]
1031 A trap that fires when control reaches a given source location. The
1032 @var{user-line} parameter is one-indexed, as a user counts lines,
1033 instead of zero-indexed, as Guile counts lines.
1036 @deffn {Scheme Procedure} trap-frame-finish frame @
1037 return-handler abort-handler [#:vm]
1038 A trap that fires when control leaves the given frame. @var{frame}
1039 should be a live frame in the current continuation. @var{return-handler}
1040 will be called on a normal return, and @var{abort-handler} on a nonlocal
1044 @deffn {Scheme Procedure} trap-in-dynamic-extent proc @
1045 enter-handler return-handler abort-handler [#:vm] [#:closure?]
1046 A more traditional dynamic-wind trap, which fires @var{enter-handler}
1047 when control enters @var{proc}, @var{return-handler} on a normal return,
1048 and @var{abort-handler} on a nonlocal exit.
1050 Note that rewinds are not handled, so there is no rewind handler.
1053 @deffn {Scheme Procedure} trap-calls-in-dynamic-extent proc @
1054 apply-handler return-handler [#:current-frame] [#:vm] [#:closure?]
1055 A trap that calls @var{apply-handler} every time a procedure is applied,
1056 and @var{return-handler} for returns, but only during the dynamic extent
1057 of an application of @var{proc}.
1060 @deffn {Scheme Procedure} trap-instructions-in-dynamic-extent proc @
1061 next-handler [#:current-frame] [#:vm] [#:closure?]
1062 A trap that calls @var{next-handler} for all retired instructions within
1063 the dynamic extent of a call to @var{proc}.
1066 @deffn {Scheme Procedure} trap-calls-to-procedure proc @
1067 apply-handler return-handler [#:vm]
1068 A trap that calls @var{apply-handler} whenever @var{proc} is applied,
1069 and @var{return-handler} when it returns, but with an additional
1070 argument, the call depth.
1072 That is to say, the handlers will get two arguments: the frame in
1073 question, and the call depth (a non-negative integer).
1076 @deffn {Scheme Procedure} trap-matching-instructions frame-pred handler [#:vm]
1077 A trap that calls @var{frame-pred} at every instruction, and if
1078 @var{frame-pred} returns a true value, calls @var{handler} on the
1083 @subsubsection Tracing Traps
1085 The @code{(system vm trace)} module defines a number of traps for
1086 tracing of procedure applications. When a procedure is @dfn{traced}, it
1087 means that every call to that procedure is reported to the user during a
1088 program run. The idea is that you can mark a collection of procedures
1089 for tracing, and Guile will subsequently print out a line of the form
1092 | | (@var{procedure} @var{args} @dots{})
1095 whenever a marked procedure is about to be applied to its arguments.
1096 This can help a programmer determine whether a function is being called
1097 at the wrong time or with the wrong set of arguments.
1099 In addition, the indentation of the output is useful for demonstrating
1100 how the traced applications are or are not tail recursive with respect
1101 to each other. Thus, a trace of a non-tail recursive factorial
1102 implementation looks like this:
1105 scheme@@(guile-user)> (define (fact1 n)
1107 (* n (fact1 (1- n)))))
1108 scheme@@(guile-user)> ,trace (fact1 4)
1111 trace: | | (fact1 2)
1112 trace: | | | (fact1 1)
1113 trace: | | | | (fact1 0)
1121 While a typical tail recursive implementation would look more like this:
1124 scheme@@(guile-user)> (define (facti acc n)
1126 (facti (* n acc) (1- n))))
1127 scheme@@(guile-user)> (define (fact2 n) (facti 1 n))
1128 scheme@@(guile-user)> ,trace (fact2 4)
1138 The low-level traps below (@pxref{Low-Level Traps}) share some common
1143 The maximum width of trace output. Trace printouts will try not to
1144 exceed this column, but for highly nested procedure calls, it may be
1145 unavoidable. Defaults to 80.
1147 The VM on which to add the traps. Defaults to the current thread's VM.
1149 A string to print out before each trace line. As seen above in the
1150 examples, defaults to @code{"trace: "}.
1153 To have access to these procedures, you'll need to have imported the
1154 @code{(system vm trace)} module:
1157 (use-modules (system vm trace))
1160 @deffn {Scheme Procedure} trace-calls-to-procedure proc @
1161 [#:width] [#:vm] [#:prefix]
1162 Print a trace at applications of and returns from @var{proc}.
1165 @deffn {Scheme Procedure} trace-calls-in-procedure proc @
1166 [#:width] [#:vm] [#:prefix]
1167 Print a trace at all applications and returns within the dynamic extent
1168 of calls to @var{proc}.
1171 @deffn {Scheme Procedure} trace-instructions-in-procedure proc [#:width] [#:vm]
1172 Print a trace at all instructions executed in the dynamic extent of
1173 calls to @var{proc}.
1176 In addition, Guile defines a procedure to call a thunk, tracing all
1177 procedure calls and returns within the thunk.
1179 @deffn {Scheme Procedure} call-with-trace thunk [#:calls?=#t] @
1180 [#:instructions?=#f] @
1181 [#:width=80] [#:vm=(the-vm)]
1182 Call @var{thunk}, tracing all execution within its dynamic extent.
1184 If @var{calls?} is true, Guile will print a brief report at each
1185 procedure call and return, as given above.
1187 If @var{instructions?} is true, Guile will also print a message each
1188 time an instruction is executed. This is a lot of output, but it is
1189 sometimes useful when doing low-level optimization.
1191 Note that because this procedure manipulates the VM trace level
1192 directly, it doesn't compose well with traps at the REPL.
1195 @xref{Profile Commands}, for more information on tracing at the REPL.
1198 @subsubsection Trap States
1200 When multiple traps are present in a system, we begin to have a
1201 bookkeeping problem. How are they named? How does one disable, enable,
1204 Guile's answer to this is to keep an implicit per-thread @dfn{trap
1205 state}. The trap state object is not exposed to the user; rather, API
1206 that works on trap states fetches the current trap state from the
1207 dynamic environment.
1209 Traps are identified by integers. A trap can be enabled, disabled, or
1210 removed, and can have an associated user-visible name.
1212 These procedures have their own module:
1215 (use-modules (system vm trap-state))
1218 @deffn {Scheme Procedure} add-trap! trap name
1219 Add a trap to the current trap state, associating the given @var{name}
1220 with it. Returns a fresh trap identifier (an integer).
1222 Note that usually the more specific functions detailed in
1223 @ref{High-Level Traps} are used in preference to this one.
1226 @deffn {Scheme Procedure} list-traps
1227 List the current set of traps, both enabled and disabled. Returns a list
1231 @deffn {Scheme Procedure} trap-name idx
1232 Returns the name associated with trap @var{idx}, or @code{#f} if there
1236 @deffn {Scheme Procedure} trap-enabled? idx
1237 Returns @code{#t} if trap @var{idx} is present and enabled, or @code{#f}
1241 @deffn {Scheme Procedure} enable-trap! idx
1242 Enables trap @var{idx}.
1245 @deffn {Scheme Procedure} disable-trap! idx
1246 Disables trap @var{idx}.
1249 @deffn {Scheme Procedure} delete-trap! idx
1250 Removes trap @var{idx}, disabling it first, if necessary.
1253 @node High-Level Traps
1254 @subsubsection High-Level Traps
1256 The low-level trap API allows one to make traps that call procedures,
1257 and the trap state API allows one to keep track of what traps are
1258 there. But neither of these APIs directly helps you when you want to
1259 set a breakpoint, because it's unclear what to do when the trap fires.
1260 Do you enter a debugger, or mail a summary of the situation to your
1261 great-aunt, or what?
1263 So for the common case in which you just want to install breakpoints,
1264 and then have them all result in calls to one parameterizable procedure,
1265 we have the high-level trap interface.
1267 Perhaps we should have started this section with this interface, as it's
1268 clearly the one most people should use. But as its capabilities and
1269 limitations proceed from the lower layers, we felt that the
1270 character-building exercise of building a mental model might be helpful.
1272 These procedures share a module with trap states:
1275 (use-modules (system vm trap-state))
1278 @deffn {Scheme Procedure} with-default-trap-handler handler thunk
1279 Call @var{thunk} in a dynamic context in which @var{handler} is the
1280 current trap handler.
1282 Additionally, during the execution of @var{thunk}, the VM trace level
1283 (@pxref{VM Hooks}) is set to the number of enabled traps. This ensures
1284 that traps will in fact fire.
1286 @var{handler} may be @code{#f}, in which case VM hooks are not enabled
1287 as they otherwise would be, as there is nothing to handle the traps.
1290 The trace-level-setting behavior of @code{with-default-trap-handler} is
1291 one of its more useful aspects, but if you are willing to forgo that,
1292 and just want to install a global trap handler, there's a function for
1295 @deffn {Scheme Procedure} install-trap-handler! handler
1296 Set the current thread's trap handler to @var{handler}.
1299 Trap handlers are called when traps installed by procedures from this
1300 module fire. The current ``consumer'' of this API is Guile's REPL, but
1301 one might easily imagine other trap handlers being used to integrate
1302 with other debugging tools.
1305 @cindex Setting breakpoints
1306 @deffn {Scheme Procedure} add-trap-at-procedure-call! proc
1307 Install a trap that will fire when @var{proc} is called.
1309 This is a breakpoint.
1313 @cindex Setting tracepoints
1314 @deffn {Scheme Procedure} add-trace-at-procedure-call! proc
1315 Install a trap that will print a tracing message when @var{proc} is
1316 called. @xref{Tracing Traps}, for more information.
1318 This is a tracepoint.
1321 @deffn {Scheme Procedure} add-trap-at-source-location! file user-line
1322 Install a trap that will fire when control reaches the given source
1323 location. @var{user-line} is one-indexed, as users count lines, instead
1324 of zero-indexed, as Guile counts lines.
1326 This is a source breakpoint.
1329 @deffn {Scheme Procedure} add-ephemeral-trap-at-frame-finish! frame handler
1330 Install a trap that will call @var{handler} when @var{frame} finishes
1331 executing. The trap will be removed from the trap state after firing, or
1334 This is a finish trap, used to implement the ``finish'' REPL command.
1337 @deffn {Scheme Procedure} add-ephemeral-stepping-trap! frame handler [#:into?] [#:instruction?]
1338 Install a trap that will call @var{handler} after stepping to a
1339 different source line or instruction. The trap will be removed from the
1340 trap state after firing, or on nonlocal exit.
1342 If @var{instruction?} is false (the default), the trap will fire when
1343 control reaches a new source line. Otherwise it will fire when control
1344 reaches a new instruction.
1346 Additionally, if @var{into?} is false (not the default), the trap will
1347 only fire for frames at or prior to the given frame. If @var{into?} is
1348 true (the default), the trap may step into nested procedure
1351 This is a stepping trap, used to implement the ``step'', ``next'',
1352 ``step-instruction'', and ``next-instruction'' REPL commands.
1356 @subsection GDB Support
1360 Sometimes, you may find it necessary to debug Guile applications at the
1361 C level. Doing so can be tedious, in particular because the debugger is
1362 oblivious to Guile's @code{SCM} type, and thus unable to display
1363 @code{SCM} values in any meaningful way:
1367 #0 scm_display (obj=0xf04310, port=0x6f9f30) at print.c:1437
1370 To address that, Guile comes with an extension of the GNU Debugger (GDB)
1371 that contains a ``pretty-printer'' for @code{SCM} values. With this GDB
1372 extension, the C frame in the example above shows up like this:
1376 #0 scm_display (obj=("hello" GDB!), port=#<port file 6f9f30>) at print.c:1437
1380 Here GDB was able to decode the list pointed to by @var{obj}, and to
1381 print it using Scheme's read syntax.
1383 That extension is a @code{.scm} file installed alongside the
1384 @file{libguile} shared library. When GDB 7.8 or later is installed and
1385 compiled with support for extensions written in Guile, the extension is
1386 automatically loaded when debugging a program linked against
1387 @file{libguile} (@pxref{Auto-loading,,, gdb, Debugging with GDB}). Note
1388 that the directory where @file{libguile} is installed must be among
1389 GDB's auto-loading ``safe directories'' (@pxref{Auto-loading safe
1390 path,,, gdb, Debugging with GDB}).
1394 @c TeX-master: "guile.texi"