1 #include <node.h>
2 #include <node_buffer.h>
3 #include <v8.h>
4
5 #include <assert.h>
6
7 static int alive;
8 static char buf[1024];
9
FreeCallback(char * data,void * hint)10 static void FreeCallback(char* data, void* hint) {
11 alive--;
12 }
13
Alloc(const v8::FunctionCallbackInfo<v8::Value> & args)14 void Alloc(const v8::FunctionCallbackInfo<v8::Value>& args) {
15 v8::Isolate* isolate = args.GetIsolate();
16 alive++;
17
18 uintptr_t alignment = args[1].As<v8::Integer>()->Value();
19 uintptr_t offset = args[2].As<v8::Integer>()->Value();
20
21 uintptr_t static_offset = reinterpret_cast<uintptr_t>(buf) % alignment;
22 char* aligned = buf + (alignment - static_offset) + offset;
23
24 args.GetReturnValue().Set(node::Buffer::New(
25 isolate,
26 aligned,
27 args[0].As<v8::Integer>()->Value(),
28 FreeCallback,
29 nullptr).ToLocalChecked());
30 }
31
Check(const v8::FunctionCallbackInfo<v8::Value> & args)32 void Check(const v8::FunctionCallbackInfo<v8::Value>& args) {
33 v8::Isolate* isolate = args.GetIsolate();
34 isolate->RequestGarbageCollectionForTesting(
35 v8::Isolate::kFullGarbageCollection);
36 assert(alive > 0);
37 }
38
init(v8::Local<v8::Object> exports)39 void init(v8::Local<v8::Object> exports) {
40 NODE_SET_METHOD(exports, "alloc", Alloc);
41 NODE_SET_METHOD(exports, "check", Check);
42 }
43
44 NODE_MODULE(NODE_GYP_MODULE_NAME, init)
45