fix leak
[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 zend_string_release(key);
950 }
951
952 php_ion_decl(catalog, Catalog, php_ion_catalog_dtor(obj));
953
954 typedef struct php_ion_reader_options {
955 ION_READER_OPTIONS opt;
956 zend_object *cat, *dec_ctx, *cb, std;
957 } php_ion_reader_options;
958
959 php_ion_decl(reader_options, Reader_Options);
960
961 typedef struct php_ion_reader {
962 ION_READER *reader;
963 ION_TYPE state;
964 enum {
965 BUFFER_READER,
966 STREAM_READER,
967 } type;
968 union {
969 zend_string *buffer;
970 struct {
971 php_stream *ptr;
972 ION_STRING buf;
973 } stream;
974 };
975 zend_object *opt, std;
976 } php_ion_reader;
977
978 static inline iERR php_ion_reader_stream_handler(struct _ion_user_stream *user)
979 {
980 php_ion_reader *reader = (php_ion_reader *) user->handler_state;
981 size_t remaining = 0, spare = reader->stream.buf.length;
982
983 if (user->curr && user->limit && (remaining = user->limit - user->curr)) {
984 memmove(reader->stream.buf.value, user->curr, remaining);
985 user->limit -= remaining;
986 spare -= remaining;
987 } else {
988 user->curr = user->limit = reader->stream.buf.value;
989 }
990
991 ssize_t read = php_stream_read(reader->stream.ptr, (char *) user->limit, spare);
992 if (EXPECTED(read > 0)) {
993 user->limit += read;
994 return IERR_OK;
995 }
996
997 if (EXPECTED(read == 0)) {
998 return IERR_EOF;
999 }
1000
1001 return IERR_READ_ERROR;
1002 }
1003
1004 static inline iERR on_context_change(void *context, ION_COLLECTION *imports)
1005 {
1006 if (context) {
1007 php_ion_reader *obj = php_ion_obj(reader, context);
1008 (void) obj;
1009 }
1010 return IERR_OK;
1011 }
1012
1013 static ION_READER_CONTEXT_CHANGE_NOTIFIER EMPTY_READER_CHANGE_NOTIFIER = {
1014 on_context_change,
1015 NULL
1016 };
1017
1018 static inline void php_ion_reader_ctor(php_ion_reader *obj)
1019 {
1020 iERR err;
1021 php_ion_reader_options *opt = php_ion_obj(reader_options, obj->opt);
1022
1023 if (opt) {
1024 opt->opt.context_change_notifier.context = obj;
1025 }
1026 if (obj->type == STREAM_READER) {
1027 PTR_CHECK(obj->stream.ptr);
1028 GC_ADDREF(obj->stream.ptr->res);
1029
1030 obj->stream.buf.length = opt && opt->opt.allocation_page_size ? opt->opt.allocation_page_size : 0x10000;
1031 obj->stream.buf.value = emalloc(obj->stream.buf.length);
1032 err = ion_reader_open_stream(&obj->reader, obj, php_ion_reader_stream_handler, opt ? &opt->opt : NULL);
1033
1034 } else {
1035 err = ion_reader_open_buffer(&obj->reader,
1036 (BYTE *) obj->buffer->val, obj->buffer->len,
1037 opt ? &opt->opt : NULL);
1038 }
1039 if (opt) {
1040 opt->opt.context_change_notifier.context = NULL;
1041 }
1042
1043 ION_CHECK(err);
1044 OBJ_CHECK(obj);
1045 }
1046 static inline void php_ion_reader_dtor(php_ion_reader *obj)
1047 {
1048 if (obj->reader) {
1049 ion_reader_close(obj->reader);
1050 }
1051 if (obj->type == STREAM_READER) {
1052 if (obj->stream.buf.value) {
1053 efree(obj->stream.buf.value);
1054 }
1055 if (obj->stream.ptr) {
1056 zend_list_delete(obj->stream.ptr->res);
1057 }
1058 } else {
1059 if (obj->buffer) {
1060 zend_string_release(obj->buffer);
1061 }
1062 }
1063 }
1064
1065 php_ion_decl(reader, Reader_Reader, php_ion_reader_dtor(obj));
1066
1067 typedef struct php_ion_writer_options {
1068 ION_WRITER_OPTIONS opt;
1069 zend_object *cat, *dec_ctx, *col, std;
1070 } php_ion_writer_options;
1071
1072 php_ion_decl(writer_options, Writer_Options);
1073
1074 typedef struct php_ion_writer {
1075 ION_WRITER *writer;
1076 enum {
1077 BUFFER_WRITER,
1078 STREAM_WRITER,
1079 } type;
1080 union {
1081 struct {
1082 zval val;
1083 smart_str str;
1084 } buffer;
1085 struct {
1086 ION_STRING buf;
1087 php_stream *ptr;
1088 } stream;
1089 };
1090 zend_object *opt, std;
1091
1092 } php_ion_writer;
1093
1094 static inline iERR php_ion_writer_stream_handler(struct _ion_user_stream *user)
1095 {
1096 php_ion_writer *writer = (php_ion_writer *) user->handler_state;
1097
1098 if (EXPECTED(user->limit && user->curr)) {
1099 ptrdiff_t len = user->curr - writer->stream.buf.value;
1100 if (len != php_stream_write(writer->stream.ptr, (char *) writer->stream.buf.value, len)) {
1101 return IERR_WRITE_ERROR;
1102 }
1103 }
1104 user->curr = writer->stream.buf.value;
1105 user->limit = writer->stream.buf.value + writer->stream.buf.length;
1106 return IERR_OK;
1107 }
1108
1109 #define REF_STR() do { \
1110 ZVAL_NEW_STR(ref, obj->buffer.str.s); \
1111 GC_ADDREF(obj->buffer.str.s); \
1112 } while (0)
1113
1114 #define NEW_REF_STR() do {\
1115 if (Z_STR_P(ref) != obj->buffer.str.s) { \
1116 zval_ptr_dtor(ref); \
1117 REF_STR(); \
1118 } \
1119 } while(0)
1120
1121 static inline void php_ion_writer_stream_init(php_ion_writer *obj, php_ion_writer_options *opt)
1122 {
1123 PTR_CHECK(obj->stream.ptr);
1124 GC_ADDREF(obj->stream.ptr->res);
1125
1126 obj->stream.buf.length = opt ? opt->opt.allocation_page_size : 0x1000;
1127 obj->stream.buf.value = emalloc(obj->stream.buf.length);
1128 }
1129 static inline void php_ion_writer_buffer_init(php_ion_writer *obj)
1130 {
1131 zval *ref = &obj->buffer.val;
1132 ZVAL_DEREF(ref);
1133
1134 smart_str_alloc(&obj->buffer.str, 0, 0);
1135 smart_str_0(&obj->buffer.str);
1136 REF_STR();
1137 }
1138
1139 static inline void php_ion_writer_buffer_grow(php_ion_writer *obj)
1140 {
1141 zval *ref = &obj->buffer.val;
1142 ZVAL_DEREF(ref);
1143
1144 switch (GC_REFCOUNT(obj->buffer.str.s)) {
1145 case 2:
1146 // nothing to do
1147 break;
1148 case 1:
1149 // we've been separated
1150 GC_ADDREF(obj->buffer.str.s);
1151 break;
1152 default:
1153 // we have to separate
1154 fprintf(stderr, "SEPARATE\n");
1155 obj->buffer.str.s = zend_string_dup(obj->buffer.str.s, 0);
1156 break;
1157 }
1158
1159 zend_string *old = obj->buffer.str.s;
1160 GC_DELREF(old);
1161 smart_str_erealloc(&obj->buffer.str, obj->buffer.str.a << 1);
1162 if (old == obj->buffer.str.s) {
1163 GC_ADDREF(old);
1164 } else if(old == Z_STR_P(ref)) {
1165 ZVAL_NULL(ref);
1166 }
1167
1168 NEW_REF_STR();
1169 }
1170
1171 static inline iERR php_ion_writer_buffer_handler(struct _ion_user_stream *user)
1172 {
1173 php_ion_writer *writer = (php_ion_writer *) user->handler_state;
1174
1175 if (user->curr) {
1176 writer->buffer.str.s->len += user->curr - (BYTE *) &writer->buffer.str.s->val[writer->buffer.str.s->len];
1177 smart_str_0(&writer->buffer.str);
1178 if (user->limit == user->curr) {
1179 php_ion_writer_buffer_grow(writer);
1180 }
1181 }
1182 user->curr = (BYTE *) &writer->buffer.str.s->val[writer->buffer.str.s->len];
1183 user->limit = user->curr + writer->buffer.str.a - writer->buffer.str.s->len;
1184
1185 return IERR_OK;
1186 }
1187
1188 static inline void php_ion_writer_ctor(php_ion_writer *obj)
1189 {
1190 if (obj->opt) {
1191 update_property_obj(&obj->std, ZEND_STRL("options"), obj->opt);
1192 }
1193
1194 php_ion_writer_options *opt = php_ion_obj(writer_options, obj->opt);
1195 ION_STREAM_HANDLER h;
1196 if (obj->type == STREAM_WRITER) {
1197 h = php_ion_writer_stream_handler;
1198 php_ion_writer_stream_init(obj, opt);
1199 } else {
1200 h = php_ion_writer_buffer_handler;
1201 php_ion_writer_buffer_init(obj);
1202 }
1203
1204 ION_CHECK(ion_writer_open_stream(&obj->writer, h, obj, opt ? &opt->opt : NULL));
1205 OBJ_CHECK(obj);
1206 }
1207
1208 static inline void php_ion_writer_dtor(php_ion_writer *obj)
1209 {
1210 if (obj->writer) {
1211 ion_writer_close(obj->writer);
1212 }
1213 if (obj->type == STREAM_WRITER) {
1214 if (obj->stream.buf.value) {
1215 efree(obj->stream.buf.value);
1216 }
1217 if (obj->stream.ptr) {
1218 zend_list_delete(obj->stream.ptr->res);
1219 }
1220 } else {
1221 if (obj->buffer.str.s) {
1222 smart_str_0(&obj->buffer.str);
1223 zend_string_release(obj->buffer.str.s);
1224 }
1225 zval_ptr_dtor(&obj->buffer.val);
1226 }
1227 }
1228
1229 php_ion_decl(writer, Writer_Writer, php_ion_writer_dtor(obj));
1230
1231 typedef struct php_ion_serializer_php {
1232 php_ion_serializer serializer;
1233 zend_object *opt, std;
1234 } php_ion_serializer_php;
1235
1236 static inline void php_ion_serializer_php_ctor(php_ion_serializer_php *ser_obj)
1237 {
1238 php_ion_serializer *global_ser = &php_ion_globals.serializer;
1239 ser_obj->serializer.ids = global_ser->ids;
1240 ser_obj->serializer.tmp = global_ser->tmp;
1241
1242 zend_update_property_bool(ser_obj->std.ce, &ser_obj->std, ZEND_STRL("callMagicSerialize"),
1243 ser_obj->serializer.call_magic);
1244 if (ser_obj->serializer.call_custom) {
1245 zend_update_property_str(ser_obj->std.ce, &ser_obj->std, ZEND_STRL("callCustomSerialize"),
1246 ser_obj->serializer.call_custom);
1247 ser_obj->serializer.call_custom = zend_string_tolower(ser_obj->serializer.call_custom);
1248 } else {
1249 zend_update_property_null(ser_obj->std.ce, &ser_obj->std, ZEND_STRL("callCustomSerialize"));
1250 }
1251 if (!ser_obj->opt) {
1252 ser_obj->opt = create_ion_Writer_Options(NULL);
1253 } else {
1254 GC_ADDREF(ser_obj->opt);
1255 }
1256 ser_obj->serializer.options = &php_ion_obj(writer_options, ser_obj->opt)->opt;
1257 update_property_obj(&ser_obj->std, ZEND_STRL("writerOptions"), ser_obj->opt);
1258 GC_DELREF(ser_obj->opt);
1259 }
1260
1261 static inline void php_ion_serializer_php_dtor(php_ion_serializer_php *obj)
1262 {
1263 if (obj->serializer.call_custom) {
1264 zend_string_release(obj->serializer.call_custom);
1265 }
1266 }
1267
1268 static inline void php_ion_serialize_zval(php_ion_serializer *, zval *);
1269
1270 static inline void php_ion_serialize_struct(php_ion_serializer *ser, zend_array *arr, bool props)
1271 {
1272 ION_CHECK(ion_writer_start_container(ser->writer, tid_STRUCT));
1273
1274 zval *v;
1275 zend_ulong h;
1276 zend_string *k = NULL;
1277 if (arr) ZEND_HASH_FOREACH_KEY_VAL_IND(arr, h, k, v)
1278 ION_STRING is;
1279 if (k) {
1280 size_t prop_len;
1281 const char *class_name, *prop_name;
1282 if (props && (SUCCESS == zend_unmangle_property_name_ex(k, &class_name, &prop_name, &prop_len)) && class_name) {
1283 ION_CHECK(ion_writer_add_annotation(ser->writer, ion_string_assign_cstr(&is, ZEND_STRL("p"))));
1284 ION_CHECK(ion_writer_add_annotation(ser->writer, ion_string_assign_cstr(&is, (char *) class_name, prop_name - class_name - 1)));
1285 } else {
1286 prop_name = k->val;
1287 prop_len = k->len;
1288 }
1289 ion_string_assign_cstr(&is, (char *) prop_name, prop_len);
1290 } else {
1291 char buf[MAX_LENGTH_OF_LONG + 1], *end = buf + sizeof(buf) - 1;
1292 char *ptr = zend_print_long_to_buf(end, (zend_long) h);
1293 ion_string_assign_cstr(&is, ptr, end - ptr);
1294 }
1295
1296 // WATCH OUT: field names need to be copied
1297 ION_STRING fn;
1298 ION_CHECK(ion_string_copy_to_owner(ser->writer, &fn, &is));
1299 ION_CHECK(ion_writer_write_field_name(ser->writer, &fn));
1300
1301 php_ion_serialize_zval(ser, v);
1302 ION_CATCH();
1303 ZEND_HASH_FOREACH_END();
1304
1305 ION_CHECK(ion_writer_finish_container(ser->writer));
1306 }
1307
1308 static inline void php_ion_serialize_list(php_ion_serializer *ser, zend_array *arr)
1309 {
1310 ION_CHECK(ion_writer_start_container(ser->writer, tid_LIST));
1311
1312 zval *v;
1313 ZEND_HASH_FOREACH_VAL_IND(arr, v)
1314 php_ion_serialize_zval(ser, v);
1315 ION_CATCH();
1316 ZEND_HASH_FOREACH_END();
1317
1318 ION_CHECK(ion_writer_finish_container(ser->writer));
1319 }
1320
1321 static inline void php_ion_serialize_array(php_ion_serializer *ser, zend_array *arr)
1322 {
1323 if (zend_array_is_list(arr)) {
1324 php_ion_serialize_list(ser, arr);
1325 } else {
1326 php_ion_serialize_struct(ser, arr, false);
1327 }
1328 }
1329
1330 static inline void php_ion_serialize_object_iface(php_ion_serializer *ser, zend_object *zobject)
1331 {
1332 uint8_t *buf;
1333 size_t len;
1334 zval tmp;
1335
1336 ZVAL_OBJ(&tmp, zobject);
1337 if (SUCCESS == zobject->ce->serialize(&tmp, &buf, &len, NULL)) {
1338 ION_STRING is;
1339 ION_CHECK(ion_writer_add_annotation(ser->writer, ion_string_assign_cstr(&is, ZEND_STRL("S"))));
1340 ION_CHECK(ion_writer_add_annotation(ser->writer, ion_string_from_zend(&is, zobject->ce->name)));
1341 ION_CHECK(ion_writer_write_string(ser->writer, ion_string_assign_cstr(&is, (char *) buf, len)));
1342 efree(buf);
1343 } else if (!EG(exception)){
1344 zend_throw_exception_ex(spl_ce_UnexpectedValueException, IERR_INTERNAL_ERROR,
1345 "Failed to serialize class %s", zobject->ce->name->val);
1346 }
1347 }
1348
1349 static inline void php_ion_serialize_object_magic(php_ion_serializer *ser, zend_object *zobject, zend_function *fn)
1350 {
1351 zval rv;
1352
1353 ZVAL_NULL(&rv);
1354 zend_call_known_instance_method_with_0_params(fn ? fn : zobject->ce->__serialize, zobject, &rv);
1355 ION_CATCH();
1356
1357 if (IS_ARRAY == Z_TYPE(rv)) {
1358 ION_STRING is;
1359 ION_CHECK(ion_writer_add_annotation(ser->writer, ion_string_assign_cstr(&is, fn ? "C" : "O", 1)));
1360 ION_CHECK(ion_writer_add_annotation(ser->writer, ion_string_from_zend(&is, zobject->ce->name)));
1361 php_ion_serialize_zval(ser, &rv);
1362 zval_ptr_dtor(&rv);
1363 } else {
1364 zend_throw_exception_ex(spl_ce_UnexpectedValueException, IERR_INTERNAL_ERROR,
1365 "%s serializer %s::%s did not return an array",
1366 fn ? "Custom" : "Magic", zobject->ce->name->val,
1367 fn ? fn->common.function_name->val : "__serialize");
1368 }
1369 }
1370
1371 static inline void php_ion_serialize_object_enum(php_ion_serializer *ser, zend_object *zobject)
1372 {
1373 ION_STRING is;
1374 ION_CHECK(ion_writer_add_annotation(ser->writer, ion_string_assign_cstr(&is, ZEND_STRL("E"))));
1375
1376 ION_CHECK(ion_writer_add_annotation(ser->writer, ion_string_from_zend(&is, zobject->ce->name)));
1377 zval *z_cname = zend_enum_fetch_case_name(zobject);
1378 ION_CHECK(ion_writer_write_symbol(ser->writer, ion_string_from_zend(&is, Z_STR_P(z_cname))));
1379 }
1380
1381 static inline void php_ion_serialize_object_std(php_ion_serializer *ser, zend_object *zobject)
1382 {
1383 ION_STRING is;
1384
1385 if (zobject->ce != zend_standard_class_def) {
1386 ION_CHECK(ion_writer_add_annotation(ser->writer, ion_string_assign_cstr(&is, ZEND_STRL("c"))));
1387 ION_CHECK(ion_writer_add_annotation(ser->writer, ion_string_from_zend(&is, zobject->ce->name)));
1388 } else {
1389 ION_CHECK(ion_writer_add_annotation(ser->writer, ion_string_assign_cstr(&is, ZEND_STRL("o"))));
1390 }
1391
1392 zval zobj;
1393 ZVAL_OBJ(&zobj, zobject);
1394 HashTable *props = zend_get_properties_for(&zobj, ZEND_PROP_PURPOSE_SERIALIZE);
1395 if (props) {
1396 php_ion_serialize_struct(ser, props, true);
1397 zend_release_properties(props);
1398 } else {
1399 zend_throw_exception_ex(spl_ce_UnexpectedValueException, IERR_INTERNAL_ERROR,
1400 "Could not get properties for serialization of class %s",
1401 zobject->ce->name->val);
1402 }
1403 }
1404
1405 static inline void php_ion_serialize_object_lob(php_ion_serializer *ser, zend_object *zobject)
1406 {
1407 zval tmp_type, *type = zend_read_property(NULL, zobject, ZEND_STRL("type"), 0, &tmp_type);
1408 zval tmp_value, *value = zend_read_property(NULL, zobject, ZEND_STRL("value"), 0, &tmp_value);
1409 switch (Z_LVAL_P(zend_enum_fetch_case_value(Z_OBJ_P(type)))) {
1410 case tid_BLOB_INT:
1411 ION_CHECK(ion_writer_write_blob(ser->writer, (BYTE *) Z_STRVAL_P(value), Z_STRLEN_P(value)));
1412 break;
1413 case tid_CLOB_INT:
1414 ION_CHECK(ion_writer_write_clob(ser->writer, (BYTE *) Z_STRVAL_P(value), Z_STRLEN_P(value)));
1415 break;
1416 default:
1417 zend_throw_exception_ex(spl_ce_InvalidArgumentException, IERR_INVALID_ARG,
1418 "Unsupported LOB type: ion\\Type::%s", Z_STRVAL_P(zend_enum_fetch_case_name(Z_OBJ_P(type))));
1419 break;
1420 }
1421 }
1422
1423 static inline bool can_call_magic_serialize(php_ion_serializer *ser, zend_class_entry *ce)
1424 {
1425 return ce->__serialize && ser->call_magic;
1426 }
1427
1428 static inline bool can_call_iface_serialize(php_ion_serializer *, zend_class_entry *ce)
1429 {
1430 return !!ce->serialize;
1431 }
1432
1433 static inline bool can_call_custom_serialize(php_ion_serializer *ser, zend_object *zobject, zend_function **fn)
1434 {
1435 if (ser->call_custom) {
1436 return !!(*fn = zend_hash_find_ptr(&zobject->ce->function_table, ser->call_custom));
1437 }
1438 return false;
1439 }
1440
1441 static inline void php_ion_serialize_object(php_ion_serializer *ser, zend_object *zobject)
1442 {
1443 zend_function *fn;
1444 zend_class_entry *ce = zobject->ce;
1445 ZEND_ASSERT(ce);
1446
1447 if (ce->ce_flags & ZEND_ACC_NOT_SERIALIZABLE) {
1448 zend_throw_exception_ex(spl_ce_InvalidArgumentException, IERR_INVALID_ARG,
1449 "Serializing %s is not allowed", ce->name->val);
1450 return;
1451 }
1452
1453 if (can_call_magic_serialize(ser, ce)) {
1454 php_ion_serialize_object_magic(ser, zobject, NULL);
1455 } else if (can_call_iface_serialize(ser, ce)) {
1456 php_ion_serialize_object_iface(ser, zobject);
1457 } else if (can_call_custom_serialize(ser, zobject, &fn)) {
1458 php_ion_serialize_object_magic(ser, zobject, fn);
1459 } else if (zobject->ce->ce_flags & ZEND_ACC_ENUM) {
1460 php_ion_serialize_object_enum(ser, zobject);
1461 } else if (ce == ce_Symbol) {
1462 ION_CHECK(ion_writer_write_ion_symbol(ser->writer, &php_ion_obj(symbol, zobject)->sym));
1463 } else if (ce == ce_Decimal) {
1464 ION_CHECK(ion_writer_write_ion_decimal(ser->writer, &php_ion_obj(decimal, zobject)->dec));
1465 } else if (ce == ce_Timestamp) {
1466 ION_TIMESTAMP its;
1467 php_ion_timestamp *pts = php_ion_obj(timestamp, zobject);
1468 decContext *ctx = ser->options ? ser->options->decimal_context : NULL;
1469 ION_CHECK(ion_writer_write_timestamp(ser->writer, ion_timestamp_from_php(&its, pts, ctx)));
1470 } else if (ce == ce_LOB) {
1471 php_ion_serialize_object_lob(ser, zobject);
1472 } else {
1473 php_ion_serialize_object_std(ser, zobject);
1474 }
1475 }
1476
1477 static inline void php_ion_serialize_refcounted(php_ion_serializer *ser, zval *zv)
1478 {
1479 zend_ulong idx = (zend_ulong) (uintptr_t) Z_COUNTED_P(zv);
1480
1481 ION_STRING is;
1482 if (zend_hash_index_exists(ser->ids, idx)) {
1483 zval *num = zend_hash_index_find(ser->ids, idx);
1484
1485 ION_CHECK(ion_writer_add_annotation(ser->writer, ion_string_assign_cstr(&is, ZEND_STRL("r"))));
1486 ION_CHECK(ion_writer_write_int64(ser->writer, Z_LVAL_P(num)));
1487 } else {
1488 zval num;
1489
1490 ZVAL_LONG(&num, zend_hash_num_elements(ser->ids));
1491 zend_hash_index_add(ser->ids, idx, &num);
1492
1493 Z_TRY_ADDREF_P(zv);
1494 zend_hash_next_index_insert(ser->tmp, zv);
1495
1496 switch (Z_TYPE_P(zv)) {
1497 case IS_STRING:
1498 ION_CHECK(ion_writer_write_string(ser->writer, ion_string_from_zend(&is, Z_STR_P(zv))));
1499 break;
1500
1501 case IS_ARRAY:
1502 php_ion_serialize_array(ser, Z_ARRVAL_P(zv));
1503 break;
1504
1505 case IS_OBJECT:
1506 php_ion_serialize_object(ser, Z_OBJ_P(zv));
1507 break;
1508
1509 case IS_REFERENCE:
1510 ION_CHECK(ion_writer_add_annotation(ser->writer, ion_string_assign_cstr(&is, ZEND_STRL("R"))));
1511 php_ion_serialize_zval(ser, Z_REFVAL_P(zv));
1512 break;
1513 }
1514 }
1515 }
1516
1517 static inline void php_ion_serialize_zval(php_ion_serializer *ser, zval *zv)
1518 {
1519 OBJ_CHECK(ser);
1520
1521 switch (Z_TYPE_P(zv)) {
1522 case IS_NULL:
1523 ION_CHECK(ion_writer_write_null(ser->writer));
1524 break;
1525 case IS_TRUE:
1526 ION_CHECK(ion_writer_write_bool(ser->writer, TRUE));
1527 break;
1528 case IS_FALSE:
1529 ION_CHECK(ion_writer_write_bool(ser->writer, FALSE));
1530 break;
1531 case IS_LONG:
1532 ION_CHECK(ion_writer_write_int64(ser->writer, Z_LVAL_P(zv)));
1533 break;
1534 case IS_DOUBLE:
1535 ION_CHECK(ion_writer_write_double(ser->writer, Z_DVAL_P(zv)));
1536 break;
1537 case IS_STRING:
1538 case IS_ARRAY:
1539 case IS_OBJECT:
1540 case IS_REFERENCE:
1541 php_ion_serialize_refcounted(ser, zv);
1542 break;
1543 default:
1544 zend_throw_exception_ex(spl_ce_InvalidArgumentException, IERR_INVALID_ARG,
1545 "Failed to serialize value of type %s", zend_zval_type_name(zv));
1546 }
1547 }
1548
1549 php_ion_decl(serializer_php, Serializer_PHP, php_ion_serializer_php_dtor(obj));
1550
1551 static inline void php_ion_serialize_ex(php_ion_serializer *ser, zval *zv)
1552 {
1553 HashPosition pos;
1554 HashTable *arr = NULL;
1555
1556 if (ser->multi_seq) {
1557 if (Z_TYPE_P(zv) != IS_ARRAY || !zend_array_is_list(Z_ARRVAL_P(zv))) {
1558 zend_throw_exception_ex(spl_ce_InvalidArgumentException, IERR_INVALID_ARG,
1559 "Expected a packed, consecutively numerically indexed array as argument to the multi sequence serializer");
1560 return;
1561 }
1562
1563 arr = Z_ARRVAL_P(zv);
1564
1565 zend_hash_internal_pointer_reset_ex(arr, &pos);
1566 zv = zend_hash_get_current_data_ex(arr, &pos);
1567 }
1568
1569 while (zv) {
1570 /* start off with a global PHP annotation instead of repeating it all over the place */
1571 if (0 == php_ion_globals_serializer_step()) {
1572 ION_STRING is;
1573 ION_CHECK(ion_writer_add_annotation(ser->writer, ion_string_assign_cstr(&is, ZEND_STRL("PHP"))));
1574 }
1575 php_ion_serialize_zval(ser, zv);
1576 php_ion_globals_serializer_exit();
1577
1578 if (!ser->multi_seq) {
1579 break;
1580 }
1581 zend_hash_move_forward_ex(arr, &pos);
1582 zv = zend_hash_get_current_data_ex(arr, &pos);
1583 }
1584 }
1585
1586 void php_ion_serialize(php_ion_serializer *ser, zval *zv, zval *return_value)
1587 {
1588 zend_object *zo_opt = NULL, *zo_ser = NULL;
1589
1590 if (!ser) {
1591 zo_ser = create_ion_Serializer_PHP(NULL);
1592 php_ion_serializer_php *o_ser = php_ion_obj(serializer_php, zo_ser);
1593 PTR_CHECK(o_ser);
1594 o_ser->serializer.call_magic = true;
1595 php_ion_serializer_php_ctor(o_ser);
1596 ION_CATCH();
1597 ser = &o_ser->serializer;
1598 }
1599
1600 zend_object *zo_writer = create_ion_Writer_Writer(ce_Writer_Buffer_Writer);
1601 php_ion_writer *writer = php_ion_obj(writer, zo_writer);
1602 writer->type = BUFFER_WRITER;
1603
1604 if (ser->options) {
1605 zo_opt = writer->opt = create_ion_Writer_Options(NULL);
1606 php_ion_obj(writer_options, writer->opt)->opt = *ser->options;
1607 }
1608
1609 php_ion_writer_ctor(writer);
1610 ser->writer = writer->writer;
1611 ser->buffer = &writer->buffer.str;
1612
1613 if (!EG(exception)) {
1614 php_ion_serialize_ex(ser, zv);
1615 }
1616
1617 /* make sure to flush when done, else str.s might not contain everything until the writer is closed */
1618 ion_writer_flush(ser->writer, NULL);
1619 RETVAL_STR_COPY(ser->buffer->s);
1620
1621 OBJ_RELEASE(zo_writer);
1622 if (zo_opt) {
1623 OBJ_RELEASE(zo_opt);
1624 }
1625 if (zo_ser) {
1626 OBJ_RELEASE(zo_ser);
1627 }
1628 }
1629
1630 typedef struct php_ion_unserializer_php {
1631 php_ion_unserializer unserializer;
1632 zend_object *opt, std;
1633 } php_ion_unserializer_php;
1634
1635 static inline void php_ion_unserializer_php_ctor(php_ion_unserializer_php *ser_obj)
1636 {
1637 php_ion_unserializer *global_ser = &php_ion_globals.unserializer;
1638 ser_obj->unserializer.ids = global_ser->ids;
1639 ser_obj->unserializer.tmp = global_ser->tmp;
1640 ser_obj->unserializer.addref = global_ser->addref;
1641
1642 zend_update_property_bool(ser_obj->std.ce, &ser_obj->std, ZEND_STRL("callMagicSerialize"),
1643 ser_obj->unserializer.call_magic);
1644 if (ser_obj->unserializer.call_custom) {
1645 zend_update_property_str(ser_obj->std.ce, &ser_obj->std, ZEND_STRL("callCustomSerialize"),
1646 ser_obj->unserializer.call_custom);
1647 ser_obj->unserializer.call_custom = zend_string_tolower(ser_obj->unserializer.call_custom);
1648 } else {
1649 zend_update_property_null(ser_obj->std.ce, &ser_obj->std, ZEND_STRL("callCustomSerialize"));
1650 }
1651 if (!ser_obj->opt) {
1652 ser_obj->opt = create_ion_Reader_Options(NULL);
1653 } else {
1654 GC_ADDREF(ser_obj->opt);
1655 }
1656 ser_obj->unserializer.options = &php_ion_obj(reader_options, ser_obj->opt)->opt;
1657 update_property_obj(&ser_obj->std, ZEND_STRL("readerOptions"), ser_obj->opt);
1658 GC_DELREF(ser_obj->opt);
1659 }
1660
1661 static inline void php_ion_unserializer_php_dtor(php_ion_unserializer_php *obj)
1662 {
1663 if (obj->unserializer.call_custom) {
1664 zend_string_release(obj->unserializer.call_custom);
1665 }
1666 }
1667
1668 static inline void php_ion_unserialize_zval(php_ion_unserializer *ser, zval *return_value, ION_TYPE *typ);
1669
1670 static inline bool can_call_magic_unserialize(php_ion_unserializer *ser, zend_class_entry *ce)
1671 {
1672 return (ce && ce->__unserialize && ser->call_magic);
1673 }
1674
1675 static inline bool can_call_iface_unserialize(php_ion_unserializer *ser, zend_class_entry *ce)
1676 {
1677 return (ce && ce->unserialize);
1678 }
1679
1680 static inline bool can_call_custom_unserialize(php_ion_unserializer *ser, zend_object *zobject, zend_function **fn)
1681 {
1682 if (ser->call_custom) {
1683 return !!(*fn = zend_hash_find_ptr(&zobject->ce->function_table, ser->call_custom));
1684 }
1685 return false;
1686 }
1687
1688 static inline zval *php_ion_unserialize_class(php_ion_unserializer *ser, zval *return_value)
1689 {
1690 zend_class_entry *ce = zend_lookup_class(ser->annotations.object_class);
1691
1692 if (ce) {
1693 object_init_ex(return_value, ce);
1694 return zend_hash_next_index_insert(ser->ids, return_value);
1695 }
1696
1697 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_IMPORT_NOT_FOUND,
1698 "Could not find class %s", ser->annotations.object_class->val);
1699 return NULL;
1700 }
1701
1702 static inline void php_ion_unserialize_object_enum(php_ion_unserializer *ser, zval *return_value)
1703 {
1704 zend_string *zs_case = zval_get_string(return_value);
1705 ION_CATCH();
1706
1707 zend_class_entry *ce = zend_lookup_class(ser->annotations.object_class);
1708 if (!ce || !(ce->ce_flags & ZEND_ACC_ENUM)) {
1709 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_INVALID_TOKEN,
1710 "Not a valid enum: %s", ser->annotations.object_class->val);
1711 return;
1712 }
1713 if (!zend_hash_exists(CE_CONSTANTS_TABLE(ce), zs_case)) {
1714 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_INVALID_TOKEN,
1715 "Not a valid enum case: %s::%s", ser->annotations.object_class->val, zs_case->val);
1716 return;
1717 }
1718 RETVAL_OBJ_COPY(zend_enum_get_case(ce, zs_case));
1719 zend_hash_next_index_insert(ser->ids, return_value);
1720 zend_string_release(zs_case);
1721 }
1722
1723 static inline void php_ion_unserialize_object_iface(php_ion_unserializer *ser, zval *return_value)
1724 {
1725 zend_class_entry *ce = zend_lookup_class(ser->annotations.object_class);
1726 if (can_call_iface_unserialize(ser, ce)) {
1727 zend_string *s = zval_get_string(return_value);
1728 ZVAL_NULL(return_value);
1729 zval *backref = zend_hash_next_index_insert(ser->ids, return_value);
1730 if (SUCCESS == ce->unserialize(backref, ce, (BYTE *) s->val, s->len, NULL)) {
1731 RETVAL_ZVAL(backref, 0, 0);
1732 } else if (!EG(exception)) {
1733 zend_throw_exception_ex(spl_ce_UnexpectedValueException, IERR_INTERNAL_ERROR,
1734 "Failed to unserialize class %s", ce->name->val);
1735 }
1736 zend_string_release(s);
1737 } else {
1738 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_INVALID_TOKEN,
1739 "Class %s does not implement Serializable", ser->annotations.object_class->val);
1740 }
1741 }
1742
1743 static inline void php_ion_unserialize_field_name(php_ion_unserializer *ser, zend_string **key)
1744 {
1745 // FIXME: symbol table
1746 ION_STRING name;
1747 ION_CHECK(ion_reader_get_field_name(ser->reader, &name));
1748 if (!name.length) {
1749 ION_SYMBOL *is_ptr;
1750 ION_CHECK(ion_reader_get_field_name_symbol(ser->reader, &is_ptr));
1751 if (!ION_SYMBOL_IS_NULL(is_ptr) && is_ptr->value.length) {
1752 name = is_ptr->value;
1753 } else if (is_ptr) {
1754 char buf[MAX_LENGTH_OF_LONG + 1 + 1] = {0}, *end = buf + sizeof(buf) - 1, *ptr;
1755 ptr = zend_print_long_to_buf(end, is_ptr->sid);
1756 *--ptr = '$';
1757 *key = zend_string_init(ptr, end - ptr, 0);
1758 return;
1759 }
1760 }
1761 *key = zend_string_from_ion(&name);
1762 }
1763
1764 static void php_ion_unserialize_props(php_ion_unserializer *ser, zval *return_value)
1765 {
1766 zend_hash_next_index_insert(ser->ids, return_value);
1767
1768 ION_CHECK(ion_reader_step_in(ser->reader));
1769
1770 while (true) {
1771 ION_TYPE typ;
1772 ION_CHECK(ion_reader_next(ser->reader, &typ));
1773
1774 if (typ == tid_EOF) {
1775 break;
1776 }
1777
1778 zend_string *key;
1779 php_ion_unserialize_field_name(ser, &key);
1780 ION_CATCH();
1781
1782 zval zvalue;
1783 php_ion_unserialize_zval(ser, &zvalue, &typ);
1784 ION_CATCH(zend_string_release(key));
1785
1786 zend_class_entry *ce = Z_OBJCE_P(return_value);
1787 if (ser->annotations.object_prop && ser->annotations.property_class->val[0] != '*') {
1788 ce = zend_lookup_class(ser->annotations.property_class);
1789 }
1790 zend_update_property_ex(ce, Z_OBJ_P(return_value), key, &zvalue);
1791 zval_ptr_dtor(&zvalue);
1792 zend_string_release(key);
1793 }
1794
1795 ION_CHECK(ion_reader_step_out(ser->reader));
1796 }
1797
1798 /**
1799 * @link https://amzn.github.io/ion-docs/docs/spec.html#struct
1800 * When two fields in the same struct have the same name [...] Implementations must preserve all such fields,
1801 * i.e., they may not discard fields that have repeated names. However, implementations may reorder fields
1802 * (the binary format identifies structs that are sorted by symbolID), so certain operations may lead to
1803 * nondeterministic behavior.
1804 */
1805 static inline void php_ion_unserialize_hash(php_ion_unserializer *ser, zval *return_value)
1806 {
1807 zend_hash_next_index_insert(ser->ids, return_value);
1808
1809 ION_CHECK(ion_reader_step_in(ser->reader));
1810
1811 while (true) {
1812 ION_TYPE typ;
1813 ION_CHECK(ion_reader_next(ser->reader, &typ));
1814
1815 if (typ == tid_EOF) {
1816 break;
1817 }
1818
1819 zend_string *key;
1820 php_ion_unserialize_field_name(ser, &key);
1821 ION_CATCH();
1822
1823 zval zvalue;
1824 php_ion_unserialize_zval(ser, &zvalue, &typ);
1825 ION_CATCH(zend_string_release(key));
1826
1827 // FIXME:: too naive; b0rked if the previous value is an array
1828 if (zend_symtable_exists(HASH_OF(return_value), key)) {
1829 zval tmp, *prev = zend_hash_find(HASH_OF(return_value), key);
1830 if (Z_TYPE_P(prev) != IS_ARRAY) {
1831 array_init(&tmp);
1832 Z_TRY_ADDREF_P(prev);
1833 zend_hash_next_index_insert(Z_ARRVAL(tmp), prev);
1834 prev = zend_hash_update(HASH_OF(return_value), key, &tmp);
1835 }
1836 zend_hash_next_index_insert(Z_ARRVAL_P(prev), &zvalue);
1837 } else {
1838 zend_symtable_update(HASH_OF(return_value), key, &zvalue);
1839 }
1840 zend_string_release(key);
1841 }
1842
1843 ION_CHECK(ion_reader_step_out(ser->reader));
1844 }
1845
1846 static inline void verify_unserializer(php_ion_unserializer *ser, zend_object *zobject, zend_function **fn)
1847 {
1848 switch (ser->annotations.object_type) {
1849 case 'c':
1850 *fn = NULL;
1851 break;
1852
1853 case 'C':
1854 if (!can_call_custom_unserialize(ser, zobject, fn)) {
1855 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_INVALID_TOKEN,
1856 "Could not find custom serializer method of %s", ser->annotations.object_class->val);
1857 }
1858 break;
1859
1860 case 'O':
1861 if (!can_call_magic_unserialize(ser, zobject->ce)) {
1862 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_INVALID_TOKEN,
1863 "Could not find method %s::__unserialize()", ser->annotations.object_class->val);
1864 }
1865 *fn = zobject->ce->__unserialize;
1866 break;
1867
1868 default:
1869 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_INVALID_TOKEN,
1870 "Invalid object type %c", ser->annotations.object_type);
1871 }
1872 }
1873
1874 static inline void php_ion_unserialize_object(php_ion_unserializer *ser, zval *return_value)
1875 {
1876 // backup possible backref to array returned by magic/custom __serialize()
1877 zval *input = zend_hash_next_index_insert(ser->tmp, return_value);
1878
1879 php_ion_unserialize_class(ser, return_value);
1880 ION_CATCH();
1881
1882 zend_function *fn = NULL;
1883 zend_object *zobject = Z_OBJ_P(return_value);
1884 verify_unserializer(ser, zobject, &fn);
1885 ION_CATCH();
1886
1887 // plain object
1888 if (!fn) {
1889 php_ion_unserialize_props(ser, return_value);
1890 return;
1891 }
1892
1893 // magic object
1894 if (Z_TYPE_P(input) != IS_ARRAY) {
1895 zval_ptr_dtor(input);
1896 array_init(input);
1897 zend_hash_real_init_mixed(Z_ARRVAL_P(input));
1898 php_ion_unserialize_hash(ser, input);
1899 ION_CATCH();
1900 }
1901 zval rv;
1902 ZVAL_NULL(&rv);
1903 zend_call_method_with_1_params(zobject, zobject->ce, &fn, "", &rv, input);
1904 zval_ptr_dtor(&rv);
1905 }
1906
1907 static inline void php_ion_unserialize_struct(php_ion_unserializer *ser, zval *return_value)
1908 {
1909 if (ser->annotations.object_class) {
1910 switch (ser->annotations.object_type) {
1911 case 'S':
1912 php_ion_unserialize_object_iface(ser, return_value);
1913 break;
1914 case 'E':
1915 php_ion_unserialize_object_enum(ser, return_value);
1916 break;
1917 default:
1918 php_ion_unserialize_object(ser, return_value);
1919 }
1920 } else if (!ser->annotations.object_type) {
1921 array_init(return_value);
1922 php_ion_unserialize_hash(ser, return_value);
1923 } else if (ser->annotations.object_type == 'o') {
1924 object_init(return_value);
1925 php_ion_unserialize_hash(ser, return_value);
1926 } else {
1927 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_INVALID_TOKEN,
1928 "Invalid object annotation %c::", ser->annotations.object_type);
1929 }
1930 }
1931
1932 static inline void php_ion_unserialize_list(php_ion_unserializer *ser, zval *return_value)
1933 {
1934 ION_CHECK(ion_reader_step_in(ser->reader));
1935 array_init(return_value);
1936 zend_hash_next_index_insert(ser->ids, return_value);
1937
1938 while (true) {
1939 ION_TYPE typ;
1940 ION_CHECK(ion_reader_next(ser->reader, &typ));
1941
1942 if (typ == tid_EOF) {
1943 break;
1944 }
1945
1946 zval next;
1947 php_ion_unserialize_zval(ser, &next, &typ);
1948 ION_CATCH();
1949
1950 zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &next);
1951 }
1952
1953 ION_CHECK(ion_reader_step_out(ser->reader));
1954 }
1955
1956 static inline void php_ion_reader_read_lob(ION_READER *reader, zval *return_value)
1957 {
1958 zend_string *zstr = zend_string_alloc(0x1000, 0);
1959 again:
1960 SIZE read = 0;
1961 iERR err = ion_reader_read_lob_bytes(reader, (BYTE *) zstr->val, zstr->len, &read);
1962 if (err == IERR_BUFFER_TOO_SMALL) {
1963 zstr = zend_string_extend(zstr, zstr->len << 2, 0);
1964 goto again;
1965 }
1966 ION_CHECK(err, zend_string_release(zstr));
1967 if (zstr->len > read) {
1968 zstr->val[read] = 0;
1969 zstr = zend_string_truncate(zstr, read, 0);
1970 }
1971 RETURN_STR(zstr);
1972 }
1973
1974 static inline void php_ion_reader_read_timestamp(ION_READER *reader, ION_READER_OPTIONS *opt, zval *return_value)
1975 {
1976 ION_TIMESTAMP ts;
1977 ION_CHECK(ion_reader_read_timestamp(reader, &ts));
1978
1979 object_init_ex(return_value, ce_Timestamp);
1980 php_ion_timestamp *ts_obj = php_ion_obj(timestamp, Z_OBJ_P(return_value));
1981
1982 zend_string *fmt = NULL;
1983 decContext *ctx = opt ? opt->decimal_context : NULL;
1984 ts_obj->time = php_time_from_ion(&ts, ctx, &fmt);
1985 php_ion_timestamp_ctor(ts_obj, ts.precision, fmt, NULL, NULL);
1986 zend_string_release(fmt);
1987
1988 OBJ_CHECK(ts_obj);
1989 }
1990
1991 static inline void php_ion_reader_read_int(ION_READER *reader, zval *return_value)
1992 {
1993 ION_INT *num = NULL;
1994 ION_CHECK(ion_int_alloc(reader, &num));
1995 ION_CHECK(ion_reader_read_ion_int(reader, num));
1996
1997 // TODO: SIZEOF_ZEND_LONG == 4
1998 int64_t i64;
1999 iERR err = ion_int_to_int64(num, &i64);
2000 switch (err) {
2001 case IERR_OK:
2002 RETVAL_LONG(i64);
2003 goto done;
2004
2005 case IERR_NUMERIC_OVERFLOW:
2006 SIZE max, len;
2007 ION_CHECK(ion_int_char_length(num, &max));
2008 zend_string *zs = zend_string_alloc(max, 0);
2009
2010 err = ion_int_to_char(num, (BYTE *) zs->val, max, &len);
2011 zs->val[zs->len = len] = 0;
2012 RETVAL_STR(zs);
2013 /* fall through */
2014
2015 default:
2016 done:
2017 ion_int_free(num);
2018 ION_CHECK(err);
2019 }
2020 }
2021
2022 static inline void php_ion_unserialize_backref(php_ion_unserializer *ser, zval *return_value)
2023 {
2024 zval *backref = zend_hash_index_find(ser->ids, Z_LVAL_P(return_value));
2025
2026 if (backref) {
2027 ZVAL_COPY_VALUE(return_value, backref);
2028 zend_hash_next_index_insert(ser->addref, return_value);
2029 } else {
2030 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_INTERNAL_ERROR,
2031 "Could not find back reference %ld", Z_LVAL_P(return_value));
2032 }
2033 }
2034
2035 static inline void php_ion_unserialize_annotations(php_ion_unserializer *ser)
2036 {
2037 memset(&ser->annotations, 0, sizeof(ser->annotations));
2038
2039 int32_t ann_cnt;
2040 ION_CHECK(ion_reader_get_annotation_count(ser->reader, &ann_cnt));
2041 for (int32_t i = 0; i < ann_cnt; ++i) {
2042 ION_STRING ann_str;
2043 ION_CHECK(ion_reader_get_an_annotation(ser->reader, i, &ann_str));
2044
2045 if (ann_str.length != 1) {
2046 continue;
2047 }
2048
2049 switch (*ann_str.value) {
2050 case 'R':
2051 if (ser->annotations.makeref) {
2052 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_INVALID_SYNTAX,
2053 "Invalid multiple reference annotations");
2054 return;
2055 }
2056 ser->annotations.makeref = true;
2057 break;
2058
2059 case 'r':
2060 if (ser->annotations.backref) {
2061 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_INVALID_SYNTAX,
2062 "Invalid multiple back reference annotations");
2063 return;
2064 }
2065 ser->annotations.backref = true;
2066 break;
2067
2068 case 'p':
2069 if (ser->annotations.object_prop) {
2070 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_INVALID_SYNTAX,
2071 "Invalid multiple object property annotations");
2072 return;
2073 }
2074 ser->annotations.object_prop = true;
2075
2076 ION_STRING prop_class;
2077 ION_CHECK(ion_reader_get_an_annotation(ser->reader, ++i, &prop_class));
2078 ser->annotations.property_class = zend_string_from_ion(&prop_class);
2079
2080 zval zptmp;
2081 ZVAL_STR(&zptmp, ser->annotations.property_class);
2082 zend_hash_next_index_insert(ser->tmp, &zptmp);
2083 break;
2084
2085 case 'E':
2086 case 'S':
2087 case 'O':
2088 case 'C':
2089 case 'o':
2090 case 'c':
2091 if (ser->annotations.object_type) {
2092 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_INVALID_SYNTAX,
2093 "Invalid multiple object type annotations: %c::%c",
2094 ser->annotations.object_type, *ann_str.value);
2095 return;
2096 }
2097 if ('o' != (ser->annotations.object_type = *ann_str.value)) {
2098 ION_STRING class_name;
2099 ION_CHECK(ion_reader_get_an_annotation(ser->reader, ++i, &class_name));
2100 ser->annotations.object_class = zend_string_from_ion(&class_name);
2101
2102 zval zctmp;
2103 ZVAL_STR(&zctmp, ser->annotations.object_class);
2104 zend_hash_next_index_insert(ser->tmp, &zctmp);
2105 }
2106 break;
2107 }
2108
2109 // sanity checks
2110 if (ser->annotations.object_type && ser->annotations.object_type != 'o' && !ser->annotations.object_class) {
2111 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_INVALID_SYNTAX,
2112 "Invalid object annotation without class name: %c::", ser->annotations.object_type);
2113 return;
2114 }
2115 if (ser->annotations.object_type == 'o' && ser->annotations.object_class) {
2116 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_INVALID_SYNTAX,
2117 "Invalid object annotation with class name: o::%s", ser->annotations.object_class->val);
2118 return;
2119 }
2120 }
2121 }
2122
2123 static inline void php_ion_unserialize_zval(php_ion_unserializer *ser, zval *return_value, ION_TYPE *typ)
2124 {
2125 if (typ) {
2126 memcpy(&ser->type, typ, sizeof(ser->type));
2127 } else {
2128 typ = &ser->type;
2129 ION_CHECK(ion_reader_next(ser->reader, typ));
2130 }
2131
2132 php_ion_unserialize_annotations(ser);
2133 ION_CATCH();
2134
2135 if (ser->annotations.makeref) {
2136 ZVAL_MAKE_REF(return_value);
2137 zend_hash_next_index_insert(ser->ids, return_value);
2138 ZVAL_DEREF(return_value);
2139 }
2140
2141 if (ION_TYPE_INT(*typ) > 0) {
2142 BOOL is_null;
2143 ION_CHECK(ion_reader_is_null(ser->reader, &is_null));
2144 if (is_null) {
2145 RETURN_NULL();
2146 }
2147 }
2148
2149 switch (ION_TYPE_INT(*typ)) {
2150 case tid_NULL_INT:
2151 ION_CHECK(ion_reader_read_null(ser->reader, typ));
2152 RETURN_NULL();
2153
2154 case tid_BOOL_INT:
2155 BOOL bval;
2156 ION_CHECK(ion_reader_read_bool(ser->reader, &bval));
2157 RETURN_BOOL(bval);
2158
2159 case tid_INT_INT:
2160 php_ion_reader_read_int(ser->reader, return_value);
2161 if (ser->annotations.backref) {
2162 ION_CATCH();
2163 php_ion_unserialize_backref(ser, return_value);
2164 }
2165 if (ser->annotations.object_type) {
2166 if (!ser->annotations.backref) {
2167 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_INVALID_SYNTAX,
2168 "Invalid object type annotation: %c::" ZEND_LONG_FMT,
2169 ser->annotations.object_type, Z_LVAL_P(return_value));
2170 return;
2171 }
2172 goto unserialize_struct;
2173 }
2174 return;
2175
2176 case tid_FLOAT_INT:
2177 double d;
2178 ION_CHECK(ion_reader_read_double(ser->reader, &d));
2179 RETURN_DOUBLE(d);
2180
2181 case tid_DECIMAL_INT:
2182 object_init_ex(return_value, ce_Decimal);
2183 php_ion_decimal *dec = php_ion_obj(decimal, Z_OBJ_P(return_value));
2184 ION_CHECK(ion_reader_read_ion_decimal(ser->reader, &dec->dec));
2185 php_ion_decimal_ctor(dec);
2186 zend_hash_next_index_insert(ser->ids, return_value);
2187 return;
2188
2189 case tid_TIMESTAMP_INT:
2190 php_ion_reader_read_timestamp(ser->reader, ser->options, return_value);
2191 zend_hash_next_index_insert(ser->ids, return_value);
2192 return;
2193
2194 case tid_SYMBOL_INT:
2195 ION_SYMBOL sym;
2196 ION_CHECK(ion_reader_read_ion_symbol(ser->reader, &sym));
2197 php_ion_symbol_zval(&sym, return_value);
2198 if (ser->annotations.object_type) {
2199 zend_hash_next_index_insert(ser->tmp, return_value);
2200 goto unserialize_struct;
2201 }
2202 zend_hash_next_index_insert(ser->ids, return_value);
2203 return;
2204
2205 case tid_STRING_INT:
2206 ION_STRING str;
2207 ION_CHECK(ion_reader_read_string(ser->reader, &str));
2208 RETVAL_STRINGL((char *) str.value, str.length);
2209 if (ser->annotations.object_type) {
2210 zend_hash_next_index_insert(ser->tmp, return_value);
2211 goto unserialize_struct;
2212 }
2213 zend_hash_next_index_insert(ser->ids, return_value);
2214 return;
2215
2216 case tid_CLOB_INT:
2217 case tid_BLOB_INT:
2218 php_ion_reader_read_lob(ser->reader, return_value);
2219 if (ser->annotations.object_type) {
2220 zend_hash_next_index_insert(ser->tmp, return_value);
2221 goto unserialize_struct;
2222 }
2223 zend_hash_next_index_insert(ser->ids, return_value);
2224 return;
2225
2226 case tid_LIST_INT:
2227 case tid_SEXP_INT: // FIXME
2228 php_ion_unserialize_list(ser, return_value);
2229 if (!ser->annotations.object_type) {
2230 return;
2231 }
2232 /* fall through */
2233
2234 case tid_STRUCT_INT:
2235 unserialize_struct: ;
2236 php_ion_unserialize_struct(ser, return_value);
2237 return;
2238
2239 case tid_none_INT:
2240 ZEND_ASSERT(0);
2241 break;
2242
2243 case tid_DATAGRAM_INT:
2244 ZEND_ASSERT(!"datagram");
2245 case tid_EOF_INT:
2246 return;
2247 }
2248 }
2249
2250 php_ion_decl(unserializer_php, Unserializer_PHP, php_ion_unserializer_php_dtor(obj));
2251
2252 static inline void php_ion_unserialize_ex(php_ion_unserializer *ser, zval *return_value)
2253 {
2254 if (ser->multi_seq) {
2255 array_init(return_value);
2256 }
2257
2258 do {
2259 zval tmp;
2260 ZVAL_NULL(&tmp);
2261 php_ion_globals_unserializer_step();
2262 php_ion_unserialize_zval(ser, &tmp, NULL);
2263 php_ion_globals_unserializer_exit();
2264 ION_CATCH(zval_ptr_dtor(&tmp));
2265
2266 if (!ser->multi_seq) {
2267 RETURN_COPY_VALUE(&tmp);
2268 } else if (ser->type != tid_EOF) {
2269 zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &tmp);
2270 }
2271 } while (ser->type != tid_EOF);
2272 }
2273
2274 void php_ion_unserialize(php_ion_unserializer *ser, zval *zdata, zval *return_value)
2275 {
2276 zend_object *zo_opt = NULL, *zo_ser = NULL;
2277
2278 if (!ser) {
2279 zo_ser = create_ion_Unserializer_PHP(NULL);
2280 php_ion_unserializer_php *o_ser = php_ion_obj(unserializer_php, zo_ser);
2281 PTR_CHECK(o_ser);
2282 o_ser->unserializer.call_magic = true;
2283 php_ion_unserializer_php_ctor(o_ser);
2284 ION_CATCH();
2285 ser = &o_ser->unserializer;
2286 }
2287
2288 zend_object *zo_reader;
2289 php_ion_reader *reader;
2290 ZVAL_DEREF(zdata);
2291
2292 if (Z_TYPE_P(zdata) == IS_RESOURCE) {
2293 zo_reader = create_ion_Reader_Reader(ce_Reader_Stream_Reader);
2294 reader = php_ion_obj(reader, zo_reader);
2295 reader->type = STREAM_READER;
2296 php_stream_from_zval_no_verify(reader->stream.ptr, zdata);
2297 } else if (Z_TYPE_P(zdata) <= IS_STRING) {
2298 zo_reader = create_ion_Reader_Reader(ce_Reader_Buffer_Reader);
2299 reader = php_ion_obj(reader, zo_reader);
2300 reader->type = BUFFER_READER;
2301 reader->buffer = zval_get_string(zdata);
2302 } else {
2303 zend_throw_exception_ex(spl_ce_InvalidArgumentException, IERR_INVALID_ARG,
2304 "Invalid source to unserialize; expected string or resource");
2305 if (zo_ser) {
2306 OBJ_RELEASE(zo_ser);
2307 }
2308 return;
2309 }
2310
2311 if (ser->options) {
2312 zo_opt = reader->opt = create_ion_Reader_Options(NULL);
2313 php_ion_obj(reader_options, reader->opt)->opt = *ser->options;
2314 }
2315
2316 php_ion_reader_ctor(reader);
2317 ser->reader = reader->reader;
2318
2319 if (!EG(exception)) {
2320 php_ion_unserialize_ex(ser, return_value);
2321 }
2322
2323 OBJ_RELEASE(zo_reader);
2324 if (zo_opt) {
2325 OBJ_RELEASE(zo_opt);
2326 }
2327 if (zo_ser) {
2328 OBJ_RELEASE(zo_ser);
2329 }
2330 }
2331
2332 static inline zval *php_ion_global_symbol_fetch_by_enum(zend_string *name)
2333 {
2334 zval *zgs = zend_hash_find(&php_ion_globals.symbol.cache, name);
2335 if (!zgs) {
2336 zval *zid = zend_hash_find(&g_sym_map, name);
2337 if (zid) {
2338 zval *zss = zend_hash_index_find(&g_sym_hash, Z_LVAL_P(zid));
2339 if (zss) {
2340 zval zsym;
2341 object_init_ex(&zsym, ce_Symbol);
2342 php_ion_symbol *sym = php_ion_obj(symbol, Z_OBJ(zsym));
2343 sym->sym.sid = Z_LVAL_P(zid);
2344 sym->value = zval_get_string(zss);
2345 php_ion_symbol_ctor(sym);
2346 zgs = zend_hash_add(&php_ion_globals.symbol.cache, name, &zsym);
2347 }
2348 }
2349 }
2350 return zgs;
2351 }