12

Is there a way in OCaml to get the current call stack programatically? By this, I do not mean inside a debugger but as a function call inside the program that will print the current call stack. I imagine this should not be beyond the capabilities of the byte-code interpreter, especially if debug symbols are available.

6
  • 4
    Did you try Printexc.get_backtrace (as documented at caml.inria.fr/pub/docs/manual-ocaml/libref/Printexc.html )? Aug 12, 2012 at 12:06
  • 1
    @PascalCuoq: That doesn't seem relevant.
    – Clément
    Apr 5, 2017 at 23:00
  • @Clément The function mention in three answers out of four is not relevant, you mean? Apr 6, 2017 at 14:49
  • 1
    Yup. The question asks for a way to get "a function call inside the program that will print the current call stack". The function you suggest "lists the program locations where the most-recently raised exception was raised and where it was propagated through function calls".
    – Clément
    Apr 6, 2017 at 17:22
  • @Clément If you do not use the name of the person you are talking to, they won't know you have posted a comment. Apr 7, 2017 at 11:56

4 Answers 4

11

I came to this question looking for the same thing, here's my solution

Printexc.get_callstack 5 |> Printexc.raw_backtrace_to_string

(Its actually a pretty good way to familiarize yourself with a new code base)

2
  • This is the only answer that actually addresses the original question. Works great! Remember to compile with ocamlc -g and run with env OCAMLRUNPARAM=b. Jul 15, 2021 at 19:51
  • Adding some extra context to help Google indexing: available since 4.01, the Printexc.get_callstack function includes this note: this function is not related to exceptions at all, despite being part of the Printexc module. This helps clarify why this is the right solution, despite the module name.
    – anol
    Feb 1 at 9:54
1

You can also use ocamldebug, with which you can start your code, compiled in bytecode. In this environment, Printexc.get_backtrace () are far more completes.

0

For native code one can use glibc's backtrace, though it may not print all stack frames correctly.

0

Unfortunately, the only way to get a backtrace from inside the code is when an exception is raised, you can then use Printexc.get_backtrace (). It won't give you though the names of the functions, just the locations in the code of what is in the stack, and only if OCaml was able to recover them...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.