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
17 #undef __attribute__ /* seems broken in 2.8.0 */
18 #define __attribute__(p)
23 /* #include "config.h" */
25 #define PERLIO_NOT_STDIO 0
26 #if !defined(PERLIO_IS_STDIO) && !defined(USE_SFIO)
35 extern CPerlObj* pPerl;
43 /* assert.h conflicts with #define of assert in perl.h */
50 #if defined(_MSC_VER) || defined(__MINGW32__)
51 #include <sys/utime.h>
57 /* Mingw32 defaults to globing command line
58 * So we turn it off like this:
65 #define EXECF_SPAWN_NOWAIT 3
67 #if defined(PERL_OBJECT)
68 #undef win32_perllib_path
69 #define win32_perllib_path g_win32_perllib_path
71 #define do_aspawn g_do_aspawn
73 #define do_spawn g_do_spawn
75 #define do_exec g_do_exec
77 #define opendir g_opendir
79 #define readdir g_readdir
81 #define telldir g_telldir
83 #define seekdir g_seekdir
85 #define rewinddir g_rewinddir
87 #define closedir g_closedir
89 #define getlogin g_getlogin
92 static DWORD os_id(void);
93 static void get_shell(void);
94 static long tokenize(char *str, char **dest, char ***destv);
95 int do_spawn2(char *cmd, int exectype);
96 static BOOL has_redirection(char *ptr);
97 static long filetime_to_clock(PFILETIME ft);
98 static BOOL filetime_from_time(PFILETIME ft, time_t t);
101 char * w32_perlshell_tokens = Nullch;
102 char ** w32_perlshell_vec;
103 long w32_perlshell_items = -1;
104 DWORD w32_platform = (DWORD)-1;
105 char w32_perllib_root[MAX_PATH+1];
106 HANDLE w32_perldll_handle = INVALID_HANDLE_VALUE;
108 long w32_num_children = 0;
109 HANDLE w32_child_pids[MAXIMUM_WAIT_OBJECTS];
114 # define FOPEN_MAX _NSTREAM_
116 # define FOPEN_MAX _NFILE_
118 # define FOPEN_MAX _NFILE
122 #ifndef USE_CRT_POPEN
123 int w32_popen_pids[FOPEN_MAX];
127 # ifdef USE_DECLSPEC_THREAD
128 __declspec(thread) char strerror_buffer[512];
129 __declspec(thread) char getlogin_buffer[128];
130 # ifdef HAVE_DES_FCRYPT
131 __declspec(thread) char crypt_buffer[30];
134 # define strerror_buffer (thr->i.Wstrerror_buffer)
135 # define getlogin_buffer (thr->i.Wgetlogin_buffer)
136 # define crypt_buffer (thr->i.Wcrypt_buffer)
139 char strerror_buffer[512];
140 char getlogin_buffer[128];
141 # ifdef HAVE_DES_FCRYPT
142 char crypt_buffer[30];
148 return (os_id() == VER_PLATFORM_WIN32_WINDOWS);
153 return (os_id() == VER_PLATFORM_WIN32_NT);
157 win32_perllib_path(char *sfx,...)
162 GetModuleFileName((w32_perldll_handle == INVALID_HANDLE_VALUE)
163 ? GetModuleHandle(NULL)
164 : w32_perldll_handle,
166 sizeof(w32_perllib_root));
167 *(end = strrchr(w32_perllib_root, '\\')) = '\0';
168 if (stricmp(end-4,"\\bin") == 0)
175 sfx = va_arg(ap,char *);
178 return (w32_perllib_root);
183 has_redirection(char *ptr)
189 * Scan string looking for redirection (< or >) or pipe
190 * characters (|) that are not in a quoted string
220 #if !defined(PERL_OBJECT)
221 /* since the current process environment is being updated in util.c
222 * the library functions will get the correct environment
225 my_popen(char *cmd, char *mode)
228 #define fixcmd(x) { \
229 char *pspace = strchr((x),' '); \
232 while (p < pspace) { \
243 win32_fflush(stdout);
244 win32_fflush(stderr);
245 return win32_popen(cmd, mode);
249 my_pclose(PerlIO *fp)
251 return win32_pclose(fp);
258 static OSVERSIONINFO osver;
260 if (osver.dwPlatformId != w32_platform) {
261 memset(&osver, 0, sizeof(OSVERSIONINFO));
262 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
263 GetVersionEx(&osver);
264 w32_platform = osver.dwPlatformId;
266 return (w32_platform);
269 /* Tokenize a string. Words are null-separated, and the list
270 * ends with a doubled null. Any character (except null and
271 * including backslash) may be escaped by preceding it with a
272 * backslash (the backslash will be stripped).
273 * Returns number of words in result buffer.
276 tokenize(char *str, char **dest, char ***destv)
278 char *retstart = Nullch;
279 char **retvstart = 0;
282 int slen = strlen(str);
284 register char **retv;
285 New(1307, ret, slen+2, char);
286 New(1308, retv, (slen+3)/2, char*);
294 if (*ret == '\\' && *str)
296 else if (*ret == ' ') {
312 retvstart[items] = Nullch;
324 if (!w32_perlshell_tokens) {
325 /* we don't use COMSPEC here for two reasons:
326 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
327 * uncontrolled unportability of the ensuing scripts.
328 * 2. PERL5SHELL could be set to a shell that may not be fit for
329 * interactive use (which is what most programs look in COMSPEC
332 char* defaultshell = (IsWinNT() ? "cmd.exe /x/c" : "command.com /c");
333 char *usershell = getenv("PERL5SHELL");
334 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
335 &w32_perlshell_tokens,
341 do_aspawn(void *vreally, void **vmark, void **vsp)
343 SV *really = (SV*)vreally;
344 SV **mark = (SV**)vmark;
356 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
358 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
363 while(++mark <= sp) {
364 if (*mark && (str = SvPV(*mark, na)))
371 status = win32_spawnvp(flag,
372 (const char*)(really ? SvPV(really,na) : argv[0]),
373 (const char* const*)argv);
375 if (status < 0 && errno == ENOEXEC) {
376 /* possible shell-builtin, invoke with shell */
378 sh_items = w32_perlshell_items;
380 argv[index+sh_items] = argv[index];
381 while (--sh_items >= 0)
382 argv[sh_items] = w32_perlshell_vec[sh_items];
384 status = win32_spawnvp(flag,
385 (const char*)(really ? SvPV(really,na) : argv[0]),
386 (const char* const*)argv);
389 if (flag != P_NOWAIT) {
392 warn("Can't spawn \"%s\": %s", argv[0], strerror(errno));
397 statusvalue = status;
404 do_spawn2(char *cmd, int exectype)
410 BOOL needToTry = TRUE;
413 /* Save an extra exec if possible. See if there are shell
414 * metacharacters in it */
415 if(!has_redirection(cmd)) {
416 New(1301,argv, strlen(cmd) / 2 + 2, char*);
417 New(1302,cmd2, strlen(cmd) + 1, char);
420 for (s = cmd2; *s;) {
421 while (*s && isspace(*s))
425 while(*s && !isspace(*s))
434 status = win32_spawnvp(P_WAIT, argv[0],
435 (const char* const*)argv);
437 case EXECF_SPAWN_NOWAIT:
438 status = win32_spawnvp(P_NOWAIT, argv[0],
439 (const char* const*)argv);
442 status = win32_execvp(argv[0], (const char* const*)argv);
445 if (status != -1 || errno == 0)
455 New(1306, argv, w32_perlshell_items + 2, char*);
456 while (++i < w32_perlshell_items)
457 argv[i] = w32_perlshell_vec[i];
462 status = win32_spawnvp(P_WAIT, argv[0],
463 (const char* const*)argv);
465 case EXECF_SPAWN_NOWAIT:
466 status = win32_spawnvp(P_NOWAIT, argv[0],
467 (const char* const*)argv);
470 status = win32_execvp(argv[0], (const char* const*)argv);
476 if (exectype != EXECF_SPAWN_NOWAIT) {
479 warn("Can't %s \"%s\": %s",
480 (exectype == EXECF_EXEC ? "exec" : "spawn"),
481 cmd, strerror(errno));
486 statusvalue = status;
494 return do_spawn2(cmd, EXECF_SPAWN);
498 do_spawn_nowait(char *cmd)
500 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
506 do_spawn2(cmd, EXECF_EXEC);
513 /* The idea here is to read all the directory names into a string table
514 * (separated by nulls) and when one of the other dir functions is called
515 * return the pointer to the current file name.
518 opendir(char *filename)
523 char scannamespc[PATHLEN];
524 char *scanname = scannamespc;
526 WIN32_FIND_DATA FindData;
528 /* char root[_MAX_PATH];*/
529 /* char volname[_MAX_PATH];*/
530 /* DWORD serial, maxname, flags;*/
534 /* check to see if filename is a directory */
535 if (win32_stat(filename, &sbuf) < 0 || (sbuf.st_mode & S_IFDIR) == 0) {
536 /* CRT is buggy on sharenames, so make sure it really isn't */
537 DWORD r = GetFileAttributes(filename);
538 if (r == 0xffffffff || !(r & FILE_ATTRIBUTE_DIRECTORY))
542 /* get the file system characteristics */
543 /* if(GetFullPathName(filename, MAX_PATH, root, &dummy)) {
544 * if(dummy = strchr(root, '\\'))
546 * if(GetVolumeInformation(root, volname, MAX_PATH, &serial,
547 * &maxname, &flags, 0, 0)) {
548 * downcase = !(flags & FS_CASE_IS_PRESERVED);
555 /* Get us a DIR structure */
556 Newz(1303, p, 1, DIR);
560 /* Create the search pattern */
561 strcpy(scanname, filename);
563 if(index("/\\", *(scanname + strlen(scanname) - 1)) == NULL)
564 strcat(scanname, "/*");
566 strcat(scanname, "*");
568 /* do the FindFirstFile call */
569 fh = FindFirstFile(scanname, &FindData);
570 if(fh == INVALID_HANDLE_VALUE) {
574 /* now allocate the first part of the string table for
575 * the filenames that we find.
577 idx = strlen(FindData.cFileName)+1;
578 New(1304, p->start, idx, char);
579 if(p->start == NULL) {
580 croak("opendir: malloc failed!\n");
582 strcpy(p->start, FindData.cFileName);
588 /* loop finding all the files that match the wildcard
589 * (which should be all of them in this directory!).
590 * the variable idx should point one past the null terminator
591 * of the previous string found.
593 while (FindNextFile(fh, &FindData)) {
594 len = strlen(FindData.cFileName);
595 /* bump the string table size by enough for the
596 * new name and it's null terminator
598 Renew(p->start, idx+len+1, char);
599 if(p->start == NULL) {
600 croak("opendir: malloc failed!\n");
602 strcpy(&p->start[idx], FindData.cFileName);
604 * strlwr(&p->start[idx]);
616 /* Readdir just returns the current string pointer and bumps the
617 * string pointer to the nDllExport entry.
623 static int dummy = 0;
626 /* first set up the structure to return */
627 len = strlen(dirp->curr);
628 strcpy(dirp->dirstr.d_name, dirp->curr);
629 dirp->dirstr.d_namlen = len;
632 dirp->dirstr.d_ino = dummy++;
634 /* Now set up for the nDllExport call to readdir */
635 dirp->curr += len + 1;
636 if (dirp->curr >= (dirp->start + dirp->size)) {
640 return &(dirp->dirstr);
646 /* Telldir returns the current string pointer position */
650 return (long) dirp->curr;
654 /* Seekdir moves the string pointer to a previously saved position
658 seekdir(DIR *dirp, long loc)
660 dirp->curr = (char *)loc;
663 /* Rewinddir resets the string pointer to the start */
667 dirp->curr = dirp->start;
670 /* free the memory allocated by opendir */
674 Safefree(dirp->start);
687 * Just pretend that everyone is a superuser. NT will let us know if
688 * we don\'t really have permission to do something.
691 #define ROOT_UID ((uid_t)0)
692 #define ROOT_GID ((gid_t)0)
721 return (auid == ROOT_UID ? 0 : -1);
727 return (agid == ROOT_GID ? 0 : -1);
734 char *buf = getlogin_buffer;
735 DWORD size = sizeof(getlogin_buffer);
736 if (GetUserName(buf,&size))
742 chown(const char *path, uid_t owner, gid_t group)
749 kill(int pid, int sig)
751 HANDLE hProcess= OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
753 if (hProcess == NULL) {
754 croak("kill process failed!\n");
757 if (!TerminateProcess(hProcess, sig))
758 croak("kill process failed!\n");
759 CloseHandle(hProcess);
768 DllExport unsigned int
769 win32_sleep(unsigned int t)
776 win32_stat(const char *path, struct stat *buffer)
779 const char *p = path;
780 int l = strlen(path);
784 switch(path[l - 1]) {
787 if (path[l - 2] != ':') {
788 strncpy(t, path, l - 1);
794 res = stat(p,buffer);
797 if (S_ISDIR(buffer->st_mode))
798 buffer->st_mode |= S_IWRITE | S_IEXEC;
799 else if (S_ISREG(buffer->st_mode)) {
800 if (l >= 4 && path[l-4] == '.') {
801 const char *e = path + l - 3;
802 if (strnicmp(e,"exe",3)
803 && strnicmp(e,"bat",3)
804 && strnicmp(e,"com",3)
805 && (IsWin95() || strnicmp(e,"cmd",3)))
806 buffer->st_mode &= ~S_IEXEC;
808 buffer->st_mode |= S_IEXEC;
811 buffer->st_mode &= ~S_IEXEC;
818 #ifndef USE_WIN32_RTL_ENV
820 BOOL GetRegStr(HKEY hkey, const char *lpszValueName, char *lpszDefault, char *lpszData, unsigned long *lpdwDataLen)
821 { // Retrieve a REG_SZ or REG_EXPAND_SZ from the registry
823 DWORD type, dwDataLen = *lpdwDataLen;
824 const char *subkey = "Software\\Perl";
825 char szBuffer[MAX_PATH+1];
828 retval = RegOpenKeyEx(hkey, subkey, 0, KEY_READ, &handle);
829 if(retval == ERROR_SUCCESS)
831 retval = RegQueryValueEx(handle, lpszValueName, 0, &type, (LPBYTE)lpszData, &dwDataLen);
833 if(retval == ERROR_SUCCESS && (type == REG_SZ || type == REG_EXPAND_SZ))
835 if(type != REG_EXPAND_SZ)
837 *lpdwDataLen = dwDataLen;
840 strcpy(szBuffer, lpszData);
841 dwDataLen = ExpandEnvironmentStrings(szBuffer, lpszData, *lpdwDataLen);
842 if(dwDataLen < *lpdwDataLen)
844 *lpdwDataLen = dwDataLen;
850 strcpy(lpszData, lpszDefault);
854 char* GetRegStr(const char *lpszValueName, char *lpszDefault, char *lpszData, unsigned long *lpdwDataLen)
856 if(!GetRegStr(HKEY_CURRENT_USER, lpszValueName, lpszDefault, lpszData, lpdwDataLen))
858 GetRegStr(HKEY_LOCAL_MACHINE, lpszValueName, lpszDefault, lpszData, lpdwDataLen);
860 if(*lpszData == '\0')
866 win32_getenv(const char *name)
868 static char *curitem = Nullch;
869 static DWORD curlen = 512;
872 New(1305,curitem,curlen,char);
873 if (!(needlen = GetEnvironmentVariable(name,curitem,curlen)))
875 while (needlen > curlen) {
876 Renew(curitem,needlen,char);
878 needlen = GetEnvironmentVariable(name,curitem,curlen);
882 unsigned long dwDataLen = curlen;
883 if(strcmp("PERL5DB", name) == 0)
884 curitem = GetRegStr(name, "", curitem, &dwDataLen);
892 filetime_to_clock(PFILETIME ft)
894 __int64 qw = ft->dwHighDateTime;
896 qw |= ft->dwLowDateTime;
897 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
902 win32_times(struct tms *timebuf)
907 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
909 timebuf->tms_utime = filetime_to_clock(&user);
910 timebuf->tms_stime = filetime_to_clock(&kernel);
911 timebuf->tms_cutime = 0;
912 timebuf->tms_cstime = 0;
915 /* That failed - e.g. Win95 fallback to clock() */
917 timebuf->tms_utime = t;
918 timebuf->tms_stime = 0;
919 timebuf->tms_cutime = 0;
920 timebuf->tms_cstime = 0;
925 /* fix utime() so it works on directories in NT
926 * thanks to Jan Dubois <jan.dubois@ibm.net>
929 filetime_from_time(PFILETIME pFileTime, time_t Time)
931 struct tm *pTM = gmtime(&Time);
932 SYSTEMTIME SystemTime;
937 SystemTime.wYear = pTM->tm_year + 1900;
938 SystemTime.wMonth = pTM->tm_mon + 1;
939 SystemTime.wDay = pTM->tm_mday;
940 SystemTime.wHour = pTM->tm_hour;
941 SystemTime.wMinute = pTM->tm_min;
942 SystemTime.wSecond = pTM->tm_sec;
943 SystemTime.wMilliseconds = 0;
945 return SystemTimeToFileTime(&SystemTime, pFileTime);
949 win32_utime(const char *filename, struct utimbuf *times)
955 struct utimbuf TimeBuffer;
957 int rc = utime(filename,times);
958 /* EACCES: path specifies directory or readonly file */
959 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
964 time(×->actime);
965 times->modtime = times->actime;
968 /* This will (and should) still fail on readonly files */
969 handle = CreateFile(filename, GENERIC_READ | GENERIC_WRITE,
970 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
971 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
972 if (handle == INVALID_HANDLE_VALUE)
975 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
976 filetime_from_time(&ftAccess, times->actime) &&
977 filetime_from_time(&ftWrite, times->modtime) &&
978 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
988 win32_wait(int *status)
993 /* XXX this wait emulation only knows about processes
994 * spawned via win32_spawnvp(P_NOWAIT, ...).
997 DWORD exitcode, waitcode;
999 if (!w32_num_children) {
1004 /* if a child exists, wait for it to die */
1005 waitcode = WaitForMultipleObjects(w32_num_children,
1009 if (waitcode != WAIT_FAILED) {
1010 if (waitcode >= WAIT_ABANDONED_0
1011 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1012 i = waitcode - WAIT_ABANDONED_0;
1014 i = waitcode - WAIT_OBJECT_0;
1015 if (GetExitCodeProcess(w32_child_pids[i], &exitcode) ) {
1016 CloseHandle(w32_child_pids[i]);
1017 *status = (int)((exitcode & 0xff) << 8);
1018 retval = (int)w32_child_pids[i];
1019 Copy(&w32_child_pids[i+1], &w32_child_pids[i],
1020 (w32_num_children-i-1), HANDLE);
1027 errno = GetLastError();
1033 static UINT timerid = 0;
1035 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1037 KillTimer(NULL,timerid);
1042 DllExport unsigned int
1043 win32_alarm(unsigned int sec)
1046 * the 'obvious' implentation is SetTimer() with a callback
1047 * which does whatever receiving SIGALRM would do
1048 * we cannot use SIGALRM even via raise() as it is not
1049 * one of the supported codes in <signal.h>
1051 * Snag is unless something is looking at the message queue
1052 * nothing happens :-(
1056 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1058 croak("Cannot set timer");
1064 KillTimer(NULL,timerid);
1071 #ifdef HAVE_DES_FCRYPT
1072 extern char * des_fcrypt(char *cbuf, const char *txt, const char *salt);
1075 win32_crypt(const char *txt, const char *salt)
1078 return des_fcrypt(crypt_buffer, txt, salt);
1082 #ifdef USE_FIXED_OSFHANDLE
1084 EXTERN_C int __cdecl _alloc_osfhnd(void);
1085 EXTERN_C int __cdecl _set_osfhnd(int fh, long value);
1086 EXTERN_C void __cdecl _lock_fhandle(int);
1087 EXTERN_C void __cdecl _unlock_fhandle(int);
1088 EXTERN_C void __cdecl _unlock(int);
1090 #if (_MSC_VER >= 1000)
1092 long osfhnd; /* underlying OS file HANDLE */
1093 char osfile; /* attributes of file (e.g., open in text mode?) */
1094 char pipech; /* one char buffer for handles opened on pipes */
1095 #if defined (_MT) && !defined (DLL_FOR_WIN32S)
1097 CRITICAL_SECTION lock;
1098 #endif /* defined (_MT) && !defined (DLL_FOR_WIN32S) */
1101 EXTERN_C ioinfo * __pioinfo[];
1103 #define IOINFO_L2E 5
1104 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
1105 #define _pioinfo(i) (__pioinfo[i >> IOINFO_L2E] + (i & (IOINFO_ARRAY_ELTS - 1)))
1106 #define _osfile(i) (_pioinfo(i)->osfile)
1108 #else /* (_MSC_VER >= 1000) */
1109 extern char _osfile[];
1110 #endif /* (_MSC_VER >= 1000) */
1112 #define FOPEN 0x01 /* file handle open */
1113 #define FAPPEND 0x20 /* file handle opened O_APPEND */
1114 #define FDEV 0x40 /* file handle refers to device */
1115 #define FTEXT 0x80 /* file handle is in text mode */
1117 #define _STREAM_LOCKS 26 /* Table of stream locks */
1118 #define _LAST_STREAM_LOCK (_STREAM_LOCKS+_NSTREAM_-1) /* Last stream lock */
1119 #define _FH_LOCKS (_LAST_STREAM_LOCK+1) /* Table of fh locks */
1122 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1125 * This function allocates a free C Runtime file handle and associates
1126 * it with the Win32 HANDLE specified by the first parameter. This is a
1127 * temperary fix for WIN95's brain damage GetFileType() error on socket
1128 * we just bypass that call for socket
1131 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1132 * int flags - flags to associate with C Runtime file handle.
1135 * returns index of entry in fh, if successful
1136 * return -1, if no free entry is found
1140 *******************************************************************************/
1143 my_open_osfhandle(long osfhandle, int flags)
1146 char fileflags; /* _osfile flags */
1148 /* copy relevant flags from second parameter */
1151 if(flags & O_APPEND)
1152 fileflags |= FAPPEND;
1157 /* attempt to allocate a C Runtime file handle */
1158 if((fh = _alloc_osfhnd()) == -1) {
1159 errno = EMFILE; /* too many open files */
1160 _doserrno = 0L; /* not an OS error */
1161 return -1; /* return error to caller */
1164 /* the file is open. now, set the info in _osfhnd array */
1165 _set_osfhnd(fh, osfhandle);
1167 fileflags |= FOPEN; /* mark as open */
1169 #if (_MSC_VER >= 1000)
1170 _osfile(fh) = fileflags; /* set osfile entry */
1171 _unlock_fhandle(fh);
1173 _osfile[fh] = fileflags; /* set osfile entry */
1174 _unlock(fh+_FH_LOCKS); /* unlock handle */
1177 return fh; /* return handle */
1180 #define _open_osfhandle my_open_osfhandle
1181 #endif /* USE_FIXED_OSFHANDLE */
1183 /* simulate flock by locking a range on the file */
1185 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1186 #define LK_LEN 0xffff0000
1189 win32_flock(int fd, int oper)
1196 croak("flock() unimplemented on this platform");
1199 fh = (HANDLE)_get_osfhandle(fd);
1200 memset(&o, 0, sizeof(o));
1203 case LOCK_SH: /* shared lock */
1204 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1206 case LOCK_EX: /* exclusive lock */
1207 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1209 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1210 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1212 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1213 LK_ERR(LockFileEx(fh,
1214 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1215 0, LK_LEN, 0, &o),i);
1217 case LOCK_UN: /* unlock lock */
1218 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1220 default: /* unknown */
1231 * redirected io subsystem for all XS modules
1244 return (&(_environ));
1247 /* the rest are the remapped stdio routines */
1267 win32_ferror(FILE *fp)
1269 return (ferror(fp));
1274 win32_feof(FILE *fp)
1280 * Since the errors returned by the socket error function
1281 * WSAGetLastError() are not known by the library routine strerror
1282 * we have to roll our own.
1286 win32_strerror(int e)
1288 #ifndef __BORLANDC__ /* Borland intolerance */
1289 extern int sys_nerr;
1293 if(e < 0 || e > sys_nerr) {
1298 if(FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
1299 strerror_buffer, sizeof(strerror_buffer), NULL) == 0)
1300 strcpy(strerror_buffer, "Unknown Error");
1302 return strerror_buffer;
1308 win32_str_os_error(void *sv, DWORD dwErr)
1312 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
1313 |FORMAT_MESSAGE_IGNORE_INSERTS
1314 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
1315 dwErr, 0, (char *)&sMsg, 1, NULL);
1317 while (0 < dwLen && isspace(sMsg[--dwLen]))
1319 if ('.' != sMsg[dwLen])
1324 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
1325 dwLen = sprintf(sMsg,
1326 "Unknown error #0x%lX (lookup 0x%lX)",
1327 dwErr, GetLastError());
1329 sv_setpvn((SV*)sv, sMsg, dwLen);
1335 win32_fprintf(FILE *fp, const char *format, ...)
1338 va_start(marker, format); /* Initialize variable arguments. */
1340 return (vfprintf(fp, format, marker));
1344 win32_printf(const char *format, ...)
1347 va_start(marker, format); /* Initialize variable arguments. */
1349 return (vprintf(format, marker));
1353 win32_vfprintf(FILE *fp, const char *format, va_list args)
1355 return (vfprintf(fp, format, args));
1359 win32_vprintf(const char *format, va_list args)
1361 return (vprintf(format, args));
1365 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
1367 return fread(buf, size, count, fp);
1371 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
1373 return fwrite(buf, size, count, fp);
1377 win32_fopen(const char *filename, const char *mode)
1379 if (stricmp(filename, "/dev/null")==0)
1380 return fopen("NUL", mode);
1381 return fopen(filename, mode);
1384 #ifndef USE_SOCKETS_AS_HANDLES
1386 #define fdopen my_fdopen
1390 win32_fdopen( int handle, const char *mode)
1392 return fdopen(handle, (char *) mode);
1396 win32_freopen( const char *path, const char *mode, FILE *stream)
1398 if (stricmp(path, "/dev/null")==0)
1399 return freopen("NUL", mode, stream);
1400 return freopen(path, mode, stream);
1404 win32_fclose(FILE *pf)
1406 return my_fclose(pf); /* defined in win32sck.c */
1410 win32_fputs(const char *s,FILE *pf)
1412 return fputs(s, pf);
1416 win32_fputc(int c,FILE *pf)
1422 win32_ungetc(int c,FILE *pf)
1424 return ungetc(c,pf);
1428 win32_getc(FILE *pf)
1434 win32_fileno(FILE *pf)
1440 win32_clearerr(FILE *pf)
1447 win32_fflush(FILE *pf)
1453 win32_ftell(FILE *pf)
1459 win32_fseek(FILE *pf,long offset,int origin)
1461 return fseek(pf, offset, origin);
1465 win32_fgetpos(FILE *pf,fpos_t *p)
1467 return fgetpos(pf, p);
1471 win32_fsetpos(FILE *pf,const fpos_t *p)
1473 return fsetpos(pf, p);
1477 win32_rewind(FILE *pf)
1497 win32_fstat(int fd,struct stat *sbufptr)
1499 return fstat(fd,sbufptr);
1503 win32_pipe(int *pfd, unsigned int size, int mode)
1505 return _pipe(pfd, size, mode);
1509 * a popen() clone that respects PERL5SHELL
1513 win32_popen(const char *command, const char *mode)
1515 #ifdef USE_CRT_POPEN
1516 return _popen(command, mode);
1524 /* establish which ends read and write */
1525 if (strchr(mode,'w')) {
1526 stdfd = 0; /* stdin */
1530 else if (strchr(mode,'r')) {
1531 stdfd = 1; /* stdout */
1538 /* set the correct mode */
1539 if (strchr(mode,'b'))
1541 else if (strchr(mode,'t'))
1544 ourmode = _fmode & (O_TEXT | O_BINARY);
1546 /* the child doesn't inherit handles */
1547 ourmode |= O_NOINHERIT;
1549 if (win32_pipe( p, 512, ourmode) == -1)
1552 /* save current stdfd */
1553 if ((oldfd = win32_dup(stdfd)) == -1)
1556 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
1557 /* stdfd will be inherited by the child */
1558 if (win32_dup2(p[child], stdfd) == -1)
1561 /* close the child end in parent */
1562 win32_close(p[child]);
1564 /* start the child */
1565 if ((childpid = do_spawn_nowait((char*)command)) == -1)
1568 /* revert stdfd to whatever it was before */
1569 if (win32_dup2(oldfd, stdfd) == -1)
1572 /* close saved handle */
1575 w32_popen_pids[p[parent]] = childpid;
1577 /* we have an fd, return a file stream */
1578 return (win32_fdopen(p[parent], (char *)mode));
1581 /* we don't need to check for errors here */
1585 win32_dup2(oldfd, stdfd);
1590 #endif /* USE_CRT_POPEN */
1598 win32_pclose(FILE *pf)
1600 #ifdef USE_CRT_POPEN
1603 int fd, childpid, status;
1605 fd = win32_fileno(pf);
1606 childpid = w32_popen_pids[fd];
1614 w32_popen_pids[fd] = 0;
1616 /* wait for the child */
1617 if (cwait(&status, childpid, WAIT_CHILD) == -1)
1619 /* cwait() returns differently on Borland */
1621 return (((status >> 8) & 0xff) | ((status << 8) & 0xff00));
1626 #endif /* USE_CRT_OPEN */
1630 win32_setmode(int fd, int mode)
1632 return setmode(fd, mode);
1636 win32_lseek(int fd, long offset, int origin)
1638 return lseek(fd, offset, origin);
1648 win32_open(const char *path, int flag, ...)
1654 pmode = va_arg(ap, int);
1657 if (stricmp(path, "/dev/null")==0)
1658 return open("NUL", flag, pmode);
1659 return open(path,flag,pmode);
1681 win32_dup2(int fd1,int fd2)
1683 return dup2(fd1,fd2);
1687 win32_read(int fd, void *buf, unsigned int cnt)
1689 return read(fd, buf, cnt);
1693 win32_write(int fd, const void *buf, unsigned int cnt)
1695 return write(fd, buf, cnt);
1699 win32_mkdir(const char *dir, int mode)
1701 return mkdir(dir); /* just ignore mode */
1705 win32_rmdir(const char *dir)
1711 win32_chdir(const char *dir)
1717 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
1721 status = spawnvp(mode, cmdname, (char * const *) argv);
1722 #ifndef __BORLANDC__
1723 /* XXX For the P_NOWAIT case, Borland RTL returns pinfo.dwProcessId
1724 * while VC RTL returns pinfo.hProcess. For purposes of the custom
1725 * implementation of win32_wait(), we assume the latter.
1727 if (mode == P_NOWAIT && status >= 0)
1728 w32_child_pids[w32_num_children++] = (HANDLE)status;
1734 win32_execvp(const char *cmdname, const char *const *argv)
1736 return execvp(cmdname, (char *const *)argv);
1740 win32_perror(const char *str)
1746 win32_setbuf(FILE *pf, char *buf)
1752 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
1754 return setvbuf(pf, buf, type, size);
1758 win32_flushall(void)
1764 win32_fcloseall(void)
1770 win32_fgets(char *s, int n, FILE *pf)
1772 return fgets(s, n, pf);
1782 win32_fgetc(FILE *pf)
1788 win32_putc(int c, FILE *pf)
1794 win32_puts(const char *s)
1806 win32_putchar(int c)
1813 #ifndef USE_PERL_SBRK
1815 static char *committed = NULL;
1816 static char *base = NULL;
1817 static char *reserved = NULL;
1818 static char *brk = NULL;
1819 static DWORD pagesize = 0;
1820 static DWORD allocsize = 0;
1828 GetSystemInfo(&info);
1829 /* Pretend page size is larger so we don't perpetually
1830 * call the OS to commit just one page ...
1832 pagesize = info.dwPageSize << 3;
1833 allocsize = info.dwAllocationGranularity;
1835 /* This scheme fails eventually if request for contiguous
1836 * block is denied so reserve big blocks - this is only
1837 * address space not memory ...
1839 if (brk+need >= reserved)
1841 DWORD size = 64*1024*1024;
1843 if (committed && reserved && committed < reserved)
1845 /* Commit last of previous chunk cannot span allocations */
1846 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
1848 committed = reserved;
1850 /* Reserve some (more) space
1851 * Note this is a little sneaky, 1st call passes NULL as reserved
1852 * so lets system choose where we start, subsequent calls pass
1853 * the old end address so ask for a contiguous block
1855 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
1858 reserved = addr+size;
1873 if (brk > committed)
1875 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
1876 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
1891 win32_malloc(size_t size)
1893 return malloc(size);
1897 win32_calloc(size_t numitems, size_t size)
1899 return calloc(numitems,size);
1903 win32_realloc(void *block, size_t size)
1905 return realloc(block,size);
1909 win32_free(void *block)
1916 win32_open_osfhandle(long handle, int flags)
1918 return _open_osfhandle(handle, flags);
1922 win32_get_osfhandle(int fd)
1924 return _get_osfhandle(fd);
1935 SV *sv = sv_newmortal();
1936 /* Make one call with zero size - return value is required size */
1937 DWORD len = GetCurrentDirectory((DWORD)0,NULL);
1938 SvUPGRADE(sv,SVt_PV);
1940 SvCUR(sv) = GetCurrentDirectory((DWORD) SvLEN(sv), SvPVX(sv));
1943 * then it worked, set PV valid,
1944 * else leave it 'undef'
1958 croak("usage: Win32::SetCurrentDirectory($cwd)");
1959 if (SetCurrentDirectory(SvPV(ST(0),na)))
1966 XS(w32_GetNextAvailDrive)
1970 char root[] = "_:\\";
1973 if (GetDriveType(root) == 1) {
1982 XS(w32_GetLastError)
1985 XSRETURN_IV(GetLastError());
1992 char *name = getlogin_buffer;
1993 DWORD size = sizeof(getlogin_buffer);
1994 if (GetUserName(name,&size)) {
1995 /* size includes NULL */
1996 ST(0) = sv_2mortal(newSVpv(name,size-1));
2006 char name[MAX_COMPUTERNAME_LENGTH+1];
2007 DWORD size = sizeof(name);
2008 if (GetComputerName(name,&size)) {
2009 /* size does NOT include NULL :-( */
2010 ST(0) = sv_2mortal(newSVpv(name,size));
2022 DWORD size = sizeof(name);
2023 if (GetUserName(name,&size)) {
2025 DWORD sidlen = sizeof(sid);
2027 DWORD dnamelen = sizeof(dname);
2029 if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
2030 dname, &dnamelen, &snu)) {
2031 XSRETURN_PV(dname); /* all that for this */
2042 DWORD flags, filecomplen;
2043 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
2044 &flags, fsname, sizeof(fsname))) {
2045 if (GIMME == G_ARRAY) {
2046 XPUSHs(sv_2mortal(newSVpv(fsname,0)));
2047 XPUSHs(sv_2mortal(newSViv(flags)));
2048 XPUSHs(sv_2mortal(newSViv(filecomplen)));
2052 XSRETURN_PV(fsname);
2058 XS(w32_GetOSVersion)
2061 OSVERSIONINFO osver;
2063 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
2064 if (GetVersionEx(&osver)) {
2065 XPUSHs(newSVpv(osver.szCSDVersion, 0));
2066 XPUSHs(newSViv(osver.dwMajorVersion));
2067 XPUSHs(newSViv(osver.dwMinorVersion));
2068 XPUSHs(newSViv(osver.dwBuildNumber));
2069 XPUSHs(newSViv(osver.dwPlatformId));
2080 XSRETURN_IV(IsWinNT());
2087 XSRETURN_IV(IsWin95());
2091 XS(w32_FormatMessage)
2098 croak("usage: Win32::FormatMessage($errno)");
2100 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
2101 &source, SvIV(ST(0)), 0,
2102 msgbuf, sizeof(msgbuf)-1, NULL))
2103 XSRETURN_PV(msgbuf);
2113 PROCESS_INFORMATION stProcInfo;
2114 STARTUPINFO stStartInfo;
2115 BOOL bSuccess = FALSE;
2118 croak("usage: Win32::Spawn($cmdName, $args, $PID)");
2120 cmd = SvPV(ST(0),na);
2121 args = SvPV(ST(1), na);
2123 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
2124 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
2125 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
2126 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
2129 cmd, /* Image path */
2130 args, /* Arguments for command line */
2131 NULL, /* Default process security */
2132 NULL, /* Default thread security */
2133 FALSE, /* Must be TRUE to use std handles */
2134 NORMAL_PRIORITY_CLASS, /* No special scheduling */
2135 NULL, /* Inherit our environment block */
2136 NULL, /* Inherit our currrent directory */
2137 &stStartInfo, /* -> Startup info */
2138 &stProcInfo)) /* <- Process info (if OK) */
2140 CloseHandle(stProcInfo.hThread);/* library source code does this. */
2141 sv_setiv(ST(2), stProcInfo.dwProcessId);
2144 XSRETURN_IV(bSuccess);
2148 XS(w32_GetTickCount)
2151 XSRETURN_IV(GetTickCount());
2155 XS(w32_GetShortPathName)
2162 croak("usage: Win32::GetShortPathName($longPathName)");
2164 shortpath = sv_mortalcopy(ST(0));
2165 SvUPGRADE(shortpath, SVt_PV);
2166 /* src == target is allowed */
2168 len = GetShortPathName(SvPVX(shortpath),
2171 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
2173 SvCUR_set(shortpath,len);
2186 croak("usage: Win32::Sleep($milliseconds)");
2191 #define TMPBUFSZ 1024
2192 #define MAX_LENGTH 2048
2193 #define SUCCESSRETURNED(x) (x == ERROR_SUCCESS)
2194 #define REGRETURN(x) XSRETURN_IV(SUCCESSRETURNED(x))
2195 #define SvHKEY(index) (HKEY)((unsigned long)SvIV(index))
2196 #define SETIV(index,value) sv_setiv(ST(index), value)
2197 #define SETNV(index,value) sv_setnv(ST(index), value)
2198 #define SETPV(index,string) sv_setpv(ST(index), string)
2199 #define SETPVN(index, buffer, length) sv_setpvn(ST(index), (char*)buffer, length)
2200 #define SETHKEY(index, hkey) SETIV(index,(long)hkey)
2202 static time_t ft2timet(FILETIME *ft)
2207 FileTimeToSystemTime(ft, &st);
2208 tm.tm_sec = st.wSecond;
2209 tm.tm_min = st.wMinute;
2210 tm.tm_hour = st.wHour;
2211 tm.tm_mday = st.wDay;
2212 tm.tm_mon = st.wMonth - 1;
2213 tm.tm_year = st.wYear - 1900;
2214 tm.tm_wday = st.wDayOfWeek;
2217 return mktime (&tm);
2227 croak("usage: Win32::RegCloseKey($hkey);\n");
2230 REGRETURN(RegCloseKey(SvHKEY(ST(0))));
2234 XS(w32_RegConnectRegistry)
2241 croak("usage: Win32::RegConnectRegistry($machine, $hkey, $handle);\n");
2244 if(SUCCESSRETURNED(RegConnectRegistry((char *)SvPV(ST(0), na), SvHKEY(ST(1)), &handle)))
2253 XS(w32_RegCreateKey)
2262 croak("usage: Win32::RegCreateKey($hkey, $subkey, $handle);\n");
2265 retval = RegCreateKeyEx(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS,
2266 NULL, &handle, &disposition);
2268 if(SUCCESSRETURNED(retval))
2277 XS(w32_RegCreateKeyEx)
2281 unsigned int length;
2286 DWORD options, disposition;
2288 SECURITY_ATTRIBUTES sa, *psa;
2292 croak("usage: Win32::RegCreateKeyEx($hkey, $subkey, $reserved, $class, $options, $sam, "
2293 "$security, $handle, $disposition);\n");
2296 hkey = SvHKEY(ST(0));
2297 subkey = (char *)SvPV(ST(1), na);
2298 keyclass = (char *)SvPV(ST(3), na);
2299 options = (DWORD) ((unsigned long)SvIV(ST(4)));
2300 sam = (REGSAM) ((unsigned long)SvIV(ST(5)));
2301 psa = (SECURITY_ATTRIBUTES*)SvPV(ST(6), length);
2302 if(length != sizeof(SECURITY_ATTRIBUTES))
2305 memset(&sa, 0, sizeof(SECURITY_ATTRIBUTES));
2306 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
2309 retval = RegCreateKeyEx(hkey, subkey, 0, keyclass, options, sam,
2310 psa, &handle, &disposition);
2312 if(SUCCESSRETURNED(retval))
2315 SETPVN(6, &sa, sizeof(sa));
2318 SETIV(8,disposition);
2325 XS(w32_RegDeleteKey)
2331 croak("usage: Win32::RegDeleteKey($hkey, $subkey);\n");
2334 REGRETURN(RegDeleteKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na)));
2338 XS(w32_RegDeleteValue)
2344 croak("usage: Win32::RegDeleteValue($hkey, $valname);\n");
2347 REGRETURN(RegDeleteValue(SvHKEY(ST(0)), (char *)SvPV(ST(1), na)));
2355 char keybuffer[TMPBUFSZ];
2359 croak("usage: Win32::RegEnumKey($hkey, $idx, $subkeyname);\n");
2362 if(SUCCESSRETURNED(RegEnumKey(SvHKEY(ST(0)), SvIV(ST(1)), keybuffer, sizeof(keybuffer))))
2364 SETPV(2, keybuffer);
2371 XS(w32_RegEnumKeyEx)
2376 DWORD keysz, classsz;
2377 char keybuffer[TMPBUFSZ];
2378 char classbuffer[TMPBUFSZ];
2384 croak("usage: Win32::RegEnumKeyEx($hkey, $idx, $subkeyname, $reserved, $class, $time);\n");
2387 keysz = sizeof(keybuffer);
2388 classsz = sizeof(classbuffer);
2389 retval = RegEnumKeyEx(SvHKEY(ST(0)), SvIV(ST(1)), keybuffer, &keysz, 0,
2390 classbuffer, &classsz, &filetime);
2391 if(SUCCESSRETURNED(retval))
2393 SETPV(2, keybuffer);
2394 SETPV(4, classbuffer);
2395 SETIV(5, ft2timet(&filetime));
2402 XS(w32_RegEnumValue)
2406 DWORD type, namesz, valsz;
2408 static HKEY last_hkey;
2409 char myvalbuf[MAX_LENGTH];
2410 char mynambuf[MAX_LENGTH];
2414 croak("usage: Win32::RegEnumValue($hkey, $i, $name, $reserved, $type, $value);\n");
2417 hkey = SvHKEY(ST(0));
2419 // If this is a new key, find out how big the maximum name and value sizes are and
2420 // allocate space for them. Free any old storage and set the old key value to the
2423 if(hkey != (HKEY)last_hkey)
2425 char keyclass[TMPBUFSZ];
2426 DWORD classsz, subkeys, maxsubkey, maxclass, values, salen, maxnamesz, maxvalsz;
2428 classsz = sizeof(keyclass);
2429 retval = RegQueryInfoKey(hkey, keyclass, &classsz, 0, &subkeys, &maxsubkey, &maxclass,
2430 &values, &maxnamesz, &maxvalsz, &salen, &ft);
2432 if(!SUCCESSRETURNED(retval))
2436 memset(myvalbuf, 0, MAX_LENGTH);
2437 memset(mynambuf, 0, MAX_LENGTH);
2441 namesz = MAX_LENGTH;
2443 retval = RegEnumValue(hkey, SvIV(ST(1)), mynambuf, &namesz, 0, &type, (LPBYTE) myvalbuf, &valsz);
2444 if(!SUCCESSRETURNED(retval))
2453 // return includes the null terminator so delete it if REG_SZ, REG_MULTI_SZ or REG_EXPAND_SZ
2462 SETPVN(5, myvalbuf, valsz);
2465 case REG_DWORD_BIG_ENDIAN:
2467 BYTE tmp = myvalbuf[0];
2468 myvalbuf[0] = myvalbuf[3];
2471 myvalbuf[1] = myvalbuf[2];
2474 case REG_DWORD_LITTLE_ENDIAN: // same as REG_DWORD
2475 SETNV(5, (double)*((DWORD*)myvalbuf));
2493 croak("usage: Win32::RegFlushKey($hkey);\n");
2496 REGRETURN(RegFlushKey(SvHKEY(ST(0))));
2500 XS(w32_RegGetKeySecurity)
2503 SECURITY_DESCRIPTOR sd;
2508 croak("usage: Win32::RegGetKeySecurity($hkey, $security_info, $security_descriptor);\n");
2511 if(SUCCESSRETURNED(RegGetKeySecurity(SvHKEY(ST(0)), SvIV(ST(1)), &sd, &sdsz)))
2513 SETPVN(2, &sd, sdsz);
2526 croak("usage: Win32::RegLoadKey($hkey, $subkey, $filename);\n");
2529 REGRETURN(RegLoadKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), (char *)SvPV(ST(2), na)));
2533 XS(w32_RegNotifyChangeKeyValue)
2535 croak("Win32::RegNotifyChangeKeyValue not yet implemented!\n");
2546 croak("usage: Win32::RegOpenKey($hkey, $subkey, $handle);\n");
2549 if(SUCCESSRETURNED(RegOpenKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), &handle)))
2558 XS(w32_RegOpenKeyEx)
2565 croak("usage: Win32::RegOpenKeyEx($hkey, $subkey, $reserved, $sam, $handle);\n");
2568 if(SUCCESSRETURNED(RegOpenKeyEx(SvHKEY(ST(0)), (char *)SvPV(ST(1), na),
2569 0, (REGSAM) ((unsigned long)SvIV(ST(3))), &handle)))
2577 #pragma optimize("", off)
2579 XS(w32_RegQueryInfoKey)
2584 char keyclass[TMPBUFSZ];
2585 DWORD subkeys, maxsubkey, maxclass, values, maxvalname, maxvaldata;
2586 DWORD seclen, classsz;
2592 croak("usage: Win32::RegQueryInfoKey($hkey, $class, $numsubkeys, $maxsubkey,"
2593 "$maxclass, $values, $maxvalname, $maxvaldata, $secdesclen,"
2594 "$lastwritetime);\n");
2597 classsz = sizeof(keyclass);
2598 retval = RegQueryInfoKey(SvHKEY(ST(0)), keyclass, &classsz, 0, &subkeys, &maxsubkey,
2599 &maxclass, &values, &maxvalname, &maxvaldata,
2601 if(SUCCESSRETURNED(retval))
2605 SETIV(3, maxsubkey);
2608 SETIV(6, maxvalname);
2609 SETIV(7, maxvaldata);
2611 SETIV(9, ft2timet(&ft));
2616 #pragma optimize("", on)
2619 XS(w32_RegQueryValue)
2623 unsigned char databuffer[TMPBUFSZ*2];
2624 long datasz = sizeof(databuffer);
2628 croak("usage: Win32::RegQueryValue($hkey, $valuename, $data);\n");
2631 if(SUCCESSRETURNED(RegQueryValue(SvHKEY(ST(0)), SvPV(ST(1), na), (char*)databuffer, &datasz)))
2633 // return includes the null terminator so delete it
2634 SETPVN(2, databuffer, --datasz);
2641 XS(w32_RegQueryValueEx)
2645 unsigned char databuffer[TMPBUFSZ*2];
2646 DWORD datasz = sizeof(databuffer);
2649 LPBYTE ptr = databuffer;
2653 croak("usage: Win32::RegQueryValueEx($hkey, $valuename, $reserved, $type, $data);\n");
2656 result = RegQueryValueEx(SvHKEY(ST(0)), SvPV(ST(1), na), 0, &type, ptr, &datasz);
2657 if(result == ERROR_MORE_DATA)
2659 New(0, ptr, datasz+1, BYTE);
2660 result = RegQueryValueEx(SvHKEY(ST(0)), SvPV(ST(1), na), 0, &type, ptr, &datasz);
2662 if(SUCCESSRETURNED(result))
2666 // return includes the null terminator so delete it if REG_SZ, REG_MULTI_SZ or REG_EXPAND_SZ
2674 SETPVN(4, ptr, datasz);
2677 case REG_DWORD_BIG_ENDIAN:
2686 case REG_DWORD_LITTLE_ENDIAN: // same as REG_DWORD
2687 SETNV(4, (double)*((DWORD*)ptr));
2694 if(ptr != databuffer)
2699 if(ptr != databuffer)
2706 XS(w32_RegReplaceKey)
2712 croak("usage: Win32::RegReplaceKey($hkey, $subkey, $newfile, $oldfile);\n");
2715 REGRETURN(RegReplaceKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), (char *)SvPV(ST(2), na), (char *)SvPV(ST(3), na)));
2719 XS(w32_RegRestoreKey)
2723 if(items < 2 || items > 3)
2725 croak("usage: Win32::RegRestoreKey($hkey, $filename [, $flags]);\n");
2728 REGRETURN(RegRestoreKey(SvHKEY(ST(0)), (char*)SvPV(ST(1), na), (DWORD)((items == 3) ? SvIV(ST(2)) : 0)));
2738 croak("usage: Win32::RegSaveKey($hkey, $filename);\n");
2741 REGRETURN(RegSaveKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), NULL));
2745 XS(w32_RegSetKeySecurity)
2751 croak("usage: Win32::RegSetKeySecurity($hkey, $security_info, $security_descriptor);\n");
2754 REGRETURN(RegSetKeySecurity(SvHKEY(ST(0)), SvIV(ST(1)), (SECURITY_DESCRIPTOR*)SvPV(ST(2), na)));
2767 croak("usage: Win32::RegSetValue($hkey, $subKey, $type, $data);\n");
2770 DWORD type = SvIV(ST(2));
2771 if(type != REG_SZ && type != REG_EXPAND_SZ)
2773 croak("Win32::RegSetValue: Type was not REG_SZ or REG_EXPAND_SZ, cannot set %s\n", (char *)SvPV(ST(1), na));
2776 buffer = (char *)SvPV(ST(3), size);
2777 REGRETURN(RegSetValue(SvHKEY(ST(0)), SvPV(ST(1), na), REG_SZ, buffer, size));
2781 XS(w32_RegSetValueEx)
2792 croak("usage: Win32::RegSetValueEx($hkey, $valname, $reserved, $type, $data);\n");
2795 type = (DWORD)SvIV(ST(3));
2802 buffer = (char *)SvPV(ST(4), size);
2803 if(type != REG_BINARY)
2804 size++; // include null terminator in size
2806 REGRETURN(RegSetValueEx(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), 0, type, (PBYTE) buffer, size));
2809 case REG_DWORD_BIG_ENDIAN:
2810 case REG_DWORD_LITTLE_ENDIAN: // Same as REG_DWORD
2811 val = (DWORD)SvIV(ST(4));
2812 REGRETURN(RegSetValueEx(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), 0, type, (PBYTE) &val, sizeof(DWORD)));
2816 croak("Win32::RegSetValueEx: Type not specified, cannot set %s\n", (char *)SvPV(ST(1), na));
2821 XS(w32_RegUnloadKey)
2827 croak("usage: Win32::RegUnLoadKey($hkey, $subkey);\n");
2830 REGRETURN(RegUnLoadKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na)));
2834 XS(w32_RegisterServer)
2837 BOOL bSuccess = FALSE;
2838 HINSTANCE hInstance;
2839 unsigned int length;
2844 croak("usage: Win32::RegisterServer($LibraryName)\n");
2847 hInstance = LoadLibrary((char *)SvPV(ST(0), length));
2848 if(hInstance != NULL)
2850 sFunc = GetProcAddress(hInstance, "DllRegisterServer");
2853 bSuccess = (sFunc() == 0);
2855 FreeLibrary(hInstance);
2866 XS(w32_UnregisterServer)
2869 BOOL bSuccess = FALSE;
2870 HINSTANCE hInstance;
2871 unsigned int length;
2876 croak("usage: Win32::UnregisterServer($LibraryName)\n");
2879 hInstance = LoadLibrary((char *)SvPV(ST(0), length));
2880 if(hInstance != NULL)
2882 sFunc = GetProcAddress(hInstance, "DllUnregisterServer");
2885 bSuccess = (sFunc() == 0);
2887 FreeLibrary(hInstance);
2899 Perl_init_os_extras()
2901 char *file = __FILE__;
2904 /* these names are Activeware compatible */
2905 newXS("Win32::GetCwd", w32_GetCwd, file);
2906 newXS("Win32::SetCwd", w32_SetCwd, file);
2907 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
2908 newXS("Win32::GetLastError", w32_GetLastError, file);
2909 newXS("Win32::LoginName", w32_LoginName, file);
2910 newXS("Win32::NodeName", w32_NodeName, file);
2911 newXS("Win32::DomainName", w32_DomainName, file);
2912 newXS("Win32::FsType", w32_FsType, file);
2913 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
2914 newXS("Win32::IsWinNT", w32_IsWinNT, file);
2915 newXS("Win32::IsWin95", w32_IsWin95, file);
2916 newXS("Win32::FormatMessage", w32_FormatMessage, file);
2917 newXS("Win32::Spawn", w32_Spawn, file);
2918 newXS("Win32::GetTickCount", w32_GetTickCount, file);
2919 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
2920 newXS("Win32::Sleep", w32_Sleep, file);
2922 /* the following extensions are used interally and may be changed at any time */
2923 /* therefore no documentation is provided */
2924 newXS("Win32::RegCloseKey", w32_RegCloseKey, file);
2925 newXS("Win32::RegConnectRegistry", w32_RegConnectRegistry, file);
2926 newXS("Win32::RegCreateKey", w32_RegCreateKey, file);
2927 newXS("Win32::RegCreateKeyEx", w32_RegCreateKeyEx, file);
2928 newXS("Win32::RegDeleteKey", w32_RegDeleteKey, file);
2929 newXS("Win32::RegDeleteValue", w32_RegDeleteValue, file);
2931 newXS("Win32::RegEnumKey", w32_RegEnumKey, file);
2932 newXS("Win32::RegEnumKeyEx", w32_RegEnumKeyEx, file);
2933 newXS("Win32::RegEnumValue", w32_RegEnumValue, file);
2935 newXS("Win32::RegFlushKey", w32_RegFlushKey, file);
2936 newXS("Win32::RegGetKeySecurity", w32_RegGetKeySecurity, file);
2938 newXS("Win32::RegLoadKey", w32_RegLoadKey, file);
2939 newXS("Win32::RegOpenKey", w32_RegOpenKey, file);
2940 newXS("Win32::RegOpenKeyEx", w32_RegOpenKeyEx, file);
2941 newXS("Win32::RegQueryInfoKey", w32_RegQueryInfoKey, file);
2942 newXS("Win32::RegQueryValue", w32_RegQueryValue, file);
2943 newXS("Win32::RegQueryValueEx", w32_RegQueryValueEx, file);
2945 newXS("Win32::RegReplaceKey", w32_RegReplaceKey, file);
2946 newXS("Win32::RegRestoreKey", w32_RegRestoreKey, file);
2947 newXS("Win32::RegSaveKey", w32_RegSaveKey, file);
2948 newXS("Win32::RegSetKeySecurity", w32_RegSetKeySecurity, file);
2949 newXS("Win32::RegSetValue", w32_RegSetValue, file);
2950 newXS("Win32::RegSetValueEx", w32_RegSetValueEx, file);
2951 newXS("Win32::RegUnloadKey", w32_RegUnloadKey, file);
2953 newXS("Win32::RegisterServer", w32_RegisterServer, file);
2954 newXS("Win32::UnregisterServer", w32_UnregisterServer, file);
2956 /* XXX Bloat Alert! The following Activeware preloads really
2957 * ought to be part of Win32::Sys::*, so they're not included
2960 /* LookupAccountName
2962 * InitiateSystemShutdown
2963 * AbortSystemShutdown
2964 * ExpandEnvrironmentStrings
2969 Perl_win32_init(int *argcp, char ***argvp)
2971 /* Disable floating point errors, Perl will trap the ones we
2972 * care about. VC++ RTL defaults to switching these off
2973 * already, but the Borland RTL doesn't. Since we don't
2974 * want to be at the vendor's whim on the default, we set
2975 * it explicitly here.
2977 #if !defined(_ALPHA_) && !defined(__GNUC__)
2978 _control87(MCW_EM, MCW_EM);
2983 #ifdef USE_BINMODE_SCRIPTS
2986 win32_strip_return(SV *sv)
2988 char *s = SvPVX(sv);
2989 char *e = s+SvCUR(sv);
2993 if (*s == '\r' && s[1] == '\n')
3003 SvCUR_set(sv,d-SvPVX(sv));