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
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!
24 @node Evaluation Model
25 @subsection Evaluation and the Scheme Stack
27 The idea of the Scheme stack is central to a lot of debugging. The
28 Scheme stack is a reified representation of the pending function returns
29 in an expression's continuation. As Guile implements function calls
30 using a stack, this reification takes the form of a number of nested
31 stack frames, each of which corresponds to the application of a
32 procedure to a set of arguments.
34 A Scheme stack always exists implicitly, and can be summoned into
35 concrete existence as a first-class Scheme value by the
36 @code{make-stack} call, so that an introspective Scheme program -- such
37 as a debugger -- can present it in some way and allow the user to query
38 its details. The first thing to understand, therefore, is how Guile's
39 function call convention creates the stack.
41 Broadly speaking, Guile represents all control flow on a stack. Calling
42 a function involves pushing an empty frame on the stack, then evaluating
43 the procedure and its arguments, then fixing up the new frame so that it
44 points to the old one. Frames on the stack are thus linked together. A
45 tail call is the same, except it reuses the existing frame instead of
48 In this way, the only frames that are on the stack are ``active''
49 frames, frames which need to do some work before the computation is
50 complete. On the other hand, a function that has tail-called another
51 function will not be on the stack, as it has no work left to do.
53 Therefore, when an error occurs in a running program, or the program
54 hits a breakpoint, or in fact at any point that the programmer chooses,
55 its state at that point can be represented by a @dfn{stack} of all the
56 procedure applications that are logically in progress at that time, each
57 of which is known as a @dfn{frame}. The programmer can learn more about
58 the program's state at that point by inspecting the stack and its
62 * Stack Capture:: Reifying a continuation.
63 * Stacks:: Accessors for the stack data type.
64 * Frames:: Likewise, accessors for stack frames.
68 @subsubsection Stack Capture
70 A Scheme program can use the @code{make-stack} primitive anywhere in its
71 code, with first arg @code{#t}, to construct a Scheme value that
72 describes the Scheme stack at that point.
80 Use @code{start-stack} to limit the stack extent captured by future
81 @code{make-stack} calls.
83 @deffn {Scheme Procedure} make-stack obj . args
84 @deffnx {C Function} scm_make_stack (obj, args)
85 Create a new stack. If @var{obj} is @code{#t}, the current
86 evaluation stack is used for creating the stack frames,
87 otherwise the frames are taken from @var{obj} (which must be
88 a continuation or a frame object).
90 @var{args} should be a list containing any combination of
91 integer, procedure, prompt tag and @code{#t} values.
93 These values specify various ways of cutting away uninteresting
94 stack frames from the top and bottom of the stack that
95 @code{make-stack} returns. They come in pairs like this:
96 @code{(@var{inner_cut_1} @var{outer_cut_1} @var{inner_cut_2}
97 @var{outer_cut_2} @dots{})}.
99 Each @var{inner_cut_N} can be @code{#t}, an integer, a prompt
100 tag, or a procedure. @code{#t} means to cut away all frames up
101 to but excluding the first user module frame. An integer means
102 to cut away exactly that number of frames. A prompt tag means
103 to cut away all frames that are inside a prompt with the given
104 tag. A procedure means to cut away all frames up to but
105 excluding the application frame whose procedure matches the
108 Each @var{outer_cut_N} can be an integer, a prompt tag, or a
109 procedure. An integer means to cut away that number of frames.
110 A prompt tag means to cut away all frames that are outside a
111 prompt with the given tag. A procedure means to cut away
112 frames down to but excluding the application frame whose
113 procedure matches the specified one.
115 If the @var{outer_cut_N} of the last pair is missing, it is
119 @deffn {Scheme Syntax} start-stack id exp
120 Evaluate @var{exp} on a new calling stack with identity @var{id}. If
121 @var{exp} is interrupted during evaluation, backtraces will not display
122 frames farther back than @var{exp}'s top-level form. This macro is a
123 way of artificially limiting backtraces and stack procedures, largely as
124 a convenience to the user.
129 @subsubsection Stacks
131 @deffn {Scheme Procedure} stack? obj
132 @deffnx {C Function} scm_stack_p (obj)
133 Return @code{#t} if @var{obj} is a calling stack.
136 @deffn {Scheme Procedure} stack-id stack
137 @deffnx {C Function} scm_stack_id (stack)
138 Return the identifier given to @var{stack} by @code{start-stack}.
141 @deffn {Scheme Procedure} stack-length stack
142 @deffnx {C Function} scm_stack_length (stack)
143 Return the length of @var{stack}.
146 @deffn {Scheme Procedure} stack-ref stack index
147 @deffnx {C Function} scm_stack_ref (stack, index)
148 Return the @var{index}'th frame from @var{stack}.
151 @deffn {Scheme Procedure} display-backtrace stack port [first [depth [highlights]]]
152 @deffnx {C Function} scm_display_backtrace_with_highlights (stack, port, first, depth, highlights)
153 @deffnx {C Function} scm_display_backtrace (stack, port, first, depth)
154 Display a backtrace to the output port @var{port}. @var{stack}
155 is the stack to take the backtrace from, @var{first} specifies
156 where in the stack to start and @var{depth} how many frames
157 to display. @var{first} and @var{depth} can be @code{#f},
158 which means that default values will be used.
159 If @var{highlights} is given it should be a list; the elements
160 of this list will be highlighted wherever they appear in the
166 @subsubsection Frames
168 @deffn {Scheme Procedure} frame? obj
169 @deffnx {C Function} scm_frame_p (obj)
170 Return @code{#t} if @var{obj} is a stack frame.
173 @deffn {Scheme Procedure} frame-previous frame
174 @deffnx {C Function} scm_frame_previous (frame)
175 Return the previous frame of @var{frame}, or @code{#f} if
176 @var{frame} is the first frame in its stack.
179 @deffn {Scheme Procedure} frame-procedure frame
180 @deffnx {C Function} scm_frame_procedure (frame)
181 Return the procedure for @var{frame}, or @code{#f} if no
182 procedure is associated with @var{frame}.
185 @deffn {Scheme Procedure} frame-arguments frame
186 @deffnx {C Function} scm_frame_arguments (frame)
187 Return the arguments of @var{frame}.
190 @deffn {Scheme Procedure} frame-address frame
191 @deffnx {Scheme Procedure} frame-instruction-pointer frame
192 @deffnx {Scheme Procedure} frame-stack-pointer frame
193 Accessors for the three VM registers associated with this frame: the
194 frame pointer (fp), instruction pointer (ip), and stack pointer (sp),
195 respectively. @xref{VM Concepts}, for more information.
198 @deffn {Scheme Procedure} frame-dynamic-link frame
199 @deffnx {Scheme Procedure} frame-return-address frame
200 @deffnx {Scheme Procedure} frame-mv-return-address frame
201 Accessors for the three saved VM registers in a frame: the previous
202 frame pointer, the single-value return address, and the multiple-value
203 return address. @xref{Stack Layout}, for more information.
206 @deffn {Scheme Procedure} frame-num-locals frame
207 @deffnx {Scheme Procedure} frame-local-ref frame i
208 @deffnx {Scheme Procedure} frame-local-set! frame i val
209 Accessors for the temporary values corresponding to @var{frame}'s
210 procedure application. The first local is the first argument given to
211 the procedure. After the arguments, there are the local variables, and
212 after that temporary values. @xref{Stack Layout}, for more information.
215 @deffn {Scheme Procedure} display-application frame [port [indent]]
216 @deffnx {C Function} scm_display_application (frame, port, indent)
217 Display a procedure application @var{frame} to the output port
218 @var{port}. @var{indent} specifies the indentation of the
222 Additionally, the @code{(system vm frame)} module defines a number of
223 higher-level introspective procedures, for example to retrieve the names
224 of local variables, and the source location to correspond to a
225 frame. See its source code for more details.
228 @node Source Properties
229 @subsection Source Properties
231 @cindex source properties
232 As Guile reads in Scheme code from file or from standard input, it
233 remembers the file name, line number and column number where each
234 expression begins. These pieces of information are known as the
235 @dfn{source properties} of the expression. Syntax expanders and the
236 compiler propagate these source properties to compiled procedures, so
237 that, if an error occurs when evaluating the transformed expression,
238 Guile's debugger can point back to the file and location where the
239 expression originated.
241 The way that source properties are stored means that Guile can only
242 associate source properties with parenthesized expressions, and not, for
243 example, with individual symbols, numbers or strings. The difference
244 can be seen by typing @code{(xxx)} and @code{xxx} at the Guile prompt
245 (where the variable @code{xxx} has not been defined):
248 scheme@@(guile-user)> (xxx)
249 <unnamed port>:4:1: In procedure module-lookup:
250 <unnamed port>:4:1: Unbound variable: xxx
252 scheme@@(guile-user)> xxx
253 ERROR: In procedure module-lookup:
254 ERROR: Unbound variable: xxx
258 In the latter case, no source properties were stored, so the error
259 doesn't have any source information.
261 The recording of source properties is controlled by the read option
262 named ``positions'' (@pxref{Scheme Read}). This option is switched
263 @emph{on} by default.
265 The following procedures can be used to access and set the source
266 properties of read expressions.
268 @deffn {Scheme Procedure} set-source-properties! obj alist
269 @deffnx {C Function} scm_set_source_properties_x (obj, alist)
270 Install the association list @var{alist} as the source property
274 @deffn {Scheme Procedure} set-source-property! obj key datum
275 @deffnx {C Function} scm_set_source_property_x (obj, key, datum)
276 Set the source property of object @var{obj}, which is specified by
277 @var{key} to @var{datum}. Normally, the key will be a symbol.
280 @deffn {Scheme Procedure} source-properties obj
281 @deffnx {C Function} scm_source_properties (obj)
282 Return the source property association list of @var{obj}.
285 @deffn {Scheme Procedure} source-property obj key
286 @deffnx {C Function} scm_source_property (obj, key)
287 Return the property specified by @var{key} from @var{obj}'s source
291 If the @code{positions} reader option is enabled, each parenthesized
292 expression will have values set for the @code{filename}, @code{line} and
293 @code{column} properties.
295 If you're stuck with defmacros (@pxref{Defmacros}), and want to preserve
296 source information, the following helper function might be useful to
299 @deffn {Scheme Procedure} cons-source xorig x y
300 @deffnx {C Function} scm_cons_source (xorig, x, y)
301 Create and return a new pair whose car and cdr are @var{x} and @var{y}.
302 Any source properties associated with @var{xorig} are also associated
307 @node Programmatic Error Handling
308 @subsection Programmatic Error Handling
310 For better or for worse, all programs have bugs, and dealing with bugs
311 is part of programming. This section deals with that class of bugs that
312 causes an exception to be raised -- from your own code, from within a
313 library, or from Guile itself.
316 * Catching Exceptions:: Handling errors after the stack is unwound.
317 * Capturing Stacks:: Capturing the stack at the time of error.
318 * Pre-Unwind Debugging:: Debugging before the exception is thrown.
319 * Debug Options:: A historical interface to debugging.
322 @node Catching Exceptions
323 @subsubsection Catching Exceptions
325 A common requirement is to be able to show as much useful context as
326 possible when a Scheme program hits an error. The most immediate
327 information about an error is the kind of error that it is -- such as
328 ``division by zero'' -- and any parameters that the code which signalled
329 the error chose explicitly to provide. This information originates with
330 the @code{error} or @code{throw} call (or their C code equivalents, if
331 the error is detected by C code) that signals the error, and is passed
332 automatically to the handler procedure of the innermost applicable
333 @code{catch} or @code{with-throw-handler} expression.
335 Therefore, to catch errors that occur within a chunk of Scheme code, and
336 to intercept basic information about those errors, you need to execute
337 that code inside the dynamic context of a @code{catch} or
338 @code{with-throw-handler} expression, or the equivalent in C. In Scheme,
339 this means you need something like this:
344 ;; Execute the code in which
345 ;; you want to catch errors here.
347 (lambda (key . parameters)
348 ;; Put the code which you want
349 ;; to handle an error here.
354 The @code{catch} here can also be @code{with-throw-handler}; see
355 @ref{Throw Handlers} for information on the when you might want to use
356 @code{with-throw-handler} instead of @code{catch}.
358 For example, to print out a message and return #f when an error occurs,
362 (define (catch-all thunk)
365 (lambda (key . parameters)
366 (format (current-error-port)
367 "Uncaught throw to '~a: ~a\n" key parameters)
371 (lambda () (error "Not a vegetable: tomato")))
372 @print{} Uncaught throw to 'misc-error: (#f ~A (Not a vegetable: tomato) #f)
376 The @code{#t} means that the catch is applicable to all kinds of error.
377 If you want to restrict your catch to just one kind of error, you can
378 put the symbol for that kind of error instead of @code{#t}. The
379 equivalent to this in C would be something like this:
382 SCM my_body_proc (void *body_data)
384 /* Execute the code in which
385 you want to catch errors here. */
389 SCM my_handler_proc (void *handler_data,
393 /* Put the code which you want
394 to handle an error here. */
400 scm_c_catch (SCM_BOOL_T,
401 my_body_proc, body_data,
402 my_handler_proc, handler_data,
409 Again, as with the Scheme version, @code{scm_c_catch} could be replaced
410 by @code{scm_c_with_throw_handler}, and @code{SCM_BOOL_T} could instead
411 be the symbol for a particular kind of error.
413 @node Capturing Stacks
414 @subsubsection Capturing the full error stack
416 The other interesting information about an error is the full Scheme
417 stack at the point where the error occurred; in other words what
418 innermost expression was being evaluated, what was the expression that
419 called that one, and so on. If you want to write your code so that it
420 captures and can display this information as well, there are a couple
421 important things to understand.
423 Firstly, the stack at the point of the error needs to be explicitly
424 captured by a @code{make-stack} call (or the C equivalent
425 @code{scm_make_stack}). The Guile library does not do this
426 ``automatically'' for you, so you will need to write code with a
427 @code{make-stack} or @code{scm_make_stack} call yourself. (We emphasise
428 this point because some people are misled by the fact that the Guile
429 interactive REPL code @emph{does} capture and display the stack
430 automatically. But the Guile interactive REPL is itself a Scheme
431 program@footnote{In effect, it is the default program which is run when
432 no commands or script file are specified on the Guile command line.}
433 running on top of the Guile library, and which uses @code{catch} and
434 @code{make-stack} in the way we are about to describe to capture the
435 stack when an error occurs.)
437 And secondly, in order to capture the stack effectively at the point
438 where the error occurred, the @code{make-stack} call must be made before
439 Guile unwinds the stack back to the location of the prevailing catch
440 expression. This means that the @code{make-stack} call must be made
441 within the handler of a @code{with-throw-handler} expression, or the
442 optional "pre-unwind" handler of a @code{catch}. (For the full story of
443 how these alternatives differ from each other, see @ref{Exceptions}. The
444 main difference is that @code{catch} terminates the error, whereas
445 @code{with-throw-handler} only intercepts it temporarily and then allow
446 it to continue propagating up to the next innermost handler.)
448 So, here are some examples of how to do all this in Scheme and in C.
449 For the purpose of these examples we assume that the captured stack
450 should be stored in a variable, so that it can be displayed or
451 arbitrarily processed later on. In Scheme:
454 (let ((captured-stack #f))
457 ;; Execute the code in which
458 ;; you want to catch errors here.
460 (lambda (key . parameters)
461 ;; Put the code which you want
462 ;; to handle an error after the
463 ;; stack has been unwound here.
465 (lambda (key . parameters)
466 ;; Capture the stack here:
467 (set! captured-stack (make-stack #t))))
471 ;; Display or process the captured stack.
480 SCM my_body_proc (void *body_data)
482 /* Execute the code in which
483 you want to catch errors here. */
487 SCM my_handler_proc (void *handler_data,
491 /* Put the code which you want
492 to handle an error after the
493 stack has been unwound here. */
497 SCM my_preunwind_proc (void *handler_data,
501 /* Capture the stack here: */
502 *(SCM *)handler_data = scm_make_stack (SCM_BOOL_T, SCM_EOL);
506 SCM captured_stack = SCM_BOOL_F;
508 scm_c_catch (SCM_BOOL_T,
509 my_body_proc, body_data,
510 my_handler_proc, handler_data,
511 my_preunwind_proc, &captured_stack);
513 if (captured_stack != SCM_BOOL_F)
515 /* Display or process the captured stack. */
522 Once you have a captured stack, you can interrogate and display its
523 details in any way that you want, using the @code{stack-@dots{}} and
524 @code{frame-@dots{}} API described in @ref{Stacks} and
527 If you want to print out a backtrace in the same format that the Guile
528 REPL does, you can use the @code{display-backtrace} procedure to do so.
529 You can also use @code{display-application} to display an individual
530 frame in the Guile REPL format.
532 @node Pre-Unwind Debugging
533 @subsubsection Pre-Unwind Debugging
535 Instead of saving a stack away and waiting for the @code{catch} to
536 return, you can handle errors directly, from within the pre-unwind
539 For example, to show a backtrace when an error is thrown, you might want
540 to use a procedure like this:
543 (define (with-backtrace thunk)
544 (with-throw-handler #t
546 (lambda args (backtrace))))
547 (with-backtrace (lambda () (error "Not a vegetable: tomato")))
550 Since we used @code{with-throw-handler} here, we didn't actually catch
551 the error. @xref{Throw Handlers}, for more information. However, we did
552 print out a context at the time of the error, using the built-in
553 procedure, @code{backtrace}.
555 @deffn {Scheme Procedure} backtrace [highlights]
556 @deffnx {C Function} scm_backtrace_with_highlights (highlights)
557 @deffnx {C Function} scm_backtrace ()
558 Display a backtrace of the current stack to the current output port. If
559 @var{highlights} is given it should be a list; the elements of this list
560 will be highlighted wherever they appear in the backtrace.
563 The Guile REPL code (in @file{system/repl/repl.scm} and related files)
564 uses a @code{catch} with a pre-unwind handler to capture the stack when
565 an error occurs in an expression that was typed into the REPL, and debug
566 that stack interactively in the context of the error.
568 These procedures are available for use by user programs, in the
569 @code{(system repl error-handling)} module.
572 (use-modules (system repl error-handling))
575 @deffn {Scheme Procedure} call-with-error-handling thunk @
576 [#:on-error on-error='debug] [#:post-error post-error='catch] @
577 [#:pass-keys pass-keys='(quit)] [#:trap-handler trap-handler='debug]
578 Call a thunk in a context in which errors are handled.
580 There are four keyword arguments:
584 Specifies what to do before the stack is unwound.
586 Valid options are @code{debug} (the default), which will enter a
587 debugger; @code{pass}, in which case nothing is done, and the exception
588 is rethrown; or a procedure, which will be the pre-unwind handler.
591 Specifies what to do after the stack is unwound.
593 Valid options are @code{catch} (the default), which will silently catch
594 errors, returning the unspecified value; @code{report}, which prints out
595 a description of the error (via @code{display-error}), and then returns
596 the unspecified value; or a procedure, which will be the catch handler.
599 Specifies a trap handler: what to do when a breakpoint is hit.
601 Valid options are @code{debug}, which will enter the debugger;
602 @code{pass}, which does nothing; or @code{disabled}, which disables
603 traps entirely. @xref{Traps}, for more information.
606 A set of keys to ignore, as a list.
611 @subsubsection Debug options
613 The behavior of the @code{backtrace} procedure and of the default error
614 handler can be parameterized via the debug options.
616 @cindex options - debug
617 @cindex debug options
618 @deffn {Scheme Procedure} debug-options [setting]
619 Display the current settings of the debug options. If @var{setting} is
620 omitted, only a short form of the current read options is printed.
621 Otherwise if @var{setting} is the symbol @code{help}, a complete options
622 description is displayed.
625 The set of available options, and their default values, may be had by
626 invoking @code{debug-options} at the prompt.
629 scheme@@(guile-user)>
630 backwards no Display backtrace in anti-chronological order.
631 width 79 Maximal width of backtrace.
632 depth 20 Maximal length of printed backtrace.
633 backtrace yes Show backtrace on error.
634 stack 1048576 Stack size limit (measured in words;
636 show-file-name #t Show file names and line numbers in backtraces
637 when not `#f'. A value of `base' displays only
638 base names, while `#t' displays full names.
639 warn-deprecated no Warn when deprecated features are used.
642 The boolean options may be toggled with @code{debug-enable} and
643 @code{debug-disable}. The non-boolean @code{keywords} option must be set
644 using @code{debug-set!}.
646 @deffn {Scheme Procedure} debug-enable option-name
647 @deffnx {Scheme Procedure} debug-disable option-name
648 @deffnx {Scheme Syntax} debug-set! option-name value
649 Modify the debug options. @code{debug-enable} should be used with boolean
650 options and switches them on, @code{debug-disable} switches them off.
652 @code{debug-set!} can be used to set an option to a specific value. Due
653 to historical oddities, it is a macro that expects an unquoted option
657 @subsubheading Stack overflow
659 @cindex overflow, stack
660 @cindex stack overflow
661 Stack overflow errors are caused by a computation trying to use more
662 stack space than has been enabled by the @code{stack} option. There are
663 actually two kinds of stack that can overflow, the C stack and the
666 Scheme stack overflows can occur if Scheme procedures recurse too far
667 deeply. An example would be the following recursive loop:
670 scheme@@(guile-user)> (let lp () (+ 1 (lp)))
671 <unnamed port>:8:17: In procedure vm-run:
672 <unnamed port>:8:17: VM: Stack overflow
675 The default stack size should allow for about 10000 frames or so, so one
676 usually doesn't hit this level of recursion. Unfortunately there is no
677 way currently to make a VM with a bigger stack. If you are in this
678 unfortunate situation, please file a bug, and in the meantime, rewrite
679 your code to be tail-recursive (@pxref{Tail Calls}).
681 The other limit you might hit would be C stack overflows. If you call a
682 primitive procedure which then calls a Scheme procedure in a loop, you
683 will consume C stack space. Guile tries to detect excessive consumption
684 of C stack space, throwing an error when you have hit 80% of the
685 process' available stack (as allocated by the operating system), or 160
686 kilowords in the absence of a strict limit.
688 For example, looping through @code{call-with-vm}, a primitive that calls
689 a thunk, gives us the following:
692 scheme@@(guile-user)> (use-modules (system vm vm))
693 scheme@@(guile-user)> (debug-set! stack 10000)
694 scheme@@(guile-user)> (let lp () (call-with-vm (the-vm) lp))
695 ERROR: In procedure call-with-vm:
696 ERROR: Stack overflow
699 If you get an error like this, you can either try rewriting your code to
700 use less stack space, or increase the maximum stack size. To increase
701 the maximum stack size, use @code{debug-set!}, for example:
704 (debug-set! stack 200000)
707 But of course it's better to have your code operate without so much
708 resource consumption, avoiding loops through C trampolines.
719 @cindex Code coverage
721 Guile's virtual machine can be configured to call out at key points to
722 arbitrary user-specified procedures.
724 In principle, these @dfn{hooks} allow Scheme code to implement any model
725 it chooses for examining the evaluation stack as program execution
726 proceeds, and for suspending execution to be resumed later.
728 VM hooks are very low-level, though, and so Guile also has a library of
729 higher-level @dfn{traps} on top of the VM hooks. A trap is an execution
730 condition that, when fulfilled, will fire a handler. For example, Guile
731 defines a trap that fires when control reaches a certain source
734 Finally, Guile also defines a third level of abstractions: per-thread
735 @dfn{trap states}. A trap state exists to give names to traps, and to
736 hold on to the set of traps so that they can be enabled, disabled, or
737 removed. The trap state infrastructure defines the most useful
738 abstractions for most cases. For example, Guile's REPL uses trap state
739 functions to set breakpoints and tracepoints.
741 The following subsections describe all this in detail, for both the
742 user wanting to use traps, and the developer interested in
743 understanding how the interface hangs together.
747 * VM Hooks:: Modifying Guile's virtual machine.
748 * Trap Interface:: Traps are on or off.
749 * Low-Level Traps:: The various kinds of low-level traps.
750 * Tracing Traps:: Traps to trace procedure calls and returns.
751 * Trap States:: One state (per thread) to bind them.
752 * High-Level Traps:: The highest-level trap interface. Use this.
757 @subsubsection VM Hooks
759 Everything that runs in Guile runs on its virtual machine, a C program
760 that defines a number of operations that Scheme programs can
763 Note that there are multiple VM ``engines'' for Guile. Only some of them
764 have support for hooks compiled in. Normally the deal is that you get
765 hooks if you are running interactively, and otherwise they are disabled,
766 as they do have some overhead (about 10 or 20 percent).
768 To ensure that you are running with hooks, pass @code{--debug} to Guile
769 when running your program, or otherwise use the @code{call-with-vm} and
770 @code{set-vm-engine!} procedures to ensure that you are running in a VM
771 with the @code{debug} engine.
773 To digress, Guile's VM has 6 different hooks (@pxref{Hooks}) that can be
774 fired at different times, which may be accessed with the following
777 All hooks are called with one argument, the frame in
778 question. @xref{Frames}. Since these hooks may be fired very
779 frequently, Guile does a terrible thing: it allocates the frames on the
780 C stack instead of the garbage-collected heap.
782 The upshot here is that the frames are only valid within the dynamic
783 extent of the call to the hook. If a hook procedure keeps a reference to
784 the frame outside the extent of the hook, bad things will happen.
786 The interface to hooks is provided by the @code{(system vm vm)} module:
789 (use-modules (system vm vm))
793 The result of calling @code{the-vm} is usually passed as the @var{vm}
794 argument to all of these procedures.
796 @deffn {Scheme Procedure} vm-next-hook vm
797 The hook that will be fired before an instruction is retired (and
801 @deffn {Scheme Procedure} vm-push-continuation-hook vm
802 The hook that will be fired after preparing a new frame. Fires just
803 before applying a procedure in a non-tail context, just before the
804 corresponding apply-hook.
807 @deffn {Scheme Procedure} vm-pop-continuation-hook vm
808 The hook that will be fired before returning from a frame.
810 This hook is a bit trickier than the rest, in that there is a particular
811 interpretation of the values on the stack. Specifically, the top value
812 on the stack is the number of values being returned, and the next
813 @var{n} values are the actual values being returned, with the last value
814 highest on the stack.
817 @deffn {Scheme Procedure} vm-apply-hook vm
818 The hook that will be fired before a procedure is applied. The frame's
819 procedure will have already been set to the new procedure.
821 Note that procedure application is somewhat orthogonal to continuation
822 pushes and pops. A non-tail call to a procedure will result first in a
823 firing of the push-continuation hook, then this application hook,
824 whereas a tail call will run without having fired a push-continuation
828 @deffn {Scheme Procedure} vm-abort-continuation-hook vm
829 The hook that will be called after aborting to a
830 prompt. @xref{Prompts}. The stack will be in the same state as for
831 @code{vm-pop-continuation-hook}.
834 @deffn {Scheme Procedure} vm-restore-continuation-hook vm
835 The hook that will be called after restoring an undelimited
836 continuation. Unfortunately it's not currently possible to introspect on
837 the values that were given to the continuation.
840 @cindex VM trace level
841 These hooks do impose a performance penalty, if they are on. Obviously,
842 the @code{vm-next-hook} has quite an impact, performance-wise. Therefore
843 Guile exposes a single, heavy-handed knob to turn hooks on or off, the
844 @dfn{VM trace level}. If the trace level is positive, hooks run;
845 otherwise they don't.
847 For convenience, when the VM fires a hook, it does so with the trap
848 level temporarily set to 0. That way the hooks don't fire while you're
849 handling a hook. The trace level is restored to whatever it was once the hook
852 @deffn {Scheme Procedure} vm-trace-level vm
853 Retrieve the ``trace level'' of the VM. If positive, the trace hooks
854 associated with @var{vm} will be run. The initial trace level is 0.
857 @deffn {Scheme Procedure} set-vm-trace-level! vm level
858 Set the ``trace level'' of the VM.
861 @xref{A Virtual Machine for Guile}, for more information on Guile's
865 @subsubsection Trap Interface
867 The capabilities provided by hooks are great, but hooks alone rarely
868 correspond to what users want to do.
870 For example, if a user wants to break when and if control reaches a
871 certain source location, how do you do it? If you install a ``next''
872 hook, you get unacceptable overhead for the execution of the entire
873 program. It would be possible to install an ``apply'' hook, then if the
874 procedure encompasses those source locations, install a ``next'' hook,
875 but already you're talking about one concept that might be implemented
876 by a varying number of lower-level concepts.
878 It's best to be clear about things and define one abstraction for all
879 such conditions: the @dfn{trap}.
881 Considering the myriad capabilities offered by the hooks though, there
882 is only a minimum of functionality shared by all traps. Guile's current
883 take is to reduce this to the absolute minimum, and have the only
884 standard interface of a trap be ``turn yourself on'' or ``turn yourself
887 This interface sounds a bit strange, but it is useful to procedurally
888 compose higher-level traps from lower-level building blocks. For
889 example, Guile defines a trap that calls one handler when control enters
890 a procedure, and another when control leaves the procedure. Given that
891 trap, one can define a trap that adds to the next-hook only when within
892 a given procedure. Building further, one can define a trap that fires
893 when control reaches particular instructions within a procedure.
895 Or of course you can stop at any of these intermediate levels. For
896 example, one might only be interested in calls to a given procedure. But
897 the point is that a simple enable/disable interface is all the
898 commonality that exists between the various kinds of traps, and
899 furthermore that such an interface serves to allow ``higher-level''
900 traps to be composed from more primitive ones.
902 Specifically, a trap, in Guile, is a procedure. When a trap is created,
903 by convention the trap is enabled; therefore, the procedure that is the
904 trap will, when called, disable the trap, and return a procedure that
905 will enable the trap, and so on.
907 Trap procedures take one optional argument: the current frame. (A trap
908 may want to add to different sets of hooks depending on the frame that
909 is current at enable-time.)
911 If this all sounds very complicated, it's because it is. Some of it is
912 essential, but probably most of it is not. The advantage of using this
913 minimal interface is that composability is more lexically apparent than
914 when, for example, using a stateful interface based on GOOPS. But
915 perhaps this reflects the cognitive limitations of the programmer who
916 made the current interface more than anything else.
918 @node Low-Level Traps
919 @subsubsection Low-Level Traps
921 To summarize the last sections, traps are enabled or disabled, and when
922 they are enabled, they add to various VM hooks.
924 Note, however, that @emph{traps do not increase the VM trace level}. So
925 if you create a trap, it will be enabled, but unless something else
926 increases the VM's trace level (@pxref{VM Hooks}), the trap will not
927 fire. It turns out that getting the VM trace level right is tricky
928 without a global view of what traps are enabled. @xref{Trap States},
929 for Guile's answer to this problem.
931 Traps are created by calling procedures. Most of these procedures share
932 a set of common keyword arguments, so rather than document them
933 separately, we discuss them all together here:
937 The VM to instrument. Defaults to the current thread's VM.
939 For traps that depend on the current frame's procedure, this argument
940 specifies whether to trap on the only the specific procedure given, or
941 on any closure that has the given procedure's code. Defaults to
943 @item #:current-frame
944 For traps that enable more hooks depending on their dynamic context,
945 this argument gives the current frame that the trap is running in.
946 Defaults to @code{#f}.
949 To have access to these procedures, you'll need to have imported the
950 @code{(system vm traps)} module:
953 (use-modules (system vm traps))
956 @deffn {Scheme Procedure} trap-at-procedure-call proc handler @
958 A trap that calls @var{handler} when @var{proc} is applied.
961 @deffn {Scheme Procedure} trap-in-procedure proc @
962 enter-handler exit-handler [#:current-frame] [#:vm] [#:closure?]
963 A trap that calls @var{enter-handler} when control enters @var{proc},
964 and @var{exit-handler} when control leaves @var{proc}.
966 Control can enter a procedure via:
971 A return to a procedure's frame on the stack.
973 A continuation returning directly to an application of this procedure.
976 Control can leave a procedure via:
979 A normal return from the procedure.
981 An application of another procedure.
983 An invocation of a continuation.
989 @deffn {Scheme Procedure} trap-instructions-in-procedure proc @
990 next-handler exit-handler [#:current-frame] [#:vm] [#:closure?]
991 A trap that calls @var{next-handler} for every instruction executed in
992 @var{proc}, and @var{exit-handler} when execution leaves @var{proc}.
995 @deffn {Scheme Procedure} trap-at-procedure-ip-in-range proc range @
996 handler [#:current-frame] [#:vm] [#:closure?]
997 A trap that calls @var{handler} when execution enters a range of
998 instructions in @var{proc}. @var{range} is a simple of pairs,
999 @code{((@var{start} . @var{end}) ...)}. The @var{start} addresses are
1000 inclusive, and @var{end} addresses are exclusive.
1003 @deffn {Scheme Procedure} trap-at-source-location file user-line handler @
1004 [#:current-frame] [#:vm]
1005 A trap that fires when control reaches a given source location. The
1006 @var{user-line} parameter is one-indexed, as a user counts lines,
1007 instead of zero-indexed, as Guile counts lines.
1010 @deffn {Scheme Procedure} trap-frame-finish frame @
1011 return-handler abort-handler [#:vm]
1012 A trap that fires when control leaves the given frame. @var{frame}
1013 should be a live frame in the current continuation. @var{return-handler}
1014 will be called on a normal return, and @var{abort-handler} on a nonlocal
1018 @deffn {Scheme Procedure} trap-in-dynamic-extent proc @
1019 enter-handler return-handler abort-handler [#:vm] [#:closure?]
1020 A more traditional dynamic-wind trap, which fires @var{enter-handler}
1021 when control enters @var{proc}, @var{return-handler} on a normal return,
1022 and @var{abort-handler} on a nonlocal exit.
1024 Note that rewinds are not handled, so there is no rewind handler.
1027 @deffn {Scheme Procedure} trap-calls-in-dynamic-extent proc @
1028 apply-handler return-handler [#:current-frame] [#:vm] [#:closure?]
1029 A trap that calls @var{apply-handler} every time a procedure is applied,
1030 and @var{return-handler} for returns, but only during the dynamic extent
1031 of an application of @var{proc}.
1034 @deffn {Scheme Procedure} trap-instructions-in-dynamic-extent proc @
1035 next-handler [#:current-frame] [#:vm] [#:closure?]
1036 A trap that calls @var{next-handler} for all retired instructions within
1037 the dynamic extent of a call to @var{proc}.
1040 @deffn {Scheme Procedure} trap-calls-to-procedure proc @
1041 apply-handler return-handler [#:vm]
1042 A trap that calls @var{apply-handler} whenever @var{proc} is applied,
1043 and @var{return-handler} when it returns, but with an additional
1044 argument, the call depth.
1046 That is to say, the handlers will get two arguments: the frame in
1047 question, and the call depth (a non-negative integer).
1050 @deffn {Scheme Procedure} trap-matching-instructions frame-pred handler [#:vm]
1051 A trap that calls @var{frame-pred} at every instruction, and if
1052 @var{frame-pred} returns a true value, calls @var{handler} on the
1057 @subsubsection Tracing Traps
1059 The @code{(system vm trace)} module defines a number of traps for
1060 tracing of procedure applications. When a procedure is @dfn{traced}, it
1061 means that every call to that procedure is reported to the user during a
1062 program run. The idea is that you can mark a collection of procedures
1063 for tracing, and Guile will subsequently print out a line of the form
1066 | | (@var{procedure} @var{args} @dots{})
1069 whenever a marked procedure is about to be applied to its arguments.
1070 This can help a programmer determine whether a function is being called
1071 at the wrong time or with the wrong set of arguments.
1073 In addition, the indentation of the output is useful for demonstrating
1074 how the traced applications are or are not tail recursive with respect
1075 to each other. Thus, a trace of a non-tail recursive factorial
1076 implementation looks like this:
1079 scheme@@(guile-user)> (define (fact1 n)
1081 (* n (fact1 (1- n)))))
1082 scheme@@(guile-user)> ,trace (fact1 4)
1085 trace: | | (fact1 2)
1086 trace: | | | (fact1 1)
1087 trace: | | | | (fact1 0)
1095 While a typical tail recursive implementation would look more like this:
1098 scheme@@(guile-user)> (define (facti acc n)
1100 (facti (* n acc) (1- n))))
1101 scheme@@(guile-user)> (define (fact2 n) (facti 1 n))
1102 scheme@@(guile-user)> ,trace (fact2 4)
1112 The low-level traps below (@pxref{Low-Level Traps}) share some common
1117 The maximum width of trace output. Trace printouts will try not to
1118 exceed this column, but for highly nested procedure calls, it may be
1119 unavoidable. Defaults to 80.
1121 The VM on which to add the traps. Defaults to the current thread's VM.
1123 A string to print out before each trace line. As seen above in the
1124 examples, defaults to @code{"trace: "}.
1127 To have access to these procedures, you'll need to have imported the
1128 @code{(system vm trace)} module:
1131 (use-modules (system vm trace))
1134 @deffn {Scheme Procedure} trace-calls-to-procedure proc @
1135 [#:width] [#:vm] [#:prefix]
1136 Print a trace at applications of and returns from @var{proc}.
1139 @deffn {Scheme Procedure} trace-calls-in-procedure proc @
1140 [#:width] [#:vm] [#:prefix]
1141 Print a trace at all applications and returns within the dynamic extent
1142 of calls to @var{proc}.
1145 @deffn {Scheme Procedure} trace-instructions-in-procedure proc [#:width] [#:vm]
1146 Print a trace at all instructions executed in the dynamic extent of
1147 calls to @var{proc}.
1150 In addition, Guile defines a procedure to call a thunk, tracing all
1151 procedure calls and returns within the thunk.
1153 @deffn {Scheme Procedure} call-with-trace thunk #:key (calls? #t) (instructions? #f) (width 80) (vm (the-vm))
1154 Call @var{thunk}, tracing all execution within its dynamic extent.
1156 If @var{calls?} is true, Guile will print a brief report at each
1157 procedure call and return, as given above.
1159 If @var{instructions?} is true, Guile will also print a message each
1160 time an instruction is executed. This is a lot of output, but it is
1161 sometimes useful when doing low-level optimization.
1163 Note that because this procedure manipulates the VM trace level
1164 directly, it doesn't compose well with traps at the REPL.
1167 @xref{Profile Commands}, for more information on tracing at the REPL.
1170 @subsubsection Trap States
1172 When multiple traps are present in a system, we begin to have a
1173 bookkeeping problem. How are they named? How does one disable, enable,
1176 Guile's answer to this is to keep an implicit per-thread @dfn{trap
1177 state}. The trap state object is not exposed to the user; rather, API
1178 that works on trap states fetches the current trap state from the
1179 dynamic environment.
1181 Traps are identified by integers. A trap can be enabled, disabled, or
1182 removed, and can have an associated user-visible name.
1184 These procedures have their own module:
1187 (use-modules (system vm trap-state))
1190 @deffn {Scheme Procedure} add-trap! trap name
1191 Add a trap to the current trap state, associating the given @var{name}
1192 with it. Returns a fresh trap identifier (an integer).
1194 Note that usually the more specific functions detailed in
1195 @ref{High-Level Traps} are used in preference to this one.
1198 @deffn {Scheme Procedure} list-traps
1199 List the current set of traps, both enabled and disabled. Returns a list
1203 @deffn {Scheme Procedure} trap-name idx
1204 Returns the name associated with trap @var{idx}, or @code{#f} if there
1208 @deffn {Scheme Procedure} trap-enabled? idx
1209 Returns @code{#t} if trap @var{idx} is present and enabled, or @code{#f}
1213 @deffn {Scheme Procedure} enable-trap! idx
1214 Enables trap @var{idx}.
1217 @deffn {Scheme Procedure} disable-trap! idx
1218 Disables trap @var{idx}.
1221 @deffn {Scheme Procedure} delete-trap! idx
1222 Removes trap @var{idx}, disabling it first, if necessary.
1225 @node High-Level Traps
1226 @subsubsection High-Level Traps
1228 The low-level trap API allows one to make traps that call procedures,
1229 and the trap state API allows one to keep track of what traps are
1230 there. But neither of these APIs directly helps you when you want to
1231 set a breakpoint, because it's unclear what to do when the trap fires.
1232 Do you enter a debugger, or mail a summary of the situation to your
1233 great-aunt, or what?
1235 So for the common case in which you just want to install breakpoints,
1236 and then have them all result in calls to one parameterizable procedure,
1237 we have the high-level trap interface.
1239 Perhaps we should have started this section with this interface, as it's
1240 clearly the one most people should use. But as its capabilities and
1241 limitations proceed from the lower layers, we felt that the
1242 character-building exercise of building a mental model might be helpful.
1244 These procedures share a module with trap states:
1247 (use-modules (system vm trap-state))
1250 @deffn {Scheme Procedure} with-default-trap-handler handler thunk
1251 Call @var{thunk} in a dynamic context in which @var{handler} is the
1252 current trap handler.
1254 Additionally, during the execution of @var{thunk}, the VM trace level
1255 (@pxref{VM Hooks}) is set to the number of enabled traps. This ensures
1256 that traps will in fact fire.
1258 @var{handler} may be @code{#f}, in which case VM hooks are not enabled
1259 as they otherwise would be, as there is nothing to handle the traps.
1262 The trace-level-setting behavior of @code{with-default-trap-handler} is
1263 one of its more useful aspects, but if you are willing to forgo that,
1264 and just want to install a global trap handler, there's a function for
1267 @deffn {Scheme Procedure} install-trap-handler! handler
1268 Set the current thread's trap handler to @var{handler}.
1271 Trap handlers are called when traps installed by procedures from this
1272 module fire. The current ``consumer'' of this API is Guile's REPL, but
1273 one might easily imagine other trap handlers being used to integrate
1274 with other debugging tools.
1277 @cindex Setting breakpoints
1278 @deffn {Scheme Procedure} add-trap-at-procedure-call! proc
1279 Install a trap that will fire when @var{proc} is called.
1281 This is a breakpoint.
1285 @cindex Setting tracepoints
1286 @deffn {Scheme Procedure} add-trace-at-procedure-call! proc
1287 Install a trap that will print a tracing message when @var{proc} is
1288 called. @xref{Tracing Traps}, for more information.
1290 This is a tracepoint.
1293 @deffn {Scheme Procedure} add-trap-at-source-location! file user-line
1294 Install a trap that will fire when control reaches the given source
1295 location. @var{user-line} is one-indexed, as users count lines, instead
1296 of zero-indexed, as Guile counts lines.
1298 This is a source breakpoint.
1301 @deffn {Scheme Procedure} add-ephemeral-trap-at-frame-finish! frame handler
1302 Install a trap that will call @var{handler} when @var{frame} finishes
1303 executing. The trap will be removed from the trap state after firing, or
1306 This is a finish trap, used to implement the ``finish'' REPL command.
1309 @deffn {Scheme Procedure} add-ephemeral-stepping-trap! frame handler [#:into?] [#:instruction?]
1310 Install a trap that will call @var{handler} after stepping to a
1311 different source line or instruction. The trap will be removed from the
1312 trap state after firing, or on nonlocal exit.
1314 If @var{instruction?} is false (the default), the trap will fire when
1315 control reaches a new source line. Otherwise it will fire when control
1316 reaches a new instruction.
1318 Additionally, if @var{into?} is false (not the default), the trap will
1319 only fire for frames at or prior to the given frame. If @var{into?} is
1320 true (the default), the trap may step into nested procedure
1323 This is a stepping trap, used to implement the ``step'', ``next'',
1324 ``step-instruction'', and ``next-instruction'' REPL commands.
1329 @c TeX-master: "guile.texi"