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 //===----------------------------------------------------------------------===// 8 9 // 10 // POSIX-like portability helper functions. 11 // 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(). 17 // 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. 21 // 22 23 #ifndef POSIX_COMPAT_H 24 #define POSIX_COMPAT_H 25 26 #include <__assert> 27 #include <__config> 28 #include <filesystem> 29 30 #include "error.h" 31 #include "time_utils.h" 32 33 #if defined(_LIBCPP_WIN32API) 34 # define WIN32_LEAN_AND_MEAN 35 # define NOMINMAX 36 # include <windows.h> 37 # include <io.h> 38 # include <winioctl.h> 39 #else 40 # include <fcntl.h> 41 # include <unistd.h> 42 # include <sys/stat.h> 43 # include <sys/statvfs.h> 44 # include <sys/time.h> 45 #endif 46 #include <stdlib.h> 47 #include <time.h> 48 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; 75 }; 76 }; 77 #endif 78 79 _LIBCPP_BEGIN_NAMESPACE_FILESYSTEM 80 81 namespace detail { 82 83 #if defined(_LIBCPP_WIN32API) 84 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. 88 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 97 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 106 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 114 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) 122 123 #define O_NONBLOCK 0 124 125 inline int set_errno(int e = GetLastError()) { 126 errno = static_cast<int>(__win_err_to_errc(e)); 127 return -1; 128 } 129 130 class WinHandle { 131 public: 132 WinHandle(const wchar_t *p, DWORD access, DWORD flags) { 133 h = CreateFileW( 134 p, access, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 135 nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | flags, nullptr); 136 } 137 ~WinHandle() { 138 if (h != INVALID_HANDLE_VALUE) 139 CloseHandle(h); 140 } 141 operator HANDLE() const { return h; } 142 operator bool() const { return h != INVALID_HANDLE_VALUE; } 143 144 private: 145 HANDLE h; 146 }; 147 148 inline int stat_handle(HANDLE h, StatT *buf) { 149 FILE_BASIC_INFO basic; 150 if (!GetFileInformationByHandleEx(h, FileBasicInfo, &basic, sizeof(basic))) 151 return set_errno(); 152 memset(buf, 0, sizeof(*buf)); 153 buf->st_mtim = filetime_to_timespec(basic.LastWriteTime); 154 buf->st_atim = filetime_to_timespec(basic.LastAccessTime); 155 buf->st_mode = 0555; // Read-only 156 if (!(basic.FileAttributes & FILE_ATTRIBUTE_READONLY)) 157 buf->st_mode |= 0222; // Write 158 if (basic.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) { 159 buf->st_mode |= _S_IFDIR; 160 } else { 161 buf->st_mode |= _S_IFREG; 162 } 163 if (basic.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) { 164 FILE_ATTRIBUTE_TAG_INFO tag; 165 if (!GetFileInformationByHandleEx(h, FileAttributeTagInfo, &tag, 166 sizeof(tag))) 167 return set_errno(); 168 if (tag.ReparseTag == IO_REPARSE_TAG_SYMLINK) 169 buf->st_mode = (buf->st_mode & ~_S_IFMT) | _S_IFLNK; 170 } 171 FILE_STANDARD_INFO standard; 172 if (!GetFileInformationByHandleEx(h, FileStandardInfo, &standard, 173 sizeof(standard))) 174 return set_errno(); 175 buf->st_nlink = standard.NumberOfLinks; 176 buf->st_size = standard.EndOfFile.QuadPart; 177 BY_HANDLE_FILE_INFORMATION info; 178 if (!GetFileInformationByHandle(h, &info)) 179 return set_errno(); 180 buf->st_dev = info.dwVolumeSerialNumber; 181 memcpy(&buf->st_ino.id[0], &info.nFileIndexHigh, 4); 182 memcpy(&buf->st_ino.id[4], &info.nFileIndexLow, 4); 183 return 0; 184 } 185 186 inline int stat_file(const wchar_t *path, StatT *buf, DWORD flags) { 187 WinHandle h(path, FILE_READ_ATTRIBUTES, flags); 188 if (!h) 189 return set_errno(); 190 int ret = stat_handle(h, buf); 191 return ret; 192 } 193 194 inline int stat(const wchar_t *path, StatT *buf) { return stat_file(path, buf, 0); } 195 196 inline int lstat(const wchar_t *path, StatT *buf) { 197 return stat_file(path, buf, FILE_FLAG_OPEN_REPARSE_POINT); 198 } 199 200 inline int fstat(int fd, StatT *buf) { 201 HANDLE h = reinterpret_cast<HANDLE>(_get_osfhandle(fd)); 202 return stat_handle(h, buf); 203 } 204 205 inline int mkdir(const wchar_t *path, int permissions) { 206 (void)permissions; 207 if (!CreateDirectoryW(path, nullptr)) 208 return set_errno(); 209 return 0; 210 } 211 212 inline int symlink_file_dir(const wchar_t *oldname, const wchar_t *newname, 213 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, 219 flags | SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE)) 220 return 0; 221 int e = GetLastError(); 222 if (e != ERROR_INVALID_PARAMETER) 223 return set_errno(e); 224 if (CreateSymbolicLinkW(newname, oldname, flags)) 225 return 0; 226 return set_errno(); 227 } 228 229 inline int symlink_file(const wchar_t *oldname, const wchar_t *newname) { 230 return symlink_file_dir(oldname, newname, false); 231 } 232 233 inline int symlink_dir(const wchar_t *oldname, const wchar_t *newname) { 234 return symlink_file_dir(oldname, newname, true); 235 } 236 237 inline int link(const wchar_t *oldname, const wchar_t *newname) { 238 if (CreateHardLinkW(newname, oldname, nullptr)) 239 return 0; 240 return set_errno(); 241 } 242 243 inline int remove(const wchar_t *path) { 244 detail::WinHandle h(path, DELETE, FILE_FLAG_OPEN_REPARSE_POINT); 245 if (!h) 246 return set_errno(); 247 FILE_DISPOSITION_INFO info; 248 info.DeleteFile = TRUE; 249 if (!SetFileInformationByHandle(h, FileDispositionInfo, &info, sizeof(info))) 250 return set_errno(); 251 return 0; 252 } 253 254 inline int truncate_handle(HANDLE h, off_t length) { 255 LARGE_INTEGER size_param; 256 size_param.QuadPart = length; 257 if (!SetFilePointerEx(h, size_param, 0, FILE_BEGIN)) 258 return set_errno(); 259 if (!SetEndOfFile(h)) 260 return set_errno(); 261 return 0; 262 } 263 264 inline int ftruncate(int fd, off_t length) { 265 HANDLE h = reinterpret_cast<HANDLE>(_get_osfhandle(fd)); 266 return truncate_handle(h, length); 267 } 268 269 inline int truncate(const wchar_t *path, off_t length) { 270 detail::WinHandle h(path, GENERIC_WRITE, 0); 271 if (!h) 272 return set_errno(); 273 return truncate_handle(h, length); 274 } 275 276 inline int rename(const wchar_t *from, const wchar_t *to) { 277 if (!(MoveFileExW(from, to, 278 MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING | 279 MOVEFILE_WRITE_THROUGH))) 280 return set_errno(); 281 return 0; 282 } 283 284 inline int chdir(const wchar_t* path) { 285 if (!SetCurrentDirectoryW(path)) 286 return set_errno(); 287 return 0; 288 } 289 290 struct StatVFS { 291 uint64_t f_frsize; 292 uint64_t f_blocks; 293 uint64_t f_bfree; 294 uint64_t f_bavail; 295 }; 296 297 inline int statvfs(const wchar_t *p, StatVFS *buf) { 298 path dir = p; 299 while (true) { 300 error_code local_ec; 301 const file_status st = status(dir, local_ec); 302 if (!exists(st) || is_directory(st)) 303 break; 304 path parent = dir.parent_path(); 305 if (parent == dir) { 306 errno = ENOENT; 307 return -1; 308 } 309 dir = parent; 310 } 311 ULARGE_INTEGER free_bytes_available_to_caller, total_number_of_bytes, 312 total_number_of_free_bytes; 313 if (!GetDiskFreeSpaceExW(dir.c_str(), &free_bytes_available_to_caller, 314 &total_number_of_bytes, &total_number_of_free_bytes)) 315 return set_errno(); 316 buf->f_frsize = 1; 317 buf->f_blocks = total_number_of_bytes.QuadPart; 318 buf->f_bfree = total_number_of_free_bytes.QuadPart; 319 buf->f_bavail = free_bytes_available_to_caller.QuadPart; 320 return 0; 321 } 322 323 inline wchar_t* getcwd([[maybe_unused]] wchar_t* in_buf, [[maybe_unused]] size_t in_size) { 324 // Only expected to be used with us allocating the buffer. 325 _LIBCPP_ASSERT(in_buf == nullptr, "Windows getcwd() assumes in_buf==nullptr"); 326 _LIBCPP_ASSERT(in_size == 0, "Windows getcwd() assumes in_size==0"); 327 328 size_t buff_size = MAX_PATH + 10; 329 std::unique_ptr<wchar_t, decltype(&::free)> buff(static_cast<wchar_t*>(malloc(buff_size * sizeof(wchar_t))), &::free); 330 DWORD retval = GetCurrentDirectoryW(buff_size, buff.get()); 331 if (retval > buff_size) { 332 buff_size = retval; 333 buff.reset(static_cast<wchar_t*>(malloc(buff_size * sizeof(wchar_t)))); 334 retval = GetCurrentDirectoryW(buff_size, buff.get()); 335 } 336 if (!retval) { 337 set_errno(); 338 return nullptr; 339 } 340 return buff.release(); 341 } 342 343 inline wchar_t *realpath(const wchar_t *path, [[maybe_unused]] wchar_t *resolved_name) { 344 // Only expected to be used with us allocating the buffer. 345 _LIBCPP_ASSERT_UNCATEGORIZED(resolved_name == nullptr, 346 "Windows realpath() assumes a null resolved_name"); 347 348 WinHandle h(path, FILE_READ_ATTRIBUTES, 0); 349 if (!h) { 350 set_errno(); 351 return nullptr; 352 } 353 size_t buff_size = MAX_PATH + 10; 354 std::unique_ptr<wchar_t, decltype(&::free)> buff( 355 static_cast<wchar_t *>(malloc(buff_size * sizeof(wchar_t))), &::free); 356 DWORD retval = GetFinalPathNameByHandleW( 357 h, buff.get(), buff_size, FILE_NAME_NORMALIZED | VOLUME_NAME_DOS); 358 if (retval > buff_size) { 359 buff_size = retval; 360 buff.reset(static_cast<wchar_t *>(malloc(buff_size * sizeof(wchar_t)))); 361 retval = GetFinalPathNameByHandleW(h, buff.get(), buff_size, 362 FILE_NAME_NORMALIZED | VOLUME_NAME_DOS); 363 } 364 if (!retval) { 365 set_errno(); 366 return nullptr; 367 } 368 wchar_t *ptr = buff.get(); 369 if (!wcsncmp(ptr, L"\\\\?\\", 4)) { 370 if (ptr[5] == ':') { // \\?\X: -> X: 371 memmove(&ptr[0], &ptr[4], (wcslen(&ptr[4]) + 1) * sizeof(wchar_t)); 372 } else if (!wcsncmp(&ptr[4], L"UNC\\", 4)) { // \\?\UNC\server -> \\server 373 wcscpy(&ptr[0], L"\\\\"); 374 memmove(&ptr[2], &ptr[8], (wcslen(&ptr[8]) + 1) * sizeof(wchar_t)); 375 } 376 } 377 return buff.release(); 378 } 379 380 #define AT_FDCWD -1 381 #define AT_SYMLINK_NOFOLLOW 1 382 using ModeT = int; 383 384 inline int fchmod_handle(HANDLE h, int perms) { 385 FILE_BASIC_INFO basic; 386 if (!GetFileInformationByHandleEx(h, FileBasicInfo, &basic, sizeof(basic))) 387 return set_errno(); 388 DWORD orig_attributes = basic.FileAttributes; 389 basic.FileAttributes &= ~FILE_ATTRIBUTE_READONLY; 390 if ((perms & 0222) == 0) 391 basic.FileAttributes |= FILE_ATTRIBUTE_READONLY; 392 if (basic.FileAttributes != orig_attributes && 393 !SetFileInformationByHandle(h, FileBasicInfo, &basic, sizeof(basic))) 394 return set_errno(); 395 return 0; 396 } 397 398 inline int fchmodat(int /*fd*/, const wchar_t *path, int perms, int flag) { 399 DWORD attributes = GetFileAttributesW(path); 400 if (attributes == INVALID_FILE_ATTRIBUTES) 401 return set_errno(); 402 if (attributes & FILE_ATTRIBUTE_REPARSE_POINT && 403 !(flag & AT_SYMLINK_NOFOLLOW)) { 404 // If the file is a symlink, and we are supposed to operate on the target 405 // of the symlink, we need to open a handle to it, without the 406 // FILE_FLAG_OPEN_REPARSE_POINT flag, to open the destination of the 407 // symlink, and operate on it via the handle. 408 detail::WinHandle h(path, FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES, 0); 409 if (!h) 410 return set_errno(); 411 return fchmod_handle(h, perms); 412 } else { 413 // For a non-symlink, or if operating on the symlink itself instead of 414 // its target, we can use SetFileAttributesW, saving a few calls. 415 DWORD orig_attributes = attributes; 416 attributes &= ~FILE_ATTRIBUTE_READONLY; 417 if ((perms & 0222) == 0) 418 attributes |= FILE_ATTRIBUTE_READONLY; 419 if (attributes != orig_attributes && !SetFileAttributesW(path, attributes)) 420 return set_errno(); 421 } 422 return 0; 423 } 424 425 inline int fchmod(int fd, int perms) { 426 HANDLE h = reinterpret_cast<HANDLE>(_get_osfhandle(fd)); 427 return fchmod_handle(h, perms); 428 } 429 430 #define MAX_SYMLINK_SIZE MAXIMUM_REPARSE_DATA_BUFFER_SIZE 431 using SSizeT = ::int64_t; 432 433 inline SSizeT readlink(const wchar_t *path, wchar_t *ret_buf, size_t bufsize) { 434 uint8_t buf[MAXIMUM_REPARSE_DATA_BUFFER_SIZE]; 435 detail::WinHandle h(path, FILE_READ_ATTRIBUTES, FILE_FLAG_OPEN_REPARSE_POINT); 436 if (!h) 437 return set_errno(); 438 DWORD out; 439 if (!DeviceIoControl(h, FSCTL_GET_REPARSE_POINT, nullptr, 0, buf, sizeof(buf), 440 &out, 0)) 441 return set_errno(); 442 const auto *reparse = reinterpret_cast<LIBCPP_REPARSE_DATA_BUFFER *>(buf); 443 size_t path_buf_offset = offsetof(LIBCPP_REPARSE_DATA_BUFFER, 444 SymbolicLinkReparseBuffer.PathBuffer[0]); 445 if (out < path_buf_offset) { 446 errno = EINVAL; 447 return -1; 448 } 449 if (reparse->ReparseTag != IO_REPARSE_TAG_SYMLINK) { 450 errno = EINVAL; 451 return -1; 452 } 453 const auto &symlink = reparse->SymbolicLinkReparseBuffer; 454 unsigned short name_offset, name_length; 455 if (symlink.PrintNameLength == 0) { 456 name_offset = symlink.SubstituteNameOffset; 457 name_length = symlink.SubstituteNameLength; 458 } else { 459 name_offset = symlink.PrintNameOffset; 460 name_length = symlink.PrintNameLength; 461 } 462 // name_offset/length are expressed in bytes, not in wchar_t 463 if (path_buf_offset + name_offset + name_length > out) { 464 errno = EINVAL; 465 return -1; 466 } 467 if (name_length / sizeof(wchar_t) > bufsize) { 468 errno = ENOMEM; 469 return -1; 470 } 471 memcpy(ret_buf, &symlink.PathBuffer[name_offset / sizeof(wchar_t)], 472 name_length); 473 return name_length / sizeof(wchar_t); 474 } 475 476 #else 477 inline int symlink_file(const char *oldname, const char *newname) { 478 return ::symlink(oldname, newname); 479 } 480 inline int symlink_dir(const char *oldname, const char *newname) { 481 return ::symlink(oldname, newname); 482 } 483 using ::chdir; 484 using ::fchmod; 485 #if defined(AT_SYMLINK_NOFOLLOW) && defined(AT_FDCWD) 486 using ::fchmodat; 487 #endif 488 using ::fstat; 489 using ::ftruncate; 490 using ::getcwd; 491 using ::link; 492 using ::lstat; 493 using ::mkdir; 494 using ::readlink; 495 using ::realpath; 496 using ::remove; 497 using ::rename; 498 using ::stat; 499 using ::statvfs; 500 using ::truncate; 501 502 #define O_BINARY 0 503 504 using StatVFS = struct statvfs; 505 using ModeT = ::mode_t; 506 using SSizeT = ::ssize_t; 507 508 #endif 509 510 } // end namespace detail 511 512 _LIBCPP_END_NAMESPACE_FILESYSTEM 513 514 #endif // POSIX_COMPAT_H 515