Files
node/test/addons/non-node-context/binding.cc
Anna Henningsen 9c7d19104d buffer: throw exception when creating from non-Node.js Context
Throw an exception instead of crashing when attempting to create
`Buffer` objects from a Context that is not associated with
a Node.js `Environment`.

Possible alternatives for the future might be just returning
a plain `Uint8Array`, or working on providing `Buffer` for all
`Context`s.

PR-URL: https://github.com/nodejs/node/pull/23938
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Daniel Bevenius <daniel.bevenius@gmail.com>
2018-11-03 23:31:03 -07:00

63 lines
1.7 KiB
C++

#include <node.h>
#include <node_buffer.h>
#include <assert.h>
namespace {
using v8::Context;
using v8::Function;
using v8::FunctionTemplate;
using v8::Isolate;
using v8::Local;
using v8::MaybeLocal;
using v8::NewStringType;
using v8::Object;
using v8::Script;
using v8::String;
using v8::Value;
inline void MakeBufferInNewContext(
const v8::FunctionCallbackInfo<v8::Value>& args) {
Isolate* isolate = args.GetIsolate();
Local<Context> context = Context::New(isolate);
Context::Scope context_scope(context);
// This should throw an exception, rather than actually do anything.
MaybeLocal<Object> buf = node::Buffer::Copy(isolate, "foo", 3);
assert(buf.IsEmpty());
}
inline void RunInNewContext(
const v8::FunctionCallbackInfo<v8::Value>& args) {
Isolate* isolate = args.GetIsolate();
Local<Context> context = Context::New(isolate);
Context::Scope context_scope(context);
context->Global()->Set(
context,
String::NewFromUtf8(isolate, "data", NewStringType::kNormal)
.ToLocalChecked(),
args[1]).FromJust();
assert(args[0]->IsString()); // source code
Local<Script> script;
Local<Value> ret;
if (!Script::Compile(context, args[0].As<String>()).ToLocal(&script) ||
!script->Run(context).ToLocal(&ret)) {
return;
}
args.GetReturnValue().Set(ret);
}
inline void Initialize(Local<Object> exports,
Local<Value> module,
Local<Context> context) {
NODE_SET_METHOD(exports, "runInNewContext", RunInNewContext);
NODE_SET_METHOD(exports, "makeBufferInNewContext", MakeBufferInNewContext);
}
} // anonymous namespace
NODE_MODULE_CONTEXT_AWARE(NODE_GYP_MODULE_NAME, Initialize)