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
19 /* #include "config.h" */
21 #define PERLIO_NOT_STDIO 0
22 #if !defined(PERLIO_IS_STDIO) && !defined(USE_SFIO)
32 /* assert.h conflicts with #define of assert in perl.h */
39 #if defined(_MSC_VER) || defined(__MINGW32__)
40 #include <sys/utime.h>
46 /* Mingw32 defaults to globing command line
47 * So we turn it off like this:
54 #define EXECF_SPAWN_NOWAIT 3
56 static DWORD os_id(void);
57 static void get_shell(void);
58 static long tokenize(char *str, char **dest, char ***destv);
59 static int do_spawn2(char *cmd, int exectype);
60 static BOOL has_redirection(char *ptr);
61 static long filetime_to_clock(PFILETIME ft);
62 static BOOL filetime_from_time(PFILETIME ft, time_t t);
64 char * w32_perlshell_tokens = Nullch;
65 char ** w32_perlshell_vec;
66 long w32_perlshell_items = -1;
67 DWORD w32_platform = (DWORD)-1;
68 char w32_perllib_root[MAX_PATH+1];
69 HANDLE w32_perldll_handle = INVALID_HANDLE_VALUE;
71 long w32_num_children = 0;
72 HANDLE w32_child_pids[MAXIMUM_WAIT_OBJECTS];
77 # define FOPEN_MAX _NSTREAM_
79 # define FOPEN_MAX _NFILE_
81 # define FOPEN_MAX _NFILE
86 int w32_popen_pids[FOPEN_MAX];
90 # ifdef USE_DECLSPEC_THREAD
91 __declspec(thread) char strerror_buffer[512];
92 __declspec(thread) char getlogin_buffer[128];
93 # ifdef HAVE_DES_FCRYPT
94 __declspec(thread) char crypt_buffer[30];
97 # define strerror_buffer (thr->i.Wstrerror_buffer)
98 # define getlogin_buffer (thr->i.Wgetlogin_buffer)
99 # define crypt_buffer (thr->i.Wcrypt_buffer)
102 char strerror_buffer[512];
103 char getlogin_buffer[128];
104 # ifdef HAVE_DES_FCRYPT
105 char crypt_buffer[30];
111 return (os_id() == VER_PLATFORM_WIN32_WINDOWS);
116 return (os_id() == VER_PLATFORM_WIN32_NT);
120 win32_perllib_path(char *sfx,...)
125 GetModuleFileName((w32_perldll_handle == INVALID_HANDLE_VALUE)
126 ? GetModuleHandle(NULL)
127 : w32_perldll_handle,
129 sizeof(w32_perllib_root));
130 *(end = strrchr(w32_perllib_root, '\\')) = '\0';
131 if (stricmp(end-4,"\\bin") == 0)
138 sfx = va_arg(ap,char *);
141 return (w32_perllib_root);
146 has_redirection(char *ptr)
152 * Scan string looking for redirection (< or >) or pipe
153 * characters (|) that are not in a quoted string
183 /* since the current process environment is being updated in util.c
184 * the library functions will get the correct environment
187 my_popen(char *cmd, char *mode)
190 #define fixcmd(x) { \
191 char *pspace = strchr((x),' '); \
194 while (p < pspace) { \
205 win32_fflush(stdout);
206 win32_fflush(stderr);
207 return win32_popen(cmd, mode);
211 my_pclose(PerlIO *fp)
213 return win32_pclose(fp);
219 static OSVERSIONINFO osver;
221 if (osver.dwPlatformId != w32_platform) {
222 memset(&osver, 0, sizeof(OSVERSIONINFO));
223 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
224 GetVersionEx(&osver);
225 w32_platform = osver.dwPlatformId;
227 return (w32_platform);
230 /* Tokenize a string. Words are null-separated, and the list
231 * ends with a doubled null. Any character (except null and
232 * including backslash) may be escaped by preceding it with a
233 * backslash (the backslash will be stripped).
234 * Returns number of words in result buffer.
237 tokenize(char *str, char **dest, char ***destv)
239 char *retstart = Nullch;
240 char **retvstart = 0;
243 int slen = strlen(str);
245 register char **retv;
246 New(1307, ret, slen+2, char);
247 New(1308, retv, (slen+3)/2, char*);
255 if (*ret == '\\' && *str)
257 else if (*ret == ' ') {
273 retvstart[items] = Nullch;
285 if (!w32_perlshell_tokens) {
286 /* we don't use COMSPEC here for two reasons:
287 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
288 * uncontrolled unportability of the ensuing scripts.
289 * 2. PERL5SHELL could be set to a shell that may not be fit for
290 * interactive use (which is what most programs look in COMSPEC
293 char* defaultshell = (IsWinNT() ? "cmd.exe /x/c" : "command.com /c");
294 char *usershell = getenv("PERL5SHELL");
295 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
296 &w32_perlshell_tokens,
302 do_aspawn(void *vreally, void **vmark, void **vsp)
304 SV *really = (SV*)vreally;
305 SV **mark = (SV**)vmark;
317 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
319 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
324 while(++mark <= sp) {
325 if (*mark && (str = SvPV(*mark, na)))
332 status = win32_spawnvp(flag,
333 (really ? SvPV(really,na) : argv[0]),
334 (const char* const*)argv);
336 if (status < 0 && errno == ENOEXEC) {
337 /* possible shell-builtin, invoke with shell */
339 sh_items = w32_perlshell_items;
341 argv[index+sh_items] = argv[index];
342 while (--sh_items >= 0)
343 argv[sh_items] = w32_perlshell_vec[sh_items];
345 status = win32_spawnvp(flag,
346 (really ? SvPV(really,na) : argv[0]),
347 (const char* const*)argv);
350 if (flag != P_NOWAIT) {
353 warn("Can't spawn \"%s\": %s", argv[0], strerror(errno));
358 statusvalue = status;
365 do_spawn2(char *cmd, int exectype)
371 BOOL needToTry = TRUE;
374 /* Save an extra exec if possible. See if there are shell
375 * metacharacters in it */
376 if(!has_redirection(cmd)) {
377 New(1301,argv, strlen(cmd) / 2 + 2, char*);
378 New(1302,cmd2, strlen(cmd) + 1, char);
381 for (s = cmd2; *s;) {
382 while (*s && isspace(*s))
386 while(*s && !isspace(*s))
395 status = win32_spawnvp(P_WAIT, argv[0],
396 (const char* const*)argv);
398 case EXECF_SPAWN_NOWAIT:
399 status = win32_spawnvp(P_NOWAIT, argv[0],
400 (const char* const*)argv);
403 status = win32_execvp(argv[0], (const char* const*)argv);
406 if (status != -1 || errno == 0)
416 New(1306, argv, w32_perlshell_items + 2, char*);
417 while (++i < w32_perlshell_items)
418 argv[i] = w32_perlshell_vec[i];
423 status = win32_spawnvp(P_WAIT, argv[0],
424 (const char* const*)argv);
426 case EXECF_SPAWN_NOWAIT:
427 status = win32_spawnvp(P_NOWAIT, argv[0],
428 (const char* const*)argv);
431 status = win32_execvp(argv[0], (const char* const*)argv);
437 if (exectype != EXECF_SPAWN_NOWAIT) {
440 warn("Can't %s \"%s\": %s",
441 (exectype == EXECF_EXEC ? "exec" : "spawn"),
442 cmd, strerror(errno));
447 statusvalue = status;
455 return do_spawn2(cmd, EXECF_SPAWN);
459 do_spawn_nowait(char *cmd)
461 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
467 do_spawn2(cmd, EXECF_EXEC);
474 /* The idea here is to read all the directory names into a string table
475 * (separated by nulls) and when one of the other dir functions is called
476 * return the pointer to the current file name.
479 opendir(char *filename)
484 char scannamespc[PATHLEN];
485 char *scanname = scannamespc;
487 WIN32_FIND_DATA FindData;
489 /* char root[_MAX_PATH];*/
490 /* char volname[_MAX_PATH];*/
491 /* DWORD serial, maxname, flags;*/
495 /* check to see if filename is a directory */
496 if (win32_stat(filename, &sbuf) < 0 || (sbuf.st_mode & S_IFDIR) == 0) {
497 /* CRT is buggy on sharenames, so make sure it really isn't */
498 DWORD r = GetFileAttributes(filename);
499 if (r == 0xffffffff || !(r & FILE_ATTRIBUTE_DIRECTORY))
503 /* get the file system characteristics */
504 /* if(GetFullPathName(filename, MAX_PATH, root, &dummy)) {
505 * if(dummy = strchr(root, '\\'))
507 * if(GetVolumeInformation(root, volname, MAX_PATH, &serial,
508 * &maxname, &flags, 0, 0)) {
509 * downcase = !(flags & FS_CASE_IS_PRESERVED);
516 /* Get us a DIR structure */
517 Newz(1303, p, 1, DIR);
521 /* Create the search pattern */
522 strcpy(scanname, filename);
524 if(index("/\\", *(scanname + strlen(scanname) - 1)) == NULL)
525 strcat(scanname, "/*");
527 strcat(scanname, "*");
529 /* do the FindFirstFile call */
530 fh = FindFirstFile(scanname, &FindData);
531 if(fh == INVALID_HANDLE_VALUE) {
535 /* now allocate the first part of the string table for
536 * the filenames that we find.
538 idx = strlen(FindData.cFileName)+1;
539 New(1304, p->start, idx, char);
540 if(p->start == NULL) {
541 croak("opendir: malloc failed!\n");
543 strcpy(p->start, FindData.cFileName);
549 /* loop finding all the files that match the wildcard
550 * (which should be all of them in this directory!).
551 * the variable idx should point one past the null terminator
552 * of the previous string found.
554 while (FindNextFile(fh, &FindData)) {
555 len = strlen(FindData.cFileName);
556 /* bump the string table size by enough for the
557 * new name and it's null terminator
559 Renew(p->start, idx+len+1, char);
560 if(p->start == NULL) {
561 croak("opendir: malloc failed!\n");
563 strcpy(&p->start[idx], FindData.cFileName);
565 * strlwr(&p->start[idx]);
577 /* Readdir just returns the current string pointer and bumps the
578 * string pointer to the nDllExport entry.
584 static int dummy = 0;
587 /* first set up the structure to return */
588 len = strlen(dirp->curr);
589 strcpy(dirp->dirstr.d_name, dirp->curr);
590 dirp->dirstr.d_namlen = len;
593 dirp->dirstr.d_ino = dummy++;
595 /* Now set up for the nDllExport call to readdir */
596 dirp->curr += len + 1;
597 if (dirp->curr >= (dirp->start + dirp->size)) {
601 return &(dirp->dirstr);
607 /* Telldir returns the current string pointer position */
611 return (long) dirp->curr;
615 /* Seekdir moves the string pointer to a previously saved position
619 seekdir(DIR *dirp, long loc)
621 dirp->curr = (char *)loc;
624 /* Rewinddir resets the string pointer to the start */
628 dirp->curr = dirp->start;
631 /* free the memory allocated by opendir */
635 Safefree(dirp->start);
648 * Just pretend that everyone is a superuser. NT will let us know if
649 * we don\'t really have permission to do something.
652 #define ROOT_UID ((uid_t)0)
653 #define ROOT_GID ((gid_t)0)
682 return (auid == ROOT_UID ? 0 : -1);
688 return (agid == ROOT_GID ? 0 : -1);
695 char *buf = getlogin_buffer;
696 DWORD size = sizeof(getlogin_buffer);
697 if (GetUserName(buf,&size))
703 chown(const char *path, uid_t owner, gid_t group)
710 kill(int pid, int sig)
712 HANDLE hProcess= OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
714 if (hProcess == NULL) {
715 croak("kill process failed!\n");
718 if (!TerminateProcess(hProcess, sig))
719 croak("kill process failed!\n");
720 CloseHandle(hProcess);
729 DllExport unsigned int
730 win32_sleep(unsigned int t)
737 win32_stat(const char *path, struct stat *buffer)
740 const char *p = path;
741 int l = strlen(path);
745 switch(path[l - 1]) {
748 if (path[l - 2] != ':') {
749 strncpy(t, path, l - 1);
755 res = stat(p,buffer);
758 if (S_ISDIR(buffer->st_mode))
759 buffer->st_mode |= S_IWRITE | S_IEXEC;
760 else if (S_ISREG(buffer->st_mode)) {
761 if (l >= 4 && path[l-4] == '.') {
762 const char *e = path + l - 3;
763 if (strnicmp(e,"exe",3)
764 && strnicmp(e,"bat",3)
765 && strnicmp(e,"com",3)
766 && (IsWin95() || strnicmp(e,"cmd",3)))
767 buffer->st_mode &= ~S_IEXEC;
769 buffer->st_mode |= S_IEXEC;
772 buffer->st_mode &= ~S_IEXEC;
779 #ifndef USE_WIN32_RTL_ENV
782 win32_getenv(const char *name)
784 static char *curitem = Nullch;
785 static DWORD curlen = 512;
788 New(1305,curitem,curlen,char);
789 if (!(needlen = GetEnvironmentVariable(name,curitem,curlen)))
791 while (needlen > curlen) {
792 Renew(curitem,needlen,char);
794 needlen = GetEnvironmentVariable(name,curitem,curlen);
802 filetime_to_clock(PFILETIME ft)
804 __int64 qw = ft->dwHighDateTime;
806 qw |= ft->dwLowDateTime;
807 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
812 win32_times(struct tms *timebuf)
817 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
819 timebuf->tms_utime = filetime_to_clock(&user);
820 timebuf->tms_stime = filetime_to_clock(&kernel);
821 timebuf->tms_cutime = 0;
822 timebuf->tms_cstime = 0;
825 /* That failed - e.g. Win95 fallback to clock() */
827 timebuf->tms_utime = t;
828 timebuf->tms_stime = 0;
829 timebuf->tms_cutime = 0;
830 timebuf->tms_cstime = 0;
835 /* fix utime() so it works on directories in NT
836 * thanks to Jan Dubois <jan.dubois@ibm.net>
839 filetime_from_time(PFILETIME pFileTime, time_t Time)
841 struct tm *pTM = gmtime(&Time);
842 SYSTEMTIME SystemTime;
847 SystemTime.wYear = pTM->tm_year + 1900;
848 SystemTime.wMonth = pTM->tm_mon + 1;
849 SystemTime.wDay = pTM->tm_mday;
850 SystemTime.wHour = pTM->tm_hour;
851 SystemTime.wMinute = pTM->tm_min;
852 SystemTime.wSecond = pTM->tm_sec;
853 SystemTime.wMilliseconds = 0;
855 return SystemTimeToFileTime(&SystemTime, pFileTime);
859 win32_utime(const char *filename, struct utimbuf *times)
865 struct utimbuf TimeBuffer;
867 int rc = utime(filename,times);
868 /* EACCES: path specifies directory or readonly file */
869 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
874 time(×->actime);
875 times->modtime = times->actime;
878 /* This will (and should) still fail on readonly files */
879 handle = CreateFile(filename, GENERIC_READ | GENERIC_WRITE,
880 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
881 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
882 if (handle == INVALID_HANDLE_VALUE)
885 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
886 filetime_from_time(&ftAccess, times->actime) &&
887 filetime_from_time(&ftWrite, times->modtime) &&
888 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
898 win32_wait(int *status)
903 /* XXX this wait emulation only knows about processes
904 * spawned via win32_spawnvp(P_NOWAIT, ...).
907 DWORD exitcode, waitcode;
909 if (!w32_num_children) {
914 /* if a child exists, wait for it to die */
915 waitcode = WaitForMultipleObjects(w32_num_children,
919 if (waitcode != WAIT_FAILED) {
920 if (waitcode >= WAIT_ABANDONED_0
921 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
922 i = waitcode - WAIT_ABANDONED_0;
924 i = waitcode - WAIT_OBJECT_0;
925 if (GetExitCodeProcess(w32_child_pids[i], &exitcode) ) {
926 CloseHandle(w32_child_pids[i]);
927 *status = (int)((exitcode & 0xff) << 8);
928 retval = (int)w32_child_pids[i];
929 Copy(&w32_child_pids[i+1], &w32_child_pids[i],
930 (w32_num_children-i-1), HANDLE);
937 errno = GetLastError();
943 static UINT timerid = 0;
945 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
947 KillTimer(NULL,timerid);
952 DllExport unsigned int
953 win32_alarm(unsigned int sec)
956 * the 'obvious' implentation is SetTimer() with a callback
957 * which does whatever receiving SIGALRM would do
958 * we cannot use SIGALRM even via raise() as it is not
959 * one of the supported codes in <signal.h>
961 * Snag is unless something is looking at the message queue
962 * nothing happens :-(
966 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
968 croak("Cannot set timer");
974 KillTimer(NULL,timerid);
981 #ifdef HAVE_DES_FCRYPT
982 extern char * des_fcrypt(char *cbuf, const char *txt, const char *salt);
985 win32_crypt(const char *txt, const char *salt)
988 return des_fcrypt(crypt_buffer, txt, salt);
992 #ifdef USE_FIXED_OSFHANDLE
994 EXTERN_C int __cdecl _alloc_osfhnd(void);
995 EXTERN_C int __cdecl _set_osfhnd(int fh, long value);
996 EXTERN_C void __cdecl _lock_fhandle(int);
997 EXTERN_C void __cdecl _unlock_fhandle(int);
998 EXTERN_C void __cdecl _unlock(int);
1000 #if (_MSC_VER >= 1000)
1002 long osfhnd; /* underlying OS file HANDLE */
1003 char osfile; /* attributes of file (e.g., open in text mode?) */
1004 char pipech; /* one char buffer for handles opened on pipes */
1005 #if defined (_MT) && !defined (DLL_FOR_WIN32S)
1007 CRITICAL_SECTION lock;
1008 #endif /* defined (_MT) && !defined (DLL_FOR_WIN32S) */
1011 EXTERN_C ioinfo * __pioinfo[];
1013 #define IOINFO_L2E 5
1014 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
1015 #define _pioinfo(i) (__pioinfo[i >> IOINFO_L2E] + (i & (IOINFO_ARRAY_ELTS - 1)))
1016 #define _osfile(i) (_pioinfo(i)->osfile)
1018 #else /* (_MSC_VER >= 1000) */
1019 extern char _osfile[];
1020 #endif /* (_MSC_VER >= 1000) */
1022 #define FOPEN 0x01 /* file handle open */
1023 #define FAPPEND 0x20 /* file handle opened O_APPEND */
1024 #define FDEV 0x40 /* file handle refers to device */
1025 #define FTEXT 0x80 /* file handle is in text mode */
1027 #define _STREAM_LOCKS 26 /* Table of stream locks */
1028 #define _LAST_STREAM_LOCK (_STREAM_LOCKS+_NSTREAM_-1) /* Last stream lock */
1029 #define _FH_LOCKS (_LAST_STREAM_LOCK+1) /* Table of fh locks */
1032 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1035 * This function allocates a free C Runtime file handle and associates
1036 * it with the Win32 HANDLE specified by the first parameter. This is a
1037 * temperary fix for WIN95's brain damage GetFileType() error on socket
1038 * we just bypass that call for socket
1041 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1042 * int flags - flags to associate with C Runtime file handle.
1045 * returns index of entry in fh, if successful
1046 * return -1, if no free entry is found
1050 *******************************************************************************/
1053 my_open_osfhandle(long osfhandle, int flags)
1056 char fileflags; /* _osfile flags */
1058 /* copy relevant flags from second parameter */
1061 if(flags & O_APPEND)
1062 fileflags |= FAPPEND;
1067 /* attempt to allocate a C Runtime file handle */
1068 if((fh = _alloc_osfhnd()) == -1) {
1069 errno = EMFILE; /* too many open files */
1070 _doserrno = 0L; /* not an OS error */
1071 return -1; /* return error to caller */
1074 /* the file is open. now, set the info in _osfhnd array */
1075 _set_osfhnd(fh, osfhandle);
1077 fileflags |= FOPEN; /* mark as open */
1079 #if (_MSC_VER >= 1000)
1080 _osfile(fh) = fileflags; /* set osfile entry */
1081 _unlock_fhandle(fh);
1083 _osfile[fh] = fileflags; /* set osfile entry */
1084 _unlock(fh+_FH_LOCKS); /* unlock handle */
1087 return fh; /* return handle */
1090 #define _open_osfhandle my_open_osfhandle
1091 #endif /* USE_FIXED_OSFHANDLE */
1093 /* simulate flock by locking a range on the file */
1095 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1096 #define LK_LEN 0xffff0000
1099 win32_flock(int fd, int oper)
1106 croak("flock() unimplemented on this platform");
1109 fh = (HANDLE)_get_osfhandle(fd);
1110 memset(&o, 0, sizeof(o));
1113 case LOCK_SH: /* shared lock */
1114 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1116 case LOCK_EX: /* exclusive lock */
1117 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1119 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1120 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1122 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1123 LK_ERR(LockFileEx(fh,
1124 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1125 0, LK_LEN, 0, &o),i);
1127 case LOCK_UN: /* unlock lock */
1128 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1130 default: /* unknown */
1141 * redirected io subsystem for all XS modules
1154 return (&(_environ));
1157 /* the rest are the remapped stdio routines */
1177 win32_ferror(FILE *fp)
1179 return (ferror(fp));
1184 win32_feof(FILE *fp)
1190 * Since the errors returned by the socket error function
1191 * WSAGetLastError() are not known by the library routine strerror
1192 * we have to roll our own.
1196 win32_strerror(int e)
1198 #ifndef __BORLANDC__ /* Borland intolerance */
1199 extern int sys_nerr;
1203 if(e < 0 || e > sys_nerr) {
1208 if(FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
1209 strerror_buffer, sizeof(strerror_buffer), NULL) == 0)
1210 strcpy(strerror_buffer, "Unknown Error");
1212 return strerror_buffer;
1218 win32_str_os_error(void *sv, DWORD dwErr)
1222 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
1223 |FORMAT_MESSAGE_IGNORE_INSERTS
1224 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
1225 dwErr, 0, (char *)&sMsg, 1, NULL);
1227 while (0 < dwLen && isspace(sMsg[--dwLen]))
1229 if ('.' != sMsg[dwLen])
1234 sMsg = LocalAlloc(0, 64/**sizeof(TCHAR)*/);
1235 dwLen = sprintf(sMsg,
1236 "Unknown error #0x%lX (lookup 0x%lX)",
1237 dwErr, GetLastError());
1239 sv_setpvn((SV*)sv, sMsg, dwLen);
1245 win32_fprintf(FILE *fp, const char *format, ...)
1248 va_start(marker, format); /* Initialize variable arguments. */
1250 return (vfprintf(fp, format, marker));
1254 win32_printf(const char *format, ...)
1257 va_start(marker, format); /* Initialize variable arguments. */
1259 return (vprintf(format, marker));
1263 win32_vfprintf(FILE *fp, const char *format, va_list args)
1265 return (vfprintf(fp, format, args));
1269 win32_vprintf(const char *format, va_list args)
1271 return (vprintf(format, args));
1275 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
1277 return fread(buf, size, count, fp);
1281 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
1283 return fwrite(buf, size, count, fp);
1287 win32_fopen(const char *filename, const char *mode)
1289 if (stricmp(filename, "/dev/null")==0)
1290 return fopen("NUL", mode);
1291 return fopen(filename, mode);
1294 #ifndef USE_SOCKETS_AS_HANDLES
1296 #define fdopen my_fdopen
1300 win32_fdopen( int handle, const char *mode)
1302 return fdopen(handle, (char *) mode);
1306 win32_freopen( const char *path, const char *mode, FILE *stream)
1308 if (stricmp(path, "/dev/null")==0)
1309 return freopen("NUL", mode, stream);
1310 return freopen(path, mode, stream);
1314 win32_fclose(FILE *pf)
1316 return my_fclose(pf); /* defined in win32sck.c */
1320 win32_fputs(const char *s,FILE *pf)
1322 return fputs(s, pf);
1326 win32_fputc(int c,FILE *pf)
1332 win32_ungetc(int c,FILE *pf)
1334 return ungetc(c,pf);
1338 win32_getc(FILE *pf)
1344 win32_fileno(FILE *pf)
1350 win32_clearerr(FILE *pf)
1357 win32_fflush(FILE *pf)
1363 win32_ftell(FILE *pf)
1369 win32_fseek(FILE *pf,long offset,int origin)
1371 return fseek(pf, offset, origin);
1375 win32_fgetpos(FILE *pf,fpos_t *p)
1377 return fgetpos(pf, p);
1381 win32_fsetpos(FILE *pf,const fpos_t *p)
1383 return fsetpos(pf, p);
1387 win32_rewind(FILE *pf)
1407 win32_fstat(int fd,struct stat *sbufptr)
1409 return fstat(fd,sbufptr);
1413 win32_pipe(int *pfd, unsigned int size, int mode)
1415 return _pipe(pfd, size, mode);
1419 * a popen() clone that respects PERL5SHELL
1423 win32_popen(const char *command, const char *mode)
1425 #ifdef USE_CRT_POPEN
1426 return _popen(command, mode);
1434 /* establish which ends read and write */
1435 if (strchr(mode,'w')) {
1436 stdfd = 0; /* stdin */
1440 else if (strchr(mode,'r')) {
1441 stdfd = 1; /* stdout */
1448 /* set the correct mode */
1449 if (strchr(mode,'b'))
1451 else if (strchr(mode,'t'))
1454 ourmode = _fmode & (O_TEXT | O_BINARY);
1456 /* the child doesn't inherit handles */
1457 ourmode |= O_NOINHERIT;
1459 if (win32_pipe( p, 512, ourmode) == -1)
1462 /* save current stdfd */
1463 if ((oldfd = win32_dup(stdfd)) == -1)
1466 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
1467 /* stdfd will be inherited by the child */
1468 if (win32_dup2(p[child], stdfd) == -1)
1471 /* close the child end in parent */
1472 win32_close(p[child]);
1474 /* start the child */
1475 if ((childpid = do_spawn_nowait((char*)command)) == -1)
1478 /* revert stdfd to whatever it was before */
1479 if (win32_dup2(oldfd, stdfd) == -1)
1482 /* close saved handle */
1485 w32_popen_pids[p[parent]] = childpid;
1487 /* we have an fd, return a file stream */
1488 return (win32_fdopen(p[parent], (char *)mode));
1491 /* we don't need to check for errors here */
1495 win32_dup2(oldfd, stdfd);
1500 #endif /* USE_CRT_POPEN */
1508 win32_pclose(FILE *pf)
1510 #ifdef USE_CRT_POPEN
1513 int fd, childpid, status;
1515 fd = win32_fileno(pf);
1516 childpid = w32_popen_pids[fd];
1524 w32_popen_pids[fd] = 0;
1526 /* wait for the child */
1527 if (cwait(&status, childpid, WAIT_CHILD) == -1)
1529 /* cwait() returns differently on Borland */
1531 return (((status >> 8) & 0xff) | ((status << 8) & 0xff00));
1536 #endif /* USE_CRT_OPEN */
1540 win32_setmode(int fd, int mode)
1542 return setmode(fd, mode);
1546 win32_lseek(int fd, long offset, int origin)
1548 return lseek(fd, offset, origin);
1558 win32_open(const char *path, int flag, ...)
1564 pmode = va_arg(ap, int);
1567 if (stricmp(path, "/dev/null")==0)
1568 return open("NUL", flag, pmode);
1569 return open(path,flag,pmode);
1591 win32_dup2(int fd1,int fd2)
1593 return dup2(fd1,fd2);
1597 win32_read(int fd, void *buf, unsigned int cnt)
1599 return read(fd, buf, cnt);
1603 win32_write(int fd, const void *buf, unsigned int cnt)
1605 return write(fd, buf, cnt);
1609 win32_mkdir(const char *dir, int mode)
1611 return mkdir(dir); /* just ignore mode */
1615 win32_rmdir(const char *dir)
1621 win32_chdir(const char *dir)
1627 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
1631 status = spawnvp(mode, cmdname, (char * const *) argv);
1632 #ifndef __BORLANDC__
1633 /* XXX For the P_NOWAIT case, Borland RTL returns pinfo.dwProcessId
1634 * while VC RTL returns pinfo.hProcess. For purposes of the custom
1635 * implementation of win32_wait(), we assume the latter.
1637 if (mode == P_NOWAIT && status >= 0)
1638 w32_child_pids[w32_num_children++] = (HANDLE)status;
1644 win32_execvp(const char *cmdname, const char *const *argv)
1646 return execvp(cmdname, (char *const *)argv);
1650 win32_perror(const char *str)
1656 win32_setbuf(FILE *pf, char *buf)
1662 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
1664 return setvbuf(pf, buf, type, size);
1668 win32_flushall(void)
1674 win32_fcloseall(void)
1680 win32_fgets(char *s, int n, FILE *pf)
1682 return fgets(s, n, pf);
1692 win32_fgetc(FILE *pf)
1698 win32_putc(int c, FILE *pf)
1704 win32_puts(const char *s)
1716 win32_putchar(int c)
1723 #ifndef USE_PERL_SBRK
1725 static char *committed = NULL;
1726 static char *base = NULL;
1727 static char *reserved = NULL;
1728 static char *brk = NULL;
1729 static DWORD pagesize = 0;
1730 static DWORD allocsize = 0;
1738 GetSystemInfo(&info);
1739 /* Pretend page size is larger so we don't perpetually
1740 * call the OS to commit just one page ...
1742 pagesize = info.dwPageSize << 3;
1743 allocsize = info.dwAllocationGranularity;
1745 /* This scheme fails eventually if request for contiguous
1746 * block is denied so reserve big blocks - this is only
1747 * address space not memory ...
1749 if (brk+need >= reserved)
1751 DWORD size = 64*1024*1024;
1753 if (committed && reserved && committed < reserved)
1755 /* Commit last of previous chunk cannot span allocations */
1756 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
1758 committed = reserved;
1760 /* Reserve some (more) space
1761 * Note this is a little sneaky, 1st call passes NULL as reserved
1762 * so lets system choose where we start, subsequent calls pass
1763 * the old end address so ask for a contiguous block
1765 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
1768 reserved = addr+size;
1783 if (brk > committed)
1785 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
1786 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
1801 win32_malloc(size_t size)
1803 return malloc(size);
1807 win32_calloc(size_t numitems, size_t size)
1809 return calloc(numitems,size);
1813 win32_realloc(void *block, size_t size)
1815 return realloc(block,size);
1819 win32_free(void *block)
1826 win32_open_osfhandle(long handle, int flags)
1828 return _open_osfhandle(handle, flags);
1832 win32_get_osfhandle(int fd)
1834 return _get_osfhandle(fd);
1845 SV *sv = sv_newmortal();
1846 /* Make one call with zero size - return value is required size */
1847 DWORD len = GetCurrentDirectory((DWORD)0,NULL);
1848 SvUPGRADE(sv,SVt_PV);
1850 SvCUR(sv) = GetCurrentDirectory((DWORD) SvLEN(sv), SvPVX(sv));
1853 * then it worked, set PV valid,
1854 * else leave it 'undef'
1868 croak("usage: Win32::SetCurrentDirectory($cwd)");
1869 if (SetCurrentDirectory(SvPV(ST(0),na)))
1876 XS(w32_GetNextAvailDrive)
1880 char root[] = "_:\\";
1883 if (GetDriveType(root) == 1) {
1892 XS(w32_GetLastError)
1895 XSRETURN_IV(GetLastError());
1902 char *name = getlogin_buffer;
1903 DWORD size = sizeof(getlogin_buffer);
1904 if (GetUserName(name,&size)) {
1905 /* size includes NULL */
1906 ST(0) = sv_2mortal(newSVpv(name,size-1));
1916 char name[MAX_COMPUTERNAME_LENGTH+1];
1917 DWORD size = sizeof(name);
1918 if (GetComputerName(name,&size)) {
1919 /* size does NOT include NULL :-( */
1920 ST(0) = sv_2mortal(newSVpv(name,size));
1932 DWORD size = sizeof(name);
1933 if (GetUserName(name,&size)) {
1935 DWORD sidlen = sizeof(sid);
1937 DWORD dnamelen = sizeof(dname);
1939 if (LookupAccountName(NULL, name, &sid, &sidlen,
1940 dname, &dnamelen, &snu)) {
1941 XSRETURN_PV(dname); /* all that for this */
1952 DWORD flags, filecomplen;
1953 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
1954 &flags, fsname, sizeof(fsname))) {
1955 if (GIMME == G_ARRAY) {
1956 XPUSHs(sv_2mortal(newSVpv(fsname,0)));
1957 XPUSHs(sv_2mortal(newSViv(flags)));
1958 XPUSHs(sv_2mortal(newSViv(filecomplen)));
1962 XSRETURN_PV(fsname);
1968 XS(w32_GetOSVersion)
1971 OSVERSIONINFO osver;
1973 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1974 if (GetVersionEx(&osver)) {
1975 XPUSHs(newSVpv(osver.szCSDVersion, 0));
1976 XPUSHs(newSViv(osver.dwMajorVersion));
1977 XPUSHs(newSViv(osver.dwMinorVersion));
1978 XPUSHs(newSViv(osver.dwBuildNumber));
1979 XPUSHs(newSViv(osver.dwPlatformId));
1990 XSRETURN_IV(IsWinNT());
1997 XSRETURN_IV(IsWin95());
2001 XS(w32_FormatMessage)
2008 croak("usage: Win32::FormatMessage($errno)");
2010 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
2011 &source, SvIV(ST(0)), 0,
2012 msgbuf, sizeof(msgbuf)-1, NULL))
2013 XSRETURN_PV(msgbuf);
2023 PROCESS_INFORMATION stProcInfo;
2024 STARTUPINFO stStartInfo;
2025 BOOL bSuccess = FALSE;
2028 croak("usage: Win32::Spawn($cmdName, $args, $PID)");
2030 cmd = SvPV(ST(0),na);
2031 args = SvPV(ST(1), na);
2033 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
2034 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
2035 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
2036 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
2039 cmd, /* Image path */
2040 args, /* Arguments for command line */
2041 NULL, /* Default process security */
2042 NULL, /* Default thread security */
2043 FALSE, /* Must be TRUE to use std handles */
2044 NORMAL_PRIORITY_CLASS, /* No special scheduling */
2045 NULL, /* Inherit our environment block */
2046 NULL, /* Inherit our currrent directory */
2047 &stStartInfo, /* -> Startup info */
2048 &stProcInfo)) /* <- Process info (if OK) */
2050 CloseHandle(stProcInfo.hThread);/* library source code does this. */
2051 sv_setiv(ST(2), stProcInfo.dwProcessId);
2054 XSRETURN_IV(bSuccess);
2058 XS(w32_GetTickCount)
2061 XSRETURN_IV(GetTickCount());
2065 XS(w32_GetShortPathName)
2072 croak("usage: Win32::GetShortPathName($longPathName)");
2074 shortpath = sv_mortalcopy(ST(0));
2075 SvUPGRADE(shortpath, SVt_PV);
2076 /* src == target is allowed */
2078 len = GetShortPathName(SvPVX(shortpath),
2081 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
2083 SvCUR_set(shortpath,len);
2096 croak("usage: Win32::Sleep($milliseconds)");
2102 Perl_init_os_extras()
2104 char *file = __FILE__;
2107 /* these names are Activeware compatible */
2108 newXS("Win32::GetCwd", w32_GetCwd, file);
2109 newXS("Win32::SetCwd", w32_SetCwd, file);
2110 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
2111 newXS("Win32::GetLastError", w32_GetLastError, file);
2112 newXS("Win32::LoginName", w32_LoginName, file);
2113 newXS("Win32::NodeName", w32_NodeName, file);
2114 newXS("Win32::DomainName", w32_DomainName, file);
2115 newXS("Win32::FsType", w32_FsType, file);
2116 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
2117 newXS("Win32::IsWinNT", w32_IsWinNT, file);
2118 newXS("Win32::IsWin95", w32_IsWin95, file);
2119 newXS("Win32::FormatMessage", w32_FormatMessage, file);
2120 newXS("Win32::Spawn", w32_Spawn, file);
2121 newXS("Win32::GetTickCount", w32_GetTickCount, file);
2122 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
2123 newXS("Win32::Sleep", w32_Sleep, file);
2125 /* XXX Bloat Alert! The following Activeware preloads really
2126 * ought to be part of Win32::Sys::*, so they're not included
2129 /* LookupAccountName
2131 * InitiateSystemShutdown
2132 * AbortSystemShutdown
2133 * ExpandEnvrironmentStrings
2138 Perl_win32_init(int *argcp, char ***argvp)
2140 /* Disable floating point errors, Perl will trap the ones we
2141 * care about. VC++ RTL defaults to switching these off
2142 * already, but the Borland RTL doesn't. Since we don't
2143 * want to be at the vendor's whim on the default, we set
2144 * it explicitly here.
2146 #if !defined(_ALPHA_) && !defined(__GNUC__)
2147 _control87(MCW_EM, MCW_EM);
2152 #ifdef USE_BINMODE_SCRIPTS
2155 win32_strip_return(SV *sv)
2157 char *s = SvPVX(sv);
2158 char *e = s+SvCUR(sv);
2162 if (*s == '\r' && s[1] == '\n')
2172 SvCUR_set(sv,d-SvPVX(sv));