45#if defined _MSC_VER && _MSC_VER >= 1400
55#include "ruby/win32.h"
58#include "win32/file.h"
61#include "internal/enc.h"
62#include "internal/object.h"
63#include "internal/static_assert.h"
66#define isdirsep(x) ((x) == '/' || (x) == '\\')
68#if defined _MSC_VER && _MSC_VER <= 1200
69# define CharNextExA(cp, p, flags) CharNextExA((WORD)(cp), (p), (flags))
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);
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)
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
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)
101# define PATH_MAX MAX_PATH
102# elif defined HAVE_SYS_PARAM_H
103# include <sys/param.h>
104# define PATH_MAX MAXPATHLEN
116#if RUBY_MSVCRT_VERSION >= 140
117# define _filbuf _fgetc_nolock
118# define _flsbuf _fputc_nolock
120#define enough_to_get(n) (--(n) >= 0)
121#define enough_to_put(n) (--(n) >= 0)
124#define Debug(something) something
126#define Debug(something)
129#define TO_SOCKET(x) _get_osfhandle(x)
131int rb_w32_reparse_symlink_p(
const WCHAR *path);
133static int has_redirection(
const char *, UINT);
134int rb_w32_wait_events(HANDLE *events,
int num, DWORD timeout);
135static int rb_w32_open_osfhandle(intptr_t osfhandle,
int flags);
136static int wstati128(
const WCHAR *path,
struct stati128 *st, BOOL lstat);
137VALUE rb_w32_conv_from_wchar(
const WCHAR *wstr, rb_encoding *enc);
138int ruby_brace_glob_with_enc(
const char *str,
int flags,
ruby_glob_func *func,
VALUE arg, rb_encoding *enc);
139static FARPROC get_proc_address(
const char *module,
const char *func, HANDLE *mh);
141#define RUBY_CRITICAL if (0) {} else
148 { ERROR_INVALID_FUNCTION, EINVAL },
149 { ERROR_FILE_NOT_FOUND, ENOENT },
150 { ERROR_PATH_NOT_FOUND, ENOENT },
151 { ERROR_TOO_MANY_OPEN_FILES, EMFILE },
152 { ERROR_ACCESS_DENIED, EACCES },
153 { ERROR_INVALID_HANDLE, EBADF },
154 { ERROR_ARENA_TRASHED, ENOMEM },
155 { ERROR_NOT_ENOUGH_MEMORY, ENOMEM },
156 { ERROR_INVALID_BLOCK, ENOMEM },
157 { ERROR_BAD_ENVIRONMENT, E2BIG },
158 { ERROR_BAD_FORMAT, ENOEXEC },
159 { ERROR_INVALID_ACCESS, EINVAL },
160 { ERROR_INVALID_DATA, EINVAL },
161 { ERROR_INVALID_DRIVE, ENOENT },
162 { ERROR_CURRENT_DIRECTORY, EACCES },
163 { ERROR_NOT_SAME_DEVICE, EXDEV },
164 { ERROR_NO_MORE_FILES, ENOENT },
165 { ERROR_WRITE_PROTECT, EROFS },
166 { ERROR_BAD_UNIT, ENODEV },
167 { ERROR_NOT_READY, ENXIO },
168 { ERROR_BAD_COMMAND, EACCES },
169 { ERROR_CRC, EACCES },
170 { ERROR_BAD_LENGTH, EACCES },
172 { ERROR_NOT_DOS_DISK, EACCES },
173 { ERROR_SECTOR_NOT_FOUND, EACCES },
174 { ERROR_OUT_OF_PAPER, EACCES },
175 { ERROR_WRITE_FAULT, EIO },
176 { ERROR_READ_FAULT, EIO },
177 { ERROR_GEN_FAILURE, EACCES },
178 { ERROR_LOCK_VIOLATION, EACCES },
179 { ERROR_SHARING_VIOLATION, EACCES },
180 { ERROR_WRONG_DISK, EACCES },
181 { ERROR_SHARING_BUFFER_EXCEEDED, EACCES },
182 { ERROR_BAD_NETPATH, ENOENT },
183 { ERROR_NETWORK_ACCESS_DENIED, EACCES },
184 { ERROR_BAD_NET_NAME, ENOENT },
185 { ERROR_FILE_EXISTS, EEXIST },
186 { ERROR_CANNOT_MAKE, EACCES },
187 { ERROR_FAIL_I24, EACCES },
188 { ERROR_INVALID_PARAMETER, EINVAL },
189 { ERROR_NO_PROC_SLOTS, EAGAIN },
190 { ERROR_DRIVE_LOCKED, EACCES },
191 { ERROR_BROKEN_PIPE, EPIPE },
192 { ERROR_DISK_FULL, ENOSPC },
193 { ERROR_INVALID_TARGET_HANDLE, EBADF },
194 { ERROR_INVALID_HANDLE, EINVAL },
195 { ERROR_WAIT_NO_CHILDREN, ECHILD },
196 { ERROR_CHILD_NOT_COMPLETE, ECHILD },
197 { ERROR_DIRECT_ACCESS_HANDLE, EBADF },
198 { ERROR_NEGATIVE_SEEK, EINVAL },
199 { ERROR_SEEK_ON_DEVICE, EACCES },
200 { ERROR_DIR_NOT_EMPTY, ENOTEMPTY },
201 { ERROR_DIRECTORY, ENOTDIR },
202 { ERROR_NOT_LOCKED, EACCES },
203 { ERROR_BAD_PATHNAME, ENOENT },
204 { ERROR_MAX_THRDS_REACHED, EAGAIN },
205 { ERROR_LOCK_FAILED, EACCES },
206 { ERROR_ALREADY_EXISTS, EEXIST },
207 { ERROR_INVALID_STARTING_CODESEG, ENOEXEC },
208 { ERROR_INVALID_STACKSEG, ENOEXEC },
209 { ERROR_INVALID_MODULETYPE, ENOEXEC },
210 { ERROR_INVALID_EXE_SIGNATURE, ENOEXEC },
211 { ERROR_EXE_MARKED_INVALID, ENOEXEC },
212 { ERROR_BAD_EXE_FORMAT, ENOEXEC },
213 { ERROR_ITERATED_DATA_EXCEEDS_64k,ENOEXEC },
214 { ERROR_INVALID_MINALLOCSIZE, ENOEXEC },
215 { ERROR_DYNLINK_FROM_INVALID_RING,ENOEXEC },
216 { ERROR_IOPL_NOT_ENABLED, ENOEXEC },
217 { ERROR_INVALID_SEGDPL, ENOEXEC },
218 { ERROR_AUTODATASEG_EXCEEDS_64k, ENOEXEC },
219 { ERROR_RING2SEG_MUST_BE_MOVABLE, ENOEXEC },
220 { ERROR_RELOC_CHAIN_XEEDS_SEGLIM, ENOEXEC },
221 { ERROR_INFLOOP_IN_RELOC_CHAIN, ENOEXEC },
222 { ERROR_FILENAME_EXCED_RANGE, ENOENT },
223 { ERROR_NESTING_NOT_ALLOWED, EAGAIN },
224#ifndef ERROR_PIPE_LOCAL
225#define ERROR_PIPE_LOCAL 229L
227 { ERROR_PIPE_LOCAL, EPIPE },
228 { ERROR_BAD_PIPE, EPIPE },
229 { ERROR_PIPE_BUSY, EAGAIN },
230 { ERROR_NO_DATA, EPIPE },
231 { ERROR_PIPE_NOT_CONNECTED, EPIPE },
232 { ERROR_OPERATION_ABORTED, EINTR },
233 { ERROR_NOT_ENOUGH_QUOTA, ENOMEM },
234 { ERROR_MOD_NOT_FOUND, ENOENT },
235 { ERROR_PRIVILEGE_NOT_HELD, EACCES, },
236 { ERROR_CANT_RESOLVE_FILENAME, ELOOP, },
239 { WSAEACCES, EACCES },
240 { WSAEFAULT, EFAULT },
241 { WSAEINVAL, EINVAL },
242 { WSAEMFILE, EMFILE },
243 { WSAEWOULDBLOCK, EWOULDBLOCK },
244 { WSAEINPROGRESS, EINPROGRESS },
245 { WSAEALREADY, EALREADY },
246 { WSAENOTSOCK, ENOTSOCK },
247 { WSAEDESTADDRREQ, EDESTADDRREQ },
248 { WSAEMSGSIZE, EMSGSIZE },
249 { WSAEPROTOTYPE, EPROTOTYPE },
250 { WSAENOPROTOOPT, ENOPROTOOPT },
251 { WSAEPROTONOSUPPORT, EPROTONOSUPPORT },
252 { WSAESOCKTNOSUPPORT, ESOCKTNOSUPPORT },
253 { WSAEOPNOTSUPP, EOPNOTSUPP },
254 { WSAEPFNOSUPPORT, EPFNOSUPPORT },
255 { WSAEAFNOSUPPORT, EAFNOSUPPORT },
256 { WSAEADDRINUSE, EADDRINUSE },
257 { WSAEADDRNOTAVAIL, EADDRNOTAVAIL },
258 { WSAENETDOWN, ENETDOWN },
259 { WSAENETUNREACH, ENETUNREACH },
260 { WSAENETRESET, ENETRESET },
261 { WSAECONNABORTED, ECONNABORTED },
262 { WSAECONNRESET, ECONNRESET },
263 { WSAENOBUFS, ENOBUFS },
264 { WSAEISCONN, EISCONN },
265 { WSAENOTCONN, ENOTCONN },
266 { WSAESHUTDOWN, ESHUTDOWN },
267 { WSAETOOMANYREFS, ETOOMANYREFS },
268 { WSAETIMEDOUT, ETIMEDOUT },
269 { WSAECONNREFUSED, ECONNREFUSED },
271 { WSAENAMETOOLONG, ENAMETOOLONG },
272 { WSAEHOSTDOWN, EHOSTDOWN },
273 { WSAEHOSTUNREACH, EHOSTUNREACH },
274 { WSAEPROCLIM, EPROCLIM },
275 { WSAENOTEMPTY, ENOTEMPTY },
276 { WSAEUSERS, EUSERS },
277 { WSAEDQUOT, EDQUOT },
278 { WSAESTALE, ESTALE },
279 { WSAEREMOTE, EREMOTE },
284rb_w32_map_errno(DWORD winerr)
292 for (i = 0; i < (int)(
sizeof(errmap) /
sizeof(*errmap)); i++) {
293 if (errmap[i].winerr == winerr) {
294 return errmap[i].err;
298 if (winerr >= WSABASEERR) {
304#define map_errno rb_w32_map_errno
306static const char *NTLoginName;
308static OSVERSIONINFO osver;
314 memset(&osver, 0,
sizeof(OSVERSIONINFO));
315 osver.dwOSVersionInfoSize =
sizeof(OSVERSIONINFO);
316 GetVersionEx(&osver);
324 return osver.dwPlatformId;
332 return osver.dwMajorVersion;
343 DWORD err = GetLastError(); \
344 if (err == ERROR_LOCK_VIOLATION || err == ERROR_IO_PENDING) \
345 errno = EWOULDBLOCK; \
346 else if (err == ERROR_NOT_LOCKED) \
349 errno = map_errno(err); \
352#define LK_LEN ULONG_MAX
356flock_winnt(uintptr_t self,
int argc, uintptr_t* argv)
360 const HANDLE fh = (HANDLE)self;
361 const int oper = argc;
363 memset(&o, 0,
sizeof(o));
367 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, LK_LEN, &o), i);
370 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, LK_LEN, &o), i);
372 case LOCK_SH|LOCK_NB:
373 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, LK_LEN, &o), i);
375 case LOCK_EX|LOCK_NB:
376 LK_ERR(LockFileEx(fh,
377 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
378 0, LK_LEN, LK_LEN, &o), i);
381 case LOCK_UN|LOCK_NB:
382 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, LK_LEN, &o), i);
395flock(
int fd,
int oper)
397 const asynchronous_func_t locker = flock_winnt;
399 return rb_w32_asynchronize(locker,
400 (
VALUE)_get_osfhandle(fd), oper, NULL,
406translate_wchar(WCHAR *p,
int from,
int to)
417translate_char(
char *p,
int from,
int to, UINT cp)
420 if ((
unsigned char)*p == from)
422 p = CharNextExA(cp, p, 0);
427#ifndef CSIDL_LOCAL_APPDATA
428#define CSIDL_LOCAL_APPDATA 28
430#ifndef CSIDL_COMMON_APPDATA
431#define CSIDL_COMMON_APPDATA 35
434#define CSIDL_WINDOWS 36
437#define CSIDL_SYSTEM 37
440#define CSIDL_PROFILE 40
445get_special_folder(
int n, WCHAR *buf,
size_t len)
450 typedef BOOL (WINAPI *get_path_func)(LPITEMIDLIST, WCHAR*, DWORD, int);
451 static get_path_func func = (get_path_func)-1;
453 if (func == (get_path_func)-1) {
454 func = (get_path_func)
455 get_proc_address(
"shell32",
"SHGetPathFromIDListEx", NULL);
457 if (!func &&
len < MAX_PATH)
return FALSE;
459 if (SHGetSpecialFolderLocation(NULL, n, &pidl) == 0) {
461 f = func(pidl, buf,
len, 0);
464 f = SHGetPathFromIDListW(pidl, buf);
467 alloc->lpVtbl->Free(alloc, pidl);
468 alloc->lpVtbl->Release(alloc);
475regulate_path(WCHAR *path)
477 WCHAR *p = translate_wchar(path, L
'\\', L
'/');
478 if (p - path == 2 && path[1] == L
':') {
486get_proc_address(
const char *module,
const char *func, HANDLE *mh)
492 h = LoadLibrary(module);
494 h = GetModuleHandle(module);
498 ptr = GetProcAddress(h, func);
510rb_w32_special_folder(
int type)
512 WCHAR path[PATH_MAX];
514 if (!get_special_folder(
type, path, numberof(path)))
return Qnil;
516 return rb_w32_conv_from_wchar(path, rb_filesystem_encoding());
519#if defined _MSC_VER && _MSC_VER <= 1200
521#define GetSystemWindowsDirectoryW GetWindowsDirectoryW
526rb_w32_system_tmpdir(WCHAR *path, UINT
len)
528 static const WCHAR temp[] = L
"temp";
531 if (!get_special_folder(CSIDL_LOCAL_APPDATA, path,
len)) {
532 if (GetSystemWindowsDirectoryW(path,
len))
return 0;
534 p = translate_wchar(path, L
'\\', L
'/');
535 if (*(p - 1) != L
'/') *p++ = L
'/';
536 if ((UINT)(p - path + numberof(temp)) >=
len)
return 0;
537 memcpy(p, temp,
sizeof(temp));
538 return (UINT)(p - path + numberof(temp) - 1);
553 WCHAR *buffer = NULL;
554 size_t buffer_len = MAX_PATH,
len = 0;
556 HOME_NONE, ENV_HOME, ENV_USERPROFILE, ENV_DRIVEPATH
557 } home_type = HOME_NONE;
559 if ((
len = GetEnvironmentVariableW(L
"HOME", NULL, 0)) != 0) {
561 home_type = ENV_HOME;
563 else if ((
len = GetEnvironmentVariableW(L
"USERPROFILE", NULL, 0)) != 0) {
565 home_type = ENV_USERPROFILE;
567 else if ((
len = GetEnvironmentVariableW(L
"HOMEDRIVE", NULL, 0)) != 0) {
569 if ((
len = GetEnvironmentVariableW(L
"HOMEPATH", NULL, 0)) != 0) {
571 home_type = ENV_DRIVEPATH;
576 buffer =
ALLOC_N(WCHAR, buffer_len);
580 GetEnvironmentVariableW(L
"HOME", buffer, buffer_len);
582 case ENV_USERPROFILE:
583 GetEnvironmentVariableW(L
"USERPROFILE", buffer, buffer_len);
586 len = GetEnvironmentVariableW(L
"HOMEDRIVE", buffer, buffer_len);
587 GetEnvironmentVariableW(L
"HOMEPATH", buffer +
len, buffer_len -
len);
590 if (!get_special_folder(CSIDL_PROFILE, buffer, buffer_len) &&
591 !get_special_folder(CSIDL_PERSONAL, buffer, buffer_len)) {
595 REALLOC_N(buffer, WCHAR, lstrlenW(buffer) + 1);
600 regulate_path(buffer);
609 static const WCHAR TMPDIR[] = L
"TMPDIR";
610 struct {WCHAR name[6], eq, val[ENV_MAX];} wk;
614#define set_env_val(vname) do { \
615 typedef char wk_name_offset[(numberof(wk.name) - (numberof(vname) - 1)) * 2 + 1]; \
616 WCHAR *const buf = wk.name + sizeof(wk_name_offset) / 2; \
617 MEMCPY(buf, vname, WCHAR, numberof(vname) - 1); \
623 if (!GetEnvironmentVariableW(L
"HOME", env, numberof(env))) {
625 if (GetEnvironmentVariableW(L
"USERPROFILE", env, numberof(env))) {
629 if (GetEnvironmentVariableW(L
"HOMEDRIVE", env, numberof(env)))
634 if (GetEnvironmentVariableW(L
"HOMEPATH", env +
len, numberof(env) -
len) ||
len) {
637 else if (get_special_folder(CSIDL_PROFILE, env, numberof(env))) {
640 else if (get_special_folder(CSIDL_PERSONAL, env, numberof(env))) {
646 set_env_val(L
"HOME");
650 if (!GetEnvironmentVariableW(L
"USER", env, numberof(env))) {
651 if (!GetEnvironmentVariableW(L
"USERNAME", env, numberof(env)) &&
652 !GetUserNameW(env, (
len = numberof(env), &
len))) {
653 NTLoginName =
"<Unknown>";
656 set_env_val(L
"USER");
657 NTLoginName = rb_w32_wstr_to_mbstr(CP_UTF8, env, -1, NULL);
661 NTLoginName = rb_w32_wstr_to_mbstr(CP_UTF8, env, -1, NULL);
664 if (!GetEnvironmentVariableW(TMPDIR, env, numberof(env)) &&
665 !GetEnvironmentVariableW(L
"TMP", env, numberof(env)) &&
666 !GetEnvironmentVariableW(L
"TEMP", env, numberof(env)) &&
667 rb_w32_system_tmpdir(env, numberof(env))) {
675static void init_stdhandle(
void);
677#if RUBY_MSVCRT_VERSION >= 80
680invalid_parameter(
const wchar_t *expr,
const wchar_t *func,
const wchar_t *file,
unsigned int line, uintptr_t dummy)
685int ruby_w32_rtc_error;
692rtc_error_handler(
int e, const
char *src,
int line, const
char *exe, const
char *fmt, ...)
697 if (!ruby_w32_rtc_error)
return 0;
698 str = rb_sprintf(
"%s:%d: ", src, line);
700 rb_str_vcatf(str, fmt, ap);
702 rb_str_cat(str,
"\n", 1);
709static CRITICAL_SECTION select_mutex;
711static CRITICAL_SECTION socklist_mutex;
712static st_table *socklist = NULL;
714static CRITICAL_SECTION conlist_mutex;
715static st_table *conlist = NULL;
716#define conlist_disabled ((st_table *)-1)
718#define thread_exclusive(obj) \
719 for (bool exclusive_for_##obj = (EnterCriticalSection(&obj##_mutex), true); \
720 exclusive_for_##obj; \
721 exclusive_for_##obj = (LeaveCriticalSection(&obj##_mutex), false))
723static CRITICAL_SECTION uenvarea_mutex;
724static char *uenvarea;
729 int state, seq[16], reverse;
734enum {constat_init = -2, constat_esc = -1, constat_seq = 0};
738free_conlist(st_data_t key, st_data_t val, st_data_t arg)
746constat_delete(HANDLE h)
748 thread_exclusive(conlist) {
749 if (conlist && conlist != conlist_disabled) {
750 st_data_t key = (st_data_t)h, val;
751 st_delete(conlist, &key, &val);
762 DeleteCriticalSection(&select_mutex);
763 DeleteCriticalSection(&socklist_mutex);
764 DeleteCriticalSection(&conlist_mutex);
765 thread_exclusive(uenvarea) {
771 DeleteCriticalSection(&uenvarea_mutex);
778 EnterCriticalSection(&socklist_mutex);
780 st_free_table(socklist);
783 LeaveCriticalSection(&socklist_mutex);
785 EnterCriticalSection(&conlist_mutex);
786 if (conlist && conlist != conlist_disabled) {
787 st_foreach(conlist, free_conlist, 0);
788 st_free_table(conlist);
791 LeaveCriticalSection(&conlist_mutex);
794#define ATOMIC_LONG_CAS(var, oldval, newval) InterlockedCompareExchange(&(var), (newval), (oldval))
798install_vm_exit_handler(
void)
800 static LONG installed = 0;
803 while ((i = ATOMIC_LONG_CAS(installed, 0, -1)) != 1) {
809 ATOMIC_LONG_CAS(installed, -1, 1);
825 version = MAKEWORD(2, 0);
826 if (WSAStartup(version, &retdata))
827 rb_fatal(
"Unable to locate winsock library!");
828 if (LOBYTE(retdata.wVersion) != 2)
829 rb_fatal(
"could not find version 2 of winsock dll");
831 InitializeCriticalSection(&select_mutex);
832 InitializeCriticalSection(&socklist_mutex);
833 InitializeCriticalSection(&conlist_mutex);
835 atexit(exit_handler);
838#define MAKE_SOCKDATA(af, fl) ((int)((((int)af)<<4)|((fl)&0xFFFF)))
839#define GET_FAMILY(v) ((int)(((v)>>4)&0xFFFF))
840#define GET_FLAGS(v) ((int)((v)&0xFFFF))
844socklist_insert(SOCKET sock,
int flag)
848 thread_exclusive(socklist) {
850 socklist = st_init_numtable();
851 install_vm_exit_handler();
853 ret = st_insert(socklist, (st_data_t)sock, (st_data_t)flag);
861socklist_lookup(SOCKET sock,
int *flagp)
866 thread_exclusive(socklist) {
867 if (!socklist)
continue;
868 ret = st_lookup(socklist, (st_data_t)sock, &data);
878socklist_delete(SOCKET *sockp,
int *flagp)
884 thread_exclusive(socklist) {
885 if (!socklist)
continue;
886 key = (st_data_t)*sockp;
888 data = (st_data_t)*flagp;
889 ret = st_delete(socklist, &key, &data);
891 *sockp = (SOCKET)key;
900#if RUBY_MSVCRT_VERSION >= 80
902# define _CrtSetReportMode(type,mode) ((void)0)
903# define _RTC_SetErrorFunc(func) ((void)0)
905static void set_pioinfo_extra(
void);
907static int w32_cmdvector(
const WCHAR *,
char ***, UINT, rb_encoding *);
913rb_w32_sysinit(
int *argc,
char ***argv)
915#if RUBY_MSVCRT_VERSION >= 80
917 _CrtSetReportMode(_CRT_ASSERT, 0);
918 _set_invalid_parameter_handler(invalid_parameter);
919 _RTC_SetErrorFunc(rtc_error_handler);
922 SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOGPFAULTERRORBOX);
929 *argc = w32_cmdvector(GetCommandLineW(), argv, CP_UTF8, &OnigEncodingUTF_8);
937 InitializeCriticalSection(&uenvarea_mutex);
949 return (
char *)NTLoginName;
952#define MAXCHILDNUM 256
961#define FOREACH_CHILD(v) do { \
962 struct ChildRecord* v; \
963 for (v = ChildRecord; v < ChildRecord + sizeof(ChildRecord) / sizeof(ChildRecord[0]); ++v)
964#define END_FOREACH_CHILD } while (0)
968FindChildSlot(rb_pid_t pid)
971 FOREACH_CHILD(child) {
972 if (child->pid == pid) {
981FindChildSlotByHandle(HANDLE h)
984 FOREACH_CHILD(child) {
985 if (child->hProcess == h) {
996 HANDLE h = child->hProcess;
997 child->hProcess = NULL;
1004FindFreeChildSlot(
void)
1006 FOREACH_CHILD(child) {
1009 child->hProcess = NULL;
1012 } END_FOREACH_CHILD;
1023#define InternalCmdsMax 8
1024static const char szInternalCmds[][InternalCmdsMax+2] = {
1078internal_match(
const void *key,
const void *elem)
1080 return strncmp(key, ((
const char *)elem) + 1, InternalCmdsMax);
1085is_command_com(
const char *interp)
1087 int i = strlen(interp) - 11;
1089 if ((i == 0 || (i > 0 && isdirsep(interp[i-1]))) &&
1090 strcasecmp(interp+i,
"command.com") == 0) {
1096static int internal_cmd_match(
const char *cmdname,
int nt);
1100is_internal_cmd(
const char *cmd,
int nt)
1102 char cmdname[9], *b = cmdname, c;
1105 if (!(c = *cmd++))
return 0;
1106 }
while (isspace(c));
1109 while (isalpha(c)) {
1111 if (b == cmdname +
sizeof(cmdname))
return 0;
1114 if (c ==
'.') c = *cmd;
1116 case '<':
case '>':
case '|':
1118 case '\0':
case ' ':
case '\t':
case '\n':
1124 return internal_cmd_match(cmdname, nt);
1129internal_cmd_match(
const char *cmdname,
int nt)
1133 nm = bsearch(cmdname, szInternalCmds,
1134 sizeof(szInternalCmds) /
sizeof(*szInternalCmds),
1135 sizeof(*szInternalCmds),
1137 if (!nm || !(nm[0] & (nt ? 2 : 1)))
1144rb_w32_get_osfhandle(
int fh)
1146 return _get_osfhandle(fh);
1151join_argv(
char *cmd,
char *
const *argv, BOOL escape, UINT cp,
int backslash)
1155 int len, n, bs, quote;
1157 for (t = argv, q = cmd,
len = 0; (p = *t) != 0; t++) {
1160 if (!*p || strpbrk(p,
" \t\"'")) {
1165 for (bs = 0; *p; ++p) {
1179 memset(q,
'\\', bs);
1184 case '<':
case '>':
case '|':
case '^':
1185 if (escape && !quote) {
1186 len += (n = p - s) + 1;
1197 p = CharNextExA(cp, p, 0) - 1;
1201 len += (n = p - s) + 1;
1205 if (backslash > 0) {
1208 translate_char(q,
'/',
'\\', cp);
1211 if (quote) *q++ =
'"';
1224#define STRNDUPV(ptr, v, src, len) \
1225 (((char *)memcpy(((ptr) = ALLOCV((v), (len) + 1)), (src), (len)))[len] = 0)
1229check_spawn_mode(
int mode)
1251 if (mode == P_OVERLAY) {
1252 WaitForSingleObject(child->hProcess, INFINITE);
1253 GetExitCodeProcess(child->hProcess, &exitcode);
1254 CloseChildHandle(child);
1262CreateChild(
struct ChildRecord *child,
const WCHAR *cmd,
const WCHAR *prog, HANDLE hInput, HANDLE hOutput, HANDLE hError, DWORD dwCreationFlags)
1265 STARTUPINFOW aStartupInfo;
1266 PROCESS_INFORMATION aProcessInformation;
1267 SECURITY_ATTRIBUTES sa;
1269 if (!cmd && !prog) {
1279 sa.nLength =
sizeof(SECURITY_ATTRIBUTES);
1280 sa.lpSecurityDescriptor = NULL;
1281 sa.bInheritHandle = TRUE;
1283 memset(&aStartupInfo, 0,
sizeof(aStartupInfo));
1284 memset(&aProcessInformation, 0,
sizeof(aProcessInformation));
1285 aStartupInfo.cb =
sizeof(aStartupInfo);
1286 aStartupInfo.dwFlags = STARTF_USESTDHANDLES;
1288 aStartupInfo.hStdInput = hInput;
1291 aStartupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
1294 aStartupInfo.hStdOutput = hOutput;
1297 aStartupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
1300 aStartupInfo.hStdError = hError;
1303 aStartupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
1306 dwCreationFlags |= NORMAL_PRIORITY_CLASS;
1308 if (lstrlenW(cmd) > 32767) {
1315 fRet = CreateProcessW(prog, (WCHAR *)cmd, &sa, &sa,
1316 sa.bInheritHandle, dwCreationFlags, NULL, NULL,
1317 &aStartupInfo, &aProcessInformation);
1318 errno = map_errno(GetLastError());
1326 CloseHandle(aProcessInformation.hThread);
1328 child->hProcess = aProcessInformation.hProcess;
1329 child->pid = (rb_pid_t)aProcessInformation.dwProcessId;
1336is_batch(
const char *cmd)
1338 int len = strlen(cmd);
1339 if (
len <= 4)
return 0;
1341 if (*cmd++ !=
'.')
return 0;
1342 if (strcasecmp(cmd,
"bat") == 0)
return 1;
1343 if (strcasecmp(cmd,
"cmd") == 0)
return 1;
1347#define filecp rb_w32_filecp
1348#define mbstr_to_wstr rb_w32_mbstr_to_wstr
1349#define wstr_to_mbstr rb_w32_wstr_to_mbstr
1350#define acp_to_wstr(str, plen) mbstr_to_wstr(CP_ACP, str, -1, plen)
1351#define wstr_to_acp(str, plen) wstr_to_mbstr(CP_ACP, str, -1, plen)
1352#define filecp_to_wstr(str, plen) mbstr_to_wstr(filecp(), str, -1, plen)
1353#define wstr_to_filecp(str, plen) wstr_to_mbstr(filecp(), str, -1, plen)
1354#define utf8_to_wstr(str, plen) mbstr_to_wstr(CP_UTF8, str, -1, plen)
1355#define wstr_to_utf8(str, plen) wstr_to_mbstr(CP_UTF8, str, -1, plen)
1359rb_w32_start_process(
const char *abspath,
char *
const *argv,
int out_fd)
1368 WCHAR *wcmd = NULL, *wprog = NULL;
1369 HANDLE outHandle = NULL;
1372 outHandle = (HANDLE)rb_w32_get_osfhandle(out_fd);
1375 len = join_argv(NULL, argv, FALSE, filecp(), 1);
1376 cmd = alloca(
sizeof(
char) *
len);
1377 join_argv(cmd, argv, FALSE, filecp(), 1);
1379 if (!(wcmd = mbstr_to_wstr(filecp(), cmd, -1, NULL))) {
1383 if (!(wprog = mbstr_to_wstr(filecp(), abspath, -1, NULL))) {
1388 if (!CreateChild(&child, wcmd, wprog, NULL, outHandle, outHandle, 0)) {
1394 return child.hProcess;
1399w32_spawn(
int mode,
const char *cmd,
const char *prog, UINT cp)
1401 char fbuf[PATH_MAX];
1403 const char *shell = NULL;
1404 WCHAR *wcmd = NULL, *wshell = NULL;
1410 char *cmd_sep = NULL;
1412 if (check_spawn_mode(mode))
return -1;
1415 if (!(p = dln_find_exe_r(prog, NULL, fbuf,
sizeof(fbuf)))) {
1420 translate_char(p,
'/',
'\\', cp);
1427 if ((shell = w32_getenv(
"RUBYSHELL", cp)) && (redir = has_redirection(cmd, cp))) {
1428 size_t shell_len = strlen(shell);
1429 size_t cmd_len = strlen(cmd) +
sizeof(
" -c ") + 2;
1430 char *tmp =
ALLOCV(v, shell_len + cmd_len);
1431 memcpy(tmp, shell, shell_len + 1);
1432 translate_char(tmp,
'/',
'\\', cp);
1433 snprintf(tmp + shell_len, cmd_len,
" -c \"%s\"", cmd);
1436 else if ((shell = w32_getenv(
"COMSPEC", cp)) &&
1437 (nt = !is_command_com(shell),
1438 (redir < 0 ? has_redirection(cmd, cp) : redir) ||
1439 is_internal_cmd(cmd, nt))) {
1440 size_t cmd_len = strlen(shell) + strlen(cmd) +
sizeof(
" /c ") + (nt ? 2 : 0);
1441 char *tmp =
ALLOCV(v, cmd_len);
1442 snprintf(tmp, cmd_len, nt ?
"%s /c \"%s\"" :
"%s /c %s", shell, cmd);
1446 int len = 0, quote = (*cmd ==
'"') ?
'"' : (*cmd ==
'\'') ?
'\'' : 0;
1448 for (prog = cmd + !!quote;; prog = CharNextExA(cp, prog, 0)) {
1449 if (*prog ==
'/') slash = 1;
1453 STRNDUPV(p, v2, cmd,
len);
1459 if ((
unsigned char)*prog == quote) {
1460 len = prog++ - cmd - 1;
1461 STRNDUPV(p, v2, cmd + 1,
len);
1465 if (quote)
continue;
1466 if (
ISSPACE(*prog) || strchr(
"<>|*?\"", *prog)) {
1468 STRNDUPV(p, v2, cmd,
len + (slash ? strlen(prog) : 0));
1471 sep = *(cmd_sep = &p[
len]);
1478 shell = dln_find_exe_r(shell, NULL, fbuf,
sizeof(fbuf));
1479 if (p && slash) translate_char(p,
'/',
'\\', cp);
1481 shell = p ? p : cmd;
1484 len = strlen(shell);
1485 if (strchr(shell,
' ')) quote = -1;
1486 if (shell == fbuf) {
1489 else if (shell != p && strchr(shell,
'/')) {
1490 STRNDUPV(p, v2, shell,
len);
1493 if (p) translate_char(p,
'/',
'\\', cp);
1494 if (is_batch(shell)) {
1495 int alen = strlen(prog);
1496 cmd = p =
ALLOCV(v,
len + alen + (quote ? 2 : 0) + 1);
1497 if (quote) *p++ =
'"';
1498 memcpy(p, shell,
len);
1500 if (quote) *p++ =
'"';
1501 memcpy(p, prog, alen + 1);
1508 if (!e && shell && !(wshell = mbstr_to_wstr(cp, shell, -1, NULL))) e = E2BIG;
1509 if (cmd_sep) *cmd_sep = sep;
1510 if (!e && cmd && !(wcmd = mbstr_to_wstr(cp, cmd, -1, NULL))) e = E2BIG;
1516 if (CreateChild(child, wcmd, wshell, NULL, NULL, NULL, 0)) {
1517 ret = child_result(child, mode);
1528rb_w32_spawn(
int mode,
const char *cmd,
const char *prog)
1531 return w32_spawn(mode, cmd, prog, filecp());
1536rb_w32_uspawn(
int mode,
const char *cmd,
const char *prog)
1538 return w32_spawn(mode, cmd, prog, CP_UTF8);
1543w32_spawn_process(
int mode,
const char *prog,
char *
const *argv,
1544 int in_fd,
int out_fd,
int err_fd, DWORD flags, UINT cp)
1548 BOOL ntcmd = FALSE, tmpnt;
1550 char *cmd, fbuf[PATH_MAX];
1551 WCHAR *wcmd = NULL, *wprog = NULL;
1555 HANDLE in_handle = NULL, out_handle = NULL, err_handle = NULL;
1557 if (check_spawn_mode(mode))
return -1;
1560 in_handle = (HANDLE)rb_w32_get_osfhandle(in_fd);
1563 out_handle = (HANDLE)rb_w32_get_osfhandle(out_fd);
1566 err_handle = (HANDLE)rb_w32_get_osfhandle(err_fd);
1569 if (!prog) prog = argv[0];
1570 if ((shell = w32_getenv(
"COMSPEC", cp)) &&
1571 internal_cmd_match(prog, tmpnt = !is_command_com(shell))) {
1576 else if ((cmd = dln_find_exe_r(prog, NULL, fbuf,
sizeof(fbuf)))) {
1577 if (cmd == prog) strlcpy(cmd = fbuf, prog,
sizeof(fbuf));
1578 translate_char(cmd,
'/',
'\\', cp);
1581 else if (strchr(prog,
'/')) {
1583 if (
len <
sizeof(fbuf))
1584 strlcpy(cmd = fbuf, prog,
sizeof(fbuf));
1586 STRNDUPV(cmd, v, prog,
len);
1587 translate_char(cmd,
'/',
'\\', cp);
1590 if (c_switch || is_batch(prog)) {
1592 progs[0] = (
char *)prog;
1594 len = join_argv(NULL, progs, ntcmd, cp, 1);
1595 if (c_switch)
len += 3;
1597 if (argv[0])
len += join_argv(NULL, argv, ntcmd, cp, 0);
1599 join_argv(cmd, progs, ntcmd, cp, 1);
1600 if (c_switch) strlcat(cmd,
" /c",
len);
1601 if (argv[0]) join_argv(cmd + strlcat(cmd,
" ",
len), argv, ntcmd, cp, 0);
1602 prog = c_switch ? shell : 0;
1605 len = join_argv(NULL, argv, FALSE, cp, 1);
1607 join_argv(cmd, argv, FALSE, cp, 1);
1610 if (!e && cmd && !(wcmd = mbstr_to_wstr(cp, cmd, -1, NULL))) e = E2BIG;
1612 if (!e && prog && !(wprog = mbstr_to_wstr(cp, prog, -1, NULL))) e = E2BIG;
1616 if (CreateChild(child, wcmd, wprog, in_handle, out_handle, err_handle, flags)) {
1617 ret = child_result(child, mode);
1628rb_w32_aspawn_flags(
int mode,
const char *prog,
char *
const *argv, DWORD flags)
1631 return w32_spawn_process(mode, prog, argv, -1, -1, -1, flags, filecp());
1636rb_w32_uaspawn_flags(
int mode,
const char *prog,
char *
const *argv, DWORD flags)
1638 return w32_spawn_process(mode, prog, argv, -1, -1, -1, flags, CP_UTF8);
1643rb_w32_aspawn(
int mode,
const char *prog,
char *
const *argv)
1645 return w32_spawn_process(mode, prog, argv, -1, -1, -1, 0, filecp());
1650rb_w32_uaspawn(
int mode,
const char *prog,
char *
const *argv)
1652 return rb_w32_uaspawn_flags(mode, prog, argv, 0);
1657rb_w32_uspawn_process(
int mode,
const char *prog,
char *
const *argv,
1658 int in_fd,
int out_fd,
int err_fd, DWORD flags)
1660 return w32_spawn_process(mode, prog, argv, in_fd, out_fd, err_fd,
1682insert(
const char *path,
VALUE vinfo,
void *enc)
1684 NtCmdLineElement *tmpcurr;
1685 NtCmdLineElement ***tail = (NtCmdLineElement ***)vinfo;
1687 tmpcurr = (NtCmdLineElement *)malloc(
sizeof(NtCmdLineElement));
1688 if (!tmpcurr)
return -1;
1689 MEMZERO(tmpcurr, NtCmdLineElement, 1);
1690 tmpcurr->len = strlen(path);
1691 tmpcurr->str =
strdup(path);
1692 if (!tmpcurr->str)
return -1;
1693 tmpcurr->flags |= NTMALLOC;
1695 *tail = &tmpcurr->next;
1701static NtCmdLineElement **
1702cmdglob(NtCmdLineElement *patt, NtCmdLineElement **tail, UINT cp, rb_encoding *enc)
1704 char buffer[PATH_MAX], *buf = buffer;
1705 NtCmdLineElement **last = tail;
1708 if (patt->len >= PATH_MAX)
1709 if (!(buf = malloc(patt->len + 1)))
return 0;
1711 memcpy(buf, patt->str, patt->len);
1712 buf[patt->len] =
'\0';
1713 translate_char(buf,
'\\',
'/', cp);
1714 status = ruby_brace_glob_with_enc(buf, 0, insert, (
VALUE)&tail, enc);
1718 if (status || last == tail)
return 0;
1719 if (patt->flags & NTMALLOC)
1732has_redirection(
const char *cmd, UINT cp)
1742 for (ptr = cmd; *ptr;) {
1748 else if (quote == *ptr)
1764 if (*++ptr !=
'_' && !
ISALPHA(*ptr))
break;
1765 while (*++ptr ==
'_' ||
ISALNUM(*ptr));
1766 if (*ptr++ ==
'%')
return TRUE;
1772 ptr = CharNextExA(cp, ptr, 0);
1780static inline WCHAR *
1781skipspace(WCHAR *ptr)
1790w32_cmdvector(
const WCHAR *cmd,
char ***vec, UINT cp, rb_encoding *enc)
1793 int elements, strsz, done;
1794 int slashes, escape;
1795 WCHAR *ptr, *base, *cmdline;
1796 char *cptr, *buffer;
1799 NtCmdLineElement *curr, **tail;
1800 NtCmdLineElement *cmdhead = NULL, **cmdtail = &cmdhead;
1812 ptr = cmdline = wcsdup(cmd);
1823 while (*(ptr = skipspace(ptr))) {
1825 quote = slashes = globbing = escape = 0;
1826 for (done = 0; !done && *ptr; ) {
1835 if (quote != L
'\'') slashes++;
1875 if (!(slashes & 1)) {
1878 else if (quote == *ptr) {
1879 if (quote == L
'"' && quote == ptr[1])
1889 ptr = CharNextW(ptr);
1912 slashes = quote = 0;
1913 while (p < base +
len) {
1917 if (quote != L
'\'') slashes++;
1922 if (!(slashes & 1) && quote && quote != c) {
1927 memcpy(p - ((slashes + 1) >> 1), p + (~slashes & 1),
1928 sizeof(WCHAR) * (base +
len - p));
1929 len -= ((slashes + 1) >> 1) + (~slashes & 1);
1930 p -= (slashes + 1) >> 1;
1931 if (!(slashes & 1)) {
1933 if (quote == L
'"' && quote == *p)
1953 curr = (NtCmdLineElement *)calloc(
sizeof(NtCmdLineElement), 1);
1954 if (!curr)
goto do_nothing;
1955 curr->str = rb_w32_wstr_to_mbstr(cp, base,
len, &curr->len);
1956 curr->flags |= NTMALLOC;
1958 if (globbing && (tail = cmdglob(curr, cmdtail, cp, enc))) {
1963 cmdtail = &curr->next;
1973 for (elements = 0, strsz = 0, curr = cmdhead; curr; curr = curr->next) {
1975 strsz += (curr->len + 1);
1978 len = (elements+1)*
sizeof(
char *) + strsz;
1979 buffer = (
char *)malloc(
len);
1982 while ((curr = cmdhead) != 0) {
1983 cmdhead = curr->next;
1984 if (curr->flags & NTMALLOC) free(curr->str);
1988 for (vptr = *vec; *vptr; ++vptr);
2004 vptr = (
char **) buffer;
2006 cptr = buffer + (elements+1) *
sizeof(
char *);
2008 while ((curr = cmdhead) != 0) {
2009 memcpy(cptr, curr->str, curr->len);
2010 cptr[curr->len] =
'\0';
2012 cptr += curr->len + 1;
2013 cmdhead = curr->next;
2014 if (curr->flags & NTMALLOC) free(curr->str);
2019 *vec = (
char **) buffer;
2028typedef DWORD (WINAPI *get_final_path_func)(HANDLE, WCHAR*, DWORD, DWORD);
2029static get_final_path_func get_final_path;
2032get_final_path_fail(HANDLE f, WCHAR *buf, DWORD
len, DWORD flag)
2038get_final_path_unknown(HANDLE f, WCHAR *buf, DWORD
len, DWORD flag)
2041 get_final_path_func func = (get_final_path_func)
2042 get_proc_address(
"kernel32",
"GetFinalPathNameByHandleW", NULL);
2043 if (!func) func = get_final_path_fail;
2044 get_final_path = func;
2045 return func(f, buf,
len, flag);
2048static get_final_path_func get_final_path = get_final_path_unknown;
2053open_special(
const WCHAR *path, DWORD access, DWORD flags)
2055 const DWORD share_mode =
2056 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
2057 return CreateFileW(path, access, share_mode, NULL, OPEN_EXISTING,
2058 FILE_FLAG_BACKUP_SEMANTICS|flags, NULL);
2068#define GetBit(bits, i) ((bits)[(i) / CHAR_BIT] & (1 << (i) % CHAR_BIT))
2069#define SetBit(bits, i) ((bits)[(i) / CHAR_BIT] |= (1 << (i) % CHAR_BIT))
2071#define BitOfIsDir(n) ((n) * 2)
2072#define BitOfIsRep(n) ((n) * 2 + 1)
2073#define DIRENT_PER_CHAR (CHAR_BIT / 2)
2075static const WCHAR namespace_prefix[] = {L
'\\', L
'\\', L
'?', L
'\\'};
2077enum {FINAL_PATH_MAX = PATH_MAX + numberof(namespace_prefix)};
2081open_dir_handle(
const WCHAR *filename, WIN32_FIND_DATAW *fd)
2092 fh = open_special(filename, 0, 0);
2093 if (fh != INVALID_HANDLE_VALUE) {
2094 len = get_final_path(fh, fullname, FINAL_PATH_MAX, 0);
2096 if (
len >= FINAL_PATH_MAX) {
2097 errno = ENAMETOOLONG;
2098 return INVALID_HANDLE_VALUE;
2102 len = lstrlenW(filename);
2103 if (
len >= PATH_MAX) {
2104 errno = ENAMETOOLONG;
2105 return INVALID_HANDLE_VALUE;
2109 p = &fullname[
len-1];
2110 if (!(isdirsep(*p) || *p == L
':')) *++p = L
'\\';
2117 fh = FindFirstFileW(fullname, fd);
2118 if (fh == INVALID_HANDLE_VALUE) {
2119 errno = map_errno(GetLastError());
2126w32_wopendir(
const WCHAR *wpath)
2128 struct stati128 sbuf;
2129 WIN32_FIND_DATAW fd;
2142 if (wstati128(wpath, &sbuf, FALSE) < 0) {
2145 if (!(sbuf.st_mode & S_IFDIR) &&
2146 (!
ISALPHA(wpath[0]) || wpath[1] != L
':' || wpath[2] != L
'\0' ||
2147 ((1 << ((wpath[0] & 0x5f) -
'A')) & GetLogicalDrives()) == 0)) {
2151 fh = open_dir_handle(wpath, &fd);
2152 if (fh == INVALID_HANDLE_VALUE) {
2159 p = calloc(
sizeof(
DIR), 1);
2163 pathlen = lstrlenW(wpath);
2173 len = lstrlenW(fd.cFileName) + 1;
2174 altlen = lstrlenW(fd.cAlternateFileName) + 1;
2180 tmpW = realloc(p->start, (idx +
len + altlen) *
sizeof(WCHAR));
2190 memcpy(&p->start[idx], fd.cFileName,
len *
sizeof(WCHAR));
2191 memcpy(&p->start[idx +
len], fd.cAlternateFileName, altlen *
sizeof(WCHAR));
2193 if (p->nfiles % DIRENT_PER_CHAR == 0) {
2194 tmp = realloc(p->bits, p->nfiles / DIRENT_PER_CHAR + 1);
2198 p->bits[p->nfiles / DIRENT_PER_CHAR] = 0;
2200 if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
2201 SetBit(p->bits, BitOfIsDir(p->nfiles));
2202 if (fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
2203 WCHAR *tmppath = malloc((pathlen +
len + 1) *
sizeof(WCHAR));
2204 memcpy(tmppath, wpath, pathlen *
sizeof(WCHAR));
2205 tmppath[pathlen] = L
'\\';
2206 memcpy(tmppath + pathlen + 1, fd.cFileName,
len *
sizeof(WCHAR));
2207 if (rb_w32_reparse_symlink_p(tmppath))
2208 SetBit(p->bits, BitOfIsRep(p->nfiles));
2213 idx +=
len + altlen;
2214 }
while (FindNextFileW(fh, &fd));
2225 UINT cp = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
2231rb_w32_wstr_to_mbstr(UINT cp,
const WCHAR *wstr,
int clen,
long *plen)
2234 int len = WideCharToMultiByte(cp, 0, wstr, clen, NULL, 0, NULL, NULL);
2235 if (!(ptr = malloc(
len)))
return 0;
2236 WideCharToMultiByte(cp, 0, wstr, clen, ptr,
len, NULL, NULL);
2239 if (clen == -1) --
len;
2247rb_w32_mbstr_to_wstr(UINT cp,
const char *str,
int clen,
long *plen)
2251 int len = MultiByteToWideChar(cp, 0, str, clen, NULL, 0);
2252 if (!(ptr = malloc(
sizeof(WCHAR) *
len)))
return 0;
2253 MultiByteToWideChar(cp, 0, str, clen, ptr,
len);
2256 if (clen == -1) --
len;
2264rb_w32_opendir(
const char *filename)
2267 WCHAR *wpath = filecp_to_wstr(filename, NULL);
2270 ret = w32_wopendir(wpath);
2277rb_w32_uopendir(
const char *filename)
2280 WCHAR *wpath = utf8_to_wstr(filename, NULL);
2283 ret = w32_wopendir(wpath);
2294move_to_next_entry(
DIR *dirp)
2298 dirp->curr += lstrlenW(dirp->curr) + 1;
2299 dirp->curr += lstrlenW(dirp->curr) + 1;
2300 if (dirp->curr >= (dirp->start + dirp->size)) {
2312win32_direct_conv(
const WCHAR *file,
const WCHAR *alt,
struct direct *entry,
const void *enc)
2314 UINT cp = *((UINT *)enc);
2315 if (!(entry->d_name = wstr_to_mbstr(cp, file, -1, &entry->d_namlen)))
2319 entry->d_altname = wstr_to_mbstr(cp, alt, -1, &altlen);
2320 entry->d_altlen = altlen;
2327rb_w32_conv_from_wchar(
const WCHAR *wstr, rb_encoding *enc)
2330 long len = lstrlenW(wstr);
2331 int encindex = rb_enc_to_index(enc);
2333 if (encindex == ENCINDEX_UTF_16LE) {
2334 return rb_enc_str_new((
char *)wstr,
len *
sizeof(WCHAR), enc);
2337#if SIZEOF_INT < SIZEOF_LONG
2338# error long should equal to int on Windows
2341 len = WideCharToMultiByte(CP_UTF8, 0, wstr, clen, NULL, 0, NULL, NULL);
2342 src = rb_enc_str_new(0,
len, rb_enc_from_index(ENCINDEX_UTF_8));
2343 WideCharToMultiByte(CP_UTF8, 0, wstr, clen, RSTRING_PTR(src),
len, NULL, NULL);
2346 case ENCINDEX_ASCII_8BIT:
2347 case ENCINDEX_US_ASCII:
2349 case ENCINDEX_UTF_8:
2358rb_w32_conv_from_wstr(
const WCHAR *wstr,
long *lenp, rb_encoding *enc)
2360 VALUE str = rb_w32_conv_from_wchar(wstr, enc);
2364 if (
NIL_P(str))
return wstr_to_utf8(wstr, lenp);
2365 *lenp =
len = RSTRING_LEN(str);
2366 memcpy(ptr = malloc(
len + 1), RSTRING_PTR(str),
len);
2373ruby_direct_conv(
const WCHAR *file,
const WCHAR *alt,
struct direct *entry,
const void *enc)
2375 if (!(entry->d_name = rb_w32_conv_from_wstr(file, &entry->d_namlen, enc)))
2379 entry->d_altname = rb_w32_conv_from_wstr(alt, &altlen, enc);
2380 entry->d_altlen = altlen;
2387readdir_internal(
DIR *dirp, BOOL (*conv)(
const WCHAR *,
const WCHAR *,
struct direct *,
const void *),
const void *enc)
2389 static long dummy_ino = 0;
2396 free(dirp->dirstr.d_name);
2397 free(dirp->dirstr.d_altname);
2398 dirp->dirstr.d_altname = 0;
2399 dirp->dirstr.d_altlen = 0;
2400 conv(dirp->curr, dirp->curr + lstrlenW(dirp->curr) + 1, &dirp->dirstr, enc);
2405 dirp->dirstr.d_ino = (ino_t)(InterlockedIncrement(&dummy_ino) - 1);
2411 if (GetBit(dirp->bits, BitOfIsRep(dirp->loc)))
2412 dirp->dirstr.d_type = DT_LNK;
2413 else if (GetBit(dirp->bits, BitOfIsDir(dirp->loc)))
2414 dirp->dirstr.d_type = DT_DIR;
2416 dirp->dirstr.d_type = DT_REG;
2422 move_to_next_entry(dirp);
2424 return &(dirp->dirstr);
2433rb_w32_readdir(
DIR *dirp, rb_encoding *enc)
2435 int idx = rb_enc_to_index(enc);
2436 if (idx == ENCINDEX_ASCII_8BIT) {
2437 const UINT cp = filecp();
2438 return readdir_internal(dirp, win32_direct_conv, &cp);
2440 else if (idx == ENCINDEX_UTF_8) {
2441 const UINT cp = CP_UTF8;
2442 return readdir_internal(dirp, win32_direct_conv, &cp);
2445 return readdir_internal(dirp, ruby_direct_conv, enc);
2450rb_w32_ureaddir(
DIR *dirp)
2452 const UINT cp = CP_UTF8;
2453 return readdir_internal(dirp, win32_direct_conv, &cp);
2462rb_w32_telldir(
DIR *dirp)
2473rb_w32_seekdir(
DIR *dirp,
long loc)
2475 if (dirp->loc > loc) rb_w32_rewinddir(dirp);
2477 while (dirp->curr && dirp->loc < loc) {
2478 move_to_next_entry(dirp);
2488rb_w32_rewinddir(
DIR *dirp)
2490 dirp->curr = dirp->start;
2500rb_w32_closedir(
DIR *dirp)
2503 free(dirp->dirstr.d_name);
2504 free(dirp->dirstr.d_altname);
2511#if RUBY_MSVCRT_VERSION >= 140
2526 CRITICAL_SECTION _lock;
2528#define FILE_COUNT(stream) ((vcruntime_file*)stream)->_cnt
2529#define FILE_READPTR(stream) ((vcruntime_file*)stream)->_ptr
2530#define FILE_FILENO(stream) ((vcruntime_file*)stream)->_file
2532#define FILE_COUNT(stream) stream->_cnt
2533#define FILE_READPTR(stream) stream->_ptr
2534#define FILE_FILENO(stream) stream->_file
2538#if RUBY_MSVCRT_VERSION >= 140
2539typedef char lowio_text_mode;
2540typedef char lowio_pipe_lookahead[3];
2543 CRITICAL_SECTION lock;
2546 unsigned char osfile;
2547 lowio_text_mode textmode;
2548 lowio_pipe_lookahead _pipe_lookahead;
2550 uint8_t unicode : 1;
2551 uint8_t utf8translations : 1;
2552 uint8_t dbcsBufferUsed : 1;
2561 CRITICAL_SECTION lock;
2562#if RUBY_MSVCRT_VERSION >= 80
2569#if !defined _CRTIMP || defined __MINGW32__
2571#define _CRTIMP __declspec(dllimport)
2574#if RUBY_MSVCRT_VERSION >= 140
2575static ioinfo ** __pioinfo = NULL;
2578EXTERN_C _CRTIMP
ioinfo * __pioinfo[];
2581static inline ioinfo* _pioinfo(
int);
2584#define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
2585#define _osfhnd(i) (_pioinfo(i)->osfhnd)
2586#define _osfile(i) (_pioinfo(i)->osfile)
2587#define rb_acrt_lowio_lock_fh(i) EnterCriticalSection(&_pioinfo(i)->lock)
2588#define rb_acrt_lowio_unlock_fh(i) LeaveCriticalSection(&_pioinfo(i)->lock)
2590#if RUBY_MSVCRT_VERSION >= 80
2591static size_t pioinfo_extra = 0;
2595set_pioinfo_extra(
void)
2597#if RUBY_MSVCRT_VERSION >= 140
2598# define FUNCTION_RET 0xc3
2600# define UCRTBASE "ucrtbased.dll"
2602# define UCRTBASE "ucrtbase.dll"
2617 char *p = (
char*)get_proc_address(UCRTBASE,
"_isatty", NULL);
2621#define IS_INSN(pc, name) ((*(pc) & name##_mask) == name##_id)
2622 const int max_num_inst = 500;
2623 uint32_t *start = (uint32_t*)p;
2624 uint32_t *end_limit = (start + max_num_inst);
2625 uint32_t *pc = start;
2628 fprintf(stderr,
"_isatty proc not found in " UCRTBASE
"\n");
2633 const uint32_t ret_id = 0xd65f0000;
2634 const uint32_t ret_mask = 0xfffffc1f;
2635 for(; pc < end_limit; pc++) {
2636 if (IS_INSN(pc, ret)) {
2640 if (pc == end_limit) {
2641 fprintf(stderr,
"end of _isatty not found in " UCRTBASE
"\n");
2646 const uint32_t adrp_id = 0x90000000;
2647 const uint32_t adrp_mask = 0x9f000000;
2648 const uint32_t add_id = 0x11000000;
2649 const uint32_t add_mask = 0x3fc00000;
2650 for(; pc > start; pc--) {
2651 if (IS_INSN(pc, adrp) && IS_INSN(pc + 1, add)) {
2656 fprintf(stderr,
"pioinfo mark not found in " UCRTBASE
"\n");
2666 const uint32_t adrp_insn = *pc;
2667 const uint32_t adrp_immhi = (adrp_insn & 0x00ffffe0) >> 5;
2668 const uint32_t adrp_immlo = (adrp_insn & 0x60000000) >> (5 + 19 + 5);
2670 const uint64_t adrp_imm = ((adrp_immhi << 2) | adrp_immlo) << 12;
2672 const uint64_t adrp_base = (uint64_t)pc & 0xfffffffffffff000;
2674 const uint32_t add_insn = *(pc + 1);
2675 const uint32_t add_sh = (add_insn & 0x400000) >> (12 + 5 + 5);
2679 const uint64_t add_imm = ((add_insn & 0x3ffc00) >> (5 + 5)) << (add_sh ? 12 : 0);
2681 __pioinfo = (
ioinfo**)(adrp_base + adrp_imm + add_imm);
2689# define FUNCTION_BEFORE_RET_MARK "\x48\x83\xc4"
2690# define FUNCTION_SKIP_BYTES 1
2693# define PIOINFO_MARK "\x48\x8d\x0d"
2696# define PIOINFO_MARK "\x48\x8d\x15"
2701# define FUNCTION_BEFORE_RET_MARK "\x5d"
2702# define FUNCTION_SKIP_BYTES 0
2704# define PIOINFO_MARK "\x8B\x04\x85"
2707 for (pend += 10; pend < p + 300; pend++) {
2709 if (memcmp(pend, FUNCTION_BEFORE_RET_MARK,
sizeof(FUNCTION_BEFORE_RET_MARK) - 1) == 0 &&
2710 (*(pend + (
sizeof(FUNCTION_BEFORE_RET_MARK) - 1) + FUNCTION_SKIP_BYTES) & FUNCTION_RET) == FUNCTION_RET) {
2712 for (pend -= (
sizeof(PIOINFO_MARK) - 1); pend > p; pend--) {
2713 if (memcmp(pend, PIOINFO_MARK,
sizeof(PIOINFO_MARK) - 1) == 0) {
2722 fprintf(stderr,
"unexpected " UCRTBASE
"\n");
2726 p +=
sizeof(PIOINFO_MARK) - 1;
2728 rel = *(int32_t*)(p);
2729 rip = p +
sizeof(int32_t);
2730 __pioinfo = (
ioinfo**)(rip + rel);
2732 __pioinfo = *(
ioinfo***)(p);
2738 fd = _open(
"NUL", O_RDONLY);
2739 for (pioinfo_extra = 0; pioinfo_extra <= 64; pioinfo_extra +=
sizeof(
void *)) {
2740 if (_osfhnd(fd) == _get_osfhandle(fd)) {
2746 if (pioinfo_extra > 64) {
2752#define pioinfo_extra 0
2758 const size_t sizeof_ioinfo =
sizeof(
ioinfo) + pioinfo_extra;
2759 return (
ioinfo*)((
char*)__pioinfo[fd >> IOINFO_L2E] +
2760 (fd & (IOINFO_ARRAY_ELTS - 1)) * sizeof_ioinfo);
2763#define _set_osfhnd(fh, osfh) (void)(_osfhnd(fh) = osfh)
2764#define _set_osflags(fh, flags) (_osfile(fh) = (flags))
2769#define FNOINHERIT 0x10
2774static int is_socket(SOCKET);
2775static int is_console(SOCKET);
2779rb_w32_io_cancelable_p(
int fd)
2781 return is_socket(TO_SOCKET(fd)) || !is_console(TO_SOCKET(fd));
2786rb_w32_open_osfhandle(intptr_t osfhandle,
int flags)
2795 if (flags & O_APPEND)
2796 fileflags |= FAPPEND;
2801 if (flags & O_NOINHERIT)
2802 fileflags |= FNOINHERIT;
2805 hF = CreateFile(
"NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
2806 fh = _open_osfhandle((intptr_t)hF, 0);
2814 rb_acrt_lowio_lock_fh(fh);
2816 _set_osfhnd(fh, osfhandle);
2820 _set_osflags(fh, fileflags);
2821 rb_acrt_lowio_unlock_fh(fh);
2832#define open_null(fd) \
2834 (nullfd = open("NUL", O_RDWR)) : 0), \
2835 ((nullfd == (fd)) ? (keep = 1) : dup2(nullfd, fd)), \
2838 if (fileno(stdin) < 0) {
2839 FILE_FILENO(stdin) = open_null(0);
2842 setmode(fileno(stdin), O_BINARY);
2844 if (fileno(stdout) < 0) {
2845 FILE_FILENO(stdout) = open_null(1);
2847 if (fileno(stderr) < 0) {
2848 FILE_FILENO(stderr) = open_null(2);
2850 if (nullfd >= 0 && !keep) close(nullfd);
2851 setvbuf(stderr, NULL, _IONBF, 0);
2854 HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
2856 if (GetConsoleMode(h, &m)) {
2857#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
2858#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x4
2860 SetConsoleMode(h, m | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
2869is_socket(SOCKET sock)
2871 if (socklist_lookup(sock, NULL))
2879rb_w32_is_socket(
int fd)
2881 return is_socket(TO_SOCKET(fd));
2894rb_w32_strerror(
int e)
2896 static char buffer[512];
2900 if (e < 0 || e > sys_nerr) {
2903#if WSAEWOULDBLOCK != EWOULDBLOCK
2904 else if (e >= EADDRINUSE && e <= EWOULDBLOCK) {
2908 for (s = 0; s < (int)(
sizeof(errmap)/
sizeof(*errmap)); s++)
2909 if (errmap[s].winerr == WSAEWOULDBLOCK)
2911 for (i = s; i < (int)(
sizeof(errmap)/
sizeof(*errmap)); i++)
2912 if (errmap[i].err == e) {
2913 e = errmap[i].winerr;
2918 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
2919 FORMAT_MESSAGE_IGNORE_INSERTS, &source, e,
2920 MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
2921 buffer,
sizeof(buffer), NULL) == 0 &&
2922 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
2923 FORMAT_MESSAGE_IGNORE_INSERTS, &source, e, 0,
2924 buffer,
sizeof(buffer), NULL) == 0)
2925 strlcpy(buffer,
"Unknown Error",
sizeof(buffer));
2928 strlcpy(buffer, strerror(e),
sizeof(buffer));
2931 while ((p = strpbrk(p,
"\r\n")) != NULL) {
2932 memmove(p, p + 1, strlen(p));
2983 return (uid == ROOT_UID ? 0 : -1);
2990 return (gid == ROOT_GID ? 0 : -1);
2999ioctl(
int i,
int u, ...)
3006rb_w32_fdset(
int fd, fd_set *set)
3015rb_w32_fdclr(
int fd, fd_set *set)
3018 SOCKET s = TO_SOCKET(fd);
3020 for (i = 0; i < set->fd_count; i++) {
3021 if (set->fd_array[i] == s) {
3022 memmove(&set->fd_array[i], &set->fd_array[i+1],
3023 sizeof(set->fd_array[0]) * (--set->fd_count - i));
3033rb_w32_fdisset(
int fd, fd_set *set)
3036 SOCKET s = TO_SOCKET(fd);
3037 if (s == (SOCKET)INVALID_HANDLE_VALUE)
3039 RUBY_CRITICAL {ret = __WSAFDIsSet(s, set);}
3047 max = min(src->fd_count, (UINT)max);
3048 if ((UINT)dst->
capa < (UINT)max) {
3049 dst->
capa = (src->fd_count / FD_SETSIZE + 1) * FD_SETSIZE;
3053 memcpy(dst->
fdset->fd_array, src->fd_array,
3054 max *
sizeof(src->fd_array[0]));
3055 dst->
fdset->fd_count = src->fd_count;
3062 if ((UINT)dst->
capa < src->
fdset->fd_count) {
3063 dst->
capa = (src->
fdset->fd_count / FD_SETSIZE + 1) * FD_SETSIZE;
3067 memcpy(dst->
fdset->fd_array, src->
fdset->fd_array,
3068 src->
fdset->fd_count *
sizeof(src->
fdset->fd_array[0]));
3082extract_fd(
rb_fdset_t *dst, fd_set *src,
int (*func)(SOCKET))
3088 while (s < src->fd_count) {
3089 SOCKET fd = src->fd_array[s];
3091 if (!func || (*func)(fd)) {
3095 for (d = 0; d < dst->
fdset->fd_count; d++) {
3096 if (dst->
fdset->fd_array[d] == fd)
3099 if (d == dst->
fdset->fd_count) {
3100 if ((
int)dst->
fdset->fd_count >= dst->
capa) {
3101 dst->
capa = (dst->
fdset->fd_count / FD_SETSIZE + 1) * FD_SETSIZE;
3104 dst->
fdset->fd_array[dst->
fdset->fd_count++] = fd;
3108 &src->fd_array[s+1],
3109 sizeof(src->fd_array[0]) * (--src->fd_count - s));
3119 return dst ? dst->
fdset->fd_count : m;
3124copy_fd(fd_set *dst, fd_set *src)
3127 if (!src || !dst)
return 0;
3129 for (s = 0; s < src->fd_count; ++s) {
3130 SOCKET fd = src->fd_array[s];
3132 for (d = 0; d < dst->fd_count; ++d) {
3133 if (dst->fd_array[d] == fd)
3136 if (d == dst->fd_count && d < FD_SETSIZE) {
3137 dst->fd_array[dst->fd_count++] = fd;
3141 return dst->fd_count;
3146is_not_socket(SOCKET sock)
3148 return !is_socket(sock);
3158 ret = (GetFileType((HANDLE)sock) == FILE_TYPE_PIPE);
3166is_readable_pipe(SOCKET sock)
3172 if (PeekNamedPipe((HANDLE)sock, NULL, 0, NULL, &n, NULL)) {
3176 ret = (GetLastError() == ERROR_BROKEN_PIPE);
3185is_console(SOCKET sock)
3192 ret = (PeekConsoleInputW((HANDLE)sock, &ir, 1, &n));
3200is_readable_console(SOCKET sock)
3207 if (PeekConsoleInputW((HANDLE)sock, &ir, 1, &n) && n > 0) {
3208 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
3209 ir.Event.KeyEvent.uChar.UnicodeChar) {
3212 else if (ir.EventType == KEY_EVENT && !ir.Event.KeyEvent.bKeyDown &&
3213 ir.Event.KeyEvent.wVirtualKeyCode == VK_MENU &&
3214 ir.Event.KeyEvent.uChar.UnicodeChar) {
3218 ReadConsoleInputW((HANDLE)sock, &ir, 1, &n);
3228is_invalid_handle(SOCKET sock)
3230 return (HANDLE)sock == INVALID_HANDLE_VALUE;
3235do_select(
int nfds, fd_set *rd, fd_set *wr, fd_set *ex,
3242 rb_w32_sleep(timeout->tv_sec * 1000 + timeout->tv_usec / 1000);
3244 rb_w32_sleep(INFINITE);
3248 thread_exclusive(select) {
3249 r = select(nfds, rd, wr, ex, timeout);
3251 if (r == SOCKET_ERROR) {
3252 errno = map_errno(WSAGetLastError());
3267rb_w32_time_subtract(
struct timeval *rest,
const struct timeval *wait)
3269 if (rest->tv_sec < wait->tv_sec) {
3272 while (rest->tv_usec < wait->tv_usec) {
3273 if (rest->tv_sec <= wait->tv_sec) {
3277 rest->tv_usec += 1000 * 1000;
3279 rest->tv_sec -= wait->tv_sec;
3280 rest->tv_usec -= wait->tv_usec;
3281 return rest->tv_sec != 0 || rest->tv_usec != 0;
3288 if (t1->tv_sec < t2->tv_sec)
3290 if (t1->tv_sec > t2->tv_sec)
3292 if (t1->tv_usec < t2->tv_usec)
3294 if (t1->tv_usec > t2->tv_usec)
3301int rb_w32_check_interrupt(
void *);
3306rb_w32_select_with_thread(
int nfds, fd_set *rd, fd_set *wr, fd_set *ex,
3307 struct timeval *timeout,
void *th)
3316 struct timeval limit = {0, 0};
3318 if (nfds < 0 || (timeout && (timeout->tv_sec < 0 || timeout->tv_usec < 0))) {
3324 if (timeout->tv_sec < 0 ||
3325 timeout->tv_usec < 0 ||
3326 timeout->tv_usec >= 1000000) {
3330 gettimeofday(&limit, NULL);
3331 limit.tv_sec += timeout->tv_sec;
3332 limit.tv_usec += timeout->tv_usec;
3333 if (limit.tv_usec >= 1000000) {
3334 limit.tv_usec -= 1000000;
3346 nonsock += extract_fd(&else_rd, rd, is_not_socket);
3349 nonsock += extract_fd(&else_wr, wr, is_not_socket);
3352 if (extract_fd(NULL, else_rd.
fdset, is_invalid_handle) > 0 ||
3353 extract_fd(NULL, else_wr.
fdset, is_invalid_handle) > 0) {
3361 extract_fd(&pipe_rd, else_rd.
fdset, is_pipe);
3364 extract_fd(&cons_rd, else_rd.
fdset, is_console);
3367 extract_fd(&except, ex, is_not_socket);
3370 if (rd && (
int)rd->fd_count > r) r = (int)rd->fd_count;
3371 if (wr && (
int)wr->fd_count > r) r = (int)wr->fd_count;
3372 if (ex && (
int)ex->fd_count > r) r = (int)ex->fd_count;
3373 if (nfds > r) nfds = r;
3377 const struct timeval wait = {0, 10 * 1000};
3380 if (th && rb_w32_check_interrupt(th) != WAIT_TIMEOUT) {
3387 extract_fd(&else_rd, pipe_rd.
fdset, is_readable_pipe);
3388 extract_fd(&else_rd, cons_rd.
fdset, is_readable_console);
3391 if (else_rd.
fdset->fd_count || else_wr.
fdset->fd_count) {
3392 r = do_select(nfds, rd, wr, ex, &zero);
3394 r += copy_fd(rd, else_rd.
fdset);
3395 r += copy_fd(wr, else_wr.
fdset);
3401 const struct timeval *dowait = &wait;
3411 if (rd) copy_fd(&orig_rd, rd);
3412 if (wr) copy_fd(&orig_wr, wr);
3413 if (ex) copy_fd(&orig_ex, ex);
3414 r = do_select(nfds, rd, wr, ex, &zero);
3416 if (rd) copy_fd(rd, &orig_rd);
3417 if (wr) copy_fd(wr, &orig_wr);
3418 if (ex) copy_fd(ex, &orig_ex);
3422 gettimeofday(&now, NULL);
3424 if (!rb_w32_time_subtract(&rest, &now))
break;
3425 if (compare(&rest, &wait) < 0) dowait = &rest;
3427 Sleep(dowait->tv_sec * 1000 + (dowait->tv_usec + 999) / 1000);
3443rb_w32_select(
int nfds, fd_set *rd, fd_set *wr, fd_set *ex,
3446 return rb_w32_select_with_thread(nfds, rd, wr, ex, timeout, 0);
3451get_wsa_extension_function(SOCKET s, GUID guid)
3456 WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, &guid,
sizeof(guid),
3457 &ptr,
sizeof(ptr), &dmy, NULL, NULL);
3467rb_w32_accept(
int s,
struct sockaddr *addr,
int *addrlen)
3473 r = accept(TO_SOCKET(s), addr, addrlen);
3474 if (r != INVALID_SOCKET) {
3475 SetHandleInformation((HANDLE)r, HANDLE_FLAG_INHERIT, 0);
3476 fd = rb_w32_open_osfhandle((intptr_t)r, O_RDWR|O_BINARY|O_NOINHERIT);
3478 socklist_insert(r, 0);
3483 errno = map_errno(WSAGetLastError());
3494rb_w32_bind(
int s,
const struct sockaddr *addr,
int addrlen)
3499 r = bind(TO_SOCKET(s), addr, addrlen);
3500 if (r == SOCKET_ERROR)
3501 errno = map_errno(WSAGetLastError());
3510rb_w32_connect(
int s,
const struct sockaddr *addr,
int addrlen)
3514 r = connect(TO_SOCKET(s), addr, addrlen);
3515 if (r == SOCKET_ERROR) {
3516 int err = WSAGetLastError();
3517 if (err != WSAEWOULDBLOCK)
3518 errno = map_errno(err);
3520 errno = EINPROGRESS;
3531rb_w32_getpeername(
int s,
struct sockaddr *addr,
int *addrlen)
3535 r = getpeername(TO_SOCKET(s), addr, addrlen);
3536 if (r == SOCKET_ERROR)
3537 errno = map_errno(WSAGetLastError());
3546rb_w32_getsockname(
int fd,
struct sockaddr *addr,
int *addrlen)
3551 sock = TO_SOCKET(fd);
3552 r = getsockname(sock, addr, addrlen);
3553 if (r == SOCKET_ERROR) {
3554 DWORD wsaerror = WSAGetLastError();
3555 if (wsaerror == WSAEINVAL) {
3557 if (socklist_lookup(sock, &flags)) {
3558 int af = GET_FAMILY(flags);
3560 memset(addr, 0, *addrlen);
3561 addr->sa_family = af;
3566 errno = map_errno(wsaerror);
3576rb_w32_getsockopt(
int s,
int level,
int optname,
char *optval,
int *optlen)
3580 r = getsockopt(TO_SOCKET(s), level, optname, optval, optlen);
3581 if (r == SOCKET_ERROR)
3582 errno = map_errno(WSAGetLastError());
3591rb_w32_ioctlsocket(
int s,
long cmd, u_long *argp)
3595 r = ioctlsocket(TO_SOCKET(s), cmd, argp);
3596 if (r == SOCKET_ERROR)
3597 errno = map_errno(WSAGetLastError());
3606rb_w32_listen(
int s,
int backlog)
3610 r = listen(TO_SOCKET(s), backlog);
3611 if (r == SOCKET_ERROR)
3612 errno = map_errno(WSAGetLastError());
3624finish_overlapped_socket(BOOL input, SOCKET s, WSAOVERLAPPED *wol,
int result, DWORD *
len, DWORD size)
3629 if (result != SOCKET_ERROR)
3631 else if ((err = WSAGetLastError()) == WSA_IO_PENDING) {
3632 switch (rb_w32_wait_events_blocking(&wol->hEvent, 1, INFINITE)) {
3635 result = WSAGetOverlappedResult(s, wol, &size, TRUE, &flg);
3642 result = SOCKET_ERROR;
3645 if ((err = WSAGetLastError()) == WSAECONNABORTED && !input)
3647 else if (err == WSAEMSGSIZE && input) {
3653 errno = map_errno(err);
3655 case WAIT_OBJECT_0 + 1:
3658 CancelIo((HANDLE)s);
3663 if (err == WSAECONNABORTED && !input)
3666 errno = map_errno(err);
3669 CloseHandle(wol->hEvent);
3676overlapped_socket_io(BOOL input,
int fd,
char *buf,
int len,
int flags,
3677 struct sockaddr *addr,
int *addrlen)
3688 socklist_lookup(s, &mode);
3689 if (GET_FLAGS(mode) & O_NONBLOCK) {
3692 if (addr && addrlen)
3693 r = recvfrom(s, buf,
len, flags, addr, addrlen);
3695 r = recv(s, buf,
len, flags);
3696 if (r == SOCKET_ERROR)
3697 errno = map_errno(WSAGetLastError());
3700 if (addr && addrlen)
3701 r = sendto(s, buf,
len, flags, addr, *addrlen);
3703 r = send(s, buf,
len, flags);
3704 if (r == SOCKET_ERROR) {
3705 DWORD err = WSAGetLastError();
3706 if (err == WSAECONNABORTED)
3709 errno = map_errno(err);
3719 memset(&wol, 0,
sizeof(wol));
3721 wol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3724 if (addr && addrlen)
3725 ret = WSARecvFrom(s, &wbuf, 1, &size, &flg, addr, addrlen,
3728 ret = WSARecv(s, &wbuf, 1, &size, &flg, &wol, NULL);
3731 if (addr && addrlen)
3732 ret = WSASendTo(s, &wbuf, 1, &size, flags, addr, *addrlen,
3735 ret = WSASend(s, &wbuf, 1, &size, flags, &wol, NULL);
3739 finish_overlapped_socket(input, s, &wol, ret, &rlen, size);
3748rb_w32_recv(
int fd,
char *buf,
int len,
int flags)
3750 return overlapped_socket_io(TRUE, fd, buf,
len, flags, NULL, NULL);
3755rb_w32_recvfrom(
int fd,
char *buf,
int len,
int flags,
3756 struct sockaddr *from,
int *fromlen)
3758 return overlapped_socket_io(TRUE, fd, buf,
len, flags, from, fromlen);
3763rb_w32_send(
int fd,
const char *buf,
int len,
int flags)
3765 return overlapped_socket_io(FALSE, fd, (
char *)buf,
len, flags, NULL, NULL);
3770rb_w32_sendto(
int fd,
const char *buf,
int len,
int flags,
3771 const struct sockaddr *to,
int tolen)
3773 return overlapped_socket_io(FALSE, fd, (
char *)buf,
len, flags,
3774 (
struct sockaddr *)to, &tolen);
3777#if !defined(MSG_TRUNC) && !defined(__MINGW32__)
3783 DWORD dwBufferCount;
3788#ifndef WSAID_WSARECVMSG
3789#define WSAID_WSARECVMSG {0xf689d7c8,0x6f1f,0x436b,{0x8a,0x53,0xe5,0x4f,0xe3,0x51,0xc3,0x22}}
3791#ifndef WSAID_WSASENDMSG
3792#define WSAID_WSASENDMSG {0xa441e712,0x754f,0x43ca,{0x84,0xa7,0x0d,0xee,0x44,0xcf,0x60,0x6d}}
3796#define msghdr_to_wsamsg(msg, wsamsg) \
3799 (wsamsg)->name = (msg)->msg_name; \
3800 (wsamsg)->namelen = (msg)->msg_namelen; \
3801 (wsamsg)->lpBuffers = ALLOCA_N(WSABUF, (msg)->msg_iovlen); \
3802 (wsamsg)->dwBufferCount = (msg)->msg_iovlen; \
3803 for (i = 0; i < (msg)->msg_iovlen; ++i) { \
3804 (wsamsg)->lpBuffers[i].buf = (msg)->msg_iov[i].iov_base; \
3805 (wsamsg)->lpBuffers[i].len = (msg)->msg_iov[i].iov_len; \
3807 (wsamsg)->Control.buf = (msg)->msg_control; \
3808 (wsamsg)->Control.len = (msg)->msg_controllen; \
3809 (wsamsg)->dwFlags = (msg)->msg_flags; \
3814recvmsg(
int fd,
struct msghdr *msg,
int flags)
3816 typedef int (WSAAPI *WSARecvMsg_t)(SOCKET,
WSAMSG *, DWORD *, WSAOVERLAPPED *, LPWSAOVERLAPPED_COMPLETION_ROUTINE);
3817 static WSARecvMsg_t pWSARecvMsg = NULL;
3827 static const GUID guid = WSAID_WSARECVMSG;
3828 pWSARecvMsg = (WSARecvMsg_t)get_wsa_extension_function(s, guid);
3833 msghdr_to_wsamsg(msg, &wsamsg);
3834 wsamsg.dwFlags |= flags;
3836 socklist_lookup(s, &mode);
3837 if (GET_FLAGS(mode) & O_NONBLOCK) {
3839 if ((ret = pWSARecvMsg(s, &wsamsg, &
len, NULL, NULL)) == SOCKET_ERROR) {
3840 errno = map_errno(WSAGetLastError());
3848 memset(&wol, 0,
sizeof(wol));
3850 wol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3851 ret = pWSARecvMsg(s, &wsamsg, &size, &wol, NULL);
3854 ret = finish_overlapped_socket(TRUE, s, &wol, ret, &
len, size);
3856 if (ret == SOCKET_ERROR)
3860 msg->msg_name = wsamsg.name;
3861 msg->msg_namelen = wsamsg.namelen;
3862 msg->msg_flags = wsamsg.dwFlags;
3869sendmsg(
int fd,
const struct msghdr *msg,
int flags)
3871 typedef int (WSAAPI *WSASendMsg_t)(SOCKET,
const WSAMSG *, DWORD, DWORD *, WSAOVERLAPPED *, LPWSAOVERLAPPED_COMPLETION_ROUTINE);
3872 static WSASendMsg_t pWSASendMsg = NULL;
3882 static const GUID guid = WSAID_WSASENDMSG;
3883 pWSASendMsg = (WSASendMsg_t)get_wsa_extension_function(s, guid);
3888 msghdr_to_wsamsg(msg, &wsamsg);
3890 socklist_lookup(s, &mode);
3891 if (GET_FLAGS(mode) & O_NONBLOCK) {
3893 if ((ret = pWSASendMsg(s, &wsamsg, flags, &
len, NULL, NULL)) == SOCKET_ERROR) {
3894 errno = map_errno(WSAGetLastError());
3902 memset(&wol, 0,
sizeof(wol));
3904 wol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3905 ret = pWSASendMsg(s, &wsamsg, flags, &size, &wol, NULL);
3908 finish_overlapped_socket(FALSE, s, &wol, ret, &
len, size);
3918rb_w32_setsockopt(
int s,
int level,
int optname,
const char *optval,
int optlen)
3922 r = setsockopt(TO_SOCKET(s), level, optname, optval, optlen);
3923 if (r == SOCKET_ERROR)
3924 errno = map_errno(WSAGetLastError());
3933rb_w32_shutdown(
int s,
int how)
3937 r = shutdown(TO_SOCKET(s), how);
3938 if (r == SOCKET_ERROR)
3939 errno = map_errno(WSAGetLastError());
3946open_ifs_socket(
int af,
int type,
int protocol)
3948 unsigned long proto_buffers_len = 0;
3950 SOCKET out = INVALID_SOCKET;
3952 if (WSAEnumProtocols(NULL, NULL, &proto_buffers_len) == SOCKET_ERROR) {
3953 error_code = WSAGetLastError();
3954 if (error_code == WSAENOBUFS) {
3955 WSAPROTOCOL_INFO *proto_buffers;
3956 int protocols_available = 0;
3958 proto_buffers = (WSAPROTOCOL_INFO *)malloc(proto_buffers_len);
3959 if (!proto_buffers) {
3960 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
3961 return INVALID_SOCKET;
3964 protocols_available =
3965 WSAEnumProtocols(NULL, proto_buffers, &proto_buffers_len);
3966 if (protocols_available != SOCKET_ERROR) {
3968 for (i = 0; i < protocols_available; i++) {
3969 if ((af != AF_UNSPEC && af != proto_buffers[i].iAddressFamily) ||
3970 (
type != proto_buffers[i].iSocketType) ||
3971 (protocol != 0 && protocol != proto_buffers[i].iProtocol))
3974 if ((proto_buffers[i].dwServiceFlags1 & XP1_IFS_HANDLES) == 0)
3977 out = WSASocket(af,
type, protocol, &(proto_buffers[i]), 0,
3978 WSA_FLAG_OVERLAPPED);
3981 if (out == INVALID_SOCKET)
3982 out = WSASocket(af,
type, protocol, NULL, 0, 0);
3983 if (out != INVALID_SOCKET)
3984 SetHandleInformation((HANDLE)out, HANDLE_FLAG_INHERIT, 0);
3987 free(proto_buffers);
3998rb_w32_socket(
int af,
int type,
int protocol)
4004 s = open_ifs_socket(af,
type, protocol);
4005 if (s == INVALID_SOCKET) {
4006 errno = map_errno(WSAGetLastError());
4010 fd = rb_w32_open_osfhandle(s, O_RDWR|O_BINARY|O_NOINHERIT);
4012 socklist_insert(s, MAKE_SOCKDATA(af, 0));
4023struct hostent * WSAAPI
4024rb_w32_gethostbyaddr(
const char *addr,
int len,
int type)
4028 r = gethostbyaddr(addr,
len,
type);
4030 errno = map_errno(WSAGetLastError());
4038struct hostent * WSAAPI
4039rb_w32_gethostbyname(
const char *name)
4043 r = gethostbyname(name);
4045 errno = map_errno(WSAGetLastError());
4054rb_w32_gethostname(
char *name,
int len)
4058 r = gethostname(name,
len);
4059 if (r == SOCKET_ERROR)
4060 errno = map_errno(WSAGetLastError());
4065#undef getprotobyname
4068struct protoent * WSAAPI
4069rb_w32_getprotobyname(
const char *name)
4073 r = getprotobyname(name);
4075 errno = map_errno(WSAGetLastError());
4080#undef getprotobynumber
4083struct protoent * WSAAPI
4084rb_w32_getprotobynumber(
int num)
4088 r = getprotobynumber(num);
4090 errno = map_errno(WSAGetLastError());
4098struct servent * WSAAPI
4099rb_w32_getservbyname(
const char *name,
const char *proto)
4103 r = getservbyname(name, proto);
4105 errno = map_errno(WSAGetLastError());
4113struct servent * WSAAPI
4114rb_w32_getservbyport(
int port,
const char *proto)
4118 r = getservbyport(port, proto);
4120 errno = map_errno(WSAGetLastError());
4129socketpair_unix_path(
struct sockaddr_un *sock_un)
4132 WCHAR wpath[
sizeof(sock_un->sun_path)/
sizeof(*sock_un->sun_path)] = L
"";
4137 listener = socket(AF_UNIX, SOCK_STREAM, 0);
4138 if (listener == INVALID_SOCKET)
4141 memset(sock_un, 0,
sizeof(*sock_un));
4142 sock_un->sun_family = AF_UNIX;
4152 for (
int try = 0; ;
try++) {
4153 LARGE_INTEGER ticks;
4154 size_t path_len = 0;
4155 const size_t maxpath =
sizeof(sock_un->sun_path)/
sizeof(*sock_un->sun_path);
4160 path_len = GetTempPathW(maxpath, wpath);
4163 wcsncpy(wpath, L
"C:/Temp/", maxpath);
4164 path_len = lstrlenW(wpath);
4171 closesocket(listener);
4176 path_len = WideCharToMultiByte(CP_UTF8, 0, wpath, path_len, sock_un->sun_path, maxpath, NULL, NULL);
4177 QueryPerformanceCounter(&ticks);
4178 path_len += snprintf(sock_un->sun_path + path_len,
4182 GetCurrentProcessId());
4185 MultiByteToWideChar(CP_UTF8, 0, sock_un->sun_path, -1, wpath,
sizeof(wpath)/
sizeof(*wpath));
4187 if (bind(listener, (
struct sockaddr *)sock_un,
sizeof(*sock_un)) != SOCKET_ERROR)
4190 closesocket(listener);
4192 return sizeof(*sock_un);
4198socketpair_internal(
int af,
int type,
int protocol, SOCKET *sv)
4200 SOCKET svr = INVALID_SOCKET, r = INVALID_SOCKET, w = INVALID_SOCKET;
4201 struct sockaddr_in sock_in4;
4204 struct sockaddr_in6 sock_in6;
4208 struct sockaddr_un sock_un = {0, {0}};
4209 WCHAR wpath[
sizeof(sock_un.sun_path)/
sizeof(*sock_un.sun_path)] = L
"";
4212 struct sockaddr *addr;
4218#if defined PF_INET && PF_INET != AF_INET
4221 sock_in4.sin_family = AF_INET;
4222 sock_in4.sin_port = 0;
4223 sock_in4.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4224 addr = (
struct sockaddr *)&sock_in4;
4225 len =
sizeof(sock_in4);
4229 memset(&sock_in6, 0,
sizeof(sock_in6));
4230 sock_in6.sin6_family = AF_INET6;
4231 sock_in6.sin6_addr = IN6ADDR_LOOPBACK_INIT;
4232 addr = (
struct sockaddr *)&sock_in6;
4233 len =
sizeof(sock_in6);
4238 addr = (
struct sockaddr *)&sock_un;
4239 len = socketpair_unix_path(&sock_un);
4240 MultiByteToWideChar(CP_UTF8, 0, sock_un.sun_path, -1, wpath,
sizeof(wpath)/
sizeof(*wpath));
4246 errno = EAFNOSUPPORT;
4249 if (
type != SOCK_STREAM) {
4254 sv[0] = (SOCKET)INVALID_HANDLE_VALUE;
4255 sv[1] = (SOCKET)INVALID_HANDLE_VALUE;
4258 svr = open_ifs_socket(af,
type, protocol);
4259 if (svr == INVALID_SOCKET)
4261 if (bind(svr, addr,
len) < 0)
4263 if (getsockname(svr, addr, &
len) < 0)
4265 if (
type == SOCK_STREAM)
4268 w = open_ifs_socket(af,
type, protocol);
4269 if (w == INVALID_SOCKET)
4271 if (connect(w, addr,
len) < 0)
4274 r = accept(svr, addr, &
len);
4275 if (r == INVALID_SOCKET)
4277 SetHandleInformation((HANDLE)r, HANDLE_FLAG_INHERIT, 0);
4283 errno = map_errno(WSAGetLastError());
4284 if (r != INVALID_SOCKET)
4286 if (w != INVALID_SOCKET)
4293 if (svr != INVALID_SOCKET)
4296 if (sock_un.sun_family == AF_UNIX)
4306socketpair(
int af,
int type,
int protocol,
int *sv)
4310 if (socketpair_internal(af,
type, protocol, pair) < 0)
4312 sv[0] = rb_w32_open_osfhandle(pair[0], O_RDWR|O_BINARY|O_NOINHERIT);
4314 closesocket(pair[0]);
4315 closesocket(pair[1]);
4318 sv[1] = rb_w32_open_osfhandle(pair[1], O_RDWR|O_BINARY|O_NOINHERIT);
4320 rb_w32_close(sv[0]);
4321 closesocket(pair[1]);
4324 socklist_insert(pair[0], MAKE_SOCKDATA(af, 0));
4325 socklist_insert(pair[1], MAKE_SOCKDATA(af, 0));
4330#if !defined(_MSC_VER) || _MSC_VER >= 1400
4333str2guid(
const char *str, GUID *guid)
4335#define hex2byte(str) \
4336 ((isdigit(*(str)) ? *(str) - '0' : toupper(*(str)) - 'A' + 10) << 4 | (isdigit(*((str) + 1)) ? *((str) + 1) - '0' : toupper(*((str) + 1)) - 'A' + 10))
4339 if (*str ==
'{') str++;
4340 guid->Data1 = (long)strtoul(str, &end, 16);
4342 guid->Data2 = (
unsigned short)strtoul(str, &end, 16);
4344 guid->Data3 = (
unsigned short)strtoul(str, &end, 16);
4346 guid->Data4[0] = hex2byte(str);
4348 guid->Data4[1] = hex2byte(str);
4350 for (i = 0; i < 6; i++) {
4351 guid->Data4[i + 2] = hex2byte(str);
4357#ifndef HAVE_TYPE_NET_LUID
4361 uint64_t Reserved :24;
4362 uint64_t NetLuidIndex :24;
4363 uint64_t IfType :16;
4367typedef DWORD (WINAPI *cigl_t)(
const GUID *,
NET_LUID *);
4368typedef DWORD (WINAPI *cilnA_t)(
const NET_LUID *,
char *, size_t);
4369static cigl_t pConvertInterfaceGuidToLuid = (cigl_t)-1;
4370static cilnA_t pConvertInterfaceLuidToNameA = (cilnA_t)-1;
4373getifaddrs(
struct ifaddrs **ifap)
4377 IP_ADAPTER_ADDRESSES *root, *addr;
4380 ret = GetAdaptersAddresses(AF_UNSPEC, 0, NULL, NULL, &size);
4381 if (ret != ERROR_BUFFER_OVERFLOW) {
4382 errno = map_errno(ret);
4385 root = ruby_xmalloc(size);
4386 ret = GetAdaptersAddresses(AF_UNSPEC, 0, NULL, root, &size);
4387 if (ret != ERROR_SUCCESS) {
4388 errno = map_errno(ret);
4393 if (pConvertInterfaceGuidToLuid == (cigl_t)-1)
4394 pConvertInterfaceGuidToLuid =
4395 (cigl_t)get_proc_address(
"iphlpapi.dll",
4396 "ConvertInterfaceGuidToLuid", NULL);
4397 if (pConvertInterfaceLuidToNameA == (cilnA_t)-1)
4398 pConvertInterfaceLuidToNameA =
4399 (cilnA_t)get_proc_address(
"iphlpapi.dll",
4400 "ConvertInterfaceLuidToNameA", NULL);
4402 for (prev = NULL, addr = root; addr; addr = addr->Next) {
4403 struct ifaddrs *ifa = ruby_xcalloc(1,
sizeof(*ifa));
4404 char name[IFNAMSIZ];
4409 prev->ifa_next = ifa;
4413 str2guid(addr->AdapterName, &guid);
4414 if (pConvertInterfaceGuidToLuid && pConvertInterfaceLuidToNameA &&
4415 pConvertInterfaceGuidToLuid(&guid, &luid) == NO_ERROR &&
4416 pConvertInterfaceLuidToNameA(&luid, name,
sizeof(name)) == NO_ERROR) {
4423 if (addr->IfType & IF_TYPE_SOFTWARE_LOOPBACK)
4424 ifa->ifa_flags |= IFF_LOOPBACK;
4425 if (addr->OperStatus == IfOperStatusUp) {
4426 ifa->ifa_flags |= IFF_UP;
4428 if (addr->FirstUnicastAddress) {
4429 IP_ADAPTER_UNICAST_ADDRESS *cur;
4431 for (cur = addr->FirstUnicastAddress; cur; cur = cur->Next) {
4432 if (cur->Flags & IP_ADAPTER_ADDRESS_TRANSIENT ||
4433 cur->DadState == IpDadStateDeprecated) {
4438 ifa = ruby_xcalloc(1,
sizeof(*ifa));
4439 prev->ifa_next = ifa;
4441 ifa->ifa_flags = prev->ifa_flags;
4443 ifa->ifa_addr = ruby_xmalloc(cur->Address.iSockaddrLength);
4444 memcpy(ifa->ifa_addr, cur->Address.lpSockaddr,
4445 cur->Address.iSockaddrLength);
4460freeifaddrs(
struct ifaddrs *ifp)
4463 struct ifaddrs *next = ifp->ifa_next;
4464 ruby_xfree(ifp->ifa_addr);
4465 ruby_xfree(ifp->ifa_name);
4477void endhostent(
void) {}
4478void endnetent(
void) {}
4479void endprotoent(
void) {}
4480void endservent(
void) {}
4482struct netent *getnetent (
void) {
return (
struct netent *) NULL;}
4484struct netent *getnetbyaddr(
long net,
int type) {
return (
struct netent *)NULL;}
4486struct netent *getnetbyname(
const char *name) {
return (
struct netent *)NULL;}
4488struct protoent *getprotoent (
void) {
return (
struct protoent *) NULL;}
4490struct servent *getservent (
void) {
return (
struct servent *) NULL;}
4492void sethostent (
int stayopen) {}
4494void setnetent (
int stayopen) {}
4496void setprotoent (
int stayopen) {}
4498void setservent (
int stayopen) {}
4501int rb_w32_set_nonblock2(
int fd,
int nonblock);
4505setfl(SOCKET sock,
int arg)
4512 socklist_lookup(sock, &flag);
4513 af = GET_FAMILY(flag);
4514 flag = GET_FLAGS(flag);
4515 if (arg & O_NONBLOCK) {
4520 flag &= ~O_NONBLOCK;
4524 ret = ioctlsocket(sock, FIONBIO, &ioctlArg);
4526 socklist_insert(sock, MAKE_SOCKDATA(af, flag));
4528 errno = map_errno(WSAGetLastError());
4536dupfd(HANDLE hDup,
int flags,
int minfd)
4544 ret = _open_osfhandle((intptr_t)hDup, flags | FOPEN);
4546 goto close_fds_and_return;
4549 goto close_fds_and_return;
4551 fds[filled++] = ret;
4552 }
while (filled < (
int)numberof(fds));
4554 ret = dupfd(hDup, flags, minfd);
4556 close_fds_and_return:
4558 while (filled > 0) {
4559 int fd = fds[--filled];
4560 _set_osfhnd(fd, (intptr_t)INVALID_HANDLE_VALUE);
4570fcntl(
int fd,
int cmd, ...)
4579 arg = va_arg(va,
int);
4581 return rb_w32_set_nonblock2(fd, arg);
4583 case F_DUPFD:
case F_DUPFD_CLOEXEC: {
4587 if (!(DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
4588 GetCurrentProcess(), &hDup, 0L,
4589 cmd == F_DUPFD && !(flag & FNOINHERIT),
4590 DUPLICATE_SAME_ACCESS))) {
4591 errno = map_errno(GetLastError());
4596 arg = va_arg(va,
int);
4602 flag &= ~FNOINHERIT;
4603 if ((ret = dupfd(hDup, flag, arg)) == -1)
4609 if (h == -1)
return -1;
4610 if (!GetHandleInformation((HANDLE)h, &flag)) {
4611 errno = map_errno(GetLastError());
4614 return (flag & HANDLE_FLAG_INHERIT) ? 0 : FD_CLOEXEC;
4618 if (h == -1)
return -1;
4620 arg = va_arg(va,
int);
4622 if (!SetHandleInformation((HANDLE)h, HANDLE_FLAG_INHERIT,
4623 (arg & FD_CLOEXEC) ? 0 : HANDLE_FLAG_INHERIT)) {
4624 errno = map_errno(GetLastError());
4627 if (arg & FD_CLOEXEC)
4628 _osfile(fd) |= FNOINHERIT;
4630 _osfile(fd) &= ~FNOINHERIT;
4641rb_w32_set_nonblock2(
int fd,
int nonblock)
4643 SOCKET sock = TO_SOCKET(fd);
4644 if (is_socket(sock)) {
4645 return setfl(sock, nonblock ? O_NONBLOCK : 0);
4647 else if (is_pipe(sock)) {
4649 if (!GetNamedPipeHandleState((HANDLE)sock, &state, NULL, NULL, NULL, NULL, 0)) {
4650 errno = map_errno(GetLastError());
4654 state |= PIPE_NOWAIT;
4657 state &= ~PIPE_NOWAIT;
4659 if (!SetNamedPipeHandleState((HANDLE)sock, &state, NULL, NULL)) {
4660 errno = map_errno(GetLastError());
4672rb_w32_set_nonblock(
int fd)
4674 return rb_w32_set_nonblock2(fd, TRUE);
4683poll_child_status(
struct ChildRecord *child,
int *stat_loc)
4688 if (!GetExitCodeProcess(child->hProcess, &exitcode)) {
4690 err = GetLastError();
4692 case ERROR_INVALID_PARAMETER:
4695 case ERROR_INVALID_HANDLE:
4699 errno = map_errno(err);
4703 CloseChildHandle(child);
4706 if (exitcode != STILL_ACTIVE) {
4709 if (rb_w32_wait_events_blocking(&child->hProcess, 1, INFINITE) != WAIT_OBJECT_0) {
4713 CloseChildHandle(child);
4715 *stat_loc = exitcode << 8;
4716 if (exitcode & 0xC0000000) {
4717 static const struct {
4721 {STATUS_ACCESS_VIOLATION, SIGSEGV},
4722 {STATUS_ILLEGAL_INSTRUCTION, SIGILL},
4723 {STATUS_PRIVILEGED_INSTRUCTION, SIGILL},
4724 {STATUS_FLOAT_DENORMAL_OPERAND, SIGFPE},
4725 {STATUS_FLOAT_DIVIDE_BY_ZERO, SIGFPE},
4726 {STATUS_FLOAT_INEXACT_RESULT, SIGFPE},
4727 {STATUS_FLOAT_INVALID_OPERATION, SIGFPE},
4728 {STATUS_FLOAT_OVERFLOW, SIGFPE},
4729 {STATUS_FLOAT_STACK_CHECK, SIGFPE},
4730 {STATUS_FLOAT_UNDERFLOW, SIGFPE},
4731#ifdef STATUS_FLOAT_MULTIPLE_FAULTS
4732 {STATUS_FLOAT_MULTIPLE_FAULTS, SIGFPE},
4734#ifdef STATUS_FLOAT_MULTIPLE_TRAPS
4735 {STATUS_FLOAT_MULTIPLE_TRAPS, SIGFPE},
4737 {STATUS_CONTROL_C_EXIT, SIGINT},
4740 for (i = 0; i < (int)numberof(table); i++) {
4741 if (table[i].status == exitcode) {
4742 *stat_loc |= table[i].sig;
4747 if (i >= (
int)numberof(table))
4748 *stat_loc |= SIGSEGV;
4758waitpid(rb_pid_t pid,
int *stat_loc,
int options)
4763 if (options == WNOHANG) {
4774 HANDLE events[MAXCHILDNUM];
4777 FOREACH_CHILD(child) {
4778 if (!child->pid || child->pid < 0)
continue;
4779 if ((pid = poll_child_status(child, stat_loc)))
return pid;
4780 events[count++] = child->hProcess;
4781 } END_FOREACH_CHILD;
4787 ret = rb_w32_wait_events_blocking(events, count, timeout);
4788 if (ret == WAIT_TIMEOUT)
return 0;
4789 if ((ret -= WAIT_OBJECT_0) == count) {
4793 errno = map_errno(GetLastError());
4797 cause = FindChildSlotByHandle(events[ret]);
4802 return poll_child_status(cause, stat_loc);
4812 while (!(pid = poll_child_status(child, stat_loc))) {
4814 int ret = rb_w32_wait_events_blocking(&child->hProcess, 1, timeout);
4815 if (ret == WAIT_OBJECT_0 + 1)
return -1;
4816 if (ret != WAIT_OBJECT_0) {
4818 if (options & WNOHANG) {
4825 if (pid == -1 && retried) pid = 0;
4831#include <sys/timeb.h>
4833static int have_precisetime = -1;
4836get_systemtime(FILETIME *ft)
4838 typedef void (WINAPI *get_time_func)(FILETIME *ft);
4839 static get_time_func func = (get_time_func)-1;
4841 if (func == (get_time_func)-1) {
4843 func = (get_time_func)get_proc_address(
"kernel32",
"GetSystemTimePreciseAsFileTime", NULL);
4845 func = GetSystemTimeAsFileTime;
4846 have_precisetime = 0;
4849 have_precisetime = 1;
4858filetime_split(
const FILETIME* ft,
long *subsec)
4864 tmp.LowPart = ft->dwLowDateTime;
4865 tmp.HighPart = ft->dwHighDateTime;
4872 lt -= (
LONG_LONG)((1970-1601)*365.2425) * 24 * 60 * 60 * subsec_unit;
4874 *subsec = (long)(lt % subsec_unit);
4875 return (time_t)(lt / subsec_unit);
4885 get_systemtime(&ft);
4886 tv->tv_sec = filetime_split(&ft, &subsec);
4887 tv->tv_usec = subsec / 10;
4894clock_gettime(clockid_t clock_id,
struct timespec *sp)
4897 case CLOCK_REALTIME:
4902 get_systemtime(&ft);
4903 sp->tv_sec = filetime_split(&ft, &subsec);
4904 sp->tv_nsec = subsec * 100;
4907 case CLOCK_MONOTONIC:
4910 LARGE_INTEGER count;
4911 if (!QueryPerformanceFrequency(&freq)) {
4912 errno = map_errno(GetLastError());
4915 if (!QueryPerformanceCounter(&count)) {
4916 errno = map_errno(GetLastError());
4919 sp->tv_sec = count.QuadPart / freq.QuadPart;
4920 if (freq.QuadPart < 1000000000)
4921 sp->tv_nsec = (count.QuadPart % freq.QuadPart) * 1000000000 / freq.QuadPart;
4923 sp->tv_nsec = (long)((count.QuadPart % freq.QuadPart) * (1000000000.0 / freq.QuadPart));
4934clock_getres(clockid_t clock_id,
struct timespec *sp)
4937 case CLOCK_REALTIME:
4943 case CLOCK_MONOTONIC:
4946 if (!QueryPerformanceFrequency(&freq)) {
4947 errno = map_errno(GetLastError());
4951 sp->tv_nsec = (long)(1000000000.0 / freq.QuadPart);
4962w32_getcwd(
char *buffer,
int size, UINT cp,
void *alloc(
int,
void *),
void *arg)
4967 len = GetCurrentDirectoryW(0, NULL);
4969 errno = map_errno(GetLastError());
4973 if (buffer && size <
len) {
4979 if (!GetCurrentDirectoryW(
len, p)) {
4980 errno = map_errno(GetLastError());
4984 wlen = translate_wchar(p, L
'\\', L
'/') - p + 1;
4985 len = WideCharToMultiByte(cp, 0, p, wlen, NULL, 0, NULL, NULL);
4993 buffer = (*alloc)(
len, arg);
4999 WideCharToMultiByte(cp, 0, p, wlen, buffer,
len, NULL, NULL);
5006getcwd_alloc(
int size,
void *dummy)
5008 return malloc(size);
5013rb_w32_getcwd(
char *buffer,
int size)
5015 return w32_getcwd(buffer, size, filecp(), getcwd_alloc, NULL);
5020rb_w32_ugetcwd(
char *buffer,
int size)
5022 return w32_getcwd(buffer, size, CP_UTF8, getcwd_alloc, NULL);
5027getcwd_value(
int size,
void *arg)
5030 return RSTRING_PTR(str);
5035rb_dir_getwd_ospath(
void)
5038 w32_getcwd(NULL, 0, CP_UTF8, getcwd_value, &cwd);
5044chown(
const char *path,
int owner,
int group)
5051rb_w32_uchown(
const char *path,
int owner,
int group)
5057lchown(
const char *path,
int owner,
int group)
5063rb_w32_ulchown(
const char *path,
int owner,
int group)
5070kill(rb_pid_t pid,
int sig)
5075 if (pid < 0 || (pid == 0 && sig != SIGINT)) {
5080 if ((
unsigned int)pid == GetCurrentProcessId() &&
5081 (sig != 0 && sig != SIGKILL)) {
5082 if ((ret = raise(sig)) != 0) {
5093 OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, (DWORD)pid);
5094 if (hProc == NULL || hProc == INVALID_HANDLE_VALUE) {
5095 if (GetLastError() == ERROR_INVALID_PARAMETER) {
5111 DWORD ctrlEvent = CTRL_C_EVENT;
5115 ctrlEvent = CTRL_BREAK_EVENT;
5117 if (!GenerateConsoleCtrlEvent(ctrlEvent, (DWORD)pid)) {
5118 if ((err = GetLastError()) == 0)
5121 errno = map_errno(GetLastError());
5132 hProc = child->hProcess;
5135 hProc = OpenProcess(PROCESS_TERMINATE | PROCESS_QUERY_INFORMATION, FALSE, (DWORD)pid);
5137 if (hProc == NULL || hProc == INVALID_HANDLE_VALUE) {
5138 if (GetLastError() == ERROR_INVALID_PARAMETER) {
5148 if (!GetExitCodeProcess(hProc, &status)) {
5149 errno = map_errno(GetLastError());
5152 else if (status == STILL_ACTIVE) {
5153 if (!TerminateProcess(hProc, 0)) {
5180wlink(
const WCHAR *from,
const WCHAR *to)
5182 if (!CreateHardLinkW(to, from, NULL)) {
5183 errno = map_errno(GetLastError());
5192rb_w32_ulink(
const char *from,
const char *to)
5198 if (!(wfrom = utf8_to_wstr(from, NULL)))
5200 if (!(wto = utf8_to_wstr(to, NULL))) {
5204 ret = wlink(wfrom, wto);
5212link(
const char *from,
const char *to)
5218 if (!(wfrom = filecp_to_wstr(from, NULL)))
5220 if (!(wto = filecp_to_wstr(to, NULL))) {
5224 ret = wlink(wfrom, wto);
5231#ifndef FILE_DEVICE_FILE_SYSTEM
5232# define FILE_DEVICE_FILE_SYSTEM 0x00000009
5234#ifndef FSCTL_GET_REPARSE_POINT
5235# define FSCTL_GET_REPARSE_POINT ((0x9<<16)|(42<<2))
5237#ifndef IO_REPARSE_TAG_SYMLINK
5238# define IO_REPARSE_TAG_SYMLINK 0xA000000CL
5249 f = open_special(path, 0, FILE_FLAG_OPEN_REPARSE_POINT);
5250 if (f == INVALID_HANDLE_VALUE) {
5251 return GetLastError();
5254 if (!DeviceIoControl(f, FSCTL_GET_REPARSE_POINT, NULL, 0,
5255 rp, size, &ret, NULL)) {
5258 else if (rp->ReparseTag != IO_REPARSE_TAG_SYMLINK &&
5259 rp->ReparseTag != IO_REPARSE_TAG_MOUNT_POINT) {
5260 e = ERROR_INVALID_PARAMETER;
5268rb_w32_reparse_symlink_p(
const WCHAR *path)
5276 e = rb_w32_read_reparse_point(path, rp,
sizeof(rbuf), &wbuf, &
len);
5277 if (e == ERROR_MORE_DATA) {
5278 size_t size = rb_w32_reparse_buffer_size(
len + 1);
5280 e = rb_w32_read_reparse_point(path, rp, size, &wbuf, &
len);
5285 case ERROR_MORE_DATA:
5294 size_t bufsize, WCHAR **result, DWORD *
len)
5296 int e = reparse_symlink(path, rp, bufsize);
5299 if (!e || e == ERROR_MORE_DATA) {
5301 if (rp->ReparseTag == IO_REPARSE_TAG_SYMLINK) {
5302 name = ((
char *)rp->SymbolicLinkReparseBuffer.PathBuffer +
5303 rp->SymbolicLinkReparseBuffer.PrintNameOffset);
5304 ret = rp->SymbolicLinkReparseBuffer.PrintNameLength;
5305 *
len = ret /
sizeof(WCHAR);
5307 else if (rp->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT) {
5308 static const WCHAR volume[] = L
"Volume{";
5310 name = ((
char *)rp->MountPointReparseBuffer.PathBuffer +
5311 rp->MountPointReparseBuffer.SubstituteNameOffset +
5312 volume_prefix_len *
sizeof(WCHAR));
5313 ret = rp->MountPointReparseBuffer.SubstituteNameLength;
5314 *
len = ret /
sizeof(WCHAR);
5315 ret -= volume_prefix_len *
sizeof(WCHAR);
5316 if (ret >
sizeof(volume) - 1 *
sizeof(WCHAR) &&
5317 memcmp(name, volume,
sizeof(volume) - 1 *
sizeof(WCHAR)) == 0)
5325 if ((
char *)name + ret +
sizeof(WCHAR) > (
char *)rp + bufsize)
5329 ((WCHAR *)name)[ret/
sizeof(WCHAR)] = L
'\0';
5330 translate_wchar(name, L
'\\', L
'/');
5340w32_readlink(UINT cp,
const char *path,
char *buf,
size_t bufsize)
5342 VALUE rp_buf, rp_buf_bigger = 0;
5343 DWORD
len = MultiByteToWideChar(cp, 0, path, -1, NULL, 0);
5344 size_t size = rb_w32_reparse_buffer_size(bufsize);
5346 WCHAR *wpath =
ALLOCV(rp_buf,
sizeof(WCHAR) *
len + size);
5351 MultiByteToWideChar(cp, 0, path, -1, wpath,
len);
5352 e = rb_w32_read_reparse_point(wpath, rp, size, &wname, &
len);
5353 if (e == ERROR_MORE_DATA) {
5354 size = rb_w32_reparse_buffer_size(
len + 1);
5355 rp =
ALLOCV(rp_buf_bigger, size);
5356 e = rb_w32_read_reparse_point(wpath, rp, size, &wname, &
len);
5361 errno = e == -1 ? EINVAL : map_errno(e);
5364 len = lstrlenW(wname);
5365 ret = WideCharToMultiByte(cp, 0, wname,
len, buf, bufsize, NULL, NULL);
5376rb_w32_ureadlink(
const char *path,
char *buf,
size_t bufsize)
5378 return w32_readlink(CP_UTF8, path, buf, bufsize);
5383readlink(
const char *path,
char *buf,
size_t bufsize)
5385 return w32_readlink(filecp(), path, buf, bufsize);
5388#ifndef SYMBOLIC_LINK_FLAG_DIRECTORY
5389#define SYMBOLIC_LINK_FLAG_DIRECTORY (0x1)
5391#ifndef SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE
5392#define SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE (0x2)
5397w32_symlink(UINT cp,
const char *src,
const char *link)
5399 int atts, len1, len2;
5401 WCHAR *wsrc, *wlink;
5406 typedef BOOLEAN (WINAPI *create_symbolic_link_func)(WCHAR*, WCHAR*, DWORD);
5407 static create_symbolic_link_func create_symbolic_link =
5408 (create_symbolic_link_func)-1;
5409 static DWORD create_flag = SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
5411 if (create_symbolic_link == (create_symbolic_link_func)-1) {
5413 create_symbolic_link = (create_symbolic_link_func)
5414 get_proc_address(
"kernel32",
"CreateSymbolicLinkW", NULL);
5416 if (!create_symbolic_link) {
5429 len1 = MultiByteToWideChar(cp, 0, src, -1, NULL, 0);
5430 len2 = MultiByteToWideChar(cp, 0, link, -1, NULL, 0);
5431 wsrc =
ALLOCV_N(WCHAR, buf, len1+len2);
5432 wlink = wsrc + len1;
5433 MultiByteToWideChar(cp, 0, src, -1, wsrc, len1);
5434 MultiByteToWideChar(cp, 0, link, -1, wlink, len2);
5435 translate_wchar(wsrc, L
'/', L
'\\');
5437 atts = GetFileAttributesW(wsrc);
5438 if (atts != -1 && atts & FILE_ATTRIBUTE_DIRECTORY)
5439 flag = SYMBOLIC_LINK_FLAG_DIRECTORY;
5440 ret = create_symbolic_link(wlink, wsrc, flag |= create_flag);
5442 (e = GetLastError()) == ERROR_INVALID_PARAMETER &&
5443 (flag & SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE)) {
5445 flag &= ~SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
5446 ret = create_symbolic_link(wlink, wsrc, flag);
5447 if (!ret) e = GetLastError();
5452 errno = map_errno(e);
5460rb_w32_usymlink(
const char *src,
const char *link)
5462 return w32_symlink(CP_UTF8, src, link);
5467symlink(
const char *src,
const char *link)
5469 return w32_symlink(filecp(), src, link);
5476 return waitpid(-1, status, 0);
5481w32_getenv(
const char *name, UINT cp)
5483 WCHAR *wenvarea, *wenv;
5484 int len = strlen(name);
5485 char *env, *found = NULL;
5488 if (
len == 0)
return NULL;
5493 return getenv(name);
5496 thread_exclusive(uenvarea) {
5501 wenvarea = GetEnvironmentStringsW();
5503 map_errno(GetLastError());
5506 for (wenv = wenvarea, wlen = 1; *wenv; wenv += lstrlenW(wenv) + 1)
5507 wlen += lstrlenW(wenv) + 1;
5508 uenvarea = wstr_to_mbstr(cp, wenvarea, wlen, NULL);
5509 FreeEnvironmentStringsW(wenvarea);
5513 for (env = uenvarea; *env; env += strlen(env) + 1) {
5514 if (strncasecmp(env, name,
len) == 0 && *(env +
len) ==
'=') {
5515 found = env +
len + 1;
5526rb_w32_ugetenv(
const char *name)
5528 return w32_getenv(name, CP_UTF8);
5533rb_w32_getenv(
const char *name)
5535 return w32_getenv(name, CP_ACP);
5540get_attr_vsn(
const WCHAR *path, DWORD *atts, DWORD *vsn)
5542 BY_HANDLE_FILE_INFORMATION st = {0};
5544 HANDLE h = open_special(path, 0, FILE_FLAG_OPEN_REPARSE_POINT);
5546 if (h == INVALID_HANDLE_VALUE) {
5551 if (!GetFileInformationByHandle(h, &st)) {
5556 *atts = st.dwFileAttributes;
5557 *vsn = st.dwVolumeSerialNumber;
5565wrename(
const WCHAR *oldpath,
const WCHAR *newpath)
5568 DWORD oldatts = 0, newatts = (DWORD)-1;
5569 DWORD oldvsn = 0, newvsn = 0, e;
5571 e = get_attr_vsn(oldpath, &oldatts, &oldvsn);
5573 errno = map_errno(e);
5576 if (oldatts & FILE_ATTRIBUTE_REPARSE_POINT) {
5577 HANDLE fh = open_special(oldpath, 0, 0);
5578 if (fh == INVALID_HANDLE_VALUE) {
5580 if (e == ERROR_CANT_RESOLVE_FILENAME) {
5587 get_attr_vsn(newpath, &newatts, &newvsn);
5590 if (newatts != (DWORD)-1 && newatts & FILE_ATTRIBUTE_READONLY)
5591 SetFileAttributesW(newpath, newatts & ~ FILE_ATTRIBUTE_READONLY);
5593 if (!MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED))
5597 DWORD e = GetLastError();
5598 if ((e == ERROR_ACCESS_DENIED) && (oldatts & FILE_ATTRIBUTE_DIRECTORY) &&
5602 errno = map_errno(e);
5605 SetFileAttributesW(newpath, oldatts);
5613rb_w32_urename(
const char *from,
const char *to)
5619 if (!(wfrom = utf8_to_wstr(from, NULL)))
5621 if (!(wto = utf8_to_wstr(to, NULL))) {
5625 ret = wrename(wfrom, wto);
5633rb_w32_rename(
const char *from,
const char *to)
5639 if (!(wfrom = filecp_to_wstr(from, NULL)))
5641 if (!(wto = filecp_to_wstr(to, NULL))) {
5645 ret = wrename(wfrom, wto);
5653isUNCRoot(
const WCHAR *path)
5655 if (path[0] == L
'\\' && path[1] == L
'\\') {
5656 const WCHAR *p = path + 2;
5657 if (p[0] == L
'?' && p[1] == L
'\\') {
5665 for (p++; *p; p++) {
5669 if (!p[0] || !p[1] || (p[1] == L
'.' && !p[2]))
5676#define COPY_STAT(src, dest, size_cast) do { \
5677 (dest).st_dev = (src).st_dev; \
5678 (dest).st_ino = (src).st_ino; \
5679 (dest).st_mode = (src).st_mode; \
5680 (dest).st_nlink = (src).st_nlink; \
5681 (dest).st_uid = (src).st_uid; \
5682 (dest).st_gid = (src).st_gid; \
5683 (dest).st_rdev = (src).st_rdev; \
5684 (dest).st_size = size_cast(src).st_size; \
5685 (dest).st_atime = (src).st_atime; \
5686 (dest).st_mtime = (src).st_mtime; \
5687 (dest).st_ctime = (src).st_ctime; \
5690static time_t filetime_to_unixtime(
const FILETIME *ft);
5691static long filetime_to_nsec(
const FILETIME *ft);
5692static WCHAR *name_for_stat(WCHAR *buf,
const WCHAR *path);
5693static DWORD stati128_handle(HANDLE h,
struct stati128 *st);
5698rb_w32_fstat(
int fd,
struct stat *st)
5700 BY_HANDLE_FILE_INFORMATION info;
5701 int ret = fstat(fd, st);
5703 if (ret)
return ret;
5704 if (GetEnvironmentVariableW(L
"TZ", NULL, 0) == 0 && GetLastError() == ERROR_ENVVAR_NOT_FOUND)
return ret;
5705 if (GetFileInformationByHandle((HANDLE)_get_osfhandle(fd), &info)) {
5706 st->st_atime = filetime_to_unixtime(&info.ftLastAccessTime);
5707 st->st_mtime = filetime_to_unixtime(&info.ftLastWriteTime);
5708 st->st_ctime = filetime_to_unixtime(&info.ftCreationTime);
5715rb_w32_fstati128(
int fd,
struct stati128 *st)
5718 int ret = fstat(fd, &tmp);
5720 if (ret)
return ret;
5721 COPY_STAT(tmp, *st, +);
5722 stati128_handle((HANDLE)_get_osfhandle(fd), st);
5726#if !defined FILE_INVALID_FILE_ID && !defined __MINGW32__
5728 BYTE Identifier[16];
5732#if !defined(_WIN32_WINNT_WIN8) || _WIN32_WINNT < 0x602
5733#define FileIdInfo 0x12
5744 typedef BOOL (WINAPI *gfibhe_t)(HANDLE, int,
void *, DWORD);
5745 static gfibhe_t pGetFileInformationByHandleEx = (gfibhe_t)-1;
5747 if (pGetFileInformationByHandleEx == (gfibhe_t)-1)
5749 pGetFileInformationByHandleEx = (gfibhe_t)get_proc_address(
"kernel32",
"GetFileInformationByHandleEx", NULL);
5751 if (pGetFileInformationByHandleEx) {
5752 if (pGetFileInformationByHandleEx(h, FileIdInfo,
id,
sizeof(*
id)))
5755 return GetLastError();
5757 return ERROR_INVALID_PARAMETER;
5762stati128_handle(HANDLE h,
struct stati128 *st)
5764 BY_HANDLE_FILE_INFORMATION info;
5765 DWORD attr = (DWORD)-1;
5767 if (GetFileInformationByHandle(h, &info)) {
5769 st->st_size = ((__int64)info.nFileSizeHigh << 32) | info.nFileSizeLow;
5770 st->st_atime = filetime_to_unixtime(&info.ftLastAccessTime);
5771 st->st_atimensec = filetime_to_nsec(&info.ftLastAccessTime);
5772 st->st_mtime = filetime_to_unixtime(&info.ftLastWriteTime);
5773 st->st_mtimensec = filetime_to_nsec(&info.ftLastWriteTime);
5774 st->st_ctime = filetime_to_unixtime(&info.ftCreationTime);
5775 st->st_ctimensec = filetime_to_nsec(&info.ftCreationTime);
5776 st->st_nlink = info.nNumberOfLinks;
5777 attr = info.dwFileAttributes;
5778 if (!get_ino(h, &fii)) {
5779 st->st_ino = *((
unsigned __int64 *)&fii.FileId);
5780 st->st_inohigh = *((__int64 *)&fii.FileId + 1);
5783 st->st_ino = ((__int64)info.nFileIndexHigh << 32) | info.nFileIndexLow;
5792filetime_to_unixtime(
const FILETIME *ft)
5795 time_t t = filetime_split(ft, &subsec);
5797 if (t < 0)
return 0;
5803filetime_to_nsec(
const FILETIME *ft)
5805 if (have_precisetime <= 0)
5809 tmp.LowPart = ft->dwLowDateTime;
5810 tmp.HighPart = ft->dwHighDateTime;
5811 return (
long)(tmp.QuadPart % 10000000) * 100;
5817fileattr_to_unixmode(DWORD attr,
const WCHAR *path,
unsigned mode)
5819 if (attr & FILE_ATTRIBUTE_READONLY) {
5823 mode |= S_IREAD | S_IWRITE | S_IWUSR;
5826 if (mode & S_IFMT) {
5829 else if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
5833 else if (attr & FILE_ATTRIBUTE_DIRECTORY) {
5834 mode |= S_IFDIR | S_IEXEC;
5840 if (path && (mode & S_IFREG)) {
5841 const WCHAR *end = path + lstrlenW(path);
5842 while (path < end) {
5843 end = CharPrevW(path, end);
5845 if ((_wcsicmp(end, L
".bat") == 0) ||
5846 (_wcsicmp(end, L
".cmd") == 0) ||
5847 (_wcsicmp(end, L
".com") == 0) ||
5848 (_wcsicmp(end, L
".exe") == 0)) {
5853 if (!iswalnum(*end))
break;
5857 mode |= (mode & 0500) >> 3;
5858 mode |= (mode & 0500) >> 6;
5865check_valid_dir(
const WCHAR *path)
5867 WIN32_FIND_DATAW fd;
5869 WCHAR full[PATH_MAX];
5875 if (!(p = wcsstr(path, L
"...")))
5877 q = p + wcsspn(p, L
".");
5878 if ((p == path || wcschr(L
":/\\", *(p - 1))) &&
5879 (!*q || wcschr(L
":/\\", *q))) {
5886 if (!GetFullPathNameW(path,
sizeof(full) /
sizeof(WCHAR), full, &dmy)) {
5887 errno = map_errno(GetLastError());
5890 if (full[1] == L
':' && !full[3] && GetDriveTypeW(full) != DRIVE_NO_ROOT_DIR)
5893 fh = open_dir_handle(path, &fd);
5894 if (fh == INVALID_HANDLE_VALUE)
5902stat_by_find(
const WCHAR *path,
struct stati128 *st)
5905 WIN32_FIND_DATAW wfd;
5908 h = FindFirstFileW(path, &wfd);
5909 if (h == INVALID_HANDLE_VALUE) {
5910 errno = map_errno(GetLastError());
5914 st->st_mode = fileattr_to_unixmode(wfd.dwFileAttributes, path, 0);
5915 st->st_atime = filetime_to_unixtime(&wfd.ftLastAccessTime);
5916 st->st_atimensec = filetime_to_nsec(&wfd.ftLastAccessTime);
5917 st->st_mtime = filetime_to_unixtime(&wfd.ftLastWriteTime);
5918 st->st_mtimensec = filetime_to_nsec(&wfd.ftLastWriteTime);
5919 st->st_ctime = filetime_to_unixtime(&wfd.ftCreationTime);
5920 st->st_ctimensec = filetime_to_nsec(&wfd.ftCreationTime);
5921 st->st_size = ((__int64)wfd.nFileSizeHigh << 32) | wfd.nFileSizeLow;
5928path_drive(
const WCHAR *path)
5930 return (iswalpha(path[0]) && path[1] == L
':') ?
5931 towupper(path[0]) - L
'A' : _getdrive() - 1;
5936winnt_stat(
const WCHAR *path,
struct stati128 *st, BOOL lstat)
5938 DWORD flags = lstat ? FILE_FLAG_OPEN_REPARSE_POINT : 0;
5940 WCHAR finalname[PATH_MAX];
5943 memset(st, 0,
sizeof(*st));
5944 f = open_special(path, 0, flags);
5945 open_error = GetLastError();
5946 if (f == INVALID_HANDLE_VALUE && !lstat) {
5948 FILE_ATTRIBUTE_TAG_INFO attr_info;
5951 f = open_special(path, 0, FILE_FLAG_OPEN_REPARSE_POINT);
5952 e = GetFileInformationByHandleEx( f, FileAttributeTagInfo,
5953 &attr_info,
sizeof(attr_info));
5954 if (!e || attr_info.ReparseTag != IO_REPARSE_TAG_AF_UNIX) {
5956 f = INVALID_HANDLE_VALUE;
5959 if (f != INVALID_HANDLE_VALUE) {
5960 DWORD attr = stati128_handle(f, st);
5961 const DWORD
len = get_final_path(f, finalname, numberof(finalname), 0);
5963 switch (GetFileType(f)) {
5964 case FILE_TYPE_CHAR:
5967 case FILE_TYPE_PIPE:
5971 if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
5972 FILE_ATTRIBUTE_TAG_INFO attr_info;
5975 e = GetFileInformationByHandleEx( f, FileAttributeTagInfo,
5976 &attr_info,
sizeof(attr_info));
5977 if (e && attr_info.ReparseTag == IO_REPARSE_TAG_AF_UNIX) {
5981 else if (rb_w32_reparse_symlink_p(path)) {
5984 mode |= S_IFLNK | S_IEXEC;
5987 mode |= S_IFDIR | S_IEXEC;
5992 if (attr & FILE_ATTRIBUTE_DIRECTORY) {
5993 if (check_valid_dir(path))
return -1;
5995 st->st_mode = fileattr_to_unixmode(attr, path, mode);
5997 finalname[min(
len, numberof(finalname)-1)] = L
'\0';
5999 if (wcsncmp(path, namespace_prefix, numberof(namespace_prefix)) == 0)
6000 path += numberof(namespace_prefix);
6004 if ((open_error == ERROR_FILE_NOT_FOUND) || (open_error == ERROR_INVALID_NAME)
6005 || (open_error == ERROR_PATH_NOT_FOUND || (open_error == ERROR_BAD_NETPATH))) {
6006 errno = map_errno(open_error);
6010 if (stat_by_find(path, st))
return -1;
6013 st->st_dev = st->st_rdev = path_drive(path);
6020rb_w32_stat(
const char *path,
struct stat *st)
6022 struct stati128 tmp;
6024 if (w32_stati128(path, &tmp, filecp(), FALSE))
return -1;
6025 COPY_STAT(tmp, *st, (_off_t));
6031wstati128(
const WCHAR *path,
struct stati128 *st, BOOL lstat)
6041 size = lstrlenW(path) + 2;
6043 if (!(path = name_for_stat(buf1, path)))
6045 ret = winnt_stat(path, st, lstat);
6054name_for_stat(WCHAR *buf1,
const WCHAR *path)
6060 for (p = path, s = buf1; *p; p++, s++) {
6068 if (!
len || L
'\"' == *(--s)) {
6072 end = buf1 +
len - 1;
6074 if (isUNCRoot(buf1)) {
6077 else if (*end != L
'\\')
6078 lstrcatW(buf1, L
"\\");
6080 else if (*end == L
'\\' || (buf1 + 1 == end && *end == L
':'))
6081 lstrcatW(buf1, L
".");
6088rb_w32_ustati128(
const char *path,
struct stati128 *st)
6090 return w32_stati128(path, st, CP_UTF8, FALSE);
6095rb_w32_stati128(
const char *path,
struct stati128 *st)
6097 return w32_stati128(path, st, filecp(), FALSE);
6102w32_stati128(
const char *path,
struct stati128 *st, UINT cp, BOOL lstat)
6107 if (!(wpath = mbstr_to_wstr(cp, path, -1, NULL)))
6109 ret = wstati128(wpath, st, lstat);
6116rb_w32_ulstati128(
const char *path,
struct stati128 *st)
6118 return w32_stati128(path, st, CP_UTF8, TRUE);
6123rb_w32_lstati128(
const char *path,
struct stati128 *st)
6125 return w32_stati128(path, st, filecp(), TRUE);
6130rb_w32_lseek(
int fd, rb_off_t ofs,
int whence)
6132 SOCKET sock = TO_SOCKET(fd);
6133 if (is_socket(sock) || is_pipe(sock)) {
6137 return _lseeki64(fd, ofs, whence);
6142w32_access(
const char *path,
int mode, UINT cp)
6144 struct stati128 stat;
6145 if (w32_stati128(path, &stat, cp, FALSE) != 0)
6148 if ((stat.st_mode & mode) != mode) {
6157rb_w32_access(
const char *path,
int mode)
6159 return w32_access(path, mode, filecp());
6164rb_w32_uaccess(
const char *path,
int mode)
6166 return w32_access(path, mode, CP_UTF8);
6171rb_chsize(HANDLE h, rb_off_t size)
6173 long upos, lpos, usize, lsize;
6177 if ((lpos = SetFilePointer(h, 0, (upos = 0, &upos), SEEK_CUR)) == -1L &&
6178 (e = GetLastError())) {
6179 errno = map_errno(e);
6182 usize = (long)(size >> 32);
6184 if (SetFilePointer(h, lsize, &usize, SEEK_SET) == (DWORD)-1L &&
6185 (e = GetLastError())) {
6186 errno = map_errno(e);
6188 else if (!SetEndOfFile(h)) {
6189 errno = map_errno(GetLastError());
6194 SetFilePointer(h, lpos, &upos, SEEK_SET);
6200w32_truncate(
const char *path, rb_off_t length, UINT cp)
6206 if (!(wpath = mbstr_to_wstr(cp, path, -1, NULL)))
6208 h = CreateFileW(wpath, GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
6209 if (h == INVALID_HANDLE_VALUE) {
6210 errno = map_errno(GetLastError());
6215 ret = rb_chsize(h, length);
6222rb_w32_utruncate(
const char *path, rb_off_t length)
6224 return w32_truncate(path, length, CP_UTF8);
6229rb_w32_truncate(
const char *path, rb_off_t length)
6231 return w32_truncate(path, length, filecp());
6236rb_w32_ftruncate(
int fd, rb_off_t length)
6240 h = (HANDLE)_get_osfhandle(fd);
6241 if (h == (HANDLE)-1)
return -1;
6242 return rb_chsize(h, length);
6247filetime_to_clock(FILETIME *ft)
6249 __int64 qw = ft->dwHighDateTime;
6251 qw |= ft->dwLowDateTime;
6258rb_w32_times(
struct tms *tmbuf)
6260 FILETIME create, exit, kernel, user;
6262 if (GetProcessTimes(GetCurrentProcess(),&create, &exit, &kernel, &user)) {
6263 tmbuf->tms_utime = filetime_to_clock(&user);
6264 tmbuf->tms_stime = filetime_to_clock(&kernel);
6265 tmbuf->tms_cutime = 0;
6266 tmbuf->tms_cstime = 0;
6269 tmbuf->tms_utime = clock();
6270 tmbuf->tms_stime = 0;
6271 tmbuf->tms_cutime = 0;
6272 tmbuf->tms_cstime = 0;
6279#define yield_once() Sleep(0)
6280#define yield_until(condition) do yield_once(); while (!(condition))
6289 uintptr_t (*func)(uintptr_t self,
int argc, uintptr_t* argv);
6297call_asynchronous(PVOID argp)
6301 arg->stackaddr = &argp;
6302 ret = (DWORD)arg->func(arg->self, arg->argc, arg->argv);
6303 arg->errnum =
errno;
6309rb_w32_asynchronize(asynchronous_func_t func, uintptr_t self,
6310 int argc, uintptr_t* argv, uintptr_t intrval)
6313 BOOL interrupted = FALSE;
6319 arg.stackaddr = NULL;
6326 thr = CreateThread(NULL, 0, call_asynchronous, &arg, 0, &val);
6329 yield_until(arg.stackaddr);
6331 if (rb_w32_wait_events_blocking(&thr, 1, INFINITE) != WAIT_OBJECT_0) {
6334 if (TerminateThread(thr, intrval)) {
6339 GetExitCodeThread(thr, &val);
6344 MEMORY_BASIC_INFORMATION m;
6346 memset(&m, 0,
sizeof(m));
6347 if (!VirtualQuery(arg.stackaddr, &m,
sizeof(m))) {
6348 Debug(fprintf(stderr,
"couldn't get stack base:%p:%d\n",
6349 arg.stackaddr, GetLastError()));
6351 else if (!VirtualFree(m.AllocationBase, 0, MEM_RELEASE)) {
6352 Debug(fprintf(stderr,
"couldn't release stack:%p:%d\n",
6353 m.AllocationBase, GetLastError()));
6364 rb_fatal(
"failed to launch waiter thread:%ld", GetLastError());
6372rb_w32_get_environ(
void)
6374 WCHAR *envtop, *env;
6375 char **myenvtop, **myenv;
6388 envtop = GetEnvironmentStringsW();
6389 for (env = envtop, num = 0; *env; env += lstrlenW(env) + 1)
6390 if (*env !=
'=') num++;
6392 myenvtop = (
char **)malloc(
sizeof(
char *) * (num + 1));
6393 for (env = envtop, myenv = myenvtop; *env; env += lstrlenW(env) + 1) {
6395 if (!(*myenv = wstr_to_utf8(env, NULL))) {
6402 FreeEnvironmentStringsW(envtop);
6409rb_w32_free_environ(
char **env)
6413 while (*t) free(*t++);
6421 return GetCurrentProcessId();
6429 typedef long (WINAPI query_func)(HANDLE, int,
void *, ULONG, ULONG *);
6430 static query_func *pNtQueryInformationProcess = (query_func *)-1;
6433 if (pNtQueryInformationProcess == (query_func *)-1)
6434 pNtQueryInformationProcess = (query_func *)get_proc_address(
"ntdll.dll",
"NtQueryInformationProcess", NULL);
6435 if (pNtQueryInformationProcess) {
6438 void* PebBaseAddress;
6439 uintptr_t AffinityMask;
6440 uintptr_t BasePriority;
6441 uintptr_t UniqueProcessId;
6442 uintptr_t ParentProcessId;
6445 long ret = pNtQueryInformationProcess(GetCurrentProcess(), 0, &pbi,
sizeof(pbi), &
len);
6447 ppid = pbi.ParentProcessId;
6454STATIC_ASSERT(std_handle, (STD_OUTPUT_HANDLE-STD_INPUT_HANDLE)==(STD_ERROR_HANDLE-STD_OUTPUT_HANDLE));
6457#define set_new_std_handle(newfd, handle) do { \
6458 if ((unsigned)(newfd) > 2) break; \
6459 SetStdHandle(STD_INPUT_HANDLE+(STD_OUTPUT_HANDLE-STD_INPUT_HANDLE)*(newfd), \
6462#define set_new_std_fd(newfd) set_new_std_handle(newfd, (HANDLE)rb_w32_get_osfhandle(newfd))
6466rb_w32_dup2(
int oldfd,
int newfd)
6470 if (oldfd == newfd)
return newfd;
6471 ret = dup2(oldfd, newfd);
6472 if (ret < 0)
return ret;
6473 set_new_std_fd(newfd);
6479rb_w32_uopen(
const char *file,
int oflag, ...)
6486 va_start(arg, oflag);
6487 pmode = va_arg(arg,
int);
6490 if (!(wfile = utf8_to_wstr(file, NULL)))
6492 ret = w32_wopen(wfile, oflag, pmode);
6499check_if_wdir(
const WCHAR *wfile)
6501 DWORD attr = GetFileAttributesW(wfile);
6502 if (attr == (DWORD)-1L ||
6503 !(attr & FILE_ATTRIBUTE_DIRECTORY) ||
6504 check_valid_dir(wfile)) {
6513rb_w32_open(
const char *file,
int oflag, ...)
6520 va_start(arg, oflag);
6521 pmode = va_arg(arg,
int);
6524 if (!(wfile = filecp_to_wstr(file, NULL)))
6526 ret = w32_wopen(wfile, oflag, pmode);
6533rb_w32_wopen(
const WCHAR *file,
int oflag, ...)
6537 if (oflag & O_CREAT) {
6539 va_start(arg, oflag);
6540 pmode = va_arg(arg,
int);
6544 return w32_wopen(file, oflag, pmode);
6548w32_wopen(
const WCHAR *file,
int oflag,
int pmode)
6554 DWORD attr = FILE_ATTRIBUTE_NORMAL;
6555 SECURITY_ATTRIBUTES sec;
6559 share_delete = oflag & O_SHARE_DELETE ? FILE_SHARE_DELETE : 0;
6560 oflag &= ~O_SHARE_DELETE;
6561 if ((oflag & O_TEXT) || !(oflag & O_BINARY)) {
6562 fd = _wopen(file, oflag, pmode);
6566 check_if_wdir(file);
6569 errno = map_errno(GetLastError());
6576 sec.nLength =
sizeof(sec);
6577 sec.lpSecurityDescriptor = NULL;
6578 if (oflag & O_NOINHERIT) {
6579 sec.bInheritHandle = FALSE;
6580 flags |= FNOINHERIT;
6583 sec.bInheritHandle = TRUE;
6585 oflag &= ~O_NOINHERIT;
6588 oflag &= ~(O_BINARY | O_TEXT);
6590 switch (oflag & (O_RDWR | O_RDONLY | O_WRONLY)) {
6592 access = GENERIC_READ | GENERIC_WRITE;
6595 access = GENERIC_READ;
6598 access = GENERIC_WRITE;
6604 oflag &= ~(O_RDWR | O_RDONLY | O_WRONLY);
6606 switch (oflag & (O_CREAT | O_EXCL | O_TRUNC)) {
6608 create = OPEN_ALWAYS;
6612 create = OPEN_EXISTING;
6614 case O_CREAT | O_EXCL:
6615 case O_CREAT | O_EXCL | O_TRUNC:
6616 create = CREATE_NEW;
6619 case O_TRUNC | O_EXCL:
6620 create = TRUNCATE_EXISTING;
6622 case O_CREAT | O_TRUNC:
6623 create = CREATE_ALWAYS;
6629 if (oflag & O_CREAT) {
6631 if (!(pmode & S_IWRITE))
6632 attr = FILE_ATTRIBUTE_READONLY;
6634 oflag &= ~(O_CREAT | O_EXCL | O_TRUNC);
6636 if (oflag & O_TEMPORARY) {
6637 attr |= FILE_FLAG_DELETE_ON_CLOSE;
6640 oflag &= ~O_TEMPORARY;
6642 if (oflag & _O_SHORT_LIVED)
6643 attr |= FILE_ATTRIBUTE_TEMPORARY;
6644 oflag &= ~_O_SHORT_LIVED;
6646 switch (oflag & (O_SEQUENTIAL | O_RANDOM)) {
6650 attr |= FILE_FLAG_SEQUENTIAL_SCAN;
6653 attr |= FILE_FLAG_RANDOM_ACCESS;
6659 oflag &= ~(O_SEQUENTIAL | O_RANDOM);
6661 if (oflag & ~O_APPEND) {
6668 h = CreateFile(
"NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
6669 fd = _open_osfhandle((intptr_t)h, 0);
6677 rb_acrt_lowio_lock_fh(fd);
6678 _set_osfhnd(fd, (intptr_t)INVALID_HANDLE_VALUE);
6679 _set_osflags(fd, 0);
6681 h = CreateFileW(file, access, FILE_SHARE_READ | FILE_SHARE_WRITE | share_delete, &sec, create, attr, NULL);
6682 if (h == INVALID_HANDLE_VALUE) {
6683 DWORD e = GetLastError();
6684 if (e != ERROR_ACCESS_DENIED || !check_if_wdir(file))
6685 errno = map_errno(e);
6686 rb_acrt_lowio_unlock_fh(fd);
6691 switch (GetFileType(h)) {
6692 case FILE_TYPE_CHAR:
6695 case FILE_TYPE_PIPE:
6698 case FILE_TYPE_UNKNOWN:
6699 errno = map_errno(GetLastError());
6701 rb_acrt_lowio_unlock_fh(fd);
6705 if (!(flags & (FDEV | FPIPE)) && (oflag & O_APPEND))
6708 _set_osfhnd(fd, (intptr_t)h);
6709 _set_osflags(fd, flags | FOPEN);
6711 rb_acrt_lowio_unlock_fh(fd);
6721rb_w32_fclose(FILE *fp)
6723 int fd = fileno(fp);
6724 SOCKET sock = TO_SOCKET(fd);
6725 int save_errno =
errno;
6727 if (fflush(fp))
return -1;
6728 if (!is_socket(sock)) {
6729 UnlockFile((HANDLE)sock, 0, 0, LK_LEN, LK_LEN);
6732 _set_osfhnd(fd, (SOCKET)INVALID_HANDLE_VALUE);
6735 if (closesocket(sock) == SOCKET_ERROR) {
6736 errno = map_errno(WSAGetLastError());
6744rb_w32_pipe(
int fds[2])
6746 static long serial = 0;
6747 static const char prefix[] =
"\\\\.\\pipe\\ruby";
6749 width_of_prefix = (int)
sizeof(prefix) - 1,
6750 width_of_pid = (int)
sizeof(rb_pid_t) * 2,
6751 width_of_serial = (int)
sizeof(serial) * 2,
6752 width_of_ids = width_of_pid + 1 + width_of_serial + 1
6754 char name[
sizeof(prefix) + width_of_ids];
6755 SECURITY_ATTRIBUTES sec;
6756 HANDLE hRead, hWrite, h;
6757 int fdRead, fdWrite;
6760 memcpy(name, prefix, width_of_prefix);
6761 snprintf(name + width_of_prefix, width_of_ids,
"%.*"PRI_PIDT_PREFIX"x-%.*lx",
6762 width_of_pid, rb_w32_getpid(), width_of_serial, InterlockedIncrement(&serial)-1);
6764 sec.nLength =
sizeof(sec);
6765 sec.lpSecurityDescriptor = NULL;
6766 sec.bInheritHandle = FALSE;
6769 hRead = CreateNamedPipe(name, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
6770 0, 2, 65536, 65536, 0, &sec);
6772 if (hRead == INVALID_HANDLE_VALUE) {
6773 DWORD err = GetLastError();
6774 if (err == ERROR_PIPE_BUSY)
6777 errno = map_errno(GetLastError());
6782 hWrite = CreateFile(name, GENERIC_READ | GENERIC_WRITE, 0, &sec,
6783 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
6785 if (hWrite == INVALID_HANDLE_VALUE) {
6786 errno = map_errno(GetLastError());
6793 h = CreateFile(
"NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
6794 fdRead = _open_osfhandle((intptr_t)h, 0);
6798 CloseHandle(hWrite);
6804 rb_acrt_lowio_lock_fh(fdRead);
6805 _set_osfhnd(fdRead, (intptr_t)hRead);
6806 _set_osflags(fdRead, FOPEN | FPIPE | FNOINHERIT);
6807 rb_acrt_lowio_unlock_fh(fdRead);
6813 h = CreateFile(
"NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
6814 fdWrite = _open_osfhandle((intptr_t)h, 0);
6816 if (fdWrite == -1) {
6818 CloseHandle(hWrite);
6822 rb_acrt_lowio_lock_fh(fdWrite);
6823 _set_osfhnd(fdWrite, (intptr_t)hWrite);
6824 _set_osflags(fdWrite, FOPEN | FPIPE | FNOINHERIT);
6825 rb_acrt_lowio_unlock_fh(fdWrite);
6828 rb_w32_close(fdRead);
6840console_emulator_p(
void)
6845 const void *
const func = WriteConsoleW;
6847 MEMORY_BASIC_INFORMATION m;
6849 memset(&m, 0,
sizeof(m));
6850 if (!VirtualQuery(func, &m,
sizeof(m))) {
6853 k = GetModuleHandle(
"kernel32.dll");
6854 if (!k)
return FALSE;
6855 return (HMODULE)m.AllocationBase != k;
6861constat_handle(HANDLE h)
6865 thread_exclusive(conlist) {
6867 if (console_emulator_p()) {
6868 conlist = conlist_disabled;
6871 conlist = st_init_numtable();
6872 install_vm_exit_handler();
6874 else if (conlist == conlist_disabled) {
6877 if (st_lookup(conlist, (st_data_t)h, &data)) {
6881 CONSOLE_SCREEN_BUFFER_INFO csbi;
6883 p->vt100.state = constat_init;
6884 p->vt100.attr = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED;
6885 p->vt100.reverse = 0;
6886 p->vt100.saved.X = p->vt100.saved.Y = 0;
6887 if (GetConsoleScreenBufferInfo(h, &csbi)) {
6888 p->vt100.attr = csbi.wAttributes;
6890 st_insert(conlist, (st_data_t)h, (st_data_t)p);
6898constat_reset(HANDLE h)
6902 thread_exclusive(conlist) {
6903 if (!conlist || conlist == conlist_disabled)
continue;
6904 if (!st_lookup(conlist, (st_data_t)h, &data))
continue;
6906 p->vt100.state = constat_init;
6910#define FOREGROUND_MASK (FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY)
6911#define BACKGROUND_MASK (BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_INTENSITY)
6913#define constat_attr_color_reverse(attr) \
6914 ((attr) & ~(FOREGROUND_MASK | BACKGROUND_MASK)) | \
6915 (((attr) & FOREGROUND_MASK) << 4) | \
6916 (((attr) & BACKGROUND_MASK) >> 4)
6920constat_attr(
int count,
const int *seq, WORD attr, WORD default_attr,
int *reverse)
6925 if (!count)
return attr;
6926 if (rev) attr = constat_attr_color_reverse(attr);
6927 bold = attr & FOREGROUND_INTENSITY;
6928 attr &= ~(FOREGROUND_INTENSITY | BACKGROUND_INTENSITY);
6930 while (count-- > 0) {
6933 attr = default_attr;
6938 bold = FOREGROUND_INTENSITY;
6941#ifndef COMMON_LVB_UNDERSCORE
6942#define COMMON_LVB_UNDERSCORE 0x8000
6944 attr |= COMMON_LVB_UNDERSCORE;
6951 attr &= ~(FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED);
6955 attr = (attr & ~(FOREGROUND_BLUE | FOREGROUND_GREEN)) | FOREGROUND_RED;
6959 attr = (attr & ~(FOREGROUND_BLUE | FOREGROUND_RED)) | FOREGROUND_GREEN;
6963 attr = (attr & ~FOREGROUND_BLUE) | FOREGROUND_GREEN | FOREGROUND_RED;
6967 attr = (attr & ~(FOREGROUND_GREEN | FOREGROUND_RED)) | FOREGROUND_BLUE;
6971 attr = (attr & ~FOREGROUND_GREEN) | FOREGROUND_BLUE | FOREGROUND_RED;
6975 attr = (attr & ~FOREGROUND_RED) | FOREGROUND_BLUE | FOREGROUND_GREEN;
6979 attr |= FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED;
6983 attr &= ~(BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED);
6986 attr = (attr & ~(BACKGROUND_BLUE | BACKGROUND_GREEN)) | BACKGROUND_RED;
6989 attr = (attr & ~(BACKGROUND_BLUE | BACKGROUND_RED)) | BACKGROUND_GREEN;
6992 attr = (attr & ~BACKGROUND_BLUE) | BACKGROUND_GREEN | BACKGROUND_RED;
6995 attr = (attr & ~(BACKGROUND_GREEN | BACKGROUND_RED)) | BACKGROUND_BLUE;
6998 attr = (attr & ~BACKGROUND_GREEN) | BACKGROUND_BLUE | BACKGROUND_RED;
7001 attr = (attr & ~BACKGROUND_RED) | BACKGROUND_BLUE | BACKGROUND_GREEN;
7004 attr |= BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED;
7009 if (rev) attr = constat_attr_color_reverse(attr);
7016constat_clear(HANDLE handle, WORD attr, DWORD
len, COORD pos)
7020 FillConsoleOutputAttribute(handle, attr,
len, pos, &written);
7021 FillConsoleOutputCharacterW(handle, L
' ',
len, pos, &written);
7026constat_apply(HANDLE handle,
struct constat *s, WCHAR w)
7028 CONSOLE_SCREEN_BUFFER_INFO csbi;
7029 const int *seq = s->vt100.seq;
7030 int count = s->vt100.state;
7034 if (!GetConsoleScreenBufferInfo(handle, &csbi))
return;
7035 arg0 = (count > 0 && seq[0] > 0);
7036 if (arg0) arg1 = seq[0];
7039 SetConsoleTextAttribute(handle, constat_attr(count, seq, csbi.wAttributes, s->vt100.attr, &s->vt100.reverse));
7042 csbi.dwCursorPosition.X = 0;
7044 csbi.dwCursorPosition.Y -= arg1;
7045 if (csbi.dwCursorPosition.Y < csbi.srWindow.Top)
7046 csbi.dwCursorPosition.Y = csbi.srWindow.Top;
7047 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
7050 csbi.dwCursorPosition.X = 0;
7053 csbi.dwCursorPosition.Y += arg1;
7054 if (csbi.dwCursorPosition.Y > csbi.srWindow.Bottom)
7055 csbi.dwCursorPosition.Y = csbi.srWindow.Bottom;
7056 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
7059 csbi.dwCursorPosition.X += arg1;
7060 if (csbi.dwCursorPosition.X >= csbi.srWindow.Right)
7061 csbi.dwCursorPosition.X = csbi.srWindow.Right;
7062 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
7065 csbi.dwCursorPosition.X -= arg1;
7066 if (csbi.dwCursorPosition.X < csbi.srWindow.Left)
7067 csbi.dwCursorPosition.X = csbi.srWindow.Left;
7068 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
7072 arg1 += csbi.srWindow.Left;
7073 if (arg1 > csbi.srWindow.Right)
7074 arg1 = csbi.srWindow.Right;
7075 csbi.dwCursorPosition.X = arg1;
7076 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
7079 arg1 += csbi.srWindow.Top;
7080 if (arg1 > csbi.srWindow.Bottom)
7081 arg1 = csbi.srWindow.Bottom;
7082 csbi.dwCursorPosition.Y = arg1;
7083 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
7087 pos.Y = arg1 + csbi.srWindow.Top - 1;
7088 if (pos.Y > csbi.srWindow.Bottom) pos.Y = csbi.srWindow.Bottom;
7089 if (count < 2 || (arg1 = seq[1]) <= 0) arg1 = 1;
7090 pos.X = arg1 + csbi.srWindow.Left - 1;
7091 if (pos.X > csbi.srWindow.Right) pos.X = csbi.srWindow.Right;
7092 SetConsoleCursorPosition(handle, pos);
7095 switch (arg0 ? arg1 : 0) {
7097 constat_clear(handle, csbi.wAttributes,
7098 (csbi.dwSize.X * (csbi.srWindow.Bottom - csbi.dwCursorPosition.Y + 1)
7099 - csbi.dwCursorPosition.X),
7100 csbi.dwCursorPosition);
7104 pos.Y = csbi.srWindow.Top;
7105 constat_clear(handle, csbi.wAttributes,
7106 (csbi.dwSize.X * (csbi.dwCursorPosition.Y - csbi.srWindow.Top)
7107 + csbi.dwCursorPosition.X + 1),
7112 pos.Y = csbi.srWindow.Top;
7113 constat_clear(handle, csbi.wAttributes,
7114 (csbi.dwSize.X * (csbi.srWindow.Bottom - csbi.srWindow.Top + 1)),
7120 constat_clear(handle, csbi.wAttributes,
7121 (csbi.dwSize.X * csbi.dwSize.Y),
7127 switch (arg0 ? arg1 : 0) {
7129 constat_clear(handle, csbi.wAttributes,
7130 (csbi.dwSize.X - csbi.dwCursorPosition.X),
7131 csbi.dwCursorPosition);
7135 pos.Y = csbi.dwCursorPosition.Y;
7136 constat_clear(handle, csbi.wAttributes,
7137 csbi.dwCursorPosition.X + 1, pos);
7141 pos.Y = csbi.dwCursorPosition.Y;
7142 constat_clear(handle, csbi.wAttributes,
7143 csbi.dwSize.X, pos);
7148 s->vt100.saved = csbi.dwCursorPosition;
7151 SetConsoleCursorPosition(handle, s->vt100.saved);
7154 if (count >= 2 && seq[0] == -1 && seq[1] == 25) {
7155 CONSOLE_CURSOR_INFO cci;
7156 GetConsoleCursorInfo(handle, &cci);
7157 cci.bVisible = TRUE;
7158 SetConsoleCursorInfo(handle, &cci);
7162 if (count >= 2 && seq[0] == -1 && seq[1] == 25) {
7163 CONSOLE_CURSOR_INFO cci;
7164 GetConsoleCursorInfo(handle, &cci);
7165 cci.bVisible = FALSE;
7166 SetConsoleCursorInfo(handle, &cci);
7174static const long MAXSIZE_CONSOLE_WRITING = 31366;
7178constat_parse(HANDLE h,
struct constat *s,
const WCHAR **ptrp,
long *lenp)
7180 const WCHAR *ptr = *ptrp;
7181 long rest,
len = *lenp;
7185 rest = *lenp -
len - 1;
7186 if (s->vt100.state == constat_esc) {
7189 s->vt100.state = constat_init;
7190 if (
len > 0 && *ptr != L
'[')
continue;
7191 s->vt100.state = constat_esc;
7193 else if (s->vt100.state == constat_esc) {
7196 s->vt100.state = constat_init;
7199 rest = *lenp -
len - 1;
7200 if (rest > 0) --rest;
7201 s->vt100.state = constat_seq;
7202 s->vt100.seq[0] = 0;
7204 else if (s->vt100.state >= constat_seq) {
7205 if (wc >= L
'0' && wc <= L
'9') {
7206 if (s->vt100.state < (
int)numberof(s->vt100.seq)) {
7207 int *seq = &s->vt100.seq[s->vt100.state];
7208 *seq = (*seq * 10) + (wc - L
'0');
7211 else if (s->vt100.state == constat_seq && s->vt100.seq[0] == 0 && wc == L
'?') {
7212 s->vt100.seq[s->vt100.state++] = -1;
7216 if (++s->vt100.state < (
int)numberof(s->vt100.seq)) {
7217 s->vt100.seq[s->vt100.state] = 0;
7220 s->vt100.state = (int)numberof(s->vt100.seq);
7224 constat_apply(h, s, wc);
7225 s->vt100.state = constat_init;
7230 else if ((rest = *lenp -
len) < MAXSIZE_CONSOLE_WRITING) {
7248 SOCKET sock = TO_SOCKET(fd);
7249 int save_errno =
errno;
7251 if (!is_socket(sock)) {
7252 UnlockFile((HANDLE)sock, 0, 0, LK_LEN, LK_LEN);
7253 constat_delete((HANDLE)sock);
7256 _set_osfhnd(fd, (SOCKET)INVALID_HANDLE_VALUE);
7257 socklist_delete(&sock, NULL);
7260 if (closesocket(sock) == SOCKET_ERROR) {
7261 errno = map_errno(WSAGetLastError());
7267#ifndef INVALID_SET_FILE_POINTER
7268#define INVALID_SET_FILE_POINTER ((DWORD)-1)
7272setup_overlapped(OVERLAPPED *ol,
int fd,
int iswrite, rb_off_t *_offset)
7274 memset(ol, 0,
sizeof(*ol));
7279 DWORD seek_method = ((_osfile(fd) & FAPPEND) && iswrite) ? FILE_END : FILE_CURRENT;
7283 uint64_t offset = *_offset;
7284 ol->Offset = (uint32_t)(offset & 0xFFFFFFFFLL);
7285 ol->OffsetHigh = (uint32_t)((offset & 0xFFFFFFFF00000000LL) >> 32);
7288 LARGE_INTEGER seek_offset = {0}, current_offset = {0};
7289 if (!SetFilePointerEx((HANDLE)_osfhnd(fd), seek_offset, ¤t_offset, seek_method)) {
7290 DWORD last_error = GetLastError();
7291 if (last_error != NO_ERROR) {
7292 errno = map_errno(last_error);
7298 *_offset = current_offset.QuadPart;
7300 else if (!(_osfile(fd) & (FDEV | FPIPE))) {
7302 DWORD low = SetFilePointer((HANDLE)_osfhnd(fd), 0, &high, seek_method);
7304 if (low == INVALID_SET_FILE_POINTER) {
7305 DWORD err = GetLastError();
7306 if (err != NO_ERROR) {
7307 errno = map_errno(err);
7313 ol->OffsetHigh = high;
7316 ol->hEvent = CreateEvent(NULL, TRUE, TRUE, NULL);
7318 errno = map_errno(GetLastError());
7325finish_overlapped(OVERLAPPED *ol,
int fd, DWORD size, rb_off_t *_offset)
7327 CloseHandle(ol->hEvent);
7331 DWORD seek_method = (_osfile(fd) & FAPPEND) ? FILE_END : FILE_BEGIN;
7333 LARGE_INTEGER seek_offset = {0};
7334 if (seek_method == FILE_BEGIN) {
7335 seek_offset.QuadPart = *_offset;
7338 SetFilePointerEx((HANDLE)_osfhnd(fd), seek_offset, NULL, seek_method);
7340 else if (!(_osfile(fd) & (FDEV | FPIPE))) {
7341 LONG high = ol->OffsetHigh;
7342 DWORD low = ol->Offset + size;
7343 if (low < ol->Offset)
7345 SetFilePointer((HANDLE)_osfhnd(fd), low, &high, FILE_BEGIN);
7352rb_w32_read_internal(
int fd,
void *buf,
size_t size, rb_off_t *offset)
7354 SOCKET sock = TO_SOCKET(fd);
7362 BOOL islineinput = FALSE;
7365 if (is_socket(sock))
7366 return rb_w32_recv(fd, buf, size, 0);
7369 if (_get_osfhandle(fd) == -1) {
7373 if (!offset && _osfile(fd) & FTEXT) {
7374 return _read(fd, buf, size);
7377 rb_acrt_lowio_lock_fh(fd);
7379 if (!size || _osfile(fd) & FEOFLAG) {
7380 _set_osflags(fd, _osfile(fd) & ~FEOFLAG);
7381 rb_acrt_lowio_unlock_fh(fd);
7386 isconsole = is_console(_osfhnd(fd)) && (osver.dwMajorVersion < 6 || (osver.dwMajorVersion == 6 && osver.dwMinorVersion < 2));
7389 GetConsoleMode((HANDLE)_osfhnd(fd),&mode);
7390 islineinput = (mode & ENABLE_LINE_INPUT) != 0;
7395 constat_reset((HANDLE)_osfhnd(fd));
7407 if (setup_overlapped(&ol, fd, FALSE, offset)) {
7408 rb_acrt_lowio_unlock_fh(fd);
7412 if (!ReadFile((HANDLE)_osfhnd(fd), buf,
len, &read, &ol)) {
7413 err = GetLastError();
7414 if (err == ERROR_NO_DATA && (_osfile(fd) & FPIPE)) {
7416 if (GetNamedPipeHandleState((HANDLE)_osfhnd(fd), &state, NULL, NULL, NULL, NULL, 0) && (state & PIPE_NOWAIT)) {
7417 errno = EWOULDBLOCK;
7420 errno = map_errno(err);
7422 rb_acrt_lowio_unlock_fh(fd);
7425 else if (err != ERROR_IO_PENDING) {
7426 CloseHandle(ol.hEvent);
7427 if (err == ERROR_ACCESS_DENIED)
7429 else if (err == ERROR_BROKEN_PIPE || err == ERROR_HANDLE_EOF) {
7430 rb_acrt_lowio_unlock_fh(fd);
7434 errno = map_errno(err);
7436 rb_acrt_lowio_unlock_fh(fd);
7440 wait = rb_w32_wait_events_blocking(&ol.hEvent, 1, INFINITE);
7441 if (wait != WAIT_OBJECT_0) {
7442 if (wait == WAIT_OBJECT_0 + 1)
7445 errno = map_errno(GetLastError());
7446 CloseHandle(ol.hEvent);
7447 CancelIo((HANDLE)_osfhnd(fd));
7448 rb_acrt_lowio_unlock_fh(fd);
7452 if (!GetOverlappedResult((HANDLE)_osfhnd(fd), &ol, &read, TRUE) &&
7453 (err = GetLastError()) != ERROR_HANDLE_EOF) {
7455 if (err != ERROR_BROKEN_PIPE) {
7456 errno = map_errno(err);
7459 CloseHandle(ol.hEvent);
7460 CancelIo((HANDLE)_osfhnd(fd));
7461 rb_acrt_lowio_unlock_fh(fd);
7466 err = GetLastError();
7467 errno = map_errno(err);
7470 finish_overlapped(&ol, fd, read, offset);
7474 buf = (
char *)buf + read;
7475 if (err != ERROR_OPERATION_ABORTED &&
7476 !(isconsole &&
len == 1 && (!islineinput || *((
char *)buf - 1) ==
'\n')) && size > 0)
7480 _set_osflags(fd, _osfile(fd) | FEOFLAG);
7483 rb_acrt_lowio_unlock_fh(fd);
7491rb_w32_write_internal(
int fd,
const void *buf,
size_t size, rb_off_t *offset)
7493 SOCKET sock = TO_SOCKET(fd);
7501 if (is_socket(sock))
7502 return rb_w32_send(fd, buf, size, 0);
7505 if (_get_osfhandle(fd) == -1) {
7510 if (!offset && (_osfile(fd) & FTEXT) &&
7511 (!(_osfile(fd) & FPIPE) || fd == fileno(stdout) || fd == fileno(stderr))) {
7512 ssize_t w = _write(fd, buf, size);
7513 if (w == (ssize_t)-1 &&
errno == EINVAL) {
7514 errno = map_errno(GetLastError());
7519 rb_acrt_lowio_lock_fh(fd);
7521 if (!size || _osfile(fd) & FEOFLAG) {
7522 rb_acrt_lowio_unlock_fh(fd);
7528 len = (_osfile(fd) & FDEV) ? min(MAXSIZE_CONSOLE_WRITING, size) : size;
7533 if (setup_overlapped(&ol, fd, TRUE, offset)) {
7534 rb_acrt_lowio_unlock_fh(fd);
7538 if (!WriteFile((HANDLE)_osfhnd(fd), buf,
len, &written, &ol)) {
7539 err = GetLastError();
7540 if (err != ERROR_IO_PENDING) {
7541 CloseHandle(ol.hEvent);
7542 if (err == ERROR_ACCESS_DENIED)
7545 errno = map_errno(err);
7547 rb_acrt_lowio_unlock_fh(fd);
7551 wait = rb_w32_wait_events_blocking(&ol.hEvent, 1, INFINITE);
7552 if (wait != WAIT_OBJECT_0) {
7553 if (wait == WAIT_OBJECT_0 + 1)
7556 errno = map_errno(GetLastError());
7557 CloseHandle(ol.hEvent);
7558 CancelIo((HANDLE)_osfhnd(fd));
7559 rb_acrt_lowio_unlock_fh(fd);
7563 if (!GetOverlappedResult((HANDLE)_osfhnd(fd), &ol, &written, TRUE)) {
7564 errno = map_errno(GetLastError());
7565 CloseHandle(ol.hEvent);
7566 CancelIo((HANDLE)_osfhnd(fd));
7567 rb_acrt_lowio_unlock_fh(fd);
7572 finish_overlapped(&ol, fd, written, offset);
7575 if (written ==
len) {
7576 buf = (
const char *)buf +
len;
7581 size_t newlen =
len / 2;
7583 size +=
len - newlen;
7588 errno = EWOULDBLOCK;
7591 rb_acrt_lowio_unlock_fh(fd);
7597rb_w32_read(
int fd,
void *buf,
size_t size)
7599 return rb_w32_read_internal(fd, buf, size, NULL);
7603rb_w32_write(
int fd,
const void *buf,
size_t size)
7605 return rb_w32_write_internal(fd, buf, size, NULL);
7609rb_w32_pread(
int descriptor,
void *base,
size_t size, rb_off_t offset)
7611 return rb_w32_read_internal(descriptor, base, size, &offset);
7615rb_w32_pwrite(
int descriptor,
const void *base,
size_t size, rb_off_t offset)
7617 return rb_w32_write_internal(descriptor, base, size, &offset);
7622rb_w32_write_console(uintptr_t strarg,
int fd)
7625 DWORD dwMode, reslen;
7629 const WCHAR *ptr, *next;
7633 handle = (HANDLE)_osfhnd(fd);
7634 if (!GetConsoleMode(handle, &dwMode))
7637 s = constat_handle(handle);
7647 case ENCINDEX_US_ASCII:
7648 case ENCINDEX_ASCII_8BIT:
7650 case ENCINDEX_UTF_8:
7651 ptr = wbuffer = mbstr_to_wstr(CP_UTF8, RSTRING_PTR(str), RSTRING_LEN(str), &
len);
7652 if (!ptr)
return -1L;
7654 case ENCINDEX_UTF_16LE:
7655 ptr = (
const WCHAR *)RSTRING_PTR(str);
7656 len = RSTRING_LEN(str) /
sizeof(WCHAR);
7660 if (dwMode & ENABLE_VIRTUAL_TERMINAL_PROCESSING) {
7661 if (!WriteConsoleW(handle, ptr,
len, &reslen, NULL))
7662 reslen = (DWORD)-1L;
7666 long curlen = constat_parse(handle, s, (next = ptr, &next), &
len);
7667 reslen += next - ptr;
7670 if (!WriteConsoleW(handle, ptr, curlen, &written, NULL)) {
7671 reslen = (DWORD)-1L;
7680 return (
long)reslen;
7683#if RUBY_MSVCRT_VERSION < 80 && !defined(HAVE__GMTIME64_S)
7686unixtime_to_filetime(time_t time, FILETIME *ft)
7690 tmp.QuadPart = ((
LONG_LONG)time + (
LONG_LONG)((1970-1601)*365.2425) * 24 * 60 * 60) * 10 * 1000 * 1000;
7691 ft->dwLowDateTime = tmp.LowPart;
7692 ft->dwHighDateTime = tmp.HighPart;
7699timespec_to_filetime(
const struct timespec *ts, FILETIME *ft)
7703 tmp.QuadPart = ((
LONG_LONG)ts->tv_sec + (
LONG_LONG)((1970-1601)*365.2425) * 24 * 60 * 60) * 10 * 1000 * 1000;
7704 tmp.QuadPart += ts->tv_nsec / 100;
7705 ft->dwLowDateTime = tmp.LowPart;
7706 ft->dwHighDateTime = tmp.HighPart;
7712wutimensat(
int dirfd,
const WCHAR *path,
const struct timespec *times,
int flags)
7715 FILETIME atime, mtime;
7716 struct stati128 stat;
7720 if (dirfd != AT_FDCWD) {
7730 if (wstati128(path, &stat, FALSE)) {
7735 if (timespec_to_filetime(×[0], &atime)) {
7738 if (timespec_to_filetime(×[1], &mtime)) {
7743 get_systemtime(&atime);
7748 const DWORD attr = GetFileAttributesW(path);
7749 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY))
7750 SetFileAttributesW(path, attr & ~FILE_ATTRIBUTE_READONLY);
7751 hFile = open_special(path, GENERIC_WRITE, 0);
7752 if (hFile == INVALID_HANDLE_VALUE) {
7753 errno = map_errno(GetLastError());
7757 if (!SetFileTime(hFile, NULL, &atime, &mtime)) {
7758 errno = map_errno(GetLastError());
7763 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY))
7764 SetFileAttributesW(path, attr);
7772w32_utimensat(
int dirfd,
const char *path,
const struct timespec *times,
int flags, UINT cp)
7774 WCHAR *wpath = mbstr_to_wstr(cp, path, -1, NULL);
7778 ret = wutimensat(dirfd, wpath, times, flags);
7786rb_w32_uutime(
const char *path,
const struct utimbuf *times)
7790 ts[0].tv_sec = times->actime;
7792 ts[1].tv_sec = times->modtime;
7794 return w32_utimensat(AT_FDCWD, path, ts, 0, CP_UTF8);
7799rb_w32_utime(
const char *path,
const struct utimbuf *times)
7803 ts[0].tv_sec = times->actime;
7805 ts[1].tv_sec = times->modtime;
7807 return w32_utimensat(AT_FDCWD, path, ts, 0, filecp());
7812rb_w32_uutimes(
const char *path,
const struct timeval *times)
7816 ts[0].tv_sec = times[0].tv_sec;
7817 ts[0].tv_nsec = times[0].tv_usec * 1000;
7818 ts[1].tv_sec = times[1].tv_sec;
7819 ts[1].tv_nsec = times[1].tv_usec * 1000;
7820 return w32_utimensat(AT_FDCWD, path, ts, 0, CP_UTF8);
7825rb_w32_utimes(
const char *path,
const struct timeval *times)
7829 ts[0].tv_sec = times[0].tv_sec;
7830 ts[0].tv_nsec = times[0].tv_usec * 1000;
7831 ts[1].tv_sec = times[1].tv_sec;
7832 ts[1].tv_nsec = times[1].tv_usec * 1000;
7833 return w32_utimensat(AT_FDCWD, path, ts, 0, filecp());
7838rb_w32_uutimensat(
int dirfd,
const char *path,
const struct timespec *times,
int flags)
7840 return w32_utimensat(dirfd, path, times, flags, CP_UTF8);
7845rb_w32_utimensat(
int dirfd,
const char *path,
const struct timespec *times,
int flags)
7847 return w32_utimensat(dirfd, path, times, flags, filecp());
7852rb_w32_uchdir(
const char *path)
7857 if (!(wpath = utf8_to_wstr(path, NULL)))
7859 ret = _wchdir(wpath);
7866wmkdir(
const WCHAR *wpath,
int mode)
7871 if (CreateDirectoryW(wpath, NULL) == FALSE) {
7872 errno = map_errno(GetLastError());
7875 if (_wchmod(wpath, mode) == -1) {
7876 RemoveDirectoryW(wpath);
7886rb_w32_umkdir(
const char *path,
int mode)
7891 if (!(wpath = utf8_to_wstr(path, NULL)))
7893 ret = wmkdir(wpath, mode);
7900rb_w32_mkdir(
const char *path,
int mode)
7905 if (!(wpath = filecp_to_wstr(path, NULL)))
7907 ret = wmkdir(wpath, mode);
7914wrmdir(
const WCHAR *wpath)
7918 const DWORD attr = GetFileAttributesW(wpath);
7919 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY)) {
7920 SetFileAttributesW(wpath, attr & ~FILE_ATTRIBUTE_READONLY);
7922 if (RemoveDirectoryW(wpath) == FALSE) {
7923 errno = map_errno(GetLastError());
7925 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY)) {
7926 SetFileAttributesW(wpath, attr);
7935rb_w32_rmdir(
const char *path)
7940 if (!(wpath = filecp_to_wstr(path, NULL)))
7942 ret = wrmdir(wpath);
7949rb_w32_urmdir(
const char *path)
7954 if (!(wpath = utf8_to_wstr(path, NULL)))
7956 ret = wrmdir(wpath);
7963wunlink(
const WCHAR *path)
7966 const DWORD SYMLINKD = FILE_ATTRIBUTE_REPARSE_POINT|FILE_ATTRIBUTE_DIRECTORY;
7968 const DWORD attr = GetFileAttributesW(path);
7969 if (attr == (DWORD)-1) {
7971 else if ((attr & SYMLINKD) == SYMLINKD) {
7972 ret = RemoveDirectoryW(path);
7975 if (attr & FILE_ATTRIBUTE_READONLY) {
7976 SetFileAttributesW(path, attr & ~FILE_ATTRIBUTE_READONLY);
7978 ret = DeleteFileW(path);
7981 errno = map_errno(GetLastError());
7983 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY)) {
7984 SetFileAttributesW(path, attr);
7993rb_w32_uunlink(
const char *path)
7998 if (!(wpath = utf8_to_wstr(path, NULL)))
8000 ret = wunlink(wpath);
8007rb_w32_unlink(
const char *path)
8012 if (!(wpath = filecp_to_wstr(path, NULL)))
8014 ret = wunlink(wpath);
8021rb_w32_uchmod(
const char *path,
int mode)
8026 if (!(wpath = utf8_to_wstr(path, NULL)))
8028 ret = _wchmod(wpath, mode);
8035fchmod(
int fd,
int mode)
8037 typedef BOOL (WINAPI *set_file_information_by_handle_func)
8038 (HANDLE, int,
void*, DWORD);
8039 static set_file_information_by_handle_func set_file_info =
8040 (set_file_information_by_handle_func)-1;
8044 LARGE_INTEGER CreationTime;
8045 LARGE_INTEGER LastAccessTime;
8046 LARGE_INTEGER LastWriteTime;
8047 LARGE_INTEGER ChangeTime;
8048 DWORD FileAttributes;
8049 } info = {{{0}}, {{0}}, {{0}},};
8050 HANDLE h = (HANDLE)_get_osfhandle(fd);
8052 if (h == INVALID_HANDLE_VALUE) {
8056 if (set_file_info == (set_file_information_by_handle_func)-1) {
8058 set_file_info = (set_file_information_by_handle_func)
8059 get_proc_address(
"kernel32",
"SetFileInformationByHandle", NULL);
8061 if (!set_file_info) {
8066 info.FileAttributes = FILE_ATTRIBUTE_NORMAL;
8067 if (!(mode & 0200)) info.FileAttributes |= FILE_ATTRIBUTE_READONLY;
8068 if (!set_file_info(h, 0, &info,
sizeof(info))) {
8069 errno = map_errno(GetLastError());
8077rb_w32_isatty(
int fd)
8082 if (_get_osfhandle(fd) == -1) {
8085 if (!GetConsoleMode((HANDLE)_osfhnd(fd), &mode)) {
8092#if defined(_MSC_VER) && RUBY_MSVCRT_VERSION <= 60
8093extern long _ftol(
double);
8114 int *ip = (
int *)(&x + 1) - 1;
8121rb_w32_inet_ntop(
int af,
const void *addr,
char *numaddr,
size_t numaddr_len)
8123 typedef char *(WSAAPI inet_ntop_t)(
int,
void *,
char *,
size_t);
8124 static inet_ntop_t *pInetNtop = (inet_ntop_t *)-1;
8125 if (pInetNtop == (inet_ntop_t *)-1)
8126 pInetNtop = (inet_ntop_t *)get_proc_address(
"ws2_32",
"inet_ntop", NULL);
8128 return pInetNtop(af, (
void *)addr, numaddr, numaddr_len);
8132 memcpy(&in.s_addr, addr,
sizeof(in.s_addr));
8133 snprintf(numaddr, numaddr_len,
"%s", inet_ntoa(in));
8140rb_w32_inet_pton(
int af,
const char *src,
void *dst)
8142 typedef int (WSAAPI inet_pton_t)(int,
const char*,
void *);
8143 static inet_pton_t *pInetPton = (inet_pton_t *)-1;
8144 if (pInetPton == (inet_pton_t *)-1)
8145 pInetPton = (inet_pton_t *)get_proc_address(
"ws2_32",
"inet_pton", NULL);
8147 return pInetPton(af, src, dst);
8154rb_w32_fd_is_text(
int fd)
8156 return _osfile(fd) & FTEXT;
8159#if RUBY_MSVCRT_VERSION < 80 && !defined(HAVE__GMTIME64_S)
8162unixtime_to_systemtime(
const time_t t, SYSTEMTIME *st)
8165 if (unixtime_to_filetime(t, &ft))
return -1;
8166 if (!FileTimeToSystemTime(&ft, st))
return -1;
8172systemtime_to_tm(
const SYSTEMTIME *st,
struct tm *t)
8174 int y = st->wYear, m = st->wMonth, d = st->wDay;
8175 t->tm_sec = st->wSecond;
8176 t->tm_min = st->wMinute;
8177 t->tm_hour = st->wHour;
8178 t->tm_mday = st->wDay;
8179 t->tm_mon = st->wMonth - 1;
8180 t->tm_year = y - 1900;
8181 t->tm_wday = st->wDayOfWeek;
8189 d += 31 + 28 + (!(y % 4) && ((y % 100) || !(y % 400)));
8190 d += ((m - 3) * 153 + 2) / 5;
8198systemtime_to_localtime(TIME_ZONE_INFORMATION *tz, SYSTEMTIME *gst, SYSTEMTIME *lst)
8200 TIME_ZONE_INFORMATION stdtz;
8203 if (!SystemTimeToTzSpecificLocalTime(tz, gst, lst))
return -1;
8205 GetTimeZoneInformation(&stdtz);
8208 if (tz->StandardBias == tz->DaylightBias)
return 0;
8209 if (!tz->StandardDate.wMonth)
return 0;
8210 if (!tz->DaylightDate.wMonth)
return 0;
8211 if (tz != &stdtz) stdtz = *tz;
8213 stdtz.StandardDate.wMonth = stdtz.DaylightDate.wMonth = 0;
8214 if (!SystemTimeToTzSpecificLocalTime(&stdtz, gst, &sst))
return 0;
8215 if (lst->wMinute == sst.wMinute && lst->wHour == sst.wHour)
8221#ifdef HAVE__GMTIME64_S
8222# ifndef HAVE__LOCALTIME64_S
8224# define HAVE__LOCALTIME64_S 1
8226# ifndef MINGW_HAS_SECURE_API
8227 _CRTIMP errno_t __cdecl _gmtime64_s(
struct tm* tm,
const __time64_t *time);
8228 _CRTIMP errno_t __cdecl _localtime64_s(
struct tm* tm,
const __time64_t *time);
8230# define gmtime_s _gmtime64_s
8231# define localtime_s _localtime64_s
8236gmtime_r(
const time_t *tp,
struct tm *rp)
8244#if RUBY_MSVCRT_VERSION >= 80 || defined(HAVE__GMTIME64_S)
8245 e = gmtime_s(rp, tp);
8246 if (e != 0)
goto error;
8250 if (unixtime_to_systemtime(*tp, &st))
goto error;
8252 systemtime_to_tm(&st, rp);
8260localtime_r(
const time_t *tp,
struct tm *rp)
8268#if RUBY_MSVCRT_VERSION >= 80 || defined(HAVE__LOCALTIME64_S)
8269 e = localtime_s(rp, tp);
8273 SYSTEMTIME gst, lst;
8274 if (unixtime_to_systemtime(*tp, &gst))
goto error;
8275 rp->tm_isdst = systemtime_to_localtime(NULL, &gst, &lst);
8276 systemtime_to_tm(&lst, rp);
8284rb_w32_wrap_io_handle(HANDLE h,
int flags)
8287 int len =
sizeof(tmp);
8288 int r = getsockopt((SOCKET)h, SOL_SOCKET, SO_DEBUG, (
char *)&tmp, &
len);
8289 if (r != SOCKET_ERROR || WSAGetLastError() != WSAENOTSOCK) {
8291 if (flags & O_NONBLOCK) {
8292 flags &= ~O_NONBLOCK;
8295 socklist_insert((SOCKET)h, f);
8297 else if (flags & O_NONBLOCK) {
8301 return rb_w32_open_osfhandle((intptr_t)h, flags);
8306rb_w32_unwrap_io_handle(
int fd)
8308 SOCKET sock = TO_SOCKET(fd);
8309 _set_osfhnd(fd, (SOCKET)INVALID_HANDLE_VALUE);
8310 if (!is_socket(sock)) {
8311 UnlockFile((HANDLE)sock, 0, 0, LK_LEN, LK_LEN);
8312 constat_delete((HANDLE)sock);
8315 socklist_delete(&sock, NULL);
8320#if !defined(__MINGW64__) && defined(__MINGW64_VERSION_MAJOR)
8326rb_w32_pow(
double x,
double y)
8330 unsigned int default_control = _controlfp(0, 0);
8331 _controlfp(_PC_64, _MCW_PC);
8334 _controlfp(default_control, _MCW_PC);
8342 BY_HANDLE_FILE_INFORMATION bhfi;
8353 tmp = rb_check_convert_type_with_id(*file,
T_FILE,
"IO", idTo_io);
8356 if (f == (HANDLE)-1)
return INVALID_HANDLE_VALUE;
8365 tmp = rb_str_encode_ospath(*file);
8366 len = MultiByteToWideChar(CP_UTF8, 0, RSTRING_PTR(tmp), -1, NULL, 0);
8368 MultiByteToWideChar(CP_UTF8, 0, RSTRING_PTR(tmp), -1, ptr,
len);
8369 f = CreateFileW(ptr, 0,
8370 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
8371 FILE_FLAG_BACKUP_SEMANTICS, NULL);
8373 if (f == INVALID_HANDLE_VALUE)
return f;
8376 if (GetFileType(f) == FILE_TYPE_DISK) {
8378 ZeroMemory(st,
sizeof(*st));
8379 err = get_ino(f, &st->info.fii);
8381 st->file_id_p = TRUE;
8384 else if (err != ERROR_INVALID_PARAMETER) {
8386 return INVALID_HANDLE_VALUE;
8390 if (GetFileInformationByHandle(f, &st->info.bhfi)) {
8391 st->file_id_p = FALSE;
8395 if (ret) CloseHandle(ret);
8396 return INVALID_HANDLE_VALUE;
8400close_handle(
VALUE h)
8402 CloseHandle((HANDLE)h);
8412call_w32_io_info(
VALUE arg)
8415 return (
VALUE)w32_io_info(p->fname, p->st);
8419rb_w32_file_identical_p(
VALUE fname1,
VALUE fname2)
8422 HANDLE f1 = 0, f2 = 0;
8424 f1 = w32_io_info(&fname1, &st1);
8425 if (f1 == INVALID_HANDLE_VALUE)
return Qfalse;
8428 arg.fname = &fname2;
8433 f2 = w32_io_info(&fname2, &st2);
8435 if (f2 == INVALID_HANDLE_VALUE)
return Qfalse;
8436 if (f2) CloseHandle(f2);
8438 if (st1.file_id_p != st2.file_id_p)
return Qfalse;
8439 if (!st1.file_id_p) {
8440 if (st1.info.bhfi.dwVolumeSerialNumber == st2.info.bhfi.dwVolumeSerialNumber &&
8441 st1.info.bhfi.nFileIndexHigh == st2.info.bhfi.nFileIndexHigh &&
8442 st1.info.bhfi.nFileIndexLow == st2.info.bhfi.nFileIndexLow)
8446 if (st1.info.fii.VolumeSerialNumber == st2.info.fii.VolumeSerialNumber &&
8447 memcmp(&st1.info.fii.FileId, &st2.info.fii.FileId,
sizeof(
FILE_ID_128)) == 0)
8454rb_w32_set_thread_description(HANDLE th,
const WCHAR *name)
8457 typedef HRESULT (WINAPI *set_thread_description_func)(HANDLE, PCWSTR);
8458 static set_thread_description_func set_thread_description =
8459 (set_thread_description_func)-1;
8460 if (set_thread_description == (set_thread_description_func)-1) {
8462 set_thread_description = (set_thread_description_func)
8463 get_proc_address(
"kernel32",
"SetThreadDescription", NULL);
8465 if (set_thread_description) {
8466 result = set_thread_description(th, name);
8472rb_w32_set_thread_description_str(HANDLE th,
VALUE name)
8474 int idx, result = FALSE;
8478 return rb_w32_set_thread_description(th, L
"");
8481 idx = rb_enc_get_index(name);
8482 if (idx == ENCINDEX_UTF_16LE) {
8483 result = rb_w32_set_thread_description(th, s);
8486 name =
rb_str_conv_enc(name, rb_enc_from_index(idx), rb_utf8_encoding());
8487 s = mbstr_to_wstr(CP_UTF8, RSTRING_PTR(name), RSTRING_LEN(name)+1, NULL);
8488 result = rb_w32_set_thread_description(th, s);
8497#if RUBY_MSVCRT_VERSION < 120
8498#include "missing/nextafter.c"
8502rb_w32_mmap(
void *addr,
size_t len,
int prot,
int flags,
int fd, rb_off_t offset)
8506 DWORD protect = PAGE_EXECUTE_READWRITE;
8508 if (fd > 0 || offset) {
8523 ptr = VirtualAlloc(addr,
len, MEM_RESERVE | MEM_COMMIT, protect);
8525 errno = rb_w32_map_errno(GetLastError());
8533rb_w32_munmap(
void *addr,
size_t len)
8535 if (!VirtualFree(addr, 0, MEM_RELEASE)) {
8536 errno = rb_w32_map_errno(GetLastError());
8544rb_w32_mprotect(
void *addr,
size_t len,
int prot)
8560 if (prot & PROT_EXEC) {
8561 if (!FlushInstructionCache(GetCurrentProcess(), addr,
len)) {
8562 errno = rb_w32_map_errno(GetLastError());
int ruby_glob_func(const char *path, VALUE arg, void *enc)
Type of a glob callback function.
#define T_FILE
Old name of RUBY_T_FILE.
#define REALLOC_N
Old name of RB_REALLOC_N.
#define ALLOCV
Old name of RB_ALLOCV.
#define ISSPACE
Old name of rb_isspace.
#define ALLOC
Old name of RB_ALLOC.
#define xfree
Old name of ruby_xfree.
#define xrealloc
Old name of ruby_xrealloc.
#define ECONV_UNDEF_REPLACE
Old name of RUBY_ECONV_UNDEF_REPLACE.
#define ENCODING_GET(obj)
Old name of RB_ENCODING_GET.
#define ECONV_INVALID_REPLACE
Old name of RUBY_ECONV_INVALID_REPLACE.
#define ASSUME
Old name of RBIMPL_ASSUME.
#define ALLOC_N
Old name of RB_ALLOC_N.
#define ISALPHA
Old name of rb_isalpha.
#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.
#define ISALNUM
Old name of rb_isalnum.
#define ALLOCV_END
Old name of RB_ALLOCV_END.
VALUE rb_str_conv_enc(VALUE str, rb_encoding *from, rb_encoding *to)
Encoding conversion main routine.
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.
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.
void rb_write_error2(const char *str, long len)
Identical to rb_write_error(), except it additionally takes the message's length.
#define rb_strlen_lit(str)
Length of a string literal.
#define rb_utf8_str_new(str, len)
Identical to rb_str_new, except it generates a string of "UTF-8" encoding.
VALUE rb_f_notimplement(int argc, const VALUE *argv, VALUE obj, VALUE marker)
Raises rb_eNotImpError.
int rb_io_descriptor(VALUE io)
Returns an integer representing the numeric file descriptor for io.
int len
Length of the buffer.
char * ruby_strdup(const char *str)
This is our own version of strdup(3) that uses ruby_xmalloc() instead of system malloc (benefits our ...
#define strdup(s)
Just another name of ruby_strdup.
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.
struct rb_vm_struct ruby_vm_t
The opaque struct to hold VM internals.
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.
void rb_w32_fd_copy(rb_fdset_t *dst, const fd_set *src, int max)
Destructively overwrites an fdset with another.
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.
#define MEMCPY(p1, p2, type, n)
Handy macro to call memcpy.
#define ALLOCA_N(type, n)
#define MEMZERO(p, type, n)
Handy macro to erase a region of memory.
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
VALUE type(ANYARGS)
ANYARGS-ed function type.
VALUE rb_ensure(type *q, VALUE w, type *e, VALUE r)
An equivalent of ensure clause.
#define RBIMPL_ATTR_NONNULL(list)
Wraps (or simulates) __attribute__((nonnull))
#define PRI_PIDT_PREFIX
A rb_sprintf() format prefix to be used for a pid_t parameter.
#define rb_fd_init
Initialises the :given :rb_fdset_t.
#define StringValueCStr(v)
Identical to StringValuePtr, except it additionally checks for the contents for viability as a C stri...
#define FilePathValue(v)
Ensures that the parameter object is a path.
#define errno
Ractor-aware version of errno.
The data structure which wraps the fd_set bitmap used by select(2).
fd_set * fdset
File descriptors buffer.
int capa
Maximum allowed number of FDs.
intptr_t SIGNED_VALUE
A signed integer type that has the same width with VALUE.
uintptr_t VALUE
Type that represents a Ruby object.