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