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