Ruby 4.1.0dev (2026-11-17 revision 373d8c72a360f0d6c3be9cd13d1f0c27360e5d90)
win32.c
1/*
2 * Copyright (c) 1993, Intergraph Corporation
3 *
4 * You may distribute under the terms of either the GNU General Public
5 * License or the Artistic License, as specified in the perl README file.
6 *
7 * Various Unix compatibility functions and NT specific functions.
8 *
9 * Some of this code was derived from the MSDOS port(s) and the OS/2 port.
10 *
11 */
12/*
13 The parts licensed under above copyright notice are marked as "Artistic or
14 GPL".
15 Another parts are licensed under Ruby's License.
16
17 Copyright (C) 1993-2011 Yukihiro Matsumoto
18 Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
19 Copyright (C) 2000 Information-technology Promotion Agency, Japan
20 */
21
22#undef __STRICT_ANSI__
23
24/* Visual C++ 2015 (14.0):
25 * - _MSC_VER: 1900
26 * - MSVCRT_VERSION: 140
27 */
28#include "ruby/ruby.h"
29#include "ruby/encoding.h"
30#include "ruby/io.h"
31#include "ruby/util.h"
32#include <fcntl.h>
33#include <process.h>
34#include <sys/stat.h>
35/* #include <sys/wait.h> */
36#include <stdio.h>
37#include <stdlib.h>
38#include <errno.h>
39#include <assert.h>
40#include <ctype.h>
41
42#include <windows.h>
43#include <winbase.h>
44#include <wincon.h>
45#include <share.h>
46#include <shlobj.h>
47#include <mbstring.h>
48#include <shlwapi.h>
49#if defined _MSC_VER
50#include <crtdbg.h>
51#include <rtcapi.h>
52#endif
53#ifdef __MINGW32__
54#include <mswsock.h>
55#endif
56#ifdef HAVE_AFUNIX_H
57# include <afunix.h>
58#endif
59#include "ruby/win32.h"
60#include "ruby/vm.h"
61#include "win32/dir.h"
62#include "win32/file.h"
63#include "id.h"
64#include "internal.h"
65#include "internal/enc.h"
66#include "internal/object.h"
67#include "internal/static_assert.h"
69#include "encindex.h"
70#define isdirsep(x) ((x) == '/' || (x) == '\\')
71
72static int w32_wopen(const WCHAR *file, int oflag, int perm);
73static int w32_stati128(const char *path, struct stati128 *st, UINT cp, BOOL lstat);
74static char *w32_getenv(const char *name, UINT cp);
75
76#undef getenv
77#undef strdup
78/*
79 * Do not remove the macros to substitute functions in dln_find.c.
80 */
81#define DLN_FIND_EXTRA_ARG_DECL ,UINT cp
82#define DLN_FIND_EXTRA_ARG ,cp
83#define rb_w32_stati128(path, st) w32_stati128(path, st, cp, FALSE)
84#define getenv(name) w32_getenv(name, cp) /* Necessarily For dln.c */
85#define DLN_CHAR_NEXT(p) CharNextExA(cp, (p), 0)
86#define dln_find_exe_r rb_w32_udln_find_exe_r
87#define dln_find_file_r rb_w32_udln_find_file_r
88#include "dln.h"
89#include "dln_find.c"
90#undef MAXPATHLEN
91#undef rb_w32_stati128
92#undef dln_find_exe_r
93#undef dln_find_file_r
94#define dln_find_exe_r(fname, path, buf, size) rb_w32_udln_find_exe_r(fname, path, buf, size, cp)
95#define dln_find_file_r(fname, path, buf, size) rb_w32_udln_find_file_r(fname, path, buf, size, cp)
96#undef CharNext /* no default cp version */
97#undef getenv
98
99#ifndef PATH_MAX
100# if defined MAX_PATH
101# define PATH_MAX MAX_PATH
102# elif defined HAVE_SYS_PARAM_H
103# include <sys/param.h>
104# define PATH_MAX MAXPATHLEN
105# endif
106#endif
107#define ENV_MAX 512
108
109#undef stat
110#undef fclose
111#undef close
112#undef setsockopt
113#undef dup2
114
115#define _filbuf _fgetc_nolock
116#define _flsbuf _fputc_nolock
117#define enough_to_get(n) (--(n) >= 0)
118#define enough_to_put(n) (--(n) >= 0)
119
120#ifdef WIN32_DEBUG
121#define Debug(something) something
122#else
123#define Debug(something) /* nothing */
124#endif
125
126#define TO_SOCKET(x) _get_osfhandle(x)
127
128int rb_w32_reparse_symlink_p(const WCHAR *path);
129
130static int has_redirection(const char *, UINT);
131int rb_w32_wait_events(HANDLE *events, int num, DWORD timeout);
132static int rb_w32_open_osfhandle(intptr_t osfhandle, int flags);
133static int wstati128(const WCHAR *path, struct stati128 *st, BOOL lstat);
134VALUE rb_w32_conv_from_wchar(const WCHAR *wstr, rb_encoding *enc);
135int ruby_brace_glob_with_enc(const char *str, int flags, ruby_glob_func *func, VALUE arg, rb_encoding *enc);
136static FARPROC get_proc_address(const char *module, const char *func, HANDLE *mh);
137
138#define RUBY_CRITICAL if (0) {} else /* just remark */
139
140/* errno mapping */
141static const struct {
142 DWORD winerr;
143 int err;
144} errmap[] = {
145 { ERROR_INVALID_FUNCTION, EINVAL },
146 { ERROR_FILE_NOT_FOUND, ENOENT },
147 { ERROR_PATH_NOT_FOUND, ENOENT },
148 { ERROR_TOO_MANY_OPEN_FILES, EMFILE },
149 { ERROR_ACCESS_DENIED, EACCES },
150 { ERROR_INVALID_HANDLE, EBADF },
151 { ERROR_ARENA_TRASHED, ENOMEM },
152 { ERROR_NOT_ENOUGH_MEMORY, ENOMEM },
153 { ERROR_INVALID_BLOCK, ENOMEM },
154 { ERROR_BAD_ENVIRONMENT, E2BIG },
155 { ERROR_BAD_FORMAT, ENOEXEC },
156 { ERROR_INVALID_ACCESS, EINVAL },
157 { ERROR_INVALID_DATA, EINVAL },
158 { ERROR_INVALID_DRIVE, ENOENT },
159 { ERROR_CURRENT_DIRECTORY, EACCES },
160 { ERROR_NOT_SAME_DEVICE, EXDEV },
161 { ERROR_NO_MORE_FILES, ENOENT },
162 { ERROR_WRITE_PROTECT, EROFS },
163 { ERROR_BAD_UNIT, ENODEV },
164 { ERROR_NOT_READY, ENXIO },
165 { ERROR_BAD_COMMAND, EACCES },
166 { ERROR_CRC, EACCES },
167 { ERROR_BAD_LENGTH, EACCES },
168 { ERROR_SEEK, EIO },
169 { ERROR_NOT_DOS_DISK, EACCES },
170 { ERROR_SECTOR_NOT_FOUND, EACCES },
171 { ERROR_OUT_OF_PAPER, EACCES },
172 { ERROR_WRITE_FAULT, EIO },
173 { ERROR_READ_FAULT, EIO },
174 { ERROR_GEN_FAILURE, EACCES },
175 { ERROR_LOCK_VIOLATION, EACCES },
176 { ERROR_SHARING_VIOLATION, EACCES },
177 { ERROR_WRONG_DISK, EACCES },
178 { ERROR_SHARING_BUFFER_EXCEEDED, EACCES },
179 { ERROR_BAD_NETPATH, ENOENT },
180 { ERROR_NETWORK_ACCESS_DENIED, EACCES },
181 { ERROR_BAD_NET_NAME, ENOENT },
182 { ERROR_FILE_EXISTS, EEXIST },
183 { ERROR_CANNOT_MAKE, EACCES },
184 { ERROR_FAIL_I24, EACCES },
185 { ERROR_INVALID_PARAMETER, EINVAL },
186 { ERROR_NO_PROC_SLOTS, EAGAIN },
187 { ERROR_DRIVE_LOCKED, EACCES },
188 { ERROR_BROKEN_PIPE, EPIPE },
189 { ERROR_DISK_FULL, ENOSPC },
190 { ERROR_INVALID_TARGET_HANDLE, EBADF },
191 { ERROR_INVALID_HANDLE, EINVAL },
192 { ERROR_WAIT_NO_CHILDREN, ECHILD },
193 { ERROR_CHILD_NOT_COMPLETE, ECHILD },
194 { ERROR_DIRECT_ACCESS_HANDLE, EBADF },
195 { ERROR_NEGATIVE_SEEK, EINVAL },
196 { ERROR_SEEK_ON_DEVICE, EACCES },
197 { ERROR_DIR_NOT_EMPTY, ENOTEMPTY },
198 { ERROR_DIRECTORY, ENOTDIR },
199 { ERROR_NOT_LOCKED, EACCES },
200 { ERROR_BAD_PATHNAME, ENOENT },
201 { ERROR_MAX_THRDS_REACHED, EAGAIN },
202 { ERROR_LOCK_FAILED, EACCES },
203 { ERROR_ALREADY_EXISTS, EEXIST },
204 { ERROR_INVALID_STARTING_CODESEG, ENOEXEC },
205 { ERROR_INVALID_STACKSEG, ENOEXEC },
206 { ERROR_INVALID_MODULETYPE, ENOEXEC },
207 { ERROR_INVALID_EXE_SIGNATURE, ENOEXEC },
208 { ERROR_EXE_MARKED_INVALID, ENOEXEC },
209 { ERROR_BAD_EXE_FORMAT, ENOEXEC },
210 { ERROR_ITERATED_DATA_EXCEEDS_64k,ENOEXEC },
211 { ERROR_INVALID_MINALLOCSIZE, ENOEXEC },
212 { ERROR_DYNLINK_FROM_INVALID_RING,ENOEXEC },
213 { ERROR_IOPL_NOT_ENABLED, ENOEXEC },
214 { ERROR_INVALID_SEGDPL, ENOEXEC },
215 { ERROR_AUTODATASEG_EXCEEDS_64k, ENOEXEC },
216 { ERROR_RING2SEG_MUST_BE_MOVABLE, ENOEXEC },
217 { ERROR_RELOC_CHAIN_XEEDS_SEGLIM, ENOEXEC },
218 { ERROR_INFLOOP_IN_RELOC_CHAIN, ENOEXEC },
219 { ERROR_FILENAME_EXCED_RANGE, ENOENT },
220 { ERROR_NESTING_NOT_ALLOWED, EAGAIN },
221#ifndef ERROR_PIPE_LOCAL
222#define ERROR_PIPE_LOCAL 229L
223#endif
224 { ERROR_PIPE_LOCAL, EPIPE },
225 { ERROR_BAD_PIPE, EPIPE },
226 { ERROR_PIPE_BUSY, EAGAIN },
227 { ERROR_NO_DATA, EPIPE },
228 { ERROR_PIPE_NOT_CONNECTED, EPIPE },
229 { ERROR_OPERATION_ABORTED, EINTR },
230 { ERROR_NOT_ENOUGH_QUOTA, ENOMEM },
231 { ERROR_MOD_NOT_FOUND, ENOENT },
232 { ERROR_PRIVILEGE_NOT_HELD, EACCES, },
233 { ERROR_CANT_RESOLVE_FILENAME, ELOOP, },
234 { WSAEINTR, EINTR },
235 { WSAEBADF, EBADF },
236 { WSAEACCES, EACCES },
237 { WSAEFAULT, EFAULT },
238 { WSAEINVAL, EINVAL },
239 { WSAEMFILE, EMFILE },
240 { WSAEWOULDBLOCK, EWOULDBLOCK },
241 { WSAEINPROGRESS, EINPROGRESS },
242 { WSAEALREADY, EALREADY },
243 { WSAENOTSOCK, ENOTSOCK },
244 { WSAEDESTADDRREQ, EDESTADDRREQ },
245 { WSAEMSGSIZE, EMSGSIZE },
246 { WSAEPROTOTYPE, EPROTOTYPE },
247 { WSAENOPROTOOPT, ENOPROTOOPT },
248 { WSAEPROTONOSUPPORT, EPROTONOSUPPORT },
249 { WSAESOCKTNOSUPPORT, ESOCKTNOSUPPORT },
250 { WSAEOPNOTSUPP, EOPNOTSUPP },
251 { WSAEPFNOSUPPORT, EPFNOSUPPORT },
252 { WSAEAFNOSUPPORT, EAFNOSUPPORT },
253 { WSAEADDRINUSE, EADDRINUSE },
254 { WSAEADDRNOTAVAIL, EADDRNOTAVAIL },
255 { WSAENETDOWN, ENETDOWN },
256 { WSAENETUNREACH, ENETUNREACH },
257 { WSAENETRESET, ENETRESET },
258 { WSAECONNABORTED, ECONNABORTED },
259 { WSAECONNRESET, ECONNRESET },
260 { WSAENOBUFS, ENOBUFS },
261 { WSAEISCONN, EISCONN },
262 { WSAENOTCONN, ENOTCONN },
263 { WSAESHUTDOWN, ESHUTDOWN },
264 { WSAETOOMANYREFS, ETOOMANYREFS },
265 { WSAETIMEDOUT, ETIMEDOUT },
266 { WSAECONNREFUSED, ECONNREFUSED },
267 { WSAELOOP, ELOOP },
268 { WSAENAMETOOLONG, ENAMETOOLONG },
269 { WSAEHOSTDOWN, EHOSTDOWN },
270 { WSAEHOSTUNREACH, EHOSTUNREACH },
271 { WSAEPROCLIM, EPROCLIM },
272 { WSAENOTEMPTY, ENOTEMPTY },
273 { WSAEUSERS, EUSERS },
274 { WSAEDQUOT, EDQUOT },
275 { WSAESTALE, ESTALE },
276 { WSAEREMOTE, EREMOTE },
277};
278
279/* License: Ruby's */
280int
281rb_w32_map_errno(DWORD winerr)
282{
283 int i;
284
285 if (winerr == 0) {
286 return 0;
287 }
288
289 for (i = 0; i < (int)(sizeof(errmap) / sizeof(*errmap)); i++) {
290 if (errmap[i].winerr == winerr) {
291 return errmap[i].err;
292 }
293 }
294
295 if (winerr >= WSABASEERR) {
296 return winerr;
297 }
298 return EINVAL;
299}
300
301#define map_errno rb_w32_map_errno
302
303static const char *NTLoginName;
304
305static OSVERSIONINFO osver;
306
307/* License: Artistic or GPL */
308static void
309get_version(void)
310{
311 memset(&osver, 0, sizeof(OSVERSIONINFO));
312 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
313 GetVersionEx(&osver);
314}
315
316/* License: Artistic or GPL */
317DWORD
318rb_w32_osver(void)
319{
320 return osver.dwMajorVersion;
321}
322
323/* simulate flock by locking a range on the file */
324
325/* License: Artistic or GPL */
326#define LK_ERR(f,i) \
327 do { \
328 if (f) \
329 i = 0; \
330 else { \
331 DWORD err = GetLastError(); \
332 if (err == ERROR_LOCK_VIOLATION || err == ERROR_IO_PENDING) \
333 errno = EWOULDBLOCK; \
334 else if (err == ERROR_NOT_LOCKED) \
335 i = 0; \
336 else \
337 errno = map_errno(err); \
338 } \
339 } while (0)
340#define LK_LEN ULONG_MAX
341
342/* License: Artistic or GPL */
343static uintptr_t
344flock_winnt(uintptr_t self, int argc, uintptr_t* argv)
345{
346 OVERLAPPED o;
347 int i = -1;
348 const HANDLE fh = (HANDLE)self;
349 const int oper = argc;
350
351 memset(&o, 0, sizeof(o));
352
353 switch (oper) {
354 case LOCK_SH: /* shared lock */
355 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, LK_LEN, &o), i);
356 break;
357 case LOCK_EX: /* exclusive lock */
358 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, LK_LEN, &o), i);
359 break;
360 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
361 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, LK_LEN, &o), i);
362 break;
363 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
364 LK_ERR(LockFileEx(fh,
365 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
366 0, LK_LEN, LK_LEN, &o), i);
367 break;
368 case LOCK_UN: /* unlock lock */
369 case LOCK_UN|LOCK_NB: /* unlock is always non-blocking, I hope */
370 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, LK_LEN, &o), i);
371 break;
372 default: /* unknown */
373 errno = EINVAL;
374 break;
375 }
376 return i;
377}
378
379#undef LK_ERR
380
381/* License: Artistic or GPL */
382int
383flock(int fd, int oper)
384{
385 const asynchronous_func_t locker = flock_winnt;
386
387 return rb_w32_asynchronize(locker,
388 (VALUE)_get_osfhandle(fd), oper, NULL,
389 (DWORD)-1);
390}
391
392/* License: Ruby's */
393static inline WCHAR *
394translate_wchar(WCHAR *p, int from, int to)
395{
396 for (; *p; p++) {
397 if (*p == from)
398 *p = to;
399 }
400 return p;
401}
402
403/* License: Ruby's */
404static inline char *
405translate_char(char *p, int from, int to, UINT cp)
406{
407 while (*p) {
408 if ((unsigned char)*p == from)
409 *p = to;
410 p = CharNextExA(cp, p, 0);
411 }
412 return p;
413}
414
415#ifndef CSIDL_LOCAL_APPDATA
416#define CSIDL_LOCAL_APPDATA 28
417#endif
418#ifndef CSIDL_COMMON_APPDATA
419#define CSIDL_COMMON_APPDATA 35
420#endif
421#ifndef CSIDL_WINDOWS
422#define CSIDL_WINDOWS 36
423#endif
424#ifndef CSIDL_SYSTEM
425#define CSIDL_SYSTEM 37
426#endif
427#ifndef CSIDL_PROFILE
428#define CSIDL_PROFILE 40
429#endif
430
431/* License: Ruby's */
432static BOOL
433get_special_folder(int n, WCHAR *buf, size_t len)
434{
435 LPITEMIDLIST pidl;
436 LPMALLOC alloc;
437 BOOL f = FALSE;
438
439 if (SHGetSpecialFolderLocation(NULL, n, &pidl) == 0) {
440 f = SHGetPathFromIDListEx(pidl, buf, len, 0);
441 SHGetMalloc(&alloc);
442 alloc->lpVtbl->Free(alloc, pidl);
443 alloc->lpVtbl->Release(alloc);
444 }
445 return f;
446}
447
448/* License: Ruby's */
449static void
450regulate_path(WCHAR *path)
451{
452 WCHAR *p = translate_wchar(path, L'\\', L'/');
453 if (p - path == 2 && path[1] == L':') {
454 *p++ = L'/';
455 *p = L'\0';
456 }
457}
458
459/* License: Ruby's */
460static FARPROC
461get_proc_address(const char *module, const char *func, HANDLE *mh)
462{
463 HANDLE h;
464 FARPROC ptr;
465
466 if (mh)
467 h = LoadLibrary(module);
468 else
469 h = GetModuleHandle(module);
470 if (!h)
471 return NULL;
472
473 ptr = GetProcAddress(h, func);
474 if (mh) {
475 if (ptr)
476 *mh = h;
477 else
478 FreeLibrary(h);
479 }
480 return ptr;
481}
482
483/* License: Ruby's */
484VALUE
485rb_w32_special_folder(int type)
486{
487 WCHAR path[PATH_MAX];
488
489 if (!get_special_folder(type, path, numberof(path))) return Qnil;
490 regulate_path(path);
491 return rb_w32_conv_from_wchar(path, rb_filesystem_encoding());
492}
493
494/* License: Ruby's */
495UINT
496rb_w32_system_tmpdir(WCHAR *path, UINT len)
497{
498 static const WCHAR temp[] = L"temp";
499 WCHAR *p;
500
501 if (!get_special_folder(CSIDL_LOCAL_APPDATA, path, len)) {
502 if (GetSystemWindowsDirectoryW(path, len)) return 0;
503 }
504 p = translate_wchar(path, L'\\', L'/');
505 if (p == path || *(p - 1) != L'/') *p++ = L'/';
506 if ((UINT)(p - path + numberof(temp)) >= len) return 0;
507 memcpy(p, temp, sizeof(temp));
508 return (UINT)(p - path + numberof(temp) - 1);
509}
510
511/*
512 Return user's home directory using environment variables combinations.
513 Memory allocated by this function should be manually freed
514 afterwards with free.
515
516 Try:
517 HOME, USERPROFILE, HOMEDRIVE + HOMEPATH environment variables
518 Special Folders - Profile and Personal
519*/
520WCHAR *
521rb_w32_home_dir(void)
522{
523 WCHAR *buffer = NULL;
524 size_t len = 0, len2;
525 /* can't use xmalloc here, since it's called too early from init_env() */
526#define alloc_buffer(len) \
527 if ((buffer = malloc(sizeof(WCHAR) * len)) != NULL) ; \
528 else return NULL
529
530 if ((len = GetEnvironmentVariableW(L"HOME", NULL, 0)) != 0) {
531 alloc_buffer(len);
532 GetEnvironmentVariableW(L"HOME", buffer, len);
533 }
534 else if ((len = GetEnvironmentVariableW(L"USERPROFILE", NULL, 0)) != 0) {
535 alloc_buffer(len);
536 GetEnvironmentVariableW(L"USERPROFILE", buffer, len);
537 }
538 else if ((len = GetEnvironmentVariableW(L"HOMEDRIVE", NULL, 0)) != 0 &&
539 (len2 = GetEnvironmentVariableW(L"HOMEPATH", NULL, 0)) != 0) {
540 len2 += len;
541 alloc_buffer(len2);
542 len = GetEnvironmentVariableW(L"HOMEDRIVE", buffer, len);
543 GetEnvironmentVariableW(L"HOMEPATH", buffer + len, len2 - len);
544 }
545 else {
546 alloc_buffer(MAX_PATH);
547 if (!get_special_folder(CSIDL_PROFILE, buffer, MAX_PATH) &&
548 !get_special_folder(CSIDL_PERSONAL, buffer, MAX_PATH)) {
549 free(buffer);
550 return NULL;
551 }
552 buffer = realloc(buffer, sizeof(WCHAR) * (lstrlenW(buffer) + 1));
553 }
554#undef alloc_buffer
555
556 /* sanitize backslashes with forwardslashes */
557 regulate_path(buffer);
558
559 return buffer;
560}
561
562/* License: Ruby's */
563static void
564init_env(void)
565{
566 WCHAR env[ENV_MAX];
567
568 if (!GetEnvironmentVariableW(L"HOME", env, numberof(env))) {
569 WCHAR *whome = rb_w32_home_dir();
570 if (whome) {
571 _wputenv_s(L"HOME", whome);
572 free(whome);
573 }
574 }
575
576 if (!GetEnvironmentVariableW(L"USER", env, numberof(env))) {
577 DWORD len;
578 if (!GetEnvironmentVariableW(L"USERNAME", env, numberof(env)) &&
579 !GetUserNameW(env, (len = numberof(env), &len))) {
580 NTLoginName = "<Unknown>";
581 }
582 else {
583 _wputenv_s(L"USER", env);
584 NTLoginName = rb_w32_wstr_to_mbstr(CP_UTF8, env, -1, NULL);
585 }
586 }
587 else {
588 NTLoginName = rb_w32_wstr_to_mbstr(CP_UTF8, env, -1, NULL);
589 }
590
591 if (!GetEnvironmentVariableW(L"TMPDIR", env, numberof(env)) &&
592 !GetEnvironmentVariableW(L"TMP", env, numberof(env)) &&
593 !GetEnvironmentVariableW(L"TEMP", env, numberof(env)) &&
594 rb_w32_system_tmpdir(env, numberof(env))) {
595 _wputenv_s(L"TMPDIR", env);
596 }
597}
598
599static void init_stdhandle(void);
600
601/* License: Ruby's */
602static void
603invalid_parameter(const wchar_t *expr, const wchar_t *func, const wchar_t *file, unsigned int line, uintptr_t dummy)
604{
605 // nothing to do
606}
607
608int ruby_w32_rtc_error;
609int ruby_w32_wer;
610
611#ifndef __MINGW32__
612/* License: Ruby's */
614RBIMPL_ATTR_FORMAT(RBIMPL_PRINTF_FORMAT, 5, 6)
615static int __cdecl
616rtc_error_handler(int e, const char *src, int line, const char *exe, const char *fmt, ...)
617{
618 va_list ap;
619 VALUE str;
620
621 if (!ruby_w32_rtc_error) return 0;
622 str = rb_sprintf("%s:%d: ", src, line);
623 va_start(ap, fmt);
624 rb_str_vcatf(str, fmt, ap);
625 va_end(ap);
626 rb_str_cat(str, "\n", 1);
627 rb_write_error2(RSTRING_PTR(str), RSTRING_LEN(str));
628 return 0;
629}
630#endif
631
632static CRITICAL_SECTION select_mutex;
633
634static CRITICAL_SECTION socklist_mutex;
635static st_table *socklist = NULL;
636
637static CRITICAL_SECTION conlist_mutex;
638static st_table *conlist = NULL;
639#define conlist_disabled ((st_table *)-1)
640
641#define thread_exclusive(obj) \
642 for (bool exclusive_for_##obj = (EnterCriticalSection(&obj##_mutex), true); \
643 exclusive_for_##obj; \
644 exclusive_for_##obj = (LeaveCriticalSection(&obj##_mutex), false))
645
646/* The string w32_getenv returned last in each thread, or in each Win32
647 * fiber, valid until the next call in the same thread or fiber. */
648static DWORD uenvarea_key;
649
650/* License: Ruby's */
651static void WINAPI
652free_uenvarea(void *uenvarea)
653{
654 free(uenvarea);
655}
656
657/* License: Ruby's */
658struct constat {
659 struct {
660 int state, seq[16], reverse;
661 WORD attr;
662 COORD saved;
663 } vt100;
664};
665enum {constat_init = -2, constat_esc = -1, constat_seq = 0};
666
667/* License: Ruby's */
668static int
669free_conlist(st_data_t key, st_data_t val, st_data_t arg)
670{
671 xfree((struct constat *)val);
672 return ST_DELETE;
673}
674
675/* License: Ruby's */
676static void
677constat_delete(HANDLE h)
678{
679 thread_exclusive(conlist) {
680 if (conlist && conlist != conlist_disabled) {
681 st_data_t key = (st_data_t)h, val;
682 st_delete(conlist, &key, &val);
683 xfree((struct constat *)val);
684 }
685 }
686}
687
688/* License: Ruby's */
689static void
690exit_handler(void)
691{
692 WSACleanup();
693 DeleteCriticalSection(&select_mutex);
694 DeleteCriticalSection(&socklist_mutex);
695 DeleteCriticalSection(&conlist_mutex);
696 FlsFree(uenvarea_key);
697}
698
699/* License: Ruby's */
700static void
701vm_exit_handler(ruby_vm_t *vm)
702{
703 EnterCriticalSection(&socklist_mutex);
704 if (socklist) {
705 st_free_table(socklist);
706 socklist = NULL;
707 }
708 LeaveCriticalSection(&socklist_mutex);
709
710 EnterCriticalSection(&conlist_mutex);
711 if (conlist && conlist != conlist_disabled) {
712 st_foreach(conlist, free_conlist, 0);
713 st_free_table(conlist);
714 conlist = NULL;
715 }
716 LeaveCriticalSection(&conlist_mutex);
717}
718
719#define ATOMIC_LONG_CAS(var, oldval, newval) InterlockedCompareExchange(&(var), (newval), (oldval))
720
721/* License: Ruby's */
722static void
723install_vm_exit_handler(void)
724{
725 static LONG installed = 0;
726 LONG i;
727
728 while ((i = ATOMIC_LONG_CAS(installed, 0, -1)) != 1) {
729 if (i != 0) {
730 Sleep(1);
731 continue;
732 }
733 ruby_vm_at_exit(vm_exit_handler);
734 ATOMIC_LONG_CAS(installed, -1, 1);
735 break;
736 }
737}
738
739/* License: Artistic or GPL */
740static void
741StartSockets(void)
742{
743 WORD version;
744 WSADATA retdata;
745
746 //
747 // initialize the winsock interface and insure that it's
748 // cleaned up at exit.
749 //
750 version = MAKEWORD(2, 0);
751 if (WSAStartup(version, &retdata))
752 rb_fatal("Unable to locate winsock library!");
753 if (LOBYTE(retdata.wVersion) != 2)
754 rb_fatal("could not find version 2 of winsock dll");
755
756 InitializeCriticalSection(&select_mutex);
757 InitializeCriticalSection(&socklist_mutex);
758 InitializeCriticalSection(&conlist_mutex);
759
760 atexit(exit_handler);
761}
762
763#define MAKE_SOCKDATA(af, fl) ((int)((((int)af)<<4)|((fl)&0xFFFF)))
764#define GET_FAMILY(v) ((int)(((v)>>4)&0xFFFF))
765#define GET_FLAGS(v) ((int)((v)&0xFFFF))
766
767/* License: Ruby's */
768static inline int
769socklist_insert(SOCKET sock, int flag)
770{
771 int ret;
772
773 thread_exclusive(socklist) {
774 if (!socklist) {
775 socklist = st_init_numtable();
776 install_vm_exit_handler();
777 }
778 ret = st_insert(socklist, (st_data_t)sock, (st_data_t)flag);
779 }
780
781 return ret;
782}
783
784/* License: Ruby's */
785static inline int
786socklist_lookup(SOCKET sock, int *flagp)
787{
788 st_data_t data;
789 int ret = 0;
790
791 thread_exclusive(socklist) {
792 if (!socklist) continue;
793 ret = st_lookup(socklist, (st_data_t)sock, &data);
794 if (ret && flagp)
795 *flagp = (int)data;
796 }
797
798 return ret;
799}
800
801/* License: Ruby's */
802static inline int
803socklist_delete(SOCKET *sockp, int *flagp)
804{
805 st_data_t key;
806 st_data_t data;
807 int ret = 0;
808
809 thread_exclusive(socklist) {
810 if (!socklist) continue;
811 key = (st_data_t)*sockp;
812 if (flagp)
813 data = (st_data_t)*flagp;
814 ret = st_delete(socklist, &key, &data);
815 if (ret) {
816 *sockp = (SOCKET)key;
817 if (flagp)
818 *flagp = (int)data;
819 }
820 }
821
822 return ret;
823}
824
825# ifdef __MINGW32__
826# define _CrtSetReportMode(type,mode) ((void)0)
827# define _RTC_SetErrorFunc(func) ((void)0)
828# endif
829static void set_pioinfo_extra(void);
830static int w32_cmdvector(const WCHAR *, char ***, UINT, rb_encoding *);
831//
832// Initialization stuff
833//
834
835/* License: Ruby's */
836/* Enable long path names for this process, whatever the registry value
837 * HKLM\SYSTEM\CurrentControlSet\Control\FileSystem\LongPathsEnabled is. The
838 * loader sets the same PEB bit for longPathAware in the manifest, but only
839 * when that registry value is set, so the manifest alone is not enough on a
840 * stock machine. Undocumented, and taken from initLongPathSupport in Go's
841 * runtime <https://go.dev/src/runtime/os_windows.go>, whose maintainers have
842 * proposed to drop it <https://github.com/golang/go/issues/66560>.
843 *
844 * Called from ruby_setup, not from rb_w32_sysinit, which a program that
845 * embeds libruby is not expected to call. */
846void
847rb_w32_init_long_paths(void)
848{
849 /* PEB.BitField, and the IsLongPathAwareProcess bit in it */
850 enum {peb_bit_field_offset = 3, is_long_path_aware_process = 0x80};
851 typedef long (WINAPI version_func)(OSVERSIONINFOW *);
852 typedef void *(WINAPI peb_func)(void);
853 version_func *pRtlGetVersion;
854 peb_func *pRtlGetCurrentPeb;
855 OSVERSIONINFOW osvi;
856 BYTE *bit_field;
857
858 pRtlGetVersion = (version_func *)get_proc_address("ntdll.dll", "RtlGetVersion", NULL);
859 if (!pRtlGetVersion) return;
860 memset(&osvi, 0, sizeof(osvi));
861 osvi.dwOSVersionInfoSize = sizeof(osvi);
862 if (pRtlGetVersion(&osvi)) return;
863
864 /* the PEB bit is honored since Windows 10 1703 (10.0.15063) */
865 if (osvi.dwMajorVersion < 10) return;
866 if (osvi.dwMajorVersion == 10 && osvi.dwMinorVersion == 0 &&
867 osvi.dwBuildNumber < 15063) return;
868
869 pRtlGetCurrentPeb = (peb_func *)get_proc_address("ntdll.dll", "RtlGetCurrentPeb", NULL);
870 if (!pRtlGetCurrentPeb) return;
871 bit_field = (BYTE *)pRtlGetCurrentPeb() + peb_bit_field_offset;
872 *bit_field |= is_long_path_aware_process;
873}
874
875/* License: Ruby's */
876void
877rb_w32_sysinit(int *argc, char ***argv)
878{
879 _CrtSetReportMode(_CRT_ASSERT, 0);
880 _set_invalid_parameter_handler(invalid_parameter);
881 _RTC_SetErrorFunc(rtc_error_handler);
882 set_pioinfo_extra();
883 /* RUBY_DEBUG=wer leaves unhandled exceptions to Windows Error Reporting,
884 * so that it can write crash dumps. */
885 SetErrorMode(SEM_FAILCRITICALERRORS|(ruby_w32_wer ? 0 : SEM_NOGPFAULTERRORBOX));
886
887 get_version();
888
889 //
890 // subvert cmd.exe's feeble attempt at command line parsing
891 //
892 *argc = w32_cmdvector(GetCommandLineW(), argv, CP_UTF8, &OnigEncodingUTF_8);
893
894 //
895 // Now set up the correct time stuff
896 //
897
898 tzset();
899
900 if ((uenvarea_key = FlsAlloc(free_uenvarea)) == FLS_OUT_OF_INDEXES)
901 rb_bug("FlsAlloc() for uenvarea_key fails");
902 init_env();
903
904 init_stdhandle();
905
906 // Initialize Winsock
907 StartSockets();
908}
909
910char *
911getlogin(void)
912{
913 return (char *)NTLoginName;
914}
915
916#define MAXCHILDNUM 256 /* max num of child processes */
917
918/* License: Ruby's */
919static struct ChildRecord {
920 HANDLE hProcess; /* process handle */
921 rb_pid_t pid; /* process id */
922} ChildRecord[MAXCHILDNUM];
923
924/* License: Ruby's */
925#define FOREACH_CHILD(v) do { \
926 struct ChildRecord* v; \
927 for (v = ChildRecord; v < ChildRecord + sizeof(ChildRecord) / sizeof(ChildRecord[0]); ++v)
928#define END_FOREACH_CHILD } while (0)
929
930/* License: Ruby's */
931static struct ChildRecord *
932FindChildSlot(rb_pid_t pid)
933{
934
935 FOREACH_CHILD(child) {
936 if (child->pid == pid) {
937 return child;
938 }
939 } END_FOREACH_CHILD;
940 return NULL;
941}
942
943/* License: Ruby's */
944static struct ChildRecord *
945FindChildSlotByHandle(HANDLE h)
946{
947
948 FOREACH_CHILD(child) {
949 if (child->hProcess == h) {
950 return child;
951 }
952 } END_FOREACH_CHILD;
953 return NULL;
954}
955
956/* License: Ruby's */
957static void
958CloseChildHandle(struct ChildRecord *child)
959{
960 HANDLE h = child->hProcess;
961 child->hProcess = NULL;
962 child->pid = 0;
963 CloseHandle(h);
964}
965
966/* License: Ruby's */
967static struct ChildRecord *
968FindFreeChildSlot(void)
969{
970 FOREACH_CHILD(child) {
971 if (!child->pid) {
972 child->pid = -1; /* lock the slot */
973 child->hProcess = NULL;
974 return child;
975 }
976 } END_FOREACH_CHILD;
977 return NULL;
978}
979
980
981#define InternalCmdsMax 8
982static const char szInternalCmds[][InternalCmdsMax+1] = {
983 "assoc",
984 "break",
985 "call",
986 "cd",
987 "chdir",
988 "cls",
989 "color",
990 "copy",
991 "date",
992 "del",
993 "dir",
994 "echo",
995 "endlocal",
996 "erase",
997 "exit",
998 "for",
999 "ftype",
1000 "goto",
1001 "if",
1002 "md",
1003 "mkdir",
1004 "mklink",
1005 "move",
1006 "path",
1007 "pause",
1008 "popd",
1009 "prompt",
1010 "pushd",
1011 "rd",
1012 "rem",
1013 "ren",
1014 "rename",
1015 "rmdir",
1016 "set",
1017 "setlocal",
1018 "shift",
1019 "start",
1020 "time",
1021 "title",
1022 "type",
1023 "ver",
1024 "verify",
1025 "vol",
1026};
1027
1028/* License: Ruby's */
1029static int
1030internal_match(const void *key, const void *elem)
1031{
1032 return strncmp(key, elem, InternalCmdsMax);
1033}
1034
1035static int internal_cmd_match(const char *cmdname);
1036
1037/* License: Ruby's */
1038static int
1039is_internal_cmd(const char *cmd)
1040{
1041 char cmdname[InternalCmdsMax+1], *b = cmdname, c;
1042
1043 do {
1044 if (!(c = *cmd++)) return 0;
1045 } while (isspace(c));
1046 if (c == '@')
1047 return 1;
1048 while (isalpha(c)) {
1049 *b++ = tolower(c);
1050 if (b == cmdname + sizeof(cmdname)) return 0;
1051 c = *cmd++;
1052 }
1053 if (c == '.') c = *cmd;
1054 switch (c) {
1055 case '<': case '>': case '|':
1056 return 1;
1057 case '\0': case ' ': case '\t': case '\n':
1058 break;
1059 default:
1060 return 0;
1061 }
1062 *b = 0;
1063 return internal_cmd_match(cmdname);
1064}
1065
1066/* License: Ruby's */
1067static int
1068internal_cmd_match(const char *cmdname)
1069{
1070 char *nm;
1071
1072 nm = bsearch(cmdname, szInternalCmds,
1073 numberof(szInternalCmds),
1074 sizeof(*szInternalCmds),
1075 internal_match);
1076
1077 return !!nm;
1078}
1079
1080/* License: Ruby's */
1081SOCKET
1082rb_w32_get_osfhandle(int fh)
1083{
1084 return _get_osfhandle(fh);
1085}
1086
1087/* License: Ruby's */
1088static int
1089join_argv(char *cmd, char *const *argv, BOOL escape, UINT cp, int backslash, BOOL quote_bs)
1090{
1091 const char *p, *s;
1092 char *q, *const *t;
1093 int len, n, bs, quote;
1094
1095 for (t = argv, q = cmd, len = 0; (p = *t) != 0; t++) {
1096 quote = 0;
1097 s = p;
1098 if (!*p || strpbrk(p, " \t\"'")) {
1099 quote = 1;
1100 len++;
1101 if (q) *q++ = '"';
1102 }
1103 for (bs = 0; *p; ++p) {
1104 switch (*p) {
1105 case '\\':
1106 ++bs;
1107 break;
1108 case '"':
1109 len += n = p - s;
1110 if (q) {
1111 memcpy(q, s, n);
1112 q += n;
1113 }
1114 s = p;
1115 len += ++bs;
1116 if (q) {
1117 memset(q, '\\', bs);
1118 q += bs;
1119 }
1120 bs = 0;
1121 break;
1122 case '<': case '>': case '|': case '^':
1123 if (escape && !quote) {
1124 len += (n = p - s) + 1;
1125 if (q) {
1126 memcpy(q, s, n);
1127 q += n;
1128 *q++ = '^';
1129 }
1130 s = p;
1131 break;
1132 }
1133 default:
1134 bs = 0;
1135 p = CharNextExA(cp, p, 0) - 1;
1136 break;
1137 }
1138 }
1139 len += (n = p - s) + 1;
1140 if (quote) len += (quote_bs ? bs : 0) + 1;
1141 if (q) {
1142 memcpy(q, s, n);
1143 if (backslash > 0) {
1144 --backslash;
1145 q[n] = 0;
1146 translate_char(q, '/', '\\', cp);
1147 }
1148 q += n;
1149 if (quote) {
1150 // See [Bug #22199]
1151 if (quote_bs && bs) {
1152 memset(q, '\\', bs);
1153 q += bs;
1154 }
1155 *q++ = '"';
1156 }
1157 *q++ = ' ';
1158 }
1159 }
1160 if (q > cmd) --len;
1161 if (q) {
1162 if (q > cmd) --q;
1163 *q = '\0';
1164 }
1165 return len;
1166}
1167
1168/* License: Ruby's */
1169#define STRNDUPV(ptr, v, src, len) \
1170 (((char *)memcpy(((ptr) = ALLOCV((v), (len) + 1)), (src), (len)))[len] = 0)
1171
1172/* License: Ruby's */
1173static int
1174check_spawn_mode(int mode)
1175{
1176 switch (mode) {
1177 case P_NOWAIT:
1178 case P_OVERLAY:
1179 return 0;
1180 default:
1181 errno = EINVAL;
1182 return -1;
1183 }
1184}
1185
1186/* License: Ruby's */
1187static rb_pid_t
1188child_result(struct ChildRecord *child, int mode)
1189{
1190 DWORD exitcode;
1191
1192 if (!child) {
1193 return -1;
1194 }
1195
1196 if (mode == P_OVERLAY) {
1197 WaitForSingleObject(child->hProcess, INFINITE);
1198 GetExitCodeProcess(child->hProcess, &exitcode);
1199 CloseChildHandle(child);
1200 _exit(exitcode);
1201 }
1202 return child->pid;
1203}
1204
1205/* License: Ruby's */
1206static int
1207CreateChild(struct ChildRecord *child, const WCHAR *cmd, const WCHAR *prog, HANDLE hInput, HANDLE hOutput, HANDLE hError, DWORD dwCreationFlags)
1208{
1209 BOOL fRet;
1210 STARTUPINFOW aStartupInfo;
1211 PROCESS_INFORMATION aProcessInformation;
1212 SECURITY_ATTRIBUTES sa;
1213
1214 if (!cmd && !prog) {
1215 errno = EFAULT;
1216 return FALSE;
1217 }
1218
1219 if (!child) {
1220 errno = EAGAIN;
1221 return FALSE;
1222 }
1223
1224 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
1225 sa.lpSecurityDescriptor = NULL;
1226 sa.bInheritHandle = TRUE;
1227
1228 memset(&aStartupInfo, 0, sizeof(aStartupInfo));
1229 memset(&aProcessInformation, 0, sizeof(aProcessInformation));
1230 aStartupInfo.cb = sizeof(aStartupInfo);
1231 aStartupInfo.dwFlags = STARTF_USESTDHANDLES;
1232 if (hInput) {
1233 aStartupInfo.hStdInput = hInput;
1234 }
1235 else {
1236 aStartupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
1237 }
1238 if (hOutput) {
1239 aStartupInfo.hStdOutput = hOutput;
1240 }
1241 else {
1242 aStartupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
1243 }
1244 if (hError) {
1245 aStartupInfo.hStdError = hError;
1246 }
1247 else {
1248 aStartupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
1249 }
1250
1251 dwCreationFlags |= NORMAL_PRIORITY_CLASS;
1252
1253 if (lstrlenW(cmd) > 32767) {
1254 child->pid = 0; /* release the slot */
1255 errno = E2BIG;
1256 return FALSE;
1257 }
1258
1259 RUBY_CRITICAL {
1260 fRet = CreateProcessW(prog, (WCHAR *)cmd, &sa, &sa,
1261 sa.bInheritHandle, dwCreationFlags, NULL, NULL,
1262 &aStartupInfo, &aProcessInformation);
1263 errno = map_errno(GetLastError());
1264 }
1265
1266 if (!fRet) {
1267 child->pid = 0; /* release the slot */
1268 return FALSE;
1269 }
1270
1271 CloseHandle(aProcessInformation.hThread);
1272
1273 child->hProcess = aProcessInformation.hProcess;
1274 child->pid = (rb_pid_t)aProcessInformation.dwProcessId;
1275
1276 return TRUE;
1277}
1278
1279/* License: Ruby's */
1280static int
1281is_batch(const char *cmd)
1282{
1283 int len = strlen(cmd);
1284 if (len <= 4) return 0;
1285 cmd += len - 4;
1286 if (*cmd++ != '.') return 0;
1287 if (strcasecmp(cmd, "bat") == 0) return 1;
1288 if (strcasecmp(cmd, "cmd") == 0) return 1;
1289 return 0;
1290}
1291
1292#define filecp rb_w32_filecp
1293#define mbstr_to_wstr rb_w32_mbstr_to_wstr
1294#define wstr_to_mbstr rb_w32_wstr_to_mbstr
1295#define acp_to_wstr(str, plen) mbstr_to_wstr(CP_ACP, str, -1, plen)
1296#define wstr_to_acp(str, plen) wstr_to_mbstr(CP_ACP, str, -1, plen)
1297#define filecp_to_wstr(str, plen) mbstr_to_wstr(filecp(), str, -1, plen)
1298#define wstr_to_filecp(str, plen) wstr_to_mbstr(filecp(), str, -1, plen)
1299#define utf8_to_wstr(str, plen) mbstr_to_wstr(CP_UTF8, str, -1, plen)
1300#define wstr_to_utf8(str, plen) wstr_to_mbstr(CP_UTF8, str, -1, plen)
1301
1302/* License: Artistic or GPL */
1303static rb_pid_t
1304w32_spawn(int mode, const char *cmd, const char *prog, UINT cp)
1305{
1306 char fbuf[PATH_MAX];
1307 char *p = NULL;
1308 const char *shell = NULL;
1309 WCHAR *wcmd = NULL, *wshell = NULL;
1310 int e = 0;
1311 rb_pid_t ret = -1;
1312 VALUE v = 0;
1313 VALUE v2 = 0;
1314 int sep = 0;
1315 char *cmd_sep = NULL;
1316
1317 if (check_spawn_mode(mode)) return -1;
1318
1319 if (prog) {
1320 if (!(p = dln_find_exe_r(prog, NULL, fbuf, sizeof(fbuf)))) {
1321 shell = prog;
1322 }
1323 else {
1324 shell = p;
1325 translate_char(p, '/', '\\', cp);
1326 }
1327 }
1328 else {
1329 int redir = -1;
1330 while (ISSPACE(*cmd)) cmd++;
1331 if ((shell = w32_getenv("RUBYSHELL", cp)) && (redir = has_redirection(cmd, cp))) {
1332 size_t shell_len = strlen(shell);
1333 size_t cmd_len = strlen(cmd) + sizeof(" -c ") + 2;
1334 char *tmp = ALLOCV(v, shell_len + cmd_len);
1335 memcpy(tmp, shell, shell_len + 1);
1336 translate_char(tmp, '/', '\\', cp);
1337 snprintf(tmp + shell_len, cmd_len, " -c \"%s\"", cmd);
1338 cmd = tmp;
1339 }
1340 else if ((shell = w32_getenv("COMSPEC", cp)) &&
1341 ((redir < 0 ? has_redirection(cmd, cp) : redir) || is_internal_cmd(cmd))) {
1342 size_t cmd_len = strlen(shell) + strlen(cmd) + sizeof(" /c \"\"");
1343 char *tmp = ALLOCV(v, cmd_len);
1344 snprintf(tmp, cmd_len, "%s /c \"%s\"", shell, cmd);
1345 cmd = tmp;
1346 }
1347 else {
1348 int len = 0, quote = (*cmd == '"') ? '"' : (*cmd == '\'') ? '\'' : 0;
1349 int slash = 0;
1350 for (prog = cmd + !!quote;; prog = CharNextExA(cp, prog, 0)) {
1351 if (*prog == '/') slash = 1;
1352 if (!*prog) {
1353 len = prog - cmd;
1354 if (slash) {
1355 STRNDUPV(p, v2, cmd, len);
1356 cmd = p;
1357 }
1358 shell = cmd;
1359 break;
1360 }
1361 if ((unsigned char)*prog == quote) {
1362 len = prog++ - cmd - 1;
1363 STRNDUPV(p, v2, cmd + 1, len);
1364 shell = p;
1365 break;
1366 }
1367 if (quote) continue;
1368 if (ISSPACE(*prog) || strchr("<>|*?\"", *prog)) {
1369 len = prog - cmd;
1370 STRNDUPV(p, v2, cmd, len + (slash ? strlen(prog) : 0));
1371 if (slash) {
1372 cmd = p;
1373 sep = *(cmd_sep = &p[len]);
1374 *cmd_sep = '\0';
1375 }
1376 shell = p;
1377 break;
1378 }
1379 }
1380 shell = dln_find_exe_r(shell, NULL, fbuf, sizeof(fbuf));
1381 if (p && slash) translate_char(p, '/', '\\', cp);
1382 if (!shell) {
1383 shell = p ? p : cmd;
1384 }
1385 else {
1386 len = strlen(shell);
1387 if (strchr(shell, ' ')) quote = -1;
1388 if (shell == fbuf) {
1389 p = fbuf;
1390 }
1391 else if (shell != p && strchr(shell, '/')) {
1392 STRNDUPV(p, v2, shell, len);
1393 shell = p;
1394 }
1395 if (p) translate_char(p, '/', '\\', cp);
1396 if (is_batch(shell)) {
1397 int alen = strlen(prog);
1398 cmd = p = ALLOCV(v, len + alen + (quote ? 2 : 0) + 1);
1399 if (quote) *p++ = '"';
1400 memcpy(p, shell, len);
1401 p += len;
1402 if (quote) *p++ = '"';
1403 memcpy(p, prog, alen + 1);
1404 shell = 0;
1405 }
1406 }
1407 }
1408 }
1409
1410 if (!e && shell && !(wshell = mbstr_to_wstr(cp, shell, -1, NULL))) e = E2BIG;
1411 if (cmd_sep) *cmd_sep = sep;
1412 if (!e && cmd && !(wcmd = mbstr_to_wstr(cp, cmd, -1, NULL))) e = E2BIG;
1413 if (v2) ALLOCV_END(v2);
1414 if (v) ALLOCV_END(v);
1415
1416 if (!e) {
1417 struct ChildRecord *child = FindFreeChildSlot();
1418 if (CreateChild(child, wcmd, wshell, NULL, NULL, NULL, 0)) {
1419 ret = child_result(child, mode);
1420 }
1421 }
1422 free(wshell);
1423 free(wcmd);
1424 if (e) errno = e;
1425 return ret;
1426}
1427
1428/* License: Ruby's */
1429rb_pid_t
1430rb_w32_spawn(int mode, const char *cmd, const char *prog)
1431{
1432 /* assume ACP */
1433 return w32_spawn(mode, cmd, prog, filecp());
1434}
1435
1436/* License: Ruby's */
1437rb_pid_t
1438rb_w32_uspawn(int mode, const char *cmd, const char *prog)
1439{
1440 return w32_spawn(mode, cmd, prog, CP_UTF8);
1441}
1442
1443/* License: Artistic or GPL */
1444static rb_pid_t
1445w32_spawn_process(int mode, const char *prog, char *const *argv,
1446 int in_fd, int out_fd, int err_fd, DWORD flags, UINT cp)
1447{
1448 int c_switch = 0;
1449 size_t len;
1450 const char *shell;
1451 char *cmd, fbuf[PATH_MAX];
1452 WCHAR *wcmd = NULL, *wprog = NULL;
1453 int e = 0;
1454 rb_pid_t ret = -1;
1455 VALUE v = 0;
1456 HANDLE in_handle = NULL, out_handle = NULL, err_handle = NULL;
1457
1458 if (check_spawn_mode(mode)) return -1;
1459
1460 if (in_fd >= 0) {
1461 in_handle = (HANDLE)rb_w32_get_osfhandle(in_fd);
1462 }
1463 if (out_fd >= 0) {
1464 out_handle = (HANDLE)rb_w32_get_osfhandle(out_fd);
1465 }
1466 if (err_fd >= 0) {
1467 err_handle = (HANDLE)rb_w32_get_osfhandle(err_fd);
1468 }
1469
1470 if (!prog) prog = argv[0];
1471 if ((shell = w32_getenv("COMSPEC", cp)) && internal_cmd_match(prog)) {
1472 prog = shell;
1473 c_switch = 1;
1474 }
1475 else if ((cmd = dln_find_exe_r(prog, NULL, fbuf, sizeof(fbuf)))) {
1476 if (cmd == prog) strlcpy(cmd = fbuf, prog, sizeof(fbuf));
1477 translate_char(cmd, '/', '\\', cp);
1478 prog = cmd;
1479 }
1480 else if (strchr(prog, '/')) {
1481 len = strlen(prog);
1482 if (len < sizeof(fbuf))
1483 strlcpy(cmd = fbuf, prog, sizeof(fbuf));
1484 else
1485 STRNDUPV(cmd, v, prog, len);
1486 translate_char(cmd, '/', '\\', cp);
1487 prog = cmd;
1488 }
1489 if (c_switch || is_batch(prog)) {
1490 char *progs[2];
1491 progs[0] = (char *)prog;
1492 progs[1] = NULL;
1493 len = join_argv(NULL, progs, TRUE, cp, 1, FALSE);
1494 if (c_switch) len += 3;
1495 else ++argv;
1496 if (argv[0]) len += join_argv(NULL, argv, TRUE, cp, 0, FALSE);
1497 cmd = ALLOCV(v, len);
1498 join_argv(cmd, progs, TRUE, cp, 1, FALSE);
1499 if (c_switch) strlcat(cmd, " /c", len);
1500 if (argv[0]) join_argv(cmd + strlcat(cmd, " ", len), argv, TRUE, cp, 0, FALSE);
1501 prog = c_switch ? shell : 0;
1502 }
1503 else {
1504 len = join_argv(NULL, argv, FALSE, cp, 1, TRUE);
1505 cmd = ALLOCV(v, len);
1506 join_argv(cmd, argv, FALSE, cp, 1, TRUE);
1507 }
1508
1509 if (!e && cmd && !(wcmd = mbstr_to_wstr(cp, cmd, -1, NULL))) e = E2BIG;
1510 if (v) ALLOCV_END(v);
1511 if (!e && prog && !(wprog = mbstr_to_wstr(cp, prog, -1, NULL))) e = E2BIG;
1512
1513 if (!e) {
1514 struct ChildRecord *child = FindFreeChildSlot();
1515 if (CreateChild(child, wcmd, wprog, in_handle, out_handle, err_handle, flags)) {
1516 ret = child_result(child, mode);
1517 }
1518 }
1519 free(wprog);
1520 free(wcmd);
1521 if (e) errno = e;
1522 return ret;
1523}
1524
1525/* License: Ruby's */
1526rb_pid_t
1527rb_w32_aspawn_flags(int mode, const char *prog, char *const *argv, DWORD flags)
1528{
1529 /* assume ACP */
1530 return w32_spawn_process(mode, prog, argv, -1, -1, -1, flags, filecp());
1531}
1532
1533/* License: Ruby's */
1534rb_pid_t
1535rb_w32_uaspawn_flags(int mode, const char *prog, char *const *argv, DWORD flags)
1536{
1537 return w32_spawn_process(mode, prog, argv, -1, -1, -1, flags, CP_UTF8);
1538}
1539
1540/* License: Ruby's */
1541rb_pid_t
1542rb_w32_aspawn(int mode, const char *prog, char *const *argv)
1543{
1544 return w32_spawn_process(mode, prog, argv, -1, -1, -1, 0, filecp());
1545}
1546
1547/* License: Ruby's */
1548rb_pid_t
1549rb_w32_uaspawn(int mode, const char *prog, char *const *argv)
1550{
1551 return rb_w32_uaspawn_flags(mode, prog, argv, 0);
1552}
1553
1554/* License: Ruby's */
1555rb_pid_t
1556rb_w32_uspawn_process(int mode, const char *prog, char *const *argv,
1557 int in_fd, int out_fd, int err_fd, DWORD flags)
1558{
1559 return w32_spawn_process(mode, prog, argv, in_fd, out_fd, err_fd,
1560 flags, CP_UTF8);
1561}
1562
1563/* License: Artistic or GPL */
1564typedef struct _NtCmdLineElement {
1565 struct _NtCmdLineElement *next;
1566 char *str;
1567 long len;
1568 int flags;
1569} NtCmdLineElement;
1570
1571//
1572// Possible values for flags
1573//
1574
1575#define NTGLOB 0x1 // element contains a wildcard
1576#define NTMALLOC 0x2 // string in element was malloc'ed
1577#define NTSTRING 0x4 // element contains a quoted string
1578
1579/* License: Ruby's */
1580static int
1581insert(const char *path, VALUE vinfo, void *enc)
1582{
1583 NtCmdLineElement *tmpcurr;
1584 NtCmdLineElement ***tail = (NtCmdLineElement ***)vinfo;
1585
1586 tmpcurr = (NtCmdLineElement *)malloc(sizeof(NtCmdLineElement));
1587 if (!tmpcurr) return -1;
1588 MEMZERO(tmpcurr, NtCmdLineElement, 1);
1589 tmpcurr->len = strlen(path);
1590 tmpcurr->str = strdup(path);
1591 if (!tmpcurr->str) return -1;
1592 tmpcurr->flags |= NTMALLOC;
1593 **tail = tmpcurr;
1594 *tail = &tmpcurr->next;
1595
1596 return 0;
1597}
1598
1599/* License: Artistic or GPL */
1600static NtCmdLineElement **
1601cmdglob(NtCmdLineElement *patt, NtCmdLineElement **tail, UINT cp, rb_encoding *enc)
1602{
1603 char buffer[PATH_MAX], *buf = buffer;
1604 NtCmdLineElement **last = tail;
1605 int status;
1606
1607 if (patt->len >= PATH_MAX)
1608 if (!(buf = malloc(patt->len + 1))) return 0;
1609
1610 memcpy(buf, patt->str, patt->len);
1611 buf[patt->len] = '\0';
1612 translate_char(buf, '\\', '/', cp);
1613 status = ruby_brace_glob_with_enc(buf, 0, insert, (VALUE)&tail, enc);
1614 if (buf != buffer)
1615 free(buf);
1616
1617 if (status || last == tail) return 0;
1618 if (patt->flags & NTMALLOC)
1619 free(patt->str);
1620 free(patt);
1621 return tail;
1622}
1623
1624//
1625// Check a command string to determine if it has I/O redirection
1626// characters that require it to be executed by a command interpreter
1627//
1628
1629/* License: Artistic or GPL */
1630static int
1631has_redirection(const char *cmd, UINT cp)
1632{
1633 char quote = '\0';
1634 const char *ptr;
1635
1636 //
1637 // Scan the string, looking for redirection characters (< or >), pipe
1638 // character (|) or newline (\n) that are not in a quoted string
1639 //
1640
1641 for (ptr = cmd; *ptr;) {
1642 switch (*ptr) {
1643 case '\'':
1644 case '\"':
1645 if (!quote)
1646 quote = *ptr;
1647 else if (quote == *ptr)
1648 quote = '\0';
1649 ptr++;
1650 break;
1651
1652 case '>':
1653 case '<':
1654 case '|':
1655 case '&':
1656 case '\n':
1657 if (!quote)
1658 return TRUE;
1659 ptr++;
1660 break;
1661
1662 case '%':
1663 if (*++ptr != '_' && !ISALPHA(*ptr)) break;
1664 while (*++ptr == '_' || ISALNUM(*ptr));
1665 if (*ptr && *ptr++ == '%') return TRUE;
1666 break;
1667
1668 case '\\':
1669 ptr++;
1670 default:
1671 ptr = CharNextExA(cp, ptr, 0);
1672 break;
1673 }
1674 }
1675 return FALSE;
1676}
1677
1678/* License: Ruby's */
1679static inline WCHAR *
1680skipspace(WCHAR *ptr)
1681{
1682 while (ISSPACE(*ptr))
1683 ptr++;
1684 return ptr;
1685}
1686
1687/* License: Artistic or GPL */
1688static int
1689w32_cmdvector(const WCHAR *cmd, char ***vec, UINT cp, rb_encoding *enc)
1690{
1691 int globbing, len;
1692 int elements, strsz, done;
1693 int slashes, escape;
1694 WCHAR *ptr, *base, *cmdline;
1695 char *cptr, *buffer;
1696 char **vptr;
1697 WCHAR quote;
1698 NtCmdLineElement *curr, **tail;
1699 NtCmdLineElement *cmdhead = NULL, **cmdtail = &cmdhead;
1700
1701 //
1702 // just return if we don't have a command line
1703 //
1704 while (ISSPACE(*cmd))
1705 cmd++;
1706 if (!*cmd) {
1707 *vec = NULL;
1708 return 0;
1709 }
1710
1711 ptr = cmdline = wcsdup(cmd);
1712
1713 //
1714 // Ok, parse the command line, building a list of CmdLineElements.
1715 // When we've finished, and it's an input command (meaning that it's
1716 // the processes argv), we'll do globing and then build the argument
1717 // vector.
1718 // The outer loop does one iteration for each element seen.
1719 // The inner loop does one iteration for each character in the element.
1720 //
1721
1722 while (*(ptr = skipspace(ptr))) {
1723 base = ptr;
1724 quote = slashes = globbing = escape = 0;
1725 for (done = 0; !done && *ptr; ) {
1726 //
1727 // Switch on the current character. We only care about the
1728 // white-space characters, the wild-card characters, and the
1729 // quote characters.
1730 //
1731
1732 switch (*ptr) {
1733 case L'\\':
1734 if (quote != L'\'') slashes++;
1735 break;
1736
1737 case L' ':
1738 case L'\t':
1739 case L'\n':
1740 //
1741 // if we're not in a string, then we're finished with this
1742 // element
1743 //
1744
1745 if (!quote) {
1746 *ptr = 0;
1747 done = 1;
1748 }
1749 slashes = 0;
1750 break;
1751
1752 case L'*':
1753 case L'?':
1754 case L'[':
1755 case L'{':
1756 //
1757 // record the fact that this element has a wildcard character
1758 // N.B. Don't glob if inside a single quoted string
1759 //
1760
1761 if (quote != L'\'')
1762 globbing++;
1763 slashes = 0;
1764 break;
1765
1766 case L'\'':
1767 case L'\"':
1768 //
1769 // if we're already in a string, see if this is the
1770 // terminating close-quote. If it is, we're finished with
1771 // the string, but not necessarily with the element.
1772 // If we're not already in a string, start one.
1773 //
1774
1775 if (!(slashes & 1)) {
1776 if (!quote)
1777 quote = *ptr;
1778 else if (quote == *ptr) {
1779 if (quote == L'"' && quote == ptr[1])
1780 ptr++;
1781 quote = L'\0';
1782 }
1783 }
1784 escape++;
1785 slashes = 0;
1786 break;
1787
1788 default:
1789 ptr = CharNextW(ptr);
1790 slashes = 0;
1791 continue;
1792 }
1793 ptr++;
1794 }
1795
1796 //
1797 // when we get here, we've got a pair of pointers to the element,
1798 // base and ptr. Base points to the start of the element while ptr
1799 // points to the character following the element.
1800 //
1801
1802 len = ptr - base;
1803 if (done) --len;
1804
1805 //
1806 // if it's an input vector element and it's enclosed by quotes,
1807 // we can remove them.
1808 //
1809
1810 if (escape) {
1811 WCHAR *p = base, c;
1812 slashes = quote = 0;
1813 while (p < base + len) {
1814 switch (c = *p) {
1815 case L'\\':
1816 p++;
1817 if (quote != L'\'') slashes++;
1818 break;
1819
1820 case L'\'':
1821 case L'"':
1822 if (!(slashes & 1) && quote && quote != c) {
1823 p++;
1824 slashes = 0;
1825 break;
1826 }
1827 memcpy(p - ((slashes + 1) >> 1), p + (~slashes & 1),
1828 sizeof(WCHAR) * (base + len - p));
1829 len -= ((slashes + 1) >> 1) + (~slashes & 1);
1830 p -= (slashes + 1) >> 1;
1831 if (!(slashes & 1)) {
1832 if (quote) {
1833 if (quote == L'"' && quote == *p)
1834 p++;
1835 quote = L'\0';
1836 }
1837 else
1838 quote = c;
1839 }
1840 else
1841 p++;
1842 slashes = 0;
1843 break;
1844
1845 default:
1846 p = CharNextW(p);
1847 slashes = 0;
1848 break;
1849 }
1850 }
1851 }
1852
1853 curr = (NtCmdLineElement *)calloc(1, sizeof(NtCmdLineElement));
1854 if (!curr) goto do_nothing;
1855 curr->str = rb_w32_wstr_to_mbstr(cp, base, len, &curr->len);
1856 curr->flags |= NTMALLOC;
1857
1858 if (globbing && (tail = cmdglob(curr, cmdtail, cp, enc))) {
1859 cmdtail = tail;
1860 }
1861 else {
1862 *cmdtail = curr;
1863 cmdtail = &curr->next;
1864 }
1865 }
1866
1867 //
1868 // Almost done!
1869 // Count up the elements, then allocate space for a vector of pointers
1870 // (argv) and a string table for the elements.
1871 //
1872
1873 for (elements = 0, strsz = 0, curr = cmdhead; curr; curr = curr->next) {
1874 elements++;
1875 strsz += (curr->len + 1);
1876 }
1877
1878 len = (elements+1)*sizeof(char *) + strsz;
1879 buffer = (char *)malloc(len);
1880 if (!buffer) {
1881 do_nothing:
1882 while ((curr = cmdhead) != 0) {
1883 cmdhead = curr->next;
1884 if (curr->flags & NTMALLOC) free(curr->str);
1885 free(curr);
1886 }
1887 free(cmdline);
1888 for (vptr = *vec; *vptr; ++vptr);
1889 return vptr - *vec;
1890 }
1891
1892 //
1893 // make vptr point to the start of the buffer
1894 // and cptr point to the area we'll consider the string table.
1895 //
1896 // buffer (*vec)
1897 // |
1898 // V ^---------------------V
1899 // +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
1900 // | | | .... | NULL | | ..... |\0 | | ..... |\0 |...
1901 // +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
1902 // |- elements+1 -| ^ 1st element ^ 2nd element
1903
1904 vptr = (char **) buffer;
1905
1906 cptr = buffer + (elements+1) * sizeof(char *);
1907
1908 while ((curr = cmdhead) != 0) {
1909 memcpy(cptr, curr->str, curr->len);
1910 cptr[curr->len] = '\0';
1911 *vptr++ = cptr;
1912 cptr += curr->len + 1;
1913 cmdhead = curr->next;
1914 if (curr->flags & NTMALLOC) free(curr->str);
1915 free(curr);
1916 }
1917 *vptr = 0;
1918
1919 *vec = (char **) buffer;
1920 free(cmdline);
1921 return elements;
1922}
1923
1924//
1925// UNIX compatible directory access functions for NT
1926//
1927
1928/* License: Ruby's */
1929/* TODO: better name */
1930static HANDLE
1931open_special(const WCHAR *path, DWORD access, DWORD flags)
1932{
1933 const DWORD share_mode =
1934 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
1935 return CreateFileW(path, access, share_mode, NULL, OPEN_EXISTING,
1936 FILE_FLAG_BACKUP_SEMANTICS|flags, NULL);
1937}
1938
1939//
1940// The idea here is to read all the directory names into a string table
1941// (separated by nulls) and when one of the other dir functions is called
1942// return the pointer to the current file name.
1943//
1944
1945/* License: Ruby's */
1946#define GetBit(bits, i) ((bits)[(i) / CHAR_BIT] & (1 << (i) % CHAR_BIT))
1947#define SetBit(bits, i) ((bits)[(i) / CHAR_BIT] |= (1 << (i) % CHAR_BIT))
1948
1949#define BitOfIsDir(n) ((n) * 2)
1950#define BitOfIsRep(n) ((n) * 2 + 1)
1951#define DIRENT_PER_CHAR (CHAR_BIT / 2)
1952
1953static const WCHAR namespace_prefix[] = {L'\\', L'\\', L'?', L'\\'};
1954
1955/* License: Ruby's */
1956/* returns 0 on failure, otherwise stores tha path in `*pathptr` and
1957 * returns the length of that path. The path must be freed. */
1958static DWORD
1959get_handle_pathname(HANDLE fh, WCHAR **pathptr, DWORD add)
1960{
1961 DWORD len = GetFinalPathNameByHandleW(fh, NULL, 0, 0);
1962 if (!len) return 0;
1963 WCHAR *path = malloc((len + add + 1) * sizeof(WCHAR));
1964 if (!(*pathptr = path)) return 0;
1965 len = GetFinalPathNameByHandleW(fh, path, len + 1, 0);
1966 if (!len) {
1967 free(path);
1968 *pathptr = NULL;
1969 }
1970 return len;
1971}
1972
1973/* License: Artistic or GPL */
1974static HANDLE
1975open_dir_handle(const WCHAR *filename, WIN32_FIND_DATAW *fd)
1976{
1977 HANDLE fh;
1978 int wildcard_len = rb_strlen_lit("\\*");
1979 WCHAR *fullname = 0;
1980 WCHAR *p;
1981 int len = 0;
1982
1983 //
1984 // Create the search pattern
1985 //
1986
1987 fh = open_special(filename, 0, 0);
1988 if (fh != INVALID_HANDLE_VALUE) {
1989 len = get_handle_pathname(fh, &fullname, wildcard_len);
1990 CloseHandle(fh);
1991 }
1992 if (!len) {
1993 len = lstrlenW(filename);
1994 fullname = malloc((len + wildcard_len + 1) * sizeof(WCHAR));
1995 if (!fullname) return INVALID_HANDLE_VALUE;
1996 MEMCPY(fullname, filename, WCHAR, len);
1997 }
1998 else {
1999 RUBY_ASSERT(fullname);
2000 }
2001 p = &fullname[len-1];
2002 if (!(isdirsep(*p) || *p == L':')) *++p = L'\\';
2003 *++p = L'*';
2004 *++p = L'\0';
2005
2006 //
2007 // do the FindFirstFile call
2008 //
2009 fh = FindFirstFileW(fullname, fd);
2010 if (fh == INVALID_HANDLE_VALUE) {
2011 errno = map_errno(GetLastError());
2012 }
2013 free(fullname);
2014 return fh;
2015}
2016
2017/* License: Artistic or GPL */
2018static DIR *
2019w32_wopendir(const WCHAR *wpath)
2020{
2021 struct stati128 sbuf;
2022 WIN32_FIND_DATAW fd;
2023 HANDLE fh;
2024 DIR *p;
2025 long pathlen;
2026 long len;
2027 long altlen;
2028 long idx;
2029 WCHAR *tmpW;
2030 char *tmp;
2031
2032 //
2033 // check to see if we've got a directory
2034 //
2035 if (wstati128(wpath, &sbuf, FALSE) < 0) {
2036 return NULL;
2037 }
2038 if (!(sbuf.st_mode & S_IFDIR) &&
2039 (!ISALPHA(wpath[0]) || wpath[1] != L':' || wpath[2] != L'\0' ||
2040 ((1 << ((wpath[0] & 0x5f) - 'A')) & GetLogicalDrives()) == 0)) {
2041 errno = ENOTDIR;
2042 return NULL;
2043 }
2044 fh = open_dir_handle(wpath, &fd);
2045 if (fh == INVALID_HANDLE_VALUE) {
2046 return NULL;
2047 }
2048
2049 //
2050 // Get us a DIR structure
2051 //
2052 p = calloc(1, sizeof(DIR));
2053 if (p == NULL)
2054 return NULL;
2055
2056 pathlen = lstrlenW(wpath);
2057 idx = 0;
2058
2059 //
2060 // loop finding all the files that match the wildcard
2061 // (which should be all of them in this directory!).
2062 // the variable idx should point one past the null terminator
2063 // of the previous string found.
2064 //
2065 do {
2066 len = lstrlenW(fd.cFileName) + 1;
2067 altlen = lstrlenW(fd.cAlternateFileName) + 1;
2068
2069 //
2070 // bump the string table size by enough for the
2071 // new name and it's null terminator
2072 //
2073 tmpW = realloc(p->start, (idx + len + altlen) * sizeof(WCHAR));
2074 if (!tmpW) {
2075 error:
2076 rb_w32_closedir(p);
2077 FindClose(fh);
2078 errno = ENOMEM;
2079 return NULL;
2080 }
2081
2082 p->start = tmpW;
2083 memcpy(&p->start[idx], fd.cFileName, len * sizeof(WCHAR));
2084 memcpy(&p->start[idx + len], fd.cAlternateFileName, altlen * sizeof(WCHAR));
2085
2086 if (p->nfiles % DIRENT_PER_CHAR == 0) {
2087 tmp = realloc(p->bits, p->nfiles / DIRENT_PER_CHAR + 1);
2088 if (!tmp)
2089 goto error;
2090 p->bits = tmp;
2091 p->bits[p->nfiles / DIRENT_PER_CHAR] = 0;
2092 }
2093 if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
2094 SetBit(p->bits, BitOfIsDir(p->nfiles));
2095 if (fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
2096 WCHAR *tmppath = malloc((pathlen + len + 1) * sizeof(WCHAR));
2097 memcpy(tmppath, wpath, pathlen * sizeof(WCHAR));
2098 tmppath[pathlen] = L'\\';
2099 memcpy(tmppath + pathlen + 1, fd.cFileName, len * sizeof(WCHAR));
2100 if (rb_w32_reparse_symlink_p(tmppath))
2101 SetBit(p->bits, BitOfIsRep(p->nfiles));
2102 free(tmppath);
2103 }
2104
2105 p->nfiles++;
2106 idx += len + altlen;
2107 } while (FindNextFileW(fh, &fd));
2108 FindClose(fh);
2109 p->size = idx;
2110 p->curr = p->start;
2111 return p;
2112}
2113
2114/* License: Ruby's */
2115UINT
2116filecp(void)
2117{
2118 UINT cp = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
2119 return cp;
2120}
2121
2122/* License: Ruby's */
2123char *
2124rb_w32_wstr_to_mbstr(UINT cp, const WCHAR *wstr, int clen, long *plen)
2125{
2126 char *ptr;
2127 int len = WideCharToMultiByte(cp, 0, wstr, clen, NULL, 0, NULL, NULL);
2128 if (!(ptr = malloc(len))) return 0;
2129 WideCharToMultiByte(cp, 0, wstr, clen, ptr, len, NULL, NULL);
2130 if (plen) {
2131 /* exclude NUL only if NUL-terminated string */
2132 if (clen == -1) --len;
2133 *plen = len;
2134 }
2135 return ptr;
2136}
2137
2138/* License: Ruby's */
2139WCHAR *
2140rb_w32_mbstr_to_wstr(UINT cp, const char *str, int clen, long *plen)
2141{
2142 WCHAR *ptr;
2143 int len = MultiByteToWideChar(cp, 0, str, clen, NULL, 0);
2144 if (!(ptr = malloc(sizeof(WCHAR) * len))) return 0;
2145 MultiByteToWideChar(cp, 0, str, clen, ptr, len);
2146 if (plen) {
2147 /* exclude NUL only if NUL-terminated string */
2148 if (clen == -1) --len;
2149 *plen = len;
2150 }
2151 return ptr;
2152}
2153
2154/* License: Ruby's */
2155DIR *
2156rb_w32_opendir(const char *filename)
2157{
2158 DIR *ret;
2159 WCHAR *wpath = filecp_to_wstr(filename, NULL);
2160 if (!wpath)
2161 return NULL;
2162 ret = w32_wopendir(wpath);
2163 free(wpath);
2164 return ret;
2165}
2166
2167/* License: Ruby's */
2168DIR *
2169rb_w32_uopendir(const char *filename)
2170{
2171 DIR *ret;
2172 WCHAR *wpath = utf8_to_wstr(filename, NULL);
2173 if (!wpath)
2174 return NULL;
2175 ret = w32_wopendir(wpath);
2176 free(wpath);
2177 return ret;
2178}
2179
2180//
2181// Move to next entry
2182//
2183
2184/* License: Artistic or GPL */
2185static void
2186move_to_next_entry(DIR *dirp)
2187{
2188 if (dirp->curr) {
2189 dirp->loc++;
2190 dirp->curr += lstrlenW(dirp->curr) + 1;
2191 dirp->curr += lstrlenW(dirp->curr) + 1;
2192 if (dirp->curr >= (dirp->start + dirp->size)) {
2193 dirp->curr = NULL;
2194 }
2195 }
2196}
2197
2198//
2199// Readdir just returns the current string pointer and bumps the
2200// string pointer to the next entry.
2201//
2202/* License: Ruby's */
2203static BOOL
2204win32_direct_conv(const WCHAR *file, const WCHAR *alt, struct direct *entry, const void *enc)
2205{
2206 UINT cp = *((UINT *)enc);
2207 if (!(entry->d_name = wstr_to_mbstr(cp, file, -1, &entry->d_namlen)))
2208 return FALSE;
2209 if (alt && *alt) {
2210 long altlen = 0;
2211 entry->d_altname = wstr_to_mbstr(cp, alt, -1, &altlen);
2212 entry->d_altlen = altlen;
2213 }
2214 return TRUE;
2215}
2216
2217/* License: Ruby's */
2218VALUE
2219rb_w32_conv_from_wchar(const WCHAR *wstr, rb_encoding *enc)
2220{
2221 VALUE src;
2222 long len = lstrlenW(wstr);
2223 int encindex = rb_enc_to_index(enc);
2224
2225 if (encindex == ENCINDEX_UTF_16LE) {
2226 return rb_enc_str_new((char *)wstr, len * sizeof(WCHAR), enc);
2227 }
2228 else {
2229#if SIZEOF_INT < SIZEOF_LONG
2230# error long should equal to int on Windows
2231#endif
2232 int clen = rb_long2int(len);
2233 len = WideCharToMultiByte(CP_UTF8, 0, wstr, clen, NULL, 0, NULL, NULL);
2234 src = rb_enc_str_new(0, len, rb_enc_from_index(ENCINDEX_UTF_8));
2235 WideCharToMultiByte(CP_UTF8, 0, wstr, clen, RSTRING_PTR(src), len, NULL, NULL);
2236 }
2237 switch (encindex) {
2238 case ENCINDEX_ASCII_8BIT:
2239 case ENCINDEX_US_ASCII:
2240 /* assume UTF-8 */
2241 case ENCINDEX_UTF_8:
2242 /* do nothing */
2243 return src;
2244 }
2245 return rb_str_conv_enc_opts(src, NULL, enc, ECONV_UNDEF_REPLACE, Qnil);
2246}
2247
2248/* License: Ruby's */
2249char *
2250rb_w32_conv_from_wstr(const WCHAR *wstr, long *lenp, rb_encoding *enc)
2251{
2252 VALUE str = rb_w32_conv_from_wchar(wstr, enc);
2253 long len;
2254 char *ptr;
2255
2256 if (NIL_P(str)) return wstr_to_utf8(wstr, lenp);
2257 *lenp = len = RSTRING_LEN(str);
2258 memcpy(ptr = malloc(len + 1), RSTRING_PTR(str), len);
2259 ptr[len] = '\0';
2260 return ptr;
2261}
2262
2263/* License: Ruby's */
2264static BOOL
2265ruby_direct_conv(const WCHAR *file, const WCHAR *alt, struct direct *entry, const void *enc)
2266{
2267 if (!(entry->d_name = rb_w32_conv_from_wstr(file, &entry->d_namlen, enc)))
2268 return FALSE;
2269 if (alt && *alt) {
2270 long altlen = 0;
2271 entry->d_altname = rb_w32_conv_from_wstr(alt, &altlen, enc);
2272 entry->d_altlen = altlen;
2273 }
2274 return TRUE;
2275}
2276
2277/* License: Artistic or GPL */
2278static struct direct *
2279readdir_internal(DIR *dirp, BOOL (*conv)(const WCHAR *, const WCHAR *, struct direct *, const void *), const void *enc)
2280{
2281 static long dummy_ino = 0;
2282
2283 if (dirp->curr) {
2284
2285 //
2286 // first set up the structure to return
2287 //
2288 free(dirp->dirstr.d_name);
2289 free(dirp->dirstr.d_altname);
2290 dirp->dirstr.d_altname = 0;
2291 dirp->dirstr.d_altlen = 0;
2292 conv(dirp->curr, dirp->curr + lstrlenW(dirp->curr) + 1, &dirp->dirstr, enc);
2293
2294 //
2295 // Fake inode
2296 //
2297 dirp->dirstr.d_ino = (ino_t)(InterlockedIncrement(&dummy_ino) - 1);
2298
2299 //
2300 // Attributes
2301 //
2302 /* ignore FILE_ATTRIBUTE_DIRECTORY as unreliable for reparse points */
2303 if (GetBit(dirp->bits, BitOfIsRep(dirp->loc)))
2304 dirp->dirstr.d_type = DT_LNK;
2305 else if (GetBit(dirp->bits, BitOfIsDir(dirp->loc)))
2306 dirp->dirstr.d_type = DT_DIR;
2307 else
2308 dirp->dirstr.d_type = DT_REG;
2309
2310 //
2311 // Now set up for the next call to readdir
2312 //
2313
2314 move_to_next_entry(dirp);
2315
2316 return &(dirp->dirstr);
2317
2318 }
2319 else
2320 return NULL;
2321}
2322
2323/* License: Ruby's */
2324struct direct *
2325rb_w32_readdir(DIR *dirp, rb_encoding *enc)
2326{
2327 int idx = rb_enc_to_index(enc);
2328 if (idx == ENCINDEX_ASCII_8BIT) {
2329 const UINT cp = filecp();
2330 return readdir_internal(dirp, win32_direct_conv, &cp);
2331 }
2332 else if (idx == ENCINDEX_UTF_8) {
2333 const UINT cp = CP_UTF8;
2334 return readdir_internal(dirp, win32_direct_conv, &cp);
2335 }
2336 else
2337 return readdir_internal(dirp, ruby_direct_conv, enc);
2338}
2339
2340/* License: Ruby's */
2341struct direct *
2342rb_w32_ureaddir(DIR *dirp)
2343{
2344 const UINT cp = CP_UTF8;
2345 return readdir_internal(dirp, win32_direct_conv, &cp);
2346}
2347
2348//
2349// Telldir returns the current string pointer position
2350//
2351
2352/* License: Artistic or GPL */
2353long
2354rb_w32_telldir(DIR *dirp)
2355{
2356 return dirp->loc;
2357}
2358
2359//
2360// Seekdir moves the string pointer to a previously saved position
2361// (Saved by telldir).
2362
2363/* License: Ruby's */
2364void
2365rb_w32_seekdir(DIR *dirp, long loc)
2366{
2367 if (dirp->loc > loc) rb_w32_rewinddir(dirp);
2368
2369 while (dirp->curr && dirp->loc < loc) {
2370 move_to_next_entry(dirp);
2371 }
2372}
2373
2374//
2375// Rewinddir resets the string pointer to the start
2376//
2377
2378/* License: Artistic or GPL */
2379void
2380rb_w32_rewinddir(DIR *dirp)
2381{
2382 dirp->curr = dirp->start;
2383 dirp->loc = 0;
2384}
2385
2386//
2387// This just free's the memory allocated by opendir
2388//
2389
2390/* License: Artistic or GPL */
2391int
2392rb_w32_closedir(DIR *dirp)
2393{
2394 if (dirp) {
2395 free(dirp->dirstr.d_name);
2396 free(dirp->dirstr.d_altname);
2397 free(dirp->start);
2398 free(dirp->bits);
2399 free(dirp);
2400 }
2401 return 0;
2402}
2403
2404typedef struct {
2405 union
2406 {
2407 FILE _public_file;
2408 char* _ptr;
2409 };
2410
2411 char* _base;
2412 int _cnt;
2413 long _flags;
2414 long _file;
2415 int _charbuf;
2416 int _bufsiz;
2417 char* _tmpfname;
2418 CRITICAL_SECTION _lock;
2420#define FILE_COUNT(stream) ((vcruntime_file*)stream)->_cnt
2421#define FILE_READPTR(stream) ((vcruntime_file*)stream)->_ptr
2422#define FILE_FILENO(stream) ((vcruntime_file*)stream)->_file
2423
2424/* License: Ruby's */
2425typedef char lowio_text_mode;
2426typedef char lowio_pipe_lookahead[3];
2427
2428typedef struct {
2429 CRITICAL_SECTION lock;
2430 intptr_t osfhnd; // underlying OS file HANDLE
2431 __int64 startpos; // File position that matches buffer start
2432 unsigned char osfile; // Attributes of file (e.g., open in text mode?)
2433 lowio_text_mode textmode;
2434 lowio_pipe_lookahead _pipe_lookahead;
2435
2436 uint8_t unicode : 1; // Was the file opened as unicode?
2437 uint8_t utf8translations : 1; // Buffer contains translations other than CRLF
2438 uint8_t dbcsBufferUsed : 1; // Is the dbcsBuffer in use?
2439 char dbcsBuffer; // Buffer for the lead byte of DBCS when converting from DBCS to Unicode
2440} ioinfo;
2441
2442#if !defined _CRTIMP || defined __MINGW32__
2443#undef _CRTIMP
2444#define _CRTIMP __declspec(dllimport)
2445#endif
2446
2447static ioinfo ** __pioinfo = NULL;
2448#define IOINFO_L2E 6
2449static inline ioinfo* _pioinfo(int);
2450
2451
2452#define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
2453#define _osfhnd(i) (_pioinfo(i)->osfhnd)
2454#define _osfile(i) (_pioinfo(i)->osfile)
2455#define rb_acrt_lowio_lock_fh(i) EnterCriticalSection(&_pioinfo(i)->lock)
2456#define rb_acrt_lowio_unlock_fh(i) LeaveCriticalSection(&_pioinfo(i)->lock)
2457
2458static size_t pioinfo_extra = 0; /* workaround for VC++8 SP1 */
2459
2460/* License: Ruby's */
2461static void
2462set_pioinfo_extra(void)
2463{
2464#define FUNCTION_RET 0xc3 /* ret */
2465#ifdef _DEBUG
2466# define UCRTBASE "ucrtbased.dll"
2467#else
2468# define UCRTBASE "ucrtbase.dll"
2469#endif
2470 /* get __pioinfo addr with _isatty */
2471 /*
2472 * Why Ruby depends to _pioinfo is
2473 * * to associate socket and fd: CRuby creates fd with dummy file handle
2474 * and set socket to emulate Unix-like behavior. Without __pioinfo
2475 * we need something which manages the fd number allocation
2476 * * to implement overlapped I/O for Windows 2000/XP
2477 * * to emulate fcntl(2)
2478 *
2479 * see also
2480 * * https://bugs.ruby-lang.org/issues/11118
2481 * * https://bugs.ruby-lang.org/issues/18605
2482 */
2483 char *p = (char*)get_proc_address(UCRTBASE, "_isatty", NULL);
2484 /* _osfile(fh) & FDEV */
2485
2486#if defined(_M_ARM64) || defined(__aarch64__)
2487#define IS_INSN(pc, name) ((*(pc) & name##_mask) == name##_id)
2488 const int max_num_inst = 500;
2489 uint32_t *start = (uint32_t*)p;
2490 uint32_t *end_limit = (start + max_num_inst);
2491 uint32_t *pc = start;
2492
2493 if (!p) {
2494 fprintf(stderr, "_isatty proc not found in " UCRTBASE "\n");
2495 _exit(1);
2496 }
2497
2498 /* end of function */
2499 const uint32_t ret_id = 0xd65f0000;
2500 const uint32_t ret_mask = 0xfffffc1f;
2501 for(; pc < end_limit; pc++) {
2502 if (IS_INSN(pc, ret)) {
2503 break;
2504 }
2505 }
2506 if (pc == end_limit) {
2507 fprintf(stderr, "end of _isatty not found in " UCRTBASE "\n");
2508 _exit(1);
2509 }
2510
2511 /* pioinfo instruction mark */
2512 const uint32_t adrp_id = 0x90000000;
2513 const uint32_t adrp_mask = 0x9f000000;
2514 const uint32_t add_id = 0x11000000;
2515 const uint32_t add_mask = 0x7fc00000;
2516 for(; pc > start; pc--) {
2517 if (IS_INSN(pc, adrp) && IS_INSN(pc + 1, add)) {
2518 break;
2519 }
2520 }
2521 if(pc == start) {
2522 fprintf(stderr, "pioinfo mark not found in " UCRTBASE "\n");
2523 _exit(1);
2524 }
2525
2526 /* We now point to instructions that load address of __pioinfo:
2527 * adrp x8, 0x1801d8000
2528 * add x8, x8, #0xdb0
2529 * https://devblogs.microsoft.com/oldnewthing/20220809-00/?p=106955
2530 * The last adrp/add sequence before ret is what we are looking for.
2531 */
2532 const uint32_t adrp_insn = *pc;
2533 const uint32_t adrp_immhi = (adrp_insn & 0x00ffffe0) >> 5;
2534 const uint32_t adrp_immlo = (adrp_insn & 0x60000000) >> (5 + 19 + 5);
2535 const int64_t adrp_sign = (adrp_insn & 0x00800000) ? ~0x001fffff : 0;
2536 /* imm = SignExtend(immhi:immlo:Zeros(12), 64) */
2537 const int64_t adrp_imm = (adrp_sign | (adrp_immhi << 2) | adrp_immlo) << 12;
2538 /* base = PC64<63:12>:Zeros(12) */
2539 const uint64_t adrp_base = (uint64_t)pc & 0xfffffffffffff000;
2540
2541 const uint32_t add_insn = *(pc + 1);
2542 const uint64_t add_imm = (add_insn & 0x3ffc00) >> (5 + 5);
2543
2544 __pioinfo = (ioinfo**)(adrp_base + adrp_imm + add_imm);
2545#else /* _M_ARM64 */
2546 char *pend = p;
2547
2548# ifdef _WIN64
2549 int32_t rel;
2550 char *rip;
2551 /* add rsp, _ */
2552# define FUNCTION_BEFORE_RET_MARK "\x48\x83\xc4"
2553# define FUNCTION_SKIP_BYTES 1
2554# ifdef _DEBUG
2555 /* lea rcx,[__pioinfo's addr in RIP-relative 32bit addr] */
2556# define PIOINFO_MARK "\x48\x8d\x0d"
2557# else
2558 /* lea rdx,[__pioinfo's addr in RIP-relative 32bit addr] */
2559# define PIOINFO_MARK "\x48\x8d\x15"
2560# endif
2561
2562# else /* x86 */
2563 /* pop ebp */
2564# define FUNCTION_BEFORE_RET_MARK "\x5d"
2565 /* leave */
2566# define FUNCTION_BEFORE_RET_MARK_2 "\xc9"
2567# define FUNCTION_SKIP_BYTES 0
2568 /* mov eax,dword ptr [eax*4+100EB430h] */
2569# define PIOINFO_MARK "\x8B\x04\x85"
2570# endif
2571 if (p) {
2572 for (pend += 10; pend < p + 500; pend++) {
2573 // find end of function
2574 if ((memcmp(pend, FUNCTION_BEFORE_RET_MARK, sizeof(FUNCTION_BEFORE_RET_MARK) - 1) == 0
2575# ifdef FUNCTION_BEFORE_RET_MARK_2
2576 || memcmp(pend, FUNCTION_BEFORE_RET_MARK_2, sizeof(FUNCTION_BEFORE_RET_MARK_2) - 1) == 0
2577# endif
2578 ) &&
2579 *(pend + (sizeof(FUNCTION_BEFORE_RET_MARK) - 1) + FUNCTION_SKIP_BYTES) == (char)FUNCTION_RET) {
2580 // search backwards from end of function
2581 for (pend -= (sizeof(PIOINFO_MARK) - 1); pend > p; pend--) {
2582 if (memcmp(pend, PIOINFO_MARK, sizeof(PIOINFO_MARK) - 1) == 0) {
2583 p = pend;
2584 goto found;
2585 }
2586 }
2587 break;
2588 }
2589 }
2590 }
2591 fprintf(stderr, "unexpected " UCRTBASE "\n");
2592 _exit(1);
2593
2594 found:
2595 p += sizeof(PIOINFO_MARK) - 1;
2596#ifdef _WIN64
2597 rel = *(int32_t*)(p);
2598 rip = p + sizeof(int32_t);
2599 __pioinfo = (ioinfo**)(rip + rel);
2600#else
2601 __pioinfo = *(ioinfo***)(p);
2602#endif
2603#endif /* _M_ARM64 */
2604 int fd;
2605
2606 fd = _open("NUL", O_RDONLY);
2607 for (pioinfo_extra = 0; pioinfo_extra <= 64; pioinfo_extra += sizeof(void *)) {
2608 if (_osfhnd(fd) == _get_osfhandle(fd)) {
2609 break;
2610 }
2611 }
2612 _close(fd);
2613
2614 if (pioinfo_extra > 64) {
2615 /* not found, maybe something wrong... */
2616 pioinfo_extra = 0;
2617 }
2618}
2619
2620static inline ioinfo*
2621_pioinfo(int fd)
2622{
2623 const size_t sizeof_ioinfo = sizeof(ioinfo) + pioinfo_extra;
2624 return (ioinfo*)((char*)__pioinfo[fd >> IOINFO_L2E] +
2625 (fd & (IOINFO_ARRAY_ELTS - 1)) * sizeof_ioinfo);
2626}
2627
2628#define _set_osfhnd(fh, osfh) (void)(_osfhnd(fh) = osfh)
2629#define _set_osflags(fh, flags) (_osfile(fh) = (flags))
2630
2631#define FOPEN 0x01 /* file handle open */
2632#define FEOFLAG 0x02 /* end of file has been encountered */
2633#define FPIPE 0x08 /* file handle refers to a pipe */
2634#define FNOINHERIT 0x10 /* file handle opened O_NOINHERIT */
2635#define FAPPEND 0x20 /* file handle opened O_APPEND */
2636#define FDEV 0x40 /* file handle refers to device */
2637#define FTEXT 0x80 /* file handle is in text mode */
2638
2639static int is_socket(SOCKET);
2640static int is_console(SOCKET);
2641
2642/* License: Ruby's */
2643int
2644rb_w32_io_cancelable_p(int fd)
2645{
2646 return is_socket(TO_SOCKET(fd)) || !is_console(TO_SOCKET(fd));
2647}
2648
2649/* License: Ruby's */
2650static int
2651rb_w32_open_osfhandle(intptr_t osfhandle, int flags)
2652{
2653 int fh;
2654 char fileflags; /* _osfile flags */
2655 HANDLE hF;
2656
2657 /* copy relevant flags from second parameter */
2658 fileflags = FDEV;
2659
2660 if (flags & O_APPEND)
2661 fileflags |= FAPPEND;
2662
2663 if (flags & O_TEXT)
2664 fileflags |= FTEXT;
2665
2666 if (flags & O_NOINHERIT)
2667 fileflags |= FNOINHERIT;
2668
2669 /* attempt to allocate a C Runtime file handle */
2670 hF = CreateFile("NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
2671 fh = _open_osfhandle((intptr_t)hF, 0);
2672 CloseHandle(hF);
2673 if (fh == -1) {
2674 errno = EMFILE; /* too many open files */
2675 _doserrno = 0L; /* not an OS error */
2676 }
2677 else {
2678
2679 rb_acrt_lowio_lock_fh(fh);
2680 /* the file is open. now, set the info in _osfhnd array */
2681 _set_osfhnd(fh, osfhandle);
2682
2683 fileflags |= FOPEN; /* mark as open */
2684
2685 _set_osflags(fh, fileflags); /* set osfile entry */
2686 rb_acrt_lowio_unlock_fh(fh);
2687 }
2688 return fh; /* return handle */
2689}
2690
2691/* License: Ruby's */
2692static void
2693init_stdhandle(void)
2694{
2695 int nullfd = -1;
2696 int keep = 0;
2697#define open_null(fd) \
2698 (((nullfd < 0) ? \
2699 (nullfd = open("NUL", O_RDWR)) : 0), \
2700 ((nullfd == (fd)) ? (keep = 1) : dup2(nullfd, fd)), \
2701 (fd))
2702
2703 if (fileno(stdin) < 0) {
2704 FILE_FILENO(stdin) = open_null(0);
2705 }
2706 else {
2707 setmode(fileno(stdin), O_BINARY);
2708 }
2709 if (fileno(stdout) < 0) {
2710 FILE_FILENO(stdout) = open_null(1);
2711 }
2712 if (fileno(stderr) < 0) {
2713 FILE_FILENO(stderr) = open_null(2);
2714 }
2715 if (nullfd >= 0 && !keep) close(nullfd);
2716 setvbuf(stderr, NULL, _IONBF, 0);
2717
2718 {
2719 HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
2720 DWORD m;
2721 if (GetConsoleMode(h, &m)) {
2722#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
2723#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x4
2724#endif
2725 SetConsoleMode(h, m | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
2726 }
2727 }
2728}
2729
2730#undef getsockopt
2731
2732/* License: Ruby's */
2733static int
2734is_socket(SOCKET sock)
2735{
2736 if (socklist_lookup(sock, NULL))
2737 return TRUE;
2738 else
2739 return FALSE;
2740}
2741
2742/* License: Ruby's */
2743int
2744rb_w32_is_socket(int fd)
2745{
2746 return is_socket(TO_SOCKET(fd));
2747}
2748
2749//
2750// Since the errors returned by the socket error function
2751// WSAGetLastError() are not known by the library routine strerror
2752// we have to roll our own.
2753//
2754
2755#undef strerror
2756
2757/* License: Artistic or GPL */
2758char *
2759rb_w32_strerror(int e)
2760{
2761 static char buffer[512];
2762 DWORD source = 0;
2763 char *p;
2764
2765 if (e < 0)
2766 strlcpy(buffer, "Unknown Error", sizeof(buffer));
2767 else if (e > sys_nerr) {
2768#if WSAEWOULDBLOCK != EWOULDBLOCK
2769 if (e >= EADDRINUSE && e <= EWOULDBLOCK) {
2770 static int s = -1;
2771 int i;
2772 if (s < 0)
2773 for (s = 0; s < (int)(sizeof(errmap)/sizeof(*errmap)); s++)
2774 if (errmap[s].winerr == WSAEWOULDBLOCK)
2775 break;
2776 for (i = s; i < (int)(sizeof(errmap)/sizeof(*errmap)); i++)
2777 if (errmap[i].err == e) {
2778 e = errmap[i].winerr;
2779 break;
2780 }
2781 }
2782#endif
2783 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
2784 FORMAT_MESSAGE_IGNORE_INSERTS, &source, e,
2785 MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
2786 buffer, sizeof(buffer), NULL) == 0 &&
2787 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
2788 FORMAT_MESSAGE_IGNORE_INSERTS, &source, e, 0,
2789 buffer, sizeof(buffer), NULL) == 0)
2790 strlcpy(buffer, "Unknown Error", sizeof(buffer));
2791 }
2792 else
2793 strlcpy(buffer, strerror(e), sizeof(buffer));
2794
2795 p = buffer;
2796 while ((p = strpbrk(p, "\r\n")) != NULL) {
2797 memmove(p, p + 1, strlen(p));
2798 }
2799 return buffer;
2800}
2801
2802//
2803// various stubs
2804//
2805
2806
2807// Ownership
2808//
2809// Just pretend that everyone is a superuser. NT will let us know if
2810// we don't really have permission to do something.
2811//
2812
2813#define ROOT_UID 0
2814#define ROOT_GID 0
2815
2816/* License: Artistic or GPL */
2817rb_uid_t
2818getuid(void)
2819{
2820 return ROOT_UID;
2821}
2822
2823/* License: Artistic or GPL */
2824rb_uid_t
2825geteuid(void)
2826{
2827 return ROOT_UID;
2828}
2829
2830/* License: Artistic or GPL */
2831rb_gid_t
2832getgid(void)
2833{
2834 return ROOT_GID;
2835}
2836
2837/* License: Artistic or GPL */
2838rb_gid_t
2839getegid(void)
2840{
2841 return ROOT_GID;
2842}
2843
2844/* License: Artistic or GPL */
2845int
2846setuid(rb_uid_t uid)
2847{
2848 return (uid == ROOT_UID ? 0 : -1);
2849}
2850
2851/* License: Artistic or GPL */
2852int
2853setgid(rb_gid_t gid)
2854{
2855 return (gid == ROOT_GID ? 0 : -1);
2856}
2857
2858//
2859// File system stuff
2860//
2861
2862/* License: Artistic or GPL */
2863int
2864ioctl(int i, int u, ...)
2865{
2866 errno = EINVAL;
2867 return -1;
2868}
2869
2870void
2871rb_w32_fdset(int fd, fd_set *set)
2872{
2873 FD_SET(fd, set);
2874}
2875
2876#undef FD_CLR
2877
2878/* License: Ruby's */
2879void
2880rb_w32_fdclr(int fd, fd_set *set)
2881{
2882 unsigned int i;
2883 SOCKET s = TO_SOCKET(fd);
2884
2885 for (i = 0; i < set->fd_count; i++) {
2886 if (set->fd_array[i] == s) {
2887 memmove(&set->fd_array[i], &set->fd_array[i+1],
2888 sizeof(set->fd_array[0]) * (--set->fd_count - i));
2889 break;
2890 }
2891 }
2892}
2893
2894#undef FD_ISSET
2895
2896/* License: Ruby's */
2897int
2898rb_w32_fdisset(int fd, fd_set *set)
2899{
2900 int ret;
2901 SOCKET s = TO_SOCKET(fd);
2902 if (s == (SOCKET)INVALID_HANDLE_VALUE)
2903 return 0;
2904 RUBY_CRITICAL {ret = __WSAFDIsSet(s, set);}
2905 return ret;
2906}
2907
2908/* License: Ruby's */
2909void
2910rb_w32_fd_copy(rb_fdset_t *dst, const fd_set *src, int max)
2911{
2912 max = min(src->fd_count, (UINT)max);
2913 if ((UINT)dst->capa < (UINT)max) {
2914 dst->capa = (src->fd_count / FD_SETSIZE + 1) * FD_SETSIZE;
2915 dst->fdset = xrealloc(dst->fdset, offsetof(fd_set, fd_array) + sizeof(SOCKET) * dst->capa);
2916 }
2917
2918 memcpy(dst->fdset->fd_array, src->fd_array,
2919 max * sizeof(src->fd_array[0]));
2920 dst->fdset->fd_count = src->fd_count;
2921}
2922
2923/* License: Ruby's */
2924void
2926{
2927 if ((UINT)dst->capa < src->fdset->fd_count) {
2928 dst->capa = (src->fdset->fd_count / FD_SETSIZE + 1) * FD_SETSIZE;
2929 dst->fdset = xrealloc(dst->fdset, offsetof(fd_set, fd_array) + sizeof(SOCKET) * dst->capa);
2930 }
2931
2932 memcpy(dst->fdset->fd_array, src->fdset->fd_array,
2933 src->fdset->fd_count * sizeof(src->fdset->fd_array[0]));
2934 dst->fdset->fd_count = src->fdset->fd_count;
2935}
2936
2937//
2938// Networking trampolines
2939// These are used to avoid socket startup/shutdown overhead in case
2940// the socket routines aren't used.
2941//
2942
2943#undef select
2944
2945/* License: Ruby's */
2946static int
2947extract_fd(rb_fdset_t *dst, fd_set *src, int (*func)(SOCKET))
2948{
2949 unsigned int s = 0;
2950 unsigned int m = 0;
2951 if (!src) return 0;
2952
2953 while (s < src->fd_count) {
2954 SOCKET fd = src->fd_array[s];
2955
2956 if (!func || (*func)(fd)) {
2957 if (dst) { /* move it to dst */
2958 unsigned int d;
2959
2960 for (d = 0; d < dst->fdset->fd_count; d++) {
2961 if (dst->fdset->fd_array[d] == fd)
2962 break;
2963 }
2964 if (d == dst->fdset->fd_count) {
2965 if ((int)dst->fdset->fd_count >= dst->capa) {
2966 dst->capa = (dst->fdset->fd_count / FD_SETSIZE + 1) * FD_SETSIZE;
2967 dst->fdset = xrealloc(dst->fdset, offsetof(fd_set, fd_array) + sizeof(SOCKET) * dst->capa);
2968 }
2969 dst->fdset->fd_array[dst->fdset->fd_count++] = fd;
2970 }
2971 memmove(
2972 &src->fd_array[s],
2973 &src->fd_array[s+1],
2974 sizeof(src->fd_array[0]) * (--src->fd_count - s));
2975 }
2976 else {
2977 m++;
2978 s++;
2979 }
2980 }
2981 else s++;
2982 }
2983
2984 return dst ? dst->fdset->fd_count : m;
2985}
2986
2987/* License: Ruby's */
2988static int
2989copy_fd(fd_set *dst, fd_set *src)
2990{
2991 unsigned int s;
2992 if (!src || !dst) return 0;
2993
2994 for (s = 0; s < src->fd_count; ++s) {
2995 SOCKET fd = src->fd_array[s];
2996 unsigned int d;
2997 for (d = 0; d < dst->fd_count; ++d) {
2998 if (dst->fd_array[d] == fd)
2999 break;
3000 }
3001 if (d == dst->fd_count) {
3002 dst->fd_array[dst->fd_count++] = fd;
3003 }
3004 }
3005
3006 return dst->fd_count;
3007}
3008
3009/* License: Ruby's */
3010static void
3011save_fd(SOCKET *dst, const fd_set *src)
3012{
3013 if (src) memcpy(dst, src->fd_array, src->fd_count * sizeof(SOCKET));
3014}
3015
3016/* License: Ruby's */
3017static void
3018restore_fd(fd_set *dst, const SOCKET *src, UINT count)
3019{
3020 if (!dst) return;
3021 memcpy(dst->fd_array, src, count * sizeof(SOCKET));
3022 dst->fd_count = count;
3023}
3024
3025/* License: Ruby's */
3026static int
3027is_not_socket(SOCKET sock)
3028{
3029 return !is_socket(sock);
3030}
3031
3032/* License: Ruby's */
3033static int
3034is_pipe(SOCKET sock) /* DONT call this for SOCKET! it claims it is PIPE. */
3035{
3036 int ret;
3037
3038 RUBY_CRITICAL {
3039 ret = (GetFileType((HANDLE)sock) == FILE_TYPE_PIPE);
3040 }
3041
3042 return ret;
3043}
3044
3045/* License: Ruby's */
3046static int
3047is_readable_pipe(SOCKET sock) /* call this for pipe only */
3048{
3049 int ret;
3050 DWORD n = 0;
3051
3052 RUBY_CRITICAL {
3053 if (PeekNamedPipe((HANDLE)sock, NULL, 0, NULL, &n, NULL)) {
3054 ret = (n > 0);
3055 }
3056 else {
3057 ret = (GetLastError() == ERROR_BROKEN_PIPE); /* pipe was closed */
3058 }
3059 }
3060
3061 return ret;
3062}
3063
3064/* License: Ruby's */
3065static int
3066is_console(SOCKET sock) /* DONT call this for SOCKET! */
3067{
3068 int ret;
3069 DWORD n = 0;
3070 INPUT_RECORD ir;
3071
3072 RUBY_CRITICAL {
3073 ret = (PeekConsoleInputW((HANDLE)sock, &ir, 1, &n));
3074 }
3075
3076 return ret;
3077}
3078
3079/* License: Ruby's */
3080static int
3081is_readable_console(SOCKET sock) /* call this for console only */
3082{
3083 int ret = 0;
3084 DWORD n = 0;
3085 INPUT_RECORD ir;
3086
3087 RUBY_CRITICAL {
3088 if (PeekConsoleInputW((HANDLE)sock, &ir, 1, &n) && n > 0) {
3089 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
3090 ir.Event.KeyEvent.uChar.UnicodeChar) {
3091 ret = 1;
3092 }
3093 else if (ir.EventType == KEY_EVENT && !ir.Event.KeyEvent.bKeyDown &&
3094 ir.Event.KeyEvent.wVirtualKeyCode == VK_MENU /* ALT key */ &&
3095 ir.Event.KeyEvent.uChar.UnicodeChar) {
3096 ret = 1;
3097 }
3098 else {
3099 ReadConsoleInputW((HANDLE)sock, &ir, 1, &n);
3100 }
3101 }
3102 }
3103
3104 return ret;
3105}
3106
3107/* License: Ruby's */
3108static int
3109is_invalid_handle(SOCKET sock)
3110{
3111 return (HANDLE)sock == INVALID_HANDLE_VALUE;
3112}
3113
3114/* License: Artistic or GPL */
3115static int
3116do_select(int nfds, fd_set *rd, fd_set *wr, fd_set *ex,
3117 struct timeval *timeout)
3118{
3119 int r = 0;
3120
3121 if (nfds == 0) {
3122 if (timeout)
3123 rb_w32_sleep(timeout->tv_sec * 1000 + timeout->tv_usec / 1000);
3124 else
3125 rb_w32_sleep(INFINITE);
3126 }
3127 else {
3128 RUBY_CRITICAL {
3129 thread_exclusive(select) {
3130 r = select(nfds, rd, wr, ex, timeout);
3131 }
3132 if (r == SOCKET_ERROR) {
3133 errno = map_errno(WSAGetLastError());
3134 r = -1;
3135 }
3136 }
3137 }
3138
3139 return r;
3140}
3141
3142/*
3143 * rest -= wait
3144 * return 0 if rest is smaller than wait.
3145 */
3146/* License: Ruby's */
3147int
3148rb_w32_time_subtract(struct timeval *rest, const struct timeval *wait)
3149{
3150 if (rest->tv_sec < wait->tv_sec) {
3151 return 0;
3152 }
3153 while (rest->tv_usec < wait->tv_usec) {
3154 if (rest->tv_sec <= wait->tv_sec) {
3155 return 0;
3156 }
3157 rest->tv_sec -= 1;
3158 rest->tv_usec += 1000 * 1000;
3159 }
3160 rest->tv_sec -= wait->tv_sec;
3161 rest->tv_usec -= wait->tv_usec;
3162 return rest->tv_sec != 0 || rest->tv_usec != 0;
3163}
3164
3165/* License: Ruby's */
3166static inline int
3167compare(const struct timeval *t1, const struct timeval *t2)
3168{
3169 if (t1->tv_sec < t2->tv_sec)
3170 return -1;
3171 if (t1->tv_sec > t2->tv_sec)
3172 return 1;
3173 if (t1->tv_usec < t2->tv_usec)
3174 return -1;
3175 if (t1->tv_usec > t2->tv_usec)
3176 return 1;
3177 return 0;
3178}
3179
3180#undef Sleep
3181
3182int rb_w32_check_interrupt(void *); /* @internal */
3183
3184/* @internal */
3185/* License: Ruby's */
3186int
3187rb_w32_select_with_thread(int nfds, fd_set *rd, fd_set *wr, fd_set *ex,
3188 struct timeval *timeout, void *th)
3189{
3190 int r;
3191 rb_fdset_t pipe_rd;
3192 rb_fdset_t cons_rd;
3193 rb_fdset_t else_rd;
3194 rb_fdset_t else_wr;
3195 rb_fdset_t except;
3196 int nonsock = 0;
3197 struct timeval limit = {0, 0};
3198
3199 if (nfds < 0 || (timeout && (timeout->tv_sec < 0 || timeout->tv_usec < 0))) {
3200 errno = EINVAL;
3201 return -1;
3202 }
3203
3204 if (timeout) {
3205 if (timeout->tv_sec < 0 ||
3206 timeout->tv_usec < 0 ||
3207 timeout->tv_usec >= 1000000) {
3208 errno = EINVAL;
3209 return -1;
3210 }
3211 gettimeofday(&limit, NULL);
3212 limit.tv_sec += timeout->tv_sec;
3213 limit.tv_usec += timeout->tv_usec;
3214 if (limit.tv_usec >= 1000000) {
3215 limit.tv_usec -= 1000000;
3216 limit.tv_sec++;
3217 }
3218 }
3219
3220 // assume else_{rd,wr} (other than socket, pipe reader, console reader)
3221 // are always readable/writable. but this implementation still has
3222 // problem. if pipe's buffer is full, writing to pipe will block
3223 // until some data is read from pipe. but ruby is single threaded system,
3224 // so whole system will be blocked forever.
3225
3226 rb_fd_init(&else_rd);
3227 nonsock += extract_fd(&else_rd, rd, is_not_socket);
3228
3229 rb_fd_init(&else_wr);
3230 nonsock += extract_fd(&else_wr, wr, is_not_socket);
3231
3232 // check invalid handles
3233 if (extract_fd(NULL, else_rd.fdset, is_invalid_handle) > 0 ||
3234 extract_fd(NULL, else_wr.fdset, is_invalid_handle) > 0) {
3235 rb_fd_term(&else_wr);
3236 rb_fd_term(&else_rd);
3237 errno = EBADF;
3238 return -1;
3239 }
3240
3241 rb_fd_init(&pipe_rd);
3242 extract_fd(&pipe_rd, else_rd.fdset, is_pipe); // should not call is_pipe for socket
3243
3244 rb_fd_init(&cons_rd);
3245 extract_fd(&cons_rd, else_rd.fdset, is_console); // ditto
3246
3247 rb_fd_init(&except);
3248 extract_fd(&except, ex, is_not_socket); // drop only
3249
3250 r = 0;
3251 if (rd && (int)rd->fd_count > r) r = (int)rd->fd_count;
3252 if (wr && (int)wr->fd_count > r) r = (int)wr->fd_count;
3253 if (ex && (int)ex->fd_count > r) r = (int)ex->fd_count;
3254 if (nfds > r) nfds = r;
3255
3256 {
3257 struct timeval rest;
3258 const struct timeval wait = {0, 10 * 1000}; // 10ms
3259 struct timeval zero = {0, 0}; // 0ms
3260 // the sets may hold more than FD_SETSIZE sockets
3261 UINT nrd = rd ? rd->fd_count : 0;
3262 UINT nwr = wr ? wr->fd_count : 0;
3263 UINT nex = ex ? ex->fd_count : 0;
3264 SOCKET *orig = ALLOC_N(SOCKET, nrd + nwr + nex);
3265
3266 save_fd(orig, rd);
3267 save_fd(orig + nrd, wr);
3268 save_fd(orig + nrd + nwr, ex);
3269 for (;;) {
3270 if (th && rb_w32_check_interrupt(th) != WAIT_TIMEOUT) {
3271 r = -1;
3272 break;
3273 }
3274 if (nonsock) {
3275 // modifying {else,pipe,cons}_rd is safe because
3276 // if they are modified, function returns immediately.
3277 extract_fd(&else_rd, pipe_rd.fdset, is_readable_pipe);
3278 extract_fd(&else_rd, cons_rd.fdset, is_readable_console);
3279 }
3280
3281 if (else_rd.fdset->fd_count || else_wr.fdset->fd_count) {
3282 r = do_select(nfds, rd, wr, ex, &zero); // polling
3283 if (r < 0) break; // XXX: should I ignore error and return signaled handles?
3284 // else_{rd,wr} came out of {rd,wr}, which have room for them
3285 r += copy_fd(rd, else_rd.fdset);
3286 r += copy_fd(wr, else_wr.fdset);
3287 if (ex)
3288 r += ex->fd_count;
3289 break;
3290 }
3291 else {
3292 const struct timeval *dowait = &wait;
3293
3294 r = do_select(nfds, rd, wr, ex, &zero); // polling
3295 if (r != 0) break; // signaled or error
3296
3297 if (timeout) {
3298 struct timeval now;
3299 gettimeofday(&now, NULL);
3300 rest = limit;
3301 if (!rb_w32_time_subtract(&rest, &now)) break; // leave the sets empty
3302 if (compare(&rest, &wait) < 0) dowait = &rest;
3303 }
3304 restore_fd(rd, orig, nrd);
3305 restore_fd(wr, orig + nrd, nwr);
3306 restore_fd(ex, orig + nrd + nwr, nex);
3307 Sleep(dowait->tv_sec * 1000 + (dowait->tv_usec + 999) / 1000);
3308 }
3309 }
3310 ruby_xfree_sized(orig, sizeof(SOCKET) * (nrd + nwr + nex));
3311 }
3312
3313 rb_fd_term(&except);
3314 rb_fd_term(&cons_rd);
3315 rb_fd_term(&pipe_rd);
3316 rb_fd_term(&else_wr);
3317 rb_fd_term(&else_rd);
3318
3319 return r;
3320}
3321
3322/* License: Ruby's */
3323int WSAAPI
3324rb_w32_select(int nfds, fd_set *rd, fd_set *wr, fd_set *ex,
3325 struct timeval *timeout)
3326{
3327 return rb_w32_select_with_thread(nfds, rd, wr, ex, timeout, 0);
3328}
3329
3330/* License: Ruby's */
3331static FARPROC
3332get_wsa_extension_function(SOCKET s, GUID guid)
3333{
3334 DWORD dmy;
3335 FARPROC ptr = NULL;
3336
3337 WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, &guid, sizeof(guid),
3338 &ptr, sizeof(ptr), &dmy, NULL, NULL);
3339 if (!ptr)
3340 errno = ENOSYS;
3341 return ptr;
3342}
3343
3344#undef accept
3345
3346/* License: Artistic or GPL */
3347int WSAAPI
3348rb_w32_accept(int s, struct sockaddr *addr, int *addrlen)
3349{
3350 SOCKET r;
3351 int fd;
3352
3353 RUBY_CRITICAL {
3354 r = accept(TO_SOCKET(s), addr, addrlen);
3355 if (r != INVALID_SOCKET) {
3356 SetHandleInformation((HANDLE)r, HANDLE_FLAG_INHERIT, 0);
3357 fd = rb_w32_open_osfhandle((intptr_t)r, O_RDWR|O_BINARY|O_NOINHERIT);
3358 if (fd != -1)
3359 socklist_insert(r, 0);
3360 else
3361 closesocket(r);
3362 }
3363 else {
3364 errno = map_errno(WSAGetLastError());
3365 fd = -1;
3366 }
3367 }
3368 return fd;
3369}
3370
3371#undef bind
3372
3373/* License: Artistic or GPL */
3374int WSAAPI
3375rb_w32_bind(int s, const struct sockaddr *addr, int addrlen)
3376{
3377 int r;
3378
3379 RUBY_CRITICAL {
3380 r = bind(TO_SOCKET(s), addr, addrlen);
3381 if (r == SOCKET_ERROR)
3382 errno = map_errno(WSAGetLastError());
3383 }
3384 return r;
3385}
3386
3387#undef connect
3388
3389/* License: Artistic or GPL */
3390int WSAAPI
3391rb_w32_connect(int s, const struct sockaddr *addr, int addrlen)
3392{
3393 int r;
3394 RUBY_CRITICAL {
3395 r = connect(TO_SOCKET(s), addr, addrlen);
3396 if (r == SOCKET_ERROR) {
3397 int err = WSAGetLastError();
3398 if (err != WSAEWOULDBLOCK)
3399 errno = map_errno(err);
3400 else
3401 errno = EINPROGRESS;
3402 }
3403 }
3404 return r;
3405}
3406
3407
3408#undef getpeername
3409
3410/* License: Artistic or GPL */
3411int WSAAPI
3412rb_w32_getpeername(int s, struct sockaddr *addr, int *addrlen)
3413{
3414 int r;
3415 RUBY_CRITICAL {
3416 r = getpeername(TO_SOCKET(s), addr, addrlen);
3417 if (r == SOCKET_ERROR)
3418 errno = map_errno(WSAGetLastError());
3419 }
3420 return r;
3421}
3422
3423#undef getsockname
3424
3425/* License: Artistic or GPL */
3426int WSAAPI
3427rb_w32_getsockname(int fd, struct sockaddr *addr, int *addrlen)
3428{
3429 int sock;
3430 int r;
3431 RUBY_CRITICAL {
3432 sock = TO_SOCKET(fd);
3433 r = getsockname(sock, addr, addrlen);
3434 if (r == SOCKET_ERROR) {
3435 DWORD wsaerror = WSAGetLastError();
3436 if (wsaerror == WSAEINVAL) {
3437 int flags;
3438 if (socklist_lookup(sock, &flags)) {
3439 int af = GET_FAMILY(flags);
3440 if (af) {
3441 memset(addr, 0, *addrlen);
3442 addr->sa_family = af;
3443 return 0;
3444 }
3445 }
3446 }
3447 errno = map_errno(wsaerror);
3448 }
3449 }
3450 return r;
3451}
3452
3453#undef getsockopt
3454
3455/* License: Artistic or GPL */
3456int WSAAPI
3457rb_w32_getsockopt(int s, int level, int optname, char *optval, int *optlen)
3458{
3459 int r;
3460 RUBY_CRITICAL {
3461 r = getsockopt(TO_SOCKET(s), level, optname, optval, optlen);
3462 if (r == SOCKET_ERROR)
3463 errno = map_errno(WSAGetLastError());
3464 }
3465 /* Winsock leaves a WSA error code in SO_ERROR, but the callers expect
3466 * an errno as on the other platforms. [Bug #18661] */
3467 if (r == 0 && level == SOL_SOCKET && optname == SO_ERROR &&
3468 *optlen == (int)sizeof(int)) {
3469 int sockerr;
3470 memcpy(&sockerr, optval, sizeof(sockerr));
3471 sockerr = map_errno(sockerr);
3472 memcpy(optval, &sockerr, sizeof(sockerr));
3473 }
3474 return r;
3475}
3476
3477#undef ioctlsocket
3478
3479/* License: Artistic or GPL */
3480int WSAAPI
3481rb_w32_ioctlsocket(int s, long cmd, u_long *argp)
3482{
3483 int r;
3484 RUBY_CRITICAL {
3485 r = ioctlsocket(TO_SOCKET(s), cmd, argp);
3486 if (r == SOCKET_ERROR)
3487 errno = map_errno(WSAGetLastError());
3488 }
3489 return r;
3490}
3491
3492#undef listen
3493
3494/* License: Artistic or GPL */
3495int WSAAPI
3496rb_w32_listen(int s, int backlog)
3497{
3498 int r;
3499 RUBY_CRITICAL {
3500 r = listen(TO_SOCKET(s), backlog);
3501 if (r == SOCKET_ERROR)
3502 errno = map_errno(WSAGetLastError());
3503 }
3504 return r;
3505}
3506
3507#undef recv
3508#undef recvfrom
3509#undef send
3510#undef sendto
3511
3512/* License: Ruby's */
3513static int
3514finish_overlapped_socket(BOOL input, SOCKET s, WSAOVERLAPPED *wol, int result, DWORD *len, DWORD size)
3515{
3516 DWORD flg;
3517 int err;
3518
3519 if (result != SOCKET_ERROR)
3520 *len = size;
3521 else if ((err = WSAGetLastError()) == WSA_IO_PENDING) {
3522 switch (rb_w32_wait_events_blocking(&wol->hEvent, 1, INFINITE)) {
3523 case WAIT_OBJECT_0:
3524 RUBY_CRITICAL {
3525 result = WSAGetOverlappedResult(s, wol, &size, TRUE, &flg);
3526 }
3527 if (result) {
3528 result = 0;
3529 *len = size;
3530 break;
3531 }
3532 result = SOCKET_ERROR;
3533 /* thru */
3534 default:
3535 if ((err = WSAGetLastError()) == WSAECONNABORTED && !input)
3536 errno = EPIPE;
3537 else if (err == WSAEMSGSIZE && input) {
3538 result = 0;
3539 *len = size;
3540 break;
3541 }
3542 else
3543 errno = map_errno(err);
3544 /* thru */
3545 case WAIT_OBJECT_0 + 1:
3546 /* interrupted */
3547 *len = -1;
3548 CancelIo((HANDLE)s);
3549 break;
3550 }
3551 }
3552 else {
3553 if (err == WSAECONNABORTED && !input)
3554 errno = EPIPE;
3555 else
3556 errno = map_errno(err);
3557 *len = -1;
3558 }
3559 CloseHandle(wol->hEvent);
3560
3561 return result;
3562}
3563
3564/* License: Artistic or GPL */
3565static int
3566overlapped_socket_io(BOOL input, int fd, char *buf, int len, int flags,
3567 struct sockaddr *addr, int *addrlen)
3568{
3569 int r;
3570 int ret;
3571 int mode = 0;
3572 DWORD flg;
3573 WSAOVERLAPPED wol;
3574 WSABUF wbuf;
3575 SOCKET s;
3576
3577 s = TO_SOCKET(fd);
3578 socklist_lookup(s, &mode);
3579 if (GET_FLAGS(mode) & O_NONBLOCK) {
3580 RUBY_CRITICAL {
3581 if (input) {
3582 if (addr && addrlen)
3583 r = recvfrom(s, buf, len, flags, addr, addrlen);
3584 else
3585 r = recv(s, buf, len, flags);
3586 if (r == SOCKET_ERROR)
3587 errno = map_errno(WSAGetLastError());
3588 }
3589 else {
3590 if (addr && addrlen)
3591 r = sendto(s, buf, len, flags, addr, *addrlen);
3592 else
3593 r = send(s, buf, len, flags);
3594 if (r == SOCKET_ERROR) {
3595 DWORD err = WSAGetLastError();
3596 if (err == WSAECONNABORTED)
3597 errno = EPIPE;
3598 else
3599 errno = map_errno(err);
3600 }
3601 }
3602 }
3603 }
3604 else {
3605 DWORD size;
3606 DWORD rlen;
3607 wbuf.len = len;
3608 wbuf.buf = buf;
3609 memset(&wol, 0, sizeof(wol));
3610 RUBY_CRITICAL {
3611 wol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3612 if (input) {
3613 flg = flags;
3614 if (addr && addrlen)
3615 ret = WSARecvFrom(s, &wbuf, 1, &size, &flg, addr, addrlen,
3616 &wol, NULL);
3617 else
3618 ret = WSARecv(s, &wbuf, 1, &size, &flg, &wol, NULL);
3619 }
3620 else {
3621 if (addr && addrlen)
3622 ret = WSASendTo(s, &wbuf, 1, &size, flags, addr, *addrlen,
3623 &wol, NULL);
3624 else
3625 ret = WSASend(s, &wbuf, 1, &size, flags, &wol, NULL);
3626 }
3627 }
3628
3629 finish_overlapped_socket(input, s, &wol, ret, &rlen, size);
3630 r = (int)rlen;
3631 }
3632
3633 return r;
3634}
3635
3636/* License: Ruby's */
3637int WSAAPI
3638rb_w32_recv(int fd, char *buf, int len, int flags)
3639{
3640 return overlapped_socket_io(TRUE, fd, buf, len, flags, NULL, NULL);
3641}
3642
3643/* License: Ruby's */
3644int WSAAPI
3645rb_w32_recvfrom(int fd, char *buf, int len, int flags,
3646 struct sockaddr *from, int *fromlen)
3647{
3648 return overlapped_socket_io(TRUE, fd, buf, len, flags, from, fromlen);
3649}
3650
3651/* License: Ruby's */
3652int WSAAPI
3653rb_w32_send(int fd, const char *buf, int len, int flags)
3654{
3655 return overlapped_socket_io(FALSE, fd, (char *)buf, len, flags, NULL, NULL);
3656}
3657
3658/* License: Ruby's */
3659int WSAAPI
3660rb_w32_sendto(int fd, const char *buf, int len, int flags,
3661 const struct sockaddr *to, int tolen)
3662{
3663 return overlapped_socket_io(FALSE, fd, (char *)buf, len, flags,
3664 (struct sockaddr *)to, &tolen);
3665}
3666
3667#if !defined(MSG_TRUNC) && !defined(__MINGW32__)
3668/* License: Ruby's */
3669typedef struct {
3670 SOCKADDR *name;
3671 int namelen;
3672 WSABUF *lpBuffers;
3673 DWORD dwBufferCount;
3674 WSABUF Control;
3675 DWORD dwFlags;
3676} WSAMSG;
3677#endif
3678#ifndef WSAID_WSARECVMSG
3679#define WSAID_WSARECVMSG {0xf689d7c8,0x6f1f,0x436b,{0x8a,0x53,0xe5,0x4f,0xe3,0x51,0xc3,0x22}}
3680#endif
3681#ifndef WSAID_WSASENDMSG
3682#define WSAID_WSASENDMSG {0xa441e712,0x754f,0x43ca,{0x84,0xa7,0x0d,0xee,0x44,0xcf,0x60,0x6d}}
3683#endif
3684
3685/* License: Ruby's */
3686#define msghdr_to_wsamsg(msg, wsamsg) \
3687 do { \
3688 int i; \
3689 (wsamsg)->name = (msg)->msg_name; \
3690 (wsamsg)->namelen = (msg)->msg_namelen; \
3691 (wsamsg)->lpBuffers = ALLOCA_N(WSABUF, (msg)->msg_iovlen); \
3692 (wsamsg)->dwBufferCount = (msg)->msg_iovlen; \
3693 for (i = 0; i < (msg)->msg_iovlen; ++i) { \
3694 (wsamsg)->lpBuffers[i].buf = (msg)->msg_iov[i].iov_base; \
3695 (wsamsg)->lpBuffers[i].len = (msg)->msg_iov[i].iov_len; \
3696 } \
3697 (wsamsg)->Control.buf = (msg)->msg_control; \
3698 (wsamsg)->Control.len = (msg)->msg_controllen; \
3699 (wsamsg)->dwFlags = (msg)->msg_flags; \
3700 } while (0)
3701
3702/* License: Ruby's */
3703int
3704recvmsg(int fd, struct msghdr *msg, int flags)
3705{
3706 typedef int (WSAAPI *WSARecvMsg_t)(SOCKET, WSAMSG *, DWORD *, WSAOVERLAPPED *, LPWSAOVERLAPPED_COMPLETION_ROUTINE);
3707 static WSARecvMsg_t pWSARecvMsg = NULL;
3708 WSAMSG wsamsg;
3709 SOCKET s;
3710 int mode = 0;
3711 DWORD len;
3712 int ret;
3713
3714 s = TO_SOCKET(fd);
3715
3716 if (!pWSARecvMsg) {
3717 static const GUID guid = WSAID_WSARECVMSG;
3718 pWSARecvMsg = (WSARecvMsg_t)get_wsa_extension_function(s, guid);
3719 if (!pWSARecvMsg)
3720 return -1;
3721 }
3722
3723 msghdr_to_wsamsg(msg, &wsamsg);
3724 wsamsg.dwFlags |= flags;
3725
3726 socklist_lookup(s, &mode);
3727 if (GET_FLAGS(mode) & O_NONBLOCK) {
3728 RUBY_CRITICAL {
3729 if ((ret = pWSARecvMsg(s, &wsamsg, &len, NULL, NULL)) == SOCKET_ERROR) {
3730 errno = map_errno(WSAGetLastError());
3731 len = -1;
3732 }
3733 }
3734 }
3735 else {
3736 DWORD size;
3737 WSAOVERLAPPED wol;
3738 memset(&wol, 0, sizeof(wol));
3739 RUBY_CRITICAL {
3740 wol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3741 ret = pWSARecvMsg(s, &wsamsg, &size, &wol, NULL);
3742 }
3743
3744 ret = finish_overlapped_socket(TRUE, s, &wol, ret, &len, size);
3745 }
3746 if (ret == SOCKET_ERROR)
3747 return -1;
3748
3749 /* WSAMSG to msghdr */
3750 msg->msg_name = wsamsg.name;
3751 msg->msg_namelen = wsamsg.namelen;
3752 msg->msg_flags = wsamsg.dwFlags;
3753
3754 return len;
3755}
3756
3757/* License: Ruby's */
3758int
3759sendmsg(int fd, const struct msghdr *msg, int flags)
3760{
3761 typedef int (WSAAPI *WSASendMsg_t)(SOCKET, const WSAMSG *, DWORD, DWORD *, WSAOVERLAPPED *, LPWSAOVERLAPPED_COMPLETION_ROUTINE);
3762 static WSASendMsg_t pWSASendMsg = NULL;
3763 WSAMSG wsamsg;
3764 SOCKET s;
3765 int mode = 0;
3766 DWORD len;
3767 int ret;
3768
3769 s = TO_SOCKET(fd);
3770
3771 if (!pWSASendMsg) {
3772 static const GUID guid = WSAID_WSASENDMSG;
3773 pWSASendMsg = (WSASendMsg_t)get_wsa_extension_function(s, guid);
3774 if (!pWSASendMsg)
3775 return -1;
3776 }
3777
3778 msghdr_to_wsamsg(msg, &wsamsg);
3779
3780 socklist_lookup(s, &mode);
3781 if (GET_FLAGS(mode) & O_NONBLOCK) {
3782 RUBY_CRITICAL {
3783 if ((ret = pWSASendMsg(s, &wsamsg, flags, &len, NULL, NULL)) == SOCKET_ERROR) {
3784 errno = map_errno(WSAGetLastError());
3785 len = -1;
3786 }
3787 }
3788 }
3789 else {
3790 DWORD size;
3791 WSAOVERLAPPED wol;
3792 memset(&wol, 0, sizeof(wol));
3793 RUBY_CRITICAL {
3794 wol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3795 ret = pWSASendMsg(s, &wsamsg, flags, &size, &wol, NULL);
3796 }
3797
3798 finish_overlapped_socket(FALSE, s, &wol, ret, &len, size);
3799 }
3800
3801 return len;
3802}
3803
3804#undef setsockopt
3805
3806/* License: Artistic or GPL */
3807int WSAAPI
3808rb_w32_setsockopt(int s, int level, int optname, const char *optval, int optlen)
3809{
3810 int r;
3811 RUBY_CRITICAL {
3812 r = setsockopt(TO_SOCKET(s), level, optname, optval, optlen);
3813 if (r == SOCKET_ERROR)
3814 errno = map_errno(WSAGetLastError());
3815 }
3816 return r;
3817}
3818
3819#undef shutdown
3820
3821/* License: Artistic or GPL */
3822int WSAAPI
3823rb_w32_shutdown(int s, int how)
3824{
3825 int r;
3826 RUBY_CRITICAL {
3827 r = shutdown(TO_SOCKET(s), how);
3828 if (r == SOCKET_ERROR)
3829 errno = map_errno(WSAGetLastError());
3830 }
3831 return r;
3832}
3833
3834/* License: Ruby's */
3835static SOCKET
3836open_ifs_socket(int af, int type, int protocol)
3837{
3838 unsigned long proto_buffers_len = 0;
3839 int error_code;
3840 SOCKET out = INVALID_SOCKET;
3841
3842 if (WSAEnumProtocols(NULL, NULL, &proto_buffers_len) == SOCKET_ERROR) {
3843 error_code = WSAGetLastError();
3844 if (error_code == WSAENOBUFS) {
3845 WSAPROTOCOL_INFO *proto_buffers;
3846 int protocols_available = 0;
3847
3848 proto_buffers = (WSAPROTOCOL_INFO *)malloc(proto_buffers_len);
3849 if (!proto_buffers) {
3850 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
3851 return INVALID_SOCKET;
3852 }
3853
3854 protocols_available =
3855 WSAEnumProtocols(NULL, proto_buffers, &proto_buffers_len);
3856 if (protocols_available != SOCKET_ERROR) {
3857 int i;
3858 for (i = 0; i < protocols_available; i++) {
3859 if ((af != AF_UNSPEC && af != proto_buffers[i].iAddressFamily) ||
3860 (type != proto_buffers[i].iSocketType) ||
3861 (protocol != 0 && protocol != proto_buffers[i].iProtocol))
3862 continue;
3863
3864 if ((proto_buffers[i].dwServiceFlags1 & XP1_IFS_HANDLES) == 0)
3865 continue;
3866
3867 out = WSASocket(af, type, protocol, &(proto_buffers[i]), 0,
3868 WSA_FLAG_OVERLAPPED);
3869 break;
3870 }
3871 if (out == INVALID_SOCKET)
3872 out = WSASocket(af, type, protocol, NULL, 0, 0);
3873 if (out != INVALID_SOCKET)
3874 SetHandleInformation((HANDLE)out, HANDLE_FLAG_INHERIT, 0);
3875 }
3876
3877 free(proto_buffers);
3878 }
3879 }
3880
3881 return out;
3882}
3883
3884#undef socket
3885
3886/* License: Artistic or GPL */
3887int WSAAPI
3888rb_w32_socket(int af, int type, int protocol)
3889{
3890 SOCKET s;
3891 int fd;
3892
3893 RUBY_CRITICAL {
3894 s = open_ifs_socket(af, type, protocol);
3895 if (s == INVALID_SOCKET) {
3896 errno = map_errno(WSAGetLastError());
3897 fd = -1;
3898 }
3899 else {
3900 fd = rb_w32_open_osfhandle(s, O_RDWR|O_BINARY|O_NOINHERIT);
3901 if (fd != -1)
3902 socklist_insert(s, MAKE_SOCKDATA(af, 0));
3903 else
3904 closesocket(s);
3905 }
3906 }
3907 return fd;
3908}
3909
3910#undef gethostbyaddr
3911
3912/* License: Artistic or GPL */
3913struct hostent * WSAAPI
3914rb_w32_gethostbyaddr(const char *addr, int len, int type)
3915{
3916 struct hostent *r;
3917 RUBY_CRITICAL {
3918 r = gethostbyaddr(addr, len, type);
3919 if (r == NULL)
3920 errno = map_errno(WSAGetLastError());
3921 }
3922 return r;
3923}
3924
3925#undef gethostbyname
3926
3927/* License: Artistic or GPL */
3928struct hostent * WSAAPI
3929rb_w32_gethostbyname(const char *name)
3930{
3931 struct hostent *r;
3932 RUBY_CRITICAL {
3933 r = gethostbyname(name);
3934 if (r == NULL)
3935 errno = map_errno(WSAGetLastError());
3936 }
3937 return r;
3938}
3939
3940#undef gethostname
3941
3942static INIT_ONCE hostname_once = INIT_ONCE_STATIC_INIT;
3943static char hostname_cache[256];
3944
3945/* License: Ruby's */
3946static BOOL CALLBACK
3947init_hostname(PINIT_ONCE once, PVOID param, PVOID *context)
3948{
3949 if (gethostname(hostname_cache, sizeof(hostname_cache)) == SOCKET_ERROR) {
3950 errno = map_errno(WSAGetLastError());
3951 return FALSE;
3952 }
3953 return TRUE;
3954}
3955
3956/* License: Artistic or GPL */
3957int WSAAPI
3958rb_w32_gethostname(char *name, int len)
3959{
3960 int n;
3961
3962 /* Winsock reads the DNS settings from the registry on every call, but
3963 * the host name does not change until the system restarts, except
3964 * through this variable that Winsock also reads on every call. */
3965 if (GetEnvironmentVariableW(L"_CLUSTER_NETWORK_NAME_", NULL, 0) > 1) {
3966 int r = gethostname(name, len);
3967 if (r == SOCKET_ERROR)
3968 errno = map_errno(WSAGetLastError());
3969 return r;
3970 }
3971 if (!InitOnceExecuteOnce(&hostname_once, init_hostname, NULL, NULL))
3972 return SOCKET_ERROR;
3973 n = (int)strlen(hostname_cache);
3974 if (!name || n >= len) {
3975 WSASetLastError(WSAEFAULT);
3976 errno = map_errno(WSAEFAULT);
3977 return SOCKET_ERROR;
3978 }
3979 memcpy(name, hostname_cache, n + 1);
3980 return 0;
3981}
3982
3983#undef getprotobyname
3984
3985/* License: Artistic or GPL */
3986struct protoent * WSAAPI
3987rb_w32_getprotobyname(const char *name)
3988{
3989 struct protoent *r;
3990 RUBY_CRITICAL {
3991 r = getprotobyname(name);
3992 if (r == NULL)
3993 errno = map_errno(WSAGetLastError());
3994 }
3995 return r;
3996}
3997
3998#undef getprotobynumber
3999
4000/* License: Artistic or GPL */
4001struct protoent * WSAAPI
4002rb_w32_getprotobynumber(int num)
4003{
4004 struct protoent *r;
4005 RUBY_CRITICAL {
4006 r = getprotobynumber(num);
4007 if (r == NULL)
4008 errno = map_errno(WSAGetLastError());
4009 }
4010 return r;
4011}
4012
4013#undef getservbyname
4014
4015/* License: Artistic or GPL */
4016struct servent * WSAAPI
4017rb_w32_getservbyname(const char *name, const char *proto)
4018{
4019 struct servent *r;
4020 RUBY_CRITICAL {
4021 r = getservbyname(name, proto);
4022 if (r == NULL)
4023 errno = map_errno(WSAGetLastError());
4024 }
4025 return r;
4026}
4027
4028#undef getservbyport
4029
4030/* License: Artistic or GPL */
4031struct servent * WSAAPI
4032rb_w32_getservbyport(int port, const char *proto)
4033{
4034 struct servent *r;
4035 RUBY_CRITICAL {
4036 r = getservbyport(port, proto);
4037 if (r == NULL)
4038 errno = map_errno(WSAGetLastError());
4039 }
4040 return r;
4041}
4042
4043#ifdef HAVE_AFUNIX_H
4044
4045/* License: Ruby's */
4046static size_t
4047socketpair_unix_path(struct sockaddr_un *sock_un, WCHAR *wpath, const int maxpath)
4048{
4049 SOCKET listener;
4050
4051 /* AF_UNIX/SOCK_STREAM became available in Windows 10
4052 * See https://devblogs.microsoft.com/commandline/af_unix-comes-to-windows
4053 */
4054 listener = socket(AF_UNIX, SOCK_STREAM, 0);
4055 if (listener == INVALID_SOCKET) {
4056 errno = EAFNOSUPPORT;
4057 return 0;
4058 }
4059
4060 memset(sock_un, 0, sizeof(*sock_un));
4061 sock_un->sun_family = AF_UNIX;
4062
4063 /* Abstract sockets (filesystem-independent) don't work, contrary to
4064 * the claims of the aforementioned blog post:
4065 * https://github.com/microsoft/WSL/issues/4240#issuecomment-549663217
4066 *
4067 * So we must use a named path, and that comes with all the attendant
4068 * problems of permissions and collisions. Trying various temporary
4069 * directories and putting high-res time and PID in the filename.
4070 */
4071 for (int try = 0; ; try++) {
4072 LARGE_INTEGER ticks;
4073 int path_len = 0;
4074 static const WCHAR FALLBACK_TEMP[] = L"C:/Temp/"; // always C: exists?
4075 static const int FALLBACK_TEMP_SIZE = numberof(FALLBACK_TEMP) - 1;
4076
4077 switch (try) {
4078 case 0:
4079 /* user temp dir from TMP or TEMP env var, it ends with a backslash */
4080 path_len = GetTempPathW(maxpath, wpath);
4081 if (path_len == 0 || path_len >= maxpath) {
4082 /* The env var path did not fit in wpath (GetTempPathW then
4083 * returns the required length and leaves wpath unfilled), or
4084 * the call failed. Skip to the next candidate directory
4085 * instead of reading past wpath in WideCharToMultiByte. */
4086 continue;
4087 }
4088 break;
4089 case 1:
4090 if (FALLBACK_TEMP_SIZE >= maxpath) continue;
4091 wcsncpy(wpath, FALLBACK_TEMP, maxpath);
4092 path_len = FALLBACK_TEMP_SIZE;
4093 break;
4094 case 2:
4095 /* Current directory */
4096 path_len = 0;
4097 break;
4098 case 3:
4099 closesocket(listener);
4100 errno = EADDRNOTAVAIL;
4101 return 0;
4102 }
4103
4104 /* Windows UNIXSocket implementation expects UTF-8 instead of UTF16 */
4105 int un_len = WideCharToMultiByte(CP_UTF8, 0, wpath, path_len, sock_un->sun_path, maxpath, NULL, NULL);
4106 QueryPerformanceCounter(&ticks);
4107 int base_len = snprintf(sock_un->sun_path + un_len,
4108 maxpath - un_len,
4109 "%lld-%ld.($)",
4110 ticks.QuadPart,
4111 GetCurrentProcessId());
4112 if (un_len + base_len >= maxpath) continue;
4113
4114 /* Convert to UTF16 for DeleteFileW */
4115 MultiByteToWideChar(CP_UTF8, 0, sock_un->sun_path + un_len, base_len + 1, wpath + path_len, maxpath - path_len);
4116
4117 if (bind(listener, (struct sockaddr *)sock_un, sizeof(*sock_un)) != SOCKET_ERROR)
4118 break;
4119 }
4120 closesocket(listener);
4121 DeleteFileW(wpath);
4122 return sizeof(*sock_un);
4123}
4124#endif
4125
4126/* License: Ruby's */
4127static int
4128socketpair_internal(int af, int type, int protocol, SOCKET *sv)
4129{
4130 SOCKET svr = INVALID_SOCKET, r = INVALID_SOCKET, w = INVALID_SOCKET;
4131 struct sockaddr_in sock_in4;
4132
4133#ifdef INET6
4134 struct sockaddr_in6 sock_in6;
4135#endif
4136
4137#ifdef HAVE_AFUNIX_H
4138 struct sockaddr_un sock_un = {0, {0}};
4139 WCHAR wpath[sizeof(sock_un.sun_path)/sizeof(*sock_un.sun_path)] = L"";
4140#endif
4141
4142 struct sockaddr *addr;
4143 int ret = -1;
4144 int len;
4145
4146 switch (af) {
4147 case AF_INET:
4148#if defined PF_INET && PF_INET != AF_INET
4149 case PF_INET:
4150#endif
4151 sock_in4.sin_family = AF_INET;
4152 sock_in4.sin_port = 0;
4153 sock_in4.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4154 addr = (struct sockaddr *)&sock_in4;
4155 len = sizeof(sock_in4);
4156 break;
4157#ifdef INET6
4158 case AF_INET6:
4159 memset(&sock_in6, 0, sizeof(sock_in6));
4160 sock_in6.sin6_family = AF_INET6;
4161 sock_in6.sin6_addr = IN6ADDR_LOOPBACK_INIT;
4162 addr = (struct sockaddr *)&sock_in6;
4163 len = sizeof(sock_in6);
4164 break;
4165#endif
4166#ifdef HAVE_AFUNIX_H
4167 case AF_UNIX:
4168 addr = (struct sockaddr *)&sock_un;
4169 len = socketpair_unix_path(&sock_un, wpath, numberof(wpath));
4170 if (!len) return -1;
4171 break;
4172#endif
4173 default:
4174 errno = EAFNOSUPPORT;
4175 return -1;
4176 }
4177 if (type != SOCK_STREAM) {
4178 errno = EPROTOTYPE;
4179 return -1;
4180 }
4181
4182 sv[0] = (SOCKET)INVALID_HANDLE_VALUE;
4183 sv[1] = (SOCKET)INVALID_HANDLE_VALUE;
4184 RUBY_CRITICAL {
4185 do {
4186 svr = open_ifs_socket(af, type, protocol);
4187 if (svr == INVALID_SOCKET)
4188 break;
4189 if (bind(svr, addr, len) < 0)
4190 break;
4191 if (getsockname(svr, addr, &len) < 0)
4192 break;
4193 if (type == SOCK_STREAM)
4194 listen(svr, 5);
4195
4196 w = open_ifs_socket(af, type, protocol);
4197 if (w == INVALID_SOCKET)
4198 break;
4199 if (connect(w, addr, len) < 0)
4200 break;
4201
4202 r = accept(svr, addr, &len);
4203 if (r == INVALID_SOCKET)
4204 break;
4205 SetHandleInformation((HANDLE)r, HANDLE_FLAG_INHERIT, 0);
4206
4207 ret = 0;
4208 } while (0);
4209
4210 if (ret < 0) {
4211 errno = map_errno(WSAGetLastError());
4212 if (r != INVALID_SOCKET)
4213 closesocket(r);
4214 if (w != INVALID_SOCKET)
4215 closesocket(w);
4216 }
4217 else {
4218 sv[0] = r;
4219 sv[1] = w;
4220 }
4221 if (svr != INVALID_SOCKET)
4222 closesocket(svr);
4223#ifdef HAVE_AFUNIX_H
4224 if (sock_un.sun_family == AF_UNIX)
4225 DeleteFileW(wpath);
4226#endif
4227 }
4228
4229 return ret;
4230}
4231
4232/* License: Ruby's */
4233int
4234socketpair(int af, int type, int protocol, int *sv)
4235{
4236 SOCKET pair[2];
4237
4238 if (socketpair_internal(af, type, protocol, pair) < 0)
4239 return -1;
4240 sv[0] = rb_w32_open_osfhandle(pair[0], O_RDWR|O_BINARY|O_NOINHERIT);
4241 if (sv[0] == -1) {
4242 closesocket(pair[0]);
4243 closesocket(pair[1]);
4244 return -1;
4245 }
4246 sv[1] = rb_w32_open_osfhandle(pair[1], O_RDWR|O_BINARY|O_NOINHERIT);
4247 if (sv[1] == -1) {
4248 rb_w32_close(sv[0]);
4249 closesocket(pair[1]);
4250 return -1;
4251 }
4252 socklist_insert(pair[0], MAKE_SOCKDATA(af, 0));
4253 socklist_insert(pair[1], MAKE_SOCKDATA(af, 0));
4254
4255 return 0;
4256}
4257
4258/* License: Ruby's */
4259static void
4260str2guid(const char *str, GUID *guid)
4261{
4262#define hex2byte(str) \
4263 ((isdigit(*(str)) ? *(str) - '0' : toupper(*(str)) - 'A' + 10) << 4 | (isdigit(*((str) + 1)) ? *((str) + 1) - '0' : toupper(*((str) + 1)) - 'A' + 10))
4264 char *end;
4265 int i;
4266 if (*str == '{') str++;
4267 guid->Data1 = (long)strtoul(str, &end, 16);
4268 str += 9;
4269 guid->Data2 = (unsigned short)strtoul(str, &end, 16);
4270 str += 5;
4271 guid->Data3 = (unsigned short)strtoul(str, &end, 16);
4272 str += 5;
4273 guid->Data4[0] = hex2byte(str);
4274 str += 2;
4275 guid->Data4[1] = hex2byte(str);
4276 str += 3;
4277 for (i = 0; i < 6; i++) {
4278 guid->Data4[i + 2] = hex2byte(str);
4279 str += 2;
4280 }
4281}
4282
4283/* License: Ruby's */
4284#ifndef HAVE_TYPE_NET_LUID
4285 typedef struct {
4286 uint64_t Value;
4287 struct {
4288 uint64_t Reserved :24;
4289 uint64_t NetLuidIndex :24;
4290 uint64_t IfType :16;
4291 } Info;
4292 } NET_LUID;
4293#endif
4294
4295int
4296getifaddrs(struct ifaddrs **ifap)
4297{
4298 ULONG size = 0;
4299 ULONG ret;
4300 IP_ADAPTER_ADDRESSES *root, *addr;
4301 struct ifaddrs *prev;
4302
4303 ret = GetAdaptersAddresses(AF_UNSPEC, 0, NULL, NULL, &size);
4304 if (ret != ERROR_BUFFER_OVERFLOW) {
4305 errno = map_errno(ret);
4306 return -1;
4307 }
4308 root = ruby_xmalloc(size);
4309 ret = GetAdaptersAddresses(AF_UNSPEC, 0, NULL, root, &size);
4310 if (ret != ERROR_SUCCESS) {
4311 errno = map_errno(ret);
4312 ruby_xfree(root);
4313 return -1;
4314 }
4315
4316 for (prev = NULL, addr = root; addr; addr = addr->Next) {
4317 struct ifaddrs *ifa = ruby_xcalloc(1, sizeof(*ifa));
4318 char name[IFNAMSIZ];
4319 GUID guid;
4320 NET_LUID luid;
4321
4322 if (prev)
4323 prev->ifa_next = ifa;
4324 else
4325 *ifap = ifa;
4326
4327 str2guid(addr->AdapterName, &guid);
4328 if (ConvertInterfaceGuidToLuid(&guid, &luid) == NO_ERROR &&
4329 ConvertInterfaceLuidToNameA(&luid, name, sizeof(name)) == NO_ERROR) {
4330 ifa->ifa_name = ruby_strdup(name);
4331 }
4332 else {
4333 ifa->ifa_name = ruby_strdup(addr->AdapterName);
4334 }
4335
4336 if (addr->IfType & IF_TYPE_SOFTWARE_LOOPBACK)
4337 ifa->ifa_flags |= IFF_LOOPBACK;
4338 if (addr->OperStatus == IfOperStatusUp) {
4339 ifa->ifa_flags |= IFF_UP;
4340
4341 if (addr->FirstUnicastAddress) {
4342 IP_ADAPTER_UNICAST_ADDRESS *cur;
4343 int added = 0;
4344 for (cur = addr->FirstUnicastAddress; cur; cur = cur->Next) {
4345 if (cur->Flags & IP_ADAPTER_ADDRESS_TRANSIENT ||
4346 cur->DadState == IpDadStateDeprecated) {
4347 continue;
4348 }
4349 if (added) {
4350 prev = ifa;
4351 ifa = ruby_xcalloc(1, sizeof(*ifa));
4352 prev->ifa_next = ifa;
4353 ifa->ifa_name = ruby_strdup(prev->ifa_name);
4354 ifa->ifa_flags = prev->ifa_flags;
4355 }
4356 ifa->ifa_addr = ruby_xmalloc(cur->Address.iSockaddrLength);
4357 memcpy(ifa->ifa_addr, cur->Address.lpSockaddr,
4358 cur->Address.iSockaddrLength);
4359 added = 1;
4360 }
4361 }
4362 }
4363
4364 prev = ifa;
4365 }
4366
4367 ruby_xfree(root);
4368 return 0;
4369}
4370
4371/* License: Ruby's */
4372void
4373freeifaddrs(struct ifaddrs *ifp)
4374{
4375 while (ifp) {
4376 struct ifaddrs *next = ifp->ifa_next;
4377 ruby_xfree(ifp->ifa_addr);
4378 ruby_xfree(ifp->ifa_name);
4379 ruby_xfree(ifp);
4380 ifp = next;
4381 }
4382}
4383
4384#if 0 // Have never been used
4385//
4386// Networking stubs
4387//
4388
4389void endhostent(void) {}
4390void endnetent(void) {}
4391void endprotoent(void) {}
4392void endservent(void) {}
4393
4394struct netent *getnetent (void) {return (struct netent *) NULL;}
4395
4396struct netent *getnetbyaddr(long net, int type) {return (struct netent *)NULL;}
4397
4398struct netent *getnetbyname(const char *name) {return (struct netent *)NULL;}
4399
4400struct protoent *getprotoent (void) {return (struct protoent *) NULL;}
4401
4402struct servent *getservent (void) {return (struct servent *) NULL;}
4403
4404void sethostent (int stayopen) {}
4405
4406void setnetent (int stayopen) {}
4407
4408void setprotoent (int stayopen) {}
4409
4410void setservent (int stayopen) {}
4411#endif
4412
4413int rb_w32_set_nonblock2(int fd, int nonblock);
4414
4415/* License: Ruby's */
4416static int
4417setfl(SOCKET sock, int arg)
4418{
4419 int ret;
4420 int af = 0;
4421 int flag = 0;
4422 u_long ioctlArg;
4423
4424 socklist_lookup(sock, &flag);
4425 af = GET_FAMILY(flag);
4426 flag = GET_FLAGS(flag);
4427 if (arg & O_NONBLOCK) {
4428 flag |= O_NONBLOCK;
4429 ioctlArg = 1;
4430 }
4431 else {
4432 flag &= ~O_NONBLOCK;
4433 ioctlArg = 0;
4434 }
4435 RUBY_CRITICAL {
4436 ret = ioctlsocket(sock, FIONBIO, &ioctlArg);
4437 if (ret == 0)
4438 socklist_insert(sock, MAKE_SOCKDATA(af, flag));
4439 else
4440 errno = map_errno(WSAGetLastError());
4441 }
4442
4443 return ret;
4444}
4445
4446/* License: Ruby's */
4447static int
4448dupfd(HANDLE hDup, int flags, int minfd)
4449{
4450 int save_errno;
4451 int ret;
4452 int fds[32];
4453 int filled = 0;
4454
4455 do {
4456 ret = _open_osfhandle((intptr_t)hDup, flags | FOPEN);
4457 if (ret == -1) {
4458 goto close_fds_and_return;
4459 }
4460 if (ret >= minfd) {
4461 goto close_fds_and_return;
4462 }
4463 fds[filled++] = ret;
4464 } while (filled < (int)numberof(fds));
4465
4466 ret = dupfd(hDup, flags, minfd);
4467
4468 close_fds_and_return:
4469 save_errno = errno;
4470 while (filled > 0) {
4471 int fd = fds[--filled];
4472 _set_osfhnd(fd, (intptr_t)INVALID_HANDLE_VALUE);
4473 close(fd);
4474 }
4475 errno = save_errno;
4476
4477 return ret;
4478}
4479
4480/* License: Ruby's */
4481int
4482fcntl(int fd, int cmd, ...)
4483{
4484 va_list va;
4485 int arg;
4486 DWORD flag;
4487
4488 switch (cmd) {
4489 case F_SETFL: {
4490 va_start(va, cmd);
4491 arg = va_arg(va, int);
4492 va_end(va);
4493 return rb_w32_set_nonblock2(fd, arg);
4494 }
4495 case F_DUPFD: case F_DUPFD_CLOEXEC: {
4496 int ret;
4497 HANDLE hDup;
4498 flag = _osfile(fd);
4499 if (!(DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
4500 GetCurrentProcess(), &hDup, 0L,
4501 cmd == F_DUPFD && !(flag & FNOINHERIT),
4502 DUPLICATE_SAME_ACCESS))) {
4503 errno = map_errno(GetLastError());
4504 return -1;
4505 }
4506
4507 va_start(va, cmd);
4508 arg = va_arg(va, int);
4509 va_end(va);
4510
4511 if (cmd != F_DUPFD)
4512 flag |= FNOINHERIT;
4513 else
4514 flag &= ~FNOINHERIT;
4515 if ((ret = dupfd(hDup, flag, arg)) == -1)
4516 CloseHandle(hDup);
4517 return ret;
4518 }
4519 case F_GETFD: {
4520 SIGNED_VALUE h = _get_osfhandle(fd);
4521 if (h == -1) return -1;
4522 if (!GetHandleInformation((HANDLE)h, &flag)) {
4523 errno = map_errno(GetLastError());
4524 return -1;
4525 }
4526 return (flag & HANDLE_FLAG_INHERIT) ? 0 : FD_CLOEXEC;
4527 }
4528 case F_SETFD: {
4529 SIGNED_VALUE h = _get_osfhandle(fd);
4530 if (h == -1) return -1;
4531 va_start(va, cmd);
4532 arg = va_arg(va, int);
4533 va_end(va);
4534 if (!SetHandleInformation((HANDLE)h, HANDLE_FLAG_INHERIT,
4535 (arg & FD_CLOEXEC) ? 0 : HANDLE_FLAG_INHERIT)) {
4536 errno = map_errno(GetLastError());
4537 return -1;
4538 }
4539 if (arg & FD_CLOEXEC)
4540 _osfile(fd) |= FNOINHERIT;
4541 else
4542 _osfile(fd) &= ~FNOINHERIT;
4543 return 0;
4544 }
4545 default:
4546 errno = EINVAL;
4547 return -1;
4548 }
4549}
4550
4551/* License: Ruby's */
4552int
4553rb_w32_set_nonblock2(int fd, int nonblock)
4554{
4555 SOCKET sock = TO_SOCKET(fd);
4556 if (is_socket(sock)) {
4557 return setfl(sock, nonblock ? O_NONBLOCK : 0);
4558 }
4559 else if (is_pipe(sock)) {
4560 DWORD state, mode;
4561 if (!GetNamedPipeHandleState((HANDLE)sock, &state, NULL, NULL, NULL, NULL, 0)) {
4562 errno = map_errno(GetLastError());
4563 return -1;
4564 }
4565 if (nonblock) {
4566 mode = state | PIPE_NOWAIT;
4567 }
4568 else {
4569 mode = state & ~PIPE_NOWAIT;
4570 }
4571 if (mode != state && !SetNamedPipeHandleState((HANDLE)sock, &mode, NULL, NULL)) {
4572 errno = map_errno(GetLastError());
4573 return -1;
4574 }
4575 return 0;
4576 }
4577 else {
4578 errno = EBADF;
4579 return -1;
4580 }
4581}
4582
4583int
4584rb_w32_set_nonblock(int fd)
4585{
4586 return rb_w32_set_nonblock2(fd, TRUE);
4587}
4588
4589#ifndef WNOHANG
4590#define WNOHANG -1
4591#endif
4592
4593/* License: Ruby's */
4594static rb_pid_t
4595poll_child_status(struct ChildRecord *child, int *stat_loc)
4596{
4597 DWORD exitcode;
4598 DWORD err;
4599
4600 if (!GetExitCodeProcess(child->hProcess, &exitcode)) {
4601 /* If an error occurred, return immediately. */
4602 err = GetLastError();
4603 switch (err) {
4604 case ERROR_INVALID_PARAMETER:
4605 errno = ECHILD;
4606 break;
4607 case ERROR_INVALID_HANDLE:
4608 errno = EINVAL;
4609 break;
4610 default:
4611 errno = map_errno(err);
4612 break;
4613 }
4614 error_exit:
4615 CloseChildHandle(child);
4616 return -1;
4617 }
4618 if (exitcode != STILL_ACTIVE) {
4619 rb_pid_t pid;
4620 /* If already died, wait process's real termination. */
4621 if (rb_w32_wait_events_blocking(&child->hProcess, 1, INFINITE) != WAIT_OBJECT_0) {
4622 goto error_exit;
4623 }
4624 pid = child->pid;
4625 CloseChildHandle(child);
4626 if (stat_loc) {
4627 *stat_loc = exitcode << 8;
4628 if (exitcode & 0xC0000000) {
4629 static const struct {
4630 DWORD status;
4631 int sig;
4632 } table[] = {
4633 {STATUS_ACCESS_VIOLATION, SIGSEGV},
4634 {STATUS_ILLEGAL_INSTRUCTION, SIGILL},
4635 {STATUS_PRIVILEGED_INSTRUCTION, SIGILL},
4636 {STATUS_FLOAT_DENORMAL_OPERAND, SIGFPE},
4637 {STATUS_FLOAT_DIVIDE_BY_ZERO, SIGFPE},
4638 {STATUS_FLOAT_INEXACT_RESULT, SIGFPE},
4639 {STATUS_FLOAT_INVALID_OPERATION, SIGFPE},
4640 {STATUS_FLOAT_OVERFLOW, SIGFPE},
4641 {STATUS_FLOAT_STACK_CHECK, SIGFPE},
4642 {STATUS_FLOAT_UNDERFLOW, SIGFPE},
4643#ifdef STATUS_FLOAT_MULTIPLE_FAULTS
4644 {STATUS_FLOAT_MULTIPLE_FAULTS, SIGFPE},
4645#endif
4646#ifdef STATUS_FLOAT_MULTIPLE_TRAPS
4647 {STATUS_FLOAT_MULTIPLE_TRAPS, SIGFPE},
4648#endif
4649 {STATUS_CONTROL_C_EXIT, SIGINT},
4650 };
4651 int i;
4652 for (i = 0; i < (int)numberof(table); i++) {
4653 if (table[i].status == exitcode) {
4654 *stat_loc |= table[i].sig;
4655 break;
4656 }
4657 }
4658 // if unknown status, assume SEGV
4659 if (i >= (int)numberof(table))
4660 *stat_loc |= SIGSEGV;
4661 }
4662 }
4663 return pid;
4664 }
4665 return 0;
4666}
4667
4668/* License: Artistic or GPL */
4669rb_pid_t
4670waitpid(rb_pid_t pid, int *stat_loc, int options)
4671{
4672 DWORD timeout;
4673
4674 /* Artistic or GPL part start */
4675 if (options == WNOHANG) {
4676 timeout = 0;
4677 }
4678 else {
4679 timeout = INFINITE;
4680 }
4681 /* Artistic or GPL part end */
4682
4683 if (pid == -1) {
4684 int count = 0;
4685 int ret;
4686 HANDLE events[MAXCHILDNUM];
4687 struct ChildRecord* cause;
4688
4689 FOREACH_CHILD(child) {
4690 if (!child->pid || child->pid < 0) continue;
4691 if ((pid = poll_child_status(child, stat_loc))) return pid;
4692 events[count++] = child->hProcess;
4693 } END_FOREACH_CHILD;
4694 if (!count) {
4695 errno = ECHILD;
4696 return -1;
4697 }
4698
4699 ret = rb_w32_wait_events_blocking(events, count, timeout);
4700 if (ret == WAIT_TIMEOUT) return 0;
4701 if ((ret -= WAIT_OBJECT_0) == count) {
4702 return -1;
4703 }
4704 if (ret > count) {
4705 errno = map_errno(GetLastError());
4706 return -1;
4707 }
4708
4709 cause = FindChildSlotByHandle(events[ret]);
4710 if (!cause) {
4711 errno = ECHILD;
4712 return -1;
4713 }
4714 return poll_child_status(cause, stat_loc);
4715 }
4716 else {
4717 struct ChildRecord* child = FindChildSlot(pid);
4718 int retried = 0;
4719 if (!child) {
4720 errno = ECHILD;
4721 return -1;
4722 }
4723
4724 while (!(pid = poll_child_status(child, stat_loc))) {
4725 /* wait... */
4726 int ret = rb_w32_wait_events_blocking(&child->hProcess, 1, timeout);
4727 if (ret == WAIT_OBJECT_0 + 1) return -1; /* maybe EINTR */
4728 if (ret != WAIT_OBJECT_0) {
4729 /* still active */
4730 if (options & WNOHANG) {
4731 pid = 0;
4732 break;
4733 }
4734 ++retried;
4735 }
4736 }
4737 if (pid == -1 && retried) pid = 0;
4738 }
4739
4740 return pid;
4741}
4742
4743#include <sys/timeb.h>
4744
4745/* License: Ruby's */
4746#define filetime_unit (10UL * 1000 * 1000)
4747#define filetime_diff_days ((1970-1601)*3652425UL/10000)
4748#define filetime_diff_secs (filetime_diff_days * (24ULL * 60 * 60))
4749#define unix_to_filetime(sec) (((sec) + filetime_diff_secs) * filetime_unit)
4750static const ULONGLONG filetime_unix_offset = unix_to_filetime(0ULL);
4751static const unsigned long secs_in_ns = 1000000000UL;
4752
4753/* License: Ruby's */
4754typedef union {
4755 /* FILETIME and ULARGE_INTEGER::u are the same layout */
4756 FILETIME ft;
4757 ULARGE_INTEGER i;
4759
4760/* License: Ruby's */
4761/* split LARGE_INTEGER value into UNIX time and sub-seconds in NT ticks */
4762static time_t
4763li_time_split(ULONGLONG lt, long *subsec)
4764{
4765 /* lt is now 100-nanosec intervals since 1601/01/01 00:00:00 UTC,
4766 convert it into UNIX time (since 1970/01/01 00:00:00 UTC).
4767 the first leap second is at 1972/06/30, so we doesn't need to think
4768 about it. */
4769 lt -= filetime_unix_offset;
4770
4771 *subsec = (long)(lt % filetime_unit);
4772 return (time_t)(lt / filetime_unit);
4773}
4774
4775/* License: Ruby's */
4776static time_t
4777li_time_split_ns(ULONGLONG lt, long *ns)
4778{
4779 long subsec;
4780 time_t t = li_time_split(lt, &subsec);
4781
4782 *ns = subsec * 100;
4783 if (t < 0) return 0;
4784 return t;
4785}
4786
4787/* License: Ruby's */
4788static ULONGLONG
4789filetime_to_li_time(const FILETIME* ft)
4790{
4791 FILETIME_INTEGER fi = {.ft = *ft};
4792 return fi.i.QuadPart;
4793}
4794
4795/* License: Ruby's */
4796int __cdecl
4797gettimeofday(struct timeval *tv, struct timezone *tz)
4798{
4799 FILETIME ft;
4800 long subsec;
4801
4802 GetSystemTimePreciseAsFileTime(&ft);
4803 tv->tv_sec = li_time_split(filetime_to_li_time(&ft), &subsec);
4804 tv->tv_usec = subsec / 10;
4805
4806 return 0;
4807}
4808
4809/* License: Ruby's */
4810static time_t
4811filetime_to_unixtime(const FILETIME *ft)
4812{
4813 long subsec;
4814 time_t t = li_time_split(filetime_to_li_time(ft), &subsec);
4815
4816 if (t < 0) return 0;
4817 return t;
4818}
4819
4820/* License: Ruby's */
4821static time_t
4822filetime_split_ns(const FILETIME *ft, long *ns)
4823{
4824 return li_time_split_ns(filetime_to_li_time(ft), ns);
4825}
4826
4827/* License: Ruby's */
4828static void
4829filetime_to_timespec(FILETIME ft, struct timespec *sp)
4830{
4831 sp->tv_sec = filetime_split_ns(&ft, &sp->tv_nsec);
4832}
4833
4834/* License: Ruby's */
4835int
4836clock_gettime(clockid_t clock_id, struct timespec *sp)
4837{
4838 switch (clock_id) {
4839 case CLOCK_REALTIME:
4840 case CLOCK_REALTIME_COARSE:
4841 {
4842 FILETIME ft;
4843
4844 GetSystemTimePreciseAsFileTime(&ft);
4845 filetime_to_timespec(ft, sp);
4846 return 0;
4847 }
4848 case CLOCK_MONOTONIC:
4849 {
4850 LARGE_INTEGER freq;
4851 LARGE_INTEGER count;
4852 if (UNLIKELY(!QueryPerformanceFrequency(&freq))) {
4853 errno = map_errno(GetLastError());
4854 return -1;
4855 }
4856 if (UNLIKELY(!QueryPerformanceCounter(&count))) {
4857 errno = map_errno(GetLastError());
4858 return -1;
4859 }
4860 sp->tv_sec = count.QuadPart / freq.QuadPart;
4861 if (freq.QuadPart < secs_in_ns)
4862 sp->tv_nsec = (count.QuadPart % freq.QuadPart) * secs_in_ns / freq.QuadPart;
4863 else
4864 sp->tv_nsec = (long)((count.QuadPart % freq.QuadPart) * ((double)secs_in_ns / freq.QuadPart));
4865 return 0;
4866 }
4867 case CLOCK_PROCESS_CPUTIME_ID:
4868 case CLOCK_THREAD_CPUTIME_ID:
4869 {
4870 FILETIME_INTEGER c, e, k, u, total;
4871 BOOL ok;
4872 if (clock_id == CLOCK_PROCESS_CPUTIME_ID) {
4873 ok = GetProcessTimes(GetCurrentProcess(), &c.ft, &e.ft, &k.ft, &u.ft);
4874 }
4875 else {
4876 ok = GetThreadTimes(GetCurrentThread(), &c.ft, &e.ft, &k.ft, &u.ft);
4877 }
4878 if (UNLIKELY(!ok)) {
4879 errno = map_errno(GetLastError());
4880 return -1;
4881 }
4882 total.i.QuadPart = k.i.QuadPart + u.i.QuadPart;
4883 filetime_to_timespec(total.ft, sp);
4884 return 0;
4885 }
4886 default:
4887 errno = EINVAL;
4888 return -1;
4889 }
4890}
4891
4892/* License: Ruby's */
4893int
4894clock_getres(clockid_t clock_id, struct timespec *sp)
4895{
4896 switch (clock_id) {
4897 case CLOCK_REALTIME:
4898 case CLOCK_REALTIME_COARSE:
4899 {
4900 sp->tv_sec = 0;
4901 sp->tv_nsec = 1000;
4902 return 0;
4903 }
4904 case CLOCK_MONOTONIC:
4905 {
4906 LARGE_INTEGER freq;
4907 if (!QueryPerformanceFrequency(&freq)) {
4908 errno = map_errno(GetLastError());
4909 return -1;
4910 }
4911 sp->tv_sec = 0;
4912 sp->tv_nsec = (long)((double)secs_in_ns / freq.QuadPart);
4913 return 0;
4914 }
4915 case CLOCK_PROCESS_CPUTIME_ID:
4916 case CLOCK_THREAD_CPUTIME_ID:
4917 {
4918 const int frames_in_sec = 60;
4919 sp->tv_sec = 0;
4920 sp->tv_nsec = (long)(secs_in_ns / frames_in_sec);
4921 return 0;
4922 }
4923 default:
4924 errno = EINVAL;
4925 return -1;
4926 }
4927}
4928
4929/* License: Ruby's */
4930static char *
4931w32_getcwd(char *buffer, int size, UINT cp, void *alloc(int, void *), void *arg)
4932{
4933 WCHAR *p;
4934 int wlen, len;
4935
4936 len = GetCurrentDirectoryW(0, NULL);
4937 if (!len) {
4938 errno = map_errno(GetLastError());
4939 return NULL;
4940 }
4941
4942 if (buffer && size < len) {
4943 errno = ERANGE;
4944 return NULL;
4945 }
4946
4947 p = ALLOCA_N(WCHAR, len);
4948 if (!GetCurrentDirectoryW(len, p)) {
4949 errno = map_errno(GetLastError());
4950 return NULL;
4951 }
4952
4953 wlen = translate_wchar(p, L'\\', L'/') - p + 1;
4954 len = WideCharToMultiByte(cp, 0, p, wlen, NULL, 0, NULL, NULL);
4955 if (buffer) {
4956 if (size < len) {
4957 errno = ERANGE;
4958 return NULL;
4959 }
4960 }
4961 else {
4962 buffer = (*alloc)(len, arg);
4963 if (!buffer) {
4964 errno = ENOMEM;
4965 return NULL;
4966 }
4967 }
4968 WideCharToMultiByte(cp, 0, p, wlen, buffer, len, NULL, NULL);
4969
4970 return buffer;
4971}
4972
4973/* License: Ruby's */
4974static void *
4975getcwd_alloc(int size, void *dummy)
4976{
4977 return malloc(size);
4978}
4979
4980/* License: Ruby's */
4981char *
4982rb_w32_getcwd(char *buffer, int size)
4983{
4984 return w32_getcwd(buffer, size, filecp(), getcwd_alloc, NULL);
4985}
4986
4987/* License: Ruby's */
4988char *
4989rb_w32_ugetcwd(char *buffer, int size)
4990{
4991 return w32_getcwd(buffer, size, CP_UTF8, getcwd_alloc, NULL);
4992}
4993
4994/* License: Ruby's */
4995static void *
4996getcwd_value(int size, void *arg)
4997{
4998 VALUE str = *(VALUE *)arg = rb_utf8_str_new(0, size - 1);
4999 return RSTRING_PTR(str);
5000}
5001
5002/* License: Ruby's */
5003VALUE
5004rb_dir_getwd_ospath(void)
5005{
5006 VALUE cwd = Qnil;
5007 w32_getcwd(NULL, 0, CP_UTF8, getcwd_value, &cwd);
5008 return cwd;
5009}
5010
5011/* License: Artistic or GPL */
5012int
5013chown(const char *path, int owner, int group)
5014{
5015 return 0;
5016}
5017
5018/* License: Artistic or GPL */
5019int
5020rb_w32_uchown(const char *path, int owner, int group)
5021{
5022 return 0;
5023}
5024
5025int
5026lchown(const char *path, int owner, int group)
5027{
5028 return 0;
5029}
5030
5031int
5032rb_w32_ulchown(const char *path, int owner, int group)
5033{
5034 return 0;
5035}
5036
5037/* License: Ruby's */
5038int
5039kill(rb_pid_t pid, int sig)
5040{
5041 int ret = 0;
5042 DWORD err;
5043
5044 if (pid < 0 || (pid == 0 && sig != SIGINT)) {
5045 errno = EINVAL;
5046 return -1;
5047 }
5048
5049 if ((unsigned int)pid == GetCurrentProcessId() &&
5050 (sig != 0 && sig != SIGKILL)) {
5051 if ((ret = raise(sig)) != 0) {
5052 /* MSVCRT doesn't set errno... */
5053 errno = EINVAL;
5054 }
5055 return ret;
5056 }
5057
5058 switch (sig) {
5059 case 0:
5060 RUBY_CRITICAL {
5061 HANDLE hProc =
5062 OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, (DWORD)pid);
5063 if (hProc == NULL || hProc == INVALID_HANDLE_VALUE) {
5064 if (GetLastError() == ERROR_INVALID_PARAMETER) {
5065 errno = ESRCH;
5066 }
5067 else {
5068 errno = EPERM;
5069 }
5070 ret = -1;
5071 }
5072 else {
5073 CloseHandle(hProc);
5074 }
5075 }
5076 break;
5077
5078 case SIGINT:
5079 RUBY_CRITICAL {
5080 DWORD ctrlEvent = CTRL_C_EVENT;
5081 if (pid != 0) {
5082 /* CTRL+C signal cannot be generated for process groups.
5083 * Instead, we use CTRL+BREAK signal. */
5084 ctrlEvent = CTRL_BREAK_EVENT;
5085 }
5086 if (!GenerateConsoleCtrlEvent(ctrlEvent, (DWORD)pid)) {
5087 if ((err = GetLastError()) == 0)
5088 errno = EPERM;
5089 else
5090 errno = map_errno(GetLastError());
5091 ret = -1;
5092 }
5093 }
5094 break;
5095
5096 case SIGKILL:
5097 RUBY_CRITICAL {
5098 HANDLE hProc;
5099 struct ChildRecord* child = FindChildSlot(pid);
5100 if (child) {
5101 hProc = child->hProcess;
5102 }
5103 else {
5104 hProc = OpenProcess(PROCESS_TERMINATE | PROCESS_QUERY_INFORMATION, FALSE, (DWORD)pid);
5105 }
5106 if (hProc == NULL || hProc == INVALID_HANDLE_VALUE) {
5107 if (GetLastError() == ERROR_INVALID_PARAMETER) {
5108 errno = ESRCH;
5109 }
5110 else {
5111 errno = EPERM;
5112 }
5113 ret = -1;
5114 }
5115 else {
5116 DWORD status;
5117 if (!GetExitCodeProcess(hProc, &status)) {
5118 errno = map_errno(GetLastError());
5119 ret = -1;
5120 }
5121 else if (status == STILL_ACTIVE) {
5122 if (!TerminateProcess(hProc, 0)) {
5123 errno = EPERM;
5124 ret = -1;
5125 }
5126 }
5127 else {
5128 errno = ESRCH;
5129 ret = -1;
5130 }
5131 if (!child) {
5132 CloseHandle(hProc);
5133 }
5134 }
5135 }
5136 break;
5137
5138 default:
5139 errno = EINVAL;
5140 ret = -1;
5141 break;
5142 }
5143
5144 return ret;
5145}
5146
5147/* License: Ruby's */
5148static int
5149wlink(const WCHAR *from, const WCHAR *to)
5150{
5151 if (!CreateHardLinkW(to, from, NULL)) {
5152 errno = map_errno(GetLastError());
5153 return -1;
5154 }
5155
5156 return 0;
5157}
5158
5159/* License: Ruby's */
5160int
5161rb_w32_ulink(const char *from, const char *to)
5162{
5163 WCHAR *wfrom;
5164 WCHAR *wto;
5165 int ret;
5166
5167 if (!(wfrom = utf8_to_wstr(from, NULL)))
5168 return -1;
5169 if (!(wto = utf8_to_wstr(to, NULL))) {
5170 free(wfrom);
5171 return -1;
5172 }
5173 ret = wlink(wfrom, wto);
5174 free(wto);
5175 free(wfrom);
5176 return ret;
5177}
5178
5179/* License: Ruby's */
5180int
5181link(const char *from, const char *to)
5182{
5183 WCHAR *wfrom;
5184 WCHAR *wto;
5185 int ret;
5186
5187 if (!(wfrom = filecp_to_wstr(from, NULL)))
5188 return -1;
5189 if (!(wto = filecp_to_wstr(to, NULL))) {
5190 free(wfrom);
5191 return -1;
5192 }
5193 ret = wlink(wfrom, wto);
5194 free(wto);
5195 free(wfrom);
5196 return ret;
5197}
5198
5199/* License: Public Domain, copied from mingw headers */
5200#ifndef FILE_DEVICE_FILE_SYSTEM
5201# define FILE_DEVICE_FILE_SYSTEM 0x00000009
5202#endif
5203#ifndef FSCTL_GET_REPARSE_POINT
5204# define FSCTL_GET_REPARSE_POINT ((0x9<<16)|(42<<2))
5205#endif
5206#ifndef IO_REPARSE_TAG_SYMLINK
5207# define IO_REPARSE_TAG_SYMLINK 0xA000000CL
5208#endif
5209
5210/* License: Ruby's */
5211static int
5212reparse_symlink(const WCHAR *path, rb_w32_reparse_buffer_t *rp, size_t size)
5213{
5214 HANDLE f;
5215 DWORD ret;
5216 int e = 0;
5217
5218 f = open_special(path, 0, FILE_FLAG_OPEN_REPARSE_POINT);
5219 if (f == INVALID_HANDLE_VALUE) {
5220 return GetLastError();
5221 }
5222
5223 if (!DeviceIoControl(f, FSCTL_GET_REPARSE_POINT, NULL, 0,
5224 rp, size, &ret, NULL)) {
5225 e = GetLastError();
5226 }
5227 else if (rp->ReparseTag != IO_REPARSE_TAG_SYMLINK &&
5228 rp->ReparseTag != IO_REPARSE_TAG_MOUNT_POINT) {
5229 e = ERROR_INVALID_PARAMETER;
5230 }
5231 CloseHandle(f);
5232 return e;
5233}
5234
5235/* License: Ruby's */
5236int
5237rb_w32_reparse_symlink_p(const WCHAR *path)
5238{
5239 VALUE wtmp = 0;
5240 rb_w32_reparse_buffer_t rbuf, *rp = &rbuf;
5241 WCHAR *wbuf;
5242 DWORD len;
5243 int e;
5244
5245 e = rb_w32_read_reparse_point(path, rp, sizeof(rbuf), &wbuf, &len);
5246 if (e == ERROR_MORE_DATA) {
5247 size_t size = rb_w32_reparse_buffer_size(len + 1);
5248 rp = ALLOCV(wtmp, size);
5249 e = rb_w32_read_reparse_point(path, rp, size, &wbuf, &len);
5250 ALLOCV_END(wtmp);
5251 }
5252 switch (e) {
5253 case 0:
5254 case ERROR_MORE_DATA:
5255 return TRUE;
5256 }
5257 return FALSE;
5258}
5259
5260/* License: Ruby's */
5261int
5262rb_w32_read_reparse_point(const WCHAR *path, rb_w32_reparse_buffer_t *rp,
5263 size_t bufsize, WCHAR **result, DWORD *len)
5264{
5265 int e = reparse_symlink(path, rp, bufsize);
5266 DWORD ret = 0;
5267
5268 if (!e || e == ERROR_MORE_DATA) {
5269 void *name;
5270 if (rp->ReparseTag == IO_REPARSE_TAG_SYMLINK) {
5271 name = ((char *)rp->SymbolicLinkReparseBuffer.PathBuffer +
5272 rp->SymbolicLinkReparseBuffer.PrintNameOffset);
5273 ret = rp->SymbolicLinkReparseBuffer.PrintNameLength;
5274 *len = ret / sizeof(WCHAR);
5275 }
5276 else if (rp->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT) {
5277 static const WCHAR volume[] = L"Volume{";
5278 enum {volume_prefix_len = rb_strlen_lit("\\??\\")};
5279 name = ((char *)rp->MountPointReparseBuffer.PathBuffer +
5280 rp->MountPointReparseBuffer.SubstituteNameOffset +
5281 volume_prefix_len * sizeof(WCHAR));
5282 ret = rp->MountPointReparseBuffer.SubstituteNameLength;
5283 *len = ret / sizeof(WCHAR);
5284 ret -= volume_prefix_len * sizeof(WCHAR);
5285 if (ret > sizeof(volume) - 1 * sizeof(WCHAR) &&
5286 memcmp(name, volume, sizeof(volume) - 1 * sizeof(WCHAR)) == 0)
5287 return -1;
5288 }
5289 else {
5290 return -1;
5291 }
5292 *result = name;
5293 if (e) {
5294 if ((char *)name + ret + sizeof(WCHAR) > (char *)rp + bufsize)
5295 return e;
5296 /* SubstituteName is not used */
5297 }
5298 ((WCHAR *)name)[ret/sizeof(WCHAR)] = L'\0';
5299 translate_wchar(name, L'\\', L'/');
5300 return 0;
5301 }
5302 else {
5303 return e;
5304 }
5305}
5306
5307/* License: Ruby's */
5308static ssize_t
5309w32_readlink(UINT cp, const char *path, char *buf, size_t bufsize)
5310{
5311 VALUE rp_buf, rp_buf_bigger = 0;
5312 DWORD len = MultiByteToWideChar(cp, 0, path, -1, NULL, 0);
5313 size_t size = rb_w32_reparse_buffer_size(bufsize);
5314 WCHAR *wname;
5315 WCHAR *wpath = ALLOCV(rp_buf, sizeof(WCHAR) * len + size);
5316 rb_w32_reparse_buffer_t *rp = (void *)(wpath + len);
5317 ssize_t ret;
5318 int e;
5319
5320 MultiByteToWideChar(cp, 0, path, -1, wpath, len);
5321 e = rb_w32_read_reparse_point(wpath, rp, size, &wname, &len);
5322 if (e == ERROR_MORE_DATA) {
5323 size = rb_w32_reparse_buffer_size(len + 1);
5324 rp = ALLOCV(rp_buf_bigger, size);
5325 e = rb_w32_read_reparse_point(wpath, rp, size, &wname, &len);
5326 }
5327 if (e) {
5328 ALLOCV_END(rp_buf);
5329 ALLOCV_END(rp_buf_bigger);
5330 errno = e == -1 ? EINVAL : map_errno(e);
5331 return -1;
5332 }
5333 len = lstrlenW(wname);
5334 ret = WideCharToMultiByte(cp, 0, wname, len, buf, bufsize, NULL, NULL);
5335 ALLOCV_END(rp_buf);
5336 ALLOCV_END(rp_buf_bigger);
5337 if (!ret) {
5338 ret = bufsize;
5339 }
5340 return ret;
5341}
5342
5343/* License: Ruby's */
5344ssize_t
5345rb_w32_ureadlink(const char *path, char *buf, size_t bufsize)
5346{
5347 return w32_readlink(CP_UTF8, path, buf, bufsize);
5348}
5349
5350/* License: Ruby's */
5351ssize_t
5352readlink(const char *path, char *buf, size_t bufsize)
5353{
5354 return w32_readlink(filecp(), path, buf, bufsize);
5355}
5356
5357#ifndef SYMBOLIC_LINK_FLAG_DIRECTORY
5358#define SYMBOLIC_LINK_FLAG_DIRECTORY (0x1)
5359#endif
5360#ifndef SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE
5361#define SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE (0x2)
5362#endif
5363
5364/* License: Ruby's */
5365static int
5366w32_symlink(UINT cp, const char *src, const char *link)
5367{
5368 int atts, len1, len2;
5369 VALUE buf;
5370 WCHAR *wsrc, *wlink;
5371 DWORD flag = 0;
5372 BOOLEAN ret;
5373 int e;
5374
5375 static DWORD create_flag = SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
5376
5377 if (!*link) {
5378 errno = ENOENT;
5379 return -1;
5380 }
5381 if (!*src) {
5382 errno = EINVAL;
5383 return -1;
5384 }
5385 len1 = MultiByteToWideChar(cp, 0, src, -1, NULL, 0);
5386 len2 = MultiByteToWideChar(cp, 0, link, -1, NULL, 0);
5387 wsrc = ALLOCV_N(WCHAR, buf, len1+len2);
5388 wlink = wsrc + len1;
5389 MultiByteToWideChar(cp, 0, src, -1, wsrc, len1);
5390 MultiByteToWideChar(cp, 0, link, -1, wlink, len2);
5391 translate_wchar(wsrc, L'/', L'\\');
5392 translate_wchar(wlink, L'/', L'\\');
5393
5394 /* A relative target is interpreted relative to the directory of the link,
5395 not the current directory. Resolve it there to decide whether to create
5396 a directory symlink; otherwise a relative target pointing at a directory
5397 would wrongly become a file symlink when the current directory differs
5398 from the link's directory. */
5399 {
5400 WCHAR *sep;
5401 int independent =
5402 (((wsrc[0] >= L'A' && wsrc[0] <= L'Z') ||
5403 (wsrc[0] >= L'a' && wsrc[0] <= L'z')) && wsrc[1] == L':') ||
5404 wsrc[0] == L'\\';
5405 if (!independent && (sep = wcsrchr(wlink, L'\\')) != NULL) {
5406 VALUE buf2;
5407 size_t dirlen = sep - wlink + 1;
5408 size_t srclen = wcslen(wsrc) + 1;
5409 WCHAR *fullsrc = ALLOCV_N(WCHAR, buf2, dirlen + srclen);
5410 MEMCPY(fullsrc, wlink, WCHAR, dirlen);
5411 MEMCPY(fullsrc + dirlen, wsrc, WCHAR, srclen);
5412 atts = GetFileAttributesW(fullsrc);
5413 ALLOCV_END(buf2);
5414 }
5415 else {
5416 atts = GetFileAttributesW(wsrc);
5417 }
5418 }
5419 if (atts != -1 && atts & FILE_ATTRIBUTE_DIRECTORY)
5420 flag = SYMBOLIC_LINK_FLAG_DIRECTORY;
5421 ret = CreateSymbolicLinkW(wlink, wsrc, flag |= create_flag);
5422 if (!ret &&
5423 (e = GetLastError()) == ERROR_INVALID_PARAMETER &&
5424 (flag & SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE)) {
5425 create_flag = 0;
5426 flag &= ~SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
5427 ret = CreateSymbolicLinkW(wlink, wsrc, flag);
5428 if (!ret) e = GetLastError();
5429 }
5430 ALLOCV_END(buf);
5431
5432 if (!ret) {
5433 errno = map_errno(e);
5434 return -1;
5435 }
5436 return 0;
5437}
5438
5439/* License: Ruby's */
5440int
5441rb_w32_usymlink(const char *src, const char *link)
5442{
5443 return w32_symlink(CP_UTF8, src, link);
5444}
5445
5446/* License: Ruby's */
5447int
5448symlink(const char *src, const char *link)
5449{
5450 return w32_symlink(filecp(), src, link);
5451}
5452
5453/* License: Ruby's */
5454rb_pid_t
5455wait(int *status)
5456{
5457 return waitpid(-1, status, 0);
5458}
5459
5460/* License: Ruby's */
5461static char *
5462w32_getenv(const char *name, UINT cp)
5463{
5464 WCHAR *wname, wbuf[256], *wval = wbuf;
5465 DWORD wlen, size = numberof(wbuf);
5466 char *uenvarea = NULL;
5467
5468 if (!*name) return NULL;
5469
5470 if (!NTLoginName) {
5471 /* initialized in init_env, uenvarea_key should have been
5472 * allocated before it */
5473 return getenv(name);
5474 }
5475
5476 if (!(wname = mbstr_to_wstr(cp, name, -1, NULL))) return NULL;
5477 for (;;) {
5478 /* 0 is also the length of an empty value, which leaves the last
5479 * error as it was */
5480 SetLastError(NO_ERROR);
5481 wlen = GetEnvironmentVariableW(wname, wval, size);
5482 if (wlen < size) break;
5483 if (wval != wbuf) free(wval);
5484 size = wlen;
5485 if (!(wval = malloc(size * sizeof(WCHAR)))) break;
5486 }
5487 if (wval && (wlen || GetLastError() == NO_ERROR))
5488 uenvarea = wstr_to_mbstr(cp, wval, wlen + 1, NULL);
5489 if (wval != wbuf) free(wval);
5490 free(wname);
5491
5492 free(FlsGetValue(uenvarea_key));
5493 FlsSetValue(uenvarea_key, uenvarea);
5494 return uenvarea;
5495}
5496
5497/* License: Ruby's */
5498char *
5499rb_w32_ugetenv(const char *name)
5500{
5501 return w32_getenv(name, CP_UTF8);
5502}
5503
5504/* License: Ruby's */
5505char *
5506rb_w32_getenv(const char *name)
5507{
5508 return w32_getenv(name, CP_ACP);
5509}
5510
5511/* License: Ruby's */
5512static DWORD
5513get_attr_vsn(const WCHAR *path, DWORD *atts, DWORD *vsn)
5514{
5515 BY_HANDLE_FILE_INFORMATION st = {0};
5516 DWORD e = 0;
5517 HANDLE h = open_special(path, 0, FILE_FLAG_OPEN_REPARSE_POINT);
5518
5519 if (h == INVALID_HANDLE_VALUE) {
5520 e = GetLastError();
5521 ASSUME(e);
5522 return e;
5523 }
5524 if (!GetFileInformationByHandle(h, &st)) {
5525 e = GetLastError();
5526 ASSUME(e);
5527 }
5528 else {
5529 *atts = st.dwFileAttributes;
5530 *vsn = st.dwVolumeSerialNumber;
5531 }
5532 CloseHandle(h);
5533 return e;
5534}
5535
5536/* License: Artistic or GPL */
5537static int
5538wrename(const WCHAR *oldpath, const WCHAR *newpath)
5539{
5540 int res = 0;
5541 DWORD oldatts = 0, newatts = (DWORD)-1;
5542 DWORD oldvsn = 0, newvsn = 0, e;
5543
5544 e = get_attr_vsn(oldpath, &oldatts, &oldvsn);
5545 if (e) {
5546 errno = map_errno(e);
5547 return -1;
5548 }
5549 if (oldatts & FILE_ATTRIBUTE_REPARSE_POINT) {
5550 HANDLE fh = open_special(oldpath, 0, 0);
5551 if (fh == INVALID_HANDLE_VALUE) {
5552 e = GetLastError();
5553 if (e == ERROR_CANT_RESOLVE_FILENAME) {
5554 errno = ELOOP;
5555 return -1;
5556 }
5557 }
5558 CloseHandle(fh);
5559 }
5560 get_attr_vsn(newpath, &newatts, &newvsn);
5561
5562 RUBY_CRITICAL {
5563 if (newatts != (DWORD)-1 && newatts & FILE_ATTRIBUTE_READONLY)
5564 SetFileAttributesW(newpath, newatts & ~ FILE_ATTRIBUTE_READONLY);
5565
5566 if (!MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED))
5567 res = -1;
5568
5569 if (res) {
5570 DWORD e = GetLastError();
5571 if ((e == ERROR_ACCESS_DENIED) && (oldatts & FILE_ATTRIBUTE_DIRECTORY) &&
5572 oldvsn != newvsn)
5573 errno = EXDEV;
5574 else
5575 errno = map_errno(e);
5576 }
5577 else
5578 SetFileAttributesW(newpath, oldatts);
5579 }
5580
5581 return res;
5582}
5583
5584/* License: Ruby's */
5585int
5586rb_w32_urename(const char *from, const char *to)
5587{
5588 WCHAR *wfrom;
5589 WCHAR *wto;
5590 int ret = -1;
5591
5592 if (!(wfrom = utf8_to_wstr(from, NULL)))
5593 return -1;
5594 if (!(wto = utf8_to_wstr(to, NULL))) {
5595 free(wfrom);
5596 return -1;
5597 }
5598 ret = wrename(wfrom, wto);
5599 free(wto);
5600 free(wfrom);
5601 return ret;
5602}
5603
5604/* License: Ruby's */
5605int
5606rb_w32_rename(const char *from, const char *to)
5607{
5608 WCHAR *wfrom;
5609 WCHAR *wto;
5610 int ret = -1;
5611
5612 if (!(wfrom = filecp_to_wstr(from, NULL)))
5613 return -1;
5614 if (!(wto = filecp_to_wstr(to, NULL))) {
5615 free(wfrom);
5616 return -1;
5617 }
5618 ret = wrename(wfrom, wto);
5619 free(wto);
5620 free(wfrom);
5621 return ret;
5622}
5623
5624/* License: Ruby's */
5625static int
5626isUNCRoot(const WCHAR *path)
5627{
5628 if (path[0] == L'\\' && path[1] == L'\\') {
5629 const WCHAR *p = path + 2;
5630 if (p[0] == L'?' && p[1] == L'\\') {
5631 p += 2;
5632 }
5633 for (; *p; p++) {
5634 if (*p == L'\\')
5635 break;
5636 }
5637 if (p[0] && p[1]) {
5638 for (p++; *p; p++) {
5639 if (*p == L'\\')
5640 break;
5641 }
5642 if (!p[0] || !p[1] || (p[1] == L'.' && !p[2]))
5643 return 1;
5644 }
5645 }
5646 return 0;
5647}
5648
5649#define COPY_STAT(src, dest, size_cast) do { \
5650 (dest).st_dev = (src).st_dev; \
5651 (dest).st_ino = (src).st_ino; \
5652 (dest).st_mode = (src).st_mode; \
5653 (dest).st_nlink = (src).st_nlink; \
5654 (dest).st_uid = (src).st_uid; \
5655 (dest).st_gid = (src).st_gid; \
5656 (dest).st_rdev = (src).st_rdev; \
5657 (dest).st_size = size_cast(src).st_size; \
5658 (dest).st_atime = (src).st_atime; \
5659 (dest).st_mtime = (src).st_mtime; \
5660 (dest).st_ctime = (src).st_ctime; \
5661 } while (0)
5662
5663static WCHAR *name_for_stat(WCHAR *buf, const WCHAR *path);
5664static DWORD stati128_handle(HANDLE h, struct stati128 *st);
5665
5666#undef fstat
5667/* License: Ruby's */
5668int
5669rb_w32_fstat(int fd, struct stat *st)
5670{
5671 BY_HANDLE_FILE_INFORMATION info;
5672 int ret = fstat(fd, st);
5673
5674 if (ret) return ret;
5675 if (GetEnvironmentVariableW(L"TZ", NULL, 0) == 0 && GetLastError() == ERROR_ENVVAR_NOT_FOUND) return ret;
5676 if (GetFileInformationByHandle((HANDLE)_get_osfhandle(fd), &info)) {
5677 st->st_atime = filetime_to_unixtime(&info.ftLastAccessTime);
5678 st->st_mtime = filetime_to_unixtime(&info.ftLastWriteTime);
5679 st->st_ctime = filetime_to_unixtime(&info.ftCreationTime);
5680 }
5681 return ret;
5682}
5683
5684/* License: Ruby's */
5685int
5686rb_w32_fstati128(int fd, struct stati128 *st)
5687{
5688 struct _stat64 tmp;
5689 int ret = _fstat64(fd, &tmp);
5690
5691 if (ret) return ret;
5692 COPY_STAT(tmp, *st, +);
5693 stati128_handle((HANDLE)_get_osfhandle(fd), st);
5694 return ret;
5695}
5696
5697#if !defined FILE_INVALID_FILE_ID && !defined __MINGW32__
5698typedef struct {
5699 BYTE Identifier[16];
5700} FILE_ID_128;
5701#endif
5702
5703#if !defined(_WIN32_WINNT_WIN8) || _WIN32_WINNT < 0x602
5704#define FileIdInfo 0x12
5705
5706typedef struct {
5707 unsigned LONG_LONG VolumeSerialNumber;
5708 FILE_ID_128 FileId;
5709} FILE_ID_INFO;
5710#endif
5711
5712static BOOL
5713get_ino(HANDLE h, FILE_ID_INFO *id)
5714{
5715 return GetFileInformationByHandleEx(h, FileIdInfo, id, sizeof(*id));
5716}
5717
5718/* License: Ruby's */
5719static DWORD
5720stati128_handle(HANDLE h, struct stati128 *st)
5721{
5722 BY_HANDLE_FILE_INFORMATION info;
5723 DWORD attr = (DWORD)-1;
5724
5725 if (GetFileInformationByHandle(h, &info)) {
5726 FILE_ID_INFO fii;
5727 st->st_size = ((__int64)info.nFileSizeHigh << 32) | info.nFileSizeLow;
5728 st->st_atime = filetime_split_ns(&info.ftLastAccessTime, &st->st_atimensec);
5729 st->st_mtime = filetime_split_ns(&info.ftLastWriteTime, &st->st_mtimensec);
5730 st->st_ctime = filetime_split_ns(&info.ftCreationTime, &st->st_ctimensec);
5731 st->st_nlink = info.nNumberOfLinks;
5732 attr = info.dwFileAttributes;
5733 if (get_ino(h, &fii)) {
5734 st->st_ino = *((unsigned __int64 *)&fii.FileId);
5735 st->st_inohigh = *((__int64 *)&fii.FileId + 1);
5736 }
5737 else {
5738 st->st_ino = ((__int64)info.nFileIndexHigh << 32) | info.nFileIndexLow;
5739 st->st_inohigh = 0;
5740 }
5741 }
5742 return attr;
5743}
5744
5745/* License: Ruby's */
5746static unsigned
5747fileattr_to_unixmode(DWORD attr, const WCHAR *path, unsigned mode)
5748{
5749 if (attr & FILE_ATTRIBUTE_READONLY) {
5750 mode |= S_IREAD;
5751 }
5752 else {
5753 mode |= S_IREAD | S_IWRITE | S_IWUSR;
5754 }
5755
5756 if (mode & S_IFMT) {
5757 /* format is already set */
5758 }
5759 else if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
5760 /* Only used by stat_by_find in the case the file can not be opened.
5761 * In this case we can't get more details. */
5762 }
5763 else if (attr & FILE_ATTRIBUTE_DIRECTORY) {
5764 mode |= S_IFDIR | S_IEXEC;
5765 }
5766 else {
5767 mode |= S_IFREG;
5768 }
5769
5770 if (path && (mode & S_IFREG)) {
5771 const WCHAR *end = path + lstrlenW(path);
5772 while (path < end) {
5773 end = CharPrevW(path, end);
5774 if (*end == L'.') {
5775 if ((_wcsicmp(end, L".bat") == 0) ||
5776 (_wcsicmp(end, L".cmd") == 0) ||
5777 (_wcsicmp(end, L".com") == 0) ||
5778 (_wcsicmp(end, L".exe") == 0)) {
5779 mode |= S_IEXEC;
5780 }
5781 break;
5782 }
5783 if (!iswalnum(*end)) break;
5784 }
5785 }
5786
5787 mode |= (mode & 0500) >> 3;
5788 mode |= (mode & 0500) >> 6;
5789
5790 return mode;
5791}
5792
5793/* License: Ruby's */
5794static int
5795check_valid_dir(const WCHAR *path)
5796{
5797 WIN32_FIND_DATAW fd;
5798 HANDLE fh;
5799 WCHAR full[PATH_MAX];
5800 WCHAR *p, *q;
5801
5802 /* GetFileAttributes() determines "..." as directory. */
5803 /* We recheck it by FindFirstFile(). */
5804 if (!(p = wcsstr(path, L"...")))
5805 return 0;
5806 q = p + wcsspn(p, L".");
5807 if ((p == path || wcschr(L":/\\", *(p - 1))) &&
5808 (!*q || wcschr(L":/\\", *q))) {
5809 errno = ENOENT;
5810 return -1;
5811 }
5812
5813 /* if the specified path is the root of a drive and the drive is empty, */
5814 /* FindFirstFile() returns INVALID_HANDLE_VALUE. */
5815 DWORD len = GetFullPathNameW(path, numberof(full), full, NULL);
5816 if (len >= numberof(full)) {
5817 WCHAR *fullpath = malloc(len * sizeof(WCHAR));
5818 if (!fullpath) return -1;
5819 len = GetFullPathNameW(path, len, fullpath, NULL);
5820 if (len == 3) MEMCPY(full, fullpath, WCHAR, len+1);
5821 free(fullpath);
5822 }
5823 if (!len) {
5824 errno = map_errno(GetLastError());
5825 return -1;
5826 }
5827 if (len == 3 && full[1] == L':' && GetDriveTypeW(full) != DRIVE_NO_ROOT_DIR)
5828 return 0; /* x:\ only */
5829
5830 fh = open_dir_handle(path, &fd);
5831 if (fh == INVALID_HANDLE_VALUE)
5832 return -1;
5833 FindClose(fh);
5834 return 0;
5835}
5836
5837/* License: Ruby's */
5838static int
5839stat_by_find(const WCHAR *path, struct stati128 *st)
5840{
5841 HANDLE h;
5842 WIN32_FIND_DATAW wfd;
5843
5844 /* Fall back to FindFirstFile for ERROR_SHARING_VIOLATION */
5845 h = FindFirstFileW(path, &wfd);
5846 if (h == INVALID_HANDLE_VALUE) {
5847 errno = map_errno(GetLastError());
5848 return -1;
5849 }
5850 FindClose(h);
5851 st->st_mode = fileattr_to_unixmode(wfd.dwFileAttributes, path, 0);
5852 st->st_atime = filetime_split_ns(&wfd.ftLastAccessTime, &st->st_atimensec);
5853 st->st_mtime = filetime_split_ns(&wfd.ftLastWriteTime, &st->st_mtimensec);
5854 st->st_ctime = filetime_split_ns(&wfd.ftCreationTime, &st->st_ctimensec);
5855 st->st_size = ((__int64)wfd.nFileSizeHigh << 32) | wfd.nFileSizeLow;
5856 st->st_nlink = 1;
5857 return 0;
5858}
5859
5860/* License: Ruby's */
5861static int
5862path_drive(const WCHAR *path)
5863{
5864 if (path[0] && path[1] == L':') {
5865 if (iswalpha(path[0])) return towupper(path[0]) - L'A';
5866 return (int)path[0];
5867 }
5868 return _getdrive() - 1;
5869}
5870
5871#if !defined(NTDDI_WIN11_ZN) || NTDDI_VERSION < NTDDI_WIN11_ZN
5872/* FileStatBasicByNameInfo in FILE_INFO_BY_NAME_CLASS and
5873 * FILE_STAT_BASIC_INFORMATION, in SDKs since Windows 11 24H2 */
5874#define FileStatBasicByNameInfo 3
5875
5876typedef struct {
5877 LARGE_INTEGER FileId;
5878 LARGE_INTEGER CreationTime;
5879 LARGE_INTEGER LastAccessTime;
5880 LARGE_INTEGER LastWriteTime;
5881 LARGE_INTEGER ChangeTime;
5882 LARGE_INTEGER AllocationSize;
5883 LARGE_INTEGER EndOfFile;
5884 DWORD FileAttributes;
5885 DWORD ReparseTag;
5886 DWORD NumberOfLinks;
5887 DWORD DeviceType;
5888 DWORD DeviceCharacteristics;
5889 DWORD Reserved;
5890 LARGE_INTEGER VolumeSerialNumber;
5891 FILE_ID_128 FileId128;
5893#endif
5894
5895#ifndef FILE_DEVICE_DISK
5896#define FILE_DEVICE_DISK 7
5897#endif
5898
5899typedef BOOL (WINAPI *get_file_information_by_name_func)
5900 (PCWSTR, int /* FILE_INFO_BY_NAME_CLASS */, PVOID, ULONG);
5901static get_file_information_by_name_func get_file_information_by_name =
5902 (get_file_information_by_name_func)-1;
5903
5904/* License: Ruby's */
5905static time_t
5906large_integer_to_unixtime(const LARGE_INTEGER *at, long *nsecp)
5907{
5908 time_t t = li_time_split_ns(at->QuadPart, nsecp);
5909 if (t < 0) return 0;
5910 return t;
5911}
5912
5913/* License: Ruby's */
5914static LONG_LONG
5915path_drive_serial(const WCHAR *path)
5916{
5917 static LONG_LONG serials[26];
5918 int drive;
5919
5920 if (path[0] && path[1] == L':') {
5921 if (!iswalpha(path[0])) return 0;
5922 drive = towupper(path[0]) - L'A';
5923 }
5924 else {
5925 drive = _getdrive() - 1;
5926 }
5927 if (drive < 0 || (int)numberof(serials) <= drive) return 0;
5928 if (!serials[drive]) {
5930 WCHAR root[] = L"_:\\";
5931 root[0] = L'A' + drive;
5932 if (get_file_information_by_name(root, FileStatBasicByNameInfo,
5933 &info, sizeof(info)))
5934 serials[drive] = info.VolumeSerialNumber.QuadPart;
5935 }
5936 return serials[drive];
5937}
5938
5939/* License: Ruby's */
5940static int
5941stat_by_name(const WCHAR *path, struct stati128 *st)
5942{
5943 /* Fill the stat result from a single metadata syscall, without
5944 * opening a file handle. Returns 1 to fall back to the
5945 * handle-based path. */
5947 unsigned __int64 ino;
5948 __int64 inohigh;
5949
5950 if (get_file_information_by_name == (get_file_information_by_name_func)-1) {
5951 /* Since Windows 11 24H2 */
5952 get_file_information_by_name = (get_file_information_by_name_func)
5953 get_proc_address("kernel32", "GetFileInformationByName", NULL);
5954 }
5955 if (!get_file_information_by_name) return 1;
5956 if (!get_file_information_by_name(path, FileStatBasicByNameInfo,
5957 &info, sizeof(info))) {
5958 DWORD e = GetLastError();
5959 switch (e) {
5960 case ERROR_FILE_NOT_FOUND:
5961 case ERROR_INVALID_NAME:
5962 case ERROR_PATH_NOT_FOUND:
5963 case ERROR_BAD_NETPATH:
5964 errno = map_errno(e);
5965 return -1;
5966 }
5967 return 1; /* devices, UNC paths, unusual errors */
5968 }
5969 if (info.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
5970 return 1; /* symlinks, junctions, AF_UNIX sockets */
5971 if (info.DeviceType != FILE_DEVICE_DISK)
5972 return 1;
5973 if (info.VolumeSerialNumber.QuadPart != path_drive_serial(path))
5974 return 1; /* reparse point in intermediate components */
5975 ino = *((unsigned __int64 *)&info.FileId128);
5976 inohigh = *((__int64 *)&info.FileId128 + 1);
5977 if (!ino && !inohigh)
5978 return 1; /* file ID is not available */
5979 if (info.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
5980 if (check_valid_dir(path)) return -1;
5981 }
5982 st->st_ino = ino;
5983 st->st_inohigh = inohigh;
5984 st->st_size = info.EndOfFile.QuadPart;
5985 st->st_atime = large_integer_to_unixtime(&info.LastAccessTime, &st->st_atimensec);
5986 st->st_mtime = large_integer_to_unixtime(&info.LastWriteTime, &st->st_mtimensec);
5987 st->st_ctime = large_integer_to_unixtime(&info.CreationTime, &st->st_ctimensec);
5988 st->st_nlink = info.NumberOfLinks;
5989 st->st_mode = fileattr_to_unixmode(info.FileAttributes, path, 0);
5990 st->st_dev = st->st_rdev = path_drive(path);
5991 return 0;
5992}
5993
5994/* License: Ruby's */
5995static int
5996winnt_stat(const WCHAR *path, struct stati128 *st, BOOL lstat)
5997{
5998 DWORD flags = lstat ? FILE_FLAG_OPEN_REPARSE_POINT : 0;
5999 HANDLE f;
6000 WCHAR *finalname = 0;
6001 int open_error;
6002
6003 memset(st, 0, sizeof(*st));
6004 switch (stat_by_name(path, st)) {
6005 case 0:
6006 return 0;
6007 case -1:
6008 return -1;
6009 }
6010 f = open_special(path, 0, flags);
6011 open_error = GetLastError();
6012 if (f == INVALID_HANDLE_VALUE && !lstat) {
6013 /* Support stat (not only lstat) of UNIXSocket */
6014 FILE_ATTRIBUTE_TAG_INFO attr_info;
6015 DWORD e;
6016
6017 f = open_special(path, 0, FILE_FLAG_OPEN_REPARSE_POINT);
6018 e = GetFileInformationByHandleEx(f, FileAttributeTagInfo,
6019 &attr_info, sizeof(attr_info));
6020 if (!e || attr_info.ReparseTag != IO_REPARSE_TAG_AF_UNIX) {
6021 CloseHandle(f);
6022 f = INVALID_HANDLE_VALUE;
6023 }
6024 }
6025 if (f != INVALID_HANDLE_VALUE) {
6026 DWORD attr = stati128_handle(f, st);
6027 unsigned mode = 0;
6028 switch (GetFileType(f)) {
6029 case FILE_TYPE_CHAR:
6030 mode = S_IFCHR;
6031 break;
6032 case FILE_TYPE_PIPE:
6033 mode = S_IFIFO;
6034 break;
6035 default:
6036 if (attr & FILE_ATTRIBUTE_DIRECTORY) {
6037 if (check_valid_dir(path)) return -1;
6038 }
6039 if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
6040 FILE_ATTRIBUTE_TAG_INFO attr_info;
6041 DWORD e;
6042
6043 e = GetFileInformationByHandleEx(f, FileAttributeTagInfo,
6044 &attr_info, sizeof(attr_info));
6045 if (e && attr_info.ReparseTag == IO_REPARSE_TAG_AF_UNIX) {
6046 st->st_size = 0;
6047 mode |= S_IFSOCK;
6048 }
6049 else if (rb_w32_reparse_symlink_p(path)) {
6050 /* TODO: size in which encoding? */
6051 st->st_size = 0;
6052 mode |= S_IFLNK | S_IEXEC;
6053 }
6054 else {
6055 mode |= S_IFDIR | S_IEXEC;
6056 }
6057 }
6058 }
6059 const DWORD len = get_handle_pathname(f, &finalname, 0);
6060 CloseHandle(f);
6061 st->st_mode = fileattr_to_unixmode(attr, path, mode);
6062 if (len) {
6063 path = finalname;
6064 if (wcsncmp(path, namespace_prefix, numberof(namespace_prefix)) == 0)
6065 path += numberof(namespace_prefix);
6066 }
6067 }
6068 else {
6069 switch (open_error) {
6070 case ERROR_FILE_NOT_FOUND:
6071 case ERROR_INVALID_NAME:
6072 case ERROR_PATH_NOT_FOUND:
6073 case ERROR_BAD_NETPATH:
6074 case ERROR_CANT_RESOLVE_FILENAME:
6075 errno = map_errno(open_error);
6076 return -1;
6077 }
6078
6079 if (stat_by_find(path, st)) return -1;
6080 }
6081
6082 st->st_dev = st->st_rdev = path_drive(path);
6083 if (finalname) free(finalname);
6084
6085 return 0;
6086}
6087
6088/* License: Ruby's */
6089int
6090rb_w32_stat(const char *path, struct stat *st)
6091{
6092 struct stati128 tmp;
6093
6094 if (w32_stati128(path, &tmp, filecp(), FALSE)) return -1;
6095 COPY_STAT(tmp, *st, (_off_t));
6096 return 0;
6097}
6098
6099/* License: Ruby's */
6100static int
6101wstati128(const WCHAR *path, struct stati128 *st, BOOL lstat)
6102{
6103 WCHAR *buf1;
6104 int ret, size;
6105 VALUE v;
6106
6107 if (!path || !st) {
6108 errno = EFAULT;
6109 return -1;
6110 }
6111 size = lstrlenW(path) + 2;
6112 buf1 = ALLOCV_N(WCHAR, v, size);
6113 if (!(path = name_for_stat(buf1, path)))
6114 return -1;
6115 ret = winnt_stat(path, st, lstat);
6116 if (v)
6117 ALLOCV_END(v);
6118
6119 return ret;
6120}
6121
6122/* License: Ruby's */
6123static WCHAR *
6124name_for_stat(WCHAR *buf1, const WCHAR *path)
6125{
6126 const WCHAR *p;
6127 WCHAR *s, *end;
6128 int len;
6129
6130 for (p = path, s = buf1; *p; p++, s++) {
6131 if (*p == L'/')
6132 *s = L'\\';
6133 else
6134 *s = *p;
6135 }
6136 *s = '\0';
6137 len = s - buf1;
6138 if (!len || L'\"' == *(--s)) {
6139 errno = ENOENT;
6140 return NULL;
6141 }
6142 end = buf1 + len - 1;
6143
6144 if (isUNCRoot(buf1)) {
6145 if (*end == L'.')
6146 *end = L'\0';
6147 else if (*end != L'\\')
6148 lstrcatW(buf1, L"\\");
6149 }
6150 else if (*end == L'\\' || (buf1 + 1 == end && *end == L':'))
6151 lstrcatW(buf1, L".");
6152
6153 return buf1;
6154}
6155
6156/* License: Ruby's */
6157int
6158rb_w32_ustati128(const char *path, struct stati128 *st)
6159{
6160 return w32_stati128(path, st, CP_UTF8, FALSE);
6161}
6162
6163/* License: Ruby's */
6164int
6165rb_w32_stati128(const char *path, struct stati128 *st)
6166{
6167 return w32_stati128(path, st, filecp(), FALSE);
6168}
6169
6170/* License: Ruby's */
6171static int
6172w32_stati128(const char *path, struct stati128 *st, UINT cp, BOOL lstat)
6173{
6174 WCHAR *wpath;
6175 int ret;
6176
6177 if (!(wpath = mbstr_to_wstr(cp, path, -1, NULL)))
6178 return -1;
6179 ret = wstati128(wpath, st, lstat);
6180 free(wpath);
6181 return ret;
6182}
6183
6184/* License: Ruby's */
6185int
6186rb_w32_ulstati128(const char *path, struct stati128 *st)
6187{
6188 return w32_stati128(path, st, CP_UTF8, TRUE);
6189}
6190
6191/* License: Ruby's */
6192int
6193rb_w32_lstati128(const char *path, struct stati128 *st)
6194{
6195 return w32_stati128(path, st, filecp(), TRUE);
6196}
6197
6198/* License: Ruby's */
6199rb_off_t
6200rb_w32_lseek(int fd, rb_off_t ofs, int whence)
6201{
6202 SOCKET sock = TO_SOCKET(fd);
6203 if (is_socket(sock) || is_pipe(sock)) {
6204 errno = ESPIPE;
6205 return -1;
6206 }
6207 return _lseeki64(fd, ofs, whence);
6208}
6209
6210/* License: Ruby's */
6211static int
6212w32_access(const char *path, int mode, UINT cp)
6213{
6214 struct stati128 stat;
6215 if (w32_stati128(path, &stat, cp, FALSE) != 0)
6216 return -1;
6217 mode <<= 6;
6218 if ((stat.st_mode & mode) != mode) {
6219 errno = EACCES;
6220 return -1;
6221 }
6222 return 0;
6223}
6224
6225/* License: Ruby's */
6226int
6227rb_w32_access(const char *path, int mode)
6228{
6229 return w32_access(path, mode, filecp());
6230}
6231
6232/* License: Ruby's */
6233int
6234rb_w32_uaccess(const char *path, int mode)
6235{
6236 return w32_access(path, mode, CP_UTF8);
6237}
6238
6239/* License: Ruby's */
6240static int
6241rb_chsize(HANDLE h, rb_off_t size)
6242{
6243 long upos, lpos, usize, lsize;
6244 int ret = -1;
6245 DWORD e;
6246
6247 if ((lpos = SetFilePointer(h, 0, (upos = 0, &upos), SEEK_CUR)) == -1L &&
6248 (e = GetLastError())) {
6249 errno = map_errno(e);
6250 return -1;
6251 }
6252 usize = (long)(size >> 32);
6253 lsize = (long)size;
6254 if (SetFilePointer(h, lsize, &usize, SEEK_SET) == (DWORD)-1L &&
6255 (e = GetLastError())) {
6256 errno = map_errno(e);
6257 }
6258 else if (!SetEndOfFile(h)) {
6259 errno = map_errno(GetLastError());
6260 }
6261 else {
6262 ret = 0;
6263 }
6264 SetFilePointer(h, lpos, &upos, SEEK_SET);
6265 return ret;
6266}
6267
6268/* License: Ruby's */
6269static int
6270w32_truncate(const char *path, rb_off_t length, UINT cp)
6271{
6272 HANDLE h;
6273 int ret;
6274 WCHAR *wpath;
6275
6276 if (!(wpath = mbstr_to_wstr(cp, path, -1, NULL)))
6277 return -1;
6278 h = CreateFileW(wpath, GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
6279 if (h == INVALID_HANDLE_VALUE) {
6280 errno = map_errno(GetLastError());
6281 free(wpath);
6282 return -1;
6283 }
6284 free(wpath);
6285 ret = rb_chsize(h, length);
6286 CloseHandle(h);
6287 return ret;
6288}
6289
6290/* License: Ruby's */
6291int
6292rb_w32_utruncate(const char *path, rb_off_t length)
6293{
6294 return w32_truncate(path, length, CP_UTF8);
6295}
6296
6297/* License: Ruby's */
6298int
6299rb_w32_truncate(const char *path, rb_off_t length)
6300{
6301 return w32_truncate(path, length, filecp());
6302}
6303
6304/* License: Ruby's */
6305int
6306rb_w32_ftruncate(int fd, rb_off_t length)
6307{
6308 HANDLE h;
6309
6310 h = (HANDLE)_get_osfhandle(fd);
6311 if (h == (HANDLE)-1) return -1;
6312 return rb_chsize(h, length);
6313}
6314
6315/* License: Ruby's */
6316static long
6317filetime_to_clock(FILETIME *ft)
6318{
6319 __int64 qw = ft->dwHighDateTime;
6320 qw <<= 32;
6321 qw |= ft->dwLowDateTime;
6322 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
6323 return (long) qw;
6324}
6325
6326/* License: Ruby's */
6327int
6328rb_w32_times(struct tms *tmbuf)
6329{
6330 FILETIME create, exit, kernel, user;
6331
6332 if (GetProcessTimes(GetCurrentProcess(),&create, &exit, &kernel, &user)) {
6333 tmbuf->tms_utime = filetime_to_clock(&user);
6334 tmbuf->tms_stime = filetime_to_clock(&kernel);
6335 tmbuf->tms_cutime = 0;
6336 tmbuf->tms_cstime = 0;
6337 }
6338 else {
6339 tmbuf->tms_utime = clock();
6340 tmbuf->tms_stime = 0;
6341 tmbuf->tms_cutime = 0;
6342 tmbuf->tms_cstime = 0;
6343 }
6344 return 0;
6345}
6346
6347
6348/* License: Ruby's */
6349#define yield_once() Sleep(0)
6350#define yield_until(condition) do yield_once(); while (!(condition))
6351
6352/* License: Ruby's */
6354 /* output field */
6355 void* stackaddr;
6356 int errnum;
6357
6358 /* input field */
6359 uintptr_t (*func)(uintptr_t self, int argc, uintptr_t* argv);
6360 uintptr_t self;
6361 int argc;
6362 uintptr_t* argv;
6363};
6364
6365/* License: Ruby's */
6366static DWORD WINAPI
6367call_asynchronous(PVOID argp)
6368{
6369 DWORD ret;
6370 struct asynchronous_arg_t *arg = argp;
6371 arg->stackaddr = &argp;
6372 ret = (DWORD)arg->func(arg->self, arg->argc, arg->argv);
6373 arg->errnum = errno;
6374 return ret;
6375}
6376
6377/* License: Ruby's */
6378uintptr_t
6379rb_w32_asynchronize(asynchronous_func_t func, uintptr_t self,
6380 int argc, uintptr_t* argv, uintptr_t intrval)
6381{
6382 DWORD val;
6383 BOOL interrupted = FALSE;
6384 HANDLE thr;
6385
6386 RUBY_CRITICAL {
6387 struct asynchronous_arg_t arg;
6388
6389 arg.stackaddr = NULL;
6390 arg.errnum = 0;
6391 arg.func = func;
6392 arg.self = self;
6393 arg.argc = argc;
6394 arg.argv = argv;
6395
6396 thr = CreateThread(NULL, 0, call_asynchronous, &arg, 0, &val);
6397
6398 if (thr) {
6399 yield_until(arg.stackaddr);
6400
6401 if (rb_w32_wait_events_blocking(&thr, 1, INFINITE) != WAIT_OBJECT_0) {
6402 interrupted = TRUE;
6403
6404 if (TerminateThread(thr, intrval)) {
6405 yield_once();
6406 }
6407 }
6408
6409 GetExitCodeThread(thr, &val);
6410 CloseHandle(thr);
6411
6412 if (interrupted) {
6413 /* must release stack of killed thread, why doesn't Windows? */
6414 MEMORY_BASIC_INFORMATION m;
6415
6416 memset(&m, 0, sizeof(m));
6417 if (!VirtualQuery(arg.stackaddr, &m, sizeof(m))) {
6418 Debug(fprintf(stderr, "couldn't get stack base:%p:%d\n",
6419 arg.stackaddr, GetLastError()));
6420 }
6421 else if (!VirtualFree(m.AllocationBase, 0, MEM_RELEASE)) {
6422 Debug(fprintf(stderr, "couldn't release stack:%p:%d\n",
6423 m.AllocationBase, GetLastError()));
6424 }
6425 errno = EINTR;
6426 }
6427 else {
6428 errno = arg.errnum;
6429 }
6430 }
6431 }
6432
6433 if (!thr) {
6434 rb_fatal("failed to launch waiter thread:%ld", GetLastError());
6435 }
6436
6437 return val;
6438}
6439
6440/* License: Ruby's */
6441char **
6442rb_w32_get_environ(void)
6443{
6444 WCHAR *envtop, *env;
6445 char **myenvtop, **myenv;
6446 int num;
6447
6448 /*
6449 * We avoid values started with `='. If you want to deal those values,
6450 * change this function, and some functions in hash.c which recognize
6451 * `=' as delimiter or rb_w32_getenv() and ruby_setenv().
6452 * CygWin deals these values by changing first `=' to '!'. But we don't
6453 * use such trick and follow cmd.exe's way that just doesn't show these
6454 * values.
6455 *
6456 * This function returns UTF-8 strings.
6457 */
6458 envtop = GetEnvironmentStringsW();
6459 for (env = envtop, num = 0; *env; env += lstrlenW(env) + 1)
6460 if (*env != '=') num++;
6461
6462 myenvtop = (char **)malloc(sizeof(char *) * (num + 1));
6463 for (env = envtop, myenv = myenvtop; *env; env += lstrlenW(env) + 1) {
6464 if (*env != '=') {
6465 if (!(*myenv = wstr_to_utf8(env, NULL))) {
6466 break;
6467 }
6468 myenv++;
6469 }
6470 }
6471 *myenv = NULL;
6472 FreeEnvironmentStringsW(envtop);
6473
6474 return myenvtop;
6475}
6476
6477/* License: Ruby's */
6478void
6479rb_w32_free_environ(char **env)
6480{
6481 char **t = env;
6482
6483 while (*t) free(*t++);
6484 free(env);
6485}
6486
6487/* License: Ruby's */
6488rb_pid_t
6489rb_w32_getpid(void)
6490{
6491 return GetCurrentProcessId();
6492}
6493
6494
6495/* License: Ruby's */
6496rb_pid_t
6497rb_w32_getppid(void)
6498{
6499 typedef long (WINAPI query_func)(HANDLE, int, void *, ULONG, ULONG *);
6500 static query_func *pNtQueryInformationProcess = (query_func *)-1;
6501 rb_pid_t ppid = 0;
6502
6503 if (pNtQueryInformationProcess == (query_func *)-1)
6504 pNtQueryInformationProcess = (query_func *)get_proc_address("ntdll.dll", "NtQueryInformationProcess", NULL);
6505 if (pNtQueryInformationProcess) {
6506 struct {
6507 long ExitStatus;
6508 void* PebBaseAddress;
6509 uintptr_t AffinityMask;
6510 uintptr_t BasePriority;
6511 uintptr_t UniqueProcessId;
6512 uintptr_t ParentProcessId;
6513 } pbi;
6514 ULONG len;
6515 long ret = pNtQueryInformationProcess(GetCurrentProcess(), 0, &pbi, sizeof(pbi), &len);
6516 if (!ret) {
6517 ppid = pbi.ParentProcessId;
6518 }
6519 }
6520
6521 return ppid;
6522}
6523
6524STATIC_ASSERT(std_handle, (STD_OUTPUT_HANDLE-STD_INPUT_HANDLE)==(STD_ERROR_HANDLE-STD_OUTPUT_HANDLE));
6525
6526/* License: Ruby's */
6527#define set_new_std_handle(newfd, handle) do { \
6528 if ((unsigned)(newfd) > 2) break; \
6529 SetStdHandle(STD_INPUT_HANDLE+(STD_OUTPUT_HANDLE-STD_INPUT_HANDLE)*(newfd), \
6530 (handle)); \
6531 } while (0)
6532#define set_new_std_fd(newfd) set_new_std_handle(newfd, (HANDLE)rb_w32_get_osfhandle(newfd))
6533
6534/* License: Ruby's */
6535int
6536rb_w32_dup2(int oldfd, int newfd)
6537{
6538 int ret;
6539
6540 if (oldfd == newfd) return newfd;
6541 ret = dup2(oldfd, newfd);
6542 if (ret < 0) return ret;
6543 set_new_std_fd(newfd);
6544 return newfd;
6545}
6546
6547/* License: Ruby's */
6548int
6549rb_w32_uopen(const char *file, int oflag, ...)
6550{
6551 WCHAR *wfile;
6552 int ret;
6553 int pmode;
6554
6555 va_list arg;
6556 va_start(arg, oflag);
6557 pmode = va_arg(arg, int);
6558 va_end(arg);
6559
6560 if (!(wfile = utf8_to_wstr(file, NULL)))
6561 return -1;
6562 ret = w32_wopen(wfile, oflag, pmode);
6563 free(wfile);
6564 return ret;
6565}
6566
6567/* License: Ruby's */
6568static int
6569check_if_wdir(const WCHAR *wfile)
6570{
6571 DWORD attr = GetFileAttributesW(wfile);
6572 if (attr == (DWORD)-1L ||
6573 !(attr & FILE_ATTRIBUTE_DIRECTORY) ||
6574 check_valid_dir(wfile)) {
6575 return FALSE;
6576 }
6577 errno = EISDIR;
6578 return TRUE;
6579}
6580
6581/* License: Ruby's */
6582int
6583rb_w32_open(const char *file, int oflag, ...)
6584{
6585 WCHAR *wfile;
6586 int ret;
6587 int pmode;
6588
6589 va_list arg;
6590 va_start(arg, oflag);
6591 pmode = va_arg(arg, int);
6592 va_end(arg);
6593
6594 if (!(wfile = filecp_to_wstr(file, NULL)))
6595 return -1;
6596 ret = w32_wopen(wfile, oflag, pmode);
6597 free(wfile);
6598 return ret;
6599}
6600
6601/* License: Ruby's */
6602int
6603rb_w32_wopen(const WCHAR *file, int oflag, ...)
6604{
6605 int pmode = 0;
6606
6607 if (oflag & O_CREAT) {
6608 va_list arg;
6609 va_start(arg, oflag);
6610 pmode = va_arg(arg, int);
6611 va_end(arg);
6612 }
6613
6614 return w32_wopen(file, oflag, pmode);
6615}
6616
6617static int
6618w32_wopen(const WCHAR *file, int oflag, int pmode)
6619{
6620 char flags = 0;
6621 int fd;
6622 DWORD access;
6623 DWORD create;
6624 DWORD attr = FILE_ATTRIBUTE_NORMAL;
6625 SECURITY_ATTRIBUTES sec;
6626 HANDLE h;
6627 int share_delete;
6628
6629 share_delete = oflag & O_SHARE_DELETE ? FILE_SHARE_DELETE : 0;
6630 oflag &= ~O_SHARE_DELETE;
6631 if ((oflag & O_TEXT) || !(oflag & O_BINARY)) {
6632 fd = _wopen(file, oflag, pmode);
6633 if (fd == -1) {
6634 switch (errno) {
6635 case EACCES:
6636 check_if_wdir(file);
6637 break;
6638 case EINVAL:
6639 errno = map_errno(GetLastError());
6640 break;
6641 }
6642 }
6643 return fd;
6644 }
6645
6646 sec.nLength = sizeof(sec);
6647 sec.lpSecurityDescriptor = NULL;
6648 if (oflag & O_NOINHERIT) {
6649 sec.bInheritHandle = FALSE;
6650 flags |= FNOINHERIT;
6651 }
6652 else {
6653 sec.bInheritHandle = TRUE;
6654 }
6655 oflag &= ~O_NOINHERIT;
6656
6657 /* always open with binary mode */
6658 oflag &= ~(O_BINARY | O_TEXT);
6659
6660 switch (oflag & (O_RDWR | O_RDONLY | O_WRONLY)) {
6661 case O_RDWR:
6662 access = GENERIC_READ | GENERIC_WRITE;
6663 break;
6664 case O_RDONLY:
6665 access = GENERIC_READ;
6666 break;
6667 case O_WRONLY:
6668 access = GENERIC_WRITE;
6669 break;
6670 default:
6671 errno = EINVAL;
6672 return -1;
6673 }
6674 oflag &= ~(O_RDWR | O_RDONLY | O_WRONLY);
6675
6676 switch (oflag & (O_CREAT | O_EXCL | O_TRUNC)) {
6677 case O_CREAT:
6678 create = OPEN_ALWAYS;
6679 break;
6680 case 0:
6681 case O_EXCL:
6682 create = OPEN_EXISTING;
6683 break;
6684 case O_CREAT | O_EXCL:
6685 case O_CREAT | O_EXCL | O_TRUNC:
6686 create = CREATE_NEW;
6687 break;
6688 case O_TRUNC:
6689 case O_TRUNC | O_EXCL:
6690 create = TRUNCATE_EXISTING;
6691 break;
6692 case O_CREAT | O_TRUNC:
6693 create = CREATE_ALWAYS;
6694 break;
6695 default:
6696 errno = EINVAL;
6697 return -1;
6698 }
6699 if (oflag & O_CREAT) {
6700 /* TODO: we need to check umask here, but it's not exported... */
6701 if (!(pmode & S_IWRITE))
6702 attr = FILE_ATTRIBUTE_READONLY;
6703 }
6704 oflag &= ~(O_CREAT | O_EXCL | O_TRUNC);
6705
6706 if (oflag & O_TEMPORARY) {
6707 attr |= FILE_FLAG_DELETE_ON_CLOSE;
6708 access |= DELETE;
6709 }
6710 oflag &= ~O_TEMPORARY;
6711
6712 if (oflag & _O_SHORT_LIVED)
6713 attr |= FILE_ATTRIBUTE_TEMPORARY;
6714 oflag &= ~_O_SHORT_LIVED;
6715
6716 switch (oflag & (O_SEQUENTIAL | O_RANDOM)) {
6717 case 0:
6718 break;
6719 case O_SEQUENTIAL:
6720 attr |= FILE_FLAG_SEQUENTIAL_SCAN;
6721 break;
6722 case O_RANDOM:
6723 attr |= FILE_FLAG_RANDOM_ACCESS;
6724 break;
6725 default:
6726 errno = EINVAL;
6727 return -1;
6728 }
6729 oflag &= ~(O_SEQUENTIAL | O_RANDOM);
6730
6731 if (oflag & ~O_APPEND) {
6732 errno = EINVAL;
6733 return -1;
6734 }
6735
6736 /* allocate a C Runtime file handle */
6737 RUBY_CRITICAL {
6738 h = CreateFile("NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
6739 fd = _open_osfhandle((intptr_t)h, 0);
6740 CloseHandle(h);
6741 }
6742 if (fd == -1) {
6743 errno = EMFILE;
6744 return -1;
6745 }
6746 RUBY_CRITICAL {
6747 rb_acrt_lowio_lock_fh(fd);
6748 _set_osfhnd(fd, (intptr_t)INVALID_HANDLE_VALUE);
6749 _set_osflags(fd, 0);
6750
6751 h = CreateFileW(file, access, FILE_SHARE_READ | FILE_SHARE_WRITE | share_delete, &sec, create, attr, NULL);
6752 if (h == INVALID_HANDLE_VALUE) {
6753 DWORD e = GetLastError();
6754 if (e != ERROR_ACCESS_DENIED || !check_if_wdir(file))
6755 errno = map_errno(e);
6756 rb_acrt_lowio_unlock_fh(fd);
6757 fd = -1;
6758 goto quit;
6759 }
6760
6761 switch (GetFileType(h)) {
6762 case FILE_TYPE_CHAR:
6763 flags |= FDEV;
6764 break;
6765 case FILE_TYPE_PIPE:
6766 flags |= FPIPE;
6767 break;
6768 case FILE_TYPE_UNKNOWN:
6769 errno = map_errno(GetLastError());
6770 CloseHandle(h);
6771 rb_acrt_lowio_unlock_fh(fd);
6772 fd = -1;
6773 goto quit;
6774 }
6775 if (!(flags & (FDEV | FPIPE)) && (oflag & O_APPEND))
6776 flags |= FAPPEND;
6777
6778 _set_osfhnd(fd, (intptr_t)h);
6779 _set_osflags(fd, flags | FOPEN);
6780
6781 rb_acrt_lowio_unlock_fh(fd);
6782 quit:
6783 ;
6784 }
6785
6786 return fd;
6787}
6788
6789/* License: Ruby's */
6790int
6791rb_w32_fclose(FILE *fp)
6792{
6793 int fd = fileno(fp);
6794 SOCKET sock = TO_SOCKET(fd);
6795 int save_errno = errno;
6796
6797 if (fflush(fp)) return -1;
6798 if (!is_socket(sock)) {
6799 UnlockFile((HANDLE)sock, 0, 0, LK_LEN, LK_LEN);
6800 return fclose(fp);
6801 }
6802 _set_osfhnd(fd, (SOCKET)INVALID_HANDLE_VALUE);
6803 fclose(fp);
6804 errno = save_errno;
6805 if (closesocket(sock) == SOCKET_ERROR) {
6806 errno = map_errno(WSAGetLastError());
6807 return -1;
6808 }
6809 return 0;
6810}
6811
6812/* License: Ruby's */
6813int
6814rb_w32_pipe(int fds[2])
6815{
6816 static long serial = 0;
6817 static const char prefix[] = "\\\\.\\pipe\\ruby";
6818 enum {
6819 width_of_prefix = (int)sizeof(prefix) - 1,
6820 width_of_pid = (int)sizeof(rb_pid_t) * 2,
6821 width_of_serial = (int)sizeof(serial) * 2,
6822 width_of_ids = width_of_pid + 1 + width_of_serial + 1
6823 };
6824 char name[sizeof(prefix) + width_of_ids];
6825 SECURITY_ATTRIBUTES sec;
6826 HANDLE hRead, hWrite, h;
6827 int fdRead, fdWrite;
6828 int ret;
6829
6830 memcpy(name, prefix, width_of_prefix);
6831 snprintf(name + width_of_prefix, width_of_ids, "%.*"PRI_PIDT_PREFIX"x-%.*lx",
6832 width_of_pid, rb_w32_getpid(), width_of_serial, (unsigned long)(InterlockedIncrement(&serial)-1));
6833
6834 sec.nLength = sizeof(sec);
6835 sec.lpSecurityDescriptor = NULL;
6836 sec.bInheritHandle = FALSE;
6837
6838 RUBY_CRITICAL {
6839 hRead = CreateNamedPipe(name, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
6840 0, 2, 65536, 65536, 0, &sec);
6841 }
6842 if (hRead == INVALID_HANDLE_VALUE) {
6843 DWORD err = GetLastError();
6844 if (err == ERROR_PIPE_BUSY)
6845 errno = EMFILE;
6846 else
6847 errno = map_errno(GetLastError());
6848 return -1;
6849 }
6850
6851 RUBY_CRITICAL {
6852 hWrite = CreateFile(name, GENERIC_READ | GENERIC_WRITE, 0, &sec,
6853 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
6854 }
6855 if (hWrite == INVALID_HANDLE_VALUE) {
6856 errno = map_errno(GetLastError());
6857 CloseHandle(hRead);
6858 return -1;
6859 }
6860
6861 RUBY_CRITICAL do {
6862 ret = 0;
6863 h = CreateFile("NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
6864 fdRead = _open_osfhandle((intptr_t)h, 0);
6865 CloseHandle(h);
6866 if (fdRead == -1) {
6867 errno = EMFILE;
6868 CloseHandle(hWrite);
6869 CloseHandle(hRead);
6870 ret = -1;
6871 break;
6872 }
6873
6874 rb_acrt_lowio_lock_fh(fdRead);
6875 _set_osfhnd(fdRead, (intptr_t)hRead);
6876 _set_osflags(fdRead, FOPEN | FPIPE | FNOINHERIT);
6877 rb_acrt_lowio_unlock_fh(fdRead);
6878 } while (0);
6879 if (ret)
6880 return ret;
6881
6882 RUBY_CRITICAL do {
6883 h = CreateFile("NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
6884 fdWrite = _open_osfhandle((intptr_t)h, 0);
6885 CloseHandle(h);
6886 if (fdWrite == -1) {
6887 errno = EMFILE;
6888 CloseHandle(hWrite);
6889 ret = -1;
6890 break;
6891 }
6892 rb_acrt_lowio_lock_fh(fdWrite);
6893 _set_osfhnd(fdWrite, (intptr_t)hWrite);
6894 _set_osflags(fdWrite, FOPEN | FPIPE | FNOINHERIT);
6895 rb_acrt_lowio_unlock_fh(fdWrite);
6896 } while (0);
6897 if (ret) {
6898 rb_w32_close(fdRead);
6899 return ret;
6900 }
6901
6902 fds[0] = fdRead;
6903 fds[1] = fdWrite;
6904
6905 return 0;
6906}
6907
6908/* License: Ruby's */
6909static int
6910console_emulator_p(void)
6911{
6912 const void *const func = WriteConsoleW;
6913 HMODULE k;
6914 MEMORY_BASIC_INFORMATION m;
6915
6916 memset(&m, 0, sizeof(m));
6917 if (!VirtualQuery(func, &m, sizeof(m))) {
6918 return FALSE;
6919 }
6920 k = GetModuleHandle("kernel32.dll");
6921 if (!k) return FALSE;
6922 return (HMODULE)m.AllocationBase != k;
6923}
6924
6925/* License: Ruby's */
6926static struct constat *
6927constat_handle(HANDLE h)
6928{
6929 st_data_t data;
6930 struct constat *p = NULL;
6931 thread_exclusive(conlist) {
6932 if (!conlist) {
6933 if (console_emulator_p()) {
6934 conlist = conlist_disabled;
6935 continue;
6936 }
6937 conlist = st_init_numtable();
6938 install_vm_exit_handler();
6939 }
6940 else if (conlist == conlist_disabled) {
6941 continue;
6942 }
6943 if (st_lookup(conlist, (st_data_t)h, &data)) {
6944 p = (struct constat *)data;
6945 }
6946 else {
6947 CONSOLE_SCREEN_BUFFER_INFO csbi;
6948 p = ALLOC(struct constat);
6949 p->vt100.state = constat_init;
6950 p->vt100.attr = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED;
6951 p->vt100.reverse = 0;
6952 p->vt100.saved.X = p->vt100.saved.Y = 0;
6953 if (GetConsoleScreenBufferInfo(h, &csbi)) {
6954 p->vt100.attr = csbi.wAttributes;
6955 }
6956 st_insert(conlist, (st_data_t)h, (st_data_t)p);
6957 }
6958 }
6959 return p;
6960}
6961
6962#define FOREGROUND_MASK (FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY)
6963#define BACKGROUND_MASK (BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_INTENSITY)
6964
6965#define constat_attr_color_reverse(attr) \
6966 ((attr) & ~(FOREGROUND_MASK | BACKGROUND_MASK)) | \
6967 (((attr) & FOREGROUND_MASK) << 4) | \
6968 (((attr) & BACKGROUND_MASK) >> 4)
6969
6970/* License: Ruby's */
6971static WORD
6972constat_attr(int count, const int *seq, WORD attr, WORD default_attr, int *reverse)
6973{
6974 int rev = *reverse;
6975 WORD bold;
6976
6977 if (!count) return attr;
6978 if (rev) attr = constat_attr_color_reverse(attr);
6979 bold = attr & FOREGROUND_INTENSITY;
6980 attr &= ~(FOREGROUND_INTENSITY | BACKGROUND_INTENSITY);
6981
6982 while (count-- > 0) {
6983 switch (*seq++) {
6984 case 0:
6985 attr = default_attr;
6986 rev = 0;
6987 bold = 0;
6988 break;
6989 case 1:
6990 bold = FOREGROUND_INTENSITY;
6991 break;
6992 case 22:
6993 bold = 0;
6994 break;
6995 case 4:
6996#ifndef COMMON_LVB_UNDERSCORE
6997#define COMMON_LVB_UNDERSCORE 0x8000
6998#endif
6999 attr |= COMMON_LVB_UNDERSCORE;
7000 break;
7001 case 24:
7002 attr &= ~COMMON_LVB_UNDERSCORE;
7003 break;
7004 case 7:
7005 rev = 1;
7006 break;
7007 case 27:
7008 rev = 0;
7009 break;
7010
7011 case 30:
7012 attr &= ~(FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED);
7013 break;
7014 case 31:
7015 attr = (attr & ~(FOREGROUND_BLUE | FOREGROUND_GREEN)) | FOREGROUND_RED;
7016 break;
7017 case 32:
7018 attr = (attr & ~(FOREGROUND_BLUE | FOREGROUND_RED)) | FOREGROUND_GREEN;
7019 break;
7020 case 33:
7021 attr = (attr & ~FOREGROUND_BLUE) | FOREGROUND_GREEN | FOREGROUND_RED;
7022 break;
7023 case 34:
7024 attr = (attr & ~(FOREGROUND_GREEN | FOREGROUND_RED)) | FOREGROUND_BLUE;
7025 break;
7026 case 35:
7027 attr = (attr & ~FOREGROUND_GREEN) | FOREGROUND_BLUE | FOREGROUND_RED;
7028 break;
7029 case 36:
7030 attr = (attr & ~FOREGROUND_RED) | FOREGROUND_BLUE | FOREGROUND_GREEN;
7031 break;
7032 case 37:
7033 attr |= FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED;
7034 break;
7035 case 38: /* 256-color or true color; N/A on old Command Prompt */
7036 break;
7037 case 39:
7038 attr = (attr & ~FOREGROUND_MASK) | (default_attr & FOREGROUND_MASK);
7039 break;
7040
7041 case 40:
7042 attr &= ~(BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED);
7043 break;
7044 case 41:
7045 attr = (attr & ~(BACKGROUND_BLUE | BACKGROUND_GREEN)) | BACKGROUND_RED;
7046 break;
7047 case 42:
7048 attr = (attr & ~(BACKGROUND_BLUE | BACKGROUND_RED)) | BACKGROUND_GREEN;
7049 break;
7050 case 43:
7051 attr = (attr & ~BACKGROUND_BLUE) | BACKGROUND_GREEN | BACKGROUND_RED;
7052 break;
7053 case 44:
7054 attr = (attr & ~(BACKGROUND_GREEN | BACKGROUND_RED)) | BACKGROUND_BLUE;
7055 break;
7056 case 45:
7057 attr = (attr & ~BACKGROUND_GREEN) | BACKGROUND_BLUE | BACKGROUND_RED;
7058 break;
7059 case 46:
7060 attr = (attr & ~BACKGROUND_RED) | BACKGROUND_BLUE | BACKGROUND_GREEN;
7061 break;
7062 case 47:
7063 attr |= BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED;
7064 break;
7065 case 48: /* 256-color or true color; N/A on old Command Prompt */
7066 break;
7067 case 49:
7068 attr = (attr & ~BACKGROUND_MASK) | (default_attr & BACKGROUND_MASK);
7069 break;
7070 }
7071 }
7072 attr |= bold;
7073 if (rev) attr = constat_attr_color_reverse(attr);
7074 *reverse = rev;
7075 return attr;
7076}
7077
7078/* License: Ruby's */
7079static void
7080constat_clear(HANDLE handle, WORD attr, DWORD len, COORD pos)
7081{
7082 DWORD written;
7083
7084 FillConsoleOutputAttribute(handle, attr, len, pos, &written);
7085 FillConsoleOutputCharacterW(handle, L' ', len, pos, &written);
7086}
7087
7088/* License: Ruby's */
7089static void
7090constat_apply(HANDLE handle, struct constat *s, WCHAR w)
7091{
7092 CONSOLE_SCREEN_BUFFER_INFO csbi;
7093 const int *seq = s->vt100.seq;
7094 int count = s->vt100.state;
7095 int arg0, arg1 = 1;
7096 COORD pos;
7097
7098 if (!GetConsoleScreenBufferInfo(handle, &csbi)) return;
7099 arg0 = (count > 0 && seq[0] > 0);
7100 if (arg0) arg1 = seq[0];
7101 switch (w) {
7102 case L'm':
7103 SetConsoleTextAttribute(handle, constat_attr(count, seq, csbi.wAttributes, s->vt100.attr, &s->vt100.reverse));
7104 break;
7105 case L'F':
7106 csbi.dwCursorPosition.X = 0;
7107 case L'A':
7108 csbi.dwCursorPosition.Y -= arg1;
7109 if (csbi.dwCursorPosition.Y < csbi.srWindow.Top)
7110 csbi.dwCursorPosition.Y = csbi.srWindow.Top;
7111 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
7112 break;
7113 case L'E':
7114 csbi.dwCursorPosition.X = 0;
7115 case L'B':
7116 case L'e':
7117 csbi.dwCursorPosition.Y += arg1;
7118 if (csbi.dwCursorPosition.Y > csbi.srWindow.Bottom)
7119 csbi.dwCursorPosition.Y = csbi.srWindow.Bottom;
7120 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
7121 break;
7122 case L'C':
7123 csbi.dwCursorPosition.X += arg1;
7124 if (csbi.dwCursorPosition.X >= csbi.srWindow.Right)
7125 csbi.dwCursorPosition.X = csbi.srWindow.Right;
7126 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
7127 break;
7128 case L'D':
7129 csbi.dwCursorPosition.X -= arg1;
7130 if (csbi.dwCursorPosition.X < csbi.srWindow.Left)
7131 csbi.dwCursorPosition.X = csbi.srWindow.Left;
7132 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
7133 break;
7134 case L'G':
7135 case L'`':
7136 arg1 += csbi.srWindow.Left;
7137 if (arg1 > csbi.srWindow.Right)
7138 arg1 = csbi.srWindow.Right;
7139 csbi.dwCursorPosition.X = arg1;
7140 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
7141 break;
7142 case L'd':
7143 arg1 += csbi.srWindow.Top;
7144 if (arg1 > csbi.srWindow.Bottom)
7145 arg1 = csbi.srWindow.Bottom;
7146 csbi.dwCursorPosition.Y = arg1;
7147 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
7148 break;
7149 case L'H':
7150 case L'f':
7151 pos.Y = arg1 + csbi.srWindow.Top - 1;
7152 if (pos.Y > csbi.srWindow.Bottom) pos.Y = csbi.srWindow.Bottom;
7153 if (count < 2 || (arg1 = seq[1]) <= 0) arg1 = 1;
7154 pos.X = arg1 + csbi.srWindow.Left - 1;
7155 if (pos.X > csbi.srWindow.Right) pos.X = csbi.srWindow.Right;
7156 SetConsoleCursorPosition(handle, pos);
7157 break;
7158 case L'J':
7159 switch (arg0 ? arg1 : 0) {
7160 case 0: /* erase after cursor */
7161 constat_clear(handle, csbi.wAttributes,
7162 (csbi.dwSize.X * (csbi.srWindow.Bottom - csbi.dwCursorPosition.Y + 1)
7163 - csbi.dwCursorPosition.X),
7164 csbi.dwCursorPosition);
7165 break;
7166 case 1: /* erase before *and* cursor */
7167 pos.X = 0;
7168 pos.Y = csbi.srWindow.Top;
7169 constat_clear(handle, csbi.wAttributes,
7170 (csbi.dwSize.X * (csbi.dwCursorPosition.Y - csbi.srWindow.Top)
7171 + csbi.dwCursorPosition.X + 1),
7172 pos);
7173 break;
7174 case 2: /* erase entire screen */
7175 pos.X = 0;
7176 pos.Y = csbi.srWindow.Top;
7177 constat_clear(handle, csbi.wAttributes,
7178 (csbi.dwSize.X * (csbi.srWindow.Bottom - csbi.srWindow.Top + 1)),
7179 pos);
7180 break;
7181 case 3: /* erase entire screen */
7182 pos.X = 0;
7183 pos.Y = 0;
7184 constat_clear(handle, csbi.wAttributes,
7185 (csbi.dwSize.X * csbi.dwSize.Y),
7186 pos);
7187 break;
7188 }
7189 break;
7190 case L'K':
7191 switch (arg0 ? arg1 : 0) {
7192 case 0: /* erase after cursor */
7193 constat_clear(handle, csbi.wAttributes,
7194 (csbi.dwSize.X - csbi.dwCursorPosition.X),
7195 csbi.dwCursorPosition);
7196 break;
7197 case 1: /* erase before *and* cursor */
7198 pos.X = 0;
7199 pos.Y = csbi.dwCursorPosition.Y;
7200 constat_clear(handle, csbi.wAttributes,
7201 csbi.dwCursorPosition.X + 1, pos);
7202 break;
7203 case 2: /* erase entire line */
7204 pos.X = 0;
7205 pos.Y = csbi.dwCursorPosition.Y;
7206 constat_clear(handle, csbi.wAttributes,
7207 csbi.dwSize.X, pos);
7208 break;
7209 }
7210 break;
7211 case L's':
7212 s->vt100.saved = csbi.dwCursorPosition;
7213 break;
7214 case L'u':
7215 SetConsoleCursorPosition(handle, s->vt100.saved);
7216 break;
7217 case L'h':
7218 if (count >= 2 && seq[0] == -1 && seq[1] == 25) {
7219 CONSOLE_CURSOR_INFO cci;
7220 GetConsoleCursorInfo(handle, &cci);
7221 cci.bVisible = TRUE;
7222 SetConsoleCursorInfo(handle, &cci);
7223 }
7224 break;
7225 case L'l':
7226 if (count >= 2 && seq[0] == -1 && seq[1] == 25) {
7227 CONSOLE_CURSOR_INFO cci;
7228 GetConsoleCursorInfo(handle, &cci);
7229 cci.bVisible = FALSE;
7230 SetConsoleCursorInfo(handle, &cci);
7231 }
7232 break;
7233 }
7234}
7235
7236/* License: Ruby's */
7237static long
7238constat_parse(HANDLE h, struct constat *s, const WCHAR **ptrp, long *lenp)
7239{
7240 const WCHAR *ptr = *ptrp;
7241 long rest, len = *lenp;
7242 while (len-- > 0) {
7243 WCHAR wc = *ptr++;
7244 if (wc == 0x1b) {
7245 rest = *lenp - len - 1;
7246 if (s->vt100.state == constat_esc) {
7247 rest++; /* reuse this ESC */
7248 }
7249 s->vt100.state = constat_init;
7250 if (len > 0 && *ptr != L'[') continue;
7251 s->vt100.state = constat_esc;
7252 }
7253 else if (s->vt100.state == constat_esc) {
7254 if (wc != L'[') {
7255 /* TODO: supply dropped ESC at beginning */
7256 s->vt100.state = constat_init;
7257 continue;
7258 }
7259 rest = *lenp - len - 1;
7260 if (rest > 0) --rest;
7261 s->vt100.state = constat_seq;
7262 s->vt100.seq[0] = 0;
7263 }
7264 else if (s->vt100.state >= constat_seq) {
7265 if (wc >= L'0' && wc <= L'9') {
7266 if (s->vt100.state < (int)numberof(s->vt100.seq)) {
7267 int *seq = &s->vt100.seq[s->vt100.state];
7268 *seq = (*seq * 10) + (wc - L'0');
7269 }
7270 }
7271 else if (s->vt100.state == constat_seq && s->vt100.seq[0] == 0 && wc == L'?') {
7272 s->vt100.seq[s->vt100.state++] = -1;
7273 }
7274 else {
7275 do {
7276 if (++s->vt100.state < (int)numberof(s->vt100.seq)) {
7277 s->vt100.seq[s->vt100.state] = 0;
7278 }
7279 else {
7280 s->vt100.state = (int)numberof(s->vt100.seq);
7281 }
7282 } while (0);
7283 if (wc != L';') {
7284 constat_apply(h, s, wc);
7285 s->vt100.state = constat_init;
7286 }
7287 }
7288 rest = 0;
7289 }
7290 else {
7291 continue;
7292 }
7293 *ptrp = ptr;
7294 *lenp = len;
7295 return rest;
7296 }
7297 len = *lenp;
7298 *ptrp = ptr;
7299 *lenp = 0;
7300 return len;
7301}
7302
7303
7304/* License: Ruby's */
7305int
7306rb_w32_close(int fd)
7307{
7308 SOCKET sock = TO_SOCKET(fd);
7309 int save_errno = errno;
7310
7311 if (!is_socket(sock)) {
7312 UnlockFile((HANDLE)sock, 0, 0, LK_LEN, LK_LEN);
7313 constat_delete((HANDLE)sock);
7314 return _close(fd);
7315 }
7316 _set_osfhnd(fd, (SOCKET)INVALID_HANDLE_VALUE);
7317 socklist_delete(&sock, NULL);
7318 _close(fd);
7319 errno = save_errno;
7320 if (closesocket(sock) == SOCKET_ERROR) {
7321 errno = map_errno(WSAGetLastError());
7322 return -1;
7323 }
7324 return 0;
7325}
7326
7327#ifndef INVALID_SET_FILE_POINTER
7328#define INVALID_SET_FILE_POINTER ((DWORD)-1)
7329#endif
7330
7331static int
7332setup_overlapped(OVERLAPPED *ol, int fd, int iswrite, rb_off_t *_offset)
7333{
7334 memset(ol, 0, sizeof(*ol));
7335
7336 // On mode:a, it can write only FILE_END.
7337 // On mode:a+, though it can write only FILE_END,
7338 // it can read from everywhere.
7339 DWORD seek_method = ((_osfile(fd) & FAPPEND) && iswrite) ? FILE_END : FILE_CURRENT;
7340
7341 if (_offset) {
7342 // Explicit offset was provided (pread/pwrite) - use it:
7343 uint64_t offset = *_offset;
7344 ol->Offset = (uint32_t)(offset & 0xFFFFFFFFLL);
7345 ol->OffsetHigh = (uint32_t)((offset & 0xFFFFFFFF00000000LL) >> 32);
7346
7347 // Update _offset with the current offset:
7348 LARGE_INTEGER seek_offset = {0}, current_offset = {0};
7349 if (!SetFilePointerEx((HANDLE)_osfhnd(fd), seek_offset, &current_offset, seek_method)) {
7350 DWORD last_error = GetLastError();
7351 if (last_error != NO_ERROR) {
7352 errno = map_errno(last_error);
7353 return -1;
7354 }
7355 }
7356
7357 // As we need to restore the current offset later, we save it here:
7358 *_offset = current_offset.QuadPart;
7359 }
7360 else if (!(_osfile(fd) & (FDEV | FPIPE))) {
7361 LONG high = 0;
7362 DWORD low = SetFilePointer((HANDLE)_osfhnd(fd), 0, &high, seek_method);
7363
7364 if (low == INVALID_SET_FILE_POINTER) {
7365 DWORD err = GetLastError();
7366 if (err != NO_ERROR) {
7367 errno = map_errno(err);
7368 return -1;
7369 }
7370 }
7371
7372 ol->Offset = low;
7373 ol->OffsetHigh = high;
7374 }
7375
7376 ol->hEvent = CreateEvent(NULL, TRUE, TRUE, NULL);
7377 if (!ol->hEvent) {
7378 errno = map_errno(GetLastError());
7379 return -1;
7380 }
7381 return 0;
7382}
7383
7384static void
7385finish_overlapped(OVERLAPPED *ol, int fd, DWORD size, rb_off_t *_offset)
7386{
7387 CloseHandle(ol->hEvent);
7388
7389 if (_offset) {
7390 // If we were doing a `pread`/`pwrite`, we need to restore the current that was saved in setup_overlapped:
7391 DWORD seek_method = (_osfile(fd) & FAPPEND) ? FILE_END : FILE_BEGIN;
7392
7393 LARGE_INTEGER seek_offset = {0};
7394 if (seek_method == FILE_BEGIN) {
7395 seek_offset.QuadPart = *_offset;
7396 }
7397
7398 SetFilePointerEx((HANDLE)_osfhnd(fd), seek_offset, NULL, seek_method);
7399 }
7400 else if (!(_osfile(fd) & (FDEV | FPIPE))) {
7401 LONG high = ol->OffsetHigh;
7402 DWORD low = ol->Offset + size;
7403 if (low < ol->Offset)
7404 ++high;
7405 SetFilePointer((HANDLE)_osfhnd(fd), low, &high, FILE_BEGIN);
7406 }
7407}
7408
7409#undef read
7410/* License: Ruby's */
7411static ssize_t
7412rb_w32_read_internal(int fd, void *buf, size_t size, rb_off_t *offset)
7413{
7414 SOCKET sock = TO_SOCKET(fd);
7415 DWORD read;
7416 DWORD wait;
7417 DWORD err;
7418 size_t len;
7419 size_t ret;
7420 OVERLAPPED ol;
7421
7422 /* recv, _read and ReadFile take 32-bit lengths; a short read is fine */
7423 if (size > INT_MAX) size = INT_MAX;
7424
7425 if (is_socket(sock))
7426 return rb_w32_recv(fd, buf, size, 0);
7427
7428 // validate fd by using _get_osfhandle() because we cannot access _nhandle
7429 if (_get_osfhandle(fd) == -1) {
7430 return -1;
7431 }
7432
7433 if (!offset && _osfile(fd) & FTEXT) {
7434 return _read(fd, buf, size);
7435 }
7436
7437 rb_acrt_lowio_lock_fh(fd);
7438
7439 if (!size || _osfile(fd) & FEOFLAG) {
7440 _set_osflags(fd, _osfile(fd) & ~FEOFLAG);
7441 rb_acrt_lowio_unlock_fh(fd);
7442 return 0;
7443 }
7444
7445 ret = 0;
7446 retry:
7447 len = size;
7448 size -= len;
7449
7450 if (setup_overlapped(&ol, fd, FALSE, offset)) {
7451 rb_acrt_lowio_unlock_fh(fd);
7452 return -1;
7453 }
7454
7455 if (!ReadFile((HANDLE)_osfhnd(fd), buf, len, &read, &ol)) {
7456 err = GetLastError();
7457 if (err == ERROR_NO_DATA && (_osfile(fd) & FPIPE)) {
7458 DWORD state;
7459 CloseHandle(ol.hEvent);
7460 if (GetNamedPipeHandleState((HANDLE)_osfhnd(fd), &state, NULL, NULL, NULL, NULL, 0) && (state & PIPE_NOWAIT)) {
7461 errno = EWOULDBLOCK;
7462 }
7463 else {
7464 errno = map_errno(err);
7465 }
7466 rb_acrt_lowio_unlock_fh(fd);
7467 return -1;
7468 }
7469 else if (err != ERROR_IO_PENDING) {
7470 CloseHandle(ol.hEvent);
7471 if (err == ERROR_ACCESS_DENIED)
7472 errno = EBADF;
7473 else if (err == ERROR_BROKEN_PIPE || err == ERROR_HANDLE_EOF) {
7474 rb_acrt_lowio_unlock_fh(fd);
7475 return 0;
7476 }
7477 else
7478 errno = map_errno(err);
7479
7480 rb_acrt_lowio_unlock_fh(fd);
7481 return -1;
7482 }
7483
7484 wait = rb_w32_wait_events_blocking(&ol.hEvent, 1, INFINITE);
7485 if (wait != WAIT_OBJECT_0) {
7486 if (wait == WAIT_OBJECT_0 + 1)
7487 errno = EINTR;
7488 else
7489 errno = map_errno(GetLastError());
7490 CancelIo((HANDLE)_osfhnd(fd));
7491 /* the read may have completed before the cancel, and the kernel
7492 * writes ol and buf until it ends either way */
7493 GetOverlappedResult((HANDLE)_osfhnd(fd), &ol, &read, TRUE);
7494 if (!read) {
7495 CloseHandle(ol.hEvent);
7496 rb_acrt_lowio_unlock_fh(fd);
7497 return -1;
7498 }
7499 }
7500 else if (!GetOverlappedResult((HANDLE)_osfhnd(fd), &ol, &read, TRUE) &&
7501 (err = GetLastError()) != ERROR_HANDLE_EOF) {
7502 int ret = 0;
7503 if (err != ERROR_BROKEN_PIPE) {
7504 errno = map_errno(err);
7505 ret = -1;
7506 }
7507 CloseHandle(ol.hEvent);
7508 CancelIo((HANDLE)_osfhnd(fd));
7509 rb_acrt_lowio_unlock_fh(fd);
7510 return ret;
7511 }
7512 }
7513 else {
7514 err = GetLastError();
7515 errno = map_errno(err);
7516 }
7517
7518 finish_overlapped(&ol, fd, read, offset);
7519
7520 ret += read;
7521 if (read >= len) {
7522 buf = (char *)buf + read;
7523 if (err != ERROR_OPERATION_ABORTED && size > 0)
7524 goto retry;
7525 }
7526 if (read == 0)
7527 _set_osflags(fd, _osfile(fd) | FEOFLAG);
7528
7529
7530 rb_acrt_lowio_unlock_fh(fd);
7531
7532 return ret;
7533}
7534
7535#undef write
7536/* License: Ruby's */
7537static ssize_t
7538rb_w32_write_internal(int fd, const void *buf, size_t size, rb_off_t *offset)
7539{
7540 SOCKET sock = TO_SOCKET(fd);
7541 DWORD written;
7542 DWORD wait;
7543 DWORD err;
7544 size_t len;
7545 size_t ret;
7546 OVERLAPPED ol;
7547
7548 /* send, _write and WriteFile take 32-bit lengths, and a short write is fine */
7549 if (size > INT_MAX) size = INT_MAX;
7550
7551 if (is_socket(sock))
7552 return rb_w32_send(fd, buf, size, 0);
7553
7554 // validate fd by using _get_osfhandle() because we cannot access _nhandle
7555 if (_get_osfhandle(fd) == -1) {
7556 return -1;
7557 }
7558
7559 // If an offset is given, we can't use `_write`.
7560 if (!offset && (_osfile(fd) & FTEXT) &&
7561 (!(_osfile(fd) & FPIPE) || fd == fileno(stdout) || fd == fileno(stderr))) {
7562 ssize_t w = _write(fd, buf, size);
7563 if (w == (ssize_t)-1 && errno == EINVAL) {
7564 errno = map_errno(GetLastError());
7565 }
7566 return w;
7567 }
7568
7569 rb_acrt_lowio_lock_fh(fd);
7570
7571 if (!size || _osfile(fd) & FEOFLAG) {
7572 rb_acrt_lowio_unlock_fh(fd);
7573 return 0;
7574 }
7575
7576 ret = 0;
7577 retry:
7578 len = size;
7579 size -= len;
7580 retry2:
7581
7582 // Provide the requested offset.
7583 if (setup_overlapped(&ol, fd, TRUE, offset)) {
7584 rb_acrt_lowio_unlock_fh(fd);
7585 return -1;
7586 }
7587
7588 if (!WriteFile((HANDLE)_osfhnd(fd), buf, len, &written, &ol)) {
7589 err = GetLastError();
7590 if (err != ERROR_IO_PENDING) {
7591 CloseHandle(ol.hEvent);
7592 if (err == ERROR_ACCESS_DENIED)
7593 errno = EBADF;
7594 else
7595 errno = map_errno(err);
7596
7597 rb_acrt_lowio_unlock_fh(fd);
7598 return -1;
7599 }
7600
7601 wait = rb_w32_wait_events_blocking(&ol.hEvent, 1, INFINITE);
7602 if (wait != WAIT_OBJECT_0) {
7603 if (wait == WAIT_OBJECT_0 + 1)
7604 errno = EINTR;
7605 else
7606 errno = map_errno(GetLastError());
7607 CancelIo((HANDLE)_osfhnd(fd));
7608 GetOverlappedResult((HANDLE)_osfhnd(fd), &ol, &written, TRUE);
7609 if (!written) {
7610 CloseHandle(ol.hEvent);
7611 rb_acrt_lowio_unlock_fh(fd);
7612 return -1;
7613 }
7614 }
7615 else if (!GetOverlappedResult((HANDLE)_osfhnd(fd), &ol, &written, TRUE)) {
7616 errno = map_errno(GetLastError());
7617 CloseHandle(ol.hEvent);
7618 CancelIo((HANDLE)_osfhnd(fd));
7619 rb_acrt_lowio_unlock_fh(fd);
7620 return -1;
7621 }
7622 }
7623
7624 finish_overlapped(&ol, fd, written, offset);
7625
7626 ret += written;
7627 if (written == len) {
7628 buf = (const char *)buf + len;
7629 if (size > 0)
7630 goto retry;
7631 }
7632 if (ret == 0) {
7633 size_t newlen = len / 2;
7634 if (newlen > 0) {
7635 size += len - newlen;
7636 len = newlen;
7637 goto retry2;
7638 }
7639 ret = -1;
7640 errno = EWOULDBLOCK;
7641 }
7642
7643 rb_acrt_lowio_unlock_fh(fd);
7644
7645 return ret;
7646}
7647
7648ssize_t
7649rb_w32_read(int fd, void *buf, size_t size)
7650{
7651 return rb_w32_read_internal(fd, buf, size, NULL);
7652}
7653
7654ssize_t
7655rb_w32_write(int fd, const void *buf, size_t size)
7656{
7657 return rb_w32_write_internal(fd, buf, size, NULL);
7658}
7659
7660ssize_t
7661rb_w32_pread(int descriptor, void *base, size_t size, rb_off_t offset)
7662{
7663 return rb_w32_read_internal(descriptor, base, size, &offset);
7664}
7665
7666ssize_t
7667rb_w32_pwrite(int descriptor, const void *base, size_t size, rb_off_t offset)
7668{
7669 return rb_w32_write_internal(descriptor, base, size, &offset);
7670}
7671
7672/* License: Ruby's */
7673long
7674rb_w32_write_console(uintptr_t strarg, int fd)
7675{
7676 HANDLE handle;
7677 DWORD dwMode, reslen;
7678 VALUE str = strarg;
7679 int encindex;
7680 WCHAR *wbuffer = 0;
7681 const WCHAR *ptr, *next;
7682 struct constat *s;
7683 long len;
7684
7685 handle = (HANDLE)_osfhnd(fd);
7686 if (!GetConsoleMode(handle, &dwMode))
7687 return -1L;
7688
7689 s = constat_handle(handle);
7690 if (!s) return -1L;
7691 encindex = ENCODING_GET(str);
7692 switch (encindex) {
7693 default:
7694 if (!rb_econv_has_convpath_p(rb_enc_name(rb_enc_from_index(encindex)), "UTF-8"))
7695 return -1L;
7696 str = rb_str_conv_enc_opts(str, NULL, rb_enc_from_index(ENCINDEX_UTF_8),
7698 /* fall through */
7699 case ENCINDEX_US_ASCII:
7700 case ENCINDEX_ASCII_8BIT:
7701 /* assume UTF-8 */
7702 case ENCINDEX_UTF_8:
7703 /* mbstr_to_wstr takes an int; the caller falls back to write(). */
7704 if (RSTRING_LEN(str) > INT_MAX) return -1L;
7705 ptr = wbuffer = mbstr_to_wstr(CP_UTF8, RSTRING_PTR(str), (int)RSTRING_LEN(str), &len);
7706 if (!ptr) return -1L;
7707 break;
7708 case ENCINDEX_UTF_16LE:
7709 if (RSTRING_LEN(str) > INT_MAX) return -1L;
7710 ptr = (const WCHAR *)RSTRING_PTR(str);
7711 len = RSTRING_LEN(str) / sizeof(WCHAR);
7712 break;
7713 }
7714 reslen = 0;
7715 if (dwMode & ENABLE_VIRTUAL_TERMINAL_PROCESSING) {
7716 if (!WriteConsoleW(handle, ptr, len, &reslen, NULL))
7717 reslen = (DWORD)-1L;
7718 }
7719 else {
7720 while (len > 0) {
7721 long curlen = constat_parse(handle, s, (next = ptr, &next), &len);
7722 reslen += next - ptr;
7723 if (curlen > 0) {
7724 DWORD written;
7725 if (!WriteConsoleW(handle, ptr, curlen, &written, NULL)) {
7726 reslen = (DWORD)-1L;
7727 break;
7728 }
7729 }
7730 ptr = next;
7731 }
7732 }
7733 RB_GC_GUARD(str);
7734 free(wbuffer);
7735 return (long)reslen;
7736}
7737
7738/* License: Ruby's */
7739static int
7740timespec_to_filetime(const struct timespec *ts, FILETIME *ft)
7741{
7742 ULARGE_INTEGER tmp;
7743
7744 tmp.QuadPart = unix_to_filetime((ULONGLONG)ts->tv_sec);
7745 tmp.QuadPart += ts->tv_nsec / 100;
7746 ft->dwLowDateTime = tmp.LowPart;
7747 ft->dwHighDateTime = tmp.HighPart;
7748 return 0;
7749}
7750
7751/* License: Ruby's */
7752static int
7753wutimensat(int dirfd, const WCHAR *path, const struct timespec *times, int flags)
7754{
7755 HANDLE hFile;
7756 FILETIME atime, mtime;
7757 struct stati128 stat;
7758 int ret = 0;
7759
7760 /* TODO: When path is absolute, dirfd should be ignored. */
7761 if (dirfd != AT_FDCWD) {
7762 errno = ENOSYS;
7763 return -1;
7764 }
7765
7766 if (flags != 0) {
7767 errno = EINVAL; /* AT_SYMLINK_NOFOLLOW isn't supported. */
7768 return -1;
7769 }
7770
7771 if (wstati128(path, &stat, FALSE)) {
7772 return -1;
7773 }
7774
7775 if (times) {
7776 if (timespec_to_filetime(&times[0], &atime)) {
7777 return -1;
7778 }
7779 if (timespec_to_filetime(&times[1], &mtime)) {
7780 return -1;
7781 }
7782 }
7783 else {
7784 GetSystemTimePreciseAsFileTime(&atime);
7785 mtime = atime;
7786 }
7787
7788 RUBY_CRITICAL {
7789 const DWORD attr = GetFileAttributesW(path);
7790 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY))
7791 SetFileAttributesW(path, attr & ~FILE_ATTRIBUTE_READONLY);
7792 hFile = open_special(path, GENERIC_WRITE, 0);
7793 if (hFile == INVALID_HANDLE_VALUE) {
7794 errno = map_errno(GetLastError());
7795 ret = -1;
7796 }
7797 else {
7798 if (!SetFileTime(hFile, NULL, &atime, &mtime)) {
7799 errno = map_errno(GetLastError());
7800 ret = -1;
7801 }
7802 CloseHandle(hFile);
7803 }
7804 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY))
7805 SetFileAttributesW(path, attr);
7806 }
7807
7808 return ret;
7809}
7810
7811/* License: Ruby's */
7812static int
7813w32_utimensat(int dirfd, const char *path, const struct timespec *times, int flags, UINT cp)
7814{
7815 WCHAR *wpath = mbstr_to_wstr(cp, path, -1, NULL);
7816 int ret = -1;
7817
7818 if (wpath) {
7819 ret = wutimensat(dirfd, wpath, times, flags);
7820 free(wpath);
7821 }
7822 return ret;
7823}
7824
7825/* License: Ruby's */
7826int
7827rb_w32_uutime(const char *path, const struct utimbuf *times)
7828{
7829 struct timespec ts[2];
7830
7831 ts[0].tv_sec = times->actime;
7832 ts[0].tv_nsec = 0;
7833 ts[1].tv_sec = times->modtime;
7834 ts[1].tv_nsec = 0;
7835 return w32_utimensat(AT_FDCWD, path, ts, 0, CP_UTF8);
7836}
7837
7838/* License: Ruby's */
7839int
7840rb_w32_utime(const char *path, const struct utimbuf *times)
7841{
7842 struct timespec ts[2];
7843
7844 ts[0].tv_sec = times->actime;
7845 ts[0].tv_nsec = 0;
7846 ts[1].tv_sec = times->modtime;
7847 ts[1].tv_nsec = 0;
7848 return w32_utimensat(AT_FDCWD, path, ts, 0, filecp());
7849}
7850
7851/* License: Ruby's */
7852int
7853rb_w32_uutimes(const char *path, const struct timeval *times)
7854{
7855 struct timespec ts[2];
7856
7857 ts[0].tv_sec = times[0].tv_sec;
7858 ts[0].tv_nsec = times[0].tv_usec * 1000;
7859 ts[1].tv_sec = times[1].tv_sec;
7860 ts[1].tv_nsec = times[1].tv_usec * 1000;
7861 return w32_utimensat(AT_FDCWD, path, ts, 0, CP_UTF8);
7862}
7863
7864/* License: Ruby's */
7865int
7866rb_w32_utimes(const char *path, const struct timeval *times)
7867{
7868 struct timespec ts[2];
7869
7870 ts[0].tv_sec = times[0].tv_sec;
7871 ts[0].tv_nsec = times[0].tv_usec * 1000;
7872 ts[1].tv_sec = times[1].tv_sec;
7873 ts[1].tv_nsec = times[1].tv_usec * 1000;
7874 return w32_utimensat(AT_FDCWD, path, ts, 0, filecp());
7875}
7876
7877/* License: Ruby's */
7878int
7879rb_w32_uutimensat(int dirfd, const char *path, const struct timespec *times, int flags)
7880{
7881 return w32_utimensat(dirfd, path, times, flags, CP_UTF8);
7882}
7883
7884/* License: Ruby's */
7885int
7886rb_w32_utimensat(int dirfd, const char *path, const struct timespec *times, int flags)
7887{
7888 return w32_utimensat(dirfd, path, times, flags, filecp());
7889}
7890
7891/* License: Ruby's */
7892int
7893rb_w32_uchdir(const char *path)
7894{
7895 WCHAR *wpath;
7896 int ret;
7897
7898 if (!(wpath = utf8_to_wstr(path, NULL)))
7899 return -1;
7900 ret = _wchdir(wpath);
7901 free(wpath);
7902 return ret;
7903}
7904
7905/* License: Ruby's */
7906static int
7907wmkdir(const WCHAR *wpath, int mode)
7908{
7909 int ret = -1;
7910
7911 RUBY_CRITICAL do {
7912 if (CreateDirectoryW(wpath, NULL) == FALSE) {
7913 errno = map_errno(GetLastError());
7914 break;
7915 }
7916 if (_wchmod(wpath, mode) == -1) {
7917 RemoveDirectoryW(wpath);
7918 break;
7919 }
7920 ret = 0;
7921 } while (0);
7922 return ret;
7923}
7924
7925/* License: Ruby's */
7926int
7927rb_w32_umkdir(const char *path, int mode)
7928{
7929 WCHAR *wpath;
7930 int ret;
7931
7932 if (!(wpath = utf8_to_wstr(path, NULL)))
7933 return -1;
7934 ret = wmkdir(wpath, mode);
7935 free(wpath);
7936 return ret;
7937}
7938
7939/* License: Ruby's */
7940int
7941rb_w32_mkdir(const char *path, int mode)
7942{
7943 WCHAR *wpath;
7944 int ret;
7945
7946 if (!(wpath = filecp_to_wstr(path, NULL)))
7947 return -1;
7948 ret = wmkdir(wpath, mode);
7949 free(wpath);
7950 return ret;
7951}
7952
7953/* License: Ruby's */
7954static int
7955wrmdir(const WCHAR *wpath)
7956{
7957 int ret = 0;
7958 RUBY_CRITICAL {
7959 const DWORD attr = GetFileAttributesW(wpath);
7960 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY)) {
7961 SetFileAttributesW(wpath, attr & ~FILE_ATTRIBUTE_READONLY);
7962 }
7963 if (RemoveDirectoryW(wpath) == FALSE) {
7964 errno = map_errno(GetLastError());
7965 ret = -1;
7966 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY)) {
7967 SetFileAttributesW(wpath, attr);
7968 }
7969 }
7970 }
7971 return ret;
7972}
7973
7974/* License: Ruby's */
7975int
7976rb_w32_rmdir(const char *path)
7977{
7978 WCHAR *wpath;
7979 int ret;
7980
7981 if (!(wpath = filecp_to_wstr(path, NULL)))
7982 return -1;
7983 ret = wrmdir(wpath);
7984 free(wpath);
7985 return ret;
7986}
7987
7988/* License: Ruby's */
7989int
7990rb_w32_urmdir(const char *path)
7991{
7992 WCHAR *wpath;
7993 int ret;
7994
7995 if (!(wpath = utf8_to_wstr(path, NULL)))
7996 return -1;
7997 ret = wrmdir(wpath);
7998 free(wpath);
7999 return ret;
8000}
8001
8002/* License: Ruby's */
8003static int
8004wunlink(const WCHAR *path)
8005{
8006 int ret = 0;
8007 const DWORD SYMLINKD = FILE_ATTRIBUTE_REPARSE_POINT|FILE_ATTRIBUTE_DIRECTORY;
8008 RUBY_CRITICAL {
8009 const DWORD attr = GetFileAttributesW(path);
8010 if (attr == (DWORD)-1) {
8011 }
8012 else if ((attr & SYMLINKD) == SYMLINKD) {
8013 ret = RemoveDirectoryW(path);
8014 }
8015 else {
8016 if (attr & FILE_ATTRIBUTE_READONLY) {
8017 SetFileAttributesW(path, attr & ~FILE_ATTRIBUTE_READONLY);
8018 }
8019 ret = DeleteFileW(path);
8020 }
8021 if (!ret) {
8022 errno = map_errno(GetLastError());
8023 ret = -1;
8024 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY)) {
8025 SetFileAttributesW(path, attr);
8026 }
8027 }
8028 }
8029 return ret;
8030}
8031
8032/* License: Ruby's */
8033int
8034rb_w32_uunlink(const char *path)
8035{
8036 WCHAR *wpath;
8037 int ret;
8038
8039 if (!(wpath = utf8_to_wstr(path, NULL)))
8040 return -1;
8041 ret = wunlink(wpath);
8042 free(wpath);
8043 return ret;
8044}
8045
8046/* License: Ruby's */
8047int
8048rb_w32_unlink(const char *path)
8049{
8050 WCHAR *wpath;
8051 int ret;
8052
8053 if (!(wpath = filecp_to_wstr(path, NULL)))
8054 return -1;
8055 ret = wunlink(wpath);
8056 free(wpath);
8057 return ret;
8058}
8059
8060/* License: Ruby's */
8061int
8062rb_w32_uchmod(const char *path, int mode)
8063{
8064 WCHAR *wpath;
8065 int ret;
8066
8067 if (!(wpath = utf8_to_wstr(path, NULL)))
8068 return -1;
8069 ret = _wchmod(wpath, mode);
8070 free(wpath);
8071 return ret;
8072}
8073
8074/* License: Ruby's */
8075int
8076fchmod(int fd, int mode)
8077{
8078 /* from winbase.h of the mingw-w64 runtime package. */
8079 struct {
8080 LARGE_INTEGER CreationTime;
8081 LARGE_INTEGER LastAccessTime;
8082 LARGE_INTEGER LastWriteTime;
8083 LARGE_INTEGER ChangeTime;
8084 DWORD FileAttributes;
8085 } info = {{{0}}, {{0}}, {{0}},}; /* fields with 0 are unchanged */
8086 HANDLE h = (HANDLE)_get_osfhandle(fd);
8087
8088 info.FileAttributes = FILE_ATTRIBUTE_NORMAL;
8089 if (!(mode & 0200)) info.FileAttributes |= FILE_ATTRIBUTE_READONLY;
8090 if (!SetFileInformationByHandle(h, 0, &info, sizeof(info))) {
8091 errno = map_errno(GetLastError());
8092 return -1;
8093 }
8094 return 0;
8095}
8096
8097/* License: Ruby's */
8098int
8099rb_w32_isatty(int fd)
8100{
8101 DWORD mode;
8102
8103 // validate fd by using _get_osfhandle() because we cannot access _nhandle
8104 if (_get_osfhandle(fd) == -1) {
8105 return 0;
8106 }
8107 if (!GetConsoleMode((HANDLE)_osfhnd(fd), &mode)) {
8108 errno = ENOTTY;
8109 return 0;
8110 }
8111 return 1;
8112}
8113
8114#ifndef signbit
8115/* License: Ruby's */
8116int
8117signbit(double x)
8118{
8119 int *ip = (int *)(&x + 1) - 1;
8120 return *ip < 0;
8121}
8122#endif
8123
8124/* License: Ruby's */
8125const char * WSAAPI
8126rb_w32_inet_ntop(int af, const void *addr, char *numaddr, size_t numaddr_len)
8127{
8128 return (inet_ntop)(af, (void *)addr, numaddr, numaddr_len);
8129}
8130
8131/* License: Ruby's */
8132int WSAAPI
8133rb_w32_inet_pton(int af, const char *src, void *dst)
8134{
8135 return (inet_pton)(af, src, dst);
8136}
8137
8138/* License: Ruby's */
8139char
8140rb_w32_fd_is_text(int fd)
8141{
8142 return _osfile(fd) & FTEXT;
8143}
8144
8145#ifdef HAVE__GMTIME64_S
8146# ifndef HAVE__LOCALTIME64_S
8147/* assume same as _gmtime64_s() */
8148# define HAVE__LOCALTIME64_S 1
8149# endif
8150# ifndef MINGW_HAS_SECURE_API
8151 _CRTIMP errno_t __cdecl _gmtime64_s(struct tm* tm, const __time64_t *time);
8152 _CRTIMP errno_t __cdecl _localtime64_s(struct tm* tm, const __time64_t *time);
8153# endif
8154# define gmtime_s _gmtime64_s
8155# define localtime_s _localtime64_s
8156#endif
8157
8158/* License: Ruby's */
8159struct tm *
8160gmtime_r(const time_t *tp, struct tm *rp)
8161{
8162 int e = EINVAL;
8163 if (!tp || !rp) {
8164 error:
8165 errno = e;
8166 return NULL;
8167 }
8168 e = gmtime_s(rp, tp);
8169 if (e != 0) goto error;
8170 return rp;
8171}
8172
8173/* License: Ruby's */
8174struct tm *
8175localtime_r(const time_t *tp, struct tm *rp)
8176{
8177 int e = EINVAL;
8178 if (!tp || !rp) {
8179 error:
8180 errno = e;
8181 return NULL;
8182 }
8183 e = localtime_s(rp, tp);
8184 if (e) goto error;
8185 return rp;
8186}
8187
8188/* License: Ruby's */
8189int
8190rb_w32_wrap_io_handle(HANDLE h, int flags)
8191{
8192 BOOL tmp;
8193 int len = sizeof(tmp);
8194 int r = getsockopt((SOCKET)h, SOL_SOCKET, SO_DEBUG, (char *)&tmp, &len);
8195 if (r != SOCKET_ERROR || WSAGetLastError() != WSAENOTSOCK) {
8196 int f = 0;
8197 if (flags & O_NONBLOCK) {
8198 flags &= ~O_NONBLOCK;
8199 f = O_NONBLOCK;
8200 }
8201 socklist_insert((SOCKET)h, f);
8202 }
8203 else if (flags & O_NONBLOCK) {
8204 errno = EINVAL;
8205 return -1;
8206 }
8207 return rb_w32_open_osfhandle((intptr_t)h, flags);
8208}
8209
8210/* License: Ruby's */
8211int
8212rb_w32_unwrap_io_handle(int fd)
8213{
8214 SOCKET sock = TO_SOCKET(fd);
8215 _set_osfhnd(fd, (SOCKET)INVALID_HANDLE_VALUE);
8216 if (!is_socket(sock)) {
8217 UnlockFile((HANDLE)sock, 0, 0, LK_LEN, LK_LEN);
8218 constat_delete((HANDLE)sock);
8219 }
8220 else {
8221 socklist_delete(&sock, NULL);
8222 }
8223 return _close(fd);
8224}
8225
8226#if !defined(__MINGW64__) && defined(__MINGW64_VERSION_MAJOR)
8227/*
8228 * Set floating point precision for pow() of mingw-w64 x86.
8229 * With default precision the result is not proper on WinXP.
8230 */
8231double
8232rb_w32_pow(double x, double y)
8233{
8234#undef pow
8235 double r;
8236 unsigned int default_control = _controlfp(0, 0);
8237 _controlfp(_PC_64, _MCW_PC);
8238 r = pow(x, y);
8239 /* Restore setting */
8240 _controlfp(default_control, _MCW_PC);
8241 return r;
8242}
8243#endif
8244
8245typedef struct {
8246 BOOL file_id_p;
8247 union {
8248 BY_HANDLE_FILE_INFORMATION bhfi;
8249 FILE_ID_INFO fii;
8250 } info;
8252
8253static HANDLE
8254w32_io_info(VALUE *file, w32_io_info_t *st)
8255{
8256 VALUE tmp;
8257 HANDLE f, ret = 0;
8258
8259 tmp = rb_check_convert_type_with_id(*file, T_FILE, "IO", idTo_io);
8260 if (!NIL_P(tmp)) {
8261 f = (HANDLE)rb_w32_get_osfhandle(rb_io_descriptor(tmp));
8262 if (f == (HANDLE)-1) return INVALID_HANDLE_VALUE;
8263 }
8264 else {
8265 VALUE tmp;
8266 WCHAR *ptr;
8267 int len;
8268 VALUE v;
8269
8270 FilePathValue(*file);
8271 tmp = rb_str_encode_ospath(*file);
8272 len = MultiByteToWideChar(CP_UTF8, 0, RSTRING_PTR(tmp), -1, NULL, 0);
8273 ptr = ALLOCV_N(WCHAR, v, len);
8274 MultiByteToWideChar(CP_UTF8, 0, RSTRING_PTR(tmp), -1, ptr, len);
8275 f = CreateFileW(ptr, 0,
8276 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
8277 FILE_FLAG_BACKUP_SEMANTICS, NULL);
8278 ALLOCV_END(v);
8279 if (f == INVALID_HANDLE_VALUE) return f;
8280 ret = f;
8281 }
8282 if (GetFileType(f) == FILE_TYPE_DISK) {
8283 ZeroMemory(st, sizeof(*st));
8284 if (get_ino(f, &st->info.fii)) {
8285 st->file_id_p = TRUE;
8286 return ret;
8287 }
8288 else if (GetLastError() != ERROR_INVALID_PARAMETER) {
8289 CloseHandle(f);
8290 return INVALID_HANDLE_VALUE;
8291 }
8292 /* this API may not work at files on non Microsoft SMB
8293 * server, fallback to old API then. */
8294 if (GetFileInformationByHandle(f, &st->info.bhfi)) {
8295 st->file_id_p = FALSE;
8296 return ret;
8297 }
8298 }
8299 if (ret) CloseHandle(ret);
8300 return INVALID_HANDLE_VALUE;
8301}
8302
8303static VALUE
8304close_handle(VALUE h)
8305{
8306 CloseHandle((HANDLE)h);
8307 return Qfalse;
8308}
8309
8311 VALUE *fname;
8312 w32_io_info_t *st;
8313};
8314
8315static VALUE
8316call_w32_io_info(VALUE arg)
8317{
8318 struct w32_io_info_args *p = (void *)arg;
8319 return (VALUE)w32_io_info(p->fname, p->st);
8320}
8321
8322VALUE
8323rb_w32_file_identical_p(VALUE fname1, VALUE fname2)
8324{
8325 w32_io_info_t st1, st2;
8326 HANDLE f1 = 0, f2 = 0;
8327
8328 f1 = w32_io_info(&fname1, &st1);
8329 if (f1 == INVALID_HANDLE_VALUE) return Qfalse;
8330 if (f1) {
8331 struct w32_io_info_args arg;
8332 arg.fname = &fname2;
8333 arg.st = &st2;
8334 f2 = (HANDLE)rb_ensure(call_w32_io_info, (VALUE)&arg, close_handle, (VALUE)f1);
8335 }
8336 else {
8337 f2 = w32_io_info(&fname2, &st2);
8338 }
8339 if (f2 == INVALID_HANDLE_VALUE) return Qfalse;
8340 if (f2) CloseHandle(f2);
8341
8342 if (st1.file_id_p != st2.file_id_p) return Qfalse;
8343 if (!st1.file_id_p) {
8344 if (st1.info.bhfi.dwVolumeSerialNumber == st2.info.bhfi.dwVolumeSerialNumber &&
8345 st1.info.bhfi.nFileIndexHigh == st2.info.bhfi.nFileIndexHigh &&
8346 st1.info.bhfi.nFileIndexLow == st2.info.bhfi.nFileIndexLow)
8347 return Qtrue;
8348 }
8349 else {
8350 if (st1.info.fii.VolumeSerialNumber == st2.info.fii.VolumeSerialNumber &&
8351 memcmp(&st1.info.fii.FileId, &st2.info.fii.FileId, sizeof(FILE_ID_128)) == 0)
8352 return Qtrue;
8353 }
8354 return Qfalse;
8355}
8356
8357int
8358rb_w32_set_thread_description(HANDLE th, const WCHAR *name)
8359{
8360 int result = FALSE;
8361 typedef HRESULT (WINAPI *set_thread_description_func)(HANDLE, PCWSTR);
8362 static set_thread_description_func set_thread_description =
8363 (set_thread_description_func)-1;
8364 if (set_thread_description == (set_thread_description_func)-1) {
8365 /* Since Windows 10, version 1607 and Windows Server 2016 */
8366 set_thread_description = (set_thread_description_func)
8367 get_proc_address("kernel32", "SetThreadDescription", NULL);
8368 }
8369 if (set_thread_description) {
8370 result = set_thread_description(th, name);
8371 }
8372 return result;
8373}
8374
8375int
8376rb_w32_set_thread_description_str(HANDLE th, VALUE name)
8377{
8378 int idx, result = FALSE;
8379 WCHAR *s;
8380
8381 if (NIL_P(name)) {
8382 return rb_w32_set_thread_description(th, L"");
8383 }
8384 s = (WCHAR *)StringValueCStr(name);
8385 idx = rb_enc_get_index(name);
8386 if (idx == ENCINDEX_UTF_16LE) {
8387 result = rb_w32_set_thread_description(th, s);
8388 }
8389 else {
8390 name = rb_str_conv_enc(name, rb_enc_from_index(idx), rb_utf8_encoding());
8391 s = mbstr_to_wstr(CP_UTF8, RSTRING_PTR(name), RSTRING_LEN(name)+1, NULL);
8392 result = rb_w32_set_thread_description(th, s);
8393 free(s);
8394 }
8395 RB_GC_GUARD(name);
8396 return result;
8397}
8398
8399VALUE (*const rb_f_notimplement_)(int, const VALUE *, VALUE, VALUE) = rb_f_notimplement;
8400
8401void *
8402rb_w32_mmap(void *addr, size_t len, int prot, int flags, int fd, rb_off_t offset)
8403{
8404 void *ptr;
8405 //DWORD protect = 0;
8406 DWORD protect = PAGE_EXECUTE_READWRITE;
8407
8408 if (fd > 0 || offset) {
8409 /* not supported */
8410 errno = EINVAL;
8411 return MAP_FAILED;
8412 }
8413
8414/*
8415 if (prot & PROT_EXEC) {
8416 if (prot & PROT_WRITE) protect = PAGE_EXECUTE_READWRITE;
8417 else if (prot & PROT_READ) protect = PAGE_EXECUTE_READ;
8418 else protect = PAGE_EXECUTE;
8419 }
8420 else if (prot & PROT_WRITE) protect = PAGE_READWRITE;
8421 else if (prot & PROT_READ) protect = PAGE_READONLY;
8422*/
8423 ptr = VirtualAlloc(addr, len, MEM_RESERVE | MEM_COMMIT, protect);
8424 if (!ptr) {
8425 errno = rb_w32_map_errno(GetLastError());
8426 return MAP_FAILED;
8427 }
8428
8429 return ptr;
8430}
8431
8432int
8433rb_w32_munmap(void *addr, size_t len)
8434{
8435 if (!VirtualFree(addr, 0, MEM_RELEASE)) {
8436 errno = rb_w32_map_errno(GetLastError());
8437 return -1;
8438 }
8439
8440 return 0;
8441}
8442
8443inline int
8444rb_w32_mprotect(void *addr, size_t len, int prot)
8445{
8446/*
8447 DWORD protect = 0;
8448 if (prot & PROT_EXEC) {
8449 if (prot & PROT_WRITE) protect = PAGE_EXECUTE_READWRITE;
8450 else if (prot & PROT_READ) protect = PAGE_EXECUTE_READ;
8451 else protect = PAGE_EXECUTE;
8452 }
8453 else if (prot & PROT_WRITE) protect = PAGE_READWRITE;
8454 else if (prot & PROT_READ) protect = PAGE_READONLY;
8455 if (!VirtualProtect(addr, len, protect, NULL)) {
8456 errno = rb_w32_map_errno(GetLastError());
8457 return -1;
8458 }
8459*/
8460 if (prot & PROT_EXEC) {
8461 if (!FlushInstructionCache(GetCurrentProcess(), addr, len)) {
8462 errno = rb_w32_map_errno(GetLastError());
8463 return -1;
8464 }
8465 }
8466 return 0;
8467}
#define LONG_LONG
Definition long_long.h:38
#define ISSPACE
@old{rb_isspace}
Definition ctype.h:88
#define ISALPHA
@old{rb_isalpha}
Definition ctype.h:92
#define ISALNUM
@old{rb_isalnum}
Definition ctype.h:91
int ruby_glob_func(const char *path, VALUE arg, void *enc)
Type of a glob callback function.
Definition glob.h:49
#define T_FILE
Old name of RUBY_T_FILE.
Definition value_type.h:62
#define ALLOCV
Old name of RB_ALLOCV.
Definition memory.h:407
#define ALLOC
Old name of RB_ALLOC.
Definition memory.h:403
#define xfree
Old name of ruby_xfree.
Definition xmalloc.h:58
#define xrealloc
Old name of ruby_xrealloc.
Definition xmalloc.h:56
#define ECONV_UNDEF_REPLACE
Old name of RUBY_ECONV_UNDEF_REPLACE.
Definition transcode.h:526
#define ENCODING_GET(obj)
Old name of RB_ENCODING_GET.
Definition encoding.h:109
#define ECONV_INVALID_REPLACE
Old name of RUBY_ECONV_INVALID_REPLACE.
Definition transcode.h:524
#define ASSUME
Old name of RBIMPL_ASSUME.
Definition assume.h:27
#define ALLOC_N
Old name of RB_ALLOC_N.
Definition memory.h:402
#define Qtrue
Old name of RUBY_Qtrue.
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define NIL_P
Old name of RB_NIL_P.
#define ALLOCV_N
Old name of RB_ALLOCV_N.
Definition memory.h:408
#define ALLOCV_END
Old name of RB_ALLOCV_END.
Definition memory.h:409
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
Encoding relates APIs.
#define RBIMPL_ATTR_FORMAT(x, y, z)
Wraps (or simulates) __attribute__((format)).
Definition format.h:33
#define RBIMPL_ATTR_NONNULL(list)
Wraps (or simulates) __attribute__((nonnull)).
Definition nonnull.h:30
rb_encoding * rb_utf8_encoding(void)
Queries the encoding that represents UTF-8.
Definition encoding.c:1578
rb_encoding * rb_filesystem_encoding(void)
Queries the "filesystem" encoding.
Definition encoding.c:1642
VALUE rb_str_conv_enc(VALUE str, rb_encoding *from, rb_encoding *to)
Encoding conversion main routine.
Definition string.c:1393
VALUE rb_str_conv_enc_opts(VALUE str, rb_encoding *from, rb_encoding *to, int ecflags, VALUE ecopts)
Identical to rb_str_conv_enc(), except it additionally takes IO encoder options.
Definition string.c:1277
int rb_econv_has_convpath_p(const char *from_encoding, const char *to_encoding)
Queries if there is more than one way to convert between the passed two encodings.
Definition transcode.c:3349
void rb_write_error2(const char *str, rb_len_t len)
Identical to rb_write_error(), except it additionally takes the message's length.
Definition io.c:9389
VALUE rb_str_cat(VALUE dst, const char *src, rb_len_t srclen)
Destructively appends the passed contents to the string.
Definition string.c:3706
#define rb_strlen_lit(str)
Length of a string literal.
Definition string.h:1717
#define rb_utf8_str_new(str, len)
Identical to rb_str_new, except it generates a string of "UTF-8" encoding.
Definition string.h:1574
VALUE rb_f_notimplement(int argc, const VALUE *argv, VALUE obj, VALUE marker)
Raises rb_eNotImpError.
Definition vm_method.c:913
int rb_io_descriptor(VALUE io)
Returns an integer representing the numeric file descriptor for io.
Definition io.c:2972
int len
Length of the buffer.
Definition io.h:8
char * ruby_strdup(const char *str)
This is our own version of strdup(3) that uses ruby_xmalloc() instead of system malloc (benefits our ...
Definition util.c:511
#define strdup(s)
Just another name of ruby_strdup.
Definition util.h:187
void ruby_vm_at_exit(void(*func)(ruby_vm_t *))
ruby_vm_at_exit registers a function func to be invoked when a VM passed away.
Definition vm.c:1064
struct rb_vm_struct ruby_vm_t
The opaque struct to hold VM internals.
Definition vm.h:25
void rb_w32_fd_dup(rb_fdset_t *dst, const rb_fdset_t *src)
Identical to rb_w32_fd_copy(), except it copies unlimited number of file descriptors.
Definition win32.c:2925
void rb_w32_fd_copy(rb_fdset_t *dst, const fd_set *src, int max)
Destructively overwrites an fdset with another.
Definition win32.c:2910
void rb_fd_term(rb_fdset_t *f)
Destroys the rb_fdset_t, releasing any memory and resources it used.
#define rb_long2int
Just another name of rb_long2int_inline.
Definition long.h:62
#define MEMCPY(p1, p2, type, n)
Handy macro to call memcpy.
Definition memory.h:375
#define ALLOCA_N(type, n)
Definition memory.h:295
#define MEMZERO(p, type, n)
Handy macro to erase a region of memory.
Definition memory.h:363
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:170
VALUE type(ANYARGS)
ANYARGS-ed function type.
int st_foreach(st_table *q, int_type *w, st_data_t e)
Iteration over the given table.
VALUE rb_ensure(type *q, VALUE w, type *e, VALUE r)
An equivalent of ensure clause.
#define PRI_PIDT_PREFIX
A rb_sprintf() format prefix to be used for a pid_t parameter.
Definition pid_t.h:38
#define rb_fd_init
Initialises the :given :rb_fdset_t.
Definition posix.h:63
#define StringValueCStr(v)
Identical to StringValuePtr, except it additionally checks for the contents for viability as a C stri...
Definition rstring.h:89
#define FilePathValue(v)
Ensures that the parameter object is a path.
Definition ruby.h:90
#define errno
Ractor-aware version of errno.
Definition ruby.h:388
C99 shim for <stdbool.h>.
Definition dir.h:22
Definition dir.h:14
The data structure which wraps the fd_set bitmap used by select(2).
Definition largesize.h:71
fd_set * fdset
File descriptors buffer.
Definition largesize.h:73
int capa
Maximum allowed number of FDs.
Definition win32.h:50
Definition win32.h:676
intptr_t SIGNED_VALUE
A signed integer type that has the same width with VALUE.
Definition value.h:63
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40