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_get_stdlib
69 #define win32_get_stdlib g_win32_get_stdlib
70 #undef win32_get_sitelib
71 #define win32_get_sitelib g_win32_get_sitelib
73 #define do_aspawn g_do_aspawn
75 #define do_spawn g_do_spawn
77 #define do_exec g_do_exec
79 #define opendir g_opendir
81 #define readdir g_readdir
83 #define telldir g_telldir
85 #define seekdir g_seekdir
87 #define rewinddir g_rewinddir
89 #define closedir g_closedir
91 #define getlogin g_getlogin
94 static DWORD os_id(void);
95 static void get_shell(void);
96 static long tokenize(char *str, char **dest, char ***destv);
97 int do_spawn2(char *cmd, int exectype);
98 static BOOL has_redirection(char *ptr);
99 static long filetime_to_clock(PFILETIME ft);
100 static BOOL filetime_from_time(PFILETIME ft, time_t t);
103 char * w32_perlshell_tokens = Nullch;
104 char ** w32_perlshell_vec;
105 long w32_perlshell_items = -1;
106 DWORD w32_platform = (DWORD)-1;
107 char w32_perllib_root[MAX_PATH+1];
108 HANDLE w32_perldll_handle = INVALID_HANDLE_VALUE;
110 long w32_num_children = 0;
111 HANDLE w32_child_pids[MAXIMUM_WAIT_OBJECTS];
116 # define FOPEN_MAX _NSTREAM_
118 # define FOPEN_MAX _NFILE_
120 # define FOPEN_MAX _NFILE
124 #ifndef USE_CRT_POPEN
125 int w32_popen_pids[FOPEN_MAX];
129 # ifdef USE_DECLSPEC_THREAD
130 __declspec(thread) char strerror_buffer[512];
131 __declspec(thread) char getlogin_buffer[128];
132 # ifdef HAVE_DES_FCRYPT
133 __declspec(thread) char crypt_buffer[30];
136 # define strerror_buffer (thr->i.Wstrerror_buffer)
137 # define getlogin_buffer (thr->i.Wgetlogin_buffer)
138 # define crypt_buffer (thr->i.Wcrypt_buffer)
141 char strerror_buffer[512];
142 char getlogin_buffer[128];
143 # ifdef HAVE_DES_FCRYPT
144 char crypt_buffer[30];
150 return (os_id() == VER_PLATFORM_WIN32_WINDOWS);
155 return (os_id() == VER_PLATFORM_WIN32_NT);
159 GetRegStrFromKey(HKEY hkey, const char *lpszValueName, char** ptr, DWORD* lpDataLen)
160 { /* Retrieve a REG_SZ or REG_EXPAND_SZ from the registry */
163 const char *subkey = "Software\\Perl";
166 retval = RegOpenKeyEx(hkey, subkey, 0, KEY_READ, &handle);
167 if(retval == ERROR_SUCCESS){
168 retval = RegQueryValueEx(handle, lpszValueName, 0, &type, NULL, lpDataLen);
169 if(retval == ERROR_SUCCESS && type == REG_SZ) {
171 Renew(*ptr, *lpDataLen, char);
174 New(1312, *ptr, *lpDataLen, char);
176 retval = RegQueryValueEx(handle, lpszValueName, 0, NULL, (PBYTE)*ptr, lpDataLen);
177 if(retval != ERROR_SUCCESS) {
188 GetRegStr(const char *lpszValueName, char** ptr, DWORD* lpDataLen)
190 *ptr = GetRegStrFromKey(HKEY_CURRENT_USER, lpszValueName, ptr, lpDataLen);
193 *ptr = GetRegStrFromKey(HKEY_LOCAL_MACHINE, lpszValueName, ptr, lpDataLen);
199 win32_get_stdlib(char *pl)
201 static char szStdLib[] = "lib";
202 int len = 0, newSize;
203 char szBuffer[MAX_PATH+1];
204 char szModuleName[MAX_PATH];
210 /* $stdlib = $HKCU{"lib-$]"} || $HKLM{"lib-$]"} || $HKCU{"lib"} || $HKLM{"lib"} || ""; */
211 sprintf(szBuffer, "%s-%s", szStdLib, pl);
212 lpPath = GetRegStr(szBuffer, &lpPath, &dwDataLen);
214 lpPath = GetRegStr(szStdLib, &lpPath, &dwDataLen);
216 /* $stdlib .= ";$EMD/../../lib" */
217 GetModuleFileName(GetModuleHandle(NULL), szModuleName, sizeof(szModuleName));
218 ptr = strrchr(szModuleName, '\\');
222 ptr = strrchr(szModuleName, '\\');
226 ptr = strrchr(szModuleName, '\\');
234 strcpy(++ptr, szStdLib);
236 /* check that this path exists */
237 GetCurrentDirectory(sizeof(szBuffer), szBuffer);
238 result = SetCurrentDirectory(szModuleName);
239 SetCurrentDirectory(szBuffer);
242 GetModuleFileName(GetModuleHandle(NULL), szModuleName, sizeof(szModuleName));
243 ptr = strrchr(szModuleName, '\\');
245 strcpy(++ptr, szStdLib);
248 newSize = strlen(szModuleName) + 1;
251 len = strlen(lpPath);
252 newSize += len + 1; /* plus 1 for ';' */
253 lpPath = Renew(lpPath, newSize, char);
256 New(1310, lpPath, newSize, char);
262 strcpy(&lpPath[len], szModuleName);
268 get_sitelib_part(char* lpRegStr, char* lpPathStr)
270 char szBuffer[MAX_PATH+1];
271 char szModuleName[MAX_PATH];
278 lpPath = GetRegStr(lpRegStr, &lpPath, &dwDataLen);
280 /* $sitelib .= ";$EMD/../../../<lpPathStr>" */
281 GetModuleFileName(GetModuleHandle(NULL), szModuleName, sizeof(szModuleName));
282 ptr = strrchr(szModuleName, '\\');
286 ptr = strrchr(szModuleName, '\\');
290 ptr = strrchr(szModuleName, '\\');
294 ptr = strrchr(szModuleName, '\\');
303 strcpy(++ptr, lpPathStr);
305 /* check that this path exists */
306 GetCurrentDirectory(sizeof(szBuffer), szBuffer);
307 result = SetCurrentDirectory(szModuleName);
308 SetCurrentDirectory(szBuffer);
312 int newSize = strlen(szModuleName) + 1;
315 len = strlen(lpPath);
316 newSize += len + 1; /* plus 1 for ';' */
317 lpPath = Renew(lpPath, newSize, char);
320 New(1311, lpPath, newSize, char);
326 strcpy(&lpPath[len], szModuleName);
333 win32_get_sitelib(char *pl)
335 static char szSiteLib[] = "sitelib";
337 char szPathStr[MAX_PATH];
341 /* $HKCU{"sitelib-$]"} || $HKLM{"sitelib-$]"} . ---; */
342 sprintf(szRegStr, "%s-%s", szSiteLib, pl);
343 sprintf(szPathStr, "site\\%s\\lib", pl);
344 lpPath1 = get_sitelib_part(szRegStr, szPathStr);
346 /* $HKCU{'sitelib'} || $HKLM{'sitelib'} . ---; */
347 lpPath2 = get_sitelib_part(szSiteLib, "site\\lib");
354 int len = strlen(lpPath1);
355 int newSize = len + strlen(lpPath2) + 2; /* plus one for ';' */
357 lpPath1 = Renew(lpPath1, newSize, char);
360 lpPath1[len++] = ';';
361 strcpy(&lpPath1[len], lpPath2);
369 has_redirection(char *ptr)
375 * Scan string looking for redirection (< or >) or pipe
376 * characters (|) that are not in a quoted string
406 #if !defined(PERL_OBJECT)
407 /* since the current process environment is being updated in util.c
408 * the library functions will get the correct environment
411 my_popen(char *cmd, char *mode)
414 #define fixcmd(x) { \
415 char *pspace = strchr((x),' '); \
418 while (p < pspace) { \
429 win32_fflush(stdout);
430 win32_fflush(stderr);
431 return win32_popen(cmd, mode);
435 my_pclose(PerlIO *fp)
437 return win32_pclose(fp);
444 static OSVERSIONINFO osver;
446 if (osver.dwPlatformId != w32_platform) {
447 memset(&osver, 0, sizeof(OSVERSIONINFO));
448 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
449 GetVersionEx(&osver);
450 w32_platform = osver.dwPlatformId;
452 return (w32_platform);
455 /* Tokenize a string. Words are null-separated, and the list
456 * ends with a doubled null. Any character (except null and
457 * including backslash) may be escaped by preceding it with a
458 * backslash (the backslash will be stripped).
459 * Returns number of words in result buffer.
462 tokenize(char *str, char **dest, char ***destv)
464 char *retstart = Nullch;
465 char **retvstart = 0;
468 int slen = strlen(str);
470 register char **retv;
471 New(1307, ret, slen+2, char);
472 New(1308, retv, (slen+3)/2, char*);
480 if (*ret == '\\' && *str)
482 else if (*ret == ' ') {
498 retvstart[items] = Nullch;
510 if (!w32_perlshell_tokens) {
511 /* we don't use COMSPEC here for two reasons:
512 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
513 * uncontrolled unportability of the ensuing scripts.
514 * 2. PERL5SHELL could be set to a shell that may not be fit for
515 * interactive use (which is what most programs look in COMSPEC
518 char* defaultshell = (IsWinNT() ? "cmd.exe /x/c" : "command.com /c");
519 char *usershell = getenv("PERL5SHELL");
520 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
521 &w32_perlshell_tokens,
527 do_aspawn(void *vreally, void **vmark, void **vsp)
529 SV *really = (SV*)vreally;
530 SV **mark = (SV**)vmark;
542 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
544 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
549 while(++mark <= sp) {
550 if (*mark && (str = SvPV(*mark, na)))
557 status = win32_spawnvp(flag,
558 (const char*)(really ? SvPV(really,na) : argv[0]),
559 (const char* const*)argv);
561 if (status < 0 && errno == ENOEXEC) {
562 /* possible shell-builtin, invoke with shell */
564 sh_items = w32_perlshell_items;
566 argv[index+sh_items] = argv[index];
567 while (--sh_items >= 0)
568 argv[sh_items] = w32_perlshell_vec[sh_items];
570 status = win32_spawnvp(flag,
571 (const char*)(really ? SvPV(really,na) : argv[0]),
572 (const char* const*)argv);
575 if (flag != P_NOWAIT) {
578 warn("Can't spawn \"%s\": %s", argv[0], strerror(errno));
583 statusvalue = status;
590 do_spawn2(char *cmd, int exectype)
596 BOOL needToTry = TRUE;
599 /* Save an extra exec if possible. See if there are shell
600 * metacharacters in it */
601 if(!has_redirection(cmd)) {
602 New(1301,argv, strlen(cmd) / 2 + 2, char*);
603 New(1302,cmd2, strlen(cmd) + 1, char);
606 for (s = cmd2; *s;) {
607 while (*s && isspace(*s))
611 while(*s && !isspace(*s))
620 status = win32_spawnvp(P_WAIT, argv[0],
621 (const char* const*)argv);
623 case EXECF_SPAWN_NOWAIT:
624 status = win32_spawnvp(P_NOWAIT, argv[0],
625 (const char* const*)argv);
628 status = win32_execvp(argv[0], (const char* const*)argv);
631 if (status != -1 || errno == 0)
641 New(1306, argv, w32_perlshell_items + 2, char*);
642 while (++i < w32_perlshell_items)
643 argv[i] = w32_perlshell_vec[i];
648 status = win32_spawnvp(P_WAIT, argv[0],
649 (const char* const*)argv);
651 case EXECF_SPAWN_NOWAIT:
652 status = win32_spawnvp(P_NOWAIT, argv[0],
653 (const char* const*)argv);
656 status = win32_execvp(argv[0], (const char* const*)argv);
662 if (exectype != EXECF_SPAWN_NOWAIT) {
665 warn("Can't %s \"%s\": %s",
666 (exectype == EXECF_EXEC ? "exec" : "spawn"),
667 cmd, strerror(errno));
672 statusvalue = status;
680 return do_spawn2(cmd, EXECF_SPAWN);
684 do_spawn_nowait(char *cmd)
686 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
692 do_spawn2(cmd, EXECF_EXEC);
699 /* The idea here is to read all the directory names into a string table
700 * (separated by nulls) and when one of the other dir functions is called
701 * return the pointer to the current file name.
704 opendir(char *filename)
709 char scannamespc[PATHLEN];
710 char *scanname = scannamespc;
712 WIN32_FIND_DATA FindData;
714 /* char root[_MAX_PATH];*/
715 /* char volname[_MAX_PATH];*/
716 /* DWORD serial, maxname, flags;*/
720 /* check to see if filename is a directory */
721 if (win32_stat(filename, &sbuf) < 0 || (sbuf.st_mode & S_IFDIR) == 0) {
722 /* CRT is buggy on sharenames, so make sure it really isn't */
723 DWORD r = GetFileAttributes(filename);
724 if (r == 0xffffffff || !(r & FILE_ATTRIBUTE_DIRECTORY))
728 /* get the file system characteristics */
729 /* if(GetFullPathName(filename, MAX_PATH, root, &dummy)) {
730 * if(dummy = strchr(root, '\\'))
732 * if(GetVolumeInformation(root, volname, MAX_PATH, &serial,
733 * &maxname, &flags, 0, 0)) {
734 * downcase = !(flags & FS_CASE_IS_PRESERVED);
741 /* Get us a DIR structure */
742 Newz(1303, p, 1, DIR);
746 /* Create the search pattern */
747 strcpy(scanname, filename);
749 if(index("/\\", *(scanname + strlen(scanname) - 1)) == NULL)
750 strcat(scanname, "/*");
752 strcat(scanname, "*");
754 /* do the FindFirstFile call */
755 fh = FindFirstFile(scanname, &FindData);
756 if(fh == INVALID_HANDLE_VALUE) {
760 /* now allocate the first part of the string table for
761 * the filenames that we find.
763 idx = strlen(FindData.cFileName)+1;
764 New(1304, p->start, idx, char);
765 if(p->start == NULL) {
766 croak("opendir: malloc failed!\n");
768 strcpy(p->start, FindData.cFileName);
774 /* loop finding all the files that match the wildcard
775 * (which should be all of them in this directory!).
776 * the variable idx should point one past the null terminator
777 * of the previous string found.
779 while (FindNextFile(fh, &FindData)) {
780 len = strlen(FindData.cFileName);
781 /* bump the string table size by enough for the
782 * new name and it's null terminator
784 Renew(p->start, idx+len+1, char);
785 if(p->start == NULL) {
786 croak("opendir: malloc failed!\n");
788 strcpy(&p->start[idx], FindData.cFileName);
790 * strlwr(&p->start[idx]);
802 /* Readdir just returns the current string pointer and bumps the
803 * string pointer to the nDllExport entry.
809 static int dummy = 0;
812 /* first set up the structure to return */
813 len = strlen(dirp->curr);
814 strcpy(dirp->dirstr.d_name, dirp->curr);
815 dirp->dirstr.d_namlen = len;
818 dirp->dirstr.d_ino = dummy++;
820 /* Now set up for the nDllExport call to readdir */
821 dirp->curr += len + 1;
822 if (dirp->curr >= (dirp->start + dirp->size)) {
826 return &(dirp->dirstr);
832 /* Telldir returns the current string pointer position */
836 return (long) dirp->curr;
840 /* Seekdir moves the string pointer to a previously saved position
844 seekdir(DIR *dirp, long loc)
846 dirp->curr = (char *)loc;
849 /* Rewinddir resets the string pointer to the start */
853 dirp->curr = dirp->start;
856 /* free the memory allocated by opendir */
860 Safefree(dirp->start);
873 * Just pretend that everyone is a superuser. NT will let us know if
874 * we don\'t really have permission to do something.
877 #define ROOT_UID ((uid_t)0)
878 #define ROOT_GID ((gid_t)0)
907 return (auid == ROOT_UID ? 0 : -1);
913 return (agid == ROOT_GID ? 0 : -1);
920 char *buf = getlogin_buffer;
921 DWORD size = sizeof(getlogin_buffer);
922 if (GetUserName(buf,&size))
928 chown(const char *path, uid_t owner, gid_t group)
935 kill(int pid, int sig)
937 HANDLE hProcess= OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
939 if (hProcess == NULL) {
940 croak("kill process failed!\n");
943 if (!TerminateProcess(hProcess, sig))
944 croak("kill process failed!\n");
945 CloseHandle(hProcess);
954 DllExport unsigned int
955 win32_sleep(unsigned int t)
962 win32_stat(const char *path, struct stat *buffer)
965 const char *p = path;
966 int l = strlen(path);
970 switch(path[l - 1]) {
973 if (path[l - 2] != ':') {
974 strncpy(t, path, l - 1);
980 res = stat(p,buffer);
983 if (S_ISDIR(buffer->st_mode))
984 buffer->st_mode |= S_IWRITE | S_IEXEC;
985 else if (S_ISREG(buffer->st_mode)) {
986 if (l >= 4 && path[l-4] == '.') {
987 const char *e = path + l - 3;
988 if (strnicmp(e,"exe",3)
989 && strnicmp(e,"bat",3)
990 && strnicmp(e,"com",3)
991 && (IsWin95() || strnicmp(e,"cmd",3)))
992 buffer->st_mode &= ~S_IEXEC;
994 buffer->st_mode |= S_IEXEC;
997 buffer->st_mode &= ~S_IEXEC;
1004 #ifndef USE_WIN32_RTL_ENV
1007 win32_getenv(const char *name)
1009 static char *curitem = Nullch;
1010 static DWORD curlen = 512;
1013 New(1305,curitem,curlen,char);
1014 if (!(needlen = GetEnvironmentVariable(name,curitem,curlen)))
1016 while (needlen > curlen) {
1017 Renew(curitem,needlen,char);
1019 needlen = GetEnvironmentVariable(name,curitem,curlen);
1023 if(strcmp("PERL5DB", name) == 0)
1024 curitem = GetRegStr(name, &curitem, &curlen);
1032 filetime_to_clock(PFILETIME ft)
1034 __int64 qw = ft->dwHighDateTime;
1036 qw |= ft->dwLowDateTime;
1037 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
1042 win32_times(struct tms *timebuf)
1047 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
1049 timebuf->tms_utime = filetime_to_clock(&user);
1050 timebuf->tms_stime = filetime_to_clock(&kernel);
1051 timebuf->tms_cutime = 0;
1052 timebuf->tms_cstime = 0;
1055 /* That failed - e.g. Win95 fallback to clock() */
1056 clock_t t = clock();
1057 timebuf->tms_utime = t;
1058 timebuf->tms_stime = 0;
1059 timebuf->tms_cutime = 0;
1060 timebuf->tms_cstime = 0;
1065 /* fix utime() so it works on directories in NT
1066 * thanks to Jan Dubois <jan.dubois@ibm.net>
1069 filetime_from_time(PFILETIME pFileTime, time_t Time)
1071 struct tm *pTM = gmtime(&Time);
1072 SYSTEMTIME SystemTime;
1077 SystemTime.wYear = pTM->tm_year + 1900;
1078 SystemTime.wMonth = pTM->tm_mon + 1;
1079 SystemTime.wDay = pTM->tm_mday;
1080 SystemTime.wHour = pTM->tm_hour;
1081 SystemTime.wMinute = pTM->tm_min;
1082 SystemTime.wSecond = pTM->tm_sec;
1083 SystemTime.wMilliseconds = 0;
1085 return SystemTimeToFileTime(&SystemTime, pFileTime);
1089 win32_utime(const char *filename, struct utimbuf *times)
1095 struct utimbuf TimeBuffer;
1097 int rc = utime(filename,times);
1098 /* EACCES: path specifies directory or readonly file */
1099 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
1102 if (times == NULL) {
1103 times = &TimeBuffer;
1104 time(×->actime);
1105 times->modtime = times->actime;
1108 /* This will (and should) still fail on readonly files */
1109 handle = CreateFile(filename, GENERIC_READ | GENERIC_WRITE,
1110 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1111 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1112 if (handle == INVALID_HANDLE_VALUE)
1115 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
1116 filetime_from_time(&ftAccess, times->actime) &&
1117 filetime_from_time(&ftWrite, times->modtime) &&
1118 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
1123 CloseHandle(handle);
1128 win32_wait(int *status)
1131 return wait(status);
1133 /* XXX this wait emulation only knows about processes
1134 * spawned via win32_spawnvp(P_NOWAIT, ...).
1137 DWORD exitcode, waitcode;
1139 if (!w32_num_children) {
1144 /* if a child exists, wait for it to die */
1145 waitcode = WaitForMultipleObjects(w32_num_children,
1149 if (waitcode != WAIT_FAILED) {
1150 if (waitcode >= WAIT_ABANDONED_0
1151 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1152 i = waitcode - WAIT_ABANDONED_0;
1154 i = waitcode - WAIT_OBJECT_0;
1155 if (GetExitCodeProcess(w32_child_pids[i], &exitcode) ) {
1156 CloseHandle(w32_child_pids[i]);
1157 *status = (int)((exitcode & 0xff) << 8);
1158 retval = (int)w32_child_pids[i];
1159 Copy(&w32_child_pids[i+1], &w32_child_pids[i],
1160 (w32_num_children-i-1), HANDLE);
1167 errno = GetLastError();
1173 static UINT timerid = 0;
1175 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1177 KillTimer(NULL,timerid);
1182 DllExport unsigned int
1183 win32_alarm(unsigned int sec)
1186 * the 'obvious' implentation is SetTimer() with a callback
1187 * which does whatever receiving SIGALRM would do
1188 * we cannot use SIGALRM even via raise() as it is not
1189 * one of the supported codes in <signal.h>
1191 * Snag is unless something is looking at the message queue
1192 * nothing happens :-(
1196 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1198 croak("Cannot set timer");
1204 KillTimer(NULL,timerid);
1211 #ifdef HAVE_DES_FCRYPT
1212 extern char * des_fcrypt(char *cbuf, const char *txt, const char *salt);
1215 win32_crypt(const char *txt, const char *salt)
1218 return des_fcrypt(crypt_buffer, txt, salt);
1222 #ifdef USE_FIXED_OSFHANDLE
1224 EXTERN_C int __cdecl _alloc_osfhnd(void);
1225 EXTERN_C int __cdecl _set_osfhnd(int fh, long value);
1226 EXTERN_C void __cdecl _lock_fhandle(int);
1227 EXTERN_C void __cdecl _unlock_fhandle(int);
1228 EXTERN_C void __cdecl _unlock(int);
1230 #if (_MSC_VER >= 1000)
1232 long osfhnd; /* underlying OS file HANDLE */
1233 char osfile; /* attributes of file (e.g., open in text mode?) */
1234 char pipech; /* one char buffer for handles opened on pipes */
1235 #if defined (_MT) && !defined (DLL_FOR_WIN32S)
1237 CRITICAL_SECTION lock;
1238 #endif /* defined (_MT) && !defined (DLL_FOR_WIN32S) */
1241 EXTERN_C ioinfo * __pioinfo[];
1243 #define IOINFO_L2E 5
1244 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
1245 #define _pioinfo(i) (__pioinfo[i >> IOINFO_L2E] + (i & (IOINFO_ARRAY_ELTS - 1)))
1246 #define _osfile(i) (_pioinfo(i)->osfile)
1248 #else /* (_MSC_VER >= 1000) */
1249 extern char _osfile[];
1250 #endif /* (_MSC_VER >= 1000) */
1252 #define FOPEN 0x01 /* file handle open */
1253 #define FAPPEND 0x20 /* file handle opened O_APPEND */
1254 #define FDEV 0x40 /* file handle refers to device */
1255 #define FTEXT 0x80 /* file handle is in text mode */
1257 #define _STREAM_LOCKS 26 /* Table of stream locks */
1258 #define _LAST_STREAM_LOCK (_STREAM_LOCKS+_NSTREAM_-1) /* Last stream lock */
1259 #define _FH_LOCKS (_LAST_STREAM_LOCK+1) /* Table of fh locks */
1262 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1265 * This function allocates a free C Runtime file handle and associates
1266 * it with the Win32 HANDLE specified by the first parameter. This is a
1267 * temperary fix for WIN95's brain damage GetFileType() error on socket
1268 * we just bypass that call for socket
1271 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1272 * int flags - flags to associate with C Runtime file handle.
1275 * returns index of entry in fh, if successful
1276 * return -1, if no free entry is found
1280 *******************************************************************************/
1283 my_open_osfhandle(long osfhandle, int flags)
1286 char fileflags; /* _osfile flags */
1288 /* copy relevant flags from second parameter */
1291 if(flags & O_APPEND)
1292 fileflags |= FAPPEND;
1297 /* attempt to allocate a C Runtime file handle */
1298 if((fh = _alloc_osfhnd()) == -1) {
1299 errno = EMFILE; /* too many open files */
1300 _doserrno = 0L; /* not an OS error */
1301 return -1; /* return error to caller */
1304 /* the file is open. now, set the info in _osfhnd array */
1305 _set_osfhnd(fh, osfhandle);
1307 fileflags |= FOPEN; /* mark as open */
1309 #if (_MSC_VER >= 1000)
1310 _osfile(fh) = fileflags; /* set osfile entry */
1311 _unlock_fhandle(fh);
1313 _osfile[fh] = fileflags; /* set osfile entry */
1314 _unlock(fh+_FH_LOCKS); /* unlock handle */
1317 return fh; /* return handle */
1320 #define _open_osfhandle my_open_osfhandle
1321 #endif /* USE_FIXED_OSFHANDLE */
1323 /* simulate flock by locking a range on the file */
1325 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1326 #define LK_LEN 0xffff0000
1329 win32_flock(int fd, int oper)
1336 croak("flock() unimplemented on this platform");
1339 fh = (HANDLE)_get_osfhandle(fd);
1340 memset(&o, 0, sizeof(o));
1343 case LOCK_SH: /* shared lock */
1344 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1346 case LOCK_EX: /* exclusive lock */
1347 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1349 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1350 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1352 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1353 LK_ERR(LockFileEx(fh,
1354 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1355 0, LK_LEN, 0, &o),i);
1357 case LOCK_UN: /* unlock lock */
1358 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1360 default: /* unknown */
1371 * redirected io subsystem for all XS modules
1384 return (&(_environ));
1387 /* the rest are the remapped stdio routines */
1407 win32_ferror(FILE *fp)
1409 return (ferror(fp));
1414 win32_feof(FILE *fp)
1420 * Since the errors returned by the socket error function
1421 * WSAGetLastError() are not known by the library routine strerror
1422 * we have to roll our own.
1426 win32_strerror(int e)
1428 #ifndef __BORLANDC__ /* Borland intolerance */
1429 extern int sys_nerr;
1433 if(e < 0 || e > sys_nerr) {
1438 if(FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
1439 strerror_buffer, sizeof(strerror_buffer), NULL) == 0)
1440 strcpy(strerror_buffer, "Unknown Error");
1442 return strerror_buffer;
1448 win32_str_os_error(void *sv, DWORD dwErr)
1452 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
1453 |FORMAT_MESSAGE_IGNORE_INSERTS
1454 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
1455 dwErr, 0, (char *)&sMsg, 1, NULL);
1457 while (0 < dwLen && isspace(sMsg[--dwLen]))
1459 if ('.' != sMsg[dwLen])
1464 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
1465 dwLen = sprintf(sMsg,
1466 "Unknown error #0x%lX (lookup 0x%lX)",
1467 dwErr, GetLastError());
1469 sv_setpvn((SV*)sv, sMsg, dwLen);
1475 win32_fprintf(FILE *fp, const char *format, ...)
1478 va_start(marker, format); /* Initialize variable arguments. */
1480 return (vfprintf(fp, format, marker));
1484 win32_printf(const char *format, ...)
1487 va_start(marker, format); /* Initialize variable arguments. */
1489 return (vprintf(format, marker));
1493 win32_vfprintf(FILE *fp, const char *format, va_list args)
1495 return (vfprintf(fp, format, args));
1499 win32_vprintf(const char *format, va_list args)
1501 return (vprintf(format, args));
1505 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
1507 return fread(buf, size, count, fp);
1511 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
1513 return fwrite(buf, size, count, fp);
1517 win32_fopen(const char *filename, const char *mode)
1519 if (stricmp(filename, "/dev/null")==0)
1520 return fopen("NUL", mode);
1521 return fopen(filename, mode);
1524 #ifndef USE_SOCKETS_AS_HANDLES
1526 #define fdopen my_fdopen
1530 win32_fdopen( int handle, const char *mode)
1532 return fdopen(handle, (char *) mode);
1536 win32_freopen( const char *path, const char *mode, FILE *stream)
1538 if (stricmp(path, "/dev/null")==0)
1539 return freopen("NUL", mode, stream);
1540 return freopen(path, mode, stream);
1544 win32_fclose(FILE *pf)
1546 return my_fclose(pf); /* defined in win32sck.c */
1550 win32_fputs(const char *s,FILE *pf)
1552 return fputs(s, pf);
1556 win32_fputc(int c,FILE *pf)
1562 win32_ungetc(int c,FILE *pf)
1564 return ungetc(c,pf);
1568 win32_getc(FILE *pf)
1574 win32_fileno(FILE *pf)
1580 win32_clearerr(FILE *pf)
1587 win32_fflush(FILE *pf)
1593 win32_ftell(FILE *pf)
1599 win32_fseek(FILE *pf,long offset,int origin)
1601 return fseek(pf, offset, origin);
1605 win32_fgetpos(FILE *pf,fpos_t *p)
1607 return fgetpos(pf, p);
1611 win32_fsetpos(FILE *pf,const fpos_t *p)
1613 return fsetpos(pf, p);
1617 win32_rewind(FILE *pf)
1637 win32_fstat(int fd,struct stat *sbufptr)
1639 return fstat(fd,sbufptr);
1643 win32_pipe(int *pfd, unsigned int size, int mode)
1645 return _pipe(pfd, size, mode);
1649 * a popen() clone that respects PERL5SHELL
1653 win32_popen(const char *command, const char *mode)
1655 #ifdef USE_CRT_POPEN
1656 return _popen(command, mode);
1664 /* establish which ends read and write */
1665 if (strchr(mode,'w')) {
1666 stdfd = 0; /* stdin */
1670 else if (strchr(mode,'r')) {
1671 stdfd = 1; /* stdout */
1678 /* set the correct mode */
1679 if (strchr(mode,'b'))
1681 else if (strchr(mode,'t'))
1684 ourmode = _fmode & (O_TEXT | O_BINARY);
1686 /* the child doesn't inherit handles */
1687 ourmode |= O_NOINHERIT;
1689 if (win32_pipe( p, 512, ourmode) == -1)
1692 /* save current stdfd */
1693 if ((oldfd = win32_dup(stdfd)) == -1)
1696 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
1697 /* stdfd will be inherited by the child */
1698 if (win32_dup2(p[child], stdfd) == -1)
1701 /* close the child end in parent */
1702 win32_close(p[child]);
1704 /* start the child */
1705 if ((childpid = do_spawn_nowait((char*)command)) == -1)
1708 /* revert stdfd to whatever it was before */
1709 if (win32_dup2(oldfd, stdfd) == -1)
1712 /* close saved handle */
1715 w32_popen_pids[p[parent]] = childpid;
1717 /* we have an fd, return a file stream */
1718 return (win32_fdopen(p[parent], (char *)mode));
1721 /* we don't need to check for errors here */
1725 win32_dup2(oldfd, stdfd);
1730 #endif /* USE_CRT_POPEN */
1738 win32_pclose(FILE *pf)
1740 #ifdef USE_CRT_POPEN
1743 int fd, childpid, status;
1745 fd = win32_fileno(pf);
1746 childpid = w32_popen_pids[fd];
1754 w32_popen_pids[fd] = 0;
1756 /* wait for the child */
1757 if (cwait(&status, childpid, WAIT_CHILD) == -1)
1759 /* cwait() returns differently on Borland */
1761 return (((status >> 8) & 0xff) | ((status << 8) & 0xff00));
1766 #endif /* USE_CRT_OPEN */
1770 win32_setmode(int fd, int mode)
1772 return setmode(fd, mode);
1776 win32_lseek(int fd, long offset, int origin)
1778 return lseek(fd, offset, origin);
1788 win32_open(const char *path, int flag, ...)
1794 pmode = va_arg(ap, int);
1797 if (stricmp(path, "/dev/null")==0)
1798 return open("NUL", flag, pmode);
1799 return open(path,flag,pmode);
1821 win32_dup2(int fd1,int fd2)
1823 return dup2(fd1,fd2);
1827 win32_read(int fd, void *buf, unsigned int cnt)
1829 return read(fd, buf, cnt);
1833 win32_write(int fd, const void *buf, unsigned int cnt)
1835 return write(fd, buf, cnt);
1839 win32_mkdir(const char *dir, int mode)
1841 return mkdir(dir); /* just ignore mode */
1845 win32_rmdir(const char *dir)
1851 win32_chdir(const char *dir)
1857 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
1861 status = spawnvp(mode, cmdname, (char * const *) argv);
1862 #ifndef __BORLANDC__
1863 /* XXX For the P_NOWAIT case, Borland RTL returns pinfo.dwProcessId
1864 * while VC RTL returns pinfo.hProcess. For purposes of the custom
1865 * implementation of win32_wait(), we assume the latter.
1867 if (mode == P_NOWAIT && status >= 0)
1868 w32_child_pids[w32_num_children++] = (HANDLE)status;
1874 win32_execvp(const char *cmdname, const char *const *argv)
1876 return execvp(cmdname, (char *const *)argv);
1880 win32_perror(const char *str)
1886 win32_setbuf(FILE *pf, char *buf)
1892 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
1894 return setvbuf(pf, buf, type, size);
1898 win32_flushall(void)
1904 win32_fcloseall(void)
1910 win32_fgets(char *s, int n, FILE *pf)
1912 return fgets(s, n, pf);
1922 win32_fgetc(FILE *pf)
1928 win32_putc(int c, FILE *pf)
1934 win32_puts(const char *s)
1946 win32_putchar(int c)
1953 #ifndef USE_PERL_SBRK
1955 static char *committed = NULL;
1956 static char *base = NULL;
1957 static char *reserved = NULL;
1958 static char *brk = NULL;
1959 static DWORD pagesize = 0;
1960 static DWORD allocsize = 0;
1968 GetSystemInfo(&info);
1969 /* Pretend page size is larger so we don't perpetually
1970 * call the OS to commit just one page ...
1972 pagesize = info.dwPageSize << 3;
1973 allocsize = info.dwAllocationGranularity;
1975 /* This scheme fails eventually if request for contiguous
1976 * block is denied so reserve big blocks - this is only
1977 * address space not memory ...
1979 if (brk+need >= reserved)
1981 DWORD size = 64*1024*1024;
1983 if (committed && reserved && committed < reserved)
1985 /* Commit last of previous chunk cannot span allocations */
1986 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
1988 committed = reserved;
1990 /* Reserve some (more) space
1991 * Note this is a little sneaky, 1st call passes NULL as reserved
1992 * so lets system choose where we start, subsequent calls pass
1993 * the old end address so ask for a contiguous block
1995 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
1998 reserved = addr+size;
2013 if (brk > committed)
2015 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
2016 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
2031 win32_malloc(size_t size)
2033 return malloc(size);
2037 win32_calloc(size_t numitems, size_t size)
2039 return calloc(numitems,size);
2043 win32_realloc(void *block, size_t size)
2045 return realloc(block,size);
2049 win32_free(void *block)
2056 win32_open_osfhandle(long handle, int flags)
2058 return _open_osfhandle(handle, flags);
2062 win32_get_osfhandle(int fd)
2064 return _get_osfhandle(fd);
2075 SV *sv = sv_newmortal();
2076 /* Make one call with zero size - return value is required size */
2077 DWORD len = GetCurrentDirectory((DWORD)0,NULL);
2078 SvUPGRADE(sv,SVt_PV);
2080 SvCUR(sv) = GetCurrentDirectory((DWORD) SvLEN(sv), SvPVX(sv));
2083 * then it worked, set PV valid,
2084 * else leave it 'undef'
2098 croak("usage: Win32::SetCurrentDirectory($cwd)");
2099 if (SetCurrentDirectory(SvPV(ST(0),na)))
2106 XS(w32_GetNextAvailDrive)
2110 char root[] = "_:\\";
2113 if (GetDriveType(root) == 1) {
2122 XS(w32_GetLastError)
2125 XSRETURN_IV(GetLastError());
2132 char *name = getlogin_buffer;
2133 DWORD size = sizeof(getlogin_buffer);
2134 if (GetUserName(name,&size)) {
2135 /* size includes NULL */
2136 ST(0) = sv_2mortal(newSVpv(name,size-1));
2146 char name[MAX_COMPUTERNAME_LENGTH+1];
2147 DWORD size = sizeof(name);
2148 if (GetComputerName(name,&size)) {
2149 /* size does NOT include NULL :-( */
2150 ST(0) = sv_2mortal(newSVpv(name,size));
2162 DWORD size = sizeof(name);
2163 if (GetUserName(name,&size)) {
2165 DWORD sidlen = sizeof(sid);
2167 DWORD dnamelen = sizeof(dname);
2169 if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
2170 dname, &dnamelen, &snu)) {
2171 XSRETURN_PV(dname); /* all that for this */
2182 DWORD flags, filecomplen;
2183 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
2184 &flags, fsname, sizeof(fsname))) {
2185 if (GIMME == G_ARRAY) {
2186 XPUSHs(sv_2mortal(newSVpv(fsname,0)));
2187 XPUSHs(sv_2mortal(newSViv(flags)));
2188 XPUSHs(sv_2mortal(newSViv(filecomplen)));
2192 XSRETURN_PV(fsname);
2198 XS(w32_GetOSVersion)
2201 OSVERSIONINFO osver;
2203 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
2204 if (GetVersionEx(&osver)) {
2205 XPUSHs(newSVpv(osver.szCSDVersion, 0));
2206 XPUSHs(newSViv(osver.dwMajorVersion));
2207 XPUSHs(newSViv(osver.dwMinorVersion));
2208 XPUSHs(newSViv(osver.dwBuildNumber));
2209 XPUSHs(newSViv(osver.dwPlatformId));
2220 XSRETURN_IV(IsWinNT());
2227 XSRETURN_IV(IsWin95());
2231 XS(w32_FormatMessage)
2238 croak("usage: Win32::FormatMessage($errno)");
2240 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
2241 &source, SvIV(ST(0)), 0,
2242 msgbuf, sizeof(msgbuf)-1, NULL))
2243 XSRETURN_PV(msgbuf);
2253 PROCESS_INFORMATION stProcInfo;
2254 STARTUPINFO stStartInfo;
2255 BOOL bSuccess = FALSE;
2258 croak("usage: Win32::Spawn($cmdName, $args, $PID)");
2260 cmd = SvPV(ST(0),na);
2261 args = SvPV(ST(1), na);
2263 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
2264 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
2265 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
2266 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
2269 cmd, /* Image path */
2270 args, /* Arguments for command line */
2271 NULL, /* Default process security */
2272 NULL, /* Default thread security */
2273 FALSE, /* Must be TRUE to use std handles */
2274 NORMAL_PRIORITY_CLASS, /* No special scheduling */
2275 NULL, /* Inherit our environment block */
2276 NULL, /* Inherit our currrent directory */
2277 &stStartInfo, /* -> Startup info */
2278 &stProcInfo)) /* <- Process info (if OK) */
2280 CloseHandle(stProcInfo.hThread);/* library source code does this. */
2281 sv_setiv(ST(2), stProcInfo.dwProcessId);
2284 XSRETURN_IV(bSuccess);
2288 XS(w32_GetTickCount)
2291 XSRETURN_IV(GetTickCount());
2295 XS(w32_GetShortPathName)
2302 croak("usage: Win32::GetShortPathName($longPathName)");
2304 shortpath = sv_mortalcopy(ST(0));
2305 SvUPGRADE(shortpath, SVt_PV);
2306 /* src == target is allowed */
2308 len = GetShortPathName(SvPVX(shortpath),
2311 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
2313 SvCUR_set(shortpath,len);
2326 croak("usage: Win32::Sleep($milliseconds)");
2331 #define TMPBUFSZ 1024
2332 #define MAX_LENGTH 2048
2333 #define SUCCESSRETURNED(x) (x == ERROR_SUCCESS)
2334 #define REGRETURN(x) XSRETURN_IV(SUCCESSRETURNED(x))
2335 #define SvHKEY(index) (HKEY)((unsigned long)SvIV(index))
2336 #define SETIV(index,value) sv_setiv(ST(index), value)
2337 #define SETNV(index,value) sv_setnv(ST(index), value)
2338 #define SETPV(index,string) sv_setpv(ST(index), string)
2339 #define SETPVN(index, buffer, length) sv_setpvn(ST(index), (char*)buffer, length)
2340 #define SETHKEY(index, hkey) SETIV(index,(long)hkey)
2342 static time_t ft2timet(FILETIME *ft)
2347 FileTimeToSystemTime(ft, &st);
2348 tm.tm_sec = st.wSecond;
2349 tm.tm_min = st.wMinute;
2350 tm.tm_hour = st.wHour;
2351 tm.tm_mday = st.wDay;
2352 tm.tm_mon = st.wMonth - 1;
2353 tm.tm_year = st.wYear - 1900;
2354 tm.tm_wday = st.wDayOfWeek;
2357 return mktime (&tm);
2367 croak("usage: Win32::RegCloseKey($hkey);\n");
2370 REGRETURN(RegCloseKey(SvHKEY(ST(0))));
2374 XS(w32_RegConnectRegistry)
2381 croak("usage: Win32::RegConnectRegistry($machine, $hkey, $handle);\n");
2384 if(SUCCESSRETURNED(RegConnectRegistry((char *)SvPV(ST(0), na), SvHKEY(ST(1)), &handle)))
2393 XS(w32_RegCreateKey)
2402 croak("usage: Win32::RegCreateKey($hkey, $subkey, $handle);\n");
2405 retval = RegCreateKeyEx(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS,
2406 NULL, &handle, &disposition);
2408 if(SUCCESSRETURNED(retval))
2417 XS(w32_RegCreateKeyEx)
2421 unsigned int length;
2426 DWORD options, disposition;
2428 SECURITY_ATTRIBUTES sa, *psa;
2432 croak("usage: Win32::RegCreateKeyEx($hkey, $subkey, $reserved, $class, $options, $sam, "
2433 "$security, $handle, $disposition);\n");
2436 hkey = SvHKEY(ST(0));
2437 subkey = (char *)SvPV(ST(1), na);
2438 keyclass = (char *)SvPV(ST(3), na);
2439 options = (DWORD) ((unsigned long)SvIV(ST(4)));
2440 sam = (REGSAM) ((unsigned long)SvIV(ST(5)));
2441 psa = (SECURITY_ATTRIBUTES*)SvPV(ST(6), length);
2442 if(length != sizeof(SECURITY_ATTRIBUTES))
2445 memset(&sa, 0, sizeof(SECURITY_ATTRIBUTES));
2446 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
2449 retval = RegCreateKeyEx(hkey, subkey, 0, keyclass, options, sam,
2450 psa, &handle, &disposition);
2452 if(SUCCESSRETURNED(retval))
2455 SETPVN(6, &sa, sizeof(sa));
2458 SETIV(8,disposition);
2465 XS(w32_RegDeleteKey)
2471 croak("usage: Win32::RegDeleteKey($hkey, $subkey);\n");
2474 REGRETURN(RegDeleteKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na)));
2478 XS(w32_RegDeleteValue)
2484 croak("usage: Win32::RegDeleteValue($hkey, $valname);\n");
2487 REGRETURN(RegDeleteValue(SvHKEY(ST(0)), (char *)SvPV(ST(1), na)));
2495 char keybuffer[TMPBUFSZ];
2499 croak("usage: Win32::RegEnumKey($hkey, $idx, $subkeyname);\n");
2502 if(SUCCESSRETURNED(RegEnumKey(SvHKEY(ST(0)), SvIV(ST(1)), keybuffer, sizeof(keybuffer))))
2504 SETPV(2, keybuffer);
2511 XS(w32_RegEnumKeyEx)
2516 DWORD keysz, classsz;
2517 char keybuffer[TMPBUFSZ];
2518 char classbuffer[TMPBUFSZ];
2524 croak("usage: Win32::RegEnumKeyEx($hkey, $idx, $subkeyname, $reserved, $class, $time);\n");
2527 keysz = sizeof(keybuffer);
2528 classsz = sizeof(classbuffer);
2529 retval = RegEnumKeyEx(SvHKEY(ST(0)), SvIV(ST(1)), keybuffer, &keysz, 0,
2530 classbuffer, &classsz, &filetime);
2531 if(SUCCESSRETURNED(retval))
2533 SETPV(2, keybuffer);
2534 SETPV(4, classbuffer);
2535 SETIV(5, ft2timet(&filetime));
2542 XS(w32_RegEnumValue)
2546 DWORD type, namesz, valsz;
2548 static HKEY last_hkey;
2549 char myvalbuf[MAX_LENGTH];
2550 char mynambuf[MAX_LENGTH];
2554 croak("usage: Win32::RegEnumValue($hkey, $i, $name, $reserved, $type, $value);\n");
2557 hkey = SvHKEY(ST(0));
2559 // If this is a new key, find out how big the maximum name and value sizes are and
2560 // allocate space for them. Free any old storage and set the old key value to the
2563 if(hkey != (HKEY)last_hkey)
2565 char keyclass[TMPBUFSZ];
2566 DWORD classsz, subkeys, maxsubkey, maxclass, values, salen, maxnamesz, maxvalsz;
2568 classsz = sizeof(keyclass);
2569 retval = RegQueryInfoKey(hkey, keyclass, &classsz, 0, &subkeys, &maxsubkey, &maxclass,
2570 &values, &maxnamesz, &maxvalsz, &salen, &ft);
2572 if(!SUCCESSRETURNED(retval))
2576 memset(myvalbuf, 0, MAX_LENGTH);
2577 memset(mynambuf, 0, MAX_LENGTH);
2581 namesz = MAX_LENGTH;
2583 retval = RegEnumValue(hkey, SvIV(ST(1)), mynambuf, &namesz, 0, &type, (LPBYTE) myvalbuf, &valsz);
2584 if(!SUCCESSRETURNED(retval))
2593 // return includes the null terminator so delete it if REG_SZ, REG_MULTI_SZ or REG_EXPAND_SZ
2602 SETPVN(5, myvalbuf, valsz);
2605 case REG_DWORD_BIG_ENDIAN:
2607 BYTE tmp = myvalbuf[0];
2608 myvalbuf[0] = myvalbuf[3];
2611 myvalbuf[1] = myvalbuf[2];
2614 case REG_DWORD_LITTLE_ENDIAN: // same as REG_DWORD
2615 SETNV(5, (double)*((DWORD*)myvalbuf));
2633 croak("usage: Win32::RegFlushKey($hkey);\n");
2636 REGRETURN(RegFlushKey(SvHKEY(ST(0))));
2640 XS(w32_RegGetKeySecurity)
2643 SECURITY_DESCRIPTOR sd;
2648 croak("usage: Win32::RegGetKeySecurity($hkey, $security_info, $security_descriptor);\n");
2651 if(SUCCESSRETURNED(RegGetKeySecurity(SvHKEY(ST(0)), SvIV(ST(1)), &sd, &sdsz)))
2653 SETPVN(2, &sd, sdsz);
2666 croak("usage: Win32::RegLoadKey($hkey, $subkey, $filename);\n");
2669 REGRETURN(RegLoadKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), (char *)SvPV(ST(2), na)));
2673 XS(w32_RegNotifyChangeKeyValue)
2675 croak("Win32::RegNotifyChangeKeyValue not yet implemented!\n");
2686 croak("usage: Win32::RegOpenKey($hkey, $subkey, $handle);\n");
2689 if(SUCCESSRETURNED(RegOpenKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), &handle)))
2698 XS(w32_RegOpenKeyEx)
2705 croak("usage: Win32::RegOpenKeyEx($hkey, $subkey, $reserved, $sam, $handle);\n");
2708 if(SUCCESSRETURNED(RegOpenKeyEx(SvHKEY(ST(0)), (char *)SvPV(ST(1), na),
2709 0, (REGSAM) ((unsigned long)SvIV(ST(3))), &handle)))
2717 #pragma optimize("", off)
2719 XS(w32_RegQueryInfoKey)
2724 char keyclass[TMPBUFSZ];
2725 DWORD subkeys, maxsubkey, maxclass, values, maxvalname, maxvaldata;
2726 DWORD seclen, classsz;
2732 croak("usage: Win32::RegQueryInfoKey($hkey, $class, $numsubkeys, $maxsubkey,"
2733 "$maxclass, $values, $maxvalname, $maxvaldata, $secdesclen,"
2734 "$lastwritetime);\n");
2737 classsz = sizeof(keyclass);
2738 retval = RegQueryInfoKey(SvHKEY(ST(0)), keyclass, &classsz, 0, &subkeys, &maxsubkey,
2739 &maxclass, &values, &maxvalname, &maxvaldata,
2741 if(SUCCESSRETURNED(retval))
2745 SETIV(3, maxsubkey);
2748 SETIV(6, maxvalname);
2749 SETIV(7, maxvaldata);
2751 SETIV(9, ft2timet(&ft));
2756 #pragma optimize("", on)
2759 XS(w32_RegQueryValue)
2763 unsigned char databuffer[TMPBUFSZ*2];
2764 long datasz = sizeof(databuffer);
2768 croak("usage: Win32::RegQueryValue($hkey, $valuename, $data);\n");
2771 if(SUCCESSRETURNED(RegQueryValue(SvHKEY(ST(0)), SvPV(ST(1), na), (char*)databuffer, &datasz)))
2773 // return includes the null terminator so delete it
2774 SETPVN(2, databuffer, --datasz);
2781 XS(w32_RegQueryValueEx)
2785 unsigned char databuffer[TMPBUFSZ*2];
2786 DWORD datasz = sizeof(databuffer);
2789 LPBYTE ptr = databuffer;
2793 croak("usage: Win32::RegQueryValueEx($hkey, $valuename, $reserved, $type, $data);\n");
2796 result = RegQueryValueEx(SvHKEY(ST(0)), SvPV(ST(1), na), 0, &type, ptr, &datasz);
2797 if(result == ERROR_MORE_DATA)
2799 New(0, ptr, datasz+1, BYTE);
2800 result = RegQueryValueEx(SvHKEY(ST(0)), SvPV(ST(1), na), 0, &type, ptr, &datasz);
2802 if(SUCCESSRETURNED(result))
2806 // return includes the null terminator so delete it if REG_SZ, REG_MULTI_SZ or REG_EXPAND_SZ
2814 SETPVN(4, ptr, datasz);
2817 case REG_DWORD_BIG_ENDIAN:
2826 case REG_DWORD_LITTLE_ENDIAN: // same as REG_DWORD
2827 SETNV(4, (double)*((DWORD*)ptr));
2834 if(ptr != databuffer)
2839 if(ptr != databuffer)
2846 XS(w32_RegReplaceKey)
2852 croak("usage: Win32::RegReplaceKey($hkey, $subkey, $newfile, $oldfile);\n");
2855 REGRETURN(RegReplaceKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), (char *)SvPV(ST(2), na), (char *)SvPV(ST(3), na)));
2859 XS(w32_RegRestoreKey)
2863 if(items < 2 || items > 3)
2865 croak("usage: Win32::RegRestoreKey($hkey, $filename [, $flags]);\n");
2868 REGRETURN(RegRestoreKey(SvHKEY(ST(0)), (char*)SvPV(ST(1), na), (DWORD)((items == 3) ? SvIV(ST(2)) : 0)));
2878 croak("usage: Win32::RegSaveKey($hkey, $filename);\n");
2881 REGRETURN(RegSaveKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), NULL));
2885 XS(w32_RegSetKeySecurity)
2891 croak("usage: Win32::RegSetKeySecurity($hkey, $security_info, $security_descriptor);\n");
2894 REGRETURN(RegSetKeySecurity(SvHKEY(ST(0)), SvIV(ST(1)), (SECURITY_DESCRIPTOR*)SvPV(ST(2), na)));
2907 croak("usage: Win32::RegSetValue($hkey, $subKey, $type, $data);\n");
2910 DWORD type = SvIV(ST(2));
2911 if(type != REG_SZ && type != REG_EXPAND_SZ)
2913 croak("Win32::RegSetValue: Type was not REG_SZ or REG_EXPAND_SZ, cannot set %s\n", (char *)SvPV(ST(1), na));
2916 buffer = (char *)SvPV(ST(3), size);
2917 REGRETURN(RegSetValue(SvHKEY(ST(0)), SvPV(ST(1), na), REG_SZ, buffer, size));
2921 XS(w32_RegSetValueEx)
2932 croak("usage: Win32::RegSetValueEx($hkey, $valname, $reserved, $type, $data);\n");
2935 type = (DWORD)SvIV(ST(3));
2942 buffer = (char *)SvPV(ST(4), size);
2943 if(type != REG_BINARY)
2944 size++; // include null terminator in size
2946 REGRETURN(RegSetValueEx(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), 0, type, (PBYTE) buffer, size));
2949 case REG_DWORD_BIG_ENDIAN:
2950 case REG_DWORD_LITTLE_ENDIAN: // Same as REG_DWORD
2951 val = (DWORD)SvIV(ST(4));
2952 REGRETURN(RegSetValueEx(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), 0, type, (PBYTE) &val, sizeof(DWORD)));
2956 croak("Win32::RegSetValueEx: Type not specified, cannot set %s\n", (char *)SvPV(ST(1), na));
2961 XS(w32_RegUnloadKey)
2967 croak("usage: Win32::RegUnLoadKey($hkey, $subkey);\n");
2970 REGRETURN(RegUnLoadKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na)));
2974 XS(w32_RegisterServer)
2977 BOOL bSuccess = FALSE;
2978 HINSTANCE hInstance;
2979 unsigned int length;
2984 croak("usage: Win32::RegisterServer($LibraryName)\n");
2987 hInstance = LoadLibrary((char *)SvPV(ST(0), length));
2988 if(hInstance != NULL)
2990 sFunc = GetProcAddress(hInstance, "DllRegisterServer");
2993 bSuccess = (sFunc() == 0);
2995 FreeLibrary(hInstance);
3006 XS(w32_UnregisterServer)
3009 BOOL bSuccess = FALSE;
3010 HINSTANCE hInstance;
3011 unsigned int length;
3016 croak("usage: Win32::UnregisterServer($LibraryName)\n");
3019 hInstance = LoadLibrary((char *)SvPV(ST(0), length));
3020 if(hInstance != NULL)
3022 sFunc = GetProcAddress(hInstance, "DllUnregisterServer");
3025 bSuccess = (sFunc() == 0);
3027 FreeLibrary(hInstance);
3039 Perl_init_os_extras()
3041 char *file = __FILE__;
3044 /* these names are Activeware compatible */
3045 newXS("Win32::GetCwd", w32_GetCwd, file);
3046 newXS("Win32::SetCwd", w32_SetCwd, file);
3047 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
3048 newXS("Win32::GetLastError", w32_GetLastError, file);
3049 newXS("Win32::LoginName", w32_LoginName, file);
3050 newXS("Win32::NodeName", w32_NodeName, file);
3051 newXS("Win32::DomainName", w32_DomainName, file);
3052 newXS("Win32::FsType", w32_FsType, file);
3053 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
3054 newXS("Win32::IsWinNT", w32_IsWinNT, file);
3055 newXS("Win32::IsWin95", w32_IsWin95, file);
3056 newXS("Win32::FormatMessage", w32_FormatMessage, file);
3057 newXS("Win32::Spawn", w32_Spawn, file);
3058 newXS("Win32::GetTickCount", w32_GetTickCount, file);
3059 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
3060 newXS("Win32::Sleep", w32_Sleep, file);
3062 /* the following extensions are used interally and may be changed at any time */
3063 /* therefore no documentation is provided */
3064 newXS("Win32::RegCloseKey", w32_RegCloseKey, file);
3065 newXS("Win32::RegConnectRegistry", w32_RegConnectRegistry, file);
3066 newXS("Win32::RegCreateKey", w32_RegCreateKey, file);
3067 newXS("Win32::RegCreateKeyEx", w32_RegCreateKeyEx, file);
3068 newXS("Win32::RegDeleteKey", w32_RegDeleteKey, file);
3069 newXS("Win32::RegDeleteValue", w32_RegDeleteValue, file);
3071 newXS("Win32::RegEnumKey", w32_RegEnumKey, file);
3072 newXS("Win32::RegEnumKeyEx", w32_RegEnumKeyEx, file);
3073 newXS("Win32::RegEnumValue", w32_RegEnumValue, file);
3075 newXS("Win32::RegFlushKey", w32_RegFlushKey, file);
3076 newXS("Win32::RegGetKeySecurity", w32_RegGetKeySecurity, file);
3078 newXS("Win32::RegLoadKey", w32_RegLoadKey, file);
3079 newXS("Win32::RegOpenKey", w32_RegOpenKey, file);
3080 newXS("Win32::RegOpenKeyEx", w32_RegOpenKeyEx, file);
3081 newXS("Win32::RegQueryInfoKey", w32_RegQueryInfoKey, file);
3082 newXS("Win32::RegQueryValue", w32_RegQueryValue, file);
3083 newXS("Win32::RegQueryValueEx", w32_RegQueryValueEx, file);
3085 newXS("Win32::RegReplaceKey", w32_RegReplaceKey, file);
3086 newXS("Win32::RegRestoreKey", w32_RegRestoreKey, file);
3087 newXS("Win32::RegSaveKey", w32_RegSaveKey, file);
3088 newXS("Win32::RegSetKeySecurity", w32_RegSetKeySecurity, file);
3089 newXS("Win32::RegSetValue", w32_RegSetValue, file);
3090 newXS("Win32::RegSetValueEx", w32_RegSetValueEx, file);
3091 newXS("Win32::RegUnloadKey", w32_RegUnloadKey, file);
3093 newXS("Win32::RegisterServer", w32_RegisterServer, file);
3094 newXS("Win32::UnregisterServer", w32_UnregisterServer, file);
3096 /* XXX Bloat Alert! The following Activeware preloads really
3097 * ought to be part of Win32::Sys::*, so they're not included
3100 /* LookupAccountName
3102 * InitiateSystemShutdown
3103 * AbortSystemShutdown
3104 * ExpandEnvrironmentStrings
3109 Perl_win32_init(int *argcp, char ***argvp)
3111 /* Disable floating point errors, Perl will trap the ones we
3112 * care about. VC++ RTL defaults to switching these off
3113 * already, but the Borland RTL doesn't. Since we don't
3114 * want to be at the vendor's whim on the default, we set
3115 * it explicitly here.
3117 #if !defined(_ALPHA_) && !defined(__GNUC__)
3118 _control87(MCW_EM, MCW_EM);
3123 #ifdef USE_BINMODE_SCRIPTS
3126 win32_strip_return(SV *sv)
3128 char *s = SvPVX(sv);
3129 char *e = s+SvCUR(sv);
3133 if (*s == '\r' && s[1] == '\n')
3143 SvCUR_set(sv,d-SvPVX(sv));