Path: blob/main/contrib/llvm-project/libcxx/src/filesystem/posix_compat.h
35231 views
//===----------------------------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78//9// POSIX-like portability helper functions.10//11// These generally behave like the proper posix functions, with these12// exceptions:13// On Windows, they take paths in wchar_t* form, instead of char* form.14// The symlink() function is split into two frontends, symlink_file()15// and symlink_dir().16//17// These are provided within an anonymous namespace within the detail18// namespace - callers need to include this header and call them as19// detail::function(), regardless of platform.20//2122#ifndef POSIX_COMPAT_H23#define POSIX_COMPAT_H2425#include <__assert>26#include <__config>27#include <filesystem>2829#include "error.h"30#include "time_utils.h"3132#if defined(_LIBCPP_WIN32API)33# define WIN32_LEAN_AND_MEAN34# define NOMINMAX35# include <io.h>36# include <windows.h>37# include <winioctl.h>38#else39# include <fcntl.h>40# include <sys/stat.h>41# include <sys/statvfs.h>42# include <sys/time.h>43# include <unistd.h>44#endif45#include <stdlib.h>46#include <time.h>4748#if defined(_LIBCPP_WIN32API)49// This struct isn't defined in the normal Windows SDK, but only in the50// Windows Driver Kit.51struct LIBCPP_REPARSE_DATA_BUFFER {52unsigned long ReparseTag;53unsigned short ReparseDataLength;54unsigned short Reserved;55union {56struct {57unsigned short SubstituteNameOffset;58unsigned short SubstituteNameLength;59unsigned short PrintNameOffset;60unsigned short PrintNameLength;61unsigned long Flags;62wchar_t PathBuffer[1];63} SymbolicLinkReparseBuffer;64struct {65unsigned short SubstituteNameOffset;66unsigned short SubstituteNameLength;67unsigned short PrintNameOffset;68unsigned short PrintNameLength;69wchar_t PathBuffer[1];70} MountPointReparseBuffer;71struct {72unsigned char DataBuffer[1];73} GenericReparseBuffer;74};75};76#endif7778_LIBCPP_BEGIN_NAMESPACE_FILESYSTEM7980namespace detail {8182#if defined(_LIBCPP_WIN32API)8384// Various C runtime header sets provide more or less of these. As we85// provide our own implementation, undef all potential defines from the86// C runtime headers and provide a complete set of macros of our own.8788# undef _S_IFMT89# undef _S_IFDIR90# undef _S_IFCHR91# undef _S_IFIFO92# undef _S_IFREG93# undef _S_IFBLK94# undef _S_IFLNK95# undef _S_IFSOCK9697# define _S_IFMT 0xF00098# define _S_IFDIR 0x400099# define _S_IFCHR 0x2000100# define _S_IFIFO 0x1000101# define _S_IFREG 0x8000102# define _S_IFBLK 0x6000103# define _S_IFLNK 0xA000104# define _S_IFSOCK 0xC000105106# undef S_ISDIR107# undef S_ISFIFO108# undef S_ISCHR109# undef S_ISREG110# undef S_ISLNK111# undef S_ISBLK112# undef S_ISSOCK113114# define S_ISDIR(m) (((m) & _S_IFMT) == _S_IFDIR)115# define S_ISCHR(m) (((m) & _S_IFMT) == _S_IFCHR)116# define S_ISFIFO(m) (((m) & _S_IFMT) == _S_IFIFO)117# define S_ISREG(m) (((m) & _S_IFMT) == _S_IFREG)118# define S_ISBLK(m) (((m) & _S_IFMT) == _S_IFBLK)119# define S_ISLNK(m) (((m) & _S_IFMT) == _S_IFLNK)120# define S_ISSOCK(m) (((m) & _S_IFMT) == _S_IFSOCK)121122# define O_NONBLOCK 0123124inline int set_errno(int e = GetLastError()) {125errno = static_cast<int>(__win_err_to_errc(e));126return -1;127}128129class WinHandle {130public:131WinHandle(const wchar_t* p, DWORD access, DWORD flags) {132h = CreateFileW(133p,134access,135FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,136nullptr,137OPEN_EXISTING,138FILE_FLAG_BACKUP_SEMANTICS | flags,139nullptr);140}141~WinHandle() {142if (h != INVALID_HANDLE_VALUE)143CloseHandle(h);144}145operator HANDLE() const { return h; }146operator bool() const { return h != INVALID_HANDLE_VALUE; }147148private:149HANDLE h;150};151152inline int stat_handle(HANDLE h, StatT* buf) {153FILE_BASIC_INFO basic;154if (!GetFileInformationByHandleEx(h, FileBasicInfo, &basic, sizeof(basic)))155return set_errno();156memset(buf, 0, sizeof(*buf));157buf->st_mtim = filetime_to_timespec(basic.LastWriteTime);158buf->st_atim = filetime_to_timespec(basic.LastAccessTime);159buf->st_mode = 0555; // Read-only160if (!(basic.FileAttributes & FILE_ATTRIBUTE_READONLY))161buf->st_mode |= 0222; // Write162if (basic.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) {163buf->st_mode |= _S_IFDIR;164} else {165buf->st_mode |= _S_IFREG;166}167if (basic.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {168FILE_ATTRIBUTE_TAG_INFO tag;169if (!GetFileInformationByHandleEx(h, FileAttributeTagInfo, &tag, sizeof(tag)))170return set_errno();171if (tag.ReparseTag == IO_REPARSE_TAG_SYMLINK)172buf->st_mode = (buf->st_mode & ~_S_IFMT) | _S_IFLNK;173}174FILE_STANDARD_INFO standard;175if (!GetFileInformationByHandleEx(h, FileStandardInfo, &standard, sizeof(standard)))176return set_errno();177buf->st_nlink = standard.NumberOfLinks;178buf->st_size = standard.EndOfFile.QuadPart;179BY_HANDLE_FILE_INFORMATION info;180if (!GetFileInformationByHandle(h, &info))181return set_errno();182buf->st_dev = info.dwVolumeSerialNumber;183memcpy(&buf->st_ino.id[0], &info.nFileIndexHigh, 4);184memcpy(&buf->st_ino.id[4], &info.nFileIndexLow, 4);185return 0;186}187188inline int stat_file(const wchar_t* path, StatT* buf, DWORD flags) {189WinHandle h(path, FILE_READ_ATTRIBUTES, flags);190if (!h)191return set_errno();192int ret = stat_handle(h, buf);193return ret;194}195196inline int stat(const wchar_t* path, StatT* buf) { return stat_file(path, buf, 0); }197198inline int lstat(const wchar_t* path, StatT* buf) { return stat_file(path, buf, FILE_FLAG_OPEN_REPARSE_POINT); }199200inline int fstat(int fd, StatT* buf) {201HANDLE h = reinterpret_cast<HANDLE>(_get_osfhandle(fd));202return stat_handle(h, buf);203}204205inline int mkdir(const wchar_t* path, int permissions) {206(void)permissions;207if (!CreateDirectoryW(path, nullptr))208return set_errno();209return 0;210}211212inline int symlink_file_dir(const wchar_t* oldname, const wchar_t* newname, bool is_dir) {213path dest(oldname);214dest.make_preferred();215oldname = dest.c_str();216DWORD flags = is_dir ? SYMBOLIC_LINK_FLAG_DIRECTORY : 0;217if (CreateSymbolicLinkW(newname, oldname, flags | SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE))218return 0;219int e = GetLastError();220if (e != ERROR_INVALID_PARAMETER)221return set_errno(e);222if (CreateSymbolicLinkW(newname, oldname, flags))223return 0;224return set_errno();225}226227inline int symlink_file(const wchar_t* oldname, const wchar_t* newname) {228return symlink_file_dir(oldname, newname, false);229}230231inline int symlink_dir(const wchar_t* oldname, const wchar_t* newname) {232return symlink_file_dir(oldname, newname, true);233}234235inline int link(const wchar_t* oldname, const wchar_t* newname) {236if (CreateHardLinkW(newname, oldname, nullptr))237return 0;238return set_errno();239}240241inline int remove(const wchar_t* path) {242detail::WinHandle h(path, DELETE, FILE_FLAG_OPEN_REPARSE_POINT);243if (!h)244return set_errno();245FILE_DISPOSITION_INFO info;246info.DeleteFile = TRUE;247if (!SetFileInformationByHandle(h, FileDispositionInfo, &info, sizeof(info)))248return set_errno();249return 0;250}251252inline int truncate_handle(HANDLE h, off_t length) {253LARGE_INTEGER size_param;254size_param.QuadPart = length;255if (!SetFilePointerEx(h, size_param, 0, FILE_BEGIN))256return set_errno();257if (!SetEndOfFile(h))258return set_errno();259return 0;260}261262inline int ftruncate(int fd, off_t length) {263HANDLE h = reinterpret_cast<HANDLE>(_get_osfhandle(fd));264return truncate_handle(h, length);265}266267inline int truncate(const wchar_t* path, off_t length) {268detail::WinHandle h(path, GENERIC_WRITE, 0);269if (!h)270return set_errno();271return truncate_handle(h, length);272}273274inline int rename(const wchar_t* from, const wchar_t* to) {275if (!(MoveFileExW(from, to, MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)))276return set_errno();277return 0;278}279280inline int chdir(const wchar_t* path) {281if (!SetCurrentDirectoryW(path))282return set_errno();283return 0;284}285286struct StatVFS {287uint64_t f_frsize;288uint64_t f_blocks;289uint64_t f_bfree;290uint64_t f_bavail;291};292293inline int statvfs(const wchar_t* p, StatVFS* buf) {294path dir = p;295while (true) {296error_code local_ec;297const file_status st = status(dir, local_ec);298if (!exists(st) || is_directory(st))299break;300path parent = dir.parent_path();301if (parent == dir) {302errno = ENOENT;303return -1;304}305dir = parent;306}307ULARGE_INTEGER free_bytes_available_to_caller, total_number_of_bytes, total_number_of_free_bytes;308if (!GetDiskFreeSpaceExW(309dir.c_str(), &free_bytes_available_to_caller, &total_number_of_bytes, &total_number_of_free_bytes))310return set_errno();311buf->f_frsize = 1;312buf->f_blocks = total_number_of_bytes.QuadPart;313buf->f_bfree = total_number_of_free_bytes.QuadPart;314buf->f_bavail = free_bytes_available_to_caller.QuadPart;315return 0;316}317318inline wchar_t* getcwd([[maybe_unused]] wchar_t* in_buf, [[maybe_unused]] size_t in_size) {319// Only expected to be used with us allocating the buffer.320_LIBCPP_ASSERT_INTERNAL(in_buf == nullptr, "Windows getcwd() assumes in_buf==nullptr");321_LIBCPP_ASSERT_INTERNAL(in_size == 0, "Windows getcwd() assumes in_size==0");322323size_t buff_size = MAX_PATH + 10;324std::unique_ptr<wchar_t, decltype(&::free)> buff(static_cast<wchar_t*>(malloc(buff_size * sizeof(wchar_t))), &::free);325DWORD retval = GetCurrentDirectoryW(buff_size, buff.get());326if (retval > buff_size) {327buff_size = retval;328buff.reset(static_cast<wchar_t*>(malloc(buff_size * sizeof(wchar_t))));329retval = GetCurrentDirectoryW(buff_size, buff.get());330}331if (!retval) {332set_errno();333return nullptr;334}335return buff.release();336}337338inline wchar_t* realpath(const wchar_t* path, [[maybe_unused]] wchar_t* resolved_name) {339// Only expected to be used with us allocating the buffer.340_LIBCPP_ASSERT_INTERNAL(resolved_name == nullptr, "Windows realpath() assumes a null resolved_name");341342WinHandle h(path, FILE_READ_ATTRIBUTES, 0);343if (!h) {344set_errno();345return nullptr;346}347size_t buff_size = MAX_PATH + 10;348std::unique_ptr<wchar_t, decltype(&::free)> buff(static_cast<wchar_t*>(malloc(buff_size * sizeof(wchar_t))), &::free);349DWORD retval = GetFinalPathNameByHandleW(h, buff.get(), buff_size, FILE_NAME_NORMALIZED | VOLUME_NAME_DOS);350if (retval > buff_size) {351buff_size = retval;352buff.reset(static_cast<wchar_t*>(malloc(buff_size * sizeof(wchar_t))));353retval = GetFinalPathNameByHandleW(h, buff.get(), buff_size, FILE_NAME_NORMALIZED | VOLUME_NAME_DOS);354}355if (!retval) {356set_errno();357return nullptr;358}359wchar_t* ptr = buff.get();360if (!wcsncmp(ptr, L"\\\\?\\", 4)) {361if (ptr[5] == ':') { // \\?\X: -> X:362memmove(&ptr[0], &ptr[4], (wcslen(&ptr[4]) + 1) * sizeof(wchar_t));363} else if (!wcsncmp(&ptr[4], L"UNC\\", 4)) { // \\?\UNC\server -> \\server364wcscpy(&ptr[0], L"\\\\");365memmove(&ptr[2], &ptr[8], (wcslen(&ptr[8]) + 1) * sizeof(wchar_t));366}367}368return buff.release();369}370371# define AT_FDCWD -1372# define AT_SYMLINK_NOFOLLOW 1373using ModeT = int;374375inline int fchmod_handle(HANDLE h, int perms) {376FILE_BASIC_INFO basic;377if (!GetFileInformationByHandleEx(h, FileBasicInfo, &basic, sizeof(basic)))378return set_errno();379DWORD orig_attributes = basic.FileAttributes;380basic.FileAttributes &= ~FILE_ATTRIBUTE_READONLY;381if ((perms & 0222) == 0)382basic.FileAttributes |= FILE_ATTRIBUTE_READONLY;383if (basic.FileAttributes != orig_attributes && !SetFileInformationByHandle(h, FileBasicInfo, &basic, sizeof(basic)))384return set_errno();385return 0;386}387388inline int fchmodat(int /*fd*/, const wchar_t* path, int perms, int flag) {389DWORD attributes = GetFileAttributesW(path);390if (attributes == INVALID_FILE_ATTRIBUTES)391return set_errno();392if (attributes & FILE_ATTRIBUTE_REPARSE_POINT && !(flag & AT_SYMLINK_NOFOLLOW)) {393// If the file is a symlink, and we are supposed to operate on the target394// of the symlink, we need to open a handle to it, without the395// FILE_FLAG_OPEN_REPARSE_POINT flag, to open the destination of the396// symlink, and operate on it via the handle.397detail::WinHandle h(path, FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES, 0);398if (!h)399return set_errno();400return fchmod_handle(h, perms);401} else {402// For a non-symlink, or if operating on the symlink itself instead of403// its target, we can use SetFileAttributesW, saving a few calls.404DWORD orig_attributes = attributes;405attributes &= ~FILE_ATTRIBUTE_READONLY;406if ((perms & 0222) == 0)407attributes |= FILE_ATTRIBUTE_READONLY;408if (attributes != orig_attributes && !SetFileAttributesW(path, attributes))409return set_errno();410}411return 0;412}413414inline int fchmod(int fd, int perms) {415HANDLE h = reinterpret_cast<HANDLE>(_get_osfhandle(fd));416return fchmod_handle(h, perms);417}418419# define MAX_SYMLINK_SIZE MAXIMUM_REPARSE_DATA_BUFFER_SIZE420using SSizeT = ::int64_t;421422inline SSizeT readlink(const wchar_t* path, wchar_t* ret_buf, size_t bufsize) {423uint8_t buf[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];424detail::WinHandle h(path, FILE_READ_ATTRIBUTES, FILE_FLAG_OPEN_REPARSE_POINT);425if (!h)426return set_errno();427DWORD out;428if (!DeviceIoControl(h, FSCTL_GET_REPARSE_POINT, nullptr, 0, buf, sizeof(buf), &out, 0))429return set_errno();430const auto* reparse = reinterpret_cast<LIBCPP_REPARSE_DATA_BUFFER*>(buf);431size_t path_buf_offset = offsetof(LIBCPP_REPARSE_DATA_BUFFER, SymbolicLinkReparseBuffer.PathBuffer[0]);432if (out < path_buf_offset) {433errno = EINVAL;434return -1;435}436if (reparse->ReparseTag != IO_REPARSE_TAG_SYMLINK) {437errno = EINVAL;438return -1;439}440const auto& symlink = reparse->SymbolicLinkReparseBuffer;441unsigned short name_offset, name_length;442if (symlink.PrintNameLength == 0) {443name_offset = symlink.SubstituteNameOffset;444name_length = symlink.SubstituteNameLength;445} else {446name_offset = symlink.PrintNameOffset;447name_length = symlink.PrintNameLength;448}449// name_offset/length are expressed in bytes, not in wchar_t450if (path_buf_offset + name_offset + name_length > out) {451errno = EINVAL;452return -1;453}454if (name_length / sizeof(wchar_t) > bufsize) {455errno = ENOMEM;456return -1;457}458memcpy(ret_buf, &symlink.PathBuffer[name_offset / sizeof(wchar_t)], name_length);459return name_length / sizeof(wchar_t);460}461462#else463inline int symlink_file(const char* oldname, const char* newname) { return ::symlink(oldname, newname); }464inline int symlink_dir(const char* oldname, const char* newname) { return ::symlink(oldname, newname); }465using ::chdir;466using ::fchmod;467# if defined(AT_SYMLINK_NOFOLLOW) && defined(AT_FDCWD)468using ::fchmodat;469# endif470using ::fstat;471using ::ftruncate;472using ::getcwd;473using ::link;474using ::lstat;475using ::mkdir;476using ::readlink;477using ::realpath;478using ::remove;479using ::rename;480using ::stat;481using ::statvfs;482using ::truncate;483484# define O_BINARY 0485486using StatVFS = struct statvfs;487using ModeT = ::mode_t;488using SSizeT = ::ssize_t;489490#endif491492} // end namespace detail493494_LIBCPP_END_NAMESPACE_FILESYSTEM495496#endif // POSIX_COMPAT_H497498499