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))
720 chown(const char *path, uid_t owner, gid_t group)
727 kill(int pid, int sig)
729 HANDLE hProcess= OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
731 if (hProcess == NULL) {
732 croak("kill process failed!\n");
735 if (!TerminateProcess(hProcess, sig))
736 croak("kill process failed!\n");
737 CloseHandle(hProcess);
746 DllExport unsigned int
747 win32_sleep(unsigned int t)
754 win32_stat(const char *path, struct stat *buffer)
757 const char *p = path;
758 int l = strlen(path);
762 switch(path[l - 1]) {
765 if (path[l - 2] != ':') {
766 strncpy(t, path, l - 1);
772 res = stat(p,buffer);
775 if (S_ISDIR(buffer->st_mode))
776 buffer->st_mode |= S_IWRITE | S_IEXEC;
777 else if (S_ISREG(buffer->st_mode)) {
778 if (l >= 4 && path[l-4] == '.') {
779 const char *e = path + l - 3;
780 if (strnicmp(e,"exe",3)
781 && strnicmp(e,"bat",3)
782 && strnicmp(e,"com",3)
783 && (IsWin95() || strnicmp(e,"cmd",3)))
784 buffer->st_mode &= ~S_IEXEC;
786 buffer->st_mode |= S_IEXEC;
789 buffer->st_mode &= ~S_IEXEC;
796 #ifndef USE_WIN32_RTL_ENV
798 BOOL GetRegStr(HKEY hkey, const char *lpszValueName, char *lpszDefault, char *lpszData, unsigned long *lpdwDataLen)
799 { // Retrieve a REG_SZ or REG_EXPAND_SZ from the registry
801 DWORD type, dwDataLen = *lpdwDataLen;
802 const char *subkey = "Software\\Perl";
803 char szBuffer[MAX_PATH+1];
806 retval = RegOpenKeyEx(hkey, subkey, 0, KEY_READ, &handle);
807 if(retval == ERROR_SUCCESS)
809 retval = RegQueryValueEx(handle, lpszValueName, 0, &type, (LPBYTE)lpszData, &dwDataLen);
811 if(retval == ERROR_SUCCESS && (type == REG_SZ || type == REG_EXPAND_SZ))
813 if(type != REG_EXPAND_SZ)
815 *lpdwDataLen = dwDataLen;
818 strcpy(szBuffer, lpszData);
819 dwDataLen = ExpandEnvironmentStrings(szBuffer, lpszData, *lpdwDataLen);
820 if(dwDataLen < *lpdwDataLen)
822 *lpdwDataLen = dwDataLen;
828 strcpy(lpszData, lpszDefault);
832 char* GetRegStr(const char *lpszValueName, char *lpszDefault, char *lpszData, unsigned long *lpdwDataLen)
834 if(!GetRegStr(HKEY_CURRENT_USER, lpszValueName, lpszDefault, lpszData, lpdwDataLen))
836 GetRegStr(HKEY_LOCAL_MACHINE, lpszValueName, lpszDefault, lpszData, lpdwDataLen);
838 if(*lpszData == '\0')
844 win32_getenv(const char *name)
846 static char *curitem = Nullch;
847 static DWORD curlen = 512;
850 New(1305,curitem,curlen,char);
851 if (!(needlen = GetEnvironmentVariable(name,curitem,curlen)))
853 while (needlen > curlen) {
854 Renew(curitem,needlen,char);
856 needlen = GetEnvironmentVariable(name,curitem,curlen);
860 unsigned long dwDataLen = curlen;
861 if(strcmp("PERL5DB", name) == 0)
862 curitem = GetRegStr(name, "", curitem, &dwDataLen);
870 filetime_to_clock(PFILETIME ft)
872 __int64 qw = ft->dwHighDateTime;
874 qw |= ft->dwLowDateTime;
875 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
880 win32_times(struct tms *timebuf)
885 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
887 timebuf->tms_utime = filetime_to_clock(&user);
888 timebuf->tms_stime = filetime_to_clock(&kernel);
889 timebuf->tms_cutime = 0;
890 timebuf->tms_cstime = 0;
893 /* That failed - e.g. Win95 fallback to clock() */
895 timebuf->tms_utime = t;
896 timebuf->tms_stime = 0;
897 timebuf->tms_cutime = 0;
898 timebuf->tms_cstime = 0;
903 /* fix utime() so it works on directories in NT
904 * thanks to Jan Dubois <jan.dubois@ibm.net>
907 filetime_from_time(PFILETIME pFileTime, time_t Time)
909 struct tm *pTM = gmtime(&Time);
910 SYSTEMTIME SystemTime;
915 SystemTime.wYear = pTM->tm_year + 1900;
916 SystemTime.wMonth = pTM->tm_mon + 1;
917 SystemTime.wDay = pTM->tm_mday;
918 SystemTime.wHour = pTM->tm_hour;
919 SystemTime.wMinute = pTM->tm_min;
920 SystemTime.wSecond = pTM->tm_sec;
921 SystemTime.wMilliseconds = 0;
923 return SystemTimeToFileTime(&SystemTime, pFileTime);
927 win32_utime(const char *filename, struct utimbuf *times)
933 struct utimbuf TimeBuffer;
935 int rc = utime(filename,times);
936 /* EACCES: path specifies directory or readonly file */
937 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
942 time(×->actime);
943 times->modtime = times->actime;
946 /* This will (and should) still fail on readonly files */
947 handle = CreateFile(filename, GENERIC_READ | GENERIC_WRITE,
948 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
949 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
950 if (handle == INVALID_HANDLE_VALUE)
953 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
954 filetime_from_time(&ftAccess, times->actime) &&
955 filetime_from_time(&ftWrite, times->modtime) &&
956 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
966 win32_wait(int *status)
971 /* XXX this wait emulation only knows about processes
972 * spawned via win32_spawnvp(P_NOWAIT, ...).
975 DWORD exitcode, waitcode;
977 if (!w32_num_children) {
982 /* if a child exists, wait for it to die */
983 waitcode = WaitForMultipleObjects(w32_num_children,
987 if (waitcode != WAIT_FAILED) {
988 if (waitcode >= WAIT_ABANDONED_0
989 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
990 i = waitcode - WAIT_ABANDONED_0;
992 i = waitcode - WAIT_OBJECT_0;
993 if (GetExitCodeProcess(w32_child_pids[i], &exitcode) ) {
994 CloseHandle(w32_child_pids[i]);
995 *status = (int)((exitcode & 0xff) << 8);
996 retval = (int)w32_child_pids[i];
997 Copy(&w32_child_pids[i+1], &w32_child_pids[i],
998 (w32_num_children-i-1), HANDLE);
1005 errno = GetLastError();
1011 static UINT timerid = 0;
1013 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1015 KillTimer(NULL,timerid);
1020 DllExport unsigned int
1021 win32_alarm(unsigned int sec)
1024 * the 'obvious' implentation is SetTimer() with a callback
1025 * which does whatever receiving SIGALRM would do
1026 * we cannot use SIGALRM even via raise() as it is not
1027 * one of the supported codes in <signal.h>
1029 * Snag is unless something is looking at the message queue
1030 * nothing happens :-(
1034 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1036 croak("Cannot set timer");
1042 KillTimer(NULL,timerid);
1049 #ifdef HAVE_DES_FCRYPT
1050 extern char * des_fcrypt(char *cbuf, const char *txt, const char *salt);
1053 win32_crypt(const char *txt, const char *salt)
1056 return des_fcrypt(crypt_buffer, txt, salt);
1060 #ifdef USE_FIXED_OSFHANDLE
1062 EXTERN_C int __cdecl _alloc_osfhnd(void);
1063 EXTERN_C int __cdecl _set_osfhnd(int fh, long value);
1064 EXTERN_C void __cdecl _lock_fhandle(int);
1065 EXTERN_C void __cdecl _unlock_fhandle(int);
1066 EXTERN_C void __cdecl _unlock(int);
1068 #if (_MSC_VER >= 1000)
1070 long osfhnd; /* underlying OS file HANDLE */
1071 char osfile; /* attributes of file (e.g., open in text mode?) */
1072 char pipech; /* one char buffer for handles opened on pipes */
1073 #if defined (_MT) && !defined (DLL_FOR_WIN32S)
1075 CRITICAL_SECTION lock;
1076 #endif /* defined (_MT) && !defined (DLL_FOR_WIN32S) */
1079 EXTERN_C ioinfo * __pioinfo[];
1081 #define IOINFO_L2E 5
1082 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
1083 #define _pioinfo(i) (__pioinfo[i >> IOINFO_L2E] + (i & (IOINFO_ARRAY_ELTS - 1)))
1084 #define _osfile(i) (_pioinfo(i)->osfile)
1086 #else /* (_MSC_VER >= 1000) */
1087 extern char _osfile[];
1088 #endif /* (_MSC_VER >= 1000) */
1090 #define FOPEN 0x01 /* file handle open */
1091 #define FAPPEND 0x20 /* file handle opened O_APPEND */
1092 #define FDEV 0x40 /* file handle refers to device */
1093 #define FTEXT 0x80 /* file handle is in text mode */
1095 #define _STREAM_LOCKS 26 /* Table of stream locks */
1096 #define _LAST_STREAM_LOCK (_STREAM_LOCKS+_NSTREAM_-1) /* Last stream lock */
1097 #define _FH_LOCKS (_LAST_STREAM_LOCK+1) /* Table of fh locks */
1100 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1103 * This function allocates a free C Runtime file handle and associates
1104 * it with the Win32 HANDLE specified by the first parameter. This is a
1105 * temperary fix for WIN95's brain damage GetFileType() error on socket
1106 * we just bypass that call for socket
1109 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1110 * int flags - flags to associate with C Runtime file handle.
1113 * returns index of entry in fh, if successful
1114 * return -1, if no free entry is found
1118 *******************************************************************************/
1121 my_open_osfhandle(long osfhandle, int flags)
1124 char fileflags; /* _osfile flags */
1126 /* copy relevant flags from second parameter */
1129 if(flags & O_APPEND)
1130 fileflags |= FAPPEND;
1135 /* attempt to allocate a C Runtime file handle */
1136 if((fh = _alloc_osfhnd()) == -1) {
1137 errno = EMFILE; /* too many open files */
1138 _doserrno = 0L; /* not an OS error */
1139 return -1; /* return error to caller */
1142 /* the file is open. now, set the info in _osfhnd array */
1143 _set_osfhnd(fh, osfhandle);
1145 fileflags |= FOPEN; /* mark as open */
1147 #if (_MSC_VER >= 1000)
1148 _osfile(fh) = fileflags; /* set osfile entry */
1149 _unlock_fhandle(fh);
1151 _osfile[fh] = fileflags; /* set osfile entry */
1152 _unlock(fh+_FH_LOCKS); /* unlock handle */
1155 return fh; /* return handle */
1158 #define _open_osfhandle my_open_osfhandle
1159 #endif /* USE_FIXED_OSFHANDLE */
1161 /* simulate flock by locking a range on the file */
1163 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1164 #define LK_LEN 0xffff0000
1167 win32_flock(int fd, int oper)
1174 croak("flock() unimplemented on this platform");
1177 fh = (HANDLE)_get_osfhandle(fd);
1178 memset(&o, 0, sizeof(o));
1181 case LOCK_SH: /* shared lock */
1182 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1184 case LOCK_EX: /* exclusive lock */
1185 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1187 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1188 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1190 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1191 LK_ERR(LockFileEx(fh,
1192 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1193 0, LK_LEN, 0, &o),i);
1195 case LOCK_UN: /* unlock lock */
1196 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1198 default: /* unknown */
1209 * redirected io subsystem for all XS modules
1222 return (&(_environ));
1225 /* the rest are the remapped stdio routines */
1245 win32_ferror(FILE *fp)
1247 return (ferror(fp));
1252 win32_feof(FILE *fp)
1258 * Since the errors returned by the socket error function
1259 * WSAGetLastError() are not known by the library routine strerror
1260 * we have to roll our own.
1264 win32_strerror(int e)
1266 #ifndef __BORLANDC__ /* Borland intolerance */
1267 extern int sys_nerr;
1271 if(e < 0 || e > sys_nerr) {
1276 if(FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
1277 strerror_buffer, sizeof(strerror_buffer), NULL) == 0)
1278 strcpy(strerror_buffer, "Unknown Error");
1280 return strerror_buffer;
1286 win32_str_os_error(void *sv, DWORD dwErr)
1290 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
1291 |FORMAT_MESSAGE_IGNORE_INSERTS
1292 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
1293 dwErr, 0, (char *)&sMsg, 1, NULL);
1295 while (0 < dwLen && isspace(sMsg[--dwLen]))
1297 if ('.' != sMsg[dwLen])
1302 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
1303 dwLen = sprintf(sMsg,
1304 "Unknown error #0x%lX (lookup 0x%lX)",
1305 dwErr, GetLastError());
1307 sv_setpvn((SV*)sv, sMsg, dwLen);
1313 win32_fprintf(FILE *fp, const char *format, ...)
1316 va_start(marker, format); /* Initialize variable arguments. */
1318 return (vfprintf(fp, format, marker));
1322 win32_printf(const char *format, ...)
1325 va_start(marker, format); /* Initialize variable arguments. */
1327 return (vprintf(format, marker));
1331 win32_vfprintf(FILE *fp, const char *format, va_list args)
1333 return (vfprintf(fp, format, args));
1337 win32_vprintf(const char *format, va_list args)
1339 return (vprintf(format, args));
1343 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
1345 return fread(buf, size, count, fp);
1349 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
1351 return fwrite(buf, size, count, fp);
1355 win32_fopen(const char *filename, const char *mode)
1357 if (stricmp(filename, "/dev/null")==0)
1358 return fopen("NUL", mode);
1359 return fopen(filename, mode);
1362 #ifndef USE_SOCKETS_AS_HANDLES
1364 #define fdopen my_fdopen
1368 win32_fdopen( int handle, const char *mode)
1370 return fdopen(handle, (char *) mode);
1374 win32_freopen( const char *path, const char *mode, FILE *stream)
1376 if (stricmp(path, "/dev/null")==0)
1377 return freopen("NUL", mode, stream);
1378 return freopen(path, mode, stream);
1382 win32_fclose(FILE *pf)
1384 return my_fclose(pf); /* defined in win32sck.c */
1388 win32_fputs(const char *s,FILE *pf)
1390 return fputs(s, pf);
1394 win32_fputc(int c,FILE *pf)
1400 win32_ungetc(int c,FILE *pf)
1402 return ungetc(c,pf);
1406 win32_getc(FILE *pf)
1412 win32_fileno(FILE *pf)
1418 win32_clearerr(FILE *pf)
1425 win32_fflush(FILE *pf)
1431 win32_ftell(FILE *pf)
1437 win32_fseek(FILE *pf,long offset,int origin)
1439 return fseek(pf, offset, origin);
1443 win32_fgetpos(FILE *pf,fpos_t *p)
1445 return fgetpos(pf, p);
1449 win32_fsetpos(FILE *pf,const fpos_t *p)
1451 return fsetpos(pf, p);
1455 win32_rewind(FILE *pf)
1475 win32_fstat(int fd,struct stat *sbufptr)
1477 return fstat(fd,sbufptr);
1481 win32_pipe(int *pfd, unsigned int size, int mode)
1483 return _pipe(pfd, size, mode);
1487 win32_popen(const char *command, const char *mode)
1489 return _popen(command, mode);
1493 win32_pclose(FILE *pf)
1499 win32_setmode(int fd, int mode)
1501 return setmode(fd, mode);
1505 win32_lseek(int fd, long offset, int origin)
1507 return lseek(fd, offset, origin);
1517 win32_open(const char *path, int flag, ...)
1523 pmode = va_arg(ap, int);
1526 if (stricmp(path, "/dev/null")==0)
1527 return open("NUL", flag, pmode);
1528 return open(path,flag,pmode);
1550 win32_dup2(int fd1,int fd2)
1552 return dup2(fd1,fd2);
1556 win32_read(int fd, void *buf, unsigned int cnt)
1558 return read(fd, buf, cnt);
1562 win32_write(int fd, const void *buf, unsigned int cnt)
1564 return write(fd, buf, cnt);
1568 win32_mkdir(const char *dir, int mode)
1570 return mkdir(dir); /* just ignore mode */
1574 win32_rmdir(const char *dir)
1580 win32_chdir(const char *dir)
1586 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
1590 status = spawnvp(mode, cmdname, (char * const *) argv);
1591 #ifndef __BORLANDC__
1592 /* XXX For the P_NOWAIT case, Borland RTL returns pinfo.dwProcessId
1593 * while VC RTL returns pinfo.hProcess. For purposes of the custom
1594 * implementation of win32_wait(), we assume the latter.
1596 if (mode == P_NOWAIT && status >= 0)
1597 w32_child_pids[w32_num_children++] = (HANDLE)status;
1603 win32_execvp(const char *cmdname, const char *const *argv)
1605 return execvp(cmdname, (char *const *)argv);
1609 win32_perror(const char *str)
1615 win32_setbuf(FILE *pf, char *buf)
1621 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
1623 return setvbuf(pf, buf, type, size);
1627 win32_flushall(void)
1633 win32_fcloseall(void)
1639 win32_fgets(char *s, int n, FILE *pf)
1641 return fgets(s, n, pf);
1651 win32_fgetc(FILE *pf)
1657 win32_putc(int c, FILE *pf)
1663 win32_puts(const char *s)
1675 win32_putchar(int c)
1682 #ifndef USE_PERL_SBRK
1684 static char *committed = NULL;
1685 static char *base = NULL;
1686 static char *reserved = NULL;
1687 static char *brk = NULL;
1688 static DWORD pagesize = 0;
1689 static DWORD allocsize = 0;
1697 GetSystemInfo(&info);
1698 /* Pretend page size is larger so we don't perpetually
1699 * call the OS to commit just one page ...
1701 pagesize = info.dwPageSize << 3;
1702 allocsize = info.dwAllocationGranularity;
1704 /* This scheme fails eventually if request for contiguous
1705 * block is denied so reserve big blocks - this is only
1706 * address space not memory ...
1708 if (brk+need >= reserved)
1710 DWORD size = 64*1024*1024;
1712 if (committed && reserved && committed < reserved)
1714 /* Commit last of previous chunk cannot span allocations */
1715 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
1717 committed = reserved;
1719 /* Reserve some (more) space
1720 * Note this is a little sneaky, 1st call passes NULL as reserved
1721 * so lets system choose where we start, subsequent calls pass
1722 * the old end address so ask for a contiguous block
1724 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
1727 reserved = addr+size;
1742 if (brk > committed)
1744 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
1745 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
1760 win32_malloc(size_t size)
1762 return malloc(size);
1766 win32_calloc(size_t numitems, size_t size)
1768 return calloc(numitems,size);
1772 win32_realloc(void *block, size_t size)
1774 return realloc(block,size);
1778 win32_free(void *block)
1785 win32_open_osfhandle(long handle, int flags)
1787 return _open_osfhandle(handle, flags);
1791 win32_get_osfhandle(int fd)
1793 return _get_osfhandle(fd);
1804 SV *sv = sv_newmortal();
1805 /* Make one call with zero size - return value is required size */
1806 DWORD len = GetCurrentDirectory((DWORD)0,NULL);
1807 SvUPGRADE(sv,SVt_PV);
1809 SvCUR(sv) = GetCurrentDirectory((DWORD) SvLEN(sv), SvPVX(sv));
1812 * then it worked, set PV valid,
1813 * else leave it 'undef'
1827 croak("usage: Win32::SetCurrentDirectory($cwd)");
1828 if (SetCurrentDirectory(SvPV(ST(0),na)))
1835 XS(w32_GetNextAvailDrive)
1839 char root[] = "_:\\";
1842 if (GetDriveType(root) == 1) {
1851 XS(w32_GetLastError)
1854 XSRETURN_IV(GetLastError());
1861 char *name = getlogin_buffer;
1862 DWORD size = sizeof(getlogin_buffer);
1863 if (GetUserName(name,&size)) {
1864 /* size includes NULL */
1865 ST(0) = sv_2mortal(newSVpv(name,size-1));
1875 char name[MAX_COMPUTERNAME_LENGTH+1];
1876 DWORD size = sizeof(name);
1877 if (GetComputerName(name,&size)) {
1878 /* size does NOT include NULL :-( */
1879 ST(0) = sv_2mortal(newSVpv(name,size));
1891 DWORD size = sizeof(name);
1892 if (GetUserName(name,&size)) {
1894 DWORD sidlen = sizeof(sid);
1896 DWORD dnamelen = sizeof(dname);
1898 if (LookupAccountName(NULL, name, &sid, &sidlen,
1899 dname, &dnamelen, &snu)) {
1900 XSRETURN_PV(dname); /* all that for this */
1911 DWORD flags, filecomplen;
1912 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
1913 &flags, fsname, sizeof(fsname))) {
1914 if (GIMME == G_ARRAY) {
1915 XPUSHs(sv_2mortal(newSVpv(fsname,0)));
1916 XPUSHs(sv_2mortal(newSViv(flags)));
1917 XPUSHs(sv_2mortal(newSViv(filecomplen)));
1921 XSRETURN_PV(fsname);
1927 XS(w32_GetOSVersion)
1930 OSVERSIONINFO osver;
1932 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1933 if (GetVersionEx(&osver)) {
1934 XPUSHs(newSVpv(osver.szCSDVersion, 0));
1935 XPUSHs(newSViv(osver.dwMajorVersion));
1936 XPUSHs(newSViv(osver.dwMinorVersion));
1937 XPUSHs(newSViv(osver.dwBuildNumber));
1938 XPUSHs(newSViv(osver.dwPlatformId));
1949 XSRETURN_IV(IsWinNT());
1956 XSRETURN_IV(IsWin95());
1960 XS(w32_FormatMessage)
1967 croak("usage: Win32::FormatMessage($errno)");
1969 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
1970 &source, SvIV(ST(0)), 0,
1971 msgbuf, sizeof(msgbuf)-1, NULL))
1972 XSRETURN_PV(msgbuf);
1982 PROCESS_INFORMATION stProcInfo;
1983 STARTUPINFO stStartInfo;
1984 BOOL bSuccess = FALSE;
1987 croak("usage: Win32::Spawn($cmdName, $args, $PID)");
1989 cmd = SvPV(ST(0),na);
1990 args = SvPV(ST(1), na);
1992 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
1993 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
1994 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
1995 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
1998 cmd, /* Image path */
1999 args, /* Arguments for command line */
2000 NULL, /* Default process security */
2001 NULL, /* Default thread security */
2002 FALSE, /* Must be TRUE to use std handles */
2003 NORMAL_PRIORITY_CLASS, /* No special scheduling */
2004 NULL, /* Inherit our environment block */
2005 NULL, /* Inherit our currrent directory */
2006 &stStartInfo, /* -> Startup info */
2007 &stProcInfo)) /* <- Process info (if OK) */
2009 CloseHandle(stProcInfo.hThread);/* library source code does this. */
2010 sv_setiv(ST(2), stProcInfo.dwProcessId);
2013 XSRETURN_IV(bSuccess);
2017 XS(w32_GetTickCount)
2020 XSRETURN_IV(GetTickCount());
2024 XS(w32_GetShortPathName)
2031 croak("usage: Win32::GetShortPathName($longPathName)");
2033 shortpath = sv_mortalcopy(ST(0));
2034 SvUPGRADE(shortpath, SVt_PV);
2035 /* src == target is allowed */
2037 len = GetShortPathName(SvPVX(shortpath),
2040 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
2042 SvCUR_set(shortpath,len);
2055 croak("usage: Win32::Sleep($milliseconds)");
2060 #define TMPBUFSZ 1024
2061 #define MAX_LENGTH 2048
2062 #define SUCCESSRETURNED(x) (x == ERROR_SUCCESS)
2063 #define REGRETURN(x) XSRETURN_IV(SUCCESSRETURNED(x))
2064 #define SvHKEY(index) (HKEY)((unsigned long)SvIV(index))
2065 #define SETIV(index,value) sv_setiv(ST(index), value)
2066 #define SETNV(index,value) sv_setnv(ST(index), value)
2067 #define SETPV(index,string) sv_setpv(ST(index), string)
2068 #define SETPVN(index, buffer, length) sv_setpvn(ST(index), (char*)buffer, length)
2069 #define SETHKEY(index, hkey) SETIV(index,(long)hkey)
2071 static time_t ft2timet(FILETIME *ft)
2076 FileTimeToSystemTime(ft, &st);
2077 tm.tm_sec = st.wSecond;
2078 tm.tm_min = st.wMinute;
2079 tm.tm_hour = st.wHour;
2080 tm.tm_mday = st.wDay;
2081 tm.tm_mon = st.wMonth - 1;
2082 tm.tm_year = st.wYear - 1900;
2083 tm.tm_wday = st.wDayOfWeek;
2086 return mktime (&tm);
2096 croak("usage: Win32::RegCloseKey($hkey);\n");
2099 REGRETURN(RegCloseKey(SvHKEY(ST(0))));
2103 XS(w32_RegConnectRegistry)
2110 croak("usage: Win32::RegConnectRegistry($machine, $hkey, $handle);\n");
2113 if(SUCCESSRETURNED(RegConnectRegistry((char *)SvPV(ST(0), na), SvHKEY(ST(1)), &handle)))
2122 XS(w32_RegCreateKey)
2131 croak("usage: Win32::RegCreateKey($hkey, $subkey, $handle);\n");
2134 retval = RegCreateKeyEx(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS,
2135 NULL, &handle, &disposition);
2137 if(SUCCESSRETURNED(retval))
2146 XS(w32_RegCreateKeyEx)
2150 unsigned int length;
2155 DWORD options, disposition;
2157 SECURITY_ATTRIBUTES sa, *psa;
2161 croak("usage: Win32::RegCreateKeyEx($hkey, $subkey, $reserved, $class, $options, $sam, "
2162 "$security, $handle, $disposition);\n");
2165 hkey = SvHKEY(ST(0));
2166 subkey = (char *)SvPV(ST(1), na);
2167 keyclass = (char *)SvPV(ST(3), na);
2168 options = (DWORD) ((unsigned long)SvIV(ST(4)));
2169 sam = (REGSAM) ((unsigned long)SvIV(ST(5)));
2170 psa = (SECURITY_ATTRIBUTES*)SvPV(ST(6), length);
2171 if(length != sizeof(SECURITY_ATTRIBUTES))
2174 memset(&sa, 0, sizeof(SECURITY_ATTRIBUTES));
2175 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
2178 retval = RegCreateKeyEx(hkey, subkey, 0, keyclass, options, sam,
2179 psa, &handle, &disposition);
2181 if(SUCCESSRETURNED(retval))
2184 SETPVN(6, &sa, sizeof(sa));
2187 SETIV(8,disposition);
2194 XS(w32_RegDeleteKey)
2200 croak("usage: Win32::RegDeleteKey($hkey, $subkey);\n");
2203 REGRETURN(RegDeleteKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na)));
2207 XS(w32_RegDeleteValue)
2213 croak("usage: Win32::RegDeleteValue($hkey, $valname);\n");
2216 REGRETURN(RegDeleteValue(SvHKEY(ST(0)), (char *)SvPV(ST(1), na)));
2224 char keybuffer[TMPBUFSZ];
2228 croak("usage: Win32::RegEnumKey($hkey, $idx, $subkeyname);\n");
2231 if(SUCCESSRETURNED(RegEnumKey(SvHKEY(ST(0)), SvIV(ST(1)), keybuffer, sizeof(keybuffer))))
2233 SETPV(2, keybuffer);
2240 XS(w32_RegEnumKeyEx)
2245 DWORD keysz, classsz;
2246 char keybuffer[TMPBUFSZ];
2247 char classbuffer[TMPBUFSZ];
2253 croak("usage: Win32::RegEnumKeyEx($hkey, $idx, $subkeyname, $reserved, $class, $time);\n");
2256 keysz = sizeof(keybuffer);
2257 classsz = sizeof(classbuffer);
2258 retval = RegEnumKeyEx(SvHKEY(ST(0)), SvIV(ST(1)), keybuffer, &keysz, 0,
2259 classbuffer, &classsz, &filetime);
2260 if(SUCCESSRETURNED(retval))
2262 SETPV(2, keybuffer);
2263 SETPV(4, classbuffer);
2264 SETIV(5, ft2timet(&filetime));
2271 XS(w32_RegEnumValue)
2275 DWORD type, namesz, valsz;
2277 static HKEY last_hkey;
2278 char myvalbuf[MAX_LENGTH];
2279 char mynambuf[MAX_LENGTH];
2283 croak("usage: Win32::RegEnumValue($hkey, $i, $name, $reserved, $type, $value);\n");
2286 hkey = SvHKEY(ST(0));
2288 // If this is a new key, find out how big the maximum name and value sizes are and
2289 // allocate space for them. Free any old storage and set the old key value to the
2292 if(hkey != (HKEY)last_hkey)
2294 char keyclass[TMPBUFSZ];
2295 DWORD classsz, subkeys, maxsubkey, maxclass, values, salen, maxnamesz, maxvalsz;
2297 classsz = sizeof(keyclass);
2298 retval = RegQueryInfoKey(hkey, keyclass, &classsz, 0, &subkeys, &maxsubkey, &maxclass,
2299 &values, &maxnamesz, &maxvalsz, &salen, &ft);
2301 if(!SUCCESSRETURNED(retval))
2305 memset(myvalbuf, 0, MAX_LENGTH);
2306 memset(mynambuf, 0, MAX_LENGTH);
2310 namesz = MAX_LENGTH;
2312 retval = RegEnumValue(hkey, SvIV(ST(1)), mynambuf, &namesz, 0, &type, (LPBYTE) myvalbuf, &valsz);
2313 if(!SUCCESSRETURNED(retval))
2322 // return includes the null terminator so delete it if REG_SZ, REG_MULTI_SZ or REG_EXPAND_SZ
2331 SETPVN(5, myvalbuf, valsz);
2334 case REG_DWORD_BIG_ENDIAN:
2336 BYTE tmp = myvalbuf[0];
2337 myvalbuf[0] = myvalbuf[3];
2340 myvalbuf[1] = myvalbuf[2];
2343 case REG_DWORD_LITTLE_ENDIAN: // same as REG_DWORD
2344 SETNV(5, (double)*((DWORD*)myvalbuf));
2362 croak("usage: Win32::RegFlushKey($hkey);\n");
2365 REGRETURN(RegFlushKey(SvHKEY(ST(0))));
2369 XS(w32_RegGetKeySecurity)
2372 SECURITY_DESCRIPTOR sd;
2377 croak("usage: Win32::RegGetKeySecurity($hkey, $security_info, $security_descriptor);\n");
2380 if(SUCCESSRETURNED(RegGetKeySecurity(SvHKEY(ST(0)), SvIV(ST(1)), &sd, &sdsz)))
2382 SETPVN(2, &sd, sdsz);
2395 croak("usage: Win32::RegLoadKey($hkey, $subkey, $filename);\n");
2398 REGRETURN(RegLoadKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), (char *)SvPV(ST(2), na)));
2402 XS(w32_RegNotifyChangeKeyValue)
2404 croak("Win32::RegNotifyChangeKeyValue not yet implemented!\n");
2415 croak("usage: Win32::RegOpenKey($hkey, $subkey, $handle);\n");
2418 if(SUCCESSRETURNED(RegOpenKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), &handle)))
2427 XS(w32_RegOpenKeyEx)
2434 croak("usage: Win32::RegOpenKeyEx($hkey, $subkey, $reserved, $sam, $handle);\n");
2437 if(SUCCESSRETURNED(RegOpenKeyEx(SvHKEY(ST(0)), (char *)SvPV(ST(1), na),
2438 0, (REGSAM) ((unsigned long)SvIV(ST(3))), &handle)))
2446 #pragma optimize("", off)
2448 XS(w32_RegQueryInfoKey)
2453 char keyclass[TMPBUFSZ];
2454 DWORD subkeys, maxsubkey, maxclass, values, maxvalname, maxvaldata;
2455 DWORD seclen, classsz;
2461 croak("usage: Win32::RegQueryInfoKey($hkey, $class, $numsubkeys, $maxsubkey,"
2462 "$maxclass, $values, $maxvalname, $maxvaldata, $secdesclen,"
2463 "$lastwritetime);\n");
2466 classsz = sizeof(keyclass);
2467 retval = RegQueryInfoKey(SvHKEY(ST(0)), keyclass, &classsz, 0, &subkeys, &maxsubkey,
2468 &maxclass, &values, &maxvalname, &maxvaldata,
2470 if(SUCCESSRETURNED(retval))
2474 SETIV(3, maxsubkey);
2477 SETIV(6, maxvalname);
2478 SETIV(7, maxvaldata);
2480 SETIV(9, ft2timet(&ft));
2485 #pragma optimize("", on)
2488 XS(w32_RegQueryValue)
2492 unsigned char databuffer[TMPBUFSZ*2];
2493 long datasz = sizeof(databuffer);
2497 croak("usage: Win32::RegQueryValue($hkey, $valuename, $data);\n");
2500 if(SUCCESSRETURNED(RegQueryValue(SvHKEY(ST(0)), SvPV(ST(1), na), (char*)databuffer, &datasz)))
2502 // return includes the null terminator so delete it
2503 SETPVN(2, databuffer, --datasz);
2510 XS(w32_RegQueryValueEx)
2514 unsigned char databuffer[TMPBUFSZ*2];
2515 DWORD datasz = sizeof(databuffer);
2518 LPBYTE ptr = databuffer;
2522 croak("usage: Win32::RegQueryValueEx($hkey, $valuename, $reserved, $type, $data);\n");
2525 result = RegQueryValueEx(SvHKEY(ST(0)), SvPV(ST(1), na), 0, &type, ptr, &datasz);
2526 if(result == ERROR_MORE_DATA)
2528 New(0, ptr, datasz+1, BYTE);
2529 result = RegQueryValueEx(SvHKEY(ST(0)), SvPV(ST(1), na), 0, &type, ptr, &datasz);
2531 if(SUCCESSRETURNED(result))
2535 // return includes the null terminator so delete it if REG_SZ, REG_MULTI_SZ or REG_EXPAND_SZ
2543 SETPVN(4, ptr, datasz);
2546 case REG_DWORD_BIG_ENDIAN:
2555 case REG_DWORD_LITTLE_ENDIAN: // same as REG_DWORD
2556 SETNV(4, (double)*((DWORD*)ptr));
2563 if(ptr != databuffer)
2568 if(ptr != databuffer)
2575 XS(w32_RegReplaceKey)
2581 croak("usage: Win32::RegReplaceKey($hkey, $subkey, $newfile, $oldfile);\n");
2584 REGRETURN(RegReplaceKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), (char *)SvPV(ST(2), na), (char *)SvPV(ST(3), na)));
2588 XS(w32_RegRestoreKey)
2592 if(items < 2 || items > 3)
2594 croak("usage: Win32::RegRestoreKey($hkey, $filename [, $flags]);\n");
2597 REGRETURN(RegRestoreKey(SvHKEY(ST(0)), (char*)SvPV(ST(1), na), (DWORD)((items == 3) ? SvIV(ST(2)) : 0)));
2607 croak("usage: Win32::RegSaveKey($hkey, $filename);\n");
2610 REGRETURN(RegSaveKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), NULL));
2614 XS(w32_RegSetKeySecurity)
2620 croak("usage: Win32::RegSetKeySecurity($hkey, $security_info, $security_descriptor);\n");
2623 REGRETURN(RegSetKeySecurity(SvHKEY(ST(0)), SvIV(ST(1)), (SECURITY_DESCRIPTOR*)SvPV(ST(2), na)));
2636 croak("usage: Win32::RegSetValue($hkey, $subKey, $type, $data);\n");
2639 DWORD type = SvIV(ST(2));
2640 if(type != REG_SZ && type != REG_EXPAND_SZ)
2642 croak("Win32::RegSetValue: Type was not REG_SZ or REG_EXPAND_SZ, cannot set %s\n", (char *)SvPV(ST(1), na));
2645 buffer = (char *)SvPV(ST(3), size);
2646 REGRETURN(RegSetValue(SvHKEY(ST(0)), SvPV(ST(1), na), REG_SZ, buffer, size));
2650 XS(w32_RegSetValueEx)
2661 croak("usage: Win32::RegSetValueEx($hkey, $valname, $reserved, $type, $data);\n");
2664 type = (DWORD)SvIV(ST(3));
2671 buffer = (char *)SvPV(ST(4), size);
2672 if(type != REG_BINARY)
2673 size++; // include null terminator in size
2675 REGRETURN(RegSetValueEx(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), 0, type, (PBYTE) buffer, size));
2678 case REG_DWORD_BIG_ENDIAN:
2679 case REG_DWORD_LITTLE_ENDIAN: // Same as REG_DWORD
2680 val = (DWORD)SvIV(ST(4));
2681 REGRETURN(RegSetValueEx(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), 0, type, (PBYTE) &val, sizeof(DWORD)));
2685 croak("Win32::RegSetValueEx: Type not specified, cannot set %s\n", (char *)SvPV(ST(1), na));
2690 XS(w32_RegUnloadKey)
2696 croak("usage: Win32::RegUnLoadKey($hkey, $subkey);\n");
2699 REGRETURN(RegUnLoadKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na)));
2703 XS(w32_RegisterServer)
2706 BOOL bSuccess = FALSE;
2707 HINSTANCE hInstance;
2708 unsigned int length;
2713 croak("usage: Win32::RegisterServer($LibraryName)\n");
2716 hInstance = LoadLibrary((char *)SvPV(ST(0), length));
2717 if(hInstance != NULL)
2719 sFunc = GetProcAddress(hInstance, "DllRegisterServer");
2722 bSuccess = (sFunc() == 0);
2724 FreeLibrary(hInstance);
2735 XS(w32_UnregisterServer)
2738 BOOL bSuccess = FALSE;
2739 HINSTANCE hInstance;
2740 unsigned int length;
2745 croak("usage: Win32::UnregisterServer($LibraryName)\n");
2748 hInstance = LoadLibrary((char *)SvPV(ST(0), length));
2749 if(hInstance != NULL)
2751 sFunc = GetProcAddress(hInstance, "DllUnregisterServer");
2754 bSuccess = (sFunc() == 0);
2756 FreeLibrary(hInstance);
2768 Perl_init_os_extras()
2770 char *file = __FILE__;
2773 /* these names are Activeware compatible */
2774 newXS("Win32::GetCwd", w32_GetCwd, file);
2775 newXS("Win32::SetCwd", w32_SetCwd, file);
2776 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
2777 newXS("Win32::GetLastError", w32_GetLastError, file);
2778 newXS("Win32::LoginName", w32_LoginName, file);
2779 newXS("Win32::NodeName", w32_NodeName, file);
2780 newXS("Win32::DomainName", w32_DomainName, file);
2781 newXS("Win32::FsType", w32_FsType, file);
2782 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
2783 newXS("Win32::IsWinNT", w32_IsWinNT, file);
2784 newXS("Win32::IsWin95", w32_IsWin95, file);
2785 newXS("Win32::FormatMessage", w32_FormatMessage, file);
2786 newXS("Win32::Spawn", w32_Spawn, file);
2787 newXS("Win32::GetTickCount", w32_GetTickCount, file);
2788 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
2789 newXS("Win32::Sleep", w32_Sleep, file);
2791 /* the following extensions are used interally and may be changed at any time */
2792 /* therefore no documentation is provided */
2793 newXS("Win32::RegCloseKey", w32_RegCloseKey, file);
2794 newXS("Win32::RegConnectRegistry", w32_RegConnectRegistry, file);
2795 newXS("Win32::RegCreateKey", w32_RegCreateKey, file);
2796 newXS("Win32::RegCreateKeyEx", w32_RegCreateKeyEx, file);
2797 newXS("Win32::RegDeleteKey", w32_RegDeleteKey, file);
2798 newXS("Win32::RegDeleteValue", w32_RegDeleteValue, file);
2800 newXS("Win32::RegEnumKey", w32_RegEnumKey, file);
2801 newXS("Win32::RegEnumKeyEx", w32_RegEnumKeyEx, file);
2802 newXS("Win32::RegEnumValue", w32_RegEnumValue, file);
2804 newXS("Win32::RegFlushKey", w32_RegFlushKey, file);
2805 newXS("Win32::RegGetKeySecurity", w32_RegGetKeySecurity, file);
2807 newXS("Win32::RegLoadKey", w32_RegLoadKey, file);
2808 newXS("Win32::RegOpenKey", w32_RegOpenKey, file);
2809 newXS("Win32::RegOpenKeyEx", w32_RegOpenKeyEx, file);
2810 newXS("Win32::RegQueryInfoKey", w32_RegQueryInfoKey, file);
2811 newXS("Win32::RegQueryValue", w32_RegQueryValue, file);
2812 newXS("Win32::RegQueryValueEx", w32_RegQueryValueEx, file);
2814 newXS("Win32::RegReplaceKey", w32_RegReplaceKey, file);
2815 newXS("Win32::RegRestoreKey", w32_RegRestoreKey, file);
2816 newXS("Win32::RegSaveKey", w32_RegSaveKey, file);
2817 newXS("Win32::RegSetKeySecurity", w32_RegSetKeySecurity, file);
2818 newXS("Win32::RegSetValue", w32_RegSetValue, file);
2819 newXS("Win32::RegSetValueEx", w32_RegSetValueEx, file);
2820 newXS("Win32::RegUnloadKey", w32_RegUnloadKey, file);
2822 newXS("Win32::RegisterServer", w32_RegisterServer, file);
2823 newXS("Win32::UnregisterServer", w32_UnregisterServer, file);
2825 /* XXX Bloat Alert! The following Activeware preloads really
2826 * ought to be part of Win32::Sys::*, so they're not included
2829 /* LookupAccountName
2831 * InitiateSystemShutdown
2832 * AbortSystemShutdown
2833 * ExpandEnvrironmentStrings
2838 Perl_win32_init(int *argcp, char ***argvp)
2840 /* Disable floating point errors, Perl will trap the ones we
2841 * care about. VC++ RTL defaults to switching these off
2842 * already, but the Borland RTL doesn't. Since we don't
2843 * want to be at the vendor's whim on the default, we set
2844 * it explicitly here.
2846 #if !defined(_ALPHA_) && !defined(__GNUC__)
2847 _control87(MCW_EM, MCW_EM);
2852 #ifdef USE_BINMODE_SCRIPTS
2855 win32_strip_return(SV *sv)
2857 char *s = SvPVX(sv);
2858 char *e = s+SvCUR(sv);
2862 if (*s == '\r' && s[1] == '\n')
2872 SvCUR_set(sv,d-SvPVX(sv));