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

JuliaLang / julia / #37919

29 Sep 2024 09:41AM UTC coverage: 86.232% (-0.3%) from 86.484%
#37919

push

local

web-flow
fix rawbigints OOB issues (#55917)

Fixes issues introduced in #50691 and found in #55906:
* use `@inbounds` and `@boundscheck` macros in rawbigints, for catching
OOB with `--check-bounds=yes`
* fix OOB in `truncate`

12 of 13 new or added lines in 1 file covered. (92.31%)

1287 existing lines in 41 files now uncovered.

77245 of 89578 relevant lines covered (86.23%)

15686161.83 hits per line

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

74.47
/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
using Base.IRShow: normalize_method_name, append_scopes!, LineInfoNode
12

13
export StackTrace, StackFrame, stacktrace
14

15
"""
16
    StackFrame
17

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

20
- `func::Symbol`
21

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

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

26
  The Method, MethodInstance, or CodeInfo containing the execution context (if it could be found), \
27
     or nothing (for example, if the inlining was a result of macro expansion).
28

29
- `file::Symbol`
30

31
  The path to the file containing the execution context.
32

33
- `line::Int`
34

35
  The line number in the file containing the execution context.
36

37
- `from_c::Bool`
38

39
  True if the code is from C.
40

41
- `inlined::Bool`
42

43
  True if the code is from an inlined frame.
44

45
- `pointer::UInt64`
46

47
  Representation of the pointer to the execution context as returned by `backtrace`.
48

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

UNCOV
68
StackFrame(func, file, line) = StackFrame(Symbol(func), Symbol(file), line,
×
69
                                          nothing, false, false, 0)
70

71
"""
72
    StackTrace
73

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

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

82

83
#=
84
If the StackFrame has function and line information, we consider two of them the same if
85
they share the same function/line information.
86
=#
87
function ==(a::StackFrame, b::StackFrame)
1✔
88
    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
69,508✔
89
end
90

91
function hash(frame::StackFrame, h::UInt)
UNCOV
92
    h += 0xf4fbda67fe20ce88 % UInt
×
93
    h = hash(frame.line, h)
1,282,526✔
94
    h = hash(frame.file, h)
1,282,526✔
95
    h = hash(frame.func, h)
1,282,526✔
96
    h = hash(frame.from_c, h)
1,282,526✔
97
    h = hash(frame.inlined, h)
1,282,526✔
UNCOV
98
    return h
×
99
end
100

101
"""
102
    lookup(pointer::Ptr{Cvoid}) -> Vector{StackFrame}
103

104
Given a pointer to an execution context (usually generated by a call to `backtrace`), looks
105
up stack frame context information. Returns an array of frame information for all functions
106
inlined at that point, innermost function first.
107
"""
108
Base.@constprop :none function lookup(pointer::Ptr{Cvoid})
16,928✔
109
    infos = ccall(:jl_lookup_code_address, Any, (Ptr{Cvoid}, Cint), pointer, false)::Core.SimpleVector
16,928✔
110
    pointer = convert(UInt64, pointer)
16,928✔
111
    isempty(infos) && return [StackFrame(empty_sym, empty_sym, -1, nothing, true, false, pointer)] # this is equal to UNKNOWN
16,928✔
112
    res = Vector{StackFrame}(undef, length(infos))
33,856✔
113
    for i in 1:length(infos)
16,928✔
114
        info = infos[i]::Core.SimpleVector
29,611✔
115
        @assert(length(info) == 6)
29,611✔
116
        func = info[1]::Symbol
29,611✔
117
        file = info[2]::Symbol
29,611✔
118
        linenum = info[3]::Int
29,611✔
119
        linfo = info[4]
29,611✔
120
        res[i] = StackFrame(func, file, linenum, linfo, info[5]::Bool, info[6]::Bool, pointer)
29,611✔
121
    end
42,294✔
122
    return res
16,928✔
123
end
124

125
const top_level_scope_sym = Symbol("top-level scope")
126

127
function lookup(ip::Union{Base.InterpreterIP,Core.Compiler.InterpreterIP})
84✔
128
    code = ip.code
84✔
129
    if code === nothing
84✔
130
        # interpreted top-level expression with no CodeInfo
131
        return [StackFrame(top_level_scope_sym, empty_sym, 0, nothing, false, false, 0)]
2✔
132
    end
133
    # prepare approximate code info
134
    if code isa MethodInstance && (meth = code.def; meth isa Method)
82✔
135
        func = meth.name
×
136
        file = meth.file
×
137
        line = meth.line
×
138
        codeinfo = meth.source
×
139
    else
140
        if code isa Core.CodeInstance
82✔
141
            codeinfo = code.inferred::CodeInfo
×
142
        else
143
            codeinfo = code::CodeInfo
82✔
144
        end
145
        func = top_level_scope_sym
3✔
146
        file = empty_sym
3✔
147
        line = Int32(0)
3✔
148
    end
149
    def = (code isa MethodInstance ? code : StackTraces) # Module just used as a token for top-level code
82✔
150
    pc::Int = max(ip.stmt + 1, 0) # n.b. ip.stmt is 0-indexed
82✔
151
    scopes = LineInfoNode[]
82✔
152
    append_scopes!(scopes, pc, codeinfo.debuginfo, def)
82✔
153
    if isempty(scopes)
82✔
154
        return [StackFrame(func, file, line, code, false, false, 0)]
×
155
    end
156
    inlined = false
82✔
157
    scopes = map(scopes) do lno
82✔
158
        if inlined
117✔
159
            def = lno.method
35✔
160
            def isa Union{Method,MethodInstance} || (def = nothing)
70✔
161
        else
162
            def = codeinfo
82✔
163
        end
164
        sf = StackFrame(normalize_method_name(lno.method), lno.file, lno.line, def, false, inlined, 0)
117✔
165
        inlined = true
117✔
166
        return sf
117✔
167
    end
168
    return scopes
82✔
169
end
170

171
"""
172
    stacktrace([trace::Vector{Ptr{Cvoid}},] [c_funcs::Bool=false]) -> StackTrace
173

174
Return a stack trace in the form of a vector of `StackFrame`s. (By default stacktrace
175
doesn't return C functions, but this can be enabled.) When called without specifying a
176
trace, `stacktrace` first calls `backtrace`.
177
"""
178
Base.@constprop :none function stacktrace(trace::Vector{<:Union{Base.InterpreterIP,Core.Compiler.InterpreterIP,Ptr{Cvoid}}}, c_funcs::Bool=false)
40✔
179
    stack = StackTrace()
67✔
180
    for ip in trace
30✔
181
        for frame in lookup(ip)
755✔
182
            # Skip frames that come from C calls.
183
            if c_funcs || !frame.from_c
1,987✔
184
                push!(stack, frame)
503✔
185
            end
186
        end
1,046✔
187
    end
755✔
188
    return stack
30✔
189
end
190

UNCOV
191
Base.@constprop :none function stacktrace(c_funcs::Bool=false)
×
UNCOV
192
    stack = stacktrace(backtrace(), c_funcs)
×
193
    # Remove frame for this function (and any functions called by this function).
UNCOV
194
    remove_frames!(stack, :stacktrace)
×
195
    # also remove all of the non-Julia functions that led up to this point (if that list is non-empty)
UNCOV
196
    c_funcs && deleteat!(stack, 1:(something(findfirst(frame -> !frame.from_c, stack), 1) - 1))
×
UNCOV
197
    return stack
×
198
end
199

200
"""
201
    remove_frames!(stack::StackTrace, name::Symbol)
202

203
Takes a `StackTrace` (a vector of `StackFrames`) and a function name (a `Symbol`) and
204
removes the `StackFrame` specified by the function name from the `StackTrace` (also removing
205
all frames above the specified function). Primarily used to remove `StackTraces` functions
206
from the `StackTrace` prior to returning it.
207
"""
UNCOV
208
function remove_frames!(stack::StackTrace, name::Symbol)
×
UNCOV
209
    deleteat!(stack, 1:something(findlast(frame -> frame.func == name, stack), 0))
×
UNCOV
210
    return stack
×
211
end
212

UNCOV
213
function remove_frames!(stack::StackTrace, names::Vector{Symbol})
×
UNCOV
214
    deleteat!(stack, 1:something(findlast(frame -> frame.func in names, stack), 0))
×
UNCOV
215
    return stack
×
216
end
217

218
"""
219
    remove_frames!(stack::StackTrace, m::Module)
220

221
Return the `StackTrace` with all `StackFrame`s from the provided `Module` removed.
222
"""
UNCOV
223
function remove_frames!(stack::StackTrace, m::Module)
×
UNCOV
224
    filter!(f -> !from(f, m), stack)
×
UNCOV
225
    return stack
×
226
end
227

228
is_top_level_frame(f::StackFrame) = f.linfo isa CodeInfo || (f.linfo === nothing && f.func === top_level_scope_sym)
5✔
229

230
function show_spec_linfo(io::IO, frame::StackFrame)
2,080✔
231
    linfo = frame.linfo
2,080✔
232
    if linfo === nothing
2,080✔
233
        if frame.func === empty_sym
491✔
234
            print(io, "ip:0x", string(frame.pointer, base=16))
×
235
        elseif frame.func === top_level_scope_sym
491✔
236
            print(io, "top-level scope")
3✔
237
        else
238
            Base.print_within_stacktrace(io, Base.demangle_function_name(string(frame.func)), bold=true)
488✔
239
        end
240
    elseif linfo isa CodeInfo
1,589✔
241
        print(io, "top-level scope")
65✔
242
    elseif linfo isa Module
514✔
243
        Base.print_within_stacktrace(io, Base.demangle_function_name(string(frame.func)), bold=true)
×
244
    elseif linfo isa MethodInstance
1,524✔
245
        def = linfo.def
1,524✔
246
        if def isa Module
1,524✔
UNCOV
247
            Base.show_mi(io, linfo, #=from_stackframe=#true)
×
248
        else
249
            show_spec_sig(io, def, linfo.specTypes)
1,524✔
250
        end
251
    else
252
        m = linfo::Method
×
253
        show_spec_sig(io, m, m.sig)
×
254
    end
255
end
256

257
function show_spec_sig(io::IO, m::Method, @nospecialize(sig::Type))
1,524✔
258
    if get(io, :limit, :false)::Bool
1,056✔
259
        if !haskey(io, :displaysize)
534✔
260
            io = IOContext(io, :displaysize => displaysize(io))
111✔
261
        end
262
    end
263
    argnames = Base.method_argnames(m)
3,048✔
264
    argnames = replace(argnames, :var"#unused#" => :var"")
3,048✔
265
    if m.nkw > 0
1,524✔
266
        # rearrange call kw_impl(kw_args..., func, pos_args...) to func(pos_args...; kw_args)
267
        kwarg_types = Any[ fieldtype(sig, i) for i = 2:(1+m.nkw) ]
322✔
268
        uw = Base.unwrap_unionall(sig)::DataType
284✔
269
        pos_sig = Base.rewrap_unionall(Tuple{uw.parameters[(m.nkw+2):end]...}, sig)
284✔
270
        kwnames = argnames[2:(m.nkw+1)]
568✔
271
        for i = 1:length(kwnames)
284✔
272
            str = string(kwnames[i])::String
322✔
273
            if endswith(str, "...")
322✔
274
                kwnames[i] = Symbol(str[1:end-3])
×
275
            end
276
        end
360✔
277
        Base.show_tuple_as_call(io, m.name, pos_sig;
284✔
278
                                demangle=true,
279
                                kwargs=zip(kwnames, kwarg_types),
280
                                argnames=argnames[m.nkw+2:end])
281
    else
282
        Base.show_tuple_as_call(io, m.name, sig; demangle=true, argnames)
1,240✔
283
    end
284
end
285

286
function show(io::IO, frame::StackFrame)
150✔
287
    show_spec_linfo(io, frame)
150✔
288
    if frame.file !== empty_sym
150✔
289
        file_info = basename(string(frame.file))
143✔
290
        print(io, " at ")
143✔
291
        print(io, file_info, ":")
143✔
292
        if frame.line >= 0
143✔
293
            print(io, frame.line)
143✔
294
        else
295
            print(io, "?")
×
296
        end
297
    end
298
    if frame.inlined
150✔
299
        print(io, " [inlined]")
39✔
300
    end
301
end
302

303
function Base.parentmodule(frame::StackFrame)
304
    linfo = frame.linfo
3,007✔
305
    if linfo isa MethodInstance
3,007✔
306
        def = linfo.def
1,560✔
307
        if def isa Module
1,560✔
308
            return def
×
309
        else
310
            return (def::Method).module
1,560✔
311
        end
312
    elseif linfo isa Method
1,447✔
313
        return linfo.module
×
314
    elseif linfo isa Module
×
315
        return linfo
×
316
    else
317
        # The module is not always available (common reasons include
318
        # frames arising from the interpreter)
319
        nothing
320
    end
321
end
322

323
"""
324
    from(frame::StackFrame, filter_mod::Module) -> Bool
325

326
Return whether the `frame` is from the provided `Module`
327
"""
UNCOV
328
function from(frame::StackFrame, m::Module)
×
UNCOV
329
    return parentmodule(frame) === m
×
330
end
331

332
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