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