Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@ project adheres to [Semantic Versioning](http://semver.org/).
(Unreleased)
==================
### Changed
* Upgrade node-addon-api from 7.x to 8.x
### Added
### Fixed
* Fix memory leak caused by N-API weak reference callbacks being deferred to SetImmediate instead of running during GC. Enabled `NAPI_EXPERIMENTAL` to use `node_api_nogc_finalize` for ObjectWrap destructor. (#2436)

3.2.3
==================
Expand Down
2 changes: 1 addition & 1 deletion binding.gyp
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@
{
'target_name': 'canvas',
'include_dirs': ["<!(node -p \"require('node-addon-api').include_dir\")"],
'defines': [ 'NAPI_DISABLE_CPP_EXCEPTIONS', 'NODE_ADDON_API_ENABLE_MAYBE' ],
'defines': [ 'NAPI_DISABLE_CPP_EXCEPTIONS', 'NODE_ADDON_API_ENABLE_MAYBE', 'NAPI_EXPERIMENTAL' ],
'sources': [
'src/bmp/BMPParser.cc',
'src/Canvas.cc',
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
"util/"
],
"dependencies": {
"node-addon-api": "^7.0.0",
"node-addon-api": "^8.7.0",
"prebuild-install": "^7.1.3"
},
"devDependencies": {
Expand Down
9 changes: 6 additions & 3 deletions src/Canvas.cc
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,12 @@ Canvas::~Canvas() {
destroySurface();
}

void Canvas::Finalize(Napi::Env env) {
if (_surface && type == CANVAS_TYPE_IMAGE) {
Napi::MemoryManagement::AdjustExternalMemory(env, -(int64_t)approxBytesPerPixel() * width * height);
}
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From my reading of node-addon-api, having this member function forces the destructor to get called after gc, though before JS goes back to executing. It makes sense since this couldn't get called if the instance were already destroyed. Here's the relevant bit, cleaned up (source):

// If class overrides the basic finalizer, execute it.
if constexpr (details::HasBasicFinalizer<T>::value) {
  HandleScope scope(env);
  instance->Finalize(Napi::BasicEnv(env));
}

// If class overrides the (extended) finalizer, schedule it.
if constexpr (details::HasExtendedFinalizer<T>::value) {
  // Attach via node_api_post_finalizer. `PostFinalizeCallback` is responsible
  // for deleting the `T* instance`, after calling the user-provided finalizer.
  napi_status status =
      node_api_post_finalizer(env, PostFinalizeCallback, data, nullptr);
  NAPI_FATAL_IF_FAILED(status,
                       "ObjectWrap<T>::FinalizeCallback",
                       "node_api_post_finalizer failed");
}
// If the instance does _not_ override the (extended) finalizer, delete the
// `T* instance` immediately.
else {
  delete instance;
}

And the PostFinalizeCallback looks like this:

T* instance = static_cast<T*>(data);
instance->Finalize(Napi::Env(env));
delete instance;

But it would be better to destroy within gc, which is the whole point of BasicEnv. All day I've been trying to figure out why that causes node to crash (your initial test failures). I know it crashes in AdjustExternalMemory, but it seems to be failing because of something internal to node or node-addon-api.

AdjustExternalMemory takes a BasicEnv, and that env should still be valid, so I'm kind of at a loss for now. I'd like to take some time to understand it, which either leads to a bug fix in node or a corrected understanding on my part. I'm a little more hesitant to use the experimental API now. If we wanted to use it now, just having this method be empty and leaving the AdjustExternalMemory below would be better, since we want that to get called if we destroy from the C++ side.

I also think we should probably refactor the classes to only store BasicEnv to avoid accidentally trying to invoke JS at the wrong times. It's pretty easy to grab the full Napi::Env from info or other context.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I made progress figuring out most of the answers to my questions: nodejs/node-addon-api#1724 (comment)

/*
* Get type string.
*/
Expand Down Expand Up @@ -993,9 +999,6 @@ Canvas::destroySurface() {
if (_surface) {
// flush any operations that may use the closure that is freed below
cairo_surface_finish(_surface);
if (type == CANVAS_TYPE_IMAGE) {
Napi::MemoryManagement::AdjustExternalMemory(env, -(int64_t)approxBytesPerPixel() * width * height);
}
cairo_surface_destroy(_surface);
_surface = nullptr;
}
Expand Down
1 change: 1 addition & 0 deletions src/Canvas.h
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ class Canvas : public Napi::ObjectWrap<Canvas> {
public:
Canvas(const Napi::CallbackInfo& info);
~Canvas();
void Finalize(Napi::Env env);
static void Initialize(Napi::Env& env, Napi::Object& target);

Napi::Value ToBuffer(const Napi::CallbackInfo& info);
Expand Down
5 changes: 5 additions & 0 deletions src/CanvasPattern.cc
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ Pattern::Pattern(const Napi::CallbackInfo& info) : ObjectWrap<Pattern>(info), en
return;
}
_pattern = cairo_pattern_create_for_surface(surface);
_source = Napi::Persistent(obj);

if (info[1].IsString()) {
if ("no-repeat" == info[1].As<Napi::String>().Utf8Value()) {
Expand Down Expand Up @@ -127,3 +128,7 @@ repeat_type_t Pattern::get_repeat_type_for_cairo_pattern(cairo_pattern_t *patter
Pattern::~Pattern() {
if (_pattern) cairo_pattern_destroy(_pattern);
}

void Pattern::Finalize(Napi::Env env) {
_source.Reset();
}
2 changes: 2 additions & 0 deletions src/CanvasPattern.h
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,10 @@ class Pattern : public Napi::ObjectWrap<Pattern> {
static repeat_type_t get_repeat_type_for_cairo_pattern(cairo_pattern_t *pattern);
inline cairo_pattern_t *pattern(){ return _pattern; }
~Pattern();
void Finalize(Napi::Env env);
Napi::Env env;
private:
cairo_pattern_t *_pattern;
Napi::Reference<Napi::Object> _source;
repeat_type_t _repeat = REPEAT;
};
3 changes: 3 additions & 0 deletions src/CanvasRenderingContext2d.cc
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,9 @@ Context2d::Context2d(const Napi::CallbackInfo& info) : Napi::ObjectWrap<Context2
Context2d::~Context2d() {
if (_layout) g_object_unref(_layout);
if (_context) cairo_destroy(_context);
}

void Context2d::Finalize(Napi::Env env) {
_resetPersistentHandles();
}

Expand Down
1 change: 1 addition & 0 deletions src/CanvasRenderingContext2d.h
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,7 @@ class Context2d : public Napi::ObjectWrap<Context2d> {
void resetState();
inline PangoLayout *layout(){ return _layout; }
~Context2d();
void Finalize(Napi::Env env);
Napi::Env env;

private:
Expand Down
Loading