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, ...);
115 HANDLE w32_perldll_handle = INVALID_HANDLE_VALUE;
116 static DWORD w32_platform = (DWORD)-1;
119 # ifdef USE_DECLSPEC_THREAD
120 __declspec(thread) char strerror_buffer[512];
121 __declspec(thread) char getlogin_buffer[128];
122 __declspec(thread) char w32_perllib_root[MAX_PATH+1];
123 # ifdef HAVE_DES_FCRYPT
124 __declspec(thread) char crypt_buffer[30];
127 # define strerror_buffer (thr->i.Wstrerror_buffer)
128 # define getlogin_buffer (thr->i.Wgetlogin_buffer)
129 # define w32_perllib_root (thr->i.Ww32_perllib_root)
130 # define crypt_buffer (thr->i.Wcrypt_buffer)
133 static char strerror_buffer[512];
134 static char getlogin_buffer[128];
135 static char w32_perllib_root[MAX_PATH+1];
136 # ifdef HAVE_DES_FCRYPT
137 static char crypt_buffer[30];
143 return (os_id() == VER_PLATFORM_WIN32_WINDOWS);
148 return (os_id() == VER_PLATFORM_WIN32_NT);
152 GetRegStrFromKey(HKEY hkey, const char *lpszValueName, char** ptr, DWORD* lpDataLen)
153 { /* Retrieve a REG_SZ or REG_EXPAND_SZ from the registry */
156 const char *subkey = "Software\\Perl";
159 retval = RegOpenKeyEx(hkey, subkey, 0, KEY_READ, &handle);
160 if (retval == ERROR_SUCCESS){
161 retval = RegQueryValueEx(handle, lpszValueName, 0, &type, NULL, lpDataLen);
162 if (retval == ERROR_SUCCESS && type == REG_SZ) {
164 Renew(*ptr, *lpDataLen, char);
167 New(1312, *ptr, *lpDataLen, char);
169 retval = RegQueryValueEx(handle, lpszValueName, 0, NULL, (PBYTE)*ptr, lpDataLen);
170 if (retval != ERROR_SUCCESS) {
181 GetRegStr(const char *lpszValueName, char** ptr, DWORD* lpDataLen)
183 *ptr = GetRegStrFromKey(HKEY_CURRENT_USER, lpszValueName, ptr, lpDataLen);
186 *ptr = GetRegStrFromKey(HKEY_LOCAL_MACHINE, lpszValueName, ptr, lpDataLen);
192 get_emd_part(char *prev_path, char *trailing_path, ...)
195 char mod_name[MAX_PATH];
199 int oldsize, newsize;
201 va_start(ap, trailing_path);
202 strip = va_arg(ap, char *);
204 GetModuleFileName(GetModuleHandle(NULL), mod_name, sizeof(mod_name));
205 ptr = strrchr(mod_name, '\\');
206 while (ptr && strip) {
207 /* look for directories to skip back */
210 ptr = strrchr(mod_name, '\\');
211 if (!ptr || stricmp(ptr+1, strip) != 0) {
215 strip = va_arg(ap, char *);
223 strcpy(++ptr, trailing_path);
225 newsize = strlen(mod_name) + 1;
227 oldsize = strlen(prev_path) + 1;
228 newsize += oldsize; /* includes plus 1 for ';' */
229 Renew(prev_path, newsize, char);
230 prev_path[oldsize] = ';';
231 strcpy(&prev_path[oldsize], mod_name);
234 New(1311, prev_path, newsize, char);
235 strcpy(prev_path, mod_name);
242 win32_get_privlib(char *pl)
244 char *stdlib = "lib";
245 char buffer[MAX_PATH+1];
249 /* $stdlib = $HKCU{"lib-$]"} || $HKLM{"lib-$]"} || $HKCU{"lib"} || $HKLM{"lib"} || ""; */
250 sprintf(buffer, "%s-%s", stdlib, pl);
251 path = GetRegStr(buffer, &path, &datalen);
253 path = GetRegStr(stdlib, &path, &datalen);
255 /* $stdlib .= ";$EMD/../../lib" */
256 return get_emd_part(path, stdlib, ARCHNAME, "bin", Nullch);
260 win32_get_sitelib(char *pl)
262 char *sitelib = "sitelib";
264 char pathstr[MAX_PATH];
266 char *path1 = Nullch;
267 char *path2 = Nullch;
270 /* $HKCU{"sitelib-$]"} || $HKLM{"sitelib-$]"} . ---; */
271 sprintf(regstr, "%s-%s", sitelib, pl);
272 path1 = GetRegStr(regstr, &path1, &datalen);
275 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/$]/lib"; */
276 sprintf(pathstr, "site\\%s\\lib", pl);
277 path1 = get_emd_part(path1, pathstr, ARCHNAME, "bin", pl, Nullch);
279 /* $HKCU{'sitelib'} || $HKLM{'sitelib'} . ---; */
280 path2 = GetRegStr(sitelib, &path2, &datalen);
283 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/lib"; */
284 path2 = get_emd_part(path2, "site\\lib", ARCHNAME, "bin", pl, Nullch);
293 newsize = len + strlen(path2) + 2; /* plus one for ';' */
295 Renew(path1, newsize, char);
297 strcpy(&path1[len], path2);
305 has_redirection(char *ptr)
311 * Scan string looking for redirection (< or >) or pipe
312 * characters (|) that are not in a quoted string
342 #if !defined(PERL_OBJECT)
343 /* since the current process environment is being updated in util.c
344 * the library functions will get the correct environment
347 my_popen(char *cmd, char *mode)
350 #define fixcmd(x) { \
351 char *pspace = strchr((x),' '); \
354 while (p < pspace) { \
365 win32_fflush(stdout);
366 win32_fflush(stderr);
367 return win32_popen(cmd, mode);
371 my_pclose(PerlIO *fp)
373 return win32_pclose(fp);
380 static OSVERSIONINFO osver;
382 if (osver.dwPlatformId != w32_platform) {
383 memset(&osver, 0, sizeof(OSVERSIONINFO));
384 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
385 GetVersionEx(&osver);
386 w32_platform = osver.dwPlatformId;
388 return (w32_platform);
391 /* Tokenize a string. Words are null-separated, and the list
392 * ends with a doubled null. Any character (except null and
393 * including backslash) may be escaped by preceding it with a
394 * backslash (the backslash will be stripped).
395 * Returns number of words in result buffer.
398 tokenize(char *str, char **dest, char ***destv)
400 char *retstart = Nullch;
401 char **retvstart = 0;
404 int slen = strlen(str);
406 register char **retv;
407 New(1307, ret, slen+2, char);
408 New(1308, retv, (slen+3)/2, char*);
416 if (*ret == '\\' && *str)
418 else if (*ret == ' ') {
434 retvstart[items] = Nullch;
446 if (!w32_perlshell_tokens) {
447 /* we don't use COMSPEC here for two reasons:
448 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
449 * uncontrolled unportability of the ensuing scripts.
450 * 2. PERL5SHELL could be set to a shell that may not be fit for
451 * interactive use (which is what most programs look in COMSPEC
454 char* defaultshell = (IsWinNT() ? "cmd.exe /x/c" : "command.com /c");
455 char *usershell = getenv("PERL5SHELL");
456 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
457 &w32_perlshell_tokens,
463 do_aspawn(void *vreally, void **vmark, void **vsp)
465 SV *really = (SV*)vreally;
466 SV **mark = (SV**)vmark;
478 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
480 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
485 while (++mark <= sp) {
486 if (*mark && (str = SvPV(*mark, na)))
493 status = win32_spawnvp(flag,
494 (const char*)(really ? SvPV(really,na) : argv[0]),
495 (const char* const*)argv);
497 if (status < 0 && errno == ENOEXEC) {
498 /* possible shell-builtin, invoke with shell */
500 sh_items = w32_perlshell_items;
502 argv[index+sh_items] = argv[index];
503 while (--sh_items >= 0)
504 argv[sh_items] = w32_perlshell_vec[sh_items];
506 status = win32_spawnvp(flag,
507 (const char*)(really ? SvPV(really,na) : argv[0]),
508 (const char* const*)argv);
511 if (flag != P_NOWAIT) {
514 warn("Can't spawn \"%s\": %s", argv[0], strerror(errno));
519 statusvalue = status;
526 do_spawn2(char *cmd, int exectype)
532 BOOL needToTry = TRUE;
535 /* Save an extra exec if possible. See if there are shell
536 * metacharacters in it */
537 if (!has_redirection(cmd)) {
538 New(1301,argv, strlen(cmd) / 2 + 2, char*);
539 New(1302,cmd2, strlen(cmd) + 1, char);
542 for (s = cmd2; *s;) {
543 while (*s && isspace(*s))
547 while (*s && !isspace(*s))
556 status = win32_spawnvp(P_WAIT, argv[0],
557 (const char* const*)argv);
559 case EXECF_SPAWN_NOWAIT:
560 status = win32_spawnvp(P_NOWAIT, argv[0],
561 (const char* const*)argv);
564 status = win32_execvp(argv[0], (const char* const*)argv);
567 if (status != -1 || errno == 0)
577 New(1306, argv, w32_perlshell_items + 2, char*);
578 while (++i < w32_perlshell_items)
579 argv[i] = w32_perlshell_vec[i];
584 status = win32_spawnvp(P_WAIT, argv[0],
585 (const char* const*)argv);
587 case EXECF_SPAWN_NOWAIT:
588 status = win32_spawnvp(P_NOWAIT, argv[0],
589 (const char* const*)argv);
592 status = win32_execvp(argv[0], (const char* const*)argv);
598 if (exectype != EXECF_SPAWN_NOWAIT) {
601 warn("Can't %s \"%s\": %s",
602 (exectype == EXECF_EXEC ? "exec" : "spawn"),
603 cmd, strerror(errno));
608 statusvalue = status;
616 return do_spawn2(cmd, EXECF_SPAWN);
620 do_spawn_nowait(char *cmd)
622 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
628 do_spawn2(cmd, EXECF_EXEC);
632 /* The idea here is to read all the directory names into a string table
633 * (separated by nulls) and when one of the other dir functions is called
634 * return the pointer to the current file name.
637 opendir(char *filename)
642 char scanname[MAX_PATH+3];
644 WIN32_FIND_DATA FindData;
647 len = strlen(filename);
651 /* check to see if filename is a directory */
652 if (win32_stat(filename, &sbuf) < 0 || (sbuf.st_mode & S_IFDIR) == 0) {
653 /* CRT is buggy on sharenames, so make sure it really isn't */
654 DWORD r = GetFileAttributes(filename);
655 if (r == 0xffffffff || !(r & FILE_ATTRIBUTE_DIRECTORY))
659 /* Get us a DIR structure */
660 Newz(1303, p, 1, DIR);
664 /* Create the search pattern */
665 strcpy(scanname, filename);
666 if (scanname[len-1] != '/' && scanname[len-1] != '\\')
667 scanname[len++] = '/';
668 scanname[len++] = '*';
669 scanname[len] = '\0';
671 /* do the FindFirstFile call */
672 fh = FindFirstFile(scanname, &FindData);
673 if (fh == INVALID_HANDLE_VALUE) {
677 /* now allocate the first part of the string table for
678 * the filenames that we find.
680 idx = strlen(FindData.cFileName)+1;
681 New(1304, p->start, idx, char);
682 if (p->start == NULL)
683 croak("opendir: malloc failed!\n");
684 strcpy(p->start, FindData.cFileName);
687 /* loop finding all the files that match the wildcard
688 * (which should be all of them in this directory!).
689 * the variable idx should point one past the null terminator
690 * of the previous string found.
692 while (FindNextFile(fh, &FindData)) {
693 len = strlen(FindData.cFileName);
694 /* bump the string table size by enough for the
695 * new name and it's null terminator
697 Renew(p->start, idx+len+1, char);
698 if (p->start == NULL)
699 croak("opendir: malloc failed!\n");
700 strcpy(&p->start[idx], FindData.cFileName);
711 /* Readdir just returns the current string pointer and bumps the
712 * string pointer to the nDllExport entry.
718 static int dummy = 0;
721 /* first set up the structure to return */
722 len = strlen(dirp->curr);
723 strcpy(dirp->dirstr.d_name, dirp->curr);
724 dirp->dirstr.d_namlen = len;
727 dirp->dirstr.d_ino = dummy++;
729 /* Now set up for the nDllExport call to readdir */
730 dirp->curr += len + 1;
731 if (dirp->curr >= (dirp->start + dirp->size)) {
735 return &(dirp->dirstr);
741 /* Telldir returns the current string pointer position */
745 return (long) dirp->curr;
749 /* Seekdir moves the string pointer to a previously saved position
753 seekdir(DIR *dirp, long loc)
755 dirp->curr = (char *)loc;
758 /* Rewinddir resets the string pointer to the start */
762 dirp->curr = dirp->start;
765 /* free the memory allocated by opendir */
769 Safefree(dirp->start);
782 * Just pretend that everyone is a superuser. NT will let us know if
783 * we don\'t really have permission to do something.
786 #define ROOT_UID ((uid_t)0)
787 #define ROOT_GID ((gid_t)0)
816 return (auid == ROOT_UID ? 0 : -1);
822 return (agid == ROOT_GID ? 0 : -1);
829 char *buf = getlogin_buffer;
830 DWORD size = sizeof(getlogin_buffer);
831 if (GetUserName(buf,&size))
837 chown(const char *path, uid_t owner, gid_t group)
844 kill(int pid, int sig)
846 HANDLE hProcess= OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
848 if (hProcess == NULL) {
849 croak("kill process failed!\n");
852 if (!TerminateProcess(hProcess, sig))
853 croak("kill process failed!\n");
854 CloseHandle(hProcess);
863 DllExport unsigned int
864 win32_sleep(unsigned int t)
871 win32_stat(const char *path, struct stat *buffer)
874 const char *p = path;
875 int l = strlen(path);
879 switch(path[l - 1]) {
882 if (path[l - 2] != ':') {
883 strncpy(t, path, l - 1);
889 res = stat(p,buffer);
892 if (S_ISDIR(buffer->st_mode))
893 buffer->st_mode |= S_IWRITE | S_IEXEC;
894 else if (S_ISREG(buffer->st_mode)) {
895 if (l >= 4 && path[l-4] == '.') {
896 const char *e = path + l - 3;
897 if (strnicmp(e,"exe",3)
898 && strnicmp(e,"bat",3)
899 && strnicmp(e,"com",3)
900 && (IsWin95() || strnicmp(e,"cmd",3)))
901 buffer->st_mode &= ~S_IEXEC;
903 buffer->st_mode |= S_IEXEC;
906 buffer->st_mode &= ~S_IEXEC;
913 #ifndef USE_WIN32_RTL_ENV
916 win32_getenv(const char *name)
918 static char *curitem = Nullch;
919 static DWORD curlen = 512;
922 New(1305,curitem,curlen,char);
924 needlen = GetEnvironmentVariable(name,curitem,curlen);
926 while (needlen > curlen) {
927 Renew(curitem,needlen,char);
929 needlen = GetEnvironmentVariable(name,curitem,curlen);
934 /* allow any environment variables that begin with 'PERL5'
935 to be stored in the registry
940 if (strncmp(name, "PERL5", 5) == 0) {
941 if (curitem != NULL) {
945 curitem = GetRegStr(name, &curitem, &curlen);
948 if(curitem != NULL && *curitem == '\0')
957 filetime_to_clock(PFILETIME ft)
959 __int64 qw = ft->dwHighDateTime;
961 qw |= ft->dwLowDateTime;
962 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
967 win32_times(struct tms *timebuf)
972 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
974 timebuf->tms_utime = filetime_to_clock(&user);
975 timebuf->tms_stime = filetime_to_clock(&kernel);
976 timebuf->tms_cutime = 0;
977 timebuf->tms_cstime = 0;
980 /* That failed - e.g. Win95 fallback to clock() */
982 timebuf->tms_utime = t;
983 timebuf->tms_stime = 0;
984 timebuf->tms_cutime = 0;
985 timebuf->tms_cstime = 0;
990 /* fix utime() so it works on directories in NT
991 * thanks to Jan Dubois <jan.dubois@ibm.net>
994 filetime_from_time(PFILETIME pFileTime, time_t Time)
996 struct tm *pTM = gmtime(&Time);
997 SYSTEMTIME SystemTime;
1002 SystemTime.wYear = pTM->tm_year + 1900;
1003 SystemTime.wMonth = pTM->tm_mon + 1;
1004 SystemTime.wDay = pTM->tm_mday;
1005 SystemTime.wHour = pTM->tm_hour;
1006 SystemTime.wMinute = pTM->tm_min;
1007 SystemTime.wSecond = pTM->tm_sec;
1008 SystemTime.wMilliseconds = 0;
1010 return SystemTimeToFileTime(&SystemTime, pFileTime);
1014 win32_utime(const char *filename, struct utimbuf *times)
1020 struct utimbuf TimeBuffer;
1022 int rc = utime(filename,times);
1023 /* EACCES: path specifies directory or readonly file */
1024 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
1027 if (times == NULL) {
1028 times = &TimeBuffer;
1029 time(×->actime);
1030 times->modtime = times->actime;
1033 /* This will (and should) still fail on readonly files */
1034 handle = CreateFile(filename, GENERIC_READ | GENERIC_WRITE,
1035 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1036 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1037 if (handle == INVALID_HANDLE_VALUE)
1040 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
1041 filetime_from_time(&ftAccess, times->actime) &&
1042 filetime_from_time(&ftWrite, times->modtime) &&
1043 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
1048 CloseHandle(handle);
1053 win32_wait(int *status)
1056 return wait(status);
1058 /* XXX this wait emulation only knows about processes
1059 * spawned via win32_spawnvp(P_NOWAIT, ...).
1062 DWORD exitcode, waitcode;
1064 if (!w32_num_children) {
1069 /* if a child exists, wait for it to die */
1070 waitcode = WaitForMultipleObjects(w32_num_children,
1074 if (waitcode != WAIT_FAILED) {
1075 if (waitcode >= WAIT_ABANDONED_0
1076 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1077 i = waitcode - WAIT_ABANDONED_0;
1079 i = waitcode - WAIT_OBJECT_0;
1080 if (GetExitCodeProcess(w32_child_pids[i], &exitcode) ) {
1081 CloseHandle(w32_child_pids[i]);
1082 *status = (int)((exitcode & 0xff) << 8);
1083 retval = (int)w32_child_pids[i];
1084 Copy(&w32_child_pids[i+1], &w32_child_pids[i],
1085 (w32_num_children-i-1), HANDLE);
1092 errno = GetLastError();
1098 static UINT timerid = 0;
1100 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1102 KillTimer(NULL,timerid);
1107 DllExport unsigned int
1108 win32_alarm(unsigned int sec)
1111 * the 'obvious' implentation is SetTimer() with a callback
1112 * which does whatever receiving SIGALRM would do
1113 * we cannot use SIGALRM even via raise() as it is not
1114 * one of the supported codes in <signal.h>
1116 * Snag is unless something is looking at the message queue
1117 * nothing happens :-(
1121 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1123 croak("Cannot set timer");
1129 KillTimer(NULL,timerid);
1136 #ifdef HAVE_DES_FCRYPT
1137 extern char * des_fcrypt(char *cbuf, const char *txt, const char *salt);
1140 win32_crypt(const char *txt, const char *salt)
1143 return des_fcrypt(crypt_buffer, txt, salt);
1147 #ifdef USE_FIXED_OSFHANDLE
1149 EXTERN_C int __cdecl _alloc_osfhnd(void);
1150 EXTERN_C int __cdecl _set_osfhnd(int fh, long value);
1151 EXTERN_C void __cdecl _lock_fhandle(int);
1152 EXTERN_C void __cdecl _unlock_fhandle(int);
1153 EXTERN_C void __cdecl _unlock(int);
1155 #if (_MSC_VER >= 1000)
1157 long osfhnd; /* underlying OS file HANDLE */
1158 char osfile; /* attributes of file (e.g., open in text mode?) */
1159 char pipech; /* one char buffer for handles opened on pipes */
1160 #if defined (_MT) && !defined (DLL_FOR_WIN32S)
1162 CRITICAL_SECTION lock;
1163 #endif /* defined (_MT) && !defined (DLL_FOR_WIN32S) */
1166 EXTERN_C ioinfo * __pioinfo[];
1168 #define IOINFO_L2E 5
1169 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
1170 #define _pioinfo(i) (__pioinfo[i >> IOINFO_L2E] + (i & (IOINFO_ARRAY_ELTS - 1)))
1171 #define _osfile(i) (_pioinfo(i)->osfile)
1173 #else /* (_MSC_VER >= 1000) */
1174 extern char _osfile[];
1175 #endif /* (_MSC_VER >= 1000) */
1177 #define FOPEN 0x01 /* file handle open */
1178 #define FAPPEND 0x20 /* file handle opened O_APPEND */
1179 #define FDEV 0x40 /* file handle refers to device */
1180 #define FTEXT 0x80 /* file handle is in text mode */
1182 #define _STREAM_LOCKS 26 /* Table of stream locks */
1183 #define _LAST_STREAM_LOCK (_STREAM_LOCKS+_NSTREAM_-1) /* Last stream lock */
1184 #define _FH_LOCKS (_LAST_STREAM_LOCK+1) /* Table of fh locks */
1187 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1190 * This function allocates a free C Runtime file handle and associates
1191 * it with the Win32 HANDLE specified by the first parameter. This is a
1192 * temperary fix for WIN95's brain damage GetFileType() error on socket
1193 * we just bypass that call for socket
1196 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1197 * int flags - flags to associate with C Runtime file handle.
1200 * returns index of entry in fh, if successful
1201 * return -1, if no free entry is found
1205 *******************************************************************************/
1208 my_open_osfhandle(long osfhandle, int flags)
1211 char fileflags; /* _osfile flags */
1213 /* copy relevant flags from second parameter */
1216 if (flags & O_APPEND)
1217 fileflags |= FAPPEND;
1222 /* attempt to allocate a C Runtime file handle */
1223 if ((fh = _alloc_osfhnd()) == -1) {
1224 errno = EMFILE; /* too many open files */
1225 _doserrno = 0L; /* not an OS error */
1226 return -1; /* return error to caller */
1229 /* the file is open. now, set the info in _osfhnd array */
1230 _set_osfhnd(fh, osfhandle);
1232 fileflags |= FOPEN; /* mark as open */
1234 #if (_MSC_VER >= 1000)
1235 _osfile(fh) = fileflags; /* set osfile entry */
1236 _unlock_fhandle(fh);
1238 _osfile[fh] = fileflags; /* set osfile entry */
1239 _unlock(fh+_FH_LOCKS); /* unlock handle */
1242 return fh; /* return handle */
1245 #define _open_osfhandle my_open_osfhandle
1246 #endif /* USE_FIXED_OSFHANDLE */
1248 /* simulate flock by locking a range on the file */
1250 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1251 #define LK_LEN 0xffff0000
1254 win32_flock(int fd, int oper)
1261 croak("flock() unimplemented on this platform");
1264 fh = (HANDLE)_get_osfhandle(fd);
1265 memset(&o, 0, sizeof(o));
1268 case LOCK_SH: /* shared lock */
1269 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1271 case LOCK_EX: /* exclusive lock */
1272 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1274 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1275 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1277 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1278 LK_ERR(LockFileEx(fh,
1279 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1280 0, LK_LEN, 0, &o),i);
1282 case LOCK_UN: /* unlock lock */
1283 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1285 default: /* unknown */
1296 * redirected io subsystem for all XS modules
1309 return (&(_environ));
1312 /* the rest are the remapped stdio routines */
1332 win32_ferror(FILE *fp)
1334 return (ferror(fp));
1339 win32_feof(FILE *fp)
1345 * Since the errors returned by the socket error function
1346 * WSAGetLastError() are not known by the library routine strerror
1347 * we have to roll our own.
1351 win32_strerror(int e)
1353 #ifndef __BORLANDC__ /* Borland intolerance */
1354 extern int sys_nerr;
1358 if (e < 0 || e > sys_nerr) {
1363 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
1364 strerror_buffer, sizeof(strerror_buffer), NULL) == 0)
1365 strcpy(strerror_buffer, "Unknown Error");
1367 return strerror_buffer;
1373 win32_str_os_error(void *sv, DWORD dwErr)
1377 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
1378 |FORMAT_MESSAGE_IGNORE_INSERTS
1379 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
1380 dwErr, 0, (char *)&sMsg, 1, NULL);
1382 while (0 < dwLen && isspace(sMsg[--dwLen]))
1384 if ('.' != sMsg[dwLen])
1389 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
1390 dwLen = sprintf(sMsg,
1391 "Unknown error #0x%lX (lookup 0x%lX)",
1392 dwErr, GetLastError());
1394 sv_setpvn((SV*)sv, sMsg, dwLen);
1400 win32_fprintf(FILE *fp, const char *format, ...)
1403 va_start(marker, format); /* Initialize variable arguments. */
1405 return (vfprintf(fp, format, marker));
1409 win32_printf(const char *format, ...)
1412 va_start(marker, format); /* Initialize variable arguments. */
1414 return (vprintf(format, marker));
1418 win32_vfprintf(FILE *fp, const char *format, va_list args)
1420 return (vfprintf(fp, format, args));
1424 win32_vprintf(const char *format, va_list args)
1426 return (vprintf(format, args));
1430 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
1432 return fread(buf, size, count, fp);
1436 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
1438 return fwrite(buf, size, count, fp);
1442 win32_fopen(const char *filename, const char *mode)
1444 if (stricmp(filename, "/dev/null")==0)
1445 return fopen("NUL", mode);
1446 return fopen(filename, mode);
1449 #ifndef USE_SOCKETS_AS_HANDLES
1451 #define fdopen my_fdopen
1455 win32_fdopen( int handle, const char *mode)
1457 return fdopen(handle, (char *) mode);
1461 win32_freopen( const char *path, const char *mode, FILE *stream)
1463 if (stricmp(path, "/dev/null")==0)
1464 return freopen("NUL", mode, stream);
1465 return freopen(path, mode, stream);
1469 win32_fclose(FILE *pf)
1471 return my_fclose(pf); /* defined in win32sck.c */
1475 win32_fputs(const char *s,FILE *pf)
1477 return fputs(s, pf);
1481 win32_fputc(int c,FILE *pf)
1487 win32_ungetc(int c,FILE *pf)
1489 return ungetc(c,pf);
1493 win32_getc(FILE *pf)
1499 win32_fileno(FILE *pf)
1505 win32_clearerr(FILE *pf)
1512 win32_fflush(FILE *pf)
1518 win32_ftell(FILE *pf)
1524 win32_fseek(FILE *pf,long offset,int origin)
1526 return fseek(pf, offset, origin);
1530 win32_fgetpos(FILE *pf,fpos_t *p)
1532 return fgetpos(pf, p);
1536 win32_fsetpos(FILE *pf,const fpos_t *p)
1538 return fsetpos(pf, p);
1542 win32_rewind(FILE *pf)
1562 win32_fstat(int fd,struct stat *sbufptr)
1564 return fstat(fd,sbufptr);
1568 win32_pipe(int *pfd, unsigned int size, int mode)
1570 return _pipe(pfd, size, mode);
1574 * a popen() clone that respects PERL5SHELL
1578 win32_popen(const char *command, const char *mode)
1580 #ifdef USE_RTL_POPEN
1581 return _popen(command, mode);
1589 /* establish which ends read and write */
1590 if (strchr(mode,'w')) {
1591 stdfd = 0; /* stdin */
1595 else if (strchr(mode,'r')) {
1596 stdfd = 1; /* stdout */
1603 /* set the correct mode */
1604 if (strchr(mode,'b'))
1606 else if (strchr(mode,'t'))
1609 ourmode = _fmode & (O_TEXT | O_BINARY);
1611 /* the child doesn't inherit handles */
1612 ourmode |= O_NOINHERIT;
1614 if (win32_pipe( p, 512, ourmode) == -1)
1617 /* save current stdfd */
1618 if ((oldfd = win32_dup(stdfd)) == -1)
1621 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
1622 /* stdfd will be inherited by the child */
1623 if (win32_dup2(p[child], stdfd) == -1)
1626 /* close the child end in parent */
1627 win32_close(p[child]);
1629 /* start the child */
1630 if ((childpid = do_spawn_nowait((char*)command)) == -1)
1633 /* revert stdfd to whatever it was before */
1634 if (win32_dup2(oldfd, stdfd) == -1)
1637 /* close saved handle */
1640 sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
1642 /* we have an fd, return a file stream */
1643 return (win32_fdopen(p[parent], (char *)mode));
1646 /* we don't need to check for errors here */
1650 win32_dup2(oldfd, stdfd);
1655 #endif /* USE_RTL_POPEN */
1663 win32_pclose(FILE *pf)
1665 #ifdef USE_RTL_POPEN
1669 #ifndef USE_RTL_WAIT
1673 int childpid, status;
1676 sv = *av_fetch(w32_fdpid, win32_fileno(pf), TRUE);
1678 childpid = SvIVX(sv);
1690 #ifndef USE_RTL_WAIT
1691 for (child = 0 ; child < w32_num_children ; ++child) {
1692 if (w32_child_pids[child] == (HANDLE)childpid) {
1693 Copy(&w32_child_pids[child+1], &w32_child_pids[child],
1694 (w32_num_children-child-1), HANDLE);
1701 /* wait for the child */
1702 if (cwait(&status, childpid, WAIT_CHILD) == -1)
1704 /* cwait() returns differently on Borland */
1706 return (((status >> 8) & 0xff) | ((status << 8) & 0xff00));
1711 #endif /* USE_RTL_POPEN */
1715 win32_setmode(int fd, int mode)
1717 return setmode(fd, mode);
1721 win32_lseek(int fd, long offset, int origin)
1723 return lseek(fd, offset, origin);
1733 win32_open(const char *path, int flag, ...)
1739 pmode = va_arg(ap, int);
1742 if (stricmp(path, "/dev/null")==0)
1743 return open("NUL", flag, pmode);
1744 return open(path,flag,pmode);
1766 win32_dup2(int fd1,int fd2)
1768 return dup2(fd1,fd2);
1772 win32_read(int fd, void *buf, unsigned int cnt)
1774 return read(fd, buf, cnt);
1778 win32_write(int fd, const void *buf, unsigned int cnt)
1780 return write(fd, buf, cnt);
1784 win32_mkdir(const char *dir, int mode)
1786 return mkdir(dir); /* just ignore mode */
1790 win32_rmdir(const char *dir)
1796 win32_chdir(const char *dir)
1802 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
1806 #ifndef USE_RTL_WAIT
1807 if (mode == P_NOWAIT && w32_num_children >= MAXIMUM_WAIT_OBJECTS)
1811 status = spawnvp(mode, cmdname, (char * const *) argv);
1812 #ifndef USE_RTL_WAIT
1813 /* XXX For the P_NOWAIT case, Borland RTL returns pinfo.dwProcessId
1814 * while VC RTL returns pinfo.hProcess. For purposes of the custom
1815 * implementation of win32_wait(), we assume the latter.
1817 if (mode == P_NOWAIT && status >= 0)
1818 w32_child_pids[w32_num_children++] = (HANDLE)status;
1824 win32_execv(const char *cmdname, const char *const *argv)
1826 return execv(cmdname, (char *const *)argv);
1830 win32_execvp(const char *cmdname, const char *const *argv)
1832 return execvp(cmdname, (char *const *)argv);
1836 win32_perror(const char *str)
1842 win32_setbuf(FILE *pf, char *buf)
1848 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
1850 return setvbuf(pf, buf, type, size);
1854 win32_flushall(void)
1860 win32_fcloseall(void)
1866 win32_fgets(char *s, int n, FILE *pf)
1868 return fgets(s, n, pf);
1878 win32_fgetc(FILE *pf)
1884 win32_putc(int c, FILE *pf)
1890 win32_puts(const char *s)
1902 win32_putchar(int c)
1909 #ifndef USE_PERL_SBRK
1911 static char *committed = NULL;
1912 static char *base = NULL;
1913 static char *reserved = NULL;
1914 static char *brk = NULL;
1915 static DWORD pagesize = 0;
1916 static DWORD allocsize = 0;
1924 GetSystemInfo(&info);
1925 /* Pretend page size is larger so we don't perpetually
1926 * call the OS to commit just one page ...
1928 pagesize = info.dwPageSize << 3;
1929 allocsize = info.dwAllocationGranularity;
1931 /* This scheme fails eventually if request for contiguous
1932 * block is denied so reserve big blocks - this is only
1933 * address space not memory ...
1935 if (brk+need >= reserved)
1937 DWORD size = 64*1024*1024;
1939 if (committed && reserved && committed < reserved)
1941 /* Commit last of previous chunk cannot span allocations */
1942 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
1944 committed = reserved;
1946 /* Reserve some (more) space
1947 * Note this is a little sneaky, 1st call passes NULL as reserved
1948 * so lets system choose where we start, subsequent calls pass
1949 * the old end address so ask for a contiguous block
1951 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
1954 reserved = addr+size;
1969 if (brk > committed)
1971 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
1972 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
1987 win32_malloc(size_t size)
1989 return malloc(size);
1993 win32_calloc(size_t numitems, size_t size)
1995 return calloc(numitems,size);
1999 win32_realloc(void *block, size_t size)
2001 return realloc(block,size);
2005 win32_free(void *block)
2012 win32_open_osfhandle(long handle, int flags)
2014 return _open_osfhandle(handle, flags);
2018 win32_get_osfhandle(int fd)
2020 return _get_osfhandle(fd);
2031 SV *sv = sv_newmortal();
2032 /* Make one call with zero size - return value is required size */
2033 DWORD len = GetCurrentDirectory((DWORD)0,NULL);
2034 SvUPGRADE(sv,SVt_PV);
2036 SvCUR(sv) = GetCurrentDirectory((DWORD) SvLEN(sv), SvPVX(sv));
2039 * then it worked, set PV valid,
2040 * else leave it 'undef'
2054 croak("usage: Win32::SetCurrentDirectory($cwd)");
2055 if (SetCurrentDirectory(SvPV(ST(0),na)))
2062 XS(w32_GetNextAvailDrive)
2066 char root[] = "_:\\";
2069 if (GetDriveType(root) == 1) {
2078 XS(w32_GetLastError)
2081 XSRETURN_IV(GetLastError());
2088 char *name = getlogin_buffer;
2089 DWORD size = sizeof(getlogin_buffer);
2090 if (GetUserName(name,&size)) {
2091 /* size includes NULL */
2092 ST(0) = sv_2mortal(newSVpv(name,size-1));
2102 char name[MAX_COMPUTERNAME_LENGTH+1];
2103 DWORD size = sizeof(name);
2104 if (GetComputerName(name,&size)) {
2105 /* size does NOT include NULL :-( */
2106 ST(0) = sv_2mortal(newSVpv(name,size));
2117 #ifndef HAS_NETWKSTAGETINFO
2118 /* mingw32 (and Win95) don't have NetWksta*(), so do it the old way */
2120 DWORD size = sizeof(name);
2121 if (GetUserName(name,&size)) {
2123 DWORD sidlen = sizeof(sid);
2125 DWORD dnamelen = sizeof(dname);
2127 if (LookupAccountName(NULL, name, &sid, &sidlen,
2128 dname, &dnamelen, &snu)) {
2129 XSRETURN_PV(dname); /* all that for this */
2133 /* this way is more reliable, in case user has a local account.
2134 * XXX need dynamic binding of netapi32.dll symbols or this will fail on
2135 * Win95. Probably makes more sense to move it into libwin32. */
2137 DWORD dnamelen = sizeof(dname);
2138 PWKSTA_INFO_100 pwi;
2139 if (NERR_Success == NetWkstaGetInfo(NULL, 100, (LPBYTE*)&pwi)) {
2140 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
2141 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
2142 -1, (LPSTR)dname, dnamelen, NULL, NULL);
2145 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
2146 -1, (LPSTR)dname, dnamelen, NULL, NULL);
2148 NetApiBufferFree(pwi);
2160 DWORD flags, filecomplen;
2161 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
2162 &flags, fsname, sizeof(fsname))) {
2163 if (GIMME == G_ARRAY) {
2164 XPUSHs(sv_2mortal(newSVpv(fsname,0)));
2165 XPUSHs(sv_2mortal(newSViv(flags)));
2166 XPUSHs(sv_2mortal(newSViv(filecomplen)));
2170 XSRETURN_PV(fsname);
2176 XS(w32_GetOSVersion)
2179 OSVERSIONINFO osver;
2181 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
2182 if (GetVersionEx(&osver)) {
2183 XPUSHs(newSVpv(osver.szCSDVersion, 0));
2184 XPUSHs(newSViv(osver.dwMajorVersion));
2185 XPUSHs(newSViv(osver.dwMinorVersion));
2186 XPUSHs(newSViv(osver.dwBuildNumber));
2187 XPUSHs(newSViv(osver.dwPlatformId));
2198 XSRETURN_IV(IsWinNT());
2205 XSRETURN_IV(IsWin95());
2209 XS(w32_FormatMessage)
2216 croak("usage: Win32::FormatMessage($errno)");
2218 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
2219 &source, SvIV(ST(0)), 0,
2220 msgbuf, sizeof(msgbuf)-1, NULL))
2221 XSRETURN_PV(msgbuf);
2231 PROCESS_INFORMATION stProcInfo;
2232 STARTUPINFO stStartInfo;
2233 BOOL bSuccess = FALSE;
2236 croak("usage: Win32::Spawn($cmdName, $args, $PID)");
2238 cmd = SvPV(ST(0),na);
2239 args = SvPV(ST(1), na);
2241 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
2242 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
2243 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
2244 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
2247 cmd, /* Image path */
2248 args, /* Arguments for command line */
2249 NULL, /* Default process security */
2250 NULL, /* Default thread security */
2251 FALSE, /* Must be TRUE to use std handles */
2252 NORMAL_PRIORITY_CLASS, /* No special scheduling */
2253 NULL, /* Inherit our environment block */
2254 NULL, /* Inherit our currrent directory */
2255 &stStartInfo, /* -> Startup info */
2256 &stProcInfo)) /* <- Process info (if OK) */
2258 CloseHandle(stProcInfo.hThread);/* library source code does this. */
2259 sv_setiv(ST(2), stProcInfo.dwProcessId);
2262 XSRETURN_IV(bSuccess);
2266 XS(w32_GetTickCount)
2269 XSRETURN_IV(GetTickCount());
2273 XS(w32_GetShortPathName)
2280 croak("usage: Win32::GetShortPathName($longPathName)");
2282 shortpath = sv_mortalcopy(ST(0));
2283 SvUPGRADE(shortpath, SVt_PV);
2284 /* src == target is allowed */
2286 len = GetShortPathName(SvPVX(shortpath),
2289 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
2291 SvCUR_set(shortpath,len);
2304 croak("usage: Win32::Sleep($milliseconds)");
2310 Perl_init_os_extras()
2312 char *file = __FILE__;
2315 w32_perlshell_tokens = Nullch;
2316 w32_perlshell_items = -1;
2317 w32_fdpid = newAV(); /* XXX needs to be in Perl_win32_init()? */
2318 #ifndef USE_RTL_WAIT
2319 w32_num_children = 0;
2322 /* these names are Activeware compatible */
2323 newXS("Win32::GetCwd", w32_GetCwd, file);
2324 newXS("Win32::SetCwd", w32_SetCwd, file);
2325 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
2326 newXS("Win32::GetLastError", w32_GetLastError, file);
2327 newXS("Win32::LoginName", w32_LoginName, file);
2328 newXS("Win32::NodeName", w32_NodeName, file);
2329 newXS("Win32::DomainName", w32_DomainName, file);
2330 newXS("Win32::FsType", w32_FsType, file);
2331 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
2332 newXS("Win32::IsWinNT", w32_IsWinNT, file);
2333 newXS("Win32::IsWin95", w32_IsWin95, file);
2334 newXS("Win32::FormatMessage", w32_FormatMessage, file);
2335 newXS("Win32::Spawn", w32_Spawn, file);
2336 newXS("Win32::GetTickCount", w32_GetTickCount, file);
2337 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
2338 newXS("Win32::Sleep", w32_Sleep, file);
2340 /* XXX Bloat Alert! The following Activeware preloads really
2341 * ought to be part of Win32::Sys::*, so they're not included
2344 /* LookupAccountName
2346 * InitiateSystemShutdown
2347 * AbortSystemShutdown
2348 * ExpandEnvrironmentStrings
2353 Perl_win32_init(int *argcp, char ***argvp)
2355 /* Disable floating point errors, Perl will trap the ones we
2356 * care about. VC++ RTL defaults to switching these off
2357 * already, but the Borland RTL doesn't. Since we don't
2358 * want to be at the vendor's whim on the default, we set
2359 * it explicitly here.
2361 #if !defined(_ALPHA_) && !defined(__GNUC__)
2362 _control87(MCW_EM, MCW_EM);
2367 #ifdef USE_BINMODE_SCRIPTS
2370 win32_strip_return(SV *sv)
2372 char *s = SvPVX(sv);
2373 char *e = s+SvCUR(sv);
2377 if (*s == '\r' && s[1] == '\n')
2387 SvCUR_set(sv,d-SvPVX(sv));