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