1

I am trying to create buffer in a .js file, and then passing that buffer to a c++ addon where I will call a Windows API.

In the c++ addon I have:

auto buf = node::Buffer::Data(args[0]);
auto len = node::Buffer::Length(args[0]);

Are there any guarantees that node::Buffers are null-terminated? Or does node::Buffer::Length have any other form of safety check to prevent an overrun?

seb35
  • 11
  • 1

1 Answers1

1

No. Think of buffers as a minimal data structure containing length and memory; they are not raw memory like what malloc() provides. A buffer is protected against memory overruns within a JavaScript context but not if you pass a pointer to the buffer memory to C/C++. And because a Buffer can be used to store binary data (as well as a string) it doesn't provide an extra byte to null-terminate a string; it doesn't "know" what is in the buffer.

I don't think the code you've posted will work; This post does a good job of explaining how to use buffers in C/C++: https://community.risingstack.com/using-buffers-node-js-c-plus-plus/

bmacnaughton
  • 4,950
  • 3
  • 27
  • 36
  • If I'm using node::Buffer::data or node::Buffer::length (as shown in the post that you linked to) and passing in those buffers to other APIs, should null characters be appended to the end of the buffers manually to prevent overflows? More context here: https://stackoverflow.com/questions/62821641/working-with-nodebuffers-in-c-node-addons – sgonzalez Jul 09 '20 at 22:10
  • 1
    no, you don't need to based on the code you posted. – bmacnaughton Jul 09 '20 at 22:23
  • Thanks for the response. Coming from higher level languages, I'm struggling to wrap my head around when buffers should be null terminated or not (or when other guarantees are needed to prevent overflows). In the case that I posted, I pass in two buffers to CryptProtectData. Buffer 1 contains the data, buffer 2 contains the length of the data. Since we are providing the length, no risk of overflow in buffer 1. But how does CryptProtectData know when to stop reading Buffer2 (since we have not provided null termination or length). Or am I completely misunderstanding? – sgonzalez Jul 09 '20 at 22:33
  • 1
    you are not passing in a buffer for CryptProtectData to output to. you're passing a data structure that it fills in with 1) a buffer it allocates and 2) the size in bytes of the data it wrote into that buffer. that's why you have to free it after you've copied the data to a javascript buffer. (accepting the answer i gave on that would be appreciated if it's right for you.) you only need to null terminate strings when working with older c-style apis. that's a high-level answer but directionally correct. most new apis have counts (and c++ strings keep counts). – bmacnaughton Jul 09 '20 at 22:38
  • 1
    Appreciate the explanation, makes sense. Accepted the answer on the other question. – sgonzalez Jul 09 '20 at 22:59