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 HANDLE w32_perldll_handle = INVALID_HANDLE_VALUE;
77 static DWORD w32_platform = (DWORD)-1;
80 # ifdef USE_DECLSPEC_THREAD
81 __declspec(thread) char strerror_buffer[512];
82 __declspec(thread) char getlogin_buffer[128];
83 __declspec(thread) char w32_perllib_root[MAX_PATH+1];
84 # ifdef HAVE_DES_FCRYPT
85 __declspec(thread) char crypt_buffer[30];
88 # define strerror_buffer (thr->i.Wstrerror_buffer)
89 # define getlogin_buffer (thr->i.Wgetlogin_buffer)
90 # define w32_perllib_root (thr->i.Ww32_perllib_root)
91 # define crypt_buffer (thr->i.Wcrypt_buffer)
94 static char strerror_buffer[512];
95 static char getlogin_buffer[128];
96 static char w32_perllib_root[MAX_PATH+1];
97 # ifdef HAVE_DES_FCRYPT
98 static char crypt_buffer[30];
104 return (os_id() == VER_PLATFORM_WIN32_WINDOWS);
109 return (os_id() == VER_PLATFORM_WIN32_NT);
113 win32_perllib_path(char *sfx,...)
120 GetModuleFileName((w32_perldll_handle == INVALID_HANDLE_VALUE)
121 ? GetModuleHandle(NULL)
122 : w32_perldll_handle,
124 sizeof(w32_perllib_root));
125 *(end = strrchr(w32_perllib_root, '\\')) = '\0';
126 if (stricmp(end-4,"\\bin") == 0)
133 sfx = va_arg(ap,char *);
136 return (w32_perllib_root);
141 has_redirection(char *ptr)
147 * Scan string looking for redirection (< or >) or pipe
148 * characters (|) that are not in a quoted string
178 /* since the current process environment is being updated in util.c
179 * the library functions will get the correct environment
182 my_popen(char *cmd, char *mode)
185 #define fixcmd(x) { \
186 char *pspace = strchr((x),' '); \
189 while (p < pspace) { \
200 win32_fflush(stdout);
201 win32_fflush(stderr);
202 return win32_popen(cmd, mode);
206 my_pclose(PerlIO *fp)
208 return win32_pclose(fp);
214 static OSVERSIONINFO osver;
216 if (osver.dwPlatformId != w32_platform) {
217 memset(&osver, 0, sizeof(OSVERSIONINFO));
218 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
219 GetVersionEx(&osver);
220 w32_platform = osver.dwPlatformId;
222 return (w32_platform);
225 /* Tokenize a string. Words are null-separated, and the list
226 * ends with a doubled null. Any character (except null and
227 * including backslash) may be escaped by preceding it with a
228 * backslash (the backslash will be stripped).
229 * Returns number of words in result buffer.
232 tokenize(char *str, char **dest, char ***destv)
234 char *retstart = Nullch;
235 char **retvstart = 0;
238 int slen = strlen(str);
240 register char **retv;
241 New(1307, ret, slen+2, char);
242 New(1308, retv, (slen+3)/2, char*);
250 if (*ret == '\\' && *str)
252 else if (*ret == ' ') {
268 retvstart[items] = Nullch;
280 if (!w32_perlshell_tokens) {
281 /* we don't use COMSPEC here for two reasons:
282 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
283 * uncontrolled unportability of the ensuing scripts.
284 * 2. PERL5SHELL could be set to a shell that may not be fit for
285 * interactive use (which is what most programs look in COMSPEC
288 char* defaultshell = (IsWinNT() ? "cmd.exe /x/c" : "command.com /c");
289 char *usershell = getenv("PERL5SHELL");
290 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
291 &w32_perlshell_tokens,
297 do_aspawn(void *vreally, void **vmark, void **vsp)
299 SV *really = (SV*)vreally;
300 SV **mark = (SV**)vmark;
312 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
314 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
319 while (++mark <= sp) {
320 if (*mark && (str = SvPV(*mark, na)))
327 status = win32_spawnvp(flag,
328 (really ? SvPV(really,na) : argv[0]),
329 (const char* const*)argv);
331 if (status < 0 && errno == ENOEXEC) {
332 /* possible shell-builtin, invoke with shell */
334 sh_items = w32_perlshell_items;
336 argv[index+sh_items] = argv[index];
337 while (--sh_items >= 0)
338 argv[sh_items] = w32_perlshell_vec[sh_items];
340 status = win32_spawnvp(flag,
341 (really ? SvPV(really,na) : argv[0]),
342 (const char* const*)argv);
345 if (flag != P_NOWAIT) {
348 warn("Can't spawn \"%s\": %s", argv[0], strerror(errno));
353 statusvalue = status;
360 do_spawn2(char *cmd, int exectype)
366 BOOL needToTry = TRUE;
369 /* Save an extra exec if possible. See if there are shell
370 * metacharacters in it */
371 if (!has_redirection(cmd)) {
372 New(1301,argv, strlen(cmd) / 2 + 2, char*);
373 New(1302,cmd2, strlen(cmd) + 1, char);
376 for (s = cmd2; *s;) {
377 while (*s && isspace(*s))
381 while (*s && !isspace(*s))
390 status = win32_spawnvp(P_WAIT, argv[0],
391 (const char* const*)argv);
393 case EXECF_SPAWN_NOWAIT:
394 status = win32_spawnvp(P_NOWAIT, argv[0],
395 (const char* const*)argv);
398 status = win32_execvp(argv[0], (const char* const*)argv);
401 if (status != -1 || errno == 0)
411 New(1306, argv, w32_perlshell_items + 2, char*);
412 while (++i < w32_perlshell_items)
413 argv[i] = w32_perlshell_vec[i];
418 status = win32_spawnvp(P_WAIT, argv[0],
419 (const char* const*)argv);
421 case EXECF_SPAWN_NOWAIT:
422 status = win32_spawnvp(P_NOWAIT, argv[0],
423 (const char* const*)argv);
426 status = win32_execvp(argv[0], (const char* const*)argv);
432 if (exectype != EXECF_SPAWN_NOWAIT) {
435 warn("Can't %s \"%s\": %s",
436 (exectype == EXECF_EXEC ? "exec" : "spawn"),
437 cmd, strerror(errno));
442 statusvalue = status;
450 return do_spawn2(cmd, EXECF_SPAWN);
454 do_spawn_nowait(char *cmd)
456 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
462 do_spawn2(cmd, EXECF_EXEC);
466 /* The idea here is to read all the directory names into a string table
467 * (separated by nulls) and when one of the other dir functions is called
468 * return the pointer to the current file name.
471 opendir(char *filename)
476 char scanname[MAX_PATH+3];
478 WIN32_FIND_DATA FindData;
481 len = strlen(filename);
485 /* check to see if filename is a directory */
486 if (win32_stat(filename, &sbuf) < 0 || (sbuf.st_mode & S_IFDIR) == 0) {
487 /* CRT is buggy on sharenames, so make sure it really isn't */
488 DWORD r = GetFileAttributes(filename);
489 if (r == 0xffffffff || !(r & FILE_ATTRIBUTE_DIRECTORY))
493 /* Get us a DIR structure */
494 Newz(1303, p, 1, DIR);
498 /* Create the search pattern */
499 strcpy(scanname, filename);
500 if (scanname[len-1] != '/' && scanname[len-1] != '\\')
501 scanname[len++] = '/';
502 scanname[len++] = '*';
503 scanname[len] = '\0';
505 /* do the FindFirstFile call */
506 fh = FindFirstFile(scanname, &FindData);
507 if (fh == INVALID_HANDLE_VALUE) {
511 /* now allocate the first part of the string table for
512 * the filenames that we find.
514 idx = strlen(FindData.cFileName)+1;
515 New(1304, p->start, idx, char);
516 if (p->start == NULL)
517 croak("opendir: malloc failed!\n");
518 strcpy(p->start, FindData.cFileName);
521 /* loop finding all the files that match the wildcard
522 * (which should be all of them in this directory!).
523 * the variable idx should point one past the null terminator
524 * of the previous string found.
526 while (FindNextFile(fh, &FindData)) {
527 len = strlen(FindData.cFileName);
528 /* bump the string table size by enough for the
529 * new name and it's null terminator
531 Renew(p->start, idx+len+1, char);
532 if (p->start == NULL)
533 croak("opendir: malloc failed!\n");
534 strcpy(&p->start[idx], FindData.cFileName);
545 /* Readdir just returns the current string pointer and bumps the
546 * string pointer to the nDllExport entry.
552 static int dummy = 0;
555 /* first set up the structure to return */
556 len = strlen(dirp->curr);
557 strcpy(dirp->dirstr.d_name, dirp->curr);
558 dirp->dirstr.d_namlen = len;
561 dirp->dirstr.d_ino = dummy++;
563 /* Now set up for the nDllExport call to readdir */
564 dirp->curr += len + 1;
565 if (dirp->curr >= (dirp->start + dirp->size)) {
569 return &(dirp->dirstr);
575 /* Telldir returns the current string pointer position */
579 return (long) dirp->curr;
583 /* Seekdir moves the string pointer to a previously saved position
587 seekdir(DIR *dirp, long loc)
589 dirp->curr = (char *)loc;
592 /* Rewinddir resets the string pointer to the start */
596 dirp->curr = dirp->start;
599 /* free the memory allocated by opendir */
603 Safefree(dirp->start);
616 * Just pretend that everyone is a superuser. NT will let us know if
617 * we don\'t really have permission to do something.
620 #define ROOT_UID ((uid_t)0)
621 #define ROOT_GID ((gid_t)0)
650 return (auid == ROOT_UID ? 0 : -1);
656 return (agid == ROOT_GID ? 0 : -1);
663 char *buf = getlogin_buffer;
664 DWORD size = sizeof(getlogin_buffer);
665 if (GetUserName(buf,&size))
671 chown(const char *path, uid_t owner, gid_t group)
678 kill(int pid, int sig)
680 HANDLE hProcess= OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
682 if (hProcess == NULL) {
683 croak("kill process failed!\n");
686 if (!TerminateProcess(hProcess, sig))
687 croak("kill process failed!\n");
688 CloseHandle(hProcess);
697 DllExport unsigned int
698 win32_sleep(unsigned int t)
705 win32_stat(const char *path, struct stat *buffer)
708 const char *p = path;
709 int l = strlen(path);
713 switch(path[l - 1]) {
716 if (path[l - 2] != ':') {
717 strncpy(t, path, l - 1);
723 res = stat(p,buffer);
726 if (S_ISDIR(buffer->st_mode))
727 buffer->st_mode |= S_IWRITE | S_IEXEC;
728 else if (S_ISREG(buffer->st_mode)) {
729 if (l >= 4 && path[l-4] == '.') {
730 const char *e = path + l - 3;
731 if (strnicmp(e,"exe",3)
732 && strnicmp(e,"bat",3)
733 && strnicmp(e,"com",3)
734 && (IsWin95() || strnicmp(e,"cmd",3)))
735 buffer->st_mode &= ~S_IEXEC;
737 buffer->st_mode |= S_IEXEC;
740 buffer->st_mode &= ~S_IEXEC;
747 #ifndef USE_WIN32_RTL_ENV
750 win32_getenv(const char *name)
752 static char *curitem = Nullch;
753 static DWORD curlen = 512;
756 New(1305,curitem,curlen,char);
757 if (!(needlen = GetEnvironmentVariable(name,curitem,curlen)))
759 while (needlen > curlen) {
760 Renew(curitem,needlen,char);
762 needlen = GetEnvironmentVariable(name,curitem,curlen);
770 filetime_to_clock(PFILETIME ft)
772 __int64 qw = ft->dwHighDateTime;
774 qw |= ft->dwLowDateTime;
775 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
780 win32_times(struct tms *timebuf)
785 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
787 timebuf->tms_utime = filetime_to_clock(&user);
788 timebuf->tms_stime = filetime_to_clock(&kernel);
789 timebuf->tms_cutime = 0;
790 timebuf->tms_cstime = 0;
793 /* That failed - e.g. Win95 fallback to clock() */
795 timebuf->tms_utime = t;
796 timebuf->tms_stime = 0;
797 timebuf->tms_cutime = 0;
798 timebuf->tms_cstime = 0;
803 /* fix utime() so it works on directories in NT
804 * thanks to Jan Dubois <jan.dubois@ibm.net>
807 filetime_from_time(PFILETIME pFileTime, time_t Time)
809 struct tm *pTM = gmtime(&Time);
810 SYSTEMTIME SystemTime;
815 SystemTime.wYear = pTM->tm_year + 1900;
816 SystemTime.wMonth = pTM->tm_mon + 1;
817 SystemTime.wDay = pTM->tm_mday;
818 SystemTime.wHour = pTM->tm_hour;
819 SystemTime.wMinute = pTM->tm_min;
820 SystemTime.wSecond = pTM->tm_sec;
821 SystemTime.wMilliseconds = 0;
823 return SystemTimeToFileTime(&SystemTime, pFileTime);
827 win32_utime(const char *filename, struct utimbuf *times)
833 struct utimbuf TimeBuffer;
835 int rc = utime(filename,times);
836 /* EACCES: path specifies directory or readonly file */
837 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
842 time(×->actime);
843 times->modtime = times->actime;
846 /* This will (and should) still fail on readonly files */
847 handle = CreateFile(filename, GENERIC_READ | GENERIC_WRITE,
848 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
849 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
850 if (handle == INVALID_HANDLE_VALUE)
853 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
854 filetime_from_time(&ftAccess, times->actime) &&
855 filetime_from_time(&ftWrite, times->modtime) &&
856 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
866 win32_wait(int *status)
871 /* XXX this wait emulation only knows about processes
872 * spawned via win32_spawnvp(P_NOWAIT, ...).
875 DWORD exitcode, waitcode;
877 if (!w32_num_children) {
882 /* if a child exists, wait for it to die */
883 waitcode = WaitForMultipleObjects(w32_num_children,
887 if (waitcode != WAIT_FAILED) {
888 if (waitcode >= WAIT_ABANDONED_0
889 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
890 i = waitcode - WAIT_ABANDONED_0;
892 i = waitcode - WAIT_OBJECT_0;
893 if (GetExitCodeProcess(w32_child_pids[i], &exitcode) ) {
894 CloseHandle(w32_child_pids[i]);
895 *status = (int)((exitcode & 0xff) << 8);
896 retval = (int)w32_child_pids[i];
897 Copy(&w32_child_pids[i+1], &w32_child_pids[i],
898 (w32_num_children-i-1), HANDLE);
905 errno = GetLastError();
911 static UINT timerid = 0;
913 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
915 KillTimer(NULL,timerid);
920 DllExport unsigned int
921 win32_alarm(unsigned int sec)
924 * the 'obvious' implentation is SetTimer() with a callback
925 * which does whatever receiving SIGALRM would do
926 * we cannot use SIGALRM even via raise() as it is not
927 * one of the supported codes in <signal.h>
929 * Snag is unless something is looking at the message queue
930 * nothing happens :-(
934 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
936 croak("Cannot set timer");
942 KillTimer(NULL,timerid);
949 #ifdef HAVE_DES_FCRYPT
950 extern char * des_fcrypt(char *cbuf, const char *txt, const char *salt);
953 win32_crypt(const char *txt, const char *salt)
956 return des_fcrypt(crypt_buffer, txt, salt);
960 #ifdef USE_FIXED_OSFHANDLE
962 EXTERN_C int __cdecl _alloc_osfhnd(void);
963 EXTERN_C int __cdecl _set_osfhnd(int fh, long value);
964 EXTERN_C void __cdecl _lock_fhandle(int);
965 EXTERN_C void __cdecl _unlock_fhandle(int);
966 EXTERN_C void __cdecl _unlock(int);
968 #if (_MSC_VER >= 1000)
970 long osfhnd; /* underlying OS file HANDLE */
971 char osfile; /* attributes of file (e.g., open in text mode?) */
972 char pipech; /* one char buffer for handles opened on pipes */
973 #if defined (_MT) && !defined (DLL_FOR_WIN32S)
975 CRITICAL_SECTION lock;
976 #endif /* defined (_MT) && !defined (DLL_FOR_WIN32S) */
979 EXTERN_C ioinfo * __pioinfo[];
982 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
983 #define _pioinfo(i) (__pioinfo[i >> IOINFO_L2E] + (i & (IOINFO_ARRAY_ELTS - 1)))
984 #define _osfile(i) (_pioinfo(i)->osfile)
986 #else /* (_MSC_VER >= 1000) */
987 extern char _osfile[];
988 #endif /* (_MSC_VER >= 1000) */
990 #define FOPEN 0x01 /* file handle open */
991 #define FAPPEND 0x20 /* file handle opened O_APPEND */
992 #define FDEV 0x40 /* file handle refers to device */
993 #define FTEXT 0x80 /* file handle is in text mode */
995 #define _STREAM_LOCKS 26 /* Table of stream locks */
996 #define _LAST_STREAM_LOCK (_STREAM_LOCKS+_NSTREAM_-1) /* Last stream lock */
997 #define _FH_LOCKS (_LAST_STREAM_LOCK+1) /* Table of fh locks */
1000 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1003 * This function allocates a free C Runtime file handle and associates
1004 * it with the Win32 HANDLE specified by the first parameter. This is a
1005 * temperary fix for WIN95's brain damage GetFileType() error on socket
1006 * we just bypass that call for socket
1009 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1010 * int flags - flags to associate with C Runtime file handle.
1013 * returns index of entry in fh, if successful
1014 * return -1, if no free entry is found
1018 *******************************************************************************/
1021 my_open_osfhandle(long osfhandle, int flags)
1024 char fileflags; /* _osfile flags */
1026 /* copy relevant flags from second parameter */
1029 if (flags & O_APPEND)
1030 fileflags |= FAPPEND;
1035 /* attempt to allocate a C Runtime file handle */
1036 if ((fh = _alloc_osfhnd()) == -1) {
1037 errno = EMFILE; /* too many open files */
1038 _doserrno = 0L; /* not an OS error */
1039 return -1; /* return error to caller */
1042 /* the file is open. now, set the info in _osfhnd array */
1043 _set_osfhnd(fh, osfhandle);
1045 fileflags |= FOPEN; /* mark as open */
1047 #if (_MSC_VER >= 1000)
1048 _osfile(fh) = fileflags; /* set osfile entry */
1049 _unlock_fhandle(fh);
1051 _osfile[fh] = fileflags; /* set osfile entry */
1052 _unlock(fh+_FH_LOCKS); /* unlock handle */
1055 return fh; /* return handle */
1058 #define _open_osfhandle my_open_osfhandle
1059 #endif /* USE_FIXED_OSFHANDLE */
1061 /* simulate flock by locking a range on the file */
1063 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1064 #define LK_LEN 0xffff0000
1067 win32_flock(int fd, int oper)
1074 croak("flock() unimplemented on this platform");
1077 fh = (HANDLE)_get_osfhandle(fd);
1078 memset(&o, 0, sizeof(o));
1081 case LOCK_SH: /* shared lock */
1082 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1084 case LOCK_EX: /* exclusive lock */
1085 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1087 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1088 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1090 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1091 LK_ERR(LockFileEx(fh,
1092 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1093 0, LK_LEN, 0, &o),i);
1095 case LOCK_UN: /* unlock lock */
1096 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1098 default: /* unknown */
1109 * redirected io subsystem for all XS modules
1122 return (&(_environ));
1125 /* the rest are the remapped stdio routines */
1145 win32_ferror(FILE *fp)
1147 return (ferror(fp));
1152 win32_feof(FILE *fp)
1158 * Since the errors returned by the socket error function
1159 * WSAGetLastError() are not known by the library routine strerror
1160 * we have to roll our own.
1164 win32_strerror(int e)
1166 #ifndef __BORLANDC__ /* Borland intolerance */
1167 extern int sys_nerr;
1171 if (e < 0 || e > sys_nerr) {
1176 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
1177 strerror_buffer, sizeof(strerror_buffer), NULL) == 0)
1178 strcpy(strerror_buffer, "Unknown Error");
1180 return strerror_buffer;
1186 win32_str_os_error(void *sv, DWORD dwErr)
1190 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
1191 |FORMAT_MESSAGE_IGNORE_INSERTS
1192 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
1193 dwErr, 0, (char *)&sMsg, 1, NULL);
1195 while (0 < dwLen && isspace(sMsg[--dwLen]))
1197 if ('.' != sMsg[dwLen])
1202 sMsg = LocalAlloc(0, 64/**sizeof(TCHAR)*/);
1203 dwLen = sprintf(sMsg,
1204 "Unknown error #0x%lX (lookup 0x%lX)",
1205 dwErr, GetLastError());
1207 sv_setpvn((SV*)sv, sMsg, dwLen);
1213 win32_fprintf(FILE *fp, const char *format, ...)
1216 va_start(marker, format); /* Initialize variable arguments. */
1218 return (vfprintf(fp, format, marker));
1222 win32_printf(const char *format, ...)
1225 va_start(marker, format); /* Initialize variable arguments. */
1227 return (vprintf(format, marker));
1231 win32_vfprintf(FILE *fp, const char *format, va_list args)
1233 return (vfprintf(fp, format, args));
1237 win32_vprintf(const char *format, va_list args)
1239 return (vprintf(format, args));
1243 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
1245 return fread(buf, size, count, fp);
1249 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
1251 return fwrite(buf, size, count, fp);
1255 win32_fopen(const char *filename, const char *mode)
1257 if (stricmp(filename, "/dev/null")==0)
1258 return fopen("NUL", mode);
1259 return fopen(filename, mode);
1262 #ifndef USE_SOCKETS_AS_HANDLES
1264 #define fdopen my_fdopen
1268 win32_fdopen( int handle, const char *mode)
1270 return fdopen(handle, (char *) mode);
1274 win32_freopen( const char *path, const char *mode, FILE *stream)
1276 if (stricmp(path, "/dev/null")==0)
1277 return freopen("NUL", mode, stream);
1278 return freopen(path, mode, stream);
1282 win32_fclose(FILE *pf)
1284 return my_fclose(pf); /* defined in win32sck.c */
1288 win32_fputs(const char *s,FILE *pf)
1290 return fputs(s, pf);
1294 win32_fputc(int c,FILE *pf)
1300 win32_ungetc(int c,FILE *pf)
1302 return ungetc(c,pf);
1306 win32_getc(FILE *pf)
1312 win32_fileno(FILE *pf)
1318 win32_clearerr(FILE *pf)
1325 win32_fflush(FILE *pf)
1331 win32_ftell(FILE *pf)
1337 win32_fseek(FILE *pf,long offset,int origin)
1339 return fseek(pf, offset, origin);
1343 win32_fgetpos(FILE *pf,fpos_t *p)
1345 return fgetpos(pf, p);
1349 win32_fsetpos(FILE *pf,const fpos_t *p)
1351 return fsetpos(pf, p);
1355 win32_rewind(FILE *pf)
1375 win32_fstat(int fd,struct stat *sbufptr)
1377 return fstat(fd,sbufptr);
1381 win32_pipe(int *pfd, unsigned int size, int mode)
1383 return _pipe(pfd, size, mode);
1387 * a popen() clone that respects PERL5SHELL
1391 win32_popen(const char *command, const char *mode)
1393 #ifdef USE_RTL_POPEN
1394 return _popen(command, mode);
1402 /* establish which ends read and write */
1403 if (strchr(mode,'w')) {
1404 stdfd = 0; /* stdin */
1408 else if (strchr(mode,'r')) {
1409 stdfd = 1; /* stdout */
1416 /* set the correct mode */
1417 if (strchr(mode,'b'))
1419 else if (strchr(mode,'t'))
1422 ourmode = _fmode & (O_TEXT | O_BINARY);
1424 /* the child doesn't inherit handles */
1425 ourmode |= O_NOINHERIT;
1427 if (win32_pipe( p, 512, ourmode) == -1)
1430 /* save current stdfd */
1431 if ((oldfd = win32_dup(stdfd)) == -1)
1434 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
1435 /* stdfd will be inherited by the child */
1436 if (win32_dup2(p[child], stdfd) == -1)
1439 /* close the child end in parent */
1440 win32_close(p[child]);
1442 /* start the child */
1443 if ((childpid = do_spawn_nowait((char*)command)) == -1)
1446 /* revert stdfd to whatever it was before */
1447 if (win32_dup2(oldfd, stdfd) == -1)
1450 /* close saved handle */
1453 sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
1455 /* we have an fd, return a file stream */
1456 return (win32_fdopen(p[parent], (char *)mode));
1459 /* we don't need to check for errors here */
1463 win32_dup2(oldfd, stdfd);
1468 #endif /* USE_RTL_POPEN */
1476 win32_pclose(FILE *pf)
1478 #ifdef USE_RTL_POPEN
1482 #ifndef USE_RTL_WAIT
1486 int childpid, status;
1489 sv = *av_fetch(w32_fdpid, win32_fileno(pf), TRUE);
1491 childpid = SvIVX(sv);
1503 #ifndef USE_RTL_WAIT
1504 for (child = 0 ; child < w32_num_children ; ++child) {
1505 if (w32_child_pids[child] == (HANDLE)childpid) {
1506 Copy(&w32_child_pids[child+1], &w32_child_pids[child],
1507 (w32_num_children-child-1), HANDLE);
1514 /* wait for the child */
1515 if (cwait(&status, childpid, WAIT_CHILD) == -1)
1517 /* cwait() returns differently on Borland */
1519 return (((status >> 8) & 0xff) | ((status << 8) & 0xff00));
1524 #endif /* USE_RTL_POPEN */
1528 win32_setmode(int fd, int mode)
1530 return setmode(fd, mode);
1534 win32_lseek(int fd, long offset, int origin)
1536 return lseek(fd, offset, origin);
1546 win32_open(const char *path, int flag, ...)
1552 pmode = va_arg(ap, int);
1555 if (stricmp(path, "/dev/null")==0)
1556 return open("NUL", flag, pmode);
1557 return open(path,flag,pmode);
1579 win32_dup2(int fd1,int fd2)
1581 return dup2(fd1,fd2);
1585 win32_read(int fd, void *buf, unsigned int cnt)
1587 return read(fd, buf, cnt);
1591 win32_write(int fd, const void *buf, unsigned int cnt)
1593 return write(fd, buf, cnt);
1597 win32_mkdir(const char *dir, int mode)
1599 return mkdir(dir); /* just ignore mode */
1603 win32_rmdir(const char *dir)
1609 win32_chdir(const char *dir)
1615 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
1619 #ifndef USE_RTL_WAIT
1620 if (mode == P_NOWAIT && w32_num_children >= MAXIMUM_WAIT_OBJECTS)
1624 status = spawnvp(mode, cmdname, (char * const *) argv);
1625 #ifndef USE_RTL_WAIT
1626 /* XXX For the P_NOWAIT case, Borland RTL returns pinfo.dwProcessId
1627 * while VC RTL returns pinfo.hProcess. For purposes of the custom
1628 * implementation of win32_wait(), we assume the latter.
1630 if (mode == P_NOWAIT && status >= 0)
1631 w32_child_pids[w32_num_children++] = (HANDLE)status;
1637 win32_execvp(const char *cmdname, const char *const *argv)
1639 return execvp(cmdname, (char *const *)argv);
1643 win32_perror(const char *str)
1649 win32_setbuf(FILE *pf, char *buf)
1655 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
1657 return setvbuf(pf, buf, type, size);
1661 win32_flushall(void)
1667 win32_fcloseall(void)
1673 win32_fgets(char *s, int n, FILE *pf)
1675 return fgets(s, n, pf);
1685 win32_fgetc(FILE *pf)
1691 win32_putc(int c, FILE *pf)
1697 win32_puts(const char *s)
1709 win32_putchar(int c)
1716 #ifndef USE_PERL_SBRK
1718 static char *committed = NULL;
1719 static char *base = NULL;
1720 static char *reserved = NULL;
1721 static char *brk = NULL;
1722 static DWORD pagesize = 0;
1723 static DWORD allocsize = 0;
1731 GetSystemInfo(&info);
1732 /* Pretend page size is larger so we don't perpetually
1733 * call the OS to commit just one page ...
1735 pagesize = info.dwPageSize << 3;
1736 allocsize = info.dwAllocationGranularity;
1738 /* This scheme fails eventually if request for contiguous
1739 * block is denied so reserve big blocks - this is only
1740 * address space not memory ...
1742 if (brk+need >= reserved)
1744 DWORD size = 64*1024*1024;
1746 if (committed && reserved && committed < reserved)
1748 /* Commit last of previous chunk cannot span allocations */
1749 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
1751 committed = reserved;
1753 /* Reserve some (more) space
1754 * Note this is a little sneaky, 1st call passes NULL as reserved
1755 * so lets system choose where we start, subsequent calls pass
1756 * the old end address so ask for a contiguous block
1758 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
1761 reserved = addr+size;
1776 if (brk > committed)
1778 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
1779 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
1794 win32_malloc(size_t size)
1796 return malloc(size);
1800 win32_calloc(size_t numitems, size_t size)
1802 return calloc(numitems,size);
1806 win32_realloc(void *block, size_t size)
1808 return realloc(block,size);
1812 win32_free(void *block)
1819 win32_open_osfhandle(long handle, int flags)
1821 return _open_osfhandle(handle, flags);
1825 win32_get_osfhandle(int fd)
1827 return _get_osfhandle(fd);
1838 SV *sv = sv_newmortal();
1839 /* Make one call with zero size - return value is required size */
1840 DWORD len = GetCurrentDirectory((DWORD)0,NULL);
1841 SvUPGRADE(sv,SVt_PV);
1843 SvCUR(sv) = GetCurrentDirectory((DWORD) SvLEN(sv), SvPVX(sv));
1846 * then it worked, set PV valid,
1847 * else leave it 'undef'
1861 croak("usage: Win32::SetCurrentDirectory($cwd)");
1862 if (SetCurrentDirectory(SvPV(ST(0),na)))
1869 XS(w32_GetNextAvailDrive)
1873 char root[] = "_:\\";
1876 if (GetDriveType(root) == 1) {
1885 XS(w32_GetLastError)
1888 XSRETURN_IV(GetLastError());
1895 char *name = getlogin_buffer;
1896 DWORD size = sizeof(getlogin_buffer);
1897 if (GetUserName(name,&size)) {
1898 /* size includes NULL */
1899 ST(0) = sv_2mortal(newSVpv(name,size-1));
1909 char name[MAX_COMPUTERNAME_LENGTH+1];
1910 DWORD size = sizeof(name);
1911 if (GetComputerName(name,&size)) {
1912 /* size does NOT include NULL :-( */
1913 ST(0) = sv_2mortal(newSVpv(name,size));
1924 #ifndef HAS_NETWKSTAGETINFO
1925 /* mingw32 (and Win95) don't have NetWksta*(), so do it the old way */
1927 DWORD size = sizeof(name);
1928 if (GetUserName(name,&size)) {
1930 DWORD sidlen = sizeof(sid);
1932 DWORD dnamelen = sizeof(dname);
1934 if (LookupAccountName(NULL, name, &sid, &sidlen,
1935 dname, &dnamelen, &snu)) {
1936 XSRETURN_PV(dname); /* all that for this */
1940 /* this way is more reliable, in case user has a local account.
1941 * XXX need dynamic binding of netapi32.dll symbols or this will fail on
1942 * Win95. Probably makes more sense to move it into libwin32. */
1944 DWORD dnamelen = sizeof(dname);
1945 PWKSTA_INFO_100 pwi;
1946 if (NERR_Success == NetWkstaGetInfo(NULL, 100, (LPBYTE*)&pwi)) {
1947 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
1948 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
1949 -1, (LPSTR)dname, dnamelen, NULL, NULL);
1952 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
1953 -1, (LPSTR)dname, dnamelen, NULL, NULL);
1955 NetApiBufferFree(pwi);
1967 DWORD flags, filecomplen;
1968 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
1969 &flags, fsname, sizeof(fsname))) {
1970 if (GIMME == G_ARRAY) {
1971 XPUSHs(sv_2mortal(newSVpv(fsname,0)));
1972 XPUSHs(sv_2mortal(newSViv(flags)));
1973 XPUSHs(sv_2mortal(newSViv(filecomplen)));
1977 XSRETURN_PV(fsname);
1983 XS(w32_GetOSVersion)
1986 OSVERSIONINFO osver;
1988 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1989 if (GetVersionEx(&osver)) {
1990 XPUSHs(newSVpv(osver.szCSDVersion, 0));
1991 XPUSHs(newSViv(osver.dwMajorVersion));
1992 XPUSHs(newSViv(osver.dwMinorVersion));
1993 XPUSHs(newSViv(osver.dwBuildNumber));
1994 XPUSHs(newSViv(osver.dwPlatformId));
2005 XSRETURN_IV(IsWinNT());
2012 XSRETURN_IV(IsWin95());
2016 XS(w32_FormatMessage)
2023 croak("usage: Win32::FormatMessage($errno)");
2025 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
2026 &source, SvIV(ST(0)), 0,
2027 msgbuf, sizeof(msgbuf)-1, NULL))
2028 XSRETURN_PV(msgbuf);
2038 PROCESS_INFORMATION stProcInfo;
2039 STARTUPINFO stStartInfo;
2040 BOOL bSuccess = FALSE;
2043 croak("usage: Win32::Spawn($cmdName, $args, $PID)");
2045 cmd = SvPV(ST(0),na);
2046 args = SvPV(ST(1), na);
2048 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
2049 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
2050 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
2051 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
2054 cmd, /* Image path */
2055 args, /* Arguments for command line */
2056 NULL, /* Default process security */
2057 NULL, /* Default thread security */
2058 FALSE, /* Must be TRUE to use std handles */
2059 NORMAL_PRIORITY_CLASS, /* No special scheduling */
2060 NULL, /* Inherit our environment block */
2061 NULL, /* Inherit our currrent directory */
2062 &stStartInfo, /* -> Startup info */
2063 &stProcInfo)) /* <- Process info (if OK) */
2065 CloseHandle(stProcInfo.hThread);/* library source code does this. */
2066 sv_setiv(ST(2), stProcInfo.dwProcessId);
2069 XSRETURN_IV(bSuccess);
2073 XS(w32_GetTickCount)
2076 XSRETURN_IV(GetTickCount());
2080 XS(w32_GetShortPathName)
2087 croak("usage: Win32::GetShortPathName($longPathName)");
2089 shortpath = sv_mortalcopy(ST(0));
2090 SvUPGRADE(shortpath, SVt_PV);
2091 /* src == target is allowed */
2093 len = GetShortPathName(SvPVX(shortpath),
2096 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
2098 SvCUR_set(shortpath,len);
2111 croak("usage: Win32::Sleep($milliseconds)");
2117 Perl_init_os_extras()
2119 char *file = __FILE__;
2122 w32_perlshell_tokens = Nullch;
2123 w32_perlshell_items = -1;
2124 w32_fdpid = newAV(); /* XXX needs to be in Perl_win32_init()? */
2125 #ifndef USE_RTL_WAIT
2126 w32_num_children = 0;
2129 /* these names are Activeware compatible */
2130 newXS("Win32::GetCwd", w32_GetCwd, file);
2131 newXS("Win32::SetCwd", w32_SetCwd, file);
2132 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
2133 newXS("Win32::GetLastError", w32_GetLastError, file);
2134 newXS("Win32::LoginName", w32_LoginName, file);
2135 newXS("Win32::NodeName", w32_NodeName, file);
2136 newXS("Win32::DomainName", w32_DomainName, file);
2137 newXS("Win32::FsType", w32_FsType, file);
2138 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
2139 newXS("Win32::IsWinNT", w32_IsWinNT, file);
2140 newXS("Win32::IsWin95", w32_IsWin95, file);
2141 newXS("Win32::FormatMessage", w32_FormatMessage, file);
2142 newXS("Win32::Spawn", w32_Spawn, file);
2143 newXS("Win32::GetTickCount", w32_GetTickCount, file);
2144 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
2145 newXS("Win32::Sleep", w32_Sleep, file);
2147 /* XXX Bloat Alert! The following Activeware preloads really
2148 * ought to be part of Win32::Sys::*, so they're not included
2151 /* LookupAccountName
2153 * InitiateSystemShutdown
2154 * AbortSystemShutdown
2155 * ExpandEnvrironmentStrings
2160 Perl_win32_init(int *argcp, char ***argvp)
2162 /* Disable floating point errors, Perl will trap the ones we
2163 * care about. VC++ RTL defaults to switching these off
2164 * already, but the Borland RTL doesn't. Since we don't
2165 * want to be at the vendor's whim on the default, we set
2166 * it explicitly here.
2168 #if !defined(_ALPHA_) && !defined(__GNUC__)
2169 _control87(MCW_EM, MCW_EM);
2174 #ifdef USE_BINMODE_SCRIPTS
2177 win32_strip_return(SV *sv)
2179 char *s = SvPVX(sv);
2180 char *e = s+SvCUR(sv);
2184 if (*s == '\r' && s[1] == '\n')
2194 SvCUR_set(sv,d-SvPVX(sv));