[Bug]: Crash when TEST_PREMATURE_EXIT_FILE points to invalid path
- Dominant language
- C++
- Stars
- 39.5k
- Forks
- 10.9k
- Avg merge
- 6d 13h
- Merged PRs (30d)
- 1
Description
### Describe the issue
In ScopedPrematureExitFile constructor, when posix::FOpen() fails to
create the premature exit file, it returns nullptr. The code then
calls fwrite() and fclose() on this nullptr, causing a crash.
The comment states "I/O errors are ignored", but the code does not
actually handle the failure case.
Location: googletest/src/gtest.cc lines 5148-5150
Current code:
```
FILE* pfile = posix::FOpen(premature_exit_filepath_.c_str(), "w");
fwrite("0", 1, 1, pfile); // crashes if pfile is nullptr
fclose(pfile); // crashes if pfile is nullptr
```
Other FOpen usages in the codebase properly check for nullptr before
use.
### Steps to reproduce the problem
1. Build GoogleTest
```
mkdir build && cd build
cmake .. -DCMAKE_BUILD_TYPE=Debug
make -j4
```
2. Create a simple test program (test_simple.cpp)
```
#include
TEST(SimpleTest, Pass) {
EXPECT_EQ(1, 1);
}
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
```
3. Compile the test program
```
g++ test_simple.cpp -o test_bug \
-std=c++17 \
-I../googletest/include \
-L./lib -lgtest -lgtest_main -pthread
```
4. Run with invalid path
`TEST_PREMATURE_EXIT_FILE=/nonexistent/path/file.txt ./test_bug`
5. Result: Program crashes with segmentation fault
zsh: segmentation fault
### What version of GoogleTest are you using?
`85087857ad10bd407cd6ed2f52f7ea9752db621f`
### What operating system and version are you using?
macOS 13.4
### What compiler and version are you using?
```
Apple clang version 14.0.3 (clang-1403.0.22.14.1)
Target: arm64-apple-darwin22.5.0
```
### What build system are you using?
CMake 4.2.1
### Additional context
```
FILE* pfile = posix::FOpen(premature_exit_filepath_.c_str(), "w");
if (pfile != nullptr) {
fwrite("0", 1, 1, pfile);
fclose(pfile);
}
```
This is consistent with other FOpen usages in the codebase (e.g.,
line 5899).
I have verified this fix resolves the crash.
Contributor guide
Research direction
Start in googletest/src/gtest.cc around lines 5148-5150 and compare the other FOpen usage around line 5899. Reproduce the failure with TEST_PREMATURE_EXIT_FILE pointing to an invalid path, then verify the program no longer crashes and that the existing build commands still pass.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- cmake, cpp
- Domain
- testing-qa
- Issue type
- Bug
- Difficulty
- 1/5
- Estimated time
- Under an hour
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 52/100