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