@@ -26,7 +26,7 @@ MRB_END_DECL
2626/* Configurable CBOR recursion depth limits */
2727#ifndef CBOR_MAX_DEPTH
2828 #if defined(MRB_PROFILE_MAIN ) || defined(MRB_PROFILE_HIGH )
29- #define CBOR_MAX_DEPTH 512
29+ #define CBOR_MAX_DEPTH 128
3030 #elif defined(MRB_PROFILE_BASELINE )
3131 #define CBOR_MAX_DEPTH 64
3232 #else
@@ -964,16 +964,26 @@ encode_bignum(CborWriter *w, mrb_value obj)
964964 }
965965
966966 mrb_value mag = mrb_bint_abs (mrb , obj );
967+ mrb_gc_protect (mrb , mag );
967968 if (sign < 0 ) {
968969 mrb_value one = mrb_fixnum_value (1 );
969970 mag = mrb_bint_sub (mrb , mag , one );
970971 }
972+ mrb_gc_protect (mrb , mag );
971973
972974 mrb_value hex = mrb_bint_to_s (mrb , mag , 16 );
973- mrb_gc_register (mrb , hex );
974- char * p = RSTRING_PTR ( hex );
975+ mrb_gc_protect (mrb , hex );
976+
975977 mrb_int len = RSTRING_LEN (hex );
978+ // Copy into a C buffer now, before any further mruby allocations
979+ char * hbuf = (char * )mrb_malloc (mrb , len + 2 ); // +2 for odd-pad + NUL
980+ memcpy (hbuf , RSTRING_PTR (hex ), len );
981+ hbuf [len ] = '\0' ;
982+
983+ // hex no longer needed as a live mruby object
984+ mrb_gc_arena_restore (mrb , idx );
976985
986+ char * p = hbuf ;
977987 while (len > 0 && * p == '0' ) { p ++ ; len -- ; }
978988
979989 if (len == 0 ) {
@@ -982,8 +992,8 @@ encode_bignum(CborWriter *w, mrb_value obj)
982992 encode_len (w , 2 , 1 );
983993 uint8_t zero = 0 ;
984994 cbor_writer_write (w , & zero , 1 );
985- mrb_gc_unregister (mrb , hex );
986995 mrb_gc_arena_restore (mrb , idx );
996+ mrb_free (mrb , hbuf );
987997 return ;
988998 }
989999
@@ -996,10 +1006,11 @@ encode_bignum(CborWriter *w, mrb_value obj)
9961006
9971007 if (odd ) { memmove (p + 1 , p , len ); p [0 ] = '0' ; }
9981008
999- uint8_t * out = (uint8_t * )mrb_alloca (mrb , byte_len );
1009+ uint8_t * out = (uint8_t * )mrb_malloc (mrb , byte_len );
10001010 hex_decode_scalar (out , p , byte_len );
10011011 cbor_writer_write (w , out , (size_t )byte_len );
1002- mrb_gc_unregister (mrb , hex );
1012+ mrb_free (mrb , hbuf );
1013+ mrb_free (mrb , out );
10031014 mrb_gc_arena_restore (mrb , idx );
10041015}
10051016#endif
0 commit comments