More stack traces in OCaml


Following up on our earlier patch, here is a patch to show backtraces in the OCaml top level and for dynamically-loaded code (this patch subsumes the previous one). This feature is often requested on the OCaml mailing list, and we have found it very useful in development to get a quick idea of where something is breaking.

Instructions are as before:

  1. download the patch and save it as backtrace.patch
  2. unpack a fresh OCaml 3.10.0 tree
  3. patch -p0 < backtrace.patch in the same directory where you unpacked OCaml.
  4. cd into the OCaml tree
  5. ./configure
  6. make core promote
  7. remove the lines in stdlib/printexc.mli that are marked UNCOMMENT
  8. make world.opt or whatever you normally do to build OCaml

In the top level, you will want to run

  • #capture_backtrace true
  • #debug true

The first turns on backtrace capturing (it just calls Printexc.capture_backtrace); the second sets the compiler so it generates debugging events when code is compiled in the top level.

Now if you #load code (or load code with Dynlink) that has debugging events, or #use an external file (or enter an expression into the toplevel, but see the caveat below), you should see a backtrace on an uncaught exception.

For programs other than the top level this facility works as before, and additionally works with code loaded through Dynlink.

Caveats:

  1. You’ll need to rebuild external libraries with debugging if you want complete backtraces (the stdlib has it already).
  2. Backtrace locations in code entered at the top level are not very helpful, since there is no filename to refer to; you’ll get better results with #use.
  3. In the stock OCaml runtime, debugging events are loaded from the executable when a backtrace is to be generated, and then garbage collected. With this patch they are loaded when the code is loaded, and kept around forever, taking up some memory.
  4. The caveat on the previous patch about changing directories no longer applies, since debugging events are loaded on startup.

Comments