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_privlib
81 #define win32_get_privlib g_win32_get_privlib
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);
113 static char * get_emd_part(char *leading, char *trailing, ...);
115 HANDLE w32_perldll_handle = INVALID_HANDLE_VALUE;
116 static DWORD w32_platform = (DWORD)-1;
119 # ifdef USE_DECLSPEC_THREAD
120 __declspec(thread) char strerror_buffer[512];
121 __declspec(thread) char getlogin_buffer[128];
122 __declspec(thread) char w32_perllib_root[MAX_PATH+1];
123 # ifdef HAVE_DES_FCRYPT
124 __declspec(thread) char crypt_buffer[30];
127 # define strerror_buffer (thr->i.Wstrerror_buffer)
128 # define getlogin_buffer (thr->i.Wgetlogin_buffer)
129 # define w32_perllib_root (thr->i.Ww32_perllib_root)
130 # define crypt_buffer (thr->i.Wcrypt_buffer)
133 static char strerror_buffer[512];
134 static char getlogin_buffer[128];
135 static char w32_perllib_root[MAX_PATH+1];
136 # ifdef HAVE_DES_FCRYPT
137 static char crypt_buffer[30];
143 return (os_id() == VER_PLATFORM_WIN32_WINDOWS);
148 return (os_id() == VER_PLATFORM_WIN32_NT);
152 GetRegStrFromKey(HKEY hkey, const char *lpszValueName, char** ptr, DWORD* lpDataLen)
153 { /* Retrieve a REG_SZ or REG_EXPAND_SZ from the registry */
156 const char *subkey = "Software\\Perl";
159 retval = RegOpenKeyEx(hkey, subkey, 0, KEY_READ, &handle);
160 if (retval == ERROR_SUCCESS){
161 retval = RegQueryValueEx(handle, lpszValueName, 0, &type, NULL, lpDataLen);
162 if (retval == ERROR_SUCCESS && type == REG_SZ) {
164 Renew(*ptr, *lpDataLen, char);
167 New(1312, *ptr, *lpDataLen, char);
169 retval = RegQueryValueEx(handle, lpszValueName, 0, NULL, (PBYTE)*ptr, lpDataLen);
170 if (retval != ERROR_SUCCESS) {
181 GetRegStr(const char *lpszValueName, char** ptr, DWORD* lpDataLen)
183 *ptr = GetRegStrFromKey(HKEY_CURRENT_USER, lpszValueName, ptr, lpDataLen);
186 *ptr = GetRegStrFromKey(HKEY_LOCAL_MACHINE, lpszValueName, ptr, lpDataLen);
192 get_emd_part(char *prev_path, char *trailing_path, ...)
195 char mod_name[MAX_PATH];
199 int oldsize, newsize;
201 va_start(ap, trailing_path);
202 strip = va_arg(ap, char *);
204 GetModuleFileName(GetModuleHandle(NULL), mod_name, sizeof(mod_name));
205 ptr = strrchr(mod_name, '\\');
206 while (ptr && strip) {
207 /* look for directories to skip back */
210 ptr = strrchr(mod_name, '\\');
211 if (!ptr || stricmp(ptr+1, strip) != 0) {
215 strip = va_arg(ap, char *);
223 strcpy(++ptr, trailing_path);
225 newsize = strlen(mod_name) + 1;
227 oldsize = strlen(prev_path) + 1;
228 newsize += oldsize; /* includes plus 1 for ';' */
229 Renew(prev_path, newsize, char);
230 prev_path[oldsize] = ';';
231 strcpy(&prev_path[oldsize], mod_name);
234 New(1311, prev_path, newsize, char);
235 strcpy(prev_path, mod_name);
242 win32_get_privlib(char *pl)
244 char *stdlib = "lib";
245 char buffer[MAX_PATH+1];
249 /* $stdlib = $HKCU{"lib-$]"} || $HKLM{"lib-$]"} || $HKCU{"lib"} || $HKLM{"lib"} || ""; */
250 sprintf(buffer, "%s-%s", stdlib, pl);
251 path = GetRegStr(buffer, &path, &datalen);
253 path = GetRegStr(stdlib, &path, &datalen);
255 /* $stdlib .= ";$EMD/../../lib" */
256 return get_emd_part(path, stdlib, ARCHNAME, "bin", Nullch);
260 win32_get_sitelib(char *pl)
262 char *sitelib = "sitelib";
264 char pathstr[MAX_PATH];
266 char *path1 = Nullch;
267 char *path2 = Nullch;
270 /* $HKCU{"sitelib-$]"} || $HKLM{"sitelib-$]"} . ---; */
271 sprintf(regstr, "%s-%s", sitelib, pl);
272 path1 = GetRegStr(regstr, &path1, &datalen);
275 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/$]/lib"; */
276 sprintf(pathstr, "site\\%s\\lib", pl);
277 path1 = get_emd_part(path1, pathstr, ARCHNAME, "bin", pl, Nullch);
279 /* $HKCU{'sitelib'} || $HKLM{'sitelib'} . ---; */
280 path2 = GetRegStr(sitelib, &path2, &datalen);
283 * ";$EMD/" . ((-d $EMD/../../../$]) ? "../../.." : "../.."). "/site/lib"; */
284 path2 = get_emd_part(path2, "site\\lib", ARCHNAME, "bin", pl, Nullch);
293 newsize = len + strlen(path2) + 2; /* plus one for ';' */
295 Renew(path1, newsize, char);
297 strcpy(&path1[len], path2);
305 has_redirection(char *ptr)
311 * Scan string looking for redirection (< or >) or pipe
312 * characters (|) that are not in a quoted string
342 #if !defined(PERL_OBJECT)
343 /* since the current process environment is being updated in util.c
344 * the library functions will get the correct environment
347 my_popen(char *cmd, char *mode)
350 #define fixcmd(x) { \
351 char *pspace = strchr((x),' '); \
354 while (p < pspace) { \
365 win32_fflush(stdout);
366 win32_fflush(stderr);
367 return win32_popen(cmd, mode);
371 my_pclose(PerlIO *fp)
373 return win32_pclose(fp);
380 static OSVERSIONINFO osver;
382 if (osver.dwPlatformId != w32_platform) {
383 memset(&osver, 0, sizeof(OSVERSIONINFO));
384 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
385 GetVersionEx(&osver);
386 w32_platform = osver.dwPlatformId;
388 return (w32_platform);
391 /* Tokenize a string. Words are null-separated, and the list
392 * ends with a doubled null. Any character (except null and
393 * including backslash) may be escaped by preceding it with a
394 * backslash (the backslash will be stripped).
395 * Returns number of words in result buffer.
398 tokenize(char *str, char **dest, char ***destv)
400 char *retstart = Nullch;
401 char **retvstart = 0;
404 int slen = strlen(str);
406 register char **retv;
407 New(1307, ret, slen+2, char);
408 New(1308, retv, (slen+3)/2, char*);
416 if (*ret == '\\' && *str)
418 else if (*ret == ' ') {
434 retvstart[items] = Nullch;
446 if (!w32_perlshell_tokens) {
447 /* we don't use COMSPEC here for two reasons:
448 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
449 * uncontrolled unportability of the ensuing scripts.
450 * 2. PERL5SHELL could be set to a shell that may not be fit for
451 * interactive use (which is what most programs look in COMSPEC
454 char* defaultshell = (IsWinNT() ? "cmd.exe /x/c" : "command.com /c");
455 char *usershell = getenv("PERL5SHELL");
456 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
457 &w32_perlshell_tokens,
463 do_aspawn(void *vreally, void **vmark, void **vsp)
465 SV *really = (SV*)vreally;
466 SV **mark = (SV**)vmark;
478 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
480 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
485 while (++mark <= sp) {
486 if (*mark && (str = SvPV(*mark, na)))
493 status = win32_spawnvp(flag,
494 (const char*)(really ? SvPV(really,na) : argv[0]),
495 (const char* const*)argv);
497 if (status < 0 && errno == ENOEXEC) {
498 /* possible shell-builtin, invoke with shell */
500 sh_items = w32_perlshell_items;
502 argv[index+sh_items] = argv[index];
503 while (--sh_items >= 0)
504 argv[sh_items] = w32_perlshell_vec[sh_items];
506 status = win32_spawnvp(flag,
507 (const char*)(really ? SvPV(really,na) : argv[0]),
508 (const char* const*)argv);
511 if (flag != P_NOWAIT) {
514 warn("Can't spawn \"%s\": %s", argv[0], strerror(errno));
519 statusvalue = status;
526 do_spawn2(char *cmd, int exectype)
532 BOOL needToTry = TRUE;
535 /* Save an extra exec if possible. See if there are shell
536 * metacharacters in it */
537 if (!has_redirection(cmd)) {
538 New(1301,argv, strlen(cmd) / 2 + 2, char*);
539 New(1302,cmd2, strlen(cmd) + 1, char);
542 for (s = cmd2; *s;) {
543 while (*s && isspace(*s))
547 while (*s && !isspace(*s))
556 status = win32_spawnvp(P_WAIT, argv[0],
557 (const char* const*)argv);
559 case EXECF_SPAWN_NOWAIT:
560 status = win32_spawnvp(P_NOWAIT, argv[0],
561 (const char* const*)argv);
564 status = win32_execvp(argv[0], (const char* const*)argv);
567 if (status != -1 || errno == 0)
577 New(1306, argv, w32_perlshell_items + 2, char*);
578 while (++i < w32_perlshell_items)
579 argv[i] = w32_perlshell_vec[i];
584 status = win32_spawnvp(P_WAIT, argv[0],
585 (const char* const*)argv);
587 case EXECF_SPAWN_NOWAIT:
588 status = win32_spawnvp(P_NOWAIT, argv[0],
589 (const char* const*)argv);
592 status = win32_execvp(argv[0], (const char* const*)argv);
598 if (exectype != EXECF_SPAWN_NOWAIT) {
601 warn("Can't %s \"%s\": %s",
602 (exectype == EXECF_EXEC ? "exec" : "spawn"),
603 cmd, strerror(errno));
608 statusvalue = status;
616 return do_spawn2(cmd, EXECF_SPAWN);
620 do_spawn_nowait(char *cmd)
622 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
628 do_spawn2(cmd, EXECF_EXEC);
632 /* The idea here is to read all the directory names into a string table
633 * (separated by nulls) and when one of the other dir functions is called
634 * return the pointer to the current file name.
637 opendir(char *filename)
642 char scanname[MAX_PATH+3];
644 WIN32_FIND_DATA FindData;
647 len = strlen(filename);
651 /* check to see if filename is a directory */
652 if (win32_stat(filename, &sbuf) < 0 || (sbuf.st_mode & S_IFDIR) == 0) {
653 /* CRT is buggy on sharenames, so make sure it really isn't */
654 DWORD r = GetFileAttributes(filename);
655 if (r == 0xffffffff || !(r & FILE_ATTRIBUTE_DIRECTORY))
659 /* Get us a DIR structure */
660 Newz(1303, p, 1, DIR);
664 /* Create the search pattern */
665 strcpy(scanname, filename);
666 if (scanname[len-1] != '/' && scanname[len-1] != '\\')
667 scanname[len++] = '/';
668 scanname[len++] = '*';
669 scanname[len] = '\0';
671 /* do the FindFirstFile call */
672 fh = FindFirstFile(scanname, &FindData);
673 if (fh == INVALID_HANDLE_VALUE) {
677 /* now allocate the first part of the string table for
678 * the filenames that we find.
680 idx = strlen(FindData.cFileName)+1;
681 New(1304, p->start, idx, char);
682 if (p->start == NULL)
683 croak("opendir: malloc failed!\n");
684 strcpy(p->start, FindData.cFileName);
687 /* loop finding all the files that match the wildcard
688 * (which should be all of them in this directory!).
689 * the variable idx should point one past the null terminator
690 * of the previous string found.
692 while (FindNextFile(fh, &FindData)) {
693 len = strlen(FindData.cFileName);
694 /* bump the string table size by enough for the
695 * new name and it's null terminator
697 Renew(p->start, idx+len+1, char);
698 if (p->start == NULL)
699 croak("opendir: malloc failed!\n");
700 strcpy(&p->start[idx], FindData.cFileName);
711 /* Readdir just returns the current string pointer and bumps the
712 * string pointer to the nDllExport entry.
718 static int dummy = 0;
721 /* first set up the structure to return */
722 len = strlen(dirp->curr);
723 strcpy(dirp->dirstr.d_name, dirp->curr);
724 dirp->dirstr.d_namlen = len;
727 dirp->dirstr.d_ino = dummy++;
729 /* Now set up for the nDllExport call to readdir */
730 dirp->curr += len + 1;
731 if (dirp->curr >= (dirp->start + dirp->size)) {
735 return &(dirp->dirstr);
741 /* Telldir returns the current string pointer position */
745 return (long) dirp->curr;
749 /* Seekdir moves the string pointer to a previously saved position
753 seekdir(DIR *dirp, long loc)
755 dirp->curr = (char *)loc;
758 /* Rewinddir resets the string pointer to the start */
762 dirp->curr = dirp->start;
765 /* free the memory allocated by opendir */
769 Safefree(dirp->start);
782 * Just pretend that everyone is a superuser. NT will let us know if
783 * we don\'t really have permission to do something.
786 #define ROOT_UID ((uid_t)0)
787 #define ROOT_GID ((gid_t)0)
816 return (auid == ROOT_UID ? 0 : -1);
822 return (agid == ROOT_GID ? 0 : -1);
829 char *buf = getlogin_buffer;
830 DWORD size = sizeof(getlogin_buffer);
831 if (GetUserName(buf,&size))
837 chown(const char *path, uid_t owner, gid_t group)
844 kill(int pid, int sig)
846 HANDLE hProcess= OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
848 if (hProcess == NULL) {
849 croak("kill process failed!\n");
852 if (!TerminateProcess(hProcess, sig))
853 croak("kill process failed!\n");
854 CloseHandle(hProcess);
863 DllExport unsigned int
864 win32_sleep(unsigned int t)
871 win32_stat(const char *path, struct stat *buffer)
874 const char *p = path;
875 int l = strlen(path);
879 switch(path[l - 1]) {
882 if (path[l - 2] != ':') {
883 strncpy(t, path, l - 1);
889 res = stat(p,buffer);
892 if (S_ISDIR(buffer->st_mode))
893 buffer->st_mode |= S_IWRITE | S_IEXEC;
894 else if (S_ISREG(buffer->st_mode)) {
895 if (l >= 4 && path[l-4] == '.') {
896 const char *e = path + l - 3;
897 if (strnicmp(e,"exe",3)
898 && strnicmp(e,"bat",3)
899 && strnicmp(e,"com",3)
900 && (IsWin95() || strnicmp(e,"cmd",3)))
901 buffer->st_mode &= ~S_IEXEC;
903 buffer->st_mode |= S_IEXEC;
906 buffer->st_mode &= ~S_IEXEC;
913 #ifndef USE_WIN32_RTL_ENV
916 win32_getenv(const char *name)
918 static char *curitem = Nullch;
919 static DWORD curlen = 512;
922 New(1305,curitem,curlen,char);
924 needlen = GetEnvironmentVariable(name,curitem,curlen);
926 while (needlen > curlen) {
927 Renew(curitem,needlen,char);
929 needlen = GetEnvironmentVariable(name,curitem,curlen);
934 /* allow any environment variables that begin with 'PERL5'
935 to be stored in the registry
940 if (strncmp(name, "PERL5", 5) == 0) {
941 if (curitem != NULL) {
945 curitem = GetRegStr(name, &curitem, &curlen);
948 if(curitem != NULL && *curitem == '\0')
957 filetime_to_clock(PFILETIME ft)
959 __int64 qw = ft->dwHighDateTime;
961 qw |= ft->dwLowDateTime;
962 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
967 win32_times(struct tms *timebuf)
972 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
974 timebuf->tms_utime = filetime_to_clock(&user);
975 timebuf->tms_stime = filetime_to_clock(&kernel);
976 timebuf->tms_cutime = 0;
977 timebuf->tms_cstime = 0;
980 /* That failed - e.g. Win95 fallback to clock() */
982 timebuf->tms_utime = t;
983 timebuf->tms_stime = 0;
984 timebuf->tms_cutime = 0;
985 timebuf->tms_cstime = 0;
990 /* fix utime() so it works on directories in NT
991 * thanks to Jan Dubois <jan.dubois@ibm.net>
994 filetime_from_time(PFILETIME pFileTime, time_t Time)
996 struct tm *pTM = gmtime(&Time);
997 SYSTEMTIME SystemTime;
1002 SystemTime.wYear = pTM->tm_year + 1900;
1003 SystemTime.wMonth = pTM->tm_mon + 1;
1004 SystemTime.wDay = pTM->tm_mday;
1005 SystemTime.wHour = pTM->tm_hour;
1006 SystemTime.wMinute = pTM->tm_min;
1007 SystemTime.wSecond = pTM->tm_sec;
1008 SystemTime.wMilliseconds = 0;
1010 return SystemTimeToFileTime(&SystemTime, pFileTime);
1014 win32_utime(const char *filename, struct utimbuf *times)
1020 struct utimbuf TimeBuffer;
1022 int rc = utime(filename,times);
1023 /* EACCES: path specifies directory or readonly file */
1024 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
1027 if (times == NULL) {
1028 times = &TimeBuffer;
1029 time(×->actime);
1030 times->modtime = times->actime;
1033 /* This will (and should) still fail on readonly files */
1034 handle = CreateFile(filename, GENERIC_READ | GENERIC_WRITE,
1035 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1036 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1037 if (handle == INVALID_HANDLE_VALUE)
1040 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
1041 filetime_from_time(&ftAccess, times->actime) &&
1042 filetime_from_time(&ftWrite, times->modtime) &&
1043 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
1048 CloseHandle(handle);
1053 win32_wait(int *status)
1056 return wait(status);
1058 /* XXX this wait emulation only knows about processes
1059 * spawned via win32_spawnvp(P_NOWAIT, ...).
1062 DWORD exitcode, waitcode;
1064 if (!w32_num_children) {
1069 /* if a child exists, wait for it to die */
1070 waitcode = WaitForMultipleObjects(w32_num_children,
1074 if (waitcode != WAIT_FAILED) {
1075 if (waitcode >= WAIT_ABANDONED_0
1076 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1077 i = waitcode - WAIT_ABANDONED_0;
1079 i = waitcode - WAIT_OBJECT_0;
1080 if (GetExitCodeProcess(w32_child_pids[i], &exitcode) ) {
1081 CloseHandle(w32_child_pids[i]);
1082 *status = (int)((exitcode & 0xff) << 8);
1083 retval = (int)w32_child_pids[i];
1084 Copy(&w32_child_pids[i+1], &w32_child_pids[i],
1085 (w32_num_children-i-1), HANDLE);
1092 errno = GetLastError();
1098 static UINT timerid = 0;
1100 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1102 KillTimer(NULL,timerid);
1107 DllExport unsigned int
1108 win32_alarm(unsigned int sec)
1111 * the 'obvious' implentation is SetTimer() with a callback
1112 * which does whatever receiving SIGALRM would do
1113 * we cannot use SIGALRM even via raise() as it is not
1114 * one of the supported codes in <signal.h>
1116 * Snag is unless something is looking at the message queue
1117 * nothing happens :-(
1121 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1123 croak("Cannot set timer");
1129 KillTimer(NULL,timerid);
1136 #ifdef HAVE_DES_FCRYPT
1137 extern char * des_fcrypt(char *cbuf, const char *txt, const char *salt);
1140 win32_crypt(const char *txt, const char *salt)
1143 return des_fcrypt(crypt_buffer, txt, salt);
1147 #ifdef USE_FIXED_OSFHANDLE
1149 EXTERN_C int __cdecl _alloc_osfhnd(void);
1150 EXTERN_C int __cdecl _set_osfhnd(int fh, long value);
1151 EXTERN_C void __cdecl _lock_fhandle(int);
1152 EXTERN_C void __cdecl _unlock_fhandle(int);
1153 EXTERN_C void __cdecl _unlock(int);
1155 #if (_MSC_VER >= 1000)
1157 long osfhnd; /* underlying OS file HANDLE */
1158 char osfile; /* attributes of file (e.g., open in text mode?) */
1159 char pipech; /* one char buffer for handles opened on pipes */
1160 #if defined (_MT) && !defined (DLL_FOR_WIN32S)
1162 CRITICAL_SECTION lock;
1163 #endif /* defined (_MT) && !defined (DLL_FOR_WIN32S) */
1166 EXTERN_C ioinfo * __pioinfo[];
1168 #define IOINFO_L2E 5
1169 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
1170 #define _pioinfo(i) (__pioinfo[i >> IOINFO_L2E] + (i & (IOINFO_ARRAY_ELTS - 1)))
1171 #define _osfile(i) (_pioinfo(i)->osfile)
1173 #else /* (_MSC_VER >= 1000) */
1174 extern char _osfile[];
1175 #endif /* (_MSC_VER >= 1000) */
1177 #define FOPEN 0x01 /* file handle open */
1178 #define FAPPEND 0x20 /* file handle opened O_APPEND */
1179 #define FDEV 0x40 /* file handle refers to device */
1180 #define FTEXT 0x80 /* file handle is in text mode */
1182 #define _STREAM_LOCKS 26 /* Table of stream locks */
1183 #define _LAST_STREAM_LOCK (_STREAM_LOCKS+_NSTREAM_-1) /* Last stream lock */
1184 #define _FH_LOCKS (_LAST_STREAM_LOCK+1) /* Table of fh locks */
1187 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1190 * This function allocates a free C Runtime file handle and associates
1191 * it with the Win32 HANDLE specified by the first parameter. This is a
1192 * temperary fix for WIN95's brain damage GetFileType() error on socket
1193 * we just bypass that call for socket
1196 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1197 * int flags - flags to associate with C Runtime file handle.
1200 * returns index of entry in fh, if successful
1201 * return -1, if no free entry is found
1205 *******************************************************************************/
1208 my_open_osfhandle(long osfhandle, int flags)
1211 char fileflags; /* _osfile flags */
1213 /* copy relevant flags from second parameter */
1216 if (flags & O_APPEND)
1217 fileflags |= FAPPEND;
1222 /* attempt to allocate a C Runtime file handle */
1223 if ((fh = _alloc_osfhnd()) == -1) {
1224 errno = EMFILE; /* too many open files */
1225 _doserrno = 0L; /* not an OS error */
1226 return -1; /* return error to caller */
1229 /* the file is open. now, set the info in _osfhnd array */
1230 _set_osfhnd(fh, osfhandle);
1232 fileflags |= FOPEN; /* mark as open */
1234 #if (_MSC_VER >= 1000)
1235 _osfile(fh) = fileflags; /* set osfile entry */
1236 _unlock_fhandle(fh);
1238 _osfile[fh] = fileflags; /* set osfile entry */
1239 _unlock(fh+_FH_LOCKS); /* unlock handle */
1242 return fh; /* return handle */
1245 #define _open_osfhandle my_open_osfhandle
1246 #endif /* USE_FIXED_OSFHANDLE */
1248 /* simulate flock by locking a range on the file */
1250 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1251 #define LK_LEN 0xffff0000
1254 win32_flock(int fd, int oper)
1261 croak("flock() unimplemented on this platform");
1264 fh = (HANDLE)_get_osfhandle(fd);
1265 memset(&o, 0, sizeof(o));
1268 case LOCK_SH: /* shared lock */
1269 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1271 case LOCK_EX: /* exclusive lock */
1272 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1274 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1275 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1277 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1278 LK_ERR(LockFileEx(fh,
1279 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1280 0, LK_LEN, 0, &o),i);
1282 case LOCK_UN: /* unlock lock */
1283 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1285 default: /* unknown */
1296 * redirected io subsystem for all XS modules
1309 return (&(_environ));
1312 /* the rest are the remapped stdio routines */
1332 win32_ferror(FILE *fp)
1334 return (ferror(fp));
1339 win32_feof(FILE *fp)
1345 * Since the errors returned by the socket error function
1346 * WSAGetLastError() are not known by the library routine strerror
1347 * we have to roll our own.
1351 win32_strerror(int e)
1353 #ifndef __BORLANDC__ /* Borland intolerance */
1354 extern int sys_nerr;
1358 if (e < 0 || e > sys_nerr) {
1363 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
1364 strerror_buffer, sizeof(strerror_buffer), NULL) == 0)
1365 strcpy(strerror_buffer, "Unknown Error");
1367 return strerror_buffer;
1373 win32_str_os_error(void *sv, DWORD dwErr)
1377 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
1378 |FORMAT_MESSAGE_IGNORE_INSERTS
1379 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
1380 dwErr, 0, (char *)&sMsg, 1, NULL);
1382 while (0 < dwLen && isspace(sMsg[--dwLen]))
1384 if ('.' != sMsg[dwLen])
1389 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
1390 dwLen = sprintf(sMsg,
1391 "Unknown error #0x%lX (lookup 0x%lX)",
1392 dwErr, GetLastError());
1394 sv_setpvn((SV*)sv, sMsg, dwLen);
1400 win32_fprintf(FILE *fp, const char *format, ...)
1403 va_start(marker, format); /* Initialize variable arguments. */
1405 return (vfprintf(fp, format, marker));
1409 win32_printf(const char *format, ...)
1412 va_start(marker, format); /* Initialize variable arguments. */
1414 return (vprintf(format, marker));
1418 win32_vfprintf(FILE *fp, const char *format, va_list args)
1420 return (vfprintf(fp, format, args));
1424 win32_vprintf(const char *format, va_list args)
1426 return (vprintf(format, args));
1430 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
1432 return fread(buf, size, count, fp);
1436 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
1438 return fwrite(buf, size, count, fp);
1442 win32_fopen(const char *filename, const char *mode)
1444 if (stricmp(filename, "/dev/null")==0)
1445 return fopen("NUL", mode);
1446 return fopen(filename, mode);
1449 #ifndef USE_SOCKETS_AS_HANDLES
1451 #define fdopen my_fdopen
1455 win32_fdopen( int handle, const char *mode)
1457 return fdopen(handle, (char *) mode);
1461 win32_freopen( const char *path, const char *mode, FILE *stream)
1463 if (stricmp(path, "/dev/null")==0)
1464 return freopen("NUL", mode, stream);
1465 return freopen(path, mode, stream);
1469 win32_fclose(FILE *pf)
1471 return my_fclose(pf); /* defined in win32sck.c */
1475 win32_fputs(const char *s,FILE *pf)
1477 return fputs(s, pf);
1481 win32_fputc(int c,FILE *pf)
1487 win32_ungetc(int c,FILE *pf)
1489 return ungetc(c,pf);
1493 win32_getc(FILE *pf)
1499 win32_fileno(FILE *pf)
1505 win32_clearerr(FILE *pf)
1512 win32_fflush(FILE *pf)
1518 win32_ftell(FILE *pf)
1524 win32_fseek(FILE *pf,long offset,int origin)
1526 return fseek(pf, offset, origin);
1530 win32_fgetpos(FILE *pf,fpos_t *p)
1532 return fgetpos(pf, p);
1536 win32_fsetpos(FILE *pf,const fpos_t *p)
1538 return fsetpos(pf, p);
1542 win32_rewind(FILE *pf)
1562 win32_fstat(int fd,struct stat *sbufptr)
1564 return fstat(fd,sbufptr);
1568 win32_pipe(int *pfd, unsigned int size, int mode)
1570 return _pipe(pfd, size, mode);
1574 * a popen() clone that respects PERL5SHELL
1578 win32_popen(const char *command, const char *mode)
1580 #ifdef USE_RTL_POPEN
1581 return _popen(command, mode);
1589 /* establish which ends read and write */
1590 if (strchr(mode,'w')) {
1591 stdfd = 0; /* stdin */
1595 else if (strchr(mode,'r')) {
1596 stdfd = 1; /* stdout */
1603 /* set the correct mode */
1604 if (strchr(mode,'b'))
1606 else if (strchr(mode,'t'))
1609 ourmode = _fmode & (O_TEXT | O_BINARY);
1611 /* the child doesn't inherit handles */
1612 ourmode |= O_NOINHERIT;
1614 if (win32_pipe( p, 512, ourmode) == -1)
1617 /* save current stdfd */
1618 if ((oldfd = win32_dup(stdfd)) == -1)
1621 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
1622 /* stdfd will be inherited by the child */
1623 if (win32_dup2(p[child], stdfd) == -1)
1626 /* close the child end in parent */
1627 win32_close(p[child]);
1629 /* start the child */
1630 if ((childpid = do_spawn_nowait((char*)command)) == -1)
1633 /* revert stdfd to whatever it was before */
1634 if (win32_dup2(oldfd, stdfd) == -1)
1637 /* close saved handle */
1640 sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
1642 /* we have an fd, return a file stream */
1643 return (win32_fdopen(p[parent], (char *)mode));
1646 /* we don't need to check for errors here */
1650 win32_dup2(oldfd, stdfd);
1655 #endif /* USE_RTL_POPEN */
1663 win32_pclose(FILE *pf)
1665 #ifdef USE_RTL_POPEN
1669 #ifndef USE_RTL_WAIT
1673 int childpid, status;
1676 sv = *av_fetch(w32_fdpid, win32_fileno(pf), TRUE);
1678 childpid = SvIVX(sv);
1690 #ifndef USE_RTL_WAIT
1691 for (child = 0 ; child < w32_num_children ; ++child) {
1692 if (w32_child_pids[child] == (HANDLE)childpid) {
1693 Copy(&w32_child_pids[child+1], &w32_child_pids[child],
1694 (w32_num_children-child-1), HANDLE);
1701 /* wait for the child */
1702 if (cwait(&status, childpid, WAIT_CHILD) == -1)
1704 /* cwait() returns differently on Borland */
1706 return (((status >> 8) & 0xff) | ((status << 8) & 0xff00));
1711 #endif /* USE_RTL_POPEN */
1715 win32_setmode(int fd, int mode)
1717 return setmode(fd, mode);
1721 win32_lseek(int fd, long offset, int origin)
1723 return lseek(fd, offset, origin);
1733 win32_open(const char *path, int flag, ...)
1739 pmode = va_arg(ap, int);
1742 if (stricmp(path, "/dev/null")==0)
1743 return open("NUL", flag, pmode);
1744 return open(path,flag,pmode);
1766 win32_dup2(int fd1,int fd2)
1768 return dup2(fd1,fd2);
1772 win32_read(int fd, void *buf, unsigned int cnt)
1774 return read(fd, buf, cnt);
1778 win32_write(int fd, const void *buf, unsigned int cnt)
1780 return write(fd, buf, cnt);
1784 win32_mkdir(const char *dir, int mode)
1786 return mkdir(dir); /* just ignore mode */
1790 win32_rmdir(const char *dir)
1796 win32_chdir(const char *dir)
1802 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
1806 #ifndef USE_RTL_WAIT
1807 if (mode == P_NOWAIT && w32_num_children >= MAXIMUM_WAIT_OBJECTS)
1811 status = spawnvp(mode, cmdname, (char * const *) argv);
1812 #ifndef USE_RTL_WAIT
1813 /* XXX For the P_NOWAIT case, Borland RTL returns pinfo.dwProcessId
1814 * while VC RTL returns pinfo.hProcess. For purposes of the custom
1815 * implementation of win32_wait(), we assume the latter.
1817 if (mode == P_NOWAIT && status >= 0)
1818 w32_child_pids[w32_num_children++] = (HANDLE)status;
1824 win32_execvp(const char *cmdname, const char *const *argv)
1826 return execvp(cmdname, (char *const *)argv);
1830 win32_perror(const char *str)
1836 win32_setbuf(FILE *pf, char *buf)
1842 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
1844 return setvbuf(pf, buf, type, size);
1848 win32_flushall(void)
1854 win32_fcloseall(void)
1860 win32_fgets(char *s, int n, FILE *pf)
1862 return fgets(s, n, pf);
1872 win32_fgetc(FILE *pf)
1878 win32_putc(int c, FILE *pf)
1884 win32_puts(const char *s)
1896 win32_putchar(int c)
1903 #ifndef USE_PERL_SBRK
1905 static char *committed = NULL;
1906 static char *base = NULL;
1907 static char *reserved = NULL;
1908 static char *brk = NULL;
1909 static DWORD pagesize = 0;
1910 static DWORD allocsize = 0;
1918 GetSystemInfo(&info);
1919 /* Pretend page size is larger so we don't perpetually
1920 * call the OS to commit just one page ...
1922 pagesize = info.dwPageSize << 3;
1923 allocsize = info.dwAllocationGranularity;
1925 /* This scheme fails eventually if request for contiguous
1926 * block is denied so reserve big blocks - this is only
1927 * address space not memory ...
1929 if (brk+need >= reserved)
1931 DWORD size = 64*1024*1024;
1933 if (committed && reserved && committed < reserved)
1935 /* Commit last of previous chunk cannot span allocations */
1936 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
1938 committed = reserved;
1940 /* Reserve some (more) space
1941 * Note this is a little sneaky, 1st call passes NULL as reserved
1942 * so lets system choose where we start, subsequent calls pass
1943 * the old end address so ask for a contiguous block
1945 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
1948 reserved = addr+size;
1963 if (brk > committed)
1965 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
1966 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
1981 win32_malloc(size_t size)
1983 return malloc(size);
1987 win32_calloc(size_t numitems, size_t size)
1989 return calloc(numitems,size);
1993 win32_realloc(void *block, size_t size)
1995 return realloc(block,size);
1999 win32_free(void *block)
2006 win32_open_osfhandle(long handle, int flags)
2008 return _open_osfhandle(handle, flags);
2012 win32_get_osfhandle(int fd)
2014 return _get_osfhandle(fd);
2025 SV *sv = sv_newmortal();
2026 /* Make one call with zero size - return value is required size */
2027 DWORD len = GetCurrentDirectory((DWORD)0,NULL);
2028 SvUPGRADE(sv,SVt_PV);
2030 SvCUR(sv) = GetCurrentDirectory((DWORD) SvLEN(sv), SvPVX(sv));
2033 * then it worked, set PV valid,
2034 * else leave it 'undef'
2048 croak("usage: Win32::SetCurrentDirectory($cwd)");
2049 if (SetCurrentDirectory(SvPV(ST(0),na)))
2056 XS(w32_GetNextAvailDrive)
2060 char root[] = "_:\\";
2063 if (GetDriveType(root) == 1) {
2072 XS(w32_GetLastError)
2075 XSRETURN_IV(GetLastError());
2082 char *name = getlogin_buffer;
2083 DWORD size = sizeof(getlogin_buffer);
2084 if (GetUserName(name,&size)) {
2085 /* size includes NULL */
2086 ST(0) = sv_2mortal(newSVpv(name,size-1));
2096 char name[MAX_COMPUTERNAME_LENGTH+1];
2097 DWORD size = sizeof(name);
2098 if (GetComputerName(name,&size)) {
2099 /* size does NOT include NULL :-( */
2100 ST(0) = sv_2mortal(newSVpv(name,size));
2111 #ifndef HAS_NETWKSTAGETINFO
2112 /* mingw32 (and Win95) don't have NetWksta*(), so do it the old way */
2114 DWORD size = sizeof(name);
2115 if (GetUserName(name,&size)) {
2117 DWORD sidlen = sizeof(sid);
2119 DWORD dnamelen = sizeof(dname);
2121 if (LookupAccountName(NULL, name, &sid, &sidlen,
2122 dname, &dnamelen, &snu)) {
2123 XSRETURN_PV(dname); /* all that for this */
2127 /* this way is more reliable, in case user has a local account.
2128 * XXX need dynamic binding of netapi32.dll symbols or this will fail on
2129 * Win95. Probably makes more sense to move it into libwin32. */
2131 DWORD dnamelen = sizeof(dname);
2132 PWKSTA_INFO_100 pwi;
2133 if (NERR_Success == NetWkstaGetInfo(NULL, 100, (LPBYTE*)&pwi)) {
2134 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
2135 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
2136 -1, (LPSTR)dname, dnamelen, NULL, NULL);
2139 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
2140 -1, (LPSTR)dname, dnamelen, NULL, NULL);
2142 NetApiBufferFree(pwi);
2154 DWORD flags, filecomplen;
2155 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
2156 &flags, fsname, sizeof(fsname))) {
2157 if (GIMME == G_ARRAY) {
2158 XPUSHs(sv_2mortal(newSVpv(fsname,0)));
2159 XPUSHs(sv_2mortal(newSViv(flags)));
2160 XPUSHs(sv_2mortal(newSViv(filecomplen)));
2164 XSRETURN_PV(fsname);
2170 XS(w32_GetOSVersion)
2173 OSVERSIONINFO osver;
2175 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
2176 if (GetVersionEx(&osver)) {
2177 XPUSHs(newSVpv(osver.szCSDVersion, 0));
2178 XPUSHs(newSViv(osver.dwMajorVersion));
2179 XPUSHs(newSViv(osver.dwMinorVersion));
2180 XPUSHs(newSViv(osver.dwBuildNumber));
2181 XPUSHs(newSViv(osver.dwPlatformId));
2192 XSRETURN_IV(IsWinNT());
2199 XSRETURN_IV(IsWin95());
2203 XS(w32_FormatMessage)
2210 croak("usage: Win32::FormatMessage($errno)");
2212 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
2213 &source, SvIV(ST(0)), 0,
2214 msgbuf, sizeof(msgbuf)-1, NULL))
2215 XSRETURN_PV(msgbuf);
2225 PROCESS_INFORMATION stProcInfo;
2226 STARTUPINFO stStartInfo;
2227 BOOL bSuccess = FALSE;
2230 croak("usage: Win32::Spawn($cmdName, $args, $PID)");
2232 cmd = SvPV(ST(0),na);
2233 args = SvPV(ST(1), na);
2235 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
2236 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
2237 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
2238 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
2241 cmd, /* Image path */
2242 args, /* Arguments for command line */
2243 NULL, /* Default process security */
2244 NULL, /* Default thread security */
2245 FALSE, /* Must be TRUE to use std handles */
2246 NORMAL_PRIORITY_CLASS, /* No special scheduling */
2247 NULL, /* Inherit our environment block */
2248 NULL, /* Inherit our currrent directory */
2249 &stStartInfo, /* -> Startup info */
2250 &stProcInfo)) /* <- Process info (if OK) */
2252 CloseHandle(stProcInfo.hThread);/* library source code does this. */
2253 sv_setiv(ST(2), stProcInfo.dwProcessId);
2256 XSRETURN_IV(bSuccess);
2260 XS(w32_GetTickCount)
2263 XSRETURN_IV(GetTickCount());
2267 XS(w32_GetShortPathName)
2274 croak("usage: Win32::GetShortPathName($longPathName)");
2276 shortpath = sv_mortalcopy(ST(0));
2277 SvUPGRADE(shortpath, SVt_PV);
2278 /* src == target is allowed */
2280 len = GetShortPathName(SvPVX(shortpath),
2283 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
2285 SvCUR_set(shortpath,len);
2298 croak("usage: Win32::Sleep($milliseconds)");
2303 #define TMPBUFSZ 1024
2304 #define MAX_LENGTH 2048
2305 #define SUCCESSRETURNED(x) (x == ERROR_SUCCESS)
2306 #define REGRETURN(x) XSRETURN_IV(SUCCESSRETURNED(x))
2307 #define SvHKEY(index) (HKEY)((unsigned long)SvIV(index))
2308 #define SETIV(index,value) sv_setiv(ST(index), value)
2309 #define SETNV(index,value) sv_setnv(ST(index), value)
2310 #define SETPV(index,string) sv_setpv(ST(index), string)
2311 #define SETPVN(index, buffer, length) sv_setpvn(ST(index), (char*)buffer, length)
2312 #define SETHKEY(index, hkey) SETIV(index,(long)hkey)
2314 static time_t ft2timet(FILETIME *ft)
2319 FileTimeToSystemTime(ft, &st);
2320 tm.tm_sec = st.wSecond;
2321 tm.tm_min = st.wMinute;
2322 tm.tm_hour = st.wHour;
2323 tm.tm_mday = st.wDay;
2324 tm.tm_mon = st.wMonth - 1;
2325 tm.tm_year = st.wYear - 1900;
2326 tm.tm_wday = st.wDayOfWeek;
2329 return mktime (&tm);
2339 croak("usage: Win32::RegCloseKey($hkey);\n");
2342 REGRETURN(RegCloseKey(SvHKEY(ST(0))));
2346 XS(w32_RegConnectRegistry)
2353 croak("usage: Win32::RegConnectRegistry($machine, $hkey, $handle);\n");
2356 if (SUCCESSRETURNED(RegConnectRegistry((char *)SvPV(ST(0), na), SvHKEY(ST(1)), &handle)))
2365 XS(w32_RegCreateKey)
2374 croak("usage: Win32::RegCreateKey($hkey, $subkey, $handle);\n");
2377 retval = RegCreateKeyEx(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS,
2378 NULL, &handle, &disposition);
2380 if (SUCCESSRETURNED(retval))
2389 XS(w32_RegCreateKeyEx)
2393 unsigned int length;
2398 DWORD options, disposition;
2400 SECURITY_ATTRIBUTES sa, *psa;
2404 croak("usage: Win32::RegCreateKeyEx($hkey, $subkey, $reserved, $class, $options, $sam, "
2405 "$security, $handle, $disposition);\n");
2408 hkey = SvHKEY(ST(0));
2409 subkey = (char *)SvPV(ST(1), na);
2410 keyclass = (char *)SvPV(ST(3), na);
2411 options = (DWORD) ((unsigned long)SvIV(ST(4)));
2412 sam = (REGSAM) ((unsigned long)SvIV(ST(5)));
2413 psa = (SECURITY_ATTRIBUTES*)SvPV(ST(6), length);
2414 if (length != sizeof(SECURITY_ATTRIBUTES))
2417 memset(&sa, 0, sizeof(SECURITY_ATTRIBUTES));
2418 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
2421 retval = RegCreateKeyEx(hkey, subkey, 0, keyclass, options, sam,
2422 psa, &handle, &disposition);
2424 if (SUCCESSRETURNED(retval))
2427 SETPVN(6, &sa, sizeof(sa));
2430 SETIV(8,disposition);
2437 XS(w32_RegDeleteKey)
2443 croak("usage: Win32::RegDeleteKey($hkey, $subkey);\n");
2446 REGRETURN(RegDeleteKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na)));
2450 XS(w32_RegDeleteValue)
2456 croak("usage: Win32::RegDeleteValue($hkey, $valname);\n");
2459 REGRETURN(RegDeleteValue(SvHKEY(ST(0)), (char *)SvPV(ST(1), na)));
2467 char keybuffer[TMPBUFSZ];
2471 croak("usage: Win32::RegEnumKey($hkey, $idx, $subkeyname);\n");
2474 if (SUCCESSRETURNED(RegEnumKey(SvHKEY(ST(0)), SvIV(ST(1)), keybuffer, sizeof(keybuffer))))
2476 SETPV(2, keybuffer);
2483 XS(w32_RegEnumKeyEx)
2488 DWORD keysz, classsz;
2489 char keybuffer[TMPBUFSZ];
2490 char classbuffer[TMPBUFSZ];
2496 croak("usage: Win32::RegEnumKeyEx($hkey, $idx, $subkeyname, $reserved, $class, $time);\n");
2499 keysz = sizeof(keybuffer);
2500 classsz = sizeof(classbuffer);
2501 retval = RegEnumKeyEx(SvHKEY(ST(0)), SvIV(ST(1)), keybuffer, &keysz, 0,
2502 classbuffer, &classsz, &filetime);
2503 if (SUCCESSRETURNED(retval))
2505 SETPV(2, keybuffer);
2506 SETPV(4, classbuffer);
2507 SETIV(5, ft2timet(&filetime));
2514 XS(w32_RegEnumValue)
2518 DWORD type, namesz, valsz;
2520 static HKEY last_hkey;
2521 char myvalbuf[MAX_LENGTH];
2522 char mynambuf[MAX_LENGTH];
2526 croak("usage: Win32::RegEnumValue($hkey, $i, $name, $reserved, $type, $value);\n");
2529 hkey = SvHKEY(ST(0));
2531 // If this is a new key, find out how big the maximum name and value sizes are and
2532 // allocate space for them. Free any old storage and set the old key value to the
2535 if (hkey != (HKEY)last_hkey)
2537 char keyclass[TMPBUFSZ];
2538 DWORD classsz, subkeys, maxsubkey, maxclass, values, salen, maxnamesz, maxvalsz;
2540 classsz = sizeof(keyclass);
2541 retval = RegQueryInfoKey(hkey, keyclass, &classsz, 0, &subkeys, &maxsubkey, &maxclass,
2542 &values, &maxnamesz, &maxvalsz, &salen, &ft);
2544 if (!SUCCESSRETURNED(retval))
2548 memset(myvalbuf, 0, MAX_LENGTH);
2549 memset(mynambuf, 0, MAX_LENGTH);
2553 namesz = MAX_LENGTH;
2555 retval = RegEnumValue(hkey, SvIV(ST(1)), mynambuf, &namesz, 0, &type, (LPBYTE) myvalbuf, &valsz);
2556 if (!SUCCESSRETURNED(retval))
2565 // return includes the null terminator so delete it if REG_SZ, REG_MULTI_SZ or REG_EXPAND_SZ
2574 SETPVN(5, myvalbuf, valsz);
2577 case REG_DWORD_BIG_ENDIAN:
2579 BYTE tmp = myvalbuf[0];
2580 myvalbuf[0] = myvalbuf[3];
2583 myvalbuf[1] = myvalbuf[2];
2586 case REG_DWORD_LITTLE_ENDIAN: // same as REG_DWORD
2587 SETNV(5, (double)*((DWORD*)myvalbuf));
2605 croak("usage: Win32::RegFlushKey($hkey);\n");
2608 REGRETURN(RegFlushKey(SvHKEY(ST(0))));
2612 XS(w32_RegGetKeySecurity)
2615 SECURITY_DESCRIPTOR sd;
2620 croak("usage: Win32::RegGetKeySecurity($hkey, $security_info, $security_descriptor);\n");
2623 if (SUCCESSRETURNED(RegGetKeySecurity(SvHKEY(ST(0)), SvIV(ST(1)), &sd, &sdsz)))
2625 SETPVN(2, &sd, sdsz);
2638 croak("usage: Win32::RegLoadKey($hkey, $subkey, $filename);\n");
2641 REGRETURN(RegLoadKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), (char *)SvPV(ST(2), na)));
2645 XS(w32_RegNotifyChangeKeyValue)
2647 croak("Win32::RegNotifyChangeKeyValue not yet implemented!\n");
2658 croak("usage: Win32::RegOpenKey($hkey, $subkey, $handle);\n");
2661 if (SUCCESSRETURNED(RegOpenKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), &handle)))
2670 XS(w32_RegOpenKeyEx)
2677 croak("usage: Win32::RegOpenKeyEx($hkey, $subkey, $reserved, $sam, $handle);\n");
2680 if (SUCCESSRETURNED(RegOpenKeyEx(SvHKEY(ST(0)), (char *)SvPV(ST(1), na),
2681 0, (REGSAM) ((unsigned long)SvIV(ST(3))), &handle)))
2689 #pragma optimize("", off)
2691 XS(w32_RegQueryInfoKey)
2696 char keyclass[TMPBUFSZ];
2697 DWORD subkeys, maxsubkey, maxclass, values, maxvalname, maxvaldata;
2698 DWORD seclen, classsz;
2704 croak("usage: Win32::RegQueryInfoKey($hkey, $class, $numsubkeys, $maxsubkey,"
2705 "$maxclass, $values, $maxvalname, $maxvaldata, $secdesclen,"
2706 "$lastwritetime);\n");
2709 classsz = sizeof(keyclass);
2710 retval = RegQueryInfoKey(SvHKEY(ST(0)), keyclass, &classsz, 0, &subkeys, &maxsubkey,
2711 &maxclass, &values, &maxvalname, &maxvaldata,
2713 if (SUCCESSRETURNED(retval))
2717 SETIV(3, maxsubkey);
2720 SETIV(6, maxvalname);
2721 SETIV(7, maxvaldata);
2723 SETIV(9, ft2timet(&ft));
2728 #pragma optimize("", on)
2731 XS(w32_RegQueryValue)
2735 unsigned char databuffer[TMPBUFSZ*2];
2736 long datasz = sizeof(databuffer);
2740 croak("usage: Win32::RegQueryValue($hkey, $valuename, $data);\n");
2743 if (SUCCESSRETURNED(RegQueryValue(SvHKEY(ST(0)), SvPV(ST(1), na), (char*)databuffer, &datasz)))
2745 // return includes the null terminator so delete it
2746 SETPVN(2, databuffer, --datasz);
2753 XS(w32_RegQueryValueEx)
2757 unsigned char databuffer[TMPBUFSZ*2];
2758 DWORD datasz = sizeof(databuffer);
2761 LPBYTE ptr = databuffer;
2765 croak("usage: Win32::RegQueryValueEx($hkey, $valuename, $reserved, $type, $data);\n");
2768 result = RegQueryValueEx(SvHKEY(ST(0)), SvPV(ST(1), na), 0, &type, ptr, &datasz);
2769 if (result == ERROR_MORE_DATA)
2771 New(0, ptr, datasz+1, BYTE);
2772 result = RegQueryValueEx(SvHKEY(ST(0)), SvPV(ST(1), na), 0, &type, ptr, &datasz);
2774 if (SUCCESSRETURNED(result))
2778 // return includes the null terminator so delete it if REG_SZ, REG_MULTI_SZ or REG_EXPAND_SZ
2786 SETPVN(4, ptr, datasz);
2789 case REG_DWORD_BIG_ENDIAN:
2798 case REG_DWORD_LITTLE_ENDIAN: // same as REG_DWORD
2799 SETNV(4, (double)*((DWORD*)ptr));
2806 if (ptr != databuffer)
2811 if (ptr != databuffer)
2818 XS(w32_RegReplaceKey)
2824 croak("usage: Win32::RegReplaceKey($hkey, $subkey, $newfile, $oldfile);\n");
2827 REGRETURN(RegReplaceKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), (char *)SvPV(ST(2), na), (char *)SvPV(ST(3), na)));
2831 XS(w32_RegRestoreKey)
2835 if (items < 2 || items > 3)
2837 croak("usage: Win32::RegRestoreKey($hkey, $filename [, $flags]);\n");
2840 REGRETURN(RegRestoreKey(SvHKEY(ST(0)), (char*)SvPV(ST(1), na), (DWORD)((items == 3) ? SvIV(ST(2)) : 0)));
2850 croak("usage: Win32::RegSaveKey($hkey, $filename);\n");
2853 REGRETURN(RegSaveKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), NULL));
2857 XS(w32_RegSetKeySecurity)
2863 croak("usage: Win32::RegSetKeySecurity($hkey, $security_info, $security_descriptor);\n");
2866 REGRETURN(RegSetKeySecurity(SvHKEY(ST(0)), SvIV(ST(1)), (SECURITY_DESCRIPTOR*)SvPV(ST(2), na)));
2880 croak("usage: Win32::RegSetValue($hkey, $subKey, $type, $data);\n");
2884 if (type != REG_SZ && type != REG_EXPAND_SZ)
2886 croak("Win32::RegSetValue: Type was not REG_SZ or REG_EXPAND_SZ, cannot set %s\n", (char *)SvPV(ST(1), na));
2889 buffer = (char *)SvPV(ST(3), size);
2890 REGRETURN(RegSetValue(SvHKEY(ST(0)), SvPV(ST(1), na), REG_SZ, buffer, size));
2894 XS(w32_RegSetValueEx)
2905 croak("usage: Win32::RegSetValueEx($hkey, $valname, $reserved, $type, $data);\n");
2908 type = (DWORD)SvIV(ST(3));
2915 buffer = (char *)SvPV(ST(4), size);
2916 if (type != REG_BINARY)
2917 size++; // include null terminator in size
2919 REGRETURN(RegSetValueEx(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), 0, type, (PBYTE) buffer, size));
2922 case REG_DWORD_BIG_ENDIAN:
2923 case REG_DWORD_LITTLE_ENDIAN: // Same as REG_DWORD
2924 val = (DWORD)SvIV(ST(4));
2925 REGRETURN(RegSetValueEx(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), 0, type, (PBYTE) &val, sizeof(DWORD)));
2929 croak("Win32::RegSetValueEx: Type not specified, cannot set %s\n", (char *)SvPV(ST(1), na));
2934 XS(w32_RegUnloadKey)
2940 croak("usage: Win32::RegUnLoadKey($hkey, $subkey);\n");
2943 REGRETURN(RegUnLoadKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na)));
2947 XS(w32_RegisterServer)
2950 BOOL bSuccess = FALSE;
2951 HINSTANCE hInstance;
2952 unsigned int length;
2957 croak("usage: Win32::RegisterServer($LibraryName)\n");
2960 hInstance = LoadLibrary((char *)SvPV(ST(0), length));
2961 if (hInstance != NULL)
2963 sFunc = GetProcAddress(hInstance, "DllRegisterServer");
2966 bSuccess = (sFunc() == 0);
2968 FreeLibrary(hInstance);
2979 XS(w32_UnregisterServer)
2982 BOOL bSuccess = FALSE;
2983 HINSTANCE hInstance;
2984 unsigned int length;
2989 croak("usage: Win32::UnregisterServer($LibraryName)\n");
2992 hInstance = LoadLibrary((char *)SvPV(ST(0), length));
2993 if (hInstance != NULL)
2995 sFunc = GetProcAddress(hInstance, "DllUnregisterServer");
2998 bSuccess = (sFunc() == 0);
3000 FreeLibrary(hInstance);
3012 Perl_init_os_extras()
3014 char *file = __FILE__;
3017 w32_perlshell_tokens = Nullch;
3018 w32_perlshell_items = -1;
3019 w32_fdpid = newAV(); /* XXX needs to be in Perl_win32_init()? */
3020 #ifndef USE_RTL_WAIT
3021 w32_num_children = 0;
3024 /* these names are Activeware compatible */
3025 newXS("Win32::GetCwd", w32_GetCwd, file);
3026 newXS("Win32::SetCwd", w32_SetCwd, file);
3027 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
3028 newXS("Win32::GetLastError", w32_GetLastError, file);
3029 newXS("Win32::LoginName", w32_LoginName, file);
3030 newXS("Win32::NodeName", w32_NodeName, file);
3031 newXS("Win32::DomainName", w32_DomainName, file);
3032 newXS("Win32::FsType", w32_FsType, file);
3033 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
3034 newXS("Win32::IsWinNT", w32_IsWinNT, file);
3035 newXS("Win32::IsWin95", w32_IsWin95, file);
3036 newXS("Win32::FormatMessage", w32_FormatMessage, file);
3037 newXS("Win32::Spawn", w32_Spawn, file);
3038 newXS("Win32::GetTickCount", w32_GetTickCount, file);
3039 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
3040 newXS("Win32::Sleep", w32_Sleep, file);
3042 /* the following extensions are used interally and may be changed at any time */
3043 /* therefore no documentation is provided */
3044 newXS("Win32::RegCloseKey", w32_RegCloseKey, file);
3045 newXS("Win32::RegConnectRegistry", w32_RegConnectRegistry, file);
3046 newXS("Win32::RegCreateKey", w32_RegCreateKey, file);
3047 newXS("Win32::RegCreateKeyEx", w32_RegCreateKeyEx, file);
3048 newXS("Win32::RegDeleteKey", w32_RegDeleteKey, file);
3049 newXS("Win32::RegDeleteValue", w32_RegDeleteValue, file);
3051 newXS("Win32::RegEnumKey", w32_RegEnumKey, file);
3052 newXS("Win32::RegEnumKeyEx", w32_RegEnumKeyEx, file);
3053 newXS("Win32::RegEnumValue", w32_RegEnumValue, file);
3055 newXS("Win32::RegFlushKey", w32_RegFlushKey, file);
3056 newXS("Win32::RegGetKeySecurity", w32_RegGetKeySecurity, file);
3058 newXS("Win32::RegLoadKey", w32_RegLoadKey, file);
3059 newXS("Win32::RegOpenKey", w32_RegOpenKey, file);
3060 newXS("Win32::RegOpenKeyEx", w32_RegOpenKeyEx, file);
3061 newXS("Win32::RegQueryInfoKey", w32_RegQueryInfoKey, file);
3062 newXS("Win32::RegQueryValue", w32_RegQueryValue, file);
3063 newXS("Win32::RegQueryValueEx", w32_RegQueryValueEx, file);
3065 newXS("Win32::RegReplaceKey", w32_RegReplaceKey, file);
3066 newXS("Win32::RegRestoreKey", w32_RegRestoreKey, file);
3067 newXS("Win32::RegSaveKey", w32_RegSaveKey, file);
3068 newXS("Win32::RegSetKeySecurity", w32_RegSetKeySecurity, file);
3069 newXS("Win32::RegSetValue", w32_RegSetValue, file);
3070 newXS("Win32::RegSetValueEx", w32_RegSetValueEx, file);
3071 newXS("Win32::RegUnloadKey", w32_RegUnloadKey, file);
3073 newXS("Win32::RegisterServer", w32_RegisterServer, file);
3074 newXS("Win32::UnregisterServer", w32_UnregisterServer, file);
3076 /* XXX Bloat Alert! The following Activeware preloads really
3077 * ought to be part of Win32::Sys::*, so they're not included
3080 /* LookupAccountName
3082 * InitiateSystemShutdown
3083 * AbortSystemShutdown
3084 * ExpandEnvrironmentStrings
3089 Perl_win32_init(int *argcp, char ***argvp)
3091 /* Disable floating point errors, Perl will trap the ones we
3092 * care about. VC++ RTL defaults to switching these off
3093 * already, but the Borland RTL doesn't. Since we don't
3094 * want to be at the vendor's whim on the default, we set
3095 * it explicitly here.
3097 #if !defined(_ALPHA_) && !defined(__GNUC__)
3098 _control87(MCW_EM, MCW_EM);
3103 #ifdef USE_BINMODE_SCRIPTS
3106 win32_strip_return(SV *sv)
3108 char *s = SvPVX(sv);
3109 char *e = s+SvCUR(sv);
3113 if (*s == '\r' && s[1] == '\n')
3123 SvCUR_set(sv,d-SvPVX(sv));