• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

JuliaLang / julia / #37544

pending completion
#37544

push

local

web-flow
follow up #49889, pass `sv::AbsIntState` to `concrete_eval_call` (#49904)

`sv` is not used by `NativeInterpreter`, but is used by external
`AbstractInterpreter` like JET.jl.

1 of 1 new or added line in 1 file covered. (100.0%)

72304 of 83685 relevant lines covered (86.4%)

36045308.81 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

82.56
/base/stacktraces.jl
1
# This file is a part of Julia. License is MIT: https://julialang.org/license
2

3
"""
4
Tools for collecting and manipulating stack traces. Mainly used for building errors.
5
"""
6
module StackTraces
7

8

9
import Base: hash, ==, show
10
import Core: CodeInfo, MethodInstance
11

12
export StackTrace, StackFrame, stacktrace
13

14
"""
15
    StackFrame
16

17
Stack information representing execution context, with the following fields:
18

19
- `func::Symbol`
20

21
  The name of the function containing the execution context.
22

23
- `linfo::Union{Core.MethodInstance, CodeInfo, Nothing}`
24

25
  The MethodInstance containing the execution context (if it could be found).
26

27
- `file::Symbol`
28

29
  The path to the file containing the execution context.
30

31
- `line::Int`
32

33
  The line number in the file containing the execution context.
34

35
- `from_c::Bool`
36

37
  True if the code is from C.
38

39
- `inlined::Bool`
40

41
  True if the code is from an inlined frame.
42

43
- `pointer::UInt64`
44

45
  Representation of the pointer to the execution context as returned by `backtrace`.
46

47
"""
48
struct StackFrame # this type should be kept platform-agnostic so that profiles can be dumped on one machine and read on another
49
    "the name of the function containing the execution context"
36,196✔
50
    func::Symbol
51
    "the path to the file containing the execution context"
52
    file::Symbol
53
    "the line number in the file containing the execution context"
54
    line::Int
55
    "the MethodInstance or CodeInfo containing the execution context (if it could be found), \
56
     or Module (for macro expansions)"
57
    linfo::Union{MethodInstance, Method, Module, CodeInfo, Nothing}
58
    "true if the code is from C"
59
    from_c::Bool
60
    "true if the code is from an inlined frame"
61
    inlined::Bool
62
    "representation of the pointer to the execution context as returned by `backtrace`"
63
    pointer::UInt64  # Large enough to be read losslessly on 32- and 64-bit machines.
64
end
65

66
StackFrame(func, file, line) = StackFrame(Symbol(func), Symbol(file), line,
×
67
                                          nothing, false, false, 0)
68

69
"""
70
    StackTrace
71

72
An alias for `Vector{StackFrame}` provided for convenience; returned by calls to
73
`stacktrace`.
74
"""
75
const StackTrace = Vector{StackFrame}
76

77
const empty_sym = Symbol("")
78
const UNKNOWN = StackFrame(empty_sym, empty_sym, -1, nothing, true, false, 0) # === lookup(C_NULL)
79

80

81
#=
82
If the StackFrame has function and line information, we consider two of them the same if
83
they share the same function/line information.
84
=#
85
function ==(a::StackFrame, b::StackFrame)
988✔
86
    return a.line == b.line && a.from_c == b.from_c && a.func == b.func && a.file == b.file && a.inlined == b.inlined # excluding linfo and pointer
57,074✔
87
end
88

89
function hash(frame::StackFrame, h::UInt)
1,394,454✔
90
    h += 0xf4fbda67fe20ce88 % UInt
1,394,454✔
91
    h = hash(frame.line, h)
1,394,454✔
92
    h = hash(frame.file, h)
1,394,454✔
93
    h = hash(frame.func, h)
1,394,454✔
94
    h = hash(frame.from_c, h)
1,394,454✔
95
    h = hash(frame.inlined, h)
1,394,454✔
96
    return h
1,394,454✔
97
end
98

99
get_inlinetable(::Any) = nothing
×
100
function get_inlinetable(mi::MethodInstance)
8,695✔
101
    isdefined(mi, :def) && mi.def isa Method && isdefined(mi, :cache) && isdefined(mi.cache, :inferred) &&
14,582✔
102
        mi.cache.inferred !== nothing || return nothing
103
    linetable = ccall(:jl_uncompress_ir, Any, (Any, Any, Any), mi.def, mi.cache, mi.cache.inferred).linetable
2,808✔
104
    return filter!(x -> x.inlined_at > 0, linetable)
1,436,966✔
105
end
106

107
get_method_instance_roots(::Any) = nothing
×
108
function get_method_instance_roots(mi::Union{Method, MethodInstance})
5,887✔
109
    m = mi isa MethodInstance ? mi.def : mi
5,887✔
110
    m isa Method && isdefined(m, :roots) || return nothing
5,887✔
111
    return filter(x -> x isa MethodInstance, m.roots)
654,317✔
112
end
113

114
function lookup_inline_frame_info(func::Symbol, file::Symbol, linenum::Int, inlinetable::Vector{Core.LineInfoNode})
1,937✔
115
    #REPL frames and some base files lack this prefix while others have it; should fix?
116
    filestripped = Symbol(lstrip(string(file), ('.', '\\', '/')))
1,937✔
117
    linfo = nothing
×
118
    #=
119
    Some matching entries contain the MethodInstance directly.
120
    Other matching entries contain only a Method or Symbol (function name); such entries
121
    are located after the entry with the MethodInstance, so backtracking is required.
122
    If backtracking fails, the Method or Module is stored for return, but we continue
123
    the search in case a MethodInstance is found later.
124
    TODO: If a backtrack has failed, do we need to backtrack again later if another Method
125
    or Symbol match is found? Or can a limit on the subsequent backtracks be placed?
126
    =#
127
    for (i, line) in enumerate(inlinetable)
3,874✔
128
        Base.IRShow.method_name(line) === func && line.file ∈ (file, filestripped) && line.line == linenum || continue
913,591✔
129
        if line.method isa MethodInstance
3,010✔
130
            linfo = line.method
1,331✔
131
            break
1,331✔
132
        elseif line.method isa Method || line.method isa Symbol
3,358✔
133
            linfo = line.method isa Method ? line.method : line.module
3,358✔
134
            # backtrack to find the matching MethodInstance, if possible
135
            for j in (i - 1):-1:1
3,358✔
136
                nextline = inlinetable[j]
3,718✔
137
                nextline.inlined_at == line.inlined_at && Base.IRShow.method_name(line) === Base.IRShow.method_name(nextline) && line.file === nextline.file || break
3,733✔
138
                if nextline.method isa MethodInstance
3,703✔
139
                    linfo = nextline.method
1,663✔
140
                    break
1,663✔
141
                end
142
            end
2,040✔
143
        end
144
    end
912,260✔
145
    return linfo
1,937✔
146
end
147

148
function lookup_inline_frame_info(func::Symbol, file::Symbol, miroots::Vector{Any})
7,746✔
149
    # REPL frames and some base files lack this prefix while others have it; should fix?
150
    filestripped = Symbol(lstrip(string(file), ('.', '\\', '/')))
7,746✔
151
    matches = filter(miroots) do x
7,746✔
152
        x.def isa Method || return false
688,641✔
153
        m = x.def::Method
688,641✔
154
        return m.name == func && m.file ∈ (file, filestripped)
688,641✔
155
    end
156
    if length(matches) > 1
7,746✔
157
        # ambiguous, check if method is same and return that instead
158
        all_matched = true
×
159
        for m in matches
4,658✔
160
            all_matched = m.def.line == matches[1].def.line &&
13,471✔
161
                m.def.module == matches[1].def.module
162
            all_matched || break
13,471✔
163
        end
10,011✔
164
        if all_matched
4,658✔
165
            return matches[1].def
599✔
166
        end
167
        # all else fails, return module if they match, or give up
168
        all_matched = true
×
169
        for m in matches
4,059✔
170
            all_matched = m.def.module == matches[1].def.module
27,800✔
171
            all_matched || break
27,800✔
172
        end
31,859✔
173
        return all_matched ? matches[1].def.module : nothing
4,059✔
174
    elseif length(matches) == 1
3,088✔
175
        return matches[1]
2,425✔
176
    end
177
    return nothing
663✔
178
end
179

180
"""
181
    lookup(pointer::Ptr{Cvoid}) -> Vector{StackFrame}
182

183
Given a pointer to an execution context (usually generated by a call to `backtrace`), looks
184
up stack frame context information. Returns an array of frame information for all functions
185
inlined at that point, innermost function first.
186
"""
187
Base.@constprop :none function lookup(pointer::Ptr{Cvoid})
21,144✔
188
    infos = ccall(:jl_lookup_code_address, Any, (Ptr{Cvoid}, Cint), pointer, false)::Core.SimpleVector
21,144✔
189
    pointer = convert(UInt64, pointer)
21,144✔
190
    isempty(infos) && return [StackFrame(empty_sym, empty_sym, -1, nothing, true, false, pointer)] # this is equal to UNKNOWN
21,144✔
191
    parent_linfo = infos[end][4]
21,144✔
192
    inlinetable = get_inlinetable(parent_linfo)
33,593✔
193
    miroots = inlinetable === nothing ? get_method_instance_roots(parent_linfo) : nothing # fallback if linetable missing
21,144✔
194
    res = Vector{StackFrame}(undef, length(infos))
21,144✔
195
    for i in reverse(1:length(infos))
42,288✔
196
        info = infos[i]::Core.SimpleVector
34,606✔
197
        @assert(length(info) == 6)
34,606✔
198
        func = info[1]::Symbol
34,606✔
199
        file = info[2]::Symbol
34,606✔
200
        linenum = info[3]::Int
34,606✔
201
        linfo = info[4]
34,606✔
202
        if i < length(infos)
34,606✔
203
            if inlinetable !== nothing
13,462✔
204
                linfo = lookup_inline_frame_info(func, file, linenum, inlinetable)
1,937✔
205
            elseif miroots !== nothing
11,525✔
206
                linfo = lookup_inline_frame_info(func, file, miroots)
7,746✔
207
            end
208
            linfo = linfo === nothing ? parentmodule(res[i + 1]) : linfo # e.g. `macro expansion`
13,695✔
209
        end
210
        res[i] = StackFrame(func, file, linenum, linfo, info[5]::Bool, info[6]::Bool, pointer)
34,606✔
211
    end
48,068✔
212
    return res
21,144✔
213
end
214

215
const top_level_scope_sym = Symbol("top-level scope")
216

217
function lookup(ip::Union{Base.InterpreterIP,Core.Compiler.InterpreterIP})
191✔
218
    code = ip.code
191✔
219
    if code === nothing
191✔
220
        # interpreted top-level expression with no CodeInfo
221
        return [StackFrame(top_level_scope_sym, empty_sym, 0, nothing, false, false, 0)]
1✔
222
    end
223
    codeinfo = (code isa MethodInstance ? code.uninferred : code)::CodeInfo
380✔
224
    # prepare approximate code info
225
    if code isa MethodInstance && (meth = code.def; meth isa Method)
190✔
226
        func = meth.name
×
227
        file = meth.file
×
228
        line = meth.line
×
229
    else
230
        func = top_level_scope_sym
×
231
        file = empty_sym
×
232
        line = Int32(0)
×
233
    end
234
    i = max(ip.stmt+1, 1)  # ip.stmt is 0-indexed
190✔
235
    if i > length(codeinfo.codelocs) || codeinfo.codelocs[i] == 0
380✔
236
        return [StackFrame(func, file, line, code, false, false, 0)]
×
237
    end
238
    lineinfo = codeinfo.linetable[codeinfo.codelocs[i]]::Core.LineInfoNode
190✔
239
    scopes = StackFrame[]
190✔
240
    while true
526✔
241
        inlined = lineinfo.inlined_at != 0
526✔
242
        push!(scopes, StackFrame(Base.IRShow.method_name(lineinfo)::Symbol, lineinfo.file, lineinfo.line, inlined ? nothing : code, false, inlined, 0))
716✔
243
        inlined || break
526✔
244
        lineinfo = codeinfo.linetable[lineinfo.inlined_at]::Core.LineInfoNode
336✔
245
    end
336✔
246
    return scopes
190✔
247
end
248

249
"""
250
    stacktrace([trace::Vector{Ptr{Cvoid}},] [c_funcs::Bool=false]) -> StackTrace
251

252
Return a stack trace in the form of a vector of `StackFrame`s. (By default stacktrace
253
doesn't return C functions, but this can be enabled.) When called without specifying a
254
trace, `stacktrace` first calls `backtrace`.
255
"""
256
Base.@constprop :none function stacktrace(trace::Vector{<:Union{Base.InterpreterIP,Core.Compiler.InterpreterIP,Ptr{Cvoid}}}, c_funcs::Bool=false)
49✔
257
    stack = StackTrace()
82✔
258
    for ip in trace
43✔
259
        for frame in lookup(ip)
1,157✔
260
            # Skip frames that come from C calls.
261
            if c_funcs || !frame.from_c
3,103✔
262
                push!(stack, frame)
557✔
263
            end
264
        end
2,774✔
265
    end
1,198✔
266
    return stack
42✔
267
end
268

269
Base.@constprop :none function stacktrace(c_funcs::Bool=false)
×
270
    stack = stacktrace(backtrace(), c_funcs)
×
271
    # Remove frame for this function (and any functions called by this function).
272
    remove_frames!(stack, :stacktrace)
×
273
    # also remove all of the non-Julia functions that led up to this point (if that list is non-empty)
274
    c_funcs && deleteat!(stack, 1:(something(findfirst(frame -> !frame.from_c, stack), 1) - 1))
×
275
    return stack
×
276
end
277

278
"""
279
    remove_frames!(stack::StackTrace, name::Symbol)
280

281
Takes a `StackTrace` (a vector of `StackFrames`) and a function name (a `Symbol`) and
282
removes the `StackFrame` specified by the function name from the `StackTrace` (also removing
283
all frames above the specified function). Primarily used to remove `StackTraces` functions
284
from the `StackTrace` prior to returning it.
285
"""
286
function remove_frames!(stack::StackTrace, name::Symbol)
×
287
    deleteat!(stack, 1:something(findlast(frame -> frame.func == name, stack), 0))
×
288
    return stack
×
289
end
290

291
function remove_frames!(stack::StackTrace, names::Vector{Symbol})
×
292
    deleteat!(stack, 1:something(findlast(frame -> frame.func in names, stack), 0))
×
293
    return stack
×
294
end
295

296
"""
297
    remove_frames!(stack::StackTrace, m::Module)
298

299
Return the `StackTrace` with all `StackFrame`s from the provided `Module` removed.
300
"""
301
function remove_frames!(stack::StackTrace, m::Module)
×
302
    filter!(f -> !from(f, m), stack)
×
303
    return stack
×
304
end
305

306
is_top_level_frame(f::StackFrame) = f.linfo isa CodeInfo || (f.linfo === nothing && f.func === top_level_scope_sym)
10✔
307

308
function show_spec_linfo(io::IO, frame::StackFrame)
3,124✔
309
    linfo = frame.linfo
3,124✔
310
    if linfo === nothing
3,124✔
311
        if frame.func === empty_sym
276✔
312
            print(io, "ip:0x", string(frame.pointer, base=16))
×
313
        elseif frame.func === top_level_scope_sym
276✔
314
            print(io, "top-level scope")
17✔
315
        else
316
            Base.print_within_stacktrace(io, Base.demangle_function_name(string(frame.func)), bold=true)
259✔
317
        end
318
    elseif linfo isa CodeInfo
2,848✔
319
        print(io, "top-level scope")
89✔
320
    elseif linfo isa Module
2,759✔
321
        Base.print_within_stacktrace(io, Base.demangle_function_name(string(frame.func)), bold=true)
674✔
322
    else
323
        def, sig = if linfo isa MethodInstance
2,085✔
324
             linfo.def, linfo.specTypes
2,066✔
325
        else
326
            linfo, linfo.sig
2,104✔
327
        end
328
        if def isa Method
2,085✔
329
            if get(io, :limit, :false)::Bool
2,028✔
330
                if !haskey(io, :displaysize)
489✔
331
                    io = IOContext(io, :displaysize => displaysize(io))
77✔
332
                end
333
            end
334
            argnames = Base.method_argnames(def)
4,170✔
335
            argnames = replace(argnames, :var"#unused#" => :var"")
2,085✔
336
            if def.nkw > 0
2,085✔
337
                # rearrange call kw_impl(kw_args..., func, pos_args...) to func(pos_args...)
338
                kwarg_types = Any[ fieldtype(sig, i) for i = 2:(1+def.nkw) ]
313✔
339
                uw = Base.unwrap_unionall(sig)::DataType
289✔
340
                pos_sig = Base.rewrap_unionall(Tuple{uw.parameters[(def.nkw+2):end]...}, sig)
292✔
341
                kwnames = argnames[2:(def.nkw+1)]
289✔
342
                for i = 1:length(kwnames)
578✔
343
                    str = string(kwnames[i])::String
313✔
344
                    if endswith(str, "...")
313✔
345
                        kwnames[i] = Symbol(str[1:end-3])
×
346
                    end
347
                end
337✔
348
                Base.show_tuple_as_call(io, def.name, pos_sig;
289✔
349
                                        demangle=true,
350
                                        kwargs=zip(kwnames, kwarg_types),
351
                                        argnames=argnames[def.nkw+2:end])
352
            else
353
                Base.show_tuple_as_call(io, def.name, sig; demangle=true, argnames)
1,796✔
354
            end
355
        else
356
            Base.show_mi(io, linfo, true)
×
357
        end
358
    end
359
end
360

361
function show(io::IO, frame::StackFrame)
197✔
362
    show_spec_linfo(io, frame)
197✔
363
    if frame.file !== empty_sym
197✔
364
        file_info = basename(string(frame.file))
190✔
365
        print(io, " at ")
190✔
366
        print(io, file_info, ":")
190✔
367
        if frame.line >= 0
190✔
368
            print(io, frame.line)
190✔
369
        else
370
            print(io, "?")
×
371
        end
372
    end
373
    if frame.inlined
197✔
374
        print(io, " [inlined]")
84✔
375
    end
376
end
377

378
function Base.parentmodule(frame::StackFrame)
2,159✔
379
    linfo = frame.linfo
8,782✔
380
    if linfo isa MethodInstance
8,782✔
381
        def = linfo.def
3,153✔
382
        if def isa Module
3,153✔
383
            return def
×
384
        else
385
            return (def::Method).module
3,153✔
386
        end
387
    elseif linfo isa Method
5,629✔
388
        return linfo.module
81✔
389
    elseif linfo isa Module
5,548✔
390
        return linfo
956✔
391
    else
392
        # The module is not always available (common reasons include
393
        # frames arising from the interpreter)
394
        nothing
4,592✔
395
    end
396
end
397

398
"""
399
    from(frame::StackFrame, filter_mod::Module) -> Bool
400

401
Return whether the `frame` is from the provided `Module`
402
"""
403
function from(frame::StackFrame, m::Module)
×
404
    return parentmodule(frame) === m
×
405
end
406

407
end
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc