SystemWindows.cpp 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. /*
  2. * Copyright (c) 2021-2022, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021-2022, Kenneth Myhra <kennethmyhra@serenityos.org>
  4. * Copyright (c) 2021-2022, Sam Atkins <atkinssj@serenityos.org>
  5. * Copyright (c) 2022, Matthias Zimmerman <matthias291999@gmail.com>
  6. * Copyright (c) 2023, Cameron Youell <cameronyouell@gmail.com>
  7. * Copyright (c) 2024, stasoid <stasoid@yahoo.com>
  8. *
  9. * SPDX-License-Identifier: BSD-2-Clause
  10. */
  11. #include <AK/ByteString.h>
  12. #include <AK/ScopeGuard.h>
  13. #include <LibCore/System.h>
  14. #include <Windows.h>
  15. #include <direct.h>
  16. #include <io.h>
  17. #include <sys/mman.h>
  18. namespace Core::System {
  19. ErrorOr<int> open(StringView path, int options, mode_t mode)
  20. {
  21. ByteString string_path = path;
  22. auto sz_path = string_path.characters();
  23. int rc = _open(sz_path, options | O_BINARY, mode);
  24. if (rc < 0) {
  25. int error = errno;
  26. struct stat st = {};
  27. if (::stat(sz_path, &st) == 0 && (st.st_mode & S_IFDIR)) {
  28. HANDLE dir_handle = CreateFile(sz_path, GENERIC_ALL, 0, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
  29. if (dir_handle == INVALID_HANDLE_VALUE)
  30. return Error::from_windows_error(GetLastError());
  31. int dir_fd = _open_osfhandle((intptr_t)dir_handle, 0);
  32. if (dir_fd != -1)
  33. return dir_fd;
  34. }
  35. return Error::from_syscall("open"sv, -error);
  36. }
  37. return rc;
  38. }
  39. ErrorOr<void> close(int fd)
  40. {
  41. if (_close(fd) < 0)
  42. return Error::from_syscall("close"sv, -errno);
  43. return {};
  44. }
  45. ErrorOr<ssize_t> read(int fd, Bytes buffer)
  46. {
  47. int rc = _read(fd, buffer.data(), buffer.size());
  48. if (rc < 0)
  49. return Error::from_syscall("read"sv, -errno);
  50. return rc;
  51. }
  52. ErrorOr<ssize_t> write(int fd, ReadonlyBytes buffer)
  53. {
  54. int rc = _write(fd, buffer.data(), buffer.size());
  55. if (rc < 0)
  56. return Error::from_syscall("write"sv, -errno);
  57. return rc;
  58. }
  59. ErrorOr<off_t> lseek(int fd, off_t offset, int whence)
  60. {
  61. long rc = _lseek(fd, offset, whence);
  62. if (rc < 0)
  63. return Error::from_syscall("lseek"sv, -errno);
  64. return rc;
  65. }
  66. ErrorOr<void> ftruncate(int fd, off_t length)
  67. {
  68. long position = _tell(fd);
  69. if (position == -1)
  70. return Error::from_errno(errno);
  71. ScopeGuard restore_position { [&] { _lseek(fd, position, SEEK_SET); } };
  72. auto result = lseek(fd, length, SEEK_SET);
  73. if (result.is_error())
  74. return result.release_error();
  75. if (SetEndOfFile((HANDLE)_get_osfhandle(fd)) == 0)
  76. return Error::from_windows_error(GetLastError());
  77. return {};
  78. }
  79. ErrorOr<struct stat> fstat(int fd)
  80. {
  81. struct stat st = {};
  82. if (::fstat(fd, &st) < 0)
  83. return Error::from_syscall("fstat"sv, -errno);
  84. return st;
  85. }
  86. ErrorOr<void> ioctl(int, unsigned, ...)
  87. {
  88. dbgln("Core::System::ioctl() is not implemented");
  89. VERIFY_NOT_REACHED();
  90. }
  91. ErrorOr<ByteString> getcwd()
  92. {
  93. auto* cwd = _getcwd(nullptr, 0);
  94. if (!cwd)
  95. return Error::from_syscall("getcwd"sv, -errno);
  96. ByteString string_cwd(cwd);
  97. free(cwd);
  98. return string_cwd;
  99. }
  100. ErrorOr<struct stat> stat(StringView path)
  101. {
  102. if (path.is_null())
  103. return Error::from_syscall("stat"sv, -EFAULT);
  104. struct stat st = {};
  105. ByteString path_string = path;
  106. if (::stat(path_string.characters(), &st) < 0)
  107. return Error::from_syscall("stat"sv, -errno);
  108. return st;
  109. }
  110. ErrorOr<void> rmdir(StringView path)
  111. {
  112. if (path.is_null())
  113. return Error::from_errno(EFAULT);
  114. ByteString path_string = path;
  115. if (_rmdir(path_string.characters()) < 0)
  116. return Error::from_syscall("rmdir"sv, -errno);
  117. return {};
  118. }
  119. ErrorOr<void> unlink(StringView path)
  120. {
  121. if (path.is_null())
  122. return Error::from_errno(EFAULT);
  123. ByteString path_string = path;
  124. if (_unlink(path_string.characters()) < 0)
  125. return Error::from_syscall("unlink"sv, -errno);
  126. return {};
  127. }
  128. ErrorOr<void> mkdir(StringView path, mode_t)
  129. {
  130. ByteString str = path;
  131. if (_mkdir(str.characters()) < 0)
  132. return Error::from_syscall("mkdir"sv, -errno);
  133. return {};
  134. }
  135. ErrorOr<int> openat(int, StringView, int, mode_t)
  136. {
  137. dbgln("Core::System::openat() is not implemented");
  138. VERIFY_NOT_REACHED();
  139. }
  140. ErrorOr<struct stat> fstatat(int, StringView, int)
  141. {
  142. dbgln("Core::System::fstatat() is not implemented");
  143. VERIFY_NOT_REACHED();
  144. }
  145. ErrorOr<void*> mmap(void* address, size_t size, int protection, int flags, int fd, off_t offset, size_t alignment, StringView)
  146. {
  147. // custom alignment is not supported
  148. VERIFY(!alignment);
  149. void* ptr = ::mmap(address, size, protection, flags, fd, offset);
  150. if (ptr == MAP_FAILED)
  151. return Error::from_syscall("mmap"sv, -errno);
  152. return ptr;
  153. }
  154. ErrorOr<void> munmap(void* address, size_t size)
  155. {
  156. if (::munmap(address, size) < 0)
  157. return Error::from_syscall("munmap"sv, -errno);
  158. return {};
  159. }
  160. int getpid()
  161. {
  162. return GetCurrentProcessId();
  163. }
  164. /* https://github.com/ncm/selectable-socketpair
  165. Copyright 2007, 2010 by Nathan C. Myers <ncm@cantrip.org>
  166. Redistribution and use in source and binary forms, with or without modification,
  167. are permitted provided that the following conditions are met:
  168. Redistributions of source code must retain the above copyright notice, this
  169. list of conditions and the following disclaimer.
  170. Redistributions in binary form must reproduce the above copyright notice,
  171. this list of conditions and the following disclaimer in the documentation
  172. and/or other materials provided with the distribution.
  173. The name of the author must not be used to endorse or promote products
  174. derived from this software without specific prior written permission.
  175. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  176. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  177. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  178. DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  179. FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  180. DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  181. SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  182. CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  183. OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  184. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  185. */
  186. static int dumb_socketpair(SOCKET socks[2], int make_overlapped)
  187. {
  188. union {
  189. struct sockaddr_in inaddr;
  190. struct sockaddr addr;
  191. } a;
  192. SOCKET listener;
  193. int e;
  194. socklen_t addrlen = sizeof(a.inaddr);
  195. DWORD flags = (make_overlapped ? WSA_FLAG_OVERLAPPED : 0);
  196. int reuse = 1;
  197. if (socks == 0) {
  198. WSASetLastError(WSAEINVAL);
  199. return SOCKET_ERROR;
  200. }
  201. socks[0] = socks[1] = -1;
  202. listener = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  203. if (listener == INVALID_SOCKET)
  204. return SOCKET_ERROR;
  205. memset(&a, 0, sizeof(a));
  206. a.inaddr.sin_family = AF_INET;
  207. a.inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  208. a.inaddr.sin_port = 0;
  209. for (;;) {
  210. if (::setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, (char*)&reuse, (socklen_t)sizeof(reuse)) == -1)
  211. break;
  212. if (bind(listener, &a.addr, sizeof(a.inaddr)) == SOCKET_ERROR)
  213. break;
  214. memset(&a, 0, sizeof(a));
  215. if (getsockname(listener, &a.addr, &addrlen) == SOCKET_ERROR)
  216. break;
  217. // win32 getsockname may only set the port number, p=0.0005.
  218. // ( http://msdn.microsoft.com/library/ms738543.aspx ):
  219. a.inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  220. a.inaddr.sin_family = AF_INET;
  221. if (::listen(listener, 1) == SOCKET_ERROR)
  222. break;
  223. socks[0] = WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0, flags);
  224. if (socks[0] == INVALID_SOCKET)
  225. break;
  226. if (connect(socks[0], &a.addr, sizeof(a.inaddr)) == SOCKET_ERROR)
  227. break;
  228. socks[1] = ::accept(listener, NULL, NULL);
  229. if (socks[1] == INVALID_SOCKET)
  230. break;
  231. closesocket(listener);
  232. return 0;
  233. }
  234. e = WSAGetLastError();
  235. closesocket(listener);
  236. closesocket(socks[0]);
  237. closesocket(socks[1]);
  238. WSASetLastError(e);
  239. socks[0] = socks[1] = -1;
  240. return SOCKET_ERROR;
  241. }
  242. ErrorOr<void> socketpair(int domain, int type, int protocol, int sv[2])
  243. {
  244. if (domain != AF_LOCAL || type != SOCK_STREAM || protocol != 0)
  245. return Error::from_string_literal("Unsupported argument value");
  246. SOCKET socks[2] = {};
  247. if (dumb_socketpair(socks, true))
  248. return Error::from_windows_error();
  249. sv[0] = handle_to_fd(socks[0], SocketHandle);
  250. sv[1] = handle_to_fd(socks[1], SocketHandle);
  251. return {};
  252. }
  253. }