1 //===----------------------------------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
10 // POSIX-like portability helper functions.
12 // These generally behave like the proper posix functions, with these
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()
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.
23 #ifndef POSIX_COMPAT_H
24 #define POSIX_COMPAT_H
31 #include "time_utils.h"
33 #if defined(_LIBCPP_WIN32API)
34 # define WIN32_LEAN_AND_MEAN
38 # include <winioctl.h>
42 # include <sys/stat.h>
43 # include <sys/statvfs.h>
44 # include <sys/time.h>
49 #if defined(_LIBCPP_WIN32API)
50 // This struct isn't defined in the normal Windows SDK, but only in the
51 // Windows Driver Kit.
52 struct LIBCPP_REPARSE_DATA_BUFFER
{
53 unsigned long ReparseTag
;
54 unsigned short ReparseDataLength
;
55 unsigned short Reserved
;
58 unsigned short SubstituteNameOffset
;
59 unsigned short SubstituteNameLength
;
60 unsigned short PrintNameOffset
;
61 unsigned short PrintNameLength
;
63 wchar_t PathBuffer
[1];
64 } SymbolicLinkReparseBuffer
;
66 unsigned short SubstituteNameOffset
;
67 unsigned short SubstituteNameLength
;
68 unsigned short PrintNameOffset
;
69 unsigned short PrintNameLength
;
70 wchar_t PathBuffer
[1];
71 } MountPointReparseBuffer
;
73 unsigned char DataBuffer
[1];
74 } GenericReparseBuffer
;
79 _LIBCPP_BEGIN_NAMESPACE_FILESYSTEM
83 #if defined(_LIBCPP_WIN32API)
85 // Various C runtime header sets provide more or less of these. As we
86 // provide our own implementation, undef all potential defines from the
87 // C runtime headers and provide a complete set of macros of our own.
98 #define _S_IFMT 0xF000
99 #define _S_IFDIR 0x4000
100 #define _S_IFCHR 0x2000
101 #define _S_IFIFO 0x1000
102 #define _S_IFREG 0x8000
103 #define _S_IFBLK 0x6000
104 #define _S_IFLNK 0xA000
105 #define _S_IFSOCK 0xC000
115 #define S_ISDIR(m) (((m) & _S_IFMT) == _S_IFDIR)
116 #define S_ISCHR(m) (((m) & _S_IFMT) == _S_IFCHR)
117 #define S_ISFIFO(m) (((m) & _S_IFMT) == _S_IFIFO)
118 #define S_ISREG(m) (((m) & _S_IFMT) == _S_IFREG)
119 #define S_ISBLK(m) (((m) & _S_IFMT) == _S_IFBLK)
120 #define S_ISLNK(m) (((m) & _S_IFMT) == _S_IFLNK)
121 #define S_ISSOCK(m) (((m) & _S_IFMT) == _S_IFSOCK)
125 inline int set_errno(int e
= GetLastError()) {
126 errno
= static_cast<int>(__win_err_to_errc(e
));
132 WinHandle(const wchar_t *p
, DWORD access
, DWORD flags
) {
134 p
, access
, FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
135 nullptr, OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
| flags
, nullptr);
138 if (h
!= INVALID_HANDLE_VALUE
)
141 operator HANDLE() const { return h
; }
142 operator bool() const { return h
!= INVALID_HANDLE_VALUE
; }
148 inline int stat_handle(HANDLE h
, StatT
*buf
) {
149 FILE_BASIC_INFO basic
;
150 if (!GetFileInformationByHandleEx(h
, FileBasicInfo
, &basic
, sizeof(basic
)))
152 memset(buf
, 0, sizeof(*buf
));
153 buf
->st_mtim
= filetime_to_timespec(basic
.LastWriteTime
);
154 buf
->st_atim
= filetime_to_timespec(basic
.LastAccessTime
);
155 buf
->st_mode
= 0555; // Read-only
156 if (!(basic
.FileAttributes
& FILE_ATTRIBUTE_READONLY
))
157 buf
->st_mode
|= 0222; // Write
158 if (basic
.FileAttributes
& FILE_ATTRIBUTE_DIRECTORY
) {
159 buf
->st_mode
|= _S_IFDIR
;
161 buf
->st_mode
|= _S_IFREG
;
163 if (basic
.FileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) {
164 FILE_ATTRIBUTE_TAG_INFO tag
;
165 if (!GetFileInformationByHandleEx(h
, FileAttributeTagInfo
, &tag
,
168 if (tag
.ReparseTag
== IO_REPARSE_TAG_SYMLINK
)
169 buf
->st_mode
= (buf
->st_mode
& ~_S_IFMT
) | _S_IFLNK
;
171 FILE_STANDARD_INFO standard
;
172 if (!GetFileInformationByHandleEx(h
, FileStandardInfo
, &standard
,
175 buf
->st_nlink
= standard
.NumberOfLinks
;
176 buf
->st_size
= standard
.EndOfFile
.QuadPart
;
177 BY_HANDLE_FILE_INFORMATION info
;
178 if (!GetFileInformationByHandle(h
, &info
))
180 buf
->st_dev
= info
.dwVolumeSerialNumber
;
181 memcpy(&buf
->st_ino
.id
[0], &info
.nFileIndexHigh
, 4);
182 memcpy(&buf
->st_ino
.id
[4], &info
.nFileIndexLow
, 4);
186 inline int stat_file(const wchar_t *path
, StatT
*buf
, DWORD flags
) {
187 WinHandle
h(path
, FILE_READ_ATTRIBUTES
, flags
);
190 int ret
= stat_handle(h
, buf
);
194 inline int stat(const wchar_t *path
, StatT
*buf
) { return stat_file(path
, buf
, 0); }
196 inline int lstat(const wchar_t *path
, StatT
*buf
) {
197 return stat_file(path
, buf
, FILE_FLAG_OPEN_REPARSE_POINT
);
200 inline int fstat(int fd
, StatT
*buf
) {
201 HANDLE h
= reinterpret_cast<HANDLE
>(_get_osfhandle(fd
));
202 return stat_handle(h
, buf
);
205 inline int mkdir(const wchar_t *path
, int permissions
) {
207 if (!CreateDirectoryW(path
, nullptr))
212 inline int symlink_file_dir(const wchar_t *oldname
, const wchar_t *newname
,
215 dest
.make_preferred();
216 oldname
= dest
.c_str();
217 DWORD flags
= is_dir
? SYMBOLIC_LINK_FLAG_DIRECTORY
: 0;
218 if (CreateSymbolicLinkW(newname
, oldname
,
219 flags
| SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE
))
221 int e
= GetLastError();
222 if (e
!= ERROR_INVALID_PARAMETER
)
224 if (CreateSymbolicLinkW(newname
, oldname
, flags
))
229 inline int symlink_file(const wchar_t *oldname
, const wchar_t *newname
) {
230 return symlink_file_dir(oldname
, newname
, false);
233 inline int symlink_dir(const wchar_t *oldname
, const wchar_t *newname
) {
234 return symlink_file_dir(oldname
, newname
, true);
237 inline int link(const wchar_t *oldname
, const wchar_t *newname
) {
238 if (CreateHardLinkW(newname
, oldname
, nullptr))
243 inline int remove(const wchar_t *path
) {
244 detail::WinHandle
h(path
, DELETE
, FILE_FLAG_OPEN_REPARSE_POINT
);
247 FILE_DISPOSITION_INFO info
;
248 info
.DeleteFile
= TRUE
;
249 if (!SetFileInformationByHandle(h
, FileDispositionInfo
, &info
, sizeof(info
)))
254 inline int truncate_handle(HANDLE h
, off_t length
) {
255 LARGE_INTEGER size_param
;
256 size_param
.QuadPart
= length
;
257 if (!SetFilePointerEx(h
, size_param
, 0, FILE_BEGIN
))
259 if (!SetEndOfFile(h
))
264 inline int ftruncate(int fd
, off_t length
) {
265 HANDLE h
= reinterpret_cast<HANDLE
>(_get_osfhandle(fd
));
266 return truncate_handle(h
, length
);
269 inline int truncate(const wchar_t *path
, off_t length
) {
270 detail::WinHandle
h(path
, GENERIC_WRITE
, 0);
273 return truncate_handle(h
, length
);
276 inline int rename(const wchar_t *from
, const wchar_t *to
) {
277 if (!(MoveFileExW(from
, to
,
278 MOVEFILE_COPY_ALLOWED
| MOVEFILE_REPLACE_EXISTING
|
279 MOVEFILE_WRITE_THROUGH
)))
284 inline int chdir(const wchar_t* path
) {
285 if (!SetCurrentDirectoryW(path
))
297 inline int statvfs(const wchar_t *p
, StatVFS
*buf
) {
301 const file_status st
= status(dir
, local_ec
);
302 if (!exists(st
) || is_directory(st
))
304 path parent
= dir
.parent_path();
311 ULARGE_INTEGER free_bytes_available_to_caller
, total_number_of_bytes
,
312 total_number_of_free_bytes
;
313 if (!GetDiskFreeSpaceExW(dir
.c_str(), &free_bytes_available_to_caller
,
314 &total_number_of_bytes
, &total_number_of_free_bytes
))
317 buf
->f_blocks
= total_number_of_bytes
.QuadPart
;
318 buf
->f_bfree
= total_number_of_free_bytes
.QuadPart
;
319 buf
->f_bavail
= free_bytes_available_to_caller
.QuadPart
;
323 inline wchar_t* getcwd([[maybe_unused
]] wchar_t* in_buf
, [[maybe_unused
]] size_t in_size
) {
324 // Only expected to be used with us allocating the buffer.
325 _LIBCPP_ASSERT_UNCATEGORIZED(in_buf
== nullptr, "Windows getcwd() assumes in_buf==nullptr");
326 _LIBCPP_ASSERT_UNCATEGORIZED(in_size
== 0, "Windows getcwd() assumes in_size==0");
328 size_t buff_size
= MAX_PATH
+ 10;
329 std::unique_ptr
<wchar_t, decltype(&::free
)> buff(static_cast<wchar_t*>(malloc(buff_size
* sizeof(wchar_t))), &::free
);
330 DWORD retval
= GetCurrentDirectoryW(buff_size
, buff
.get());
331 if (retval
> buff_size
) {
333 buff
.reset(static_cast<wchar_t*>(malloc(buff_size
* sizeof(wchar_t))));
334 retval
= GetCurrentDirectoryW(buff_size
, buff
.get());
340 return buff
.release();
343 inline wchar_t *realpath(const wchar_t *path
, [[maybe_unused
]] wchar_t *resolved_name
) {
344 // Only expected to be used with us allocating the buffer.
345 _LIBCPP_ASSERT_UNCATEGORIZED(resolved_name
== nullptr,
346 "Windows realpath() assumes a null resolved_name");
348 WinHandle
h(path
, FILE_READ_ATTRIBUTES
, 0);
353 size_t buff_size
= MAX_PATH
+ 10;
354 std::unique_ptr
<wchar_t, decltype(&::free
)> buff(
355 static_cast<wchar_t *>(malloc(buff_size
* sizeof(wchar_t))), &::free
);
356 DWORD retval
= GetFinalPathNameByHandleW(
357 h
, buff
.get(), buff_size
, FILE_NAME_NORMALIZED
| VOLUME_NAME_DOS
);
358 if (retval
> buff_size
) {
360 buff
.reset(static_cast<wchar_t *>(malloc(buff_size
* sizeof(wchar_t))));
361 retval
= GetFinalPathNameByHandleW(h
, buff
.get(), buff_size
,
362 FILE_NAME_NORMALIZED
| VOLUME_NAME_DOS
);
368 wchar_t *ptr
= buff
.get();
369 if (!wcsncmp(ptr
, L
"\\\\?\\", 4)) {
370 if (ptr
[5] == ':') { // \\?\X: -> X:
371 memmove(&ptr
[0], &ptr
[4], (wcslen(&ptr
[4]) + 1) * sizeof(wchar_t));
372 } else if (!wcsncmp(&ptr
[4], L
"UNC\\", 4)) { // \\?\UNC\server -> \\server
373 wcscpy(&ptr
[0], L
"\\\\");
374 memmove(&ptr
[2], &ptr
[8], (wcslen(&ptr
[8]) + 1) * sizeof(wchar_t));
377 return buff
.release();
381 #define AT_SYMLINK_NOFOLLOW 1
384 inline int fchmod_handle(HANDLE h
, int perms
) {
385 FILE_BASIC_INFO basic
;
386 if (!GetFileInformationByHandleEx(h
, FileBasicInfo
, &basic
, sizeof(basic
)))
388 DWORD orig_attributes
= basic
.FileAttributes
;
389 basic
.FileAttributes
&= ~FILE_ATTRIBUTE_READONLY
;
390 if ((perms
& 0222) == 0)
391 basic
.FileAttributes
|= FILE_ATTRIBUTE_READONLY
;
392 if (basic
.FileAttributes
!= orig_attributes
&&
393 !SetFileInformationByHandle(h
, FileBasicInfo
, &basic
, sizeof(basic
)))
398 inline int fchmodat(int /*fd*/, const wchar_t *path
, int perms
, int flag
) {
399 DWORD attributes
= GetFileAttributesW(path
);
400 if (attributes
== INVALID_FILE_ATTRIBUTES
)
402 if (attributes
& FILE_ATTRIBUTE_REPARSE_POINT
&&
403 !(flag
& AT_SYMLINK_NOFOLLOW
)) {
404 // If the file is a symlink, and we are supposed to operate on the target
405 // of the symlink, we need to open a handle to it, without the
406 // FILE_FLAG_OPEN_REPARSE_POINT flag, to open the destination of the
407 // symlink, and operate on it via the handle.
408 detail::WinHandle
h(path
, FILE_READ_ATTRIBUTES
| FILE_WRITE_ATTRIBUTES
, 0);
411 return fchmod_handle(h
, perms
);
413 // For a non-symlink, or if operating on the symlink itself instead of
414 // its target, we can use SetFileAttributesW, saving a few calls.
415 DWORD orig_attributes
= attributes
;
416 attributes
&= ~FILE_ATTRIBUTE_READONLY
;
417 if ((perms
& 0222) == 0)
418 attributes
|= FILE_ATTRIBUTE_READONLY
;
419 if (attributes
!= orig_attributes
&& !SetFileAttributesW(path
, attributes
))
425 inline int fchmod(int fd
, int perms
) {
426 HANDLE h
= reinterpret_cast<HANDLE
>(_get_osfhandle(fd
));
427 return fchmod_handle(h
, perms
);
430 #define MAX_SYMLINK_SIZE MAXIMUM_REPARSE_DATA_BUFFER_SIZE
431 using SSizeT
= ::int64_t;
433 inline SSizeT
readlink(const wchar_t *path
, wchar_t *ret_buf
, size_t bufsize
) {
434 uint8_t buf
[MAXIMUM_REPARSE_DATA_BUFFER_SIZE
];
435 detail::WinHandle
h(path
, FILE_READ_ATTRIBUTES
, FILE_FLAG_OPEN_REPARSE_POINT
);
439 if (!DeviceIoControl(h
, FSCTL_GET_REPARSE_POINT
, nullptr, 0, buf
, sizeof(buf
),
442 const auto *reparse
= reinterpret_cast<LIBCPP_REPARSE_DATA_BUFFER
*>(buf
);
443 size_t path_buf_offset
= offsetof(LIBCPP_REPARSE_DATA_BUFFER
,
444 SymbolicLinkReparseBuffer
.PathBuffer
[0]);
445 if (out
< path_buf_offset
) {
449 if (reparse
->ReparseTag
!= IO_REPARSE_TAG_SYMLINK
) {
453 const auto &symlink
= reparse
->SymbolicLinkReparseBuffer
;
454 unsigned short name_offset
, name_length
;
455 if (symlink
.PrintNameLength
== 0) {
456 name_offset
= symlink
.SubstituteNameOffset
;
457 name_length
= symlink
.SubstituteNameLength
;
459 name_offset
= symlink
.PrintNameOffset
;
460 name_length
= symlink
.PrintNameLength
;
462 // name_offset/length are expressed in bytes, not in wchar_t
463 if (path_buf_offset
+ name_offset
+ name_length
> out
) {
467 if (name_length
/ sizeof(wchar_t) > bufsize
) {
471 memcpy(ret_buf
, &symlink
.PathBuffer
[name_offset
/ sizeof(wchar_t)],
473 return name_length
/ sizeof(wchar_t);
477 inline int symlink_file(const char *oldname
, const char *newname
) {
478 return ::symlink(oldname
, newname
);
480 inline int symlink_dir(const char *oldname
, const char *newname
) {
481 return ::symlink(oldname
, newname
);
485 #if defined(AT_SYMLINK_NOFOLLOW) && defined(AT_FDCWD)
504 using StatVFS
= struct statvfs
;
505 using ModeT
= ::mode_t
;
506 using SSizeT
= ::ssize_t
;
510 } // end namespace detail
512 _LIBCPP_END_NAMESPACE_FILESYSTEM
514 #endif // POSIX_COMPAT_H