-
Notifications
You must be signed in to change notification settings - Fork 171
/
serialization.c
3223 lines (2812 loc) · 130 KB
/
serialization.c
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
#include <moar.h>
#include <sha1.h>
#ifndef MAX
#define MAX(x, y) ((y) > (x) ? (y) : (x))
#endif
/* Whether we deserialize lazily or not. */
#define MVM_SERIALIZATION_LAZY 1
/* Version of the serialization format that we are currently at and lowest
* version we support. */
#define CURRENT_VERSION 20
#define MIN_VERSION 16
/* Various sizes (in bytes). */
#define HEADER_SIZE (4 * 18)
#define DEP_TABLE_ENTRY_SIZE 8
#define STABLES_TABLE_ENTRY_SIZE 12
#define OBJECTS_TABLE_ENTRY_SIZE 8
#define CLOSURES_TABLE_ENTRY_SIZE 24
#define CONTEXTS_TABLE_ENTRY_SIZE 16
#define REPOS_TABLE_ENTRY_SIZE 16
/* Some guesses. */
#define DEFAULT_STABLE_DATA_SIZE 4096
#define STABLES_TABLE_ENTRIES_GUESS 16
#define OBJECT_SIZE_GUESS 8
#define CLOSURES_TABLE_ENTRIES_GUESS 16
#define CONTEXTS_TABLE_ENTRIES_GUESS 4
#define DEFAULT_CONTEXTS_DATA_SIZE 1024
#define DEFAULT_PARAM_INTERNS_DATA_SIZE 128
/* Possible reference types we can serialize. */
#define REFVAR_NULL 1
#define REFVAR_OBJECT 2
#define REFVAR_VM_NULL 3
#define REFVAR_VM_INT 4
#define REFVAR_VM_NUM 5
#define REFVAR_VM_STR 6
#define REFVAR_VM_ARR_VAR 7
#define REFVAR_VM_ARR_STR 8
#define REFVAR_VM_ARR_INT 9
#define REFVAR_VM_HASH_STR_VAR 10
#define REFVAR_STATIC_CODEREF 11
#define REFVAR_CLONED_CODEREF 12
#define REFVAR_SC_REF 13
/* For the packed format, for "small" values of si and idx */
#define OBJECTS_TABLE_ENTRY_SC_MASK 0x7FF
#define OBJECTS_TABLE_ENTRY_SC_IDX_MASK 0x000FFFFF
#define OBJECTS_TABLE_ENTRY_SC_MAX 0x7FE
#define OBJECTS_TABLE_ENTRY_SC_IDX_MAX 0x000FFFFF
#define OBJECTS_TABLE_ENTRY_SC_SHIFT 20
#define OBJECTS_TABLE_ENTRY_SC_OVERFLOW 0x7FF
#define OBJECTS_TABLE_ENTRY_IS_CONCRETE 0x80000000
/* In the main serialization data blobs we have 1 more bit to play with.
The format is either 32 bits, with a packed value.
or 32 bits with an overflow flag, 32 bits of ID, and 32 bits of index.
The packed ID could be in the range 0..4094, the packed index 0..1048575.
With these ranges, overflow isn't even needed for compiling the setting.
An alternative format would be 8 bits of ID (so 0..254) and then 32 bits of
index (0..65535), or 8 bits for an overflow flag, then 32 and 32.
For this format, it turns out that currently for the setting, 296046 entries
would pack into 3 bytes, and 59757 would overflow and need 9.
296046 * 3 + 59757 * 9 == 1425951
(296046 + 59757) * 4 == 1423212
Hence that format is not quite as space efficient. */
#define PACKED_SC_IDX_MASK 0x000FFFFF
#define PACKED_SC_MAX 0xFFE
#define PACKED_SC_IDX_MAX 0x000FFFFF
#define PACKED_SC_SHIFT 20
#define PACKED_SC_OVERFLOW 0xFFF
#define STRING_HEAP_LOC_MAX 0x7FFFFFFF
#define STRING_HEAP_LOC_PACKED_MAX 0x00007FFF
#define STRING_HEAP_LOC_PACKED_OVERFLOW 0x00008000
#define STRING_HEAP_LOC_PACKED_LOW_MASK 0x0000FFFF
#define STRING_HEAP_LOC_PACKED_SHIFT 16
#define STABLE_BOOLIFICATION_SPEC_MODE_MASK 0x0F
#define STABLE_HAS_CONTAINER_SPEC 0x10
#define STABLE_HAS_INVOCATION_SPEC 0x20
#define STABLE_HAS_HLL_OWNER 0x40
#define STABLE_HAS_HLL_ROLE 0x80
#define GROW_TABLE(table, alloc) \
table = (char *)MVM_recalloc( \
table, \
alloc, \
alloc * 2 \
); \
alloc *= 2;
/* Endian translation (file format is little endian, so on big endian we need
* to twiddle. */
#ifdef MVM_BIGENDIAN
static void switch_endian(char *bytes, size_t size)
{
size_t low = 0;
size_t high = size - 1;
while (high > low) {
char tmp = bytes[low];
bytes[low] = bytes[high];
bytes[high] = tmp;
low++;
high--;
}
}
#endif
/* Base64 encoding */
static char * base64_encode(const void *buf, size_t size)
{
static const char base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
char* str = (char*) MVM_malloc((size+3)*4/3 + 1);
char* p = str;
const unsigned char* q = (const unsigned char*) buf;
size_t i = 0;
while (i < size) {
int c = q[i++];
c *= 256;
if (i < size)
c += q[i];
i++;
c *= 256;
if (i < size)
c += q[i];
i++;
*p++ = base64[(c & 0x00fc0000) >> 18];
*p++ = base64[(c & 0x0003f000) >> 12];
if (i > size + 1)
*p++ = '=';
else
*p++ = base64[(c & 0x00000fc0) >> 6];
if (i > size)
*p++ = '=';
else
*p++ = base64[c & 0x0000003f];
}
*p = 0;
return str;
}
/* Base64 decoding */
static int POS(char c)
{
/* XXX TODO: investigate whether enumerating all 256 cases of
* this in a switch/case can help the compiler turn it into a
* jump table instead of a bunch of comparisons (if it doesn't
* already, of course!)... */
if (c>='A' && c<='Z') return c - 'A';
if (c>='a' && c<='z') return c - 'a' + 26;
if (c>='0' && c<='9') return c - '0' + 52;
if (c == '+') return 62;
if (c == '/') return 63;
if (c == '=') return -1;
return -2;
}
static void * base64_decode(const char *s, size_t *data_len)
{
const char *p;
unsigned char *q, *data;
/* XXX TODO: investigate whether putting these n[4] into 4
* separate locals helps the compiler optimize them better.. */
int n[4] = {-1, -1, -1, -1};
size_t len = strlen(s);
if (len % 4) {
*data_len = 0;
return NULL;
}
data = (unsigned char*) MVM_malloc(len/4*3);
q = (unsigned char*) data;
for (p = s; *p; ) {
n[0] = POS(*p++);
n[1] = POS(*p++);
n[2] = POS(*p++);
n[3] = POS(*p++);
/* XXX TODO: investigate jump table possibility here too,
* or at least collapse some of the branches... */
if (n[0] == -2
|| n[1] == -2
|| n[2] == -2
|| n[3] == -2
|| n[0] == -1
|| n[1] == -1
|| (n[2] == -1 && n[3] != -1)) {
MVM_free(data);
return NULL;
}
q[0] = (n[0] << 2) + (n[1] >> 4);
if (n[2] != -1)
q[1] = ((n[1] & 15) << 4) + (n[2] >> 2);
if (n[3] != -1)
q[2] = ((n[2] & 3) << 6) + n[3];
q += 3;
}
*data_len = q-data - (n[2]==-1) - (n[3]==-1);
return data;
}
/* ***************************************************************************
* Serialization (writing related)
* ***************************************************************************/
/* Writes an int32 into a buffer. */
static void write_int32(char *buffer, size_t offset, MVMint32 value) {
memcpy(buffer + offset, &value, 4);
#ifdef MVM_BIGENDIAN
switch_endian(buffer + offset, 4);
#endif
}
/* Writes a uint16 into a buffer. */
static void write_uint16(char *buffer, size_t offset, MVMuint16 value) {
memcpy(buffer + offset, &value, 2);
#if MVM_BIGENDIAN
switch_endian(buffer + offset, 2);
#endif
}
/* Writes an double into a buffer. */
static void write_double(char *buffer, size_t offset, double value) {
memcpy(buffer + offset, &value, 8);
#ifdef MVM_BIGENDIAN
switch_endian(buffer + offset, 8);
#endif
}
/* Adds an item to the MVMString heap if needed, and returns the index where
* it may be found. */
static MVMint32 add_string_to_heap(MVMThreadContext *tc, MVMSerializationWriter *writer, MVMString *s) {
if (s == NULL) {
/* We ensured that the first entry in the heap represents the null MVMString,
* so can just hand back 0 here. */
return 0;
}
else if (MVM_repr_exists_key(tc, writer->seen_strings, s)) {
return (MVMint32)MVM_repr_at_key_int(tc, writer->seen_strings, s);
}
else {
MVMint64 next_idx = MVM_repr_elems(tc, writer->root.string_heap);
MVM_repr_bind_pos_s(tc, writer->root.string_heap, next_idx, s);
MVM_repr_bind_key_int(tc, writer->seen_strings, s, next_idx);
return (MVMint32)next_idx;
}
}
/* Gets the ID of a serialization context. Returns 0 if it's the current
* one, or its dependency table offset (base-1) otherwise. Note that if
* it is not yet in the dependency table, it will be added. */
static MVMuint32 get_sc_id(MVMThreadContext *tc, MVMSerializationWriter *writer, MVMSerializationContext *sc) {
MVMint64 i, num_deps, offset;
/* Easy if it's in the current SC. */
if (writer->root.sc == sc)
return 0;
/* Otherwise, find it in our dependencies list. */
num_deps = writer->root.num_dependencies;
for (i = 0; i < num_deps; i++)
if (writer->root.dependent_scs[i] == sc)
return (MVMuint32)i + 1;
/* Otherwise, need to add it to our dependencies list. Ensure there's
* space in the dependencies table; grow if not. */
offset = num_deps * DEP_TABLE_ENTRY_SIZE;
if (offset + DEP_TABLE_ENTRY_SIZE > writer->dependencies_table_alloc) {
GROW_TABLE(writer->root.dependencies_table, writer->dependencies_table_alloc);
}
/* Add dependency. */
writer->root.dependent_scs = MVM_realloc(writer->root.dependent_scs, sizeof(MVMSerializationContext *) * (writer->root.num_dependencies + 1));
writer->root.dependent_scs[writer->root.num_dependencies] = sc;
write_int32(writer->root.dependencies_table, offset,
add_string_to_heap(tc, writer, MVM_sc_get_handle(tc, sc)));
write_int32(writer->root.dependencies_table, offset + 4,
add_string_to_heap(tc, writer, MVM_sc_get_description(tc, sc)));
writer->root.num_dependencies++;
return writer->root.num_dependencies; /* Deliberately index + 1. */
}
#define OBJ_IS_NULL(obj) ((obj) == NULL)
/* Takes an STable. If it's already in an SC, returns information on how
* to reference it. Otherwise, adds it to the current SC, effectively
* placing it onto the work list. */
static void get_stable_ref_info(MVMThreadContext *tc, MVMSerializationWriter *writer,
MVMSTable *st, MVMuint32 *sc, MVMuint32 *sc_idx) {
/* Add to this SC if needed. */
if (MVM_sc_get_stable_sc(tc, st) == NULL) {
MVM_sc_set_stable_sc(tc, st, writer->root.sc);
MVM_sc_push_stable(tc, writer->root.sc, st);
}
/* Work out SC reference. */
*sc = get_sc_id(tc, writer, MVM_sc_get_stable_sc(tc, st));
*sc_idx = (MVMuint32)MVM_sc_find_stable_idx(tc, MVM_sc_get_stable_sc(tc, st), st);
}
/* Expands current target storage as needed. */
static void expand_storage_if_needed(MVMThreadContext *tc, MVMSerializationWriter *writer, MVMint64 need) {
if (*(writer->cur_write_offset) + need > *(writer->cur_write_limit)) {
*(writer->cur_write_limit) *= 2;
*(writer->cur_write_buffer) = (char *)MVM_realloc(*(writer->cur_write_buffer),
*(writer->cur_write_limit));
}
}
/* Writing function for null-terminated char array strings */
void MVM_serialization_write_cstr(MVMThreadContext *tc, MVMSerializationWriter *writer, char *string) {
size_t len;
if (string)
len = strlen(string);
else
len = 0;
if (len) {
MVM_serialization_write_int(tc, writer, len);
expand_storage_if_needed(tc, writer, len);
memcpy(*(writer->cur_write_buffer) + *(writer->cur_write_offset), string, len);
*(writer->cur_write_offset) += len;
} else {
MVM_serialization_write_int(tc, writer, 0);
}
}
/* Writing function for variable sized integers. Writes out a 64 bit value
using between 1 and 9 bytes. */
void MVM_serialization_write_int(MVMThreadContext *tc, MVMSerializationWriter *writer, MVMint64 value) {
MVMuint8 storage_needed;
char *buffer;
size_t offset;
if (value >= -1 && value <= 126) {
storage_needed = 1;
} else {
const MVMint64 abs_val = value < 0 ? -value - 1 : value;
if (abs_val <= 0x7FF)
storage_needed = 2;
else if (abs_val <= 0x000000000007FFFF)
storage_needed = 3;
else if (abs_val <= 0x0000000007FFFFFF)
storage_needed = 4;
else if (abs_val <= 0x00000007FFFFFFFF)
storage_needed = 5;
else if (abs_val <= 0x000007FFFFFFFFFFLL)
storage_needed = 6;
else if (abs_val <= 0x0007FFFFFFFFFFFFLL)
storage_needed = 7;
else if (abs_val <= 0x07FFFFFFFFFFFFFFLL)
storage_needed = 8;
else
storage_needed = 9;
}
expand_storage_if_needed(tc, writer, storage_needed);
buffer = *(writer->cur_write_buffer);
offset = *(writer->cur_write_offset);
if (storage_needed == 1) {
buffer[offset] = 0x80 | (value + 129);
} else if (storage_needed == 9) {
buffer[offset++] = 0x00;
memcpy(buffer + offset, &value, 8);
#ifdef MVM_BIGENDIAN
switch_endian(buffer + offset, 8);
#endif
} else {
MVMuint8 rest = storage_needed - 1;
MVMint64 nybble = value >> 8 * rest;
/* All the other high bits should be the same as the top bit of the
nybble we keep. Or we have a bug. */
assert((nybble >> 3) == 0
|| (nybble >> 3) == ~(MVMuint64)0);
buffer[offset++] = (rest << 4) | (nybble & 0xF);
#ifdef MVM_BIGENDIAN
memcpy(buffer + offset, (char *)&value + 8 - rest, rest);
switch_endian(buffer + offset, rest);
#else
memcpy(buffer + offset, &value, rest);
#endif
}
*(writer->cur_write_offset) += storage_needed;
}
/* Writing function for native numbers. */
void MVM_serialization_write_num(MVMThreadContext *tc, MVMSerializationWriter *writer, MVMnum64 value) {
expand_storage_if_needed(tc, writer, 8);
write_double(*(writer->cur_write_buffer), *(writer->cur_write_offset), value);
*(writer->cur_write_offset) += 8;
}
/* Writing function for native strings. */
void MVM_serialization_write_str(MVMThreadContext *tc, MVMSerializationWriter *writer, MVMString *value) {
MVMint32 heap_loc = add_string_to_heap(tc, writer, value);
/* avoid warnings that heap_loc > STRING_HEAP_LOC_MAX is always false */
if (!(heap_loc >= 0 && heap_loc <= STRING_HEAP_LOC_MAX))
MVM_exception_throw_adhoc(tc,
"Serialization error: string offset %d can't be serialized",
heap_loc);
if (heap_loc <= STRING_HEAP_LOC_PACKED_MAX) {
expand_storage_if_needed(tc, writer, 2);
write_uint16(*(writer->cur_write_buffer), *(writer->cur_write_offset),
heap_loc);
*(writer->cur_write_offset) += 2;
} else {
expand_storage_if_needed(tc, writer, 4);
write_uint16(*(writer->cur_write_buffer), *(writer->cur_write_offset),
(heap_loc >> STRING_HEAP_LOC_PACKED_SHIFT)
| STRING_HEAP_LOC_PACKED_OVERFLOW);
*(writer->cur_write_offset) += 2;
write_uint16(*(writer->cur_write_buffer), *(writer->cur_write_offset),
heap_loc & STRING_HEAP_LOC_PACKED_LOW_MASK);
*(writer->cur_write_offset) += 2;
}
}
/* Writes the ID, index pair that identifies an entry in a Serialization
context. */
static void write_locate_sc_and_index(MVMThreadContext *tc, MVMSerializationWriter *writer, MVMint32 sc_id, MVMint32 idx) {
if (sc_id <= PACKED_SC_MAX && idx <= PACKED_SC_IDX_MAX) {
MVMuint32 packed = (sc_id << PACKED_SC_SHIFT) | (idx & PACKED_SC_IDX_MASK);
MVM_serialization_write_int(tc, writer, packed);
} else {
MVMuint32 packed = PACKED_SC_OVERFLOW << PACKED_SC_SHIFT;
MVM_serialization_write_int(tc, writer, packed);
MVM_serialization_write_int(tc, writer, sc_id);
MVM_serialization_write_int(tc, writer, idx);
}
}
/* Writes an object reference. */
static void write_obj_ref(MVMThreadContext *tc, MVMSerializationWriter *writer, MVMObject *ref) {
MVMint32 sc_id, idx;
if (OBJ_IS_NULL(MVM_sc_get_obj_sc(tc, ref))) {
/* This object doesn't belong to an SC yet, so it must be serialized as part of
* this compilation unit. Add it to the work list. */
MVM_sc_set_obj_sc(tc, ref, writer->root.sc);
MVM_sc_push_object(tc, writer->root.sc, ref);
}
sc_id = get_sc_id(tc, writer, MVM_sc_get_obj_sc(tc, ref));
idx = (MVMint32)MVM_sc_find_object_idx(tc, MVM_sc_get_obj_sc(tc, ref), ref);
write_locate_sc_and_index(tc, writer, sc_id, idx);
}
/* Writes an array where each item is a variant reference. */
static void write_array_var(MVMThreadContext *tc, MVMSerializationWriter *writer, MVMObject *arr) {
MVMint32 elems = (MVMint32)MVM_repr_elems(tc, arr);
MVMint32 i;
/* Write out element count. */
MVM_serialization_write_int(tc, writer, elems);
/* Write elements. */
for (i = 0; i < elems; i++)
MVM_serialization_write_ref(tc, writer, MVM_repr_at_pos_o(tc, arr, i));
}
/* Writes an array where each item is an integer. */
static void write_array_int(MVMThreadContext *tc, MVMSerializationWriter *writer, MVMObject *arr) {
MVMint32 elems = (MVMint32)MVM_repr_elems(tc, arr);
MVMint32 i;
/* Write out element count. */
MVM_serialization_write_int(tc, writer, elems);
/* Write elements. */
for (i = 0; i < elems; i++)
MVM_serialization_write_int(tc, writer, MVM_repr_at_pos_i(tc, arr, i));
}
/* Writes an array where each item is a MVMString. */
static void write_array_str(MVMThreadContext *tc, MVMSerializationWriter *writer, MVMObject *arr) {
MVMint32 elems = (MVMint32)MVM_repr_elems(tc, arr);
MVMint32 i;
/* Write out element count. */
MVM_serialization_write_int(tc, writer, elems);
/* Write elements. */
for (i = 0; i < elems; i++)
MVM_serialization_write_str(tc, writer, MVM_repr_at_pos_s(tc, arr, i));
}
/* Writes a hash where each key is a MVMString and each value a variant reference. */
MVMThreadContext *cmp_tc;
static int cmp_strings(const void *s1, const void *s2) {
return MVM_string_compare(cmp_tc, *(MVMString **)s1, *(MVMString **)s2);
}
static void write_hash_str_var(MVMThreadContext *tc, MVMSerializationWriter *writer, MVMObject *hash) {
MVMint32 elems = (MVMint32)MVM_repr_elems(tc, hash);
MVMString **keys = MVM_malloc(sizeof(MVMString *) * elems);
MVMObject *iter = MVM_iter(tc, hash);
MVMuint64 i = 0;
/* Write out element count. */
MVM_serialization_write_int(tc, writer, elems);
/* Write elements, as key,value,key,value etc. */
while (MVM_iter_istrue(tc, (MVMIter *)iter)) {
MVM_repr_shift_o(tc, iter);
keys[i++] = MVM_iterkey_s(tc, (MVMIter *)iter);
}
cmp_tc = tc;
qsort(keys, elems, sizeof(MVMString*), cmp_strings);
for (i = 0; i < elems; i++) {
MVM_serialization_write_str(tc, writer, keys[i]);
MVM_serialization_write_ref(tc, writer, MVM_repr_at_key_o(tc, hash, keys[i]));
}
MVM_free(keys);
}
/* Writes a reference to a code object in some SC. */
static void write_code_ref(MVMThreadContext *tc, MVMSerializationWriter *writer, MVMObject *code) {
MVMSerializationContext *sc = MVM_sc_get_obj_sc(tc, code);
MVMint32 sc_id = get_sc_id(tc, writer, sc);
MVMint32 idx = (MVMint32)MVM_sc_find_code_idx(tc, sc, code);
write_locate_sc_and_index(tc, writer, sc_id, idx);
}
MVM_NO_RETURN void throw_closure_serialization_error(MVMThreadContext *tc, MVMCode *closure, const char *message) MVM_NO_RETURN_ATTRIBUTE;
MVM_NO_RETURN void throw_closure_serialization_error(MVMThreadContext *tc, MVMCode *closure, const char *message) {
MVMString *file;
MVMint32 line;
MVM_gc_enter_from_allocator(tc); /* opportunity for creating a heap snapshot for debugging */
MVM_code_location_out(tc, (MVMObject *)closure, &file, &line);
{
char *c_name = MVM_string_utf8_encode_C_string(tc,
(closure->body.sf)->body.name);
char *c_file = MVM_string_utf8_encode_C_string(tc, file);
char *waste[] = { c_name, c_file, NULL };
MVM_exception_throw_adhoc_free(tc, waste,
"Serialization Error: %s '%s' (%s:%d)",
message, c_name, c_file, line);
}
}
/* Given a closure, locate the static code reference it was originally cloned
* from. */
static MVMObject * closure_to_static_code_ref(MVMThreadContext *tc, MVMObject *closure, MVMint64 fatal) {
MVMObject *scr = (MVMObject *)(((MVMCode *)closure)->body.sf)->body.static_code;
if (scr == NULL || MVM_sc_get_obj_sc(tc, scr) == NULL) {
if (fatal) {
throw_closure_serialization_error(
tc,
(MVMCode *)closure,
"missing static code ref for closure"
);
}
return NULL;
}
return scr;
}
/* Takes an outer context that is potentially to be serialized. Checks if it
* is of interest, and if so sets it up to be serialized. */
static MVMint32 get_serialized_context_idx(MVMThreadContext *tc, MVMSerializationWriter *writer, MVMFrame *ctx, MVMCode *closure) {
if (OBJ_IS_NULL(MVM_sc_get_frame_sc(tc, ctx))) {
/* Make sure we should chase a level down. */
if (OBJ_IS_NULL(closure_to_static_code_ref(tc, ctx->code_ref, 0))) {
return 0;
}
else {
if (writer->num_contexts == writer->alloc_contexts) {
writer->alloc_contexts += 256;
writer->contexts_list = MVM_realloc(writer->contexts_list,
writer->alloc_contexts * sizeof(MVMFrame *));
}
writer->contexts_list[writer->num_contexts++] = ctx;
MVM_sc_set_frame_sc(tc, ctx, writer->root.sc);
return (MVMint32)writer->num_contexts;
}
}
else {
MVMint64 i, c;
if (MVM_sc_get_frame_sc(tc, ctx) != writer->root.sc)
throw_closure_serialization_error(tc,
closure,
"reference to context outside of SC for"
);
c = writer->num_contexts;
for (i = 0; i < c; i++)
if (writer->contexts_list[i] == ctx)
return (MVMint32)i + 1;
throw_closure_serialization_error(
tc,
closure,
"could not locate outer context in current SC for"
);
}
}
/* Takes a closure, that is to be serialized. Checks if it has an outer that is
* of interest, and if so sets it up to be serialized. */
static MVMint32 get_serialized_outer_context_idx(MVMThreadContext *tc, MVMSerializationWriter *writer, MVMObject *closure) {
if (((MVMCode *)closure)->body.is_compiler_stub)
return 0;
if (((MVMCode *)closure)->body.outer == NULL)
return 0;
return get_serialized_context_idx(tc, writer, ((MVMCode *)closure)->body.outer, (MVMCode *)closure);
}
/* Takes a closure that needs to be serialized. Makes an entry in the closures
* table for it. Also adds it to this SC's code refs set and tags it with the
* current SC. */
static void serialize_closure(MVMThreadContext *tc, MVMSerializationWriter *writer, MVMObject *closure) {
MVMint32 static_sc_id, static_idx, context_idx;
/* Locate the static code object. */
MVMObject *static_code_ref = closure_to_static_code_ref(tc, closure, 1);
MVMSerializationContext *static_code_sc = MVM_sc_get_obj_sc(tc, static_code_ref);
/* Ensure there's space in the closures table; grow if not. */
MVMint32 offset = writer->root.num_closures * CLOSURES_TABLE_ENTRY_SIZE;
if (offset + CLOSURES_TABLE_ENTRY_SIZE > writer->closures_table_alloc) {
GROW_TABLE(writer->root.closures_table, writer->closures_table_alloc);
}
/* Get the index of the context (which will add it to the todo list if
* needed). */
context_idx = get_serialized_outer_context_idx(tc, writer, closure);
/* Add an entry to the closures table. */
static_sc_id = get_sc_id(tc, writer, static_code_sc);
static_idx = (MVMint32)MVM_sc_find_code_idx(tc, static_code_sc, static_code_ref);
write_int32(writer->root.closures_table, offset, static_sc_id);
write_int32(writer->root.closures_table, offset + 4, static_idx);
write_int32(writer->root.closures_table, offset + 8, context_idx);
/* Check if it has a static code object. */
if (((MVMCode *)closure)->body.code_object) {
MVMObject *code_obj = (MVMObject *)((MVMCode *)closure)->body.code_object;
write_int32(writer->root.closures_table, offset + 12, 1);
if (!MVM_sc_get_obj_sc(tc, code_obj)) {
MVM_sc_set_obj_sc(tc, code_obj, writer->root.sc);
MVM_sc_push_object(tc, writer->root.sc, code_obj);
}
write_int32(writer->root.closures_table, offset + 16,
get_sc_id(tc, writer, MVM_sc_get_obj_sc(tc, code_obj)));
write_int32(writer->root.closures_table, offset + 20,
(MVMint32)MVM_sc_find_object_idx(tc, MVM_sc_get_obj_sc(tc, code_obj), code_obj));
}
else {
write_int32(writer->root.closures_table, offset + 12, 0);
}
/* Increment count of closures in the table. */
writer->root.num_closures++;
/* Add the closure to this SC, and mark it as as being in it. */
MVM_repr_push_o(tc, writer->codes_list, closure);
MVM_sc_set_obj_sc(tc, closure, writer->root.sc);
}
/* Writing function for references to things. */
void MVM_serialization_write_ref(MVMThreadContext *tc, MVMSerializationWriter *writer, MVMObject *ref) {
/* Work out what kind of thing we have and determine the discriminator. */
/* Note, we could use 0xFF as the sentinel value, and 0 as a "valid" value.
*/
MVMuint8 discrim = 0;
if (ref == NULL) {
discrim = REFVAR_NULL;
}
else if (ref == tc->instance->VMNull) {
discrim = REFVAR_VM_NULL;
}
else if (REPR(ref)->ID == MVM_REPR_ID_MVMMultiCache) {
discrim = REFVAR_VM_NULL;
}
else if (REPR(ref)->ID == MVM_REPR_ID_MVMOSHandle) {
discrim = REFVAR_VM_NULL;
}
else if (REPR(ref)->ID == MVM_REPR_ID_Decoder && IS_CONCRETE(ref)) {
discrim = REFVAR_VM_NULL;
}
else if (STABLE(ref) == STABLE(tc->instance->boot_types.BOOTInt) && IS_CONCRETE(ref)) {
discrim = REFVAR_VM_INT;
}
else if (STABLE(ref) == STABLE(tc->instance->boot_types.BOOTNum) && IS_CONCRETE(ref)) {
discrim = REFVAR_VM_NUM;
}
else if (STABLE(ref) == STABLE(tc->instance->boot_types.BOOTStr) && IS_CONCRETE(ref)) {
discrim = REFVAR_VM_STR;
}
else if (STABLE(ref) == STABLE(tc->instance->boot_types.BOOTArray) && IS_CONCRETE(ref)) {
discrim = REFVAR_VM_ARR_VAR;
}
else if (STABLE(ref) == STABLE(tc->instance->boot_types.BOOTIntArray) && IS_CONCRETE(ref)) {
discrim = REFVAR_VM_ARR_INT;
}
else if (STABLE(ref) == STABLE(tc->instance->boot_types.BOOTStrArray) && IS_CONCRETE(ref)) {
discrim = REFVAR_VM_ARR_STR;
}
else if (STABLE(ref) == STABLE(tc->instance->boot_types.BOOTHash) && IS_CONCRETE(ref)) {
discrim = REFVAR_VM_HASH_STR_VAR;
}
else if (REPR(ref)->ID == MVM_REPR_ID_MVMCode && IS_CONCRETE(ref)) {
if (MVM_sc_get_obj_sc(tc, ref) && ((MVMCode *)ref)->body.is_static) {
/* Static code reference. */
discrim = REFVAR_STATIC_CODEREF;
}
else if (MVM_sc_get_obj_sc(tc, ref)) {
/* Closure, but already seen and serialization already handled. */
discrim = REFVAR_CLONED_CODEREF;
}
else {
/* Closure but didn't see it yet. Take care of its serialization, which
* gets it marked with this SC. Then it's just a normal code ref that
* needs serializing. */
serialize_closure(tc, writer, ref);
discrim = REFVAR_CLONED_CODEREF;
}
}
else if (REPR(ref)->ID == MVM_REPR_ID_SCRef && IS_CONCRETE(ref)) {
discrim = REFVAR_SC_REF;
}
else {
discrim = REFVAR_OBJECT;
}
/* Write the discriminator. */
expand_storage_if_needed(tc, writer, 1);
*(*(writer->cur_write_buffer) + *(writer->cur_write_offset)) = discrim;
++*(writer->cur_write_offset);
/* Now take appropriate action. */
switch (discrim) {
case REFVAR_NULL: break;
case REFVAR_OBJECT:
write_obj_ref(tc, writer, ref);
break;
case REFVAR_VM_NULL:
/* Nothing to do for these. */
break;
case REFVAR_VM_INT:
MVM_serialization_write_int(tc, writer, MVM_repr_get_int(tc, ref));
break;
case REFVAR_VM_NUM:
MVM_serialization_write_num(tc, writer, MVM_repr_get_num(tc, ref));
break;
case REFVAR_VM_STR:
MVM_serialization_write_str(tc, writer, MVM_repr_get_str(tc, ref));
break;
case REFVAR_VM_ARR_VAR:
write_array_var(tc, writer, ref);
break;
case REFVAR_VM_ARR_STR:
write_array_str(tc, writer, ref);
break;
case REFVAR_VM_ARR_INT:
write_array_int(tc, writer, ref);
break;
case REFVAR_VM_HASH_STR_VAR:
write_hash_str_var(tc, writer, ref);
break;
case REFVAR_STATIC_CODEREF:
case REFVAR_CLONED_CODEREF:
write_code_ref(tc, writer, ref);
break;
case REFVAR_SC_REF: {
MVMString *handle = MVM_sc_get_handle(tc, (MVMSerializationContext *)ref);
MVM_serialization_write_str(tc, writer, handle);
break;
}
default:
MVM_exception_throw_adhoc(tc,
"Serialization Error: Unimplemented discriminator %d in MVM_serialization_read_ref",
discrim);
}
}
/* Writing function for references to STables. */
void MVM_serialization_write_stable_ref(MVMThreadContext *tc, MVMSerializationWriter *writer, MVMSTable *st) {
MVMuint32 sc_id, idx;
get_stable_ref_info(tc, writer, st, &sc_id, &idx);
write_locate_sc_and_index(tc, writer, sc_id, idx);
}
/* Concatenates the various output segments into a single binary MVMString. */
static MVMString * concatenate_outputs(MVMThreadContext *tc, MVMSerializationWriter *writer) {
char *output = NULL;
char *output_b64 = NULL;
MVMuint32 output_size = 0;
MVMuint32 offset = 0;
MVMString *result;
/* Calculate total size. */
output_size += MVM_ALIGN_SECTION(HEADER_SIZE);
output_size += MVM_ALIGN_SECTION(writer->root.num_dependencies * DEP_TABLE_ENTRY_SIZE);
output_size += MVM_ALIGN_SECTION(writer->root.num_stables * STABLES_TABLE_ENTRY_SIZE);
output_size += MVM_ALIGN_SECTION(writer->stables_data_offset);
output_size += MVM_ALIGN_SECTION(writer->root.num_objects * OBJECTS_TABLE_ENTRY_SIZE);
output_size += MVM_ALIGN_SECTION(writer->objects_data_offset);
output_size += MVM_ALIGN_SECTION(writer->root.num_closures * CLOSURES_TABLE_ENTRY_SIZE);
output_size += MVM_ALIGN_SECTION(writer->root.num_contexts * CONTEXTS_TABLE_ENTRY_SIZE);
output_size += MVM_ALIGN_SECTION(writer->contexts_data_offset);
output_size += MVM_ALIGN_SECTION(writer->root.num_repos * REPOS_TABLE_ENTRY_SIZE);
output_size += MVM_ALIGN_SECTION(writer->param_interns_data_offset);
/* Allocate a buffer that size. */
output = (char *)MVM_calloc(1, output_size);
/* Write version into header. */
write_int32(output, 0, CURRENT_VERSION);
offset += MVM_ALIGN_SECTION(HEADER_SIZE);
/* Put dependencies table in place and set location/rows in header. */
write_int32(output, 4, offset);
write_int32(output, 8, writer->root.num_dependencies);
memcpy(output + offset, writer->root.dependencies_table,
writer->root.num_dependencies * DEP_TABLE_ENTRY_SIZE);
offset += MVM_ALIGN_SECTION(writer->root.num_dependencies * DEP_TABLE_ENTRY_SIZE);
/* Put STables table in place, and set location/rows in header. */
write_int32(output, 12, offset);
write_int32(output, 16, writer->root.num_stables);
memcpy(output + offset, writer->root.stables_table,
writer->root.num_stables * STABLES_TABLE_ENTRY_SIZE);
offset += MVM_ALIGN_SECTION(writer->root.num_stables * STABLES_TABLE_ENTRY_SIZE);
/* Put STables data in place. */
write_int32(output, 20, offset);
memcpy(output + offset, writer->root.stables_data,
writer->stables_data_offset);
offset += MVM_ALIGN_SECTION(writer->stables_data_offset);
/* Put objects table in place, and set location/rows in header. */
write_int32(output, 24, offset);
write_int32(output, 28, writer->root.num_objects);
memcpy(output + offset, writer->root.objects_table,
writer->root.num_objects * OBJECTS_TABLE_ENTRY_SIZE);
offset += MVM_ALIGN_SECTION(writer->root.num_objects * OBJECTS_TABLE_ENTRY_SIZE);
/* Put objects data in place. */
write_int32(output, 32, offset);
memcpy(output + offset, writer->root.objects_data,
writer->objects_data_offset);
offset += MVM_ALIGN_SECTION(writer->objects_data_offset);
/* Put closures table in place, and set location/rows in header. */
write_int32(output, 36, offset);
write_int32(output, 40, writer->root.num_closures);
memcpy(output + offset, writer->root.closures_table,
writer->root.num_closures * CLOSURES_TABLE_ENTRY_SIZE);
offset += MVM_ALIGN_SECTION(writer->root.num_closures * CLOSURES_TABLE_ENTRY_SIZE);
/* Put contexts table in place, and set location/rows in header. */
write_int32(output, 44, offset);
write_int32(output, 48, writer->root.num_contexts);
memcpy(output + offset, writer->root.contexts_table,
writer->root.num_contexts * CONTEXTS_TABLE_ENTRY_SIZE);
offset += MVM_ALIGN_SECTION(writer->root.num_contexts * CONTEXTS_TABLE_ENTRY_SIZE);
/* Put contexts data in place. */
write_int32(output, 52, offset);
memcpy(output + offset, writer->root.contexts_data,
writer->contexts_data_offset);
offset += MVM_ALIGN_SECTION(writer->contexts_data_offset);
/* Put repossessions table in place, and set location/rows in header. */
write_int32(output, 56, offset);
write_int32(output, 60, writer->root.num_repos);
memcpy(output + offset, writer->root.repos_table,
writer->root.num_repos * REPOS_TABLE_ENTRY_SIZE);
offset += MVM_ALIGN_SECTION(writer->root.num_repos * REPOS_TABLE_ENTRY_SIZE);
/* Put parameterized type intern data in place. */
write_int32(output, 64, offset);
write_int32(output, 68, writer->root.num_param_interns);
memcpy(output + offset, writer->root.param_interns_data,
writer->param_interns_data_offset);
offset += MVM_ALIGN_SECTION(writer->param_interns_data_offset);
/* Sanity check. */
if (offset != output_size)
MVM_exception_throw_adhoc(tc,
"Serialization sanity check failed: offset != output_size");
/* If we are compiling at present, then just stash the output for later
* incorporation into the bytecode file. */
if (tc->compiling_scs && MVM_repr_elems(tc, tc->compiling_scs) &&
MVM_repr_at_pos_o(tc, tc->compiling_scs, 0) == (MVMObject *)writer->root.sc) {
if (tc->serialized)
MVM_free(tc->serialized);
tc->serialized = output;
tc->serialized_size = output_size;
tc->serialized_string_heap = writer->root.string_heap;
output_b64 = base64_encode(output, output_size);
}
else {
/* Base 64 encode. */
output_b64 = base64_encode(output, output_size);
MVM_free(output);
}
if (output_b64 == NULL)
MVM_exception_throw_adhoc(tc,
"Serialization error: failed to convert to base64");
/* Make a MVMString containing it. */
result = MVM_string_ascii_decode_nt(tc, tc->instance->VMString, output_b64);
MVM_free(output_b64);
return result;
}
/* Serializes the possibly-not-deserialized HOW. */
static void serialize_how_lazy(MVMThreadContext *tc, MVMSerializationWriter *writer, MVMSTable *st) {
if (st->HOW) {
write_obj_ref(tc, writer, st->HOW);
}
else {
MVMint32 sc_id = get_sc_id(tc, writer, st->HOW_sc);
write_locate_sc_and_index(tc, writer, sc_id, st->HOW_idx);
}
}
/* Adds an entry to the parameterized type intern section. */
static void add_param_intern(MVMThreadContext *tc, MVMSerializationWriter *writer,
MVMObject *type, MVMObject *ptype, MVMObject *params) {
MVMint64 num_params, i;
/* Save previous write buffer. */
char **orig_write_buffer = writer->cur_write_buffer;
MVMuint32 *orig_write_offset = writer->cur_write_offset;
MVMuint32 *orig_write_limit = writer->cur_write_limit;
/* Switch to intern data buffer. */
writer->cur_write_buffer = &(writer->root.param_interns_data);
writer->cur_write_offset = &(writer->param_interns_data_offset);
writer->cur_write_limit = &(writer->param_interns_data_alloc);
/* Parametric type object reference. */
write_obj_ref(tc, writer, ptype);
/* Indexes in this SC of type object and STable. */
expand_storage_if_needed(tc, writer, 12);
if (MVM_sc_get_obj_sc(tc, type) != writer->root.sc)
MVM_exception_throw_adhoc(tc,
"Serialization error: parameterized type to intern not in current SC");
write_int32(*(writer->cur_write_buffer), *(writer->cur_write_offset),
MVM_sc_find_object_idx(tc, writer->root.sc, type));
*(writer->cur_write_offset) += 4;
if (MVM_sc_get_stable_sc(tc, STABLE(type)) != writer->root.sc)
MVM_exception_throw_adhoc(tc,
"Serialization error: STable of parameterized type to intern not in current SC");
write_int32(*(writer->cur_write_buffer), *(writer->cur_write_offset),
MVM_sc_find_stable_idx(tc, writer->root.sc, STABLE(type)));
*(writer->cur_write_offset) += 4;
/* Write parameter count and parameter object refs. */
num_params = MVM_repr_elems(tc, params);
write_int32(*(writer->cur_write_buffer), *(writer->cur_write_offset),
(MVMint32)num_params);
*(writer->cur_write_offset) += 4;
for (i = 0; i < num_params; i++)
write_obj_ref(tc, writer, MVM_repr_at_pos_o(tc, params, i));
/* Increment number of parameterization interns. */
writer->root.num_param_interns++;
/* Restore original output buffer. */
writer->cur_write_buffer = orig_write_buffer;
writer->cur_write_offset = orig_write_offset;
writer->cur_write_limit = orig_write_limit;
}
/* This handles the serialization of an STable, and calls off to serialize
* its representation data also. */
static void serialize_stable(MVMThreadContext *tc, MVMSerializationWriter *writer, MVMSTable *st) {
MVMint64 i;
MVMuint8 flags;
/* Ensure there's space in the STables table; grow if not. */
MVMint32 offset = writer->root.num_stables * STABLES_TABLE_ENTRY_SIZE;
if (offset + STABLES_TABLE_ENTRY_SIZE > writer->stables_table_alloc) {
GROW_TABLE(writer->root.stables_table, writer->stables_table_alloc);