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