elisp @@ macro
[bpt/guile.git] / doc / ref / api-debug.texi
1 @c -*-texinfo-*-
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.
6
7 @node Debugging
8 @section Debugging Infrastructure
9
10 @cindex Debugging
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.
16
17 @menu
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.
23 @end menu
24
25 @node Evaluation Model
26 @subsection Evaluation and the Scheme Stack
27
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.
34
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.
41
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
47 pushing on a new one.
48
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.
53
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
60 frames.
61
62 @menu
63 * Stack Capture:: Reifying a continuation.
64 * Stacks:: Accessors for the stack data type.
65 * Frames:: Likewise, accessors for stack frames.
66 @end menu
67
68 @node Stack Capture
69 @subsubsection Stack Capture
70
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.
74
75 @lisp
76 (make-stack #t)
77 @result{}
78 #<stack 25205a0>
79 @end lisp
80
81 Use @code{start-stack} to limit the stack extent captured by future
82 @code{make-stack} calls.
83
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).
90
91 @var{arg} @dots{} can be any combination of integer, procedure, address
92 range, and prompt tag values.
93
94 These values specify various ways of cutting away uninteresting stack
95 frames from the top and bottom of the stack that @code{make-stack}
96 returns. They come in pairs like this: @code{(@var{inner_cut_1}
97 @var{outer_cut_1} @var{inner_cut_2} @var{outer_cut_2} @dots{})}.
98
99 Each @var{inner_cut_i} can be an integer, a procedure, an address range,
100 or a prompt tag. An integer means to cut away exactly that number of
101 frames. A procedure means to cut away all frames up to but excluding
102 the frame whose procedure matches the specified one. An address range
103 is a pair of integers indicating the low and high addresses of a
104 procedure's code, and is the same as cutting away to a procedure (though
105 with less work). Anything else is interpreted as a prompt tag which
106 cuts away all frames that are inside a prompt with the given tag.
107
108 Each @var{outer_cut_i} can likewise be an integer, a procedure, an
109 address range, or a prompt tag. An integer means to cut away that
110 number of frames. A procedure means to cut away frames down to but
111 excluding the frame whose procedure matches the specified one. An
112 address range is the same, but with the procedure's code specified as an
113 address range. Anything else is taken to be a prompt tag, which cuts
114 away all frames that are outside a prompt with the given tag.
115
116
117 If the @var{outer_cut_i} of the last pair is missing, it is taken as 0.
118 @end deffn
119
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.
126 @end deffn
127
128
129 @node Stacks
130 @subsubsection Stacks
131
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.
135 @end deffn
136
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}.
140 @end deffn
141
142 @deffn {Scheme Procedure} stack-length stack
143 @deffnx {C Function} scm_stack_length (stack)
144 Return the length of @var{stack}.
145 @end deffn
146
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}.
150 @end deffn
151
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
162 backtrace.
163 @end deffn
164
165
166 @node Frames
167 @subsubsection Frames
168
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.
172 @end deffn
173
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.
178 @end deffn
179
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}.
184 @end deffn
185
186 @deffn {Scheme Procedure} frame-arguments frame
187 @deffnx {C Function} scm_frame_arguments (frame)
188 Return the arguments of @var{frame}.
189 @end deffn
190
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.
197 @end deffn
198
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.
205 @end deffn
206
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.
214 @end deffn
215
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
220 output.
221 @end deffn
222
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.
227
228
229 @node Source Properties
230 @subsection Source Properties
231
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.
241
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):
247
248 @example
249 scheme@@(guile-user)> (xxx)
250 <unnamed port>:4:1: In procedure module-lookup:
251 <unnamed port>:4:1: Unbound variable: xxx
252
253 scheme@@(guile-user)> xxx
254 ERROR: In procedure module-lookup:
255 ERROR: Unbound variable: xxx
256 @end example
257
258 @noindent
259 In the latter case, no source properties were stored, so the error
260 doesn't have any source information.
261
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},
265 otherwise return #f.
266 @end deffn
267
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.
271
272 The following procedures can be used to access and set the source
273 properties of read expressions.
274
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
278 list for @var{obj}.
279 @end deffn
280
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.
285 @end deffn
286
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}.
290 @end deffn
291
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
295 properties.
296 @end deffn
297
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.
301
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
305 more.
306
307 Guile also defines a couple of convenience macros built on
308 @code{syntax-source}:
309
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.
313 @end deffn
314
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.
319 @end deffn
320
321 If you're stuck with defmacros (@pxref{Defmacros}), and want to preserve
322 source information, the following helper function might be useful to
323 you:
324
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
329 with the new pair.
330 @end deffn
331
332
333 @node Programmatic Error Handling
334 @subsection Programmatic Error Handling
335
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.
340
341 @menu
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 * Stack Overflow:: Detecting and handling runaway recursion.
346 * Debug Options:: A historical interface to debugging.
347 @end menu
348
349 @node Catching Exceptions
350 @subsubsection Catching Exceptions
351
352 A common requirement is to be able to show as much useful context as
353 possible when a Scheme program hits an error. The most immediate
354 information about an error is the kind of error that it is -- such as
355 ``division by zero'' -- and any parameters that the code which signalled
356 the error chose explicitly to provide. This information originates with
357 the @code{error} or @code{throw} call (or their C code equivalents, if
358 the error is detected by C code) that signals the error, and is passed
359 automatically to the handler procedure of the innermost applicable
360 @code{catch} or @code{with-throw-handler} expression.
361
362 Therefore, to catch errors that occur within a chunk of Scheme code, and
363 to intercept basic information about those errors, you need to execute
364 that code inside the dynamic context of a @code{catch} or
365 @code{with-throw-handler} expression, or the equivalent in C. In Scheme,
366 this means you need something like this:
367
368 @lisp
369 (catch #t
370 (lambda ()
371 ;; Execute the code in which
372 ;; you want to catch errors here.
373 ...)
374 (lambda (key . parameters)
375 ;; Put the code which you want
376 ;; to handle an error here.
377 ...))
378 @end lisp
379
380 @noindent
381 The @code{catch} here can also be @code{with-throw-handler}; see
382 @ref{Throw Handlers} for information on the when you might want to use
383 @code{with-throw-handler} instead of @code{catch}.
384
385 For example, to print out a message and return #f when an error occurs,
386 you might use:
387
388 @smalllisp
389 (define (catch-all thunk)
390 (catch #t
391 thunk
392 (lambda (key . parameters)
393 (format (current-error-port)
394 "Uncaught throw to '~a: ~a\n" key parameters)
395 #f)))
396
397 (catch-all
398 (lambda () (error "Not a vegetable: tomato")))
399 @print{} Uncaught throw to 'misc-error: (#f ~A (Not a vegetable: tomato) #f)
400 @result{} #f
401 @end smalllisp
402
403 The @code{#t} means that the catch is applicable to all kinds of error.
404 If you want to restrict your catch to just one kind of error, you can
405 put the symbol for that kind of error instead of @code{#t}. The
406 equivalent to this in C would be something like this:
407
408 @lisp
409 SCM my_body_proc (void *body_data)
410 @{
411 /* Execute the code in which
412 you want to catch errors here. */
413 ...
414 @}
415
416 SCM my_handler_proc (void *handler_data,
417 SCM key,
418 SCM parameters)
419 @{
420 /* Put the code which you want
421 to handle an error here. */
422 ...
423 @}
424
425 @{
426 ...
427 scm_c_catch (SCM_BOOL_T,
428 my_body_proc, body_data,
429 my_handler_proc, handler_data,
430 NULL, NULL);
431 ...
432 @}
433 @end lisp
434
435 @noindent
436 Again, as with the Scheme version, @code{scm_c_catch} could be replaced
437 by @code{scm_c_with_throw_handler}, and @code{SCM_BOOL_T} could instead
438 be the symbol for a particular kind of error.
439
440 @node Capturing Stacks
441 @subsubsection Capturing the full error stack
442
443 The other interesting information about an error is the full Scheme
444 stack at the point where the error occurred; in other words what
445 innermost expression was being evaluated, what was the expression that
446 called that one, and so on. If you want to write your code so that it
447 captures and can display this information as well, there are a couple
448 important things to understand.
449
450 Firstly, the stack at the point of the error needs to be explicitly
451 captured by a @code{make-stack} call (or the C equivalent
452 @code{scm_make_stack}). The Guile library does not do this
453 ``automatically'' for you, so you will need to write code with a
454 @code{make-stack} or @code{scm_make_stack} call yourself. (We emphasise
455 this point because some people are misled by the fact that the Guile
456 interactive REPL code @emph{does} capture and display the stack
457 automatically. But the Guile interactive REPL is itself a Scheme
458 program@footnote{In effect, it is the default program which is run when
459 no commands or script file are specified on the Guile command line.}
460 running on top of the Guile library, and which uses @code{catch} and
461 @code{make-stack} in the way we are about to describe to capture the
462 stack when an error occurs.)
463
464 And secondly, in order to capture the stack effectively at the point
465 where the error occurred, the @code{make-stack} call must be made before
466 Guile unwinds the stack back to the location of the prevailing catch
467 expression. This means that the @code{make-stack} call must be made
468 within the handler of a @code{with-throw-handler} expression, or the
469 optional "pre-unwind" handler of a @code{catch}. (For the full story of
470 how these alternatives differ from each other, see @ref{Exceptions}. The
471 main difference is that @code{catch} terminates the error, whereas
472 @code{with-throw-handler} only intercepts it temporarily and then allow
473 it to continue propagating up to the next innermost handler.)
474
475 So, here are some examples of how to do all this in Scheme and in C.
476 For the purpose of these examples we assume that the captured stack
477 should be stored in a variable, so that it can be displayed or
478 arbitrarily processed later on. In Scheme:
479
480 @lisp
481 (let ((captured-stack #f))
482 (catch #t
483 (lambda ()
484 ;; Execute the code in which
485 ;; you want to catch errors here.
486 ...)
487 (lambda (key . parameters)
488 ;; Put the code which you want
489 ;; to handle an error after the
490 ;; stack has been unwound here.
491 ...)
492 (lambda (key . parameters)
493 ;; Capture the stack here:
494 (set! captured-stack (make-stack #t))))
495 ...
496 (if captured-stack
497 (begin
498 ;; Display or process the captured stack.
499 ...))
500 ...)
501 @end lisp
502
503 @noindent
504 And in C:
505
506 @lisp
507 SCM my_body_proc (void *body_data)
508 @{
509 /* Execute the code in which
510 you want to catch errors here. */
511 ...
512 @}
513
514 SCM my_handler_proc (void *handler_data,
515 SCM key,
516 SCM parameters)
517 @{
518 /* Put the code which you want
519 to handle an error after the
520 stack has been unwound here. */
521 ...
522 @}
523
524 SCM my_preunwind_proc (void *handler_data,
525 SCM key,
526 SCM parameters)
527 @{
528 /* Capture the stack here: */
529 *(SCM *)handler_data = scm_make_stack (SCM_BOOL_T, SCM_EOL);
530 @}
531
532 @{
533 SCM captured_stack = SCM_BOOL_F;
534 ...
535 scm_c_catch (SCM_BOOL_T,
536 my_body_proc, body_data,
537 my_handler_proc, handler_data,
538 my_preunwind_proc, &captured_stack);
539 ...
540 if (captured_stack != SCM_BOOL_F)
541 @{
542 /* Display or process the captured stack. */
543 ...
544 @}
545 ...
546 @}
547 @end lisp
548
549 Once you have a captured stack, you can interrogate and display its
550 details in any way that you want, using the @code{stack-@dots{}} and
551 @code{frame-@dots{}} API described in @ref{Stacks} and
552 @ref{Frames}.
553
554 If you want to print out a backtrace in the same format that the Guile
555 REPL does, you can use the @code{display-backtrace} procedure to do so.
556 You can also use @code{display-application} to display an individual
557 frame in the Guile REPL format.
558
559 @node Pre-Unwind Debugging
560 @subsubsection Pre-Unwind Debugging
561
562 Instead of saving a stack away and waiting for the @code{catch} to
563 return, you can handle errors directly, from within the pre-unwind
564 handler.
565
566 For example, to show a backtrace when an error is thrown, you might want
567 to use a procedure like this:
568
569 @lisp
570 (define (with-backtrace thunk)
571 (with-throw-handler #t
572 thunk
573 (lambda args (backtrace))))
574 (with-backtrace (lambda () (error "Not a vegetable: tomato")))
575 @end lisp
576
577 Since we used @code{with-throw-handler} here, we didn't actually catch
578 the error. @xref{Throw Handlers}, for more information. However, we did
579 print out a context at the time of the error, using the built-in
580 procedure, @code{backtrace}.
581
582 @deffn {Scheme Procedure} backtrace [highlights]
583 @deffnx {C Function} scm_backtrace_with_highlights (highlights)
584 @deffnx {C Function} scm_backtrace ()
585 Display a backtrace of the current stack to the current output port. If
586 @var{highlights} is given it should be a list; the elements of this list
587 will be highlighted wherever they appear in the backtrace.
588 @end deffn
589
590 The Guile REPL code (in @file{system/repl/repl.scm} and related files)
591 uses a @code{catch} with a pre-unwind handler to capture the stack when
592 an error occurs in an expression that was typed into the REPL, and debug
593 that stack interactively in the context of the error.
594
595 These procedures are available for use by user programs, in the
596 @code{(system repl error-handling)} module.
597
598 @lisp
599 (use-modules (system repl error-handling))
600 @end lisp
601
602 @deffn {Scheme Procedure} call-with-error-handling thunk @
603 [#:on-error on-error='debug] [#:post-error post-error='catch] @
604 [#:pass-keys pass-keys='(quit)] @
605 [#:report-keys report-keys='(stack-overflow)] @
606 [#:trap-handler trap-handler='debug]
607 Call a thunk in a context in which errors are handled.
608
609 There are five keyword arguments:
610
611 @table @var
612 @item on-error
613 Specifies what to do before the stack is unwound.
614
615 Valid options are @code{debug} (the default), which will enter a
616 debugger; @code{pass}, in which case nothing is done, and the exception
617 is rethrown; or a procedure, which will be the pre-unwind handler.
618
619 @item post-error
620 Specifies what to do after the stack is unwound.
621
622 Valid options are @code{catch} (the default), which will silently catch
623 errors, returning the unspecified value; @code{report}, which prints out
624 a description of the error (via @code{display-error}), and then returns
625 the unspecified value; or a procedure, which will be the catch handler.
626
627 @item trap-handler
628 Specifies a trap handler: what to do when a breakpoint is hit.
629
630 Valid options are @code{debug}, which will enter the debugger;
631 @code{pass}, which does nothing; or @code{disabled}, which disables
632 traps entirely. @xref{Traps}, for more information.
633
634 @item pass-keys
635 A set of keys to ignore, as a list.
636
637 @item report-keys
638 A set of keys to always report even if the post-error handler is
639 @code{catch}, as a list.
640 @end table
641 @end deffn
642
643 @node Stack Overflow
644 @subsubsection Stack Overflow
645
646 @cindex overflow, stack
647 @cindex stack overflow
648 Every time a Scheme program makes a call that is not in tail position,
649 it pushes a new frame onto the stack. Returning a value from a function
650 pops the top frame off the stack. Stack frames take up memory, and as
651 nobody has an infinite amount of memory, deep recursion could cause
652 Guile to run out of memory. Running out of stack memory is called
653 @dfn{stack overflow}.
654
655 @subsubheading Stack Limits
656
657 Most languages have a terrible stack overflow story. For example, in C,
658 if you use too much stack, your program will exhibit ``undefined
659 behavior'', which if you are lucky means that it will crash. It's
660 especially bad in C, as you neither know ahead of time how much stack
661 your functions use, nor the stack limit imposed by the user's system,
662 and the stack limit is often quite small relative to the total memory
663 size.
664
665 Managed languages like Python have a better error story, as they are
666 defined to raise an exception on stack overflow -- but like C, Python
667 and most dynamic languages still have a fixed stack size limit that is
668 usually much smaller than the heap.
669
670 Arbitrary stack limits would have an unfortunate effect on Guile
671 programs. For example, the following implementation of the inner loop
672 of @code{map} is clean and elegant:
673
674 @example
675 (define (map f l)
676 (if (pair? l)
677 (cons (f (car l))
678 (map f (cdr l)))
679 '()))
680 @end example
681
682 However, if there were a stack limit, that would limit the size of lists
683 that can be processed with this @code{map}. Eventually, you would have
684 to rewrite it to use iteration with an accumulator:
685
686 @example
687 (define (map f l)
688 (let lp ((l l) (out '()))
689 (if (pair? l)
690 (lp (cdr l) (cons (f (car l)) out))
691 (reverse out))))
692 @end example
693
694 This second version is sadly not as clear, and it also allocates more
695 heap memory (once to build the list in reverse, and then again to
696 reverse the list). You would be tempted to use the destructive
697 @code{reverse!} to save memory and time, but then your code would not be
698 continuation-safe -- if @var{f} returned again after the map had
699 finished, it would see an @var{out} list that had already been
700 reversed. The recursive @code{map} has none of these problems.
701
702 Guile has no stack limit for Scheme code. When a thread makes its first
703 Guile call, a small stack is allocated -- just one page of memory.
704 Whenever that memory limit would be reached, Guile arranges to grow the
705 stack by a factor of two. When garbage collection happens, Guile
706 arranges to return the unused part of the stack to the operating system,
707 but without causing the stack to shrink. In this way, the stack can
708 grow to consume up to all memory available to the Guile process, and
709 when the recursive computation eventually finishes, that stack memory is
710 returned to the system.
711
712 @subsubheading Exceptional Situations
713
714 Of course, it's still possible to run out of stack memory. The most
715 common cause of this is program bugs that cause unbounded recursion, as
716 in:
717
718 @example
719 (define (faulty-map f l)
720 (if (pair? l)
721 (cons (f (car l)) (faulty-map f l))
722 '()))
723 @end example
724
725 Did you spot the bug? The recursive call to @code{faulty-map} recursed
726 on @var{l}, not @code{(cdr @var{l})}. Running this program would cause
727 Guile to use up all memory in your system, and eventually Guile would
728 fail to grow the stack. At that point you have a problem: Guile needs
729 to raise an exception to unwind the stack and return memory to the
730 system, but the user might have throw handlers in place (@pxref{Throw
731 Handlers}) that want to run before the stack is unwound, and we don't
732 have any stack in which to run them.
733
734 Therefore in this case, Guile throws an unwind-only exception that does
735 not run pre-unwind handlers. Because this is such an odd case, Guile
736 prints out a message on the console, in case the user was expecting to
737 be able to get a backtrace from any pre-unwind handler.
738
739 @subsubheading Runaway Recursion
740
741 Still, this failure mode is not so nice. If you are running an
742 environment in which you are interactively building a program while it
743 is running, such as at a REPL, you might want to impose an artificial
744 stack limit on the part of your program that you are building to detect
745 accidental runaway recursion. For that purpose, there is
746 @code{call-with-stack-overflow-handler}, from @code{(system vm vm)}.
747
748 @example
749 (use-module (system vm vm))
750 @end example
751
752 @deffn {Scheme Procedure} call-with-stack-overflow-handler limit thunk handler
753 Call @var{thunk} in an environment in which the stack limit has been
754 reduced to @var{limit} additional words. If the limit is reached,
755 @var{handler} (a thunk) will be invoked in the dynamic environment of
756 the error. For the extent of the call to @var{handler}, the stack limit
757 and handler are restored to the values that were in place when
758 @code{call-with-stack-overflow-handler} was called.
759
760 Usually, @var{handler} should raise an exception or abort to an outer
761 prompt. However if @var{handler} does return, it should return a number
762 of additional words of stack space to allow to the inner environment.
763 @end deffn
764
765 A stack overflow handler may only ever ``credit'' the inner thunk with
766 stack space that was available when the handler was instated. When
767 Guile first starts, there is no stack limit in place, so the outer
768 handler may allow the inner thunk an arbitrary amount of space, but any
769 nested stack overflow handler will not be able to consume more than its
770 limit.
771
772 Unlike the unwind-only exception that is thrown if Guile is unable to
773 grow its stack, any exception thrown by a stack overflow handler might
774 invoke pre-unwind handlers. Indeed, the stack overflow handler is
775 itself a pre-unwind handler of sorts. If the code imposing the stack
776 limit wants to protect itself against malicious pre-unwind handlers from
777 the inner thunk, it should abort to a prompt of its own making instead
778 of throwing an exception that might be caught by the inner thunk.
779
780 @subsubheading C Stack Usage
781
782 It is also possible for Guile to run out of space on the C stack. If
783 you call a primitive procedure which then calls a Scheme procedure in a
784 loop, you will consume C stack space. Guile tries to detect excessive
785 consumption of C stack space, throwing an error when you have hit 80% of
786 the process' available stack (as allocated by the operating system), or
787 160 kilowords in the absence of a strict limit.
788
789 For example, looping through @code{call-with-vm}, a primitive that calls
790 a thunk, gives us the following:
791
792 @lisp
793 scheme@@(guile-user)> (use-modules (system vm vm))
794 scheme@@(guile-user)> (let lp () (call-with-vm lp))
795 ERROR: Stack overflow
796 @end lisp
797
798 Unfortunately, that's all the information we get. Overrunning the C
799 stack will throw an unwind-only exception, because it's not safe to
800 do very much when you are close to the C stack limit.
801
802 If you get an error like this, you can either try rewriting your code to
803 use less stack space, or increase the maximum stack size. To increase
804 the maximum stack size, use @code{debug-set!}, for example:
805
806 @lisp
807 (debug-set! stack 200000)
808 @end lisp
809
810 The next section describes @code{debug-set!} more thoroughly. Of course
811 the best thing is to have your code operate without so much resource
812 consumption by avoiding loops through C trampolines.
813
814
815 @node Debug Options
816 @subsubsection Debug options
817
818 The behavior of the @code{backtrace} procedure and of the default error
819 handler can be parameterized via the debug options.
820
821 @cindex options - debug
822 @cindex debug options
823 @deffn {Scheme Procedure} debug-options [setting]
824 Display the current settings of the debug options. If @var{setting} is
825 omitted, only a short form of the current read options is printed.
826 Otherwise if @var{setting} is the symbol @code{help}, a complete options
827 description is displayed.
828 @end deffn
829
830 The set of available options, and their default values, may be had by
831 invoking @code{debug-options} at the prompt.
832
833 @smallexample
834 scheme@@(guile-user)>
835 backwards no Display backtrace in anti-chronological order.
836 width 79 Maximal width of backtrace.
837 depth 20 Maximal length of printed backtrace.
838 backtrace yes Show backtrace on error.
839 stack 1048576 Stack size limit (measured in words;
840 0 = no check).
841 show-file-name #t Show file names and line numbers in backtraces
842 when not `#f'. A value of `base' displays only
843 base names, while `#t' displays full names.
844 warn-deprecated no Warn when deprecated features are used.
845 @end smallexample
846
847 The boolean options may be toggled with @code{debug-enable} and
848 @code{debug-disable}. The non-boolean options must be set using
849 @code{debug-set!}.
850
851 @deffn {Scheme Procedure} debug-enable option-name
852 @deffnx {Scheme Procedure} debug-disable option-name
853 @deffnx {Scheme Syntax} debug-set! option-name value
854 Modify the debug options. @code{debug-enable} should be used with boolean
855 options and switches them on, @code{debug-disable} switches them off.
856
857 @code{debug-set!} can be used to set an option to a specific value. Due
858 to historical oddities, it is a macro that expects an unquoted option
859 name.
860 @end deffn
861
862
863 @node Traps
864 @subsection Traps
865
866 @cindex Traps
867 @cindex VM hooks
868 @cindex Breakpoints
869 @cindex Trace
870 @cindex Tracing
871 @cindex Code coverage
872 @cindex Profiling
873 Guile's virtual machine can be configured to call out at key points to
874 arbitrary user-specified procedures.
875
876 In principle, these @dfn{hooks} allow Scheme code to implement any model
877 it chooses for examining the evaluation stack as program execution
878 proceeds, and for suspending execution to be resumed later.
879
880 VM hooks are very low-level, though, and so Guile also has a library of
881 higher-level @dfn{traps} on top of the VM hooks. A trap is an execution
882 condition that, when fulfilled, will fire a handler. For example, Guile
883 defines a trap that fires when control reaches a certain source
884 location.
885
886 Finally, Guile also defines a third level of abstractions: per-thread
887 @dfn{trap states}. A trap state exists to give names to traps, and to
888 hold on to the set of traps so that they can be enabled, disabled, or
889 removed. The trap state infrastructure defines the most useful
890 abstractions for most cases. For example, Guile's REPL uses trap state
891 functions to set breakpoints and tracepoints.
892
893 The following subsections describe all this in detail, for both the
894 user wanting to use traps, and the developer interested in
895 understanding how the interface hangs together.
896
897
898 @menu
899 * VM Hooks:: Modifying Guile's virtual machine.
900 * Trap Interface:: Traps are on or off.
901 * Low-Level Traps:: The various kinds of low-level traps.
902 * Tracing Traps:: Traps to trace procedure calls and returns.
903 * Trap States:: One state (per thread) to bind them.
904 * High-Level Traps:: The highest-level trap interface. Use this.
905 @end menu
906
907
908 @node VM Hooks
909 @subsubsection VM Hooks
910
911 Everything that runs in Guile runs on its virtual machine, a C program
912 that defines a number of operations that Scheme programs can
913 perform.
914
915 Note that there are multiple VM ``engines'' for Guile. Only some of them
916 have support for hooks compiled in. Normally the deal is that you get
917 hooks if you are running interactively, and otherwise they are disabled,
918 as they do have some overhead (about 10 or 20 percent).
919
920 To ensure that you are running with hooks, pass @code{--debug} to Guile
921 when running your program, or otherwise use the @code{call-with-vm} and
922 @code{set-vm-engine!} procedures to ensure that you are running in a VM
923 with the @code{debug} engine.
924
925 To digress, Guile's VM has 6 different hooks (@pxref{Hooks}) that can be
926 fired at different times, which may be accessed with the following
927 procedures.
928
929 The first argument of calls to these hooks is the frame in question.
930 @xref{Frames}. Some hooks may call their procedures with more
931 arguments. Since these hooks may be fired very frequently, Guile does a
932 terrible thing: it allocates the frames on the C stack instead of the
933 garbage-collected heap.
934
935 The upshot here is that the frames are only valid within the dynamic
936 extent of the call to the hook. If a hook procedure keeps a reference to
937 the frame outside the extent of the hook, bad things will happen.
938
939 The interface to hooks is provided by the @code{(system vm vm)} module:
940
941 @example
942 (use-modules (system vm vm))
943 @end example
944
945 @noindent
946 All of these functions implicitly act on the VM for the current thread
947 only.
948
949 @deffn {Scheme Procedure} vm-next-hook
950 The hook that will be fired before an instruction is retired (and
951 executed).
952 @end deffn
953
954 @deffn {Scheme Procedure} vm-push-continuation-hook
955 The hook that will be fired after preparing a new frame. Fires just
956 before applying a procedure in a non-tail context, just before the
957 corresponding apply-hook.
958 @end deffn
959
960 @deffn {Scheme Procedure} vm-pop-continuation-hook
961 The hook that will be fired before returning from a frame.
962
963 This hook fires with a variable number of arguments, corresponding to
964 the values that the frame returns to its continuation.
965 @end deffn
966
967 @deffn {Scheme Procedure} vm-apply-hook
968 The hook that will be fired before a procedure is applied. The frame's
969 procedure will have already been set to the new procedure.
970
971 Note that procedure application is somewhat orthogonal to continuation
972 pushes and pops. A non-tail call to a procedure will result first in a
973 firing of the push-continuation hook, then this application hook,
974 whereas a tail call will run without having fired a push-continuation
975 hook.
976 @end deffn
977
978 @deffn {Scheme Procedure} vm-abort-continuation-hook
979 The hook that will be called after aborting to a
980 prompt. @xref{Prompts}.
981
982 Like the pop-continuation hook, this hook fires with a variable number
983 of arguments, corresponding to the values that returned to the
984 continuation.
985 @end deffn
986
987 @deffn {Scheme Procedure} vm-restore-continuation-hook
988 The hook that will be called after restoring an undelimited
989 continuation. Unfortunately it's not currently possible to introspect on
990 the values that were given to the continuation.
991 @end deffn
992
993 @cindex VM trace level
994 These hooks do impose a performance penalty, if they are on. Obviously,
995 the @code{vm-next-hook} has quite an impact, performance-wise. Therefore
996 Guile exposes a single, heavy-handed knob to turn hooks on or off, the
997 @dfn{VM trace level}. If the trace level is positive, hooks run;
998 otherwise they don't.
999
1000 For convenience, when the VM fires a hook, it does so with the trap
1001 level temporarily set to 0. That way the hooks don't fire while you're
1002 handling a hook. The trace level is restored to whatever it was once the hook
1003 procedure finishes.
1004
1005 @deffn {Scheme Procedure} vm-trace-level
1006 Retrieve the ``trace level'' of the VM. If positive, the trace hooks
1007 associated with @var{vm} will be run. The initial trace level is 0.
1008 @end deffn
1009
1010 @deffn {Scheme Procedure} set-vm-trace-level! level
1011 Set the ``trace level'' of the VM.
1012 @end deffn
1013
1014 @xref{A Virtual Machine for Guile}, for more information on Guile's
1015 virtual machine.
1016
1017 @node Trap Interface
1018 @subsubsection Trap Interface
1019
1020 The capabilities provided by hooks are great, but hooks alone rarely
1021 correspond to what users want to do.
1022
1023 For example, if a user wants to break when and if control reaches a
1024 certain source location, how do you do it? If you install a ``next''
1025 hook, you get unacceptable overhead for the execution of the entire
1026 program. It would be possible to install an ``apply'' hook, then if the
1027 procedure encompasses those source locations, install a ``next'' hook,
1028 but already you're talking about one concept that might be implemented
1029 by a varying number of lower-level concepts.
1030
1031 It's best to be clear about things and define one abstraction for all
1032 such conditions: the @dfn{trap}.
1033
1034 Considering the myriad capabilities offered by the hooks though, there
1035 is only a minimum of functionality shared by all traps. Guile's current
1036 take is to reduce this to the absolute minimum, and have the only
1037 standard interface of a trap be ``turn yourself on'' or ``turn yourself
1038 off''.
1039
1040 This interface sounds a bit strange, but it is useful to procedurally
1041 compose higher-level traps from lower-level building blocks. For
1042 example, Guile defines a trap that calls one handler when control enters
1043 a procedure, and another when control leaves the procedure. Given that
1044 trap, one can define a trap that adds to the next-hook only when within
1045 a given procedure. Building further, one can define a trap that fires
1046 when control reaches particular instructions within a procedure.
1047
1048 Or of course you can stop at any of these intermediate levels. For
1049 example, one might only be interested in calls to a given procedure. But
1050 the point is that a simple enable/disable interface is all the
1051 commonality that exists between the various kinds of traps, and
1052 furthermore that such an interface serves to allow ``higher-level''
1053 traps to be composed from more primitive ones.
1054
1055 Specifically, a trap, in Guile, is a procedure. When a trap is created,
1056 by convention the trap is enabled; therefore, the procedure that is the
1057 trap will, when called, disable the trap, and return a procedure that
1058 will enable the trap, and so on.
1059
1060 Trap procedures take one optional argument: the current frame. (A trap
1061 may want to add to different sets of hooks depending on the frame that
1062 is current at enable-time.)
1063
1064 If this all sounds very complicated, it's because it is. Some of it is
1065 essential, but probably most of it is not. The advantage of using this
1066 minimal interface is that composability is more lexically apparent than
1067 when, for example, using a stateful interface based on GOOPS. But
1068 perhaps this reflects the cognitive limitations of the programmer who
1069 made the current interface more than anything else.
1070
1071 @node Low-Level Traps
1072 @subsubsection Low-Level Traps
1073
1074 To summarize the last sections, traps are enabled or disabled, and when
1075 they are enabled, they add to various VM hooks.
1076
1077 Note, however, that @emph{traps do not increase the VM trace level}. So
1078 if you create a trap, it will be enabled, but unless something else
1079 increases the VM's trace level (@pxref{VM Hooks}), the trap will not
1080 fire. It turns out that getting the VM trace level right is tricky
1081 without a global view of what traps are enabled. @xref{Trap States},
1082 for Guile's answer to this problem.
1083
1084 Traps are created by calling procedures. Most of these procedures share
1085 a set of common keyword arguments, so rather than document them
1086 separately, we discuss them all together here:
1087
1088 @table @code
1089 @item #:vm
1090 The VM to instrument. Defaults to the current thread's VM.
1091 @item #:closure?
1092 For traps that depend on the current frame's procedure, this argument
1093 specifies whether to trap on the only the specific procedure given, or
1094 on any closure that has the given procedure's code. Defaults to
1095 @code{#f}.
1096 @item #:current-frame
1097 For traps that enable more hooks depending on their dynamic context,
1098 this argument gives the current frame that the trap is running in.
1099 Defaults to @code{#f}.
1100 @end table
1101
1102 To have access to these procedures, you'll need to have imported the
1103 @code{(system vm traps)} module:
1104
1105 @lisp
1106 (use-modules (system vm traps))
1107 @end lisp
1108
1109 @deffn {Scheme Procedure} trap-at-procedure-call proc handler @
1110 [#:vm] [#:closure?]
1111 A trap that calls @var{handler} when @var{proc} is applied.
1112 @end deffn
1113
1114 @deffn {Scheme Procedure} trap-in-procedure proc @
1115 enter-handler exit-handler [#:current-frame] [#:vm] [#:closure?]
1116 A trap that calls @var{enter-handler} when control enters @var{proc},
1117 and @var{exit-handler} when control leaves @var{proc}.
1118
1119 Control can enter a procedure via:
1120 @itemize
1121 @item
1122 A procedure call.
1123 @item
1124 A return to a procedure's frame on the stack.
1125 @item
1126 A continuation returning directly to an application of this procedure.
1127 @end itemize
1128
1129 Control can leave a procedure via:
1130 @itemize
1131 @item
1132 A normal return from the procedure.
1133 @item
1134 An application of another procedure.
1135 @item
1136 An invocation of a continuation.
1137 @item
1138 An abort.
1139 @end itemize
1140 @end deffn
1141
1142 @deffn {Scheme Procedure} trap-instructions-in-procedure proc @
1143 next-handler exit-handler [#:current-frame] [#:vm] [#:closure?]
1144 A trap that calls @var{next-handler} for every instruction executed in
1145 @var{proc}, and @var{exit-handler} when execution leaves @var{proc}.
1146 @end deffn
1147
1148 @deffn {Scheme Procedure} trap-at-procedure-ip-in-range proc range @
1149 handler [#:current-frame] [#:vm] [#:closure?]
1150 A trap that calls @var{handler} when execution enters a range of
1151 instructions in @var{proc}. @var{range} is a simple of pairs,
1152 @code{((@var{start} . @var{end}) ...)}. The @var{start} addresses are
1153 inclusive, and @var{end} addresses are exclusive.
1154 @end deffn
1155
1156 @deffn {Scheme Procedure} trap-at-source-location file user-line handler @
1157 [#:current-frame] [#:vm]
1158 A trap that fires when control reaches a given source location. The
1159 @var{user-line} parameter is one-indexed, as a user counts lines,
1160 instead of zero-indexed, as Guile counts lines.
1161 @end deffn
1162
1163 @deffn {Scheme Procedure} trap-frame-finish frame @
1164 return-handler abort-handler [#:vm]
1165 A trap that fires when control leaves the given frame. @var{frame}
1166 should be a live frame in the current continuation. @var{return-handler}
1167 will be called on a normal return, and @var{abort-handler} on a nonlocal
1168 exit.
1169 @end deffn
1170
1171 @deffn {Scheme Procedure} trap-in-dynamic-extent proc @
1172 enter-handler return-handler abort-handler [#:vm] [#:closure?]
1173 A more traditional dynamic-wind trap, which fires @var{enter-handler}
1174 when control enters @var{proc}, @var{return-handler} on a normal return,
1175 and @var{abort-handler} on a nonlocal exit.
1176
1177 Note that rewinds are not handled, so there is no rewind handler.
1178 @end deffn
1179
1180 @deffn {Scheme Procedure} trap-calls-in-dynamic-extent proc @
1181 apply-handler return-handler [#:current-frame] [#:vm] [#:closure?]
1182 A trap that calls @var{apply-handler} every time a procedure is applied,
1183 and @var{return-handler} for returns, but only during the dynamic extent
1184 of an application of @var{proc}.
1185 @end deffn
1186
1187 @deffn {Scheme Procedure} trap-instructions-in-dynamic-extent proc @
1188 next-handler [#:current-frame] [#:vm] [#:closure?]
1189 A trap that calls @var{next-handler} for all retired instructions within
1190 the dynamic extent of a call to @var{proc}.
1191 @end deffn
1192
1193 @deffn {Scheme Procedure} trap-calls-to-procedure proc @
1194 apply-handler return-handler [#:vm]
1195 A trap that calls @var{apply-handler} whenever @var{proc} is applied,
1196 and @var{return-handler} when it returns, but with an additional
1197 argument, the call depth.
1198
1199 That is to say, the handlers will get two arguments: the frame in
1200 question, and the call depth (a non-negative integer).
1201 @end deffn
1202
1203 @deffn {Scheme Procedure} trap-matching-instructions frame-pred handler [#:vm]
1204 A trap that calls @var{frame-pred} at every instruction, and if
1205 @var{frame-pred} returns a true value, calls @var{handler} on the
1206 frame.
1207 @end deffn
1208
1209 @node Tracing Traps
1210 @subsubsection Tracing Traps
1211
1212 The @code{(system vm trace)} module defines a number of traps for
1213 tracing of procedure applications. When a procedure is @dfn{traced}, it
1214 means that every call to that procedure is reported to the user during a
1215 program run. The idea is that you can mark a collection of procedures
1216 for tracing, and Guile will subsequently print out a line of the form
1217
1218 @lisp
1219 | | (@var{procedure} @var{args} @dots{})
1220 @end lisp
1221
1222 whenever a marked procedure is about to be applied to its arguments.
1223 This can help a programmer determine whether a function is being called
1224 at the wrong time or with the wrong set of arguments.
1225
1226 In addition, the indentation of the output is useful for demonstrating
1227 how the traced applications are or are not tail recursive with respect
1228 to each other. Thus, a trace of a non-tail recursive factorial
1229 implementation looks like this:
1230
1231 @lisp
1232 scheme@@(guile-user)> (define (fact1 n)
1233 (if (zero? n) 1
1234 (* n (fact1 (1- n)))))
1235 scheme@@(guile-user)> ,trace (fact1 4)
1236 trace: (fact1 4)
1237 trace: | (fact1 3)
1238 trace: | | (fact1 2)
1239 trace: | | | (fact1 1)
1240 trace: | | | | (fact1 0)
1241 trace: | | | | 1
1242 trace: | | | 1
1243 trace: | | 2
1244 trace: | 6
1245 trace: 24
1246 @end lisp
1247
1248 While a typical tail recursive implementation would look more like this:
1249
1250 @lisp
1251 scheme@@(guile-user)> (define (facti acc n)
1252 (if (zero? n) acc
1253 (facti (* n acc) (1- n))))
1254 scheme@@(guile-user)> (define (fact2 n) (facti 1 n))
1255 scheme@@(guile-user)> ,trace (fact2 4)
1256 trace: (fact2 4)
1257 trace: (facti 1 4)
1258 trace: (facti 4 3)
1259 trace: (facti 12 2)
1260 trace: (facti 24 1)
1261 trace: (facti 24 0)
1262 trace: 24
1263 @end lisp
1264
1265 The low-level traps below (@pxref{Low-Level Traps}) share some common
1266 options:
1267
1268 @table @code
1269 @item #:width
1270 The maximum width of trace output. Trace printouts will try not to
1271 exceed this column, but for highly nested procedure calls, it may be
1272 unavoidable. Defaults to 80.
1273 @item #:vm
1274 The VM on which to add the traps. Defaults to the current thread's VM.
1275 @item #:prefix
1276 A string to print out before each trace line. As seen above in the
1277 examples, defaults to @code{"trace: "}.
1278 @end table
1279
1280 To have access to these procedures, you'll need to have imported the
1281 @code{(system vm trace)} module:
1282
1283 @lisp
1284 (use-modules (system vm trace))
1285 @end lisp
1286
1287 @deffn {Scheme Procedure} trace-calls-to-procedure proc @
1288 [#:width] [#:vm] [#:prefix]
1289 Print a trace at applications of and returns from @var{proc}.
1290 @end deffn
1291
1292 @deffn {Scheme Procedure} trace-calls-in-procedure proc @
1293 [#:width] [#:vm] [#:prefix]
1294 Print a trace at all applications and returns within the dynamic extent
1295 of calls to @var{proc}.
1296 @end deffn
1297
1298 @deffn {Scheme Procedure} trace-instructions-in-procedure proc [#:width] [#:vm]
1299 Print a trace at all instructions executed in the dynamic extent of
1300 calls to @var{proc}.
1301 @end deffn
1302
1303 In addition, Guile defines a procedure to call a thunk, tracing all
1304 procedure calls and returns within the thunk.
1305
1306 @deffn {Scheme Procedure} call-with-trace thunk [#:calls?=#t] @
1307 [#:instructions?=#f] @
1308 [#:width=80]
1309 Call @var{thunk}, tracing all execution within its dynamic extent.
1310
1311 If @var{calls?} is true, Guile will print a brief report at each
1312 procedure call and return, as given above.
1313
1314 If @var{instructions?} is true, Guile will also print a message each
1315 time an instruction is executed. This is a lot of output, but it is
1316 sometimes useful when doing low-level optimization.
1317
1318 Note that because this procedure manipulates the VM trace level
1319 directly, it doesn't compose well with traps at the REPL.
1320 @end deffn
1321
1322 @xref{Profile Commands}, for more information on tracing at the REPL.
1323
1324 @node Trap States
1325 @subsubsection Trap States
1326
1327 When multiple traps are present in a system, we begin to have a
1328 bookkeeping problem. How are they named? How does one disable, enable,
1329 or delete them?
1330
1331 Guile's answer to this is to keep an implicit per-thread @dfn{trap
1332 state}. The trap state object is not exposed to the user; rather, API
1333 that works on trap states fetches the current trap state from the
1334 dynamic environment.
1335
1336 Traps are identified by integers. A trap can be enabled, disabled, or
1337 removed, and can have an associated user-visible name.
1338
1339 These procedures have their own module:
1340
1341 @lisp
1342 (use-modules (system vm trap-state))
1343 @end lisp
1344
1345 @deffn {Scheme Procedure} add-trap! trap name
1346 Add a trap to the current trap state, associating the given @var{name}
1347 with it. Returns a fresh trap identifier (an integer).
1348
1349 Note that usually the more specific functions detailed in
1350 @ref{High-Level Traps} are used in preference to this one.
1351 @end deffn
1352
1353 @deffn {Scheme Procedure} list-traps
1354 List the current set of traps, both enabled and disabled. Returns a list
1355 of integers.
1356 @end deffn
1357
1358 @deffn {Scheme Procedure} trap-name idx
1359 Returns the name associated with trap @var{idx}, or @code{#f} if there
1360 is no such trap.
1361 @end deffn
1362
1363 @deffn {Scheme Procedure} trap-enabled? idx
1364 Returns @code{#t} if trap @var{idx} is present and enabled, or @code{#f}
1365 otherwise.
1366 @end deffn
1367
1368 @deffn {Scheme Procedure} enable-trap! idx
1369 Enables trap @var{idx}.
1370 @end deffn
1371
1372 @deffn {Scheme Procedure} disable-trap! idx
1373 Disables trap @var{idx}.
1374 @end deffn
1375
1376 @deffn {Scheme Procedure} delete-trap! idx
1377 Removes trap @var{idx}, disabling it first, if necessary.
1378 @end deffn
1379
1380 @node High-Level Traps
1381 @subsubsection High-Level Traps
1382
1383 The low-level trap API allows one to make traps that call procedures,
1384 and the trap state API allows one to keep track of what traps are
1385 there. But neither of these APIs directly helps you when you want to
1386 set a breakpoint, because it's unclear what to do when the trap fires.
1387 Do you enter a debugger, or mail a summary of the situation to your
1388 great-aunt, or what?
1389
1390 So for the common case in which you just want to install breakpoints,
1391 and then have them all result in calls to one parameterizable procedure,
1392 we have the high-level trap interface.
1393
1394 Perhaps we should have started this section with this interface, as it's
1395 clearly the one most people should use. But as its capabilities and
1396 limitations proceed from the lower layers, we felt that the
1397 character-building exercise of building a mental model might be helpful.
1398
1399 These procedures share a module with trap states:
1400
1401 @lisp
1402 (use-modules (system vm trap-state))
1403 @end lisp
1404
1405 @deffn {Scheme Procedure} with-default-trap-handler handler thunk
1406 Call @var{thunk} in a dynamic context in which @var{handler} is the
1407 current trap handler.
1408
1409 Additionally, during the execution of @var{thunk}, the VM trace level
1410 (@pxref{VM Hooks}) is set to the number of enabled traps. This ensures
1411 that traps will in fact fire.
1412
1413 @var{handler} may be @code{#f}, in which case VM hooks are not enabled
1414 as they otherwise would be, as there is nothing to handle the traps.
1415 @end deffn
1416
1417 The trace-level-setting behavior of @code{with-default-trap-handler} is
1418 one of its more useful aspects, but if you are willing to forgo that,
1419 and just want to install a global trap handler, there's a function for
1420 that too:
1421
1422 @deffn {Scheme Procedure} install-trap-handler! handler
1423 Set the current thread's trap handler to @var{handler}.
1424 @end deffn
1425
1426 Trap handlers are called when traps installed by procedures from this
1427 module fire. The current ``consumer'' of this API is Guile's REPL, but
1428 one might easily imagine other trap handlers being used to integrate
1429 with other debugging tools.
1430
1431 @cindex Breakpoints
1432 @cindex Setting breakpoints
1433 @deffn {Scheme Procedure} add-trap-at-procedure-call! proc
1434 Install a trap that will fire when @var{proc} is called.
1435
1436 This is a breakpoint.
1437 @end deffn
1438
1439 @cindex Tracepoints
1440 @cindex Setting tracepoints
1441 @deffn {Scheme Procedure} add-trace-at-procedure-call! proc
1442 Install a trap that will print a tracing message when @var{proc} is
1443 called. @xref{Tracing Traps}, for more information.
1444
1445 This is a tracepoint.
1446 @end deffn
1447
1448 @deffn {Scheme Procedure} add-trap-at-source-location! file user-line
1449 Install a trap that will fire when control reaches the given source
1450 location. @var{user-line} is one-indexed, as users count lines, instead
1451 of zero-indexed, as Guile counts lines.
1452
1453 This is a source breakpoint.
1454 @end deffn
1455
1456 @deffn {Scheme Procedure} add-ephemeral-trap-at-frame-finish! frame handler
1457 Install a trap that will call @var{handler} when @var{frame} finishes
1458 executing. The trap will be removed from the trap state after firing, or
1459 on nonlocal exit.
1460
1461 This is a finish trap, used to implement the ``finish'' REPL command.
1462 @end deffn
1463
1464 @deffn {Scheme Procedure} add-ephemeral-stepping-trap! frame handler [#:into?] [#:instruction?]
1465 Install a trap that will call @var{handler} after stepping to a
1466 different source line or instruction. The trap will be removed from the
1467 trap state after firing, or on nonlocal exit.
1468
1469 If @var{instruction?} is false (the default), the trap will fire when
1470 control reaches a new source line. Otherwise it will fire when control
1471 reaches a new instruction.
1472
1473 Additionally, if @var{into?} is false (not the default), the trap will
1474 only fire for frames at or prior to the given frame. If @var{into?} is
1475 true (the default), the trap may step into nested procedure
1476 invocations.
1477
1478 This is a stepping trap, used to implement the ``step'', ``next'',
1479 ``step-instruction'', and ``next-instruction'' REPL commands.
1480 @end deffn
1481
1482 @node GDB Support
1483 @subsection GDB Support
1484
1485 @cindex GDB support
1486
1487 Sometimes, you may find it necessary to debug Guile applications at the
1488 C level. Doing so can be tedious, in particular because the debugger is
1489 oblivious to Guile's @code{SCM} type, and thus unable to display
1490 @code{SCM} values in any meaningful way:
1491
1492 @example
1493 (gdb) frame
1494 #0 scm_display (obj=0xf04310, port=0x6f9f30) at print.c:1437
1495 @end example
1496
1497 To address that, Guile comes with an extension of the GNU Debugger (GDB)
1498 that contains a ``pretty-printer'' for @code{SCM} values. With this GDB
1499 extension, the C frame in the example above shows up like this:
1500
1501 @example
1502 (gdb) frame
1503 #0 scm_display (obj=("hello" GDB!), port=#<port file 6f9f30>) at print.c:1437
1504 @end example
1505
1506 @noindent
1507 Here GDB was able to decode the list pointed to by @var{obj}, and to
1508 print it using Scheme's read syntax.
1509
1510 That extension is a @code{.scm} file installed alongside the
1511 @file{libguile} shared library. When GDB 7.8 or later is installed and
1512 compiled with support for extensions written in Guile, the extension is
1513 automatically loaded when debugging a program linked against
1514 @file{libguile} (@pxref{Auto-loading,,, gdb, Debugging with GDB}). Note
1515 that the directory where @file{libguile} is installed must be among
1516 GDB's auto-loading ``safe directories'' (@pxref{Auto-loading safe
1517 path,,, gdb, Debugging with GDB}).
1518
1519
1520 @c Local Variables:
1521 @c TeX-master: "guile.texi"
1522 @c End: