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 extern WIN32_IOSUBSYSTEM win32stdio;
35 __declspec(thread) PWIN32_IOSUBSYSTEM pIOSubSystem = &win32stdio;
36 /*__declspec(thread) PWIN32_IOSUBSYSTEM pIOSubSystem = NULL;*/
38 BOOL ProbeEnv = FALSE;
40 char szShellPath[MAX_PATH+1];
41 char szPerlLibRoot[MAX_PATH+1];
42 HANDLE PerlDllHandle = INVALID_HANDLE_VALUE;
46 return (Win32System == VER_PLATFORM_WIN32_WINDOWS);
51 return (Win32System == VER_PLATFORM_WIN32_NT);
55 SetIOSubSystem(void *p)
57 PWIN32_IOSUBSYSTEM old = pIOSubSystem;
59 PWIN32_IOSUBSYSTEM pio = (PWIN32_IOSUBSYSTEM)p;
60 if (pio->signature_begin == 12345678L
61 && pio->signature_end == 87654321L) {
66 pIOSubSystem = &win32stdio;
72 win32PerlLibPath(void)
75 GetModuleFileName((PerlDllHandle == INVALID_HANDLE_VALUE)
76 ? GetModuleHandle(NULL)
79 sizeof(szPerlLibRoot));
81 *(end = strrchr(szPerlLibRoot, '\\')) = '\0';
82 if (stricmp(end-4,"\\bin") == 0)
85 return (szPerlLibRoot);
89 HasRedirection(char *ptr)
95 * Scan string looking for redirection (< or >) or pipe
96 * characters (|) that are not in a quoted string
126 /* since the current process environment is being updated in util.c
127 * the library functions will get the correct environment
130 my_popen(char *cmd, char *mode)
133 #define fixcmd(x) { \
134 char *pspace = strchr((x),' '); \
137 while (p < pspace) { \
149 /* was #ifndef PERLDLL, but the #else stuff doesn't work on NT
153 return win32_popen(cmd, mode);
156 * There seems to be some problems for the _popen call in a DLL
157 * this trick at the moment seems to work but it is never test
162 #define EXT_C_FUNC extern "C"
164 #define EXT_C_FUNC extern
167 EXT_C_FUNC int __cdecl _set_osfhnd(int fh, long value);
168 EXT_C_FUNC void __cdecl _lock_fhandle(int);
169 EXT_C_FUNC void __cdecl _unlock_fhandle(int);
172 PerlIO *pf; /* to store the _popen return value */
173 int tm = 0; /* flag indicating tDllExport or binary mode */
174 int fhNeeded, fhInherited, fhDup;
175 int ineeded, iinherited;
177 int phdls[2]; /* I/O handles for pipe */
178 HANDLE hPIn, hPOut, hPErr,
179 hSaveStdin, hSaveStdout, hSaveStderr,
180 hPNeeded, hPInherited, hPDuped;
182 /* first check for errors in the arguments */
183 if ( (cmd == NULL) || (mode == NULL)
184 || ((*mode != 'w') && (*mode != _T('r'))) )
187 if ( *(mode + 1) == _T('t') )
189 else if ( *(mode + 1) == _T('b') )
192 tm = (*mode == 'w' ? _O_BINARY : _O_TEXT);
196 if (&win32stdio != pIOSubSystem)
197 return win32_popen(cmd, mode);
200 if ( _pipe( phdls, 1024, tm ) == -1 )
202 if ( win32_pipe( phdls, 1024, tm ) == -1 )
206 /* save the current situation */
207 hSaveStdin = GetStdHandle(STD_INPUT_HANDLE);
208 hSaveStdout = GetStdHandle(STD_OUTPUT_HANDLE);
209 hSaveStderr = GetStdHandle(STD_ERROR_HANDLE);
211 if (*mode == _T('w')) {
213 dwDup = STD_INPUT_HANDLE;
218 dwDup = STD_OUTPUT_HANDLE;
222 fhNeeded = phdls[ineeded];
223 fhInherited = phdls[iinherited];
225 fSuccess = DuplicateHandle(GetCurrentProcess(),
226 (HANDLE) stolen_get_osfhandle(fhNeeded),
230 FALSE, /* not inherited */
231 DUPLICATE_SAME_ACCESS);
236 fhDup = stolen_open_osfhandle((long) hPNeeded, tm);
237 win32_dup2(fhDup, fhNeeded);
241 /* Close the Out pipe, child won't need it */
242 hPDuped = (HANDLE) stolen_get_osfhandle(fhNeeded);
244 _lock_fhandle(fhNeeded);
245 _set_osfhnd(fhNeeded, (long)hPNeeded); /* put in ours duplicated one */
246 _unlock_fhandle(fhNeeded);
248 CloseHandle(hPDuped); /* close the handle first */
251 if (!SetStdHandle(dwDup, (HANDLE) stolen_get_osfhandle(fhInherited)))
255 * make sure the child see the same stderr as the calling program
257 if (!SetStdHandle(STD_ERROR_HANDLE,
258 (HANDLE)stolen_get_osfhandle(win32_fileno(win32_stderr()))))
261 pf = win32_popen(cmd, mode); /* ask _popen to do the job */
263 /* restore to where we were */
264 SetStdHandle(STD_INPUT_HANDLE, hSaveStdin);
265 SetStdHandle(STD_OUTPUT_HANDLE, hSaveStdout);
266 SetStdHandle(STD_ERROR_HANDLE, hSaveStderr);
268 /* we don't need it any more, that's for the child */
269 win32_close(fhInherited);
272 /* something wrong */
273 win32_close(fhNeeded);
278 * here we steal the file handle in pf and stuff ours in
280 win32_dup2(fhNeeded, win32_fileno(pf));
281 win32_close(fhNeeded);
286 win32_close(fhNeeded);
287 win32_close(fhInherited);
296 my_pclose(PerlIO *fp)
298 return win32_pclose(fp);
306 memset(&osver, 0, sizeof(OSVERSIONINFO));
307 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
308 GetVersionEx(&osver);
309 Win32System = osver.dwPlatformId;
316 static char* szWin95ShellEntry = "Win95Shell";
317 static char* szWin95DefaultShell = "Cmd32.exe";
318 static char* szWinNTDefaultShell = "cmd.exe";
321 IdOS(), ProbeEnv = TRUE;
323 strcpy(szShellPath, szWin95DefaultShell);
326 strcpy(szShellPath, szWinNTDefaultShell);
333 do_aspawn(void* really, void** mark, void** arglast)
341 SV *sv = (SV*)really;
342 SV** pSv = (SV**)mark;
344 New(1110, argv, (arglast - mark) + 4, char*);
347 cmd = SvPV(sv, length);
350 argv[index++] = cmd = GetShell();
351 argv[index++] = "/x"; /* always enable command extensions */
352 argv[index++] = "/c";
355 while(++pSv <= (SV**)arglast) {
357 strPtr = SvPV(sv, length);
358 if(strPtr != NULL && *strPtr != '\0')
359 argv[index++] = strPtr;
363 status = win32_spawnvpe(P_WAIT, cmd, (const char* const*)argv,
364 (const char* const*)environ);
370 warn("Can't spawn \"%s\": %s", cmd, strerror(errno));
383 BOOL needToTry = TRUE;
386 /* save an extra exec if possible */
389 /* see if there are shell metacharacters in it */
390 if(!HasRedirection(cmd)) {
391 New(1102,argv, strlen(cmd) / 2 + 2, char*);
392 New(1103,cmd2, strlen(cmd) + 1, char);
395 for (s = cmd2; *s;) {
396 while (*s && isspace(*s))
400 while(*s && !isspace(*s))
407 status = win32_spawnvpe(P_WAIT,
409 (const char* const*)argv,
410 (const char* const*)environ);
411 if(status != -1 || errno == 0)
418 status = win32_spawnle(P_WAIT,
422 "/c", cmd, (char*)0, environ);
426 warn("Can't spawn \"%s\": %s", needToTry ? shell : argv[0],
436 /* The idea here is to read all the directory names into a string table
437 * (separated by nulls) and when one of the other dir functions is called
438 * return the pointer to the current file name.
441 opendir(char *filename)
446 char scannamespc[PATHLEN];
447 char *scanname = scannamespc;
449 WIN32_FIND_DATA FindData;
451 /* char root[_MAX_PATH];*/
452 /* char volname[_MAX_PATH];*/
453 /* DWORD serial, maxname, flags;*/
457 /* check to see if filename is a directory */
458 if(stat(filename, &sbuf) < 0 || sbuf.st_mode & _S_IFDIR == 0) {
462 /* get the file system characteristics */
463 /* if(GetFullPathName(filename, MAX_PATH, root, &dummy)) {
464 * if(dummy = strchr(root, '\\'))
466 * if(GetVolumeInformation(root, volname, MAX_PATH, &serial,
467 * &maxname, &flags, 0, 0)) {
468 * downcase = !(flags & FS_CASE_IS_PRESERVED);
475 /* Get us a DIR structure */
476 Newz(1501, p, 1, DIR);
480 /* Create the search pattern */
481 strcpy(scanname, filename);
483 if(index("/\\", *(scanname + strlen(scanname) - 1)) == NULL)
484 strcat(scanname, "/*");
486 strcat(scanname, "*");
488 /* do the FindFirstFile call */
489 fh = FindFirstFile(scanname, &FindData);
490 if(fh == INVALID_HANDLE_VALUE) {
494 /* now allocate the first part of the string table for
495 * the filenames that we find.
497 idx = strlen(FindData.cFileName)+1;
498 New(1502, p->start, idx, char);
499 if(p->start == NULL) {
500 CROAK("opendir: malloc failed!\n");
502 strcpy(p->start, FindData.cFileName);
508 /* loop finding all the files that match the wildcard
509 * (which should be all of them in this directory!).
510 * the variable idx should point one past the null terminator
511 * of the previous string found.
513 while (FindNextFile(fh, &FindData)) {
514 len = strlen(FindData.cFileName);
515 /* bump the string table size by enough for the
516 * new name and it's null terminator
518 Renew(p->start, idx+len+1, char);
519 if(p->start == NULL) {
520 CROAK("opendir: malloc failed!\n");
522 strcpy(&p->start[idx], FindData.cFileName);
524 * strlwr(&p->start[idx]);
536 /* Readdir just returns the current string pointer and bumps the
537 * string pointer to the nDllExport entry.
543 static int dummy = 0;
546 /* first set up the structure to return */
547 len = strlen(dirp->curr);
548 strcpy(dirp->dirstr.d_name, dirp->curr);
549 dirp->dirstr.d_namlen = len;
552 dirp->dirstr.d_ino = dummy++;
554 /* Now set up for the nDllExport call to readdir */
555 dirp->curr += len + 1;
556 if (dirp->curr >= (dirp->start + dirp->size)) {
560 return &(dirp->dirstr);
566 /* Telldir returns the current string pointer position */
570 return (long) dirp->curr;
574 /* Seekdir moves the string pointer to a previously saved position
578 seekdir(DIR *dirp, long loc)
580 dirp->curr = (char *)loc;
583 /* Rewinddir resets the string pointer to the start */
587 dirp->curr = dirp->start;
590 /* free the memory allocated by opendir */
594 Safefree(dirp->start);
607 * Just pretend that everyone is a superuser. NT will let us know if
608 * we don\'t really have permission to do something.
611 #define ROOT_UID ((uid_t)0)
612 #define ROOT_GID ((gid_t)0)
641 return (uid == ROOT_UID ? 0 : -1);
647 return (gid == ROOT_GID ? 0 : -1);
654 kill(int pid, int sig)
656 HANDLE hProcess= OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
658 if (hProcess == NULL) {
659 CROAK("kill process failed!\n");
662 if (!TerminateProcess(hProcess, sig))
663 CROAK("kill process failed!\n");
664 CloseHandle(hProcess);
674 ioctl(int i, unsigned int u, char *data)
676 CROAK("ioctl not implemented!\n");
681 sleep(unsigned int t)
691 myrename(char *OldFileName, char *newname)
693 if(_access(newname, 0) != -1) { /* file exists */
696 return rename(OldFileName, newname);
701 win32_stat(const char *path, struct stat *buffer)
704 const char *p = path;
705 int l = strlen(path);
708 switch(path[l - 1]) {
711 if (path[l - 2] != ':') {
712 strncpy(t, path, l - 1);
718 return stat(p, buffer);
723 mytimes(struct tms *timebuf)
726 timebuf->tms_utime = t;
727 timebuf->tms_stime = 0;
728 timebuf->tms_cutime = 0;
729 timebuf->tms_cstime = 0;
736 myalarm(unsigned int sec)
738 /* we warn the usuage of alarm function */
740 WARN("dummy function alarm called, program might not function as expected\n");
745 * redirected io subsystem for all XS modules
752 return (pIOSubSystem->pfnerrno());
758 return (pIOSubSystem->pfnenviron());
761 /* the rest are the remapped stdio routines */
765 return (pIOSubSystem->pfnstderr());
771 return (pIOSubSystem->pfnstdin());
777 return (pIOSubSystem->pfnstdout());
781 win32_ferror(FILE *fp)
783 return (pIOSubSystem->pfnferror(fp));
790 return (pIOSubSystem->pfnfeof(fp));
794 * Since the errors returned by the socket error function
795 * WSAGetLastError() are not known by the library routine strerror
796 * we have to roll our own.
799 __declspec(thread) char strerror_buffer[512];
802 win32_strerror(int e)
807 if(e < 0 || e > sys_nerr) {
811 if(FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
812 strerror_buffer, sizeof(strerror_buffer), NULL) == 0)
813 strcpy(strerror_buffer, "Unknown Error");
815 return strerror_buffer;
817 return pIOSubSystem->pfnstrerror(e);
821 win32_fprintf(FILE *fp, const char *format, ...)
824 va_start(marker, format); /* Initialize variable arguments. */
826 return (pIOSubSystem->pfnvfprintf(fp, format, marker));
830 win32_printf(const char *format, ...)
833 va_start(marker, format); /* Initialize variable arguments. */
835 return (pIOSubSystem->pfnvprintf(format, marker));
839 win32_vfprintf(FILE *fp, const char *format, va_list args)
841 return (pIOSubSystem->pfnvfprintf(fp, format, args));
845 win32_vprintf(const char *format, va_list args)
847 return (pIOSubSystem->pfnvprintf(format, args));
851 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
853 return pIOSubSystem->pfnfread(buf, size, count, fp);
857 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
859 return pIOSubSystem->pfnfwrite(buf, size, count, fp);
863 win32_fopen(const char *filename, const char *mode)
865 if (stricmp(filename, "/dev/null")==0)
866 return pIOSubSystem->pfnfopen("NUL", mode);
867 return pIOSubSystem->pfnfopen(filename, mode);
871 win32_fdopen( int handle, const char *mode)
873 return pIOSubSystem->pfnfdopen(handle, mode);
877 win32_freopen( const char *path, const char *mode, FILE *stream)
879 if (stricmp(path, "/dev/null")==0)
880 return pIOSubSystem->pfnfreopen("NUL", mode, stream);
881 return pIOSubSystem->pfnfreopen(path, mode, stream);
885 win32_fclose(FILE *pf)
887 return pIOSubSystem->pfnfclose(pf);
891 win32_fputs(const char *s,FILE *pf)
893 return pIOSubSystem->pfnfputs(s, pf);
897 win32_fputc(int c,FILE *pf)
899 return pIOSubSystem->pfnfputc(c,pf);
903 win32_ungetc(int c,FILE *pf)
905 return pIOSubSystem->pfnungetc(c,pf);
911 return pIOSubSystem->pfngetc(pf);
915 win32_fileno(FILE *pf)
917 return pIOSubSystem->pfnfileno(pf);
921 win32_clearerr(FILE *pf)
923 pIOSubSystem->pfnclearerr(pf);
928 win32_fflush(FILE *pf)
930 return pIOSubSystem->pfnfflush(pf);
934 win32_ftell(FILE *pf)
936 return pIOSubSystem->pfnftell(pf);
940 win32_fseek(FILE *pf,long offset,int origin)
942 return pIOSubSystem->pfnfseek(pf, offset, origin);
946 win32_fgetpos(FILE *pf,fpos_t *p)
948 return pIOSubSystem->pfnfgetpos(pf, p);
952 win32_fsetpos(FILE *pf,const fpos_t *p)
954 return pIOSubSystem->pfnfsetpos(pf, p);
958 win32_rewind(FILE *pf)
960 pIOSubSystem->pfnrewind(pf);
967 return pIOSubSystem->pfntmpfile();
973 pIOSubSystem->pfnabort();
978 win32_fstat(int fd,struct stat *bufptr)
980 return pIOSubSystem->pfnfstat(fd,bufptr);
984 win32_pipe(int *pfd, unsigned int size, int mode)
986 return pIOSubSystem->pfnpipe(pfd, size, mode);
990 win32_popen(const char *command, const char *mode)
992 return pIOSubSystem->pfnpopen(command, mode);
996 win32_pclose(FILE *pf)
998 return pIOSubSystem->pfnpclose(pf);
1002 win32_setmode(int fd, int mode)
1004 return pIOSubSystem->pfnsetmode(fd, mode);
1008 win32_lseek(int fd, long offset, int origin)
1010 return pIOSubSystem->pfnlseek(fd, offset, origin);
1016 return pIOSubSystem->pfntell(fd);
1020 win32_open(const char *path, int flag, ...)
1026 pmode = va_arg(ap, int);
1029 if (stricmp(path, "/dev/null")==0)
1030 return pIOSubSystem->pfnopen("NUL", flag, pmode);
1031 return pIOSubSystem->pfnopen(path,flag,pmode);
1037 return pIOSubSystem->pfnclose(fd);
1043 return pIOSubSystem->pfneof(fd);
1049 return pIOSubSystem->pfndup(fd);
1053 win32_dup2(int fd1,int fd2)
1055 return pIOSubSystem->pfndup2(fd1,fd2);
1059 win32_read(int fd, char *buf, unsigned int cnt)
1061 return pIOSubSystem->pfnread(fd, buf, cnt);
1065 win32_write(int fd, const char *buf, unsigned int cnt)
1067 return pIOSubSystem->pfnwrite(fd, buf, cnt);
1071 win32_mkdir(const char *dir, int mode)
1073 return pIOSubSystem->pfnmkdir(dir); /* just ignore mode */
1077 win32_rmdir(const char *dir)
1079 return pIOSubSystem->pfnrmdir(dir);
1083 win32_chdir(const char *dir)
1085 return pIOSubSystem->pfnchdir(dir);
1089 win32_spawnvpe(int mode, const char *cmdname,
1090 const char *const *argv, const char *const *envp)
1092 return pIOSubSystem->pfnspawnvpe(mode, cmdname, argv, envp);
1096 win32_spawnle(int mode, const char *cmdname, const char *arglist,...)
1098 const char* const* envp;
1099 const char* const* argp;
1103 envp = (const char* const*)*argp;
1105 return pIOSubSystem->pfnspawnvpe(mode, cmdname, &arglist, envp);
1109 stolen_open_osfhandle(long handle, int flags)
1111 return pIOSubSystem->pfn_open_osfhandle(handle, flags);
1115 stolen_get_osfhandle(int fd)
1117 return pIOSubSystem->pfn_get_osfhandle(fd);