[MemProf] Templatize CallStackRadixTreeBuilder (NFC) (#117014)
[llvm-project.git] / libcxx / src / filesystem / posix_compat.h
blobb41c004341af3a69b21a66f4668a73cbed6968cc
1 //===----------------------------------------------------------------------===//
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 //===----------------------------------------------------------------------===//
9 //
10 // POSIX-like portability helper functions.
12 // These generally behave like the proper posix functions, with these
13 // exceptions:
14 // On Windows, they take paths in wchar_t* form, instead of char* form.
15 // The symlink() function is split into two frontends, symlink_file()
16 // and symlink_dir().
18 // These are provided within an anonymous namespace within the detail
19 // namespace - callers need to include this header and call them as
20 // detail::function(), regardless of platform.
23 #ifndef POSIX_COMPAT_H
24 #define POSIX_COMPAT_H
26 #include <__assert>
27 #include <__config>
28 #include <filesystem>
30 #include "error.h"
31 #include "time_utils.h"
33 #if defined(_LIBCPP_WIN32API)
34 # define WIN32_LEAN_AND_MEAN
35 # define NOMINMAX
36 # include <io.h>
37 # include <windows.h>
38 # include <winioctl.h>
39 #else
40 # include <fcntl.h>
41 # include <sys/stat.h>
42 # include <sys/statvfs.h>
43 # include <sys/time.h>
44 # include <unistd.h>
45 #endif
46 #include <stdlib.h>
47 #include <time.h>
49 #if defined(_LIBCPP_WIN32API)
50 // This struct isn't defined in the normal Windows SDK, but only in the
51 // Windows Driver Kit.
52 struct LIBCPP_REPARSE_DATA_BUFFER {
53 unsigned long ReparseTag;
54 unsigned short ReparseDataLength;
55 unsigned short Reserved;
56 union {
57 struct {
58 unsigned short SubstituteNameOffset;
59 unsigned short SubstituteNameLength;
60 unsigned short PrintNameOffset;
61 unsigned short PrintNameLength;
62 unsigned long Flags;
63 wchar_t PathBuffer[1];
64 } SymbolicLinkReparseBuffer;
65 struct {
66 unsigned short SubstituteNameOffset;
67 unsigned short SubstituteNameLength;
68 unsigned short PrintNameOffset;
69 unsigned short PrintNameLength;
70 wchar_t PathBuffer[1];
71 } MountPointReparseBuffer;
72 struct {
73 unsigned char DataBuffer[1];
74 } GenericReparseBuffer;
77 #endif
79 _LIBCPP_BEGIN_NAMESPACE_FILESYSTEM
81 namespace detail {
83 #if defined(_LIBCPP_WIN32API)
85 // Various C runtime header sets provide more or less of these. As we
86 // provide our own implementation, undef all potential defines from the
87 // C runtime headers and provide a complete set of macros of our own.
89 # undef _S_IFMT
90 # undef _S_IFDIR
91 # undef _S_IFCHR
92 # undef _S_IFIFO
93 # undef _S_IFREG
94 # undef _S_IFBLK
95 # undef _S_IFLNK
96 # undef _S_IFSOCK
98 # define _S_IFMT 0xF000
99 # define _S_IFDIR 0x4000
100 # define _S_IFCHR 0x2000
101 # define _S_IFIFO 0x1000
102 # define _S_IFREG 0x8000
103 # define _S_IFBLK 0x6000
104 # define _S_IFLNK 0xA000
105 # define _S_IFSOCK 0xC000
107 # undef S_ISDIR
108 # undef S_ISFIFO
109 # undef S_ISCHR
110 # undef S_ISREG
111 # undef S_ISLNK
112 # undef S_ISBLK
113 # undef S_ISSOCK
115 # define S_ISDIR(m) (((m) & _S_IFMT) == _S_IFDIR)
116 # define S_ISCHR(m) (((m) & _S_IFMT) == _S_IFCHR)
117 # define S_ISFIFO(m) (((m) & _S_IFMT) == _S_IFIFO)
118 # define S_ISREG(m) (((m) & _S_IFMT) == _S_IFREG)
119 # define S_ISBLK(m) (((m) & _S_IFMT) == _S_IFBLK)
120 # define S_ISLNK(m) (((m) & _S_IFMT) == _S_IFLNK)
121 # define S_ISSOCK(m) (((m) & _S_IFMT) == _S_IFSOCK)
123 # define O_NONBLOCK 0
125 inline int set_errno(int e = GetLastError()) {
126 errno = static_cast<int>(__win_err_to_errc(e));
127 return -1;
130 class WinHandle {
131 public:
132 WinHandle(const wchar_t* p, DWORD access, DWORD flags) {
133 h = CreateFileW(
135 access,
136 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
137 nullptr,
138 OPEN_EXISTING,
139 FILE_FLAG_BACKUP_SEMANTICS | flags,
140 nullptr);
142 ~WinHandle() {
143 if (h != INVALID_HANDLE_VALUE)
144 CloseHandle(h);
146 operator HANDLE() const { return h; }
147 operator bool() const { return h != INVALID_HANDLE_VALUE; }
149 private:
150 HANDLE h;
153 inline int stat_handle(HANDLE h, StatT* buf) {
154 FILE_BASIC_INFO basic;
155 if (!GetFileInformationByHandleEx(h, FileBasicInfo, &basic, sizeof(basic)))
156 return set_errno();
157 memset(buf, 0, sizeof(*buf));
158 buf->st_mtim = filetime_to_timespec(basic.LastWriteTime);
159 buf->st_atim = filetime_to_timespec(basic.LastAccessTime);
160 buf->st_mode = 0555; // Read-only
161 if (!(basic.FileAttributes & FILE_ATTRIBUTE_READONLY))
162 buf->st_mode |= 0222; // Write
163 if (basic.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
164 buf->st_mode |= _S_IFDIR;
165 } else {
166 buf->st_mode |= _S_IFREG;
168 if (basic.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
169 FILE_ATTRIBUTE_TAG_INFO tag;
170 if (!GetFileInformationByHandleEx(h, FileAttributeTagInfo, &tag, sizeof(tag)))
171 return set_errno();
172 if (tag.ReparseTag == IO_REPARSE_TAG_SYMLINK)
173 buf->st_mode = (buf->st_mode & ~_S_IFMT) | _S_IFLNK;
175 FILE_STANDARD_INFO standard;
176 if (!GetFileInformationByHandleEx(h, FileStandardInfo, &standard, sizeof(standard)))
177 return set_errno();
178 buf->st_nlink = standard.NumberOfLinks;
179 buf->st_size = standard.EndOfFile.QuadPart;
180 BY_HANDLE_FILE_INFORMATION info;
181 if (!GetFileInformationByHandle(h, &info))
182 return set_errno();
183 buf->st_dev = info.dwVolumeSerialNumber;
184 memcpy(&buf->st_ino.id[0], &info.nFileIndexHigh, 4);
185 memcpy(&buf->st_ino.id[4], &info.nFileIndexLow, 4);
186 return 0;
189 inline int stat_file(const wchar_t* path, StatT* buf, DWORD flags) {
190 WinHandle h(path, FILE_READ_ATTRIBUTES, flags);
191 if (!h)
192 return set_errno();
193 int ret = stat_handle(h, buf);
194 return ret;
197 inline int stat(const wchar_t* path, StatT* buf) { return stat_file(path, buf, 0); }
199 inline int lstat(const wchar_t* path, StatT* buf) { return stat_file(path, buf, FILE_FLAG_OPEN_REPARSE_POINT); }
201 inline int fstat(int fd, StatT* buf) {
202 HANDLE h = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
203 return stat_handle(h, buf);
206 inline int mkdir(const wchar_t* path, int permissions) {
207 (void)permissions;
208 if (!CreateDirectoryW(path, nullptr))
209 return set_errno();
210 return 0;
213 inline int symlink_file_dir(const wchar_t* oldname, const wchar_t* newname, bool is_dir) {
214 path dest(oldname);
215 dest.make_preferred();
216 oldname = dest.c_str();
217 DWORD flags = is_dir ? SYMBOLIC_LINK_FLAG_DIRECTORY : 0;
218 if (CreateSymbolicLinkW(newname, oldname, flags | SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE))
219 return 0;
220 int e = GetLastError();
221 if (e != ERROR_INVALID_PARAMETER)
222 return set_errno(e);
223 if (CreateSymbolicLinkW(newname, oldname, flags))
224 return 0;
225 return set_errno();
228 inline int symlink_file(const wchar_t* oldname, const wchar_t* newname) {
229 return symlink_file_dir(oldname, newname, false);
232 inline int symlink_dir(const wchar_t* oldname, const wchar_t* newname) {
233 return symlink_file_dir(oldname, newname, true);
236 inline int link(const wchar_t* oldname, const wchar_t* newname) {
237 if (CreateHardLinkW(newname, oldname, nullptr))
238 return 0;
239 return set_errno();
242 inline int remove(const wchar_t* path) {
243 detail::WinHandle h(path, DELETE, FILE_FLAG_OPEN_REPARSE_POINT);
244 if (!h)
245 return set_errno();
246 FILE_DISPOSITION_INFO info;
247 info.DeleteFile = TRUE;
248 if (!SetFileInformationByHandle(h, FileDispositionInfo, &info, sizeof(info)))
249 return set_errno();
250 return 0;
253 inline int truncate_handle(HANDLE h, off_t length) {
254 LARGE_INTEGER size_param;
255 size_param.QuadPart = length;
256 if (!SetFilePointerEx(h, size_param, 0, FILE_BEGIN))
257 return set_errno();
258 if (!SetEndOfFile(h))
259 return set_errno();
260 return 0;
263 inline int ftruncate(int fd, off_t length) {
264 HANDLE h = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
265 return truncate_handle(h, length);
268 inline int truncate(const wchar_t* path, off_t length) {
269 detail::WinHandle h(path, GENERIC_WRITE, 0);
270 if (!h)
271 return set_errno();
272 return truncate_handle(h, length);
275 inline int rename(const wchar_t* from, const wchar_t* to) {
276 if (!(MoveFileExW(from, to, MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)))
277 return set_errno();
278 return 0;
281 inline int chdir(const wchar_t* path) {
282 if (!SetCurrentDirectoryW(path))
283 return set_errno();
284 return 0;
287 struct StatVFS {
288 uint64_t f_frsize;
289 uint64_t f_blocks;
290 uint64_t f_bfree;
291 uint64_t f_bavail;
294 inline int statvfs(const wchar_t* p, StatVFS* buf) {
295 path dir = p;
296 while (true) {
297 error_code local_ec;
298 const file_status st = status(dir, local_ec);
299 if (!exists(st) || is_directory(st))
300 break;
301 path parent = dir.parent_path();
302 if (parent == dir) {
303 errno = ENOENT;
304 return -1;
306 dir = parent;
308 ULARGE_INTEGER free_bytes_available_to_caller, total_number_of_bytes, total_number_of_free_bytes;
309 if (!GetDiskFreeSpaceExW(
310 dir.c_str(), &free_bytes_available_to_caller, &total_number_of_bytes, &total_number_of_free_bytes))
311 return set_errno();
312 buf->f_frsize = 1;
313 buf->f_blocks = total_number_of_bytes.QuadPart;
314 buf->f_bfree = total_number_of_free_bytes.QuadPart;
315 buf->f_bavail = free_bytes_available_to_caller.QuadPart;
316 return 0;
319 inline wchar_t* getcwd([[maybe_unused]] wchar_t* in_buf, [[maybe_unused]] size_t in_size) {
320 // Only expected to be used with us allocating the buffer.
321 _LIBCPP_ASSERT_INTERNAL(in_buf == nullptr, "Windows getcwd() assumes in_buf==nullptr");
322 _LIBCPP_ASSERT_INTERNAL(in_size == 0, "Windows getcwd() assumes in_size==0");
324 size_t buff_size = MAX_PATH + 10;
325 std::unique_ptr<wchar_t, decltype(&::free)> buff(static_cast<wchar_t*>(malloc(buff_size * sizeof(wchar_t))), &::free);
326 DWORD retval = GetCurrentDirectoryW(buff_size, buff.get());
327 if (retval > buff_size) {
328 buff_size = retval;
329 buff.reset(static_cast<wchar_t*>(malloc(buff_size * sizeof(wchar_t))));
330 retval = GetCurrentDirectoryW(buff_size, buff.get());
332 if (!retval) {
333 set_errno();
334 return nullptr;
336 return buff.release();
339 inline wchar_t* realpath(const wchar_t* path, [[maybe_unused]] wchar_t* resolved_name) {
340 // Only expected to be used with us allocating the buffer.
341 _LIBCPP_ASSERT_INTERNAL(resolved_name == nullptr, "Windows realpath() assumes a null resolved_name");
343 WinHandle h(path, FILE_READ_ATTRIBUTES, 0);
344 if (!h) {
345 set_errno();
346 return nullptr;
348 size_t buff_size = MAX_PATH + 10;
349 std::unique_ptr<wchar_t, decltype(&::free)> buff(static_cast<wchar_t*>(malloc(buff_size * sizeof(wchar_t))), &::free);
350 DWORD retval = GetFinalPathNameByHandleW(h, buff.get(), buff_size, FILE_NAME_NORMALIZED | VOLUME_NAME_DOS);
351 if (retval > buff_size) {
352 buff_size = retval;
353 buff.reset(static_cast<wchar_t*>(malloc(buff_size * sizeof(wchar_t))));
354 retval = GetFinalPathNameByHandleW(h, buff.get(), buff_size, FILE_NAME_NORMALIZED | VOLUME_NAME_DOS);
356 if (!retval) {
357 set_errno();
358 return nullptr;
360 wchar_t* ptr = buff.get();
361 if (!wcsncmp(ptr, L"\\\\?\\", 4)) {
362 if (ptr[5] == ':') { // \\?\X: -> X:
363 memmove(&ptr[0], &ptr[4], (wcslen(&ptr[4]) + 1) * sizeof(wchar_t));
364 } else if (!wcsncmp(&ptr[4], L"UNC\\", 4)) { // \\?\UNC\server -> \\server
365 wcscpy(&ptr[0], L"\\\\");
366 memmove(&ptr[2], &ptr[8], (wcslen(&ptr[8]) + 1) * sizeof(wchar_t));
369 return buff.release();
372 # define AT_FDCWD -1
373 # define AT_SYMLINK_NOFOLLOW 1
374 using ModeT = int;
376 inline int fchmod_handle(HANDLE h, int perms) {
377 FILE_BASIC_INFO basic;
378 if (!GetFileInformationByHandleEx(h, FileBasicInfo, &basic, sizeof(basic)))
379 return set_errno();
380 DWORD orig_attributes = basic.FileAttributes;
381 basic.FileAttributes &= ~FILE_ATTRIBUTE_READONLY;
382 if ((perms & 0222) == 0)
383 basic.FileAttributes |= FILE_ATTRIBUTE_READONLY;
384 if (basic.FileAttributes != orig_attributes && !SetFileInformationByHandle(h, FileBasicInfo, &basic, sizeof(basic)))
385 return set_errno();
386 return 0;
389 inline int fchmodat(int /*fd*/, const wchar_t* path, int perms, int flag) {
390 DWORD attributes = GetFileAttributesW(path);
391 if (attributes == INVALID_FILE_ATTRIBUTES)
392 return set_errno();
393 if (attributes & FILE_ATTRIBUTE_REPARSE_POINT && !(flag & AT_SYMLINK_NOFOLLOW)) {
394 // If the file is a symlink, and we are supposed to operate on the target
395 // of the symlink, we need to open a handle to it, without the
396 // FILE_FLAG_OPEN_REPARSE_POINT flag, to open the destination of the
397 // symlink, and operate on it via the handle.
398 detail::WinHandle h(path, FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES, 0);
399 if (!h)
400 return set_errno();
401 return fchmod_handle(h, perms);
402 } else {
403 // For a non-symlink, or if operating on the symlink itself instead of
404 // its target, we can use SetFileAttributesW, saving a few calls.
405 DWORD orig_attributes = attributes;
406 attributes &= ~FILE_ATTRIBUTE_READONLY;
407 if ((perms & 0222) == 0)
408 attributes |= FILE_ATTRIBUTE_READONLY;
409 if (attributes != orig_attributes && !SetFileAttributesW(path, attributes))
410 return set_errno();
412 return 0;
415 inline int fchmod(int fd, int perms) {
416 HANDLE h = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
417 return fchmod_handle(h, perms);
420 # define MAX_SYMLINK_SIZE MAXIMUM_REPARSE_DATA_BUFFER_SIZE
421 using SSizeT = ::int64_t;
423 inline SSizeT readlink(const wchar_t* path, wchar_t* ret_buf, size_t bufsize) {
424 uint8_t buf[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
425 detail::WinHandle h(path, FILE_READ_ATTRIBUTES, FILE_FLAG_OPEN_REPARSE_POINT);
426 if (!h)
427 return set_errno();
428 DWORD out;
429 if (!DeviceIoControl(h, FSCTL_GET_REPARSE_POINT, nullptr, 0, buf, sizeof(buf), &out, 0))
430 return set_errno();
431 const auto* reparse = reinterpret_cast<LIBCPP_REPARSE_DATA_BUFFER*>(buf);
432 size_t path_buf_offset = offsetof(LIBCPP_REPARSE_DATA_BUFFER, SymbolicLinkReparseBuffer.PathBuffer[0]);
433 if (out < path_buf_offset) {
434 errno = EINVAL;
435 return -1;
437 if (reparse->ReparseTag != IO_REPARSE_TAG_SYMLINK) {
438 errno = EINVAL;
439 return -1;
441 const auto& symlink = reparse->SymbolicLinkReparseBuffer;
442 unsigned short name_offset, name_length;
443 if (symlink.PrintNameLength == 0) {
444 name_offset = symlink.SubstituteNameOffset;
445 name_length = symlink.SubstituteNameLength;
446 } else {
447 name_offset = symlink.PrintNameOffset;
448 name_length = symlink.PrintNameLength;
450 // name_offset/length are expressed in bytes, not in wchar_t
451 if (path_buf_offset + name_offset + name_length > out) {
452 errno = EINVAL;
453 return -1;
455 if (name_length / sizeof(wchar_t) > bufsize) {
456 errno = ENOMEM;
457 return -1;
459 memcpy(ret_buf, &symlink.PathBuffer[name_offset / sizeof(wchar_t)], name_length);
460 return name_length / sizeof(wchar_t);
463 #else
464 inline int symlink_file(const char* oldname, const char* newname) { return ::symlink(oldname, newname); }
465 inline int symlink_dir(const char* oldname, const char* newname) { return ::symlink(oldname, newname); }
466 using ::chdir;
467 using ::fchmod;
468 # if defined(AT_SYMLINK_NOFOLLOW) && defined(AT_FDCWD)
469 using ::fchmodat;
470 # endif
471 using ::fstat;
472 using ::ftruncate;
473 using ::getcwd;
474 using ::link;
475 using ::lstat;
476 using ::mkdir;
477 using ::readlink;
478 using ::realpath;
479 using ::remove;
480 using ::rename;
481 using ::stat;
482 using ::statvfs;
483 using ::truncate;
485 # define O_BINARY 0
487 using StatVFS = struct statvfs;
488 using ModeT = ::mode_t;
489 using SSizeT = ::ssize_t;
491 #endif
493 } // namespace detail
495 _LIBCPP_END_NAMESPACE_FILESYSTEM
497 #endif // POSIX_COMPAT_H