node-ffi-napi / ref-napi

Turn Buffer instances into "pointers"
MIT License
123 stars 67 forks source link

ReadPointer function can return nullptr #81

Open Hikai opened 1 year ago

Hikai commented 1 year ago
let i32 = {
    size: 4,
    indirection: 1,
    get: function get(buf, offset) {
        return buf['readInt32' + "LE"](offset || 0);
    },
    set: function set(buf, offset, val) {
        return buf['writeInt32' + "LE"](val, offset || 0);
    }
};
let PtrI32 = refType(i32);
var test_alloc = alloc(PtrI32);
var test_deref = test_alloc.deref()

// A segment fault occurs on the line below.
test_deref[0]; // or console.log(test_deref);

I edited ReadPointer function like as follows.

// binding.cc, Line 322
Value ReadPointer(const CallbackInfo& args) {
  Env env = args.Env();
  char* ptr = AddressForArgs(args);

  if (ptr == nullptr) {
    throw Error::New(env, "readPointer: Cannot read from nullptr pointer");
  }

  int64_t size = args[2].ToNumber();

  printf("ptr: %p\n", ptr);
  char* val = *reinterpret_cast<char**>(ptr);
  printf("val: %p\n", val);
  return WrapPointer(env, val, size);
}

Then, executed the node and got the result as follows.

ptr: 0000024B2112E8D0
val: 0000000000000002

I did not believe these results. So, some tests have been performed.

#include <iostream>

int main(void)
{
    char ptr[1024] = "";
    printf("ptr: %p\n", ptr);

    char* val = *reinterpret_cast<char**>(ptr);
    printf("val: %p\n", val);

}

Result:

ptr: 00CFF8FC
val: 00000000

I think need to patch a part of the ReadPointer function.