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