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

Provided by KDAB

Privacy Policy
Improve your Profiling and Debugging skills
Find out more

source code of libcxx/src/filesystem/posix_compat.h