1*c303c47eSjoerg //===----------------------------------------------------------------------===//
2*c303c47eSjoerg //
3*c303c47eSjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*c303c47eSjoerg // See https://llvm.org/LICENSE.txt for license information.
5*c303c47eSjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*c303c47eSjoerg //
7*c303c47eSjoerg //===----------------------------------------------------------------------===//
8*c303c47eSjoerg 
9*c303c47eSjoerg //
10*c303c47eSjoerg // POSIX-like portability helper functions.
11*c303c47eSjoerg //
12*c303c47eSjoerg // These generally behave like the proper posix functions, with these
13*c303c47eSjoerg // exceptions:
14*c303c47eSjoerg // On Windows, they take paths in wchar_t* form, instead of char* form.
15*c303c47eSjoerg // The symlink() function is split into two frontends, symlink_file()
16*c303c47eSjoerg // and symlink_dir().
17*c303c47eSjoerg //
18*c303c47eSjoerg // These are provided within an anonymous namespace within the detail
19*c303c47eSjoerg // namespace - callers need to include this header and call them as
20*c303c47eSjoerg // detail::function(), regardless of platform.
21*c303c47eSjoerg //
22*c303c47eSjoerg 
23*c303c47eSjoerg #ifndef POSIX_COMPAT_H
24*c303c47eSjoerg #define POSIX_COMPAT_H
25*c303c47eSjoerg 
26*c303c47eSjoerg #include "filesystem"
27*c303c47eSjoerg 
28*c303c47eSjoerg #include "filesystem_common.h"
29*c303c47eSjoerg 
30*c303c47eSjoerg #if defined(_LIBCPP_WIN32API)
31*c303c47eSjoerg # define WIN32_LEAN_AND_MEAN
32*c303c47eSjoerg # define NOMINMAX
33*c303c47eSjoerg # include <windows.h>
34*c303c47eSjoerg # include <io.h>
35*c303c47eSjoerg # include <winioctl.h>
36*c303c47eSjoerg #else
37*c303c47eSjoerg # include <unistd.h>
38*c303c47eSjoerg # include <sys/stat.h>
39*c303c47eSjoerg # include <sys/statvfs.h>
40*c303c47eSjoerg #endif
41*c303c47eSjoerg #include <time.h>
42*c303c47eSjoerg 
43*c303c47eSjoerg #if defined(_LIBCPP_WIN32API)
44*c303c47eSjoerg // This struct isn't defined in the normal Windows SDK, but only in the
45*c303c47eSjoerg // Windows Driver Kit.
46*c303c47eSjoerg struct LIBCPP_REPARSE_DATA_BUFFER {
47*c303c47eSjoerg   unsigned long  ReparseTag;
48*c303c47eSjoerg   unsigned short ReparseDataLength;
49*c303c47eSjoerg   unsigned short Reserved;
50*c303c47eSjoerg   union {
51*c303c47eSjoerg     struct {
52*c303c47eSjoerg       unsigned short SubstituteNameOffset;
53*c303c47eSjoerg       unsigned short SubstituteNameLength;
54*c303c47eSjoerg       unsigned short PrintNameOffset;
55*c303c47eSjoerg       unsigned short PrintNameLength;
56*c303c47eSjoerg       unsigned long  Flags;
57*c303c47eSjoerg       wchar_t        PathBuffer[1];
58*c303c47eSjoerg     } SymbolicLinkReparseBuffer;
59*c303c47eSjoerg     struct {
60*c303c47eSjoerg       unsigned short SubstituteNameOffset;
61*c303c47eSjoerg       unsigned short SubstituteNameLength;
62*c303c47eSjoerg       unsigned short PrintNameOffset;
63*c303c47eSjoerg       unsigned short PrintNameLength;
64*c303c47eSjoerg       wchar_t        PathBuffer[1];
65*c303c47eSjoerg     } MountPointReparseBuffer;
66*c303c47eSjoerg     struct {
67*c303c47eSjoerg       unsigned char DataBuffer[1];
68*c303c47eSjoerg     } GenericReparseBuffer;
69*c303c47eSjoerg   };
70*c303c47eSjoerg };
71*c303c47eSjoerg #endif
72*c303c47eSjoerg 
73*c303c47eSjoerg _LIBCPP_BEGIN_NAMESPACE_FILESYSTEM
74*c303c47eSjoerg 
75*c303c47eSjoerg namespace detail {
76*c303c47eSjoerg namespace {
77*c303c47eSjoerg 
78*c303c47eSjoerg #if defined(_LIBCPP_WIN32API)
79*c303c47eSjoerg 
80*c303c47eSjoerg // Various C runtime header sets provide more or less of these. As we
81*c303c47eSjoerg // provide our own implementation, undef all potential defines from the
82*c303c47eSjoerg // C runtime headers and provide a complete set of macros of our own.
83*c303c47eSjoerg 
84*c303c47eSjoerg #undef _S_IFMT
85*c303c47eSjoerg #undef _S_IFDIR
86*c303c47eSjoerg #undef _S_IFCHR
87*c303c47eSjoerg #undef _S_IFIFO
88*c303c47eSjoerg #undef _S_IFREG
89*c303c47eSjoerg #undef _S_IFBLK
90*c303c47eSjoerg #undef _S_IFLNK
91*c303c47eSjoerg #undef _S_IFSOCK
92*c303c47eSjoerg 
93*c303c47eSjoerg #define _S_IFMT   0xF000
94*c303c47eSjoerg #define _S_IFDIR  0x4000
95*c303c47eSjoerg #define _S_IFCHR  0x2000
96*c303c47eSjoerg #define _S_IFIFO  0x1000
97*c303c47eSjoerg #define _S_IFREG  0x8000
98*c303c47eSjoerg #define _S_IFBLK  0x6000
99*c303c47eSjoerg #define _S_IFLNK  0xA000
100*c303c47eSjoerg #define _S_IFSOCK 0xC000
101*c303c47eSjoerg 
102*c303c47eSjoerg #undef S_ISDIR
103*c303c47eSjoerg #undef S_ISFIFO
104*c303c47eSjoerg #undef S_ISCHR
105*c303c47eSjoerg #undef S_ISREG
106*c303c47eSjoerg #undef S_ISLNK
107*c303c47eSjoerg #undef S_ISBLK
108*c303c47eSjoerg #undef S_ISSOCK
109*c303c47eSjoerg 
110*c303c47eSjoerg #define S_ISDIR(m)      (((m) & _S_IFMT) == _S_IFDIR)
111*c303c47eSjoerg #define S_ISCHR(m)      (((m) & _S_IFMT) == _S_IFCHR)
112*c303c47eSjoerg #define S_ISFIFO(m)     (((m) & _S_IFMT) == _S_IFIFO)
113*c303c47eSjoerg #define S_ISREG(m)      (((m) & _S_IFMT) == _S_IFREG)
114*c303c47eSjoerg #define S_ISBLK(m)      (((m) & _S_IFMT) == _S_IFBLK)
115*c303c47eSjoerg #define S_ISLNK(m)      (((m) & _S_IFMT) == _S_IFLNK)
116*c303c47eSjoerg #define S_ISSOCK(m)     (((m) & _S_IFMT) == _S_IFSOCK)
117*c303c47eSjoerg 
118*c303c47eSjoerg #define O_NONBLOCK 0
119*c303c47eSjoerg 
120*c303c47eSjoerg 
121*c303c47eSjoerg // There were 369 years and 89 leap days from the Windows epoch
122*c303c47eSjoerg // (1601) to the Unix epoch (1970).
123*c303c47eSjoerg #define FILE_TIME_OFFSET_SECS (uint64_t(369 * 365 + 89) * (24 * 60 * 60))
124*c303c47eSjoerg 
filetime_to_timespec(LARGE_INTEGER li)125*c303c47eSjoerg TimeSpec filetime_to_timespec(LARGE_INTEGER li) {
126*c303c47eSjoerg   TimeSpec ret;
127*c303c47eSjoerg   ret.tv_sec = li.QuadPart / 10000000 - FILE_TIME_OFFSET_SECS;
128*c303c47eSjoerg   ret.tv_nsec = (li.QuadPart % 10000000) * 100;
129*c303c47eSjoerg   return ret;
130*c303c47eSjoerg }
131*c303c47eSjoerg 
filetime_to_timespec(FILETIME ft)132*c303c47eSjoerg TimeSpec filetime_to_timespec(FILETIME ft) {
133*c303c47eSjoerg   LARGE_INTEGER li;
134*c303c47eSjoerg   li.LowPart = ft.dwLowDateTime;
135*c303c47eSjoerg   li.HighPart = ft.dwHighDateTime;
136*c303c47eSjoerg   return filetime_to_timespec(li);
137*c303c47eSjoerg }
138*c303c47eSjoerg 
timespec_to_filetime(TimeSpec ts)139*c303c47eSjoerg FILETIME timespec_to_filetime(TimeSpec ts) {
140*c303c47eSjoerg   LARGE_INTEGER li;
141*c303c47eSjoerg   li.QuadPart =
142*c303c47eSjoerg       ts.tv_nsec / 100 + (ts.tv_sec + FILE_TIME_OFFSET_SECS) * 10000000;
143*c303c47eSjoerg   FILETIME ft;
144*c303c47eSjoerg   ft.dwLowDateTime = li.LowPart;
145*c303c47eSjoerg   ft.dwHighDateTime = li.HighPart;
146*c303c47eSjoerg   return ft;
147*c303c47eSjoerg }
148*c303c47eSjoerg 
149*c303c47eSjoerg int set_errno(int e = GetLastError()) {
150*c303c47eSjoerg   errno = static_cast<int>(__win_err_to_errc(e));
151*c303c47eSjoerg   return -1;
152*c303c47eSjoerg }
153*c303c47eSjoerg 
154*c303c47eSjoerg class WinHandle {
155*c303c47eSjoerg public:
WinHandle(const wchar_t * p,DWORD access,DWORD flags)156*c303c47eSjoerg   WinHandle(const wchar_t *p, DWORD access, DWORD flags) {
157*c303c47eSjoerg     h = CreateFileW(
158*c303c47eSjoerg         p, access, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
159*c303c47eSjoerg         nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | flags, nullptr);
160*c303c47eSjoerg   }
~WinHandle()161*c303c47eSjoerg   ~WinHandle() {
162*c303c47eSjoerg     if (h != INVALID_HANDLE_VALUE)
163*c303c47eSjoerg       CloseHandle(h);
164*c303c47eSjoerg   }
HANDLE()165*c303c47eSjoerg   operator HANDLE() const { return h; }
166*c303c47eSjoerg   operator bool() const { return h != INVALID_HANDLE_VALUE; }
167*c303c47eSjoerg 
168*c303c47eSjoerg private:
169*c303c47eSjoerg   HANDLE h;
170*c303c47eSjoerg };
171*c303c47eSjoerg 
stat_handle(HANDLE h,StatT * buf)172*c303c47eSjoerg int stat_handle(HANDLE h, StatT *buf) {
173*c303c47eSjoerg   FILE_BASIC_INFO basic;
174*c303c47eSjoerg   if (!GetFileInformationByHandleEx(h, FileBasicInfo, &basic, sizeof(basic)))
175*c303c47eSjoerg     return set_errno();
176*c303c47eSjoerg   memset(buf, 0, sizeof(*buf));
177*c303c47eSjoerg   buf->st_mtim = filetime_to_timespec(basic.LastWriteTime);
178*c303c47eSjoerg   buf->st_atim = filetime_to_timespec(basic.LastAccessTime);
179*c303c47eSjoerg   buf->st_mode = 0555; // Read-only
180*c303c47eSjoerg   if (!(basic.FileAttributes & FILE_ATTRIBUTE_READONLY))
181*c303c47eSjoerg     buf->st_mode |= 0222; // Write
182*c303c47eSjoerg   if (basic.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
183*c303c47eSjoerg     buf->st_mode |= _S_IFDIR;
184*c303c47eSjoerg   } else {
185*c303c47eSjoerg     buf->st_mode |= _S_IFREG;
186*c303c47eSjoerg   }
187*c303c47eSjoerg   if (basic.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
188*c303c47eSjoerg     FILE_ATTRIBUTE_TAG_INFO tag;
189*c303c47eSjoerg     if (!GetFileInformationByHandleEx(h, FileAttributeTagInfo, &tag,
190*c303c47eSjoerg                                       sizeof(tag)))
191*c303c47eSjoerg       return set_errno();
192*c303c47eSjoerg     if (tag.ReparseTag == IO_REPARSE_TAG_SYMLINK)
193*c303c47eSjoerg       buf->st_mode = (buf->st_mode & ~_S_IFMT) | _S_IFLNK;
194*c303c47eSjoerg   }
195*c303c47eSjoerg   FILE_STANDARD_INFO standard;
196*c303c47eSjoerg   if (!GetFileInformationByHandleEx(h, FileStandardInfo, &standard,
197*c303c47eSjoerg                                     sizeof(standard)))
198*c303c47eSjoerg     return set_errno();
199*c303c47eSjoerg   buf->st_nlink = standard.NumberOfLinks;
200*c303c47eSjoerg   buf->st_size = standard.EndOfFile.QuadPart;
201*c303c47eSjoerg   BY_HANDLE_FILE_INFORMATION info;
202*c303c47eSjoerg   if (!GetFileInformationByHandle(h, &info))
203*c303c47eSjoerg     return set_errno();
204*c303c47eSjoerg   buf->st_dev = info.dwVolumeSerialNumber;
205*c303c47eSjoerg   memcpy(&buf->st_ino.id[0], &info.nFileIndexHigh, 4);
206*c303c47eSjoerg   memcpy(&buf->st_ino.id[4], &info.nFileIndexLow, 4);
207*c303c47eSjoerg   return 0;
208*c303c47eSjoerg }
209*c303c47eSjoerg 
stat_file(const wchar_t * path,StatT * buf,DWORD flags)210*c303c47eSjoerg int stat_file(const wchar_t *path, StatT *buf, DWORD flags) {
211*c303c47eSjoerg   WinHandle h(path, FILE_READ_ATTRIBUTES, flags);
212*c303c47eSjoerg   if (!h)
213*c303c47eSjoerg     return set_errno();
214*c303c47eSjoerg   int ret = stat_handle(h, buf);
215*c303c47eSjoerg   return ret;
216*c303c47eSjoerg }
217*c303c47eSjoerg 
stat(const wchar_t * path,StatT * buf)218*c303c47eSjoerg int stat(const wchar_t *path, StatT *buf) { return stat_file(path, buf, 0); }
219*c303c47eSjoerg 
lstat(const wchar_t * path,StatT * buf)220*c303c47eSjoerg int lstat(const wchar_t *path, StatT *buf) {
221*c303c47eSjoerg   return stat_file(path, buf, FILE_FLAG_OPEN_REPARSE_POINT);
222*c303c47eSjoerg }
223*c303c47eSjoerg 
fstat(int fd,StatT * buf)224*c303c47eSjoerg int fstat(int fd, StatT *buf) {
225*c303c47eSjoerg   HANDLE h = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
226*c303c47eSjoerg   return stat_handle(h, buf);
227*c303c47eSjoerg }
228*c303c47eSjoerg 
mkdir(const wchar_t * path,int permissions)229*c303c47eSjoerg int mkdir(const wchar_t *path, int permissions) {
230*c303c47eSjoerg   (void)permissions;
231*c303c47eSjoerg   return _wmkdir(path);
232*c303c47eSjoerg }
233*c303c47eSjoerg 
symlink_file_dir(const wchar_t * oldname,const wchar_t * newname,bool is_dir)234*c303c47eSjoerg int symlink_file_dir(const wchar_t *oldname, const wchar_t *newname,
235*c303c47eSjoerg                      bool is_dir) {
236*c303c47eSjoerg   path dest(oldname);
237*c303c47eSjoerg   dest.make_preferred();
238*c303c47eSjoerg   oldname = dest.c_str();
239*c303c47eSjoerg   DWORD flags = is_dir ? SYMBOLIC_LINK_FLAG_DIRECTORY : 0;
240*c303c47eSjoerg   if (CreateSymbolicLinkW(newname, oldname,
241*c303c47eSjoerg                           flags | SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE))
242*c303c47eSjoerg     return 0;
243*c303c47eSjoerg   int e = GetLastError();
244*c303c47eSjoerg   if (e != ERROR_INVALID_PARAMETER)
245*c303c47eSjoerg     return set_errno(e);
246*c303c47eSjoerg   if (CreateSymbolicLinkW(newname, oldname, flags))
247*c303c47eSjoerg     return 0;
248*c303c47eSjoerg   return set_errno();
249*c303c47eSjoerg }
250*c303c47eSjoerg 
symlink_file(const wchar_t * oldname,const wchar_t * newname)251*c303c47eSjoerg int symlink_file(const wchar_t *oldname, const wchar_t *newname) {
252*c303c47eSjoerg   return symlink_file_dir(oldname, newname, false);
253*c303c47eSjoerg }
254*c303c47eSjoerg 
symlink_dir(const wchar_t * oldname,const wchar_t * newname)255*c303c47eSjoerg int symlink_dir(const wchar_t *oldname, const wchar_t *newname) {
256*c303c47eSjoerg   return symlink_file_dir(oldname, newname, true);
257*c303c47eSjoerg }
258*c303c47eSjoerg 
link(const wchar_t * oldname,const wchar_t * newname)259*c303c47eSjoerg int link(const wchar_t *oldname, const wchar_t *newname) {
260*c303c47eSjoerg   if (CreateHardLinkW(newname, oldname, nullptr))
261*c303c47eSjoerg     return 0;
262*c303c47eSjoerg   return set_errno();
263*c303c47eSjoerg }
264*c303c47eSjoerg 
remove(const wchar_t * path)265*c303c47eSjoerg int remove(const wchar_t *path) {
266*c303c47eSjoerg   detail::WinHandle h(path, DELETE, FILE_FLAG_OPEN_REPARSE_POINT);
267*c303c47eSjoerg   if (!h)
268*c303c47eSjoerg     return set_errno();
269*c303c47eSjoerg   FILE_DISPOSITION_INFO info;
270*c303c47eSjoerg   info.DeleteFile = TRUE;
271*c303c47eSjoerg   if (!SetFileInformationByHandle(h, FileDispositionInfo, &info, sizeof(info)))
272*c303c47eSjoerg     return set_errno();
273*c303c47eSjoerg   return 0;
274*c303c47eSjoerg }
275*c303c47eSjoerg 
truncate_handle(HANDLE h,off_t length)276*c303c47eSjoerg int truncate_handle(HANDLE h, off_t length) {
277*c303c47eSjoerg   LARGE_INTEGER size_param;
278*c303c47eSjoerg   size_param.QuadPart = length;
279*c303c47eSjoerg   if (!SetFilePointerEx(h, size_param, 0, FILE_BEGIN))
280*c303c47eSjoerg     return set_errno();
281*c303c47eSjoerg   if (!SetEndOfFile(h))
282*c303c47eSjoerg     return set_errno();
283*c303c47eSjoerg   return 0;
284*c303c47eSjoerg }
285*c303c47eSjoerg 
ftruncate(int fd,off_t length)286*c303c47eSjoerg int ftruncate(int fd, off_t length) {
287*c303c47eSjoerg   HANDLE h = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
288*c303c47eSjoerg   return truncate_handle(h, length);
289*c303c47eSjoerg }
290*c303c47eSjoerg 
truncate(const wchar_t * path,off_t length)291*c303c47eSjoerg int truncate(const wchar_t *path, off_t length) {
292*c303c47eSjoerg   detail::WinHandle h(path, GENERIC_WRITE, 0);
293*c303c47eSjoerg   if (!h)
294*c303c47eSjoerg     return set_errno();
295*c303c47eSjoerg   return truncate_handle(h, length);
296*c303c47eSjoerg }
297*c303c47eSjoerg 
rename(const wchar_t * from,const wchar_t * to)298*c303c47eSjoerg int rename(const wchar_t *from, const wchar_t *to) {
299*c303c47eSjoerg   if (!(MoveFileExW(from, to,
300*c303c47eSjoerg                     MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING |
301*c303c47eSjoerg                         MOVEFILE_WRITE_THROUGH)))
302*c303c47eSjoerg     return set_errno();
303*c303c47eSjoerg   return 0;
304*c303c47eSjoerg }
305*c303c47eSjoerg 
open(const wchar_t * filename,Args...args)306*c303c47eSjoerg template <class... Args> int open(const wchar_t *filename, Args... args) {
307*c303c47eSjoerg   return _wopen(filename, args...);
308*c303c47eSjoerg }
close(int fd)309*c303c47eSjoerg int close(int fd) { return _close(fd); }
chdir(const wchar_t * path)310*c303c47eSjoerg int chdir(const wchar_t *path) { return _wchdir(path); }
311*c303c47eSjoerg 
312*c303c47eSjoerg struct StatVFS {
313*c303c47eSjoerg   uint64_t f_frsize;
314*c303c47eSjoerg   uint64_t f_blocks;
315*c303c47eSjoerg   uint64_t f_bfree;
316*c303c47eSjoerg   uint64_t f_bavail;
317*c303c47eSjoerg };
318*c303c47eSjoerg 
statvfs(const wchar_t * p,StatVFS * buf)319*c303c47eSjoerg int statvfs(const wchar_t *p, StatVFS *buf) {
320*c303c47eSjoerg   path dir = p;
321*c303c47eSjoerg   while (true) {
322*c303c47eSjoerg     error_code local_ec;
323*c303c47eSjoerg     const file_status st = status(dir, local_ec);
324*c303c47eSjoerg     if (!exists(st) || is_directory(st))
325*c303c47eSjoerg       break;
326*c303c47eSjoerg     path parent = dir.parent_path();
327*c303c47eSjoerg     if (parent == dir) {
328*c303c47eSjoerg       errno = ENOENT;
329*c303c47eSjoerg       return -1;
330*c303c47eSjoerg     }
331*c303c47eSjoerg     dir = parent;
332*c303c47eSjoerg   }
333*c303c47eSjoerg   ULARGE_INTEGER free_bytes_available_to_caller, total_number_of_bytes,
334*c303c47eSjoerg       total_number_of_free_bytes;
335*c303c47eSjoerg   if (!GetDiskFreeSpaceExW(dir.c_str(), &free_bytes_available_to_caller,
336*c303c47eSjoerg                            &total_number_of_bytes, &total_number_of_free_bytes))
337*c303c47eSjoerg     return set_errno();
338*c303c47eSjoerg   buf->f_frsize = 1;
339*c303c47eSjoerg   buf->f_blocks = total_number_of_bytes.QuadPart;
340*c303c47eSjoerg   buf->f_bfree = total_number_of_free_bytes.QuadPart;
341*c303c47eSjoerg   buf->f_bavail = free_bytes_available_to_caller.QuadPart;
342*c303c47eSjoerg   return 0;
343*c303c47eSjoerg }
344*c303c47eSjoerg 
getcwd(wchar_t * buff,size_t size)345*c303c47eSjoerg wchar_t *getcwd(wchar_t *buff, size_t size) { return _wgetcwd(buff, size); }
346*c303c47eSjoerg 
realpath(const wchar_t * path,wchar_t * resolved_name)347*c303c47eSjoerg wchar_t *realpath(const wchar_t *path, wchar_t *resolved_name) {
348*c303c47eSjoerg   // Only expected to be used with us allocating the buffer.
349*c303c47eSjoerg   _LIBCPP_ASSERT(resolved_name == nullptr,
350*c303c47eSjoerg                  "Windows realpath() assumes a null resolved_name");
351*c303c47eSjoerg 
352*c303c47eSjoerg   WinHandle h(path, FILE_READ_ATTRIBUTES, 0);
353*c303c47eSjoerg   if (!h) {
354*c303c47eSjoerg     set_errno();
355*c303c47eSjoerg     return nullptr;
356*c303c47eSjoerg   }
357*c303c47eSjoerg   size_t buff_size = MAX_PATH + 10;
358*c303c47eSjoerg   std::unique_ptr<wchar_t, decltype(&::free)> buff(
359*c303c47eSjoerg       static_cast<wchar_t *>(malloc(buff_size * sizeof(wchar_t))), &::free);
360*c303c47eSjoerg   DWORD retval = GetFinalPathNameByHandleW(
361*c303c47eSjoerg       h, buff.get(), buff_size, FILE_NAME_NORMALIZED | VOLUME_NAME_DOS);
362*c303c47eSjoerg   if (retval > buff_size) {
363*c303c47eSjoerg     buff_size = retval;
364*c303c47eSjoerg     buff.reset(static_cast<wchar_t *>(malloc(buff_size * sizeof(wchar_t))));
365*c303c47eSjoerg     retval = GetFinalPathNameByHandleW(h, buff.get(), buff_size,
366*c303c47eSjoerg                                        FILE_NAME_NORMALIZED | VOLUME_NAME_DOS);
367*c303c47eSjoerg   }
368*c303c47eSjoerg   if (!retval) {
369*c303c47eSjoerg     set_errno();
370*c303c47eSjoerg     return nullptr;
371*c303c47eSjoerg   }
372*c303c47eSjoerg   wchar_t *ptr = buff.get();
373*c303c47eSjoerg   if (!wcsncmp(ptr, L"\\\\?\\", 4)) {
374*c303c47eSjoerg     if (ptr[5] == ':') { // \\?\X: -> X:
375*c303c47eSjoerg       memmove(&ptr[0], &ptr[4], (wcslen(&ptr[4]) + 1) * sizeof(wchar_t));
376*c303c47eSjoerg     } else if (!wcsncmp(&ptr[4], L"UNC\\", 4)) { // \\?\UNC\server -> \\server
377*c303c47eSjoerg       wcscpy(&ptr[0], L"\\\\");
378*c303c47eSjoerg       memmove(&ptr[2], &ptr[8], (wcslen(&ptr[8]) + 1) * sizeof(wchar_t));
379*c303c47eSjoerg     }
380*c303c47eSjoerg   }
381*c303c47eSjoerg   return buff.release();
382*c303c47eSjoerg }
383*c303c47eSjoerg 
384*c303c47eSjoerg #define AT_FDCWD -1
385*c303c47eSjoerg #define AT_SYMLINK_NOFOLLOW 1
386*c303c47eSjoerg using ModeT = int;
387*c303c47eSjoerg 
fchmod_handle(HANDLE h,int perms)388*c303c47eSjoerg int fchmod_handle(HANDLE h, int perms) {
389*c303c47eSjoerg   FILE_BASIC_INFO basic;
390*c303c47eSjoerg   if (!GetFileInformationByHandleEx(h, FileBasicInfo, &basic, sizeof(basic)))
391*c303c47eSjoerg     return set_errno();
392*c303c47eSjoerg   DWORD orig_attributes = basic.FileAttributes;
393*c303c47eSjoerg   basic.FileAttributes &= ~FILE_ATTRIBUTE_READONLY;
394*c303c47eSjoerg   if ((perms & 0222) == 0)
395*c303c47eSjoerg     basic.FileAttributes |= FILE_ATTRIBUTE_READONLY;
396*c303c47eSjoerg   if (basic.FileAttributes != orig_attributes &&
397*c303c47eSjoerg       !SetFileInformationByHandle(h, FileBasicInfo, &basic, sizeof(basic)))
398*c303c47eSjoerg     return set_errno();
399*c303c47eSjoerg   return 0;
400*c303c47eSjoerg }
401*c303c47eSjoerg 
fchmodat(int fd,const wchar_t * path,int perms,int flag)402*c303c47eSjoerg int fchmodat(int fd, const wchar_t *path, int perms, int flag) {
403*c303c47eSjoerg   DWORD attributes = GetFileAttributesW(path);
404*c303c47eSjoerg   if (attributes == INVALID_FILE_ATTRIBUTES)
405*c303c47eSjoerg     return set_errno();
406*c303c47eSjoerg   if (attributes & FILE_ATTRIBUTE_REPARSE_POINT &&
407*c303c47eSjoerg       !(flag & AT_SYMLINK_NOFOLLOW)) {
408*c303c47eSjoerg     // If the file is a symlink, and we are supposed to operate on the target
409*c303c47eSjoerg     // of the symlink, we need to open a handle to it, without the
410*c303c47eSjoerg     // FILE_FLAG_OPEN_REPARSE_POINT flag, to open the destination of the
411*c303c47eSjoerg     // symlink, and operate on it via the handle.
412*c303c47eSjoerg     detail::WinHandle h(path, FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES, 0);
413*c303c47eSjoerg     if (!h)
414*c303c47eSjoerg       return set_errno();
415*c303c47eSjoerg     return fchmod_handle(h, perms);
416*c303c47eSjoerg   } else {
417*c303c47eSjoerg     // For a non-symlink, or if operating on the symlink itself instead of
418*c303c47eSjoerg     // its target, we can use SetFileAttributesW, saving a few calls.
419*c303c47eSjoerg     DWORD orig_attributes = attributes;
420*c303c47eSjoerg     attributes &= ~FILE_ATTRIBUTE_READONLY;
421*c303c47eSjoerg     if ((perms & 0222) == 0)
422*c303c47eSjoerg       attributes |= FILE_ATTRIBUTE_READONLY;
423*c303c47eSjoerg     if (attributes != orig_attributes && !SetFileAttributesW(path, attributes))
424*c303c47eSjoerg       return set_errno();
425*c303c47eSjoerg   }
426*c303c47eSjoerg   return 0;
427*c303c47eSjoerg }
428*c303c47eSjoerg 
fchmod(int fd,int perms)429*c303c47eSjoerg int fchmod(int fd, int perms) {
430*c303c47eSjoerg   HANDLE h = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
431*c303c47eSjoerg   return fchmod_handle(h, perms);
432*c303c47eSjoerg }
433*c303c47eSjoerg 
434*c303c47eSjoerg #define MAX_SYMLINK_SIZE MAXIMUM_REPARSE_DATA_BUFFER_SIZE
435*c303c47eSjoerg using SSizeT = ::int64_t;
436*c303c47eSjoerg 
readlink(const wchar_t * path,wchar_t * ret_buf,size_t bufsize)437*c303c47eSjoerg SSizeT readlink(const wchar_t *path, wchar_t *ret_buf, size_t bufsize) {
438*c303c47eSjoerg   uint8_t buf[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
439*c303c47eSjoerg   detail::WinHandle h(path, FILE_READ_ATTRIBUTES, FILE_FLAG_OPEN_REPARSE_POINT);
440*c303c47eSjoerg   if (!h)
441*c303c47eSjoerg     return set_errno();
442*c303c47eSjoerg   DWORD out;
443*c303c47eSjoerg   if (!DeviceIoControl(h, FSCTL_GET_REPARSE_POINT, nullptr, 0, buf, sizeof(buf),
444*c303c47eSjoerg                        &out, 0))
445*c303c47eSjoerg     return set_errno();
446*c303c47eSjoerg   const auto *reparse = reinterpret_cast<LIBCPP_REPARSE_DATA_BUFFER *>(buf);
447*c303c47eSjoerg   size_t path_buf_offset = offsetof(LIBCPP_REPARSE_DATA_BUFFER,
448*c303c47eSjoerg                                     SymbolicLinkReparseBuffer.PathBuffer[0]);
449*c303c47eSjoerg   if (out < path_buf_offset) {
450*c303c47eSjoerg     errno = EINVAL;
451*c303c47eSjoerg     return -1;
452*c303c47eSjoerg   }
453*c303c47eSjoerg   if (reparse->ReparseTag != IO_REPARSE_TAG_SYMLINK) {
454*c303c47eSjoerg     errno = EINVAL;
455*c303c47eSjoerg     return -1;
456*c303c47eSjoerg   }
457*c303c47eSjoerg   const auto &symlink = reparse->SymbolicLinkReparseBuffer;
458*c303c47eSjoerg   unsigned short name_offset, name_length;
459*c303c47eSjoerg   if (symlink.PrintNameLength == 0) {
460*c303c47eSjoerg     name_offset = symlink.SubstituteNameOffset;
461*c303c47eSjoerg     name_length = symlink.SubstituteNameLength;
462*c303c47eSjoerg   } else {
463*c303c47eSjoerg     name_offset = symlink.PrintNameOffset;
464*c303c47eSjoerg     name_length = symlink.PrintNameLength;
465*c303c47eSjoerg   }
466*c303c47eSjoerg   // name_offset/length are expressed in bytes, not in wchar_t
467*c303c47eSjoerg   if (path_buf_offset + name_offset + name_length > out) {
468*c303c47eSjoerg     errno = EINVAL;
469*c303c47eSjoerg     return -1;
470*c303c47eSjoerg   }
471*c303c47eSjoerg   if (name_length / sizeof(wchar_t) > bufsize) {
472*c303c47eSjoerg     errno = ENOMEM;
473*c303c47eSjoerg     return -1;
474*c303c47eSjoerg   }
475*c303c47eSjoerg   memcpy(ret_buf, &symlink.PathBuffer[name_offset / sizeof(wchar_t)],
476*c303c47eSjoerg          name_length);
477*c303c47eSjoerg   return name_length / sizeof(wchar_t);
478*c303c47eSjoerg }
479*c303c47eSjoerg 
480*c303c47eSjoerg #else
481*c303c47eSjoerg int symlink_file(const char *oldname, const char *newname) {
482*c303c47eSjoerg   return ::symlink(oldname, newname);
483*c303c47eSjoerg }
484*c303c47eSjoerg int symlink_dir(const char *oldname, const char *newname) {
485*c303c47eSjoerg   return ::symlink(oldname, newname);
486*c303c47eSjoerg }
487*c303c47eSjoerg using ::chdir;
488*c303c47eSjoerg using ::close;
489*c303c47eSjoerg using ::fchmod;
490*c303c47eSjoerg #if defined(AT_SYMLINK_NOFOLLOW) && defined(AT_FDCWD)
491*c303c47eSjoerg using ::fchmodat;
492*c303c47eSjoerg #endif
493*c303c47eSjoerg using ::fstat;
494*c303c47eSjoerg using ::ftruncate;
495*c303c47eSjoerg using ::getcwd;
496*c303c47eSjoerg using ::link;
497*c303c47eSjoerg using ::lstat;
498*c303c47eSjoerg using ::mkdir;
499*c303c47eSjoerg using ::open;
500*c303c47eSjoerg using ::readlink;
501*c303c47eSjoerg using ::realpath;
502*c303c47eSjoerg using ::remove;
503*c303c47eSjoerg using ::rename;
504*c303c47eSjoerg using ::stat;
505*c303c47eSjoerg using ::statvfs;
506*c303c47eSjoerg using ::truncate;
507*c303c47eSjoerg 
508*c303c47eSjoerg #define O_BINARY 0
509*c303c47eSjoerg 
510*c303c47eSjoerg using StatVFS = struct statvfs;
511*c303c47eSjoerg using ModeT = ::mode_t;
512*c303c47eSjoerg using SSizeT = ::ssize_t;
513*c303c47eSjoerg 
514*c303c47eSjoerg #endif
515*c303c47eSjoerg 
516*c303c47eSjoerg } // namespace
517*c303c47eSjoerg } // end namespace detail
518*c303c47eSjoerg 
519*c303c47eSjoerg _LIBCPP_END_NAMESPACE_FILESYSTEM
520*c303c47eSjoerg 
521*c303c47eSjoerg #endif // POSIX_COMPAT_H
522