src: unify implementations of Utf8Value etc.

Unify the common code of `Utf8Value`, `TwoByteValue`, `BufferValue`
and `StringBytes::InlineDecoder` into one class. Always make the
result zero-terminated for the first three.

This fixes two problems in passing:

* When the conversion of the input value to String fails,
  make the buffer zero-terminated anyway. Previously, this would
  have resulted in possibly reading uninitialized data in multiple
  places in the code. An instance of that problem can be reproduced
  by running e.g.
  `valgrind node -e 'net.isIP({ toString() { throw Error() } })'`.
* Previously, `BufferValue` copied one byte too much from the source,
  possibly resulting in an out-of-bounds memory access.
  This can be reproduced by running e.g.
  `valgrind node -e \
    'fs.openSync(Buffer.from("node".repeat(8192)), "r")'`.

Further minor changes:
* This lifts the `out()` method of `StringBytes::InlineDecoder`
  to the common class so that it can be used when using the
  overloaded `operator*` does not seem appropiate.
* Hopefully clearer variable names.
* Add checks to make sure the length of the data does not exceed
  the allocated storage size, including the possible null terminator.

PR-URL: https://github.com/nodejs/node/pull/6357
Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Trevor Norris <trev.norris@gmail.com>
This commit is contained in:
Anna Henningsen committed 2016-04-29 15:40:50 +02:00
1 parent c8e137b1b5
commit 44a40325da
3 files changed
+135 -131

No files matched your search

+15 -29
View File
@@ -7,22 +7,14 @@
#include "node.h"
#include "env.h"
#include "env-inl.h"
#include "util.h"
namespace node {
class StringBytes {
public:
class InlineDecoder {
class InlineDecoder : public MaybeStackBuffer<char> {
public:
InlineDecoder() : out_(nullptr) {
}
~InlineDecoder() {
if (out_ != out_st_)
delete[] out_;
out_ = nullptr;
}
inline bool Decode(Environment* env,
v8::Local<v8::String> string,
v8::Local<v8::Value> encoding,
@@ -33,28 +25,22 @@ class StringBytes {
return false;
}
size_t buflen = StringBytes::StorageSize(env->isolate(), string, enc);
if (buflen > sizeof(out_st_))
out_ = new char[buflen];
else
out_ = out_st_;
size_ = StringBytes::Write(env->isolate(),
out_,
buflen,
string,
enc);
const size_t storage = StringBytes::StorageSize(env->isolate(),
string,
enc);
AllocateSufficientStorage(storage);
const size_t length = StringBytes::Write(env->isolate(),
out(),
storage,
string,
enc);
// No zero terminator is included when using this method.
SetLength(length);
return true;
}
inline const char* out() const { return out_; }
inline size_t size() const { return size_; }
private:
static const int kStorageSize = 1024;
char out_st_[kStorageSize];
char* out_;
size_t size_;
inline size_t size() const { return length(); }
};
// Does the string match the encoding? Quick but non-exhaustive.