堆栈溢出后,如何在 OCaml 中获得完整的、未截断的堆栈跟踪?

Clé*_*ent 5 stack-overflow debugging ocaml

堆栈溢出的 OCaml 堆栈跟踪被截断;例如,以下程序生成如下所示的堆栈跟踪:

\n\n
let rec f0 () = 1 + f1 ()\n    and f1 () = 1 + f2 ()\n    and f2 () = 1 + f3 ()\n    and f3 () = 1 + f4 ()\n    and f4 () = 1 + f5 ()\n    and f5 () = 1 + f5 ()\n\nlet _ =\n  Printexc.record_backtrace true;\n  f0 ()\n
Run Code Online (Sandbox Code Playgroud)\n\n
\n\n
Fatal error: exception Stack overflow\nRaised by primitive operation at file "stackoverflow.ml", line 6, characters 20-25\nCalled from file "stackoverflow.ml", line 6, characters 20-25\n\xe2\x80\xa6\nCalled from file "stackoverflow.ml", line 6, characters 20-25\n
Run Code Online (Sandbox Code Playgroud)\n\n

当错误不是堆栈溢出时与堆栈跟踪进行对比(将最终更改f5 ()failwith "Oops"

\n\n
Fatal error: exception Failure("Oops")\nRaised at file "pervasives.ml", line 30, characters 22-33\nCalled from file "stackoverflow.ml", line 6, characters 20-35\nCalled from file "stackoverflow.ml", line 5, characters 20-25\nCalled from file "stackoverflow.ml", line 4, characters 20-25\nCalled from file "stackoverflow.ml", line 3, characters 20-25\nCalled from file "stackoverflow.ml", line 2, characters 20-25\nCalled from file "stackoverflow.ml", line 1, characters 20-25\nCalled from file "stackoverflow.ml", line 10, characters 2-7\n
Run Code Online (Sandbox Code Playgroud)\n\n

如何防止 OCaml 截断堆栈跟踪?

\n

bth*_*hom 2

您可以使用 ocamldebug 来获取堆栈跟踪:

ocamlc stackoverflow.ml -o stackoverflow
ocamldebug stackoverflow
Run Code Online (Sandbox Code Playgroud)

然后在 ocamldebug 中:

(ocd) run
 [...] 
 Uncaught exception: Stack_overflow
(ocd) backstep
(ocd) bt
Run Code Online (Sandbox Code Playgroud)

您可能需要将调试标志添加到 ocamlc (-g) 以在调试器中执行额外的操作。