forked from samhocevar/z8lua
-
Notifications
You must be signed in to change notification settings - Fork 3
/
eris.c
2714 lines (2390 loc) · 102 KB
/
eris.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
/*
Eris - Heavy-duty persistence for Lua 5.2.4 - Based on Pluto
Copyright (c) 2013-2015 by Florian Nuecke.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/* Standard library headers. */
#include <assert.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
/* Not using stdbool because Visual Studio lives in the past... */
#ifndef __cplusplus
typedef int bool;
#define false 0
#define true 1
#endif
/* Mark us as part of the Lua core to get access to what we need. */
#define eris_c
#define LUA_CORE
/* Public Lua headers. */
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
/* Internal Lua headers. */
#include "ldebug.h"
#include "ldo.h"
#include "lfunc.h"
#include "lobject.h"
#include "lstate.h"
#include "lstring.h"
#include "lzio.h"
/* Eris header. */
#include "eris.h"
/*
** {===========================================================================
** Default settings.
** ============================================================================
*/
/* Note that these are the default settings. They can be changed either from C
* by calling eris_g|set_setting() or from Lua using eris.settings(). */
/* The metatable key we use to allow customized persistence for tables and
* userdata. */
static const char *const kPersistKey = "__persist";
/* Whether to pass the IO object (reader/writer) to the special function
* defined in the metafield or not. This is disabled per default because it
* mey allow Lua scripts to do more than they should. Enable this as needed. */
static const bool kPassIOToPersist = false;
/* Whether to persist debug information such as line numbers and upvalue and
* local variable names. */
static const bool kWriteDebugInformation = true;
/* Generate a human readable "path" that is shown together with error messages
* to indicate where in the object the error occurred. For example:
* eris.persist({false, bad = setmetatable({}, {__persist = false})})
* Will produce: main:1: attempt to persist forbidden table (root.bad)
* This can be used for debugging, but is disabled per default due to the
* processing and memory overhead this introduces. */
static const bool kGeneratePath = false;
/* The maximum object complexity. This is the number of allowed recursions when
* persisting or unpersisting an object, for example for nested tables. This is
* used to avoid segfaults when writing or reading user data. */
static const lua_Unsigned kMaxComplexity = 10000;
/*
** ============================================================================
** Lua internals interfacing.
** ============================================================================
*/
/* Lua internals we use. We define these as macros to make it easier to swap
* them out, should the need ever arise. For example, the later Pluto versions
* copied these function to own files (presumably to allow building it as an
* extra shared library). These should be all functions we use that are not
* declared in lua.h or lauxlib.h. If there are some still directly in the code
* they were missed and should be replaced with a macro added here instead. */
/* I'm quite sure we won't ever want to do this, because Eris needs a slightly
* patched Lua version to be able to persist some of the library functions,
* anyway: it needs to put the continuation C functions in the perms table. */
/* ldebug.h */
#define eris_ci_func ci_func
/* ldo.h */
#define eris_incr_top incr_top
#define eris_savestack savestack
#define eris_restorestack restorestack
#define eris_reallocstack luaD_reallocstack
/* lfunc.h */
#define eris_newproto luaF_newproto
#define eris_newLclosure luaF_newLclosure
#define eris_newupval luaF_newupval
#define eris_findupval luaF_findupval
/* lgc.h */
#define eris_barrierproto luaC_barrierproto
/* lmem.h */
#define eris_reallocvector luaM_reallocvector
/* lobject.h */
#define eris_ttypenv ttypenv
#define eris_clLvalue clLvalue
#define eris_setnilvalue setnilvalue
#define eris_setclLvalue setclLvalue
#define eris_setobj setobj
#define eris_setsvalue2n setsvalue2n
/* lstate.h */
#define eris_isLua isLua
#define eris_gch gch
#define eris_gco2uv gco2uv
#define eris_obj2gco obj2gco
#define eris_extendCI luaE_extendCI
/* lstring. h */
#define eris_newlstr luaS_newlstr
/* lzio.h */
#define eris_initbuffer luaZ_initbuffer
#define eris_buffer luaZ_buffer
#define eris_sizebuffer luaZ_sizebuffer
#define eris_bufflen luaZ_bufflen
#define eris_init luaZ_init
#define eris_read luaZ_read
/* These are required for cross-platform support, since the size of TValue may
* differ, so the byte offset used by savestack/restorestack in Lua it is not a
* valid measure. */
#define eris_savestackidx(L, p) ((p) - (L)->stack)
#define eris_restorestackidx(L, n) ((L)->stack + (n))
/*
** ============================================================================
** Language strings for errors.
** ============================================================================
*/
#define ERIS_ERR_CFUNC "attempt to persist a light C function (%p)"
#define ERIS_ERR_COMPLEXITY "object too complex"
#define ERIS_ERR_METATABLE "bad metatable, not nil or table"
#define ERIS_ERR_NOFUNC "attempt to persist unknown function type"
#define ERIS_ERR_READ "could not read data"
#define ERIS_ERR_SPER_FUNC "%s did not return a function"
#define ERIS_ERR_SPER_LOAD "bad unpersist function (%s expected, returned %s)"
#define ERIS_ERR_SPER_PROT "attempt to persist forbidden table"
#define ERIS_ERR_SPER_TYPE "%d not nil, boolean, or function"
#define ERIS_ERR_SPER_UFUNC "invalid restore function"
#define ERIS_ERR_SPER_UPERM "bad permanent value (%s expected, got %s)"
#define ERIS_ERR_SPER_UPERMNIL "bad permanent value (no value)"
#define ERIS_ERR_STACKBOUNDS "stack index out of bounds"
#define ERIS_ERR_TABLE "bad table value, got a nil value"
#define ERIS_ERR_THREAD "cannot persist currently running thread"
#define ERIS_ERR_THREADCI "invalid callinfo"
#define ERIS_ERR_THREADCTX "bad C continuation function"
#define ERIS_ERR_THREADERRF "invalid errfunc"
#define ERIS_ERR_THREADPC "saved program counter out of bounds"
#define ERIS_ERR_TRUNC_INT "int value would get truncated"
#define ERIS_ERR_TRUNC_SIZE "size_t value would get truncated"
#define ERIS_ERR_TYPE_FLOAT "unsupported lua_Number type"
#define ERIS_ERR_TYPE_INT "unsupported int type"
#define ERIS_ERR_TYPE_SIZE "unsupported size_t type"
#define ERIS_ERR_TYPEP "trying to persist unknown type %d"
#define ERIS_ERR_TYPEU "trying to unpersist unknown type %d"
#define ERIS_ERR_UCFUNC "bad C closure (C function expected, got %s)"
#define ERIS_ERR_UCFUNCNULL "bad C closure (C function expected, got null)"
#define ERIS_ERR_USERDATA "attempt to literally persist userdata"
#define ERIS_ERR_WRITE "could not write data"
#define ERIS_ERR_REF "invalid reference #%d. this usually means a special "\
"persistence callback of a table referenced said table "\
"(directly or indirectly via an upvalue)."
/*
** ============================================================================
** Constants, settings, types and forward declarations.
** ============================================================================
*/
/* The "type" we write when we persist a value via a replacement from the
* permanents table. This is just an arbitrary number, but it must we lower
* than the reference offset (below) and outside the range Lua uses for its
* types (> LUA_TOTALTAGS). */
#define ERIS_PERMANENT (LUA_TOTALTAGS + 1)
/* This is essentially the first reference we'll use. We do this to save one
* field in our persisted data: if the value is smaller than this, the object
* itself follows, otherwise we have a reference to an already unpersisted
* object. Note that in the reftable the actual entries are still stored
* starting at the first array index to have a sequence (when unpersisting). */
#define ERIS_REFERENCE_OFFSET (ERIS_PERMANENT + 1)
/* Avoids having to write the NULL all the time, plus makes it easier adding
* a custom error message should you ever decide you want one. */
#define eris_checkstack(L, n) luaL_checkstack(L, n, NULL)
/* Used for internal consistency checks, for debugging. These are true asserts
* in the sense that they should never fire, even for bad inputs. */
#if 0
#define eris_assert(c) assert(c)
#define eris_ifassert(e) e
#else
#define eris_assert(c) ((void)0)
#define eris_ifassert(e) ((void)0)
#endif
/* State information when persisting an object. */
typedef struct PersistInfo {
lua_Writer writer;
void *ud;
const char *metafield;
bool writeDebugInfo;
} PersistInfo;
/* State information when unpersisting an object. */
typedef struct UnpersistInfo {
ZIO zio;
size_t sizeof_int;
size_t sizeof_size_t;
} UnpersistInfo;
/* Info shared in persist and unpersist. */
typedef struct Info {
lua_State *L;
lua_Unsigned level;
int refcount; /* int because rawseti/rawgeti takes an int. */
lua_Unsigned maxComplexity;
bool generatePath;
bool passIOToPersist;
/* Which one it really is will always be clear from the context. */
union {
PersistInfo pi;
UnpersistInfo upi;
} u;
} Info;
/* Type names, used for error messages. */
static const char *const kTypenames[] = {
"nil", "boolean", "lightuserdata", "number", "string",
"table", "function", "userdata", "thread", "proto", "upval",
"deadkey", "permanent"
};
/* Setting names as used in eris.settings / eris_g|set_setting. Also, the
* addresses of these static variables are used as keys in the registry of Lua
* states to save the current values of the settings (as light userdata). */
static const char *const kSettingMetafield = "spkey";
static const char *const kSettingPassIOToPersist = "spio";
static const char *const kSettingGeneratePath = "path";
static const char *const kSettingWriteDebugInfo = "debug";
static const char *const kSettingMaxComplexity = "maxrec";
/* Header we prefix to persisted data for a quick check when unpersisting. */
static char const kHeader[] = { 'E', 'R', 'I', 'S' };
#define HEADER_LENGTH sizeof(kHeader)
/* Floating point number used to check compatibility of loaded data. */
static const lua_Number kHeaderNumber = (lua_Number)-1.234567890;
/* Stack indices of some internal values/tables, to avoid magic numbers. */
#define PERMIDX 1
#define REFTIDX 2
#define BUFFIDX 3
#define PATHIDX 4
/* Table indices for upvalue tables, keeping track of upvals to open. */
#define UVTOCL 1
#define UVTONU 2
#define UVTVAL 3
#define UVTREF 4
/* }======================================================================== */
/*
** {===========================================================================
** Utility functions.
** ============================================================================
*/
/* Pushes an object into the reference table when unpersisting. This creates an
* entry pointing from the id the object is referenced by to the object. */
static int
registerobject(Info *info) { /* perms reftbl ... obj */
const int reference = ++(info->refcount);
eris_checkstack(info->L, 1);
lua_pushvalue(info->L, -1); /* perms reftbl ... obj obj */
lua_rawseti(info->L, REFTIDX, reference); /* perms reftbl ... obj */
return reference;
}
/** ======================================================================== */
/* Pushes a TString* onto the stack if it holds a value, nil if it is NULL. */
static void
pushtstring(lua_State* L, TString *ts) { /* ... */
if (ts) {
eris_setsvalue2n(L, L->top, ts);
eris_incr_top(L); /* ... str */
}
else {
lua_pushnil(L); /* ... nil */
}
}
/* Creates a copy of the string on top of the stack and sets it as the value
* of the specified TString**. */
static void
copytstring(lua_State* L, TString **ts) {
size_t length;
const char *value = lua_tolstring(L, -1, &length);
*ts = eris_newlstr(L, value, length);
}
/** ======================================================================== */
/* Pushes the specified segment to the current path, if we're generating one.
* This supports formatting strings using Lua's formatting capabilities. */
static void
pushpath(Info *info, const char* fmt, ...) { /* perms reftbl var path ... */
if (!info->generatePath) {
return;
}
else {
va_list argp;
eris_checkstack(info->L, 1);
va_start(argp, fmt);
lua_pushvfstring(info->L, fmt, argp); /* perms reftbl var path ... str */
va_end(argp);
lua_rawseti(info->L, PATHIDX, luaL_len(info->L, PATHIDX) + 1);
} /* perms reftbl var path ... */
}
/* Pops the last added segment from the current path if we're generating one. */
static void
poppath(Info *info) { /* perms reftbl var path ... */
if (!info->generatePath) {
return;
}
eris_checkstack(info->L, 1);
lua_pushnil(info->L); /* perms reftbl var path ... nil */
lua_rawseti(info->L, PATHIDX, luaL_len(info->L, PATHIDX));
} /* perms reftbl var path ... */
/* Concatenates all current path segments into one string, pushes it and
* returns it. This is relatively inefficient, but it's for errors only and
* keeps the stack small, so it's better this way. */
static const char*
path(Info *info) { /* perms reftbl var path ... */
if (!info->generatePath) {
return "";
}
eris_checkstack(info->L, 3);
lua_pushstring(info->L, ""); /* perms reftbl var path ... str */
lua_pushnil(info->L); /* perms reftbl var path ... str nil */
while (lua_next(info->L, PATHIDX)) { /* perms reftbl var path ... str k v */
lua_insert(info->L, -2); /* perms reftbl var path ... str v k */
lua_insert(info->L, -3); /* perms reftbl var path ... k str v */
lua_concat(info->L, 2); /* perms reftbl var path ... k str */
lua_insert(info->L, -2); /* perms reftbl var path ... str k */
} /* perms reftbl var path ... str */
return lua_tostring(info->L, -1);
}
/* Generates an error message with the appended path, if available. */
static int
eris_error(Info *info, const char *fmt, ...) { /* ... */
va_list argp;
eris_checkstack(info->L, 5);
luaL_where(info->L, 1); /* ... where */
va_start(argp, fmt);
lua_pushvfstring(info->L, fmt, argp); /* ... where str */
va_end(argp);
if (info->generatePath) {
lua_pushstring(info->L, " ("); /* ... where str " (" */
path(info); /* ... where str " (" path */
lua_pushstring(info->L, ")"); /* ... where str " (" path ")" */
lua_concat(info->L, 5); /* ... msg */
}
else {
lua_concat(info->L, 2); /* ... msg */
}
return lua_error(info->L);
}
/** ======================================================================== */
/* Tries to get a setting from the registry. */
static bool
get_setting(lua_State *L, void *key) { /* ... */
eris_checkstack(L, 1);
lua_pushlightuserdata(L, key); /* ... key */
lua_gettable(L, LUA_REGISTRYINDEX); /* ... value/nil */
if (lua_isnil(L, -1)) { /* ... nil */
lua_pop(L, 1); /* ... */
return false;
} /* ... value */
return true;
}
/* Stores a setting in the registry (or removes it if the value is nil). */
static void
set_setting(lua_State *L, void *key) { /* ... value */
eris_checkstack(L, 2);
lua_pushlightuserdata(L, key); /* ... value key */
lua_insert(L, -2); /* ... key value */
lua_settable(L, LUA_REGISTRYINDEX); /* ... */
}
/* Used as a callback for luaL_opt to check boolean setting values. */
static bool
checkboolean(lua_State *L, int narg) { /* ... bool? ... */
if (!lua_isboolean(L, narg)) { /* ... :( ... */
return luaL_argerror(L, narg, lua_pushfstring(L,
"boolean expected, got %s", lua_typename(L, lua_type(L, narg))));
} /* ... bool ... */
return lua_toboolean(L, narg);
}
/* }======================================================================== */
/*
** {===========================================================================
** Persist and unpersist.
** ============================================================================
*/
/* I have macros and I'm not afraid to use them! These are highly situational
* and assume an Info* named 'info' is available. */
/* Writes a raw memory block with the specified size. */
#define WRITE_RAW(value, size) {\
if (info->u.pi.writer(info->L, (value), (size), info->u.pi.ud)) \
eris_error(info, ERIS_ERR_WRITE); }
/* Writes a single value with the specified type. */
#define WRITE_VALUE(value, type) write_##type(info, value)
/* Writes a typed array with the specified length. */
#define WRITE(value, length, type) { \
int i; for (i = 0; i < length; ++i) WRITE_VALUE((value)[i], type); }
/** ======================================================================== */
/* Reads a raw block of memory with the specified size. */
#define READ_RAW(value, size) {\
if (eris_read(&info->u.upi.zio, (value), (size))) \
eris_error(info, ERIS_ERR_READ); }
/* Reads a single value with the specified type. */
#define READ_VALUE(type) read_##type(info)
/* Reads a typed array with the specified length. */
#define READ(value, length, type) { \
int i; for (i = 0; i < length; ++i) (value)[i] = READ_VALUE(type); }
/** ======================================================================== */
static void
write_uint8_t(Info *info, uint8_t value) {
WRITE_RAW(&value, sizeof(uint8_t));
}
static void
write_uint16_t(Info *info, uint16_t value) {
write_uint8_t(info, value);
write_uint8_t(info, value >> 8);
}
static void
write_uint32_t(Info *info, uint32_t value) {
write_uint8_t(info, value);
write_uint8_t(info, value >> 8);
write_uint8_t(info, value >> 16);
write_uint8_t(info, value >> 24);
}
static void
write_uint64_t(Info *info, uint64_t value) {
write_uint8_t(info, value);
write_uint8_t(info, value >> 8);
write_uint8_t(info, value >> 16);
write_uint8_t(info, value >> 24);
write_uint8_t(info, value >> 32);
write_uint8_t(info, value >> 40);
write_uint8_t(info, value >> 48);
write_uint8_t(info, value >> 56);
}
static void
write_int16_t(Info *info, int16_t value) {
write_uint16_t(info, (uint16_t)value);
}
static void
write_int32_t(Info *info, int32_t value) {
write_uint32_t(info, (uint32_t)value);
}
static void
write_int64_t(Info *info, int64_t value) {
write_uint64_t(info, (uint64_t)value);
}
static void
write_float32(Info *info, float value) {
uint32_t rep;
memcpy(&rep, &value, sizeof(float));
write_uint32_t(info, rep);
}
static void
write_float64(Info *info, double value) {
uint64_t rep;
memcpy(&rep, &value, sizeof(double));
write_uint64_t(info, rep);
}
/* Note regarding the following: any decent compiler should be able
* to reduce these to just the write call, since sizeof is constant. */
static void
write_int(Info *info, int value) {
if (sizeof(int) == sizeof(int16_t)) {
write_int16_t(info, value);
}
else if (sizeof(int) == sizeof(int32_t)) {
write_int32_t(info, value);
}
else if (sizeof(int) == sizeof(int64_t)) {
write_int64_t(info, value);
}
else {
eris_error(info, ERIS_ERR_TYPE_INT);
}
}
static void
write_size_t(Info *info, size_t value) {
if (sizeof(size_t) == sizeof(uint16_t)) {
write_uint16_t(info, value);
}
else if (sizeof(size_t) == sizeof(uint32_t)) {
write_uint32_t(info, value);
}
else if (sizeof(size_t) == sizeof(uint64_t)) {
write_uint64_t(info, value);
}
else {
eris_error(info, ERIS_ERR_TYPE_SIZE);
}
}
static void
write_lua_Number(Info *info, lua_Number value) {
write_int32_t(info, value.bits());
}
/* Note that Lua only ever uses 32 bits of the Instruction type, so we can
* assert that there will be no truncation, even if the underlying type has
* more bits (might be the case on some 64 bit systems). */
static void
write_Instruction(Info *info, Instruction value) {
if (sizeof(Instruction) == sizeof(uint32_t)) {
write_uint32_t(info, value);
}
else {
uint32_t pvalue = (uint32_t)value;
/* Lua only uses 32 bits for its instructions. */
eris_assert((Instruction)pvalue == value);
write_uint32_t(info, pvalue);
}
}
/** ======================================================================== */
static uint8_t
read_uint8_t(Info *info) {
uint8_t value;
READ_RAW(&value, sizeof(uint8_t));
return value;
}
static uint16_t
read_uint16_t(Info *info) {
uint16_t value = (uint16_t)read_uint8_t(info);
value |= (uint16_t)read_uint8_t(info) << 8;
return value;
}
static uint32_t
read_uint32_t(Info *info) {
uint32_t value = (uint32_t)read_uint8_t(info);
value |= (uint32_t)read_uint8_t(info) << 8;
value |= (uint32_t)read_uint8_t(info) << 16;
value |= (uint32_t)read_uint8_t(info) << 24;
return value;
}
static uint64_t
read_uint64_t(Info *info) {
uint64_t value = (uint64_t)read_uint8_t(info);
value |= (uint64_t)read_uint8_t(info) << 8;
value |= (uint64_t)read_uint8_t(info) << 16;
value |= (uint64_t)read_uint8_t(info) << 24;
value |= (uint64_t)read_uint8_t(info) << 32;
value |= (uint64_t)read_uint8_t(info) << 40;
value |= (uint64_t)read_uint8_t(info) << 48;
value |= (uint64_t)read_uint8_t(info) << 56;
return value;
}
static int16_t
read_int16_t(Info *info) {
return (int16_t)read_uint16_t(info);
}
static int32_t
read_int32_t(Info *info) {
return (int32_t)read_uint32_t(info);
}
static int64_t
read_int64_t(Info *info) {
return (int64_t)read_uint64_t(info);
}
static float
read_float32(Info *info) {
float value;
uint32_t rep = read_uint32_t(info);
memcpy(&value, &rep, sizeof(float));
return value;
}
static double
read_float64(Info *info) {
double value;
uint64_t rep = read_uint64_t(info);
memcpy(&value, &rep, sizeof(double));
return value;
}
/* Note regarding the following: unlike with writing the sizeof check will be
* impossible to optimize away, since it depends on the input; however, the
* truncation check may be optimized away in the case where the read data size
* equals the native one, so reading data written on the same machine should be
* reasonably quick. Doing a (rather rudimentary) benchmark this did not have
* any measurable impact on performance. */
static int
read_int(Info *info) {
int value;
if (info->u.upi.sizeof_int == sizeof(int16_t)) {
int16_t pvalue = read_int16_t(info);
value = (int)pvalue;
if ((int32_t)value != pvalue) {
eris_error(info, ERIS_ERR_TRUNC_INT);
}
}
else if (info->u.upi.sizeof_int == sizeof(int32_t)) {
int32_t pvalue = read_int32_t(info);
value = (int)pvalue;
if ((int32_t)value != pvalue) {
eris_error(info, ERIS_ERR_TRUNC_INT);
}
}
else if (info->u.upi.sizeof_int == sizeof(int64_t)) {
int64_t pvalue = read_int64_t(info);
value = (int)pvalue;
if ((int64_t)value != pvalue) {
eris_error(info, ERIS_ERR_TRUNC_INT);
}
}
else {
eris_error(info, ERIS_ERR_TYPE_INT);
value = 0; /* not reached */
}
return value;
}
static size_t
read_size_t(Info *info) {
size_t value;
if (info->u.upi.sizeof_size_t == sizeof(uint16_t)) {
uint16_t pvalue = read_uint16_t(info);
value = (size_t)pvalue;
if ((uint32_t)value != pvalue) {
eris_error(info, ERIS_ERR_TRUNC_SIZE);
}
}
else if (info->u.upi.sizeof_size_t == sizeof(uint32_t)) {
uint32_t pvalue = read_uint32_t(info);
value = (size_t)pvalue;
if ((uint32_t)value != pvalue) {
eris_error(info, ERIS_ERR_TRUNC_SIZE);
}
}
else if (info->u.upi.sizeof_size_t == sizeof(uint64_t)) {
uint64_t pvalue = read_uint64_t(info);
value = (size_t)pvalue;
if ((uint64_t)value != pvalue) {
eris_error(info, ERIS_ERR_TRUNC_SIZE);
}
}
else {
eris_error(info, ERIS_ERR_TYPE_SIZE);
value = 0; /* not reached */
}
return value;
}
static lua_Number
read_lua_Number(Info *info) {
return lua_Number::frombits(read_int32_t(info));
}
static Instruction
read_Instruction(Info *info) {
return (Instruction)read_uint32_t(info);
}
/** ======================================================================== */
/* Forward declarations for recursively called top-level functions. */
static void persist_keyed(Info*, int type);
static void persist(Info*);
static void unpersist(Info*);
/*
** ============================================================================
** Simple types.
** ============================================================================
*/
static void
p_boolean(Info *info) { /* ... bool */
WRITE_VALUE(lua_toboolean(info->L, -1), uint8_t);
}
static void
u_boolean(Info *info) { /* ... */
eris_checkstack(info->L, 1);
lua_pushboolean(info->L, READ_VALUE(uint8_t)); /* ... bool */
eris_assert(lua_type(info->L, -1) == LUA_TBOOLEAN);
}
/** ======================================================================== */
static void
p_pointer(Info *info) { /* ... ludata */
WRITE_VALUE((size_t)lua_touserdata(info->L, -1), size_t);
}
static void
u_pointer(Info *info) { /* ... */
eris_checkstack(info->L, 1);
lua_pushlightuserdata(info->L, (void*)READ_VALUE(size_t)); /* ... ludata */
eris_assert(lua_type(info->L, -1) == LUA_TLIGHTUSERDATA);
}
/** ======================================================================== */
static void
p_number(Info *info) { /* ... num */
WRITE_VALUE(lua_tonumber(info->L, -1), lua_Number);
}
static void
u_number(Info *info) { /* ... */
eris_checkstack(info->L, 1);
lua_pushnumber(info->L, READ_VALUE(lua_Number)); /* ... num */
eris_assert(lua_type(info->L, -1) == LUA_TNUMBER);
}
/** ======================================================================== */
static void
p_string(Info *info) { /* ... str */
size_t length;
const char *value = lua_tolstring(info->L, -1, &length);
WRITE_VALUE(length, size_t);
WRITE_RAW(value, length);
}
static void
u_string(Info *info) { /* ... */
eris_checkstack(info->L, 2);
{
/* TODO Can we avoid this copy somehow? (Without it getting too nasty) */
const size_t length = READ_VALUE(size_t);
char *value = (char*)lua_newuserdata(info->L, length * sizeof(char)); /* ... tmp */
READ_RAW(value, length);
lua_pushlstring(info->L, value, length); /* ... tmp str */
lua_replace(info->L, -2); /* ... str */
}
registerobject(info);
eris_assert(lua_type(info->L, -1) == LUA_TSTRING);
}
/*
** ============================================================================
** Tables and userdata.
** ============================================================================
*/
static void
p_metatable(Info *info) { /* ... obj */
eris_checkstack(info->L, 1);
pushpath(info, "@metatable");
if (!lua_getmetatable(info->L, -1)) { /* ... obj mt? */
lua_pushnil(info->L); /* ... obj nil */
} /* ... obj mt/nil */
persist(info); /* ... obj mt/nil */
lua_pop(info->L, 1); /* ... obj */
poppath(info);
}
static void
u_metatable(Info *info) { /* ... tbl */
eris_checkstack(info->L, 1);
pushpath(info, "@metatable");
unpersist(info); /* ... tbl mt/nil? */
if (lua_istable(info->L, -1)) { /* ... tbl mt */
lua_setmetatable(info->L, -2); /* ... tbl */
}
else if (lua_isnil(info->L, -1)) { /* ... tbl nil */
lua_pop(info->L, 1); /* ... tbl */
}
else { /* tbl :( */
eris_error(info, ERIS_ERR_METATABLE);
}
poppath(info);
}
/** ======================================================================== */
static void
p_literaltable(Info *info) { /* ... tbl */
eris_checkstack(info->L, 3);
/* Persist all key / value pairs. */
lua_pushnil(info->L); /* ... tbl nil */
while (lua_next(info->L, -2)) { /* ... tbl k v */
lua_pushvalue(info->L, -2); /* ... tbl k v k */
if (info->generatePath) {
if (lua_type(info->L, -1) == LUA_TSTRING) {
const char *key = lua_tostring(info->L, -1);
pushpath(info, ".%s", key);
}
else {
const char *key = luaL_tolstring(info->L, -1, NULL);
pushpath(info, "[%s]", key);
lua_pop(info->L, 1);
}
}
persist(info); /* ... tbl k v k */
lua_pop(info->L, 1); /* ... tbl k v */
persist(info); /* ... tbl k v */
lua_pop(info->L, 1); /* ... tbl k */
poppath(info);
} /* ... tbl */
/* Terminate list. */
lua_pushnil(info->L); /* ... tbl nil */
persist(info); /* ... tbl nil */
lua_pop(info->L, 1); /* ... tbl */
p_metatable(info);
}
static void
u_literaltable(Info *info) { /* ... */
eris_checkstack(info->L, 3);
lua_newtable(info->L); /* ... tbl */
/* Preregister table for handling of cycles (keys, values or metatable). */
registerobject(info);
/* Unpersist all key / value pairs. */
for (;;) {
pushpath(info, "@key");
unpersist(info); /* ... tbl key/nil */
poppath(info);
if (lua_isnil(info->L, -1)) { /* ... tbl nil */
lua_pop(info->L, 1); /* ... tbl */
break;
} /* ... tbl key */
if (info->generatePath) {
if (lua_type(info->L, -1) == LUA_TSTRING) {
const char *key = lua_tostring(info->L, -1);
pushpath(info, ".%s", key);
}
else {
const char *key = luaL_tolstring(info->L, -1, NULL);
pushpath(info, "[%s]", key);
lua_pop(info->L, 1);
}
}
unpersist(info); /* ... tbl key value? */
if (!lua_isnil(info->L, -1)) { /* ... tbl key value */
lua_rawset(info->L, -3); /* ... tbl */
}
else {
eris_error(info, ERIS_ERR_TABLE);
}
poppath(info);
}
u_metatable(info); /* ... tbl */
}
/** ======================================================================== */
static void
p_literaluserdata(Info *info) { /* ... udata */
const size_t size = lua_rawlen(info->L, -1);
const void *value = lua_touserdata(info->L, -1);
WRITE_VALUE(size, size_t);
WRITE_RAW(value, size);
p_metatable(info); /* ... udata */
}
static void
u_literaluserdata(Info *info) { /* ... */
eris_checkstack(info->L, 1);
{
size_t size = READ_VALUE(size_t);
void *value = lua_newuserdata(info->L, size); /* ... udata */
READ_RAW(value, size); /* ... udata */
}
registerobject(info);
u_metatable(info);
}
/** ======================================================================== */
typedef void (*Callback) (Info*);
static void
p_special(Info *info, Callback literal) { /* ... obj */
int allow = (lua_type(info->L, -1) == LUA_TTABLE);
eris_checkstack(info->L, 4);
/* Check whether we should persist literally, or via the metafunction. */
if (lua_getmetatable(info->L, -1)) { /* ... obj mt */
lua_pushstring(info->L, info->u.pi.metafield); /* ... obj mt pkey */
lua_rawget(info->L, -2); /* ... obj mt persist? */
switch (lua_type(info->L, -1)) {
/* No entry, act according to default. */
case LUA_TNIL: /* ... obj mt nil */
lua_pop(info->L, 2); /* ... obj */
break;
/* Boolean value, tells us whether allowed or not. */
case LUA_TBOOLEAN: /* ... obj mt bool */
allow = lua_toboolean(info->L, -1);
lua_pop(info->L, 2); /* ... obj */
break;
/* Function value, call it and don't persist literally. */
case LUA_TFUNCTION: /* ... obj mt func */
lua_replace(info->L, -2); /* ... obj func */
lua_pushvalue(info->L, -2); /* ... obj func obj */
if (info->passIOToPersist) {
lua_pushlightuserdata(info->L, (void*)info->u.pi.writer);
/* ... obj func obj writer */