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 */
40 /* Mingw32 defaults to globing command line
41 * So we turn it off like this:
48 #define EXECF_SPAWN_NOWAIT 3
50 static DWORD os_id(void);
51 static void get_shell(void);
52 static long tokenize(char *str, char **dest, char ***destv);
53 static int do_spawn2(char *cmd, int exectype);
54 static BOOL has_redirection(char *ptr);
55 static long filetime_to_clock(PFILETIME ft);
57 char * w32_perlshell_tokens = Nullch;
58 char ** w32_perlshell_vec;
59 long w32_perlshell_items = -1;
60 DWORD w32_platform = (DWORD)-1;
61 char w32_perllib_root[MAX_PATH+1];
62 HANDLE w32_perldll_handle = INVALID_HANDLE_VALUE;
64 long w32_num_children = 0;
65 HANDLE w32_child_pids[MAXIMUM_WAIT_OBJECTS];
69 # ifdef USE_DECLSPEC_THREAD
70 __declspec(thread) char strerror_buffer[512];
71 __declspec(thread) char getlogin_buffer[128];
72 # ifdef HAVE_DES_FCRYPT
73 __declspec(thread) char crypt_buffer[30];
76 # define strerror_buffer (thr->i.Wstrerror_buffer)
77 # define getlogin_buffer (thr->i.Wgetlogin_buffer)
78 # define crypt_buffer (thr->i.Wcrypt_buffer)
81 char strerror_buffer[512];
82 char getlogin_buffer[128];
83 # ifdef HAVE_DES_FCRYPT
84 char crypt_buffer[30];
90 return (os_id() == VER_PLATFORM_WIN32_WINDOWS);
95 return (os_id() == VER_PLATFORM_WIN32_NT);
99 win32_perllib_path(char *sfx,...)
104 GetModuleFileName((w32_perldll_handle == INVALID_HANDLE_VALUE)
105 ? GetModuleHandle(NULL)
106 : w32_perldll_handle,
108 sizeof(w32_perllib_root));
109 *(end = strrchr(w32_perllib_root, '\\')) = '\0';
110 if (stricmp(end-4,"\\bin") == 0)
117 sfx = va_arg(ap,char *);
120 return (w32_perllib_root);
125 has_redirection(char *ptr)
131 * Scan string looking for redirection (< or >) or pipe
132 * characters (|) that are not in a quoted string
162 /* since the current process environment is being updated in util.c
163 * the library functions will get the correct environment
166 my_popen(char *cmd, char *mode)
169 #define fixcmd(x) { \
170 char *pspace = strchr((x),' '); \
173 while (p < pspace) { \
184 #ifdef __BORLANDC__ /* workaround a Borland stdio bug */
185 win32_fflush(stdout);
186 win32_fflush(stderr);
188 return win32_popen(cmd, mode);
192 my_pclose(PerlIO *fp)
194 return win32_pclose(fp);
200 static OSVERSIONINFO osver;
202 if (osver.dwPlatformId != w32_platform) {
203 memset(&osver, 0, sizeof(OSVERSIONINFO));
204 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
205 GetVersionEx(&osver);
206 w32_platform = osver.dwPlatformId;
208 return (w32_platform);
211 /* Tokenize a string. Words are null-separated, and the list
212 * ends with a doubled null. Any character (except null and
213 * including backslash) may be escaped by preceding it with a
214 * backslash (the backslash will be stripped).
215 * Returns number of words in result buffer.
218 tokenize(char *str, char **dest, char ***destv)
220 char *retstart = Nullch;
221 char **retvstart = 0;
224 int slen = strlen(str);
226 register char **retv;
227 New(1307, ret, slen+2, char);
228 New(1308, retv, (slen+3)/2, char*);
236 if (*ret == '\\' && *str)
238 else if (*ret == ' ') {
254 retvstart[items] = Nullch;
266 if (!w32_perlshell_tokens) {
267 /* we don't use COMSPEC here for two reasons:
268 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
269 * uncontrolled unportability of the ensuing scripts.
270 * 2. PERL5SHELL could be set to a shell that may not be fit for
271 * interactive use (which is what most programs look in COMSPEC
274 char* defaultshell = (IsWinNT() ? "cmd.exe /x/c" : "command.com /c");
275 char *usershell = getenv("PERL5SHELL");
276 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
277 &w32_perlshell_tokens,
283 do_aspawn(void *vreally, void **vmark, void **vsp)
285 SV *really = (SV*)vreally;
286 SV **mark = (SV**)vmark;
298 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
300 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
305 while(++mark <= sp) {
306 if (*mark && (str = SvPV(*mark, na)))
313 status = win32_spawnvp(flag,
314 (really ? SvPV(really,na) : argv[0]),
315 (const char* const*)argv);
317 if (status < 0 && errno == ENOEXEC) {
318 /* possible shell-builtin, invoke with shell */
320 sh_items = w32_perlshell_items;
322 argv[index+sh_items] = argv[index];
323 while (--sh_items >= 0)
324 argv[sh_items] = w32_perlshell_vec[sh_items];
326 status = win32_spawnvp(flag,
327 (really ? SvPV(really,na) : argv[0]),
328 (const char* const*)argv);
333 warn("Can't spawn \"%s\": %s", argv[0], strerror(errno));
336 else if (flag != P_NOWAIT)
339 return (statusvalue = status);
343 do_spawn2(char *cmd, int exectype)
349 BOOL needToTry = TRUE;
352 /* Save an extra exec if possible. See if there are shell
353 * metacharacters in it */
354 if(!has_redirection(cmd)) {
355 New(1301,argv, strlen(cmd) / 2 + 2, char*);
356 New(1302,cmd2, strlen(cmd) + 1, char);
359 for (s = cmd2; *s;) {
360 while (*s && isspace(*s))
364 while(*s && !isspace(*s))
373 status = win32_spawnvp(P_WAIT, argv[0],
374 (const char* const*)argv);
376 case EXECF_SPAWN_NOWAIT:
377 status = win32_spawnvp(P_NOWAIT, argv[0],
378 (const char* const*)argv);
381 status = win32_execvp(argv[0], (const char* const*)argv);
384 if (status != -1 || errno == 0)
394 New(1306, argv, w32_perlshell_items + 2, char*);
395 while (++i < w32_perlshell_items)
396 argv[i] = w32_perlshell_vec[i];
401 status = win32_spawnvp(P_WAIT, argv[0],
402 (const char* const*)argv);
404 case EXECF_SPAWN_NOWAIT:
405 status = win32_spawnvp(P_NOWAIT, argv[0],
406 (const char* const*)argv);
409 status = win32_execvp(argv[0], (const char* const*)argv);
417 warn("Can't %s \"%s\": %s",
418 (exectype == EXECF_EXEC ? "exec" : "spawn"),
419 cmd, strerror(errno));
422 else if (exectype != EXECF_SPAWN_NOWAIT)
424 return (statusvalue = status);
430 return do_spawn2(cmd, EXECF_SPAWN);
434 do_spawn_nowait(char *cmd)
436 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
442 do_spawn2(cmd, EXECF_EXEC);
449 /* The idea here is to read all the directory names into a string table
450 * (separated by nulls) and when one of the other dir functions is called
451 * return the pointer to the current file name.
454 opendir(char *filename)
459 char scannamespc[PATHLEN];
460 char *scanname = scannamespc;
462 WIN32_FIND_DATA FindData;
464 /* char root[_MAX_PATH];*/
465 /* char volname[_MAX_PATH];*/
466 /* DWORD serial, maxname, flags;*/
470 /* check to see if filename is a directory */
471 if (win32_stat(filename, &sbuf) < 0 || (sbuf.st_mode & S_IFDIR) == 0) {
475 /* get the file system characteristics */
476 /* if(GetFullPathName(filename, MAX_PATH, root, &dummy)) {
477 * if(dummy = strchr(root, '\\'))
479 * if(GetVolumeInformation(root, volname, MAX_PATH, &serial,
480 * &maxname, &flags, 0, 0)) {
481 * downcase = !(flags & FS_CASE_IS_PRESERVED);
488 /* Get us a DIR structure */
489 Newz(1303, p, 1, DIR);
493 /* Create the search pattern */
494 strcpy(scanname, filename);
496 if(index("/\\", *(scanname + strlen(scanname) - 1)) == NULL)
497 strcat(scanname, "/*");
499 strcat(scanname, "*");
501 /* do the FindFirstFile call */
502 fh = FindFirstFile(scanname, &FindData);
503 if(fh == INVALID_HANDLE_VALUE) {
507 /* now allocate the first part of the string table for
508 * the filenames that we find.
510 idx = strlen(FindData.cFileName)+1;
511 New(1304, p->start, idx, char);
512 if(p->start == NULL) {
513 croak("opendir: malloc failed!\n");
515 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");
535 strcpy(&p->start[idx], FindData.cFileName);
537 * strlwr(&p->start[idx]);
549 /* Readdir just returns the current string pointer and bumps the
550 * string pointer to the nDllExport entry.
556 static int dummy = 0;
559 /* first set up the structure to return */
560 len = strlen(dirp->curr);
561 strcpy(dirp->dirstr.d_name, dirp->curr);
562 dirp->dirstr.d_namlen = len;
565 dirp->dirstr.d_ino = dummy++;
567 /* Now set up for the nDllExport call to readdir */
568 dirp->curr += len + 1;
569 if (dirp->curr >= (dirp->start + dirp->size)) {
573 return &(dirp->dirstr);
579 /* Telldir returns the current string pointer position */
583 return (long) dirp->curr;
587 /* Seekdir moves the string pointer to a previously saved position
591 seekdir(DIR *dirp, long loc)
593 dirp->curr = (char *)loc;
596 /* Rewinddir resets the string pointer to the start */
600 dirp->curr = dirp->start;
603 /* free the memory allocated by opendir */
607 Safefree(dirp->start);
620 * Just pretend that everyone is a superuser. NT will let us know if
621 * we don\'t really have permission to do something.
624 #define ROOT_UID ((uid_t)0)
625 #define ROOT_GID ((gid_t)0)
654 return (auid == ROOT_UID ? 0 : -1);
660 return (agid == ROOT_GID ? 0 : -1);
667 char *buf = getlogin_buffer;
668 DWORD size = sizeof(getlogin_buffer);
669 if (GetUserName(buf,&size))
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;
804 win32_wait(int *status)
809 /* XXX this wait emulation only knows about processes
810 * spawned via win32_spawnvp(P_NOWAIT, ...).
813 DWORD exitcode, waitcode;
815 if (!w32_num_children) {
820 /* if a child exists, wait for it to die */
821 waitcode = WaitForMultipleObjects(w32_num_children,
825 if (waitcode != WAIT_FAILED) {
826 if (waitcode >= WAIT_ABANDONED_0
827 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
828 i = waitcode - WAIT_ABANDONED_0;
830 i = waitcode - WAIT_OBJECT_0;
831 if (GetExitCodeProcess(w32_child_pids[i], &exitcode) ) {
832 CloseHandle(w32_child_pids[i]);
833 *status = (int)((exitcode & 0xff) << 8);
834 retval = (int)w32_child_pids[i];
835 Copy(&w32_child_pids[i+1], &w32_child_pids[i],
836 (w32_num_children-i-1), HANDLE);
843 errno = GetLastError();
849 static UINT timerid = 0;
851 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
853 KillTimer(NULL,timerid);
858 DllExport unsigned int
859 win32_alarm(unsigned int sec)
862 * the 'obvious' implentation is SetTimer() with a callback
863 * which does whatever receiving SIGALRM would do
864 * we cannot use SIGALRM even via raise() as it is not
865 * one of the supported codes in <signal.h>
867 * Snag is unless something is looking at the message queue
868 * nothing happens :-(
872 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
874 croak("Cannot set timer");
880 KillTimer(NULL,timerid);
887 #ifdef HAVE_DES_FCRYPT
888 extern char * des_fcrypt(char *cbuf, const char *txt, const char *salt);
891 win32_crypt(const char *txt, const char *salt)
894 return des_fcrypt(crypt_buffer, txt, salt);
898 #ifdef USE_FIXED_OSFHANDLE
900 EXTERN_C int __cdecl _alloc_osfhnd(void);
901 EXTERN_C int __cdecl _set_osfhnd(int fh, long value);
902 EXTERN_C void __cdecl _lock_fhandle(int);
903 EXTERN_C void __cdecl _unlock_fhandle(int);
904 EXTERN_C void __cdecl _unlock(int);
906 #if (_MSC_VER >= 1000)
908 long osfhnd; /* underlying OS file HANDLE */
909 char osfile; /* attributes of file (e.g., open in text mode?) */
910 char pipech; /* one char buffer for handles opened on pipes */
911 #if defined (_MT) && !defined (DLL_FOR_WIN32S)
913 CRITICAL_SECTION lock;
914 #endif /* defined (_MT) && !defined (DLL_FOR_WIN32S) */
917 EXTERN_C ioinfo * __pioinfo[];
920 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
921 #define _pioinfo(i) (__pioinfo[i >> IOINFO_L2E] + (i & (IOINFO_ARRAY_ELTS - 1)))
922 #define _osfile(i) (_pioinfo(i)->osfile)
924 #else /* (_MSC_VER >= 1000) */
925 extern char _osfile[];
926 #endif /* (_MSC_VER >= 1000) */
928 #define FOPEN 0x01 /* file handle open */
929 #define FAPPEND 0x20 /* file handle opened O_APPEND */
930 #define FDEV 0x40 /* file handle refers to device */
931 #define FTEXT 0x80 /* file handle is in text mode */
933 #define _STREAM_LOCKS 26 /* Table of stream locks */
934 #define _LAST_STREAM_LOCK (_STREAM_LOCKS+_NSTREAM_-1) /* Last stream lock */
935 #define _FH_LOCKS (_LAST_STREAM_LOCK+1) /* Table of fh locks */
938 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
941 * This function allocates a free C Runtime file handle and associates
942 * it with the Win32 HANDLE specified by the first parameter. This is a
943 * temperary fix for WIN95's brain damage GetFileType() error on socket
944 * we just bypass that call for socket
947 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
948 * int flags - flags to associate with C Runtime file handle.
951 * returns index of entry in fh, if successful
952 * return -1, if no free entry is found
956 *******************************************************************************/
959 my_open_osfhandle(long osfhandle, int flags)
962 char fileflags; /* _osfile flags */
964 /* copy relevant flags from second parameter */
968 fileflags |= FAPPEND;
973 /* attempt to allocate a C Runtime file handle */
974 if((fh = _alloc_osfhnd()) == -1) {
975 errno = EMFILE; /* too many open files */
976 _doserrno = 0L; /* not an OS error */
977 return -1; /* return error to caller */
980 /* the file is open. now, set the info in _osfhnd array */
981 _set_osfhnd(fh, osfhandle);
983 fileflags |= FOPEN; /* mark as open */
985 #if (_MSC_VER >= 1000)
986 _osfile(fh) = fileflags; /* set osfile entry */
989 _osfile[fh] = fileflags; /* set osfile entry */
990 _unlock(fh+_FH_LOCKS); /* unlock handle */
993 return fh; /* return handle */
996 #define _open_osfhandle my_open_osfhandle
997 #endif /* USE_FIXED_OSFHANDLE */
999 /* simulate flock by locking a range on the file */
1001 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1002 #define LK_LEN 0xffff0000
1005 win32_flock(int fd, int oper)
1012 croak("flock() unimplemented on this platform");
1015 fh = (HANDLE)_get_osfhandle(fd);
1016 memset(&o, 0, sizeof(o));
1019 case LOCK_SH: /* shared lock */
1020 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1022 case LOCK_EX: /* exclusive lock */
1023 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1025 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1026 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1028 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1029 LK_ERR(LockFileEx(fh,
1030 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1031 0, LK_LEN, 0, &o),i);
1033 case LOCK_UN: /* unlock lock */
1034 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1036 default: /* unknown */
1047 * redirected io subsystem for all XS modules
1060 return (&(_environ));
1063 /* the rest are the remapped stdio routines */
1083 win32_ferror(FILE *fp)
1085 return (ferror(fp));
1090 win32_feof(FILE *fp)
1096 * Since the errors returned by the socket error function
1097 * WSAGetLastError() are not known by the library routine strerror
1098 * we have to roll our own.
1102 win32_strerror(int e)
1104 #ifndef __BORLANDC__ /* Borland intolerance */
1105 extern int sys_nerr;
1109 if(e < 0 || e > sys_nerr) {
1114 if(FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
1115 strerror_buffer, sizeof(strerror_buffer), NULL) == 0)
1116 strcpy(strerror_buffer, "Unknown Error");
1118 return strerror_buffer;
1124 win32_str_os_error(SV *sv, unsigned long dwErr)
1128 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
1129 |FORMAT_MESSAGE_IGNORE_INSERTS
1130 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
1131 dwErr, 0, (char *)&sMsg, 1, NULL);
1133 while (0 < dwLen && isspace(sMsg[--dwLen]))
1135 if ('.' != sMsg[dwLen])
1140 sMsg = LocalAlloc(0, 64/**sizeof(TCHAR)*/);
1141 dwLen = sprintf(sMsg,
1142 "Unknown error #0x%lX (lookup 0x%lX)",
1143 dwErr, GetLastError());
1145 sv_setpvn(sv, sMsg, dwLen);
1151 win32_fprintf(FILE *fp, const char *format, ...)
1154 va_start(marker, format); /* Initialize variable arguments. */
1156 return (vfprintf(fp, format, marker));
1160 win32_printf(const char *format, ...)
1163 va_start(marker, format); /* Initialize variable arguments. */
1165 return (vprintf(format, marker));
1169 win32_vfprintf(FILE *fp, const char *format, va_list args)
1171 return (vfprintf(fp, format, args));
1175 win32_vprintf(const char *format, va_list args)
1177 return (vprintf(format, args));
1181 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
1183 return fread(buf, size, count, fp);
1187 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
1189 return fwrite(buf, size, count, fp);
1193 win32_fopen(const char *filename, const char *mode)
1195 if (stricmp(filename, "/dev/null")==0)
1196 return fopen("NUL", mode);
1197 return fopen(filename, mode);
1200 #ifndef USE_SOCKETS_AS_HANDLES
1202 #define fdopen my_fdopen
1206 win32_fdopen( int handle, const char *mode)
1208 return fdopen(handle, (char *) mode);
1212 win32_freopen( const char *path, const char *mode, FILE *stream)
1214 if (stricmp(path, "/dev/null")==0)
1215 return freopen("NUL", mode, stream);
1216 return freopen(path, mode, stream);
1220 win32_fclose(FILE *pf)
1222 return my_fclose(pf); /* defined in win32sck.c */
1226 win32_fputs(const char *s,FILE *pf)
1228 return fputs(s, pf);
1232 win32_fputc(int c,FILE *pf)
1238 win32_ungetc(int c,FILE *pf)
1240 return ungetc(c,pf);
1244 win32_getc(FILE *pf)
1250 win32_fileno(FILE *pf)
1256 win32_clearerr(FILE *pf)
1263 win32_fflush(FILE *pf)
1269 win32_ftell(FILE *pf)
1275 win32_fseek(FILE *pf,long offset,int origin)
1277 return fseek(pf, offset, origin);
1281 win32_fgetpos(FILE *pf,fpos_t *p)
1283 return fgetpos(pf, p);
1287 win32_fsetpos(FILE *pf,const fpos_t *p)
1289 return fsetpos(pf, p);
1293 win32_rewind(FILE *pf)
1313 win32_fstat(int fd,struct stat *sbufptr)
1315 return fstat(fd,sbufptr);
1319 win32_pipe(int *pfd, unsigned int size, int mode)
1321 return _pipe(pfd, size, mode);
1325 win32_popen(const char *command, const char *mode)
1327 return _popen(command, mode);
1331 win32_pclose(FILE *pf)
1337 win32_setmode(int fd, int mode)
1339 return setmode(fd, mode);
1343 win32_lseek(int fd, long offset, int origin)
1345 return lseek(fd, offset, origin);
1355 win32_open(const char *path, int flag, ...)
1361 pmode = va_arg(ap, int);
1364 if (stricmp(path, "/dev/null")==0)
1365 return open("NUL", flag, pmode);
1366 return open(path,flag,pmode);
1388 win32_dup2(int fd1,int fd2)
1390 return dup2(fd1,fd2);
1394 win32_read(int fd, void *buf, unsigned int cnt)
1396 return read(fd, buf, cnt);
1400 win32_write(int fd, const void *buf, unsigned int cnt)
1402 return write(fd, buf, cnt);
1406 win32_mkdir(const char *dir, int mode)
1408 return mkdir(dir); /* just ignore mode */
1412 win32_rmdir(const char *dir)
1418 win32_chdir(const char *dir)
1424 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
1428 status = spawnvp(mode, cmdname, (char * const *) argv);
1429 #ifndef __BORLANDC__
1430 /* XXX For the P_NOWAIT case, Borland RTL returns pinfo.dwProcessId
1431 * while VC RTL returns pinfo.hProcess. For purposes of the custom
1432 * implementation of win32_wait(), we assume the latter.
1434 if (mode == P_NOWAIT && status >= 0)
1435 w32_child_pids[w32_num_children++] = (HANDLE)status;
1441 win32_execvp(const char *cmdname, const char *const *argv)
1443 return execvp(cmdname, (char *const *)argv);
1447 win32_perror(const char *str)
1453 win32_setbuf(FILE *pf, char *buf)
1459 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
1461 return setvbuf(pf, buf, type, size);
1465 win32_flushall(void)
1471 win32_fcloseall(void)
1477 win32_fgets(char *s, int n, FILE *pf)
1479 return fgets(s, n, pf);
1489 win32_fgetc(FILE *pf)
1495 win32_putc(int c, FILE *pf)
1501 win32_puts(const char *s)
1513 win32_putchar(int c)
1520 #ifndef USE_PERL_SBRK
1522 static char *committed = NULL;
1523 static char *base = NULL;
1524 static char *reserved = NULL;
1525 static char *brk = NULL;
1526 static DWORD pagesize = 0;
1527 static DWORD allocsize = 0;
1535 GetSystemInfo(&info);
1536 /* Pretend page size is larger so we don't perpetually
1537 * call the OS to commit just one page ...
1539 pagesize = info.dwPageSize << 3;
1540 allocsize = info.dwAllocationGranularity;
1542 /* This scheme fails eventually if request for contiguous
1543 * block is denied so reserve big blocks - this is only
1544 * address space not memory ...
1546 if (brk+need >= reserved)
1548 DWORD size = 64*1024*1024;
1550 if (committed && reserved && committed < reserved)
1552 /* Commit last of previous chunk cannot span allocations */
1553 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
1555 committed = reserved;
1557 /* Reserve some (more) space
1558 * Note this is a little sneaky, 1st call passes NULL as reserved
1559 * so lets system choose where we start, subsequent calls pass
1560 * the old end address so ask for a contiguous block
1562 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
1565 reserved = addr+size;
1580 if (brk > committed)
1582 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
1583 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
1598 win32_malloc(size_t size)
1600 return malloc(size);
1604 win32_calloc(size_t numitems, size_t size)
1606 return calloc(numitems,size);
1610 win32_realloc(void *block, size_t size)
1612 return realloc(block,size);
1616 win32_free(void *block)
1623 win32_open_osfhandle(long handle, int flags)
1625 return _open_osfhandle(handle, flags);
1629 win32_get_osfhandle(int fd)
1631 return _get_osfhandle(fd);
1642 SV *sv = sv_newmortal();
1643 /* Make one call with zero size - return value is required size */
1644 DWORD len = GetCurrentDirectory((DWORD)0,NULL);
1645 SvUPGRADE(sv,SVt_PV);
1647 SvCUR(sv) = GetCurrentDirectory((DWORD) SvLEN(sv), SvPVX(sv));
1650 * then it worked, set PV valid,
1651 * else leave it 'undef'
1665 croak("usage: Win32::SetCurrentDirectory($cwd)");
1666 if (SetCurrentDirectory(SvPV(ST(0),na)))
1673 XS(w32_GetNextAvailDrive)
1677 char root[] = "_:\\";
1680 if (GetDriveType(root) == 1) {
1689 XS(w32_GetLastError)
1692 XSRETURN_IV(GetLastError());
1699 char *name = getlogin_buffer;
1700 DWORD size = sizeof(getlogin_buffer);
1701 if (GetUserName(name,&size)) {
1702 /* size includes NULL */
1703 ST(0) = sv_2mortal(newSVpv(name,size-1));
1713 char name[MAX_COMPUTERNAME_LENGTH+1];
1714 DWORD size = sizeof(name);
1715 if (GetComputerName(name,&size)) {
1716 /* size does NOT include NULL :-( */
1717 ST(0) = sv_2mortal(newSVpv(name,size));
1729 DWORD size = sizeof(name);
1730 if (GetUserName(name,&size)) {
1732 DWORD sidlen = sizeof(sid);
1734 DWORD dnamelen = sizeof(dname);
1736 if (LookupAccountName(NULL, name, &sid, &sidlen,
1737 dname, &dnamelen, &snu)) {
1738 XSRETURN_PV(dname); /* all that for this */
1749 DWORD flags, filecomplen;
1750 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
1751 &flags, fsname, sizeof(fsname))) {
1752 if (GIMME == G_ARRAY) {
1753 XPUSHs(sv_2mortal(newSVpv(fsname,0)));
1754 XPUSHs(sv_2mortal(newSViv(flags)));
1755 XPUSHs(sv_2mortal(newSViv(filecomplen)));
1759 XSRETURN_PV(fsname);
1765 XS(w32_GetOSVersion)
1768 OSVERSIONINFO osver;
1770 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1771 if (GetVersionEx(&osver)) {
1772 XPUSHs(newSVpv(osver.szCSDVersion, 0));
1773 XPUSHs(newSViv(osver.dwMajorVersion));
1774 XPUSHs(newSViv(osver.dwMinorVersion));
1775 XPUSHs(newSViv(osver.dwBuildNumber));
1776 XPUSHs(newSViv(osver.dwPlatformId));
1787 XSRETURN_IV(IsWinNT());
1794 XSRETURN_IV(IsWin95());
1798 XS(w32_FormatMessage)
1805 croak("usage: Win32::FormatMessage($errno)");
1807 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
1808 &source, SvIV(ST(0)), 0,
1809 msgbuf, sizeof(msgbuf)-1, NULL))
1810 XSRETURN_PV(msgbuf);
1820 PROCESS_INFORMATION stProcInfo;
1821 STARTUPINFO stStartInfo;
1822 BOOL bSuccess = FALSE;
1825 croak("usage: Win32::Spawn($cmdName, $args, $PID)");
1827 cmd = SvPV(ST(0),na);
1828 args = SvPV(ST(1), na);
1830 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
1831 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
1832 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
1833 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
1836 cmd, /* Image path */
1837 args, /* Arguments for command line */
1838 NULL, /* Default process security */
1839 NULL, /* Default thread security */
1840 FALSE, /* Must be TRUE to use std handles */
1841 NORMAL_PRIORITY_CLASS, /* No special scheduling */
1842 NULL, /* Inherit our environment block */
1843 NULL, /* Inherit our currrent directory */
1844 &stStartInfo, /* -> Startup info */
1845 &stProcInfo)) /* <- Process info (if OK) */
1847 CloseHandle(stProcInfo.hThread);/* library source code does this. */
1848 sv_setiv(ST(2), stProcInfo.dwProcessId);
1851 XSRETURN_IV(bSuccess);
1855 XS(w32_GetTickCount)
1858 XSRETURN_IV(GetTickCount());
1862 XS(w32_GetShortPathName)
1869 croak("usage: Win32::GetShortPathName($longPathName)");
1871 shortpath = sv_mortalcopy(ST(0));
1872 SvUPGRADE(shortpath, SVt_PV);
1873 /* src == target is allowed */
1875 len = GetShortPathName(SvPVX(shortpath),
1878 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
1880 SvCUR_set(shortpath,len);
1889 Perl_init_os_extras()
1891 char *file = __FILE__;
1894 /* XXX should be removed after checking with Nick */
1895 newXS("Win32::GetCurrentDirectory", w32_GetCwd, file);
1897 /* these names are Activeware compatible */
1898 newXS("Win32::GetCwd", w32_GetCwd, file);
1899 newXS("Win32::SetCwd", w32_SetCwd, file);
1900 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
1901 newXS("Win32::GetLastError", w32_GetLastError, file);
1902 newXS("Win32::LoginName", w32_LoginName, file);
1903 newXS("Win32::NodeName", w32_NodeName, file);
1904 newXS("Win32::DomainName", w32_DomainName, file);
1905 newXS("Win32::FsType", w32_FsType, file);
1906 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
1907 newXS("Win32::IsWinNT", w32_IsWinNT, file);
1908 newXS("Win32::IsWin95", w32_IsWin95, file);
1909 newXS("Win32::FormatMessage", w32_FormatMessage, file);
1910 newXS("Win32::Spawn", w32_Spawn, file);
1911 newXS("Win32::GetTickCount", w32_GetTickCount, file);
1912 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
1914 /* XXX Bloat Alert! The following Activeware preloads really
1915 * ought to be part of Win32::Sys::*, so they're not included
1918 /* LookupAccountName
1920 * InitiateSystemShutdown
1921 * AbortSystemShutdown
1922 * ExpandEnvrironmentStrings
1927 Perl_win32_init(int *argcp, char ***argvp)
1929 /* Disable floating point errors, Perl will trap the ones we
1930 * care about. VC++ RTL defaults to switching these off
1931 * already, but the Borland RTL doesn't. Since we don't
1932 * want to be at the vendor's whim on the default, we set
1933 * it explicitly here.
1935 #if !defined(_ALPHA_) && !defined(__GNUC__)
1936 _control87(MCW_EM, MCW_EM);
1941 #ifdef USE_BINMODE_SCRIPTS
1944 win32_strip_return(SV *sv)
1946 char *s = SvPVX(sv);
1947 char *e = s+SvCUR(sv);
1951 if (*s == '\r' && s[1] == '\n')
1961 SvCUR_set(sv,d-SvPVX(sv));