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;
44 #define IsWin95() (Win32System == VER_PLATFORM_WIN32_WINDOWS)
45 #define IsWinNT() (Win32System == VER_PLATFORM_WIN32_NT)
48 SetIOSubSystem(void *p)
51 PWIN32_IOSUBSYSTEM pio = (PWIN32_IOSUBSYSTEM)p;
53 if (pio->signature_begin == 12345678L
54 && pio->signature_end == 87654321L) {
55 PWIN32_IOSUBSYSTEM pold = pIOSubSystem;
61 /* re-assign our stuff */
62 /* pIOSubSystem = &win32stdio; */
69 win32PerlLibPath(void)
72 GetModuleFileName((PerlDllHandle == INVALID_HANDLE_VALUE)
73 ? GetModuleHandle(NULL)
76 sizeof(szPerlLibRoot));
78 *(end = strrchr(szPerlLibRoot, '\\')) = '\0';
79 if (stricmp(end-4,"\\bin") == 0)
82 return (szPerlLibRoot);
86 HasRedirection(char *ptr)
92 * Scan string looking for redirection (< or >) or pipe
93 * characters (|) that are not in a quoted string
123 /* since the current process environment is being updated in util.c
124 * the library functions will get the correct environment
127 my_popen(char *cmd, char *mode)
130 #define fixcmd(x) { \
131 char *pspace = strchr((x),' '); \
134 while (p < pspace) { \
146 /* was #ifndef PERLDLL, but the #else stuff doesn't work on NT
150 return win32_popen(cmd, mode);
153 * There seems to be some problems for the _popen call in a DLL
154 * this trick at the moment seems to work but it is never test
159 #define EXT_C_FUNC extern "C"
161 #define EXT_C_FUNC extern
164 EXT_C_FUNC int __cdecl _set_osfhnd(int fh, long value);
165 EXT_C_FUNC void __cdecl _lock_fhandle(int);
166 EXT_C_FUNC void __cdecl _unlock_fhandle(int);
169 PerlIO *pf; /* to store the _popen return value */
170 int tm = 0; /* flag indicating tDllExport or binary mode */
171 int fhNeeded, fhInherited, fhDup;
172 int ineeded, iinherited;
174 int phdls[2]; /* I/O handles for pipe */
175 HANDLE hPIn, hPOut, hPErr,
176 hSaveStdin, hSaveStdout, hSaveStderr,
177 hPNeeded, hPInherited, hPDuped;
179 /* first check for errors in the arguments */
180 if ( (cmd == NULL) || (mode == NULL)
181 || ((*mode != 'w') && (*mode != _T('r'))) )
184 if ( *(mode + 1) == _T('t') )
186 else if ( *(mode + 1) == _T('b') )
189 tm = (*mode == 'w' ? _O_BINARY : _O_TEXT);
193 if (&win32stdio != pIOSubSystem)
194 return win32_popen(cmd, mode);
197 if ( _pipe( phdls, 1024, tm ) == -1 )
199 if ( win32_pipe( phdls, 1024, tm ) == -1 )
203 /* save the current situation */
204 hSaveStdin = GetStdHandle(STD_INPUT_HANDLE);
205 hSaveStdout = GetStdHandle(STD_OUTPUT_HANDLE);
206 hSaveStderr = GetStdHandle(STD_ERROR_HANDLE);
208 if (*mode == _T('w')) {
210 dwDup = STD_INPUT_HANDLE;
215 dwDup = STD_OUTPUT_HANDLE;
219 fhNeeded = phdls[ineeded];
220 fhInherited = phdls[iinherited];
222 fSuccess = DuplicateHandle(GetCurrentProcess(),
223 (HANDLE) stolen_get_osfhandle(fhNeeded),
227 FALSE, /* not inherited */
228 DUPLICATE_SAME_ACCESS);
233 fhDup = stolen_open_osfhandle((long) hPNeeded, tm);
234 win32_dup2(fhDup, fhNeeded);
238 /* Close the Out pipe, child won't need it */
239 hPDuped = (HANDLE) stolen_get_osfhandle(fhNeeded);
241 _lock_fhandle(fhNeeded);
242 _set_osfhnd(fhNeeded, (long)hPNeeded); /* put in ours duplicated one */
243 _unlock_fhandle(fhNeeded);
245 CloseHandle(hPDuped); /* close the handle first */
248 if (!SetStdHandle(dwDup, (HANDLE) stolen_get_osfhandle(fhInherited)))
252 * make sure the child see the same stderr as the calling program
254 if (!SetStdHandle(STD_ERROR_HANDLE,
255 (HANDLE)stolen_get_osfhandle(win32_fileno(win32_stderr()))))
258 pf = win32_popen(cmd, mode); /* ask _popen to do the job */
260 /* restore to where we were */
261 SetStdHandle(STD_INPUT_HANDLE, hSaveStdin);
262 SetStdHandle(STD_OUTPUT_HANDLE, hSaveStdout);
263 SetStdHandle(STD_ERROR_HANDLE, hSaveStderr);
265 /* we don't need it any more, that's for the child */
266 win32_close(fhInherited);
269 /* something wrong */
270 win32_close(fhNeeded);
275 * here we steal the file handle in pf and stuff ours in
277 win32_dup2(fhNeeded, win32_fileno(pf));
278 win32_close(fhNeeded);
283 win32_close(fhNeeded);
284 win32_close(fhInherited);
293 my_pclose(PerlIO *fp)
295 return win32_pclose(fp);
303 memset(&osver, 0, sizeof(OSVERSIONINFO));
304 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
305 GetVersionEx(&osver);
306 Win32System = osver.dwPlatformId;
313 static char* szWin95ShellEntry = "Win95Shell";
314 static char* szWin95DefaultShell = "Cmd32.exe";
315 static char* szWinNTDefaultShell = "cmd.exe";
318 IdOS(), ProbeEnv = TRUE;
320 strcpy(szShellPath, szWin95DefaultShell);
323 strcpy(szShellPath, szWinNTDefaultShell);
330 do_aspawn(void* really, void** mark, void** arglast)
338 SV *sv = (SV*)really;
339 SV** pSv = (SV**)mark;
341 New(1110, argv, (arglast - mark) + 3, char*);
344 cmd = SvPV(sv, length);
348 argv[index++] = "/c";
351 while(pSv <= (SV**)arglast) {
353 strPtr = SvPV(sv, length);
354 if(strPtr != NULL && *strPtr != '\0')
355 argv[index++] = strPtr;
359 status = win32_spawnvpe(P_WAIT, cmd, (const char* const*)argv,
360 (const char* const*)environ);
364 /* set statusvalue the perl variable $? */
365 return (statusvalue = status*256);
375 BOOL needToTry = TRUE;
378 /* save an extra exec if possible */
381 /* see if there are shell metacharacters in it */
382 if(!HasRedirection(cmd)) {
383 New(1102,argv, strlen(cmd) / 2 + 2, char*);
384 New(1103,cmd2, strlen(cmd) + 1, char);
387 for (s = cmd2; *s;) {
388 while (*s && isspace(*s))
392 while(*s && !isspace(*s))
399 status = win32_spawnvpe(P_WAIT,
401 (const char* const*)argv,
402 (const char* const*)environ);
403 if(status != -1 || errno == 0)
410 status = win32_spawnle(P_WAIT,
413 "/c", cmd, (char*)0, environ);
416 /* set statusvalue the perl variable $? */
417 return (statusvalue = status*256);
423 /* The idea here is to read all the directory names into a string table
424 * (separated by nulls) and when one of the other dir functions is called
425 * return the pointer to the current file name.
428 opendir(char *filename)
433 char scannamespc[PATHLEN];
434 char *scanname = scannamespc;
436 WIN32_FIND_DATA FindData;
438 /* char root[_MAX_PATH];*/
439 /* char volname[_MAX_PATH];*/
440 /* DWORD serial, maxname, flags;*/
444 /* check to see if filename is a directory */
445 if(stat(filename, &sbuf) < 0 || sbuf.st_mode & _S_IFDIR == 0) {
449 /* get the file system characteristics */
450 /* if(GetFullPathName(filename, MAX_PATH, root, &dummy)) {
451 * if(dummy = strchr(root, '\\'))
453 * if(GetVolumeInformation(root, volname, MAX_PATH, &serial,
454 * &maxname, &flags, 0, 0)) {
455 * downcase = !(flags & FS_CASE_IS_PRESERVED);
462 /* Get us a DIR structure */
463 Newz(1501, p, 1, DIR);
467 /* Create the search pattern */
468 strcpy(scanname, filename);
470 if(index("/\\", *(scanname + strlen(scanname) - 1)) == NULL)
471 strcat(scanname, "/*");
473 strcat(scanname, "*");
475 /* do the FindFirstFile call */
476 fh = FindFirstFile(scanname, &FindData);
477 if(fh == INVALID_HANDLE_VALUE) {
481 /* now allocate the first part of the string table for
482 * the filenames that we find.
484 idx = strlen(FindData.cFileName)+1;
485 New(1502, p->start, idx, char);
486 if(p->start == NULL) {
487 CROAK("opendir: malloc failed!\n");
489 strcpy(p->start, FindData.cFileName);
495 /* loop finding all the files that match the wildcard
496 * (which should be all of them in this directory!).
497 * the variable idx should point one past the null terminator
498 * of the previous string found.
500 while (FindNextFile(fh, &FindData)) {
501 len = strlen(FindData.cFileName);
502 /* bump the string table size by enough for the
503 * new name and it's null terminator
505 Renew(p->start, idx+len+1, char);
506 if(p->start == NULL) {
507 CROAK("opendir: malloc failed!\n");
509 strcpy(&p->start[idx], FindData.cFileName);
511 * strlwr(&p->start[idx]);
523 /* Readdir just returns the current string pointer and bumps the
524 * string pointer to the nDllExport entry.
530 static int dummy = 0;
533 /* first set up the structure to return */
534 len = strlen(dirp->curr);
535 strcpy(dirp->dirstr.d_name, dirp->curr);
536 dirp->dirstr.d_namlen = len;
539 dirp->dirstr.d_ino = dummy++;
541 /* Now set up for the nDllExport call to readdir */
542 dirp->curr += len + 1;
543 if (dirp->curr >= (dirp->start + dirp->size)) {
547 return &(dirp->dirstr);
553 /* Telldir returns the current string pointer position */
557 return (long) dirp->curr;
561 /* Seekdir moves the string pointer to a previously saved position
565 seekdir(DIR *dirp, long loc)
567 dirp->curr = (char *)loc;
570 /* Rewinddir resets the string pointer to the start */
574 dirp->curr = dirp->start;
577 /* free the memory allocated by opendir */
581 Safefree(dirp->start);
594 * Just pretend that everyone is a superuser. NT will let us know if
595 * we don\'t really have permission to do something.
598 #define ROOT_UID ((uid_t)0)
599 #define ROOT_GID ((gid_t)0)
628 return (uid == ROOT_UID ? 0 : -1);
634 return (gid == ROOT_GID ? 0 : -1);
641 kill(int pid, int sig)
643 HANDLE hProcess= OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
645 if (hProcess == NULL) {
646 CROAK("kill process failed!\n");
649 if (!TerminateProcess(hProcess, sig))
650 CROAK("kill process failed!\n");
651 CloseHandle(hProcess);
661 ioctl(int i, unsigned int u, char *data)
663 CROAK("ioctl not implemented!\n");
668 sleep(unsigned int t)
678 myrename(char *OldFileName, char *newname)
680 if(_access(newname, 0) != -1) { /* file exists */
683 return rename(OldFileName, newname);
688 win32_stat(const char *path, struct stat *buffer)
691 const char *p = path;
692 int l = strlen(path);
695 switch(path[l - 1]) {
698 if (path[l - 2] != ':') {
699 strncpy(t, path, l - 1);
705 return stat(p, buffer);
710 mytimes(struct tms *timebuf)
713 timebuf->tms_utime = t;
714 timebuf->tms_stime = 0;
715 timebuf->tms_cutime = 0;
716 timebuf->tms_cstime = 0;
723 myalarm(unsigned int sec)
725 /* we warn the usuage of alarm function */
727 WARN("dummy function alarm called, program might not function as expected\n");
732 * redirected io subsystem for all XS modules
739 return (pIOSubSystem->pfnerrno());
742 /* the rest are the remapped stdio routines */
746 return (pIOSubSystem->pfnstderr());
752 return (pIOSubSystem->pfnstdin());
758 return (pIOSubSystem->pfnstdout());
762 win32_ferror(FILE *fp)
764 return (pIOSubSystem->pfnferror(fp));
771 return (pIOSubSystem->pfnfeof(fp));
775 * Since the errors returned by the socket error function
776 * WSAGetLastError() are not known by the library routine strerror
777 * we have to roll our own.
780 __declspec(thread) char strerror_buffer[512];
783 win32_strerror(int e)
788 if(e < 0 || e > sys_nerr) {
792 if(FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
793 strerror_buffer, sizeof(strerror_buffer), NULL) == 0)
794 strcpy(strerror_buffer, "Unknown Error");
796 return strerror_buffer;
798 return pIOSubSystem->pfnstrerror(e);
802 win32_fprintf(FILE *fp, const char *format, ...)
805 va_start(marker, format); /* Initialize variable arguments. */
807 return (pIOSubSystem->pfnvfprintf(fp, format, marker));
811 win32_printf(const char *format, ...)
814 va_start(marker, format); /* Initialize variable arguments. */
816 return (pIOSubSystem->pfnvprintf(format, marker));
820 win32_vfprintf(FILE *fp, const char *format, va_list args)
822 return (pIOSubSystem->pfnvfprintf(fp, format, args));
826 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
828 return pIOSubSystem->pfnfread(buf, size, count, fp);
832 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
834 return pIOSubSystem->pfnfwrite(buf, size, count, fp);
838 win32_fopen(const char *filename, const char *mode)
840 if (stricmp(filename, "/dev/null")==0)
841 return pIOSubSystem->pfnfopen("NUL", mode);
842 return pIOSubSystem->pfnfopen(filename, mode);
846 win32_fdopen( int handle, const char *mode)
848 return pIOSubSystem->pfnfdopen(handle, mode);
852 win32_freopen( const char *path, const char *mode, FILE *stream)
854 if (stricmp(path, "/dev/null")==0)
855 return pIOSubSystem->pfnfreopen("NUL", mode, stream);
856 return pIOSubSystem->pfnfreopen(path, mode, stream);
860 win32_fclose(FILE *pf)
862 return pIOSubSystem->pfnfclose(pf);
866 win32_fputs(const char *s,FILE *pf)
868 return pIOSubSystem->pfnfputs(s, pf);
872 win32_fputc(int c,FILE *pf)
874 return pIOSubSystem->pfnfputc(c,pf);
878 win32_ungetc(int c,FILE *pf)
880 return pIOSubSystem->pfnungetc(c,pf);
886 return pIOSubSystem->pfngetc(pf);
890 win32_fileno(FILE *pf)
892 return pIOSubSystem->pfnfileno(pf);
896 win32_clearerr(FILE *pf)
898 pIOSubSystem->pfnclearerr(pf);
903 win32_fflush(FILE *pf)
905 return pIOSubSystem->pfnfflush(pf);
909 win32_ftell(FILE *pf)
911 return pIOSubSystem->pfnftell(pf);
915 win32_fseek(FILE *pf,long offset,int origin)
917 return pIOSubSystem->pfnfseek(pf, offset, origin);
921 win32_fgetpos(FILE *pf,fpos_t *p)
923 return pIOSubSystem->pfnfgetpos(pf, p);
927 win32_fsetpos(FILE *pf,const fpos_t *p)
929 return pIOSubSystem->pfnfsetpos(pf, p);
933 win32_rewind(FILE *pf)
935 pIOSubSystem->pfnrewind(pf);
942 return pIOSubSystem->pfntmpfile();
948 pIOSubSystem->pfnabort();
953 win32_fstat(int fd,struct stat *bufptr)
955 return pIOSubSystem->pfnfstat(fd,bufptr);
959 win32_pipe(int *pfd, unsigned int size, int mode)
961 return pIOSubSystem->pfnpipe(pfd, size, mode);
965 win32_popen(const char *command, const char *mode)
967 return pIOSubSystem->pfnpopen(command, mode);
971 win32_pclose(FILE *pf)
973 return pIOSubSystem->pfnpclose(pf);
977 win32_setmode(int fd, int mode)
979 return pIOSubSystem->pfnsetmode(fd, mode);
983 win32_open(const char *path, int flag, ...)
989 pmode = va_arg(ap, int);
992 if (stricmp(path, "/dev/null")==0)
993 return pIOSubSystem->pfnopen("NUL", flag, pmode);
994 return pIOSubSystem->pfnopen(path,flag,pmode);
1000 return pIOSubSystem->pfnclose(fd);
1006 return pIOSubSystem->pfndup(fd);
1010 win32_dup2(int fd1,int fd2)
1012 return pIOSubSystem->pfndup2(fd1,fd2);
1016 win32_read(int fd, char *buf, unsigned int cnt)
1018 return pIOSubSystem->pfnread(fd, buf, cnt);
1022 win32_write(int fd, const char *buf, unsigned int cnt)
1024 return pIOSubSystem->pfnwrite(fd, buf, cnt);
1028 win32_spawnvpe(int mode, const char *cmdname,
1029 const char *const *argv, const char *const *envp)
1031 return pIOSubSystem->pfnspawnvpe(mode, cmdname, argv, envp);
1035 win32_spawnle(int mode, const char *cmdname, const char *arglist,...)
1037 const char* const* envp;
1038 const char* const* argp;
1043 return pIOSubSystem->pfnspawnvpe(mode, cmdname, &arglist, argp);
1047 stolen_open_osfhandle(long handle, int flags)
1049 return pIOSubSystem->pfn_open_osfhandle(handle, flags);
1053 stolen_get_osfhandle(int fd)
1055 return pIOSubSystem->pfn_get_osfhandle(fd);