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
22 /* ugliness to work around a buggy struct definition in lmwksta.h */
29 #endif /* __MINGW32__ */
31 /* #include "config.h" */
33 #define PERLIO_NOT_STDIO 0
34 #if !defined(PERLIO_IS_STDIO) && !defined(USE_SFIO)
44 /* assert.h conflicts with #define of assert in perl.h */
51 #if defined(_MSC_VER) || defined(__MINGW32__)
52 #include <sys/utime.h>
58 /* Mingw32 defaults to globing command line
59 * So we turn it off like this:
66 #define EXECF_SPAWN_NOWAIT 3
68 static DWORD os_id(void);
69 static void get_shell(void);
70 static long tokenize(char *str, char **dest, char ***destv);
71 static int do_spawn2(char *cmd, int exectype);
72 static BOOL has_redirection(char *ptr);
73 static long filetime_to_clock(PFILETIME ft);
74 static BOOL filetime_from_time(PFILETIME ft, time_t t);
76 char * w32_perlshell_tokens = Nullch;
77 char ** w32_perlshell_vec;
78 long w32_perlshell_items = -1;
79 DWORD w32_platform = (DWORD)-1;
80 char w32_perllib_root[MAX_PATH+1];
81 HANDLE w32_perldll_handle = INVALID_HANDLE_VALUE;
83 long w32_num_children = 0;
84 HANDLE w32_child_pids[MAXIMUM_WAIT_OBJECTS];
89 # define FOPEN_MAX _NSTREAM_
91 # define FOPEN_MAX _NFILE_
93 # define FOPEN_MAX _NFILE
98 int w32_popen_pids[FOPEN_MAX];
102 # ifdef USE_DECLSPEC_THREAD
103 __declspec(thread) char strerror_buffer[512];
104 __declspec(thread) char getlogin_buffer[128];
105 # ifdef HAVE_DES_FCRYPT
106 __declspec(thread) char crypt_buffer[30];
109 # define strerror_buffer (thr->i.Wstrerror_buffer)
110 # define getlogin_buffer (thr->i.Wgetlogin_buffer)
111 # define crypt_buffer (thr->i.Wcrypt_buffer)
114 char strerror_buffer[512];
115 char getlogin_buffer[128];
116 # ifdef HAVE_DES_FCRYPT
117 char crypt_buffer[30];
123 return (os_id() == VER_PLATFORM_WIN32_WINDOWS);
128 return (os_id() == VER_PLATFORM_WIN32_NT);
132 win32_perllib_path(char *sfx,...)
137 GetModuleFileName((w32_perldll_handle == INVALID_HANDLE_VALUE)
138 ? GetModuleHandle(NULL)
139 : w32_perldll_handle,
141 sizeof(w32_perllib_root));
142 *(end = strrchr(w32_perllib_root, '\\')) = '\0';
143 if (stricmp(end-4,"\\bin") == 0)
150 sfx = va_arg(ap,char *);
153 return (w32_perllib_root);
158 has_redirection(char *ptr)
164 * Scan string looking for redirection (< or >) or pipe
165 * characters (|) that are not in a quoted string
195 /* since the current process environment is being updated in util.c
196 * the library functions will get the correct environment
199 my_popen(char *cmd, char *mode)
202 #define fixcmd(x) { \
203 char *pspace = strchr((x),' '); \
206 while (p < pspace) { \
217 win32_fflush(stdout);
218 win32_fflush(stderr);
219 return win32_popen(cmd, mode);
223 my_pclose(PerlIO *fp)
225 return win32_pclose(fp);
231 static OSVERSIONINFO osver;
233 if (osver.dwPlatformId != w32_platform) {
234 memset(&osver, 0, sizeof(OSVERSIONINFO));
235 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
236 GetVersionEx(&osver);
237 w32_platform = osver.dwPlatformId;
239 return (w32_platform);
242 /* Tokenize a string. Words are null-separated, and the list
243 * ends with a doubled null. Any character (except null and
244 * including backslash) may be escaped by preceding it with a
245 * backslash (the backslash will be stripped).
246 * Returns number of words in result buffer.
249 tokenize(char *str, char **dest, char ***destv)
251 char *retstart = Nullch;
252 char **retvstart = 0;
255 int slen = strlen(str);
257 register char **retv;
258 New(1307, ret, slen+2, char);
259 New(1308, retv, (slen+3)/2, char*);
267 if (*ret == '\\' && *str)
269 else if (*ret == ' ') {
285 retvstart[items] = Nullch;
297 if (!w32_perlshell_tokens) {
298 /* we don't use COMSPEC here for two reasons:
299 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
300 * uncontrolled unportability of the ensuing scripts.
301 * 2. PERL5SHELL could be set to a shell that may not be fit for
302 * interactive use (which is what most programs look in COMSPEC
305 char* defaultshell = (IsWinNT() ? "cmd.exe /x/c" : "command.com /c");
306 char *usershell = getenv("PERL5SHELL");
307 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
308 &w32_perlshell_tokens,
314 do_aspawn(void *vreally, void **vmark, void **vsp)
316 SV *really = (SV*)vreally;
317 SV **mark = (SV**)vmark;
329 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
331 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
336 while (++mark <= sp) {
337 if (*mark && (str = SvPV(*mark, na)))
344 status = win32_spawnvp(flag,
345 (really ? SvPV(really,na) : argv[0]),
346 (const char* const*)argv);
348 if (status < 0 && errno == ENOEXEC) {
349 /* possible shell-builtin, invoke with shell */
351 sh_items = w32_perlshell_items;
353 argv[index+sh_items] = argv[index];
354 while (--sh_items >= 0)
355 argv[sh_items] = w32_perlshell_vec[sh_items];
357 status = win32_spawnvp(flag,
358 (really ? SvPV(really,na) : argv[0]),
359 (const char* const*)argv);
362 if (flag != P_NOWAIT) {
365 warn("Can't spawn \"%s\": %s", argv[0], strerror(errno));
370 statusvalue = status;
377 do_spawn2(char *cmd, int exectype)
383 BOOL needToTry = TRUE;
386 /* Save an extra exec if possible. See if there are shell
387 * metacharacters in it */
388 if (!has_redirection(cmd)) {
389 New(1301,argv, strlen(cmd) / 2 + 2, char*);
390 New(1302,cmd2, strlen(cmd) + 1, char);
393 for (s = cmd2; *s;) {
394 while (*s && isspace(*s))
398 while (*s && !isspace(*s))
407 status = win32_spawnvp(P_WAIT, argv[0],
408 (const char* const*)argv);
410 case EXECF_SPAWN_NOWAIT:
411 status = win32_spawnvp(P_NOWAIT, argv[0],
412 (const char* const*)argv);
415 status = win32_execvp(argv[0], (const char* const*)argv);
418 if (status != -1 || errno == 0)
428 New(1306, argv, w32_perlshell_items + 2, char*);
429 while (++i < w32_perlshell_items)
430 argv[i] = w32_perlshell_vec[i];
435 status = win32_spawnvp(P_WAIT, argv[0],
436 (const char* const*)argv);
438 case EXECF_SPAWN_NOWAIT:
439 status = win32_spawnvp(P_NOWAIT, argv[0],
440 (const char* const*)argv);
443 status = win32_execvp(argv[0], (const char* const*)argv);
449 if (exectype != EXECF_SPAWN_NOWAIT) {
452 warn("Can't %s \"%s\": %s",
453 (exectype == EXECF_EXEC ? "exec" : "spawn"),
454 cmd, strerror(errno));
459 statusvalue = status;
467 return do_spawn2(cmd, EXECF_SPAWN);
471 do_spawn_nowait(char *cmd)
473 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
479 do_spawn2(cmd, EXECF_EXEC);
483 /* The idea here is to read all the directory names into a string table
484 * (separated by nulls) and when one of the other dir functions is called
485 * return the pointer to the current file name.
488 opendir(char *filename)
493 char scanname[MAX_PATH+3];
495 WIN32_FIND_DATA FindData;
498 len = strlen(filename);
502 /* check to see if filename is a directory */
503 if (win32_stat(filename, &sbuf) < 0 || (sbuf.st_mode & S_IFDIR) == 0) {
504 /* CRT is buggy on sharenames, so make sure it really isn't */
505 DWORD r = GetFileAttributes(filename);
506 if (r == 0xffffffff || !(r & FILE_ATTRIBUTE_DIRECTORY))
510 /* Get us a DIR structure */
511 Newz(1303, p, 1, DIR);
515 /* Create the search pattern */
516 strcpy(scanname, filename);
517 if (scanname[len-1] != '/' && scanname[len-1] != '\\')
518 scanname[len++] = '/';
519 scanname[len++] = '*';
520 scanname[len] = '\0';
522 /* do the FindFirstFile call */
523 fh = FindFirstFile(scanname, &FindData);
524 if (fh == INVALID_HANDLE_VALUE) {
528 /* now allocate the first part of the string table for
529 * the filenames that we find.
531 idx = strlen(FindData.cFileName)+1;
532 New(1304, p->start, idx, char);
533 if (p->start == NULL)
534 croak("opendir: malloc failed!\n");
535 strcpy(p->start, FindData.cFileName);
538 /* loop finding all the files that match the wildcard
539 * (which should be all of them in this directory!).
540 * the variable idx should point one past the null terminator
541 * of the previous string found.
543 while (FindNextFile(fh, &FindData)) {
544 len = strlen(FindData.cFileName);
545 /* bump the string table size by enough for the
546 * new name and it's null terminator
548 Renew(p->start, idx+len+1, char);
549 if (p->start == NULL)
550 croak("opendir: malloc failed!\n");
551 strcpy(&p->start[idx], FindData.cFileName);
562 /* Readdir just returns the current string pointer and bumps the
563 * string pointer to the nDllExport entry.
569 static int dummy = 0;
572 /* first set up the structure to return */
573 len = strlen(dirp->curr);
574 strcpy(dirp->dirstr.d_name, dirp->curr);
575 dirp->dirstr.d_namlen = len;
578 dirp->dirstr.d_ino = dummy++;
580 /* Now set up for the nDllExport call to readdir */
581 dirp->curr += len + 1;
582 if (dirp->curr >= (dirp->start + dirp->size)) {
586 return &(dirp->dirstr);
592 /* Telldir returns the current string pointer position */
596 return (long) dirp->curr;
600 /* Seekdir moves the string pointer to a previously saved position
604 seekdir(DIR *dirp, long loc)
606 dirp->curr = (char *)loc;
609 /* Rewinddir resets the string pointer to the start */
613 dirp->curr = dirp->start;
616 /* free the memory allocated by opendir */
620 Safefree(dirp->start);
633 * Just pretend that everyone is a superuser. NT will let us know if
634 * we don\'t really have permission to do something.
637 #define ROOT_UID ((uid_t)0)
638 #define ROOT_GID ((gid_t)0)
667 return (auid == ROOT_UID ? 0 : -1);
673 return (agid == ROOT_GID ? 0 : -1);
680 char *buf = getlogin_buffer;
681 DWORD size = sizeof(getlogin_buffer);
682 if (GetUserName(buf,&size))
688 chown(const char *path, uid_t owner, gid_t group)
695 kill(int pid, int sig)
697 HANDLE hProcess= OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
699 if (hProcess == NULL) {
700 croak("kill process failed!\n");
703 if (!TerminateProcess(hProcess, sig))
704 croak("kill process failed!\n");
705 CloseHandle(hProcess);
714 DllExport unsigned int
715 win32_sleep(unsigned int t)
722 win32_stat(const char *path, struct stat *buffer)
725 const char *p = path;
726 int l = strlen(path);
730 switch(path[l - 1]) {
733 if (path[l - 2] != ':') {
734 strncpy(t, path, l - 1);
740 res = stat(p,buffer);
743 if (S_ISDIR(buffer->st_mode))
744 buffer->st_mode |= S_IWRITE | S_IEXEC;
745 else if (S_ISREG(buffer->st_mode)) {
746 if (l >= 4 && path[l-4] == '.') {
747 const char *e = path + l - 3;
748 if (strnicmp(e,"exe",3)
749 && strnicmp(e,"bat",3)
750 && strnicmp(e,"com",3)
751 && (IsWin95() || strnicmp(e,"cmd",3)))
752 buffer->st_mode &= ~S_IEXEC;
754 buffer->st_mode |= S_IEXEC;
757 buffer->st_mode &= ~S_IEXEC;
764 #ifndef USE_WIN32_RTL_ENV
767 win32_getenv(const char *name)
769 static char *curitem = Nullch;
770 static DWORD curlen = 512;
773 New(1305,curitem,curlen,char);
774 if (!(needlen = GetEnvironmentVariable(name,curitem,curlen)))
776 while (needlen > curlen) {
777 Renew(curitem,needlen,char);
779 needlen = GetEnvironmentVariable(name,curitem,curlen);
787 filetime_to_clock(PFILETIME ft)
789 __int64 qw = ft->dwHighDateTime;
791 qw |= ft->dwLowDateTime;
792 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
797 win32_times(struct tms *timebuf)
802 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
804 timebuf->tms_utime = filetime_to_clock(&user);
805 timebuf->tms_stime = filetime_to_clock(&kernel);
806 timebuf->tms_cutime = 0;
807 timebuf->tms_cstime = 0;
810 /* That failed - e.g. Win95 fallback to clock() */
812 timebuf->tms_utime = t;
813 timebuf->tms_stime = 0;
814 timebuf->tms_cutime = 0;
815 timebuf->tms_cstime = 0;
820 /* fix utime() so it works on directories in NT
821 * thanks to Jan Dubois <jan.dubois@ibm.net>
824 filetime_from_time(PFILETIME pFileTime, time_t Time)
826 struct tm *pTM = gmtime(&Time);
827 SYSTEMTIME SystemTime;
832 SystemTime.wYear = pTM->tm_year + 1900;
833 SystemTime.wMonth = pTM->tm_mon + 1;
834 SystemTime.wDay = pTM->tm_mday;
835 SystemTime.wHour = pTM->tm_hour;
836 SystemTime.wMinute = pTM->tm_min;
837 SystemTime.wSecond = pTM->tm_sec;
838 SystemTime.wMilliseconds = 0;
840 return SystemTimeToFileTime(&SystemTime, pFileTime);
844 win32_utime(const char *filename, struct utimbuf *times)
850 struct utimbuf TimeBuffer;
852 int rc = utime(filename,times);
853 /* EACCES: path specifies directory or readonly file */
854 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
859 time(×->actime);
860 times->modtime = times->actime;
863 /* This will (and should) still fail on readonly files */
864 handle = CreateFile(filename, GENERIC_READ | GENERIC_WRITE,
865 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
866 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
867 if (handle == INVALID_HANDLE_VALUE)
870 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
871 filetime_from_time(&ftAccess, times->actime) &&
872 filetime_from_time(&ftWrite, times->modtime) &&
873 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
883 win32_wait(int *status)
888 /* XXX this wait emulation only knows about processes
889 * spawned via win32_spawnvp(P_NOWAIT, ...).
892 DWORD exitcode, waitcode;
894 if (!w32_num_children) {
899 /* if a child exists, wait for it to die */
900 waitcode = WaitForMultipleObjects(w32_num_children,
904 if (waitcode != WAIT_FAILED) {
905 if (waitcode >= WAIT_ABANDONED_0
906 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
907 i = waitcode - WAIT_ABANDONED_0;
909 i = waitcode - WAIT_OBJECT_0;
910 if (GetExitCodeProcess(w32_child_pids[i], &exitcode) ) {
911 CloseHandle(w32_child_pids[i]);
912 *status = (int)((exitcode & 0xff) << 8);
913 retval = (int)w32_child_pids[i];
914 Copy(&w32_child_pids[i+1], &w32_child_pids[i],
915 (w32_num_children-i-1), HANDLE);
922 errno = GetLastError();
928 static UINT timerid = 0;
930 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
932 KillTimer(NULL,timerid);
937 DllExport unsigned int
938 win32_alarm(unsigned int sec)
941 * the 'obvious' implentation is SetTimer() with a callback
942 * which does whatever receiving SIGALRM would do
943 * we cannot use SIGALRM even via raise() as it is not
944 * one of the supported codes in <signal.h>
946 * Snag is unless something is looking at the message queue
947 * nothing happens :-(
951 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
953 croak("Cannot set timer");
959 KillTimer(NULL,timerid);
966 #ifdef HAVE_DES_FCRYPT
967 extern char * des_fcrypt(char *cbuf, const char *txt, const char *salt);
970 win32_crypt(const char *txt, const char *salt)
973 return des_fcrypt(crypt_buffer, txt, salt);
977 #ifdef USE_FIXED_OSFHANDLE
979 EXTERN_C int __cdecl _alloc_osfhnd(void);
980 EXTERN_C int __cdecl _set_osfhnd(int fh, long value);
981 EXTERN_C void __cdecl _lock_fhandle(int);
982 EXTERN_C void __cdecl _unlock_fhandle(int);
983 EXTERN_C void __cdecl _unlock(int);
985 #if (_MSC_VER >= 1000)
987 long osfhnd; /* underlying OS file HANDLE */
988 char osfile; /* attributes of file (e.g., open in text mode?) */
989 char pipech; /* one char buffer for handles opened on pipes */
990 #if defined (_MT) && !defined (DLL_FOR_WIN32S)
992 CRITICAL_SECTION lock;
993 #endif /* defined (_MT) && !defined (DLL_FOR_WIN32S) */
996 EXTERN_C ioinfo * __pioinfo[];
999 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
1000 #define _pioinfo(i) (__pioinfo[i >> IOINFO_L2E] + (i & (IOINFO_ARRAY_ELTS - 1)))
1001 #define _osfile(i) (_pioinfo(i)->osfile)
1003 #else /* (_MSC_VER >= 1000) */
1004 extern char _osfile[];
1005 #endif /* (_MSC_VER >= 1000) */
1007 #define FOPEN 0x01 /* file handle open */
1008 #define FAPPEND 0x20 /* file handle opened O_APPEND */
1009 #define FDEV 0x40 /* file handle refers to device */
1010 #define FTEXT 0x80 /* file handle is in text mode */
1012 #define _STREAM_LOCKS 26 /* Table of stream locks */
1013 #define _LAST_STREAM_LOCK (_STREAM_LOCKS+_NSTREAM_-1) /* Last stream lock */
1014 #define _FH_LOCKS (_LAST_STREAM_LOCK+1) /* Table of fh locks */
1017 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1020 * This function allocates a free C Runtime file handle and associates
1021 * it with the Win32 HANDLE specified by the first parameter. This is a
1022 * temperary fix for WIN95's brain damage GetFileType() error on socket
1023 * we just bypass that call for socket
1026 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1027 * int flags - flags to associate with C Runtime file handle.
1030 * returns index of entry in fh, if successful
1031 * return -1, if no free entry is found
1035 *******************************************************************************/
1038 my_open_osfhandle(long osfhandle, int flags)
1041 char fileflags; /* _osfile flags */
1043 /* copy relevant flags from second parameter */
1046 if (flags & O_APPEND)
1047 fileflags |= FAPPEND;
1052 /* attempt to allocate a C Runtime file handle */
1053 if ((fh = _alloc_osfhnd()) == -1) {
1054 errno = EMFILE; /* too many open files */
1055 _doserrno = 0L; /* not an OS error */
1056 return -1; /* return error to caller */
1059 /* the file is open. now, set the info in _osfhnd array */
1060 _set_osfhnd(fh, osfhandle);
1062 fileflags |= FOPEN; /* mark as open */
1064 #if (_MSC_VER >= 1000)
1065 _osfile(fh) = fileflags; /* set osfile entry */
1066 _unlock_fhandle(fh);
1068 _osfile[fh] = fileflags; /* set osfile entry */
1069 _unlock(fh+_FH_LOCKS); /* unlock handle */
1072 return fh; /* return handle */
1075 #define _open_osfhandle my_open_osfhandle
1076 #endif /* USE_FIXED_OSFHANDLE */
1078 /* simulate flock by locking a range on the file */
1080 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1081 #define LK_LEN 0xffff0000
1084 win32_flock(int fd, int oper)
1091 croak("flock() unimplemented on this platform");
1094 fh = (HANDLE)_get_osfhandle(fd);
1095 memset(&o, 0, sizeof(o));
1098 case LOCK_SH: /* shared lock */
1099 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1101 case LOCK_EX: /* exclusive lock */
1102 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1104 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1105 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1107 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1108 LK_ERR(LockFileEx(fh,
1109 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1110 0, LK_LEN, 0, &o),i);
1112 case LOCK_UN: /* unlock lock */
1113 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1115 default: /* unknown */
1126 * redirected io subsystem for all XS modules
1139 return (&(_environ));
1142 /* the rest are the remapped stdio routines */
1162 win32_ferror(FILE *fp)
1164 return (ferror(fp));
1169 win32_feof(FILE *fp)
1175 * Since the errors returned by the socket error function
1176 * WSAGetLastError() are not known by the library routine strerror
1177 * we have to roll our own.
1181 win32_strerror(int e)
1183 #ifndef __BORLANDC__ /* Borland intolerance */
1184 extern int sys_nerr;
1188 if (e < 0 || e > sys_nerr) {
1193 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
1194 strerror_buffer, sizeof(strerror_buffer), NULL) == 0)
1195 strcpy(strerror_buffer, "Unknown Error");
1197 return strerror_buffer;
1203 win32_str_os_error(void *sv, DWORD dwErr)
1207 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
1208 |FORMAT_MESSAGE_IGNORE_INSERTS
1209 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
1210 dwErr, 0, (char *)&sMsg, 1, NULL);
1212 while (0 < dwLen && isspace(sMsg[--dwLen]))
1214 if ('.' != sMsg[dwLen])
1219 sMsg = LocalAlloc(0, 64/**sizeof(TCHAR)*/);
1220 dwLen = sprintf(sMsg,
1221 "Unknown error #0x%lX (lookup 0x%lX)",
1222 dwErr, GetLastError());
1224 sv_setpvn((SV*)sv, sMsg, dwLen);
1230 win32_fprintf(FILE *fp, const char *format, ...)
1233 va_start(marker, format); /* Initialize variable arguments. */
1235 return (vfprintf(fp, format, marker));
1239 win32_printf(const char *format, ...)
1242 va_start(marker, format); /* Initialize variable arguments. */
1244 return (vprintf(format, marker));
1248 win32_vfprintf(FILE *fp, const char *format, va_list args)
1250 return (vfprintf(fp, format, args));
1254 win32_vprintf(const char *format, va_list args)
1256 return (vprintf(format, args));
1260 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
1262 return fread(buf, size, count, fp);
1266 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
1268 return fwrite(buf, size, count, fp);
1272 win32_fopen(const char *filename, const char *mode)
1274 if (stricmp(filename, "/dev/null")==0)
1275 return fopen("NUL", mode);
1276 return fopen(filename, mode);
1279 #ifndef USE_SOCKETS_AS_HANDLES
1281 #define fdopen my_fdopen
1285 win32_fdopen( int handle, const char *mode)
1287 return fdopen(handle, (char *) mode);
1291 win32_freopen( const char *path, const char *mode, FILE *stream)
1293 if (stricmp(path, "/dev/null")==0)
1294 return freopen("NUL", mode, stream);
1295 return freopen(path, mode, stream);
1299 win32_fclose(FILE *pf)
1301 return my_fclose(pf); /* defined in win32sck.c */
1305 win32_fputs(const char *s,FILE *pf)
1307 return fputs(s, pf);
1311 win32_fputc(int c,FILE *pf)
1317 win32_ungetc(int c,FILE *pf)
1319 return ungetc(c,pf);
1323 win32_getc(FILE *pf)
1329 win32_fileno(FILE *pf)
1335 win32_clearerr(FILE *pf)
1342 win32_fflush(FILE *pf)
1348 win32_ftell(FILE *pf)
1354 win32_fseek(FILE *pf,long offset,int origin)
1356 return fseek(pf, offset, origin);
1360 win32_fgetpos(FILE *pf,fpos_t *p)
1362 return fgetpos(pf, p);
1366 win32_fsetpos(FILE *pf,const fpos_t *p)
1368 return fsetpos(pf, p);
1372 win32_rewind(FILE *pf)
1392 win32_fstat(int fd,struct stat *sbufptr)
1394 return fstat(fd,sbufptr);
1398 win32_pipe(int *pfd, unsigned int size, int mode)
1400 return _pipe(pfd, size, mode);
1404 * a popen() clone that respects PERL5SHELL
1408 win32_popen(const char *command, const char *mode)
1410 #ifdef USE_CRT_POPEN
1411 return _popen(command, mode);
1419 /* establish which ends read and write */
1420 if (strchr(mode,'w')) {
1421 stdfd = 0; /* stdin */
1425 else if (strchr(mode,'r')) {
1426 stdfd = 1; /* stdout */
1433 /* set the correct mode */
1434 if (strchr(mode,'b'))
1436 else if (strchr(mode,'t'))
1439 ourmode = _fmode & (O_TEXT | O_BINARY);
1441 /* the child doesn't inherit handles */
1442 ourmode |= O_NOINHERIT;
1444 if (win32_pipe( p, 512, ourmode) == -1)
1447 /* save current stdfd */
1448 if ((oldfd = win32_dup(stdfd)) == -1)
1451 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
1452 /* stdfd will be inherited by the child */
1453 if (win32_dup2(p[child], stdfd) == -1)
1456 /* close the child end in parent */
1457 win32_close(p[child]);
1459 /* start the child */
1460 if ((childpid = do_spawn_nowait((char*)command)) == -1)
1463 /* revert stdfd to whatever it was before */
1464 if (win32_dup2(oldfd, stdfd) == -1)
1467 /* close saved handle */
1470 w32_popen_pids[p[parent]] = childpid;
1472 /* we have an fd, return a file stream */
1473 return (win32_fdopen(p[parent], (char *)mode));
1476 /* we don't need to check for errors here */
1480 win32_dup2(oldfd, stdfd);
1485 #endif /* USE_CRT_POPEN */
1493 win32_pclose(FILE *pf)
1495 #ifdef USE_CRT_POPEN
1498 int fd, childpid, status;
1500 fd = win32_fileno(pf);
1501 childpid = w32_popen_pids[fd];
1509 w32_popen_pids[fd] = 0;
1511 /* wait for the child */
1512 if (cwait(&status, childpid, WAIT_CHILD) == -1)
1514 /* cwait() returns differently on Borland */
1516 return (((status >> 8) & 0xff) | ((status << 8) & 0xff00));
1521 #endif /* USE_CRT_OPEN */
1525 win32_setmode(int fd, int mode)
1527 return setmode(fd, mode);
1531 win32_lseek(int fd, long offset, int origin)
1533 return lseek(fd, offset, origin);
1543 win32_open(const char *path, int flag, ...)
1549 pmode = va_arg(ap, int);
1552 if (stricmp(path, "/dev/null")==0)
1553 return open("NUL", flag, pmode);
1554 return open(path,flag,pmode);
1576 win32_dup2(int fd1,int fd2)
1578 return dup2(fd1,fd2);
1582 win32_read(int fd, void *buf, unsigned int cnt)
1584 return read(fd, buf, cnt);
1588 win32_write(int fd, const void *buf, unsigned int cnt)
1590 return write(fd, buf, cnt);
1594 win32_mkdir(const char *dir, int mode)
1596 return mkdir(dir); /* just ignore mode */
1600 win32_rmdir(const char *dir)
1606 win32_chdir(const char *dir)
1612 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
1616 status = spawnvp(mode, cmdname, (char * const *) argv);
1617 #ifndef __BORLANDC__
1618 /* XXX For the P_NOWAIT case, Borland RTL returns pinfo.dwProcessId
1619 * while VC RTL returns pinfo.hProcess. For purposes of the custom
1620 * implementation of win32_wait(), we assume the latter.
1622 if (mode == P_NOWAIT && status >= 0)
1623 w32_child_pids[w32_num_children++] = (HANDLE)status;
1629 win32_execvp(const char *cmdname, const char *const *argv)
1631 return execvp(cmdname, (char *const *)argv);
1635 win32_perror(const char *str)
1641 win32_setbuf(FILE *pf, char *buf)
1647 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
1649 return setvbuf(pf, buf, type, size);
1653 win32_flushall(void)
1659 win32_fcloseall(void)
1665 win32_fgets(char *s, int n, FILE *pf)
1667 return fgets(s, n, pf);
1677 win32_fgetc(FILE *pf)
1683 win32_putc(int c, FILE *pf)
1689 win32_puts(const char *s)
1701 win32_putchar(int c)
1708 #ifndef USE_PERL_SBRK
1710 static char *committed = NULL;
1711 static char *base = NULL;
1712 static char *reserved = NULL;
1713 static char *brk = NULL;
1714 static DWORD pagesize = 0;
1715 static DWORD allocsize = 0;
1723 GetSystemInfo(&info);
1724 /* Pretend page size is larger so we don't perpetually
1725 * call the OS to commit just one page ...
1727 pagesize = info.dwPageSize << 3;
1728 allocsize = info.dwAllocationGranularity;
1730 /* This scheme fails eventually if request for contiguous
1731 * block is denied so reserve big blocks - this is only
1732 * address space not memory ...
1734 if (brk+need >= reserved)
1736 DWORD size = 64*1024*1024;
1738 if (committed && reserved && committed < reserved)
1740 /* Commit last of previous chunk cannot span allocations */
1741 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
1743 committed = reserved;
1745 /* Reserve some (more) space
1746 * Note this is a little sneaky, 1st call passes NULL as reserved
1747 * so lets system choose where we start, subsequent calls pass
1748 * the old end address so ask for a contiguous block
1750 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
1753 reserved = addr+size;
1768 if (brk > committed)
1770 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
1771 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
1786 win32_malloc(size_t size)
1788 return malloc(size);
1792 win32_calloc(size_t numitems, size_t size)
1794 return calloc(numitems,size);
1798 win32_realloc(void *block, size_t size)
1800 return realloc(block,size);
1804 win32_free(void *block)
1811 win32_open_osfhandle(long handle, int flags)
1813 return _open_osfhandle(handle, flags);
1817 win32_get_osfhandle(int fd)
1819 return _get_osfhandle(fd);
1830 SV *sv = sv_newmortal();
1831 /* Make one call with zero size - return value is required size */
1832 DWORD len = GetCurrentDirectory((DWORD)0,NULL);
1833 SvUPGRADE(sv,SVt_PV);
1835 SvCUR(sv) = GetCurrentDirectory((DWORD) SvLEN(sv), SvPVX(sv));
1838 * then it worked, set PV valid,
1839 * else leave it 'undef'
1853 croak("usage: Win32::SetCurrentDirectory($cwd)");
1854 if (SetCurrentDirectory(SvPV(ST(0),na)))
1861 XS(w32_GetNextAvailDrive)
1865 char root[] = "_:\\";
1868 if (GetDriveType(root) == 1) {
1877 XS(w32_GetLastError)
1880 XSRETURN_IV(GetLastError());
1887 char *name = getlogin_buffer;
1888 DWORD size = sizeof(getlogin_buffer);
1889 if (GetUserName(name,&size)) {
1890 /* size includes NULL */
1891 ST(0) = sv_2mortal(newSVpv(name,size-1));
1901 char name[MAX_COMPUTERNAME_LENGTH+1];
1902 DWORD size = sizeof(name);
1903 if (GetComputerName(name,&size)) {
1904 /* size does NOT include NULL :-( */
1905 ST(0) = sv_2mortal(newSVpv(name,size));
1917 /* mingw32 doesn't have NetWksta*() yet, so do it the old way */
1919 DWORD size = sizeof(name);
1920 if (GetUserName(name,&size)) {
1922 DWORD sidlen = sizeof(sid);
1924 DWORD dnamelen = sizeof(dname);
1926 if (LookupAccountName(NULL, name, &sid, &sidlen,
1927 dname, &dnamelen, &snu)) {
1928 XSRETURN_PV(dname); /* all that for this */
1932 /* this way is more reliable, in case user has a local account */
1934 DWORD dnamelen = sizeof(dname);
1935 PWKSTA_INFO_100 pwi;
1936 if (NERR_Success == NetWkstaGetInfo(NULL, 100, (LPBYTE*)&pwi)) {
1937 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
1938 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
1939 -1, (LPSTR)dname, dnamelen, NULL, NULL);
1942 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
1943 -1, (LPSTR)dname, dnamelen, NULL, NULL);
1945 NetApiBufferFree(pwi);
1957 DWORD flags, filecomplen;
1958 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
1959 &flags, fsname, sizeof(fsname))) {
1960 if (GIMME == G_ARRAY) {
1961 XPUSHs(sv_2mortal(newSVpv(fsname,0)));
1962 XPUSHs(sv_2mortal(newSViv(flags)));
1963 XPUSHs(sv_2mortal(newSViv(filecomplen)));
1967 XSRETURN_PV(fsname);
1973 XS(w32_GetOSVersion)
1976 OSVERSIONINFO osver;
1978 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1979 if (GetVersionEx(&osver)) {
1980 XPUSHs(newSVpv(osver.szCSDVersion, 0));
1981 XPUSHs(newSViv(osver.dwMajorVersion));
1982 XPUSHs(newSViv(osver.dwMinorVersion));
1983 XPUSHs(newSViv(osver.dwBuildNumber));
1984 XPUSHs(newSViv(osver.dwPlatformId));
1995 XSRETURN_IV(IsWinNT());
2002 XSRETURN_IV(IsWin95());
2006 XS(w32_FormatMessage)
2013 croak("usage: Win32::FormatMessage($errno)");
2015 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
2016 &source, SvIV(ST(0)), 0,
2017 msgbuf, sizeof(msgbuf)-1, NULL))
2018 XSRETURN_PV(msgbuf);
2028 PROCESS_INFORMATION stProcInfo;
2029 STARTUPINFO stStartInfo;
2030 BOOL bSuccess = FALSE;
2033 croak("usage: Win32::Spawn($cmdName, $args, $PID)");
2035 cmd = SvPV(ST(0),na);
2036 args = SvPV(ST(1), na);
2038 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
2039 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
2040 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
2041 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
2044 cmd, /* Image path */
2045 args, /* Arguments for command line */
2046 NULL, /* Default process security */
2047 NULL, /* Default thread security */
2048 FALSE, /* Must be TRUE to use std handles */
2049 NORMAL_PRIORITY_CLASS, /* No special scheduling */
2050 NULL, /* Inherit our environment block */
2051 NULL, /* Inherit our currrent directory */
2052 &stStartInfo, /* -> Startup info */
2053 &stProcInfo)) /* <- Process info (if OK) */
2055 CloseHandle(stProcInfo.hThread);/* library source code does this. */
2056 sv_setiv(ST(2), stProcInfo.dwProcessId);
2059 XSRETURN_IV(bSuccess);
2063 XS(w32_GetTickCount)
2066 XSRETURN_IV(GetTickCount());
2070 XS(w32_GetShortPathName)
2077 croak("usage: Win32::GetShortPathName($longPathName)");
2079 shortpath = sv_mortalcopy(ST(0));
2080 SvUPGRADE(shortpath, SVt_PV);
2081 /* src == target is allowed */
2083 len = GetShortPathName(SvPVX(shortpath),
2086 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
2088 SvCUR_set(shortpath,len);
2101 croak("usage: Win32::Sleep($milliseconds)");
2107 Perl_init_os_extras()
2109 char *file = __FILE__;
2112 /* these names are Activeware compatible */
2113 newXS("Win32::GetCwd", w32_GetCwd, file);
2114 newXS("Win32::SetCwd", w32_SetCwd, file);
2115 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
2116 newXS("Win32::GetLastError", w32_GetLastError, file);
2117 newXS("Win32::LoginName", w32_LoginName, file);
2118 newXS("Win32::NodeName", w32_NodeName, file);
2119 newXS("Win32::DomainName", w32_DomainName, file);
2120 newXS("Win32::FsType", w32_FsType, file);
2121 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
2122 newXS("Win32::IsWinNT", w32_IsWinNT, file);
2123 newXS("Win32::IsWin95", w32_IsWin95, file);
2124 newXS("Win32::FormatMessage", w32_FormatMessage, file);
2125 newXS("Win32::Spawn", w32_Spawn, file);
2126 newXS("Win32::GetTickCount", w32_GetTickCount, file);
2127 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
2128 newXS("Win32::Sleep", w32_Sleep, file);
2130 /* XXX Bloat Alert! The following Activeware preloads really
2131 * ought to be part of Win32::Sys::*, so they're not included
2134 /* LookupAccountName
2136 * InitiateSystemShutdown
2137 * AbortSystemShutdown
2138 * ExpandEnvrironmentStrings
2143 Perl_win32_init(int *argcp, char ***argvp)
2145 /* Disable floating point errors, Perl will trap the ones we
2146 * care about. VC++ RTL defaults to switching these off
2147 * already, but the Borland RTL doesn't. Since we don't
2148 * want to be at the vendor's whim on the default, we set
2149 * it explicitly here.
2151 #if !defined(_ALPHA_) && !defined(__GNUC__)
2152 _control87(MCW_EM, MCW_EM);
2157 #ifdef USE_BINMODE_SCRIPTS
2160 win32_strip_return(SV *sv)
2162 char *s = SvPVX(sv);
2163 char *e = s+SvCUR(sv);
2167 if (*s == '\r' && s[1] == '\n')
2177 SvCUR_set(sv,d-SvPVX(sv));