api-debug.texi 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402
  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, 2018, 2021
  4. @c Free Software Foundation, Inc.
  5. @c See the file guile.texi for copying conditions.
  6. @node Debugging
  7. @section Debugging Infrastructure
  8. @cindex Debugging
  9. In order to understand Guile's debugging facilities, you first need to
  10. understand a little about how Guile represents the Scheme control stack.
  11. With that in place we explain the low level trap calls that the virtual
  12. machine can be configured to make, and the trap and breakpoint
  13. infrastructure that builds on top of those calls.
  14. @menu
  15. * Evaluation Model:: Evaluation and the Scheme stack.
  16. * Source Properties:: From expressions to source locations.
  17. * Programmatic Error Handling:: Debugging when an error occurs.
  18. * Traps:: Breakpoints, tracepoints, oh my!
  19. * GDB Support:: C-level debugging with GDB.
  20. @end menu
  21. @node Evaluation Model
  22. @subsection Evaluation and the Scheme Stack
  23. The idea of the Scheme stack is central to a lot of debugging. The
  24. Scheme stack is a reified representation of the pending function returns
  25. in an expression's continuation. As Guile implements function calls
  26. using a stack, this reification takes the form of a number of nested
  27. stack frames, each of which corresponds to the application of a
  28. procedure to a set of arguments.
  29. A Scheme stack always exists implicitly, and can be summoned into
  30. concrete existence as a first-class Scheme value by the
  31. @code{make-stack} call, so that an introspective Scheme program -- such
  32. as a debugger -- can present it in some way and allow the user to query
  33. its details. The first thing to understand, therefore, is how Guile's
  34. function call convention creates the stack.
  35. Broadly speaking, Guile represents all control flow on a stack. Calling
  36. a function involves pushing an empty frame on the stack, then evaluating
  37. the procedure and its arguments, then fixing up the new frame so that it
  38. points to the old one. Frames on the stack are thus linked together. A
  39. tail call is the same, except it reuses the existing frame instead of
  40. pushing on a new one.
  41. In this way, the only frames that are on the stack are ``active''
  42. frames, frames which need to do some work before the computation is
  43. complete. On the other hand, a function that has tail-called another
  44. function will not be on the stack, as it has no work left to do.
  45. Therefore, when an error occurs in a running program, or the program
  46. hits a breakpoint, or in fact at any point that the programmer chooses,
  47. its state at that point can be represented by a @dfn{stack} of all the
  48. procedure applications that are logically in progress at that time, each
  49. of which is known as a @dfn{frame}. The programmer can learn more about
  50. the program's state at that point by inspecting the stack and its
  51. frames.
  52. @menu
  53. * Stack Capture:: Reifying a continuation.
  54. * Stacks:: Accessors for the stack data type.
  55. * Frames:: Likewise, accessors for stack frames.
  56. @end menu
  57. @node Stack Capture
  58. @subsubsection Stack Capture
  59. A Scheme program can use the @code{make-stack} primitive anywhere in its
  60. code, with first arg @code{#t}, to construct a Scheme value that
  61. describes the Scheme stack at that point.
  62. @lisp
  63. (make-stack #t)
  64. @result{}
  65. #<stack 25205a0>
  66. @end lisp
  67. Use @code{start-stack} to limit the stack extent captured by future
  68. @code{make-stack} calls.
  69. @deffn {Scheme Procedure} make-stack obj arg @dots{}
  70. @deffnx {C Function} scm_make_stack (obj, args)
  71. Create a new stack. If @var{obj} is @code{#t}, the current
  72. evaluation stack is used for creating the stack frames,
  73. otherwise the frames are taken from @var{obj} (which must be
  74. a continuation or a frame object).
  75. @var{arg} @dots{} can be any combination of integer, procedure, address
  76. range, and prompt tag values.
  77. These values specify various ways of cutting away uninteresting stack
  78. frames from the top and bottom of the stack that @code{make-stack}
  79. returns. They come in pairs like this: @code{(@var{inner_cut_1}
  80. @var{outer_cut_1} @var{inner_cut_2} @var{outer_cut_2} @dots{})}.
  81. Each @var{inner_cut_i} can be an integer, a procedure, an address range,
  82. or a prompt tag. An integer means to cut away exactly that number of
  83. frames. A procedure means to cut away all frames up to but excluding
  84. the frame whose procedure matches the specified one. An address range
  85. is a pair of integers indicating the low and high addresses of a
  86. procedure's code, and is the same as cutting away to a procedure (though
  87. with less work). Anything else is interpreted as a prompt tag which
  88. cuts away all frames that are inside a prompt with the given tag.
  89. Each @var{outer_cut_i} can likewise be an integer, a procedure, an
  90. address range, or a prompt tag. An integer means to cut away that
  91. number of frames. A procedure means to cut away frames down to but
  92. excluding the frame whose procedure matches the specified one. An
  93. address range is the same, but with the procedure's code specified as an
  94. address range. Anything else is taken to be a prompt tag, which cuts
  95. away all frames that are outside a prompt with the given tag.
  96. If the @var{outer_cut_i} of the last pair is missing, it is taken as 0.
  97. @end deffn
  98. @deffn {Scheme Syntax} start-stack id exp
  99. Evaluate @var{exp} on a new calling stack with identity @var{id}. If
  100. @var{exp} is interrupted during evaluation, backtraces will not display
  101. frames farther back than @var{exp}'s top-level form. This macro is a
  102. way of artificially limiting backtraces and stack procedures, largely as
  103. a convenience to the user.
  104. @end deffn
  105. @node Stacks
  106. @subsubsection Stacks
  107. @deffn {Scheme Procedure} stack? obj
  108. @deffnx {C Function} scm_stack_p (obj)
  109. Return @code{#t} if @var{obj} is a calling stack.
  110. @end deffn
  111. @deffn {Scheme Procedure} stack-id stack
  112. @deffnx {C Function} scm_stack_id (stack)
  113. Return the identifier given to @var{stack} by @code{start-stack}.
  114. @end deffn
  115. @deffn {Scheme Procedure} stack-length stack
  116. @deffnx {C Function} scm_stack_length (stack)
  117. Return the length of @var{stack}.
  118. @end deffn
  119. @deffn {Scheme Procedure} stack-ref stack index
  120. @deffnx {C Function} scm_stack_ref (stack, index)
  121. Return the @var{index}'th frame from @var{stack}.
  122. @end deffn
  123. @deffn {Scheme Procedure} display-backtrace stack port [first [depth [highlights]]]
  124. @deffnx {C Function} scm_display_backtrace_with_highlights (stack, port, first, depth, highlights)
  125. @deffnx {C Function} scm_display_backtrace (stack, port, first, depth)
  126. Display a backtrace to the output port @var{port}. @var{stack}
  127. is the stack to take the backtrace from, @var{first} specifies
  128. where in the stack to start and @var{depth} how many frames
  129. to display. @var{first} and @var{depth} can be @code{#f},
  130. which means that default values will be used.
  131. If @var{highlights} is given it should be a list; the elements
  132. of this list will be highlighted wherever they appear in the
  133. backtrace.
  134. @end deffn
  135. @node Frames
  136. @subsubsection Frames
  137. @deffn {Scheme Procedure} frame? obj
  138. @deffnx {C Function} scm_frame_p (obj)
  139. Return @code{#t} if @var{obj} is a stack frame.
  140. @end deffn
  141. @deffn {Scheme Procedure} frame-previous frame
  142. @deffnx {C Function} scm_frame_previous (frame)
  143. Return the previous frame of @var{frame}, or @code{#f} if
  144. @var{frame} is the first frame in its stack.
  145. @end deffn
  146. @deffn {Scheme Procedure} frame-procedure-name frame
  147. @deffnx {C Function} scm_frame_procedure_name (frame)
  148. Return the name of the procedure being applied in @var{frame}, as a
  149. symbol, or @code{#f} if the procedure has no name.
  150. @end deffn
  151. @deffn {Scheme Procedure} frame-arguments frame
  152. @deffnx {C Function} scm_frame_arguments (frame)
  153. Return the arguments of @var{frame}.
  154. @end deffn
  155. @deffn {Scheme Procedure} frame-address frame
  156. @deffnx {Scheme Procedure} frame-instruction-pointer frame
  157. @deffnx {Scheme Procedure} frame-stack-pointer frame
  158. Accessors for the three VM registers associated with this frame: the
  159. frame pointer (fp), instruction pointer (ip), and stack pointer (sp),
  160. respectively. @xref{VM Concepts}, for more information.
  161. @end deffn
  162. @deffn {Scheme Procedure} frame-dynamic-link frame
  163. @deffnx {Scheme Procedure} frame-return-address frame
  164. @deffnx {Scheme Procedure} frame-mv-return-address frame
  165. Accessors for the three saved VM registers in a frame: the previous
  166. frame pointer, the single-value return address, and the multiple-value
  167. return address. @xref{Stack Layout}, for more information.
  168. @end deffn
  169. @deffn {Scheme Procedure} frame-bindings frame
  170. Return a list of binding records indicating the local variables that are
  171. live in a frame.
  172. @end deffn
  173. @deffn {Scheme Procedure} frame-lookup-binding frame var
  174. Fetch the bindings in @var{frame}, and return the first one whose name
  175. is @var{var}, or @code{#f} otherwise.
  176. @end deffn
  177. @deffn {Scheme Procedure} binding-index binding
  178. @deffnx {Scheme Procedure} binding-name binding
  179. @deffnx {Scheme Procedure} binding-slot binding
  180. @deffnx {Scheme Procedure} binding-representation binding
  181. Accessors for the various fields in a binding. The implicit ``callee''
  182. argument is index 0, the first argument is index 1, and so on to the end
  183. of the arguments. After that are temporary variables. Note that if a
  184. variable is dead, it might not be available.
  185. @end deffn
  186. @deffn {Scheme Procedure} binding-ref binding
  187. @deffnx {Scheme Procedure} binding-set! binding val
  188. Accessors for the values of local variables in a frame.
  189. @end deffn
  190. @deffn {Scheme Procedure} display-application frame [port [indent]]
  191. @deffnx {C Function} scm_display_application (frame, port, indent)
  192. Display a procedure application @var{frame} to the output port
  193. @var{port}. @var{indent} specifies the indentation of the
  194. output.
  195. @end deffn
  196. Additionally, the @code{(system vm frame)} module defines a number of
  197. higher-level introspective procedures, for example to retrieve the names
  198. of local variables, and the source location to correspond to a
  199. frame. See its source code for more details.
  200. @node Source Properties
  201. @subsection Source Properties
  202. How best to associate source locations with datums parsed from a port?
  203. The right way to do this is to annotate all components of each parsed
  204. datum. @xref{Annotated Scheme Read}, for more on @code{read-syntax}.
  205. @cindex source properties
  206. Guile only switched to use @code{read-syntax} in 2021, however. For the
  207. previous thirty years, it used a mechanism known as @dfn{source
  208. properties}.
  209. As Guile reads in Scheme code from file or from standard input, it can
  210. record the file name, line number and column number where each
  211. expression begins in a side table.
  212. The way that this side table associates datums with source properties
  213. has a limitation, however: Guile can only associate source properties
  214. with freshly allocated objects. This notably excludes individual
  215. symbols, keywords, characters, booleans, or small integers. This
  216. limitation finally motivated the switch to @code{read-syntax}.
  217. @deffn {Scheme Procedure} supports-source-properties? obj
  218. @deffnx {C Function} scm_supports_source_properties_p (obj)
  219. Return #t if source properties can be associated with @var{obj},
  220. otherwise return #f.
  221. @end deffn
  222. The recording of source properties is controlled by the read option
  223. named ``positions'' (@pxref{Scheme Read}). This option is switched
  224. @emph{on} by default. Now that @code{read-syntax} is available,
  225. however, Guile may change the default for this flag to off in the
  226. future.
  227. The following procedures can be used to access and set the source
  228. properties of read expressions.
  229. @deffn {Scheme Procedure} set-source-properties! obj alist
  230. @deffnx {C Function} scm_set_source_properties_x (obj, alist)
  231. Install the association list @var{alist} as the source property
  232. list for @var{obj}.
  233. @end deffn
  234. @deffn {Scheme Procedure} set-source-property! obj key datum
  235. @deffnx {C Function} scm_set_source_property_x (obj, key, datum)
  236. Set the source property of object @var{obj}, which is specified by
  237. @var{key} to @var{datum}. Normally, the key will be a symbol.
  238. @end deffn
  239. @deffn {Scheme Procedure} source-properties obj
  240. @deffnx {C Function} scm_source_properties (obj)
  241. Return the source property association list of @var{obj}.
  242. @end deffn
  243. @deffn {Scheme Procedure} source-property obj key
  244. @deffnx {C Function} scm_source_property (obj, key)
  245. Return the property specified by @var{key} from @var{obj}'s source
  246. properties.
  247. @end deffn
  248. If the @code{positions} reader option is enabled, supported expressions
  249. will have values set for the @code{filename}, @code{line} and
  250. @code{column} properties.
  251. Source properties are also associated with syntax objects. Procedural
  252. macros can get at the source location of their input using the
  253. @code{syntax-source} accessor. @xref{Syntax Transformer Helpers}, for
  254. more.
  255. Guile also defines a couple of convenience macros built on
  256. @code{syntax-source}:
  257. @deffn {Scheme Syntax} current-source-location
  258. Expands to the source properties corresponding to the location of the
  259. @code{(current-source-location)} form.
  260. @end deffn
  261. @deffn {Scheme Syntax} current-filename
  262. Expands to the current filename: the filename that the
  263. @code{(current-filename)} form appears in. Expands to @code{#f} if this
  264. information is unavailable.
  265. @end deffn
  266. If you're stuck with defmacros (@pxref{Defmacros}), and want to preserve
  267. source information, the following helper function might be useful to
  268. you:
  269. @deffn {Scheme Procedure} cons-source xorig x y
  270. @deffnx {C Function} scm_cons_source (xorig, x, y)
  271. Create and return a new pair whose car and cdr are @var{x} and @var{y}.
  272. Any source properties associated with @var{xorig} are also associated
  273. with the new pair.
  274. @end deffn
  275. @node Programmatic Error Handling
  276. @subsection Programmatic Error Handling
  277. For better or for worse, all programs have bugs, and dealing with bugs
  278. is part of programming. This section deals with that class of bugs that
  279. causes an exception to be raised -- from your own code, from within a
  280. library, or from Guile itself.
  281. @menu
  282. * Catching Exceptions:: Handling errors after the stack is unwound.
  283. * Pre-Unwind Debugging:: Debugging before the exception is thrown.
  284. * Standard Error Handling:: Call-with-error-handling.
  285. * Stack Overflow:: Detecting and handling runaway recursion.
  286. * Debug Options:: A historical interface to debugging.
  287. @end menu
  288. @node Catching Exceptions
  289. @subsubsection Catching Exceptions
  290. A common requirement is to be able to show as much useful context as
  291. possible when a Scheme program hits an error. The most immediate
  292. information about an error is the kind of error that it is -- such as
  293. ``division by zero'' -- and any parameters that the code which signaled
  294. the error chose explicitly to provide. This information originates with
  295. the @code{error} or @code{raise-exception} call (or their C code
  296. equivalents, if the error is detected by C code) that signals the error,
  297. and is passed automatically to the handler procedure of the innermost
  298. applicable exception handler.
  299. Therefore, to catch errors that occur within a chunk of Scheme code, and
  300. to intercept basic information about those errors, you need to execute
  301. that code inside the dynamic context of a @code{with-exception-handler},
  302. or the equivalent in C.
  303. For example, to print out a message and return #f when an error occurs,
  304. you might use:
  305. @smalllisp
  306. (define (catch-all thunk)
  307. (with-exception-handler
  308. (lambda (exn)
  309. (format (current-error-port)
  310. "Uncaught exception: ~s\n" exn)
  311. #f)
  312. thunk
  313. #:unwind? #t))
  314. (catch-all
  315. (lambda () (error "Not a vegetable: tomato")))
  316. @print{} Uncaught exception: #<&exception-with-kind-and-args ...>
  317. @result{} #f
  318. @end smalllisp
  319. @xref{Exceptions}, for full details.
  320. @node Pre-Unwind Debugging
  321. @subsubsection Pre-Unwind Debugging
  322. Sometimes when something goes wrong, what you want is not just a
  323. representation of the exceptional situation, but the context that
  324. brought about that situation. The example in the previous section
  325. passed @code{#:unwind #t} to @code{with-exception-handler}, indicating
  326. that @code{raise-exception} should unwind the stack before invoking the
  327. exception handler. However if you don't take this approach and instead
  328. let the exception handler be invoked in the context of the
  329. @code{raise-exception}, you can print a backtrace, launch a recursive
  330. debugger, or take other ``pre-unwind'' actions.
  331. The most basic idea would be to simply print a backtrace:
  332. @example
  333. (define (call-with-backtrace thunk)
  334. (with-exception-handler
  335. (lambda (exn)
  336. (backtrace)
  337. (raise-exception exn))
  338. thunk))
  339. @end example
  340. Here we use the built-in @code{backtrace} procedure to print the
  341. backtrace.
  342. @deffn {Scheme Procedure} backtrace [highlights]
  343. @deffnx {C Function} scm_backtrace_with_highlights (highlights)
  344. @deffnx {C Function} scm_backtrace ()
  345. Display a backtrace of the current stack to the current output port. If
  346. @var{highlights} is given it should be a list; the elements of this list
  347. will be highlighted wherever they appear in the backtrace.
  348. @end deffn
  349. By re-raising the exception, @code{call-with-backtrace} doesn't actually
  350. handle the error. We could define a version that instead aborts the
  351. computation:
  352. @example
  353. (use-modules (ice-9 control))
  354. (define (call-with-backtrace thunk)
  355. (let/ec cancel
  356. (with-exception-handler
  357. (lambda (exn)
  358. (backtrace)
  359. (cancel #f))
  360. thunk)))
  361. @end example
  362. In this second example, we use an escape continuation to abort the
  363. computation after printing the backtrace, returning @code{#f} instead.
  364. It could be that you want to only print a limited backtrace. In that
  365. case, use @code{start-stack}:
  366. @example
  367. (use-modules (ice-9 control))
  368. (define (call-with-backtrace thunk)
  369. (let/ec cancel
  370. (start-stack 'stack-with-backtrace
  371. (with-exception-handler
  372. (lambda (exn)
  373. (backtrace)
  374. (cancel #f))
  375. thunk))))
  376. @end example
  377. There are also more powerful, programmatic ways to walk the stack using
  378. @code{make-stack} and friends; see the API described in @ref{Stacks} and
  379. @ref{Frames}.
  380. @node Standard Error Handling
  381. @subsubsection call-with-error-handling
  382. The Guile REPL code (in @file{system/repl/repl.scm} and related files)
  383. uses a @code{catch} with a pre-unwind handler to capture the stack when
  384. an error occurs in an expression that was typed into the REPL, and debug
  385. that stack interactively in the context of the error.
  386. These procedures are available for use by user programs, in the
  387. @code{(system repl error-handling)} module.
  388. @lisp
  389. (use-modules (system repl error-handling))
  390. @end lisp
  391. @deffn {Scheme Procedure} call-with-error-handling thunk @
  392. [#:on-error on-error='debug] [#:post-error post-error='catch] @
  393. [#:pass-keys pass-keys='(quit)] @
  394. [#:report-keys report-keys='(stack-overflow)] @
  395. [#:trap-handler trap-handler='debug]
  396. Call a thunk in a context in which errors are handled.
  397. Note that this function was written when @code{throw}/@code{catch} were
  398. the fundamental exception handling primitives in Guile, and so exposes
  399. some aspects of that interface (notably in the form of the procedural
  400. handlers). Guile will probably replace this function with a
  401. @code{call-with-standard-exception-handling} in the future.
  402. There are five keyword arguments:
  403. @table @var
  404. @item on-error
  405. Specifies what to do before the stack is unwound.
  406. Valid options are @code{debug} (the default), which will enter a
  407. debugger; @code{pass}, in which case nothing is done, and the exception
  408. is rethrown; or a procedure, which will be the pre-unwind handler.
  409. @item post-error
  410. Specifies what to do after the stack is unwound.
  411. Valid options are @code{catch} (the default), which will silently catch
  412. errors, returning the unspecified value; @code{report}, which prints out
  413. a description of the error (via @code{display-error}), and then returns
  414. the unspecified value; or a procedure, which will be the catch handler.
  415. @item trap-handler
  416. Specifies a trap handler: what to do when a breakpoint is hit.
  417. Valid options are @code{debug}, which will enter the debugger;
  418. @code{pass}, which does nothing; or @code{disabled}, which disables
  419. traps entirely. @xref{Traps}, for more information.
  420. @item pass-keys
  421. A set of keys to ignore, as a list.
  422. @item report-keys
  423. A set of keys to always report even if the post-error handler is
  424. @code{catch}, as a list.
  425. @end table
  426. @end deffn
  427. @node Stack Overflow
  428. @subsubsection Stack Overflow
  429. @cindex overflow, stack
  430. @cindex stack overflow
  431. Every time a Scheme program makes a call that is not in tail position,
  432. it pushes a new frame onto the stack. Returning a value from a function
  433. pops the top frame off the stack. Stack frames take up memory, and as
  434. nobody has an infinite amount of memory, deep recursion could cause
  435. Guile to run out of memory. Running out of stack memory is called
  436. @dfn{stack overflow}.
  437. @subsubheading Stack Limits
  438. Most languages have a terrible stack overflow story. For example, in C,
  439. if you use too much stack, your program will exhibit ``undefined
  440. behavior'', which if you are lucky means that it will crash. It's
  441. especially bad in C, as you neither know ahead of time how much stack
  442. your functions use, nor the stack limit imposed by the user's system,
  443. and the stack limit is often quite small relative to the total memory
  444. size.
  445. Managed languages like Python have a better error story, as they are
  446. defined to raise an exception on stack overflow -- but like C, Python
  447. and most dynamic languages still have a fixed stack size limit that is
  448. usually much smaller than the heap.
  449. Arbitrary stack limits would have an unfortunate effect on Guile
  450. programs. For example, the following implementation of the inner loop
  451. of @code{map} is clean and elegant:
  452. @example
  453. (define (map f l)
  454. (if (pair? l)
  455. (cons (f (car l))
  456. (map f (cdr l)))
  457. '()))
  458. @end example
  459. However, if there were a stack limit, that would limit the size of lists
  460. that can be processed with this @code{map}. Eventually, you would have
  461. to rewrite it to use iteration with an accumulator:
  462. @example
  463. (define (map f l)
  464. (let lp ((l l) (out '()))
  465. (if (pair? l)
  466. (lp (cdr l) (cons (f (car l)) out))
  467. (reverse out))))
  468. @end example
  469. This second version is sadly not as clear, and it also allocates more
  470. heap memory (once to build the list in reverse, and then again to
  471. reverse the list). You would be tempted to use the destructive
  472. @code{reverse!} to save memory and time, but then your code would not be
  473. continuation-safe -- if @var{f} returned again after the map had
  474. finished, it would see an @var{out} list that had already been
  475. reversed. The recursive @code{map} has none of these problems.
  476. Guile has no stack limit for Scheme code. When a thread makes its first
  477. Guile call, a small stack is allocated -- just one page of memory.
  478. Whenever that memory limit would be reached, Guile arranges to grow the
  479. stack by a factor of two. When garbage collection happens, Guile
  480. arranges to return the unused part of the stack to the operating system,
  481. but without causing the stack to shrink. In this way, the stack can
  482. grow to consume up to all memory available to the Guile process, and
  483. when the recursive computation eventually finishes, that stack memory is
  484. returned to the system.
  485. @subsubheading Exceptional Situations
  486. Of course, it's still possible to run out of stack memory. The most
  487. common cause of this is program bugs that cause unbounded recursion, as
  488. in:
  489. @example
  490. (define (faulty-map f l)
  491. (if (pair? l)
  492. (cons (f (car l)) (faulty-map f l))
  493. '()))
  494. @end example
  495. Did you spot the bug? The recursive call to @code{faulty-map} recursed
  496. on @var{l}, not @code{(cdr @var{l})}. Running this program would cause
  497. Guile to use up all memory in your system, and eventually Guile would
  498. fail to grow the stack. At that point you have a problem: Guile needs
  499. to raise an exception to unwind the stack and return memory to the
  500. system, but the user might have exception handlers in place
  501. (@pxref{Raising and Handling Exceptions}) that want to run before the
  502. stack is unwound, and we don't have any stack in which to run them.
  503. Therefore in this case, Guile raises an unwind-only exception that does
  504. not run pre-unwind handlers. Because this is such an odd case, Guile
  505. prints out a message on the console, in case the user was expecting to
  506. be able to get a backtrace from any pre-unwind handler.
  507. @subsubheading Runaway Recursion
  508. Still, this failure mode is not so nice. If you are running an
  509. environment in which you are interactively building a program while it
  510. is running, such as at a REPL, you might want to impose an artificial
  511. stack limit on the part of your program that you are building to detect
  512. accidental runaway recursion. For that purpose, there is
  513. @code{call-with-stack-overflow-handler}, from @code{(system vm vm)}.
  514. @example
  515. (use-module (system vm vm))
  516. @end example
  517. @deffn {Scheme Procedure} call-with-stack-overflow-handler limit thunk handler
  518. Call @var{thunk} in an environment in which the stack limit has been
  519. reduced to @var{limit} additional words. If the limit is reached,
  520. @var{handler} (a thunk) will be invoked in the dynamic environment of
  521. the error. For the extent of the call to @var{handler}, the stack limit
  522. and handler are restored to the values that were in place when
  523. @code{call-with-stack-overflow-handler} was called.
  524. Usually, @var{handler} should raise an exception or abort to an outer
  525. prompt. However if @var{handler} does return, it should return a number
  526. of additional words of stack space to allow to the inner environment.
  527. @end deffn
  528. A stack overflow handler may only ever ``credit'' the inner thunk with
  529. stack space that was available when the handler was instated. When
  530. Guile first starts, there is no stack limit in place, so the outer
  531. handler may allow the inner thunk an arbitrary amount of space, but any
  532. nested stack overflow handler will not be able to consume more than its
  533. limit.
  534. Unlike the unwind-only exception that is thrown if Guile is unable to
  535. grow its stack, any exception thrown by a stack overflow handler might
  536. invoke pre-unwind handlers. Indeed, the stack overflow handler is
  537. itself a pre-unwind handler of sorts. If the code imposing the stack
  538. limit wants to protect itself against malicious pre-unwind handlers from
  539. the inner thunk, it should abort to a prompt of its own making instead
  540. of throwing an exception that might be caught by the inner thunk.
  541. @subsubheading C Stack Usage
  542. It is also possible for Guile to run out of space on the C stack. If
  543. you call a primitive procedure which then calls a Scheme procedure in a
  544. loop, you will consume C stack space. Guile tries to detect excessive
  545. consumption of C stack space, throwing an error when you have hit 80% of
  546. the process' available stack (as allocated by the operating system), or
  547. 160 kilowords in the absence of a strict limit.
  548. For example, looping through @code{call-with-vm}, a primitive that calls
  549. a thunk, gives us the following:
  550. @lisp
  551. scheme@@(guile-user)> (use-modules (system vm vm))
  552. scheme@@(guile-user)> (let lp () (call-with-vm lp))
  553. ERROR: Stack overflow
  554. @end lisp
  555. Unfortunately, that's all the information we get. Overrunning the C
  556. stack will throw an unwind-only exception, because it's not safe to
  557. do very much when you are close to the C stack limit.
  558. If you get an error like this, you can either try rewriting your code to
  559. use less stack space, or increase the maximum stack size. To increase
  560. the maximum stack size, use @code{debug-set!}, for example:
  561. @lisp
  562. (debug-set! stack 200000)
  563. @end lisp
  564. The next section describes @code{debug-set!} more thoroughly. Of course
  565. the best thing is to have your code operate without so much resource
  566. consumption by avoiding loops through C trampolines.
  567. @node Debug Options
  568. @subsubsection Debug options
  569. The behavior of the @code{backtrace} procedure and of the default error
  570. handler can be parameterized via the debug options.
  571. @cindex options - debug
  572. @cindex debug options
  573. @deffn {Scheme Procedure} debug-options [setting]
  574. Display the current settings of the debug options. If @var{setting} is
  575. omitted, only a short form of the current read options is printed.
  576. Otherwise if @var{setting} is the symbol @code{help}, a complete options
  577. description is displayed.
  578. @end deffn
  579. The set of available options, and their default values, may be had by
  580. invoking @code{debug-options} at the prompt.
  581. @smallexample
  582. scheme@@(guile-user)>
  583. backwards no Display backtrace in anti-chronological order.
  584. width 79 Maximal width of backtrace.
  585. depth 20 Maximal length of printed backtrace.
  586. backtrace yes Show backtrace on error.
  587. stack 1048576 Stack size limit (measured in words;
  588. 0 = no check).
  589. show-file-name #t Show file names and line numbers in backtraces
  590. when not `#f'. A value of `base' displays only
  591. base names, while `#t' displays full names.
  592. warn-deprecated no Warn when deprecated features are used.
  593. @end smallexample
  594. The boolean options may be toggled with @code{debug-enable} and
  595. @code{debug-disable}. The non-boolean options must be set using
  596. @code{debug-set!}.
  597. @deffn {Scheme Procedure} debug-enable option-name
  598. @deffnx {Scheme Procedure} debug-disable option-name
  599. @deffnx {Scheme Syntax} debug-set! option-name value
  600. Modify the debug options. @code{debug-enable} should be used with boolean
  601. options and switches them on, @code{debug-disable} switches them off.
  602. @code{debug-set!} can be used to set an option to a specific value. Due
  603. to historical oddities, it is a macro that expects an unquoted option
  604. name.
  605. @end deffn
  606. @node Traps
  607. @subsection Traps
  608. @cindex Traps
  609. @cindex VM hooks
  610. @cindex Breakpoints
  611. @cindex Trace
  612. @cindex Tracing
  613. @cindex Code coverage
  614. @cindex Profiling
  615. Guile's virtual machine can be configured to call out at key points to
  616. arbitrary user-specified procedures.
  617. In principle, these @dfn{hooks} allow Scheme code to implement any model
  618. it chooses for examining the evaluation stack as program execution
  619. proceeds, and for suspending execution to be resumed later.
  620. VM hooks are very low-level, though, and so Guile also has a library of
  621. higher-level @dfn{traps} on top of the VM hooks. A trap is an execution
  622. condition that, when fulfilled, will fire a handler. For example, Guile
  623. defines a trap that fires when control reaches a certain source
  624. location.
  625. Finally, Guile also defines a third level of abstractions: per-thread
  626. @dfn{trap states}. A trap state exists to give names to traps, and to
  627. hold on to the set of traps so that they can be enabled, disabled, or
  628. removed. The trap state infrastructure defines the most useful
  629. abstractions for most cases. For example, Guile's REPL uses trap state
  630. functions to set breakpoints and tracepoints.
  631. The following subsections describe all this in detail, for both the
  632. user wanting to use traps, and the developer interested in
  633. understanding how the interface hangs together.
  634. @menu
  635. * VM Hooks:: Modifying Guile's virtual machine.
  636. * Trap Interface:: Traps are on or off.
  637. * Low-Level Traps:: The various kinds of low-level traps.
  638. * Tracing Traps:: Traps to trace procedure calls and returns.
  639. * Trap States:: One state (per thread) to bind them.
  640. * High-Level Traps:: The highest-level trap interface. Use this.
  641. @end menu
  642. @node VM Hooks
  643. @subsubsection VM Hooks
  644. Everything that runs in Guile runs on its virtual machine, a C program
  645. that defines a number of operations that Scheme programs can
  646. perform.
  647. Note that there are multiple VM ``engines'' for Guile. Only some of them
  648. have support for hooks compiled in. Normally the deal is that you get
  649. hooks if you are running interactively, and otherwise they are disabled,
  650. as they do have some overhead (about 10 or 20 percent).
  651. To ensure that you are running with hooks, pass @code{--debug} to Guile
  652. when running your program, or otherwise use the @code{call-with-vm} and
  653. @code{set-vm-engine!} procedures to ensure that you are running in a VM
  654. with the @code{debug} engine.
  655. To digress, Guile's VM has 4 different hooks that can be fired at
  656. different times. For implementation reasons, these hooks are not
  657. actually implemented with first-class Scheme hooks (@pxref{Hooks}); they
  658. are managed using an ad-hoc interface.
  659. VM hooks are called with one argument: the current frame.
  660. @xref{Frames}. Since these hooks may be fired very frequently, Guile
  661. does a terrible thing: it allocates the frames on the C stack instead of
  662. the garbage-collected heap.
  663. The upshot here is that the frames are only valid within the dynamic
  664. extent of the call to the hook. If a hook procedure keeps a reference to
  665. the frame outside the extent of the hook, bad things will happen.
  666. The interface to hooks is provided by the @code{(system vm vm)} module:
  667. @example
  668. (use-modules (system vm vm))
  669. @end example
  670. @noindent
  671. All of these functions implicitly act on the VM for the current thread
  672. only.
  673. @deffn {Scheme Procedure} vm-add-next-hook! f
  674. Arrange to call @var{f} when before an instruction is retired (and
  675. executed).
  676. @end deffn
  677. @deffn {Scheme Procedure} vm-add-apply-hook! f
  678. Arrange to call @var{f} whenever a procedure is applied. The frame
  679. locals will be the callee, followed by the arguments to the call.
  680. Note that procedure application is somewhat orthogonal to continuation
  681. pushes and pops. To know whether a call is a tail call or not, with
  682. respect to the frame previously in place, check the value of the frame
  683. pointer compared the previous frame pointer.
  684. @end deffn
  685. @deffn {Scheme Procedure} vm-add-return-hook! f
  686. Arrange to call @var{f} before returning from a frame. The values in
  687. the frame will be the frame's return values.
  688. Note that it's possible to return from an ``inner'' frame: one that was
  689. not immediately proceeded by a call with that frame pointer. In that
  690. case, it corresponds to a non-local control flow jump, either because of
  691. applying a composable continuation or because of restoring a saved
  692. undelimited continuation.
  693. @end deffn
  694. @deffn {Scheme Procedure} vm-add-abort-hook!
  695. Arrange to call @var{f} after aborting to a prompt. @xref{Prompts}.
  696. Unfortunately, the values passed to the prompt handler are not easily
  697. available to @var{f}.
  698. @end deffn
  699. @deffn {Scheme Procedure} vm-remove-next-hook! f
  700. @deffnx {Scheme Procedure} vm-remove-apply-hook! f
  701. @deffnx {Scheme Procedure} vm-remove-return-hook! f
  702. @deffnx {Scheme Procedure} vm-remove-abort-hook! f
  703. Remove @var{f} from the corresponding VM hook for the current thread.
  704. @end deffn
  705. @cindex VM trace level
  706. These hooks do impose a performance penalty, if they are on. Obviously,
  707. the @code{vm-next-hook} has quite an impact, performance-wise. Therefore
  708. Guile exposes a single, heavy-handed knob to turn hooks on or off, the
  709. @dfn{VM trace level}. If the trace level is positive, hooks run;
  710. otherwise they don't.
  711. For convenience, when the VM fires a hook, it does so with the trap
  712. level temporarily set to 0. That way the hooks don't fire while you're
  713. handling a hook. The trace level is restored to whatever it was once the hook
  714. procedure finishes.
  715. @deffn {Scheme Procedure} vm-trace-level
  716. Retrieve the ``trace level'' of the VM. If positive, the trace hooks
  717. associated with @var{vm} will be run. The initial trace level is 0.
  718. @end deffn
  719. @deffn {Scheme Procedure} set-vm-trace-level! level
  720. Set the ``trace level'' of the VM.
  721. @end deffn
  722. @xref{A Virtual Machine for Guile}, for more information on Guile's
  723. virtual machine.
  724. @node Trap Interface
  725. @subsubsection Trap Interface
  726. The capabilities provided by hooks are great, but hooks alone rarely
  727. correspond to what users want to do.
  728. For example, if a user wants to break when and if control reaches a
  729. certain source location, how do you do it? If you install a ``next''
  730. hook, you get unacceptable overhead for the execution of the entire
  731. program. It would be possible to install an ``apply'' hook, then if the
  732. procedure encompasses those source locations, install a ``next'' hook,
  733. but already you're talking about one concept that might be implemented
  734. by a varying number of lower-level concepts.
  735. It's best to be clear about things and define one abstraction for all
  736. such conditions: the @dfn{trap}.
  737. Considering the myriad capabilities offered by the hooks though, there
  738. is only a minimum of functionality shared by all traps. Guile's current
  739. take is to reduce this to the absolute minimum, and have the only
  740. standard interface of a trap be ``turn yourself on'' or ``turn yourself
  741. off''.
  742. This interface sounds a bit strange, but it is useful to procedurally
  743. compose higher-level traps from lower-level building blocks. For
  744. example, Guile defines a trap that calls one handler when control enters
  745. a procedure, and another when control leaves the procedure. Given that
  746. trap, one can define a trap that adds to the next-hook only when within
  747. a given procedure. Building further, one can define a trap that fires
  748. when control reaches particular instructions within a procedure.
  749. Or of course you can stop at any of these intermediate levels. For
  750. example, one might only be interested in calls to a given procedure. But
  751. the point is that a simple enable/disable interface is all the
  752. commonality that exists between the various kinds of traps, and
  753. furthermore that such an interface serves to allow ``higher-level''
  754. traps to be composed from more primitive ones.
  755. Specifically, a trap, in Guile, is a procedure. When a trap is created,
  756. by convention the trap is enabled; therefore, the procedure that is the
  757. trap will, when called, disable the trap, and return a procedure that
  758. will enable the trap, and so on.
  759. Trap procedures take one optional argument: the current frame. (A trap
  760. may want to add to different sets of hooks depending on the frame that
  761. is current at enable-time.)
  762. If this all sounds very complicated, it's because it is. Some of it is
  763. essential, but probably most of it is not. The advantage of using this
  764. minimal interface is that composability is more lexically apparent than
  765. when, for example, using a stateful interface based on GOOPS. But
  766. perhaps this reflects the cognitive limitations of the programmer who
  767. made the current interface more than anything else.
  768. @node Low-Level Traps
  769. @subsubsection Low-Level Traps
  770. To summarize the last sections, traps are enabled or disabled, and when
  771. they are enabled, they add to various VM hooks.
  772. Note, however, that @emph{traps do not increase the VM trace level}. So
  773. if you create a trap, it will be enabled, but unless something else
  774. increases the VM's trace level (@pxref{VM Hooks}), the trap will not
  775. fire. It turns out that getting the VM trace level right is tricky
  776. without a global view of what traps are enabled. @xref{Trap States},
  777. for Guile's answer to this problem.
  778. Traps are created by calling procedures. Most of these procedures share
  779. a set of common keyword arguments, so rather than document them
  780. separately, we discuss them all together here:
  781. @table @code
  782. @item #:vm
  783. The VM to instrument. Defaults to the current thread's VM.
  784. @item #:current-frame
  785. For traps that enable more hooks depending on their dynamic context,
  786. this argument gives the current frame that the trap is running in.
  787. Defaults to @code{#f}.
  788. @end table
  789. To have access to these procedures, you'll need to have imported the
  790. @code{(system vm traps)} module:
  791. @lisp
  792. (use-modules (system vm traps))
  793. @end lisp
  794. @deffn {Scheme Procedure} trap-at-procedure-call proc handler @
  795. [#:vm]
  796. A trap that calls @var{handler} when @var{proc} is applied.
  797. @end deffn
  798. @deffn {Scheme Procedure} trap-in-procedure proc @
  799. enter-handler exit-handler [#:current-frame] [#:vm]
  800. A trap that calls @var{enter-handler} when control enters @var{proc},
  801. and @var{exit-handler} when control leaves @var{proc}.
  802. Control can enter a procedure via:
  803. @itemize
  804. @item
  805. A procedure call.
  806. @item
  807. A return to a procedure's frame on the stack.
  808. @item
  809. A continuation returning directly to an application of this procedure.
  810. @end itemize
  811. Control can leave a procedure via:
  812. @itemize
  813. @item
  814. A normal return from the procedure.
  815. @item
  816. An application of another procedure.
  817. @item
  818. An invocation of a continuation.
  819. @item
  820. An abort.
  821. @end itemize
  822. @end deffn
  823. @deffn {Scheme Procedure} trap-instructions-in-procedure proc @
  824. next-handler exit-handler [#:current-frame] [#:vm]
  825. A trap that calls @var{next-handler} for every instruction executed in
  826. @var{proc}, and @var{exit-handler} when execution leaves @var{proc}.
  827. @end deffn
  828. @deffn {Scheme Procedure} trap-at-procedure-ip-in-range proc range @
  829. handler [#:current-frame] [#:vm]
  830. A trap that calls @var{handler} when execution enters a range of
  831. instructions in @var{proc}. @var{range} is a simple of pairs,
  832. @code{((@var{start} . @var{end}) ...)}. The @var{start} addresses are
  833. inclusive, and @var{end} addresses are exclusive.
  834. @end deffn
  835. @deffn {Scheme Procedure} trap-at-source-location file user-line handler @
  836. [#:current-frame] [#:vm]
  837. A trap that fires when control reaches a given source location. The
  838. @var{user-line} parameter is one-indexed, as a user counts lines,
  839. instead of zero-indexed, as Guile counts lines.
  840. @end deffn
  841. @deffn {Scheme Procedure} trap-frame-finish frame @
  842. return-handler abort-handler [#:vm]
  843. A trap that fires when control leaves the given frame. @var{frame}
  844. should be a live frame in the current continuation. @var{return-handler}
  845. will be called on a normal return, and @var{abort-handler} on a nonlocal
  846. exit.
  847. @end deffn
  848. @deffn {Scheme Procedure} trap-in-dynamic-extent proc @
  849. enter-handler return-handler abort-handler [#:vm]
  850. A more traditional dynamic-wind trap, which fires @var{enter-handler}
  851. when control enters @var{proc}, @var{return-handler} on a normal return,
  852. and @var{abort-handler} on a nonlocal exit.
  853. Note that rewinds are not handled, so there is no rewind handler.
  854. @end deffn
  855. @deffn {Scheme Procedure} trap-calls-in-dynamic-extent proc @
  856. apply-handler return-handler [#:current-frame] [#:vm]
  857. A trap that calls @var{apply-handler} every time a procedure is applied,
  858. and @var{return-handler} for returns, but only during the dynamic extent
  859. of an application of @var{proc}.
  860. @end deffn
  861. @deffn {Scheme Procedure} trap-instructions-in-dynamic-extent proc @
  862. next-handler [#:current-frame] [#:vm]
  863. A trap that calls @var{next-handler} for all retired instructions within
  864. the dynamic extent of a call to @var{proc}.
  865. @end deffn
  866. @deffn {Scheme Procedure} trap-calls-to-procedure proc @
  867. apply-handler return-handler [#:vm]
  868. A trap that calls @var{apply-handler} whenever @var{proc} is applied,
  869. and @var{return-handler} when it returns, but with an additional
  870. argument, the call depth.
  871. That is to say, the handlers will get two arguments: the frame in
  872. question, and the call depth (a non-negative integer).
  873. @end deffn
  874. @deffn {Scheme Procedure} trap-matching-instructions frame-pred handler [#:vm]
  875. A trap that calls @var{frame-pred} at every instruction, and if
  876. @var{frame-pred} returns a true value, calls @var{handler} on the
  877. frame.
  878. @end deffn
  879. @node Tracing Traps
  880. @subsubsection Tracing Traps
  881. The @code{(system vm trace)} module defines a number of traps for
  882. tracing of procedure applications. When a procedure is @dfn{traced}, it
  883. means that every call to that procedure is reported to the user during a
  884. program run. The idea is that you can mark a collection of procedures
  885. for tracing, and Guile will subsequently print out a line of the form
  886. @lisp
  887. | | (@var{procedure} @var{args} @dots{})
  888. @end lisp
  889. whenever a marked procedure is about to be applied to its arguments.
  890. This can help a programmer determine whether a function is being called
  891. at the wrong time or with the wrong set of arguments.
  892. In addition, the indentation of the output is useful for demonstrating
  893. how the traced applications are or are not tail recursive with respect
  894. to each other. Thus, a trace of a non-tail recursive factorial
  895. implementation looks like this:
  896. @lisp
  897. scheme@@(guile-user)> (define (fact1 n)
  898. (if (zero? n) 1
  899. (* n (fact1 (1- n)))))
  900. scheme@@(guile-user)> ,trace (fact1 4)
  901. trace: (fact1 4)
  902. trace: | (fact1 3)
  903. trace: | | (fact1 2)
  904. trace: | | | (fact1 1)
  905. trace: | | | | (fact1 0)
  906. trace: | | | | 1
  907. trace: | | | 1
  908. trace: | | 2
  909. trace: | 6
  910. trace: 24
  911. @end lisp
  912. While a typical tail recursive implementation would look more like this:
  913. @lisp
  914. scheme@@(guile-user)> (define (facti acc n)
  915. (if (zero? n) acc
  916. (facti (* n acc) (1- n))))
  917. scheme@@(guile-user)> (define (fact2 n) (facti 1 n))
  918. scheme@@(guile-user)> ,trace (fact2 4)
  919. trace: (fact2 4)
  920. trace: (facti 1 4)
  921. trace: (facti 4 3)
  922. trace: (facti 12 2)
  923. trace: (facti 24 1)
  924. trace: (facti 24 0)
  925. trace: 24
  926. @end lisp
  927. The low-level traps below (@pxref{Low-Level Traps}) share some common
  928. options:
  929. @table @code
  930. @item #:width
  931. The maximum width of trace output. Trace printouts will try not to
  932. exceed this column, but for highly nested procedure calls, it may be
  933. unavoidable. Defaults to 80.
  934. @item #:vm
  935. The VM on which to add the traps. Defaults to the current thread's VM.
  936. @item #:prefix
  937. A string to print out before each trace line. As seen above in the
  938. examples, defaults to @code{"trace: "}.
  939. @end table
  940. To have access to these procedures, you'll need to have imported the
  941. @code{(system vm trace)} module:
  942. @lisp
  943. (use-modules (system vm trace))
  944. @end lisp
  945. @deffn {Scheme Procedure} trace-calls-to-procedure proc @
  946. [#:width] [#:vm] [#:prefix]
  947. Print a trace at applications of and returns from @var{proc}.
  948. @end deffn
  949. @deffn {Scheme Procedure} trace-calls-in-procedure proc @
  950. [#:width] [#:vm] [#:prefix]
  951. Print a trace at all applications and returns within the dynamic extent
  952. of calls to @var{proc}.
  953. @end deffn
  954. @deffn {Scheme Procedure} trace-instructions-in-procedure proc [#:width] [#:vm]
  955. Print a trace at all instructions executed in the dynamic extent of
  956. calls to @var{proc}.
  957. @end deffn
  958. In addition, Guile defines a procedure to call a thunk, tracing all
  959. procedure calls and returns within the thunk.
  960. @deffn {Scheme Procedure} call-with-trace thunk [#:calls?=#t] @
  961. [#:instructions?=#f] @
  962. [#:width=80]
  963. Call @var{thunk}, tracing all execution within its dynamic extent.
  964. If @var{calls?} is true, Guile will print a brief report at each
  965. procedure call and return, as given above.
  966. If @var{instructions?} is true, Guile will also print a message each
  967. time an instruction is executed. This is a lot of output, but it is
  968. sometimes useful when doing low-level optimization.
  969. Note that because this procedure manipulates the VM trace level
  970. directly, it doesn't compose well with traps at the REPL.
  971. @end deffn
  972. @xref{Profile Commands}, for more information on tracing at the REPL.
  973. @node Trap States
  974. @subsubsection Trap States
  975. When multiple traps are present in a system, we begin to have a
  976. bookkeeping problem. How are they named? How does one disable, enable,
  977. or delete them?
  978. Guile's answer to this is to keep an implicit per-thread @dfn{trap
  979. state}. The trap state object is not exposed to the user; rather, API
  980. that works on trap states fetches the current trap state from the
  981. dynamic environment.
  982. Traps are identified by integers. A trap can be enabled, disabled, or
  983. removed, and can have an associated user-visible name.
  984. These procedures have their own module:
  985. @lisp
  986. (use-modules (system vm trap-state))
  987. @end lisp
  988. @deffn {Scheme Procedure} add-trap! trap name
  989. Add a trap to the current trap state, associating the given @var{name}
  990. with it. Returns a fresh trap identifier (an integer).
  991. Note that usually the more specific functions detailed in
  992. @ref{High-Level Traps} are used in preference to this one.
  993. @end deffn
  994. @deffn {Scheme Procedure} list-traps
  995. List the current set of traps, both enabled and disabled. Returns a list
  996. of integers.
  997. @end deffn
  998. @deffn {Scheme Procedure} trap-name idx
  999. Returns the name associated with trap @var{idx}, or @code{#f} if there
  1000. is no such trap.
  1001. @end deffn
  1002. @deffn {Scheme Procedure} trap-enabled? idx
  1003. Returns @code{#t} if trap @var{idx} is present and enabled, or @code{#f}
  1004. otherwise.
  1005. @end deffn
  1006. @deffn {Scheme Procedure} enable-trap! idx
  1007. Enables trap @var{idx}.
  1008. @end deffn
  1009. @deffn {Scheme Procedure} disable-trap! idx
  1010. Disables trap @var{idx}.
  1011. @end deffn
  1012. @deffn {Scheme Procedure} delete-trap! idx
  1013. Removes trap @var{idx}, disabling it first, if necessary.
  1014. @end deffn
  1015. @node High-Level Traps
  1016. @subsubsection High-Level Traps
  1017. The low-level trap API allows one to make traps that call procedures,
  1018. and the trap state API allows one to keep track of what traps are
  1019. there. But neither of these APIs directly helps you when you want to
  1020. set a breakpoint, because it's unclear what to do when the trap fires.
  1021. Do you enter a debugger, or mail a summary of the situation to your
  1022. great-aunt, or what?
  1023. So for the common case in which you just want to install breakpoints,
  1024. and then have them all result in calls to one parameterizable procedure,
  1025. we have the high-level trap interface.
  1026. Perhaps we should have started this section with this interface, as it's
  1027. clearly the one most people should use. But as its capabilities and
  1028. limitations proceed from the lower layers, we felt that the
  1029. character-building exercise of building a mental model might be helpful.
  1030. These procedures share a module with trap states:
  1031. @lisp
  1032. (use-modules (system vm trap-state))
  1033. @end lisp
  1034. @deffn {Scheme Procedure} with-default-trap-handler handler thunk
  1035. Call @var{thunk} in a dynamic context in which @var{handler} is the
  1036. current trap handler.
  1037. Additionally, during the execution of @var{thunk}, the VM trace level
  1038. (@pxref{VM Hooks}) is set to the number of enabled traps. This ensures
  1039. that traps will in fact fire.
  1040. @var{handler} may be @code{#f}, in which case VM hooks are not enabled
  1041. as they otherwise would be, as there is nothing to handle the traps.
  1042. @end deffn
  1043. The trace-level-setting behavior of @code{with-default-trap-handler} is
  1044. one of its more useful aspects, but if you are willing to forgo that,
  1045. and just want to install a global trap handler, there's a function for
  1046. that too:
  1047. @deffn {Scheme Procedure} install-trap-handler! handler
  1048. Set the current thread's trap handler to @var{handler}.
  1049. @end deffn
  1050. Trap handlers are called when traps installed by procedures from this
  1051. module fire. The current ``consumer'' of this API is Guile's REPL, but
  1052. one might easily imagine other trap handlers being used to integrate
  1053. with other debugging tools.
  1054. @cindex Breakpoints
  1055. @cindex Setting breakpoints
  1056. @deffn {Scheme Procedure} add-trap-at-procedure-call! proc
  1057. Install a trap that will fire when @var{proc} is called.
  1058. This is a breakpoint.
  1059. @end deffn
  1060. @cindex Tracepoints
  1061. @cindex Setting tracepoints
  1062. @deffn {Scheme Procedure} add-trace-at-procedure-call! proc
  1063. Install a trap that will print a tracing message when @var{proc} is
  1064. called. @xref{Tracing Traps}, for more information.
  1065. This is a tracepoint.
  1066. @end deffn
  1067. @deffn {Scheme Procedure} add-trap-at-source-location! file user-line
  1068. Install a trap that will fire when control reaches the given source
  1069. location. @var{user-line} is one-indexed, as users count lines, instead
  1070. of zero-indexed, as Guile counts lines.
  1071. This is a source breakpoint.
  1072. @end deffn
  1073. @deffn {Scheme Procedure} add-ephemeral-trap-at-frame-finish! frame handler
  1074. Install a trap that will call @var{handler} when @var{frame} finishes
  1075. executing. The trap will be removed from the trap state after firing, or
  1076. on nonlocal exit.
  1077. This is a finish trap, used to implement the ``finish'' REPL command.
  1078. @end deffn
  1079. @deffn {Scheme Procedure} add-ephemeral-stepping-trap! frame handler [#:into?] [#:instruction?]
  1080. Install a trap that will call @var{handler} after stepping to a
  1081. different source line or instruction. The trap will be removed from the
  1082. trap state after firing, or on nonlocal exit.
  1083. If @var{instruction?} is false (the default), the trap will fire when
  1084. control reaches a new source line. Otherwise it will fire when control
  1085. reaches a new instruction.
  1086. Additionally, if @var{into?} is false (not the default), the trap will
  1087. only fire for frames at or prior to the given frame. If @var{into?} is
  1088. true (the default), the trap may step into nested procedure
  1089. invocations.
  1090. This is a stepping trap, used to implement the ``step'', ``next'',
  1091. ``step-instruction'', and ``next-instruction'' REPL commands.
  1092. @end deffn
  1093. @node GDB Support
  1094. @subsection GDB Support
  1095. @cindex GDB support
  1096. Sometimes, you may find it necessary to debug Guile applications at the
  1097. C level. Doing so can be tedious, in particular because the debugger is
  1098. oblivious to Guile's @code{SCM} type, and thus unable to display
  1099. @code{SCM} values in any meaningful way:
  1100. @example
  1101. (gdb) frame
  1102. #0 scm_display (obj=0xf04310, port=0x6f9f30) at print.c:1437
  1103. @end example
  1104. To address that, Guile comes with an extension of the GNU Debugger (GDB)
  1105. that contains a ``pretty-printer'' for @code{SCM} values. With this GDB
  1106. extension, the C frame in the example above shows up like this:
  1107. @example
  1108. (gdb) frame
  1109. #0 scm_display (obj=("hello" GDB!), port=#<port file 6f9f30>) at print.c:1437
  1110. @end example
  1111. @noindent
  1112. Here GDB was able to decode the list pointed to by @var{obj}, and to
  1113. print it using Scheme's read syntax.
  1114. That extension is a @code{.scm} file installed alongside the
  1115. @file{libguile} shared library. When GDB 7.8 or later is installed and
  1116. compiled with support for extensions written in Guile, the extension is
  1117. automatically loaded when debugging a program linked against
  1118. @file{libguile} (@pxref{Auto-loading,,, gdb, Debugging with GDB}). Note
  1119. that the directory where @file{libguile} is installed must be among
  1120. GDB's auto-loading ``safe directories'' (@pxref{Auto-loading safe
  1121. path,,, gdb, Debugging with GDB}).
  1122. @c Local Variables:
  1123. @c TeX-master: "guile.texi"
  1124. @c End: