From 88c476c0eac9a04a716db516eed4ea7023c2d782 Mon Sep 17 00:00:00 2001 From: Stenzek Date: Mon, 22 Apr 2024 23:01:17 +1000 Subject: [PATCH] GS: Fix crash and file leak during dump --- pcsx2/GS/GSPng.cpp | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/pcsx2/GS/GSPng.cpp b/pcsx2/GS/GSPng.cpp index 0366aa5f3a49a..cd688a8e01483 100644 --- a/pcsx2/GS/GSPng.cpp +++ b/pcsx2/GS/GSPng.cpp @@ -38,8 +38,8 @@ namespace GSPng const int offset = first_image ? 0 : pixel[fmt].bytes_per_pixel_out; const int bytes_per_pixel_out = first_image ? pixel[fmt].bytes_per_pixel_out : bytes_per_pixel_in - offset; - FILE* fp = FileSystem::OpenCFile(file.c_str(), "wb"); - if (fp == nullptr) + auto fp = FileSystem::OpenManagedCFile(file.c_str(), "wb"); + if (!fp) return false; png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr); @@ -55,7 +55,14 @@ namespace GSPng if (setjmp(png_jmpbuf(png_ptr))) return false; - png_init_io(png_ptr, fp); + png_set_write_fn( + png_ptr, fp.get(), + [](png_structp png_ptr, png_bytep data_ptr, png_size_t size) { + if (std::fwrite(data_ptr, size, 1, static_cast(png_get_io_ptr(png_ptr))) != 1) + png_error(png_ptr, "file write error"); + }, + [](png_structp png_ptr) {}); + png_set_compression_level(png_ptr, compression); png_set_IHDR(png_ptr, info_ptr, width, height, channel_bit_depth, type, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); @@ -77,7 +84,6 @@ namespace GSPng if (png_ptr) png_destroy_write_struct(&png_ptr, info_ptr ? &info_ptr : nullptr); - std::fclose(fp); return true; }