22 #undef __STRICT_ANSI__
45 #if defined _MSC_VER && _MSC_VER >= 1400
55 #include "ruby/win32.h"
57 #include "win32/dir.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))
72 static int w32_wopen(
const WCHAR *file,
int oflag,
int perm);
73 static int w32_stati128(
const char *path,
struct stati128 *st, UINT cp, BOOL lstat);
74 static 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
91 #undef rb_w32_stati128
93 #undef dln_find_file_r
94 #define dln_find_exe_r(fname, path, buf, size) rb_w32_udln_find_exe_r(fname, path, buf, size, cp)
95 #define dln_find_file_r(fname, path, buf, size) rb_w32_udln_find_file_r(fname, path, buf, size, cp)
100 # if defined MAX_PATH
101 # define PATH_MAX MAX_PATH
102 # elif defined HAVE_SYS_PARAM_H
103 # include <sys/param.h>
104 # define PATH_MAX MAXPATHLEN
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)
131 int rb_w32_reparse_symlink_p(
const WCHAR *path);
133 static int has_redirection(
const char *, UINT);
134 int rb_w32_wait_events(HANDLE *events,
int num, DWORD timeout);
135 static int rb_w32_open_osfhandle(intptr_t osfhandle,
int flags);
136 static int wstati128(
const WCHAR *path,
struct stati128 *st, BOOL lstat);
139 static FARPROC get_proc_address(
const char *module,
const char *func, HANDLE *mh);
141 #define RUBY_CRITICAL if (0) {} else
144 static const struct {
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 },
284 rb_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
306 static const char *NTLoginName;
308 static OSVERSIONINFO osver;
314 memset(&osver, 0,
sizeof(OSVERSIONINFO));
315 osver.dwOSVersionInfoSize =
sizeof(OSVERSIONINFO);
316 GetVersionEx(&osver);
324 return osver.dwPlatformId;
332 return osver.dwMajorVersion;
338 #define LK_ERR(f,i) \
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
356 flock_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);
395 flock(
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,
405 static inline WCHAR *
406 translate_wchar(WCHAR *p,
int from,
int to)
417 translate_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
433 #ifndef CSIDL_WINDOWS
434 #define CSIDL_WINDOWS 36
437 #define CSIDL_SYSTEM 37
439 #ifndef CSIDL_PROFILE
440 #define CSIDL_PROFILE 40
445 get_special_folder(
int n, WCHAR *buf,
size_t len)
451 if (SHGetSpecialFolderLocation(NULL, n, &pidl) == 0) {
452 f = SHGetPathFromIDListEx(pidl, buf,
len, 0);
454 alloc->lpVtbl->Free(alloc, pidl);
455 alloc->lpVtbl->Release(alloc);
462 regulate_path(WCHAR *path)
464 WCHAR *p = translate_wchar(path, L
'\\', L
'/');
465 if (p - path == 2 && path[1] == L
':') {
473 get_proc_address(
const char *module,
const char *func, HANDLE *mh)
479 h = LoadLibrary(module);
481 h = GetModuleHandle(module);
485 ptr = GetProcAddress(h, func);
497 rb_w32_special_folder(
int type)
499 WCHAR path[PATH_MAX];
501 if (!get_special_folder(
type, path, numberof(path)))
return Qnil;
506 #if defined _MSC_VER && _MSC_VER <= 1200
508 #define GetSystemWindowsDirectoryW GetWindowsDirectoryW
513 rb_w32_system_tmpdir(WCHAR *path, UINT
len)
515 static const WCHAR temp[] = L
"temp";
518 if (!get_special_folder(CSIDL_LOCAL_APPDATA, path,
len)) {
519 if (GetSystemWindowsDirectoryW(path,
len))
return 0;
521 p = translate_wchar(path, L
'\\', L
'/');
522 if (*(p - 1) != L
'/') *p++ = L
'/';
523 if ((UINT)(p - path + numberof(temp)) >=
len)
return 0;
524 memcpy(p, temp,
sizeof(temp));
525 return (UINT)(p - path + numberof(temp) - 1);
538 rb_w32_home_dir(
void)
540 WCHAR *buffer = NULL;
541 size_t buffer_len = MAX_PATH,
len = 0;
543 HOME_NONE, ENV_HOME, ENV_USERPROFILE, ENV_DRIVEPATH
544 } home_type = HOME_NONE;
546 if ((
len = GetEnvironmentVariableW(L
"HOME", NULL, 0)) != 0) {
548 home_type = ENV_HOME;
550 else if ((
len = GetEnvironmentVariableW(L
"USERPROFILE", NULL, 0)) != 0) {
552 home_type = ENV_USERPROFILE;
554 else if ((
len = GetEnvironmentVariableW(L
"HOMEDRIVE", NULL, 0)) != 0) {
556 if ((
len = GetEnvironmentVariableW(L
"HOMEPATH", NULL, 0)) != 0) {
558 home_type = ENV_DRIVEPATH;
563 buffer = malloc(
sizeof(WCHAR) * buffer_len);
564 if (buffer == NULL)
return NULL;
568 GetEnvironmentVariableW(L
"HOME", buffer, buffer_len);
570 case ENV_USERPROFILE:
571 GetEnvironmentVariableW(L
"USERPROFILE", buffer, buffer_len);
574 len = GetEnvironmentVariableW(L
"HOMEDRIVE", buffer, buffer_len);
575 GetEnvironmentVariableW(L
"HOMEPATH", buffer +
len, buffer_len -
len);
578 if (!get_special_folder(CSIDL_PROFILE, buffer, buffer_len) &&
579 !get_special_folder(CSIDL_PERSONAL, buffer, buffer_len)) {
583 buffer = realloc(buffer,
sizeof(WCHAR) * (lstrlenW(buffer) + 1));
588 regulate_path(buffer);
599 if (!GetEnvironmentVariableW(L
"HOME", env, numberof(env))) {
600 WCHAR *whome = rb_w32_home_dir();
602 _wputenv_s(L
"HOME", whome);
607 if (!GetEnvironmentVariableW(L
"USER", env, numberof(env))) {
609 if (!GetEnvironmentVariableW(L
"USERNAME", env, numberof(env)) &&
610 !GetUserNameW(env, (
len = numberof(env), &
len))) {
611 NTLoginName =
"<Unknown>";
614 _wputenv_s(L
"USER", env);
615 NTLoginName = rb_w32_wstr_to_mbstr(CP_UTF8, env, -1, NULL);
619 NTLoginName = rb_w32_wstr_to_mbstr(CP_UTF8, env, -1, NULL);
622 if (!GetEnvironmentVariableW(L
"TMPDIR", env, numberof(env)) &&
623 !GetEnvironmentVariableW(L
"TMP", env, numberof(env)) &&
624 !GetEnvironmentVariableW(L
"TEMP", env, numberof(env)) &&
625 rb_w32_system_tmpdir(env, numberof(env))) {
626 _wputenv_s(L
"TMPDIR", env);
630 static void init_stdhandle(
void);
632 #if RUBY_MSVCRT_VERSION >= 80
635 invalid_parameter(
const wchar_t *expr,
const wchar_t *func,
const wchar_t *file,
unsigned int line, uintptr_t dummy)
640 int ruby_w32_rtc_error;
647 rtc_error_handler(
int e, const
char *src,
int line, const
char *exe, const
char *fmt, ...)
652 if (!ruby_w32_rtc_error)
return 0;
664 static CRITICAL_SECTION select_mutex;
666 static CRITICAL_SECTION socklist_mutex;
669 static CRITICAL_SECTION conlist_mutex;
671 #define conlist_disabled ((st_table *)-1)
673 #define thread_exclusive(obj) \
674 for (bool exclusive_for_##obj = (EnterCriticalSection(&obj##_mutex), true); \
675 exclusive_for_##obj; \
676 exclusive_for_##obj = (LeaveCriticalSection(&obj##_mutex), false))
678 static CRITICAL_SECTION uenvarea_mutex;
679 static char *uenvarea;
684 int state, seq[16], reverse;
689 enum {constat_init = -2, constat_esc = -1, constat_seq = 0};
693 free_conlist(st_data_t key, st_data_t val, st_data_t arg)
701 constat_delete(HANDLE h)
703 thread_exclusive(conlist) {
704 if (conlist && conlist != conlist_disabled) {
705 st_data_t key = (st_data_t)h, val;
706 st_delete(conlist, &key, &val);
717 DeleteCriticalSection(&select_mutex);
718 DeleteCriticalSection(&socklist_mutex);
719 DeleteCriticalSection(&conlist_mutex);
720 thread_exclusive(uenvarea) {
726 DeleteCriticalSection(&uenvarea_mutex);
733 EnterCriticalSection(&socklist_mutex);
735 st_free_table(socklist);
738 LeaveCriticalSection(&socklist_mutex);
740 EnterCriticalSection(&conlist_mutex);
741 if (conlist && conlist != conlist_disabled) {
743 st_free_table(conlist);
746 LeaveCriticalSection(&conlist_mutex);
749 #define ATOMIC_LONG_CAS(var, oldval, newval) InterlockedCompareExchange(&(var), (newval), (oldval))
753 install_vm_exit_handler(
void)
755 static LONG installed = 0;
758 while ((i = ATOMIC_LONG_CAS(installed, 0, -1)) != 1) {
764 ATOMIC_LONG_CAS(installed, -1, 1);
780 version = MAKEWORD(2, 0);
781 if (WSAStartup(version, &retdata))
782 rb_fatal(
"Unable to locate winsock library!");
783 if (LOBYTE(retdata.wVersion) != 2)
784 rb_fatal(
"could not find version 2 of winsock dll");
786 InitializeCriticalSection(&select_mutex);
787 InitializeCriticalSection(&socklist_mutex);
788 InitializeCriticalSection(&conlist_mutex);
790 atexit(exit_handler);
793 #define MAKE_SOCKDATA(af, fl) ((int)((((int)af)<<4)|((fl)&0xFFFF)))
794 #define GET_FAMILY(v) ((int)(((v)>>4)&0xFFFF))
795 #define GET_FLAGS(v) ((int)((v)&0xFFFF))
799 socklist_insert(SOCKET sock,
int flag)
803 thread_exclusive(socklist) {
805 socklist = st_init_numtable();
806 install_vm_exit_handler();
808 ret = st_insert(socklist, (st_data_t)sock, (st_data_t)flag);
816 socklist_lookup(SOCKET sock,
int *flagp)
821 thread_exclusive(socklist) {
822 if (!socklist)
continue;
823 ret = st_lookup(socklist, (st_data_t)sock, &data);
833 socklist_delete(SOCKET *sockp,
int *flagp)
839 thread_exclusive(socklist) {
840 if (!socklist)
continue;
841 key = (st_data_t)*sockp;
843 data = (st_data_t)*flagp;
844 ret = st_delete(socklist, &key, &data);
846 *sockp = (SOCKET)key;
855 #if RUBY_MSVCRT_VERSION >= 80
857 # define _CrtSetReportMode(type,mode) ((void)0)
858 # define _RTC_SetErrorFunc(func) ((void)0)
860 static void set_pioinfo_extra(
void);
862 static int w32_cmdvector(
const WCHAR *,
char ***, UINT,
rb_encoding *);
868 rb_w32_sysinit(
int *argc,
char ***argv)
870 #if RUBY_MSVCRT_VERSION >= 80
872 _CrtSetReportMode(_CRT_ASSERT, 0);
873 _set_invalid_parameter_handler(invalid_parameter);
874 _RTC_SetErrorFunc(rtc_error_handler);
877 SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOGPFAULTERRORBOX);
884 *argc = w32_cmdvector(GetCommandLineW(), argv, CP_UTF8, &OnigEncodingUTF_8);
892 InitializeCriticalSection(&uenvarea_mutex);
904 return (
char *)NTLoginName;
907 #define MAXCHILDNUM 256
916 #define FOREACH_CHILD(v) do { \
917 struct ChildRecord* v; \
918 for (v = ChildRecord; v < ChildRecord + sizeof(ChildRecord) / sizeof(ChildRecord[0]); ++v)
919 #define END_FOREACH_CHILD } while (0)
923 FindChildSlot(rb_pid_t pid)
926 FOREACH_CHILD(child) {
927 if (child->pid == pid) {
936 FindChildSlotByHandle(HANDLE h)
939 FOREACH_CHILD(child) {
940 if (child->hProcess == h) {
951 HANDLE h = child->hProcess;
952 child->hProcess = NULL;
959 FindFreeChildSlot(
void)
961 FOREACH_CHILD(child) {
964 child->hProcess = NULL;
978 #define InternalCmdsMax 8
979 static const char szInternalCmds[][InternalCmdsMax+2] = {
1033 internal_match(
const void *key,
const void *elem)
1035 return strncmp(key, ((
const char *)elem) + 1, InternalCmdsMax);
1040 is_command_com(
const char *interp)
1042 int i = strlen(interp) - 11;
1044 if ((i == 0 || (i > 0 && isdirsep(interp[i-1]))) &&
1045 strcasecmp(interp+i,
"command.com") == 0) {
1051 static int internal_cmd_match(
const char *cmdname,
int nt);
1055 is_internal_cmd(
const char *cmd,
int nt)
1057 char cmdname[9], *b = cmdname, c;
1060 if (!(c = *cmd++))
return 0;
1061 }
while (isspace(c));
1064 while (isalpha(c)) {
1066 if (b == cmdname +
sizeof(cmdname))
return 0;
1069 if (c ==
'.') c = *cmd;
1071 case '<':
case '>':
case '|':
1073 case '\0':
case ' ':
case '\t':
case '\n':
1079 return internal_cmd_match(cmdname, nt);
1084 internal_cmd_match(
const char *cmdname,
int nt)
1088 nm = bsearch(cmdname, szInternalCmds,
1089 sizeof(szInternalCmds) /
sizeof(*szInternalCmds),
1090 sizeof(*szInternalCmds),
1092 if (!nm || !(nm[0] & (nt ? 2 : 1)))
1099 rb_w32_get_osfhandle(
int fh)
1101 return _get_osfhandle(fh);
1106 join_argv(
char *cmd,
char *
const *argv, BOOL escape, UINT cp,
int backslash)
1110 int len, n, bs, quote;
1112 for (t = argv, q = cmd,
len = 0; (p = *t) != 0; t++) {
1115 if (!*p || strpbrk(p,
" \t\"'")) {
1120 for (bs = 0; *p; ++p) {
1134 memset(q,
'\\', bs);
1139 case '<':
case '>':
case '|':
case '^':
1140 if (escape && !quote) {
1141 len += (n = p - s) + 1;
1152 p = CharNextExA(cp, p, 0) - 1;
1156 len += (n = p - s) + 1;
1160 if (backslash > 0) {
1163 translate_char(q,
'/',
'\\', cp);
1166 if (quote) *q++ =
'"';
1179 #define STRNDUPV(ptr, v, src, len) \
1180 (((char *)memcpy(((ptr) = ALLOCV((v), (len) + 1)), (src), (len)))[len] = 0)
1184 check_spawn_mode(
int mode)
1206 if (mode == P_OVERLAY) {
1207 WaitForSingleObject(child->hProcess, INFINITE);
1208 GetExitCodeProcess(child->hProcess, &exitcode);
1209 CloseChildHandle(child);
1217 CreateChild(
struct ChildRecord *child,
const WCHAR *cmd,
const WCHAR *prog, HANDLE hInput, HANDLE hOutput, HANDLE hError, DWORD dwCreationFlags)
1220 STARTUPINFOW aStartupInfo;
1221 PROCESS_INFORMATION aProcessInformation;
1222 SECURITY_ATTRIBUTES sa;
1224 if (!cmd && !prog) {
1234 sa.nLength =
sizeof(SECURITY_ATTRIBUTES);
1235 sa.lpSecurityDescriptor = NULL;
1236 sa.bInheritHandle = TRUE;
1238 memset(&aStartupInfo, 0,
sizeof(aStartupInfo));
1239 memset(&aProcessInformation, 0,
sizeof(aProcessInformation));
1240 aStartupInfo.cb =
sizeof(aStartupInfo);
1241 aStartupInfo.dwFlags = STARTF_USESTDHANDLES;
1243 aStartupInfo.hStdInput = hInput;
1246 aStartupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
1249 aStartupInfo.hStdOutput = hOutput;
1252 aStartupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
1255 aStartupInfo.hStdError = hError;
1258 aStartupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
1261 dwCreationFlags |= NORMAL_PRIORITY_CLASS;
1263 if (lstrlenW(cmd) > 32767) {
1270 fRet = CreateProcessW(prog, (WCHAR *)cmd, &sa, &sa,
1271 sa.bInheritHandle, dwCreationFlags, NULL, NULL,
1272 &aStartupInfo, &aProcessInformation);
1273 errno = map_errno(GetLastError());
1281 CloseHandle(aProcessInformation.hThread);
1283 child->hProcess = aProcessInformation.hProcess;
1284 child->pid = (rb_pid_t)aProcessInformation.dwProcessId;
1291 is_batch(
const char *cmd)
1293 int len = strlen(cmd);
1294 if (
len <= 4)
return 0;
1296 if (*cmd++ !=
'.')
return 0;
1297 if (strcasecmp(cmd,
"bat") == 0)
return 1;
1298 if (strcasecmp(cmd,
"cmd") == 0)
return 1;
1302 #define filecp rb_w32_filecp
1303 #define mbstr_to_wstr rb_w32_mbstr_to_wstr
1304 #define wstr_to_mbstr rb_w32_wstr_to_mbstr
1305 #define acp_to_wstr(str, plen) mbstr_to_wstr(CP_ACP, str, -1, plen)
1306 #define wstr_to_acp(str, plen) wstr_to_mbstr(CP_ACP, str, -1, plen)
1307 #define filecp_to_wstr(str, plen) mbstr_to_wstr(filecp(), str, -1, plen)
1308 #define wstr_to_filecp(str, plen) wstr_to_mbstr(filecp(), str, -1, plen)
1309 #define utf8_to_wstr(str, plen) mbstr_to_wstr(CP_UTF8, str, -1, plen)
1310 #define wstr_to_utf8(str, plen) wstr_to_mbstr(CP_UTF8, str, -1, plen)
1314 rb_w32_start_process(
const char *abspath,
char *
const *argv,
int out_fd)
1323 WCHAR *wcmd = NULL, *wprog = NULL;
1324 HANDLE outHandle = NULL;
1327 outHandle = (HANDLE)rb_w32_get_osfhandle(out_fd);
1330 len = join_argv(NULL, argv, FALSE, filecp(), 1);
1331 cmd = alloca(
sizeof(
char) *
len);
1332 join_argv(cmd, argv, FALSE, filecp(), 1);
1334 if (!(wcmd = mbstr_to_wstr(filecp(), cmd, -1, NULL))) {
1338 if (!(wprog = mbstr_to_wstr(filecp(), abspath, -1, NULL))) {
1343 if (!CreateChild(&child, wcmd, wprog, NULL, outHandle, outHandle, 0)) {
1349 return child.hProcess;
1354 w32_spawn(
int mode,
const char *cmd,
const char *prog, UINT cp)
1356 char fbuf[PATH_MAX];
1358 const char *shell = NULL;
1359 WCHAR *wcmd = NULL, *wshell = NULL;
1365 char *cmd_sep = NULL;
1367 if (check_spawn_mode(mode))
return -1;
1370 if (!(p = dln_find_exe_r(prog, NULL, fbuf,
sizeof(fbuf)))) {
1375 translate_char(p,
'/',
'\\', cp);
1382 if ((shell = w32_getenv(
"RUBYSHELL", cp)) && (redir = has_redirection(cmd, cp))) {
1383 size_t shell_len = strlen(shell);
1384 size_t cmd_len = strlen(cmd) +
sizeof(
" -c ") + 2;
1385 char *tmp =
ALLOCV(v, shell_len + cmd_len);
1386 memcpy(tmp, shell, shell_len + 1);
1387 translate_char(tmp,
'/',
'\\', cp);
1388 snprintf(tmp + shell_len, cmd_len,
" -c \"%s\"", cmd);
1391 else if ((shell = w32_getenv(
"COMSPEC", cp)) &&
1392 (nt = !is_command_com(shell),
1393 (redir < 0 ? has_redirection(cmd, cp) : redir) ||
1394 is_internal_cmd(cmd, nt))) {
1395 size_t cmd_len = strlen(shell) + strlen(cmd) +
sizeof(
" /c ") + (nt ? 2 : 0);
1396 char *tmp =
ALLOCV(v, cmd_len);
1397 snprintf(tmp, cmd_len, nt ?
"%s /c \"%s\"" :
"%s /c %s", shell, cmd);
1401 int len = 0, quote = (*cmd ==
'"') ?
'"' : (*cmd ==
'\'') ?
'\'' : 0;
1403 for (prog = cmd + !!quote;; prog = CharNextExA(cp, prog, 0)) {
1404 if (*prog ==
'/') slash = 1;
1408 STRNDUPV(p, v2, cmd,
len);
1414 if ((
unsigned char)*prog == quote) {
1415 len = prog++ - cmd - 1;
1416 STRNDUPV(p, v2, cmd + 1,
len);
1420 if (quote)
continue;
1421 if (
ISSPACE(*prog) || strchr(
"<>|*?\"", *prog)) {
1423 STRNDUPV(p, v2, cmd,
len + (slash ? strlen(prog) : 0));
1426 sep = *(cmd_sep = &p[
len]);
1433 shell = dln_find_exe_r(shell, NULL, fbuf,
sizeof(fbuf));
1434 if (p && slash) translate_char(p,
'/',
'\\', cp);
1436 shell = p ? p : cmd;
1439 len = strlen(shell);
1440 if (strchr(shell,
' ')) quote = -1;
1441 if (shell == fbuf) {
1444 else if (shell != p && strchr(shell,
'/')) {
1445 STRNDUPV(p, v2, shell,
len);
1448 if (p) translate_char(p,
'/',
'\\', cp);
1449 if (is_batch(shell)) {
1450 int alen = strlen(prog);
1451 cmd = p =
ALLOCV(v,
len + alen + (quote ? 2 : 0) + 1);
1452 if (quote) *p++ =
'"';
1453 memcpy(p, shell,
len);
1455 if (quote) *p++ =
'"';
1456 memcpy(p, prog, alen + 1);
1463 if (!e && shell && !(wshell = mbstr_to_wstr(cp, shell, -1, NULL))) e = E2BIG;
1464 if (cmd_sep) *cmd_sep = sep;
1465 if (!e && cmd && !(wcmd = mbstr_to_wstr(cp, cmd, -1, NULL))) e = E2BIG;
1471 if (CreateChild(child, wcmd, wshell, NULL, NULL, NULL, 0)) {
1472 ret = child_result(child, mode);
1483 rb_w32_spawn(
int mode,
const char *cmd,
const char *prog)
1486 return w32_spawn(mode, cmd, prog, filecp());
1491 rb_w32_uspawn(
int mode,
const char *cmd,
const char *prog)
1493 return w32_spawn(mode, cmd, prog, CP_UTF8);
1498 w32_spawn_process(
int mode,
const char *prog,
char *
const *argv,
1499 int in_fd,
int out_fd,
int err_fd, DWORD flags, UINT cp)
1503 BOOL ntcmd = FALSE, tmpnt;
1505 char *cmd, fbuf[PATH_MAX];
1506 WCHAR *wcmd = NULL, *wprog = NULL;
1510 HANDLE in_handle = NULL, out_handle = NULL, err_handle = NULL;
1512 if (check_spawn_mode(mode))
return -1;
1515 in_handle = (HANDLE)rb_w32_get_osfhandle(in_fd);
1518 out_handle = (HANDLE)rb_w32_get_osfhandle(out_fd);
1521 err_handle = (HANDLE)rb_w32_get_osfhandle(err_fd);
1524 if (!prog) prog = argv[0];
1525 if ((shell = w32_getenv(
"COMSPEC", cp)) &&
1526 internal_cmd_match(prog, tmpnt = !is_command_com(shell))) {
1531 else if ((cmd = dln_find_exe_r(prog, NULL, fbuf,
sizeof(fbuf)))) {
1532 if (cmd == prog) strlcpy(cmd = fbuf, prog,
sizeof(fbuf));
1533 translate_char(cmd,
'/',
'\\', cp);
1536 else if (strchr(prog,
'/')) {
1538 if (
len <
sizeof(fbuf))
1539 strlcpy(cmd = fbuf, prog,
sizeof(fbuf));
1541 STRNDUPV(cmd, v, prog,
len);
1542 translate_char(cmd,
'/',
'\\', cp);
1545 if (c_switch || is_batch(prog)) {
1547 progs[0] = (
char *)prog;
1549 len = join_argv(NULL, progs, ntcmd, cp, 1);
1550 if (c_switch)
len += 3;
1552 if (argv[0])
len += join_argv(NULL, argv, ntcmd, cp, 0);
1554 join_argv(cmd, progs, ntcmd, cp, 1);
1555 if (c_switch) strlcat(cmd,
" /c",
len);
1556 if (argv[0]) join_argv(cmd + strlcat(cmd,
" ",
len), argv, ntcmd, cp, 0);
1557 prog = c_switch ? shell : 0;
1560 len = join_argv(NULL, argv, FALSE, cp, 1);
1562 join_argv(cmd, argv, FALSE, cp, 1);
1565 if (!e && cmd && !(wcmd = mbstr_to_wstr(cp, cmd, -1, NULL))) e = E2BIG;
1567 if (!e && prog && !(wprog = mbstr_to_wstr(cp, prog, -1, NULL))) e = E2BIG;
1571 if (CreateChild(child, wcmd, wprog, in_handle, out_handle, err_handle, flags)) {
1572 ret = child_result(child, mode);
1583 rb_w32_aspawn_flags(
int mode,
const char *prog,
char *
const *argv, DWORD flags)
1586 return w32_spawn_process(mode, prog, argv, -1, -1, -1, flags, filecp());
1591 rb_w32_uaspawn_flags(
int mode,
const char *prog,
char *
const *argv, DWORD flags)
1593 return w32_spawn_process(mode, prog, argv, -1, -1, -1, flags, CP_UTF8);
1598 rb_w32_aspawn(
int mode,
const char *prog,
char *
const *argv)
1600 return w32_spawn_process(mode, prog, argv, -1, -1, -1, 0, filecp());
1605 rb_w32_uaspawn(
int mode,
const char *prog,
char *
const *argv)
1607 return rb_w32_uaspawn_flags(mode, prog, argv, 0);
1612 rb_w32_uspawn_process(
int mode,
const char *prog,
char *
const *argv,
1613 int in_fd,
int out_fd,
int err_fd, DWORD flags)
1615 return w32_spawn_process(mode, prog, argv, in_fd, out_fd, err_fd,
1632 #define NTMALLOC 0x2
1633 #define NTSTRING 0x4
1637 insert(
const char *path,
VALUE vinfo,
void *enc)
1643 if (!tmpcurr)
return -1;
1645 tmpcurr->len = strlen(path);
1646 tmpcurr->str =
strdup(path);
1647 if (!tmpcurr->str)
return -1;
1648 tmpcurr->flags |= NTMALLOC;
1650 *tail = &tmpcurr->next;
1659 char buffer[PATH_MAX], *buf = buffer;
1663 if (patt->len >= PATH_MAX)
1664 if (!(buf = malloc(patt->len + 1)))
return 0;
1666 memcpy(buf, patt->str, patt->len);
1667 buf[patt->len] =
'\0';
1668 translate_char(buf,
'\\',
'/', cp);
1669 status = ruby_brace_glob_with_enc(buf, 0, insert, (
VALUE)&tail, enc);
1673 if (status || last == tail)
return 0;
1674 if (patt->flags & NTMALLOC)
1687 has_redirection(
const char *cmd, UINT cp)
1703 else if (quote == *
ptr)
1721 if (*
ptr++ ==
'%')
return TRUE;
1727 ptr = CharNextExA(cp,
ptr, 0);
1735 static inline WCHAR *
1736 skipspace(WCHAR *
ptr)
1745 w32_cmdvector(
const WCHAR *cmd,
char ***vec, UINT cp,
rb_encoding *enc)
1748 int elements, strsz, done;
1749 int slashes, escape;
1750 WCHAR *
ptr, *base, *cmdline;
1751 char *cptr, *buffer;
1767 ptr = cmdline = wcsdup(cmd);
1778 while (*(
ptr = skipspace(
ptr))) {
1780 quote = slashes = globbing = escape = 0;
1781 for (done = 0; !done && *
ptr; ) {
1790 if (quote != L
'\'') slashes++;
1830 if (!(slashes & 1)) {
1833 else if (quote == *
ptr) {
1834 if (quote == L
'"' && quote ==
ptr[1])
1867 slashes = quote = 0;
1868 while (p < base +
len) {
1872 if (quote != L
'\'') slashes++;
1877 if (!(slashes & 1) && quote && quote != c) {
1882 memcpy(p - ((slashes + 1) >> 1), p + (~slashes & 1),
1883 sizeof(WCHAR) * (base +
len - p));
1884 len -= ((slashes + 1) >> 1) + (~slashes & 1);
1885 p -= (slashes + 1) >> 1;
1886 if (!(slashes & 1)) {
1888 if (quote == L
'"' && quote == *p)
1909 if (!curr)
goto do_nothing;
1910 curr->str = rb_w32_wstr_to_mbstr(cp, base,
len, &curr->len);
1911 curr->flags |= NTMALLOC;
1913 if (globbing && (tail = cmdglob(curr, cmdtail, cp, enc))) {
1918 cmdtail = &curr->next;
1928 for (elements = 0, strsz = 0, curr = cmdhead; curr; curr = curr->next) {
1930 strsz += (curr->len + 1);
1933 len = (elements+1)*
sizeof(
char *) + strsz;
1934 buffer = (
char *)malloc(
len);
1937 while ((curr = cmdhead) != 0) {
1938 cmdhead = curr->next;
1939 if (curr->flags & NTMALLOC) free(curr->str);
1943 for (vptr = *vec; *vptr; ++vptr);
1959 vptr = (
char **) buffer;
1961 cptr = buffer + (elements+1) *
sizeof(
char *);
1963 while ((curr = cmdhead) != 0) {
1964 memcpy(cptr, curr->str, curr->len);
1965 cptr[curr->len] =
'\0';
1967 cptr += curr->len + 1;
1968 cmdhead = curr->next;
1969 if (curr->flags & NTMALLOC) free(curr->str);
1974 *vec = (
char **) buffer;
1986 open_special(
const WCHAR *path, DWORD access, DWORD flags)
1988 const DWORD share_mode =
1989 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
1990 return CreateFileW(path, access, share_mode, NULL, OPEN_EXISTING,
1991 FILE_FLAG_BACKUP_SEMANTICS|flags, NULL);
2001 #define GetBit(bits, i) ((bits)[(i) / CHAR_BIT] & (1 << (i) % CHAR_BIT))
2002 #define SetBit(bits, i) ((bits)[(i) / CHAR_BIT] |= (1 << (i) % CHAR_BIT))
2004 #define BitOfIsDir(n) ((n) * 2)
2005 #define BitOfIsRep(n) ((n) * 2 + 1)
2006 #define DIRENT_PER_CHAR (CHAR_BIT / 2)
2008 static const WCHAR namespace_prefix[] = {L
'\\', L
'\\', L
'?', L
'\\'};
2010 enum {FINAL_PATH_MAX = PATH_MAX + numberof(namespace_prefix)};
2014 open_dir_handle(
const WCHAR *filename, WIN32_FIND_DATAW *fd)
2025 fh = open_special(filename, 0, 0);
2026 if (fh != INVALID_HANDLE_VALUE) {
2027 len = GetFinalPathNameByHandleW(fh, fullname, FINAL_PATH_MAX, 0);
2029 if (
len >= FINAL_PATH_MAX) {
2030 errno = ENAMETOOLONG;
2031 return INVALID_HANDLE_VALUE;
2035 len = lstrlenW(filename);
2036 if (
len >= PATH_MAX) {
2037 errno = ENAMETOOLONG;
2038 return INVALID_HANDLE_VALUE;
2042 p = &fullname[
len-1];
2043 if (!(isdirsep(*p) || *p == L
':')) *++p = L
'\\';
2050 fh = FindFirstFileW(fullname, fd);
2051 if (fh == INVALID_HANDLE_VALUE) {
2052 errno = map_errno(GetLastError());
2059 w32_wopendir(
const WCHAR *wpath)
2062 WIN32_FIND_DATAW fd;
2075 if (wstati128(wpath, &sbuf, FALSE) < 0) {
2078 if (!(sbuf.st_mode & S_IFDIR) &&
2079 (!
ISALPHA(wpath[0]) || wpath[1] != L
':' || wpath[2] != L
'\0' ||
2080 ((1 << ((wpath[0] & 0x5f) -
'A')) & GetLogicalDrives()) == 0)) {
2084 fh = open_dir_handle(wpath, &fd);
2085 if (fh == INVALID_HANDLE_VALUE) {
2092 p = calloc(1,
sizeof(
DIR));
2096 pathlen = lstrlenW(wpath);
2106 len = lstrlenW(fd.cFileName) + 1;
2107 altlen = lstrlenW(fd.cAlternateFileName) + 1;
2113 tmpW = realloc(p->start, (idx +
len + altlen) *
sizeof(WCHAR));
2123 memcpy(&p->start[idx], fd.cFileName,
len *
sizeof(WCHAR));
2124 memcpy(&p->start[idx +
len], fd.cAlternateFileName, altlen *
sizeof(WCHAR));
2126 if (p->nfiles % DIRENT_PER_CHAR == 0) {
2127 tmp = realloc(p->bits, p->nfiles / DIRENT_PER_CHAR + 1);
2131 p->bits[p->nfiles / DIRENT_PER_CHAR] = 0;
2133 if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
2134 SetBit(p->bits, BitOfIsDir(p->nfiles));
2135 if (fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
2136 WCHAR *tmppath = malloc((pathlen +
len + 1) *
sizeof(WCHAR));
2137 memcpy(tmppath, wpath, pathlen *
sizeof(WCHAR));
2138 tmppath[pathlen] = L
'\\';
2139 memcpy(tmppath + pathlen + 1, fd.cFileName,
len *
sizeof(WCHAR));
2140 if (rb_w32_reparse_symlink_p(tmppath))
2141 SetBit(p->bits, BitOfIsRep(p->nfiles));
2146 idx +=
len + altlen;
2147 }
while (FindNextFileW(fh, &fd));
2158 UINT cp = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
2164 rb_w32_wstr_to_mbstr(UINT cp,
const WCHAR *wstr,
int clen,
long *plen)
2167 int len = WideCharToMultiByte(cp, 0, wstr, clen, NULL, 0, NULL, NULL);
2168 if (!(
ptr = malloc(
len)))
return 0;
2169 WideCharToMultiByte(cp, 0, wstr, clen,
ptr,
len, NULL, NULL);
2172 if (clen == -1) --
len;
2180 rb_w32_mbstr_to_wstr(UINT cp,
const char *str,
int clen,
long *plen)
2184 int len = MultiByteToWideChar(cp, 0, str, clen, NULL, 0);
2185 if (!(
ptr = malloc(
sizeof(WCHAR) *
len)))
return 0;
2186 MultiByteToWideChar(cp, 0, str, clen,
ptr,
len);
2189 if (clen == -1) --
len;
2197 rb_w32_opendir(
const char *filename)
2200 WCHAR *wpath = filecp_to_wstr(filename, NULL);
2203 ret = w32_wopendir(wpath);
2210 rb_w32_uopendir(
const char *filename)
2213 WCHAR *wpath = utf8_to_wstr(filename, NULL);
2216 ret = w32_wopendir(wpath);
2227 move_to_next_entry(
DIR *dirp)
2231 dirp->curr += lstrlenW(dirp->curr) + 1;
2232 dirp->curr += lstrlenW(dirp->curr) + 1;
2233 if (dirp->curr >= (dirp->start + dirp->size)) {
2245 win32_direct_conv(
const WCHAR *file,
const WCHAR *alt,
struct direct *entry,
const void *enc)
2247 UINT cp = *((UINT *)enc);
2248 if (!(entry->d_name = wstr_to_mbstr(cp, file, -1, &entry->d_namlen)))
2252 entry->d_altname = wstr_to_mbstr(cp, alt, -1, &altlen);
2253 entry->d_altlen = altlen;
2260 rb_w32_conv_from_wchar(
const WCHAR *wstr,
rb_encoding *enc)
2263 long len = lstrlenW(wstr);
2266 if (encindex == ENCINDEX_UTF_16LE) {
2270 #if SIZEOF_INT < SIZEOF_LONG
2271 # error long should equal to int on Windows
2274 len = WideCharToMultiByte(CP_UTF8, 0, wstr, clen, NULL, 0, NULL, NULL);
2276 WideCharToMultiByte(CP_UTF8, 0, wstr, clen,
RSTRING_PTR(src),
len, NULL, NULL);
2279 case ENCINDEX_ASCII_8BIT:
2280 case ENCINDEX_US_ASCII:
2282 case ENCINDEX_UTF_8:
2291 rb_w32_conv_from_wstr(
const WCHAR *wstr,
long *lenp,
rb_encoding *enc)
2293 VALUE str = rb_w32_conv_from_wchar(wstr, enc);
2297 if (
NIL_P(str))
return wstr_to_utf8(wstr, lenp);
2306 ruby_direct_conv(
const WCHAR *file,
const WCHAR *alt,
struct direct *entry,
const void *enc)
2308 if (!(entry->d_name = rb_w32_conv_from_wstr(file, &entry->d_namlen, enc)))
2312 entry->d_altname = rb_w32_conv_from_wstr(alt, &altlen, enc);
2313 entry->d_altlen = altlen;
2320 readdir_internal(
DIR *dirp, BOOL (*conv)(
const WCHAR *,
const WCHAR *,
struct direct *,
const void *),
const void *enc)
2322 static long dummy_ino = 0;
2329 free(dirp->dirstr.d_name);
2330 free(dirp->dirstr.d_altname);
2331 dirp->dirstr.d_altname = 0;
2332 dirp->dirstr.d_altlen = 0;
2333 conv(dirp->curr, dirp->curr + lstrlenW(dirp->curr) + 1, &dirp->dirstr, enc);
2338 dirp->dirstr.d_ino = (ino_t)(InterlockedIncrement(&dummy_ino) - 1);
2344 if (GetBit(dirp->bits, BitOfIsRep(dirp->loc)))
2345 dirp->dirstr.d_type = DT_LNK;
2346 else if (GetBit(dirp->bits, BitOfIsDir(dirp->loc)))
2347 dirp->dirstr.d_type = DT_DIR;
2349 dirp->dirstr.d_type = DT_REG;
2355 move_to_next_entry(dirp);
2357 return &(dirp->dirstr);
2369 if (idx == ENCINDEX_ASCII_8BIT) {
2370 const UINT cp = filecp();
2371 return readdir_internal(dirp, win32_direct_conv, &cp);
2373 else if (idx == ENCINDEX_UTF_8) {
2374 const UINT cp = CP_UTF8;
2375 return readdir_internal(dirp, win32_direct_conv, &cp);
2378 return readdir_internal(dirp, ruby_direct_conv, enc);
2383 rb_w32_ureaddir(
DIR *dirp)
2385 const UINT cp = CP_UTF8;
2386 return readdir_internal(dirp, win32_direct_conv, &cp);
2395 rb_w32_telldir(
DIR *dirp)
2406 rb_w32_seekdir(
DIR *dirp,
long loc)
2408 if (dirp->loc > loc) rb_w32_rewinddir(dirp);
2410 while (dirp->curr && dirp->loc < loc) {
2411 move_to_next_entry(dirp);
2421 rb_w32_rewinddir(
DIR *dirp)
2423 dirp->curr = dirp->start;
2433 rb_w32_closedir(
DIR *dirp)
2436 free(dirp->dirstr.d_name);
2437 free(dirp->dirstr.d_altname);
2445 #if RUBY_MSVCRT_VERSION >= 140
2460 CRITICAL_SECTION _lock;
2462 #define FILE_COUNT(stream) ((vcruntime_file*)stream)->_cnt
2463 #define FILE_READPTR(stream) ((vcruntime_file*)stream)->_ptr
2464 #define FILE_FILENO(stream) ((vcruntime_file*)stream)->_file
2466 #define FILE_COUNT(stream) stream->_cnt
2467 #define FILE_READPTR(stream) stream->_ptr
2468 #define FILE_FILENO(stream) stream->_file
2472 #if RUBY_MSVCRT_VERSION >= 140
2473 typedef char lowio_text_mode;
2474 typedef char lowio_pipe_lookahead[3];
2477 CRITICAL_SECTION lock;
2480 unsigned char osfile;
2481 lowio_text_mode textmode;
2482 lowio_pipe_lookahead _pipe_lookahead;
2484 uint8_t unicode : 1;
2485 uint8_t utf8translations : 1;
2486 uint8_t dbcsBufferUsed : 1;
2495 CRITICAL_SECTION lock;
2496 #if RUBY_MSVCRT_VERSION >= 80
2503 #if !defined _CRTIMP || defined __MINGW32__
2505 #define _CRTIMP __declspec(dllimport)
2508 #if RUBY_MSVCRT_VERSION >= 140
2509 static ioinfo ** __pioinfo = NULL;
2510 #define IOINFO_L2E 6
2512 EXTERN_C _CRTIMP
ioinfo * __pioinfo[];
2513 #define IOINFO_L2E 5
2515 static inline ioinfo* _pioinfo(
int);
2518 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
2519 #define _osfhnd(i) (_pioinfo(i)->osfhnd)
2520 #define _osfile(i) (_pioinfo(i)->osfile)
2521 #define rb_acrt_lowio_lock_fh(i) EnterCriticalSection(&_pioinfo(i)->lock)
2522 #define rb_acrt_lowio_unlock_fh(i) LeaveCriticalSection(&_pioinfo(i)->lock)
2524 #if RUBY_MSVCRT_VERSION >= 80
2525 static size_t pioinfo_extra = 0;
2529 set_pioinfo_extra(
void)
2531 #if RUBY_MSVCRT_VERSION >= 140
2532 # define FUNCTION_RET 0xc3
2534 # define UCRTBASE "ucrtbased.dll"
2536 # define UCRTBASE "ucrtbase.dll"
2551 char *p = (
char*)get_proc_address(UCRTBASE,
"_isatty", NULL);
2554 #if defined(_M_ARM64) || defined(__aarch64__)
2555 #define IS_INSN(pc, name) ((*(pc) & name##_mask) == name##_id)
2556 const int max_num_inst = 500;
2557 uint32_t *start = (uint32_t*)p;
2558 uint32_t *end_limit = (start + max_num_inst);
2559 uint32_t *pc = start;
2562 fprintf(stderr,
"_isatty proc not found in " UCRTBASE
"\n");
2567 const uint32_t ret_id = 0xd65f0000;
2568 const uint32_t ret_mask = 0xfffffc1f;
2569 for(; pc < end_limit; pc++) {
2570 if (IS_INSN(pc, ret)) {
2574 if (pc == end_limit) {
2575 fprintf(stderr,
"end of _isatty not found in " UCRTBASE
"\n");
2580 const uint32_t adrp_id = 0x90000000;
2581 const uint32_t adrp_mask = 0x9f000000;
2582 const uint32_t add_id = 0x11000000;
2583 const uint32_t add_mask = 0x7fc00000;
2584 for(; pc > start; pc--) {
2585 if (IS_INSN(pc, adrp) && IS_INSN(pc + 1, add)) {
2590 fprintf(stderr,
"pioinfo mark not found in " UCRTBASE
"\n");
2600 const uint32_t adrp_insn = *pc;
2601 const uint32_t adrp_immhi = (adrp_insn & 0x00ffffe0) >> 5;
2602 const uint32_t adrp_immlo = (adrp_insn & 0x60000000) >> (5 + 19 + 5);
2603 const int64_t adrp_sign = (adrp_insn & 0x00800000) ? ~0x001fffff : 0;
2605 const int64_t adrp_imm = (adrp_sign | (adrp_immhi << 2) | adrp_immlo) << 12;
2607 const uint64_t adrp_base = (uint64_t)pc & 0xfffffffffffff000;
2609 const uint32_t add_insn = *(pc + 1);
2610 const uint64_t add_imm = (add_insn & 0x3ffc00) >> (5 + 5);
2612 __pioinfo = (
ioinfo**)(adrp_base + adrp_imm + add_imm);
2620 # define FUNCTION_BEFORE_RET_MARK "\x48\x83\xc4"
2621 # define FUNCTION_SKIP_BYTES 1
2624 # define PIOINFO_MARK "\x48\x8d\x0d"
2627 # define PIOINFO_MARK "\x48\x8d\x15"
2632 # define FUNCTION_BEFORE_RET_MARK "\x5d"
2634 # define FUNCTION_BEFORE_RET_MARK_2 "\xc9"
2635 # define FUNCTION_SKIP_BYTES 0
2637 # define PIOINFO_MARK "\x8B\x04\x85"
2640 for (pend += 10; pend < p + 500; pend++) {
2642 if ((memcmp(pend, FUNCTION_BEFORE_RET_MARK,
sizeof(FUNCTION_BEFORE_RET_MARK) - 1) == 0
2643 # ifdef FUNCTION_BEFORE_RET_MARK_2
2644 || memcmp(pend, FUNCTION_BEFORE_RET_MARK_2,
sizeof(FUNCTION_BEFORE_RET_MARK_2) - 1) == 0
2647 *(pend + (
sizeof(FUNCTION_BEFORE_RET_MARK) - 1) + FUNCTION_SKIP_BYTES) == (
char)FUNCTION_RET) {
2649 for (pend -= (
sizeof(PIOINFO_MARK) - 1); pend > p; pend--) {
2650 if (memcmp(pend, PIOINFO_MARK,
sizeof(PIOINFO_MARK) - 1) == 0) {
2659 fprintf(stderr,
"unexpected " UCRTBASE
"\n");
2663 p +=
sizeof(PIOINFO_MARK) - 1;
2665 rel = *(int32_t*)(p);
2666 rip = p +
sizeof(int32_t);
2667 __pioinfo = (
ioinfo**)(rip + rel);
2669 __pioinfo = *(
ioinfo***)(p);
2675 fd = _open(
"NUL", O_RDONLY);
2676 for (pioinfo_extra = 0; pioinfo_extra <= 64; pioinfo_extra +=
sizeof(
void *)) {
2677 if (_osfhnd(fd) == _get_osfhandle(fd)) {
2683 if (pioinfo_extra > 64) {
2689 #define pioinfo_extra 0
2695 const size_t sizeof_ioinfo =
sizeof(
ioinfo) + pioinfo_extra;
2696 return (
ioinfo*)((
char*)__pioinfo[fd >> IOINFO_L2E] +
2697 (fd & (IOINFO_ARRAY_ELTS - 1)) * sizeof_ioinfo);
2700 #define _set_osfhnd(fh, osfh) (void)(_osfhnd(fh) = osfh)
2701 #define _set_osflags(fh, flags) (_osfile(fh) = (flags))
2704 #define FEOFLAG 0x02
2706 #define FNOINHERIT 0x10
2707 #define FAPPEND 0x20
2711 static int is_socket(SOCKET);
2712 static int is_console(SOCKET);
2716 rb_w32_io_cancelable_p(
int fd)
2718 return is_socket(TO_SOCKET(fd)) || !is_console(TO_SOCKET(fd));
2723 rb_w32_open_osfhandle(intptr_t osfhandle,
int flags)
2732 if (flags & O_APPEND)
2733 fileflags |= FAPPEND;
2738 if (flags & O_NOINHERIT)
2739 fileflags |= FNOINHERIT;
2742 hF = CreateFile(
"NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
2743 fh = _open_osfhandle((intptr_t)hF, 0);
2751 rb_acrt_lowio_lock_fh(fh);
2753 _set_osfhnd(fh, osfhandle);
2757 _set_osflags(fh, fileflags);
2758 rb_acrt_lowio_unlock_fh(fh);
2765 init_stdhandle(
void)
2769 #define open_null(fd) \
2771 (nullfd = open("NUL", O_RDWR)) : 0), \
2772 ((nullfd == (fd)) ? (keep = 1) : dup2(nullfd, fd)), \
2775 if (fileno(stdin) < 0) {
2776 FILE_FILENO(stdin) = open_null(0);
2779 setmode(fileno(stdin), O_BINARY);
2781 if (fileno(stdout) < 0) {
2782 FILE_FILENO(stdout) = open_null(1);
2784 if (fileno(stderr) < 0) {
2785 FILE_FILENO(stderr) = open_null(2);
2787 if (nullfd >= 0 && !keep) close(nullfd);
2788 setvbuf(stderr, NULL, _IONBF, 0);
2791 HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
2793 if (GetConsoleMode(h, &m)) {
2794 #ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
2795 #define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x4
2797 SetConsoleMode(h, m | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
2806 is_socket(SOCKET sock)
2808 if (socklist_lookup(sock, NULL))
2816 rb_w32_is_socket(
int fd)
2818 return is_socket(TO_SOCKET(fd));
2831 rb_w32_strerror(
int e)
2833 static char buffer[512];
2837 if (e < 0 || e > sys_nerr) {
2840 #if WSAEWOULDBLOCK != EWOULDBLOCK
2841 else if (e >= EADDRINUSE && e <= EWOULDBLOCK) {
2845 for (s = 0; s < (int)(
sizeof(errmap)/
sizeof(*errmap)); s++)
2846 if (errmap[s].winerr == WSAEWOULDBLOCK)
2848 for (i = s; i < (int)(
sizeof(errmap)/
sizeof(*errmap)); i++)
2849 if (errmap[i].err == e) {
2850 e = errmap[i].winerr;
2855 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
2856 FORMAT_MESSAGE_IGNORE_INSERTS, &source, e,
2857 MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
2858 buffer,
sizeof(buffer), NULL) == 0 &&
2859 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
2860 FORMAT_MESSAGE_IGNORE_INSERTS, &source, e, 0,
2861 buffer,
sizeof(buffer), NULL) == 0)
2862 strlcpy(buffer,
"Unknown Error",
sizeof(buffer));
2865 strlcpy(buffer, strerror(e),
sizeof(buffer));
2868 while ((p = strpbrk(p,
"\r\n")) != NULL) {
2869 memmove(p, p + 1, strlen(p));
2918 setuid(rb_uid_t uid)
2920 return (uid == ROOT_UID ? 0 : -1);
2925 setgid(rb_gid_t gid)
2927 return (gid == ROOT_GID ? 0 : -1);
2936 ioctl(
int i,
int u, ...)
2943 rb_w32_fdset(
int fd, fd_set *set)
2952 rb_w32_fdclr(
int fd, fd_set *set)
2955 SOCKET s = TO_SOCKET(fd);
2957 for (i = 0; i < set->fd_count; i++) {
2958 if (set->fd_array[i] == s) {
2959 memmove(&set->fd_array[i], &set->fd_array[i+1],
2960 sizeof(set->fd_array[0]) * (--set->fd_count - i));
2970 rb_w32_fdisset(
int fd, fd_set *set)
2973 SOCKET s = TO_SOCKET(fd);
2974 if (s == (SOCKET)INVALID_HANDLE_VALUE)
2976 RUBY_CRITICAL {ret = __WSAFDIsSet(s, set);}
2984 max = min(src->fd_count, (UINT)max);
2985 if ((UINT)dst->
capa < (UINT)max) {
2986 dst->
capa = (src->fd_count / FD_SETSIZE + 1) * FD_SETSIZE;
2990 memcpy(dst->
fdset->fd_array, src->fd_array,
2991 max *
sizeof(src->fd_array[0]));
2992 dst->
fdset->fd_count = src->fd_count;
2999 if ((UINT)dst->
capa < src->
fdset->fd_count) {
3000 dst->
capa = (src->
fdset->fd_count / FD_SETSIZE + 1) * FD_SETSIZE;
3004 memcpy(dst->
fdset->fd_array, src->
fdset->fd_array,
3005 src->
fdset->fd_count *
sizeof(src->
fdset->fd_array[0]));
3019 extract_fd(
rb_fdset_t *dst, fd_set *src,
int (*func)(SOCKET))
3025 while (s < src->fd_count) {
3026 SOCKET fd = src->fd_array[s];
3028 if (!func || (*func)(fd)) {
3032 for (d = 0; d < dst->
fdset->fd_count; d++) {
3033 if (dst->
fdset->fd_array[d] == fd)
3036 if (d == dst->
fdset->fd_count) {
3037 if ((
int)dst->
fdset->fd_count >= dst->
capa) {
3038 dst->
capa = (dst->
fdset->fd_count / FD_SETSIZE + 1) * FD_SETSIZE;
3041 dst->
fdset->fd_array[dst->
fdset->fd_count++] = fd;
3045 &src->fd_array[s+1],
3046 sizeof(src->fd_array[0]) * (--src->fd_count - s));
3056 return dst ? dst->
fdset->fd_count : m;
3061 copy_fd(fd_set *dst, fd_set *src)
3064 if (!src || !dst)
return 0;
3066 for (s = 0; s < src->fd_count; ++s) {
3067 SOCKET fd = src->fd_array[s];
3069 for (d = 0; d < dst->fd_count; ++d) {
3070 if (dst->fd_array[d] == fd)
3073 if (d == dst->fd_count && d < FD_SETSIZE) {
3074 dst->fd_array[dst->fd_count++] = fd;
3078 return dst->fd_count;
3083 is_not_socket(SOCKET sock)
3085 return !is_socket(sock);
3090 is_pipe(SOCKET sock)
3095 ret = (GetFileType((HANDLE)sock) == FILE_TYPE_PIPE);
3103 is_readable_pipe(SOCKET sock)
3109 if (PeekNamedPipe((HANDLE)sock, NULL, 0, NULL, &n, NULL)) {
3113 ret = (GetLastError() == ERROR_BROKEN_PIPE);
3122 is_console(SOCKET sock)
3129 ret = (PeekConsoleInputW((HANDLE)sock, &ir, 1, &n));
3137 is_readable_console(SOCKET sock)
3144 if (PeekConsoleInputW((HANDLE)sock, &ir, 1, &n) && n > 0) {
3145 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
3146 ir.Event.KeyEvent.uChar.UnicodeChar) {
3149 else if (ir.EventType == KEY_EVENT && !ir.Event.KeyEvent.bKeyDown &&
3150 ir.Event.KeyEvent.wVirtualKeyCode == VK_MENU &&
3151 ir.Event.KeyEvent.uChar.UnicodeChar) {
3155 ReadConsoleInputW((HANDLE)sock, &ir, 1, &n);
3165 is_invalid_handle(SOCKET sock)
3167 return (HANDLE)sock == INVALID_HANDLE_VALUE;
3172 do_select(
int nfds, fd_set *rd, fd_set *wr, fd_set *ex,
3179 rb_w32_sleep(timeout->tv_sec * 1000 + timeout->tv_usec / 1000);
3181 rb_w32_sleep(INFINITE);
3185 thread_exclusive(select) {
3186 r = select(nfds, rd, wr, ex, timeout);
3188 if (r == SOCKET_ERROR) {
3189 errno = map_errno(WSAGetLastError());
3204 rb_w32_time_subtract(
struct timeval *rest,
const struct timeval *wait)
3206 if (rest->tv_sec < wait->tv_sec) {
3209 while (rest->tv_usec < wait->tv_usec) {
3210 if (rest->tv_sec <= wait->tv_sec) {
3214 rest->tv_usec += 1000 * 1000;
3216 rest->tv_sec -= wait->tv_sec;
3217 rest->tv_usec -= wait->tv_usec;
3218 return rest->tv_sec != 0 || rest->tv_usec != 0;
3225 if (t1->tv_sec < t2->tv_sec)
3227 if (t1->tv_sec > t2->tv_sec)
3229 if (t1->tv_usec < t2->tv_usec)
3231 if (t1->tv_usec > t2->tv_usec)
3238 int rb_w32_check_interrupt(
void *);
3243 rb_w32_select_with_thread(
int nfds, fd_set *rd, fd_set *wr, fd_set *ex,
3244 struct timeval *timeout,
void *th)
3253 struct timeval limit = {0, 0};
3255 if (nfds < 0 || (timeout && (timeout->tv_sec < 0 || timeout->tv_usec < 0))) {
3261 if (timeout->tv_sec < 0 ||
3262 timeout->tv_usec < 0 ||
3263 timeout->tv_usec >= 1000000) {
3267 gettimeofday(&limit, NULL);
3268 limit.tv_sec += timeout->tv_sec;
3269 limit.tv_usec += timeout->tv_usec;
3270 if (limit.tv_usec >= 1000000) {
3271 limit.tv_usec -= 1000000;
3283 nonsock += extract_fd(&else_rd, rd, is_not_socket);
3286 nonsock += extract_fd(&else_wr, wr, is_not_socket);
3289 if (extract_fd(NULL, else_rd.
fdset, is_invalid_handle) > 0 ||
3290 extract_fd(NULL, else_wr.
fdset, is_invalid_handle) > 0) {
3298 extract_fd(&pipe_rd, else_rd.
fdset, is_pipe);
3301 extract_fd(&cons_rd, else_rd.
fdset, is_console);
3304 extract_fd(&except, ex, is_not_socket);
3307 if (rd && (
int)rd->fd_count > r) r = (int)rd->fd_count;
3308 if (wr && (
int)wr->fd_count > r) r = (
int)wr->fd_count;
3309 if (ex && (
int)ex->fd_count > r) r = (
int)ex->fd_count;
3310 if (nfds > r) nfds = r;
3314 const struct timeval wait = {0, 10 * 1000};
3317 if (th && rb_w32_check_interrupt(th) != WAIT_TIMEOUT) {
3324 extract_fd(&else_rd, pipe_rd.
fdset, is_readable_pipe);
3325 extract_fd(&else_rd, cons_rd.
fdset, is_readable_console);
3328 if (else_rd.
fdset->fd_count || else_wr.
fdset->fd_count) {
3329 r = do_select(nfds, rd, wr, ex, &zero);
3331 r += copy_fd(rd, else_rd.
fdset);
3332 r += copy_fd(wr, else_wr.
fdset);
3338 const struct timeval *dowait = &wait;
3348 if (rd) copy_fd(&orig_rd, rd);
3349 if (wr) copy_fd(&orig_wr, wr);
3350 if (ex) copy_fd(&orig_ex, ex);
3351 r = do_select(nfds, rd, wr, ex, &zero);
3353 if (rd) copy_fd(rd, &orig_rd);
3354 if (wr) copy_fd(wr, &orig_wr);
3355 if (ex) copy_fd(ex, &orig_ex);
3359 gettimeofday(&now, NULL);
3361 if (!rb_w32_time_subtract(&rest, &now))
break;
3362 if (compare(&rest, &wait) < 0) dowait = &rest;
3364 Sleep(dowait->tv_sec * 1000 + (dowait->tv_usec + 999) / 1000);
3380 rb_w32_select(
int nfds, fd_set *rd, fd_set *wr, fd_set *ex,
3383 return rb_w32_select_with_thread(nfds, rd, wr, ex, timeout, 0);
3388 get_wsa_extension_function(SOCKET s, GUID guid)
3393 WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, &guid,
sizeof(guid),
3394 &
ptr,
sizeof(
ptr), &dmy, NULL, NULL);
3404 rb_w32_accept(
int s,
struct sockaddr *addr,
int *addrlen)
3410 r = accept(TO_SOCKET(s), addr, addrlen);
3411 if (r != INVALID_SOCKET) {
3412 SetHandleInformation((HANDLE)r, HANDLE_FLAG_INHERIT, 0);
3413 fd = rb_w32_open_osfhandle((intptr_t)r, O_RDWR|O_BINARY|O_NOINHERIT);
3415 socklist_insert(r, 0);
3420 errno = map_errno(WSAGetLastError());
3431 rb_w32_bind(
int s,
const struct sockaddr *addr,
int addrlen)
3436 r = bind(TO_SOCKET(s), addr, addrlen);
3437 if (r == SOCKET_ERROR)
3438 errno = map_errno(WSAGetLastError());
3447 rb_w32_connect(
int s,
const struct sockaddr *addr,
int addrlen)
3451 r = connect(TO_SOCKET(s), addr, addrlen);
3452 if (r == SOCKET_ERROR) {
3453 int err = WSAGetLastError();
3454 if (err != WSAEWOULDBLOCK)
3455 errno = map_errno(err);
3457 errno = EINPROGRESS;
3468 rb_w32_getpeername(
int s,
struct sockaddr *addr,
int *addrlen)
3472 r = getpeername(TO_SOCKET(s), addr, addrlen);
3473 if (r == SOCKET_ERROR)
3474 errno = map_errno(WSAGetLastError());
3483 rb_w32_getsockname(
int fd,
struct sockaddr *addr,
int *addrlen)
3488 sock = TO_SOCKET(fd);
3489 r = getsockname(sock, addr, addrlen);
3490 if (r == SOCKET_ERROR) {
3491 DWORD wsaerror = WSAGetLastError();
3492 if (wsaerror == WSAEINVAL) {
3494 if (socklist_lookup(sock, &flags)) {
3495 int af = GET_FAMILY(flags);
3497 memset(addr, 0, *addrlen);
3498 addr->sa_family = af;
3503 errno = map_errno(wsaerror);
3513 rb_w32_getsockopt(
int s,
int level,
int optname,
char *optval,
int *optlen)
3517 r = getsockopt(TO_SOCKET(s), level, optname, optval, optlen);
3518 if (r == SOCKET_ERROR)
3519 errno = map_errno(WSAGetLastError());
3528 rb_w32_ioctlsocket(
int s,
long cmd, u_long *argp)
3532 r = ioctlsocket(TO_SOCKET(s), cmd, argp);
3533 if (r == SOCKET_ERROR)
3534 errno = map_errno(WSAGetLastError());
3543 rb_w32_listen(
int s,
int backlog)
3547 r = listen(TO_SOCKET(s), backlog);
3548 if (r == SOCKET_ERROR)
3549 errno = map_errno(WSAGetLastError());
3561 finish_overlapped_socket(BOOL input, SOCKET s, WSAOVERLAPPED *wol,
int result, DWORD *
len, DWORD size)
3566 if (result != SOCKET_ERROR)
3568 else if ((err = WSAGetLastError()) == WSA_IO_PENDING) {
3569 switch (rb_w32_wait_events_blocking(&wol->hEvent, 1, INFINITE)) {
3572 result = WSAGetOverlappedResult(s, wol, &size, TRUE, &flg);
3579 result = SOCKET_ERROR;
3582 if ((err = WSAGetLastError()) == WSAECONNABORTED && !input)
3584 else if (err == WSAEMSGSIZE && input) {
3590 errno = map_errno(err);
3592 case WAIT_OBJECT_0 + 1:
3595 CancelIo((HANDLE)s);
3600 if (err == WSAECONNABORTED && !input)
3603 errno = map_errno(err);
3606 CloseHandle(wol->hEvent);
3613 overlapped_socket_io(BOOL input,
int fd,
char *buf,
int len,
int flags,
3614 struct sockaddr *addr,
int *addrlen)
3625 socklist_lookup(s, &mode);
3626 if (GET_FLAGS(mode) & O_NONBLOCK) {
3629 if (addr && addrlen)
3630 r = recvfrom(s, buf,
len, flags, addr, addrlen);
3632 r = recv(s, buf,
len, flags);
3633 if (r == SOCKET_ERROR)
3634 errno = map_errno(WSAGetLastError());
3637 if (addr && addrlen)
3638 r = sendto(s, buf,
len, flags, addr, *addrlen);
3640 r = send(s, buf,
len, flags);
3641 if (r == SOCKET_ERROR) {
3642 DWORD err = WSAGetLastError();
3643 if (err == WSAECONNABORTED)
3646 errno = map_errno(err);
3656 memset(&wol, 0,
sizeof(wol));
3658 wol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3661 if (addr && addrlen)
3662 ret = WSARecvFrom(s, &wbuf, 1, &size, &flg, addr, addrlen,
3665 ret = WSARecv(s, &wbuf, 1, &size, &flg, &wol, NULL);
3668 if (addr && addrlen)
3669 ret = WSASendTo(s, &wbuf, 1, &size, flags, addr, *addrlen,
3672 ret = WSASend(s, &wbuf, 1, &size, flags, &wol, NULL);
3676 finish_overlapped_socket(input, s, &wol, ret, &rlen, size);
3685 rb_w32_recv(
int fd,
char *buf,
int len,
int flags)
3687 return overlapped_socket_io(TRUE, fd, buf,
len, flags, NULL, NULL);
3692 rb_w32_recvfrom(
int fd,
char *buf,
int len,
int flags,
3693 struct sockaddr *from,
int *fromlen)
3695 return overlapped_socket_io(TRUE, fd, buf,
len, flags, from, fromlen);
3700 rb_w32_send(
int fd,
const char *buf,
int len,
int flags)
3702 return overlapped_socket_io(FALSE, fd, (
char *)buf,
len, flags, NULL, NULL);
3707 rb_w32_sendto(
int fd,
const char *buf,
int len,
int flags,
3708 const struct sockaddr *to,
int tolen)
3710 return overlapped_socket_io(FALSE, fd, (
char *)buf,
len, flags,
3711 (
struct sockaddr *)to, &tolen);
3714 #if !defined(MSG_TRUNC) && !defined(__MINGW32__)
3720 DWORD dwBufferCount;
3725 #ifndef WSAID_WSARECVMSG
3726 #define WSAID_WSARECVMSG {0xf689d7c8,0x6f1f,0x436b,{0x8a,0x53,0xe5,0x4f,0xe3,0x51,0xc3,0x22}}
3728 #ifndef WSAID_WSASENDMSG
3729 #define WSAID_WSASENDMSG {0xa441e712,0x754f,0x43ca,{0x84,0xa7,0x0d,0xee,0x44,0xcf,0x60,0x6d}}
3733 #define msghdr_to_wsamsg(msg, wsamsg) \
3736 (wsamsg)->name = (msg)->msg_name; \
3737 (wsamsg)->namelen = (msg)->msg_namelen; \
3738 (wsamsg)->lpBuffers = ALLOCA_N(WSABUF, (msg)->msg_iovlen); \
3739 (wsamsg)->dwBufferCount = (msg)->msg_iovlen; \
3740 for (i = 0; i < (msg)->msg_iovlen; ++i) { \
3741 (wsamsg)->lpBuffers[i].buf = (msg)->msg_iov[i].iov_base; \
3742 (wsamsg)->lpBuffers[i].len = (msg)->msg_iov[i].iov_len; \
3744 (wsamsg)->Control.buf = (msg)->msg_control; \
3745 (wsamsg)->Control.len = (msg)->msg_controllen; \
3746 (wsamsg)->dwFlags = (msg)->msg_flags; \
3751 recvmsg(
int fd,
struct msghdr *msg,
int flags)
3753 typedef int (WSAAPI *WSARecvMsg_t)(SOCKET,
WSAMSG *, DWORD *, WSAOVERLAPPED *, LPWSAOVERLAPPED_COMPLETION_ROUTINE);
3754 static WSARecvMsg_t pWSARecvMsg = NULL;
3764 static const GUID guid = WSAID_WSARECVMSG;
3765 pWSARecvMsg = (WSARecvMsg_t)get_wsa_extension_function(s, guid);
3770 msghdr_to_wsamsg(msg, &wsamsg);
3771 wsamsg.dwFlags |= flags;
3773 socklist_lookup(s, &mode);
3774 if (GET_FLAGS(mode) & O_NONBLOCK) {
3776 if ((ret = pWSARecvMsg(s, &wsamsg, &
len, NULL, NULL)) == SOCKET_ERROR) {
3777 errno = map_errno(WSAGetLastError());
3785 memset(&wol, 0,
sizeof(wol));
3787 wol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3788 ret = pWSARecvMsg(s, &wsamsg, &size, &wol, NULL);
3791 ret = finish_overlapped_socket(TRUE, s, &wol, ret, &
len, size);
3793 if (ret == SOCKET_ERROR)
3797 msg->msg_name = wsamsg.name;
3798 msg->msg_namelen = wsamsg.namelen;
3799 msg->msg_flags = wsamsg.dwFlags;
3806 sendmsg(
int fd,
const struct msghdr *msg,
int flags)
3808 typedef int (WSAAPI *WSASendMsg_t)(SOCKET,
const WSAMSG *, DWORD, DWORD *, WSAOVERLAPPED *, LPWSAOVERLAPPED_COMPLETION_ROUTINE);
3809 static WSASendMsg_t pWSASendMsg = NULL;
3819 static const GUID guid = WSAID_WSASENDMSG;
3820 pWSASendMsg = (WSASendMsg_t)get_wsa_extension_function(s, guid);
3825 msghdr_to_wsamsg(msg, &wsamsg);
3827 socklist_lookup(s, &mode);
3828 if (GET_FLAGS(mode) & O_NONBLOCK) {
3830 if ((ret = pWSASendMsg(s, &wsamsg, flags, &
len, NULL, NULL)) == SOCKET_ERROR) {
3831 errno = map_errno(WSAGetLastError());
3839 memset(&wol, 0,
sizeof(wol));
3841 wol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3842 ret = pWSASendMsg(s, &wsamsg, flags, &size, &wol, NULL);
3845 finish_overlapped_socket(FALSE, s, &wol, ret, &
len, size);
3855 rb_w32_setsockopt(
int s,
int level,
int optname,
const char *optval,
int optlen)
3859 r = setsockopt(TO_SOCKET(s), level, optname, optval, optlen);
3860 if (r == SOCKET_ERROR)
3861 errno = map_errno(WSAGetLastError());
3870 rb_w32_shutdown(
int s,
int how)
3874 r = shutdown(TO_SOCKET(s), how);
3875 if (r == SOCKET_ERROR)
3876 errno = map_errno(WSAGetLastError());
3883 open_ifs_socket(
int af,
int type,
int protocol)
3885 unsigned long proto_buffers_len = 0;
3887 SOCKET out = INVALID_SOCKET;
3889 if (WSAEnumProtocols(NULL, NULL, &proto_buffers_len) == SOCKET_ERROR) {
3890 error_code = WSAGetLastError();
3891 if (error_code == WSAENOBUFS) {
3892 WSAPROTOCOL_INFO *proto_buffers;
3893 int protocols_available = 0;
3895 proto_buffers = (WSAPROTOCOL_INFO *)malloc(proto_buffers_len);
3896 if (!proto_buffers) {
3897 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
3898 return INVALID_SOCKET;
3901 protocols_available =
3902 WSAEnumProtocols(NULL, proto_buffers, &proto_buffers_len);
3903 if (protocols_available != SOCKET_ERROR) {
3905 for (i = 0; i < protocols_available; i++) {
3906 if ((af != AF_UNSPEC && af != proto_buffers[i].iAddressFamily) ||
3907 (
type != proto_buffers[i].iSocketType) ||
3908 (protocol != 0 && protocol != proto_buffers[i].iProtocol))
3911 if ((proto_buffers[i].dwServiceFlags1 & XP1_IFS_HANDLES) == 0)
3914 out = WSASocket(af,
type, protocol, &(proto_buffers[i]), 0,
3915 WSA_FLAG_OVERLAPPED);
3918 if (out == INVALID_SOCKET)
3919 out = WSASocket(af,
type, protocol, NULL, 0, 0);
3920 if (out != INVALID_SOCKET)
3921 SetHandleInformation((HANDLE)out, HANDLE_FLAG_INHERIT, 0);
3924 free(proto_buffers);
3935 rb_w32_socket(
int af,
int type,
int protocol)
3941 s = open_ifs_socket(af,
type, protocol);
3942 if (s == INVALID_SOCKET) {
3943 errno = map_errno(WSAGetLastError());
3947 fd = rb_w32_open_osfhandle(s, O_RDWR|O_BINARY|O_NOINHERIT);
3949 socklist_insert(s, MAKE_SOCKDATA(af, 0));
3957 #undef gethostbyaddr
3960 struct hostent * WSAAPI
3961 rb_w32_gethostbyaddr(
const char *addr,
int len,
int type)
3965 r = gethostbyaddr(addr,
len,
type);
3967 errno = map_errno(WSAGetLastError());
3972 #undef gethostbyname
3975 struct hostent * WSAAPI
3976 rb_w32_gethostbyname(
const char *name)
3980 r = gethostbyname(name);
3982 errno = map_errno(WSAGetLastError());
3991 rb_w32_gethostname(
char *name,
int len)
3995 r = gethostname(name,
len);
3996 if (r == SOCKET_ERROR)
3997 errno = map_errno(WSAGetLastError());
4002 #undef getprotobyname
4005 struct protoent * WSAAPI
4006 rb_w32_getprotobyname(
const char *name)
4010 r = getprotobyname(name);
4012 errno = map_errno(WSAGetLastError());
4017 #undef getprotobynumber
4020 struct protoent * WSAAPI
4021 rb_w32_getprotobynumber(
int num)
4025 r = getprotobynumber(num);
4027 errno = map_errno(WSAGetLastError());
4032 #undef getservbyname
4035 struct servent * WSAAPI
4036 rb_w32_getservbyname(
const char *name,
const char *proto)
4040 r = getservbyname(name, proto);
4042 errno = map_errno(WSAGetLastError());
4047 #undef getservbyport
4050 struct servent * WSAAPI
4051 rb_w32_getservbyport(
int port,
const char *proto)
4055 r = getservbyport(port, proto);
4057 errno = map_errno(WSAGetLastError());
4062 #ifdef HAVE_AFUNIX_H
4066 socketpair_unix_path(
struct sockaddr_un *sock_un)
4069 WCHAR wpath[
sizeof(sock_un->sun_path)/
sizeof(*sock_un->sun_path)] = L
"";
4074 listener = socket(AF_UNIX, SOCK_STREAM, 0);
4075 if (listener == INVALID_SOCKET)
4078 memset(sock_un, 0,
sizeof(*sock_un));
4079 sock_un->sun_family = AF_UNIX;
4089 for (
int try = 0; ;
try++) {
4090 LARGE_INTEGER ticks;
4091 size_t path_len = 0;
4092 const size_t maxpath =
sizeof(sock_un->sun_path)/
sizeof(*sock_un->sun_path);
4097 path_len = GetTempPathW(maxpath, wpath);
4100 wcsncpy(wpath, L
"C:/Temp/", maxpath);
4101 path_len = lstrlenW(wpath);
4108 closesocket(listener);
4113 path_len = WideCharToMultiByte(CP_UTF8, 0, wpath, path_len, sock_un->sun_path, maxpath, NULL, NULL);
4114 QueryPerformanceCounter(&ticks);
4115 path_len += snprintf(sock_un->sun_path + path_len,
4119 GetCurrentProcessId());
4122 MultiByteToWideChar(CP_UTF8, 0, sock_un->sun_path, -1, wpath,
sizeof(wpath)/
sizeof(*wpath));
4124 if (bind(listener, (
struct sockaddr *)sock_un,
sizeof(*sock_un)) != SOCKET_ERROR)
4127 closesocket(listener);
4129 return sizeof(*sock_un);
4135 socketpair_internal(
int af,
int type,
int protocol, SOCKET *sv)
4137 SOCKET svr = INVALID_SOCKET, r = INVALID_SOCKET, w = INVALID_SOCKET;
4138 struct sockaddr_in sock_in4;
4141 struct sockaddr_in6 sock_in6;
4144 #ifdef HAVE_AFUNIX_H
4145 struct sockaddr_un sock_un = {0, {0}};
4146 WCHAR wpath[
sizeof(sock_un.sun_path)/
sizeof(*sock_un.sun_path)] = L
"";
4149 struct sockaddr *addr;
4155 #if defined PF_INET && PF_INET != AF_INET
4158 sock_in4.sin_family = AF_INET;
4159 sock_in4.sin_port = 0;
4160 sock_in4.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4161 addr = (
struct sockaddr *)&sock_in4;
4162 len =
sizeof(sock_in4);
4166 memset(&sock_in6, 0,
sizeof(sock_in6));
4167 sock_in6.sin6_family = AF_INET6;
4168 sock_in6.sin6_addr = IN6ADDR_LOOPBACK_INIT;
4169 addr = (
struct sockaddr *)&sock_in6;
4170 len =
sizeof(sock_in6);
4173 #ifdef HAVE_AFUNIX_H
4175 addr = (
struct sockaddr *)&sock_un;
4176 len = socketpair_unix_path(&sock_un);
4177 MultiByteToWideChar(CP_UTF8, 0, sock_un.sun_path, -1, wpath,
sizeof(wpath)/
sizeof(*wpath));
4183 errno = EAFNOSUPPORT;
4186 if (
type != SOCK_STREAM) {
4191 sv[0] = (SOCKET)INVALID_HANDLE_VALUE;
4192 sv[1] = (SOCKET)INVALID_HANDLE_VALUE;
4195 svr = open_ifs_socket(af,
type, protocol);
4196 if (svr == INVALID_SOCKET)
4198 if (bind(svr, addr,
len) < 0)
4200 if (getsockname(svr, addr, &
len) < 0)
4202 if (
type == SOCK_STREAM)
4205 w = open_ifs_socket(af,
type, protocol);
4206 if (w == INVALID_SOCKET)
4208 if (connect(w, addr,
len) < 0)
4211 r = accept(svr, addr, &
len);
4212 if (r == INVALID_SOCKET)
4214 SetHandleInformation((HANDLE)r, HANDLE_FLAG_INHERIT, 0);
4220 errno = map_errno(WSAGetLastError());
4221 if (r != INVALID_SOCKET)
4223 if (w != INVALID_SOCKET)
4230 if (svr != INVALID_SOCKET)
4232 #ifdef HAVE_AFUNIX_H
4233 if (sock_un.sun_family == AF_UNIX)
4243 socketpair(
int af,
int type,
int protocol,
int *sv)
4247 if (socketpair_internal(af,
type, protocol, pair) < 0)
4249 sv[0] = rb_w32_open_osfhandle(pair[0], O_RDWR|O_BINARY|O_NOINHERIT);
4251 closesocket(pair[0]);
4252 closesocket(pair[1]);
4255 sv[1] = rb_w32_open_osfhandle(pair[1], O_RDWR|O_BINARY|O_NOINHERIT);
4257 rb_w32_close(sv[0]);
4258 closesocket(pair[1]);
4261 socklist_insert(pair[0], MAKE_SOCKDATA(af, 0));
4262 socklist_insert(pair[1], MAKE_SOCKDATA(af, 0));
4267 #if !defined(_MSC_VER) || _MSC_VER >= 1400
4270 str2guid(
const char *str, GUID *guid)
4272 #define hex2byte(str) \
4273 ((isdigit(*(str)) ? *(str) - '0' : toupper(*(str)) - 'A' + 10) << 4 | (isdigit(*((str) + 1)) ? *((str) + 1) - '0' : toupper(*((str) + 1)) - 'A' + 10))
4276 if (*str ==
'{') str++;
4277 guid->Data1 = (long)strtoul(str, &end, 16);
4279 guid->Data2 = (
unsigned short)strtoul(str, &end, 16);
4281 guid->Data3 = (
unsigned short)strtoul(str, &end, 16);
4283 guid->Data4[0] = hex2byte(str);
4285 guid->Data4[1] = hex2byte(str);
4287 for (i = 0; i < 6; i++) {
4288 guid->Data4[i + 2] = hex2byte(str);
4294 #ifndef HAVE_TYPE_NET_LUID
4298 uint64_t Reserved :24;
4299 uint64_t NetLuidIndex :24;
4300 uint64_t IfType :16;
4306 getifaddrs(
struct ifaddrs **ifap)
4310 IP_ADAPTER_ADDRESSES *root, *addr;
4313 ret = GetAdaptersAddresses(AF_UNSPEC, 0, NULL, NULL, &size);
4314 if (ret != ERROR_BUFFER_OVERFLOW) {
4315 errno = map_errno(ret);
4319 ret = GetAdaptersAddresses(AF_UNSPEC, 0, NULL, root, &size);
4320 if (ret != ERROR_SUCCESS) {
4321 errno = map_errno(ret);
4326 for (prev = NULL, addr = root; addr; addr = addr->Next) {
4328 char name[IFNAMSIZ];
4333 prev->ifa_next = ifa;
4337 str2guid(addr->AdapterName, &guid);
4338 if (ConvertInterfaceGuidToLuid(&guid, &luid) == NO_ERROR &&
4339 ConvertInterfaceLuidToNameA(&luid, name,
sizeof(name)) == NO_ERROR) {
4346 if (addr->IfType & IF_TYPE_SOFTWARE_LOOPBACK)
4347 ifa->ifa_flags |= IFF_LOOPBACK;
4348 if (addr->OperStatus == IfOperStatusUp) {
4349 ifa->ifa_flags |= IFF_UP;
4351 if (addr->FirstUnicastAddress) {
4352 IP_ADAPTER_UNICAST_ADDRESS *cur;
4354 for (cur = addr->FirstUnicastAddress; cur; cur = cur->Next) {
4355 if (cur->Flags & IP_ADAPTER_ADDRESS_TRANSIENT ||
4356 cur->DadState == IpDadStateDeprecated) {
4362 prev->ifa_next = ifa;
4364 ifa->ifa_flags = prev->ifa_flags;
4366 ifa->ifa_addr =
ruby_xmalloc(cur->Address.iSockaddrLength);
4367 memcpy(ifa->ifa_addr, cur->Address.lpSockaddr,
4368 cur->Address.iSockaddrLength);
4383 freeifaddrs(
struct ifaddrs *ifp)
4386 struct ifaddrs *next = ifp->ifa_next;
4400 void endhostent(
void) {}
4401 void endnetent(
void) {}
4402 void endprotoent(
void) {}
4403 void endservent(
void) {}
4405 struct netent *getnetent (
void) {
return (
struct netent *) NULL;}
4407 struct netent *getnetbyaddr(
long net,
int type) {
return (
struct netent *)NULL;}
4409 struct netent *getnetbyname(
const char *name) {
return (
struct netent *)NULL;}
4411 struct protoent *getprotoent (
void) {
return (
struct protoent *) NULL;}
4413 struct servent *getservent (
void) {
return (
struct servent *) NULL;}
4415 void sethostent (
int stayopen) {}
4417 void setnetent (
int stayopen) {}
4419 void setprotoent (
int stayopen) {}
4421 void setservent (
int stayopen) {}
4424 int rb_w32_set_nonblock2(
int fd,
int nonblock);
4428 setfl(SOCKET sock,
int arg)
4435 socklist_lookup(sock, &flag);
4436 af = GET_FAMILY(flag);
4437 flag = GET_FLAGS(flag);
4438 if (arg & O_NONBLOCK) {
4443 flag &= ~O_NONBLOCK;
4447 ret = ioctlsocket(sock, FIONBIO, &ioctlArg);
4449 socklist_insert(sock, MAKE_SOCKDATA(af, flag));
4451 errno = map_errno(WSAGetLastError());
4459 dupfd(HANDLE hDup,
int flags,
int minfd)
4467 ret = _open_osfhandle((intptr_t)hDup, flags | FOPEN);
4469 goto close_fds_and_return;
4472 goto close_fds_and_return;
4474 fds[filled++] = ret;
4475 }
while (filled < (
int)numberof(fds));
4477 ret = dupfd(hDup, flags, minfd);
4479 close_fds_and_return:
4481 while (filled > 0) {
4482 int fd = fds[--filled];
4483 _set_osfhnd(fd, (intptr_t)INVALID_HANDLE_VALUE);
4493 fcntl(
int fd,
int cmd, ...)
4502 arg = va_arg(va,
int);
4504 return rb_w32_set_nonblock2(fd, arg);
4506 case F_DUPFD:
case F_DUPFD_CLOEXEC: {
4510 if (!(DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
4511 GetCurrentProcess(), &hDup, 0L,
4512 cmd == F_DUPFD && !(flag & FNOINHERIT),
4513 DUPLICATE_SAME_ACCESS))) {
4514 errno = map_errno(GetLastError());
4519 arg = va_arg(va,
int);
4525 flag &= ~FNOINHERIT;
4526 if ((ret = dupfd(hDup, flag, arg)) == -1)
4532 if (h == -1)
return -1;
4533 if (!GetHandleInformation((HANDLE)h, &flag)) {
4534 errno = map_errno(GetLastError());
4537 return (flag & HANDLE_FLAG_INHERIT) ? 0 : FD_CLOEXEC;
4541 if (h == -1)
return -1;
4543 arg = va_arg(va,
int);
4545 if (!SetHandleInformation((HANDLE)h, HANDLE_FLAG_INHERIT,
4546 (arg & FD_CLOEXEC) ? 0 : HANDLE_FLAG_INHERIT)) {
4547 errno = map_errno(GetLastError());
4550 if (arg & FD_CLOEXEC)
4551 _osfile(fd) |= FNOINHERIT;
4553 _osfile(fd) &= ~FNOINHERIT;
4564 rb_w32_set_nonblock2(
int fd,
int nonblock)
4566 SOCKET sock = TO_SOCKET(fd);
4567 if (is_socket(sock)) {
4568 return setfl(sock, nonblock ? O_NONBLOCK : 0);
4570 else if (is_pipe(sock)) {
4572 if (!GetNamedPipeHandleState((HANDLE)sock, &state, NULL, NULL, NULL, NULL, 0)) {
4573 errno = map_errno(GetLastError());
4577 state |= PIPE_NOWAIT;
4580 state &= ~PIPE_NOWAIT;
4582 if (!SetNamedPipeHandleState((HANDLE)sock, &state, NULL, NULL)) {
4583 errno = map_errno(GetLastError());
4595 rb_w32_set_nonblock(
int fd)
4597 return rb_w32_set_nonblock2(fd, TRUE);
4606 poll_child_status(
struct ChildRecord *child,
int *stat_loc)
4611 if (!GetExitCodeProcess(child->hProcess, &exitcode)) {
4613 err = GetLastError();
4615 case ERROR_INVALID_PARAMETER:
4618 case ERROR_INVALID_HANDLE:
4622 errno = map_errno(err);
4626 CloseChildHandle(child);
4629 if (exitcode != STILL_ACTIVE) {
4632 if (rb_w32_wait_events_blocking(&child->hProcess, 1, INFINITE) != WAIT_OBJECT_0) {
4636 CloseChildHandle(child);
4638 *stat_loc = exitcode << 8;
4639 if (exitcode & 0xC0000000) {
4640 static const struct {
4644 {STATUS_ACCESS_VIOLATION, SIGSEGV},
4645 {STATUS_ILLEGAL_INSTRUCTION, SIGILL},
4646 {STATUS_PRIVILEGED_INSTRUCTION, SIGILL},
4647 {STATUS_FLOAT_DENORMAL_OPERAND, SIGFPE},
4648 {STATUS_FLOAT_DIVIDE_BY_ZERO, SIGFPE},
4649 {STATUS_FLOAT_INEXACT_RESULT, SIGFPE},
4650 {STATUS_FLOAT_INVALID_OPERATION, SIGFPE},
4651 {STATUS_FLOAT_OVERFLOW, SIGFPE},
4652 {STATUS_FLOAT_STACK_CHECK, SIGFPE},
4653 {STATUS_FLOAT_UNDERFLOW, SIGFPE},
4654 #ifdef STATUS_FLOAT_MULTIPLE_FAULTS
4655 {STATUS_FLOAT_MULTIPLE_FAULTS, SIGFPE},
4657 #ifdef STATUS_FLOAT_MULTIPLE_TRAPS
4658 {STATUS_FLOAT_MULTIPLE_TRAPS, SIGFPE},
4660 {STATUS_CONTROL_C_EXIT, SIGINT},
4663 for (i = 0; i < (int)numberof(table); i++) {
4664 if (table[i].status == exitcode) {
4665 *stat_loc |= table[i].sig;
4670 if (i >= (
int)numberof(table))
4671 *stat_loc |= SIGSEGV;
4681 waitpid(rb_pid_t pid,
int *stat_loc,
int options)
4686 if (options == WNOHANG) {
4697 HANDLE events[MAXCHILDNUM];
4700 FOREACH_CHILD(child) {
4701 if (!child->pid || child->pid < 0)
continue;
4702 if ((pid = poll_child_status(child, stat_loc)))
return pid;
4703 events[count++] = child->hProcess;
4704 } END_FOREACH_CHILD;
4710 ret = rb_w32_wait_events_blocking(events, count, timeout);
4711 if (ret == WAIT_TIMEOUT)
return 0;
4712 if ((ret -= WAIT_OBJECT_0) == count) {
4716 errno = map_errno(GetLastError());
4720 cause = FindChildSlotByHandle(events[ret]);
4725 return poll_child_status(cause, stat_loc);
4735 while (!(pid = poll_child_status(child, stat_loc))) {
4737 int ret = rb_w32_wait_events_blocking(&child->hProcess, 1, timeout);
4738 if (ret == WAIT_OBJECT_0 + 1)
return -1;
4739 if (ret != WAIT_OBJECT_0) {
4741 if (options & WNOHANG) {
4748 if (pid == -1 && retried) pid = 0;
4754 #include <sys/timeb.h>
4759 filetime_split(
const FILETIME* ft,
long *subsec)
4765 tmp.LowPart = ft->dwLowDateTime;
4766 tmp.HighPart = ft->dwHighDateTime;
4773 lt -= (
LONG_LONG)((1970-1601)*365.2425) * 24 * 60 * 60 * subsec_unit;
4775 *subsec = (long)(lt % subsec_unit);
4776 return (time_t)(lt / subsec_unit);
4786 GetSystemTimePreciseAsFileTime(&ft);
4787 tv->tv_sec = filetime_split(&ft, &subsec);
4788 tv->tv_usec = subsec / 10;
4795 clock_gettime(clockid_t clock_id,
struct timespec *sp)
4798 case CLOCK_REALTIME:
4803 GetSystemTimePreciseAsFileTime(&ft);
4804 sp->tv_sec = filetime_split(&ft, &subsec);
4805 sp->tv_nsec = subsec * 100;
4808 case CLOCK_MONOTONIC:
4811 LARGE_INTEGER count;
4812 if (!QueryPerformanceFrequency(&freq)) {
4813 errno = map_errno(GetLastError());
4816 if (!QueryPerformanceCounter(&count)) {
4817 errno = map_errno(GetLastError());
4820 sp->tv_sec = count.QuadPart / freq.QuadPart;
4821 if (freq.QuadPart < 1000000000)
4822 sp->tv_nsec = (count.QuadPart % freq.QuadPart) * 1000000000 / freq.QuadPart;
4824 sp->tv_nsec = (
long)((count.QuadPart % freq.QuadPart) * (1000000000.0 / freq.QuadPart));
4835 clock_getres(clockid_t clock_id,
struct timespec *sp)
4838 case CLOCK_REALTIME:
4844 case CLOCK_MONOTONIC:
4847 if (!QueryPerformanceFrequency(&freq)) {
4848 errno = map_errno(GetLastError());
4852 sp->tv_nsec = (long)(1000000000.0 / freq.QuadPart);
4863 w32_getcwd(
char *buffer,
int size, UINT cp,
void *alloc(
int,
void *),
void *arg)
4868 len = GetCurrentDirectoryW(0, NULL);
4870 errno = map_errno(GetLastError());
4874 if (buffer && size <
len) {
4880 if (!GetCurrentDirectoryW(
len, p)) {
4881 errno = map_errno(GetLastError());
4885 wlen = translate_wchar(p, L
'\\', L
'/') - p + 1;
4886 len = WideCharToMultiByte(cp, 0, p, wlen, NULL, 0, NULL, NULL);
4894 buffer = (*alloc)(
len, arg);
4900 WideCharToMultiByte(cp, 0, p, wlen, buffer,
len, NULL, NULL);
4907 getcwd_alloc(
int size,
void *dummy)
4909 return malloc(size);
4914 rb_w32_getcwd(
char *buffer,
int size)
4916 return w32_getcwd(buffer, size, filecp(), getcwd_alloc, NULL);
4921 rb_w32_ugetcwd(
char *buffer,
int size)
4923 return w32_getcwd(buffer, size, CP_UTF8, getcwd_alloc, NULL);
4928 getcwd_value(
int size,
void *arg)
4936 rb_dir_getwd_ospath(
void)
4939 w32_getcwd(NULL, 0, CP_UTF8, getcwd_value, &cwd);
4945 chown(
const char *path,
int owner,
int group)
4952 rb_w32_uchown(
const char *path,
int owner,
int group)
4958 lchown(
const char *path,
int owner,
int group)
4964 rb_w32_ulchown(
const char *path,
int owner,
int group)
4971 kill(rb_pid_t pid,
int sig)
4976 if (pid < 0 || (pid == 0 && sig != SIGINT)) {
4981 if ((
unsigned int)pid == GetCurrentProcessId() &&
4982 (sig != 0 && sig != SIGKILL)) {
4983 if ((ret =
raise(sig)) != 0) {
4994 OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, (DWORD)pid);
4995 if (hProc == NULL || hProc == INVALID_HANDLE_VALUE) {
4996 if (GetLastError() == ERROR_INVALID_PARAMETER) {
5012 DWORD ctrlEvent = CTRL_C_EVENT;
5016 ctrlEvent = CTRL_BREAK_EVENT;
5018 if (!GenerateConsoleCtrlEvent(ctrlEvent, (DWORD)pid)) {
5019 if ((err = GetLastError()) == 0)
5022 errno = map_errno(GetLastError());
5033 hProc = child->hProcess;
5036 hProc = OpenProcess(PROCESS_TERMINATE | PROCESS_QUERY_INFORMATION, FALSE, (DWORD)pid);
5038 if (hProc == NULL || hProc == INVALID_HANDLE_VALUE) {
5039 if (GetLastError() == ERROR_INVALID_PARAMETER) {
5049 if (!GetExitCodeProcess(hProc, &status)) {
5050 errno = map_errno(GetLastError());
5053 else if (status == STILL_ACTIVE) {
5054 if (!TerminateProcess(hProc, 0)) {
5081 wlink(
const WCHAR *from,
const WCHAR *to)
5083 if (!CreateHardLinkW(to, from, NULL)) {
5084 errno = map_errno(GetLastError());
5093 rb_w32_ulink(
const char *from,
const char *to)
5099 if (!(wfrom = utf8_to_wstr(from, NULL)))
5101 if (!(wto = utf8_to_wstr(to, NULL))) {
5105 ret = wlink(wfrom, wto);
5113 link(
const char *from,
const char *to)
5119 if (!(wfrom = filecp_to_wstr(from, NULL)))
5121 if (!(wto = filecp_to_wstr(to, NULL))) {
5125 ret = wlink(wfrom, wto);
5132 #ifndef FILE_DEVICE_FILE_SYSTEM
5133 # define FILE_DEVICE_FILE_SYSTEM 0x00000009
5135 #ifndef FSCTL_GET_REPARSE_POINT
5136 # define FSCTL_GET_REPARSE_POINT ((0x9<<16)|(42<<2))
5138 #ifndef IO_REPARSE_TAG_SYMLINK
5139 # define IO_REPARSE_TAG_SYMLINK 0xA000000CL
5150 f = open_special(path, 0, FILE_FLAG_OPEN_REPARSE_POINT);
5151 if (f == INVALID_HANDLE_VALUE) {
5152 return GetLastError();
5155 if (!DeviceIoControl(f, FSCTL_GET_REPARSE_POINT, NULL, 0,
5156 rp, size, &ret, NULL)) {
5159 else if (rp->ReparseTag != IO_REPARSE_TAG_SYMLINK &&
5160 rp->ReparseTag != IO_REPARSE_TAG_MOUNT_POINT) {
5161 e = ERROR_INVALID_PARAMETER;
5169 rb_w32_reparse_symlink_p(
const WCHAR *path)
5177 e = rb_w32_read_reparse_point(path, rp,
sizeof(rbuf), &wbuf, &
len);
5178 if (e == ERROR_MORE_DATA) {
5179 size_t size = rb_w32_reparse_buffer_size(
len + 1);
5181 e = rb_w32_read_reparse_point(path, rp, size, &wbuf, &
len);
5186 case ERROR_MORE_DATA:
5195 size_t bufsize, WCHAR **result, DWORD *
len)
5197 int e = reparse_symlink(path, rp, bufsize);
5200 if (!e || e == ERROR_MORE_DATA) {
5202 if (rp->ReparseTag == IO_REPARSE_TAG_SYMLINK) {
5203 name = ((
char *)rp->SymbolicLinkReparseBuffer.PathBuffer +
5204 rp->SymbolicLinkReparseBuffer.PrintNameOffset);
5205 ret = rp->SymbolicLinkReparseBuffer.PrintNameLength;
5206 *
len = ret /
sizeof(WCHAR);
5208 else if (rp->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT) {
5209 static const WCHAR volume[] = L
"Volume{";
5211 name = ((
char *)rp->MountPointReparseBuffer.PathBuffer +
5212 rp->MountPointReparseBuffer.SubstituteNameOffset +
5213 volume_prefix_len *
sizeof(WCHAR));
5214 ret = rp->MountPointReparseBuffer.SubstituteNameLength;
5215 *
len = ret /
sizeof(WCHAR);
5216 ret -= volume_prefix_len *
sizeof(WCHAR);
5217 if (ret >
sizeof(volume) - 1 *
sizeof(WCHAR) &&
5218 memcmp(name, volume,
sizeof(volume) - 1 *
sizeof(WCHAR)) == 0)
5226 if ((
char *)name + ret +
sizeof(WCHAR) > (
char *)rp + bufsize)
5230 ((WCHAR *)name)[ret/
sizeof(WCHAR)] = L
'\0';
5231 translate_wchar(name, L
'\\', L
'/');
5241 w32_readlink(UINT cp,
const char *path,
char *buf,
size_t bufsize)
5243 VALUE rp_buf, rp_buf_bigger = 0;
5244 DWORD
len = MultiByteToWideChar(cp, 0, path, -1, NULL, 0);
5245 size_t size = rb_w32_reparse_buffer_size(bufsize);
5247 WCHAR *wpath =
ALLOCV(rp_buf,
sizeof(WCHAR) *
len + size);
5252 MultiByteToWideChar(cp, 0, path, -1, wpath,
len);
5253 e = rb_w32_read_reparse_point(wpath, rp, size, &wname, &
len);
5254 if (e == ERROR_MORE_DATA) {
5255 size = rb_w32_reparse_buffer_size(
len + 1);
5256 rp =
ALLOCV(rp_buf_bigger, size);
5257 e = rb_w32_read_reparse_point(wpath, rp, size, &wname, &
len);
5262 errno = e == -1 ? EINVAL : map_errno(e);
5265 len = lstrlenW(wname);
5266 ret = WideCharToMultiByte(cp, 0, wname,
len, buf, bufsize, NULL, NULL);
5277 rb_w32_ureadlink(
const char *path,
char *buf,
size_t bufsize)
5279 return w32_readlink(CP_UTF8, path, buf, bufsize);
5284 readlink(
const char *path,
char *buf,
size_t bufsize)
5286 return w32_readlink(filecp(), path, buf, bufsize);
5289 #ifndef SYMBOLIC_LINK_FLAG_DIRECTORY
5290 #define SYMBOLIC_LINK_FLAG_DIRECTORY (0x1)
5292 #ifndef SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE
5293 #define SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE (0x2)
5298 w32_symlink(UINT cp,
const char *src,
const char *link)
5300 int atts, len1, len2;
5302 WCHAR *wsrc, *wlink;
5307 static DWORD create_flag = SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
5317 len1 = MultiByteToWideChar(cp, 0, src, -1, NULL, 0);
5318 len2 = MultiByteToWideChar(cp, 0, link, -1, NULL, 0);
5319 wsrc =
ALLOCV_N(WCHAR, buf, len1+len2);
5320 wlink = wsrc + len1;
5321 MultiByteToWideChar(cp, 0, src, -1, wsrc, len1);
5322 MultiByteToWideChar(cp, 0, link, -1, wlink, len2);
5323 translate_wchar(wsrc, L
'/', L
'\\');
5325 atts = GetFileAttributesW(wsrc);
5326 if (atts != -1 && atts & FILE_ATTRIBUTE_DIRECTORY)
5327 flag = SYMBOLIC_LINK_FLAG_DIRECTORY;
5328 ret = CreateSymbolicLinkW(wlink, wsrc, flag |= create_flag);
5330 (e = GetLastError()) == ERROR_INVALID_PARAMETER &&
5331 (flag & SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE)) {
5333 flag &= ~SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
5334 ret = CreateSymbolicLinkW(wlink, wsrc, flag);
5335 if (!ret) e = GetLastError();
5340 errno = map_errno(e);
5348 rb_w32_usymlink(
const char *src,
const char *link)
5350 return w32_symlink(CP_UTF8, src, link);
5355 symlink(
const char *src,
const char *link)
5357 return w32_symlink(filecp(), src, link);
5364 return waitpid(-1, status, 0);
5369 w32_getenv(
const char *name, UINT cp)
5371 WCHAR *wenvarea, *wenv;
5372 int len = strlen(name);
5373 char *env, *found = NULL;
5376 if (
len == 0)
return NULL;
5381 return getenv(name);
5384 thread_exclusive(uenvarea) {
5389 wenvarea = GetEnvironmentStringsW();
5391 map_errno(GetLastError());
5394 for (wenv = wenvarea, wlen = 1; *wenv; wenv += lstrlenW(wenv) + 1)
5395 wlen += lstrlenW(wenv) + 1;
5396 uenvarea = wstr_to_mbstr(cp, wenvarea, wlen, NULL);
5397 FreeEnvironmentStringsW(wenvarea);
5401 for (env = uenvarea; *env; env += strlen(env) + 1) {
5402 if (strncasecmp(env, name,
len) == 0 && *(env +
len) ==
'=') {
5403 found = env +
len + 1;
5414 rb_w32_ugetenv(
const char *name)
5416 return w32_getenv(name, CP_UTF8);
5421 rb_w32_getenv(
const char *name)
5423 return w32_getenv(name, CP_ACP);
5428 get_attr_vsn(
const WCHAR *path, DWORD *atts, DWORD *vsn)
5430 BY_HANDLE_FILE_INFORMATION st = {0};
5432 HANDLE h = open_special(path, 0, FILE_FLAG_OPEN_REPARSE_POINT);
5434 if (h == INVALID_HANDLE_VALUE) {
5439 if (!GetFileInformationByHandle(h, &st)) {
5444 *atts = st.dwFileAttributes;
5445 *vsn = st.dwVolumeSerialNumber;
5453 wrename(
const WCHAR *oldpath,
const WCHAR *newpath)
5456 DWORD oldatts = 0, newatts = (DWORD)-1;
5457 DWORD oldvsn = 0, newvsn = 0, e;
5459 e = get_attr_vsn(oldpath, &oldatts, &oldvsn);
5461 errno = map_errno(e);
5464 if (oldatts & FILE_ATTRIBUTE_REPARSE_POINT) {
5465 HANDLE fh = open_special(oldpath, 0, 0);
5466 if (fh == INVALID_HANDLE_VALUE) {
5468 if (e == ERROR_CANT_RESOLVE_FILENAME) {
5475 get_attr_vsn(newpath, &newatts, &newvsn);
5478 if (newatts != (DWORD)-1 && newatts & FILE_ATTRIBUTE_READONLY)
5479 SetFileAttributesW(newpath, newatts & ~ FILE_ATTRIBUTE_READONLY);
5481 if (!MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED))
5485 DWORD e = GetLastError();
5486 if ((e == ERROR_ACCESS_DENIED) && (oldatts & FILE_ATTRIBUTE_DIRECTORY) &&
5490 errno = map_errno(e);
5493 SetFileAttributesW(newpath, oldatts);
5501 rb_w32_urename(
const char *from,
const char *to)
5507 if (!(wfrom = utf8_to_wstr(from, NULL)))
5509 if (!(wto = utf8_to_wstr(to, NULL))) {
5513 ret = wrename(wfrom, wto);
5521 rb_w32_rename(
const char *from,
const char *to)
5527 if (!(wfrom = filecp_to_wstr(from, NULL)))
5529 if (!(wto = filecp_to_wstr(to, NULL))) {
5533 ret = wrename(wfrom, wto);
5541 isUNCRoot(
const WCHAR *path)
5543 if (path[0] == L
'\\' && path[1] == L
'\\') {
5544 const WCHAR *p = path + 2;
5545 if (p[0] == L
'?' && p[1] == L
'\\') {
5553 for (p++; *p; p++) {
5557 if (!p[0] || !p[1] || (p[1] == L
'.' && !p[2]))
5564 #define COPY_STAT(src, dest, size_cast) do { \
5565 (dest).st_dev = (src).st_dev; \
5566 (dest).st_ino = (src).st_ino; \
5567 (dest).st_mode = (src).st_mode; \
5568 (dest).st_nlink = (src).st_nlink; \
5569 (dest).st_uid = (src).st_uid; \
5570 (dest).st_gid = (src).st_gid; \
5571 (dest).st_rdev = (src).st_rdev; \
5572 (dest).st_size = size_cast(src).st_size; \
5573 (dest).st_atime = (src).st_atime; \
5574 (dest).st_mtime = (src).st_mtime; \
5575 (dest).st_ctime = (src).st_ctime; \
5578 static time_t filetime_to_unixtime(
const FILETIME *ft);
5579 static long filetime_to_nsec(
const FILETIME *ft);
5580 static WCHAR *name_for_stat(WCHAR *buf,
const WCHAR *path);
5581 static DWORD stati128_handle(HANDLE h,
struct stati128 *st);
5586 rb_w32_fstat(
int fd,
struct stat *st)
5588 BY_HANDLE_FILE_INFORMATION info;
5589 int ret = fstat(fd, st);
5591 if (ret)
return ret;
5592 if (GetEnvironmentVariableW(L
"TZ", NULL, 0) == 0 && GetLastError() == ERROR_ENVVAR_NOT_FOUND)
return ret;
5593 if (GetFileInformationByHandle((HANDLE)_get_osfhandle(fd), &info)) {
5594 st->st_atime = filetime_to_unixtime(&info.ftLastAccessTime);
5595 st->st_mtime = filetime_to_unixtime(&info.ftLastWriteTime);
5596 st->st_ctime = filetime_to_unixtime(&info.ftCreationTime);
5603 rb_w32_fstati128(
int fd,
struct stati128 *st)
5606 int ret = fstat(fd, &tmp);
5608 if (ret)
return ret;
5609 COPY_STAT(tmp, *st, +);
5610 stati128_handle((HANDLE)_get_osfhandle(fd), st);
5614 #if !defined FILE_INVALID_FILE_ID && !defined __MINGW32__
5616 BYTE Identifier[16];
5620 #if !defined(_WIN32_WINNT_WIN8) || _WIN32_WINNT < 0x602
5621 #define FileIdInfo 0x12
5632 return GetFileInformationByHandleEx(h, FileIdInfo,
id,
sizeof(*
id));
5637 stati128_handle(HANDLE h,
struct stati128 *st)
5639 BY_HANDLE_FILE_INFORMATION info;
5640 DWORD attr = (DWORD)-1;
5642 if (GetFileInformationByHandle(h, &info)) {
5644 st->st_size = ((__int64)info.nFileSizeHigh << 32) | info.nFileSizeLow;
5645 st->st_atime = filetime_to_unixtime(&info.ftLastAccessTime);
5646 st->st_atimensec = filetime_to_nsec(&info.ftLastAccessTime);
5647 st->st_mtime = filetime_to_unixtime(&info.ftLastWriteTime);
5648 st->st_mtimensec = filetime_to_nsec(&info.ftLastWriteTime);
5649 st->st_ctime = filetime_to_unixtime(&info.ftCreationTime);
5650 st->st_ctimensec = filetime_to_nsec(&info.ftCreationTime);
5651 st->st_nlink = info.nNumberOfLinks;
5652 attr = info.dwFileAttributes;
5653 if (get_ino(h, &fii)) {
5654 st->st_ino = *((
unsigned __int64 *)&fii.FileId);
5655 st->st_inohigh = *((__int64 *)&fii.FileId + 1);
5658 st->st_ino = ((__int64)info.nFileIndexHigh << 32) | info.nFileIndexLow;
5667 filetime_to_unixtime(
const FILETIME *ft)
5670 time_t t = filetime_split(ft, &subsec);
5672 if (t < 0)
return 0;
5678 filetime_to_nsec(
const FILETIME *ft)
5681 tmp.LowPart = ft->dwLowDateTime;
5682 tmp.HighPart = ft->dwHighDateTime;
5683 return (
long)(tmp.QuadPart % 10000000) * 100;
5688 fileattr_to_unixmode(DWORD attr,
const WCHAR *path,
unsigned mode)
5690 if (attr & FILE_ATTRIBUTE_READONLY) {
5694 mode |= S_IREAD | S_IWRITE | S_IWUSR;
5697 if (mode & S_IFMT) {
5700 else if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
5704 else if (attr & FILE_ATTRIBUTE_DIRECTORY) {
5705 mode |= S_IFDIR | S_IEXEC;
5711 if (path && (mode & S_IFREG)) {
5712 const WCHAR *end = path + lstrlenW(path);
5713 while (path < end) {
5714 end = CharPrevW(path, end);
5716 if ((_wcsicmp(end, L
".bat") == 0) ||
5717 (_wcsicmp(end, L
".cmd") == 0) ||
5718 (_wcsicmp(end, L
".com") == 0) ||
5719 (_wcsicmp(end, L
".exe") == 0)) {
5724 if (!iswalnum(*end))
break;
5728 mode |= (mode & 0500) >> 3;
5729 mode |= (mode & 0500) >> 6;
5736 check_valid_dir(
const WCHAR *path)
5738 WIN32_FIND_DATAW fd;
5740 WCHAR full[PATH_MAX];
5746 if (!(p = wcsstr(path, L
"...")))
5748 q = p + wcsspn(p, L
".");
5749 if ((p == path || wcschr(L
":/\\", *(p - 1))) &&
5750 (!*q || wcschr(L
":/\\", *q))) {
5757 if (!GetFullPathNameW(path,
sizeof(full) /
sizeof(WCHAR), full, &dmy)) {
5758 errno = map_errno(GetLastError());
5761 if (full[1] == L
':' && !full[3] && GetDriveTypeW(full) != DRIVE_NO_ROOT_DIR)
5764 fh = open_dir_handle(path, &fd);
5765 if (fh == INVALID_HANDLE_VALUE)
5773 stat_by_find(
const WCHAR *path,
struct stati128 *st)
5776 WIN32_FIND_DATAW wfd;
5779 h = FindFirstFileW(path, &wfd);
5780 if (h == INVALID_HANDLE_VALUE) {
5781 errno = map_errno(GetLastError());
5785 st->st_mode = fileattr_to_unixmode(wfd.dwFileAttributes, path, 0);
5786 st->st_atime = filetime_to_unixtime(&wfd.ftLastAccessTime);
5787 st->st_atimensec = filetime_to_nsec(&wfd.ftLastAccessTime);
5788 st->st_mtime = filetime_to_unixtime(&wfd.ftLastWriteTime);
5789 st->st_mtimensec = filetime_to_nsec(&wfd.ftLastWriteTime);
5790 st->st_ctime = filetime_to_unixtime(&wfd.ftCreationTime);
5791 st->st_ctimensec = filetime_to_nsec(&wfd.ftCreationTime);
5792 st->st_size = ((__int64)wfd.nFileSizeHigh << 32) | wfd.nFileSizeLow;
5799 path_drive(
const WCHAR *path)
5801 return (iswalpha(path[0]) && path[1] == L
':') ?
5802 towupper(path[0]) - L
'A' : _getdrive() - 1;
5807 winnt_stat(
const WCHAR *path,
struct stati128 *st, BOOL lstat)
5809 DWORD flags = lstat ? FILE_FLAG_OPEN_REPARSE_POINT : 0;
5811 WCHAR finalname[PATH_MAX];
5814 memset(st, 0,
sizeof(*st));
5815 f = open_special(path, 0, flags);
5816 open_error = GetLastError();
5817 if (f == INVALID_HANDLE_VALUE && !lstat) {
5819 FILE_ATTRIBUTE_TAG_INFO attr_info;
5822 f = open_special(path, 0, FILE_FLAG_OPEN_REPARSE_POINT);
5823 e = GetFileInformationByHandleEx(f, FileAttributeTagInfo,
5824 &attr_info,
sizeof(attr_info));
5825 if (!e || attr_info.ReparseTag != IO_REPARSE_TAG_AF_UNIX) {
5827 f = INVALID_HANDLE_VALUE;
5830 if (f != INVALID_HANDLE_VALUE) {
5831 DWORD attr = stati128_handle(f, st);
5832 const DWORD
len = GetFinalPathNameByHandleW(f, finalname, numberof(finalname), 0);
5834 switch (GetFileType(f)) {
5835 case FILE_TYPE_CHAR:
5838 case FILE_TYPE_PIPE:
5842 if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
5843 FILE_ATTRIBUTE_TAG_INFO attr_info;
5846 e = GetFileInformationByHandleEx(f, FileAttributeTagInfo,
5847 &attr_info,
sizeof(attr_info));
5848 if (e && attr_info.ReparseTag == IO_REPARSE_TAG_AF_UNIX) {
5852 else if (rb_w32_reparse_symlink_p(path)) {
5855 mode |= S_IFLNK | S_IEXEC;
5858 mode |= S_IFDIR | S_IEXEC;
5863 if (attr & FILE_ATTRIBUTE_DIRECTORY) {
5864 if (check_valid_dir(path))
return -1;
5866 st->st_mode = fileattr_to_unixmode(attr, path, mode);
5868 finalname[min(
len, numberof(finalname)-1)] = L
'\0';
5870 if (wcsncmp(path, namespace_prefix, numberof(namespace_prefix)) == 0)
5871 path += numberof(namespace_prefix);
5875 if ((open_error == ERROR_FILE_NOT_FOUND) || (open_error == ERROR_INVALID_NAME)
5876 || (open_error == ERROR_PATH_NOT_FOUND || (open_error == ERROR_BAD_NETPATH))) {
5877 errno = map_errno(open_error);
5881 if (stat_by_find(path, st))
return -1;
5884 st->st_dev = st->st_rdev = path_drive(path);
5891 rb_w32_stat(
const char *path,
struct stat *st)
5895 if (w32_stati128(path, &tmp, filecp(), FALSE))
return -1;
5896 COPY_STAT(tmp, *st, (_off_t));
5902 wstati128(
const WCHAR *path,
struct stati128 *st, BOOL lstat)
5912 size = lstrlenW(path) + 2;
5914 if (!(path = name_for_stat(buf1, path)))
5916 ret = winnt_stat(path, st, lstat);
5925 name_for_stat(WCHAR *buf1,
const WCHAR *path)
5931 for (p = path, s = buf1; *p; p++, s++) {
5939 if (!
len || L
'\"' == *(--s)) {
5943 end = buf1 +
len - 1;
5945 if (isUNCRoot(buf1)) {
5948 else if (*end != L
'\\')
5949 lstrcatW(buf1, L
"\\");
5951 else if (*end == L
'\\' || (buf1 + 1 == end && *end == L
':'))
5952 lstrcatW(buf1, L
".");
5959 rb_w32_ustati128(
const char *path,
struct stati128 *st)
5961 return w32_stati128(path, st, CP_UTF8, FALSE);
5966 rb_w32_stati128(
const char *path,
struct stati128 *st)
5968 return w32_stati128(path, st, filecp(), FALSE);
5973 w32_stati128(
const char *path,
struct stati128 *st, UINT cp, BOOL lstat)
5978 if (!(wpath = mbstr_to_wstr(cp, path, -1, NULL)))
5980 ret = wstati128(wpath, st, lstat);
5987 rb_w32_ulstati128(
const char *path,
struct stati128 *st)
5989 return w32_stati128(path, st, CP_UTF8, TRUE);
5994 rb_w32_lstati128(
const char *path,
struct stati128 *st)
5996 return w32_stati128(path, st, filecp(), TRUE);
6001 rb_w32_lseek(
int fd, rb_off_t ofs,
int whence)
6003 SOCKET sock = TO_SOCKET(fd);
6004 if (is_socket(sock) || is_pipe(sock)) {
6008 return _lseeki64(fd, ofs, whence);
6013 w32_access(
const char *path,
int mode, UINT cp)
6016 if (w32_stati128(path, &stat, cp, FALSE) != 0)
6019 if ((stat.st_mode & mode) != mode) {
6028 rb_w32_access(
const char *path,
int mode)
6030 return w32_access(path, mode, filecp());
6035 rb_w32_uaccess(
const char *path,
int mode)
6037 return w32_access(path, mode, CP_UTF8);
6042 rb_chsize(HANDLE h, rb_off_t size)
6044 long upos, lpos, usize, lsize;
6048 if ((lpos = SetFilePointer(h, 0, (upos = 0, &upos), SEEK_CUR)) == -1L &&
6049 (e = GetLastError())) {
6050 errno = map_errno(e);
6053 usize = (long)(size >> 32);
6055 if (SetFilePointer(h, lsize, &usize, SEEK_SET) == (DWORD)-1L &&
6056 (e = GetLastError())) {
6057 errno = map_errno(e);
6059 else if (!SetEndOfFile(h)) {
6060 errno = map_errno(GetLastError());
6065 SetFilePointer(h, lpos, &upos, SEEK_SET);
6071 w32_truncate(
const char *path, rb_off_t length, UINT cp)
6077 if (!(wpath = mbstr_to_wstr(cp, path, -1, NULL)))
6079 h = CreateFileW(wpath, GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
6080 if (h == INVALID_HANDLE_VALUE) {
6081 errno = map_errno(GetLastError());
6086 ret = rb_chsize(h, length);
6093 rb_w32_utruncate(
const char *path, rb_off_t length)
6095 return w32_truncate(path, length, CP_UTF8);
6100 rb_w32_truncate(
const char *path, rb_off_t length)
6102 return w32_truncate(path, length, filecp());
6107 rb_w32_ftruncate(
int fd, rb_off_t length)
6111 h = (HANDLE)_get_osfhandle(fd);
6112 if (h == (HANDLE)-1)
return -1;
6113 return rb_chsize(h, length);
6118 filetime_to_clock(FILETIME *ft)
6120 __int64 qw = ft->dwHighDateTime;
6122 qw |= ft->dwLowDateTime;
6129 rb_w32_times(
struct tms *tmbuf)
6131 FILETIME create, exit, kernel, user;
6133 if (GetProcessTimes(GetCurrentProcess(),&create, &exit, &kernel, &user)) {
6134 tmbuf->tms_utime = filetime_to_clock(&user);
6135 tmbuf->tms_stime = filetime_to_clock(&kernel);
6136 tmbuf->tms_cutime = 0;
6137 tmbuf->tms_cstime = 0;
6140 tmbuf->tms_utime = clock();
6141 tmbuf->tms_stime = 0;
6142 tmbuf->tms_cutime = 0;
6143 tmbuf->tms_cstime = 0;
6150 #define yield_once() Sleep(0)
6151 #define yield_until(condition) do yield_once(); while (!(condition))
6160 uintptr_t (*func)(uintptr_t
self,
int argc, uintptr_t* argv);
6168 call_asynchronous(PVOID argp)
6172 arg->stackaddr = &argp;
6173 ret = (DWORD)arg->func(arg->self, arg->argc, arg->argv);
6174 arg->errnum =
errno;
6180 rb_w32_asynchronize(asynchronous_func_t func, uintptr_t
self,
6181 int argc, uintptr_t* argv, uintptr_t intrval)
6184 BOOL interrupted = FALSE;
6190 arg.stackaddr = NULL;
6197 thr = CreateThread(NULL, 0, call_asynchronous, &arg, 0, &val);
6200 yield_until(arg.stackaddr);
6202 if (rb_w32_wait_events_blocking(&thr, 1, INFINITE) != WAIT_OBJECT_0) {
6205 if (TerminateThread(thr, intrval)) {
6210 GetExitCodeThread(thr, &val);
6215 MEMORY_BASIC_INFORMATION m;
6217 memset(&m, 0,
sizeof(m));
6218 if (!VirtualQuery(arg.stackaddr, &m,
sizeof(m))) {
6219 Debug(fprintf(stderr,
"couldn't get stack base:%p:%d\n",
6220 arg.stackaddr, GetLastError()));
6222 else if (!VirtualFree(m.AllocationBase, 0, MEM_RELEASE)) {
6223 Debug(fprintf(stderr,
"couldn't release stack:%p:%d\n",
6224 m.AllocationBase, GetLastError()));
6235 rb_fatal(
"failed to launch waiter thread:%ld", GetLastError());
6243 rb_w32_get_environ(
void)
6245 WCHAR *envtop, *env;
6246 char **myenvtop, **myenv;
6259 envtop = GetEnvironmentStringsW();
6260 for (env = envtop, num = 0; *env; env += lstrlenW(env) + 1)
6261 if (*env !=
'=') num++;
6263 myenvtop = (
char **)malloc(
sizeof(
char *) * (num + 1));
6264 for (env = envtop, myenv = myenvtop; *env; env += lstrlenW(env) + 1) {
6266 if (!(*myenv = wstr_to_utf8(env, NULL))) {
6273 FreeEnvironmentStringsW(envtop);
6280 rb_w32_free_environ(
char **env)
6284 while (*t) free(*t++);
6292 return GetCurrentProcessId();
6298 rb_w32_getppid(
void)
6300 typedef long (WINAPI query_func)(HANDLE, int,
void *, ULONG, ULONG *);
6301 static query_func *pNtQueryInformationProcess = (query_func *)-1;
6304 if (pNtQueryInformationProcess == (query_func *)-1)
6305 pNtQueryInformationProcess = (query_func *)get_proc_address(
"ntdll.dll",
"NtQueryInformationProcess", NULL);
6306 if (pNtQueryInformationProcess) {
6309 void* PebBaseAddress;
6310 uintptr_t AffinityMask;
6311 uintptr_t BasePriority;
6312 uintptr_t UniqueProcessId;
6313 uintptr_t ParentProcessId;
6316 long ret = pNtQueryInformationProcess(GetCurrentProcess(), 0, &pbi,
sizeof(pbi), &
len);
6318 ppid = pbi.ParentProcessId;
6325 STATIC_ASSERT(std_handle, (STD_OUTPUT_HANDLE-STD_INPUT_HANDLE)==(STD_ERROR_HANDLE-STD_OUTPUT_HANDLE));
6328 #define set_new_std_handle(newfd, handle) do { \
6329 if ((unsigned)(newfd) > 2) break; \
6330 SetStdHandle(STD_INPUT_HANDLE+(STD_OUTPUT_HANDLE-STD_INPUT_HANDLE)*(newfd), \
6333 #define set_new_std_fd(newfd) set_new_std_handle(newfd, (HANDLE)rb_w32_get_osfhandle(newfd))
6337 rb_w32_dup2(
int oldfd,
int newfd)
6341 if (oldfd == newfd)
return newfd;
6342 ret = dup2(oldfd, newfd);
6343 if (ret < 0)
return ret;
6344 set_new_std_fd(newfd);
6350 rb_w32_uopen(
const char *file,
int oflag, ...)
6357 va_start(arg, oflag);
6358 pmode = va_arg(arg,
int);
6361 if (!(wfile = utf8_to_wstr(file, NULL)))
6363 ret = w32_wopen(wfile, oflag, pmode);
6370 check_if_wdir(
const WCHAR *wfile)
6372 DWORD attr = GetFileAttributesW(wfile);
6373 if (attr == (DWORD)-1L ||
6374 !(attr & FILE_ATTRIBUTE_DIRECTORY) ||
6375 check_valid_dir(wfile)) {
6384 rb_w32_open(
const char *file,
int oflag, ...)
6391 va_start(arg, oflag);
6392 pmode = va_arg(arg,
int);
6395 if (!(wfile = filecp_to_wstr(file, NULL)))
6397 ret = w32_wopen(wfile, oflag, pmode);
6404 rb_w32_wopen(
const WCHAR *file,
int oflag, ...)
6408 if (oflag & O_CREAT) {
6410 va_start(arg, oflag);
6411 pmode = va_arg(arg,
int);
6415 return w32_wopen(file, oflag, pmode);
6419 w32_wopen(
const WCHAR *file,
int oflag,
int pmode)
6425 DWORD attr = FILE_ATTRIBUTE_NORMAL;
6426 SECURITY_ATTRIBUTES sec;
6430 share_delete = oflag & O_SHARE_DELETE ? FILE_SHARE_DELETE : 0;
6431 oflag &= ~O_SHARE_DELETE;
6432 if ((oflag & O_TEXT) || !(oflag & O_BINARY)) {
6433 fd = _wopen(file, oflag, pmode);
6437 check_if_wdir(file);
6440 errno = map_errno(GetLastError());
6447 sec.nLength =
sizeof(sec);
6448 sec.lpSecurityDescriptor = NULL;
6449 if (oflag & O_NOINHERIT) {
6450 sec.bInheritHandle = FALSE;
6451 flags |= FNOINHERIT;
6454 sec.bInheritHandle = TRUE;
6456 oflag &= ~O_NOINHERIT;
6459 oflag &= ~(O_BINARY | O_TEXT);
6461 switch (oflag & (O_RDWR | O_RDONLY | O_WRONLY)) {
6463 access = GENERIC_READ | GENERIC_WRITE;
6466 access = GENERIC_READ;
6469 access = GENERIC_WRITE;
6475 oflag &= ~(O_RDWR | O_RDONLY | O_WRONLY);
6477 switch (oflag & (O_CREAT | O_EXCL | O_TRUNC)) {
6479 create = OPEN_ALWAYS;
6483 create = OPEN_EXISTING;
6485 case O_CREAT | O_EXCL:
6486 case O_CREAT | O_EXCL | O_TRUNC:
6487 create = CREATE_NEW;
6490 case O_TRUNC | O_EXCL:
6491 create = TRUNCATE_EXISTING;
6493 case O_CREAT | O_TRUNC:
6494 create = CREATE_ALWAYS;
6500 if (oflag & O_CREAT) {
6502 if (!(pmode & S_IWRITE))
6503 attr = FILE_ATTRIBUTE_READONLY;
6505 oflag &= ~(O_CREAT | O_EXCL | O_TRUNC);
6507 if (oflag & O_TEMPORARY) {
6508 attr |= FILE_FLAG_DELETE_ON_CLOSE;
6511 oflag &= ~O_TEMPORARY;
6513 if (oflag & _O_SHORT_LIVED)
6514 attr |= FILE_ATTRIBUTE_TEMPORARY;
6515 oflag &= ~_O_SHORT_LIVED;
6517 switch (oflag & (O_SEQUENTIAL | O_RANDOM)) {
6521 attr |= FILE_FLAG_SEQUENTIAL_SCAN;
6524 attr |= FILE_FLAG_RANDOM_ACCESS;
6530 oflag &= ~(O_SEQUENTIAL | O_RANDOM);
6532 if (oflag & ~O_APPEND) {
6539 h = CreateFile(
"NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
6540 fd = _open_osfhandle((intptr_t)h, 0);
6548 rb_acrt_lowio_lock_fh(fd);
6549 _set_osfhnd(fd, (intptr_t)INVALID_HANDLE_VALUE);
6550 _set_osflags(fd, 0);
6552 h = CreateFileW(file, access, FILE_SHARE_READ | FILE_SHARE_WRITE | share_delete, &sec, create, attr, NULL);
6553 if (h == INVALID_HANDLE_VALUE) {
6554 DWORD e = GetLastError();
6555 if (e != ERROR_ACCESS_DENIED || !check_if_wdir(file))
6556 errno = map_errno(e);
6557 rb_acrt_lowio_unlock_fh(fd);
6562 switch (GetFileType(h)) {
6563 case FILE_TYPE_CHAR:
6566 case FILE_TYPE_PIPE:
6569 case FILE_TYPE_UNKNOWN:
6570 errno = map_errno(GetLastError());
6572 rb_acrt_lowio_unlock_fh(fd);
6576 if (!(flags & (FDEV | FPIPE)) && (oflag & O_APPEND))
6579 _set_osfhnd(fd, (intptr_t)h);
6580 _set_osflags(fd, flags | FOPEN);
6582 rb_acrt_lowio_unlock_fh(fd);
6592 rb_w32_fclose(
FILE *fp)
6594 int fd = fileno(fp);
6595 SOCKET sock = TO_SOCKET(fd);
6596 int save_errno =
errno;
6598 if (fflush(fp))
return -1;
6599 if (!is_socket(sock)) {
6600 UnlockFile((HANDLE)sock, 0, 0, LK_LEN, LK_LEN);
6603 _set_osfhnd(fd, (SOCKET)INVALID_HANDLE_VALUE);
6606 if (closesocket(sock) == SOCKET_ERROR) {
6607 errno = map_errno(WSAGetLastError());
6615 rb_w32_pipe(
int fds[2])
6617 static long serial = 0;
6618 static const char prefix[] =
"\\\\.\\pipe\\ruby";
6620 width_of_prefix = (int)
sizeof(prefix) - 1,
6621 width_of_pid = (int)
sizeof(rb_pid_t) * 2,
6622 width_of_serial = (int)
sizeof(serial) * 2,
6623 width_of_ids = width_of_pid + 1 + width_of_serial + 1
6625 char name[
sizeof(prefix) + width_of_ids];
6626 SECURITY_ATTRIBUTES sec;
6627 HANDLE hRead, hWrite, h;
6628 int fdRead, fdWrite;
6631 memcpy(name, prefix, width_of_prefix);
6632 snprintf(name + width_of_prefix, width_of_ids,
"%.*"PRI_PIDT_PREFIX"x-%.*lx",
6633 width_of_pid, rb_w32_getpid(), width_of_serial, InterlockedIncrement(&serial)-1);
6635 sec.nLength =
sizeof(sec);
6636 sec.lpSecurityDescriptor = NULL;
6637 sec.bInheritHandle = FALSE;
6640 hRead = CreateNamedPipe(name, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
6641 0, 2, 65536, 65536, 0, &sec);
6643 if (hRead == INVALID_HANDLE_VALUE) {
6644 DWORD err = GetLastError();
6645 if (err == ERROR_PIPE_BUSY)
6648 errno = map_errno(GetLastError());
6653 hWrite = CreateFile(name, GENERIC_READ | GENERIC_WRITE, 0, &sec,
6654 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
6656 if (hWrite == INVALID_HANDLE_VALUE) {
6657 errno = map_errno(GetLastError());
6664 h = CreateFile(
"NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
6665 fdRead = _open_osfhandle((intptr_t)h, 0);
6669 CloseHandle(hWrite);
6675 rb_acrt_lowio_lock_fh(fdRead);
6676 _set_osfhnd(fdRead, (intptr_t)hRead);
6677 _set_osflags(fdRead, FOPEN | FPIPE | FNOINHERIT);
6678 rb_acrt_lowio_unlock_fh(fdRead);
6684 h = CreateFile(
"NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
6685 fdWrite = _open_osfhandle((intptr_t)h, 0);
6687 if (fdWrite == -1) {
6689 CloseHandle(hWrite);
6693 rb_acrt_lowio_lock_fh(fdWrite);
6694 _set_osfhnd(fdWrite, (intptr_t)hWrite);
6695 _set_osflags(fdWrite, FOPEN | FPIPE | FNOINHERIT);
6696 rb_acrt_lowio_unlock_fh(fdWrite);
6699 rb_w32_close(fdRead);
6711 console_emulator_p(
void)
6716 const void *
const func = WriteConsoleW;
6718 MEMORY_BASIC_INFORMATION m;
6720 memset(&m, 0,
sizeof(m));
6721 if (!VirtualQuery(func, &m,
sizeof(m))) {
6724 k = GetModuleHandle(
"kernel32.dll");
6725 if (!k)
return FALSE;
6726 return (HMODULE)m.AllocationBase != k;
6732 constat_handle(HANDLE h)
6736 thread_exclusive(conlist) {
6738 if (console_emulator_p()) {
6739 conlist = conlist_disabled;
6742 conlist = st_init_numtable();
6743 install_vm_exit_handler();
6745 else if (conlist == conlist_disabled) {
6748 if (st_lookup(conlist, (st_data_t)h, &data)) {
6752 CONSOLE_SCREEN_BUFFER_INFO csbi;
6754 p->vt100.state = constat_init;
6755 p->vt100.attr = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED;
6756 p->vt100.reverse = 0;
6757 p->vt100.saved.X = p->vt100.saved.Y = 0;
6758 if (GetConsoleScreenBufferInfo(h, &csbi)) {
6759 p->vt100.attr = csbi.wAttributes;
6761 st_insert(conlist, (st_data_t)h, (st_data_t)p);
6769 constat_reset(HANDLE h)
6773 thread_exclusive(conlist) {
6774 if (!conlist || conlist == conlist_disabled)
continue;
6775 if (!st_lookup(conlist, (st_data_t)h, &data))
continue;
6777 p->vt100.state = constat_init;
6781 #define FOREGROUND_MASK (FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY)
6782 #define BACKGROUND_MASK (BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_INTENSITY)
6784 #define constat_attr_color_reverse(attr) \
6785 ((attr) & ~(FOREGROUND_MASK | BACKGROUND_MASK)) | \
6786 (((attr) & FOREGROUND_MASK) << 4) | \
6787 (((attr) & BACKGROUND_MASK) >> 4)
6791 constat_attr(
int count,
const int *seq, WORD attr, WORD default_attr,
int *reverse)
6796 if (!count)
return attr;
6797 if (rev) attr = constat_attr_color_reverse(attr);
6798 bold = attr & FOREGROUND_INTENSITY;
6799 attr &= ~(FOREGROUND_INTENSITY | BACKGROUND_INTENSITY);
6801 while (count-- > 0) {
6804 attr = default_attr;
6809 bold = FOREGROUND_INTENSITY;
6812 #ifndef COMMON_LVB_UNDERSCORE
6813 #define COMMON_LVB_UNDERSCORE 0x8000
6815 attr |= COMMON_LVB_UNDERSCORE;
6822 attr &= ~(FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED);
6826 attr = (attr & ~(FOREGROUND_BLUE | FOREGROUND_GREEN)) | FOREGROUND_RED;
6830 attr = (attr & ~(FOREGROUND_BLUE | FOREGROUND_RED)) | FOREGROUND_GREEN;
6834 attr = (attr & ~FOREGROUND_BLUE) | FOREGROUND_GREEN | FOREGROUND_RED;
6838 attr = (attr & ~(FOREGROUND_GREEN | FOREGROUND_RED)) | FOREGROUND_BLUE;
6842 attr = (attr & ~FOREGROUND_GREEN) | FOREGROUND_BLUE | FOREGROUND_RED;
6846 attr = (attr & ~FOREGROUND_RED) | FOREGROUND_BLUE | FOREGROUND_GREEN;
6850 attr |= FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED;
6854 attr &= ~(BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED);
6857 attr = (attr & ~(BACKGROUND_BLUE | BACKGROUND_GREEN)) | BACKGROUND_RED;
6860 attr = (attr & ~(BACKGROUND_BLUE | BACKGROUND_RED)) | BACKGROUND_GREEN;
6863 attr = (attr & ~BACKGROUND_BLUE) | BACKGROUND_GREEN | BACKGROUND_RED;
6866 attr = (attr & ~(BACKGROUND_GREEN | BACKGROUND_RED)) | BACKGROUND_BLUE;
6869 attr = (attr & ~BACKGROUND_GREEN) | BACKGROUND_BLUE | BACKGROUND_RED;
6872 attr = (attr & ~BACKGROUND_RED) | BACKGROUND_BLUE | BACKGROUND_GREEN;
6875 attr |= BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED;
6880 if (rev) attr = constat_attr_color_reverse(attr);
6887 constat_clear(HANDLE handle, WORD attr, DWORD
len, COORD pos)
6891 FillConsoleOutputAttribute(handle, attr,
len, pos, &written);
6892 FillConsoleOutputCharacterW(handle, L
' ',
len, pos, &written);
6897 constat_apply(HANDLE handle,
struct constat *s, WCHAR w)
6899 CONSOLE_SCREEN_BUFFER_INFO csbi;
6900 const int *seq = s->vt100.seq;
6901 int count = s->vt100.state;
6905 if (!GetConsoleScreenBufferInfo(handle, &csbi))
return;
6906 arg0 = (count > 0 && seq[0] > 0);
6907 if (arg0) arg1 = seq[0];
6910 SetConsoleTextAttribute(handle, constat_attr(count, seq, csbi.wAttributes, s->vt100.attr, &s->vt100.reverse));
6913 csbi.dwCursorPosition.X = 0;
6915 csbi.dwCursorPosition.Y -= arg1;
6916 if (csbi.dwCursorPosition.Y < csbi.srWindow.Top)
6917 csbi.dwCursorPosition.Y = csbi.srWindow.Top;
6918 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
6921 csbi.dwCursorPosition.X = 0;
6924 csbi.dwCursorPosition.Y += arg1;
6925 if (csbi.dwCursorPosition.Y > csbi.srWindow.Bottom)
6926 csbi.dwCursorPosition.Y = csbi.srWindow.Bottom;
6927 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
6930 csbi.dwCursorPosition.X += arg1;
6931 if (csbi.dwCursorPosition.X >= csbi.srWindow.Right)
6932 csbi.dwCursorPosition.X = csbi.srWindow.Right;
6933 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
6936 csbi.dwCursorPosition.X -= arg1;
6937 if (csbi.dwCursorPosition.X < csbi.srWindow.Left)
6938 csbi.dwCursorPosition.X = csbi.srWindow.Left;
6939 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
6943 arg1 += csbi.srWindow.Left;
6944 if (arg1 > csbi.srWindow.Right)
6945 arg1 = csbi.srWindow.Right;
6946 csbi.dwCursorPosition.X = arg1;
6947 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
6950 arg1 += csbi.srWindow.Top;
6951 if (arg1 > csbi.srWindow.Bottom)
6952 arg1 = csbi.srWindow.Bottom;
6953 csbi.dwCursorPosition.Y = arg1;
6954 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
6958 pos.Y = arg1 + csbi.srWindow.Top - 1;
6959 if (pos.Y > csbi.srWindow.Bottom) pos.Y = csbi.srWindow.Bottom;
6960 if (count < 2 || (arg1 = seq[1]) <= 0) arg1 = 1;
6961 pos.X = arg1 + csbi.srWindow.Left - 1;
6962 if (pos.X > csbi.srWindow.Right) pos.X = csbi.srWindow.Right;
6963 SetConsoleCursorPosition(handle, pos);
6966 switch (arg0 ? arg1 : 0) {
6968 constat_clear(handle, csbi.wAttributes,
6969 (csbi.dwSize.X * (csbi.srWindow.Bottom - csbi.dwCursorPosition.Y + 1)
6970 - csbi.dwCursorPosition.X),
6971 csbi.dwCursorPosition);
6975 pos.Y = csbi.srWindow.Top;
6976 constat_clear(handle, csbi.wAttributes,
6977 (csbi.dwSize.X * (csbi.dwCursorPosition.Y - csbi.srWindow.Top)
6978 + csbi.dwCursorPosition.X + 1),
6983 pos.Y = csbi.srWindow.Top;
6984 constat_clear(handle, csbi.wAttributes,
6985 (csbi.dwSize.X * (csbi.srWindow.Bottom - csbi.srWindow.Top + 1)),
6991 constat_clear(handle, csbi.wAttributes,
6992 (csbi.dwSize.X * csbi.dwSize.Y),
6998 switch (arg0 ? arg1 : 0) {
7000 constat_clear(handle, csbi.wAttributes,
7001 (csbi.dwSize.X - csbi.dwCursorPosition.X),
7002 csbi.dwCursorPosition);
7006 pos.Y = csbi.dwCursorPosition.Y;
7007 constat_clear(handle, csbi.wAttributes,
7008 csbi.dwCursorPosition.X + 1, pos);
7012 pos.Y = csbi.dwCursorPosition.Y;
7013 constat_clear(handle, csbi.wAttributes,
7014 csbi.dwSize.X, pos);
7019 s->vt100.saved = csbi.dwCursorPosition;
7022 SetConsoleCursorPosition(handle, s->vt100.saved);
7025 if (count >= 2 && seq[0] == -1 && seq[1] == 25) {
7026 CONSOLE_CURSOR_INFO cci;
7027 GetConsoleCursorInfo(handle, &cci);
7028 cci.bVisible = TRUE;
7029 SetConsoleCursorInfo(handle, &cci);
7033 if (count >= 2 && seq[0] == -1 && seq[1] == 25) {
7034 CONSOLE_CURSOR_INFO cci;
7035 GetConsoleCursorInfo(handle, &cci);
7036 cci.bVisible = FALSE;
7037 SetConsoleCursorInfo(handle, &cci);
7045 static const long MAXSIZE_CONSOLE_WRITING = 31366;
7049 constat_parse(HANDLE h,
struct constat *s,
const WCHAR **ptrp,
long *lenp)
7051 const WCHAR *
ptr = *ptrp;
7052 long rest,
len = *lenp;
7056 rest = *lenp -
len - 1;
7057 if (s->vt100.state == constat_esc) {
7060 s->vt100.state = constat_init;
7061 if (
len > 0 && *
ptr != L
'[')
continue;
7062 s->vt100.state = constat_esc;
7064 else if (s->vt100.state == constat_esc) {
7067 s->vt100.state = constat_init;
7070 rest = *lenp -
len - 1;
7071 if (rest > 0) --rest;
7072 s->vt100.state = constat_seq;
7073 s->vt100.seq[0] = 0;
7075 else if (s->vt100.state >= constat_seq) {
7076 if (wc >= L
'0' && wc <= L
'9') {
7077 if (s->vt100.state < (
int)numberof(s->vt100.seq)) {
7078 int *seq = &s->vt100.seq[s->vt100.state];
7079 *seq = (*seq * 10) + (wc - L
'0');
7082 else if (s->vt100.state == constat_seq && s->vt100.seq[0] == 0 && wc == L
'?') {
7083 s->vt100.seq[s->vt100.state++] = -1;
7087 if (++s->vt100.state < (
int)numberof(s->vt100.seq)) {
7088 s->vt100.seq[s->vt100.state] = 0;
7091 s->vt100.state = (int)numberof(s->vt100.seq);
7095 constat_apply(h, s, wc);
7096 s->vt100.state = constat_init;
7101 else if ((rest = *lenp -
len) < MAXSIZE_CONSOLE_WRITING) {
7117 rb_w32_close(
int fd)
7119 SOCKET sock = TO_SOCKET(fd);
7120 int save_errno =
errno;
7122 if (!is_socket(sock)) {
7123 UnlockFile((HANDLE)sock, 0, 0, LK_LEN, LK_LEN);
7124 constat_delete((HANDLE)sock);
7127 _set_osfhnd(fd, (SOCKET)INVALID_HANDLE_VALUE);
7128 socklist_delete(&sock, NULL);
7131 if (closesocket(sock) == SOCKET_ERROR) {
7132 errno = map_errno(WSAGetLastError());
7138 #ifndef INVALID_SET_FILE_POINTER
7139 #define INVALID_SET_FILE_POINTER ((DWORD)-1)
7143 setup_overlapped(OVERLAPPED *ol,
int fd,
int iswrite, rb_off_t *_offset)
7145 memset(ol, 0,
sizeof(*ol));
7150 DWORD seek_method = ((_osfile(fd) & FAPPEND) && iswrite) ? FILE_END : FILE_CURRENT;
7154 uint64_t offset = *_offset;
7155 ol->Offset = (uint32_t)(offset & 0xFFFFFFFFLL);
7156 ol->OffsetHigh = (uint32_t)((offset & 0xFFFFFFFF00000000LL) >> 32);
7159 LARGE_INTEGER seek_offset = {0}, current_offset = {0};
7160 if (!SetFilePointerEx((HANDLE)_osfhnd(fd), seek_offset, ¤t_offset, seek_method)) {
7161 DWORD last_error = GetLastError();
7162 if (last_error != NO_ERROR) {
7163 errno = map_errno(last_error);
7169 *_offset = current_offset.QuadPart;
7171 else if (!(_osfile(fd) & (FDEV | FPIPE))) {
7173 DWORD low = SetFilePointer((HANDLE)_osfhnd(fd), 0, &high, seek_method);
7175 if (low == INVALID_SET_FILE_POINTER) {
7176 DWORD err = GetLastError();
7177 if (err != NO_ERROR) {
7178 errno = map_errno(err);
7184 ol->OffsetHigh = high;
7187 ol->hEvent = CreateEvent(NULL, TRUE, TRUE, NULL);
7189 errno = map_errno(GetLastError());
7196 finish_overlapped(OVERLAPPED *ol,
int fd, DWORD size, rb_off_t *_offset)
7198 CloseHandle(ol->hEvent);
7202 DWORD seek_method = (_osfile(fd) & FAPPEND) ? FILE_END : FILE_BEGIN;
7204 LARGE_INTEGER seek_offset = {0};
7205 if (seek_method == FILE_BEGIN) {
7206 seek_offset.QuadPart = *_offset;
7209 SetFilePointerEx((HANDLE)_osfhnd(fd), seek_offset, NULL, seek_method);
7211 else if (!(_osfile(fd) & (FDEV | FPIPE))) {
7212 LONG high = ol->OffsetHigh;
7213 DWORD low = ol->Offset + size;
7214 if (low < ol->Offset)
7216 SetFilePointer((HANDLE)_osfhnd(fd), low, &high, FILE_BEGIN);
7223 rb_w32_read_internal(
int fd,
void *buf,
size_t size, rb_off_t *offset)
7225 SOCKET sock = TO_SOCKET(fd);
7233 BOOL islineinput = FALSE;
7236 if (is_socket(sock))
7237 return rb_w32_recv(fd, buf, size, 0);
7240 if (_get_osfhandle(fd) == -1) {
7244 if (!offset && _osfile(fd) & FTEXT) {
7245 return _read(fd, buf, size);
7248 rb_acrt_lowio_lock_fh(fd);
7250 if (!size || _osfile(fd) & FEOFLAG) {
7251 _set_osflags(fd, _osfile(fd) & ~FEOFLAG);
7252 rb_acrt_lowio_unlock_fh(fd);
7257 isconsole = is_console(_osfhnd(fd)) && (osver.dwMajorVersion < 6 || (osver.dwMajorVersion == 6 && osver.dwMinorVersion < 2));
7260 GetConsoleMode((HANDLE)_osfhnd(fd),&mode);
7261 islineinput = (mode & ENABLE_LINE_INPUT) != 0;
7266 constat_reset((HANDLE)_osfhnd(fd));
7278 if (setup_overlapped(&ol, fd, FALSE, offset)) {
7279 rb_acrt_lowio_unlock_fh(fd);
7283 if (!ReadFile((HANDLE)_osfhnd(fd), buf,
len, &read, &ol)) {
7284 err = GetLastError();
7285 if (err == ERROR_NO_DATA && (_osfile(fd) & FPIPE)) {
7287 if (GetNamedPipeHandleState((HANDLE)_osfhnd(fd), &state, NULL, NULL, NULL, NULL, 0) && (state & PIPE_NOWAIT)) {
7288 errno = EWOULDBLOCK;
7291 errno = map_errno(err);
7293 rb_acrt_lowio_unlock_fh(fd);
7296 else if (err != ERROR_IO_PENDING) {
7297 CloseHandle(ol.hEvent);
7298 if (err == ERROR_ACCESS_DENIED)
7300 else if (err == ERROR_BROKEN_PIPE || err == ERROR_HANDLE_EOF) {
7301 rb_acrt_lowio_unlock_fh(fd);
7305 errno = map_errno(err);
7307 rb_acrt_lowio_unlock_fh(fd);
7311 wait = rb_w32_wait_events_blocking(&ol.hEvent, 1, INFINITE);
7312 if (wait != WAIT_OBJECT_0) {
7313 if (wait == WAIT_OBJECT_0 + 1)
7316 errno = map_errno(GetLastError());
7317 CloseHandle(ol.hEvent);
7318 CancelIo((HANDLE)_osfhnd(fd));
7319 rb_acrt_lowio_unlock_fh(fd);
7323 if (!GetOverlappedResult((HANDLE)_osfhnd(fd), &ol, &read, TRUE) &&
7324 (err = GetLastError()) != ERROR_HANDLE_EOF) {
7326 if (err != ERROR_BROKEN_PIPE) {
7327 errno = map_errno(err);
7330 CloseHandle(ol.hEvent);
7331 CancelIo((HANDLE)_osfhnd(fd));
7332 rb_acrt_lowio_unlock_fh(fd);
7337 err = GetLastError();
7338 errno = map_errno(err);
7341 finish_overlapped(&ol, fd, read, offset);
7345 buf = (
char *)buf + read;
7346 if (err != ERROR_OPERATION_ABORTED &&
7347 !(isconsole &&
len == 1 && (!islineinput || *((
char *)buf - 1) ==
'\n')) && size > 0)
7351 _set_osflags(fd, _osfile(fd) | FEOFLAG);
7354 rb_acrt_lowio_unlock_fh(fd);
7362 rb_w32_write_internal(
int fd,
const void *buf,
size_t size, rb_off_t *offset)
7364 SOCKET sock = TO_SOCKET(fd);
7372 if (is_socket(sock))
7373 return rb_w32_send(fd, buf, size, 0);
7376 if (_get_osfhandle(fd) == -1) {
7381 if (!offset && (_osfile(fd) & FTEXT) &&
7382 (!(_osfile(fd) & FPIPE) || fd == fileno(stdout) || fd == fileno(stderr))) {
7383 ssize_t w = _write(fd, buf, size);
7384 if (w == (ssize_t)-1 &&
errno == EINVAL) {
7385 errno = map_errno(GetLastError());
7390 rb_acrt_lowio_lock_fh(fd);
7392 if (!size || _osfile(fd) & FEOFLAG) {
7393 rb_acrt_lowio_unlock_fh(fd);
7399 len = (_osfile(fd) & FDEV) ? min(MAXSIZE_CONSOLE_WRITING, size) : size;
7404 if (setup_overlapped(&ol, fd, TRUE, offset)) {
7405 rb_acrt_lowio_unlock_fh(fd);
7409 if (!WriteFile((HANDLE)_osfhnd(fd), buf,
len, &written, &ol)) {
7410 err = GetLastError();
7411 if (err != ERROR_IO_PENDING) {
7412 CloseHandle(ol.hEvent);
7413 if (err == ERROR_ACCESS_DENIED)
7416 errno = map_errno(err);
7418 rb_acrt_lowio_unlock_fh(fd);
7422 wait = rb_w32_wait_events_blocking(&ol.hEvent, 1, INFINITE);
7423 if (wait != WAIT_OBJECT_0) {
7424 if (wait == WAIT_OBJECT_0 + 1)
7427 errno = map_errno(GetLastError());
7428 CloseHandle(ol.hEvent);
7429 CancelIo((HANDLE)_osfhnd(fd));
7430 rb_acrt_lowio_unlock_fh(fd);
7434 if (!GetOverlappedResult((HANDLE)_osfhnd(fd), &ol, &written, TRUE)) {
7435 errno = map_errno(GetLastError());
7436 CloseHandle(ol.hEvent);
7437 CancelIo((HANDLE)_osfhnd(fd));
7438 rb_acrt_lowio_unlock_fh(fd);
7443 finish_overlapped(&ol, fd, written, offset);
7446 if (written ==
len) {
7447 buf = (
const char *)buf +
len;
7452 size_t newlen =
len / 2;
7454 size +=
len - newlen;
7459 errno = EWOULDBLOCK;
7462 rb_acrt_lowio_unlock_fh(fd);
7468 rb_w32_read(
int fd,
void *buf,
size_t size)
7470 return rb_w32_read_internal(fd, buf, size, NULL);
7474 rb_w32_write(
int fd,
const void *buf,
size_t size)
7476 return rb_w32_write_internal(fd, buf, size, NULL);
7480 rb_w32_pread(
int descriptor,
void *base,
size_t size, rb_off_t offset)
7482 return rb_w32_read_internal(descriptor, base, size, &offset);
7486 rb_w32_pwrite(
int descriptor,
const void *base,
size_t size, rb_off_t offset)
7488 return rb_w32_write_internal(descriptor, base, size, &offset);
7493 rb_w32_write_console(uintptr_t strarg,
int fd)
7496 DWORD dwMode, reslen;
7500 const WCHAR *
ptr, *next;
7504 handle = (HANDLE)_osfhnd(fd);
7505 if (!GetConsoleMode(handle, &dwMode))
7508 s = constat_handle(handle);
7518 case ENCINDEX_US_ASCII:
7519 case ENCINDEX_ASCII_8BIT:
7521 case ENCINDEX_UTF_8:
7523 if (!
ptr)
return -1L;
7525 case ENCINDEX_UTF_16LE:
7531 if (dwMode & ENABLE_VIRTUAL_TERMINAL_PROCESSING) {
7532 if (!WriteConsoleW(handle,
ptr,
len, &reslen, NULL))
7533 reslen = (DWORD)-1L;
7537 long curlen = constat_parse(handle, s, (next =
ptr, &next), &
len);
7538 reslen += next -
ptr;
7541 if (!WriteConsoleW(handle,
ptr, curlen, &written, NULL)) {
7542 reslen = (DWORD)-1L;
7551 return (
long)reslen;
7554 #if RUBY_MSVCRT_VERSION < 80 && !defined(HAVE__GMTIME64_S)
7557 unixtime_to_filetime(time_t time, FILETIME *ft)
7561 tmp.QuadPart = ((
LONG_LONG)time + (
LONG_LONG)((1970-1601)*365.2425) * 24 * 60 * 60) * 10 * 1000 * 1000;
7562 ft->dwLowDateTime = tmp.LowPart;
7563 ft->dwHighDateTime = tmp.HighPart;
7570 timespec_to_filetime(
const struct timespec *ts, FILETIME *ft)
7574 tmp.QuadPart = ((
LONG_LONG)ts->tv_sec + (
LONG_LONG)((1970-1601)*365.2425) * 24 * 60 * 60) * 10 * 1000 * 1000;
7575 tmp.QuadPart += ts->tv_nsec / 100;
7576 ft->dwLowDateTime = tmp.LowPart;
7577 ft->dwHighDateTime = tmp.HighPart;
7583 wutimensat(
int dirfd,
const WCHAR *path,
const struct timespec *times,
int flags)
7586 FILETIME atime, mtime;
7591 if (dirfd != AT_FDCWD) {
7601 if (wstati128(path, &stat, FALSE)) {
7606 if (timespec_to_filetime(×[0], &atime)) {
7609 if (timespec_to_filetime(×[1], &mtime)) {
7614 GetSystemTimePreciseAsFileTime(&atime);
7619 const DWORD attr = GetFileAttributesW(path);
7620 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY))
7621 SetFileAttributesW(path, attr & ~FILE_ATTRIBUTE_READONLY);
7622 hFile = open_special(path, GENERIC_WRITE, 0);
7623 if (hFile == INVALID_HANDLE_VALUE) {
7624 errno = map_errno(GetLastError());
7628 if (!SetFileTime(hFile, NULL, &atime, &mtime)) {
7629 errno = map_errno(GetLastError());
7634 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY))
7635 SetFileAttributesW(path, attr);
7643 w32_utimensat(
int dirfd,
const char *path,
const struct timespec *times,
int flags, UINT cp)
7645 WCHAR *wpath = mbstr_to_wstr(cp, path, -1, NULL);
7649 ret = wutimensat(dirfd, wpath, times, flags);
7657 rb_w32_uutime(
const char *path,
const struct utimbuf *times)
7661 ts[0].tv_sec = times->actime;
7663 ts[1].tv_sec = times->modtime;
7665 return w32_utimensat(AT_FDCWD, path, ts, 0, CP_UTF8);
7670 rb_w32_utime(
const char *path,
const struct utimbuf *times)
7674 ts[0].tv_sec = times->actime;
7676 ts[1].tv_sec = times->modtime;
7678 return w32_utimensat(AT_FDCWD, path, ts, 0, filecp());
7683 rb_w32_uutimes(
const char *path,
const struct timeval *times)
7687 ts[0].tv_sec = times[0].tv_sec;
7688 ts[0].tv_nsec = times[0].tv_usec * 1000;
7689 ts[1].tv_sec = times[1].tv_sec;
7690 ts[1].tv_nsec = times[1].tv_usec * 1000;
7691 return w32_utimensat(AT_FDCWD, path, ts, 0, CP_UTF8);
7696 rb_w32_utimes(
const char *path,
const struct timeval *times)
7700 ts[0].tv_sec = times[0].tv_sec;
7701 ts[0].tv_nsec = times[0].tv_usec * 1000;
7702 ts[1].tv_sec = times[1].tv_sec;
7703 ts[1].tv_nsec = times[1].tv_usec * 1000;
7704 return w32_utimensat(AT_FDCWD, path, ts, 0, filecp());
7709 rb_w32_uutimensat(
int dirfd,
const char *path,
const struct timespec *times,
int flags)
7711 return w32_utimensat(dirfd, path, times, flags, CP_UTF8);
7716 rb_w32_utimensat(
int dirfd,
const char *path,
const struct timespec *times,
int flags)
7718 return w32_utimensat(dirfd, path, times, flags, filecp());
7723 rb_w32_uchdir(
const char *path)
7728 if (!(wpath = utf8_to_wstr(path, NULL)))
7730 ret = _wchdir(wpath);
7737 wmkdir(
const WCHAR *wpath,
int mode)
7742 if (CreateDirectoryW(wpath, NULL) == FALSE) {
7743 errno = map_errno(GetLastError());
7746 if (_wchmod(wpath, mode) == -1) {
7747 RemoveDirectoryW(wpath);
7757 rb_w32_umkdir(
const char *path,
int mode)
7762 if (!(wpath = utf8_to_wstr(path, NULL)))
7764 ret = wmkdir(wpath, mode);
7771 rb_w32_mkdir(
const char *path,
int mode)
7776 if (!(wpath = filecp_to_wstr(path, NULL)))
7778 ret = wmkdir(wpath, mode);
7785 wrmdir(
const WCHAR *wpath)
7789 const DWORD attr = GetFileAttributesW(wpath);
7790 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY)) {
7791 SetFileAttributesW(wpath, attr & ~FILE_ATTRIBUTE_READONLY);
7793 if (RemoveDirectoryW(wpath) == FALSE) {
7794 errno = map_errno(GetLastError());
7796 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY)) {
7797 SetFileAttributesW(wpath, attr);
7806 rb_w32_rmdir(
const char *path)
7811 if (!(wpath = filecp_to_wstr(path, NULL)))
7813 ret = wrmdir(wpath);
7820 rb_w32_urmdir(
const char *path)
7825 if (!(wpath = utf8_to_wstr(path, NULL)))
7827 ret = wrmdir(wpath);
7834 wunlink(
const WCHAR *path)
7837 const DWORD SYMLINKD = FILE_ATTRIBUTE_REPARSE_POINT|FILE_ATTRIBUTE_DIRECTORY;
7839 const DWORD attr = GetFileAttributesW(path);
7840 if (attr == (DWORD)-1) {
7842 else if ((attr & SYMLINKD) == SYMLINKD) {
7843 ret = RemoveDirectoryW(path);
7846 if (attr & FILE_ATTRIBUTE_READONLY) {
7847 SetFileAttributesW(path, attr & ~FILE_ATTRIBUTE_READONLY);
7849 ret = DeleteFileW(path);
7852 errno = map_errno(GetLastError());
7854 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY)) {
7855 SetFileAttributesW(path, attr);
7864 rb_w32_uunlink(
const char *path)
7869 if (!(wpath = utf8_to_wstr(path, NULL)))
7871 ret = wunlink(wpath);
7878 rb_w32_unlink(
const char *path)
7883 if (!(wpath = filecp_to_wstr(path, NULL)))
7885 ret = wunlink(wpath);
7892 rb_w32_uchmod(
const char *path,
int mode)
7897 if (!(wpath = utf8_to_wstr(path, NULL)))
7899 ret = _wchmod(wpath, mode);
7906 fchmod(
int fd,
int mode)
7910 LARGE_INTEGER CreationTime;
7911 LARGE_INTEGER LastAccessTime;
7912 LARGE_INTEGER LastWriteTime;
7913 LARGE_INTEGER ChangeTime;
7914 DWORD FileAttributes;
7915 } info = {{{0}}, {{0}}, {{0}},};
7916 HANDLE h = (HANDLE)_get_osfhandle(fd);
7918 info.FileAttributes = FILE_ATTRIBUTE_NORMAL;
7919 if (!(mode & 0200)) info.FileAttributes |= FILE_ATTRIBUTE_READONLY;
7920 if (!SetFileInformationByHandle(h, 0, &info,
sizeof(info))) {
7921 errno = map_errno(GetLastError());
7929 rb_w32_isatty(
int fd)
7934 if (_get_osfhandle(fd) == -1) {
7937 if (!GetConsoleMode((HANDLE)_osfhnd(fd), &mode)) {
7944 #if defined(_MSC_VER) && RUBY_MSVCRT_VERSION <= 60
7945 extern long _ftol(
double);
7955 _ftol2_sse(
double d)
7966 int *ip = (
int *)(&x + 1) - 1;
7973 rb_w32_inet_ntop(
int af,
const void *addr,
char *numaddr,
size_t numaddr_len)
7975 return (inet_ntop)(af, (
void *)addr, numaddr, numaddr_len);
7980 rb_w32_inet_pton(
int af,
const char *src,
void *dst)
7982 return (inet_pton)(af, src, dst);
7987 rb_w32_fd_is_text(
int fd)
7989 return _osfile(fd) & FTEXT;
7992 #if RUBY_MSVCRT_VERSION < 80 && !defined(HAVE__GMTIME64_S)
7995 unixtime_to_systemtime(
const time_t t, SYSTEMTIME *st)
7998 if (unixtime_to_filetime(t, &ft))
return -1;
7999 if (!FileTimeToSystemTime(&ft, st))
return -1;
8005 systemtime_to_tm(
const SYSTEMTIME *st,
struct tm *t)
8007 int y = st->wYear, m = st->wMonth, d = st->wDay;
8008 t->tm_sec = st->wSecond;
8009 t->tm_min = st->wMinute;
8010 t->tm_hour = st->wHour;
8011 t->tm_mday = st->wDay;
8012 t->tm_mon = st->wMonth - 1;
8013 t->tm_year = y - 1900;
8014 t->tm_wday = st->wDayOfWeek;
8022 d += 31 + 28 + (!(y % 4) && ((y % 100) || !(y % 400)));
8023 d += ((m - 3) * 153 + 2) / 5;
8031 systemtime_to_localtime(TIME_ZONE_INFORMATION *tz, SYSTEMTIME *gst, SYSTEMTIME *lst)
8033 TIME_ZONE_INFORMATION stdtz;
8036 if (!SystemTimeToTzSpecificLocalTime(tz, gst, lst))
return -1;
8038 GetTimeZoneInformation(&stdtz);
8041 if (tz->StandardBias == tz->DaylightBias)
return 0;
8042 if (!tz->StandardDate.wMonth)
return 0;
8043 if (!tz->DaylightDate.wMonth)
return 0;
8044 if (tz != &stdtz) stdtz = *tz;
8046 stdtz.StandardDate.wMonth = stdtz.DaylightDate.wMonth = 0;
8047 if (!SystemTimeToTzSpecificLocalTime(&stdtz, gst, &sst))
return 0;
8048 if (lst->wMinute == sst.wMinute && lst->wHour == sst.wHour)
8054 #ifdef HAVE__GMTIME64_S
8055 # ifndef HAVE__LOCALTIME64_S
8057 # define HAVE__LOCALTIME64_S 1
8059 # ifndef MINGW_HAS_SECURE_API
8060 _CRTIMP errno_t __cdecl _gmtime64_s(
struct tm* tm,
const __time64_t *time);
8061 _CRTIMP errno_t __cdecl _localtime64_s(
struct tm* tm,
const __time64_t *time);
8063 # define gmtime_s _gmtime64_s
8064 # define localtime_s _localtime64_s
8069 gmtime_r(
const time_t *tp,
struct tm *rp)
8077 #if RUBY_MSVCRT_VERSION >= 80 || defined(HAVE__GMTIME64_S)
8078 e = gmtime_s(rp, tp);
8079 if (e != 0)
goto error;
8083 if (unixtime_to_systemtime(*tp, &st))
goto error;
8085 systemtime_to_tm(&st, rp);
8093 localtime_r(
const time_t *tp,
struct tm *rp)
8101 #if RUBY_MSVCRT_VERSION >= 80 || defined(HAVE__LOCALTIME64_S)
8102 e = localtime_s(rp, tp);
8106 SYSTEMTIME gst, lst;
8107 if (unixtime_to_systemtime(*tp, &gst))
goto error;
8108 rp->tm_isdst = systemtime_to_localtime(NULL, &gst, &lst);
8109 systemtime_to_tm(&lst, rp);
8117 rb_w32_wrap_io_handle(HANDLE h,
int flags)
8120 int len =
sizeof(tmp);
8121 int r = getsockopt((SOCKET)h, SOL_SOCKET, SO_DEBUG, (
char *)&tmp, &
len);
8122 if (r != SOCKET_ERROR || WSAGetLastError() != WSAENOTSOCK) {
8124 if (flags & O_NONBLOCK) {
8125 flags &= ~O_NONBLOCK;
8128 socklist_insert((SOCKET)h, f);
8130 else if (flags & O_NONBLOCK) {
8134 return rb_w32_open_osfhandle((intptr_t)h, flags);
8139 rb_w32_unwrap_io_handle(
int fd)
8141 SOCKET sock = TO_SOCKET(fd);
8142 _set_osfhnd(fd, (SOCKET)INVALID_HANDLE_VALUE);
8143 if (!is_socket(sock)) {
8144 UnlockFile((HANDLE)sock, 0, 0, LK_LEN, LK_LEN);
8145 constat_delete((HANDLE)sock);
8148 socklist_delete(&sock, NULL);
8153 #if !defined(__MINGW64__) && defined(__MINGW64_VERSION_MAJOR)
8159 rb_w32_pow(
double x,
double y)
8163 unsigned int default_control = _controlfp(0, 0);
8164 _controlfp(_PC_64, _MCW_PC);
8167 _controlfp(default_control, _MCW_PC);
8175 BY_HANDLE_FILE_INFORMATION bhfi;
8186 tmp = rb_check_convert_type_with_id(*file,
T_FILE,
"IO", idTo_io);
8189 if (f == (HANDLE)-1)
return INVALID_HANDLE_VALUE;
8199 len = MultiByteToWideChar(CP_UTF8, 0,
RSTRING_PTR(tmp), -1, NULL, 0);
8202 f = CreateFileW(
ptr, 0,
8203 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
8204 FILE_FLAG_BACKUP_SEMANTICS, NULL);
8206 if (f == INVALID_HANDLE_VALUE)
return f;
8209 if (GetFileType(f) == FILE_TYPE_DISK) {
8210 ZeroMemory(st,
sizeof(*st));
8211 if (get_ino(f, &st->info.fii)) {
8212 st->file_id_p = TRUE;
8215 else if (GetLastError() != ERROR_INVALID_PARAMETER) {
8217 return INVALID_HANDLE_VALUE;
8221 if (GetFileInformationByHandle(f, &st->info.bhfi)) {
8222 st->file_id_p = FALSE;
8226 if (ret) CloseHandle(ret);
8227 return INVALID_HANDLE_VALUE;
8231 close_handle(
VALUE h)
8233 CloseHandle((HANDLE)h);
8243 call_w32_io_info(
VALUE arg)
8246 return (
VALUE)w32_io_info(p->fname, p->st);
8250 rb_w32_file_identical_p(
VALUE fname1,
VALUE fname2)
8253 HANDLE f1 = 0, f2 = 0;
8255 f1 = w32_io_info(&fname1, &st1);
8256 if (f1 == INVALID_HANDLE_VALUE)
return Qfalse;
8259 arg.fname = &fname2;
8264 f2 = w32_io_info(&fname2, &st2);
8266 if (f2 == INVALID_HANDLE_VALUE)
return Qfalse;
8267 if (f2) CloseHandle(f2);
8269 if (st1.file_id_p != st2.file_id_p)
return Qfalse;
8270 if (!st1.file_id_p) {
8271 if (st1.info.bhfi.dwVolumeSerialNumber == st2.info.bhfi.dwVolumeSerialNumber &&
8272 st1.info.bhfi.nFileIndexHigh == st2.info.bhfi.nFileIndexHigh &&
8273 st1.info.bhfi.nFileIndexLow == st2.info.bhfi.nFileIndexLow)
8277 if (st1.info.fii.VolumeSerialNumber == st2.info.fii.VolumeSerialNumber &&
8278 memcmp(&st1.info.fii.FileId, &st2.info.fii.FileId,
sizeof(
FILE_ID_128)) == 0)
8285 rb_w32_set_thread_description(HANDLE th,
const WCHAR *name)
8288 typedef HRESULT (WINAPI *set_thread_description_func)(HANDLE, PCWSTR);
8289 static set_thread_description_func set_thread_description =
8290 (set_thread_description_func)-1;
8291 if (set_thread_description == (set_thread_description_func)-1) {
8293 set_thread_description = (set_thread_description_func)
8294 get_proc_address(
"kernel32",
"SetThreadDescription", NULL);
8296 if (set_thread_description) {
8297 result = set_thread_description(th, name);
8303 rb_w32_set_thread_description_str(HANDLE th,
VALUE name)
8305 int idx, result = FALSE;
8309 return rb_w32_set_thread_description(th, L
"");
8313 if (idx == ENCINDEX_UTF_16LE) {
8314 result = rb_w32_set_thread_description(th, s);
8319 result = rb_w32_set_thread_description(th, s);
8328 #if RUBY_MSVCRT_VERSION < 120
8329 #include "missing/nextafter.c"
8333 rb_w32_mmap(
void *addr,
size_t len,
int prot,
int flags,
int fd, rb_off_t offset)
8337 DWORD protect = PAGE_EXECUTE_READWRITE;
8339 if (fd > 0 || offset) {
8354 ptr = VirtualAlloc(addr,
len, MEM_RESERVE | MEM_COMMIT, protect);
8356 errno = rb_w32_map_errno(GetLastError());
8364 rb_w32_munmap(
void *addr,
size_t len)
8366 if (!VirtualFree(addr, 0, MEM_RELEASE)) {
8367 errno = rb_w32_map_errno(GetLastError());
8375 rb_w32_mprotect(
void *addr,
size_t len,
int prot)
8391 if (prot & PROT_EXEC) {
8392 if (!FlushInstructionCache(GetCurrentProcess(), addr,
len)) {
8393 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 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 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.
void rb_fatal(const char *fmt,...)
Raises the unsung "fatal" exception.
VALUE rb_ensure(VALUE(*b_proc)(VALUE), VALUE data1, VALUE(*e_proc)(VALUE), VALUE data2)
An equivalent to ensure clause.
int rb_enc_get_index(VALUE obj)
Queries the index of the encoding of the passed object, if any.
int rb_enc_to_index(rb_encoding *enc)
Queries the index of the encoding.
rb_encoding * rb_utf8_encoding(void)
Queries the encoding that represents UTF-8.
rb_encoding * rb_enc_from_index(int idx)
Identical to rb_find_encoding(), except it takes an encoding index instead of a Ruby object.
static const char * rb_enc_name(rb_encoding *enc)
Queries the (canonical) name of the passed encoding.
rb_encoding * rb_filesystem_encoding(void)
Queries the "filesystem" encoding.
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.
VALUE rb_enc_str_new(const char *ptr, long len, rb_encoding *enc)
Identical to rb_str_new(), except it additionally takes an encoding.
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.
VALUE rb_str_encode_ospath(VALUE path)
Converts a string into an "OS Path" encoding, if any.
void rb_write_error2(const char *str, long len)
Identical to rb_write_error(), except it additionally takes the message's length.
VALUE rb_utf8_str_new(const char *ptr, long len)
Identical to rb_str_new(), except it generates a string of "UTF-8" encoding.
VALUE rb_str_cat(VALUE dst, const char *src, long srclen)
Destructively appends the passed contents to the string.
#define rb_strlen_lit(str)
Length of a string literal.
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.
char * ptr
Pointer to the underlying memory region, of at least capa bytes.
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.
VALUE rb_sprintf(const char *fmt,...)
Ruby's extended sprintf(3).
VALUE rb_str_vcatf(VALUE dst, const char *fmt, va_list ap)
Identical to rb_str_catf(), except it takes a va_list.
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.
int st_foreach(st_table *q, int_type *w, st_data_t e)
Iteration over the given table.
#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.
static char * RSTRING_PTR(VALUE str)
Queries the contents pointer of the string.
static long RSTRING_LEN(VALUE str)
Queries the length of the string.
#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.
void * ruby_xmalloc(size_t size)
Allocates a storage instance.
void ruby_xfree(void *ptr)
Deallocates a storage instance.
void * ruby_xcalloc(size_t nelems, size_t elemsiz)
Identical to ruby_xmalloc2(), except it returns a zero-filled storage instance.