xref: /llvm-project/llvm/unittests/Support/ReplaceFileTest.cpp (revision 2946cd701067404b99c39fb29dc9c74bd7193eb3)
1 //===- llvm/unittest/Support/ReplaceFileTest.cpp - unit tests -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "llvm/Support/Errc.h"
10 #include "llvm/Support/ErrorHandling.h"
11 #include "llvm/Support/FileSystem.h"
12 #include "llvm/Support/MemoryBuffer.h"
13 #include "llvm/Support/Path.h"
14 #include "llvm/Support/Process.h"
15 #include "gtest/gtest.h"
16 
17 using namespace llvm;
18 using namespace llvm::sys;
19 
20 #define ASSERT_NO_ERROR(x)                                                 \
21   do {                                                                     \
22     if (std::error_code ASSERT_NO_ERROR_ec = x) {                          \
23       errs() << #x ": did not return errc::success.\n"                     \
24              << "error number: " << ASSERT_NO_ERROR_ec.value() << "\n"     \
25              << "error message: " << ASSERT_NO_ERROR_ec.message() << "\n"; \
26     }                                                                      \
27   } while (false)
28 
29 namespace {
30 std::error_code CreateFileWithContent(const SmallString<128> &FilePath,
31                                       const StringRef &content) {
32   int FD = 0;
33   if (std::error_code ec = fs::openFileForWrite(FilePath, FD))
34     return ec;
35 
36   const bool ShouldClose = true;
37   raw_fd_ostream OS(FD, ShouldClose);
38   OS << content;
39 
40   return std::error_code();
41 }
42 
43 class ScopedFD {
44   int FD;
45 
46   ScopedFD(const ScopedFD &) = delete;
47   ScopedFD &operator=(const ScopedFD &) = delete;
48 
49  public:
50   explicit ScopedFD(int Descriptor) : FD(Descriptor) {}
51   ~ScopedFD() { Process::SafelyCloseFileDescriptor(FD); }
52 };
53 
54 bool FDHasContent(int FD, StringRef Content) {
55   auto Buffer = MemoryBuffer::getOpenFile(FD, "", -1);
56   assert(Buffer);
57   return Buffer.get()->getBuffer() == Content;
58 }
59 
60 bool FileHasContent(StringRef File, StringRef Content) {
61   int FD = 0;
62   auto EC = fs::openFileForRead(File, FD);
63   (void)EC;
64   assert(!EC);
65   ScopedFD EventuallyCloseIt(FD);
66   return FDHasContent(FD, Content);
67 }
68 
69 TEST(rename, FileOpenedForReadingCanBeReplaced) {
70   // Create unique temporary directory for this test.
71   SmallString<128> TestDirectory;
72   ASSERT_NO_ERROR(fs::createUniqueDirectory(
73       "FileOpenedForReadingCanBeReplaced-test", TestDirectory));
74 
75   // Add a couple of files to the test directory.
76   SmallString<128> SourceFileName(TestDirectory);
77   path::append(SourceFileName, "source");
78 
79   SmallString<128> TargetFileName(TestDirectory);
80   path::append(TargetFileName, "target");
81 
82   ASSERT_NO_ERROR(CreateFileWithContent(SourceFileName, "!!source!!"));
83   ASSERT_NO_ERROR(CreateFileWithContent(TargetFileName, "!!target!!"));
84 
85   {
86     // Open the target file for reading.
87     int ReadFD = 0;
88     ASSERT_NO_ERROR(fs::openFileForRead(TargetFileName, ReadFD));
89     ScopedFD EventuallyCloseIt(ReadFD);
90 
91     // Confirm we can replace the file while it is open.
92     EXPECT_TRUE(!fs::rename(SourceFileName, TargetFileName));
93 
94     // We should still be able to read the old data through the existing
95     // descriptor.
96     EXPECT_TRUE(FDHasContent(ReadFD, "!!target!!"));
97 
98     // The source file should no longer exist
99     EXPECT_FALSE(fs::exists(SourceFileName));
100   }
101 
102   // If we obtain a new descriptor for the target file, we should find that it
103   // contains the content that was in the source file.
104   EXPECT_TRUE(FileHasContent(TargetFileName, "!!source!!"));
105 
106   // Rename the target file back to the source file name to confirm that rename
107   // still works if the destination does not already exist.
108   EXPECT_TRUE(!fs::rename(TargetFileName, SourceFileName));
109   EXPECT_FALSE(fs::exists(TargetFileName));
110   ASSERT_TRUE(fs::exists(SourceFileName));
111 
112   // Clean up.
113   ASSERT_NO_ERROR(fs::remove(SourceFileName));
114   ASSERT_NO_ERROR(fs::remove(TestDirectory.str()));
115 }
116 
117 TEST(rename, ExistingTemp) {
118   // Test that existing .tmpN files don't get deleted by the Windows
119   // sys::fs::rename implementation.
120   SmallString<128> TestDirectory;
121   ASSERT_NO_ERROR(
122       fs::createUniqueDirectory("ExistingTemp-test", TestDirectory));
123 
124   SmallString<128> SourceFileName(TestDirectory);
125   path::append(SourceFileName, "source");
126 
127   SmallString<128> TargetFileName(TestDirectory);
128   path::append(TargetFileName, "target");
129 
130   SmallString<128> TargetTmp0FileName(TestDirectory);
131   path::append(TargetTmp0FileName, "target.tmp0");
132 
133   SmallString<128> TargetTmp1FileName(TestDirectory);
134   path::append(TargetTmp1FileName, "target.tmp1");
135 
136   ASSERT_NO_ERROR(CreateFileWithContent(SourceFileName, "!!source!!"));
137   ASSERT_NO_ERROR(CreateFileWithContent(TargetFileName, "!!target!!"));
138   ASSERT_NO_ERROR(CreateFileWithContent(TargetTmp0FileName, "!!target.tmp0!!"));
139 
140   {
141     // Use mapped_file_region to make sure that the destination file is mmap'ed.
142     // This will cause SetInformationByHandle to fail when renaming to the
143     // destination, and we will follow the code path that tries to give target
144     // a temporary name.
145     int TargetFD;
146     std::error_code EC;
147     ASSERT_NO_ERROR(fs::openFileForRead(TargetFileName, TargetFD));
148     ScopedFD X(TargetFD);
149     sys::fs::mapped_file_region MFR(
150         TargetFD, sys::fs::mapped_file_region::readonly, 10, 0, EC);
151     ASSERT_FALSE(EC);
152 
153     ASSERT_NO_ERROR(fs::rename(SourceFileName, TargetFileName));
154 
155 #ifdef _WIN32
156     // Make sure that target was temporarily renamed to target.tmp1 on Windows.
157     // This is signified by a permission denied error as opposed to no such file
158     // or directory when trying to open it.
159     int Tmp1FD;
160     EXPECT_EQ(errc::permission_denied,
161               fs::openFileForRead(TargetTmp1FileName, Tmp1FD));
162 #endif
163   }
164 
165   EXPECT_TRUE(FileHasContent(TargetTmp0FileName, "!!target.tmp0!!"));
166 
167   ASSERT_NO_ERROR(fs::remove(TargetFileName));
168   ASSERT_NO_ERROR(fs::remove(TargetTmp0FileName));
169   ASSERT_NO_ERROR(fs::remove(TestDirectory.str()));
170 }
171 
172 }  // anonymous namespace
173