diff --git a/ext/json/ext/generator/generator.c b/ext/json/ext/generator/generator.c index 18b6c544..ae27eeef 100644 --- a/ext/json/ext/generator/generator.c +++ b/ext/json/ext/generator/generator.c @@ -17,9 +17,9 @@ typedef struct JSON_Generator_StateStruct { VALUE array_nl; VALUE as_json; - long max_nesting; - long depth; - long buffer_initial_length; + size_t max_nesting; + size_t depth; + size_t buffer_initial_length; bool allow_duplicate_key; bool as_json_single_arg; @@ -56,7 +56,7 @@ struct generate_json_data { JSON_Generator_State *state; VALUE obj; generator_func func; - long depth; + size_t depth; }; #if defined(HAVE_SIMD) && defined(HAVE_SIMD_SSE2) @@ -284,7 +284,7 @@ static inline void escape_UTF8_char(search_state *search, unsigned char ch_len) #ifdef HAVE_SIMD -ALWAYS_INLINE(static) char *copy_remaining_bytes(search_state *search, unsigned long vec_len, unsigned long len) +ALWAYS_INLINE(static) char *copy_remaining_bytes(search_state *search, size_t vec_len, size_t len) { RBIMPL_ASSERT_OR_ASSUME(len < vec_len); @@ -396,7 +396,7 @@ static inline unsigned char search_escape_basic_neon(search_state *search) } // There are fewer than 16 bytes left. - unsigned long remaining = (search->end - search->ptr); + size_t remaining = (search->end - search->ptr); if (remaining >= SIMD_MINIMUM_THRESHOLD) { char *s = copy_remaining_bytes(search, sizeof(uint8x16_t), remaining); @@ -479,7 +479,7 @@ ALWAYS_INLINE(static) TARGET_SSE2 unsigned char search_escape_basic_sse2(search_ } // There are fewer than 16 bytes left. - unsigned long remaining = (search->end - search->ptr); + size_t remaining = (search->end - search->ptr); if (remaining >= SIMD_MINIMUM_THRESHOLD) { char *s = copy_remaining_bytes(search, sizeof(__m128i), remaining); @@ -966,7 +966,7 @@ json_object_i(VALUE key, VALUE val, VALUE _arg) FBuffer *buffer = data->buffer; JSON_Generator_State *state = data->state; - long depth = data->depth; + size_t depth = data->depth; int key_type = rb_type(key); if (arg->first) { @@ -1040,11 +1040,11 @@ json_object_i(VALUE key, VALUE val, VALUE _arg) return ST_CONTINUE; } -static inline long increase_depth(struct generate_json_data *data) +static inline size_t increase_depth(struct generate_json_data *data) { JSON_Generator_State *state = data->state; if (RB_UNLIKELY(data->depth >= state->max_nesting && state->max_nesting)) { - rb_raise(eNestingError, "nesting of %ld is too deep. Did you try to serialize objects with circular references?", data->depth + 1); + rb_raise(eNestingError, "nesting of %"PRIuSIZE" is too deep. Did you try to serialize objects with circular references?", data->depth + 1); } return ++data->depth; } @@ -1060,7 +1060,7 @@ static void generate_json_object(FBuffer *buffer, struct generate_json_data *dat Check_Type(obj, T_HASH); } - long depth = increase_depth(data); + size_t depth = increase_depth(data); if (RHASH_SIZE(obj) == 0) { fbuffer_append(buffer, "{}", 2); @@ -1089,7 +1089,7 @@ static void generate_json_object(FBuffer *buffer, struct generate_json_data *dat static void generate_json_array(FBuffer *buffer, struct generate_json_data *data, VALUE obj) { - long depth = increase_depth(data); + size_t depth = increase_depth(data); if (RARRAY_LEN(obj) == 0) { fbuffer_append(buffer, "[]", 2); @@ -1639,26 +1639,31 @@ static VALUE cState_check_circular_p(VALUE self) static VALUE cState_max_nesting(VALUE self) { GET_STATE(self); - return LONG2FIX(state->max_nesting); + return SIZET2NUM(state->max_nesting); } -static long long_config(VALUE num) +static size_t max_nesting_config(VALUE num) { - return RTEST(num) ? NUM2LONG(num) : 0; + if (!RTEST(num)) return 0; + ssize_t max_nesting = NUM2SSIZET(num); + if (RB_UNLIKELY(max_nesting < 0)) { + rb_raise(rb_eArgError, "max_nesting must be >= 0 (got %"PRIdSIZE")", max_nesting); + } + return (size_t)max_nesting; } // depth must never be negative; reject early with a clear error. -static long depth_config(VALUE num) +static size_t depth_config(VALUE num) { if (!RTEST(num)) return 0; - long d = NUM2LONG(num); + ssize_t d = NUM2SSIZET(num); if (RB_UNLIKELY(d < 0)) { - rb_raise(rb_eArgError, "depth must be >= 0 (got %ld)", d); + rb_raise(rb_eArgError, "depth must be >= 0 (got %"PRIdSIZE")", d); } if (RB_UNLIKELY(d > INT_MAX)) { - rb_raise(rb_eArgError, "depth is too large (got %ld)", d); + rb_raise(rb_eArgError, "depth is too large (got %"PRIdSIZE")", d); } - return d; + return (size_t)d; } /* @@ -1671,7 +1676,7 @@ static VALUE cState_max_nesting_set(VALUE self, VALUE depth) { rb_check_frozen(self); GET_STATE(self); - state->max_nesting = long_config(depth); + state->max_nesting = max_nesting_config(depth); return Qnil; } @@ -1897,7 +1902,7 @@ static VALUE cState_allow_duplicate_key_p(VALUE self) static VALUE cState_depth(VALUE self) { GET_STATE(self); - return LONG2FIX(state->depth); + return SIZET2NUM(state->depth); } /* @@ -1921,15 +1926,15 @@ static VALUE cState_depth_set(VALUE self, VALUE depth) static VALUE cState_buffer_initial_length(VALUE self) { GET_STATE(self); - return LONG2FIX(state->buffer_initial_length); + return SIZET2NUM(state->buffer_initial_length); } static void buffer_initial_length_set(JSON_Generator_State *state, VALUE buffer_initial_length) { Check_Type(buffer_initial_length, T_FIXNUM); - long initial_length = FIX2LONG(buffer_initial_length); + ssize_t initial_length = NUM2SSIZET(buffer_initial_length); if (initial_length > 0) { - state->buffer_initial_length = initial_length; + state->buffer_initial_length = (size_t)initial_length; } } @@ -1972,7 +1977,7 @@ static int configure_state_i(VALUE key, VALUE val, VALUE _arg) else if (key == sym_space_before) { state_write_value(data, &state->space_before, string_config(val)); } else if (key == sym_object_nl) { state_write_value(data, &state->object_nl, string_config(val)); } else if (key == sym_array_nl) { state_write_value(data, &state->array_nl, string_config(val)); } - else if (key == sym_max_nesting) { state->max_nesting = long_config(val); } + else if (key == sym_max_nesting) { state->max_nesting = max_nesting_config(val); } else if (key == sym_allow_nan) { state->allow_nan = RTEST(val); } else if (key == sym_ascii_only) { state->ascii_only = RTEST(val); } else if (key == sym_depth) { state->depth = depth_config(val); } diff --git a/ext/json/ext/parser/parser.c b/ext/json/ext/parser/parser.c index b533c994..facd12a0 100644 --- a/ext/json/ext/parser/parser.c +++ b/ext/json/ext/parser/parser.c @@ -79,17 +79,17 @@ static rb_encoding *enc_utf8; #define JSON_RVALUE_CACHE_MAX_ENTRY_LENGTH 55 -static inline VALUE build_interned_string(const char *str, const rb_len_t length) +static inline VALUE build_interned_string(const char *str, const size_t length) { # ifdef HAVE_RB_ENC_INTERNED_STR - return rb_enc_interned_str(str, length, enc_utf8); + return rb_enc_interned_str(str, (rb_len_t)length, enc_utf8); # else - VALUE rstring = rb_utf8_str_new(str, length); + VALUE rstring = rb_utf8_str_new(str, (rb_len_t)length); return rb_funcall(rb_str_freeze(rstring), i_uminus, 0); # endif } -static inline VALUE build_symbol(const char *str, const rb_len_t length) +static inline VALUE build_symbol(const char *str, const size_t length) { return rb_str_intern(build_interned_string(str, length)); } @@ -106,12 +106,12 @@ static void rvalue_cache_insert_at(rvalue_cache *cache, int index, VALUE rstring #if JSON_CPU_LITTLE_ENDIAN_64BITS #if __has_builtin(__builtin_bswap64) #undef rstring_cache_memcmp -ALWAYS_INLINE(static) int rstring_cache_memcmp(const char *str, const char *rptr, const long length) +ALWAYS_INLINE(static) int rstring_cache_memcmp(const char *str, const char *rptr, const size_t length) { // The libc memcmp has numerous complex optimizations, but in this particular case, // we know the string is small (JSON_RVALUE_CACHE_MAX_ENTRY_LENGTH), so being able to // inline a simpler memcmp outperforms calling the libc version. - long i = 0; + size_t i = 0; for (; i + 8 <= length; i += 8) { uint64_t a, b; @@ -135,21 +135,21 @@ ALWAYS_INLINE(static) int rstring_cache_memcmp(const char *str, const char *rptr #endif #endif -ALWAYS_INLINE(static) int rstring_cache_cmp(const char *str, const long length, VALUE rstring) +ALWAYS_INLINE(static) int rstring_cache_cmp(const char *str, const size_t length, VALUE rstring) { const char *rstring_ptr; rb_len_t rstring_length; RSTRING_GETMEM(rstring, rstring_ptr, rstring_length); - if (length == rstring_length) { + if (length == (size_t)rstring_length) { return rstring_cache_memcmp(str, rstring_ptr, length); } else { - return (int)(length - rstring_length); + return length < (size_t)rstring_length ? -1 : 1; } } -ALWAYS_INLINE(static) VALUE rstring_cache_fetch(rvalue_cache *cache, const char *str, const long length) +ALWAYS_INLINE(static) VALUE rstring_cache_fetch(rvalue_cache *cache, const char *str, const size_t length) { int low = 0; int high = cache->length - 1; @@ -176,7 +176,7 @@ ALWAYS_INLINE(static) VALUE rstring_cache_fetch(rvalue_cache *cache, const char return rstring; } -static VALUE rsymbol_cache_fetch(rvalue_cache *cache, const char *str, const long length) +static VALUE rsymbol_cache_fetch(rvalue_cache *cache, const char *str, const size_t length) { int low = 0; int high = cache->length - 1; @@ -214,8 +214,8 @@ enum rvalue_stack_type { typedef struct rvalue_stack_struct { enum rvalue_stack_type type; - long capa; - long head; + size_t capa; + size_t head; VALUE *ptr; } rvalue_stack; @@ -223,7 +223,7 @@ static rvalue_stack *rvalue_stack_spill(rvalue_stack *old_stack, VALUE *handle, static rvalue_stack *rvalue_stack_grow(rvalue_stack *stack, VALUE *handle, rvalue_stack **stack_ref) { - long required = stack->capa ? stack->capa * 2 : RVALUE_STACK_INITIAL_CAPA; + size_t required = stack->capa ? stack->capa * 2 : RVALUE_STACK_INITIAL_CAPA; if (stack->type == RVALUE_STACK_STACK_ALLOCATED) { stack = rvalue_stack_spill(stack, handle, stack_ref); @@ -248,12 +248,12 @@ static VALUE rvalue_stack_push(rvalue_stack *stack, VALUE value, VALUE *handle, return value; } -static inline VALUE *rvalue_stack_peek(rvalue_stack *stack, long count) +static inline VALUE *rvalue_stack_peek(rvalue_stack *stack, size_t count) { return stack->ptr + (stack->head - count); } -static inline void rvalue_stack_pop(rvalue_stack *stack, long count) +static inline void rvalue_stack_pop(rvalue_stack *stack, size_t count) { stack->head -= count; } @@ -261,7 +261,7 @@ static inline void rvalue_stack_pop(rvalue_stack *stack, long count) static void rvalue_stack_mark(void *ptr) { rvalue_stack *stack = (rvalue_stack *)ptr; - long index; + size_t index; if (stack && stack->ptr) { for (index = 0; index < stack->head; index++) { rb_gc_mark_movable(stack->ptr[index]); @@ -299,7 +299,7 @@ static size_t rvalue_stack_memsize(const void *ptr) static void rvalue_stack_compact(void *ptr) { rvalue_stack *stack = (rvalue_stack *)ptr; - long index; + size_t index; if (stack && stack->ptr) { for (index = 0; index < stack->head; index++) { stack->ptr[index] = rb_gc_location(stack->ptr[index]); @@ -395,14 +395,14 @@ enum json_frame_phase { typedef struct json_frame_struct { enum json_frame_type type; enum json_frame_phase phase; - long value_stack_head; // rvalue_stack->head when this container opened + size_t value_stack_head; // rvalue_stack->head when this container opened size_t start_offset; // object frames only (the '{'); NULL otherwise } json_frame; typedef struct json_frame_stack_struct { enum rvalue_stack_type type; // shared with rvalue_stack: is ptr stack- or heap-allocated - long capa; - long head; + size_t capa; + size_t head; json_frame *ptr; } json_frame_stack; @@ -410,7 +410,7 @@ typedef struct JSON_ParserStruct { VALUE on_load_proc; VALUE decimal_class; ID decimal_method_id; - int max_nesting; + size_t max_nesting; bool allow_comments; bool allow_duplicate_key; bool allow_nan; @@ -430,8 +430,8 @@ typedef struct JSON_ParserStateStruct { rvalue_stack *value_stack; json_frame_stack *frames; rvalue_cache name_cache; - int in_array; - int current_nesting; + size_t in_array; + size_t current_nesting; VALUE parser; } JSON_ParserState; @@ -439,7 +439,7 @@ static json_frame_stack *json_frame_stack_spill(json_frame_stack *old_stack, VAL static json_frame_stack *json_frame_stack_grow(json_frame_stack *stack, VALUE *handle, json_frame_stack **stack_ref) { - long required = stack->capa ? stack->capa * 2 : JSON_FRAME_STACK_INITIAL_CAPA; + size_t required = stack->capa ? stack->capa * 2 : JSON_FRAME_STACK_INITIAL_CAPA; if (stack->type == RVALUE_STACK_STACK_ALLOCATED) { stack = json_frame_stack_spill(stack, handle, stack_ref); @@ -583,7 +583,7 @@ static inline char peek(JSON_ParserState *state) return *state->cursor; } -static void cursor_position(JSON_ParserState *state, long *line_out, rb_len_t *column_out) +static void cursor_position(JSON_ParserState *state, size_t *line_out, rb_len_t *column_out) { JSON_ASSERT(!state->parser); JSON_ASSERT(state->cursor); @@ -595,7 +595,7 @@ static void cursor_position(JSON_ParserState *state, long *line_out, rb_len_t *c } const char *cursor = state->cursor; - long line = 1; + size_t line = 1; while (cursor > state->start && cursor[-1] != '\n') { cursor--; @@ -655,15 +655,15 @@ static VALUE json_path_new(JSON_ParserState *state, VALUE duplicate_key) json_frame_stack *frames = state->frames; rvalue_stack *values = state->value_stack; - for (long depth = 1; depth < frames->head; depth++) { + for (size_t depth = 1; depth < frames->head; depth++) { json_frame *frame = &frames->ptr[depth]; bool innermost = depth == frames->head - 1; - long child_head = innermost ? values->head : frames->ptr[depth + 1].value_stack_head; - long count = child_head - frame->value_stack_head; + size_t child_head = innermost ? values->head : frames->ptr[depth + 1].value_stack_head; + size_t count = child_head - frame->value_stack_head; if (frame->type == JSON_FRAME_ARRAY) { - rb_ary_push(path, LONG2NUM(frame->phase == JSON_PHASE_ARRAY_COMMA ? count - 1 : count)); + rb_ary_push(path, SIZET2NUM(frame->phase == JSON_PHASE_ARRAY_COMMA ? count - 1 : count)); } else if (innermost && !UNDEF_P(duplicate_key)) { rb_ary_push(path, duplicate_key); } else if (count & 1) { @@ -678,10 +678,10 @@ static VALUE json_path_new(JSON_ParserState *state, VALUE duplicate_key) return path; } -static VALUE parse_error_new(JSON_ParserState *state, VALUE message, long line, rb_len_t column, bool eos) +static VALUE parse_error_new(JSON_ParserState *state, VALUE message, size_t line, rb_len_t column, bool eos) { VALUE exc = rb_exc_new_str(eParserError, message); - rb_ivar_set(exc, i_at_line, LONG2NUM(line)); + rb_ivar_set(exc, i_at_line, SIZET2NUM(line)); rb_ivar_set(exc, i_at_column, LEN2NUM(column)); rb_ivar_set(exc, i_at_json_path, json_path_new(state, Qundef)); return exc; @@ -700,10 +700,10 @@ NORETURN(static) void raise_parse_error(const char *format, JSON_ParserState *st } } else { VALUE message = build_parse_error_message(format, state); - long line; + size_t line; rb_len_t column; cursor_position(state, &line, &column); - rb_str_catf(message, " at line %ld column %"PRIdLEN, line, column); + rb_str_catf(message, " at line %"PRIuSIZE" column %"PRIdLEN, line, column); rb_exc_raise(parse_error_new(state, message, line, column, eos)); } } @@ -944,9 +944,9 @@ static inline VALUE json_string_fastpath(JSON_ParserState *state, JSON_ParserCon #define JSON_MAX_UNESCAPE_POSITIONS 16 typedef struct _json_unescape_positions { - long size; + size_t size; const char **positions; - unsigned long additional_backslashes; + size_t additional_backslashes; } JSON_UnescapePositions; static inline const char *json_next_backslash(const char *pe, const char *stringEnd, JSON_UnescapePositions *positions) @@ -1194,7 +1194,7 @@ static inline VALUE json_decode_float(JSON_ParserConfig *config, uint64_t mantis return DBL2NUM(ffp_s2d(exponent, mantissa, negative)); } -static inline VALUE json_decode_array(JSON_ParserState *state, JSON_ParserConfig *config, long count) +static inline VALUE json_decode_array(JSON_ParserState *state, JSON_ParserConfig *config, size_t count) { VALUE array = rb_ary_new_from_values(count, rvalue_stack_peek(state->value_stack, count)); rvalue_stack_pop(state->value_stack, count); @@ -1235,10 +1235,10 @@ NORETURN(static) void raise_duplicate_key_error(JSON_ParserState *state, VALUE d if (state->parser) { // line and columns can't be accurate in resumable exc = parse_error_new(state, message, 0, 0, false); } else { - long line; + size_t line; rb_len_t column; cursor_position(state, &line, &column); - rb_str_catf(message, " at line %ld column %"PRIdLEN, line, column); + rb_str_catf(message, " at line %"PRIuSIZE" column %"PRIdLEN, line, column); exc = parse_error_new(state, message, line, column, false); } rb_ivar_set(exc, i_at_json_path, json_path_new(state, duplicate_key)); @@ -1548,7 +1548,7 @@ static inline VALUE json_parse_number(JSON_ParserState *state, JSON_ParserConfig // How many values (array elements, or interleaved object keys+values) have been // pushed onto the rvalue stack since this container opened. Used to size the // bulk decode on close, and to tell the first key/colon from later ones. -static inline long json_frame_entry_count(const json_frame *frame, const rvalue_stack *value_stack) +static inline size_t json_frame_entry_count(const json_frame *frame, const rvalue_stack *value_stack) { return value_stack->head - frame->value_stack_head; } @@ -1728,7 +1728,7 @@ ALWAYS_INLINE(static) bool json_parse_any(JSON_ParserState *state, JSON_ParserCo state->current_nesting++; if (RB_UNLIKELY(config->max_nesting && (config->max_nesting < state->current_nesting))) { - rb_raise(eNestingError, "nesting of %d is too deep", state->current_nesting); + rb_raise(eNestingError, "nesting of %"PRIuSIZE" is too deep", state->current_nesting); } state->in_array++; @@ -1757,7 +1757,7 @@ ALWAYS_INLINE(static) bool json_parse_any(JSON_ParserState *state, JSON_ParserCo state->current_nesting++; if (RB_UNLIKELY(config->max_nesting && (config->max_nesting < state->current_nesting))) { - rb_raise(eNestingError, "nesting of %d is too deep", state->current_nesting); + rb_raise(eNestingError, "nesting of %"PRIuSIZE" is too deep", state->current_nesting); } // Phase KEY: the next iteration reads the first key. @@ -1879,7 +1879,7 @@ ALWAYS_INLINE(static) bool json_parse_any(JSON_ParserState *state, JSON_ParserCo goto JSON_PHASE_VALUE; } else if (next_char == ']') { state->cursor++; - long count = json_frame_entry_count(frame, state->value_stack); + size_t count = json_frame_entry_count(frame, state->value_stack); state->current_nesting--; state->in_array--; @@ -2006,13 +2006,23 @@ static void parser_config_wb_write(VALUE self, VALUE *dest, VALUE val) if (self) RB_OBJ_WRITTEN(self, Qundef, val); } +static size_t max_nesting_config(VALUE num) +{ + if (!RTEST(num)) return 0; + ssize_t max_nesting = NUM2SSIZET(num); + if (RB_UNLIKELY(max_nesting < 0)) { + rb_raise(rb_eArgError, "max_nesting must be >= 0 (got %"PRIdSIZE")", max_nesting); + } + return (size_t)max_nesting; +} + static int parser_config_init_i(VALUE key, VALUE val, VALUE data) { struct parser_config_init_args *args = (struct parser_config_init_args *)data; JSON_ParserConfig *config = args->config; VALUE self = args->self; - if (key == sym_max_nesting) { config->max_nesting = RTEST(val) ? FIX2INT(val) : 0; } + if (key == sym_max_nesting) { config->max_nesting = max_nesting_config(val); } else if (key == sym_allow_nan) { config->allow_nan = RTEST(val); } else if (key == sym_allow_trailing_comma) { config->allow_trailing_comma = RTEST(val); } else if (key == sym_allow_comments) { config->allow_comments = RTEST(val); } @@ -2671,10 +2681,8 @@ static VALUE cResumableParser_partial_value_body(VALUE self) } json_frame *frame = json_frame_stack_peek(parser.state.frames); - long missing_object_value = 0; - if (frame->type == JSON_FRAME_OBJECT && (frame->phase == JSON_PHASE_VALUE || frame->phase == JSON_PHASE_OBJECT_COLON)) { - missing_object_value = 1; - } + bool missing_object_value = frame->type == JSON_FRAME_OBJECT && + (frame->phase == JSON_PHASE_VALUE || frame->phase == JSON_PHASE_OBJECT_COLON); // Copy the value stack as we need to mutate it. The collapse loop folds each // open container by popping its entries and pushing the single result, so a @@ -2682,7 +2690,7 @@ static VALUE cResumableParser_partial_value_body(VALUE self) // most one, either for the missing-value placeholder pushed below or for the // result of folding an empty innermost container. That one spare slot keeps // rvalue_stack_push from growing (reallocating) this ALLOCV buffer. - long capa = parser.value_stack.head; + size_t capa = parser.value_stack.head; parser.value_stack.capa = capa + 1; VALUE tmpbuf, *value_stack_buffer = ALLOCV_N(VALUE, tmpbuf, parser.value_stack.capa); MEMCPY(value_stack_buffer, parser.value_stack.ptr, VALUE, capa); @@ -2707,7 +2715,7 @@ static VALUE cResumableParser_partial_value_body(VALUE self) } case JSON_FRAME_ARRAY: { - long count = json_frame_entry_count(frame, state->value_stack); + size_t count = json_frame_entry_count(frame, state->value_stack); json_push_value(state, config, json_decode_array(state, config, count)); json_frame_stack_pop(state->frames); @@ -2715,7 +2723,7 @@ static VALUE cResumableParser_partial_value_body(VALUE self) } case JSON_FRAME_OBJECT: { - long count = json_frame_entry_count(frame, state->value_stack); + size_t count = json_frame_entry_count(frame, state->value_stack); json_push_value(state, config, json_decode_object(state, config, count)); json_frame_stack_pop(state->frames); break; diff --git a/java/src/json/ext/Generator.java b/java/src/json/ext/Generator.java index 4f3ae479..96d58a2e 100644 --- a/java/src/json/ext/Generator.java +++ b/java/src/json/ext/Generator.java @@ -58,7 +58,7 @@ static RubyString generateJson(ThreadContext context, T .forGeneration(context); Session session = new Session(state); state.validateRfc8785(context); - int depth = state.depth; + long depth = state.depth; try { return handler.generateNew(context, session, object); } finally { @@ -90,7 +90,7 @@ static RubyString generateJson(ThreadContext context, T GeneratorState state = config.forGeneration(context); Session session = new Session(state); state.validateRfc8785(context); - int depth = state.depth; + long depth = state.depth; try { Handler handler = getHandlerFor(context.runtime, object); @@ -449,12 +449,12 @@ private static class ArrayHandler extends Handler> { @Override int guessSize(ThreadContext context, Session session, RubyArray object) { GeneratorState state = session.getState(context); - int depth = state.getDepth(); - int perItem = + long depth = state.getDepth(); + long perItem = 4 // prealloc + (depth + 1) * state.getIndent().length() // indent + 1 + state.getArrayNl().length(); // ',' arrayNl - return 2 + object.size() * perItem; + return (int) Math.min(2 + object.size() * perItem, Integer.MAX_VALUE); } @Override @@ -465,7 +465,7 @@ void generate(ThreadContext context, Session session, RubyArray obj static void generateArray(ThreadContext context, Session session, RubyArray object, OutputStream buffer) throws IOException { GeneratorState state = session.getState(context); - int depth = state.increaseDepth(context); + long depth = state.increaseDepth(context); if (object.isEmpty()) { buffer.write(EMPTY_ARRAY_BYTES); @@ -510,12 +510,12 @@ private static class HashHandler extends Handler { @Override int guessSize(ThreadContext context, Session session, RubyHash object) { GeneratorState state = session.getState(context); - int perItem = + long perItem = 12 // key, colon, comma + (state.getDepth() + 1) * state.getIndent().length() + state.getSpaceBefore().length() + state.getSpace().length(); - return 2 + object.size() * perItem; + return (int) Math.min(2 + object.size() * perItem, Integer.MAX_VALUE); } @Override @@ -581,7 +581,7 @@ private void report(ThreadContext context, Session session) { static void generateHash(ThreadContext context, Session session, RubyHash object, OutputStream buffer) throws IOException { final GeneratorState state = session.getState(context); - final int depth = state.increaseDepth(context); + final long depth = state.increaseDepth(context); if (object.isEmpty()) { buffer.write(EMPTY_HASH_BYTES); @@ -598,7 +598,7 @@ static void generateHash(ThreadContext context, Session session, RubyHash object final ByteList objectNl = state.getObjectNl(); byte[] objectNLBytes = objectNl.unsafeBytes(); - final byte[] indent = Utils.repeat(state.getIndent(), depth); + final byte[] indent = Utils.repeat(state.getIndent(), Math.toIntExact(depth)); final ByteList spaceBefore = state.getSpaceBefore(); final ByteList space = state.getSpace(); @@ -616,7 +616,7 @@ static void generateHash(ThreadContext context, Session session, RubyHash object processEntry(context, session, buffer, entry, firstPair, objectNl, indent, spaceBefore, space); firstPair = false; } - int oldDepth = state.decreaseDepth(); + long oldDepth = state.decreaseDepth(); if (!firstPair && !objectNl.isEmpty()) { buffer.write(objectNLBytes); } @@ -837,7 +837,7 @@ static RubyString generateGenericNew(ThreadContext context, Session session, IRu } throw Utils.buildGeneratorError(context, object, object + " not allowed in JSON").toThrowable(); } else if (object.respondsTo("to_json")) { - int depth = state.depth; + long depth = state.depth; IRubyObject result; try { result = object.callMethod(context, "to_json", state); diff --git a/java/src/json/ext/GeneratorState.java b/java/src/json/ext/GeneratorState.java index 3fec3d24..723bc87a 100644 --- a/java/src/json/ext/GeneratorState.java +++ b/java/src/json/ext/GeneratorState.java @@ -72,7 +72,7 @@ public class GeneratorState extends RubyObject { * The maximum level of nesting of structures allowed. * 0 means disabled. */ - private int maxNesting = DEFAULT_MAX_NESTING; + private long maxNesting = DEFAULT_MAX_NESTING; static final int DEFAULT_MAX_NESTING = 100; /** * Whether special float values (NaN, Infinity, @@ -104,7 +104,7 @@ public class GeneratorState extends RubyObject { * The initial buffer length of this state. (This isn't really used on all * non-C implementations.) */ - private int bufferInitialLength = DEFAULT_BUFFER_INITIAL_LENGTH; + private long bufferInitialLength = DEFAULT_BUFFER_INITIAL_LENGTH; static final int DEFAULT_BUFFER_INITIAL_LENGTH = 1024; /** @@ -119,7 +119,7 @@ public class GeneratorState extends RubyObject { /** * The current depth (inside a #to_json call) */ - protected int depth = 0; + protected long depth = 0; static final ObjectAllocator ALLOCATOR = GeneratorState::new; @@ -401,9 +401,13 @@ public RubyInteger max_nesting_get(ThreadContext context) { } @JRubyMethod(name="max_nesting=") - public IRubyObject max_nesting_set(IRubyObject max_nesting) { + public IRubyObject max_nesting_set(ThreadContext context, IRubyObject max_nesting) { checkFrozen(); - maxNesting = RubyNumeric.fix2int(max_nesting); + long value = RubyNumeric.num2long(max_nesting); + if (value < 0) { + throw context.runtime.newArgumentError("max_nesting must be >= 0 (got: " + value + ")"); + } + maxNesting = value; return max_nesting; } @@ -493,7 +497,7 @@ public RubyInteger buffer_initial_length_get(ThreadContext context) { @JRubyMethod(name="buffer_initial_length=") public IRubyObject buffer_initial_length_set(IRubyObject buffer_initial_length) { checkFrozen(); - int newLength = RubyNumeric.fix2int(buffer_initial_length); + long newLength = RubyNumeric.num2long(buffer_initial_length); if (newLength > 0) bufferInitialLength = newLength; return buffer_initial_length; } @@ -542,7 +546,7 @@ public void validateRfc8785(ThreadContext context) { } } - public int getDepth() { + public long getDepth() { return depth; } @@ -554,10 +558,7 @@ public RubyInteger depth_get(ThreadContext context) { @JRubyMethod(name="depth=") public IRubyObject depth_set(ThreadContext context, IRubyObject vDepth) { checkFrozen(); - depth = RubyNumeric.fix2int(vDepth); - if (depth < 0) { - throw context.runtime.newArgumentError("depth must be >= 0 (got: " + depth + ")"); - } + depth = checkDepth(context, RubyNumeric.num2long(vDepth)); return vDepth; } @@ -602,17 +603,17 @@ public IRubyObject _configure(ThreadContext context, IRubyObject vOpts) { if (opts.hasKey("as_json")) this.asJSON = opts.getProc("as_json"); - maxNesting = opts.getInt("max_nesting", maxNesting); + maxNesting = opts.getLong("max_nesting", maxNesting); + if (maxNesting < 0) { + throw context.runtime.newArgumentError("max_nesting must be >= 0 (got: " + maxNesting + ")"); + } allowNaN = opts.getBool("allow_nan", allowNaN); asciiOnly = opts.getBool("ascii_only", asciiOnly); scriptSafe = opts.getBool("script_safe", scriptSafe); strict = opts.getBool("strict", strict); - bufferInitialLength = opts.getInt("buffer_initial_length", bufferInitialLength); + bufferInitialLength = opts.getLong("buffer_initial_length", bufferInitialLength); - depth = opts.getInt("depth", depth); - if (depth < 0) { - throw context.runtime.newArgumentError("depth must be >= 0 (got: " + depth + ")"); - } + depth = checkDepth(context, opts.getLong("depth", depth)); this.allowDuplicateKey = opts.getBool("allow_duplicate_key", allowDuplicateKey); if (opts.hasKey("sort_keys")) sortKeys = normalizeSortKeys(context, opts.get("sort_keys")); @@ -680,12 +681,22 @@ GeneratorState forGeneration(ThreadContext context) { return copy; } - public int increaseDepth(ThreadContext context) { + private static long checkDepth(ThreadContext context, long depth) { + if (depth < 0) { + throw context.runtime.newArgumentError("depth must be >= 0 (got: " + depth + ")"); + } + if (depth > Integer.MAX_VALUE) { + throw context.runtime.newArgumentError("depth is too large (got: " + depth + ")"); + } + return depth; + } + + public long increaseDepth(ThreadContext context) { checkMaxNesting(context); return ++depth; } - public int decreaseDepth() { + public long decreaseDepth() { return --depth; } diff --git a/java/src/json/ext/OptionsReader.java b/java/src/json/ext/OptionsReader.java index d93d3cd7..086ad437 100644 --- a/java/src/json/ext/OptionsReader.java +++ b/java/src/json/ext/OptionsReader.java @@ -92,6 +92,13 @@ int getInt(String key, int defaultValue) { return RubyNumeric.fix2int(value); } + long getLong(String key, long defaultValue) { + IRubyObject value = get(key); + if (value == null) return defaultValue; + if (!value.isTrue()) return 0; + return RubyNumeric.num2long(value); + } + /** * Reads the setting from the options hash. If no entry is set for this * key or if it evaluates to false, returns null; attempts to diff --git a/java/src/json/ext/Parser.java b/java/src/json/ext/Parser.java index eb5ce3a9..9319d6e1 100644 --- a/java/src/json/ext/Parser.java +++ b/java/src/json/ext/Parser.java @@ -44,7 +44,7 @@ */ public class Parser extends RubyObject { private final RuntimeInfo info; - private int maxNesting; + private long maxNesting; private boolean allowNaN; private boolean allowTrailingComma; private boolean allowComments; @@ -104,7 +104,10 @@ public IRubyObject initialize(ThreadContext context, IRubyObject options) { Ruby runtime = context.runtime; OptionsReader opts = new OptionsReader(context, options); - this.maxNesting = opts.getInt("max_nesting", DEFAULT_MAX_NESTING); + this.maxNesting = opts.getLong("max_nesting", DEFAULT_MAX_NESTING); + if (maxNesting < 0) { + throw runtime.newArgumentError("max_nesting must be >= 0 (got: " + maxNesting + ")"); + } this.allowNaN = opts.getBool("allow_nan", false); this.allowComments = opts.getBool("allow_comments", false); this.allowControlCharacters = opts.getBool("allow_control_characters", false); @@ -266,7 +269,7 @@ private static final class Frame { // Integer value accumulated by the most recent scanDigits() call. private long digitsValue; - private int currentNesting = 0; + private long currentNesting = 0; private int inArray = 0; diff --git a/java/src/json/ext/Utils.java b/java/src/json/ext/Utils.java index 38491d2e..646eafe8 100644 --- a/java/src/json/ext/Utils.java +++ b/java/src/json/ext/Utils.java @@ -96,12 +96,12 @@ static byte[] repeat(byte[] a, int begin, int length, int n) { return result; } - static void repeatWrite(OutputStream out, ByteList a, int n) throws IOException { + static void repeatWrite(OutputStream out, ByteList a, long n) throws IOException { byte[] bytes = a.unsafeBytes(); int begin = a.begin(); int length = a.length(); - for (int i = 0; i < n; i++) { + for (long i = 0; i < n; i++) { out.write(bytes, begin, length); } } diff --git a/lib/json/truffle_ruby/generator.rb b/lib/json/truffle_ruby/generator.rb index 04a36b02..7dd49b63 100644 --- a/lib/json/truffle_ruby/generator.rb +++ b/lib/json/truffle_ruby/generator.rb @@ -203,7 +203,15 @@ def as_json=(value) # This integer returns the maximum level of data structure nesting in # the generated JSON, max_nesting = 0 if no maximum is checked. - attr_accessor :max_nesting + attr_reader :max_nesting + + def max_nesting=(max_nesting) + max_nesting ||= 0 + if max_nesting.negative? + raise ArgumentError, "max_nesting must be >= 0 (got #{max_nesting})" + end + @max_nesting = max_nesting + end # If this attribute is set to true, forward slashes will be escaped in # all json strings. @@ -352,6 +360,10 @@ def configure(options) raise TypeError, ":max_nesting must be `false` or an Integer, got: #{max_nesting.class}" end + if max_nesting && max_nesting.negative? + raise ArgumentError, "max_nesting must be >= 0 (got #{max_nesting})" + end + @indent = indent || '' @space = space || '' @space_before = space_before || '' diff --git a/test/json/json_generator_test.rb b/test/json/json_generator_test.rb index 9e6cb9c3..9bb5e6cd 100755 --- a/test/json/json_generator_test.rb +++ b/test/json/json_generator_test.rb @@ -497,6 +497,23 @@ def test_depth assert_equal %({\n "foo": 42\n }), state.generate(foo: 42) end + def test_large_max_nesting + [2**62, 2**63 - 1].each do |value| + state = JSON::State.new + state.max_nesting = value + assert_equal value, state.max_nesting + assert_equal value, state.to_h[:max_nesting] + assert_equal value, JSON::State.new(max_nesting: value).max_nesting + end + end + + def test_negative_max_nesting + assert_raise(ArgumentError) { JSON::State.new.max_nesting = -1 } + assert_raise(ArgumentError) { JSON::State.new(max_nesting: -1) } + assert_raise(ArgumentError) { JSON::State.new.configure(max_nesting: -(2**63)) } + assert_raise(ArgumentError) { JSON.generate([], max_nesting: -1) } + end + def test_depth_nesting_error ary = []; ary << ary assert_raise(JSON::NestingError) { generate(ary) } diff --git a/test/json/json_parser_test.rb b/test/json/json_parser_test.rb index 39dd62f2..b81d9c0b 100644 --- a/test/json/json_parser_test.rb +++ b/test/json/json_parser_test.rb @@ -595,6 +595,9 @@ def test_nesting assert_equal too_deep_ary, ok ok = parse too_deep, max_nesting: 0 assert_equal too_deep_ary, ok + ok = parse too_deep, max_nesting: 2**62 + assert_equal too_deep_ary, ok + assert_raise(ArgumentError) { parse too_deep, max_nesting: -1 } end def test_backslash