fix default options
[awesomized/ext-ion] / ion_private.h
1 /*
2 +--------------------------------------------------------------------+
3 | PECL :: ion |
4 +--------------------------------------------------------------------+
5 | Redistribution and use in source and binary forms, with or without |
6 | modification, are permitted provided that the conditions mentioned |
7 | in the accompanying LICENSE file are met. |
8 +--------------------------------------------------------------------+
9 | Copyright (c) 2021, Michael Wallner <mike@php.net> |
10 +--------------------------------------------------------------------+
11 */
12
13 #include "php.h"
14 #include "ext/date/php_date.h"
15
16 #define DECNUMDIGITS 34 /* DECQUAD_Pmax */
17 #include "ionc/ion.h"
18
19 #define PHP_ION_SYMBOL_TABLE_VERSION 1
20 #define PHP_ION_SYMBOL(e, s) {0, {sizeof(e)-1, (BYTE *) e}, {sizeof(s)-1, (BYTE *) s}},
21
22 typedef struct php_ion_global_symbol {
23 SID id;
24 ION_STRING e;
25 ION_STRING s;
26 } php_ion_global_symbol;
27
28 static php_ion_global_symbol g_sym_tab_php_sym[] = {
29 PHP_ION_SYMBOL("PHP", "PHP")
30 PHP_ION_SYMBOL("Reference", "R")
31 PHP_ION_SYMBOL("Backref", "r")
32 PHP_ION_SYMBOL("Property", "p")
33 PHP_ION_SYMBOL("ClassObject", "c")
34 PHP_ION_SYMBOL("CustomObject", "C")
35 PHP_ION_SYMBOL("Object", "o")
36 PHP_ION_SYMBOL("MagicObject", "O")
37 PHP_ION_SYMBOL("Serializable", "S")
38 PHP_ION_SYMBOL("Enum", "E")
39 {0}
40 };
41 #undef PHP_ION_SYMBOL
42
43 static ION_SYMBOL_TABLE *g_sym_tab_php;
44
45 /* [SID => STRING, STRING => SID] */
46 static HashTable g_sym_hash;
47 /* [enum_case_name => SID] */
48 static HashTable g_sym_map;
49
50 #define ION_SYS_SYMBOL_SYMBOL_TABLE \
51 ION_SYS_SYMBOL_ION_SYMBOL_TABLE
52 #define g_sym_add(enum_name, c_name) do { \
53 g_sym_hash_add(ION_SYS_SID_ ## c_name, ION_SYS_SYMBOL_ ## c_name, ION_SYS_STRLEN_ ## c_name); \
54 g_sym_map_add(ION_SYS_SID_ ## c_name, enum_name, sizeof(enum_name)-1); \
55 } while (0)
56
57 static inline void g_sym_hash_add(int sid, const char *str, size_t len)
58 {
59 zval zl, zs;
60 ZVAL_LONG(&zl, sid);
61 ZVAL_STR(&zs, zend_string_init_interned(str, len ,1));
62 zend_hash_add(&g_sym_hash, Z_STR(zs), &zl);
63 zend_hash_index_add(&g_sym_hash, sid, &zs);
64 }
65
66 static inline void g_sym_map_add(int sid, const char *str, size_t len)
67 {
68 zval zv;
69 ZVAL_LONG(&zv, sid);
70 zend_hash_str_add(&g_sym_map, str, len, &zv);
71 }
72
73 static inline int g_sym_init(void)
74 {
75 zend_hash_init(&g_sym_hash, 0, NULL, NULL, 1);
76 zend_hash_init(&g_sym_map, 0, NULL, NULL, 1);
77
78 g_sym_hash_add(0, ZEND_STRL(""));
79 g_sym_map_add(0, ZEND_STRL(""));
80 g_sym_add("Ion", ION);
81 g_sym_add("Ivm_1_0", IVM);
82 g_sym_add("IonSymbolTable", SYMBOL_TABLE);
83 g_sym_add("Name", NAME);
84 g_sym_add("Version", VERSION);
85 g_sym_add("Imports", IMPORTS);
86 g_sym_add("Symbols", SYMBOLS);
87 g_sym_add("MaxId", MAX_ID);
88 g_sym_add("SharedSymbolTable", SHARED_SYMBOL_TABLE);
89
90 int sys_max_id = ION_SYS_SID_SHARED_SYMBOL_TABLE;
91
92 if (IERR_OK != ion_symbol_table_open_with_type(&g_sym_tab_php, NULL, ist_SHARED)) {
93 return FAILURE;
94 }
95 php_ion_global_symbol *ptr = g_sym_tab_php_sym;
96 ion_symbol_table_set_version(g_sym_tab_php, PHP_ION_SYMBOL_TABLE_VERSION);
97 ion_symbol_table_set_name(g_sym_tab_php, &ptr->s);
98 while (ptr->e.value) {
99 ion_symbol_table_add_symbol(g_sym_tab_php, &ptr->s, &ptr->id);
100 g_sym_hash_add(sys_max_id + ptr->id, (const char *) ptr->s.value, ptr->s.length);
101 g_sym_map_add(sys_max_id + ptr->id, (const char *) ptr->e.value, ptr->e.length);
102 ++ptr;
103 }
104 ion_symbol_table_lock(g_sym_tab_php);
105 return SUCCESS;
106 }
107
108 typedef struct php_ion_serializer {
109 ION_WRITER *writer;
110 ION_WRITER_OPTIONS *options;
111 smart_str *buffer;
112
113 zend_string *call_custom;
114 zend_bool call_magic;
115 zend_bool multi_seq;
116
117 uint32_t level;
118 HashTable *ids;
119 HashTable *tmp;
120 } php_ion_serializer;
121
122 typedef struct php_ion_annotaions {
123 uint8_t backref:1;
124 uint8_t makeref:1;
125 uint8_t object_prop:1;
126 uint8_t object_type;
127 zend_string *object_class;
128 zend_string *property_class;
129 } php_ion_annotations;
130
131 typedef struct php_ion_unserializer {
132 ION_READER *reader;
133 ION_READER_OPTIONS *options;
134 ION_TYPE type;
135
136 zend_string *call_custom;
137 zend_bool call_magic;
138 zend_bool multi_seq;
139
140 uint32_t level;
141 HashTable *ids;
142 HashTable *tmp;
143 HashTable *addref;
144
145 php_ion_annotations annotations;
146 } php_ion_unserializer;
147
148 ZEND_BEGIN_MODULE_GLOBALS(ion)
149
150 struct {
151 decContext ctx;
152 ION_DECIMAL zend_max;
153 ION_DECIMAL zend_min;
154 } decimal;
155
156 struct {
157 HashTable cache;
158 } symbol;
159
160 php_ion_serializer serializer;
161 php_ion_unserializer unserializer;
162
163 struct {
164 HashTable serializer[2];
165 HashTable unserializer[3];
166 } _ht;
167
168 ZEND_END_MODULE_GLOBALS(ion);
169
170 #ifdef ZTS
171 # define php_ion_globals (*((zend_ion_globals *) (*((void ***) tsrm_get_ls_cache()))[TSRM_UNSHUFFLE_RSRC_ID(ion_globals_id)]))
172 #else
173 # define php_ion_globals ion_globals
174 #endif
175
176 ZEND_DECLARE_MODULE_GLOBALS(ion);
177
178 static zend_class_entry
179 *ce_Catalog,
180 *ce_Collection,
181 *ce_Decimal,
182 *ce_Decimal_Context,
183 *ce_Decimal_Context_Rounding,
184 *ce_LOB,
185 *ce_Reader,
186 *ce_Reader_Options,
187 *ce_Reader_Reader,
188 *ce_Reader_Buffer,
189 *ce_Reader_Stream,
190 *ce_Reader_Buffer_Reader,
191 *ce_Reader_Stream_Reader,
192 *ce_Serializer,
193 *ce_Serializer_PHP,
194 *ce_Symbol,
195 *ce_Symbol_ImportLocation,
196 *ce_Symbol_Enum,
197 *ce_Symbol_Table,
198 *ce_Symbol_Table_Local,
199 *ce_Symbol_Table_PHP,
200 *ce_Symbol_Table_Shared,
201 *ce_Symbol_Table_System,
202 *ce_Timestamp,
203 *ce_Timestamp_Precision,
204 *ce_Type,
205 *ce_Unserializer,
206 *ce_Unserializer_PHP,
207 *ce_Writer,
208 *ce_Writer_Options,
209 *ce_Writer_Buffer,
210 *ce_Writer_Buffer_Writer,
211 *ce_Writer_Stream,
212 *ce_Writer_Stream_Writer,
213 *ce_Writer_Writer
214 ;
215
216 static inline void php_ion_globals_symbols_init(void)
217 {
218 zend_hash_init(&php_ion_globals.symbol.cache, 0, NULL, ZVAL_PTR_DTOR, 0);
219 }
220
221 static inline void php_ion_globals_symbols_dtor(void)
222 {
223 zend_hash_destroy(&php_ion_globals.symbol.cache);
224 }
225
226 static inline void php_ion_globals_serializer_init(void)
227 {
228 php_ion_serializer *s = &php_ion_globals.serializer;
229 HashTable *h = php_ion_globals._ht.serializer;
230
231 zend_hash_init(s->tmp = &h[0], 0, NULL, ZVAL_PTR_DTOR, 0);
232 zend_hash_init(s->ids = &h[1], 0, NULL, NULL, 0);
233 }
234
235 static inline uint32_t php_ion_globals_serializer_step(void)
236 {
237 php_ion_serializer *s = &php_ion_globals.serializer;
238 uint32_t level;
239
240 if (!(level = s->level++)) {
241 zend_hash_clean(s->ids);
242 zend_hash_clean(s->tmp);
243 }
244 return level;
245 }
246
247 static inline uint32_t php_ion_globals_serializer_exit(void)
248 {
249 php_ion_serializer *s = &php_ion_globals.serializer;
250
251 ZEND_ASSERT(s->level);
252 if (!--s->level) {
253 zend_hash_clean(s->ids);
254 zend_hash_clean(s->tmp);
255 }
256 return s->level;
257 }
258
259 static inline void php_ion_globals_serializer_dtor(void)
260 {
261 php_ion_serializer *s = &php_ion_globals.serializer;
262
263 zend_hash_destroy(s->tmp);
264 zend_hash_destroy(s->ids);
265 }
266
267 void ZVAL_ADDREF(zval *zv)
268 {
269 if (Z_ISREF_P(zv)) {
270 Z_TRY_ADDREF_P(Z_REFVAL_P(zv));
271 } else {
272 Z_TRY_ADDREF_P(zv);
273 }
274 }
275 static inline void php_ion_globals_unserializer_init(void)
276 {
277 php_ion_unserializer *s = &php_ion_globals.unserializer;
278 HashTable *h = php_ion_globals._ht.unserializer;
279
280 zend_hash_init(s->tmp = &h[0], 0, NULL, ZVAL_PTR_DTOR, 0);
281 zend_hash_init(s->ids = &h[1], 0, NULL, NULL, 0);
282 zend_hash_init(s->addref = &h[2], 0, NULL, ZVAL_ADDREF, 0);
283 }
284
285 static inline void php_ion_globals_unserializer_step(void)
286 {
287 php_ion_unserializer *s = &php_ion_globals.unserializer;
288
289 if (!s->level++) {
290 zend_hash_clean(s->addref);
291 zend_hash_clean(s->ids);
292 zend_hash_clean(s->tmp);
293 }
294 }
295
296 static inline void php_ion_globals_unserializer_exit(void)
297 {
298 php_ion_unserializer *s = &php_ion_globals.unserializer;
299
300 ZEND_ASSERT(s->level);
301 if (!--s->level) {
302 zend_hash_clean(s->addref);
303 zend_hash_clean(s->ids);
304 zend_hash_clean(s->tmp);
305 }
306 }
307
308 static inline void php_ion_globals_unserializer_dtor(void)
309 {
310 php_ion_unserializer *s = &php_ion_globals.unserializer;
311
312 zend_hash_destroy(s->addref);
313 zend_hash_destroy(s->ids);
314 zend_hash_destroy(s->tmp);
315 }
316
317 #define php_ion_decl(type, cname, ...) \
318 static zend_object_handlers oh_ ## cname; \
319 static inline zend_object *create_ion_ ## cname(zend_class_entry *ce) \
320 { \
321 if (!ce) ce = ce_ ## cname; \
322 php_ion_ ## type *o = ecalloc(1, sizeof(*o) + zend_object_properties_size(ce)); \
323 zend_object_std_init(&o->std, ce); \
324 object_properties_init(&o->std, ce); \
325 o->std.handlers = &oh_ ## cname; \
326 return &o->std; \
327 } \
328 static inline void free_ion_ ## cname(zend_object *std) \
329 { \
330 php_ion_ ## type *obj = php_ion_obj(type, std); \
331 __VA_ARGS__; \
332 zend_object_std_dtor(std); \
333 (void) obj; \
334 }
335 #define php_ion_register(type, cname, ...) do { \
336 ce_ ## cname = register_class_ion_ ## cname(__VA_ARGS__); \
337 ce_ ## cname ->create_object = create_ion_ ## cname; \
338 memcpy(&oh_ ## cname, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); \
339 oh_ ## cname .offset = offsetof(php_ion_ ## type, std); \
340 oh_ ## cname .free_obj = free_ion_ ## cname; \
341 } while (0)
342
343 #define php_ion_obj(type, obj) \
344 ((php_ion_ ## type *) (obj ? ((char *)(obj) - XtOffsetOf(php_ion_ ## type, std)) : NULL))
345
346 #define ION_CHECK_RETURN(r, err, ...) do { \
347 iERR __err = err; \
348 if (__err) { \
349 zend_throw_exception_ex(spl_ce_RuntimeException, __err, "%s: %s", ion_error_to_str(__err), #err); \
350 __VA_ARGS__; \
351 return r; \
352 } \
353 } while (0)
354
355 #define ION_CHECK(err, ...) \
356 ION_CHECK_RETURN(, err, __VA_ARGS__)
357
358 #define ION_CATCH(...) do { \
359 if (EG(exception)) { \
360 __VA_ARGS__; \
361 return; \
362 } \
363 } while (0)
364
365 #define PTR_CHECK(ptr, ...) do { \
366 if (!(ptr)) { \
367 zend_throw_error(NULL, "Uninitialized object"); \
368 __VA_ARGS__; \
369 return; \
370 } \
371 } while (0)
372
373 #define OBJ_CHECK(obj, ...) do { \
374 PTR_CHECK(obj, __VA_ARGS__); \
375 PTR_CHECK(*((void **)obj), __VA_ARGS__); \
376 } while (0)
377
378 static inline ION_STRING *ion_string_from_zend(ION_STRING *is, const zend_string *zs)
379 {
380 is->length = zs ? zs->len : 0;
381 is->value = (BYTE *) (zs ? zs->val : NULL);
382 return is;
383 }
384
385 static inline zend_string *zend_string_from_ion(const ION_STRING *s)
386 {
387 return zend_string_init((const char *) s->value, s->length, 0);
388 }
389
390 static inline void update_property_obj(zend_object *obj, const char *n, size_t l, zend_object *p)
391 {
392 zval zobj;
393 ZVAL_OBJ(&zobj, p);
394 zend_update_property(obj->ce, obj, n, l, &zobj);
395 }
396
397 typedef struct php_ion_type {
398 ION_TYPE typ;
399 zend_object std;
400 } php_ion_type;
401
402 php_ion_decl(type, Type);
403
404 #define RETURN_IONTYPE(typ) do { \
405 zend_object *__zo = php_ion_type_fetch(typ); \
406 if (UNEXPECTED(!__zo)) { \
407 RETURN_THROWS(); \
408 } \
409 RETURN_OBJ_COPY(__zo); \
410 } while(0)
411
412 static inline zend_object *php_ion_type_fetch(ION_TYPE typ)
413 {
414 zend_long index = ION_TYPE_INT(typ);
415 zval *ztype = zend_hash_index_find(ce_Type->backed_enum_table, index);
416
417 if (UNEXPECTED(!ztype || Z_TYPE_P(ztype) != IS_STRING)) {
418 zend_value_error(ZEND_LONG_FMT " is not a valid backing value for enum \"%s\"", index, ZSTR_VAL(ce_Type->name));
419 return NULL;
420 }
421 return zend_enum_get_case(ce_Type, Z_STR_P(ztype));
422 }
423
424 typedef struct php_ion_symbol_iloc {
425 ION_SYMBOL_IMPORT_LOCATION loc;
426 zend_string *name;
427 zend_object std;
428 } php_ion_symbol_iloc;
429
430 static inline void php_ion_symbol_iloc_ctor(php_ion_symbol_iloc *obj)
431 {
432 zend_update_property_long(obj->std.ce, &obj->std, ZEND_STRL("location"), obj->loc.location);
433 zend_update_property_str(obj->std.ce, &obj->std, ZEND_STRL("name"), obj->name);
434 ion_string_from_zend(&obj->loc.name, obj->name);
435 }
436
437 static inline void php_ion_symbol_iloc_dtor(php_ion_symbol_iloc *obj)
438 {
439 zend_string_release(obj->name);
440 }
441
442 php_ion_decl(symbol_iloc, Symbol_ImportLocation, php_ion_symbol_iloc_dtor(obj));
443
444 typedef struct php_ion_symbol {
445 ION_SYMBOL sym;
446 zend_string *value;
447 zend_object *iloc, std;
448 } php_ion_symbol;
449
450 static inline int php_ion_symbol_zval_compare(zval *zv1, zval *zv2) {
451 zend_string *zs1 = zval_get_string(zv1);
452 zend_string *zs2 = zval_get_string(zv2);
453
454 if (EG(exception)) {
455 return 0;
456 }
457
458 int result;
459 if (zs1->len > zs2->len) {
460 result = 1;
461 } else if (zs2->len > zs1->len) {
462 result = -1;
463 } else {
464 result = memcmp(zs1->val, zs2->val, zs1->len);
465 }
466 zend_string_release(zs1);
467 zend_string_release(zs2);
468 return result;
469 }
470
471 static inline void php_ion_symbol_ctor(php_ion_symbol *obj)
472 {
473 zend_update_property_long(obj->std.ce, &obj->std, ZEND_STRL("sid"),
474 obj->sym.sid);
475 if (obj->value) {
476 zend_update_property_str(obj->std.ce, &obj->std, ZEND_STRL("value"), obj->value);
477 } else{
478 zend_update_property_null(obj->std.ce, &obj->std, ZEND_STRL("value"));
479 }
480 ion_string_from_zend(&obj->sym.value, obj->value);
481 if (obj->iloc) {
482 update_property_obj(&obj->std, ZEND_STRL("importLocation"), obj->iloc);
483 obj->sym.import_location = php_ion_obj(symbol_iloc, obj->iloc)->loc;
484 } else {
485 zend_update_property_null(obj->std.ce, &obj->std, ZEND_STRL("importLocation"));
486 }
487 }
488
489 static inline void php_ion_symbol_dtor(php_ion_symbol *obj)
490 {
491 if (obj->value) {
492 zend_string_release(obj->value);
493 }
494 }
495
496 static inline void php_ion_symbol_zval(ION_SYMBOL *sym_ptr, zval *return_value)
497 {
498 object_init_ex(return_value, ce_Symbol);
499 php_ion_symbol *sym = php_ion_obj(symbol, Z_OBJ_P(return_value));
500
501 sym->sym.sid = sym_ptr->sid;
502 sym->value = zend_string_from_ion(&sym_ptr->value);
503 if (!ION_SYMBOL_IMPORT_LOCATION_IS_NULL(sym_ptr)) {
504 zval ziloc;
505 object_init_ex(&ziloc, ce_Symbol_ImportLocation);
506 sym->iloc = Z_OBJ(ziloc);
507
508 php_ion_symbol_iloc *iloc = php_ion_obj(symbol_iloc, sym->iloc);
509 iloc->loc.location = sym_ptr->import_location.location;
510 iloc->name = zend_string_from_ion(&sym_ptr->import_location.name);
511
512 php_ion_symbol_iloc_ctor(iloc);
513 }
514
515 php_ion_symbol_ctor(sym);
516
517 if (!ION_SYMBOL_IMPORT_LOCATION_IS_NULL(sym_ptr)) {
518 GC_DELREF(sym->iloc);
519 }
520 }
521
522 php_ion_decl(symbol, Symbol, php_ion_symbol_dtor(obj));
523
524 typedef struct php_ion_symbol_table {
525 ION_SYMBOL_TABLE *tab;
526 int (*dtor)(ION_SYMBOL_TABLE *);
527 zend_object std;
528 } php_ion_symbol_table;
529
530 static inline void php_ion_symbol_table_ctor(php_ion_symbol_table *obj)
531 {
532 OBJ_CHECK(obj);
533
534 ION_STRING is;
535 if (IERR_OK == ion_symbol_table_get_name(obj->tab, &is)) {
536 zend_update_property_stringl(obj->std.ce, &obj->std, ZEND_STRL("name"), (char *) is.value, is.length);
537 }
538 int32_t iv;
539 if (IERR_OK == ion_symbol_table_get_version(obj->tab, &iv)) {
540 zend_update_property_long(obj->std.ce, &obj->std, ZEND_STRL("version"), iv);
541 }
542 }
543
544 static inline void php_ion_symbol_table_dtor(php_ion_symbol_table *obj)
545 {
546 if (obj->tab) {
547 if (obj->dtor) {
548 obj->dtor(obj->tab);
549 }
550 obj->tab = NULL;
551 }
552 }
553
554 static inline void php_ion_symbol_table_import(php_ion_symbol_table *obj, php_ion_symbol_table *import)
555 {
556 OBJ_CHECK(obj);
557 OBJ_CHECK(import);
558
559 zval tmp;
560 zval *zimports = zend_read_property(obj->std.ce, &obj->std, ZEND_STRL("imports"), 0, &tmp);
561 if (zimports) {
562 zend_ulong idx = (uintptr_t) &import->std.gc;
563 if (!zend_hash_index_exists(Z_ARRVAL_P(zimports), idx)) {
564 ION_CHECK(ion_symbol_table_import_symbol_table(obj->tab, import->tab));
565
566 SEPARATE_ARRAY(zimports);
567 GC_ADDREF(&import->std);
568 add_index_object(zimports, idx, &import->std);
569 zend_update_property(obj->std.ce, &obj->std, ZEND_STRL("imports"), zimports);
570 }
571 }
572 }
573
574 static inline void php_ion_symbol_table_symbol_zval(php_ion_symbol_table *obj, ION_SYMBOL *sym, zval *return_value)
575 {
576 zval tmp;
577 zval *zsyms = zend_read_property(obj->std.ce, &obj->std, ZEND_STRL("symbols"), 0, &tmp);
578 if (zsyms) {
579 zval *zsym = zend_hash_index_find(Z_ARRVAL_P(zsyms), sym->sid);
580 if (zsym) {
581 RETURN_COPY(zsym);
582 }
583 }
584
585 php_ion_symbol_zval(sym, return_value);
586
587 if (zsyms) {
588 SEPARATE_ARRAY(zsyms);
589 ZVAL_ADDREF(return_value);
590 add_index_zval(zsyms, sym->sid, return_value);
591 }
592 }
593
594 php_ion_decl(symbol_table, Symbol_Table, php_ion_symbol_table_dtor(obj));
595
596 typedef struct php_ion_decimal_ctx {
597 decContext ctx;
598 zend_object std;
599 } php_ion_decimal_ctx;
600
601 #define php_ion_decimal_ctx_init_max(c, rounding) \
602 php_ion_decimal_ctx_init((c), DEC_MAX_DIGITS, DEC_MAX_EMAX, DEC_MIN_EMIN, (rounding), false)
603 static inline void php_ion_decimal_ctx_init(decContext *ctx,
604 zend_long digits, zend_long emax, zend_long emin, zend_long round, zend_bool clamp)
605 {
606 memset(ctx, 0, sizeof(*ctx));
607 ctx->digits = digits;
608 ctx->emax = emax;
609 ctx->emin = emin;
610 ctx->round = round;
611 ctx->clamp = clamp;
612 }
613
614 static inline void php_ion_decimal_ctx_ctor(php_ion_decimal_ctx *obj, zend_object *o_round)
615 {
616 if (!obj->ctx.digits) {
617 php_ion_decimal_ctx_init_max(&obj->ctx, DEC_ROUND_HALF_EVEN);
618 }
619 if (o_round) {
620 update_property_obj(&obj->std, ZEND_STRL("round"), o_round);
621 } else {
622 zend_update_property_long(obj->std.ce, &obj->std, ZEND_STRL("round"), obj->ctx.round);
623 }
624 zend_update_property_long(obj->std.ce, &obj->std, ZEND_STRL("digits"), obj->ctx.digits);
625 zend_update_property_long(obj->std.ce, &obj->std, ZEND_STRL("eMax"), obj->ctx.emax);
626 zend_update_property_long(obj->std.ce, &obj->std, ZEND_STRL("eMin"), obj->ctx.emin);
627 zend_update_property_bool(obj->std.ce, &obj->std, ZEND_STRL("clamp"), obj->ctx.clamp);
628 }
629
630 php_ion_decl(decimal_ctx, Decimal_Context);
631
632 typedef struct php_ion_decimal {
633 ION_DECIMAL dec;
634 zend_object *ctx, std;
635 } php_ion_decimal;
636
637 static inline void php_ion_decimal_from_zend_long(ION_DECIMAL *dec, decContext *ctx, zend_long num)
638 {
639 if (num <= INT32_MAX && num >= INT32_MIN) {
640 ION_CHECK(ion_decimal_from_int32(dec, num));
641 } else if (num > 0 && num <= UINT32_MAX) {
642 ION_CHECK(ion_decimal_from_uint32(dec, num));
643 } else {
644 ION_INT *iint;
645 ION_CHECK(ion_int_alloc(NULL, &iint));
646 ION_CHECK(ion_int_from_long(iint, num),
647 ion_int_free(iint));
648 /* WATCH OUT: BS API */
649 dec->type = ION_DECIMAL_TYPE_QUAD;
650 ION_CHECK(ion_decimal_from_ion_int(dec, ctx, iint),
651 ion_int_free(iint));
652 ion_int_free(iint);
653 }
654 }
655
656 static inline zend_string *php_ion_decimal_to_string(ION_DECIMAL *dec)
657 {
658 zend_string *zstr = zend_string_alloc(ION_DECIMAL_STRLEN(dec), 0);
659 (void) ion_decimal_to_string(dec, zstr->val);
660 return zend_string_truncate(zstr, strlen(zstr->val), 0);
661 }
662
663 static inline void php_ion_decimal_to_zend_long(ION_DECIMAL *dec, decContext *ctx, zend_long *l)
664 {
665 ION_INT *ii = NULL;
666 ION_CHECK(ion_int_alloc(NULL, &ii));
667 ION_CHECK(ion_decimal_to_ion_int(dec, ctx, ii), ion_int_free(ii));
668 int64_t i64;
669 ION_CHECK(ion_int_to_int64(ii, &i64), ion_int_free(ii));
670 *l = i64;
671 ion_int_free(ii);
672 }
673
674 static inline bool php_ion_decimal_fits_zend_long(php_ion_decimal *obj)
675 {
676 int32_t result;
677
678 if (!ion_decimal_is_integer(&obj->dec)) {
679 return false;
680 }
681
682 result = 1;
683 ion_decimal_compare(&obj->dec, &php_ion_globals.decimal.zend_max, &php_ion_globals.decimal.ctx, &result);
684 if (result == 1) {
685 return false;
686 }
687 result = -1;
688 ion_decimal_compare(&obj->dec, &php_ion_globals.decimal.zend_min, &php_ion_globals.decimal.ctx, &result);
689 if (result == -1) {
690 return false;
691 }
692 return true;
693 }
694
695 static inline void php_ion_decimal_ctor(php_ion_decimal *obj)
696 {
697 if (!obj->ctx) {
698 zval zdc;
699 object_init_ex(&zdc, ce_Decimal_Context);
700 obj->ctx = Z_OBJ(zdc);
701 php_ion_decimal_ctx_ctor(php_ion_obj(decimal_ctx, obj->ctx), NULL);
702 GC_DELREF(obj->ctx);
703 }
704 update_property_obj(&obj->std, ZEND_STRL("context"), obj->ctx);
705
706 if (php_ion_decimal_fits_zend_long(obj)) {
707 zend_long l;
708 php_ion_decimal_to_zend_long(&obj->dec, &php_ion_obj(decimal_ctx, obj->ctx)->ctx, &l);
709 zend_update_property_long(obj->std.ce, &obj->std, ZEND_STRL("number"), l);
710 } else {
711 zend_string *zstr = php_ion_decimal_to_string(&obj->dec);
712 zend_update_property_str(obj->std.ce, &obj->std, ZEND_STRL("number"), zstr);
713 zend_string_release(zstr);
714 }
715 }
716
717 static inline void php_ion_decimal_dtor(php_ion_decimal *obj)
718 {
719 ion_decimal_free(&obj->dec);
720 }
721
722 php_ion_decl(decimal, Decimal, php_ion_decimal_dtor(obj));
723
724 typedef php_date_obj php_ion_timestamp;
725
726 static inline zend_long php_usec_from_ion(const decQuad *frac, decContext *ctx)
727 {
728 if (!ctx) {
729 ctx = &php_ion_globals.decimal.ctx;
730 }
731 decQuad microsecs, result;
732 decQuadMultiply(&result, decQuadFromInt32(&microsecs, 1000000), frac, ctx);
733 return (zend_long) decQuadToUInt32(&result, ctx, DEC_ROUND_HALF_EVEN);
734 }
735
736 static inline decQuad *ion_ts_frac_from_usec(decQuad *frac, zend_long usec, decContext *ctx)
737 {
738 if (!ctx) {
739 ctx = &php_ion_globals.decimal.ctx;
740 }
741 decQuad microsecs, us;
742 return decQuadDivide(frac, decQuadFromInt32(&us, usec), decQuadFromInt32(&microsecs, 1000000), ctx);
743 }
744
745 static inline zend_string *php_dt_format_from_precision(int precision)
746 {
747 switch (precision & 0x7f) {
748 case ION_TS_FRAC:
749 return zend_string_init(ZEND_STRL("c"), 0);
750 case ION_TS_SEC:
751 return zend_string_init(ZEND_STRL("Y-m-d\\TH:i:sP"), 0);
752 case ION_TS_MIN:
753 return zend_string_init(ZEND_STRL("Y-m-d\\TH:iP"), 0);
754 case ION_TS_DAY:
755 return zend_string_init(ZEND_STRL("Y-m-d\\T"), 0);
756 case ION_TS_MONTH:
757 return zend_string_init(ZEND_STRL("Y-m\\T"), 0);
758 case ION_TS_YEAR:
759 return zend_string_init(ZEND_STRL("Y\\T"), 0);
760 default:
761 return zend_string_init(ZEND_STRL("c"), 0);
762 }
763 }
764
765 static inline timelib_time* php_time_from_ion(const ION_TIMESTAMP *ts, decContext *ctx, zend_string **fmt)
766 {
767 timelib_time *time = timelib_time_ctor();
768
769 int precision = ION_TS_FRAC;
770 ion_timestamp_get_precision(ts, &precision);
771 switch (precision) {
772 case ION_TS_FRAC:
773 time->us = php_usec_from_ion(&ts->fraction, ctx);
774 /* fallthrough */
775 case ION_TS_SEC:
776 time->s = ts->seconds;
777 /* fallthrough */
778 case ION_TS_MIN:
779 time->i = ts->minutes;
780 time->h = ts->hours;
781 /* fallthrough */
782 case ION_TS_DAY:
783 time->d = ts->day;
784 /* fallthrough */
785 case ION_TS_MONTH:
786 time->m = ts->month;
787 /* fallthrough */
788 case ION_TS_YEAR:
789 time->y = ts->year;
790 /* fallthrough */
791 default:
792 time->z = ts->tz_offset * 60;
793 if (time->z) {
794 time->zone_type = TIMELIB_ZONETYPE_OFFSET;
795 } else {
796 time->zone_type = TIMELIB_ZONETYPE_ID;
797 time->tz_info = get_timezone_info();
798 }
799 }
800
801 if (fmt) {
802 *fmt = php_dt_format_from_precision(precision);
803 }
804 return time;
805 }
806
807 static inline ION_TIMESTAMP *ion_timestamp_from_php(ION_TIMESTAMP *buf, php_ion_timestamp *ts, decContext *ctx)
808 {
809 memset(buf, 0, sizeof(*buf));
810
811 zval tmp;
812 int precision = Z_LVAL_P(zend_read_property(ts->std.ce, &ts->std, ZEND_STRL("precision"), 0, &tmp));
813
814 if (!precision || precision > ION_TS_FRAC) {
815 zend_throw_exception_ex(spl_ce_InvalidArgumentException, IERR_INVALID_ARG,
816 "Invalid precision (%d) of ion\\Timestamp", precision);
817 } else switch ((buf->precision = precision)) {
818 case ION_TS_FRAC:
819 ion_ts_frac_from_usec(&buf->fraction, ts->time->us, ctx);
820 /* fallthrough */
821 case ION_TS_SEC:
822 buf->seconds = ts->time->s;
823 /* fallthrough */
824 case ION_TS_MIN:
825 buf->minutes = ts->time->i;
826 /* fallthrough */
827 case ION_TS_DAY:
828 buf->hours = ts->time->h;
829 buf->day = ts->time->d;
830 /* fallthrough */
831 case ION_TS_MONTH:
832 buf->month = ts->time->m;
833 /* fallthrough */
834 case ION_TS_YEAR:
835 buf->year = ts->time->y;
836 /* fallthrough */
837 default:
838 buf->tz_offset = ts->time->z / 60;
839 if (buf->tz_offset) {
840 buf->precision |= 0x80;
841 }
842 }
843
844 return buf;
845 }
846
847 static inline void php_ion_timestamp_ctor(php_ion_timestamp *obj, zend_long precision, zend_string *fmt, zend_string *dt, zval *tz)
848 {
849 if (!obj->time) {
850 php_date_initialize(obj, dt ? dt->val : "", dt ? dt->len : 0, fmt ? fmt->val : NULL, tz, PHP_DATE_INIT_CTOR);
851 }
852 zend_update_property_long(obj->std.ce, &obj->std, ZEND_STRL("precision"), precision);
853
854 fmt = php_dt_format_from_precision(precision);
855 zend_update_property_str(obj->std.ce, &obj->std, ZEND_STRL("format"), fmt);
856 zend_string_release(fmt);
857 }
858
859 typedef struct php_ion_catalog {
860 ION_CATALOG *cat;
861 zend_object std;
862 } php_ion_catalog;
863
864 static inline void php_ion_catalog_ctor(php_ion_catalog *obj)
865 {
866 ION_CHECK(ion_catalog_open(&obj->cat));
867 }
868
869 static inline void php_ion_catalog_dtor(php_ion_catalog *obj)
870 {
871 if (obj->cat) {
872 ion_catalog_close(obj->cat);
873 }
874 }
875
876 static inline zend_string *ion_symbol_table_to_key(ION_SYMBOL_TABLE *tab)
877 {
878 int32_t version;
879 ION_STRING is;
880 ION_CHECK_RETURN(NULL, ion_symbol_table_get_name(tab, &is));
881 ION_CHECK_RETURN(NULL, ion_symbol_table_get_version(tab, &version));
882
883 smart_str s = {0};
884 smart_str_appendl(&s, (char *) is.value, is.length);
885 smart_str_appendc(&s, ':');
886 smart_str_append_long(&s, version);
887 smart_str_0(&s);
888
889 return s.s;
890 }
891
892 static inline void php_ion_catalog_add_symbol_table(php_ion_catalog *obj, php_ion_symbol_table *tab)
893 {
894 OBJ_CHECK(obj);
895 OBJ_CHECK(tab);
896
897 zval tmp;
898 zval *ztabs = zend_read_property(obj->std.ce, &obj->std, ZEND_STRL("symbolTables"), 0, &tmp);
899 if (ztabs) {
900 zend_ulong idx = (uintptr_t) &tab->std.gc;
901 if (!zend_hash_index_exists(Z_ARRVAL_P(ztabs), idx)) {
902 zend_string *key = ion_symbol_table_to_key(tab->tab);
903 if (key) {
904 ION_CHECK(ion_catalog_add_symbol_table(obj->cat, tab->tab),
905 zend_string_release(key));
906 SEPARATE_ARRAY(ztabs);
907 GC_ADDREF(&tab->std);
908 add_index_object(ztabs, idx, &tab->std);
909 GC_ADDREF(&tab->std);
910 add_assoc_object_ex(ztabs, key->val, key->len, &tab->std);
911 zend_update_property(obj->std.ce, &obj->std, ZEND_STRL("symbolTables"), ztabs);
912 zend_string_release(key);
913 }
914 }
915 }
916 }
917
918 static inline void php_ion_catalog_symbol_table_zval(php_ion_catalog *obj, ION_SYMBOL_TABLE *tab, zval *return_value)
919 {
920 zend_string *key = ion_symbol_table_to_key(tab);
921 PTR_CHECK(key);
922
923 zval tmp;
924 zval *ztabs = zend_read_property(obj->std.ce, &obj->std, ZEND_STRL("symbolTables"), 0, &tmp);
925 if (ztabs) {
926 zval *ztab = zend_hash_find(Z_ARRVAL_P(ztabs), key);
927 if (ztab) {
928 zend_string_release(key);
929 RETURN_COPY(ztab);
930 } else {
931 fprintf(stderr, "FAIL\n");
932 }
933 }
934
935 php_error_docref(NULL, E_NOTICE, "Previously unknown ion\\Symbol\\Table encountered: %s", key->val);
936
937 object_init_ex(return_value, ce_Symbol_Table_Shared);
938 php_ion_symbol_table *o_tab = php_ion_obj(symbol_table, Z_OBJ_P(return_value));
939 OBJ_CHECK(o_tab, zend_string_release(key));
940 php_ion_symbol_table_ctor(o_tab);
941
942 if (ztabs) {
943 SEPARATE_ARRAY(ztabs);
944 ZVAL_ADDREF(return_value);
945 add_index_zval(ztabs, (uintptr_t) &o_tab->std.gc, return_value);
946 ZVAL_ADDREF(return_value);
947 add_assoc_zval_ex(ztabs, key->val, key->len, return_value);
948 }
949 }
950
951 php_ion_decl(catalog, Catalog, php_ion_catalog_dtor(obj));
952
953 typedef struct php_ion_reader_options {
954 ION_READER_OPTIONS opt;
955 zend_object *cat, *dec_ctx, *cb, std;
956 } php_ion_reader_options;
957
958 php_ion_decl(reader_options, Reader_Options);
959
960 typedef struct php_ion_reader {
961 ION_READER *reader;
962 ION_TYPE state;
963 enum {
964 BUFFER_READER,
965 STREAM_READER,
966 } type;
967 union {
968 zend_string *buffer;
969 struct {
970 php_stream *ptr;
971 ION_STRING buf;
972 } stream;
973 };
974 zend_object *opt, std;
975 } php_ion_reader;
976
977 static inline iERR php_ion_reader_stream_handler(struct _ion_user_stream *user)
978 {
979 php_ion_reader *reader = (php_ion_reader *) user->handler_state;
980 size_t remaining = 0, spare = reader->stream.buf.length;
981
982 if (user->curr && user->limit && (remaining = user->limit - user->curr)) {
983 memmove(reader->stream.buf.value, user->curr, remaining);
984 user->limit -= remaining;
985 spare -= remaining;
986 } else {
987 user->curr = user->limit = reader->stream.buf.value;
988 }
989
990 ssize_t read = php_stream_read(reader->stream.ptr, (char *) user->limit, spare);
991 if (EXPECTED(read > 0)) {
992 user->limit += read;
993 return IERR_OK;
994 }
995
996 if (EXPECTED(read == 0)) {
997 return IERR_EOF;
998 }
999
1000 return IERR_READ_ERROR;
1001 }
1002
1003 static inline iERR on_context_change(void *context, ION_COLLECTION *imports)
1004 {
1005 if (context) {
1006 php_ion_reader *obj = php_ion_obj(reader, context);
1007 (void) obj;
1008 }
1009 return IERR_OK;
1010 }
1011
1012 static ION_READER_CONTEXT_CHANGE_NOTIFIER EMPTY_READER_CHANGE_NOTIFIER = {
1013 on_context_change,
1014 NULL
1015 };
1016
1017 static inline void php_ion_reader_ctor(php_ion_reader *obj)
1018 {
1019 iERR err;
1020 php_ion_reader_options *opt = php_ion_obj(reader_options, obj->opt);
1021
1022 if (opt) {
1023 opt->opt.context_change_notifier.context = obj;
1024 }
1025 if (obj->type == STREAM_READER) {
1026 PTR_CHECK(obj->stream.ptr);
1027 GC_ADDREF(obj->stream.ptr->res);
1028
1029 obj->stream.buf.length = opt && opt->opt.allocation_page_size ? opt->opt.allocation_page_size : 0x10000;
1030 obj->stream.buf.value = emalloc(obj->stream.buf.length);
1031 err = ion_reader_open_stream(&obj->reader, obj, php_ion_reader_stream_handler, opt ? &opt->opt : NULL);
1032
1033 } else {
1034 err = ion_reader_open_buffer(&obj->reader,
1035 (BYTE *) obj->buffer->val, obj->buffer->len,
1036 opt ? &opt->opt : NULL);
1037 }
1038 if (opt) {
1039 opt->opt.context_change_notifier.context = NULL;
1040 }
1041
1042 ION_CHECK(err);
1043 OBJ_CHECK(obj);
1044 }
1045 static inline void php_ion_reader_dtor(php_ion_reader *obj)
1046 {
1047 if (obj->reader) {
1048 ion_reader_close(obj->reader);
1049 }
1050 if (obj->type == STREAM_READER) {
1051 if (obj->stream.buf.value) {
1052 efree(obj->stream.buf.value);
1053 }
1054 if (obj->stream.ptr) {
1055 zend_list_delete(obj->stream.ptr->res);
1056 }
1057 } else {
1058 if (obj->buffer) {
1059 zend_string_release(obj->buffer);
1060 }
1061 }
1062 }
1063
1064 php_ion_decl(reader, Reader_Reader, php_ion_reader_dtor(obj));
1065
1066 typedef struct php_ion_writer_options {
1067 ION_WRITER_OPTIONS opt;
1068 zend_object *cat, *dec_ctx, *col, std;
1069 } php_ion_writer_options;
1070
1071 php_ion_decl(writer_options, Writer_Options);
1072
1073 typedef struct php_ion_writer {
1074 ION_WRITER *writer;
1075 enum {
1076 BUFFER_WRITER,
1077 STREAM_WRITER,
1078 } type;
1079 union {
1080 struct {
1081 zval val;
1082 smart_str str;
1083 } buffer;
1084 struct {
1085 ION_STRING buf;
1086 php_stream *ptr;
1087 } stream;
1088 };
1089 zend_object *opt, std;
1090
1091 } php_ion_writer;
1092
1093 static inline iERR php_ion_writer_stream_handler(struct _ion_user_stream *user)
1094 {
1095 php_ion_writer *writer = (php_ion_writer *) user->handler_state;
1096
1097 if (EXPECTED(user->limit && user->curr)) {
1098 ptrdiff_t len = user->curr - writer->stream.buf.value;
1099 if (len != php_stream_write(writer->stream.ptr, (char *) writer->stream.buf.value, len)) {
1100 return IERR_WRITE_ERROR;
1101 }
1102 }
1103 user->curr = writer->stream.buf.value;
1104 user->limit = writer->stream.buf.value + writer->stream.buf.length;
1105 return IERR_OK;
1106 }
1107
1108 #define REF_STR() do { \
1109 ZVAL_NEW_STR(ref, obj->buffer.str.s); \
1110 GC_ADDREF(obj->buffer.str.s); \
1111 } while (0)
1112
1113 #define NEW_REF_STR() do {\
1114 if (Z_STR_P(ref) != obj->buffer.str.s) { \
1115 zval_ptr_dtor(ref); \
1116 REF_STR(); \
1117 } \
1118 } while(0)
1119
1120 static inline void php_ion_writer_stream_init(php_ion_writer *obj, php_ion_writer_options *opt)
1121 {
1122 PTR_CHECK(obj->stream.ptr);
1123 GC_ADDREF(obj->stream.ptr->res);
1124
1125 obj->stream.buf.length = opt ? opt->opt.allocation_page_size : 0x1000;
1126 obj->stream.buf.value = emalloc(obj->stream.buf.length);
1127 }
1128 static inline void php_ion_writer_buffer_init(php_ion_writer *obj)
1129 {
1130 zval *ref = &obj->buffer.val;
1131 ZVAL_DEREF(ref);
1132
1133 smart_str_alloc(&obj->buffer.str, 0, 0);
1134 smart_str_0(&obj->buffer.str);
1135 REF_STR();
1136 }
1137
1138 static inline void php_ion_writer_buffer_grow(php_ion_writer *obj)
1139 {
1140 zval *ref = &obj->buffer.val;
1141 ZVAL_DEREF(ref);
1142
1143 switch (GC_REFCOUNT(obj->buffer.str.s)) {
1144 case 2:
1145 // nothing to do
1146 break;
1147 case 1:
1148 // we've been separated
1149 GC_ADDREF(obj->buffer.str.s);
1150 break;
1151 default:
1152 // we have to separate
1153 fprintf(stderr, "SEPARATE\n");
1154 obj->buffer.str.s = zend_string_dup(obj->buffer.str.s, 0);
1155 break;
1156 }
1157
1158 zend_string *old = obj->buffer.str.s;
1159 GC_DELREF(old);
1160 smart_str_erealloc(&obj->buffer.str, obj->buffer.str.a << 1);
1161 if (old == obj->buffer.str.s) {
1162 GC_ADDREF(old);
1163 } else if(old == Z_STR_P(ref)) {
1164 ZVAL_NULL(ref);
1165 }
1166
1167 NEW_REF_STR();
1168 }
1169
1170 static inline iERR php_ion_writer_buffer_handler(struct _ion_user_stream *user)
1171 {
1172 php_ion_writer *writer = (php_ion_writer *) user->handler_state;
1173
1174 if (user->curr) {
1175 writer->buffer.str.s->len += user->curr - (BYTE *) &writer->buffer.str.s->val[writer->buffer.str.s->len];
1176 smart_str_0(&writer->buffer.str);
1177 if (user->limit == user->curr) {
1178 php_ion_writer_buffer_grow(writer);
1179 }
1180 }
1181 user->curr = (BYTE *) &writer->buffer.str.s->val[writer->buffer.str.s->len];
1182 user->limit = user->curr + writer->buffer.str.a - writer->buffer.str.s->len;
1183
1184 return IERR_OK;
1185 }
1186
1187 static inline void php_ion_writer_ctor(php_ion_writer *obj)
1188 {
1189 if (obj->opt) {
1190 update_property_obj(&obj->std, ZEND_STRL("options"), obj->opt);
1191 }
1192
1193 php_ion_writer_options *opt = php_ion_obj(writer_options, obj->opt);
1194 ION_STREAM_HANDLER h;
1195 if (obj->type == STREAM_WRITER) {
1196 h = php_ion_writer_stream_handler;
1197 php_ion_writer_stream_init(obj, opt);
1198 } else {
1199 h = php_ion_writer_buffer_handler;
1200 php_ion_writer_buffer_init(obj);
1201 }
1202
1203 ION_CHECK(ion_writer_open_stream(&obj->writer, h, obj, opt ? &opt->opt : NULL));
1204 OBJ_CHECK(obj);
1205 }
1206
1207 static inline void php_ion_writer_dtor(php_ion_writer *obj)
1208 {
1209 if (obj->writer) {
1210 ion_writer_close(obj->writer);
1211 }
1212 if (obj->type == STREAM_WRITER) {
1213 if (obj->stream.buf.value) {
1214 efree(obj->stream.buf.value);
1215 }
1216 if (obj->stream.ptr) {
1217 zend_list_delete(obj->stream.ptr->res);
1218 }
1219 } else {
1220 if (obj->buffer.str.s) {
1221 smart_str_0(&obj->buffer.str);
1222 zend_string_release(obj->buffer.str.s);
1223 }
1224 zval_ptr_dtor(&obj->buffer.val);
1225 }
1226 }
1227
1228 php_ion_decl(writer, Writer_Writer, php_ion_writer_dtor(obj));
1229
1230 typedef struct php_ion_serializer_php {
1231 php_ion_serializer serializer;
1232 zend_object *opt, std;
1233 } php_ion_serializer_php;
1234
1235 static inline void php_ion_serializer_php_ctor(php_ion_serializer_php *ser_obj)
1236 {
1237 php_ion_serializer *global_ser = &php_ion_globals.serializer;
1238 ser_obj->serializer.ids = global_ser->ids;
1239 ser_obj->serializer.tmp = global_ser->tmp;
1240
1241 zend_update_property_bool(ser_obj->std.ce, &ser_obj->std, ZEND_STRL("callMagicSerialize"),
1242 ser_obj->serializer.call_magic);
1243 if (ser_obj->serializer.call_custom) {
1244 zend_update_property_str(ser_obj->std.ce, &ser_obj->std, ZEND_STRL("callCustomSerialize"),
1245 ser_obj->serializer.call_custom);
1246 ser_obj->serializer.call_custom = zend_string_tolower(ser_obj->serializer.call_custom);
1247 } else {
1248 zend_update_property_null(ser_obj->std.ce, &ser_obj->std, ZEND_STRL("callCustomSerialize"));
1249 }
1250 if (!ser_obj->opt) {
1251 ser_obj->opt = create_ion_Writer_Options(NULL);
1252 } else {
1253 GC_ADDREF(ser_obj->opt);
1254 }
1255 ser_obj->serializer.options = &php_ion_obj(writer_options, ser_obj->opt)->opt;
1256 update_property_obj(&ser_obj->std, ZEND_STRL("writerOptions"), ser_obj->opt);
1257 GC_DELREF(ser_obj->opt);
1258 }
1259
1260 static inline void php_ion_serializer_php_dtor(php_ion_serializer_php *obj)
1261 {
1262 if (obj->serializer.call_custom) {
1263 zend_string_release(obj->serializer.call_custom);
1264 }
1265 }
1266
1267 static inline void php_ion_serialize_zval(php_ion_serializer *, zval *);
1268
1269 static inline void php_ion_serialize_struct(php_ion_serializer *ser, zend_array *arr, bool props)
1270 {
1271 ION_CHECK(ion_writer_start_container(ser->writer, tid_STRUCT));
1272
1273 zval *v;
1274 zend_ulong h;
1275 zend_string *k = NULL;
1276 if (arr) ZEND_HASH_FOREACH_KEY_VAL_IND(arr, h, k, v)
1277 ION_STRING is;
1278 if (k) {
1279 size_t prop_len;
1280 const char *class_name, *prop_name;
1281 if (props && (SUCCESS == zend_unmangle_property_name_ex(k, &class_name, &prop_name, &prop_len)) && class_name) {
1282 ION_CHECK(ion_writer_add_annotation(ser->writer, ion_string_assign_cstr(&is, ZEND_STRL("p"))));
1283 ION_CHECK(ion_writer_add_annotation(ser->writer, ion_string_assign_cstr(&is, (char *) class_name, prop_name - class_name - 1)));
1284 } else {
1285 prop_name = k->val;
1286 prop_len = k->len;
1287 }
1288 ion_string_assign_cstr(&is, (char *) prop_name, prop_len);
1289 } else {
1290 char buf[MAX_LENGTH_OF_LONG + 1], *end = buf + sizeof(buf) - 1;
1291 char *ptr = zend_print_long_to_buf(end, (zend_long) h);
1292 ion_string_assign_cstr(&is, ptr, end - ptr);
1293 }
1294
1295 // WATCH OUT: field names need to be copied
1296 ION_STRING fn;
1297 ION_CHECK(ion_string_copy_to_owner(ser->writer, &fn, &is));
1298 ION_CHECK(ion_writer_write_field_name(ser->writer, &fn));
1299
1300 php_ion_serialize_zval(ser, v);
1301 ION_CATCH();
1302 ZEND_HASH_FOREACH_END();
1303
1304 ION_CHECK(ion_writer_finish_container(ser->writer));
1305 }
1306
1307 static inline void php_ion_serialize_list(php_ion_serializer *ser, zend_array *arr)
1308 {
1309 ION_CHECK(ion_writer_start_container(ser->writer, tid_LIST));
1310
1311 zval *v;
1312 ZEND_HASH_FOREACH_VAL_IND(arr, v)
1313 php_ion_serialize_zval(ser, v);
1314 ION_CATCH();
1315 ZEND_HASH_FOREACH_END();
1316
1317 ION_CHECK(ion_writer_finish_container(ser->writer));
1318 }
1319
1320 static inline void php_ion_serialize_array(php_ion_serializer *ser, zend_array *arr)
1321 {
1322 if (zend_array_is_list(arr)) {
1323 php_ion_serialize_list(ser, arr);
1324 } else {
1325 php_ion_serialize_struct(ser, arr, false);
1326 }
1327 }
1328
1329 static inline void php_ion_serialize_object_iface(php_ion_serializer *ser, zend_object *zobject)
1330 {
1331 uint8_t *buf;
1332 size_t len;
1333 zval tmp;
1334
1335 ZVAL_OBJ(&tmp, zobject);
1336 if (SUCCESS == zobject->ce->serialize(&tmp, &buf, &len, NULL)) {
1337 ION_STRING is;
1338 ION_CHECK(ion_writer_add_annotation(ser->writer, ion_string_assign_cstr(&is, ZEND_STRL("S"))));
1339 ION_CHECK(ion_writer_add_annotation(ser->writer, ion_string_from_zend(&is, zobject->ce->name)));
1340 ION_CHECK(ion_writer_write_string(ser->writer, ion_string_assign_cstr(&is, (char *) buf, len)));
1341 efree(buf);
1342 } else if (!EG(exception)){
1343 zend_throw_exception_ex(spl_ce_UnexpectedValueException, IERR_INTERNAL_ERROR,
1344 "Failed to serialize class %s", zobject->ce->name->val);
1345 }
1346 }
1347
1348 static inline void php_ion_serialize_object_magic(php_ion_serializer *ser, zend_object *zobject, zend_function *fn)
1349 {
1350 zval rv;
1351
1352 ZVAL_NULL(&rv);
1353 zend_call_known_instance_method_with_0_params(fn ? fn : zobject->ce->__serialize, zobject, &rv);
1354 ION_CATCH();
1355
1356 if (IS_ARRAY == Z_TYPE(rv)) {
1357 ION_STRING is;
1358 ION_CHECK(ion_writer_add_annotation(ser->writer, ion_string_assign_cstr(&is, fn ? "C" : "O", 1)));
1359 ION_CHECK(ion_writer_add_annotation(ser->writer, ion_string_from_zend(&is, zobject->ce->name)));
1360 php_ion_serialize_zval(ser, &rv);
1361 zval_ptr_dtor(&rv);
1362 } else {
1363 zend_throw_exception_ex(spl_ce_UnexpectedValueException, IERR_INTERNAL_ERROR,
1364 "%s serializer %s::%s did not return an array",
1365 fn ? "Custom" : "Magic", zobject->ce->name->val,
1366 fn ? fn->common.function_name->val : "__serialize");
1367 }
1368 }
1369
1370 static inline void php_ion_serialize_object_enum(php_ion_serializer *ser, zend_object *zobject)
1371 {
1372 ION_STRING is;
1373 ION_CHECK(ion_writer_add_annotation(ser->writer, ion_string_assign_cstr(&is, ZEND_STRL("E"))));
1374
1375 ION_CHECK(ion_writer_add_annotation(ser->writer, ion_string_from_zend(&is, zobject->ce->name)));
1376 zval *z_cname = zend_enum_fetch_case_name(zobject);
1377 ION_CHECK(ion_writer_write_symbol(ser->writer, ion_string_from_zend(&is, Z_STR_P(z_cname))));
1378 }
1379
1380 static inline void php_ion_serialize_object_std(php_ion_serializer *ser, zend_object *zobject)
1381 {
1382 ION_STRING is;
1383
1384 if (zobject->ce != zend_standard_class_def) {
1385 ION_CHECK(ion_writer_add_annotation(ser->writer, ion_string_assign_cstr(&is, ZEND_STRL("c"))));
1386 ION_CHECK(ion_writer_add_annotation(ser->writer, ion_string_from_zend(&is, zobject->ce->name)));
1387 } else {
1388 ION_CHECK(ion_writer_add_annotation(ser->writer, ion_string_assign_cstr(&is, ZEND_STRL("o"))));
1389 }
1390
1391 zval zobj;
1392 ZVAL_OBJ(&zobj, zobject);
1393 HashTable *props = zend_get_properties_for(&zobj, ZEND_PROP_PURPOSE_SERIALIZE);
1394 if (props) {
1395 php_ion_serialize_struct(ser, props, true);
1396 zend_release_properties(props);
1397 } else {
1398 zend_throw_exception_ex(spl_ce_UnexpectedValueException, IERR_INTERNAL_ERROR,
1399 "Could not get properties for serialization of class %s",
1400 zobject->ce->name->val);
1401 }
1402 }
1403
1404 static inline void php_ion_serialize_object_lob(php_ion_serializer *ser, zend_object *zobject)
1405 {
1406 zval tmp_type, *type = zend_read_property(NULL, zobject, ZEND_STRL("type"), 0, &tmp_type);
1407 zval tmp_value, *value = zend_read_property(NULL, zobject, ZEND_STRL("value"), 0, &tmp_value);
1408 switch (Z_LVAL_P(zend_enum_fetch_case_value(Z_OBJ_P(type)))) {
1409 case tid_BLOB_INT:
1410 ION_CHECK(ion_writer_write_blob(ser->writer, (BYTE *) Z_STRVAL_P(value), Z_STRLEN_P(value)));
1411 break;
1412 case tid_CLOB_INT:
1413 ION_CHECK(ion_writer_write_clob(ser->writer, (BYTE *) Z_STRVAL_P(value), Z_STRLEN_P(value)));
1414 break;
1415 default:
1416 zend_throw_exception_ex(spl_ce_InvalidArgumentException, IERR_INVALID_ARG,
1417 "Unsupported LOB type: ion\\Type::%s", Z_STRVAL_P(zend_enum_fetch_case_name(Z_OBJ_P(type))));
1418 break;
1419 }
1420 }
1421
1422 static inline bool can_call_magic_serialize(php_ion_serializer *ser, zend_class_entry *ce)
1423 {
1424 return ce->__serialize && ser->call_magic;
1425 }
1426
1427 static inline bool can_call_iface_serialize(php_ion_serializer *, zend_class_entry *ce)
1428 {
1429 return !!ce->serialize;
1430 }
1431
1432 static inline bool can_call_custom_serialize(php_ion_serializer *ser, zend_object *zobject, zend_function **fn)
1433 {
1434 if (ser->call_custom) {
1435 return !!(*fn = zend_hash_find_ptr(&zobject->ce->function_table, ser->call_custom));
1436 }
1437 return false;
1438 }
1439
1440 static inline void php_ion_serialize_object(php_ion_serializer *ser, zend_object *zobject)
1441 {
1442 zend_function *fn;
1443 zend_class_entry *ce = zobject->ce;
1444 ZEND_ASSERT(ce);
1445
1446 if (ce->ce_flags & ZEND_ACC_NOT_SERIALIZABLE) {
1447 zend_throw_exception_ex(spl_ce_InvalidArgumentException, IERR_INVALID_ARG,
1448 "Serializing %s is not allowed", ce->name->val);
1449 return;
1450 }
1451
1452 if (can_call_magic_serialize(ser, ce)) {
1453 php_ion_serialize_object_magic(ser, zobject, NULL);
1454 } else if (can_call_iface_serialize(ser, ce)) {
1455 php_ion_serialize_object_iface(ser, zobject);
1456 } else if (can_call_custom_serialize(ser, zobject, &fn)) {
1457 php_ion_serialize_object_magic(ser, zobject, fn);
1458 } else if (zobject->ce->ce_flags & ZEND_ACC_ENUM) {
1459 php_ion_serialize_object_enum(ser, zobject);
1460 } else if (ce == ce_Symbol) {
1461 ION_CHECK(ion_writer_write_ion_symbol(ser->writer, &php_ion_obj(symbol, zobject)->sym));
1462 } else if (ce == ce_Decimal) {
1463 ION_CHECK(ion_writer_write_ion_decimal(ser->writer, &php_ion_obj(decimal, zobject)->dec));
1464 } else if (ce == ce_Timestamp) {
1465 ION_TIMESTAMP its;
1466 php_ion_timestamp *pts = php_ion_obj(timestamp, zobject);
1467 decContext *ctx = ser->options ? ser->options->decimal_context : NULL;
1468 ION_CHECK(ion_writer_write_timestamp(ser->writer, ion_timestamp_from_php(&its, pts, ctx)));
1469 } else if (ce == ce_LOB) {
1470 php_ion_serialize_object_lob(ser, zobject);
1471 } else {
1472 php_ion_serialize_object_std(ser, zobject);
1473 }
1474 }
1475
1476 static inline void php_ion_serialize_refcounted(php_ion_serializer *ser, zval *zv)
1477 {
1478 zend_ulong idx = (zend_ulong) (uintptr_t) Z_COUNTED_P(zv);
1479
1480 ION_STRING is;
1481 if (zend_hash_index_exists(ser->ids, idx)) {
1482 zval *num = zend_hash_index_find(ser->ids, idx);
1483
1484 ION_CHECK(ion_writer_add_annotation(ser->writer, ion_string_assign_cstr(&is, ZEND_STRL("r"))));
1485 ION_CHECK(ion_writer_write_int64(ser->writer, Z_LVAL_P(num)));
1486 } else {
1487 zval num;
1488
1489 ZVAL_LONG(&num, zend_hash_num_elements(ser->ids));
1490 zend_hash_index_add(ser->ids, idx, &num);
1491
1492 Z_TRY_ADDREF_P(zv);
1493 zend_hash_next_index_insert(ser->tmp, zv);
1494
1495 switch (Z_TYPE_P(zv)) {
1496 case IS_STRING:
1497 ION_CHECK(ion_writer_write_string(ser->writer, ion_string_from_zend(&is, Z_STR_P(zv))));
1498 break;
1499
1500 case IS_ARRAY:
1501 php_ion_serialize_array(ser, Z_ARRVAL_P(zv));
1502 break;
1503
1504 case IS_OBJECT:
1505 php_ion_serialize_object(ser, Z_OBJ_P(zv));
1506 break;
1507
1508 case IS_REFERENCE:
1509 ION_CHECK(ion_writer_add_annotation(ser->writer, ion_string_assign_cstr(&is, ZEND_STRL("R"))));
1510 php_ion_serialize_zval(ser, Z_REFVAL_P(zv));
1511 break;
1512 }
1513 }
1514 }
1515
1516 static inline void php_ion_serialize_zval(php_ion_serializer *ser, zval *zv)
1517 {
1518 OBJ_CHECK(ser);
1519
1520 switch (Z_TYPE_P(zv)) {
1521 case IS_NULL:
1522 ION_CHECK(ion_writer_write_null(ser->writer));
1523 break;
1524 case IS_TRUE:
1525 ION_CHECK(ion_writer_write_bool(ser->writer, TRUE));
1526 break;
1527 case IS_FALSE:
1528 ION_CHECK(ion_writer_write_bool(ser->writer, FALSE));
1529 break;
1530 case IS_LONG:
1531 ION_CHECK(ion_writer_write_int64(ser->writer, Z_LVAL_P(zv)));
1532 break;
1533 case IS_DOUBLE:
1534 ION_CHECK(ion_writer_write_double(ser->writer, Z_DVAL_P(zv)));
1535 break;
1536 case IS_STRING:
1537 case IS_ARRAY:
1538 case IS_OBJECT:
1539 case IS_REFERENCE:
1540 php_ion_serialize_refcounted(ser, zv);
1541 break;
1542 default:
1543 zend_throw_exception_ex(spl_ce_InvalidArgumentException, IERR_INVALID_ARG,
1544 "Failed to serialize value of type %s", zend_zval_type_name(zv));
1545 }
1546 }
1547
1548 php_ion_decl(serializer_php, Serializer_PHP, php_ion_serializer_php_dtor(obj));
1549
1550 static inline void php_ion_serialize_ex(php_ion_serializer *ser, zval *zv)
1551 {
1552 HashPosition pos;
1553 HashTable *arr = NULL;
1554
1555 if (ser->multi_seq) {
1556 if (Z_TYPE_P(zv) != IS_ARRAY || !zend_array_is_list(Z_ARRVAL_P(zv))) {
1557 zend_throw_exception_ex(spl_ce_InvalidArgumentException, IERR_INVALID_ARG,
1558 "Expected a packed, consecutively numerically indexed array as argument to the multi sequence serializer");
1559 return;
1560 }
1561
1562 arr = Z_ARRVAL_P(zv);
1563
1564 zend_hash_internal_pointer_reset_ex(arr, &pos);
1565 zv = zend_hash_get_current_data_ex(arr, &pos);
1566 }
1567
1568 while (zv) {
1569 /* start off with a global PHP annotation instead of repeating it all over the place */
1570 if (0 == php_ion_globals_serializer_step()) {
1571 ION_STRING is;
1572 ION_CHECK(ion_writer_add_annotation(ser->writer, ion_string_assign_cstr(&is, ZEND_STRL("PHP"))));
1573 }
1574 php_ion_serialize_zval(ser, zv);
1575 php_ion_globals_serializer_exit();
1576
1577 if (!ser->multi_seq) {
1578 break;
1579 }
1580 zend_hash_move_forward_ex(arr, &pos);
1581 zv = zend_hash_get_current_data_ex(arr, &pos);
1582 }
1583 }
1584
1585 void php_ion_serialize(php_ion_serializer *ser, zval *zv, zval *return_value)
1586 {
1587 zend_object *zo_opt = NULL, *zo_ser = NULL;
1588
1589 if (!ser) {
1590 zo_ser = create_ion_Serializer_PHP(NULL);
1591 php_ion_serializer_php *o_ser = php_ion_obj(serializer_php, zo_ser);
1592 PTR_CHECK(o_ser);
1593 o_ser->serializer.call_magic = true;
1594 php_ion_serializer_php_ctor(o_ser);
1595 ION_CATCH();
1596 ser = &o_ser->serializer;
1597 }
1598
1599 zend_object *zo_writer = create_ion_Writer_Writer(ce_Writer_Buffer_Writer);
1600 php_ion_writer *writer = php_ion_obj(writer, zo_writer);
1601 writer->type = BUFFER_WRITER;
1602
1603 if (ser->options) {
1604 zo_opt = writer->opt = create_ion_Writer_Options(NULL);
1605 php_ion_obj(writer_options, writer->opt)->opt = *ser->options;
1606 }
1607
1608 php_ion_writer_ctor(writer);
1609 ser->writer = writer->writer;
1610 ser->buffer = &writer->buffer.str;
1611
1612 if (!EG(exception)) {
1613 php_ion_serialize_ex(ser, zv);
1614 }
1615
1616 /* make sure to flush when done, else str.s might not contain everything until the writer is closed */
1617 ion_writer_flush(ser->writer, NULL);
1618 RETVAL_STR_COPY(ser->buffer->s);
1619
1620 OBJ_RELEASE(zo_writer);
1621 if (zo_opt) {
1622 OBJ_RELEASE(zo_opt);
1623 }
1624 if (zo_ser) {
1625 OBJ_RELEASE(zo_ser);
1626 }
1627 }
1628
1629 typedef struct php_ion_unserializer_php {
1630 php_ion_unserializer unserializer;
1631 zend_object *opt, std;
1632 } php_ion_unserializer_php;
1633
1634 static inline void php_ion_unserializer_php_ctor(php_ion_unserializer_php *ser_obj)
1635 {
1636 php_ion_unserializer *global_ser = &php_ion_globals.unserializer;
1637 ser_obj->unserializer.ids = global_ser->ids;
1638 ser_obj->unserializer.tmp = global_ser->tmp;
1639 ser_obj->unserializer.addref = global_ser->addref;
1640
1641 zend_update_property_bool(ser_obj->std.ce, &ser_obj->std, ZEND_STRL("callMagicSerialize"),
1642 ser_obj->unserializer.call_magic);
1643 if (ser_obj->unserializer.call_custom) {
1644 zend_update_property_str(ser_obj->std.ce, &ser_obj->std, ZEND_STRL("callCustomSerialize"),
1645 ser_obj->unserializer.call_custom);
1646 ser_obj->unserializer.call_custom = zend_string_tolower(ser_obj->unserializer.call_custom);
1647 } else {
1648 zend_update_property_null(ser_obj->std.ce, &ser_obj->std, ZEND_STRL("callCustomSerialize"));
1649 }
1650 if (!ser_obj->opt) {
1651 ser_obj->opt = create_ion_Reader_Options(NULL);
1652 } else {
1653 GC_ADDREF(ser_obj->opt);
1654 }
1655 ser_obj->unserializer.options = &php_ion_obj(reader_options, ser_obj->opt)->opt;
1656 update_property_obj(&ser_obj->std, ZEND_STRL("readerOptions"), ser_obj->opt);
1657 GC_DELREF(ser_obj->opt);
1658 }
1659
1660 static inline void php_ion_unserializer_php_dtor(php_ion_unserializer_php *obj)
1661 {
1662 if (obj->unserializer.call_custom) {
1663 zend_string_release(obj->unserializer.call_custom);
1664 }
1665 }
1666
1667 static inline void php_ion_unserialize_zval(php_ion_unserializer *ser, zval *return_value, ION_TYPE *typ);
1668
1669 static inline bool can_call_magic_unserialize(php_ion_unserializer *ser, zend_class_entry *ce)
1670 {
1671 return (ce && ce->__unserialize && ser->call_magic);
1672 }
1673
1674 static inline bool can_call_iface_unserialize(php_ion_unserializer *ser, zend_class_entry *ce)
1675 {
1676 return (ce && ce->unserialize);
1677 }
1678
1679 static inline bool can_call_custom_unserialize(php_ion_unserializer *ser, zend_object *zobject, zend_function **fn)
1680 {
1681 if (ser->call_custom) {
1682 return !!(*fn = zend_hash_find_ptr(&zobject->ce->function_table, ser->call_custom));
1683 }
1684 return false;
1685 }
1686
1687 static inline zval *php_ion_unserialize_class(php_ion_unserializer *ser, zval *return_value)
1688 {
1689 zend_class_entry *ce = zend_lookup_class(ser->annotations.object_class);
1690
1691 if (ce) {
1692 object_init_ex(return_value, ce);
1693 return zend_hash_next_index_insert(ser->ids, return_value);
1694 }
1695
1696 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_IMPORT_NOT_FOUND,
1697 "Could not find class %s", ser->annotations.object_class->val);
1698 return NULL;
1699 }
1700
1701 static inline void php_ion_unserialize_object_enum(php_ion_unserializer *ser, zval *return_value)
1702 {
1703 zend_string *zs_case = zval_get_string(return_value);
1704 ION_CATCH();
1705
1706 zend_class_entry *ce = zend_lookup_class(ser->annotations.object_class);
1707 if (!ce || !(ce->ce_flags & ZEND_ACC_ENUM)) {
1708 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_INVALID_TOKEN,
1709 "Not a valid enum: %s", ser->annotations.object_class->val);
1710 return;
1711 }
1712 if (!zend_hash_exists(CE_CONSTANTS_TABLE(ce), zs_case)) {
1713 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_INVALID_TOKEN,
1714 "Not a valid enum case: %s::%s", ser->annotations.object_class->val, zs_case->val);
1715 return;
1716 }
1717 RETVAL_OBJ_COPY(zend_enum_get_case(ce, zs_case));
1718 zend_hash_next_index_insert(ser->ids, return_value);
1719 zend_string_release(zs_case);
1720 }
1721
1722 static inline void php_ion_unserialize_object_iface(php_ion_unserializer *ser, zval *return_value)
1723 {
1724 zend_class_entry *ce = zend_lookup_class(ser->annotations.object_class);
1725 if (can_call_iface_unserialize(ser, ce)) {
1726 zend_string *s = zval_get_string(return_value);
1727 ZVAL_NULL(return_value);
1728 zval *backref = zend_hash_next_index_insert(ser->ids, return_value);
1729 if (SUCCESS == ce->unserialize(backref, ce, (BYTE *) s->val, s->len, NULL)) {
1730 RETVAL_ZVAL(backref, 0, 0);
1731 } else if (!EG(exception)) {
1732 zend_throw_exception_ex(spl_ce_UnexpectedValueException, IERR_INTERNAL_ERROR,
1733 "Failed to unserialize class %s", ce->name->val);
1734 }
1735 zend_string_release(s);
1736 } else {
1737 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_INVALID_TOKEN,
1738 "Class %s does not implement Serializable", ser->annotations.object_class->val);
1739 }
1740 }
1741
1742 static inline void php_ion_unserialize_field_name(php_ion_unserializer *ser, zend_string **key)
1743 {
1744 // FIXME: symbol table
1745 ION_STRING name;
1746 ION_CHECK(ion_reader_get_field_name(ser->reader, &name));
1747 if (!name.length) {
1748 ION_SYMBOL *is_ptr;
1749 ION_CHECK(ion_reader_get_field_name_symbol(ser->reader, &is_ptr));
1750 if (!ION_SYMBOL_IS_NULL(is_ptr) && is_ptr->value.length) {
1751 name = is_ptr->value;
1752 } else if (is_ptr) {
1753 char buf[MAX_LENGTH_OF_LONG + 1 + 1] = {0}, *end = buf + sizeof(buf) - 1, *ptr;
1754 ptr = zend_print_long_to_buf(end, is_ptr->sid);
1755 *--ptr = '$';
1756 *key = zend_string_init(ptr, end - ptr, 0);
1757 return;
1758 }
1759 }
1760 *key = zend_string_from_ion(&name);
1761 }
1762
1763 static void php_ion_unserialize_props(php_ion_unserializer *ser, zval *return_value)
1764 {
1765 zend_hash_next_index_insert(ser->ids, return_value);
1766
1767 ION_CHECK(ion_reader_step_in(ser->reader));
1768
1769 while (true) {
1770 ION_TYPE typ;
1771 ION_CHECK(ion_reader_next(ser->reader, &typ));
1772
1773 if (typ == tid_EOF) {
1774 break;
1775 }
1776
1777 zend_string *key;
1778 php_ion_unserialize_field_name(ser, &key);
1779 ION_CATCH();
1780
1781 zval zvalue;
1782 php_ion_unserialize_zval(ser, &zvalue, &typ);
1783 ION_CATCH(zend_string_release(key));
1784
1785 zend_class_entry *ce = Z_OBJCE_P(return_value);
1786 if (ser->annotations.object_prop && ser->annotations.property_class->val[0] != '*') {
1787 ce = zend_lookup_class(ser->annotations.property_class);
1788 }
1789 zend_update_property_ex(ce, Z_OBJ_P(return_value), key, &zvalue);
1790 zval_ptr_dtor(&zvalue);
1791 zend_string_release(key);
1792 }
1793
1794 ION_CHECK(ion_reader_step_out(ser->reader));
1795 }
1796
1797 /**
1798 * @link https://amzn.github.io/ion-docs/docs/spec.html#struct
1799 * When two fields in the same struct have the same name [...] Implementations must preserve all such fields,
1800 * i.e., they may not discard fields that have repeated names. However, implementations may reorder fields
1801 * (the binary format identifies structs that are sorted by symbolID), so certain operations may lead to
1802 * nondeterministic behavior.
1803 */
1804 static inline void php_ion_unserialize_hash(php_ion_unserializer *ser, zval *return_value)
1805 {
1806 zend_hash_next_index_insert(ser->ids, return_value);
1807
1808 ION_CHECK(ion_reader_step_in(ser->reader));
1809
1810 while (true) {
1811 ION_TYPE typ;
1812 ION_CHECK(ion_reader_next(ser->reader, &typ));
1813
1814 if (typ == tid_EOF) {
1815 break;
1816 }
1817
1818 zend_string *key;
1819 php_ion_unserialize_field_name(ser, &key);
1820 ION_CATCH();
1821
1822 zval zvalue;
1823 php_ion_unserialize_zval(ser, &zvalue, &typ);
1824 ION_CATCH(zend_string_release(key));
1825
1826 // FIXME:: too naive; b0rked if the previous value is an array
1827 if (zend_symtable_exists(HASH_OF(return_value), key)) {
1828 zval tmp, *prev = zend_hash_find(HASH_OF(return_value), key);
1829 if (Z_TYPE_P(prev) != IS_ARRAY) {
1830 array_init(&tmp);
1831 Z_TRY_ADDREF_P(prev);
1832 zend_hash_next_index_insert(Z_ARRVAL(tmp), prev);
1833 prev = zend_hash_update(HASH_OF(return_value), key, &tmp);
1834 }
1835 zend_hash_next_index_insert(Z_ARRVAL_P(prev), &zvalue);
1836 } else {
1837 zend_symtable_update(HASH_OF(return_value), key, &zvalue);
1838 }
1839 zend_string_release(key);
1840 }
1841
1842 ION_CHECK(ion_reader_step_out(ser->reader));
1843 }
1844
1845 static inline void verify_unserializer(php_ion_unserializer *ser, zend_object *zobject, zend_function **fn)
1846 {
1847 switch (ser->annotations.object_type) {
1848 case 'c':
1849 *fn = NULL;
1850 break;
1851
1852 case 'C':
1853 if (!can_call_custom_unserialize(ser, zobject, fn)) {
1854 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_INVALID_TOKEN,
1855 "Could not find custom serializer method of %s", ser->annotations.object_class->val);
1856 }
1857 break;
1858
1859 case 'O':
1860 if (!can_call_magic_unserialize(ser, zobject->ce)) {
1861 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_INVALID_TOKEN,
1862 "Could not find method %s::__unserialize()", ser->annotations.object_class->val);
1863 }
1864 *fn = zobject->ce->__unserialize;
1865 break;
1866
1867 default:
1868 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_INVALID_TOKEN,
1869 "Invalid object type %c", ser->annotations.object_type);
1870 }
1871 }
1872
1873 static inline void php_ion_unserialize_object(php_ion_unserializer *ser, zval *return_value)
1874 {
1875 // backup possible backref to array returned by magic/custom __serialize()
1876 zval *input = zend_hash_next_index_insert(ser->tmp, return_value);
1877
1878 php_ion_unserialize_class(ser, return_value);
1879 ION_CATCH();
1880
1881 zend_function *fn = NULL;
1882 zend_object *zobject = Z_OBJ_P(return_value);
1883 verify_unserializer(ser, zobject, &fn);
1884 ION_CATCH();
1885
1886 // plain object
1887 if (!fn) {
1888 php_ion_unserialize_props(ser, return_value);
1889 return;
1890 }
1891
1892 // magic object
1893 if (Z_TYPE_P(input) != IS_ARRAY) {
1894 zval_ptr_dtor(input);
1895 array_init(input);
1896 zend_hash_real_init_mixed(Z_ARRVAL_P(input));
1897 php_ion_unserialize_hash(ser, input);
1898 ION_CATCH();
1899 }
1900 zval rv;
1901 ZVAL_NULL(&rv);
1902 zend_call_method_with_1_params(zobject, zobject->ce, &fn, "", &rv, input);
1903 zval_ptr_dtor(&rv);
1904 }
1905
1906 static inline void php_ion_unserialize_struct(php_ion_unserializer *ser, zval *return_value)
1907 {
1908 if (ser->annotations.object_class) {
1909 switch (ser->annotations.object_type) {
1910 case 'S':
1911 php_ion_unserialize_object_iface(ser, return_value);
1912 break;
1913 case 'E':
1914 php_ion_unserialize_object_enum(ser, return_value);
1915 break;
1916 default:
1917 php_ion_unserialize_object(ser, return_value);
1918 }
1919 } else if (!ser->annotations.object_type) {
1920 array_init(return_value);
1921 php_ion_unserialize_hash(ser, return_value);
1922 } else if (ser->annotations.object_type == 'o') {
1923 object_init(return_value);
1924 php_ion_unserialize_hash(ser, return_value);
1925 } else {
1926 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_INVALID_TOKEN,
1927 "Invalid object annotation %c::", ser->annotations.object_type);
1928 }
1929 }
1930
1931 static inline void php_ion_unserialize_list(php_ion_unserializer *ser, zval *return_value)
1932 {
1933 ION_CHECK(ion_reader_step_in(ser->reader));
1934 array_init(return_value);
1935 zend_hash_next_index_insert(ser->ids, return_value);
1936
1937 while (true) {
1938 ION_TYPE typ;
1939 ION_CHECK(ion_reader_next(ser->reader, &typ));
1940
1941 if (typ == tid_EOF) {
1942 break;
1943 }
1944
1945 zval next;
1946 php_ion_unserialize_zval(ser, &next, &typ);
1947 ION_CATCH();
1948
1949 zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &next);
1950 }
1951
1952 ION_CHECK(ion_reader_step_out(ser->reader));
1953 }
1954
1955 static inline void php_ion_reader_read_lob(ION_READER *reader, zval *return_value)
1956 {
1957 zend_string *zstr = zend_string_alloc(0x1000, 0);
1958 again:
1959 SIZE read = 0;
1960 iERR err = ion_reader_read_lob_bytes(reader, (BYTE *) zstr->val, zstr->len, &read);
1961 if (err == IERR_BUFFER_TOO_SMALL) {
1962 zstr = zend_string_extend(zstr, zstr->len << 2, 0);
1963 goto again;
1964 }
1965 ION_CHECK(err, zend_string_release(zstr));
1966 if (zstr->len > read) {
1967 zstr->val[read] = 0;
1968 zstr = zend_string_truncate(zstr, read, 0);
1969 }
1970 RETURN_STR(zstr);
1971 }
1972
1973 static inline void php_ion_reader_read_timestamp(ION_READER *reader, ION_READER_OPTIONS *opt, zval *return_value)
1974 {
1975 ION_TIMESTAMP ts;
1976 ION_CHECK(ion_reader_read_timestamp(reader, &ts));
1977
1978 object_init_ex(return_value, ce_Timestamp);
1979 php_ion_timestamp *ts_obj = php_ion_obj(timestamp, Z_OBJ_P(return_value));
1980
1981 zend_string *fmt = NULL;
1982 decContext *ctx = opt ? opt->decimal_context : NULL;
1983 ts_obj->time = php_time_from_ion(&ts, ctx, &fmt);
1984 php_ion_timestamp_ctor(ts_obj, ts.precision, fmt, NULL, NULL);
1985 zend_string_release(fmt);
1986
1987 OBJ_CHECK(ts_obj);
1988 }
1989
1990 static inline void php_ion_reader_read_int(ION_READER *reader, zval *return_value)
1991 {
1992 ION_INT *num = NULL;
1993 ION_CHECK(ion_int_alloc(reader, &num));
1994 ION_CHECK(ion_reader_read_ion_int(reader, num));
1995
1996 // TODO: SIZEOF_ZEND_LONG == 4
1997 int64_t i64;
1998 iERR err = ion_int_to_int64(num, &i64);
1999 switch (err) {
2000 case IERR_OK:
2001 RETVAL_LONG(i64);
2002 goto done;
2003
2004 case IERR_NUMERIC_OVERFLOW:
2005 SIZE max, len;
2006 ION_CHECK(ion_int_char_length(num, &max));
2007 zend_string *zs = zend_string_alloc(max, 0);
2008
2009 err = ion_int_to_char(num, (BYTE *) zs->val, max, &len);
2010 zs->val[zs->len = len] = 0;
2011 RETVAL_STR(zs);
2012 /* fall through */
2013
2014 default:
2015 done:
2016 ion_int_free(num);
2017 ION_CHECK(err);
2018 }
2019 }
2020
2021 static inline void php_ion_unserialize_backref(php_ion_unserializer *ser, zval *return_value)
2022 {
2023 zval *backref = zend_hash_index_find(ser->ids, Z_LVAL_P(return_value));
2024
2025 if (backref) {
2026 ZVAL_COPY_VALUE(return_value, backref);
2027 zend_hash_next_index_insert(ser->addref, return_value);
2028 } else {
2029 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_INTERNAL_ERROR,
2030 "Could not find back reference %ld", Z_LVAL_P(return_value));
2031 }
2032 }
2033
2034 static inline void php_ion_unserialize_annotations(php_ion_unserializer *ser)
2035 {
2036 memset(&ser->annotations, 0, sizeof(ser->annotations));
2037
2038 int32_t ann_cnt;
2039 ION_CHECK(ion_reader_get_annotation_count(ser->reader, &ann_cnt));
2040 for (int32_t i = 0; i < ann_cnt; ++i) {
2041 ION_STRING ann_str;
2042 ION_CHECK(ion_reader_get_an_annotation(ser->reader, i, &ann_str));
2043
2044 if (ann_str.length != 1) {
2045 continue;
2046 }
2047
2048 switch (*ann_str.value) {
2049 case 'R':
2050 if (ser->annotations.makeref) {
2051 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_INVALID_SYNTAX,
2052 "Invalid multiple reference annotations");
2053 return;
2054 }
2055 ser->annotations.makeref = true;
2056 break;
2057
2058 case 'r':
2059 if (ser->annotations.backref) {
2060 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_INVALID_SYNTAX,
2061 "Invalid multiple back reference annotations");
2062 return;
2063 }
2064 ser->annotations.backref = true;
2065 break;
2066
2067 case 'p':
2068 if (ser->annotations.object_prop) {
2069 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_INVALID_SYNTAX,
2070 "Invalid multiple object property annotations");
2071 return;
2072 }
2073 ser->annotations.object_prop = true;
2074
2075 ION_STRING prop_class;
2076 ION_CHECK(ion_reader_get_an_annotation(ser->reader, ++i, &prop_class));
2077 ser->annotations.property_class = zend_string_from_ion(&prop_class);
2078
2079 zval zptmp;
2080 ZVAL_STR(&zptmp, ser->annotations.property_class);
2081 zend_hash_next_index_insert(ser->tmp, &zptmp);
2082 break;
2083
2084 case 'E':
2085 case 'S':
2086 case 'O':
2087 case 'C':
2088 case 'o':
2089 case 'c':
2090 if (ser->annotations.object_type) {
2091 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_INVALID_SYNTAX,
2092 "Invalid multiple object type annotations: %c::%c",
2093 ser->annotations.object_type, *ann_str.value);
2094 return;
2095 }
2096 if ('o' != (ser->annotations.object_type = *ann_str.value)) {
2097 ION_STRING class_name;
2098 ION_CHECK(ion_reader_get_an_annotation(ser->reader, ++i, &class_name));
2099 ser->annotations.object_class = zend_string_from_ion(&class_name);
2100
2101 zval zctmp;
2102 ZVAL_STR(&zctmp, ser->annotations.object_class);
2103 zend_hash_next_index_insert(ser->tmp, &zctmp);
2104 }
2105 break;
2106 }
2107
2108 // sanity checks
2109 if (ser->annotations.object_type && ser->annotations.object_type != 'o' && !ser->annotations.object_class) {
2110 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_INVALID_SYNTAX,
2111 "Invalid object annotation without class name: %c::", ser->annotations.object_type);
2112 return;
2113 }
2114 if (ser->annotations.object_type == 'o' && ser->annotations.object_class) {
2115 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_INVALID_SYNTAX,
2116 "Invalid object annotation with class name: o::%s", ser->annotations.object_class->val);
2117 return;
2118 }
2119 }
2120 }
2121
2122 static inline void php_ion_unserialize_zval(php_ion_unserializer *ser, zval *return_value, ION_TYPE *typ)
2123 {
2124 if (typ) {
2125 memcpy(&ser->type, typ, sizeof(ser->type));
2126 } else {
2127 typ = &ser->type;
2128 ION_CHECK(ion_reader_next(ser->reader, typ));
2129 }
2130
2131 php_ion_unserialize_annotations(ser);
2132 ION_CATCH();
2133
2134 if (ser->annotations.makeref) {
2135 ZVAL_MAKE_REF(return_value);
2136 zend_hash_next_index_insert(ser->ids, return_value);
2137 ZVAL_DEREF(return_value);
2138 }
2139
2140 if (ION_TYPE_INT(*typ) > 0) {
2141 BOOL is_null;
2142 ION_CHECK(ion_reader_is_null(ser->reader, &is_null));
2143 if (is_null) {
2144 RETURN_NULL();
2145 }
2146 }
2147
2148 switch (ION_TYPE_INT(*typ)) {
2149 case tid_NULL_INT:
2150 ION_CHECK(ion_reader_read_null(ser->reader, typ));
2151 RETURN_NULL();
2152
2153 case tid_BOOL_INT:
2154 BOOL bval;
2155 ION_CHECK(ion_reader_read_bool(ser->reader, &bval));
2156 RETURN_BOOL(bval);
2157
2158 case tid_INT_INT:
2159 php_ion_reader_read_int(ser->reader, return_value);
2160 if (ser->annotations.backref) {
2161 ION_CATCH();
2162 php_ion_unserialize_backref(ser, return_value);
2163 }
2164 if (ser->annotations.object_type) {
2165 if (!ser->annotations.backref) {
2166 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_INVALID_SYNTAX,
2167 "Invalid object type annotation: %c::" ZEND_LONG_FMT,
2168 ser->annotations.object_type, Z_LVAL_P(return_value));
2169 return;
2170 }
2171 goto unserialize_struct;
2172 }
2173 return;
2174
2175 case tid_FLOAT_INT:
2176 double d;
2177 ION_CHECK(ion_reader_read_double(ser->reader, &d));
2178 RETURN_DOUBLE(d);
2179
2180 case tid_DECIMAL_INT:
2181 object_init_ex(return_value, ce_Decimal);
2182 php_ion_decimal *dec = php_ion_obj(decimal, Z_OBJ_P(return_value));
2183 ION_CHECK(ion_reader_read_ion_decimal(ser->reader, &dec->dec));
2184 php_ion_decimal_ctor(dec);
2185 zend_hash_next_index_insert(ser->ids, return_value);
2186 return;
2187
2188 case tid_TIMESTAMP_INT:
2189 php_ion_reader_read_timestamp(ser->reader, ser->options, return_value);
2190 zend_hash_next_index_insert(ser->ids, return_value);
2191 return;
2192
2193 case tid_SYMBOL_INT:
2194 ION_SYMBOL sym;
2195 ION_CHECK(ion_reader_read_ion_symbol(ser->reader, &sym));
2196 php_ion_symbol_zval(&sym, return_value);
2197 if (ser->annotations.object_type) {
2198 zend_hash_next_index_insert(ser->tmp, return_value);
2199 goto unserialize_struct;
2200 }
2201 zend_hash_next_index_insert(ser->ids, return_value);
2202 return;
2203
2204 case tid_STRING_INT:
2205 ION_STRING str;
2206 ION_CHECK(ion_reader_read_string(ser->reader, &str));
2207 RETVAL_STRINGL((char *) str.value, str.length);
2208 if (ser->annotations.object_type) {
2209 zend_hash_next_index_insert(ser->tmp, return_value);
2210 goto unserialize_struct;
2211 }
2212 zend_hash_next_index_insert(ser->ids, return_value);
2213 return;
2214
2215 case tid_CLOB_INT:
2216 case tid_BLOB_INT:
2217 php_ion_reader_read_lob(ser->reader, return_value);
2218 if (ser->annotations.object_type) {
2219 zend_hash_next_index_insert(ser->tmp, return_value);
2220 goto unserialize_struct;
2221 }
2222 zend_hash_next_index_insert(ser->ids, return_value);
2223 return;
2224
2225 case tid_LIST_INT:
2226 case tid_SEXP_INT: // FIXME
2227 php_ion_unserialize_list(ser, return_value);
2228 if (!ser->annotations.object_type) {
2229 return;
2230 }
2231 /* fall through */
2232
2233 case tid_STRUCT_INT:
2234 unserialize_struct: ;
2235 php_ion_unserialize_struct(ser, return_value);
2236 return;
2237
2238 case tid_none_INT:
2239 ZEND_ASSERT(0);
2240 break;
2241
2242 case tid_DATAGRAM_INT:
2243 ZEND_ASSERT(!"datagram");
2244 case tid_EOF_INT:
2245 return;
2246 }
2247 }
2248
2249 php_ion_decl(unserializer_php, Unserializer_PHP, php_ion_unserializer_php_dtor(obj));
2250
2251 static inline void php_ion_unserialize_ex(php_ion_unserializer *ser, zval *return_value)
2252 {
2253 if (ser->multi_seq) {
2254 array_init(return_value);
2255 }
2256
2257 do {
2258 zval tmp;
2259 ZVAL_NULL(&tmp);
2260 php_ion_globals_unserializer_step();
2261 php_ion_unserialize_zval(ser, &tmp, NULL);
2262 php_ion_globals_unserializer_exit();
2263 ION_CATCH(zval_ptr_dtor(&tmp));
2264
2265 if (!ser->multi_seq) {
2266 RETURN_COPY_VALUE(&tmp);
2267 } else if (ser->type != tid_EOF) {
2268 zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &tmp);
2269 }
2270 } while (ser->type != tid_EOF);
2271 }
2272
2273 void php_ion_unserialize(php_ion_unserializer *ser, zval *zdata, zval *return_value)
2274 {
2275 zend_object *zo_opt = NULL, *zo_ser = NULL;
2276
2277 if (!ser) {
2278 zo_ser = create_ion_Unserializer_PHP(NULL);
2279 php_ion_unserializer_php *o_ser = php_ion_obj(unserializer_php, zo_ser);
2280 PTR_CHECK(o_ser);
2281 o_ser->unserializer.call_magic = true;
2282 php_ion_unserializer_php_ctor(o_ser);
2283 ION_CATCH();
2284 ser = &o_ser->unserializer;
2285 }
2286
2287 zend_object *zo_reader;
2288 php_ion_reader *reader;
2289 ZVAL_DEREF(zdata);
2290
2291 if (Z_TYPE_P(zdata) == IS_RESOURCE) {
2292 zo_reader = create_ion_Reader_Reader(ce_Reader_Stream_Reader);
2293 reader = php_ion_obj(reader, zo_reader);
2294 reader->type = STREAM_READER;
2295 php_stream_from_zval_no_verify(reader->stream.ptr, zdata);
2296 } else if (Z_TYPE_P(zdata) <= IS_STRING) {
2297 zo_reader = create_ion_Reader_Reader(ce_Reader_Buffer_Reader);
2298 reader = php_ion_obj(reader, zo_reader);
2299 reader->type = BUFFER_READER;
2300 reader->buffer = zval_get_string(zdata);
2301 } else {
2302 zend_throw_exception_ex(spl_ce_InvalidArgumentException, IERR_INVALID_ARG,
2303 "Invalid source to unserialize; expected string or resource");
2304 if (zo_ser) {
2305 OBJ_RELEASE(zo_ser);
2306 }
2307 return;
2308 }
2309
2310 if (ser->options) {
2311 zo_opt = reader->opt = create_ion_Reader_Options(NULL);
2312 php_ion_obj(reader_options, reader->opt)->opt = *ser->options;
2313 }
2314
2315 php_ion_reader_ctor(reader);
2316 ser->reader = reader->reader;
2317
2318 if (!EG(exception)) {
2319 php_ion_unserialize_ex(ser, return_value);
2320 }
2321
2322 OBJ_RELEASE(zo_reader);
2323 if (zo_opt) {
2324 OBJ_RELEASE(zo_opt);
2325 }
2326 if (zo_ser) {
2327 OBJ_RELEASE(zo_ser);
2328 }
2329 }
2330
2331 static inline zval *php_ion_global_symbol_fetch_by_enum(zend_string *name)
2332 {
2333 zval *zgs = zend_hash_find(&php_ion_globals.symbol.cache, name);
2334 if (!zgs) {
2335 zval *zid = zend_hash_find(&g_sym_map, name);
2336 if (zid) {
2337 zval *zss = zend_hash_index_find(&g_sym_hash, Z_LVAL_P(zid));
2338 if (zss) {
2339 zval zsym;
2340 object_init_ex(&zsym, ce_Symbol);
2341 php_ion_symbol *sym = php_ion_obj(symbol, Z_OBJ(zsym));
2342 sym->sym.sid = Z_LVAL_P(zid);
2343 sym->value = zval_get_string(zss);
2344 php_ion_symbol_ctor(sym);
2345 zgs = zend_hash_add(&php_ion_globals.symbol.cache, name, &zsym);
2346 }
2347 }
2348 }
2349 return zgs;
2350 }