api-debug.texi 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530
  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
  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 represent 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. @cindex source properties
  203. As Guile reads in Scheme code from file or from standard input, it
  204. remembers the file name, line number and column number where each
  205. expression begins. These pieces of information are known as the
  206. @dfn{source properties} of the expression. Syntax expanders and the
  207. compiler propagate these source properties to compiled procedures, so
  208. that, if an error occurs when evaluating the transformed expression,
  209. Guile's debugger can point back to the file and location where the
  210. expression originated.
  211. The way that source properties are stored means that Guile cannot
  212. associate source properties with individual symbols, keywords,
  213. characters, booleans, or small integers. This can be seen by typing
  214. @code{(xxx)} and @code{xxx} at the Guile prompt (where the variable
  215. @code{xxx} has not been defined):
  216. @example
  217. scheme@@(guile-user)> (xxx)
  218. <unnamed port>:4:1: In procedure module-lookup:
  219. <unnamed port>:4:1: Unbound variable: xxx
  220. scheme@@(guile-user)> xxx
  221. ERROR: In procedure module-lookup:
  222. ERROR: Unbound variable: xxx
  223. @end example
  224. @noindent
  225. In the latter case, no source properties were stored, so the error
  226. doesn't have any source information.
  227. @deffn {Scheme Procedure} supports-source-properties? obj
  228. @deffnx {C Function} scm_supports_source_properties_p (obj)
  229. Return #t if source properties can be associated with @var{obj},
  230. otherwise return #f.
  231. @end deffn
  232. The recording of source properties is controlled by the read option
  233. named ``positions'' (@pxref{Scheme Read}). This option is switched
  234. @emph{on} by default.
  235. The following procedures can be used to access and set the source
  236. properties of read expressions.
  237. @deffn {Scheme Procedure} set-source-properties! obj alist
  238. @deffnx {C Function} scm_set_source_properties_x (obj, alist)
  239. Install the association list @var{alist} as the source property
  240. list for @var{obj}.
  241. @end deffn
  242. @deffn {Scheme Procedure} set-source-property! obj key datum
  243. @deffnx {C Function} scm_set_source_property_x (obj, key, datum)
  244. Set the source property of object @var{obj}, which is specified by
  245. @var{key} to @var{datum}. Normally, the key will be a symbol.
  246. @end deffn
  247. @deffn {Scheme Procedure} source-properties obj
  248. @deffnx {C Function} scm_source_properties (obj)
  249. Return the source property association list of @var{obj}.
  250. @end deffn
  251. @deffn {Scheme Procedure} source-property obj key
  252. @deffnx {C Function} scm_source_property (obj, key)
  253. Return the property specified by @var{key} from @var{obj}'s source
  254. properties.
  255. @end deffn
  256. If the @code{positions} reader option is enabled, supported expressions
  257. will have values set for the @code{filename}, @code{line} and
  258. @code{column} properties.
  259. Source properties are also associated with syntax objects. Procedural
  260. macros can get at the source location of their input using the
  261. @code{syntax-source} accessor. @xref{Syntax Transformer Helpers}, for
  262. more.
  263. Guile also defines a couple of convenience macros built on
  264. @code{syntax-source}:
  265. @deffn {Scheme Syntax} current-source-location
  266. Expands to the source properties corresponding to the location of the
  267. @code{(current-source-location)} form.
  268. @end deffn
  269. @deffn {Scheme Syntax} current-filename
  270. Expands to the current filename: the filename that the
  271. @code{(current-filename)} form appears in. Expands to @code{#f} if this
  272. information is unavailable.
  273. @end deffn
  274. If you're stuck with defmacros (@pxref{Defmacros}), and want to preserve
  275. source information, the following helper function might be useful to
  276. you:
  277. @deffn {Scheme Procedure} cons-source xorig x y
  278. @deffnx {C Function} scm_cons_source (xorig, x, y)
  279. Create and return a new pair whose car and cdr are @var{x} and @var{y}.
  280. Any source properties associated with @var{xorig} are also associated
  281. with the new pair.
  282. @end deffn
  283. @node Programmatic Error Handling
  284. @subsection Programmatic Error Handling
  285. For better or for worse, all programs have bugs, and dealing with bugs
  286. is part of programming. This section deals with that class of bugs that
  287. causes an exception to be raised -- from your own code, from within a
  288. library, or from Guile itself.
  289. @menu
  290. * Catching Exceptions:: Handling errors after the stack is unwound.
  291. * Capturing Stacks:: Capturing the stack at the time of error.
  292. * Pre-Unwind Debugging:: Debugging before the exception is thrown.
  293. * Stack Overflow:: Detecting and handling runaway recursion.
  294. * Debug Options:: A historical interface to debugging.
  295. @end menu
  296. @node Catching Exceptions
  297. @subsubsection Catching Exceptions
  298. A common requirement is to be able to show as much useful context as
  299. possible when a Scheme program hits an error. The most immediate
  300. information about an error is the kind of error that it is -- such as
  301. ``division by zero'' -- and any parameters that the code which signalled
  302. the error chose explicitly to provide. This information originates with
  303. the @code{error} or @code{throw} call (or their C code equivalents, if
  304. the error is detected by C code) that signals the error, and is passed
  305. automatically to the handler procedure of the innermost applicable
  306. @code{catch} or @code{with-throw-handler} expression.
  307. Therefore, to catch errors that occur within a chunk of Scheme code, and
  308. to intercept basic information about those errors, you need to execute
  309. that code inside the dynamic context of a @code{catch} or
  310. @code{with-throw-handler} expression, or the equivalent in C. In Scheme,
  311. this means you need something like this:
  312. @lisp
  313. (catch #t
  314. (lambda ()
  315. ;; Execute the code in which
  316. ;; you want to catch errors here.
  317. ...)
  318. (lambda (key . parameters)
  319. ;; Put the code which you want
  320. ;; to handle an error here.
  321. ...))
  322. @end lisp
  323. @noindent
  324. The @code{catch} here can also be @code{with-throw-handler}; see
  325. @ref{Throw Handlers} for information on the when you might want to use
  326. @code{with-throw-handler} instead of @code{catch}.
  327. For example, to print out a message and return #f when an error occurs,
  328. you might use:
  329. @smalllisp
  330. (define (catch-all thunk)
  331. (catch #t
  332. thunk
  333. (lambda (key . parameters)
  334. (format (current-error-port)
  335. "Uncaught throw to '~a: ~a\n" key parameters)
  336. #f)))
  337. (catch-all
  338. (lambda () (error "Not a vegetable: tomato")))
  339. @print{} Uncaught throw to 'misc-error: (#f ~A (Not a vegetable: tomato) #f)
  340. @result{} #f
  341. @end smalllisp
  342. The @code{#t} means that the catch is applicable to all kinds of error.
  343. If you want to restrict your catch to just one kind of error, you can
  344. put the symbol for that kind of error instead of @code{#t}. The
  345. equivalent to this in C would be something like this:
  346. @lisp
  347. SCM my_body_proc (void *body_data)
  348. @{
  349. /* Execute the code in which
  350. you want to catch errors here. */
  351. ...
  352. @}
  353. SCM my_handler_proc (void *handler_data,
  354. SCM key,
  355. SCM parameters)
  356. @{
  357. /* Put the code which you want
  358. to handle an error here. */
  359. ...
  360. @}
  361. @{
  362. ...
  363. scm_c_catch (SCM_BOOL_T,
  364. my_body_proc, body_data,
  365. my_handler_proc, handler_data,
  366. NULL, NULL);
  367. ...
  368. @}
  369. @end lisp
  370. @noindent
  371. Again, as with the Scheme version, @code{scm_c_catch} could be replaced
  372. by @code{scm_c_with_throw_handler}, and @code{SCM_BOOL_T} could instead
  373. be the symbol for a particular kind of error.
  374. @node Capturing Stacks
  375. @subsubsection Capturing the full error stack
  376. The other interesting information about an error is the full Scheme
  377. stack at the point where the error occurred; in other words what
  378. innermost expression was being evaluated, what was the expression that
  379. called that one, and so on. If you want to write your code so that it
  380. captures and can display this information as well, there are a couple
  381. important things to understand.
  382. Firstly, the stack at the point of the error needs to be explicitly
  383. captured by a @code{make-stack} call (or the C equivalent
  384. @code{scm_make_stack}). The Guile library does not do this
  385. ``automatically'' for you, so you will need to write code with a
  386. @code{make-stack} or @code{scm_make_stack} call yourself. (We emphasise
  387. this point because some people are misled by the fact that the Guile
  388. interactive REPL code @emph{does} capture and display the stack
  389. automatically. But the Guile interactive REPL is itself a Scheme
  390. program@footnote{In effect, it is the default program which is run when
  391. no commands or script file are specified on the Guile command line.}
  392. running on top of the Guile library, and which uses @code{catch} and
  393. @code{make-stack} in the way we are about to describe to capture the
  394. stack when an error occurs.)
  395. And secondly, in order to capture the stack effectively at the point
  396. where the error occurred, the @code{make-stack} call must be made before
  397. Guile unwinds the stack back to the location of the prevailing catch
  398. expression. This means that the @code{make-stack} call must be made
  399. within the handler of a @code{with-throw-handler} expression, or the
  400. optional "pre-unwind" handler of a @code{catch}. (For the full story of
  401. how these alternatives differ from each other, see @ref{Exceptions}. The
  402. main difference is that @code{catch} terminates the error, whereas
  403. @code{with-throw-handler} only intercepts it temporarily and then allow
  404. it to continue propagating up to the next innermost handler.)
  405. So, here are some examples of how to do all this in Scheme and in C.
  406. For the purpose of these examples we assume that the captured stack
  407. should be stored in a variable, so that it can be displayed or
  408. arbitrarily processed later on. In Scheme:
  409. @lisp
  410. (let ((captured-stack #f))
  411. (catch #t
  412. (lambda ()
  413. ;; Execute the code in which
  414. ;; you want to catch errors here.
  415. ...)
  416. (lambda (key . parameters)
  417. ;; Put the code which you want
  418. ;; to handle an error after the
  419. ;; stack has been unwound here.
  420. ...)
  421. (lambda (key . parameters)
  422. ;; Capture the stack here:
  423. (set! captured-stack (make-stack #t))))
  424. ...
  425. (if captured-stack
  426. (begin
  427. ;; Display or process the captured stack.
  428. ...))
  429. ...)
  430. @end lisp
  431. @noindent
  432. And in C:
  433. @lisp
  434. SCM my_body_proc (void *body_data)
  435. @{
  436. /* Execute the code in which
  437. you want to catch errors here. */
  438. ...
  439. @}
  440. SCM my_handler_proc (void *handler_data,
  441. SCM key,
  442. SCM parameters)
  443. @{
  444. /* Put the code which you want
  445. to handle an error after the
  446. stack has been unwound here. */
  447. ...
  448. @}
  449. SCM my_preunwind_proc (void *handler_data,
  450. SCM key,
  451. SCM parameters)
  452. @{
  453. /* Capture the stack here: */
  454. *(SCM *)handler_data = scm_make_stack (SCM_BOOL_T, SCM_EOL);
  455. @}
  456. @{
  457. SCM captured_stack = SCM_BOOL_F;
  458. ...
  459. scm_c_catch (SCM_BOOL_T,
  460. my_body_proc, body_data,
  461. my_handler_proc, handler_data,
  462. my_preunwind_proc, &captured_stack);
  463. ...
  464. if (captured_stack != SCM_BOOL_F)
  465. @{
  466. /* Display or process the captured stack. */
  467. ...
  468. @}
  469. ...
  470. @}
  471. @end lisp
  472. Once you have a captured stack, you can interrogate and display its
  473. details in any way that you want, using the @code{stack-@dots{}} and
  474. @code{frame-@dots{}} API described in @ref{Stacks} and
  475. @ref{Frames}.
  476. If you want to print out a backtrace in the same format that the Guile
  477. REPL does, you can use the @code{display-backtrace} procedure to do so.
  478. You can also use @code{display-application} to display an individual
  479. frame in the Guile REPL format.
  480. @node Pre-Unwind Debugging
  481. @subsubsection Pre-Unwind Debugging
  482. Instead of saving a stack away and waiting for the @code{catch} to
  483. return, you can handle errors directly, from within the pre-unwind
  484. handler.
  485. For example, to show a backtrace when an error is thrown, you might want
  486. to use a procedure like this:
  487. @lisp
  488. (define (with-backtrace thunk)
  489. (with-throw-handler #t
  490. thunk
  491. (lambda args (backtrace))))
  492. (with-backtrace (lambda () (error "Not a vegetable: tomato")))
  493. @end lisp
  494. Since we used @code{with-throw-handler} here, we didn't actually catch
  495. the error. @xref{Throw Handlers}, for more information. However, we did
  496. print out a context at the time of the error, using the built-in
  497. procedure, @code{backtrace}.
  498. @deffn {Scheme Procedure} backtrace [highlights]
  499. @deffnx {C Function} scm_backtrace_with_highlights (highlights)
  500. @deffnx {C Function} scm_backtrace ()
  501. Display a backtrace of the current stack to the current output port. If
  502. @var{highlights} is given it should be a list; the elements of this list
  503. will be highlighted wherever they appear in the backtrace.
  504. @end deffn
  505. The Guile REPL code (in @file{system/repl/repl.scm} and related files)
  506. uses a @code{catch} with a pre-unwind handler to capture the stack when
  507. an error occurs in an expression that was typed into the REPL, and debug
  508. that stack interactively in the context of the error.
  509. These procedures are available for use by user programs, in the
  510. @code{(system repl error-handling)} module.
  511. @lisp
  512. (use-modules (system repl error-handling))
  513. @end lisp
  514. @deffn {Scheme Procedure} call-with-error-handling thunk @
  515. [#:on-error on-error='debug] [#:post-error post-error='catch] @
  516. [#:pass-keys pass-keys='(quit)] @
  517. [#:report-keys report-keys='(stack-overflow)] @
  518. [#:trap-handler trap-handler='debug]
  519. Call a thunk in a context in which errors are handled.
  520. There are five keyword arguments:
  521. @table @var
  522. @item on-error
  523. Specifies what to do before the stack is unwound.
  524. Valid options are @code{debug} (the default), which will enter a
  525. debugger; @code{pass}, in which case nothing is done, and the exception
  526. is rethrown; or a procedure, which will be the pre-unwind handler.
  527. @item post-error
  528. Specifies what to do after the stack is unwound.
  529. Valid options are @code{catch} (the default), which will silently catch
  530. errors, returning the unspecified value; @code{report}, which prints out
  531. a description of the error (via @code{display-error}), and then returns
  532. the unspecified value; or a procedure, which will be the catch handler.
  533. @item trap-handler
  534. Specifies a trap handler: what to do when a breakpoint is hit.
  535. Valid options are @code{debug}, which will enter the debugger;
  536. @code{pass}, which does nothing; or @code{disabled}, which disables
  537. traps entirely. @xref{Traps}, for more information.
  538. @item pass-keys
  539. A set of keys to ignore, as a list.
  540. @item report-keys
  541. A set of keys to always report even if the post-error handler is
  542. @code{catch}, as a list.
  543. @end table
  544. @end deffn
  545. @node Stack Overflow
  546. @subsubsection Stack Overflow
  547. @cindex overflow, stack
  548. @cindex stack overflow
  549. Every time a Scheme program makes a call that is not in tail position,
  550. it pushes a new frame onto the stack. Returning a value from a function
  551. pops the top frame off the stack. Stack frames take up memory, and as
  552. nobody has an infinite amount of memory, deep recursion could cause
  553. Guile to run out of memory. Running out of stack memory is called
  554. @dfn{stack overflow}.
  555. @subsubheading Stack Limits
  556. Most languages have a terrible stack overflow story. For example, in C,
  557. if you use too much stack, your program will exhibit ``undefined
  558. behavior'', which if you are lucky means that it will crash. It's
  559. especially bad in C, as you neither know ahead of time how much stack
  560. your functions use, nor the stack limit imposed by the user's system,
  561. and the stack limit is often quite small relative to the total memory
  562. size.
  563. Managed languages like Python have a better error story, as they are
  564. defined to raise an exception on stack overflow -- but like C, Python
  565. and most dynamic languages still have a fixed stack size limit that is
  566. usually much smaller than the heap.
  567. Arbitrary stack limits would have an unfortunate effect on Guile
  568. programs. For example, the following implementation of the inner loop
  569. of @code{map} is clean and elegant:
  570. @example
  571. (define (map f l)
  572. (if (pair? l)
  573. (cons (f (car l))
  574. (map f (cdr l)))
  575. '()))
  576. @end example
  577. However, if there were a stack limit, that would limit the size of lists
  578. that can be processed with this @code{map}. Eventually, you would have
  579. to rewrite it to use iteration with an accumulator:
  580. @example
  581. (define (map f l)
  582. (let lp ((l l) (out '()))
  583. (if (pair? l)
  584. (lp (cdr l) (cons (f (car l)) out))
  585. (reverse out))))
  586. @end example
  587. This second version is sadly not as clear, and it also allocates more
  588. heap memory (once to build the list in reverse, and then again to
  589. reverse the list). You would be tempted to use the destructive
  590. @code{reverse!} to save memory and time, but then your code would not be
  591. continuation-safe -- if @var{f} returned again after the map had
  592. finished, it would see an @var{out} list that had already been
  593. reversed. The recursive @code{map} has none of these problems.
  594. Guile has no stack limit for Scheme code. When a thread makes its first
  595. Guile call, a small stack is allocated -- just one page of memory.
  596. Whenever that memory limit would be reached, Guile arranges to grow the
  597. stack by a factor of two. When garbage collection happens, Guile
  598. arranges to return the unused part of the stack to the operating system,
  599. but without causing the stack to shrink. In this way, the stack can
  600. grow to consume up to all memory available to the Guile process, and
  601. when the recursive computation eventually finishes, that stack memory is
  602. returned to the system.
  603. @subsubheading Exceptional Situations
  604. Of course, it's still possible to run out of stack memory. The most
  605. common cause of this is program bugs that cause unbounded recursion, as
  606. in:
  607. @example
  608. (define (faulty-map f l)
  609. (if (pair? l)
  610. (cons (f (car l)) (faulty-map f l))
  611. '()))
  612. @end example
  613. Did you spot the bug? The recursive call to @code{faulty-map} recursed
  614. on @var{l}, not @code{(cdr @var{l})}. Running this program would cause
  615. Guile to use up all memory in your system, and eventually Guile would
  616. fail to grow the stack. At that point you have a problem: Guile needs
  617. to raise an exception to unwind the stack and return memory to the
  618. system, but the user might have throw handlers in place (@pxref{Throw
  619. Handlers}) that want to run before the stack is unwound, and we don't
  620. have any stack in which to run them.
  621. Therefore in this case, Guile throws an unwind-only exception that does
  622. not run pre-unwind handlers. Because this is such an odd case, Guile
  623. prints out a message on the console, in case the user was expecting to
  624. be able to get a backtrace from any pre-unwind handler.
  625. @subsubheading Runaway Recursion
  626. Still, this failure mode is not so nice. If you are running an
  627. environment in which you are interactively building a program while it
  628. is running, such as at a REPL, you might want to impose an artificial
  629. stack limit on the part of your program that you are building to detect
  630. accidental runaway recursion. For that purpose, there is
  631. @code{call-with-stack-overflow-handler}, from @code{(system vm vm)}.
  632. @example
  633. (use-module (system vm vm))
  634. @end example
  635. @deffn {Scheme Procedure} call-with-stack-overflow-handler limit thunk handler
  636. Call @var{thunk} in an environment in which the stack limit has been
  637. reduced to @var{limit} additional words. If the limit is reached,
  638. @var{handler} (a thunk) will be invoked in the dynamic environment of
  639. the error. For the extent of the call to @var{handler}, the stack limit
  640. and handler are restored to the values that were in place when
  641. @code{call-with-stack-overflow-handler} was called.
  642. Usually, @var{handler} should raise an exception or abort to an outer
  643. prompt. However if @var{handler} does return, it should return a number
  644. of additional words of stack space to allow to the inner environment.
  645. @end deffn
  646. A stack overflow handler may only ever ``credit'' the inner thunk with
  647. stack space that was available when the handler was instated. When
  648. Guile first starts, there is no stack limit in place, so the outer
  649. handler may allow the inner thunk an arbitrary amount of space, but any
  650. nested stack overflow handler will not be able to consume more than its
  651. limit.
  652. Unlike the unwind-only exception that is thrown if Guile is unable to
  653. grow its stack, any exception thrown by a stack overflow handler might
  654. invoke pre-unwind handlers. Indeed, the stack overflow handler is
  655. itself a pre-unwind handler of sorts. If the code imposing the stack
  656. limit wants to protect itself against malicious pre-unwind handlers from
  657. the inner thunk, it should abort to a prompt of its own making instead
  658. of throwing an exception that might be caught by the inner thunk.
  659. @subsubheading C Stack Usage
  660. It is also possible for Guile to run out of space on the C stack. If
  661. you call a primitive procedure which then calls a Scheme procedure in a
  662. loop, you will consume C stack space. Guile tries to detect excessive
  663. consumption of C stack space, throwing an error when you have hit 80% of
  664. the process' available stack (as allocated by the operating system), or
  665. 160 kilowords in the absence of a strict limit.
  666. For example, looping through @code{call-with-vm}, a primitive that calls
  667. a thunk, gives us the following:
  668. @lisp
  669. scheme@@(guile-user)> (use-modules (system vm vm))
  670. scheme@@(guile-user)> (let lp () (call-with-vm lp))
  671. ERROR: Stack overflow
  672. @end lisp
  673. Unfortunately, that's all the information we get. Overrunning the C
  674. stack will throw an unwind-only exception, because it's not safe to
  675. do very much when you are close to the C stack limit.
  676. If you get an error like this, you can either try rewriting your code to
  677. use less stack space, or increase the maximum stack size. To increase
  678. the maximum stack size, use @code{debug-set!}, for example:
  679. @lisp
  680. (debug-set! stack 200000)
  681. @end lisp
  682. The next section describes @code{debug-set!} more thoroughly. Of course
  683. the best thing is to have your code operate without so much resource
  684. consumption by avoiding loops through C trampolines.
  685. @node Debug Options
  686. @subsubsection Debug options
  687. The behavior of the @code{backtrace} procedure and of the default error
  688. handler can be parameterized via the debug options.
  689. @cindex options - debug
  690. @cindex debug options
  691. @deffn {Scheme Procedure} debug-options [setting]
  692. Display the current settings of the debug options. If @var{setting} is
  693. omitted, only a short form of the current read options is printed.
  694. Otherwise if @var{setting} is the symbol @code{help}, a complete options
  695. description is displayed.
  696. @end deffn
  697. The set of available options, and their default values, may be had by
  698. invoking @code{debug-options} at the prompt.
  699. @smallexample
  700. scheme@@(guile-user)>
  701. backwards no Display backtrace in anti-chronological order.
  702. width 79 Maximal width of backtrace.
  703. depth 20 Maximal length of printed backtrace.
  704. backtrace yes Show backtrace on error.
  705. stack 1048576 Stack size limit (measured in words;
  706. 0 = no check).
  707. show-file-name #t Show file names and line numbers in backtraces
  708. when not `#f'. A value of `base' displays only
  709. base names, while `#t' displays full names.
  710. warn-deprecated no Warn when deprecated features are used.
  711. @end smallexample
  712. The boolean options may be toggled with @code{debug-enable} and
  713. @code{debug-disable}. The non-boolean options must be set using
  714. @code{debug-set!}.
  715. @deffn {Scheme Procedure} debug-enable option-name
  716. @deffnx {Scheme Procedure} debug-disable option-name
  717. @deffnx {Scheme Syntax} debug-set! option-name value
  718. Modify the debug options. @code{debug-enable} should be used with boolean
  719. options and switches them on, @code{debug-disable} switches them off.
  720. @code{debug-set!} can be used to set an option to a specific value. Due
  721. to historical oddities, it is a macro that expects an unquoted option
  722. name.
  723. @end deffn
  724. @node Traps
  725. @subsection Traps
  726. @cindex Traps
  727. @cindex VM hooks
  728. @cindex Breakpoints
  729. @cindex Trace
  730. @cindex Tracing
  731. @cindex Code coverage
  732. @cindex Profiling
  733. Guile's virtual machine can be configured to call out at key points to
  734. arbitrary user-specified procedures.
  735. In principle, these @dfn{hooks} allow Scheme code to implement any model
  736. it chooses for examining the evaluation stack as program execution
  737. proceeds, and for suspending execution to be resumed later.
  738. VM hooks are very low-level, though, and so Guile also has a library of
  739. higher-level @dfn{traps} on top of the VM hooks. A trap is an execution
  740. condition that, when fulfilled, will fire a handler. For example, Guile
  741. defines a trap that fires when control reaches a certain source
  742. location.
  743. Finally, Guile also defines a third level of abstractions: per-thread
  744. @dfn{trap states}. A trap state exists to give names to traps, and to
  745. hold on to the set of traps so that they can be enabled, disabled, or
  746. removed. The trap state infrastructure defines the most useful
  747. abstractions for most cases. For example, Guile's REPL uses trap state
  748. functions to set breakpoints and tracepoints.
  749. The following subsections describe all this in detail, for both the
  750. user wanting to use traps, and the developer interested in
  751. understanding how the interface hangs together.
  752. @menu
  753. * VM Hooks:: Modifying Guile's virtual machine.
  754. * Trap Interface:: Traps are on or off.
  755. * Low-Level Traps:: The various kinds of low-level traps.
  756. * Tracing Traps:: Traps to trace procedure calls and returns.
  757. * Trap States:: One state (per thread) to bind them.
  758. * High-Level Traps:: The highest-level trap interface. Use this.
  759. @end menu
  760. @node VM Hooks
  761. @subsubsection VM Hooks
  762. Everything that runs in Guile runs on its virtual machine, a C program
  763. that defines a number of operations that Scheme programs can
  764. perform.
  765. Note that there are multiple VM ``engines'' for Guile. Only some of them
  766. have support for hooks compiled in. Normally the deal is that you get
  767. hooks if you are running interactively, and otherwise they are disabled,
  768. as they do have some overhead (about 10 or 20 percent).
  769. To ensure that you are running with hooks, pass @code{--debug} to Guile
  770. when running your program, or otherwise use the @code{call-with-vm} and
  771. @code{set-vm-engine!} procedures to ensure that you are running in a VM
  772. with the @code{debug} engine.
  773. To digress, Guile's VM has 4 different hooks that can be fired at
  774. different times. For implementation reasons, these hooks are not
  775. actually implemented with first-class Scheme hooks (@pxref{Hooks}); they
  776. are managed using an ad-hoc interface.
  777. VM hooks are called with one argument: the current frame.
  778. @xref{Frames}. Since these hooks may be fired very frequently, Guile
  779. does a terrible thing: it allocates the frames on the C stack instead of
  780. the garbage-collected heap.
  781. The upshot here is that the frames are only valid within the dynamic
  782. extent of the call to the hook. If a hook procedure keeps a reference to
  783. the frame outside the extent of the hook, bad things will happen.
  784. The interface to hooks is provided by the @code{(system vm vm)} module:
  785. @example
  786. (use-modules (system vm vm))
  787. @end example
  788. @noindent
  789. All of these functions implicitly act on the VM for the current thread
  790. only.
  791. @deffn {Scheme Procedure} vm-add-next-hook! f
  792. Arrange to call @var{f} when before an instruction is retired (and
  793. executed).
  794. @end deffn
  795. @deffn {Scheme Procedure} vm-add-apply-hook! f
  796. Arrange to call @var{f} whenever a procedure is applied. The frame
  797. locals will be the callee, followed by the arguments to the call.
  798. Note that procedure application is somewhat orthogonal to continuation
  799. pushes and pops. To know whether a call is a tail call or not, with
  800. respect to the frame previously in place, check the value of the frame
  801. pointer compared the previous frame pointer.
  802. @end deffn
  803. @deffn {Scheme Procedure} vm-add-return-hook! f
  804. Arrange to call @var{f} before returning from a frame. The values in
  805. the frame will be the frame's return values.
  806. Note that it's possible to return from an ``inner'' frame: one that was
  807. not immediately proceeded by a call with that frame pointer. In that
  808. case, it corresponds to a non-local control flow jump, either because of
  809. applying a composable continuation or because of restoring a saved
  810. undelimited continuation.
  811. @end deffn
  812. @deffn {Scheme Procedure} vm-add-abort-hook!
  813. Arrange to call @var{f} after aborting to a prompt. @xref{Prompts}.
  814. Unfortunately, the values passed to the prompt handler are not easily
  815. available to @var{f}.
  816. @end deffn
  817. @deffn {Scheme Procedure} vm-remove-next-hook! f
  818. @deffnx {Scheme Procedure} vm-remove-apply-hook! f
  819. @deffnx {Scheme Procedure} vm-remove-return-hook! f
  820. @deffnx {Scheme Procedure} vm-remove-abort-hook! f
  821. Remove @var{f} from the corresponding VM hook for the current thread.
  822. @end deffn
  823. @cindex VM trace level
  824. These hooks do impose a performance penalty, if they are on. Obviously,
  825. the @code{vm-next-hook} has quite an impact, performance-wise. Therefore
  826. Guile exposes a single, heavy-handed knob to turn hooks on or off, the
  827. @dfn{VM trace level}. If the trace level is positive, hooks run;
  828. otherwise they don't.
  829. For convenience, when the VM fires a hook, it does so with the trap
  830. level temporarily set to 0. That way the hooks don't fire while you're
  831. handling a hook. The trace level is restored to whatever it was once the hook
  832. procedure finishes.
  833. @deffn {Scheme Procedure} vm-trace-level
  834. Retrieve the ``trace level'' of the VM. If positive, the trace hooks
  835. associated with @var{vm} will be run. The initial trace level is 0.
  836. @end deffn
  837. @deffn {Scheme Procedure} set-vm-trace-level! level
  838. Set the ``trace level'' of the VM.
  839. @end deffn
  840. @xref{A Virtual Machine for Guile}, for more information on Guile's
  841. virtual machine.
  842. @node Trap Interface
  843. @subsubsection Trap Interface
  844. The capabilities provided by hooks are great, but hooks alone rarely
  845. correspond to what users want to do.
  846. For example, if a user wants to break when and if control reaches a
  847. certain source location, how do you do it? If you install a ``next''
  848. hook, you get unacceptable overhead for the execution of the entire
  849. program. It would be possible to install an ``apply'' hook, then if the
  850. procedure encompasses those source locations, install a ``next'' hook,
  851. but already you're talking about one concept that might be implemented
  852. by a varying number of lower-level concepts.
  853. It's best to be clear about things and define one abstraction for all
  854. such conditions: the @dfn{trap}.
  855. Considering the myriad capabilities offered by the hooks though, there
  856. is only a minimum of functionality shared by all traps. Guile's current
  857. take is to reduce this to the absolute minimum, and have the only
  858. standard interface of a trap be ``turn yourself on'' or ``turn yourself
  859. off''.
  860. This interface sounds a bit strange, but it is useful to procedurally
  861. compose higher-level traps from lower-level building blocks. For
  862. example, Guile defines a trap that calls one handler when control enters
  863. a procedure, and another when control leaves the procedure. Given that
  864. trap, one can define a trap that adds to the next-hook only when within
  865. a given procedure. Building further, one can define a trap that fires
  866. when control reaches particular instructions within a procedure.
  867. Or of course you can stop at any of these intermediate levels. For
  868. example, one might only be interested in calls to a given procedure. But
  869. the point is that a simple enable/disable interface is all the
  870. commonality that exists between the various kinds of traps, and
  871. furthermore that such an interface serves to allow ``higher-level''
  872. traps to be composed from more primitive ones.
  873. Specifically, a trap, in Guile, is a procedure. When a trap is created,
  874. by convention the trap is enabled; therefore, the procedure that is the
  875. trap will, when called, disable the trap, and return a procedure that
  876. will enable the trap, and so on.
  877. Trap procedures take one optional argument: the current frame. (A trap
  878. may want to add to different sets of hooks depending on the frame that
  879. is current at enable-time.)
  880. If this all sounds very complicated, it's because it is. Some of it is
  881. essential, but probably most of it is not. The advantage of using this
  882. minimal interface is that composability is more lexically apparent than
  883. when, for example, using a stateful interface based on GOOPS. But
  884. perhaps this reflects the cognitive limitations of the programmer who
  885. made the current interface more than anything else.
  886. @node Low-Level Traps
  887. @subsubsection Low-Level Traps
  888. To summarize the last sections, traps are enabled or disabled, and when
  889. they are enabled, they add to various VM hooks.
  890. Note, however, that @emph{traps do not increase the VM trace level}. So
  891. if you create a trap, it will be enabled, but unless something else
  892. increases the VM's trace level (@pxref{VM Hooks}), the trap will not
  893. fire. It turns out that getting the VM trace level right is tricky
  894. without a global view of what traps are enabled. @xref{Trap States},
  895. for Guile's answer to this problem.
  896. Traps are created by calling procedures. Most of these procedures share
  897. a set of common keyword arguments, so rather than document them
  898. separately, we discuss them all together here:
  899. @table @code
  900. @item #:vm
  901. The VM to instrument. Defaults to the current thread's VM.
  902. @item #:current-frame
  903. For traps that enable more hooks depending on their dynamic context,
  904. this argument gives the current frame that the trap is running in.
  905. Defaults to @code{#f}.
  906. @end table
  907. To have access to these procedures, you'll need to have imported the
  908. @code{(system vm traps)} module:
  909. @lisp
  910. (use-modules (system vm traps))
  911. @end lisp
  912. @deffn {Scheme Procedure} trap-at-procedure-call proc handler @
  913. [#:vm]
  914. A trap that calls @var{handler} when @var{proc} is applied.
  915. @end deffn
  916. @deffn {Scheme Procedure} trap-in-procedure proc @
  917. enter-handler exit-handler [#:current-frame] [#:vm]
  918. A trap that calls @var{enter-handler} when control enters @var{proc},
  919. and @var{exit-handler} when control leaves @var{proc}.
  920. Control can enter a procedure via:
  921. @itemize
  922. @item
  923. A procedure call.
  924. @item
  925. A return to a procedure's frame on the stack.
  926. @item
  927. A continuation returning directly to an application of this procedure.
  928. @end itemize
  929. Control can leave a procedure via:
  930. @itemize
  931. @item
  932. A normal return from the procedure.
  933. @item
  934. An application of another procedure.
  935. @item
  936. An invocation of a continuation.
  937. @item
  938. An abort.
  939. @end itemize
  940. @end deffn
  941. @deffn {Scheme Procedure} trap-instructions-in-procedure proc @
  942. next-handler exit-handler [#:current-frame] [#:vm]
  943. A trap that calls @var{next-handler} for every instruction executed in
  944. @var{proc}, and @var{exit-handler} when execution leaves @var{proc}.
  945. @end deffn
  946. @deffn {Scheme Procedure} trap-at-procedure-ip-in-range proc range @
  947. handler [#:current-frame] [#:vm]
  948. A trap that calls @var{handler} when execution enters a range of
  949. instructions in @var{proc}. @var{range} is a simple of pairs,
  950. @code{((@var{start} . @var{end}) ...)}. The @var{start} addresses are
  951. inclusive, and @var{end} addresses are exclusive.
  952. @end deffn
  953. @deffn {Scheme Procedure} trap-at-source-location file user-line handler @
  954. [#:current-frame] [#:vm]
  955. A trap that fires when control reaches a given source location. The
  956. @var{user-line} parameter is one-indexed, as a user counts lines,
  957. instead of zero-indexed, as Guile counts lines.
  958. @end deffn
  959. @deffn {Scheme Procedure} trap-frame-finish frame @
  960. return-handler abort-handler [#:vm]
  961. A trap that fires when control leaves the given frame. @var{frame}
  962. should be a live frame in the current continuation. @var{return-handler}
  963. will be called on a normal return, and @var{abort-handler} on a nonlocal
  964. exit.
  965. @end deffn
  966. @deffn {Scheme Procedure} trap-in-dynamic-extent proc @
  967. enter-handler return-handler abort-handler [#:vm]
  968. A more traditional dynamic-wind trap, which fires @var{enter-handler}
  969. when control enters @var{proc}, @var{return-handler} on a normal return,
  970. and @var{abort-handler} on a nonlocal exit.
  971. Note that rewinds are not handled, so there is no rewind handler.
  972. @end deffn
  973. @deffn {Scheme Procedure} trap-calls-in-dynamic-extent proc @
  974. apply-handler return-handler [#:current-frame] [#:vm]
  975. A trap that calls @var{apply-handler} every time a procedure is applied,
  976. and @var{return-handler} for returns, but only during the dynamic extent
  977. of an application of @var{proc}.
  978. @end deffn
  979. @deffn {Scheme Procedure} trap-instructions-in-dynamic-extent proc @
  980. next-handler [#:current-frame] [#:vm]
  981. A trap that calls @var{next-handler} for all retired instructions within
  982. the dynamic extent of a call to @var{proc}.
  983. @end deffn
  984. @deffn {Scheme Procedure} trap-calls-to-procedure proc @
  985. apply-handler return-handler [#:vm]
  986. A trap that calls @var{apply-handler} whenever @var{proc} is applied,
  987. and @var{return-handler} when it returns, but with an additional
  988. argument, the call depth.
  989. That is to say, the handlers will get two arguments: the frame in
  990. question, and the call depth (a non-negative integer).
  991. @end deffn
  992. @deffn {Scheme Procedure} trap-matching-instructions frame-pred handler [#:vm]
  993. A trap that calls @var{frame-pred} at every instruction, and if
  994. @var{frame-pred} returns a true value, calls @var{handler} on the
  995. frame.
  996. @end deffn
  997. @node Tracing Traps
  998. @subsubsection Tracing Traps
  999. The @code{(system vm trace)} module defines a number of traps for
  1000. tracing of procedure applications. When a procedure is @dfn{traced}, it
  1001. means that every call to that procedure is reported to the user during a
  1002. program run. The idea is that you can mark a collection of procedures
  1003. for tracing, and Guile will subsequently print out a line of the form
  1004. @lisp
  1005. | | (@var{procedure} @var{args} @dots{})
  1006. @end lisp
  1007. whenever a marked procedure is about to be applied to its arguments.
  1008. This can help a programmer determine whether a function is being called
  1009. at the wrong time or with the wrong set of arguments.
  1010. In addition, the indentation of the output is useful for demonstrating
  1011. how the traced applications are or are not tail recursive with respect
  1012. to each other. Thus, a trace of a non-tail recursive factorial
  1013. implementation looks like this:
  1014. @lisp
  1015. scheme@@(guile-user)> (define (fact1 n)
  1016. (if (zero? n) 1
  1017. (* n (fact1 (1- n)))))
  1018. scheme@@(guile-user)> ,trace (fact1 4)
  1019. trace: (fact1 4)
  1020. trace: | (fact1 3)
  1021. trace: | | (fact1 2)
  1022. trace: | | | (fact1 1)
  1023. trace: | | | | (fact1 0)
  1024. trace: | | | | 1
  1025. trace: | | | 1
  1026. trace: | | 2
  1027. trace: | 6
  1028. trace: 24
  1029. @end lisp
  1030. While a typical tail recursive implementation would look more like this:
  1031. @lisp
  1032. scheme@@(guile-user)> (define (facti acc n)
  1033. (if (zero? n) acc
  1034. (facti (* n acc) (1- n))))
  1035. scheme@@(guile-user)> (define (fact2 n) (facti 1 n))
  1036. scheme@@(guile-user)> ,trace (fact2 4)
  1037. trace: (fact2 4)
  1038. trace: (facti 1 4)
  1039. trace: (facti 4 3)
  1040. trace: (facti 12 2)
  1041. trace: (facti 24 1)
  1042. trace: (facti 24 0)
  1043. trace: 24
  1044. @end lisp
  1045. The low-level traps below (@pxref{Low-Level Traps}) share some common
  1046. options:
  1047. @table @code
  1048. @item #:width
  1049. The maximum width of trace output. Trace printouts will try not to
  1050. exceed this column, but for highly nested procedure calls, it may be
  1051. unavoidable. Defaults to 80.
  1052. @item #:vm
  1053. The VM on which to add the traps. Defaults to the current thread's VM.
  1054. @item #:prefix
  1055. A string to print out before each trace line. As seen above in the
  1056. examples, defaults to @code{"trace: "}.
  1057. @end table
  1058. To have access to these procedures, you'll need to have imported the
  1059. @code{(system vm trace)} module:
  1060. @lisp
  1061. (use-modules (system vm trace))
  1062. @end lisp
  1063. @deffn {Scheme Procedure} trace-calls-to-procedure proc @
  1064. [#:width] [#:vm] [#:prefix]
  1065. Print a trace at applications of and returns from @var{proc}.
  1066. @end deffn
  1067. @deffn {Scheme Procedure} trace-calls-in-procedure proc @
  1068. [#:width] [#:vm] [#:prefix]
  1069. Print a trace at all applications and returns within the dynamic extent
  1070. of calls to @var{proc}.
  1071. @end deffn
  1072. @deffn {Scheme Procedure} trace-instructions-in-procedure proc [#:width] [#:vm]
  1073. Print a trace at all instructions executed in the dynamic extent of
  1074. calls to @var{proc}.
  1075. @end deffn
  1076. In addition, Guile defines a procedure to call a thunk, tracing all
  1077. procedure calls and returns within the thunk.
  1078. @deffn {Scheme Procedure} call-with-trace thunk [#:calls?=#t] @
  1079. [#:instructions?=#f] @
  1080. [#:width=80]
  1081. Call @var{thunk}, tracing all execution within its dynamic extent.
  1082. If @var{calls?} is true, Guile will print a brief report at each
  1083. procedure call and return, as given above.
  1084. If @var{instructions?} is true, Guile will also print a message each
  1085. time an instruction is executed. This is a lot of output, but it is
  1086. sometimes useful when doing low-level optimization.
  1087. Note that because this procedure manipulates the VM trace level
  1088. directly, it doesn't compose well with traps at the REPL.
  1089. @end deffn
  1090. @xref{Profile Commands}, for more information on tracing at the REPL.
  1091. @node Trap States
  1092. @subsubsection Trap States
  1093. When multiple traps are present in a system, we begin to have a
  1094. bookkeeping problem. How are they named? How does one disable, enable,
  1095. or delete them?
  1096. Guile's answer to this is to keep an implicit per-thread @dfn{trap
  1097. state}. The trap state object is not exposed to the user; rather, API
  1098. that works on trap states fetches the current trap state from the
  1099. dynamic environment.
  1100. Traps are identified by integers. A trap can be enabled, disabled, or
  1101. removed, and can have an associated user-visible name.
  1102. These procedures have their own module:
  1103. @lisp
  1104. (use-modules (system vm trap-state))
  1105. @end lisp
  1106. @deffn {Scheme Procedure} add-trap! trap name
  1107. Add a trap to the current trap state, associating the given @var{name}
  1108. with it. Returns a fresh trap identifier (an integer).
  1109. Note that usually the more specific functions detailed in
  1110. @ref{High-Level Traps} are used in preference to this one.
  1111. @end deffn
  1112. @deffn {Scheme Procedure} list-traps
  1113. List the current set of traps, both enabled and disabled. Returns a list
  1114. of integers.
  1115. @end deffn
  1116. @deffn {Scheme Procedure} trap-name idx
  1117. Returns the name associated with trap @var{idx}, or @code{#f} if there
  1118. is no such trap.
  1119. @end deffn
  1120. @deffn {Scheme Procedure} trap-enabled? idx
  1121. Returns @code{#t} if trap @var{idx} is present and enabled, or @code{#f}
  1122. otherwise.
  1123. @end deffn
  1124. @deffn {Scheme Procedure} enable-trap! idx
  1125. Enables trap @var{idx}.
  1126. @end deffn
  1127. @deffn {Scheme Procedure} disable-trap! idx
  1128. Disables trap @var{idx}.
  1129. @end deffn
  1130. @deffn {Scheme Procedure} delete-trap! idx
  1131. Removes trap @var{idx}, disabling it first, if necessary.
  1132. @end deffn
  1133. @node High-Level Traps
  1134. @subsubsection High-Level Traps
  1135. The low-level trap API allows one to make traps that call procedures,
  1136. and the trap state API allows one to keep track of what traps are
  1137. there. But neither of these APIs directly helps you when you want to
  1138. set a breakpoint, because it's unclear what to do when the trap fires.
  1139. Do you enter a debugger, or mail a summary of the situation to your
  1140. great-aunt, or what?
  1141. So for the common case in which you just want to install breakpoints,
  1142. and then have them all result in calls to one parameterizable procedure,
  1143. we have the high-level trap interface.
  1144. Perhaps we should have started this section with this interface, as it's
  1145. clearly the one most people should use. But as its capabilities and
  1146. limitations proceed from the lower layers, we felt that the
  1147. character-building exercise of building a mental model might be helpful.
  1148. These procedures share a module with trap states:
  1149. @lisp
  1150. (use-modules (system vm trap-state))
  1151. @end lisp
  1152. @deffn {Scheme Procedure} with-default-trap-handler handler thunk
  1153. Call @var{thunk} in a dynamic context in which @var{handler} is the
  1154. current trap handler.
  1155. Additionally, during the execution of @var{thunk}, the VM trace level
  1156. (@pxref{VM Hooks}) is set to the number of enabled traps. This ensures
  1157. that traps will in fact fire.
  1158. @var{handler} may be @code{#f}, in which case VM hooks are not enabled
  1159. as they otherwise would be, as there is nothing to handle the traps.
  1160. @end deffn
  1161. The trace-level-setting behavior of @code{with-default-trap-handler} is
  1162. one of its more useful aspects, but if you are willing to forgo that,
  1163. and just want to install a global trap handler, there's a function for
  1164. that too:
  1165. @deffn {Scheme Procedure} install-trap-handler! handler
  1166. Set the current thread's trap handler to @var{handler}.
  1167. @end deffn
  1168. Trap handlers are called when traps installed by procedures from this
  1169. module fire. The current ``consumer'' of this API is Guile's REPL, but
  1170. one might easily imagine other trap handlers being used to integrate
  1171. with other debugging tools.
  1172. @cindex Breakpoints
  1173. @cindex Setting breakpoints
  1174. @deffn {Scheme Procedure} add-trap-at-procedure-call! proc
  1175. Install a trap that will fire when @var{proc} is called.
  1176. This is a breakpoint.
  1177. @end deffn
  1178. @cindex Tracepoints
  1179. @cindex Setting tracepoints
  1180. @deffn {Scheme Procedure} add-trace-at-procedure-call! proc
  1181. Install a trap that will print a tracing message when @var{proc} is
  1182. called. @xref{Tracing Traps}, for more information.
  1183. This is a tracepoint.
  1184. @end deffn
  1185. @deffn {Scheme Procedure} add-trap-at-source-location! file user-line
  1186. Install a trap that will fire when control reaches the given source
  1187. location. @var{user-line} is one-indexed, as users count lines, instead
  1188. of zero-indexed, as Guile counts lines.
  1189. This is a source breakpoint.
  1190. @end deffn
  1191. @deffn {Scheme Procedure} add-ephemeral-trap-at-frame-finish! frame handler
  1192. Install a trap that will call @var{handler} when @var{frame} finishes
  1193. executing. The trap will be removed from the trap state after firing, or
  1194. on nonlocal exit.
  1195. This is a finish trap, used to implement the ``finish'' REPL command.
  1196. @end deffn
  1197. @deffn {Scheme Procedure} add-ephemeral-stepping-trap! frame handler [#:into?] [#:instruction?]
  1198. Install a trap that will call @var{handler} after stepping to a
  1199. different source line or instruction. The trap will be removed from the
  1200. trap state after firing, or on nonlocal exit.
  1201. If @var{instruction?} is false (the default), the trap will fire when
  1202. control reaches a new source line. Otherwise it will fire when control
  1203. reaches a new instruction.
  1204. Additionally, if @var{into?} is false (not the default), the trap will
  1205. only fire for frames at or prior to the given frame. If @var{into?} is
  1206. true (the default), the trap may step into nested procedure
  1207. invocations.
  1208. This is a stepping trap, used to implement the ``step'', ``next'',
  1209. ``step-instruction'', and ``next-instruction'' REPL commands.
  1210. @end deffn
  1211. @node GDB Support
  1212. @subsection GDB Support
  1213. @cindex GDB support
  1214. Sometimes, you may find it necessary to debug Guile applications at the
  1215. C level. Doing so can be tedious, in particular because the debugger is
  1216. oblivious to Guile's @code{SCM} type, and thus unable to display
  1217. @code{SCM} values in any meaningful way:
  1218. @example
  1219. (gdb) frame
  1220. #0 scm_display (obj=0xf04310, port=0x6f9f30) at print.c:1437
  1221. @end example
  1222. To address that, Guile comes with an extension of the GNU Debugger (GDB)
  1223. that contains a ``pretty-printer'' for @code{SCM} values. With this GDB
  1224. extension, the C frame in the example above shows up like this:
  1225. @example
  1226. (gdb) frame
  1227. #0 scm_display (obj=("hello" GDB!), port=#<port file 6f9f30>) at print.c:1437
  1228. @end example
  1229. @noindent
  1230. Here GDB was able to decode the list pointed to by @var{obj}, and to
  1231. print it using Scheme's read syntax.
  1232. That extension is a @code{.scm} file installed alongside the
  1233. @file{libguile} shared library. When GDB 7.8 or later is installed and
  1234. compiled with support for extensions written in Guile, the extension is
  1235. automatically loaded when debugging a program linked against
  1236. @file{libguile} (@pxref{Auto-loading,,, gdb, Debugging with GDB}). Note
  1237. that the directory where @file{libguile} is installed must be among
  1238. GDB's auto-loading ``safe directories'' (@pxref{Auto-loading safe
  1239. path,,, gdb, Debugging with GDB}).
  1240. @c Local Variables:
  1241. @c TeX-master: "guile.texi"
  1242. @c End: