From 4d1347c928fd506e1f0add3ad058f9aaeecf3ee6 Mon Sep 17 00:00:00 2001 From: Matt Loring Date: Tue, 8 Mar 2016 11:15:01 -0800 Subject: [PATCH] buffer: throw range error before truncating write The check to determine whether `noAssert` was set to true and thus whether RangeErrors should be thrown was happening after the write was truncated to the available size of the buffer. These checks now occur in the correct order. Fixes: #5587 --- src/node_buffer.cc | 6 +++--- test/parallel/test-buffer.js | 10 ++++++++++ 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/node_buffer.cc b/src/node_buffer.cc index aecc6874d80c6d..a7729e9f2e8de6 100644 --- a/src/node_buffer.cc +++ b/src/node_buffer.cc @@ -794,14 +794,14 @@ void WriteFloatGeneric(const FunctionCallbackInfo& args) { size_t offset = args[2]->IntegerValue(env->context()).FromMaybe(0); size_t memcpy_num = sizeof(T); - if (offset + sizeof(T) > ts_obj_length) - memcpy_num = ts_obj_length - offset; if (should_assert) { CHECK_NOT_OOB(offset + memcpy_num >= memcpy_num); CHECK_NOT_OOB(offset + memcpy_num <= ts_obj_length); } - CHECK_LE(offset + memcpy_num, ts_obj_length); + + if (offset + memcpy_num > ts_obj_length) + memcpy_num = ts_obj_length - offset; union NoAlias { T val; diff --git a/test/parallel/test-buffer.js b/test/parallel/test-buffer.js index 8d42bea82d5e8c..c833a9b0c68c31 100644 --- a/test/parallel/test-buffer.js +++ b/test/parallel/test-buffer.js @@ -1041,6 +1041,16 @@ assert.throws(function() { new Buffer(0xFFFFFFFFF); }, RangeError); +// issue GH-5587 +assert.throws(function() { + var buf = new Buffer(8); + buf.writeFloatLE(0, 5); +}, RangeError); +assert.throws(function() { + var buf = new Buffer(16); + buf.writeDoubleLE(0, 9); +}, RangeError); + // attempt to overflow buffers, similar to previous bug in array buffers assert.throws(function() {