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];
109 # ifdef USE_DECLSPEC_THREAD
110 __declspec(thread) char strerror_buffer[512];
111 __declspec(thread) char getlogin_buffer[128];
112 # ifdef HAVE_DES_FCRYPT
113 __declspec(thread) char crypt_buffer[30];
116 # define strerror_buffer (thr->i.Wstrerror_buffer)
117 # define getlogin_buffer (thr->i.Wgetlogin_buffer)
118 # define crypt_buffer (thr->i.Wcrypt_buffer)
121 char strerror_buffer[512];
122 char getlogin_buffer[128];
123 # ifdef HAVE_DES_FCRYPT
124 char crypt_buffer[30];
130 return (os_id() == VER_PLATFORM_WIN32_WINDOWS);
135 return (os_id() == VER_PLATFORM_WIN32_NT);
139 win32_perllib_path(char *sfx,...)
144 GetModuleFileName((w32_perldll_handle == INVALID_HANDLE_VALUE)
145 ? GetModuleHandle(NULL)
146 : w32_perldll_handle,
148 sizeof(w32_perllib_root));
149 *(end = strrchr(w32_perllib_root, '\\')) = '\0';
150 if (stricmp(end-4,"\\bin") == 0)
157 sfx = va_arg(ap,char *);
160 return (w32_perllib_root);
165 has_redirection(char *ptr)
171 * Scan string looking for redirection (< or >) or pipe
172 * characters (|) that are not in a quoted string
202 #if !defined(PERL_OBJECT)
203 /* since the current process environment is being updated in util.c
204 * the library functions will get the correct environment
207 my_popen(char *cmd, char *mode)
210 #define fixcmd(x) { \
211 char *pspace = strchr((x),' '); \
214 while (p < pspace) { \
225 #ifdef __BORLANDC__ /* workaround a Borland stdio bug */
226 win32_fflush(stdout);
227 win32_fflush(stderr);
229 return win32_popen(cmd, mode);
233 my_pclose(PerlIO *fp)
235 return win32_pclose(fp);
242 static OSVERSIONINFO osver;
244 if (osver.dwPlatformId != w32_platform) {
245 memset(&osver, 0, sizeof(OSVERSIONINFO));
246 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
247 GetVersionEx(&osver);
248 w32_platform = osver.dwPlatformId;
250 return (w32_platform);
253 /* Tokenize a string. Words are null-separated, and the list
254 * ends with a doubled null. Any character (except null and
255 * including backslash) may be escaped by preceding it with a
256 * backslash (the backslash will be stripped).
257 * Returns number of words in result buffer.
260 tokenize(char *str, char **dest, char ***destv)
262 char *retstart = Nullch;
263 char **retvstart = 0;
266 int slen = strlen(str);
268 register char **retv;
269 New(1307, ret, slen+2, char);
270 New(1308, retv, (slen+3)/2, char*);
278 if (*ret == '\\' && *str)
280 else if (*ret == ' ') {
296 retvstart[items] = Nullch;
308 if (!w32_perlshell_tokens) {
309 /* we don't use COMSPEC here for two reasons:
310 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
311 * uncontrolled unportability of the ensuing scripts.
312 * 2. PERL5SHELL could be set to a shell that may not be fit for
313 * interactive use (which is what most programs look in COMSPEC
316 char* defaultshell = (IsWinNT() ? "cmd.exe /x/c" : "command.com /c");
317 char *usershell = getenv("PERL5SHELL");
318 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
319 &w32_perlshell_tokens,
325 do_aspawn(void *vreally, void **vmark, void **vsp)
327 SV *really = (SV*)vreally;
328 SV **mark = (SV**)vmark;
340 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
342 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
347 while(++mark <= sp) {
348 if (*mark && (str = SvPV(*mark, na)))
355 status = win32_spawnvp(flag,
356 (const char*)(really ? SvPV(really,na) : argv[0]),
357 (const char* const*)argv);
359 if (status < 0 && errno == ENOEXEC) {
360 /* possible shell-builtin, invoke with shell */
362 sh_items = w32_perlshell_items;
364 argv[index+sh_items] = argv[index];
365 while (--sh_items >= 0)
366 argv[sh_items] = w32_perlshell_vec[sh_items];
368 status = win32_spawnvp(flag,
369 (const char*)(really ? SvPV(really,na) : argv[0]),
370 (const char* const*)argv);
375 warn("Can't spawn \"%s\": %s", argv[0], strerror(errno));
378 else if (flag != P_NOWAIT)
381 return (statusvalue = status);
385 do_spawn2(char *cmd, int exectype)
391 BOOL needToTry = TRUE;
394 /* Save an extra exec if possible. See if there are shell
395 * metacharacters in it */
396 if(!has_redirection(cmd)) {
397 New(1301,argv, strlen(cmd) / 2 + 2, char*);
398 New(1302,cmd2, strlen(cmd) + 1, char);
401 for (s = cmd2; *s;) {
402 while (*s && isspace(*s))
406 while(*s && !isspace(*s))
415 status = win32_spawnvp(P_WAIT, argv[0],
416 (const char* const*)argv);
418 case EXECF_SPAWN_NOWAIT:
419 status = win32_spawnvp(P_NOWAIT, argv[0],
420 (const char* const*)argv);
423 status = win32_execvp(argv[0], (const char* const*)argv);
426 if (status != -1 || errno == 0)
436 New(1306, argv, w32_perlshell_items + 2, char*);
437 while (++i < w32_perlshell_items)
438 argv[i] = w32_perlshell_vec[i];
443 status = win32_spawnvp(P_WAIT, argv[0],
444 (const char* const*)argv);
446 case EXECF_SPAWN_NOWAIT:
447 status = win32_spawnvp(P_NOWAIT, argv[0],
448 (const char* const*)argv);
451 status = win32_execvp(argv[0], (const char* const*)argv);
459 warn("Can't %s \"%s\": %s",
460 (exectype == EXECF_EXEC ? "exec" : "spawn"),
461 cmd, strerror(errno));
464 else if (exectype != EXECF_SPAWN_NOWAIT)
466 return (statusvalue = status);
472 return do_spawn2(cmd, EXECF_SPAWN);
476 do_spawn_nowait(char *cmd)
478 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
484 do_spawn2(cmd, EXECF_EXEC);
491 /* The idea here is to read all the directory names into a string table
492 * (separated by nulls) and when one of the other dir functions is called
493 * return the pointer to the current file name.
496 opendir(char *filename)
501 char scannamespc[PATHLEN];
502 char *scanname = scannamespc;
504 WIN32_FIND_DATA FindData;
506 /* char root[_MAX_PATH];*/
507 /* char volname[_MAX_PATH];*/
508 /* DWORD serial, maxname, flags;*/
512 /* check to see if filename is a directory */
513 if (win32_stat(filename, &sbuf) < 0 || (sbuf.st_mode & S_IFDIR) == 0) {
514 /* CRT is buggy on sharenames, so make sure it really isn't */
515 DWORD r = GetFileAttributes(filename);
516 if (r == 0xffffffff || !(r & FILE_ATTRIBUTE_DIRECTORY))
520 /* get the file system characteristics */
521 /* if(GetFullPathName(filename, MAX_PATH, root, &dummy)) {
522 * if(dummy = strchr(root, '\\'))
524 * if(GetVolumeInformation(root, volname, MAX_PATH, &serial,
525 * &maxname, &flags, 0, 0)) {
526 * downcase = !(flags & FS_CASE_IS_PRESERVED);
533 /* Get us a DIR structure */
534 Newz(1303, p, 1, DIR);
538 /* Create the search pattern */
539 strcpy(scanname, filename);
541 if(index("/\\", *(scanname + strlen(scanname) - 1)) == NULL)
542 strcat(scanname, "/*");
544 strcat(scanname, "*");
546 /* do the FindFirstFile call */
547 fh = FindFirstFile(scanname, &FindData);
548 if(fh == INVALID_HANDLE_VALUE) {
552 /* now allocate the first part of the string table for
553 * the filenames that we find.
555 idx = strlen(FindData.cFileName)+1;
556 New(1304, p->start, idx, char);
557 if(p->start == NULL) {
558 croak("opendir: malloc failed!\n");
560 strcpy(p->start, FindData.cFileName);
566 /* loop finding all the files that match the wildcard
567 * (which should be all of them in this directory!).
568 * the variable idx should point one past the null terminator
569 * of the previous string found.
571 while (FindNextFile(fh, &FindData)) {
572 len = strlen(FindData.cFileName);
573 /* bump the string table size by enough for the
574 * new name and it's null terminator
576 Renew(p->start, idx+len+1, char);
577 if(p->start == NULL) {
578 croak("opendir: malloc failed!\n");
580 strcpy(&p->start[idx], FindData.cFileName);
582 * strlwr(&p->start[idx]);
594 /* Readdir just returns the current string pointer and bumps the
595 * string pointer to the nDllExport entry.
601 static int dummy = 0;
604 /* first set up the structure to return */
605 len = strlen(dirp->curr);
606 strcpy(dirp->dirstr.d_name, dirp->curr);
607 dirp->dirstr.d_namlen = len;
610 dirp->dirstr.d_ino = dummy++;
612 /* Now set up for the nDllExport call to readdir */
613 dirp->curr += len + 1;
614 if (dirp->curr >= (dirp->start + dirp->size)) {
618 return &(dirp->dirstr);
624 /* Telldir returns the current string pointer position */
628 return (long) dirp->curr;
632 /* Seekdir moves the string pointer to a previously saved position
636 seekdir(DIR *dirp, long loc)
638 dirp->curr = (char *)loc;
641 /* Rewinddir resets the string pointer to the start */
645 dirp->curr = dirp->start;
648 /* free the memory allocated by opendir */
652 Safefree(dirp->start);
665 * Just pretend that everyone is a superuser. NT will let us know if
666 * we don\'t really have permission to do something.
669 #define ROOT_UID ((uid_t)0)
670 #define ROOT_GID ((gid_t)0)
699 return (auid == ROOT_UID ? 0 : -1);
705 return (agid == ROOT_GID ? 0 : -1);
712 char *buf = getlogin_buffer;
713 DWORD size = sizeof(getlogin_buffer);
714 if (GetUserName(buf,&size))
723 kill(int pid, int sig)
725 HANDLE hProcess= OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
727 if (hProcess == NULL) {
728 croak("kill process failed!\n");
731 if (!TerminateProcess(hProcess, sig))
732 croak("kill process failed!\n");
733 CloseHandle(hProcess);
742 DllExport unsigned int
743 win32_sleep(unsigned int t)
750 win32_stat(const char *path, struct stat *buffer)
753 const char *p = path;
754 int l = strlen(path);
758 switch(path[l - 1]) {
761 if (path[l - 2] != ':') {
762 strncpy(t, path, l - 1);
768 res = stat(p,buffer);
771 if (S_ISDIR(buffer->st_mode))
772 buffer->st_mode |= S_IWRITE | S_IEXEC;
773 else if (S_ISREG(buffer->st_mode)) {
774 if (l >= 4 && path[l-4] == '.') {
775 const char *e = path + l - 3;
776 if (strnicmp(e,"exe",3)
777 && strnicmp(e,"bat",3)
778 && strnicmp(e,"com",3)
779 && (IsWin95() || strnicmp(e,"cmd",3)))
780 buffer->st_mode &= ~S_IEXEC;
782 buffer->st_mode |= S_IEXEC;
785 buffer->st_mode &= ~S_IEXEC;
792 #ifndef USE_WIN32_RTL_ENV
794 BOOL GetRegStr(HKEY hkey, const char *lpszValueName, char *lpszDefault, char *lpszData, unsigned long *lpdwDataLen)
795 { // Retrieve a REG_SZ or REG_EXPAND_SZ from the registry
797 DWORD type, dwDataLen = *lpdwDataLen;
798 const char *subkey = "Software\\Perl";
799 char szBuffer[MAX_PATH+1];
802 retval = RegOpenKeyEx(hkey, subkey, 0, KEY_READ, &handle);
803 if(retval == ERROR_SUCCESS)
805 retval = RegQueryValueEx(handle, lpszValueName, 0, &type, (LPBYTE)lpszData, &dwDataLen);
807 if(retval == ERROR_SUCCESS && (type == REG_SZ || type == REG_EXPAND_SZ))
809 if(type != REG_EXPAND_SZ)
811 *lpdwDataLen = dwDataLen;
814 strcpy(szBuffer, lpszData);
815 dwDataLen = ExpandEnvironmentStrings(szBuffer, lpszData, *lpdwDataLen);
816 if(dwDataLen < *lpdwDataLen)
818 *lpdwDataLen = dwDataLen;
824 strcpy(lpszData, lpszDefault);
828 char* GetRegStr(const char *lpszValueName, char *lpszDefault, char *lpszData, unsigned long *lpdwDataLen)
830 if(!GetRegStr(HKEY_CURRENT_USER, lpszValueName, lpszDefault, lpszData, lpdwDataLen))
832 GetRegStr(HKEY_LOCAL_MACHINE, lpszValueName, lpszDefault, lpszData, lpdwDataLen);
834 if(*lpszData == '\0')
840 win32_getenv(const char *name)
842 static char *curitem = Nullch;
843 static DWORD curlen = 512;
846 New(1305,curitem,curlen,char);
847 if (!(needlen = GetEnvironmentVariable(name,curitem,curlen)))
849 while (needlen > curlen) {
850 Renew(curitem,needlen,char);
852 needlen = GetEnvironmentVariable(name,curitem,curlen);
856 unsigned long dwDataLen = curlen;
857 if(strcmp("PERL5DB", name) == 0)
858 curitem = GetRegStr(name, "", curitem, &dwDataLen);
866 filetime_to_clock(PFILETIME ft)
868 __int64 qw = ft->dwHighDateTime;
870 qw |= ft->dwLowDateTime;
871 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
876 win32_times(struct tms *timebuf)
881 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
883 timebuf->tms_utime = filetime_to_clock(&user);
884 timebuf->tms_stime = filetime_to_clock(&kernel);
885 timebuf->tms_cutime = 0;
886 timebuf->tms_cstime = 0;
889 /* That failed - e.g. Win95 fallback to clock() */
891 timebuf->tms_utime = t;
892 timebuf->tms_stime = 0;
893 timebuf->tms_cutime = 0;
894 timebuf->tms_cstime = 0;
899 /* fix utime() so it works on directories in NT
900 * thanks to Jan Dubois <jan.dubois@ibm.net>
903 filetime_from_time(PFILETIME pFileTime, time_t Time)
905 struct tm *pTM = gmtime(&Time);
906 SYSTEMTIME SystemTime;
911 SystemTime.wYear = pTM->tm_year + 1900;
912 SystemTime.wMonth = pTM->tm_mon + 1;
913 SystemTime.wDay = pTM->tm_mday;
914 SystemTime.wHour = pTM->tm_hour;
915 SystemTime.wMinute = pTM->tm_min;
916 SystemTime.wSecond = pTM->tm_sec;
917 SystemTime.wMilliseconds = 0;
919 return SystemTimeToFileTime(&SystemTime, pFileTime);
923 win32_utime(const char *filename, struct utimbuf *times)
929 struct utimbuf TimeBuffer;
931 int rc = utime(filename,times);
932 /* EACCES: path specifies directory or readonly file */
933 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
938 time(×->actime);
939 times->modtime = times->actime;
942 /* This will (and should) still fail on readonly files */
943 handle = CreateFile(filename, GENERIC_READ | GENERIC_WRITE,
944 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
945 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
946 if (handle == INVALID_HANDLE_VALUE)
949 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
950 filetime_from_time(&ftAccess, times->actime) &&
951 filetime_from_time(&ftWrite, times->modtime) &&
952 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
962 win32_wait(int *status)
967 /* XXX this wait emulation only knows about processes
968 * spawned via win32_spawnvp(P_NOWAIT, ...).
971 DWORD exitcode, waitcode;
973 if (!w32_num_children) {
978 /* if a child exists, wait for it to die */
979 waitcode = WaitForMultipleObjects(w32_num_children,
983 if (waitcode != WAIT_FAILED) {
984 if (waitcode >= WAIT_ABANDONED_0
985 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
986 i = waitcode - WAIT_ABANDONED_0;
988 i = waitcode - WAIT_OBJECT_0;
989 if (GetExitCodeProcess(w32_child_pids[i], &exitcode) ) {
990 CloseHandle(w32_child_pids[i]);
991 *status = (int)((exitcode & 0xff) << 8);
992 retval = (int)w32_child_pids[i];
993 Copy(&w32_child_pids[i+1], &w32_child_pids[i],
994 (w32_num_children-i-1), HANDLE);
1001 errno = GetLastError();
1007 static UINT timerid = 0;
1009 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1011 KillTimer(NULL,timerid);
1016 DllExport unsigned int
1017 win32_alarm(unsigned int sec)
1020 * the 'obvious' implentation is SetTimer() with a callback
1021 * which does whatever receiving SIGALRM would do
1022 * we cannot use SIGALRM even via raise() as it is not
1023 * one of the supported codes in <signal.h>
1025 * Snag is unless something is looking at the message queue
1026 * nothing happens :-(
1030 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1032 croak("Cannot set timer");
1038 KillTimer(NULL,timerid);
1045 #ifdef HAVE_DES_FCRYPT
1046 extern char * des_fcrypt(char *cbuf, const char *txt, const char *salt);
1049 win32_crypt(const char *txt, const char *salt)
1052 return des_fcrypt(crypt_buffer, txt, salt);
1056 #ifdef USE_FIXED_OSFHANDLE
1058 EXTERN_C int __cdecl _alloc_osfhnd(void);
1059 EXTERN_C int __cdecl _set_osfhnd(int fh, long value);
1060 EXTERN_C void __cdecl _lock_fhandle(int);
1061 EXTERN_C void __cdecl _unlock_fhandle(int);
1062 EXTERN_C void __cdecl _unlock(int);
1064 #if (_MSC_VER >= 1000)
1066 long osfhnd; /* underlying OS file HANDLE */
1067 char osfile; /* attributes of file (e.g., open in text mode?) */
1068 char pipech; /* one char buffer for handles opened on pipes */
1069 #if defined (_MT) && !defined (DLL_FOR_WIN32S)
1071 CRITICAL_SECTION lock;
1072 #endif /* defined (_MT) && !defined (DLL_FOR_WIN32S) */
1075 EXTERN_C ioinfo * __pioinfo[];
1077 #define IOINFO_L2E 5
1078 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
1079 #define _pioinfo(i) (__pioinfo[i >> IOINFO_L2E] + (i & (IOINFO_ARRAY_ELTS - 1)))
1080 #define _osfile(i) (_pioinfo(i)->osfile)
1082 #else /* (_MSC_VER >= 1000) */
1083 extern char _osfile[];
1084 #endif /* (_MSC_VER >= 1000) */
1086 #define FOPEN 0x01 /* file handle open */
1087 #define FAPPEND 0x20 /* file handle opened O_APPEND */
1088 #define FDEV 0x40 /* file handle refers to device */
1089 #define FTEXT 0x80 /* file handle is in text mode */
1091 #define _STREAM_LOCKS 26 /* Table of stream locks */
1092 #define _LAST_STREAM_LOCK (_STREAM_LOCKS+_NSTREAM_-1) /* Last stream lock */
1093 #define _FH_LOCKS (_LAST_STREAM_LOCK+1) /* Table of fh locks */
1096 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1099 * This function allocates a free C Runtime file handle and associates
1100 * it with the Win32 HANDLE specified by the first parameter. This is a
1101 * temperary fix for WIN95's brain damage GetFileType() error on socket
1102 * we just bypass that call for socket
1105 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1106 * int flags - flags to associate with C Runtime file handle.
1109 * returns index of entry in fh, if successful
1110 * return -1, if no free entry is found
1114 *******************************************************************************/
1117 my_open_osfhandle(long osfhandle, int flags)
1120 char fileflags; /* _osfile flags */
1122 /* copy relevant flags from second parameter */
1125 if(flags & O_APPEND)
1126 fileflags |= FAPPEND;
1131 /* attempt to allocate a C Runtime file handle */
1132 if((fh = _alloc_osfhnd()) == -1) {
1133 errno = EMFILE; /* too many open files */
1134 _doserrno = 0L; /* not an OS error */
1135 return -1; /* return error to caller */
1138 /* the file is open. now, set the info in _osfhnd array */
1139 _set_osfhnd(fh, osfhandle);
1141 fileflags |= FOPEN; /* mark as open */
1143 #if (_MSC_VER >= 1000)
1144 _osfile(fh) = fileflags; /* set osfile entry */
1145 _unlock_fhandle(fh);
1147 _osfile[fh] = fileflags; /* set osfile entry */
1148 _unlock(fh+_FH_LOCKS); /* unlock handle */
1151 return fh; /* return handle */
1154 #define _open_osfhandle my_open_osfhandle
1155 #endif /* USE_FIXED_OSFHANDLE */
1157 /* simulate flock by locking a range on the file */
1159 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1160 #define LK_LEN 0xffff0000
1163 win32_flock(int fd, int oper)
1170 croak("flock() unimplemented on this platform");
1173 fh = (HANDLE)_get_osfhandle(fd);
1174 memset(&o, 0, sizeof(o));
1177 case LOCK_SH: /* shared lock */
1178 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1180 case LOCK_EX: /* exclusive lock */
1181 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1183 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1184 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1186 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1187 LK_ERR(LockFileEx(fh,
1188 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1189 0, LK_LEN, 0, &o),i);
1191 case LOCK_UN: /* unlock lock */
1192 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1194 default: /* unknown */
1205 * redirected io subsystem for all XS modules
1218 return (&(_environ));
1221 /* the rest are the remapped stdio routines */
1241 win32_ferror(FILE *fp)
1243 return (ferror(fp));
1248 win32_feof(FILE *fp)
1254 * Since the errors returned by the socket error function
1255 * WSAGetLastError() are not known by the library routine strerror
1256 * we have to roll our own.
1260 win32_strerror(int e)
1262 #ifndef __BORLANDC__ /* Borland intolerance */
1263 extern int sys_nerr;
1267 if(e < 0 || e > sys_nerr) {
1272 if(FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
1273 strerror_buffer, sizeof(strerror_buffer), NULL) == 0)
1274 strcpy(strerror_buffer, "Unknown Error");
1276 return strerror_buffer;
1282 win32_str_os_error(void *sv, DWORD dwErr)
1286 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
1287 |FORMAT_MESSAGE_IGNORE_INSERTS
1288 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
1289 dwErr, 0, (char *)&sMsg, 1, NULL);
1291 while (0 < dwLen && isspace(sMsg[--dwLen]))
1293 if ('.' != sMsg[dwLen])
1298 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
1299 dwLen = sprintf(sMsg,
1300 "Unknown error #0x%lX (lookup 0x%lX)",
1301 dwErr, GetLastError());
1303 sv_setpvn((SV*)sv, sMsg, dwLen);
1309 win32_fprintf(FILE *fp, const char *format, ...)
1312 va_start(marker, format); /* Initialize variable arguments. */
1314 return (vfprintf(fp, format, marker));
1318 win32_printf(const char *format, ...)
1321 va_start(marker, format); /* Initialize variable arguments. */
1323 return (vprintf(format, marker));
1327 win32_vfprintf(FILE *fp, const char *format, va_list args)
1329 return (vfprintf(fp, format, args));
1333 win32_vprintf(const char *format, va_list args)
1335 return (vprintf(format, args));
1339 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
1341 return fread(buf, size, count, fp);
1345 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
1347 return fwrite(buf, size, count, fp);
1351 win32_fopen(const char *filename, const char *mode)
1353 if (stricmp(filename, "/dev/null")==0)
1354 return fopen("NUL", mode);
1355 return fopen(filename, mode);
1358 #ifndef USE_SOCKETS_AS_HANDLES
1360 #define fdopen my_fdopen
1364 win32_fdopen( int handle, const char *mode)
1366 return fdopen(handle, (char *) mode);
1370 win32_freopen( const char *path, const char *mode, FILE *stream)
1372 if (stricmp(path, "/dev/null")==0)
1373 return freopen("NUL", mode, stream);
1374 return freopen(path, mode, stream);
1378 win32_fclose(FILE *pf)
1380 return my_fclose(pf); /* defined in win32sck.c */
1384 win32_fputs(const char *s,FILE *pf)
1386 return fputs(s, pf);
1390 win32_fputc(int c,FILE *pf)
1396 win32_ungetc(int c,FILE *pf)
1398 return ungetc(c,pf);
1402 win32_getc(FILE *pf)
1408 win32_fileno(FILE *pf)
1414 win32_clearerr(FILE *pf)
1421 win32_fflush(FILE *pf)
1427 win32_ftell(FILE *pf)
1433 win32_fseek(FILE *pf,long offset,int origin)
1435 return fseek(pf, offset, origin);
1439 win32_fgetpos(FILE *pf,fpos_t *p)
1441 return fgetpos(pf, p);
1445 win32_fsetpos(FILE *pf,const fpos_t *p)
1447 return fsetpos(pf, p);
1451 win32_rewind(FILE *pf)
1471 win32_fstat(int fd,struct stat *sbufptr)
1473 return fstat(fd,sbufptr);
1477 win32_pipe(int *pfd, unsigned int size, int mode)
1479 return _pipe(pfd, size, mode);
1483 win32_popen(const char *command, const char *mode)
1485 return _popen(command, mode);
1489 win32_pclose(FILE *pf)
1495 win32_setmode(int fd, int mode)
1497 return setmode(fd, mode);
1501 win32_lseek(int fd, long offset, int origin)
1503 return lseek(fd, offset, origin);
1513 win32_open(const char *path, int flag, ...)
1519 pmode = va_arg(ap, int);
1522 if (stricmp(path, "/dev/null")==0)
1523 return open("NUL", flag, pmode);
1524 return open(path,flag,pmode);
1546 win32_dup2(int fd1,int fd2)
1548 return dup2(fd1,fd2);
1552 win32_read(int fd, void *buf, unsigned int cnt)
1554 return read(fd, buf, cnt);
1558 win32_write(int fd, const void *buf, unsigned int cnt)
1560 return write(fd, buf, cnt);
1564 win32_mkdir(const char *dir, int mode)
1566 return mkdir(dir); /* just ignore mode */
1570 win32_rmdir(const char *dir)
1576 win32_chdir(const char *dir)
1582 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
1586 status = spawnvp(mode, cmdname, (char * const *) argv);
1587 #ifndef __BORLANDC__
1588 /* XXX For the P_NOWAIT case, Borland RTL returns pinfo.dwProcessId
1589 * while VC RTL returns pinfo.hProcess. For purposes of the custom
1590 * implementation of win32_wait(), we assume the latter.
1592 if (mode == P_NOWAIT && status >= 0)
1593 w32_child_pids[w32_num_children++] = (HANDLE)status;
1599 win32_execvp(const char *cmdname, const char *const *argv)
1601 return execvp(cmdname, (char *const *)argv);
1605 win32_perror(const char *str)
1611 win32_setbuf(FILE *pf, char *buf)
1617 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
1619 return setvbuf(pf, buf, type, size);
1623 win32_flushall(void)
1629 win32_fcloseall(void)
1635 win32_fgets(char *s, int n, FILE *pf)
1637 return fgets(s, n, pf);
1647 win32_fgetc(FILE *pf)
1653 win32_putc(int c, FILE *pf)
1659 win32_puts(const char *s)
1671 win32_putchar(int c)
1678 #ifndef USE_PERL_SBRK
1680 static char *committed = NULL;
1681 static char *base = NULL;
1682 static char *reserved = NULL;
1683 static char *brk = NULL;
1684 static DWORD pagesize = 0;
1685 static DWORD allocsize = 0;
1693 GetSystemInfo(&info);
1694 /* Pretend page size is larger so we don't perpetually
1695 * call the OS to commit just one page ...
1697 pagesize = info.dwPageSize << 3;
1698 allocsize = info.dwAllocationGranularity;
1700 /* This scheme fails eventually if request for contiguous
1701 * block is denied so reserve big blocks - this is only
1702 * address space not memory ...
1704 if (brk+need >= reserved)
1706 DWORD size = 64*1024*1024;
1708 if (committed && reserved && committed < reserved)
1710 /* Commit last of previous chunk cannot span allocations */
1711 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
1713 committed = reserved;
1715 /* Reserve some (more) space
1716 * Note this is a little sneaky, 1st call passes NULL as reserved
1717 * so lets system choose where we start, subsequent calls pass
1718 * the old end address so ask for a contiguous block
1720 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
1723 reserved = addr+size;
1738 if (brk > committed)
1740 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
1741 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
1756 win32_malloc(size_t size)
1758 return malloc(size);
1762 win32_calloc(size_t numitems, size_t size)
1764 return calloc(numitems,size);
1768 win32_realloc(void *block, size_t size)
1770 return realloc(block,size);
1774 win32_free(void *block)
1781 win32_open_osfhandle(long handle, int flags)
1783 return _open_osfhandle(handle, flags);
1787 win32_get_osfhandle(int fd)
1789 return _get_osfhandle(fd);
1800 SV *sv = sv_newmortal();
1801 /* Make one call with zero size - return value is required size */
1802 DWORD len = GetCurrentDirectory((DWORD)0,NULL);
1803 SvUPGRADE(sv,SVt_PV);
1805 SvCUR(sv) = GetCurrentDirectory((DWORD) SvLEN(sv), SvPVX(sv));
1808 * then it worked, set PV valid,
1809 * else leave it 'undef'
1823 croak("usage: Win32::SetCurrentDirectory($cwd)");
1824 if (SetCurrentDirectory(SvPV(ST(0),na)))
1831 XS(w32_GetNextAvailDrive)
1835 char root[] = "_:\\";
1838 if (GetDriveType(root) == 1) {
1847 XS(w32_GetLastError)
1850 XSRETURN_IV(GetLastError());
1857 char *name = getlogin_buffer;
1858 DWORD size = sizeof(getlogin_buffer);
1859 if (GetUserName(name,&size)) {
1860 /* size includes NULL */
1861 ST(0) = sv_2mortal(newSVpv(name,size-1));
1871 char name[MAX_COMPUTERNAME_LENGTH+1];
1872 DWORD size = sizeof(name);
1873 if (GetComputerName(name,&size)) {
1874 /* size does NOT include NULL :-( */
1875 ST(0) = sv_2mortal(newSVpv(name,size));
1887 DWORD size = sizeof(name);
1888 if (GetUserName(name,&size)) {
1890 DWORD sidlen = sizeof(sid);
1892 DWORD dnamelen = sizeof(dname);
1894 if (LookupAccountName(NULL, name, &sid, &sidlen,
1895 dname, &dnamelen, &snu)) {
1896 XSRETURN_PV(dname); /* all that for this */
1907 DWORD flags, filecomplen;
1908 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
1909 &flags, fsname, sizeof(fsname))) {
1910 if (GIMME == G_ARRAY) {
1911 XPUSHs(sv_2mortal(newSVpv(fsname,0)));
1912 XPUSHs(sv_2mortal(newSViv(flags)));
1913 XPUSHs(sv_2mortal(newSViv(filecomplen)));
1917 XSRETURN_PV(fsname);
1923 XS(w32_GetOSVersion)
1926 OSVERSIONINFO osver;
1928 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1929 if (GetVersionEx(&osver)) {
1930 XPUSHs(newSVpv(osver.szCSDVersion, 0));
1931 XPUSHs(newSViv(osver.dwMajorVersion));
1932 XPUSHs(newSViv(osver.dwMinorVersion));
1933 XPUSHs(newSViv(osver.dwBuildNumber));
1934 XPUSHs(newSViv(osver.dwPlatformId));
1945 XSRETURN_IV(IsWinNT());
1952 XSRETURN_IV(IsWin95());
1956 XS(w32_FormatMessage)
1963 croak("usage: Win32::FormatMessage($errno)");
1965 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
1966 &source, SvIV(ST(0)), 0,
1967 msgbuf, sizeof(msgbuf)-1, NULL))
1968 XSRETURN_PV(msgbuf);
1978 PROCESS_INFORMATION stProcInfo;
1979 STARTUPINFO stStartInfo;
1980 BOOL bSuccess = FALSE;
1983 croak("usage: Win32::Spawn($cmdName, $args, $PID)");
1985 cmd = SvPV(ST(0),na);
1986 args = SvPV(ST(1), na);
1988 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
1989 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
1990 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
1991 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
1994 cmd, /* Image path */
1995 args, /* Arguments for command line */
1996 NULL, /* Default process security */
1997 NULL, /* Default thread security */
1998 FALSE, /* Must be TRUE to use std handles */
1999 NORMAL_PRIORITY_CLASS, /* No special scheduling */
2000 NULL, /* Inherit our environment block */
2001 NULL, /* Inherit our currrent directory */
2002 &stStartInfo, /* -> Startup info */
2003 &stProcInfo)) /* <- Process info (if OK) */
2005 CloseHandle(stProcInfo.hThread);/* library source code does this. */
2006 sv_setiv(ST(2), stProcInfo.dwProcessId);
2009 XSRETURN_IV(bSuccess);
2013 XS(w32_GetTickCount)
2016 XSRETURN_IV(GetTickCount());
2020 XS(w32_GetShortPathName)
2027 croak("usage: Win32::GetShortPathName($longPathName)");
2029 shortpath = sv_mortalcopy(ST(0));
2030 SvUPGRADE(shortpath, SVt_PV);
2031 /* src == target is allowed */
2033 len = GetShortPathName(SvPVX(shortpath),
2036 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
2038 SvCUR_set(shortpath,len);
2051 croak("usage: Win32::Sleep($milliseconds)");
2056 #define TMPBUFSZ 1024
2057 #define MAX_LENGTH 2048
2058 #define SUCCESSRETURNED(x) (x == ERROR_SUCCESS)
2059 #define REGRETURN(x) XSRETURN_IV(SUCCESSRETURNED(x))
2060 #define SvHKEY(index) (HKEY)((unsigned long)SvIV(index))
2061 #define SETIV(index,value) sv_setiv(ST(index), value)
2062 #define SETNV(index,value) sv_setnv(ST(index), value)
2063 #define SETPV(index,string) sv_setpv(ST(index), string)
2064 #define SETPVN(index, buffer, length) sv_setpvn(ST(index), (char*)buffer, length)
2065 #define SETHKEY(index, hkey) SETIV(index,(long)hkey)
2067 static time_t ft2timet(FILETIME *ft)
2072 FileTimeToSystemTime(ft, &st);
2073 tm.tm_sec = st.wSecond;
2074 tm.tm_min = st.wMinute;
2075 tm.tm_hour = st.wHour;
2076 tm.tm_mday = st.wDay;
2077 tm.tm_mon = st.wMonth - 1;
2078 tm.tm_year = st.wYear - 1900;
2079 tm.tm_wday = st.wDayOfWeek;
2082 return mktime (&tm);
2092 croak("usage: Win32::RegCloseKey($hkey);\n");
2095 REGRETURN(RegCloseKey(SvHKEY(ST(0))));
2099 XS(w32_RegConnectRegistry)
2106 croak("usage: Win32::RegConnectRegistry($machine, $hkey, $handle);\n");
2109 if(SUCCESSRETURNED(RegConnectRegistry((char *)SvPV(ST(0), na), SvHKEY(ST(1)), &handle)))
2118 XS(w32_RegCreateKey)
2127 croak("usage: Win32::RegCreateKey($hkey, $subkey, $handle);\n");
2130 retval = RegCreateKeyEx(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS,
2131 NULL, &handle, &disposition);
2133 if(SUCCESSRETURNED(retval))
2142 XS(w32_RegCreateKeyEx)
2146 unsigned int length;
2151 DWORD options, disposition;
2153 SECURITY_ATTRIBUTES sa, *psa;
2157 croak("usage: Win32::RegCreateKeyEx($hkey, $subkey, $reserved, $class, $options, $sam, "
2158 "$security, $handle, $disposition);\n");
2161 hkey = SvHKEY(ST(0));
2162 subkey = (char *)SvPV(ST(1), na);
2163 keyclass = (char *)SvPV(ST(3), na);
2164 options = (DWORD) ((unsigned long)SvIV(ST(4)));
2165 sam = (REGSAM) ((unsigned long)SvIV(ST(5)));
2166 psa = (SECURITY_ATTRIBUTES*)SvPV(ST(6), length);
2167 if(length != sizeof(SECURITY_ATTRIBUTES))
2170 memset(&sa, 0, sizeof(SECURITY_ATTRIBUTES));
2171 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
2174 retval = RegCreateKeyEx(hkey, subkey, 0, keyclass, options, sam,
2175 psa, &handle, &disposition);
2177 if(SUCCESSRETURNED(retval))
2180 SETPVN(6, &sa, sizeof(sa));
2183 SETIV(8,disposition);
2190 XS(w32_RegDeleteKey)
2196 croak("usage: Win32::RegDeleteKey($hkey, $subkey);\n");
2199 REGRETURN(RegDeleteKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na)));
2203 XS(w32_RegDeleteValue)
2209 croak("usage: Win32::RegDeleteValue($hkey, $valname);\n");
2212 REGRETURN(RegDeleteValue(SvHKEY(ST(0)), (char *)SvPV(ST(1), na)));
2220 char keybuffer[TMPBUFSZ];
2224 croak("usage: Win32::RegEnumKey($hkey, $idx, $subkeyname);\n");
2227 if(SUCCESSRETURNED(RegEnumKey(SvHKEY(ST(0)), SvIV(ST(1)), keybuffer, sizeof(keybuffer))))
2229 SETPV(2, keybuffer);
2236 XS(w32_RegEnumKeyEx)
2241 DWORD keysz, classsz;
2242 char keybuffer[TMPBUFSZ];
2243 char classbuffer[TMPBUFSZ];
2249 croak("usage: Win32::RegEnumKeyEx($hkey, $idx, $subkeyname, $reserved, $class, $time);\n");
2252 keysz = sizeof(keybuffer);
2253 classsz = sizeof(classbuffer);
2254 retval = RegEnumKeyEx(SvHKEY(ST(0)), SvIV(ST(1)), keybuffer, &keysz, 0,
2255 classbuffer, &classsz, &filetime);
2256 if(SUCCESSRETURNED(retval))
2258 SETPV(2, keybuffer);
2259 SETPV(4, classbuffer);
2260 SETIV(5, ft2timet(&filetime));
2267 XS(w32_RegEnumValue)
2271 DWORD type, namesz, valsz;
2273 static HKEY last_hkey;
2274 char myvalbuf[MAX_LENGTH];
2275 char mynambuf[MAX_LENGTH];
2279 croak("usage: Win32::RegEnumValue($hkey, $i, $name, $reserved, $type, $value);\n");
2282 hkey = SvHKEY(ST(0));
2284 // If this is a new key, find out how big the maximum name and value sizes are and
2285 // allocate space for them. Free any old storage and set the old key value to the
2288 if(hkey != (HKEY)last_hkey)
2290 char keyclass[TMPBUFSZ];
2291 DWORD classsz, subkeys, maxsubkey, maxclass, values, salen, maxnamesz, maxvalsz;
2293 classsz = sizeof(keyclass);
2294 retval = RegQueryInfoKey(hkey, keyclass, &classsz, 0, &subkeys, &maxsubkey, &maxclass,
2295 &values, &maxnamesz, &maxvalsz, &salen, &ft);
2297 if(!SUCCESSRETURNED(retval))
2301 memset(myvalbuf, 0, MAX_LENGTH);
2302 memset(mynambuf, 0, MAX_LENGTH);
2306 namesz = MAX_LENGTH;
2308 retval = RegEnumValue(hkey, SvIV(ST(1)), mynambuf, &namesz, 0, &type, (LPBYTE) myvalbuf, &valsz);
2309 if(!SUCCESSRETURNED(retval))
2318 // return includes the null terminator so delete it if REG_SZ, REG_MULTI_SZ or REG_EXPAND_SZ
2327 SETPVN(5, myvalbuf, valsz);
2330 case REG_DWORD_BIG_ENDIAN:
2332 BYTE tmp = myvalbuf[0];
2333 myvalbuf[0] = myvalbuf[3];
2336 myvalbuf[1] = myvalbuf[2];
2339 case REG_DWORD_LITTLE_ENDIAN: // same as REG_DWORD
2340 SETNV(5, (double)*((DWORD*)myvalbuf));
2358 croak("usage: Win32::RegFlushKey($hkey);\n");
2361 REGRETURN(RegFlushKey(SvHKEY(ST(0))));
2365 XS(w32_RegGetKeySecurity)
2368 SECURITY_DESCRIPTOR sd;
2373 croak("usage: Win32::RegGetKeySecurity($hkey, $security_info, $security_descriptor);\n");
2376 if(SUCCESSRETURNED(RegGetKeySecurity(SvHKEY(ST(0)), SvIV(ST(1)), &sd, &sdsz)))
2378 SETPVN(2, &sd, sdsz);
2391 croak("usage: Win32::RegLoadKey($hkey, $subkey, $filename);\n");
2394 REGRETURN(RegLoadKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), (char *)SvPV(ST(2), na)));
2398 XS(w32_RegNotifyChangeKeyValue)
2400 croak("Win32::RegNotifyChangeKeyValue not yet implemented!\n");
2411 croak("usage: Win32::RegOpenKey($hkey, $subkey, $handle);\n");
2414 if(SUCCESSRETURNED(RegOpenKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), &handle)))
2423 XS(w32_RegOpenKeyEx)
2430 croak("usage: Win32::RegOpenKeyEx($hkey, $subkey, $reserved, $sam, $handle);\n");
2433 if(SUCCESSRETURNED(RegOpenKeyEx(SvHKEY(ST(0)), (char *)SvPV(ST(1), na),
2434 0, (REGSAM) ((unsigned long)SvIV(ST(3))), &handle)))
2442 #pragma optimize("", off)
2444 XS(w32_RegQueryInfoKey)
2449 char keyclass[TMPBUFSZ];
2450 DWORD subkeys, maxsubkey, maxclass, values, maxvalname, maxvaldata;
2451 DWORD seclen, classsz;
2457 croak("usage: Win32::RegQueryInfoKey($hkey, $class, $numsubkeys, $maxsubkey,"
2458 "$maxclass, $values, $maxvalname, $maxvaldata, $secdesclen,"
2459 "$lastwritetime);\n");
2462 classsz = sizeof(keyclass);
2463 retval = RegQueryInfoKey(SvHKEY(ST(0)), keyclass, &classsz, 0, &subkeys, &maxsubkey,
2464 &maxclass, &values, &maxvalname, &maxvaldata,
2466 if(SUCCESSRETURNED(retval))
2470 SETIV(3, maxsubkey);
2473 SETIV(6, maxvalname);
2474 SETIV(7, maxvaldata);
2476 SETIV(9, ft2timet(&ft));
2481 #pragma optimize("", on)
2484 XS(w32_RegQueryValue)
2488 unsigned char databuffer[TMPBUFSZ*2];
2489 long datasz = sizeof(databuffer);
2493 croak("usage: Win32::RegQueryValue($hkey, $valuename, $data);\n");
2496 if(SUCCESSRETURNED(RegQueryValue(SvHKEY(ST(0)), SvPV(ST(1), na), (char*)databuffer, &datasz)))
2498 // return includes the null terminator so delete it
2499 SETPVN(2, databuffer, --datasz);
2506 XS(w32_RegQueryValueEx)
2510 unsigned char databuffer[TMPBUFSZ*2];
2511 DWORD datasz = sizeof(databuffer);
2514 LPBYTE ptr = databuffer;
2518 croak("usage: Win32::RegQueryValueEx($hkey, $valuename, $reserved, $type, $data);\n");
2521 result = RegQueryValueEx(SvHKEY(ST(0)), SvPV(ST(1), na), 0, &type, ptr, &datasz);
2522 if(result == ERROR_MORE_DATA)
2524 New(0, ptr, datasz+1, BYTE);
2525 result = RegQueryValueEx(SvHKEY(ST(0)), SvPV(ST(1), na), 0, &type, ptr, &datasz);
2527 if(SUCCESSRETURNED(result))
2531 // return includes the null terminator so delete it if REG_SZ, REG_MULTI_SZ or REG_EXPAND_SZ
2539 SETPVN(4, ptr, datasz);
2542 case REG_DWORD_BIG_ENDIAN:
2551 case REG_DWORD_LITTLE_ENDIAN: // same as REG_DWORD
2552 SETNV(4, (double)*((DWORD*)ptr));
2559 if(ptr != databuffer)
2564 if(ptr != databuffer)
2571 XS(w32_RegReplaceKey)
2577 croak("usage: Win32::RegReplaceKey($hkey, $subkey, $newfile, $oldfile);\n");
2580 REGRETURN(RegReplaceKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), (char *)SvPV(ST(2), na), (char *)SvPV(ST(3), na)));
2584 XS(w32_RegRestoreKey)
2588 if(items < 2 || items > 3)
2590 croak("usage: Win32::RegRestoreKey($hkey, $filename [, $flags]);\n");
2593 REGRETURN(RegRestoreKey(SvHKEY(ST(0)), (char*)SvPV(ST(1), na), (DWORD)((items == 3) ? SvIV(ST(2)) : 0)));
2603 croak("usage: Win32::RegSaveKey($hkey, $filename);\n");
2606 REGRETURN(RegSaveKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), NULL));
2610 XS(w32_RegSetKeySecurity)
2616 croak("usage: Win32::RegSetKeySecurity($hkey, $security_info, $security_descriptor);\n");
2619 REGRETURN(RegSetKeySecurity(SvHKEY(ST(0)), SvIV(ST(1)), (SECURITY_DESCRIPTOR*)SvPV(ST(2), na)));
2632 croak("usage: Win32::RegSetValue($hkey, $subKey, $type, $data);\n");
2635 DWORD type = SvIV(ST(2));
2636 if(type != REG_SZ && type != REG_EXPAND_SZ)
2638 croak("Win32::RegSetValue: Type was not REG_SZ or REG_EXPAND_SZ, cannot set %s\n", (char *)SvPV(ST(1), na));
2641 buffer = (char *)SvPV(ST(3), size);
2642 REGRETURN(RegSetValue(SvHKEY(ST(0)), SvPV(ST(1), na), REG_SZ, buffer, size));
2646 XS(w32_RegSetValueEx)
2657 croak("usage: Win32::RegSetValueEx($hkey, $valname, $reserved, $type, $data);\n");
2660 type = (DWORD)SvIV(ST(3));
2667 buffer = (char *)SvPV(ST(4), size);
2668 if(type != REG_BINARY)
2669 size++; // include null terminator in size
2671 REGRETURN(RegSetValueEx(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), 0, type, (PBYTE) buffer, size));
2674 case REG_DWORD_BIG_ENDIAN:
2675 case REG_DWORD_LITTLE_ENDIAN: // Same as REG_DWORD
2676 val = (DWORD)SvIV(ST(4));
2677 REGRETURN(RegSetValueEx(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), 0, type, (PBYTE) &val, sizeof(DWORD)));
2681 croak("Win32::RegSetValueEx: Type not specified, cannot set %s\n", (char *)SvPV(ST(1), na));
2686 XS(w32_RegUnloadKey)
2692 croak("usage: Win32::RegUnLoadKey($hkey, $subkey);\n");
2695 REGRETURN(RegUnLoadKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na)));
2699 XS(w32_RegisterServer)
2702 BOOL bSuccess = FALSE;
2703 HINSTANCE hInstance;
2704 unsigned int length;
2709 croak("usage: Win32::RegisterServer($LibraryName)\n");
2712 hInstance = LoadLibrary((char *)SvPV(ST(0), length));
2713 if(hInstance != NULL)
2715 sFunc = GetProcAddress(hInstance, "DllRegisterServer");
2718 bSuccess = (sFunc() == 0);
2720 FreeLibrary(hInstance);
2731 XS(w32_UnregisterServer)
2734 BOOL bSuccess = FALSE;
2735 HINSTANCE hInstance;
2736 unsigned int length;
2741 croak("usage: Win32::UnregisterServer($LibraryName)\n");
2744 hInstance = LoadLibrary((char *)SvPV(ST(0), length));
2745 if(hInstance != NULL)
2747 sFunc = GetProcAddress(hInstance, "DllUnregisterServer");
2750 bSuccess = (sFunc() == 0);
2752 FreeLibrary(hInstance);
2764 Perl_init_os_extras()
2766 char *file = __FILE__;
2769 /* these names are Activeware compatible */
2770 newXS("Win32::GetCwd", w32_GetCwd, file);
2771 newXS("Win32::SetCwd", w32_SetCwd, file);
2772 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
2773 newXS("Win32::GetLastError", w32_GetLastError, file);
2774 newXS("Win32::LoginName", w32_LoginName, file);
2775 newXS("Win32::NodeName", w32_NodeName, file);
2776 newXS("Win32::DomainName", w32_DomainName, file);
2777 newXS("Win32::FsType", w32_FsType, file);
2778 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
2779 newXS("Win32::IsWinNT", w32_IsWinNT, file);
2780 newXS("Win32::IsWin95", w32_IsWin95, file);
2781 newXS("Win32::FormatMessage", w32_FormatMessage, file);
2782 newXS("Win32::Spawn", w32_Spawn, file);
2783 newXS("Win32::GetTickCount", w32_GetTickCount, file);
2784 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
2785 newXS("Win32::Sleep", w32_Sleep, file);
2787 /* the following extensions are used interally and may be changed at any time */
2788 /* therefore no documentation is provided */
2789 newXS("Win32::RegCloseKey", w32_RegCloseKey, file);
2790 newXS("Win32::RegConnectRegistry", w32_RegConnectRegistry, file);
2791 newXS("Win32::RegCreateKey", w32_RegCreateKey, file);
2792 newXS("Win32::RegCreateKeyEx", w32_RegCreateKeyEx, file);
2793 newXS("Win32::RegDeleteKey", w32_RegDeleteKey, file);
2794 newXS("Win32::RegDeleteValue", w32_RegDeleteValue, file);
2796 newXS("Win32::RegEnumKey", w32_RegEnumKey, file);
2797 newXS("Win32::RegEnumKeyEx", w32_RegEnumKeyEx, file);
2798 newXS("Win32::RegEnumValue", w32_RegEnumValue, file);
2800 newXS("Win32::RegFlushKey", w32_RegFlushKey, file);
2801 newXS("Win32::RegGetKeySecurity", w32_RegGetKeySecurity, file);
2803 newXS("Win32::RegLoadKey", w32_RegLoadKey, file);
2804 newXS("Win32::RegOpenKey", w32_RegOpenKey, file);
2805 newXS("Win32::RegOpenKeyEx", w32_RegOpenKeyEx, file);
2806 newXS("Win32::RegQueryInfoKey", w32_RegQueryInfoKey, file);
2807 newXS("Win32::RegQueryValue", w32_RegQueryValue, file);
2808 newXS("Win32::RegQueryValueEx", w32_RegQueryValueEx, file);
2810 newXS("Win32::RegReplaceKey", w32_RegReplaceKey, file);
2811 newXS("Win32::RegRestoreKey", w32_RegRestoreKey, file);
2812 newXS("Win32::RegSaveKey", w32_RegSaveKey, file);
2813 newXS("Win32::RegSetKeySecurity", w32_RegSetKeySecurity, file);
2814 newXS("Win32::RegSetValue", w32_RegSetValue, file);
2815 newXS("Win32::RegSetValueEx", w32_RegSetValueEx, file);
2816 newXS("Win32::RegUnloadKey", w32_RegUnloadKey, file);
2818 newXS("Win32::RegisterServer", w32_RegisterServer, file);
2819 newXS("Win32::UnregisterServer", w32_UnregisterServer, file);
2821 /* XXX Bloat Alert! The following Activeware preloads really
2822 * ought to be part of Win32::Sys::*, so they're not included
2825 /* LookupAccountName
2827 * InitiateSystemShutdown
2828 * AbortSystemShutdown
2829 * ExpandEnvrironmentStrings
2834 Perl_win32_init(int *argcp, char ***argvp)
2836 /* Disable floating point errors, Perl will trap the ones we
2837 * care about. VC++ RTL defaults to switching these off
2838 * already, but the Borland RTL doesn't. Since we don't
2839 * want to be at the vendor's whim on the default, we set
2840 * it explicitly here.
2842 #if !defined(_ALPHA_) && !defined(__GNUC__)
2843 _control87(MCW_EM, MCW_EM);
2848 #ifdef USE_BINMODE_SCRIPTS
2851 win32_strip_return(SV *sv)
2853 char *s = SvPVX(sv);
2854 char *e = s+SvCUR(sv);
2858 if (*s == '\r' && s[1] == '\n')
2868 SvCUR_set(sv,d-SvPVX(sv));