From e3310812781701527c0ce2be233964357f2de2a4 Mon Sep 17 00:00:00 2001 From: Alvin Jaison Date: Thu, 23 Jul 2026 09:24:19 +0100 Subject: [PATCH] Fix null pointer dereference in ScopedPrematureExitFile When TEST_PREMATURE_EXIT_FILE is set to a path that cannot be opened for writing (e.g., non-existent directory or insufficient permissions), posix::FOpen returns NULL. Previously, fwrite and fclose were called unconditionally on the result, causing a segmentation fault. This change: - Adds a null check before calling fwrite/fclose - Tracks whether the file was successfully created via a file_created_ flag, so the destructor only attempts removal when the file actually exists This matches the existing comment's stated intent that I/O errors should be silently ignored. --- googletest/src/gtest.cc | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/googletest/src/gtest.cc b/googletest/src/gtest.cc index b38f551e0..7b1d7256e 100644 --- a/googletest/src/gtest.cc +++ b/googletest/src/gtest.cc @@ -5166,21 +5166,25 @@ class ScopedPrematureExitFile { public: explicit ScopedPrematureExitFile(const char* premature_exit_filepath) : premature_exit_filepath_( - premature_exit_filepath ? premature_exit_filepath : "") { + premature_exit_filepath ? premature_exit_filepath : ""), + file_created_(false) { // If a path to the premature-exit file is specified... if (!premature_exit_filepath_.empty()) { // create the file with a single "0" character in it. I/O // errors are ignored as there's nothing better we can do and we // don't want to fail the test because of this. FILE* pfile = posix::FOpen(premature_exit_filepath_.c_str(), "w"); - fwrite("0", 1, 1, pfile); - fclose(pfile); + if (pfile != nullptr) { + fwrite("0", 1, 1, pfile); + fclose(pfile); + file_created_ = true; + } } } ~ScopedPrematureExitFile() { #ifndef GTEST_OS_ESP8266 - if (!premature_exit_filepath_.empty()) { + if (file_created_) { int retval = remove(premature_exit_filepath_.c_str()); if (retval) { GTEST_LOG_(ERROR) << "Failed to remove premature exit filepath \"" @@ -5193,6 +5197,7 @@ class ScopedPrematureExitFile { private: const std::string premature_exit_filepath_; + bool file_created_; ScopedPrematureExitFile(const ScopedPrematureExitFile&) = delete; ScopedPrematureExitFile& operator=(const ScopedPrematureExitFile&) = delete;