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 char * get_shell(void);
52 static int do_spawn2(char *cmd, int exectype);
53 static BOOL has_redirection(char *ptr);
54 static long filetime_to_clock(PFILETIME ft);
56 BOOL w32_env_probed = FALSE;
57 DWORD w32_platform = (DWORD)-1;
58 char w32_shellpath[MAX_PATH+1];
59 char w32_perllib_root[MAX_PATH+1];
60 HANDLE w32_perldll_handle = INVALID_HANDLE_VALUE;
62 long w32_num_children = 0;
63 HANDLE w32_child_pids[MAXIMUM_WAIT_OBJECTS];
67 # ifdef USE_DECLSPEC_THREAD
68 __declspec(thread) char strerror_buffer[512];
69 __declspec(thread) char getlogin_buffer[128];
70 # ifdef HAVE_DES_FCRYPT
71 __declspec(thread) char crypt_buffer[30];
74 # define strerror_buffer (thr->i.Wstrerror_buffer)
75 # define getlogin_buffer (thr->i.Wgetlogin_buffer)
76 # define crypt_buffer (thr->i.Wcrypt_buffer)
79 char strerror_buffer[512];
80 char getlogin_buffer[128];
81 # ifdef HAVE_DES_FCRYPT
82 char crypt_buffer[30];
88 return (os_id() == VER_PLATFORM_WIN32_WINDOWS);
93 return (os_id() == VER_PLATFORM_WIN32_NT);
97 win32_perllib_path(char *sfx,...)
102 GetModuleFileName((w32_perldll_handle == INVALID_HANDLE_VALUE)
103 ? GetModuleHandle(NULL)
104 : w32_perldll_handle,
106 sizeof(w32_perllib_root));
107 *(end = strrchr(w32_perllib_root, '\\')) = '\0';
108 if (stricmp(end-4,"\\bin") == 0)
115 sfx = va_arg(ap,char *);
118 return (w32_perllib_root);
123 has_redirection(char *ptr)
129 * Scan string looking for redirection (< or >) or pipe
130 * characters (|) that are not in a quoted string
160 /* since the current process environment is being updated in util.c
161 * the library functions will get the correct environment
164 my_popen(char *cmd, char *mode)
167 #define fixcmd(x) { \
168 char *pspace = strchr((x),' '); \
171 while (p < pspace) { \
182 #ifdef __BORLANDC__ /* workaround a Borland stdio bug */
183 win32_fflush(stdout);
184 win32_fflush(stderr);
186 return win32_popen(cmd, mode);
190 my_pclose(PerlIO *fp)
192 return win32_pclose(fp);
198 static OSVERSIONINFO osver;
200 if (osver.dwPlatformId != w32_platform) {
201 memset(&osver, 0, sizeof(OSVERSIONINFO));
202 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
203 GetVersionEx(&osver);
204 w32_platform = osver.dwPlatformId;
206 return (w32_platform);
209 /* XXX PERL5SHELL must be tokenized to allow switches to be passed */
213 if (!w32_env_probed) {
214 char* defaultshell = (IsWinNT() ? "cmd.exe" : "command.com");
215 /* we don't use COMSPEC here for two reasons:
216 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
217 * uncontrolled unportability of the ensuing scripts.
218 * 2. PERL5SHELL could be set to a shell that may not be fit for
219 * interactive use (which is what most programs look in COMSPEC
222 char *usershell = getenv("PERL5SHELL");
224 w32_env_probed = TRUE;
225 strcpy(w32_shellpath, usershell ? usershell : defaultshell);
227 return w32_shellpath;
231 do_aspawn(void *vreally, void **vmark, void **vsp)
233 SV *really = (SV*)vreally;
234 SV **mark = (SV**)vmark;
245 New(1301, argv, (sp - mark) + 4, char*);
247 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
252 while(++mark <= sp) {
253 if (*mark && (str = SvPV(*mark, na)))
260 status = win32_spawnvp(flag,
261 (really ? SvPV(really,na) : argv[0]),
262 (const char* const*)argv);
264 if (status < 0 && errno == ENOEXEC) {
265 /* possible shell-builtin, invoke with shell */
268 argv[index+sh_items] = argv[index];
270 argv[--sh_items] = "/x/c"; /* always enable command extensions */
272 argv[--sh_items] = "/c";
273 argv[--sh_items] = get_shell();
275 status = win32_spawnvp(flag,
276 (really ? SvPV(really,na) : argv[0]),
277 (const char* const*)argv);
283 warn("Can't spawn \"%s\": %s", argv[0], strerror(errno));
286 else if (flag != P_NOWAIT)
288 return (statusvalue = status);
292 do_spawn2(char *cmd, int exectype)
298 BOOL needToTry = TRUE;
301 /* Save an extra exec if possible. See if there are shell
302 * metacharacters in it */
303 if(!has_redirection(cmd)) {
304 New(1301,argv, strlen(cmd) / 2 + 2, char*);
305 New(1302,cmd2, strlen(cmd) + 1, char);
308 for (s = cmd2; *s;) {
309 while (*s && isspace(*s))
313 while(*s && !isspace(*s))
322 status = win32_spawnvp(P_WAIT, argv[0],
323 (const char* const*)argv);
325 case EXECF_SPAWN_NOWAIT:
326 status = win32_spawnvp(P_NOWAIT, argv[0],
327 (const char* const*)argv);
330 status = win32_execvp(argv[0], (const char* const*)argv);
333 if (status != -1 || errno == 0)
342 argv[i++] = get_shell();
351 status = win32_spawnvp(P_WAIT, argv[0],
352 (const char* const*)argv);
354 case EXECF_SPAWN_NOWAIT:
355 status = win32_spawnvp(P_NOWAIT, argv[0],
356 (const char* const*)argv);
359 status = win32_execvp(argv[0], (const char* const*)argv);
365 warn("Can't %s \"%s\": %s",
366 (exectype == EXECF_EXEC ? "exec" : "spawn"),
367 argv[0], strerror(errno));
370 else if (exectype != EXECF_SPAWN_NOWAIT)
372 return (statusvalue = status);
378 return do_spawn2(cmd, EXECF_SPAWN);
382 do_spawn_nowait(char *cmd)
384 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
390 do_spawn2(cmd, EXECF_EXEC);
397 /* The idea here is to read all the directory names into a string table
398 * (separated by nulls) and when one of the other dir functions is called
399 * return the pointer to the current file name.
402 opendir(char *filename)
407 char scannamespc[PATHLEN];
408 char *scanname = scannamespc;
410 WIN32_FIND_DATA FindData;
412 /* char root[_MAX_PATH];*/
413 /* char volname[_MAX_PATH];*/
414 /* DWORD serial, maxname, flags;*/
418 /* check to see if filename is a directory */
419 if (win32_stat(filename, &sbuf) < 0 || (sbuf.st_mode & S_IFDIR) == 0) {
423 /* get the file system characteristics */
424 /* if(GetFullPathName(filename, MAX_PATH, root, &dummy)) {
425 * if(dummy = strchr(root, '\\'))
427 * if(GetVolumeInformation(root, volname, MAX_PATH, &serial,
428 * &maxname, &flags, 0, 0)) {
429 * downcase = !(flags & FS_CASE_IS_PRESERVED);
436 /* Get us a DIR structure */
437 Newz(1303, p, 1, DIR);
441 /* Create the search pattern */
442 strcpy(scanname, filename);
444 if(index("/\\", *(scanname + strlen(scanname) - 1)) == NULL)
445 strcat(scanname, "/*");
447 strcat(scanname, "*");
449 /* do the FindFirstFile call */
450 fh = FindFirstFile(scanname, &FindData);
451 if(fh == INVALID_HANDLE_VALUE) {
455 /* now allocate the first part of the string table for
456 * the filenames that we find.
458 idx = strlen(FindData.cFileName)+1;
459 New(1304, p->start, idx, char);
460 if(p->start == NULL) {
461 croak("opendir: malloc failed!\n");
463 strcpy(p->start, FindData.cFileName);
469 /* loop finding all the files that match the wildcard
470 * (which should be all of them in this directory!).
471 * the variable idx should point one past the null terminator
472 * of the previous string found.
474 while (FindNextFile(fh, &FindData)) {
475 len = strlen(FindData.cFileName);
476 /* bump the string table size by enough for the
477 * new name and it's null terminator
479 Renew(p->start, idx+len+1, char);
480 if(p->start == NULL) {
481 croak("opendir: malloc failed!\n");
483 strcpy(&p->start[idx], FindData.cFileName);
485 * strlwr(&p->start[idx]);
497 /* Readdir just returns the current string pointer and bumps the
498 * string pointer to the nDllExport entry.
504 static int dummy = 0;
507 /* first set up the structure to return */
508 len = strlen(dirp->curr);
509 strcpy(dirp->dirstr.d_name, dirp->curr);
510 dirp->dirstr.d_namlen = len;
513 dirp->dirstr.d_ino = dummy++;
515 /* Now set up for the nDllExport call to readdir */
516 dirp->curr += len + 1;
517 if (dirp->curr >= (dirp->start + dirp->size)) {
521 return &(dirp->dirstr);
527 /* Telldir returns the current string pointer position */
531 return (long) dirp->curr;
535 /* Seekdir moves the string pointer to a previously saved position
539 seekdir(DIR *dirp, long loc)
541 dirp->curr = (char *)loc;
544 /* Rewinddir resets the string pointer to the start */
548 dirp->curr = dirp->start;
551 /* free the memory allocated by opendir */
555 Safefree(dirp->start);
568 * Just pretend that everyone is a superuser. NT will let us know if
569 * we don\'t really have permission to do something.
572 #define ROOT_UID ((uid_t)0)
573 #define ROOT_GID ((gid_t)0)
602 return (auid == ROOT_UID ? 0 : -1);
608 return (agid == ROOT_GID ? 0 : -1);
615 char *buf = getlogin_buffer;
616 DWORD size = sizeof(getlogin_buffer);
617 if (GetUserName(buf,&size))
626 kill(int pid, int sig)
628 HANDLE hProcess= OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
630 if (hProcess == NULL) {
631 croak("kill process failed!\n");
634 if (!TerminateProcess(hProcess, sig))
635 croak("kill process failed!\n");
636 CloseHandle(hProcess);
645 DllExport unsigned int
646 win32_sleep(unsigned int t)
653 win32_stat(const char *path, struct stat *buffer)
656 const char *p = path;
657 int l = strlen(path);
661 switch(path[l - 1]) {
664 if (path[l - 2] != ':') {
665 strncpy(t, path, l - 1);
671 res = stat(p,buffer);
674 if (S_ISDIR(buffer->st_mode))
675 buffer->st_mode |= S_IWRITE | S_IEXEC;
676 else if (S_ISREG(buffer->st_mode)) {
677 if (l >= 4 && path[l-4] == '.') {
678 const char *e = path + l - 3;
679 if (strnicmp(e,"exe",3)
680 && strnicmp(e,"bat",3)
681 && strnicmp(e,"com",3)
682 && (IsWin95() || strnicmp(e,"cmd",3)))
683 buffer->st_mode &= ~S_IEXEC;
685 buffer->st_mode |= S_IEXEC;
688 buffer->st_mode &= ~S_IEXEC;
695 #ifndef USE_WIN32_RTL_ENV
698 win32_getenv(const char *name)
700 static char *curitem = Nullch;
701 static DWORD curlen = 512;
704 New(1305,curitem,curlen,char);
705 if (!(needlen = GetEnvironmentVariable(name,curitem,curlen)))
707 while (needlen > curlen) {
708 Renew(curitem,needlen,char);
710 needlen = GetEnvironmentVariable(name,curitem,curlen);
718 filetime_to_clock(PFILETIME ft)
720 __int64 qw = ft->dwHighDateTime;
722 qw |= ft->dwLowDateTime;
723 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
728 win32_times(struct tms *timebuf)
733 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
735 timebuf->tms_utime = filetime_to_clock(&user);
736 timebuf->tms_stime = filetime_to_clock(&kernel);
737 timebuf->tms_cutime = 0;
738 timebuf->tms_cstime = 0;
741 /* That failed - e.g. Win95 fallback to clock() */
743 timebuf->tms_utime = t;
744 timebuf->tms_stime = 0;
745 timebuf->tms_cutime = 0;
746 timebuf->tms_cstime = 0;
752 win32_wait(int *status)
757 /* XXX this wait emulation only knows about processes
758 * spawned via win32_spawnvp(P_NOWAIT, ...).
761 DWORD exitcode, waitcode;
763 if (!w32_num_children) {
768 /* if a child exists, wait for it to die */
769 waitcode = WaitForMultipleObjects(w32_num_children,
773 if (waitcode != WAIT_FAILED) {
774 if (waitcode >= WAIT_ABANDONED_0
775 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
776 i = waitcode - WAIT_ABANDONED_0;
778 i = waitcode - WAIT_OBJECT_0;
779 if (GetExitCodeProcess(w32_child_pids[i], &exitcode) ) {
780 CloseHandle(w32_child_pids[i]);
781 *status = (int)((exitcode & 0xff) << 8);
782 retval = (int)w32_child_pids[i];
783 Copy(&w32_child_pids[i+1], &w32_child_pids[i],
784 (w32_num_children-i-1), HANDLE);
791 errno = GetLastError();
797 static UINT timerid = 0;
799 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
801 KillTimer(NULL,timerid);
806 DllExport unsigned int
807 win32_alarm(unsigned int sec)
810 * the 'obvious' implentation is SetTimer() with a callback
811 * which does whatever receiving SIGALRM would do
812 * we cannot use SIGALRM even via raise() as it is not
813 * one of the supported codes in <signal.h>
815 * Snag is unless something is looking at the message queue
816 * nothing happens :-(
820 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
822 croak("Cannot set timer");
828 KillTimer(NULL,timerid);
835 #ifdef HAVE_DES_FCRYPT
836 extern char * des_fcrypt(char *cbuf, const char *txt, const char *salt);
839 win32_crypt(const char *txt, const char *salt)
842 return des_fcrypt(crypt_buffer, txt, salt);
846 #ifdef USE_FIXED_OSFHANDLE
848 EXTERN_C int __cdecl _alloc_osfhnd(void);
849 EXTERN_C int __cdecl _set_osfhnd(int fh, long value);
850 EXTERN_C void __cdecl _lock_fhandle(int);
851 EXTERN_C void __cdecl _unlock_fhandle(int);
852 EXTERN_C void __cdecl _unlock(int);
854 #if (_MSC_VER >= 1000)
856 long osfhnd; /* underlying OS file HANDLE */
857 char osfile; /* attributes of file (e.g., open in text mode?) */
858 char pipech; /* one char buffer for handles opened on pipes */
859 #if defined (_MT) && !defined (DLL_FOR_WIN32S)
861 CRITICAL_SECTION lock;
862 #endif /* defined (_MT) && !defined (DLL_FOR_WIN32S) */
865 EXTERN_C ioinfo * __pioinfo[];
868 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
869 #define _pioinfo(i) (__pioinfo[i >> IOINFO_L2E] + (i & (IOINFO_ARRAY_ELTS - 1)))
870 #define _osfile(i) (_pioinfo(i)->osfile)
872 #else /* (_MSC_VER >= 1000) */
873 extern char _osfile[];
874 #endif /* (_MSC_VER >= 1000) */
876 #define FOPEN 0x01 /* file handle open */
877 #define FAPPEND 0x20 /* file handle opened O_APPEND */
878 #define FDEV 0x40 /* file handle refers to device */
879 #define FTEXT 0x80 /* file handle is in text mode */
881 #define _STREAM_LOCKS 26 /* Table of stream locks */
882 #define _LAST_STREAM_LOCK (_STREAM_LOCKS+_NSTREAM_-1) /* Last stream lock */
883 #define _FH_LOCKS (_LAST_STREAM_LOCK+1) /* Table of fh locks */
886 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
889 * This function allocates a free C Runtime file handle and associates
890 * it with the Win32 HANDLE specified by the first parameter. This is a
891 * temperary fix for WIN95's brain damage GetFileType() error on socket
892 * we just bypass that call for socket
895 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
896 * int flags - flags to associate with C Runtime file handle.
899 * returns index of entry in fh, if successful
900 * return -1, if no free entry is found
904 *******************************************************************************/
907 my_open_osfhandle(long osfhandle, int flags)
910 char fileflags; /* _osfile flags */
912 /* copy relevant flags from second parameter */
916 fileflags |= FAPPEND;
921 /* attempt to allocate a C Runtime file handle */
922 if((fh = _alloc_osfhnd()) == -1) {
923 errno = EMFILE; /* too many open files */
924 _doserrno = 0L; /* not an OS error */
925 return -1; /* return error to caller */
928 /* the file is open. now, set the info in _osfhnd array */
929 _set_osfhnd(fh, osfhandle);
931 fileflags |= FOPEN; /* mark as open */
933 #if (_MSC_VER >= 1000)
934 _osfile(fh) = fileflags; /* set osfile entry */
937 _osfile[fh] = fileflags; /* set osfile entry */
938 _unlock(fh+_FH_LOCKS); /* unlock handle */
941 return fh; /* return handle */
944 #define _open_osfhandle my_open_osfhandle
945 #endif /* USE_FIXED_OSFHANDLE */
947 /* simulate flock by locking a range on the file */
949 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
950 #define LK_LEN 0xffff0000
953 win32_flock(int fd, int oper)
960 croak("flock() unimplemented on this platform");
963 fh = (HANDLE)_get_osfhandle(fd);
964 memset(&o, 0, sizeof(o));
967 case LOCK_SH: /* shared lock */
968 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
970 case LOCK_EX: /* exclusive lock */
971 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
973 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
974 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
976 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
977 LK_ERR(LockFileEx(fh,
978 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
979 0, LK_LEN, 0, &o),i);
981 case LOCK_UN: /* unlock lock */
982 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
984 default: /* unknown */
995 * redirected io subsystem for all XS modules
1008 return (&(_environ));
1011 /* the rest are the remapped stdio routines */
1031 win32_ferror(FILE *fp)
1033 return (ferror(fp));
1038 win32_feof(FILE *fp)
1044 * Since the errors returned by the socket error function
1045 * WSAGetLastError() are not known by the library routine strerror
1046 * we have to roll our own.
1050 win32_strerror(int e)
1052 #ifndef __BORLANDC__ /* Borland intolerance */
1053 extern int sys_nerr;
1057 if(e < 0 || e > sys_nerr) {
1062 if(FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
1063 strerror_buffer, sizeof(strerror_buffer), NULL) == 0)
1064 strcpy(strerror_buffer, "Unknown Error");
1066 return strerror_buffer;
1072 win32_fprintf(FILE *fp, const char *format, ...)
1075 va_start(marker, format); /* Initialize variable arguments. */
1077 return (vfprintf(fp, format, marker));
1081 win32_printf(const char *format, ...)
1084 va_start(marker, format); /* Initialize variable arguments. */
1086 return (vprintf(format, marker));
1090 win32_vfprintf(FILE *fp, const char *format, va_list args)
1092 return (vfprintf(fp, format, args));
1096 win32_vprintf(const char *format, va_list args)
1098 return (vprintf(format, args));
1102 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
1104 return fread(buf, size, count, fp);
1108 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
1110 return fwrite(buf, size, count, fp);
1114 win32_fopen(const char *filename, const char *mode)
1116 if (stricmp(filename, "/dev/null")==0)
1117 return fopen("NUL", mode);
1118 return fopen(filename, mode);
1121 #ifndef USE_SOCKETS_AS_HANDLES
1123 #define fdopen my_fdopen
1127 win32_fdopen( int handle, const char *mode)
1129 return fdopen(handle, (char *) mode);
1133 win32_freopen( const char *path, const char *mode, FILE *stream)
1135 if (stricmp(path, "/dev/null")==0)
1136 return freopen("NUL", mode, stream);
1137 return freopen(path, mode, stream);
1141 win32_fclose(FILE *pf)
1143 return my_fclose(pf); /* defined in win32sck.c */
1147 win32_fputs(const char *s,FILE *pf)
1149 return fputs(s, pf);
1153 win32_fputc(int c,FILE *pf)
1159 win32_ungetc(int c,FILE *pf)
1161 return ungetc(c,pf);
1165 win32_getc(FILE *pf)
1171 win32_fileno(FILE *pf)
1177 win32_clearerr(FILE *pf)
1184 win32_fflush(FILE *pf)
1190 win32_ftell(FILE *pf)
1196 win32_fseek(FILE *pf,long offset,int origin)
1198 return fseek(pf, offset, origin);
1202 win32_fgetpos(FILE *pf,fpos_t *p)
1204 return fgetpos(pf, p);
1208 win32_fsetpos(FILE *pf,const fpos_t *p)
1210 return fsetpos(pf, p);
1214 win32_rewind(FILE *pf)
1234 win32_fstat(int fd,struct stat *sbufptr)
1236 return fstat(fd,sbufptr);
1240 win32_pipe(int *pfd, unsigned int size, int mode)
1242 return _pipe(pfd, size, mode);
1246 win32_popen(const char *command, const char *mode)
1248 return _popen(command, mode);
1252 win32_pclose(FILE *pf)
1258 win32_setmode(int fd, int mode)
1260 return setmode(fd, mode);
1264 win32_lseek(int fd, long offset, int origin)
1266 return lseek(fd, offset, origin);
1276 win32_open(const char *path, int flag, ...)
1282 pmode = va_arg(ap, int);
1285 if (stricmp(path, "/dev/null")==0)
1286 return open("NUL", flag, pmode);
1287 return open(path,flag,pmode);
1309 win32_dup2(int fd1,int fd2)
1311 return dup2(fd1,fd2);
1315 win32_read(int fd, void *buf, unsigned int cnt)
1317 return read(fd, buf, cnt);
1321 win32_write(int fd, const void *buf, unsigned int cnt)
1323 return write(fd, buf, cnt);
1327 win32_mkdir(const char *dir, int mode)
1329 return mkdir(dir); /* just ignore mode */
1333 win32_rmdir(const char *dir)
1339 win32_chdir(const char *dir)
1345 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
1349 status = spawnvp(mode, cmdname, (char * const *) argv);
1350 #ifndef __BORLANDC__
1351 /* XXX For the P_NOWAIT case, Borland RTL returns pinfo.dwProcessId
1352 * while VC RTL returns pinfo.hProcess. For purposes of the custom
1353 * implementation of win32_wait(), we assume the latter.
1355 if (mode == P_NOWAIT && status >= 0)
1356 w32_child_pids[w32_num_children++] = (HANDLE)status;
1362 win32_execvp(const char *cmdname, const char *const *argv)
1364 return execvp(cmdname, (char *const *)argv);
1368 win32_perror(const char *str)
1374 win32_setbuf(FILE *pf, char *buf)
1380 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
1382 return setvbuf(pf, buf, type, size);
1386 win32_flushall(void)
1392 win32_fcloseall(void)
1398 win32_fgets(char *s, int n, FILE *pf)
1400 return fgets(s, n, pf);
1410 win32_fgetc(FILE *pf)
1416 win32_putc(int c, FILE *pf)
1422 win32_puts(const char *s)
1434 win32_putchar(int c)
1441 #ifndef USE_PERL_SBRK
1443 static char *committed = NULL;
1444 static char *base = NULL;
1445 static char *reserved = NULL;
1446 static char *brk = NULL;
1447 static DWORD pagesize = 0;
1448 static DWORD allocsize = 0;
1456 GetSystemInfo(&info);
1457 /* Pretend page size is larger so we don't perpetually
1458 * call the OS to commit just one page ...
1460 pagesize = info.dwPageSize << 3;
1461 allocsize = info.dwAllocationGranularity;
1463 /* This scheme fails eventually if request for contiguous
1464 * block is denied so reserve big blocks - this is only
1465 * address space not memory ...
1467 if (brk+need >= reserved)
1469 DWORD size = 64*1024*1024;
1471 if (committed && reserved && committed < reserved)
1473 /* Commit last of previous chunk cannot span allocations */
1474 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
1476 committed = reserved;
1478 /* Reserve some (more) space
1479 * Note this is a little sneaky, 1st call passes NULL as reserved
1480 * so lets system choose where we start, subsequent calls pass
1481 * the old end address so ask for a contiguous block
1483 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
1486 reserved = addr+size;
1501 if (brk > committed)
1503 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
1504 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
1519 win32_malloc(size_t size)
1521 return malloc(size);
1525 win32_calloc(size_t numitems, size_t size)
1527 return calloc(numitems,size);
1531 win32_realloc(void *block, size_t size)
1533 return realloc(block,size);
1537 win32_free(void *block)
1544 win32_open_osfhandle(long handle, int flags)
1546 return _open_osfhandle(handle, flags);
1550 win32_get_osfhandle(int fd)
1552 return _get_osfhandle(fd);
1563 SV *sv = sv_newmortal();
1564 /* Make one call with zero size - return value is required size */
1565 DWORD len = GetCurrentDirectory((DWORD)0,NULL);
1566 SvUPGRADE(sv,SVt_PV);
1568 SvCUR(sv) = GetCurrentDirectory((DWORD) SvLEN(sv), SvPVX(sv));
1571 * then it worked, set PV valid,
1572 * else leave it 'undef'
1586 croak("usage: Win32::SetCurrentDirectory($cwd)");
1587 if (SetCurrentDirectory(SvPV(ST(0),na)))
1594 XS(w32_GetNextAvailDrive)
1598 char root[] = "_:\\";
1601 if (GetDriveType(root) == 1) {
1610 XS(w32_GetLastError)
1613 XSRETURN_IV(GetLastError());
1620 char *name = getlogin_buffer;
1621 DWORD size = sizeof(getlogin_buffer);
1622 if (GetUserName(name,&size)) {
1623 /* size includes NULL */
1624 ST(0) = sv_2mortal(newSVpv(name,size-1));
1634 char name[MAX_COMPUTERNAME_LENGTH+1];
1635 DWORD size = sizeof(name);
1636 if (GetComputerName(name,&size)) {
1637 /* size does NOT include NULL :-( */
1638 ST(0) = sv_2mortal(newSVpv(name,size));
1650 DWORD size = sizeof(name);
1651 if (GetUserName(name,&size)) {
1653 DWORD sidlen = sizeof(sid);
1655 DWORD dnamelen = sizeof(dname);
1657 if (LookupAccountName(NULL, name, &sid, &sidlen,
1658 dname, &dnamelen, &snu)) {
1659 XSRETURN_PV(dname); /* all that for this */
1670 DWORD flags, filecomplen;
1671 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
1672 &flags, fsname, sizeof(fsname))) {
1673 if (GIMME == G_ARRAY) {
1674 XPUSHs(sv_2mortal(newSVpv(fsname,0)));
1675 XPUSHs(sv_2mortal(newSViv(flags)));
1676 XPUSHs(sv_2mortal(newSViv(filecomplen)));
1680 XSRETURN_PV(fsname);
1686 XS(w32_GetOSVersion)
1689 OSVERSIONINFO osver;
1691 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1692 if (GetVersionEx(&osver)) {
1693 XPUSHs(newSVpv(osver.szCSDVersion, 0));
1694 XPUSHs(newSViv(osver.dwMajorVersion));
1695 XPUSHs(newSViv(osver.dwMinorVersion));
1696 XPUSHs(newSViv(osver.dwBuildNumber));
1697 XPUSHs(newSViv(osver.dwPlatformId));
1708 XSRETURN_IV(IsWinNT());
1715 XSRETURN_IV(IsWin95());
1719 XS(w32_FormatMessage)
1726 croak("usage: Win32::FormatMessage($errno)");
1728 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
1729 &source, SvIV(ST(0)), 0,
1730 msgbuf, sizeof(msgbuf)-1, NULL))
1731 XSRETURN_PV(msgbuf);
1741 PROCESS_INFORMATION stProcInfo;
1742 STARTUPINFO stStartInfo;
1743 BOOL bSuccess = FALSE;
1746 croak("usage: Win32::Spawn($cmdName, $args, $PID)");
1748 cmd = SvPV(ST(0),na);
1749 args = SvPV(ST(1), na);
1751 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
1752 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
1753 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
1754 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
1757 cmd, /* Image path */
1758 args, /* Arguments for command line */
1759 NULL, /* Default process security */
1760 NULL, /* Default thread security */
1761 FALSE, /* Must be TRUE to use std handles */
1762 NORMAL_PRIORITY_CLASS, /* No special scheduling */
1763 NULL, /* Inherit our environment block */
1764 NULL, /* Inherit our currrent directory */
1765 &stStartInfo, /* -> Startup info */
1766 &stProcInfo)) /* <- Process info (if OK) */
1768 CloseHandle(stProcInfo.hThread);/* library source code does this. */
1769 sv_setiv(ST(2), stProcInfo.dwProcessId);
1772 XSRETURN_IV(bSuccess);
1776 XS(w32_GetTickCount)
1779 XSRETURN_IV(GetTickCount());
1783 XS(w32_GetShortPathName)
1790 croak("usage: Win32::GetShortPathName($longPathName)");
1792 shortpath = sv_mortalcopy(ST(0));
1793 SvUPGRADE(shortpath, SVt_PV);
1794 /* src == target is allowed */
1796 len = GetShortPathName(SvPVX(shortpath),
1799 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
1801 SvCUR_set(shortpath,len);
1810 Perl_init_os_extras()
1812 char *file = __FILE__;
1815 /* XXX should be removed after checking with Nick */
1816 newXS("Win32::GetCurrentDirectory", w32_GetCwd, file);
1818 /* these names are Activeware compatible */
1819 newXS("Win32::GetCwd", w32_GetCwd, file);
1820 newXS("Win32::SetCwd", w32_SetCwd, file);
1821 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
1822 newXS("Win32::GetLastError", w32_GetLastError, file);
1823 newXS("Win32::LoginName", w32_LoginName, file);
1824 newXS("Win32::NodeName", w32_NodeName, file);
1825 newXS("Win32::DomainName", w32_DomainName, file);
1826 newXS("Win32::FsType", w32_FsType, file);
1827 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
1828 newXS("Win32::IsWinNT", w32_IsWinNT, file);
1829 newXS("Win32::IsWin95", w32_IsWin95, file);
1830 newXS("Win32::FormatMessage", w32_FormatMessage, file);
1831 newXS("Win32::Spawn", w32_Spawn, file);
1832 newXS("Win32::GetTickCount", w32_GetTickCount, file);
1833 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
1835 /* XXX Bloat Alert! The following Activeware preloads really
1836 * ought to be part of Win32::Sys::*, so they're not included
1839 /* LookupAccountName
1841 * InitiateSystemShutdown
1842 * AbortSystemShutdown
1843 * ExpandEnvrironmentStrings
1848 Perl_win32_init(int *argcp, char ***argvp)
1850 /* Disable floating point errors, Perl will trap the ones we
1851 * care about. VC++ RTL defaults to switching these off
1852 * already, but the Borland RTL doesn't. Since we don't
1853 * want to be at the vendor's whim on the default, we set
1854 * it explicitly here.
1856 #if !defined(_ALPHA_) && !defined(__GNUC__)
1857 _control87(MCW_EM, MCW_EM);
1862 #ifdef USE_BINMODE_SCRIPTS
1865 win32_strip_return(SV *sv)
1867 char *s = SvPVX(sv);
1868 char *e = s+SvCUR(sv);
1872 if (*s == '\r' && s[1] == '\n')
1882 SvCUR_set(sv,d-SvPVX(sv));