Stack traces: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
(Added zkl)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(48 intermediate revisions by 25 users not shown)
Line 2:
Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers.
 
This task calls for you to print out (in a manner considered suitable for the platform) the current call stack. The amount of information printed for each frame on the call stack is not constrained, but should include at least the name of the function or method at that level of the stack frame. You may explicitly add a call to produce the stack trace to the (example) code being instrumented for examination.
 
;Task:
The task should allow the program to continue after generating the stack trace. The task report here must include the trace from a sample program.
Print out (in a manner considered suitable for the platform) the current call stack.
<br clear=all>
 
The amount of information printed for each frame on the call stack is not constrained, but should include at least the name of the function or method at that level of the stack frame.
 
You may explicitly add a call to produce the stack trace to the (example) code being instrumented for examination.
 
The task should allow the program to continue after generating the stack trace.
 
The task report here must include the trace from a sample program.
<br><br>
 
=={{header|Ada}}==
{{works with|GNAT}}
 
The provided solution is specific to the [[GNAT]] Ada compiler. Further it is restricted to some platforms. See the description of the package GNAT.Traceback supplied with [[GNAT]]. The switch -g must be used in order to include debug information into the executable.
<syntaxhighlight lang Ada="ada">with Ada.Text_IO; use Ada.Text_IO;
with GNAT.Traceback; use GNAT.Traceback;
with GNAT.Traceback.Symbolic; use GNAT.Traceback.Symbolic;
 
procedure Test_Stack_Trace is
procedure Call_Stack is
Trace : GNAT.Traceback.Tracebacks_Array (1..1_000);
Length : Natural;
begin
GNAT.Traceback.Call_Chain (Trace, Length);
Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (Trace (1..Length)));
end Call_Stack;
 
Line 40 ⟶ 49:
begin
Outer (2,3,5);
end Test_Stack_Trace;</langsyntaxhighlight>
Sample output:
<pre>
Line 54 ⟶ 63:
7C817075 in ?? at ??:0
</pre>
 
=={{header|AutoHotkey}}==
The local, static, and global bindings are viewable using 'Listvars'
Line 60 ⟶ 70:
ListLines can be turned on or off... with:
<br> ListLines, On|Off
<langsyntaxhighlight lang="autohotkey">f()
return
Line 76 ⟶ 86:
msgbox, variable bindings
}
#Persistent</langsyntaxhighlight>
Output:
<langsyntaxhighlight lang="autohotkey">001: f()
006: Return,g()
011: ListLines (0.05)
Line 92 ⟶ 102:
0[1 of 3]: 0
ErrorLevel[1 of 3]: 0
</syntaxhighlight>
</lang>
 
=={{header|BASIC}}==
Line 173 ⟶ 183:
In order to be able to see the symbols, we need to link with an option telling to export symbols names in the dynamic section (for ELF and targets supporting it); for gcc, it means using the option <tt>-rdynamic</tt> (or <tt>-export-dynamic</tt> in the GNU linker). Otherwise we see only addresses. Static functions will always have their names "hidden".
 
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
Line 211 ⟶ 221:
outer(2,3,5);
return EXIT_SUCCESS;
}</langsyntaxhighlight>
 
Sample output on my system:
Line 241 ⟶ 251:
 
'''==> stack_trace.h <=='''
<syntaxhighlight lang="c">
<lang C>
/* stack_trace.c - macros for hinting/tracing where a program crashed
on a system _without_ any form of debugger.
Line 320 ⟶ 330:
#define END }
 
#endif</langsyntaxhighlight>
'''==> stack_trace.c <=='''
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stddef.h>
 
Line 406 ⟶ 416:
print_indent(); fprintf(stderr, "--- (depth %d) ---\n", stack_trace.stack.depth);
}
}</langsyntaxhighlight>
 
'''==> stack_trace_test.c <=='''
Line 412 ⟶ 422:
The following code demonstrates the usage of the macros. Note that the initial and last curly brackets have been changed to BEGIN(procedure_name) and END. This is sometimes called '''macro magic''' and is unfashionable.
 
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdlib.h>
 
Line 440 ⟶ 450:
stack_trace.on = FALSE;
RETURN(EXIT_SUCCESS);
END</langsyntaxhighlight>
 
{{out}}
Line 459 ⟶ 469:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Diagnostics;
 
Line 483 ⟶ 493:
Outer();
}
}</langsyntaxhighlight>
Sample output:
<syntaxhighlight lang="text">at Program.Inner()
at Program.Middle()
at Program.Outer()
at Program.Main()</langsyntaxhighlight>
 
=={{header|Clojure}}==
{{works with|Java|1.6+}}
 
[http://docs.oracle.com/javase/8/docs/api/java/lang/management/ThreadMXBean.html ThreadMXBean] can be used to show you the stack of all live threads.
 
<syntaxhighlight lang="clojure">
(doall
(map println (.dumpAllThreads (java.lang.management.ManagementFactory/getThreadMXBean) false false)))
</syntaxhighlight>
{{out}}
<pre>
#<ThreadInfo "nREPL-worker-26" Id=64 RUNNABLE
at sun.management.ThreadImpl.dumpThreads0(Native Method)
at sun.management.ThreadImpl.dumpAllThreads(ThreadImpl.java:446)
at user$eval1285.invoke(form-init6675235431801252432.clj:1)
at clojure.lang.Compiler.eval(Compiler.java:6619)
at clojure.lang.Compiler.eval(Compiler.java:6582)
at clojure.core$eval.invoke(core.clj:2852)
at clojure.main$repl$read_eval_print__6588$fn__6591.invoke(main.clj:259)
at clojure.main$repl$read_eval_print__6588.invoke(main.clj:259)
...
</pre>
 
=={{header|Common Lisp}}==
 
Line 495 ⟶ 529:
Here we use SWANK, which a component of SLIME, a Common Lisp IDE (it is the library loaded into the target Lisp system to enable interaction and remote debugging), to make use of its portable debugging facilities:
 
<langsyntaxhighlight lang="lisp">(swank-backend:call-with-debugging-environment
(lambda ()
(swank:backtrace 0 nil)))</langsyntaxhighlight>
 
Here are a few lines of the result when running under [[SBCL]], the rest is omitted since it's long and boring:
<langsyntaxhighlight lang="lisp">((0 "((LAMBDA (SWANK-BACKEND::DEBUGGER-LOOP-FN)) #<FUNCTION (LAMBDA #) {100459BBC9}>)")
(1 "(SB-INT:SIMPLE-EVAL-IN-LEXENV (SWANK-BACKEND:CALL-WITH-DEBUGGING-ENVIRONMENT (LAMBDA () (SWANK:BACKTRACE 0 NIL))) #<NULL-LEXENV>)")
(2 "(SWANK::EVAL-REGION \"(swank-backend:call-with-debugging-environment\\n (lambda ()\\n (swank:backtrace 0 nil)))\\n\\n\")")
(3 "((LAMBDA ()))") ...)</langsyntaxhighlight>
 
Note that this is a data structure containing the backtrace, not a format intended for presentation. In [[SBCL]], executing <code>(sb-debug:backtrace 7)</code> produces output like this (run from the SLIME-REPL, which is why it still contains mentions of SWANK):
 
<langsyntaxhighlight lang="lisp">CL-USER> (sb-debug:backtrace 7)
0: (SB-DEBUG::MAP-BACKTRACE
#<CLOSURE (LAMBDA (SB-DEBUG::FRAME)) {1193EFCD}>)[:EXTERNAL]
Line 523 ⟶ 557:
6: (SWANK::CALL-WITH-RETRY-RESTART
"Retry SLIME REPL evaluation request."
#<CLOSURE (LAMBDA ()) {1193EC4D}>)</langsyntaxhighlight>
 
SBCL's backtraces consist entirely of lists of the form <code>(<var>function-name</var> <var>args...</var>)</code>.
Line 530 ⟶ 564:
Compiled with the dmd compiler using the -g switch.
{{trans|Java}}
<langsyntaxhighlight lang="d">import std.stdio, core.runtime;
 
void inner() { defaultTraceHandler.writeln; }
Line 539 ⟶ 573:
outer;
"After the stack trace.".writeln;
}</langsyntaxhighlight>
{{out}}
<pre>0x00404FBE in core.sys.windows.stacktrace.StackTrace core.sys.windows.stacktrace.StackTrace.__ctor(uint, core.sys.windows.windows.CONTEXT*) at E:\dmd2\src\druntime\import\core\sys\windows\stacktrace.d(69)
Line 560 ⟶ 594:
=={{header|DWScript}}==
Stack traces can be obtained from exception objects
<langsyntaxhighlight lang="delphi">procedure Inner;
begin
try
Line 580 ⟶ 614:
end;
 
Outer;</langsyntaxhighlight>
Output:<pre>Inner [line: 4, column: 23]
Middle [line: 13, column: 4]
Outer [line: 18, column: 4]
[line: 21, column: 1]</pre>
 
=={{header|Elena}}==
{{trans|C#}}
ELENA 6.x :
<syntaxhighlight lang="elena">import extensions;
public singleton program
{
inner()
{
console.printLine(new CallStack())
}
middle()
{
self.inner()
}
outer()
{
self.middle()
}
// program entry point
function()
{
program.outer()
}
}</syntaxhighlight>
{{out}}
<pre>
sandbox'program.inner[1]:sandbox.l(7)
sandbox'program.middle[1]:sandbox.l(12)
sandbox'program.outer[1]:sandbox.l(17)
sandbox'program.function:#invoke:sandbox.l(23)
system'$private'entry.function:#invoke:app.l(5)
system'$private'entrySymbol#sym:app.l(44)
</pre>
 
=={{header|Elixir}}==
{{trans|Erlang}}
<syntaxhighlight lang="elixir">defmodule Stack_traces do
def main do
{:ok, a} = outer
IO.inspect a
end
defp outer do
{:ok, a} = middle
{:ok, a}
end
defp middle do
{:ok, a} = inner
{:ok, a}
end
defp inner do
try do
throw(42)
catch 42 -> {:ok, :erlang.get_stacktrace}
end
end
end
 
Stack_traces.main</syntaxhighlight>
 
{{out}}
<pre>
[{Stack_traces, :inner, 0, [file: 'stack_trace.exs', line: 19]},
{Stack_traces, :middle, 0, [file: 'stack_trace.exs', line: 13]},
{Stack_traces, :outer, 0, [file: 'stack_trace.exs', line: 8]},
{Stack_traces, :main, 0, [file: 'stack_trace.exs', line: 3]},
{:elixir_compiler, :dispatch_loaded, 6,
[file: 'src/elixir_compiler.erl', line: 125]},
{:elixir_lexical, :run, 3, [file: 'src/elixir_lexical.erl', line: 16]},
{:elixir_compiler, :quoted, 3, [file: 'src/elixir_compiler.erl', line: 30]},
{Code, :require_file, 2, [file: 'lib/code.ex', line: 363]}]
</pre>
 
=={{header|Erlang}}==
{{trans|Java}}
Stack traces only can be obtained inside a catch block. Additionally, it doesn't work for tail calls.
<langsyntaxhighlight lang="erlang">-module(stack_traces).
 
-export([main/0]).
Line 606 ⟶ 719:
 
inner() ->
try throw(42) catch 42 -> {ok,erlang:get_stacktrace()} end.</langsyntaxhighlight>
{{out}}
Output:<pre>[{stack_traces,inner,0,[{file,"stack_traces.erl"},{line,18}]},
<pre>[{stack_traces,inner,0,[{file,"stack_traces.erl"},{line,18}]},
{stack_traces,middle,0,[{file,"stack_traces.erl"},{line,14}]},
{stack_traces,outer,0,[{file,"stack_traces.erl"},{line,10}]},
Line 616 ⟶ 730:
=={{header|F_Sharp|F#}}==
{{trans|C#}}
<langsyntaxhighlight lang="fsharp">open System.Diagnostics
 
type myClass() =
Line 627 ⟶ 741:
let that = new myClass()
that.outer()
0</langsyntaxhighlight>
Output
<pre> at Rosetta.myClass.inner()
Line 633 ⟶ 747:
at Rosetta.myClass.outer()
at Rosetta.main(String[] args)</pre>
 
=={{header|Factor}}==
This stack trace shows the listener — Factor's Read-Eval-Print-Loop. The current execution point in each call frame is indicated by <code>=></code>. Press ctrl+w in the listener to walk through the call stack one step at a time and watch how it affects the data stack. You can even step backward in most cases. This is handy for debugging.
<syntaxhighlight lang="factor">USE: prettyprint
get-callstack callstack.</syntaxhighlight>
{{out}}
<pre>
(U)
Quotation: [ set-namestack init-catchstack self quot>> call => stop ]
(O)
Word: listener-thread
(O)
Word: listener
(O)
Word: (listener)
(O)
Word: listener-step
(U)
Quotation: [
[ ~quotation~ dip swap ~quotation~ dip ] dip swap
[ call get-datastack ] dip => swap [ set-datastack ] dip
]
</pre>
 
=={{header|Forth}}==
Line 638 ⟶ 775:
 
{{works with|4tH|3.60.0}}
<langsyntaxhighlight lang="forth">[UNDEFINED] R.S [IF]
\ Return stack counterpart of DEPTH
\ Note the STACK-CELLS correction is there to hide RDEPTH itself
Line 651 ⟶ 788:
BEGIN DUP WHILE ROT DUP . >R 1- REPEAT DROP
THEN ." (TORS) " DROP >R ;
[THEN]</langsyntaxhighlight>
 
=={{header|Fortran}}==
Fortran provides nothing of the sort as a language feature. A given compiler may (possibly via an option) record information in the code file that when a fatal error such as divide-by-zero is caught, allows the error message to name the routine in which the error occurred, possibly identifying the source line and perhaps even the sequence of routines that were invoked to get there. Otherwise, a routine has no information whereby it might identify its caller - or for that matter, itself. Some compilers might make available special routines, but, there is no such requirement in the standard. Outside of Fortran's lack of standardised access, some systems such as TaskInfo on Windows can show a task's current call stack (updated each time TaskInfo re-samples, say every four seconds), possibly including the names of the called routines. Watching this being updated as the task runs a lengthy computation gives hints that otherwise could be provided via execution profiling and a lot more effort.
 
Otherwise, it is up to the programmer. For instance, on entry to ''every'' routine, <code>CALL SUBIN("''name''")</code> and on exit, ''without fail'', <code>CALL SUBOUT("''name''")</code> which routines maintain a ... stack of names, and further can count invocations, though perhaps not for heavily-used routines - trials suggest that around ten million SUBIN calls consume about a second of cpu time. Add to this the judicious use of a routine <code>CALL STATE("''activity description''")</code> similarly using a stack (the stack pointer being maintained by SUBIN/SUBOUT) not only provides interesting documentation in the source but also, should there be a disaster, <code>CALL CROAK("''dismayed message''")</code> can be used to end a run, routine CROAK of course displaying the current stack with at each level the declared activity message before the final STOP. A similar routine could be invoked to display the current stack state without a STOP as some sort of status report. With this protocol in place, the routine to present trace output can name its caller (and, the caller of that) to provide some context for the bewildering output.
 
Here for example is a run of such a programme, called Gnash (for New Zealand's national collection of half-hourly electricity data) that accepts certain commands and in particular a command "croak". A log of input and output is maintained, echoing what appears on the screen. Thus, the programme requests the next input after prompting "Gnash:" and that input is the command "croak" followed by some text...
<pre>
Gnash: croak Life is troubled
Goodbye, cruel world!
Routine XeqACard croaks: Life is troubled
...from XeqACard Confronting croak Life is troubled
...from Attack some input
...from Gnash Gnash gnashing
Omitted exit from level 3:XeqACard
Omitted exit from level 2:Attack
</pre>
So, Gnash has invoked ATTACK to deal with input commands, as if cards are being read. ATTACK states that it is dealing with some input (possibly from a script file but in this case the keyboard), and invokes XeqACard to do so. It states that it is confronting some text, then invokes the appropriate command handler - which invokes CROAK, which unwinds the stack. Its final act is <code>STOP "I STOP now. Farewell..." !Whatever pit I was in, I'm gone.</code> which of course is not written to the log file and unless you're using a DOS-style session, the window will be closed before you can read it.
 
Should a fatal error be declared by the run-time system, none of this will happen, but if while running, some unrecoverable or a should-never-happen but I'll check anyway type of problem be noted, then a possibly informative output will follow.
 
=={{header|FreeBASIC}}==
Code extracted from FreeBAsic Forum
[https://freebasic.net/forum/viewtopic.php?t=31371 https://freebasic.net/forum/viewtopic.php?t=31371]
<syntaxhighlight lang="vb">#include "windows.bi"
 
Private Function Fn2() As Long
Dim frames(0 To 60) As Any Ptr
Dim framesPtr As Any Ptr Ptr = @frames(0)
Dim hash As DWORD
Dim As Long caught = CaptureStackBackTrace(0, 61, framesPtr, @hash)
Print Using "Caught & frames using stack capture"; caught
For i As Long = 0 To caught - 1
Print Using "&) &"; caught - i; Hex(frames(i))
Next
Return caught
End Function
 
Private Sub Fn1(num As Ulong)
Dim As Long numFn2 = Fn2()
Print Using "Fn2 returned & with num = &"; numFn2; num
End Sub
 
Fn1(87)
Sleep</syntaxhighlight>
{{out}}
<pre>Caught 7 frames using stack capture
7) 4016FE
6) 40185E
5) 4015BA
4) 4013B4
3) 40150B
2) 7FFBD6AC7614
1) 7FFBD7B226A1
Fn2 returned 7 with num = 87</pre>
 
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
"fmt"
"runtime/debug"
)
 
func main() {
stackTrace := make([]byte, 1024)
// to print it to standard error
n := runtime.Stack(stackTrace, true)
debug.PrintStack()
stackTrace = stackTrace[:n]
// alternately to get it in a variable:
fmt.Printf("%s\n", stackTrace)
stackTrace := debug.Stack()
fmt.Printf("(%d bytes)\n", len(stackTrace))
}</langsyntaxhighlight>
outputs:
<pre>
goroutine 16 [running]:
/home/foo/test/test.go:12 (0x8048c26)
main: debug.PrintStackmain()
/tmpfs/gosandbox-efa5a722_5cfcad46_bebc14b4_0486dec5_bd9e34fc/prog.go:10 +0xa0
/home/foo/go/hg/src/pkg/runtime/386/asm.s:93 (0x8049b72)
 
mainstart: CALL main·main(SB)
goroutine 19 [runnable]:
/home/foo/go/hg/src/pkg/runtime/proc.c:149 (0x80531de)
runfinq()
goexit: runtime·goexit(void)
/tmp/sandbox/go/src/pkg/runtime/mgc0.c:2606
(227 bytes)
runtime.goexit()
/tmp/sandbox/go/src/pkg/runtime/proc.c:1445
 
(259 bytes)
</pre>
 
=={{header|Groovy}}==
Solution:
<langsyntaxhighlight lang="groovy">def rawTrace = { Thread.currentThread().stackTrace }</langsyntaxhighlight>
 
Test: (demonstrates, among other things, continued execution after generating stack trace)
<langsyntaxhighlight lang="groovy">def trace = rawTrace().collect {
def props = it.properties
def keys = (it.properties.keySet() - (new Object().properties.keySet()))
Line 697 ⟶ 894:
trace.each {
propNames.eachWithIndex{ name, i -> printf("%-${propWidths[i]}s ", it[name].toString()) }; println ''
}</langsyntaxhighlight>
 
Output:
Line 771 ⟶ 968:
{{libheader|Unicon Code Library}}
[http://tapestry.tucson.az.us/unilib/pack_Utils.html the following code for buildStackTrace in Utils is taken verbatim and shown below the main program]
<syntaxhighlight lang="unicon">
<lang Unicon>
import Utils # for buildStackTrace
 
Line 787 ⟶ 984:
# Using 1 as argument omits the trace of buildStackTrace itself
every write("\t",!buildStackTrace(1))
end</langsyntaxhighlight>
 
<syntaxhighlight lang="unicon">#<p>
<lang Unicon>#<p>
# Compute the current stack trace. Starting at level <i>n</i> above
# the current procedure. Here, <i>n</i> defaults to 0, which will
Line 810 ⟶ 1,007:
}
return L
end</langsyntaxhighlight>
 
The output of this example is:
Line 827 ⟶ 1,024:
 
To enable suspension and record subsequent stack frames:
<syntaxhighlight lang ="j"> 13!:0]1</langsyntaxhighlight>
 
To retrieve a current stack trace:
<syntaxhighlight lang ="j"> 13!:13''</langsyntaxhighlight>
 
See also: http://www.jsoftware.com/help/dictionary/dx013.htm
Line 836 ⟶ 1,033:
Example:
 
<langsyntaxhighlight lang="j"> f=:g
g=:13!:13 bind ''
f 7 NB. empty stack trace because debugging has not been enabled
Line 849 ⟶ 1,046:
│ │ │ │ │ │││7││ │ │
│ │ │ │ │ ││└─┘│ │ │
└─┴─┴─┴─┴─────────────┴┴───┴──┴─┘</langsyntaxhighlight>
 
Technical note: the stack trace is not displayed, here, until after the stack has been discarded. This is because we have returned the stack trace as a result and relied on J's implicit display of the result of an expression to display the stack trace.
Line 855 ⟶ 1,052:
=={{header|Java}}==
{{works with|Java|1.5+}}
<langsyntaxhighlight lang="java5">public class StackTracer {
public static void printStackTrace() {
StackTraceElement[] elems = Thread.currentThread().getStackTrace();
Line 865 ⟶ 1,062:
}
}
}</langsyntaxhighlight>
Demonstration code:
<langsyntaxhighlight lang="java5">public class StackTraceDemo {
static void inner() {
StackTracer.printStackTrace();
Line 880 ⟶ 1,077:
outer();
}
}</langsyntaxhighlight>
Output:
<pre>Stack trace:
Line 891 ⟶ 1,088:
There is no standard way to do this, but some implementations provide it.<br />
{{works with|Firefox}}
<langsyntaxhighlight lang="javascript">try {
throw new Error;
} catch(e) {
alert(e.stack);
}</langsyntaxhighlight>
 
The following version works in many browsers but it infinitely loops when there is recursion:
<langsyntaxhighlight lang="javascript">function foo () {
var stack = "Stack trace:";
for (var f = arguments.callee // current function
Line 906 ⟶ 1,103:
alert(stack);
}
foo();</langsyntaxhighlight>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
 
<syntaxhighlight lang="julia">f() = g()
g() = println.(stacktrace())
 
f()</syntaxhighlight>
 
{{out}}
<pre>g() at Stack_traces.jl:5
f() at Stack_traces.jl:4
include_string(::String, ::String) at loading.jl:515
include_string(::Module, ::String, ::String) at Compat.jl:464
(::Atom.##57#60{String,String})() at eval.jl:74
withpath(::Atom.##57#60{String,String}, ::String) at utils.jl:30
withpath(::Function, ::String) at eval.jl:38
macro expansion at eval.jl:72 [inlined]
(::Atom.##56#59{Dict{String,Any}})() at task.jl:80</pre>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// version 1.1.2 (stacktrace.kt which compiles to StacktraceKt.class)
 
fun myFunc() {
println(Throwable().stackTrace.joinToString("\n"))
}
 
fun main(args:Array<String>) {
myFunc()
println("\nContinuing ... ")
}</syntaxhighlight>
 
{{out}}
<pre>
StacktraceKt.myFunc(stacktrace.kt:4)
StacktraceKt.main(stacktrace.kt:8)
 
Continuing ...
</pre>
 
=={{header|Lang}}==
<syntaxhighlight lang="lang">
# fn.getStackTrace() returns a text-based stack trace
fp.printStackTrace = () -> fn.println(fn.getStackTrace())
 
# Example
fp.f1 = () -> {
fn.println(F1:)
fp.printStackTrace()
}
fp.f2 = () -> {
fn.println(F2:)
fp.printStackTrace()
fp.f1()
}
fp.f2()
 
fn.combA0(fp.f2)
 
# Partially called combinator functions' names are represented as "<comb...-func(...)>"
fn.combA(fn.combC(fn.combAE(), x), fp.f2)
</syntaxhighlight>
{{out}}
The file paths were redacted. If ":x" is outputted as the line number, no line number information is available (e.g. If Lang is implemented with an interpreter, predefined functions are written in the host language)
<pre>
F2:
at "[redacted]:x" in function "getStackTrace"
at "[redacted]:2" in function "fp.printStackTrace"
at "[redacted]:11" in function "fp.f2"
at "[redacted]:14" in function "main"
F1:
at "[redacted]:x" in function "getStackTrace"
at "[redacted]:2" in function "fp.printStackTrace"
at "[redacted]:7" in function "fp.f1"
at "[redacted]:12" in function "fp.f2"
at "[redacted]:14" in function "main"
F2:
at "[redacted]:x" in function "getStackTrace"
at "[redacted]:2" in function "fp.printStackTrace"
at "[redacted]:11" in function "fp.f2"
at "[redacted]:x" in function "combA0"
at "[redacted]:16" in function "main"
F1:
at "[redacted]:x" in function "getStackTrace"
at "[redacted]:2" in function "fp.printStackTrace"
at "[redacted]:7" in function "fp.f1"
at "[redacted]:12" in function "fp.f2"
at "[redacted]:x" in function "combA0"
at "[redacted]:16" in function "main"
F2:
at "[redacted]:x" in function "getStackTrace"
at "[redacted]:2" in function "fp.printStackTrace"
at "[redacted]:11" in function "fp.f2"
at "[redacted]:x" in function "<combAE-func()>"
at "[redacted]:x" in function "<combC-func(<combAE-func()>, <arg>)>"
at "[redacted]:x" in function "combA"
at "[redacted]:19" in function "main"
F1:
at "[redacted]:x" in function "getStackTrace"
at "[redacted]:2" in function "fp.printStackTrace"
at "[redacted]:7" in function "fp.f1"
at "[redacted]:12" in function "fp.f2"
at "[redacted]:x" in function "<combAE-func()>"
at "[redacted]:x" in function "<combC-func(<combAE-func()>, <arg>)>"
at "[redacted]:x" in function "combA"
at "[redacted]:19" in function "main"
</pre>
 
=={{header|Lasso}}==
By default Lasso tracks the file path, line and column numbers. You can create a trace method to track type and method names illustrated below or use one of the public libraries like L-Debug [https://github.com/zeroloop/l-debug].
 
<langsyntaxhighlight Lassolang="lasso">// Define our own trace method
define trace => {
local(gb) = givenblock
Line 933 ⟶ 1,238:
)
return #gb()
}</langsyntaxhighlight>
 
;Use Trace:
 
<langsyntaxhighlight Lassolang="lasso">define stackexample => type {
public oncreate => trace => { return self }
public inner => trace => { }
Line 944 ⟶ 1,249:
}
 
stackexample->outer</langsyntaxhighlight>
 
{{out}}
Line 954 ⟶ 1,259:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function Inner( k )
print( debug.traceback() )
print "Program continues..."
Line 967 ⟶ 1,272:
end
 
Outer( 2, 3, 5 )</langsyntaxhighlight>
<pre>stack traceback:
./prog:4: in function 'Inner'
Line 976 ⟶ 1,281:
Program continues...</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Built-in function Stack does the task, example I:
<langsyntaxhighlight Mathematicalang="mathematica">f[g[1, Print[Stack[]]; 2]]</langsyntaxhighlight>
prints, gives back:
<langsyntaxhighlight Mathematicalang="mathematica">{f,g,CompoundExpression,Print}
f[g[1, 2]]</langsyntaxhighlight>
Example II:
<langsyntaxhighlight Mathematicalang="mathematica">f[g[1, Print[Stack[_]]; 2]]</langsyntaxhighlight>
prints, gives back:
<langsyntaxhighlight Mathematicalang="mathematica">{f[g[1,Print[Stack[_]];2]],g[1,Print[Stack[_]];2],Print[Stack[_]];2,Print[Stack[_]]}
f[g[1, 2]]</langsyntaxhighlight>
Related and similar functions are: Trace, TracePrint, TraceScan,TraceDialog, Monitor, StackInhibit, StackBegin, StackComplete. In the manual look for 'guide/SymbolicExecutionHistory'.
 
=={{header|Nanoquery}}==
__calls__ contains a list that represents a trace of calls that have been made.
<syntaxhighlight lang="nanoquery">def print_stack()
global __calls__
 
println "stack trace:"
for i in range(len(__calls__) - 2, 0)
println "\t" + __calls__[i]
end
end
 
print_stack()
println
 
for i in range(1, 1)
print_stack()
end
 
println
println "The program would continue."</syntaxhighlight>
{{out}}
<pre>stack trace:
<global>:10
 
stack trace:
<for>:1
<global>:13
 
The program would continue.</pre>
 
=={{header|NetRexx}}==
{{trans|Java}}
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 1,013 ⟶ 1,348:
j_ = j_ + 2
end i_
</syntaxhighlight>
</lang>
'''Output:'''
<pre>
Line 1,022 ⟶ 1,357:
RStackTraces.inner
</pre>
 
=={{header|Nim}}==
In (normal) debug builds stacktraces are enabled, while in release builds stacktraces are disabled by default, but can be enabled like this: <code>nim c -d:release --stacktrace:on --linetrace:on file.nim</code>
<syntaxhighlight lang="nim">proc g() =
# Writes the current stack trace to stderr.
writeStackTrace()
# Or fetch the stack trace entries for the current stack trace:
echo "----"
for e in getStackTraceEntries():
echo e.filename, "@", e.line, " in ", e.procname
 
proc f() =
g()
 
f()</syntaxhighlight>
{{out}}
For a release build:
<pre>Traceback (most recent call last)
stack_traces.nim(12) stack_traces
stack_traces.nim(10) f
stack_traces.nim(3) g
----
stack_traces.nim@12 in stack_traces
stack_traces.nim@10 in f
stack_traces.nim@6 in g
</pre>
In a debug build the stacktrace contains the full path to the source.
 
=={{header|Objective-C}}==
<langsyntaxhighlight lang="objc">#include <execinfo.h>
 
void *frames[128];
Line 1,032 ⟶ 1,394:
NSLog(@"%s", symbols[i]);
}
free(symbols);</langsyntaxhighlight>
 
Or in Mac OS X 10.6+:
<langsyntaxhighlight lang="objc">NSArray *symbols = [NSThread callStackSymbols];
for (NSString *symbol in symbols) {
NSLog(@"%@", symbol);
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
{{works with|OCaml|3.11+}}
<langsyntaxhighlight lang="ocaml">let div a b = a / b
 
let () =
Line 1,049 ⟶ 1,411:
prerr_endline(Printexc.to_string e);
Printexc.print_backtrace stderr;
;;</langsyntaxhighlight>
 
outputs:
Line 1,060 ⟶ 1,422:
 
Then the code doesn't need additional statements:
<langsyntaxhighlight lang="ocaml">let div a b = a / b
 
let () =
let _ = div 3 0 in ()
;;</langsyntaxhighlight>
outputs:
Fatal error: exception Division_by_zero
Raised at file "test.ml", line 4, characters 10-17
 
=={{header|Oforth}}==
 
Stack trace is only available :
 
1) When an exception is raised
 
2) And when oforth debug mode is set, using --D command line option.
 
Otherwise no stack trace is available nor printed.
 
<syntaxhighlight lang="oforth">: f1 Exception throw("An exception") ;
Integer method: f2 self f1 ;
: f3 f2 ;
: f4 f3 ;
 
10 f4</syntaxhighlight>
 
{{out}}
<pre>
[1:interpreter] Exception : An exception
Into Method #throw self = (Exception) An exception
Into Method #throw self = (Class) Exception
Into Function #f1
Into Method #f2 self = (Integer) 10
Into Function #f3
</pre>
 
=={{header|OxygenBasic}}==
<langsyntaxhighlight lang="oxygenbasic">
'32bit x86
 
Line 1,151 ⟶ 1,540:
0017FE1C 07 00000000
*/
</syntaxhighlight>
</lang>
 
=={{header|Oz}}==
System exceptions contain the current stack at the nested feature <code>debug.stack</code>. For example:
<langsyntaxhighlight lang="oz">declare
proc {Test}
_ = 1 div 0
Line 1,164 ⟶ 1,553:
catch E then
{Inspect E}
end</langsyntaxhighlight>
Output:
[[File:Oz_stacktrace1.png|center|Stack trace of a system exception in Oz.]]
Line 1,171 ⟶ 1,560:
 
To access the stack trace directly, you can use the undocumented internal Debug module. Its <code>getTaskStack</code> function takes a thread, a depth value and a boolean "verbose" flag. It returns a list of stack frames. Example:
<langsyntaxhighlight lang="oz">%% make sure that simple function calls are not optimized away
\switch +controlflowinfo
 
Line 1,185 ⟶ 1,574:
end
in
{F}</langsyntaxhighlight>
 
Output:
Line 1,191 ⟶ 1,580:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use Carp 'cluck';
 
sub g {cluck 'Hello from &g';}
sub f {g;}
 
f;</langsyntaxhighlight>
 
This prints:
Line 1,203 ⟶ 1,592:
main::g() called at Print a Stack Trace line 4
main::f() called at Print a Stack Trace line 6</pre>
 
=={{header|Perl 6}}==
=={{header|Phix}}==
{{works with|Rakudo|2013-03-03}}
There no standard method of obtaining a stack trace mid-run (as yet, non-fatally that is), but we can quickly cobble something together:
<lang perl6>sub g { say Backtrace.new.concise }
<!--<syntaxhighlight lang="phix">(notonline)-->
sub f { g }
<span style="color: #008080;">constant</span> <span style="color: #000000;">W</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">machine_word</span><span style="color: #0000FF;">(),</span>
sub MAIN { f }</lang>
<span style="color: #0000FF;">{</span><span style="color: #000000;">RTN</span><span style="color: #0000FF;">,</span><span style="color: #000000;">PREVEBP</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">W</span><span style="color: #0000FF;">=</span><span style="color: #000000;">4</span><span style="color: #0000FF;">?{</span><span style="color: #000000;">8</span><span style="color: #0000FF;">,</span><span style="color: #000000;">20</span><span style="color: #0000FF;">}:{</span><span style="color: #000000;">16</span><span style="color: #0000FF;">,</span><span style="color: #000000;">40</span><span style="color: #0000FF;">})</span>
{{out}}
<pre> in sub g at bt:1
<span style="color: #008080;">procedure</span> <span style="color: #000000;">show_stack</span><span style="color: #0000FF;">()</span>
in sub f at bt:2
<span style="color: #004080;">sequence</span> <span style="color: #000000;">symtab</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">symtabN</span>
in sub MAIN at bt:3</pre>
<span style="color: #004080;">integer</span> <span style="color: #000000;">rtn</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">prev_ebp</span>
#ilASM{
[32]
lea edi,[symtab]
call :%opGetST -- [edi]=symtab (ie our local:=the real symtab)
mov edi,[ebp+20] -- prev_ebp
mov eax,[edi+8] -- calling routine no
mov [rtn],eax
mov eax,edi
lea edi,[prev_ebp]
call :%pStoreMint
[64]
lea rdi,[symtab]
call :%opGetST -- [rdi]=symtab (ie our local:=the real symtab)
mov rdi,[rbp+40] -- prev_ebp
mov rax,[rdi+16] -- calling routine no
mov [rtn],rax
mov rax,rdi
lea rdi,[prev_ebp]
call :%pStoreMint
[]
}
<span style="color: #008080;">while</span> <span style="color: #000000;">rtn</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">21</span> <span style="color: #008080;">do</span> <span style="color: #000080;font-style:italic;">-- (T_maintls, main top level routine, always present)</span>
<span style="color: #000000;">symtabN</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">symtab</span><span style="color: #0000FF;">[</span><span style="color: #000000;">rtn</span><span style="color: #0000FF;">]</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">symtabN</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
<span style="color: #000000;">prev_ebp</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">peekNS</span><span style="color: #0000FF;">(</span><span style="color: #000000;">prev_ebp</span><span style="color: #0000FF;">+</span><span style="color: #000000;">PREVEBP</span><span style="color: #0000FF;">,</span><span style="color: #000000;">W</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">rtn</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">peekNS</span><span style="color: #0000FF;">(</span><span style="color: #000000;">prev_ebp</span><span style="color: #0000FF;">+</span><span style="color: #000000;">RTN</span><span style="color: #0000FF;">,</span><span style="color: #000000;">W</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">three</span><span style="color: #0000FF;">(</span><span style="color: #004080;">bool</span> <span style="color: #000000;">die</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">die</span> <span style="color: #008080;">then</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">9</span><span style="color: #0000FF;">/</span><span style="color: #000000;">0</span>
<span style="color: #008080;">else</span>
<span style="color: #000000;">show_stack</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">two</span><span style="color: #0000FF;">(</span><span style="color: #004080;">bool</span> <span style="color: #000000;">die</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">three</span><span style="color: #0000FF;">(</span><span style="color: #000000;">die</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">one</span><span style="color: #0000FF;">(</span><span style="color: #004080;">bool</span> <span style="color: #000000;">die</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">two</span><span style="color: #0000FF;">(</span><span style="color: #000000;">die</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">one</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">routine_id</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"dummy"</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- see note below</span>
<span style="color: #000000;">one</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
During compilation, the symbol table entries hold an integer ternary tree index rather than a string name, and normally
things are left like that during interpretation (the proper string names are always written out when an executable is
created) unless and until a fatal error occurs, or the compiler has evidence that they might be needed, such as that
unresolved routine_id("dummy"). The -1 in the output below is that call failing to find any such routine.
{{Out}}
<pre>
"three"
"two"
"one"
-1
 
C:\Program Files (x86)\Phix\e01.exw:59 in procedure three()
attempt to divide by 0
die = 1
... called from C:\Program Files (x86)\Phix\e01.exw:66 in procedure two()
die = 1
... called from C:\Program Files (x86)\Phix\e01.exw:70 in procedure one()
die = 1
... called from C:\Program Files (x86)\Phix\e01.exw:75
 
Global & Local Variables
 
--> see C:\Program Files (x86)\Phix\ex.err
Press Enter...
</pre>
The first half (up to the -1) is the output from show_stack_trace(), the rest is standard fatal error diagnostics.<br>
For more details of how the latter is actually produced, refer to builtins\VM\pDiagN.e - in particular the conversion of
raw addresses into source code line numbers is not trivial (and not worth trying to replicate here). In fact I didn't just
type all that #ilASM gunk above in, but instead copied it from other source files in builtins\VM.
 
Alternatively, but only when interpreting (whereas the above works as shown both when interpreting and pre-compiled), the debugger is
started with the much saner
<!--<syntaxhighlight lang="phix">-->
<span style="color: #008080;">trace</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
though as yet it offers no means of examining the stack trace (resume-ably), the above suggests it should be relative easy to add.
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php
class StackTraceDemo {
static function inner() {
Line 1,228 ⟶ 1,705:
 
StackTraceDemo::outer();
?></langsyntaxhighlight>
 
<pre>#0 StackTraceDemo::inner() called at [/home/cweiske/Dev/cvs/test/php-stacktrace.php:7]
#1 StackTraceDemo::middle() called at [/home/cweiske/Dev/cvs/test/php-stacktrace.php:10]
#2 StackTraceDemo::outer() called at [/home/cweiske/Dev/cvs/test/php-stacktrace.php:14]</pre>
 
=={{header|PL/I}}==
<lang PL/I>
/* The SNAP option in the ON statement is sufficient to obtain */
/* a traceback. The SYSTEM option specifies that standard */
/* system action is to occur, which resume execution after the */
/* SIGNAL statement. */
on condition(traceback) snap system;
...
signal condition(traceback);
</lang>
 
=={{header|PicoLisp}}==
Line 1,251 ⟶ 1,717:
 
As this mechanism uses 'let' to hold the stack frames, it is robust also across catch/throw, coroutines and error handling.
<langsyntaxhighlight PicoLisplang="picolisp">(off "Stack")
 
(de $$ "Prg"
Line 1,286 ⟶ 1,752:
(de dumpStack ()
(more (reverse (cdr "Stack")))
T )</langsyntaxhighlight>
Test:
<langsyntaxhighlight PicoLisplang="picolisp">(de foo (A B)
(let C 3
(bar (inc 'A) (inc 'B) (inc 'C)) ) )
Line 1,296 ⟶ 1,762:
(! println A B C) ) ) # Set a breakpoint before (println A B C)
 
(stackAll)</langsyntaxhighlight>
<pre>: (foo 1 2) # Call 'foo'
(println A B C) # Stopped at breakpoint in 'bar'
Line 1,307 ⟶ 1,773:
-> 9
:</pre>
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
/* The SNAP option in the ON statement is sufficient to obtain */
/* a traceback. The SYSTEM option specifies that standard */
/* system action is to occur, which resume execution after the */
/* SIGNAL statement. */
on condition(traceback) snap system;
...
signal condition(traceback);
</syntaxhighlight>
 
=={{header|PureBasic}}==
The [http://www.purebasic.com/documentation/debugger/showcallstack.html ShowCallstack()]command opens a interactive display allowing viewing of the procedures in the calling path an all their local variables.
<langsyntaxhighlight PureBasiclang="purebasic">Procedure Three()
a=7
ShowCallstack()
Line 1,326 ⟶ 1,803:
EndProcedure
 
One()</langsyntaxhighlight>
 
=={{header|Python}}==
 
See the [http://docs.python.org/library/traceback.html traceback] module
<langsyntaxhighlight lang="python">import traceback
 
def f(): return g()
def g(): traceback.print_stack()
 
f()</langsyntaxhighlight>
 
Sample output from a session in the Idle IDE:
Line 1,351 ⟶ 1,828:
def g(): traceback.print_stack()
</pre>
 
=={{header|Quackery}}==
 
Quackery has two system stacks, the call or return stack and a data stack. The words <code>echoreturn</code> and <code>echostack</code> display the current state of them. Each call to a word or nest places two entries on the return stack, a pointer to the word or nest, and an index into that word or nest. These are displayed as the name of the word, or <code>[...]</code> for an unnamed nest, and the index into the word or nest as an integer. Pairs of entries are displayed wrapped in braces, e.g. <code>{shell 5}</code>.
 
This is illustrated with a Quackery shell dialogue. The Quackery shell is written in Quackery, and as can be seen, occupies five pairs of entries on the return stack. After each interaction with the user the data stack is automatically displayed. Here the user opens the Quackery shell, displays the return stack, defines a naive recursive Fibonacci word that displays the return and data stack at the start of each call, and uses it to compute and display the fifth Fibonacci number (5).
 
<pre> > quackery
 
Welcome to Quackery.
 
Enter "leave" to leave the shell.
 
Building extensions.
 
/O> echoreturn
...
{[...] 0} {quackery 1} {[...] 11} {shell 5} {quackery 1} {[...] 0}
Stack empty.
 
/O> [ cr echoreturn
... cr echostack
... dup 2 < if done
... dup 1 - swap 2 -
... recurse swap recurse + ] is fib
...
 
Stack empty.
 
/O> 5 fib echo
...
 
{[...] 0} {quackery 1} {[...] 11} {shell 5} {quackery 1} {[...] 1} {fib 1}
Stack: 5
 
{[...] 0} {quackery 1} {[...] 11} {shell 5} {quackery 1} {[...] 1} {fib 15} {recurse 1} {fib 1}
Stack: 4 3
 
{[...] 0} {quackery 1} {[...] 11} {shell 5} {quackery 1} {[...] 1} {fib 15} {recurse 1} {fib 15} {recurse 1} {fib 1}
Stack: 4 2 1
 
{[...] 0} {quackery 1} {[...] 11} {shell 5} {quackery 1} {[...] 1} {fib 15} {recurse 1} {fib 17} {recurse 1} {fib 1}
Stack: 4 1 2
 
{[...] 0} {quackery 1} {[...] 11} {shell 5} {quackery 1} {[...] 1} {fib 15} {recurse 1} {fib 17} {recurse 1} {fib 15} {recurse 1} {fib 1}
Stack: 4 1 1 0
 
{[...] 0} {quackery 1} {[...] 11} {shell 5} {quackery 1} {[...] 1} {fib 15} {recurse 1} {fib 17} {recurse 1} {fib 17} {recurse 1} {fib 1}
Stack: 4 1 0 1
 
{[...] 0} {quackery 1} {[...] 11} {shell 5} {quackery 1} {[...] 1} {fib 17} {recurse 1} {fib 1}
Stack: 2 4
 
{[...] 0} {quackery 1} {[...] 11} {shell 5} {quackery 1} {[...] 1} {fib 17} {recurse 1} {fib 15} {recurse 1} {fib 1}
Stack: 2 3 2
 
{[...] 0} {quackery 1} {[...] 11} {shell 5} {quackery 1} {[...] 1} {fib 17} {recurse 1} {fib 15} {recurse 1} {fib 15} {recurse 1} {fib 1}
Stack: 2 3 1 0
 
{[...] 0} {quackery 1} {[...] 11} {shell 5} {quackery 1} {[...] 1} {fib 17} {recurse 1} {fib 15} {recurse 1} {fib 17} {recurse 1} {fib 1}
Stack: 2 3 0 1
 
{[...] 0} {quackery 1} {[...] 11} {shell 5} {quackery 1} {[...] 1} {fib 17} {recurse 1} {fib 17} {recurse 1} {fib 1}
Stack: 2 1 3
 
{[...] 0} {quackery 1} {[...] 11} {shell 5} {quackery 1} {[...] 1} {fib 17} {recurse 1} {fib 17} {recurse 1} {fib 15} {recurse 1} {fib 1}
Stack: 2 1 2 1
 
{[...] 0} {quackery 1} {[...] 11} {shell 5} {quackery 1} {[...] 1} {fib 17} {recurse 1} {fib 17} {recurse 1} {fib 17} {recurse 1} {fib 1}
Stack: 2 1 1 2
 
{[...] 0} {quackery 1} {[...] 11} {shell 5} {quackery 1} {[...] 1} {fib 17} {recurse 1} {fib 17} {recurse 1} {fib 17} {recurse 1} {fib 15} {recurse 1} {fib 1}
Stack: 2 1 1 1 0
 
{[...] 0} {quackery 1} {[...] 11} {shell 5} {quackery 1} {[...] 1} {fib 17} {recurse 1} {fib 17} {recurse 1} {fib 17} {recurse 1} {fib 17} {recurse 1} {fib 1}
Stack: 2 1 1 0 1
5
Stack empty.
 
/O></pre>
 
 
=={{header|R}}==
<langsyntaxhighlight Rlang="r">foo <- function()
{
bar <- function()
Line 1,362 ⟶ 1,920:
}
 
foo()</langsyntaxhighlight>
<nowiki>[[1]]</nowiki>
foo()
Line 1,370 ⟶ 1,928:
 
You can also see the stack trace when a function is called (or as it exits) using the trace function.
<langsyntaxhighlight Rlang="r">trace("foo", recover)
foo()</langsyntaxhighlight>
<pre>
Tracing foo() on entry
Line 1,383 ⟶ 1,941:
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 1,401 ⟶ 1,959:
(when (car s) (printf "~s: ~s\n" i (car s)))))
(foo)
</syntaxhighlight>
</lang>
 
Output:
Line 1,410 ⟶ 1,968:
3: |[running body]|
</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2013-03-03}}
<syntaxhighlight lang="raku" line>sub g { say Backtrace.new.concise }
sub f { g }
sub MAIN { f }</syntaxhighlight>
{{out}}
<pre> in sub g at bt:1
in sub f at bt:2
in sub MAIN at bt:3</pre>
 
=={{header|Raven}}==
<langsyntaxhighlight Ravenlang="raven"> [1 2 3 4] 42 { 'a' 1 'b' 2 'c' 3 } 34.1234 ( -1 -2 -3 ) "The quick brown fox" FILE dump</langsyntaxhighlight>
{{out}}
<pre>hash (4 items)
Line 1,431 ⟶ 2,000:
2 => 3
3 => 4</pre>
 
=={{header|REXX}}==
{{works with|Regina}}
<syntaxhighlight lang="rexx">/* call stack */
say 'Call A'
call A '123'
say result
exit 0
 
A:
say 'Call B'
call B '456'
say result
return ARG(1)
 
B:
say 'Call C'
call C '789'
say result
return ARG(1)
 
C:
call callstack
return ARG(1)
 
callstack: procedure
getcallstack(cs.)
say 'Dump call stack with' cs.0 'items'
do i = 1 to cs.0
parse var cs.i line func
say format(line, 3) ':' left(func, 9) ': source "' || sourceline(line) || '"'
end
return cs.0</syntaxhighlight>
 
{{out}}
<pre>prompt$ regina callstack.rexx
Call A
Call B
Call C
Dump call stack with 4 items
20 : CALLSTACK : source "call callstack"
15 : C : source "call C '789'"
9 : B : source "call B '456'"
3 : A : source "call A '123'"
789
456
123</pre>
 
Regina will also dump a call stack during certain error conditions. For instance, if the code listing above raised an unhandled signal (simulated here with "signal noname" in routine C). This is not a recoverable scenario though, and the program will not continue.
 
<syntaxhighlight lang="rexx">C:
signal noname
call callstack
return ARG(1)</syntaxhighlight>
 
{{out}}
<pre>prompt$ regina callstack.rexx
Call A
Call B
Call C
20 +++ signal noname
15 +++ call C '789'
9 +++ call B '456'
3 +++ call A '123'
Error 16 running "/demos/callstack.rexx", line 20: Label not found
Error 16.1: Label "NONAME" not found</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">def outer(a,b,c)
middle a+b, b+c
end
Line 1,446 ⟶ 2,081:
end
 
outer 2,3,5</langsyntaxhighlight>
<pre>$ ruby stacktrace.rb
stacktrace.rb:10:in `inner'
Line 1,455 ⟶ 2,090:
 
Exceptions caught in a rescue clause contain the trace information:
<langsyntaxhighlight lang="ruby">def outer(a,b,c)
middle a+b, b+c
end
Line 1,473 ⟶ 2,108:
puts e.backtrace
end
puts "continuing after the rescue..."</langsyntaxhighlight>
<pre>stacktrace.rb:10:in `inner'
stacktrace.rb:6:in `middle'
Line 1,479 ⟶ 2,114:
stacktrace.rb:15
continuing after the rescue...</pre>
Thread has a backtrace method:
<syntaxhighlight lang="ruby">p Thread.current.backtrace</syntaxhighlight>
 
=={{header|Scala}}==
Line 1,484 ⟶ 2,121:
the way, could be used from Java as well, with minor modifications.
 
<langsyntaxhighlight lang="scala">def callStack = try { error("exception") } catch { case ex => ex.getStackTrace drop 2 }
 
def printStackTrace = callStack drop 1 /* don't print ourselves! */ foreach println</langsyntaxhighlight>
 
Usage example:
Line 1,539 ⟶ 2,176:
The following #printCurrentStack is already defined in the base slate image but it is replicated here.
 
<langsyntaxhighlight lang="slate">slate[1]> d@(Debugger traits) printCurrentStack &limit: limit &stream: out &showLocation: showLocation
[
d clone `>> [baseFramePointer: (d interpreter framePointerOf: #printCurrentStack).
Line 1,546 ⟶ 2,183:
].
Defining function 'printCurrentStack' on: 'Debugger traits'
[printCurrentStack &limit: &stream: &showLocation:]</langsyntaxhighlight>
 
The output from calling the function:
 
<langsyntaxhighlight lang="slate">slate[2]> Debugger printCurrentStack.
Backtrace (method @ source):
frame: 0 [printCurrentStack &limit: &stream: &showLocation:] @ stdin:0
Line 1,563 ⟶ 2,200:
frame: 9 [start &resource:] @ src/lib/repl.slate:185
frame: 10 [start] @ src/mobius/prelude.slate:38
Nil</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
Line 1,570 ⟶ 2,207:
A backtrace is normally sent when some error occurs; however, it can be "forced":
 
<langsyntaxhighlight lang="smalltalk">Object subclass: Container [
Container class >> outer: a and: b and: c [
self middle: (a+b) and: (b+c)
Line 1,584 ⟶ 2,221:
Container outer: 2 and: 3 and: 5.
 
'Anyway, we continue with it' displayNl.</langsyntaxhighlight>
 
Output:
Line 1,595 ⟶ 2,232:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc printStackTrace {} {
puts "Stack trace:"
for {set i 1} {$i < [info level]} {incr i} {
puts [string repeat " " $i][info level $i]
}
}</langsyntaxhighlight>
Demonstration code:
<langsyntaxhighlight lang="tcl">proc outer {a b c} {
middle [expr {$a+$b}] [expr {$b+$c}]
}
Line 1,611 ⟶ 2,248:
printStackTrace
}
outer 2 3 5</langsyntaxhighlight>
Produces this output:
<pre>Stack trace:
Line 1,617 ⟶ 2,254:
middle 5 8
inner 40</pre>
 
=={{header|VBA}}==
In VBE the VBA Editor hitting Control+L while stepping through your code in debug mode will pop up a window which displays the call stack.
 
=={{header|Wren}}==
You can always force Wren CLI to produce a stack trace by either engineering an actual error or calling Fiber.abort() at the relevant part of the script.
 
However, it is not possible to continue execution of the script afterwards. Whilst one can 'catch' such an error using Fiber.try() this will only allow you to inspect the error itself, not the chain of function calls that led up to it.
<syntaxhighlight lang="wren">var func2 = Fn.new {
Fiber.abort("Forced error.")
}
 
var func1 = Fn.new {
func2.call()
}
 
func1.call()</syntaxhighlight>
 
{{out}}
<pre>
Forced error.
[./stack_trace line 2] in new(_) block argument
[./stack_trace line 6] in new(_) block argument
[./stack_trace line 9] in (script)
</pre>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn f{println("F");vm.stackTrace().println()} fcn g{println("G")}
f();g();</langsyntaxhighlight>
{{out}}
stackTrace just returns a string. You don't get to futz with the stack.
9,476

edits