12#include "ruby/internal/config.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/numeric.h"
32#include "internal/object.h"
33#include "internal/struct.h"
34#include "internal/symbol.h"
35#include "internal/util.h"
36#include "internal/vm.h"
45#define BITSPERSHORT (2*CHAR_BIT)
46#define SHORTMASK ((1<<BITSPERSHORT)-1)
47#define SHORTDN(x) RSHIFT((x),BITSPERSHORT)
49#if SIZEOF_SHORT == SIZEOF_BDIGIT
50#define SHORTLEN(x) (x)
53shortlen(
size_t len, BDIGIT *ds)
63 return (
len - 1)*SIZEOF_BDIGIT/2 + offset;
65#define SHORTLEN(x) shortlen((x),d)
68#define MARSHAL_MAJOR 4
69#define MARSHAL_MINOR 8
74#define TYPE_FIXNUM 'i'
76#define TYPE_EXTENDED 'e'
77#define TYPE_UCLASS 'C'
78#define TYPE_OBJECT 'o'
80#define TYPE_USERDEF 'u'
81#define TYPE_USRMARSHAL 'U'
83#define TYPE_BIGNUM 'l'
84#define TYPE_STRING '"'
85#define TYPE_REGEXP '/'
88#define TYPE_HASH_DEF '}'
89#define TYPE_STRUCT 'S'
90#define TYPE_MODULE_OLD 'M'
92#define TYPE_MODULE 'm'
94#define TYPE_SYMBOL ':'
95#define TYPE_SYMLINK ';'
100static ID s_dump, s_load, s_mdump, s_mload;
101static ID s_dump_data, s_load_data, s_alloc, s_call;
102static ID s_getbyte, s_read, s_write, s_binmode;
103static ID s_encoding_short, s_ruby2_keywords_flag;
104#define s_encoding_long rb_id_encoding()
106#define name_s_dump "_dump"
107#define name_s_load "_load"
108#define name_s_mdump "marshal_dump"
109#define name_s_mload "marshal_load"
110#define name_s_dump_data "_dump_data"
111#define name_s_load_data "_load_data"
112#define name_s_alloc "_alloc"
113#define name_s_call "call"
114#define name_s_getbyte "getbyte"
115#define name_s_read "read"
116#define name_s_write "write"
117#define name_s_binmode "binmode"
118#define name_s_encoding_short "E"
119#define name_s_encoding_long "encoding"
120#define name_s_ruby2_keywords_flag "K"
125 VALUE (*dumper)(VALUE);
126 VALUE (*loader)(VALUE, VALUE);
129static st_table *compat_allocator_tbl;
130static VALUE compat_allocator_tbl_wrapper;
131static VALUE rb_marshal_dump_limited(VALUE obj, VALUE port, int limit);
132static VALUE rb_marshal_load_with_proc(VALUE port, VALUE proc, bool freeze);
134static st_table *compat_allocator_table(void);
137rb_marshal_define_compat(VALUE newclass, VALUE oldclass, VALUE (*dumper)(VALUE), VALUE (*loader)(VALUE, VALUE))
139 marshal_compat_t *compat;
140 rb_alloc_func_t allocator = rb_get_alloc_func(newclass);
143 rb_raise(rb_eTypeError, "no allocator");
146 compat_allocator_table();
147 compat = ALLOC(marshal_compat_t);
148 compat->newclass = newclass;
149 compat->oldclass = oldclass;
150 compat->dumper = dumper;
151 compat->loader = loader;
153 st_insert(compat_allocator_table(), (st_data_t)allocator, (st_data_t)compat);
154 RB_OBJ_WRITTEN(compat_allocator_tbl_wrapper, Qundef, newclass);
155 RB_OBJ_WRITTEN(compat_allocator_tbl_wrapper, Qundef, oldclass);
162 st_table *compat_tbl;
165 st_index_t num_entries;
168struct dump_call_arg {
170 struct dump_arg *arg;
175check_dump_arg(VALUE ret, struct dump_arg *arg, const char *name)
178 rb_raise(rb_eRuntimeError, "Marshal.dump reentered at %s",
185check_userdump_arg(VALUE obj, ID sym, int argc, const VALUE *argv,
186 struct dump_arg *arg, const char *name)
188 VALUE ret = rb_funcallv(obj, sym, argc, argv);
189 VALUE klass = CLASS_OF(obj);
190 if (CLASS_OF(ret) == klass) {
191 rb_raise(rb_eRuntimeError, "%"PRIsVALUE"#%s returned same class instance",
194 return check_dump_arg(ret, arg, name);
197#define dump_funcall(arg, obj, sym, argc, argv) \
198 check_userdump_arg(obj, sym, argc, argv, arg, name_##sym)
199#define dump_check_funcall(arg, obj, sym, argc, argv) \
200 check_dump_arg(rb_check_funcall(obj, sym, argc, argv), arg, name_##sym)
202static void clear_dump_arg(struct dump_arg *arg);
205mark_dump_arg(void *ptr)
207 struct dump_arg *p = ptr;
210 rb_mark_set(p->symbols);
211 rb_mark_set(p->data);
212 rb_mark_hash(p->compat_tbl);
213 rb_mark_set(p->userdefs);
218free_dump_arg(void *ptr)
224memsize_dump_arg(const void *ptr)
226 const struct dump_arg *p = (struct dump_arg *)ptr;
228 if (p->symbols) memsize += rb_st_memsize(p->symbols);
229 if (p->data) memsize += rb_st_memsize(p->data);
230 if (p->compat_tbl) memsize += rb_st_memsize(p->compat_tbl);
231 if (p->userdefs) memsize += rb_st_memsize(p->userdefs);
232 if (p->encodings) memsize += rb_st_memsize(p->encodings);
236static const rb_data_type_t dump_arg_data = {
238 {mark_dump_arg, free_dump_arg, memsize_dump_arg,},
239 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_EMBEDDABLE
243must_not_be_anonymous(const char *type, VALUE path)
245 char *n = RSTRING_PTR(path);
247 if (!rb_enc_asciicompat(rb_enc_get(path))) {
249 rb_raise(rb_eTypeError, "can't dump non-ascii %s name % "PRIsVALUE,
253 rb_raise(rb_eTypeError, "can't dump anonymous %s % "PRIsVALUE,
260class2path(VALUE klass)
262 VALUE path = rb_class_path(klass);
264 must_not_be_anonymous((RB_TYPE_P(klass, T_CLASS) ? "class" : "module"), path);
265 if (rb_path_to_class(path) != rb_class_real(klass)) {
266 rb_raise(rb_eTypeError, "% "PRIsVALUE" can't be referred to", path);
271int ruby_marshal_write_long(long x, char *buf);
272static void w_long(long, struct dump_arg*);
273static int w_encoding(VALUE encname, struct dump_call_arg *arg);
274static VALUE encoding_name(VALUE obj, struct dump_arg *arg);
277w_nbyte(const char *s, long n, struct dump_arg *arg)
279 VALUE buf = arg->str;
280 rb_str_buf_cat(buf, s, n);
281 if (arg->dest && RSTRING_LEN(buf) >= BUFSIZ) {
282 rb_io_write(arg->dest, buf);
283 rb_str_resize(buf, 0);
288w_byte(char c, struct dump_arg *arg)
294w_bytes(const char *s, long n, struct dump_arg *arg)
300#define w_cstr(s, arg) w_bytes((s), strlen(s), (arg))
303w_short(int x, struct dump_arg *arg)
305 w_byte((char)((x >> 0) & 0xff), arg);
306 w_byte((char)((x >> 8) & 0xff), arg);
310w_long(long x, struct dump_arg *arg)
312 char buf[sizeof(long)+1];
313 int i = ruby_marshal_write_long(x, buf);
315 rb_raise(rb_eTypeError, "long too big to dump");
317 w_nbyte(buf, i, arg);
321ruby_marshal_write_long(long x, char *buf)
326 if (!(RSHIFT(x, 31) == 0 || RSHIFT(x, 31) == -1)) {
327 /* big long does not fit in 4 bytes */
336 if (0 < x && x < 123) {
337 buf[0] = (char)(x + 5);
340 if (-124 < x && x < 0) {
341 buf[0] = (char)((x - 5)&0xff);
344 for (i=1;i<(int)sizeof(long)+1;i++) {
345 buf[i] = (char)(x & 0xff);
360#define DECIMAL_MANT (53-16) /* from IEEE754 double precision */
364#elif DBL_MANT_DIG > 24
366#elif DBL_MANT_DIG > 16
373load_mantissa(double d, const char *buf, long len)
376 if (--len > 0 && !*buf++) { /* binary mantissa mark */
377 int e, s = d < 0, dig = 0;
380 modf(ldexp(frexp(fabs(d), &e), DECIMAL_MANT), &d);
384 default: m = *buf++ & 0xff; /* fall through */
386 case 3: m = (m << 8) | (*buf++ & 0xff); /* fall through */
389 case 2: m = (m << 8) | (*buf++ & 0xff); /* fall through */
392 case 1: m = (m << 8) | (*buf++ & 0xff);
395 dig -= len < MANT_BITS / 8 ? 8 * (unsigned)len : MANT_BITS;
396 d += ldexp((double)m, dig);
397 } while ((len -= MANT_BITS / 8) > 0);
398 d = ldexp(d, e - DECIMAL_MANT);
404#define load_mantissa(d, buf, len) (d)
408#define FLOAT_DIG (DBL_DIG+2)
414w_float(double d, struct dump_arg *arg)
416 char buf[FLOAT_DIG + (DECIMAL_MANT + 7) / 8 + 10];
419 if (d < 0) w_cstr("-inf", arg);
420 else w_cstr("inf", arg);
426 if (signbit(d)) w_cstr("-0", arg);
427 else w_cstr("0", arg);
430 int decpt, sign, digs, len = 0;
431 char *e, *p = ruby_dtoa(d, 0, 0, &decpt, &sign, &e);
432 if (sign) buf[len++] = '-';
434 if (decpt < -3 || decpt > digs) {
436 if (--digs > 0) buf[len++] = '.';
437 memcpy(buf + len, p + 1, digs);
439 len += snprintf(buf + len, sizeof(buf) - len, "e%d", decpt - 1);
441 else if (decpt > 0) {
442 memcpy(buf + len, p, decpt);
444 if ((digs -= decpt) > 0) {
446 memcpy(buf + len, p + decpt, digs);
454 memset(buf + len, '0', -decpt);
457 memcpy(buf + len, p, digs);
461 w_bytes(buf, len, arg);
467w_encivar(VALUE str, struct dump_arg *arg)
469 VALUE encname = encoding_name(str, arg);
470 if (NIL_P(encname) ||
471 is_ascii_string(str)) {
474 w_byte(TYPE_IVAR, arg);
479w_encname(VALUE encname, struct dump_arg *arg)
481 if (!NIL_P(encname)) {
482 struct dump_call_arg c_arg;
486 w_encoding(encname, &c_arg);
491w_symbol(VALUE sym, struct dump_arg *arg)
496 if (st_lookup(arg->symbols, sym, &num)) {
497 w_byte(TYPE_SYMLINK, arg);
498 w_long((long)num, arg);
501 const VALUE orig_sym = sym;
502 sym = rb_sym2str(sym);
504 rb_raise(rb_eTypeError, "can't dump anonymous ID %"PRIdVALUE, sym);
506 encname = w_encivar(sym, arg);
507 w_byte(TYPE_SYMBOL, arg);
508 w_bytes(RSTRING_PTR(sym), RSTRING_LEN(sym), arg);
509 st_add_direct(arg->symbols, orig_sym, arg->symbols->num_entries);
510 w_encname(encname, arg);
515w_unique(VALUE s, struct dump_arg *arg)
517 must_not_be_anonymous("class", s);
518 w_symbol(rb_str_intern(s), arg);
521static void w_object(VALUE,struct dump_arg*,int);
524hash_each(VALUE key, VALUE value, VALUE v)
526 struct dump_call_arg *arg = (void *)v;
527 w_object(key, arg->arg, arg->limit);
528 w_object(value, arg->arg, arg->limit);
532#define SINGLETON_DUMP_UNABLE_P(klass) \
533 (rb_id_table_size(RCLASS_M_TBL(klass)) > 0 || \
534 rb_ivar_count(klass) > 0)
537w_extended(VALUE klass, struct dump_arg *arg, int check)
539 if (check && RCLASS_SINGLETON_P(klass)) {
540 VALUE origin = RCLASS_ORIGIN(klass);
541 if (SINGLETON_DUMP_UNABLE_P(klass) ||
542 (origin != klass && SINGLETON_DUMP_UNABLE_P(origin))) {
543 rb_raise(rb_eTypeError, "singleton can't be dumped");
545 klass = RCLASS_SUPER(klass);
547 while (BUILTIN_TYPE(klass) == T_ICLASS) {
548 if (!RICLASS_IS_ORIGIN_P(klass) ||
549 BUILTIN_TYPE(RBASIC(klass)->klass) != T_MODULE) {
550 VALUE path = rb_class_name(RBASIC(klass)->klass);
551 w_byte(TYPE_EXTENDED, arg);
554 klass = RCLASS_SUPER(klass);
559w_class(char type, VALUE obj, struct dump_arg *arg, int check)
565 if (arg->compat_tbl &&
566 st_lookup(arg->compat_tbl, (st_data_t)obj, &real_obj)) {
567 obj = (VALUE)real_obj;
569 klass = CLASS_OF(obj);
570 w_extended(klass, arg, check);
572 path = class2path(rb_class_real(klass));
577w_uclass(VALUE obj, VALUE super, struct dump_arg *arg)
579 VALUE klass = CLASS_OF(obj);
581 w_extended(klass, arg, TRUE);
582 klass = rb_class_real(klass);
583 if (klass != super) {
584 w_byte(TYPE_UCLASS, arg);
585 w_unique(class2path(klass), arg);
590rb_hash_ruby2_keywords_p(VALUE obj)
592 return (RHASH(obj)->basic.flags & RHASH_PASS_AS_KEYWORDS) != 0;
596rb_hash_ruby2_keywords(VALUE obj)
598 RHASH(obj)->basic.flags |= RHASH_PASS_AS_KEYWORDS;
602 * if instance variable name `id` is a special name to be skipped,
603 * returns the name of it. otherwise it cannot be dumped (unnamed),
604 * returns `name` as-is. returns NULL for ID that can be dumped.
606static inline const char *
607skipping_ivar_name(const ID id, const char *name)
609#define IS_SKIPPED_IVAR(idname) \
610 ((id == idname) && (name = name_##idname, true))
611 if (IS_SKIPPED_IVAR(s_encoding_short)) return name;
612 if (IS_SKIPPED_IVAR(s_ruby2_keywords_flag)) return name;
613 if (IS_SKIPPED_IVAR(s_encoding_long)) return name;
614 if (!rb_id2str(id)) return name;
619 struct dump_call_arg *dump;
624w_obj_each(ID id, VALUE value, st_data_t a)
626 struct w_ivar_arg *ivarg = (struct w_ivar_arg *)a;
627 struct dump_call_arg *arg = ivarg->dump;
628 const char unnamed[] = "", *ivname = skipping_ivar_name(id, unnamed);
631 if (ivname != unnamed) {
632 rb_warn("instance variable '%s' on class %"PRIsVALUE" is not dumped",
633 ivname, CLASS_OF(arg->obj));
638 w_symbol(ID2SYM(id), arg->arg);
639 w_object(value, arg->arg, arg->limit);
644obj_count_ivars(ID id, VALUE val, st_data_t a)
646 if (!skipping_ivar_name(id, "") && UNLIKELY(!++*(st_index_t *)a)) {
647 rb_raise(rb_eRuntimeError, "too many instance variables");
653encoding_name(VALUE obj, struct dump_arg *arg)
655 if (rb_enc_capable(obj)) {
656 int encidx = rb_enc_get_index(obj);
657 rb_encoding *enc = 0;
660 if (encidx <= 0 || !(enc = rb_enc_from_index(encidx))) {
664 /* special treatment for US-ASCII and UTF-8 */
665 if (encidx == rb_usascii_encindex()) {
668 else if (encidx == rb_utf8_encindex()) {
673 !st_lookup(arg->encodings, (st_data_t)rb_enc_name(enc), &name) :
674 (arg->encodings = st_init_strcasetable(), 1)) {
675 name = (st_data_t)rb_str_new_cstr(rb_enc_name(enc));
676 st_insert(arg->encodings, (st_data_t)rb_enc_name(enc), name);
686w_encoding(VALUE encname, struct dump_call_arg *arg)
688 int limit = arg->limit;
689 if (limit >= 0) ++limit;
693 w_symbol(ID2SYM(s_encoding_short), arg->arg);
694 w_object(encname, arg->arg, limit);
699 w_symbol(ID2SYM(rb_id_encoding()), arg->arg);
700 w_object(encname, arg->arg, limit);
705has_ivars(VALUE obj, VALUE encname, VALUE *ivobj)
707 st_index_t num = !NIL_P(encname);
709 if (SPECIAL_CONST_P(obj)) goto generic;
710 switch (BUILTIN_TYPE(obj)) {
714 break; /* counted elsewhere */
716 if (rb_hash_ruby2_keywords_p(obj)) ++num;
720 rb_ivar_foreach(obj, obj_count_ivars, (st_data_t)&num);
721 if (num) *ivobj = obj;
728w_ivar_each(VALUE obj, st_index_t num, struct dump_call_arg *arg)
730 struct w_ivar_arg ivarg = {arg, num};
732 rb_ivar_foreach_buffered(obj, w_obj_each, (st_data_t)&ivarg);
736w_ivar(st_index_t num, VALUE ivobj, VALUE encname, struct dump_call_arg *arg)
738 w_long(num, arg->arg);
739 num -= w_encoding(encname, arg);
740 if (RB_TYPE_P(ivobj, T_HASH) && rb_hash_ruby2_keywords_p(ivobj)) {
741 int limit = arg->limit;
742 if (limit >= 0) ++limit;
743 w_symbol(ID2SYM(s_ruby2_keywords_flag), arg->arg);
744 w_object(Qtrue, arg->arg, limit);
747 if (!UNDEF_P(ivobj) && num) {
748 w_ivar_each(ivobj, num, arg);
753w_objivar(VALUE obj, struct dump_call_arg *arg)
757 rb_ivar_foreach(obj, obj_count_ivars, (st_data_t)&num);
758 w_long(num, arg->arg);
759 w_ivar_each(obj, num, arg);
763// Optimized dump for fixnum larger than 31-bits
765w_bigfixnum(VALUE obj, struct dump_arg *arg)
767 RUBY_ASSERT(FIXNUM_P(obj));
769 w_byte(TYPE_BIGNUM, arg);
771#if SIZEOF_LONG == SIZEOF_VALUE
775 long long num, slen_num;
779 char sign = num < 0 ? '-' : '+';
782 // Guaranteed not to overflow, as FIXNUM is 1-bit less than long
783 if (num < 0) num = -num;
785 // calculate the size in shorts
791 slen_num = SHORTDN(slen_num);
795 RUBY_ASSERT(slen > 0 && slen <= SIZEOF_LONG / 2);
797 w_long((long)slen, arg);
799 for (int i = 0; i < slen; i++) {
800 w_short(num & SHORTMASK, arg);
804 // We aren't adding this object to the link table, but we need to increment
808 RUBY_ASSERT(num == 0);
813w_remember(VALUE obj, struct dump_arg *arg)
815 st_add_direct(arg->data, obj, arg->num_entries++);
819w_object(VALUE obj, struct dump_arg *arg, int limit)
821 struct dump_call_arg c_arg;
822 VALUE ivobj = Qundef;
824 st_index_t hasiv = 0;
825 VALUE encname = Qnil;
828 rb_raise(rb_eArgError, "exceed depth limit");
832 w_byte(TYPE_NIL, arg);
834 else if (obj == Qtrue) {
835 w_byte(TYPE_TRUE, arg);
837 else if (obj == Qfalse) {
838 w_byte(TYPE_FALSE, arg);
840 else if (FIXNUM_P(obj)) {
842 w_byte(TYPE_FIXNUM, arg);
843 w_long(FIX2INT(obj), arg);
845 if (RSHIFT((long)obj, 31) == 0 || RSHIFT((long)obj, 31) == -1) {
846 w_byte(TYPE_FIXNUM, arg);
847 w_long(FIX2LONG(obj), arg);
850 w_bigfixnum(obj, arg);
854 else if (SYMBOL_P(obj)) {
858 if (st_lookup(arg->data, obj, &num)) {
859 w_byte(TYPE_LINK, arg);
860 w_long((long)num, arg);
864 if (limit > 0) limit--;
870 w_remember(obj, arg);
871 w_byte(TYPE_FLOAT, arg);
872 w_float(RFLOAT_VALUE(obj), arg);
878 if (!RBASIC_CLASS(obj)) {
879 rb_raise(rb_eTypeError, "can't dump internal %s",
880 rb_builtin_type_name(BUILTIN_TYPE(obj)));
883 if (rb_obj_respond_to(obj, s_mdump, TRUE)) {
884 w_remember(obj, arg);
886 v = dump_funcall(arg, obj, s_mdump, 0, 0);
887 w_class(TYPE_USRMARSHAL, obj, arg, FALSE);
888 w_object(v, arg, limit);
891 if (rb_obj_respond_to(obj, s_dump, TRUE)) {
892 VALUE ivobj2 = Qundef;
896 if (arg->userdefs && st_is_member(arg->userdefs, (st_data_t)obj)) {
897 rb_raise(rb_eRuntimeError, "can't dump recursive object using _dump()");
900 v = dump_funcall(arg, obj, s_dump, 1, &v);
901 if (!RB_TYPE_P(v, T_STRING)) {
902 rb_raise(rb_eTypeError, "_dump() must return string");
904 hasiv = has_ivars(obj, (encname = encoding_name(obj, arg)), &ivobj);
905 hasiv2 = has_ivars(v, (encname2 = encoding_name(v, arg)), &ivobj2);
911 if (hasiv) w_byte(TYPE_IVAR, arg);
912 w_class(TYPE_USERDEF, obj, arg, FALSE);
913 w_bytes(RSTRING_PTR(v), RSTRING_LEN(v), arg);
915 st_data_t userdefs = (st_data_t)obj;
916 if (!arg->userdefs) {
917 arg->userdefs = rb_init_identtable();
919 st_add_direct(arg->userdefs, userdefs, 0);
920 w_ivar(hasiv, ivobj, encname, &c_arg);
921 st_delete(arg->userdefs, &userdefs, NULL);
923 w_remember(obj, arg);
927 w_remember(obj, arg);
929 hasiv = has_ivars(obj, (encname = encoding_name(obj, arg)), &ivobj);
931 st_data_t compat_data;
932 rb_alloc_func_t allocator = rb_get_alloc_func(RBASIC(obj)->klass);
933 if (st_lookup(compat_allocator_tbl,
934 (st_data_t)allocator,
936 marshal_compat_t *compat = (marshal_compat_t*)compat_data;
937 VALUE real_obj = obj;
938 obj = compat->dumper(real_obj);
939 if (!arg->compat_tbl) {
940 arg->compat_tbl = rb_init_identtable();
942 st_insert(arg->compat_tbl, (st_data_t)obj, (st_data_t)real_obj);
943 if (obj != real_obj && UNDEF_P(ivobj)) hasiv = 0;
946 if (hasiv) w_byte(TYPE_IVAR, arg);
948 switch (BUILTIN_TYPE(obj)) {
950 if (FL_TEST(obj, FL_SINGLETON)) {
951 rb_raise(rb_eTypeError, "singleton class can't be dumped");
954 VALUE path = class2path(obj);
955 VALUE encname = w_encivar(path, arg);
956 w_byte(TYPE_CLASS, arg);
957 w_bytes(RSTRING_PTR(path), RSTRING_LEN(path), arg);
958 w_encname(encname, arg);
965 VALUE path = class2path(obj);
966 VALUE encname = w_encivar(path, arg);
967 w_byte(TYPE_MODULE, arg);
968 w_bytes(RSTRING_PTR(path), RSTRING_LEN(path), arg);
969 w_encname(encname, arg);
975 w_byte(TYPE_FLOAT, arg);
976 w_float(RFLOAT_VALUE(obj), arg);
980 w_byte(TYPE_BIGNUM, arg);
982 char sign = BIGNUM_SIGN(obj) ? '+' : '-';
983 size_t len = BIGNUM_LEN(obj);
986 BDIGIT *d = BIGNUM_DIGITS(obj);
988 slen = SHORTLEN(len);
989 if (LONG_MAX < slen) {
990 rb_raise(rb_eTypeError, "too big Bignum can't be dumped");
994 w_long((long)slen, arg);
995 for (j = 0; j < len; j++) {
996#if SIZEOF_BDIGIT > SIZEOF_SHORT
1000 for (i=0; i<SIZEOF_BDIGIT; i+=SIZEOF_SHORT) {
1001 w_short(num & SHORTMASK, arg);
1003 if (j == len - 1 && num == 0) break;
1014 w_uclass(obj, rb_cString, arg);
1015 w_byte(TYPE_STRING, arg);
1016 w_bytes(RSTRING_PTR(obj), RSTRING_LEN(obj), arg);
1020 w_uclass(obj, rb_cRegexp, arg);
1021 w_byte(TYPE_REGEXP, arg);
1023 int opts = rb_reg_options(obj);
1024 w_bytes(RREGEXP_SRC_PTR(obj), RREGEXP_SRC_LEN(obj), arg);
1025 w_byte((char)opts, arg);
1030 w_uclass(obj, rb_cArray, arg);
1031 w_byte(TYPE_ARRAY, arg);
1033 long i, len = RARRAY_LEN(obj);
1036 for (i=0; i<RARRAY_LEN(obj); i++) {
1037 w_object(RARRAY_AREF(obj, i), arg, limit);
1038 if (len != RARRAY_LEN(obj)) {
1039 rb_raise(rb_eRuntimeError, "array modified during dump");
1046 w_uclass(obj, rb_cHash, arg);
1047 if (rb_hash_compare_by_id_p(obj)) {
1048 w_byte(TYPE_UCLASS, arg);
1049 w_symbol(rb_sym_intern_ascii_cstr("Hash"), arg);
1051 if (NIL_P(RHASH_IFNONE(obj))) {
1052 w_byte(TYPE_HASH, arg);
1054 else if (FL_TEST(obj, RHASH_PROC_DEFAULT)) {
1055 rb_raise(rb_eTypeError, "can't dump hash with default proc");
1058 w_byte(TYPE_HASH_DEF, arg);
1060 w_long(rb_hash_size_num(obj), arg);
1061 rb_hash_foreach(obj, hash_each, (st_data_t)&c_arg);
1062 if (!NIL_P(RHASH_IFNONE(obj))) {
1063 w_object(RHASH_IFNONE(obj), arg, limit);
1068 w_class(TYPE_STRUCT, obj, arg, TRUE);
1070 long len = RSTRUCT_LEN(obj);
1075 mem = rb_struct_members(obj);
1076 for (i=0; i<len; i++) {
1077 w_symbol(RARRAY_AREF(mem, i), arg);
1078 w_object(RSTRUCT_GET(obj, i), arg, limit);
1084 w_class(TYPE_OBJECT, obj, arg, TRUE);
1085 w_objivar(obj, &c_arg);
1092 if (!rb_obj_respond_to(obj, s_dump_data, TRUE)) {
1093 rb_raise(rb_eTypeError,
1094 "no _dump_data is defined for class %"PRIsVALUE,
1097 v = dump_funcall(arg, obj, s_dump_data, 0, 0);
1098 w_class(TYPE_DATA, obj, arg, TRUE);
1099 w_object(v, arg, limit);
1104 rb_raise(rb_eTypeError, "can't dump %"PRIsVALUE,
1111 w_ivar(hasiv, ivobj, encname, &c_arg);
1116clear_dump_arg(struct dump_arg *arg)
1118 if (!arg->symbols) return;
1119 st_free_table(arg->symbols);
1121 st_free_table(arg->data);
1123 arg->num_entries = 0;
1124 if (arg->compat_tbl) {
1125 st_free_table(arg->compat_tbl);
1126 arg->compat_tbl = 0;
1128 if (arg->encodings) {
1129 st_free_table(arg->encodings);
1132 if (arg->userdefs) {
1133 st_free_table(arg->userdefs);
1138NORETURN(static inline void io_needed(void));
1142 rb_raise(rb_eTypeError, "instance of IO needed");
1147 * dump( obj [, anIO] , limit=-1 ) -> anIO
1149 * Serializes obj and all descendant objects. If anIO is
1150 * specified, the serialized data will be written to it, otherwise the
1151 * data will be returned as a String. If limit is specified, the
1152 * traversal of subobjects will be limited to that depth. If limit is
1153 * negative, no checking of depth will be performed.
1156 * def initialize(str)
1164 * (produces no output)
1166 * o = Klass.new("hello\n")
1167 * data = Marshal.dump(o)
1168 * obj = Marshal.load(data)
1169 * obj.say_hello #=> "hello\n"
1171 * Marshal can't dump following objects:
1172 * * anonymous Class/Module.
1173 * * objects which are related to system (ex: Dir, File::Stat, IO, File, Socket
1175 * * an instance of MatchData, Method, UnboundMethod, Proc, Thread,
1176 * ThreadGroup, Continuation
1177 * * objects which define singleton methods
1180marshal_dump(int argc, VALUE *argv, VALUE _)
1182 VALUE obj, port, a1, a2;
1186 rb_scan_args(argc, argv, "12", &obj, &a1, &a2);
1188 if (!NIL_P(a2)) limit = NUM2INT(a2);
1189 if (NIL_P(a1)) io_needed();
1192 else if (argc == 2) {
1193 if (FIXNUM_P(a1)) limit = FIX2INT(a1);
1194 else if (NIL_P(a1)) io_needed();
1197 return rb_marshal_dump_limited(obj, port, limit);
1201rb_marshal_dump_limited(VALUE obj, VALUE port, int limit)
1203 struct dump_arg *arg;
1204 VALUE wrapper; /* used to avoid memory leak in case of exception */
1206 wrapper = TypedData_Make_Struct(0, struct dump_arg, &dump_arg_data, arg);
1208 arg->symbols = st_init_numtable();
1209 arg->data = rb_init_identtable();
1210 arg->num_entries = 0;
1211 arg->compat_tbl = 0;
1214 arg->str = rb_str_buf_new(0);
1216 if (!rb_respond_to(port, s_write)) {
1220 dump_check_funcall(arg, port, s_binmode, 0, 0);
1226 w_byte(MARSHAL_MAJOR, arg);
1227 w_byte(MARSHAL_MINOR, arg);
1229 w_object(obj, arg, limit);
1231 rb_io_write(arg->dest, arg->str);
1232 rb_str_resize(arg->str, 0);
1234 clear_dump_arg(arg);
1235 RB_GC_GUARD(wrapper);
1249 st_table *partial_objects;
1251 st_table *compat_tbl;
1256check_load_arg(VALUE ret, struct load_arg *arg, const char *name)
1258 if (!arg->symbols) {
1259 rb_raise(rb_eRuntimeError, "Marshal.load reentered at %s",
1264#define load_funcall(arg, obj, sym, argc, argv) \
1265 check_load_arg(rb_funcallv(obj, sym, argc, argv), arg, name_##sym)
1267static void clear_load_arg(struct load_arg *arg);
1270mark_load_arg(void *ptr)
1272 struct load_arg *p = ptr;
1275 rb_mark_tbl(p->symbols);
1276 rb_mark_tbl(p->data);
1277 rb_mark_tbl(p->partial_objects);
1278 rb_mark_hash(p->compat_tbl);
1282free_load_arg(void *ptr)
1284 clear_load_arg(ptr);
1288memsize_load_arg(const void *ptr)
1290 const struct load_arg *p = (struct load_arg *)ptr;
1292 if (p->symbols) memsize += rb_st_memsize(p->symbols);
1293 if (p->data) memsize += rb_st_memsize(p->data);
1294 if (p->partial_objects) memsize += rb_st_memsize(p->partial_objects);
1295 if (p->compat_tbl) memsize += rb_st_memsize(p->compat_tbl);
1299static const rb_data_type_t load_arg_data = {
1301 {mark_load_arg, free_load_arg, memsize_load_arg,},
1302 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_EMBEDDABLE
1305#define r_entry(v, arg) r_entry0((v), (arg)->data->num_entries, (arg))
1306static VALUE r_object(struct load_arg *arg);
1307static VALUE r_symbol(struct load_arg *arg);
1309NORETURN(static void too_short(void));
1313 rb_raise(rb_eArgError, "marshal data too short");
1317r_prepare(struct load_arg *arg)
1319 st_index_t idx = arg->data->num_entries;
1321 st_insert(arg->data, (st_data_t)idx, (st_data_t)Qundef);
1326r_byte1_buffered(struct load_arg *arg)
1328 if (arg->buflen == 0) {
1329 long readable = arg->readable < arg->bufsize ? arg->readable : arg->bufsize;
1331 VALUE str, n = LONG2NUM(readable);
1333 str = load_funcall(arg, arg->src, s_read, 1, &n);
1334 if (NIL_P(str)) too_short();
1336 read_len = RSTRING_LEN(str);
1337 if (UNLIKELY(read_len < readable)) too_short();
1338 if (UNLIKELY(read_len > arg->bufsize)) {
1339 arg->buf = ruby_sized_realloc_n(arg->buf, read_len, 1, arg->bufsize);
1340 arg->bufsize = read_len;
1342 memcpy(arg->buf, RSTRING_PTR(str), read_len);
1344 arg->buflen = read_len;
1348 return arg->buf[arg->offset++];
1352r_byte(struct load_arg *arg)
1356 if (RB_TYPE_P(arg->src, T_STRING)) {
1357 if (RSTRING_LEN(arg->src) > arg->offset) {
1358 c = (unsigned char)RSTRING_PTR(arg->src)[arg->offset++];
1365 if (arg->readable >0 || arg->buflen > 0) {
1366 c = r_byte1_buffered(arg);
1369 VALUE v = load_funcall(arg, arg->src, s_getbyte, 0, 0);
1370 if (NIL_P(v)) rb_eof_error();
1371 c = (unsigned char)NUM2CHR(v);
1377NORETURN(static void long_toobig(int size));
1380long_toobig(int size)
1382 rb_raise(rb_eTypeError, "long too big for this architecture (size "
1383 STRINGIZE(SIZEOF_LONG)", given %d)", size);
1387r_long(struct load_arg *arg)
1390 int c = (signed char)r_byte(arg);
1393 if (c == 0) return 0;
1395 if (4 < c && c < 128) {
1398 if (c > (int)sizeof(long)) long_toobig(c);
1401 x |= (long)r_byte(arg) << (8*i);
1405 if (-129 < c && c < -4) {
1409 if (c > (int)sizeof(long)) long_toobig(c);
1412 x &= ~((long)0xff << (8*i));
1413 x |= (long)r_byte(arg) << (8*i);
1420ruby_marshal_read_long(const char **buf, long len)
1423 struct RString src = {RBASIC_INIT};
1424 struct load_arg arg;
1425 memset(&arg, 0, sizeof(arg));
1426 arg.src = rb_setup_fake_str(&src, *buf, len, 0);
1433r_keep_readable(struct load_arg *arg, long len, size_t size)
1435 if (UNLIKELY(len < 0)) {
1436 rb_raise(rb_eArgError, "negative length");
1438 if (UNLIKELY((unsigned long)len > SIZE_MAX / size || arg->readable >= LONG_MAX - len)) {
1439 rb_raise(rb_eArgError, "marshaled data too big");
1445r_bytes1(long len, struct load_arg *arg)
1447 VALUE str, n = LONG2NUM(len);
1449 str = load_funcall(arg, arg->src, s_read, 1, &n);
1450 if (NIL_P(str)) too_short();
1452 if (RSTRING_LEN(str) != len) too_short();
1458r_bytes1_buffered(long len, struct load_arg *arg)
1462 if (len <= arg->buflen) {
1463 str = rb_str_new(arg->buf+arg->offset, len);
1468 long buflen = arg->buflen;
1469 long readable = arg->readable + 1;
1470 long tmp_len, read_len, need_len = len - buflen;
1473 readable = readable < arg->bufsize ? readable : arg->bufsize;
1474 read_len = need_len > readable ? need_len : readable;
1475 n = LONG2NUM(read_len);
1476 tmp = load_funcall(arg, arg->src, s_read, 1, &n);
1477 if (NIL_P(tmp)) too_short();
1480 tmp_len = RSTRING_LEN(tmp);
1482 if (tmp_len < need_len) too_short();
1484 str = rb_str_new(arg->buf+arg->offset, buflen);
1485 rb_str_cat(str, RSTRING_PTR(tmp), need_len);
1487 if (tmp_len > need_len) {
1488 buflen = tmp_len - need_len;
1489 memcpy(arg->buf, RSTRING_PTR(tmp)+need_len, buflen);
1490 arg->buflen = buflen;
1501#define r_bytes(arg) r_bytes0(r_long(arg), (arg))
1504r_bytes0(long len, struct load_arg *arg)
1508 if (len == 0) return rb_str_new(0, 0);
1509 if (RB_TYPE_P(arg->src, T_STRING)) {
1510 if (RSTRING_LEN(arg->src) - arg->offset >= len) {
1511 str = rb_str_new(RSTRING_PTR(arg->src)+arg->offset, len);
1519 if (arg->readable > 0 || arg->buflen > 0) {
1520 str = r_bytes1_buffered(len, arg);
1523 str = r_bytes1(len, arg);
1530name_equal(const char *name, size_t nlen, const char *p, long l)
1532 if ((size_t)l != nlen || *p != *name) return 0;
1533 return nlen == 1 || memcmp(p+1, name+1, nlen-1) == 0;
1537sym2encidx(VALUE sym, VALUE val)
1539 RBIMPL_ATTR_NONSTRING() static const char name_encoding[8] = "encoding";
1542 if (rb_enc_get_index(sym) != ENCINDEX_US_ASCII) return -1;
1543 RSTRING_GETMEM(sym, p, l);
1544 if (l <= 0) return -1;
1545 if (name_equal(name_encoding, sizeof(name_encoding), p, l)) {
1546 int idx = rb_enc_find_index(StringValueCStr(val));
1549 if (name_equal(name_s_encoding_short, rb_strlen_lit(name_s_encoding_short), p, l)) {
1550 if (val == Qfalse) return rb_usascii_encindex();
1551 else if (val == Qtrue) return rb_utf8_encindex();
1558symname_equal(VALUE sym, const char *name, size_t nlen)
1562 if (rb_enc_get_index(sym) != ENCINDEX_US_ASCII) return 0;
1563 RSTRING_GETMEM(sym, p, l);
1564 return name_equal(name, nlen, p, l);
1567#define BUILD_ASSERT_POSITIVE(n) \
1568 /* make 0 negative to workaround the "zero size array" GCC extension, */ \
1569 ((sizeof(char [2*(ssize_t)(n)-1])+1)/2) /* assuming no overflow */
1570#define symname_equal_lit(sym, sym_name) \
1571 symname_equal(sym, sym_name, BUILD_ASSERT_POSITIVE(rb_strlen_lit(sym_name)))
1574r_symlink(struct load_arg *arg)
1577 long num = r_long(arg);
1579 if (!st_lookup(arg->symbols, num, &sym)) {
1580 rb_raise(rb_eArgError, "bad symbol");
1586r_symreal(struct load_arg *arg, int ivar)
1588 VALUE s = r_bytes(arg);
1591 st_index_t n = arg->symbols->num_entries;
1593 if (rb_enc_str_asciionly_p(s)) rb_enc_associate_index(s, ENCINDEX_US_ASCII);
1594 st_insert(arg->symbols, (st_data_t)n, (st_data_t)s);
1596 long num = r_long(arg);
1598 sym = r_symbol(arg);
1599 idx = sym2encidx(sym, r_object(arg));
1603 rb_enc_associate_index(s, idx);
1604 if (is_broken_string(s)) {
1605 rb_raise(rb_eArgError, "invalid byte sequence in %s: %+"PRIsVALUE,
1606 rb_enc_name(rb_enc_from_index(idx)), s);
1614r_symbol(struct load_arg *arg)
1619 switch ((type = r_byte(arg))) {
1621 rb_raise(rb_eArgError, "dump format error for symbol(0x%x)", type);
1626 return r_symreal(arg, ivar);
1629 rb_raise(rb_eArgError, "dump format error (symlink with encoding)");
1631 return r_symlink(arg);
1636r_unique(struct load_arg *arg)
1638 return r_symbol(arg);
1642r_string(struct load_arg *arg)
1644 return r_bytes(arg);
1648r_entry0(VALUE v, st_index_t num, struct load_arg *arg)
1650 st_data_t real_obj = (st_data_t)v;
1651 if (arg->compat_tbl) {
1652 /* real_obj is kept if not found */
1653 st_lookup(arg->compat_tbl, v, &real_obj);
1655 st_insert(arg->data, num, real_obj);
1656 st_insert(arg->partial_objects, (st_data_t)real_obj, Qtrue);
1661r_fixup_compat(VALUE v, struct load_arg *arg)
1664 st_data_t key = (st_data_t)v;
1665 if (arg->compat_tbl && st_delete(arg->compat_tbl, &key, &data)) {
1666 VALUE real_obj = (VALUE)data;
1667 rb_alloc_func_t allocator = rb_get_alloc_func(CLASS_OF(real_obj));
1668 if (st_lookup(compat_allocator_tbl, (st_data_t)allocator, &data)) {
1669 marshal_compat_t *compat = (marshal_compat_t*)data;
1670 compat->loader(real_obj, v);
1678r_post_proc(VALUE v, struct load_arg *arg)
1681 v = load_funcall(arg, arg->proc, s_call, 1, &v);
1687r_leave(VALUE v, struct load_arg *arg, bool partial)
1689 v = r_fixup_compat(v, arg);
1692 st_data_t key = (st_data_t)v;
1693 st_delete(arg->partial_objects, &key, &data);
1695 if (RB_TYPE_P(v, T_MODULE) || RB_TYPE_P(v, T_CLASS)) {
1698 else if (RB_TYPE_P(v, T_STRING)) {
1699 v = rb_str_to_interned_str(v);
1705 v = r_post_proc(v, arg);
1711copy_ivar_i(ID vid, VALUE value, st_data_t arg)
1713 VALUE obj = (VALUE)arg;
1715 if (!rb_ivar_defined(obj, vid))
1716 rb_ivar_set(obj, vid, value);
1721r_copy_ivar(VALUE v, VALUE data)
1723 rb_ivar_foreach(data, copy_ivar_i, (st_data_t)v);
1727#define override_ivar_error(type, str) \
1728 rb_raise(rb_eTypeError, \
1729 "can't override instance variable of "type" '%"PRIsVALUE"'", \
1733r_ivar_encoding(VALUE obj, struct load_arg *arg, VALUE sym, VALUE val)
1735 int idx = sym2encidx(sym, val);
1737 if (rb_enc_capable(obj)) {
1738 rb_enc_associate_index(obj, idx);
1741 rb_raise(rb_eArgError, "%"PRIsVALUE" is not enc_capable", obj);
1749r_encname(VALUE obj, struct load_arg *arg)
1751 long len = r_long(arg);
1753 VALUE sym = r_symbol(arg);
1754 VALUE val = r_object(arg);
1755 len -= r_ivar_encoding(obj, arg, sym, val);
1761r_ivar(VALUE obj, int *has_encoding, struct load_arg *arg)
1767 if (RB_TYPE_P(obj, T_MODULE)) {
1768 override_ivar_error("module", rb_mod_name(obj));
1770 else if (RB_TYPE_P(obj, T_CLASS)) {
1771 override_ivar_error("class", rb_class_name(obj));
1774 VALUE sym = r_symbol(arg);
1775 VALUE val = r_object(arg);
1776 if (r_ivar_encoding(obj, arg, sym, val)) {
1777 if (has_encoding) *has_encoding = TRUE;
1779 else if (symname_equal_lit(sym, name_s_ruby2_keywords_flag)) {
1780 if (RB_TYPE_P(obj, T_HASH)) {
1781 rb_hash_ruby2_keywords(obj);
1784 rb_raise(rb_eArgError, "ruby2_keywords flag is given but %"PRIsVALUE" is not a Hash", obj);
1788 rb_ivar_set(obj, rb_intern_str(sym), val);
1790 } while (--len > 0);
1795path2class(VALUE path)
1797 VALUE v = rb_path_to_class(path);
1799 if (!RB_TYPE_P(v, T_CLASS)) {
1800 rb_raise(rb_eArgError, "%"PRIsVALUE" does not refer to class", path);
1805#define path2module(path) must_be_module(rb_path_to_class(path), path)
1808must_be_module(VALUE v, VALUE path)
1810 if (!RB_TYPE_P(v, T_MODULE)) {
1811 rb_raise(rb_eArgError, "%"PRIsVALUE" does not refer to module", path);
1817obj_alloc_by_klass(VALUE klass, struct load_arg *arg, VALUE *oldclass)
1820 rb_alloc_func_t allocator;
1822 allocator = rb_get_alloc_func(klass);
1823 if (st_lookup(compat_allocator_tbl, (st_data_t)allocator, &data)) {
1824 marshal_compat_t *compat = (marshal_compat_t*)data;
1825 VALUE real_obj = rb_obj_alloc(klass);
1826 VALUE obj = rb_obj_alloc(compat->oldclass);
1827 if (oldclass) *oldclass = compat->oldclass;
1829 if (!arg->compat_tbl) {
1830 arg->compat_tbl = rb_init_identtable();
1832 st_insert(arg->compat_tbl, (st_data_t)obj, (st_data_t)real_obj);
1836 return rb_obj_alloc(klass);
1840obj_alloc_by_path(VALUE path, struct load_arg *arg)
1842 return obj_alloc_by_klass(path2class(path), arg, 0);
1846append_extmod(VALUE obj, VALUE extmod)
1848 long i = RARRAY_LEN(extmod);
1850 VALUE m = RARRAY_AREF(extmod, --i);
1851 rb_extend_object(obj, m);
1856#define prohibit_ivar(type, str) do { \
1857 if (!ivp || !*ivp) break; \
1858 override_ivar_error(type, str); \
1861static VALUE r_object_for(struct load_arg *arg, bool partial, int *ivp, VALUE extmod, int type);
1864r_object0(struct load_arg *arg, bool partial, int *ivp, VALUE extmod)
1866 int type = r_byte(arg);
1867 return r_object_for(arg, partial, ivp, extmod, type);
1871r_object_for(struct load_arg *arg, bool partial, int *ivp, VALUE extmod, int type)
1873 VALUE (*hash_new_with_size)(st_index_t) = rb_hash_new_with_size;
1881 if (!st_lookup(arg->data, (st_data_t)id, &link)) {
1882 rb_raise(rb_eArgError, "dump format error (unlinked)");
1885 if (!st_lookup(arg->partial_objects, (st_data_t)v, &link)) {
1886 if (arg->freeze && RB_TYPE_P(v, T_STRING)) {
1887 v = rb_str_to_interned_str(v);
1889 v = r_post_proc(v, arg);
1896 v = r_object0(arg, true, &ivar, extmod);
1897 if (ivar) r_ivar(v, NULL, arg);
1898 v = r_leave(v, arg, partial);
1904 VALUE path = r_unique(arg);
1905 VALUE m = rb_path_to_class(path);
1906 if (NIL_P(extmod)) extmod = rb_ary_hidden_new(0);
1908 if (RB_TYPE_P(m, T_CLASS)) { /* prepended */
1911 v = r_object0(arg, true, 0, Qnil);
1913 if (c != m || FL_TEST(c, FL_SINGLETON)) {
1914 rb_raise(rb_eArgError,
1915 "prepended class %"PRIsVALUE" differs from class %"PRIsVALUE,
1916 path, rb_class_name(c));
1918 c = rb_singleton_class(v);
1919 while (RARRAY_LEN(extmod) > 0) {
1920 m = rb_ary_pop(extmod);
1921 rb_prepend_module(c, m);
1925 must_be_module(m, path);
1926 rb_ary_push(extmod, m);
1928 v = r_object0(arg, true, 0, extmod);
1929 while (RARRAY_LEN(extmod) > 0) {
1930 m = rb_ary_pop(extmod);
1931 rb_extend_object(v, m);
1934 v = r_leave(v, arg, partial);
1940 VALUE c = path2class(r_unique(arg));
1942 if (FL_TEST(c, FL_SINGLETON)) {
1943 rb_raise(rb_eTypeError, "singleton can't be loaded");
1946 if ((c == rb_cHash) &&
1947 /* Hack for compare_by_identify */
1948 (type == TYPE_HASH || type == TYPE_HASH_DEF)) {
1949 hash_new_with_size = rb_ident_hash_new_with_size;
1952 v = r_object_for(arg, partial, 0, extmod, type);
1953 if (RB_SPECIAL_CONST_P(v) || RB_TYPE_P(v, T_OBJECT) || RB_TYPE_P(v, T_CLASS)) {
1956 if (RB_TYPE_P(v, T_MODULE) || !RTEST(rb_class_inherited_p(c, RBASIC(v)->klass))) {
1957 VALUE tmp = rb_obj_alloc(c);
1959 if (TYPE(v) != TYPE(tmp)) goto format_error;
1961 RBASIC_SET_CLASS(v, c);
1966 rb_raise(rb_eArgError, "dump format error (user class)");
1970 v = r_leave(v, arg, false);
1975 v = r_leave(v, arg, false);
1980 v = r_leave(v, arg, false);
1985 long i = r_long(arg);
1988 v = r_leave(v, arg, false);
1994 VALUE str = r_bytes(arg);
1995 const char *ptr = RSTRING_PTR(str);
1997 if (strcmp(ptr, "nan") == 0) {
2000 else if (strcmp(ptr, "inf") == 0) {
2003 else if (strcmp(ptr, "-inf") == 0) {
2008 d = strtod(ptr, &e);
2009 d = load_mantissa(d, e, RSTRING_LEN(str) - (e - ptr));
2012 v = r_entry(v, arg);
2013 v = r_leave(v, arg, false);
2024 if (sign != '+' && sign != '-') {
2025 rb_raise(rb_eArgError, "invalid Bignum sign");
2027 len = r_keep_readable(arg, r_long(arg), 2);
2029 if (SIZEOF_VALUE >= 8 && len <= 4) {
2030 // Representable within uintptr, likely FIXNUM
2032 for (int i = 0; i < len; i++) {
2033 num |= (VALUE)r_byte(arg) << (i * 16);
2034 num |= (VALUE)r_byte(arg) << (i * 16 + 8);
2036#if SIZEOF_VALUE == SIZEOF_LONG
2042 v = rb_int_uminus(v);
2046 data = r_bytes0(len * 2, arg);
2047 v = rb_integer_unpack(RSTRING_PTR(data), len, 2, 0,
2048 INTEGER_PACK_LITTLE_ENDIAN | (sign == '-' ? INTEGER_PACK_NEGATIVE : 0));
2049 rb_str_resize(data, 0L);
2051 v = r_entry(v, arg);
2052 v = r_leave(v, arg, false);
2057 v = r_entry(r_string(arg), arg);
2058 v = r_leave(v, arg, partial);
2063 VALUE str = r_bytes(arg);
2064 int options = r_byte(arg);
2065 int has_encoding = FALSE;
2066 st_index_t idx = r_prepare(arg);
2069 r_ivar(str, &has_encoding, arg);
2072 if (!has_encoding) {
2073 /* 1.8 compatibility; remove escapes undefined in 1.8 */
2074 char *ptr = RSTRING_PTR(str), *dst = ptr, *src = ptr;
2075 long len = RSTRING_LEN(str);
2077 for (; len-- > 0; *dst++ = *src++) {
2079 case '\\': bs++; break;
2080 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
2081 case 'm': case 'o': case 'p': case 'q': case 'u': case 'y':
2082 case 'E': case 'F': case 'H': case 'I': case 'J': case 'K':
2083 case 'L': case 'N': case 'O': case 'P': case 'Q': case 'R':
2084 case 'S': case 'T': case 'U': case 'V': case 'X': case 'Y':
2087 default: bs = 0; break;
2090 rb_str_set_len(str, dst - ptr);
2092 VALUE regexp = rb_reg_new_str(str, options);
2093 r_copy_ivar(regexp, str);
2095 v = r_entry0(regexp, idx, arg);
2096 v = r_leave(v, arg, partial);
2102 long len = r_keep_readable(arg, r_long(arg), 1);
2104 v = rb_ary_new2(len);
2105 v = r_entry(v, arg);
2106 arg->readable += len - 1;
2108 rb_ary_push(v, r_object(arg));
2111 v = r_leave(v, arg, partial);
2120 long len = r_keep_readable(arg, r_long(arg), 2);
2122 v = hash_new_with_size(len);
2123 v = r_entry(v, arg);
2124 arg->readable += (len - 1) * 2;
2126 VALUE key = r_object(arg);
2127 VALUE value = r_object(arg);
2128 rb_hash_aset(v, key, value);
2132 if (type == TYPE_HASH_DEF) {
2133 RHASH_SET_IFNONE(v, r_object(arg));
2135 v = r_leave(v, arg, partial);
2144 st_index_t idx = r_prepare(arg);
2145 VALUE klass = path2class(r_unique(arg));
2146 long len = r_keep_readable(arg, r_long(arg), 2);
2148 v = rb_obj_alloc(klass);
2149 if (!RB_TYPE_P(v, T_STRUCT)) {
2150 rb_raise(rb_eTypeError, "class %"PRIsVALUE" not a struct", rb_class_name(klass));
2152 mem = rb_struct_s_members(klass);
2153 if (RARRAY_LEN(mem) != len) {
2154 rb_raise(rb_eTypeError, "struct %"PRIsVALUE" not compatible (struct size differs)",
2155 rb_class_name(klass));
2158 arg->readable += (len - 1) * 2;
2159 v = r_entry0(v, idx, arg);
2160 values = rb_ary_new2(len);
2162 VALUE keywords = Qfalse;
2163 if (RTEST(rb_struct_s_keyword_init(klass))) {
2164 keywords = rb_hash_new();
2165 rb_ary_push(values, keywords);
2168 for (i=0; i<len; i++) {
2169 VALUE n = rb_sym2str(RARRAY_AREF(mem, i));
2170 slot = r_symbol(arg);
2172 if (!rb_str_equal(n, slot)) {
2173 rb_raise(rb_eTypeError, "struct %"PRIsVALUE" not compatible (:%"PRIsVALUE" for :%"PRIsVALUE")",
2174 rb_class_name(klass),
2178 rb_hash_aset(keywords, RARRAY_AREF(mem, i), r_object(arg));
2181 rb_ary_push(values, r_object(arg));
2186 rb_struct_initialize(v, values);
2187 v = r_leave(v, arg, partial);
2194 VALUE name = r_unique(arg);
2195 VALUE klass = path2class(name);
2199 if (!rb_obj_respond_to(klass, s_load, TRUE)) {
2200 rb_raise(rb_eTypeError, "class %"PRIsVALUE" needs to have method '_load'",
2203 data = r_string(arg);
2205 r_ivar(data, NULL, arg);
2208 v = load_funcall(arg, klass, s_load, 1, &data);
2209 v = r_entry(v, arg);
2210 if (st_lookup(compat_allocator_tbl, (st_data_t)rb_get_alloc_func(klass), &d)) {
2211 marshal_compat_t *compat = (marshal_compat_t*)d;
2212 v = compat->loader(klass, v);
2218 v = r_post_proc(v, arg);
2223 case TYPE_USRMARSHAL:
2225 VALUE name = r_unique(arg);
2226 VALUE klass = path2class(name);
2230 v = obj_alloc_by_klass(klass, arg, &oldclass);
2231 if (!NIL_P(extmod)) {
2232 /* for the case marshal_load is overridden */
2233 append_extmod(v, extmod);
2235 if (!rb_obj_respond_to(v, s_mload, TRUE)) {
2236 rb_raise(rb_eTypeError, "instance of %"PRIsVALUE" needs to have method 'marshal_load'",
2239 v = r_entry(v, arg);
2240 data = r_object(arg);
2241 load_funcall(arg, v, s_mload, 1, &data);
2242 v = r_fixup_compat(v, arg);
2243 v = r_copy_ivar(v, data);
2247 v = r_post_proc(v, arg);
2248 if (!NIL_P(extmod)) {
2249 if (oldclass) append_extmod(v, extmod);
2250 rb_ary_clear(extmod);
2257 st_index_t idx = r_prepare(arg);
2258 v = obj_alloc_by_path(r_unique(arg), arg);
2259 if (!RB_TYPE_P(v, T_OBJECT)) {
2260 rb_raise(rb_eArgError, "dump format error");
2262 v = r_entry0(v, idx, arg);
2263 r_ivar(v, NULL, arg);
2264 v = r_leave(v, arg, partial);
2270 VALUE name = r_unique(arg);
2271 VALUE klass = path2class(name);
2275 v = obj_alloc_by_klass(klass, arg, &oldclass);
2276 if (!RB_TYPE_P(v, T_DATA)) {
2277 rb_raise(rb_eArgError, "dump format error");
2279 v = r_entry(v, arg);
2280 if (!rb_obj_respond_to(v, s_load_data, TRUE)) {
2281 rb_raise(rb_eTypeError,
2282 "class %"PRIsVALUE" needs to have instance method '_load_data'",
2285 r = r_object0(arg, partial, 0, extmod);
2286 load_funcall(arg, v, s_load_data, 1, &r);
2287 v = r_leave(v, arg, partial);
2291 case TYPE_MODULE_OLD:
2293 VALUE str = r_bytes(arg);
2295 v = rb_path_to_class(str);
2296 prohibit_ivar("class/module", str);
2297 v = r_entry(v, arg);
2298 v = r_leave(v, arg, partial);
2304 VALUE str = r_bytes(arg);
2306 if (ivp && *ivp > 0) *ivp = r_encname(str, arg) > 0;
2307 v = path2class(str);
2308 prohibit_ivar("class", str);
2309 v = r_entry(v, arg);
2310 v = r_leave(v, arg, partial);
2316 VALUE str = r_bytes(arg);
2318 if (ivp && *ivp > 0) *ivp = r_encname(str, arg) > 0;
2319 v = path2module(str);
2320 prohibit_ivar("module", str);
2321 v = r_entry(v, arg);
2322 v = r_leave(v, arg, partial);
2328 v = r_symreal(arg, *ivp);
2332 v = r_symreal(arg, 0);
2334 v = rb_str_intern(v);
2335 v = r_leave(v, arg, partial);
2339 v = rb_str_intern(r_symlink(arg));
2343 rb_raise(rb_eArgError, "dump format error(0x%x)", type);
2348 rb_raise(rb_eArgError, "dump format error (bad link)");
2355r_object(struct load_arg *arg)
2357 return r_object0(arg, false, 0, Qnil);
2361clear_load_arg(struct load_arg *arg)
2369 if (!arg->symbols) return;
2370 st_free_table(arg->symbols);
2372 st_free_table(arg->data);
2374 st_free_table(arg->partial_objects);
2375 arg->partial_objects = 0;
2376 if (arg->compat_tbl) {
2377 st_free_table(arg->compat_tbl);
2378 arg->compat_tbl = 0;
2383rb_marshal_load_with_proc(VALUE port, VALUE proc, bool freeze)
2387 VALUE wrapper; /* used to avoid memory leak in case of exception */
2388 struct load_arg *arg;
2390 v = rb_check_string_type(port);
2394 else if (rb_respond_to(port, s_getbyte) && rb_respond_to(port, s_read)) {
2395 rb_check_funcall(port, s_binmode, 0, 0);
2400 wrapper = TypedData_Make_Struct(0, struct load_arg, &load_arg_data, arg);
2403 arg->symbols = st_init_numtable();
2404 arg->data = rb_init_identtable();
2405 arg->partial_objects = rb_init_identtable();
2406 arg->compat_tbl = 0;
2409 arg->freeze = freeze;
2412 arg->bufsize = BUFSIZ;
2413 arg->buf = xmalloc(BUFSIZ);
2420 major = r_byte(arg);
2421 minor = r_byte(arg);
2422 if (major != MARSHAL_MAJOR || minor > MARSHAL_MINOR) {
2423 clear_load_arg(arg);
2424 rb_raise(rb_eTypeError, "incompatible marshal file format (can't be read)\n\
2425\tformat version %d.%d required; %d.%d given",
2426 MARSHAL_MAJOR, MARSHAL_MINOR, major, minor);
2428 if (RTEST(ruby_verbose) && minor != MARSHAL_MINOR) {
2429 rb_warn("incompatible marshal file format (can be read)\n\
2430\tformat version %d.%d required; %d.%d given",
2431 MARSHAL_MAJOR, MARSHAL_MINOR, major, minor);
2434 if (!NIL_P(proc)) arg->proc = proc;
2436 clear_load_arg(arg);
2437 RB_GC_GUARD(wrapper);
2443marshal_load(rb_execution_context_t *ec, VALUE mod, VALUE source, VALUE proc, VALUE freeze)
2445 return rb_marshal_load_with_proc(source, proc, RTEST(freeze));
2448#include "marshal.rbinc"
2451 * The marshaling library converts collections of Ruby objects into a
2452 * byte stream, allowing them to be stored outside the currently
2453 * active script. This data may subsequently be read and the original
2454 * objects reconstituted.
2456 * Marshaled data has major and minor version numbers stored along
2457 * with the object information. In normal use, marshaling can only
2458 * load data written with the same major version number and an equal
2459 * or lower minor version number. If Ruby's ``verbose'' flag is set
2460 * (normally using -d, -v, -w, or --verbose) the major and minor
2461 * numbers must match exactly. Marshal versioning is independent of
2462 * Ruby's version numbers. You can extract the version by reading the
2463 * first two bytes of marshaled data.
2465 * str = Marshal.dump("thing")
2466 * RUBY_VERSION #=> "1.9.0"
2470 * Some objects cannot be dumped: if the objects to be dumped include
2471 * bindings, procedure or method objects, instances of class IO, or
2472 * singleton objects, a TypeError will be raised.
2474 * If your class has special serialization needs (for example, if you
2475 * want to serialize in some specific format), or if it contains
2476 * objects that would otherwise not be serializable, you can implement
2477 * your own serialization strategy.
2479 * There are two methods of doing this, your object can define either
2480 * marshal_dump and marshal_load or _dump and _load. marshal_dump will take
2481 * precedence over _dump if both are defined. marshal_dump may result in
2482 * smaller Marshal strings.
2484 * == Security considerations
2486 * By design, Marshal.load can deserialize almost any class loaded into the
2487 * Ruby process. In many cases this can lead to remote code execution if the
2488 * Marshal data is loaded from an untrusted source.
2490 * As a result, Marshal.load is not suitable as a general purpose serialization
2491 * format and you should never unmarshal user supplied input or other untrusted
2494 * If you need to deserialize untrusted data, use JSON or another serialization
2495 * format that is only able to load simple, 'primitive' types such as String,
2496 * Array, Hash, etc. Never allow user input to specify arbitrary types to
2499 * == marshal_dump and marshal_load
2501 * When dumping an object the method marshal_dump will be called.
2502 * marshal_dump must return a result containing the information necessary for
2503 * marshal_load to reconstitute the object. The result can be any object.
2505 * When loading an object dumped using marshal_dump the object is first
2506 * allocated then marshal_load is called with the result from marshal_dump.
2507 * marshal_load must recreate the object from the information in the result.
2512 * def initialize name, version, data
2514 * @version = version
2522 * def marshal_load array
2523 * @name, @version = array
2527 * == _dump and _load
2529 * Use _dump and _load when you need to allocate the object you're restoring
2532 * When dumping an object the instance method _dump is called with an Integer
2533 * which indicates the maximum depth of objects to dump (a value of -1 implies
2534 * that you should disable depth checking). _dump must return a String
2535 * containing the information necessary to reconstitute the object.
2537 * The class method _load should take a String and use it to return an object
2538 * of the same class.
2543 * def initialize name, version, data
2545 * @version = version
2550 * [@name, @version].join ':'
2553 * def self._load args
2554 * new(*args.split(':'))
2558 * Since Marshal.dump outputs a string you can have _dump return a Marshal
2559 * string which is Marshal.loaded in _load for complex objects.
2564 VALUE rb_mMarshal = rb_define_module("Marshal");
2565#define set_id(sym) sym = rb_intern_const(name_##sym)
2570 set_id(s_dump_data);
2571 set_id(s_load_data);
2578 set_id(s_encoding_short);
2579 set_id(s_ruby2_keywords_flag);
2581 rb_define_module_function(rb_mMarshal, "dump", marshal_dump, -1);
2584 rb_define_const(rb_mMarshal, "MAJOR_VERSION", INT2FIX(MARSHAL_MAJOR));
2586 rb_define_const(rb_mMarshal, "MINOR_VERSION", INT2FIX(MARSHAL_MINOR));
2590marshal_compat_table_mark_and_move_i(st_data_t key, st_data_t value, st_data_t _)
2592 marshal_compat_t *p = (marshal_compat_t *)value;
2593 rb_gc_mark_and_move(&p->newclass);
2594 rb_gc_mark_and_move(&p->oldclass);
2599marshal_compat_table_mark_and_move(void *tbl)
2602 st_foreach(tbl, marshal_compat_table_mark_and_move_i, 0);
2606marshal_compat_table_free_i(st_data_t key, st_data_t value, st_data_t _)
2608 xfree((marshal_compat_t *)value);
2613marshal_compat_table_free(void *data)
2615 st_foreach(data, marshal_compat_table_free_i, 0);
2616 st_free_table(data);
2620marshal_compat_table_memsize(const void *data)
2622 return st_memsize(data) + sizeof(marshal_compat_t) * st_table_size(data);
2625static const rb_data_type_t marshal_compat_type = {
2626 .wrap_struct_name = "marshal_compat_table",
2628 .dmark = marshal_compat_table_mark_and_move,
2629 .dfree = marshal_compat_table_free,
2630 .dsize = marshal_compat_table_memsize,
2631 .dcompact = marshal_compat_table_mark_and_move,
2633 .flags = RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_FREE_IMMEDIATELY,
2637compat_allocator_table(void)
2639 if (compat_allocator_tbl) return compat_allocator_tbl;
2640 compat_allocator_tbl = st_init_numtable();
2641 compat_allocator_tbl_wrapper =
2642 TypedData_Wrap_Struct(0, &marshal_compat_type, compat_allocator_tbl);
2643 rb_vm_register_global_object(compat_allocator_tbl_wrapper);
2644 return compat_allocator_tbl;
2648rb_marshal_dump(VALUE obj, VALUE port)
2650 return rb_marshal_dump_limited(obj, port, -1);
2654rb_marshal_load(VALUE port)
2656 return rb_marshal_load_with_proc(port, Qnil, false);
int len
Length of the buffer.
Defines RBIMPL_ATTR_NONSTRING.