IBM / nodejs-idb-connector

A JavaScript (Node.js) library for communicating with Db2 for IBM i, with support for queries, procedures, and much more. Uses traditional callback-style syntax
MIT License
37 stars 23 forks source link

Buffer should be given a Finalizer #86

Closed markdirish closed 5 years ago

markdirish commented 5 years ago

Probably related to #26

https://github.com/IBM/nodejs-idb-connector/blob/6c9dfacbcf193628cdaa5ed82e035f4f03aab71e/src/db2ia/dbstmt.cc#L2078-L2081

I ran into an issue in odbc where data was being corrupted in my ArrayBuffer, and the same issue looks like it could potentially happen here as well:

Buffer stores a pointer, unlike Number or String, which internally store the data they point to. When the data pointed to by the Buffer is deleted, the Buffer will point to an area of memory that is no longer valid.

What needs to be done is the data in result[i][j].data should be copied to a new array, and then the Buffer should be passed a finalizerCallback that deletes the data when the Buffer is destroyed by the JavaScript garbage collection:

case SQL_VARBINARY :
case SQL_BINARY : 
case SQL_BLOB :
{
  SQLCHAR *binaryData = new SQLCHAR[result[i][j].rlength]; // have to save the data on the heap
  memcpy((SQLCHAR *) binaryData, result[i][j].data, result[i][j].rlength);
  value = Napi::Buffer::New(env, binaryData, result[i][j].rlength, [](Napi::Env env, void* finalizeData) {
    delete[] (SQLCHAR*)finalizeData;
  });
  break;
}
markdirish commented 5 years ago

I can probably fix this sometime today or this evening.