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)
26 /* ugliness to work around a buggy struct definition in lmwksta.h */
33 #endif /* __MINGW32__ */
35 /* #include "config.h" */
37 #define PERLIO_NOT_STDIO 0
38 #if !defined(PERLIO_IS_STDIO) && !defined(USE_SFIO)
47 extern CPerlObj* pPerl;
55 /* assert.h conflicts with #define of assert in perl.h */
62 #if defined(_MSC_VER) || defined(__MINGW32__)
63 #include <sys/utime.h>
69 /* Mingw32 defaults to globing command line
70 * So we turn it off like this:
77 #define EXECF_SPAWN_NOWAIT 3
79 #if defined(PERL_OBJECT)
80 #undef win32_get_stdlib
81 #define win32_get_stdlib g_win32_get_stdlib
82 #undef win32_get_sitelib
83 #define win32_get_sitelib g_win32_get_sitelib
85 #define do_aspawn g_do_aspawn
87 #define do_spawn g_do_spawn
89 #define do_exec g_do_exec
91 #define opendir g_opendir
93 #define readdir g_readdir
95 #define telldir g_telldir
97 #define seekdir g_seekdir
99 #define rewinddir g_rewinddir
101 #define closedir g_closedir
103 #define getlogin g_getlogin
106 static DWORD os_id(void);
107 static void get_shell(void);
108 static long tokenize(char *str, char **dest, char ***destv);
109 int do_spawn2(char *cmd, int exectype);
110 static BOOL has_redirection(char *ptr);
111 static long filetime_to_clock(PFILETIME ft);
112 static BOOL filetime_from_time(PFILETIME ft, time_t t);
115 char * w32_perlshell_tokens = Nullch;
116 char ** w32_perlshell_vec;
117 long w32_perlshell_items = -1;
118 DWORD w32_platform = (DWORD)-1;
119 char w32_perllib_root[MAX_PATH+1];
120 HANDLE w32_perldll_handle = INVALID_HANDLE_VALUE;
122 long w32_num_children = 0;
123 HANDLE w32_child_pids[MAXIMUM_WAIT_OBJECTS];
127 # if defined(_NSTREAM_)
128 # define FOPEN_MAX _NSTREAM_
129 # elsif defined(_NFILE_)
130 # define FOPEN_MAX _NFILE_
131 # elsif defined(_NFILE)
132 # define FOPEN_MAX _NFILE
136 #ifndef USE_CRT_POPEN
137 int w32_popen_pids[FOPEN_MAX];
141 # ifdef USE_DECLSPEC_THREAD
142 __declspec(thread) char strerror_buffer[512];
143 __declspec(thread) char getlogin_buffer[128];
144 # ifdef HAVE_DES_FCRYPT
145 __declspec(thread) char crypt_buffer[30];
148 # define strerror_buffer (thr->i.Wstrerror_buffer)
149 # define getlogin_buffer (thr->i.Wgetlogin_buffer)
150 # define crypt_buffer (thr->i.Wcrypt_buffer)
153 char strerror_buffer[512];
154 char getlogin_buffer[128];
155 # ifdef HAVE_DES_FCRYPT
156 char crypt_buffer[30];
162 return (os_id() == VER_PLATFORM_WIN32_WINDOWS);
167 return (os_id() == VER_PLATFORM_WIN32_NT);
171 GetRegStrFromKey(HKEY hkey, const char *lpszValueName, char** ptr, DWORD* lpDataLen)
172 { /* Retrieve a REG_SZ or REG_EXPAND_SZ from the registry */
175 const char *subkey = "Software\\Perl";
178 retval = RegOpenKeyEx(hkey, subkey, 0, KEY_READ, &handle);
179 if (retval == ERROR_SUCCESS){
180 retval = RegQueryValueEx(handle, lpszValueName, 0, &type, NULL, lpDataLen);
181 if (retval == ERROR_SUCCESS && type == REG_SZ) {
183 Renew(*ptr, *lpDataLen, char);
186 New(1312, *ptr, *lpDataLen, char);
188 retval = RegQueryValueEx(handle, lpszValueName, 0, NULL, (PBYTE)*ptr, lpDataLen);
189 if (retval != ERROR_SUCCESS) {
200 GetRegStr(const char *lpszValueName, char** ptr, DWORD* lpDataLen)
202 *ptr = GetRegStrFromKey(HKEY_CURRENT_USER, lpszValueName, ptr, lpDataLen);
205 *ptr = GetRegStrFromKey(HKEY_LOCAL_MACHINE, lpszValueName, ptr, lpDataLen);
211 win32_get_stdlib(char *pl)
213 static char szStdLib[] = "lib";
214 int len = 0, newSize;
215 char szBuffer[MAX_PATH+1];
216 char szModuleName[MAX_PATH];
222 /* $stdlib = $HKCU{"lib-$]"} || $HKLM{"lib-$]"} || $HKCU{"lib"} || $HKLM{"lib"} || ""; */
223 sprintf(szBuffer, "%s-%s", szStdLib, pl);
224 lpPath = GetRegStr(szBuffer, &lpPath, &dwDataLen);
226 lpPath = GetRegStr(szStdLib, &lpPath, &dwDataLen);
228 /* $stdlib .= ";$EMD/../../lib" */
229 GetModuleFileName(GetModuleHandle(NULL), szModuleName, sizeof(szModuleName));
230 ptr = strrchr(szModuleName, '\\');
234 ptr = strrchr(szModuleName, '\\');
238 ptr = strrchr(szModuleName, '\\');
246 strcpy(++ptr, szStdLib);
248 /* check that this path exists */
249 GetCurrentDirectory(sizeof(szBuffer), szBuffer);
250 result = SetCurrentDirectory(szModuleName);
251 SetCurrentDirectory(szBuffer);
254 GetModuleFileName(GetModuleHandle(NULL), szModuleName, sizeof(szModuleName));
255 ptr = strrchr(szModuleName, '\\');
257 strcpy(++ptr, szStdLib);
260 newSize = strlen(szModuleName) + 1;
263 len = strlen(lpPath);
264 newSize += len + 1; /* plus 1 for ';' */
265 lpPath = Renew(lpPath, newSize, char);
268 New(1310, lpPath, newSize, char);
274 strcpy(&lpPath[len], szModuleName);
280 get_sitelib_part(char* lpRegStr, char* lpPathStr)
282 char szBuffer[MAX_PATH+1];
283 char szModuleName[MAX_PATH];
290 lpPath = GetRegStr(lpRegStr, &lpPath, &dwDataLen);
292 /* $sitelib .= ";$EMD/../../../<lpPathStr>" */
293 GetModuleFileName(GetModuleHandle(NULL), szModuleName, sizeof(szModuleName));
294 ptr = strrchr(szModuleName, '\\');
298 ptr = strrchr(szModuleName, '\\');
302 ptr = strrchr(szModuleName, '\\');
306 ptr = strrchr(szModuleName, '\\');
315 strcpy(++ptr, lpPathStr);
317 /* check that this path exists */
318 GetCurrentDirectory(sizeof(szBuffer), szBuffer);
319 result = SetCurrentDirectory(szModuleName);
320 SetCurrentDirectory(szBuffer);
324 int newSize = strlen(szModuleName) + 1;
327 len = strlen(lpPath);
328 newSize += len + 1; /* plus 1 for ';' */
329 lpPath = Renew(lpPath, newSize, char);
332 New(1311, lpPath, newSize, char);
338 strcpy(&lpPath[len], szModuleName);
345 win32_get_sitelib(char *pl)
347 static char szSiteLib[] = "sitelib";
349 char szPathStr[MAX_PATH];
354 /* $HKCU{"sitelib-$]"} || $HKLM{"sitelib-$]"} . ---; */
355 sprintf(szRegStr, "%s-%s", szSiteLib, pl);
356 sprintf(szPathStr, "site\\%s\\lib", pl);
357 lpPath1 = get_sitelib_part(szRegStr, szPathStr);
359 /* $HKCU{'sitelib'} || $HKLM{'sitelib'} . ---; */
360 lpPath2 = get_sitelib_part(szSiteLib, "site\\lib");
367 len = strlen(lpPath1);
368 newSize = len + strlen(lpPath2) + 2; /* plus one for ';' */
370 lpPath1 = Renew(lpPath1, newSize, char);
373 lpPath1[len++] = ';';
374 strcpy(&lpPath1[len], lpPath2);
382 has_redirection(char *ptr)
388 * Scan string looking for redirection (< or >) or pipe
389 * characters (|) that are not in a quoted string
419 #if !defined(PERL_OBJECT)
420 /* since the current process environment is being updated in util.c
421 * the library functions will get the correct environment
424 my_popen(char *cmd, char *mode)
427 #define fixcmd(x) { \
428 char *pspace = strchr((x),' '); \
431 while (p < pspace) { \
442 win32_fflush(stdout);
443 win32_fflush(stderr);
444 return win32_popen(cmd, mode);
448 my_pclose(PerlIO *fp)
450 return win32_pclose(fp);
457 static OSVERSIONINFO osver;
459 if (osver.dwPlatformId != w32_platform) {
460 memset(&osver, 0, sizeof(OSVERSIONINFO));
461 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
462 GetVersionEx(&osver);
463 w32_platform = osver.dwPlatformId;
465 return (w32_platform);
468 /* Tokenize a string. Words are null-separated, and the list
469 * ends with a doubled null. Any character (except null and
470 * including backslash) may be escaped by preceding it with a
471 * backslash (the backslash will be stripped).
472 * Returns number of words in result buffer.
475 tokenize(char *str, char **dest, char ***destv)
477 char *retstart = Nullch;
478 char **retvstart = 0;
481 int slen = strlen(str);
483 register char **retv;
484 New(1307, ret, slen+2, char);
485 New(1308, retv, (slen+3)/2, char*);
493 if (*ret == '\\' && *str)
495 else if (*ret == ' ') {
511 retvstart[items] = Nullch;
523 if (!w32_perlshell_tokens) {
524 /* we don't use COMSPEC here for two reasons:
525 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
526 * uncontrolled unportability of the ensuing scripts.
527 * 2. PERL5SHELL could be set to a shell that may not be fit for
528 * interactive use (which is what most programs look in COMSPEC
531 char* defaultshell = (IsWinNT() ? "cmd.exe /x/c" : "command.com /c");
532 char *usershell = getenv("PERL5SHELL");
533 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
534 &w32_perlshell_tokens,
540 do_aspawn(void *vreally, void **vmark, void **vsp)
542 SV *really = (SV*)vreally;
543 SV **mark = (SV**)vmark;
555 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
557 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
562 while (++mark <= sp) {
563 if (*mark && (str = SvPV(*mark, na)))
570 status = win32_spawnvp(flag,
571 (const char*)(really ? SvPV(really,na) : argv[0]),
572 (const char* const*)argv);
574 if (status < 0 && errno == ENOEXEC) {
575 /* possible shell-builtin, invoke with shell */
577 sh_items = w32_perlshell_items;
579 argv[index+sh_items] = argv[index];
580 while (--sh_items >= 0)
581 argv[sh_items] = w32_perlshell_vec[sh_items];
583 status = win32_spawnvp(flag,
584 (const char*)(really ? SvPV(really,na) : argv[0]),
585 (const char* const*)argv);
588 if (flag != P_NOWAIT) {
591 warn("Can't spawn \"%s\": %s", argv[0], strerror(errno));
596 statusvalue = status;
603 do_spawn2(char *cmd, int exectype)
609 BOOL needToTry = TRUE;
612 /* Save an extra exec if possible. See if there are shell
613 * metacharacters in it */
614 if (!has_redirection(cmd)) {
615 New(1301,argv, strlen(cmd) / 2 + 2, char*);
616 New(1302,cmd2, strlen(cmd) + 1, char);
619 for (s = cmd2; *s;) {
620 while (*s && isspace(*s))
624 while (*s && !isspace(*s))
633 status = win32_spawnvp(P_WAIT, argv[0],
634 (const char* const*)argv);
636 case EXECF_SPAWN_NOWAIT:
637 status = win32_spawnvp(P_NOWAIT, argv[0],
638 (const char* const*)argv);
641 status = win32_execvp(argv[0], (const char* const*)argv);
644 if (status != -1 || errno == 0)
654 New(1306, argv, w32_perlshell_items + 2, char*);
655 while (++i < w32_perlshell_items)
656 argv[i] = w32_perlshell_vec[i];
661 status = win32_spawnvp(P_WAIT, argv[0],
662 (const char* const*)argv);
664 case EXECF_SPAWN_NOWAIT:
665 status = win32_spawnvp(P_NOWAIT, argv[0],
666 (const char* const*)argv);
669 status = win32_execvp(argv[0], (const char* const*)argv);
675 if (exectype != EXECF_SPAWN_NOWAIT) {
678 warn("Can't %s \"%s\": %s",
679 (exectype == EXECF_EXEC ? "exec" : "spawn"),
680 cmd, strerror(errno));
685 statusvalue = status;
693 return do_spawn2(cmd, EXECF_SPAWN);
697 do_spawn_nowait(char *cmd)
699 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
705 do_spawn2(cmd, EXECF_EXEC);
709 /* The idea here is to read all the directory names into a string table
710 * (separated by nulls) and when one of the other dir functions is called
711 * return the pointer to the current file name.
714 opendir(char *filename)
719 char scanname[MAX_PATH+3];
721 WIN32_FIND_DATA FindData;
724 len = strlen(filename);
728 /* check to see if filename is a directory */
729 if (win32_stat(filename, &sbuf) < 0 || (sbuf.st_mode & S_IFDIR) == 0) {
730 /* CRT is buggy on sharenames, so make sure it really isn't */
731 DWORD r = GetFileAttributes(filename);
732 if (r == 0xffffffff || !(r & FILE_ATTRIBUTE_DIRECTORY))
736 /* Get us a DIR structure */
737 Newz(1303, p, 1, DIR);
741 /* Create the search pattern */
742 strcpy(scanname, filename);
743 if (scanname[len-1] != '/' && scanname[len-1] != '\\')
744 scanname[len++] = '/';
745 scanname[len++] = '*';
746 scanname[len] = '\0';
748 /* do the FindFirstFile call */
749 fh = FindFirstFile(scanname, &FindData);
750 if (fh == INVALID_HANDLE_VALUE) {
754 /* now allocate the first part of the string table for
755 * the filenames that we find.
757 idx = strlen(FindData.cFileName)+1;
758 New(1304, p->start, idx, char);
759 if (p->start == NULL)
760 croak("opendir: malloc failed!\n");
761 strcpy(p->start, FindData.cFileName);
764 /* loop finding all the files that match the wildcard
765 * (which should be all of them in this directory!).
766 * the variable idx should point one past the null terminator
767 * of the previous string found.
769 while (FindNextFile(fh, &FindData)) {
770 len = strlen(FindData.cFileName);
771 /* bump the string table size by enough for the
772 * new name and it's null terminator
774 Renew(p->start, idx+len+1, char);
775 if (p->start == NULL)
776 croak("opendir: malloc failed!\n");
777 strcpy(&p->start[idx], FindData.cFileName);
788 /* Readdir just returns the current string pointer and bumps the
789 * string pointer to the nDllExport entry.
795 static int dummy = 0;
798 /* first set up the structure to return */
799 len = strlen(dirp->curr);
800 strcpy(dirp->dirstr.d_name, dirp->curr);
801 dirp->dirstr.d_namlen = len;
804 dirp->dirstr.d_ino = dummy++;
806 /* Now set up for the nDllExport call to readdir */
807 dirp->curr += len + 1;
808 if (dirp->curr >= (dirp->start + dirp->size)) {
812 return &(dirp->dirstr);
818 /* Telldir returns the current string pointer position */
822 return (long) dirp->curr;
826 /* Seekdir moves the string pointer to a previously saved position
830 seekdir(DIR *dirp, long loc)
832 dirp->curr = (char *)loc;
835 /* Rewinddir resets the string pointer to the start */
839 dirp->curr = dirp->start;
842 /* free the memory allocated by opendir */
846 Safefree(dirp->start);
859 * Just pretend that everyone is a superuser. NT will let us know if
860 * we don\'t really have permission to do something.
863 #define ROOT_UID ((uid_t)0)
864 #define ROOT_GID ((gid_t)0)
893 return (auid == ROOT_UID ? 0 : -1);
899 return (agid == ROOT_GID ? 0 : -1);
906 char *buf = getlogin_buffer;
907 DWORD size = sizeof(getlogin_buffer);
908 if (GetUserName(buf,&size))
914 chown(const char *path, uid_t owner, gid_t group)
921 kill(int pid, int sig)
923 HANDLE hProcess= OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
925 if (hProcess == NULL) {
926 croak("kill process failed!\n");
929 if (!TerminateProcess(hProcess, sig))
930 croak("kill process failed!\n");
931 CloseHandle(hProcess);
940 DllExport unsigned int
941 win32_sleep(unsigned int t)
948 win32_stat(const char *path, struct stat *buffer)
951 const char *p = path;
952 int l = strlen(path);
956 switch(path[l - 1]) {
959 if (path[l - 2] != ':') {
960 strncpy(t, path, l - 1);
966 res = stat(p,buffer);
969 if (S_ISDIR(buffer->st_mode))
970 buffer->st_mode |= S_IWRITE | S_IEXEC;
971 else if (S_ISREG(buffer->st_mode)) {
972 if (l >= 4 && path[l-4] == '.') {
973 const char *e = path + l - 3;
974 if (strnicmp(e,"exe",3)
975 && strnicmp(e,"bat",3)
976 && strnicmp(e,"com",3)
977 && (IsWin95() || strnicmp(e,"cmd",3)))
978 buffer->st_mode &= ~S_IEXEC;
980 buffer->st_mode |= S_IEXEC;
983 buffer->st_mode &= ~S_IEXEC;
990 #ifndef USE_WIN32_RTL_ENV
993 win32_getenv(const char *name)
995 static char *curitem = Nullch;
996 static DWORD curlen = 512;
999 New(1305,curitem,curlen,char);
1000 if (!(needlen = GetEnvironmentVariable(name,curitem,curlen)))
1002 while (needlen > curlen) {
1003 Renew(curitem,needlen,char);
1005 needlen = GetEnvironmentVariable(name,curitem,curlen);
1007 if (curitem == NULL)
1009 if (strcmp("PERL5DB", name) == 0)
1010 curitem = GetRegStr(name, &curitem, &curlen);
1018 filetime_to_clock(PFILETIME ft)
1020 __int64 qw = ft->dwHighDateTime;
1022 qw |= ft->dwLowDateTime;
1023 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
1028 win32_times(struct tms *timebuf)
1033 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
1035 timebuf->tms_utime = filetime_to_clock(&user);
1036 timebuf->tms_stime = filetime_to_clock(&kernel);
1037 timebuf->tms_cutime = 0;
1038 timebuf->tms_cstime = 0;
1041 /* That failed - e.g. Win95 fallback to clock() */
1042 clock_t t = clock();
1043 timebuf->tms_utime = t;
1044 timebuf->tms_stime = 0;
1045 timebuf->tms_cutime = 0;
1046 timebuf->tms_cstime = 0;
1051 /* fix utime() so it works on directories in NT
1052 * thanks to Jan Dubois <jan.dubois@ibm.net>
1055 filetime_from_time(PFILETIME pFileTime, time_t Time)
1057 struct tm *pTM = gmtime(&Time);
1058 SYSTEMTIME SystemTime;
1063 SystemTime.wYear = pTM->tm_year + 1900;
1064 SystemTime.wMonth = pTM->tm_mon + 1;
1065 SystemTime.wDay = pTM->tm_mday;
1066 SystemTime.wHour = pTM->tm_hour;
1067 SystemTime.wMinute = pTM->tm_min;
1068 SystemTime.wSecond = pTM->tm_sec;
1069 SystemTime.wMilliseconds = 0;
1071 return SystemTimeToFileTime(&SystemTime, pFileTime);
1075 win32_utime(const char *filename, struct utimbuf *times)
1081 struct utimbuf TimeBuffer;
1083 int rc = utime(filename,times);
1084 /* EACCES: path specifies directory or readonly file */
1085 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
1088 if (times == NULL) {
1089 times = &TimeBuffer;
1090 time(×->actime);
1091 times->modtime = times->actime;
1094 /* This will (and should) still fail on readonly files */
1095 handle = CreateFile(filename, GENERIC_READ | GENERIC_WRITE,
1096 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1097 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1098 if (handle == INVALID_HANDLE_VALUE)
1101 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
1102 filetime_from_time(&ftAccess, times->actime) &&
1103 filetime_from_time(&ftWrite, times->modtime) &&
1104 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
1109 CloseHandle(handle);
1114 win32_wait(int *status)
1117 return wait(status);
1119 /* XXX this wait emulation only knows about processes
1120 * spawned via win32_spawnvp(P_NOWAIT, ...).
1123 DWORD exitcode, waitcode;
1125 if (!w32_num_children) {
1130 /* if a child exists, wait for it to die */
1131 waitcode = WaitForMultipleObjects(w32_num_children,
1135 if (waitcode != WAIT_FAILED) {
1136 if (waitcode >= WAIT_ABANDONED_0
1137 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1138 i = waitcode - WAIT_ABANDONED_0;
1140 i = waitcode - WAIT_OBJECT_0;
1141 if (GetExitCodeProcess(w32_child_pids[i], &exitcode) ) {
1142 CloseHandle(w32_child_pids[i]);
1143 *status = (int)((exitcode & 0xff) << 8);
1144 retval = (int)w32_child_pids[i];
1145 Copy(&w32_child_pids[i+1], &w32_child_pids[i],
1146 (w32_num_children-i-1), HANDLE);
1153 errno = GetLastError();
1159 static UINT timerid = 0;
1161 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1163 KillTimer(NULL,timerid);
1168 DllExport unsigned int
1169 win32_alarm(unsigned int sec)
1172 * the 'obvious' implentation is SetTimer() with a callback
1173 * which does whatever receiving SIGALRM would do
1174 * we cannot use SIGALRM even via raise() as it is not
1175 * one of the supported codes in <signal.h>
1177 * Snag is unless something is looking at the message queue
1178 * nothing happens :-(
1182 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1184 croak("Cannot set timer");
1190 KillTimer(NULL,timerid);
1197 #ifdef HAVE_DES_FCRYPT
1198 extern char * des_fcrypt(char *cbuf, const char *txt, const char *salt);
1201 win32_crypt(const char *txt, const char *salt)
1204 return des_fcrypt(crypt_buffer, txt, salt);
1208 #ifdef USE_FIXED_OSFHANDLE
1210 EXTERN_C int __cdecl _alloc_osfhnd(void);
1211 EXTERN_C int __cdecl _set_osfhnd(int fh, long value);
1212 EXTERN_C void __cdecl _lock_fhandle(int);
1213 EXTERN_C void __cdecl _unlock_fhandle(int);
1214 EXTERN_C void __cdecl _unlock(int);
1216 #if (_MSC_VER >= 1000)
1218 long osfhnd; /* underlying OS file HANDLE */
1219 char osfile; /* attributes of file (e.g., open in text mode?) */
1220 char pipech; /* one char buffer for handles opened on pipes */
1221 #if defined (_MT) && !defined (DLL_FOR_WIN32S)
1223 CRITICAL_SECTION lock;
1224 #endif /* defined (_MT) && !defined (DLL_FOR_WIN32S) */
1227 EXTERN_C ioinfo * __pioinfo[];
1229 #define IOINFO_L2E 5
1230 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
1231 #define _pioinfo(i) (__pioinfo[i >> IOINFO_L2E] + (i & (IOINFO_ARRAY_ELTS - 1)))
1232 #define _osfile(i) (_pioinfo(i)->osfile)
1234 #else /* (_MSC_VER >= 1000) */
1235 extern char _osfile[];
1236 #endif /* (_MSC_VER >= 1000) */
1238 #define FOPEN 0x01 /* file handle open */
1239 #define FAPPEND 0x20 /* file handle opened O_APPEND */
1240 #define FDEV 0x40 /* file handle refers to device */
1241 #define FTEXT 0x80 /* file handle is in text mode */
1243 #define _STREAM_LOCKS 26 /* Table of stream locks */
1244 #define _LAST_STREAM_LOCK (_STREAM_LOCKS+_NSTREAM_-1) /* Last stream lock */
1245 #define _FH_LOCKS (_LAST_STREAM_LOCK+1) /* Table of fh locks */
1248 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1251 * This function allocates a free C Runtime file handle and associates
1252 * it with the Win32 HANDLE specified by the first parameter. This is a
1253 * temperary fix for WIN95's brain damage GetFileType() error on socket
1254 * we just bypass that call for socket
1257 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1258 * int flags - flags to associate with C Runtime file handle.
1261 * returns index of entry in fh, if successful
1262 * return -1, if no free entry is found
1266 *******************************************************************************/
1269 my_open_osfhandle(long osfhandle, int flags)
1272 char fileflags; /* _osfile flags */
1274 /* copy relevant flags from second parameter */
1277 if (flags & O_APPEND)
1278 fileflags |= FAPPEND;
1283 /* attempt to allocate a C Runtime file handle */
1284 if ((fh = _alloc_osfhnd()) == -1) {
1285 errno = EMFILE; /* too many open files */
1286 _doserrno = 0L; /* not an OS error */
1287 return -1; /* return error to caller */
1290 /* the file is open. now, set the info in _osfhnd array */
1291 _set_osfhnd(fh, osfhandle);
1293 fileflags |= FOPEN; /* mark as open */
1295 #if (_MSC_VER >= 1000)
1296 _osfile(fh) = fileflags; /* set osfile entry */
1297 _unlock_fhandle(fh);
1299 _osfile[fh] = fileflags; /* set osfile entry */
1300 _unlock(fh+_FH_LOCKS); /* unlock handle */
1303 return fh; /* return handle */
1306 #define _open_osfhandle my_open_osfhandle
1307 #endif /* USE_FIXED_OSFHANDLE */
1309 /* simulate flock by locking a range on the file */
1311 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1312 #define LK_LEN 0xffff0000
1315 win32_flock(int fd, int oper)
1322 croak("flock() unimplemented on this platform");
1325 fh = (HANDLE)_get_osfhandle(fd);
1326 memset(&o, 0, sizeof(o));
1329 case LOCK_SH: /* shared lock */
1330 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1332 case LOCK_EX: /* exclusive lock */
1333 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1335 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1336 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1338 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1339 LK_ERR(LockFileEx(fh,
1340 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1341 0, LK_LEN, 0, &o),i);
1343 case LOCK_UN: /* unlock lock */
1344 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1346 default: /* unknown */
1357 * redirected io subsystem for all XS modules
1370 return (&(_environ));
1373 /* the rest are the remapped stdio routines */
1393 win32_ferror(FILE *fp)
1395 return (ferror(fp));
1400 win32_feof(FILE *fp)
1406 * Since the errors returned by the socket error function
1407 * WSAGetLastError() are not known by the library routine strerror
1408 * we have to roll our own.
1412 win32_strerror(int e)
1414 #ifndef __BORLANDC__ /* Borland intolerance */
1415 extern int sys_nerr;
1419 if (e < 0 || e > sys_nerr) {
1424 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
1425 strerror_buffer, sizeof(strerror_buffer), NULL) == 0)
1426 strcpy(strerror_buffer, "Unknown Error");
1428 return strerror_buffer;
1434 win32_str_os_error(void *sv, DWORD dwErr)
1438 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
1439 |FORMAT_MESSAGE_IGNORE_INSERTS
1440 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
1441 dwErr, 0, (char *)&sMsg, 1, NULL);
1443 while (0 < dwLen && isspace(sMsg[--dwLen]))
1445 if ('.' != sMsg[dwLen])
1450 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
1451 dwLen = sprintf(sMsg,
1452 "Unknown error #0x%lX (lookup 0x%lX)",
1453 dwErr, GetLastError());
1455 sv_setpvn((SV*)sv, sMsg, dwLen);
1461 win32_fprintf(FILE *fp, const char *format, ...)
1464 va_start(marker, format); /* Initialize variable arguments. */
1466 return (vfprintf(fp, format, marker));
1470 win32_printf(const char *format, ...)
1473 va_start(marker, format); /* Initialize variable arguments. */
1475 return (vprintf(format, marker));
1479 win32_vfprintf(FILE *fp, const char *format, va_list args)
1481 return (vfprintf(fp, format, args));
1485 win32_vprintf(const char *format, va_list args)
1487 return (vprintf(format, args));
1491 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
1493 return fread(buf, size, count, fp);
1497 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
1499 return fwrite(buf, size, count, fp);
1503 win32_fopen(const char *filename, const char *mode)
1505 if (stricmp(filename, "/dev/null")==0)
1506 return fopen("NUL", mode);
1507 return fopen(filename, mode);
1510 #ifndef USE_SOCKETS_AS_HANDLES
1512 #define fdopen my_fdopen
1516 win32_fdopen( int handle, const char *mode)
1518 return fdopen(handle, (char *) mode);
1522 win32_freopen( const char *path, const char *mode, FILE *stream)
1524 if (stricmp(path, "/dev/null")==0)
1525 return freopen("NUL", mode, stream);
1526 return freopen(path, mode, stream);
1530 win32_fclose(FILE *pf)
1532 return my_fclose(pf); /* defined in win32sck.c */
1536 win32_fputs(const char *s,FILE *pf)
1538 return fputs(s, pf);
1542 win32_fputc(int c,FILE *pf)
1548 win32_ungetc(int c,FILE *pf)
1550 return ungetc(c,pf);
1554 win32_getc(FILE *pf)
1560 win32_fileno(FILE *pf)
1566 win32_clearerr(FILE *pf)
1573 win32_fflush(FILE *pf)
1579 win32_ftell(FILE *pf)
1585 win32_fseek(FILE *pf,long offset,int origin)
1587 return fseek(pf, offset, origin);
1591 win32_fgetpos(FILE *pf,fpos_t *p)
1593 return fgetpos(pf, p);
1597 win32_fsetpos(FILE *pf,const fpos_t *p)
1599 return fsetpos(pf, p);
1603 win32_rewind(FILE *pf)
1623 win32_fstat(int fd,struct stat *sbufptr)
1625 return fstat(fd,sbufptr);
1629 win32_pipe(int *pfd, unsigned int size, int mode)
1631 return _pipe(pfd, size, mode);
1635 * a popen() clone that respects PERL5SHELL
1639 win32_popen(const char *command, const char *mode)
1641 #ifdef USE_CRT_POPEN
1642 return _popen(command, mode);
1650 /* establish which ends read and write */
1651 if (strchr(mode,'w')) {
1652 stdfd = 0; /* stdin */
1656 else if (strchr(mode,'r')) {
1657 stdfd = 1; /* stdout */
1664 /* set the correct mode */
1665 if (strchr(mode,'b'))
1667 else if (strchr(mode,'t'))
1670 ourmode = _fmode & (O_TEXT | O_BINARY);
1672 /* the child doesn't inherit handles */
1673 ourmode |= O_NOINHERIT;
1675 if (win32_pipe( p, 512, ourmode) == -1)
1678 /* save current stdfd */
1679 if ((oldfd = win32_dup(stdfd)) == -1)
1682 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
1683 /* stdfd will be inherited by the child */
1684 if (win32_dup2(p[child], stdfd) == -1)
1687 /* close the child end in parent */
1688 win32_close(p[child]);
1690 /* start the child */
1691 if ((childpid = do_spawn_nowait((char*)command)) == -1)
1694 /* revert stdfd to whatever it was before */
1695 if (win32_dup2(oldfd, stdfd) == -1)
1698 /* close saved handle */
1701 w32_popen_pids[p[parent]] = childpid;
1703 /* we have an fd, return a file stream */
1704 return (win32_fdopen(p[parent], (char *)mode));
1707 /* we don't need to check for errors here */
1711 win32_dup2(oldfd, stdfd);
1716 #endif /* USE_CRT_POPEN */
1724 win32_pclose(FILE *pf)
1726 #ifdef USE_CRT_POPEN
1729 int fd, childpid, status;
1731 fd = win32_fileno(pf);
1732 childpid = w32_popen_pids[fd];
1740 w32_popen_pids[fd] = 0;
1742 /* wait for the child */
1743 if (cwait(&status, childpid, WAIT_CHILD) == -1)
1745 /* cwait() returns differently on Borland */
1747 return (((status >> 8) & 0xff) | ((status << 8) & 0xff00));
1752 #endif /* USE_CRT_OPEN */
1756 win32_setmode(int fd, int mode)
1758 return setmode(fd, mode);
1762 win32_lseek(int fd, long offset, int origin)
1764 return lseek(fd, offset, origin);
1774 win32_open(const char *path, int flag, ...)
1780 pmode = va_arg(ap, int);
1783 if (stricmp(path, "/dev/null")==0)
1784 return open("NUL", flag, pmode);
1785 return open(path,flag,pmode);
1807 win32_dup2(int fd1,int fd2)
1809 return dup2(fd1,fd2);
1813 win32_read(int fd, void *buf, unsigned int cnt)
1815 return read(fd, buf, cnt);
1819 win32_write(int fd, const void *buf, unsigned int cnt)
1821 return write(fd, buf, cnt);
1825 win32_mkdir(const char *dir, int mode)
1827 return mkdir(dir); /* just ignore mode */
1831 win32_rmdir(const char *dir)
1837 win32_chdir(const char *dir)
1843 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
1847 status = spawnvp(mode, cmdname, (char * const *) argv);
1848 #ifndef __BORLANDC__
1849 /* XXX For the P_NOWAIT case, Borland RTL returns pinfo.dwProcessId
1850 * while VC RTL returns pinfo.hProcess. For purposes of the custom
1851 * implementation of win32_wait(), we assume the latter.
1853 if (mode == P_NOWAIT && status >= 0)
1854 w32_child_pids[w32_num_children++] = (HANDLE)status;
1860 win32_execvp(const char *cmdname, const char *const *argv)
1862 return execvp(cmdname, (char *const *)argv);
1866 win32_perror(const char *str)
1872 win32_setbuf(FILE *pf, char *buf)
1878 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
1880 return setvbuf(pf, buf, type, size);
1884 win32_flushall(void)
1890 win32_fcloseall(void)
1896 win32_fgets(char *s, int n, FILE *pf)
1898 return fgets(s, n, pf);
1908 win32_fgetc(FILE *pf)
1914 win32_putc(int c, FILE *pf)
1920 win32_puts(const char *s)
1932 win32_putchar(int c)
1939 #ifndef USE_PERL_SBRK
1941 static char *committed = NULL;
1942 static char *base = NULL;
1943 static char *reserved = NULL;
1944 static char *brk = NULL;
1945 static DWORD pagesize = 0;
1946 static DWORD allocsize = 0;
1954 GetSystemInfo(&info);
1955 /* Pretend page size is larger so we don't perpetually
1956 * call the OS to commit just one page ...
1958 pagesize = info.dwPageSize << 3;
1959 allocsize = info.dwAllocationGranularity;
1961 /* This scheme fails eventually if request for contiguous
1962 * block is denied so reserve big blocks - this is only
1963 * address space not memory ...
1965 if (brk+need >= reserved)
1967 DWORD size = 64*1024*1024;
1969 if (committed && reserved && committed < reserved)
1971 /* Commit last of previous chunk cannot span allocations */
1972 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
1974 committed = reserved;
1976 /* Reserve some (more) space
1977 * Note this is a little sneaky, 1st call passes NULL as reserved
1978 * so lets system choose where we start, subsequent calls pass
1979 * the old end address so ask for a contiguous block
1981 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
1984 reserved = addr+size;
1999 if (brk > committed)
2001 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
2002 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
2017 win32_malloc(size_t size)
2019 return malloc(size);
2023 win32_calloc(size_t numitems, size_t size)
2025 return calloc(numitems,size);
2029 win32_realloc(void *block, size_t size)
2031 return realloc(block,size);
2035 win32_free(void *block)
2042 win32_open_osfhandle(long handle, int flags)
2044 return _open_osfhandle(handle, flags);
2048 win32_get_osfhandle(int fd)
2050 return _get_osfhandle(fd);
2061 SV *sv = sv_newmortal();
2062 /* Make one call with zero size - return value is required size */
2063 DWORD len = GetCurrentDirectory((DWORD)0,NULL);
2064 SvUPGRADE(sv,SVt_PV);
2066 SvCUR(sv) = GetCurrentDirectory((DWORD) SvLEN(sv), SvPVX(sv));
2069 * then it worked, set PV valid,
2070 * else leave it 'undef'
2084 croak("usage: Win32::SetCurrentDirectory($cwd)");
2085 if (SetCurrentDirectory(SvPV(ST(0),na)))
2092 XS(w32_GetNextAvailDrive)
2096 char root[] = "_:\\";
2099 if (GetDriveType(root) == 1) {
2108 XS(w32_GetLastError)
2111 XSRETURN_IV(GetLastError());
2118 char *name = getlogin_buffer;
2119 DWORD size = sizeof(getlogin_buffer);
2120 if (GetUserName(name,&size)) {
2121 /* size includes NULL */
2122 ST(0) = sv_2mortal(newSVpv(name,size-1));
2132 char name[MAX_COMPUTERNAME_LENGTH+1];
2133 DWORD size = sizeof(name);
2134 if (GetComputerName(name,&size)) {
2135 /* size does NOT include NULL :-( */
2136 ST(0) = sv_2mortal(newSVpv(name,size));
2147 #ifndef HAS_NETWKSTAGETINFO
2148 /* mingw32 (and Win95) don't have NetWksta*(), so do it the old way */
2150 DWORD size = sizeof(name);
2151 if (GetUserName(name,&size)) {
2153 DWORD sidlen = sizeof(sid);
2155 DWORD dnamelen = sizeof(dname);
2157 if (LookupAccountName(NULL, name, &sid, &sidlen,
2158 dname, &dnamelen, &snu)) {
2159 XSRETURN_PV(dname); /* all that for this */
2163 /* this way is more reliable, in case user has a local account.
2164 * XXX need dynamic binding of netapi32.dll symbols or this will fail on
2165 * Win95. Probably makes more sense to move it into libwin32. */
2167 DWORD dnamelen = sizeof(dname);
2168 PWKSTA_INFO_100 pwi;
2169 if (NERR_Success == NetWkstaGetInfo(NULL, 100, (LPBYTE*)&pwi)) {
2170 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
2171 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
2172 -1, (LPSTR)dname, dnamelen, NULL, NULL);
2175 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
2176 -1, (LPSTR)dname, dnamelen, NULL, NULL);
2178 NetApiBufferFree(pwi);
2190 DWORD flags, filecomplen;
2191 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
2192 &flags, fsname, sizeof(fsname))) {
2193 if (GIMME == G_ARRAY) {
2194 XPUSHs(sv_2mortal(newSVpv(fsname,0)));
2195 XPUSHs(sv_2mortal(newSViv(flags)));
2196 XPUSHs(sv_2mortal(newSViv(filecomplen)));
2200 XSRETURN_PV(fsname);
2206 XS(w32_GetOSVersion)
2209 OSVERSIONINFO osver;
2211 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
2212 if (GetVersionEx(&osver)) {
2213 XPUSHs(newSVpv(osver.szCSDVersion, 0));
2214 XPUSHs(newSViv(osver.dwMajorVersion));
2215 XPUSHs(newSViv(osver.dwMinorVersion));
2216 XPUSHs(newSViv(osver.dwBuildNumber));
2217 XPUSHs(newSViv(osver.dwPlatformId));
2228 XSRETURN_IV(IsWinNT());
2235 XSRETURN_IV(IsWin95());
2239 XS(w32_FormatMessage)
2246 croak("usage: Win32::FormatMessage($errno)");
2248 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
2249 &source, SvIV(ST(0)), 0,
2250 msgbuf, sizeof(msgbuf)-1, NULL))
2251 XSRETURN_PV(msgbuf);
2261 PROCESS_INFORMATION stProcInfo;
2262 STARTUPINFO stStartInfo;
2263 BOOL bSuccess = FALSE;
2266 croak("usage: Win32::Spawn($cmdName, $args, $PID)");
2268 cmd = SvPV(ST(0),na);
2269 args = SvPV(ST(1), na);
2271 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
2272 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
2273 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
2274 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
2277 cmd, /* Image path */
2278 args, /* Arguments for command line */
2279 NULL, /* Default process security */
2280 NULL, /* Default thread security */
2281 FALSE, /* Must be TRUE to use std handles */
2282 NORMAL_PRIORITY_CLASS, /* No special scheduling */
2283 NULL, /* Inherit our environment block */
2284 NULL, /* Inherit our currrent directory */
2285 &stStartInfo, /* -> Startup info */
2286 &stProcInfo)) /* <- Process info (if OK) */
2288 CloseHandle(stProcInfo.hThread);/* library source code does this. */
2289 sv_setiv(ST(2), stProcInfo.dwProcessId);
2292 XSRETURN_IV(bSuccess);
2296 XS(w32_GetTickCount)
2299 XSRETURN_IV(GetTickCount());
2303 XS(w32_GetShortPathName)
2310 croak("usage: Win32::GetShortPathName($longPathName)");
2312 shortpath = sv_mortalcopy(ST(0));
2313 SvUPGRADE(shortpath, SVt_PV);
2314 /* src == target is allowed */
2316 len = GetShortPathName(SvPVX(shortpath),
2319 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
2321 SvCUR_set(shortpath,len);
2334 croak("usage: Win32::Sleep($milliseconds)");
2339 #define TMPBUFSZ 1024
2340 #define MAX_LENGTH 2048
2341 #define SUCCESSRETURNED(x) (x == ERROR_SUCCESS)
2342 #define REGRETURN(x) XSRETURN_IV(SUCCESSRETURNED(x))
2343 #define SvHKEY(index) (HKEY)((unsigned long)SvIV(index))
2344 #define SETIV(index,value) sv_setiv(ST(index), value)
2345 #define SETNV(index,value) sv_setnv(ST(index), value)
2346 #define SETPV(index,string) sv_setpv(ST(index), string)
2347 #define SETPVN(index, buffer, length) sv_setpvn(ST(index), (char*)buffer, length)
2348 #define SETHKEY(index, hkey) SETIV(index,(long)hkey)
2350 static time_t ft2timet(FILETIME *ft)
2355 FileTimeToSystemTime(ft, &st);
2356 tm.tm_sec = st.wSecond;
2357 tm.tm_min = st.wMinute;
2358 tm.tm_hour = st.wHour;
2359 tm.tm_mday = st.wDay;
2360 tm.tm_mon = st.wMonth - 1;
2361 tm.tm_year = st.wYear - 1900;
2362 tm.tm_wday = st.wDayOfWeek;
2365 return mktime (&tm);
2375 croak("usage: Win32::RegCloseKey($hkey);\n");
2378 REGRETURN(RegCloseKey(SvHKEY(ST(0))));
2382 XS(w32_RegConnectRegistry)
2389 croak("usage: Win32::RegConnectRegistry($machine, $hkey, $handle);\n");
2392 if (SUCCESSRETURNED(RegConnectRegistry((char *)SvPV(ST(0), na), SvHKEY(ST(1)), &handle)))
2401 XS(w32_RegCreateKey)
2410 croak("usage: Win32::RegCreateKey($hkey, $subkey, $handle);\n");
2413 retval = RegCreateKeyEx(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS,
2414 NULL, &handle, &disposition);
2416 if (SUCCESSRETURNED(retval))
2425 XS(w32_RegCreateKeyEx)
2429 unsigned int length;
2434 DWORD options, disposition;
2436 SECURITY_ATTRIBUTES sa, *psa;
2440 croak("usage: Win32::RegCreateKeyEx($hkey, $subkey, $reserved, $class, $options, $sam, "
2441 "$security, $handle, $disposition);\n");
2444 hkey = SvHKEY(ST(0));
2445 subkey = (char *)SvPV(ST(1), na);
2446 keyclass = (char *)SvPV(ST(3), na);
2447 options = (DWORD) ((unsigned long)SvIV(ST(4)));
2448 sam = (REGSAM) ((unsigned long)SvIV(ST(5)));
2449 psa = (SECURITY_ATTRIBUTES*)SvPV(ST(6), length);
2450 if (length != sizeof(SECURITY_ATTRIBUTES))
2453 memset(&sa, 0, sizeof(SECURITY_ATTRIBUTES));
2454 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
2457 retval = RegCreateKeyEx(hkey, subkey, 0, keyclass, options, sam,
2458 psa, &handle, &disposition);
2460 if (SUCCESSRETURNED(retval))
2463 SETPVN(6, &sa, sizeof(sa));
2466 SETIV(8,disposition);
2473 XS(w32_RegDeleteKey)
2479 croak("usage: Win32::RegDeleteKey($hkey, $subkey);\n");
2482 REGRETURN(RegDeleteKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na)));
2486 XS(w32_RegDeleteValue)
2492 croak("usage: Win32::RegDeleteValue($hkey, $valname);\n");
2495 REGRETURN(RegDeleteValue(SvHKEY(ST(0)), (char *)SvPV(ST(1), na)));
2503 char keybuffer[TMPBUFSZ];
2507 croak("usage: Win32::RegEnumKey($hkey, $idx, $subkeyname);\n");
2510 if (SUCCESSRETURNED(RegEnumKey(SvHKEY(ST(0)), SvIV(ST(1)), keybuffer, sizeof(keybuffer))))
2512 SETPV(2, keybuffer);
2519 XS(w32_RegEnumKeyEx)
2524 DWORD keysz, classsz;
2525 char keybuffer[TMPBUFSZ];
2526 char classbuffer[TMPBUFSZ];
2532 croak("usage: Win32::RegEnumKeyEx($hkey, $idx, $subkeyname, $reserved, $class, $time);\n");
2535 keysz = sizeof(keybuffer);
2536 classsz = sizeof(classbuffer);
2537 retval = RegEnumKeyEx(SvHKEY(ST(0)), SvIV(ST(1)), keybuffer, &keysz, 0,
2538 classbuffer, &classsz, &filetime);
2539 if (SUCCESSRETURNED(retval))
2541 SETPV(2, keybuffer);
2542 SETPV(4, classbuffer);
2543 SETIV(5, ft2timet(&filetime));
2550 XS(w32_RegEnumValue)
2554 DWORD type, namesz, valsz;
2556 static HKEY last_hkey;
2557 char myvalbuf[MAX_LENGTH];
2558 char mynambuf[MAX_LENGTH];
2562 croak("usage: Win32::RegEnumValue($hkey, $i, $name, $reserved, $type, $value);\n");
2565 hkey = SvHKEY(ST(0));
2567 // If this is a new key, find out how big the maximum name and value sizes are and
2568 // allocate space for them. Free any old storage and set the old key value to the
2571 if (hkey != (HKEY)last_hkey)
2573 char keyclass[TMPBUFSZ];
2574 DWORD classsz, subkeys, maxsubkey, maxclass, values, salen, maxnamesz, maxvalsz;
2576 classsz = sizeof(keyclass);
2577 retval = RegQueryInfoKey(hkey, keyclass, &classsz, 0, &subkeys, &maxsubkey, &maxclass,
2578 &values, &maxnamesz, &maxvalsz, &salen, &ft);
2580 if (!SUCCESSRETURNED(retval))
2584 memset(myvalbuf, 0, MAX_LENGTH);
2585 memset(mynambuf, 0, MAX_LENGTH);
2589 namesz = MAX_LENGTH;
2591 retval = RegEnumValue(hkey, SvIV(ST(1)), mynambuf, &namesz, 0, &type, (LPBYTE) myvalbuf, &valsz);
2592 if (!SUCCESSRETURNED(retval))
2601 // return includes the null terminator so delete it if REG_SZ, REG_MULTI_SZ or REG_EXPAND_SZ
2610 SETPVN(5, myvalbuf, valsz);
2613 case REG_DWORD_BIG_ENDIAN:
2615 BYTE tmp = myvalbuf[0];
2616 myvalbuf[0] = myvalbuf[3];
2619 myvalbuf[1] = myvalbuf[2];
2622 case REG_DWORD_LITTLE_ENDIAN: // same as REG_DWORD
2623 SETNV(5, (double)*((DWORD*)myvalbuf));
2641 croak("usage: Win32::RegFlushKey($hkey);\n");
2644 REGRETURN(RegFlushKey(SvHKEY(ST(0))));
2648 XS(w32_RegGetKeySecurity)
2651 SECURITY_DESCRIPTOR sd;
2656 croak("usage: Win32::RegGetKeySecurity($hkey, $security_info, $security_descriptor);\n");
2659 if (SUCCESSRETURNED(RegGetKeySecurity(SvHKEY(ST(0)), SvIV(ST(1)), &sd, &sdsz)))
2661 SETPVN(2, &sd, sdsz);
2674 croak("usage: Win32::RegLoadKey($hkey, $subkey, $filename);\n");
2677 REGRETURN(RegLoadKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), (char *)SvPV(ST(2), na)));
2681 XS(w32_RegNotifyChangeKeyValue)
2683 croak("Win32::RegNotifyChangeKeyValue not yet implemented!\n");
2694 croak("usage: Win32::RegOpenKey($hkey, $subkey, $handle);\n");
2697 if (SUCCESSRETURNED(RegOpenKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), &handle)))
2706 XS(w32_RegOpenKeyEx)
2713 croak("usage: Win32::RegOpenKeyEx($hkey, $subkey, $reserved, $sam, $handle);\n");
2716 if (SUCCESSRETURNED(RegOpenKeyEx(SvHKEY(ST(0)), (char *)SvPV(ST(1), na),
2717 0, (REGSAM) ((unsigned long)SvIV(ST(3))), &handle)))
2725 #pragma optimize("", off)
2727 XS(w32_RegQueryInfoKey)
2732 char keyclass[TMPBUFSZ];
2733 DWORD subkeys, maxsubkey, maxclass, values, maxvalname, maxvaldata;
2734 DWORD seclen, classsz;
2740 croak("usage: Win32::RegQueryInfoKey($hkey, $class, $numsubkeys, $maxsubkey,"
2741 "$maxclass, $values, $maxvalname, $maxvaldata, $secdesclen,"
2742 "$lastwritetime);\n");
2745 classsz = sizeof(keyclass);
2746 retval = RegQueryInfoKey(SvHKEY(ST(0)), keyclass, &classsz, 0, &subkeys, &maxsubkey,
2747 &maxclass, &values, &maxvalname, &maxvaldata,
2749 if (SUCCESSRETURNED(retval))
2753 SETIV(3, maxsubkey);
2756 SETIV(6, maxvalname);
2757 SETIV(7, maxvaldata);
2759 SETIV(9, ft2timet(&ft));
2764 #pragma optimize("", on)
2767 XS(w32_RegQueryValue)
2771 unsigned char databuffer[TMPBUFSZ*2];
2772 long datasz = sizeof(databuffer);
2776 croak("usage: Win32::RegQueryValue($hkey, $valuename, $data);\n");
2779 if (SUCCESSRETURNED(RegQueryValue(SvHKEY(ST(0)), SvPV(ST(1), na), (char*)databuffer, &datasz)))
2781 // return includes the null terminator so delete it
2782 SETPVN(2, databuffer, --datasz);
2789 XS(w32_RegQueryValueEx)
2793 unsigned char databuffer[TMPBUFSZ*2];
2794 DWORD datasz = sizeof(databuffer);
2797 LPBYTE ptr = databuffer;
2801 croak("usage: Win32::RegQueryValueEx($hkey, $valuename, $reserved, $type, $data);\n");
2804 result = RegQueryValueEx(SvHKEY(ST(0)), SvPV(ST(1), na), 0, &type, ptr, &datasz);
2805 if (result == ERROR_MORE_DATA)
2807 New(0, ptr, datasz+1, BYTE);
2808 result = RegQueryValueEx(SvHKEY(ST(0)), SvPV(ST(1), na), 0, &type, ptr, &datasz);
2810 if (SUCCESSRETURNED(result))
2814 // return includes the null terminator so delete it if REG_SZ, REG_MULTI_SZ or REG_EXPAND_SZ
2822 SETPVN(4, ptr, datasz);
2825 case REG_DWORD_BIG_ENDIAN:
2834 case REG_DWORD_LITTLE_ENDIAN: // same as REG_DWORD
2835 SETNV(4, (double)*((DWORD*)ptr));
2842 if (ptr != databuffer)
2847 if (ptr != databuffer)
2854 XS(w32_RegReplaceKey)
2860 croak("usage: Win32::RegReplaceKey($hkey, $subkey, $newfile, $oldfile);\n");
2863 REGRETURN(RegReplaceKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), (char *)SvPV(ST(2), na), (char *)SvPV(ST(3), na)));
2867 XS(w32_RegRestoreKey)
2871 if (items < 2 || items > 3)
2873 croak("usage: Win32::RegRestoreKey($hkey, $filename [, $flags]);\n");
2876 REGRETURN(RegRestoreKey(SvHKEY(ST(0)), (char*)SvPV(ST(1), na), (DWORD)((items == 3) ? SvIV(ST(2)) : 0)));
2886 croak("usage: Win32::RegSaveKey($hkey, $filename);\n");
2889 REGRETURN(RegSaveKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), NULL));
2893 XS(w32_RegSetKeySecurity)
2899 croak("usage: Win32::RegSetKeySecurity($hkey, $security_info, $security_descriptor);\n");
2902 REGRETURN(RegSetKeySecurity(SvHKEY(ST(0)), SvIV(ST(1)), (SECURITY_DESCRIPTOR*)SvPV(ST(2), na)));
2916 croak("usage: Win32::RegSetValue($hkey, $subKey, $type, $data);\n");
2920 if (type != REG_SZ && type != REG_EXPAND_SZ)
2922 croak("Win32::RegSetValue: Type was not REG_SZ or REG_EXPAND_SZ, cannot set %s\n", (char *)SvPV(ST(1), na));
2925 buffer = (char *)SvPV(ST(3), size);
2926 REGRETURN(RegSetValue(SvHKEY(ST(0)), SvPV(ST(1), na), REG_SZ, buffer, size));
2930 XS(w32_RegSetValueEx)
2941 croak("usage: Win32::RegSetValueEx($hkey, $valname, $reserved, $type, $data);\n");
2944 type = (DWORD)SvIV(ST(3));
2951 buffer = (char *)SvPV(ST(4), size);
2952 if (type != REG_BINARY)
2953 size++; // include null terminator in size
2955 REGRETURN(RegSetValueEx(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), 0, type, (PBYTE) buffer, size));
2958 case REG_DWORD_BIG_ENDIAN:
2959 case REG_DWORD_LITTLE_ENDIAN: // Same as REG_DWORD
2960 val = (DWORD)SvIV(ST(4));
2961 REGRETURN(RegSetValueEx(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), 0, type, (PBYTE) &val, sizeof(DWORD)));
2965 croak("Win32::RegSetValueEx: Type not specified, cannot set %s\n", (char *)SvPV(ST(1), na));
2970 XS(w32_RegUnloadKey)
2976 croak("usage: Win32::RegUnLoadKey($hkey, $subkey);\n");
2979 REGRETURN(RegUnLoadKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na)));
2983 XS(w32_RegisterServer)
2986 BOOL bSuccess = FALSE;
2987 HINSTANCE hInstance;
2988 unsigned int length;
2993 croak("usage: Win32::RegisterServer($LibraryName)\n");
2996 hInstance = LoadLibrary((char *)SvPV(ST(0), length));
2997 if (hInstance != NULL)
2999 sFunc = GetProcAddress(hInstance, "DllRegisterServer");
3002 bSuccess = (sFunc() == 0);
3004 FreeLibrary(hInstance);
3015 XS(w32_UnregisterServer)
3018 BOOL bSuccess = FALSE;
3019 HINSTANCE hInstance;
3020 unsigned int length;
3025 croak("usage: Win32::UnregisterServer($LibraryName)\n");
3028 hInstance = LoadLibrary((char *)SvPV(ST(0), length));
3029 if (hInstance != NULL)
3031 sFunc = GetProcAddress(hInstance, "DllUnregisterServer");
3034 bSuccess = (sFunc() == 0);
3036 FreeLibrary(hInstance);
3048 Perl_init_os_extras()
3050 char *file = __FILE__;
3053 /* these names are Activeware compatible */
3054 newXS("Win32::GetCwd", w32_GetCwd, file);
3055 newXS("Win32::SetCwd", w32_SetCwd, file);
3056 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
3057 newXS("Win32::GetLastError", w32_GetLastError, file);
3058 newXS("Win32::LoginName", w32_LoginName, file);
3059 newXS("Win32::NodeName", w32_NodeName, file);
3060 newXS("Win32::DomainName", w32_DomainName, file);
3061 newXS("Win32::FsType", w32_FsType, file);
3062 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
3063 newXS("Win32::IsWinNT", w32_IsWinNT, file);
3064 newXS("Win32::IsWin95", w32_IsWin95, file);
3065 newXS("Win32::FormatMessage", w32_FormatMessage, file);
3066 newXS("Win32::Spawn", w32_Spawn, file);
3067 newXS("Win32::GetTickCount", w32_GetTickCount, file);
3068 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
3069 newXS("Win32::Sleep", w32_Sleep, file);
3071 /* the following extensions are used interally and may be changed at any time */
3072 /* therefore no documentation is provided */
3073 newXS("Win32::RegCloseKey", w32_RegCloseKey, file);
3074 newXS("Win32::RegConnectRegistry", w32_RegConnectRegistry, file);
3075 newXS("Win32::RegCreateKey", w32_RegCreateKey, file);
3076 newXS("Win32::RegCreateKeyEx", w32_RegCreateKeyEx, file);
3077 newXS("Win32::RegDeleteKey", w32_RegDeleteKey, file);
3078 newXS("Win32::RegDeleteValue", w32_RegDeleteValue, file);
3080 newXS("Win32::RegEnumKey", w32_RegEnumKey, file);
3081 newXS("Win32::RegEnumKeyEx", w32_RegEnumKeyEx, file);
3082 newXS("Win32::RegEnumValue", w32_RegEnumValue, file);
3084 newXS("Win32::RegFlushKey", w32_RegFlushKey, file);
3085 newXS("Win32::RegGetKeySecurity", w32_RegGetKeySecurity, file);
3087 newXS("Win32::RegLoadKey", w32_RegLoadKey, file);
3088 newXS("Win32::RegOpenKey", w32_RegOpenKey, file);
3089 newXS("Win32::RegOpenKeyEx", w32_RegOpenKeyEx, file);
3090 newXS("Win32::RegQueryInfoKey", w32_RegQueryInfoKey, file);
3091 newXS("Win32::RegQueryValue", w32_RegQueryValue, file);
3092 newXS("Win32::RegQueryValueEx", w32_RegQueryValueEx, file);
3094 newXS("Win32::RegReplaceKey", w32_RegReplaceKey, file);
3095 newXS("Win32::RegRestoreKey", w32_RegRestoreKey, file);
3096 newXS("Win32::RegSaveKey", w32_RegSaveKey, file);
3097 newXS("Win32::RegSetKeySecurity", w32_RegSetKeySecurity, file);
3098 newXS("Win32::RegSetValue", w32_RegSetValue, file);
3099 newXS("Win32::RegSetValueEx", w32_RegSetValueEx, file);
3100 newXS("Win32::RegUnloadKey", w32_RegUnloadKey, file);
3102 newXS("Win32::RegisterServer", w32_RegisterServer, file);
3103 newXS("Win32::UnregisterServer", w32_UnregisterServer, file);
3105 /* XXX Bloat Alert! The following Activeware preloads really
3106 * ought to be part of Win32::Sys::*, so they're not included
3109 /* LookupAccountName
3111 * InitiateSystemShutdown
3112 * AbortSystemShutdown
3113 * ExpandEnvrironmentStrings
3118 Perl_win32_init(int *argcp, char ***argvp)
3120 /* Disable floating point errors, Perl will trap the ones we
3121 * care about. VC++ RTL defaults to switching these off
3122 * already, but the Borland RTL doesn't. Since we don't
3123 * want to be at the vendor's whim on the default, we set
3124 * it explicitly here.
3126 #if !defined(_ALPHA_) && !defined(__GNUC__)
3127 _control87(MCW_EM, MCW_EM);
3132 #ifdef USE_BINMODE_SCRIPTS
3135 win32_strip_return(SV *sv)
3137 char *s = SvPVX(sv);
3138 char *e = s+SvCUR(sv);
3142 if (*s == '\r' && s[1] == '\n')
3152 SvCUR_set(sv,d-SvPVX(sv));