Sun, 22 Oct 2006

Ocaml : Exception Backtraces.

There's a paper dated December 2002 by Kevin Murphy where he explains why he was looking at Ocaml. That article was recently linked on programming.reddit.com and there was a comment complaining that Ocaml couldn't print out backtraces on exceptions. Someone posted later that this was not right, but I've heard this complaint often enough that I thought I should blog about how to do it.

First off, Ocaml has two compilers, one which produces bytecode and one which produces native binaries. The native code compiler is not currently able to produce exception backtraces and this is where the Reddit commenter got the idea. However, there is a patch in the Ocaml bug tracker which adds backtrace capabilities. I'm hoping that this goes into the compiler proper in the next release or two.

For a project that is currently compiling with ocamlopt (the native code compiler), changing the to bytecode compiler is as simple as editing the Makefile and replacing all invocations of "ocamlopt" with "ocamlc -g" where the "-g" turns on exception backtraces. You can then rebuild the application. The final step is to turn on backtraces in the bytecode run time environment which is done by setting an environment variable:

export OCAMLRUNPARAM="b1"

Once compiled to bytecode and with the environment variable set, the application can be run and should produce the required backtrace. The following is an example of a backtrace from something I'm working on at the moment (I hacked the code to make sure I could get one).

Fatal error: exception Invalid_argument("index out of bounds") Raised by primitive operation at unknown location Called from file "meyers_diff.ml", line 93, characters 1-31 Called from file "meyers_diff.ml", line 200, characters 10-52 Called from file "meyers_diff.ml", line 221, characters 16-60 Called from file "meyers_diff.ml", line 264, characters 11-148 Called from file "meyers_diff.ml", line 305, characters 17-50 Called from file "array.ml", line 130, characters 31-51 Called from file "meyers_diff.ml", line 323, characters 1-316

Obviously it would be nicer if function names were included here, but this is more than sufficient for debugging purposes.

Posted at: 10:39 | Category: CodeHacking/Ocaml | Permalink