LLDB mainline
common/FileSystem.cpp
Go to the documentation of this file.
1//===-- FileSystem.cpp ----------------------------------------------------===//
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
10
12
13#include "llvm/Support/Errc.h"
14#include "llvm/Support/Errno.h"
15#include "llvm/Support/Error.h"
16#include "llvm/Support/FileSystem.h"
17#include "llvm/Support/Path.h"
18#include "llvm/Support/Program.h"
19#include "llvm/Support/Threading.h"
20
21#include <cerrno>
22#include <climits>
23#include <cstdarg>
24#include <cstdio>
25#include <fcntl.h>
26
27#ifdef _WIN32
29#else
30#include <sys/ioctl.h>
31#include <sys/stat.h>
32#include <termios.h>
33#include <unistd.h>
34#endif
35
36#include <algorithm>
37#include <fstream>
38#include <memory>
39#include <optional>
40#include <vector>
41
42using namespace lldb;
43using namespace lldb_private;
44using namespace llvm;
45
47
49 lldbassert(InstanceImpl() && "Already terminated.");
50 InstanceImpl().reset();
51}
52
53std::optional<FileSystem> &FileSystem::InstanceImpl() {
54 static std::optional<FileSystem> g_fs;
55 return g_fs;
56}
57
58vfs::directory_iterator FileSystem::DirBegin(const FileSpec &file_spec,
59 std::error_code &ec) {
60 if (!file_spec) {
61 ec = std::error_code(static_cast<int>(errc::no_such_file_or_directory),
62 std::system_category());
63 return {};
64 }
65 return DirBegin(file_spec.GetPath(), ec);
66}
67
68vfs::directory_iterator FileSystem::DirBegin(const Twine &dir,
69 std::error_code &ec) {
70 return m_fs->dir_begin(dir, ec);
71}
72
73llvm::ErrorOr<vfs::Status>
74FileSystem::GetStatus(const FileSpec &file_spec) const {
75 if (!file_spec)
76 return std::error_code(static_cast<int>(errc::no_such_file_or_directory),
77 std::system_category());
78 return GetStatus(file_spec.GetPath());
79}
80
81llvm::ErrorOr<vfs::Status> FileSystem::GetStatus(const Twine &path) const {
82 return m_fs->status(path);
83}
84
85sys::TimePoint<>
87 if (!file_spec)
88 return sys::TimePoint<>();
89 return GetModificationTime(file_spec.GetPath());
90}
91
92sys::TimePoint<> FileSystem::GetModificationTime(const Twine &path) const {
93 ErrorOr<vfs::Status> status = m_fs->status(path);
94 if (!status)
95 return sys::TimePoint<>();
96 return status->getLastModificationTime();
97}
98
99uint64_t FileSystem::GetByteSize(const FileSpec &file_spec) const {
100 if (!file_spec)
101 return 0;
102 return GetByteSize(file_spec.GetPath());
103}
104
105uint64_t FileSystem::GetByteSize(const Twine &path) const {
106 ErrorOr<vfs::Status> status = m_fs->status(path);
107 if (!status)
108 return 0;
109 return status->getSize();
110}
111
112uint32_t FileSystem::GetPermissions(const FileSpec &file_spec) const {
113 return GetPermissions(file_spec.GetPath());
114}
115
116uint32_t FileSystem::GetPermissions(const FileSpec &file_spec,
117 std::error_code &ec) const {
118 if (!file_spec)
119 return sys::fs::perms::perms_not_known;
120 return GetPermissions(file_spec.GetPath(), ec);
121}
122
123uint32_t FileSystem::GetPermissions(const Twine &path) const {
124 std::error_code ec;
125 return GetPermissions(path, ec);
126}
127
128uint32_t FileSystem::GetPermissions(const Twine &path,
129 std::error_code &ec) const {
130 ErrorOr<vfs::Status> status = m_fs->status(path);
131 if (!status) {
132 ec = status.getError();
133 return sys::fs::perms::perms_not_known;
134 }
135 return status->getPermissions();
136}
137
138bool FileSystem::Exists(const Twine &path) const { return m_fs->exists(path); }
139
140bool FileSystem::Exists(const FileSpec &file_spec) const {
141 return file_spec && Exists(file_spec.GetPath());
142}
143
144bool FileSystem::Readable(const Twine &path) const {
145 return GetPermissions(path) & sys::fs::perms::all_read;
146}
147
148bool FileSystem::Readable(const FileSpec &file_spec) const {
149 return file_spec && Readable(file_spec.GetPath());
150}
151
152bool FileSystem::IsDirectory(const Twine &path) const {
153 ErrorOr<vfs::Status> status = m_fs->status(path);
154 if (!status)
155 return false;
156 return status->isDirectory();
157}
158
159bool FileSystem::IsDirectory(const FileSpec &file_spec) const {
160 return file_spec && IsDirectory(file_spec.GetPath());
161}
162
163bool FileSystem::IsLocal(const Twine &path) const {
164 bool b = false;
165 m_fs->isLocal(path, b);
166 return b;
167}
168
169bool FileSystem::IsLocal(const FileSpec &file_spec) const {
170 return file_spec && IsLocal(file_spec.GetPath());
171}
172
173void FileSystem::EnumerateDirectory(Twine path, bool find_directories,
174 bool find_files, bool find_other,
176 void *callback_baton) {
177 std::error_code EC;
178 vfs::recursive_directory_iterator Iter(*m_fs, path, EC);
179 vfs::recursive_directory_iterator End;
180 for (; Iter != End && !EC; Iter.increment(EC)) {
181 const auto &Item = *Iter;
182 ErrorOr<vfs::Status> Status = m_fs->status(Item.path());
183 if (!Status)
184 continue;
185 if (!find_files && Status->isRegularFile())
186 continue;
187 if (!find_directories && Status->isDirectory())
188 continue;
189 if (!find_other && Status->isOther())
190 continue;
191
192 auto Result = callback(callback_baton, Status->getType(), Item.path());
193 if (Result == eEnumerateDirectoryResultQuit)
194 return;
195 if (Result == eEnumerateDirectoryResultNext) {
196 // Default behavior is to recurse. Opt out if the callback doesn't want
197 // this behavior.
198 Iter.no_push();
199 }
200 }
201}
202
204 return m_fs->makeAbsolute(path);
205}
206
207std::error_code FileSystem::MakeAbsolute(FileSpec &file_spec) const {
208 SmallString<128> path;
209 file_spec.GetPath(path, false);
210
211 auto EC = MakeAbsolute(path);
212 if (EC)
213 return EC;
214
215 FileSpec new_file_spec(path, file_spec.GetPathStyle());
216 file_spec = new_file_spec;
217 return {};
218}
219
220std::error_code FileSystem::GetRealPath(const Twine &path,
221 SmallVectorImpl<char> &output) const {
222 return m_fs->getRealPath(path, output);
223}
224
226 bool force_make_absolute) {
227 if (path.empty())
228 return;
229
230 // Resolve tilde in path.
231 SmallString<128> resolved(path.begin(), path.end());
232 assert(m_tilde_resolver && "must initialize tilde resolver in constructor");
233 m_tilde_resolver->ResolveFullPath(llvm::StringRef(path.begin(), path.size()),
234 resolved);
235
236 // Try making the path absolute if it exists.
237 SmallString<128> absolute(resolved.begin(), resolved.end());
238 MakeAbsolute(absolute);
239
240 path.clear();
241 if (force_make_absolute || Exists(absolute)) {
242 path.append(absolute.begin(), absolute.end());
243 } else {
244 path.append(resolved.begin(), resolved.end());
245 }
246}
247
248void FileSystem::Resolve(FileSpec &file_spec, bool force_make_absolute) {
249 if (!file_spec)
250 return;
251
252 // Extract path from the FileSpec.
253 SmallString<128> path;
254 file_spec.GetPath(path);
255
256 // Resolve the path.
257 Resolve(path, force_make_absolute);
258
259 // Update the FileSpec with the resolved path.
260 if (file_spec.GetFilename().IsEmpty())
261 file_spec.SetDirectory(path);
262 else
263 file_spec.SetPath(path);
264}
265
266template <typename T>
267static std::unique_ptr<T> GetMemoryBuffer(const llvm::Twine &path,
268 uint64_t size, uint64_t offset,
269 bool is_volatile) {
270 std::unique_ptr<T> buffer;
271 if (size == 0) {
272 auto buffer_or_error = T::getFile(path, is_volatile);
273 if (!buffer_or_error)
274 return nullptr;
275 buffer = std::move(*buffer_or_error);
276 } else {
277 auto buffer_or_error = T::getFileSlice(path, size, offset, is_volatile);
278 if (!buffer_or_error)
279 return nullptr;
280 buffer = std::move(*buffer_or_error);
281 }
282 return buffer;
283}
284
285std::shared_ptr<WritableDataBuffer>
286FileSystem::CreateWritableDataBuffer(const llvm::Twine &path, uint64_t size,
287 uint64_t offset) {
288 const bool is_volatile = !IsLocal(path);
289 auto buffer = GetMemoryBuffer<llvm::WritableMemoryBuffer>(path, size, offset,
290 is_volatile);
291 if (!buffer)
292 return {};
293 return std::make_shared<WritableDataBufferLLVM>(std::move(buffer));
294}
295
296std::shared_ptr<DataBuffer>
297FileSystem::CreateDataBuffer(const llvm::Twine &path, uint64_t size,
298 uint64_t offset) {
299 const bool is_volatile = !IsLocal(path);
300 auto buffer =
301 GetMemoryBuffer<llvm::MemoryBuffer>(path, size, offset, is_volatile);
302 if (!buffer)
303 return {};
304 return std::make_shared<DataBufferLLVM>(std::move(buffer));
305}
306
307std::shared_ptr<WritableDataBuffer>
308FileSystem::CreateWritableDataBuffer(const FileSpec &file_spec, uint64_t size,
309 uint64_t offset) {
310 return CreateWritableDataBuffer(file_spec.GetPath(), size, offset);
311}
312
313std::shared_ptr<DataBuffer>
314FileSystem::CreateDataBuffer(const FileSpec &file_spec, uint64_t size,
315 uint64_t offset) {
316 return CreateDataBuffer(file_spec.GetPath(), size, offset);
317}
318
320 // If the directory is set there's nothing to do.
321 ConstString directory = file_spec.GetDirectory();
322 if (directory)
323 return false;
324
325 // We cannot look for a file if there's no file name.
326 ConstString filename = file_spec.GetFilename();
327 if (!filename)
328 return false;
329
330 // Search for the file on the host.
331 const std::string filename_str(filename.GetCString());
332 llvm::ErrorOr<std::string> error_or_path =
333 llvm::sys::findProgramByName(filename_str);
334 if (!error_or_path)
335 return false;
336
337 // findProgramByName returns "." if it can't find the file.
338 llvm::StringRef path = *error_or_path;
339 llvm::StringRef parent = llvm::sys::path::parent_path(path);
340 if (parent.empty() || parent == ".")
341 return false;
342
343 // Make sure that the result exists.
344 FileSpec result(*error_or_path);
345 if (!Exists(result))
346 return false;
347
348 file_spec = result;
349 return true;
350}
351
353 if (!m_home_directory.empty()) {
354 path.assign(m_home_directory.begin(), m_home_directory.end());
355 return true;
356 }
357 return llvm::sys::path::home_directory(path);
358}
359
361 SmallString<128> home_dir;
362 if (!GetHomeDirectory(home_dir))
363 return false;
364 file_spec.SetPath(home_dir);
365 return true;
366}
367
368static int OpenWithFS(const FileSystem &fs, const char *path, int flags,
369 int mode) {
370 return const_cast<FileSystem &>(fs).Open(path, flags, mode);
371}
372
373static int GetOpenFlags(File::OpenOptions options) {
374 int open_flags = 0;
380 open_flags |= O_RDWR;
381 else
382 open_flags |= O_WRONLY;
383
384 if (options & File::eOpenOptionAppend)
385 open_flags |= O_APPEND;
386
387 if (options & File::eOpenOptionTruncate)
388 open_flags |= O_TRUNC;
389
390 if (options & File::eOpenOptionCanCreate)
391 open_flags |= O_CREAT;
392
394 open_flags |= O_CREAT | O_EXCL;
395 } else if (rw == File::eOpenOptionReadOnly) {
396 open_flags |= O_RDONLY;
397
398#ifndef _WIN32
400 open_flags |= O_NOFOLLOW;
401#endif
402 }
403
404#ifndef _WIN32
405 if (options & File::eOpenOptionNonBlocking)
406 open_flags |= O_NONBLOCK;
407 if (options & File::eOpenOptionCloseOnExec)
408 open_flags |= O_CLOEXEC;
409#else
410 open_flags |= O_BINARY;
411#endif
412
413 return open_flags;
414}
415
416static mode_t GetOpenMode(uint32_t permissions) {
417 mode_t mode = 0;
418 if (permissions & lldb::eFilePermissionsUserRead)
419 mode |= S_IRUSR;
420 if (permissions & lldb::eFilePermissionsUserWrite)
421 mode |= S_IWUSR;
422 if (permissions & lldb::eFilePermissionsUserExecute)
423 mode |= S_IXUSR;
424 if (permissions & lldb::eFilePermissionsGroupRead)
425 mode |= S_IRGRP;
426 if (permissions & lldb::eFilePermissionsGroupWrite)
427 mode |= S_IWGRP;
428 if (permissions & lldb::eFilePermissionsGroupExecute)
429 mode |= S_IXGRP;
430 if (permissions & lldb::eFilePermissionsWorldRead)
431 mode |= S_IROTH;
432 if (permissions & lldb::eFilePermissionsWorldWrite)
433 mode |= S_IWOTH;
434 if (permissions & lldb::eFilePermissionsWorldExecute)
435 mode |= S_IXOTH;
436 return mode;
437}
438
439Expected<FileUP> FileSystem::Open(const FileSpec &file_spec,
440 File::OpenOptions options,
441 uint32_t permissions, bool should_close_fd) {
442 const int open_flags = GetOpenFlags(options);
443 const mode_t open_mode =
444 (open_flags & O_CREAT) ? GetOpenMode(permissions) : 0;
445
446 auto path = file_spec.GetPath();
447
448 int descriptor = llvm::sys::RetryAfterSignal(
449 -1, OpenWithFS, *this, path.c_str(), open_flags, open_mode);
450
451 if (!File::DescriptorIsValid(descriptor))
452 return llvm::errorCodeToError(
453 std::error_code(errno, std::system_category()));
454
455 auto file = std::unique_ptr<File>(
456 new NativeFile(descriptor, options, should_close_fd));
457 assert(file->IsValid());
458 return std::move(file);
459}
460
461void FileSystem::SetHomeDirectory(std::string home_directory) {
462 m_home_directory = std::move(home_directory);
463}
464
466 return RemoveFile(file_spec.GetPath());
467}
468
469Status FileSystem::RemoveFile(const llvm::Twine &path) {
470 return Status(llvm::sys::fs::remove(path));
471}
#define lldbassert(x)
Definition LLDBAssert.h:16
A uniqued constant string class.
Definition ConstString.h:40
bool IsEmpty() const
Test for empty string.
const char * GetCString() const
Get the string value as a C string.
A file utility class.
Definition FileSpec.h:57
void SetDirectory(ConstString directory)
Directory string set accessor.
Definition FileSpec.cpp:342
const ConstString & GetFilename() const
Filename string const get accessor.
Definition FileSpec.h:251
const ConstString & GetDirectory() const
Directory string const get accessor.
Definition FileSpec.h:234
void SetPath(llvm::StringRef p)
Temporary helper for FileSystem change.
Definition FileSpec.h:290
Style GetPathStyle() const
Definition FileSpec.cpp:340
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:374
uint64_t GetByteSize(const FileSpec &file_spec) const
Returns the on-disk size of the given file in bytes.
bool GetHomeDirectory(llvm::SmallVectorImpl< char > &path) const
Get the user home directory.
void EnumerateDirectory(llvm::Twine path, bool find_directories, bool find_files, bool find_other, EnumerateDirectoryCallbackType callback, void *callback_baton)
@ eEnumerateDirectoryResultNext
Enumerate next entry in the current directory.
Definition FileSystem.h:182
@ eEnumerateDirectoryResultQuit
Stop directory enumerations at any level.
Definition FileSystem.h:187
llvm::sys::TimePoint GetModificationTime(const FileSpec &file_spec) const
Returns the modification time of the given file.
EnumerateDirectoryResult(* EnumerateDirectoryCallbackType)(void *baton, llvm::sys::fs::file_type file_type, llvm::StringRef)
Definition FileSystem.h:190
std::string m_home_directory
Definition FileSystem.h:215
bool ResolveExecutableLocation(FileSpec &file_spec)
Call into the Host to see if it can help find the file.
bool Exists(const FileSpec &file_spec) const
Returns whether the given file exists.
int Open(const char *path, int flags, int mode=0600)
Wraps open in a platform-independent way.
std::error_code GetRealPath(const llvm::Twine &path, llvm::SmallVectorImpl< char > &output) const
void SetHomeDirectory(std::string home_directory)
static std::optional< FileSystem > & InstanceImpl()
std::unique_ptr< TildeExpressionResolver > m_tilde_resolver
Definition FileSystem.h:214
uint32_t GetPermissions(const FileSpec &file_spec) const
Return the current permissions of the given file.
llvm::vfs::directory_iterator DirBegin(const FileSpec &file_spec, std::error_code &ec)
Get a directory iterator.
std::error_code MakeAbsolute(llvm::SmallVectorImpl< char > &path) const
Make the given file path absolute.
llvm::ErrorOr< llvm::vfs::Status > GetStatus(const FileSpec &file_spec) const
Returns the Status object for the given file.
llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > m_fs
Definition FileSystem.h:213
std::shared_ptr< WritableDataBuffer > CreateWritableDataBuffer(const llvm::Twine &path, uint64_t size=0, uint64_t offset=0)
bool Readable(const FileSpec &file_spec) const
Returns whether the given file is readable.
bool IsDirectory(const FileSpec &file_spec) const
Returns whether the given path is a directory.
static FileSystem & Instance()
void Resolve(llvm::SmallVectorImpl< char > &path, bool force_make_absolute=false)
Resolve path to make it canonical.
Status RemoveFile(const FileSpec &file_spec)
Remove a single file.
bool IsLocal(const FileSpec &file_spec) const
Returns whether the given path is local to the file system.
std::shared_ptr< DataBuffer > CreateDataBuffer(const llvm::Twine &path, uint64_t size=0, uint64_t offset=0)
Create memory buffer from path.
static bool DescriptorIsValid(int descriptor)
Definition File.h:74
@ eOpenOptionReadOnly
Definition File.h:51
@ eOpenOptionCanCreateNewOnly
Definition File.h:58
@ eOpenOptionReadWrite
Definition File.h:53
@ eOpenOptionWriteOnly
Definition File.h:52
@ eOpenOptionCanCreate
Definition File.h:56
@ eOpenOptionCloseOnExec
Definition File.h:63
@ eOpenOptionDontFollowSymlinks
Definition File.h:62
@ eOpenOptionTruncate
Definition File.h:57
@ eOpenOptionNonBlocking
Definition File.h:61
An error handling class.
Definition Status.h:118
static int GetOpenFlags(File::OpenOptions options)
static mode_t GetOpenMode(uint32_t permissions)
static std::unique_ptr< T > GetMemoryBuffer(const llvm::Twine &path, uint64_t size, uint64_t offset, bool is_volatile)
static int OpenWithFS(const FileSystem &fs, const char *path, int flags, int mode)
A class that represents a running process on the host machine.
#define S_IXGRP
#define S_IROTH
#define O_NONBLOCK
#define S_IXOTH
#define S_IRGRP
#define S_IWOTH
#define S_IRUSR
#define S_IWUSR
#define S_IWGRP
#define S_IXUSR