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

JuliaLang / julia / 1706

21 Nov 2026 07:28PM UTC coverage: 93.2% (-0.003%) from 93.203%
1706

push

buildkite

web-flow
Merge pull request #65088 from arnavk23/ak/fastmath-hypot

fastmath: Support unary and variadic `hypot`

4 of 6 new or added lines in 1 file covered. (66.67%)

122 existing lines in 8 files now uncovered.

100553 of 107889 relevant lines covered (93.2%)

399.33 hits per line

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

96.38
/stdlib/Serialization/src/Serialization.jl
1
# This file is a part of Julia. License is MIT: https://julialang.org/license
2

3
"""
4
    Serialization
5

6
Writing Julia objects to a stream with [`serialize`](@ref), and reading them back with
7
[`deserialize`](@ref). Newer Julia releases can read what older 1.x releases wrote, but not
8
the other way round.
9
"""
10
module Serialization
11

12
import Base: Bottom, unsafe_convert
13
import Base.ScopedValues: ScopedValue, with
14
import Core: svec, SimpleVector
15
using Base: @assume_effects, unaliascopy, unwrap_unionall, require_one_based_indexing, ntupleany
16
using Core.IR
17

18
export serialize, deserialize, AbstractSerializer, Serializer
19

20
abstract type AbstractSerializer end
21

22
# Dict is generally a much better dictionary than IdDict, but we want objectid comparison
23
struct IdKey val::Any end
274 ✔
24
Base.hash(k::IdKey, h::UInt) = hash(objectid(k.val), h)
274 ✔
25
Base.isequal(a::IdKey, b::IdKey) = a.val === b.val
166 ✔
26

27
mutable struct Serializer{I<:IO} <: AbstractSerializer
28
    const io::I
29
    counter::Int
30
    const cycle_table::Dict{IdKey,Int}
31
    const backref_table::Vector{Any}
32
    const pending_refs::Vector{Int}
33
    const known_object_data::Dict{UInt64,Any}
34
    version::Int
35
    Serializer{I}(io::I) where I<:IO = new(io, 0, Dict{IdKey,Int}(), Any[], Int[], Dict{UInt64,Any}(), ser_version)
274 ✔
36
end
37

38
Serializer(io::IO) = Serializer{typeof(io)}(io)
274 ✔
39

40
const current_module = ScopedValue{Union{Nothing,Module}}(nothing)
41

42
## serializing values ##
43

44
const n_int_literals = 33
45
const n_reserved_slots = 24
46
const n_reserved_tags = 8
47

48
const TAGS = Any[
49
    Symbol, Int8, UInt8, Int16, UInt16, Int32, UInt32, Int64, UInt64, Int128, UInt128,
50
    Float16, Float32, Float64, Char, DataType, Union, UnionAll, Core.TypeName, Tuple,
51
    Array, Expr, LineNumberNode, :__LabelNode__, GotoNode, QuoteNode, CodeInfo, TypeVar,
52
    Core.Box, Core.MethodInstance, Module, Task, String, SimpleVector, Method,
53
    GlobalRef, SlotNumber, Const, NewvarNode, SSAValue,
54

55
    # dummy entries for tags that don't correspond directly to types
56
    Symbol, # UNDEFREF_TAG
57
    Symbol, # BACKREF_TAG
58
    Symbol, # LONGBACKREF_TAG
59
    Symbol, # SHORTBACKREF_TAG
60
    Symbol, # LONGTUPLE_TAG
61
    Symbol, # LONGSYMBOL_TAG
62
    Symbol, # LONGEXPR_TAG
63
    Symbol, # LONGSTRING_TAG
64
    Symbol, # SHORTINT64_TAG
65
    Symbol, # FULL_DATATYPE_TAG
66
    Symbol, # WRAPPER_DATATYPE_TAG
67
    Symbol, # OBJECT_TAG
68
    Symbol, # REF_OBJECT_TAG
69
    Symbol, # FULL_GLOBALREF_TAG
70
    Symbol, # HEADER_TAG
71
    Symbol, # IDDICT_TAG
72
    Symbol, # SHARED_REF_TAG
73
    ReturnNode, GotoIfNot,
74
    fill(Symbol, n_reserved_tags)...,
75

76
    (), Bool, Any, Bottom, Core.TypeofBottom, Type, svec(), Tuple{}, false, true, nothing,
77
    :Any, :Array, :TypeVar, :Box, :Tuple, :Ptr, :return, :call, Symbol("::"), :Function,
78
    :(=), :(==), :(===), :gotoifnot, :A, :B, :C, :M, :N, :T, :S, :X, :Y, :a, :b, :c, :d, :e, :f,
79
    :g, :h, :i, :j, :k, :l, :m, :n, :o, :p, :q, :r, :s, :t, :u, :v, :w, :x, :y, :z, :add_int,
80
    :sub_int, :mul_int, :add_float, :sub_float, :new, :mul_float, :bitcast, :start, :done, :next,
81
    :indexed_iterate, :getfield, :meta, :eq_int, :slt_int, :sle_int, :ne_int, :push_loc, :pop_loc,
82
    :pop, :arrayset, :arrayref, :apply_type, :inbounds, :getindex, :setindex!, :Core, :!, :+,
83
    :Base, :static_parameter, :convert, :colon, Symbol("#self#"), Symbol("#temp#"), :tuple, Symbol(""),
84

85
    fill(:_reserved_, n_reserved_slots)...,
86

87
    (Int32(0):Int32(n_int_literals-1))...,
88
    (Int64(0):Int64(n_int_literals-1))...
89
]
90

91
const NTAGS = length(TAGS)
92
@assert NTAGS == 255
93

94
const ser_version = 31 # do not make changes without bumping the version #!
95

96
format_version(::AbstractSerializer) = ser_version
123 ✔
97
format_version(s::Serializer) = s.version
3 ✔
98

99
# static lookup table of serializee value --> TAG index via objectid + linear probe
100
# omit constant ints & reserved slots from the table as sertag doesn't return these
101
const NSERTAG_KEYS = NTAGS - n_reserved_slots - 2*n_int_literals
102

103
# keeps >50% sparse so linear probes hit in 1-2 steps. also allows :terminates
104
const SERTAG_TABLE_SIZE = nextpow(2, 2 * NSERTAG_KEYS)
105

106
struct SertagEmpty end
×
107
const sertag_empty = SertagEmpty()
108

109
struct SertagTable
110
    keys::Memory{Any}
×
111
    vals::Memory{Int32}
112
end
113

114
const sertag_table = let
115
    keys = Memory{Any}(undef, SERTAG_TABLE_SIZE)
116
    vals = Memory{Int32}(undef, SERTAG_TABLE_SIZE)
117
    fill!(keys, sertag_empty)
118
    @assume_effects :terminates_locally :noub @inbounds for i in Iterators.reverse(1:NSERTAG_KEYS)
119
        key = TAGS[i]
120
        loc = mod1(objectid(key), SERTAG_TABLE_SIZE)
121
        while true
122
            k = keys[loc]
123
            if k === sertag_empty || k === key
124
                keys[loc] = key
125
                vals[loc] = Int32(i)
126
                break
127
            end
128
            loc = mod1(loc + 1, SERTAG_TABLE_SIZE)
129
        end
130
    end
131
    SertagTable(keys, vals)
132
end
133

134
@inline function sertag(@nospecialize(v))
464 ✔
135
    (; keys, vals) = sertag_table
464 ✔
136
    loc = mod1(objectid(v), SERTAG_TABLE_SIZE)
464 ✔
137
    @assume_effects :terminates_locally :noub @inbounds while true
464 ✔
138
        @inbounds k = keys[loc]
464 ✔
139
        if k === v
464 ✔
140
            return vals[loc]
423 ✔
141
        elseif k === sertag_empty
461 ✔
142
            return Int32(-1)
461 ✔
143
        else
144
            loc = mod1(loc + 1, SERTAG_TABLE_SIZE)
387 ✔
145
        end
146
    end
387 ✔
147
end
148
desertag(i::Int32) = @inbounds(TAGS[i])
535 ✔
149

150
# tags >= this just represent themselves, their whole representation is 1 byte
151
const VALUE_TAGS = sertag(())
152
const ZERO32_TAG = Int32(NTAGS-(2*n_int_literals-1))
153
const ZERO64_TAG = Int64(NTAGS-(n_int_literals-1))
154
const TRUE_TAG = sertag(true)
155
const FALSE_TAG = sertag(false)
156
const EMPTYTUPLE_TAG = sertag(())
157
const TUPLE_TAG = sertag(Tuple)
158
const SIMPLEVECTOR_TAG = sertag(SimpleVector)
159
const SYMBOL_TAG = sertag(Symbol)
160
const INT8_TAG = sertag(Int8)
161
const ARRAY_TAG = sertag(Array)
162
const EXPR_TAG = sertag(Expr)
163
const MODULE_TAG = sertag(Module)
164
const METHODINSTANCE_TAG = sertag(Core.MethodInstance)
165
const METHOD_TAG = sertag(Method)
166
const TASK_TAG = sertag(Task)
167
const DATATYPE_TAG = sertag(DataType)
168
const TYPENAME_TAG = sertag(Core.TypeName)
169
const INT32_TAG = sertag(Int32)
170
const INT64_TAG = sertag(Int64)
171
const GLOBALREF_TAG = sertag(GlobalRef)
172
const BOTTOM_TAG = sertag(Bottom)
173
const UNIONALL_TAG = sertag(UnionAll)
174
const STRING_TAG = sertag(String)
175
const o0 = sertag(SSAValue)
176
const UNDEFREF_TAG         = Int32(o0+1)
177
const BACKREF_TAG          = Int32(o0+2)
178
const LONGBACKREF_TAG      = Int32(o0+3)
179
const SHORTBACKREF_TAG     = Int32(o0+4)
180
const LONGTUPLE_TAG        = Int32(o0+5)
181
const LONGSYMBOL_TAG       = Int32(o0+6)
182
const LONGEXPR_TAG         = Int32(o0+7)
183
const LONGSTRING_TAG       = Int32(o0+8)
184
const SHORTINT64_TAG       = Int32(o0+9)
185
const FULL_DATATYPE_TAG    = Int32(o0+10)
186
const WRAPPER_DATATYPE_TAG = Int32(o0+11)
187
const OBJECT_TAG           = Int32(o0+12)
188
const REF_OBJECT_TAG       = Int32(o0+13)
189
const FULL_GLOBALREF_TAG   = Int32(o0+14)
190
const HEADER_TAG           = Int32(o0+15)
191
const IDDICT_TAG           = Int32(o0+16)
192
const SHARED_REF_TAG       = Int32(o0+17)
193

194
writetag(s::IO, tag) = (write(s, UInt8(tag)); nothing)
537 ✔
195

196
function write_as_tag(s::IO, tag)
423 ✔
197
    tag < VALUE_TAGS && write(s, UInt8(0))
423 ✔
198
    write(s, UInt8(tag))
423 ✔
199
    nothing
423 ✔
200
end
201

202
# cycle handling
203
_getcycle(s::AbstractSerializer, @nospecialize(x)) = get(s.table, x, -1)::Int
310 ✔
204
_getcycle(s::Serializer, @nospecialize(x)) = get(s.cycle_table, IdKey(x), -1)
274 ✔
205
_setcycle!(s::AbstractSerializer, @nospecialize(x), v::Int) = (s.table[x] = v; nothing)
310 ✔
206
_setcycle!(s::Serializer, @nospecialize(x), v::Int) = (s.cycle_table[IdKey(x)] = v; nothing)
274 ✔
207

208
_setbackref!(s::AbstractSerializer, slot::Int, @nospecialize(x)) = (s.table[slot] = x; nothing)
420 ✔
209
function _setbackref!(s::Serializer, slot::Int, @nospecialize(x))
138 ✔
210
    bt = s.backref_table
138 ✔
211
    i = slot + 1
138 ✔
212
    i > length(bt) && resize!(bt, max(i, 2 * length(bt) + 1))
138 ✔
213
    @inbounds bt[i] = x
138 ✔
214
    nothing
138 ✔
215
end
216

217
@noinline function __getbackref_error(id::Int)
×
218
    error("""Inconsistent Serializer state when deserializing.
×
219
            Attempt to access internal table with key $id failed.
220

221
            This might occur if the Serializer contexts when serializing and deserializing are inconsistent.
222
            In particular, if multiple serialize calls use the same Serializer object then
223
            the corresponding deserialize calls should also use the same Serializer object.
224
        """)
225
end
226

227
_getbackref(s::AbstractSerializer, id::Int) = get(() -> __getbackref_error(id), s.table, id)
396 ✔
228
function _getbackref(s::Serializer, id::Int)
121 ✔
229
    bt = s.backref_table
121 ✔
230
    i = id + 1
121 ✔
231
    (id < 0 || i > length(bt) || !isassigned(bt, i)) && __getbackref_error(id)
121 ✔
232
    @inbounds return bt[i]
121 ✔
233
end
234

235
_sizehint_cycle!(s::AbstractSerializer, n::Integer) = (sizehint!(s.table, n); nothing)
276 ✔
236
_sizehint_cycle!(s::Serializer, n::Integer) = (sizehint!(s.cycle_table, n; shrink=false); nothing)
167 ✔
237

238
_sizehint_backref!(s::AbstractSerializer, n::Integer) = (sizehint!(s.table, n); nothing)
420 ✔
239
_sizehint_backref!(s::Serializer, n::Integer) = (sizehint!(s.backref_table, n; shrink=false); nothing)
14 ✔
240

241
function _emit_backref(io::IO, offs::Int)
284 ✔
242
    if offs <= typemax(UInt16)
284 ✔
243
        writetag(io, SHORTBACKREF_TAG)
284 ✔
244
        write(io, UInt16(offs))
284 ✔
245
    elseif offs <= typemax(Int32)
6 ✔
246
        writetag(io, BACKREF_TAG)
6 ✔
247
        write(io, Int32(offs))
6 ✔
248
    else
249
        writetag(io, LONGBACKREF_TAG)
×
250
        write(io, Int64(offs))
×
251
    end
252
    nothing
284 ✔
253
end
254

255
function serialize_cycle(s::AbstractSerializer, @nospecialize(x))
414 ✔
256
    offs = _getcycle(s, x)
414 ✔
257
    if offs != -1
414 ✔
258
        _emit_backref(s.io, offs)
284 ✔
259
        return true
284 ✔
260
    end
261
    _setcycle!(s, x, s.counter)
414 ✔
262
    s.counter += 1
414 ✔
263
    return false
414 ✔
264
end
265

266
function serialize_cycle_header(s::AbstractSerializer, @nospecialize(x))
244 ✔
267
    serialize_cycle(s, x) && return true
244 ✔
268
    serialize_type(s, typeof(x), true)
244 ✔
269
    return false
244 ✔
270
end
271

272
function reset_state(s::AbstractSerializer)
433 ✔
273
    s.counter = 0
433 ✔
274
    empty!(s.table)
433 ✔
275
    empty!(s.pending_refs)
433 ✔
276
    s
433 ✔
277
end
278
function reset_state(s::Serializer)
3 ✔
279
    s.counter = 0
3 ✔
280
    empty!(s.cycle_table)
3 ✔
281
    empty!(s.backref_table)
3 ✔
282
    empty!(s.pending_refs)
3 ✔
283
    s
3 ✔
284
end
285

286
serialize(s::AbstractSerializer, x::Bool) = x ? writetag(s.io, TRUE_TAG) :
372 ✔
287
                                                writetag(s.io, FALSE_TAG)
288

289
serialize(s::AbstractSerializer, p::Ptr) = serialize_any(s, oftype(p, C_NULL))
101 ✔
290

291
serialize(s::AbstractSerializer, ::Tuple{}) = writetag(s.io, EMPTYTUPLE_TAG)
268 ✔
292

293
function serialize(s::AbstractSerializer, t::Tuple)
387 ✔
294
    l = length(t)
387 ✔
295
    if l <= NTAGS
387 ✔
296
        writetag(s.io, TUPLE_TAG)
387 ✔
297
        write(s.io, UInt8(l))
387 ✔
298
    else
299
        writetag(s.io, LONGTUPLE_TAG)
3 ✔
300
        write(s.io, Int32(l))
3 ✔
301
    end
302
    for x in t
387 ✔
303
        serialize(s, x)
387 ✔
304
    end
387 ✔
305
end
306

307
function serialize(s::AbstractSerializer, v::SimpleVector)
186 ✔
308
    writetag(s.io, SIMPLEVECTOR_TAG)
186 ✔
309
    write(s.io, Int32(length(v)))
186 ✔
310
    for x in v
186 ✔
311
        serialize(s, x)
176 ✔
312
    end
176 ✔
313
end
314

315
function serialize(s::AbstractSerializer, x::Symbol)
461 ✔
316
    tag = sertag(x)
461 ✔
317
    if tag > 0
461 ✔
318
        return write_as_tag(s.io, tag)
385 ✔
319
    end
320
    pname = unsafe_convert(Ptr{UInt8}, x)
461 ✔
321
    len = Int(ccall(:strlen, Csize_t, (Cstring,), pname))
461 ✔
322
    if len > 7
461 ✔
323
        serialize_cycle(s, x) && return
387 ✔
324
    end
325
    if len <= NTAGS
461 ✔
326
        writetag(s.io, SYMBOL_TAG)
461 ✔
327
        write(s.io, UInt8(len))
461 ✔
328
    else
329
        writetag(s.io, LONGSYMBOL_TAG)
79 ✔
330
        write(s.io, Int32(len))
79 ✔
331
    end
332
    unsafe_write(s.io, pname, len)
461 ✔
333
    nothing
461 ✔
334
end
335

336
function serialize_array_data(s::IO, a)
301 ✔
337
    require_one_based_indexing(a)
301 ✔
338
    isempty(a) && return 0
301 ✔
339
    if eltype(a) === Bool
285 ✔
340
        last = a[1]::Bool
3 ✔
341
        count = 1
3 ✔
342
        for i = 2:length(a)
3 ✔
343
            if a[i]::Bool != last || count == 127
3 ✔
344
                write(s, UInt8((UInt8(last) << 7) | count))
3 ✔
345
                last = a[i]::Bool
3 ✔
346
                count = 1
3 ✔
347
            else
348
                count += 1
3 ✔
349
            end
350
        end
3 ✔
351
        write(s, UInt8((UInt8(last) << 7) | count))
3 ✔
352
    else
353
        write(s, a)
285 ✔
354
    end
355
end
356

357
function _serialize_non_bits_elements!(s::AbstractSerializer, a)
276 ✔
358
    _sizehint_cycle!(s, div(length(a), 4))  # prepare for lots of pointers
276 ✔
359
    @inbounds for i in eachindex(a)
276 ✔
360
        if isassigned(a, i)
260 ✔
361
            serialize(s, a[i])
260 ✔
362
        else
363
            writetag(s.io, UNDEFREF_TAG)
3 ✔
364
        end
365
    end
260 ✔
366
end
367

368
function serialize(s::AbstractSerializer, a::Array)
298 ✔
369
    serialize_cycle(s, a) && return
298 ✔
370
    elty = eltype(a)
298 ✔
371
    writetag(s.io, ARRAY_TAG)
298 ✔
372
    if elty !== UInt8
298 ✔
373
        serialize(s, elty)
288 ✔
374
    end
375
    if ndims(a) != 1
298 ✔
376
        serialize(s, size(a))
33 ✔
377
    else
378
        serialize(s, length(a))
298 ✔
379
    end
380
    if isbitstype(elty)
298 ✔
381
        serialize_array_data(s.io, a)
247 ✔
382
    else
383
        _serialize_non_bits_elements!(s, a)
276 ✔
384
    end
385
end
386

387
function serialize(s::AbstractSerializer, a::SubArray{T,N,A}) where {T,N,A<:Array}
6 ✔
388
    # SubArray's copy only selects the relevant data (and reduces the size) but does not
389
    # preserve the type of the argument. This internal function does both:
390
    b = unaliascopy(a)
6 ✔
391
    serialize_any(s, b)
6 ✔
392
end
393

394
serialize(::AbstractSerializer, ::GenericMemory) = error("GenericMemory{:atomic} currently cannot be serialized")
3 ✔
395
function serialize(s::AbstractSerializer, m::Memory)
72 ✔
396
    serialize_cycle_header(s, m) && return
72 ✔
397
    serialize(s, length(m))
72 ✔
398
    elty = eltype(m)
72 ✔
399
    if isbitstype(elty)
72 ✔
400
        serialize_array_data(s.io, m)
72 ✔
401
    else
402
        _serialize_non_bits_elements!(s, m)
3 ✔
403
    end
404
end
405

406
function serialize(s::AbstractSerializer, x::GenericMemoryRef)
3 ✔
407
    serialize_type(s, typeof(x))
3 ✔
408
    serialize(s, getfield(x, :mem))
3 ✔
409
    serialize(s, Base.memoryrefoffset(x))
3 ✔
410
end
411

412
function serialize(s::AbstractSerializer, ss::String)
364 ✔
413
    len = sizeof(ss)
364 ✔
414
    if len > 7
364 ✔
415
        serialize_cycle(s, ss) && return
346 ✔
416
        writetag(s.io, SHARED_REF_TAG)
346 ✔
417
    end
418
    if len <= NTAGS
364 ✔
419
        writetag(s.io, STRING_TAG)
364 ✔
420
        write(s.io, UInt8(len))
364 ✔
421
    else
422
        writetag(s.io, LONGSTRING_TAG)
176 ✔
423
        write(s.io, Int64(len))
176 ✔
424
    end
425
    write(s.io, ss)
364 ✔
426
    nothing
364 ✔
427
end
428

429
function serialize(s::AbstractSerializer, ss::SubString{String})
121 ✔
430
    # avoid saving a copy of the parent string, keeping the type of ss
431
    serialize_any(s, SubString(String(ss)))
121 ✔
432
end
433

434
# Don't serialize the pointers
435
function serialize(s::AbstractSerializer, r::Regex)
3 ✔
436
    serialize_type(s, typeof(r))
3 ✔
437
    serialize(s, r.pattern)
3 ✔
438
    serialize(s, r.compile_options)
3 ✔
439
    serialize(s, r.match_options)
3 ✔
440
end
441

442
function serialize(s::AbstractSerializer, n::BigInt)
3 ✔
443
    serialize_type(s, BigInt)
3 ✔
444
    serialize(s, string(n, base = 62))
3 ✔
445
end
446

447
function serialize(s::AbstractSerializer, ex::Expr)
213 ✔
448
    serialize_cycle(s, ex) && return
213 ✔
449
    l = length(ex.args)
213 ✔
450
    if l <= NTAGS
213 ✔
451
        writetag(s.io, EXPR_TAG)
213 ✔
452
        write(s.io, UInt8(l))
213 ✔
453
    else
454
        writetag(s.io, LONGEXPR_TAG)
3 ✔
455
        write(s.io, Int32(l))
3 ✔
456
    end
457
    serialize(s, ex.head)
213 ✔
458
    for a in ex.args
213 ✔
459
        serialize(s, a)
213 ✔
460
    end
213 ✔
461
end
462

463
function serialize_dict_data(s::AbstractSerializer, d::AbstractDict)
179 ✔
464
    write(s.io, Int32(length(d)))
179 ✔
465
    for (k,v) in d
179 ✔
466
        serialize(s, k)
177 ✔
467
        serialize(s, v)
177 ✔
468
    end
177 ✔
469
end
470

471
function serialize(s::AbstractSerializer, d::Dict)
179 ✔
472
    serialize_cycle_header(s, d) && return
179 ✔
473
    serialize_dict_data(s, d)
179 ✔
474
end
475

476
function serialize(s::AbstractSerializer, d::IdDict)
3 ✔
477
    serialize_cycle(s, d) && return
3 ✔
478
    writetag(s.io, IDDICT_TAG)
3 ✔
479
    serialize_type_data(s, typeof(d))
3 ✔
480
    serialize_dict_data(s, d)
3 ✔
481
end
482

483
function serialize_mod_names(s::AbstractSerializer, m::Module)
387 ✔
484
    p = parentmodule(m)
387 ✔
485
    if p === m || m === Base
387 ✔
486
        key = Base.root_module_key(m)
387 ✔
487
        uuid = key.uuid
387 ✔
488
        serialize(s, uuid === nothing ? nothing : uuid.value)
387 ✔
489
        serialize(s, Symbol(key.name))
387 ✔
490
    else
491
        serialize_mod_names(s, p)
164 ✔
492
        serialize(s, nameof(m))
164 ✔
493
    end
494
end
495

496
function serialize(s::AbstractSerializer, m::Module)
387 ✔
497
    writetag(s.io, MODULE_TAG)
387 ✔
498
    serialize_mod_names(s, m)
387 ✔
499
    writetag(s.io, EMPTYTUPLE_TAG)
387 ✔
500
end
501

502
# TODO: make this bidirectional, so objects can be sent back via the same key
503
const object_numbers = WeakKeyDict()
504
const obj_number_salt = Ref{UInt64}(0)
505
function object_number(::AbstractSerializer, @nospecialize(l))
3 ✔
506
    global obj_number_salt, object_numbers
3 ✔
507
    if haskey(object_numbers, l)
3 ✔
508
        return object_numbers[l]
3 ✔
509
    end
510
    ln = obj_number_salt[]
3 ✔
511
    object_numbers[l] = ln
3 ✔
512
    obj_number_salt[] += 1
3 ✔
513
    return ln::UInt64
3 ✔
514
end
515

516
lookup_object_number(::AbstractSerializer, ::UInt64) = nothing
×
517

518
remember_object(::AbstractSerializer, @nospecialize(_), ::UInt64) = nothing
×
519

520
function lookup_object_number(s::Serializer, n::UInt64)
3 ✔
521
    return get(s.known_object_data, n, nothing)
3 ✔
522
end
523

524
function remember_object(s::Serializer, @nospecialize(o), n::UInt64)
3 ✔
525
    s.known_object_data[n] = o
3 ✔
526
    return nothing
3 ✔
527
end
528

529
function serialize(s::AbstractSerializer, meth::Method)
186 ✔
530
    serialize_cycle(s, meth) && return
186 ✔
531
    writetag(s.io, METHOD_TAG)
186 ✔
532
    write(s.io, object_number(s, meth))
186 ✔
533
    serialize(s, meth.module)
186 ✔
534
    serialize(s, meth.name)
186 ✔
535
    serialize(s, meth.file)
186 ✔
536
    serialize(s, meth.line)
186 ✔
537
    serialize(s, meth.sig)
186 ✔
538
    serialize(s, meth.slot_syms)
186 ✔
539
    serialize(s, meth.nargs)
186 ✔
540
    serialize(s, meth.isva)
186 ✔
541
    serialize(s, meth.is_for_opaque_closure)
186 ✔
542
    serialize(s, meth.nospecializeinfer)
186 ✔
543
    serialize(s, meth.constprop)
186 ✔
544
    serialize(s, meth.purity)
186 ✔
545
    if isdefined(meth, :source)
186 ✔
546
        serialize(s, Base._uncompressed_ast(meth))
186 ✔
547
    else
548
        serialize(s, nothing)
3 ✔
549
    end
550
    if isdefined(meth, :generator)
186 ✔
551
        serialize(s, meth.generator)
3 ✔
552
    else
553
        serialize(s, nothing)
186 ✔
554
    end
555
    if isdefined(meth, :recursion_relation)
186 ✔
556
        serialize(s, meth.recursion_relation)
3 ✔
557
    else
558
        serialize(s, nothing)
186 ✔
559
    end
560
    if isdefined(meth, :external_mt)
186 ✔
561
        error("cannot serialize Method objects with external method tables")
3 ✔
562
    end
563
    nothing
186 ✔
564
end
565

566
function serialize(s::AbstractSerializer, mt::Core.MethodTable)
3 ✔
567
    serialize_type(s, typeof(mt))
3 ✔
568
    serialize(s, mt.name)
3 ✔
569
    serialize(s, mt.module)
3 ✔
570
    nothing
3 ✔
571
end
572

573
function serialize(::AbstractSerializer, ::Core.MethodCache)
3 ✔
574
    error("cannot serialize MethodCache objects")
3 ✔
575
end
576

577
# Only the (strong) parent links and the state bytes are serialized; the
578
# weak intrusive child lists are rebuilt on deserialization by relinking
579
# the source under its parents as if it were newly constructed (which also
580
# re-inherits the parents' current cancellation state).
581
function serialize(s::AbstractSerializer, src::Core.CancellationTokenSource)
3 ✔
582
    serialize_cycle_header(s, src) && return
3 ✔
583
    np = Int(src.nparents)
3 ✔
584
    serialize(s, np % Int64)  # fixed width: streams are word-size independent
3 ✔
585
    for i in 1:np
3 ✔
586
        serialize(s, Base._cancel_parent(src, i))
3 ✔
587
    end
3 ✔
588
    serialize(s, @atomic src.state)
3 ✔
589
    nothing
3 ✔
590
end
591

592
function deserialize(s::AbstractSerializer, ::Type{Core.CancellationTokenSource})
3 ✔
593
    np = Int(deserialize(s)::Int64)
3 ✔
594
    parents = Vector{Any}(undef, np)
3 ✔
595
    for i in 1:np
3 ✔
596
        parents[i] = deserialize(s)::Core.CancellationTokenSource
3 ✔
597
    end
3 ✔
598
    src = Core._new_cancel_source(parents...)::Core.CancellationTokenSource
3 ✔
599
    deserialize_cycle(s, src)
3 ✔
600
    state = deserialize(s)::UInt8
3 ✔
601
    if state != 0x00
3 ✔
602
        # reject severities the API cannot produce rather than letting a
603
        # corrupt stream inject an unescalatable bogus level
604
        if !(state == 0x1 || state == 0x3 || state == 0x4)
3 ✔
605
            throw(ArgumentError("invalid cancellation severity $(repr(state)) in serialized CancellationTokenSource"))
3 ✔
606
        end
607
        # CAS-max with whatever the relinking inherited from the parents;
608
        # severities only ever escalate
609
        Base._raise_state!(src, state)
3 ✔
610
    end
611
    return src
3 ✔
612
end
613

614
# Core.WaitEntryN has a hidden variable-length slot tail that the generic
615
# deserializer - which allocates only the fixed datatype size - cannot
616
# reproduce (the GC would then scan a nonexistent tail). Its contents are
617
# transient wait-registration state that does not round-trip: only the slot
618
# count is written (plus a `nothing` task), and deserialization
619
# reconstructs through the runtime allocator with fresh, free slots.
620
function serialize(s::AbstractSerializer, w::Core.WaitEntryN)
3 ✔
621
    serialize_cycle_header(s, w) && return
3 ✔
622
    serialize(s, nothing)  # task: transient, never round-trips
3 ✔
623
    serialize(s, Int64(w.nslots))
3 ✔
624
    nothing
3 ✔
625
end
626

627
function deserialize(s::AbstractSerializer, ::Type{Core.WaitEntryN})
3 ✔
628
    task = deserialize(s)::Union{Task, Nothing}
3 ✔
629
    ns = Int(deserialize(s)::Int64)
3 ✔
630
    0 <= ns <= typemax(UInt32) ||
3 ✔
631
        throw(ArgumentError("invalid slot count $ns in serialized WaitEntryN"))
632
    w = Base.WaitEntryN(task, ns)
3 ✔
633
    deserialize_cycle(s, w)
3 ✔
634
    return w
3 ✔
635
end
636

637

638
function serialize(s::AbstractSerializer, linfo::Core.MethodInstance)
3 ✔
639
    serialize_cycle(s, linfo) && return
3 ✔
640
    writetag(s.io, METHODINSTANCE_TAG)
3 ✔
641
    serialize(s, nothing)  # for backwards compat
3 ✔
642
    serialize(s, linfo.sparam_vals)
3 ✔
643
    serialize(s, Any)  # for backwards compat
3 ✔
644
    serialize(s, linfo.specTypes)
3 ✔
645
    serialize(s, linfo.def)
3 ✔
646
    nothing
3 ✔
647
end
648

649
function serialize(s::AbstractSerializer, @nospecialize(u::Union))
164 ✔
650
    serialize_type(s, Union, false)
164 ✔
651
    serialize(s, u.a)
164 ✔
652
    serialize(s, u.b)
164 ✔
653
end
654

655
function serialize(s::AbstractSerializer, t::Task)
6 ✔
656
    serialize_cycle(s, t) && return
6 ✔
657
    if istaskstarted(t) && !istaskdone(t)
6 ✔
658
        error("cannot serialize a running Task")
3 ✔
659
    end
660
    # Compiler-injected CodeInstances are process-local optimization metadata and are
661
    # intentionally omitted. Other targets carry explicit Core.invoke semantics.
662
    has_invoked = isdefined(t, :invoked) && !(getfield(t, :invoked) isa Core.CodeInstance)
6 ✔
663
    writetag(s.io, TASK_TAG)
6 ✔
664
    serialize(s, t.code)
6 ✔
665
    serialize(s, t.storage)
6 ✔
666
    serialize(s, t.state)
6 ✔
667
    if t._isexception && (stk = Base.current_exceptions(t); !isempty(stk))
6 ✔
668
        # the exception stack field is hidden inside the task, so if there
669
        # is any information there make a CapturedException from it instead.
670
        # TODO: Handle full exception chain, not just the first one.
671
        serialize(s, CapturedException(stk[1].exception, stk[1].backtrace))
6 ✔
672
    else
673
        serialize(s, t.result)
3 ✔
674
    end
675
    serialize(s, t._isexception)
6 ✔
676
    serialize(s, has_invoked)
6 ✔
677
    if has_invoked
6 ✔
678
        serialize(s, getfield(t, :invoked))
3 ✔
679
    end
680
end
681

682
function serialize(s::AbstractSerializer, g::GlobalRef)
186 ✔
683
    if (g.mod === __deserialized_types__ ) ||
186 ✔
684
        (g.mod === Main && isdefined(g.mod, g.name) && isconst(g.mod, g.name))
685

686
        v = getglobal(g.mod, g.name)
30 ✔
687
        unw = unwrap_unionall(v)
30 ✔
688
        if isa(unw,DataType) && v === unw.name.wrapper && should_send_whole_type(unw)
30 ✔
689
            # handle references to types in Main by sending the whole type.
690
            # needed to be able to send nested functions (#15451).
691
            writetag(s.io, FULL_GLOBALREF_TAG)
15 ✔
692
            serialize(s, v)
15 ✔
693
            return
15 ✔
694
        end
695
    end
696
    writetag(s.io, GLOBALREF_TAG)
186 ✔
697
    serialize(s, g.mod)
186 ✔
698
    serialize(s, g.name)
186 ✔
699
end
700

701
function serialize(s::AbstractSerializer, t::Core.TypeName)
3 ✔
702
    serialize_cycle(s, t) && return
3 ✔
703
    writetag(s.io, TYPENAME_TAG)
3 ✔
704
    write(s.io, object_number(s, t))
3 ✔
705
    serialize_typename(s, t)
3 ✔
706
end
707

708
function serialize_typename(s::AbstractSerializer, t::Core.TypeName)
186 ✔
709
    serialize(s, t.name)
186 ✔
710
    serialize(s, t.names)
186 ✔
711
    primary = unwrap_unionall(t.wrapper)
186 ✔
712
    serialize(s, primary.super)
186 ✔
713
    serialize(s, primary.parameters)
186 ✔
714
    serialize(s, primary.types)
186 ✔
715
    serialize(s, Base.issingletontype(primary))
186 ✔
716
    serialize(s, t.flags & 0x1 == 0x1) # .abstract
186 ✔
717
    serialize(s, t.flags & 0x2 == 0x2) # .mutable
186 ✔
718
    serialize(s, Int32(length(primary.types) - t.n_uninitialized))
186 ✔
719
    serialize(s, t.max_methods)
186 ✔
720
    ms = Base.matches_to_methods(Base._methods_by_ftype(Tuple{t.wrapper, Vararg}, -1, Base.get_world_counter())::Vector, t, nothing).ms
186 ✔
721
    if t.singletonname !== t.name || !isempty(ms)
186 ✔
722
        serialize(s, t.singletonname)
186 ✔
723
        serialize(s, ms)
186 ✔
724
        serialize(s, t.max_args)
186 ✔
725
        kws = Base.matches_to_methods(Base._methods_by_ftype(Tuple{typeof(Core.kwcall), Any, t.wrapper, Vararg}, -1, Base.get_world_counter())::Vector, t, nothing).ms
186 ✔
726
        if isempty(kws)
186 ✔
727
            writetag(s.io, UNDEFREF_TAG)
186 ✔
728
        else
729
            serialize(s, kws)
3 ✔
730
        end
731
    else
732
        writetag(s.io, UNDEFREF_TAG)
×
733
    end
734
    nothing
186 ✔
735
end
736

737
# decide whether to send all data for a type (instead of just its name)
738
function should_send_whole_type(t::DataType)
387 ✔
739
    tn = t.name
387 ✔
740
    # TODO improve somehow?
741
    # send whole type for anonymous functions in Main
742
    name = tn.singletonname
387 ✔
743
    mod = tn.module
387 ✔
744
    mod === __deserialized_types__ && return true
387 ✔
745
    isanonfunction = mod === Main && # only Main
387 ✔
746
        t.super === Function && # only Functions
747
        unsafe_load(unsafe_convert(Ptr{UInt8}, tn.name)) == UInt8('#') && # hidden type
748
        (!isdefined(mod, name) || t != typeof(getglobal(mod, name))) # XXX: 95% accurate test for this being an inner function
749
        # TODO: more accurate test? (tn.name !== "#" name)
750
    return isanonfunction
387 ✔
751
end
752

753
function serialize_type_data(s, @nospecialize(t::DataType))
387 ✔
754
    whole = should_send_whole_type(t)
387 ✔
755
    iswrapper = (t === unwrap_unionall(t.name.wrapper))
387 ✔
756
    if whole && iswrapper
387 ✔
757
        writetag(s.io, WRAPPER_DATATYPE_TAG)
186 ✔
758
        serialize(s, t.name)
186 ✔
759
        return
186 ✔
760
    end
761
    serialize_cycle(s, t) && return
387 ✔
762
    if whole
387 ✔
763
        writetag(s.io, FULL_DATATYPE_TAG)
176 ✔
764
        serialize(s, t.name)
176 ✔
765
    else
766
        writetag(s.io, DATATYPE_TAG)
387 ✔
767
        serialize(s, nameof(t))
387 ✔
768
        serialize(s, parentmodule(t))
387 ✔
769
    end
770
    if !isempty(t.parameters)
387 ✔
771
        if iswrapper
382 ✔
772
            write(s.io, Int32(0))
3 ✔
773
        else
774
            write(s.io, Int32(length(t.parameters)))
382 ✔
775
            for p in t.parameters
382 ✔
776
                serialize(s, p)
382 ✔
777
            end
382 ✔
778
        end
779
    end
780
    nothing
387 ✔
781
end
782

783
function serialize(s::AbstractSerializer, t::DataType)
412 ✔
784
    tag = sertag(t)
412 ✔
785
    tag > 0 && return write_as_tag(s.io, tag)
412 ✔
786
    if t === Tuple
363 ✔
787
        # `sertag` is not able to find types === to `Tuple` because they
788
        # will not have been hash-consed. Plus `serialize_type_data` does not
789
        # handle this case correctly, since Tuple{} != Tuple. `Tuple` is the
790
        # only type with this property. issue #15849
791
        return write_as_tag(s.io, TUPLE_TAG)
×
792
    end
793
    serialize_type_data(s, t)
363 ✔
794
end
795

796
function serialize_type(s::AbstractSerializer, @nospecialize(t::DataType), ref::Bool = false)
387 ✔
797
    tag = sertag(t)
387 ✔
798
    tag > 0 && return writetag(s.io, tag)
387 ✔
799
    writetag(s.io, ref ? REF_OBJECT_TAG : OBJECT_TAG)
387 ✔
800
    serialize_type_data(s, t)
387 ✔
801
end
802

803
function serialize(s::AbstractSerializer, n::Int32)
332 ✔
804
    if 0 <= n <= (n_int_literals-1)
332 ✔
805
        write(s.io, UInt8(ZERO32_TAG+n))
195 ✔
806
    else
807
        writetag(s.io, INT32_TAG)
332 ✔
808
        write(s.io, n)
332 ✔
809
    end
810
    nothing
332 ✔
811
end
812

813
function serialize(s::AbstractSerializer, n::Int64)
535 ✔
814
    if 0 <= n <= (n_int_literals-1)
535 ✔
815
        write(s.io, UInt8(ZERO64_TAG+n))
535 ✔
816
    elseif typemin(Int32) <= n <= typemax(Int32)
439 ✔
817
        writetag(s.io, SHORTINT64_TAG)
439 ✔
818
        write(s.io, Int32(n))
439 ✔
819
    else
820
        writetag(s.io, INT64_TAG)
79 ✔
821
        write(s.io, n)
79 ✔
822
    end
823
    nothing
535 ✔
824
end
825

826
for i in 0:13
827
    tag = Int32(INT8_TAG + i)
828
    ty = TAGS[tag]
829
    (ty === Int32 || ty === Int64) && continue
830
    @eval serialize(s::AbstractSerializer, n::$ty) = (writetag(s.io, $tag); write(s.io, n); nothing)
395 ✔
831
end
832

833
serialize(s::AbstractSerializer, ::Type{Bottom}) = write_as_tag(s.io, BOTTOM_TAG)
268 ✔
834

835
function serialize(s::AbstractSerializer, u::UnionAll)
176 ✔
836
    writetag(s.io, UNIONALL_TAG)
176 ✔
837
    n = 0; t = u
176 ✔
838
    while isa(t, UnionAll)
176 ✔
839
        t = t.body
176 ✔
840
        n += 1
176 ✔
841
    end
176 ✔
842
    if isa(t, DataType) && t === unwrap_unionall(t.name.wrapper)
176 ✔
843
        write(s.io, UInt8(1))
176 ✔
844
        write(s.io, Int16(n))
176 ✔
845
        serialize(s, t)
176 ✔
846
    else
847
        write(s.io, UInt8(0))
3 ✔
848
        serialize(s, u.var)
3 ✔
849
        serialize(s, u.body)
3 ✔
850
    end
851
end
852

853
serialize(s::AbstractSerializer, @nospecialize(x)) = serialize_any(s, x)
404 ✔
854

855
function serialize(s::AbstractSerializer, x::Core.AddrSpace)
72 ✔
856
    serialize_type(s, typeof(x))
72 ✔
857
    write(s.io, Core.bitcast(UInt8, x))
72 ✔
858
end
859

860
function serialize(s::AbstractSerializer, x::Core.IntrinsicFunction)
3 ✔
861
    serialize_type(s, typeof(x))
3 ✔
862
    serialize(s, nameof(x))
3 ✔
863
end
864

865
function serialize_any(s::AbstractSerializer, @nospecialize(x))
404 ✔
866
    tag = sertag(x)
404 ✔
867
    if tag > 0
404 ✔
868
        return write_as_tag(s.io, tag)
402 ✔
869
    end
870
    t = typeof(x)::DataType
387 ✔
871
    if isprimitivetype(t)
387 ✔
872
        serialize_type(s, t)
109 ✔
873
        write(s.io, x)
109 ✔
874
    else
875
        if ismutable(x)
387 ✔
876
            serialize_cycle(s, x) && return
294 ✔
877
            serialize_type(s, t, true)
294 ✔
878
        else
879
            serialize_type(s, t, false)
377 ✔
880
        end
881
        nf = nfields(x)
387 ✔
882
        for i in 1:nf
387 ✔
883
            if isdefined(x, i)
387 ✔
884
                serialize(s, getfield(x, i))
387 ✔
885
            else
886
                writetag(s.io, UNDEFREF_TAG)
6 ✔
887
            end
888
        end
387 ✔
889
    end
890
    nothing
387 ✔
891
end
892

893
"""
894
    Serialization.writeheader(s::AbstractSerializer)
895

896
Write an identifying header to the specified serializer. The header consists of
897
8 bytes as follows:
898

899
| Offset | Description                                     |
900
|:-------|:------------------------------------------------|
901
|   0    | tag byte (0x37)                                 |
902
|   1-2  | signature bytes "JL"                            |
903
|   3    | protocol version                                |
904
|   4    | bits 0-1: endianness: 0 = little, 1 = big       |
905
|   4    | bits 2-3: platform: 0 = 32-bit, 1 = 64-bit      |
906
|   5-7  | reserved                                        |
907
"""
908
function writeheader(s::AbstractSerializer)
274 ✔
909
    io = s.io
274 ✔
910
    writetag(io, HEADER_TAG)
274 ✔
911
    write(io, "JL")  # magic bytes
274 ✔
912
    write(io, UInt8(ser_version))
274 ✔
913
    endianness = (ENDIAN_BOM == 0x04030201 ? 0 :
274 ✔
914
                  ENDIAN_BOM == 0x01020304 ? 1 :
915
                  error("unsupported endianness in serializer"))
916
    machine = (sizeof(Int) == 4 ? 0 :
274 ✔
917
               sizeof(Int) == 8 ? 1 :
918
               error("unsupported word size in serializer"))
919
    write(io, UInt8(endianness) | (UInt8(machine) << 2))
274 ✔
920
    write(io, [0x00,0x00,0x00]) # 3 reserved bytes
274 ✔
921
    nothing
274 ✔
922
end
923

924
# `io` is often not concretely typed, so `read` would not infer as `T`
925
_read(io::IO, ::Type{T}) where {T} = read(io, T)::T
535 ✔
926

927
function readheader(s::AbstractSerializer)
138 ✔
928
    # Tag already read
929
    io = s.io
138 ✔
930
    m1 = _read(io, UInt8)
138 ✔
931
    m2 = _read(io, UInt8)
138 ✔
932
    if m1 != UInt8('J') || m2 != UInt8('L')
138 ✔
933
        error("Unsupported serialization format (got header magic bytes $m1 $m2)")
3 ✔
934
    end
935
    version    = _read(io, UInt8)
138 ✔
936
    flags      = _read(io, UInt8)
138 ✔
937
    _reserved1 = _read(io, UInt8)
138 ✔
938
    _reserved2 = _read(io, UInt8)
138 ✔
939
    _reserved3 = _read(io, UInt8)
138 ✔
940
    endianflag = flags & 0x3
138 ✔
941
    wordflag   = (flags >> 2) & 0x3
138 ✔
942
    _wordsize = wordflag == 0 ? 4 :
138 ✔
943
                wordflag == 1 ? 8 :
944
                error("Unknown word size flag in header")
945
    endian_bom = endianflag == 0 ? 0x04030201 :
138 ✔
946
                 endianflag == 1 ? 0x01020304 :
947
                 error("Unknown endianness flag in header")
948
    # Check protocol compatibility.
949
    endian_bom == ENDIAN_BOM  || error("Serialized byte order mismatch ($(repr(endian_bom)))")
138 ✔
950
    # We don't check wordsize == sizeof(Int) here, as Int is encoded concretely
951
    # as Int32 or Int64, which should be enough to correctly deserialize a range
952
    # of data structures between Julia versions.
953
    if version > ser_version
138 ✔
954
        error("""Cannot read stream serialized with a newer version of Julia.
3 ✔
955
                 Got data version $version > current version $ser_version""")
956
    end
957
    s.version = version
138 ✔
958
    return
138 ✔
959
end
960

961
"""
962
    serialize(stream::IO, value)
963

964
Write an arbitrary value to a stream in an opaque format, such that it can be read back by
965
[`deserialize`](@ref). The read-back value will be as identical as possible to the original,
966
but note that `Ptr` values are serialized as all-zero bit patterns (`NULL`).
967

968
An 8-byte identifying header is written to the stream first. To avoid writing the header,
969
construct a `Serializer` and use it as the first argument to `serialize` instead.
970
See also [`Serialization.writeheader`](@ref).
971

972
The data format can change in minor (1.x) Julia releases, but files written by prior 1.x
973
versions will remain readable. The main exception to this is when the definition of a
974
type in an external package changes. If that occurs, it may be necessary to specify
975
an explicit compatible version of the affected package in your environment.
976
Renaming functions, even private functions, inside packages can also put existing files
977
out of sync. Anonymous functions require special care: because their names are automatically
978
generated, minor code changes can cause them to be renamed.
979
Serializing anonymous functions should be avoided in files intended for long-term storage.
980

981
In some cases, the word size (32- or 64-bit) of the reading and writing machines must match.
982
In rarer cases the OS or architecture must also match, for example when using packages
983
that contain platform-dependent code.
984
"""
985
function serialize(s::IO, x)
274 ✔
986
    ss = Serializer(s)
274 ✔
987
    writeheader(ss)
274 ✔
988
    serialize(ss, x)
274 ✔
989
end
990

991
"""
992
    serialize(filename::AbstractString, value)
993

994
Open a file and serialize the given value to it.
995

996
!!! compat "Julia 1.1"
997
    This method is available as of Julia 1.1.
998
"""
999
serialize(filename::AbstractString, x) = open(io->serialize(io, x), filename, "w")
167 ✔
1000

1001
## deserializing values ##
1002

1003
"""
1004
    deserialize(stream)
1005

1006
Read a value written by [`serialize`](@ref). `deserialize` assumes the binary data read from
1007
`stream` is correct and has been serialized by a compatible implementation of [`serialize`](@ref).
1008
`deserialize` is designed for simplicity and performance, and so does not validate
1009
the data read. Malformed data can result in process termination. The caller must ensure
1010
the integrity and correctness of data read from `stream`.
1011

1012
!!! warning
1013
    `deserialize` is not secure against maliciously constructed data, which can execute
1014
    arbitrary code when deserialized. Never deserialize data received from an untrusted or
1015
    unauthenticated source.
1016
"""
1017
deserialize(s::IO) = deserialize(Serializer(s))
138 ✔
1018

1019
"""
1020
    deserialize(filename::AbstractString)
1021

1022
Open a file and deserialize its contents.
1023

1024
!!! compat "Julia 1.1"
1025
    This method is available as of Julia 1.1.
1026
"""
1027
deserialize(filename::AbstractString) = open(deserialize, filename)
6 ✔
1028

1029
function deserialize(s::AbstractSerializer)
535 ✔
1030
    handle_deserialize(s, Int32(_read(s.io, UInt8)))
535 ✔
1031
end
1032

1033
function deserialize_cycle(s::AbstractSerializer, @nospecialize(x))
230 ✔
1034
    slot = pop!(s.pending_refs)
230 ✔
1035
    _setbackref!(s, slot, x)
230 ✔
1036
    nothing
230 ✔
1037
end
1038

1039
# optimized version of:
1040
#     slot = s.counter; s.counter += 1
1041
#     push!(s.pending_refs, slot)
1042
#     slot = pop!(s.pending_refs)
1043
#     _setbackref!(s, slot, x)
1044
function resolve_ref_immediately(s::AbstractSerializer, @nospecialize(x))
501 ✔
1045
    _setbackref!(s, s.counter, x)
501 ✔
1046
    s.counter += 1
501 ✔
1047
    nothing
501 ✔
1048
end
1049

1050
# deserialize_ is an internal function to dispatch on the tag
1051
# describing the serialized representation. the number of
1052
# representations is fixed, so deserialize_ does not get extended.
1053
function handle_deserialize(s::AbstractSerializer, b::Int32)
535 ✔
1054
    if b == 0
535 ✔
1055
        return desertag(Int32(_read(s.io, UInt8)))
509 ✔
1056
    end
1057
    if b >= VALUE_TAGS
535 ✔
1058
        return desertag(b)
535 ✔
1059
    elseif b == TUPLE_TAG
535 ✔
1060
        return deserialize_tuple(s, Int(_read(s.io, UInt8)))
396 ✔
1061
    elseif b == SHORTBACKREF_TAG
535 ✔
1062
        id = _read(s.io, UInt16)
498 ✔
1063
        return _getbackref(s, Int(id))
498 ✔
1064
    elseif b == BACKREF_TAG
535 ✔
1065
        id = _read(s.io, Int32)
6 ✔
1066
        return _getbackref(s, Int(id))
6 ✔
1067
    elseif b == ARRAY_TAG
535 ✔
1068
        return deserialize_array(s)
420 ✔
1069
    elseif b == DATATYPE_TAG
535 ✔
1070
        return deserialize_datatype(s, false)
488 ✔
1071
    elseif b == FULL_DATATYPE_TAG
535 ✔
1072
        return deserialize_datatype(s, true)
35 ✔
1073
    elseif b == WRAPPER_DATATYPE_TAG
535 ✔
1074
        tname = deserialize(s)::Core.TypeName
126 ✔
1075
        return unwrap_unionall(tname.wrapper)
126 ✔
1076
    elseif b == OBJECT_TAG
535 ✔
1077
        t = deserialize(s)
488 ✔
1078
        if t === Missing
488 ✔
1079
            return missing
3 ✔
1080
        end
1081
        return deserialize(s, t)
488 ✔
1082
    elseif b == REF_OBJECT_TAG
535 ✔
1083
        slot = s.counter; s.counter += 1
152 ✔
1084
        push!(s.pending_refs, slot)
152 ✔
1085
        t = deserialize(s)
152 ✔
1086
        return deserialize(s, t)
152 ✔
1087
    elseif b == SHARED_REF_TAG
535 ✔
1088
        slot = s.counter; s.counter += 1
474 ✔
1089
        obj = deserialize(s)
474 ✔
1090
        _setbackref!(s, slot, obj)
474 ✔
1091
        return obj
474 ✔
1092
    elseif b == SYMBOL_TAG
535 ✔
1093
        return deserialize_symbol(s, Int(_read(s.io, UInt8)))
528 ✔
1094
    elseif b == SHORTINT64_TAG
532 ✔
1095
        return Int64(_read(s.io, Int32))
474 ✔
1096
    elseif b == EXPR_TAG
522 ✔
1097
        return deserialize_expr(s, Int(_read(s.io, UInt8)))
316 ✔
1098
    elseif b == MODULE_TAG
522 ✔
1099
        return deserialize_module(s)
488 ✔
1100
    elseif b == STRING_TAG
522 ✔
1101
        return deserialize_string(s, Int(_read(s.io, UInt8)))
495 ✔
1102
    elseif b == LONGSTRING_TAG
501 ✔
1103
        return deserialize_string(s, Int(_read(s.io, Int64)))
122 ✔
1104
    elseif b == SIMPLEVECTOR_TAG
501 ✔
1105
        return deserialize_svec(s)
126 ✔
1106
    elseif b == GLOBALREF_TAG
501 ✔
1107
        return GlobalRef(deserialize(s)::Module, deserialize(s)::Symbol)
126 ✔
1108
    elseif b == FULL_GLOBALREF_TAG
501 ✔
1109
        ty = deserialize(s)
22 ✔
1110
        tn = unwrap_unionall(ty).name
22 ✔
1111
        return GlobalRef(tn.module, tn.name)
22 ✔
1112
    elseif b == LONGTUPLE_TAG
501 ✔
1113
        return deserialize_tuple(s, Int(_read(s.io, Int32)))
3 ✔
1114
    elseif b == LONGEXPR_TAG
501 ✔
1115
        return deserialize_expr(s, Int(_read(s.io, Int32)))
3 ✔
1116
    elseif b == LONGBACKREF_TAG
501 ✔
UNCOV
1117
        id = _read(s.io, Int64)
×
UNCOV
1118
        return _getbackref(s, Int(id))
×
1119
    elseif b == LONGSYMBOL_TAG
501 ✔
1120
        return deserialize_symbol(s, Int(_read(s.io, Int32)))
104 ✔
1121
    elseif b == HEADER_TAG
501 ✔
1122
        readheader(s)
138 ✔
1123
        return deserialize(s)
138 ✔
1124
    elseif b == INT8_TAG
501 ✔
1125
        return _read(s.io, Int8)
21 ✔
1126
    elseif b == INT8_TAG+1
501 ✔
1127
        return _read(s.io, UInt8)
129 ✔
1128
    elseif b == INT8_TAG+2
501 ✔
1129
        return _read(s.io, Int16)
21 ✔
1130
    elseif b == INT8_TAG+3
501 ✔
1131
        return _read(s.io, UInt16)
132 ✔
1132
    elseif b == INT32_TAG
501 ✔
1133
        return _read(s.io, Int32)
112 ✔
1134
    elseif b == INT8_TAG+5
501 ✔
1135
        return _read(s.io, UInt32)
39 ✔
1136
    elseif b == INT64_TAG
501 ✔
1137
        return _read(s.io, Int64)
6 ✔
1138
    elseif b == INT8_TAG+7
501 ✔
1139
        return _read(s.io, UInt64)
131 ✔
1140
    elseif b == INT8_TAG+8
501 ✔
1141
        return _read(s.io, Int128)
6 ✔
1142
    elseif b == INT8_TAG+9
501 ✔
1143
        return _read(s.io, UInt128)
488 ✔
1144
    elseif b == INT8_TAG+10
325 ✔
1145
        return _read(s.io, Float16)
6 ✔
1146
    elseif b == INT8_TAG+11
325 ✔
1147
        return _read(s.io, Float32)
3 ✔
1148
    elseif b == INT8_TAG+12
325 ✔
1149
        return _read(s.io, Float64)
42 ✔
1150
    elseif b == INT8_TAG+13
322 ✔
1151
        return _read(s.io, Char)
21 ✔
1152
    elseif b == IDDICT_TAG
322 ✔
1153
        slot = s.counter; s.counter += 1
3 ✔
1154
        push!(s.pending_refs, slot)
3 ✔
1155
        t = deserialize(s)
3 ✔
1156
        return deserialize_dict(s, t)
3 ✔
1157
    end
1158
    t = desertag(b)::DataType
322 ✔
1159
    if ismutabletype(t) && fieldcount(t) > 0
322 ✔
1160
        slot = s.counter; s.counter += 1
126 ✔
1161
        push!(s.pending_refs, slot)
126 ✔
1162
    end
1163
    return deserialize(s, t)
322 ✔
1164
end
1165

1166
function deserialize_symbol(s::AbstractSerializer, len::Int)
528 ✔
1167
    str = Base._string_n(len)
528 ✔
1168
    unsafe_read(s.io, pointer(str), len)
528 ✔
1169
    sym = Symbol(str)
528 ✔
1170
    if len > 7
528 ✔
1171
        resolve_ref_immediately(s, sym)
501 ✔
1172
    end
1173
    return sym
528 ✔
1174
end
1175

1176
function deserialize_tuple(s::AbstractSerializer, len)
396 ✔
1177
    len == 0 && return ()
396 ✔
1178
    Base.Cartesian.@nexprs 10 i -> begin
396 ✔
1179
        len == i && return (Base.Cartesian.@ntuple i _ -> deserialize(s))
1180
    end
1181
    return ntupleany(_ -> deserialize(s), len)
3 ✔
1182
end
1183

1184
function deserialize_svec(s::AbstractSerializer)
126 ✔
1185
    n = _read(s.io, Int32)
126 ✔
1186
    svec(Any[ deserialize(s) for _=1:n ]...)
126 ✔
1187
end
1188

1189
function deserialize_module(s::AbstractSerializer)
488 ✔
1190
    mkey = deserialize(s)
488 ✔
1191
    if isa(mkey, Tuple)
488 ✔
1192
        # old version, TODO: remove
1193
        if mkey === ()
×
1194
            return Main
×
1195
        end
1196
        m = Base.root_module(mkey[1])
×
UNCOV
1197
        for i = 2:length(mkey)
×
UNCOV
1198
            m = getglobal(m, mkey[i])::Module
×
UNCOV
1199
        end
×
1200
    else
1201
        name = String(deserialize(s)::Symbol)
488 ✔
1202
        pkg = (mkey === nothing) ? Base.PkgId(name) : Base.PkgId(Base.UUID(mkey), name)
488 ✔
1203
        m = Base.root_module(pkg)
488 ✔
1204
        mname = deserialize(s)
488 ✔
1205
        while mname !== ()
488 ✔
1206
            m = getglobal(m, mname)::Module
336 ✔
1207
            mname = deserialize(s)
336 ✔
1208
        end
336 ✔
1209
    end
1210
    return m
488 ✔
1211
end
1212

1213
function deserialize(s::AbstractSerializer, ::Type{Method})
126 ✔
1214
    lnumber = _read(s.io, UInt64)
126 ✔
1215
    meth = lookup_object_number(s, lnumber)
126 ✔
1216
    if meth !== nothing
126 ✔
1217
        meth = meth::Method
3 ✔
1218
        makenew = false
3 ✔
1219
    else
1220
        meth = ccall(:jl_new_method_uninit, Ref{Method}, (Any,), Main)
126 ✔
1221
        makenew = true
126 ✔
1222
    end
1223
    deserialize_cycle(s, meth)
126 ✔
1224
    mod = deserialize(s)::Module
126 ✔
1225
    name = deserialize(s)::Symbol
126 ✔
1226
    file = deserialize(s)::Symbol
126 ✔
1227
    line = deserialize(s)::Int32
126 ✔
1228
    sig = deserialize(s)::Type
126 ✔
1229
    syms = deserialize(s)
126 ✔
1230
    if syms isa SimpleVector
126 ✔
1231
        # < v1.2
1232
        _ambig = deserialize(s)
3 ✔
1233
        slot_syms = nothing
3 ✔
1234
    else
1235
        slot_syms = syms::String
126 ✔
1236
    end
1237
    nargs = deserialize(s)::Int32
126 ✔
1238
    isva = deserialize(s)::Bool
126 ✔
1239
    is_for_opaque_closure = false
126 ✔
1240
    nospecializeinfer = false
126 ✔
1241
    constprop = 0x00
126 ✔
1242
    purity = 0x0000
126 ✔
1243
    template_or_is_opaque = with(current_module => mod) do
126 ✔
1244
        deserialize(s)
126 ✔
1245
    end
1246
    template = if isa(template_or_is_opaque, Bool)
126 ✔
1247
        is_for_opaque_closure = template_or_is_opaque
126 ✔
1248
        if format_version(s) >= 24
126 ✔
1249
            nospecializeinfer = deserialize(s)::Bool
126 ✔
1250
        end
1251
        if format_version(s) >= 14
126 ✔
1252
            constprop = deserialize(s)::UInt8
126 ✔
1253
        end
1254
        if format_version(s) >= 26
126 ✔
1255
            purity = deserialize(s)::UInt16
126 ✔
UNCOV
1256
        elseif format_version(s) >= 17
×
UNCOV
1257
            purity = UInt16(deserialize(s)::UInt8)
×
1258
        end
1259
        with(current_module => mod) do
126 ✔
1260
            deserialize(s)
126 ✔
1261
        end
1262
    else
1263
        template_or_is_opaque
126 ✔
1264
    end
1265
    generator = deserialize(s)
126 ✔
1266
    recursion_relation = nothing
126 ✔
1267
    if format_version(s) >= 15
126 ✔
1268
        recursion_relation = deserialize(s)
126 ✔
1269
    end
1270
    if makenew
126 ✔
1271
        meth.module = mod
126 ✔
1272
        meth.debuginfo = NullDebugInfo
126 ✔
1273
        meth.name = name
126 ✔
1274
        meth.file = file
126 ✔
1275
        meth.line = line
126 ✔
1276
        meth.sig = sig
126 ✔
1277
        meth.nargs = nargs
126 ✔
1278
        meth.isva = isva
126 ✔
1279
        meth.is_for_opaque_closure = is_for_opaque_closure
126 ✔
1280
        meth.nospecializeinfer = nospecializeinfer
126 ✔
1281
        meth.constprop = constprop
126 ✔
1282
        meth.purity = purity
126 ✔
1283
        if template !== nothing
126 ✔
1284
            # TODO: compress template
1285
            template = template::CodeInfo
126 ✔
1286
            if format_version(s) < 29
126 ✔
1287
                template.nargs = nargs
3 ✔
1288
                template.isva = isva
3 ✔
1289
            end
1290
            meth.source = template
126 ✔
1291
            meth.debuginfo = template.debuginfo
126 ✔
1292
            if slot_syms === nothing
126 ✔
1293
                slot_syms = ccall(:jl_compress_argnames, Ref{String}, (Any,), meth.source.slotnames)
3 ✔
1294
            end
1295
        end
1296
        # pre-v1.2 streams carry no slot names, so they can only be recovered from the source
1297
        slot_syms === nothing && error("cannot deserialize method `$name` without source from a pre-v1.2 stream")
126 ✔
1298
        meth.slot_syms = slot_syms
126 ✔
1299
        if generator !== nothing
126 ✔
1300
            meth.generator = generator
3 ✔
1301
        end
1302
        if recursion_relation !== nothing
126 ✔
1303
            meth.recursion_relation = recursion_relation
3 ✔
1304
        end
1305
        if !is_for_opaque_closure
126 ✔
1306
            mt = Core.methodtable
126 ✔
1307
            if nothing === ccall(:jl_methtable_lookup, Any, (Any, UInt), sig, Base.get_world_counter()) # XXX: quite sketchy?
126 ✔
1308
                ccall(:jl_method_table_insert, Cvoid, (Any, Any), mt, meth)
126 ✔
1309
            end
1310
        end
1311
        remember_object(s, meth, lnumber)
126 ✔
1312
    end
1313
    return meth
126 ✔
1314
end
1315

1316
function deserialize(s::AbstractSerializer, ::Type{Core.MethodTable})
3 ✔
1317
    name = deserialize(s)::Symbol
3 ✔
1318
    mod = deserialize(s)::Module
3 ✔
1319
    return getglobal(mod, name)::Core.MethodTable
3 ✔
1320
end
1321

1322
function deserialize(s::AbstractSerializer, ::Type{Core.MethodInstance})
3 ✔
1323
    linfo = ccall(:jl_new_method_instance_uninit, Ref{Core.MethodInstance}, (Ptr{Cvoid},), C_NULL)
3 ✔
1324
    deserialize_cycle(s, linfo)
3 ✔
1325
    if format_version(s) < 28
3 ✔
1326
        tag = Int32(_read(s.io, UInt8))
×
1327
        if tag != UNDEFREF_TAG
×
UNCOV
1328
            code = handle_deserialize(s, tag)::CodeInfo
×
UNCOV
1329
            ci = ccall(:jl_new_codeinst_for_uninferred, Ref{CodeInstance}, (Any, Any), linfo, code)
×
UNCOV
1330
            @atomic linfo.cache = ci
×
1331
        end
1332
    end
1333
    tag = Int32(_read(s.io, UInt8))
3 ✔
1334
    if tag != UNDEFREF_TAG
3 ✔
1335
        # for reading files prior to v1.2
1336
        handle_deserialize(s, tag)
3 ✔
1337
    end
1338
    linfo.sparam_vals = deserialize(s)::SimpleVector
3 ✔
1339
    _rettype = deserialize(s)  # for backwards compat
3 ✔
1340
    linfo.specTypes = deserialize(s)
3 ✔
1341
    linfo.def = deserialize(s)
3 ✔
1342
    return linfo
3 ✔
1343
end
1344

1345
function deserialize(s::AbstractSerializer, ::Type{Core.LineInfoNode})
3 ✔
1346
    mod = deserialize(s)
3 ✔
1347
    if mod isa Module
3 ✔
1348
        method = deserialize(s)
3 ✔
1349
    else
1350
        # files post v1.2 and pre v1.6 are broken
UNCOV
1351
        method = mod
×
UNCOV
1352
        mod = Main
×
1353
    end
1354
    return Core.LineInfoNode(mod, method, deserialize(s)::Symbol, Int32(deserialize(s)::Union{Int32, Int}), Int32(deserialize(s)::Union{Int32, Int}))
3 ✔
1355
end
1356

1357

1358
function deserialize(s::AbstractSerializer, ::Type{PhiNode})
3 ✔
1359
    edges = deserialize(s)
3 ✔
1360
    if edges isa Vector{Any}
3 ✔
UNCOV
1361
        edges = Vector{Int32}(edges)
×
1362
    end
1363
    values = deserialize(s)::Vector{Any}
3 ✔
1364
    return PhiNode(edges, values)
3 ✔
1365
end
1366

1367
# v1.12 disallows bare symbols in IR, but older CodeInfos might still have them
1368
function symbol_to_globalref(@nospecialize(x), m::Module)
126 ✔
1369
    mapper(@nospecialize(x)) = symbol_to_globalref(x, m)
126 ✔
1370
    if x isa Symbol
126 ✔
1371
        return GlobalRef(m, x)
3 ✔
1372
    elseif x isa Expr
126 ✔
1373
        return Expr(x.head, map(mapper, x.args)...)
126 ✔
1374
    elseif x isa ReturnNode
126 ✔
1375
        return ReturnNode(mapper(x.val))
126 ✔
1376
    elseif x isa GotoIfNot
126 ✔
1377
        return GotoIfNot(mapper(x.cond), x.dest)
60 ✔
1378
    else
1379
        return x
126 ✔
1380
    end
1381
end
1382

1383
function deserialize(s::AbstractSerializer, ::Type{CodeInfo})
126 ✔
1384
    ci = ccall(:jl_new_code_info_uninit, Ref{CodeInfo}, ())
126 ✔
1385
    deserialize_cycle(s, ci)
126 ✔
1386
    code = deserialize(s)::Vector{Any}
126 ✔
1387
    ci.code = code
126 ✔
1388
    ci.debuginfo = NullDebugInfo
126 ✔
1389
    # allow older-style IR with return and gotoifnot Exprs
1390
    for i in 1:length(code)
126 ✔
1391
        stmt = code[i]
126 ✔
1392
        if isa(stmt, Expr)
126 ✔
1393
            ex = stmt::Expr
126 ✔
1394
            if ex.head === :return
126 ✔
1395
                code[i] = ReturnNode(isempty(ex.args) ? nothing : ex.args[1])
3 ✔
1396
            elseif ex.head === :gotoifnot
126 ✔
UNCOV
1397
                code[i] = GotoIfNot(ex.args[1], ex.args[2])
×
1398
            end
1399
        end
1400
    end
126 ✔
1401
    cm = current_module[]
126 ✔
1402
    if cm !== nothing
126 ✔
1403
        map!(x->symbol_to_globalref(x, cm), code)
126 ✔
1404
    end
1405
    _x = deserialize(s)
126 ✔
1406
    have_debuginfo = _x isa Core.DebugInfo
126 ✔
1407
    if have_debuginfo
126 ✔
1408
        ci.debuginfo = _x
126 ✔
1409
    else
1410
        _codelocs = _x::Vector{Int32}
3 ✔
1411
        # TODO: convert codelocs to debuginfo format?
1412
    end
1413
    _x = deserialize(s)
126 ✔
1414
    if _x isa Array || _x isa Int
126 ✔
1415
        pre_12 = false
126 ✔
1416
    else
1417
        pre_12 = true
3 ✔
1418
        # < v1.2
1419
        ci.method_for_inference_limit_heuristics = _x
3 ✔
1420
        _x = deserialize(s)
3 ✔
1421
    end
1422
    ci.ssavaluetypes = _x
126 ✔
1423
    if pre_12
126 ✔
1424
        _linetable = deserialize(s)
3 ✔
1425
        # TODO: convert linetable to debuginfo format?
1426
    end
1427
    ssaflags = deserialize(s)
126 ✔
1428
    if length(ssaflags) ≠ length(code)
126 ✔
1429
        # make sure the length of `ssaflags` matches that of `code`
1430
        # so that the latest inference doesn't throw on IRs serialized from old versions
1431
        ssaflags = UInt32[0x00 for _ in 1:length(code)]
3 ✔
1432
    elseif eltype(ssaflags) != UInt32
126 ✔
UNCOV
1433
        ssaflags = map(UInt32, ssaflags)
×
1434
    end
1435
    ci.ssaflags = ssaflags
126 ✔
1436
    if pre_12
126 ✔
1437
        ci.slotflags = deserialize(s)
3 ✔
1438
    else
1439
        if format_version(s) <= 26
126 ✔
1440
            ci.method_for_inference_limit_heuristics = deserialize(s)
3 ✔
1441
        end
1442
        if !have_debuginfo # pre v1.11 format
126 ✔
1443
            _linetable = deserialize(s)
3 ✔
1444
            # TODO: convert linetable to debuginfo format?
1445
        end
1446
    end
1447
    ci.slotnames = deserialize(s)
126 ✔
1448
    if !pre_12
126 ✔
1449
        ci.slotflags = deserialize(s)
126 ✔
1450
        ci.slottypes = deserialize(s)
126 ✔
1451
        ci.rettype = deserialize(s)
126 ✔
1452
        ci.parent = deserialize(s)
126 ✔
1453
        if format_version(s) < 29 && ci.parent isa MethodInstance && ci.parent.def isa Method
126 ✔
UNCOV
1454
            ci.nargs = ci.parent.def.nargs
×
1455
        end
1456
        world_or_edges = deserialize(s)
126 ✔
1457
        pre_13 = isa(world_or_edges, Union{UInt, Int})
126 ✔
1458
        if pre_13
126 ✔
UNCOV
1459
            ci.min_world = reinterpret(UInt, world_or_edges)
×
UNCOV
1460
            ci.max_world = reinterpret(UInt, deserialize(s))
×
1461
        else
1462
            ci.edges = world_or_edges
126 ✔
1463
            ci.min_world = deserialize(s)::UInt
126 ✔
1464
            ci.max_world = deserialize(s)::UInt
126 ✔
1465
        end
1466
        if format_version(s) >= 29
126 ✔
1467
            ci.method_for_inference_limit_heuristics = deserialize(s)
126 ✔
1468
        end
1469
    end
1470
    if format_version(s) <= 26
126 ✔
1471
        deserialize(s)::Bool # inferred
3 ✔
1472
    end
1473
    if format_version(s) < 22
126 ✔
1474
        inlining_cost = deserialize(s)
3 ✔
1475
        if isa(inlining_cost, Bool)
3 ✔
1476
            Core.Compiler.set_inlineable!(ci, inlining_cost)
3 ✔
1477
        else
UNCOV
1478
            ci.inlining_cost = inlining_cost
×
1479
        end
1480
    end
1481
    if format_version(s) >= 29
126 ✔
1482
        ci.nargs = deserialize(s)
126 ✔
1483
    end
1484
    ci.propagate_inbounds = deserialize(s)
126 ✔
1485
    if format_version(s) < 23
126 ✔
1486
        deserialize(s) # `pure` field has been removed
3 ✔
1487
    end
1488
    if format_version(s) >= 20
126 ✔
1489
        ci.has_fcall = deserialize(s)
126 ✔
1490
    end
1491
    if format_version(s) >= 30
126 ✔
1492
        ci.has_image_globalref = deserialize(s)::Bool
126 ✔
1493
    end
1494
    if format_version(s) >= 24
126 ✔
1495
        ci.nospecializeinfer = deserialize(s)::Bool
126 ✔
1496
    end
1497
    if format_version(s) >= 29
126 ✔
1498
        ci.isva = deserialize(s)::Bool
126 ✔
1499
    end
1500
    if format_version(s) >= 21
126 ✔
1501
        ci.inlining = deserialize(s)::UInt8
126 ✔
1502
    end
1503
    if format_version(s) >= 14
126 ✔
1504
        ci.constprop = deserialize(s)::UInt8
126 ✔
1505
    end
1506
    if format_version(s) >= 26
126 ✔
1507
        ci.purity = deserialize(s)::UInt16
126 ✔
1508
    elseif format_version(s) >= 17
3 ✔
UNCOV
1509
        ci.purity = deserialize(s)::UInt8
×
1510
    end
1511
    if format_version(s) >= 22
126 ✔
1512
        ci.inlining_cost = deserialize(s)::UInt16
126 ✔
1513
    end
1514
    ci.debuginfo = NullDebugInfo
126 ✔
1515
    hoist_returned_calls!(ci)
126 ✔
1516
    return ci
126 ✔
1517
end
1518

1519
# Lowering before v1.12 put the creation of a generic function directly in a `return`,
1520
# which `deserialize_expr` rewrites into a `Core.define_method` call in place. Since a
1521
# `return` value must be an argument, move such a call into a statement of its own. The
1522
# statement is appended so that no SSA value or label needs renumbering.
1523
function hoist_returned_calls!(ci::CodeInfo)
126 ✔
1524
    code = ci.code
126 ✔
1525
    for i in 1:length(code)
126 ✔
1526
        stmt = code[i]
126 ✔
1527
        isa(stmt, ReturnNode) && isdefined(stmt, :val) || continue
126 ✔
1528
        val = stmt.val
126 ✔
1529
        isa(val, Expr) && val.head === :call || continue
126 ✔
1530
        n = length(code)
3 ✔
1531
        push!(code, val, ReturnNode(SSAValue(n + 1)))
3 ✔
1532
        code[i] = GotoNode(n + 1)
3 ✔
1533
        push!(ci.ssaflags, 0x00000000, 0x00000000)
3 ✔
1534
        ssavaluetypes = ci.ssavaluetypes
3 ✔
1535
        if isa(ssavaluetypes, Int)
3 ✔
1536
            ci.ssavaluetypes = ssavaluetypes + 2
3 ✔
1537
        else
UNCOV
1538
            push!(ssavaluetypes::Vector{Any}, Any, Any)
×
1539
        end
1540
    end
126 ✔
1541
    return ci
126 ✔
1542
end
1543

1544
import Core: NullDebugInfo
1545

1546
if Int === Int64
1547
const OtherInt = Int32
1548
else
1549
const OtherInt = Int64
1550
end
1551

1552
function deserialize_array(s::AbstractSerializer)
420 ✔
1553
    slot = s.counter; s.counter += 1
420 ✔
1554
    d1 = deserialize(s)
420 ✔
1555
    if isa(d1, Type)
420 ✔
1556
        elty = d1
420 ✔
1557
        d1 = deserialize(s)
420 ✔
1558
    else
1559
        elty = UInt8
128 ✔
1560
    end
1561
    if isa(d1, Int32) || isa(d1, Int64)
420 ✔
1562
        if elty !== Bool && isbitstype(elty)
420 ✔
1563
            a = Vector{elty}(undef, d1)
390 ✔
1564
            _setbackref!(s, slot, a)
390 ✔
1565
            return read!(s.io, a)
390 ✔
1566
        end
1567
        dims = (Int(d1),)
420 ✔
1568
    elseif d1 isa Dims
24 ✔
1569
        dims = d1::Dims
24 ✔
1570
    else
UNCOV
1571
        dims = convert(Dims, d1::Tuple{Vararg{OtherInt}})::Dims
×
1572
    end
1573
    if isbitstype(elty)
420 ✔
1574
        n = prod(dims)::Int
21 ✔
1575
        if elty === Bool && n > 0
21 ✔
1576
            A = Array{Bool, length(dims)}(undef, dims)
3 ✔
1577
            i = 1
3 ✔
1578
            while i <= n
3 ✔
1579
                b = _read(s.io, UInt8)
3 ✔
1580
                v = (b >> 7) != 0
3 ✔
1581
                count = b & 0x7f
3 ✔
1582
                nxt = i + count
3 ✔
1583
                while i < nxt
3 ✔
1584
                    A[i] = v
3 ✔
1585
                    i += 1
3 ✔
1586
                end
3 ✔
1587
            end
3 ✔
1588
        else
1589
            A = read!(s.io, Array{elty}(undef, dims))
21 ✔
1590
        end
1591
        _setbackref!(s, slot, A)
21 ✔
1592
        return A
21 ✔
1593
    end
1594
    A = Array{elty, length(dims)}(undef, dims)
420 ✔
1595
    _setbackref!(s, slot, A)
420 ✔
1596
    _sizehint_backref!(s, s.counter + div(length(A)::Int,4))
420 ✔
1597
    deserialize_fillarray!(A, s)
420 ✔
1598
    return A
420 ✔
1599
end
1600

1601
function deserialize_fillarray!(A::Union{Array{T},Memory{T}}, s::AbstractSerializer) where {T}
420 ✔
1602
    for i = eachindex(A)
420 ✔
1603
        tag = Int32(_read(s.io, UInt8))
377 ✔
1604
        if tag != UNDEFREF_TAG
377 ✔
1605
            @inbounds A[i] = handle_deserialize(s, tag)
377 ✔
1606
        end
1607
    end
377 ✔
1608
    return A
420 ✔
1609
end
1610

1611
function deserialize(s::AbstractSerializer, X::Type{Memory{T}} where T)
102 ✔
1612
    slot = pop!(s.pending_refs) # e.g. deserialize_cycle
102 ✔
1613
    n = deserialize(s)::Int
102 ✔
1614
    elty = eltype(X)
102 ✔
1615
    if isbitstype(elty)
102 ✔
1616
        A = X(undef, n)
102 ✔
1617
        if X === Memory{Bool}
102 ✔
1618
            i = 1
3 ✔
1619
            while i <= n
3 ✔
1620
                b = _read(s.io, UInt8)
3 ✔
1621
                v = (b >> 7) != 0
3 ✔
1622
                count = b & 0x7f
3 ✔
1623
                nxt = i + count
3 ✔
1624
                while i < nxt
3 ✔
1625
                    A[i] = v
3 ✔
1626
                    i += 1
3 ✔
1627
                end
3 ✔
1628
            end
3 ✔
1629
        else
1630
            A = read!(s.io, A)::X
102 ✔
1631
        end
1632
        _setbackref!(s, slot, A)
102 ✔
1633
        return A
102 ✔
1634
    end
1635
    A = X(undef, n)
3 ✔
1636
    _setbackref!(s, slot, A)
3 ✔
1637
    _sizehint_backref!(s, s.counter + div(n, 4))
3 ✔
1638
    deserialize_fillarray!(A, s)
3 ✔
1639
    return A
3 ✔
1640
end
1641

1642
function deserialize(s::AbstractSerializer, X::Type{MemoryRef{T}} where T)
3 ✔
1643
    x = Core.memoryref(deserialize(s))::X
3 ✔
1644
    i = deserialize(s)::Int
3 ✔
1645
    i == 1 || (x = Core.memoryrefnew(x, i, true))
3 ✔
1646
    return x::X
3 ✔
1647
end
1648

1649
function deserialize(s::AbstractSerializer, X::Type{Core.AddrSpace{M}} where M)
102 ✔
1650
    Core.bitcast(X, _read(s.io, UInt8))
102 ✔
1651
end
1652

1653
function deserialize(s::AbstractSerializer, ::Type{Core.IntrinsicFunction})
3 ✔
1654
    name = deserialize(s)::Symbol
3 ✔
1655
    return getfield(Core.Intrinsics, name)::Core.IntrinsicFunction
3 ✔
1656
end
1657

1658
function deserialize_expr(s::AbstractSerializer, len)
316 ✔
1659
    e = Expr(:temp)
316 ✔
1660
    resolve_ref_immediately(s, e)
316 ✔
1661
    e.head = deserialize(s)::Symbol
316 ✔
1662
    e.args = Any[ deserialize(s) for _ = 1:len ]
316 ✔
1663

1664
    # Rewrite old :method expressions to define_method calls
1665
    if e.head === :method
316 ✔
1666
        mod = current_module[]
3 ✔
1667
        if mod === nothing
3 ✔
1668
            # No current module context, keep the :method expression and hope for the best
1669
            # This shouldn't happen in practice for deserialization of top-level code
1670
            return e
3 ✔
1671
        end
1672

1673
        if len == 1
3 ✔
1674
            # Short form: (:method name) → (call Core.define_method module (inert name))
1675
            name = e.args[1]
3 ✔
1676
            if name isa GlobalRef
3 ✔
1677
                # Extract module and name from GlobalRef
1678
                mod_ref = name.mod
3 ✔
1679
                sym = name.name
3 ✔
1680
                e = Expr(:call, GlobalRef(Core, :define_method), mod_ref, QuoteNode(sym))
3 ✔
1681
            else
1682
                # Simple symbol - use the current module
1683
                e = Expr(:call, GlobalRef(Core, :define_method), mod, QuoteNode(name))
3 ✔
1684
            end
1685
        elseif len == 3
3 ✔
1686
            # Long form: (:method name_or_mt sigtype code) → (call Core.define_method module name_or_mt sigtype code)
1687
            name_or_mt = e.args[1]
3 ✔
1688
            sigtype = e.args[2]
3 ✔
1689
            code = e.args[3]
3 ✔
1690
            if name_or_mt isa Symbol
3 ✔
1691
                name_or_mt = QuoteNode(name_or_mt)
3 ✔
1692
                e = Expr(:call, GlobalRef(Core, :define_method), mod, name_or_mt, sigtype, code)
3 ✔
1693
            elseif name_or_mt isa GlobalRef
3 ✔
1694
                mod_ref = name_or_mt.mod
3 ✔
1695
                sym = name_or_mt.name
3 ✔
1696
                e = Expr(:call, GlobalRef(Core, :define_method), mod_ref, QuoteNode(sym), sigtype, code)
3 ✔
1697
            else
1698
                # name_or_mt is already something else (like false or a method table)
1699
                e = Expr(:call, GlobalRef(Core, :define_method), mod, name_or_mt, sigtype, code)
3 ✔
1700
            end
1701
        end
1702
    end
1703
    e
316 ✔
1704
end
1705

1706
module __deserialized_types__ end
1707

1708
function deserialize(s::AbstractSerializer, ::Type{Core.TypeName})
3 ✔
1709
    number = _read(s.io, UInt64)
3 ✔
1710
    return deserialize_typename(s, number)
3 ✔
1711
end
1712

1713
function deserialize_typename(s::AbstractSerializer, number)
126 ✔
1714
    name = deserialize(s)::Symbol
126 ✔
1715
    tn = lookup_object_number(s, number)
126 ✔
1716
    if tn !== nothing
126 ✔
1717
        makenew = false
6 ✔
1718
    else
1719
        # reuse the same name for the type, if possible, for nicer debugging
1720
        tn_name = isdefined(__deserialized_types__, name) ? gensym() : name
126 ✔
1721
        tn = ccall(:jl_new_typename_in, Any, (Any, Any, Cint, Cint),
126 ✔
1722
                   tn_name, __deserialized_types__, false, false)
1723
        makenew = true
126 ✔
1724
    end
1725
    tn = tn::Core.TypeName
126 ✔
1726
    remember_object(s, tn, number)
126 ✔
1727
    deserialize_cycle(s, tn)
126 ✔
1728

1729
    names = deserialize(s)::SimpleVector
126 ✔
1730
    super = deserialize(s)::Type
126 ✔
1731
    parameters = deserialize(s)::SimpleVector
126 ✔
1732
    types = deserialize(s)::SimpleVector
126 ✔
1733
    attrs = Core.svec()
126 ✔
1734
    has_instance = deserialize(s)::Bool
126 ✔
1735
    abstr = deserialize(s)::Bool
126 ✔
1736
    mutabl = deserialize(s)::Bool
126 ✔
1737
    ninitialized = deserialize(s)::Int32
126 ✔
1738
    maxm = format_version(s) >= 18 ? deserialize(s)::UInt8 : UInt8(0)
126 ✔
1739

1740
    if makenew
126 ✔
1741
        # TODO: there's an unhanded cycle in the dependency graph at this point:
1742
        # while deserializing super and/or types, we may have encountered
1743
        # tn.wrapper and throw UndefRefException before we get to this point
1744
        ndt = ccall(:jl_new_datatype, Any, (Any, Any, Any, Any, Any, Any, Any, Cint, Cint, Cint),
126 ✔
1745
                    tn, tn.module, super, parameters, names, types, attrs,
1746
                    abstr, mutabl, ninitialized)
1747
        @assert tn == ndt.name
126 ✔
1748
        ccall(:jl_set_const, Cvoid, (Any, Any, Any), tn.module, tn.name, tn.wrapper)
126 ✔
1749
        ty = tn.wrapper
126 ✔
1750
        tn.max_methods = maxm
126 ✔
1751
        if has_instance
126 ✔
1752
            ty = ty::DataType
117 ✔
1753
            if !isdefined(ty, :instance)
117 ✔
UNCOV
1754
                singleton = ccall(:jl_new_struct, Any, (Any, Any...), ty)
×
1755
                # use setfield! directly to avoid `fieldtype` lowering expecting to see a Singleton object already on ty
UNCOV
1756
                ccall(:jl_set_nth_field, Cvoid, (Any, Csize_t, Any), ty, Base.fieldindex(DataType, :instance)-1, singleton)
×
1757
            end
1758
        end
1759
    end
1760

1761
    tag = Int32(_read(s.io, UInt8))
126 ✔
1762
    if tag != UNDEFREF_TAG
126 ✔
1763
        mtname = handle_deserialize(s, tag)
126 ✔
1764
        _defs = deserialize(s)
126 ✔
1765
        maxa = deserialize(s)::Union{Int,Int32}
126 ✔
1766
        if makenew
126 ✔
1767
            tn.singletonname = mtname
126 ✔
1768
            setfield!(tn, :max_args, Int32(maxa), :monotonic)
126 ✔
1769
        end
1770
        tag = Int32(_read(s.io, UInt8))
126 ✔
1771
        if tag != UNDEFREF_TAG
126 ✔
1772
            kws = handle_deserialize(s, tag)
3 ✔
1773
            if makenew && !(kws isa Vector{Method})
3 ✔
1774
                # old object format -- try to forward from old to new
UNCOV
1775
                @eval Core.kwcall(kwargs::NamedTuple, f::$ty, args...) = $kws(kwargs, f, args...)
×
1776
            end
1777
        end
1778
    end
1779
    return tn
126 ✔
1780
end
1781

1782
function deserialize_datatype(s::AbstractSerializer, full::Bool)
488 ✔
1783
    slot = s.counter; s.counter += 1
488 ✔
1784
    if full
488 ✔
1785
        tname = deserialize(s)::Core.TypeName
35 ✔
1786
        ty = tname.wrapper
35 ✔
1787
    else
1788
        name = deserialize(s)::Symbol
488 ✔
1789
        mod = deserialize(s)::Module
488 ✔
1790
        ty = getglobal(mod, name)
488 ✔
1791
    end
1792
    if isa(ty,DataType) && isempty(ty.parameters)
488 ✔
1793
        t = ty
488 ✔
1794
    else
1795
        np = Int(_read(s.io, Int32))
488 ✔
1796
        if np == 0
488 ✔
1797
            t = unwrap_unionall(ty)
3 ✔
1798
        elseif ty === Tuple
488 ✔
1799
            # note np==0 has its own tag
1800
            if np == 1
287 ✔
1801
                t = Tuple{deserialize(s)}
232 ✔
1802
            elseif np == 2
103 ✔
1803
                t = Tuple{deserialize(s), deserialize(s)}
85 ✔
1804
            elseif np == 3
69 ✔
1805
                t = Tuple{deserialize(s), deserialize(s), deserialize(s)}
27 ✔
1806
            elseif np == 4
69 ✔
1807
                t = Tuple{deserialize(s), deserialize(s), deserialize(s), deserialize(s)}
63 ✔
1808
            else
1809
                t = Tuple{Any[ deserialize(s) for _=1:np ]...}
27 ✔
1810
            end
1811
        else
1812
            t = ty
488 ✔
1813
            for _ = 1:np
488 ✔
1814
                t = t{deserialize(s)}
488 ✔
1815
            end
488 ✔
1816
        end
1817
    end
1818
    _setbackref!(s, slot, t)
488 ✔
1819
    return t
488 ✔
1820
end
1821

1822
function deserialize(s::AbstractSerializer, ::Type{UnionAll})
38 ✔
1823
    form = _read(s.io, UInt8)
38 ✔
1824
    if form == 0
38 ✔
1825
        var = deserialize(s)
3 ✔
1826
        body = deserialize(s)
3 ✔
1827
        return UnionAll(var, body)
3 ✔
1828
    else
1829
        n = _read(s.io, Int16)
38 ✔
1830
        t = deserialize(s)::DataType
38 ✔
1831
        w = t.name.wrapper
38 ✔
1832
        k = 0
38 ✔
1833
        while isa(w, UnionAll)
38 ✔
1834
            w = w.body
38 ✔
1835
            k += 1
38 ✔
1836
        end
38 ✔
1837
        w = t.name.wrapper
38 ✔
1838
        k -= n
38 ✔
1839
        while k > 0
38 ✔
1840
            w = w.body
3 ✔
1841
            k -= 1
3 ✔
1842
        end
3 ✔
1843
        return w
38 ✔
1844
    end
1845
end
1846

1847
function deserialize(s::AbstractSerializer, ::Type{Task})
6 ✔
1848
    # The task code is replaced below, so prevent attaching invoke metadata for the dummy closure.
1849
    t = Task(Base.inferencebarrier(()->nothing))
6 ✔
1850
    deserialize_cycle(s, t)
6 ✔
1851
    t.code = deserialize(s)
6 ✔
1852
    t.storage = deserialize(s)
6 ✔
1853
    state = deserialize(s)
6 ✔
1854
    if state === :runnable
6 ✔
1855
        @atomic :release t._state = Base.task_state_runnable
3 ✔
1856
    elseif state === :done
6 ✔
1857
        @atomic :release t._state = Base.task_state_done
3 ✔
1858
    elseif state === :failed
6 ✔
1859
        @atomic :release t._state = Base.task_state_failed
6 ✔
1860
    else
UNCOV
1861
        @assert false
×
1862
    end
1863
    setfield!(t, :result, deserialize(s))
6 ✔
1864
    exc = deserialize(s)
6 ✔
1865
    if exc === nothing
6 ✔
UNCOV
1866
        t._isexception = false
×
1867
    elseif exc isa Bool
6 ✔
1868
        t._isexception = exc
6 ✔
1869
    else
UNCOV
1870
        t._isexception = true
×
UNCOV
1871
        setfield!(t, :result, exc)
×
1872
    end
1873
    if format_version(s) >= 31 && (deserialize(s)::Bool)
6 ✔
1874
        setfield!(t, :invoked, deserialize(s))
3 ✔
1875
    end
1876
    t
6 ✔
1877
end
1878

1879
function deserialize_string(s::AbstractSerializer, len::Int)
497 ✔
1880
    out = ccall(:jl_alloc_string, Ref{String}, (Csize_t,), len)
497 ✔
1881
    unsafe_read(s.io, pointer(out), len)
497 ✔
1882
    return out
497 ✔
1883
end
1884

1885
# default DataType deserializer
1886
function deserialize(s::AbstractSerializer, t::DataType)
498 ✔
1887
    nf = fieldcount(t)
498 ✔
1888
    if isprimitivetype(t)
498 ✔
1889
        return read(s.io, t)
17 ✔
1890
    elseif ismutabletype(t)
498 ✔
1891
        x = ccall(:jl_new_struct_uninit, Any, (Any,), t)
153 ✔
1892
        deserialize_cycle(s, x)
153 ✔
1893
        for i in 1:nf
153 ✔
1894
            tag = Int32(_read(s.io, UInt8))
153 ✔
1895
            if tag != UNDEFREF_TAG
153 ✔
1896
                ccall(:jl_set_nth_field, Cvoid, (Any, Csize_t, Any), x, i-1, handle_deserialize(s, tag))
153 ✔
1897
            end
1898
        end
153 ✔
1899
        return x
153 ✔
1900
    elseif nf == 0
498 ✔
1901
        return ccall(:jl_new_struct_uninit, Any, (Any,), t)
396 ✔
1902
    else
1903
        na = nf
498 ✔
1904
        vflds = Vector{Any}(undef, nf)
498 ✔
1905
        for i in 1:nf
498 ✔
1906
            tag = Int32(_read(s.io, UInt8))
498 ✔
1907
            if tag != UNDEFREF_TAG
498 ✔
1908
                f = handle_deserialize(s, tag)
498 ✔
1909
                na >= i && (vflds[i] = f)
498 ✔
1910
            else
1911
                na >= i && (na = i - 1) # rest of tail must be undefined values
15 ✔
1912
            end
1913
        end
498 ✔
1914
        return ccall(:jl_new_structv, Any, (Any, Ptr{Any}, UInt32), t, vflds, na)
498 ✔
1915
    end
1916
end
1917

1918
function deserialize_dict(s::AbstractSerializer, T::Type{<:AbstractDict})
13 ✔
1919
    n = _read(s.io, Int32)
13 ✔
1920
    t = T(); sizehint!(t, n)
13 ✔
1921
    deserialize_cycle(s, t)
13 ✔
1922
    for _ = 1:n
13 ✔
1923
        k = deserialize(s)
13 ✔
1924
        v = deserialize(s)
13 ✔
1925
        t[k] = v
13 ✔
1926
    end
13 ✔
1927
    return t
13 ✔
1928
end
1929

1930
function deserialize(s::AbstractSerializer, T::Type{Dict{K,V}}) where {K,V}
13 ✔
1931
    return deserialize_dict(s, T)
13 ✔
1932
end
1933

1934
deserialize(s::AbstractSerializer, ::Type{BigInt}) = parse(BigInt, deserialize(s), base = 62)
3 ✔
1935

1936
function deserialize(s::AbstractSerializer, ::Type{Regex})
3 ✔
1937
    pattern = deserialize(s)
3 ✔
1938
    compile_options = deserialize(s)
3 ✔
1939
    match_options = deserialize(s)
3 ✔
1940
    return Regex(pattern, compile_options, match_options)
3 ✔
1941
end
1942

1943
## StackTraces
1944

1945
# provide a custom serializer that skips attempting to serialize the `outer_linfo`
1946
# which is likely to contain complex references, types, and module references
1947
# that may not exist on the receiver end
1948
function serialize(s::AbstractSerializer, frame::Base.StackTraces.StackFrame)
50 ✔
1949
    serialize_type(s, typeof(frame))
50 ✔
1950
    serialize(s, frame.func)
50 ✔
1951
    serialize(s, frame.file)
50 ✔
1952
    write(s.io, frame.line)
50 ✔
1953
    write(s.io, frame.from_c)
50 ✔
1954
    write(s.io, frame.inlined)
50 ✔
1955
    write(s.io, frame.pointer)
50 ✔
1956
    nothing
50 ✔
1957
end
1958

1959
function deserialize(s::AbstractSerializer, ::Type{Base.StackTraces.StackFrame})
14 ✔
1960
    func = deserialize(s)
14 ✔
1961
    file = deserialize(s)
14 ✔
1962
    line = _read(s.io, Int)
14 ✔
1963
    from_c = _read(s.io, Bool)
14 ✔
1964
    inlined = _read(s.io, Bool)
14 ✔
1965
    pointer = _read(s.io, UInt64)
14 ✔
1966
    return Base.StackTraces.StackFrame(func, file, line, nothing, from_c, inlined, pointer)
14 ✔
1967
end
1968

1969
function serialize(s::AbstractSerializer, lock::Base.AbstractLock)
15 ✔
1970
    # assert_havelock(lock)
1971
    serialize_cycle_header(s, lock)
15 ✔
1972
    nothing
15 ✔
1973
end
1974

1975
function deserialize(s::AbstractSerializer, ::Type{T}) where T<:Base.AbstractLock
34 ✔
1976
    lock = T()
34 ✔
1977
    deserialize_cycle(s, lock)
34 ✔
1978
    return lock
34 ✔
1979
end
1980

1981
function serialize(s::AbstractSerializer, cond::Base.GenericCondition)
3 ✔
1982
    serialize_cycle_header(s, cond) && return
3 ✔
1983
    serialize(s, cond.lock)
3 ✔
1984
    nothing
3 ✔
1985
end
1986

1987
function deserialize(s::AbstractSerializer, ::Type{T}) where T<:Base.GenericCondition
3 ✔
1988
    lock = deserialize(s)
3 ✔
1989
    cond = T(lock)
3 ✔
1990
    deserialize_cycle(s, cond)
3 ✔
1991
    return cond
3 ✔
1992
end
1993

1994
serialize(s::AbstractSerializer, l::LazyString) =
6 ✔
1995
    invoke(serialize, Tuple{AbstractSerializer,Any}, s, Base._LazyString((), string(l)))
6 ✔
1996

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

© 2026 Coveralls, Inc