hermes icon indicating copy to clipboard operation
hermes copied to clipboard

Semantics of evaluateJavaScript/prepareJavaScript Buffer argument

Open tudorms opened this issue 6 years ago • 3 comments

Hi,

The evaluateJavaScript and prepareJavaScript functions get a jsi::Buffer as a shared_ptr. Most users (such as react-native or test code) pass in a unique_ptr.

My question is what are the expectations around the lifetime of the Buffer object after the functions finish executing. Is the Hermes runtime ever keeping the Buffer refcount up (keeping it alive) after the functions return? It doesn't look like that is the case today but the shape of the API is unclear.

If the expectation is that the functions use the Buffer to parse / compile the JS / byte code and don't keep it around can that be documented or -better yet- can the API shape be changed to take a const Buffer& or const Buffer* or const char* (since nulltermination is a requirement in createBCProviderFromSrc)?

Thank you!

tudorms avatar Apr 24 '20 23:04 tudorms

The Buffer object may be kept alive until no references to the compiled function exist and the function has been garbage collected, which may be long after the function has returned. Even after the function returns, there may still be references to it, and even if there aren't, there may be an indeterminate amount of time before the GC runs and collects it.

This is necessary because at runtime Hermes relies on lazy compilation - functions are only compiled the first time they are invoked, and in general there is no guarantee when that may happen, so we must keep the source around.

Note that we recommend that prepareJavaScript() and evaluateJavaScript() from source should be avoided if possible in release builds, except perhaps for small functions. While we do support runtime compilation, it is relatively expensive.

tmikov avatar Apr 25 '20 01:04 tmikov

In addition to what @tmikov has said, evaluateJavaScript() can also be passed Hermes bytecode. The engine evaluates bytecode in place from the provided buffer, so it must remain valid until it is no longer possible to evaluate such code. There are other references from inside Hermes state, too, such as to literal strings in the bytecode file's string table. These references can also keep a Buffer alive.

mhorowitz avatar Apr 25 '20 02:04 mhorowitz

Thank you for your time and the clarifications, this was super informative!

tudorms avatar Apr 25 '20 02:04 tudorms