forked from bnoordhuis/node-mmap
/
mmap.cc
65 lines (49 loc) · 1.75 KB
/
mmap.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <v8.h>
#include <node.h>
#include <node_buffer.h>
#include <errno.h>
#include <unistd.h>
#include <sys/mman.h>
namespace {
using namespace v8;
using namespace node;
void Unmap(char* data, void* hint) {
munmap(data, (size_t) hint);
}
Handle<Value> Map(const Arguments& args) {
HandleScope scope;
if (args.Length() <= 3) {
return ThrowException(Exception::Error(
String::New("Constructor takes 4 arguments: size, protection, flags, fd and offset.")));
}
const size_t size = args[0]->ToInteger()->Value();
const int protection = args[1]->ToInteger()->Value();
const int flags = args[2]->ToInteger()->Value();
const int fd = args[3]->ToInteger()->Value();
const off_t offset = args[4]->ToInteger()->Value();
char* data = (char *) mmap(
0, size, protection, flags, fd, offset);
if (data == MAP_FAILED) {
return ThrowException(
ErrnoException(errno, "mmap", ""));
}
else {
Buffer* buffer = Buffer::New(
data, size, Unmap, (void *) size);
return buffer->handle_;
}
}
extern "C" void init(Handle<Object> target) {
HandleScope scope;
const PropertyAttribute attribs = (PropertyAttribute) (ReadOnly | DontDelete);
target->Set(String::New("PROT_READ"), Integer::New(PROT_READ), attribs);
target->Set(String::New("PROT_WRITE"), Integer::New(PROT_WRITE), attribs);
target->Set(String::New("PROT_EXEC"), Integer::New(PROT_EXEC), attribs);
target->Set(String::New("PROT_NONE"), Integer::New(PROT_NONE), attribs);
target->Set(String::New("MAP_SHARED"), Integer::New(MAP_SHARED), attribs);
target->Set(String::New("MAP_PRIVATE"), Integer::New(MAP_PRIVATE), attribs);
target->Set(String::New("PAGESIZE"), Integer::New(sysconf(_SC_PAGESIZE)),
attribs);
target->Set(String::NewSymbol("map"), FunctionTemplate::New(Map)->GetFunction());
}
}