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