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
16 /* #include "config.h" */
18 #define PERLIO_NOT_STDIO 0
19 #if !defined(PERLIO_IS_STDIO) && !defined(USE_SFIO)
34 static DWORD IdOS(void);
36 extern WIN32_IOSUBSYSTEM win32stdio;
37 #ifndef __BORLANDC__ /* pointers cannot be declared TLS! */
40 PWIN32_IOSUBSYSTEM pIOSubSystem = &win32stdio;
42 BOOL ProbeEnv = FALSE;
43 DWORD Win32System = (DWORD)-1;
44 char szShellPath[MAX_PATH+1];
45 char szPerlLibRoot[MAX_PATH+1];
46 HANDLE PerlDllHandle = INVALID_HANDLE_VALUE;
50 return (IdOS() == VER_PLATFORM_WIN32_WINDOWS);
55 return (IdOS() == VER_PLATFORM_WIN32_NT);
59 SetIOSubSystem(void *p)
61 PWIN32_IOSUBSYSTEM old = pIOSubSystem;
63 PWIN32_IOSUBSYSTEM pio = (PWIN32_IOSUBSYSTEM)p;
64 if (pio->signature_begin == 12345678L
65 && pio->signature_end == 87654321L) {
70 pIOSubSystem = &win32stdio;
76 win32PerlLibPath(void)
79 GetModuleFileName((PerlDllHandle == INVALID_HANDLE_VALUE)
80 ? GetModuleHandle(NULL)
83 sizeof(szPerlLibRoot));
85 *(end = strrchr(szPerlLibRoot, '\\')) = '\0';
86 if (stricmp(end-4,"\\bin") == 0)
89 return (szPerlLibRoot);
93 HasRedirection(char *ptr)
99 * Scan string looking for redirection (< or >) or pipe
100 * characters (|) that are not in a quoted string
130 /* since the current process environment is being updated in util.c
131 * the library functions will get the correct environment
134 my_popen(char *cmd, char *mode)
137 #define fixcmd(x) { \
138 char *pspace = strchr((x),' '); \
141 while (p < pspace) { \
153 /* was #ifndef PERLDLL, but the #else stuff doesn't work on NT
157 #ifdef __BORLANDC__ /* workaround a Borland stdio bug */
158 win32_fflush(stdout);
159 win32_fflush(stderr);
161 return win32_popen(cmd, mode);
164 * There seems to be some problems for the _popen call in a DLL
165 * this trick at the moment seems to work but it is never test
170 #define EXT_C_FUNC extern "C"
172 #define EXT_C_FUNC extern
175 EXT_C_FUNC int __cdecl _set_osfhnd(int fh, long value);
176 EXT_C_FUNC void __cdecl _lock_fhandle(int);
177 EXT_C_FUNC void __cdecl _unlock_fhandle(int);
180 PerlIO *pf; /* to store the _popen return value */
181 int tm = 0; /* flag indicating tDllExport or binary mode */
182 int fhNeeded, fhInherited, fhDup;
183 int ineeded, iinherited;
185 int phdls[2]; /* I/O handles for pipe */
186 HANDLE hPIn, hPOut, hPErr,
187 hSaveStdin, hSaveStdout, hSaveStderr,
188 hPNeeded, hPInherited, hPDuped;
190 /* first check for errors in the arguments */
191 if ( (cmd == NULL) || (mode == NULL)
192 || ((*mode != 'w') && (*mode != _T('r'))) )
195 if ( *(mode + 1) == _T('t') )
197 else if ( *(mode + 1) == _T('b') )
200 tm = (*mode == 'w' ? O_BINARY : O_TEXT);
204 if (&win32stdio != pIOSubSystem)
205 return win32_popen(cmd, mode);
208 if ( _pipe( phdls, 1024, tm ) == -1 )
210 if ( win32_pipe( phdls, 1024, tm ) == -1 )
214 /* save the current situation */
215 hSaveStdin = GetStdHandle(STD_INPUT_HANDLE);
216 hSaveStdout = GetStdHandle(STD_OUTPUT_HANDLE);
217 hSaveStderr = GetStdHandle(STD_ERROR_HANDLE);
219 if (*mode == _T('w')) {
221 dwDup = STD_INPUT_HANDLE;
226 dwDup = STD_OUTPUT_HANDLE;
230 fhNeeded = phdls[ineeded];
231 fhInherited = phdls[iinherited];
233 fSuccess = DuplicateHandle(GetCurrentProcess(),
234 (HANDLE) stolen_get_osfhandle(fhNeeded),
238 FALSE, /* not inherited */
239 DUPLICATE_SAME_ACCESS);
244 fhDup = stolen_open_osfhandle((long) hPNeeded, tm);
245 win32_dup2(fhDup, fhNeeded);
249 /* Close the Out pipe, child won't need it */
250 hPDuped = (HANDLE) stolen_get_osfhandle(fhNeeded);
252 _lock_fhandle(fhNeeded);
253 _set_osfhnd(fhNeeded, (long)hPNeeded); /* put in ours duplicated one */
254 _unlock_fhandle(fhNeeded);
256 CloseHandle(hPDuped); /* close the handle first */
259 if (!SetStdHandle(dwDup, (HANDLE) stolen_get_osfhandle(fhInherited)))
263 * make sure the child see the same stderr as the calling program
265 if (!SetStdHandle(STD_ERROR_HANDLE,
266 (HANDLE)stolen_get_osfhandle(win32_fileno(win32_stderr()))))
269 pf = win32_popen(cmd, mode); /* ask _popen to do the job */
271 /* restore to where we were */
272 SetStdHandle(STD_INPUT_HANDLE, hSaveStdin);
273 SetStdHandle(STD_OUTPUT_HANDLE, hSaveStdout);
274 SetStdHandle(STD_ERROR_HANDLE, hSaveStderr);
276 /* we don't need it any more, that's for the child */
277 win32_close(fhInherited);
280 /* something wrong */
281 win32_close(fhNeeded);
286 * here we steal the file handle in pf and stuff ours in
288 win32_dup2(fhNeeded, win32_fileno(pf));
289 win32_close(fhNeeded);
294 win32_close(fhNeeded);
295 win32_close(fhInherited);
304 my_pclose(PerlIO *fp)
306 return win32_pclose(fp);
312 static OSVERSIONINFO osver;
314 if (osver.dwPlatformId != Win32System) {
315 memset(&osver, 0, sizeof(OSVERSIONINFO));
316 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
317 GetVersionEx(&osver);
318 Win32System = osver.dwPlatformId;
320 return (Win32System);
327 char* defaultshell = (IsWinNT() ? "cmd.exe" : "command.com");
328 /* we don't use COMSPEC here for two reasons:
329 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
330 * uncontrolled unportability of the ensuing scripts.
331 * 2. PERL5SHELL could be set to a shell that may not be fit for
332 * interactive use (which is what most programs look in COMSPEC
335 char *usershell = getenv("PERL5SHELL");
338 strcpy(szShellPath, usershell ? usershell : defaultshell);
344 do_aspawn(void* really, void** mark, void** arglast)
352 SV *sv = (SV*)really;
353 SV** pSv = (SV**)mark;
355 New(1310, argv, (arglast - mark) + 4, char*);
358 cmd = SvPV(sv, length);
361 argv[index++] = cmd = GetShell();
362 argv[index++] = "/x"; /* always enable command extensions */
363 argv[index++] = "/c";
366 while(++pSv <= (SV**)arglast) {
368 strPtr = SvPV(sv, length);
369 if(strPtr != NULL && *strPtr != '\0')
370 argv[index++] = strPtr;
374 status = win32_spawnvp(P_WAIT, cmd, (const char* const*)argv);
380 warn("Can't spawn \"%s\": %s", cmd, strerror(errno));
393 BOOL needToTry = TRUE;
396 /* save an extra exec if possible */
399 /* see if there are shell metacharacters in it */
400 if(!HasRedirection(cmd)) {
401 New(1301,argv, strlen(cmd) / 2 + 2, char*);
402 New(1302,cmd2, strlen(cmd) + 1, char);
405 for (s = cmd2; *s;) {
406 while (*s && isspace(*s))
410 while(*s && !isspace(*s))
417 status = win32_spawnvp(P_WAIT, argv[0], (const char* const*)argv);
418 if(status != -1 || errno == 0)
426 argv[0] = shell; argv[1] = "/x"; argv[2] = "/c";
427 argv[3] = cmd; argv[4] = Nullch;
428 status = win32_spawnvp(P_WAIT, argv[0], (const char* const*)argv);
432 warn("Can't spawn \"%s\": %s", needToTry ? shell : argv[0],
442 /* The idea here is to read all the directory names into a string table
443 * (separated by nulls) and when one of the other dir functions is called
444 * return the pointer to the current file name.
447 opendir(char *filename)
452 char scannamespc[PATHLEN];
453 char *scanname = scannamespc;
455 WIN32_FIND_DATA FindData;
457 /* char root[_MAX_PATH];*/
458 /* char volname[_MAX_PATH];*/
459 /* DWORD serial, maxname, flags;*/
463 /* check to see if filename is a directory */
464 if(stat(filename, &sbuf) < 0 || sbuf.st_mode & S_IFDIR == 0) {
468 /* get the file system characteristics */
469 /* if(GetFullPathName(filename, MAX_PATH, root, &dummy)) {
470 * if(dummy = strchr(root, '\\'))
472 * if(GetVolumeInformation(root, volname, MAX_PATH, &serial,
473 * &maxname, &flags, 0, 0)) {
474 * downcase = !(flags & FS_CASE_IS_PRESERVED);
481 /* Get us a DIR structure */
482 Newz(1303, p, 1, DIR);
486 /* Create the search pattern */
487 strcpy(scanname, filename);
489 if(index("/\\", *(scanname + strlen(scanname) - 1)) == NULL)
490 strcat(scanname, "/*");
492 strcat(scanname, "*");
494 /* do the FindFirstFile call */
495 fh = FindFirstFile(scanname, &FindData);
496 if(fh == INVALID_HANDLE_VALUE) {
500 /* now allocate the first part of the string table for
501 * the filenames that we find.
503 idx = strlen(FindData.cFileName)+1;
504 New(1304, p->start, idx, char);
505 if(p->start == NULL) {
506 CROAK("opendir: malloc failed!\n");
508 strcpy(p->start, FindData.cFileName);
514 /* loop finding all the files that match the wildcard
515 * (which should be all of them in this directory!).
516 * the variable idx should point one past the null terminator
517 * of the previous string found.
519 while (FindNextFile(fh, &FindData)) {
520 len = strlen(FindData.cFileName);
521 /* bump the string table size by enough for the
522 * new name and it's null terminator
524 Renew(p->start, idx+len+1, char);
525 if(p->start == NULL) {
526 CROAK("opendir: malloc failed!\n");
528 strcpy(&p->start[idx], FindData.cFileName);
530 * strlwr(&p->start[idx]);
542 /* Readdir just returns the current string pointer and bumps the
543 * string pointer to the nDllExport entry.
549 static int dummy = 0;
552 /* first set up the structure to return */
553 len = strlen(dirp->curr);
554 strcpy(dirp->dirstr.d_name, dirp->curr);
555 dirp->dirstr.d_namlen = len;
558 dirp->dirstr.d_ino = dummy++;
560 /* Now set up for the nDllExport call to readdir */
561 dirp->curr += len + 1;
562 if (dirp->curr >= (dirp->start + dirp->size)) {
566 return &(dirp->dirstr);
572 /* Telldir returns the current string pointer position */
576 return (long) dirp->curr;
580 /* Seekdir moves the string pointer to a previously saved position
584 seekdir(DIR *dirp, long loc)
586 dirp->curr = (char *)loc;
589 /* Rewinddir resets the string pointer to the start */
593 dirp->curr = dirp->start;
596 /* free the memory allocated by opendir */
600 Safefree(dirp->start);
613 * Just pretend that everyone is a superuser. NT will let us know if
614 * we don\'t really have permission to do something.
617 #define ROOT_UID ((uid_t)0)
618 #define ROOT_GID ((gid_t)0)
647 return (uid == ROOT_UID ? 0 : -1);
653 return (gid == ROOT_GID ? 0 : -1);
660 kill(int pid, int sig)
662 HANDLE hProcess= OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
664 if (hProcess == NULL) {
665 CROAK("kill process failed!\n");
668 if (!TerminateProcess(hProcess, sig))
669 CROAK("kill process failed!\n");
670 CloseHandle(hProcess);
681 ioctl(int i, unsigned int u, char *data)
683 CROAK("ioctl not implemented!\n");
689 sleep(unsigned int t)
699 myrename(char *OldFileName, char *newname)
701 if(_access(newname, 0) != -1) { /* file exists */
704 return rename(OldFileName, newname);
709 win32_stat(const char *path, struct stat *buffer)
712 const char *p = path;
713 int l = strlen(path);
716 switch(path[l - 1]) {
719 if (path[l - 2] != ':') {
720 strncpy(t, path, l - 1);
726 return stat(p, buffer);
731 mytimes(struct tms *timebuf)
734 timebuf->tms_utime = t;
735 timebuf->tms_stime = 0;
736 timebuf->tms_cutime = 0;
737 timebuf->tms_cstime = 0;
744 myalarm(unsigned int sec)
746 /* we warn the usuage of alarm function */
748 WARN("dummy function alarm called, program might not function as expected\n");
753 * redirected io subsystem for all XS modules
760 return (pIOSubSystem->pfnerrno());
766 return (pIOSubSystem->pfnenviron());
769 /* the rest are the remapped stdio routines */
773 return (pIOSubSystem->pfnstderr());
779 return (pIOSubSystem->pfnstdin());
785 return (pIOSubSystem->pfnstdout());
789 win32_ferror(FILE *fp)
791 return (pIOSubSystem->pfnferror(fp));
798 return (pIOSubSystem->pfnfeof(fp));
802 * Since the errors returned by the socket error function
803 * WSAGetLastError() are not known by the library routine strerror
804 * we have to roll our own.
807 __declspec(thread) char strerror_buffer[512];
810 win32_strerror(int e)
812 #ifndef __BORLANDC__ /* Borland intolerance */
817 if(e < 0 || e > sys_nerr) {
821 if(FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
822 strerror_buffer, sizeof(strerror_buffer), NULL) == 0)
823 strcpy(strerror_buffer, "Unknown Error");
825 return strerror_buffer;
827 return pIOSubSystem->pfnstrerror(e);
831 win32_fprintf(FILE *fp, const char *format, ...)
834 va_start(marker, format); /* Initialize variable arguments. */
836 return (pIOSubSystem->pfnvfprintf(fp, format, marker));
840 win32_printf(const char *format, ...)
843 va_start(marker, format); /* Initialize variable arguments. */
845 return (pIOSubSystem->pfnvprintf(format, marker));
849 win32_vfprintf(FILE *fp, const char *format, va_list args)
851 return (pIOSubSystem->pfnvfprintf(fp, format, args));
855 win32_vprintf(const char *format, va_list args)
857 return (pIOSubSystem->pfnvprintf(format, args));
861 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
863 return pIOSubSystem->pfnfread(buf, size, count, fp);
867 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
869 return pIOSubSystem->pfnfwrite(buf, size, count, fp);
873 win32_fopen(const char *filename, const char *mode)
875 if (stricmp(filename, "/dev/null")==0)
876 return pIOSubSystem->pfnfopen("NUL", mode);
877 return pIOSubSystem->pfnfopen(filename, mode);
881 win32_fdopen( int handle, const char *mode)
883 return pIOSubSystem->pfnfdopen(handle, mode);
887 win32_freopen( const char *path, const char *mode, FILE *stream)
889 if (stricmp(path, "/dev/null")==0)
890 return pIOSubSystem->pfnfreopen("NUL", mode, stream);
891 return pIOSubSystem->pfnfreopen(path, mode, stream);
895 win32_fclose(FILE *pf)
897 return pIOSubSystem->pfnfclose(pf);
901 win32_fputs(const char *s,FILE *pf)
903 return pIOSubSystem->pfnfputs(s, pf);
907 win32_fputc(int c,FILE *pf)
909 return pIOSubSystem->pfnfputc(c,pf);
913 win32_ungetc(int c,FILE *pf)
915 return pIOSubSystem->pfnungetc(c,pf);
921 return pIOSubSystem->pfngetc(pf);
925 win32_fileno(FILE *pf)
927 return pIOSubSystem->pfnfileno(pf);
931 win32_clearerr(FILE *pf)
933 pIOSubSystem->pfnclearerr(pf);
938 win32_fflush(FILE *pf)
940 return pIOSubSystem->pfnfflush(pf);
944 win32_ftell(FILE *pf)
946 return pIOSubSystem->pfnftell(pf);
950 win32_fseek(FILE *pf,long offset,int origin)
952 return pIOSubSystem->pfnfseek(pf, offset, origin);
956 win32_fgetpos(FILE *pf,fpos_t *p)
958 return pIOSubSystem->pfnfgetpos(pf, p);
962 win32_fsetpos(FILE *pf,const fpos_t *p)
964 return pIOSubSystem->pfnfsetpos(pf, p);
968 win32_rewind(FILE *pf)
970 pIOSubSystem->pfnrewind(pf);
977 return pIOSubSystem->pfntmpfile();
983 pIOSubSystem->pfnabort();
988 win32_fstat(int fd,struct stat *bufptr)
990 return pIOSubSystem->pfnfstat(fd,bufptr);
994 win32_pipe(int *pfd, unsigned int size, int mode)
996 return pIOSubSystem->pfnpipe(pfd, size, mode);
1000 win32_popen(const char *command, const char *mode)
1002 return pIOSubSystem->pfnpopen(command, mode);
1006 win32_pclose(FILE *pf)
1008 return pIOSubSystem->pfnpclose(pf);
1012 win32_setmode(int fd, int mode)
1014 return pIOSubSystem->pfnsetmode(fd, mode);
1018 win32_lseek(int fd, long offset, int origin)
1020 return pIOSubSystem->pfnlseek(fd, offset, origin);
1026 return pIOSubSystem->pfntell(fd);
1030 win32_open(const char *path, int flag, ...)
1036 pmode = va_arg(ap, int);
1039 if (stricmp(path, "/dev/null")==0)
1040 return pIOSubSystem->pfnopen("NUL", flag, pmode);
1041 return pIOSubSystem->pfnopen(path,flag,pmode);
1047 return pIOSubSystem->pfnclose(fd);
1053 return pIOSubSystem->pfneof(fd);
1059 return pIOSubSystem->pfndup(fd);
1063 win32_dup2(int fd1,int fd2)
1065 return pIOSubSystem->pfndup2(fd1,fd2);
1069 win32_read(int fd, void *buf, unsigned int cnt)
1071 return pIOSubSystem->pfnread(fd, buf, cnt);
1075 win32_write(int fd, const void *buf, unsigned int cnt)
1077 return pIOSubSystem->pfnwrite(fd, buf, cnt);
1081 win32_mkdir(const char *dir, int mode)
1083 return pIOSubSystem->pfnmkdir(dir); /* just ignore mode */
1087 win32_rmdir(const char *dir)
1089 return pIOSubSystem->pfnrmdir(dir);
1093 win32_chdir(const char *dir)
1095 return pIOSubSystem->pfnchdir(dir);
1099 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
1101 return pIOSubSystem->pfnspawnvp(mode, cmdname, argv);
1105 stolen_open_osfhandle(long handle, int flags)
1107 return pIOSubSystem->pfn_open_osfhandle(handle, flags);
1111 stolen_get_osfhandle(int fd)
1113 return pIOSubSystem->pfn_get_osfhandle(fd);
1121 win32_flock(int fd, int oper)
1124 croak("flock() unimplemented on this platform");
1127 return pIOSubSystem->pfnflock(fd, oper);