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