1 //===- unittests/Basic/FileMangerTest.cpp ------------ FileManger 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 "clang/Basic/FileManager.h"
10 #include "clang/Basic/FileSystemOptions.h"
11 #include "clang/Basic/FileSystemStatCache.h"
12 #include "llvm/ADT/STLExtras.h"
13 #include "llvm/Support/Path.h"
14 #include "llvm/Support/VirtualFileSystem.h"
15 #include "gtest/gtest.h"
16 
17 using namespace llvm;
18 using namespace clang;
19 
20 namespace {
21 
22 // Used to create a fake file system for running the tests with such
23 // that the tests are not affected by the structure/contents of the
24 // file system on the machine running the tests.
25 class FakeStatCache : public FileSystemStatCache {
26 private:
27   // Maps a file/directory path to its desired stat result.  Anything
28   // not in this map is considered to not exist in the file system.
29   llvm::StringMap<llvm::vfs::Status, llvm::BumpPtrAllocator> StatCalls;
30 
31   void InjectFileOrDirectory(const char *Path, ino_t INode, bool IsFile) {
32 #ifndef _WIN32
33     SmallString<128> NormalizedPath(Path);
34     llvm::sys::path::native(NormalizedPath);
35     Path = NormalizedPath.c_str();
36 #endif
37 
38     auto fileType = IsFile ?
39       llvm::sys::fs::file_type::regular_file :
40       llvm::sys::fs::file_type::directory_file;
41     llvm::vfs::Status Status(Path, llvm::sys::fs::UniqueID(1, INode),
42                              /*MTime*/{}, /*User*/0, /*Group*/0,
43                              /*Size*/0, fileType,
44                              llvm::sys::fs::perms::all_all);
45     StatCalls[Path] = Status;
46   }
47 
48 public:
49   // Inject a file with the given inode value to the fake file system.
50   void InjectFile(const char *Path, ino_t INode) {
51     InjectFileOrDirectory(Path, INode, /*IsFile=*/true);
52   }
53 
54   // Inject a directory with the given inode value to the fake file system.
55   void InjectDirectory(const char *Path, ino_t INode) {
56     InjectFileOrDirectory(Path, INode, /*IsFile=*/false);
57   }
58 
59   // Implement FileSystemStatCache::getStat().
60   std::error_code getStat(StringRef Path, llvm::vfs::Status &Status,
61                           bool isFile,
62                           std::unique_ptr<llvm::vfs::File> *F,
63                           llvm::vfs::FileSystem &FS) override {
64 #ifndef _WIN32
65     SmallString<128> NormalizedPath(Path);
66     llvm::sys::path::native(NormalizedPath);
67     Path = NormalizedPath.c_str();
68 #endif
69 
70     if (StatCalls.count(Path) != 0) {
71       Status = StatCalls[Path];
72       return std::error_code();
73     }
74 
75     return std::make_error_code(std::errc::no_such_file_or_directory);
76   }
77 };
78 
79 // The test fixture.
80 class FileManagerTest : public ::testing::Test {
81  protected:
82   FileManagerTest() : manager(options) {
83   }
84 
85   FileSystemOptions options;
86   FileManager manager;
87 };
88 
89 // When a virtual file is added, its getDir() field is set correctly
90 // (not NULL, correct name).
91 TEST_F(FileManagerTest, getVirtualFileSetsTheDirFieldCorrectly) {
92   const FileEntry *file = manager.getVirtualFile("foo.cpp", 42, 0);
93   ASSERT_TRUE(file != nullptr);
94 
95   const DirectoryEntry *dir = file->getDir();
96   ASSERT_TRUE(dir != nullptr);
97   EXPECT_EQ(".", dir->getName());
98 
99   file = manager.getVirtualFile("x/y/z.cpp", 42, 0);
100   ASSERT_TRUE(file != nullptr);
101 
102   dir = file->getDir();
103   ASSERT_TRUE(dir != nullptr);
104   EXPECT_EQ("x/y", dir->getName());
105 }
106 
107 // Before any virtual file is added, no virtual directory exists.
108 TEST_F(FileManagerTest, NoVirtualDirectoryExistsBeforeAVirtualFileIsAdded) {
109   // An empty FakeStatCache causes all stat calls made by the
110   // FileManager to report "file/directory doesn't exist".  This
111   // avoids the possibility of the result of this test being affected
112   // by what's in the real file system.
113   manager.setStatCache(llvm::make_unique<FakeStatCache>());
114 
115   ASSERT_FALSE(manager.getDirectory("virtual/dir/foo"));
116   ASSERT_FALSE(manager.getDirectory("virtual/dir"));
117   ASSERT_FALSE(manager.getDirectory("virtual"));
118 }
119 
120 // When a virtual file is added, all of its ancestors should be created.
121 TEST_F(FileManagerTest, getVirtualFileCreatesDirectoryEntriesForAncestors) {
122   // Fake an empty real file system.
123   manager.setStatCache(llvm::make_unique<FakeStatCache>());
124 
125   manager.getVirtualFile("virtual/dir/bar.h", 100, 0);
126   ASSERT_FALSE(manager.getDirectory("virtual/dir/foo"));
127 
128   auto dir = manager.getDirectory("virtual/dir");
129   ASSERT_TRUE(dir);
130   EXPECT_EQ("virtual/dir", (*dir)->getName());
131 
132   dir = manager.getDirectory("virtual");
133   ASSERT_TRUE(dir);
134   EXPECT_EQ("virtual", (*dir)->getName());
135 }
136 
137 // getFile() returns non-NULL if a real file exists at the given path.
138 TEST_F(FileManagerTest, getFileReturnsValidFileEntryForExistingRealFile) {
139   // Inject fake files into the file system.
140   auto statCache = llvm::make_unique<FakeStatCache>();
141   statCache->InjectDirectory("/tmp", 42);
142   statCache->InjectFile("/tmp/test", 43);
143 
144 #ifdef _WIN32
145   const char *DirName = "C:.";
146   const char *FileName = "C:test";
147   statCache->InjectDirectory(DirName, 44);
148   statCache->InjectFile(FileName, 45);
149 #endif
150 
151   manager.setStatCache(std::move(statCache));
152 
153   auto file = manager.getFile("/tmp/test");
154   ASSERT_TRUE(file);
155   ASSERT_TRUE((*file)->isValid());
156   EXPECT_EQ("/tmp/test", (*file)->getName());
157 
158   const DirectoryEntry *dir = (*file)->getDir();
159   ASSERT_TRUE(dir != nullptr);
160   EXPECT_EQ("/tmp", dir->getName());
161 
162 #ifdef _WIN32
163   file = manager.getFile(FileName);
164   ASSERT_TRUE(file);
165 
166   dir = file->getDir();
167   ASSERT_TRUE(dir != NULL);
168   EXPECT_EQ(DirName, dir->getName());
169 #endif
170 }
171 
172 // getFile() returns non-NULL if a virtual file exists at the given path.
173 TEST_F(FileManagerTest, getFileReturnsValidFileEntryForExistingVirtualFile) {
174   // Fake an empty real file system.
175   manager.setStatCache(llvm::make_unique<FakeStatCache>());
176 
177   manager.getVirtualFile("virtual/dir/bar.h", 100, 0);
178   auto file = manager.getFile("virtual/dir/bar.h");
179   ASSERT_TRUE(file);
180   ASSERT_TRUE((*file)->isValid());
181   EXPECT_EQ("virtual/dir/bar.h", (*file)->getName());
182 
183   const DirectoryEntry *dir = (*file)->getDir();
184   ASSERT_TRUE(dir != nullptr);
185   EXPECT_EQ("virtual/dir", dir->getName());
186 }
187 
188 // getFile() returns different FileEntries for different paths when
189 // there's no aliasing.
190 TEST_F(FileManagerTest, getFileReturnsDifferentFileEntriesForDifferentFiles) {
191   // Inject two fake files into the file system.  Different inodes
192   // mean the files are not symlinked together.
193   auto statCache = llvm::make_unique<FakeStatCache>();
194   statCache->InjectDirectory(".", 41);
195   statCache->InjectFile("foo.cpp", 42);
196   statCache->InjectFile("bar.cpp", 43);
197   manager.setStatCache(std::move(statCache));
198 
199   auto fileFoo = manager.getFile("foo.cpp");
200   auto fileBar = manager.getFile("bar.cpp");
201   ASSERT_TRUE(fileFoo);
202   ASSERT_TRUE((*fileFoo)->isValid());
203   ASSERT_TRUE(fileBar);
204   ASSERT_TRUE((*fileBar)->isValid());
205   EXPECT_NE(*fileFoo, *fileBar);
206 }
207 
208 // getFile() returns NULL if neither a real file nor a virtual file
209 // exists at the given path.
210 TEST_F(FileManagerTest, getFileReturnsNULLForNonexistentFile) {
211   // Inject a fake foo.cpp into the file system.
212   auto statCache = llvm::make_unique<FakeStatCache>();
213   statCache->InjectDirectory(".", 41);
214   statCache->InjectFile("foo.cpp", 42);
215   manager.setStatCache(std::move(statCache));
216 
217   // Create a virtual bar.cpp file.
218   manager.getVirtualFile("bar.cpp", 200, 0);
219 
220   auto file = manager.getFile("xyz.txt");
221   ASSERT_FALSE(file);
222 }
223 
224 // The following tests apply to Unix-like system only.
225 
226 #ifndef _WIN32
227 
228 // getFile() returns the same FileEntry for real files that are aliases.
229 TEST_F(FileManagerTest, getFileReturnsSameFileEntryForAliasedRealFiles) {
230   // Inject two real files with the same inode.
231   auto statCache = llvm::make_unique<FakeStatCache>();
232   statCache->InjectDirectory("abc", 41);
233   statCache->InjectFile("abc/foo.cpp", 42);
234   statCache->InjectFile("abc/bar.cpp", 42);
235   manager.setStatCache(std::move(statCache));
236 
237   auto f1 = manager.getFile("abc/foo.cpp");
238   auto f2 = manager.getFile("abc/bar.cpp");
239 
240   EXPECT_EQ(f1 ? *f1 : nullptr,
241             f2 ? *f2 : nullptr);
242 }
243 
244 // getFile() returns the same FileEntry for virtual files that have
245 // corresponding real files that are aliases.
246 TEST_F(FileManagerTest, getFileReturnsSameFileEntryForAliasedVirtualFiles) {
247   // Inject two real files with the same inode.
248   auto statCache = llvm::make_unique<FakeStatCache>();
249   statCache->InjectDirectory("abc", 41);
250   statCache->InjectFile("abc/foo.cpp", 42);
251   statCache->InjectFile("abc/bar.cpp", 42);
252   manager.setStatCache(std::move(statCache));
253 
254   ASSERT_TRUE(manager.getVirtualFile("abc/foo.cpp", 100, 0)->isValid());
255   ASSERT_TRUE(manager.getVirtualFile("abc/bar.cpp", 200, 0)->isValid());
256 
257   auto f1 = manager.getFile("abc/foo.cpp");
258   auto f2 = manager.getFile("abc/bar.cpp");
259 
260   EXPECT_EQ(f1 ? *f1 : nullptr,
261             f2 ? *f2 : nullptr);
262 }
263 
264 // getFile() Should return the same entry as getVirtualFile if the file actually
265 // is a virtual file, even if the name is not exactly the same (but is after
266 // normalisation done by the file system, like on Windows). This can be checked
267 // here by checking the size.
268 TEST_F(FileManagerTest, getVirtualFileWithDifferentName) {
269   // Inject fake files into the file system.
270   auto statCache = llvm::make_unique<FakeStatCache>();
271   statCache->InjectDirectory("c:\\tmp", 42);
272   statCache->InjectFile("c:\\tmp\\test", 43);
273 
274   manager.setStatCache(std::move(statCache));
275 
276   // Inject the virtual file:
277   const FileEntry *file1 = manager.getVirtualFile("c:\\tmp\\test", 123, 1);
278   ASSERT_TRUE(file1 != nullptr);
279   ASSERT_TRUE(file1->isValid());
280   EXPECT_EQ(43U, file1->getUniqueID().getFile());
281   EXPECT_EQ(123, file1->getSize());
282 
283   // Lookup the virtual file with a different name:
284   auto file2 = manager.getFile("c:/tmp/test", 100, 1);
285   ASSERT_TRUE(file2);
286   ASSERT_TRUE((*file2)->isValid());
287   // Check that it's the same UFE:
288   EXPECT_EQ(file1, *file2);
289   EXPECT_EQ(43U, (*file2)->getUniqueID().getFile());
290   // Check that the contents of the UFE are not overwritten by the entry in the
291   // filesystem:
292   EXPECT_EQ(123, (*file2)->getSize());
293 }
294 
295 #endif  // !_WIN32
296 
297 TEST_F(FileManagerTest, makeAbsoluteUsesVFS) {
298   SmallString<64> CustomWorkingDir;
299 #ifdef _WIN32
300   CustomWorkingDir = "C:";
301 #else
302   CustomWorkingDir = "/";
303 #endif
304   llvm::sys::path::append(CustomWorkingDir, "some", "weird", "path");
305 
306   auto FS = IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem>(
307       new llvm::vfs::InMemoryFileSystem);
308   // setCurrentworkingdirectory must finish without error.
309   ASSERT_TRUE(!FS->setCurrentWorkingDirectory(CustomWorkingDir));
310 
311   FileSystemOptions Opts;
312   FileManager Manager(Opts, FS);
313 
314   SmallString<64> Path("a/foo.cpp");
315 
316   SmallString<64> ExpectedResult(CustomWorkingDir);
317   llvm::sys::path::append(ExpectedResult, Path);
318 
319   ASSERT_TRUE(Manager.makeAbsolutePath(Path));
320   EXPECT_EQ(Path, ExpectedResult);
321 }
322 
323 // getVirtualFile should always fill the real path.
324 TEST_F(FileManagerTest, getVirtualFileFillsRealPathName) {
325   SmallString<64> CustomWorkingDir;
326 #ifdef _WIN32
327   CustomWorkingDir = "C:/";
328 #else
329   CustomWorkingDir = "/";
330 #endif
331 
332   auto FS = IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem>(
333       new llvm::vfs::InMemoryFileSystem);
334   // setCurrentworkingdirectory must finish without error.
335   ASSERT_TRUE(!FS->setCurrentWorkingDirectory(CustomWorkingDir));
336 
337   FileSystemOptions Opts;
338   FileManager Manager(Opts, FS);
339 
340   // Inject fake files into the file system.
341   auto statCache = llvm::make_unique<FakeStatCache>();
342   statCache->InjectDirectory("/tmp", 42);
343   statCache->InjectFile("/tmp/test", 43);
344 
345   Manager.setStatCache(std::move(statCache));
346 
347   // Check for real path.
348   const FileEntry *file = Manager.getVirtualFile("/tmp/test", 123, 1);
349   ASSERT_TRUE(file != nullptr);
350   ASSERT_TRUE(file->isValid());
351   SmallString<64> ExpectedResult = CustomWorkingDir;
352 
353   llvm::sys::path::append(ExpectedResult, "tmp", "test");
354   EXPECT_EQ(file->tryGetRealPathName(), ExpectedResult);
355 }
356 
357 TEST_F(FileManagerTest, getFileDontOpenRealPath) {
358   SmallString<64> CustomWorkingDir;
359 #ifdef _WIN32
360   CustomWorkingDir = "C:/";
361 #else
362   CustomWorkingDir = "/";
363 #endif
364 
365   auto FS = IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem>(
366       new llvm::vfs::InMemoryFileSystem);
367   // setCurrentworkingdirectory must finish without error.
368   ASSERT_TRUE(!FS->setCurrentWorkingDirectory(CustomWorkingDir));
369 
370   FileSystemOptions Opts;
371   FileManager Manager(Opts, FS);
372 
373   // Inject fake files into the file system.
374   auto statCache = llvm::make_unique<FakeStatCache>();
375   statCache->InjectDirectory("/tmp", 42);
376   statCache->InjectFile("/tmp/test", 43);
377 
378   Manager.setStatCache(std::move(statCache));
379 
380   // Check for real path.
381   const FileEntry *file = Manager.getFile("/tmp/test", /*OpenFile=*/false);
382   ASSERT_TRUE(file != nullptr);
383   ASSERT_TRUE(file->isValid());
384   SmallString<64> ExpectedResult = CustomWorkingDir;
385 
386   llvm::sys::path::append(ExpectedResult, "tmp", "test");
387   EXPECT_EQ(file->tryGetRealPathName(), ExpectedResult);
388 }
389 
390 } // anonymous namespace
391