Stack traces: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
(Added Quackery.)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(10 intermediate revisions by 6 users not shown)
Line 19:
 
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.
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO; use Ada.Text_IO;
with GNAT.Traceback;
with GNAT.Traceback.Symbolic;
Line 49:
begin
Outer (2,3,5);
end Test_Stack_Trace;</langsyntaxhighlight>
Sample output:
<pre>
Line 70:
ListLines can be turned on or off... with:
<br> ListLines, On|Off
<langsyntaxhighlight lang="autohotkey">f()
return
Line 86:
msgbox, variable bindings
}
#Persistent</langsyntaxhighlight>
Output:
<langsyntaxhighlight lang="autohotkey">001: f()
006: Return,g()
011: ListLines (0.05)
Line 102:
0[1 of 3]: 0
ErrorLevel[1 of 3]: 0
</syntaxhighlight>
</lang>
 
=={{header|BASIC}}==
Line 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 221:
outer(2,3,5);
return EXIT_SUCCESS;
}</langsyntaxhighlight>
 
Sample output on my system:
Line 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 330:
#define END }
 
#endif</langsyntaxhighlight>
'''==> stack_trace.c <=='''
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stddef.h>
 
Line 416:
print_indent(); fprintf(stderr, "--- (depth %d) ---\n", stack_trace.stack.depth);
}
}</langsyntaxhighlight>
 
'''==> stack_trace_test.c <=='''
Line 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 450:
stack_trace.on = FALSE;
RETURN(EXIT_SUCCESS);
END</langsyntaxhighlight>
 
{{out}}
Line 469:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Diagnostics;
 
Line 493:
Outer();
}
}</langsyntaxhighlight>
Sample output:
<syntaxhighlight lang="text">at Program.Inner()
at Program.Middle()
at Program.Outer()
at Program.Main()</langsyntaxhighlight>
 
=={{header|Clojure}}==
Line 505:
[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.
 
<langsyntaxhighlight lang="clojure">
(doall
(map println (.dumpAllThreads (java.lang.management.ManagementFactory/getThreadMXBean) false false)))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 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 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 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 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 594:
=={{header|DWScript}}==
Stack traces can be obtained from exception objects
<langsyntaxhighlight lang="delphi">procedure Inner;
begin
try
Line 614:
end;
 
Outer;</langsyntaxhighlight>
Output:<pre>Inner [line: 4, column: 23]
Middle [line: 13, column: 4]
Line 622:
=={{header|Elena}}==
{{trans|C#}}
ELENA 56.0x :
<langsyntaxhighlight lang="elena">import extensions;
public singleton program
Line 647:
program.outer()
}
}</langsyntaxhighlight>
{{out}}
<pre>
mytestsandbox'program.inner[01]:testsandbox.l(7)
mytestsandbox'program.middle[01]:testsandbox.l(12)
mytestsandbox'program.outer[01]:testsandbox.l(17)
mytestsandbox'program.function:#invoke[0]:testsandbox.l(23)
system'$private'entry.function:#invoke[0]:win32_appapp.l(375)
system'$private'entrySymbol#startUpsym:win32_appapp.l(5544)
</pre>
 
=={{header|Elixir}}==
{{trans|Erlang}}
<langsyntaxhighlight lang="elixir">defmodule Stack_traces do
def main do
{:ok, a} = outer
Line 684:
end
 
Stack_traces.main</langsyntaxhighlight>
 
{{out}}
Line 702:
{{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 719:
 
inner() ->
try throw(42) catch 42 -> {ok,erlang:get_stacktrace()} end.</langsyntaxhighlight>
{{out}}
<pre>[{stack_traces,inner,0,[{file,"stack_traces.erl"},{line,18}]},
Line 730:
=={{header|F_Sharp|F#}}==
{{trans|C#}}
<langsyntaxhighlight lang="fsharp">open System.Diagnostics
 
type myClass() =
Line 741:
let that = new myClass()
that.outer()
0</langsyntaxhighlight>
Output
<pre> at Rosetta.myClass.inner()
Line 750:
=={{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.
<langsyntaxhighlight lang="factor">USE: prettyprint
get-callstack callstack.</langsyntaxhighlight>
{{out}}
<pre>
Line 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 788:
BEGIN DUP WHILE ROT DUP . >R 1- REPEAT DROP
THEN ." (TORS) " DROP >R ;
[THEN]</langsyntaxhighlight>
 
=={{header|Fortran}}==
Line 809:
 
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 (
Line 824 ⟶ 860:
fmt.Printf("%s\n", stackTrace)
fmt.Printf("(%d bytes)\n", len(stackTrace))
}</langsyntaxhighlight>
outputs:
<pre>
Line 842 ⟶ 878:
=={{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 858 ⟶ 894:
trace.each {
propNames.eachWithIndex{ name, i -> printf("%-${propWidths[i]}s ", it[name].toString()) }; println ''
}</langsyntaxhighlight>
 
Output:
Line 932 ⟶ 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 948 ⟶ 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 971 ⟶ 1,007:
}
return L
end</langsyntaxhighlight>
 
The output of this example is:
Line 988 ⟶ 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 997 ⟶ 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 1,010 ⟶ 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 1,016 ⟶ 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 1,026 ⟶ 1,062:
}
}
}</langsyntaxhighlight>
Demonstration code:
<langsyntaxhighlight lang="java5">public class StackTraceDemo {
static void inner() {
StackTracer.printStackTrace();
Line 1,041 ⟶ 1,077:
outer();
}
}</langsyntaxhighlight>
Output:
<pre>Stack trace:
Line 1,052 ⟶ 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 1,067 ⟶ 1,103:
alert(stack);
}
foo();</langsyntaxhighlight>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">f() = g()
g() = println.(stacktrace())
 
f()</langsyntaxhighlight>
 
{{out}}
Line 1,089 ⟶ 1,125:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2 (stacktrace.kt which compiles to StacktraceKt.class)
 
fun myFunc() {
Line 1,098 ⟶ 1,134:
myFunc()
println("\nContinuing ... ")
}</langsyntaxhighlight>
 
{{out}}
Line 1,106 ⟶ 1,142:
 
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>
 
Line 1,111 ⟶ 1,215:
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 1,134 ⟶ 1,238:
)
return #gb()
}</langsyntaxhighlight>
 
;Use Trace:
 
<langsyntaxhighlight Lassolang="lasso">define stackexample => type {
public oncreate => trace => { return self }
public inner => trace => { }
Line 1,145 ⟶ 1,249:
}
 
stackexample->outer</langsyntaxhighlight>
 
{{out}}
Line 1,155 ⟶ 1,259:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function Inner( k )
print( debug.traceback() )
print "Program continues..."
Line 1,168 ⟶ 1,272:
end
 
Outer( 2, 3, 5 )</langsyntaxhighlight>
<pre>stack traceback:
./prog:4: in function 'Inner'
Line 1,177 ⟶ 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.
<langsyntaxhighlight lang="nanoquery">def print_stack()
global __calls__
 
Line 1,209 ⟶ 1,313:
 
println
println "The program would continue."</langsyntaxhighlight>
{{out}}
<pre>stack trace:
Line 1,222 ⟶ 1,326:
=={{header|NetRexx}}==
{{trans|Java}}
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 1,244 ⟶ 1,348:
j_ = j_ + 2
end i_
</syntaxhighlight>
</lang>
'''Output:'''
<pre>
Line 1,256 ⟶ 1,360:
=={{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>
<langsyntaxhighlight lang="nim">proc g() =
# Writes the current stack trace to stderr.
writeStackTrace()
Line 1,267 ⟶ 1,371:
g()
 
f()</langsyntaxhighlight>
{{out}}
For a release build:
Line 1,282 ⟶ 1,386:
 
=={{header|Objective-C}}==
<langsyntaxhighlight lang="objc">#include <execinfo.h>
 
void *frames[128];
Line 1,290 ⟶ 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,307 ⟶ 1,411:
prerr_endline(Printexc.to_string e);
Printexc.print_backtrace stderr;
;;</langsyntaxhighlight>
 
outputs:
Line 1,318 ⟶ 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
Line 1,337 ⟶ 1,441:
Otherwise no stack trace is available nor printed.
 
<langsyntaxhighlight Oforthlang="oforth">: f1 Exception throw("An exception") ;
Integer method: f2 self f1 ;
: f3 f2 ;
: f4 f3 ;
 
10 f4</langsyntaxhighlight>
 
{{out}}
Line 1,355 ⟶ 1,459:
 
=={{header|OxygenBasic}}==
<langsyntaxhighlight lang="oxygenbasic">
'32bit x86
 
Line 1,436 ⟶ 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,449 ⟶ 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,456 ⟶ 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,470 ⟶ 1,574:
end
in
{F}</langsyntaxhighlight>
 
Output:
Line 1,476 ⟶ 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,491 ⟶ 1,595:
=={{header|Phix}}==
There no standard method of obtaining a stack trace mid-run (as yet, non-fatally that is), but we can quickly cobble something together:
<!--<langsyntaxhighlight Phixlang="phix">(notonline)-->
<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>
<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>
Line 1,548 ⟶ 1,652:
<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>
<!--</langsyntaxhighlight>-->
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
Line 1,581 ⟶ 1,685:
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
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #008080;">trace</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<!--</langsyntaxhighlight>-->
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,601 ⟶ 1,705:
 
StackTraceDemo::outer();
?></langsyntaxhighlight>
 
<pre>#0 StackTraceDemo::inner() called at [/home/cweiske/Dev/cvs/test/php-stacktrace.php:7]
Line 1,613 ⟶ 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,648 ⟶ 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,658 ⟶ 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,671 ⟶ 1,775:
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
/* The SNAP option in the ON statement is sufficient to obtain */
/* a traceback. The SYSTEM option specifies that standard */
Line 1,679 ⟶ 1,783:
...
signal condition(traceback);
</syntaxhighlight>
</lang>
 
=={{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,699 ⟶ 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,807 ⟶ 1,911:
 
=={{header|R}}==
<langsyntaxhighlight Rlang="r">foo <- function()
{
bar <- function()
Line 1,816 ⟶ 1,920:
}
 
foo()</langsyntaxhighlight>
<nowiki>[[1]]</nowiki>
foo()
Line 1,824 ⟶ 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,837 ⟶ 1,941:
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 1,855 ⟶ 1,959:
(when (car s) (printf "~s: ~s\n" i (car s)))))
(foo)
</syntaxhighlight>
</lang>
 
Output:
Line 1,868 ⟶ 1,972:
(formerly Perl 6)
{{works with|Rakudo|2013-03-03}}
<syntaxhighlight lang="raku" perl6line>sub g { say Backtrace.new.concise }
sub f { g }
sub MAIN { f }</langsyntaxhighlight>
{{out}}
<pre> in sub g at bt:1
Line 1,877 ⟶ 1,981:
 
=={{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,899 ⟶ 2,003:
=={{header|REXX}}==
{{works with|Regina}}
<langsyntaxhighlight lang="rexx">/* call stack */
say 'Call A'
call A '123'
Line 1,928 ⟶ 2,032:
say format(line, 3) ':' left(func, 9) ': source "' || sourceline(line) || '"'
end
return cs.0</langsyntaxhighlight>
 
{{out}}
Line 1,946 ⟶ 2,050:
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.
 
<langsyntaxhighlight lang="rexx">C:
signal noname
call callstack
return ARG(1)</langsyntaxhighlight>
 
{{out}}
Line 1,964 ⟶ 2,068:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">def outer(a,b,c)
middle a+b, b+c
end
Line 1,977 ⟶ 2,081:
end
 
outer 2,3,5</langsyntaxhighlight>
<pre>$ ruby stacktrace.rb
stacktrace.rb:10:in `inner'
Line 1,986 ⟶ 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 2,004 ⟶ 2,108:
puts e.backtrace
end
puts "continuing after the rescue..."</langsyntaxhighlight>
<pre>stacktrace.rb:10:in `inner'
stacktrace.rb:6:in `middle'
Line 2,011 ⟶ 2,115:
continuing after the rescue...</pre>
Thread has a backtrace method:
<syntaxhighlight lang ="ruby">p Thread.current.backtrace</langsyntaxhighlight>
 
=={{header|Scala}}==
Line 2,017 ⟶ 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 2,072 ⟶ 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 2,079 ⟶ 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 2,096 ⟶ 2,200:
frame: 9 [start &resource:] @ src/lib/repl.slate:185
frame: 10 [start] @ src/mobius/prelude.slate:38
Nil</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
Line 2,103 ⟶ 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 2,117 ⟶ 2,221:
Container outer: 2 and: 3 and: 5.
 
'Anyway, we continue with it' displayNl.</langsyntaxhighlight>
 
Output:
Line 2,128 ⟶ 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 2,144 ⟶ 2,248:
printStackTrace
}
outer 2 3 5</langsyntaxhighlight>
Produces this output:
<pre>Stack trace:
Line 2,158 ⟶ 2,262:
 
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.
<langsyntaxhighlight ecmascriptlang="wren">var func2 = Fn.new {
Fiber.abort("Forced error.")
}
Line 2,166 ⟶ 2,270:
}
 
func1.call()</langsyntaxhighlight>
 
{{out}}
Line 2,177 ⟶ 2,281:
 
=={{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