fix: ensure external memory adjustments are balanced (#33266)

This commit is contained in:
David Sanders 2022-03-16 10:54:30 -07:00 committed by GitHub
parent cf3ee7be56
commit 652680e801
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 13 additions and 7 deletions

View file

@ -109,7 +109,7 @@ base::win::ScopedHICON ReadICOFromPath(int size, const base::FilePath& path) {
NativeImage::NativeImage(v8::Isolate* isolate, const gfx::Image& image) NativeImage::NativeImage(v8::Isolate* isolate, const gfx::Image& image)
: image_(image), isolate_(isolate) { : image_(image), isolate_(isolate) {
AdjustAmountOfExternalAllocatedMemory(true); UpdateExternalAllocatedMemoryUsage();
} }
#if BUILDFLAG(IS_WIN) #if BUILDFLAG(IS_WIN)
@ -120,22 +120,27 @@ NativeImage::NativeImage(v8::Isolate* isolate, const base::FilePath& hicon_path)
electron::util::ReadImageSkiaFromICO(&image_skia, GetHICON(256)); electron::util::ReadImageSkiaFromICO(&image_skia, GetHICON(256));
image_ = gfx::Image(image_skia); image_ = gfx::Image(image_skia);
AdjustAmountOfExternalAllocatedMemory(true); UpdateExternalAllocatedMemoryUsage();
} }
#endif #endif
NativeImage::~NativeImage() { NativeImage::~NativeImage() {
AdjustAmountOfExternalAllocatedMemory(false); isolate_->AdjustAmountOfExternalAllocatedMemory(-memory_usage_);
} }
void NativeImage::AdjustAmountOfExternalAllocatedMemory(bool add) { void NativeImage::UpdateExternalAllocatedMemoryUsage() {
int32_t new_memory_usage = 0;
if (image_.HasRepresentation(gfx::Image::kImageRepSkia)) { if (image_.HasRepresentation(gfx::Image::kImageRepSkia)) {
auto* const image_skia = image_.ToImageSkia(); auto* const image_skia = image_.ToImageSkia();
if (!image_skia->isNull()) { if (!image_skia->isNull()) {
int64_t size = image_skia->bitmap()->computeByteSize(); new_memory_usage = image_skia->bitmap()->computeByteSize();
isolate_->AdjustAmountOfExternalAllocatedMemory(add ? size : -size);
} }
} }
isolate_->AdjustAmountOfExternalAllocatedMemory(new_memory_usage -
memory_usage_);
memory_usage_ = new_memory_usage;
} }
// static // static

View file

@ -121,7 +121,7 @@ class NativeImage : public gin::Wrappable<NativeImage> {
float GetAspectRatio(const absl::optional<float> scale_factor); float GetAspectRatio(const absl::optional<float> scale_factor);
void AddRepresentation(const gin_helper::Dictionary& options); void AddRepresentation(const gin_helper::Dictionary& options);
void AdjustAmountOfExternalAllocatedMemory(bool add); void UpdateExternalAllocatedMemoryUsage();
// Mark the image as template image. // Mark the image as template image.
void SetTemplateImage(bool setAsTemplate); void SetTemplateImage(bool setAsTemplate);
@ -136,6 +136,7 @@ class NativeImage : public gin::Wrappable<NativeImage> {
gfx::Image image_; gfx::Image image_;
v8::Isolate* isolate_; v8::Isolate* isolate_;
int32_t memory_usage_ = 0;
}; };
} // namespace api } // namespace api