2f80d8467a5e215917fc6530607993db9908b8aa
[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 static inline void php_ion_unserialize_hash(php_ion_unserializer *ser, zval *return_value)
1495 {
1496 zend_hash_next_index_insert(ser->ids, return_value);
1497
1498 ION_CHECK(ion_reader_step_in(ser->reader));
1499
1500 while (true) {
1501 ION_TYPE typ;
1502 ION_CHECK(ion_reader_next(ser->reader, &typ));
1503
1504 if (typ == tid_EOF) {
1505 break;
1506 }
1507
1508 zend_string *key;
1509 php_ion_unserialize_field_name(ser, &key);
1510 ION_CATCH();
1511
1512 zval zvalue;
1513 php_ion_unserialize_zval(ser, &zvalue, &typ);
1514 ION_CATCH(zend_string_release(key));
1515
1516 zend_symtable_update(HASH_OF(return_value), key, &zvalue);
1517
1518 zend_string_release(key);
1519 }
1520
1521 ION_CHECK(ion_reader_step_out(ser->reader));
1522 }
1523
1524 static inline void verify_unserializer(php_ion_unserializer *ser, zend_object *zobject, zend_function **fn)
1525 {
1526 switch (ser->annotations.object_type) {
1527 case 'c':
1528 *fn = NULL;
1529 break;
1530
1531 case 'C':
1532 if (!can_call_custom_unserialize(ser, zobject, fn)) {
1533 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_INVALID_TOKEN,
1534 "Could not find custom serializer method of %s", ser->annotations.object_class->val);
1535 }
1536 break;
1537
1538 case 'O':
1539 if (!can_call_magic_unserialize(ser, zobject->ce)) {
1540 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_INVALID_TOKEN,
1541 "Could not find method %s::__unserialize()", ser->annotations.object_class->val);
1542 }
1543 *fn = zobject->ce->__unserialize;
1544 break;
1545
1546 default:
1547 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_INVALID_TOKEN,
1548 "Invalid object type %c", ser->annotations.object_type);
1549 }
1550 }
1551
1552 static inline void php_ion_unserialize_object(php_ion_unserializer *ser, zval *return_value)
1553 {
1554 // backup possible backref to array returned by magic/custom __serialize()
1555 zval *input = zend_hash_next_index_insert(ser->tmp, return_value);
1556
1557 php_ion_unserialize_class(ser, return_value);
1558 ION_CATCH();
1559
1560 zend_function *fn = NULL;
1561 zend_object *zobject = Z_OBJ_P(return_value);
1562 verify_unserializer(ser, zobject, &fn);
1563 ION_CATCH();
1564
1565 // plain object
1566 if (!fn) {
1567 php_ion_unserialize_props(ser, return_value);
1568 return;
1569 }
1570
1571 // magic object
1572 if (Z_TYPE_P(input) != IS_ARRAY) {
1573 zval_ptr_dtor(input);
1574 array_init(input);
1575 zend_hash_real_init_mixed(Z_ARRVAL_P(input));
1576 php_ion_unserialize_hash(ser, input);
1577 ION_CATCH();
1578 }
1579 zval rv;
1580 ZVAL_NULL(&rv);
1581 zend_call_method_with_1_params(zobject, zobject->ce, &fn, "", &rv, input);
1582 zval_ptr_dtor(&rv);
1583 }
1584
1585 static inline void php_ion_unserialize_struct(php_ion_unserializer *ser, zval *return_value)
1586 {
1587 if (ser->annotations.object_class) {
1588 switch (ser->annotations.object_type) {
1589 case 'S':
1590 php_ion_unserialize_object_iface(ser, return_value);
1591 break;
1592 case 'E':
1593 php_ion_unserialize_object_enum(ser, return_value);
1594 break;
1595 default:
1596 php_ion_unserialize_object(ser, return_value);
1597 }
1598 } else if (!ser->annotations.object_type) {
1599 array_init(return_value);
1600 php_ion_unserialize_hash(ser, return_value);
1601 } else if (ser->annotations.object_type == 'o') {
1602 object_init(return_value);
1603 php_ion_unserialize_hash(ser, return_value);
1604 } else {
1605 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_INVALID_TOKEN,
1606 "Invalid object annotation %c::", ser->annotations.object_type);
1607 }
1608 }
1609
1610 static inline void php_ion_unserialize_list(php_ion_unserializer *ser, zval *return_value)
1611 {
1612 ION_CHECK(ion_reader_step_in(ser->reader));
1613 array_init(return_value);
1614 zend_hash_next_index_insert(ser->ids, return_value);
1615
1616 while (true) {
1617 ION_TYPE typ;
1618 ION_CHECK(ion_reader_next(ser->reader, &typ));
1619
1620 if (typ == tid_EOF) {
1621 break;
1622 }
1623
1624 zval next;
1625 php_ion_unserialize_zval(ser, &next, &typ);
1626 ION_CATCH();
1627
1628 zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &next);
1629 }
1630
1631 ION_CHECK(ion_reader_step_out(ser->reader));
1632 }
1633
1634 static inline void php_ion_reader_read_lob(ION_READER *reader, zval *return_value)
1635 {
1636 zend_string *zstr = zend_string_alloc(0x1000, 0);
1637 again:
1638 SIZE read = 0;
1639 iERR err = ion_reader_read_lob_bytes(reader, (BYTE *) zstr->val, zstr->len, &read);
1640 if (err == IERR_BUFFER_TOO_SMALL) {
1641 zstr = zend_string_extend(zstr, zstr->len << 2, 0);
1642 goto again;
1643 }
1644 ION_CHECK(err, zend_string_release(zstr));
1645 if (zstr->len > read) {
1646 zstr->val[read] = 0;
1647 zstr = zend_string_truncate(zstr, read, 0);
1648 }
1649 RETURN_STR(zstr);
1650 }
1651
1652 static inline void php_ion_reader_read_timestamp(ION_READER *reader, ION_READER_OPTIONS *opt, zval *return_value)
1653 {
1654 ION_TIMESTAMP ts;
1655 ION_CHECK(ion_reader_read_timestamp(reader, &ts));
1656
1657 object_init_ex(return_value, ce_Timestamp);
1658 php_ion_timestamp *ts_obj = php_ion_obj(timestamp, Z_OBJ_P(return_value));
1659
1660 zend_string *fmt = NULL;
1661 decContext *ctx = opt ? opt->decimal_context : NULL;
1662 ts_obj->time = php_time_from_ion(&ts, ctx, &fmt);
1663 php_ion_timestamp_ctor(ts_obj, ts.precision, fmt, NULL, NULL);
1664 zend_string_release(fmt);
1665
1666 OBJ_CHECK(ts_obj);
1667 }
1668
1669 static inline void php_ion_reader_read_int(ION_READER *reader, zval *return_value)
1670 {
1671 ION_INT *num = NULL;
1672 ION_CHECK(ion_int_alloc(reader, &num));
1673 ION_CHECK(ion_reader_read_ion_int(reader, num));
1674
1675 // TODO: SIZEOF_ZEND_LONG == 4
1676 int64_t i64;
1677 iERR err = ion_int_to_int64(num, &i64);
1678 switch (err) {
1679 case IERR_OK:
1680 RETVAL_LONG(i64);
1681 goto done;
1682
1683 case IERR_NUMERIC_OVERFLOW:
1684 SIZE max, len;
1685 ION_CHECK(ion_int_char_length(num, &max));
1686 zend_string *zs = zend_string_alloc(max, 0);
1687
1688 err = ion_int_to_char(num, (BYTE *) zs->val, max, &len);
1689 zs->val[zs->len = len] = 0;
1690 RETVAL_STR(zs);
1691 /* fall through */
1692
1693 default:
1694 done:
1695 ion_int_free(num);
1696 ION_CHECK(err);
1697 }
1698 }
1699
1700 static inline void php_ion_unserialize_backref(php_ion_unserializer *ser, zval *return_value)
1701 {
1702 zval *backref = zend_hash_index_find(ser->ids, Z_LVAL_P(return_value));
1703
1704 if (backref) {
1705 ZVAL_COPY_VALUE(return_value, backref);
1706 zend_hash_next_index_insert(ser->addref, return_value);
1707 } else {
1708 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_INTERNAL_ERROR,
1709 "Could not find back reference %ld", Z_LVAL_P(return_value));
1710 }
1711 }
1712
1713 static inline void php_ion_unserialize_annotations(php_ion_unserializer *ser)
1714 {
1715 memset(&ser->annotations, 0, sizeof(ser->annotations));
1716
1717 int32_t ann_cnt;
1718 ION_CHECK(ion_reader_get_annotation_count(ser->reader, &ann_cnt));
1719 for (int32_t i = 0; i < ann_cnt; ++i) {
1720 ION_STRING ann_str;
1721 ION_CHECK(ion_reader_get_an_annotation(ser->reader, i, &ann_str));
1722
1723 if (ann_str.length != 1) {
1724 continue;
1725 }
1726
1727 switch (*ann_str.value) {
1728 case 'R':
1729 if (ser->annotations.makeref) {
1730 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_INVALID_SYNTAX,
1731 "Invalid multiple reference annotations");
1732 return;
1733 }
1734 ser->annotations.makeref = true;
1735 break;
1736
1737 case 'r':
1738 if (ser->annotations.backref) {
1739 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_INVALID_SYNTAX,
1740 "Invalid multiple back reference annotations");
1741 return;
1742 }
1743 ser->annotations.backref = true;
1744 break;
1745
1746 case 'p':
1747 if (ser->annotations.object_prop) {
1748 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_INVALID_SYNTAX,
1749 "Invalid multiple object property annotations");
1750 return;
1751 }
1752 ser->annotations.object_prop = true;
1753
1754 ION_STRING prop_class;
1755 ION_CHECK(ion_reader_get_an_annotation(ser->reader, ++i, &prop_class));
1756 ser->annotations.property_class = zend_string_from_ion(&prop_class);
1757
1758 zval zptmp;
1759 ZVAL_STR(&zptmp, ser->annotations.property_class);
1760 zend_hash_next_index_insert(ser->tmp, &zptmp);
1761 break;
1762
1763 case 'E':
1764 case 'S':
1765 case 'O':
1766 case 'C':
1767 case 'o':
1768 case 'c':
1769 if (ser->annotations.object_type) {
1770 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_INVALID_SYNTAX,
1771 "Invalid multiple object type annotations: %c::%c",
1772 ser->annotations.object_type, *ann_str.value);
1773 return;
1774 }
1775 if ('o' != (ser->annotations.object_type = *ann_str.value)) {
1776 ION_STRING class_name;
1777 ION_CHECK(ion_reader_get_an_annotation(ser->reader, ++i, &class_name));
1778 ser->annotations.object_class = zend_string_from_ion(&class_name);
1779
1780 zval zctmp;
1781 ZVAL_STR(&zctmp, ser->annotations.object_class);
1782 zend_hash_next_index_insert(ser->tmp, &zctmp);
1783 }
1784 break;
1785 }
1786
1787 // sanity checks
1788 if (ser->annotations.object_type && ser->annotations.object_type != 'o' && !ser->annotations.object_class) {
1789 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_INVALID_SYNTAX,
1790 "Invalid object annotation without class name: %c::", ser->annotations.object_type);
1791 return;
1792 }
1793 if (ser->annotations.object_type == 'o' && ser->annotations.object_class) {
1794 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_INVALID_SYNTAX,
1795 "Invalid object annotation with class name: o::%s", ser->annotations.object_class->val);
1796 return;
1797 }
1798 }
1799 }
1800
1801 static inline void php_ion_unserialize_zval(php_ion_unserializer *ser, zval *return_value, ION_TYPE *typ)
1802 {
1803 if (typ) {
1804 memcpy(&ser->type, typ, sizeof(ser->type));
1805 } else {
1806 typ = &ser->type;
1807 ION_CHECK(ion_reader_next(ser->reader, typ));
1808 }
1809
1810 php_ion_unserialize_annotations(ser);
1811 ION_CATCH();
1812
1813 if (ser->annotations.makeref) {
1814 ZVAL_MAKE_REF(return_value);
1815 zend_hash_next_index_insert(ser->ids, return_value);
1816 ZVAL_DEREF(return_value);
1817 }
1818
1819 if (ION_TYPE_INT(*typ) > 0) {
1820 BOOL is_null;
1821 ION_CHECK(ion_reader_is_null(ser->reader, &is_null));
1822 if (is_null) {
1823 RETURN_NULL();
1824 }
1825 }
1826
1827 switch (ION_TYPE_INT(*typ)) {
1828 case tid_NULL_INT:
1829 ION_CHECK(ion_reader_read_null(ser->reader, typ));
1830 RETURN_NULL();
1831
1832 case tid_BOOL_INT:
1833 BOOL bval;
1834 ION_CHECK(ion_reader_read_bool(ser->reader, &bval));
1835 RETURN_BOOL(bval);
1836
1837 case tid_INT_INT:
1838 php_ion_reader_read_int(ser->reader, return_value);
1839 if (ser->annotations.backref) {
1840 ION_CATCH();
1841 php_ion_unserialize_backref(ser, return_value);
1842 }
1843 if (ser->annotations.object_type) {
1844 if (!ser->annotations.backref) {
1845 zend_throw_exception_ex(spl_ce_RuntimeException, IERR_INVALID_SYNTAX,
1846 "Invalid object type annotation: %c::" ZEND_LONG_FMT,
1847 ser->annotations.object_type, Z_LVAL_P(return_value));
1848 return;
1849 }
1850 goto unserialize_struct;
1851 }
1852 return;
1853
1854 case tid_FLOAT_INT:
1855 double d;
1856 ION_CHECK(ion_reader_read_double(ser->reader, &d));
1857 RETURN_DOUBLE(d);
1858
1859 case tid_DECIMAL_INT:
1860 object_init_ex(return_value, ce_Decimal);
1861 php_ion_decimal *dec = php_ion_obj(decimal, Z_OBJ_P(return_value));
1862 ION_CHECK(ion_reader_read_ion_decimal(ser->reader, &dec->dec));
1863 php_ion_decimal_ctor(dec);
1864 zend_hash_next_index_insert(ser->ids, return_value);
1865 return;
1866
1867 case tid_TIMESTAMP_INT:
1868 php_ion_reader_read_timestamp(ser->reader, ser->options, return_value);
1869 zend_hash_next_index_insert(ser->ids, return_value);
1870 return;
1871
1872 case tid_SYMBOL_INT:
1873 ION_SYMBOL sym;
1874 ION_CHECK(ion_reader_read_ion_symbol(ser->reader, &sym));
1875 php_ion_symbol_zval(&sym, return_value);
1876 if (ser->annotations.object_type) {
1877 zend_hash_next_index_insert(ser->tmp, return_value);
1878 goto unserialize_struct;
1879 }
1880 zend_hash_next_index_insert(ser->ids, return_value);
1881 return;
1882
1883 case tid_STRING_INT:
1884 ION_STRING str;
1885 ION_CHECK(ion_reader_read_string(ser->reader, &str));
1886 RETVAL_STRINGL((char *) str.value, str.length);
1887 if (ser->annotations.object_type) {
1888 zend_hash_next_index_insert(ser->tmp, return_value);
1889 goto unserialize_struct;
1890 }
1891 zend_hash_next_index_insert(ser->ids, return_value);
1892 return;
1893
1894 case tid_CLOB_INT:
1895 case tid_BLOB_INT:
1896 php_ion_reader_read_lob(ser->reader, return_value);
1897 if (ser->annotations.object_type) {
1898 zend_hash_next_index_insert(ser->tmp, return_value);
1899 goto unserialize_struct;
1900 }
1901 zend_hash_next_index_insert(ser->ids, return_value);
1902 return;
1903
1904 case tid_LIST_INT:
1905 case tid_SEXP_INT: // FIXME
1906 php_ion_unserialize_list(ser, return_value);
1907 if (!ser->annotations.object_type) {
1908 return;
1909 }
1910 /* fall through */
1911
1912 case tid_STRUCT_INT:
1913 unserialize_struct: ;
1914 php_ion_unserialize_struct(ser, return_value);
1915 return;
1916
1917 case tid_none_INT:
1918 ZEND_ASSERT(0);
1919 break;
1920
1921 case tid_DATAGRAM_INT:
1922 ZEND_ASSERT(!"datagram");
1923 case tid_EOF_INT:
1924 return;
1925 }
1926 }
1927
1928 php_ion_decl(unserializer_php, Unserializer_PHP, php_ion_unserializer_php_dtor(obj));
1929
1930 static inline void php_ion_unserialize_ex(php_ion_unserializer *ser, zval *return_value)
1931 {
1932 if (ser->multi_seq) {
1933 array_init(return_value);
1934 }
1935
1936 do {
1937 zval tmp;
1938 ZVAL_NULL(&tmp);
1939 php_ion_globals_unserializer_step();
1940 php_ion_unserialize_zval(ser, &tmp, NULL);
1941 php_ion_globals_unserializer_exit();
1942 ION_CATCH(zval_ptr_dtor(&tmp));
1943
1944 if (!ser->multi_seq) {
1945 RETURN_COPY_VALUE(&tmp);
1946 } else if (ser->type != tid_EOF) {
1947 zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &tmp);
1948 }
1949 } while (ser->type != tid_EOF);
1950 }
1951
1952 void php_ion_unserialize(php_ion_unserializer *ser, zval *zdata, zval *return_value)
1953 {
1954 zend_object *zo_opt = NULL, *zo_ser = NULL;
1955
1956 if (!ser) {
1957 zo_ser = create_ion_Unserializer_PHP(NULL);
1958 php_ion_unserializer_php *o_ser = php_ion_obj(unserializer_php, zo_ser);
1959 PTR_CHECK(o_ser);
1960 o_ser->unserializer.call_magic = true;
1961 php_ion_unserializer_php_ctor(o_ser);
1962 ION_CATCH();
1963 ser = &o_ser->unserializer;
1964 }
1965
1966 zend_object *zo_reader;
1967 php_ion_reader *reader;
1968 ZVAL_DEREF(zdata);
1969
1970 if (Z_TYPE_P(zdata) == IS_RESOURCE) {
1971 zo_reader = create_ion_Reader_Reader(ce_Reader_Stream_Reader);
1972 reader = php_ion_obj(reader, zo_reader);
1973 reader->type = STREAM_READER;
1974 php_stream_from_zval_no_verify(reader->stream.ptr, zdata);
1975 } else if (Z_TYPE_P(zdata) <= IS_STRING) {
1976 zo_reader = create_ion_Reader_Reader(ce_Reader_Buffer_Reader);
1977 reader = php_ion_obj(reader, zo_reader);
1978 reader->type = BUFFER_READER;
1979 reader->buffer = zval_get_string(zdata);
1980 } else {
1981 zend_throw_exception_ex(spl_ce_InvalidArgumentException, IERR_INVALID_ARG,
1982 "Invalid source to unserialize; expected string or resource");
1983 if (zo_ser) {
1984 OBJ_RELEASE(zo_ser);
1985 }
1986 return;
1987 }
1988
1989 if (ser->options) {
1990 zo_opt = reader->opt = create_ion_Reader_Options(NULL);
1991 php_ion_obj(reader_options, reader->opt)->opt = *ser->options;
1992 }
1993
1994 php_ion_reader_ctor(reader);
1995 ser->reader = reader->reader;
1996
1997 if (!EG(exception)) {
1998 php_ion_unserialize_ex(ser, return_value);
1999 }
2000
2001 OBJ_RELEASE(zo_reader);
2002 if (zo_opt) {
2003 OBJ_RELEASE(zo_opt);
2004 }
2005 if (zo_ser) {
2006 OBJ_RELEASE(zo_ser);
2007 }
2008 }