From 25053f92ffcefa7659ac8c7b1aa2d80986942c4f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bartek=20Iwa=C5=84czuk?= Date: Wed, 9 Sep 2020 20:52:11 +0200 Subject: [PATCH] fix(core): panic on big string allocation (#7395) Co-authored-by: Bert Belder --- core/bindings.rs | 19 ++++++++++++++++--- core/encode_decode_test.js | 11 +++++++++++ 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/core/bindings.rs b/core/bindings.rs index 0a755c2987..d0d916bdc4 100644 --- a/core/bindings.rs +++ b/core/bindings.rs @@ -673,9 +673,22 @@ fn decode( ) }; - let text_str = - v8::String::new_from_utf8(scope, &buf, v8::NewStringType::Normal).unwrap(); - rv.set(text_str.into()) + // If `String::new_from_utf8()` returns `None`, this means that the + // length of the decoded string would be longer than what V8 can + // handle. In this case we return `RangeError`. + // + // For more details see: + // - https://encoding.spec.whatwg.org/#dom-textdecoder-decode + // - https://github.com/denoland/deno/issues/6649 + // - https://github.com/v8/v8/blob/d68fb4733e39525f9ff0a9222107c02c28096e2a/include/v8.h#L3277-L3278 + match v8::String::new_from_utf8(scope, &buf, v8::NewStringType::Normal) { + Some(text) => rv.set(text.into()), + None => { + let msg = v8::String::new(scope, "string too long").unwrap(); + let exception = v8::Exception::range_error(scope, msg); + scope.throw_exception(exception); + } + }; } fn queue_microtask( diff --git a/core/encode_decode_test.js b/core/encode_decode_test.js index 69e6e053b0..bbb52252e0 100644 --- a/core/encode_decode_test.js +++ b/core/encode_decode_test.js @@ -41,6 +41,17 @@ function main() { assert(Deno.core.decode(new Uint8Array(fixture1)) === "𝓽𝓮𝔁𝓽"); assert(Deno.core.decode(new Uint8Array(fixture2)) === "Hello �� World"); + + // See https://github.com/denoland/deno/issues/6649 + let thrown = false; + try { + Deno.core.decode(new Uint8Array(2 ** 29)); + } catch (e) { + thrown = true; + assert(e instanceof RangeError); + assert(e.message === "string too long"); + } + assert(thrown); } main();