[sanitizer_common] Use O_TRUNC for WrOnly access mode.

Summary: Otherwise if the file existed and was larger than the write size before the OpenFile call, the file will not be truncated and contain garbage in trailing bytes.

Reviewers: glider, kcc, vitalybuka

Subscribers: kubamracek, delcypher, llvm-commits, #sanitizers

Differential Revision: https://reviews.llvm.org/D48250

llvm-svn: 334881
This commit is contained in:
Fangrui Song 2018-06-16 03:32:59 +00:00
parent d4ff2f8a74
commit d40fc6019b
3 changed files with 8 additions and 2 deletions

View File

@ -160,7 +160,7 @@ fd_t OpenFile(const char *filename, FileAccessMode mode, error_t *errno_p) {
int flags;
switch (mode) {
case RdOnly: flags = O_RDONLY; break;
case WrOnly: flags = O_WRONLY | O_CREAT; break;
case WrOnly: flags = O_WRONLY | O_CREAT | O_TRUNC; break;
case RdWr: flags = O_RDWR | O_CREAT; break;
}
fd_t res = internal_open(filename, flags, 0660);

View File

@ -193,7 +193,7 @@ fd_t OpenFile(const char *filename, FileAccessMode mode, error_t *errno_p) {
int flags;
switch (mode) {
case RdOnly: flags = O_RDONLY; break;
case WrOnly: flags = O_WRONLY | O_CREAT; break;
case WrOnly: flags = O_WRONLY | O_CREAT | O_TRUNC; break;
case RdWr: flags = O_RDWR | O_CREAT; break;
}
fd_t res = open(filename, flags, 0660);

View File

@ -108,6 +108,12 @@ TEST(SanitizerCommon, FileOps) {
temp_file_name(tmpfile, sizeof(tmpfile), "sanitizer_common.fileops.tmp.");
fd_t fd = OpenFile(tmpfile, WrOnly);
ASSERT_NE(fd, kInvalidFd);
ASSERT_FALSE(internal_iserror(internal_write(fd, "A", 1)));
CloseFile(fd);
fd = OpenFile(tmpfile, WrOnly);
ASSERT_NE(fd, kInvalidFd);
EXPECT_EQ(internal_lseek(fd, 0, SEEK_END), 0u);
uptr bytes_written = 0;
EXPECT_TRUE(WriteToFile(fd, str1, len1, &bytes_written));
EXPECT_EQ(len1, bytes_written);