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)
36 #define EXECF_SPAWN_NOWAIT 3
38 static DWORD IdOS(void);
40 extern WIN32_IOSUBSYSTEM win32stdio;
41 static PWIN32_IOSUBSYSTEM pIOSubSystem = &win32stdio;
43 BOOL ProbeEnv = FALSE;
44 DWORD Win32System = (DWORD)-1;
45 char szShellPath[MAX_PATH+1];
46 char szPerlLibRoot[MAX_PATH+1];
47 HANDLE PerlDllHandle = INVALID_HANDLE_VALUE;
49 static int do_spawn2(char *cmd, int exectype);
53 return (IdOS() == VER_PLATFORM_WIN32_WINDOWS);
58 return (IdOS() == VER_PLATFORM_WIN32_NT);
62 SetIOSubSystem(void *p)
64 PWIN32_IOSUBSYSTEM old = pIOSubSystem;
66 PWIN32_IOSUBSYSTEM pio = (PWIN32_IOSUBSYSTEM)p;
67 if (pio->signature_begin == 12345678L
68 && pio->signature_end == 87654321L) {
73 pIOSubSystem = &win32stdio;
79 win32PerlLibPath(void)
82 GetModuleFileName((PerlDllHandle == INVALID_HANDLE_VALUE)
83 ? GetModuleHandle(NULL)
86 sizeof(szPerlLibRoot));
88 *(end = strrchr(szPerlLibRoot, '\\')) = '\0';
89 if (stricmp(end-4,"\\bin") == 0)
92 return (szPerlLibRoot);
96 win32SiteLibPath(void)
98 static char szPerlSiteLib[MAXPATH+1];
99 strcpy(szPerlSiteLib, win32PerlLibPath());
100 strcat(szPerlSiteLib, "\\site");
101 return (szPerlSiteLib);
105 HasRedirection(char *ptr)
111 * Scan string looking for redirection (< or >) or pipe
112 * characters (|) that are not in a quoted string
142 /* since the current process environment is being updated in util.c
143 * the library functions will get the correct environment
146 my_popen(char *cmd, char *mode)
149 #define fixcmd(x) { \
150 char *pspace = strchr((x),' '); \
153 while (p < pspace) { \
165 /* was #ifndef PERLDLL, but the #else stuff doesn't work on NT
169 #ifdef __BORLANDC__ /* workaround a Borland stdio bug */
170 win32_fflush(stdout);
171 win32_fflush(stderr);
173 return win32_popen(cmd, mode);
176 * There seems to be some problems for the _popen call in a DLL
177 * this trick at the moment seems to work but it is never test
182 #define EXT_C_FUNC extern "C"
184 #define EXT_C_FUNC extern
187 EXT_C_FUNC int __cdecl _set_osfhnd(int fh, long value);
188 EXT_C_FUNC void __cdecl _lock_fhandle(int);
189 EXT_C_FUNC void __cdecl _unlock_fhandle(int);
192 PerlIO *pf; /* to store the _popen return value */
193 int tm = 0; /* flag indicating tDllExport or binary mode */
194 int fhNeeded, fhInherited, fhDup;
195 int ineeded, iinherited;
197 int phdls[2]; /* I/O handles for pipe */
198 HANDLE hPIn, hPOut, hPErr,
199 hSaveStdin, hSaveStdout, hSaveStderr,
200 hPNeeded, hPInherited, hPDuped;
202 /* first check for errors in the arguments */
203 if ( (cmd == NULL) || (mode == NULL)
204 || ((*mode != 'w') && (*mode != _T('r'))) )
207 if ( *(mode + 1) == _T('t') )
209 else if ( *(mode + 1) == _T('b') )
212 tm = (*mode == 'w' ? O_BINARY : O_TEXT);
216 if (&win32stdio != pIOSubSystem)
217 return win32_popen(cmd, mode);
220 if ( _pipe( phdls, 1024, tm ) == -1 )
222 if ( win32_pipe( phdls, 1024, tm ) == -1 )
226 /* save the current situation */
227 hSaveStdin = GetStdHandle(STD_INPUT_HANDLE);
228 hSaveStdout = GetStdHandle(STD_OUTPUT_HANDLE);
229 hSaveStderr = GetStdHandle(STD_ERROR_HANDLE);
231 if (*mode == _T('w')) {
233 dwDup = STD_INPUT_HANDLE;
238 dwDup = STD_OUTPUT_HANDLE;
242 fhNeeded = phdls[ineeded];
243 fhInherited = phdls[iinherited];
245 fSuccess = DuplicateHandle(GetCurrentProcess(),
246 (HANDLE) stolen_get_osfhandle(fhNeeded),
250 FALSE, /* not inherited */
251 DUPLICATE_SAME_ACCESS);
256 fhDup = stolen_open_osfhandle((long) hPNeeded, tm);
257 win32_dup2(fhDup, fhNeeded);
261 /* Close the Out pipe, child won't need it */
262 hPDuped = (HANDLE) stolen_get_osfhandle(fhNeeded);
264 _lock_fhandle(fhNeeded);
265 _set_osfhnd(fhNeeded, (long)hPNeeded); /* put in ours duplicated one */
266 _unlock_fhandle(fhNeeded);
268 CloseHandle(hPDuped); /* close the handle first */
271 if (!SetStdHandle(dwDup, (HANDLE) stolen_get_osfhandle(fhInherited)))
275 * make sure the child see the same stderr as the calling program
277 if (!SetStdHandle(STD_ERROR_HANDLE,
278 (HANDLE)stolen_get_osfhandle(win32_fileno(win32_stderr()))))
281 pf = win32_popen(cmd, mode); /* ask _popen to do the job */
283 /* restore to where we were */
284 SetStdHandle(STD_INPUT_HANDLE, hSaveStdin);
285 SetStdHandle(STD_OUTPUT_HANDLE, hSaveStdout);
286 SetStdHandle(STD_ERROR_HANDLE, hSaveStderr);
288 /* we don't need it any more, that's for the child */
289 win32_close(fhInherited);
292 /* something wrong */
293 win32_close(fhNeeded);
298 * here we steal the file handle in pf and stuff ours in
300 win32_dup2(fhNeeded, win32_fileno(pf));
301 win32_close(fhNeeded);
306 win32_close(fhNeeded);
307 win32_close(fhInherited);
316 my_pclose(PerlIO *fp)
318 return win32_pclose(fp);
324 static OSVERSIONINFO osver;
326 if (osver.dwPlatformId != Win32System) {
327 memset(&osver, 0, sizeof(OSVERSIONINFO));
328 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
329 GetVersionEx(&osver);
330 Win32System = osver.dwPlatformId;
332 return (Win32System);
339 char* defaultshell = (IsWinNT() ? "cmd.exe" : "command.com");
340 /* we don't use COMSPEC here for two reasons:
341 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
342 * uncontrolled unportability of the ensuing scripts.
343 * 2. PERL5SHELL could be set to a shell that may not be fit for
344 * interactive use (which is what most programs look in COMSPEC
347 char *usershell = getenv("PERL5SHELL");
350 strcpy(szShellPath, usershell ? usershell : defaultshell);
356 do_aspawn(void* really, void** mark, void** arglast)
364 SV *sv = (SV*)really;
365 SV** pSv = (SV**)mark;
367 New(1310, argv, (arglast - mark) + 4, char*);
370 cmd = SvPV(sv, length);
373 argv[index++] = cmd = GetShell();
374 argv[index++] = "/x"; /* always enable command extensions */
375 argv[index++] = "/c";
378 while(++pSv <= (SV**)arglast) {
380 strPtr = SvPV(sv, length);
381 if(strPtr != NULL && *strPtr != '\0')
382 argv[index++] = strPtr;
386 status = win32_spawnvp(P_WAIT, cmd, (const char* const*)argv);
392 warn("Can't spawn \"%s\": %s", cmd, strerror(errno));
399 do_spawn2(char *cmd, int exectype)
405 BOOL needToTry = TRUE;
408 /* save an extra exec if possible */
411 /* see if there are shell metacharacters in it */
412 if(!HasRedirection(cmd)) {
413 New(1301,argv, strlen(cmd) / 2 + 2, char*);
414 New(1302,cmd2, strlen(cmd) + 1, char);
417 for (s = cmd2; *s;) {
418 while (*s && isspace(*s))
422 while(*s && !isspace(*s))
431 status = win32_spawnvp(P_WAIT, argv[0],
432 (const char* const*)argv);
434 case EXECF_SPAWN_NOWAIT:
435 status = win32_spawnvp(P_NOWAIT, argv[0],
436 (const char* const*)argv);
439 status = win32_execvp(argv[0], (const char* const*)argv);
442 if(status != -1 || errno == 0)
450 argv[0] = shell; argv[1] = "/x"; argv[2] = "/c";
451 argv[3] = cmd; argv[4] = Nullch;
454 status = win32_spawnvp(P_WAIT, argv[0],
455 (const char* const*)argv);
457 case EXECF_SPAWN_NOWAIT:
458 status = win32_spawnvp(P_NOWAIT, argv[0],
459 (const char* const*)argv);
462 status = win32_execvp(argv[0], (const char* const*)argv);
468 warn("Can't %s \"%s\": %s",
469 (exectype == EXECF_EXEC ? "exec" : "spawn"),
470 needToTry ? shell : argv[0],
480 return do_spawn2(cmd, EXECF_SPAWN);
486 do_spawn2(cmd, EXECF_EXEC);
493 /* The idea here is to read all the directory names into a string table
494 * (separated by nulls) and when one of the other dir functions is called
495 * return the pointer to the current file name.
498 opendir(char *filename)
503 char scannamespc[PATHLEN];
504 char *scanname = scannamespc;
506 WIN32_FIND_DATA FindData;
508 /* char root[_MAX_PATH];*/
509 /* char volname[_MAX_PATH];*/
510 /* DWORD serial, maxname, flags;*/
514 /* check to see if filename is a directory */
515 if(stat(filename, &sbuf) < 0 || sbuf.st_mode & S_IFDIR == 0) {
519 /* get the file system characteristics */
520 /* if(GetFullPathName(filename, MAX_PATH, root, &dummy)) {
521 * if(dummy = strchr(root, '\\'))
523 * if(GetVolumeInformation(root, volname, MAX_PATH, &serial,
524 * &maxname, &flags, 0, 0)) {
525 * downcase = !(flags & FS_CASE_IS_PRESERVED);
532 /* Get us a DIR structure */
533 Newz(1303, p, 1, DIR);
537 /* Create the search pattern */
538 strcpy(scanname, filename);
540 if(index("/\\", *(scanname + strlen(scanname) - 1)) == NULL)
541 strcat(scanname, "/*");
543 strcat(scanname, "*");
545 /* do the FindFirstFile call */
546 fh = FindFirstFile(scanname, &FindData);
547 if(fh == INVALID_HANDLE_VALUE) {
551 /* now allocate the first part of the string table for
552 * the filenames that we find.
554 idx = strlen(FindData.cFileName)+1;
555 New(1304, p->start, idx, char);
556 if(p->start == NULL) {
557 CROAK("opendir: malloc failed!\n");
559 strcpy(p->start, FindData.cFileName);
565 /* loop finding all the files that match the wildcard
566 * (which should be all of them in this directory!).
567 * the variable idx should point one past the null terminator
568 * of the previous string found.
570 while (FindNextFile(fh, &FindData)) {
571 len = strlen(FindData.cFileName);
572 /* bump the string table size by enough for the
573 * new name and it's null terminator
575 Renew(p->start, idx+len+1, char);
576 if(p->start == NULL) {
577 CROAK("opendir: malloc failed!\n");
579 strcpy(&p->start[idx], FindData.cFileName);
581 * strlwr(&p->start[idx]);
593 /* Readdir just returns the current string pointer and bumps the
594 * string pointer to the nDllExport entry.
600 static int dummy = 0;
603 /* first set up the structure to return */
604 len = strlen(dirp->curr);
605 strcpy(dirp->dirstr.d_name, dirp->curr);
606 dirp->dirstr.d_namlen = len;
609 dirp->dirstr.d_ino = dummy++;
611 /* Now set up for the nDllExport call to readdir */
612 dirp->curr += len + 1;
613 if (dirp->curr >= (dirp->start + dirp->size)) {
617 return &(dirp->dirstr);
623 /* Telldir returns the current string pointer position */
627 return (long) dirp->curr;
631 /* Seekdir moves the string pointer to a previously saved position
635 seekdir(DIR *dirp, long loc)
637 dirp->curr = (char *)loc;
640 /* Rewinddir resets the string pointer to the start */
644 dirp->curr = dirp->start;
647 /* free the memory allocated by opendir */
651 Safefree(dirp->start);
664 * Just pretend that everyone is a superuser. NT will let us know if
665 * we don\'t really have permission to do something.
668 #define ROOT_UID ((uid_t)0)
669 #define ROOT_GID ((gid_t)0)
698 return (uid == ROOT_UID ? 0 : -1);
704 return (gid == ROOT_GID ? 0 : -1);
711 kill(int pid, int sig)
713 HANDLE hProcess= OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
715 if (hProcess == NULL) {
716 CROAK("kill process failed!\n");
719 if (!TerminateProcess(hProcess, sig))
720 CROAK("kill process failed!\n");
721 CloseHandle(hProcess);
732 ioctl(int i, unsigned int u, char *data)
734 CROAK("ioctl not implemented!\n");
740 sleep(unsigned int t)
750 myrename(char *OldFileName, char *newname)
752 if(_access(newname, 0) != -1) { /* file exists */
755 return rename(OldFileName, newname);
760 win32_stat(const char *path, struct stat *buffer)
763 const char *p = path;
764 int l = strlen(path);
767 switch(path[l - 1]) {
770 if (path[l - 2] != ':') {
771 strncpy(t, path, l - 1);
777 return stat(p, buffer);
782 mytimes(struct tms *timebuf)
785 timebuf->tms_utime = t;
786 timebuf->tms_stime = 0;
787 timebuf->tms_cutime = 0;
788 timebuf->tms_cstime = 0;
795 myalarm(unsigned int sec)
797 /* we warn the usuage of alarm function */
799 WARN("dummy function alarm called, program might not function as expected\n");
804 * redirected io subsystem for all XS modules
811 return (pIOSubSystem->pfnerrno());
817 return (pIOSubSystem->pfnenviron());
820 /* the rest are the remapped stdio routines */
824 return (pIOSubSystem->pfnstderr());
830 return (pIOSubSystem->pfnstdin());
836 return (pIOSubSystem->pfnstdout());
840 win32_ferror(FILE *fp)
842 return (pIOSubSystem->pfnferror(fp));
849 return (pIOSubSystem->pfnfeof(fp));
853 * Since the errors returned by the socket error function
854 * WSAGetLastError() are not known by the library routine strerror
855 * we have to roll our own.
858 __declspec(thread) char strerror_buffer[512];
861 win32_strerror(int e)
863 #ifndef __BORLANDC__ /* Borland intolerance */
868 if(e < 0 || e > sys_nerr) {
872 if(FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
873 strerror_buffer, sizeof(strerror_buffer), NULL) == 0)
874 strcpy(strerror_buffer, "Unknown Error");
876 return strerror_buffer;
878 return pIOSubSystem->pfnstrerror(e);
882 win32_fprintf(FILE *fp, const char *format, ...)
885 va_start(marker, format); /* Initialize variable arguments. */
887 return (pIOSubSystem->pfnvfprintf(fp, format, marker));
891 win32_printf(const char *format, ...)
894 va_start(marker, format); /* Initialize variable arguments. */
896 return (pIOSubSystem->pfnvprintf(format, marker));
900 win32_vfprintf(FILE *fp, const char *format, va_list args)
902 return (pIOSubSystem->pfnvfprintf(fp, format, args));
906 win32_vprintf(const char *format, va_list args)
908 return (pIOSubSystem->pfnvprintf(format, args));
912 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
914 return pIOSubSystem->pfnfread(buf, size, count, fp);
918 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
920 return pIOSubSystem->pfnfwrite(buf, size, count, fp);
924 win32_fopen(const char *filename, const char *mode)
926 if (stricmp(filename, "/dev/null")==0)
927 return pIOSubSystem->pfnfopen("NUL", mode);
928 return pIOSubSystem->pfnfopen(filename, mode);
932 win32_fdopen( int handle, const char *mode)
934 return pIOSubSystem->pfnfdopen(handle, mode);
938 win32_freopen( const char *path, const char *mode, FILE *stream)
940 if (stricmp(path, "/dev/null")==0)
941 return pIOSubSystem->pfnfreopen("NUL", mode, stream);
942 return pIOSubSystem->pfnfreopen(path, mode, stream);
946 win32_fclose(FILE *pf)
948 return pIOSubSystem->pfnfclose(pf);
952 win32_fputs(const char *s,FILE *pf)
954 return pIOSubSystem->pfnfputs(s, pf);
958 win32_fputc(int c,FILE *pf)
960 return pIOSubSystem->pfnfputc(c,pf);
964 win32_ungetc(int c,FILE *pf)
966 return pIOSubSystem->pfnungetc(c,pf);
972 return pIOSubSystem->pfngetc(pf);
976 win32_fileno(FILE *pf)
978 return pIOSubSystem->pfnfileno(pf);
982 win32_clearerr(FILE *pf)
984 pIOSubSystem->pfnclearerr(pf);
989 win32_fflush(FILE *pf)
991 return pIOSubSystem->pfnfflush(pf);
995 win32_ftell(FILE *pf)
997 return pIOSubSystem->pfnftell(pf);
1001 win32_fseek(FILE *pf,long offset,int origin)
1003 return pIOSubSystem->pfnfseek(pf, offset, origin);
1007 win32_fgetpos(FILE *pf,fpos_t *p)
1009 return pIOSubSystem->pfnfgetpos(pf, p);
1013 win32_fsetpos(FILE *pf,const fpos_t *p)
1015 return pIOSubSystem->pfnfsetpos(pf, p);
1019 win32_rewind(FILE *pf)
1021 pIOSubSystem->pfnrewind(pf);
1028 return pIOSubSystem->pfntmpfile();
1034 pIOSubSystem->pfnabort();
1039 win32_fstat(int fd,struct stat *bufptr)
1041 return pIOSubSystem->pfnfstat(fd,bufptr);
1045 win32_pipe(int *pfd, unsigned int size, int mode)
1047 return pIOSubSystem->pfnpipe(pfd, size, mode);
1051 win32_popen(const char *command, const char *mode)
1053 return pIOSubSystem->pfnpopen(command, mode);
1057 win32_pclose(FILE *pf)
1059 return pIOSubSystem->pfnpclose(pf);
1063 win32_setmode(int fd, int mode)
1065 return pIOSubSystem->pfnsetmode(fd, mode);
1069 win32_lseek(int fd, long offset, int origin)
1071 return pIOSubSystem->pfnlseek(fd, offset, origin);
1077 return pIOSubSystem->pfntell(fd);
1081 win32_open(const char *path, int flag, ...)
1087 pmode = va_arg(ap, int);
1090 if (stricmp(path, "/dev/null")==0)
1091 return pIOSubSystem->pfnopen("NUL", flag, pmode);
1092 return pIOSubSystem->pfnopen(path,flag,pmode);
1098 return pIOSubSystem->pfnclose(fd);
1104 return pIOSubSystem->pfneof(fd);
1110 return pIOSubSystem->pfndup(fd);
1114 win32_dup2(int fd1,int fd2)
1116 return pIOSubSystem->pfndup2(fd1,fd2);
1120 win32_read(int fd, void *buf, unsigned int cnt)
1122 return pIOSubSystem->pfnread(fd, buf, cnt);
1126 win32_write(int fd, const void *buf, unsigned int cnt)
1128 return pIOSubSystem->pfnwrite(fd, buf, cnt);
1132 win32_mkdir(const char *dir, int mode)
1134 return pIOSubSystem->pfnmkdir(dir); /* just ignore mode */
1138 win32_rmdir(const char *dir)
1140 return pIOSubSystem->pfnrmdir(dir);
1144 win32_chdir(const char *dir)
1146 return pIOSubSystem->pfnchdir(dir);
1150 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
1152 return pIOSubSystem->pfnspawnvp(mode, cmdname, argv);
1156 win32_execvp(const char *cmdname, const char *const *argv)
1158 return pIOSubSystem->pfnexecvp(cmdname, argv);
1162 stolen_open_osfhandle(long handle, int flags)
1164 return pIOSubSystem->pfn_open_osfhandle(handle, flags);
1168 stolen_get_osfhandle(int fd)
1170 return pIOSubSystem->pfn_get_osfhandle(fd);
1178 win32_flock(int fd, int oper)
1181 croak("flock() unimplemented on this platform");
1184 return pIOSubSystem->pfnflock(fd, oper);