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);
322 return osver.dwPlatformId;
330 return osver.dwMajorVersion;
341 DWORD err = GetLastError(); \
342 if (err == ERROR_LOCK_VIOLATION || err == ERROR_IO_PENDING) \
343 errno = EWOULDBLOCK; \
344 else if (err == ERROR_NOT_LOCKED) \
347 errno = map_errno(err); \
350#define LK_LEN ULONG_MAX
354flock_winnt(uintptr_t self,
int argc, uintptr_t* argv)
358 const HANDLE fh = (HANDLE)self;
359 const int oper = argc;
361 memset(&o, 0,
sizeof(o));
365 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, LK_LEN, &o), i);
368 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, LK_LEN, &o), i);
370 case LOCK_SH|LOCK_NB:
371 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, LK_LEN, &o), i);
373 case LOCK_EX|LOCK_NB:
374 LK_ERR(LockFileEx(fh,
375 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
376 0, LK_LEN, LK_LEN, &o), i);
379 case LOCK_UN|LOCK_NB:
380 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, LK_LEN, &o), i);
393flock(
int fd,
int oper)
395 const asynchronous_func_t locker = flock_winnt;
397 return rb_w32_asynchronize(locker,
398 (
VALUE)_get_osfhandle(fd), oper, NULL,
404translate_wchar(WCHAR *p,
int from,
int to)
415translate_char(
char *p,
int from,
int to, UINT cp)
418 if ((
unsigned char)*p == from)
420 p = CharNextExA(cp, p, 0);
425#ifndef CSIDL_LOCAL_APPDATA
426#define CSIDL_LOCAL_APPDATA 28
428#ifndef CSIDL_COMMON_APPDATA
429#define CSIDL_COMMON_APPDATA 35
432#define CSIDL_WINDOWS 36
435#define CSIDL_SYSTEM 37
438#define CSIDL_PROFILE 40
443get_special_folder(
int n, WCHAR *buf,
size_t len)
449 if (SHGetSpecialFolderLocation(NULL, n, &pidl) == 0) {
450 f = SHGetPathFromIDListEx(pidl, buf,
len, 0);
452 alloc->lpVtbl->Free(alloc, pidl);
453 alloc->lpVtbl->Release(alloc);
460regulate_path(WCHAR *path)
462 WCHAR *p = translate_wchar(path, L
'\\', L
'/');
463 if (p - path == 2 && path[1] == L
':') {
471get_proc_address(
const char *module,
const char *func, HANDLE *mh)
477 h = LoadLibrary(module);
479 h = GetModuleHandle(module);
483 ptr = GetProcAddress(h, func);
495rb_w32_special_folder(
int type)
497 WCHAR path[PATH_MAX];
499 if (!get_special_folder(
type, path, numberof(path)))
return Qnil;
501 return rb_w32_conv_from_wchar(path, rb_filesystem_encoding());
506rb_w32_system_tmpdir(WCHAR *path, UINT
len)
508 static const WCHAR temp[] = L
"temp";
511 if (!get_special_folder(CSIDL_LOCAL_APPDATA, path,
len)) {
512 if (GetSystemWindowsDirectoryW(path,
len))
return 0;
514 p = translate_wchar(path, L
'\\', L
'/');
515 if (*(p - 1) != L
'/') *p++ = L
'/';
516 if ((UINT)(p - path + numberof(temp)) >=
len)
return 0;
517 memcpy(p, temp,
sizeof(temp));
518 return (UINT)(p - path + numberof(temp) - 1);
533 WCHAR *buffer = NULL;
534 size_t buffer_len = MAX_PATH,
len = 0;
536 HOME_NONE, ENV_HOME, ENV_USERPROFILE, ENV_DRIVEPATH
537 } home_type = HOME_NONE;
539 if ((
len = GetEnvironmentVariableW(L
"HOME", NULL, 0)) != 0) {
541 home_type = ENV_HOME;
543 else if ((
len = GetEnvironmentVariableW(L
"USERPROFILE", NULL, 0)) != 0) {
545 home_type = ENV_USERPROFILE;
547 else if ((
len = GetEnvironmentVariableW(L
"HOMEDRIVE", NULL, 0)) != 0) {
549 if ((
len = GetEnvironmentVariableW(L
"HOMEPATH", NULL, 0)) != 0) {
551 home_type = ENV_DRIVEPATH;
556 buffer = malloc(
sizeof(WCHAR) * buffer_len);
557 if (buffer == NULL)
return NULL;
561 GetEnvironmentVariableW(L
"HOME", buffer, buffer_len);
563 case ENV_USERPROFILE:
564 GetEnvironmentVariableW(L
"USERPROFILE", buffer, buffer_len);
567 len = GetEnvironmentVariableW(L
"HOMEDRIVE", buffer, buffer_len);
568 GetEnvironmentVariableW(L
"HOMEPATH", buffer +
len, buffer_len -
len);
571 if (!get_special_folder(CSIDL_PROFILE, buffer, buffer_len) &&
572 !get_special_folder(CSIDL_PERSONAL, buffer, buffer_len)) {
576 buffer = realloc(buffer,
sizeof(WCHAR) * (lstrlenW(buffer) + 1));
581 regulate_path(buffer);
592 if (!GetEnvironmentVariableW(L
"HOME", env, numberof(env))) {
593 WCHAR *whome = rb_w32_home_dir();
595 _wputenv_s(L
"HOME", whome);
600 if (!GetEnvironmentVariableW(L
"USER", env, numberof(env))) {
602 if (!GetEnvironmentVariableW(L
"USERNAME", env, numberof(env)) &&
603 !GetUserNameW(env, (
len = numberof(env), &
len))) {
604 NTLoginName =
"<Unknown>";
607 _wputenv_s(L
"USER", env);
608 NTLoginName = rb_w32_wstr_to_mbstr(CP_UTF8, env, -1, NULL);
612 NTLoginName = rb_w32_wstr_to_mbstr(CP_UTF8, env, -1, NULL);
615 if (!GetEnvironmentVariableW(L
"TMPDIR", env, numberof(env)) &&
616 !GetEnvironmentVariableW(L
"TMP", env, numberof(env)) &&
617 !GetEnvironmentVariableW(L
"TEMP", env, numberof(env)) &&
618 rb_w32_system_tmpdir(env, numberof(env))) {
619 _wputenv_s(L
"TMPDIR", env);
623static void init_stdhandle(
void);
627invalid_parameter(
const wchar_t *expr,
const wchar_t *func,
const wchar_t *file,
unsigned int line, uintptr_t dummy)
632int ruby_w32_rtc_error;
639rtc_error_handler(
int e, const
char *src,
int line, const
char *exe, const
char *fmt, ...)
644 if (!ruby_w32_rtc_error)
return 0;
645 str = rb_sprintf(
"%s:%d: ", src, line);
647 rb_str_vcatf(str, fmt, ap);
655static CRITICAL_SECTION select_mutex;
657static CRITICAL_SECTION socklist_mutex;
660static CRITICAL_SECTION conlist_mutex;
662#define conlist_disabled ((st_table *)-1)
664#define thread_exclusive(obj) \
665 for (bool exclusive_for_##obj = (EnterCriticalSection(&obj##_mutex), true); \
666 exclusive_for_##obj; \
667 exclusive_for_##obj = (LeaveCriticalSection(&obj##_mutex), false))
669static CRITICAL_SECTION uenvarea_mutex;
670static char *uenvarea;
675 int state, seq[16], reverse;
680enum {constat_init = -2, constat_esc = -1, constat_seq = 0};
684free_conlist(st_data_t key, st_data_t val, st_data_t arg)
692constat_delete(HANDLE h)
694 thread_exclusive(conlist) {
695 if (conlist && conlist != conlist_disabled) {
696 st_data_t key = (st_data_t)h, val;
697 st_delete(conlist, &key, &val);
708 DeleteCriticalSection(&select_mutex);
709 DeleteCriticalSection(&socklist_mutex);
710 DeleteCriticalSection(&conlist_mutex);
711 thread_exclusive(uenvarea) {
717 DeleteCriticalSection(&uenvarea_mutex);
724 EnterCriticalSection(&socklist_mutex);
726 st_free_table(socklist);
729 LeaveCriticalSection(&socklist_mutex);
731 EnterCriticalSection(&conlist_mutex);
732 if (conlist && conlist != conlist_disabled) {
733 st_foreach(conlist, free_conlist, 0);
734 st_free_table(conlist);
737 LeaveCriticalSection(&conlist_mutex);
740#define ATOMIC_LONG_CAS(var, oldval, newval) InterlockedCompareExchange(&(var), (newval), (oldval))
744install_vm_exit_handler(
void)
746 static LONG installed = 0;
749 while ((i = ATOMIC_LONG_CAS(installed, 0, -1)) != 1) {
755 ATOMIC_LONG_CAS(installed, -1, 1);
771 version = MAKEWORD(2, 0);
772 if (WSAStartup(version, &retdata))
773 rb_fatal(
"Unable to locate winsock library!");
774 if (LOBYTE(retdata.wVersion) != 2)
775 rb_fatal(
"could not find version 2 of winsock dll");
777 InitializeCriticalSection(&select_mutex);
778 InitializeCriticalSection(&socklist_mutex);
779 InitializeCriticalSection(&conlist_mutex);
781 atexit(exit_handler);
784#define MAKE_SOCKDATA(af, fl) ((int)((((int)af)<<4)|((fl)&0xFFFF)))
785#define GET_FAMILY(v) ((int)(((v)>>4)&0xFFFF))
786#define GET_FLAGS(v) ((int)((v)&0xFFFF))
790socklist_insert(SOCKET sock,
int flag)
794 thread_exclusive(socklist) {
796 socklist = st_init_numtable();
797 install_vm_exit_handler();
799 ret = st_insert(socklist, (st_data_t)sock, (st_data_t)flag);
807socklist_lookup(SOCKET sock,
int *flagp)
812 thread_exclusive(socklist) {
813 if (!socklist)
continue;
814 ret = st_lookup(socklist, (st_data_t)sock, &data);
824socklist_delete(SOCKET *sockp,
int *flagp)
830 thread_exclusive(socklist) {
831 if (!socklist)
continue;
832 key = (st_data_t)*sockp;
834 data = (st_data_t)*flagp;
835 ret = st_delete(socklist, &key, &data);
837 *sockp = (SOCKET)key;
847# define _CrtSetReportMode(type,mode) ((void)0)
848# define _RTC_SetErrorFunc(func) ((void)0)
850static void set_pioinfo_extra(
void);
851static int w32_cmdvector(
const WCHAR *,
char ***, UINT,
rb_encoding *);
857rb_w32_sysinit(
int *argc,
char ***argv)
859 _CrtSetReportMode(_CRT_ASSERT, 0);
860 _set_invalid_parameter_handler(invalid_parameter);
861 _RTC_SetErrorFunc(rtc_error_handler);
863 SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOGPFAULTERRORBOX);
870 *argc = w32_cmdvector(GetCommandLineW(), argv, CP_UTF8, &OnigEncodingUTF_8);
878 InitializeCriticalSection(&uenvarea_mutex);
890 return (
char *)NTLoginName;
893#define MAXCHILDNUM 256
902#define FOREACH_CHILD(v) do { \
903 struct ChildRecord* v; \
904 for (v = ChildRecord; v < ChildRecord + sizeof(ChildRecord) / sizeof(ChildRecord[0]); ++v)
905#define END_FOREACH_CHILD } while (0)
909FindChildSlot(rb_pid_t pid)
912 FOREACH_CHILD(child) {
913 if (child->pid == pid) {
922FindChildSlotByHandle(HANDLE h)
925 FOREACH_CHILD(child) {
926 if (child->hProcess == h) {
937 HANDLE h = child->hProcess;
938 child->hProcess = NULL;
945FindFreeChildSlot(
void)
947 FOREACH_CHILD(child) {
950 child->hProcess = NULL;
964#define InternalCmdsMax 8
965static const char szInternalCmds[][InternalCmdsMax+2] = {
1019internal_match(
const void *key,
const void *elem)
1021 return strncmp(key, ((
const char *)elem) + 1, InternalCmdsMax);
1026is_command_com(
const char *interp)
1028 int i = strlen(interp) - 11;
1030 if ((i == 0 || (i > 0 && isdirsep(interp[i-1]))) &&
1031 strcasecmp(interp+i,
"command.com") == 0) {
1037static int internal_cmd_match(
const char *cmdname,
int nt);
1041is_internal_cmd(
const char *cmd,
int nt)
1043 char cmdname[9], *b = cmdname, c;
1046 if (!(c = *cmd++))
return 0;
1047 }
while (isspace(c));
1050 while (isalpha(c)) {
1052 if (b == cmdname +
sizeof(cmdname))
return 0;
1055 if (c ==
'.') c = *cmd;
1057 case '<':
case '>':
case '|':
1059 case '\0':
case ' ':
case '\t':
case '\n':
1065 return internal_cmd_match(cmdname, nt);
1070internal_cmd_match(
const char *cmdname,
int nt)
1074 nm = bsearch(cmdname, szInternalCmds,
1075 sizeof(szInternalCmds) /
sizeof(*szInternalCmds),
1076 sizeof(*szInternalCmds),
1078 if (!nm || !(nm[0] & (nt ? 2 : 1)))
1085rb_w32_get_osfhandle(
int fh)
1087 return _get_osfhandle(fh);
1092join_argv(
char *cmd,
char *
const *argv, BOOL escape, UINT cp,
int backslash)
1096 int len, n, bs, quote;
1098 for (t = argv, q = cmd,
len = 0; (p = *t) != 0; t++) {
1101 if (!*p || strpbrk(p,
" \t\"'")) {
1106 for (bs = 0; *p; ++p) {
1120 memset(q,
'\\', bs);
1125 case '<':
case '>':
case '|':
case '^':
1126 if (escape && !quote) {
1127 len += (n = p - s) + 1;
1138 p = CharNextExA(cp, p, 0) - 1;
1142 len += (n = p - s) + 1;
1146 if (backslash > 0) {
1149 translate_char(q,
'/',
'\\', cp);
1152 if (quote) *q++ =
'"';
1165#define STRNDUPV(ptr, v, src, len) \
1166 (((char *)memcpy(((ptr) = ALLOCV((v), (len) + 1)), (src), (len)))[len] = 0)
1170check_spawn_mode(
int mode)
1192 if (mode == P_OVERLAY) {
1193 WaitForSingleObject(child->hProcess, INFINITE);
1194 GetExitCodeProcess(child->hProcess, &exitcode);
1195 CloseChildHandle(child);
1203CreateChild(
struct ChildRecord *child,
const WCHAR *cmd,
const WCHAR *prog, HANDLE hInput, HANDLE hOutput, HANDLE hError, DWORD dwCreationFlags)
1206 STARTUPINFOW aStartupInfo;
1207 PROCESS_INFORMATION aProcessInformation;
1208 SECURITY_ATTRIBUTES sa;
1210 if (!cmd && !prog) {
1220 sa.nLength =
sizeof(SECURITY_ATTRIBUTES);
1221 sa.lpSecurityDescriptor = NULL;
1222 sa.bInheritHandle = TRUE;
1224 memset(&aStartupInfo, 0,
sizeof(aStartupInfo));
1225 memset(&aProcessInformation, 0,
sizeof(aProcessInformation));
1226 aStartupInfo.cb =
sizeof(aStartupInfo);
1227 aStartupInfo.dwFlags = STARTF_USESTDHANDLES;
1229 aStartupInfo.hStdInput = hInput;
1232 aStartupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
1235 aStartupInfo.hStdOutput = hOutput;
1238 aStartupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
1241 aStartupInfo.hStdError = hError;
1244 aStartupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
1247 dwCreationFlags |= NORMAL_PRIORITY_CLASS;
1249 if (lstrlenW(cmd) > 32767) {
1256 fRet = CreateProcessW(prog, (WCHAR *)cmd, &sa, &sa,
1257 sa.bInheritHandle, dwCreationFlags, NULL, NULL,
1258 &aStartupInfo, &aProcessInformation);
1259 errno = map_errno(GetLastError());
1267 CloseHandle(aProcessInformation.hThread);
1269 child->hProcess = aProcessInformation.hProcess;
1270 child->pid = (rb_pid_t)aProcessInformation.dwProcessId;
1277is_batch(
const char *cmd)
1279 int len = strlen(cmd);
1280 if (
len <= 4)
return 0;
1282 if (*cmd++ !=
'.')
return 0;
1283 if (strcasecmp(cmd,
"bat") == 0)
return 1;
1284 if (strcasecmp(cmd,
"cmd") == 0)
return 1;
1288#define filecp rb_w32_filecp
1289#define mbstr_to_wstr rb_w32_mbstr_to_wstr
1290#define wstr_to_mbstr rb_w32_wstr_to_mbstr
1291#define acp_to_wstr(str, plen) mbstr_to_wstr(CP_ACP, str, -1, plen)
1292#define wstr_to_acp(str, plen) wstr_to_mbstr(CP_ACP, str, -1, plen)
1293#define filecp_to_wstr(str, plen) mbstr_to_wstr(filecp(), str, -1, plen)
1294#define wstr_to_filecp(str, plen) wstr_to_mbstr(filecp(), str, -1, plen)
1295#define utf8_to_wstr(str, plen) mbstr_to_wstr(CP_UTF8, str, -1, plen)
1296#define wstr_to_utf8(str, plen) wstr_to_mbstr(CP_UTF8, str, -1, plen)
1300w32_spawn(
int mode,
const char *cmd,
const char *prog, UINT cp)
1302 char fbuf[PATH_MAX];
1304 const char *shell = NULL;
1305 WCHAR *wcmd = NULL, *wshell = NULL;
1311 char *cmd_sep = NULL;
1313 if (check_spawn_mode(mode))
return -1;
1316 if (!(p = dln_find_exe_r(prog, NULL, fbuf,
sizeof(fbuf)))) {
1321 translate_char(p,
'/',
'\\', cp);
1328 if ((shell = w32_getenv(
"RUBYSHELL", cp)) && (redir = has_redirection(cmd, cp))) {
1329 size_t shell_len = strlen(shell);
1330 size_t cmd_len = strlen(cmd) +
sizeof(
" -c ") + 2;
1331 char *tmp =
ALLOCV(v, shell_len + cmd_len);
1332 memcpy(tmp, shell, shell_len + 1);
1333 translate_char(tmp,
'/',
'\\', cp);
1334 snprintf(tmp + shell_len, cmd_len,
" -c \"%s\"", cmd);
1337 else if ((shell = w32_getenv(
"COMSPEC", cp)) &&
1338 (nt = !is_command_com(shell),
1339 (redir < 0 ? has_redirection(cmd, cp) : redir) ||
1340 is_internal_cmd(cmd, nt))) {
1341 size_t cmd_len = strlen(shell) + strlen(cmd) +
sizeof(
" /c ") + (nt ? 2 : 0);
1342 char *tmp =
ALLOCV(v, cmd_len);
1343 snprintf(tmp, cmd_len, nt ?
"%s /c \"%s\"" :
"%s /c %s", shell, cmd);
1347 int len = 0, quote = (*cmd ==
'"') ?
'"' : (*cmd ==
'\'') ?
'\'' : 0;
1349 for (prog = cmd + !!quote;; prog = CharNextExA(cp, prog, 0)) {
1350 if (*prog ==
'/') slash = 1;
1354 STRNDUPV(p, v2, cmd,
len);
1360 if ((
unsigned char)*prog == quote) {
1361 len = prog++ - cmd - 1;
1362 STRNDUPV(p, v2, cmd + 1,
len);
1366 if (quote)
continue;
1367 if (
ISSPACE(*prog) || strchr(
"<>|*?\"", *prog)) {
1369 STRNDUPV(p, v2, cmd,
len + (slash ? strlen(prog) : 0));
1372 sep = *(cmd_sep = &p[
len]);
1379 shell = dln_find_exe_r(shell, NULL, fbuf,
sizeof(fbuf));
1380 if (p && slash) translate_char(p,
'/',
'\\', cp);
1382 shell = p ? p : cmd;
1385 len = strlen(shell);
1386 if (strchr(shell,
' ')) quote = -1;
1387 if (shell == fbuf) {
1390 else if (shell != p && strchr(shell,
'/')) {
1391 STRNDUPV(p, v2, shell,
len);
1394 if (p) translate_char(p,
'/',
'\\', cp);
1395 if (is_batch(shell)) {
1396 int alen = strlen(prog);
1397 cmd = p =
ALLOCV(v,
len + alen + (quote ? 2 : 0) + 1);
1398 if (quote) *p++ =
'"';
1399 memcpy(p, shell,
len);
1401 if (quote) *p++ =
'"';
1402 memcpy(p, prog, alen + 1);
1409 if (!e && shell && !(wshell = mbstr_to_wstr(cp, shell, -1, NULL))) e = E2BIG;
1410 if (cmd_sep) *cmd_sep = sep;
1411 if (!e && cmd && !(wcmd = mbstr_to_wstr(cp, cmd, -1, NULL))) e = E2BIG;
1417 if (CreateChild(child, wcmd, wshell, NULL, NULL, NULL, 0)) {
1418 ret = child_result(child, mode);
1429rb_w32_spawn(
int mode,
const char *cmd,
const char *prog)
1432 return w32_spawn(mode, cmd, prog, filecp());
1437rb_w32_uspawn(
int mode,
const char *cmd,
const char *prog)
1439 return w32_spawn(mode, cmd, prog, CP_UTF8);
1444w32_spawn_process(
int mode,
const char *prog,
char *
const *argv,
1445 int in_fd,
int out_fd,
int err_fd, DWORD flags, UINT cp)
1449 BOOL ntcmd = FALSE, tmpnt;
1451 char *cmd, fbuf[PATH_MAX];
1452 WCHAR *wcmd = NULL, *wprog = NULL;
1456 HANDLE in_handle = NULL, out_handle = NULL, err_handle = NULL;
1458 if (check_spawn_mode(mode))
return -1;
1461 in_handle = (HANDLE)rb_w32_get_osfhandle(in_fd);
1464 out_handle = (HANDLE)rb_w32_get_osfhandle(out_fd);
1467 err_handle = (HANDLE)rb_w32_get_osfhandle(err_fd);
1470 if (!prog) prog = argv[0];
1471 if ((shell = w32_getenv(
"COMSPEC", cp)) &&
1472 internal_cmd_match(prog, tmpnt = !is_command_com(shell))) {
1477 else if ((cmd = dln_find_exe_r(prog, NULL, fbuf,
sizeof(fbuf)))) {
1478 if (cmd == prog) strlcpy(cmd = fbuf, prog,
sizeof(fbuf));
1479 translate_char(cmd,
'/',
'\\', cp);
1482 else if (strchr(prog,
'/')) {
1484 if (
len <
sizeof(fbuf))
1485 strlcpy(cmd = fbuf, prog,
sizeof(fbuf));
1487 STRNDUPV(cmd, v, prog,
len);
1488 translate_char(cmd,
'/',
'\\', cp);
1491 if (c_switch || is_batch(prog)) {
1493 progs[0] = (
char *)prog;
1495 len = join_argv(NULL, progs, ntcmd, cp, 1);
1496 if (c_switch)
len += 3;
1498 if (argv[0])
len += join_argv(NULL, argv, ntcmd, cp, 0);
1500 join_argv(cmd, progs, ntcmd, cp, 1);
1501 if (c_switch) strlcat(cmd,
" /c",
len);
1502 if (argv[0]) join_argv(cmd + strlcat(cmd,
" ",
len), argv, ntcmd, cp, 0);
1503 prog = c_switch ? shell : 0;
1506 len = join_argv(NULL, argv, FALSE, cp, 1);
1508 join_argv(cmd, argv, FALSE, cp, 1);
1511 if (!e && cmd && !(wcmd = mbstr_to_wstr(cp, cmd, -1, NULL))) e = E2BIG;
1513 if (!e && prog && !(wprog = mbstr_to_wstr(cp, prog, -1, NULL))) e = E2BIG;
1517 if (CreateChild(child, wcmd, wprog, in_handle, out_handle, err_handle, flags)) {
1518 ret = child_result(child, mode);
1529rb_w32_aspawn_flags(
int mode,
const char *prog,
char *
const *argv, DWORD flags)
1532 return w32_spawn_process(mode, prog, argv, -1, -1, -1, flags, filecp());
1537rb_w32_uaspawn_flags(
int mode,
const char *prog,
char *
const *argv, DWORD flags)
1539 return w32_spawn_process(mode, prog, argv, -1, -1, -1, flags, CP_UTF8);
1544rb_w32_aspawn(
int mode,
const char *prog,
char *
const *argv)
1546 return w32_spawn_process(mode, prog, argv, -1, -1, -1, 0, filecp());
1551rb_w32_uaspawn(
int mode,
const char *prog,
char *
const *argv)
1553 return rb_w32_uaspawn_flags(mode, prog, argv, 0);
1558rb_w32_uspawn_process(
int mode,
const char *prog,
char *
const *argv,
1559 int in_fd,
int out_fd,
int err_fd, DWORD flags)
1561 return w32_spawn_process(mode, prog, argv, in_fd, out_fd, err_fd,
1583insert(
const char *path,
VALUE vinfo,
void *enc)
1589 if (!tmpcurr)
return -1;
1591 tmpcurr->len = strlen(path);
1592 tmpcurr->str =
strdup(path);
1593 if (!tmpcurr->str)
return -1;
1594 tmpcurr->flags |= NTMALLOC;
1596 *tail = &tmpcurr->next;
1605 char buffer[PATH_MAX], *buf = buffer;
1609 if (patt->len >= PATH_MAX)
1610 if (!(buf = malloc(patt->len + 1)))
return 0;
1612 memcpy(buf, patt->str, patt->len);
1613 buf[patt->len] =
'\0';
1614 translate_char(buf,
'\\',
'/', cp);
1615 status = ruby_brace_glob_with_enc(buf, 0, insert, (
VALUE)&tail, enc);
1619 if (status || last == tail)
return 0;
1620 if (patt->flags & NTMALLOC)
1633has_redirection(
const char *cmd, UINT cp)
1643 for (ptr = cmd; *ptr;) {
1649 else if (quote == *ptr)
1665 if (*++ptr !=
'_' && !
ISALPHA(*ptr))
break;
1666 while (*++ptr ==
'_' ||
ISALNUM(*ptr));
1667 if (*ptr++ ==
'%')
return TRUE;
1673 ptr = CharNextExA(cp, ptr, 0);
1681static inline WCHAR *
1682skipspace(WCHAR *ptr)
1691w32_cmdvector(
const WCHAR *cmd,
char ***vec, UINT cp,
rb_encoding *enc)
1694 int elements, strsz, done;
1695 int slashes, escape;
1696 WCHAR *ptr, *base, *cmdline;
1697 char *cptr, *buffer;
1713 ptr = cmdline = wcsdup(cmd);
1724 while (*(ptr = skipspace(ptr))) {
1726 quote = slashes = globbing = escape = 0;
1727 for (done = 0; !done && *ptr; ) {
1736 if (quote != L
'\'') slashes++;
1776 if (!(slashes & 1)) {
1779 else if (quote == *ptr) {
1780 if (quote == L
'"' && quote == ptr[1])
1790 ptr = CharNextW(ptr);
1813 slashes = quote = 0;
1814 while (p < base +
len) {
1818 if (quote != L
'\'') slashes++;
1823 if (!(slashes & 1) && quote && quote != c) {
1828 memcpy(p - ((slashes + 1) >> 1), p + (~slashes & 1),
1829 sizeof(WCHAR) * (base +
len - p));
1830 len -= ((slashes + 1) >> 1) + (~slashes & 1);
1831 p -= (slashes + 1) >> 1;
1832 if (!(slashes & 1)) {
1834 if (quote == L
'"' && quote == *p)
1855 if (!curr)
goto do_nothing;
1856 curr->str = rb_w32_wstr_to_mbstr(cp, base,
len, &curr->len);
1857 curr->flags |= NTMALLOC;
1859 if (globbing && (tail = cmdglob(curr, cmdtail, cp, enc))) {
1864 cmdtail = &curr->next;
1874 for (elements = 0, strsz = 0, curr = cmdhead; curr; curr = curr->next) {
1876 strsz += (curr->len + 1);
1879 len = (elements+1)*
sizeof(
char *) + strsz;
1880 buffer = (
char *)malloc(
len);
1883 while ((curr = cmdhead) != 0) {
1884 cmdhead = curr->next;
1885 if (curr->flags & NTMALLOC) free(curr->str);
1889 for (vptr = *vec; *vptr; ++vptr);
1905 vptr = (
char **) buffer;
1907 cptr = buffer + (elements+1) *
sizeof(
char *);
1909 while ((curr = cmdhead) != 0) {
1910 memcpy(cptr, curr->str, curr->len);
1911 cptr[curr->len] =
'\0';
1913 cptr += curr->len + 1;
1914 cmdhead = curr->next;
1915 if (curr->flags & NTMALLOC) free(curr->str);
1920 *vec = (
char **) buffer;
1932open_special(
const WCHAR *path, DWORD access, DWORD flags)
1934 const DWORD share_mode =
1935 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
1936 return CreateFileW(path, access, share_mode, NULL, OPEN_EXISTING,
1937 FILE_FLAG_BACKUP_SEMANTICS|flags, NULL);
1947#define GetBit(bits, i) ((bits)[(i) / CHAR_BIT] & (1 << (i) % CHAR_BIT))
1948#define SetBit(bits, i) ((bits)[(i) / CHAR_BIT] |= (1 << (i) % CHAR_BIT))
1950#define BitOfIsDir(n) ((n) * 2)
1951#define BitOfIsRep(n) ((n) * 2 + 1)
1952#define DIRENT_PER_CHAR (CHAR_BIT / 2)
1954static const WCHAR namespace_prefix[] = {L
'\\', L
'\\', L
'?', L
'\\'};
1960get_handle_pathname(HANDLE fh, WCHAR **pathptr, DWORD add)
1962 DWORD
len = GetFinalPathNameByHandleW(fh, NULL, 0, 0);
1964 WCHAR *path = malloc((
len + add + 1) *
sizeof(WCHAR));
1965 if (!(*pathptr = path))
return 0;
1966 len = GetFinalPathNameByHandleW(fh, path,
len + 1, 0);
1967 if (!
len) free(path);
1973open_dir_handle(
const WCHAR *filename, WIN32_FIND_DATAW *fd)
1977 WCHAR *fullname = 0;
1985 fh = open_special(filename, 0, 0);
1986 if (fh != INVALID_HANDLE_VALUE) {
1987 len = get_handle_pathname(fh, &fullname, wildcard_len);
1991 len = lstrlenW(filename);
1992 fullname = malloc((
len + wildcard_len + 1) *
sizeof(WCHAR));
1993 if (!fullname)
return INVALID_HANDLE_VALUE;
1999 p = &fullname[
len-1];
2000 if (!(isdirsep(*p) || *p == L
':')) *++p = L
'\\';
2007 fh = FindFirstFileW(fullname, fd);
2008 if (fh == INVALID_HANDLE_VALUE) {
2009 errno = map_errno(GetLastError());
2017w32_wopendir(
const WCHAR *wpath)
2020 WIN32_FIND_DATAW fd;
2033 if (wstati128(wpath, &sbuf, FALSE) < 0) {
2036 if (!(sbuf.st_mode & S_IFDIR) &&
2037 (!
ISALPHA(wpath[0]) || wpath[1] != L
':' || wpath[2] != L
'\0' ||
2038 ((1 << ((wpath[0] & 0x5f) -
'A')) & GetLogicalDrives()) == 0)) {
2042 fh = open_dir_handle(wpath, &fd);
2043 if (fh == INVALID_HANDLE_VALUE) {
2050 p = calloc(1,
sizeof(
DIR));
2054 pathlen = lstrlenW(wpath);
2064 len = lstrlenW(fd.cFileName) + 1;
2065 altlen = lstrlenW(fd.cAlternateFileName) + 1;
2071 tmpW = realloc(p->start, (idx +
len + altlen) *
sizeof(WCHAR));
2081 memcpy(&p->start[idx], fd.cFileName,
len *
sizeof(WCHAR));
2082 memcpy(&p->start[idx +
len], fd.cAlternateFileName, altlen *
sizeof(WCHAR));
2084 if (p->nfiles % DIRENT_PER_CHAR == 0) {
2085 tmp = realloc(p->bits, p->nfiles / DIRENT_PER_CHAR + 1);
2089 p->bits[p->nfiles / DIRENT_PER_CHAR] = 0;
2091 if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
2092 SetBit(p->bits, BitOfIsDir(p->nfiles));
2093 if (fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
2094 WCHAR *tmppath = malloc((pathlen +
len + 1) *
sizeof(WCHAR));
2095 memcpy(tmppath, wpath, pathlen *
sizeof(WCHAR));
2096 tmppath[pathlen] = L
'\\';
2097 memcpy(tmppath + pathlen + 1, fd.cFileName,
len *
sizeof(WCHAR));
2098 if (rb_w32_reparse_symlink_p(tmppath))
2099 SetBit(p->bits, BitOfIsRep(p->nfiles));
2104 idx +=
len + altlen;
2105 }
while (FindNextFileW(fh, &fd));
2116 UINT cp = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
2122rb_w32_wstr_to_mbstr(UINT cp,
const WCHAR *wstr,
int clen,
long *plen)
2125 int len = WideCharToMultiByte(cp, 0, wstr, clen, NULL, 0, NULL, NULL);
2126 if (!(ptr = malloc(
len)))
return 0;
2127 WideCharToMultiByte(cp, 0, wstr, clen, ptr,
len, NULL, NULL);
2130 if (clen == -1) --
len;
2138rb_w32_mbstr_to_wstr(UINT cp,
const char *str,
int clen,
long *plen)
2141 int len = MultiByteToWideChar(cp, 0, str, clen, NULL, 0);
2142 if (!(ptr = malloc(
sizeof(WCHAR) *
len)))
return 0;
2143 MultiByteToWideChar(cp, 0, str, clen, ptr,
len);
2146 if (clen == -1) --
len;
2154rb_w32_opendir(
const char *filename)
2157 WCHAR *wpath = filecp_to_wstr(filename, NULL);
2160 ret = w32_wopendir(wpath);
2167rb_w32_uopendir(
const char *filename)
2170 WCHAR *wpath = utf8_to_wstr(filename, NULL);
2173 ret = w32_wopendir(wpath);
2184move_to_next_entry(
DIR *dirp)
2188 dirp->curr += lstrlenW(dirp->curr) + 1;
2189 dirp->curr += lstrlenW(dirp->curr) + 1;
2190 if (dirp->curr >= (dirp->start + dirp->size)) {
2202win32_direct_conv(
const WCHAR *file,
const WCHAR *alt,
struct direct *entry,
const void *enc)
2204 UINT cp = *((UINT *)enc);
2205 if (!(entry->d_name = wstr_to_mbstr(cp, file, -1, &entry->d_namlen)))
2209 entry->d_altname = wstr_to_mbstr(cp, alt, -1, &altlen);
2210 entry->d_altlen = altlen;
2217rb_w32_conv_from_wchar(
const WCHAR *wstr,
rb_encoding *enc)
2220 long len = lstrlenW(wstr);
2221 int encindex = rb_enc_to_index(enc);
2223 if (encindex == ENCINDEX_UTF_16LE) {
2224 return rb_enc_str_new((
char *)wstr,
len *
sizeof(WCHAR), enc);
2227#if SIZEOF_INT < SIZEOF_LONG
2228# error long should equal to int on Windows
2231 len = WideCharToMultiByte(CP_UTF8, 0, wstr, clen, NULL, 0, NULL, NULL);
2232 src = rb_enc_str_new(0,
len, rb_enc_from_index(ENCINDEX_UTF_8));
2233 WideCharToMultiByte(CP_UTF8, 0, wstr, clen, RSTRING_PTR(src),
len, NULL, NULL);
2236 case ENCINDEX_ASCII_8BIT:
2237 case ENCINDEX_US_ASCII:
2239 case ENCINDEX_UTF_8:
2248rb_w32_conv_from_wstr(
const WCHAR *wstr,
long *lenp,
rb_encoding *enc)
2250 VALUE str = rb_w32_conv_from_wchar(wstr, enc);
2254 if (
NIL_P(str))
return wstr_to_utf8(wstr, lenp);
2255 *lenp =
len = RSTRING_LEN(str);
2256 memcpy(ptr = malloc(
len + 1), RSTRING_PTR(str),
len);
2263ruby_direct_conv(
const WCHAR *file,
const WCHAR *alt,
struct direct *entry,
const void *enc)
2265 if (!(entry->d_name = rb_w32_conv_from_wstr(file, &entry->d_namlen, enc)))
2269 entry->d_altname = rb_w32_conv_from_wstr(alt, &altlen, enc);
2270 entry->d_altlen = altlen;
2277readdir_internal(
DIR *dirp, BOOL (*conv)(
const WCHAR *,
const WCHAR *,
struct direct *,
const void *),
const void *enc)
2279 static long dummy_ino = 0;
2286 free(dirp->dirstr.d_name);
2287 free(dirp->dirstr.d_altname);
2288 dirp->dirstr.d_altname = 0;
2289 dirp->dirstr.d_altlen = 0;
2290 conv(dirp->curr, dirp->curr + lstrlenW(dirp->curr) + 1, &dirp->dirstr, enc);
2295 dirp->dirstr.d_ino = (ino_t)(InterlockedIncrement(&dummy_ino) - 1);
2301 if (GetBit(dirp->bits, BitOfIsRep(dirp->loc)))
2302 dirp->dirstr.d_type = DT_LNK;
2303 else if (GetBit(dirp->bits, BitOfIsDir(dirp->loc)))
2304 dirp->dirstr.d_type = DT_DIR;
2306 dirp->dirstr.d_type = DT_REG;
2312 move_to_next_entry(dirp);
2314 return &(dirp->dirstr);
2325 int idx = rb_enc_to_index(enc);
2326 if (idx == ENCINDEX_ASCII_8BIT) {
2327 const UINT cp = filecp();
2328 return readdir_internal(dirp, win32_direct_conv, &cp);
2330 else if (idx == ENCINDEX_UTF_8) {
2331 const UINT cp = CP_UTF8;
2332 return readdir_internal(dirp, win32_direct_conv, &cp);
2335 return readdir_internal(dirp, ruby_direct_conv, enc);
2340rb_w32_ureaddir(
DIR *dirp)
2342 const UINT cp = CP_UTF8;
2343 return readdir_internal(dirp, win32_direct_conv, &cp);
2352rb_w32_telldir(
DIR *dirp)
2363rb_w32_seekdir(
DIR *dirp,
long loc)
2365 if (dirp->loc > loc) rb_w32_rewinddir(dirp);
2367 while (dirp->curr && dirp->loc < loc) {
2368 move_to_next_entry(dirp);
2378rb_w32_rewinddir(
DIR *dirp)
2380 dirp->curr = dirp->start;
2390rb_w32_closedir(
DIR *dirp)
2393 free(dirp->dirstr.d_name);
2394 free(dirp->dirstr.d_altname);
2416 CRITICAL_SECTION _lock;
2418#define FILE_COUNT(stream) ((vcruntime_file*)stream)->_cnt
2419#define FILE_READPTR(stream) ((vcruntime_file*)stream)->_ptr
2420#define FILE_FILENO(stream) ((vcruntime_file*)stream)->_file
2423typedef char lowio_text_mode;
2424typedef char lowio_pipe_lookahead[3];
2427 CRITICAL_SECTION lock;
2430 unsigned char osfile;
2431 lowio_text_mode textmode;
2432 lowio_pipe_lookahead _pipe_lookahead;
2434 uint8_t unicode : 1;
2435 uint8_t utf8translations : 1;
2436 uint8_t dbcsBufferUsed : 1;
2440#if !defined _CRTIMP || defined __MINGW32__
2442#define _CRTIMP __declspec(dllimport)
2445static ioinfo ** __pioinfo = NULL;
2447static inline ioinfo* _pioinfo(
int);
2450#define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
2451#define _osfhnd(i) (_pioinfo(i)->osfhnd)
2452#define _osfile(i) (_pioinfo(i)->osfile)
2453#define rb_acrt_lowio_lock_fh(i) EnterCriticalSection(&_pioinfo(i)->lock)
2454#define rb_acrt_lowio_unlock_fh(i) LeaveCriticalSection(&_pioinfo(i)->lock)
2456static size_t pioinfo_extra = 0;
2460set_pioinfo_extra(
void)
2462#define FUNCTION_RET 0xc3
2464# define UCRTBASE "ucrtbased.dll"
2466# define UCRTBASE "ucrtbase.dll"
2481 char *p = (
char*)get_proc_address(UCRTBASE,
"_isatty", NULL);
2484#if defined(_M_ARM64) || defined(__aarch64__)
2485#define IS_INSN(pc, name) ((*(pc) & name##_mask) == name##_id)
2486 const int max_num_inst = 500;
2487 uint32_t *start = (uint32_t*)p;
2488 uint32_t *end_limit = (start + max_num_inst);
2489 uint32_t *pc = start;
2492 fprintf(stderr,
"_isatty proc not found in " UCRTBASE
"\n");
2497 const uint32_t ret_id = 0xd65f0000;
2498 const uint32_t ret_mask = 0xfffffc1f;
2499 for(; pc < end_limit; pc++) {
2500 if (IS_INSN(pc, ret)) {
2504 if (pc == end_limit) {
2505 fprintf(stderr,
"end of _isatty not found in " UCRTBASE
"\n");
2510 const uint32_t adrp_id = 0x90000000;
2511 const uint32_t adrp_mask = 0x9f000000;
2512 const uint32_t add_id = 0x11000000;
2513 const uint32_t add_mask = 0x7fc00000;
2514 for(; pc > start; pc--) {
2515 if (IS_INSN(pc, adrp) && IS_INSN(pc + 1, add)) {
2520 fprintf(stderr,
"pioinfo mark not found in " UCRTBASE
"\n");
2530 const uint32_t adrp_insn = *pc;
2531 const uint32_t adrp_immhi = (adrp_insn & 0x00ffffe0) >> 5;
2532 const uint32_t adrp_immlo = (adrp_insn & 0x60000000) >> (5 + 19 + 5);
2533 const int64_t adrp_sign = (adrp_insn & 0x00800000) ? ~0x001fffff : 0;
2535 const int64_t adrp_imm = (adrp_sign | (adrp_immhi << 2) | adrp_immlo) << 12;
2537 const uint64_t adrp_base = (uint64_t)pc & 0xfffffffffffff000;
2539 const uint32_t add_insn = *(pc + 1);
2540 const uint64_t add_imm = (add_insn & 0x3ffc00) >> (5 + 5);
2542 __pioinfo = (
ioinfo**)(adrp_base + adrp_imm + add_imm);
2550# define FUNCTION_BEFORE_RET_MARK "\x48\x83\xc4"
2551# define FUNCTION_SKIP_BYTES 1
2554# define PIOINFO_MARK "\x48\x8d\x0d"
2557# define PIOINFO_MARK "\x48\x8d\x15"
2562# define FUNCTION_BEFORE_RET_MARK "\x5d"
2564# define FUNCTION_BEFORE_RET_MARK_2 "\xc9"
2565# define FUNCTION_SKIP_BYTES 0
2567# define PIOINFO_MARK "\x8B\x04\x85"
2570 for (pend += 10; pend < p + 500; pend++) {
2572 if ((memcmp(pend, FUNCTION_BEFORE_RET_MARK,
sizeof(FUNCTION_BEFORE_RET_MARK) - 1) == 0
2573# ifdef FUNCTION_BEFORE_RET_MARK_2
2574 || memcmp(pend, FUNCTION_BEFORE_RET_MARK_2,
sizeof(FUNCTION_BEFORE_RET_MARK_2) - 1) == 0
2577 *(pend + (
sizeof(FUNCTION_BEFORE_RET_MARK) - 1) + FUNCTION_SKIP_BYTES) == (
char)FUNCTION_RET) {
2579 for (pend -= (
sizeof(PIOINFO_MARK) - 1); pend > p; pend--) {
2580 if (memcmp(pend, PIOINFO_MARK,
sizeof(PIOINFO_MARK) - 1) == 0) {
2589 fprintf(stderr,
"unexpected " UCRTBASE
"\n");
2593 p +=
sizeof(PIOINFO_MARK) - 1;
2595 rel = *(int32_t*)(p);
2596 rip = p +
sizeof(int32_t);
2597 __pioinfo = (
ioinfo**)(rip + rel);
2599 __pioinfo = *(
ioinfo***)(p);
2604 fd = _open(
"NUL", O_RDONLY);
2605 for (pioinfo_extra = 0; pioinfo_extra <= 64; pioinfo_extra +=
sizeof(
void *)) {
2606 if (_osfhnd(fd) == _get_osfhandle(fd)) {
2612 if (pioinfo_extra > 64) {
2621 const size_t sizeof_ioinfo =
sizeof(
ioinfo) + pioinfo_extra;
2622 return (
ioinfo*)((
char*)__pioinfo[fd >> IOINFO_L2E] +
2623 (fd & (IOINFO_ARRAY_ELTS - 1)) * sizeof_ioinfo);
2626#define _set_osfhnd(fh, osfh) (void)(_osfhnd(fh) = osfh)
2627#define _set_osflags(fh, flags) (_osfile(fh) = (flags))
2632#define FNOINHERIT 0x10
2637static int is_socket(SOCKET);
2638static int is_console(SOCKET);
2642rb_w32_io_cancelable_p(
int fd)
2644 return is_socket(TO_SOCKET(fd)) || !is_console(TO_SOCKET(fd));
2649rb_w32_open_osfhandle(intptr_t osfhandle,
int flags)
2658 if (flags & O_APPEND)
2659 fileflags |= FAPPEND;
2664 if (flags & O_NOINHERIT)
2665 fileflags |= FNOINHERIT;
2668 hF = CreateFile(
"NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
2669 fh = _open_osfhandle((intptr_t)hF, 0);
2677 rb_acrt_lowio_lock_fh(fh);
2679 _set_osfhnd(fh, osfhandle);
2683 _set_osflags(fh, fileflags);
2684 rb_acrt_lowio_unlock_fh(fh);
2695#define open_null(fd) \
2697 (nullfd = open("NUL", O_RDWR)) : 0), \
2698 ((nullfd == (fd)) ? (keep = 1) : dup2(nullfd, fd)), \
2701 if (fileno(stdin) < 0) {
2702 FILE_FILENO(stdin) = open_null(0);
2705 setmode(fileno(stdin), O_BINARY);
2707 if (fileno(stdout) < 0) {
2708 FILE_FILENO(stdout) = open_null(1);
2710 if (fileno(stderr) < 0) {
2711 FILE_FILENO(stderr) = open_null(2);
2713 if (nullfd >= 0 && !keep) close(nullfd);
2714 setvbuf(stderr, NULL, _IONBF, 0);
2717 HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
2719 if (GetConsoleMode(h, &m)) {
2720#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
2721#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x4
2723 SetConsoleMode(h, m | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
2732is_socket(SOCKET sock)
2734 if (socklist_lookup(sock, NULL))
2742rb_w32_is_socket(
int fd)
2744 return is_socket(TO_SOCKET(fd));
2757rb_w32_strerror(
int e)
2759 static char buffer[512];
2764 strlcpy(buffer,
"Unknown Error",
sizeof(buffer));
2765 else if (e > sys_nerr) {
2766#if WSAEWOULDBLOCK != EWOULDBLOCK
2767 if (e >= EADDRINUSE && e <= EWOULDBLOCK) {
2771 for (s = 0; s < (int)(
sizeof(errmap)/
sizeof(*errmap)); s++)
2772 if (errmap[s].winerr == WSAEWOULDBLOCK)
2774 for (i = s; i < (int)(
sizeof(errmap)/
sizeof(*errmap)); i++)
2775 if (errmap[i].err == e) {
2776 e = errmap[i].winerr;
2781 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
2782 FORMAT_MESSAGE_IGNORE_INSERTS, &source, e,
2783 MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
2784 buffer,
sizeof(buffer), NULL) == 0 &&
2785 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
2786 FORMAT_MESSAGE_IGNORE_INSERTS, &source, e, 0,
2787 buffer,
sizeof(buffer), NULL) == 0)
2788 strlcpy(buffer,
"Unknown Error",
sizeof(buffer));
2791 strlcpy(buffer, strerror(e),
sizeof(buffer));
2794 while ((p = strpbrk(p,
"\r\n")) != NULL) {
2795 memmove(p, p + 1, strlen(p));
2846 return (uid == ROOT_UID ? 0 : -1);
2853 return (gid == ROOT_GID ? 0 : -1);
2862ioctl(
int i,
int u, ...)
2869rb_w32_fdset(
int fd, fd_set *set)
2878rb_w32_fdclr(
int fd, fd_set *set)
2881 SOCKET s = TO_SOCKET(fd);
2883 for (i = 0; i < set->fd_count; i++) {
2884 if (set->fd_array[i] == s) {
2885 memmove(&set->fd_array[i], &set->fd_array[i+1],
2886 sizeof(set->fd_array[0]) * (--set->fd_count - i));
2896rb_w32_fdisset(
int fd, fd_set *set)
2899 SOCKET s = TO_SOCKET(fd);
2900 if (s == (SOCKET)INVALID_HANDLE_VALUE)
2902 RUBY_CRITICAL {ret = __WSAFDIsSet(s, set);}
2910 max = min(src->fd_count, (UINT)max);
2911 if ((UINT)dst->
capa < (UINT)max) {
2912 dst->
capa = (src->fd_count / FD_SETSIZE + 1) * FD_SETSIZE;
2916 memcpy(dst->
fdset->fd_array, src->fd_array,
2917 max *
sizeof(src->fd_array[0]));
2918 dst->
fdset->fd_count = src->fd_count;
2925 if ((UINT)dst->
capa < src->
fdset->fd_count) {
2926 dst->
capa = (src->
fdset->fd_count / FD_SETSIZE + 1) * FD_SETSIZE;
2930 memcpy(dst->
fdset->fd_array, src->
fdset->fd_array,
2931 src->
fdset->fd_count *
sizeof(src->
fdset->fd_array[0]));
2945extract_fd(
rb_fdset_t *dst, fd_set *src,
int (*func)(SOCKET))
2951 while (s < src->fd_count) {
2952 SOCKET fd = src->fd_array[s];
2954 if (!func || (*func)(fd)) {
2958 for (d = 0; d < dst->
fdset->fd_count; d++) {
2959 if (dst->
fdset->fd_array[d] == fd)
2962 if (d == dst->
fdset->fd_count) {
2963 if ((
int)dst->
fdset->fd_count >= dst->
capa) {
2964 dst->
capa = (dst->
fdset->fd_count / FD_SETSIZE + 1) * FD_SETSIZE;
2967 dst->
fdset->fd_array[dst->
fdset->fd_count++] = fd;
2971 &src->fd_array[s+1],
2972 sizeof(src->fd_array[0]) * (--src->fd_count - s));
2982 return dst ? dst->
fdset->fd_count : m;
2987copy_fd(fd_set *dst, fd_set *src)
2990 if (!src || !dst)
return 0;
2992 for (s = 0; s < src->fd_count; ++s) {
2993 SOCKET fd = src->fd_array[s];
2995 for (d = 0; d < dst->fd_count; ++d) {
2996 if (dst->fd_array[d] == fd)
2999 if (d == dst->fd_count && d < FD_SETSIZE) {
3000 dst->fd_array[dst->fd_count++] = fd;
3004 return dst->fd_count;
3009is_not_socket(SOCKET sock)
3011 return !is_socket(sock);
3021 ret = (GetFileType((HANDLE)sock) == FILE_TYPE_PIPE);
3029is_readable_pipe(SOCKET sock)
3035 if (PeekNamedPipe((HANDLE)sock, NULL, 0, NULL, &n, NULL)) {
3039 ret = (GetLastError() == ERROR_BROKEN_PIPE);
3048is_console(SOCKET sock)
3055 ret = (PeekConsoleInputW((HANDLE)sock, &ir, 1, &n));
3063is_readable_console(SOCKET sock)
3070 if (PeekConsoleInputW((HANDLE)sock, &ir, 1, &n) && n > 0) {
3071 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
3072 ir.Event.KeyEvent.uChar.UnicodeChar) {
3075 else if (ir.EventType == KEY_EVENT && !ir.Event.KeyEvent.bKeyDown &&
3076 ir.Event.KeyEvent.wVirtualKeyCode == VK_MENU &&
3077 ir.Event.KeyEvent.uChar.UnicodeChar) {
3081 ReadConsoleInputW((HANDLE)sock, &ir, 1, &n);
3091is_invalid_handle(SOCKET sock)
3093 return (HANDLE)sock == INVALID_HANDLE_VALUE;
3098do_select(
int nfds, fd_set *rd, fd_set *wr, fd_set *ex,
3105 rb_w32_sleep(timeout->tv_sec * 1000 + timeout->tv_usec / 1000);
3107 rb_w32_sleep(INFINITE);
3111 thread_exclusive(select) {
3112 r = select(nfds, rd, wr, ex, timeout);
3114 if (r == SOCKET_ERROR) {
3115 errno = map_errno(WSAGetLastError());
3130rb_w32_time_subtract(
struct timeval *rest,
const struct timeval *wait)
3132 if (rest->tv_sec < wait->tv_sec) {
3135 while (rest->tv_usec < wait->tv_usec) {
3136 if (rest->tv_sec <= wait->tv_sec) {
3140 rest->tv_usec += 1000 * 1000;
3142 rest->tv_sec -= wait->tv_sec;
3143 rest->tv_usec -= wait->tv_usec;
3144 return rest->tv_sec != 0 || rest->tv_usec != 0;
3151 if (t1->tv_sec < t2->tv_sec)
3153 if (t1->tv_sec > t2->tv_sec)
3155 if (t1->tv_usec < t2->tv_usec)
3157 if (t1->tv_usec > t2->tv_usec)
3164int rb_w32_check_interrupt(
void *);
3169rb_w32_select_with_thread(
int nfds, fd_set *rd, fd_set *wr, fd_set *ex,
3170 struct timeval *timeout,
void *th)
3179 struct timeval limit = {0, 0};
3181 if (nfds < 0 || (timeout && (timeout->tv_sec < 0 || timeout->tv_usec < 0))) {
3187 if (timeout->tv_sec < 0 ||
3188 timeout->tv_usec < 0 ||
3189 timeout->tv_usec >= 1000000) {
3193 gettimeofday(&limit, NULL);
3194 limit.tv_sec += timeout->tv_sec;
3195 limit.tv_usec += timeout->tv_usec;
3196 if (limit.tv_usec >= 1000000) {
3197 limit.tv_usec -= 1000000;
3209 nonsock += extract_fd(&else_rd, rd, is_not_socket);
3212 nonsock += extract_fd(&else_wr, wr, is_not_socket);
3215 if (extract_fd(NULL, else_rd.
fdset, is_invalid_handle) > 0 ||
3216 extract_fd(NULL, else_wr.
fdset, is_invalid_handle) > 0) {
3224 extract_fd(&pipe_rd, else_rd.
fdset, is_pipe);
3227 extract_fd(&cons_rd, else_rd.
fdset, is_console);
3230 extract_fd(&except, ex, is_not_socket);
3233 if (rd && (
int)rd->fd_count > r) r = (int)rd->fd_count;
3234 if (wr && (
int)wr->fd_count > r) r = (int)wr->fd_count;
3235 if (ex && (
int)ex->fd_count > r) r = (int)ex->fd_count;
3236 if (nfds > r) nfds = r;
3240 const struct timeval wait = {0, 10 * 1000};
3243 if (th && rb_w32_check_interrupt(th) != WAIT_TIMEOUT) {
3250 extract_fd(&else_rd, pipe_rd.
fdset, is_readable_pipe);
3251 extract_fd(&else_rd, cons_rd.
fdset, is_readable_console);
3254 if (else_rd.
fdset->fd_count || else_wr.
fdset->fd_count) {
3255 r = do_select(nfds, rd, wr, ex, &zero);
3257 r += copy_fd(rd, else_rd.
fdset);
3258 r += copy_fd(wr, else_wr.
fdset);
3264 const struct timeval *dowait = &wait;
3274 if (rd) copy_fd(&orig_rd, rd);
3275 if (wr) copy_fd(&orig_wr, wr);
3276 if (ex) copy_fd(&orig_ex, ex);
3277 r = do_select(nfds, rd, wr, ex, &zero);
3279 if (rd) copy_fd(rd, &orig_rd);
3280 if (wr) copy_fd(wr, &orig_wr);
3281 if (ex) copy_fd(ex, &orig_ex);
3285 gettimeofday(&now, NULL);
3287 if (!rb_w32_time_subtract(&rest, &now))
break;
3288 if (compare(&rest, &wait) < 0) dowait = &rest;
3290 Sleep(dowait->tv_sec * 1000 + (dowait->tv_usec + 999) / 1000);
3306rb_w32_select(
int nfds, fd_set *rd, fd_set *wr, fd_set *ex,
3309 return rb_w32_select_with_thread(nfds, rd, wr, ex, timeout, 0);
3314get_wsa_extension_function(SOCKET s, GUID guid)
3319 WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, &guid,
sizeof(guid),
3320 &ptr,
sizeof(ptr), &dmy, NULL, NULL);
3330rb_w32_accept(
int s,
struct sockaddr *addr,
int *addrlen)
3336 r = accept(TO_SOCKET(s), addr, addrlen);
3337 if (r != INVALID_SOCKET) {
3338 SetHandleInformation((HANDLE)r, HANDLE_FLAG_INHERIT, 0);
3339 fd = rb_w32_open_osfhandle((intptr_t)r, O_RDWR|O_BINARY|O_NOINHERIT);
3341 socklist_insert(r, 0);
3346 errno = map_errno(WSAGetLastError());
3357rb_w32_bind(
int s,
const struct sockaddr *addr,
int addrlen)
3362 r = bind(TO_SOCKET(s), addr, addrlen);
3363 if (r == SOCKET_ERROR)
3364 errno = map_errno(WSAGetLastError());
3373rb_w32_connect(
int s,
const struct sockaddr *addr,
int addrlen)
3377 r = connect(TO_SOCKET(s), addr, addrlen);
3378 if (r == SOCKET_ERROR) {
3379 int err = WSAGetLastError();
3380 if (err != WSAEWOULDBLOCK)
3381 errno = map_errno(err);
3383 errno = EINPROGRESS;
3394rb_w32_getpeername(
int s,
struct sockaddr *addr,
int *addrlen)
3398 r = getpeername(TO_SOCKET(s), addr, addrlen);
3399 if (r == SOCKET_ERROR)
3400 errno = map_errno(WSAGetLastError());
3409rb_w32_getsockname(
int fd,
struct sockaddr *addr,
int *addrlen)
3414 sock = TO_SOCKET(fd);
3415 r = getsockname(sock, addr, addrlen);
3416 if (r == SOCKET_ERROR) {
3417 DWORD wsaerror = WSAGetLastError();
3418 if (wsaerror == WSAEINVAL) {
3420 if (socklist_lookup(sock, &flags)) {
3421 int af = GET_FAMILY(flags);
3423 memset(addr, 0, *addrlen);
3424 addr->sa_family = af;
3429 errno = map_errno(wsaerror);
3439rb_w32_getsockopt(
int s,
int level,
int optname,
char *optval,
int *optlen)
3443 r = getsockopt(TO_SOCKET(s), level, optname, optval, optlen);
3444 if (r == SOCKET_ERROR)
3445 errno = map_errno(WSAGetLastError());
3454rb_w32_ioctlsocket(
int s,
long cmd, u_long *argp)
3458 r = ioctlsocket(TO_SOCKET(s), cmd, argp);
3459 if (r == SOCKET_ERROR)
3460 errno = map_errno(WSAGetLastError());
3469rb_w32_listen(
int s,
int backlog)
3473 r = listen(TO_SOCKET(s), backlog);
3474 if (r == SOCKET_ERROR)
3475 errno = map_errno(WSAGetLastError());
3487finish_overlapped_socket(BOOL input, SOCKET s, WSAOVERLAPPED *wol,
int result, DWORD *
len, DWORD size)
3492 if (result != SOCKET_ERROR)
3494 else if ((err = WSAGetLastError()) == WSA_IO_PENDING) {
3495 switch (rb_w32_wait_events_blocking(&wol->hEvent, 1, INFINITE)) {
3498 result = WSAGetOverlappedResult(s, wol, &size, TRUE, &flg);
3505 result = SOCKET_ERROR;
3508 if ((err = WSAGetLastError()) == WSAECONNABORTED && !input)
3510 else if (err == WSAEMSGSIZE && input) {
3516 errno = map_errno(err);
3518 case WAIT_OBJECT_0 + 1:
3521 CancelIo((HANDLE)s);
3526 if (err == WSAECONNABORTED && !input)
3529 errno = map_errno(err);
3532 CloseHandle(wol->hEvent);
3539overlapped_socket_io(BOOL input,
int fd,
char *buf,
int len,
int flags,
3540 struct sockaddr *addr,
int *addrlen)
3551 socklist_lookup(s, &mode);
3552 if (GET_FLAGS(mode) & O_NONBLOCK) {
3555 if (addr && addrlen)
3556 r = recvfrom(s, buf,
len, flags, addr, addrlen);
3558 r = recv(s, buf,
len, flags);
3559 if (r == SOCKET_ERROR)
3560 errno = map_errno(WSAGetLastError());
3563 if (addr && addrlen)
3564 r = sendto(s, buf,
len, flags, addr, *addrlen);
3566 r = send(s, buf,
len, flags);
3567 if (r == SOCKET_ERROR) {
3568 DWORD err = WSAGetLastError();
3569 if (err == WSAECONNABORTED)
3572 errno = map_errno(err);
3582 memset(&wol, 0,
sizeof(wol));
3584 wol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3587 if (addr && addrlen)
3588 ret = WSARecvFrom(s, &wbuf, 1, &size, &flg, addr, addrlen,
3591 ret = WSARecv(s, &wbuf, 1, &size, &flg, &wol, NULL);
3594 if (addr && addrlen)
3595 ret = WSASendTo(s, &wbuf, 1, &size, flags, addr, *addrlen,
3598 ret = WSASend(s, &wbuf, 1, &size, flags, &wol, NULL);
3602 finish_overlapped_socket(input, s, &wol, ret, &rlen, size);
3611rb_w32_recv(
int fd,
char *buf,
int len,
int flags)
3613 return overlapped_socket_io(TRUE, fd, buf,
len, flags, NULL, NULL);
3618rb_w32_recvfrom(
int fd,
char *buf,
int len,
int flags,
3619 struct sockaddr *from,
int *fromlen)
3621 return overlapped_socket_io(TRUE, fd, buf,
len, flags, from, fromlen);
3626rb_w32_send(
int fd,
const char *buf,
int len,
int flags)
3628 return overlapped_socket_io(FALSE, fd, (
char *)buf,
len, flags, NULL, NULL);
3633rb_w32_sendto(
int fd,
const char *buf,
int len,
int flags,
3634 const struct sockaddr *to,
int tolen)
3636 return overlapped_socket_io(FALSE, fd, (
char *)buf,
len, flags,
3637 (
struct sockaddr *)to, &tolen);
3640#if !defined(MSG_TRUNC) && !defined(__MINGW32__)
3646 DWORD dwBufferCount;
3651#ifndef WSAID_WSARECVMSG
3652#define WSAID_WSARECVMSG {0xf689d7c8,0x6f1f,0x436b,{0x8a,0x53,0xe5,0x4f,0xe3,0x51,0xc3,0x22}}
3654#ifndef WSAID_WSASENDMSG
3655#define WSAID_WSASENDMSG {0xa441e712,0x754f,0x43ca,{0x84,0xa7,0x0d,0xee,0x44,0xcf,0x60,0x6d}}
3659#define msghdr_to_wsamsg(msg, wsamsg) \
3662 (wsamsg)->name = (msg)->msg_name; \
3663 (wsamsg)->namelen = (msg)->msg_namelen; \
3664 (wsamsg)->lpBuffers = ALLOCA_N(WSABUF, (msg)->msg_iovlen); \
3665 (wsamsg)->dwBufferCount = (msg)->msg_iovlen; \
3666 for (i = 0; i < (msg)->msg_iovlen; ++i) { \
3667 (wsamsg)->lpBuffers[i].buf = (msg)->msg_iov[i].iov_base; \
3668 (wsamsg)->lpBuffers[i].len = (msg)->msg_iov[i].iov_len; \
3670 (wsamsg)->Control.buf = (msg)->msg_control; \
3671 (wsamsg)->Control.len = (msg)->msg_controllen; \
3672 (wsamsg)->dwFlags = (msg)->msg_flags; \
3677recvmsg(
int fd,
struct msghdr *msg,
int flags)
3679 typedef int (WSAAPI *WSARecvMsg_t)(SOCKET,
WSAMSG *, DWORD *, WSAOVERLAPPED *, LPWSAOVERLAPPED_COMPLETION_ROUTINE);
3680 static WSARecvMsg_t pWSARecvMsg = NULL;
3690 static const GUID guid = WSAID_WSARECVMSG;
3691 pWSARecvMsg = (WSARecvMsg_t)get_wsa_extension_function(s, guid);
3696 msghdr_to_wsamsg(msg, &wsamsg);
3697 wsamsg.dwFlags |= flags;
3699 socklist_lookup(s, &mode);
3700 if (GET_FLAGS(mode) & O_NONBLOCK) {
3702 if ((ret = pWSARecvMsg(s, &wsamsg, &
len, NULL, NULL)) == SOCKET_ERROR) {
3703 errno = map_errno(WSAGetLastError());
3711 memset(&wol, 0,
sizeof(wol));
3713 wol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3714 ret = pWSARecvMsg(s, &wsamsg, &size, &wol, NULL);
3717 ret = finish_overlapped_socket(TRUE, s, &wol, ret, &
len, size);
3719 if (ret == SOCKET_ERROR)
3723 msg->msg_name = wsamsg.name;
3724 msg->msg_namelen = wsamsg.namelen;
3725 msg->msg_flags = wsamsg.dwFlags;
3732sendmsg(
int fd,
const struct msghdr *msg,
int flags)
3734 typedef int (WSAAPI *WSASendMsg_t)(SOCKET,
const WSAMSG *, DWORD, DWORD *, WSAOVERLAPPED *, LPWSAOVERLAPPED_COMPLETION_ROUTINE);
3735 static WSASendMsg_t pWSASendMsg = NULL;
3745 static const GUID guid = WSAID_WSASENDMSG;
3746 pWSASendMsg = (WSASendMsg_t)get_wsa_extension_function(s, guid);
3751 msghdr_to_wsamsg(msg, &wsamsg);
3753 socklist_lookup(s, &mode);
3754 if (GET_FLAGS(mode) & O_NONBLOCK) {
3756 if ((ret = pWSASendMsg(s, &wsamsg, flags, &
len, NULL, NULL)) == SOCKET_ERROR) {
3757 errno = map_errno(WSAGetLastError());
3765 memset(&wol, 0,
sizeof(wol));
3767 wol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3768 ret = pWSASendMsg(s, &wsamsg, flags, &size, &wol, NULL);
3771 finish_overlapped_socket(FALSE, s, &wol, ret, &
len, size);
3781rb_w32_setsockopt(
int s,
int level,
int optname,
const char *optval,
int optlen)
3785 r = setsockopt(TO_SOCKET(s), level, optname, optval, optlen);
3786 if (r == SOCKET_ERROR)
3787 errno = map_errno(WSAGetLastError());
3796rb_w32_shutdown(
int s,
int how)
3800 r = shutdown(TO_SOCKET(s), how);
3801 if (r == SOCKET_ERROR)
3802 errno = map_errno(WSAGetLastError());
3809open_ifs_socket(
int af,
int type,
int protocol)
3811 unsigned long proto_buffers_len = 0;
3813 SOCKET out = INVALID_SOCKET;
3815 if (WSAEnumProtocols(NULL, NULL, &proto_buffers_len) == SOCKET_ERROR) {
3816 error_code = WSAGetLastError();
3817 if (error_code == WSAENOBUFS) {
3818 WSAPROTOCOL_INFO *proto_buffers;
3819 int protocols_available = 0;
3821 proto_buffers = (WSAPROTOCOL_INFO *)malloc(proto_buffers_len);
3822 if (!proto_buffers) {
3823 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
3824 return INVALID_SOCKET;
3827 protocols_available =
3828 WSAEnumProtocols(NULL, proto_buffers, &proto_buffers_len);
3829 if (protocols_available != SOCKET_ERROR) {
3831 for (i = 0; i < protocols_available; i++) {
3832 if ((af != AF_UNSPEC && af != proto_buffers[i].iAddressFamily) ||
3833 (
type != proto_buffers[i].iSocketType) ||
3834 (protocol != 0 && protocol != proto_buffers[i].iProtocol))
3837 if ((proto_buffers[i].dwServiceFlags1 & XP1_IFS_HANDLES) == 0)
3840 out = WSASocket(af,
type, protocol, &(proto_buffers[i]), 0,
3841 WSA_FLAG_OVERLAPPED);
3844 if (out == INVALID_SOCKET)
3845 out = WSASocket(af,
type, protocol, NULL, 0, 0);
3846 if (out != INVALID_SOCKET)
3847 SetHandleInformation((HANDLE)out, HANDLE_FLAG_INHERIT, 0);
3850 free(proto_buffers);
3861rb_w32_socket(
int af,
int type,
int protocol)
3867 s = open_ifs_socket(af,
type, protocol);
3868 if (s == INVALID_SOCKET) {
3869 errno = map_errno(WSAGetLastError());
3873 fd = rb_w32_open_osfhandle(s, O_RDWR|O_BINARY|O_NOINHERIT);
3875 socklist_insert(s, MAKE_SOCKDATA(af, 0));
3886struct hostent * WSAAPI
3887rb_w32_gethostbyaddr(
const char *addr,
int len,
int type)
3891 r = gethostbyaddr(addr,
len,
type);
3893 errno = map_errno(WSAGetLastError());
3901struct hostent * WSAAPI
3902rb_w32_gethostbyname(
const char *name)
3906 r = gethostbyname(name);
3908 errno = map_errno(WSAGetLastError());
3917rb_w32_gethostname(
char *name,
int len)
3921 r = gethostname(name,
len);
3922 if (r == SOCKET_ERROR)
3923 errno = map_errno(WSAGetLastError());
3928#undef getprotobyname
3931struct protoent * WSAAPI
3932rb_w32_getprotobyname(
const char *name)
3936 r = getprotobyname(name);
3938 errno = map_errno(WSAGetLastError());
3943#undef getprotobynumber
3946struct protoent * WSAAPI
3947rb_w32_getprotobynumber(
int num)
3951 r = getprotobynumber(num);
3953 errno = map_errno(WSAGetLastError());
3961struct servent * WSAAPI
3962rb_w32_getservbyname(
const char *name,
const char *proto)
3966 r = getservbyname(name, proto);
3968 errno = map_errno(WSAGetLastError());
3976struct servent * WSAAPI
3977rb_w32_getservbyport(
int port,
const char *proto)
3981 r = getservbyport(port, proto);
3983 errno = map_errno(WSAGetLastError());
3992socketpair_unix_path(
struct sockaddr_un *sock_un)
3995 WCHAR wpath[
sizeof(sock_un->sun_path)/
sizeof(*sock_un->sun_path)] = L
"";
4000 listener = socket(AF_UNIX, SOCK_STREAM, 0);
4001 if (listener == INVALID_SOCKET)
4004 memset(sock_un, 0,
sizeof(*sock_un));
4005 sock_un->sun_family = AF_UNIX;
4015 for (
int try = 0; ;
try++) {
4016 LARGE_INTEGER ticks;
4017 size_t path_len = 0;
4018 const size_t maxpath =
sizeof(sock_un->sun_path)/
sizeof(*sock_un->sun_path);
4023 path_len = GetTempPathW(maxpath, wpath);
4026 wcsncpy(wpath, L
"C:/Temp/", maxpath);
4027 path_len = lstrlenW(wpath);
4034 closesocket(listener);
4039 path_len = WideCharToMultiByte(CP_UTF8, 0, wpath, path_len, sock_un->sun_path, maxpath, NULL, NULL);
4040 QueryPerformanceCounter(&ticks);
4041 path_len += snprintf(sock_un->sun_path + path_len,
4045 GetCurrentProcessId());
4048 MultiByteToWideChar(CP_UTF8, 0, sock_un->sun_path, -1, wpath,
sizeof(wpath)/
sizeof(*wpath));
4050 if (bind(listener, (
struct sockaddr *)sock_un,
sizeof(*sock_un)) != SOCKET_ERROR)
4053 closesocket(listener);
4055 return sizeof(*sock_un);
4061socketpair_internal(
int af,
int type,
int protocol, SOCKET *sv)
4063 SOCKET svr = INVALID_SOCKET, r = INVALID_SOCKET, w = INVALID_SOCKET;
4064 struct sockaddr_in sock_in4;
4067 struct sockaddr_in6 sock_in6;
4071 struct sockaddr_un sock_un = {0, {0}};
4072 WCHAR wpath[
sizeof(sock_un.sun_path)/
sizeof(*sock_un.sun_path)] = L
"";
4075 struct sockaddr *addr;
4081#if defined PF_INET && PF_INET != AF_INET
4084 sock_in4.sin_family = AF_INET;
4085 sock_in4.sin_port = 0;
4086 sock_in4.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4087 addr = (
struct sockaddr *)&sock_in4;
4088 len =
sizeof(sock_in4);
4092 memset(&sock_in6, 0,
sizeof(sock_in6));
4093 sock_in6.sin6_family = AF_INET6;
4094 sock_in6.sin6_addr = IN6ADDR_LOOPBACK_INIT;
4095 addr = (
struct sockaddr *)&sock_in6;
4096 len =
sizeof(sock_in6);
4101 addr = (
struct sockaddr *)&sock_un;
4102 len = socketpair_unix_path(&sock_un);
4103 MultiByteToWideChar(CP_UTF8, 0, sock_un.sun_path, -1, wpath,
sizeof(wpath)/
sizeof(*wpath));
4109 errno = EAFNOSUPPORT;
4112 if (
type != SOCK_STREAM) {
4117 sv[0] = (SOCKET)INVALID_HANDLE_VALUE;
4118 sv[1] = (SOCKET)INVALID_HANDLE_VALUE;
4121 svr = open_ifs_socket(af,
type, protocol);
4122 if (svr == INVALID_SOCKET)
4124 if (bind(svr, addr,
len) < 0)
4126 if (getsockname(svr, addr, &
len) < 0)
4128 if (
type == SOCK_STREAM)
4131 w = open_ifs_socket(af,
type, protocol);
4132 if (w == INVALID_SOCKET)
4134 if (connect(w, addr,
len) < 0)
4137 r = accept(svr, addr, &
len);
4138 if (r == INVALID_SOCKET)
4140 SetHandleInformation((HANDLE)r, HANDLE_FLAG_INHERIT, 0);
4146 errno = map_errno(WSAGetLastError());
4147 if (r != INVALID_SOCKET)
4149 if (w != INVALID_SOCKET)
4156 if (svr != INVALID_SOCKET)
4159 if (sock_un.sun_family == AF_UNIX)
4169socketpair(
int af,
int type,
int protocol,
int *sv)
4173 if (socketpair_internal(af,
type, protocol, pair) < 0)
4175 sv[0] = rb_w32_open_osfhandle(pair[0], O_RDWR|O_BINARY|O_NOINHERIT);
4177 closesocket(pair[0]);
4178 closesocket(pair[1]);
4181 sv[1] = rb_w32_open_osfhandle(pair[1], O_RDWR|O_BINARY|O_NOINHERIT);
4183 rb_w32_close(sv[0]);
4184 closesocket(pair[1]);
4187 socklist_insert(pair[0], MAKE_SOCKDATA(af, 0));
4188 socklist_insert(pair[1], MAKE_SOCKDATA(af, 0));
4195str2guid(
const char *str, GUID *guid)
4197#define hex2byte(str) \
4198 ((isdigit(*(str)) ? *(str) - '0' : toupper(*(str)) - 'A' + 10) << 4 | (isdigit(*((str) + 1)) ? *((str) + 1) - '0' : toupper(*((str) + 1)) - 'A' + 10))
4201 if (*str ==
'{') str++;
4202 guid->Data1 = (long)strtoul(str, &end, 16);
4204 guid->Data2 = (
unsigned short)strtoul(str, &end, 16);
4206 guid->Data3 = (
unsigned short)strtoul(str, &end, 16);
4208 guid->Data4[0] = hex2byte(str);
4210 guid->Data4[1] = hex2byte(str);
4212 for (i = 0; i < 6; i++) {
4213 guid->Data4[i + 2] = hex2byte(str);
4219#ifndef HAVE_TYPE_NET_LUID
4223 uint64_t Reserved :24;
4224 uint64_t NetLuidIndex :24;
4225 uint64_t IfType :16;
4231getifaddrs(
struct ifaddrs **ifap)
4235 IP_ADAPTER_ADDRESSES *root, *addr;
4238 ret = GetAdaptersAddresses(AF_UNSPEC, 0, NULL, NULL, &size);
4239 if (ret != ERROR_BUFFER_OVERFLOW) {
4240 errno = map_errno(ret);
4243 root = ruby_xmalloc(size);
4244 ret = GetAdaptersAddresses(AF_UNSPEC, 0, NULL, root, &size);
4245 if (ret != ERROR_SUCCESS) {
4246 errno = map_errno(ret);
4251 for (prev = NULL, addr = root; addr; addr = addr->Next) {
4252 struct ifaddrs *ifa = ruby_xcalloc(1,
sizeof(*ifa));
4253 char name[IFNAMSIZ];
4258 prev->ifa_next = ifa;
4262 str2guid(addr->AdapterName, &guid);
4263 if (ConvertInterfaceGuidToLuid(&guid, &luid) == NO_ERROR &&
4264 ConvertInterfaceLuidToNameA(&luid, name,
sizeof(name)) == NO_ERROR) {
4271 if (addr->IfType & IF_TYPE_SOFTWARE_LOOPBACK)
4272 ifa->ifa_flags |= IFF_LOOPBACK;
4273 if (addr->OperStatus == IfOperStatusUp) {
4274 ifa->ifa_flags |= IFF_UP;
4276 if (addr->FirstUnicastAddress) {
4277 IP_ADAPTER_UNICAST_ADDRESS *cur;
4279 for (cur = addr->FirstUnicastAddress; cur; cur = cur->Next) {
4280 if (cur->Flags & IP_ADAPTER_ADDRESS_TRANSIENT ||
4281 cur->DadState == IpDadStateDeprecated) {
4286 ifa = ruby_xcalloc(1,
sizeof(*ifa));
4287 prev->ifa_next = ifa;
4289 ifa->ifa_flags = prev->ifa_flags;
4291 ifa->ifa_addr = ruby_xmalloc(cur->Address.iSockaddrLength);
4292 memcpy(ifa->ifa_addr, cur->Address.lpSockaddr,
4293 cur->Address.iSockaddrLength);
4308freeifaddrs(
struct ifaddrs *ifp)
4311 struct ifaddrs *next = ifp->ifa_next;
4312 ruby_xfree(ifp->ifa_addr);
4313 ruby_xfree(ifp->ifa_name);
4324void endhostent(
void) {}
4325void endnetent(
void) {}
4326void endprotoent(
void) {}
4327void endservent(
void) {}
4329struct netent *getnetent (
void) {
return (
struct netent *) NULL;}
4331struct netent *getnetbyaddr(
long net,
int type) {
return (
struct netent *)NULL;}
4333struct netent *getnetbyname(
const char *name) {
return (
struct netent *)NULL;}
4335struct protoent *getprotoent (
void) {
return (
struct protoent *) NULL;}
4337struct servent *getservent (
void) {
return (
struct servent *) NULL;}
4339void sethostent (
int stayopen) {}
4341void setnetent (
int stayopen) {}
4343void setprotoent (
int stayopen) {}
4345void setservent (
int stayopen) {}
4348int rb_w32_set_nonblock2(
int fd,
int nonblock);
4352setfl(SOCKET sock,
int arg)
4359 socklist_lookup(sock, &flag);
4360 af = GET_FAMILY(flag);
4361 flag = GET_FLAGS(flag);
4362 if (arg & O_NONBLOCK) {
4367 flag &= ~O_NONBLOCK;
4371 ret = ioctlsocket(sock, FIONBIO, &ioctlArg);
4373 socklist_insert(sock, MAKE_SOCKDATA(af, flag));
4375 errno = map_errno(WSAGetLastError());
4383dupfd(HANDLE hDup,
int flags,
int minfd)
4391 ret = _open_osfhandle((intptr_t)hDup, flags | FOPEN);
4393 goto close_fds_and_return;
4396 goto close_fds_and_return;
4398 fds[filled++] = ret;
4399 }
while (filled < (
int)numberof(fds));
4401 ret = dupfd(hDup, flags, minfd);
4403 close_fds_and_return:
4405 while (filled > 0) {
4406 int fd = fds[--filled];
4407 _set_osfhnd(fd, (intptr_t)INVALID_HANDLE_VALUE);
4417fcntl(
int fd,
int cmd, ...)
4426 arg = va_arg(va,
int);
4428 return rb_w32_set_nonblock2(fd, arg);
4430 case F_DUPFD:
case F_DUPFD_CLOEXEC: {
4434 if (!(DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
4435 GetCurrentProcess(), &hDup, 0L,
4436 cmd == F_DUPFD && !(flag & FNOINHERIT),
4437 DUPLICATE_SAME_ACCESS))) {
4438 errno = map_errno(GetLastError());
4443 arg = va_arg(va,
int);
4449 flag &= ~FNOINHERIT;
4450 if ((ret = dupfd(hDup, flag, arg)) == -1)
4456 if (h == -1)
return -1;
4457 if (!GetHandleInformation((HANDLE)h, &flag)) {
4458 errno = map_errno(GetLastError());
4461 return (flag & HANDLE_FLAG_INHERIT) ? 0 : FD_CLOEXEC;
4465 if (h == -1)
return -1;
4467 arg = va_arg(va,
int);
4469 if (!SetHandleInformation((HANDLE)h, HANDLE_FLAG_INHERIT,
4470 (arg & FD_CLOEXEC) ? 0 : HANDLE_FLAG_INHERIT)) {
4471 errno = map_errno(GetLastError());
4474 if (arg & FD_CLOEXEC)
4475 _osfile(fd) |= FNOINHERIT;
4477 _osfile(fd) &= ~FNOINHERIT;
4488rb_w32_set_nonblock2(
int fd,
int nonblock)
4490 SOCKET sock = TO_SOCKET(fd);
4491 if (is_socket(sock)) {
4492 return setfl(sock, nonblock ? O_NONBLOCK : 0);
4494 else if (is_pipe(sock)) {
4496 if (!GetNamedPipeHandleState((HANDLE)sock, &state, NULL, NULL, NULL, NULL, 0)) {
4497 errno = map_errno(GetLastError());
4501 state |= PIPE_NOWAIT;
4504 state &= ~PIPE_NOWAIT;
4506 if (!SetNamedPipeHandleState((HANDLE)sock, &state, NULL, NULL)) {
4507 errno = map_errno(GetLastError());
4519rb_w32_set_nonblock(
int fd)
4521 return rb_w32_set_nonblock2(fd, TRUE);
4530poll_child_status(
struct ChildRecord *child,
int *stat_loc)
4535 if (!GetExitCodeProcess(child->hProcess, &exitcode)) {
4537 err = GetLastError();
4539 case ERROR_INVALID_PARAMETER:
4542 case ERROR_INVALID_HANDLE:
4546 errno = map_errno(err);
4550 CloseChildHandle(child);
4553 if (exitcode != STILL_ACTIVE) {
4556 if (rb_w32_wait_events_blocking(&child->hProcess, 1, INFINITE) != WAIT_OBJECT_0) {
4560 CloseChildHandle(child);
4562 *stat_loc = exitcode << 8;
4563 if (exitcode & 0xC0000000) {
4564 static const struct {
4568 {STATUS_ACCESS_VIOLATION, SIGSEGV},
4569 {STATUS_ILLEGAL_INSTRUCTION, SIGILL},
4570 {STATUS_PRIVILEGED_INSTRUCTION, SIGILL},
4571 {STATUS_FLOAT_DENORMAL_OPERAND, SIGFPE},
4572 {STATUS_FLOAT_DIVIDE_BY_ZERO, SIGFPE},
4573 {STATUS_FLOAT_INEXACT_RESULT, SIGFPE},
4574 {STATUS_FLOAT_INVALID_OPERATION, SIGFPE},
4575 {STATUS_FLOAT_OVERFLOW, SIGFPE},
4576 {STATUS_FLOAT_STACK_CHECK, SIGFPE},
4577 {STATUS_FLOAT_UNDERFLOW, SIGFPE},
4578#ifdef STATUS_FLOAT_MULTIPLE_FAULTS
4579 {STATUS_FLOAT_MULTIPLE_FAULTS, SIGFPE},
4581#ifdef STATUS_FLOAT_MULTIPLE_TRAPS
4582 {STATUS_FLOAT_MULTIPLE_TRAPS, SIGFPE},
4584 {STATUS_CONTROL_C_EXIT, SIGINT},
4587 for (i = 0; i < (int)numberof(table); i++) {
4588 if (table[i].status == exitcode) {
4589 *stat_loc |= table[i].sig;
4594 if (i >= (
int)numberof(table))
4595 *stat_loc |= SIGSEGV;
4605waitpid(rb_pid_t pid,
int *stat_loc,
int options)
4610 if (options == WNOHANG) {
4621 HANDLE events[MAXCHILDNUM];
4624 FOREACH_CHILD(child) {
4625 if (!child->pid || child->pid < 0)
continue;
4626 if ((pid = poll_child_status(child, stat_loc)))
return pid;
4627 events[count++] = child->hProcess;
4628 } END_FOREACH_CHILD;
4634 ret = rb_w32_wait_events_blocking(events, count, timeout);
4635 if (ret == WAIT_TIMEOUT)
return 0;
4636 if ((ret -= WAIT_OBJECT_0) == count) {
4640 errno = map_errno(GetLastError());
4644 cause = FindChildSlotByHandle(events[ret]);
4649 return poll_child_status(cause, stat_loc);
4659 while (!(pid = poll_child_status(child, stat_loc))) {
4661 int ret = rb_w32_wait_events_blocking(&child->hProcess, 1, timeout);
4662 if (ret == WAIT_OBJECT_0 + 1)
return -1;
4663 if (ret != WAIT_OBJECT_0) {
4665 if (options & WNOHANG) {
4672 if (pid == -1 && retried) pid = 0;
4678#include <sys/timeb.h>
4681#define filetime_unit (10UL * 1000 * 1000)
4682#define filetime_diff_days ((1970-1601)*3652425UL/10000)
4683#define filetime_diff_secs (filetime_diff_days * (24ULL * 60 * 60))
4684#define unix_to_filetime(sec) (((sec) + filetime_diff_secs) * filetime_unit)
4685#define filetime_unix_offset unix_to_filetime(0ULL)
4697filetime_split(
const FILETIME* ft,
long *subsec)
4700 ULONGLONG lt = fi.i.QuadPart;
4706 lt -= unix_to_filetime(0);
4708 *subsec = (long)(lt % filetime_unit);
4709 return (time_t)(lt / filetime_unit);
4719 GetSystemTimePreciseAsFileTime(&ft);
4720 tv->tv_sec = filetime_split(&ft, &subsec);
4721 tv->tv_usec = subsec / 10;
4728filetime_to_timespec(FILETIME ft,
struct timespec *sp)
4731 sp->tv_sec = filetime_split(&ft, &subsec);
4732 sp->tv_nsec = subsec * 100;
4736static const long secs_in_ns = 1000000000;
4740clock_gettime(clockid_t clock_id,
struct timespec *sp)
4743 case CLOCK_REALTIME:
4744 case CLOCK_REALTIME_COARSE:
4748 GetSystemTimePreciseAsFileTime(&ft);
4749 filetime_to_timespec(ft, sp);
4752 case CLOCK_MONOTONIC:
4755 LARGE_INTEGER count;
4756 if (UNLIKELY(!QueryPerformanceFrequency(&freq))) {
4757 errno = map_errno(GetLastError());
4760 if (UNLIKELY(!QueryPerformanceCounter(&count))) {
4761 errno = map_errno(GetLastError());
4764 sp->tv_sec = count.QuadPart / freq.QuadPart;
4765 if (freq.QuadPart < secs_in_ns)
4766 sp->tv_nsec = (count.QuadPart % freq.QuadPart) * secs_in_ns / freq.QuadPart;
4768 sp->tv_nsec = (long)((count.QuadPart % freq.QuadPart) * ((double)secs_in_ns / freq.QuadPart));
4771 case CLOCK_PROCESS_CPUTIME_ID:
4772 case CLOCK_THREAD_CPUTIME_ID:
4776 if (clock_id == CLOCK_PROCESS_CPUTIME_ID) {
4777 ok = GetProcessTimes(GetCurrentProcess(), &c.ft, &e.ft, &k.ft, &u.ft);
4780 ok = GetThreadTimes(GetCurrentThread(), &c.ft, &e.ft, &k.ft, &u.ft);
4782 if (UNLIKELY(!ok)) {
4783 errno = map_errno(GetLastError());
4786 total.i.QuadPart = k.i.QuadPart + u.i.QuadPart;
4787 filetime_to_timespec(total.ft, sp);
4798clock_getres(clockid_t clock_id,
struct timespec *sp)
4801 case CLOCK_REALTIME:
4802 case CLOCK_REALTIME_COARSE:
4808 case CLOCK_MONOTONIC:
4811 if (!QueryPerformanceFrequency(&freq)) {
4812 errno = map_errno(GetLastError());
4816 sp->tv_nsec = (long)((
double)secs_in_ns / freq.QuadPart);
4819 case CLOCK_PROCESS_CPUTIME_ID:
4820 case CLOCK_THREAD_CPUTIME_ID:
4822 const int frames_in_sec = 60;
4824 sp->tv_nsec = (long)(secs_in_ns / frames_in_sec);
4835w32_getcwd(
char *buffer,
int size, UINT cp,
void *alloc(
int,
void *),
void *arg)
4840 len = GetCurrentDirectoryW(0, NULL);
4842 errno = map_errno(GetLastError());
4846 if (buffer && size <
len) {
4852 if (!GetCurrentDirectoryW(
len, p)) {
4853 errno = map_errno(GetLastError());
4857 wlen = translate_wchar(p, L
'\\', L
'/') - p + 1;
4858 len = WideCharToMultiByte(cp, 0, p, wlen, NULL, 0, NULL, NULL);
4866 buffer = (*alloc)(
len, arg);
4872 WideCharToMultiByte(cp, 0, p, wlen, buffer,
len, NULL, NULL);
4879getcwd_alloc(
int size,
void *dummy)
4881 return malloc(size);
4886rb_w32_getcwd(
char *buffer,
int size)
4888 return w32_getcwd(buffer, size, filecp(), getcwd_alloc, NULL);
4893rb_w32_ugetcwd(
char *buffer,
int size)
4895 return w32_getcwd(buffer, size, CP_UTF8, getcwd_alloc, NULL);
4900getcwd_value(
int size,
void *arg)
4903 return RSTRING_PTR(str);
4908rb_dir_getwd_ospath(
void)
4911 w32_getcwd(NULL, 0, CP_UTF8, getcwd_value, &cwd);
4917chown(
const char *path,
int owner,
int group)
4924rb_w32_uchown(
const char *path,
int owner,
int group)
4930lchown(
const char *path,
int owner,
int group)
4936rb_w32_ulchown(
const char *path,
int owner,
int group)
4943kill(rb_pid_t pid,
int sig)
4948 if (pid < 0 || (pid == 0 && sig != SIGINT)) {
4953 if ((
unsigned int)pid == GetCurrentProcessId() &&
4954 (sig != 0 && sig != SIGKILL)) {
4955 if ((ret = raise(sig)) != 0) {
4966 OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, (DWORD)pid);
4967 if (hProc == NULL || hProc == INVALID_HANDLE_VALUE) {
4968 if (GetLastError() == ERROR_INVALID_PARAMETER) {
4984 DWORD ctrlEvent = CTRL_C_EVENT;
4988 ctrlEvent = CTRL_BREAK_EVENT;
4990 if (!GenerateConsoleCtrlEvent(ctrlEvent, (DWORD)pid)) {
4991 if ((err = GetLastError()) == 0)
4994 errno = map_errno(GetLastError());
5005 hProc = child->hProcess;
5008 hProc = OpenProcess(PROCESS_TERMINATE | PROCESS_QUERY_INFORMATION, FALSE, (DWORD)pid);
5010 if (hProc == NULL || hProc == INVALID_HANDLE_VALUE) {
5011 if (GetLastError() == ERROR_INVALID_PARAMETER) {
5021 if (!GetExitCodeProcess(hProc, &status)) {
5022 errno = map_errno(GetLastError());
5025 else if (status == STILL_ACTIVE) {
5026 if (!TerminateProcess(hProc, 0)) {
5053wlink(
const WCHAR *from,
const WCHAR *to)
5055 if (!CreateHardLinkW(to, from, NULL)) {
5056 errno = map_errno(GetLastError());
5065rb_w32_ulink(
const char *from,
const char *to)
5071 if (!(wfrom = utf8_to_wstr(from, NULL)))
5073 if (!(wto = utf8_to_wstr(to, NULL))) {
5077 ret = wlink(wfrom, wto);
5085link(
const char *from,
const char *to)
5091 if (!(wfrom = filecp_to_wstr(from, NULL)))
5093 if (!(wto = filecp_to_wstr(to, NULL))) {
5097 ret = wlink(wfrom, wto);
5104#ifndef FILE_DEVICE_FILE_SYSTEM
5105# define FILE_DEVICE_FILE_SYSTEM 0x00000009
5107#ifndef FSCTL_GET_REPARSE_POINT
5108# define FSCTL_GET_REPARSE_POINT ((0x9<<16)|(42<<2))
5110#ifndef IO_REPARSE_TAG_SYMLINK
5111# define IO_REPARSE_TAG_SYMLINK 0xA000000CL
5122 f = open_special(path, 0, FILE_FLAG_OPEN_REPARSE_POINT);
5123 if (f == INVALID_HANDLE_VALUE) {
5124 return GetLastError();
5127 if (!DeviceIoControl(f, FSCTL_GET_REPARSE_POINT, NULL, 0,
5128 rp, size, &ret, NULL)) {
5131 else if (rp->ReparseTag != IO_REPARSE_TAG_SYMLINK &&
5132 rp->ReparseTag != IO_REPARSE_TAG_MOUNT_POINT) {
5133 e = ERROR_INVALID_PARAMETER;
5141rb_w32_reparse_symlink_p(
const WCHAR *path)
5149 e = rb_w32_read_reparse_point(path, rp,
sizeof(rbuf), &wbuf, &
len);
5150 if (e == ERROR_MORE_DATA) {
5151 size_t size = rb_w32_reparse_buffer_size(
len + 1);
5153 e = rb_w32_read_reparse_point(path, rp, size, &wbuf, &
len);
5158 case ERROR_MORE_DATA:
5167 size_t bufsize, WCHAR **result, DWORD *
len)
5169 int e = reparse_symlink(path, rp, bufsize);
5172 if (!e || e == ERROR_MORE_DATA) {
5174 if (rp->ReparseTag == IO_REPARSE_TAG_SYMLINK) {
5175 name = ((
char *)rp->SymbolicLinkReparseBuffer.PathBuffer +
5176 rp->SymbolicLinkReparseBuffer.PrintNameOffset);
5177 ret = rp->SymbolicLinkReparseBuffer.PrintNameLength;
5178 *
len = ret /
sizeof(WCHAR);
5180 else if (rp->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT) {
5181 static const WCHAR volume[] = L
"Volume{";
5183 name = ((
char *)rp->MountPointReparseBuffer.PathBuffer +
5184 rp->MountPointReparseBuffer.SubstituteNameOffset +
5185 volume_prefix_len *
sizeof(WCHAR));
5186 ret = rp->MountPointReparseBuffer.SubstituteNameLength;
5187 *
len = ret /
sizeof(WCHAR);
5188 ret -= volume_prefix_len *
sizeof(WCHAR);
5189 if (ret >
sizeof(volume) - 1 *
sizeof(WCHAR) &&
5190 memcmp(name, volume,
sizeof(volume) - 1 *
sizeof(WCHAR)) == 0)
5198 if ((
char *)name + ret +
sizeof(WCHAR) > (
char *)rp + bufsize)
5202 ((WCHAR *)name)[ret/
sizeof(WCHAR)] = L
'\0';
5203 translate_wchar(name, L
'\\', L
'/');
5213w32_readlink(UINT cp,
const char *path,
char *buf,
size_t bufsize)
5215 VALUE rp_buf, rp_buf_bigger = 0;
5216 DWORD
len = MultiByteToWideChar(cp, 0, path, -1, NULL, 0);
5217 size_t size = rb_w32_reparse_buffer_size(bufsize);
5219 WCHAR *wpath =
ALLOCV(rp_buf,
sizeof(WCHAR) *
len + size);
5224 MultiByteToWideChar(cp, 0, path, -1, wpath,
len);
5225 e = rb_w32_read_reparse_point(wpath, rp, size, &wname, &
len);
5226 if (e == ERROR_MORE_DATA) {
5227 size = rb_w32_reparse_buffer_size(
len + 1);
5228 rp =
ALLOCV(rp_buf_bigger, size);
5229 e = rb_w32_read_reparse_point(wpath, rp, size, &wname, &
len);
5234 errno = e == -1 ? EINVAL : map_errno(e);
5237 len = lstrlenW(wname);
5238 ret = WideCharToMultiByte(cp, 0, wname,
len, buf, bufsize, NULL, NULL);
5249rb_w32_ureadlink(
const char *path,
char *buf,
size_t bufsize)
5251 return w32_readlink(CP_UTF8, path, buf, bufsize);
5256readlink(
const char *path,
char *buf,
size_t bufsize)
5258 return w32_readlink(filecp(), path, buf, bufsize);
5261#ifndef SYMBOLIC_LINK_FLAG_DIRECTORY
5262#define SYMBOLIC_LINK_FLAG_DIRECTORY (0x1)
5264#ifndef SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE
5265#define SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE (0x2)
5270w32_symlink(UINT cp,
const char *src,
const char *link)
5272 int atts, len1, len2;
5274 WCHAR *wsrc, *wlink;
5279 static DWORD create_flag = SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
5289 len1 = MultiByteToWideChar(cp, 0, src, -1, NULL, 0);
5290 len2 = MultiByteToWideChar(cp, 0, link, -1, NULL, 0);
5291 wsrc =
ALLOCV_N(WCHAR, buf, len1+len2);
5292 wlink = wsrc + len1;
5293 MultiByteToWideChar(cp, 0, src, -1, wsrc, len1);
5294 MultiByteToWideChar(cp, 0, link, -1, wlink, len2);
5295 translate_wchar(wsrc, L
'/', L
'\\');
5297 atts = GetFileAttributesW(wsrc);
5298 if (atts != -1 && atts & FILE_ATTRIBUTE_DIRECTORY)
5299 flag = SYMBOLIC_LINK_FLAG_DIRECTORY;
5300 ret = CreateSymbolicLinkW(wlink, wsrc, flag |= create_flag);
5302 (e = GetLastError()) == ERROR_INVALID_PARAMETER &&
5303 (flag & SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE)) {
5305 flag &= ~SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
5306 ret = CreateSymbolicLinkW(wlink, wsrc, flag);
5307 if (!ret) e = GetLastError();
5312 errno = map_errno(e);
5320rb_w32_usymlink(
const char *src,
const char *link)
5322 return w32_symlink(CP_UTF8, src, link);
5327symlink(
const char *src,
const char *link)
5329 return w32_symlink(filecp(), src, link);
5336 return waitpid(-1, status, 0);
5341w32_getenv(
const char *name, UINT cp)
5343 WCHAR *wenvarea, *wenv;
5344 int len = strlen(name);
5345 char *env, *found = NULL;
5348 if (
len == 0)
return NULL;
5353 return getenv(name);
5356 thread_exclusive(uenvarea) {
5361 wenvarea = GetEnvironmentStringsW();
5363 map_errno(GetLastError());
5366 for (wenv = wenvarea, wlen = 1; *wenv; wenv += lstrlenW(wenv) + 1)
5367 wlen += lstrlenW(wenv) + 1;
5368 uenvarea = wstr_to_mbstr(cp, wenvarea, wlen, NULL);
5369 FreeEnvironmentStringsW(wenvarea);
5373 for (env = uenvarea; *env; env += strlen(env) + 1) {
5374 if (strncasecmp(env, name,
len) == 0 && *(env +
len) ==
'=') {
5375 found = env +
len + 1;
5386rb_w32_ugetenv(
const char *name)
5388 return w32_getenv(name, CP_UTF8);
5393rb_w32_getenv(
const char *name)
5395 return w32_getenv(name, CP_ACP);
5400get_attr_vsn(
const WCHAR *path, DWORD *atts, DWORD *vsn)
5402 BY_HANDLE_FILE_INFORMATION st = {0};
5404 HANDLE h = open_special(path, 0, FILE_FLAG_OPEN_REPARSE_POINT);
5406 if (h == INVALID_HANDLE_VALUE) {
5411 if (!GetFileInformationByHandle(h, &st)) {
5416 *atts = st.dwFileAttributes;
5417 *vsn = st.dwVolumeSerialNumber;
5425wrename(
const WCHAR *oldpath,
const WCHAR *newpath)
5428 DWORD oldatts = 0, newatts = (DWORD)-1;
5429 DWORD oldvsn = 0, newvsn = 0, e;
5431 e = get_attr_vsn(oldpath, &oldatts, &oldvsn);
5433 errno = map_errno(e);
5436 if (oldatts & FILE_ATTRIBUTE_REPARSE_POINT) {
5437 HANDLE fh = open_special(oldpath, 0, 0);
5438 if (fh == INVALID_HANDLE_VALUE) {
5440 if (e == ERROR_CANT_RESOLVE_FILENAME) {
5447 get_attr_vsn(newpath, &newatts, &newvsn);
5450 if (newatts != (DWORD)-1 && newatts & FILE_ATTRIBUTE_READONLY)
5451 SetFileAttributesW(newpath, newatts & ~ FILE_ATTRIBUTE_READONLY);
5453 if (!MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED))
5457 DWORD e = GetLastError();
5458 if ((e == ERROR_ACCESS_DENIED) && (oldatts & FILE_ATTRIBUTE_DIRECTORY) &&
5462 errno = map_errno(e);
5465 SetFileAttributesW(newpath, oldatts);
5473rb_w32_urename(
const char *from,
const char *to)
5479 if (!(wfrom = utf8_to_wstr(from, NULL)))
5481 if (!(wto = utf8_to_wstr(to, NULL))) {
5485 ret = wrename(wfrom, wto);
5493rb_w32_rename(
const char *from,
const char *to)
5499 if (!(wfrom = filecp_to_wstr(from, NULL)))
5501 if (!(wto = filecp_to_wstr(to, NULL))) {
5505 ret = wrename(wfrom, wto);
5513isUNCRoot(
const WCHAR *path)
5515 if (path[0] == L
'\\' && path[1] == L
'\\') {
5516 const WCHAR *p = path + 2;
5517 if (p[0] == L
'?' && p[1] == L
'\\') {
5525 for (p++; *p; p++) {
5529 if (!p[0] || !p[1] || (p[1] == L
'.' && !p[2]))
5536#define COPY_STAT(src, dest, size_cast) do { \
5537 (dest).st_dev = (src).st_dev; \
5538 (dest).st_ino = (src).st_ino; \
5539 (dest).st_mode = (src).st_mode; \
5540 (dest).st_nlink = (src).st_nlink; \
5541 (dest).st_uid = (src).st_uid; \
5542 (dest).st_gid = (src).st_gid; \
5543 (dest).st_rdev = (src).st_rdev; \
5544 (dest).st_size = size_cast(src).st_size; \
5545 (dest).st_atime = (src).st_atime; \
5546 (dest).st_mtime = (src).st_mtime; \
5547 (dest).st_ctime = (src).st_ctime; \
5550static time_t filetime_to_unixtime(
const FILETIME *ft);
5551static long filetime_to_nsec(
const FILETIME *ft);
5552static WCHAR *name_for_stat(WCHAR *buf,
const WCHAR *path);
5553static DWORD stati128_handle(HANDLE h,
struct stati128 *st);
5558rb_w32_fstat(
int fd,
struct stat *st)
5560 BY_HANDLE_FILE_INFORMATION info;
5561 int ret = fstat(fd, st);
5563 if (ret)
return ret;
5564 if (GetEnvironmentVariableW(L
"TZ", NULL, 0) == 0 && GetLastError() == ERROR_ENVVAR_NOT_FOUND)
return ret;
5565 if (GetFileInformationByHandle((HANDLE)_get_osfhandle(fd), &info)) {
5566 st->st_atime = filetime_to_unixtime(&info.ftLastAccessTime);
5567 st->st_mtime = filetime_to_unixtime(&info.ftLastWriteTime);
5568 st->st_ctime = filetime_to_unixtime(&info.ftCreationTime);
5575rb_w32_fstati128(
int fd,
struct stati128 *st)
5578 int ret = fstat(fd, &tmp);
5580 if (ret)
return ret;
5581 COPY_STAT(tmp, *st, +);
5582 stati128_handle((HANDLE)_get_osfhandle(fd), st);
5586#if !defined FILE_INVALID_FILE_ID && !defined __MINGW32__
5588 BYTE Identifier[16];
5592#if !defined(_WIN32_WINNT_WIN8) || _WIN32_WINNT < 0x602
5593#define FileIdInfo 0x12
5604 return GetFileInformationByHandleEx(h, FileIdInfo,
id,
sizeof(*
id));
5609stati128_handle(HANDLE h,
struct stati128 *st)
5611 BY_HANDLE_FILE_INFORMATION info;
5612 DWORD attr = (DWORD)-1;
5614 if (GetFileInformationByHandle(h, &info)) {
5616 st->st_size = ((__int64)info.nFileSizeHigh << 32) | info.nFileSizeLow;
5617 st->st_atime = filetime_to_unixtime(&info.ftLastAccessTime);
5618 st->st_atimensec = filetime_to_nsec(&info.ftLastAccessTime);
5619 st->st_mtime = filetime_to_unixtime(&info.ftLastWriteTime);
5620 st->st_mtimensec = filetime_to_nsec(&info.ftLastWriteTime);
5621 st->st_ctime = filetime_to_unixtime(&info.ftCreationTime);
5622 st->st_ctimensec = filetime_to_nsec(&info.ftCreationTime);
5623 st->st_nlink = info.nNumberOfLinks;
5624 attr = info.dwFileAttributes;
5625 if (get_ino(h, &fii)) {
5626 st->st_ino = *((
unsigned __int64 *)&fii.FileId);
5627 st->st_inohigh = *((__int64 *)&fii.FileId + 1);
5630 st->st_ino = ((__int64)info.nFileIndexHigh << 32) | info.nFileIndexLow;
5639filetime_to_unixtime(
const FILETIME *ft)
5642 time_t t = filetime_split(ft, &subsec);
5644 if (t < 0)
return 0;
5650filetime_to_nsec(
const FILETIME *ft)
5653 tmp.LowPart = ft->dwLowDateTime;
5654 tmp.HighPart = ft->dwHighDateTime;
5655 return (
long)(tmp.QuadPart % 10000000) * 100;
5660fileattr_to_unixmode(DWORD attr,
const WCHAR *path,
unsigned mode)
5662 if (attr & FILE_ATTRIBUTE_READONLY) {
5666 mode |= S_IREAD | S_IWRITE | S_IWUSR;
5669 if (mode & S_IFMT) {
5672 else if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
5676 else if (attr & FILE_ATTRIBUTE_DIRECTORY) {
5677 mode |= S_IFDIR | S_IEXEC;
5683 if (path && (mode & S_IFREG)) {
5684 const WCHAR *end = path + lstrlenW(path);
5685 while (path < end) {
5686 end = CharPrevW(path, end);
5688 if ((_wcsicmp(end, L
".bat") == 0) ||
5689 (_wcsicmp(end, L
".cmd") == 0) ||
5690 (_wcsicmp(end, L
".com") == 0) ||
5691 (_wcsicmp(end, L
".exe") == 0)) {
5696 if (!iswalnum(*end))
break;
5700 mode |= (mode & 0500) >> 3;
5701 mode |= (mode & 0500) >> 6;
5708check_valid_dir(
const WCHAR *path)
5710 WIN32_FIND_DATAW fd;
5712 WCHAR full[PATH_MAX];
5717 if (!(p = wcsstr(path, L
"...")))
5719 q = p + wcsspn(p, L
".");
5720 if ((p == path || wcschr(L
":/\\", *(p - 1))) &&
5721 (!*q || wcschr(L
":/\\", *q))) {
5728 DWORD
len = GetFullPathNameW(path, numberof(full), full, NULL);
5729 if (
len >= numberof(full)) {
5730 WCHAR *fullpath = malloc(
len *
sizeof(WCHAR));
5731 if (!fullpath)
return -1;
5732 len = GetFullPathNameW(path,
len, fullpath, NULL);
5737 errno = map_errno(GetLastError());
5740 if (
len == 3 && full[1] == L
':' && GetDriveTypeW(full) != DRIVE_NO_ROOT_DIR)
5743 fh = open_dir_handle(path, &fd);
5744 if (fh == INVALID_HANDLE_VALUE)
5752stat_by_find(
const WCHAR *path,
struct stati128 *st)
5755 WIN32_FIND_DATAW wfd;
5758 h = FindFirstFileW(path, &wfd);
5759 if (h == INVALID_HANDLE_VALUE) {
5760 errno = map_errno(GetLastError());
5764 st->st_mode = fileattr_to_unixmode(wfd.dwFileAttributes, path, 0);
5765 st->st_atime = filetime_to_unixtime(&wfd.ftLastAccessTime);
5766 st->st_atimensec = filetime_to_nsec(&wfd.ftLastAccessTime);
5767 st->st_mtime = filetime_to_unixtime(&wfd.ftLastWriteTime);
5768 st->st_mtimensec = filetime_to_nsec(&wfd.ftLastWriteTime);
5769 st->st_ctime = filetime_to_unixtime(&wfd.ftCreationTime);
5770 st->st_ctimensec = filetime_to_nsec(&wfd.ftCreationTime);
5771 st->st_size = ((__int64)wfd.nFileSizeHigh << 32) | wfd.nFileSizeLow;
5778path_drive(
const WCHAR *path)
5780 if (path[0] && path[1] == L
':') {
5781 if (iswalpha(path[0]))
return towupper(path[0]) - L
'A';
5782 return (
int)path[0];
5784 return _getdrive() - 1;
5789winnt_stat(
const WCHAR *path,
struct stati128 *st, BOOL lstat)
5791 DWORD flags = lstat ? FILE_FLAG_OPEN_REPARSE_POINT : 0;
5793 WCHAR *finalname = 0;
5796 memset(st, 0,
sizeof(*st));
5797 f = open_special(path, 0, flags);
5798 open_error = GetLastError();
5799 if (f == INVALID_HANDLE_VALUE && !lstat) {
5801 FILE_ATTRIBUTE_TAG_INFO attr_info;
5804 f = open_special(path, 0, FILE_FLAG_OPEN_REPARSE_POINT);
5805 e = GetFileInformationByHandleEx(f, FileAttributeTagInfo,
5806 &attr_info,
sizeof(attr_info));
5807 if (!e || attr_info.ReparseTag != IO_REPARSE_TAG_AF_UNIX) {
5809 f = INVALID_HANDLE_VALUE;
5812 if (f != INVALID_HANDLE_VALUE) {
5813 DWORD attr = stati128_handle(f, st);
5815 switch (GetFileType(f)) {
5816 case FILE_TYPE_CHAR:
5819 case FILE_TYPE_PIPE:
5823 if (attr & FILE_ATTRIBUTE_DIRECTORY) {
5824 if (check_valid_dir(path))
return -1;
5826 if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
5827 FILE_ATTRIBUTE_TAG_INFO attr_info;
5830 e = GetFileInformationByHandleEx(f, FileAttributeTagInfo,
5831 &attr_info,
sizeof(attr_info));
5832 if (e && attr_info.ReparseTag == IO_REPARSE_TAG_AF_UNIX) {
5836 else if (rb_w32_reparse_symlink_p(path)) {
5839 mode |= S_IFLNK | S_IEXEC;
5842 mode |= S_IFDIR | S_IEXEC;
5846 const DWORD
len = get_handle_pathname(f, &finalname, 0);
5848 st->st_mode = fileattr_to_unixmode(attr, path, mode);
5851 if (wcsncmp(path, namespace_prefix, numberof(namespace_prefix)) == 0)
5852 path += numberof(namespace_prefix);
5856 if ((open_error == ERROR_FILE_NOT_FOUND) || (open_error == ERROR_INVALID_NAME)
5857 || (open_error == ERROR_PATH_NOT_FOUND || (open_error == ERROR_BAD_NETPATH))) {
5858 errno = map_errno(open_error);
5862 if (stat_by_find(path, st))
return -1;
5865 st->st_dev = st->st_rdev = path_drive(path);
5866 if (finalname) free(finalname);
5873rb_w32_stat(
const char *path,
struct stat *st)
5877 if (w32_stati128(path, &tmp, filecp(), FALSE))
return -1;
5878 COPY_STAT(tmp, *st, (_off_t));
5884wstati128(
const WCHAR *path,
struct stati128 *st, BOOL lstat)
5894 size = lstrlenW(path) + 2;
5896 if (!(path = name_for_stat(buf1, path)))
5898 ret = winnt_stat(path, st, lstat);
5907name_for_stat(WCHAR *buf1,
const WCHAR *path)
5913 for (p = path, s = buf1; *p; p++, s++) {
5921 if (!
len || L
'\"' == *(--s)) {
5925 end = buf1 +
len - 1;
5927 if (isUNCRoot(buf1)) {
5930 else if (*end != L
'\\')
5931 lstrcatW(buf1, L
"\\");
5933 else if (*end == L
'\\' || (buf1 + 1 == end && *end == L
':'))
5934 lstrcatW(buf1, L
".");
5941rb_w32_ustati128(
const char *path,
struct stati128 *st)
5943 return w32_stati128(path, st, CP_UTF8, FALSE);
5948rb_w32_stati128(
const char *path,
struct stati128 *st)
5950 return w32_stati128(path, st, filecp(), FALSE);
5955w32_stati128(
const char *path,
struct stati128 *st, UINT cp, BOOL lstat)
5960 if (!(wpath = mbstr_to_wstr(cp, path, -1, NULL)))
5962 ret = wstati128(wpath, st, lstat);
5969rb_w32_ulstati128(
const char *path,
struct stati128 *st)
5971 return w32_stati128(path, st, CP_UTF8, TRUE);
5976rb_w32_lstati128(
const char *path,
struct stati128 *st)
5978 return w32_stati128(path, st, filecp(), TRUE);
5983rb_w32_lseek(
int fd, rb_off_t ofs,
int whence)
5985 SOCKET sock = TO_SOCKET(fd);
5986 if (is_socket(sock) || is_pipe(sock)) {
5990 return _lseeki64(fd, ofs, whence);
5995w32_access(
const char *path,
int mode, UINT cp)
5998 if (w32_stati128(path, &stat, cp, FALSE) != 0)
6001 if ((stat.st_mode & mode) != mode) {
6010rb_w32_access(
const char *path,
int mode)
6012 return w32_access(path, mode, filecp());
6017rb_w32_uaccess(
const char *path,
int mode)
6019 return w32_access(path, mode, CP_UTF8);
6024rb_chsize(HANDLE h, rb_off_t size)
6026 long upos, lpos, usize, lsize;
6030 if ((lpos = SetFilePointer(h, 0, (upos = 0, &upos), SEEK_CUR)) == -1L &&
6031 (e = GetLastError())) {
6032 errno = map_errno(e);
6035 usize = (long)(size >> 32);
6037 if (SetFilePointer(h, lsize, &usize, SEEK_SET) == (DWORD)-1L &&
6038 (e = GetLastError())) {
6039 errno = map_errno(e);
6041 else if (!SetEndOfFile(h)) {
6042 errno = map_errno(GetLastError());
6047 SetFilePointer(h, lpos, &upos, SEEK_SET);
6053w32_truncate(
const char *path, rb_off_t length, UINT cp)
6059 if (!(wpath = mbstr_to_wstr(cp, path, -1, NULL)))
6061 h = CreateFileW(wpath, GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
6062 if (h == INVALID_HANDLE_VALUE) {
6063 errno = map_errno(GetLastError());
6068 ret = rb_chsize(h, length);
6075rb_w32_utruncate(
const char *path, rb_off_t length)
6077 return w32_truncate(path, length, CP_UTF8);
6082rb_w32_truncate(
const char *path, rb_off_t length)
6084 return w32_truncate(path, length, filecp());
6089rb_w32_ftruncate(
int fd, rb_off_t length)
6093 h = (HANDLE)_get_osfhandle(fd);
6094 if (h == (HANDLE)-1)
return -1;
6095 return rb_chsize(h, length);
6100filetime_to_clock(FILETIME *ft)
6102 __int64 qw = ft->dwHighDateTime;
6104 qw |= ft->dwLowDateTime;
6111rb_w32_times(
struct tms *tmbuf)
6113 FILETIME create, exit, kernel, user;
6115 if (GetProcessTimes(GetCurrentProcess(),&create, &exit, &kernel, &user)) {
6116 tmbuf->tms_utime = filetime_to_clock(&user);
6117 tmbuf->tms_stime = filetime_to_clock(&kernel);
6118 tmbuf->tms_cutime = 0;
6119 tmbuf->tms_cstime = 0;
6122 tmbuf->tms_utime = clock();
6123 tmbuf->tms_stime = 0;
6124 tmbuf->tms_cutime = 0;
6125 tmbuf->tms_cstime = 0;
6132#define yield_once() Sleep(0)
6133#define yield_until(condition) do yield_once(); while (!(condition))
6142 uintptr_t (*func)(uintptr_t self,
int argc, uintptr_t* argv);
6150call_asynchronous(PVOID argp)
6154 arg->stackaddr = &argp;
6155 ret = (DWORD)arg->func(arg->self, arg->argc, arg->argv);
6156 arg->errnum =
errno;
6162rb_w32_asynchronize(asynchronous_func_t func, uintptr_t self,
6163 int argc, uintptr_t* argv, uintptr_t intrval)
6166 BOOL interrupted = FALSE;
6172 arg.stackaddr = NULL;
6179 thr = CreateThread(NULL, 0, call_asynchronous, &arg, 0, &val);
6182 yield_until(arg.stackaddr);
6184 if (rb_w32_wait_events_blocking(&thr, 1, INFINITE) != WAIT_OBJECT_0) {
6187 if (TerminateThread(thr, intrval)) {
6192 GetExitCodeThread(thr, &val);
6197 MEMORY_BASIC_INFORMATION m;
6199 memset(&m, 0,
sizeof(m));
6200 if (!VirtualQuery(arg.stackaddr, &m,
sizeof(m))) {
6201 Debug(fprintf(stderr,
"couldn't get stack base:%p:%d\n",
6202 arg.stackaddr, GetLastError()));
6204 else if (!VirtualFree(m.AllocationBase, 0, MEM_RELEASE)) {
6205 Debug(fprintf(stderr,
"couldn't release stack:%p:%d\n",
6206 m.AllocationBase, GetLastError()));
6217 rb_fatal(
"failed to launch waiter thread:%ld", GetLastError());
6225rb_w32_get_environ(
void)
6227 WCHAR *envtop, *env;
6228 char **myenvtop, **myenv;
6241 envtop = GetEnvironmentStringsW();
6242 for (env = envtop, num = 0; *env; env += lstrlenW(env) + 1)
6243 if (*env !=
'=') num++;
6245 myenvtop = (
char **)malloc(
sizeof(
char *) * (num + 1));
6246 for (env = envtop, myenv = myenvtop; *env; env += lstrlenW(env) + 1) {
6248 if (!(*myenv = wstr_to_utf8(env, NULL))) {
6255 FreeEnvironmentStringsW(envtop);
6262rb_w32_free_environ(
char **env)
6266 while (*t) free(*t++);
6274 return GetCurrentProcessId();
6282 typedef long (WINAPI query_func)(HANDLE, int,
void *, ULONG, ULONG *);
6283 static query_func *pNtQueryInformationProcess = (query_func *)-1;
6286 if (pNtQueryInformationProcess == (query_func *)-1)
6287 pNtQueryInformationProcess = (query_func *)get_proc_address(
"ntdll.dll",
"NtQueryInformationProcess", NULL);
6288 if (pNtQueryInformationProcess) {
6291 void* PebBaseAddress;
6292 uintptr_t AffinityMask;
6293 uintptr_t BasePriority;
6294 uintptr_t UniqueProcessId;
6295 uintptr_t ParentProcessId;
6298 long ret = pNtQueryInformationProcess(GetCurrentProcess(), 0, &pbi,
sizeof(pbi), &
len);
6300 ppid = pbi.ParentProcessId;
6307STATIC_ASSERT(std_handle, (STD_OUTPUT_HANDLE-STD_INPUT_HANDLE)==(STD_ERROR_HANDLE-STD_OUTPUT_HANDLE));
6310#define set_new_std_handle(newfd, handle) do { \
6311 if ((unsigned)(newfd) > 2) break; \
6312 SetStdHandle(STD_INPUT_HANDLE+(STD_OUTPUT_HANDLE-STD_INPUT_HANDLE)*(newfd), \
6315#define set_new_std_fd(newfd) set_new_std_handle(newfd, (HANDLE)rb_w32_get_osfhandle(newfd))
6319rb_w32_dup2(
int oldfd,
int newfd)
6323 if (oldfd == newfd)
return newfd;
6324 ret = dup2(oldfd, newfd);
6325 if (ret < 0)
return ret;
6326 set_new_std_fd(newfd);
6332rb_w32_uopen(
const char *file,
int oflag, ...)
6339 va_start(arg, oflag);
6340 pmode = va_arg(arg,
int);
6343 if (!(wfile = utf8_to_wstr(file, NULL)))
6345 ret = w32_wopen(wfile, oflag, pmode);
6352check_if_wdir(
const WCHAR *wfile)
6354 DWORD attr = GetFileAttributesW(wfile);
6355 if (attr == (DWORD)-1L ||
6356 !(attr & FILE_ATTRIBUTE_DIRECTORY) ||
6357 check_valid_dir(wfile)) {
6366rb_w32_open(
const char *file,
int oflag, ...)
6373 va_start(arg, oflag);
6374 pmode = va_arg(arg,
int);
6377 if (!(wfile = filecp_to_wstr(file, NULL)))
6379 ret = w32_wopen(wfile, oflag, pmode);
6386rb_w32_wopen(
const WCHAR *file,
int oflag, ...)
6390 if (oflag & O_CREAT) {
6392 va_start(arg, oflag);
6393 pmode = va_arg(arg,
int);
6397 return w32_wopen(file, oflag, pmode);
6401w32_wopen(
const WCHAR *file,
int oflag,
int pmode)
6407 DWORD attr = FILE_ATTRIBUTE_NORMAL;
6408 SECURITY_ATTRIBUTES sec;
6412 share_delete = oflag & O_SHARE_DELETE ? FILE_SHARE_DELETE : 0;
6413 oflag &= ~O_SHARE_DELETE;
6414 if ((oflag & O_TEXT) || !(oflag & O_BINARY)) {
6415 fd = _wopen(file, oflag, pmode);
6419 check_if_wdir(file);
6422 errno = map_errno(GetLastError());
6429 sec.nLength =
sizeof(sec);
6430 sec.lpSecurityDescriptor = NULL;
6431 if (oflag & O_NOINHERIT) {
6432 sec.bInheritHandle = FALSE;
6433 flags |= FNOINHERIT;
6436 sec.bInheritHandle = TRUE;
6438 oflag &= ~O_NOINHERIT;
6441 oflag &= ~(O_BINARY | O_TEXT);
6443 switch (oflag & (O_RDWR | O_RDONLY | O_WRONLY)) {
6445 access = GENERIC_READ | GENERIC_WRITE;
6448 access = GENERIC_READ;
6451 access = GENERIC_WRITE;
6457 oflag &= ~(O_RDWR | O_RDONLY | O_WRONLY);
6459 switch (oflag & (O_CREAT | O_EXCL | O_TRUNC)) {
6461 create = OPEN_ALWAYS;
6465 create = OPEN_EXISTING;
6467 case O_CREAT | O_EXCL:
6468 case O_CREAT | O_EXCL | O_TRUNC:
6469 create = CREATE_NEW;
6472 case O_TRUNC | O_EXCL:
6473 create = TRUNCATE_EXISTING;
6475 case O_CREAT | O_TRUNC:
6476 create = CREATE_ALWAYS;
6482 if (oflag & O_CREAT) {
6484 if (!(pmode & S_IWRITE))
6485 attr = FILE_ATTRIBUTE_READONLY;
6487 oflag &= ~(O_CREAT | O_EXCL | O_TRUNC);
6489 if (oflag & O_TEMPORARY) {
6490 attr |= FILE_FLAG_DELETE_ON_CLOSE;
6493 oflag &= ~O_TEMPORARY;
6495 if (oflag & _O_SHORT_LIVED)
6496 attr |= FILE_ATTRIBUTE_TEMPORARY;
6497 oflag &= ~_O_SHORT_LIVED;
6499 switch (oflag & (O_SEQUENTIAL | O_RANDOM)) {
6503 attr |= FILE_FLAG_SEQUENTIAL_SCAN;
6506 attr |= FILE_FLAG_RANDOM_ACCESS;
6512 oflag &= ~(O_SEQUENTIAL | O_RANDOM);
6514 if (oflag & ~O_APPEND) {
6521 h = CreateFile(
"NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
6522 fd = _open_osfhandle((intptr_t)h, 0);
6530 rb_acrt_lowio_lock_fh(fd);
6531 _set_osfhnd(fd, (intptr_t)INVALID_HANDLE_VALUE);
6532 _set_osflags(fd, 0);
6534 h = CreateFileW(file, access, FILE_SHARE_READ | FILE_SHARE_WRITE | share_delete, &sec, create, attr, NULL);
6535 if (h == INVALID_HANDLE_VALUE) {
6536 DWORD e = GetLastError();
6537 if (e != ERROR_ACCESS_DENIED || !check_if_wdir(file))
6538 errno = map_errno(e);
6539 rb_acrt_lowio_unlock_fh(fd);
6544 switch (GetFileType(h)) {
6545 case FILE_TYPE_CHAR:
6548 case FILE_TYPE_PIPE:
6551 case FILE_TYPE_UNKNOWN:
6552 errno = map_errno(GetLastError());
6554 rb_acrt_lowio_unlock_fh(fd);
6558 if (!(flags & (FDEV | FPIPE)) && (oflag & O_APPEND))
6561 _set_osfhnd(fd, (intptr_t)h);
6562 _set_osflags(fd, flags | FOPEN);
6564 rb_acrt_lowio_unlock_fh(fd);
6574rb_w32_fclose(
FILE *fp)
6576 int fd = fileno(fp);
6577 SOCKET sock = TO_SOCKET(fd);
6578 int save_errno =
errno;
6580 if (fflush(fp))
return -1;
6581 if (!is_socket(sock)) {
6582 UnlockFile((HANDLE)sock, 0, 0, LK_LEN, LK_LEN);
6585 _set_osfhnd(fd, (SOCKET)INVALID_HANDLE_VALUE);
6588 if (closesocket(sock) == SOCKET_ERROR) {
6589 errno = map_errno(WSAGetLastError());
6597rb_w32_pipe(
int fds[2])
6599 static long serial = 0;
6600 static const char prefix[] =
"\\\\.\\pipe\\ruby";
6602 width_of_prefix = (int)
sizeof(prefix) - 1,
6603 width_of_pid = (int)
sizeof(rb_pid_t) * 2,
6604 width_of_serial = (int)
sizeof(serial) * 2,
6605 width_of_ids = width_of_pid + 1 + width_of_serial + 1
6607 char name[
sizeof(prefix) + width_of_ids];
6608 SECURITY_ATTRIBUTES sec;
6609 HANDLE hRead, hWrite, h;
6610 int fdRead, fdWrite;
6613 memcpy(name, prefix, width_of_prefix);
6614 snprintf(name + width_of_prefix, width_of_ids,
"%.*"PRI_PIDT_PREFIX"x-%.*lx",
6615 width_of_pid, rb_w32_getpid(), width_of_serial, InterlockedIncrement(&serial)-1);
6617 sec.nLength =
sizeof(sec);
6618 sec.lpSecurityDescriptor = NULL;
6619 sec.bInheritHandle = FALSE;
6622 hRead = CreateNamedPipe(name, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
6623 0, 2, 65536, 65536, 0, &sec);
6625 if (hRead == INVALID_HANDLE_VALUE) {
6626 DWORD err = GetLastError();
6627 if (err == ERROR_PIPE_BUSY)
6630 errno = map_errno(GetLastError());
6635 hWrite = CreateFile(name, GENERIC_READ | GENERIC_WRITE, 0, &sec,
6636 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
6638 if (hWrite == INVALID_HANDLE_VALUE) {
6639 errno = map_errno(GetLastError());
6646 h = CreateFile(
"NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
6647 fdRead = _open_osfhandle((intptr_t)h, 0);
6651 CloseHandle(hWrite);
6657 rb_acrt_lowio_lock_fh(fdRead);
6658 _set_osfhnd(fdRead, (intptr_t)hRead);
6659 _set_osflags(fdRead, FOPEN | FPIPE | FNOINHERIT);
6660 rb_acrt_lowio_unlock_fh(fdRead);
6666 h = CreateFile(
"NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
6667 fdWrite = _open_osfhandle((intptr_t)h, 0);
6669 if (fdWrite == -1) {
6671 CloseHandle(hWrite);
6675 rb_acrt_lowio_lock_fh(fdWrite);
6676 _set_osfhnd(fdWrite, (intptr_t)hWrite);
6677 _set_osflags(fdWrite, FOPEN | FPIPE | FNOINHERIT);
6678 rb_acrt_lowio_unlock_fh(fdWrite);
6681 rb_w32_close(fdRead);
6693console_emulator_p(
void)
6698 const void *
const func = WriteConsoleW;
6700 MEMORY_BASIC_INFORMATION m;
6702 memset(&m, 0,
sizeof(m));
6703 if (!VirtualQuery(func, &m,
sizeof(m))) {
6706 k = GetModuleHandle(
"kernel32.dll");
6707 if (!k)
return FALSE;
6708 return (HMODULE)m.AllocationBase != k;
6714constat_handle(HANDLE h)
6718 thread_exclusive(conlist) {
6720 if (console_emulator_p()) {
6721 conlist = conlist_disabled;
6724 conlist = st_init_numtable();
6725 install_vm_exit_handler();
6727 else if (conlist == conlist_disabled) {
6730 if (st_lookup(conlist, (st_data_t)h, &data)) {
6734 CONSOLE_SCREEN_BUFFER_INFO csbi;
6736 p->vt100.state = constat_init;
6737 p->vt100.attr = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED;
6738 p->vt100.reverse = 0;
6739 p->vt100.saved.X = p->vt100.saved.Y = 0;
6740 if (GetConsoleScreenBufferInfo(h, &csbi)) {
6741 p->vt100.attr = csbi.wAttributes;
6743 st_insert(conlist, (st_data_t)h, (st_data_t)p);
6751constat_reset(HANDLE h)
6755 thread_exclusive(conlist) {
6756 if (!conlist || conlist == conlist_disabled)
continue;
6757 if (!st_lookup(conlist, (st_data_t)h, &data))
continue;
6759 p->vt100.state = constat_init;
6763#define FOREGROUND_MASK (FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY)
6764#define BACKGROUND_MASK (BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_INTENSITY)
6766#define constat_attr_color_reverse(attr) \
6767 ((attr) & ~(FOREGROUND_MASK | BACKGROUND_MASK)) | \
6768 (((attr) & FOREGROUND_MASK) << 4) | \
6769 (((attr) & BACKGROUND_MASK) >> 4)
6773constat_attr(
int count,
const int *seq, WORD attr, WORD default_attr,
int *reverse)
6778 if (!count)
return attr;
6779 if (rev) attr = constat_attr_color_reverse(attr);
6780 bold = attr & FOREGROUND_INTENSITY;
6781 attr &= ~(FOREGROUND_INTENSITY | BACKGROUND_INTENSITY);
6783 while (count-- > 0) {
6786 attr = default_attr;
6791 bold = FOREGROUND_INTENSITY;
6797#ifndef COMMON_LVB_UNDERSCORE
6798#define COMMON_LVB_UNDERSCORE 0x8000
6800 attr |= COMMON_LVB_UNDERSCORE;
6803 attr &= ~COMMON_LVB_UNDERSCORE;
6813 attr &= ~(FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED);
6816 attr = (attr & ~(FOREGROUND_BLUE | FOREGROUND_GREEN)) | FOREGROUND_RED;
6819 attr = (attr & ~(FOREGROUND_BLUE | FOREGROUND_RED)) | FOREGROUND_GREEN;
6822 attr = (attr & ~FOREGROUND_BLUE) | FOREGROUND_GREEN | FOREGROUND_RED;
6825 attr = (attr & ~(FOREGROUND_GREEN | FOREGROUND_RED)) | FOREGROUND_BLUE;
6828 attr = (attr & ~FOREGROUND_GREEN) | FOREGROUND_BLUE | FOREGROUND_RED;
6831 attr = (attr & ~FOREGROUND_RED) | FOREGROUND_BLUE | FOREGROUND_GREEN;
6834 attr |= FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED;
6839 attr = (attr & ~FOREGROUND_MASK) | (default_attr & FOREGROUND_MASK);
6843 attr &= ~(BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED);
6846 attr = (attr & ~(BACKGROUND_BLUE | BACKGROUND_GREEN)) | BACKGROUND_RED;
6849 attr = (attr & ~(BACKGROUND_BLUE | BACKGROUND_RED)) | BACKGROUND_GREEN;
6852 attr = (attr & ~BACKGROUND_BLUE) | BACKGROUND_GREEN | BACKGROUND_RED;
6855 attr = (attr & ~(BACKGROUND_GREEN | BACKGROUND_RED)) | BACKGROUND_BLUE;
6858 attr = (attr & ~BACKGROUND_GREEN) | BACKGROUND_BLUE | BACKGROUND_RED;
6861 attr = (attr & ~BACKGROUND_RED) | BACKGROUND_BLUE | BACKGROUND_GREEN;
6864 attr |= BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED;
6869 attr = (attr & ~BACKGROUND_MASK) | (default_attr & BACKGROUND_MASK);
6874 if (rev) attr = constat_attr_color_reverse(attr);
6881constat_clear(HANDLE handle, WORD attr, DWORD
len, COORD pos)
6885 FillConsoleOutputAttribute(handle, attr,
len, pos, &written);
6886 FillConsoleOutputCharacterW(handle, L
' ',
len, pos, &written);
6891constat_apply(HANDLE handle,
struct constat *s, WCHAR w)
6893 CONSOLE_SCREEN_BUFFER_INFO csbi;
6894 const int *seq = s->vt100.seq;
6895 int count = s->vt100.state;
6899 if (!GetConsoleScreenBufferInfo(handle, &csbi))
return;
6900 arg0 = (count > 0 && seq[0] > 0);
6901 if (arg0) arg1 = seq[0];
6904 SetConsoleTextAttribute(handle, constat_attr(count, seq, csbi.wAttributes, s->vt100.attr, &s->vt100.reverse));
6907 csbi.dwCursorPosition.X = 0;
6909 csbi.dwCursorPosition.Y -= arg1;
6910 if (csbi.dwCursorPosition.Y < csbi.srWindow.Top)
6911 csbi.dwCursorPosition.Y = csbi.srWindow.Top;
6912 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
6915 csbi.dwCursorPosition.X = 0;
6918 csbi.dwCursorPosition.Y += arg1;
6919 if (csbi.dwCursorPosition.Y > csbi.srWindow.Bottom)
6920 csbi.dwCursorPosition.Y = csbi.srWindow.Bottom;
6921 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
6924 csbi.dwCursorPosition.X += arg1;
6925 if (csbi.dwCursorPosition.X >= csbi.srWindow.Right)
6926 csbi.dwCursorPosition.X = csbi.srWindow.Right;
6927 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
6930 csbi.dwCursorPosition.X -= arg1;
6931 if (csbi.dwCursorPosition.X < csbi.srWindow.Left)
6932 csbi.dwCursorPosition.X = csbi.srWindow.Left;
6933 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
6937 arg1 += csbi.srWindow.Left;
6938 if (arg1 > csbi.srWindow.Right)
6939 arg1 = csbi.srWindow.Right;
6940 csbi.dwCursorPosition.X = arg1;
6941 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
6944 arg1 += csbi.srWindow.Top;
6945 if (arg1 > csbi.srWindow.Bottom)
6946 arg1 = csbi.srWindow.Bottom;
6947 csbi.dwCursorPosition.Y = arg1;
6948 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
6952 pos.Y = arg1 + csbi.srWindow.Top - 1;
6953 if (pos.Y > csbi.srWindow.Bottom) pos.Y = csbi.srWindow.Bottom;
6954 if (count < 2 || (arg1 = seq[1]) <= 0) arg1 = 1;
6955 pos.X = arg1 + csbi.srWindow.Left - 1;
6956 if (pos.X > csbi.srWindow.Right) pos.X = csbi.srWindow.Right;
6957 SetConsoleCursorPosition(handle, pos);
6960 switch (arg0 ? arg1 : 0) {
6962 constat_clear(handle, csbi.wAttributes,
6963 (csbi.dwSize.X * (csbi.srWindow.Bottom - csbi.dwCursorPosition.Y + 1)
6964 - csbi.dwCursorPosition.X),
6965 csbi.dwCursorPosition);
6969 pos.Y = csbi.srWindow.Top;
6970 constat_clear(handle, csbi.wAttributes,
6971 (csbi.dwSize.X * (csbi.dwCursorPosition.Y - csbi.srWindow.Top)
6972 + csbi.dwCursorPosition.X + 1),
6977 pos.Y = csbi.srWindow.Top;
6978 constat_clear(handle, csbi.wAttributes,
6979 (csbi.dwSize.X * (csbi.srWindow.Bottom - csbi.srWindow.Top + 1)),
6985 constat_clear(handle, csbi.wAttributes,
6986 (csbi.dwSize.X * csbi.dwSize.Y),
6992 switch (arg0 ? arg1 : 0) {
6994 constat_clear(handle, csbi.wAttributes,
6995 (csbi.dwSize.X - csbi.dwCursorPosition.X),
6996 csbi.dwCursorPosition);
7000 pos.Y = csbi.dwCursorPosition.Y;
7001 constat_clear(handle, csbi.wAttributes,
7002 csbi.dwCursorPosition.X + 1, pos);
7006 pos.Y = csbi.dwCursorPosition.Y;
7007 constat_clear(handle, csbi.wAttributes,
7008 csbi.dwSize.X, pos);
7013 s->vt100.saved = csbi.dwCursorPosition;
7016 SetConsoleCursorPosition(handle, s->vt100.saved);
7019 if (count >= 2 && seq[0] == -1 && seq[1] == 25) {
7020 CONSOLE_CURSOR_INFO cci;
7021 GetConsoleCursorInfo(handle, &cci);
7022 cci.bVisible = TRUE;
7023 SetConsoleCursorInfo(handle, &cci);
7027 if (count >= 2 && seq[0] == -1 && seq[1] == 25) {
7028 CONSOLE_CURSOR_INFO cci;
7029 GetConsoleCursorInfo(handle, &cci);
7030 cci.bVisible = FALSE;
7031 SetConsoleCursorInfo(handle, &cci);
7039static const long MAXSIZE_CONSOLE_WRITING = 31366;
7043constat_parse(HANDLE h,
struct constat *s,
const WCHAR **ptrp,
long *lenp)
7045 const WCHAR *ptr = *ptrp;
7046 long rest,
len = *lenp;
7050 rest = *lenp -
len - 1;
7051 if (s->vt100.state == constat_esc) {
7054 s->vt100.state = constat_init;
7055 if (
len > 0 && *ptr != L
'[')
continue;
7056 s->vt100.state = constat_esc;
7058 else if (s->vt100.state == constat_esc) {
7061 s->vt100.state = constat_init;
7064 rest = *lenp -
len - 1;
7065 if (rest > 0) --rest;
7066 s->vt100.state = constat_seq;
7067 s->vt100.seq[0] = 0;
7069 else if (s->vt100.state >= constat_seq) {
7070 if (wc >= L
'0' && wc <= L
'9') {
7071 if (s->vt100.state < (
int)numberof(s->vt100.seq)) {
7072 int *seq = &s->vt100.seq[s->vt100.state];
7073 *seq = (*seq * 10) + (wc - L
'0');
7076 else if (s->vt100.state == constat_seq && s->vt100.seq[0] == 0 && wc == L
'?') {
7077 s->vt100.seq[s->vt100.state++] = -1;
7081 if (++s->vt100.state < (
int)numberof(s->vt100.seq)) {
7082 s->vt100.seq[s->vt100.state] = 0;
7085 s->vt100.state = (int)numberof(s->vt100.seq);
7089 constat_apply(h, s, wc);
7090 s->vt100.state = constat_init;
7095 else if ((rest = *lenp -
len) < MAXSIZE_CONSOLE_WRITING) {
7113 SOCKET sock = TO_SOCKET(fd);
7114 int save_errno =
errno;
7116 if (!is_socket(sock)) {
7117 UnlockFile((HANDLE)sock, 0, 0, LK_LEN, LK_LEN);
7118 constat_delete((HANDLE)sock);
7121 _set_osfhnd(fd, (SOCKET)INVALID_HANDLE_VALUE);
7122 socklist_delete(&sock, NULL);
7125 if (closesocket(sock) == SOCKET_ERROR) {
7126 errno = map_errno(WSAGetLastError());
7132#ifndef INVALID_SET_FILE_POINTER
7133#define INVALID_SET_FILE_POINTER ((DWORD)-1)
7137setup_overlapped(OVERLAPPED *ol,
int fd,
int iswrite, rb_off_t *_offset)
7139 memset(ol, 0,
sizeof(*ol));
7144 DWORD seek_method = ((_osfile(fd) & FAPPEND) && iswrite) ? FILE_END : FILE_CURRENT;
7148 uint64_t offset = *_offset;
7149 ol->Offset = (uint32_t)(offset & 0xFFFFFFFFLL);
7150 ol->OffsetHigh = (uint32_t)((offset & 0xFFFFFFFF00000000LL) >> 32);
7153 LARGE_INTEGER seek_offset = {0}, current_offset = {0};
7154 if (!SetFilePointerEx((HANDLE)_osfhnd(fd), seek_offset, ¤t_offset, seek_method)) {
7155 DWORD last_error = GetLastError();
7156 if (last_error != NO_ERROR) {
7157 errno = map_errno(last_error);
7163 *_offset = current_offset.QuadPart;
7165 else if (!(_osfile(fd) & (FDEV | FPIPE))) {
7167 DWORD low = SetFilePointer((HANDLE)_osfhnd(fd), 0, &high, seek_method);
7169 if (low == INVALID_SET_FILE_POINTER) {
7170 DWORD err = GetLastError();
7171 if (err != NO_ERROR) {
7172 errno = map_errno(err);
7178 ol->OffsetHigh = high;
7181 ol->hEvent = CreateEvent(NULL, TRUE, TRUE, NULL);
7183 errno = map_errno(GetLastError());
7190finish_overlapped(OVERLAPPED *ol,
int fd, DWORD size, rb_off_t *_offset)
7192 CloseHandle(ol->hEvent);
7196 DWORD seek_method = (_osfile(fd) & FAPPEND) ? FILE_END : FILE_BEGIN;
7198 LARGE_INTEGER seek_offset = {0};
7199 if (seek_method == FILE_BEGIN) {
7200 seek_offset.QuadPart = *_offset;
7203 SetFilePointerEx((HANDLE)_osfhnd(fd), seek_offset, NULL, seek_method);
7205 else if (!(_osfile(fd) & (FDEV | FPIPE))) {
7206 LONG high = ol->OffsetHigh;
7207 DWORD low = ol->Offset + size;
7208 if (low < ol->Offset)
7210 SetFilePointer((HANDLE)_osfhnd(fd), low, &high, FILE_BEGIN);
7217rb_w32_read_internal(
int fd,
void *buf,
size_t size, rb_off_t *offset)
7219 SOCKET sock = TO_SOCKET(fd);
7227 BOOL islineinput = FALSE;
7230 if (is_socket(sock))
7231 return rb_w32_recv(fd, buf, size, 0);
7234 if (_get_osfhandle(fd) == -1) {
7238 if (!offset && _osfile(fd) & FTEXT) {
7239 return _read(fd, buf, size);
7242 rb_acrt_lowio_lock_fh(fd);
7244 if (!size || _osfile(fd) & FEOFLAG) {
7245 _set_osflags(fd, _osfile(fd) & ~FEOFLAG);
7246 rb_acrt_lowio_unlock_fh(fd);
7251 isconsole = is_console(_osfhnd(fd)) && (osver.dwMajorVersion < 6 || (osver.dwMajorVersion == 6 && osver.dwMinorVersion < 2));
7254 GetConsoleMode((HANDLE)_osfhnd(fd),&mode);
7255 islineinput = (mode & ENABLE_LINE_INPUT) != 0;
7260 constat_reset((HANDLE)_osfhnd(fd));
7272 if (setup_overlapped(&ol, fd, FALSE, offset)) {
7273 rb_acrt_lowio_unlock_fh(fd);
7277 if (!ReadFile((HANDLE)_osfhnd(fd), buf,
len, &read, &ol)) {
7278 err = GetLastError();
7279 if (err == ERROR_NO_DATA && (_osfile(fd) & FPIPE)) {
7281 if (GetNamedPipeHandleState((HANDLE)_osfhnd(fd), &state, NULL, NULL, NULL, NULL, 0) && (state & PIPE_NOWAIT)) {
7282 errno = EWOULDBLOCK;
7285 errno = map_errno(err);
7287 rb_acrt_lowio_unlock_fh(fd);
7290 else if (err != ERROR_IO_PENDING) {
7291 CloseHandle(ol.hEvent);
7292 if (err == ERROR_ACCESS_DENIED)
7294 else if (err == ERROR_BROKEN_PIPE || err == ERROR_HANDLE_EOF) {
7295 rb_acrt_lowio_unlock_fh(fd);
7299 errno = map_errno(err);
7301 rb_acrt_lowio_unlock_fh(fd);
7305 wait = rb_w32_wait_events_blocking(&ol.hEvent, 1, INFINITE);
7306 if (wait != WAIT_OBJECT_0) {
7307 if (wait == WAIT_OBJECT_0 + 1)
7310 errno = map_errno(GetLastError());
7311 CloseHandle(ol.hEvent);
7312 CancelIo((HANDLE)_osfhnd(fd));
7313 rb_acrt_lowio_unlock_fh(fd);
7317 if (!GetOverlappedResult((HANDLE)_osfhnd(fd), &ol, &read, TRUE) &&
7318 (err = GetLastError()) != ERROR_HANDLE_EOF) {
7320 if (err != ERROR_BROKEN_PIPE) {
7321 errno = map_errno(err);
7324 CloseHandle(ol.hEvent);
7325 CancelIo((HANDLE)_osfhnd(fd));
7326 rb_acrt_lowio_unlock_fh(fd);
7331 err = GetLastError();
7332 errno = map_errno(err);
7335 finish_overlapped(&ol, fd, read, offset);
7339 buf = (
char *)buf + read;
7340 if (err != ERROR_OPERATION_ABORTED &&
7341 !(isconsole &&
len == 1 && (!islineinput || *((
char *)buf - 1) ==
'\n')) && size > 0)
7345 _set_osflags(fd, _osfile(fd) | FEOFLAG);
7348 rb_acrt_lowio_unlock_fh(fd);
7356rb_w32_write_internal(
int fd,
const void *buf,
size_t size, rb_off_t *offset)
7358 SOCKET sock = TO_SOCKET(fd);
7366 if (is_socket(sock))
7367 return rb_w32_send(fd, buf, size, 0);
7370 if (_get_osfhandle(fd) == -1) {
7375 if (!offset && (_osfile(fd) & FTEXT) &&
7376 (!(_osfile(fd) & FPIPE) || fd == fileno(stdout) || fd == fileno(stderr))) {
7377 ssize_t w = _write(fd, buf, size);
7378 if (w == (ssize_t)-1 &&
errno == EINVAL) {
7379 errno = map_errno(GetLastError());
7384 rb_acrt_lowio_lock_fh(fd);
7386 if (!size || _osfile(fd) & FEOFLAG) {
7387 rb_acrt_lowio_unlock_fh(fd);
7393 len = (_osfile(fd) & FDEV) ? min(MAXSIZE_CONSOLE_WRITING, size) : size;
7398 if (setup_overlapped(&ol, fd, TRUE, offset)) {
7399 rb_acrt_lowio_unlock_fh(fd);
7403 if (!WriteFile((HANDLE)_osfhnd(fd), buf,
len, &written, &ol)) {
7404 err = GetLastError();
7405 if (err != ERROR_IO_PENDING) {
7406 CloseHandle(ol.hEvent);
7407 if (err == ERROR_ACCESS_DENIED)
7410 errno = map_errno(err);
7412 rb_acrt_lowio_unlock_fh(fd);
7416 wait = rb_w32_wait_events_blocking(&ol.hEvent, 1, INFINITE);
7417 if (wait != WAIT_OBJECT_0) {
7418 if (wait == WAIT_OBJECT_0 + 1)
7421 errno = map_errno(GetLastError());
7422 CloseHandle(ol.hEvent);
7423 CancelIo((HANDLE)_osfhnd(fd));
7424 rb_acrt_lowio_unlock_fh(fd);
7428 if (!GetOverlappedResult((HANDLE)_osfhnd(fd), &ol, &written, TRUE)) {
7429 errno = map_errno(GetLastError());
7430 CloseHandle(ol.hEvent);
7431 CancelIo((HANDLE)_osfhnd(fd));
7432 rb_acrt_lowio_unlock_fh(fd);
7437 finish_overlapped(&ol, fd, written, offset);
7440 if (written ==
len) {
7441 buf = (
const char *)buf +
len;
7446 size_t newlen =
len / 2;
7448 size +=
len - newlen;
7453 errno = EWOULDBLOCK;
7456 rb_acrt_lowio_unlock_fh(fd);
7462rb_w32_read(
int fd,
void *buf,
size_t size)
7464 return rb_w32_read_internal(fd, buf, size, NULL);
7468rb_w32_write(
int fd,
const void *buf,
size_t size)
7470 return rb_w32_write_internal(fd, buf, size, NULL);
7474rb_w32_pread(
int descriptor,
void *base,
size_t size, rb_off_t offset)
7476 return rb_w32_read_internal(descriptor, base, size, &offset);
7480rb_w32_pwrite(
int descriptor,
const void *base,
size_t size, rb_off_t offset)
7482 return rb_w32_write_internal(descriptor, base, size, &offset);
7487rb_w32_write_console(uintptr_t strarg,
int fd)
7490 DWORD dwMode, reslen;
7494 const WCHAR *ptr, *next;
7498 handle = (HANDLE)_osfhnd(fd);
7499 if (!GetConsoleMode(handle, &dwMode))
7502 s = constat_handle(handle);
7512 case ENCINDEX_US_ASCII:
7513 case ENCINDEX_ASCII_8BIT:
7515 case ENCINDEX_UTF_8:
7516 ptr = wbuffer = mbstr_to_wstr(CP_UTF8, RSTRING_PTR(str), RSTRING_LEN(str), &
len);
7517 if (!ptr)
return -1L;
7519 case ENCINDEX_UTF_16LE:
7520 ptr = (
const WCHAR *)RSTRING_PTR(str);
7521 len = RSTRING_LEN(str) /
sizeof(WCHAR);
7525 if (dwMode & ENABLE_VIRTUAL_TERMINAL_PROCESSING) {
7526 if (!WriteConsoleW(handle, ptr,
len, &reslen, NULL))
7527 reslen = (DWORD)-1L;
7531 long curlen = constat_parse(handle, s, (next = ptr, &next), &
len);
7532 reslen += next - ptr;
7535 if (!WriteConsoleW(handle, ptr, curlen, &written, NULL)) {
7536 reslen = (DWORD)-1L;
7545 return (
long)reslen;
7550timespec_to_filetime(
const struct timespec *ts, FILETIME *ft)
7554 tmp.QuadPart = unix_to_filetime((ULONGLONG)ts->tv_sec);
7555 tmp.QuadPart += ts->tv_nsec / 100;
7556 ft->dwLowDateTime = tmp.LowPart;
7557 ft->dwHighDateTime = tmp.HighPart;
7563wutimensat(
int dirfd,
const WCHAR *path,
const struct timespec *times,
int flags)
7566 FILETIME atime, mtime;
7571 if (dirfd != AT_FDCWD) {
7581 if (wstati128(path, &stat, FALSE)) {
7586 if (timespec_to_filetime(×[0], &atime)) {
7589 if (timespec_to_filetime(×[1], &mtime)) {
7594 GetSystemTimePreciseAsFileTime(&atime);
7599 const DWORD attr = GetFileAttributesW(path);
7600 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY))
7601 SetFileAttributesW(path, attr & ~FILE_ATTRIBUTE_READONLY);
7602 hFile = open_special(path, GENERIC_WRITE, 0);
7603 if (hFile == INVALID_HANDLE_VALUE) {
7604 errno = map_errno(GetLastError());
7608 if (!SetFileTime(hFile, NULL, &atime, &mtime)) {
7609 errno = map_errno(GetLastError());
7614 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY))
7615 SetFileAttributesW(path, attr);
7623w32_utimensat(
int dirfd,
const char *path,
const struct timespec *times,
int flags, UINT cp)
7625 WCHAR *wpath = mbstr_to_wstr(cp, path, -1, NULL);
7629 ret = wutimensat(dirfd, wpath, times, flags);
7637rb_w32_uutime(
const char *path,
const struct utimbuf *times)
7641 ts[0].tv_sec = times->actime;
7643 ts[1].tv_sec = times->modtime;
7645 return w32_utimensat(AT_FDCWD, path, ts, 0, CP_UTF8);
7650rb_w32_utime(
const char *path,
const struct utimbuf *times)
7654 ts[0].tv_sec = times->actime;
7656 ts[1].tv_sec = times->modtime;
7658 return w32_utimensat(AT_FDCWD, path, ts, 0, filecp());
7663rb_w32_uutimes(
const char *path,
const struct timeval *times)
7667 ts[0].tv_sec = times[0].tv_sec;
7668 ts[0].tv_nsec = times[0].tv_usec * 1000;
7669 ts[1].tv_sec = times[1].tv_sec;
7670 ts[1].tv_nsec = times[1].tv_usec * 1000;
7671 return w32_utimensat(AT_FDCWD, path, ts, 0, CP_UTF8);
7676rb_w32_utimes(
const char *path,
const struct timeval *times)
7680 ts[0].tv_sec = times[0].tv_sec;
7681 ts[0].tv_nsec = times[0].tv_usec * 1000;
7682 ts[1].tv_sec = times[1].tv_sec;
7683 ts[1].tv_nsec = times[1].tv_usec * 1000;
7684 return w32_utimensat(AT_FDCWD, path, ts, 0, filecp());
7689rb_w32_uutimensat(
int dirfd,
const char *path,
const struct timespec *times,
int flags)
7691 return w32_utimensat(dirfd, path, times, flags, CP_UTF8);
7696rb_w32_utimensat(
int dirfd,
const char *path,
const struct timespec *times,
int flags)
7698 return w32_utimensat(dirfd, path, times, flags, filecp());
7703rb_w32_uchdir(
const char *path)
7708 if (!(wpath = utf8_to_wstr(path, NULL)))
7710 ret = _wchdir(wpath);
7717wmkdir(
const WCHAR *wpath,
int mode)
7722 if (CreateDirectoryW(wpath, NULL) == FALSE) {
7723 errno = map_errno(GetLastError());
7726 if (_wchmod(wpath, mode) == -1) {
7727 RemoveDirectoryW(wpath);
7737rb_w32_umkdir(
const char *path,
int mode)
7742 if (!(wpath = utf8_to_wstr(path, NULL)))
7744 ret = wmkdir(wpath, mode);
7751rb_w32_mkdir(
const char *path,
int mode)
7756 if (!(wpath = filecp_to_wstr(path, NULL)))
7758 ret = wmkdir(wpath, mode);
7765wrmdir(
const WCHAR *wpath)
7769 const DWORD attr = GetFileAttributesW(wpath);
7770 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY)) {
7771 SetFileAttributesW(wpath, attr & ~FILE_ATTRIBUTE_READONLY);
7773 if (RemoveDirectoryW(wpath) == FALSE) {
7774 errno = map_errno(GetLastError());
7776 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY)) {
7777 SetFileAttributesW(wpath, attr);
7786rb_w32_rmdir(
const char *path)
7791 if (!(wpath = filecp_to_wstr(path, NULL)))
7793 ret = wrmdir(wpath);
7800rb_w32_urmdir(
const char *path)
7805 if (!(wpath = utf8_to_wstr(path, NULL)))
7807 ret = wrmdir(wpath);
7814wunlink(
const WCHAR *path)
7817 const DWORD SYMLINKD = FILE_ATTRIBUTE_REPARSE_POINT|FILE_ATTRIBUTE_DIRECTORY;
7819 const DWORD attr = GetFileAttributesW(path);
7820 if (attr == (DWORD)-1) {
7822 else if ((attr & SYMLINKD) == SYMLINKD) {
7823 ret = RemoveDirectoryW(path);
7826 if (attr & FILE_ATTRIBUTE_READONLY) {
7827 SetFileAttributesW(path, attr & ~FILE_ATTRIBUTE_READONLY);
7829 ret = DeleteFileW(path);
7832 errno = map_errno(GetLastError());
7834 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY)) {
7835 SetFileAttributesW(path, attr);
7844rb_w32_uunlink(
const char *path)
7849 if (!(wpath = utf8_to_wstr(path, NULL)))
7851 ret = wunlink(wpath);
7858rb_w32_unlink(
const char *path)
7863 if (!(wpath = filecp_to_wstr(path, NULL)))
7865 ret = wunlink(wpath);
7872rb_w32_uchmod(
const char *path,
int mode)
7877 if (!(wpath = utf8_to_wstr(path, NULL)))
7879 ret = _wchmod(wpath, mode);
7886fchmod(
int fd,
int mode)
7890 LARGE_INTEGER CreationTime;
7891 LARGE_INTEGER LastAccessTime;
7892 LARGE_INTEGER LastWriteTime;
7893 LARGE_INTEGER ChangeTime;
7894 DWORD FileAttributes;
7895 } info = {{{0}}, {{0}}, {{0}},};
7896 HANDLE h = (HANDLE)_get_osfhandle(fd);
7898 info.FileAttributes = FILE_ATTRIBUTE_NORMAL;
7899 if (!(mode & 0200)) info.FileAttributes |= FILE_ATTRIBUTE_READONLY;
7900 if (!SetFileInformationByHandle(h, 0, &info,
sizeof(info))) {
7901 errno = map_errno(GetLastError());
7909rb_w32_isatty(
int fd)
7914 if (_get_osfhandle(fd) == -1) {
7917 if (!GetConsoleMode((HANDLE)_osfhnd(fd), &mode)) {
7929 int *ip = (
int *)(&x + 1) - 1;
7936rb_w32_inet_ntop(
int af,
const void *addr,
char *numaddr,
size_t numaddr_len)
7938 return (inet_ntop)(af, (
void *)addr, numaddr, numaddr_len);
7943rb_w32_inet_pton(
int af,
const char *src,
void *dst)
7945 return (inet_pton)(af, src, dst);
7950rb_w32_fd_is_text(
int fd)
7952 return _osfile(fd) & FTEXT;
7955#ifdef HAVE__GMTIME64_S
7956# ifndef HAVE__LOCALTIME64_S
7958# define HAVE__LOCALTIME64_S 1
7960# ifndef MINGW_HAS_SECURE_API
7961 _CRTIMP errno_t __cdecl _gmtime64_s(
struct tm* tm,
const __time64_t *time);
7962 _CRTIMP errno_t __cdecl _localtime64_s(
struct tm* tm,
const __time64_t *time);
7964# define gmtime_s _gmtime64_s
7965# define localtime_s _localtime64_s
7970gmtime_r(
const time_t *tp,
struct tm *rp)
7978 e = gmtime_s(rp, tp);
7979 if (e != 0)
goto error;
7985localtime_r(
const time_t *tp,
struct tm *rp)
7993 e = localtime_s(rp, tp);
8000rb_w32_wrap_io_handle(HANDLE h,
int flags)
8003 int len =
sizeof(tmp);
8004 int r = getsockopt((SOCKET)h, SOL_SOCKET, SO_DEBUG, (
char *)&tmp, &
len);
8005 if (r != SOCKET_ERROR || WSAGetLastError() != WSAENOTSOCK) {
8007 if (flags & O_NONBLOCK) {
8008 flags &= ~O_NONBLOCK;
8011 socklist_insert((SOCKET)h, f);
8013 else if (flags & O_NONBLOCK) {
8017 return rb_w32_open_osfhandle((intptr_t)h, flags);
8022rb_w32_unwrap_io_handle(
int fd)
8024 SOCKET sock = TO_SOCKET(fd);
8025 _set_osfhnd(fd, (SOCKET)INVALID_HANDLE_VALUE);
8026 if (!is_socket(sock)) {
8027 UnlockFile((HANDLE)sock, 0, 0, LK_LEN, LK_LEN);
8028 constat_delete((HANDLE)sock);
8031 socklist_delete(&sock, NULL);
8036#if !defined(__MINGW64__) && defined(__MINGW64_VERSION_MAJOR)
8042rb_w32_pow(
double x,
double y)
8046 unsigned int default_control = _controlfp(0, 0);
8047 _controlfp(_PC_64, _MCW_PC);
8050 _controlfp(default_control, _MCW_PC);
8058 BY_HANDLE_FILE_INFORMATION bhfi;
8069 tmp = rb_check_convert_type_with_id(*file,
T_FILE,
"IO", idTo_io);
8072 if (f == (HANDLE)-1)
return INVALID_HANDLE_VALUE;
8081 tmp = rb_str_encode_ospath(*file);
8082 len = MultiByteToWideChar(CP_UTF8, 0, RSTRING_PTR(tmp), -1, NULL, 0);
8084 MultiByteToWideChar(CP_UTF8, 0, RSTRING_PTR(tmp), -1, ptr,
len);
8085 f = CreateFileW(ptr, 0,
8086 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
8087 FILE_FLAG_BACKUP_SEMANTICS, NULL);
8089 if (f == INVALID_HANDLE_VALUE)
return f;
8092 if (GetFileType(f) == FILE_TYPE_DISK) {
8093 ZeroMemory(st,
sizeof(*st));
8094 if (get_ino(f, &st->info.fii)) {
8095 st->file_id_p = TRUE;
8098 else if (GetLastError() != ERROR_INVALID_PARAMETER) {
8100 return INVALID_HANDLE_VALUE;
8104 if (GetFileInformationByHandle(f, &st->info.bhfi)) {
8105 st->file_id_p = FALSE;
8109 if (ret) CloseHandle(ret);
8110 return INVALID_HANDLE_VALUE;
8114close_handle(
VALUE h)
8116 CloseHandle((HANDLE)h);
8126call_w32_io_info(
VALUE arg)
8129 return (
VALUE)w32_io_info(p->fname, p->st);
8133rb_w32_file_identical_p(
VALUE fname1,
VALUE fname2)
8136 HANDLE f1 = 0, f2 = 0;
8138 f1 = w32_io_info(&fname1, &st1);
8139 if (f1 == INVALID_HANDLE_VALUE)
return Qfalse;
8142 arg.fname = &fname2;
8147 f2 = w32_io_info(&fname2, &st2);
8149 if (f2 == INVALID_HANDLE_VALUE)
return Qfalse;
8150 if (f2) CloseHandle(f2);
8152 if (st1.file_id_p != st2.file_id_p)
return Qfalse;
8153 if (!st1.file_id_p) {
8154 if (st1.info.bhfi.dwVolumeSerialNumber == st2.info.bhfi.dwVolumeSerialNumber &&
8155 st1.info.bhfi.nFileIndexHigh == st2.info.bhfi.nFileIndexHigh &&
8156 st1.info.bhfi.nFileIndexLow == st2.info.bhfi.nFileIndexLow)
8160 if (st1.info.fii.VolumeSerialNumber == st2.info.fii.VolumeSerialNumber &&
8161 memcmp(&st1.info.fii.FileId, &st2.info.fii.FileId,
sizeof(
FILE_ID_128)) == 0)
8168rb_w32_set_thread_description(HANDLE th,
const WCHAR *name)
8171 typedef HRESULT (WINAPI *set_thread_description_func)(HANDLE, PCWSTR);
8172 static set_thread_description_func set_thread_description =
8173 (set_thread_description_func)-1;
8174 if (set_thread_description == (set_thread_description_func)-1) {
8176 set_thread_description = (set_thread_description_func)
8177 get_proc_address(
"kernel32",
"SetThreadDescription", NULL);
8179 if (set_thread_description) {
8180 result = set_thread_description(th, name);
8186rb_w32_set_thread_description_str(HANDLE th,
VALUE name)
8188 int idx, result = FALSE;
8192 return rb_w32_set_thread_description(th, L
"");
8195 idx = rb_enc_get_index(name);
8196 if (idx == ENCINDEX_UTF_16LE) {
8197 result = rb_w32_set_thread_description(th, s);
8200 name =
rb_str_conv_enc(name, rb_enc_from_index(idx), rb_utf8_encoding());
8201 s = mbstr_to_wstr(CP_UTF8, RSTRING_PTR(name), RSTRING_LEN(name)+1, NULL);
8202 result = rb_w32_set_thread_description(th, s);
8212rb_w32_mmap(
void *addr,
size_t len,
int prot,
int flags,
int fd, rb_off_t offset)
8216 DWORD protect = PAGE_EXECUTE_READWRITE;
8218 if (fd > 0 || offset) {
8233 ptr = VirtualAlloc(addr,
len, MEM_RESERVE | MEM_COMMIT, protect);
8235 errno = rb_w32_map_errno(GetLastError());
8243rb_w32_munmap(
void *addr,
size_t len)
8245 if (!VirtualFree(addr, 0, MEM_RELEASE)) {
8246 errno = rb_w32_map_errno(GetLastError());
8254rb_w32_mprotect(
void *addr,
size_t len,
int prot)
8270 if (prot & PROT_EXEC) {
8271 if (!FlushInstructionCache(GetCurrentProcess(), addr,
len)) {
8272 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.
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 RBIMPL_ATTR_NONNULL(list)
Wraps (or simulates) __attribute__((nonnull))
#define PRI_PIDT_PREFIX
A rb_sprintf() format prefix to be used for a pid_t parameter.
#define rb_fd_init
Initialises the :given :rb_fdset_t.
#define StringValueCStr(v)
Identical to StringValuePtr, except it additionally checks for the contents for viability as a C stri...
#define FilePathValue(v)
Ensures that the parameter object is a path.
#define errno
Ractor-aware version of errno.
The data structure which wraps the fd_set bitmap used by select(2).
fd_set * fdset
File descriptors buffer.
int capa
Maximum allowed number of FDs.
intptr_t SIGNED_VALUE
A signed integer type that has the same width with VALUE.
uintptr_t VALUE
Type that represents a Ruby object.