-
Notifications
You must be signed in to change notification settings - Fork 0
/
win32.c
5767 lines (5059 loc) · 122 KB
/
win32.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 1993, Intergraph Corporation
*
* You may distribute under the terms of either the GNU General Public
* License or the Artistic License, as specified in the perl README file.
*
* Various Unix compatibility functions and NT specific functions.
*
* Some of this code was derived from the MSDOS port(s) and the OS/2 port.
*
*/
#include "ruby/ruby.h"
#include "ruby/encoding.h"
#include "dln.h"
#include <fcntl.h>
#include <process.h>
#include <sys/stat.h>
/* #include <sys/wait.h> */
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <assert.h>
#include <ctype.h>
#include <windows.h>
#include <winbase.h>
#include <wincon.h>
#include <share.h>
#include <shlobj.h>
#include <mbstring.h>
#if _MSC_VER >= 1400
#include <crtdbg.h>
#include <rtcapi.h>
#endif
#ifdef __MINGW32__
#include <mswsock.h>
#endif
#include "ruby/win32.h"
#include "win32/dir.h"
#define isdirsep(x) ((x) == '/' || (x) == '\\')
#undef stat
#undef fclose
#undef close
#undef setsockopt
#if defined __BORLANDC__
# define _filbuf _fgetc
# define _flsbuf _fputc
# define enough_to_get(n) (--(n) >= 0)
# define enough_to_put(n) (++(n) < 0)
#else
# define enough_to_get(n) (--(n) >= 0)
# define enough_to_put(n) (--(n) >= 0)
#endif
#ifdef WIN32_DEBUG
#define Debug(something) something
#else
#define Debug(something) /* nothing */
#endif
#define TO_SOCKET(x) _get_osfhandle(x)
static struct ChildRecord *CreateChild(const WCHAR *, const WCHAR *, SECURITY_ATTRIBUTES *, HANDLE, HANDLE, HANDLE);
static int has_redirection(const char *);
int rb_w32_wait_events(HANDLE *events, int num, DWORD timeout);
static int rb_w32_open_osfhandle(intptr_t osfhandle, int flags);
static int wstati64(const WCHAR *path, struct stati64 *st);
VALUE rb_w32_conv_from_wchar(const WCHAR *wstr, rb_encoding *enc);
#define RUBY_CRITICAL(expr) do { expr; } while (0)
/* errno mapping */
static struct {
DWORD winerr;
int err;
} errmap[] = {
{ ERROR_INVALID_FUNCTION, EINVAL },
{ ERROR_FILE_NOT_FOUND, ENOENT },
{ ERROR_PATH_NOT_FOUND, ENOENT },
{ ERROR_TOO_MANY_OPEN_FILES, EMFILE },
{ ERROR_ACCESS_DENIED, EACCES },
{ ERROR_INVALID_HANDLE, EBADF },
{ ERROR_ARENA_TRASHED, ENOMEM },
{ ERROR_NOT_ENOUGH_MEMORY, ENOMEM },
{ ERROR_INVALID_BLOCK, ENOMEM },
{ ERROR_BAD_ENVIRONMENT, E2BIG },
{ ERROR_BAD_FORMAT, ENOEXEC },
{ ERROR_INVALID_ACCESS, EINVAL },
{ ERROR_INVALID_DATA, EINVAL },
{ ERROR_INVALID_DRIVE, ENOENT },
{ ERROR_CURRENT_DIRECTORY, EACCES },
{ ERROR_NOT_SAME_DEVICE, EXDEV },
{ ERROR_NO_MORE_FILES, ENOENT },
{ ERROR_WRITE_PROTECT, EROFS },
{ ERROR_BAD_UNIT, ENODEV },
{ ERROR_NOT_READY, ENXIO },
{ ERROR_BAD_COMMAND, EACCES },
{ ERROR_CRC, EACCES },
{ ERROR_BAD_LENGTH, EACCES },
{ ERROR_SEEK, EIO },
{ ERROR_NOT_DOS_DISK, EACCES },
{ ERROR_SECTOR_NOT_FOUND, EACCES },
{ ERROR_OUT_OF_PAPER, EACCES },
{ ERROR_WRITE_FAULT, EIO },
{ ERROR_READ_FAULT, EIO },
{ ERROR_GEN_FAILURE, EACCES },
{ ERROR_LOCK_VIOLATION, EACCES },
{ ERROR_SHARING_VIOLATION, EACCES },
{ ERROR_WRONG_DISK, EACCES },
{ ERROR_SHARING_BUFFER_EXCEEDED, EACCES },
{ ERROR_BAD_NETPATH, ENOENT },
{ ERROR_NETWORK_ACCESS_DENIED, EACCES },
{ ERROR_BAD_NET_NAME, ENOENT },
{ ERROR_FILE_EXISTS, EEXIST },
{ ERROR_CANNOT_MAKE, EACCES },
{ ERROR_FAIL_I24, EACCES },
{ ERROR_INVALID_PARAMETER, EINVAL },
{ ERROR_NO_PROC_SLOTS, EAGAIN },
{ ERROR_DRIVE_LOCKED, EACCES },
{ ERROR_BROKEN_PIPE, EPIPE },
{ ERROR_DISK_FULL, ENOSPC },
{ ERROR_INVALID_TARGET_HANDLE, EBADF },
{ ERROR_INVALID_HANDLE, EINVAL },
{ ERROR_WAIT_NO_CHILDREN, ECHILD },
{ ERROR_CHILD_NOT_COMPLETE, ECHILD },
{ ERROR_DIRECT_ACCESS_HANDLE, EBADF },
{ ERROR_NEGATIVE_SEEK, EINVAL },
{ ERROR_SEEK_ON_DEVICE, EACCES },
{ ERROR_DIR_NOT_EMPTY, ENOTEMPTY },
{ ERROR_DIRECTORY, ENOTDIR },
{ ERROR_NOT_LOCKED, EACCES },
{ ERROR_BAD_PATHNAME, ENOENT },
{ ERROR_MAX_THRDS_REACHED, EAGAIN },
{ ERROR_LOCK_FAILED, EACCES },
{ ERROR_ALREADY_EXISTS, EEXIST },
{ ERROR_INVALID_STARTING_CODESEG, ENOEXEC },
{ ERROR_INVALID_STACKSEG, ENOEXEC },
{ ERROR_INVALID_MODULETYPE, ENOEXEC },
{ ERROR_INVALID_EXE_SIGNATURE, ENOEXEC },
{ ERROR_EXE_MARKED_INVALID, ENOEXEC },
{ ERROR_BAD_EXE_FORMAT, ENOEXEC },
{ ERROR_ITERATED_DATA_EXCEEDS_64k,ENOEXEC },
{ ERROR_INVALID_MINALLOCSIZE, ENOEXEC },
{ ERROR_DYNLINK_FROM_INVALID_RING,ENOEXEC },
{ ERROR_IOPL_NOT_ENABLED, ENOEXEC },
{ ERROR_INVALID_SEGDPL, ENOEXEC },
{ ERROR_AUTODATASEG_EXCEEDS_64k, ENOEXEC },
{ ERROR_RING2SEG_MUST_BE_MOVABLE, ENOEXEC },
{ ERROR_RELOC_CHAIN_XEEDS_SEGLIM, ENOEXEC },
{ ERROR_INFLOOP_IN_RELOC_CHAIN, ENOEXEC },
{ ERROR_FILENAME_EXCED_RANGE, ENOENT },
{ ERROR_NESTING_NOT_ALLOWED, EAGAIN },
#ifndef ERROR_PIPE_LOCAL
#define ERROR_PIPE_LOCAL 229L
#endif
{ ERROR_PIPE_LOCAL, EPIPE },
{ ERROR_BAD_PIPE, EPIPE },
{ ERROR_PIPE_BUSY, EAGAIN },
{ ERROR_NO_DATA, EPIPE },
{ ERROR_PIPE_NOT_CONNECTED, EPIPE },
{ ERROR_OPERATION_ABORTED, EINTR },
{ ERROR_NOT_ENOUGH_QUOTA, ENOMEM },
{ ERROR_MOD_NOT_FOUND, ENOENT },
{ WSAEINTR, EINTR },
{ WSAEBADF, EBADF },
{ WSAEACCES, EACCES },
{ WSAEFAULT, EFAULT },
{ WSAEINVAL, EINVAL },
{ WSAEMFILE, EMFILE },
{ WSAEWOULDBLOCK, EWOULDBLOCK },
{ WSAEINPROGRESS, EINPROGRESS },
{ WSAEALREADY, EALREADY },
{ WSAENOTSOCK, ENOTSOCK },
{ WSAEDESTADDRREQ, EDESTADDRREQ },
{ WSAEMSGSIZE, EMSGSIZE },
{ WSAEPROTOTYPE, EPROTOTYPE },
{ WSAENOPROTOOPT, ENOPROTOOPT },
{ WSAEPROTONOSUPPORT, EPROTONOSUPPORT },
{ WSAESOCKTNOSUPPORT, ESOCKTNOSUPPORT },
{ WSAEOPNOTSUPP, EOPNOTSUPP },
{ WSAEPFNOSUPPORT, EPFNOSUPPORT },
{ WSAEAFNOSUPPORT, EAFNOSUPPORT },
{ WSAEADDRINUSE, EADDRINUSE },
{ WSAEADDRNOTAVAIL, EADDRNOTAVAIL },
{ WSAENETDOWN, ENETDOWN },
{ WSAENETUNREACH, ENETUNREACH },
{ WSAENETRESET, ENETRESET },
{ WSAECONNABORTED, ECONNABORTED },
{ WSAECONNRESET, ECONNRESET },
{ WSAENOBUFS, ENOBUFS },
{ WSAEISCONN, EISCONN },
{ WSAENOTCONN, ENOTCONN },
{ WSAESHUTDOWN, ESHUTDOWN },
{ WSAETOOMANYREFS, ETOOMANYREFS },
{ WSAETIMEDOUT, ETIMEDOUT },
{ WSAECONNREFUSED, ECONNREFUSED },
{ WSAELOOP, ELOOP },
{ WSAENAMETOOLONG, ENAMETOOLONG },
{ WSAEHOSTDOWN, EHOSTDOWN },
{ WSAEHOSTUNREACH, EHOSTUNREACH },
{ WSAEPROCLIM, EPROCLIM },
{ WSAENOTEMPTY, ENOTEMPTY },
{ WSAEUSERS, EUSERS },
{ WSAEDQUOT, EDQUOT },
{ WSAESTALE, ESTALE },
{ WSAEREMOTE, EREMOTE },
};
int
rb_w32_map_errno(DWORD winerr)
{
int i;
if (winerr == 0) {
return 0;
}
for (i = 0; i < (int)(sizeof(errmap) / sizeof(*errmap)); i++) {
if (errmap[i].winerr == winerr) {
return errmap[i].err;
}
}
if (winerr >= WSABASEERR) {
return winerr;
}
return EINVAL;
}
#define map_errno rb_w32_map_errno
static const char *NTLoginName;
static OSVERSIONINFO osver;
static void
get_version(void)
{
memset(&osver, 0, sizeof(OSVERSIONINFO));
osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx(&osver);
}
#ifdef _M_IX86
DWORD
rb_w32_osid(void)
{
return osver.dwPlatformId;
}
#endif
DWORD
rb_w32_osver(void)
{
return osver.dwMajorVersion;
}
#define IsWinNT() rb_w32_iswinnt()
#define IsWin95() rb_w32_iswin95()
#ifdef WIN95
#define IfWin95(win95, winnt) (IsWin95() ? (win95) : (winnt))
#else
#define IfWin95(win95, winnt) (winnt)
#endif
HANDLE
GetCurrentThreadHandle(void)
{
static HANDLE current_process_handle = NULL;
HANDLE h;
if (!current_process_handle)
current_process_handle = GetCurrentProcess();
if (!DuplicateHandle(current_process_handle, GetCurrentThread(),
current_process_handle, &h,
0, FALSE, DUPLICATE_SAME_ACCESS))
return NULL;
return h;
}
/* simulate flock by locking a range on the file */
#define LK_ERR(f,i) \
do { \
if (f) \
i = 0; \
else { \
DWORD err = GetLastError(); \
if (err == ERROR_LOCK_VIOLATION || err == ERROR_IO_PENDING) \
errno = EWOULDBLOCK; \
else if (err == ERROR_NOT_LOCKED) \
i = 0; \
else \
errno = map_errno(err); \
} \
} while (0)
#define LK_LEN ULONG_MAX
static uintptr_t
flock_winnt(uintptr_t self, int argc, uintptr_t* argv)
{
OVERLAPPED o;
int i = -1;
const HANDLE fh = (HANDLE)self;
const int oper = argc;
memset(&o, 0, sizeof(o));
switch(oper) {
case LOCK_SH: /* shared lock */
LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, LK_LEN, &o), i);
break;
case LOCK_EX: /* exclusive lock */
LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, LK_LEN, &o), i);
break;
case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, LK_LEN, &o), i);
break;
case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
LK_ERR(LockFileEx(fh,
LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
0, LK_LEN, LK_LEN, &o), i);
break;
case LOCK_UN: /* unlock lock */
case LOCK_UN|LOCK_NB: /* unlock is always non-blocking, I hope */
LK_ERR(UnlockFileEx(fh, 0, LK_LEN, LK_LEN, &o), i);
break;
default: /* unknown */
errno = EINVAL;
break;
}
return i;
}
#ifdef WIN95
static uintptr_t
flock_win95(uintptr_t self, int argc, uintptr_t* argv)
{
int i = -1;
const HANDLE fh = (HANDLE)self;
const int oper = argc;
switch(oper) {
case LOCK_EX:
do {
LK_ERR(LockFile(fh, 0, 0, LK_LEN, LK_LEN), i);
} while (i && errno == EWOULDBLOCK);
break;
case LOCK_EX|LOCK_NB:
LK_ERR(LockFile(fh, 0, 0, LK_LEN, LK_LEN), i);
break;
case LOCK_UN:
case LOCK_UN|LOCK_NB:
LK_ERR(UnlockFile(fh, 0, 0, LK_LEN, LK_LEN), i);
break;
default:
errno = EINVAL;
break;
}
return i;
}
#endif
#undef LK_ERR
int
flock(int fd, int oper)
{
#ifdef WIN95
static asynchronous_func_t locker = NULL;
if (!locker) {
if (IsWinNT())
locker = flock_winnt;
else
locker = flock_win95;
}
#else
const asynchronous_func_t locker = flock_winnt;
#endif
return rb_w32_asynchronize(locker,
(VALUE)_get_osfhandle(fd), oper, NULL,
(DWORD)-1);
}
static inline WCHAR *
translate_wchar(WCHAR *p, int from, int to)
{
for (; *p; p++) {
if (*p == from)
*p = to;
}
return p;
}
static inline char *
translate_char(char *p, int from, int to)
{
while (*p) {
if ((unsigned char)*p == from)
*p = to;
p = CharNext(p);
}
return p;
}
#ifndef CSIDL_LOCAL_APPDATA
#define CSIDL_LOCAL_APPDATA 28
#endif
#ifndef CSIDL_COMMON_APPDATA
#define CSIDL_COMMON_APPDATA 35
#endif
#ifndef CSIDL_WINDOWS
#define CSIDL_WINDOWS 36
#endif
#ifndef CSIDL_SYSTEM
#define CSIDL_SYSTEM 37
#endif
#ifndef CSIDL_PROFILE
#define CSIDL_PROFILE 40
#endif
static BOOL
get_special_folder(int n, WCHAR *env)
{
LPITEMIDLIST pidl;
LPMALLOC alloc;
BOOL f = FALSE;
if (SHGetSpecialFolderLocation(NULL, n, &pidl) == 0) {
f = SHGetPathFromIDListW(pidl, env);
SHGetMalloc(&alloc);
alloc->lpVtbl->Free(alloc, pidl);
alloc->lpVtbl->Release(alloc);
}
return f;
}
static void
regulate_path(WCHAR *path)
{
WCHAR *p = translate_wchar(path, L'\\', L'/');
if (p - path == 2 && path[1] == L':') {
*p++ = L'/';
*p = L'\0';
}
}
static FARPROC
get_proc_address(const char *module, const char *func, HANDLE *mh)
{
HANDLE h;
FARPROC ptr;
if (mh)
h = LoadLibrary(module);
else
h = GetModuleHandle(module);
if (!h)
return NULL;
ptr = GetProcAddress(h, func);
if (mh) {
if (ptr)
*mh = h;
else
FreeLibrary(h);
}
return ptr;
}
static UINT
get_system_directory(WCHAR *path, UINT len)
{
typedef UINT WINAPI wgetdir_func(WCHAR*, UINT);
FARPROC ptr =
get_proc_address("kernel32", "GetSystemWindowsDirectoryW", NULL);
if (ptr)
return (*(wgetdir_func *)ptr)(path, len);
return GetWindowsDirectoryW(path, len);
}
#define numberof(array) (sizeof(array) / sizeof(*array))
VALUE
rb_w32_special_folder(int type)
{
WCHAR path[_MAX_PATH];
if (!get_special_folder(type, path)) return Qnil;
regulate_path(path);
return rb_w32_conv_from_wchar(path, rb_filesystem_encoding());
}
UINT
rb_w32_system_tmpdir(WCHAR *path, UINT len)
{
static const WCHAR temp[] = L"temp";
WCHAR *p;
if (!get_special_folder(CSIDL_LOCAL_APPDATA, path)) {
if (get_system_directory(path, len)) return 0;
}
p = translate_wchar(path, L'\\', L'/');
if (*(p - 1) != L'/') *p++ = L'/';
if (p - path + numberof(temp) >= len) return 0;
memcpy(p, temp, sizeof(temp));
return p - path + numberof(temp) - 1;
}
static void
init_env(void)
{
static const WCHAR TMPDIR[] = L"TMPDIR";
struct {WCHAR name[6], eq, val[_MAX_PATH];} wk;
DWORD len;
BOOL f;
#define env wk.val
#define set_env_val(vname) do { \
typedef char namesizecheck[numberof(wk.name) < numberof(vname) - 1 ? -1 : 1]; \
WCHAR *const buf = wk.name + numberof(wk.name) - numberof(vname) + 1; \
MEMCPY(buf, vname, WCHAR, numberof(vname) - 1); \
_wputenv(buf); \
} while (0)
wk.eq = L'=';
if (!GetEnvironmentVariableW(L"HOME", env, numberof(env))) {
f = FALSE;
if (GetEnvironmentVariableW(L"HOMEDRIVE", env, numberof(env)))
len = lstrlenW(env);
else
len = 0;
if (GetEnvironmentVariableW(L"HOMEPATH", env + len, numberof(env) - len) || len) {
f = TRUE;
}
else if (GetEnvironmentVariableW(L"USERPROFILE", env, numberof(env))) {
f = TRUE;
}
else if (get_special_folder(CSIDL_PROFILE, env)) {
f = TRUE;
}
else if (get_special_folder(CSIDL_PERSONAL, env)) {
f = TRUE;
}
if (f) {
regulate_path(env);
set_env_val(L"HOME");
}
}
if (!GetEnvironmentVariableW(L"USER", env, numberof(env))) {
if (!GetEnvironmentVariableW(L"USERNAME", env, numberof(env)) &&
!GetUserNameW(env, (len = numberof(env), &len))) {
NTLoginName = "<Unknown>";
return;
}
set_env_val(L"USER");
}
NTLoginName = strdup(rb_w32_getenv("USER"));
if (!GetEnvironmentVariableW(TMPDIR, env, numberof(env)) &&
!GetEnvironmentVariableW(L"TMP", env, numberof(env)) &&
!GetEnvironmentVariableW(L"TEMP", env, numberof(env)) &&
rb_w32_system_tmpdir(env, numberof(env))) {
set_env_val(TMPDIR);
}
#undef env
#undef set_env_val
}
typedef BOOL (WINAPI *cancel_io_t)(HANDLE);
static cancel_io_t cancel_io = NULL;
int
rb_w32_has_cancel_io(void)
{
return cancel_io != NULL;
}
static void
init_func(void)
{
if (!cancel_io)
cancel_io = (cancel_io_t)get_proc_address("kernel32", "CancelIo", NULL);
}
static void init_stdhandle(void);
#if RT_VER >= 80
static void
invalid_parameter(const wchar_t *expr, const wchar_t *func, const wchar_t *file, unsigned int line, uintptr_t dummy)
{
// nothing to do
}
int ruby_w32_rtc_error;
static int __cdecl
rtc_error_handler(int e, const char *src, int line, const char *exe, const char *fmt, ...)
{
va_list ap;
VALUE str;
if (!ruby_w32_rtc_error) return 0;
str = rb_sprintf("%s:%d: ", src, line);
va_start(ap, fmt);
rb_str_vcatf(str, fmt, ap);
va_end(ap);
rb_str_cat(str, "\n", 1);
rb_write_error2(RSTRING_PTR(str), RSTRING_LEN(str));
return 0;
}
#endif
static CRITICAL_SECTION select_mutex;
static int NtSocketsInitialized = 0;
static st_table *socklist = NULL;
static char *envarea;
static void
exit_handler(void)
{
if (NtSocketsInitialized) {
WSACleanup();
st_free_table(socklist);
socklist = NULL;
NtSocketsInitialized = 0;
}
if (envarea) {
FreeEnvironmentStrings(envarea);
envarea = NULL;
}
DeleteCriticalSection(&select_mutex);
}
static void
StartSockets(void)
{
WORD version;
WSADATA retdata;
//
// initalize the winsock interface and insure that it's
// cleaned up at exit.
//
version = MAKEWORD(2, 0);
if (WSAStartup(version, &retdata))
rb_fatal ("Unable to locate winsock library!\n");
if (LOBYTE(retdata.wVersion) != 2)
rb_fatal("could not find version 2 of winsock dll\n");
socklist = st_init_numtable();
NtSocketsInitialized = 1;
}
//
// Initialization stuff
//
void
rb_w32_sysinit(int *argc, char ***argv)
{
#if RT_VER >= 80
static void set_pioinfo_extra(void);
_CrtSetReportMode(_CRT_ASSERT, 0);
_set_invalid_parameter_handler(invalid_parameter);
_RTC_SetErrorFunc(rtc_error_handler);
set_pioinfo_extra();
#endif
get_version();
//
// subvert cmd.exe's feeble attempt at command line parsing
//
*argc = rb_w32_cmdvector(GetCommandLine(), argv);
//
// Now set up the correct time stuff
//
tzset();
init_env();
init_func();
init_stdhandle();
InitializeCriticalSection(&select_mutex);
atexit(exit_handler);
// Initialize Winsock
StartSockets();
}
char *
getlogin(void)
{
return (char *)NTLoginName;
}
#define MAXCHILDNUM 256 /* max num of child processes */
static struct ChildRecord {
HANDLE hProcess; /* process handle */
rb_pid_t pid; /* process id */
} ChildRecord[MAXCHILDNUM];
#define FOREACH_CHILD(v) do { \
struct ChildRecord* v; \
for (v = ChildRecord; v < ChildRecord + sizeof(ChildRecord) / sizeof(ChildRecord[0]); ++v)
#define END_FOREACH_CHILD } while (0)
static struct ChildRecord *
FindChildSlot(rb_pid_t pid)
{
FOREACH_CHILD(child) {
if (child->pid == pid) {
return child;
}
} END_FOREACH_CHILD;
return NULL;
}
static struct ChildRecord *
FindChildSlotByHandle(HANDLE h)
{
FOREACH_CHILD(child) {
if (child->hProcess == h) {
return child;
}
} END_FOREACH_CHILD;
return NULL;
}
static void
CloseChildHandle(struct ChildRecord *child)
{
HANDLE h = child->hProcess;
child->hProcess = NULL;
child->pid = 0;
CloseHandle(h);
}
static struct ChildRecord *
FindFreeChildSlot(void)
{
FOREACH_CHILD(child) {
if (!child->pid) {
child->pid = -1; /* lock the slot */
child->hProcess = NULL;
return child;
}
} END_FOREACH_CHILD;
return NULL;
}
/*
ruby -lne 'BEGIN{$cmds = Hash.new(0); $mask = 1}'
-e '$cmds[$_.downcase] |= $mask' -e '$mask <<= 1 if ARGF.eof'
-e 'END{$cmds.sort.each{|n,f|puts " \"\\#{f.to_s(8)}\" #{n.dump} + 1,"}}'
98cmd ntcmd
*/
static const char *const szInternalCmds[] = {
"\2" "assoc" + 1,
"\3" "break" + 1,
"\3" "call" + 1,
"\3" "cd" + 1,
"\1" "chcp" + 1,
"\3" "chdir" + 1,
"\3" "cls" + 1,
"\2" "color" + 1,
"\3" "copy" + 1,
"\1" "ctty" + 1,
"\3" "date" + 1,
"\3" "del" + 1,
"\3" "dir" + 1,
"\3" "echo" + 1,
"\2" "endlocal" + 1,
"\3" "erase" + 1,
"\3" "exit" + 1,
"\3" "for" + 1,
"\2" "ftype" + 1,
"\3" "goto" + 1,
"\3" "if" + 1,
"\1" "lfnfor" + 1,
"\1" "lh" + 1,
"\1" "lock" + 1,
"\3" "md" + 1,
"\3" "mkdir" + 1,
"\2" "move" + 1,
"\3" "path" + 1,
"\3" "pause" + 1,
"\2" "popd" + 1,
"\3" "prompt" + 1,
"\2" "pushd" + 1,
"\3" "rd" + 1,
"\3" "rem" + 1,
"\3" "ren" + 1,
"\3" "rename" + 1,
"\3" "rmdir" + 1,
"\3" "set" + 1,
"\2" "setlocal" + 1,
"\3" "shift" + 1,
"\2" "start" + 1,
"\3" "time" + 1,
"\2" "title" + 1,
"\1" "truename" + 1,
"\3" "type" + 1,
"\1" "unlock" + 1,
"\3" "ver" + 1,
"\3" "verify" + 1,
"\3" "vol" + 1,
};
static int
internal_match(const void *key, const void *elem)
{
return strcmp(key, *(const char *const *)elem);
}
static int
is_command_com(const char *interp)
{
int i = strlen(interp) - 11;
if ((i == 0 || i > 0 && isdirsep(interp[i-1])) &&
strcasecmp(interp+i, "command.com") == 0) {
return 1;
}
return 0;
}
static int internal_cmd_match(const char *cmdname, int nt);
static int
is_internal_cmd(const char *cmd, int nt)
{
char cmdname[9], *b = cmdname, c;
do {
if (!(c = *cmd++)) return 0;
} while (isspace(c));
if (c == '@')
return 1;
while (isalpha(c)) {
*b++ = tolower(c);
if (b == cmdname + sizeof(cmdname)) return 0;
c = *cmd++;
}
if (c == '.') c = *cmd;
switch (c) {
case '<': case '>': case '|':
return 1;
case '\0': case ' ': case '\t': case '\n':
break;
default:
return 0;
}
*b = 0;
return internal_cmd_match(cmdname, nt);
}
static int
internal_cmd_match(const char *cmdname, int nt)
{
char **nm;
nm = bsearch(cmdname, szInternalCmds,
sizeof(szInternalCmds) / sizeof(*szInternalCmds),
sizeof(*szInternalCmds),
internal_match);
if (!nm || !(nm[0][-1] & (nt ? 2 : 1)))
return 0;
return 1;
}
SOCKET
rb_w32_get_osfhandle(int fh)
{
return _get_osfhandle(fh);
}
static int
join_argv(char *cmd, char *const *argv, BOOL escape)
{
const char *p, *s;
char *q, *const *t;
int len, n, bs, quote;
for (t = argv, q = cmd, len = 0; p = *t; t++) {
quote = 0;
s = p;
if (!*p || strpbrk(p, " \t\"'")) {
quote = 1;
len++;
if (q) *q++ = '"';
}
for (bs = 0; *p; ++p) {
switch (*p) {
case '\\':
++bs;
break;
case '"':
len += n = p - s;
if (q) {
memcpy(q, s, n);
q += n;
}
s = p;
len += ++bs;
if (q) {
memset(q, '\\', bs);
q += bs;
}
bs = 0;
break;
case '<': case '>': case '|': case '^':
if (escape && !quote) {
len += (n = p - s) + 1;
if (q) {
memcpy(q, s, n);
q += n;
*q++ = '^';
}
s = p;
break;
}
default:
bs = 0;
p = CharNext(p) - 1;
break;
}
}
len += (n = p - s) + 1;
if (quote) len++;
if (q) {
memcpy(q, s, n);
q += n;
if (quote) *q++ = '"';
*q++ = ' ';
}
}
if (q > cmd) --len;
if (q) {
if (q > cmd) --q;
*q = '\0';
}
return len;
}
#ifdef HAVE_SYS_PARAM_H
# include <sys/param.h>
#else
# define MAXPATHLEN 512
#endif
#define STRNDUPV(ptr, v, src, len) \
(((char *)memcpy(((ptr) = ALLOCV((v), (len) + 1)), (src), (len)))[len] = 0)
static int
check_spawn_mode(int mode)
{
switch (mode) {
case P_NOWAIT:
case P_OVERLAY:
return 0;
default:
errno = EINVAL;
return -1;
}
}
static rb_pid_t
child_result(struct ChildRecord *child, int mode)
{
DWORD exitcode;
if (!child) {
return -1;
}
switch (mode) {
case P_NOWAIT:
return child->pid;
case P_OVERLAY:
WaitForSingleObject(child->hProcess, INFINITE);