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