59#include "ruby/win32.h"
62#include "win32/file.h"
65#include "internal/enc.h"
66#include "internal/object.h"
67#include "internal/static_assert.h"
70#define isdirsep(x) ((x) == '/' || (x) == '\\')
72static int w32_wopen(
const WCHAR *file,
int oflag,
int perm);
73static int w32_stati128(
const char *path,
struct stati128 *st, UINT cp, BOOL lstat);
74static char *w32_getenv(
const char *name, UINT cp);
80#define DLN_FIND_EXTRA_ARG_DECL ,UINT cp
81#define DLN_FIND_EXTRA_ARG ,cp
82#define rb_w32_stati128(path, st) w32_stati128(path, st, cp, FALSE)
83#define getenv(name) w32_getenv(name, cp)
85#define CharNext(p) CharNextExA(cp, (p), 0)
86#define dln_find_exe_r rb_w32_udln_find_exe_r
87#define dln_find_file_r rb_w32_udln_find_file_r
94#define dln_find_exe_r(fname, path, buf, size) rb_w32_udln_find_exe_r(fname, path, buf, size, cp)
95#define dln_find_file_r(fname, path, buf, size) rb_w32_udln_find_file_r(fname, path, buf, size, cp)
101# define PATH_MAX MAX_PATH
102# elif defined HAVE_SYS_PARAM_H
103# include <sys/param.h>
104# define PATH_MAX MAXPATHLEN
116#define _filbuf _fgetc_nolock
117#define _flsbuf _fputc_nolock
118#define enough_to_get(n) (--(n) >= 0)
119#define enough_to_put(n) (--(n) >= 0)
122#define Debug(something) something
124#define Debug(something)
127#define TO_SOCKET(x) _get_osfhandle(x)
129int rb_w32_reparse_symlink_p(
const WCHAR *path);
131static int has_redirection(
const char *, UINT);
132int rb_w32_wait_events(HANDLE *events,
int num, DWORD timeout);
133static int rb_w32_open_osfhandle(intptr_t osfhandle,
int flags);
134static int wstati128(
const WCHAR *path,
struct stati128 *st, BOOL lstat);
137static FARPROC get_proc_address(
const char *module,
const char *func, HANDLE *mh);
139#define RUBY_CRITICAL if (0) {} else
146 { ERROR_INVALID_FUNCTION, EINVAL },
147 { ERROR_FILE_NOT_FOUND, ENOENT },
148 { ERROR_PATH_NOT_FOUND, ENOENT },
149 { ERROR_TOO_MANY_OPEN_FILES, EMFILE },
150 { ERROR_ACCESS_DENIED, EACCES },
151 { ERROR_INVALID_HANDLE, EBADF },
152 { ERROR_ARENA_TRASHED, ENOMEM },
153 { ERROR_NOT_ENOUGH_MEMORY, ENOMEM },
154 { ERROR_INVALID_BLOCK, ENOMEM },
155 { ERROR_BAD_ENVIRONMENT, E2BIG },
156 { ERROR_BAD_FORMAT, ENOEXEC },
157 { ERROR_INVALID_ACCESS, EINVAL },
158 { ERROR_INVALID_DATA, EINVAL },
159 { ERROR_INVALID_DRIVE, ENOENT },
160 { ERROR_CURRENT_DIRECTORY, EACCES },
161 { ERROR_NOT_SAME_DEVICE, EXDEV },
162 { ERROR_NO_MORE_FILES, ENOENT },
163 { ERROR_WRITE_PROTECT, EROFS },
164 { ERROR_BAD_UNIT, ENODEV },
165 { ERROR_NOT_READY, ENXIO },
166 { ERROR_BAD_COMMAND, EACCES },
167 { ERROR_CRC, EACCES },
168 { ERROR_BAD_LENGTH, EACCES },
170 { ERROR_NOT_DOS_DISK, EACCES },
171 { ERROR_SECTOR_NOT_FOUND, EACCES },
172 { ERROR_OUT_OF_PAPER, EACCES },
173 { ERROR_WRITE_FAULT, EIO },
174 { ERROR_READ_FAULT, EIO },
175 { ERROR_GEN_FAILURE, EACCES },
176 { ERROR_LOCK_VIOLATION, EACCES },
177 { ERROR_SHARING_VIOLATION, EACCES },
178 { ERROR_WRONG_DISK, EACCES },
179 { ERROR_SHARING_BUFFER_EXCEEDED, EACCES },
180 { ERROR_BAD_NETPATH, ENOENT },
181 { ERROR_NETWORK_ACCESS_DENIED, EACCES },
182 { ERROR_BAD_NET_NAME, ENOENT },
183 { ERROR_FILE_EXISTS, EEXIST },
184 { ERROR_CANNOT_MAKE, EACCES },
185 { ERROR_FAIL_I24, EACCES },
186 { ERROR_INVALID_PARAMETER, EINVAL },
187 { ERROR_NO_PROC_SLOTS, EAGAIN },
188 { ERROR_DRIVE_LOCKED, EACCES },
189 { ERROR_BROKEN_PIPE, EPIPE },
190 { ERROR_DISK_FULL, ENOSPC },
191 { ERROR_INVALID_TARGET_HANDLE, EBADF },
192 { ERROR_INVALID_HANDLE, EINVAL },
193 { ERROR_WAIT_NO_CHILDREN, ECHILD },
194 { ERROR_CHILD_NOT_COMPLETE, ECHILD },
195 { ERROR_DIRECT_ACCESS_HANDLE, EBADF },
196 { ERROR_NEGATIVE_SEEK, EINVAL },
197 { ERROR_SEEK_ON_DEVICE, EACCES },
198 { ERROR_DIR_NOT_EMPTY, ENOTEMPTY },
199 { ERROR_DIRECTORY, ENOTDIR },
200 { ERROR_NOT_LOCKED, EACCES },
201 { ERROR_BAD_PATHNAME, ENOENT },
202 { ERROR_MAX_THRDS_REACHED, EAGAIN },
203 { ERROR_LOCK_FAILED, EACCES },
204 { ERROR_ALREADY_EXISTS, EEXIST },
205 { ERROR_INVALID_STARTING_CODESEG, ENOEXEC },
206 { ERROR_INVALID_STACKSEG, ENOEXEC },
207 { ERROR_INVALID_MODULETYPE, ENOEXEC },
208 { ERROR_INVALID_EXE_SIGNATURE, ENOEXEC },
209 { ERROR_EXE_MARKED_INVALID, ENOEXEC },
210 { ERROR_BAD_EXE_FORMAT, ENOEXEC },
211 { ERROR_ITERATED_DATA_EXCEEDS_64k,ENOEXEC },
212 { ERROR_INVALID_MINALLOCSIZE, ENOEXEC },
213 { ERROR_DYNLINK_FROM_INVALID_RING,ENOEXEC },
214 { ERROR_IOPL_NOT_ENABLED, ENOEXEC },
215 { ERROR_INVALID_SEGDPL, ENOEXEC },
216 { ERROR_AUTODATASEG_EXCEEDS_64k, ENOEXEC },
217 { ERROR_RING2SEG_MUST_BE_MOVABLE, ENOEXEC },
218 { ERROR_RELOC_CHAIN_XEEDS_SEGLIM, ENOEXEC },
219 { ERROR_INFLOOP_IN_RELOC_CHAIN, ENOEXEC },
220 { ERROR_FILENAME_EXCED_RANGE, ENOENT },
221 { ERROR_NESTING_NOT_ALLOWED, EAGAIN },
222#ifndef ERROR_PIPE_LOCAL
223#define ERROR_PIPE_LOCAL 229L
225 { ERROR_PIPE_LOCAL, EPIPE },
226 { ERROR_BAD_PIPE, EPIPE },
227 { ERROR_PIPE_BUSY, EAGAIN },
228 { ERROR_NO_DATA, EPIPE },
229 { ERROR_PIPE_NOT_CONNECTED, EPIPE },
230 { ERROR_OPERATION_ABORTED, EINTR },
231 { ERROR_NOT_ENOUGH_QUOTA, ENOMEM },
232 { ERROR_MOD_NOT_FOUND, ENOENT },
233 { ERROR_PRIVILEGE_NOT_HELD, EACCES, },
234 { ERROR_CANT_RESOLVE_FILENAME, ELOOP, },
237 { WSAEACCES, EACCES },
238 { WSAEFAULT, EFAULT },
239 { WSAEINVAL, EINVAL },
240 { WSAEMFILE, EMFILE },
241 { WSAEWOULDBLOCK, EWOULDBLOCK },
242 { WSAEINPROGRESS, EINPROGRESS },
243 { WSAEALREADY, EALREADY },
244 { WSAENOTSOCK, ENOTSOCK },
245 { WSAEDESTADDRREQ, EDESTADDRREQ },
246 { WSAEMSGSIZE, EMSGSIZE },
247 { WSAEPROTOTYPE, EPROTOTYPE },
248 { WSAENOPROTOOPT, ENOPROTOOPT },
249 { WSAEPROTONOSUPPORT, EPROTONOSUPPORT },
250 { WSAESOCKTNOSUPPORT, ESOCKTNOSUPPORT },
251 { WSAEOPNOTSUPP, EOPNOTSUPP },
252 { WSAEPFNOSUPPORT, EPFNOSUPPORT },
253 { WSAEAFNOSUPPORT, EAFNOSUPPORT },
254 { WSAEADDRINUSE, EADDRINUSE },
255 { WSAEADDRNOTAVAIL, EADDRNOTAVAIL },
256 { WSAENETDOWN, ENETDOWN },
257 { WSAENETUNREACH, ENETUNREACH },
258 { WSAENETRESET, ENETRESET },
259 { WSAECONNABORTED, ECONNABORTED },
260 { WSAECONNRESET, ECONNRESET },
261 { WSAENOBUFS, ENOBUFS },
262 { WSAEISCONN, EISCONN },
263 { WSAENOTCONN, ENOTCONN },
264 { WSAESHUTDOWN, ESHUTDOWN },
265 { WSAETOOMANYREFS, ETOOMANYREFS },
266 { WSAETIMEDOUT, ETIMEDOUT },
267 { WSAECONNREFUSED, ECONNREFUSED },
269 { WSAENAMETOOLONG, ENAMETOOLONG },
270 { WSAEHOSTDOWN, EHOSTDOWN },
271 { WSAEHOSTUNREACH, EHOSTUNREACH },
272 { WSAEPROCLIM, EPROCLIM },
273 { WSAENOTEMPTY, ENOTEMPTY },
274 { WSAEUSERS, EUSERS },
275 { WSAEDQUOT, EDQUOT },
276 { WSAESTALE, ESTALE },
277 { WSAEREMOTE, EREMOTE },
282rb_w32_map_errno(DWORD winerr)
290 for (i = 0; i < (int)(
sizeof(errmap) /
sizeof(*errmap)); i++) {
291 if (errmap[i].winerr == winerr) {
292 return errmap[i].err;
296 if (winerr >= WSABASEERR) {
302#define map_errno rb_w32_map_errno
304static const char *NTLoginName;
306static OSVERSIONINFO osver;
312 memset(&osver, 0,
sizeof(OSVERSIONINFO));
313 osver.dwOSVersionInfoSize =
sizeof(OSVERSIONINFO);
314 GetVersionEx(&osver);
321 return osver.dwMajorVersion;
332 DWORD err = GetLastError(); \
333 if (err == ERROR_LOCK_VIOLATION || err == ERROR_IO_PENDING) \
334 errno = EWOULDBLOCK; \
335 else if (err == ERROR_NOT_LOCKED) \
338 errno = map_errno(err); \
341#define LK_LEN ULONG_MAX
345flock_winnt(uintptr_t self,
int argc, uintptr_t* argv)
349 const HANDLE fh = (HANDLE)self;
350 const int oper = argc;
352 memset(&o, 0,
sizeof(o));
356 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, LK_LEN, &o), i);
359 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, LK_LEN, &o), i);
361 case LOCK_SH|LOCK_NB:
362 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, LK_LEN, &o), i);
364 case LOCK_EX|LOCK_NB:
365 LK_ERR(LockFileEx(fh,
366 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
367 0, LK_LEN, LK_LEN, &o), i);
370 case LOCK_UN|LOCK_NB:
371 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, LK_LEN, &o), i);
384flock(
int fd,
int oper)
386 const asynchronous_func_t locker = flock_winnt;
388 return rb_w32_asynchronize(locker,
389 (
VALUE)_get_osfhandle(fd), oper, NULL,
395translate_wchar(WCHAR *p,
int from,
int to)
406translate_char(
char *p,
int from,
int to, UINT cp)
409 if ((
unsigned char)*p == from)
411 p = CharNextExA(cp, p, 0);
416#ifndef CSIDL_LOCAL_APPDATA
417#define CSIDL_LOCAL_APPDATA 28
419#ifndef CSIDL_COMMON_APPDATA
420#define CSIDL_COMMON_APPDATA 35
423#define CSIDL_WINDOWS 36
426#define CSIDL_SYSTEM 37
429#define CSIDL_PROFILE 40
434get_special_folder(
int n, WCHAR *buf,
size_t len)
440 if (SHGetSpecialFolderLocation(NULL, n, &pidl) == 0) {
441 f = SHGetPathFromIDListEx(pidl, buf,
len, 0);
443 alloc->lpVtbl->Free(alloc, pidl);
444 alloc->lpVtbl->Release(alloc);
451regulate_path(WCHAR *path)
453 WCHAR *p = translate_wchar(path, L
'\\', L
'/');
454 if (p - path == 2 && path[1] == L
':') {
462get_proc_address(
const char *module,
const char *func, HANDLE *mh)
468 h = LoadLibrary(module);
470 h = GetModuleHandle(module);
474 ptr = GetProcAddress(h, func);
486rb_w32_special_folder(
int type)
488 WCHAR path[PATH_MAX];
490 if (!get_special_folder(
type, path, numberof(path)))
return Qnil;
492 return rb_w32_conv_from_wchar(path, rb_filesystem_encoding());
497rb_w32_system_tmpdir(WCHAR *path, UINT
len)
499 static const WCHAR temp[] = L
"temp";
502 if (!get_special_folder(CSIDL_LOCAL_APPDATA, path,
len)) {
503 if (GetSystemWindowsDirectoryW(path,
len))
return 0;
505 p = translate_wchar(path, L
'\\', L
'/');
506 if (*(p - 1) != L
'/') *p++ = L
'/';
507 if ((UINT)(p - path + numberof(temp)) >=
len)
return 0;
508 memcpy(p, temp,
sizeof(temp));
509 return (UINT)(p - path + numberof(temp) - 1);
524 WCHAR *buffer = NULL;
525 size_t buffer_len = MAX_PATH,
len = 0;
527 HOME_NONE, ENV_HOME, ENV_USERPROFILE, ENV_DRIVEPATH
528 } home_type = HOME_NONE;
530 if ((
len = GetEnvironmentVariableW(L
"HOME", NULL, 0)) != 0) {
532 home_type = ENV_HOME;
534 else if ((
len = GetEnvironmentVariableW(L
"USERPROFILE", NULL, 0)) != 0) {
536 home_type = ENV_USERPROFILE;
538 else if ((
len = GetEnvironmentVariableW(L
"HOMEDRIVE", NULL, 0)) != 0) {
540 if ((
len = GetEnvironmentVariableW(L
"HOMEPATH", NULL, 0)) != 0) {
542 home_type = ENV_DRIVEPATH;
547 buffer = malloc(
sizeof(WCHAR) * buffer_len);
548 if (buffer == NULL)
return NULL;
552 GetEnvironmentVariableW(L
"HOME", buffer, buffer_len);
554 case ENV_USERPROFILE:
555 GetEnvironmentVariableW(L
"USERPROFILE", buffer, buffer_len);
558 len = GetEnvironmentVariableW(L
"HOMEDRIVE", buffer, buffer_len);
559 GetEnvironmentVariableW(L
"HOMEPATH", buffer +
len, buffer_len -
len);
562 if (!get_special_folder(CSIDL_PROFILE, buffer, buffer_len) &&
563 !get_special_folder(CSIDL_PERSONAL, buffer, buffer_len)) {
567 buffer = realloc(buffer,
sizeof(WCHAR) * (lstrlenW(buffer) + 1));
572 regulate_path(buffer);
583 if (!GetEnvironmentVariableW(L
"HOME", env, numberof(env))) {
584 WCHAR *whome = rb_w32_home_dir();
586 _wputenv_s(L
"HOME", whome);
591 if (!GetEnvironmentVariableW(L
"USER", env, numberof(env))) {
593 if (!GetEnvironmentVariableW(L
"USERNAME", env, numberof(env)) &&
594 !GetUserNameW(env, (
len = numberof(env), &
len))) {
595 NTLoginName =
"<Unknown>";
598 _wputenv_s(L
"USER", env);
599 NTLoginName = rb_w32_wstr_to_mbstr(CP_UTF8, env, -1, NULL);
603 NTLoginName = rb_w32_wstr_to_mbstr(CP_UTF8, env, -1, NULL);
606 if (!GetEnvironmentVariableW(L
"TMPDIR", env, numberof(env)) &&
607 !GetEnvironmentVariableW(L
"TMP", env, numberof(env)) &&
608 !GetEnvironmentVariableW(L
"TEMP", env, numberof(env)) &&
609 rb_w32_system_tmpdir(env, numberof(env))) {
610 _wputenv_s(L
"TMPDIR", env);
614static void init_stdhandle(
void);
618invalid_parameter(
const wchar_t *expr,
const wchar_t *func,
const wchar_t *file,
unsigned int line, uintptr_t dummy)
623int ruby_w32_rtc_error;
630rtc_error_handler(
int e, const
char *src,
int line, const
char *exe, const
char *fmt, ...)
635 if (!ruby_w32_rtc_error)
return 0;
636 str = rb_sprintf(
"%s:%d: ", src, line);
638 rb_str_vcatf(str, fmt, ap);
646static CRITICAL_SECTION select_mutex;
648static CRITICAL_SECTION socklist_mutex;
651static CRITICAL_SECTION conlist_mutex;
653#define conlist_disabled ((st_table *)-1)
655#define thread_exclusive(obj) \
656 for (bool exclusive_for_##obj = (EnterCriticalSection(&obj##_mutex), true); \
657 exclusive_for_##obj; \
658 exclusive_for_##obj = (LeaveCriticalSection(&obj##_mutex), false))
660static CRITICAL_SECTION uenvarea_mutex;
661static char *uenvarea;
666 int state, seq[16], reverse;
671enum {constat_init = -2, constat_esc = -1, constat_seq = 0};
675free_conlist(st_data_t key, st_data_t val, st_data_t arg)
683constat_delete(HANDLE h)
685 thread_exclusive(conlist) {
686 if (conlist && conlist != conlist_disabled) {
687 st_data_t key = (st_data_t)h, val;
688 st_delete(conlist, &key, &val);
699 DeleteCriticalSection(&select_mutex);
700 DeleteCriticalSection(&socklist_mutex);
701 DeleteCriticalSection(&conlist_mutex);
702 thread_exclusive(uenvarea) {
708 DeleteCriticalSection(&uenvarea_mutex);
715 EnterCriticalSection(&socklist_mutex);
717 st_free_table(socklist);
720 LeaveCriticalSection(&socklist_mutex);
722 EnterCriticalSection(&conlist_mutex);
723 if (conlist && conlist != conlist_disabled) {
724 st_foreach(conlist, free_conlist, 0);
725 st_free_table(conlist);
728 LeaveCriticalSection(&conlist_mutex);
731#define ATOMIC_LONG_CAS(var, oldval, newval) InterlockedCompareExchange(&(var), (newval), (oldval))
735install_vm_exit_handler(
void)
737 static LONG installed = 0;
740 while ((i = ATOMIC_LONG_CAS(installed, 0, -1)) != 1) {
746 ATOMIC_LONG_CAS(installed, -1, 1);
762 version = MAKEWORD(2, 0);
763 if (WSAStartup(version, &retdata))
764 rb_fatal(
"Unable to locate winsock library!");
765 if (LOBYTE(retdata.wVersion) != 2)
766 rb_fatal(
"could not find version 2 of winsock dll");
768 InitializeCriticalSection(&select_mutex);
769 InitializeCriticalSection(&socklist_mutex);
770 InitializeCriticalSection(&conlist_mutex);
772 atexit(exit_handler);
775#define MAKE_SOCKDATA(af, fl) ((int)((((int)af)<<4)|((fl)&0xFFFF)))
776#define GET_FAMILY(v) ((int)(((v)>>4)&0xFFFF))
777#define GET_FLAGS(v) ((int)((v)&0xFFFF))
781socklist_insert(SOCKET sock,
int flag)
785 thread_exclusive(socklist) {
787 socklist = st_init_numtable();
788 install_vm_exit_handler();
790 ret = st_insert(socklist, (st_data_t)sock, (st_data_t)flag);
798socklist_lookup(SOCKET sock,
int *flagp)
803 thread_exclusive(socklist) {
804 if (!socklist)
continue;
805 ret = st_lookup(socklist, (st_data_t)sock, &data);
815socklist_delete(SOCKET *sockp,
int *flagp)
821 thread_exclusive(socklist) {
822 if (!socklist)
continue;
823 key = (st_data_t)*sockp;
825 data = (st_data_t)*flagp;
826 ret = st_delete(socklist, &key, &data);
828 *sockp = (SOCKET)key;
838# define _CrtSetReportMode(type,mode) ((void)0)
839# define _RTC_SetErrorFunc(func) ((void)0)
841static void set_pioinfo_extra(
void);
842static int w32_cmdvector(
const WCHAR *,
char ***, UINT,
rb_encoding *);
859rb_w32_init_long_paths(
void)
862 enum {peb_bit_field_offset = 3, is_long_path_aware_process = 0x80};
863 typedef long (WINAPI version_func)(OSVERSIONINFOW *);
864 typedef void *(WINAPI peb_func)(
void);
865 version_func *pRtlGetVersion;
866 peb_func *pRtlGetCurrentPeb;
870 pRtlGetVersion = (version_func *)get_proc_address(
"ntdll.dll",
"RtlGetVersion", NULL);
871 if (!pRtlGetVersion)
return;
872 memset(&osvi, 0,
sizeof(osvi));
873 osvi.dwOSVersionInfoSize =
sizeof(osvi);
874 if (pRtlGetVersion(&osvi))
return;
877 if (osvi.dwMajorVersion < 10)
return;
878 if (osvi.dwMajorVersion == 10 && osvi.dwMinorVersion == 0 &&
879 osvi.dwBuildNumber < 15063)
return;
881 pRtlGetCurrentPeb = (peb_func *)get_proc_address(
"ntdll.dll",
"RtlGetCurrentPeb", NULL);
882 if (!pRtlGetCurrentPeb)
return;
883 bit_field = (BYTE *)pRtlGetCurrentPeb() + peb_bit_field_offset;
884 *bit_field |= is_long_path_aware_process;
889rb_w32_sysinit(
int *argc,
char ***argv)
891 _CrtSetReportMode(_CRT_ASSERT, 0);
892 _set_invalid_parameter_handler(invalid_parameter);
893 _RTC_SetErrorFunc(rtc_error_handler);
895 SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOGPFAULTERRORBOX);
902 *argc = w32_cmdvector(GetCommandLineW(), argv, CP_UTF8, &OnigEncodingUTF_8);
910 InitializeCriticalSection(&uenvarea_mutex);
922 return (
char *)NTLoginName;
925#define MAXCHILDNUM 256
934#define FOREACH_CHILD(v) do { \
935 struct ChildRecord* v; \
936 for (v = ChildRecord; v < ChildRecord + sizeof(ChildRecord) / sizeof(ChildRecord[0]); ++v)
937#define END_FOREACH_CHILD } while (0)
941FindChildSlot(rb_pid_t pid)
944 FOREACH_CHILD(child) {
945 if (child->pid == pid) {
954FindChildSlotByHandle(HANDLE h)
957 FOREACH_CHILD(child) {
958 if (child->hProcess == h) {
969 HANDLE h = child->hProcess;
970 child->hProcess = NULL;
977FindFreeChildSlot(
void)
979 FOREACH_CHILD(child) {
982 child->hProcess = NULL;
996#define InternalCmdsMax 8
997static const char szInternalCmds[][InternalCmdsMax+2] = {
1052internal_match(
const void *key,
const void *elem)
1054 return strncmp(key, ((
const char *)elem) + 1, InternalCmdsMax);
1059is_command_com(
const char *interp)
1061 int i = strlen(interp) - 11;
1063 if ((i == 0 || (i > 0 && isdirsep(interp[i-1]))) &&
1064 strcasecmp(interp+i,
"command.com") == 0) {
1070static int internal_cmd_match(
const char *cmdname,
int nt);
1074is_internal_cmd(
const char *cmd,
int nt)
1076 char cmdname[9], *b = cmdname, c;
1079 if (!(c = *cmd++))
return 0;
1080 }
while (isspace(c));
1083 while (isalpha(c)) {
1085 if (b == cmdname +
sizeof(cmdname))
return 0;
1088 if (c ==
'.') c = *cmd;
1090 case '<':
case '>':
case '|':
1092 case '\0':
case ' ':
case '\t':
case '\n':
1098 return internal_cmd_match(cmdname, nt);
1103internal_cmd_match(
const char *cmdname,
int nt)
1107 nm = bsearch(cmdname, szInternalCmds,
1108 sizeof(szInternalCmds) /
sizeof(*szInternalCmds),
1109 sizeof(*szInternalCmds),
1111 if (!nm || !(nm[0] & (nt ? 2 : 1)))
1118rb_w32_get_osfhandle(
int fh)
1120 return _get_osfhandle(fh);
1125join_argv(
char *cmd,
char *
const *argv, BOOL escape, UINT cp,
int backslash, BOOL quote_bs)
1129 int len, n, bs, quote;
1131 for (t = argv, q = cmd,
len = 0; (p = *t) != 0; t++) {
1134 if (!*p || strpbrk(p,
" \t\"'")) {
1139 for (bs = 0; *p; ++p) {
1153 memset(q,
'\\', bs);
1158 case '<':
case '>':
case '|':
case '^':
1159 if (escape && !quote) {
1160 len += (n = p - s) + 1;
1171 p = CharNextExA(cp, p, 0) - 1;
1175 len += (n = p - s) + 1;
1176 if (quote)
len += (quote_bs ? bs : 0) + 1;
1179 if (backslash > 0) {
1182 translate_char(q,
'/',
'\\', cp);
1187 if (quote_bs && bs) {
1188 memset(q,
'\\', bs);
1205#define STRNDUPV(ptr, v, src, len) \
1206 (((char *)memcpy(((ptr) = ALLOCV((v), (len) + 1)), (src), (len)))[len] = 0)
1210check_spawn_mode(
int mode)
1232 if (mode == P_OVERLAY) {
1233 WaitForSingleObject(child->hProcess, INFINITE);
1234 GetExitCodeProcess(child->hProcess, &exitcode);
1235 CloseChildHandle(child);
1243CreateChild(
struct ChildRecord *child,
const WCHAR *cmd,
const WCHAR *prog, HANDLE hInput, HANDLE hOutput, HANDLE hError, DWORD dwCreationFlags)
1246 STARTUPINFOW aStartupInfo;
1247 PROCESS_INFORMATION aProcessInformation;
1248 SECURITY_ATTRIBUTES sa;
1250 if (!cmd && !prog) {
1260 sa.nLength =
sizeof(SECURITY_ATTRIBUTES);
1261 sa.lpSecurityDescriptor = NULL;
1262 sa.bInheritHandle = TRUE;
1264 memset(&aStartupInfo, 0,
sizeof(aStartupInfo));
1265 memset(&aProcessInformation, 0,
sizeof(aProcessInformation));
1266 aStartupInfo.cb =
sizeof(aStartupInfo);
1267 aStartupInfo.dwFlags = STARTF_USESTDHANDLES;
1269 aStartupInfo.hStdInput = hInput;
1272 aStartupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
1275 aStartupInfo.hStdOutput = hOutput;
1278 aStartupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
1281 aStartupInfo.hStdError = hError;
1284 aStartupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
1287 dwCreationFlags |= NORMAL_PRIORITY_CLASS;
1289 if (lstrlenW(cmd) > 32767) {
1296 fRet = CreateProcessW(prog, (WCHAR *)cmd, &sa, &sa,
1297 sa.bInheritHandle, dwCreationFlags, NULL, NULL,
1298 &aStartupInfo, &aProcessInformation);
1299 errno = map_errno(GetLastError());
1307 CloseHandle(aProcessInformation.hThread);
1309 child->hProcess = aProcessInformation.hProcess;
1310 child->pid = (rb_pid_t)aProcessInformation.dwProcessId;
1317is_batch(
const char *cmd)
1319 int len = strlen(cmd);
1320 if (
len <= 4)
return 0;
1322 if (*cmd++ !=
'.')
return 0;
1323 if (strcasecmp(cmd,
"bat") == 0)
return 1;
1324 if (strcasecmp(cmd,
"cmd") == 0)
return 1;
1328#define filecp rb_w32_filecp
1329#define mbstr_to_wstr rb_w32_mbstr_to_wstr
1330#define wstr_to_mbstr rb_w32_wstr_to_mbstr
1331#define acp_to_wstr(str, plen) mbstr_to_wstr(CP_ACP, str, -1, plen)
1332#define wstr_to_acp(str, plen) wstr_to_mbstr(CP_ACP, str, -1, plen)
1333#define filecp_to_wstr(str, plen) mbstr_to_wstr(filecp(), str, -1, plen)
1334#define wstr_to_filecp(str, plen) wstr_to_mbstr(filecp(), str, -1, plen)
1335#define utf8_to_wstr(str, plen) mbstr_to_wstr(CP_UTF8, str, -1, plen)
1336#define wstr_to_utf8(str, plen) wstr_to_mbstr(CP_UTF8, str, -1, plen)
1340w32_spawn(
int mode,
const char *cmd,
const char *prog, UINT cp)
1342 char fbuf[PATH_MAX];
1344 const char *shell = NULL;
1345 WCHAR *wcmd = NULL, *wshell = NULL;
1351 char *cmd_sep = NULL;
1353 if (check_spawn_mode(mode))
return -1;
1356 if (!(p = dln_find_exe_r(prog, NULL, fbuf,
sizeof(fbuf)))) {
1361 translate_char(p,
'/',
'\\', cp);
1368 if ((shell = w32_getenv(
"RUBYSHELL", cp)) && (redir = has_redirection(cmd, cp))) {
1369 size_t shell_len = strlen(shell);
1370 size_t cmd_len = strlen(cmd) +
sizeof(
" -c ") + 2;
1371 char *tmp =
ALLOCV(v, shell_len + cmd_len);
1372 memcpy(tmp, shell, shell_len + 1);
1373 translate_char(tmp,
'/',
'\\', cp);
1374 snprintf(tmp + shell_len, cmd_len,
" -c \"%s\"", cmd);
1377 else if ((shell = w32_getenv(
"COMSPEC", cp)) &&
1378 (nt = !is_command_com(shell),
1379 (redir < 0 ? has_redirection(cmd, cp) : redir) ||
1380 is_internal_cmd(cmd, nt))) {
1381 size_t cmd_len = strlen(shell) + strlen(cmd) +
sizeof(
" /c ") + (nt ? 2 : 0);
1382 char *tmp =
ALLOCV(v, cmd_len);
1383 snprintf(tmp, cmd_len, nt ?
"%s /c \"%s\"" :
"%s /c %s", shell, cmd);
1387 int len = 0, quote = (*cmd ==
'"') ?
'"' : (*cmd ==
'\'') ?
'\'' : 0;
1389 for (prog = cmd + !!quote;; prog = CharNextExA(cp, prog, 0)) {
1390 if (*prog ==
'/') slash = 1;
1394 STRNDUPV(p, v2, cmd,
len);
1400 if ((
unsigned char)*prog == quote) {
1401 len = prog++ - cmd - 1;
1402 STRNDUPV(p, v2, cmd + 1,
len);
1406 if (quote)
continue;
1407 if (
ISSPACE(*prog) || strchr(
"<>|*?\"", *prog)) {
1409 STRNDUPV(p, v2, cmd,
len + (slash ? strlen(prog) : 0));
1412 sep = *(cmd_sep = &p[
len]);
1419 shell = dln_find_exe_r(shell, NULL, fbuf,
sizeof(fbuf));
1420 if (p && slash) translate_char(p,
'/',
'\\', cp);
1422 shell = p ? p : cmd;
1425 len = strlen(shell);
1426 if (strchr(shell,
' ')) quote = -1;
1427 if (shell == fbuf) {
1430 else if (shell != p && strchr(shell,
'/')) {
1431 STRNDUPV(p, v2, shell,
len);
1434 if (p) translate_char(p,
'/',
'\\', cp);
1435 if (is_batch(shell)) {
1436 int alen = strlen(prog);
1437 cmd = p =
ALLOCV(v,
len + alen + (quote ? 2 : 0) + 1);
1438 if (quote) *p++ =
'"';
1439 memcpy(p, shell,
len);
1441 if (quote) *p++ =
'"';
1442 memcpy(p, prog, alen + 1);
1449 if (!e && shell && !(wshell = mbstr_to_wstr(cp, shell, -1, NULL))) e = E2BIG;
1450 if (cmd_sep) *cmd_sep = sep;
1451 if (!e && cmd && !(wcmd = mbstr_to_wstr(cp, cmd, -1, NULL))) e = E2BIG;
1457 if (CreateChild(child, wcmd, wshell, NULL, NULL, NULL, 0)) {
1458 ret = child_result(child, mode);
1469rb_w32_spawn(
int mode,
const char *cmd,
const char *prog)
1472 return w32_spawn(mode, cmd, prog, filecp());
1477rb_w32_uspawn(
int mode,
const char *cmd,
const char *prog)
1479 return w32_spawn(mode, cmd, prog, CP_UTF8);
1484w32_spawn_process(
int mode,
const char *prog,
char *
const *argv,
1485 int in_fd,
int out_fd,
int err_fd, DWORD flags, UINT cp)
1489 BOOL ntcmd = FALSE, tmpnt;
1491 char *cmd, fbuf[PATH_MAX];
1492 WCHAR *wcmd = NULL, *wprog = NULL;
1496 HANDLE in_handle = NULL, out_handle = NULL, err_handle = NULL;
1498 if (check_spawn_mode(mode))
return -1;
1501 in_handle = (HANDLE)rb_w32_get_osfhandle(in_fd);
1504 out_handle = (HANDLE)rb_w32_get_osfhandle(out_fd);
1507 err_handle = (HANDLE)rb_w32_get_osfhandle(err_fd);
1510 if (!prog) prog = argv[0];
1511 if ((shell = w32_getenv(
"COMSPEC", cp)) &&
1512 internal_cmd_match(prog, tmpnt = !is_command_com(shell))) {
1517 else if ((cmd = dln_find_exe_r(prog, NULL, fbuf,
sizeof(fbuf)))) {
1518 if (cmd == prog) strlcpy(cmd = fbuf, prog,
sizeof(fbuf));
1519 translate_char(cmd,
'/',
'\\', cp);
1522 else if (strchr(prog,
'/')) {
1524 if (
len <
sizeof(fbuf))
1525 strlcpy(cmd = fbuf, prog,
sizeof(fbuf));
1527 STRNDUPV(cmd, v, prog,
len);
1528 translate_char(cmd,
'/',
'\\', cp);
1531 if (c_switch || is_batch(prog)) {
1533 progs[0] = (
char *)prog;
1535 len = join_argv(NULL, progs, ntcmd, cp, 1, FALSE);
1536 if (c_switch)
len += 3;
1538 if (argv[0])
len += join_argv(NULL, argv, ntcmd, cp, 0, FALSE);
1540 join_argv(cmd, progs, ntcmd, cp, 1, FALSE);
1541 if (c_switch) strlcat(cmd,
" /c",
len);
1542 if (argv[0]) join_argv(cmd + strlcat(cmd,
" ",
len), argv, ntcmd, cp, 0, FALSE);
1543 prog = c_switch ? shell : 0;
1546 len = join_argv(NULL, argv, FALSE, cp, 1, TRUE);
1548 join_argv(cmd, argv, FALSE, cp, 1, TRUE);
1551 if (!e && cmd && !(wcmd = mbstr_to_wstr(cp, cmd, -1, NULL))) e = E2BIG;
1553 if (!e && prog && !(wprog = mbstr_to_wstr(cp, prog, -1, NULL))) e = E2BIG;
1557 if (CreateChild(child, wcmd, wprog, in_handle, out_handle, err_handle, flags)) {
1558 ret = child_result(child, mode);
1569rb_w32_aspawn_flags(
int mode,
const char *prog,
char *
const *argv, DWORD flags)
1572 return w32_spawn_process(mode, prog, argv, -1, -1, -1, flags, filecp());
1577rb_w32_uaspawn_flags(
int mode,
const char *prog,
char *
const *argv, DWORD flags)
1579 return w32_spawn_process(mode, prog, argv, -1, -1, -1, flags, CP_UTF8);
1584rb_w32_aspawn(
int mode,
const char *prog,
char *
const *argv)
1586 return w32_spawn_process(mode, prog, argv, -1, -1, -1, 0, filecp());
1591rb_w32_uaspawn(
int mode,
const char *prog,
char *
const *argv)
1593 return rb_w32_uaspawn_flags(mode, prog, argv, 0);
1598rb_w32_uspawn_process(
int mode,
const char *prog,
char *
const *argv,
1599 int in_fd,
int out_fd,
int err_fd, DWORD flags)
1601 return w32_spawn_process(mode, prog, argv, in_fd, out_fd, err_fd,
1623insert(
const char *path,
VALUE vinfo,
void *enc)
1629 if (!tmpcurr)
return -1;
1631 tmpcurr->len = strlen(path);
1632 tmpcurr->str =
strdup(path);
1633 if (!tmpcurr->str)
return -1;
1634 tmpcurr->flags |= NTMALLOC;
1636 *tail = &tmpcurr->next;
1645 char buffer[PATH_MAX], *buf = buffer;
1649 if (patt->len >= PATH_MAX)
1650 if (!(buf = malloc(patt->len + 1)))
return 0;
1652 memcpy(buf, patt->str, patt->len);
1653 buf[patt->len] =
'\0';
1654 translate_char(buf,
'\\',
'/', cp);
1655 status = ruby_brace_glob_with_enc(buf, 0, insert, (
VALUE)&tail, enc);
1659 if (status || last == tail)
return 0;
1660 if (patt->flags & NTMALLOC)
1673has_redirection(
const char *cmd, UINT cp)
1683 for (ptr = cmd; *ptr;) {
1689 else if (quote == *ptr)
1705 if (*++ptr !=
'_' && !
ISALPHA(*ptr))
break;
1706 while (*++ptr ==
'_' ||
ISALNUM(*ptr));
1707 if (*ptr && *ptr++ ==
'%')
return TRUE;
1713 ptr = CharNextExA(cp, ptr, 0);
1721static inline WCHAR *
1722skipspace(WCHAR *ptr)
1731w32_cmdvector(
const WCHAR *cmd,
char ***vec, UINT cp,
rb_encoding *enc)
1734 int elements, strsz, done;
1735 int slashes, escape;
1736 WCHAR *ptr, *base, *cmdline;
1737 char *cptr, *buffer;
1753 ptr = cmdline = wcsdup(cmd);
1764 while (*(ptr = skipspace(ptr))) {
1766 quote = slashes = globbing = escape = 0;
1767 for (done = 0; !done && *ptr; ) {
1776 if (quote != L
'\'') slashes++;
1817 if (!(slashes & 1)) {
1820 else if (quote == *ptr) {
1821 if (quote == L
'"' && quote == ptr[1])
1831 ptr = CharNextW(ptr);
1854 slashes = quote = 0;
1855 while (p < base +
len) {
1859 if (quote != L
'\'') slashes++;
1864 if (!(slashes & 1) && quote && quote != c) {
1869 memcpy(p - ((slashes + 1) >> 1), p + (~slashes & 1),
1870 sizeof(WCHAR) * (base +
len - p));
1871 len -= ((slashes + 1) >> 1) + (~slashes & 1);
1872 p -= (slashes + 1) >> 1;
1873 if (!(slashes & 1)) {
1875 if (quote == L
'"' && quote == *p)
1896 if (!curr)
goto do_nothing;
1897 curr->str = rb_w32_wstr_to_mbstr(cp, base,
len, &curr->len);
1898 curr->flags |= NTMALLOC;
1900 if (globbing && (tail = cmdglob(curr, cmdtail, cp, enc))) {
1905 cmdtail = &curr->next;
1915 for (elements = 0, strsz = 0, curr = cmdhead; curr; curr = curr->next) {
1917 strsz += (curr->len + 1);
1920 len = (elements+1)*
sizeof(
char *) + strsz;
1921 buffer = (
char *)malloc(
len);
1924 while ((curr = cmdhead) != 0) {
1925 cmdhead = curr->next;
1926 if (curr->flags & NTMALLOC) free(curr->str);
1930 for (vptr = *vec; *vptr; ++vptr);
1946 vptr = (
char **) buffer;
1948 cptr = buffer + (elements+1) *
sizeof(
char *);
1950 while ((curr = cmdhead) != 0) {
1951 memcpy(cptr, curr->str, curr->len);
1952 cptr[curr->len] =
'\0';
1954 cptr += curr->len + 1;
1955 cmdhead = curr->next;
1956 if (curr->flags & NTMALLOC) free(curr->str);
1961 *vec = (
char **) buffer;
1973open_special(
const WCHAR *path, DWORD access, DWORD flags)
1975 const DWORD share_mode =
1976 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
1977 return CreateFileW(path, access, share_mode, NULL, OPEN_EXISTING,
1978 FILE_FLAG_BACKUP_SEMANTICS|flags, NULL);
1988#define GetBit(bits, i) ((bits)[(i) / CHAR_BIT] & (1 << (i) % CHAR_BIT))
1989#define SetBit(bits, i) ((bits)[(i) / CHAR_BIT] |= (1 << (i) % CHAR_BIT))
1991#define BitOfIsDir(n) ((n) * 2)
1992#define BitOfIsRep(n) ((n) * 2 + 1)
1993#define DIRENT_PER_CHAR (CHAR_BIT / 2)
1995static const WCHAR namespace_prefix[] = {L
'\\', L
'\\', L
'?', L
'\\'};
2001get_handle_pathname(HANDLE fh, WCHAR **pathptr, DWORD add)
2003 DWORD
len = GetFinalPathNameByHandleW(fh, NULL, 0, 0);
2005 WCHAR *path = malloc((
len + add + 1) *
sizeof(WCHAR));
2006 if (!(*pathptr = path))
return 0;
2007 len = GetFinalPathNameByHandleW(fh, path,
len + 1, 0);
2017open_dir_handle(
const WCHAR *filename, WIN32_FIND_DATAW *fd)
2021 WCHAR *fullname = 0;
2029 fh = open_special(filename, 0, 0);
2030 if (fh != INVALID_HANDLE_VALUE) {
2031 len = get_handle_pathname(fh, &fullname, wildcard_len);
2035 len = lstrlenW(filename);
2036 fullname = malloc((
len + wildcard_len + 1) *
sizeof(WCHAR));
2037 if (!fullname)
return INVALID_HANDLE_VALUE;
2043 p = &fullname[
len-1];
2044 if (!(isdirsep(*p) || *p == L
':')) *++p = L
'\\';
2051 fh = FindFirstFileW(fullname, fd);
2052 if (fh == INVALID_HANDLE_VALUE) {
2053 errno = map_errno(GetLastError());
2061w32_wopendir(
const WCHAR *wpath)
2064 WIN32_FIND_DATAW fd;
2077 if (wstati128(wpath, &sbuf, FALSE) < 0) {
2080 if (!(sbuf.st_mode & S_IFDIR) &&
2081 (!
ISALPHA(wpath[0]) || wpath[1] != L
':' || wpath[2] != L
'\0' ||
2082 ((1 << ((wpath[0] & 0x5f) -
'A')) & GetLogicalDrives()) == 0)) {
2086 fh = open_dir_handle(wpath, &fd);
2087 if (fh == INVALID_HANDLE_VALUE) {
2094 p = calloc(1,
sizeof(
DIR));
2098 pathlen = lstrlenW(wpath);
2108 len = lstrlenW(fd.cFileName) + 1;
2109 altlen = lstrlenW(fd.cAlternateFileName) + 1;
2115 tmpW = realloc(p->start, (idx +
len + altlen) *
sizeof(WCHAR));
2125 memcpy(&p->start[idx], fd.cFileName,
len *
sizeof(WCHAR));
2126 memcpy(&p->start[idx +
len], fd.cAlternateFileName, altlen *
sizeof(WCHAR));
2128 if (p->nfiles % DIRENT_PER_CHAR == 0) {
2129 tmp = realloc(p->bits, p->nfiles / DIRENT_PER_CHAR + 1);
2133 p->bits[p->nfiles / DIRENT_PER_CHAR] = 0;
2135 if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
2136 SetBit(p->bits, BitOfIsDir(p->nfiles));
2137 if (fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
2138 WCHAR *tmppath = malloc((pathlen +
len + 1) *
sizeof(WCHAR));
2139 memcpy(tmppath, wpath, pathlen *
sizeof(WCHAR));
2140 tmppath[pathlen] = L
'\\';
2141 memcpy(tmppath + pathlen + 1, fd.cFileName,
len *
sizeof(WCHAR));
2142 if (rb_w32_reparse_symlink_p(tmppath))
2143 SetBit(p->bits, BitOfIsRep(p->nfiles));
2148 idx +=
len + altlen;
2149 }
while (FindNextFileW(fh, &fd));
2160 UINT cp = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
2166rb_w32_wstr_to_mbstr(UINT cp,
const WCHAR *wstr,
int clen,
long *plen)
2169 int len = WideCharToMultiByte(cp, 0, wstr, clen, NULL, 0, NULL, NULL);
2170 if (!(ptr = malloc(
len)))
return 0;
2171 WideCharToMultiByte(cp, 0, wstr, clen, ptr,
len, NULL, NULL);
2174 if (clen == -1) --
len;
2182rb_w32_mbstr_to_wstr(UINT cp,
const char *str,
int clen,
long *plen)
2185 int len = MultiByteToWideChar(cp, 0, str, clen, NULL, 0);
2186 if (!(ptr = malloc(
sizeof(WCHAR) *
len)))
return 0;
2187 MultiByteToWideChar(cp, 0, str, clen, ptr,
len);
2190 if (clen == -1) --
len;
2198rb_w32_opendir(
const char *filename)
2201 WCHAR *wpath = filecp_to_wstr(filename, NULL);
2204 ret = w32_wopendir(wpath);
2211rb_w32_uopendir(
const char *filename)
2214 WCHAR *wpath = utf8_to_wstr(filename, NULL);
2217 ret = w32_wopendir(wpath);
2228move_to_next_entry(
DIR *dirp)
2232 dirp->curr += lstrlenW(dirp->curr) + 1;
2233 dirp->curr += lstrlenW(dirp->curr) + 1;
2234 if (dirp->curr >= (dirp->start + dirp->size)) {
2246win32_direct_conv(
const WCHAR *file,
const WCHAR *alt,
struct direct *entry,
const void *enc)
2248 UINT cp = *((UINT *)enc);
2249 if (!(entry->d_name = wstr_to_mbstr(cp, file, -1, &entry->d_namlen)))
2253 entry->d_altname = wstr_to_mbstr(cp, alt, -1, &altlen);
2254 entry->d_altlen = altlen;
2261rb_w32_conv_from_wchar(
const WCHAR *wstr,
rb_encoding *enc)
2264 long len = lstrlenW(wstr);
2265 int encindex = rb_enc_to_index(enc);
2267 if (encindex == ENCINDEX_UTF_16LE) {
2268 return rb_enc_str_new((
char *)wstr,
len *
sizeof(WCHAR), enc);
2271#if SIZEOF_INT < SIZEOF_LONG
2272# error long should equal to int on Windows
2275 len = WideCharToMultiByte(CP_UTF8, 0, wstr, clen, NULL, 0, NULL, NULL);
2276 src = rb_enc_str_new(0,
len, rb_enc_from_index(ENCINDEX_UTF_8));
2277 WideCharToMultiByte(CP_UTF8, 0, wstr, clen, RSTRING_PTR(src),
len, NULL, NULL);
2280 case ENCINDEX_ASCII_8BIT:
2281 case ENCINDEX_US_ASCII:
2283 case ENCINDEX_UTF_8:
2292rb_w32_conv_from_wstr(
const WCHAR *wstr,
long *lenp,
rb_encoding *enc)
2294 VALUE str = rb_w32_conv_from_wchar(wstr, enc);
2298 if (
NIL_P(str))
return wstr_to_utf8(wstr, lenp);
2299 *lenp =
len = RSTRING_LEN(str);
2300 memcpy(ptr = malloc(
len + 1), RSTRING_PTR(str),
len);
2307ruby_direct_conv(
const WCHAR *file,
const WCHAR *alt,
struct direct *entry,
const void *enc)
2309 if (!(entry->d_name = rb_w32_conv_from_wstr(file, &entry->d_namlen, enc)))
2313 entry->d_altname = rb_w32_conv_from_wstr(alt, &altlen, enc);
2314 entry->d_altlen = altlen;
2321readdir_internal(
DIR *dirp, BOOL (*conv)(
const WCHAR *,
const WCHAR *,
struct direct *,
const void *),
const void *enc)
2323 static long dummy_ino = 0;
2330 free(dirp->dirstr.d_name);
2331 free(dirp->dirstr.d_altname);
2332 dirp->dirstr.d_altname = 0;
2333 dirp->dirstr.d_altlen = 0;
2334 conv(dirp->curr, dirp->curr + lstrlenW(dirp->curr) + 1, &dirp->dirstr, enc);
2339 dirp->dirstr.d_ino = (ino_t)(InterlockedIncrement(&dummy_ino) - 1);
2345 if (GetBit(dirp->bits, BitOfIsRep(dirp->loc)))
2346 dirp->dirstr.d_type = DT_LNK;
2347 else if (GetBit(dirp->bits, BitOfIsDir(dirp->loc)))
2348 dirp->dirstr.d_type = DT_DIR;
2350 dirp->dirstr.d_type = DT_REG;
2356 move_to_next_entry(dirp);
2358 return &(dirp->dirstr);
2369 int idx = rb_enc_to_index(enc);
2370 if (idx == ENCINDEX_ASCII_8BIT) {
2371 const UINT cp = filecp();
2372 return readdir_internal(dirp, win32_direct_conv, &cp);
2374 else if (idx == ENCINDEX_UTF_8) {
2375 const UINT cp = CP_UTF8;
2376 return readdir_internal(dirp, win32_direct_conv, &cp);
2379 return readdir_internal(dirp, ruby_direct_conv, enc);
2384rb_w32_ureaddir(
DIR *dirp)
2386 const UINT cp = CP_UTF8;
2387 return readdir_internal(dirp, win32_direct_conv, &cp);
2396rb_w32_telldir(
DIR *dirp)
2407rb_w32_seekdir(
DIR *dirp,
long loc)
2409 if (dirp->loc > loc) rb_w32_rewinddir(dirp);
2411 while (dirp->curr && dirp->loc < loc) {
2412 move_to_next_entry(dirp);
2422rb_w32_rewinddir(
DIR *dirp)
2424 dirp->curr = dirp->start;
2434rb_w32_closedir(
DIR *dirp)
2437 free(dirp->dirstr.d_name);
2438 free(dirp->dirstr.d_altname);
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
2467typedef char lowio_text_mode;
2468typedef char lowio_pipe_lookahead[3];
2471 CRITICAL_SECTION lock;
2474 unsigned char osfile;
2475 lowio_text_mode textmode;
2476 lowio_pipe_lookahead _pipe_lookahead;
2478 uint8_t unicode : 1;
2479 uint8_t utf8translations : 1;
2480 uint8_t dbcsBufferUsed : 1;
2484#if !defined _CRTIMP || defined __MINGW32__
2486#define _CRTIMP __declspec(dllimport)
2489static ioinfo ** __pioinfo = NULL;
2491static inline ioinfo* _pioinfo(
int);
2494#define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
2495#define _osfhnd(i) (_pioinfo(i)->osfhnd)
2496#define _osfile(i) (_pioinfo(i)->osfile)
2497#define rb_acrt_lowio_lock_fh(i) EnterCriticalSection(&_pioinfo(i)->lock)
2498#define rb_acrt_lowio_unlock_fh(i) LeaveCriticalSection(&_pioinfo(i)->lock)
2500static size_t pioinfo_extra = 0;
2504set_pioinfo_extra(
void)
2506#define FUNCTION_RET 0xc3
2508# define UCRTBASE "ucrtbased.dll"
2510# define UCRTBASE "ucrtbase.dll"
2525 char *p = (
char*)get_proc_address(UCRTBASE,
"_isatty", NULL);
2528#if defined(_M_ARM64) || defined(__aarch64__)
2529#define IS_INSN(pc, name) ((*(pc) & name##_mask) == name##_id)
2530 const int max_num_inst = 500;
2531 uint32_t *start = (uint32_t*)p;
2532 uint32_t *end_limit = (start + max_num_inst);
2533 uint32_t *pc = start;
2536 fprintf(stderr,
"_isatty proc not found in " UCRTBASE
"\n");
2541 const uint32_t ret_id = 0xd65f0000;
2542 const uint32_t ret_mask = 0xfffffc1f;
2543 for(; pc < end_limit; pc++) {
2544 if (IS_INSN(pc, ret)) {
2548 if (pc == end_limit) {
2549 fprintf(stderr,
"end of _isatty not found in " UCRTBASE
"\n");
2554 const uint32_t adrp_id = 0x90000000;
2555 const uint32_t adrp_mask = 0x9f000000;
2556 const uint32_t add_id = 0x11000000;
2557 const uint32_t add_mask = 0x7fc00000;
2558 for(; pc > start; pc--) {
2559 if (IS_INSN(pc, adrp) && IS_INSN(pc + 1, add)) {
2564 fprintf(stderr,
"pioinfo mark not found in " UCRTBASE
"\n");
2574 const uint32_t adrp_insn = *pc;
2575 const uint32_t adrp_immhi = (adrp_insn & 0x00ffffe0) >> 5;
2576 const uint32_t adrp_immlo = (adrp_insn & 0x60000000) >> (5 + 19 + 5);
2577 const int64_t adrp_sign = (adrp_insn & 0x00800000) ? ~0x001fffff : 0;
2579 const int64_t adrp_imm = (adrp_sign | (adrp_immhi << 2) | adrp_immlo) << 12;
2581 const uint64_t adrp_base = (uint64_t)pc & 0xfffffffffffff000;
2583 const uint32_t add_insn = *(pc + 1);
2584 const uint64_t add_imm = (add_insn & 0x3ffc00) >> (5 + 5);
2586 __pioinfo = (
ioinfo**)(adrp_base + adrp_imm + add_imm);
2594# define FUNCTION_BEFORE_RET_MARK "\x48\x83\xc4"
2595# define FUNCTION_SKIP_BYTES 1
2598# define PIOINFO_MARK "\x48\x8d\x0d"
2601# define PIOINFO_MARK "\x48\x8d\x15"
2606# define FUNCTION_BEFORE_RET_MARK "\x5d"
2608# define FUNCTION_BEFORE_RET_MARK_2 "\xc9"
2609# define FUNCTION_SKIP_BYTES 0
2611# define PIOINFO_MARK "\x8B\x04\x85"
2614 for (pend += 10; pend < p + 500; pend++) {
2616 if ((memcmp(pend, FUNCTION_BEFORE_RET_MARK,
sizeof(FUNCTION_BEFORE_RET_MARK) - 1) == 0
2617# ifdef FUNCTION_BEFORE_RET_MARK_2
2618 || memcmp(pend, FUNCTION_BEFORE_RET_MARK_2,
sizeof(FUNCTION_BEFORE_RET_MARK_2) - 1) == 0
2621 *(pend + (
sizeof(FUNCTION_BEFORE_RET_MARK) - 1) + FUNCTION_SKIP_BYTES) == (
char)FUNCTION_RET) {
2623 for (pend -= (
sizeof(PIOINFO_MARK) - 1); pend > p; pend--) {
2624 if (memcmp(pend, PIOINFO_MARK,
sizeof(PIOINFO_MARK) - 1) == 0) {
2633 fprintf(stderr,
"unexpected " UCRTBASE
"\n");
2637 p +=
sizeof(PIOINFO_MARK) - 1;
2639 rel = *(int32_t*)(p);
2640 rip = p +
sizeof(int32_t);
2641 __pioinfo = (
ioinfo**)(rip + rel);
2643 __pioinfo = *(
ioinfo***)(p);
2648 fd = _open(
"NUL", O_RDONLY);
2649 for (pioinfo_extra = 0; pioinfo_extra <= 64; pioinfo_extra +=
sizeof(
void *)) {
2650 if (_osfhnd(fd) == _get_osfhandle(fd)) {
2656 if (pioinfo_extra > 64) {
2665 const size_t sizeof_ioinfo =
sizeof(
ioinfo) + pioinfo_extra;
2666 return (
ioinfo*)((
char*)__pioinfo[fd >> IOINFO_L2E] +
2667 (fd & (IOINFO_ARRAY_ELTS - 1)) * sizeof_ioinfo);
2670#define _set_osfhnd(fh, osfh) (void)(_osfhnd(fh) = osfh)
2671#define _set_osflags(fh, flags) (_osfile(fh) = (flags))
2676#define FNOINHERIT 0x10
2681static int is_socket(SOCKET);
2682static int is_console(SOCKET);
2686rb_w32_io_cancelable_p(
int fd)
2688 return is_socket(TO_SOCKET(fd)) || !is_console(TO_SOCKET(fd));
2693rb_w32_open_osfhandle(intptr_t osfhandle,
int flags)
2702 if (flags & O_APPEND)
2703 fileflags |= FAPPEND;
2708 if (flags & O_NOINHERIT)
2709 fileflags |= FNOINHERIT;
2712 hF = CreateFile(
"NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
2713 fh = _open_osfhandle((intptr_t)hF, 0);
2721 rb_acrt_lowio_lock_fh(fh);
2723 _set_osfhnd(fh, osfhandle);
2727 _set_osflags(fh, fileflags);
2728 rb_acrt_lowio_unlock_fh(fh);
2739#define open_null(fd) \
2741 (nullfd = open("NUL", O_RDWR)) : 0), \
2742 ((nullfd == (fd)) ? (keep = 1) : dup2(nullfd, fd)), \
2745 if (fileno(stdin) < 0) {
2746 FILE_FILENO(stdin) = open_null(0);
2749 setmode(fileno(stdin), O_BINARY);
2751 if (fileno(stdout) < 0) {
2752 FILE_FILENO(stdout) = open_null(1);
2754 if (fileno(stderr) < 0) {
2755 FILE_FILENO(stderr) = open_null(2);
2757 if (nullfd >= 0 && !keep) close(nullfd);
2758 setvbuf(stderr, NULL, _IONBF, 0);
2761 HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
2763 if (GetConsoleMode(h, &m)) {
2764#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
2765#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x4
2767 SetConsoleMode(h, m | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
2776is_socket(SOCKET sock)
2778 if (socklist_lookup(sock, NULL))
2786rb_w32_is_socket(
int fd)
2788 return is_socket(TO_SOCKET(fd));
2801rb_w32_strerror(
int e)
2803 static char buffer[512];
2808 strlcpy(buffer,
"Unknown Error",
sizeof(buffer));
2809 else if (e > sys_nerr) {
2810#if WSAEWOULDBLOCK != EWOULDBLOCK
2811 if (e >= EADDRINUSE && e <= EWOULDBLOCK) {
2815 for (s = 0; s < (int)(
sizeof(errmap)/
sizeof(*errmap)); s++)
2816 if (errmap[s].winerr == WSAEWOULDBLOCK)
2818 for (i = s; i < (int)(
sizeof(errmap)/
sizeof(*errmap)); i++)
2819 if (errmap[i].err == e) {
2820 e = errmap[i].winerr;
2825 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
2826 FORMAT_MESSAGE_IGNORE_INSERTS, &source, e,
2827 MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
2828 buffer,
sizeof(buffer), NULL) == 0 &&
2829 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
2830 FORMAT_MESSAGE_IGNORE_INSERTS, &source, e, 0,
2831 buffer,
sizeof(buffer), NULL) == 0)
2832 strlcpy(buffer,
"Unknown Error",
sizeof(buffer));
2835 strlcpy(buffer, strerror(e),
sizeof(buffer));
2838 while ((p = strpbrk(p,
"\r\n")) != NULL) {
2839 memmove(p, p + 1, strlen(p));
2890 return (uid == ROOT_UID ? 0 : -1);
2897 return (gid == ROOT_GID ? 0 : -1);
2906ioctl(
int i,
int u, ...)
2913rb_w32_fdset(
int fd, fd_set *set)
2922rb_w32_fdclr(
int fd, fd_set *set)
2925 SOCKET s = TO_SOCKET(fd);
2927 for (i = 0; i < set->fd_count; i++) {
2928 if (set->fd_array[i] == s) {
2929 memmove(&set->fd_array[i], &set->fd_array[i+1],
2930 sizeof(set->fd_array[0]) * (--set->fd_count - i));
2940rb_w32_fdisset(
int fd, fd_set *set)
2943 SOCKET s = TO_SOCKET(fd);
2944 if (s == (SOCKET)INVALID_HANDLE_VALUE)
2946 RUBY_CRITICAL {ret = __WSAFDIsSet(s, set);}
2954 max = min(src->fd_count, (UINT)max);
2955 if ((UINT)dst->
capa < (UINT)max) {
2956 dst->
capa = (src->fd_count / FD_SETSIZE + 1) * FD_SETSIZE;
2960 memcpy(dst->
fdset->fd_array, src->fd_array,
2961 max *
sizeof(src->fd_array[0]));
2962 dst->
fdset->fd_count = src->fd_count;
2969 if ((UINT)dst->
capa < src->
fdset->fd_count) {
2970 dst->
capa = (src->
fdset->fd_count / FD_SETSIZE + 1) * FD_SETSIZE;
2974 memcpy(dst->
fdset->fd_array, src->
fdset->fd_array,
2975 src->
fdset->fd_count *
sizeof(src->
fdset->fd_array[0]));
2989extract_fd(
rb_fdset_t *dst, fd_set *src,
int (*func)(SOCKET))
2995 while (s < src->fd_count) {
2996 SOCKET fd = src->fd_array[s];
2998 if (!func || (*func)(fd)) {
3002 for (d = 0; d < dst->
fdset->fd_count; d++) {
3003 if (dst->
fdset->fd_array[d] == fd)
3006 if (d == dst->
fdset->fd_count) {
3007 if ((
int)dst->
fdset->fd_count >= dst->
capa) {
3008 dst->
capa = (dst->
fdset->fd_count / FD_SETSIZE + 1) * FD_SETSIZE;
3011 dst->
fdset->fd_array[dst->
fdset->fd_count++] = fd;
3015 &src->fd_array[s+1],
3016 sizeof(src->fd_array[0]) * (--src->fd_count - s));
3026 return dst ? dst->
fdset->fd_count : m;
3031copy_fd(fd_set *dst, fd_set *src)
3034 if (!src || !dst)
return 0;
3036 for (s = 0; s < src->fd_count; ++s) {
3037 SOCKET fd = src->fd_array[s];
3039 for (d = 0; d < dst->fd_count; ++d) {
3040 if (dst->fd_array[d] == fd)
3043 if (d == dst->fd_count && d < FD_SETSIZE) {
3044 dst->fd_array[dst->fd_count++] = fd;
3048 return dst->fd_count;
3053is_not_socket(SOCKET sock)
3055 return !is_socket(sock);
3065 ret = (GetFileType((HANDLE)sock) == FILE_TYPE_PIPE);
3073is_readable_pipe(SOCKET sock)
3079 if (PeekNamedPipe((HANDLE)sock, NULL, 0, NULL, &n, NULL)) {
3083 ret = (GetLastError() == ERROR_BROKEN_PIPE);
3092is_console(SOCKET sock)
3099 ret = (PeekConsoleInputW((HANDLE)sock, &ir, 1, &n));
3107is_readable_console(SOCKET sock)
3114 if (PeekConsoleInputW((HANDLE)sock, &ir, 1, &n) && n > 0) {
3115 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
3116 ir.Event.KeyEvent.uChar.UnicodeChar) {
3119 else if (ir.EventType == KEY_EVENT && !ir.Event.KeyEvent.bKeyDown &&
3120 ir.Event.KeyEvent.wVirtualKeyCode == VK_MENU &&
3121 ir.Event.KeyEvent.uChar.UnicodeChar) {
3125 ReadConsoleInputW((HANDLE)sock, &ir, 1, &n);
3135is_invalid_handle(SOCKET sock)
3137 return (HANDLE)sock == INVALID_HANDLE_VALUE;
3142do_select(
int nfds, fd_set *rd, fd_set *wr, fd_set *ex,
3149 rb_w32_sleep(timeout->tv_sec * 1000 + timeout->tv_usec / 1000);
3151 rb_w32_sleep(INFINITE);
3155 thread_exclusive(select) {
3156 r = select(nfds, rd, wr, ex, timeout);
3158 if (r == SOCKET_ERROR) {
3159 errno = map_errno(WSAGetLastError());
3174rb_w32_time_subtract(
struct timeval *rest,
const struct timeval *wait)
3176 if (rest->tv_sec < wait->tv_sec) {
3179 while (rest->tv_usec < wait->tv_usec) {
3180 if (rest->tv_sec <= wait->tv_sec) {
3184 rest->tv_usec += 1000 * 1000;
3186 rest->tv_sec -= wait->tv_sec;
3187 rest->tv_usec -= wait->tv_usec;
3188 return rest->tv_sec != 0 || rest->tv_usec != 0;
3195 if (t1->tv_sec < t2->tv_sec)
3197 if (t1->tv_sec > t2->tv_sec)
3199 if (t1->tv_usec < t2->tv_usec)
3201 if (t1->tv_usec > t2->tv_usec)
3208int rb_w32_check_interrupt(
void *);
3213rb_w32_select_with_thread(
int nfds, fd_set *rd, fd_set *wr, fd_set *ex,
3214 struct timeval *timeout,
void *th)
3223 struct timeval limit = {0, 0};
3225 if (nfds < 0 || (timeout && (timeout->tv_sec < 0 || timeout->tv_usec < 0))) {
3231 if (timeout->tv_sec < 0 ||
3232 timeout->tv_usec < 0 ||
3233 timeout->tv_usec >= 1000000) {
3237 gettimeofday(&limit, NULL);
3238 limit.tv_sec += timeout->tv_sec;
3239 limit.tv_usec += timeout->tv_usec;
3240 if (limit.tv_usec >= 1000000) {
3241 limit.tv_usec -= 1000000;
3253 nonsock += extract_fd(&else_rd, rd, is_not_socket);
3256 nonsock += extract_fd(&else_wr, wr, is_not_socket);
3259 if (extract_fd(NULL, else_rd.
fdset, is_invalid_handle) > 0 ||
3260 extract_fd(NULL, else_wr.
fdset, is_invalid_handle) > 0) {
3268 extract_fd(&pipe_rd, else_rd.
fdset, is_pipe);
3271 extract_fd(&cons_rd, else_rd.
fdset, is_console);
3274 extract_fd(&except, ex, is_not_socket);
3277 if (rd && (
int)rd->fd_count > r) r = (int)rd->fd_count;
3278 if (wr && (
int)wr->fd_count > r) r = (int)wr->fd_count;
3279 if (ex && (
int)ex->fd_count > r) r = (int)ex->fd_count;
3280 if (nfds > r) nfds = r;
3284 const struct timeval wait = {0, 10 * 1000};
3287 if (th && rb_w32_check_interrupt(th) != WAIT_TIMEOUT) {
3294 extract_fd(&else_rd, pipe_rd.
fdset, is_readable_pipe);
3295 extract_fd(&else_rd, cons_rd.
fdset, is_readable_console);
3298 if (else_rd.
fdset->fd_count || else_wr.
fdset->fd_count) {
3299 r = do_select(nfds, rd, wr, ex, &zero);
3301 r += copy_fd(rd, else_rd.
fdset);
3302 r += copy_fd(wr, else_wr.
fdset);
3308 const struct timeval *dowait = &wait;
3318 if (rd) copy_fd(&orig_rd, rd);
3319 if (wr) copy_fd(&orig_wr, wr);
3320 if (ex) copy_fd(&orig_ex, ex);
3321 r = do_select(nfds, rd, wr, ex, &zero);
3323 if (rd) copy_fd(rd, &orig_rd);
3324 if (wr) copy_fd(wr, &orig_wr);
3325 if (ex) copy_fd(ex, &orig_ex);
3329 gettimeofday(&now, NULL);
3331 if (!rb_w32_time_subtract(&rest, &now))
break;
3332 if (compare(&rest, &wait) < 0) dowait = &rest;
3334 Sleep(dowait->tv_sec * 1000 + (dowait->tv_usec + 999) / 1000);
3350rb_w32_select(
int nfds, fd_set *rd, fd_set *wr, fd_set *ex,
3353 return rb_w32_select_with_thread(nfds, rd, wr, ex, timeout, 0);
3358get_wsa_extension_function(SOCKET s, GUID guid)
3363 WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, &guid,
sizeof(guid),
3364 &ptr,
sizeof(ptr), &dmy, NULL, NULL);
3374rb_w32_accept(
int s,
struct sockaddr *addr,
int *addrlen)
3380 r = accept(TO_SOCKET(s), addr, addrlen);
3381 if (r != INVALID_SOCKET) {
3382 SetHandleInformation((HANDLE)r, HANDLE_FLAG_INHERIT, 0);
3383 fd = rb_w32_open_osfhandle((intptr_t)r, O_RDWR|O_BINARY|O_NOINHERIT);
3385 socklist_insert(r, 0);
3390 errno = map_errno(WSAGetLastError());
3401rb_w32_bind(
int s,
const struct sockaddr *addr,
int addrlen)
3406 r = bind(TO_SOCKET(s), addr, addrlen);
3407 if (r == SOCKET_ERROR)
3408 errno = map_errno(WSAGetLastError());
3417rb_w32_connect(
int s,
const struct sockaddr *addr,
int addrlen)
3421 r = connect(TO_SOCKET(s), addr, addrlen);
3422 if (r == SOCKET_ERROR) {
3423 int err = WSAGetLastError();
3424 if (err != WSAEWOULDBLOCK)
3425 errno = map_errno(err);
3427 errno = EINPROGRESS;
3438rb_w32_getpeername(
int s,
struct sockaddr *addr,
int *addrlen)
3442 r = getpeername(TO_SOCKET(s), addr, addrlen);
3443 if (r == SOCKET_ERROR)
3444 errno = map_errno(WSAGetLastError());
3453rb_w32_getsockname(
int fd,
struct sockaddr *addr,
int *addrlen)
3458 sock = TO_SOCKET(fd);
3459 r = getsockname(sock, addr, addrlen);
3460 if (r == SOCKET_ERROR) {
3461 DWORD wsaerror = WSAGetLastError();
3462 if (wsaerror == WSAEINVAL) {
3464 if (socklist_lookup(sock, &flags)) {
3465 int af = GET_FAMILY(flags);
3467 memset(addr, 0, *addrlen);
3468 addr->sa_family = af;
3473 errno = map_errno(wsaerror);
3483rb_w32_getsockopt(
int s,
int level,
int optname,
char *optval,
int *optlen)
3487 r = getsockopt(TO_SOCKET(s), level, optname, optval, optlen);
3488 if (r == SOCKET_ERROR)
3489 errno = map_errno(WSAGetLastError());
3493 if (r == 0 && level == SOL_SOCKET && optname == SO_ERROR &&
3494 *optlen == (
int)
sizeof(
int)) {
3496 memcpy(&sockerr, optval,
sizeof(sockerr));
3497 sockerr = map_errno(sockerr);
3498 memcpy(optval, &sockerr,
sizeof(sockerr));
3507rb_w32_ioctlsocket(
int s,
long cmd, u_long *argp)
3511 r = ioctlsocket(TO_SOCKET(s), cmd, argp);
3512 if (r == SOCKET_ERROR)
3513 errno = map_errno(WSAGetLastError());
3522rb_w32_listen(
int s,
int backlog)
3526 r = listen(TO_SOCKET(s), backlog);
3527 if (r == SOCKET_ERROR)
3528 errno = map_errno(WSAGetLastError());
3540finish_overlapped_socket(BOOL input, SOCKET s, WSAOVERLAPPED *wol,
int result, DWORD *
len, DWORD size)
3545 if (result != SOCKET_ERROR)
3547 else if ((err = WSAGetLastError()) == WSA_IO_PENDING) {
3548 switch (rb_w32_wait_events_blocking(&wol->hEvent, 1, INFINITE)) {
3551 result = WSAGetOverlappedResult(s, wol, &size, TRUE, &flg);
3558 result = SOCKET_ERROR;
3561 if ((err = WSAGetLastError()) == WSAECONNABORTED && !input)
3563 else if (err == WSAEMSGSIZE && input) {
3569 errno = map_errno(err);
3571 case WAIT_OBJECT_0 + 1:
3574 CancelIo((HANDLE)s);
3579 if (err == WSAECONNABORTED && !input)
3582 errno = map_errno(err);
3585 CloseHandle(wol->hEvent);
3592overlapped_socket_io(BOOL input,
int fd,
char *buf,
int len,
int flags,
3593 struct sockaddr *addr,
int *addrlen)
3604 socklist_lookup(s, &mode);
3605 if (GET_FLAGS(mode) & O_NONBLOCK) {
3608 if (addr && addrlen)
3609 r = recvfrom(s, buf,
len, flags, addr, addrlen);
3611 r = recv(s, buf,
len, flags);
3612 if (r == SOCKET_ERROR)
3613 errno = map_errno(WSAGetLastError());
3616 if (addr && addrlen)
3617 r = sendto(s, buf,
len, flags, addr, *addrlen);
3619 r = send(s, buf,
len, flags);
3620 if (r == SOCKET_ERROR) {
3621 DWORD err = WSAGetLastError();
3622 if (err == WSAECONNABORTED)
3625 errno = map_errno(err);
3635 memset(&wol, 0,
sizeof(wol));
3637 wol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3640 if (addr && addrlen)
3641 ret = WSARecvFrom(s, &wbuf, 1, &size, &flg, addr, addrlen,
3644 ret = WSARecv(s, &wbuf, 1, &size, &flg, &wol, NULL);
3647 if (addr && addrlen)
3648 ret = WSASendTo(s, &wbuf, 1, &size, flags, addr, *addrlen,
3651 ret = WSASend(s, &wbuf, 1, &size, flags, &wol, NULL);
3655 finish_overlapped_socket(input, s, &wol, ret, &rlen, size);
3664rb_w32_recv(
int fd,
char *buf,
int len,
int flags)
3666 return overlapped_socket_io(TRUE, fd, buf,
len, flags, NULL, NULL);
3671rb_w32_recvfrom(
int fd,
char *buf,
int len,
int flags,
3672 struct sockaddr *from,
int *fromlen)
3674 return overlapped_socket_io(TRUE, fd, buf,
len, flags, from, fromlen);
3679rb_w32_send(
int fd,
const char *buf,
int len,
int flags)
3681 return overlapped_socket_io(FALSE, fd, (
char *)buf,
len, flags, NULL, NULL);
3686rb_w32_sendto(
int fd,
const char *buf,
int len,
int flags,
3687 const struct sockaddr *to,
int tolen)
3689 return overlapped_socket_io(FALSE, fd, (
char *)buf,
len, flags,
3690 (
struct sockaddr *)to, &tolen);
3693#if !defined(MSG_TRUNC) && !defined(__MINGW32__)
3699 DWORD dwBufferCount;
3704#ifndef WSAID_WSARECVMSG
3705#define WSAID_WSARECVMSG {0xf689d7c8,0x6f1f,0x436b,{0x8a,0x53,0xe5,0x4f,0xe3,0x51,0xc3,0x22}}
3707#ifndef WSAID_WSASENDMSG
3708#define WSAID_WSASENDMSG {0xa441e712,0x754f,0x43ca,{0x84,0xa7,0x0d,0xee,0x44,0xcf,0x60,0x6d}}
3712#define msghdr_to_wsamsg(msg, wsamsg) \
3715 (wsamsg)->name = (msg)->msg_name; \
3716 (wsamsg)->namelen = (msg)->msg_namelen; \
3717 (wsamsg)->lpBuffers = ALLOCA_N(WSABUF, (msg)->msg_iovlen); \
3718 (wsamsg)->dwBufferCount = (msg)->msg_iovlen; \
3719 for (i = 0; i < (msg)->msg_iovlen; ++i) { \
3720 (wsamsg)->lpBuffers[i].buf = (msg)->msg_iov[i].iov_base; \
3721 (wsamsg)->lpBuffers[i].len = (msg)->msg_iov[i].iov_len; \
3723 (wsamsg)->Control.buf = (msg)->msg_control; \
3724 (wsamsg)->Control.len = (msg)->msg_controllen; \
3725 (wsamsg)->dwFlags = (msg)->msg_flags; \
3730recvmsg(
int fd,
struct msghdr *msg,
int flags)
3732 typedef int (WSAAPI *WSARecvMsg_t)(SOCKET,
WSAMSG *, DWORD *, WSAOVERLAPPED *, LPWSAOVERLAPPED_COMPLETION_ROUTINE);
3733 static WSARecvMsg_t pWSARecvMsg = NULL;
3743 static const GUID guid = WSAID_WSARECVMSG;
3744 pWSARecvMsg = (WSARecvMsg_t)get_wsa_extension_function(s, guid);
3749 msghdr_to_wsamsg(msg, &wsamsg);
3750 wsamsg.dwFlags |= flags;
3752 socklist_lookup(s, &mode);
3753 if (GET_FLAGS(mode) & O_NONBLOCK) {
3755 if ((ret = pWSARecvMsg(s, &wsamsg, &
len, NULL, NULL)) == SOCKET_ERROR) {
3756 errno = map_errno(WSAGetLastError());
3764 memset(&wol, 0,
sizeof(wol));
3766 wol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3767 ret = pWSARecvMsg(s, &wsamsg, &size, &wol, NULL);
3770 ret = finish_overlapped_socket(TRUE, s, &wol, ret, &
len, size);
3772 if (ret == SOCKET_ERROR)
3776 msg->msg_name = wsamsg.name;
3777 msg->msg_namelen = wsamsg.namelen;
3778 msg->msg_flags = wsamsg.dwFlags;
3785sendmsg(
int fd,
const struct msghdr *msg,
int flags)
3787 typedef int (WSAAPI *WSASendMsg_t)(SOCKET,
const WSAMSG *, DWORD, DWORD *, WSAOVERLAPPED *, LPWSAOVERLAPPED_COMPLETION_ROUTINE);
3788 static WSASendMsg_t pWSASendMsg = NULL;
3798 static const GUID guid = WSAID_WSASENDMSG;
3799 pWSASendMsg = (WSASendMsg_t)get_wsa_extension_function(s, guid);
3804 msghdr_to_wsamsg(msg, &wsamsg);
3806 socklist_lookup(s, &mode);
3807 if (GET_FLAGS(mode) & O_NONBLOCK) {
3809 if ((ret = pWSASendMsg(s, &wsamsg, flags, &
len, NULL, NULL)) == SOCKET_ERROR) {
3810 errno = map_errno(WSAGetLastError());
3818 memset(&wol, 0,
sizeof(wol));
3820 wol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3821 ret = pWSASendMsg(s, &wsamsg, flags, &size, &wol, NULL);
3824 finish_overlapped_socket(FALSE, s, &wol, ret, &
len, size);
3834rb_w32_setsockopt(
int s,
int level,
int optname,
const char *optval,
int optlen)
3838 r = setsockopt(TO_SOCKET(s), level, optname, optval, optlen);
3839 if (r == SOCKET_ERROR)
3840 errno = map_errno(WSAGetLastError());
3849rb_w32_shutdown(
int s,
int how)
3853 r = shutdown(TO_SOCKET(s), how);
3854 if (r == SOCKET_ERROR)
3855 errno = map_errno(WSAGetLastError());
3862open_ifs_socket(
int af,
int type,
int protocol)
3864 unsigned long proto_buffers_len = 0;
3866 SOCKET out = INVALID_SOCKET;
3868 if (WSAEnumProtocols(NULL, NULL, &proto_buffers_len) == SOCKET_ERROR) {
3869 error_code = WSAGetLastError();
3870 if (error_code == WSAENOBUFS) {
3871 WSAPROTOCOL_INFO *proto_buffers;
3872 int protocols_available = 0;
3874 proto_buffers = (WSAPROTOCOL_INFO *)malloc(proto_buffers_len);
3875 if (!proto_buffers) {
3876 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
3877 return INVALID_SOCKET;
3880 protocols_available =
3881 WSAEnumProtocols(NULL, proto_buffers, &proto_buffers_len);
3882 if (protocols_available != SOCKET_ERROR) {
3884 for (i = 0; i < protocols_available; i++) {
3885 if ((af != AF_UNSPEC && af != proto_buffers[i].iAddressFamily) ||
3886 (
type != proto_buffers[i].iSocketType) ||
3887 (protocol != 0 && protocol != proto_buffers[i].iProtocol))
3890 if ((proto_buffers[i].dwServiceFlags1 & XP1_IFS_HANDLES) == 0)
3893 out = WSASocket(af,
type, protocol, &(proto_buffers[i]), 0,
3894 WSA_FLAG_OVERLAPPED);
3897 if (out == INVALID_SOCKET)
3898 out = WSASocket(af,
type, protocol, NULL, 0, 0);
3899 if (out != INVALID_SOCKET)
3900 SetHandleInformation((HANDLE)out, HANDLE_FLAG_INHERIT, 0);
3903 free(proto_buffers);
3914rb_w32_socket(
int af,
int type,
int protocol)
3920 s = open_ifs_socket(af,
type, protocol);
3921 if (s == INVALID_SOCKET) {
3922 errno = map_errno(WSAGetLastError());
3926 fd = rb_w32_open_osfhandle(s, O_RDWR|O_BINARY|O_NOINHERIT);
3928 socklist_insert(s, MAKE_SOCKDATA(af, 0));
3939struct hostent * WSAAPI
3940rb_w32_gethostbyaddr(
const char *addr,
int len,
int type)
3944 r = gethostbyaddr(addr,
len,
type);
3946 errno = map_errno(WSAGetLastError());
3954struct hostent * WSAAPI
3955rb_w32_gethostbyname(
const char *name)
3959 r = gethostbyname(name);
3961 errno = map_errno(WSAGetLastError());
3970rb_w32_gethostname(
char *name,
int len)
3974 r = gethostname(name,
len);
3975 if (r == SOCKET_ERROR)
3976 errno = map_errno(WSAGetLastError());
3981#undef getprotobyname
3984struct protoent * WSAAPI
3985rb_w32_getprotobyname(
const char *name)
3989 r = getprotobyname(name);
3991 errno = map_errno(WSAGetLastError());
3996#undef getprotobynumber
3999struct protoent * WSAAPI
4000rb_w32_getprotobynumber(
int num)
4004 r = getprotobynumber(num);
4006 errno = map_errno(WSAGetLastError());
4014struct servent * WSAAPI
4015rb_w32_getservbyname(
const char *name,
const char *proto)
4019 r = getservbyname(name, proto);
4021 errno = map_errno(WSAGetLastError());
4029struct servent * WSAAPI
4030rb_w32_getservbyport(
int port,
const char *proto)
4034 r = getservbyport(port, proto);
4036 errno = map_errno(WSAGetLastError());
4045socketpair_unix_path(
struct sockaddr_un *sock_un)
4048 WCHAR wpath[
sizeof(sock_un->sun_path)/
sizeof(*sock_un->sun_path)] = L
"";
4053 listener = socket(AF_UNIX, SOCK_STREAM, 0);
4054 if (listener == INVALID_SOCKET)
4057 memset(sock_un, 0,
sizeof(*sock_un));
4058 sock_un->sun_family = AF_UNIX;
4068 for (
int try = 0; ;
try++) {
4069 LARGE_INTEGER ticks;
4070 size_t path_len = 0;
4071 const size_t maxpath =
sizeof(sock_un->sun_path)/
sizeof(*sock_un->sun_path);
4076 path_len = GetTempPathW(maxpath, wpath);
4077 if (path_len == 0 || path_len > maxpath) {
4086 wcsncpy(wpath, L
"C:/Temp/", maxpath);
4087 path_len = lstrlenW(wpath);
4094 closesocket(listener);
4099 path_len = WideCharToMultiByte(CP_UTF8, 0, wpath, path_len, sock_un->sun_path, maxpath, NULL, NULL);
4100 QueryPerformanceCounter(&ticks);
4101 path_len += snprintf(sock_un->sun_path + path_len,
4105 GetCurrentProcessId());
4108 MultiByteToWideChar(CP_UTF8, 0, sock_un->sun_path, -1, wpath,
sizeof(wpath)/
sizeof(*wpath));
4110 if (bind(listener, (
struct sockaddr *)sock_un,
sizeof(*sock_un)) != SOCKET_ERROR)
4113 closesocket(listener);
4115 return sizeof(*sock_un);
4121socketpair_internal(
int af,
int type,
int protocol, SOCKET *sv)
4123 SOCKET svr = INVALID_SOCKET, r = INVALID_SOCKET, w = INVALID_SOCKET;
4124 struct sockaddr_in sock_in4;
4127 struct sockaddr_in6 sock_in6;
4131 struct sockaddr_un sock_un = {0, {0}};
4132 WCHAR wpath[
sizeof(sock_un.sun_path)/
sizeof(*sock_un.sun_path)] = L
"";
4135 struct sockaddr *addr;
4141#if defined PF_INET && PF_INET != AF_INET
4144 sock_in4.sin_family = AF_INET;
4145 sock_in4.sin_port = 0;
4146 sock_in4.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4147 addr = (
struct sockaddr *)&sock_in4;
4148 len =
sizeof(sock_in4);
4152 memset(&sock_in6, 0,
sizeof(sock_in6));
4153 sock_in6.sin6_family = AF_INET6;
4154 sock_in6.sin6_addr = IN6ADDR_LOOPBACK_INIT;
4155 addr = (
struct sockaddr *)&sock_in6;
4156 len =
sizeof(sock_in6);
4161 addr = (
struct sockaddr *)&sock_un;
4162 len = socketpair_unix_path(&sock_un);
4163 MultiByteToWideChar(CP_UTF8, 0, sock_un.sun_path, -1, wpath,
sizeof(wpath)/
sizeof(*wpath));
4169 errno = EAFNOSUPPORT;
4172 if (
type != SOCK_STREAM) {
4177 sv[0] = (SOCKET)INVALID_HANDLE_VALUE;
4178 sv[1] = (SOCKET)INVALID_HANDLE_VALUE;
4181 svr = open_ifs_socket(af,
type, protocol);
4182 if (svr == INVALID_SOCKET)
4184 if (bind(svr, addr,
len) < 0)
4186 if (getsockname(svr, addr, &
len) < 0)
4188 if (
type == SOCK_STREAM)
4191 w = open_ifs_socket(af,
type, protocol);
4192 if (w == INVALID_SOCKET)
4194 if (connect(w, addr,
len) < 0)
4197 r = accept(svr, addr, &
len);
4198 if (r == INVALID_SOCKET)
4200 SetHandleInformation((HANDLE)r, HANDLE_FLAG_INHERIT, 0);
4206 errno = map_errno(WSAGetLastError());
4207 if (r != INVALID_SOCKET)
4209 if (w != INVALID_SOCKET)
4216 if (svr != INVALID_SOCKET)
4219 if (sock_un.sun_family == AF_UNIX)
4229socketpair(
int af,
int type,
int protocol,
int *sv)
4233 if (socketpair_internal(af,
type, protocol, pair) < 0)
4235 sv[0] = rb_w32_open_osfhandle(pair[0], O_RDWR|O_BINARY|O_NOINHERIT);
4237 closesocket(pair[0]);
4238 closesocket(pair[1]);
4241 sv[1] = rb_w32_open_osfhandle(pair[1], O_RDWR|O_BINARY|O_NOINHERIT);
4243 rb_w32_close(sv[0]);
4244 closesocket(pair[1]);
4247 socklist_insert(pair[0], MAKE_SOCKDATA(af, 0));
4248 socklist_insert(pair[1], MAKE_SOCKDATA(af, 0));
4255str2guid(
const char *str, GUID *guid)
4257#define hex2byte(str) \
4258 ((isdigit(*(str)) ? *(str) - '0' : toupper(*(str)) - 'A' + 10) << 4 | (isdigit(*((str) + 1)) ? *((str) + 1) - '0' : toupper(*((str) + 1)) - 'A' + 10))
4261 if (*str ==
'{') str++;
4262 guid->Data1 = (long)strtoul(str, &end, 16);
4264 guid->Data2 = (
unsigned short)strtoul(str, &end, 16);
4266 guid->Data3 = (
unsigned short)strtoul(str, &end, 16);
4268 guid->Data4[0] = hex2byte(str);
4270 guid->Data4[1] = hex2byte(str);
4272 for (i = 0; i < 6; i++) {
4273 guid->Data4[i + 2] = hex2byte(str);
4279#ifndef HAVE_TYPE_NET_LUID
4283 uint64_t Reserved :24;
4284 uint64_t NetLuidIndex :24;
4285 uint64_t IfType :16;
4291getifaddrs(
struct ifaddrs **ifap)
4295 IP_ADAPTER_ADDRESSES *root, *addr;
4298 ret = GetAdaptersAddresses(AF_UNSPEC, 0, NULL, NULL, &size);
4299 if (ret != ERROR_BUFFER_OVERFLOW) {
4300 errno = map_errno(ret);
4303 root = ruby_xmalloc(size);
4304 ret = GetAdaptersAddresses(AF_UNSPEC, 0, NULL, root, &size);
4305 if (ret != ERROR_SUCCESS) {
4306 errno = map_errno(ret);
4311 for (prev = NULL, addr = root; addr; addr = addr->Next) {
4312 struct ifaddrs *ifa = ruby_xcalloc(1,
sizeof(*ifa));
4313 char name[IFNAMSIZ];
4318 prev->ifa_next = ifa;
4322 str2guid(addr->AdapterName, &guid);
4323 if (ConvertInterfaceGuidToLuid(&guid, &luid) == NO_ERROR &&
4324 ConvertInterfaceLuidToNameA(&luid, name,
sizeof(name)) == NO_ERROR) {
4331 if (addr->IfType & IF_TYPE_SOFTWARE_LOOPBACK)
4332 ifa->ifa_flags |= IFF_LOOPBACK;
4333 if (addr->OperStatus == IfOperStatusUp) {
4334 ifa->ifa_flags |= IFF_UP;
4336 if (addr->FirstUnicastAddress) {
4337 IP_ADAPTER_UNICAST_ADDRESS *cur;
4339 for (cur = addr->FirstUnicastAddress; cur; cur = cur->Next) {
4340 if (cur->Flags & IP_ADAPTER_ADDRESS_TRANSIENT ||
4341 cur->DadState == IpDadStateDeprecated) {
4346 ifa = ruby_xcalloc(1,
sizeof(*ifa));
4347 prev->ifa_next = ifa;
4349 ifa->ifa_flags = prev->ifa_flags;
4351 ifa->ifa_addr = ruby_xmalloc(cur->Address.iSockaddrLength);
4352 memcpy(ifa->ifa_addr, cur->Address.lpSockaddr,
4353 cur->Address.iSockaddrLength);
4368freeifaddrs(
struct ifaddrs *ifp)
4371 struct ifaddrs *next = ifp->ifa_next;
4372 ruby_xfree(ifp->ifa_addr);
4373 ruby_xfree(ifp->ifa_name);
4384void endhostent(
void) {}
4385void endnetent(
void) {}
4386void endprotoent(
void) {}
4387void endservent(
void) {}
4389struct netent *getnetent (
void) {
return (
struct netent *) NULL;}
4391struct netent *getnetbyaddr(
long net,
int type) {
return (
struct netent *)NULL;}
4393struct netent *getnetbyname(
const char *name) {
return (
struct netent *)NULL;}
4395struct protoent *getprotoent (
void) {
return (
struct protoent *) NULL;}
4397struct servent *getservent (
void) {
return (
struct servent *) NULL;}
4399void sethostent (
int stayopen) {}
4401void setnetent (
int stayopen) {}
4403void setprotoent (
int stayopen) {}
4405void setservent (
int stayopen) {}
4408int rb_w32_set_nonblock2(
int fd,
int nonblock);
4412setfl(SOCKET sock,
int arg)
4419 socklist_lookup(sock, &flag);
4420 af = GET_FAMILY(flag);
4421 flag = GET_FLAGS(flag);
4422 if (arg & O_NONBLOCK) {
4427 flag &= ~O_NONBLOCK;
4431 ret = ioctlsocket(sock, FIONBIO, &ioctlArg);
4433 socklist_insert(sock, MAKE_SOCKDATA(af, flag));
4435 errno = map_errno(WSAGetLastError());
4443dupfd(HANDLE hDup,
int flags,
int minfd)
4451 ret = _open_osfhandle((intptr_t)hDup, flags | FOPEN);
4453 goto close_fds_and_return;
4456 goto close_fds_and_return;
4458 fds[filled++] = ret;
4459 }
while (filled < (
int)numberof(fds));
4461 ret = dupfd(hDup, flags, minfd);
4463 close_fds_and_return:
4465 while (filled > 0) {
4466 int fd = fds[--filled];
4467 _set_osfhnd(fd, (intptr_t)INVALID_HANDLE_VALUE);
4477fcntl(
int fd,
int cmd, ...)
4486 arg = va_arg(va,
int);
4488 return rb_w32_set_nonblock2(fd, arg);
4490 case F_DUPFD:
case F_DUPFD_CLOEXEC: {
4494 if (!(DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
4495 GetCurrentProcess(), &hDup, 0L,
4496 cmd == F_DUPFD && !(flag & FNOINHERIT),
4497 DUPLICATE_SAME_ACCESS))) {
4498 errno = map_errno(GetLastError());
4503 arg = va_arg(va,
int);
4509 flag &= ~FNOINHERIT;
4510 if ((ret = dupfd(hDup, flag, arg)) == -1)
4516 if (h == -1)
return -1;
4517 if (!GetHandleInformation((HANDLE)h, &flag)) {
4518 errno = map_errno(GetLastError());
4521 return (flag & HANDLE_FLAG_INHERIT) ? 0 : FD_CLOEXEC;
4525 if (h == -1)
return -1;
4527 arg = va_arg(va,
int);
4529 if (!SetHandleInformation((HANDLE)h, HANDLE_FLAG_INHERIT,
4530 (arg & FD_CLOEXEC) ? 0 : HANDLE_FLAG_INHERIT)) {
4531 errno = map_errno(GetLastError());
4534 if (arg & FD_CLOEXEC)
4535 _osfile(fd) |= FNOINHERIT;
4537 _osfile(fd) &= ~FNOINHERIT;
4548rb_w32_set_nonblock2(
int fd,
int nonblock)
4550 SOCKET sock = TO_SOCKET(fd);
4551 if (is_socket(sock)) {
4552 return setfl(sock, nonblock ? O_NONBLOCK : 0);
4554 else if (is_pipe(sock)) {
4556 if (!GetNamedPipeHandleState((HANDLE)sock, &state, NULL, NULL, NULL, NULL, 0)) {
4557 errno = map_errno(GetLastError());
4561 state |= PIPE_NOWAIT;
4564 state &= ~PIPE_NOWAIT;
4566 if (!SetNamedPipeHandleState((HANDLE)sock, &state, NULL, NULL)) {
4567 errno = map_errno(GetLastError());
4579rb_w32_set_nonblock(
int fd)
4581 return rb_w32_set_nonblock2(fd, TRUE);
4590poll_child_status(
struct ChildRecord *child,
int *stat_loc)
4595 if (!GetExitCodeProcess(child->hProcess, &exitcode)) {
4597 err = GetLastError();
4599 case ERROR_INVALID_PARAMETER:
4602 case ERROR_INVALID_HANDLE:
4606 errno = map_errno(err);
4610 CloseChildHandle(child);
4613 if (exitcode != STILL_ACTIVE) {
4616 if (rb_w32_wait_events_blocking(&child->hProcess, 1, INFINITE) != WAIT_OBJECT_0) {
4620 CloseChildHandle(child);
4622 *stat_loc = exitcode << 8;
4623 if (exitcode & 0xC0000000) {
4624 static const struct {
4628 {STATUS_ACCESS_VIOLATION, SIGSEGV},
4629 {STATUS_ILLEGAL_INSTRUCTION, SIGILL},
4630 {STATUS_PRIVILEGED_INSTRUCTION, SIGILL},
4631 {STATUS_FLOAT_DENORMAL_OPERAND, SIGFPE},
4632 {STATUS_FLOAT_DIVIDE_BY_ZERO, SIGFPE},
4633 {STATUS_FLOAT_INEXACT_RESULT, SIGFPE},
4634 {STATUS_FLOAT_INVALID_OPERATION, SIGFPE},
4635 {STATUS_FLOAT_OVERFLOW, SIGFPE},
4636 {STATUS_FLOAT_STACK_CHECK, SIGFPE},
4637 {STATUS_FLOAT_UNDERFLOW, SIGFPE},
4638#ifdef STATUS_FLOAT_MULTIPLE_FAULTS
4639 {STATUS_FLOAT_MULTIPLE_FAULTS, SIGFPE},
4641#ifdef STATUS_FLOAT_MULTIPLE_TRAPS
4642 {STATUS_FLOAT_MULTIPLE_TRAPS, SIGFPE},
4644 {STATUS_CONTROL_C_EXIT, SIGINT},
4647 for (i = 0; i < (int)numberof(table); i++) {
4648 if (table[i].status == exitcode) {
4649 *stat_loc |= table[i].sig;
4654 if (i >= (
int)numberof(table))
4655 *stat_loc |= SIGSEGV;
4665waitpid(rb_pid_t pid,
int *stat_loc,
int options)
4670 if (options == WNOHANG) {
4681 HANDLE events[MAXCHILDNUM];
4684 FOREACH_CHILD(child) {
4685 if (!child->pid || child->pid < 0)
continue;
4686 if ((pid = poll_child_status(child, stat_loc)))
return pid;
4687 events[count++] = child->hProcess;
4688 } END_FOREACH_CHILD;
4694 ret = rb_w32_wait_events_blocking(events, count, timeout);
4695 if (ret == WAIT_TIMEOUT)
return 0;
4696 if ((ret -= WAIT_OBJECT_0) == count) {
4700 errno = map_errno(GetLastError());
4704 cause = FindChildSlotByHandle(events[ret]);
4709 return poll_child_status(cause, stat_loc);
4719 while (!(pid = poll_child_status(child, stat_loc))) {
4721 int ret = rb_w32_wait_events_blocking(&child->hProcess, 1, timeout);
4722 if (ret == WAIT_OBJECT_0 + 1)
return -1;
4723 if (ret != WAIT_OBJECT_0) {
4725 if (options & WNOHANG) {
4732 if (pid == -1 && retried) pid = 0;
4738#include <sys/timeb.h>
4741#define filetime_unit (10UL * 1000 * 1000)
4742#define filetime_diff_days ((1970-1601)*3652425UL/10000)
4743#define filetime_diff_secs (filetime_diff_days * (24ULL * 60 * 60))
4744#define unix_to_filetime(sec) (((sec) + filetime_diff_secs) * filetime_unit)
4745#define filetime_unix_offset unix_to_filetime(0ULL)
4757filetime_split(
const FILETIME* ft,
long *subsec)
4760 ULONGLONG lt = fi.i.QuadPart;
4766 lt -= unix_to_filetime(0);
4768 *subsec = (long)(lt % filetime_unit);
4769 return (time_t)(lt / filetime_unit);
4779 GetSystemTimePreciseAsFileTime(&ft);
4780 tv->tv_sec = filetime_split(&ft, &subsec);
4781 tv->tv_usec = subsec / 10;
4788filetime_to_timespec(FILETIME ft,
struct timespec *sp)
4791 sp->tv_sec = filetime_split(&ft, &subsec);
4792 sp->tv_nsec = subsec * 100;
4796static const long secs_in_ns = 1000000000;
4800clock_gettime(clockid_t clock_id,
struct timespec *sp)
4803 case CLOCK_REALTIME:
4804 case CLOCK_REALTIME_COARSE:
4808 GetSystemTimePreciseAsFileTime(&ft);
4809 filetime_to_timespec(ft, sp);
4812 case CLOCK_MONOTONIC:
4815 LARGE_INTEGER count;
4816 if (UNLIKELY(!QueryPerformanceFrequency(&freq))) {
4817 errno = map_errno(GetLastError());
4820 if (UNLIKELY(!QueryPerformanceCounter(&count))) {
4821 errno = map_errno(GetLastError());
4824 sp->tv_sec = count.QuadPart / freq.QuadPart;
4825 if (freq.QuadPart < secs_in_ns)
4826 sp->tv_nsec = (count.QuadPart % freq.QuadPart) * secs_in_ns / freq.QuadPart;
4828 sp->tv_nsec = (long)((count.QuadPart % freq.QuadPart) * ((double)secs_in_ns / freq.QuadPart));
4831 case CLOCK_PROCESS_CPUTIME_ID:
4832 case CLOCK_THREAD_CPUTIME_ID:
4836 if (clock_id == CLOCK_PROCESS_CPUTIME_ID) {
4837 ok = GetProcessTimes(GetCurrentProcess(), &c.ft, &e.ft, &k.ft, &u.ft);
4840 ok = GetThreadTimes(GetCurrentThread(), &c.ft, &e.ft, &k.ft, &u.ft);
4842 if (UNLIKELY(!ok)) {
4843 errno = map_errno(GetLastError());
4846 total.i.QuadPart = k.i.QuadPart + u.i.QuadPart;
4847 filetime_to_timespec(total.ft, sp);
4858clock_getres(clockid_t clock_id,
struct timespec *sp)
4861 case CLOCK_REALTIME:
4862 case CLOCK_REALTIME_COARSE:
4868 case CLOCK_MONOTONIC:
4871 if (!QueryPerformanceFrequency(&freq)) {
4872 errno = map_errno(GetLastError());
4876 sp->tv_nsec = (long)((
double)secs_in_ns / freq.QuadPart);
4879 case CLOCK_PROCESS_CPUTIME_ID:
4880 case CLOCK_THREAD_CPUTIME_ID:
4882 const int frames_in_sec = 60;
4884 sp->tv_nsec = (long)(secs_in_ns / frames_in_sec);
4895w32_getcwd(
char *buffer,
int size, UINT cp,
void *alloc(
int,
void *),
void *arg)
4900 len = GetCurrentDirectoryW(0, NULL);
4902 errno = map_errno(GetLastError());
4906 if (buffer && size <
len) {
4912 if (!GetCurrentDirectoryW(
len, p)) {
4913 errno = map_errno(GetLastError());
4917 wlen = translate_wchar(p, L
'\\', L
'/') - p + 1;
4918 len = WideCharToMultiByte(cp, 0, p, wlen, NULL, 0, NULL, NULL);
4926 buffer = (*alloc)(
len, arg);
4932 WideCharToMultiByte(cp, 0, p, wlen, buffer,
len, NULL, NULL);
4939getcwd_alloc(
int size,
void *dummy)
4941 return malloc(size);
4946rb_w32_getcwd(
char *buffer,
int size)
4948 return w32_getcwd(buffer, size, filecp(), getcwd_alloc, NULL);
4953rb_w32_ugetcwd(
char *buffer,
int size)
4955 return w32_getcwd(buffer, size, CP_UTF8, getcwd_alloc, NULL);
4960getcwd_value(
int size,
void *arg)
4963 return RSTRING_PTR(str);
4968rb_dir_getwd_ospath(
void)
4971 w32_getcwd(NULL, 0, CP_UTF8, getcwd_value, &cwd);
4977chown(
const char *path,
int owner,
int group)
4984rb_w32_uchown(
const char *path,
int owner,
int group)
4990lchown(
const char *path,
int owner,
int group)
4996rb_w32_ulchown(
const char *path,
int owner,
int group)
5003kill(rb_pid_t pid,
int sig)
5008 if (pid < 0 || (pid == 0 && sig != SIGINT)) {
5013 if ((
unsigned int)pid == GetCurrentProcessId() &&
5014 (sig != 0 && sig != SIGKILL)) {
5015 if ((ret = raise(sig)) != 0) {
5026 OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, (DWORD)pid);
5027 if (hProc == NULL || hProc == INVALID_HANDLE_VALUE) {
5028 if (GetLastError() == ERROR_INVALID_PARAMETER) {
5044 DWORD ctrlEvent = CTRL_C_EVENT;
5048 ctrlEvent = CTRL_BREAK_EVENT;
5050 if (!GenerateConsoleCtrlEvent(ctrlEvent, (DWORD)pid)) {
5051 if ((err = GetLastError()) == 0)
5054 errno = map_errno(GetLastError());
5065 hProc = child->hProcess;
5068 hProc = OpenProcess(PROCESS_TERMINATE | PROCESS_QUERY_INFORMATION, FALSE, (DWORD)pid);
5070 if (hProc == NULL || hProc == INVALID_HANDLE_VALUE) {
5071 if (GetLastError() == ERROR_INVALID_PARAMETER) {
5081 if (!GetExitCodeProcess(hProc, &status)) {
5082 errno = map_errno(GetLastError());
5085 else if (status == STILL_ACTIVE) {
5086 if (!TerminateProcess(hProc, 0)) {
5113wlink(
const WCHAR *from,
const WCHAR *to)
5115 if (!CreateHardLinkW(to, from, NULL)) {
5116 errno = map_errno(GetLastError());
5125rb_w32_ulink(
const char *from,
const char *to)
5131 if (!(wfrom = utf8_to_wstr(from, NULL)))
5133 if (!(wto = utf8_to_wstr(to, NULL))) {
5137 ret = wlink(wfrom, wto);
5145link(
const char *from,
const char *to)
5151 if (!(wfrom = filecp_to_wstr(from, NULL)))
5153 if (!(wto = filecp_to_wstr(to, NULL))) {
5157 ret = wlink(wfrom, wto);
5164#ifndef FILE_DEVICE_FILE_SYSTEM
5165# define FILE_DEVICE_FILE_SYSTEM 0x00000009
5167#ifndef FSCTL_GET_REPARSE_POINT
5168# define FSCTL_GET_REPARSE_POINT ((0x9<<16)|(42<<2))
5170#ifndef IO_REPARSE_TAG_SYMLINK
5171# define IO_REPARSE_TAG_SYMLINK 0xA000000CL
5182 f = open_special(path, 0, FILE_FLAG_OPEN_REPARSE_POINT);
5183 if (f == INVALID_HANDLE_VALUE) {
5184 return GetLastError();
5187 if (!DeviceIoControl(f, FSCTL_GET_REPARSE_POINT, NULL, 0,
5188 rp, size, &ret, NULL)) {
5191 else if (rp->ReparseTag != IO_REPARSE_TAG_SYMLINK &&
5192 rp->ReparseTag != IO_REPARSE_TAG_MOUNT_POINT) {
5193 e = ERROR_INVALID_PARAMETER;
5201rb_w32_reparse_symlink_p(
const WCHAR *path)
5209 e = rb_w32_read_reparse_point(path, rp,
sizeof(rbuf), &wbuf, &
len);
5210 if (e == ERROR_MORE_DATA) {
5211 size_t size = rb_w32_reparse_buffer_size(
len + 1);
5213 e = rb_w32_read_reparse_point(path, rp, size, &wbuf, &
len);
5218 case ERROR_MORE_DATA:
5227 size_t bufsize, WCHAR **result, DWORD *
len)
5229 int e = reparse_symlink(path, rp, bufsize);
5232 if (!e || e == ERROR_MORE_DATA) {
5234 if (rp->ReparseTag == IO_REPARSE_TAG_SYMLINK) {
5235 name = ((
char *)rp->SymbolicLinkReparseBuffer.PathBuffer +
5236 rp->SymbolicLinkReparseBuffer.PrintNameOffset);
5237 ret = rp->SymbolicLinkReparseBuffer.PrintNameLength;
5238 *
len = ret /
sizeof(WCHAR);
5240 else if (rp->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT) {
5241 static const WCHAR volume[] = L
"Volume{";
5243 name = ((
char *)rp->MountPointReparseBuffer.PathBuffer +
5244 rp->MountPointReparseBuffer.SubstituteNameOffset +
5245 volume_prefix_len *
sizeof(WCHAR));
5246 ret = rp->MountPointReparseBuffer.SubstituteNameLength;
5247 *
len = ret /
sizeof(WCHAR);
5248 ret -= volume_prefix_len *
sizeof(WCHAR);
5249 if (ret >
sizeof(volume) - 1 *
sizeof(WCHAR) &&
5250 memcmp(name, volume,
sizeof(volume) - 1 *
sizeof(WCHAR)) == 0)
5258 if ((
char *)name + ret +
sizeof(WCHAR) > (
char *)rp + bufsize)
5262 ((WCHAR *)name)[ret/
sizeof(WCHAR)] = L
'\0';
5263 translate_wchar(name, L
'\\', L
'/');
5273w32_readlink(UINT cp,
const char *path,
char *buf,
size_t bufsize)
5275 VALUE rp_buf, rp_buf_bigger = 0;
5276 DWORD
len = MultiByteToWideChar(cp, 0, path, -1, NULL, 0);
5277 size_t size = rb_w32_reparse_buffer_size(bufsize);
5279 WCHAR *wpath =
ALLOCV(rp_buf,
sizeof(WCHAR) *
len + size);
5284 MultiByteToWideChar(cp, 0, path, -1, wpath,
len);
5285 e = rb_w32_read_reparse_point(wpath, rp, size, &wname, &
len);
5286 if (e == ERROR_MORE_DATA) {
5287 size = rb_w32_reparse_buffer_size(
len + 1);
5288 rp =
ALLOCV(rp_buf_bigger, size);
5289 e = rb_w32_read_reparse_point(wpath, rp, size, &wname, &
len);
5294 errno = e == -1 ? EINVAL : map_errno(e);
5297 len = lstrlenW(wname);
5298 ret = WideCharToMultiByte(cp, 0, wname,
len, buf, bufsize, NULL, NULL);
5309rb_w32_ureadlink(
const char *path,
char *buf,
size_t bufsize)
5311 return w32_readlink(CP_UTF8, path, buf, bufsize);
5316readlink(
const char *path,
char *buf,
size_t bufsize)
5318 return w32_readlink(filecp(), path, buf, bufsize);
5321#ifndef SYMBOLIC_LINK_FLAG_DIRECTORY
5322#define SYMBOLIC_LINK_FLAG_DIRECTORY (0x1)
5324#ifndef SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE
5325#define SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE (0x2)
5330w32_symlink(UINT cp,
const char *src,
const char *link)
5332 int atts, len1, len2;
5334 WCHAR *wsrc, *wlink;
5339 static DWORD create_flag = SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
5349 len1 = MultiByteToWideChar(cp, 0, src, -1, NULL, 0);
5350 len2 = MultiByteToWideChar(cp, 0, link, -1, NULL, 0);
5351 wsrc =
ALLOCV_N(WCHAR, buf, len1+len2);
5352 wlink = wsrc + len1;
5353 MultiByteToWideChar(cp, 0, src, -1, wsrc, len1);
5354 MultiByteToWideChar(cp, 0, link, -1, wlink, len2);
5355 translate_wchar(wsrc, L
'/', L
'\\');
5356 translate_wchar(wlink, L
'/', L
'\\');
5366 (((wsrc[0] >= L
'A' && wsrc[0] <= L
'Z') ||
5367 (wsrc[0] >= L
'a' && wsrc[0] <= L
'z')) && wsrc[1] == L
':') ||
5369 if (!independent && (sep = wcsrchr(wlink, L
'\\')) != NULL) {
5371 size_t dirlen = sep - wlink + 1;
5372 size_t srclen = wcslen(wsrc) + 1;
5373 WCHAR *fullsrc =
ALLOCV_N(WCHAR, buf2, dirlen + srclen);
5374 MEMCPY(fullsrc, wlink, WCHAR, dirlen);
5375 MEMCPY(fullsrc + dirlen, wsrc, WCHAR, srclen);
5376 atts = GetFileAttributesW(fullsrc);
5380 atts = GetFileAttributesW(wsrc);
5383 if (atts != -1 && atts & FILE_ATTRIBUTE_DIRECTORY)
5384 flag = SYMBOLIC_LINK_FLAG_DIRECTORY;
5385 ret = CreateSymbolicLinkW(wlink, wsrc, flag |= create_flag);
5387 (e = GetLastError()) == ERROR_INVALID_PARAMETER &&
5388 (flag & SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE)) {
5390 flag &= ~SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
5391 ret = CreateSymbolicLinkW(wlink, wsrc, flag);
5392 if (!ret) e = GetLastError();
5397 errno = map_errno(e);
5405rb_w32_usymlink(
const char *src,
const char *link)
5407 return w32_symlink(CP_UTF8, src, link);
5412symlink(
const char *src,
const char *link)
5414 return w32_symlink(filecp(), src, link);
5421 return waitpid(-1, status, 0);
5426w32_getenv(
const char *name, UINT cp)
5428 WCHAR *wenvarea, *wenv;
5429 int len = strlen(name);
5430 char *env, *found = NULL;
5433 if (
len == 0)
return NULL;
5438 return getenv(name);
5441 thread_exclusive(uenvarea) {
5446 wenvarea = GetEnvironmentStringsW();
5448 map_errno(GetLastError());
5451 for (wenv = wenvarea, wlen = 1; *wenv; wenv += lstrlenW(wenv) + 1)
5452 wlen += lstrlenW(wenv) + 1;
5453 uenvarea = wstr_to_mbstr(cp, wenvarea, wlen, NULL);
5454 FreeEnvironmentStringsW(wenvarea);
5458 for (env = uenvarea; *env; env += strlen(env) + 1) {
5459 if (strncasecmp(env, name,
len) == 0 && *(env +
len) ==
'=') {
5460 found = env +
len + 1;
5471rb_w32_ugetenv(
const char *name)
5473 return w32_getenv(name, CP_UTF8);
5478rb_w32_getenv(
const char *name)
5480 return w32_getenv(name, CP_ACP);
5485get_attr_vsn(
const WCHAR *path, DWORD *atts, DWORD *vsn)
5487 BY_HANDLE_FILE_INFORMATION st = {0};
5489 HANDLE h = open_special(path, 0, FILE_FLAG_OPEN_REPARSE_POINT);
5491 if (h == INVALID_HANDLE_VALUE) {
5496 if (!GetFileInformationByHandle(h, &st)) {
5501 *atts = st.dwFileAttributes;
5502 *vsn = st.dwVolumeSerialNumber;
5510wrename(
const WCHAR *oldpath,
const WCHAR *newpath)
5513 DWORD oldatts = 0, newatts = (DWORD)-1;
5514 DWORD oldvsn = 0, newvsn = 0, e;
5516 e = get_attr_vsn(oldpath, &oldatts, &oldvsn);
5518 errno = map_errno(e);
5521 if (oldatts & FILE_ATTRIBUTE_REPARSE_POINT) {
5522 HANDLE fh = open_special(oldpath, 0, 0);
5523 if (fh == INVALID_HANDLE_VALUE) {
5525 if (e == ERROR_CANT_RESOLVE_FILENAME) {
5532 get_attr_vsn(newpath, &newatts, &newvsn);
5535 if (newatts != (DWORD)-1 && newatts & FILE_ATTRIBUTE_READONLY)
5536 SetFileAttributesW(newpath, newatts & ~ FILE_ATTRIBUTE_READONLY);
5538 if (!MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED))
5542 DWORD e = GetLastError();
5543 if ((e == ERROR_ACCESS_DENIED) && (oldatts & FILE_ATTRIBUTE_DIRECTORY) &&
5547 errno = map_errno(e);
5550 SetFileAttributesW(newpath, oldatts);
5558rb_w32_urename(
const char *from,
const char *to)
5564 if (!(wfrom = utf8_to_wstr(from, NULL)))
5566 if (!(wto = utf8_to_wstr(to, NULL))) {
5570 ret = wrename(wfrom, wto);
5578rb_w32_rename(
const char *from,
const char *to)
5584 if (!(wfrom = filecp_to_wstr(from, NULL)))
5586 if (!(wto = filecp_to_wstr(to, NULL))) {
5590 ret = wrename(wfrom, wto);
5598isUNCRoot(
const WCHAR *path)
5600 if (path[0] == L
'\\' && path[1] == L
'\\') {
5601 const WCHAR *p = path + 2;
5602 if (p[0] == L
'?' && p[1] == L
'\\') {
5610 for (p++; *p; p++) {
5614 if (!p[0] || !p[1] || (p[1] == L
'.' && !p[2]))
5621#define COPY_STAT(src, dest, size_cast) do { \
5622 (dest).st_dev = (src).st_dev; \
5623 (dest).st_ino = (src).st_ino; \
5624 (dest).st_mode = (src).st_mode; \
5625 (dest).st_nlink = (src).st_nlink; \
5626 (dest).st_uid = (src).st_uid; \
5627 (dest).st_gid = (src).st_gid; \
5628 (dest).st_rdev = (src).st_rdev; \
5629 (dest).st_size = size_cast(src).st_size; \
5630 (dest).st_atime = (src).st_atime; \
5631 (dest).st_mtime = (src).st_mtime; \
5632 (dest).st_ctime = (src).st_ctime; \
5635static time_t filetime_to_unixtime(
const FILETIME *ft);
5636static long filetime_to_nsec(
const FILETIME *ft);
5637static WCHAR *name_for_stat(WCHAR *buf,
const WCHAR *path);
5638static DWORD stati128_handle(HANDLE h,
struct stati128 *st);
5643rb_w32_fstat(
int fd,
struct stat *st)
5645 BY_HANDLE_FILE_INFORMATION info;
5646 int ret = fstat(fd, st);
5648 if (ret)
return ret;
5649 if (GetEnvironmentVariableW(L
"TZ", NULL, 0) == 0 && GetLastError() == ERROR_ENVVAR_NOT_FOUND)
return ret;
5650 if (GetFileInformationByHandle((HANDLE)_get_osfhandle(fd), &info)) {
5651 st->st_atime = filetime_to_unixtime(&info.ftLastAccessTime);
5652 st->st_mtime = filetime_to_unixtime(&info.ftLastWriteTime);
5653 st->st_ctime = filetime_to_unixtime(&info.ftCreationTime);
5660rb_w32_fstati128(
int fd,
struct stati128 *st)
5663 int ret = fstat(fd, &tmp);
5665 if (ret)
return ret;
5666 COPY_STAT(tmp, *st, +);
5667 stati128_handle((HANDLE)_get_osfhandle(fd), st);
5671#if !defined FILE_INVALID_FILE_ID && !defined __MINGW32__
5673 BYTE Identifier[16];
5677#if !defined(_WIN32_WINNT_WIN8) || _WIN32_WINNT < 0x602
5678#define FileIdInfo 0x12
5689 return GetFileInformationByHandleEx(h, FileIdInfo,
id,
sizeof(*
id));
5694stati128_handle(HANDLE h,
struct stati128 *st)
5696 BY_HANDLE_FILE_INFORMATION info;
5697 DWORD attr = (DWORD)-1;
5699 if (GetFileInformationByHandle(h, &info)) {
5701 st->st_size = ((__int64)info.nFileSizeHigh << 32) | info.nFileSizeLow;
5702 st->st_atime = filetime_to_unixtime(&info.ftLastAccessTime);
5703 st->st_atimensec = filetime_to_nsec(&info.ftLastAccessTime);
5704 st->st_mtime = filetime_to_unixtime(&info.ftLastWriteTime);
5705 st->st_mtimensec = filetime_to_nsec(&info.ftLastWriteTime);
5706 st->st_ctime = filetime_to_unixtime(&info.ftCreationTime);
5707 st->st_ctimensec = filetime_to_nsec(&info.ftCreationTime);
5708 st->st_nlink = info.nNumberOfLinks;
5709 attr = info.dwFileAttributes;
5710 if (get_ino(h, &fii)) {
5711 st->st_ino = *((
unsigned __int64 *)&fii.FileId);
5712 st->st_inohigh = *((__int64 *)&fii.FileId + 1);
5715 st->st_ino = ((__int64)info.nFileIndexHigh << 32) | info.nFileIndexLow;
5724filetime_to_unixtime(
const FILETIME *ft)
5727 time_t t = filetime_split(ft, &subsec);
5729 if (t < 0)
return 0;
5735filetime_to_nsec(
const FILETIME *ft)
5738 tmp.LowPart = ft->dwLowDateTime;
5739 tmp.HighPart = ft->dwHighDateTime;
5740 return (
long)(tmp.QuadPart % 10000000) * 100;
5745fileattr_to_unixmode(DWORD attr,
const WCHAR *path,
unsigned mode)
5747 if (attr & FILE_ATTRIBUTE_READONLY) {
5751 mode |= S_IREAD | S_IWRITE | S_IWUSR;
5754 if (mode & S_IFMT) {
5757 else if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
5761 else if (attr & FILE_ATTRIBUTE_DIRECTORY) {
5762 mode |= S_IFDIR | S_IEXEC;
5768 if (path && (mode & S_IFREG)) {
5769 const WCHAR *end = path + lstrlenW(path);
5770 while (path < end) {
5771 end = CharPrevW(path, end);
5773 if ((_wcsicmp(end, L
".bat") == 0) ||
5774 (_wcsicmp(end, L
".cmd") == 0) ||
5775 (_wcsicmp(end, L
".com") == 0) ||
5776 (_wcsicmp(end, L
".exe") == 0)) {
5781 if (!iswalnum(*end))
break;
5785 mode |= (mode & 0500) >> 3;
5786 mode |= (mode & 0500) >> 6;
5793check_valid_dir(
const WCHAR *path)
5795 WIN32_FIND_DATAW fd;
5797 WCHAR full[PATH_MAX];
5802 if (!(p = wcsstr(path, L
"...")))
5804 q = p + wcsspn(p, L
".");
5805 if ((p == path || wcschr(L
":/\\", *(p - 1))) &&
5806 (!*q || wcschr(L
":/\\", *q))) {
5813 DWORD
len = GetFullPathNameW(path, numberof(full), full, NULL);
5814 if (
len >= numberof(full)) {
5815 WCHAR *fullpath = malloc(
len *
sizeof(WCHAR));
5816 if (!fullpath)
return -1;
5817 len = GetFullPathNameW(path,
len, fullpath, NULL);
5822 errno = map_errno(GetLastError());
5825 if (
len == 3 && full[1] == L
':' && GetDriveTypeW(full) != DRIVE_NO_ROOT_DIR)
5828 fh = open_dir_handle(path, &fd);
5829 if (fh == INVALID_HANDLE_VALUE)
5837stat_by_find(
const WCHAR *path,
struct stati128 *st)
5840 WIN32_FIND_DATAW wfd;
5843 h = FindFirstFileW(path, &wfd);
5844 if (h == INVALID_HANDLE_VALUE) {
5845 errno = map_errno(GetLastError());
5849 st->st_mode = fileattr_to_unixmode(wfd.dwFileAttributes, path, 0);
5850 st->st_atime = filetime_to_unixtime(&wfd.ftLastAccessTime);
5851 st->st_atimensec = filetime_to_nsec(&wfd.ftLastAccessTime);
5852 st->st_mtime = filetime_to_unixtime(&wfd.ftLastWriteTime);
5853 st->st_mtimensec = filetime_to_nsec(&wfd.ftLastWriteTime);
5854 st->st_ctime = filetime_to_unixtime(&wfd.ftCreationTime);
5855 st->st_ctimensec = filetime_to_nsec(&wfd.ftCreationTime);
5856 st->st_size = ((__int64)wfd.nFileSizeHigh << 32) | wfd.nFileSizeLow;
5863path_drive(
const WCHAR *path)
5865 if (path[0] && path[1] == L
':') {
5866 if (iswalpha(path[0]))
return towupper(path[0]) - L
'A';
5867 return (
int)path[0];
5869 return _getdrive() - 1;
5872#if !defined(NTDDI_WIN11_ZN) || NTDDI_VERSION < NTDDI_WIN11_ZN
5875#define FileStatBasicByNameInfo 3
5878 LARGE_INTEGER FileId;
5879 LARGE_INTEGER CreationTime;
5880 LARGE_INTEGER LastAccessTime;
5881 LARGE_INTEGER LastWriteTime;
5882 LARGE_INTEGER ChangeTime;
5883 LARGE_INTEGER AllocationSize;
5884 LARGE_INTEGER EndOfFile;
5885 DWORD FileAttributes;
5887 DWORD NumberOfLinks;
5889 DWORD DeviceCharacteristics;
5891 LARGE_INTEGER VolumeSerialNumber;
5896#ifndef FILE_DEVICE_DISK
5897#define FILE_DEVICE_DISK 7
5900typedef BOOL (WINAPI *get_file_information_by_name_func)
5901 (PCWSTR,
int , PVOID, ULONG);
5902static get_file_information_by_name_func get_file_information_by_name =
5903 (get_file_information_by_name_func)-1;
5907large_integer_to_unixtime(
const LARGE_INTEGER *at,
long *nsecp)
5911 ft.dwLowDateTime = at->LowPart;
5912 ft.dwHighDateTime = at->HighPart;
5913 *nsecp = filetime_to_nsec(&ft);
5914 return filetime_to_unixtime(&ft);
5919path_drive_serial(
const WCHAR *path)
5924 if (path[0] && path[1] == L
':') {
5925 if (!iswalpha(path[0]))
return 0;
5926 drive = towupper(path[0]) - L
'A';
5929 drive = _getdrive() - 1;
5931 if (drive < 0 || (
int)numberof(serials) <= drive)
return 0;
5932 if (!serials[drive]) {
5934 WCHAR root[] = L
"_:\\";
5935 root[0] = L
'A' + drive;
5936 if (get_file_information_by_name(root, FileStatBasicByNameInfo,
5937 &info,
sizeof(info)))
5938 serials[drive] = info.VolumeSerialNumber.QuadPart;
5940 return serials[drive];
5945stat_by_name(
const WCHAR *path,
struct stati128 *st)
5951 unsigned __int64 ino;
5954 if (get_file_information_by_name == (get_file_information_by_name_func)-1) {
5956 get_file_information_by_name = (get_file_information_by_name_func)
5957 get_proc_address(
"kernel32",
"GetFileInformationByName", NULL);
5959 if (!get_file_information_by_name)
return 1;
5960 if (!get_file_information_by_name(path, FileStatBasicByNameInfo,
5961 &info,
sizeof(info))) {
5962 DWORD e = GetLastError();
5964 case ERROR_FILE_NOT_FOUND:
5965 case ERROR_INVALID_NAME:
5966 case ERROR_PATH_NOT_FOUND:
5967 case ERROR_BAD_NETPATH:
5968 errno = map_errno(e);
5973 if (info.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
5975 if (info.DeviceType != FILE_DEVICE_DISK)
5977 if (info.VolumeSerialNumber.QuadPart != path_drive_serial(path))
5979 ino = *((
unsigned __int64 *)&info.FileId128);
5980 inohigh = *((__int64 *)&info.FileId128 + 1);
5981 if (!ino && !inohigh)
5983 if (info.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
5984 if (check_valid_dir(path))
return -1;
5987 st->st_inohigh = inohigh;
5988 st->st_size = info.EndOfFile.QuadPart;
5989 st->st_atime = large_integer_to_unixtime(&info.LastAccessTime, &st->st_atimensec);
5990 st->st_mtime = large_integer_to_unixtime(&info.LastWriteTime, &st->st_mtimensec);
5991 st->st_ctime = large_integer_to_unixtime(&info.CreationTime, &st->st_ctimensec);
5992 st->st_nlink = info.NumberOfLinks;
5993 st->st_mode = fileattr_to_unixmode(info.FileAttributes, path, 0);
5994 st->st_dev = st->st_rdev = path_drive(path);
6000winnt_stat(
const WCHAR *path,
struct stati128 *st, BOOL lstat)
6002 DWORD flags = lstat ? FILE_FLAG_OPEN_REPARSE_POINT : 0;
6004 WCHAR *finalname = 0;
6007 memset(st, 0,
sizeof(*st));
6008 switch (stat_by_name(path, st)) {
6014 f = open_special(path, 0, flags);
6015 open_error = GetLastError();
6016 if (f == INVALID_HANDLE_VALUE && !lstat) {
6018 FILE_ATTRIBUTE_TAG_INFO attr_info;
6021 f = open_special(path, 0, FILE_FLAG_OPEN_REPARSE_POINT);
6022 e = GetFileInformationByHandleEx(f, FileAttributeTagInfo,
6023 &attr_info,
sizeof(attr_info));
6024 if (!e || attr_info.ReparseTag != IO_REPARSE_TAG_AF_UNIX) {
6026 f = INVALID_HANDLE_VALUE;
6029 if (f != INVALID_HANDLE_VALUE) {
6030 DWORD attr = stati128_handle(f, st);
6032 switch (GetFileType(f)) {
6033 case FILE_TYPE_CHAR:
6036 case FILE_TYPE_PIPE:
6040 if (attr & FILE_ATTRIBUTE_DIRECTORY) {
6041 if (check_valid_dir(path))
return -1;
6043 if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
6044 FILE_ATTRIBUTE_TAG_INFO attr_info;
6047 e = GetFileInformationByHandleEx(f, FileAttributeTagInfo,
6048 &attr_info,
sizeof(attr_info));
6049 if (e && attr_info.ReparseTag == IO_REPARSE_TAG_AF_UNIX) {
6053 else if (rb_w32_reparse_symlink_p(path)) {
6056 mode |= S_IFLNK | S_IEXEC;
6059 mode |= S_IFDIR | S_IEXEC;
6063 const DWORD
len = get_handle_pathname(f, &finalname, 0);
6065 st->st_mode = fileattr_to_unixmode(attr, path, mode);
6068 if (wcsncmp(path, namespace_prefix, numberof(namespace_prefix)) == 0)
6069 path += numberof(namespace_prefix);
6073 if ((open_error == ERROR_FILE_NOT_FOUND) || (open_error == ERROR_INVALID_NAME)
6074 || (open_error == ERROR_PATH_NOT_FOUND || (open_error == ERROR_BAD_NETPATH))) {
6075 errno = map_errno(open_error);
6079 if (stat_by_find(path, st))
return -1;
6082 st->st_dev = st->st_rdev = path_drive(path);
6083 if (finalname) free(finalname);
6090rb_w32_stat(
const char *path,
struct stat *st)
6094 if (w32_stati128(path, &tmp, filecp(), FALSE))
return -1;
6095 COPY_STAT(tmp, *st, (_off_t));
6101wstati128(
const WCHAR *path,
struct stati128 *st, BOOL lstat)
6111 size = lstrlenW(path) + 2;
6113 if (!(path = name_for_stat(buf1, path)))
6115 ret = winnt_stat(path, st, lstat);
6124name_for_stat(WCHAR *buf1,
const WCHAR *path)
6130 for (p = path, s = buf1; *p; p++, s++) {
6138 if (!
len || L
'\"' == *(--s)) {
6142 end = buf1 +
len - 1;
6144 if (isUNCRoot(buf1)) {
6147 else if (*end != L
'\\')
6148 lstrcatW(buf1, L
"\\");
6150 else if (*end == L
'\\' || (buf1 + 1 == end && *end == L
':'))
6151 lstrcatW(buf1, L
".");
6158rb_w32_ustati128(
const char *path,
struct stati128 *st)
6160 return w32_stati128(path, st, CP_UTF8, FALSE);
6165rb_w32_stati128(
const char *path,
struct stati128 *st)
6167 return w32_stati128(path, st, filecp(), FALSE);
6172w32_stati128(
const char *path,
struct stati128 *st, UINT cp, BOOL lstat)
6177 if (!(wpath = mbstr_to_wstr(cp, path, -1, NULL)))
6179 ret = wstati128(wpath, st, lstat);
6186rb_w32_ulstati128(
const char *path,
struct stati128 *st)
6188 return w32_stati128(path, st, CP_UTF8, TRUE);
6193rb_w32_lstati128(
const char *path,
struct stati128 *st)
6195 return w32_stati128(path, st, filecp(), TRUE);
6200rb_w32_lseek(
int fd, rb_off_t ofs,
int whence)
6202 SOCKET sock = TO_SOCKET(fd);
6203 if (is_socket(sock) || is_pipe(sock)) {
6207 return _lseeki64(fd, ofs, whence);
6212w32_access(
const char *path,
int mode, UINT cp)
6215 if (w32_stati128(path, &stat, cp, FALSE) != 0)
6218 if ((stat.st_mode & mode) != mode) {
6227rb_w32_access(
const char *path,
int mode)
6229 return w32_access(path, mode, filecp());
6234rb_w32_uaccess(
const char *path,
int mode)
6236 return w32_access(path, mode, CP_UTF8);
6241rb_chsize(HANDLE h, rb_off_t size)
6243 long upos, lpos, usize, lsize;
6247 if ((lpos = SetFilePointer(h, 0, (upos = 0, &upos), SEEK_CUR)) == -1L &&
6248 (e = GetLastError())) {
6249 errno = map_errno(e);
6252 usize = (long)(size >> 32);
6254 if (SetFilePointer(h, lsize, &usize, SEEK_SET) == (DWORD)-1L &&
6255 (e = GetLastError())) {
6256 errno = map_errno(e);
6258 else if (!SetEndOfFile(h)) {
6259 errno = map_errno(GetLastError());
6264 SetFilePointer(h, lpos, &upos, SEEK_SET);
6270w32_truncate(
const char *path, rb_off_t length, UINT cp)
6276 if (!(wpath = mbstr_to_wstr(cp, path, -1, NULL)))
6278 h = CreateFileW(wpath, GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
6279 if (h == INVALID_HANDLE_VALUE) {
6280 errno = map_errno(GetLastError());
6285 ret = rb_chsize(h, length);
6292rb_w32_utruncate(
const char *path, rb_off_t length)
6294 return w32_truncate(path, length, CP_UTF8);
6299rb_w32_truncate(
const char *path, rb_off_t length)
6301 return w32_truncate(path, length, filecp());
6306rb_w32_ftruncate(
int fd, rb_off_t length)
6310 h = (HANDLE)_get_osfhandle(fd);
6311 if (h == (HANDLE)-1)
return -1;
6312 return rb_chsize(h, length);
6317filetime_to_clock(FILETIME *ft)
6319 __int64 qw = ft->dwHighDateTime;
6321 qw |= ft->dwLowDateTime;
6328rb_w32_times(
struct tms *tmbuf)
6330 FILETIME create, exit, kernel, user;
6332 if (GetProcessTimes(GetCurrentProcess(),&create, &exit, &kernel, &user)) {
6333 tmbuf->tms_utime = filetime_to_clock(&user);
6334 tmbuf->tms_stime = filetime_to_clock(&kernel);
6335 tmbuf->tms_cutime = 0;
6336 tmbuf->tms_cstime = 0;
6339 tmbuf->tms_utime = clock();
6340 tmbuf->tms_stime = 0;
6341 tmbuf->tms_cutime = 0;
6342 tmbuf->tms_cstime = 0;
6349#define yield_once() Sleep(0)
6350#define yield_until(condition) do yield_once(); while (!(condition))
6359 uintptr_t (*func)(uintptr_t self,
int argc, uintptr_t* argv);
6367call_asynchronous(PVOID argp)
6371 arg->stackaddr = &argp;
6372 ret = (DWORD)arg->func(arg->self, arg->argc, arg->argv);
6373 arg->errnum =
errno;
6379rb_w32_asynchronize(asynchronous_func_t func, uintptr_t self,
6380 int argc, uintptr_t* argv, uintptr_t intrval)
6383 BOOL interrupted = FALSE;
6389 arg.stackaddr = NULL;
6396 thr = CreateThread(NULL, 0, call_asynchronous, &arg, 0, &val);
6399 yield_until(arg.stackaddr);
6401 if (rb_w32_wait_events_blocking(&thr, 1, INFINITE) != WAIT_OBJECT_0) {
6404 if (TerminateThread(thr, intrval)) {
6409 GetExitCodeThread(thr, &val);
6414 MEMORY_BASIC_INFORMATION m;
6416 memset(&m, 0,
sizeof(m));
6417 if (!VirtualQuery(arg.stackaddr, &m,
sizeof(m))) {
6418 Debug(fprintf(stderr,
"couldn't get stack base:%p:%d\n",
6419 arg.stackaddr, GetLastError()));
6421 else if (!VirtualFree(m.AllocationBase, 0, MEM_RELEASE)) {
6422 Debug(fprintf(stderr,
"couldn't release stack:%p:%d\n",
6423 m.AllocationBase, GetLastError()));
6434 rb_fatal(
"failed to launch waiter thread:%ld", GetLastError());
6442rb_w32_get_environ(
void)
6444 WCHAR *envtop, *env;
6445 char **myenvtop, **myenv;
6458 envtop = GetEnvironmentStringsW();
6459 for (env = envtop, num = 0; *env; env += lstrlenW(env) + 1)
6460 if (*env !=
'=') num++;
6462 myenvtop = (
char **)malloc(
sizeof(
char *) * (num + 1));
6463 for (env = envtop, myenv = myenvtop; *env; env += lstrlenW(env) + 1) {
6465 if (!(*myenv = wstr_to_utf8(env, NULL))) {
6472 FreeEnvironmentStringsW(envtop);
6479rb_w32_free_environ(
char **env)
6483 while (*t) free(*t++);
6491 return GetCurrentProcessId();
6499 typedef long (WINAPI query_func)(HANDLE, int,
void *, ULONG, ULONG *);
6500 static query_func *pNtQueryInformationProcess = (query_func *)-1;
6503 if (pNtQueryInformationProcess == (query_func *)-1)
6504 pNtQueryInformationProcess = (query_func *)get_proc_address(
"ntdll.dll",
"NtQueryInformationProcess", NULL);
6505 if (pNtQueryInformationProcess) {
6508 void* PebBaseAddress;
6509 uintptr_t AffinityMask;
6510 uintptr_t BasePriority;
6511 uintptr_t UniqueProcessId;
6512 uintptr_t ParentProcessId;
6515 long ret = pNtQueryInformationProcess(GetCurrentProcess(), 0, &pbi,
sizeof(pbi), &
len);
6517 ppid = pbi.ParentProcessId;
6524STATIC_ASSERT(std_handle, (STD_OUTPUT_HANDLE-STD_INPUT_HANDLE)==(STD_ERROR_HANDLE-STD_OUTPUT_HANDLE));
6527#define set_new_std_handle(newfd, handle) do { \
6528 if ((unsigned)(newfd) > 2) break; \
6529 SetStdHandle(STD_INPUT_HANDLE+(STD_OUTPUT_HANDLE-STD_INPUT_HANDLE)*(newfd), \
6532#define set_new_std_fd(newfd) set_new_std_handle(newfd, (HANDLE)rb_w32_get_osfhandle(newfd))
6536rb_w32_dup2(
int oldfd,
int newfd)
6540 if (oldfd == newfd)
return newfd;
6541 ret = dup2(oldfd, newfd);
6542 if (ret < 0)
return ret;
6543 set_new_std_fd(newfd);
6549rb_w32_uopen(
const char *file,
int oflag, ...)
6556 va_start(arg, oflag);
6557 pmode = va_arg(arg,
int);
6560 if (!(wfile = utf8_to_wstr(file, NULL)))
6562 ret = w32_wopen(wfile, oflag, pmode);
6569check_if_wdir(
const WCHAR *wfile)
6571 DWORD attr = GetFileAttributesW(wfile);
6572 if (attr == (DWORD)-1L ||
6573 !(attr & FILE_ATTRIBUTE_DIRECTORY) ||
6574 check_valid_dir(wfile)) {
6583rb_w32_open(
const char *file,
int oflag, ...)
6590 va_start(arg, oflag);
6591 pmode = va_arg(arg,
int);
6594 if (!(wfile = filecp_to_wstr(file, NULL)))
6596 ret = w32_wopen(wfile, oflag, pmode);
6603rb_w32_wopen(
const WCHAR *file,
int oflag, ...)
6607 if (oflag & O_CREAT) {
6609 va_start(arg, oflag);
6610 pmode = va_arg(arg,
int);
6614 return w32_wopen(file, oflag, pmode);
6618w32_wopen(
const WCHAR *file,
int oflag,
int pmode)
6624 DWORD attr = FILE_ATTRIBUTE_NORMAL;
6625 SECURITY_ATTRIBUTES sec;
6629 share_delete = oflag & O_SHARE_DELETE ? FILE_SHARE_DELETE : 0;
6630 oflag &= ~O_SHARE_DELETE;
6631 if ((oflag & O_TEXT) || !(oflag & O_BINARY)) {
6632 fd = _wopen(file, oflag, pmode);
6636 check_if_wdir(file);
6639 errno = map_errno(GetLastError());
6646 sec.nLength =
sizeof(sec);
6647 sec.lpSecurityDescriptor = NULL;
6648 if (oflag & O_NOINHERIT) {
6649 sec.bInheritHandle = FALSE;
6650 flags |= FNOINHERIT;
6653 sec.bInheritHandle = TRUE;
6655 oflag &= ~O_NOINHERIT;
6658 oflag &= ~(O_BINARY | O_TEXT);
6660 switch (oflag & (O_RDWR | O_RDONLY | O_WRONLY)) {
6662 access = GENERIC_READ | GENERIC_WRITE;
6665 access = GENERIC_READ;
6668 access = GENERIC_WRITE;
6674 oflag &= ~(O_RDWR | O_RDONLY | O_WRONLY);
6676 switch (oflag & (O_CREAT | O_EXCL | O_TRUNC)) {
6678 create = OPEN_ALWAYS;
6682 create = OPEN_EXISTING;
6684 case O_CREAT | O_EXCL:
6685 case O_CREAT | O_EXCL | O_TRUNC:
6686 create = CREATE_NEW;
6689 case O_TRUNC | O_EXCL:
6690 create = TRUNCATE_EXISTING;
6692 case O_CREAT | O_TRUNC:
6693 create = CREATE_ALWAYS;
6699 if (oflag & O_CREAT) {
6701 if (!(pmode & S_IWRITE))
6702 attr = FILE_ATTRIBUTE_READONLY;
6704 oflag &= ~(O_CREAT | O_EXCL | O_TRUNC);
6706 if (oflag & O_TEMPORARY) {
6707 attr |= FILE_FLAG_DELETE_ON_CLOSE;
6710 oflag &= ~O_TEMPORARY;
6712 if (oflag & _O_SHORT_LIVED)
6713 attr |= FILE_ATTRIBUTE_TEMPORARY;
6714 oflag &= ~_O_SHORT_LIVED;
6716 switch (oflag & (O_SEQUENTIAL | O_RANDOM)) {
6720 attr |= FILE_FLAG_SEQUENTIAL_SCAN;
6723 attr |= FILE_FLAG_RANDOM_ACCESS;
6729 oflag &= ~(O_SEQUENTIAL | O_RANDOM);
6731 if (oflag & ~O_APPEND) {
6738 h = CreateFile(
"NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
6739 fd = _open_osfhandle((intptr_t)h, 0);
6747 rb_acrt_lowio_lock_fh(fd);
6748 _set_osfhnd(fd, (intptr_t)INVALID_HANDLE_VALUE);
6749 _set_osflags(fd, 0);
6751 h = CreateFileW(file, access, FILE_SHARE_READ | FILE_SHARE_WRITE | share_delete, &sec, create, attr, NULL);
6752 if (h == INVALID_HANDLE_VALUE) {
6753 DWORD e = GetLastError();
6754 if (e != ERROR_ACCESS_DENIED || !check_if_wdir(file))
6755 errno = map_errno(e);
6756 rb_acrt_lowio_unlock_fh(fd);
6761 switch (GetFileType(h)) {
6762 case FILE_TYPE_CHAR:
6765 case FILE_TYPE_PIPE:
6768 case FILE_TYPE_UNKNOWN:
6769 errno = map_errno(GetLastError());
6771 rb_acrt_lowio_unlock_fh(fd);
6775 if (!(flags & (FDEV | FPIPE)) && (oflag & O_APPEND))
6778 _set_osfhnd(fd, (intptr_t)h);
6779 _set_osflags(fd, flags | FOPEN);
6781 rb_acrt_lowio_unlock_fh(fd);
6791rb_w32_fclose(
FILE *fp)
6793 int fd = fileno(fp);
6794 SOCKET sock = TO_SOCKET(fd);
6795 int save_errno =
errno;
6797 if (fflush(fp))
return -1;
6798 if (!is_socket(sock)) {
6799 UnlockFile((HANDLE)sock, 0, 0, LK_LEN, LK_LEN);
6802 _set_osfhnd(fd, (SOCKET)INVALID_HANDLE_VALUE);
6805 if (closesocket(sock) == SOCKET_ERROR) {
6806 errno = map_errno(WSAGetLastError());
6814rb_w32_pipe(
int fds[2])
6816 static long serial = 0;
6817 static const char prefix[] =
"\\\\.\\pipe\\ruby";
6819 width_of_prefix = (int)
sizeof(prefix) - 1,
6820 width_of_pid = (int)
sizeof(rb_pid_t) * 2,
6821 width_of_serial = (int)
sizeof(serial) * 2,
6822 width_of_ids = width_of_pid + 1 + width_of_serial + 1
6824 char name[
sizeof(prefix) + width_of_ids];
6825 SECURITY_ATTRIBUTES sec;
6826 HANDLE hRead, hWrite, h;
6827 int fdRead, fdWrite;
6830 memcpy(name, prefix, width_of_prefix);
6831 snprintf(name + width_of_prefix, width_of_ids,
"%.*"PRI_PIDT_PREFIX"x-%.*lx",
6832 width_of_pid, rb_w32_getpid(), width_of_serial, (
unsigned long)(InterlockedIncrement(&serial)-1));
6834 sec.nLength =
sizeof(sec);
6835 sec.lpSecurityDescriptor = NULL;
6836 sec.bInheritHandle = FALSE;
6839 hRead = CreateNamedPipe(name, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
6840 0, 2, 65536, 65536, 0, &sec);
6842 if (hRead == INVALID_HANDLE_VALUE) {
6843 DWORD err = GetLastError();
6844 if (err == ERROR_PIPE_BUSY)
6847 errno = map_errno(GetLastError());
6852 hWrite = CreateFile(name, GENERIC_READ | GENERIC_WRITE, 0, &sec,
6853 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
6855 if (hWrite == INVALID_HANDLE_VALUE) {
6856 errno = map_errno(GetLastError());
6863 h = CreateFile(
"NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
6864 fdRead = _open_osfhandle((intptr_t)h, 0);
6868 CloseHandle(hWrite);
6874 rb_acrt_lowio_lock_fh(fdRead);
6875 _set_osfhnd(fdRead, (intptr_t)hRead);
6876 _set_osflags(fdRead, FOPEN | FPIPE | FNOINHERIT);
6877 rb_acrt_lowio_unlock_fh(fdRead);
6883 h = CreateFile(
"NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
6884 fdWrite = _open_osfhandle((intptr_t)h, 0);
6886 if (fdWrite == -1) {
6888 CloseHandle(hWrite);
6892 rb_acrt_lowio_lock_fh(fdWrite);
6893 _set_osfhnd(fdWrite, (intptr_t)hWrite);
6894 _set_osflags(fdWrite, FOPEN | FPIPE | FNOINHERIT);
6895 rb_acrt_lowio_unlock_fh(fdWrite);
6898 rb_w32_close(fdRead);
6910console_emulator_p(
void)
6912 const void *
const func = WriteConsoleW;
6914 MEMORY_BASIC_INFORMATION m;
6916 memset(&m, 0,
sizeof(m));
6917 if (!VirtualQuery(func, &m,
sizeof(m))) {
6920 k = GetModuleHandle(
"kernel32.dll");
6921 if (!k)
return FALSE;
6922 return (HMODULE)m.AllocationBase != k;
6927constat_handle(HANDLE h)
6931 thread_exclusive(conlist) {
6933 if (console_emulator_p()) {
6934 conlist = conlist_disabled;
6937 conlist = st_init_numtable();
6938 install_vm_exit_handler();
6940 else if (conlist == conlist_disabled) {
6943 if (st_lookup(conlist, (st_data_t)h, &data)) {
6947 CONSOLE_SCREEN_BUFFER_INFO csbi;
6949 p->vt100.state = constat_init;
6950 p->vt100.attr = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED;
6951 p->vt100.reverse = 0;
6952 p->vt100.saved.X = p->vt100.saved.Y = 0;
6953 if (GetConsoleScreenBufferInfo(h, &csbi)) {
6954 p->vt100.attr = csbi.wAttributes;
6956 st_insert(conlist, (st_data_t)h, (st_data_t)p);
6962#define FOREGROUND_MASK (FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY)
6963#define BACKGROUND_MASK (BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_INTENSITY)
6965#define constat_attr_color_reverse(attr) \
6966 ((attr) & ~(FOREGROUND_MASK | BACKGROUND_MASK)) | \
6967 (((attr) & FOREGROUND_MASK) << 4) | \
6968 (((attr) & BACKGROUND_MASK) >> 4)
6972constat_attr(
int count,
const int *seq, WORD attr, WORD default_attr,
int *reverse)
6977 if (!count)
return attr;
6978 if (rev) attr = constat_attr_color_reverse(attr);
6979 bold = attr & FOREGROUND_INTENSITY;
6980 attr &= ~(FOREGROUND_INTENSITY | BACKGROUND_INTENSITY);
6982 while (count-- > 0) {
6985 attr = default_attr;
6990 bold = FOREGROUND_INTENSITY;
6996#ifndef COMMON_LVB_UNDERSCORE
6997#define COMMON_LVB_UNDERSCORE 0x8000
6999 attr |= COMMON_LVB_UNDERSCORE;
7002 attr &= ~COMMON_LVB_UNDERSCORE;
7012 attr &= ~(FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED);
7015 attr = (attr & ~(FOREGROUND_BLUE | FOREGROUND_GREEN)) | FOREGROUND_RED;
7018 attr = (attr & ~(FOREGROUND_BLUE | FOREGROUND_RED)) | FOREGROUND_GREEN;
7021 attr = (attr & ~FOREGROUND_BLUE) | FOREGROUND_GREEN | FOREGROUND_RED;
7024 attr = (attr & ~(FOREGROUND_GREEN | FOREGROUND_RED)) | FOREGROUND_BLUE;
7027 attr = (attr & ~FOREGROUND_GREEN) | FOREGROUND_BLUE | FOREGROUND_RED;
7030 attr = (attr & ~FOREGROUND_RED) | FOREGROUND_BLUE | FOREGROUND_GREEN;
7033 attr |= FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED;
7038 attr = (attr & ~FOREGROUND_MASK) | (default_attr & FOREGROUND_MASK);
7042 attr &= ~(BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED);
7045 attr = (attr & ~(BACKGROUND_BLUE | BACKGROUND_GREEN)) | BACKGROUND_RED;
7048 attr = (attr & ~(BACKGROUND_BLUE | BACKGROUND_RED)) | BACKGROUND_GREEN;
7051 attr = (attr & ~BACKGROUND_BLUE) | BACKGROUND_GREEN | BACKGROUND_RED;
7054 attr = (attr & ~(BACKGROUND_GREEN | BACKGROUND_RED)) | BACKGROUND_BLUE;
7057 attr = (attr & ~BACKGROUND_GREEN) | BACKGROUND_BLUE | BACKGROUND_RED;
7060 attr = (attr & ~BACKGROUND_RED) | BACKGROUND_BLUE | BACKGROUND_GREEN;
7063 attr |= BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED;
7068 attr = (attr & ~BACKGROUND_MASK) | (default_attr & BACKGROUND_MASK);
7073 if (rev) attr = constat_attr_color_reverse(attr);
7080constat_clear(HANDLE handle, WORD attr, DWORD
len, COORD pos)
7084 FillConsoleOutputAttribute(handle, attr,
len, pos, &written);
7085 FillConsoleOutputCharacterW(handle, L
' ',
len, pos, &written);
7090constat_apply(HANDLE handle,
struct constat *s, WCHAR w)
7092 CONSOLE_SCREEN_BUFFER_INFO csbi;
7093 const int *seq = s->vt100.seq;
7094 int count = s->vt100.state;
7098 if (!GetConsoleScreenBufferInfo(handle, &csbi))
return;
7099 arg0 = (count > 0 && seq[0] > 0);
7100 if (arg0) arg1 = seq[0];
7103 SetConsoleTextAttribute(handle, constat_attr(count, seq, csbi.wAttributes, s->vt100.attr, &s->vt100.reverse));
7106 csbi.dwCursorPosition.X = 0;
7108 csbi.dwCursorPosition.Y -= arg1;
7109 if (csbi.dwCursorPosition.Y < csbi.srWindow.Top)
7110 csbi.dwCursorPosition.Y = csbi.srWindow.Top;
7111 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
7114 csbi.dwCursorPosition.X = 0;
7117 csbi.dwCursorPosition.Y += arg1;
7118 if (csbi.dwCursorPosition.Y > csbi.srWindow.Bottom)
7119 csbi.dwCursorPosition.Y = csbi.srWindow.Bottom;
7120 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
7123 csbi.dwCursorPosition.X += arg1;
7124 if (csbi.dwCursorPosition.X >= csbi.srWindow.Right)
7125 csbi.dwCursorPosition.X = csbi.srWindow.Right;
7126 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
7129 csbi.dwCursorPosition.X -= arg1;
7130 if (csbi.dwCursorPosition.X < csbi.srWindow.Left)
7131 csbi.dwCursorPosition.X = csbi.srWindow.Left;
7132 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
7136 arg1 += csbi.srWindow.Left;
7137 if (arg1 > csbi.srWindow.Right)
7138 arg1 = csbi.srWindow.Right;
7139 csbi.dwCursorPosition.X = arg1;
7140 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
7143 arg1 += csbi.srWindow.Top;
7144 if (arg1 > csbi.srWindow.Bottom)
7145 arg1 = csbi.srWindow.Bottom;
7146 csbi.dwCursorPosition.Y = arg1;
7147 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
7151 pos.Y = arg1 + csbi.srWindow.Top - 1;
7152 if (pos.Y > csbi.srWindow.Bottom) pos.Y = csbi.srWindow.Bottom;
7153 if (count < 2 || (arg1 = seq[1]) <= 0) arg1 = 1;
7154 pos.X = arg1 + csbi.srWindow.Left - 1;
7155 if (pos.X > csbi.srWindow.Right) pos.X = csbi.srWindow.Right;
7156 SetConsoleCursorPosition(handle, pos);
7159 switch (arg0 ? arg1 : 0) {
7161 constat_clear(handle, csbi.wAttributes,
7162 (csbi.dwSize.X * (csbi.srWindow.Bottom - csbi.dwCursorPosition.Y + 1)
7163 - csbi.dwCursorPosition.X),
7164 csbi.dwCursorPosition);
7168 pos.Y = csbi.srWindow.Top;
7169 constat_clear(handle, csbi.wAttributes,
7170 (csbi.dwSize.X * (csbi.dwCursorPosition.Y - csbi.srWindow.Top)
7171 + csbi.dwCursorPosition.X + 1),
7176 pos.Y = csbi.srWindow.Top;
7177 constat_clear(handle, csbi.wAttributes,
7178 (csbi.dwSize.X * (csbi.srWindow.Bottom - csbi.srWindow.Top + 1)),
7184 constat_clear(handle, csbi.wAttributes,
7185 (csbi.dwSize.X * csbi.dwSize.Y),
7191 switch (arg0 ? arg1 : 0) {
7193 constat_clear(handle, csbi.wAttributes,
7194 (csbi.dwSize.X - csbi.dwCursorPosition.X),
7195 csbi.dwCursorPosition);
7199 pos.Y = csbi.dwCursorPosition.Y;
7200 constat_clear(handle, csbi.wAttributes,
7201 csbi.dwCursorPosition.X + 1, pos);
7205 pos.Y = csbi.dwCursorPosition.Y;
7206 constat_clear(handle, csbi.wAttributes,
7207 csbi.dwSize.X, pos);
7212 s->vt100.saved = csbi.dwCursorPosition;
7215 SetConsoleCursorPosition(handle, s->vt100.saved);
7218 if (count >= 2 && seq[0] == -1 && seq[1] == 25) {
7219 CONSOLE_CURSOR_INFO cci;
7220 GetConsoleCursorInfo(handle, &cci);
7221 cci.bVisible = TRUE;
7222 SetConsoleCursorInfo(handle, &cci);
7226 if (count >= 2 && seq[0] == -1 && seq[1] == 25) {
7227 CONSOLE_CURSOR_INFO cci;
7228 GetConsoleCursorInfo(handle, &cci);
7229 cci.bVisible = FALSE;
7230 SetConsoleCursorInfo(handle, &cci);
7238static const long MAXSIZE_CONSOLE_WRITING = 31366;
7242constat_parse(HANDLE h,
struct constat *s,
const WCHAR **ptrp,
long *lenp)
7244 const WCHAR *ptr = *ptrp;
7245 long rest,
len = *lenp;
7249 rest = *lenp -
len - 1;
7250 if (s->vt100.state == constat_esc) {
7253 s->vt100.state = constat_init;
7254 if (
len > 0 && *ptr != L
'[')
continue;
7255 s->vt100.state = constat_esc;
7257 else if (s->vt100.state == constat_esc) {
7260 s->vt100.state = constat_init;
7263 rest = *lenp -
len - 1;
7264 if (rest > 0) --rest;
7265 s->vt100.state = constat_seq;
7266 s->vt100.seq[0] = 0;
7268 else if (s->vt100.state >= constat_seq) {
7269 if (wc >= L
'0' && wc <= L
'9') {
7270 if (s->vt100.state < (
int)numberof(s->vt100.seq)) {
7271 int *seq = &s->vt100.seq[s->vt100.state];
7272 *seq = (*seq * 10) + (wc - L
'0');
7275 else if (s->vt100.state == constat_seq && s->vt100.seq[0] == 0 && wc == L
'?') {
7276 s->vt100.seq[s->vt100.state++] = -1;
7280 if (++s->vt100.state < (
int)numberof(s->vt100.seq)) {
7281 s->vt100.seq[s->vt100.state] = 0;
7284 s->vt100.state = (int)numberof(s->vt100.seq);
7288 constat_apply(h, s, wc);
7289 s->vt100.state = constat_init;
7294 else if ((rest = *lenp -
len) < MAXSIZE_CONSOLE_WRITING) {
7312 SOCKET sock = TO_SOCKET(fd);
7313 int save_errno =
errno;
7315 if (!is_socket(sock)) {
7316 UnlockFile((HANDLE)sock, 0, 0, LK_LEN, LK_LEN);
7317 constat_delete((HANDLE)sock);
7320 _set_osfhnd(fd, (SOCKET)INVALID_HANDLE_VALUE);
7321 socklist_delete(&sock, NULL);
7324 if (closesocket(sock) == SOCKET_ERROR) {
7325 errno = map_errno(WSAGetLastError());
7331#ifndef INVALID_SET_FILE_POINTER
7332#define INVALID_SET_FILE_POINTER ((DWORD)-1)
7336setup_overlapped(OVERLAPPED *ol,
int fd,
int iswrite, rb_off_t *_offset)
7338 memset(ol, 0,
sizeof(*ol));
7343 DWORD seek_method = ((_osfile(fd) & FAPPEND) && iswrite) ? FILE_END : FILE_CURRENT;
7347 uint64_t offset = *_offset;
7348 ol->Offset = (uint32_t)(offset & 0xFFFFFFFFLL);
7349 ol->OffsetHigh = (uint32_t)((offset & 0xFFFFFFFF00000000LL) >> 32);
7352 LARGE_INTEGER seek_offset = {0}, current_offset = {0};
7353 if (!SetFilePointerEx((HANDLE)_osfhnd(fd), seek_offset, ¤t_offset, seek_method)) {
7354 DWORD last_error = GetLastError();
7355 if (last_error != NO_ERROR) {
7356 errno = map_errno(last_error);
7362 *_offset = current_offset.QuadPart;
7364 else if (!(_osfile(fd) & (FDEV | FPIPE))) {
7366 DWORD low = SetFilePointer((HANDLE)_osfhnd(fd), 0, &high, seek_method);
7368 if (low == INVALID_SET_FILE_POINTER) {
7369 DWORD err = GetLastError();
7370 if (err != NO_ERROR) {
7371 errno = map_errno(err);
7377 ol->OffsetHigh = high;
7380 ol->hEvent = CreateEvent(NULL, TRUE, TRUE, NULL);
7382 errno = map_errno(GetLastError());
7389finish_overlapped(OVERLAPPED *ol,
int fd, DWORD size, rb_off_t *_offset)
7391 CloseHandle(ol->hEvent);
7395 DWORD seek_method = (_osfile(fd) & FAPPEND) ? FILE_END : FILE_BEGIN;
7397 LARGE_INTEGER seek_offset = {0};
7398 if (seek_method == FILE_BEGIN) {
7399 seek_offset.QuadPart = *_offset;
7402 SetFilePointerEx((HANDLE)_osfhnd(fd), seek_offset, NULL, seek_method);
7404 else if (!(_osfile(fd) & (FDEV | FPIPE))) {
7405 LONG high = ol->OffsetHigh;
7406 DWORD low = ol->Offset + size;
7407 if (low < ol->Offset)
7409 SetFilePointer((HANDLE)_osfhnd(fd), low, &high, FILE_BEGIN);
7416rb_w32_read_internal(
int fd,
void *buf,
size_t size, rb_off_t *offset)
7418 SOCKET sock = TO_SOCKET(fd);
7426 if (is_socket(sock))
7427 return rb_w32_recv(fd, buf, size, 0);
7430 if (_get_osfhandle(fd) == -1) {
7434 if (!offset && _osfile(fd) & FTEXT) {
7435 return _read(fd, buf, size);
7438 rb_acrt_lowio_lock_fh(fd);
7440 if (!size || _osfile(fd) & FEOFLAG) {
7441 _set_osflags(fd, _osfile(fd) & ~FEOFLAG);
7442 rb_acrt_lowio_unlock_fh(fd);
7451 if (setup_overlapped(&ol, fd, FALSE, offset)) {
7452 rb_acrt_lowio_unlock_fh(fd);
7456 if (!ReadFile((HANDLE)_osfhnd(fd), buf,
len, &read, &ol)) {
7457 err = GetLastError();
7458 if (err == ERROR_NO_DATA && (_osfile(fd) & FPIPE)) {
7460 if (GetNamedPipeHandleState((HANDLE)_osfhnd(fd), &state, NULL, NULL, NULL, NULL, 0) && (state & PIPE_NOWAIT)) {
7461 errno = EWOULDBLOCK;
7464 errno = map_errno(err);
7466 rb_acrt_lowio_unlock_fh(fd);
7469 else if (err != ERROR_IO_PENDING) {
7470 CloseHandle(ol.hEvent);
7471 if (err == ERROR_ACCESS_DENIED)
7473 else if (err == ERROR_BROKEN_PIPE || err == ERROR_HANDLE_EOF) {
7474 rb_acrt_lowio_unlock_fh(fd);
7478 errno = map_errno(err);
7480 rb_acrt_lowio_unlock_fh(fd);
7484 wait = rb_w32_wait_events_blocking(&ol.hEvent, 1, INFINITE);
7485 if (wait != WAIT_OBJECT_0) {
7486 if (wait == WAIT_OBJECT_0 + 1)
7489 errno = map_errno(GetLastError());
7490 CloseHandle(ol.hEvent);
7491 CancelIo((HANDLE)_osfhnd(fd));
7492 rb_acrt_lowio_unlock_fh(fd);
7496 if (!GetOverlappedResult((HANDLE)_osfhnd(fd), &ol, &read, TRUE) &&
7497 (err = GetLastError()) != ERROR_HANDLE_EOF) {
7499 if (err != ERROR_BROKEN_PIPE) {
7500 errno = map_errno(err);
7503 CloseHandle(ol.hEvent);
7504 CancelIo((HANDLE)_osfhnd(fd));
7505 rb_acrt_lowio_unlock_fh(fd);
7510 err = GetLastError();
7511 errno = map_errno(err);
7514 finish_overlapped(&ol, fd, read, offset);
7518 buf = (
char *)buf + read;
7519 if (err != ERROR_OPERATION_ABORTED && size > 0)
7523 _set_osflags(fd, _osfile(fd) | FEOFLAG);
7526 rb_acrt_lowio_unlock_fh(fd);
7534rb_w32_write_internal(
int fd,
const void *buf,
size_t size, rb_off_t *offset)
7536 SOCKET sock = TO_SOCKET(fd);
7544 if (is_socket(sock))
7545 return rb_w32_send(fd, buf, size, 0);
7548 if (_get_osfhandle(fd) == -1) {
7553 if (!offset && (_osfile(fd) & FTEXT) &&
7554 (!(_osfile(fd) & FPIPE) || fd == fileno(stdout) || fd == fileno(stderr))) {
7555 ssize_t w = _write(fd, buf, size);
7556 if (w == (ssize_t)-1 &&
errno == EINVAL) {
7557 errno = map_errno(GetLastError());
7562 rb_acrt_lowio_lock_fh(fd);
7564 if (!size || _osfile(fd) & FEOFLAG) {
7565 rb_acrt_lowio_unlock_fh(fd);
7571 len = (_osfile(fd) & FDEV) ? min(MAXSIZE_CONSOLE_WRITING, size) : size;
7576 if (setup_overlapped(&ol, fd, TRUE, offset)) {
7577 rb_acrt_lowio_unlock_fh(fd);
7581 if (!WriteFile((HANDLE)_osfhnd(fd), buf,
len, &written, &ol)) {
7582 err = GetLastError();
7583 if (err != ERROR_IO_PENDING) {
7584 CloseHandle(ol.hEvent);
7585 if (err == ERROR_ACCESS_DENIED)
7588 errno = map_errno(err);
7590 rb_acrt_lowio_unlock_fh(fd);
7594 wait = rb_w32_wait_events_blocking(&ol.hEvent, 1, INFINITE);
7595 if (wait != WAIT_OBJECT_0) {
7596 if (wait == WAIT_OBJECT_0 + 1)
7599 errno = map_errno(GetLastError());
7600 CloseHandle(ol.hEvent);
7601 CancelIo((HANDLE)_osfhnd(fd));
7602 rb_acrt_lowio_unlock_fh(fd);
7606 if (!GetOverlappedResult((HANDLE)_osfhnd(fd), &ol, &written, TRUE)) {
7607 errno = map_errno(GetLastError());
7608 CloseHandle(ol.hEvent);
7609 CancelIo((HANDLE)_osfhnd(fd));
7610 rb_acrt_lowio_unlock_fh(fd);
7615 finish_overlapped(&ol, fd, written, offset);
7618 if (written ==
len) {
7619 buf = (
const char *)buf +
len;
7624 size_t newlen =
len / 2;
7626 size +=
len - newlen;
7631 errno = EWOULDBLOCK;
7634 rb_acrt_lowio_unlock_fh(fd);
7640rb_w32_read(
int fd,
void *buf,
size_t size)
7642 return rb_w32_read_internal(fd, buf, size, NULL);
7646rb_w32_write(
int fd,
const void *buf,
size_t size)
7648 return rb_w32_write_internal(fd, buf, size, NULL);
7652rb_w32_pread(
int descriptor,
void *base,
size_t size, rb_off_t offset)
7654 return rb_w32_read_internal(descriptor, base, size, &offset);
7658rb_w32_pwrite(
int descriptor,
const void *base,
size_t size, rb_off_t offset)
7660 return rb_w32_write_internal(descriptor, base, size, &offset);
7665rb_w32_write_console(uintptr_t strarg,
int fd)
7668 DWORD dwMode, reslen;
7672 const WCHAR *ptr, *next;
7676 handle = (HANDLE)_osfhnd(fd);
7677 if (!GetConsoleMode(handle, &dwMode))
7680 s = constat_handle(handle);
7690 case ENCINDEX_US_ASCII:
7691 case ENCINDEX_ASCII_8BIT:
7693 case ENCINDEX_UTF_8:
7694 ptr = wbuffer = mbstr_to_wstr(CP_UTF8, RSTRING_PTR(str), RSTRING_LEN(str), &
len);
7695 if (!ptr)
return -1L;
7697 case ENCINDEX_UTF_16LE:
7698 ptr = (
const WCHAR *)RSTRING_PTR(str);
7699 len = RSTRING_LEN(str) /
sizeof(WCHAR);
7703 if (dwMode & ENABLE_VIRTUAL_TERMINAL_PROCESSING) {
7704 if (!WriteConsoleW(handle, ptr,
len, &reslen, NULL))
7705 reslen = (DWORD)-1L;
7709 long curlen = constat_parse(handle, s, (next = ptr, &next), &
len);
7710 reslen += next - ptr;
7713 if (!WriteConsoleW(handle, ptr, curlen, &written, NULL)) {
7714 reslen = (DWORD)-1L;
7723 return (
long)reslen;
7728timespec_to_filetime(
const struct timespec *ts, FILETIME *ft)
7732 tmp.QuadPart = unix_to_filetime((ULONGLONG)ts->tv_sec);
7733 tmp.QuadPart += ts->tv_nsec / 100;
7734 ft->dwLowDateTime = tmp.LowPart;
7735 ft->dwHighDateTime = tmp.HighPart;
7741wutimensat(
int dirfd,
const WCHAR *path,
const struct timespec *times,
int flags)
7744 FILETIME atime, mtime;
7749 if (dirfd != AT_FDCWD) {
7759 if (wstati128(path, &stat, FALSE)) {
7764 if (timespec_to_filetime(×[0], &atime)) {
7767 if (timespec_to_filetime(×[1], &mtime)) {
7772 GetSystemTimePreciseAsFileTime(&atime);
7777 const DWORD attr = GetFileAttributesW(path);
7778 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY))
7779 SetFileAttributesW(path, attr & ~FILE_ATTRIBUTE_READONLY);
7780 hFile = open_special(path, GENERIC_WRITE, 0);
7781 if (hFile == INVALID_HANDLE_VALUE) {
7782 errno = map_errno(GetLastError());
7786 if (!SetFileTime(hFile, NULL, &atime, &mtime)) {
7787 errno = map_errno(GetLastError());
7792 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY))
7793 SetFileAttributesW(path, attr);
7801w32_utimensat(
int dirfd,
const char *path,
const struct timespec *times,
int flags, UINT cp)
7803 WCHAR *wpath = mbstr_to_wstr(cp, path, -1, NULL);
7807 ret = wutimensat(dirfd, wpath, times, flags);
7815rb_w32_uutime(
const char *path,
const struct utimbuf *times)
7819 ts[0].tv_sec = times->actime;
7821 ts[1].tv_sec = times->modtime;
7823 return w32_utimensat(AT_FDCWD, path, ts, 0, CP_UTF8);
7828rb_w32_utime(
const char *path,
const struct utimbuf *times)
7832 ts[0].tv_sec = times->actime;
7834 ts[1].tv_sec = times->modtime;
7836 return w32_utimensat(AT_FDCWD, path, ts, 0, filecp());
7841rb_w32_uutimes(
const char *path,
const struct timeval *times)
7845 ts[0].tv_sec = times[0].tv_sec;
7846 ts[0].tv_nsec = times[0].tv_usec * 1000;
7847 ts[1].tv_sec = times[1].tv_sec;
7848 ts[1].tv_nsec = times[1].tv_usec * 1000;
7849 return w32_utimensat(AT_FDCWD, path, ts, 0, CP_UTF8);
7854rb_w32_utimes(
const char *path,
const struct timeval *times)
7858 ts[0].tv_sec = times[0].tv_sec;
7859 ts[0].tv_nsec = times[0].tv_usec * 1000;
7860 ts[1].tv_sec = times[1].tv_sec;
7861 ts[1].tv_nsec = times[1].tv_usec * 1000;
7862 return w32_utimensat(AT_FDCWD, path, ts, 0, filecp());
7867rb_w32_uutimensat(
int dirfd,
const char *path,
const struct timespec *times,
int flags)
7869 return w32_utimensat(dirfd, path, times, flags, CP_UTF8);
7874rb_w32_utimensat(
int dirfd,
const char *path,
const struct timespec *times,
int flags)
7876 return w32_utimensat(dirfd, path, times, flags, filecp());
7881rb_w32_uchdir(
const char *path)
7886 if (!(wpath = utf8_to_wstr(path, NULL)))
7888 ret = _wchdir(wpath);
7895wmkdir(
const WCHAR *wpath,
int mode)
7900 if (CreateDirectoryW(wpath, NULL) == FALSE) {
7901 errno = map_errno(GetLastError());
7904 if (_wchmod(wpath, mode) == -1) {
7905 RemoveDirectoryW(wpath);
7915rb_w32_umkdir(
const char *path,
int mode)
7920 if (!(wpath = utf8_to_wstr(path, NULL)))
7922 ret = wmkdir(wpath, mode);
7929rb_w32_mkdir(
const char *path,
int mode)
7934 if (!(wpath = filecp_to_wstr(path, NULL)))
7936 ret = wmkdir(wpath, mode);
7943wrmdir(
const WCHAR *wpath)
7947 const DWORD attr = GetFileAttributesW(wpath);
7948 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY)) {
7949 SetFileAttributesW(wpath, attr & ~FILE_ATTRIBUTE_READONLY);
7951 if (RemoveDirectoryW(wpath) == FALSE) {
7952 errno = map_errno(GetLastError());
7954 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY)) {
7955 SetFileAttributesW(wpath, attr);
7964rb_w32_rmdir(
const char *path)
7969 if (!(wpath = filecp_to_wstr(path, NULL)))
7971 ret = wrmdir(wpath);
7978rb_w32_urmdir(
const char *path)
7983 if (!(wpath = utf8_to_wstr(path, NULL)))
7985 ret = wrmdir(wpath);
7992wunlink(
const WCHAR *path)
7995 const DWORD SYMLINKD = FILE_ATTRIBUTE_REPARSE_POINT|FILE_ATTRIBUTE_DIRECTORY;
7997 const DWORD attr = GetFileAttributesW(path);
7998 if (attr == (DWORD)-1) {
8000 else if ((attr & SYMLINKD) == SYMLINKD) {
8001 ret = RemoveDirectoryW(path);
8004 if (attr & FILE_ATTRIBUTE_READONLY) {
8005 SetFileAttributesW(path, attr & ~FILE_ATTRIBUTE_READONLY);
8007 ret = DeleteFileW(path);
8010 errno = map_errno(GetLastError());
8012 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY)) {
8013 SetFileAttributesW(path, attr);
8022rb_w32_uunlink(
const char *path)
8027 if (!(wpath = utf8_to_wstr(path, NULL)))
8029 ret = wunlink(wpath);
8036rb_w32_unlink(
const char *path)
8041 if (!(wpath = filecp_to_wstr(path, NULL)))
8043 ret = wunlink(wpath);
8050rb_w32_uchmod(
const char *path,
int mode)
8055 if (!(wpath = utf8_to_wstr(path, NULL)))
8057 ret = _wchmod(wpath, mode);
8064fchmod(
int fd,
int mode)
8068 LARGE_INTEGER CreationTime;
8069 LARGE_INTEGER LastAccessTime;
8070 LARGE_INTEGER LastWriteTime;
8071 LARGE_INTEGER ChangeTime;
8072 DWORD FileAttributes;
8073 } info = {{{0}}, {{0}}, {{0}},};
8074 HANDLE h = (HANDLE)_get_osfhandle(fd);
8076 info.FileAttributes = FILE_ATTRIBUTE_NORMAL;
8077 if (!(mode & 0200)) info.FileAttributes |= FILE_ATTRIBUTE_READONLY;
8078 if (!SetFileInformationByHandle(h, 0, &info,
sizeof(info))) {
8079 errno = map_errno(GetLastError());
8087rb_w32_isatty(
int fd)
8092 if (_get_osfhandle(fd) == -1) {
8095 if (!GetConsoleMode((HANDLE)_osfhnd(fd), &mode)) {
8107 int *ip = (
int *)(&x + 1) - 1;
8114rb_w32_inet_ntop(
int af,
const void *addr,
char *numaddr,
size_t numaddr_len)
8116 return (inet_ntop)(af, (
void *)addr, numaddr, numaddr_len);
8121rb_w32_inet_pton(
int af,
const char *src,
void *dst)
8123 return (inet_pton)(af, src, dst);
8128rb_w32_fd_is_text(
int fd)
8130 return _osfile(fd) & FTEXT;
8133#ifdef HAVE__GMTIME64_S
8134# ifndef HAVE__LOCALTIME64_S
8136# define HAVE__LOCALTIME64_S 1
8138# ifndef MINGW_HAS_SECURE_API
8139 _CRTIMP errno_t __cdecl _gmtime64_s(
struct tm* tm,
const __time64_t *time);
8140 _CRTIMP errno_t __cdecl _localtime64_s(
struct tm* tm,
const __time64_t *time);
8142# define gmtime_s _gmtime64_s
8143# define localtime_s _localtime64_s
8148gmtime_r(
const time_t *tp,
struct tm *rp)
8156 e = gmtime_s(rp, tp);
8157 if (e != 0)
goto error;
8163localtime_r(
const time_t *tp,
struct tm *rp)
8171 e = localtime_s(rp, tp);
8178rb_w32_wrap_io_handle(HANDLE h,
int flags)
8181 int len =
sizeof(tmp);
8182 int r = getsockopt((SOCKET)h, SOL_SOCKET, SO_DEBUG, (
char *)&tmp, &
len);
8183 if (r != SOCKET_ERROR || WSAGetLastError() != WSAENOTSOCK) {
8185 if (flags & O_NONBLOCK) {
8186 flags &= ~O_NONBLOCK;
8189 socklist_insert((SOCKET)h, f);
8191 else if (flags & O_NONBLOCK) {
8195 return rb_w32_open_osfhandle((intptr_t)h, flags);
8200rb_w32_unwrap_io_handle(
int fd)
8202 SOCKET sock = TO_SOCKET(fd);
8203 _set_osfhnd(fd, (SOCKET)INVALID_HANDLE_VALUE);
8204 if (!is_socket(sock)) {
8205 UnlockFile((HANDLE)sock, 0, 0, LK_LEN, LK_LEN);
8206 constat_delete((HANDLE)sock);
8209 socklist_delete(&sock, NULL);
8214#if !defined(__MINGW64__) && defined(__MINGW64_VERSION_MAJOR)
8220rb_w32_pow(
double x,
double y)
8224 unsigned int default_control = _controlfp(0, 0);
8225 _controlfp(_PC_64, _MCW_PC);
8228 _controlfp(default_control, _MCW_PC);
8236 BY_HANDLE_FILE_INFORMATION bhfi;
8247 tmp = rb_check_convert_type_with_id(*file,
T_FILE,
"IO", idTo_io);
8250 if (f == (HANDLE)-1)
return INVALID_HANDLE_VALUE;
8259 tmp = rb_str_encode_ospath(*file);
8260 len = MultiByteToWideChar(CP_UTF8, 0, RSTRING_PTR(tmp), -1, NULL, 0);
8262 MultiByteToWideChar(CP_UTF8, 0, RSTRING_PTR(tmp), -1, ptr,
len);
8263 f = CreateFileW(ptr, 0,
8264 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
8265 FILE_FLAG_BACKUP_SEMANTICS, NULL);
8267 if (f == INVALID_HANDLE_VALUE)
return f;
8270 if (GetFileType(f) == FILE_TYPE_DISK) {
8271 ZeroMemory(st,
sizeof(*st));
8272 if (get_ino(f, &st->info.fii)) {
8273 st->file_id_p = TRUE;
8276 else if (GetLastError() != ERROR_INVALID_PARAMETER) {
8278 return INVALID_HANDLE_VALUE;
8282 if (GetFileInformationByHandle(f, &st->info.bhfi)) {
8283 st->file_id_p = FALSE;
8287 if (ret) CloseHandle(ret);
8288 return INVALID_HANDLE_VALUE;
8292close_handle(
VALUE h)
8294 CloseHandle((HANDLE)h);
8304call_w32_io_info(
VALUE arg)
8307 return (
VALUE)w32_io_info(p->fname, p->st);
8311rb_w32_file_identical_p(
VALUE fname1,
VALUE fname2)
8314 HANDLE f1 = 0, f2 = 0;
8316 f1 = w32_io_info(&fname1, &st1);
8317 if (f1 == INVALID_HANDLE_VALUE)
return Qfalse;
8320 arg.fname = &fname2;
8325 f2 = w32_io_info(&fname2, &st2);
8327 if (f2 == INVALID_HANDLE_VALUE)
return Qfalse;
8328 if (f2) CloseHandle(f2);
8330 if (st1.file_id_p != st2.file_id_p)
return Qfalse;
8331 if (!st1.file_id_p) {
8332 if (st1.info.bhfi.dwVolumeSerialNumber == st2.info.bhfi.dwVolumeSerialNumber &&
8333 st1.info.bhfi.nFileIndexHigh == st2.info.bhfi.nFileIndexHigh &&
8334 st1.info.bhfi.nFileIndexLow == st2.info.bhfi.nFileIndexLow)
8338 if (st1.info.fii.VolumeSerialNumber == st2.info.fii.VolumeSerialNumber &&
8339 memcmp(&st1.info.fii.FileId, &st2.info.fii.FileId,
sizeof(
FILE_ID_128)) == 0)
8346rb_w32_set_thread_description(HANDLE th,
const WCHAR *name)
8349 typedef HRESULT (WINAPI *set_thread_description_func)(HANDLE, PCWSTR);
8350 static set_thread_description_func set_thread_description =
8351 (set_thread_description_func)-1;
8352 if (set_thread_description == (set_thread_description_func)-1) {
8354 set_thread_description = (set_thread_description_func)
8355 get_proc_address(
"kernel32",
"SetThreadDescription", NULL);
8357 if (set_thread_description) {
8358 result = set_thread_description(th, name);
8364rb_w32_set_thread_description_str(HANDLE th,
VALUE name)
8366 int idx, result = FALSE;
8370 return rb_w32_set_thread_description(th, L
"");
8373 idx = rb_enc_get_index(name);
8374 if (idx == ENCINDEX_UTF_16LE) {
8375 result = rb_w32_set_thread_description(th, s);
8378 name =
rb_str_conv_enc(name, rb_enc_from_index(idx), rb_utf8_encoding());
8379 s = mbstr_to_wstr(CP_UTF8, RSTRING_PTR(name), RSTRING_LEN(name)+1, NULL);
8380 result = rb_w32_set_thread_description(th, s);
8390rb_w32_mmap(
void *addr,
size_t len,
int prot,
int flags,
int fd, rb_off_t offset)
8394 DWORD protect = PAGE_EXECUTE_READWRITE;
8396 if (fd > 0 || offset) {
8411 ptr = VirtualAlloc(addr,
len, MEM_RESERVE | MEM_COMMIT, protect);
8413 errno = rb_w32_map_errno(GetLastError());
8421rb_w32_munmap(
void *addr,
size_t len)
8423 if (!VirtualFree(addr, 0, MEM_RELEASE)) {
8424 errno = rb_w32_map_errno(GetLastError());
8432rb_w32_mprotect(
void *addr,
size_t len,
int prot)
8448 if (prot & PROT_EXEC) {
8449 if (!FlushInstructionCache(GetCurrentProcess(), addr,
len)) {
8450 errno = rb_w32_map_errno(GetLastError());
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
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.
#define RBIMPL_ATTR_NONNULL(list)
Wraps (or simulates) __attribute__((nonnull))
VALUE rb_str_conv_enc(VALUE str, rb_encoding *from, rb_encoding *to)
Encoding conversion main routine.
VALUE rb_str_conv_enc_opts(VALUE str, rb_encoding *from, rb_encoding *to, int ecflags, VALUE ecopts)
Identical to rb_str_conv_enc(), except it additionally takes IO encoder options.
int rb_econv_has_convpath_p(const char *from_encoding, const char *to_encoding)
Queries if there is more than one way to convert between the passed two encodings.
void rb_write_error2(const char *str, long len)
Identical to rb_write_error(), except it additionally takes the message's length.
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.
#define rb_utf8_str_new(str, len)
Identical to rb_str_new, except it generates a string of "UTF-8" encoding.
VALUE rb_f_notimplement(int argc, const VALUE *argv, VALUE obj, VALUE marker)
Raises rb_eNotImpError.
int rb_io_descriptor(VALUE io)
Returns an integer representing the numeric file descriptor for io.
int len
Length of the buffer.
char * ruby_strdup(const char *str)
This is our own version of strdup(3) that uses ruby_xmalloc() instead of system malloc (benefits our ...
#define strdup(s)
Just another name of ruby_strdup.
void ruby_vm_at_exit(void(*func)(ruby_vm_t *))
ruby_vm_at_exit registers a function func to be invoked when a VM passed away.
void rb_w32_fd_dup(rb_fdset_t *dst, const rb_fdset_t *src)
Identical to rb_w32_fd_copy(), except it copies unlimited number of file descriptors.
void rb_w32_fd_copy(rb_fdset_t *dst, const fd_set *src, int max)
Destructively overwrites an fdset with another.
void rb_fd_term(rb_fdset_t *f)
Destroys the rb_fdset_t, releasing any memory and resources it used.
#define rb_long2int
Just another name of rb_long2int_inline.
#define MEMCPY(p1, p2, type, n)
Handy macro to call memcpy.
#define ALLOCA_N(type, n)
#define MEMZERO(p, type, n)
Handy macro to erase a region of memory.
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
VALUE type(ANYARGS)
ANYARGS-ed function type.
VALUE rb_ensure(type *q, VALUE w, type *e, VALUE r)
An equivalent of ensure clause.
#define PRI_PIDT_PREFIX
A rb_sprintf() format prefix to be used for a pid_t parameter.
#define rb_fd_init
Initialises the :given :rb_fdset_t.
#define StringValueCStr(v)
Identical to StringValuePtr, except it additionally checks for the contents for viability as a C stri...
#define FilePathValue(v)
Ensures that the parameter object is a path.
#define errno
Ractor-aware version of errno.
The data structure which wraps the fd_set bitmap used by select(2).
fd_set * fdset
File descriptors buffer.
int capa
Maximum allowed number of FDs.
intptr_t SIGNED_VALUE
A signed integer type that has the same width with VALUE.
uintptr_t VALUE
Type that represents a Ruby object.