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>
41 # include <sys/stat.h>
42 # include <sys/statvfs.h>
43 # 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)
123 # define O_NONBLOCK 0
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
) {
136 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
139 FILE_FLAG_BACKUP_SEMANTICS
| flags
,
143 if (h
!= INVALID_HANDLE_VALUE
)
146 operator HANDLE() const { return h
; }
147 operator bool() const { return h
!= INVALID_HANDLE_VALUE
; }
153 inline int stat_handle(HANDLE h
, StatT
* buf
) {
154 FILE_BASIC_INFO basic
;
155 if (!GetFileInformationByHandleEx(h
, FileBasicInfo
, &basic
, sizeof(basic
)))
157 memset(buf
, 0, sizeof(*buf
));
158 buf
->st_mtim
= filetime_to_timespec(basic
.LastWriteTime
);
159 buf
->st_atim
= filetime_to_timespec(basic
.LastAccessTime
);
160 buf
->st_mode
= 0555; // Read-only
161 if (!(basic
.FileAttributes
& FILE_ATTRIBUTE_READONLY
))
162 buf
->st_mode
|= 0222; // Write
163 if (basic
.FileAttributes
& FILE_ATTRIBUTE_DIRECTORY
) {
164 buf
->st_mode
|= _S_IFDIR
;
166 buf
->st_mode
|= _S_IFREG
;
168 if (basic
.FileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) {
169 FILE_ATTRIBUTE_TAG_INFO tag
;
170 if (!GetFileInformationByHandleEx(h
, FileAttributeTagInfo
, &tag
, sizeof(tag
)))
172 if (tag
.ReparseTag
== IO_REPARSE_TAG_SYMLINK
)
173 buf
->st_mode
= (buf
->st_mode
& ~_S_IFMT
) | _S_IFLNK
;
175 FILE_STANDARD_INFO standard
;
176 if (!GetFileInformationByHandleEx(h
, FileStandardInfo
, &standard
, sizeof(standard
)))
178 buf
->st_nlink
= standard
.NumberOfLinks
;
179 buf
->st_size
= standard
.EndOfFile
.QuadPart
;
180 BY_HANDLE_FILE_INFORMATION info
;
181 if (!GetFileInformationByHandle(h
, &info
))
183 buf
->st_dev
= info
.dwVolumeSerialNumber
;
184 memcpy(&buf
->st_ino
.id
[0], &info
.nFileIndexHigh
, 4);
185 memcpy(&buf
->st_ino
.id
[4], &info
.nFileIndexLow
, 4);
189 inline int stat_file(const wchar_t* path
, StatT
* buf
, DWORD flags
) {
190 WinHandle
h(path
, FILE_READ_ATTRIBUTES
, flags
);
193 int ret
= stat_handle(h
, buf
);
197 inline int stat(const wchar_t* path
, StatT
* buf
) { return stat_file(path
, buf
, 0); }
199 inline int lstat(const wchar_t* path
, StatT
* buf
) { return stat_file(path
, buf
, FILE_FLAG_OPEN_REPARSE_POINT
); }
201 inline int fstat(int fd
, StatT
* buf
) {
202 HANDLE h
= reinterpret_cast<HANDLE
>(_get_osfhandle(fd
));
203 return stat_handle(h
, buf
);
206 inline int mkdir(const wchar_t* path
, int permissions
) {
208 if (!CreateDirectoryW(path
, nullptr))
213 inline int symlink_file_dir(const wchar_t* oldname
, const wchar_t* newname
, bool is_dir
) {
215 dest
.make_preferred();
216 oldname
= dest
.c_str();
217 DWORD flags
= is_dir
? SYMBOLIC_LINK_FLAG_DIRECTORY
: 0;
218 if (CreateSymbolicLinkW(newname
, oldname
, flags
| SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE
))
220 int e
= GetLastError();
221 if (e
!= ERROR_INVALID_PARAMETER
)
223 if (CreateSymbolicLinkW(newname
, oldname
, flags
))
228 inline int symlink_file(const wchar_t* oldname
, const wchar_t* newname
) {
229 return symlink_file_dir(oldname
, newname
, false);
232 inline int symlink_dir(const wchar_t* oldname
, const wchar_t* newname
) {
233 return symlink_file_dir(oldname
, newname
, true);
236 inline int link(const wchar_t* oldname
, const wchar_t* newname
) {
237 if (CreateHardLinkW(newname
, oldname
, nullptr))
242 inline int remove(const wchar_t* path
) {
243 detail::WinHandle
h(path
, DELETE
, FILE_FLAG_OPEN_REPARSE_POINT
);
246 FILE_DISPOSITION_INFO info
;
247 info
.DeleteFile
= TRUE
;
248 if (!SetFileInformationByHandle(h
, FileDispositionInfo
, &info
, sizeof(info
)))
253 inline int truncate_handle(HANDLE h
, off_t length
) {
254 LARGE_INTEGER size_param
;
255 size_param
.QuadPart
= length
;
256 if (!SetFilePointerEx(h
, size_param
, 0, FILE_BEGIN
))
258 if (!SetEndOfFile(h
))
263 inline int ftruncate(int fd
, off_t length
) {
264 HANDLE h
= reinterpret_cast<HANDLE
>(_get_osfhandle(fd
));
265 return truncate_handle(h
, length
);
268 inline int truncate(const wchar_t* path
, off_t length
) {
269 detail::WinHandle
h(path
, GENERIC_WRITE
, 0);
272 return truncate_handle(h
, length
);
275 inline int rename(const wchar_t* from
, const wchar_t* to
) {
276 if (!(MoveFileExW(from
, to
, MOVEFILE_COPY_ALLOWED
| MOVEFILE_REPLACE_EXISTING
| MOVEFILE_WRITE_THROUGH
)))
281 inline int chdir(const wchar_t* path
) {
282 if (!SetCurrentDirectoryW(path
))
294 inline int statvfs(const wchar_t* p
, StatVFS
* buf
) {
298 const file_status st
= status(dir
, local_ec
);
299 if (!exists(st
) || is_directory(st
))
301 path parent
= dir
.parent_path();
308 ULARGE_INTEGER free_bytes_available_to_caller
, total_number_of_bytes
, total_number_of_free_bytes
;
309 if (!GetDiskFreeSpaceExW(
310 dir
.c_str(), &free_bytes_available_to_caller
, &total_number_of_bytes
, &total_number_of_free_bytes
))
313 buf
->f_blocks
= total_number_of_bytes
.QuadPart
;
314 buf
->f_bfree
= total_number_of_free_bytes
.QuadPart
;
315 buf
->f_bavail
= free_bytes_available_to_caller
.QuadPart
;
319 inline wchar_t* getcwd([[maybe_unused
]] wchar_t* in_buf
, [[maybe_unused
]] size_t in_size
) {
320 // Only expected to be used with us allocating the buffer.
321 _LIBCPP_ASSERT_INTERNAL(in_buf
== nullptr, "Windows getcwd() assumes in_buf==nullptr");
322 _LIBCPP_ASSERT_INTERNAL(in_size
== 0, "Windows getcwd() assumes in_size==0");
324 size_t buff_size
= MAX_PATH
+ 10;
325 std::unique_ptr
<wchar_t, decltype(&::free
)> buff(static_cast<wchar_t*>(malloc(buff_size
* sizeof(wchar_t))), &::free
);
326 DWORD retval
= GetCurrentDirectoryW(buff_size
, buff
.get());
327 if (retval
> buff_size
) {
329 buff
.reset(static_cast<wchar_t*>(malloc(buff_size
* sizeof(wchar_t))));
330 retval
= GetCurrentDirectoryW(buff_size
, buff
.get());
336 return buff
.release();
339 inline wchar_t* realpath(const wchar_t* path
, [[maybe_unused
]] wchar_t* resolved_name
) {
340 // Only expected to be used with us allocating the buffer.
341 _LIBCPP_ASSERT_INTERNAL(resolved_name
== nullptr, "Windows realpath() assumes a null resolved_name");
343 WinHandle
h(path
, FILE_READ_ATTRIBUTES
, 0);
348 size_t buff_size
= MAX_PATH
+ 10;
349 std::unique_ptr
<wchar_t, decltype(&::free
)> buff(static_cast<wchar_t*>(malloc(buff_size
* sizeof(wchar_t))), &::free
);
350 DWORD retval
= GetFinalPathNameByHandleW(h
, buff
.get(), buff_size
, FILE_NAME_NORMALIZED
| VOLUME_NAME_DOS
);
351 if (retval
> buff_size
) {
353 buff
.reset(static_cast<wchar_t*>(malloc(buff_size
* sizeof(wchar_t))));
354 retval
= GetFinalPathNameByHandleW(h
, buff
.get(), buff_size
, FILE_NAME_NORMALIZED
| VOLUME_NAME_DOS
);
360 wchar_t* ptr
= buff
.get();
361 if (!wcsncmp(ptr
, L
"\\\\?\\", 4)) {
362 if (ptr
[5] == ':') { // \\?\X: -> X:
363 memmove(&ptr
[0], &ptr
[4], (wcslen(&ptr
[4]) + 1) * sizeof(wchar_t));
364 } else if (!wcsncmp(&ptr
[4], L
"UNC\\", 4)) { // \\?\UNC\server -> \\server
365 wcscpy(&ptr
[0], L
"\\\\");
366 memmove(&ptr
[2], &ptr
[8], (wcslen(&ptr
[8]) + 1) * sizeof(wchar_t));
369 return buff
.release();
373 # define AT_SYMLINK_NOFOLLOW 1
376 inline int fchmod_handle(HANDLE h
, int perms
) {
377 FILE_BASIC_INFO basic
;
378 if (!GetFileInformationByHandleEx(h
, FileBasicInfo
, &basic
, sizeof(basic
)))
380 DWORD orig_attributes
= basic
.FileAttributes
;
381 basic
.FileAttributes
&= ~FILE_ATTRIBUTE_READONLY
;
382 if ((perms
& 0222) == 0)
383 basic
.FileAttributes
|= FILE_ATTRIBUTE_READONLY
;
384 if (basic
.FileAttributes
!= orig_attributes
&& !SetFileInformationByHandle(h
, FileBasicInfo
, &basic
, sizeof(basic
)))
389 inline int fchmodat(int /*fd*/, const wchar_t* path
, int perms
, int flag
) {
390 DWORD attributes
= GetFileAttributesW(path
);
391 if (attributes
== INVALID_FILE_ATTRIBUTES
)
393 if (attributes
& FILE_ATTRIBUTE_REPARSE_POINT
&& !(flag
& AT_SYMLINK_NOFOLLOW
)) {
394 // If the file is a symlink, and we are supposed to operate on the target
395 // of the symlink, we need to open a handle to it, without the
396 // FILE_FLAG_OPEN_REPARSE_POINT flag, to open the destination of the
397 // symlink, and operate on it via the handle.
398 detail::WinHandle
h(path
, FILE_READ_ATTRIBUTES
| FILE_WRITE_ATTRIBUTES
, 0);
401 return fchmod_handle(h
, perms
);
403 // For a non-symlink, or if operating on the symlink itself instead of
404 // its target, we can use SetFileAttributesW, saving a few calls.
405 DWORD orig_attributes
= attributes
;
406 attributes
&= ~FILE_ATTRIBUTE_READONLY
;
407 if ((perms
& 0222) == 0)
408 attributes
|= FILE_ATTRIBUTE_READONLY
;
409 if (attributes
!= orig_attributes
&& !SetFileAttributesW(path
, attributes
))
415 inline int fchmod(int fd
, int perms
) {
416 HANDLE h
= reinterpret_cast<HANDLE
>(_get_osfhandle(fd
));
417 return fchmod_handle(h
, perms
);
420 # define MAX_SYMLINK_SIZE MAXIMUM_REPARSE_DATA_BUFFER_SIZE
421 using SSizeT
= ::int64_t;
423 inline SSizeT
readlink(const wchar_t* path
, wchar_t* ret_buf
, size_t bufsize
) {
424 uint8_t buf
[MAXIMUM_REPARSE_DATA_BUFFER_SIZE
];
425 detail::WinHandle
h(path
, FILE_READ_ATTRIBUTES
, FILE_FLAG_OPEN_REPARSE_POINT
);
429 if (!DeviceIoControl(h
, FSCTL_GET_REPARSE_POINT
, nullptr, 0, buf
, sizeof(buf
), &out
, 0))
431 const auto* reparse
= reinterpret_cast<LIBCPP_REPARSE_DATA_BUFFER
*>(buf
);
432 size_t path_buf_offset
= offsetof(LIBCPP_REPARSE_DATA_BUFFER
, SymbolicLinkReparseBuffer
.PathBuffer
[0]);
433 if (out
< path_buf_offset
) {
437 if (reparse
->ReparseTag
!= IO_REPARSE_TAG_SYMLINK
) {
441 const auto& symlink
= reparse
->SymbolicLinkReparseBuffer
;
442 unsigned short name_offset
, name_length
;
443 if (symlink
.PrintNameLength
== 0) {
444 name_offset
= symlink
.SubstituteNameOffset
;
445 name_length
= symlink
.SubstituteNameLength
;
447 name_offset
= symlink
.PrintNameOffset
;
448 name_length
= symlink
.PrintNameLength
;
450 // name_offset/length are expressed in bytes, not in wchar_t
451 if (path_buf_offset
+ name_offset
+ name_length
> out
) {
455 if (name_length
/ sizeof(wchar_t) > bufsize
) {
459 memcpy(ret_buf
, &symlink
.PathBuffer
[name_offset
/ sizeof(wchar_t)], name_length
);
460 return name_length
/ sizeof(wchar_t);
464 inline int symlink_file(const char* oldname
, const char* newname
) { return ::symlink(oldname
, newname
); }
465 inline int symlink_dir(const char* oldname
, const char* newname
) { return ::symlink(oldname
, newname
); }
468 # if defined(AT_SYMLINK_NOFOLLOW) && defined(AT_FDCWD)
487 using StatVFS
= struct statvfs
;
488 using ModeT
= ::mode_t
;
489 using SSizeT
= ::ssize_t
;
493 } // namespace detail
495 _LIBCPP_END_NAMESPACE_FILESYSTEM
497 #endif // POSIX_COMPAT_H