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)
58 PWIN32_IOSUBSYSTEM pio = (PWIN32_IOSUBSYSTEM)p;
60 if (pio->signature_begin == 12345678L
61 && pio->signature_end == 87654321L) {
62 PWIN32_IOSUBSYSTEM pold = pIOSubSystem;
68 /* re-assign our stuff */
69 /* 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 return win32_popen(cmd, mode);
160 * There seems to be some problems for the _popen call in a DLL
161 * this trick at the moment seems to work but it is never test
166 #define EXT_C_FUNC extern "C"
168 #define EXT_C_FUNC extern
171 EXT_C_FUNC int __cdecl _set_osfhnd(int fh, long value);
172 EXT_C_FUNC void __cdecl _lock_fhandle(int);
173 EXT_C_FUNC void __cdecl _unlock_fhandle(int);
176 PerlIO *pf; /* to store the _popen return value */
177 int tm = 0; /* flag indicating tDllExport or binary mode */
178 int fhNeeded, fhInherited, fhDup;
179 int ineeded, iinherited;
181 int phdls[2]; /* I/O handles for pipe */
182 HANDLE hPIn, hPOut, hPErr,
183 hSaveStdin, hSaveStdout, hSaveStderr,
184 hPNeeded, hPInherited, hPDuped;
186 /* first check for errors in the arguments */
187 if ( (cmd == NULL) || (mode == NULL)
188 || ((*mode != 'w') && (*mode != _T('r'))) )
191 if ( *(mode + 1) == _T('t') )
193 else if ( *(mode + 1) == _T('b') )
196 tm = (*mode == 'w' ? _O_BINARY : _O_TEXT);
200 if (&win32stdio != pIOSubSystem)
201 return win32_popen(cmd, mode);
204 if ( _pipe( phdls, 1024, tm ) == -1 )
206 if ( win32_pipe( phdls, 1024, tm ) == -1 )
210 /* save the current situation */
211 hSaveStdin = GetStdHandle(STD_INPUT_HANDLE);
212 hSaveStdout = GetStdHandle(STD_OUTPUT_HANDLE);
213 hSaveStderr = GetStdHandle(STD_ERROR_HANDLE);
215 if (*mode == _T('w')) {
217 dwDup = STD_INPUT_HANDLE;
222 dwDup = STD_OUTPUT_HANDLE;
226 fhNeeded = phdls[ineeded];
227 fhInherited = phdls[iinherited];
229 fSuccess = DuplicateHandle(GetCurrentProcess(),
230 (HANDLE) stolen_get_osfhandle(fhNeeded),
234 FALSE, /* not inherited */
235 DUPLICATE_SAME_ACCESS);
240 fhDup = stolen_open_osfhandle((long) hPNeeded, tm);
241 win32_dup2(fhDup, fhNeeded);
245 /* Close the Out pipe, child won't need it */
246 hPDuped = (HANDLE) stolen_get_osfhandle(fhNeeded);
248 _lock_fhandle(fhNeeded);
249 _set_osfhnd(fhNeeded, (long)hPNeeded); /* put in ours duplicated one */
250 _unlock_fhandle(fhNeeded);
252 CloseHandle(hPDuped); /* close the handle first */
255 if (!SetStdHandle(dwDup, (HANDLE) stolen_get_osfhandle(fhInherited)))
259 * make sure the child see the same stderr as the calling program
261 if (!SetStdHandle(STD_ERROR_HANDLE,
262 (HANDLE)stolen_get_osfhandle(win32_fileno(win32_stderr()))))
265 pf = win32_popen(cmd, mode); /* ask _popen to do the job */
267 /* restore to where we were */
268 SetStdHandle(STD_INPUT_HANDLE, hSaveStdin);
269 SetStdHandle(STD_OUTPUT_HANDLE, hSaveStdout);
270 SetStdHandle(STD_ERROR_HANDLE, hSaveStderr);
272 /* we don't need it any more, that's for the child */
273 win32_close(fhInherited);
276 /* something wrong */
277 win32_close(fhNeeded);
282 * here we steal the file handle in pf and stuff ours in
284 win32_dup2(fhNeeded, win32_fileno(pf));
285 win32_close(fhNeeded);
290 win32_close(fhNeeded);
291 win32_close(fhInherited);
300 my_pclose(PerlIO *fp)
302 return win32_pclose(fp);
310 memset(&osver, 0, sizeof(OSVERSIONINFO));
311 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
312 GetVersionEx(&osver);
313 Win32System = osver.dwPlatformId;
320 static char* szWin95ShellEntry = "Win95Shell";
321 static char* szWin95DefaultShell = "Cmd32.exe";
322 static char* szWinNTDefaultShell = "cmd.exe";
325 IdOS(), ProbeEnv = TRUE;
327 strcpy(szShellPath, szWin95DefaultShell);
330 strcpy(szShellPath, szWinNTDefaultShell);
337 do_aspawn(void* really, void** mark, void** arglast)
345 SV *sv = (SV*)really;
346 SV** pSv = (SV**)mark;
348 New(1110, argv, (arglast - mark) + 3, char*);
351 cmd = SvPV(sv, length);
354 argv[index++] = cmd = GetShell();
355 argv[index++] = "/x"; /* always enable command extensions */
356 argv[index++] = "/c";
359 while(pSv <= (SV**)arglast) {
361 strPtr = SvPV(sv, length);
362 if(strPtr != NULL && *strPtr != '\0')
363 argv[index++] = strPtr;
367 status = win32_spawnvpe(P_WAIT, cmd, (const char* const*)argv,
368 (const char* const*)environ);
372 /* set statusvalue the perl variable $? */
373 return (statusvalue = status*256);
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);
425 /* set statusvalue the perl variable $? */
426 return (statusvalue = status*256);
432 /* The idea here is to read all the directory names into a string table
433 * (separated by nulls) and when one of the other dir functions is called
434 * return the pointer to the current file name.
437 opendir(char *filename)
442 char scannamespc[PATHLEN];
443 char *scanname = scannamespc;
445 WIN32_FIND_DATA FindData;
447 /* char root[_MAX_PATH];*/
448 /* char volname[_MAX_PATH];*/
449 /* DWORD serial, maxname, flags;*/
453 /* check to see if filename is a directory */
454 if(stat(filename, &sbuf) < 0 || sbuf.st_mode & _S_IFDIR == 0) {
458 /* get the file system characteristics */
459 /* if(GetFullPathName(filename, MAX_PATH, root, &dummy)) {
460 * if(dummy = strchr(root, '\\'))
462 * if(GetVolumeInformation(root, volname, MAX_PATH, &serial,
463 * &maxname, &flags, 0, 0)) {
464 * downcase = !(flags & FS_CASE_IS_PRESERVED);
471 /* Get us a DIR structure */
472 Newz(1501, p, 1, DIR);
476 /* Create the search pattern */
477 strcpy(scanname, filename);
479 if(index("/\\", *(scanname + strlen(scanname) - 1)) == NULL)
480 strcat(scanname, "/*");
482 strcat(scanname, "*");
484 /* do the FindFirstFile call */
485 fh = FindFirstFile(scanname, &FindData);
486 if(fh == INVALID_HANDLE_VALUE) {
490 /* now allocate the first part of the string table for
491 * the filenames that we find.
493 idx = strlen(FindData.cFileName)+1;
494 New(1502, p->start, idx, char);
495 if(p->start == NULL) {
496 CROAK("opendir: malloc failed!\n");
498 strcpy(p->start, FindData.cFileName);
504 /* loop finding all the files that match the wildcard
505 * (which should be all of them in this directory!).
506 * the variable idx should point one past the null terminator
507 * of the previous string found.
509 while (FindNextFile(fh, &FindData)) {
510 len = strlen(FindData.cFileName);
511 /* bump the string table size by enough for the
512 * new name and it's null terminator
514 Renew(p->start, idx+len+1, char);
515 if(p->start == NULL) {
516 CROAK("opendir: malloc failed!\n");
518 strcpy(&p->start[idx], FindData.cFileName);
520 * strlwr(&p->start[idx]);
532 /* Readdir just returns the current string pointer and bumps the
533 * string pointer to the nDllExport entry.
539 static int dummy = 0;
542 /* first set up the structure to return */
543 len = strlen(dirp->curr);
544 strcpy(dirp->dirstr.d_name, dirp->curr);
545 dirp->dirstr.d_namlen = len;
548 dirp->dirstr.d_ino = dummy++;
550 /* Now set up for the nDllExport call to readdir */
551 dirp->curr += len + 1;
552 if (dirp->curr >= (dirp->start + dirp->size)) {
556 return &(dirp->dirstr);
562 /* Telldir returns the current string pointer position */
566 return (long) dirp->curr;
570 /* Seekdir moves the string pointer to a previously saved position
574 seekdir(DIR *dirp, long loc)
576 dirp->curr = (char *)loc;
579 /* Rewinddir resets the string pointer to the start */
583 dirp->curr = dirp->start;
586 /* free the memory allocated by opendir */
590 Safefree(dirp->start);
603 * Just pretend that everyone is a superuser. NT will let us know if
604 * we don\'t really have permission to do something.
607 #define ROOT_UID ((uid_t)0)
608 #define ROOT_GID ((gid_t)0)
637 return (uid == ROOT_UID ? 0 : -1);
643 return (gid == ROOT_GID ? 0 : -1);
650 kill(int pid, int sig)
652 HANDLE hProcess= OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
654 if (hProcess == NULL) {
655 CROAK("kill process failed!\n");
658 if (!TerminateProcess(hProcess, sig))
659 CROAK("kill process failed!\n");
660 CloseHandle(hProcess);
670 ioctl(int i, unsigned int u, char *data)
672 CROAK("ioctl not implemented!\n");
677 sleep(unsigned int t)
687 myrename(char *OldFileName, char *newname)
689 if(_access(newname, 0) != -1) { /* file exists */
692 return rename(OldFileName, newname);
697 win32_stat(const char *path, struct stat *buffer)
700 const char *p = path;
701 int l = strlen(path);
704 switch(path[l - 1]) {
707 if (path[l - 2] != ':') {
708 strncpy(t, path, l - 1);
714 return stat(p, buffer);
719 mytimes(struct tms *timebuf)
722 timebuf->tms_utime = t;
723 timebuf->tms_stime = 0;
724 timebuf->tms_cutime = 0;
725 timebuf->tms_cstime = 0;
732 myalarm(unsigned int sec)
734 /* we warn the usuage of alarm function */
736 WARN("dummy function alarm called, program might not function as expected\n");
741 * redirected io subsystem for all XS modules
748 return (pIOSubSystem->pfnerrno());
751 /* the rest are the remapped stdio routines */
755 return (pIOSubSystem->pfnstderr());
761 return (pIOSubSystem->pfnstdin());
767 return (pIOSubSystem->pfnstdout());
771 win32_ferror(FILE *fp)
773 return (pIOSubSystem->pfnferror(fp));
780 return (pIOSubSystem->pfnfeof(fp));
784 * Since the errors returned by the socket error function
785 * WSAGetLastError() are not known by the library routine strerror
786 * we have to roll our own.
789 __declspec(thread) char strerror_buffer[512];
792 win32_strerror(int e)
797 if(e < 0 || e > sys_nerr) {
801 if(FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
802 strerror_buffer, sizeof(strerror_buffer), NULL) == 0)
803 strcpy(strerror_buffer, "Unknown Error");
805 return strerror_buffer;
807 return pIOSubSystem->pfnstrerror(e);
811 win32_fprintf(FILE *fp, const char *format, ...)
814 va_start(marker, format); /* Initialize variable arguments. */
816 return (pIOSubSystem->pfnvfprintf(fp, format, marker));
820 win32_printf(const char *format, ...)
823 va_start(marker, format); /* Initialize variable arguments. */
825 return (pIOSubSystem->pfnvprintf(format, marker));
829 win32_vfprintf(FILE *fp, const char *format, va_list args)
831 return (pIOSubSystem->pfnvfprintf(fp, format, args));
835 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
837 return pIOSubSystem->pfnfread(buf, size, count, fp);
841 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
843 return pIOSubSystem->pfnfwrite(buf, size, count, fp);
847 win32_fopen(const char *filename, const char *mode)
849 if (stricmp(filename, "/dev/null")==0)
850 return pIOSubSystem->pfnfopen("NUL", mode);
851 return pIOSubSystem->pfnfopen(filename, mode);
855 win32_fdopen( int handle, const char *mode)
857 return pIOSubSystem->pfnfdopen(handle, mode);
861 win32_freopen( const char *path, const char *mode, FILE *stream)
863 if (stricmp(path, "/dev/null")==0)
864 return pIOSubSystem->pfnfreopen("NUL", mode, stream);
865 return pIOSubSystem->pfnfreopen(path, mode, stream);
869 win32_fclose(FILE *pf)
871 return pIOSubSystem->pfnfclose(pf);
875 win32_fputs(const char *s,FILE *pf)
877 return pIOSubSystem->pfnfputs(s, pf);
881 win32_fputc(int c,FILE *pf)
883 return pIOSubSystem->pfnfputc(c,pf);
887 win32_ungetc(int c,FILE *pf)
889 return pIOSubSystem->pfnungetc(c,pf);
895 return pIOSubSystem->pfngetc(pf);
899 win32_fileno(FILE *pf)
901 return pIOSubSystem->pfnfileno(pf);
905 win32_clearerr(FILE *pf)
907 pIOSubSystem->pfnclearerr(pf);
912 win32_fflush(FILE *pf)
914 return pIOSubSystem->pfnfflush(pf);
918 win32_ftell(FILE *pf)
920 return pIOSubSystem->pfnftell(pf);
924 win32_fseek(FILE *pf,long offset,int origin)
926 return pIOSubSystem->pfnfseek(pf, offset, origin);
930 win32_fgetpos(FILE *pf,fpos_t *p)
932 return pIOSubSystem->pfnfgetpos(pf, p);
936 win32_fsetpos(FILE *pf,const fpos_t *p)
938 return pIOSubSystem->pfnfsetpos(pf, p);
942 win32_rewind(FILE *pf)
944 pIOSubSystem->pfnrewind(pf);
951 return pIOSubSystem->pfntmpfile();
957 pIOSubSystem->pfnabort();
962 win32_fstat(int fd,struct stat *bufptr)
964 return pIOSubSystem->pfnfstat(fd,bufptr);
968 win32_pipe(int *pfd, unsigned int size, int mode)
970 return pIOSubSystem->pfnpipe(pfd, size, mode);
974 win32_popen(const char *command, const char *mode)
976 return pIOSubSystem->pfnpopen(command, mode);
980 win32_pclose(FILE *pf)
982 return pIOSubSystem->pfnpclose(pf);
986 win32_setmode(int fd, int mode)
988 return pIOSubSystem->pfnsetmode(fd, mode);
992 win32_open(const char *path, int flag, ...)
998 pmode = va_arg(ap, int);
1001 if (stricmp(path, "/dev/null")==0)
1002 return pIOSubSystem->pfnopen("NUL", flag, pmode);
1003 return pIOSubSystem->pfnopen(path,flag,pmode);
1009 return pIOSubSystem->pfnclose(fd);
1015 return pIOSubSystem->pfndup(fd);
1019 win32_dup2(int fd1,int fd2)
1021 return pIOSubSystem->pfndup2(fd1,fd2);
1025 win32_read(int fd, char *buf, unsigned int cnt)
1027 return pIOSubSystem->pfnread(fd, buf, cnt);
1031 win32_write(int fd, const char *buf, unsigned int cnt)
1033 return pIOSubSystem->pfnwrite(fd, buf, cnt);
1037 win32_spawnvpe(int mode, const char *cmdname,
1038 const char *const *argv, const char *const *envp)
1040 return pIOSubSystem->pfnspawnvpe(mode, cmdname, argv, envp);
1044 win32_spawnle(int mode, const char *cmdname, const char *arglist,...)
1046 const char* const* envp;
1047 const char* const* argp;
1051 envp = (const char* const*)*argp;
1053 return pIOSubSystem->pfnspawnvpe(mode, cmdname, &arglist, envp);
1057 stolen_open_osfhandle(long handle, int flags)
1059 return pIOSubSystem->pfn_open_osfhandle(handle, flags);
1063 stolen_get_osfhandle(int fd)
1065 return pIOSubSystem->pfn_get_osfhandle(fd);