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