From c4cb4164605db7aa76ed698e28eff3cf37e559d9 Mon Sep 17 00:00:00 2001 From: "Yukihiro \"Matz\" Matsumoto" Date: Mon, 25 Jul 2022 08:09:13 +0900 Subject: [PATCH] string.c: new configuration MRB_STR_LENGTH_MAX. The default value is 1MB. If you want to avoid the limitation, set this value to 0. --- include/mrbconf.h | 5 +++++ src/string.c | 19 +++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/include/mrbconf.h b/include/mrbconf.h index e11a55e8c..77618ce25 100644 --- a/include/mrbconf.h +++ b/include/mrbconf.h @@ -107,6 +107,11 @@ /* string class to handle UTF-8 encoding */ //#define MRB_UTF8_STRING +/* maximum length of strings */ +/* the default value is 1MB */ +/* set this value to zero to skip the check */ +//#define MRB_STR_LENGTH_MAX 1048576 + /* argv max size in mrb_funcall */ //#define MRB_FUNCALL_ARGC_MAX 16 diff --git a/src/string.c b/src/string.c index 2b01535d9..eaa8ffbbc 100644 --- a/src/string.c +++ b/src/string.c @@ -28,10 +28,28 @@ const char mrb_digitmap[] = "0123456789abcdefghijklmnopqrstuvwxyz"; #define mrb_obj_alloc_string(mrb) MRB_OBJ_ALLOC((mrb), MRB_TT_STRING, (mrb)->string_class) +#ifndef MRB_STR_LENGTH_MAX +#define MRB_STR_LENGTH_MAX 1048576 +#endif + +static void +str_check_too_big(mrb_state *mrb, mrb_int len) +{ + if (len < 0) { + mrb_raise(mrb, E_ARGUMENT_ERROR, "[BUG] negative string length"); + } +#if MRB_STR_LENGTH_MAX != 0 + if (len > MRB_STR_LENGTH_MAX-1) { + mrb_raisef(mrb, E_ARGUMENT_ERROR, "string too long (len=%i max=" MRB_STRINGIZE(MRB_STR_LENGTH_MAX) ")", len); + } +#endif +} + static struct RString* str_init_normal_capa(mrb_state *mrb, struct RString *s, const char *p, mrb_int len, mrb_int capa) { + str_check_too_big(mrb, capa); char *dst = (char *)mrb_malloc(mrb, capa + 1); if (p) memcpy(dst, p, len); dst[len] = '\0'; @@ -150,6 +168,7 @@ resize_capa(mrb_state *mrb, struct RString *s, mrb_int capacity) } } else { + str_check_too_big(mrb, capacity); s->as.heap.ptr = (char*)mrb_realloc(mrb, RSTR_PTR(s), capacity+1); s->as.heap.aux.capa = (mrb_ssize)capacity; }