3 * (c) 1995 Microsoft Corporation. All rights reserved.
4 * Developed by hip communications inc., http://info.hip.com/info/
5 * Portions (c) 1993 Intergraph Corporation. All rights reserved.
7 * You may distribute under the terms of either the GNU General Public
8 * License or the Artistic License, as specified in the README file.
11 #define WIN32_LEAN_AND_MEAN
12 #define WIN32IO_IS_STDIO
17 #undef __attribute__ /* seems broken in 2.8.0 */
18 #define __attribute__(p)
26 /* ugliness to work around a buggy struct definition in lmwksta.h */
33 #endif /* __MINGW32__ */
35 /* #include "config.h" */
37 #define PERLIO_NOT_STDIO 0
38 #if !defined(PERLIO_IS_STDIO) && !defined(USE_SFIO)
47 extern CPerlObj* pPerl;
55 /* assert.h conflicts with #define of assert in perl.h */
62 #if defined(_MSC_VER) || defined(__MINGW32__)
63 #include <sys/utime.h>
69 /* Mingw32 defaults to globing command line
70 * So we turn it off like this:
77 #define EXECF_SPAWN_NOWAIT 3
79 #if defined(PERL_OBJECT)
80 #undef win32_get_privlib
81 #define win32_get_privlib g_win32_get_privlib
82 #undef win32_get_sitelib
83 #define win32_get_sitelib g_win32_get_sitelib
85 #define do_aspawn g_do_aspawn
87 #define do_spawn g_do_spawn
89 #define do_exec g_do_exec
91 #define opendir g_opendir
93 #define readdir g_readdir
95 #define telldir g_telldir
97 #define seekdir g_seekdir
99 #define rewinddir g_rewinddir
101 #define closedir g_closedir
103 #define getlogin g_getlogin
106 static DWORD os_id(void);
107 static void get_shell(void);
108 static long tokenize(char *str, char **dest, char ***destv);
109 int do_spawn2(char *cmd, int exectype);
110 static BOOL has_redirection(char *ptr);
111 static long filetime_to_clock(PFILETIME ft);
112 static BOOL filetime_from_time(PFILETIME ft, time_t t);
113 static char * get_emd_part(char *leading, char *trailing, ...);
114 static void remove_dead_process(HANDLE deceased);
116 HANDLE w32_perldll_handle = INVALID_HANDLE_VALUE;
117 static DWORD w32_platform = (DWORD)-1;
120 # ifdef USE_DECLSPEC_THREAD
121 __declspec(thread) char strerror_buffer[512];
122 __declspec(thread) char getlogin_buffer[128];
123 __declspec(thread) char w32_perllib_root[MAX_PATH+1];
124 # ifdef HAVE_DES_FCRYPT
125 __declspec(thread) char crypt_buffer[30];
128 # define strerror_buffer (thr->i.Wstrerror_buffer)
129 # define getlogin_buffer (thr->i.Wgetlogin_buffer)
130 # define w32_perllib_root (thr->i.Ww32_perllib_root)
131 # define crypt_buffer (thr->i.Wcrypt_buffer)
134 static char strerror_buffer[512];
135 static char getlogin_buffer[128];
136 static char w32_perllib_root[MAX_PATH+1];
137 # ifdef HAVE_DES_FCRYPT
138 static char crypt_buffer[30];
144 return (os_id() == VER_PLATFORM_WIN32_WINDOWS);
149 return (os_id() == VER_PLATFORM_WIN32_NT);
153 GetRegStrFromKey(HKEY hkey, const char *lpszValueName, char** ptr, DWORD* lpDataLen)
154 { /* Retrieve a REG_SZ or REG_EXPAND_SZ from the registry */
157 const char *subkey = "Software\\Perl";
160 retval = RegOpenKeyEx(hkey, subkey, 0, KEY_READ, &handle);
161 if (retval == ERROR_SUCCESS){
162 retval = RegQueryValueEx(handle, lpszValueName, 0, &type, NULL, lpDataLen);
163 if (retval == ERROR_SUCCESS && type == REG_SZ) {
165 Renew(*ptr, *lpDataLen, char);
168 New(1312, *ptr, *lpDataLen, char);
170 retval = RegQueryValueEx(handle, lpszValueName, 0, NULL, (PBYTE)*ptr, lpDataLen);
171 if (retval != ERROR_SUCCESS) {
182 GetRegStr(const char *lpszValueName, char** ptr, DWORD* lpDataLen)
184 *ptr = GetRegStrFromKey(HKEY_CURRENT_USER, lpszValueName, ptr, lpDataLen);
187 *ptr = GetRegStrFromKey(HKEY_LOCAL_MACHINE, lpszValueName, ptr, lpDataLen);
193 get_emd_part(char *prev_path, char *trailing_path, ...)
196 char mod_name[MAX_PATH];
200 int oldsize, newsize;
202 va_start(ap, trailing_path);
203 strip = va_arg(ap, char *);
205 GetModuleFileName(GetModuleHandle(NULL), mod_name, sizeof(mod_name));
206 ptr = strrchr(mod_name, '\\');
207 while (ptr && strip) {
208 /* look for directories to skip back */
211 ptr = strrchr(mod_name, '\\');
212 if (!ptr || stricmp(ptr+1, strip) != 0) {
216 strip = va_arg(ap, char *);
224 strcpy(++ptr, trailing_path);
226 newsize = strlen(mod_name) + 1;
228 oldsize = strlen(prev_path) + 1;
229 newsize += oldsize; /* includes plus 1 for ';' */
230 Renew(prev_path, newsize, char);
231 prev_path[oldsize] = ';';
232 strcpy(&prev_path[oldsize], mod_name);
235 New(1311, prev_path, newsize, char);
236 strcpy(prev_path, mod_name);
243 win32_get_privlib(char *pl)
245 char *stdlib = "lib";
246 char buffer[MAX_PATH+1];
250 /* $stdlib = $HKCU{"lib-$]"} || $HKLM{"lib-$]"} || $HKCU{"lib"} || $HKLM{"lib"} || ""; */
251 sprintf(buffer, "%s-%s", stdlib, pl);
252 path = GetRegStr(buffer, &path, &datalen);
254 path = GetRegStr(stdlib, &path, &datalen);
256 /* $stdlib .= ";$EMD/../../lib" */
257 return get_emd_part(path, stdlib, ARCHNAME, "bin", Nullch);
261 win32_get_sitelib(char *pl)
263 char *sitelib = "sitelib";
265 char pathstr[MAX_PATH];
267 char *path1 = Nullch;
268 char *path2 = Nullch;
271 /* $HKCU{"sitelib-$]"} || $HKLM{"sitelib-$]"} . ---; */
272 sprintf(regstr, "%s-%s", sitelib, pl);
273 path1 = GetRegStr(regstr, &path1, &datalen);
276 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/$]/lib"; */
277 sprintf(pathstr, "site\\%s\\lib", pl);
278 path1 = get_emd_part(path1, pathstr, ARCHNAME, "bin", pl, Nullch);
280 /* $HKCU{'sitelib'} || $HKLM{'sitelib'} . ---; */
281 path2 = GetRegStr(sitelib, &path2, &datalen);
284 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/lib"; */
285 path2 = get_emd_part(path2, "site\\lib", ARCHNAME, "bin", pl, Nullch);
294 newsize = len + strlen(path2) + 2; /* plus one for ';' */
296 Renew(path1, newsize, char);
298 strcpy(&path1[len], path2);
306 has_redirection(char *ptr)
312 * Scan string looking for redirection (< or >) or pipe
313 * characters (|) that are not in a quoted string
343 #if !defined(PERL_OBJECT)
344 /* since the current process environment is being updated in util.c
345 * the library functions will get the correct environment
348 my_popen(char *cmd, char *mode)
351 #define fixcmd(x) { \
352 char *pspace = strchr((x),' '); \
355 while (p < pspace) { \
366 win32_fflush(stdout);
367 win32_fflush(stderr);
368 return win32_popen(cmd, mode);
372 my_pclose(PerlIO *fp)
374 return win32_pclose(fp);
381 static OSVERSIONINFO osver;
383 if (osver.dwPlatformId != w32_platform) {
384 memset(&osver, 0, sizeof(OSVERSIONINFO));
385 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
386 GetVersionEx(&osver);
387 w32_platform = osver.dwPlatformId;
389 return (w32_platform);
392 /* Tokenize a string. Words are null-separated, and the list
393 * ends with a doubled null. Any character (except null and
394 * including backslash) may be escaped by preceding it with a
395 * backslash (the backslash will be stripped).
396 * Returns number of words in result buffer.
399 tokenize(char *str, char **dest, char ***destv)
401 char *retstart = Nullch;
402 char **retvstart = 0;
405 int slen = strlen(str);
407 register char **retv;
408 New(1307, ret, slen+2, char);
409 New(1308, retv, (slen+3)/2, char*);
417 if (*ret == '\\' && *str)
419 else if (*ret == ' ') {
435 retvstart[items] = Nullch;
447 if (!w32_perlshell_tokens) {
448 /* we don't use COMSPEC here for two reasons:
449 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
450 * uncontrolled unportability of the ensuing scripts.
451 * 2. PERL5SHELL could be set to a shell that may not be fit for
452 * interactive use (which is what most programs look in COMSPEC
455 char* defaultshell = (IsWinNT() ? "cmd.exe /x/c" : "command.com /c");
456 char *usershell = getenv("PERL5SHELL");
457 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
458 &w32_perlshell_tokens,
464 do_aspawn(void *vreally, void **vmark, void **vsp)
466 SV *really = (SV*)vreally;
467 SV **mark = (SV**)vmark;
479 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
481 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
486 while (++mark <= sp) {
487 if (*mark && (str = SvPV(*mark, na)))
494 status = win32_spawnvp(flag,
495 (const char*)(really ? SvPV(really,na) : argv[0]),
496 (const char* const*)argv);
498 if (status < 0 && errno == ENOEXEC) {
499 /* possible shell-builtin, invoke with shell */
501 sh_items = w32_perlshell_items;
503 argv[index+sh_items] = argv[index];
504 while (--sh_items >= 0)
505 argv[sh_items] = w32_perlshell_vec[sh_items];
507 status = win32_spawnvp(flag,
508 (const char*)(really ? SvPV(really,na) : argv[0]),
509 (const char* const*)argv);
512 if (flag != P_NOWAIT) {
515 warn("Can't spawn \"%s\": %s", argv[0], strerror(errno));
520 statusvalue = status;
527 do_spawn2(char *cmd, int exectype)
533 BOOL needToTry = TRUE;
536 /* Save an extra exec if possible. See if there are shell
537 * metacharacters in it */
538 if (!has_redirection(cmd)) {
539 New(1301,argv, strlen(cmd) / 2 + 2, char*);
540 New(1302,cmd2, strlen(cmd) + 1, char);
543 for (s = cmd2; *s;) {
544 while (*s && isspace(*s))
548 while (*s && !isspace(*s))
557 status = win32_spawnvp(P_WAIT, argv[0],
558 (const char* const*)argv);
560 case EXECF_SPAWN_NOWAIT:
561 status = win32_spawnvp(P_NOWAIT, argv[0],
562 (const char* const*)argv);
565 status = win32_execvp(argv[0], (const char* const*)argv);
568 if (status != -1 || errno == 0)
578 New(1306, argv, w32_perlshell_items + 2, char*);
579 while (++i < w32_perlshell_items)
580 argv[i] = w32_perlshell_vec[i];
585 status = win32_spawnvp(P_WAIT, argv[0],
586 (const char* const*)argv);
588 case EXECF_SPAWN_NOWAIT:
589 status = win32_spawnvp(P_NOWAIT, argv[0],
590 (const char* const*)argv);
593 status = win32_execvp(argv[0], (const char* const*)argv);
599 if (exectype != EXECF_SPAWN_NOWAIT) {
602 warn("Can't %s \"%s\": %s",
603 (exectype == EXECF_EXEC ? "exec" : "spawn"),
604 cmd, strerror(errno));
609 statusvalue = status;
617 return do_spawn2(cmd, EXECF_SPAWN);
621 do_spawn_nowait(char *cmd)
623 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
629 do_spawn2(cmd, EXECF_EXEC);
633 /* The idea here is to read all the directory names into a string table
634 * (separated by nulls) and when one of the other dir functions is called
635 * return the pointer to the current file name.
638 opendir(char *filename)
643 char scanname[MAX_PATH+3];
645 WIN32_FIND_DATA FindData;
648 len = strlen(filename);
652 /* check to see if filename is a directory */
653 if (win32_stat(filename, &sbuf) < 0 || (sbuf.st_mode & S_IFDIR) == 0) {
654 /* CRT is buggy on sharenames, so make sure it really isn't */
655 DWORD r = GetFileAttributes(filename);
656 if (r == 0xffffffff || !(r & FILE_ATTRIBUTE_DIRECTORY))
660 /* Get us a DIR structure */
661 Newz(1303, p, 1, DIR);
665 /* Create the search pattern */
666 strcpy(scanname, filename);
667 if (scanname[len-1] != '/' && scanname[len-1] != '\\')
668 scanname[len++] = '/';
669 scanname[len++] = '*';
670 scanname[len] = '\0';
672 /* do the FindFirstFile call */
673 fh = FindFirstFile(scanname, &FindData);
674 if (fh == INVALID_HANDLE_VALUE) {
678 /* now allocate the first part of the string table for
679 * the filenames that we find.
681 idx = strlen(FindData.cFileName)+1;
682 New(1304, p->start, idx, char);
683 if (p->start == NULL)
684 croak("opendir: malloc failed!\n");
685 strcpy(p->start, FindData.cFileName);
688 /* loop finding all the files that match the wildcard
689 * (which should be all of them in this directory!).
690 * the variable idx should point one past the null terminator
691 * of the previous string found.
693 while (FindNextFile(fh, &FindData)) {
694 len = strlen(FindData.cFileName);
695 /* bump the string table size by enough for the
696 * new name and it's null terminator
698 Renew(p->start, idx+len+1, char);
699 if (p->start == NULL)
700 croak("opendir: malloc failed!\n");
701 strcpy(&p->start[idx], FindData.cFileName);
712 /* Readdir just returns the current string pointer and bumps the
713 * string pointer to the nDllExport entry.
719 static int dummy = 0;
722 /* first set up the structure to return */
723 len = strlen(dirp->curr);
724 strcpy(dirp->dirstr.d_name, dirp->curr);
725 dirp->dirstr.d_namlen = len;
728 dirp->dirstr.d_ino = dummy++;
730 /* Now set up for the nDllExport call to readdir */
731 dirp->curr += len + 1;
732 if (dirp->curr >= (dirp->start + dirp->size)) {
736 return &(dirp->dirstr);
742 /* Telldir returns the current string pointer position */
746 return (long) dirp->curr;
750 /* Seekdir moves the string pointer to a previously saved position
754 seekdir(DIR *dirp, long loc)
756 dirp->curr = (char *)loc;
759 /* Rewinddir resets the string pointer to the start */
763 dirp->curr = dirp->start;
766 /* free the memory allocated by opendir */
770 Safefree(dirp->start);
783 * Just pretend that everyone is a superuser. NT will let us know if
784 * we don\'t really have permission to do something.
787 #define ROOT_UID ((uid_t)0)
788 #define ROOT_GID ((gid_t)0)
817 return (auid == ROOT_UID ? 0 : -1);
823 return (agid == ROOT_GID ? 0 : -1);
830 char *buf = getlogin_buffer;
831 DWORD size = sizeof(getlogin_buffer);
832 if (GetUserName(buf,&size))
838 chown(const char *path, uid_t owner, gid_t group)
845 remove_dead_process(HANDLE deceased)
849 for (child = 0 ; child < w32_num_children ; ++child) {
850 if (w32_child_pids[child] == deceased) {
851 Copy(&w32_child_pids[child+1], &w32_child_pids[child],
852 (w32_num_children-child-1), HANDLE);
861 win32_kill(int pid, int sig)
864 HANDLE hProcess= OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
866 HANDLE hProcess = (HANDLE) pid;
869 if (hProcess == NULL) {
870 croak("kill process failed!\n");
873 if (!TerminateProcess(hProcess, sig))
874 croak("kill process failed!\n");
875 CloseHandle(hProcess);
877 /* WaitForMultipleObjects() on a pid that was killed returns error
878 * so if we know the pid is gone we remove it from process list */
879 remove_dead_process(hProcess);
888 DllExport unsigned int
889 win32_sleep(unsigned int t)
896 win32_stat(const char *path, struct stat *buffer)
899 const char *p = path;
900 int l = strlen(path);
904 switch(path[l - 1]) {
907 if (path[l - 2] != ':') {
908 strncpy(t, path, l - 1);
914 res = stat(p,buffer);
917 if (S_ISDIR(buffer->st_mode))
918 buffer->st_mode |= S_IWRITE | S_IEXEC;
919 else if (S_ISREG(buffer->st_mode)) {
920 if (l >= 4 && path[l-4] == '.') {
921 const char *e = path + l - 3;
922 if (strnicmp(e,"exe",3)
923 && strnicmp(e,"bat",3)
924 && strnicmp(e,"com",3)
925 && (IsWin95() || strnicmp(e,"cmd",3)))
926 buffer->st_mode &= ~S_IEXEC;
928 buffer->st_mode |= S_IEXEC;
931 buffer->st_mode &= ~S_IEXEC;
938 #ifndef USE_WIN32_RTL_ENV
941 win32_getenv(const char *name)
943 static char *curitem = Nullch;
944 static DWORD curlen = 512;
947 New(1305,curitem,curlen,char);
949 needlen = GetEnvironmentVariable(name,curitem,curlen);
951 while (needlen > curlen) {
952 Renew(curitem,needlen,char);
954 needlen = GetEnvironmentVariable(name,curitem,curlen);
959 /* allow any environment variables that begin with 'PERL5'
960 to be stored in the registry
965 if (strncmp(name, "PERL5", 5) == 0) {
966 if (curitem != NULL) {
970 curitem = GetRegStr(name, &curitem, &curlen);
973 if(curitem != NULL && *curitem == '\0')
982 filetime_to_clock(PFILETIME ft)
984 __int64 qw = ft->dwHighDateTime;
986 qw |= ft->dwLowDateTime;
987 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
992 win32_times(struct tms *timebuf)
997 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
999 timebuf->tms_utime = filetime_to_clock(&user);
1000 timebuf->tms_stime = filetime_to_clock(&kernel);
1001 timebuf->tms_cutime = 0;
1002 timebuf->tms_cstime = 0;
1005 /* That failed - e.g. Win95 fallback to clock() */
1006 clock_t t = clock();
1007 timebuf->tms_utime = t;
1008 timebuf->tms_stime = 0;
1009 timebuf->tms_cutime = 0;
1010 timebuf->tms_cstime = 0;
1015 /* fix utime() so it works on directories in NT
1016 * thanks to Jan Dubois <jan.dubois@ibm.net>
1019 filetime_from_time(PFILETIME pFileTime, time_t Time)
1021 struct tm *pTM = gmtime(&Time);
1022 SYSTEMTIME SystemTime;
1027 SystemTime.wYear = pTM->tm_year + 1900;
1028 SystemTime.wMonth = pTM->tm_mon + 1;
1029 SystemTime.wDay = pTM->tm_mday;
1030 SystemTime.wHour = pTM->tm_hour;
1031 SystemTime.wMinute = pTM->tm_min;
1032 SystemTime.wSecond = pTM->tm_sec;
1033 SystemTime.wMilliseconds = 0;
1035 return SystemTimeToFileTime(&SystemTime, pFileTime);
1039 win32_utime(const char *filename, struct utimbuf *times)
1045 struct utimbuf TimeBuffer;
1047 int rc = utime(filename,times);
1048 /* EACCES: path specifies directory or readonly file */
1049 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
1052 if (times == NULL) {
1053 times = &TimeBuffer;
1054 time(×->actime);
1055 times->modtime = times->actime;
1058 /* This will (and should) still fail on readonly files */
1059 handle = CreateFile(filename, GENERIC_READ | GENERIC_WRITE,
1060 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1061 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1062 if (handle == INVALID_HANDLE_VALUE)
1065 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
1066 filetime_from_time(&ftAccess, times->actime) &&
1067 filetime_from_time(&ftWrite, times->modtime) &&
1068 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
1073 CloseHandle(handle);
1078 win32_waitpid(int pid, int *status, int flags)
1082 return win32_wait(status);
1084 rc = cwait(status, pid, WAIT_CHILD);
1085 /* cwait() returns differently on Borland */
1088 *status = (((*status >> 8) & 0xff) | ((*status << 8) & 0xff00));
1090 remove_dead_process((HANDLE)pid);
1092 return rc >= 0 ? pid : rc;
1096 win32_wait(int *status)
1099 return wait(status);
1101 /* XXX this wait emulation only knows about processes
1102 * spawned via win32_spawnvp(P_NOWAIT, ...).
1105 DWORD exitcode, waitcode;
1107 if (!w32_num_children) {
1112 /* if a child exists, wait for it to die */
1113 waitcode = WaitForMultipleObjects(w32_num_children,
1117 if (waitcode != WAIT_FAILED) {
1118 if (waitcode >= WAIT_ABANDONED_0
1119 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1120 i = waitcode - WAIT_ABANDONED_0;
1122 i = waitcode - WAIT_OBJECT_0;
1123 if (GetExitCodeProcess(w32_child_pids[i], &exitcode) ) {
1124 CloseHandle(w32_child_pids[i]);
1125 *status = (int)((exitcode & 0xff) << 8);
1126 retval = (int)w32_child_pids[i];
1127 Copy(&w32_child_pids[i+1], &w32_child_pids[i],
1128 (w32_num_children-i-1), HANDLE);
1135 errno = GetLastError();
1141 static UINT timerid = 0;
1143 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1145 KillTimer(NULL,timerid);
1150 DllExport unsigned int
1151 win32_alarm(unsigned int sec)
1154 * the 'obvious' implentation is SetTimer() with a callback
1155 * which does whatever receiving SIGALRM would do
1156 * we cannot use SIGALRM even via raise() as it is not
1157 * one of the supported codes in <signal.h>
1159 * Snag is unless something is looking at the message queue
1160 * nothing happens :-(
1164 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1166 croak("Cannot set timer");
1172 KillTimer(NULL,timerid);
1179 #ifdef HAVE_DES_FCRYPT
1180 extern char * des_fcrypt(char *cbuf, const char *txt, const char *salt);
1183 win32_crypt(const char *txt, const char *salt)
1186 return des_fcrypt(crypt_buffer, txt, salt);
1190 #ifdef USE_FIXED_OSFHANDLE
1192 EXTERN_C int __cdecl _alloc_osfhnd(void);
1193 EXTERN_C int __cdecl _set_osfhnd(int fh, long value);
1194 EXTERN_C void __cdecl _lock_fhandle(int);
1195 EXTERN_C void __cdecl _unlock_fhandle(int);
1196 EXTERN_C void __cdecl _unlock(int);
1198 #if (_MSC_VER >= 1000)
1200 long osfhnd; /* underlying OS file HANDLE */
1201 char osfile; /* attributes of file (e.g., open in text mode?) */
1202 char pipech; /* one char buffer for handles opened on pipes */
1203 #if defined (_MT) && !defined (DLL_FOR_WIN32S)
1205 CRITICAL_SECTION lock;
1206 #endif /* defined (_MT) && !defined (DLL_FOR_WIN32S) */
1209 EXTERN_C ioinfo * __pioinfo[];
1211 #define IOINFO_L2E 5
1212 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
1213 #define _pioinfo(i) (__pioinfo[i >> IOINFO_L2E] + (i & (IOINFO_ARRAY_ELTS - 1)))
1214 #define _osfile(i) (_pioinfo(i)->osfile)
1216 #else /* (_MSC_VER >= 1000) */
1217 extern char _osfile[];
1218 #endif /* (_MSC_VER >= 1000) */
1220 #define FOPEN 0x01 /* file handle open */
1221 #define FAPPEND 0x20 /* file handle opened O_APPEND */
1222 #define FDEV 0x40 /* file handle refers to device */
1223 #define FTEXT 0x80 /* file handle is in text mode */
1225 #define _STREAM_LOCKS 26 /* Table of stream locks */
1226 #define _LAST_STREAM_LOCK (_STREAM_LOCKS+_NSTREAM_-1) /* Last stream lock */
1227 #define _FH_LOCKS (_LAST_STREAM_LOCK+1) /* Table of fh locks */
1230 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1233 * This function allocates a free C Runtime file handle and associates
1234 * it with the Win32 HANDLE specified by the first parameter. This is a
1235 * temperary fix for WIN95's brain damage GetFileType() error on socket
1236 * we just bypass that call for socket
1239 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1240 * int flags - flags to associate with C Runtime file handle.
1243 * returns index of entry in fh, if successful
1244 * return -1, if no free entry is found
1248 *******************************************************************************/
1251 my_open_osfhandle(long osfhandle, int flags)
1254 char fileflags; /* _osfile flags */
1256 /* copy relevant flags from second parameter */
1259 if (flags & O_APPEND)
1260 fileflags |= FAPPEND;
1265 /* attempt to allocate a C Runtime file handle */
1266 if ((fh = _alloc_osfhnd()) == -1) {
1267 errno = EMFILE; /* too many open files */
1268 _doserrno = 0L; /* not an OS error */
1269 return -1; /* return error to caller */
1272 /* the file is open. now, set the info in _osfhnd array */
1273 _set_osfhnd(fh, osfhandle);
1275 fileflags |= FOPEN; /* mark as open */
1277 #if (_MSC_VER >= 1000)
1278 _osfile(fh) = fileflags; /* set osfile entry */
1279 _unlock_fhandle(fh);
1281 _osfile[fh] = fileflags; /* set osfile entry */
1282 _unlock(fh+_FH_LOCKS); /* unlock handle */
1285 return fh; /* return handle */
1288 #define _open_osfhandle my_open_osfhandle
1289 #endif /* USE_FIXED_OSFHANDLE */
1291 /* simulate flock by locking a range on the file */
1293 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1294 #define LK_LEN 0xffff0000
1297 win32_flock(int fd, int oper)
1304 croak("flock() unimplemented on this platform");
1307 fh = (HANDLE)_get_osfhandle(fd);
1308 memset(&o, 0, sizeof(o));
1311 case LOCK_SH: /* shared lock */
1312 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1314 case LOCK_EX: /* exclusive lock */
1315 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1317 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1318 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1320 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1321 LK_ERR(LockFileEx(fh,
1322 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1323 0, LK_LEN, 0, &o),i);
1325 case LOCK_UN: /* unlock lock */
1326 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1328 default: /* unknown */
1339 * redirected io subsystem for all XS modules
1352 return (&(_environ));
1355 /* the rest are the remapped stdio routines */
1375 win32_ferror(FILE *fp)
1377 return (ferror(fp));
1382 win32_feof(FILE *fp)
1388 * Since the errors returned by the socket error function
1389 * WSAGetLastError() are not known by the library routine strerror
1390 * we have to roll our own.
1394 win32_strerror(int e)
1396 #ifndef __BORLANDC__ /* Borland intolerance */
1397 extern int sys_nerr;
1401 if (e < 0 || e > sys_nerr) {
1406 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
1407 strerror_buffer, sizeof(strerror_buffer), NULL) == 0)
1408 strcpy(strerror_buffer, "Unknown Error");
1410 return strerror_buffer;
1416 win32_str_os_error(void *sv, DWORD dwErr)
1420 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
1421 |FORMAT_MESSAGE_IGNORE_INSERTS
1422 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
1423 dwErr, 0, (char *)&sMsg, 1, NULL);
1425 while (0 < dwLen && isspace(sMsg[--dwLen]))
1427 if ('.' != sMsg[dwLen])
1432 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
1433 dwLen = sprintf(sMsg,
1434 "Unknown error #0x%lX (lookup 0x%lX)",
1435 dwErr, GetLastError());
1437 sv_setpvn((SV*)sv, sMsg, dwLen);
1443 win32_fprintf(FILE *fp, const char *format, ...)
1446 va_start(marker, format); /* Initialize variable arguments. */
1448 return (vfprintf(fp, format, marker));
1452 win32_printf(const char *format, ...)
1455 va_start(marker, format); /* Initialize variable arguments. */
1457 return (vprintf(format, marker));
1461 win32_vfprintf(FILE *fp, const char *format, va_list args)
1463 return (vfprintf(fp, format, args));
1467 win32_vprintf(const char *format, va_list args)
1469 return (vprintf(format, args));
1473 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
1475 return fread(buf, size, count, fp);
1479 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
1481 return fwrite(buf, size, count, fp);
1485 win32_fopen(const char *filename, const char *mode)
1487 if (stricmp(filename, "/dev/null")==0)
1488 return fopen("NUL", mode);
1489 return fopen(filename, mode);
1492 #ifndef USE_SOCKETS_AS_HANDLES
1494 #define fdopen my_fdopen
1498 win32_fdopen( int handle, const char *mode)
1500 return fdopen(handle, (char *) mode);
1504 win32_freopen( const char *path, const char *mode, FILE *stream)
1506 if (stricmp(path, "/dev/null")==0)
1507 return freopen("NUL", mode, stream);
1508 return freopen(path, mode, stream);
1512 win32_fclose(FILE *pf)
1514 return my_fclose(pf); /* defined in win32sck.c */
1518 win32_fputs(const char *s,FILE *pf)
1520 return fputs(s, pf);
1524 win32_fputc(int c,FILE *pf)
1530 win32_ungetc(int c,FILE *pf)
1532 return ungetc(c,pf);
1536 win32_getc(FILE *pf)
1542 win32_fileno(FILE *pf)
1548 win32_clearerr(FILE *pf)
1555 win32_fflush(FILE *pf)
1561 win32_ftell(FILE *pf)
1567 win32_fseek(FILE *pf,long offset,int origin)
1569 return fseek(pf, offset, origin);
1573 win32_fgetpos(FILE *pf,fpos_t *p)
1575 return fgetpos(pf, p);
1579 win32_fsetpos(FILE *pf,const fpos_t *p)
1581 return fsetpos(pf, p);
1585 win32_rewind(FILE *pf)
1605 win32_fstat(int fd,struct stat *sbufptr)
1607 return fstat(fd,sbufptr);
1611 win32_pipe(int *pfd, unsigned int size, int mode)
1613 return _pipe(pfd, size, mode);
1617 * a popen() clone that respects PERL5SHELL
1621 win32_popen(const char *command, const char *mode)
1623 #ifdef USE_RTL_POPEN
1624 return _popen(command, mode);
1632 /* establish which ends read and write */
1633 if (strchr(mode,'w')) {
1634 stdfd = 0; /* stdin */
1638 else if (strchr(mode,'r')) {
1639 stdfd = 1; /* stdout */
1646 /* set the correct mode */
1647 if (strchr(mode,'b'))
1649 else if (strchr(mode,'t'))
1652 ourmode = _fmode & (O_TEXT | O_BINARY);
1654 /* the child doesn't inherit handles */
1655 ourmode |= O_NOINHERIT;
1657 if (win32_pipe( p, 512, ourmode) == -1)
1660 /* save current stdfd */
1661 if ((oldfd = win32_dup(stdfd)) == -1)
1664 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
1665 /* stdfd will be inherited by the child */
1666 if (win32_dup2(p[child], stdfd) == -1)
1669 /* close the child end in parent */
1670 win32_close(p[child]);
1672 /* start the child */
1673 if ((childpid = do_spawn_nowait((char*)command)) == -1)
1676 /* revert stdfd to whatever it was before */
1677 if (win32_dup2(oldfd, stdfd) == -1)
1680 /* close saved handle */
1683 sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
1685 /* we have an fd, return a file stream */
1686 return (win32_fdopen(p[parent], (char *)mode));
1689 /* we don't need to check for errors here */
1693 win32_dup2(oldfd, stdfd);
1698 #endif /* USE_RTL_POPEN */
1706 win32_pclose(FILE *pf)
1708 #ifdef USE_RTL_POPEN
1712 int childpid, status;
1715 sv = *av_fetch(w32_fdpid, win32_fileno(pf), TRUE);
1717 childpid = SvIVX(sv);
1729 remove_dead_process((HANDLE)childpid);
1731 /* wait for the child */
1732 if (cwait(&status, childpid, WAIT_CHILD) == -1)
1734 /* cwait() returns differently on Borland */
1736 return (((status >> 8) & 0xff) | ((status << 8) & 0xff00));
1741 #endif /* USE_RTL_POPEN */
1745 win32_setmode(int fd, int mode)
1747 return setmode(fd, mode);
1751 win32_lseek(int fd, long offset, int origin)
1753 return lseek(fd, offset, origin);
1763 win32_open(const char *path, int flag, ...)
1769 pmode = va_arg(ap, int);
1772 if (stricmp(path, "/dev/null")==0)
1773 return open("NUL", flag, pmode);
1774 return open(path,flag,pmode);
1796 win32_dup2(int fd1,int fd2)
1798 return dup2(fd1,fd2);
1802 win32_read(int fd, void *buf, unsigned int cnt)
1804 return read(fd, buf, cnt);
1808 win32_write(int fd, const void *buf, unsigned int cnt)
1810 return write(fd, buf, cnt);
1814 win32_mkdir(const char *dir, int mode)
1816 return mkdir(dir); /* just ignore mode */
1820 win32_rmdir(const char *dir)
1826 win32_chdir(const char *dir)
1832 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
1836 #ifndef USE_RTL_WAIT
1837 if (mode == P_NOWAIT && w32_num_children >= MAXIMUM_WAIT_OBJECTS)
1841 status = spawnvp(mode, cmdname, (char * const *) argv);
1842 #ifndef USE_RTL_WAIT
1843 /* XXX For the P_NOWAIT case, Borland RTL returns pinfo.dwProcessId
1844 * while VC RTL returns pinfo.hProcess. For purposes of the custom
1845 * implementation of win32_wait(), we assume the latter.
1847 if (mode == P_NOWAIT && status >= 0)
1848 w32_child_pids[w32_num_children++] = (HANDLE)status;
1854 win32_execv(const char *cmdname, const char *const *argv)
1856 return execv(cmdname, (char *const *)argv);
1860 win32_execvp(const char *cmdname, const char *const *argv)
1862 return execvp(cmdname, (char *const *)argv);
1866 win32_perror(const char *str)
1872 win32_setbuf(FILE *pf, char *buf)
1878 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
1880 return setvbuf(pf, buf, type, size);
1884 win32_flushall(void)
1890 win32_fcloseall(void)
1896 win32_fgets(char *s, int n, FILE *pf)
1898 return fgets(s, n, pf);
1908 win32_fgetc(FILE *pf)
1914 win32_putc(int c, FILE *pf)
1920 win32_puts(const char *s)
1932 win32_putchar(int c)
1939 #ifndef USE_PERL_SBRK
1941 static char *committed = NULL;
1942 static char *base = NULL;
1943 static char *reserved = NULL;
1944 static char *brk = NULL;
1945 static DWORD pagesize = 0;
1946 static DWORD allocsize = 0;
1954 GetSystemInfo(&info);
1955 /* Pretend page size is larger so we don't perpetually
1956 * call the OS to commit just one page ...
1958 pagesize = info.dwPageSize << 3;
1959 allocsize = info.dwAllocationGranularity;
1961 /* This scheme fails eventually if request for contiguous
1962 * block is denied so reserve big blocks - this is only
1963 * address space not memory ...
1965 if (brk+need >= reserved)
1967 DWORD size = 64*1024*1024;
1969 if (committed && reserved && committed < reserved)
1971 /* Commit last of previous chunk cannot span allocations */
1972 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
1974 committed = reserved;
1976 /* Reserve some (more) space
1977 * Note this is a little sneaky, 1st call passes NULL as reserved
1978 * so lets system choose where we start, subsequent calls pass
1979 * the old end address so ask for a contiguous block
1981 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
1984 reserved = addr+size;
1999 if (brk > committed)
2001 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
2002 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
2017 win32_malloc(size_t size)
2019 return malloc(size);
2023 win32_calloc(size_t numitems, size_t size)
2025 return calloc(numitems,size);
2029 win32_realloc(void *block, size_t size)
2031 return realloc(block,size);
2035 win32_free(void *block)
2042 win32_open_osfhandle(long handle, int flags)
2044 return _open_osfhandle(handle, flags);
2048 win32_get_osfhandle(int fd)
2050 return _get_osfhandle(fd);
2061 SV *sv = sv_newmortal();
2062 /* Make one call with zero size - return value is required size */
2063 DWORD len = GetCurrentDirectory((DWORD)0,NULL);
2064 SvUPGRADE(sv,SVt_PV);
2066 SvCUR(sv) = GetCurrentDirectory((DWORD) SvLEN(sv), SvPVX(sv));
2069 * then it worked, set PV valid,
2070 * else leave it 'undef'
2084 croak("usage: Win32::SetCurrentDirectory($cwd)");
2085 if (SetCurrentDirectory(SvPV(ST(0),na)))
2092 XS(w32_GetNextAvailDrive)
2096 char root[] = "_:\\";
2099 if (GetDriveType(root) == 1) {
2108 XS(w32_GetLastError)
2111 XSRETURN_IV(GetLastError());
2118 char *name = getlogin_buffer;
2119 DWORD size = sizeof(getlogin_buffer);
2120 if (GetUserName(name,&size)) {
2121 /* size includes NULL */
2122 ST(0) = sv_2mortal(newSVpv(name,size-1));
2132 char name[MAX_COMPUTERNAME_LENGTH+1];
2133 DWORD size = sizeof(name);
2134 if (GetComputerName(name,&size)) {
2135 /* size does NOT include NULL :-( */
2136 ST(0) = sv_2mortal(newSVpv(name,size));
2147 #ifndef HAS_NETWKSTAGETINFO
2148 /* mingw32 (and Win95) don't have NetWksta*(), so do it the old way */
2150 DWORD size = sizeof(name);
2151 if (GetUserName(name,&size)) {
2153 DWORD sidlen = sizeof(sid);
2155 DWORD dnamelen = sizeof(dname);
2157 if (LookupAccountName(NULL, name, &sid, &sidlen,
2158 dname, &dnamelen, &snu)) {
2159 XSRETURN_PV(dname); /* all that for this */
2163 /* this way is more reliable, in case user has a local account.
2164 * XXX need dynamic binding of netapi32.dll symbols or this will fail on
2165 * Win95. Probably makes more sense to move it into libwin32. */
2167 DWORD dnamelen = sizeof(dname);
2168 PWKSTA_INFO_100 pwi;
2169 if (NERR_Success == NetWkstaGetInfo(NULL, 100, (LPBYTE*)&pwi)) {
2170 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
2171 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
2172 -1, (LPSTR)dname, dnamelen, NULL, NULL);
2175 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
2176 -1, (LPSTR)dname, dnamelen, NULL, NULL);
2178 NetApiBufferFree(pwi);
2190 DWORD flags, filecomplen;
2191 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
2192 &flags, fsname, sizeof(fsname))) {
2193 if (GIMME == G_ARRAY) {
2194 XPUSHs(sv_2mortal(newSVpv(fsname,0)));
2195 XPUSHs(sv_2mortal(newSViv(flags)));
2196 XPUSHs(sv_2mortal(newSViv(filecomplen)));
2200 XSRETURN_PV(fsname);
2206 XS(w32_GetOSVersion)
2209 OSVERSIONINFO osver;
2211 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
2212 if (GetVersionEx(&osver)) {
2213 XPUSHs(newSVpv(osver.szCSDVersion, 0));
2214 XPUSHs(newSViv(osver.dwMajorVersion));
2215 XPUSHs(newSViv(osver.dwMinorVersion));
2216 XPUSHs(newSViv(osver.dwBuildNumber));
2217 XPUSHs(newSViv(osver.dwPlatformId));
2228 XSRETURN_IV(IsWinNT());
2235 XSRETURN_IV(IsWin95());
2239 XS(w32_FormatMessage)
2246 croak("usage: Win32::FormatMessage($errno)");
2248 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
2249 &source, SvIV(ST(0)), 0,
2250 msgbuf, sizeof(msgbuf)-1, NULL))
2251 XSRETURN_PV(msgbuf);
2261 PROCESS_INFORMATION stProcInfo;
2262 STARTUPINFO stStartInfo;
2263 BOOL bSuccess = FALSE;
2266 croak("usage: Win32::Spawn($cmdName, $args, $PID)");
2268 cmd = SvPV(ST(0),na);
2269 args = SvPV(ST(1), na);
2271 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
2272 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
2273 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
2274 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
2277 cmd, /* Image path */
2278 args, /* Arguments for command line */
2279 NULL, /* Default process security */
2280 NULL, /* Default thread security */
2281 FALSE, /* Must be TRUE to use std handles */
2282 NORMAL_PRIORITY_CLASS, /* No special scheduling */
2283 NULL, /* Inherit our environment block */
2284 NULL, /* Inherit our currrent directory */
2285 &stStartInfo, /* -> Startup info */
2286 &stProcInfo)) /* <- Process info (if OK) */
2288 CloseHandle(stProcInfo.hThread);/* library source code does this. */
2289 sv_setiv(ST(2), stProcInfo.dwProcessId);
2292 XSRETURN_IV(bSuccess);
2296 XS(w32_GetTickCount)
2299 XSRETURN_IV(GetTickCount());
2303 XS(w32_GetShortPathName)
2310 croak("usage: Win32::GetShortPathName($longPathName)");
2312 shortpath = sv_mortalcopy(ST(0));
2313 SvUPGRADE(shortpath, SVt_PV);
2314 /* src == target is allowed */
2316 len = GetShortPathName(SvPVX(shortpath),
2319 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
2321 SvCUR_set(shortpath,len);
2334 croak("usage: Win32::Sleep($milliseconds)");
2340 Perl_init_os_extras()
2342 char *file = __FILE__;
2345 w32_perlshell_tokens = Nullch;
2346 w32_perlshell_items = -1;
2347 w32_fdpid = newAV(); /* XXX needs to be in Perl_win32_init()? */
2348 #ifndef USE_RTL_WAIT
2349 w32_num_children = 0;
2352 /* these names are Activeware compatible */
2353 newXS("Win32::GetCwd", w32_GetCwd, file);
2354 newXS("Win32::SetCwd", w32_SetCwd, file);
2355 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
2356 newXS("Win32::GetLastError", w32_GetLastError, file);
2357 newXS("Win32::LoginName", w32_LoginName, file);
2358 newXS("Win32::NodeName", w32_NodeName, file);
2359 newXS("Win32::DomainName", w32_DomainName, file);
2360 newXS("Win32::FsType", w32_FsType, file);
2361 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
2362 newXS("Win32::IsWinNT", w32_IsWinNT, file);
2363 newXS("Win32::IsWin95", w32_IsWin95, file);
2364 newXS("Win32::FormatMessage", w32_FormatMessage, file);
2365 newXS("Win32::Spawn", w32_Spawn, file);
2366 newXS("Win32::GetTickCount", w32_GetTickCount, file);
2367 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
2368 newXS("Win32::Sleep", w32_Sleep, file);
2370 /* XXX Bloat Alert! The following Activeware preloads really
2371 * ought to be part of Win32::Sys::*, so they're not included
2374 /* LookupAccountName
2376 * InitiateSystemShutdown
2377 * AbortSystemShutdown
2378 * ExpandEnvrironmentStrings
2383 Perl_win32_init(int *argcp, char ***argvp)
2385 /* Disable floating point errors, Perl will trap the ones we
2386 * care about. VC++ RTL defaults to switching these off
2387 * already, but the Borland RTL doesn't. Since we don't
2388 * want to be at the vendor's whim on the default, we set
2389 * it explicitly here.
2391 #if !defined(_ALPHA_) && !defined(__GNUC__)
2392 _control87(MCW_EM, MCW_EM);
2397 #ifdef USE_BINMODE_SCRIPTS
2400 win32_strip_return(SV *sv)
2402 char *s = SvPVX(sv);
2403 char *e = s+SvCUR(sv);
2407 if (*s == '\r' && s[1] == '\n')
2417 SvCUR_set(sv,d-SvPVX(sv));