sharp icon indicating copy to clipboard operation
sharp copied to clipboard

Native Memory Leak of Metadata Buffers on Error Paths in `MetadataWorker`

Open codeCraft-Ritik opened this issue 1 month ago • 1 comments

  • Severity: 🟠 High (Native Memory Leak)
  • Target Files:
    • src/metadata.cc
    • src/metadata.h

Description & Root Cause

In MetadataWorker::Execute(), native metadata buffers are allocated on the heap using GLib's g_malloc:

baton->exif = static_cast<char*>(g_malloc(exifLength));
memcpy(baton->exif, exif, exifLength);
// Same for icc, iptc, xmp, tifftagPhotoshop, gainMap

In MetadataWorker::OnOK():

if (baton->err.empty()) {
  // Transferred to Napi::Buffer with sharp::FreeCallback
} else {
  Callback().SHARP_CALLBACK_FN_NAME(Receiver().Value(),
    { Napi::Error::New(env, sharp::TrimEnd(baton->err)).Value() });
}
delete baton->input;
delete baton;

MetadataBaton has no destructor. If an error is encountered during image inspection (such as a warning treated as error when failOn="warning", or corrupted subsequent fields):

  • The else branch executes.
  • baton->exif, baton->icc, baton->iptc, baton->xmp, baton->tifftagPhotoshop, and baton->gainMap are never freed.
  • delete baton; leaks all allocated heap memory.

Recommended Fix

Add a destructor to MetadataBaton in src/metadata.h:

~MetadataBaton() {
  g_free(exif);
  g_free(icc);
  g_free(iptc);
  g_free(xmp);
  g_free(tifftagPhotoshop);
  g_free(gainMap);
}

And reset pointers to nullptr when ownership is passed to Napi::Buffer in OnOK().

codeCraft-Ritik avatar Oct 11 '26 04:10 codeCraft-Ritik

This is more LLM-generated nonsense, there is no memory leak, the description is of a code path that is not possible.

lovell avatar Oct 11 '26 10:10 lovell