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