1 //===-- FileSystem.cpp ------------------------------------------*- C++ -*-===//
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 "lldb/Host/FileSystem.h"
10 
11 #include "lldb/Utility/LLDBAssert.h"
12 #include "lldb/Utility/TildeExpressionResolver.h"
13 
14 #include "llvm/Support/Errc.h"
15 #include "llvm/Support/Errno.h"
16 #include "llvm/Support/Error.h"
17 #include "llvm/Support/FileSystem.h"
18 #include "llvm/Support/Path.h"
19 #include "llvm/Support/Program.h"
20 #include "llvm/Support/Threading.h"
21 
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <limits.h>
25 #include <stdarg.h>
26 #include <stdio.h>
27 
28 #ifdef _WIN32
29 #include "lldb/Host/windows/windows.h"
30 #else
31 #include <sys/ioctl.h>
32 #include <sys/stat.h>
33 #include <termios.h>
34 #include <unistd.h>
35 #endif
36 
37 #include <algorithm>
38 #include <fstream>
39 #include <vector>
40 
41 using namespace lldb;
42 using namespace lldb_private;
43 using namespace llvm;
44 
45 FileSystem &FileSystem::Instance() { return *InstanceImpl(); }
46 
47 void FileSystem::Initialize() {
48   lldbassert(!InstanceImpl() && "Already initialized.");
49   InstanceImpl().emplace();
50 }
51 
52 void FileSystem::Initialize(FileCollector &collector) {
53   lldbassert(!InstanceImpl() && "Already initialized.");
54   InstanceImpl().emplace(collector);
55 }
56 
57 llvm::Error FileSystem::Initialize(const FileSpec &mapping) {
58   lldbassert(!InstanceImpl() && "Already initialized.");
59 
60   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> buffer =
61       llvm::vfs::getRealFileSystem()->getBufferForFile(mapping.GetPath());
62 
63   if (!buffer)
64     return llvm::errorCodeToError(buffer.getError());
65 
66   InstanceImpl().emplace(
67       llvm::vfs::getVFSFromYAML(std::move(buffer.get()), nullptr, ""), true);
68 
69   return llvm::Error::success();
70 }
71 
72 void FileSystem::Initialize(IntrusiveRefCntPtr<vfs::FileSystem> fs) {
73   lldbassert(!InstanceImpl() && "Already initialized.");
74   InstanceImpl().emplace(fs);
75 }
76 
77 void FileSystem::Terminate() {
78   lldbassert(InstanceImpl() && "Already terminated.");
79   InstanceImpl().reset();
80 }
81 
82 Optional<FileSystem> &FileSystem::InstanceImpl() {
83   static Optional<FileSystem> g_fs;
84   return g_fs;
85 }
86 
87 vfs::directory_iterator FileSystem::DirBegin(const FileSpec &file_spec,
88                                              std::error_code &ec) {
89   return DirBegin(file_spec.GetPath(), ec);
90 }
91 
92 vfs::directory_iterator FileSystem::DirBegin(const Twine &dir,
93                                              std::error_code &ec) {
94   return m_fs->dir_begin(dir, ec);
95 }
96 
97 llvm::ErrorOr<vfs::Status>
98 FileSystem::GetStatus(const FileSpec &file_spec) const {
99   return GetStatus(file_spec.GetPath());
100 }
101 
102 llvm::ErrorOr<vfs::Status> FileSystem::GetStatus(const Twine &path) const {
103   return m_fs->status(path);
104 }
105 
106 sys::TimePoint<>
107 FileSystem::GetModificationTime(const FileSpec &file_spec) const {
108   return GetModificationTime(file_spec.GetPath());
109 }
110 
111 sys::TimePoint<> FileSystem::GetModificationTime(const Twine &path) const {
112   ErrorOr<vfs::Status> status = m_fs->status(path);
113   if (!status)
114     return sys::TimePoint<>();
115   return status->getLastModificationTime();
116 }
117 
118 uint64_t FileSystem::GetByteSize(const FileSpec &file_spec) const {
119   return GetByteSize(file_spec.GetPath());
120 }
121 
122 uint64_t FileSystem::GetByteSize(const Twine &path) const {
123   ErrorOr<vfs::Status> status = m_fs->status(path);
124   if (!status)
125     return 0;
126   return status->getSize();
127 }
128 
129 uint32_t FileSystem::GetPermissions(const FileSpec &file_spec) const {
130   return GetPermissions(file_spec.GetPath());
131 }
132 
133 uint32_t FileSystem::GetPermissions(const FileSpec &file_spec,
134                                     std::error_code &ec) const {
135   return GetPermissions(file_spec.GetPath(), ec);
136 }
137 
138 uint32_t FileSystem::GetPermissions(const Twine &path) const {
139   std::error_code ec;
140   return GetPermissions(path, ec);
141 }
142 
143 uint32_t FileSystem::GetPermissions(const Twine &path,
144                                     std::error_code &ec) const {
145   ErrorOr<vfs::Status> status = m_fs->status(path);
146   if (!status) {
147     ec = status.getError();
148     return sys::fs::perms::perms_not_known;
149   }
150   return status->getPermissions();
151 }
152 
153 bool FileSystem::Exists(const Twine &path) const { return m_fs->exists(path); }
154 
155 bool FileSystem::Exists(const FileSpec &file_spec) const {
156   return Exists(file_spec.GetPath());
157 }
158 
159 bool FileSystem::Readable(const Twine &path) const {
160   return GetPermissions(path) & sys::fs::perms::all_read;
161 }
162 
163 bool FileSystem::Readable(const FileSpec &file_spec) const {
164   return Readable(file_spec.GetPath());
165 }
166 
167 bool FileSystem::IsDirectory(const Twine &path) const {
168   ErrorOr<vfs::Status> status = m_fs->status(path);
169   if (!status)
170     return false;
171   return status->isDirectory();
172 }
173 
174 bool FileSystem::IsDirectory(const FileSpec &file_spec) const {
175   return IsDirectory(file_spec.GetPath());
176 }
177 
178 bool FileSystem::IsLocal(const Twine &path) const {
179   bool b = false;
180   m_fs->isLocal(path, b);
181   return b;
182 }
183 
184 bool FileSystem::IsLocal(const FileSpec &file_spec) const {
185   return IsLocal(file_spec.GetPath());
186 }
187 
188 void FileSystem::EnumerateDirectory(Twine path, bool find_directories,
189                                     bool find_files, bool find_other,
190                                     EnumerateDirectoryCallbackType callback,
191                                     void *callback_baton) {
192   std::error_code EC;
193   vfs::recursive_directory_iterator Iter(*m_fs, path, EC);
194   vfs::recursive_directory_iterator End;
195   for (; Iter != End && !EC; Iter.increment(EC)) {
196     const auto &Item = *Iter;
197     ErrorOr<vfs::Status> Status = m_fs->status(Item.path());
198     if (!Status)
199       break;
200     if (!find_files && Status->isRegularFile())
201       continue;
202     if (!find_directories && Status->isDirectory())
203       continue;
204     if (!find_other && Status->isOther())
205       continue;
206 
207     auto Result = callback(callback_baton, Status->getType(), Item.path());
208     if (Result == eEnumerateDirectoryResultQuit)
209       return;
210     if (Result == eEnumerateDirectoryResultNext) {
211       // Default behavior is to recurse. Opt out if the callback doesn't want
212       // this behavior.
213       Iter.no_push();
214     }
215   }
216 }
217 
218 std::error_code FileSystem::MakeAbsolute(SmallVectorImpl<char> &path) const {
219   return m_fs->makeAbsolute(path);
220 }
221 
222 std::error_code FileSystem::MakeAbsolute(FileSpec &file_spec) const {
223   SmallString<128> path;
224   file_spec.GetPath(path, false);
225 
226   auto EC = MakeAbsolute(path);
227   if (EC)
228     return EC;
229 
230   FileSpec new_file_spec(path, file_spec.GetPathStyle());
231   file_spec = new_file_spec;
232   return {};
233 }
234 
235 std::error_code FileSystem::GetRealPath(const Twine &path,
236                                         SmallVectorImpl<char> &output) const {
237   return m_fs->getRealPath(path, output);
238 }
239 
240 void FileSystem::Resolve(SmallVectorImpl<char> &path) {
241   if (path.empty())
242     return;
243 
244   // Resolve tilde in path.
245   SmallString<128> resolved(path.begin(), path.end());
246   StandardTildeExpressionResolver Resolver;
247   Resolver.ResolveFullPath(llvm::StringRef(path.begin(), path.size()),
248                            resolved);
249 
250   // Try making the path absolute if it exists.
251   SmallString<128> absolute(resolved.begin(), resolved.end());
252   MakeAbsolute(absolute);
253 
254   path.clear();
255   if (Exists(absolute)) {
256     path.append(absolute.begin(), absolute.end());
257   } else {
258     path.append(resolved.begin(), resolved.end());
259   }
260 }
261 
262 void FileSystem::Resolve(FileSpec &file_spec) {
263   // Extract path from the FileSpec.
264   SmallString<128> path;
265   file_spec.GetPath(path);
266 
267   // Resolve the path.
268   Resolve(path);
269 
270   // Update the FileSpec with the resolved path.
271   if (file_spec.GetFilename().IsEmpty())
272     file_spec.GetDirectory().SetString(path);
273   else
274     file_spec.SetPath(path);
275   file_spec.SetIsResolved(true);
276 }
277 
278 std::shared_ptr<DataBufferLLVM>
279 FileSystem::CreateDataBuffer(const llvm::Twine &path, uint64_t size,
280                              uint64_t offset) {
281   if (m_collector)
282     m_collector->AddFile(path);
283 
284   const bool is_volatile = !IsLocal(path);
285   const ErrorOr<std::string> external_path = GetExternalPath(path);
286 
287   if (!external_path)
288     return nullptr;
289 
290   std::unique_ptr<llvm::WritableMemoryBuffer> buffer;
291   if (size == 0) {
292     auto buffer_or_error =
293         llvm::WritableMemoryBuffer::getFile(*external_path, -1, is_volatile);
294     if (!buffer_or_error)
295       return nullptr;
296     buffer = std::move(*buffer_or_error);
297   } else {
298     auto buffer_or_error = llvm::WritableMemoryBuffer::getFileSlice(
299         *external_path, size, offset, is_volatile);
300     if (!buffer_or_error)
301       return nullptr;
302     buffer = std::move(*buffer_or_error);
303   }
304   return std::shared_ptr<DataBufferLLVM>(new DataBufferLLVM(std::move(buffer)));
305 }
306 
307 std::shared_ptr<DataBufferLLVM>
308 FileSystem::CreateDataBuffer(const FileSpec &file_spec, uint64_t size,
309                              uint64_t offset) {
310   return CreateDataBuffer(file_spec.GetPath(), size, offset);
311 }
312 
313 bool FileSystem::ResolveExecutableLocation(FileSpec &file_spec) {
314   // If the directory is set there's nothing to do.
315   ConstString directory = file_spec.GetDirectory();
316   if (directory)
317     return false;
318 
319   // We cannot look for a file if there's no file name.
320   ConstString filename = file_spec.GetFilename();
321   if (!filename)
322     return false;
323 
324   // Search for the file on the host.
325   const std::string filename_str(filename.GetCString());
326   llvm::ErrorOr<std::string> error_or_path =
327       llvm::sys::findProgramByName(filename_str);
328   if (!error_or_path)
329     return false;
330 
331   // findProgramByName returns "." if it can't find the file.
332   llvm::StringRef path = *error_or_path;
333   llvm::StringRef parent = llvm::sys::path::parent_path(path);
334   if (parent.empty() || parent == ".")
335     return false;
336 
337   // Make sure that the result exists.
338   FileSpec result(*error_or_path);
339   if (!Exists(result))
340     return false;
341 
342   file_spec = result;
343   return true;
344 }
345 
346 static int OpenWithFS(const FileSystem &fs, const char *path, int flags,
347                       int mode) {
348   return const_cast<FileSystem &>(fs).Open(path, flags, mode);
349 }
350 
351 static int GetOpenFlags(uint32_t options) {
352   const bool read = options & File::eOpenOptionRead;
353   const bool write = options & File::eOpenOptionWrite;
354 
355   int open_flags = 0;
356   if (write) {
357     if (read)
358       open_flags |= O_RDWR;
359     else
360       open_flags |= O_WRONLY;
361 
362     if (options & File::eOpenOptionAppend)
363       open_flags |= O_APPEND;
364 
365     if (options & File::eOpenOptionTruncate)
366       open_flags |= O_TRUNC;
367 
368     if (options & File::eOpenOptionCanCreate)
369       open_flags |= O_CREAT;
370 
371     if (options & File::eOpenOptionCanCreateNewOnly)
372       open_flags |= O_CREAT | O_EXCL;
373   } else if (read) {
374     open_flags |= O_RDONLY;
375 
376 #ifndef _WIN32
377     if (options & File::eOpenOptionDontFollowSymlinks)
378       open_flags |= O_NOFOLLOW;
379 #endif
380   }
381 
382 #ifndef _WIN32
383   if (options & File::eOpenOptionNonBlocking)
384     open_flags |= O_NONBLOCK;
385   if (options & File::eOpenOptionCloseOnExec)
386     open_flags |= O_CLOEXEC;
387 #else
388   open_flags |= O_BINARY;
389 #endif
390 
391   return open_flags;
392 }
393 
394 static mode_t GetOpenMode(uint32_t permissions) {
395   mode_t mode = 0;
396   if (permissions & lldb::eFilePermissionsUserRead)
397     mode |= S_IRUSR;
398   if (permissions & lldb::eFilePermissionsUserWrite)
399     mode |= S_IWUSR;
400   if (permissions & lldb::eFilePermissionsUserExecute)
401     mode |= S_IXUSR;
402   if (permissions & lldb::eFilePermissionsGroupRead)
403     mode |= S_IRGRP;
404   if (permissions & lldb::eFilePermissionsGroupWrite)
405     mode |= S_IWGRP;
406   if (permissions & lldb::eFilePermissionsGroupExecute)
407     mode |= S_IXGRP;
408   if (permissions & lldb::eFilePermissionsWorldRead)
409     mode |= S_IROTH;
410   if (permissions & lldb::eFilePermissionsWorldWrite)
411     mode |= S_IWOTH;
412   if (permissions & lldb::eFilePermissionsWorldExecute)
413     mode |= S_IXOTH;
414   return mode;
415 }
416 
417 Status FileSystem::Open(File &File, const FileSpec &file_spec, uint32_t options,
418                         uint32_t permissions, bool should_close_fd) {
419   if (m_collector)
420     m_collector->AddFile(file_spec);
421 
422   if (File.IsValid())
423     File.Close();
424 
425   const int open_flags = GetOpenFlags(options);
426   const mode_t open_mode =
427       (open_flags & O_CREAT) ? GetOpenMode(permissions) : 0;
428 
429   auto path = GetExternalPath(file_spec);
430   if (!path)
431     return Status(path.getError());
432 
433   int descriptor = llvm::sys::RetryAfterSignal(
434       -1, OpenWithFS, *this, path->c_str(), open_flags, open_mode);
435 
436   Status error;
437   if (!File::DescriptorIsValid(descriptor)) {
438     File.SetDescriptor(descriptor, false);
439     error.SetErrorToErrno();
440   } else {
441     File.SetDescriptor(descriptor, should_close_fd);
442     File.SetOptions(options);
443   }
444   return error;
445 }
446 
447 ErrorOr<std::string> FileSystem::GetExternalPath(const llvm::Twine &path) {
448   if (!m_mapped)
449     return path.str();
450 
451   // If VFS mapped we know the underlying FS is a RedirectingFileSystem.
452   ErrorOr<vfs::RedirectingFileSystem::Entry *> E =
453       static_cast<vfs::RedirectingFileSystem &>(*m_fs).lookupPath(path);
454   if (!E) {
455     if (E.getError() == llvm::errc::no_such_file_or_directory) {
456       return path.str();
457     }
458     return E.getError();
459   }
460 
461   auto *F = dyn_cast<vfs::RedirectingFileSystem::RedirectingFileEntry>(*E);
462   if (!F)
463     return make_error_code(llvm::errc::not_supported);
464 
465   return F->getExternalContentsPath().str();
466 }
467 
468 ErrorOr<std::string> FileSystem::GetExternalPath(const FileSpec &file_spec) {
469   return GetExternalPath(file_spec.GetPath());
470 }
471