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];
88 # ifdef USE_DECLSPEC_THREAD
89 __declspec(thread) char strerror_buffer[512];
90 __declspec(thread) char getlogin_buffer[128];
91 # ifdef HAVE_DES_FCRYPT
92 __declspec(thread) char crypt_buffer[30];
95 # define strerror_buffer (thr->i.Wstrerror_buffer)
96 # define getlogin_buffer (thr->i.Wgetlogin_buffer)
97 # define crypt_buffer (thr->i.Wcrypt_buffer)
100 char strerror_buffer[512];
101 char getlogin_buffer[128];
102 # ifdef HAVE_DES_FCRYPT
103 char crypt_buffer[30];
109 return (os_id() == VER_PLATFORM_WIN32_WINDOWS);
114 return (os_id() == VER_PLATFORM_WIN32_NT);
118 win32_perllib_path(char *sfx,...)
123 GetModuleFileName((w32_perldll_handle == INVALID_HANDLE_VALUE)
124 ? GetModuleHandle(NULL)
125 : w32_perldll_handle,
127 sizeof(w32_perllib_root));
128 *(end = strrchr(w32_perllib_root, '\\')) = '\0';
129 if (stricmp(end-4,"\\bin") == 0)
136 sfx = va_arg(ap,char *);
139 return (w32_perllib_root);
144 has_redirection(char *ptr)
150 * Scan string looking for redirection (< or >) or pipe
151 * characters (|) that are not in a quoted string
181 /* since the current process environment is being updated in util.c
182 * the library functions will get the correct environment
185 my_popen(char *cmd, char *mode)
188 #define fixcmd(x) { \
189 char *pspace = strchr((x),' '); \
192 while (p < pspace) { \
203 win32_fflush(stdout);
204 win32_fflush(stderr);
205 return win32_popen(cmd, mode);
209 my_pclose(PerlIO *fp)
211 return win32_pclose(fp);
217 static OSVERSIONINFO osver;
219 if (osver.dwPlatformId != w32_platform) {
220 memset(&osver, 0, sizeof(OSVERSIONINFO));
221 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
222 GetVersionEx(&osver);
223 w32_platform = osver.dwPlatformId;
225 return (w32_platform);
228 /* Tokenize a string. Words are null-separated, and the list
229 * ends with a doubled null. Any character (except null and
230 * including backslash) may be escaped by preceding it with a
231 * backslash (the backslash will be stripped).
232 * Returns number of words in result buffer.
235 tokenize(char *str, char **dest, char ***destv)
237 char *retstart = Nullch;
238 char **retvstart = 0;
241 int slen = strlen(str);
243 register char **retv;
244 New(1307, ret, slen+2, char);
245 New(1308, retv, (slen+3)/2, char*);
253 if (*ret == '\\' && *str)
255 else if (*ret == ' ') {
271 retvstart[items] = Nullch;
283 if (!w32_perlshell_tokens) {
284 /* we don't use COMSPEC here for two reasons:
285 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
286 * uncontrolled unportability of the ensuing scripts.
287 * 2. PERL5SHELL could be set to a shell that may not be fit for
288 * interactive use (which is what most programs look in COMSPEC
291 char* defaultshell = (IsWinNT() ? "cmd.exe /x/c" : "command.com /c");
292 char *usershell = getenv("PERL5SHELL");
293 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
294 &w32_perlshell_tokens,
300 do_aspawn(void *vreally, void **vmark, void **vsp)
302 SV *really = (SV*)vreally;
303 SV **mark = (SV**)vmark;
315 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
317 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
322 while (++mark <= sp) {
323 if (*mark && (str = SvPV(*mark, na)))
330 status = win32_spawnvp(flag,
331 (really ? SvPV(really,na) : argv[0]),
332 (const char* const*)argv);
334 if (status < 0 && errno == ENOEXEC) {
335 /* possible shell-builtin, invoke with shell */
337 sh_items = w32_perlshell_items;
339 argv[index+sh_items] = argv[index];
340 while (--sh_items >= 0)
341 argv[sh_items] = w32_perlshell_vec[sh_items];
343 status = win32_spawnvp(flag,
344 (really ? SvPV(really,na) : argv[0]),
345 (const char* const*)argv);
348 if (flag != P_NOWAIT) {
351 warn("Can't spawn \"%s\": %s", argv[0], strerror(errno));
356 statusvalue = status;
363 do_spawn2(char *cmd, int exectype)
369 BOOL needToTry = TRUE;
372 /* Save an extra exec if possible. See if there are shell
373 * metacharacters in it */
374 if (!has_redirection(cmd)) {
375 New(1301,argv, strlen(cmd) / 2 + 2, char*);
376 New(1302,cmd2, strlen(cmd) + 1, char);
379 for (s = cmd2; *s;) {
380 while (*s && isspace(*s))
384 while (*s && !isspace(*s))
393 status = win32_spawnvp(P_WAIT, argv[0],
394 (const char* const*)argv);
396 case EXECF_SPAWN_NOWAIT:
397 status = win32_spawnvp(P_NOWAIT, argv[0],
398 (const char* const*)argv);
401 status = win32_execvp(argv[0], (const char* const*)argv);
404 if (status != -1 || errno == 0)
414 New(1306, argv, w32_perlshell_items + 2, char*);
415 while (++i < w32_perlshell_items)
416 argv[i] = w32_perlshell_vec[i];
421 status = win32_spawnvp(P_WAIT, argv[0],
422 (const char* const*)argv);
424 case EXECF_SPAWN_NOWAIT:
425 status = win32_spawnvp(P_NOWAIT, argv[0],
426 (const char* const*)argv);
429 status = win32_execvp(argv[0], (const char* const*)argv);
435 if (exectype != EXECF_SPAWN_NOWAIT) {
438 warn("Can't %s \"%s\": %s",
439 (exectype == EXECF_EXEC ? "exec" : "spawn"),
440 cmd, strerror(errno));
445 statusvalue = status;
453 return do_spawn2(cmd, EXECF_SPAWN);
457 do_spawn_nowait(char *cmd)
459 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
465 do_spawn2(cmd, EXECF_EXEC);
469 /* The idea here is to read all the directory names into a string table
470 * (separated by nulls) and when one of the other dir functions is called
471 * return the pointer to the current file name.
474 opendir(char *filename)
479 char scanname[MAX_PATH+3];
481 WIN32_FIND_DATA FindData;
484 len = strlen(filename);
488 /* check to see if filename is a directory */
489 if (win32_stat(filename, &sbuf) < 0 || (sbuf.st_mode & S_IFDIR) == 0) {
490 /* CRT is buggy on sharenames, so make sure it really isn't */
491 DWORD r = GetFileAttributes(filename);
492 if (r == 0xffffffff || !(r & FILE_ATTRIBUTE_DIRECTORY))
496 /* Get us a DIR structure */
497 Newz(1303, p, 1, DIR);
501 /* Create the search pattern */
502 strcpy(scanname, filename);
503 if (scanname[len-1] != '/' && scanname[len-1] != '\\')
504 scanname[len++] = '/';
505 scanname[len++] = '*';
506 scanname[len] = '\0';
508 /* do the FindFirstFile call */
509 fh = FindFirstFile(scanname, &FindData);
510 if (fh == INVALID_HANDLE_VALUE) {
514 /* now allocate the first part of the string table for
515 * the filenames that we find.
517 idx = strlen(FindData.cFileName)+1;
518 New(1304, p->start, idx, char);
519 if (p->start == NULL)
520 croak("opendir: malloc failed!\n");
521 strcpy(p->start, FindData.cFileName);
524 /* loop finding all the files that match the wildcard
525 * (which should be all of them in this directory!).
526 * the variable idx should point one past the null terminator
527 * of the previous string found.
529 while (FindNextFile(fh, &FindData)) {
530 len = strlen(FindData.cFileName);
531 /* bump the string table size by enough for the
532 * new name and it's null terminator
534 Renew(p->start, idx+len+1, char);
535 if (p->start == NULL)
536 croak("opendir: malloc failed!\n");
537 strcpy(&p->start[idx], FindData.cFileName);
548 /* Readdir just returns the current string pointer and bumps the
549 * string pointer to the nDllExport entry.
555 static int dummy = 0;
558 /* first set up the structure to return */
559 len = strlen(dirp->curr);
560 strcpy(dirp->dirstr.d_name, dirp->curr);
561 dirp->dirstr.d_namlen = len;
564 dirp->dirstr.d_ino = dummy++;
566 /* Now set up for the nDllExport call to readdir */
567 dirp->curr += len + 1;
568 if (dirp->curr >= (dirp->start + dirp->size)) {
572 return &(dirp->dirstr);
578 /* Telldir returns the current string pointer position */
582 return (long) dirp->curr;
586 /* Seekdir moves the string pointer to a previously saved position
590 seekdir(DIR *dirp, long loc)
592 dirp->curr = (char *)loc;
595 /* Rewinddir resets the string pointer to the start */
599 dirp->curr = dirp->start;
602 /* free the memory allocated by opendir */
606 Safefree(dirp->start);
619 * Just pretend that everyone is a superuser. NT will let us know if
620 * we don\'t really have permission to do something.
623 #define ROOT_UID ((uid_t)0)
624 #define ROOT_GID ((gid_t)0)
653 return (auid == ROOT_UID ? 0 : -1);
659 return (agid == ROOT_GID ? 0 : -1);
666 char *buf = getlogin_buffer;
667 DWORD size = sizeof(getlogin_buffer);
668 if (GetUserName(buf,&size))
674 chown(const char *path, uid_t owner, gid_t group)
681 kill(int pid, int sig)
683 HANDLE hProcess= OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
685 if (hProcess == NULL) {
686 croak("kill process failed!\n");
689 if (!TerminateProcess(hProcess, sig))
690 croak("kill process failed!\n");
691 CloseHandle(hProcess);
700 DllExport unsigned int
701 win32_sleep(unsigned int t)
708 win32_stat(const char *path, struct stat *buffer)
711 const char *p = path;
712 int l = strlen(path);
716 switch(path[l - 1]) {
719 if (path[l - 2] != ':') {
720 strncpy(t, path, l - 1);
726 res = stat(p,buffer);
729 if (S_ISDIR(buffer->st_mode))
730 buffer->st_mode |= S_IWRITE | S_IEXEC;
731 else if (S_ISREG(buffer->st_mode)) {
732 if (l >= 4 && path[l-4] == '.') {
733 const char *e = path + l - 3;
734 if (strnicmp(e,"exe",3)
735 && strnicmp(e,"bat",3)
736 && strnicmp(e,"com",3)
737 && (IsWin95() || strnicmp(e,"cmd",3)))
738 buffer->st_mode &= ~S_IEXEC;
740 buffer->st_mode |= S_IEXEC;
743 buffer->st_mode &= ~S_IEXEC;
750 #ifndef USE_WIN32_RTL_ENV
753 win32_getenv(const char *name)
755 static char *curitem = Nullch;
756 static DWORD curlen = 512;
759 New(1305,curitem,curlen,char);
760 if (!(needlen = GetEnvironmentVariable(name,curitem,curlen)))
762 while (needlen > curlen) {
763 Renew(curitem,needlen,char);
765 needlen = GetEnvironmentVariable(name,curitem,curlen);
773 filetime_to_clock(PFILETIME ft)
775 __int64 qw = ft->dwHighDateTime;
777 qw |= ft->dwLowDateTime;
778 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
783 win32_times(struct tms *timebuf)
788 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
790 timebuf->tms_utime = filetime_to_clock(&user);
791 timebuf->tms_stime = filetime_to_clock(&kernel);
792 timebuf->tms_cutime = 0;
793 timebuf->tms_cstime = 0;
796 /* That failed - e.g. Win95 fallback to clock() */
798 timebuf->tms_utime = t;
799 timebuf->tms_stime = 0;
800 timebuf->tms_cutime = 0;
801 timebuf->tms_cstime = 0;
806 /* fix utime() so it works on directories in NT
807 * thanks to Jan Dubois <jan.dubois@ibm.net>
810 filetime_from_time(PFILETIME pFileTime, time_t Time)
812 struct tm *pTM = gmtime(&Time);
813 SYSTEMTIME SystemTime;
818 SystemTime.wYear = pTM->tm_year + 1900;
819 SystemTime.wMonth = pTM->tm_mon + 1;
820 SystemTime.wDay = pTM->tm_mday;
821 SystemTime.wHour = pTM->tm_hour;
822 SystemTime.wMinute = pTM->tm_min;
823 SystemTime.wSecond = pTM->tm_sec;
824 SystemTime.wMilliseconds = 0;
826 return SystemTimeToFileTime(&SystemTime, pFileTime);
830 win32_utime(const char *filename, struct utimbuf *times)
836 struct utimbuf TimeBuffer;
838 int rc = utime(filename,times);
839 /* EACCES: path specifies directory or readonly file */
840 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
845 time(×->actime);
846 times->modtime = times->actime;
849 /* This will (and should) still fail on readonly files */
850 handle = CreateFile(filename, GENERIC_READ | GENERIC_WRITE,
851 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
852 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
853 if (handle == INVALID_HANDLE_VALUE)
856 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
857 filetime_from_time(&ftAccess, times->actime) &&
858 filetime_from_time(&ftWrite, times->modtime) &&
859 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
869 win32_wait(int *status)
874 /* XXX this wait emulation only knows about processes
875 * spawned via win32_spawnvp(P_NOWAIT, ...).
878 DWORD exitcode, waitcode;
880 if (!w32_num_children) {
885 /* if a child exists, wait for it to die */
886 waitcode = WaitForMultipleObjects(w32_num_children,
890 if (waitcode != WAIT_FAILED) {
891 if (waitcode >= WAIT_ABANDONED_0
892 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
893 i = waitcode - WAIT_ABANDONED_0;
895 i = waitcode - WAIT_OBJECT_0;
896 if (GetExitCodeProcess(w32_child_pids[i], &exitcode) ) {
897 CloseHandle(w32_child_pids[i]);
898 *status = (int)((exitcode & 0xff) << 8);
899 retval = (int)w32_child_pids[i];
900 Copy(&w32_child_pids[i+1], &w32_child_pids[i],
901 (w32_num_children-i-1), HANDLE);
908 errno = GetLastError();
914 static UINT timerid = 0;
916 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
918 KillTimer(NULL,timerid);
923 DllExport unsigned int
924 win32_alarm(unsigned int sec)
927 * the 'obvious' implentation is SetTimer() with a callback
928 * which does whatever receiving SIGALRM would do
929 * we cannot use SIGALRM even via raise() as it is not
930 * one of the supported codes in <signal.h>
932 * Snag is unless something is looking at the message queue
933 * nothing happens :-(
937 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
939 croak("Cannot set timer");
945 KillTimer(NULL,timerid);
952 #ifdef HAVE_DES_FCRYPT
953 extern char * des_fcrypt(char *cbuf, const char *txt, const char *salt);
956 win32_crypt(const char *txt, const char *salt)
959 return des_fcrypt(crypt_buffer, txt, salt);
963 #ifdef USE_FIXED_OSFHANDLE
965 EXTERN_C int __cdecl _alloc_osfhnd(void);
966 EXTERN_C int __cdecl _set_osfhnd(int fh, long value);
967 EXTERN_C void __cdecl _lock_fhandle(int);
968 EXTERN_C void __cdecl _unlock_fhandle(int);
969 EXTERN_C void __cdecl _unlock(int);
971 #if (_MSC_VER >= 1000)
973 long osfhnd; /* underlying OS file HANDLE */
974 char osfile; /* attributes of file (e.g., open in text mode?) */
975 char pipech; /* one char buffer for handles opened on pipes */
976 #if defined (_MT) && !defined (DLL_FOR_WIN32S)
978 CRITICAL_SECTION lock;
979 #endif /* defined (_MT) && !defined (DLL_FOR_WIN32S) */
982 EXTERN_C ioinfo * __pioinfo[];
985 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
986 #define _pioinfo(i) (__pioinfo[i >> IOINFO_L2E] + (i & (IOINFO_ARRAY_ELTS - 1)))
987 #define _osfile(i) (_pioinfo(i)->osfile)
989 #else /* (_MSC_VER >= 1000) */
990 extern char _osfile[];
991 #endif /* (_MSC_VER >= 1000) */
993 #define FOPEN 0x01 /* file handle open */
994 #define FAPPEND 0x20 /* file handle opened O_APPEND */
995 #define FDEV 0x40 /* file handle refers to device */
996 #define FTEXT 0x80 /* file handle is in text mode */
998 #define _STREAM_LOCKS 26 /* Table of stream locks */
999 #define _LAST_STREAM_LOCK (_STREAM_LOCKS+_NSTREAM_-1) /* Last stream lock */
1000 #define _FH_LOCKS (_LAST_STREAM_LOCK+1) /* Table of fh locks */
1003 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1006 * This function allocates a free C Runtime file handle and associates
1007 * it with the Win32 HANDLE specified by the first parameter. This is a
1008 * temperary fix for WIN95's brain damage GetFileType() error on socket
1009 * we just bypass that call for socket
1012 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1013 * int flags - flags to associate with C Runtime file handle.
1016 * returns index of entry in fh, if successful
1017 * return -1, if no free entry is found
1021 *******************************************************************************/
1024 my_open_osfhandle(long osfhandle, int flags)
1027 char fileflags; /* _osfile flags */
1029 /* copy relevant flags from second parameter */
1032 if (flags & O_APPEND)
1033 fileflags |= FAPPEND;
1038 /* attempt to allocate a C Runtime file handle */
1039 if ((fh = _alloc_osfhnd()) == -1) {
1040 errno = EMFILE; /* too many open files */
1041 _doserrno = 0L; /* not an OS error */
1042 return -1; /* return error to caller */
1045 /* the file is open. now, set the info in _osfhnd array */
1046 _set_osfhnd(fh, osfhandle);
1048 fileflags |= FOPEN; /* mark as open */
1050 #if (_MSC_VER >= 1000)
1051 _osfile(fh) = fileflags; /* set osfile entry */
1052 _unlock_fhandle(fh);
1054 _osfile[fh] = fileflags; /* set osfile entry */
1055 _unlock(fh+_FH_LOCKS); /* unlock handle */
1058 return fh; /* return handle */
1061 #define _open_osfhandle my_open_osfhandle
1062 #endif /* USE_FIXED_OSFHANDLE */
1064 /* simulate flock by locking a range on the file */
1066 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1067 #define LK_LEN 0xffff0000
1070 win32_flock(int fd, int oper)
1077 croak("flock() unimplemented on this platform");
1080 fh = (HANDLE)_get_osfhandle(fd);
1081 memset(&o, 0, sizeof(o));
1084 case LOCK_SH: /* shared lock */
1085 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1087 case LOCK_EX: /* exclusive lock */
1088 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1090 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1091 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1093 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1094 LK_ERR(LockFileEx(fh,
1095 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1096 0, LK_LEN, 0, &o),i);
1098 case LOCK_UN: /* unlock lock */
1099 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1101 default: /* unknown */
1112 * redirected io subsystem for all XS modules
1125 return (&(_environ));
1128 /* the rest are the remapped stdio routines */
1148 win32_ferror(FILE *fp)
1150 return (ferror(fp));
1155 win32_feof(FILE *fp)
1161 * Since the errors returned by the socket error function
1162 * WSAGetLastError() are not known by the library routine strerror
1163 * we have to roll our own.
1167 win32_strerror(int e)
1169 #ifndef __BORLANDC__ /* Borland intolerance */
1170 extern int sys_nerr;
1174 if (e < 0 || e > sys_nerr) {
1179 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
1180 strerror_buffer, sizeof(strerror_buffer), NULL) == 0)
1181 strcpy(strerror_buffer, "Unknown Error");
1183 return strerror_buffer;
1189 win32_str_os_error(void *sv, DWORD dwErr)
1193 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
1194 |FORMAT_MESSAGE_IGNORE_INSERTS
1195 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
1196 dwErr, 0, (char *)&sMsg, 1, NULL);
1198 while (0 < dwLen && isspace(sMsg[--dwLen]))
1200 if ('.' != sMsg[dwLen])
1205 sMsg = LocalAlloc(0, 64/**sizeof(TCHAR)*/);
1206 dwLen = sprintf(sMsg,
1207 "Unknown error #0x%lX (lookup 0x%lX)",
1208 dwErr, GetLastError());
1210 sv_setpvn((SV*)sv, sMsg, dwLen);
1216 win32_fprintf(FILE *fp, const char *format, ...)
1219 va_start(marker, format); /* Initialize variable arguments. */
1221 return (vfprintf(fp, format, marker));
1225 win32_printf(const char *format, ...)
1228 va_start(marker, format); /* Initialize variable arguments. */
1230 return (vprintf(format, marker));
1234 win32_vfprintf(FILE *fp, const char *format, va_list args)
1236 return (vfprintf(fp, format, args));
1240 win32_vprintf(const char *format, va_list args)
1242 return (vprintf(format, args));
1246 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
1248 return fread(buf, size, count, fp);
1252 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
1254 return fwrite(buf, size, count, fp);
1258 win32_fopen(const char *filename, const char *mode)
1260 if (stricmp(filename, "/dev/null")==0)
1261 return fopen("NUL", mode);
1262 return fopen(filename, mode);
1265 #ifndef USE_SOCKETS_AS_HANDLES
1267 #define fdopen my_fdopen
1271 win32_fdopen( int handle, const char *mode)
1273 return fdopen(handle, (char *) mode);
1277 win32_freopen( const char *path, const char *mode, FILE *stream)
1279 if (stricmp(path, "/dev/null")==0)
1280 return freopen("NUL", mode, stream);
1281 return freopen(path, mode, stream);
1285 win32_fclose(FILE *pf)
1287 return my_fclose(pf); /* defined in win32sck.c */
1291 win32_fputs(const char *s,FILE *pf)
1293 return fputs(s, pf);
1297 win32_fputc(int c,FILE *pf)
1303 win32_ungetc(int c,FILE *pf)
1305 return ungetc(c,pf);
1309 win32_getc(FILE *pf)
1315 win32_fileno(FILE *pf)
1321 win32_clearerr(FILE *pf)
1328 win32_fflush(FILE *pf)
1334 win32_ftell(FILE *pf)
1340 win32_fseek(FILE *pf,long offset,int origin)
1342 return fseek(pf, offset, origin);
1346 win32_fgetpos(FILE *pf,fpos_t *p)
1348 return fgetpos(pf, p);
1352 win32_fsetpos(FILE *pf,const fpos_t *p)
1354 return fsetpos(pf, p);
1358 win32_rewind(FILE *pf)
1378 win32_fstat(int fd,struct stat *sbufptr)
1380 return fstat(fd,sbufptr);
1384 win32_pipe(int *pfd, unsigned int size, int mode)
1386 return _pipe(pfd, size, mode);
1390 * a popen() clone that respects PERL5SHELL
1394 win32_popen(const char *command, const char *mode)
1396 #ifdef USE_CRT_POPEN
1397 return _popen(command, mode);
1405 /* establish which ends read and write */
1406 if (strchr(mode,'w')) {
1407 stdfd = 0; /* stdin */
1411 else if (strchr(mode,'r')) {
1412 stdfd = 1; /* stdout */
1419 /* set the correct mode */
1420 if (strchr(mode,'b'))
1422 else if (strchr(mode,'t'))
1425 ourmode = _fmode & (O_TEXT | O_BINARY);
1427 /* the child doesn't inherit handles */
1428 ourmode |= O_NOINHERIT;
1430 if (win32_pipe( p, 512, ourmode) == -1)
1433 /* save current stdfd */
1434 if ((oldfd = win32_dup(stdfd)) == -1)
1437 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
1438 /* stdfd will be inherited by the child */
1439 if (win32_dup2(p[child], stdfd) == -1)
1442 /* close the child end in parent */
1443 win32_close(p[child]);
1445 /* start the child */
1446 if ((childpid = do_spawn_nowait((char*)command)) == -1)
1449 /* revert stdfd to whatever it was before */
1450 if (win32_dup2(oldfd, stdfd) == -1)
1453 /* close saved handle */
1455 sv_setiv(*av_fetch(fdpid, p[parent], TRUE), childpid);
1457 /* we have an fd, return a file stream */
1458 return (win32_fdopen(p[parent], (char *)mode));
1461 /* we don't need to check for errors here */
1465 win32_dup2(oldfd, stdfd);
1470 #endif /* USE_CRT_POPEN */
1478 win32_pclose(FILE *pf)
1480 #ifdef USE_CRT_POPEN
1484 #ifndef __BORLANDC__
1488 int childpid, status;
1491 sv = *av_fetch(fdpid, win32_fileno(pf), TRUE);
1493 childpid = SvIVX(sv);
1505 #ifndef __BORLANDC__
1506 for (child = 0 ; child < w32_num_children ; ++child) {
1507 if (w32_child_pids[child] == (HANDLE)childpid) {
1508 Copy(&w32_child_pids[child+1], &w32_child_pids[child],
1509 (w32_num_children-child-1), HANDLE);
1516 /* wait for the child */
1517 if (cwait(&status, childpid, WAIT_CHILD) == -1)
1519 /* cwait() returns differently on Borland */
1521 return (((status >> 8) & 0xff) | ((status << 8) & 0xff00));
1526 #endif /* USE_CRT_OPEN */
1530 win32_setmode(int fd, int mode)
1532 return setmode(fd, mode);
1536 win32_lseek(int fd, long offset, int origin)
1538 return lseek(fd, offset, origin);
1548 win32_open(const char *path, int flag, ...)
1554 pmode = va_arg(ap, int);
1557 if (stricmp(path, "/dev/null")==0)
1558 return open("NUL", flag, pmode);
1559 return open(path,flag,pmode);
1581 win32_dup2(int fd1,int fd2)
1583 return dup2(fd1,fd2);
1587 win32_read(int fd, void *buf, unsigned int cnt)
1589 return read(fd, buf, cnt);
1593 win32_write(int fd, const void *buf, unsigned int cnt)
1595 return write(fd, buf, cnt);
1599 win32_mkdir(const char *dir, int mode)
1601 return mkdir(dir); /* just ignore mode */
1605 win32_rmdir(const char *dir)
1611 win32_chdir(const char *dir)
1617 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
1621 #ifndef __BORLANDC__
1622 if (mode == P_NOWAIT && w32_num_children >= MAXIMUM_WAIT_OBJECTS)
1626 status = spawnvp(mode, cmdname, (char * const *) argv);
1627 #ifndef __BORLANDC__
1628 /* XXX For the P_NOWAIT case, Borland RTL returns pinfo.dwProcessId
1629 * while VC RTL returns pinfo.hProcess. For purposes of the custom
1630 * implementation of win32_wait(), we assume the latter.
1632 if (mode == P_NOWAIT && status >= 0)
1633 w32_child_pids[w32_num_children++] = (HANDLE)status;
1639 win32_execvp(const char *cmdname, const char *const *argv)
1641 return execvp(cmdname, (char *const *)argv);
1645 win32_perror(const char *str)
1651 win32_setbuf(FILE *pf, char *buf)
1657 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
1659 return setvbuf(pf, buf, type, size);
1663 win32_flushall(void)
1669 win32_fcloseall(void)
1675 win32_fgets(char *s, int n, FILE *pf)
1677 return fgets(s, n, pf);
1687 win32_fgetc(FILE *pf)
1693 win32_putc(int c, FILE *pf)
1699 win32_puts(const char *s)
1711 win32_putchar(int c)
1718 #ifndef USE_PERL_SBRK
1720 static char *committed = NULL;
1721 static char *base = NULL;
1722 static char *reserved = NULL;
1723 static char *brk = NULL;
1724 static DWORD pagesize = 0;
1725 static DWORD allocsize = 0;
1733 GetSystemInfo(&info);
1734 /* Pretend page size is larger so we don't perpetually
1735 * call the OS to commit just one page ...
1737 pagesize = info.dwPageSize << 3;
1738 allocsize = info.dwAllocationGranularity;
1740 /* This scheme fails eventually if request for contiguous
1741 * block is denied so reserve big blocks - this is only
1742 * address space not memory ...
1744 if (brk+need >= reserved)
1746 DWORD size = 64*1024*1024;
1748 if (committed && reserved && committed < reserved)
1750 /* Commit last of previous chunk cannot span allocations */
1751 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
1753 committed = reserved;
1755 /* Reserve some (more) space
1756 * Note this is a little sneaky, 1st call passes NULL as reserved
1757 * so lets system choose where we start, subsequent calls pass
1758 * the old end address so ask for a contiguous block
1760 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
1763 reserved = addr+size;
1778 if (brk > committed)
1780 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
1781 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
1796 win32_malloc(size_t size)
1798 return malloc(size);
1802 win32_calloc(size_t numitems, size_t size)
1804 return calloc(numitems,size);
1808 win32_realloc(void *block, size_t size)
1810 return realloc(block,size);
1814 win32_free(void *block)
1821 win32_open_osfhandle(long handle, int flags)
1823 return _open_osfhandle(handle, flags);
1827 win32_get_osfhandle(int fd)
1829 return _get_osfhandle(fd);
1840 SV *sv = sv_newmortal();
1841 /* Make one call with zero size - return value is required size */
1842 DWORD len = GetCurrentDirectory((DWORD)0,NULL);
1843 SvUPGRADE(sv,SVt_PV);
1845 SvCUR(sv) = GetCurrentDirectory((DWORD) SvLEN(sv), SvPVX(sv));
1848 * then it worked, set PV valid,
1849 * else leave it 'undef'
1863 croak("usage: Win32::SetCurrentDirectory($cwd)");
1864 if (SetCurrentDirectory(SvPV(ST(0),na)))
1871 XS(w32_GetNextAvailDrive)
1875 char root[] = "_:\\";
1878 if (GetDriveType(root) == 1) {
1887 XS(w32_GetLastError)
1890 XSRETURN_IV(GetLastError());
1897 char *name = getlogin_buffer;
1898 DWORD size = sizeof(getlogin_buffer);
1899 if (GetUserName(name,&size)) {
1900 /* size includes NULL */
1901 ST(0) = sv_2mortal(newSVpv(name,size-1));
1911 char name[MAX_COMPUTERNAME_LENGTH+1];
1912 DWORD size = sizeof(name);
1913 if (GetComputerName(name,&size)) {
1914 /* size does NOT include NULL :-( */
1915 ST(0) = sv_2mortal(newSVpv(name,size));
1926 #ifndef HAS_NETWKSTAGETINFO
1927 /* mingw32 (and Win95) don't have NetWksta*(), so do it the old way */
1929 DWORD size = sizeof(name);
1930 if (GetUserName(name,&size)) {
1932 DWORD sidlen = sizeof(sid);
1934 DWORD dnamelen = sizeof(dname);
1936 if (LookupAccountName(NULL, name, &sid, &sidlen,
1937 dname, &dnamelen, &snu)) {
1938 XSRETURN_PV(dname); /* all that for this */
1942 /* this way is more reliable, in case user has a local account.
1943 * XXX need dynamic binding of netapi32.dll symbols or this will fail on
1944 * Win95. Probably makes more sense to move it into libwin32. */
1946 DWORD dnamelen = sizeof(dname);
1947 PWKSTA_INFO_100 pwi;
1948 if (NERR_Success == NetWkstaGetInfo(NULL, 100, (LPBYTE*)&pwi)) {
1949 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
1950 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
1951 -1, (LPSTR)dname, dnamelen, NULL, NULL);
1954 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
1955 -1, (LPSTR)dname, dnamelen, NULL, NULL);
1957 NetApiBufferFree(pwi);
1969 DWORD flags, filecomplen;
1970 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
1971 &flags, fsname, sizeof(fsname))) {
1972 if (GIMME == G_ARRAY) {
1973 XPUSHs(sv_2mortal(newSVpv(fsname,0)));
1974 XPUSHs(sv_2mortal(newSViv(flags)));
1975 XPUSHs(sv_2mortal(newSViv(filecomplen)));
1979 XSRETURN_PV(fsname);
1985 XS(w32_GetOSVersion)
1988 OSVERSIONINFO osver;
1990 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1991 if (GetVersionEx(&osver)) {
1992 XPUSHs(newSVpv(osver.szCSDVersion, 0));
1993 XPUSHs(newSViv(osver.dwMajorVersion));
1994 XPUSHs(newSViv(osver.dwMinorVersion));
1995 XPUSHs(newSViv(osver.dwBuildNumber));
1996 XPUSHs(newSViv(osver.dwPlatformId));
2007 XSRETURN_IV(IsWinNT());
2014 XSRETURN_IV(IsWin95());
2018 XS(w32_FormatMessage)
2025 croak("usage: Win32::FormatMessage($errno)");
2027 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
2028 &source, SvIV(ST(0)), 0,
2029 msgbuf, sizeof(msgbuf)-1, NULL))
2030 XSRETURN_PV(msgbuf);
2040 PROCESS_INFORMATION stProcInfo;
2041 STARTUPINFO stStartInfo;
2042 BOOL bSuccess = FALSE;
2045 croak("usage: Win32::Spawn($cmdName, $args, $PID)");
2047 cmd = SvPV(ST(0),na);
2048 args = SvPV(ST(1), na);
2050 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
2051 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
2052 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
2053 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
2056 cmd, /* Image path */
2057 args, /* Arguments for command line */
2058 NULL, /* Default process security */
2059 NULL, /* Default thread security */
2060 FALSE, /* Must be TRUE to use std handles */
2061 NORMAL_PRIORITY_CLASS, /* No special scheduling */
2062 NULL, /* Inherit our environment block */
2063 NULL, /* Inherit our currrent directory */
2064 &stStartInfo, /* -> Startup info */
2065 &stProcInfo)) /* <- Process info (if OK) */
2067 CloseHandle(stProcInfo.hThread);/* library source code does this. */
2068 sv_setiv(ST(2), stProcInfo.dwProcessId);
2071 XSRETURN_IV(bSuccess);
2075 XS(w32_GetTickCount)
2078 XSRETURN_IV(GetTickCount());
2082 XS(w32_GetShortPathName)
2089 croak("usage: Win32::GetShortPathName($longPathName)");
2091 shortpath = sv_mortalcopy(ST(0));
2092 SvUPGRADE(shortpath, SVt_PV);
2093 /* src == target is allowed */
2095 len = GetShortPathName(SvPVX(shortpath),
2098 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
2100 SvCUR_set(shortpath,len);
2113 croak("usage: Win32::Sleep($milliseconds)");
2119 Perl_init_os_extras()
2121 char *file = __FILE__;
2124 /* these names are Activeware compatible */
2125 newXS("Win32::GetCwd", w32_GetCwd, file);
2126 newXS("Win32::SetCwd", w32_SetCwd, file);
2127 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
2128 newXS("Win32::GetLastError", w32_GetLastError, file);
2129 newXS("Win32::LoginName", w32_LoginName, file);
2130 newXS("Win32::NodeName", w32_NodeName, file);
2131 newXS("Win32::DomainName", w32_DomainName, file);
2132 newXS("Win32::FsType", w32_FsType, file);
2133 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
2134 newXS("Win32::IsWinNT", w32_IsWinNT, file);
2135 newXS("Win32::IsWin95", w32_IsWin95, file);
2136 newXS("Win32::FormatMessage", w32_FormatMessage, file);
2137 newXS("Win32::Spawn", w32_Spawn, file);
2138 newXS("Win32::GetTickCount", w32_GetTickCount, file);
2139 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
2140 newXS("Win32::Sleep", w32_Sleep, file);
2142 /* XXX Bloat Alert! The following Activeware preloads really
2143 * ought to be part of Win32::Sys::*, so they're not included
2146 /* LookupAccountName
2148 * InitiateSystemShutdown
2149 * AbortSystemShutdown
2150 * ExpandEnvrironmentStrings
2155 Perl_win32_init(int *argcp, char ***argvp)
2157 /* Disable floating point errors, Perl will trap the ones we
2158 * care about. VC++ RTL defaults to switching these off
2159 * already, but the Borland RTL doesn't. Since we don't
2160 * want to be at the vendor's whim on the default, we set
2161 * it explicitly here.
2163 #if !defined(_ALPHA_) && !defined(__GNUC__)
2164 _control87(MCW_EM, MCW_EM);
2169 #ifdef USE_BINMODE_SCRIPTS
2172 win32_strip_return(SV *sv)
2174 char *s = SvPVX(sv);
2175 char *e = s+SvCUR(sv);
2179 if (*s == '\r' && s[1] == '\n')
2189 SvCUR_set(sv,d-SvPVX(sv));