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