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
19 /* #include "config.h" */
21 #define PERLIO_NOT_STDIO 0
22 #if !defined(PERLIO_IS_STDIO) && !defined(USE_SFIO)
31 extern CPerlObj* pPerl;
39 /* assert.h conflicts with #define of assert in perl.h */
46 #if defined(_MSC_VER) || defined(__MINGW32__)
47 #include <sys/utime.h>
53 /* Mingw32 defaults to globing command line
54 * So we turn it off like this:
61 #define EXECF_SPAWN_NOWAIT 3
63 #if defined(PERL_OBJECT)
64 #undef win32_perllib_path
65 #define win32_perllib_path g_win32_perllib_path
67 #define do_aspawn g_do_aspawn
69 #define do_spawn g_do_spawn
71 #define do_exec g_do_exec
73 #define opendir g_opendir
75 #define readdir g_readdir
77 #define telldir g_telldir
79 #define seekdir g_seekdir
81 #define rewinddir g_rewinddir
83 #define closedir g_closedir
85 #define getlogin g_getlogin
88 static DWORD os_id(void);
89 static void get_shell(void);
90 static long tokenize(char *str, char **dest, char ***destv);
91 int do_spawn2(char *cmd, int exectype);
92 static BOOL has_redirection(char *ptr);
93 static long filetime_to_clock(PFILETIME ft);
94 static BOOL filetime_from_time(PFILETIME ft, time_t t);
97 char * w32_perlshell_tokens = Nullch;
98 char ** w32_perlshell_vec;
99 long w32_perlshell_items = -1;
100 DWORD w32_platform = (DWORD)-1;
101 char w32_perllib_root[MAX_PATH+1];
102 HANDLE w32_perldll_handle = INVALID_HANDLE_VALUE;
104 long w32_num_children = 0;
105 HANDLE w32_child_pids[MAXIMUM_WAIT_OBJECTS];
110 # define FOPEN_MAX _NSTREAM_
112 # define FOPEN_MAX _NFILE_
114 # define FOPEN_MAX _NFILE
118 #ifndef USE_CRT_POPEN
119 int w32_popen_pids[FOPEN_MAX];
123 # ifdef USE_DECLSPEC_THREAD
124 __declspec(thread) char strerror_buffer[512];
125 __declspec(thread) char getlogin_buffer[128];
126 # ifdef HAVE_DES_FCRYPT
127 __declspec(thread) char crypt_buffer[30];
130 # define strerror_buffer (thr->i.Wstrerror_buffer)
131 # define getlogin_buffer (thr->i.Wgetlogin_buffer)
132 # define crypt_buffer (thr->i.Wcrypt_buffer)
135 char strerror_buffer[512];
136 char getlogin_buffer[128];
137 # ifdef HAVE_DES_FCRYPT
138 char crypt_buffer[30];
144 return (os_id() == VER_PLATFORM_WIN32_WINDOWS);
149 return (os_id() == VER_PLATFORM_WIN32_NT);
153 win32_perllib_path(char *sfx,...)
158 GetModuleFileName((w32_perldll_handle == INVALID_HANDLE_VALUE)
159 ? GetModuleHandle(NULL)
160 : w32_perldll_handle,
162 sizeof(w32_perllib_root));
163 *(end = strrchr(w32_perllib_root, '\\')) = '\0';
164 if (stricmp(end-4,"\\bin") == 0)
171 sfx = va_arg(ap,char *);
174 return (w32_perllib_root);
179 has_redirection(char *ptr)
185 * Scan string looking for redirection (< or >) or pipe
186 * characters (|) that are not in a quoted string
216 #if !defined(PERL_OBJECT)
217 /* since the current process environment is being updated in util.c
218 * the library functions will get the correct environment
221 my_popen(char *cmd, char *mode)
224 #define fixcmd(x) { \
225 char *pspace = strchr((x),' '); \
228 while (p < pspace) { \
239 win32_fflush(stdout);
240 win32_fflush(stderr);
241 return win32_popen(cmd, mode);
245 my_pclose(PerlIO *fp)
247 return win32_pclose(fp);
254 static OSVERSIONINFO osver;
256 if (osver.dwPlatformId != w32_platform) {
257 memset(&osver, 0, sizeof(OSVERSIONINFO));
258 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
259 GetVersionEx(&osver);
260 w32_platform = osver.dwPlatformId;
262 return (w32_platform);
265 /* Tokenize a string. Words are null-separated, and the list
266 * ends with a doubled null. Any character (except null and
267 * including backslash) may be escaped by preceding it with a
268 * backslash (the backslash will be stripped).
269 * Returns number of words in result buffer.
272 tokenize(char *str, char **dest, char ***destv)
274 char *retstart = Nullch;
275 char **retvstart = 0;
278 int slen = strlen(str);
280 register char **retv;
281 New(1307, ret, slen+2, char);
282 New(1308, retv, (slen+3)/2, char*);
290 if (*ret == '\\' && *str)
292 else if (*ret == ' ') {
308 retvstart[items] = Nullch;
320 if (!w32_perlshell_tokens) {
321 /* we don't use COMSPEC here for two reasons:
322 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
323 * uncontrolled unportability of the ensuing scripts.
324 * 2. PERL5SHELL could be set to a shell that may not be fit for
325 * interactive use (which is what most programs look in COMSPEC
328 char* defaultshell = (IsWinNT() ? "cmd.exe /x/c" : "command.com /c");
329 char *usershell = getenv("PERL5SHELL");
330 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
331 &w32_perlshell_tokens,
337 do_aspawn(void *vreally, void **vmark, void **vsp)
339 SV *really = (SV*)vreally;
340 SV **mark = (SV**)vmark;
352 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
354 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
359 while(++mark <= sp) {
360 if (*mark && (str = SvPV(*mark, na)))
367 status = win32_spawnvp(flag,
368 (const char*)(really ? SvPV(really,na) : argv[0]),
369 (const char* const*)argv);
371 if (status < 0 && errno == ENOEXEC) {
372 /* possible shell-builtin, invoke with shell */
374 sh_items = w32_perlshell_items;
376 argv[index+sh_items] = argv[index];
377 while (--sh_items >= 0)
378 argv[sh_items] = w32_perlshell_vec[sh_items];
380 status = win32_spawnvp(flag,
381 (const char*)(really ? SvPV(really,na) : argv[0]),
382 (const char* const*)argv);
385 if (flag != P_NOWAIT) {
388 warn("Can't spawn \"%s\": %s", argv[0], strerror(errno));
393 statusvalue = status;
400 do_spawn2(char *cmd, int exectype)
406 BOOL needToTry = TRUE;
409 /* Save an extra exec if possible. See if there are shell
410 * metacharacters in it */
411 if(!has_redirection(cmd)) {
412 New(1301,argv, strlen(cmd) / 2 + 2, char*);
413 New(1302,cmd2, strlen(cmd) + 1, char);
416 for (s = cmd2; *s;) {
417 while (*s && isspace(*s))
421 while(*s && !isspace(*s))
430 status = win32_spawnvp(P_WAIT, argv[0],
431 (const char* const*)argv);
433 case EXECF_SPAWN_NOWAIT:
434 status = win32_spawnvp(P_NOWAIT, argv[0],
435 (const char* const*)argv);
438 status = win32_execvp(argv[0], (const char* const*)argv);
441 if (status != -1 || errno == 0)
451 New(1306, argv, w32_perlshell_items + 2, char*);
452 while (++i < w32_perlshell_items)
453 argv[i] = w32_perlshell_vec[i];
458 status = win32_spawnvp(P_WAIT, argv[0],
459 (const char* const*)argv);
461 case EXECF_SPAWN_NOWAIT:
462 status = win32_spawnvp(P_NOWAIT, argv[0],
463 (const char* const*)argv);
466 status = win32_execvp(argv[0], (const char* const*)argv);
472 if (exectype != EXECF_SPAWN_NOWAIT) {
475 warn("Can't %s \"%s\": %s",
476 (exectype == EXECF_EXEC ? "exec" : "spawn"),
477 cmd, strerror(errno));
482 statusvalue = status;
490 return do_spawn2(cmd, EXECF_SPAWN);
494 do_spawn_nowait(char *cmd)
496 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
502 do_spawn2(cmd, EXECF_EXEC);
509 /* The idea here is to read all the directory names into a string table
510 * (separated by nulls) and when one of the other dir functions is called
511 * return the pointer to the current file name.
514 opendir(char *filename)
519 char scannamespc[PATHLEN];
520 char *scanname = scannamespc;
522 WIN32_FIND_DATA FindData;
524 /* char root[_MAX_PATH];*/
525 /* char volname[_MAX_PATH];*/
526 /* DWORD serial, maxname, flags;*/
530 /* check to see if filename is a directory */
531 if (win32_stat(filename, &sbuf) < 0 || (sbuf.st_mode & S_IFDIR) == 0) {
532 /* CRT is buggy on sharenames, so make sure it really isn't */
533 DWORD r = GetFileAttributes(filename);
534 if (r == 0xffffffff || !(r & FILE_ATTRIBUTE_DIRECTORY))
538 /* get the file system characteristics */
539 /* if(GetFullPathName(filename, MAX_PATH, root, &dummy)) {
540 * if(dummy = strchr(root, '\\'))
542 * if(GetVolumeInformation(root, volname, MAX_PATH, &serial,
543 * &maxname, &flags, 0, 0)) {
544 * downcase = !(flags & FS_CASE_IS_PRESERVED);
551 /* Get us a DIR structure */
552 Newz(1303, p, 1, DIR);
556 /* Create the search pattern */
557 strcpy(scanname, filename);
559 if(index("/\\", *(scanname + strlen(scanname) - 1)) == NULL)
560 strcat(scanname, "/*");
562 strcat(scanname, "*");
564 /* do the FindFirstFile call */
565 fh = FindFirstFile(scanname, &FindData);
566 if(fh == INVALID_HANDLE_VALUE) {
570 /* now allocate the first part of the string table for
571 * the filenames that we find.
573 idx = strlen(FindData.cFileName)+1;
574 New(1304, p->start, idx, char);
575 if(p->start == NULL) {
576 croak("opendir: malloc failed!\n");
578 strcpy(p->start, FindData.cFileName);
584 /* loop finding all the files that match the wildcard
585 * (which should be all of them in this directory!).
586 * the variable idx should point one past the null terminator
587 * of the previous string found.
589 while (FindNextFile(fh, &FindData)) {
590 len = strlen(FindData.cFileName);
591 /* bump the string table size by enough for the
592 * new name and it's null terminator
594 Renew(p->start, idx+len+1, char);
595 if(p->start == NULL) {
596 croak("opendir: malloc failed!\n");
598 strcpy(&p->start[idx], FindData.cFileName);
600 * strlwr(&p->start[idx]);
612 /* Readdir just returns the current string pointer and bumps the
613 * string pointer to the nDllExport entry.
619 static int dummy = 0;
622 /* first set up the structure to return */
623 len = strlen(dirp->curr);
624 strcpy(dirp->dirstr.d_name, dirp->curr);
625 dirp->dirstr.d_namlen = len;
628 dirp->dirstr.d_ino = dummy++;
630 /* Now set up for the nDllExport call to readdir */
631 dirp->curr += len + 1;
632 if (dirp->curr >= (dirp->start + dirp->size)) {
636 return &(dirp->dirstr);
642 /* Telldir returns the current string pointer position */
646 return (long) dirp->curr;
650 /* Seekdir moves the string pointer to a previously saved position
654 seekdir(DIR *dirp, long loc)
656 dirp->curr = (char *)loc;
659 /* Rewinddir resets the string pointer to the start */
663 dirp->curr = dirp->start;
666 /* free the memory allocated by opendir */
670 Safefree(dirp->start);
683 * Just pretend that everyone is a superuser. NT will let us know if
684 * we don\'t really have permission to do something.
687 #define ROOT_UID ((uid_t)0)
688 #define ROOT_GID ((gid_t)0)
717 return (auid == ROOT_UID ? 0 : -1);
723 return (agid == ROOT_GID ? 0 : -1);
730 char *buf = getlogin_buffer;
731 DWORD size = sizeof(getlogin_buffer);
732 if (GetUserName(buf,&size))
738 chown(const char *path, uid_t owner, gid_t group)
745 kill(int pid, int sig)
747 HANDLE hProcess= OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
749 if (hProcess == NULL) {
750 croak("kill process failed!\n");
753 if (!TerminateProcess(hProcess, sig))
754 croak("kill process failed!\n");
755 CloseHandle(hProcess);
764 DllExport unsigned int
765 win32_sleep(unsigned int t)
772 win32_stat(const char *path, struct stat *buffer)
775 const char *p = path;
776 int l = strlen(path);
780 switch(path[l - 1]) {
783 if (path[l - 2] != ':') {
784 strncpy(t, path, l - 1);
790 res = stat(p,buffer);
793 if (S_ISDIR(buffer->st_mode))
794 buffer->st_mode |= S_IWRITE | S_IEXEC;
795 else if (S_ISREG(buffer->st_mode)) {
796 if (l >= 4 && path[l-4] == '.') {
797 const char *e = path + l - 3;
798 if (strnicmp(e,"exe",3)
799 && strnicmp(e,"bat",3)
800 && strnicmp(e,"com",3)
801 && (IsWin95() || strnicmp(e,"cmd",3)))
802 buffer->st_mode &= ~S_IEXEC;
804 buffer->st_mode |= S_IEXEC;
807 buffer->st_mode &= ~S_IEXEC;
814 #ifndef USE_WIN32_RTL_ENV
816 BOOL GetRegStr(HKEY hkey, const char *lpszValueName, char *lpszDefault, char *lpszData, unsigned long *lpdwDataLen)
817 { // Retrieve a REG_SZ or REG_EXPAND_SZ from the registry
819 DWORD type, dwDataLen = *lpdwDataLen;
820 const char *subkey = "Software\\Perl";
821 char szBuffer[MAX_PATH+1];
824 retval = RegOpenKeyEx(hkey, subkey, 0, KEY_READ, &handle);
825 if(retval == ERROR_SUCCESS)
827 retval = RegQueryValueEx(handle, lpszValueName, 0, &type, (LPBYTE)lpszData, &dwDataLen);
829 if(retval == ERROR_SUCCESS && (type == REG_SZ || type == REG_EXPAND_SZ))
831 if(type != REG_EXPAND_SZ)
833 *lpdwDataLen = dwDataLen;
836 strcpy(szBuffer, lpszData);
837 dwDataLen = ExpandEnvironmentStrings(szBuffer, lpszData, *lpdwDataLen);
838 if(dwDataLen < *lpdwDataLen)
840 *lpdwDataLen = dwDataLen;
846 strcpy(lpszData, lpszDefault);
850 char* GetRegStr(const char *lpszValueName, char *lpszDefault, char *lpszData, unsigned long *lpdwDataLen)
852 if(!GetRegStr(HKEY_CURRENT_USER, lpszValueName, lpszDefault, lpszData, lpdwDataLen))
854 GetRegStr(HKEY_LOCAL_MACHINE, lpszValueName, lpszDefault, lpszData, lpdwDataLen);
856 if(*lpszData == '\0')
862 win32_getenv(const char *name)
864 static char *curitem = Nullch;
865 static DWORD curlen = 512;
868 New(1305,curitem,curlen,char);
869 if (!(needlen = GetEnvironmentVariable(name,curitem,curlen)))
871 while (needlen > curlen) {
872 Renew(curitem,needlen,char);
874 needlen = GetEnvironmentVariable(name,curitem,curlen);
878 unsigned long dwDataLen = curlen;
879 if(strcmp("PERL5DB", name) == 0)
880 curitem = GetRegStr(name, "", curitem, &dwDataLen);
888 filetime_to_clock(PFILETIME ft)
890 __int64 qw = ft->dwHighDateTime;
892 qw |= ft->dwLowDateTime;
893 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
898 win32_times(struct tms *timebuf)
903 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
905 timebuf->tms_utime = filetime_to_clock(&user);
906 timebuf->tms_stime = filetime_to_clock(&kernel);
907 timebuf->tms_cutime = 0;
908 timebuf->tms_cstime = 0;
911 /* That failed - e.g. Win95 fallback to clock() */
913 timebuf->tms_utime = t;
914 timebuf->tms_stime = 0;
915 timebuf->tms_cutime = 0;
916 timebuf->tms_cstime = 0;
921 /* fix utime() so it works on directories in NT
922 * thanks to Jan Dubois <jan.dubois@ibm.net>
925 filetime_from_time(PFILETIME pFileTime, time_t Time)
927 struct tm *pTM = gmtime(&Time);
928 SYSTEMTIME SystemTime;
933 SystemTime.wYear = pTM->tm_year + 1900;
934 SystemTime.wMonth = pTM->tm_mon + 1;
935 SystemTime.wDay = pTM->tm_mday;
936 SystemTime.wHour = pTM->tm_hour;
937 SystemTime.wMinute = pTM->tm_min;
938 SystemTime.wSecond = pTM->tm_sec;
939 SystemTime.wMilliseconds = 0;
941 return SystemTimeToFileTime(&SystemTime, pFileTime);
945 win32_utime(const char *filename, struct utimbuf *times)
951 struct utimbuf TimeBuffer;
953 int rc = utime(filename,times);
954 /* EACCES: path specifies directory or readonly file */
955 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
960 time(×->actime);
961 times->modtime = times->actime;
964 /* This will (and should) still fail on readonly files */
965 handle = CreateFile(filename, GENERIC_READ | GENERIC_WRITE,
966 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
967 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
968 if (handle == INVALID_HANDLE_VALUE)
971 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
972 filetime_from_time(&ftAccess, times->actime) &&
973 filetime_from_time(&ftWrite, times->modtime) &&
974 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
984 win32_wait(int *status)
989 /* XXX this wait emulation only knows about processes
990 * spawned via win32_spawnvp(P_NOWAIT, ...).
993 DWORD exitcode, waitcode;
995 if (!w32_num_children) {
1000 /* if a child exists, wait for it to die */
1001 waitcode = WaitForMultipleObjects(w32_num_children,
1005 if (waitcode != WAIT_FAILED) {
1006 if (waitcode >= WAIT_ABANDONED_0
1007 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1008 i = waitcode - WAIT_ABANDONED_0;
1010 i = waitcode - WAIT_OBJECT_0;
1011 if (GetExitCodeProcess(w32_child_pids[i], &exitcode) ) {
1012 CloseHandle(w32_child_pids[i]);
1013 *status = (int)((exitcode & 0xff) << 8);
1014 retval = (int)w32_child_pids[i];
1015 Copy(&w32_child_pids[i+1], &w32_child_pids[i],
1016 (w32_num_children-i-1), HANDLE);
1023 errno = GetLastError();
1029 static UINT timerid = 0;
1031 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1033 KillTimer(NULL,timerid);
1038 DllExport unsigned int
1039 win32_alarm(unsigned int sec)
1042 * the 'obvious' implentation is SetTimer() with a callback
1043 * which does whatever receiving SIGALRM would do
1044 * we cannot use SIGALRM even via raise() as it is not
1045 * one of the supported codes in <signal.h>
1047 * Snag is unless something is looking at the message queue
1048 * nothing happens :-(
1052 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1054 croak("Cannot set timer");
1060 KillTimer(NULL,timerid);
1067 #ifdef HAVE_DES_FCRYPT
1068 extern char * des_fcrypt(char *cbuf, const char *txt, const char *salt);
1071 win32_crypt(const char *txt, const char *salt)
1074 return des_fcrypt(crypt_buffer, txt, salt);
1078 #ifdef USE_FIXED_OSFHANDLE
1080 EXTERN_C int __cdecl _alloc_osfhnd(void);
1081 EXTERN_C int __cdecl _set_osfhnd(int fh, long value);
1082 EXTERN_C void __cdecl _lock_fhandle(int);
1083 EXTERN_C void __cdecl _unlock_fhandle(int);
1084 EXTERN_C void __cdecl _unlock(int);
1086 #if (_MSC_VER >= 1000)
1088 long osfhnd; /* underlying OS file HANDLE */
1089 char osfile; /* attributes of file (e.g., open in text mode?) */
1090 char pipech; /* one char buffer for handles opened on pipes */
1091 #if defined (_MT) && !defined (DLL_FOR_WIN32S)
1093 CRITICAL_SECTION lock;
1094 #endif /* defined (_MT) && !defined (DLL_FOR_WIN32S) */
1097 EXTERN_C ioinfo * __pioinfo[];
1099 #define IOINFO_L2E 5
1100 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
1101 #define _pioinfo(i) (__pioinfo[i >> IOINFO_L2E] + (i & (IOINFO_ARRAY_ELTS - 1)))
1102 #define _osfile(i) (_pioinfo(i)->osfile)
1104 #else /* (_MSC_VER >= 1000) */
1105 extern char _osfile[];
1106 #endif /* (_MSC_VER >= 1000) */
1108 #define FOPEN 0x01 /* file handle open */
1109 #define FAPPEND 0x20 /* file handle opened O_APPEND */
1110 #define FDEV 0x40 /* file handle refers to device */
1111 #define FTEXT 0x80 /* file handle is in text mode */
1113 #define _STREAM_LOCKS 26 /* Table of stream locks */
1114 #define _LAST_STREAM_LOCK (_STREAM_LOCKS+_NSTREAM_-1) /* Last stream lock */
1115 #define _FH_LOCKS (_LAST_STREAM_LOCK+1) /* Table of fh locks */
1118 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1121 * This function allocates a free C Runtime file handle and associates
1122 * it with the Win32 HANDLE specified by the first parameter. This is a
1123 * temperary fix for WIN95's brain damage GetFileType() error on socket
1124 * we just bypass that call for socket
1127 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1128 * int flags - flags to associate with C Runtime file handle.
1131 * returns index of entry in fh, if successful
1132 * return -1, if no free entry is found
1136 *******************************************************************************/
1139 my_open_osfhandle(long osfhandle, int flags)
1142 char fileflags; /* _osfile flags */
1144 /* copy relevant flags from second parameter */
1147 if(flags & O_APPEND)
1148 fileflags |= FAPPEND;
1153 /* attempt to allocate a C Runtime file handle */
1154 if((fh = _alloc_osfhnd()) == -1) {
1155 errno = EMFILE; /* too many open files */
1156 _doserrno = 0L; /* not an OS error */
1157 return -1; /* return error to caller */
1160 /* the file is open. now, set the info in _osfhnd array */
1161 _set_osfhnd(fh, osfhandle);
1163 fileflags |= FOPEN; /* mark as open */
1165 #if (_MSC_VER >= 1000)
1166 _osfile(fh) = fileflags; /* set osfile entry */
1167 _unlock_fhandle(fh);
1169 _osfile[fh] = fileflags; /* set osfile entry */
1170 _unlock(fh+_FH_LOCKS); /* unlock handle */
1173 return fh; /* return handle */
1176 #define _open_osfhandle my_open_osfhandle
1177 #endif /* USE_FIXED_OSFHANDLE */
1179 /* simulate flock by locking a range on the file */
1181 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1182 #define LK_LEN 0xffff0000
1185 win32_flock(int fd, int oper)
1192 croak("flock() unimplemented on this platform");
1195 fh = (HANDLE)_get_osfhandle(fd);
1196 memset(&o, 0, sizeof(o));
1199 case LOCK_SH: /* shared lock */
1200 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1202 case LOCK_EX: /* exclusive lock */
1203 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1205 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1206 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1208 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1209 LK_ERR(LockFileEx(fh,
1210 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1211 0, LK_LEN, 0, &o),i);
1213 case LOCK_UN: /* unlock lock */
1214 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1216 default: /* unknown */
1227 * redirected io subsystem for all XS modules
1240 return (&(_environ));
1243 /* the rest are the remapped stdio routines */
1263 win32_ferror(FILE *fp)
1265 return (ferror(fp));
1270 win32_feof(FILE *fp)
1276 * Since the errors returned by the socket error function
1277 * WSAGetLastError() are not known by the library routine strerror
1278 * we have to roll our own.
1282 win32_strerror(int e)
1284 #ifndef __BORLANDC__ /* Borland intolerance */
1285 extern int sys_nerr;
1289 if(e < 0 || e > sys_nerr) {
1294 if(FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
1295 strerror_buffer, sizeof(strerror_buffer), NULL) == 0)
1296 strcpy(strerror_buffer, "Unknown Error");
1298 return strerror_buffer;
1304 win32_str_os_error(void *sv, DWORD dwErr)
1308 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
1309 |FORMAT_MESSAGE_IGNORE_INSERTS
1310 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
1311 dwErr, 0, (char *)&sMsg, 1, NULL);
1313 while (0 < dwLen && isspace(sMsg[--dwLen]))
1315 if ('.' != sMsg[dwLen])
1320 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
1321 dwLen = sprintf(sMsg,
1322 "Unknown error #0x%lX (lookup 0x%lX)",
1323 dwErr, GetLastError());
1325 sv_setpvn((SV*)sv, sMsg, dwLen);
1331 win32_fprintf(FILE *fp, const char *format, ...)
1334 va_start(marker, format); /* Initialize variable arguments. */
1336 return (vfprintf(fp, format, marker));
1340 win32_printf(const char *format, ...)
1343 va_start(marker, format); /* Initialize variable arguments. */
1345 return (vprintf(format, marker));
1349 win32_vfprintf(FILE *fp, const char *format, va_list args)
1351 return (vfprintf(fp, format, args));
1355 win32_vprintf(const char *format, va_list args)
1357 return (vprintf(format, args));
1361 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
1363 return fread(buf, size, count, fp);
1367 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
1369 return fwrite(buf, size, count, fp);
1373 win32_fopen(const char *filename, const char *mode)
1375 if (stricmp(filename, "/dev/null")==0)
1376 return fopen("NUL", mode);
1377 return fopen(filename, mode);
1380 #ifndef USE_SOCKETS_AS_HANDLES
1382 #define fdopen my_fdopen
1386 win32_fdopen( int handle, const char *mode)
1388 return fdopen(handle, (char *) mode);
1392 win32_freopen( const char *path, const char *mode, FILE *stream)
1394 if (stricmp(path, "/dev/null")==0)
1395 return freopen("NUL", mode, stream);
1396 return freopen(path, mode, stream);
1400 win32_fclose(FILE *pf)
1402 return my_fclose(pf); /* defined in win32sck.c */
1406 win32_fputs(const char *s,FILE *pf)
1408 return fputs(s, pf);
1412 win32_fputc(int c,FILE *pf)
1418 win32_ungetc(int c,FILE *pf)
1420 return ungetc(c,pf);
1424 win32_getc(FILE *pf)
1430 win32_fileno(FILE *pf)
1436 win32_clearerr(FILE *pf)
1443 win32_fflush(FILE *pf)
1449 win32_ftell(FILE *pf)
1455 win32_fseek(FILE *pf,long offset,int origin)
1457 return fseek(pf, offset, origin);
1461 win32_fgetpos(FILE *pf,fpos_t *p)
1463 return fgetpos(pf, p);
1467 win32_fsetpos(FILE *pf,const fpos_t *p)
1469 return fsetpos(pf, p);
1473 win32_rewind(FILE *pf)
1493 win32_fstat(int fd,struct stat *sbufptr)
1495 return fstat(fd,sbufptr);
1499 win32_pipe(int *pfd, unsigned int size, int mode)
1501 return _pipe(pfd, size, mode);
1505 * a popen() clone that respects PERL5SHELL
1509 win32_popen(const char *command, const char *mode)
1511 #ifdef USE_CRT_POPEN
1512 return _popen(command, mode);
1520 /* establish which ends read and write */
1521 if (strchr(mode,'w')) {
1522 stdfd = 0; /* stdin */
1526 else if (strchr(mode,'r')) {
1527 stdfd = 1; /* stdout */
1534 /* set the correct mode */
1535 if (strchr(mode,'b'))
1537 else if (strchr(mode,'t'))
1540 ourmode = _fmode & (O_TEXT | O_BINARY);
1542 /* the child doesn't inherit handles */
1543 ourmode |= O_NOINHERIT;
1545 if (win32_pipe( p, 512, ourmode) == -1)
1548 /* save current stdfd */
1549 if ((oldfd = win32_dup(stdfd)) == -1)
1552 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
1553 /* stdfd will be inherited by the child */
1554 if (win32_dup2(p[child], stdfd) == -1)
1557 /* close the child end in parent */
1558 win32_close(p[child]);
1560 /* start the child */
1561 if ((childpid = do_spawn_nowait((char*)command)) == -1)
1564 /* revert stdfd to whatever it was before */
1565 if (win32_dup2(oldfd, stdfd) == -1)
1568 /* close saved handle */
1571 w32_popen_pids[p[parent]] = childpid;
1573 /* we have an fd, return a file stream */
1574 return (win32_fdopen(p[parent], (char *)mode));
1577 /* we don't need to check for errors here */
1581 win32_dup2(oldfd, stdfd);
1586 #endif /* USE_CRT_POPEN */
1594 win32_pclose(FILE *pf)
1596 #ifdef USE_CRT_POPEN
1599 int fd, childpid, status;
1601 fd = win32_fileno(pf);
1602 childpid = w32_popen_pids[fd];
1610 w32_popen_pids[fd] = 0;
1612 /* wait for the child */
1613 if (cwait(&status, childpid, WAIT_CHILD) == -1)
1615 /* cwait() returns differently on Borland */
1617 return (((status >> 8) & 0xff) | ((status << 8) & 0xff00));
1622 #endif /* USE_CRT_OPEN */
1626 win32_setmode(int fd, int mode)
1628 return setmode(fd, mode);
1632 win32_lseek(int fd, long offset, int origin)
1634 return lseek(fd, offset, origin);
1644 win32_open(const char *path, int flag, ...)
1650 pmode = va_arg(ap, int);
1653 if (stricmp(path, "/dev/null")==0)
1654 return open("NUL", flag, pmode);
1655 return open(path,flag,pmode);
1677 win32_dup2(int fd1,int fd2)
1679 return dup2(fd1,fd2);
1683 win32_read(int fd, void *buf, unsigned int cnt)
1685 return read(fd, buf, cnt);
1689 win32_write(int fd, const void *buf, unsigned int cnt)
1691 return write(fd, buf, cnt);
1695 win32_mkdir(const char *dir, int mode)
1697 return mkdir(dir); /* just ignore mode */
1701 win32_rmdir(const char *dir)
1707 win32_chdir(const char *dir)
1713 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
1717 status = spawnvp(mode, cmdname, (char * const *) argv);
1718 #ifndef __BORLANDC__
1719 /* XXX For the P_NOWAIT case, Borland RTL returns pinfo.dwProcessId
1720 * while VC RTL returns pinfo.hProcess. For purposes of the custom
1721 * implementation of win32_wait(), we assume the latter.
1723 if (mode == P_NOWAIT && status >= 0)
1724 w32_child_pids[w32_num_children++] = (HANDLE)status;
1730 win32_execvp(const char *cmdname, const char *const *argv)
1732 return execvp(cmdname, (char *const *)argv);
1736 win32_perror(const char *str)
1742 win32_setbuf(FILE *pf, char *buf)
1748 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
1750 return setvbuf(pf, buf, type, size);
1754 win32_flushall(void)
1760 win32_fcloseall(void)
1766 win32_fgets(char *s, int n, FILE *pf)
1768 return fgets(s, n, pf);
1778 win32_fgetc(FILE *pf)
1784 win32_putc(int c, FILE *pf)
1790 win32_puts(const char *s)
1802 win32_putchar(int c)
1809 #ifndef USE_PERL_SBRK
1811 static char *committed = NULL;
1812 static char *base = NULL;
1813 static char *reserved = NULL;
1814 static char *brk = NULL;
1815 static DWORD pagesize = 0;
1816 static DWORD allocsize = 0;
1824 GetSystemInfo(&info);
1825 /* Pretend page size is larger so we don't perpetually
1826 * call the OS to commit just one page ...
1828 pagesize = info.dwPageSize << 3;
1829 allocsize = info.dwAllocationGranularity;
1831 /* This scheme fails eventually if request for contiguous
1832 * block is denied so reserve big blocks - this is only
1833 * address space not memory ...
1835 if (brk+need >= reserved)
1837 DWORD size = 64*1024*1024;
1839 if (committed && reserved && committed < reserved)
1841 /* Commit last of previous chunk cannot span allocations */
1842 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
1844 committed = reserved;
1846 /* Reserve some (more) space
1847 * Note this is a little sneaky, 1st call passes NULL as reserved
1848 * so lets system choose where we start, subsequent calls pass
1849 * the old end address so ask for a contiguous block
1851 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
1854 reserved = addr+size;
1869 if (brk > committed)
1871 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
1872 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
1887 win32_malloc(size_t size)
1889 return malloc(size);
1893 win32_calloc(size_t numitems, size_t size)
1895 return calloc(numitems,size);
1899 win32_realloc(void *block, size_t size)
1901 return realloc(block,size);
1905 win32_free(void *block)
1912 win32_open_osfhandle(long handle, int flags)
1914 return _open_osfhandle(handle, flags);
1918 win32_get_osfhandle(int fd)
1920 return _get_osfhandle(fd);
1931 SV *sv = sv_newmortal();
1932 /* Make one call with zero size - return value is required size */
1933 DWORD len = GetCurrentDirectory((DWORD)0,NULL);
1934 SvUPGRADE(sv,SVt_PV);
1936 SvCUR(sv) = GetCurrentDirectory((DWORD) SvLEN(sv), SvPVX(sv));
1939 * then it worked, set PV valid,
1940 * else leave it 'undef'
1954 croak("usage: Win32::SetCurrentDirectory($cwd)");
1955 if (SetCurrentDirectory(SvPV(ST(0),na)))
1962 XS(w32_GetNextAvailDrive)
1966 char root[] = "_:\\";
1969 if (GetDriveType(root) == 1) {
1978 XS(w32_GetLastError)
1981 XSRETURN_IV(GetLastError());
1988 char *name = getlogin_buffer;
1989 DWORD size = sizeof(getlogin_buffer);
1990 if (GetUserName(name,&size)) {
1991 /* size includes NULL */
1992 ST(0) = sv_2mortal(newSVpv(name,size-1));
2002 char name[MAX_COMPUTERNAME_LENGTH+1];
2003 DWORD size = sizeof(name);
2004 if (GetComputerName(name,&size)) {
2005 /* size does NOT include NULL :-( */
2006 ST(0) = sv_2mortal(newSVpv(name,size));
2018 DWORD size = sizeof(name);
2019 if (GetUserName(name,&size)) {
2021 DWORD sidlen = sizeof(sid);
2023 DWORD dnamelen = sizeof(dname);
2025 if (LookupAccountName(NULL, name, &sid, &sidlen,
2026 dname, &dnamelen, &snu)) {
2027 XSRETURN_PV(dname); /* all that for this */
2038 DWORD flags, filecomplen;
2039 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
2040 &flags, fsname, sizeof(fsname))) {
2041 if (GIMME == G_ARRAY) {
2042 XPUSHs(sv_2mortal(newSVpv(fsname,0)));
2043 XPUSHs(sv_2mortal(newSViv(flags)));
2044 XPUSHs(sv_2mortal(newSViv(filecomplen)));
2048 XSRETURN_PV(fsname);
2054 XS(w32_GetOSVersion)
2057 OSVERSIONINFO osver;
2059 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
2060 if (GetVersionEx(&osver)) {
2061 XPUSHs(newSVpv(osver.szCSDVersion, 0));
2062 XPUSHs(newSViv(osver.dwMajorVersion));
2063 XPUSHs(newSViv(osver.dwMinorVersion));
2064 XPUSHs(newSViv(osver.dwBuildNumber));
2065 XPUSHs(newSViv(osver.dwPlatformId));
2076 XSRETURN_IV(IsWinNT());
2083 XSRETURN_IV(IsWin95());
2087 XS(w32_FormatMessage)
2094 croak("usage: Win32::FormatMessage($errno)");
2096 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
2097 &source, SvIV(ST(0)), 0,
2098 msgbuf, sizeof(msgbuf)-1, NULL))
2099 XSRETURN_PV(msgbuf);
2109 PROCESS_INFORMATION stProcInfo;
2110 STARTUPINFO stStartInfo;
2111 BOOL bSuccess = FALSE;
2114 croak("usage: Win32::Spawn($cmdName, $args, $PID)");
2116 cmd = SvPV(ST(0),na);
2117 args = SvPV(ST(1), na);
2119 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
2120 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
2121 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
2122 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
2125 cmd, /* Image path */
2126 args, /* Arguments for command line */
2127 NULL, /* Default process security */
2128 NULL, /* Default thread security */
2129 FALSE, /* Must be TRUE to use std handles */
2130 NORMAL_PRIORITY_CLASS, /* No special scheduling */
2131 NULL, /* Inherit our environment block */
2132 NULL, /* Inherit our currrent directory */
2133 &stStartInfo, /* -> Startup info */
2134 &stProcInfo)) /* <- Process info (if OK) */
2136 CloseHandle(stProcInfo.hThread);/* library source code does this. */
2137 sv_setiv(ST(2), stProcInfo.dwProcessId);
2140 XSRETURN_IV(bSuccess);
2144 XS(w32_GetTickCount)
2147 XSRETURN_IV(GetTickCount());
2151 XS(w32_GetShortPathName)
2158 croak("usage: Win32::GetShortPathName($longPathName)");
2160 shortpath = sv_mortalcopy(ST(0));
2161 SvUPGRADE(shortpath, SVt_PV);
2162 /* src == target is allowed */
2164 len = GetShortPathName(SvPVX(shortpath),
2167 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
2169 SvCUR_set(shortpath,len);
2182 croak("usage: Win32::Sleep($milliseconds)");
2187 #define TMPBUFSZ 1024
2188 #define MAX_LENGTH 2048
2189 #define SUCCESSRETURNED(x) (x == ERROR_SUCCESS)
2190 #define REGRETURN(x) XSRETURN_IV(SUCCESSRETURNED(x))
2191 #define SvHKEY(index) (HKEY)((unsigned long)SvIV(index))
2192 #define SETIV(index,value) sv_setiv(ST(index), value)
2193 #define SETNV(index,value) sv_setnv(ST(index), value)
2194 #define SETPV(index,string) sv_setpv(ST(index), string)
2195 #define SETPVN(index, buffer, length) sv_setpvn(ST(index), (char*)buffer, length)
2196 #define SETHKEY(index, hkey) SETIV(index,(long)hkey)
2198 static time_t ft2timet(FILETIME *ft)
2203 FileTimeToSystemTime(ft, &st);
2204 tm.tm_sec = st.wSecond;
2205 tm.tm_min = st.wMinute;
2206 tm.tm_hour = st.wHour;
2207 tm.tm_mday = st.wDay;
2208 tm.tm_mon = st.wMonth - 1;
2209 tm.tm_year = st.wYear - 1900;
2210 tm.tm_wday = st.wDayOfWeek;
2213 return mktime (&tm);
2223 croak("usage: Win32::RegCloseKey($hkey);\n");
2226 REGRETURN(RegCloseKey(SvHKEY(ST(0))));
2230 XS(w32_RegConnectRegistry)
2237 croak("usage: Win32::RegConnectRegistry($machine, $hkey, $handle);\n");
2240 if(SUCCESSRETURNED(RegConnectRegistry((char *)SvPV(ST(0), na), SvHKEY(ST(1)), &handle)))
2249 XS(w32_RegCreateKey)
2258 croak("usage: Win32::RegCreateKey($hkey, $subkey, $handle);\n");
2261 retval = RegCreateKeyEx(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS,
2262 NULL, &handle, &disposition);
2264 if(SUCCESSRETURNED(retval))
2273 XS(w32_RegCreateKeyEx)
2277 unsigned int length;
2282 DWORD options, disposition;
2284 SECURITY_ATTRIBUTES sa, *psa;
2288 croak("usage: Win32::RegCreateKeyEx($hkey, $subkey, $reserved, $class, $options, $sam, "
2289 "$security, $handle, $disposition);\n");
2292 hkey = SvHKEY(ST(0));
2293 subkey = (char *)SvPV(ST(1), na);
2294 keyclass = (char *)SvPV(ST(3), na);
2295 options = (DWORD) ((unsigned long)SvIV(ST(4)));
2296 sam = (REGSAM) ((unsigned long)SvIV(ST(5)));
2297 psa = (SECURITY_ATTRIBUTES*)SvPV(ST(6), length);
2298 if(length != sizeof(SECURITY_ATTRIBUTES))
2301 memset(&sa, 0, sizeof(SECURITY_ATTRIBUTES));
2302 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
2305 retval = RegCreateKeyEx(hkey, subkey, 0, keyclass, options, sam,
2306 psa, &handle, &disposition);
2308 if(SUCCESSRETURNED(retval))
2311 SETPVN(6, &sa, sizeof(sa));
2314 SETIV(8,disposition);
2321 XS(w32_RegDeleteKey)
2327 croak("usage: Win32::RegDeleteKey($hkey, $subkey);\n");
2330 REGRETURN(RegDeleteKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na)));
2334 XS(w32_RegDeleteValue)
2340 croak("usage: Win32::RegDeleteValue($hkey, $valname);\n");
2343 REGRETURN(RegDeleteValue(SvHKEY(ST(0)), (char *)SvPV(ST(1), na)));
2351 char keybuffer[TMPBUFSZ];
2355 croak("usage: Win32::RegEnumKey($hkey, $idx, $subkeyname);\n");
2358 if(SUCCESSRETURNED(RegEnumKey(SvHKEY(ST(0)), SvIV(ST(1)), keybuffer, sizeof(keybuffer))))
2360 SETPV(2, keybuffer);
2367 XS(w32_RegEnumKeyEx)
2372 DWORD keysz, classsz;
2373 char keybuffer[TMPBUFSZ];
2374 char classbuffer[TMPBUFSZ];
2380 croak("usage: Win32::RegEnumKeyEx($hkey, $idx, $subkeyname, $reserved, $class, $time);\n");
2383 keysz = sizeof(keybuffer);
2384 classsz = sizeof(classbuffer);
2385 retval = RegEnumKeyEx(SvHKEY(ST(0)), SvIV(ST(1)), keybuffer, &keysz, 0,
2386 classbuffer, &classsz, &filetime);
2387 if(SUCCESSRETURNED(retval))
2389 SETPV(2, keybuffer);
2390 SETPV(4, classbuffer);
2391 SETIV(5, ft2timet(&filetime));
2398 XS(w32_RegEnumValue)
2402 DWORD type, namesz, valsz;
2404 static HKEY last_hkey;
2405 char myvalbuf[MAX_LENGTH];
2406 char mynambuf[MAX_LENGTH];
2410 croak("usage: Win32::RegEnumValue($hkey, $i, $name, $reserved, $type, $value);\n");
2413 hkey = SvHKEY(ST(0));
2415 // If this is a new key, find out how big the maximum name and value sizes are and
2416 // allocate space for them. Free any old storage and set the old key value to the
2419 if(hkey != (HKEY)last_hkey)
2421 char keyclass[TMPBUFSZ];
2422 DWORD classsz, subkeys, maxsubkey, maxclass, values, salen, maxnamesz, maxvalsz;
2424 classsz = sizeof(keyclass);
2425 retval = RegQueryInfoKey(hkey, keyclass, &classsz, 0, &subkeys, &maxsubkey, &maxclass,
2426 &values, &maxnamesz, &maxvalsz, &salen, &ft);
2428 if(!SUCCESSRETURNED(retval))
2432 memset(myvalbuf, 0, MAX_LENGTH);
2433 memset(mynambuf, 0, MAX_LENGTH);
2437 namesz = MAX_LENGTH;
2439 retval = RegEnumValue(hkey, SvIV(ST(1)), mynambuf, &namesz, 0, &type, (LPBYTE) myvalbuf, &valsz);
2440 if(!SUCCESSRETURNED(retval))
2449 // return includes the null terminator so delete it if REG_SZ, REG_MULTI_SZ or REG_EXPAND_SZ
2458 SETPVN(5, myvalbuf, valsz);
2461 case REG_DWORD_BIG_ENDIAN:
2463 BYTE tmp = myvalbuf[0];
2464 myvalbuf[0] = myvalbuf[3];
2467 myvalbuf[1] = myvalbuf[2];
2470 case REG_DWORD_LITTLE_ENDIAN: // same as REG_DWORD
2471 SETNV(5, (double)*((DWORD*)myvalbuf));
2489 croak("usage: Win32::RegFlushKey($hkey);\n");
2492 REGRETURN(RegFlushKey(SvHKEY(ST(0))));
2496 XS(w32_RegGetKeySecurity)
2499 SECURITY_DESCRIPTOR sd;
2504 croak("usage: Win32::RegGetKeySecurity($hkey, $security_info, $security_descriptor);\n");
2507 if(SUCCESSRETURNED(RegGetKeySecurity(SvHKEY(ST(0)), SvIV(ST(1)), &sd, &sdsz)))
2509 SETPVN(2, &sd, sdsz);
2522 croak("usage: Win32::RegLoadKey($hkey, $subkey, $filename);\n");
2525 REGRETURN(RegLoadKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), (char *)SvPV(ST(2), na)));
2529 XS(w32_RegNotifyChangeKeyValue)
2531 croak("Win32::RegNotifyChangeKeyValue not yet implemented!\n");
2542 croak("usage: Win32::RegOpenKey($hkey, $subkey, $handle);\n");
2545 if(SUCCESSRETURNED(RegOpenKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), &handle)))
2554 XS(w32_RegOpenKeyEx)
2561 croak("usage: Win32::RegOpenKeyEx($hkey, $subkey, $reserved, $sam, $handle);\n");
2564 if(SUCCESSRETURNED(RegOpenKeyEx(SvHKEY(ST(0)), (char *)SvPV(ST(1), na),
2565 0, (REGSAM) ((unsigned long)SvIV(ST(3))), &handle)))
2573 #pragma optimize("", off)
2575 XS(w32_RegQueryInfoKey)
2580 char keyclass[TMPBUFSZ];
2581 DWORD subkeys, maxsubkey, maxclass, values, maxvalname, maxvaldata;
2582 DWORD seclen, classsz;
2588 croak("usage: Win32::RegQueryInfoKey($hkey, $class, $numsubkeys, $maxsubkey,"
2589 "$maxclass, $values, $maxvalname, $maxvaldata, $secdesclen,"
2590 "$lastwritetime);\n");
2593 classsz = sizeof(keyclass);
2594 retval = RegQueryInfoKey(SvHKEY(ST(0)), keyclass, &classsz, 0, &subkeys, &maxsubkey,
2595 &maxclass, &values, &maxvalname, &maxvaldata,
2597 if(SUCCESSRETURNED(retval))
2601 SETIV(3, maxsubkey);
2604 SETIV(6, maxvalname);
2605 SETIV(7, maxvaldata);
2607 SETIV(9, ft2timet(&ft));
2612 #pragma optimize("", on)
2615 XS(w32_RegQueryValue)
2619 unsigned char databuffer[TMPBUFSZ*2];
2620 long datasz = sizeof(databuffer);
2624 croak("usage: Win32::RegQueryValue($hkey, $valuename, $data);\n");
2627 if(SUCCESSRETURNED(RegQueryValue(SvHKEY(ST(0)), SvPV(ST(1), na), (char*)databuffer, &datasz)))
2629 // return includes the null terminator so delete it
2630 SETPVN(2, databuffer, --datasz);
2637 XS(w32_RegQueryValueEx)
2641 unsigned char databuffer[TMPBUFSZ*2];
2642 DWORD datasz = sizeof(databuffer);
2645 LPBYTE ptr = databuffer;
2649 croak("usage: Win32::RegQueryValueEx($hkey, $valuename, $reserved, $type, $data);\n");
2652 result = RegQueryValueEx(SvHKEY(ST(0)), SvPV(ST(1), na), 0, &type, ptr, &datasz);
2653 if(result == ERROR_MORE_DATA)
2655 New(0, ptr, datasz+1, BYTE);
2656 result = RegQueryValueEx(SvHKEY(ST(0)), SvPV(ST(1), na), 0, &type, ptr, &datasz);
2658 if(SUCCESSRETURNED(result))
2662 // return includes the null terminator so delete it if REG_SZ, REG_MULTI_SZ or REG_EXPAND_SZ
2670 SETPVN(4, ptr, datasz);
2673 case REG_DWORD_BIG_ENDIAN:
2682 case REG_DWORD_LITTLE_ENDIAN: // same as REG_DWORD
2683 SETNV(4, (double)*((DWORD*)ptr));
2690 if(ptr != databuffer)
2695 if(ptr != databuffer)
2702 XS(w32_RegReplaceKey)
2708 croak("usage: Win32::RegReplaceKey($hkey, $subkey, $newfile, $oldfile);\n");
2711 REGRETURN(RegReplaceKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), (char *)SvPV(ST(2), na), (char *)SvPV(ST(3), na)));
2715 XS(w32_RegRestoreKey)
2719 if(items < 2 || items > 3)
2721 croak("usage: Win32::RegRestoreKey($hkey, $filename [, $flags]);\n");
2724 REGRETURN(RegRestoreKey(SvHKEY(ST(0)), (char*)SvPV(ST(1), na), (DWORD)((items == 3) ? SvIV(ST(2)) : 0)));
2734 croak("usage: Win32::RegSaveKey($hkey, $filename);\n");
2737 REGRETURN(RegSaveKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), NULL));
2741 XS(w32_RegSetKeySecurity)
2747 croak("usage: Win32::RegSetKeySecurity($hkey, $security_info, $security_descriptor);\n");
2750 REGRETURN(RegSetKeySecurity(SvHKEY(ST(0)), SvIV(ST(1)), (SECURITY_DESCRIPTOR*)SvPV(ST(2), na)));
2763 croak("usage: Win32::RegSetValue($hkey, $subKey, $type, $data);\n");
2766 DWORD type = SvIV(ST(2));
2767 if(type != REG_SZ && type != REG_EXPAND_SZ)
2769 croak("Win32::RegSetValue: Type was not REG_SZ or REG_EXPAND_SZ, cannot set %s\n", (char *)SvPV(ST(1), na));
2772 buffer = (char *)SvPV(ST(3), size);
2773 REGRETURN(RegSetValue(SvHKEY(ST(0)), SvPV(ST(1), na), REG_SZ, buffer, size));
2777 XS(w32_RegSetValueEx)
2788 croak("usage: Win32::RegSetValueEx($hkey, $valname, $reserved, $type, $data);\n");
2791 type = (DWORD)SvIV(ST(3));
2798 buffer = (char *)SvPV(ST(4), size);
2799 if(type != REG_BINARY)
2800 size++; // include null terminator in size
2802 REGRETURN(RegSetValueEx(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), 0, type, (PBYTE) buffer, size));
2805 case REG_DWORD_BIG_ENDIAN:
2806 case REG_DWORD_LITTLE_ENDIAN: // Same as REG_DWORD
2807 val = (DWORD)SvIV(ST(4));
2808 REGRETURN(RegSetValueEx(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), 0, type, (PBYTE) &val, sizeof(DWORD)));
2812 croak("Win32::RegSetValueEx: Type not specified, cannot set %s\n", (char *)SvPV(ST(1), na));
2817 XS(w32_RegUnloadKey)
2823 croak("usage: Win32::RegUnLoadKey($hkey, $subkey);\n");
2826 REGRETURN(RegUnLoadKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na)));
2830 XS(w32_RegisterServer)
2833 BOOL bSuccess = FALSE;
2834 HINSTANCE hInstance;
2835 unsigned int length;
2840 croak("usage: Win32::RegisterServer($LibraryName)\n");
2843 hInstance = LoadLibrary((char *)SvPV(ST(0), length));
2844 if(hInstance != NULL)
2846 sFunc = GetProcAddress(hInstance, "DllRegisterServer");
2849 bSuccess = (sFunc() == 0);
2851 FreeLibrary(hInstance);
2862 XS(w32_UnregisterServer)
2865 BOOL bSuccess = FALSE;
2866 HINSTANCE hInstance;
2867 unsigned int length;
2872 croak("usage: Win32::UnregisterServer($LibraryName)\n");
2875 hInstance = LoadLibrary((char *)SvPV(ST(0), length));
2876 if(hInstance != NULL)
2878 sFunc = GetProcAddress(hInstance, "DllUnregisterServer");
2881 bSuccess = (sFunc() == 0);
2883 FreeLibrary(hInstance);
2895 Perl_init_os_extras()
2897 char *file = __FILE__;
2900 /* these names are Activeware compatible */
2901 newXS("Win32::GetCwd", w32_GetCwd, file);
2902 newXS("Win32::SetCwd", w32_SetCwd, file);
2903 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
2904 newXS("Win32::GetLastError", w32_GetLastError, file);
2905 newXS("Win32::LoginName", w32_LoginName, file);
2906 newXS("Win32::NodeName", w32_NodeName, file);
2907 newXS("Win32::DomainName", w32_DomainName, file);
2908 newXS("Win32::FsType", w32_FsType, file);
2909 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
2910 newXS("Win32::IsWinNT", w32_IsWinNT, file);
2911 newXS("Win32::IsWin95", w32_IsWin95, file);
2912 newXS("Win32::FormatMessage", w32_FormatMessage, file);
2913 newXS("Win32::Spawn", w32_Spawn, file);
2914 newXS("Win32::GetTickCount", w32_GetTickCount, file);
2915 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
2916 newXS("Win32::Sleep", w32_Sleep, file);
2918 /* the following extensions are used interally and may be changed at any time */
2919 /* therefore no documentation is provided */
2920 newXS("Win32::RegCloseKey", w32_RegCloseKey, file);
2921 newXS("Win32::RegConnectRegistry", w32_RegConnectRegistry, file);
2922 newXS("Win32::RegCreateKey", w32_RegCreateKey, file);
2923 newXS("Win32::RegCreateKeyEx", w32_RegCreateKeyEx, file);
2924 newXS("Win32::RegDeleteKey", w32_RegDeleteKey, file);
2925 newXS("Win32::RegDeleteValue", w32_RegDeleteValue, file);
2927 newXS("Win32::RegEnumKey", w32_RegEnumKey, file);
2928 newXS("Win32::RegEnumKeyEx", w32_RegEnumKeyEx, file);
2929 newXS("Win32::RegEnumValue", w32_RegEnumValue, file);
2931 newXS("Win32::RegFlushKey", w32_RegFlushKey, file);
2932 newXS("Win32::RegGetKeySecurity", w32_RegGetKeySecurity, file);
2934 newXS("Win32::RegLoadKey", w32_RegLoadKey, file);
2935 newXS("Win32::RegOpenKey", w32_RegOpenKey, file);
2936 newXS("Win32::RegOpenKeyEx", w32_RegOpenKeyEx, file);
2937 newXS("Win32::RegQueryInfoKey", w32_RegQueryInfoKey, file);
2938 newXS("Win32::RegQueryValue", w32_RegQueryValue, file);
2939 newXS("Win32::RegQueryValueEx", w32_RegQueryValueEx, file);
2941 newXS("Win32::RegReplaceKey", w32_RegReplaceKey, file);
2942 newXS("Win32::RegRestoreKey", w32_RegRestoreKey, file);
2943 newXS("Win32::RegSaveKey", w32_RegSaveKey, file);
2944 newXS("Win32::RegSetKeySecurity", w32_RegSetKeySecurity, file);
2945 newXS("Win32::RegSetValue", w32_RegSetValue, file);
2946 newXS("Win32::RegSetValueEx", w32_RegSetValueEx, file);
2947 newXS("Win32::RegUnloadKey", w32_RegUnloadKey, file);
2949 newXS("Win32::RegisterServer", w32_RegisterServer, file);
2950 newXS("Win32::UnregisterServer", w32_UnregisterServer, file);
2952 /* XXX Bloat Alert! The following Activeware preloads really
2953 * ought to be part of Win32::Sys::*, so they're not included
2956 /* LookupAccountName
2958 * InitiateSystemShutdown
2959 * AbortSystemShutdown
2960 * ExpandEnvrironmentStrings
2965 Perl_win32_init(int *argcp, char ***argvp)
2967 /* Disable floating point errors, Perl will trap the ones we
2968 * care about. VC++ RTL defaults to switching these off
2969 * already, but the Borland RTL doesn't. Since we don't
2970 * want to be at the vendor's whim on the default, we set
2971 * it explicitly here.
2973 #if !defined(_ALPHA_) && !defined(__GNUC__)
2974 _control87(MCW_EM, MCW_EM);
2979 #ifdef USE_BINMODE_SCRIPTS
2982 win32_strip_return(SV *sv)
2984 char *s = SvPVX(sv);
2985 char *e = s+SvCUR(sv);
2989 if (*s == '\r' && s[1] == '\n')
2999 SvCUR_set(sv,d-SvPVX(sv));