Ruby 4.1.0dev (2026-09-26 revision b49347c28a15c475eba951ce426564647aeeacf0)
marshal.c (b49347c28a15c475eba951ce426564647aeeacf0)
1/**********************************************************************
2
3 marshal.c -
4
5 $Author$
6 created at: Thu Apr 27 16:30:01 JST 1995
7
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
9
10**********************************************************************/
11
12#include "ruby/internal/config.h"
13
14#include <math.h>
15#ifdef HAVE_FLOAT_H
16#include <float.h>
17#endif
18#ifdef HAVE_IEEEFP_H
19#include <ieeefp.h>
20#endif
21
22#include "encindex.h"
23#include "id_table.h"
24#include "internal.h"
25#include "internal/array.h"
26#include "internal/bignum.h"
27#include "internal/class.h"
28#include "internal/encoding.h"
29#include "internal/error.h"
30#include "internal/hash.h"
31#include "internal/marshal.h"
32#include "internal/numeric.h"
33#include "internal/object.h"
34#include "internal/re.h"
35#include "internal/st.h"
36#include "internal/struct.h"
37#include "internal/symbol.h"
38#include "internal/util.h"
39#include "internal/vm.h"
40#include "ruby/io.h"
41#include "ruby/ruby.h"
42#include "ruby/st.h"
43#include "ruby/util.h"
44#include "builtin.h"
45#include "shape.h"
47
48#define BITSPERSHORT (2*CHAR_BIT)
49#define SHORTMASK ((1<<BITSPERSHORT)-1)
50#define SHORTDN(x) RSHIFT((x),BITSPERSHORT)
51
52#if SIZEOF_SHORT == SIZEOF_BDIGIT
53#define SHORTLEN(x) (x)
54#else
55static size_t
56shortlen(size_t len, BDIGIT *ds)
57{
58 BDIGIT num;
59 int offset = 0;
60
61 num = ds[len-1];
62 while (num) {
63 num = SHORTDN(num);
64 offset++;
65 }
66 return (len - 1)*SIZEOF_BDIGIT/2 + offset;
67}
68#define SHORTLEN(x) shortlen((x),d)
69#endif
70
71#define MARSHAL_MAJOR 4
72#define MARSHAL_MINOR 8
73
74#define TYPE_NIL '0'
75#define TYPE_TRUE 'T'
76#define TYPE_FALSE 'F'
77#define TYPE_FIXNUM 'i'
78
79#define TYPE_EXTENDED 'e'
80#define TYPE_UCLASS 'C'
81#define TYPE_OBJECT 'o'
82#define TYPE_DATA 'd'
83#define TYPE_USERDEF 'u'
84#define TYPE_USRMARSHAL 'U'
85#define TYPE_FLOAT 'f'
86#define TYPE_BIGNUM 'l'
87#define TYPE_STRING '"'
88#define TYPE_REGEXP '/'
89#define TYPE_ARRAY '['
90#define TYPE_HASH '{'
91#define TYPE_HASH_DEF '}'
92#define TYPE_STRUCT 'S'
93#define TYPE_MODULE_OLD 'M'
94#define TYPE_CLASS 'c'
95#define TYPE_MODULE 'm'
96
97#define TYPE_SYMBOL ':'
98#define TYPE_SYMLINK ';'
99
100#define TYPE_IVAR 'I'
101#define TYPE_LINK '@'
102
103static ID s_dump, s_load, s_mdump, s_mload;
104static ID s_dump_data, s_load_data, s_call;
105static ID s_getbyte, s_read, s_write, s_binmode;
106static ID s_encoding_short, s_ruby2_keywords_flag;
107#define s_encoding_long rb_id_encoding()
108
109#define name_s_dump "_dump"
110#define name_s_load "_load"
111#define name_s_mdump "marshal_dump"
112#define name_s_mload "marshal_load"
113#define name_s_dump_data "_dump_data"
114#define name_s_load_data "_load_data"
115#define name_s_call "call"
116#define name_s_getbyte "getbyte"
117#define name_s_read "read"
118#define name_s_write "write"
119#define name_s_binmode "binmode"
120#define name_s_encoding_short "E"
121#define name_s_encoding_long "encoding"
122#define name_s_ruby2_keywords_flag "K"
123
124typedef struct {
125 VALUE newclass;
126 VALUE oldclass;
127 VALUE (*dumper)(VALUE);
128 VALUE (*loader)(VALUE, VALUE);
129} marshal_compat_t;
130
131static st_table *compat_allocator_tbl;
132static VALUE compat_allocator_tbl_wrapper;
133static VALUE rb_marshal_dump_limited(VALUE obj, VALUE port, int limit);
134static VALUE rb_marshal_load_with_proc(VALUE port, VALUE proc, bool freeze);
135
136static st_table *compat_allocator_table(void);
137
138void
139rb_marshal_define_compat(VALUE newclass, VALUE oldclass, VALUE (*dumper)(VALUE), VALUE (*loader)(VALUE, VALUE))
140{
141 marshal_compat_t *compat;
142 rb_alloc_func_t allocator = rb_get_alloc_func(newclass);
143
144 if (!allocator) {
145 rb_raise(rb_eTypeError, "no allocator");
146 }
147
148 compat_allocator_table();
149 compat = ALLOC(marshal_compat_t);
150 compat->newclass = newclass;
151 compat->oldclass = oldclass;
152 compat->dumper = dumper;
153 compat->loader = loader;
154
155 st_insert(compat_allocator_table(), (st_data_t)allocator, (st_data_t)compat);
156 RB_OBJ_WRITTEN(compat_allocator_tbl_wrapper, Qundef, newclass);
157 RB_OBJ_WRITTEN(compat_allocator_tbl_wrapper, Qundef, oldclass);
158}
159
160/* The rb_marshal_define_compat entry for an instance of klass, if any, so the Ractor
161 * courier can dump and load it the way Marshal does. */
162bool
163rb_marshal_compat_lookup(VALUE klass, VALUE (**dumper)(VALUE), VALUE (**loader)(VALUE, VALUE))
164{
165 st_data_t data;
166 rb_alloc_func_t allocator = RCLASS_SINGLETON_P(klass) ? 0 : rb_get_alloc_func(klass);
167 if (!allocator || !st_lookup(compat_allocator_tbl, (st_data_t)allocator, &data)) return false;
168 marshal_compat_t *compat = (marshal_compat_t *)data;
169 if (!compat->dumper || !compat->loader) return false;
170 if (dumper) *dumper = compat->dumper;
171 if (loader) *loader = compat->loader;
172 return true;
173}
174
175struct dump_arg {
176 VALUE str, dest;
177 st_table symbols;
178 st_table data;
179 st_table userdefs;
180 st_table encodings;
181 st_table compat_tbl;
182 bool has_symbols;
183 bool has_data;
184 bool has_userdefs;
185 bool has_encodings;
186 bool has_compat_tbl;
187 st_index_t num_entries;
188};
189
190struct dump_call_arg {
191 VALUE obj;
192 struct dump_arg *arg;
193 int limit;
194};
195
196static VALUE
197check_dump_arg(VALUE ret, struct dump_arg *arg, const char *name)
198{
199 if (!arg->has_symbols) {
200 rb_raise(rb_eRuntimeError, "Marshal.dump reentered at %s",
201 name);
202 }
203 return ret;
204}
205
206static VALUE
207check_userdump_arg(VALUE obj, ID sym, int argc, const VALUE *argv,
208 struct dump_arg *arg, const char *name)
209{
210 VALUE ret = rb_funcallv(obj, sym, argc, argv);
211 VALUE klass = CLASS_OF(obj);
212 if (CLASS_OF(ret) == klass) {
213 rb_raise(rb_eRuntimeError, "%"PRIsVALUE"#%s returned same class instance",
214 klass, name);
215 }
216 return check_dump_arg(ret, arg, name);
217}
218
219#define dump_funcall(arg, obj, sym, argc, argv) \
220 check_userdump_arg(obj, sym, argc, argv, arg, name_##sym)
221#define dump_check_funcall(arg, obj, sym, argc, argv) \
222 check_dump_arg(rb_check_funcall(obj, sym, argc, argv), arg, name_##sym)
223
224static void clear_dump_arg(struct dump_arg *arg);
225
226static void
227mark_dump_arg(void *ptr)
228{
229 struct dump_arg *p = ptr;
230 if (!p->has_symbols)
231 return;
232 rb_mark_set(&p->symbols);
233 if (p->has_data) rb_mark_set(&p->data);
234 if (p->has_compat_tbl) rb_mark_hash(&p->compat_tbl);
235 if (p->has_userdefs) rb_mark_set(&p->userdefs);
236 rb_gc_mark(p->str);
237}
238
239static void
240free_dump_arg(void *ptr)
241{
242 clear_dump_arg(ptr);
243}
244
245static size_t
246memsize_dump_arg(const void *ptr)
247{
248 const struct dump_arg *p = (struct dump_arg *)ptr;
249 size_t memsize = 0;
250 if (p->has_symbols) memsize += rb_st_allocated_memsize(&p->symbols);
251 if (p->has_data) memsize += rb_st_allocated_memsize(&p->data);
252 if (p->has_compat_tbl) memsize += rb_st_allocated_memsize(&p->compat_tbl);
253 if (p->has_userdefs) memsize += rb_st_allocated_memsize(&p->userdefs);
254 if (p->has_encodings) memsize += rb_st_allocated_memsize(&p->encodings);
255 return memsize;
256}
257
258static const rb_data_type_t dump_arg_data = {
259 "dump_arg",
260 {mark_dump_arg, free_dump_arg, memsize_dump_arg,},
261 0, 0, RUBY_TYPED_THREAD_SAFE_FREE | RUBY_TYPED_EMBEDDABLE
262};
263
264static VALUE
265must_not_be_anonymous(const char *type, VALUE path)
266{
267 char *n = RSTRING_PTR(path);
268
269 if (!rb_enc_asciicompat(rb_enc_get(path))) {
270 /* cannot occur? */
271 rb_raise(rb_eTypeError, "can't dump non-ascii %s name % "PRIsVALUE,
272 type, path);
273 }
274 if (n[0] == '#') {
275 rb_raise(rb_eTypeError, "can't dump anonymous %s % "PRIsVALUE,
276 type, path);
277 }
278 return path;
279}
280
281static VALUE
282class2path(VALUE klass)
283{
284 VALUE path = rb_class_path(klass);
285
286 must_not_be_anonymous((RB_TYPE_P(klass, T_CLASS) ? "class" : "module"), path);
287 if (rb_path_to_class(path) != rb_class_real(klass)) {
288 rb_raise(rb_eTypeError, "% "PRIsVALUE" can't be referred to", path);
289 }
290 return path;
291}
292
293int ruby_marshal_write_long(long x, char *buf);
294static void w_long(long, struct dump_arg*);
295static int w_encoding(VALUE encname, struct dump_call_arg *arg);
296static VALUE encoding_name(VALUE obj, struct dump_arg *arg);
297
298static void
299w_nbyte(const char *s, long n, struct dump_arg *arg)
300{
301 VALUE buf = arg->str;
302 rb_str_buf_cat(buf, s, n);
303 if (arg->dest && RSTRING_LEN(buf) >= BUFSIZ) {
304 rb_io_write(arg->dest, buf);
305 rb_str_resize(buf, 0);
306 }
307}
308
309static void
310w_byte(char c, struct dump_arg *arg)
311{
312 w_nbyte(&c, 1, arg);
313}
314
315static void
316w_bytes(const char *s, long n, struct dump_arg *arg)
317{
318 w_long(n, arg);
319 w_nbyte(s, n, arg);
320}
321
322/* Like w_bytes, but for a Ruby String. Flushing the dump buffer in w_long
323 * can run arbitrary Ruby code through the destination IO's write method,
324 * which can modify the string, so re-validate it before using the pointer. */
325static void
326w_str_bytes(VALUE str, struct dump_arg *arg)
327{
328 long len = RSTRING_LEN(str);
329 const char *ptr = RSTRING_PTR(str);
330 w_long(len, arg);
331 if (RSTRING_PTR(str) != ptr || RSTRING_LEN(str) != len) {
332 rb_raise(rb_eRuntimeError, "string modified during dump");
333 }
334 w_nbyte(ptr, len, arg);
335}
336
337#define w_cstr(s, arg) w_bytes((s), strlen(s), (arg))
338
339static void
340w_short(int x, struct dump_arg *arg)
341{
342 w_byte((char)((x >> 0) & 0xff), arg);
343 w_byte((char)((x >> 8) & 0xff), arg);
344}
345
346static void
347w_long(long x, struct dump_arg *arg)
348{
349 char buf[sizeof(long)+1];
350 int i = ruby_marshal_write_long(x, buf);
351 if (i < 0) {
352 rb_raise(rb_eTypeError, "long too big to dump");
353 }
354 w_nbyte(buf, i, arg);
355}
356
357int
358ruby_marshal_write_long(long x, char *buf)
359{
360 int i;
361
362#if SIZEOF_LONG > 4
363 if (!(RSHIFT(x, 31) == 0 || RSHIFT(x, 31) == -1)) {
364 /* big long does not fit in 4 bytes */
365 return -1;
366 }
367#endif
368
369 if (x == 0) {
370 buf[0] = 0;
371 return 1;
372 }
373 if (0 < x && x < 123) {
374 buf[0] = (char)(x + 5);
375 return 1;
376 }
377 if (-124 < x && x < 0) {
378 buf[0] = (char)((x - 5)&0xff);
379 return 1;
380 }
381 for (i=1;i<(int)sizeof(long)+1;i++) {
382 buf[i] = (char)(x & 0xff);
383 x = RSHIFT(x,8);
384 if (x == 0) {
385 buf[0] = i;
386 break;
387 }
388 if (x == -1) {
389 buf[0] = -i;
390 break;
391 }
392 }
393 return i+1;
394}
395
396#ifdef DBL_MANT_DIG
397#define DECIMAL_MANT (53-16) /* from IEEE754 double precision */
398
399#if DBL_MANT_DIG > 32
400#define MANT_BITS 32
401#elif DBL_MANT_DIG > 24
402#define MANT_BITS 24
403#elif DBL_MANT_DIG > 16
404#define MANT_BITS 16
405#else
406#define MANT_BITS 8
407#endif
408
409static double
410load_mantissa(double d, const char *buf, long len)
411{
412 if (!len) return d;
413 if (--len > 0 && !*buf++) { /* binary mantissa mark */
414 int e, s = d < 0, dig = 0;
415 unsigned long m;
416
417 modf(ldexp(frexp(fabs(d), &e), DECIMAL_MANT), &d);
418 do {
419 m = 0;
420 switch (len) {
421 default: m = *buf++ & 0xff; /* fall through */
422#if MANT_BITS > 24
423 case 3: m = (m << 8) | (*buf++ & 0xff); /* fall through */
424#endif
425#if MANT_BITS > 16
426 case 2: m = (m << 8) | (*buf++ & 0xff); /* fall through */
427#endif
428#if MANT_BITS > 8
429 case 1: m = (m << 8) | (*buf++ & 0xff);
430#endif
431 }
432 dig -= len < MANT_BITS / 8 ? 8 * (unsigned)len : MANT_BITS;
433 d += ldexp((double)m, dig);
434 } while ((len -= MANT_BITS / 8) > 0);
435 d = ldexp(d, e - DECIMAL_MANT);
436 if (s) d = -d;
437 }
438 return d;
439}
440#else
441#define load_mantissa(d, buf, len) (d)
442#endif
443
444#ifdef DBL_DIG
445#define FLOAT_DIG (DBL_DIG+2)
446#else
447#define FLOAT_DIG 17
448#endif
449
450static void
451w_float(double d, struct dump_arg *arg)
452{
453 char buf[FLOAT_DIG + (DECIMAL_MANT + 7) / 8 + 10];
454
455 if (isinf(d)) {
456 if (d < 0) w_cstr("-inf", arg);
457 else w_cstr("inf", arg);
458 }
459 else if (isnan(d)) {
460 w_cstr("nan", arg);
461 }
462 else if (d == 0.0) {
463 if (signbit(d)) w_cstr("-0", arg);
464 else w_cstr("0", arg);
465 }
466 else {
467 int decpt, sign, digs, len = 0;
468 char *e, *p = ruby_dtoa(d, 0, 0, &decpt, &sign, &e);
469 if (sign) buf[len++] = '-';
470 digs = (int)(e - p);
471 if (decpt < -3 || decpt > digs) {
472 buf[len++] = p[0];
473 if (--digs > 0) buf[len++] = '.';
474 memcpy(buf + len, p + 1, digs);
475 len += digs;
476 len += snprintf(buf + len, sizeof(buf) - len, "e%d", decpt - 1);
477 }
478 else if (decpt > 0) {
479 memcpy(buf + len, p, decpt);
480 len += decpt;
481 if ((digs -= decpt) > 0) {
482 buf[len++] = '.';
483 memcpy(buf + len, p + decpt, digs);
484 len += digs;
485 }
486 }
487 else {
488 buf[len++] = '0';
489 buf[len++] = '.';
490 if (decpt) {
491 memset(buf + len, '0', -decpt);
492 len -= decpt;
493 }
494 memcpy(buf + len, p, digs);
495 len += digs;
496 }
497 free(p);
498 w_bytes(buf, len, arg);
499 }
500}
501
502
503static VALUE
504w_encivar(VALUE str, struct dump_arg *arg)
505{
506 VALUE encname = encoding_name(str, arg);
507 if (NIL_P(encname) ||
508 is_ascii_string(str)) {
509 return Qnil;
510 }
511 w_byte(TYPE_IVAR, arg);
512 return encname;
513}
514
515static void
516w_encname(VALUE encname, struct dump_arg *arg)
517{
518 if (!NIL_P(encname)) {
519 struct dump_call_arg c_arg;
520 c_arg.limit = 1;
521 c_arg.arg = arg;
522 w_long(1L, arg);
523 w_encoding(encname, &c_arg);
524 }
525}
526
527static void
528w_symbol(VALUE sym, struct dump_arg *arg)
529{
530 st_data_t num;
531 VALUE encname;
532
533 if (st_lookup(&arg->symbols, sym, &num)) {
534 w_byte(TYPE_SYMLINK, arg);
535 w_long((long)num, arg);
536 }
537 else {
538 const VALUE orig_sym = sym;
539 sym = rb_sym2str(sym);
540 if (!sym) {
541 rb_raise(rb_eTypeError, "can't dump anonymous ID %"PRIdVALUE, sym);
542 }
543 encname = w_encivar(sym, arg);
544 w_byte(TYPE_SYMBOL, arg);
545 w_bytes(RSTRING_PTR(sym), RSTRING_LEN(sym), arg);
546 st_add_direct(&arg->symbols, orig_sym, arg->symbols.num_entries);
547 w_encname(encname, arg);
548 }
549}
550
551static void
552w_unique(VALUE s, struct dump_arg *arg)
553{
554 must_not_be_anonymous("class", s);
555 w_symbol(rb_str_intern(s), arg);
556}
557
558static void w_object(VALUE,struct dump_arg*,int);
559
560static int
561hash_each(VALUE key, VALUE value, VALUE v)
562{
563 struct dump_call_arg *arg = (void *)v;
564 w_object(key, arg->arg, arg->limit);
565 w_object(value, arg->arg, arg->limit);
566 return ST_CONTINUE;
567}
568
569#define SINGLETON_DUMP_UNABLE_P(klass) \
570 (rb_id_table_size(RCLASS_M_TBL(klass)) > 0 || \
571 rb_ivar_count(klass) > 0)
572
573static void
574w_extended(VALUE klass, struct dump_arg *arg, int check)
575{
576 if (check && RCLASS_SINGLETON_P(klass)) {
577 VALUE origin = RCLASS_ORIGIN(klass);
578 if (SINGLETON_DUMP_UNABLE_P(klass) ||
579 (origin != klass && SINGLETON_DUMP_UNABLE_P(origin))) {
580 rb_raise(rb_eTypeError, "singleton can't be dumped");
581 }
582 klass = RCLASS_SUPER(klass);
583 }
584 while (BUILTIN_TYPE(klass) == T_ICLASS) {
585 if (!RICLASS_IS_ORIGIN_P(klass) ||
586 BUILTIN_TYPE(RBASIC(klass)->klass) != T_MODULE) {
587 VALUE path = rb_class_name(RBASIC(klass)->klass);
588 w_byte(TYPE_EXTENDED, arg);
589 w_unique(path, arg);
590 }
591 klass = RCLASS_SUPER(klass);
592 }
593}
594
595static void
596w_class(char type, VALUE obj, struct dump_arg *arg, int check)
597{
598 VALUE path;
599 st_data_t real_obj;
600 VALUE klass;
601
602 if (arg->has_compat_tbl &&
603 st_lookup(&arg->compat_tbl, (st_data_t)obj, &real_obj)) {
604 obj = (VALUE)real_obj;
605 }
606 klass = CLASS_OF(obj);
607 w_extended(klass, arg, check);
608 w_byte(type, arg);
609 path = class2path(rb_class_real(klass));
610 w_unique(path, arg);
611}
612
613static void
614w_uclass(VALUE obj, VALUE super, struct dump_arg *arg)
615{
616 VALUE klass = CLASS_OF(obj);
617
618 w_extended(klass, arg, TRUE);
619 klass = rb_class_real(klass);
620 if (klass != super) {
621 w_byte(TYPE_UCLASS, arg);
622 w_unique(class2path(klass), arg);
623 }
624}
625
626static bool
627rb_hash_ruby2_keywords_p(VALUE obj)
628{
629 return (RHASH(obj)->basic.flags & RHASH_PASS_AS_KEYWORDS) != 0;
630}
631
632static void
633rb_hash_ruby2_keywords(VALUE obj)
634{
635 RHASH(obj)->basic.flags |= RHASH_PASS_AS_KEYWORDS;
636}
637
638/*
639 * if instance variable name `id` is a special name to be skipped,
640 * returns the name of it. otherwise it cannot be dumped (unnamed),
641 * returns `name` as-is. returns NULL for ID that can be dumped.
642 */
643static inline const char *
644skipping_ivar_name(const ID id, const char *name)
645{
646#define IS_SKIPPED_IVAR(idname) \
647 ((id == idname) && (name = name_##idname, true))
648 if (IS_SKIPPED_IVAR(s_encoding_short)) return name;
649 if (IS_SKIPPED_IVAR(s_ruby2_keywords_flag)) return name;
650 if (IS_SKIPPED_IVAR(s_encoding_long)) return name;
651 if (!rb_id2str(id)) return name;
652 return NULL;
653}
654
655struct w_ivar_arg {
656 struct dump_call_arg *dump;
657 st_data_t num_ivar;
658};
659
660static int
661w_obj_each(ID id, VALUE value, st_data_t a)
662{
663 struct w_ivar_arg *ivarg = (struct w_ivar_arg *)a;
664 struct dump_call_arg *arg = ivarg->dump;
665 const char unnamed[] = "", *ivname = skipping_ivar_name(id, unnamed);
666
667 if (ivname) {
668 if (ivname != unnamed) {
669 rb_warn("instance variable '%s' on class %"PRIsVALUE" is not dumped",
670 ivname, CLASS_OF(arg->obj));
671 }
672 return ST_CONTINUE;
673 }
674 --ivarg->num_ivar;
675 w_symbol(ID2SYM(id), arg->arg);
676 w_object(value, arg->arg, arg->limit);
677 return ST_CONTINUE;
678}
679
680static int
681obj_count_ivars(ID id, VALUE val, st_data_t a)
682{
683 if (!skipping_ivar_name(id, "") && UNLIKELY(!++*(st_index_t *)a)) {
684 rb_raise(rb_eRuntimeError, "too many instance variables");
685 }
686 return ST_CONTINUE;
687}
688
689static VALUE
690encoding_name(VALUE obj, struct dump_arg *arg)
691{
692 if (rb_enc_capable(obj)) {
693 int encidx = rb_enc_get_index(obj);
694 rb_encoding *enc = 0;
695 st_data_t name;
696
697 if (encidx <= 0 || !(enc = rb_enc_from_index(encidx))) {
698 return Qnil;
699 }
700
701 /* special treatment for US-ASCII and UTF-8 */
702 if (encidx == rb_usascii_encindex()) {
703 return Qfalse;
704 }
705 else if (encidx == rb_utf8_encindex()) {
706 return Qtrue;
707 }
708
709 if (arg->has_encodings) {
710 if (st_lookup(&arg->encodings, (st_data_t)rb_enc_name(enc), &name)) {
711 return (VALUE)name;
712 }
713 }
714 else {
715 st_init_existing_strtable_with_size(&arg->encodings, 1);
716 arg->has_encodings = true;
717 }
718
719 name = (st_data_t)rb_str_new_cstr(rb_enc_name(enc));
720 st_insert(&arg->encodings, (st_data_t)rb_enc_name(enc), name);
721 return (VALUE)name;
722 }
723 else {
724 return Qnil;
725 }
726}
727
728static int
729w_encoding(VALUE encname, struct dump_call_arg *arg)
730{
731 int limit = arg->limit;
732 if (limit >= 0) ++limit;
733 switch (encname) {
734 case Qfalse:
735 case Qtrue:
736 w_symbol(ID2SYM(s_encoding_short), arg->arg);
737 w_object(encname, arg->arg, limit);
738 return 1;
739 case Qnil:
740 return 0;
741 }
742 w_symbol(ID2SYM(rb_id_encoding()), arg->arg);
743 w_object(encname, arg->arg, limit);
744 return 1;
745}
746
747static st_index_t
748has_ivars(VALUE obj, VALUE encname, VALUE *ivobj)
749{
750 st_index_t num = !NIL_P(encname);
751
752 if (SPECIAL_CONST_P(obj)) goto generic;
753 switch (BUILTIN_TYPE(obj)) {
754 case T_OBJECT:
755 case T_CLASS:
756 case T_MODULE:
757 break; /* counted elsewhere */
758 case T_HASH:
759 if (rb_hash_ruby2_keywords_p(obj)) ++num;
760 /* fall through */
761 default:
762 generic:
763 rb_ivar_foreach(obj, obj_count_ivars, (st_data_t)&num);
764 if (num) *ivobj = obj;
765 }
766
767 return num;
768}
769
770static void
771w_ivar_each(VALUE obj, st_index_t num, struct dump_call_arg *arg)
772{
773 struct w_ivar_arg ivarg = {arg, num};
774 if (!num) return;
775 rb_ivar_foreach_buffered(obj, w_obj_each, (st_data_t)&ivarg);
776}
777
778static void
779w_ivar(st_index_t num, VALUE ivobj, VALUE encname, struct dump_call_arg *arg)
780{
781 w_long(num, arg->arg);
782 num -= w_encoding(encname, arg);
783 if (RB_TYPE_P(ivobj, T_HASH) && rb_hash_ruby2_keywords_p(ivobj)) {
784 int limit = arg->limit;
785 if (limit >= 0) ++limit;
786 w_symbol(ID2SYM(s_ruby2_keywords_flag), arg->arg);
787 w_object(Qtrue, arg->arg, limit);
788 num--;
789 }
790 if (!UNDEF_P(ivobj) && num) {
791 w_ivar_each(ivobj, num, arg);
792 }
793}
794
795static void
796w_objivar(VALUE obj, struct dump_call_arg *arg)
797{
798 st_data_t num = 0;
799
800 rb_ivar_foreach(obj, obj_count_ivars, (st_data_t)&num);
801 w_long(num, arg->arg);
802 w_ivar_each(obj, num, arg);
803}
804
805#if SIZEOF_LONG > 4
806// Optimized dump for fixnum larger than 31-bits
807static void
808w_bigfixnum(VALUE obj, struct dump_arg *arg)
809{
810 RUBY_ASSERT(FIXNUM_P(obj));
811
812 w_byte(TYPE_BIGNUM, arg);
813
814#if SIZEOF_LONG == SIZEOF_VALUE
815 long num, slen_num;
816 num = FIX2LONG(obj);
817#else
818 long long num, slen_num;
819 num = NUM2LL(obj);
820#endif
821
822 char sign = num < 0 ? '-' : '+';
823 w_byte(sign, arg);
824
825 // Guaranteed not to overflow, as FIXNUM is 1-bit less than long
826 if (num < 0) num = -num;
827
828 // calculate the size in shorts
829 int slen = 0;
830 {
831 slen_num = num;
832 while (slen_num) {
833 slen++;
834 slen_num = SHORTDN(slen_num);
835 }
836 }
837
838 RUBY_ASSERT(slen > 0 && slen <= SIZEOF_LONG / 2);
839
840 w_long((long)slen, arg);
841
842 for (int i = 0; i < slen; i++) {
843 w_short(num & SHORTMASK, arg);
844 num = SHORTDN(num);
845 }
846
847 // We aren't adding this object to the link table, but we need to increment
848 // the index.
849 arg->num_entries++;
850
851 RUBY_ASSERT(num == 0);
852}
853#endif
854
855static void
856w_remember(VALUE obj, struct dump_arg *arg)
857{
858 st_add_direct(&arg->data, obj, arg->num_entries++);
859}
860
861static void
862w_object(VALUE obj, struct dump_arg *arg, int limit)
863{
864 struct dump_call_arg c_arg;
865 VALUE ivobj = Qundef;
866 st_data_t num;
867 st_index_t hasiv = 0;
868 VALUE encname = Qnil;
869
870 if (limit == 0) {
871 rb_raise(rb_eArgError, "exceed depth limit");
872 }
873
874 if (NIL_P(obj)) {
875 w_byte(TYPE_NIL, arg);
876 }
877 else if (obj == Qtrue) {
878 w_byte(TYPE_TRUE, arg);
879 }
880 else if (obj == Qfalse) {
881 w_byte(TYPE_FALSE, arg);
882 }
883 else if (FIXNUM_P(obj)) {
884#if SIZEOF_LONG <= 4
885 w_byte(TYPE_FIXNUM, arg);
886 w_long(FIX2INT(obj), arg);
887#else
888 if (RSHIFT((long)obj, 31) == 0 || RSHIFT((long)obj, 31) == -1) {
889 w_byte(TYPE_FIXNUM, arg);
890 w_long(FIX2LONG(obj), arg);
891 }
892 else {
893 w_bigfixnum(obj, arg);
894 }
895#endif
896 }
897 else if (SYMBOL_P(obj)) {
898 w_symbol(obj, arg);
899 }
900 else {
901 if (st_lookup(&arg->data, obj, &num)) {
902 w_byte(TYPE_LINK, arg);
903 w_long((long)num, arg);
904 return;
905 }
906
907 if (limit > 0) limit--;
908 c_arg.limit = limit;
909 c_arg.arg = arg;
910 c_arg.obj = obj;
911
912 if (FLONUM_P(obj)) {
913 w_remember(obj, arg);
914 w_byte(TYPE_FLOAT, arg);
915 w_float(RFLOAT_VALUE(obj), arg);
916 return;
917 }
918
919 VALUE v;
920
921 if (!RBASIC_CLASS(obj)) {
922 rb_raise(rb_eTypeError, "can't dump internal %s",
923 rb_builtin_type_name(BUILTIN_TYPE(obj)));
924 }
925
926 if (rb_obj_respond_to(obj, s_mdump, TRUE)) {
927 w_remember(obj, arg);
928
929 v = dump_funcall(arg, obj, s_mdump, 0, 0);
930 w_class(TYPE_USRMARSHAL, obj, arg, FALSE);
931 w_object(v, arg, limit);
932 return;
933 }
934 if (rb_obj_respond_to(obj, s_dump, TRUE)) {
935 VALUE ivobj2 = Qundef;
936 st_index_t hasiv2;
937 VALUE encname2;
938
939 if (arg->has_userdefs && st_is_member(&arg->userdefs, (st_data_t)obj)) {
940 rb_raise(rb_eRuntimeError, "can't dump recursive object using _dump()");
941 }
942 v = INT2NUM(limit);
943 v = dump_funcall(arg, obj, s_dump, 1, &v);
944 if (!RB_TYPE_P(v, T_STRING)) {
945 rb_raise(rb_eTypeError, "_dump() must return string");
946 }
947 hasiv = has_ivars(obj, (encname = encoding_name(obj, arg)), &ivobj);
948 hasiv2 = has_ivars(v, (encname2 = encoding_name(v, arg)), &ivobj2);
949 if (hasiv2) {
950 hasiv = hasiv2;
951 ivobj = ivobj2;
952 encname = encname2;
953 }
954 if (hasiv) w_byte(TYPE_IVAR, arg);
955 w_class(TYPE_USERDEF, obj, arg, FALSE);
956 w_str_bytes(v, arg);
957 if (hasiv) {
958 st_data_t userdefs = (st_data_t)obj;
959 if (!arg->has_userdefs) {
960 rb_init_existing_identtable_with_size(&arg->userdefs, 1);
961 arg->has_userdefs = true;
962 }
963 st_add_direct(&arg->userdefs, userdefs, 0);
964 w_ivar(hasiv, ivobj, encname, &c_arg);
965 st_delete(&arg->userdefs, &userdefs, NULL);
966 }
967 w_remember(obj, arg);
968 return;
969 }
970
971 w_remember(obj, arg);
972
973 hasiv = has_ivars(obj, (encname = encoding_name(obj, arg)), &ivobj);
974 {
975 st_data_t compat_data;
976 VALUE klass = CLASS_OF(obj);
977 rb_alloc_func_t allocator = RCLASS_SINGLETON_P(klass) ? 0 : rb_get_alloc_func(klass);
978 if (allocator && st_lookup(compat_allocator_tbl,
979 (st_data_t)allocator,
980 &compat_data)) {
981 marshal_compat_t *compat = (marshal_compat_t*)compat_data;
982 VALUE real_obj = obj;
983 obj = compat->dumper(real_obj);
984 if (!arg->has_compat_tbl) {
985 rb_init_existing_identtable_with_size(&arg->compat_tbl, 1);
986 arg->has_compat_tbl = true;
987 }
988 st_insert(&arg->compat_tbl, (st_data_t)obj, (st_data_t)real_obj);
989 if (obj != real_obj && UNDEF_P(ivobj)) hasiv = 0;
990 }
991 }
992 if (hasiv) w_byte(TYPE_IVAR, arg);
993
994 switch (BUILTIN_TYPE(obj)) {
995 case T_CLASS:
996 if (FL_TEST(obj, FL_SINGLETON)) {
997 rb_raise(rb_eTypeError, "singleton class can't be dumped");
998 }
999 {
1000 VALUE path = class2path(obj);
1001 VALUE encname = w_encivar(path, arg);
1002 w_byte(TYPE_CLASS, arg);
1003 w_bytes(RSTRING_PTR(path), RSTRING_LEN(path), arg);
1004 w_encname(encname, arg);
1005 RB_GC_GUARD(path);
1006 }
1007 break;
1008
1009 case T_MODULE:
1010 {
1011 VALUE path = class2path(obj);
1012 VALUE encname = w_encivar(path, arg);
1013 w_byte(TYPE_MODULE, arg);
1014 w_bytes(RSTRING_PTR(path), RSTRING_LEN(path), arg);
1015 w_encname(encname, arg);
1016 RB_GC_GUARD(path);
1017 }
1018 break;
1019
1020 case T_FLOAT:
1021 w_byte(TYPE_FLOAT, arg);
1022 w_float(RFLOAT_VALUE(obj), arg);
1023 break;
1024
1025 case T_BIGNUM:
1026 w_byte(TYPE_BIGNUM, arg);
1027 {
1028 char sign = BIGNUM_SIGN(obj) ? '+' : '-';
1029 size_t len = BIGNUM_LEN(obj);
1030 size_t slen;
1031 size_t j;
1032 BDIGIT *d = BIGNUM_DIGITS(obj);
1033
1034 slen = SHORTLEN(len);
1035 if (LONG_MAX < slen) {
1036 rb_raise(rb_eTypeError, "too big Bignum can't be dumped");
1037 }
1038
1039 w_byte(sign, arg);
1040 w_long((long)slen, arg);
1041 for (j = 0; j < len; j++) {
1042#if SIZEOF_BDIGIT > SIZEOF_SHORT
1043 BDIGIT num = *d;
1044 int i;
1045
1046 for (i=0; i<SIZEOF_BDIGIT; i+=SIZEOF_SHORT) {
1047 w_short(num & SHORTMASK, arg);
1048 num = SHORTDN(num);
1049 if (j == len - 1 && num == 0) break;
1050 }
1051#else
1052 w_short(*d, arg);
1053#endif
1054 d++;
1055 }
1056 }
1057 break;
1058
1059 case T_STRING:
1060 w_uclass(obj, rb_cString, arg);
1061 w_byte(TYPE_STRING, arg);
1062 w_str_bytes(obj, arg);
1063 break;
1064
1065 case T_REGEXP:
1066 w_uclass(obj, rb_cRegexp, arg);
1067 w_byte(TYPE_REGEXP, arg);
1068 {
1069 int opts = rb_reg_options(obj);
1070 w_bytes(RREGEXP_SRC_PTR(obj), RREGEXP_SRC_LEN(obj), arg);
1071 w_byte((char)opts, arg);
1072 }
1073 break;
1074
1075 case T_ARRAY:
1076 w_uclass(obj, rb_cArray, arg);
1077 w_byte(TYPE_ARRAY, arg);
1078 {
1079 long i, len = RARRAY_LEN(obj);
1080
1081 w_long(len, arg);
1082 for (i=0; i<RARRAY_LEN(obj); i++) {
1083 w_object(RARRAY_AREF(obj, i), arg, limit);
1084 if (len != RARRAY_LEN(obj)) {
1085 rb_raise(rb_eRuntimeError, "array modified during dump");
1086 }
1087 }
1088 }
1089 break;
1090
1091 case T_HASH:
1092 w_uclass(obj, rb_cHash, arg);
1093 if (rb_hash_compare_by_id_p(obj)) {
1094 w_byte(TYPE_UCLASS, arg);
1095 w_symbol(rb_sym_intern_ascii_cstr("Hash"), arg);
1096 }
1097 if (NIL_P(RHASH_IFNONE(obj))) {
1098 w_byte(TYPE_HASH, arg);
1099 }
1100 else if (FL_TEST(obj, RHASH_PROC_DEFAULT)) {
1101 rb_raise(rb_eTypeError, "can't dump hash with default proc");
1102 }
1103 else {
1104 w_byte(TYPE_HASH_DEF, arg);
1105 }
1106 w_long(rb_hash_size_num(obj), arg);
1107 rb_hash_foreach(obj, hash_each, (st_data_t)&c_arg);
1108 if (!NIL_P(RHASH_IFNONE(obj))) {
1109 w_object(RHASH_IFNONE(obj), arg, limit);
1110 }
1111 break;
1112
1113 case T_STRUCT:
1114 w_class(TYPE_STRUCT, obj, arg, TRUE);
1115 {
1116 long len = RSTRUCT_LEN_RAW(obj);
1117 VALUE mem;
1118 long i;
1119
1120 w_long(len, arg);
1121 mem = rb_struct_members(obj);
1122 for (i=0; i<len; i++) {
1123 w_symbol(RARRAY_AREF(mem, i), arg);
1124 w_object(RSTRUCT_GET_RAW(obj, i), arg, limit);
1125 }
1126 }
1127 break;
1128
1129 case T_OBJECT:
1130 w_class(TYPE_OBJECT, obj, arg, TRUE);
1131 w_objivar(obj, &c_arg);
1132 break;
1133
1134 case T_DATA:
1135 {
1136 VALUE v;
1137
1138 if (!rb_obj_respond_to(obj, s_dump_data, TRUE)) {
1139 rb_raise(rb_eTypeError,
1140 "no _dump_data is defined for class %"PRIsVALUE,
1141 rb_obj_class(obj));
1142 }
1143 v = dump_funcall(arg, obj, s_dump_data, 0, 0);
1144 w_class(TYPE_DATA, obj, arg, TRUE);
1145 w_object(v, arg, limit);
1146 }
1147 break;
1148
1149 default:
1150 rb_raise(rb_eTypeError, "can't dump %"PRIsVALUE,
1151 rb_obj_class(obj));
1152 break;
1153 }
1154 RB_GC_GUARD(obj);
1155 }
1156 if (hasiv) {
1157 w_ivar(hasiv, ivobj, encname, &c_arg);
1158 }
1159}
1160
1161static void
1162clear_dump_arg(struct dump_arg *arg)
1163{
1164 if (!arg->has_symbols) return;
1165 st_free_embedded_table(&arg->symbols);
1166 arg->has_symbols = false;
1167 st_free_embedded_table(&arg->data);
1168 arg->has_data = false;
1169 arg->num_entries = 0;
1170 if (arg->has_compat_tbl) {
1171 st_free_embedded_table(&arg->compat_tbl);
1172 arg->has_compat_tbl = false;
1173 }
1174 if (arg->has_encodings) {
1175 st_free_embedded_table(&arg->encodings);
1176 arg->has_encodings = false;
1177 }
1178 if (arg->has_userdefs) {
1179 st_free_embedded_table(&arg->userdefs);
1180 arg->has_userdefs = false;
1181 }
1182}
1183
1184NORETURN(static inline void io_needed(void));
1185static inline void
1186io_needed(void)
1187{
1188 rb_raise(rb_eTypeError, "instance of IO needed");
1189}
1190
1191/*
1192 * call-seq:
1193 * dump( obj [, anIO] , limit=-1 ) -> anIO
1194 *
1195 * Serializes obj and all descendant objects. If anIO is
1196 * specified, the serialized data will be written to it, otherwise the
1197 * data will be returned as a String. If limit is specified, the
1198 * traversal of subobjects will be limited to that depth. If limit is
1199 * negative, no checking of depth will be performed.
1200 *
1201 * class Klass
1202 * def initialize(str)
1203 * @str = str
1204 * end
1205 * def say_hello
1206 * @str
1207 * end
1208 * end
1209 *
1210 * (produces no output)
1211 *
1212 * o = Klass.new("hello\n")
1213 * data = Marshal.dump(o)
1214 * obj = Marshal.load(data)
1215 * obj.say_hello #=> "hello\n"
1216 *
1217 * Marshal can't dump following objects:
1218 * * anonymous Class/Module.
1219 * * objects which are related to system (ex: Dir, File::Stat, IO, File, Socket
1220 * and so on)
1221 * * an instance of MatchData, Method, UnboundMethod, Proc, Thread,
1222 * ThreadGroup, Continuation
1223 * * objects which define singleton methods
1224 */
1225static VALUE
1226marshal_dump(int argc, VALUE *argv, VALUE _)
1227{
1228 VALUE obj, port, a1, a2;
1229 int limit = -1;
1230
1231 port = Qnil;
1232 rb_scan_args(argc, argv, "12", &obj, &a1, &a2);
1233 if (argc == 3) {
1234 if (!NIL_P(a2)) limit = NUM2INT(a2);
1235 if (NIL_P(a1)) io_needed();
1236 port = a1;
1237 }
1238 else if (argc == 2) {
1239 if (FIXNUM_P(a1)) limit = FIX2INT(a1);
1240 else if (NIL_P(a1)) io_needed();
1241 else port = a1;
1242 }
1243 return rb_marshal_dump_limited(obj, port, limit);
1244}
1245
1246VALUE
1247rb_marshal_dump_limited(VALUE obj, VALUE port, int limit)
1248{
1249 struct dump_arg *arg;
1250 VALUE wrapper; /* used to avoid memory leak in case of exception */
1251
1252 wrapper = TypedData_Make_Struct(0, struct dump_arg, &dump_arg_data, arg);
1253 arg->dest = 0;
1254 st_init_existing_numtable_with_size(&arg->symbols, 0);
1255 arg->has_symbols = true;
1256
1257 rb_init_existing_identtable_with_size(&arg->data, 0);
1258 arg->has_data = true;
1259 arg->num_entries = 0;
1260 arg->str = rb_str_buf_new(0);
1261 if (!NIL_P(port)) {
1262 if (!rb_respond_to(port, s_write)) {
1263 io_needed();
1264 }
1265 arg->dest = port;
1266 dump_check_funcall(arg, port, s_binmode, 0, 0);
1267 }
1268 else {
1269 port = arg->str;
1270 }
1271
1272 w_byte(MARSHAL_MAJOR, arg);
1273 w_byte(MARSHAL_MINOR, arg);
1274
1275 w_object(obj, arg, limit);
1276 if (arg->dest) {
1277 rb_io_write(arg->dest, arg->str);
1278 rb_str_resize(arg->str, 0);
1279 }
1280 clear_dump_arg(arg);
1281 RB_GC_GUARD(wrapper);
1282
1283 return port;
1284}
1285
1286struct load_arg {
1287 VALUE src;
1288 char *buf;
1289 long bufsize;
1290 long buflen;
1291 long readable;
1292 long offset;
1293 st_table symbols;
1294 st_table data;
1295 st_table partial_objects;
1296 VALUE proc;
1297 st_table compat_tbl;
1298 bool has_symbols;
1299 bool has_data;
1300 bool has_partial_objects;
1301 bool has_compat_tbl;
1302 bool freeze;
1303};
1304
1305static VALUE
1306check_load_arg(VALUE ret, struct load_arg *arg, const char *name)
1307{
1308 if (!arg->has_symbols) {
1309 rb_raise(rb_eRuntimeError, "Marshal.load reentered at %s",
1310 name);
1311 }
1312 return ret;
1313}
1314#define load_funcall(arg, obj, sym, argc, argv) \
1315 check_load_arg(rb_funcallv(obj, sym, argc, argv), arg, name_##sym)
1316
1317static void clear_load_arg(struct load_arg *arg);
1318
1319static void
1320mark_load_arg(void *ptr)
1321{
1322 struct load_arg *p = ptr;
1323 if (!p->has_symbols)
1324 return;
1325 rb_mark_tbl(&p->symbols);
1326 if (p->has_data) rb_mark_tbl(&p->data);
1327 if (p->has_partial_objects) rb_mark_tbl(&p->partial_objects);
1328 if (p->has_compat_tbl) rb_mark_hash(&p->compat_tbl);
1329}
1330
1331static void
1332free_load_arg(void *ptr)
1333{
1334 clear_load_arg(ptr);
1335}
1336
1337static size_t
1338memsize_load_arg(const void *ptr)
1339{
1340 const struct load_arg *p = (struct load_arg *)ptr;
1341 size_t memsize = 0;
1342 if (p->has_symbols) memsize += rb_st_allocated_memsize(&p->symbols);
1343 if (p->has_data) memsize += rb_st_allocated_memsize(&p->data);
1344 if (p->has_partial_objects) memsize += rb_st_allocated_memsize(&p->partial_objects);
1345 if (p->has_compat_tbl) memsize += rb_st_allocated_memsize(&p->compat_tbl);
1346 return memsize;
1347}
1348
1349static const rb_data_type_t load_arg_data = {
1350 "load_arg",
1351 {mark_load_arg, free_load_arg, memsize_load_arg,},
1352 0, 0, RUBY_TYPED_THREAD_SAFE_FREE | RUBY_TYPED_EMBEDDABLE
1353};
1354
1355#define r_entry(v, arg) r_entry0((v), (arg)->data.num_entries, (arg))
1356static VALUE r_object(struct load_arg *arg);
1357static VALUE r_symbol(struct load_arg *arg);
1358
1359NORETURN(static void too_short(void));
1360static void
1361too_short(void)
1362{
1363 rb_raise(rb_eArgError, "marshal data too short");
1364}
1365
1366static st_index_t
1367r_prepare(struct load_arg *arg)
1368{
1369 st_index_t idx = arg->data.num_entries;
1370
1371 st_insert(&arg->data, (st_data_t)idx, (st_data_t)Qundef);
1372 return idx;
1373}
1374
1375static unsigned char
1376r_byte1_buffered(struct load_arg *arg)
1377{
1378 if (arg->buflen == 0) {
1379 long readable = arg->readable < arg->bufsize ? arg->readable : arg->bufsize;
1380 long read_len;
1381 VALUE str, n = LONG2NUM(readable);
1382
1383 str = load_funcall(arg, arg->src, s_read, 1, &n);
1384 if (NIL_P(str)) too_short();
1385 StringValue(str);
1386 read_len = RSTRING_LEN(str);
1387 if (UNLIKELY(read_len < readable)) too_short();
1388 if (UNLIKELY(read_len > arg->bufsize)) {
1389 arg->buf = ruby_sized_realloc_n(arg->buf, read_len, 1, arg->bufsize);
1390 arg->bufsize = read_len;
1391 }
1392 memcpy(arg->buf, RSTRING_PTR(str), read_len);
1393 arg->offset = 0;
1394 arg->buflen = read_len;
1395 RB_GC_GUARD(str);
1396 }
1397 arg->buflen--;
1398 return arg->buf[arg->offset++];
1399}
1400
1401static int
1402r_byte(struct load_arg *arg)
1403{
1404 int c;
1405
1406 if (RB_TYPE_P(arg->src, T_STRING)) {
1407 if (RSTRING_LEN(arg->src) > arg->offset) {
1408 c = (unsigned char)RSTRING_PTR(arg->src)[arg->offset++];
1409 }
1410 else {
1411 too_short();
1412 }
1413 }
1414 else {
1415 if (arg->readable >0 || arg->buflen > 0) {
1416 c = r_byte1_buffered(arg);
1417 }
1418 else {
1419 VALUE v = load_funcall(arg, arg->src, s_getbyte, 0, 0);
1420 if (NIL_P(v)) rb_eof_error();
1421 c = (unsigned char)NUM2CHR(v);
1422 }
1423 }
1424 return c;
1425}
1426
1427NORETURN(static void long_toobig(int size));
1428
1429static void
1430long_toobig(int size)
1431{
1432 rb_raise(rb_eTypeError, "long too big for this architecture (size "
1433 STRINGIZE(SIZEOF_LONG)", given %d)", size);
1434}
1435
1436static long
1437r_long(struct load_arg *arg)
1438{
1439 register long x;
1440 int c = (signed char)r_byte(arg);
1441 long i;
1442
1443 if (c == 0) return 0;
1444 if (c > 0) {
1445 if (4 < c && c < 128) {
1446 return c - 5;
1447 }
1448 if (c > (int)sizeof(long)) long_toobig(c);
1449 x = 0;
1450 for (i=0;i<c;i++) {
1451 x |= (long)r_byte(arg) << (8*i);
1452 }
1453 }
1454 else {
1455 if (-129 < c && c < -4) {
1456 return c + 5;
1457 }
1458 c = -c;
1459 if (c > (int)sizeof(long)) long_toobig(c);
1460 x = -1;
1461 for (i=0;i<c;i++) {
1462 x &= ~((long)0xff << (8*i));
1463 x |= (long)r_byte(arg) << (8*i);
1464 }
1465 }
1466 return x;
1467}
1468
1469long
1470ruby_marshal_read_long(const char **buf, long len)
1471{
1472 long x;
1473 struct RString src = {RBASIC_INIT};
1474 struct load_arg arg;
1475 memset(&arg, 0, sizeof(arg));
1476 arg.src = rb_setup_fake_str(&src, *buf, len, 0);
1477 x = r_long(&arg);
1478 *buf += arg.offset;
1479 return x;
1480}
1481
1482static long
1483r_keep_readable(struct load_arg *arg, long len, size_t size)
1484{
1485 if (UNLIKELY(len < 0)) {
1486 rb_raise(rb_eArgError, "negative length");
1487 }
1488 if (UNLIKELY((unsigned long)len > SIZE_MAX / size || arg->readable >= LONG_MAX - len)) {
1489 rb_raise(rb_eArgError, "marshaled data too big");
1490 }
1491 return len;
1492}
1493
1494static VALUE
1495r_bytes1(long len, struct load_arg *arg)
1496{
1497 VALUE str, n = LONG2NUM(len);
1498
1499 str = load_funcall(arg, arg->src, s_read, 1, &n);
1500 if (NIL_P(str)) too_short();
1501 StringValue(str);
1502 if (RSTRING_LEN(str) != len) too_short();
1503
1504 return str;
1505}
1506
1507static VALUE
1508r_bytes1_buffered(long len, struct load_arg *arg)
1509{
1510 VALUE str;
1511
1512 if (len <= arg->buflen) {
1513 str = rb_str_new(arg->buf+arg->offset, len);
1514 arg->offset += len;
1515 arg->buflen -= len;
1516 }
1517 else {
1518 long buflen = arg->buflen;
1519 long readable = arg->readable + 1;
1520 long tmp_len, read_len, need_len = len - buflen;
1521 VALUE tmp, n;
1522
1523 readable = readable < arg->bufsize ? readable : arg->bufsize;
1524 read_len = need_len > readable ? need_len : readable;
1525 n = LONG2NUM(read_len);
1526 tmp = load_funcall(arg, arg->src, s_read, 1, &n);
1527 if (NIL_P(tmp)) too_short();
1528 StringValue(tmp);
1529
1530 tmp_len = RSTRING_LEN(tmp);
1531
1532 if (tmp_len < need_len) too_short();
1533
1534 str = rb_str_new(arg->buf+arg->offset, buflen);
1535 rb_str_cat(str, RSTRING_PTR(tmp), need_len);
1536
1537 if (tmp_len > need_len) {
1538 buflen = tmp_len - need_len;
1539 if (UNLIKELY(buflen > arg->bufsize)) {
1540 arg->buf = ruby_sized_realloc_n(arg->buf, buflen, 1, arg->bufsize);
1541 arg->bufsize = buflen;
1542 }
1543 memcpy(arg->buf, RSTRING_PTR(tmp)+need_len, buflen);
1544 arg->buflen = buflen;
1545 }
1546 else {
1547 arg->buflen = 0;
1548 }
1549 arg->offset = 0;
1550 }
1551
1552 return str;
1553}
1554
1555#define r_bytes(arg) r_bytes0(r_long(arg), (arg))
1556
1557static VALUE
1558r_bytes0(long len, struct load_arg *arg)
1559{
1560 VALUE str;
1561
1562 if (len == 0) return rb_str_new(0, 0);
1563 if (RB_TYPE_P(arg->src, T_STRING)) {
1564 if (RSTRING_LEN(arg->src) - arg->offset >= len) {
1565 str = rb_str_new(RSTRING_PTR(arg->src)+arg->offset, len);
1566 arg->offset += len;
1567 }
1568 else {
1569 too_short();
1570 }
1571 }
1572 else {
1573 if (arg->readable > 0 || arg->buflen > 0) {
1574 str = r_bytes1_buffered(len, arg);
1575 }
1576 else {
1577 str = r_bytes1(len, arg);
1578 }
1579 }
1580 return str;
1581}
1582
1583static inline int
1584name_equal(const char *name, size_t nlen, const char *p, long l)
1585{
1586 if ((size_t)l != nlen || *p != *name) return 0;
1587 return nlen == 1 || memcmp(p+1, name+1, nlen-1) == 0;
1588}
1589
1590static int
1591sym2encidx(VALUE sym, VALUE val)
1592{
1593 RBIMPL_ATTR_NONSTRING() static const char name_encoding[8] = "encoding";
1594 const char *p;
1595 long l;
1596 if (rb_enc_get_index(sym) != ENCINDEX_US_ASCII) return -1;
1597 RSTRING_GETMEM(sym, p, l);
1598 if (l <= 0) return -1;
1599 if (name_equal(name_encoding, sizeof(name_encoding), p, l)) {
1600 int idx = rb_enc_find_index(StringValueCStr(val));
1601 return idx;
1602 }
1603 if (name_equal(name_s_encoding_short, rb_strlen_lit(name_s_encoding_short), p, l)) {
1604 if (val == Qfalse) return rb_usascii_encindex();
1605 else if (val == Qtrue) return rb_utf8_encindex();
1606 /* bogus ignore */
1607 }
1608 return -1;
1609}
1610
1611static int
1612symname_equal(VALUE sym, const char *name, size_t nlen)
1613{
1614 const char *p;
1615 long l;
1616 if (rb_enc_get_index(sym) != ENCINDEX_US_ASCII) return 0;
1617 RSTRING_GETMEM(sym, p, l);
1618 return name_equal(name, nlen, p, l);
1619}
1620
1621#define BUILD_ASSERT_POSITIVE(n) \
1622 /* make 0 negative to workaround the "zero size array" GCC extension, */ \
1623 ((sizeof(char [2*(ssize_t)(n)-1])+1)/2) /* assuming no overflow */
1624#define symname_equal_lit(sym, sym_name) \
1625 symname_equal(sym, sym_name, BUILD_ASSERT_POSITIVE(rb_strlen_lit(sym_name)))
1626
1627static VALUE
1628r_symlink(struct load_arg *arg)
1629{
1630 st_data_t sym;
1631 long num = r_long(arg);
1632
1633 if (!st_lookup(&arg->symbols, num, &sym)) {
1634 rb_raise(rb_eArgError, "bad symbol");
1635 }
1636 return (VALUE)sym;
1637}
1638
1639static VALUE
1640r_symreal(struct load_arg *arg, int ivar)
1641{
1642 VALUE s = r_bytes(arg);
1643 VALUE sym;
1644 int idx = -1;
1645 st_index_t n = arg->symbols.num_entries;
1646
1647 if (rb_enc_str_asciionly_p(s)) rb_enc_associate_index(s, ENCINDEX_US_ASCII);
1648 st_insert(&arg->symbols, (st_data_t)n, (st_data_t)s);
1649 if (ivar) {
1650 long num = r_long(arg);
1651 while (num-- > 0) {
1652 sym = r_symbol(arg);
1653 idx = sym2encidx(sym, r_object(arg));
1654 }
1655 }
1656 if (idx > 0) {
1657 rb_enc_associate_index(s, idx);
1658 if (is_broken_string(s)) {
1659 rb_raise(rb_eArgError, "invalid byte sequence in %s: %+"PRIsVALUE,
1660 rb_enc_name(rb_enc_from_index(idx)), s);
1661 }
1662 }
1663
1664 return s;
1665}
1666
1667static VALUE
1668r_symbol(struct load_arg *arg)
1669{
1670 int type, ivar = 0;
1671
1672 again:
1673 switch ((type = r_byte(arg))) {
1674 default:
1675 rb_raise(rb_eArgError, "dump format error for symbol(0x%x)", type);
1676 case TYPE_IVAR:
1677 ivar = 1;
1678 goto again;
1679 case TYPE_SYMBOL:
1680 return r_symreal(arg, ivar);
1681 case TYPE_SYMLINK:
1682 if (ivar) {
1683 rb_raise(rb_eArgError, "dump format error (symlink with encoding)");
1684 }
1685 return r_symlink(arg);
1686 }
1687}
1688
1689static VALUE
1690r_unique(struct load_arg *arg)
1691{
1692 return r_symbol(arg);
1693}
1694
1695static VALUE
1696r_string(struct load_arg *arg)
1697{
1698 return r_bytes(arg);
1699}
1700
1701static VALUE
1702r_entry0(VALUE v, st_index_t num, struct load_arg *arg)
1703{
1704 st_data_t real_obj = (st_data_t)v;
1705 if (arg->has_compat_tbl) {
1706 /* real_obj is kept if not found */
1707 st_lookup(&arg->compat_tbl, v, &real_obj);
1708 }
1709 st_insert(&arg->data, num, real_obj);
1710 if (arg->has_partial_objects) {
1711 st_insert(&arg->partial_objects, (st_data_t)real_obj, Qtrue);
1712 }
1713 return v;
1714}
1715
1716static VALUE
1717r_fixup_compat(VALUE v, struct load_arg *arg)
1718{
1719 st_data_t data;
1720 st_data_t key = (st_data_t)v;
1721 if (arg->has_compat_tbl && st_delete(&arg->compat_tbl, &key, &data)) {
1722 VALUE real_obj = (VALUE)data;
1723 rb_alloc_func_t allocator = rb_get_alloc_func(CLASS_OF(real_obj));
1724 if (st_lookup(compat_allocator_tbl, (st_data_t)allocator, &data)) {
1725 marshal_compat_t *compat = (marshal_compat_t*)data;
1726 compat->loader(real_obj, v);
1727 }
1728 v = real_obj;
1729 }
1730 return v;
1731}
1732
1733static VALUE
1734r_post_proc(VALUE v, struct load_arg *arg)
1735{
1736 if (arg->proc) {
1737 v = load_funcall(arg, arg->proc, s_call, 1, &v);
1738 }
1739 return v;
1740}
1741
1742static VALUE
1743r_leave(VALUE v, struct load_arg *arg, bool partial)
1744{
1745 v = r_fixup_compat(v, arg);
1746 if (!partial) {
1747 if (arg->has_partial_objects) {
1748 st_data_t data;
1749 st_data_t key = (st_data_t)v;
1750 st_delete(&arg->partial_objects, &key, &data);
1751 }
1752 if (arg->freeze) {
1753 if (RB_TYPE_P(v, T_MODULE) || RB_TYPE_P(v, T_CLASS)) {
1754 // noop
1755 }
1756 else if (RB_TYPE_P(v, T_STRING)) {
1757 v = rb_str_to_interned_str(v);
1758 }
1759 else {
1760 OBJ_FREEZE(v);
1761 }
1762 }
1763 v = r_post_proc(v, arg);
1764 }
1765 return v;
1766}
1767
1768static int
1769copy_ivar_i(ID vid, VALUE value, st_data_t arg)
1770{
1771 VALUE obj = (VALUE)arg;
1772
1773 if (!rb_ivar_defined(obj, vid))
1774 rb_ivar_set(obj, vid, value);
1775 return ST_CONTINUE;
1776}
1777
1778static VALUE
1779r_copy_ivar(VALUE v, VALUE data)
1780{
1781 rb_ivar_foreach(data, copy_ivar_i, (st_data_t)v);
1782 return v;
1783}
1784
1785#define override_ivar_error(type, str) \
1786 rb_raise(rb_eTypeError, \
1787 "can't override instance variable of "type" '%"PRIsVALUE"'", \
1788 (str))
1789
1790static int
1791r_ivar_encoding(VALUE obj, struct load_arg *arg, VALUE sym, VALUE val)
1792{
1793 int idx = sym2encidx(sym, val);
1794 if (idx >= 0) {
1795 if (rb_enc_capable(obj)) {
1796 // Check if needed to avoid rb_check_frozen() check for Regexps
1797 if (rb_enc_get_index(obj) != idx) {
1798 rb_enc_associate_index(obj, idx);
1799 }
1800 }
1801 else {
1802 rb_raise(rb_eArgError, "%"PRIsVALUE" is not enc_capable", obj);
1803 }
1804 return TRUE;
1805 }
1806 return FALSE;
1807}
1808
1809static long
1810r_encname(VALUE obj, struct load_arg *arg)
1811{
1812 long len = r_long(arg);
1813 if (len > 0) {
1814 VALUE sym = r_symbol(arg);
1815 VALUE val = r_object(arg);
1816 len -= r_ivar_encoding(obj, arg, sym, val);
1817 }
1818 return len;
1819}
1820
1821static void
1822r_ivar(VALUE obj, int *has_encoding, struct load_arg *arg)
1823{
1824 long len;
1825
1826 len = r_long(arg);
1827 if (len > 0) {
1828 if (RB_TYPE_P(obj, T_MODULE)) {
1829 override_ivar_error("module", rb_mod_name(obj));
1830 }
1831 else if (RB_TYPE_P(obj, T_CLASS)) {
1832 override_ivar_error("class", rb_class_name(obj));
1833 }
1834 do {
1835 VALUE sym = r_symbol(arg);
1836 VALUE val = r_object(arg);
1837 if (r_ivar_encoding(obj, arg, sym, val)) {
1838 if (has_encoding) *has_encoding = TRUE;
1839 }
1840 else if (symname_equal_lit(sym, name_s_ruby2_keywords_flag)) {
1841 if (RB_TYPE_P(obj, T_HASH)) {
1842 rb_hash_ruby2_keywords(obj);
1843 }
1844 else {
1845 rb_raise(rb_eArgError, "ruby2_keywords flag is given but %"PRIsVALUE" is not a Hash", obj);
1846 }
1847 }
1848 else {
1849 rb_ivar_set(obj, rb_intern_str(sym), val);
1850 }
1851 } while (--len > 0);
1852 }
1853}
1854
1855static VALUE
1856path2class(VALUE path)
1857{
1858 VALUE v = rb_path_to_class(path);
1859
1860 if (!RB_TYPE_P(v, T_CLASS)) {
1861 rb_raise(rb_eArgError, "%"PRIsVALUE" does not refer to class", path);
1862 }
1863 return v;
1864}
1865
1866#define path2module(path) must_be_module(rb_path_to_class(path), path)
1867
1868static VALUE
1869must_be_module(VALUE v, VALUE path)
1870{
1871 if (!RB_TYPE_P(v, T_MODULE)) {
1872 rb_raise(rb_eArgError, "%"PRIsVALUE" does not refer to module", path);
1873 }
1874 return v;
1875}
1876
1877static VALUE
1878obj_alloc_by_klass(VALUE klass, struct load_arg *arg, VALUE *oldclass)
1879{
1880 st_data_t data;
1881 rb_alloc_func_t allocator;
1882
1883 allocator = rb_get_alloc_func(klass);
1884 if (st_lookup(compat_allocator_tbl, (st_data_t)allocator, &data)) {
1885 marshal_compat_t *compat = (marshal_compat_t*)data;
1886 VALUE real_obj = rb_obj_alloc(klass);
1887 VALUE obj = rb_obj_alloc(compat->oldclass);
1888 if (oldclass) *oldclass = compat->oldclass;
1889
1890 if (!arg->has_compat_tbl) {
1891 rb_init_existing_identtable_with_size(&arg->compat_tbl, 1);
1892 arg->has_compat_tbl = true;
1893 }
1894 st_insert(&arg->compat_tbl, (st_data_t)obj, (st_data_t)real_obj);
1895 return obj;
1896 }
1897
1898 return rb_obj_alloc(klass);
1899}
1900
1901static VALUE
1902obj_alloc_by_path(VALUE path, struct load_arg *arg)
1903{
1904 return obj_alloc_by_klass(path2class(path), arg, 0);
1905}
1906
1907static VALUE
1908append_extmod(VALUE obj, VALUE extmod)
1909{
1910 long i = RARRAY_LEN(extmod);
1911 while (i > 0) {
1912 VALUE m = RARRAY_AREF(extmod, --i);
1913 rb_extend_object(obj, m);
1914 }
1915 return obj;
1916}
1917
1918#define prohibit_ivar(type, str) do { \
1919 if (!ivp || !*ivp) break; \
1920 override_ivar_error(type, str); \
1921 } while (0)
1922
1923static VALUE r_object_for(struct load_arg *arg, bool partial, int *ivp, VALUE klass, VALUE extmod, int type);
1924
1925static VALUE
1926r_object0(struct load_arg *arg, bool partial, int *ivp, VALUE extmod)
1927{
1928 int type = r_byte(arg);
1929 return r_object_for(arg, partial, ivp, 0, extmod, type);
1930}
1931
1932static VALUE
1933r_object_for(struct load_arg *arg, bool partial, int *ivp, VALUE klass, VALUE extmod, int type)
1934{
1935 VALUE (*hash_new_capa)(long) = rb_hash_new_capa;
1936 VALUE v = Qnil;
1937 long id;
1938 st_data_t link;
1939
1940 switch (type) {
1941 case TYPE_LINK:
1942 id = r_long(arg);
1943 if (!st_lookup(&arg->data, (st_data_t)id, &link)) {
1944 rb_raise(rb_eArgError, "dump format error (unlinked)");
1945 }
1946 v = (VALUE)link;
1947 if (arg->has_partial_objects &&
1948 !st_lookup(&arg->partial_objects, (st_data_t)v, &link)) {
1949 if (arg->freeze && RB_TYPE_P(v, T_STRING)) {
1950 v = rb_str_to_interned_str(v);
1951 }
1952 v = r_post_proc(v, arg);
1953 }
1954 break;
1955
1956 case TYPE_IVAR:
1957 {
1958 int ivar = TRUE;
1959 v = r_object0(arg, true, &ivar, extmod);
1960 if (ivar) r_ivar(v, NULL, arg);
1961 v = r_leave(v, arg, partial);
1962 }
1963 break;
1964
1965 case TYPE_EXTENDED:
1966 {
1967 VALUE path = r_unique(arg);
1968 VALUE m = rb_path_to_class(path);
1969 if (NIL_P(extmod)) extmod = rb_ary_hidden_new(0);
1970
1971 if (RB_TYPE_P(m, T_CLASS)) { /* prepended */
1972 VALUE c;
1973
1974 v = r_object0(arg, true, 0, Qnil);
1975 c = CLASS_OF(v);
1976 if (c != m || FL_TEST(c, FL_SINGLETON)) {
1977 rb_raise(rb_eArgError,
1978 "prepended class %"PRIsVALUE" differs from class %"PRIsVALUE,
1979 path, rb_class_name(c));
1980 }
1981 c = rb_singleton_class(v);
1982 while (RARRAY_LEN(extmod) > 0) {
1983 m = rb_ary_pop(extmod);
1984 rb_prepend_module(c, m);
1985 }
1986 }
1987 else {
1988 must_be_module(m, path);
1989 rb_ary_push(extmod, m);
1990
1991 v = r_object0(arg, true, 0, extmod);
1992 while (RARRAY_LEN(extmod) > 0) {
1993 m = rb_ary_pop(extmod);
1994 rb_extend_object(v, m);
1995 }
1996 }
1997 v = r_leave(v, arg, partial);
1998 }
1999 break;
2000
2001 case TYPE_UCLASS:
2002 {
2003 VALUE c = path2class(r_unique(arg));
2004
2005 if (FL_TEST(c, FL_SINGLETON)) {
2006 rb_raise(rb_eTypeError, "singleton can't be loaded");
2007 }
2008 type = r_byte(arg);
2009 if ((c == rb_cHash) &&
2010 /* Hack for compare_by_identity */
2011 (type == TYPE_HASH || type == TYPE_HASH_DEF)) {
2012 hash_new_capa = rb_ident_hash_new_capa;
2013 goto type_hash;
2014 }
2015 v = r_object_for(arg, partial, 0, c, extmod, type);
2016 if (RB_SPECIAL_CONST_P(v) || RB_TYPE_P(v, T_OBJECT) || RB_TYPE_P(v, T_CLASS)) {
2017 goto format_error;
2018 }
2019 if (RB_TYPE_P(v, T_MODULE) || !RTEST(rb_class_inherited_p(c, RBASIC(v)->klass))) {
2020 VALUE tmp = rb_obj_alloc(c);
2021
2022 if (TYPE(v) != TYPE(tmp)) goto format_error;
2023 }
2024 if (RB_TYPE_P(v, T_STRUCT) &&
2025 RSTRUCT_LEN_RAW(v) != RARRAY_LEN(rb_struct_s_members(c))) {
2026 rb_raise(rb_eTypeError, "struct %"PRIsVALUE" not compatible (struct size differs)",
2027 rb_class_name(c));
2028 }
2029 RBASIC_SET_CLASS(v, c);
2030 }
2031 break;
2032
2033 format_error:
2034 rb_raise(rb_eArgError, "dump format error (user class)");
2035
2036 case TYPE_NIL:
2037 v = Qnil;
2038 v = r_leave(v, arg, false);
2039 break;
2040
2041 case TYPE_TRUE:
2042 v = Qtrue;
2043 v = r_leave(v, arg, false);
2044 break;
2045
2046 case TYPE_FALSE:
2047 v = Qfalse;
2048 v = r_leave(v, arg, false);
2049 break;
2050
2051 case TYPE_FIXNUM:
2052 {
2053 long i = r_long(arg);
2054 v = LONG2FIX(i);
2055 }
2056 v = r_leave(v, arg, false);
2057 break;
2058
2059 case TYPE_FLOAT:
2060 {
2061 double d;
2062 VALUE str = r_bytes(arg);
2063 const char *ptr = RSTRING_PTR(str);
2064
2065 if (strcmp(ptr, "nan") == 0) {
2066 d = nan("");
2067 }
2068 else if (strcmp(ptr, "inf") == 0) {
2069 d = HUGE_VAL;
2070 }
2071 else if (strcmp(ptr, "-inf") == 0) {
2072 d = -HUGE_VAL;
2073 }
2074 else {
2075 char *e;
2076 d = strtod(ptr, &e);
2077 d = load_mantissa(d, e, RSTRING_LEN(str) - (e - ptr));
2078 }
2079 v = DBL2NUM(d);
2080 v = r_entry(v, arg);
2081 v = r_leave(v, arg, false);
2082 }
2083 break;
2084
2085 case TYPE_BIGNUM:
2086 {
2087 long len;
2088 VALUE data;
2089 int sign;
2090
2091 sign = r_byte(arg);
2092 if (sign != '+' && sign != '-') {
2093 rb_raise(rb_eArgError, "invalid Bignum sign");
2094 }
2095 len = r_keep_readable(arg, r_long(arg), 2);
2096
2097 if (SIZEOF_VALUE >= 8 && len <= 4) {
2098 // Representable within uintptr, likely FIXNUM
2099 VALUE num = 0;
2100 for (int i = 0; i < len; i++) {
2101 num |= (VALUE)r_byte(arg) << (i * 16);
2102 num |= (VALUE)r_byte(arg) << (i * 16 + 8);
2103 }
2104#if SIZEOF_VALUE == SIZEOF_LONG
2105 v = ULONG2NUM(num);
2106#else
2107 v = ULL2NUM(num);
2108#endif
2109 if (sign == '-') {
2110 v = rb_int_uminus(v);
2111 }
2112 }
2113 else {
2114 data = r_bytes0(len * 2, arg);
2115 v = rb_integer_unpack(RSTRING_PTR(data), len, 2, 0,
2116 INTEGER_PACK_LITTLE_ENDIAN | (sign == '-' ? INTEGER_PACK_NEGATIVE : 0));
2117 rb_str_resize(data, 0L);
2118 }
2119 v = r_entry(v, arg);
2120 v = r_leave(v, arg, false);
2121 }
2122 break;
2123
2124 case TYPE_STRING:
2125 v = r_entry(r_string(arg), arg);
2126 v = r_leave(v, arg, partial);
2127 break;
2128
2129 case TYPE_REGEXP:
2130 {
2131 VALUE str = r_bytes(arg);
2132 int options = r_byte(arg);
2133 int has_encoding = FALSE;
2134 st_index_t idx = r_prepare(arg);
2135
2136 if (ivp) {
2137 r_ivar(str, &has_encoding, arg);
2138 *ivp = FALSE;
2139 }
2140 if (!has_encoding) {
2141 /* 1.8 compatibility; remove escapes undefined in 1.8 */
2142 char *ptr = RSTRING_PTR(str), *dst = ptr, *src = ptr;
2143 long len = RSTRING_LEN(str);
2144 long bs = 0;
2145 for (; len-- > 0; *dst++ = *src++) {
2146 switch (*src) {
2147 case '\\': bs++; break;
2148 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
2149 case 'm': case 'o': case 'p': case 'q': case 'u': case 'y':
2150 case 'E': case 'F': case 'H': case 'I': case 'J': case 'K':
2151 case 'L': case 'N': case 'O': case 'P': case 'Q': case 'R':
2152 case 'S': case 'T': case 'U': case 'V': case 'X': case 'Y':
2153 if (bs & 1) --dst;
2154 /* fall through */
2155 default: bs = 0; break;
2156 }
2157 }
2158 rb_str_set_len(str, dst - ptr);
2159 }
2160 if (!klass) {
2161 klass = rb_cRegexp;
2162 }
2163 VALUE regexp = rb_reg_init_str(rb_reg_s_alloc(klass), str, options);
2164 r_copy_ivar(regexp, str);
2165
2166 v = r_entry0(regexp, idx, arg);
2167 v = r_leave(v, arg, partial);
2168 }
2169 break;
2170
2171 case TYPE_ARRAY:
2172 {
2173 long len = r_keep_readable(arg, r_long(arg), 1);
2174
2175 v = rb_ary_new2(len);
2176 v = r_entry(v, arg);
2177 arg->readable += len - 1;
2178 while (len--) {
2179 rb_ary_push(v, r_object(arg));
2180 arg->readable--;
2181 }
2182 v = r_leave(v, arg, partial);
2183 arg->readable++;
2184 }
2185 break;
2186
2187 case TYPE_HASH:
2188 case TYPE_HASH_DEF:
2189 type_hash:
2190 {
2191 long len = r_keep_readable(arg, r_long(arg), 2);
2192
2193 v = hash_new_capa(len);
2194 v = r_entry(v, arg);
2195 arg->readable += (len - 1) * 2;
2196 while (len--) {
2197 VALUE key = r_object(arg);
2198 VALUE value = r_object(arg);
2199 rb_hash_aset(v, key, value);
2200 arg->readable -= 2;
2201 }
2202 arg->readable += 2;
2203 if (type == TYPE_HASH_DEF) {
2204 RHASH_SET_IFNONE(v, r_object(arg));
2205 }
2206 v = r_leave(v, arg, partial);
2207 }
2208 break;
2209
2210 case TYPE_STRUCT:
2211 {
2212 VALUE mem, values;
2213 long i;
2214 VALUE slot;
2215 st_index_t idx = r_prepare(arg);
2216 VALUE klass = path2class(r_unique(arg));
2217 long len = r_keep_readable(arg, r_long(arg), 2);
2218
2219 v = rb_obj_alloc(klass);
2220 if (!RB_TYPE_P(v, T_STRUCT)) {
2221 rb_raise(rb_eTypeError, "class %"PRIsVALUE" not a struct", rb_class_name(klass));
2222 }
2223 mem = rb_struct_s_members(klass);
2224 if (RARRAY_LEN(mem) != len) {
2225 rb_raise(rb_eTypeError, "struct %"PRIsVALUE" not compatible (struct size differs)",
2226 rb_class_name(klass));
2227 }
2228
2229 arg->readable += (len - 1) * 2;
2230 v = r_entry0(v, idx, arg);
2231 values = rb_ary_new2(len);
2232 {
2233 VALUE keywords = Qfalse;
2234 if (RTEST(rb_struct_s_keyword_init(klass))) {
2235 keywords = rb_hash_new();
2236 rb_ary_push(values, keywords);
2237 }
2238
2239 for (i=0; i<len; i++) {
2240 VALUE n = rb_sym2str(RARRAY_AREF(mem, i));
2241 slot = r_symbol(arg);
2242
2243 if (!rb_str_equal(n, slot)) {
2244 rb_raise(rb_eTypeError, "struct %"PRIsVALUE" not compatible (:%"PRIsVALUE" for :%"PRIsVALUE")",
2245 rb_class_name(klass),
2246 slot, n);
2247 }
2248 if (keywords) {
2249 rb_hash_aset(keywords, RARRAY_AREF(mem, i), r_object(arg));
2250 }
2251 else {
2252 rb_ary_push(values, r_object(arg));
2253 }
2254 arg->readable -= 2;
2255 }
2256 }
2257 rb_struct_initialize(v, values);
2258 v = r_leave(v, arg, partial);
2259 arg->readable += 2;
2260 }
2261 break;
2262
2263 case TYPE_USERDEF:
2264 {
2265 VALUE name = r_unique(arg);
2266 VALUE klass = path2class(name);
2267 VALUE data;
2268 st_data_t d;
2269
2270 if (!rb_obj_respond_to(klass, s_load, TRUE)) {
2271 rb_raise(rb_eTypeError, "class %"PRIsVALUE" needs to have method '_load'",
2272 name);
2273 }
2274 data = r_string(arg);
2275 if (ivp) {
2276 r_ivar(data, NULL, arg);
2277 *ivp = FALSE;
2278 }
2279 v = load_funcall(arg, klass, s_load, 1, &data);
2280 v = r_entry(v, arg);
2281 if (st_lookup(compat_allocator_tbl, (st_data_t)rb_get_alloc_func(klass), &d)) {
2282 marshal_compat_t *compat = (marshal_compat_t*)d;
2283 v = compat->loader(klass, v);
2284 }
2285 if (!partial) {
2286 if (arg->freeze) {
2287 OBJ_FREEZE(v);
2288 }
2289 v = r_post_proc(v, arg);
2290 }
2291 }
2292 break;
2293
2294 case TYPE_USRMARSHAL:
2295 {
2296 VALUE name = r_unique(arg);
2297 VALUE klass = path2class(name);
2298 VALUE oldclass = 0;
2299 VALUE data;
2300
2301 v = obj_alloc_by_klass(klass, arg, &oldclass);
2302 if (!NIL_P(extmod)) {
2303 /* for the case marshal_load is overridden */
2304 append_extmod(v, extmod);
2305 }
2306 if (!rb_obj_respond_to(v, s_mload, TRUE)) {
2307 rb_raise(rb_eTypeError, "instance of %"PRIsVALUE" needs to have method 'marshal_load'",
2308 name);
2309 }
2310 v = r_entry(v, arg);
2311 data = r_object(arg);
2312 load_funcall(arg, v, s_mload, 1, &data);
2313 v = r_fixup_compat(v, arg);
2314 v = r_copy_ivar(v, data);
2315 if (arg->freeze) {
2316 OBJ_FREEZE(v);
2317 }
2318 v = r_post_proc(v, arg);
2319 if (!NIL_P(extmod)) {
2320 if (oldclass) append_extmod(v, extmod);
2321 rb_ary_clear(extmod);
2322 }
2323 }
2324 break;
2325
2326 case TYPE_OBJECT:
2327 {
2328 st_index_t idx = r_prepare(arg);
2329 v = obj_alloc_by_path(r_unique(arg), arg);
2330 if (!RB_TYPE_P(v, T_OBJECT)) {
2331 rb_raise(rb_eArgError, "dump format error");
2332 }
2333 v = r_entry0(v, idx, arg);
2334 r_ivar(v, NULL, arg);
2335 v = r_leave(v, arg, partial);
2336 }
2337 break;
2338
2339 case TYPE_DATA:
2340 {
2341 VALUE name = r_unique(arg);
2342 VALUE klass = path2class(name);
2343 VALUE oldclass = 0;
2344 VALUE r;
2345
2346 v = obj_alloc_by_klass(klass, arg, &oldclass);
2347 if (!RB_TYPE_P(v, T_DATA)) {
2348 rb_raise(rb_eArgError, "dump format error");
2349 }
2350 v = r_entry(v, arg);
2351 if (!rb_obj_respond_to(v, s_load_data, TRUE)) {
2352 rb_raise(rb_eTypeError,
2353 "class %"PRIsVALUE" needs to have instance method '_load_data'",
2354 name);
2355 }
2356 r = r_object0(arg, partial, 0, extmod);
2357 load_funcall(arg, v, s_load_data, 1, &r);
2358 v = r_leave(v, arg, partial);
2359 }
2360 break;
2361
2362 case TYPE_MODULE_OLD:
2363 {
2364 VALUE str = r_bytes(arg);
2365
2366 v = rb_path_to_class(str);
2367 prohibit_ivar("class/module", str);
2368 v = r_entry(v, arg);
2369 v = r_leave(v, arg, partial);
2370 }
2371 break;
2372
2373 case TYPE_CLASS:
2374 {
2375 VALUE str = r_bytes(arg);
2376
2377 if (ivp && *ivp > 0) *ivp = r_encname(str, arg) > 0;
2378 v = path2class(str);
2379 prohibit_ivar("class", str);
2380 v = r_entry(v, arg);
2381 v = r_leave(v, arg, partial);
2382 }
2383 break;
2384
2385 case TYPE_MODULE:
2386 {
2387 VALUE str = r_bytes(arg);
2388
2389 if (ivp && *ivp > 0) *ivp = r_encname(str, arg) > 0;
2390 v = path2module(str);
2391 prohibit_ivar("module", str);
2392 v = r_entry(v, arg);
2393 v = r_leave(v, arg, partial);
2394 }
2395 break;
2396
2397 case TYPE_SYMBOL:
2398 if (ivp) {
2399 v = r_symreal(arg, *ivp);
2400 *ivp = FALSE;
2401 }
2402 else {
2403 v = r_symreal(arg, 0);
2404 }
2405 v = rb_str_intern(v);
2406 v = r_leave(v, arg, partial);
2407 break;
2408
2409 case TYPE_SYMLINK:
2410 v = rb_str_intern(r_symlink(arg));
2411 break;
2412
2413 default:
2414 rb_raise(rb_eArgError, "dump format error(0x%x)", type);
2415 break;
2416 }
2417
2418 if (UNDEF_P(v)) {
2419 rb_raise(rb_eArgError, "dump format error (bad link)");
2420 }
2421
2422 return v;
2423}
2424
2425static VALUE
2426r_object(struct load_arg *arg)
2427{
2428 return r_object0(arg, false, 0, Qnil);
2429}
2430
2431static void
2432clear_load_arg(struct load_arg *arg)
2433{
2434 ruby_xfree_sized(arg->buf, arg->bufsize);
2435 arg->buf = NULL;
2436 arg->bufsize = 0;
2437 arg->buflen = 0;
2438 arg->offset = 0;
2439 arg->readable = 0;
2440 if (!arg->has_symbols) return;
2441 st_free_embedded_table(&arg->symbols);
2442 arg->has_symbols = false;
2443 st_free_embedded_table(&arg->data);
2444 arg->has_data = false;
2445 if (arg->has_partial_objects) {
2446 st_free_embedded_table(&arg->partial_objects);
2447 arg->has_partial_objects = false;
2448 }
2449 if (arg->has_compat_tbl) {
2450 st_free_embedded_table(&arg->compat_tbl);
2451 arg->has_compat_tbl = false;
2452 }
2453}
2454
2455VALUE
2456rb_marshal_load_with_proc(VALUE port, VALUE proc, bool freeze)
2457{
2458 int major, minor;
2459 VALUE v;
2460 VALUE wrapper; /* used to avoid memory leak in case of exception */
2461 struct load_arg *arg;
2462
2463 v = rb_check_string_type(port);
2464 if (!NIL_P(v)) {
2465 port = v;
2466 }
2467 else if (rb_respond_to(port, s_getbyte) && rb_respond_to(port, s_read)) {
2468 rb_check_funcall(port, s_binmode, 0, 0);
2469 }
2470 else {
2471 io_needed();
2472 }
2473 wrapper = TypedData_Make_Struct(0, struct load_arg, &load_arg_data, arg);
2474 arg->src = port;
2475 arg->offset = 0;
2476 st_init_existing_numtable_with_size(&arg->symbols, 0);
2477 arg->has_symbols = true;
2478 rb_init_existing_identtable_with_size(&arg->data, 0);
2479 arg->has_data = true;
2480 if (RTEST(proc) || freeze) {
2481 rb_init_existing_identtable_with_size(&arg->partial_objects, 0);
2482 arg->has_partial_objects = true;
2483 }
2484 arg->proc = 0;
2485 arg->readable = 0;
2486 arg->freeze = freeze;
2487
2488 if (NIL_P(v)) {
2489 arg->bufsize = BUFSIZ;
2490 arg->buf = xmalloc(BUFSIZ);
2491 }
2492 else {
2493 arg->bufsize = 0;
2494 arg->buf = 0;
2495 }
2496
2497 major = r_byte(arg);
2498 minor = r_byte(arg);
2499 if (major != MARSHAL_MAJOR || minor > MARSHAL_MINOR) {
2500 clear_load_arg(arg);
2501 rb_raise(rb_eTypeError, "incompatible marshal file format (can't be read)\n\
2502\tformat version %d.%d required; %d.%d given",
2503 MARSHAL_MAJOR, MARSHAL_MINOR, major, minor);
2504 }
2505 if (RTEST(ruby_verbose) && minor != MARSHAL_MINOR) {
2506 rb_warn("incompatible marshal file format (can be read)\n\
2507\tformat version %d.%d required; %d.%d given",
2508 MARSHAL_MAJOR, MARSHAL_MINOR, major, minor);
2509 }
2510
2511 if (!NIL_P(proc)) arg->proc = proc;
2512 v = r_object(arg);
2513 clear_load_arg(arg);
2514 RB_GC_GUARD(wrapper);
2515
2516 return v;
2517}
2518
2519static VALUE
2520marshal_load(rb_execution_context_t *ec, VALUE mod, VALUE source, VALUE proc, VALUE freeze)
2521{
2522 return rb_marshal_load_with_proc(source, proc, RTEST(freeze));
2523}
2524
2525#include "marshal.rbinc"
2526
2527/*
2528 * The marshaling library converts collections of Ruby objects into a
2529 * byte stream, allowing them to be stored outside the currently
2530 * active script. This data may subsequently be read and the original
2531 * objects reconstituted.
2532 *
2533 * Marshaled data has major and minor version numbers stored along
2534 * with the object information. In normal use, marshaling can only
2535 * load data written with the same major version number and an equal
2536 * or lower minor version number. If Ruby's ``verbose'' flag is set
2537 * (normally using -d, -v, -w, or --verbose) the major and minor
2538 * numbers must match exactly. Marshal versioning is independent of
2539 * Ruby's version numbers. You can extract the version by reading the
2540 * first two bytes of marshaled data.
2541 *
2542 * str = Marshal.dump("thing")
2543 * RUBY_VERSION #=> "1.9.0"
2544 * str[0].ord #=> 4
2545 * str[1].ord #=> 8
2546 *
2547 * Some objects cannot be dumped: if the objects to be dumped include
2548 * bindings, procedure or method objects, instances of class IO, or
2549 * singleton objects, a TypeError will be raised.
2550 *
2551 * If your class has special serialization needs (for example, if you
2552 * want to serialize in some specific format), or if it contains
2553 * objects that would otherwise not be serializable, you can implement
2554 * your own serialization strategy.
2555 *
2556 * There are two methods of doing this, your object can define either
2557 * marshal_dump and marshal_load or _dump and _load. marshal_dump will take
2558 * precedence over _dump if both are defined. marshal_dump may result in
2559 * smaller Marshal strings.
2560 *
2561 * == Security considerations
2562 *
2563 * By design, Marshal.load can deserialize almost any class loaded into the
2564 * Ruby process. In many cases this can lead to remote code execution if the
2565 * Marshal data is loaded from an untrusted source.
2566 *
2567 * As a result, Marshal.load is not suitable as a general purpose serialization
2568 * format and you should never unmarshal user supplied input or other untrusted
2569 * data.
2570 *
2571 * If you need to deserialize untrusted data, use JSON or another serialization
2572 * format that is only able to load simple, 'primitive' types such as String,
2573 * Array, Hash, etc. Never allow user input to specify arbitrary types to
2574 * deserialize into.
2575 *
2576 * == marshal_dump and marshal_load
2577 *
2578 * When dumping an object the method marshal_dump will be called.
2579 * marshal_dump must return a result containing the information necessary for
2580 * marshal_load to reconstitute the object. The result can be any object.
2581 *
2582 * When loading an object dumped using marshal_dump the object is first
2583 * allocated then marshal_load is called with the result from marshal_dump.
2584 * marshal_load must recreate the object from the information in the result.
2585 *
2586 * Example:
2587 *
2588 * class MyObj
2589 * def initialize name, version, data
2590 * @name = name
2591 * @version = version
2592 * @data = data
2593 * end
2594 *
2595 * def marshal_dump
2596 * [@name, @version]
2597 * end
2598 *
2599 * def marshal_load array
2600 * @name, @version = array
2601 * end
2602 * end
2603 *
2604 * == _dump and _load
2605 *
2606 * Use _dump and _load when you need to allocate the object you're restoring
2607 * yourself.
2608 *
2609 * When dumping an object the instance method _dump is called with an Integer
2610 * which indicates the maximum depth of objects to dump (a value of -1 implies
2611 * that you should disable depth checking). _dump must return a String
2612 * containing the information necessary to reconstitute the object.
2613 *
2614 * The class method _load should take a String and use it to return an object
2615 * of the same class.
2616 *
2617 * Example:
2618 *
2619 * class MyObj
2620 * def initialize name, version, data
2621 * @name = name
2622 * @version = version
2623 * @data = data
2624 * end
2625 *
2626 * def _dump level
2627 * [@name, @version].join ':'
2628 * end
2629 *
2630 * def self._load args
2631 * new(*args.split(':'))
2632 * end
2633 * end
2634 *
2635 * Since Marshal.dump outputs a string you can have _dump return a Marshal
2636 * string which is Marshal.loaded in _load for complex objects.
2637 */
2638void
2639Init_marshal(void)
2640{
2641 VALUE rb_mMarshal = rb_define_module("Marshal");
2642#define set_id(sym) sym = rb_intern_const(name_##sym)
2643 set_id(s_dump);
2644 set_id(s_load);
2645 set_id(s_mdump);
2646 set_id(s_mload);
2647 set_id(s_dump_data);
2648 set_id(s_load_data);
2649 set_id(s_call);
2650 set_id(s_getbyte);
2651 set_id(s_read);
2652 set_id(s_write);
2653 set_id(s_binmode);
2654 set_id(s_encoding_short);
2655 set_id(s_ruby2_keywords_flag);
2656
2657 rb_define_module_function(rb_mMarshal, "dump", marshal_dump, -1);
2658
2659 /* major version */
2660 rb_define_const(rb_mMarshal, "MAJOR_VERSION", INT2FIX(MARSHAL_MAJOR));
2661 /* minor version */
2662 rb_define_const(rb_mMarshal, "MINOR_VERSION", INT2FIX(MARSHAL_MINOR));
2663}
2664
2665static int
2666marshal_compat_table_mark_and_move_i(st_data_t key, st_data_t value, st_data_t _)
2667{
2668 marshal_compat_t *p = (marshal_compat_t *)value;
2669 rb_gc_mark_and_move(&p->newclass);
2670 rb_gc_mark_and_move(&p->oldclass);
2671 return ST_CONTINUE;
2672}
2673
2674static void
2675marshal_compat_table_mark_and_move(void *tbl)
2676{
2677 if (!tbl) return;
2678 st_foreach(tbl, marshal_compat_table_mark_and_move_i, 0);
2679}
2680
2681static int
2682marshal_compat_table_free_i(st_data_t key, st_data_t value, st_data_t _)
2683{
2684 SIZED_FREE((marshal_compat_t *)value);
2685 return ST_CONTINUE;
2686}
2687
2688static void
2689marshal_compat_table_free(void *data)
2690{
2691 st_foreach(data, marshal_compat_table_free_i, 0);
2692 st_free_table(data);
2693}
2694
2695static size_t
2696marshal_compat_table_memsize(const void *data)
2697{
2698 return st_memsize(data) + sizeof(marshal_compat_t) * st_table_size(data);
2699}
2700
2701static const rb_data_type_t marshal_compat_type = {
2702 .wrap_struct_name = "marshal_compat_table",
2703 .function = {
2704 .dmark = marshal_compat_table_mark_and_move,
2705 .dfree = marshal_compat_table_free,
2706 .dsize = marshal_compat_table_memsize,
2707 .dcompact = marshal_compat_table_mark_and_move,
2708 },
2709 .flags = RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_THREAD_SAFE_FREE,
2710};
2711
2712static st_table *
2713compat_allocator_table(void)
2714{
2715 if (compat_allocator_tbl) return compat_allocator_tbl;
2716 compat_allocator_tbl = st_init_numtable();
2717 compat_allocator_tbl_wrapper =
2718 TypedData_Wrap_Struct(0, &marshal_compat_type, compat_allocator_tbl);
2719 rb_vm_register_global_object(compat_allocator_tbl_wrapper);
2720 return compat_allocator_tbl;
2721}
2722
2723VALUE
2724rb_marshal_dump(VALUE obj, VALUE port)
2725{
2726 return rb_marshal_dump_limited(obj, port, -1);
2727}
2728
2729VALUE
2730rb_marshal_load(VALUE port)
2731{
2732 return rb_marshal_load_with_proc(port, Qnil, false);
2733}
Defines RBIMPL_HAS_BUILTIN.
int len
Length of the buffer.
Definition io.h:8
Defines RBIMPL_ATTR_NONSTRING.