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];
353 /* $HKCU{"sitelib-$]"} || $HKLM{"sitelib-$]"} . ---; */
354 sprintf(szRegStr, "%s-%s", szSiteLib, pl);
355 sprintf(szPathStr, "site\\%s\\lib", pl);
356 lpPath1 = get_sitelib_part(szRegStr, szPathStr);
358 /* $HKCU{'sitelib'} || $HKLM{'sitelib'} . ---; */
359 lpPath2 = get_sitelib_part(szSiteLib, "site\\lib");
366 int len = strlen(lpPath1);
367 int newSize = len + strlen(lpPath2) + 2; /* plus one for ';' */
369 lpPath1 = Renew(lpPath1, newSize, char);
372 lpPath1[len++] = ';';
373 strcpy(&lpPath1[len], lpPath2);
381 has_redirection(char *ptr)
387 * Scan string looking for redirection (< or >) or pipe
388 * characters (|) that are not in a quoted string
418 #if !defined(PERL_OBJECT)
419 /* since the current process environment is being updated in util.c
420 * the library functions will get the correct environment
423 my_popen(char *cmd, char *mode)
426 #define fixcmd(x) { \
427 char *pspace = strchr((x),' '); \
430 while (p < pspace) { \
441 win32_fflush(stdout);
442 win32_fflush(stderr);
443 return win32_popen(cmd, mode);
447 my_pclose(PerlIO *fp)
449 return win32_pclose(fp);
456 static OSVERSIONINFO osver;
458 if (osver.dwPlatformId != w32_platform) {
459 memset(&osver, 0, sizeof(OSVERSIONINFO));
460 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
461 GetVersionEx(&osver);
462 w32_platform = osver.dwPlatformId;
464 return (w32_platform);
467 /* Tokenize a string. Words are null-separated, and the list
468 * ends with a doubled null. Any character (except null and
469 * including backslash) may be escaped by preceding it with a
470 * backslash (the backslash will be stripped).
471 * Returns number of words in result buffer.
474 tokenize(char *str, char **dest, char ***destv)
476 char *retstart = Nullch;
477 char **retvstart = 0;
480 int slen = strlen(str);
482 register char **retv;
483 New(1307, ret, slen+2, char);
484 New(1308, retv, (slen+3)/2, char*);
492 if (*ret == '\\' && *str)
494 else if (*ret == ' ') {
510 retvstart[items] = Nullch;
522 if (!w32_perlshell_tokens) {
523 /* we don't use COMSPEC here for two reasons:
524 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
525 * uncontrolled unportability of the ensuing scripts.
526 * 2. PERL5SHELL could be set to a shell that may not be fit for
527 * interactive use (which is what most programs look in COMSPEC
530 char* defaultshell = (IsWinNT() ? "cmd.exe /x/c" : "command.com /c");
531 char *usershell = getenv("PERL5SHELL");
532 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
533 &w32_perlshell_tokens,
539 do_aspawn(void *vreally, void **vmark, void **vsp)
541 SV *really = (SV*)vreally;
542 SV **mark = (SV**)vmark;
554 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
556 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
561 while (++mark <= sp) {
562 if (*mark && (str = SvPV(*mark, na)))
569 status = win32_spawnvp(flag,
570 (const char*)(really ? SvPV(really,na) : argv[0]),
571 (const char* const*)argv);
573 if (status < 0 && errno == ENOEXEC) {
574 /* possible shell-builtin, invoke with shell */
576 sh_items = w32_perlshell_items;
578 argv[index+sh_items] = argv[index];
579 while (--sh_items >= 0)
580 argv[sh_items] = w32_perlshell_vec[sh_items];
582 status = win32_spawnvp(flag,
583 (const char*)(really ? SvPV(really,na) : argv[0]),
584 (const char* const*)argv);
587 if (flag != P_NOWAIT) {
590 warn("Can't spawn \"%s\": %s", argv[0], strerror(errno));
595 statusvalue = status;
602 do_spawn2(char *cmd, int exectype)
608 BOOL needToTry = TRUE;
611 /* Save an extra exec if possible. See if there are shell
612 * metacharacters in it */
613 if (!has_redirection(cmd)) {
614 New(1301,argv, strlen(cmd) / 2 + 2, char*);
615 New(1302,cmd2, strlen(cmd) + 1, char);
618 for (s = cmd2; *s;) {
619 while (*s && isspace(*s))
623 while (*s && !isspace(*s))
632 status = win32_spawnvp(P_WAIT, argv[0],
633 (const char* const*)argv);
635 case EXECF_SPAWN_NOWAIT:
636 status = win32_spawnvp(P_NOWAIT, argv[0],
637 (const char* const*)argv);
640 status = win32_execvp(argv[0], (const char* const*)argv);
643 if (status != -1 || errno == 0)
653 New(1306, argv, w32_perlshell_items + 2, char*);
654 while (++i < w32_perlshell_items)
655 argv[i] = w32_perlshell_vec[i];
660 status = win32_spawnvp(P_WAIT, argv[0],
661 (const char* const*)argv);
663 case EXECF_SPAWN_NOWAIT:
664 status = win32_spawnvp(P_NOWAIT, argv[0],
665 (const char* const*)argv);
668 status = win32_execvp(argv[0], (const char* const*)argv);
674 if (exectype != EXECF_SPAWN_NOWAIT) {
677 warn("Can't %s \"%s\": %s",
678 (exectype == EXECF_EXEC ? "exec" : "spawn"),
679 cmd, strerror(errno));
684 statusvalue = status;
692 return do_spawn2(cmd, EXECF_SPAWN);
696 do_spawn_nowait(char *cmd)
698 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
704 do_spawn2(cmd, EXECF_EXEC);
708 /* The idea here is to read all the directory names into a string table
709 * (separated by nulls) and when one of the other dir functions is called
710 * return the pointer to the current file name.
713 opendir(char *filename)
718 char scanname[MAX_PATH+3];
720 WIN32_FIND_DATA FindData;
723 len = strlen(filename);
727 /* check to see if filename is a directory */
728 if (win32_stat(filename, &sbuf) < 0 || (sbuf.st_mode & S_IFDIR) == 0) {
729 /* CRT is buggy on sharenames, so make sure it really isn't */
730 DWORD r = GetFileAttributes(filename);
731 if (r == 0xffffffff || !(r & FILE_ATTRIBUTE_DIRECTORY))
735 /* Get us a DIR structure */
736 Newz(1303, p, 1, DIR);
740 /* Create the search pattern */
741 strcpy(scanname, filename);
742 if (scanname[len-1] != '/' && scanname[len-1] != '\\')
743 scanname[len++] = '/';
744 scanname[len++] = '*';
745 scanname[len] = '\0';
747 /* do the FindFirstFile call */
748 fh = FindFirstFile(scanname, &FindData);
749 if (fh == INVALID_HANDLE_VALUE) {
753 /* now allocate the first part of the string table for
754 * the filenames that we find.
756 idx = strlen(FindData.cFileName)+1;
757 New(1304, p->start, idx, char);
758 if (p->start == NULL)
759 croak("opendir: malloc failed!\n");
760 strcpy(p->start, FindData.cFileName);
763 /* loop finding all the files that match the wildcard
764 * (which should be all of them in this directory!).
765 * the variable idx should point one past the null terminator
766 * of the previous string found.
768 while (FindNextFile(fh, &FindData)) {
769 len = strlen(FindData.cFileName);
770 /* bump the string table size by enough for the
771 * new name and it's null terminator
773 Renew(p->start, idx+len+1, char);
774 if (p->start == NULL)
775 croak("opendir: malloc failed!\n");
776 strcpy(&p->start[idx], FindData.cFileName);
787 /* Readdir just returns the current string pointer and bumps the
788 * string pointer to the nDllExport entry.
794 static int dummy = 0;
797 /* first set up the structure to return */
798 len = strlen(dirp->curr);
799 strcpy(dirp->dirstr.d_name, dirp->curr);
800 dirp->dirstr.d_namlen = len;
803 dirp->dirstr.d_ino = dummy++;
805 /* Now set up for the nDllExport call to readdir */
806 dirp->curr += len + 1;
807 if (dirp->curr >= (dirp->start + dirp->size)) {
811 return &(dirp->dirstr);
817 /* Telldir returns the current string pointer position */
821 return (long) dirp->curr;
825 /* Seekdir moves the string pointer to a previously saved position
829 seekdir(DIR *dirp, long loc)
831 dirp->curr = (char *)loc;
834 /* Rewinddir resets the string pointer to the start */
838 dirp->curr = dirp->start;
841 /* free the memory allocated by opendir */
845 Safefree(dirp->start);
858 * Just pretend that everyone is a superuser. NT will let us know if
859 * we don\'t really have permission to do something.
862 #define ROOT_UID ((uid_t)0)
863 #define ROOT_GID ((gid_t)0)
892 return (auid == ROOT_UID ? 0 : -1);
898 return (agid == ROOT_GID ? 0 : -1);
905 char *buf = getlogin_buffer;
906 DWORD size = sizeof(getlogin_buffer);
907 if (GetUserName(buf,&size))
913 chown(const char *path, uid_t owner, gid_t group)
920 kill(int pid, int sig)
922 HANDLE hProcess= OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
924 if (hProcess == NULL) {
925 croak("kill process failed!\n");
928 if (!TerminateProcess(hProcess, sig))
929 croak("kill process failed!\n");
930 CloseHandle(hProcess);
939 DllExport unsigned int
940 win32_sleep(unsigned int t)
947 win32_stat(const char *path, struct stat *buffer)
950 const char *p = path;
951 int l = strlen(path);
955 switch(path[l - 1]) {
958 if (path[l - 2] != ':') {
959 strncpy(t, path, l - 1);
965 res = stat(p,buffer);
968 if (S_ISDIR(buffer->st_mode))
969 buffer->st_mode |= S_IWRITE | S_IEXEC;
970 else if (S_ISREG(buffer->st_mode)) {
971 if (l >= 4 && path[l-4] == '.') {
972 const char *e = path + l - 3;
973 if (strnicmp(e,"exe",3)
974 && strnicmp(e,"bat",3)
975 && strnicmp(e,"com",3)
976 && (IsWin95() || strnicmp(e,"cmd",3)))
977 buffer->st_mode &= ~S_IEXEC;
979 buffer->st_mode |= S_IEXEC;
982 buffer->st_mode &= ~S_IEXEC;
989 #ifndef USE_WIN32_RTL_ENV
992 win32_getenv(const char *name)
994 static char *curitem = Nullch;
995 static DWORD curlen = 512;
998 New(1305,curitem,curlen,char);
999 if (!(needlen = GetEnvironmentVariable(name,curitem,curlen)))
1001 while (needlen > curlen) {
1002 Renew(curitem,needlen,char);
1004 needlen = GetEnvironmentVariable(name,curitem,curlen);
1006 if (curitem == NULL)
1008 if (strcmp("PERL5DB", name) == 0)
1009 curitem = GetRegStr(name, &curitem, &curlen);
1017 filetime_to_clock(PFILETIME ft)
1019 __int64 qw = ft->dwHighDateTime;
1021 qw |= ft->dwLowDateTime;
1022 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
1027 win32_times(struct tms *timebuf)
1032 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
1034 timebuf->tms_utime = filetime_to_clock(&user);
1035 timebuf->tms_stime = filetime_to_clock(&kernel);
1036 timebuf->tms_cutime = 0;
1037 timebuf->tms_cstime = 0;
1040 /* That failed - e.g. Win95 fallback to clock() */
1041 clock_t t = clock();
1042 timebuf->tms_utime = t;
1043 timebuf->tms_stime = 0;
1044 timebuf->tms_cutime = 0;
1045 timebuf->tms_cstime = 0;
1050 /* fix utime() so it works on directories in NT
1051 * thanks to Jan Dubois <jan.dubois@ibm.net>
1054 filetime_from_time(PFILETIME pFileTime, time_t Time)
1056 struct tm *pTM = gmtime(&Time);
1057 SYSTEMTIME SystemTime;
1062 SystemTime.wYear = pTM->tm_year + 1900;
1063 SystemTime.wMonth = pTM->tm_mon + 1;
1064 SystemTime.wDay = pTM->tm_mday;
1065 SystemTime.wHour = pTM->tm_hour;
1066 SystemTime.wMinute = pTM->tm_min;
1067 SystemTime.wSecond = pTM->tm_sec;
1068 SystemTime.wMilliseconds = 0;
1070 return SystemTimeToFileTime(&SystemTime, pFileTime);
1074 win32_utime(const char *filename, struct utimbuf *times)
1080 struct utimbuf TimeBuffer;
1082 int rc = utime(filename,times);
1083 /* EACCES: path specifies directory or readonly file */
1084 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
1087 if (times == NULL) {
1088 times = &TimeBuffer;
1089 time(×->actime);
1090 times->modtime = times->actime;
1093 /* This will (and should) still fail on readonly files */
1094 handle = CreateFile(filename, GENERIC_READ | GENERIC_WRITE,
1095 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1096 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1097 if (handle == INVALID_HANDLE_VALUE)
1100 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
1101 filetime_from_time(&ftAccess, times->actime) &&
1102 filetime_from_time(&ftWrite, times->modtime) &&
1103 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
1108 CloseHandle(handle);
1113 win32_wait(int *status)
1116 return wait(status);
1118 /* XXX this wait emulation only knows about processes
1119 * spawned via win32_spawnvp(P_NOWAIT, ...).
1122 DWORD exitcode, waitcode;
1124 if (!w32_num_children) {
1129 /* if a child exists, wait for it to die */
1130 waitcode = WaitForMultipleObjects(w32_num_children,
1134 if (waitcode != WAIT_FAILED) {
1135 if (waitcode >= WAIT_ABANDONED_0
1136 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1137 i = waitcode - WAIT_ABANDONED_0;
1139 i = waitcode - WAIT_OBJECT_0;
1140 if (GetExitCodeProcess(w32_child_pids[i], &exitcode) ) {
1141 CloseHandle(w32_child_pids[i]);
1142 *status = (int)((exitcode & 0xff) << 8);
1143 retval = (int)w32_child_pids[i];
1144 Copy(&w32_child_pids[i+1], &w32_child_pids[i],
1145 (w32_num_children-i-1), HANDLE);
1152 errno = GetLastError();
1158 static UINT timerid = 0;
1160 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1162 KillTimer(NULL,timerid);
1167 DllExport unsigned int
1168 win32_alarm(unsigned int sec)
1171 * the 'obvious' implentation is SetTimer() with a callback
1172 * which does whatever receiving SIGALRM would do
1173 * we cannot use SIGALRM even via raise() as it is not
1174 * one of the supported codes in <signal.h>
1176 * Snag is unless something is looking at the message queue
1177 * nothing happens :-(
1181 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1183 croak("Cannot set timer");
1189 KillTimer(NULL,timerid);
1196 #ifdef HAVE_DES_FCRYPT
1197 extern char * des_fcrypt(char *cbuf, const char *txt, const char *salt);
1200 win32_crypt(const char *txt, const char *salt)
1203 return des_fcrypt(crypt_buffer, txt, salt);
1207 #ifdef USE_FIXED_OSFHANDLE
1209 EXTERN_C int __cdecl _alloc_osfhnd(void);
1210 EXTERN_C int __cdecl _set_osfhnd(int fh, long value);
1211 EXTERN_C void __cdecl _lock_fhandle(int);
1212 EXTERN_C void __cdecl _unlock_fhandle(int);
1213 EXTERN_C void __cdecl _unlock(int);
1215 #if (_MSC_VER >= 1000)
1217 long osfhnd; /* underlying OS file HANDLE */
1218 char osfile; /* attributes of file (e.g., open in text mode?) */
1219 char pipech; /* one char buffer for handles opened on pipes */
1220 #if defined (_MT) && !defined (DLL_FOR_WIN32S)
1222 CRITICAL_SECTION lock;
1223 #endif /* defined (_MT) && !defined (DLL_FOR_WIN32S) */
1226 EXTERN_C ioinfo * __pioinfo[];
1228 #define IOINFO_L2E 5
1229 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
1230 #define _pioinfo(i) (__pioinfo[i >> IOINFO_L2E] + (i & (IOINFO_ARRAY_ELTS - 1)))
1231 #define _osfile(i) (_pioinfo(i)->osfile)
1233 #else /* (_MSC_VER >= 1000) */
1234 extern char _osfile[];
1235 #endif /* (_MSC_VER >= 1000) */
1237 #define FOPEN 0x01 /* file handle open */
1238 #define FAPPEND 0x20 /* file handle opened O_APPEND */
1239 #define FDEV 0x40 /* file handle refers to device */
1240 #define FTEXT 0x80 /* file handle is in text mode */
1242 #define _STREAM_LOCKS 26 /* Table of stream locks */
1243 #define _LAST_STREAM_LOCK (_STREAM_LOCKS+_NSTREAM_-1) /* Last stream lock */
1244 #define _FH_LOCKS (_LAST_STREAM_LOCK+1) /* Table of fh locks */
1247 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1250 * This function allocates a free C Runtime file handle and associates
1251 * it with the Win32 HANDLE specified by the first parameter. This is a
1252 * temperary fix for WIN95's brain damage GetFileType() error on socket
1253 * we just bypass that call for socket
1256 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1257 * int flags - flags to associate with C Runtime file handle.
1260 * returns index of entry in fh, if successful
1261 * return -1, if no free entry is found
1265 *******************************************************************************/
1268 my_open_osfhandle(long osfhandle, int flags)
1271 char fileflags; /* _osfile flags */
1273 /* copy relevant flags from second parameter */
1276 if (flags & O_APPEND)
1277 fileflags |= FAPPEND;
1282 /* attempt to allocate a C Runtime file handle */
1283 if ((fh = _alloc_osfhnd()) == -1) {
1284 errno = EMFILE; /* too many open files */
1285 _doserrno = 0L; /* not an OS error */
1286 return -1; /* return error to caller */
1289 /* the file is open. now, set the info in _osfhnd array */
1290 _set_osfhnd(fh, osfhandle);
1292 fileflags |= FOPEN; /* mark as open */
1294 #if (_MSC_VER >= 1000)
1295 _osfile(fh) = fileflags; /* set osfile entry */
1296 _unlock_fhandle(fh);
1298 _osfile[fh] = fileflags; /* set osfile entry */
1299 _unlock(fh+_FH_LOCKS); /* unlock handle */
1302 return fh; /* return handle */
1305 #define _open_osfhandle my_open_osfhandle
1306 #endif /* USE_FIXED_OSFHANDLE */
1308 /* simulate flock by locking a range on the file */
1310 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1311 #define LK_LEN 0xffff0000
1314 win32_flock(int fd, int oper)
1321 croak("flock() unimplemented on this platform");
1324 fh = (HANDLE)_get_osfhandle(fd);
1325 memset(&o, 0, sizeof(o));
1328 case LOCK_SH: /* shared lock */
1329 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1331 case LOCK_EX: /* exclusive lock */
1332 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1334 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1335 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1337 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1338 LK_ERR(LockFileEx(fh,
1339 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1340 0, LK_LEN, 0, &o),i);
1342 case LOCK_UN: /* unlock lock */
1343 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1345 default: /* unknown */
1356 * redirected io subsystem for all XS modules
1369 return (&(_environ));
1372 /* the rest are the remapped stdio routines */
1392 win32_ferror(FILE *fp)
1394 return (ferror(fp));
1399 win32_feof(FILE *fp)
1405 * Since the errors returned by the socket error function
1406 * WSAGetLastError() are not known by the library routine strerror
1407 * we have to roll our own.
1411 win32_strerror(int e)
1413 #ifndef __BORLANDC__ /* Borland intolerance */
1414 extern int sys_nerr;
1418 if (e < 0 || e > sys_nerr) {
1423 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
1424 strerror_buffer, sizeof(strerror_buffer), NULL) == 0)
1425 strcpy(strerror_buffer, "Unknown Error");
1427 return strerror_buffer;
1433 win32_str_os_error(void *sv, DWORD dwErr)
1437 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
1438 |FORMAT_MESSAGE_IGNORE_INSERTS
1439 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
1440 dwErr, 0, (char *)&sMsg, 1, NULL);
1442 while (0 < dwLen && isspace(sMsg[--dwLen]))
1444 if ('.' != sMsg[dwLen])
1449 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
1450 dwLen = sprintf(sMsg,
1451 "Unknown error #0x%lX (lookup 0x%lX)",
1452 dwErr, GetLastError());
1454 sv_setpvn((SV*)sv, sMsg, dwLen);
1460 win32_fprintf(FILE *fp, const char *format, ...)
1463 va_start(marker, format); /* Initialize variable arguments. */
1465 return (vfprintf(fp, format, marker));
1469 win32_printf(const char *format, ...)
1472 va_start(marker, format); /* Initialize variable arguments. */
1474 return (vprintf(format, marker));
1478 win32_vfprintf(FILE *fp, const char *format, va_list args)
1480 return (vfprintf(fp, format, args));
1484 win32_vprintf(const char *format, va_list args)
1486 return (vprintf(format, args));
1490 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
1492 return fread(buf, size, count, fp);
1496 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
1498 return fwrite(buf, size, count, fp);
1502 win32_fopen(const char *filename, const char *mode)
1504 if (stricmp(filename, "/dev/null")==0)
1505 return fopen("NUL", mode);
1506 return fopen(filename, mode);
1509 #ifndef USE_SOCKETS_AS_HANDLES
1511 #define fdopen my_fdopen
1515 win32_fdopen( int handle, const char *mode)
1517 return fdopen(handle, (char *) mode);
1521 win32_freopen( const char *path, const char *mode, FILE *stream)
1523 if (stricmp(path, "/dev/null")==0)
1524 return freopen("NUL", mode, stream);
1525 return freopen(path, mode, stream);
1529 win32_fclose(FILE *pf)
1531 return my_fclose(pf); /* defined in win32sck.c */
1535 win32_fputs(const char *s,FILE *pf)
1537 return fputs(s, pf);
1541 win32_fputc(int c,FILE *pf)
1547 win32_ungetc(int c,FILE *pf)
1549 return ungetc(c,pf);
1553 win32_getc(FILE *pf)
1559 win32_fileno(FILE *pf)
1565 win32_clearerr(FILE *pf)
1572 win32_fflush(FILE *pf)
1578 win32_ftell(FILE *pf)
1584 win32_fseek(FILE *pf,long offset,int origin)
1586 return fseek(pf, offset, origin);
1590 win32_fgetpos(FILE *pf,fpos_t *p)
1592 return fgetpos(pf, p);
1596 win32_fsetpos(FILE *pf,const fpos_t *p)
1598 return fsetpos(pf, p);
1602 win32_rewind(FILE *pf)
1622 win32_fstat(int fd,struct stat *sbufptr)
1624 return fstat(fd,sbufptr);
1628 win32_pipe(int *pfd, unsigned int size, int mode)
1630 return _pipe(pfd, size, mode);
1634 * a popen() clone that respects PERL5SHELL
1638 win32_popen(const char *command, const char *mode)
1640 #ifdef USE_CRT_POPEN
1641 return _popen(command, mode);
1649 /* establish which ends read and write */
1650 if (strchr(mode,'w')) {
1651 stdfd = 0; /* stdin */
1655 else if (strchr(mode,'r')) {
1656 stdfd = 1; /* stdout */
1663 /* set the correct mode */
1664 if (strchr(mode,'b'))
1666 else if (strchr(mode,'t'))
1669 ourmode = _fmode & (O_TEXT | O_BINARY);
1671 /* the child doesn't inherit handles */
1672 ourmode |= O_NOINHERIT;
1674 if (win32_pipe( p, 512, ourmode) == -1)
1677 /* save current stdfd */
1678 if ((oldfd = win32_dup(stdfd)) == -1)
1681 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
1682 /* stdfd will be inherited by the child */
1683 if (win32_dup2(p[child], stdfd) == -1)
1686 /* close the child end in parent */
1687 win32_close(p[child]);
1689 /* start the child */
1690 if ((childpid = do_spawn_nowait((char*)command)) == -1)
1693 /* revert stdfd to whatever it was before */
1694 if (win32_dup2(oldfd, stdfd) == -1)
1697 /* close saved handle */
1700 w32_popen_pids[p[parent]] = childpid;
1702 /* we have an fd, return a file stream */
1703 return (win32_fdopen(p[parent], (char *)mode));
1706 /* we don't need to check for errors here */
1710 win32_dup2(oldfd, stdfd);
1715 #endif /* USE_CRT_POPEN */
1723 win32_pclose(FILE *pf)
1725 #ifdef USE_CRT_POPEN
1728 int fd, childpid, status;
1730 fd = win32_fileno(pf);
1731 childpid = w32_popen_pids[fd];
1739 w32_popen_pids[fd] = 0;
1741 /* wait for the child */
1742 if (cwait(&status, childpid, WAIT_CHILD) == -1)
1744 /* cwait() returns differently on Borland */
1746 return (((status >> 8) & 0xff) | ((status << 8) & 0xff00));
1751 #endif /* USE_CRT_OPEN */
1755 win32_setmode(int fd, int mode)
1757 return setmode(fd, mode);
1761 win32_lseek(int fd, long offset, int origin)
1763 return lseek(fd, offset, origin);
1773 win32_open(const char *path, int flag, ...)
1779 pmode = va_arg(ap, int);
1782 if (stricmp(path, "/dev/null")==0)
1783 return open("NUL", flag, pmode);
1784 return open(path,flag,pmode);
1806 win32_dup2(int fd1,int fd2)
1808 return dup2(fd1,fd2);
1812 win32_read(int fd, void *buf, unsigned int cnt)
1814 return read(fd, buf, cnt);
1818 win32_write(int fd, const void *buf, unsigned int cnt)
1820 return write(fd, buf, cnt);
1824 win32_mkdir(const char *dir, int mode)
1826 return mkdir(dir); /* just ignore mode */
1830 win32_rmdir(const char *dir)
1836 win32_chdir(const char *dir)
1842 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
1846 status = spawnvp(mode, cmdname, (char * const *) argv);
1847 #ifndef __BORLANDC__
1848 /* XXX For the P_NOWAIT case, Borland RTL returns pinfo.dwProcessId
1849 * while VC RTL returns pinfo.hProcess. For purposes of the custom
1850 * implementation of win32_wait(), we assume the latter.
1852 if (mode == P_NOWAIT && status >= 0)
1853 w32_child_pids[w32_num_children++] = (HANDLE)status;
1859 win32_execvp(const char *cmdname, const char *const *argv)
1861 return execvp(cmdname, (char *const *)argv);
1865 win32_perror(const char *str)
1871 win32_setbuf(FILE *pf, char *buf)
1877 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
1879 return setvbuf(pf, buf, type, size);
1883 win32_flushall(void)
1889 win32_fcloseall(void)
1895 win32_fgets(char *s, int n, FILE *pf)
1897 return fgets(s, n, pf);
1907 win32_fgetc(FILE *pf)
1913 win32_putc(int c, FILE *pf)
1919 win32_puts(const char *s)
1931 win32_putchar(int c)
1938 #ifndef USE_PERL_SBRK
1940 static char *committed = NULL;
1941 static char *base = NULL;
1942 static char *reserved = NULL;
1943 static char *brk = NULL;
1944 static DWORD pagesize = 0;
1945 static DWORD allocsize = 0;
1953 GetSystemInfo(&info);
1954 /* Pretend page size is larger so we don't perpetually
1955 * call the OS to commit just one page ...
1957 pagesize = info.dwPageSize << 3;
1958 allocsize = info.dwAllocationGranularity;
1960 /* This scheme fails eventually if request for contiguous
1961 * block is denied so reserve big blocks - this is only
1962 * address space not memory ...
1964 if (brk+need >= reserved)
1966 DWORD size = 64*1024*1024;
1968 if (committed && reserved && committed < reserved)
1970 /* Commit last of previous chunk cannot span allocations */
1971 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
1973 committed = reserved;
1975 /* Reserve some (more) space
1976 * Note this is a little sneaky, 1st call passes NULL as reserved
1977 * so lets system choose where we start, subsequent calls pass
1978 * the old end address so ask for a contiguous block
1980 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
1983 reserved = addr+size;
1998 if (brk > committed)
2000 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
2001 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
2016 win32_malloc(size_t size)
2018 return malloc(size);
2022 win32_calloc(size_t numitems, size_t size)
2024 return calloc(numitems,size);
2028 win32_realloc(void *block, size_t size)
2030 return realloc(block,size);
2034 win32_free(void *block)
2041 win32_open_osfhandle(long handle, int flags)
2043 return _open_osfhandle(handle, flags);
2047 win32_get_osfhandle(int fd)
2049 return _get_osfhandle(fd);
2060 SV *sv = sv_newmortal();
2061 /* Make one call with zero size - return value is required size */
2062 DWORD len = GetCurrentDirectory((DWORD)0,NULL);
2063 SvUPGRADE(sv,SVt_PV);
2065 SvCUR(sv) = GetCurrentDirectory((DWORD) SvLEN(sv), SvPVX(sv));
2068 * then it worked, set PV valid,
2069 * else leave it 'undef'
2083 croak("usage: Win32::SetCurrentDirectory($cwd)");
2084 if (SetCurrentDirectory(SvPV(ST(0),na)))
2091 XS(w32_GetNextAvailDrive)
2095 char root[] = "_:\\";
2098 if (GetDriveType(root) == 1) {
2107 XS(w32_GetLastError)
2110 XSRETURN_IV(GetLastError());
2117 char *name = getlogin_buffer;
2118 DWORD size = sizeof(getlogin_buffer);
2119 if (GetUserName(name,&size)) {
2120 /* size includes NULL */
2121 ST(0) = sv_2mortal(newSVpv(name,size-1));
2131 char name[MAX_COMPUTERNAME_LENGTH+1];
2132 DWORD size = sizeof(name);
2133 if (GetComputerName(name,&size)) {
2134 /* size does NOT include NULL :-( */
2135 ST(0) = sv_2mortal(newSVpv(name,size));
2146 #ifndef HAS_NETWKSTAGETINFO
2147 /* mingw32 (and Win95) don't have NetWksta*(), so do it the old way */
2149 DWORD size = sizeof(name);
2150 if (GetUserName(name,&size)) {
2152 DWORD sidlen = sizeof(sid);
2154 DWORD dnamelen = sizeof(dname);
2156 if (LookupAccountName(NULL, name, &sid, &sidlen,
2157 dname, &dnamelen, &snu)) {
2158 XSRETURN_PV(dname); /* all that for this */
2162 /* this way is more reliable, in case user has a local account.
2163 * XXX need dynamic binding of netapi32.dll symbols or this will fail on
2164 * Win95. Probably makes more sense to move it into libwin32. */
2166 DWORD dnamelen = sizeof(dname);
2167 PWKSTA_INFO_100 pwi;
2168 if (NERR_Success == NetWkstaGetInfo(NULL, 100, (LPBYTE*)&pwi)) {
2169 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
2170 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
2171 -1, (LPSTR)dname, dnamelen, NULL, NULL);
2174 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
2175 -1, (LPSTR)dname, dnamelen, NULL, NULL);
2177 NetApiBufferFree(pwi);
2189 DWORD flags, filecomplen;
2190 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
2191 &flags, fsname, sizeof(fsname))) {
2192 if (GIMME == G_ARRAY) {
2193 XPUSHs(sv_2mortal(newSVpv(fsname,0)));
2194 XPUSHs(sv_2mortal(newSViv(flags)));
2195 XPUSHs(sv_2mortal(newSViv(filecomplen)));
2199 XSRETURN_PV(fsname);
2205 XS(w32_GetOSVersion)
2208 OSVERSIONINFO osver;
2210 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
2211 if (GetVersionEx(&osver)) {
2212 XPUSHs(newSVpv(osver.szCSDVersion, 0));
2213 XPUSHs(newSViv(osver.dwMajorVersion));
2214 XPUSHs(newSViv(osver.dwMinorVersion));
2215 XPUSHs(newSViv(osver.dwBuildNumber));
2216 XPUSHs(newSViv(osver.dwPlatformId));
2227 XSRETURN_IV(IsWinNT());
2234 XSRETURN_IV(IsWin95());
2238 XS(w32_FormatMessage)
2245 croak("usage: Win32::FormatMessage($errno)");
2247 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
2248 &source, SvIV(ST(0)), 0,
2249 msgbuf, sizeof(msgbuf)-1, NULL))
2250 XSRETURN_PV(msgbuf);
2260 PROCESS_INFORMATION stProcInfo;
2261 STARTUPINFO stStartInfo;
2262 BOOL bSuccess = FALSE;
2265 croak("usage: Win32::Spawn($cmdName, $args, $PID)");
2267 cmd = SvPV(ST(0),na);
2268 args = SvPV(ST(1), na);
2270 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
2271 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
2272 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
2273 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
2276 cmd, /* Image path */
2277 args, /* Arguments for command line */
2278 NULL, /* Default process security */
2279 NULL, /* Default thread security */
2280 FALSE, /* Must be TRUE to use std handles */
2281 NORMAL_PRIORITY_CLASS, /* No special scheduling */
2282 NULL, /* Inherit our environment block */
2283 NULL, /* Inherit our currrent directory */
2284 &stStartInfo, /* -> Startup info */
2285 &stProcInfo)) /* <- Process info (if OK) */
2287 CloseHandle(stProcInfo.hThread);/* library source code does this. */
2288 sv_setiv(ST(2), stProcInfo.dwProcessId);
2291 XSRETURN_IV(bSuccess);
2295 XS(w32_GetTickCount)
2298 XSRETURN_IV(GetTickCount());
2302 XS(w32_GetShortPathName)
2309 croak("usage: Win32::GetShortPathName($longPathName)");
2311 shortpath = sv_mortalcopy(ST(0));
2312 SvUPGRADE(shortpath, SVt_PV);
2313 /* src == target is allowed */
2315 len = GetShortPathName(SvPVX(shortpath),
2318 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
2320 SvCUR_set(shortpath,len);
2333 croak("usage: Win32::Sleep($milliseconds)");
2338 #define TMPBUFSZ 1024
2339 #define MAX_LENGTH 2048
2340 #define SUCCESSRETURNED(x) (x == ERROR_SUCCESS)
2341 #define REGRETURN(x) XSRETURN_IV(SUCCESSRETURNED(x))
2342 #define SvHKEY(index) (HKEY)((unsigned long)SvIV(index))
2343 #define SETIV(index,value) sv_setiv(ST(index), value)
2344 #define SETNV(index,value) sv_setnv(ST(index), value)
2345 #define SETPV(index,string) sv_setpv(ST(index), string)
2346 #define SETPVN(index, buffer, length) sv_setpvn(ST(index), (char*)buffer, length)
2347 #define SETHKEY(index, hkey) SETIV(index,(long)hkey)
2349 static time_t ft2timet(FILETIME *ft)
2354 FileTimeToSystemTime(ft, &st);
2355 tm.tm_sec = st.wSecond;
2356 tm.tm_min = st.wMinute;
2357 tm.tm_hour = st.wHour;
2358 tm.tm_mday = st.wDay;
2359 tm.tm_mon = st.wMonth - 1;
2360 tm.tm_year = st.wYear - 1900;
2361 tm.tm_wday = st.wDayOfWeek;
2364 return mktime (&tm);
2374 croak("usage: Win32::RegCloseKey($hkey);\n");
2377 REGRETURN(RegCloseKey(SvHKEY(ST(0))));
2381 XS(w32_RegConnectRegistry)
2388 croak("usage: Win32::RegConnectRegistry($machine, $hkey, $handle);\n");
2391 if (SUCCESSRETURNED(RegConnectRegistry((char *)SvPV(ST(0), na), SvHKEY(ST(1)), &handle)))
2400 XS(w32_RegCreateKey)
2409 croak("usage: Win32::RegCreateKey($hkey, $subkey, $handle);\n");
2412 retval = RegCreateKeyEx(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS,
2413 NULL, &handle, &disposition);
2415 if (SUCCESSRETURNED(retval))
2424 XS(w32_RegCreateKeyEx)
2428 unsigned int length;
2433 DWORD options, disposition;
2435 SECURITY_ATTRIBUTES sa, *psa;
2439 croak("usage: Win32::RegCreateKeyEx($hkey, $subkey, $reserved, $class, $options, $sam, "
2440 "$security, $handle, $disposition);\n");
2443 hkey = SvHKEY(ST(0));
2444 subkey = (char *)SvPV(ST(1), na);
2445 keyclass = (char *)SvPV(ST(3), na);
2446 options = (DWORD) ((unsigned long)SvIV(ST(4)));
2447 sam = (REGSAM) ((unsigned long)SvIV(ST(5)));
2448 psa = (SECURITY_ATTRIBUTES*)SvPV(ST(6), length);
2449 if (length != sizeof(SECURITY_ATTRIBUTES))
2452 memset(&sa, 0, sizeof(SECURITY_ATTRIBUTES));
2453 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
2456 retval = RegCreateKeyEx(hkey, subkey, 0, keyclass, options, sam,
2457 psa, &handle, &disposition);
2459 if (SUCCESSRETURNED(retval))
2462 SETPVN(6, &sa, sizeof(sa));
2465 SETIV(8,disposition);
2472 XS(w32_RegDeleteKey)
2478 croak("usage: Win32::RegDeleteKey($hkey, $subkey);\n");
2481 REGRETURN(RegDeleteKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na)));
2485 XS(w32_RegDeleteValue)
2491 croak("usage: Win32::RegDeleteValue($hkey, $valname);\n");
2494 REGRETURN(RegDeleteValue(SvHKEY(ST(0)), (char *)SvPV(ST(1), na)));
2502 char keybuffer[TMPBUFSZ];
2506 croak("usage: Win32::RegEnumKey($hkey, $idx, $subkeyname);\n");
2509 if (SUCCESSRETURNED(RegEnumKey(SvHKEY(ST(0)), SvIV(ST(1)), keybuffer, sizeof(keybuffer))))
2511 SETPV(2, keybuffer);
2518 XS(w32_RegEnumKeyEx)
2523 DWORD keysz, classsz;
2524 char keybuffer[TMPBUFSZ];
2525 char classbuffer[TMPBUFSZ];
2531 croak("usage: Win32::RegEnumKeyEx($hkey, $idx, $subkeyname, $reserved, $class, $time);\n");
2534 keysz = sizeof(keybuffer);
2535 classsz = sizeof(classbuffer);
2536 retval = RegEnumKeyEx(SvHKEY(ST(0)), SvIV(ST(1)), keybuffer, &keysz, 0,
2537 classbuffer, &classsz, &filetime);
2538 if (SUCCESSRETURNED(retval))
2540 SETPV(2, keybuffer);
2541 SETPV(4, classbuffer);
2542 SETIV(5, ft2timet(&filetime));
2549 XS(w32_RegEnumValue)
2553 DWORD type, namesz, valsz;
2555 static HKEY last_hkey;
2556 char myvalbuf[MAX_LENGTH];
2557 char mynambuf[MAX_LENGTH];
2561 croak("usage: Win32::RegEnumValue($hkey, $i, $name, $reserved, $type, $value);\n");
2564 hkey = SvHKEY(ST(0));
2566 // If this is a new key, find out how big the maximum name and value sizes are and
2567 // allocate space for them. Free any old storage and set the old key value to the
2570 if (hkey != (HKEY)last_hkey)
2572 char keyclass[TMPBUFSZ];
2573 DWORD classsz, subkeys, maxsubkey, maxclass, values, salen, maxnamesz, maxvalsz;
2575 classsz = sizeof(keyclass);
2576 retval = RegQueryInfoKey(hkey, keyclass, &classsz, 0, &subkeys, &maxsubkey, &maxclass,
2577 &values, &maxnamesz, &maxvalsz, &salen, &ft);
2579 if (!SUCCESSRETURNED(retval))
2583 memset(myvalbuf, 0, MAX_LENGTH);
2584 memset(mynambuf, 0, MAX_LENGTH);
2588 namesz = MAX_LENGTH;
2590 retval = RegEnumValue(hkey, SvIV(ST(1)), mynambuf, &namesz, 0, &type, (LPBYTE) myvalbuf, &valsz);
2591 if (!SUCCESSRETURNED(retval))
2600 // return includes the null terminator so delete it if REG_SZ, REG_MULTI_SZ or REG_EXPAND_SZ
2609 SETPVN(5, myvalbuf, valsz);
2612 case REG_DWORD_BIG_ENDIAN:
2614 BYTE tmp = myvalbuf[0];
2615 myvalbuf[0] = myvalbuf[3];
2618 myvalbuf[1] = myvalbuf[2];
2621 case REG_DWORD_LITTLE_ENDIAN: // same as REG_DWORD
2622 SETNV(5, (double)*((DWORD*)myvalbuf));
2640 croak("usage: Win32::RegFlushKey($hkey);\n");
2643 REGRETURN(RegFlushKey(SvHKEY(ST(0))));
2647 XS(w32_RegGetKeySecurity)
2650 SECURITY_DESCRIPTOR sd;
2655 croak("usage: Win32::RegGetKeySecurity($hkey, $security_info, $security_descriptor);\n");
2658 if (SUCCESSRETURNED(RegGetKeySecurity(SvHKEY(ST(0)), SvIV(ST(1)), &sd, &sdsz)))
2660 SETPVN(2, &sd, sdsz);
2673 croak("usage: Win32::RegLoadKey($hkey, $subkey, $filename);\n");
2676 REGRETURN(RegLoadKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), (char *)SvPV(ST(2), na)));
2680 XS(w32_RegNotifyChangeKeyValue)
2682 croak("Win32::RegNotifyChangeKeyValue not yet implemented!\n");
2693 croak("usage: Win32::RegOpenKey($hkey, $subkey, $handle);\n");
2696 if (SUCCESSRETURNED(RegOpenKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), &handle)))
2705 XS(w32_RegOpenKeyEx)
2712 croak("usage: Win32::RegOpenKeyEx($hkey, $subkey, $reserved, $sam, $handle);\n");
2715 if (SUCCESSRETURNED(RegOpenKeyEx(SvHKEY(ST(0)), (char *)SvPV(ST(1), na),
2716 0, (REGSAM) ((unsigned long)SvIV(ST(3))), &handle)))
2724 #pragma optimize("", off)
2726 XS(w32_RegQueryInfoKey)
2731 char keyclass[TMPBUFSZ];
2732 DWORD subkeys, maxsubkey, maxclass, values, maxvalname, maxvaldata;
2733 DWORD seclen, classsz;
2739 croak("usage: Win32::RegQueryInfoKey($hkey, $class, $numsubkeys, $maxsubkey,"
2740 "$maxclass, $values, $maxvalname, $maxvaldata, $secdesclen,"
2741 "$lastwritetime);\n");
2744 classsz = sizeof(keyclass);
2745 retval = RegQueryInfoKey(SvHKEY(ST(0)), keyclass, &classsz, 0, &subkeys, &maxsubkey,
2746 &maxclass, &values, &maxvalname, &maxvaldata,
2748 if (SUCCESSRETURNED(retval))
2752 SETIV(3, maxsubkey);
2755 SETIV(6, maxvalname);
2756 SETIV(7, maxvaldata);
2758 SETIV(9, ft2timet(&ft));
2763 #pragma optimize("", on)
2766 XS(w32_RegQueryValue)
2770 unsigned char databuffer[TMPBUFSZ*2];
2771 long datasz = sizeof(databuffer);
2775 croak("usage: Win32::RegQueryValue($hkey, $valuename, $data);\n");
2778 if (SUCCESSRETURNED(RegQueryValue(SvHKEY(ST(0)), SvPV(ST(1), na), (char*)databuffer, &datasz)))
2780 // return includes the null terminator so delete it
2781 SETPVN(2, databuffer, --datasz);
2788 XS(w32_RegQueryValueEx)
2792 unsigned char databuffer[TMPBUFSZ*2];
2793 DWORD datasz = sizeof(databuffer);
2796 LPBYTE ptr = databuffer;
2800 croak("usage: Win32::RegQueryValueEx($hkey, $valuename, $reserved, $type, $data);\n");
2803 result = RegQueryValueEx(SvHKEY(ST(0)), SvPV(ST(1), na), 0, &type, ptr, &datasz);
2804 if (result == ERROR_MORE_DATA)
2806 New(0, ptr, datasz+1, BYTE);
2807 result = RegQueryValueEx(SvHKEY(ST(0)), SvPV(ST(1), na), 0, &type, ptr, &datasz);
2809 if (SUCCESSRETURNED(result))
2813 // return includes the null terminator so delete it if REG_SZ, REG_MULTI_SZ or REG_EXPAND_SZ
2821 SETPVN(4, ptr, datasz);
2824 case REG_DWORD_BIG_ENDIAN:
2833 case REG_DWORD_LITTLE_ENDIAN: // same as REG_DWORD
2834 SETNV(4, (double)*((DWORD*)ptr));
2841 if (ptr != databuffer)
2846 if (ptr != databuffer)
2853 XS(w32_RegReplaceKey)
2859 croak("usage: Win32::RegReplaceKey($hkey, $subkey, $newfile, $oldfile);\n");
2862 REGRETURN(RegReplaceKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), (char *)SvPV(ST(2), na), (char *)SvPV(ST(3), na)));
2866 XS(w32_RegRestoreKey)
2870 if (items < 2 || items > 3)
2872 croak("usage: Win32::RegRestoreKey($hkey, $filename [, $flags]);\n");
2875 REGRETURN(RegRestoreKey(SvHKEY(ST(0)), (char*)SvPV(ST(1), na), (DWORD)((items == 3) ? SvIV(ST(2)) : 0)));
2885 croak("usage: Win32::RegSaveKey($hkey, $filename);\n");
2888 REGRETURN(RegSaveKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), NULL));
2892 XS(w32_RegSetKeySecurity)
2898 croak("usage: Win32::RegSetKeySecurity($hkey, $security_info, $security_descriptor);\n");
2901 REGRETURN(RegSetKeySecurity(SvHKEY(ST(0)), SvIV(ST(1)), (SECURITY_DESCRIPTOR*)SvPV(ST(2), na)));
2914 croak("usage: Win32::RegSetValue($hkey, $subKey, $type, $data);\n");
2917 DWORD type = SvIV(ST(2));
2918 if (type != REG_SZ && type != REG_EXPAND_SZ)
2920 croak("Win32::RegSetValue: Type was not REG_SZ or REG_EXPAND_SZ, cannot set %s\n", (char *)SvPV(ST(1), na));
2923 buffer = (char *)SvPV(ST(3), size);
2924 REGRETURN(RegSetValue(SvHKEY(ST(0)), SvPV(ST(1), na), REG_SZ, buffer, size));
2928 XS(w32_RegSetValueEx)
2939 croak("usage: Win32::RegSetValueEx($hkey, $valname, $reserved, $type, $data);\n");
2942 type = (DWORD)SvIV(ST(3));
2949 buffer = (char *)SvPV(ST(4), size);
2950 if (type != REG_BINARY)
2951 size++; // include null terminator in size
2953 REGRETURN(RegSetValueEx(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), 0, type, (PBYTE) buffer, size));
2956 case REG_DWORD_BIG_ENDIAN:
2957 case REG_DWORD_LITTLE_ENDIAN: // Same as REG_DWORD
2958 val = (DWORD)SvIV(ST(4));
2959 REGRETURN(RegSetValueEx(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), 0, type, (PBYTE) &val, sizeof(DWORD)));
2963 croak("Win32::RegSetValueEx: Type not specified, cannot set %s\n", (char *)SvPV(ST(1), na));
2968 XS(w32_RegUnloadKey)
2974 croak("usage: Win32::RegUnLoadKey($hkey, $subkey);\n");
2977 REGRETURN(RegUnLoadKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na)));
2981 XS(w32_RegisterServer)
2984 BOOL bSuccess = FALSE;
2985 HINSTANCE hInstance;
2986 unsigned int length;
2991 croak("usage: Win32::RegisterServer($LibraryName)\n");
2994 hInstance = LoadLibrary((char *)SvPV(ST(0), length));
2995 if (hInstance != NULL)
2997 sFunc = GetProcAddress(hInstance, "DllRegisterServer");
3000 bSuccess = (sFunc() == 0);
3002 FreeLibrary(hInstance);
3013 XS(w32_UnregisterServer)
3016 BOOL bSuccess = FALSE;
3017 HINSTANCE hInstance;
3018 unsigned int length;
3023 croak("usage: Win32::UnregisterServer($LibraryName)\n");
3026 hInstance = LoadLibrary((char *)SvPV(ST(0), length));
3027 if (hInstance != NULL)
3029 sFunc = GetProcAddress(hInstance, "DllUnregisterServer");
3032 bSuccess = (sFunc() == 0);
3034 FreeLibrary(hInstance);
3046 Perl_init_os_extras()
3048 char *file = __FILE__;
3051 /* these names are Activeware compatible */
3052 newXS("Win32::GetCwd", w32_GetCwd, file);
3053 newXS("Win32::SetCwd", w32_SetCwd, file);
3054 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
3055 newXS("Win32::GetLastError", w32_GetLastError, file);
3056 newXS("Win32::LoginName", w32_LoginName, file);
3057 newXS("Win32::NodeName", w32_NodeName, file);
3058 newXS("Win32::DomainName", w32_DomainName, file);
3059 newXS("Win32::FsType", w32_FsType, file);
3060 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
3061 newXS("Win32::IsWinNT", w32_IsWinNT, file);
3062 newXS("Win32::IsWin95", w32_IsWin95, file);
3063 newXS("Win32::FormatMessage", w32_FormatMessage, file);
3064 newXS("Win32::Spawn", w32_Spawn, file);
3065 newXS("Win32::GetTickCount", w32_GetTickCount, file);
3066 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
3067 newXS("Win32::Sleep", w32_Sleep, file);
3069 /* the following extensions are used interally and may be changed at any time */
3070 /* therefore no documentation is provided */
3071 newXS("Win32::RegCloseKey", w32_RegCloseKey, file);
3072 newXS("Win32::RegConnectRegistry", w32_RegConnectRegistry, file);
3073 newXS("Win32::RegCreateKey", w32_RegCreateKey, file);
3074 newXS("Win32::RegCreateKeyEx", w32_RegCreateKeyEx, file);
3075 newXS("Win32::RegDeleteKey", w32_RegDeleteKey, file);
3076 newXS("Win32::RegDeleteValue", w32_RegDeleteValue, file);
3078 newXS("Win32::RegEnumKey", w32_RegEnumKey, file);
3079 newXS("Win32::RegEnumKeyEx", w32_RegEnumKeyEx, file);
3080 newXS("Win32::RegEnumValue", w32_RegEnumValue, file);
3082 newXS("Win32::RegFlushKey", w32_RegFlushKey, file);
3083 newXS("Win32::RegGetKeySecurity", w32_RegGetKeySecurity, file);
3085 newXS("Win32::RegLoadKey", w32_RegLoadKey, file);
3086 newXS("Win32::RegOpenKey", w32_RegOpenKey, file);
3087 newXS("Win32::RegOpenKeyEx", w32_RegOpenKeyEx, file);
3088 newXS("Win32::RegQueryInfoKey", w32_RegQueryInfoKey, file);
3089 newXS("Win32::RegQueryValue", w32_RegQueryValue, file);
3090 newXS("Win32::RegQueryValueEx", w32_RegQueryValueEx, file);
3092 newXS("Win32::RegReplaceKey", w32_RegReplaceKey, file);
3093 newXS("Win32::RegRestoreKey", w32_RegRestoreKey, file);
3094 newXS("Win32::RegSaveKey", w32_RegSaveKey, file);
3095 newXS("Win32::RegSetKeySecurity", w32_RegSetKeySecurity, file);
3096 newXS("Win32::RegSetValue", w32_RegSetValue, file);
3097 newXS("Win32::RegSetValueEx", w32_RegSetValueEx, file);
3098 newXS("Win32::RegUnloadKey", w32_RegUnloadKey, file);
3100 newXS("Win32::RegisterServer", w32_RegisterServer, file);
3101 newXS("Win32::UnregisterServer", w32_UnregisterServer, file);
3103 /* XXX Bloat Alert! The following Activeware preloads really
3104 * ought to be part of Win32::Sys::*, so they're not included
3107 /* LookupAccountName
3109 * InitiateSystemShutdown
3110 * AbortSystemShutdown
3111 * ExpandEnvrironmentStrings
3116 Perl_win32_init(int *argcp, char ***argvp)
3118 /* Disable floating point errors, Perl will trap the ones we
3119 * care about. VC++ RTL defaults to switching these off
3120 * already, but the Borland RTL doesn't. Since we don't
3121 * want to be at the vendor's whim on the default, we set
3122 * it explicitly here.
3124 #if !defined(_ALPHA_) && !defined(__GNUC__)
3125 _control87(MCW_EM, MCW_EM);
3130 #ifdef USE_BINMODE_SCRIPTS
3133 win32_strip_return(SV *sv)
3135 char *s = SvPVX(sv);
3136 char *e = s+SvCUR(sv);
3140 if (*s == '\r' && s[1] == '\n')
3150 SvCUR_set(sv,d-SvPVX(sv));