-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
Serialization.jl
1508 lines (1388 loc) · 46.4 KB
/
Serialization.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This file is a part of Julia. License is MIT: https://julialang.org/license
"""
Provide serialization of Julia objects via the functions
* [`serialize`](@ref)
* [`deserialize`](@ref)
"""
module Serialization
import Base: GMP, Bottom, unsafe_convert, uncompressed_ast
import Core: svec, SimpleVector
using Base: unaliascopy, unwrap_unionall, require_one_based_indexing, ntupleany
using Core.IR
export serialize, deserialize, AbstractSerializer, Serializer
abstract type AbstractSerializer end
mutable struct Serializer{I<:IO} <: AbstractSerializer
io::I
counter::Int
table::IdDict{Any,Any}
pending_refs::Vector{Int}
known_object_data::Dict{UInt64,Any}
version::Int
Serializer{I}(io::I) where I<:IO = new(io, 0, IdDict(), Int[], Dict{UInt64,Any}(), ser_version)
end
Serializer(io::IO) = Serializer{typeof(io)}(io)
## serializing values ##
const n_int_literals = 33
const n_reserved_slots = 24
const n_reserved_tags = 8
const TAGS = Any[
Symbol, Int8, UInt8, Int16, UInt16, Int32, UInt32, Int64, UInt64, Int128, UInt128,
Float16, Float32, Float64, Char, DataType, Union, UnionAll, Core.TypeName, Tuple,
Array, Expr, LineNumberNode, :__LabelNode__, GotoNode, QuoteNode, CodeInfo, TypeVar,
Core.Box, Core.MethodInstance, Module, Task, String, SimpleVector, Method,
GlobalRef, SlotNumber, TypedSlot, NewvarNode, SSAValue,
# dummy entries for tags that don't correspond directly to types
Symbol, # UNDEFREF_TAG
Symbol, # BACKREF_TAG
Symbol, # LONGBACKREF_TAG
Symbol, # SHORTBACKREF_TAG
Symbol, # LONGTUPLE_TAG
Symbol, # LONGSYMBOL_TAG
Symbol, # LONGEXPR_TAG
Symbol, # LONGSTRING_TAG
Symbol, # SHORTINT64_TAG
Symbol, # FULL_DATATYPE_TAG
Symbol, # WRAPPER_DATATYPE_TAG
Symbol, # OBJECT_TAG
Symbol, # REF_OBJECT_TAG
Symbol, # FULL_GLOBALREF_TAG
Symbol, # HEADER_TAG
Symbol, # IDDICT_TAG
Symbol, # SHARED_REF_TAG
ReturnNode, GotoIfNot,
fill(Symbol, n_reserved_tags)...,
(), Bool, Any, Bottom, Core.TypeofBottom, Type, svec(), Tuple{}, false, true, nothing,
:Any, :Array, :TypeVar, :Box, :Tuple, :Ptr, :return, :call, Symbol("::"), :Function,
:(=), :(==), :(===), :gotoifnot, :A, :B, :C, :M, :N, :T, :S, :X, :Y, :a, :b, :c, :d, :e, :f,
:g, :h, :i, :j, :k, :l, :m, :n, :o, :p, :q, :r, :s, :t, :u, :v, :w, :x, :y, :z, :add_int,
:sub_int, :mul_int, :add_float, :sub_float, :new, :mul_float, :bitcast, :start, :done, :next,
:indexed_iterate, :getfield, :meta, :eq_int, :slt_int, :sle_int, :ne_int, :push_loc, :pop_loc,
:pop, :arrayset, :arrayref, :apply_type, :inbounds, :getindex, :setindex!, :Core, :!, :+,
:Base, :static_parameter, :convert, :colon, Symbol("#self#"), Symbol("#temp#"), :tuple, Symbol(""),
fill(:_reserved_, n_reserved_slots)...,
(Int32(0):Int32(n_int_literals-1))...,
(Int64(0):Int64(n_int_literals-1))...
]
@assert length(TAGS) == 255
const ser_version = 15 # do not make changes without bumping the version #!
format_version(::AbstractSerializer) = ser_version
format_version(s::Serializer) = s.version
const NTAGS = length(TAGS)
function sertag(@nospecialize(v))
# NOTE: we use jl_value_ptr directly since we know at least one of the arguments
# in the comparison below is a singleton.
ptr = ccall(:jl_value_ptr, Ptr{Cvoid}, (Any,), v)
ptags = convert(Ptr{Ptr{Cvoid}}, pointer(TAGS))
# note: constant ints & reserved slots never returned here
@inbounds for i in 1:(NTAGS-(n_reserved_slots+2*n_int_literals))
ptr == unsafe_load(ptags,i) && return i%Int32
end
return Int32(-1)
end
desertag(i::Int32) = @inbounds(TAGS[i])
# tags >= this just represent themselves, their whole representation is 1 byte
const VALUE_TAGS = sertag(())
const ZERO32_TAG = Int32(NTAGS-(2*n_int_literals-1))
const ZERO64_TAG = Int64(NTAGS-(n_int_literals-1))
const TRUE_TAG = sertag(true)
const FALSE_TAG = sertag(false)
const EMPTYTUPLE_TAG = sertag(())
const TUPLE_TAG = sertag(Tuple)
const SIMPLEVECTOR_TAG = sertag(SimpleVector)
const SYMBOL_TAG = sertag(Symbol)
const INT8_TAG = sertag(Int8)
const ARRAY_TAG = findfirst(==(Array), TAGS)%Int32
const EXPR_TAG = sertag(Expr)
const MODULE_TAG = sertag(Module)
const METHODINSTANCE_TAG = sertag(Core.MethodInstance)
const METHOD_TAG = sertag(Method)
const TASK_TAG = sertag(Task)
const DATATYPE_TAG = sertag(DataType)
const TYPENAME_TAG = sertag(Core.TypeName)
const INT32_TAG = sertag(Int32)
const INT64_TAG = sertag(Int64)
const GLOBALREF_TAG = sertag(GlobalRef)
const BOTTOM_TAG = sertag(Bottom)
const UNIONALL_TAG = sertag(UnionAll)
const STRING_TAG = sertag(String)
const o0 = sertag(SSAValue)
const UNDEFREF_TAG = Int32(o0+1)
const BACKREF_TAG = Int32(o0+2)
const LONGBACKREF_TAG = Int32(o0+3)
const SHORTBACKREF_TAG = Int32(o0+4)
const LONGTUPLE_TAG = Int32(o0+5)
const LONGSYMBOL_TAG = Int32(o0+6)
const LONGEXPR_TAG = Int32(o0+7)
const LONGSTRING_TAG = Int32(o0+8)
const SHORTINT64_TAG = Int32(o0+9)
const FULL_DATATYPE_TAG = Int32(o0+10)
const WRAPPER_DATATYPE_TAG = Int32(o0+11)
const OBJECT_TAG = Int32(o0+12)
const REF_OBJECT_TAG = Int32(o0+13)
const FULL_GLOBALREF_TAG = Int32(o0+14)
const HEADER_TAG = Int32(o0+15)
const IDDICT_TAG = Int32(o0+16)
const SHARED_REF_TAG = Int32(o0+17)
writetag(s::IO, tag) = (write(s, UInt8(tag)); nothing)
function write_as_tag(s::IO, tag)
tag < VALUE_TAGS && write(s, UInt8(0))
write(s, UInt8(tag))
nothing
end
# cycle handling
function serialize_cycle(s::AbstractSerializer, @nospecialize(x))
offs = get(s.table, x, -1)::Int
if offs != -1
if offs <= typemax(UInt16)
writetag(s.io, SHORTBACKREF_TAG)
write(s.io, UInt16(offs))
elseif offs <= typemax(Int32)
writetag(s.io, BACKREF_TAG)
write(s.io, Int32(offs))
else
writetag(s.io, LONGBACKREF_TAG)
write(s.io, Int64(offs))
end
return true
end
s.table[x] = s.counter
s.counter += 1
return false
end
function serialize_cycle_header(s::AbstractSerializer, @nospecialize(x))
serialize_cycle(s, x) && return true
serialize_type(s, typeof(x), true)
return false
end
function reset_state(s::AbstractSerializer)
s.counter = 0
empty!(s.table)
empty!(s.pending_refs)
s
end
serialize(s::AbstractSerializer, x::Bool) = x ? writetag(s.io, TRUE_TAG) :
writetag(s.io, FALSE_TAG)
serialize(s::AbstractSerializer, p::Ptr) = serialize_any(s, oftype(p, C_NULL))
serialize(s::AbstractSerializer, ::Tuple{}) = writetag(s.io, EMPTYTUPLE_TAG)
function serialize(s::AbstractSerializer, t::Tuple)
l = length(t)
if l <= 255
writetag(s.io, TUPLE_TAG)
write(s.io, UInt8(l))
else
writetag(s.io, LONGTUPLE_TAG)
write(s.io, Int32(l))
end
for x in t
serialize(s, x)
end
end
function serialize(s::AbstractSerializer, v::SimpleVector)
writetag(s.io, SIMPLEVECTOR_TAG)
write(s.io, Int32(length(v)))
for x in v
serialize(s, x)
end
end
function serialize(s::AbstractSerializer, x::Symbol)
tag = sertag(x)
if tag > 0
return write_as_tag(s.io, tag)
end
pname = unsafe_convert(Ptr{UInt8}, x)
len = Int(ccall(:strlen, Csize_t, (Cstring,), pname))
if len > 7
serialize_cycle(s, x) && return
end
if len <= 255
writetag(s.io, SYMBOL_TAG)
write(s.io, UInt8(len))
else
writetag(s.io, LONGSYMBOL_TAG)
write(s.io, Int32(len))
end
unsafe_write(s.io, pname, len)
nothing
end
function serialize_array_data(s::IO, a)
require_one_based_indexing(a)
isempty(a) && return 0
if eltype(a) === Bool
last = a[1]::Bool
count = 1
for i = 2:length(a)
if a[i]::Bool != last || count == 127
write(s, UInt8((UInt8(last) << 7) | count))
last = a[i]::Bool
count = 1
else
count += 1
end
end
write(s, UInt8((UInt8(last) << 7) | count))
else
write(s, a)
end
end
function serialize(s::AbstractSerializer, a::Array)
serialize_cycle(s, a) && return
elty = eltype(a)
writetag(s.io, ARRAY_TAG)
if elty !== UInt8
serialize(s, elty)
end
if ndims(a) != 1
serialize(s, size(a))
else
serialize(s, length(a))
end
if isbitstype(elty)
serialize_array_data(s.io, a)
else
sizehint!(s.table, div(length(a),4)) # prepare for lots of pointers
@inbounds for i in eachindex(a)
if isassigned(a, i)
serialize(s, a[i])
else
writetag(s.io, UNDEFREF_TAG)
end
end
end
end
function serialize(s::AbstractSerializer, a::SubArray{T,N,A}) where {T,N,A<:Array}
# SubArray's copy only selects the relevant data (and reduces the size) but does not
# preserve the type of the argument. This internal function does both:
b = unaliascopy(a)
serialize_any(s, b)
end
function serialize(s::AbstractSerializer, ss::String)
len = sizeof(ss)
if len > 7
serialize_cycle(s, ss) && return
writetag(s.io, SHARED_REF_TAG)
end
if len <= 255
writetag(s.io, STRING_TAG)
write(s.io, UInt8(len))
else
writetag(s.io, LONGSTRING_TAG)
write(s.io, Int64(len))
end
write(s.io, ss)
nothing
end
function serialize(s::AbstractSerializer, ss::SubString{String})
# avoid saving a copy of the parent string, keeping the type of ss
serialize_any(s, SubString(String(ss)))
end
# Don't serialize the pointers
function serialize(s::AbstractSerializer, r::Regex)
serialize_type(s, typeof(r))
serialize(s, r.pattern)
serialize(s, r.compile_options)
serialize(s, r.match_options)
end
function serialize(s::AbstractSerializer, n::BigInt)
serialize_type(s, BigInt)
serialize(s, string(n, base = 62))
end
function serialize(s::AbstractSerializer, ex::Expr)
serialize_cycle(s, ex) && return
l = length(ex.args)
if l <= 255
writetag(s.io, EXPR_TAG)
write(s.io, UInt8(l))
else
writetag(s.io, LONGEXPR_TAG)
write(s.io, Int32(l))
end
serialize(s, ex.head)
for a in ex.args
serialize(s, a)
end
end
function serialize_dict_data(s::AbstractSerializer, d::AbstractDict)
write(s.io, Int32(length(d)))
for (k,v) in d
serialize(s, k)
serialize(s, v)
end
end
function serialize(s::AbstractSerializer, d::Dict)
serialize_cycle_header(s, d) && return
serialize_dict_data(s, d)
end
function serialize(s::AbstractSerializer, d::IdDict)
serialize_cycle(s, d) && return
writetag(s.io, IDDICT_TAG)
serialize_type_data(s, typeof(d))
serialize_dict_data(s, d)
end
function serialize_mod_names(s::AbstractSerializer, m::Module)
p = parentmodule(m)
if p === m || m === Base
key = Base.root_module_key(m)
serialize(s, key.uuid === nothing ? nothing : key.uuid.value)
serialize(s, Symbol(key.name))
else
serialize_mod_names(s, p)
serialize(s, nameof(m))
end
end
function serialize(s::AbstractSerializer, m::Module)
writetag(s.io, MODULE_TAG)
serialize_mod_names(s, m)
writetag(s.io, EMPTYTUPLE_TAG)
end
# TODO: make this bidirectional, so objects can be sent back via the same key
const object_numbers = WeakKeyDict()
const obj_number_salt = Ref{UInt64}(0)
function object_number(s::AbstractSerializer, @nospecialize(l))
global obj_number_salt, object_numbers
if haskey(object_numbers, l)
return object_numbers[l]
end
ln = obj_number_salt[]
object_numbers[l] = ln
obj_number_salt[] += 1
return ln::UInt64
end
lookup_object_number(s::AbstractSerializer, n::UInt64) = nothing
remember_object(s::AbstractSerializer, @nospecialize(o), n::UInt64) = nothing
function lookup_object_number(s::Serializer, n::UInt64)
return get(s.known_object_data, n, nothing)
end
function remember_object(s::Serializer, @nospecialize(o), n::UInt64)
s.known_object_data[n] = o
return nothing
end
function serialize(s::AbstractSerializer, meth::Method)
serialize_cycle(s, meth) && return
writetag(s.io, METHOD_TAG)
write(s.io, object_number(s, meth))
serialize(s, meth.module)
serialize(s, meth.name)
serialize(s, meth.file)
serialize(s, meth.line)
serialize(s, meth.sig)
serialize(s, meth.slot_syms)
serialize(s, meth.nargs)
serialize(s, meth.isva)
serialize(s, meth.is_for_opaque_closure)
serialize(s, meth.aggressive_constprop)
if isdefined(meth, :source)
serialize(s, Base._uncompressed_ast(meth, meth.source))
else
serialize(s, nothing)
end
if isdefined(meth, :generator)
serialize(s, meth.generator)
else
serialize(s, nothing)
end
if isdefined(meth, :recursion_relation)
serialize(s, method.recursion_relation)
else
serialize(s, nothing)
end
if isdefined(meth, :external_mt)
error("cannot serialize Method objects with external method tables")
end
nothing
end
function serialize(s::AbstractSerializer, linfo::Core.MethodInstance)
serialize_cycle(s, linfo) && return
writetag(s.io, METHODINSTANCE_TAG)
if isdefined(linfo, :uninferred)
serialize(s, linfo.uninferred)
else
writetag(s.io, UNDEFREF_TAG)
end
serialize(s, nothing) # for backwards compat
serialize(s, linfo.sparam_vals)
serialize(s, Any) # for backwards compat
serialize(s, linfo.specTypes)
serialize(s, linfo.def)
nothing
end
function serialize(s::AbstractSerializer, t::Task)
serialize_cycle(s, t) && return
if istaskstarted(t) && !istaskdone(t)
error("cannot serialize a running Task")
end
writetag(s.io, TASK_TAG)
serialize(s, t.code)
serialize(s, t.storage)
serialize(s, t.state)
if t._isexception && (stk = Base.current_exceptions(t); !isempty(stk))
# the exception stack field is hidden inside the task, so if there
# is any information there make a CapturedException from it instead.
# TODO: Handle full exception chain, not just the first one.
serialize(s, CapturedException(stk[1].exception, stk[1].backtrace))
else
serialize(s, t.result)
end
serialize(s, t._isexception)
end
function serialize(s::AbstractSerializer, g::GlobalRef)
if (g.mod === __deserialized_types__ ) ||
(g.mod === Main && isdefined(g.mod, g.name) && isconst(g.mod, g.name))
v = getfield(g.mod, g.name)
unw = unwrap_unionall(v)
if isa(unw,DataType) && v === unw.name.wrapper && should_send_whole_type(s, unw)
# handle references to types in Main by sending the whole type.
# needed to be able to send nested functions (#15451).
writetag(s.io, FULL_GLOBALREF_TAG)
serialize(s, v)
return
end
end
writetag(s.io, GLOBALREF_TAG)
serialize(s, g.mod)
serialize(s, g.name)
end
function serialize(s::AbstractSerializer, t::Core.TypeName)
serialize_cycle(s, t) && return
writetag(s.io, TYPENAME_TAG)
write(s.io, object_number(s, t))
serialize_typename(s, t)
end
function serialize_typename(s::AbstractSerializer, t::Core.TypeName)
serialize(s, t.name)
serialize(s, t.names)
primary = unwrap_unionall(t.wrapper)
serialize(s, primary.super)
serialize(s, primary.parameters)
serialize(s, primary.types)
serialize(s, isdefined(primary, :instance))
serialize(s, t.flags & 0x1 == 0x1) # .abstract
serialize(s, t.flags & 0x2 == 0x2) # .mutable
serialize(s, Int32(length(primary.types) - t.n_uninitialized))
if isdefined(t, :mt) && t.mt !== Symbol.name.mt
serialize(s, t.mt.name)
serialize(s, collect(Base.MethodList(t.mt)))
serialize(s, t.mt.max_args)
if isdefined(t.mt, :kwsorter)
serialize(s, t.mt.kwsorter)
else
writetag(s.io, UNDEFREF_TAG)
end
else
writetag(s.io, UNDEFREF_TAG)
end
nothing
end
# decide whether to send all data for a type (instead of just its name)
function should_send_whole_type(s, t::DataType)
tn = t.name
if isdefined(tn, :mt)
# TODO improve somehow
# send whole type for anonymous functions in Main
name = tn.mt.name
mod = tn.module
isanonfunction = mod === Main && # only Main
t.super === Function && # only Functions
unsafe_load(unsafe_convert(Ptr{UInt8}, tn.name)) == UInt8('#') && # hidden type
(!isdefined(mod, name) || t != typeof(getfield(mod, name))) # XXX: 95% accurate test for this being an inner function
# TODO: more accurate test? (tn.name !== "#" name)
#TODO: iskw = startswith(tn.name, "#kw#") && ???
#TODO: iskw && return send-as-kwftype
return mod === __deserialized_types__ || isanonfunction
end
return false
end
function serialize_type_data(s, @nospecialize(t::DataType))
whole = should_send_whole_type(s, t)
iswrapper = (t === unwrap_unionall(t.name.wrapper))
if whole && iswrapper
writetag(s.io, WRAPPER_DATATYPE_TAG)
serialize(s, t.name)
return
end
serialize_cycle(s, t) && return
if whole
writetag(s.io, FULL_DATATYPE_TAG)
serialize(s, t.name)
else
writetag(s.io, DATATYPE_TAG)
tname = t.name.name
serialize(s, tname)
mod = t.name.module
serialize(s, mod)
end
if !isempty(t.parameters)
if iswrapper
write(s.io, Int32(0))
else
write(s.io, Int32(length(t.parameters)))
for p in t.parameters
serialize(s, p)
end
end
end
nothing
end
function serialize(s::AbstractSerializer, t::DataType)
tag = sertag(t)
tag > 0 && return write_as_tag(s.io, tag)
if t === Tuple
# `sertag` is not able to find types === to `Tuple` because they
# will not have been hash-consed. Plus `serialize_type_data` does not
# handle this case correctly, since Tuple{} != Tuple. `Tuple` is the
# only type with this property. issue #15849
return write_as_tag(s.io, TUPLE_TAG)
end
serialize_type_data(s, t)
end
function serialize_type(s::AbstractSerializer, @nospecialize(t::DataType), ref::Bool = false)
tag = sertag(t)
tag > 0 && return writetag(s.io, tag)
writetag(s.io, ref ? REF_OBJECT_TAG : OBJECT_TAG)
serialize_type_data(s, t)
end
function serialize(s::AbstractSerializer, n::Int32)
if 0 <= n <= (n_int_literals-1)
write(s.io, UInt8(ZERO32_TAG+n))
else
writetag(s.io, INT32_TAG)
write(s.io, n)
end
nothing
end
function serialize(s::AbstractSerializer, n::Int64)
if 0 <= n <= (n_int_literals-1)
write(s.io, UInt8(ZERO64_TAG+n))
elseif typemin(Int32) <= n <= typemax(Int32)
writetag(s.io, SHORTINT64_TAG)
write(s.io, Int32(n))
else
writetag(s.io, INT64_TAG)
write(s.io, n)
end
nothing
end
for i in 0:13
tag = Int32(INT8_TAG + i)
ty = TAGS[tag]
(ty === Int32 || ty === Int64) && continue
@eval serialize(s::AbstractSerializer, n::$ty) = (writetag(s.io, $tag); write(s.io, n); nothing)
end
serialize(s::AbstractSerializer, ::Type{Bottom}) = write_as_tag(s.io, BOTTOM_TAG)
function serialize(s::AbstractSerializer, u::UnionAll)
writetag(s.io, UNIONALL_TAG)
n = 0; t = u
while isa(t, UnionAll)
t = t.body
n += 1
end
if isa(t, DataType) && t === unwrap_unionall(t.name.wrapper)
write(s.io, UInt8(1))
write(s.io, Int16(n))
serialize(s, t)
else
write(s.io, UInt8(0))
serialize(s, u.var)
serialize(s, u.body)
end
end
serialize(s::AbstractSerializer, @nospecialize(x)) = serialize_any(s, x)
function serialize_any(s::AbstractSerializer, @nospecialize(x))
tag = sertag(x)
if tag > 0
return write_as_tag(s.io, tag)
end
t = typeof(x)::DataType
nf = nfields(x)
if nf == 0 && t.size > 0
serialize_type(s, t)
write(s.io, x)
else
if ismutable(x)
serialize_cycle(s, x) && return
serialize_type(s, t, true)
else
serialize_type(s, t, false)
end
for i in 1:nf
if isdefined(x, i)
serialize(s, getfield(x, i))
else
writetag(s.io, UNDEFREF_TAG)
end
end
end
nothing
end
"""
Serialization.writeheader(s::AbstractSerializer)
Write an identifying header to the specified serializer. The header consists of
8 bytes as follows:
| Offset | Description |
|:-------|:------------------------------------------------|
| 0 | tag byte (0x37) |
| 1-2 | signature bytes "JL" |
| 3 | protocol version |
| 4 | bits 0-1: endianness: 0 = little, 1 = big |
| 4 | bits 2-3: platform: 0 = 32-bit, 1 = 64-bit |
| 5-7 | reserved |
"""
function writeheader(s::AbstractSerializer)
io = s.io
writetag(io, HEADER_TAG)
write(io, "JL") # magic bytes
write(io, UInt8(ser_version))
endianness = (ENDIAN_BOM == 0x04030201 ? 0 :
ENDIAN_BOM == 0x01020304 ? 1 :
error("unsupported endianness in serializer"))
machine = (sizeof(Int) == 4 ? 0 :
sizeof(Int) == 8 ? 1 :
error("unsupported word size in serializer"))
write(io, UInt8(endianness) | (UInt8(machine) << 2))
write(io, [0x00,0x00,0x00]) # 3 reserved bytes
nothing
end
function readheader(s::AbstractSerializer)
# Tag already read
io = s.io
m1 = read(io, UInt8)
m2 = read(io, UInt8)
if m1 != UInt8('J') || m2 != UInt8('L')
error("Unsupported serialization format (got header magic bytes $m1 $m2)")
end
version = read(io, UInt8)
flags = read(io, UInt8)
reserved1 = read(io, UInt8)
reserved2 = read(io, UInt8)
reserved3 = read(io, UInt8)
endianflag = flags & 0x3
wordflag = (flags >> 2) & 0x3
wordsize = wordflag == 0 ? 4 :
wordflag == 1 ? 8 :
error("Unknown word size flag in header")
endian_bom = endianflag == 0 ? 0x04030201 :
endianflag == 1 ? 0x01020304 :
error("Unknown endianness flag in header")
# Check protocol compatibility.
endian_bom == ENDIAN_BOM || error("Serialized byte order mismatch ($(repr(endian_bom)))")
# We don't check wordsize == sizeof(Int) here, as Int is encoded concretely
# as Int32 or Int64, which should be enough to correctly deserialize a range
# of data structures between Julia versions.
if version > ser_version
error("""Cannot read stream serialized with a newer version of Julia.
Got data version $version > current version $ser_version""")
end
s.version = version
return
end
"""
serialize(stream::IO, value)
Write an arbitrary value to a stream in an opaque format, such that it can be read back by
[`deserialize`](@ref). The read-back value will be as identical as possible to the original.
In general, this process will not work if the reading and writing are done by different
versions of Julia, or an instance of Julia with a different system image. `Ptr` values are
serialized as all-zero bit patterns (`NULL`).
An 8-byte identifying header is written to the stream first. To avoid writing the header,
construct a `Serializer` and use it as the first argument to `serialize` instead.
See also [`Serialization.writeheader`](@ref).
"""
function serialize(s::IO, x)
ss = Serializer(s)
writeheader(ss)
serialize(ss, x)
end
"""
serialize(filename::AbstractString, value)
Open a file and serialize the given value to it.
!!! compat "Julia 1.1"
This method is available as of Julia 1.1.
"""
serialize(filename::AbstractString, x) = open(io->serialize(io, x), filename, "w")
## deserializing values ##
"""
deserialize(stream)
Read a value written by [`serialize`](@ref). `deserialize` assumes the binary data read from
`stream` is correct and has been serialized by a compatible implementation of [`serialize`](@ref).
It has been designed with simplicity and performance as a goal and does not validate
the data read. Malformed data can result in process termination. The caller has to ensure
the integrity and correctness of data read from `stream`.
"""
deserialize(s::IO) = deserialize(Serializer(s))
"""
deserialize(filename::AbstractString)
Open a file and deserialize its contents.
!!! compat "Julia 1.1"
This method is available as of Julia 1.1.
"""
deserialize(filename::AbstractString) = open(deserialize, filename)
function deserialize(s::AbstractSerializer)
handle_deserialize(s, Int32(read(s.io, UInt8)::UInt8))
end
function deserialize_cycle(s::AbstractSerializer, @nospecialize(x))
slot = pop!(s.pending_refs)
s.table[slot] = x
nothing
end
# optimized version of:
# slot = s.counter; s.counter += 1
# push!(s.pending_refs, slot)
# slot = pop!(s.pending_refs)
# s.table[slot] = x
function resolve_ref_immediately(s::AbstractSerializer, @nospecialize(x))
s.table[s.counter] = x
s.counter += 1
nothing
end
function gettable(s::AbstractSerializer, id::Int)
get(s.table, id) do
errmsg = """Inconsistent Serializer state when deserializing.
Attempt to access internal table with key $id failed.
This might occur if the Serializer contexts when serializing and deserializing are inconsistent.
In particular, if multiple serialize calls use the same Serializer object then
the corresponding deserialize calls should also use the same Serializer object.
"""
error(errmsg)
end
end
# deserialize_ is an internal function to dispatch on the tag
# describing the serialized representation. the number of
# representations is fixed, so deserialize_ does not get extended.
function handle_deserialize(s::AbstractSerializer, b::Int32)
if b == 0
return desertag(Int32(read(s.io, UInt8)::UInt8))
end
if b >= VALUE_TAGS
return desertag(b)
elseif b == TUPLE_TAG
return deserialize_tuple(s, Int(read(s.io, UInt8)::UInt8))
elseif b == SHORTBACKREF_TAG
id = read(s.io, UInt16)::UInt16
return gettable(s, Int(id))
elseif b == BACKREF_TAG
id = read(s.io, Int32)::Int32
return gettable(s, Int(id))
elseif b == ARRAY_TAG
return deserialize_array(s)
elseif b == DATATYPE_TAG
return deserialize_datatype(s, false)
elseif b == FULL_DATATYPE_TAG
return deserialize_datatype(s, true)
elseif b == WRAPPER_DATATYPE_TAG
tname = deserialize(s)::Core.TypeName
return unwrap_unionall(tname.wrapper)
elseif b == OBJECT_TAG
t = deserialize(s)
if t === Missing
return missing
end
return deserialize(s, t)
elseif b == REF_OBJECT_TAG
slot = s.counter; s.counter += 1
push!(s.pending_refs, slot)
t = deserialize(s)
return deserialize(s, t)
elseif b == SHARED_REF_TAG
slot = s.counter; s.counter += 1
obj = deserialize(s)
s.table[slot] = obj
return obj
elseif b == SYMBOL_TAG
return deserialize_symbol(s, Int(read(s.io, UInt8)::UInt8))
elseif b == SHORTINT64_TAG
return Int64(read(s.io, Int32)::Int32)
elseif b == EXPR_TAG
return deserialize_expr(s, Int(read(s.io, UInt8)::UInt8))
elseif b == MODULE_TAG
return deserialize_module(s)
elseif b == STRING_TAG
return deserialize_string(s, Int(read(s.io, UInt8)::UInt8))
elseif b == LONGSTRING_TAG
return deserialize_string(s, Int(read(s.io, Int64)::Int64))
elseif b == SIMPLEVECTOR_TAG
return deserialize_svec(s)
elseif b == GLOBALREF_TAG
return GlobalRef(deserialize(s)::Module, deserialize(s)::Symbol)
elseif b == FULL_GLOBALREF_TAG
ty = deserialize(s)
tn = unwrap_unionall(ty).name
return GlobalRef(tn.module, tn.name)
elseif b == LONGTUPLE_TAG
return deserialize_tuple(s, Int(read(s.io, Int32)::Int32))
elseif b == LONGEXPR_TAG
return deserialize_expr(s, Int(read(s.io, Int32)::Int32))
elseif b == LONGBACKREF_TAG
id = read(s.io, Int64)::Int64
return gettable(s, Int(id))
elseif b == LONGSYMBOL_TAG
return deserialize_symbol(s, Int(read(s.io, Int32)::Int32))
elseif b == HEADER_TAG
readheader(s)
return deserialize(s)
elseif b == INT8_TAG
return read(s.io, Int8)
elseif b == INT8_TAG+1
return read(s.io, UInt8)
elseif b == INT8_TAG+2
return read(s.io, Int16)
elseif b == INT8_TAG+3
return read(s.io, UInt16)
elseif b == INT32_TAG
return read(s.io, Int32)
elseif b == INT8_TAG+5
return read(s.io, UInt32)
elseif b == INT64_TAG
return read(s.io, Int64)
elseif b == INT8_TAG+7
return read(s.io, UInt64)
elseif b == INT8_TAG+8
return read(s.io, Int128)
elseif b == INT8_TAG+9
return read(s.io, UInt128)
elseif b == INT8_TAG+10
return read(s.io, Float16)
elseif b == INT8_TAG+11
return read(s.io, Float32)
elseif b == INT8_TAG+12
return read(s.io, Float64)
elseif b == INT8_TAG+13
return read(s.io, Char)
elseif b == IDDICT_TAG
slot = s.counter; s.counter += 1
push!(s.pending_refs, slot)
t = deserialize(s)
return deserialize_dict(s, t)
end
t = desertag(b)::DataType
if ismutabletype(t) && length(t.types) > 0 # manual specialization of fieldcount
slot = s.counter; s.counter += 1
push!(s.pending_refs, slot)
end
return deserialize(s, t)
end
function deserialize_symbol(s::AbstractSerializer, len::Int)
str = Base._string_n(len)
unsafe_read(s.io, pointer(str), len)
sym = Symbol(str)
if len > 7
resolve_ref_immediately(s, sym)
end
return sym
end
deserialize_tuple(s::AbstractSerializer, len) = ntupleany(i->deserialize(s), len)
function deserialize_svec(s::AbstractSerializer)
n = read(s.io, Int32)
svec(Any[ deserialize(s) for i=1:n ]...)
end
function deserialize_module(s::AbstractSerializer)
mkey = deserialize(s)
if isa(mkey, Tuple)
# old version, TODO: remove
if mkey === ()
return Main
end
m = Base.root_module(mkey[1])
for i = 2:length(mkey)
m = getfield(m, mkey[i])::Module
end
else
name = String(deserialize(s)::Symbol)
pkg = (mkey === nothing) ? Base.PkgId(name) : Base.PkgId(Base.UUID(mkey), name)
m = Base.root_module(pkg)
mname = deserialize(s)
while mname !== ()
m = getfield(m, mname)::Module
mname = deserialize(s)
end
end
return m
end
function deserialize(s::AbstractSerializer, ::Type{Method})
lnumber = read(s.io, UInt64)
meth = lookup_object_number(s, lnumber)
if meth !== nothing
meth = meth::Method
makenew = false
else
meth = ccall(:jl_new_method_uninit, Ref{Method}, (Any,), Main)
makenew = true
end