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 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 win32_get_stdlib(char *pl)
194 static char szStdLib[] = "lib";
195 int len = 0, newSize;
196 char szBuffer[MAX_PATH+1];
197 char szModuleName[MAX_PATH];
203 /* $stdlib = $HKCU{"lib-$]"} || $HKLM{"lib-$]"} || $HKCU{"lib"} || $HKLM{"lib"} || ""; */
204 sprintf(szBuffer, "%s-%s", szStdLib, pl);
205 lpPath = GetRegStr(szBuffer, &lpPath, &dwDataLen);
207 lpPath = GetRegStr(szStdLib, &lpPath, &dwDataLen);
209 /* $stdlib .= ";$EMD/../../lib" */
210 GetModuleFileName(GetModuleHandle(NULL), szModuleName, sizeof(szModuleName));
211 ptr = strrchr(szModuleName, '\\');
215 ptr = strrchr(szModuleName, '\\');
219 ptr = strrchr(szModuleName, '\\');
227 strcpy(++ptr, szStdLib);
229 /* check that this path exists */
230 GetCurrentDirectory(sizeof(szBuffer), szBuffer);
231 result = SetCurrentDirectory(szModuleName);
232 SetCurrentDirectory(szBuffer);
235 GetModuleFileName(GetModuleHandle(NULL), szModuleName, sizeof(szModuleName));
236 ptr = strrchr(szModuleName, '\\');
238 strcpy(++ptr, szStdLib);
241 newSize = strlen(szModuleName) + 1;
244 len = strlen(lpPath);
245 newSize += len + 1; /* plus 1 for ';' */
246 lpPath = Renew(lpPath, newSize, char);
249 New(1310, lpPath, newSize, char);
255 strcpy(&lpPath[len], szModuleName);
261 get_sitelib_part(char* lpRegStr, char* lpPathStr)
263 char szBuffer[MAX_PATH+1];
264 char szModuleName[MAX_PATH];
271 lpPath = GetRegStr(lpRegStr, &lpPath, &dwDataLen);
273 /* $sitelib .= ";$EMD/../../../<lpPathStr>" */
274 GetModuleFileName(GetModuleHandle(NULL), szModuleName, sizeof(szModuleName));
275 ptr = strrchr(szModuleName, '\\');
279 ptr = strrchr(szModuleName, '\\');
283 ptr = strrchr(szModuleName, '\\');
287 ptr = strrchr(szModuleName, '\\');
296 strcpy(++ptr, lpPathStr);
298 /* check that this path exists */
299 GetCurrentDirectory(sizeof(szBuffer), szBuffer);
300 result = SetCurrentDirectory(szModuleName);
301 SetCurrentDirectory(szBuffer);
305 int newSize = strlen(szModuleName) + 1;
308 len = strlen(lpPath);
309 newSize += len + 1; /* plus 1 for ';' */
310 lpPath = Renew(lpPath, newSize, char);
313 New(1311, lpPath, newSize, char);
319 strcpy(&lpPath[len], szModuleName);
326 win32_get_sitelib(char *pl)
328 static char szSiteLib[] = "sitelib";
330 char szPathStr[MAX_PATH];
335 /* $HKCU{"sitelib-$]"} || $HKLM{"sitelib-$]"} . ---; */
336 sprintf(szRegStr, "%s-%s", szSiteLib, pl);
337 sprintf(szPathStr, "site\\%s\\lib", pl);
338 lpPath1 = get_sitelib_part(szRegStr, szPathStr);
340 /* $HKCU{'sitelib'} || $HKLM{'sitelib'} . ---; */
341 lpPath2 = get_sitelib_part(szSiteLib, "site\\lib");
348 len = strlen(lpPath1);
349 newSize = len + strlen(lpPath2) + 2; /* plus one for ';' */
351 lpPath1 = Renew(lpPath1, newSize, char);
354 lpPath1[len++] = ';';
355 strcpy(&lpPath1[len], lpPath2);
363 has_redirection(char *ptr)
369 * Scan string looking for redirection (< or >) or pipe
370 * characters (|) that are not in a quoted string
400 #if !defined(PERL_OBJECT)
401 /* since the current process environment is being updated in util.c
402 * the library functions will get the correct environment
405 my_popen(char *cmd, char *mode)
408 #define fixcmd(x) { \
409 char *pspace = strchr((x),' '); \
412 while (p < pspace) { \
423 win32_fflush(stdout);
424 win32_fflush(stderr);
425 return win32_popen(cmd, mode);
429 my_pclose(PerlIO *fp)
431 return win32_pclose(fp);
438 static OSVERSIONINFO osver;
440 if (osver.dwPlatformId != w32_platform) {
441 memset(&osver, 0, sizeof(OSVERSIONINFO));
442 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
443 GetVersionEx(&osver);
444 w32_platform = osver.dwPlatformId;
446 return (w32_platform);
449 /* Tokenize a string. Words are null-separated, and the list
450 * ends with a doubled null. Any character (except null and
451 * including backslash) may be escaped by preceding it with a
452 * backslash (the backslash will be stripped).
453 * Returns number of words in result buffer.
456 tokenize(char *str, char **dest, char ***destv)
458 char *retstart = Nullch;
459 char **retvstart = 0;
462 int slen = strlen(str);
464 register char **retv;
465 New(1307, ret, slen+2, char);
466 New(1308, retv, (slen+3)/2, char*);
474 if (*ret == '\\' && *str)
476 else if (*ret == ' ') {
492 retvstart[items] = Nullch;
504 if (!w32_perlshell_tokens) {
505 /* we don't use COMSPEC here for two reasons:
506 * 1. the same reason perl on UNIX doesn't use SHELL--rampant and
507 * uncontrolled unportability of the ensuing scripts.
508 * 2. PERL5SHELL could be set to a shell that may not be fit for
509 * interactive use (which is what most programs look in COMSPEC
512 char* defaultshell = (IsWinNT() ? "cmd.exe /x/c" : "command.com /c");
513 char *usershell = getenv("PERL5SHELL");
514 w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
515 &w32_perlshell_tokens,
521 do_aspawn(void *vreally, void **vmark, void **vsp)
523 SV *really = (SV*)vreally;
524 SV **mark = (SV**)vmark;
536 New(1306, argv, (sp - mark) + w32_perlshell_items + 2, char*);
538 if (SvNIOKp(*(mark+1)) && !SvPOKp(*(mark+1))) {
543 while (++mark <= sp) {
544 if (*mark && (str = SvPV(*mark, na)))
551 status = win32_spawnvp(flag,
552 (const char*)(really ? SvPV(really,na) : argv[0]),
553 (const char* const*)argv);
555 if (status < 0 && errno == ENOEXEC) {
556 /* possible shell-builtin, invoke with shell */
558 sh_items = w32_perlshell_items;
560 argv[index+sh_items] = argv[index];
561 while (--sh_items >= 0)
562 argv[sh_items] = w32_perlshell_vec[sh_items];
564 status = win32_spawnvp(flag,
565 (const char*)(really ? SvPV(really,na) : argv[0]),
566 (const char* const*)argv);
569 if (flag != P_NOWAIT) {
572 warn("Can't spawn \"%s\": %s", argv[0], strerror(errno));
577 statusvalue = status;
584 do_spawn2(char *cmd, int exectype)
590 BOOL needToTry = TRUE;
593 /* Save an extra exec if possible. See if there are shell
594 * metacharacters in it */
595 if (!has_redirection(cmd)) {
596 New(1301,argv, strlen(cmd) / 2 + 2, char*);
597 New(1302,cmd2, strlen(cmd) + 1, char);
600 for (s = cmd2; *s;) {
601 while (*s && isspace(*s))
605 while (*s && !isspace(*s))
614 status = win32_spawnvp(P_WAIT, argv[0],
615 (const char* const*)argv);
617 case EXECF_SPAWN_NOWAIT:
618 status = win32_spawnvp(P_NOWAIT, argv[0],
619 (const char* const*)argv);
622 status = win32_execvp(argv[0], (const char* const*)argv);
625 if (status != -1 || errno == 0)
635 New(1306, argv, w32_perlshell_items + 2, char*);
636 while (++i < w32_perlshell_items)
637 argv[i] = w32_perlshell_vec[i];
642 status = win32_spawnvp(P_WAIT, argv[0],
643 (const char* const*)argv);
645 case EXECF_SPAWN_NOWAIT:
646 status = win32_spawnvp(P_NOWAIT, argv[0],
647 (const char* const*)argv);
650 status = win32_execvp(argv[0], (const char* const*)argv);
656 if (exectype != EXECF_SPAWN_NOWAIT) {
659 warn("Can't %s \"%s\": %s",
660 (exectype == EXECF_EXEC ? "exec" : "spawn"),
661 cmd, strerror(errno));
666 statusvalue = status;
674 return do_spawn2(cmd, EXECF_SPAWN);
678 do_spawn_nowait(char *cmd)
680 return do_spawn2(cmd, EXECF_SPAWN_NOWAIT);
686 do_spawn2(cmd, EXECF_EXEC);
690 /* The idea here is to read all the directory names into a string table
691 * (separated by nulls) and when one of the other dir functions is called
692 * return the pointer to the current file name.
695 opendir(char *filename)
700 char scanname[MAX_PATH+3];
702 WIN32_FIND_DATA FindData;
705 len = strlen(filename);
709 /* check to see if filename is a directory */
710 if (win32_stat(filename, &sbuf) < 0 || (sbuf.st_mode & S_IFDIR) == 0) {
711 /* CRT is buggy on sharenames, so make sure it really isn't */
712 DWORD r = GetFileAttributes(filename);
713 if (r == 0xffffffff || !(r & FILE_ATTRIBUTE_DIRECTORY))
717 /* Get us a DIR structure */
718 Newz(1303, p, 1, DIR);
722 /* Create the search pattern */
723 strcpy(scanname, filename);
724 if (scanname[len-1] != '/' && scanname[len-1] != '\\')
725 scanname[len++] = '/';
726 scanname[len++] = '*';
727 scanname[len] = '\0';
729 /* do the FindFirstFile call */
730 fh = FindFirstFile(scanname, &FindData);
731 if (fh == INVALID_HANDLE_VALUE) {
735 /* now allocate the first part of the string table for
736 * the filenames that we find.
738 idx = strlen(FindData.cFileName)+1;
739 New(1304, p->start, idx, char);
740 if (p->start == NULL)
741 croak("opendir: malloc failed!\n");
742 strcpy(p->start, FindData.cFileName);
745 /* loop finding all the files that match the wildcard
746 * (which should be all of them in this directory!).
747 * the variable idx should point one past the null terminator
748 * of the previous string found.
750 while (FindNextFile(fh, &FindData)) {
751 len = strlen(FindData.cFileName);
752 /* bump the string table size by enough for the
753 * new name and it's null terminator
755 Renew(p->start, idx+len+1, char);
756 if (p->start == NULL)
757 croak("opendir: malloc failed!\n");
758 strcpy(&p->start[idx], FindData.cFileName);
769 /* Readdir just returns the current string pointer and bumps the
770 * string pointer to the nDllExport entry.
776 static int dummy = 0;
779 /* first set up the structure to return */
780 len = strlen(dirp->curr);
781 strcpy(dirp->dirstr.d_name, dirp->curr);
782 dirp->dirstr.d_namlen = len;
785 dirp->dirstr.d_ino = dummy++;
787 /* Now set up for the nDllExport call to readdir */
788 dirp->curr += len + 1;
789 if (dirp->curr >= (dirp->start + dirp->size)) {
793 return &(dirp->dirstr);
799 /* Telldir returns the current string pointer position */
803 return (long) dirp->curr;
807 /* Seekdir moves the string pointer to a previously saved position
811 seekdir(DIR *dirp, long loc)
813 dirp->curr = (char *)loc;
816 /* Rewinddir resets the string pointer to the start */
820 dirp->curr = dirp->start;
823 /* free the memory allocated by opendir */
827 Safefree(dirp->start);
840 * Just pretend that everyone is a superuser. NT will let us know if
841 * we don\'t really have permission to do something.
844 #define ROOT_UID ((uid_t)0)
845 #define ROOT_GID ((gid_t)0)
874 return (auid == ROOT_UID ? 0 : -1);
880 return (agid == ROOT_GID ? 0 : -1);
887 char *buf = getlogin_buffer;
888 DWORD size = sizeof(getlogin_buffer);
889 if (GetUserName(buf,&size))
895 chown(const char *path, uid_t owner, gid_t group)
902 kill(int pid, int sig)
904 HANDLE hProcess= OpenProcess(PROCESS_ALL_ACCESS, TRUE, pid);
906 if (hProcess == NULL) {
907 croak("kill process failed!\n");
910 if (!TerminateProcess(hProcess, sig))
911 croak("kill process failed!\n");
912 CloseHandle(hProcess);
921 DllExport unsigned int
922 win32_sleep(unsigned int t)
929 win32_stat(const char *path, struct stat *buffer)
932 const char *p = path;
933 int l = strlen(path);
937 switch(path[l - 1]) {
940 if (path[l - 2] != ':') {
941 strncpy(t, path, l - 1);
947 res = stat(p,buffer);
950 if (S_ISDIR(buffer->st_mode))
951 buffer->st_mode |= S_IWRITE | S_IEXEC;
952 else if (S_ISREG(buffer->st_mode)) {
953 if (l >= 4 && path[l-4] == '.') {
954 const char *e = path + l - 3;
955 if (strnicmp(e,"exe",3)
956 && strnicmp(e,"bat",3)
957 && strnicmp(e,"com",3)
958 && (IsWin95() || strnicmp(e,"cmd",3)))
959 buffer->st_mode &= ~S_IEXEC;
961 buffer->st_mode |= S_IEXEC;
964 buffer->st_mode &= ~S_IEXEC;
971 #ifndef USE_WIN32_RTL_ENV
974 win32_getenv(const char *name)
976 static char *curitem = Nullch;
977 static DWORD curlen = 512;
980 New(1305,curitem,curlen,char);
981 if (!(needlen = GetEnvironmentVariable(name,curitem,curlen)))
983 while (needlen > curlen) {
984 Renew(curitem,needlen,char);
986 needlen = GetEnvironmentVariable(name,curitem,curlen);
990 if (strcmp("PERL5DB", name) == 0)
991 curitem = GetRegStr(name, &curitem, &curlen);
999 filetime_to_clock(PFILETIME ft)
1001 __int64 qw = ft->dwHighDateTime;
1003 qw |= ft->dwLowDateTime;
1004 qw /= 10000; /* File time ticks at 0.1uS, clock at 1mS */
1009 win32_times(struct tms *timebuf)
1014 if (GetProcessTimes(GetCurrentProcess(), &dummy, &dummy,
1016 timebuf->tms_utime = filetime_to_clock(&user);
1017 timebuf->tms_stime = filetime_to_clock(&kernel);
1018 timebuf->tms_cutime = 0;
1019 timebuf->tms_cstime = 0;
1022 /* That failed - e.g. Win95 fallback to clock() */
1023 clock_t t = clock();
1024 timebuf->tms_utime = t;
1025 timebuf->tms_stime = 0;
1026 timebuf->tms_cutime = 0;
1027 timebuf->tms_cstime = 0;
1032 /* fix utime() so it works on directories in NT
1033 * thanks to Jan Dubois <jan.dubois@ibm.net>
1036 filetime_from_time(PFILETIME pFileTime, time_t Time)
1038 struct tm *pTM = gmtime(&Time);
1039 SYSTEMTIME SystemTime;
1044 SystemTime.wYear = pTM->tm_year + 1900;
1045 SystemTime.wMonth = pTM->tm_mon + 1;
1046 SystemTime.wDay = pTM->tm_mday;
1047 SystemTime.wHour = pTM->tm_hour;
1048 SystemTime.wMinute = pTM->tm_min;
1049 SystemTime.wSecond = pTM->tm_sec;
1050 SystemTime.wMilliseconds = 0;
1052 return SystemTimeToFileTime(&SystemTime, pFileTime);
1056 win32_utime(const char *filename, struct utimbuf *times)
1062 struct utimbuf TimeBuffer;
1064 int rc = utime(filename,times);
1065 /* EACCES: path specifies directory or readonly file */
1066 if (rc == 0 || errno != EACCES /* || !IsWinNT() */)
1069 if (times == NULL) {
1070 times = &TimeBuffer;
1071 time(×->actime);
1072 times->modtime = times->actime;
1075 /* This will (and should) still fail on readonly files */
1076 handle = CreateFile(filename, GENERIC_READ | GENERIC_WRITE,
1077 FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,
1078 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1079 if (handle == INVALID_HANDLE_VALUE)
1082 if (GetFileTime(handle, &ftCreate, &ftAccess, &ftWrite) &&
1083 filetime_from_time(&ftAccess, times->actime) &&
1084 filetime_from_time(&ftWrite, times->modtime) &&
1085 SetFileTime(handle, &ftCreate, &ftAccess, &ftWrite))
1090 CloseHandle(handle);
1095 win32_wait(int *status)
1098 return wait(status);
1100 /* XXX this wait emulation only knows about processes
1101 * spawned via win32_spawnvp(P_NOWAIT, ...).
1104 DWORD exitcode, waitcode;
1106 if (!w32_num_children) {
1111 /* if a child exists, wait for it to die */
1112 waitcode = WaitForMultipleObjects(w32_num_children,
1116 if (waitcode != WAIT_FAILED) {
1117 if (waitcode >= WAIT_ABANDONED_0
1118 && waitcode < WAIT_ABANDONED_0 + w32_num_children)
1119 i = waitcode - WAIT_ABANDONED_0;
1121 i = waitcode - WAIT_OBJECT_0;
1122 if (GetExitCodeProcess(w32_child_pids[i], &exitcode) ) {
1123 CloseHandle(w32_child_pids[i]);
1124 *status = (int)((exitcode & 0xff) << 8);
1125 retval = (int)w32_child_pids[i];
1126 Copy(&w32_child_pids[i+1], &w32_child_pids[i],
1127 (w32_num_children-i-1), HANDLE);
1134 errno = GetLastError();
1140 static UINT timerid = 0;
1142 static VOID CALLBACK TimerProc(HWND win, UINT msg, UINT id, DWORD time)
1144 KillTimer(NULL,timerid);
1149 DllExport unsigned int
1150 win32_alarm(unsigned int sec)
1153 * the 'obvious' implentation is SetTimer() with a callback
1154 * which does whatever receiving SIGALRM would do
1155 * we cannot use SIGALRM even via raise() as it is not
1156 * one of the supported codes in <signal.h>
1158 * Snag is unless something is looking at the message queue
1159 * nothing happens :-(
1163 timerid = SetTimer(NULL,timerid,sec*1000,(TIMERPROC)TimerProc);
1165 croak("Cannot set timer");
1171 KillTimer(NULL,timerid);
1178 #ifdef HAVE_DES_FCRYPT
1179 extern char * des_fcrypt(char *cbuf, const char *txt, const char *salt);
1182 win32_crypt(const char *txt, const char *salt)
1185 return des_fcrypt(crypt_buffer, txt, salt);
1189 #ifdef USE_FIXED_OSFHANDLE
1191 EXTERN_C int __cdecl _alloc_osfhnd(void);
1192 EXTERN_C int __cdecl _set_osfhnd(int fh, long value);
1193 EXTERN_C void __cdecl _lock_fhandle(int);
1194 EXTERN_C void __cdecl _unlock_fhandle(int);
1195 EXTERN_C void __cdecl _unlock(int);
1197 #if (_MSC_VER >= 1000)
1199 long osfhnd; /* underlying OS file HANDLE */
1200 char osfile; /* attributes of file (e.g., open in text mode?) */
1201 char pipech; /* one char buffer for handles opened on pipes */
1202 #if defined (_MT) && !defined (DLL_FOR_WIN32S)
1204 CRITICAL_SECTION lock;
1205 #endif /* defined (_MT) && !defined (DLL_FOR_WIN32S) */
1208 EXTERN_C ioinfo * __pioinfo[];
1210 #define IOINFO_L2E 5
1211 #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
1212 #define _pioinfo(i) (__pioinfo[i >> IOINFO_L2E] + (i & (IOINFO_ARRAY_ELTS - 1)))
1213 #define _osfile(i) (_pioinfo(i)->osfile)
1215 #else /* (_MSC_VER >= 1000) */
1216 extern char _osfile[];
1217 #endif /* (_MSC_VER >= 1000) */
1219 #define FOPEN 0x01 /* file handle open */
1220 #define FAPPEND 0x20 /* file handle opened O_APPEND */
1221 #define FDEV 0x40 /* file handle refers to device */
1222 #define FTEXT 0x80 /* file handle is in text mode */
1224 #define _STREAM_LOCKS 26 /* Table of stream locks */
1225 #define _LAST_STREAM_LOCK (_STREAM_LOCKS+_NSTREAM_-1) /* Last stream lock */
1226 #define _FH_LOCKS (_LAST_STREAM_LOCK+1) /* Table of fh locks */
1229 *int my_open_osfhandle(long osfhandle, int flags) - open C Runtime file handle
1232 * This function allocates a free C Runtime file handle and associates
1233 * it with the Win32 HANDLE specified by the first parameter. This is a
1234 * temperary fix for WIN95's brain damage GetFileType() error on socket
1235 * we just bypass that call for socket
1238 * long osfhandle - Win32 HANDLE to associate with C Runtime file handle.
1239 * int flags - flags to associate with C Runtime file handle.
1242 * returns index of entry in fh, if successful
1243 * return -1, if no free entry is found
1247 *******************************************************************************/
1250 my_open_osfhandle(long osfhandle, int flags)
1253 char fileflags; /* _osfile flags */
1255 /* copy relevant flags from second parameter */
1258 if (flags & O_APPEND)
1259 fileflags |= FAPPEND;
1264 /* attempt to allocate a C Runtime file handle */
1265 if ((fh = _alloc_osfhnd()) == -1) {
1266 errno = EMFILE; /* too many open files */
1267 _doserrno = 0L; /* not an OS error */
1268 return -1; /* return error to caller */
1271 /* the file is open. now, set the info in _osfhnd array */
1272 _set_osfhnd(fh, osfhandle);
1274 fileflags |= FOPEN; /* mark as open */
1276 #if (_MSC_VER >= 1000)
1277 _osfile(fh) = fileflags; /* set osfile entry */
1278 _unlock_fhandle(fh);
1280 _osfile[fh] = fileflags; /* set osfile entry */
1281 _unlock(fh+_FH_LOCKS); /* unlock handle */
1284 return fh; /* return handle */
1287 #define _open_osfhandle my_open_osfhandle
1288 #endif /* USE_FIXED_OSFHANDLE */
1290 /* simulate flock by locking a range on the file */
1292 #define LK_ERR(f,i) ((f) ? (i = 0) : (errno = GetLastError()))
1293 #define LK_LEN 0xffff0000
1296 win32_flock(int fd, int oper)
1303 croak("flock() unimplemented on this platform");
1306 fh = (HANDLE)_get_osfhandle(fd);
1307 memset(&o, 0, sizeof(o));
1310 case LOCK_SH: /* shared lock */
1311 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, 0, &o),i);
1313 case LOCK_EX: /* exclusive lock */
1314 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, 0, &o),i);
1316 case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
1317 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, 0, &o),i);
1319 case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
1320 LK_ERR(LockFileEx(fh,
1321 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
1322 0, LK_LEN, 0, &o),i);
1324 case LOCK_UN: /* unlock lock */
1325 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, 0, &o),i);
1327 default: /* unknown */
1338 * redirected io subsystem for all XS modules
1351 return (&(_environ));
1354 /* the rest are the remapped stdio routines */
1374 win32_ferror(FILE *fp)
1376 return (ferror(fp));
1381 win32_feof(FILE *fp)
1387 * Since the errors returned by the socket error function
1388 * WSAGetLastError() are not known by the library routine strerror
1389 * we have to roll our own.
1393 win32_strerror(int e)
1395 #ifndef __BORLANDC__ /* Borland intolerance */
1396 extern int sys_nerr;
1400 if (e < 0 || e > sys_nerr) {
1405 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, &source, e, 0,
1406 strerror_buffer, sizeof(strerror_buffer), NULL) == 0)
1407 strcpy(strerror_buffer, "Unknown Error");
1409 return strerror_buffer;
1415 win32_str_os_error(void *sv, DWORD dwErr)
1419 dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER
1420 |FORMAT_MESSAGE_IGNORE_INSERTS
1421 |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
1422 dwErr, 0, (char *)&sMsg, 1, NULL);
1424 while (0 < dwLen && isspace(sMsg[--dwLen]))
1426 if ('.' != sMsg[dwLen])
1431 sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
1432 dwLen = sprintf(sMsg,
1433 "Unknown error #0x%lX (lookup 0x%lX)",
1434 dwErr, GetLastError());
1436 sv_setpvn((SV*)sv, sMsg, dwLen);
1442 win32_fprintf(FILE *fp, const char *format, ...)
1445 va_start(marker, format); /* Initialize variable arguments. */
1447 return (vfprintf(fp, format, marker));
1451 win32_printf(const char *format, ...)
1454 va_start(marker, format); /* Initialize variable arguments. */
1456 return (vprintf(format, marker));
1460 win32_vfprintf(FILE *fp, const char *format, va_list args)
1462 return (vfprintf(fp, format, args));
1466 win32_vprintf(const char *format, va_list args)
1468 return (vprintf(format, args));
1472 win32_fread(void *buf, size_t size, size_t count, FILE *fp)
1474 return fread(buf, size, count, fp);
1478 win32_fwrite(const void *buf, size_t size, size_t count, FILE *fp)
1480 return fwrite(buf, size, count, fp);
1484 win32_fopen(const char *filename, const char *mode)
1486 if (stricmp(filename, "/dev/null")==0)
1487 return fopen("NUL", mode);
1488 return fopen(filename, mode);
1491 #ifndef USE_SOCKETS_AS_HANDLES
1493 #define fdopen my_fdopen
1497 win32_fdopen( int handle, const char *mode)
1499 return fdopen(handle, (char *) mode);
1503 win32_freopen( const char *path, const char *mode, FILE *stream)
1505 if (stricmp(path, "/dev/null")==0)
1506 return freopen("NUL", mode, stream);
1507 return freopen(path, mode, stream);
1511 win32_fclose(FILE *pf)
1513 return my_fclose(pf); /* defined in win32sck.c */
1517 win32_fputs(const char *s,FILE *pf)
1519 return fputs(s, pf);
1523 win32_fputc(int c,FILE *pf)
1529 win32_ungetc(int c,FILE *pf)
1531 return ungetc(c,pf);
1535 win32_getc(FILE *pf)
1541 win32_fileno(FILE *pf)
1547 win32_clearerr(FILE *pf)
1554 win32_fflush(FILE *pf)
1560 win32_ftell(FILE *pf)
1566 win32_fseek(FILE *pf,long offset,int origin)
1568 return fseek(pf, offset, origin);
1572 win32_fgetpos(FILE *pf,fpos_t *p)
1574 return fgetpos(pf, p);
1578 win32_fsetpos(FILE *pf,const fpos_t *p)
1580 return fsetpos(pf, p);
1584 win32_rewind(FILE *pf)
1604 win32_fstat(int fd,struct stat *sbufptr)
1606 return fstat(fd,sbufptr);
1610 win32_pipe(int *pfd, unsigned int size, int mode)
1612 return _pipe(pfd, size, mode);
1616 * a popen() clone that respects PERL5SHELL
1620 win32_popen(const char *command, const char *mode)
1622 #ifdef USE_RTL_POPEN
1623 return _popen(command, mode);
1631 /* establish which ends read and write */
1632 if (strchr(mode,'w')) {
1633 stdfd = 0; /* stdin */
1637 else if (strchr(mode,'r')) {
1638 stdfd = 1; /* stdout */
1645 /* set the correct mode */
1646 if (strchr(mode,'b'))
1648 else if (strchr(mode,'t'))
1651 ourmode = _fmode & (O_TEXT | O_BINARY);
1653 /* the child doesn't inherit handles */
1654 ourmode |= O_NOINHERIT;
1656 if (win32_pipe( p, 512, ourmode) == -1)
1659 /* save current stdfd */
1660 if ((oldfd = win32_dup(stdfd)) == -1)
1663 /* make stdfd go to child end of pipe (implicitly closes stdfd) */
1664 /* stdfd will be inherited by the child */
1665 if (win32_dup2(p[child], stdfd) == -1)
1668 /* close the child end in parent */
1669 win32_close(p[child]);
1671 /* start the child */
1672 if ((childpid = do_spawn_nowait((char*)command)) == -1)
1675 /* revert stdfd to whatever it was before */
1676 if (win32_dup2(oldfd, stdfd) == -1)
1679 /* close saved handle */
1682 sv_setiv(*av_fetch(w32_fdpid, p[parent], TRUE), childpid);
1684 /* we have an fd, return a file stream */
1685 return (win32_fdopen(p[parent], (char *)mode));
1688 /* we don't need to check for errors here */
1692 win32_dup2(oldfd, stdfd);
1697 #endif /* USE_RTL_POPEN */
1705 win32_pclose(FILE *pf)
1707 #ifdef USE_RTL_POPEN
1711 #ifndef USE_RTL_WAIT
1715 int childpid, status;
1718 sv = *av_fetch(w32_fdpid, win32_fileno(pf), TRUE);
1720 childpid = SvIVX(sv);
1732 #ifndef USE_RTL_WAIT
1733 for (child = 0 ; child < w32_num_children ; ++child) {
1734 if (w32_child_pids[child] == (HANDLE)childpid) {
1735 Copy(&w32_child_pids[child+1], &w32_child_pids[child],
1736 (w32_num_children-child-1), HANDLE);
1743 /* wait for the child */
1744 if (cwait(&status, childpid, WAIT_CHILD) == -1)
1746 /* cwait() returns differently on Borland */
1748 return (((status >> 8) & 0xff) | ((status << 8) & 0xff00));
1753 #endif /* USE_RTL_POPEN */
1757 win32_setmode(int fd, int mode)
1759 return setmode(fd, mode);
1763 win32_lseek(int fd, long offset, int origin)
1765 return lseek(fd, offset, origin);
1775 win32_open(const char *path, int flag, ...)
1781 pmode = va_arg(ap, int);
1784 if (stricmp(path, "/dev/null")==0)
1785 return open("NUL", flag, pmode);
1786 return open(path,flag,pmode);
1808 win32_dup2(int fd1,int fd2)
1810 return dup2(fd1,fd2);
1814 win32_read(int fd, void *buf, unsigned int cnt)
1816 return read(fd, buf, cnt);
1820 win32_write(int fd, const void *buf, unsigned int cnt)
1822 return write(fd, buf, cnt);
1826 win32_mkdir(const char *dir, int mode)
1828 return mkdir(dir); /* just ignore mode */
1832 win32_rmdir(const char *dir)
1838 win32_chdir(const char *dir)
1844 win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
1848 #ifndef USE_RTL_WAIT
1849 if (mode == P_NOWAIT && w32_num_children >= MAXIMUM_WAIT_OBJECTS)
1853 status = spawnvp(mode, cmdname, (char * const *) argv);
1854 #ifndef USE_RTL_WAIT
1855 /* XXX For the P_NOWAIT case, Borland RTL returns pinfo.dwProcessId
1856 * while VC RTL returns pinfo.hProcess. For purposes of the custom
1857 * implementation of win32_wait(), we assume the latter.
1859 if (mode == P_NOWAIT && status >= 0)
1860 w32_child_pids[w32_num_children++] = (HANDLE)status;
1866 win32_execvp(const char *cmdname, const char *const *argv)
1868 return execvp(cmdname, (char *const *)argv);
1872 win32_perror(const char *str)
1878 win32_setbuf(FILE *pf, char *buf)
1884 win32_setvbuf(FILE *pf, char *buf, int type, size_t size)
1886 return setvbuf(pf, buf, type, size);
1890 win32_flushall(void)
1896 win32_fcloseall(void)
1902 win32_fgets(char *s, int n, FILE *pf)
1904 return fgets(s, n, pf);
1914 win32_fgetc(FILE *pf)
1920 win32_putc(int c, FILE *pf)
1926 win32_puts(const char *s)
1938 win32_putchar(int c)
1945 #ifndef USE_PERL_SBRK
1947 static char *committed = NULL;
1948 static char *base = NULL;
1949 static char *reserved = NULL;
1950 static char *brk = NULL;
1951 static DWORD pagesize = 0;
1952 static DWORD allocsize = 0;
1960 GetSystemInfo(&info);
1961 /* Pretend page size is larger so we don't perpetually
1962 * call the OS to commit just one page ...
1964 pagesize = info.dwPageSize << 3;
1965 allocsize = info.dwAllocationGranularity;
1967 /* This scheme fails eventually if request for contiguous
1968 * block is denied so reserve big blocks - this is only
1969 * address space not memory ...
1971 if (brk+need >= reserved)
1973 DWORD size = 64*1024*1024;
1975 if (committed && reserved && committed < reserved)
1977 /* Commit last of previous chunk cannot span allocations */
1978 addr = (char *) VirtualAlloc(committed,reserved-committed,MEM_COMMIT,PAGE_READWRITE);
1980 committed = reserved;
1982 /* Reserve some (more) space
1983 * Note this is a little sneaky, 1st call passes NULL as reserved
1984 * so lets system choose where we start, subsequent calls pass
1985 * the old end address so ask for a contiguous block
1987 addr = (char *) VirtualAlloc(reserved,size,MEM_RESERVE,PAGE_NOACCESS);
1990 reserved = addr+size;
2005 if (brk > committed)
2007 DWORD size = ((brk-committed + pagesize -1)/pagesize) * pagesize;
2008 char *addr = (char *) VirtualAlloc(committed,size,MEM_COMMIT,PAGE_READWRITE);
2023 win32_malloc(size_t size)
2025 return malloc(size);
2029 win32_calloc(size_t numitems, size_t size)
2031 return calloc(numitems,size);
2035 win32_realloc(void *block, size_t size)
2037 return realloc(block,size);
2041 win32_free(void *block)
2048 win32_open_osfhandle(long handle, int flags)
2050 return _open_osfhandle(handle, flags);
2054 win32_get_osfhandle(int fd)
2056 return _get_osfhandle(fd);
2067 SV *sv = sv_newmortal();
2068 /* Make one call with zero size - return value is required size */
2069 DWORD len = GetCurrentDirectory((DWORD)0,NULL);
2070 SvUPGRADE(sv,SVt_PV);
2072 SvCUR(sv) = GetCurrentDirectory((DWORD) SvLEN(sv), SvPVX(sv));
2075 * then it worked, set PV valid,
2076 * else leave it 'undef'
2090 croak("usage: Win32::SetCurrentDirectory($cwd)");
2091 if (SetCurrentDirectory(SvPV(ST(0),na)))
2098 XS(w32_GetNextAvailDrive)
2102 char root[] = "_:\\";
2105 if (GetDriveType(root) == 1) {
2114 XS(w32_GetLastError)
2117 XSRETURN_IV(GetLastError());
2124 char *name = getlogin_buffer;
2125 DWORD size = sizeof(getlogin_buffer);
2126 if (GetUserName(name,&size)) {
2127 /* size includes NULL */
2128 ST(0) = sv_2mortal(newSVpv(name,size-1));
2138 char name[MAX_COMPUTERNAME_LENGTH+1];
2139 DWORD size = sizeof(name);
2140 if (GetComputerName(name,&size)) {
2141 /* size does NOT include NULL :-( */
2142 ST(0) = sv_2mortal(newSVpv(name,size));
2153 #ifndef HAS_NETWKSTAGETINFO
2154 /* mingw32 (and Win95) don't have NetWksta*(), so do it the old way */
2156 DWORD size = sizeof(name);
2157 if (GetUserName(name,&size)) {
2159 DWORD sidlen = sizeof(sid);
2161 DWORD dnamelen = sizeof(dname);
2163 if (LookupAccountName(NULL, name, &sid, &sidlen,
2164 dname, &dnamelen, &snu)) {
2165 XSRETURN_PV(dname); /* all that for this */
2169 /* this way is more reliable, in case user has a local account.
2170 * XXX need dynamic binding of netapi32.dll symbols or this will fail on
2171 * Win95. Probably makes more sense to move it into libwin32. */
2173 DWORD dnamelen = sizeof(dname);
2174 PWKSTA_INFO_100 pwi;
2175 if (NERR_Success == NetWkstaGetInfo(NULL, 100, (LPBYTE*)&pwi)) {
2176 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
2177 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
2178 -1, (LPSTR)dname, dnamelen, NULL, NULL);
2181 WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
2182 -1, (LPSTR)dname, dnamelen, NULL, NULL);
2184 NetApiBufferFree(pwi);
2196 DWORD flags, filecomplen;
2197 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
2198 &flags, fsname, sizeof(fsname))) {
2199 if (GIMME == G_ARRAY) {
2200 XPUSHs(sv_2mortal(newSVpv(fsname,0)));
2201 XPUSHs(sv_2mortal(newSViv(flags)));
2202 XPUSHs(sv_2mortal(newSViv(filecomplen)));
2206 XSRETURN_PV(fsname);
2212 XS(w32_GetOSVersion)
2215 OSVERSIONINFO osver;
2217 osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
2218 if (GetVersionEx(&osver)) {
2219 XPUSHs(newSVpv(osver.szCSDVersion, 0));
2220 XPUSHs(newSViv(osver.dwMajorVersion));
2221 XPUSHs(newSViv(osver.dwMinorVersion));
2222 XPUSHs(newSViv(osver.dwBuildNumber));
2223 XPUSHs(newSViv(osver.dwPlatformId));
2234 XSRETURN_IV(IsWinNT());
2241 XSRETURN_IV(IsWin95());
2245 XS(w32_FormatMessage)
2252 croak("usage: Win32::FormatMessage($errno)");
2254 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
2255 &source, SvIV(ST(0)), 0,
2256 msgbuf, sizeof(msgbuf)-1, NULL))
2257 XSRETURN_PV(msgbuf);
2267 PROCESS_INFORMATION stProcInfo;
2268 STARTUPINFO stStartInfo;
2269 BOOL bSuccess = FALSE;
2272 croak("usage: Win32::Spawn($cmdName, $args, $PID)");
2274 cmd = SvPV(ST(0),na);
2275 args = SvPV(ST(1), na);
2277 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
2278 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
2279 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
2280 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
2283 cmd, /* Image path */
2284 args, /* Arguments for command line */
2285 NULL, /* Default process security */
2286 NULL, /* Default thread security */
2287 FALSE, /* Must be TRUE to use std handles */
2288 NORMAL_PRIORITY_CLASS, /* No special scheduling */
2289 NULL, /* Inherit our environment block */
2290 NULL, /* Inherit our currrent directory */
2291 &stStartInfo, /* -> Startup info */
2292 &stProcInfo)) /* <- Process info (if OK) */
2294 CloseHandle(stProcInfo.hThread);/* library source code does this. */
2295 sv_setiv(ST(2), stProcInfo.dwProcessId);
2298 XSRETURN_IV(bSuccess);
2302 XS(w32_GetTickCount)
2305 XSRETURN_IV(GetTickCount());
2309 XS(w32_GetShortPathName)
2316 croak("usage: Win32::GetShortPathName($longPathName)");
2318 shortpath = sv_mortalcopy(ST(0));
2319 SvUPGRADE(shortpath, SVt_PV);
2320 /* src == target is allowed */
2322 len = GetShortPathName(SvPVX(shortpath),
2325 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
2327 SvCUR_set(shortpath,len);
2340 croak("usage: Win32::Sleep($milliseconds)");
2345 #define TMPBUFSZ 1024
2346 #define MAX_LENGTH 2048
2347 #define SUCCESSRETURNED(x) (x == ERROR_SUCCESS)
2348 #define REGRETURN(x) XSRETURN_IV(SUCCESSRETURNED(x))
2349 #define SvHKEY(index) (HKEY)((unsigned long)SvIV(index))
2350 #define SETIV(index,value) sv_setiv(ST(index), value)
2351 #define SETNV(index,value) sv_setnv(ST(index), value)
2352 #define SETPV(index,string) sv_setpv(ST(index), string)
2353 #define SETPVN(index, buffer, length) sv_setpvn(ST(index), (char*)buffer, length)
2354 #define SETHKEY(index, hkey) SETIV(index,(long)hkey)
2356 static time_t ft2timet(FILETIME *ft)
2361 FileTimeToSystemTime(ft, &st);
2362 tm.tm_sec = st.wSecond;
2363 tm.tm_min = st.wMinute;
2364 tm.tm_hour = st.wHour;
2365 tm.tm_mday = st.wDay;
2366 tm.tm_mon = st.wMonth - 1;
2367 tm.tm_year = st.wYear - 1900;
2368 tm.tm_wday = st.wDayOfWeek;
2371 return mktime (&tm);
2381 croak("usage: Win32::RegCloseKey($hkey);\n");
2384 REGRETURN(RegCloseKey(SvHKEY(ST(0))));
2388 XS(w32_RegConnectRegistry)
2395 croak("usage: Win32::RegConnectRegistry($machine, $hkey, $handle);\n");
2398 if (SUCCESSRETURNED(RegConnectRegistry((char *)SvPV(ST(0), na), SvHKEY(ST(1)), &handle)))
2407 XS(w32_RegCreateKey)
2416 croak("usage: Win32::RegCreateKey($hkey, $subkey, $handle);\n");
2419 retval = RegCreateKeyEx(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS,
2420 NULL, &handle, &disposition);
2422 if (SUCCESSRETURNED(retval))
2431 XS(w32_RegCreateKeyEx)
2435 unsigned int length;
2440 DWORD options, disposition;
2442 SECURITY_ATTRIBUTES sa, *psa;
2446 croak("usage: Win32::RegCreateKeyEx($hkey, $subkey, $reserved, $class, $options, $sam, "
2447 "$security, $handle, $disposition);\n");
2450 hkey = SvHKEY(ST(0));
2451 subkey = (char *)SvPV(ST(1), na);
2452 keyclass = (char *)SvPV(ST(3), na);
2453 options = (DWORD) ((unsigned long)SvIV(ST(4)));
2454 sam = (REGSAM) ((unsigned long)SvIV(ST(5)));
2455 psa = (SECURITY_ATTRIBUTES*)SvPV(ST(6), length);
2456 if (length != sizeof(SECURITY_ATTRIBUTES))
2459 memset(&sa, 0, sizeof(SECURITY_ATTRIBUTES));
2460 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
2463 retval = RegCreateKeyEx(hkey, subkey, 0, keyclass, options, sam,
2464 psa, &handle, &disposition);
2466 if (SUCCESSRETURNED(retval))
2469 SETPVN(6, &sa, sizeof(sa));
2472 SETIV(8,disposition);
2479 XS(w32_RegDeleteKey)
2485 croak("usage: Win32::RegDeleteKey($hkey, $subkey);\n");
2488 REGRETURN(RegDeleteKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na)));
2492 XS(w32_RegDeleteValue)
2498 croak("usage: Win32::RegDeleteValue($hkey, $valname);\n");
2501 REGRETURN(RegDeleteValue(SvHKEY(ST(0)), (char *)SvPV(ST(1), na)));
2509 char keybuffer[TMPBUFSZ];
2513 croak("usage: Win32::RegEnumKey($hkey, $idx, $subkeyname);\n");
2516 if (SUCCESSRETURNED(RegEnumKey(SvHKEY(ST(0)), SvIV(ST(1)), keybuffer, sizeof(keybuffer))))
2518 SETPV(2, keybuffer);
2525 XS(w32_RegEnumKeyEx)
2530 DWORD keysz, classsz;
2531 char keybuffer[TMPBUFSZ];
2532 char classbuffer[TMPBUFSZ];
2538 croak("usage: Win32::RegEnumKeyEx($hkey, $idx, $subkeyname, $reserved, $class, $time);\n");
2541 keysz = sizeof(keybuffer);
2542 classsz = sizeof(classbuffer);
2543 retval = RegEnumKeyEx(SvHKEY(ST(0)), SvIV(ST(1)), keybuffer, &keysz, 0,
2544 classbuffer, &classsz, &filetime);
2545 if (SUCCESSRETURNED(retval))
2547 SETPV(2, keybuffer);
2548 SETPV(4, classbuffer);
2549 SETIV(5, ft2timet(&filetime));
2556 XS(w32_RegEnumValue)
2560 DWORD type, namesz, valsz;
2562 static HKEY last_hkey;
2563 char myvalbuf[MAX_LENGTH];
2564 char mynambuf[MAX_LENGTH];
2568 croak("usage: Win32::RegEnumValue($hkey, $i, $name, $reserved, $type, $value);\n");
2571 hkey = SvHKEY(ST(0));
2573 // If this is a new key, find out how big the maximum name and value sizes are and
2574 // allocate space for them. Free any old storage and set the old key value to the
2577 if (hkey != (HKEY)last_hkey)
2579 char keyclass[TMPBUFSZ];
2580 DWORD classsz, subkeys, maxsubkey, maxclass, values, salen, maxnamesz, maxvalsz;
2582 classsz = sizeof(keyclass);
2583 retval = RegQueryInfoKey(hkey, keyclass, &classsz, 0, &subkeys, &maxsubkey, &maxclass,
2584 &values, &maxnamesz, &maxvalsz, &salen, &ft);
2586 if (!SUCCESSRETURNED(retval))
2590 memset(myvalbuf, 0, MAX_LENGTH);
2591 memset(mynambuf, 0, MAX_LENGTH);
2595 namesz = MAX_LENGTH;
2597 retval = RegEnumValue(hkey, SvIV(ST(1)), mynambuf, &namesz, 0, &type, (LPBYTE) myvalbuf, &valsz);
2598 if (!SUCCESSRETURNED(retval))
2607 // return includes the null terminator so delete it if REG_SZ, REG_MULTI_SZ or REG_EXPAND_SZ
2616 SETPVN(5, myvalbuf, valsz);
2619 case REG_DWORD_BIG_ENDIAN:
2621 BYTE tmp = myvalbuf[0];
2622 myvalbuf[0] = myvalbuf[3];
2625 myvalbuf[1] = myvalbuf[2];
2628 case REG_DWORD_LITTLE_ENDIAN: // same as REG_DWORD
2629 SETNV(5, (double)*((DWORD*)myvalbuf));
2647 croak("usage: Win32::RegFlushKey($hkey);\n");
2650 REGRETURN(RegFlushKey(SvHKEY(ST(0))));
2654 XS(w32_RegGetKeySecurity)
2657 SECURITY_DESCRIPTOR sd;
2662 croak("usage: Win32::RegGetKeySecurity($hkey, $security_info, $security_descriptor);\n");
2665 if (SUCCESSRETURNED(RegGetKeySecurity(SvHKEY(ST(0)), SvIV(ST(1)), &sd, &sdsz)))
2667 SETPVN(2, &sd, sdsz);
2680 croak("usage: Win32::RegLoadKey($hkey, $subkey, $filename);\n");
2683 REGRETURN(RegLoadKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), (char *)SvPV(ST(2), na)));
2687 XS(w32_RegNotifyChangeKeyValue)
2689 croak("Win32::RegNotifyChangeKeyValue not yet implemented!\n");
2700 croak("usage: Win32::RegOpenKey($hkey, $subkey, $handle);\n");
2703 if (SUCCESSRETURNED(RegOpenKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), &handle)))
2712 XS(w32_RegOpenKeyEx)
2719 croak("usage: Win32::RegOpenKeyEx($hkey, $subkey, $reserved, $sam, $handle);\n");
2722 if (SUCCESSRETURNED(RegOpenKeyEx(SvHKEY(ST(0)), (char *)SvPV(ST(1), na),
2723 0, (REGSAM) ((unsigned long)SvIV(ST(3))), &handle)))
2731 #pragma optimize("", off)
2733 XS(w32_RegQueryInfoKey)
2738 char keyclass[TMPBUFSZ];
2739 DWORD subkeys, maxsubkey, maxclass, values, maxvalname, maxvaldata;
2740 DWORD seclen, classsz;
2746 croak("usage: Win32::RegQueryInfoKey($hkey, $class, $numsubkeys, $maxsubkey,"
2747 "$maxclass, $values, $maxvalname, $maxvaldata, $secdesclen,"
2748 "$lastwritetime);\n");
2751 classsz = sizeof(keyclass);
2752 retval = RegQueryInfoKey(SvHKEY(ST(0)), keyclass, &classsz, 0, &subkeys, &maxsubkey,
2753 &maxclass, &values, &maxvalname, &maxvaldata,
2755 if (SUCCESSRETURNED(retval))
2759 SETIV(3, maxsubkey);
2762 SETIV(6, maxvalname);
2763 SETIV(7, maxvaldata);
2765 SETIV(9, ft2timet(&ft));
2770 #pragma optimize("", on)
2773 XS(w32_RegQueryValue)
2777 unsigned char databuffer[TMPBUFSZ*2];
2778 long datasz = sizeof(databuffer);
2782 croak("usage: Win32::RegQueryValue($hkey, $valuename, $data);\n");
2785 if (SUCCESSRETURNED(RegQueryValue(SvHKEY(ST(0)), SvPV(ST(1), na), (char*)databuffer, &datasz)))
2787 // return includes the null terminator so delete it
2788 SETPVN(2, databuffer, --datasz);
2795 XS(w32_RegQueryValueEx)
2799 unsigned char databuffer[TMPBUFSZ*2];
2800 DWORD datasz = sizeof(databuffer);
2803 LPBYTE ptr = databuffer;
2807 croak("usage: Win32::RegQueryValueEx($hkey, $valuename, $reserved, $type, $data);\n");
2810 result = RegQueryValueEx(SvHKEY(ST(0)), SvPV(ST(1), na), 0, &type, ptr, &datasz);
2811 if (result == ERROR_MORE_DATA)
2813 New(0, ptr, datasz+1, BYTE);
2814 result = RegQueryValueEx(SvHKEY(ST(0)), SvPV(ST(1), na), 0, &type, ptr, &datasz);
2816 if (SUCCESSRETURNED(result))
2820 // return includes the null terminator so delete it if REG_SZ, REG_MULTI_SZ or REG_EXPAND_SZ
2828 SETPVN(4, ptr, datasz);
2831 case REG_DWORD_BIG_ENDIAN:
2840 case REG_DWORD_LITTLE_ENDIAN: // same as REG_DWORD
2841 SETNV(4, (double)*((DWORD*)ptr));
2848 if (ptr != databuffer)
2853 if (ptr != databuffer)
2860 XS(w32_RegReplaceKey)
2866 croak("usage: Win32::RegReplaceKey($hkey, $subkey, $newfile, $oldfile);\n");
2869 REGRETURN(RegReplaceKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), (char *)SvPV(ST(2), na), (char *)SvPV(ST(3), na)));
2873 XS(w32_RegRestoreKey)
2877 if (items < 2 || items > 3)
2879 croak("usage: Win32::RegRestoreKey($hkey, $filename [, $flags]);\n");
2882 REGRETURN(RegRestoreKey(SvHKEY(ST(0)), (char*)SvPV(ST(1), na), (DWORD)((items == 3) ? SvIV(ST(2)) : 0)));
2892 croak("usage: Win32::RegSaveKey($hkey, $filename);\n");
2895 REGRETURN(RegSaveKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), NULL));
2899 XS(w32_RegSetKeySecurity)
2905 croak("usage: Win32::RegSetKeySecurity($hkey, $security_info, $security_descriptor);\n");
2908 REGRETURN(RegSetKeySecurity(SvHKEY(ST(0)), SvIV(ST(1)), (SECURITY_DESCRIPTOR*)SvPV(ST(2), na)));
2922 croak("usage: Win32::RegSetValue($hkey, $subKey, $type, $data);\n");
2926 if (type != REG_SZ && type != REG_EXPAND_SZ)
2928 croak("Win32::RegSetValue: Type was not REG_SZ or REG_EXPAND_SZ, cannot set %s\n", (char *)SvPV(ST(1), na));
2931 buffer = (char *)SvPV(ST(3), size);
2932 REGRETURN(RegSetValue(SvHKEY(ST(0)), SvPV(ST(1), na), REG_SZ, buffer, size));
2936 XS(w32_RegSetValueEx)
2947 croak("usage: Win32::RegSetValueEx($hkey, $valname, $reserved, $type, $data);\n");
2950 type = (DWORD)SvIV(ST(3));
2957 buffer = (char *)SvPV(ST(4), size);
2958 if (type != REG_BINARY)
2959 size++; // include null terminator in size
2961 REGRETURN(RegSetValueEx(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), 0, type, (PBYTE) buffer, size));
2964 case REG_DWORD_BIG_ENDIAN:
2965 case REG_DWORD_LITTLE_ENDIAN: // Same as REG_DWORD
2966 val = (DWORD)SvIV(ST(4));
2967 REGRETURN(RegSetValueEx(SvHKEY(ST(0)), (char *)SvPV(ST(1), na), 0, type, (PBYTE) &val, sizeof(DWORD)));
2971 croak("Win32::RegSetValueEx: Type not specified, cannot set %s\n", (char *)SvPV(ST(1), na));
2976 XS(w32_RegUnloadKey)
2982 croak("usage: Win32::RegUnLoadKey($hkey, $subkey);\n");
2985 REGRETURN(RegUnLoadKey(SvHKEY(ST(0)), (char *)SvPV(ST(1), na)));
2989 XS(w32_RegisterServer)
2992 BOOL bSuccess = FALSE;
2993 HINSTANCE hInstance;
2994 unsigned int length;
2999 croak("usage: Win32::RegisterServer($LibraryName)\n");
3002 hInstance = LoadLibrary((char *)SvPV(ST(0), length));
3003 if (hInstance != NULL)
3005 sFunc = GetProcAddress(hInstance, "DllRegisterServer");
3008 bSuccess = (sFunc() == 0);
3010 FreeLibrary(hInstance);
3021 XS(w32_UnregisterServer)
3024 BOOL bSuccess = FALSE;
3025 HINSTANCE hInstance;
3026 unsigned int length;
3031 croak("usage: Win32::UnregisterServer($LibraryName)\n");
3034 hInstance = LoadLibrary((char *)SvPV(ST(0), length));
3035 if (hInstance != NULL)
3037 sFunc = GetProcAddress(hInstance, "DllUnregisterServer");
3040 bSuccess = (sFunc() == 0);
3042 FreeLibrary(hInstance);
3054 Perl_init_os_extras()
3056 char *file = __FILE__;
3059 w32_perlshell_tokens = Nullch;
3060 w32_perlshell_items = -1;
3061 w32_fdpid = newAV(); /* XXX needs to be in Perl_win32_init()? */
3062 #ifndef USE_RTL_WAIT
3063 w32_num_children = 0;
3066 /* these names are Activeware compatible */
3067 newXS("Win32::GetCwd", w32_GetCwd, file);
3068 newXS("Win32::SetCwd", w32_SetCwd, file);
3069 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
3070 newXS("Win32::GetLastError", w32_GetLastError, file);
3071 newXS("Win32::LoginName", w32_LoginName, file);
3072 newXS("Win32::NodeName", w32_NodeName, file);
3073 newXS("Win32::DomainName", w32_DomainName, file);
3074 newXS("Win32::FsType", w32_FsType, file);
3075 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
3076 newXS("Win32::IsWinNT", w32_IsWinNT, file);
3077 newXS("Win32::IsWin95", w32_IsWin95, file);
3078 newXS("Win32::FormatMessage", w32_FormatMessage, file);
3079 newXS("Win32::Spawn", w32_Spawn, file);
3080 newXS("Win32::GetTickCount", w32_GetTickCount, file);
3081 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
3082 newXS("Win32::Sleep", w32_Sleep, file);
3084 /* the following extensions are used interally and may be changed at any time */
3085 /* therefore no documentation is provided */
3086 newXS("Win32::RegCloseKey", w32_RegCloseKey, file);
3087 newXS("Win32::RegConnectRegistry", w32_RegConnectRegistry, file);
3088 newXS("Win32::RegCreateKey", w32_RegCreateKey, file);
3089 newXS("Win32::RegCreateKeyEx", w32_RegCreateKeyEx, file);
3090 newXS("Win32::RegDeleteKey", w32_RegDeleteKey, file);
3091 newXS("Win32::RegDeleteValue", w32_RegDeleteValue, file);
3093 newXS("Win32::RegEnumKey", w32_RegEnumKey, file);
3094 newXS("Win32::RegEnumKeyEx", w32_RegEnumKeyEx, file);
3095 newXS("Win32::RegEnumValue", w32_RegEnumValue, file);
3097 newXS("Win32::RegFlushKey", w32_RegFlushKey, file);
3098 newXS("Win32::RegGetKeySecurity", w32_RegGetKeySecurity, file);
3100 newXS("Win32::RegLoadKey", w32_RegLoadKey, file);
3101 newXS("Win32::RegOpenKey", w32_RegOpenKey, file);
3102 newXS("Win32::RegOpenKeyEx", w32_RegOpenKeyEx, file);
3103 newXS("Win32::RegQueryInfoKey", w32_RegQueryInfoKey, file);
3104 newXS("Win32::RegQueryValue", w32_RegQueryValue, file);
3105 newXS("Win32::RegQueryValueEx", w32_RegQueryValueEx, file);
3107 newXS("Win32::RegReplaceKey", w32_RegReplaceKey, file);
3108 newXS("Win32::RegRestoreKey", w32_RegRestoreKey, file);
3109 newXS("Win32::RegSaveKey", w32_RegSaveKey, file);
3110 newXS("Win32::RegSetKeySecurity", w32_RegSetKeySecurity, file);
3111 newXS("Win32::RegSetValue", w32_RegSetValue, file);
3112 newXS("Win32::RegSetValueEx", w32_RegSetValueEx, file);
3113 newXS("Win32::RegUnloadKey", w32_RegUnloadKey, file);
3115 newXS("Win32::RegisterServer", w32_RegisterServer, file);
3116 newXS("Win32::UnregisterServer", w32_UnregisterServer, file);
3118 /* XXX Bloat Alert! The following Activeware preloads really
3119 * ought to be part of Win32::Sys::*, so they're not included
3122 /* LookupAccountName
3124 * InitiateSystemShutdown
3125 * AbortSystemShutdown
3126 * ExpandEnvrironmentStrings
3131 Perl_win32_init(int *argcp, char ***argvp)
3133 /* Disable floating point errors, Perl will trap the ones we
3134 * care about. VC++ RTL defaults to switching these off
3135 * already, but the Borland RTL doesn't. Since we don't
3136 * want to be at the vendor's whim on the default, we set
3137 * it explicitly here.
3139 #if !defined(_ALPHA_) && !defined(__GNUC__)
3140 _control87(MCW_EM, MCW_EM);
3145 #ifdef USE_BINMODE_SCRIPTS
3148 win32_strip_return(SV *sv)
3150 char *s = SvPVX(sv);
3151 char *e = s+SvCUR(sv);
3155 if (*s == '\r' && s[1] == '\n')
3165 SvCUR_set(sv,d-SvPVX(sv));