1 //===-- FileSystem.cpp ----------------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "lldb/Host/FileSystem.h"
11 #include "lldb/Utility/LLDBAssert.h"
12 #include "lldb/Utility/TildeExpressionResolver.h"
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"
29 #include "lldb/Host/windows/windows.h"
31 #include <sys/ioctl.h>
42 using namespace lldb_private;
45 FileSystem &FileSystem::Instance() { return *InstanceImpl(); }
47 void FileSystem::Initialize() {
48 lldbassert(!InstanceImpl() && "Already initialized.");
49 InstanceImpl().emplace();
52 void FileSystem::Initialize(std::shared_ptr<FileCollector> collector) {
53 lldbassert(!InstanceImpl() && "Already initialized.");
54 InstanceImpl().emplace(collector);
57 llvm::Error FileSystem::Initialize(const FileSpec &mapping) {
58 lldbassert(!InstanceImpl() && "Already initialized.");
60 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> buffer =
61 llvm::vfs::getRealFileSystem()->getBufferForFile(mapping.GetPath());
64 return llvm::errorCodeToError(buffer.getError());
66 InstanceImpl().emplace(llvm::vfs::getVFSFromYAML(std::move(buffer.get()),
67 nullptr, mapping.GetPath()),
70 return llvm::Error::success();
73 void FileSystem::Initialize(IntrusiveRefCntPtr<vfs::FileSystem> fs) {
74 lldbassert(!InstanceImpl() && "Already initialized.");
75 InstanceImpl().emplace(fs);
78 void FileSystem::Terminate() {
79 lldbassert(InstanceImpl() && "Already terminated.");
80 InstanceImpl().reset();
83 Optional<FileSystem> &FileSystem::InstanceImpl() {
84 static Optional<FileSystem> g_fs;
88 vfs::directory_iterator FileSystem::DirBegin(const FileSpec &file_spec,
89 std::error_code &ec) {
91 ec = std::error_code(static_cast<int>(errc::no_such_file_or_directory),
92 std::system_category());
95 return DirBegin(file_spec.GetPath(), ec);
98 vfs::directory_iterator FileSystem::DirBegin(const Twine &dir,
99 std::error_code &ec) {
100 return m_fs->dir_begin(dir, ec);
103 llvm::ErrorOr<vfs::Status>
104 FileSystem::GetStatus(const FileSpec &file_spec) const {
106 return std::error_code(static_cast<int>(errc::no_such_file_or_directory),
107 std::system_category());
108 return GetStatus(file_spec.GetPath());
111 llvm::ErrorOr<vfs::Status> FileSystem::GetStatus(const Twine &path) const {
112 return m_fs->status(path);
116 FileSystem::GetModificationTime(const FileSpec &file_spec) const {
118 return sys::TimePoint<>();
119 return GetModificationTime(file_spec.GetPath());
122 sys::TimePoint<> FileSystem::GetModificationTime(const Twine &path) const {
123 ErrorOr<vfs::Status> status = m_fs->status(path);
125 return sys::TimePoint<>();
126 return status->getLastModificationTime();
129 uint64_t FileSystem::GetByteSize(const FileSpec &file_spec) const {
132 return GetByteSize(file_spec.GetPath());
135 uint64_t FileSystem::GetByteSize(const Twine &path) const {
136 ErrorOr<vfs::Status> status = m_fs->status(path);
139 return status->getSize();
142 uint32_t FileSystem::GetPermissions(const FileSpec &file_spec) const {
143 return GetPermissions(file_spec.GetPath());
146 uint32_t FileSystem::GetPermissions(const FileSpec &file_spec,
147 std::error_code &ec) const {
149 return sys::fs::perms::perms_not_known;
150 return GetPermissions(file_spec.GetPath(), ec);
153 uint32_t FileSystem::GetPermissions(const Twine &path) const {
155 return GetPermissions(path, ec);
158 uint32_t FileSystem::GetPermissions(const Twine &path,
159 std::error_code &ec) const {
160 ErrorOr<vfs::Status> status = m_fs->status(path);
162 ec = status.getError();
163 return sys::fs::perms::perms_not_known;
165 return status->getPermissions();
168 bool FileSystem::Exists(const Twine &path) const { return m_fs->exists(path); }
170 bool FileSystem::Exists(const FileSpec &file_spec) const {
171 return file_spec && Exists(file_spec.GetPath());
174 bool FileSystem::Readable(const Twine &path) const {
175 return GetPermissions(path) & sys::fs::perms::all_read;
178 bool FileSystem::Readable(const FileSpec &file_spec) const {
179 return file_spec && Readable(file_spec.GetPath());
182 bool FileSystem::IsDirectory(const Twine &path) const {
183 ErrorOr<vfs::Status> status = m_fs->status(path);
186 return status->isDirectory();
189 bool FileSystem::IsDirectory(const FileSpec &file_spec) const {
190 return file_spec && IsDirectory(file_spec.GetPath());
193 bool FileSystem::IsLocal(const Twine &path) const {
195 m_fs->isLocal(path, b);
199 bool FileSystem::IsLocal(const FileSpec &file_spec) const {
200 return file_spec && IsLocal(file_spec.GetPath());
203 void FileSystem::EnumerateDirectory(Twine path, bool find_directories,
204 bool find_files, bool find_other,
205 EnumerateDirectoryCallbackType callback,
206 void *callback_baton) {
208 vfs::recursive_directory_iterator Iter(*m_fs, path, EC);
209 vfs::recursive_directory_iterator End;
210 for (; Iter != End && !EC; Iter.increment(EC)) {
211 const auto &Item = *Iter;
212 ErrorOr<vfs::Status> Status = m_fs->status(Item.path());
215 if (!find_files && Status->isRegularFile())
217 if (!find_directories && Status->isDirectory())
219 if (!find_other && Status->isOther())
222 auto Result = callback(callback_baton, Status->getType(), Item.path());
223 if (Result == eEnumerateDirectoryResultQuit)
225 if (Result == eEnumerateDirectoryResultNext) {
226 // Default behavior is to recurse. Opt out if the callback doesn't want
233 std::error_code FileSystem::MakeAbsolute(SmallVectorImpl<char> &path) const {
234 return m_fs->makeAbsolute(path);
237 std::error_code FileSystem::MakeAbsolute(FileSpec &file_spec) const {
238 SmallString<128> path;
239 file_spec.GetPath(path, false);
241 auto EC = MakeAbsolute(path);
245 FileSpec new_file_spec(path, file_spec.GetPathStyle());
246 file_spec = new_file_spec;
250 std::error_code FileSystem::GetRealPath(const Twine &path,
251 SmallVectorImpl<char> &output) const {
252 return m_fs->getRealPath(path, output);
255 void FileSystem::Resolve(SmallVectorImpl<char> &path) {
259 // Resolve tilde in path.
260 SmallString<128> resolved(path.begin(), path.end());
261 StandardTildeExpressionResolver Resolver;
262 Resolver.ResolveFullPath(llvm::StringRef(path.begin(), path.size()),
265 // Try making the path absolute if it exists.
266 SmallString<128> absolute(resolved.begin(), resolved.end());
267 MakeAbsolute(absolute);
270 if (Exists(absolute)) {
271 path.append(absolute.begin(), absolute.end());
273 path.append(resolved.begin(), resolved.end());
277 void FileSystem::Resolve(FileSpec &file_spec) {
281 // Extract path from the FileSpec.
282 SmallString<128> path;
283 file_spec.GetPath(path);
288 // Update the FileSpec with the resolved path.
289 if (file_spec.GetFilename().IsEmpty())
290 file_spec.GetDirectory().SetString(path);
292 file_spec.SetPath(path);
293 file_spec.SetIsResolved(true);
296 std::shared_ptr<DataBufferLLVM>
297 FileSystem::CreateDataBuffer(const llvm::Twine &path, uint64_t size,
301 const bool is_volatile = !IsLocal(path);
302 const ErrorOr<std::string> external_path = GetExternalPath(path);
307 std::unique_ptr<llvm::WritableMemoryBuffer> buffer;
309 auto buffer_or_error =
310 llvm::WritableMemoryBuffer::getFile(*external_path, -1, is_volatile);
311 if (!buffer_or_error)
313 buffer = std::move(*buffer_or_error);
315 auto buffer_or_error = llvm::WritableMemoryBuffer::getFileSlice(
316 *external_path, size, offset, is_volatile);
317 if (!buffer_or_error)
319 buffer = std::move(*buffer_or_error);
321 return std::shared_ptr<DataBufferLLVM>(new DataBufferLLVM(std::move(buffer)));
324 std::shared_ptr<DataBufferLLVM>
325 FileSystem::CreateDataBuffer(const FileSpec &file_spec, uint64_t size,
327 return CreateDataBuffer(file_spec.GetPath(), size, offset);
330 bool FileSystem::ResolveExecutableLocation(FileSpec &file_spec) {
331 // If the directory is set there's nothing to do.
332 ConstString directory = file_spec.GetDirectory();
336 // We cannot look for a file if there's no file name.
337 ConstString filename = file_spec.GetFilename();
341 // Search for the file on the host.
342 const std::string filename_str(filename.GetCString());
343 llvm::ErrorOr<std::string> error_or_path =
344 llvm::sys::findProgramByName(filename_str);
348 // findProgramByName returns "." if it can't find the file.
349 llvm::StringRef path = *error_or_path;
350 llvm::StringRef parent = llvm::sys::path::parent_path(path);
351 if (parent.empty() || parent == ".")
354 // Make sure that the result exists.
355 FileSpec result(*error_or_path);
363 static int OpenWithFS(const FileSystem &fs, const char *path, int flags,
365 return const_cast<FileSystem &>(fs).Open(path, flags, mode);
368 static int GetOpenFlags(uint32_t options) {
369 const bool read = options & File::eOpenOptionRead;
370 const bool write = options & File::eOpenOptionWrite;
375 open_flags |= O_RDWR;
377 open_flags |= O_WRONLY;
379 if (options & File::eOpenOptionAppend)
380 open_flags |= O_APPEND;
382 if (options & File::eOpenOptionTruncate)
383 open_flags |= O_TRUNC;
385 if (options & File::eOpenOptionCanCreate)
386 open_flags |= O_CREAT;
388 if (options & File::eOpenOptionCanCreateNewOnly)
389 open_flags |= O_CREAT | O_EXCL;
391 open_flags |= O_RDONLY;
394 if (options & File::eOpenOptionDontFollowSymlinks)
395 open_flags |= O_NOFOLLOW;
400 if (options & File::eOpenOptionNonBlocking)
401 open_flags |= O_NONBLOCK;
402 if (options & File::eOpenOptionCloseOnExec)
403 open_flags |= O_CLOEXEC;
405 open_flags |= O_BINARY;
411 static mode_t GetOpenMode(uint32_t permissions) {
413 if (permissions & lldb::eFilePermissionsUserRead)
415 if (permissions & lldb::eFilePermissionsUserWrite)
417 if (permissions & lldb::eFilePermissionsUserExecute)
419 if (permissions & lldb::eFilePermissionsGroupRead)
421 if (permissions & lldb::eFilePermissionsGroupWrite)
423 if (permissions & lldb::eFilePermissionsGroupExecute)
425 if (permissions & lldb::eFilePermissionsWorldRead)
427 if (permissions & lldb::eFilePermissionsWorldWrite)
429 if (permissions & lldb::eFilePermissionsWorldExecute)
434 Expected<FileUP> FileSystem::Open(const FileSpec &file_spec,
435 File::OpenOptions options,
436 uint32_t permissions, bool should_close_fd) {
437 Collect(file_spec.GetPath());
439 const int open_flags = GetOpenFlags(options);
440 const mode_t open_mode =
441 (open_flags & O_CREAT) ? GetOpenMode(permissions) : 0;
443 auto path = GetExternalPath(file_spec);
445 return errorCodeToError(path.getError());
447 int descriptor = llvm::sys::RetryAfterSignal(
448 -1, OpenWithFS, *this, path->c_str(), open_flags, open_mode);
450 if (!File::DescriptorIsValid(descriptor))
451 return llvm::errorCodeToError(
452 std::error_code(errno, std::system_category()));
454 auto file = std::unique_ptr<File>(
455 new NativeFile(descriptor, options, should_close_fd));
456 assert(file->IsValid());
457 return std::move(file);
460 ErrorOr<std::string> FileSystem::GetExternalPath(const llvm::Twine &path) {
464 // If VFS mapped we know the underlying FS is a RedirectingFileSystem.
465 ErrorOr<vfs::RedirectingFileSystem::Entry *> E =
466 static_cast<vfs::RedirectingFileSystem &>(*m_fs).lookupPath(path);
468 if (E.getError() == llvm::errc::no_such_file_or_directory) {
474 auto *F = dyn_cast<vfs::RedirectingFileSystem::RedirectingFileEntry>(*E);
476 return make_error_code(llvm::errc::not_supported);
478 return F->getExternalContentsPath().str();
481 ErrorOr<std::string> FileSystem::GetExternalPath(const FileSpec &file_spec) {
482 return GetExternalPath(file_spec.GetPath());
485 void FileSystem::Collect(const FileSpec &file_spec) {
486 Collect(file_spec.GetPath());
489 void FileSystem::Collect(const llvm::Twine &file) {
493 if (llvm::sys::fs::is_directory(file))
494 m_collector->addDirectory(file);
496 m_collector->addFile(file);