5 #define PERL_NO_GET_CONTEXT
11 # define countof(array) (sizeof (array) / sizeof (*(array)))
14 #define SE_SHUTDOWN_NAMEA "SeShutdownPrivilege"
16 #ifndef WC_NO_BEST_FIT_CHARS
17 # define WC_NO_BEST_FIT_CHARS 0x00000400
20 #define GETPROC(fn) pfn##fn = (PFN##fn)GetProcAddress(module, #fn)
22 typedef BOOL (WINAPI *PFNSHGetSpecialFolderPathA)(HWND, char*, int, BOOL);
23 typedef BOOL (WINAPI *PFNSHGetSpecialFolderPathW)(HWND, WCHAR*, int, BOOL);
24 typedef HRESULT (WINAPI *PFNSHGetFolderPathA)(HWND, int, HANDLE, DWORD, LPTSTR);
25 typedef HRESULT (WINAPI *PFNSHGetFolderPathW)(HWND, int, HANDLE, DWORD, LPWSTR);
26 typedef BOOL (WINAPI *PFNCreateEnvironmentBlock)(void**, HANDLE, BOOL);
27 typedef BOOL (WINAPI *PFNDestroyEnvironmentBlock)(void*);
28 typedef int (__stdcall *PFNDllRegisterServer)(void);
29 typedef int (__stdcall *PFNDllUnregisterServer)(void);
30 typedef DWORD (__stdcall *PFNNetApiBufferFree)(void*);
31 typedef DWORD (__stdcall *PFNNetWkstaGetInfo)(LPWSTR, DWORD, void*);
33 typedef BOOL (__stdcall *PFNOpenProcessToken)(HANDLE, DWORD, HANDLE*);
34 typedef BOOL (__stdcall *PFNOpenThreadToken)(HANDLE, DWORD, BOOL, HANDLE*);
35 typedef BOOL (__stdcall *PFNGetTokenInformation)(HANDLE, TOKEN_INFORMATION_CLASS, void*, DWORD, DWORD*);
36 typedef BOOL (__stdcall *PFNAllocateAndInitializeSid)(PSID_IDENTIFIER_AUTHORITY, BYTE, DWORD, DWORD,
37 DWORD, DWORD, DWORD, DWORD, DWORD, DWORD, PSID*);
38 typedef BOOL (__stdcall *PFNEqualSid)(PSID, PSID);
39 typedef void* (__stdcall *PFNFreeSid)(PSID);
40 typedef BOOL (__stdcall *PFNIsUserAnAdmin)();
43 # define CSIDL_MYMUSIC 0x000D
46 # define CSIDL_MYVIDEO 0x000E
48 #ifndef CSIDL_LOCAL_APPDATA
49 # define CSIDL_LOCAL_APPDATA 0x001C
51 #ifndef CSIDL_COMMON_FAVORITES
52 # define CSIDL_COMMON_FAVORITES 0x001F
54 #ifndef CSIDL_INTERNET_CACHE
55 # define CSIDL_INTERNET_CACHE 0x0020
58 # define CSIDL_COOKIES 0x0021
61 # define CSIDL_HISTORY 0x0022
63 #ifndef CSIDL_COMMON_APPDATA
64 # define CSIDL_COMMON_APPDATA 0x0023
67 # define CSIDL_WINDOWS 0x0024
69 #ifndef CSIDL_PROGRAM_FILES
70 # define CSIDL_PROGRAM_FILES 0x0026
72 #ifndef CSIDL_MYPICTURES
73 # define CSIDL_MYPICTURES 0x0027
76 # define CSIDL_PROFILE 0x0028
78 #ifndef CSIDL_PROGRAM_FILES_COMMON
79 # define CSIDL_PROGRAM_FILES_COMMON 0x002B
81 #ifndef CSIDL_COMMON_TEMPLATES
82 # define CSIDL_COMMON_TEMPLATES 0x002D
84 #ifndef CSIDL_COMMON_DOCUMENTS
85 # define CSIDL_COMMON_DOCUMENTS 0x002E
87 #ifndef CSIDL_COMMON_ADMINTOOLS
88 # define CSIDL_COMMON_ADMINTOOLS 0x002F
90 #ifndef CSIDL_ADMINTOOLS
91 # define CSIDL_ADMINTOOLS 0x0030
93 #ifndef CSIDL_COMMON_MUSIC
94 # define CSIDL_COMMON_MUSIC 0x0035
96 #ifndef CSIDL_COMMON_PICTURES
97 # define CSIDL_COMMON_PICTURES 0x0036
99 #ifndef CSIDL_COMMON_VIDEO
100 # define CSIDL_COMMON_VIDEO 0x0037
102 #ifndef CSIDL_CDBURN_AREA
103 # define CSIDL_CDBURN_AREA 0x003B
105 #ifndef CSIDL_FLAG_CREATE
106 # define CSIDL_FLAG_CREATE 0x8000
109 /* Use explicit struct definition because wSuiteMask and
110 * wProductType are not defined in the VC++ 6.0 headers.
111 * WORD type has been replaced by unsigned short because
112 * WORD is already used by Perl itself.
115 DWORD dwOSVersionInfoSize;
116 DWORD dwMajorVersion;
117 DWORD dwMinorVersion;
120 CHAR szCSDVersion[128];
121 unsigned short wServicePackMajor;
122 unsigned short wServicePackMinor;
123 unsigned short wSuiteMask;
126 } g_osver = {0, 0, 0, 0, 0, "", 0, 0, 0, 0, 0};
127 BOOL g_osver_ex = TRUE;
129 #define ONE_K_BUFSIZE 1024
134 return (g_osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS);
140 return (g_osver.dwPlatformId == VER_PLATFORM_WIN32_NT);
146 return (g_osver.dwMajorVersion > 4);
149 /* Convert SV to wide character string. The return value must be
150 * freed using Safefree().
153 sv_to_wstr(pTHX_ SV *sv)
158 char *str = SvPV(sv, len);
159 UINT cp = SvUTF8(sv) ? CP_UTF8 : CP_ACP;
161 wlen = MultiByteToWideChar(cp, 0, str, len+1, NULL, 0);
162 New(0, wstr, wlen, WCHAR);
163 MultiByteToWideChar(cp, 0, str, len+1, wstr, wlen);
168 /* Convert wide character string to mortal SV. Use UTF8 encoding
169 * if the string cannot be represented in the system codepage.
172 wstr_to_sv(pTHX_ WCHAR *wstr)
174 size_t wlen = wcslen(wstr)+1;
175 BOOL use_default = FALSE;
176 int len = WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, wstr, wlen, NULL, 0, NULL, NULL);
177 SV *sv = sv_2mortal(newSV(len));
179 len = WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, wstr, wlen, SvPVX(sv), len, NULL, &use_default);
181 len = WideCharToMultiByte(CP_UTF8, 0, wstr, wlen, NULL, 0, NULL, NULL);
183 len = WideCharToMultiByte(CP_UTF8, 0, wstr, wlen, SvPVX(sv), len, NULL, NULL);
186 /* Shouldn't really ever fail since we ask for the required length first, but who knows... */
189 SvCUR_set(sv, len-1);
194 /* Retrieve a variable from the Unicode environment in a mortal SV.
196 * Recreates the Unicode environment because a bug in earlier Perl versions
197 * overwrites it with the ANSI version, which contains replacement
198 * characters for the characters not in the ANSI codepage.
201 get_unicode_env(pTHX_ WCHAR *name)
207 PFNOpenProcessToken pfnOpenProcessToken;
209 /* Get security token for the current process owner */
210 module = LoadLibrary("advapi32.dll");
214 GETPROC(OpenProcessToken);
216 if (pfnOpenProcessToken == NULL ||
217 !pfnOpenProcessToken(GetCurrentProcess(), TOKEN_QUERY | TOKEN_DUPLICATE, &token))
224 /* Create a Unicode environment block for this process */
225 module = LoadLibrary("userenv.dll");
227 PFNCreateEnvironmentBlock pfnCreateEnvironmentBlock;
228 PFNDestroyEnvironmentBlock pfnDestroyEnvironmentBlock;
230 GETPROC(CreateEnvironmentBlock);
231 GETPROC(DestroyEnvironmentBlock);
233 if (pfnCreateEnvironmentBlock && pfnDestroyEnvironmentBlock &&
234 pfnCreateEnvironmentBlock(&env, token, FALSE))
236 size_t name_len = wcslen(name);
240 size_t entry_len = wcslen(entry);
241 BOOL equal = (entry_len > name_len) && (entry[name_len] == '=');
243 for (i=0; equal && i < name_len; ++i)
244 equal = (towupper(entry[i]) == towupper(name[i]));
247 sv = wstr_to_sv(aTHX_ entry+name_len+1);
250 entry += entry_len+1;
252 pfnDestroyEnvironmentBlock(env);
260 /* Define both an ANSI and a Wide version of win32_longpath */
263 #define WIN32_FIND_DATA_T WIN32_FIND_DATAA
264 #define FN_FINDFIRSTFILE FindFirstFileA
265 #define FN_STRLEN strlen
266 #define FN_STRCPY strcpy
267 #define LONGPATH my_longpathA
268 #include "longpath.inc"
271 #define WIN32_FIND_DATA_T WIN32_FIND_DATAW
272 #define FN_FINDFIRSTFILE FindFirstFileW
273 #define FN_STRLEN wcslen
274 #define FN_STRCPY wcscpy
275 #define LONGPATH my_longpathW
276 #include "longpath.inc"
278 /* The my_ansipath() function takes a Unicode filename and converts it
279 * into the current Windows codepage. If some characters cannot be mapped,
280 * then it will convert the short name instead.
282 * The buffer to the ansi pathname must be freed with Safefree() when it
283 * it no longer needed.
285 * The argument to my_ansipath() must exist before this function is
286 * called; otherwise there is no way to determine the short path name.
288 * Ideas for future refinement:
289 * - Only convert those segments of the path that are not in the current
290 * codepage, but leave the other segments in their long form.
291 * - If the resulting name is longer than MAX_PATH, start converting
292 * additional path segments into short names until the full name
293 * is shorter than MAX_PATH. Shorten the filename part last!
296 /* This is a modified version of core Perl win32/win32.c(win32_ansipath).
297 * It uses New() etc. instead of win32_malloc().
301 my_ansipath(const WCHAR *widename)
304 BOOL use_default = FALSE;
305 size_t widelen = wcslen(widename)+1;
306 int len = WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, widename, widelen,
307 NULL, 0, NULL, NULL);
308 New(0, name, len, char);
309 WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, widename, widelen,
310 name, len, NULL, &use_default);
312 DWORD shortlen = GetShortPathNameW(widename, NULL, 0);
315 New(0, shortname, shortlen, WCHAR);
316 shortlen = GetShortPathNameW(widename, shortname, shortlen)+1;
318 len = WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, shortname, shortlen,
319 NULL, 0, NULL, NULL);
320 Renew(name, len, char);
321 WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, shortname, shortlen,
322 name, len, NULL, NULL);
329 /* Convert wide character path to ANSI path and return as mortal SV. */
331 wstr_to_ansipath(pTHX_ WCHAR *wstr)
333 char *ansi = my_ansipath(wstr);
334 SV *sv = sv_2mortal(newSVpvn(ansi, strlen(ansi)));
348 WCHAR filename[MAX_PATH+1];
349 GetCurrentDirectoryW(MAX_PATH+1, filename);
350 ptr = my_ansipath(filename);
353 char filename[MAX_PATH+1];
354 GetCurrentDirectoryA(MAX_PATH+1, filename);
355 New(0, ptr, strlen(filename)+1, char);
356 strcpy(ptr, filename);
362 free_childdir(char *d)
375 free_childenv(void *d)
379 # define PerlDir_mapA(dir) (dir)
383 XS(w32_ExpandEnvironmentStrings)
388 croak("usage: Win32::ExpandEnvironmentStrings($String);\n");
391 WCHAR value[31*1024];
392 WCHAR *source = sv_to_wstr(aTHX_ ST(0));
393 ExpandEnvironmentStringsW(source, value, countof(value)-1);
394 ST(0) = wstr_to_sv(aTHX_ value);
400 ExpandEnvironmentStringsA(SvPV_nolen(ST(0)), value, countof(value)-2);
409 PFNIsUserAnAdmin pfnIsUserAnAdmin;
410 PFNOpenThreadToken pfnOpenThreadToken;
411 PFNOpenProcessToken pfnOpenProcessToken;
412 PFNGetTokenInformation pfnGetTokenInformation;
413 PFNAllocateAndInitializeSid pfnAllocateAndInitializeSid;
414 PFNEqualSid pfnEqualSid;
415 PFNFreeSid pfnFreeSid;
418 TOKEN_GROUPS *lpTokInfo;
419 SID_IDENTIFIER_AUTHORITY NtAuth = SECURITY_NT_AUTHORITY;
425 croak("usage: Win32::IsAdminUser()");
427 /* There is no concept of "Administrator" user accounts on Win9x systems,
428 so just return true. */
432 /* Use IsUserAnAdmin() when available. On Vista this will only return TRUE
433 * if the process is running with elevated privileges and not just when the
434 * process owner is a member of the "Administrators" group.
436 module = LoadLibrary("shell32.dll");
438 GETPROC(IsUserAnAdmin);
439 if (pfnIsUserAnAdmin) {
441 ST(0) = sv_2mortal(newSViv(pfnIsUserAnAdmin() ? 1 : 0));
448 module = LoadLibrary("advapi32.dll");
450 warn("Cannot load advapi32.dll library");
454 GETPROC(OpenThreadToken);
455 GETPROC(OpenProcessToken);
456 GETPROC(GetTokenInformation);
457 GETPROC(AllocateAndInitializeSid);
461 if (!(pfnOpenThreadToken && pfnOpenProcessToken &&
462 pfnGetTokenInformation && pfnAllocateAndInitializeSid &&
463 pfnEqualSid && pfnFreeSid))
465 warn("Cannot load functions from advapi32.dll library");
470 if (!pfnOpenThreadToken(GetCurrentThread(), TOKEN_QUERY, FALSE, &hTok)) {
471 if (!pfnOpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hTok)) {
472 warn("Cannot open thread token or process token");
478 pfnGetTokenInformation(hTok, TokenGroups, NULL, 0, &dwTokInfoLen);
479 if (!New(1, lpTokInfo, dwTokInfoLen, TOKEN_GROUPS)) {
480 warn("Cannot allocate token information structure");
486 if (!pfnGetTokenInformation(hTok, TokenGroups, lpTokInfo, dwTokInfoLen,
489 warn("Cannot get token information");
496 if (!pfnAllocateAndInitializeSid(&NtAuth, 2, SECURITY_BUILTIN_DOMAIN_RID,
497 DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &pAdminSid))
499 warn("Cannot allocate administrators' SID");
507 for (i = 0; i < lpTokInfo->GroupCount; ++i) {
508 if (pfnEqualSid(lpTokInfo->Groups[i].Sid, pAdminSid)) {
514 pfnFreeSid(pAdminSid);
520 ST(0) = sv_2mortal(newSViv(iRetVal));
524 XS(w32_LookupAccountName)
535 croak("usage: Win32::LookupAccountName($system, $account, $domain, "
536 "$sid, $sidtype);\n");
538 SIDLen = sizeof(SID);
539 DomLen = sizeof(Domain);
541 bResult = LookupAccountNameA(SvPV_nolen(ST(0)), /* System */
542 SvPV_nolen(ST(1)), /* Account name */
543 &SID, /* SID structure */
544 &SIDLen, /* Size of SID buffer */
545 Domain, /* Domain buffer */
546 &DomLen, /* Domain buffer size */
547 &snu); /* SID name type */
549 sv_setpv(ST(2), Domain);
550 sv_setpvn(ST(3), SID, SIDLen);
551 sv_setiv(ST(4), snu);
558 XS(w32_LookupAccountSID)
563 DWORD AcctLen = sizeof(Account);
565 DWORD DomLen = sizeof(Domain);
570 croak("usage: Win32::LookupAccountSID($system, $sid, $account, $domain, $sidtype);\n");
572 sid = SvPV_nolen(ST(1));
573 if (IsValidSid(sid)) {
574 bResult = LookupAccountSidA(SvPV_nolen(ST(0)), /* System */
575 sid, /* SID structure */
576 Account, /* Account name buffer */
577 &AcctLen, /* name buffer length */
578 Domain, /* Domain buffer */
579 &DomLen, /* Domain buffer length */
580 &snu); /* SID name type */
582 sv_setpv(ST(2), Account);
583 sv_setpv(ST(3), Domain);
584 sv_setiv(ST(4), (IV)snu);
591 XS(w32_InitiateSystemShutdown)
594 HANDLE hToken; /* handle to process token */
595 TOKEN_PRIVILEGES tkp; /* pointer to token structure */
597 char *machineName, *message;
600 croak("usage: Win32::InitiateSystemShutdown($machineName, $message, "
601 "$timeOut, $forceClose, $reboot);\n");
603 machineName = SvPV_nolen(ST(0));
605 if (OpenProcessToken(GetCurrentProcess(),
606 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
609 LookupPrivilegeValueA(machineName,
611 &tkp.Privileges[0].Luid);
613 tkp.PrivilegeCount = 1; /* only setting one */
614 tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
616 /* Get shutdown privilege for this process. */
617 AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,
618 (PTOKEN_PRIVILEGES)NULL, 0);
621 message = SvPV_nolen(ST(1));
622 bRet = InitiateSystemShutdownA(machineName, message,
623 SvIV(ST(2)), SvIV(ST(3)), SvIV(ST(4)));
625 /* Disable shutdown privilege. */
626 tkp.Privileges[0].Attributes = 0;
627 AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,
628 (PTOKEN_PRIVILEGES)NULL, 0);
633 XS(w32_AbortSystemShutdown)
636 HANDLE hToken; /* handle to process token */
637 TOKEN_PRIVILEGES tkp; /* pointer to token structure */
642 croak("usage: Win32::AbortSystemShutdown($machineName);\n");
644 machineName = SvPV_nolen(ST(0));
646 if (OpenProcessToken(GetCurrentProcess(),
647 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
650 LookupPrivilegeValueA(machineName,
652 &tkp.Privileges[0].Luid);
654 tkp.PrivilegeCount = 1; /* only setting one */
655 tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
657 /* Get shutdown privilege for this process. */
658 AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,
659 (PTOKEN_PRIVILEGES)NULL, 0);
662 bRet = AbortSystemShutdownA(machineName);
664 /* Disable shutdown privilege. */
665 tkp.Privileges[0].Attributes = 0;
666 AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,
667 (PTOKEN_PRIVILEGES)NULL, 0);
676 DWORD flags = MB_ICONEXCLAMATION;
679 if (items < 1 || items > 3)
680 croak("usage: Win32::MsgBox($message [, $flags [, $title]]);\n");
687 WCHAR *msg = sv_to_wstr(aTHX_ ST(0));
689 title = sv_to_wstr(aTHX_ ST(2));
690 result = MessageBoxW(GetActiveWindow(), msg, title ? title : L"Perl", flags);
696 char *title = "Perl";
697 char *msg = SvPV_nolen(ST(0));
699 title = SvPV_nolen(ST(2));
700 result = MessageBoxA(GetActiveWindow(), msg, title, flags);
711 croak("usage: Win32::LoadLibrary($libname)\n");
712 hHandle = LoadLibraryA(SvPV_nolen(ST(0)));
713 XSRETURN_IV((long)hHandle);
721 croak("usage: Win32::FreeLibrary($handle)\n");
722 if (FreeLibrary(INT2PTR(HINSTANCE, SvIV(ST(0))))) {
728 XS(w32_GetProcAddress)
733 croak("usage: Win32::GetProcAddress($hinstance, $procname)\n");
734 XSRETURN_IV(PTR2IV(GetProcAddress(INT2PTR(HINSTANCE, SvIV(ST(0))), SvPV_nolen(ST(1)))));
737 XS(w32_RegisterServer)
744 croak("usage: Win32::RegisterServer($libname)\n");
746 module = LoadLibraryA(SvPV_nolen(ST(0)));
748 PFNDllRegisterServer pfnDllRegisterServer;
749 GETPROC(DllRegisterServer);
750 if (pfnDllRegisterServer && pfnDllRegisterServer() == 0)
754 ST(0) = boolSV(result);
758 XS(w32_UnregisterServer)
765 croak("usage: Win32::UnregisterServer($libname)\n");
767 module = LoadLibraryA(SvPV_nolen(ST(0)));
769 PFNDllUnregisterServer pfnDllUnregisterServer;
770 GETPROC(DllUnregisterServer);
771 if (pfnDllUnregisterServer && pfnDllUnregisterServer() == 0)
775 ST(0) = boolSV(result);
779 /* XXX rather bogus */
783 XSRETURN_PV(getenv("PROCESSOR_ARCHITECTURE"));
791 Zero(&sysinfo,1,SYSTEM_INFO);
792 GetSystemInfo(&sysinfo);
793 /* XXX docs say dwProcessorType is deprecated on NT */
794 XSRETURN_IV(sysinfo.dwProcessorType);
801 char szGUID[50] = {'\0'};
802 HRESULT hr = CoCreateGuid(&guid);
805 LPOLESTR pStr = NULL;
806 if (SUCCEEDED(StringFromCLSID(&guid, &pStr))) {
807 WideCharToMultiByte(CP_ACP, 0, pStr, wcslen(pStr), szGUID,
808 sizeof(szGUID), NULL, NULL);
816 XS(w32_GetFolderPath)
819 char path[MAX_PATH+1];
820 WCHAR wpath[MAX_PATH+1];
825 if (items != 1 && items != 2)
826 croak("usage: Win32::GetFolderPath($csidl [, $create])\n");
828 folder = SvIV(ST(0));
830 create = SvTRUE(ST(1)) ? CSIDL_FLAG_CREATE : 0;
832 module = LoadLibrary("shfolder.dll");
834 PFNSHGetFolderPathA pfna;
836 PFNSHGetFolderPathW pfnw;
837 pfnw = (PFNSHGetFolderPathW)GetProcAddress(module, "SHGetFolderPathW");
838 if (pfnw && SUCCEEDED(pfnw(NULL, folder|create, NULL, 0, wpath))) {
840 ST(0) = wstr_to_ansipath(aTHX_ wpath);
844 pfna = (PFNSHGetFolderPathA)GetProcAddress(module, "SHGetFolderPathA");
845 if (pfna && SUCCEEDED(pfna(NULL, folder|create, NULL, 0, path))) {
852 module = LoadLibrary("shell32.dll");
854 PFNSHGetSpecialFolderPathA pfna;
856 PFNSHGetSpecialFolderPathW pfnw;
857 pfnw = (PFNSHGetSpecialFolderPathW)GetProcAddress(module, "SHGetSpecialFolderPathW");
858 if (pfnw && pfnw(NULL, wpath, folder, !!create)) {
860 ST(0) = wstr_to_ansipath(aTHX_ wpath);
864 pfna = (PFNSHGetSpecialFolderPathA)GetProcAddress(module, "SHGetSpecialFolderPathA");
865 if (pfna && pfna(NULL, path, folder, !!create)) {
872 /* SHGetFolderPathW() and SHGetSpecialFolderPathW() may fail on older
873 * Perl versions that have replaced the Unicode environment with an
874 * ANSI version. Let's go spelunking in the registry now...
879 HKEY root = HKEY_CURRENT_USER;
883 case CSIDL_ADMINTOOLS: name = L"Administrative Tools"; break;
884 case CSIDL_APPDATA: name = L"AppData"; break;
885 case CSIDL_CDBURN_AREA: name = L"CD Burning"; break;
886 case CSIDL_COOKIES: name = L"Cookies"; break;
888 case CSIDL_DESKTOPDIRECTORY: name = L"Desktop"; break;
889 case CSIDL_FAVORITES: name = L"Favorites"; break;
890 case CSIDL_FONTS: name = L"Fonts"; break;
891 case CSIDL_HISTORY: name = L"History"; break;
892 case CSIDL_INTERNET_CACHE: name = L"Cache"; break;
893 case CSIDL_LOCAL_APPDATA: name = L"Local AppData"; break;
894 case CSIDL_MYMUSIC: name = L"My Music"; break;
895 case CSIDL_MYPICTURES: name = L"My Pictures"; break;
896 case CSIDL_MYVIDEO: name = L"My Video"; break;
897 case CSIDL_NETHOOD: name = L"NetHood"; break;
898 case CSIDL_PERSONAL: name = L"Personal"; break;
899 case CSIDL_PRINTHOOD: name = L"PrintHood"; break;
900 case CSIDL_PROGRAMS: name = L"Programs"; break;
901 case CSIDL_RECENT: name = L"Recent"; break;
902 case CSIDL_SENDTO: name = L"SendTo"; break;
903 case CSIDL_STARTMENU: name = L"Start Menu"; break;
904 case CSIDL_STARTUP: name = L"Startup"; break;
905 case CSIDL_TEMPLATES: name = L"Templates"; break;
906 /* XXX L"Local Settings" */
910 root = HKEY_LOCAL_MACHINE;
912 case CSIDL_COMMON_ADMINTOOLS: name = L"Common Administrative Tools"; break;
913 case CSIDL_COMMON_APPDATA: name = L"Common AppData"; break;
914 case CSIDL_COMMON_DESKTOPDIRECTORY: name = L"Common Desktop"; break;
915 case CSIDL_COMMON_DOCUMENTS: name = L"Common Documents"; break;
916 case CSIDL_COMMON_FAVORITES: name = L"Common Favorites"; break;
917 case CSIDL_COMMON_PROGRAMS: name = L"Common Programs"; break;
918 case CSIDL_COMMON_STARTMENU: name = L"Common Start Menu"; break;
919 case CSIDL_COMMON_STARTUP: name = L"Common Startup"; break;
920 case CSIDL_COMMON_TEMPLATES: name = L"Common Templates"; break;
921 case CSIDL_COMMON_MUSIC: name = L"CommonMusic"; break;
922 case CSIDL_COMMON_PICTURES: name = L"CommonPictures"; break;
923 case CSIDL_COMMON_VIDEO: name = L"CommonVideo"; break;
927 * case CSIDL_SYSTEM # GetSystemDirectory()
928 * case CSIDL_RESOURCES # %windir%\Resources\, For theme and other windows resources.
929 * case CSIDL_RESOURCES_LOCALIZED # %windir%\Resources\<LangID>, for theme and other windows specific resources.
932 #define SHELL_FOLDERS "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders"
934 if (name && RegOpenKeyEx(root, SHELL_FOLDERS, 0, KEY_QUERY_VALUE, &hkey) == ERROR_SUCCESS) {
935 WCHAR data[MAX_PATH+1];
936 DWORD cb = sizeof(data)-sizeof(WCHAR);
937 DWORD type = REG_NONE;
938 long rc = RegQueryValueExW(hkey, name, NULL, &type, (BYTE*)&data, &cb);
940 if (rc == ERROR_SUCCESS && type == REG_SZ && cb > sizeof(WCHAR) && data[0]) {
941 /* Make sure the string is properly terminated */
942 data[cb/sizeof(WCHAR)] = '\0';
943 ST(0) = wstr_to_ansipath(aTHX_ data);
950 /* Unders some circumstances the registry entries seem to have a null string
951 * as their value even when the directory already exists. The environment
952 * variables do get set though, so try re-create a Unicode environment and
953 * check if they are there.
957 case CSIDL_APPDATA: sv = get_unicode_env(aTHX_ L"APPDATA"); break;
958 case CSIDL_PROFILE: sv = get_unicode_env(aTHX_ L"USERPROFILE"); break;
959 case CSIDL_PROGRAM_FILES: sv = get_unicode_env(aTHX_ L"ProgramFiles"); break;
960 case CSIDL_PROGRAM_FILES_COMMON: sv = get_unicode_env(aTHX_ L"CommonProgramFiles"); break;
961 case CSIDL_WINDOWS: sv = get_unicode_env(aTHX_ L"SystemRoot"); break;
972 XS(w32_GetFileVersion)
981 croak("usage: Win32::GetFileVersion($filename)\n");
983 filename = SvPV_nolen(ST(0));
984 size = GetFileVersionInfoSize(filename, &handle);
988 New(0, data, size, char);
992 if (GetFileVersionInfo(filename, handle, size, data)) {
993 VS_FIXEDFILEINFO *info;
995 if (VerQueryValue(data, "\\", (void**)&info, &len)) {
996 int dwValueMS1 = (info->dwFileVersionMS>>16);
997 int dwValueMS2 = (info->dwFileVersionMS&0xffff);
998 int dwValueLS1 = (info->dwFileVersionLS>>16);
999 int dwValueLS2 = (info->dwFileVersionLS&0xffff);
1001 if (GIMME_V == G_ARRAY) {
1003 XST_mIV(0, dwValueMS1);
1004 XST_mIV(1, dwValueMS2);
1005 XST_mIV(2, dwValueLS1);
1006 XST_mIV(3, dwValueLS2);
1011 sprintf(version, "%d.%d.%d.%d", dwValueMS1, dwValueMS2, dwValueLS1, dwValueLS2);
1012 XST_mPV(0, version);
1024 XS(w32_SetChildShowWindow)
1026 /* This function doesn't do anything useful for cygwin. In the
1027 * MSWin32 case it modifies w32_showwindow, which is used by
1028 * win32_spawnvp(). Since w32_showwindow is an internal variable
1029 * inside the thread_intern structure, the MSWin32 implementation
1030 * lives in win32/win32.c in the core Perl distribution.
1040 /* Make the host for current directory */
1041 char* ptr = PerlEnv_get_childdir();
1044 * then it worked, set PV valid,
1045 * else return 'undef'
1048 SV *sv = sv_newmortal();
1050 PerlEnv_free_childdir(ptr);
1052 #ifndef INCOMPLETE_TAINTS
1067 Perl_croak(aTHX_ "usage: Win32::SetCwd($cwd)");
1069 if (IsWin2000() && SvUTF8(ST(0))) {
1070 WCHAR *wide = sv_to_wstr(aTHX_ ST(0));
1071 char *ansi = my_ansipath(wide);
1072 int rc = PerlDir_chdir(ansi);
1079 if (!PerlDir_chdir(SvPV_nolen(ST(0))))
1086 XS(w32_GetNextAvailDrive)
1090 char root[] = "_:\\";
1095 if (GetDriveType(root) == 1) {
1103 XS(w32_GetLastError)
1107 XSRETURN_IV(GetLastError());
1110 XS(w32_SetLastError)
1114 Perl_croak(aTHX_ "usage: Win32::SetLastError($error)");
1115 SetLastError(SvIV(ST(0)));
1125 DWORD size = countof(name);
1126 if (GetUserNameW(name, &size)) {
1127 ST(0) = wstr_to_sv(aTHX_ name);
1133 DWORD size = countof(name);
1134 if (GetUserNameA(name, &size)) {
1135 /* size includes NULL */
1136 ST(0) = sv_2mortal(newSVpvn(name, size-1));
1146 char name[MAX_COMPUTERNAME_LENGTH+1];
1147 DWORD size = sizeof(name);
1149 if (GetComputerName(name,&size)) {
1150 /* size does NOT include NULL :-( */
1151 ST(0) = sv_2mortal(newSVpvn(name,size));
1161 HMODULE module = LoadLibrary("netapi32.dll");
1162 PFNNetApiBufferFree pfnNetApiBufferFree;
1163 PFNNetWkstaGetInfo pfnNetWkstaGetInfo;
1166 GETPROC(NetApiBufferFree);
1167 GETPROC(NetWkstaGetInfo);
1170 if (module && pfnNetWkstaGetInfo && pfnNetApiBufferFree) {
1171 /* this way is more reliable, in case user has a local account. */
1173 DWORD dnamelen = sizeof(dname);
1175 DWORD wki100_platform_id;
1176 LPWSTR wki100_computername;
1177 LPWSTR wki100_langroup;
1178 DWORD wki100_ver_major;
1179 DWORD wki100_ver_minor;
1182 retval = pfnNetWkstaGetInfo(NULL, 100, &pwi);
1183 /* NERR_Success *is* 0*/
1185 if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
1186 WideCharToMultiByte(CP_ACP, 0, pwi->wki100_langroup,
1187 -1, (LPSTR)dname, dnamelen, NULL, NULL);
1190 WideCharToMultiByte(CP_ACP, 0, pwi->wki100_computername,
1191 -1, (LPSTR)dname, dnamelen, NULL, NULL);
1193 pfnNetApiBufferFree(pwi);
1194 FreeLibrary(module);
1197 FreeLibrary(module);
1198 SetLastError(retval);
1201 /* Win95 doesn't have NetWksta*(), so do it the old way */
1203 DWORD size = sizeof(name);
1205 FreeLibrary(module);
1206 if (GetUserName(name,&size)) {
1207 char sid[ONE_K_BUFSIZE];
1208 DWORD sidlen = sizeof(sid);
1210 DWORD dnamelen = sizeof(dname);
1212 if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
1213 dname, &dnamelen, &snu)) {
1214 XSRETURN_PV(dname); /* all that for this */
1225 DWORD flags, filecomplen;
1226 if (GetVolumeInformation(NULL, NULL, 0, NULL, &filecomplen,
1227 &flags, fsname, sizeof(fsname))) {
1228 if (GIMME_V == G_ARRAY) {
1229 XPUSHs(sv_2mortal(newSVpvn(fsname,strlen(fsname))));
1230 XPUSHs(sv_2mortal(newSViv(flags)));
1231 XPUSHs(sv_2mortal(newSViv(filecomplen)));
1236 XSRETURN_PV(fsname);
1241 XS(w32_GetOSVersion)
1245 if (GIMME_V == G_SCALAR) {
1246 XSRETURN_IV(g_osver.dwPlatformId);
1248 XPUSHs(newSVpvn(g_osver.szCSDVersion, strlen(g_osver.szCSDVersion)));
1250 XPUSHs(newSViv(g_osver.dwMajorVersion));
1251 XPUSHs(newSViv(g_osver.dwMinorVersion));
1252 XPUSHs(newSViv(g_osver.dwBuildNumber));
1253 XPUSHs(newSViv(g_osver.dwPlatformId));
1255 XPUSHs(newSViv(g_osver.wServicePackMajor));
1256 XPUSHs(newSViv(g_osver.wServicePackMinor));
1257 XPUSHs(newSViv(g_osver.wSuiteMask));
1258 XPUSHs(newSViv(g_osver.wProductType));
1267 XSRETURN_IV(IsWinNT());
1274 XSRETURN_IV(IsWin95());
1277 XS(w32_FormatMessage)
1281 char msgbuf[ONE_K_BUFSIZE];
1284 Perl_croak(aTHX_ "usage: Win32::FormatMessage($errno)");
1286 if (FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM,
1287 &source, SvIV(ST(0)), 0,
1288 msgbuf, sizeof(msgbuf)-1, NULL))
1290 XSRETURN_PV(msgbuf);
1302 PROCESS_INFORMATION stProcInfo;
1303 STARTUPINFO stStartInfo;
1304 BOOL bSuccess = FALSE;
1307 Perl_croak(aTHX_ "usage: Win32::Spawn($cmdName, $args, $PID)");
1309 cmd = SvPV_nolen(ST(0));
1310 args = SvPV_nolen(ST(1));
1312 env = PerlEnv_get_childenv();
1313 dir = PerlEnv_get_childdir();
1315 memset(&stStartInfo, 0, sizeof(stStartInfo)); /* Clear the block */
1316 stStartInfo.cb = sizeof(stStartInfo); /* Set the structure size */
1317 stStartInfo.dwFlags = STARTF_USESHOWWINDOW; /* Enable wShowWindow control */
1318 stStartInfo.wShowWindow = SW_SHOWMINNOACTIVE; /* Start min (normal) */
1321 cmd, /* Image path */
1322 args, /* Arguments for command line */
1323 NULL, /* Default process security */
1324 NULL, /* Default thread security */
1325 FALSE, /* Must be TRUE to use std handles */
1326 NORMAL_PRIORITY_CLASS, /* No special scheduling */
1327 env, /* Inherit our environment block */
1328 dir, /* Inherit our currrent directory */
1329 &stStartInfo, /* -> Startup info */
1330 &stProcInfo)) /* <- Process info (if OK) */
1332 int pid = (int)stProcInfo.dwProcessId;
1333 if (IsWin95() && pid < 0)
1335 sv_setiv(ST(2), pid);
1336 CloseHandle(stProcInfo.hThread);/* library source code does this. */
1339 PerlEnv_free_childenv(env);
1340 PerlEnv_free_childdir(dir);
1341 XSRETURN_IV(bSuccess);
1344 XS(w32_GetTickCount)
1347 DWORD msec = GetTickCount();
1354 XS(w32_GetShortPathName)
1361 Perl_croak(aTHX_ "usage: Win32::GetShortPathName($longPathName)");
1364 WCHAR wshort[MAX_PATH+1];
1365 WCHAR *wlong = sv_to_wstr(aTHX_ ST(0));
1366 len = GetShortPathNameW(wlong, wshort, countof(wshort));
1368 if (len && len < sizeof(wshort)) {
1369 ST(0) = wstr_to_sv(aTHX_ wshort);
1375 shortpath = sv_mortalcopy(ST(0));
1376 SvUPGRADE(shortpath, SVt_PV);
1377 if (!SvPVX(shortpath) || !SvLEN(shortpath))
1380 /* src == target is allowed */
1382 len = GetShortPathName(SvPVX(shortpath),
1385 } while (len >= SvLEN(shortpath) && sv_grow(shortpath,len+1));
1387 SvCUR_set(shortpath,len);
1388 *SvEND(shortpath) = '\0';
1395 XS(w32_GetFullPathName)
1401 /* The code below relies on the fact that PerlDir_mapX() returns an
1402 * absolute path, which is only true under PERL_IMPLICIT_SYS when
1403 * we use the virtualization code from win32/vdir.h.
1404 * Without it PerlDir_mapX() is a no-op and we need to use the same
1405 * code as we use for Cygwin.
1407 #if __CYGWIN__ || !defined(PERL_IMPLICIT_SYS)
1408 char buffer[2*MAX_PATH];
1412 Perl_croak(aTHX_ "usage: Win32::GetFullPathName($filename)");
1414 #if __CYGWIN__ || !defined(PERL_IMPLICIT_SYS)
1416 WCHAR *filename = sv_to_wstr(aTHX_ ST(0));
1417 WCHAR full[2*MAX_PATH];
1418 DWORD len = GetFullPathNameW(filename, countof(full), full, NULL);
1420 if (len == 0 || len >= countof(full))
1422 ansi = fullname = my_ansipath(full);
1425 DWORD len = GetFullPathNameA(SvPV_nolen(ST(0)), countof(buffer), buffer, NULL);
1426 if (len == 0 || len >= countof(buffer))
1431 /* Don't use my_ansipath() unless the $filename argument is in Unicode.
1432 * If the relative path doesn't exist, GetShortPathName() will fail and
1433 * my_ansipath() will use the long name with replacement characters.
1434 * In that case we will be better off using PerlDir_mapA(), which
1435 * already uses the ANSI name of the current directory.
1437 * XXX The one missing case is where we could downgrade $filename
1438 * XXX from UTF8 into the current codepage.
1440 if (IsWin2000() && SvUTF8(ST(0))) {
1441 WCHAR *filename = sv_to_wstr(aTHX_ ST(0));
1442 WCHAR *mappedname = PerlDir_mapW(filename);
1444 ansi = fullname = my_ansipath(mappedname);
1447 fullname = PerlDir_mapA(SvPV_nolen(ST(0)));
1449 # if PERL_VERSION < 8
1451 /* PerlDir_mapX() in Perl 5.6 used to return forward slashes */
1452 char *str = fullname;
1462 /* GetFullPathName() on Windows NT drops trailing backslash */
1463 if (g_osver.dwMajorVersion == 4 && *fullname) {
1465 char *pv = SvPV(ST(0), len);
1466 char *lastchar = fullname + strlen(fullname) - 1;
1467 /* If ST(0) ends with a slash, but fullname doesn't ... */
1468 if (len && (pv[len-1] == '/' || pv[len-1] == '\\') && *lastchar != '\\') {
1469 /* fullname is the MAX_PATH+1 sized buffer returned from PerlDir_mapA()
1470 * or the 2*MAX_PATH sized local buffer in the __CYGWIN__ case.
1472 strcpy(lastchar+1, "\\");
1476 if (GIMME_V == G_ARRAY) {
1477 char *filepart = strrchr(fullname, '\\');
1481 XST_mPV(1, ++filepart);
1489 XST_mPV(0, fullname);
1496 XS(w32_GetLongPathName)
1501 Perl_croak(aTHX_ "usage: Win32::GetLongPathName($pathname)");
1504 WCHAR *wstr = sv_to_wstr(aTHX_ ST(0));
1505 WCHAR wide_path[MAX_PATH+1];
1508 wcscpy(wide_path, wstr);
1510 long_path = my_longpathW(wide_path);
1512 ST(0) = wstr_to_sv(aTHX_ long_path);
1518 char tmpbuf[MAX_PATH+1];
1523 pathstr = SvPV(path,len);
1524 strcpy(tmpbuf, pathstr);
1525 pathstr = my_longpathA(tmpbuf);
1527 ST(0) = sv_2mortal(newSVpvn(pathstr, strlen(pathstr)));
1534 XS(w32_GetANSIPathName)
1540 Perl_croak(aTHX_ "usage: Win32::GetANSIPathName($pathname)");
1542 wide_path = sv_to_wstr(aTHX_ ST(0));
1543 ST(0) = wstr_to_ansipath(aTHX_ wide_path);
1544 Safefree(wide_path);
1552 Perl_croak(aTHX_ "usage: Win32::Sleep($milliseconds)");
1561 char szSourceFile[MAX_PATH+1];
1564 Perl_croak(aTHX_ "usage: Win32::CopyFile($from, $to, $overwrite)");
1565 strcpy(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(0))));
1566 bResult = CopyFileA(szSourceFile, PerlDir_mapA(SvPV_nolen(ST(1))), !SvTRUE(ST(2)));
1572 XS(w32_OutputDebugString)
1576 Perl_croak(aTHX_ "usage: Win32::OutputDebugString($string)");
1578 if (SvUTF8(ST(0))) {
1579 WCHAR *str = sv_to_wstr(aTHX_ ST(0));
1580 OutputDebugStringW(str);
1584 OutputDebugStringA(SvPV_nolen(ST(0)));
1589 XS(w32_GetCurrentThreadId)
1593 XSRETURN_IV(GetCurrentThreadId());
1596 XS(w32_CreateDirectory)
1602 Perl_croak(aTHX_ "usage: Win32::CreateDirectory($dir)");
1604 if (IsWin2000() && SvUTF8(ST(0))) {
1605 WCHAR *dir = sv_to_wstr(aTHX_ ST(0));
1606 result = CreateDirectoryW(dir, NULL);
1610 result = CreateDirectoryA(SvPV_nolen(ST(0)), NULL);
1613 ST(0) = boolSV(result);
1623 Perl_croak(aTHX_ "usage: Win32::CreateFile($file)");
1625 if (IsWin2000() && SvUTF8(ST(0))) {
1626 WCHAR *file = sv_to_wstr(aTHX_ ST(0));
1627 handle = CreateFileW(file, GENERIC_WRITE, FILE_SHARE_WRITE,
1628 NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);
1632 handle = CreateFileA(SvPV_nolen(ST(0)), GENERIC_WRITE, FILE_SHARE_WRITE,
1633 NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);
1636 if (handle != INVALID_HANDLE_VALUE)
1637 CloseHandle(handle);
1639 ST(0) = boolSV(handle != INVALID_HANDLE_VALUE);
1643 MODULE = Win32 PACKAGE = Win32
1649 char *file = __FILE__;
1651 if (g_osver.dwOSVersionInfoSize == 0) {
1652 g_osver.dwOSVersionInfoSize = sizeof(g_osver);
1653 if (!GetVersionExA((OSVERSIONINFOA*)&g_osver)) {
1655 g_osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
1656 GetVersionExA((OSVERSIONINFOA*)&g_osver);
1660 newXS("Win32::LookupAccountName", w32_LookupAccountName, file);
1661 newXS("Win32::LookupAccountSID", w32_LookupAccountSID, file);
1662 newXS("Win32::InitiateSystemShutdown", w32_InitiateSystemShutdown, file);
1663 newXS("Win32::AbortSystemShutdown", w32_AbortSystemShutdown, file);
1664 newXS("Win32::ExpandEnvironmentStrings", w32_ExpandEnvironmentStrings, file);
1665 newXS("Win32::MsgBox", w32_MsgBox, file);
1666 newXS("Win32::LoadLibrary", w32_LoadLibrary, file);
1667 newXS("Win32::FreeLibrary", w32_FreeLibrary, file);
1668 newXS("Win32::GetProcAddress", w32_GetProcAddress, file);
1669 newXS("Win32::RegisterServer", w32_RegisterServer, file);
1670 newXS("Win32::UnregisterServer", w32_UnregisterServer, file);
1671 newXS("Win32::GetArchName", w32_GetArchName, file);
1672 newXS("Win32::GetChipName", w32_GetChipName, file);
1673 newXS("Win32::GuidGen", w32_GuidGen, file);
1674 newXS("Win32::GetFolderPath", w32_GetFolderPath, file);
1675 newXS("Win32::IsAdminUser", w32_IsAdminUser, file);
1676 newXS("Win32::GetFileVersion", w32_GetFileVersion, file);
1678 newXS("Win32::GetCwd", w32_GetCwd, file);
1679 newXS("Win32::SetCwd", w32_SetCwd, file);
1680 newXS("Win32::GetNextAvailDrive", w32_GetNextAvailDrive, file);
1681 newXS("Win32::GetLastError", w32_GetLastError, file);
1682 newXS("Win32::SetLastError", w32_SetLastError, file);
1683 newXS("Win32::LoginName", w32_LoginName, file);
1684 newXS("Win32::NodeName", w32_NodeName, file);
1685 newXS("Win32::DomainName", w32_DomainName, file);
1686 newXS("Win32::FsType", w32_FsType, file);
1687 newXS("Win32::GetOSVersion", w32_GetOSVersion, file);
1688 newXS("Win32::IsWinNT", w32_IsWinNT, file);
1689 newXS("Win32::IsWin95", w32_IsWin95, file);
1690 newXS("Win32::FormatMessage", w32_FormatMessage, file);
1691 newXS("Win32::Spawn", w32_Spawn, file);
1692 newXS("Win32::GetTickCount", w32_GetTickCount, file);
1693 newXS("Win32::GetShortPathName", w32_GetShortPathName, file);
1694 newXS("Win32::GetFullPathName", w32_GetFullPathName, file);
1695 newXS("Win32::GetLongPathName", w32_GetLongPathName, file);
1696 newXS("Win32::GetANSIPathName", w32_GetANSIPathName, file);
1697 newXS("Win32::CopyFile", w32_CopyFile, file);
1698 newXS("Win32::Sleep", w32_Sleep, file);
1699 newXS("Win32::OutputDebugString", w32_OutputDebugString, file);
1700 newXS("Win32::GetCurrentThreadId", w32_GetCurrentThreadId, file);
1701 newXS("Win32::CreateDirectory", w32_CreateDirectory, file);
1702 newXS("Win32::CreateFile", w32_CreateFile, file);
1704 newXS("Win32::SetChildShowWindow", w32_SetChildShowWindow, file);