Add interface to disable automatic finalization
[bpt/guile.git] / doc / ref / api-debug.texi
CommitLineData
07d83abe
MV
1@c -*-texinfo-*-
2@c This is part of the GNU Guile Reference Manual.
359f46a4 3@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2007, 2010, 2011, 2012, 2013, 2014
07d83abe
MV
4@c Free Software Foundation, Inc.
5@c See the file guile.texi for copying conditions.
6
07d83abe
MV
7@node Debugging
8@section Debugging Infrastructure
9
b20ef3a6 10@cindex Debugging
5af872e1 11In order to understand Guile's debugging facilities, you first need to
42cb9b03 12understand a little about how Guile represent the Scheme control stack.
a1652dec
AW
13With that in place we explain the low level trap calls that the virtual
14machine can be configured to make, and the trap and breakpoint
5af872e1
NJ
15infrastructure that builds on top of those calls.
16
07d83abe 17@menu
5af872e1 18* Evaluation Model:: Evaluation and the Scheme stack.
5db7c0bf 19* Source Properties:: From expressions to source locations.
359f46a4 20* Programmatic Error Handling:: Debugging when an error occurs.
3b541ca2 21* Traps:: Breakpoints, tracepoints, oh my!
359f46a4 22* GDB Support:: C-level debugging with GDB.
5af872e1
NJ
23@end menu
24
25@node Evaluation Model
26@subsection Evaluation and the Scheme Stack
27
42cb9b03
AW
28The idea of the Scheme stack is central to a lot of debugging. The
29Scheme stack is a reified representation of the pending function returns
a1652dec 30in an expression's continuation. As Guile implements function calls
42cb9b03 31using a stack, this reification takes the form of a number of nested
a1652dec
AW
32stack frames, each of which corresponds to the application of a
33procedure to a set of arguments.
42cb9b03
AW
34
35A Scheme stack always exists implicitly, and can be summoned into
36concrete existence as a first-class Scheme value by the
37@code{make-stack} call, so that an introspective Scheme program -- such
38as a debugger -- can present it in some way and allow the user to query
39its details. The first thing to understand, therefore, is how Guile's
40function call convention creates the stack.
41
42Broadly speaking, Guile represents all control flow on a stack. Calling
43a function involves pushing an empty frame on the stack, then evaluating
44the procedure and its arguments, then fixing up the new frame so that it
45points to the old one. Frames on the stack are thus linked together. A
46tail call is the same, except it reuses the existing frame instead of
47pushing on a new one.
48
49In this way, the only frames that are on the stack are ``active''
50frames, frames which need to do some work before the computation is
51complete. On the other hand, a function that has tail-called another
52function will not be on the stack, as it has no work left to do.
5af872e1
NJ
53
54Therefore, when an error occurs in a running program, or the program
55hits a breakpoint, or in fact at any point that the programmer chooses,
56its state at that point can be represented by a @dfn{stack} of all the
a1652dec
AW
57procedure applications that are logically in progress at that time, each
58of which is known as a @dfn{frame}. The programmer can learn more about
59the program's state at that point by inspecting the stack and its
60frames.
5af872e1
NJ
61
62@menu
5db7c0bf
AW
63* Stack Capture:: Reifying a continuation.
64* Stacks:: Accessors for the stack data type.
65* Frames:: Likewise, accessors for stack frames.
07d83abe
MV
66@end menu
67
5db7c0bf
AW
68@node Stack Capture
69@subsubsection Stack Capture
07d83abe 70
5af872e1
NJ
71A Scheme program can use the @code{make-stack} primitive anywhere in its
72code, with first arg @code{#t}, to construct a Scheme value that
73describes the Scheme stack at that point.
74
75@lisp
76(make-stack #t)
77@result{}
a1652dec 78#<stack 25205a0>
5af872e1 79@end lisp
07d83abe 80
5db7c0bf
AW
81Use @code{start-stack} to limit the stack extent captured by future
82@code{make-stack} calls.
83
df0a1002 84@deffn {Scheme Procedure} make-stack obj arg @dots{}
07d83abe
MV
85@deffnx {C Function} scm_make_stack (obj, args)
86Create a new stack. If @var{obj} is @code{#t}, the current
87evaluation stack is used for creating the stack frames,
88otherwise the frames are taken from @var{obj} (which must be
42cb9b03 89a continuation or a frame object).
07d83abe 90
df0a1002
BT
91@var{arg} @dots{} can be any combination of integer, procedure, prompt
92tag and @code{#t} values.
07d83abe
MV
93
94These values specify various ways of cutting away uninteresting
95stack frames from the top and bottom of the stack that
96@code{make-stack} returns. They come in pairs like this:
97@code{(@var{inner_cut_1} @var{outer_cut_1} @var{inner_cut_2}
98@var{outer_cut_2} @dots{})}.
99
64de6db5 100Each @var{inner_cut_i} can be @code{#t}, an integer, a prompt
42cb9b03
AW
101tag, or a procedure. @code{#t} means to cut away all frames up
102to but excluding the first user module frame. An integer means
103to cut away exactly that number of frames. A prompt tag means
104to cut away all frames that are inside a prompt with the given
105tag. A procedure means to cut away all frames up to but
106excluding the application frame whose procedure matches the
107specified one.
108
64de6db5 109Each @var{outer_cut_i} can be an integer, a prompt tag, or a
42cb9b03
AW
110procedure. An integer means to cut away that number of frames.
111A prompt tag means to cut away all frames that are outside a
112prompt with the given tag. A procedure means to cut away
113frames down to but excluding the application frame whose
07d83abe
MV
114procedure matches the specified one.
115
64de6db5 116If the @var{outer_cut_i} of the last pair is missing, it is
07d83abe
MV
117taken as 0.
118@end deffn
119
5db7c0bf
AW
120@deffn {Scheme Syntax} start-stack id exp
121Evaluate @var{exp} on a new calling stack with identity @var{id}. If
122@var{exp} is interrupted during evaluation, backtraces will not display
123frames farther back than @var{exp}'s top-level form. This macro is a
124way of artificially limiting backtraces and stack procedures, largely as
125a convenience to the user.
126@end deffn
127
07d83abe 128
6e069bbf
AW
129@node Stacks
130@subsubsection Stacks
07d83abe
MV
131
132@deffn {Scheme Procedure} stack? obj
133@deffnx {C Function} scm_stack_p (obj)
134Return @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)
139Return 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)
144Return 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)
149Return the @var{index}'th frame from @var{stack}.
150@end deffn
151
7cd44c6d
MV
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)
07d83abe 154@deffnx {C Function} scm_display_backtrace (stack, port, first, depth)
fc3d5c43 155Display a backtrace to the output port @var{port}. @var{stack}
07d83abe 156is the stack to take the backtrace from, @var{first} specifies
fc3d5c43
NJ
157where in the stack to start and @var{depth} how many frames
158to display. @var{first} and @var{depth} can be @code{#f},
07d83abe 159which means that default values will be used.
fc3d5c43
NJ
160If @var{highlights} is given it should be a list; the elements
161of this list will be highlighted wherever they appear in the
162backtrace.
07d83abe
MV
163@end deffn
164
165
6e069bbf
AW
166@node Frames
167@subsubsection Frames
07d83abe
MV
168
169@deffn {Scheme Procedure} frame? obj
170@deffnx {C Function} scm_frame_p (obj)
171Return @code{#t} if @var{obj} is a stack frame.
172@end deffn
173
07d83abe
MV
174@deffn {Scheme Procedure} frame-previous frame
175@deffnx {C Function} scm_frame_previous (frame)
176Return the previous frame of @var{frame}, or @code{#f} if
177@var{frame} is the first frame in its stack.
178@end deffn
179
07d83abe
MV
180@deffn {Scheme Procedure} frame-procedure frame
181@deffnx {C Function} scm_frame_procedure (frame)
182Return the procedure for @var{frame}, or @code{#f} if no
183procedure is associated with @var{frame}.
184@end deffn
185
186@deffn {Scheme Procedure} frame-arguments frame
187@deffnx {C Function} scm_frame_arguments (frame)
188Return the arguments of @var{frame}.
189@end deffn
190
5db7c0bf
AW
191@deffn {Scheme Procedure} frame-address frame
192@deffnx {Scheme Procedure} frame-instruction-pointer frame
193@deffnx {Scheme Procedure} frame-stack-pointer frame
194Accessors for the three VM registers associated with this frame: the
195frame pointer (fp), instruction pointer (ip), and stack pointer (sp),
196respectively. @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
202Accessors for the three saved VM registers in a frame: the previous
203frame pointer, the single-value return address, and the multiple-value
204return 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
210Accessors for the temporary values corresponding to @var{frame}'s
211procedure application. The first local is the first argument given to
212the procedure. After the arguments, there are the local variables, and
213after that temporary values. @xref{Stack Layout}, for more information.
214@end deffn
215
07d83abe
MV
216@deffn {Scheme Procedure} display-application frame [port [indent]]
217@deffnx {C Function} scm_display_application (frame, port, indent)
218Display a procedure application @var{frame} to the output port
219@var{port}. @var{indent} specifies the indentation of the
220output.
221@end deffn
222
5db7c0bf
AW
223Additionally, the @code{(system vm frame)} module defines a number of
224higher-level introspective procedures, for example to retrieve the names
225of local variables, and the source location to correspond to a
226frame. See its source code for more details.
227
07d83abe 228
5af872e1 229@node Source Properties
5db7c0bf 230@subsection Source Properties
5af872e1
NJ
231
232@cindex source properties
233As Guile reads in Scheme code from file or from standard input, it
234remembers the file name, line number and column number where each
42cb9b03
AW
235expression begins. These pieces of information are known as the
236@dfn{source properties} of the expression. Syntax expanders and the
237compiler propagate these source properties to compiled procedures, so
238that, if an error occurs when evaluating the transformed expression,
239Guile's debugger can point back to the file and location where the
240expression originated.
5af872e1 241
b131b233 242The way that source properties are stored means that Guile cannot
38f19074
MW
243associate source properties with individual symbols, keywords,
244characters, booleans, or small integers. This can be seen by typing
b131b233
MW
245@code{(xxx)} and @code{xxx} at the Guile prompt (where the variable
246@code{xxx} has not been defined):
5af872e1
NJ
247
248@example
a1652dec
AW
249scheme@@(guile-user)> (xxx)
250<unnamed port>:4:1: In procedure module-lookup:
251<unnamed port>:4:1: Unbound variable: xxx
252
253scheme@@(guile-user)> xxx
254ERROR: In procedure module-lookup:
255ERROR: Unbound variable: xxx
5af872e1
NJ
256@end example
257
258@noindent
a1652dec
AW
259In the latter case, no source properties were stored, so the error
260doesn't have any source information.
5af872e1 261
76b9bac5
MW
262@deffn {Scheme Procedure} supports-source-properties? obj
263@deffnx {C Function} scm_supports_source_properties_p (obj)
264Return #t if source properties can be associated with @var{obj},
265otherwise return #f.
266@end deffn
267
5af872e1 268The recording of source properties is controlled by the read option
1518f649 269named ``positions'' (@pxref{Scheme Read}). This option is switched
42cb9b03 270@emph{on} by default.
5af872e1
NJ
271
272The following procedures can be used to access and set the source
273properties of read expressions.
274
916f175f
NJ
275@deffn {Scheme Procedure} set-source-properties! obj alist
276@deffnx {C Function} scm_set_source_properties_x (obj, alist)
277Install the association list @var{alist} as the source property
5af872e1
NJ
278list 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)
283Set 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)
289Return 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)
916f175f
NJ
294Return the property specified by @var{key} from @var{obj}'s source
295properties.
5af872e1
NJ
296@end deffn
297
b131b233
MW
298If the @code{positions} reader option is enabled, supported expressions
299will have values set for the @code{filename}, @code{line} and
42cb9b03 300@code{column} properties.
5af872e1 301
925172cf
AW
302Source properties are also associated with syntax objects. Procedural
303macros can get at the source location of their input using the
304@code{syntax-source} accessor. @xref{Syntax Transformer Helpers}, for
305more.
306
307Guile also defines a couple of convenience macros built on
308@code{syntax-source}:
309
310@deffn {Scheme Syntax} current-source-location
311Expands 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
316Expands to the current filename: the filename that the
317@code{(current-filename)} form appears in. Expands to @code{#f} if this
318information is unavailable.
319@end deffn
320
1fc8dcc7
AW
321If you're stuck with defmacros (@pxref{Defmacros}), and want to preserve
322source information, the following helper function might be useful to
323you:
07d83abe 324
1fc8dcc7
AW
325@deffn {Scheme Procedure} cons-source xorig x y
326@deffnx {C Function} scm_cons_source (xorig, x, y)
327Create and return a new pair whose car and cdr are @var{x} and @var{y}.
328Any source properties associated with @var{xorig} are also associated
329with the new pair.
07d83abe
MV
330@end deffn
331
332
659c1e29
AW
333@node Programmatic Error Handling
334@subsection Programmatic Error Handling
335
336For better or for worse, all programs have bugs, and dealing with bugs
337is part of programming. This section deals with that class of bugs that
338causes an exception to be raised -- from your own code, from within a
339library, 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* Debug Options:: A historical interface to debugging.
346@end menu
347
348@node Catching Exceptions
349@subsubsection Catching Exceptions
5af872e1 350
2202fd6c
NJ
351A common requirement is to be able to show as much useful context as
352possible when a Scheme program hits an error. The most immediate
353information about an error is the kind of error that it is -- such as
354``division by zero'' -- and any parameters that the code which signalled
355the error chose explicitly to provide. This information originates with
356the @code{error} or @code{throw} call (or their C code equivalents, if
357the error is detected by C code) that signals the error, and is passed
358automatically to the handler procedure of the innermost applicable
42cb9b03 359@code{catch} or @code{with-throw-handler} expression.
2202fd6c 360
2202fd6c
NJ
361Therefore, to catch errors that occur within a chunk of Scheme code, and
362to intercept basic information about those errors, you need to execute
42cb9b03
AW
363that code inside the dynamic context of a @code{catch} or
364@code{with-throw-handler} expression, or the equivalent in C. In Scheme,
365this means you need something like this:
2202fd6c
NJ
366
367@lisp
368(catch #t
369 (lambda ()
370 ;; Execute the code in which
371 ;; you want to catch errors here.
372 ...)
373 (lambda (key . parameters)
374 ;; Put the code which you want
375 ;; to handle an error here.
376 ...))
377@end lisp
378
379@noindent
659c1e29
AW
380The @code{catch} here can also be @code{with-throw-handler}; see
381@ref{Throw Handlers} for information on the when you might want to use
382@code{with-throw-handler} instead of @code{catch}.
383
384For example, to print out a message and return #f when an error occurs,
385you might use:
386
387@smalllisp
388(define (catch-all thunk)
389 (catch #t
390 thunk
391 (lambda (key . parameters)
392 (format (current-error-port)
393 "Uncaught throw to '~a: ~a\n" key parameters)
394 #f)))
395
396(catch-all
397 (lambda () (error "Not a vegetable: tomato")))
3b3518e7 398@print{} Uncaught throw to 'misc-error: (#f ~A (Not a vegetable: tomato) #f)
659c1e29
AW
399@result{} #f
400@end smalllisp
401
402The @code{#t} means that the catch is applicable to all kinds of error.
403If you want to restrict your catch to just one kind of error, you can
404put the symbol for that kind of error instead of @code{#t}. The
405equivalent to this in C would be something like this:
2202fd6c
NJ
406
407@lisp
408SCM my_body_proc (void *body_data)
409@{
410 /* Execute the code in which
411 you want to catch errors here. */
412 ...
413@}
414
fc3d5c43
NJ
415SCM my_handler_proc (void *handler_data,
416 SCM key,
417 SCM parameters)
2202fd6c
NJ
418@{
419 /* Put the code which you want
420 to handle an error here. */
421 ...
422@}
423
424@{
425 ...
426 scm_c_catch (SCM_BOOL_T,
427 my_body_proc, body_data,
428 my_handler_proc, handler_data,
429 NULL, NULL);
430 ...
431@}
432@end lisp
433
434@noindent
435Again, as with the Scheme version, @code{scm_c_catch} could be replaced
42cb9b03
AW
436by @code{scm_c_with_throw_handler}, and @code{SCM_BOOL_T} could instead
437be the symbol for a particular kind of error.
2202fd6c 438
659c1e29 439@node Capturing Stacks
2202fd6c
NJ
440@subsubsection Capturing the full error stack
441
442The other interesting information about an error is the full Scheme
443stack at the point where the error occurred; in other words what
444innermost expression was being evaluated, what was the expression that
445called that one, and so on. If you want to write your code so that it
42cb9b03 446captures and can display this information as well, there are a couple
2202fd6c
NJ
447important things to understand.
448
42cb9b03 449Firstly, the stack at the point of the error needs to be explicitly
2202fd6c 450captured by a @code{make-stack} call (or the C equivalent
fc3d5c43 451@code{scm_make_stack}). The Guile library does not do this
2202fd6c
NJ
452``automatically'' for you, so you will need to write code with a
453@code{make-stack} or @code{scm_make_stack} call yourself. (We emphasise
454this point because some people are misled by the fact that the Guile
455interactive REPL code @emph{does} capture and display the stack
456automatically. But the Guile interactive REPL is itself a Scheme
457program@footnote{In effect, it is the default program which is run when
458no commands or script file are specified on the Guile command line.}
459running on top of the Guile library, and which uses @code{catch} and
460@code{make-stack} in the way we are about to describe to capture the
461stack when an error occurs.)
462
42cb9b03
AW
463And secondly, in order to capture the stack effectively at the point
464where the error occurred, the @code{make-stack} call must be made before
465Guile unwinds the stack back to the location of the prevailing catch
466expression. This means that the @code{make-stack} call must be made
467within the handler of a @code{with-throw-handler} expression, or the
468optional "pre-unwind" handler of a @code{catch}. (For the full story of
469how these alternatives differ from each other, see @ref{Exceptions}. The
470main difference is that @code{catch} terminates the error, whereas
471@code{with-throw-handler} only intercepts it temporarily and then allow
fc3d5c43
NJ
472it to continue propagating up to the next innermost handler.)
473
474So, here are some examples of how to do all this in Scheme and in C.
475For the purpose of these examples we assume that the captured stack
476should be stored in a variable, so that it can be displayed or
477arbitrarily processed later on. In Scheme:
478
479@lisp
480(let ((captured-stack #f))
481 (catch #t
482 (lambda ()
483 ;; Execute the code in which
484 ;; you want to catch errors here.
485 ...)
486 (lambda (key . parameters)
487 ;; Put the code which you want
488 ;; to handle an error after the
489 ;; stack has been unwound here.
490 ...)
491 (lambda (key . parameters)
492 ;; Capture the stack here:
493 (set! captured-stack (make-stack #t))))
494 ...
495 (if captured-stack
496 (begin
497 ;; Display or process the captured stack.
498 ...))
499 ...)
500@end lisp
501
502@noindent
503And in C:
504
505@lisp
506SCM my_body_proc (void *body_data)
507@{
508 /* Execute the code in which
509 you want to catch errors here. */
510 ...
511@}
512
513SCM my_handler_proc (void *handler_data,
514 SCM key,
515 SCM parameters)
516@{
517 /* Put the code which you want
518 to handle an error after the
519 stack has been unwound here. */
520 ...
521@}
522
523SCM my_preunwind_proc (void *handler_data,
524 SCM key,
525 SCM parameters)
526@{
527 /* Capture the stack here: */
528 *(SCM *)handler_data = scm_make_stack (SCM_BOOL_T, SCM_EOL);
529@}
530
531@{
532 SCM captured_stack = SCM_BOOL_F;
533 ...
534 scm_c_catch (SCM_BOOL_T,
535 my_body_proc, body_data,
536 my_handler_proc, handler_data,
537 my_preunwind_proc, &captured_stack);
538 ...
539 if (captured_stack != SCM_BOOL_F)
540 @{
541 /* Display or process the captured stack. */
542 ...
543 @}
544 ...
545@}
546@end lisp
547
fc3d5c43
NJ
548Once you have a captured stack, you can interrogate and display its
549details in any way that you want, using the @code{stack-@dots{}} and
6e069bbf
AW
550@code{frame-@dots{}} API described in @ref{Stacks} and
551@ref{Frames}.
fc3d5c43
NJ
552
553If you want to print out a backtrace in the same format that the Guile
554REPL does, you can use the @code{display-backtrace} procedure to do so.
555You can also use @code{display-application} to display an individual
659c1e29 556frame in the Guile REPL format.
fc3d5c43 557
659c1e29
AW
558@node Pre-Unwind Debugging
559@subsubsection Pre-Unwind Debugging
fc3d5c43 560
659c1e29
AW
561Instead of saving a stack away and waiting for the @code{catch} to
562return, you can handle errors directly, from within the pre-unwind
563handler.
564
565For example, to show a backtrace when an error is thrown, you might want
566to use a procedure like this:
567
568@lisp
569(define (with-backtrace thunk)
570 (with-throw-handler #t
571 thunk
572 (lambda args (backtrace))))
573(with-backtrace (lambda () (error "Not a vegetable: tomato")))
574@end lisp
575
576Since we used @code{with-throw-handler} here, we didn't actually catch
577the error. @xref{Throw Handlers}, for more information. However, we did
578print out a context at the time of the error, using the built-in
579procedure, @code{backtrace}.
fc3d5c43 580
5af872e1
NJ
581@deffn {Scheme Procedure} backtrace [highlights]
582@deffnx {C Function} scm_backtrace_with_highlights (highlights)
583@deffnx {C Function} scm_backtrace ()
659c1e29
AW
584Display a backtrace of the current stack to the current output port. If
585@var{highlights} is given it should be a list; the elements of this list
586will be highlighted wherever they appear in the backtrace.
5af872e1
NJ
587@end deffn
588
659c1e29
AW
589The Guile REPL code (in @file{system/repl/repl.scm} and related files)
590uses a @code{catch} with a pre-unwind handler to capture the stack when
591an error occurs in an expression that was typed into the REPL, and debug
592that stack interactively in the context of the error.
593
594These procedures are available for use by user programs, in the
595@code{(system repl error-handling)} module.
596
597@lisp
598(use-modules (system repl error-handling))
599@end lisp
5b2da4cc 600
1f603ae2
AW
601@deffn {Scheme Procedure} call-with-error-handling thunk @
602 [#:on-error on-error='debug] [#:post-error post-error='catch] @
603 [#:pass-keys pass-keys='(quit)] [#:trap-handler trap-handler='debug]
604Call a thunk in a context in which errors are handled.
605
606There are four keyword arguments:
607
608@table @var
609@item on-error
610Specifies what to do before the stack is unwound.
611
612Valid options are @code{debug} (the default), which will enter a
613debugger; @code{pass}, in which case nothing is done, and the exception
614is rethrown; or a procedure, which will be the pre-unwind handler.
615
616@item post-error
617Specifies what to do after the stack is unwound.
618
619Valid options are @code{catch} (the default), which will silently catch
620errors, returning the unspecified value; @code{report}, which prints out
621a description of the error (via @code{display-error}), and then returns
622the unspecified value; or a procedure, which will be the catch handler.
623
624@item trap-handler
625Specifies a trap handler: what to do when a breakpoint is hit.
626
627Valid options are @code{debug}, which will enter the debugger;
628@code{pass}, which does nothing; or @code{disabled}, which disables
629traps entirely. @xref{Traps}, for more information.
630
631@item pass-keys
632A set of keys to ignore, as a list.
633@end table
5af872e1
NJ
634@end deffn
635
659c1e29 636@node Debug Options
1cfdb1bb
AW
637@subsubsection Debug options
638
c005daf9
AW
639The behavior of the @code{backtrace} procedure and of the default error
640handler can be parameterized via the debug options.
1cfdb1bb
AW
641
642@cindex options - debug
643@cindex debug options
644@deffn {Scheme Procedure} debug-options [setting]
645Display the current settings of the debug options. If @var{setting} is
646omitted, only a short form of the current read options is printed.
647Otherwise if @var{setting} is the symbol @code{help}, a complete options
648description is displayed.
649@end deffn
650
651The set of available options, and their default values, may be had by
652invoking @code{debug-options} at the prompt.
653
654@smallexample
655scheme@@(guile-user)>
656backwards no Display backtrace in anti-chronological order.
657width 79 Maximal width of backtrace.
658depth 20 Maximal length of printed backtrace.
659backtrace yes Show backtrace on error.
660stack 1048576 Stack size limit (measured in words;
661 0 = no check).
662show-file-name #t Show file names and line numbers in backtraces
663 when not `#f'. A value of `base' displays only
664 base names, while `#t' displays full names.
665warn-deprecated no Warn when deprecated features are used.
666@end smallexample
667
668The boolean options may be toggled with @code{debug-enable} and
669@code{debug-disable}. The non-boolean @code{keywords} option must be set
670using @code{debug-set!}.
671
672@deffn {Scheme Procedure} debug-enable option-name
673@deffnx {Scheme Procedure} debug-disable option-name
1233b383 674@deffnx {Scheme Syntax} debug-set! option-name value
1cfdb1bb
AW
675Modify the debug options. @code{debug-enable} should be used with boolean
676options and switches them on, @code{debug-disable} switches them off.
1233b383
AW
677
678@code{debug-set!} can be used to set an option to a specific value. Due
679to historical oddities, it is a macro that expects an unquoted option
680name.
1cfdb1bb
AW
681@end deffn
682
683@subsubheading Stack overflow
684
685@cindex overflow, stack
686@cindex stack overflow
687Stack overflow errors are caused by a computation trying to use more
3b3518e7
AW
688stack space than has been enabled by the @code{stack} option. There are
689actually two kinds of stack that can overflow, the C stack and the
690Scheme stack.
691
692Scheme stack overflows can occur if Scheme procedures recurse too far
693deeply. An example would be the following recursive loop:
694
695@lisp
696scheme@@(guile-user)> (let lp () (+ 1 (lp)))
697<unnamed port>:8:17: In procedure vm-run:
698<unnamed port>:8:17: VM: Stack overflow
699@end lisp
700
701The default stack size should allow for about 10000 frames or so, so one
702usually doesn't hit this level of recursion. Unfortunately there is no
703way currently to make a VM with a bigger stack. If you are in this
704unfortunate situation, please file a bug, and in the meantime, rewrite
705your code to be tail-recursive (@pxref{Tail Calls}).
706
707The other limit you might hit would be C stack overflows. If you call a
708primitive procedure which then calls a Scheme procedure in a loop, you
709will consume C stack space. Guile tries to detect excessive consumption
710of C stack space, throwing an error when you have hit 80% of the
711process' available stack (as allocated by the operating system), or 160
712kilowords in the absence of a strict limit.
713
714For example, looping through @code{call-with-vm}, a primitive that calls
715a thunk, gives us the following:
1cfdb1bb
AW
716
717@lisp
3b3518e7
AW
718scheme@@(guile-user)> (use-modules (system vm vm))
719scheme@@(guile-user)> (debug-set! stack 10000)
720scheme@@(guile-user)> (let lp () (call-with-vm (the-vm) lp))
721ERROR: In procedure call-with-vm:
1cfdb1bb 722ERROR: Stack overflow
1cfdb1bb
AW
723@end lisp
724
725If you get an error like this, you can either try rewriting your code to
726use less stack space, or increase the maximum stack size. To increase
727the maximum stack size, use @code{debug-set!}, for example:
728
729@lisp
730(debug-set! stack 200000)
1cfdb1bb
AW
731@end lisp
732
3b3518e7
AW
733But of course it's better to have your code operate without so much
734resource consumption, avoiding loops through C trampolines.
1cfdb1bb 735
62ae9557 736
24dbb5ed
NJ
737@node Traps
738@subsection Traps
62ae9557
NJ
739
740@cindex Traps
6e069bbf 741@cindex VM hooks
62ae9557
NJ
742@cindex Breakpoints
743@cindex Trace
744@cindex Tracing
745@cindex Code coverage
746@cindex Profiling
42cb9b03 747Guile's virtual machine can be configured to call out at key points to
6e069bbf
AW
748arbitrary user-specified procedures.
749
750In principle, these @dfn{hooks} allow Scheme code to implement any model
751it chooses for examining the evaluation stack as program execution
752proceeds, and for suspending execution to be resumed later.
753
754VM hooks are very low-level, though, and so Guile also has a library of
755higher-level @dfn{traps} on top of the VM hooks. A trap is an execution
756condition that, when fulfilled, will fire a handler. For example, Guile
757defines a trap that fires when control reaches a certain source
758location.
759
760Finally, Guile also defines a third level of abstractions: per-thread
761@dfn{trap states}. A trap state exists to give names to traps, and to
762hold on to the set of traps so that they can be enabled, disabled, or
763removed. The trap state infrastructure defines the most useful
764abstractions for most cases. For example, Guile's REPL uses trap state
765functions to set breakpoints and tracepoints.
24dbb5ed
NJ
766
767The following subsections describe all this in detail, for both the
768user wanting to use traps, and the developer interested in
62ae9557
NJ
769understanding how the interface hangs together.
770
771
6e069bbf
AW
772@menu
773* VM Hooks:: Modifying Guile's virtual machine.
774* Trap Interface:: Traps are on or off.
775* Low-Level Traps:: The various kinds of low-level traps.
776* Tracing Traps:: Traps to trace procedure calls and returns.
777* Trap States:: One state (per thread) to bind them.
63e36ea6 778* High-Level Traps:: The highest-level trap interface. Use this.
6e069bbf 779@end menu
42cb9b03 780
42cb9b03 781
6e069bbf
AW
782@node VM Hooks
783@subsubsection VM Hooks
42cb9b03 784
6e069bbf
AW
785Everything that runs in Guile runs on its virtual machine, a C program
786that defines a number of operations that Scheme programs can
787perform.
62ae9557 788
6e069bbf
AW
789Note that there are multiple VM ``engines'' for Guile. Only some of them
790have support for hooks compiled in. Normally the deal is that you get
791hooks if you are running interactively, and otherwise they are disabled,
792as they do have some overhead (about 10 or 20 percent).
62ae9557 793
6e069bbf
AW
794To ensure that you are running with hooks, pass @code{--debug} to Guile
795when running your program, or otherwise use the @code{call-with-vm} and
796@code{set-vm-engine!} procedures to ensure that you are running in a VM
797with the @code{debug} engine.
62ae9557 798
6e069bbf
AW
799To digress, Guile's VM has 6 different hooks (@pxref{Hooks}) that can be
800fired at different times, which may be accessed with the following
801procedures.
62ae9557 802
6e069bbf 803All hooks are called with one argument, the frame in
5db7c0bf
AW
804question. @xref{Frames}. Since these hooks may be fired very
805frequently, Guile does a terrible thing: it allocates the frames on the
806C stack instead of the garbage-collected heap.
62ae9557 807
6e069bbf
AW
808The upshot here is that the frames are only valid within the dynamic
809extent of the call to the hook. If a hook procedure keeps a reference to
810the frame outside the extent of the hook, bad things will happen.
62ae9557 811
6e069bbf 812The interface to hooks is provided by the @code{(system vm vm)} module:
62ae9557 813
6e069bbf
AW
814@example
815(use-modules (system vm vm))
816@end example
62ae9557 817
6e069bbf
AW
818@noindent
819The result of calling @code{the-vm} is usually passed as the @var{vm}
820argument to all of these procedures.
62ae9557 821
6e069bbf
AW
822@deffn {Scheme Procedure} vm-next-hook vm
823The hook that will be fired before an instruction is retired (and
824executed).
825@end deffn
62ae9557 826
6e069bbf
AW
827@deffn {Scheme Procedure} vm-push-continuation-hook vm
828The hook that will be fired after preparing a new frame. Fires just
829before applying a procedure in a non-tail context, just before the
830corresponding apply-hook.
831@end deffn
62ae9557 832
6e069bbf
AW
833@deffn {Scheme Procedure} vm-pop-continuation-hook vm
834The hook that will be fired before returning from a frame.
62ae9557 835
6e069bbf
AW
836This hook is a bit trickier than the rest, in that there is a particular
837interpretation of the values on the stack. Specifically, the top value
838on the stack is the number of values being returned, and the next
839@var{n} values are the actual values being returned, with the last value
840highest on the stack.
841@end deffn
62ae9557 842
6e069bbf
AW
843@deffn {Scheme Procedure} vm-apply-hook vm
844The hook that will be fired before a procedure is applied. The frame's
845procedure will have already been set to the new procedure.
62ae9557 846
6e069bbf
AW
847Note that procedure application is somewhat orthogonal to continuation
848pushes and pops. A non-tail call to a procedure will result first in a
849firing of the push-continuation hook, then this application hook,
850whereas a tail call will run without having fired a push-continuation
851hook.
852@end deffn
62ae9557 853
6e069bbf
AW
854@deffn {Scheme Procedure} vm-abort-continuation-hook vm
855The hook that will be called after aborting to a
856prompt. @xref{Prompts}. The stack will be in the same state as for
857@code{vm-pop-continuation-hook}.
858@end deffn
62ae9557 859
6e069bbf
AW
860@deffn {Scheme Procedure} vm-restore-continuation-hook vm
861The hook that will be called after restoring an undelimited
862continuation. Unfortunately it's not currently possible to introspect on
863the values that were given to the continuation.
864@end deffn
62ae9557 865
6e069bbf
AW
866@cindex VM trace level
867These hooks do impose a performance penalty, if they are on. Obviously,
868the @code{vm-next-hook} has quite an impact, performance-wise. Therefore
869Guile exposes a single, heavy-handed knob to turn hooks on or off, the
870@dfn{VM trace level}. If the trace level is positive, hooks run;
871otherwise they don't.
62ae9557 872
5db7c0bf
AW
873For convenience, when the VM fires a hook, it does so with the trap
874level temporarily set to 0. That way the hooks don't fire while you're
875handling a hook. The trace level is restored to whatever it was once the hook
876procedure finishes.
877
6e069bbf
AW
878@deffn {Scheme Procedure} vm-trace-level vm
879Retrieve the ``trace level'' of the VM. If positive, the trace hooks
880associated with @var{vm} will be run. The initial trace level is 0.
881@end deffn
62ae9557 882
6e069bbf
AW
883@deffn {Scheme Procedure} set-vm-trace-level! vm level
884Set the ``trace level'' of the VM.
885@end deffn
886
887@xref{A Virtual Machine for Guile}, for more information on Guile's
888virtual machine.
889
890@node Trap Interface
891@subsubsection Trap Interface
892
893The capabilities provided by hooks are great, but hooks alone rarely
894correspond to what users want to do.
895
896For example, if a user wants to break when and if control reaches a
897certain source location, how do you do it? If you install a ``next''
898hook, you get unacceptable overhead for the execution of the entire
899program. It would be possible to install an ``apply'' hook, then if the
900procedure encompasses those source locations, install a ``next'' hook,
901but already you're talking about one concept that might be implemented
902by a varying number of lower-level concepts.
903
904It's best to be clear about things and define one abstraction for all
905such conditions: the @dfn{trap}.
906
907Considering the myriad capabilities offered by the hooks though, there
908is only a minimum of functionality shared by all traps. Guile's current
909take is to reduce this to the absolute minimum, and have the only
910standard interface of a trap be ``turn yourself on'' or ``turn yourself
911off''.
912
913This interface sounds a bit strange, but it is useful to procedurally
914compose higher-level traps from lower-level building blocks. For
915example, Guile defines a trap that calls one handler when control enters
916a procedure, and another when control leaves the procedure. Given that
917trap, one can define a trap that adds to the next-hook only when within
918a given procedure. Building further, one can define a trap that fires
919when control reaches particular instructions within a procedure.
920
921Or of course you can stop at any of these intermediate levels. For
922example, one might only be interested in calls to a given procedure. But
923the point is that a simple enable/disable interface is all the
924commonality that exists between the various kinds of traps, and
925furthermore that such an interface serves to allow ``higher-level''
926traps to be composed from more primitive ones.
927
928Specifically, a trap, in Guile, is a procedure. When a trap is created,
929by convention the trap is enabled; therefore, the procedure that is the
930trap will, when called, disable the trap, and return a procedure that
931will enable the trap, and so on.
932
933Trap procedures take one optional argument: the current frame. (A trap
934may want to add to different sets of hooks depending on the frame that
935is current at enable-time.)
936
937If this all sounds very complicated, it's because it is. Some of it is
938essential, but probably most of it is not. The advantage of using this
939minimal interface is that composability is more lexically apparent than
940when, for example, using a stateful interface based on GOOPS. But
941perhaps this reflects the cognitive limitations of the programmer who
942made the current interface more than anything else.
943
944@node Low-Level Traps
945@subsubsection Low-Level Traps
946
5db7c0bf
AW
947To summarize the last sections, traps are enabled or disabled, and when
948they are enabled, they add to various VM hooks.
949
950Note, however, that @emph{traps do not increase the VM trace level}. So
951if you create a trap, it will be enabled, but unless something else
952increases the VM's trace level (@pxref{VM Hooks}), the trap will not
953fire. It turns out that getting the VM trace level right is tricky
954without a global view of what traps are enabled. @xref{Trap States},
955for Guile's answer to this problem.
956
957Traps are created by calling procedures. Most of these procedures share
958a set of common keyword arguments, so rather than document them
959separately, we discuss them all together here:
960
961@table @code
962@item #:vm
963The VM to instrument. Defaults to the current thread's VM.
964@item #:closure?
965For traps that depend on the current frame's procedure, this argument
966specifies whether to trap on the only the specific procedure given, or
967on any closure that has the given procedure's code. Defaults to
968@code{#f}.
969@item #:current-frame
970For traps that enable more hooks depending on their dynamic context,
971this argument gives the current frame that the trap is running in.
972Defaults to @code{#f}.
973@end table
974
63e36ea6
AW
975To have access to these procedures, you'll need to have imported the
976@code{(system vm traps)} module:
977
978@lisp
979(use-modules (system vm traps))
980@end lisp
981
6e069bbf 982@deffn {Scheme Procedure} trap-at-procedure-call proc handler @
5db7c0bf
AW
983 [#:vm] [#:closure?]
984A trap that calls @var{handler} when @var{proc} is applied.
6e069bbf 985@end deffn
62ae9557 986
6e069bbf 987@deffn {Scheme Procedure} trap-in-procedure proc @
5db7c0bf
AW
988 enter-handler exit-handler [#:current-frame] [#:vm] [#:closure?]
989A trap that calls @var{enter-handler} when control enters @var{proc},
990and @var{exit-handler} when control leaves @var{proc}.
6e069bbf
AW
991
992Control can enter a procedure via:
5db7c0bf
AW
993@itemize
994@item
995A procedure call.
996@item
997A return to a procedure's frame on the stack.
998@item
999A continuation returning directly to an application of this procedure.
1000@end itemize
6e069bbf
AW
1001
1002Control can leave a procedure via:
5db7c0bf
AW
1003@itemize
1004@item
1005A normal return from the procedure.
1006@item
1007An application of another procedure.
1008@item
1009An invocation of a continuation.
1010@item
1011An abort.
1012@end itemize
62ae9557
NJ
1013@end deffn
1014
6e069bbf 1015@deffn {Scheme Procedure} trap-instructions-in-procedure proc @
5db7c0bf
AW
1016 next-handler exit-handler [#:current-frame] [#:vm] [#:closure?]
1017A trap that calls @var{next-handler} for every instruction executed in
1018@var{proc}, and @var{exit-handler} when execution leaves @var{proc}.
62ae9557
NJ
1019@end deffn
1020
6e069bbf 1021@deffn {Scheme Procedure} trap-at-procedure-ip-in-range proc range @
5db7c0bf
AW
1022 handler [#:current-frame] [#:vm] [#:closure?]
1023A trap that calls @var{handler} when execution enters a range of
1024instructions in @var{proc}. @var{range} is a simple of pairs,
1025@code{((@var{start} . @var{end}) ...)}. The @var{start} addresses are
1026inclusive, and @var{end} addresses are exclusive.
6e069bbf 1027@end deffn
62ae9557 1028
6e069bbf 1029@deffn {Scheme Procedure} trap-at-source-location file user-line handler @
5db7c0bf
AW
1030 [#:current-frame] [#:vm]
1031A trap that fires when control reaches a given source location. The
1032@var{user-line} parameter is one-indexed, as a user counts lines,
1033instead of zero-indexed, as Guile counts lines.
6e069bbf 1034@end deffn
62ae9557 1035
5db7c0bf
AW
1036@deffn {Scheme Procedure} trap-frame-finish frame @
1037 return-handler abort-handler [#:vm]
1038A trap that fires when control leaves the given frame. @var{frame}
1039should be a live frame in the current continuation. @var{return-handler}
1040will be called on a normal return, and @var{abort-handler} on a nonlocal
1041exit.
6e069bbf 1042@end deffn
62ae9557 1043
6e069bbf 1044@deffn {Scheme Procedure} trap-in-dynamic-extent proc @
5db7c0bf
AW
1045 enter-handler return-handler abort-handler [#:vm] [#:closure?]
1046A more traditional dynamic-wind trap, which fires @var{enter-handler}
1047when control enters @var{proc}, @var{return-handler} on a normal return,
1048and @var{abort-handler} on a nonlocal exit.
1049
1050Note that rewinds are not handled, so there is no rewind handler.
62ae9557
NJ
1051@end deffn
1052
6e069bbf 1053@deffn {Scheme Procedure} trap-calls-in-dynamic-extent proc @
5db7c0bf
AW
1054 apply-handler return-handler [#:current-frame] [#:vm] [#:closure?]
1055A trap that calls @var{apply-handler} every time a procedure is applied,
1056and @var{return-handler} for returns, but only during the dynamic extent
1057of an application of @var{proc}.
62ae9557
NJ
1058@end deffn
1059
6e069bbf 1060@deffn {Scheme Procedure} trap-instructions-in-dynamic-extent proc @
5db7c0bf 1061 next-handler [#:current-frame] [#:vm] [#:closure?]
ecb87335 1062A trap that calls @var{next-handler} for all retired instructions within
5db7c0bf 1063the dynamic extent of a call to @var{proc}.
62ae9557
NJ
1064@end deffn
1065
6e069bbf 1066@deffn {Scheme Procedure} trap-calls-to-procedure proc @
5db7c0bf
AW
1067 apply-handler return-handler [#:vm]
1068A trap that calls @var{apply-handler} whenever @var{proc} is applied,
1069and @var{return-handler} when it returns, but with an additional
1070argument, the call depth.
1071
1072That is to say, the handlers will get two arguments: the frame in
1073question, and the call depth (a non-negative integer).
62ae9557
NJ
1074@end deffn
1075
5db7c0bf
AW
1076@deffn {Scheme Procedure} trap-matching-instructions frame-pred handler [#:vm]
1077A trap that calls @var{frame-pred} at every instruction, and if
1078@var{frame-pred} returns a true value, calls @var{handler} on the
1079frame.
62ae9557
NJ
1080@end deffn
1081
6e069bbf
AW
1082@node Tracing Traps
1083@subsubsection Tracing Traps
62ae9557 1084
6e069bbf
AW
1085The @code{(system vm trace)} module defines a number of traps for
1086tracing of procedure applications. When a procedure is @dfn{traced}, it
1087means that every call to that procedure is reported to the user during a
1088program run. The idea is that you can mark a collection of procedures
1089for tracing, and Guile will subsequently print out a line of the form
62ae9557
NJ
1090
1091@lisp
6e069bbf 1092| | (@var{procedure} @var{args} @dots{})
62ae9557
NJ
1093@end lisp
1094
6e069bbf
AW
1095whenever a marked procedure is about to be applied to its arguments.
1096This can help a programmer determine whether a function is being called
1097at the wrong time or with the wrong set of arguments.
1098
1099In addition, the indentation of the output is useful for demonstrating
1100how the traced applications are or are not tail recursive with respect
1101to each other. Thus, a trace of a non-tail recursive factorial
1102implementation looks like this:
1103
1104@lisp
1105scheme@@(guile-user)> (define (fact1 n)
1106 (if (zero? n) 1
1107 (* n (fact1 (1- n)))))
1108scheme@@(guile-user)> ,trace (fact1 4)
1109trace: (fact1 4)
1110trace: | (fact1 3)
1111trace: | | (fact1 2)
1112trace: | | | (fact1 1)
1113trace: | | | | (fact1 0)
1114trace: | | | | 1
1115trace: | | | 1
1116trace: | | 2
1117trace: | 6
1118trace: 24
1119@end lisp
1120
1121While a typical tail recursive implementation would look more like this:
1122
1123@lisp
1124scheme@@(guile-user)> (define (facti acc n)
1125 (if (zero? n) acc
1126 (facti (* n acc) (1- n))))
1127scheme@@(guile-user)> (define (fact2 n) (facti 1 n))
1128scheme@@(guile-user)> ,trace (fact2 4)
1129trace: (fact2 4)
1130trace: (facti 1 4)
1131trace: (facti 4 3)
1132trace: (facti 12 2)
1133trace: (facti 24 1)
1134trace: (facti 24 0)
1135trace: 24
1136@end lisp
1137
90729e71
AW
1138The low-level traps below (@pxref{Low-Level Traps}) share some common
1139options:
1140
1141@table @code
1142@item #:width
1143The maximum width of trace output. Trace printouts will try not to
1144exceed this column, but for highly nested procedure calls, it may be
1145unavoidable. Defaults to 80.
1146@item #:vm
1147The VM on which to add the traps. Defaults to the current thread's VM.
1148@item #:prefix
1149A string to print out before each trace line. As seen above in the
1150examples, defaults to @code{"trace: "}.
1151@end table
1152
63e36ea6
AW
1153To have access to these procedures, you'll need to have imported the
1154@code{(system vm trace)} module:
1155
1156@lisp
1157(use-modules (system vm trace))
1158@end lisp
1159
90729e71
AW
1160@deffn {Scheme Procedure} trace-calls-to-procedure proc @
1161 [#:width] [#:vm] [#:prefix]
1162Print a trace at applications of and returns from @var{proc}.
6e069bbf
AW
1163@end deffn
1164
90729e71
AW
1165@deffn {Scheme Procedure} trace-calls-in-procedure proc @
1166 [#:width] [#:vm] [#:prefix]
1167Print a trace at all applications and returns within the dynamic extent
1168of calls to @var{proc}.
6e069bbf
AW
1169@end deffn
1170
90729e71
AW
1171@deffn {Scheme Procedure} trace-instructions-in-procedure proc [#:width] [#:vm]
1172Print a trace at all instructions executed in the dynamic extent of
1173calls to @var{proc}.
6e069bbf
AW
1174@end deffn
1175
1176In addition, Guile defines a procedure to call a thunk, tracing all
1177procedure calls and returns within the thunk.
1178
994d87be
BT
1179@deffn {Scheme Procedure} call-with-trace thunk [#:calls?=#t] @
1180 [#:instructions?=#f] @
1181 [#:width=80] [#:vm=(the-vm)]
6e069bbf
AW
1182Call @var{thunk}, tracing all execution within its dynamic extent.
1183
1184If @var{calls?} is true, Guile will print a brief report at each
1185procedure call and return, as given above.
1186
1187If @var{instructions?} is true, Guile will also print a message each
1188time an instruction is executed. This is a lot of output, but it is
1189sometimes useful when doing low-level optimization.
1190
1191Note that because this procedure manipulates the VM trace level
1192directly, it doesn't compose well with traps at the REPL.
1193@end deffn
1194
1195@xref{Profile Commands}, for more information on tracing at the REPL.
1196
1197@node Trap States
1198@subsubsection Trap States
1199
de03880a
AW
1200When multiple traps are present in a system, we begin to have a
1201bookkeeping problem. How are they named? How does one disable, enable,
1202or delete them?
1203
1204Guile's answer to this is to keep an implicit per-thread @dfn{trap
1205state}. The trap state object is not exposed to the user; rather, API
1206that works on trap states fetches the current trap state from the
1207dynamic environment.
1208
6b1d1af7 1209Traps are identified by integers. A trap can be enabled, disabled, or
de03880a
AW
1210removed, and can have an associated user-visible name.
1211
63e36ea6
AW
1212These procedures have their own module:
1213
1214@lisp
1215(use-modules (system vm trap-state))
1216@end lisp
1217
de03880a
AW
1218@deffn {Scheme Procedure} add-trap! trap name
1219Add a trap to the current trap state, associating the given @var{name}
1220with it. Returns a fresh trap identifier (an integer).
1221
63e36ea6
AW
1222Note that usually the more specific functions detailed in
1223@ref{High-Level Traps} are used in preference to this one.
de03880a
AW
1224@end deffn
1225
6e069bbf 1226@deffn {Scheme Procedure} list-traps
de03880a
AW
1227List the current set of traps, both enabled and disabled. Returns a list
1228of integers.
6e069bbf
AW
1229@end deffn
1230
1231@deffn {Scheme Procedure} trap-name idx
de03880a
AW
1232Returns the name associated with trap @var{idx}, or @code{#f} if there
1233is no such trap.
6e069bbf
AW
1234@end deffn
1235
1236@deffn {Scheme Procedure} trap-enabled? idx
de03880a
AW
1237Returns @code{#t} if trap @var{idx} is present and enabled, or @code{#f}
1238otherwise.
6e069bbf
AW
1239@end deffn
1240
1241@deffn {Scheme Procedure} enable-trap! idx
de03880a 1242Enables trap @var{idx}.
6e069bbf
AW
1243@end deffn
1244
1245@deffn {Scheme Procedure} disable-trap! idx
de03880a 1246Disables trap @var{idx}.
6e069bbf
AW
1247@end deffn
1248
1249@deffn {Scheme Procedure} delete-trap! idx
de03880a 1250Removes trap @var{idx}, disabling it first, if necessary.
6e069bbf 1251@end deffn
62ae9557 1252
63e36ea6
AW
1253@node High-Level Traps
1254@subsubsection High-Level Traps
1255
1256The low-level trap API allows one to make traps that call procedures,
1257and the trap state API allows one to keep track of what traps are
1258there. But neither of these APIs directly helps you when you want to
1259set a breakpoint, because it's unclear what to do when the trap fires.
1260Do you enter a debugger, or mail a summary of the situation to your
1261great-aunt, or what?
1262
1263So for the common case in which you just want to install breakpoints,
6b1d1af7
AW
1264and then have them all result in calls to one parameterizable procedure,
1265we have the high-level trap interface.
63e36ea6
AW
1266
1267Perhaps we should have started this section with this interface, as it's
1268clearly the one most people should use. But as its capabilities and
1269limitations proceed from the lower layers, we felt that the
6b1d1af7 1270character-building exercise of building a mental model might be helpful.
62ae9557 1271
63e36ea6
AW
1272These procedures share a module with trap states:
1273
1274@lisp
1275(use-modules (system vm trap-state))
1276@end lisp
62ae9557 1277
6e069bbf 1278@deffn {Scheme Procedure} with-default-trap-handler handler thunk
63e36ea6
AW
1279Call @var{thunk} in a dynamic context in which @var{handler} is the
1280current trap handler.
1281
1282Additionally, during the execution of @var{thunk}, the VM trace level
1283(@pxref{VM Hooks}) is set to the number of enabled traps. This ensures
1284that traps will in fact fire.
1285
1286@var{handler} may be @code{#f}, in which case VM hooks are not enabled
1287as they otherwise would be, as there is nothing to handle the traps.
62ae9557
NJ
1288@end deffn
1289
63e36ea6
AW
1290The trace-level-setting behavior of @code{with-default-trap-handler} is
1291one of its more useful aspects, but if you are willing to forgo that,
1292and just want to install a global trap handler, there's a function for
1293that too:
1294
6e069bbf 1295@deffn {Scheme Procedure} install-trap-handler! handler
63e36ea6 1296Set the current thread's trap handler to @var{handler}.
6e069bbf
AW
1297@end deffn
1298
63e36ea6
AW
1299Trap handlers are called when traps installed by procedures from this
1300module fire. The current ``consumer'' of this API is Guile's REPL, but
1301one might easily imagine other trap handlers being used to integrate
1302with other debugging tools.
6e069bbf 1303
63e36ea6
AW
1304@cindex Breakpoints
1305@cindex Setting breakpoints
6e069bbf 1306@deffn {Scheme Procedure} add-trap-at-procedure-call! proc
63e36ea6
AW
1307Install a trap that will fire when @var{proc} is called.
1308
1309This is a breakpoint.
62ae9557
NJ
1310@end deffn
1311
63e36ea6
AW
1312@cindex Tracepoints
1313@cindex Setting tracepoints
6e069bbf 1314@deffn {Scheme Procedure} add-trace-at-procedure-call! proc
63e36ea6
AW
1315Install a trap that will print a tracing message when @var{proc} is
1316called. @xref{Tracing Traps}, for more information.
1317
1318This is a tracepoint.
62ae9557
NJ
1319@end deffn
1320
6e069bbf 1321@deffn {Scheme Procedure} add-trap-at-source-location! file user-line
63e36ea6
AW
1322Install a trap that will fire when control reaches the given source
1323location. @var{user-line} is one-indexed, as users count lines, instead
1324of zero-indexed, as Guile counts lines.
1325
1326This is a source breakpoint.
62ae9557
NJ
1327@end deffn
1328
6e069bbf 1329@deffn {Scheme Procedure} add-ephemeral-trap-at-frame-finish! frame handler
63e36ea6
AW
1330Install a trap that will call @var{handler} when @var{frame} finishes
1331executing. The trap will be removed from the trap state after firing, or
1332on nonlocal exit.
1333
1334This is a finish trap, used to implement the ``finish'' REPL command.
62ae9557
NJ
1335@end deffn
1336
63e36ea6
AW
1337@deffn {Scheme Procedure} add-ephemeral-stepping-trap! frame handler [#:into?] [#:instruction?]
1338Install a trap that will call @var{handler} after stepping to a
1339different source line or instruction. The trap will be removed from the
1340trap state after firing, or on nonlocal exit.
1341
1342If @var{instruction?} is false (the default), the trap will fire when
1343control reaches a new source line. Otherwise it will fire when control
1344reaches a new instruction.
1345
1346Additionally, if @var{into?} is false (not the default), the trap will
1347only fire for frames at or prior to the given frame. If @var{into?} is
1348true (the default), the trap may step into nested procedure
1349invocations.
1350
1351This is a stepping trap, used to implement the ``step'', ``next'',
1352``step-instruction'', and ``next-instruction'' REPL commands.
62ae9557
NJ
1353@end deffn
1354
359f46a4
LC
1355@node GDB Support
1356@subsection GDB Support
1357
1358@cindex GDB support
1359
1360Sometimes, you may find it necessary to debug Guile applications at the
1361C level. Doing so can be tedious, in particular because the debugger is
1362oblivious to Guile's @code{SCM} type, and thus unable to display
1363@code{SCM} values in any meaningful way:
1364
1365@example
1366(gdb) frame
1367#0 scm_display (obj=0xf04310, port=0x6f9f30) at print.c:1437
1368@end example
1369
1370To address that, Guile comes with an extension of the GNU Debugger (GDB)
1371that contains a ``pretty-printer'' for @code{SCM} values. With this GDB
1372extension, the C frame in the example above shows up like this:
1373
1374@example
1375(gdb) frame
1376#0 scm_display (obj=("hello" GDB!), port=#<port file 6f9f30>) at print.c:1437
1377@end example
1378
1379@noindent
1380Here GDB was able to decode the list pointed to by @var{obj}, and to
1381print it using Scheme's read syntax.
1382
1383That extension is a @code{.scm} file installed alongside the
1384@file{libguile} shared library. When GDB 7.8 or later is installed and
1385compiled with support for extensions written in Guile, the extension is
1386automatically loaded when debugging a program linked against
1387@file{libguile} (@pxref{Auto-loading,,, gdb, Debugging with GDB}). Note
1388that the directory where @file{libguile} is installed must be among
1389GDB's auto-loading ``safe directories'' (@pxref{Auto-loading safe
1390path,,, gdb, Debugging with GDB}).
1391
62ae9557 1392
07d83abe
MV
1393@c Local Variables:
1394@c TeX-master: "guile.texi"
1395@c End: