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"
44#define BITSPERSHORT (2*CHAR_BIT)
45#define SHORTMASK ((1<<BITSPERSHORT)-1)
46#define SHORTDN(x) RSHIFT((x),BITSPERSHORT)
48#if SIZEOF_SHORT == SIZEOF_BDIGIT
49#define SHORTLEN(x) (x)
52shortlen(
size_t len, BDIGIT *ds)
62 return (len - 1)*SIZEOF_BDIGIT/2 + offset;
64#define SHORTLEN(x) shortlen((x),d)
67#define MARSHAL_MAJOR 4
68#define MARSHAL_MINOR 8
73#define TYPE_FIXNUM 'i'
75#define TYPE_EXTENDED 'e'
76#define TYPE_UCLASS 'C'
77#define TYPE_OBJECT 'o'
79#define TYPE_USERDEF 'u'
80#define TYPE_USRMARSHAL 'U'
82#define TYPE_BIGNUM 'l'
83#define TYPE_STRING '"'
84#define TYPE_REGEXP '/'
87#define TYPE_HASH_DEF '}'
88#define TYPE_STRUCT 'S'
89#define TYPE_MODULE_OLD 'M'
91#define TYPE_MODULE 'm'
93#define TYPE_SYMBOL ':'
94#define TYPE_SYMLINK ';'
99static ID s_dump, s_load, s_mdump, s_mload;
100static ID s_dump_data, s_load_data, s_alloc, s_call;
101static ID s_getbyte, s_read, s_write, s_binmode;
102static ID s_encoding_short, s_ruby2_keywords_flag;
104#define name_s_dump "_dump"
105#define name_s_load "_load"
106#define name_s_mdump "marshal_dump"
107#define name_s_mload "marshal_load"
108#define name_s_dump_data "_dump_data"
109#define name_s_load_data "_load_data"
110#define name_s_alloc "_alloc"
111#define name_s_call "call"
112#define name_s_getbyte "getbyte"
113#define name_s_read "read"
114#define name_s_write "write"
115#define name_s_binmode "binmode"
116#define name_s_encoding_short "E"
117#define name_s_ruby2_keywords_flag "K"
122 VALUE (*dumper)(VALUE);
123 VALUE (*loader)(VALUE, VALUE);
126static st_table *compat_allocator_tbl;
127static VALUE compat_allocator_tbl_wrapper;
128static VALUE rb_marshal_dump_limited(VALUE obj, VALUE port, int limit);
129static VALUE rb_marshal_load_with_proc(VALUE port, VALUE proc, bool freeze);
132mark_marshal_compat_i(st_data_t key, st_data_t value, st_data_t _)
134 marshal_compat_t *p = (marshal_compat_t *)value;
135 rb_gc_mark(p->newclass);
136 rb_gc_mark(p->oldclass);
141mark_marshal_compat_t(void *tbl)
144 st_foreach(tbl, mark_marshal_compat_i, 0);
147static st_table *compat_allocator_table(void);
150rb_marshal_define_compat(VALUE newclass, VALUE oldclass, VALUE (*dumper)(VALUE), VALUE (*loader)(VALUE, VALUE))
152 marshal_compat_t *compat;
153 rb_alloc_func_t allocator = rb_get_alloc_func(newclass);
156 rb_raise(rb_eTypeError, "no allocator");
159 compat = ALLOC(marshal_compat_t);
160 compat->newclass = Qnil;
161 compat->oldclass = Qnil;
162 compat->newclass = newclass;
163 compat->oldclass = oldclass;
164 compat->dumper = dumper;
165 compat->loader = loader;
167 st_insert(compat_allocator_table(), (st_data_t)allocator, (st_data_t)compat);
174 st_table *compat_tbl;
176 unsigned long num_entries;
179struct dump_call_arg {
181 struct dump_arg *arg;
186check_dump_arg(VALUE ret, struct dump_arg *arg, const char *name)
189 rb_raise(rb_eRuntimeError, "Marshal.dump reentered at %s",
196check_userdump_arg(VALUE obj, ID sym, int argc, const VALUE *argv,
197 struct dump_arg *arg, const char *name)
199 VALUE ret = rb_funcallv(obj, sym, argc, argv);
200 VALUE klass = CLASS_OF(obj);
201 if (CLASS_OF(ret) == klass) {
202 rb_raise(rb_eRuntimeError, "%"PRIsVALUE"#%s returned same class instance",
205 return check_dump_arg(ret, arg, name);
208#define dump_funcall(arg, obj, sym, argc, argv) \
209 check_userdump_arg(obj, sym, argc, argv, arg, name_##sym)
210#define dump_check_funcall(arg, obj, sym, argc, argv) \
211 check_dump_arg(rb_check_funcall(obj, sym, argc, argv), arg, name_##sym)
213static void clear_dump_arg(struct dump_arg *arg);
216mark_dump_arg(void *ptr)
218 struct dump_arg *p = ptr;
221 rb_mark_set(p->symbols);
222 rb_mark_set(p->data);
223 rb_mark_hash(p->compat_tbl);
228free_dump_arg(void *ptr)
235memsize_dump_arg(const void *ptr)
237 return sizeof(struct dump_arg);
240static const rb_data_type_t dump_arg_data = {
242 {mark_dump_arg, free_dump_arg, memsize_dump_arg,},
243 0, 0, RUBY_TYPED_FREE_IMMEDIATELY
247must_not_be_anonymous(const char *type, VALUE path)
249 char *n = RSTRING_PTR(path);
251 if (!rb_enc_asciicompat(rb_enc_get(path))) {
253 rb_raise(rb_eTypeError, "can't dump non-ascii %s name % "PRIsVALUE,
257 rb_raise(rb_eTypeError, "can't dump anonymous %s % "PRIsVALUE,
264class2path(VALUE klass)
266 VALUE path = rb_class_path(klass);
268 must_not_be_anonymous((RB_TYPE_P(klass, T_CLASS) ? "class" : "module"), path);
269 if (rb_path_to_class(path) != rb_class_real(klass)) {
270 rb_raise(rb_eTypeError, "% "PRIsVALUE" can't be referred to", path);
275int ruby_marshal_write_long(long x, char *buf);
276static void w_long(long, struct dump_arg*);
277static int w_encoding(VALUE encname, struct dump_call_arg *arg);
278static VALUE encoding_name(VALUE obj, struct dump_arg *arg);
281w_nbyte(const char *s, long n, struct dump_arg *arg)
283 VALUE buf = arg->str;
284 rb_str_buf_cat(buf, s, n);
285 if (arg->dest && RSTRING_LEN(buf) >= BUFSIZ) {
286 rb_io_write(arg->dest, buf);
287 rb_str_resize(buf, 0);
292w_byte(char c, struct dump_arg *arg)
298w_bytes(const char *s, long n, struct dump_arg *arg)
304#define w_cstr(s, arg) w_bytes((s), strlen(s), (arg))
307w_short(int x, struct dump_arg *arg)
309 w_byte((char)((x >> 0) & 0xff), arg);
310 w_byte((char)((x >> 8) & 0xff), arg);
314w_long(long x, struct dump_arg *arg)
316 char buf[sizeof(long)+1];
317 int i = ruby_marshal_write_long(x, buf);
319 rb_raise(rb_eTypeError, "long too big to dump");
321 w_nbyte(buf, i, arg);
325ruby_marshal_write_long(long x, char *buf)
330 if (!(RSHIFT(x, 31) == 0 || RSHIFT(x, 31) == -1)) {
331 /* big long does not fit in 4 bytes */
340 if (0 < x && x < 123) {
341 buf[0] = (char)(x + 5);
344 if (-124 < x && x < 0) {
345 buf[0] = (char)((x - 5)&0xff);
348 for (i=1;i<(int)sizeof(long)+1;i++) {
349 buf[i] = (char)(x & 0xff);
364#define DECIMAL_MANT (53-16) /* from IEEE754 double precision */
368#elif DBL_MANT_DIG > 24
370#elif DBL_MANT_DIG > 16
377load_mantissa(double d, const char *buf, long len)
380 if (--len > 0 && !*buf++) { /* binary mantissa mark */
381 int e, s = d < 0, dig = 0;
384 modf(ldexp(frexp(fabs(d), &e), DECIMAL_MANT), &d);
388 default: m = *buf++ & 0xff; /* fall through */
390 case 3: m = (m << 8) | (*buf++ & 0xff); /* fall through */
393 case 2: m = (m << 8) | (*buf++ & 0xff); /* fall through */
396 case 1: m = (m << 8) | (*buf++ & 0xff);
399 dig -= len < MANT_BITS / 8 ? 8 * (unsigned)len : MANT_BITS;
400 d += ldexp((double)m, dig);
401 } while ((len -= MANT_BITS / 8) > 0);
402 d = ldexp(d, e - DECIMAL_MANT);
408#define load_mantissa(d, buf, len) (d)
412#define FLOAT_DIG (DBL_DIG+2)
418w_float(double d, struct dump_arg *arg)
420 char buf[FLOAT_DIG + (DECIMAL_MANT + 7) / 8 + 10];
423 if (d < 0) w_cstr("-inf", arg);
424 else w_cstr("inf", arg);
430 if (signbit(d)) w_cstr("-0", arg);
431 else w_cstr("0", arg);
434 int decpt, sign, digs, len = 0;
435 char *e, *p = ruby_dtoa(d, 0, 0, &decpt, &sign, &e);
436 if (sign) buf[len++] = '-';
438 if (decpt < -3 || decpt > digs) {
440 if (--digs > 0) buf[len++] = '.';
441 memcpy(buf + len, p + 1, digs);
443 len += snprintf(buf + len, sizeof(buf) - len, "e%d", decpt - 1);
445 else if (decpt > 0) {
446 memcpy(buf + len, p, decpt);
448 if ((digs -= decpt) > 0) {
450 memcpy(buf + len, p + decpt, digs);
458 memset(buf + len, '0', -decpt);
461 memcpy(buf + len, p, digs);
465 w_bytes(buf, len, arg);
470w_symbol(VALUE sym, struct dump_arg *arg)
475 if (st_lookup(arg->symbols, sym, &num)) {
476 w_byte(TYPE_SYMLINK, arg);
477 w_long((long)num, arg);
480 const VALUE orig_sym = sym;
481 sym = rb_sym2str(sym);
483 rb_raise(rb_eTypeError, "can't dump anonymous ID %"PRIdVALUE, sym);
485 encname = encoding_name(sym, arg);
486 if (NIL_P(encname) ||
487 is_ascii_string(sym)) {
491 w_byte(TYPE_IVAR, arg);
493 w_byte(TYPE_SYMBOL, arg);
494 w_bytes(RSTRING_PTR(sym), RSTRING_LEN(sym), arg);
495 st_add_direct(arg->symbols, orig_sym, arg->symbols->num_entries);
496 if (!NIL_P(encname)) {
497 struct dump_call_arg c_arg;
501 w_encoding(encname, &c_arg);
507w_unique(VALUE s, struct dump_arg *arg)
509 must_not_be_anonymous("class", s);
510 w_symbol(rb_str_intern(s), arg);
513static void w_object(VALUE,struct dump_arg*,int);
516hash_each(VALUE key, VALUE value, VALUE v)
518 struct dump_call_arg *arg = (void *)v;
519 w_object(key, arg->arg, arg->limit);
520 w_object(value, arg->arg, arg->limit);
524#define SINGLETON_DUMP_UNABLE_P(klass) \
525 (rb_id_table_size(RCLASS_M_TBL(klass)) > 0 || \
526 rb_ivar_count(klass) > 1)
529w_extended(VALUE klass, struct dump_arg *arg, int check)
531 if (check && FL_TEST(klass, FL_SINGLETON)) {
532 VALUE origin = RCLASS_ORIGIN(klass);
533 if (SINGLETON_DUMP_UNABLE_P(klass) ||
534 (origin != klass && SINGLETON_DUMP_UNABLE_P(origin))) {
535 rb_raise(rb_eTypeError, "singleton can't be dumped");
537 klass = RCLASS_SUPER(klass);
539 while (BUILTIN_TYPE(klass) == T_ICLASS) {
540 if (!FL_TEST(klass, RICLASS_IS_ORIGIN) ||
541 BUILTIN_TYPE(RBASIC(klass)->klass) != T_MODULE) {
542 VALUE path = rb_class_name(RBASIC(klass)->klass);
543 w_byte(TYPE_EXTENDED, arg);
546 klass = RCLASS_SUPER(klass);
551w_class(char type, VALUE obj, struct dump_arg *arg, int check)
557 if (arg->compat_tbl &&
558 st_lookup(arg->compat_tbl, (st_data_t)obj, &real_obj)) {
559 obj = (VALUE)real_obj;
561 klass = CLASS_OF(obj);
562 w_extended(klass, arg, check);
564 path = class2path(rb_class_real(klass));
569w_uclass(VALUE obj, VALUE super, struct dump_arg *arg)
571 VALUE klass = CLASS_OF(obj);
573 w_extended(klass, arg, TRUE);
574 klass = rb_class_real(klass);
575 if (klass != super) {
576 w_byte(TYPE_UCLASS, arg);
577 w_unique(class2path(klass), arg);
582rb_hash_ruby2_keywords_p(VALUE obj)
584 return (RHASH(obj)->basic.flags & RHASH_PASS_AS_KEYWORDS) != 0;
588rb_hash_ruby2_keywords(VALUE obj)
590 RHASH(obj)->basic.flags |= RHASH_PASS_AS_KEYWORDS;
594to_be_skipped_id(const ID id)
596 if (id == s_encoding_short) return true;
597 if (id == s_ruby2_keywords_flag) return true;
598 if (id == rb_id_encoding()) return true;
599 return !rb_id2str(id);
603 struct dump_call_arg *dump;
608w_obj_each(st_data_t key, st_data_t val, st_data_t a)
611 VALUE value = (VALUE)val;
612 struct w_ivar_arg *ivarg = (struct w_ivar_arg *)a;
613 struct dump_call_arg *arg = ivarg->dump;
615 if (to_be_skipped_id(id)) {
616 if (id == s_encoding_short) {
617 rb_warn("instance variable `"name_s_encoding_short"' on class %"PRIsVALUE" is not dumped",
620 if (id == s_ruby2_keywords_flag) {
621 rb_warn("instance variable `"name_s_ruby2_keywords_flag"' on class %"PRIsVALUE" is not dumped",
627 w_symbol(ID2SYM(id), arg->arg);
628 w_object(value, arg->arg, arg->limit);
633obj_count_ivars(st_data_t key, st_data_t val, st_data_t a)
636 if (!to_be_skipped_id(id) && UNLIKELY(!++*(st_index_t *)a)) {
637 rb_raise(rb_eRuntimeError, "too many instance variables");
643encoding_name(VALUE obj, struct dump_arg *arg)
645 if (rb_enc_capable(obj)) {
646 int encidx = rb_enc_get_index(obj);
647 rb_encoding *enc = 0;
650 if (encidx <= 0 || !(enc = rb_enc_from_index(encidx))) {
654 /* special treatment for US-ASCII and UTF-8 */
655 if (encidx == rb_usascii_encindex()) {
658 else if (encidx == rb_utf8_encindex()) {
663 !st_lookup(arg->encodings, (st_data_t)rb_enc_name(enc), &name) :
664 (arg->encodings = st_init_strcasetable(), 1)) {
665 name = (st_data_t)rb_str_new_cstr(rb_enc_name(enc));
666 st_insert(arg->encodings, (st_data_t)rb_enc_name(enc), name);
676w_encoding(VALUE encname, struct dump_call_arg *arg)
678 int limit = arg->limit;
679 if (limit >= 0) ++limit;
683 w_symbol(ID2SYM(s_encoding_short), arg->arg);
684 w_object(encname, arg->arg, limit);
689 w_symbol(ID2SYM(rb_id_encoding()), arg->arg);
690 w_object(encname, arg->arg, limit);
695has_ivars(VALUE obj, VALUE encname, VALUE *ivobj)
697 st_index_t num = !NIL_P(encname);
699 if (SPECIAL_CONST_P(obj)) goto generic;
700 switch (BUILTIN_TYPE(obj)) {
704 break; /* counted elsewhere */
706 if (rb_hash_ruby2_keywords_p(obj)) ++num;
710 rb_ivar_foreach(obj, obj_count_ivars, (st_data_t)&num);
711 if (num) *ivobj = obj;
718w_ivar_each(VALUE obj, st_index_t num, struct dump_call_arg *arg)
720 shape_id_t shape_id = rb_shape_get_shape_id(arg->obj);
721 struct w_ivar_arg ivarg = {arg, num};
723 rb_ivar_foreach(obj, w_obj_each, (st_data_t)&ivarg);
725 if (shape_id != rb_shape_get_shape_id(arg->obj)) {
726 rb_shape_t * expected_shape = rb_shape_get_shape_by_id(shape_id);
727 rb_shape_t * actual_shape = rb_shape_get_shape(arg->obj);
729 // If the shape tree got _shorter_ then we probably removed an IV
730 // If the shape tree got longer, then we probably added an IV.
731 // The exception message might not be accurate when someone adds and
732 // removes the same number of IVs, but they will still get an exception
733 if (rb_shape_depth(expected_shape) > rb_shape_depth(actual_shape)) {
734 rb_raise(rb_eRuntimeError, "instance variable removed from %"PRIsVALUE" instance",
738 rb_raise(rb_eRuntimeError, "instance variable added to %"PRIsVALUE" instance",
745w_ivar(st_index_t num, VALUE ivobj, VALUE encname, struct dump_call_arg *arg)
747 w_long(num, arg->arg);
748 num -= w_encoding(encname, arg);
749 if (RB_TYPE_P(ivobj, T_HASH) && rb_hash_ruby2_keywords_p(ivobj)) {
750 int limit = arg->limit;
751 if (limit >= 0) ++limit;
752 w_symbol(ID2SYM(s_ruby2_keywords_flag), arg->arg);
753 w_object(Qtrue, arg->arg, limit);
756 if (!UNDEF_P(ivobj) && num) {
757 w_ivar_each(ivobj, num, arg);
762w_objivar(VALUE obj, struct dump_call_arg *arg)
766 rb_ivar_foreach(obj, obj_count_ivars, (st_data_t)&num);
767 w_long(num, arg->arg);
768 w_ivar_each(obj, num, arg);
772// Optimized dump for fixnum larger than 31-bits
774w_bigfixnum(VALUE obj, struct dump_arg *arg)
776 RUBY_ASSERT(FIXNUM_P(obj));
778 w_byte(TYPE_BIGNUM, arg);
780#if SIZEOF_LONG == SIZEOF_VALUE
784 long long num, slen_num;
788 char sign = num < 0 ? '-' : '+';
791 // Guaranteed not to overflow, as FIXNUM is 1-bit less than long
792 if (num < 0) num = -num;
794 // calculate the size in shorts
800 slen_num = SHORTDN(slen_num);
804 RUBY_ASSERT(slen > 0 && slen <= SIZEOF_LONG / 2);
806 w_long((long)slen, arg);
808 for (int i = 0; i < slen; i++) {
809 w_short(num & SHORTMASK, arg);
813 // We aren't adding this object to the link table, but we need to increment
817 RUBY_ASSERT(num == 0);
822w_remember(VALUE obj, struct dump_arg *arg)
824 st_add_direct(arg->data, obj, arg->num_entries++);
828w_object(VALUE obj, struct dump_arg *arg, int limit)
830 struct dump_call_arg c_arg;
831 VALUE ivobj = Qundef;
833 st_index_t hasiv = 0;
834 VALUE encname = Qnil;
837 rb_raise(rb_eArgError, "exceed depth limit");
841 w_byte(TYPE_NIL, arg);
843 else if (obj == Qtrue) {
844 w_byte(TYPE_TRUE, arg);
846 else if (obj == Qfalse) {
847 w_byte(TYPE_FALSE, arg);
849 else if (FIXNUM_P(obj)) {
851 w_byte(TYPE_FIXNUM, arg);
852 w_long(FIX2INT(obj), arg);
854 if (RSHIFT((long)obj, 31) == 0 || RSHIFT((long)obj, 31) == -1) {
855 w_byte(TYPE_FIXNUM, arg);
856 w_long(FIX2LONG(obj), arg);
859 w_bigfixnum(obj, arg);
863 else if (SYMBOL_P(obj)) {
867 if (st_lookup(arg->data, obj, &num)) {
868 w_byte(TYPE_LINK, arg);
869 w_long((long)num, arg);
873 if (limit > 0) limit--;
879 w_remember(obj, arg);
880 w_byte(TYPE_FLOAT, arg);
881 w_float(RFLOAT_VALUE(obj), arg);
887 if (!RBASIC_CLASS(obj)) {
888 rb_raise(rb_eTypeError, "can't dump internal %s",
889 rb_builtin_type_name(BUILTIN_TYPE(obj)));
892 if (rb_obj_respond_to(obj, s_mdump, TRUE)) {
893 w_remember(obj, arg);
895 v = dump_funcall(arg, obj, s_mdump, 0, 0);
896 w_class(TYPE_USRMARSHAL, obj, arg, FALSE);
897 w_object(v, arg, limit);
900 if (rb_obj_respond_to(obj, s_dump, TRUE)) {
901 VALUE ivobj2 = Qundef;
906 v = dump_funcall(arg, obj, s_dump, 1, &v);
907 if (!RB_TYPE_P(v, T_STRING)) {
908 rb_raise(rb_eTypeError, "_dump() must return string");
910 hasiv = has_ivars(obj, (encname = encoding_name(obj, arg)), &ivobj);
911 hasiv2 = has_ivars(v, (encname2 = encoding_name(v, arg)), &ivobj2);
917 if (hasiv) w_byte(TYPE_IVAR, arg);
918 w_class(TYPE_USERDEF, obj, arg, FALSE);
919 w_bytes(RSTRING_PTR(v), RSTRING_LEN(v), arg);
921 w_ivar(hasiv, ivobj, encname, &c_arg);
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");
953 w_byte(TYPE_CLASS, arg);
955 VALUE path = class2path(obj);
956 w_bytes(RSTRING_PTR(path), RSTRING_LEN(path), arg);
962 w_byte(TYPE_MODULE, arg);
964 VALUE path = class2path(obj);
965 w_bytes(RSTRING_PTR(path), RSTRING_LEN(path), arg);
971 w_byte(TYPE_FLOAT, arg);
972 w_float(RFLOAT_VALUE(obj), arg);
976 w_byte(TYPE_BIGNUM, arg);
978 char sign = BIGNUM_SIGN(obj) ? '+' : '-';
979 size_t len = BIGNUM_LEN(obj);
982 BDIGIT *d = BIGNUM_DIGITS(obj);
984 slen = SHORTLEN(len);
985 if (LONG_MAX < slen) {
986 rb_raise(rb_eTypeError, "too big Bignum can't be dumped");
990 w_long((long)slen, arg);
991 for (j = 0; j < len; j++) {
992#if SIZEOF_BDIGIT > SIZEOF_SHORT
996 for (i=0; i<SIZEOF_BDIGIT; i+=SIZEOF_SHORT) {
997 w_short(num & SHORTMASK, arg);
999 if (j == len - 1 && num == 0) break;
1010 w_uclass(obj, rb_cString, arg);
1011 w_byte(TYPE_STRING, arg);
1012 w_bytes(RSTRING_PTR(obj), RSTRING_LEN(obj), arg);
1016 w_uclass(obj, rb_cRegexp, arg);
1017 w_byte(TYPE_REGEXP, arg);
1019 int opts = rb_reg_options(obj);
1020 w_bytes(RREGEXP_SRC_PTR(obj), RREGEXP_SRC_LEN(obj), arg);
1021 w_byte((char)opts, arg);
1026 w_uclass(obj, rb_cArray, arg);
1027 w_byte(TYPE_ARRAY, arg);
1029 long i, len = RARRAY_LEN(obj);
1032 for (i=0; i<RARRAY_LEN(obj); i++) {
1033 w_object(RARRAY_AREF(obj, i), arg, limit);
1034 if (len != RARRAY_LEN(obj)) {
1035 rb_raise(rb_eRuntimeError, "array modified during dump");
1042 w_uclass(obj, rb_cHash, arg);
1043 if (rb_hash_compare_by_id_p(obj)) {
1044 w_byte(TYPE_UCLASS, arg);
1045 w_symbol(rb_sym_intern_ascii_cstr("Hash"), arg);
1047 if (NIL_P(RHASH_IFNONE(obj))) {
1048 w_byte(TYPE_HASH, arg);
1050 else if (FL_TEST(obj, RHASH_PROC_DEFAULT)) {
1051 rb_raise(rb_eTypeError, "can't dump hash with default proc");
1054 w_byte(TYPE_HASH_DEF, arg);
1056 w_long(rb_hash_size_num(obj), arg);
1057 rb_hash_foreach(obj, hash_each, (st_data_t)&c_arg);
1058 if (!NIL_P(RHASH_IFNONE(obj))) {
1059 w_object(RHASH_IFNONE(obj), arg, limit);
1064 w_class(TYPE_STRUCT, obj, arg, TRUE);
1066 long len = RSTRUCT_LEN(obj);
1071 mem = rb_struct_members(obj);
1072 for (i=0; i<len; i++) {
1073 w_symbol(RARRAY_AREF(mem, i), arg);
1074 w_object(RSTRUCT_GET(obj, i), arg, limit);
1080 w_class(TYPE_OBJECT, obj, arg, TRUE);
1081 w_objivar(obj, &c_arg);
1088 if (!rb_obj_respond_to(obj, s_dump_data, TRUE)) {
1089 rb_raise(rb_eTypeError,
1090 "no _dump_data is defined for class %"PRIsVALUE,
1093 v = dump_funcall(arg, obj, s_dump_data, 0, 0);
1094 w_class(TYPE_DATA, obj, arg, TRUE);
1095 w_object(v, arg, limit);
1100 rb_raise(rb_eTypeError, "can't dump %"PRIsVALUE,
1107 w_ivar(hasiv, ivobj, encname, &c_arg);
1112clear_dump_arg(struct dump_arg *arg)
1114 if (!arg->symbols) return;
1115 st_free_table(arg->symbols);
1117 st_free_table(arg->data);
1119 arg->num_entries = 0;
1120 if (arg->compat_tbl) {
1121 st_free_table(arg->compat_tbl);
1122 arg->compat_tbl = 0;
1124 if (arg->encodings) {
1125 st_free_table(arg->encodings);
1130NORETURN(static inline void io_needed(void));
1134 rb_raise(rb_eTypeError, "instance of IO needed");
1139 * dump( obj [, anIO] , limit=-1 ) -> anIO
1141 * Serializes obj and all descendant objects. If anIO is
1142 * specified, the serialized data will be written to it, otherwise the
1143 * data will be returned as a String. If limit is specified, the
1144 * traversal of subobjects will be limited to that depth. If limit is
1145 * negative, no checking of depth will be performed.
1148 * def initialize(str)
1156 * (produces no output)
1158 * o = Klass.new("hello\n")
1159 * data = Marshal.dump(o)
1160 * obj = Marshal.load(data)
1161 * obj.say_hello #=> "hello\n"
1163 * Marshal can't dump following objects:
1164 * * anonymous Class/Module.
1165 * * objects which are related to system (ex: Dir, File::Stat, IO, File, Socket
1167 * * an instance of MatchData, Data, Method, UnboundMethod, Proc, Thread,
1168 * ThreadGroup, Continuation
1169 * * objects which define singleton methods
1172marshal_dump(int argc, VALUE *argv, VALUE _)
1174 VALUE obj, port, a1, a2;
1178 rb_scan_args(argc, argv, "12", &obj, &a1, &a2);
1180 if (!NIL_P(a2)) limit = NUM2INT(a2);
1181 if (NIL_P(a1)) io_needed();
1184 else if (argc == 2) {
1185 if (FIXNUM_P(a1)) limit = FIX2INT(a1);
1186 else if (NIL_P(a1)) io_needed();
1189 return rb_marshal_dump_limited(obj, port, limit);
1193rb_marshal_dump_limited(VALUE obj, VALUE port, int limit)
1195 struct dump_arg *arg;
1196 VALUE wrapper; /* used to avoid memory leak in case of exception */
1198 wrapper = TypedData_Make_Struct(0, struct dump_arg, &dump_arg_data, arg);
1200 arg->symbols = st_init_numtable();
1201 arg->data = rb_init_identtable();
1202 arg->num_entries = 0;
1203 arg->compat_tbl = 0;
1205 arg->str = rb_str_buf_new(0);
1207 if (!rb_respond_to(port, s_write)) {
1211 dump_check_funcall(arg, port, s_binmode, 0, 0);
1217 w_byte(MARSHAL_MAJOR, arg);
1218 w_byte(MARSHAL_MINOR, arg);
1220 w_object(obj, arg, limit);
1222 rb_io_write(arg->dest, arg->str);
1223 rb_str_resize(arg->str, 0);
1225 clear_dump_arg(arg);
1226 RB_GC_GUARD(wrapper);
1239 st_table *partial_objects;
1241 st_table *compat_tbl;
1246check_load_arg(VALUE ret, struct load_arg *arg, const char *name)
1248 if (!arg->symbols) {
1249 rb_raise(rb_eRuntimeError, "Marshal.load reentered at %s",
1254#define load_funcall(arg, obj, sym, argc, argv) \
1255 check_load_arg(rb_funcallv(obj, sym, argc, argv), arg, name_##sym)
1257static void clear_load_arg(struct load_arg *arg);
1260mark_load_arg(void *ptr)
1262 struct load_arg *p = ptr;
1265 rb_mark_tbl(p->symbols);
1266 rb_mark_tbl(p->data);
1267 rb_mark_tbl(p->partial_objects);
1268 rb_mark_hash(p->compat_tbl);
1272free_load_arg(void *ptr)
1274 clear_load_arg(ptr);
1279memsize_load_arg(const void *ptr)
1281 return sizeof(struct load_arg);
1284static const rb_data_type_t load_arg_data = {
1286 {mark_load_arg, free_load_arg, memsize_load_arg,},
1287 0, 0, RUBY_TYPED_FREE_IMMEDIATELY
1290#define r_entry(v, arg) r_entry0((v), (arg)->data->num_entries, (arg))
1291static VALUE r_object(struct load_arg *arg);
1292static VALUE r_symbol(struct load_arg *arg);
1294NORETURN(static void too_short(void));
1298 rb_raise(rb_eArgError, "marshal data too short");
1302r_prepare(struct load_arg *arg)
1304 st_index_t idx = arg->data->num_entries;
1306 st_insert(arg->data, (st_data_t)idx, (st_data_t)Qundef);
1311r_byte1_buffered(struct load_arg *arg)
1313 if (arg->buflen == 0) {
1314 long readable = arg->readable < BUFSIZ ? arg->readable : BUFSIZ;
1315 VALUE str, n = LONG2NUM(readable);
1317 str = load_funcall(arg, arg->src, s_read, 1, &n);
1318 if (NIL_P(str)) too_short();
1320 memcpy(arg->buf, RSTRING_PTR(str), RSTRING_LEN(str));
1322 arg->buflen = RSTRING_LEN(str);
1325 return arg->buf[arg->offset++];
1329r_byte(struct load_arg *arg)
1333 if (RB_TYPE_P(arg->src, T_STRING)) {
1334 if (RSTRING_LEN(arg->src) > arg->offset) {
1335 c = (unsigned char)RSTRING_PTR(arg->src)[arg->offset++];
1342 if (arg->readable >0 || arg->buflen > 0) {
1343 c = r_byte1_buffered(arg);
1346 VALUE v = load_funcall(arg, arg->src, s_getbyte, 0, 0);
1347 if (NIL_P(v)) rb_eof_error();
1348 c = (unsigned char)NUM2CHR(v);
1354NORETURN(static void long_toobig(int size));
1357long_toobig(int size)
1359 rb_raise(rb_eTypeError, "long too big for this architecture (size "
1360 STRINGIZE(SIZEOF_LONG)", given %d)", size);
1364r_long(struct load_arg *arg)
1367 int c = (signed char)r_byte(arg);
1370 if (c == 0) return 0;
1372 if (4 < c && c < 128) {
1375 if (c > (int)sizeof(long)) long_toobig(c);
1378 x |= (long)r_byte(arg) << (8*i);
1382 if (-129 < c && c < -4) {
1386 if (c > (int)sizeof(long)) long_toobig(c);
1389 x &= ~((long)0xff << (8*i));
1390 x |= (long)r_byte(arg) << (8*i);
1397ruby_marshal_read_long(const char **buf, long len)
1401 struct load_arg arg;
1402 memset(&arg, 0, sizeof(arg));
1403 arg.src = rb_setup_fake_str(&src, *buf, len, 0);
1410r_bytes1(long len, struct load_arg *arg)
1412 VALUE str, n = LONG2NUM(len);
1414 str = load_funcall(arg, arg->src, s_read, 1, &n);
1415 if (NIL_P(str)) too_short();
1417 if (RSTRING_LEN(str) != len) too_short();
1423r_bytes1_buffered(long len, struct load_arg *arg)
1427 if (len <= arg->buflen) {
1428 str = rb_str_new(arg->buf+arg->offset, len);
1433 long buflen = arg->buflen;
1434 long readable = arg->readable + 1;
1435 long tmp_len, read_len, need_len = len - buflen;
1438 readable = readable < BUFSIZ ? readable : BUFSIZ;
1439 read_len = need_len > readable ? need_len : readable;
1440 n = LONG2NUM(read_len);
1441 tmp = load_funcall(arg, arg->src, s_read, 1, &n);
1442 if (NIL_P(tmp)) too_short();
1445 tmp_len = RSTRING_LEN(tmp);
1447 if (tmp_len < need_len) too_short();
1449 str = rb_str_new(arg->buf+arg->offset, buflen);
1450 rb_str_cat(str, RSTRING_PTR(tmp), need_len);
1452 if (tmp_len > need_len) {
1453 buflen = tmp_len - need_len;
1454 memcpy(arg->buf, RSTRING_PTR(tmp)+need_len, buflen);
1455 arg->buflen = buflen;
1466#define r_bytes(arg) r_bytes0(r_long(arg), (arg))
1469r_bytes0(long len, struct load_arg *arg)
1473 if (len == 0) return rb_str_new(0, 0);
1474 if (RB_TYPE_P(arg->src, T_STRING)) {
1475 if (RSTRING_LEN(arg->src) - arg->offset >= len) {
1476 str = rb_str_new(RSTRING_PTR(arg->src)+arg->offset, len);
1484 if (arg->readable > 0 || arg->buflen > 0) {
1485 str = r_bytes1_buffered(len, arg);
1488 str = r_bytes1(len, arg);
1495name_equal(const char *name, size_t nlen, const char *p, long l)
1497 if ((size_t)l != nlen || *p != *name) return 0;
1498 return nlen == 1 || memcmp(p+1, name+1, nlen-1) == 0;
1502sym2encidx(VALUE sym, VALUE val)
1504 static const char name_encoding[8] = "encoding";
1507 if (rb_enc_get_index(sym) != ENCINDEX_US_ASCII) return -1;
1508 RSTRING_GETMEM(sym, p, l);
1509 if (l <= 0) return -1;
1510 if (name_equal(name_encoding, sizeof(name_encoding), p, l)) {
1511 int idx = rb_enc_find_index(StringValueCStr(val));
1514 if (name_equal(name_s_encoding_short, rb_strlen_lit(name_s_encoding_short), p, l)) {
1515 if (val == Qfalse) return rb_usascii_encindex();
1516 else if (val == Qtrue) return rb_utf8_encindex();
1523symname_equal(VALUE sym, const char *name, size_t nlen)
1527 if (rb_enc_get_index(sym) != ENCINDEX_US_ASCII) return 0;
1528 RSTRING_GETMEM(sym, p, l);
1529 return name_equal(name, nlen, p, l);
1532#define BUILD_ASSERT_POSITIVE(n) \
1533 /* make 0 negative to workaround the "zero size array" GCC extension, */ \
1534 ((sizeof(char [2*(ssize_t)(n)-1])+1)/2) /* assuming no overflow */
1535#define symname_equal_lit(sym, sym_name) \
1536 symname_equal(sym, sym_name, BUILD_ASSERT_POSITIVE(rb_strlen_lit(sym_name)))
1539r_symlink(struct load_arg *arg)
1542 long num = r_long(arg);
1544 if (!st_lookup(arg->symbols, num, &sym)) {
1545 rb_raise(rb_eArgError, "bad symbol");
1551r_symreal(struct load_arg *arg, int ivar)
1553 VALUE s = r_bytes(arg);
1556 st_index_t n = arg->symbols->num_entries;
1558 if (rb_enc_str_asciionly_p(s)) rb_enc_associate_index(s, ENCINDEX_US_ASCII);
1559 st_insert(arg->symbols, (st_data_t)n, (st_data_t)s);
1561 long num = r_long(arg);
1563 sym = r_symbol(arg);
1564 idx = sym2encidx(sym, r_object(arg));
1568 rb_enc_associate_index(s, idx);
1569 if (is_broken_string(s)) {
1570 rb_raise(rb_eArgError, "invalid byte sequence in %s: %+"PRIsVALUE,
1571 rb_enc_name(rb_enc_from_index(idx)), s);
1579r_symbol(struct load_arg *arg)
1584 switch ((type = r_byte(arg))) {
1586 rb_raise(rb_eArgError, "dump format error for symbol(0x%x)", type);
1591 return r_symreal(arg, ivar);
1594 rb_raise(rb_eArgError, "dump format error (symlink with encoding)");
1596 return r_symlink(arg);
1601r_unique(struct load_arg *arg)
1603 return r_symbol(arg);
1607r_string(struct load_arg *arg)
1609 return r_bytes(arg);
1613r_entry0(VALUE v, st_index_t num, struct load_arg *arg)
1615 st_data_t real_obj = (st_data_t)v;
1616 if (arg->compat_tbl) {
1617 /* real_obj is kept if not found */
1618 st_lookup(arg->compat_tbl, v, &real_obj);
1620 st_insert(arg->data, num, real_obj);
1621 st_insert(arg->partial_objects, (st_data_t)real_obj, Qtrue);
1626r_fixup_compat(VALUE v, struct load_arg *arg)
1629 st_data_t key = (st_data_t)v;
1630 if (arg->compat_tbl && st_delete(arg->compat_tbl, &key, &data)) {
1631 VALUE real_obj = (VALUE)data;
1632 rb_alloc_func_t allocator = rb_get_alloc_func(CLASS_OF(real_obj));
1633 if (st_lookup(compat_allocator_tbl, (st_data_t)allocator, &data)) {
1634 marshal_compat_t *compat = (marshal_compat_t*)data;
1635 compat->loader(real_obj, v);
1643r_post_proc(VALUE v, struct load_arg *arg)
1646 v = load_funcall(arg, arg->proc, s_call, 1, &v);
1652r_leave(VALUE v, struct load_arg *arg, bool partial)
1654 v = r_fixup_compat(v, arg);
1657 st_data_t key = (st_data_t)v;
1658 st_delete(arg->partial_objects, &key, &data);
1660 if (RB_TYPE_P(v, T_MODULE) || RB_TYPE_P(v, T_CLASS)) {
1663 else if (RB_TYPE_P(v, T_STRING)) {
1664 v = rb_str_to_interned_str(v);
1670 v = r_post_proc(v, arg);
1676copy_ivar_i(st_data_t key, st_data_t val, st_data_t arg)
1678 VALUE obj = (VALUE)arg, value = (VALUE)val;
1681 if (!rb_ivar_defined(obj, vid))
1682 rb_ivar_set(obj, vid, value);
1687r_copy_ivar(VALUE v, VALUE data)
1689 rb_ivar_foreach(data, copy_ivar_i, (st_data_t)v);
1694r_ivar(VALUE obj, int *has_encoding, struct load_arg *arg)
1701 VALUE sym = r_symbol(arg);
1702 VALUE val = r_object(arg);
1703 int idx = sym2encidx(sym, val);
1705 if (rb_enc_capable(obj)) {
1706 rb_enc_associate_index(obj, idx);
1709 rb_raise(rb_eArgError, "%"PRIsVALUE" is not enc_capable", obj);
1711 if (has_encoding) *has_encoding = TRUE;
1713 else if (symname_equal_lit(sym, name_s_ruby2_keywords_flag)) {
1714 if (RB_TYPE_P(obj, T_HASH)) {
1715 rb_hash_ruby2_keywords(obj);
1718 rb_raise(rb_eArgError, "ruby2_keywords flag is given but %"PRIsVALUE" is not a Hash", obj);
1722 rb_ivar_set(obj, rb_intern_str(sym), val);
1724 } while (--len > 0);
1729path2class(VALUE path)
1731 VALUE v = rb_path_to_class(path);
1733 if (!RB_TYPE_P(v, T_CLASS)) {
1734 rb_raise(rb_eArgError, "%"PRIsVALUE" does not refer to class", path);
1739#define path2module(path) must_be_module(rb_path_to_class(path), path)
1742must_be_module(VALUE v, VALUE path)
1744 if (!RB_TYPE_P(v, T_MODULE)) {
1745 rb_raise(rb_eArgError, "%"PRIsVALUE" does not refer to module", path);
1751obj_alloc_by_klass(VALUE klass, struct load_arg *arg, VALUE *oldclass)
1754 rb_alloc_func_t allocator;
1756 allocator = rb_get_alloc_func(klass);
1757 if (st_lookup(compat_allocator_tbl, (st_data_t)allocator, &data)) {
1758 marshal_compat_t *compat = (marshal_compat_t*)data;
1759 VALUE real_obj = rb_obj_alloc(klass);
1760 VALUE obj = rb_obj_alloc(compat->oldclass);
1761 if (oldclass) *oldclass = compat->oldclass;
1763 if (!arg->compat_tbl) {
1764 arg->compat_tbl = rb_init_identtable();
1766 st_insert(arg->compat_tbl, (st_data_t)obj, (st_data_t)real_obj);
1770 return rb_obj_alloc(klass);
1774obj_alloc_by_path(VALUE path, struct load_arg *arg)
1776 return obj_alloc_by_klass(path2class(path), arg, 0);
1780append_extmod(VALUE obj, VALUE extmod)
1782 long i = RARRAY_LEN(extmod);
1784 VALUE m = RARRAY_AREF(extmod, --i);
1785 rb_extend_object(obj, m);
1790#define prohibit_ivar(type, str) do { \
1791 if (!ivp || !*ivp) break; \
1792 rb_raise(rb_eTypeError, \
1793 "can't override instance variable of "type" `%"PRIsVALUE"'", \
1797static VALUE r_object_for(struct load_arg *arg, bool partial, int *ivp, VALUE extmod, int type);
1800r_object0(struct load_arg *arg, bool partial, int *ivp, VALUE extmod)
1802 int type = r_byte(arg);
1803 return r_object_for(arg, partial, ivp, extmod, type);
1807r_object_for(struct load_arg *arg, bool partial, int *ivp, VALUE extmod, int type)
1809 VALUE (*hash_new_with_size)(st_index_t) = rb_hash_new_with_size;
1817 if (!st_lookup(arg->data, (st_data_t)id, &link)) {
1818 rb_raise(rb_eArgError, "dump format error (unlinked)");
1821 if (!st_lookup(arg->partial_objects, (st_data_t)v, &link)) {
1822 v = r_post_proc(v, arg);
1830 v = r_object0(arg, true, &ivar, extmod);
1831 if (ivar) r_ivar(v, NULL, arg);
1832 v = r_leave(v, arg, partial);
1838 VALUE path = r_unique(arg);
1839 VALUE m = rb_path_to_class(path);
1840 if (NIL_P(extmod)) extmod = rb_ary_hidden_new(0);
1842 if (RB_TYPE_P(m, T_CLASS)) { /* prepended */
1845 v = r_object0(arg, true, 0, Qnil);
1847 if (c != m || FL_TEST(c, FL_SINGLETON)) {
1848 rb_raise(rb_eArgError,
1849 "prepended class %"PRIsVALUE" differs from class %"PRIsVALUE,
1850 path, rb_class_name(c));
1852 c = rb_singleton_class(v);
1853 while (RARRAY_LEN(extmod) > 0) {
1854 m = rb_ary_pop(extmod);
1855 rb_prepend_module(c, m);
1859 must_be_module(m, path);
1860 rb_ary_push(extmod, m);
1862 v = r_object0(arg, true, 0, extmod);
1863 while (RARRAY_LEN(extmod) > 0) {
1864 m = rb_ary_pop(extmod);
1865 rb_extend_object(v, m);
1873 VALUE c = path2class(r_unique(arg));
1875 if (FL_TEST(c, FL_SINGLETON)) {
1876 rb_raise(rb_eTypeError, "singleton can't be loaded");
1879 if ((c == rb_cHash) &&
1880 /* Hack for compare_by_identify */
1881 (type == TYPE_HASH || type == TYPE_HASH_DEF)) {
1882 hash_new_with_size = rb_ident_hash_new_with_size;
1885 v = r_object_for(arg, partial, 0, extmod, type);
1886 if (rb_special_const_p(v) || RB_TYPE_P(v, T_OBJECT) || RB_TYPE_P(v, T_CLASS)) {
1889 if (RB_TYPE_P(v, T_MODULE) || !RTEST(rb_class_inherited_p(c, RBASIC(v)->klass))) {
1890 VALUE tmp = rb_obj_alloc(c);
1892 if (TYPE(v) != TYPE(tmp)) goto format_error;
1894 RBASIC_SET_CLASS(v, c);
1899 rb_raise(rb_eArgError, "dump format error (user class)");
1903 v = r_leave(v, arg, false);
1908 v = r_leave(v, arg, false);
1913 v = r_leave(v, arg, false);
1918 long i = r_long(arg);
1921 v = r_leave(v, arg, false);
1927 VALUE str = r_bytes(arg);
1928 const char *ptr = RSTRING_PTR(str);
1930 if (strcmp(ptr, "nan") == 0) {
1933 else if (strcmp(ptr, "inf") == 0) {
1936 else if (strcmp(ptr, "-inf") == 0) {
1941 d = strtod(ptr, &e);
1942 d = load_mantissa(d, e, RSTRING_LEN(str) - (e - ptr));
1945 v = r_entry(v, arg);
1946 v = r_leave(v, arg, false);
1959 if (SIZEOF_VALUE >= 8 && len <= 4) {
1960 // Representable within uintptr, likely FIXNUM
1962 for (int i = 0; i < len; i++) {
1963 num |= (VALUE)r_byte(arg) << (i * 16);
1964 num |= (VALUE)r_byte(arg) << (i * 16 + 8);
1966#if SIZEOF_VALUE == SIZEOF_LONG
1972 v = rb_int_uminus(v);
1976 data = r_bytes0(len * 2, arg);
1977 v = rb_integer_unpack(RSTRING_PTR(data), len, 2, 0,
1978 INTEGER_PACK_LITTLE_ENDIAN | (sign == '-' ? INTEGER_PACK_NEGATIVE : 0));
1979 rb_str_resize(data, 0L);
1981 v = r_entry(v, arg);
1982 v = r_leave(v, arg, false);
1987 v = r_entry(r_string(arg), arg);
1988 v = r_leave(v, arg, partial);
1993 VALUE str = r_bytes(arg);
1994 int options = r_byte(arg);
1995 int has_encoding = FALSE;
1996 st_index_t idx = r_prepare(arg);
1999 r_ivar(str, &has_encoding, arg);
2002 if (!has_encoding) {
2003 /* 1.8 compatibility; remove escapes undefined in 1.8 */
2004 char *ptr = RSTRING_PTR(str), *dst = ptr, *src = ptr;
2005 long len = RSTRING_LEN(str);
2007 for (; len-- > 0; *dst++ = *src++) {
2009 case '\\': bs++; break;
2010 case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
2011 case 'm': case 'o': case 'p': case 'q': case 'u': case 'y':
2012 case 'E': case 'F': case 'H': case 'I': case 'J': case 'K':
2013 case 'L': case 'N': case 'O': case 'P': case 'Q': case 'R':
2014 case 'S': case 'T': case 'U': case 'V': case 'X': case 'Y':
2017 default: bs = 0; break;
2020 rb_str_set_len(str, dst - ptr);
2022 v = r_entry0(rb_reg_new_str(str, options), idx, arg);
2023 v = r_leave(v, arg, partial);
2029 long len = r_long(arg);
2031 v = rb_ary_new2(len);
2032 v = r_entry(v, arg);
2033 arg->readable += len - 1;
2035 rb_ary_push(v, r_object(arg));
2038 v = r_leave(v, arg, partial);
2047 long len = r_long(arg);
2049 v = hash_new_with_size(len);
2050 v = r_entry(v, arg);
2051 arg->readable += (len - 1) * 2;
2053 VALUE key = r_object(arg);
2054 VALUE value = r_object(arg);
2055 rb_hash_aset(v, key, value);
2059 if (type == TYPE_HASH_DEF) {
2060 RHASH_SET_IFNONE(v, r_object(arg));
2062 v = r_leave(v, arg, partial);
2071 st_index_t idx = r_prepare(arg);
2072 VALUE klass = path2class(r_unique(arg));
2073 long len = r_long(arg);
2075 v = rb_obj_alloc(klass);
2076 if (!RB_TYPE_P(v, T_STRUCT)) {
2077 rb_raise(rb_eTypeError, "class %"PRIsVALUE" not a struct", rb_class_name(klass));
2079 mem = rb_struct_s_members(klass);
2080 if (RARRAY_LEN(mem) != len) {
2081 rb_raise(rb_eTypeError, "struct %"PRIsVALUE" not compatible (struct size differs)",
2082 rb_class_name(klass));
2085 arg->readable += (len - 1) * 2;
2086 v = r_entry0(v, idx, arg);
2087 values = rb_ary_new2(len);
2089 VALUE keywords = Qfalse;
2090 if (RTEST(rb_struct_s_keyword_init(klass))) {
2091 keywords = rb_hash_new();
2092 rb_ary_push(values, keywords);
2095 for (i=0; i<len; i++) {
2096 VALUE n = rb_sym2str(RARRAY_AREF(mem, i));
2097 slot = r_symbol(arg);
2099 if (!rb_str_equal(n, slot)) {
2100 rb_raise(rb_eTypeError, "struct %"PRIsVALUE" not compatible (:%"PRIsVALUE" for :%"PRIsVALUE")",
2101 rb_class_name(klass),
2105 rb_hash_aset(keywords, RARRAY_AREF(mem, i), r_object(arg));
2108 rb_ary_push(values, r_object(arg));
2113 rb_struct_initialize(v, values);
2114 v = r_leave(v, arg, partial);
2121 VALUE name = r_unique(arg);
2122 VALUE klass = path2class(name);
2126 if (!rb_obj_respond_to(klass, s_load, TRUE)) {
2127 rb_raise(rb_eTypeError, "class %"PRIsVALUE" needs to have method `_load'",
2130 data = r_string(arg);
2132 r_ivar(data, NULL, arg);
2135 v = load_funcall(arg, klass, s_load, 1, &data);
2136 v = r_entry(v, arg);
2137 if (st_lookup(compat_allocator_tbl, (st_data_t)rb_get_alloc_func(klass), &d)) {
2138 marshal_compat_t *compat = (marshal_compat_t*)d;
2139 v = compat->loader(klass, v);
2141 if (!partial) v = r_post_proc(v, arg);
2145 case TYPE_USRMARSHAL:
2147 VALUE name = r_unique(arg);
2148 VALUE klass = path2class(name);
2152 v = obj_alloc_by_klass(klass, arg, &oldclass);
2153 if (!NIL_P(extmod)) {
2154 /* for the case marshal_load is overridden */
2155 append_extmod(v, extmod);
2157 if (!rb_obj_respond_to(v, s_mload, TRUE)) {
2158 rb_raise(rb_eTypeError, "instance of %"PRIsVALUE" needs to have method `marshal_load'",
2161 v = r_entry(v, arg);
2162 data = r_object(arg);
2163 load_funcall(arg, v, s_mload, 1, &data);
2164 v = r_fixup_compat(v, arg);
2165 v = r_copy_ivar(v, data);
2166 v = r_post_proc(v, arg);
2167 if (!NIL_P(extmod)) {
2168 if (oldclass) append_extmod(v, extmod);
2169 rb_ary_clear(extmod);
2176 st_index_t idx = r_prepare(arg);
2177 v = obj_alloc_by_path(r_unique(arg), arg);
2178 if (!RB_TYPE_P(v, T_OBJECT)) {
2179 rb_raise(rb_eArgError, "dump format error");
2181 v = r_entry0(v, idx, arg);
2182 r_ivar(v, NULL, arg);
2183 v = r_leave(v, arg, partial);
2189 VALUE name = r_unique(arg);
2190 VALUE klass = path2class(name);
2194 v = obj_alloc_by_klass(klass, arg, &oldclass);
2195 if (!RB_TYPE_P(v, T_DATA)) {
2196 rb_raise(rb_eArgError, "dump format error");
2198 v = r_entry(v, arg);
2199 if (!rb_obj_respond_to(v, s_load_data, TRUE)) {
2200 rb_raise(rb_eTypeError,
2201 "class %"PRIsVALUE" needs to have instance method `_load_data'",
2204 r = r_object0(arg, partial, 0, extmod);
2205 load_funcall(arg, v, s_load_data, 1, &r);
2206 v = r_leave(v, arg, partial);
2210 case TYPE_MODULE_OLD:
2212 VALUE str = r_bytes(arg);
2214 v = rb_path_to_class(str);
2215 prohibit_ivar("class/module", str);
2216 v = r_entry(v, arg);
2217 v = r_leave(v, arg, partial);
2223 VALUE str = r_bytes(arg);
2225 v = path2class(str);
2226 prohibit_ivar("class", str);
2227 v = r_entry(v, arg);
2228 v = r_leave(v, arg, partial);
2234 VALUE str = r_bytes(arg);
2236 v = path2module(str);
2237 prohibit_ivar("module", str);
2238 v = r_entry(v, arg);
2239 v = r_leave(v, arg, partial);
2245 v = r_symreal(arg, *ivp);
2249 v = r_symreal(arg, 0);
2251 v = rb_str_intern(v);
2252 v = r_leave(v, arg, partial);
2256 v = rb_str_intern(r_symlink(arg));
2260 rb_raise(rb_eArgError, "dump format error(0x%x)", type);
2265 rb_raise(rb_eArgError, "dump format error (bad link)");
2272r_object(struct load_arg *arg)
2274 return r_object0(arg, false, 0, Qnil);
2278clear_load_arg(struct load_arg *arg)
2287 if (!arg->symbols) return;
2288 st_free_table(arg->symbols);
2290 st_free_table(arg->data);
2292 st_free_table(arg->partial_objects);
2293 arg->partial_objects = 0;
2294 if (arg->compat_tbl) {
2295 st_free_table(arg->compat_tbl);
2296 arg->compat_tbl = 0;
2301rb_marshal_load_with_proc(VALUE port, VALUE proc, bool freeze)
2305 VALUE wrapper; /* used to avoid memory leak in case of exception */
2306 struct load_arg *arg;
2308 v = rb_check_string_type(port);
2312 else if (rb_respond_to(port, s_getbyte) && rb_respond_to(port, s_read)) {
2313 rb_check_funcall(port, s_binmode, 0, 0);
2318 wrapper = TypedData_Make_Struct(0, struct load_arg, &load_arg_data, arg);
2321 arg->symbols = st_init_numtable();
2322 arg->data = rb_init_identtable();
2323 arg->partial_objects = rb_init_identtable();
2324 arg->compat_tbl = 0;
2327 arg->freeze = freeze;
2330 arg->buf = xmalloc(BUFSIZ);
2334 major = r_byte(arg);
2335 minor = r_byte(arg);
2336 if (major != MARSHAL_MAJOR || minor > MARSHAL_MINOR) {
2337 clear_load_arg(arg);
2338 rb_raise(rb_eTypeError, "incompatible marshal file format (can't be read)\n\
2339\tformat version %d.%d required; %d.%d given",
2340 MARSHAL_MAJOR, MARSHAL_MINOR, major, minor);
2342 if (RTEST(ruby_verbose) && minor != MARSHAL_MINOR) {
2343 rb_warn("incompatible marshal file format (can be read)\n\
2344\tformat version %d.%d required; %d.%d given",
2345 MARSHAL_MAJOR, MARSHAL_MINOR, major, minor);
2348 if (!NIL_P(proc)) arg->proc = proc;
2350 clear_load_arg(arg);
2351 RB_GC_GUARD(wrapper);
2357marshal_load(rb_execution_context_t *ec, VALUE mod, VALUE source, VALUE proc, VALUE freeze)
2359 return rb_marshal_load_with_proc(source, proc, RTEST(freeze));
2362#include "marshal.rbinc"
2365 * The marshaling library converts collections of Ruby objects into a
2366 * byte stream, allowing them to be stored outside the currently
2367 * active script. This data may subsequently be read and the original
2368 * objects reconstituted.
2370 * Marshaled data has major and minor version numbers stored along
2371 * with the object information. In normal use, marshaling can only
2372 * load data written with the same major version number and an equal
2373 * or lower minor version number. If Ruby's ``verbose'' flag is set
2374 * (normally using -d, -v, -w, or --verbose) the major and minor
2375 * numbers must match exactly. Marshal versioning is independent of
2376 * Ruby's version numbers. You can extract the version by reading the
2377 * first two bytes of marshaled data.
2379 * str = Marshal.dump("thing")
2380 * RUBY_VERSION #=> "1.9.0"
2384 * Some objects cannot be dumped: if the objects to be dumped include
2385 * bindings, procedure or method objects, instances of class IO, or
2386 * singleton objects, a TypeError will be raised.
2388 * If your class has special serialization needs (for example, if you
2389 * want to serialize in some specific format), or if it contains
2390 * objects that would otherwise not be serializable, you can implement
2391 * your own serialization strategy.
2393 * There are two methods of doing this, your object can define either
2394 * marshal_dump and marshal_load or _dump and _load. marshal_dump will take
2395 * precedence over _dump if both are defined. marshal_dump may result in
2396 * smaller Marshal strings.
2398 * == Security considerations
2400 * By design, Marshal.load can deserialize almost any class loaded into the
2401 * Ruby process. In many cases this can lead to remote code execution if the
2402 * Marshal data is loaded from an untrusted source.
2404 * As a result, Marshal.load is not suitable as a general purpose serialization
2405 * format and you should never unmarshal user supplied input or other untrusted
2408 * If you need to deserialize untrusted data, use JSON or another serialization
2409 * format that is only able to load simple, 'primitive' types such as String,
2410 * Array, Hash, etc. Never allow user input to specify arbitrary types to
2413 * == marshal_dump and marshal_load
2415 * When dumping an object the method marshal_dump will be called.
2416 * marshal_dump must return a result containing the information necessary for
2417 * marshal_load to reconstitute the object. The result can be any object.
2419 * When loading an object dumped using marshal_dump the object is first
2420 * allocated then marshal_load is called with the result from marshal_dump.
2421 * marshal_load must recreate the object from the information in the result.
2426 * def initialize name, version, data
2428 * @version = version
2436 * def marshal_load array
2437 * @name, @version = array
2441 * == _dump and _load
2443 * Use _dump and _load when you need to allocate the object you're restoring
2446 * When dumping an object the instance method _dump is called with an Integer
2447 * which indicates the maximum depth of objects to dump (a value of -1 implies
2448 * that you should disable depth checking). _dump must return a String
2449 * containing the information necessary to reconstitute the object.
2451 * The class method _load should take a String and use it to return an object
2452 * of the same class.
2457 * def initialize name, version, data
2459 * @version = version
2464 * [@name, @version].join ':'
2467 * def self._load args
2468 * new(*args.split(':'))
2472 * Since Marshal.dump outputs a string you can have _dump return a Marshal
2473 * string which is Marshal.loaded in _load for complex objects.
2478 VALUE rb_mMarshal = rb_define_module("Marshal");
2479#define set_id(sym) sym = rb_intern_const(name_##sym)
2484 set_id(s_dump_data);
2485 set_id(s_load_data);
2492 set_id(s_encoding_short);
2493 set_id(s_ruby2_keywords_flag);
2495 rb_define_module_function(rb_mMarshal, "dump", marshal_dump, -1);
2498 rb_define_const(rb_mMarshal, "MAJOR_VERSION", INT2FIX(MARSHAL_MAJOR));
2500 rb_define_const(rb_mMarshal, "MINOR_VERSION", INT2FIX(MARSHAL_MINOR));
2504compat_allocator_table(void)
2506 if (compat_allocator_tbl) return compat_allocator_tbl;
2507 compat_allocator_tbl = st_init_numtable();
2508#undef RUBY_UNTYPED_DATA_WARNING
2509#define RUBY_UNTYPED_DATA_WARNING 0
2510 compat_allocator_tbl_wrapper =
2511 Data_Wrap_Struct(0, mark_marshal_compat_t, 0, compat_allocator_tbl);
2512 rb_gc_register_mark_object(compat_allocator_tbl_wrapper);
2513 return compat_allocator_tbl;
2517rb_marshal_dump(VALUE obj, VALUE port)
2519 return rb_marshal_dump_limited(obj, port, -1);
2523rb_marshal_load(VALUE port)
2525 return rb_marshal_load_with_proc(port, Qnil, false);
Defines RBIMPL_HAS_BUILTIN.