From b6f174cce76b4091da2be2fff3d550e63135920c Mon Sep 17 00:00:00 2001 From: Zoltan Herczeg Date: Thu, 11 Aug 2016 00:52:45 -0700 Subject: [PATCH] Gracefully throw an error when parser runs out of memory. JerryScript-DCO-1.0-Signed-off-by: Zoltan Herczeg zherczeg.u-szeged@partner.samsung.com --- jerry-core/parser/js/js-parser-mem.c | 5 ++-- jerry-core/parser/js/js-parser.c | 7 +++++ tests/jerry/parser-oom.js | 40 ++++++++++++++++++++++++++++ 3 files changed, 50 insertions(+), 2 deletions(-) create mode 100644 tests/jerry/parser-oom.js diff --git a/jerry-core/parser/js/js-parser-mem.c b/jerry-core/parser/js/js-parser-mem.c index 5f3b830a4..f8629de4a 100644 --- a/jerry-core/parser/js/js-parser-mem.c +++ b/jerry-core/parser/js/js-parser-mem.c @@ -39,8 +39,9 @@ parser_malloc (parser_context_t *context_p, /**< context */ void *result; JERRY_ASSERT (size > 0); - result = jmem_heap_alloc_block (size); - if (result == 0) + result = jmem_heap_alloc_block_null_on_error (size); + + if (result == NULL) { parser_raise_error (context_p, PARSER_ERR_OUT_OF_MEMORY); } diff --git a/jerry-core/parser/js/js-parser.c b/jerry-core/parser/js/js-parser.c index c112cbc7b..49f9d80aa 100644 --- a/jerry-core/parser/js/js-parser.c +++ b/jerry-core/parser/js/js-parser.c @@ -2241,6 +2241,13 @@ parser_parse_script (const uint8_t *source_p, /**< source code */ if (!*bytecode_data_p) { + if (parse_error.error == PARSER_ERR_OUT_OF_MEMORY) + { + /* It is unlikely that memory can be allocated in an out-of-memory + * situation. However, a simple value can still be thrown. */ + return ecma_make_error_value (ecma_make_simple_value (ECMA_SIMPLE_VALUE_NULL)); + } + return ecma_raise_syntax_error (parser_error_to_string (parse_error.error)); } diff --git a/tests/jerry/parser-oom.js b/tests/jerry/parser-oom.js new file mode 100644 index 000000000..1e5392898 --- /dev/null +++ b/tests/jerry/parser-oom.js @@ -0,0 +1,40 @@ +// Copyright 2016 Samsung Electronics Co., Ltd. +// Copyright 2016 University of Szeged. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/* String which is 32 bytes long. */ +var str = "1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+"; + +for (var i = 0; i < 10; i++) { + str = str + str; +} + +str = "(function() { return " + str + "1 })"; + +/* Eat memory. */ +var array = []; + +try +{ + for (var i = 0; i < 15; i++) + { + array[i] = eval(str); + } + assert (false); +} +catch (err) +{ + array = null; + assert (err === null); +}