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