1 /* Utility and Unix shadow routines for GNU Emacs on the Microsoft Windows API.
2 Copyright (C) 1994-1995, 2000-2012 Free Software Foundation, Inc.
4 This file is part of GNU Emacs.
6 GNU Emacs is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 GNU Emacs is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 Geoff Voelker (voelker@cs.washington.edu) 7-29-94
22 #include <stddef.h> /* for offsetof */
25 #include <float.h> /* for DBL_EPSILON */
33 #include <sys/utime.h>
37 /* must include CRT headers *before* config.h */
40 #include <mbstring.h> /* for _mbspbrk */
73 #define _ANONYMOUS_UNION
74 #define _ANONYMOUS_STRUCT
77 /* Some versions of compiler define MEMORYSTATUSEX, some don't, so we
78 use a different name to avoid compilation problems. */
79 typedef struct _MEMORY_STATUS_EX
{
82 DWORDLONG ullTotalPhys
;
83 DWORDLONG ullAvailPhys
;
84 DWORDLONG ullTotalPageFile
;
85 DWORDLONG ullAvailPageFile
;
86 DWORDLONG ullTotalVirtual
;
87 DWORDLONG ullAvailVirtual
;
88 DWORDLONG ullAvailExtendedVirtual
;
89 } MEMORY_STATUS_EX
,*LPMEMORY_STATUS_EX
;
99 #if !defined (__MINGW32__) || __W32API_MAJOR_VERSION < 3 || (__W32API_MAJOR_VERSION == 3 && __W32API_MINOR_VERSION < 15)
100 /* This either is not in psapi.h or guarded by higher value of
101 _WIN32_WINNT than what we use. w32api supplied with MinGW 3.15
102 defines it in psapi.h */
103 typedef struct _PROCESS_MEMORY_COUNTERS_EX
{
105 DWORD PageFaultCount
;
106 SIZE_T PeakWorkingSetSize
;
107 SIZE_T WorkingSetSize
;
108 SIZE_T QuotaPeakPagedPoolUsage
;
109 SIZE_T QuotaPagedPoolUsage
;
110 SIZE_T QuotaPeakNonPagedPoolUsage
;
111 SIZE_T QuotaNonPagedPoolUsage
;
112 SIZE_T PagefileUsage
;
113 SIZE_T PeakPagefileUsage
;
115 } PROCESS_MEMORY_COUNTERS_EX
,*PPROCESS_MEMORY_COUNTERS_EX
;
118 #include <winioctl.h>
124 /* This is not in MinGW's sddl.h (but they are in MSVC headers), so we
125 define them by hand if not already defined. */
126 #ifndef SDDL_REVISION_1
127 #define SDDL_REVISION_1 1
128 #endif /* SDDL_REVISION_1 */
131 /* MSVC doesn't provide the definition of REPARSE_DATA_BUFFER and the
132 associated macros, except on ntifs.h, which cannot be included
133 because it triggers conflicts with other Windows API headers. So
134 we define it here by hand. */
136 typedef struct _REPARSE_DATA_BUFFER
{
138 USHORT ReparseDataLength
;
142 USHORT SubstituteNameOffset
;
143 USHORT SubstituteNameLength
;
144 USHORT PrintNameOffset
;
145 USHORT PrintNameLength
;
148 } SymbolicLinkReparseBuffer
;
150 USHORT SubstituteNameOffset
;
151 USHORT SubstituteNameLength
;
152 USHORT PrintNameOffset
;
153 USHORT PrintNameLength
;
155 } MountPointReparseBuffer
;
158 } GenericReparseBuffer
;
160 } REPARSE_DATA_BUFFER
, *PREPARSE_DATA_BUFFER
;
162 #ifndef FILE_DEVICE_FILE_SYSTEM
163 #define FILE_DEVICE_FILE_SYSTEM 9
165 #ifndef METHOD_BUFFERED
166 #define METHOD_BUFFERED 0
168 #ifndef FILE_ANY_ACCESS
169 #define FILE_ANY_ACCESS 0x00000000
172 #define CTL_CODE(t,f,m,a) (((t)<<16)|((a)<<14)|((f)<<2)|(m))
174 #define FSCTL_GET_REPARSE_POINT \
175 CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 42, METHOD_BUFFERED, FILE_ANY_ACCESS)
178 /* TCP connection support. */
179 #include <sys/socket.h>
200 #include "w32common.h"
202 #include "w32select.h"
204 #include "dispextern.h" /* for xstrcasecmp */
205 #include "coding.h" /* for Vlocale_coding_system */
207 #include "careadlinkat.h"
208 #include "allocator.h"
210 /* For serial_configure and serial_open. */
213 typedef HRESULT (WINAPI
* ShGetFolderPath_fn
)
214 (IN HWND
, IN
int, IN HANDLE
, IN DWORD
, OUT
char *);
216 Lisp_Object QCloaded_from
;
218 void globals_of_w32 (void);
219 static DWORD
get_rid (PSID
);
220 static int is_symlink (const char *);
221 static char * chase_symlinks (const char *);
222 static int enable_privilege (LPCTSTR
, BOOL
, TOKEN_PRIVILEGES
*);
223 static int restore_privilege (TOKEN_PRIVILEGES
*);
224 static BOOL WINAPI
revert_to_self (void);
226 extern int sys_access (const char *, int);
227 extern void *e_malloc (size_t);
228 extern int sys_select (int, SELECT_TYPE
*, SELECT_TYPE
*, SELECT_TYPE
*,
229 EMACS_TIME
*, void *);
233 /* Initialization states.
235 WARNING: If you add any more such variables for additional APIs,
236 you MUST add initialization for them to globals_of_w32
237 below. This is because these variables might get set
238 to non-NULL values during dumping, but the dumped Emacs
239 cannot reuse those values, because it could be run on a
240 different version of the OS, where API addresses are
242 static BOOL g_b_init_is_windows_9x
;
243 static BOOL g_b_init_open_process_token
;
244 static BOOL g_b_init_get_token_information
;
245 static BOOL g_b_init_lookup_account_sid
;
246 static BOOL g_b_init_get_sid_sub_authority
;
247 static BOOL g_b_init_get_sid_sub_authority_count
;
248 static BOOL g_b_init_get_security_info
;
249 static BOOL g_b_init_get_file_security
;
250 static BOOL g_b_init_get_security_descriptor_owner
;
251 static BOOL g_b_init_get_security_descriptor_group
;
252 static BOOL g_b_init_is_valid_sid
;
253 static BOOL g_b_init_create_toolhelp32_snapshot
;
254 static BOOL g_b_init_process32_first
;
255 static BOOL g_b_init_process32_next
;
256 static BOOL g_b_init_open_thread_token
;
257 static BOOL g_b_init_impersonate_self
;
258 static BOOL g_b_init_revert_to_self
;
259 static BOOL g_b_init_get_process_memory_info
;
260 static BOOL g_b_init_get_process_working_set_size
;
261 static BOOL g_b_init_global_memory_status
;
262 static BOOL g_b_init_global_memory_status_ex
;
263 static BOOL g_b_init_get_length_sid
;
264 static BOOL g_b_init_equal_sid
;
265 static BOOL g_b_init_copy_sid
;
266 static BOOL g_b_init_get_native_system_info
;
267 static BOOL g_b_init_get_system_times
;
268 static BOOL g_b_init_create_symbolic_link
;
269 static BOOL g_b_init_get_security_descriptor_dacl
;
270 static BOOL g_b_init_convert_sd_to_sddl
;
271 static BOOL g_b_init_convert_sddl_to_sd
;
272 static BOOL g_b_init_is_valid_security_descriptor
;
273 static BOOL g_b_init_set_file_security
;
276 BEGIN: Wrapper functions around OpenProcessToken
277 and other functions in advapi32.dll that are only
278 supported in Windows NT / 2k / XP
280 /* ** Function pointer typedefs ** */
281 typedef BOOL (WINAPI
* OpenProcessToken_Proc
) (
282 HANDLE ProcessHandle
,
284 PHANDLE TokenHandle
);
285 typedef BOOL (WINAPI
* GetTokenInformation_Proc
) (
287 TOKEN_INFORMATION_CLASS TokenInformationClass
,
288 LPVOID TokenInformation
,
289 DWORD TokenInformationLength
,
290 PDWORD ReturnLength
);
291 typedef BOOL (WINAPI
* GetProcessTimes_Proc
) (
292 HANDLE process_handle
,
293 LPFILETIME creation_time
,
294 LPFILETIME exit_time
,
295 LPFILETIME kernel_time
,
296 LPFILETIME user_time
);
298 GetProcessTimes_Proc get_process_times_fn
= NULL
;
301 const char * const LookupAccountSid_Name
= "LookupAccountSidW";
302 const char * const GetFileSecurity_Name
= "GetFileSecurityW";
303 const char * const SetFileSecurity_Name
= "SetFileSecurityW";
305 const char * const LookupAccountSid_Name
= "LookupAccountSidA";
306 const char * const GetFileSecurity_Name
= "GetFileSecurityA";
307 const char * const SetFileSecurity_Name
= "SetFileSecurityA";
309 typedef BOOL (WINAPI
* LookupAccountSid_Proc
) (
310 LPCTSTR lpSystemName
,
315 LPDWORD cbDomainName
,
316 PSID_NAME_USE peUse
);
317 typedef PDWORD (WINAPI
* GetSidSubAuthority_Proc
) (
320 typedef PUCHAR (WINAPI
* GetSidSubAuthorityCount_Proc
) (
322 typedef DWORD (WINAPI
* GetSecurityInfo_Proc
) (
324 SE_OBJECT_TYPE ObjectType
,
325 SECURITY_INFORMATION SecurityInfo
,
330 PSECURITY_DESCRIPTOR
*ppSecurityDescriptor
);
331 typedef BOOL (WINAPI
* GetFileSecurity_Proc
) (
333 SECURITY_INFORMATION RequestedInformation
,
334 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
336 LPDWORD lpnLengthNeeded
);
337 typedef BOOL (WINAPI
*SetFileSecurity_Proc
) (
339 SECURITY_INFORMATION SecurityInformation
,
340 PSECURITY_DESCRIPTOR pSecurityDescriptor
);
341 typedef BOOL (WINAPI
* GetSecurityDescriptorOwner_Proc
) (
342 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
344 LPBOOL lpbOwnerDefaulted
);
345 typedef BOOL (WINAPI
* GetSecurityDescriptorGroup_Proc
) (
346 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
348 LPBOOL lpbGroupDefaulted
);
349 typedef BOOL (WINAPI
*GetSecurityDescriptorDacl_Proc
) (
350 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
351 LPBOOL lpbDaclPresent
,
353 LPBOOL lpbDaclDefaulted
);
354 typedef BOOL (WINAPI
* IsValidSid_Proc
) (
356 typedef HANDLE (WINAPI
* CreateToolhelp32Snapshot_Proc
) (
358 DWORD th32ProcessID
);
359 typedef BOOL (WINAPI
* Process32First_Proc
) (
361 LPPROCESSENTRY32 lppe
);
362 typedef BOOL (WINAPI
* Process32Next_Proc
) (
364 LPPROCESSENTRY32 lppe
);
365 typedef BOOL (WINAPI
* OpenThreadToken_Proc
) (
369 PHANDLE TokenHandle
);
370 typedef BOOL (WINAPI
* ImpersonateSelf_Proc
) (
371 SECURITY_IMPERSONATION_LEVEL ImpersonationLevel
);
372 typedef BOOL (WINAPI
* RevertToSelf_Proc
) (void);
373 typedef BOOL (WINAPI
* GetProcessMemoryInfo_Proc
) (
375 PPROCESS_MEMORY_COUNTERS ppsmemCounters
,
377 typedef BOOL (WINAPI
* GetProcessWorkingSetSize_Proc
) (
379 PSIZE_T lpMinimumWorkingSetSize
,
380 PSIZE_T lpMaximumWorkingSetSize
);
381 typedef BOOL (WINAPI
* GlobalMemoryStatus_Proc
) (
382 LPMEMORYSTATUS lpBuffer
);
383 typedef BOOL (WINAPI
* GlobalMemoryStatusEx_Proc
) (
384 LPMEMORY_STATUS_EX lpBuffer
);
385 typedef BOOL (WINAPI
* CopySid_Proc
) (
386 DWORD nDestinationSidLength
,
387 PSID pDestinationSid
,
389 typedef BOOL (WINAPI
* EqualSid_Proc
) (
392 typedef DWORD (WINAPI
* GetLengthSid_Proc
) (
394 typedef void (WINAPI
* GetNativeSystemInfo_Proc
) (
395 LPSYSTEM_INFO lpSystemInfo
);
396 typedef BOOL (WINAPI
* GetSystemTimes_Proc
) (
397 LPFILETIME lpIdleTime
,
398 LPFILETIME lpKernelTime
,
399 LPFILETIME lpUserTime
);
400 typedef BOOLEAN (WINAPI
*CreateSymbolicLink_Proc
) (
401 LPTSTR lpSymlinkFileName
,
402 LPTSTR lpTargetFileName
,
404 typedef BOOL (WINAPI
*ConvertStringSecurityDescriptorToSecurityDescriptor_Proc
) (
405 LPCTSTR StringSecurityDescriptor
,
406 DWORD StringSDRevision
,
407 PSECURITY_DESCRIPTOR
*SecurityDescriptor
,
408 PULONG SecurityDescriptorSize
);
409 typedef BOOL (WINAPI
*ConvertSecurityDescriptorToStringSecurityDescriptor_Proc
) (
410 PSECURITY_DESCRIPTOR SecurityDescriptor
,
411 DWORD RequestedStringSDRevision
,
412 SECURITY_INFORMATION SecurityInformation
,
413 LPTSTR
*StringSecurityDescriptor
,
414 PULONG StringSecurityDescriptorLen
);
415 typedef BOOL (WINAPI
*IsValidSecurityDescriptor_Proc
) (PSECURITY_DESCRIPTOR
);
417 /* ** A utility function ** */
421 static BOOL s_b_ret
= 0;
422 OSVERSIONINFO os_ver
;
423 if (g_b_init_is_windows_9x
== 0)
425 g_b_init_is_windows_9x
= 1;
426 ZeroMemory (&os_ver
, sizeof (OSVERSIONINFO
));
427 os_ver
.dwOSVersionInfoSize
= sizeof (OSVERSIONINFO
);
428 if (GetVersionEx (&os_ver
))
430 s_b_ret
= (os_ver
.dwPlatformId
== VER_PLATFORM_WIN32_WINDOWS
);
436 static Lisp_Object
ltime (ULONGLONG
);
438 /* Get total user and system times for get-internal-run-time.
439 Returns a list of integers if the times are provided by the OS
440 (NT derivatives), otherwise it returns the result of current-time. */
442 w32_get_internal_run_time (void)
444 if (get_process_times_fn
)
446 FILETIME create
, exit
, kernel
, user
;
447 HANDLE proc
= GetCurrentProcess ();
448 if ((*get_process_times_fn
) (proc
, &create
, &exit
, &kernel
, &user
))
450 LARGE_INTEGER user_int
, kernel_int
, total
;
451 user_int
.LowPart
= user
.dwLowDateTime
;
452 user_int
.HighPart
= user
.dwHighDateTime
;
453 kernel_int
.LowPart
= kernel
.dwLowDateTime
;
454 kernel_int
.HighPart
= kernel
.dwHighDateTime
;
455 total
.QuadPart
= user_int
.QuadPart
+ kernel_int
.QuadPart
;
456 return ltime (total
.QuadPart
);
460 return Fcurrent_time ();
463 /* ** The wrapper functions ** */
466 open_process_token (HANDLE ProcessHandle
,
470 static OpenProcessToken_Proc s_pfn_Open_Process_Token
= NULL
;
471 HMODULE hm_advapi32
= NULL
;
472 if (is_windows_9x () == TRUE
)
476 if (g_b_init_open_process_token
== 0)
478 g_b_init_open_process_token
= 1;
479 hm_advapi32
= LoadLibrary ("Advapi32.dll");
480 s_pfn_Open_Process_Token
=
481 (OpenProcessToken_Proc
) GetProcAddress (hm_advapi32
, "OpenProcessToken");
483 if (s_pfn_Open_Process_Token
== NULL
)
488 s_pfn_Open_Process_Token (
496 get_token_information (HANDLE TokenHandle
,
497 TOKEN_INFORMATION_CLASS TokenInformationClass
,
498 LPVOID TokenInformation
,
499 DWORD TokenInformationLength
,
502 static GetTokenInformation_Proc s_pfn_Get_Token_Information
= NULL
;
503 HMODULE hm_advapi32
= NULL
;
504 if (is_windows_9x () == TRUE
)
508 if (g_b_init_get_token_information
== 0)
510 g_b_init_get_token_information
= 1;
511 hm_advapi32
= LoadLibrary ("Advapi32.dll");
512 s_pfn_Get_Token_Information
=
513 (GetTokenInformation_Proc
) GetProcAddress (hm_advapi32
, "GetTokenInformation");
515 if (s_pfn_Get_Token_Information
== NULL
)
520 s_pfn_Get_Token_Information (
522 TokenInformationClass
,
524 TokenInformationLength
,
530 lookup_account_sid (LPCTSTR lpSystemName
,
535 LPDWORD cbDomainName
,
538 static LookupAccountSid_Proc s_pfn_Lookup_Account_Sid
= NULL
;
539 HMODULE hm_advapi32
= NULL
;
540 if (is_windows_9x () == TRUE
)
544 if (g_b_init_lookup_account_sid
== 0)
546 g_b_init_lookup_account_sid
= 1;
547 hm_advapi32
= LoadLibrary ("Advapi32.dll");
548 s_pfn_Lookup_Account_Sid
=
549 (LookupAccountSid_Proc
) GetProcAddress (hm_advapi32
, LookupAccountSid_Name
);
551 if (s_pfn_Lookup_Account_Sid
== NULL
)
556 s_pfn_Lookup_Account_Sid (
568 get_sid_sub_authority (PSID pSid
, DWORD n
)
570 static GetSidSubAuthority_Proc s_pfn_Get_Sid_Sub_Authority
= NULL
;
571 static DWORD zero
= 0U;
572 HMODULE hm_advapi32
= NULL
;
573 if (is_windows_9x () == TRUE
)
577 if (g_b_init_get_sid_sub_authority
== 0)
579 g_b_init_get_sid_sub_authority
= 1;
580 hm_advapi32
= LoadLibrary ("Advapi32.dll");
581 s_pfn_Get_Sid_Sub_Authority
=
582 (GetSidSubAuthority_Proc
) GetProcAddress (
583 hm_advapi32
, "GetSidSubAuthority");
585 if (s_pfn_Get_Sid_Sub_Authority
== NULL
)
589 return (s_pfn_Get_Sid_Sub_Authority (pSid
, n
));
593 get_sid_sub_authority_count (PSID pSid
)
595 static GetSidSubAuthorityCount_Proc s_pfn_Get_Sid_Sub_Authority_Count
= NULL
;
596 static UCHAR zero
= 0U;
597 HMODULE hm_advapi32
= NULL
;
598 if (is_windows_9x () == TRUE
)
602 if (g_b_init_get_sid_sub_authority_count
== 0)
604 g_b_init_get_sid_sub_authority_count
= 1;
605 hm_advapi32
= LoadLibrary ("Advapi32.dll");
606 s_pfn_Get_Sid_Sub_Authority_Count
=
607 (GetSidSubAuthorityCount_Proc
) GetProcAddress (
608 hm_advapi32
, "GetSidSubAuthorityCount");
610 if (s_pfn_Get_Sid_Sub_Authority_Count
== NULL
)
614 return (s_pfn_Get_Sid_Sub_Authority_Count (pSid
));
618 get_security_info (HANDLE handle
,
619 SE_OBJECT_TYPE ObjectType
,
620 SECURITY_INFORMATION SecurityInfo
,
625 PSECURITY_DESCRIPTOR
*ppSecurityDescriptor
)
627 static GetSecurityInfo_Proc s_pfn_Get_Security_Info
= NULL
;
628 HMODULE hm_advapi32
= NULL
;
629 if (is_windows_9x () == TRUE
)
633 if (g_b_init_get_security_info
== 0)
635 g_b_init_get_security_info
= 1;
636 hm_advapi32
= LoadLibrary ("Advapi32.dll");
637 s_pfn_Get_Security_Info
=
638 (GetSecurityInfo_Proc
) GetProcAddress (
639 hm_advapi32
, "GetSecurityInfo");
641 if (s_pfn_Get_Security_Info
== NULL
)
645 return (s_pfn_Get_Security_Info (handle
, ObjectType
, SecurityInfo
,
646 ppsidOwner
, ppsidGroup
, ppDacl
, ppSacl
,
647 ppSecurityDescriptor
));
651 get_file_security (LPCTSTR lpFileName
,
652 SECURITY_INFORMATION RequestedInformation
,
653 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
655 LPDWORD lpnLengthNeeded
)
657 static GetFileSecurity_Proc s_pfn_Get_File_Security
= NULL
;
658 HMODULE hm_advapi32
= NULL
;
659 if (is_windows_9x () == TRUE
)
664 if (g_b_init_get_file_security
== 0)
666 g_b_init_get_file_security
= 1;
667 hm_advapi32
= LoadLibrary ("Advapi32.dll");
668 s_pfn_Get_File_Security
=
669 (GetFileSecurity_Proc
) GetProcAddress (
670 hm_advapi32
, GetFileSecurity_Name
);
672 if (s_pfn_Get_File_Security
== NULL
)
677 return (s_pfn_Get_File_Security (lpFileName
, RequestedInformation
,
678 pSecurityDescriptor
, nLength
,
683 set_file_security (LPCTSTR lpFileName
,
684 SECURITY_INFORMATION SecurityInformation
,
685 PSECURITY_DESCRIPTOR pSecurityDescriptor
)
687 static SetFileSecurity_Proc s_pfn_Set_File_Security
= NULL
;
688 HMODULE hm_advapi32
= NULL
;
689 if (is_windows_9x () == TRUE
)
694 if (g_b_init_set_file_security
== 0)
696 g_b_init_set_file_security
= 1;
697 hm_advapi32
= LoadLibrary ("Advapi32.dll");
698 s_pfn_Set_File_Security
=
699 (SetFileSecurity_Proc
) GetProcAddress (
700 hm_advapi32
, SetFileSecurity_Name
);
702 if (s_pfn_Set_File_Security
== NULL
)
707 return (s_pfn_Set_File_Security (lpFileName
, SecurityInformation
,
708 pSecurityDescriptor
));
712 get_security_descriptor_owner (PSECURITY_DESCRIPTOR pSecurityDescriptor
,
714 LPBOOL lpbOwnerDefaulted
)
716 static GetSecurityDescriptorOwner_Proc s_pfn_Get_Security_Descriptor_Owner
= NULL
;
717 HMODULE hm_advapi32
= NULL
;
718 if (is_windows_9x () == TRUE
)
723 if (g_b_init_get_security_descriptor_owner
== 0)
725 g_b_init_get_security_descriptor_owner
= 1;
726 hm_advapi32
= LoadLibrary ("Advapi32.dll");
727 s_pfn_Get_Security_Descriptor_Owner
=
728 (GetSecurityDescriptorOwner_Proc
) GetProcAddress (
729 hm_advapi32
, "GetSecurityDescriptorOwner");
731 if (s_pfn_Get_Security_Descriptor_Owner
== NULL
)
736 return (s_pfn_Get_Security_Descriptor_Owner (pSecurityDescriptor
, pOwner
,
741 get_security_descriptor_group (PSECURITY_DESCRIPTOR pSecurityDescriptor
,
743 LPBOOL lpbGroupDefaulted
)
745 static GetSecurityDescriptorGroup_Proc s_pfn_Get_Security_Descriptor_Group
= NULL
;
746 HMODULE hm_advapi32
= NULL
;
747 if (is_windows_9x () == TRUE
)
752 if (g_b_init_get_security_descriptor_group
== 0)
754 g_b_init_get_security_descriptor_group
= 1;
755 hm_advapi32
= LoadLibrary ("Advapi32.dll");
756 s_pfn_Get_Security_Descriptor_Group
=
757 (GetSecurityDescriptorGroup_Proc
) GetProcAddress (
758 hm_advapi32
, "GetSecurityDescriptorGroup");
760 if (s_pfn_Get_Security_Descriptor_Group
== NULL
)
765 return (s_pfn_Get_Security_Descriptor_Group (pSecurityDescriptor
, pGroup
,
770 get_security_descriptor_dacl (PSECURITY_DESCRIPTOR pSecurityDescriptor
,
771 LPBOOL lpbDaclPresent
,
773 LPBOOL lpbDaclDefaulted
)
775 static GetSecurityDescriptorDacl_Proc s_pfn_Get_Security_Descriptor_Dacl
= NULL
;
776 HMODULE hm_advapi32
= NULL
;
777 if (is_windows_9x () == TRUE
)
782 if (g_b_init_get_security_descriptor_dacl
== 0)
784 g_b_init_get_security_descriptor_dacl
= 1;
785 hm_advapi32
= LoadLibrary ("Advapi32.dll");
786 s_pfn_Get_Security_Descriptor_Dacl
=
787 (GetSecurityDescriptorDacl_Proc
) GetProcAddress (
788 hm_advapi32
, "GetSecurityDescriptorDacl");
790 if (s_pfn_Get_Security_Descriptor_Dacl
== NULL
)
795 return (s_pfn_Get_Security_Descriptor_Dacl (pSecurityDescriptor
,
796 lpbDaclPresent
, pDacl
,
801 is_valid_sid (PSID sid
)
803 static IsValidSid_Proc s_pfn_Is_Valid_Sid
= NULL
;
804 HMODULE hm_advapi32
= NULL
;
805 if (is_windows_9x () == TRUE
)
809 if (g_b_init_is_valid_sid
== 0)
811 g_b_init_is_valid_sid
= 1;
812 hm_advapi32
= LoadLibrary ("Advapi32.dll");
814 (IsValidSid_Proc
) GetProcAddress (
815 hm_advapi32
, "IsValidSid");
817 if (s_pfn_Is_Valid_Sid
== NULL
)
821 return (s_pfn_Is_Valid_Sid (sid
));
825 equal_sid (PSID sid1
, PSID sid2
)
827 static EqualSid_Proc s_pfn_Equal_Sid
= NULL
;
828 HMODULE hm_advapi32
= NULL
;
829 if (is_windows_9x () == TRUE
)
833 if (g_b_init_equal_sid
== 0)
835 g_b_init_equal_sid
= 1;
836 hm_advapi32
= LoadLibrary ("Advapi32.dll");
838 (EqualSid_Proc
) GetProcAddress (
839 hm_advapi32
, "EqualSid");
841 if (s_pfn_Equal_Sid
== NULL
)
845 return (s_pfn_Equal_Sid (sid1
, sid2
));
849 get_length_sid (PSID sid
)
851 static GetLengthSid_Proc s_pfn_Get_Length_Sid
= NULL
;
852 HMODULE hm_advapi32
= NULL
;
853 if (is_windows_9x () == TRUE
)
857 if (g_b_init_get_length_sid
== 0)
859 g_b_init_get_length_sid
= 1;
860 hm_advapi32
= LoadLibrary ("Advapi32.dll");
861 s_pfn_Get_Length_Sid
=
862 (GetLengthSid_Proc
) GetProcAddress (
863 hm_advapi32
, "GetLengthSid");
865 if (s_pfn_Get_Length_Sid
== NULL
)
869 return (s_pfn_Get_Length_Sid (sid
));
873 copy_sid (DWORD destlen
, PSID dest
, PSID src
)
875 static CopySid_Proc s_pfn_Copy_Sid
= NULL
;
876 HMODULE hm_advapi32
= NULL
;
877 if (is_windows_9x () == TRUE
)
881 if (g_b_init_copy_sid
== 0)
883 g_b_init_copy_sid
= 1;
884 hm_advapi32
= LoadLibrary ("Advapi32.dll");
886 (CopySid_Proc
) GetProcAddress (
887 hm_advapi32
, "CopySid");
889 if (s_pfn_Copy_Sid
== NULL
)
893 return (s_pfn_Copy_Sid (destlen
, dest
, src
));
897 END: Wrapper functions around OpenProcessToken
898 and other functions in advapi32.dll that are only
899 supported in Windows NT / 2k / XP
903 get_native_system_info (LPSYSTEM_INFO lpSystemInfo
)
905 static GetNativeSystemInfo_Proc s_pfn_Get_Native_System_Info
= NULL
;
906 if (is_windows_9x () != TRUE
)
908 if (g_b_init_get_native_system_info
== 0)
910 g_b_init_get_native_system_info
= 1;
911 s_pfn_Get_Native_System_Info
=
912 (GetNativeSystemInfo_Proc
)GetProcAddress (GetModuleHandle ("kernel32.dll"),
913 "GetNativeSystemInfo");
915 if (s_pfn_Get_Native_System_Info
!= NULL
)
916 s_pfn_Get_Native_System_Info (lpSystemInfo
);
919 lpSystemInfo
->dwNumberOfProcessors
= -1;
923 get_system_times (LPFILETIME lpIdleTime
,
924 LPFILETIME lpKernelTime
,
925 LPFILETIME lpUserTime
)
927 static GetSystemTimes_Proc s_pfn_Get_System_times
= NULL
;
928 if (is_windows_9x () == TRUE
)
932 if (g_b_init_get_system_times
== 0)
934 g_b_init_get_system_times
= 1;
935 s_pfn_Get_System_times
=
936 (GetSystemTimes_Proc
)GetProcAddress (GetModuleHandle ("kernel32.dll"),
939 if (s_pfn_Get_System_times
== NULL
)
941 return (s_pfn_Get_System_times (lpIdleTime
, lpKernelTime
, lpUserTime
));
944 static BOOLEAN WINAPI
945 create_symbolic_link (LPTSTR lpSymlinkFilename
,
946 LPTSTR lpTargetFileName
,
949 static CreateSymbolicLink_Proc s_pfn_Create_Symbolic_Link
= NULL
;
952 if (is_windows_9x () == TRUE
)
957 if (g_b_init_create_symbolic_link
== 0)
959 g_b_init_create_symbolic_link
= 1;
961 s_pfn_Create_Symbolic_Link
=
962 (CreateSymbolicLink_Proc
)GetProcAddress (GetModuleHandle ("kernel32.dll"),
963 "CreateSymbolicLinkW");
965 s_pfn_Create_Symbolic_Link
=
966 (CreateSymbolicLink_Proc
)GetProcAddress (GetModuleHandle ("kernel32.dll"),
967 "CreateSymbolicLinkA");
970 if (s_pfn_Create_Symbolic_Link
== NULL
)
976 retval
= s_pfn_Create_Symbolic_Link (lpSymlinkFilename
, lpTargetFileName
,
978 /* If we were denied creation of the symlink, try again after
979 enabling the SeCreateSymbolicLinkPrivilege for our process. */
982 TOKEN_PRIVILEGES priv_current
;
984 if (enable_privilege (SE_CREATE_SYMBOLIC_LINK_NAME
, TRUE
, &priv_current
))
986 retval
= s_pfn_Create_Symbolic_Link (lpSymlinkFilename
, lpTargetFileName
,
988 restore_privilege (&priv_current
);
996 is_valid_security_descriptor (PSECURITY_DESCRIPTOR pSecurityDescriptor
)
998 static IsValidSecurityDescriptor_Proc s_pfn_Is_Valid_Security_Descriptor_Proc
= NULL
;
1000 if (is_windows_9x () == TRUE
)
1006 if (g_b_init_is_valid_security_descriptor
== 0)
1008 g_b_init_is_valid_security_descriptor
= 1;
1009 s_pfn_Is_Valid_Security_Descriptor_Proc
=
1010 (IsValidSecurityDescriptor_Proc
)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1011 "IsValidSecurityDescriptor");
1013 if (s_pfn_Is_Valid_Security_Descriptor_Proc
== NULL
)
1019 return s_pfn_Is_Valid_Security_Descriptor_Proc (pSecurityDescriptor
);
1023 convert_sd_to_sddl (PSECURITY_DESCRIPTOR SecurityDescriptor
,
1024 DWORD RequestedStringSDRevision
,
1025 SECURITY_INFORMATION SecurityInformation
,
1026 LPTSTR
*StringSecurityDescriptor
,
1027 PULONG StringSecurityDescriptorLen
)
1029 static ConvertSecurityDescriptorToStringSecurityDescriptor_Proc s_pfn_Convert_SD_To_SDDL
= NULL
;
1032 if (is_windows_9x () == TRUE
)
1038 if (g_b_init_convert_sd_to_sddl
== 0)
1040 g_b_init_convert_sd_to_sddl
= 1;
1042 s_pfn_Convert_SD_To_SDDL
=
1043 (ConvertSecurityDescriptorToStringSecurityDescriptor_Proc
)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1044 "ConvertSecurityDescriptorToStringSecurityDescriptorW");
1046 s_pfn_Convert_SD_To_SDDL
=
1047 (ConvertSecurityDescriptorToStringSecurityDescriptor_Proc
)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1048 "ConvertSecurityDescriptorToStringSecurityDescriptorA");
1051 if (s_pfn_Convert_SD_To_SDDL
== NULL
)
1057 retval
= s_pfn_Convert_SD_To_SDDL (SecurityDescriptor
,
1058 RequestedStringSDRevision
,
1059 SecurityInformation
,
1060 StringSecurityDescriptor
,
1061 StringSecurityDescriptorLen
);
1067 convert_sddl_to_sd (LPCTSTR StringSecurityDescriptor
,
1068 DWORD StringSDRevision
,
1069 PSECURITY_DESCRIPTOR
*SecurityDescriptor
,
1070 PULONG SecurityDescriptorSize
)
1072 static ConvertStringSecurityDescriptorToSecurityDescriptor_Proc s_pfn_Convert_SDDL_To_SD
= NULL
;
1075 if (is_windows_9x () == TRUE
)
1081 if (g_b_init_convert_sddl_to_sd
== 0)
1083 g_b_init_convert_sddl_to_sd
= 1;
1085 s_pfn_Convert_SDDL_To_SD
=
1086 (ConvertStringSecurityDescriptorToSecurityDescriptor_Proc
)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1087 "ConvertStringSecurityDescriptorToSecurityDescriptorW");
1089 s_pfn_Convert_SDDL_To_SD
=
1090 (ConvertStringSecurityDescriptorToSecurityDescriptor_Proc
)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1091 "ConvertStringSecurityDescriptorToSecurityDescriptorA");
1094 if (s_pfn_Convert_SDDL_To_SD
== NULL
)
1100 retval
= s_pfn_Convert_SDDL_To_SD (StringSecurityDescriptor
,
1103 SecurityDescriptorSize
);
1110 /* Return 1 if P is a valid pointer to an object of size SIZE. Return
1111 0 if P is NOT a valid pointer. Return -1 if we cannot validate P.
1113 This is called from alloc.c:valid_pointer_p. */
1115 w32_valid_pointer_p (void *p
, int size
)
1118 HANDLE h
= OpenProcess (PROCESS_VM_READ
, FALSE
, GetCurrentProcessId ());
1122 unsigned char *buf
= alloca (size
);
1123 int retval
= ReadProcessMemory (h
, p
, buf
, size
, &done
);
1132 static char startup_dir
[MAXPATHLEN
];
1134 /* Get the current working directory. */
1136 getcwd (char *dir
, int dirsize
)
1143 if (dirsize
<= strlen (startup_dir
))
1149 if (GetCurrentDirectory (MAXPATHLEN
, dir
) > 0)
1153 /* Emacs doesn't actually change directory itself, it stays in the
1154 same directory where it was started. */
1155 strcpy (dir
, startup_dir
);
1160 /* Emulate getloadavg. */
1162 struct load_sample
{
1169 /* Number of processors on this machine. */
1170 static unsigned num_of_processors
;
1172 /* We maintain 1-sec samples for the last 16 minutes in a circular buffer. */
1173 static struct load_sample samples
[16*60];
1174 static int first_idx
= -1, last_idx
= -1;
1175 static int max_idx
= sizeof (samples
) / sizeof (samples
[0]);
1180 int next_idx
= from
+ 1;
1182 if (next_idx
>= max_idx
)
1191 int prev_idx
= from
- 1;
1194 prev_idx
= max_idx
- 1;
1200 sample_system_load (ULONGLONG
*idle
, ULONGLONG
*kernel
, ULONGLONG
*user
)
1202 SYSTEM_INFO sysinfo
;
1203 FILETIME ft_idle
, ft_user
, ft_kernel
;
1205 /* Initialize the number of processors on this machine. */
1206 if (num_of_processors
<= 0)
1208 get_native_system_info (&sysinfo
);
1209 num_of_processors
= sysinfo
.dwNumberOfProcessors
;
1210 if (num_of_processors
<= 0)
1212 GetSystemInfo (&sysinfo
);
1213 num_of_processors
= sysinfo
.dwNumberOfProcessors
;
1215 if (num_of_processors
<= 0)
1216 num_of_processors
= 1;
1219 /* TODO: Take into account threads that are ready to run, by
1220 sampling the "\System\Processor Queue Length" performance
1221 counter. The code below accounts only for threads that are
1222 actually running. */
1224 if (get_system_times (&ft_idle
, &ft_kernel
, &ft_user
))
1226 ULARGE_INTEGER uidle
, ukernel
, uuser
;
1228 memcpy (&uidle
, &ft_idle
, sizeof (ft_idle
));
1229 memcpy (&ukernel
, &ft_kernel
, sizeof (ft_kernel
));
1230 memcpy (&uuser
, &ft_user
, sizeof (ft_user
));
1231 *idle
= uidle
.QuadPart
;
1232 *kernel
= ukernel
.QuadPart
;
1233 *user
= uuser
.QuadPart
;
1243 /* Produce the load average for a given time interval, using the
1244 samples in the samples[] array. WHICH can be 0, 1, or 2, meaning
1245 1-minute, 5-minute, or 15-minute average, respectively. */
1249 double retval
= -1.0;
1252 double span
= (which
== 0 ? 1.0 : (which
== 1 ? 5.0 : 15.0)) * 60;
1253 time_t now
= samples
[last_idx
].sample_time
;
1255 if (first_idx
!= last_idx
)
1257 for (idx
= buf_prev (last_idx
); ; idx
= buf_prev (idx
))
1259 tdiff
= difftime (now
, samples
[idx
].sample_time
);
1260 if (tdiff
>= span
- 2*DBL_EPSILON
*now
)
1263 samples
[last_idx
].kernel
+ samples
[last_idx
].user
1264 - (samples
[idx
].kernel
+ samples
[idx
].user
);
1265 long double idl
= samples
[last_idx
].idle
- samples
[idx
].idle
;
1267 retval
= (1.0 - idl
/ sys
) * num_of_processors
;
1270 if (idx
== first_idx
)
1279 getloadavg (double loadavg
[], int nelem
)
1282 ULONGLONG idle
, kernel
, user
;
1283 time_t now
= time (NULL
);
1285 /* Store another sample. We ignore samples that are less than 1 sec
1287 if (difftime (now
, samples
[last_idx
].sample_time
) >= 1.0 - 2*DBL_EPSILON
*now
)
1289 sample_system_load (&idle
, &kernel
, &user
);
1290 last_idx
= buf_next (last_idx
);
1291 samples
[last_idx
].sample_time
= now
;
1292 samples
[last_idx
].idle
= idle
;
1293 samples
[last_idx
].kernel
= kernel
;
1294 samples
[last_idx
].user
= user
;
1295 /* If the buffer has more that 15 min worth of samples, discard
1297 if (first_idx
== -1)
1298 first_idx
= last_idx
;
1299 while (first_idx
!= last_idx
1300 && (difftime (now
, samples
[first_idx
].sample_time
)
1301 >= 15.0*60 + 2*DBL_EPSILON
*now
))
1302 first_idx
= buf_next (first_idx
);
1305 for (elem
= 0; elem
< nelem
; elem
++)
1307 double avg
= getavg (elem
);
1311 loadavg
[elem
] = avg
;
1317 /* Emulate getpwuid, getpwnam and others. */
1319 #define PASSWD_FIELD_SIZE 256
1321 static char dflt_passwd_name
[PASSWD_FIELD_SIZE
];
1322 static char dflt_passwd_passwd
[PASSWD_FIELD_SIZE
];
1323 static char dflt_passwd_gecos
[PASSWD_FIELD_SIZE
];
1324 static char dflt_passwd_dir
[PASSWD_FIELD_SIZE
];
1325 static char dflt_passwd_shell
[PASSWD_FIELD_SIZE
];
1327 static struct passwd dflt_passwd
=
1339 static char dflt_group_name
[GNLEN
+1];
1341 static struct group dflt_group
=
1343 /* When group information is not available, we return this as the
1344 group for all files. */
1352 return dflt_passwd
.pw_uid
;
1358 /* I could imagine arguing for checking to see whether the user is
1359 in the Administrators group and returning a UID of 0 for that
1360 case, but I don't know how wise that would be in the long run. */
1367 return dflt_passwd
.pw_gid
;
1377 getpwuid (unsigned uid
)
1379 if (uid
== dflt_passwd
.pw_uid
)
1380 return &dflt_passwd
;
1385 getgrgid (gid_t gid
)
1391 getpwnam (char *name
)
1395 pw
= getpwuid (getuid ());
1399 if (xstrcasecmp (name
, pw
->pw_name
))
1406 init_user_info (void)
1408 /* Find the user's real name by opening the process token and
1409 looking up the name associated with the user-sid in that token.
1411 Use the relative portion of the identifier authority value from
1412 the user-sid as the user id value (same for group id using the
1413 primary group sid from the process token). */
1415 char uname
[UNLEN
+1], gname
[GNLEN
+1], domain
[1025];
1416 DWORD ulength
= sizeof (uname
), dlength
= sizeof (domain
), needed
;
1417 DWORD glength
= sizeof (gname
);
1418 HANDLE token
= NULL
;
1419 SID_NAME_USE user_type
;
1420 unsigned char *buf
= NULL
;
1422 TOKEN_USER user_token
;
1423 TOKEN_PRIMARY_GROUP group_token
;
1426 result
= open_process_token (GetCurrentProcess (), TOKEN_QUERY
, &token
);
1429 result
= get_token_information (token
, TokenUser
, NULL
, 0, &blen
);
1430 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
1432 buf
= xmalloc (blen
);
1433 result
= get_token_information (token
, TokenUser
,
1434 (LPVOID
)buf
, blen
, &needed
);
1437 memcpy (&user_token
, buf
, sizeof (user_token
));
1438 result
= lookup_account_sid (NULL
, user_token
.User
.Sid
,
1440 domain
, &dlength
, &user_type
);
1448 strcpy (dflt_passwd
.pw_name
, uname
);
1449 /* Determine a reasonable uid value. */
1450 if (xstrcasecmp ("administrator", uname
) == 0)
1452 dflt_passwd
.pw_uid
= 500; /* well-known Administrator uid */
1453 dflt_passwd
.pw_gid
= 513; /* well-known None gid */
1457 /* Use the last sub-authority value of the RID, the relative
1458 portion of the SID, as user/group ID. */
1459 dflt_passwd
.pw_uid
= get_rid (user_token
.User
.Sid
);
1461 /* Get group id and name. */
1462 result
= get_token_information (token
, TokenPrimaryGroup
,
1463 (LPVOID
)buf
, blen
, &needed
);
1464 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
1466 buf
= xrealloc (buf
, blen
= needed
);
1467 result
= get_token_information (token
, TokenPrimaryGroup
,
1468 (LPVOID
)buf
, blen
, &needed
);
1472 memcpy (&group_token
, buf
, sizeof (group_token
));
1473 dflt_passwd
.pw_gid
= get_rid (group_token
.PrimaryGroup
);
1474 dlength
= sizeof (domain
);
1475 /* If we can get at the real Primary Group name, use that.
1476 Otherwise, the default group name was already set to
1477 "None" in globals_of_w32. */
1478 if (lookup_account_sid (NULL
, group_token
.PrimaryGroup
,
1479 gname
, &glength
, NULL
, &dlength
,
1481 strcpy (dflt_group_name
, gname
);
1484 dflt_passwd
.pw_gid
= dflt_passwd
.pw_uid
;
1487 /* If security calls are not supported (presumably because we
1488 are running under Windows 9X), fallback to this: */
1489 else if (GetUserName (uname
, &ulength
))
1491 strcpy (dflt_passwd
.pw_name
, uname
);
1492 if (xstrcasecmp ("administrator", uname
) == 0)
1493 dflt_passwd
.pw_uid
= 0;
1495 dflt_passwd
.pw_uid
= 123;
1496 dflt_passwd
.pw_gid
= dflt_passwd
.pw_uid
;
1500 strcpy (dflt_passwd
.pw_name
, "unknown");
1501 dflt_passwd
.pw_uid
= 123;
1502 dflt_passwd
.pw_gid
= 123;
1504 dflt_group
.gr_gid
= dflt_passwd
.pw_gid
;
1506 /* Ensure HOME and SHELL are defined. */
1507 if (getenv ("HOME") == NULL
)
1509 if (getenv ("SHELL") == NULL
)
1512 /* Set dir and shell from environment variables. */
1513 strcpy (dflt_passwd
.pw_dir
, getenv ("HOME"));
1514 strcpy (dflt_passwd
.pw_shell
, getenv ("SHELL"));
1518 CloseHandle (token
);
1524 /* rand () on NT gives us 15 random bits...hack together 30 bits. */
1525 return ((rand () << 15) | rand ());
1535 /* Normalize filename by converting all path separators to
1536 the specified separator. Also conditionally convert upper
1537 case path name components to lower case. */
1540 normalize_filename (register char *fp
, char path_sep
)
1545 /* Always lower-case drive letters a-z, even if the filesystem
1546 preserves case in filenames.
1547 This is so filenames can be compared by string comparison
1548 functions that are case-sensitive. Even case-preserving filesystems
1549 do not distinguish case in drive letters. */
1550 if (fp
[1] == ':' && *fp
>= 'A' && *fp
<= 'Z')
1556 if (NILP (Vw32_downcase_file_names
))
1560 if (*fp
== '/' || *fp
== '\\')
1567 sep
= path_sep
; /* convert to this path separator */
1568 elem
= fp
; /* start of current path element */
1571 if (*fp
>= 'a' && *fp
<= 'z')
1572 elem
= 0; /* don't convert this element */
1574 if (*fp
== 0 || *fp
== ':')
1576 sep
= *fp
; /* restore current separator (or 0) */
1577 *fp
= '/'; /* after conversion of this element */
1580 if (*fp
== '/' || *fp
== '\\')
1582 if (elem
&& elem
!= fp
)
1584 *fp
= 0; /* temporary end of string */
1585 _strlwr (elem
); /* while we convert to lower case */
1587 *fp
= sep
; /* convert (or restore) path separator */
1588 elem
= fp
+ 1; /* next element starts after separator */
1594 /* Destructively turn backslashes into slashes. */
1596 dostounix_filename (register char *p
)
1598 normalize_filename (p
, '/');
1601 /* Destructively turn slashes into backslashes. */
1603 unixtodos_filename (register char *p
)
1605 normalize_filename (p
, '\\');
1608 /* Remove all CR's that are followed by a LF.
1609 (From msdos.c...probably should figure out a way to share it,
1610 although this code isn't going to ever change.) */
1612 crlf_to_lf (register int n
, register unsigned char *buf
)
1614 unsigned char *np
= buf
;
1615 unsigned char *startp
= buf
;
1616 unsigned char *endp
= buf
+ n
;
1620 while (buf
< endp
- 1)
1624 if (*(++buf
) != 0x0a)
1635 /* Parse the root part of file name, if present. Return length and
1636 optionally store pointer to char after root. */
1638 parse_root (char * name
, char ** pPath
)
1640 char * start
= name
;
1645 /* find the root name of the volume if given */
1646 if (isalpha (name
[0]) && name
[1] == ':')
1648 /* skip past drive specifier */
1650 if (IS_DIRECTORY_SEP (name
[0]))
1653 else if (IS_DIRECTORY_SEP (name
[0]) && IS_DIRECTORY_SEP (name
[1]))
1659 if (IS_DIRECTORY_SEP (*name
) && --slashes
== 0)
1664 if (IS_DIRECTORY_SEP (name
[0]))
1671 return name
- start
;
1674 /* Get long base name for name; name is assumed to be absolute. */
1676 get_long_basename (char * name
, char * buf
, int size
)
1678 WIN32_FIND_DATA find_data
;
1682 /* must be valid filename, no wild cards or other invalid characters */
1683 if (_mbspbrk (name
, "*?|<>\""))
1686 dir_handle
= FindFirstFile (name
, &find_data
);
1687 if (dir_handle
!= INVALID_HANDLE_VALUE
)
1689 if ((len
= strlen (find_data
.cFileName
)) < size
)
1690 memcpy (buf
, find_data
.cFileName
, len
+ 1);
1693 FindClose (dir_handle
);
1698 /* Get long name for file, if possible (assumed to be absolute). */
1700 w32_get_long_filename (char * name
, char * buf
, int size
)
1705 char full
[ MAX_PATH
];
1708 len
= strlen (name
);
1709 if (len
>= MAX_PATH
)
1712 /* Use local copy for destructive modification. */
1713 memcpy (full
, name
, len
+1);
1714 unixtodos_filename (full
);
1716 /* Copy root part verbatim. */
1717 len
= parse_root (full
, &p
);
1718 memcpy (o
, full
, len
);
1723 while (p
!= NULL
&& *p
)
1726 p
= strchr (q
, '\\');
1728 len
= get_long_basename (full
, o
, size
);
1751 is_unc_volume (const char *filename
)
1753 const char *ptr
= filename
;
1755 if (!IS_DIRECTORY_SEP (ptr
[0]) || !IS_DIRECTORY_SEP (ptr
[1]) || !ptr
[2])
1758 if (_mbspbrk (ptr
+ 2, "*?|<>\"\\/"))
1764 /* Emulate the Posix unsetenv. */
1766 unsetenv (const char *name
)
1772 if (name
== NULL
|| *name
== '\0' || strchr (name
, '=') != NULL
)
1777 name_len
= strlen (name
);
1778 /* MS docs says an environment variable cannot be longer than 32K. */
1779 if (name_len
> 32767)
1784 /* It is safe to use 'alloca' with 32K size, since the stack is at
1785 least 2MB, and we set it to 8MB in the link command line. */
1786 var
= alloca (name_len
+ 2);
1787 var
[name_len
++] = '=';
1788 var
[name_len
] = '\0';
1789 return _putenv (var
);
1792 /* MS _putenv doesn't support removing a variable when the argument
1793 does not include the '=' character, so we fix that here. */
1795 sys_putenv (char *str
)
1797 const char *const name_end
= strchr (str
, '=');
1799 if (name_end
== NULL
)
1801 /* Remove the variable from the environment. */
1802 return unsetenv (str
);
1805 return _putenv (str
);
1808 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
1811 w32_get_resource (char *key
, LPDWORD lpdwtype
)
1814 HKEY hrootkey
= NULL
;
1817 /* Check both the current user and the local machine to see if
1818 we have any resources. */
1820 if (RegOpenKeyEx (HKEY_CURRENT_USER
, REG_ROOT
, 0, KEY_READ
, &hrootkey
) == ERROR_SUCCESS
)
1824 if (RegQueryValueEx (hrootkey
, key
, NULL
, NULL
, NULL
, &cbData
) == ERROR_SUCCESS
1825 && (lpvalue
= xmalloc (cbData
)) != NULL
1826 && RegQueryValueEx (hrootkey
, key
, NULL
, lpdwtype
, lpvalue
, &cbData
) == ERROR_SUCCESS
)
1828 RegCloseKey (hrootkey
);
1834 RegCloseKey (hrootkey
);
1837 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE
, REG_ROOT
, 0, KEY_READ
, &hrootkey
) == ERROR_SUCCESS
)
1841 if (RegQueryValueEx (hrootkey
, key
, NULL
, NULL
, NULL
, &cbData
) == ERROR_SUCCESS
1842 && (lpvalue
= xmalloc (cbData
)) != NULL
1843 && RegQueryValueEx (hrootkey
, key
, NULL
, lpdwtype
, lpvalue
, &cbData
) == ERROR_SUCCESS
)
1845 RegCloseKey (hrootkey
);
1851 RegCloseKey (hrootkey
);
1857 char *get_emacs_configuration (void);
1860 init_environment (char ** argv
)
1862 static const char * const tempdirs
[] = {
1863 "$TMPDIR", "$TEMP", "$TMP", "c:/"
1868 const int imax
= sizeof (tempdirs
) / sizeof (tempdirs
[0]);
1870 /* Make sure they have a usable $TMPDIR. Many Emacs functions use
1871 temporary files and assume "/tmp" if $TMPDIR is unset, which
1872 will break on DOS/Windows. Refuse to work if we cannot find
1873 a directory, not even "c:/", usable for that purpose. */
1874 for (i
= 0; i
< imax
; i
++)
1876 const char *tmp
= tempdirs
[i
];
1879 tmp
= getenv (tmp
+ 1);
1880 /* Note that `access' can lie to us if the directory resides on a
1881 read-only filesystem, like CD-ROM or a write-protected floppy.
1882 The only way to be really sure is to actually create a file and
1883 see if it succeeds. But I think that's too much to ask. */
1885 /* MSVCRT's _access crashes with D_OK. */
1886 if (tmp
&& faccessat (AT_FDCWD
, tmp
, D_OK
, AT_EACCESS
) == 0)
1888 char * var
= alloca (strlen (tmp
) + 8);
1889 sprintf (var
, "TMPDIR=%s", tmp
);
1890 _putenv (strdup (var
));
1897 Fcons (build_string ("no usable temporary directories found!!"),
1899 "While setting TMPDIR: ");
1901 /* Check for environment variables and use registry settings if they
1902 don't exist. Fallback on default values where applicable. */
1907 char locale_name
[32];
1908 char default_home
[MAX_PATH
];
1911 static const struct env_entry
1917 /* If the default value is NULL, we will use the value from the
1918 outside environment or the Registry, but will not push the
1919 variable into the Emacs environment if it is defined neither
1920 in the Registry nor in the outside environment. */
1922 {"PRELOAD_WINSOCK", NULL
},
1923 {"emacs_dir", "C:/emacs"},
1924 {"EMACSLOADPATH", NULL
},
1925 {"SHELL", "%emacs_dir%/bin/cmdproxy.exe"},
1926 {"EMACSDATA", NULL
},
1927 {"EMACSPATH", NULL
},
1934 #define N_ENV_VARS sizeof (dflt_envvars)/sizeof (dflt_envvars[0])
1936 /* We need to copy dflt_envvars[] and work on the copy because we
1937 don't want the dumped Emacs to inherit the values of
1938 environment variables we saw during dumping (which could be on
1939 a different system). The defaults above must be left intact. */
1940 struct env_entry env_vars
[N_ENV_VARS
];
1942 for (i
= 0; i
< N_ENV_VARS
; i
++)
1943 env_vars
[i
] = dflt_envvars
[i
];
1945 /* For backwards compatibility, check if a .emacs file exists in C:/
1946 If not, then we can try to default to the appdata directory under the
1947 user's profile, which is more likely to be writable. */
1948 if (!check_existing ("C:/.emacs"))
1950 HRESULT profile_result
;
1951 /* Dynamically load ShGetFolderPath, as it won't exist on versions
1952 of Windows 95 and NT4 that have not been updated to include
1954 ShGetFolderPath_fn get_folder_path
;
1955 get_folder_path
= (ShGetFolderPath_fn
)
1956 GetProcAddress (GetModuleHandle ("shell32.dll"), "SHGetFolderPathA");
1958 if (get_folder_path
!= NULL
)
1960 profile_result
= get_folder_path (NULL
, CSIDL_APPDATA
, NULL
,
1963 /* If we can't get the appdata dir, revert to old behavior. */
1964 if (profile_result
== S_OK
)
1966 env_vars
[0].def_value
= default_home
;
1972 /* Get default locale info and use it for LANG. */
1973 if (GetLocaleInfo (LOCALE_USER_DEFAULT
,
1974 LOCALE_SABBREVLANGNAME
| LOCALE_USE_CP_ACP
,
1975 locale_name
, sizeof (locale_name
)))
1977 for (i
= 0; i
< N_ENV_VARS
; i
++)
1979 if (strcmp (env_vars
[i
].name
, "LANG") == 0)
1981 env_vars
[i
].def_value
= locale_name
;
1987 #define SET_ENV_BUF_SIZE (4 * MAX_PATH) /* to cover EMACSLOADPATH */
1989 /* Treat emacs_dir specially: set it unconditionally based on our
1993 char modname
[MAX_PATH
];
1995 if (!GetModuleFileName (NULL
, modname
, MAX_PATH
))
1997 if ((p
= strrchr (modname
, '\\')) == NULL
)
2001 if ((p
= strrchr (modname
, '\\')) && xstrcasecmp (p
, "\\bin") == 0)
2003 char buf
[SET_ENV_BUF_SIZE
];
2006 for (p
= modname
; *p
; p
++)
2007 if (*p
== '\\') *p
= '/';
2009 _snprintf (buf
, sizeof (buf
)-1, "emacs_dir=%s", modname
);
2010 _putenv (strdup (buf
));
2012 /* Handle running emacs from the build directory: src/oo-spd/i386/ */
2014 /* FIXME: should use substring of get_emacs_configuration ().
2015 But I don't think the Windows build supports alpha, mips etc
2016 anymore, so have taken the easy option for now. */
2017 else if (p
&& (xstrcasecmp (p
, "\\i386") == 0
2018 || xstrcasecmp (p
, "\\AMD64") == 0))
2021 p
= strrchr (modname
, '\\');
2025 p
= strrchr (modname
, '\\');
2026 if (p
&& xstrcasecmp (p
, "\\src") == 0)
2028 char buf
[SET_ENV_BUF_SIZE
];
2031 for (p
= modname
; *p
; p
++)
2032 if (*p
== '\\') *p
= '/';
2034 _snprintf (buf
, sizeof (buf
)-1, "emacs_dir=%s", modname
);
2035 _putenv (strdup (buf
));
2041 for (i
= 0; i
< N_ENV_VARS
; i
++)
2043 if (!getenv (env_vars
[i
].name
))
2047 if ((lpval
= w32_get_resource (env_vars
[i
].name
, &dwType
)) == NULL
2048 /* Also ignore empty environment variables. */
2052 lpval
= env_vars
[i
].def_value
;
2053 dwType
= REG_EXPAND_SZ
;
2055 if (!strcmp (env_vars
[i
].name
, "HOME") && !appdata
)
2056 Vdelayed_warnings_list
2057 = Fcons (listn (CONSTYPE_HEAP
, 2,
2058 intern ("initialization"),
2059 build_string ("Setting HOME to C:\\ by default is deprecated")),
2060 Vdelayed_warnings_list
);
2065 char buf1
[SET_ENV_BUF_SIZE
], buf2
[SET_ENV_BUF_SIZE
];
2067 if (dwType
== REG_EXPAND_SZ
)
2068 ExpandEnvironmentStrings ((LPSTR
) lpval
, buf1
, sizeof (buf1
));
2069 else if (dwType
== REG_SZ
)
2070 strcpy (buf1
, lpval
);
2071 if (dwType
== REG_EXPAND_SZ
|| dwType
== REG_SZ
)
2073 _snprintf (buf2
, sizeof (buf2
)-1, "%s=%s", env_vars
[i
].name
,
2075 _putenv (strdup (buf2
));
2085 /* Rebuild system configuration to reflect invoking system. */
2086 Vsystem_configuration
= build_string (EMACS_CONFIGURATION
);
2088 /* Another special case: on NT, the PATH variable is actually named
2089 "Path" although cmd.exe (perhaps NT itself) arranges for
2090 environment variable lookup and setting to be case insensitive.
2091 However, Emacs assumes a fully case sensitive environment, so we
2092 need to change "Path" to "PATH" to match the expectations of
2093 various elisp packages. We do this by the sneaky method of
2094 modifying the string in the C runtime environ entry.
2096 The same applies to COMSPEC. */
2100 for (envp
= environ
; *envp
; envp
++)
2101 if (_strnicmp (*envp
, "PATH=", 5) == 0)
2102 memcpy (*envp
, "PATH=", 5);
2103 else if (_strnicmp (*envp
, "COMSPEC=", 8) == 0)
2104 memcpy (*envp
, "COMSPEC=", 8);
2107 /* Remember the initial working directory for getcwd. */
2108 /* FIXME: Do we need to resolve possible symlinks in startup_dir?
2109 Does it matter anywhere in Emacs? */
2110 if (!GetCurrentDirectory (MAXPATHLEN
, startup_dir
))
2114 static char modname
[MAX_PATH
];
2116 if (!GetModuleFileName (NULL
, modname
, MAX_PATH
))
2121 /* Determine if there is a middle mouse button, to allow parse_button
2122 to decide whether right mouse events should be mouse-2 or
2124 w32_num_mouse_buttons
= GetSystemMetrics (SM_CMOUSEBUTTONS
);
2129 /* Called from expand-file-name when default-directory is not a string. */
2132 emacs_root_dir (void)
2134 static char root_dir
[FILENAME_MAX
];
2137 p
= getenv ("emacs_dir");
2140 strcpy (root_dir
, p
);
2141 root_dir
[parse_root (root_dir
, NULL
)] = '\0';
2142 dostounix_filename (root_dir
);
2146 /* We don't have scripts to automatically determine the system configuration
2147 for Emacs before it's compiled, and we don't want to have to make the
2148 user enter it, so we define EMACS_CONFIGURATION to invoke this runtime
2152 get_emacs_configuration (void)
2154 char *arch
, *oem
, *os
;
2156 static char configuration_buffer
[32];
2158 /* Determine the processor type. */
2159 switch (get_processor_type ())
2162 #ifdef PROCESSOR_INTEL_386
2163 case PROCESSOR_INTEL_386
:
2164 case PROCESSOR_INTEL_486
:
2165 case PROCESSOR_INTEL_PENTIUM
:
2173 #ifdef PROCESSOR_AMD_X8664
2174 case PROCESSOR_AMD_X8664
:
2179 #ifdef PROCESSOR_MIPS_R2000
2180 case PROCESSOR_MIPS_R2000
:
2181 case PROCESSOR_MIPS_R3000
:
2182 case PROCESSOR_MIPS_R4000
:
2187 #ifdef PROCESSOR_ALPHA_21064
2188 case PROCESSOR_ALPHA_21064
:
2198 /* Use the OEM field to reflect the compiler/library combination. */
2200 #define COMPILER_NAME "msvc"
2203 #define COMPILER_NAME "mingw"
2205 #define COMPILER_NAME "unknown"
2208 oem
= COMPILER_NAME
;
2210 switch (osinfo_cache
.dwPlatformId
) {
2211 case VER_PLATFORM_WIN32_NT
:
2213 build_num
= osinfo_cache
.dwBuildNumber
;
2215 case VER_PLATFORM_WIN32_WINDOWS
:
2216 if (osinfo_cache
.dwMinorVersion
== 0) {
2221 build_num
= LOWORD (osinfo_cache
.dwBuildNumber
);
2223 case VER_PLATFORM_WIN32s
:
2224 /* Not supported, should not happen. */
2226 build_num
= LOWORD (osinfo_cache
.dwBuildNumber
);
2234 if (osinfo_cache
.dwPlatformId
== VER_PLATFORM_WIN32_NT
) {
2235 sprintf (configuration_buffer
, "%s-%s-%s%d.%d.%d", arch
, oem
, os
,
2236 get_w32_major_version (), get_w32_minor_version (), build_num
);
2238 sprintf (configuration_buffer
, "%s-%s-%s.%d", arch
, oem
, os
, build_num
);
2241 return configuration_buffer
;
2245 get_emacs_configuration_options (void)
2247 static char *options_buffer
;
2248 char cv
[32]; /* Enough for COMPILER_VERSION. */
2250 cv
, /* To be filled later. */
2254 #ifdef ENABLE_CHECKING
2255 " --enable-checking",
2257 /* configure.bat already sets USER_CFLAGS and USER_LDFLAGS
2258 with a starting space to save work here. */
2260 " --cflags", USER_CFLAGS
,
2263 " --ldflags", USER_LDFLAGS
,
2270 /* Work out the effective configure options for this build. */
2272 #define COMPILER_VERSION "--with-msvc (%d.%02d)", _MSC_VER / 100, _MSC_VER % 100
2275 #define COMPILER_VERSION "--with-gcc (%d.%d)", __GNUC__, __GNUC_MINOR__
2277 #define COMPILER_VERSION ""
2281 if (_snprintf (cv
, sizeof (cv
) - 1, COMPILER_VERSION
) < 0)
2282 return "Error: not enough space for compiler version";
2283 cv
[sizeof (cv
) - 1] = '\0';
2285 for (i
= 0; options
[i
]; i
++)
2286 size
+= strlen (options
[i
]);
2288 options_buffer
= xmalloc (size
+ 1);
2289 options_buffer
[0] = '\0';
2291 for (i
= 0; options
[i
]; i
++)
2292 strcat (options_buffer
, options
[i
]);
2294 return options_buffer
;
2298 #include <sys/timeb.h>
2300 /* Emulate gettimeofday (Ulrich Leodolter, 1/11/95). */
2302 gettimeofday (struct timeval
*tv
, struct timezone
*tz
)
2307 tv
->tv_sec
= tb
.time
;
2308 tv
->tv_usec
= tb
.millitm
* 1000L;
2309 /* Implementation note: _ftime sometimes doesn't update the dstflag
2310 according to the new timezone when the system timezone is
2311 changed. We could fix that by using GetSystemTime and
2312 GetTimeZoneInformation, but that doesn't seem necessary, since
2313 Emacs always calls gettimeofday with the 2nd argument NULL (see
2314 current_emacs_time). */
2317 tz
->tz_minuteswest
= tb
.timezone
; /* minutes west of Greenwich */
2318 tz
->tz_dsttime
= tb
.dstflag
; /* type of dst correction */
2322 /* Emulate fdutimens. */
2324 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2325 TIMESPEC[0] and TIMESPEC[1], respectively.
2326 FD must be either negative -- in which case it is ignored --
2327 or a file descriptor that is open on FILE.
2328 If FD is nonnegative, then FILE can be NULL, which means
2329 use just futimes instead of utimes.
2330 If TIMESPEC is null, FAIL.
2331 Return 0 on success, -1 (setting errno) on failure. */
2334 fdutimens (int fd
, char const *file
, struct timespec
const timespec
[2])
2343 if (fd
< 0 && !file
)
2348 ut
.actime
= timespec
[0].tv_sec
;
2349 ut
.modtime
= timespec
[1].tv_sec
;
2351 return _futime (fd
, &ut
);
2353 return _utime (file
, &ut
);
2357 /* ------------------------------------------------------------------------- */
2358 /* IO support and wrapper functions for the Windows API. */
2359 /* ------------------------------------------------------------------------- */
2361 /* Place a wrapper around the MSVC version of ctime. It returns NULL
2362 on network directories, so we handle that case here.
2363 (Ulrich Leodolter, 1/11/95). */
2365 sys_ctime (const time_t *t
)
2367 char *str
= (char *) ctime (t
);
2368 return (str
? str
: "Sun Jan 01 00:00:00 1970");
2371 /* Emulate sleep...we could have done this with a define, but that
2372 would necessitate including windows.h in the files that used it.
2373 This is much easier. */
2375 sys_sleep (int seconds
)
2377 Sleep (seconds
* 1000);
2380 /* Internal MSVC functions for low-level descriptor munging */
2381 extern int __cdecl
_set_osfhnd (int fd
, long h
);
2382 extern int __cdecl
_free_osfhnd (int fd
);
2384 /* parallel array of private info on file handles */
2385 filedesc fd_info
[ MAXDESC
];
2387 typedef struct volume_info_data
{
2388 struct volume_info_data
* next
;
2390 /* time when info was obtained */
2393 /* actual volume info */
2402 /* Global referenced by various functions. */
2403 static volume_info_data volume_info
;
2405 /* Vector to indicate which drives are local and fixed (for which cached
2406 data never expires). */
2407 static BOOL fixed_drives
[26];
2409 /* Consider cached volume information to be stale if older than 10s,
2410 at least for non-local drives. Info for fixed drives is never stale. */
2411 #define DRIVE_INDEX( c ) ( (c) <= 'Z' ? (c) - 'A' : (c) - 'a' )
2412 #define VOLINFO_STILL_VALID( root_dir, info ) \
2413 ( ( isalpha (root_dir[0]) && \
2414 fixed_drives[ DRIVE_INDEX (root_dir[0]) ] ) \
2415 || GetTickCount () - info->timestamp < 10000 )
2417 /* Cache support functions. */
2419 /* Simple linked list with linear search is sufficient. */
2420 static volume_info_data
*volume_cache
= NULL
;
2422 static volume_info_data
*
2423 lookup_volume_info (char * root_dir
)
2425 volume_info_data
* info
;
2427 for (info
= volume_cache
; info
; info
= info
->next
)
2428 if (xstrcasecmp (info
->root_dir
, root_dir
) == 0)
2434 add_volume_info (char * root_dir
, volume_info_data
* info
)
2436 info
->root_dir
= xstrdup (root_dir
);
2437 info
->next
= volume_cache
;
2438 volume_cache
= info
;
2442 /* Wrapper for GetVolumeInformation, which uses caching to avoid
2443 performance penalty (~2ms on 486 for local drives, 7.5ms for local
2444 cdrom drive, ~5-10ms or more for remote drives on LAN). */
2445 static volume_info_data
*
2446 GetCachedVolumeInformation (char * root_dir
)
2448 volume_info_data
* info
;
2449 char default_root
[ MAX_PATH
];
2451 /* NULL for root_dir means use root from current directory. */
2452 if (root_dir
== NULL
)
2454 if (GetCurrentDirectory (MAX_PATH
, default_root
) == 0)
2456 parse_root (default_root
, &root_dir
);
2458 root_dir
= default_root
;
2461 /* Local fixed drives can be cached permanently. Removable drives
2462 cannot be cached permanently, since the volume name and serial
2463 number (if nothing else) can change. Remote drives should be
2464 treated as if they are removable, since there is no sure way to
2465 tell whether they are or not. Also, the UNC association of drive
2466 letters mapped to remote volumes can be changed at any time (even
2467 by other processes) without notice.
2469 As a compromise, so we can benefit from caching info for remote
2470 volumes, we use a simple expiry mechanism to invalidate cache
2471 entries that are more than ten seconds old. */
2474 /* No point doing this, because WNetGetConnection is even slower than
2475 GetVolumeInformation, consistently taking ~50ms on a 486 (FWIW,
2476 GetDriveType is about the only call of this type which does not
2477 involve network access, and so is extremely quick). */
2479 /* Map drive letter to UNC if remote. */
2480 if (isalpha (root_dir
[0]) && !fixed
[DRIVE_INDEX (root_dir
[0])])
2482 char remote_name
[ 256 ];
2483 char drive
[3] = { root_dir
[0], ':' };
2485 if (WNetGetConnection (drive
, remote_name
, sizeof (remote_name
))
2487 /* do something */ ;
2491 info
= lookup_volume_info (root_dir
);
2493 if (info
== NULL
|| ! VOLINFO_STILL_VALID (root_dir
, info
))
2501 /* Info is not cached, or is stale. */
2502 if (!GetVolumeInformation (root_dir
,
2503 name
, sizeof (name
),
2507 type
, sizeof (type
)))
2510 /* Cache the volume information for future use, overwriting existing
2511 entry if present. */
2514 info
= xmalloc (sizeof (volume_info_data
));
2515 add_volume_info (root_dir
, info
);
2523 info
->name
= xstrdup (name
);
2524 info
->serialnum
= serialnum
;
2525 info
->maxcomp
= maxcomp
;
2526 info
->flags
= flags
;
2527 info
->type
= xstrdup (type
);
2528 info
->timestamp
= GetTickCount ();
2534 /* Get information on the volume where NAME is held; set path pointer to
2535 start of pathname in NAME (past UNC header\volume header if present),
2536 if pPath is non-NULL.
2538 Note: if NAME includes symlinks, the information is for the volume
2539 of the symlink, not of its target. That's because, even though
2540 GetVolumeInformation returns information about the symlink target
2541 of its argument, we only pass the root directory to
2542 GetVolumeInformation, not the full NAME. */
2544 get_volume_info (const char * name
, const char ** pPath
)
2546 char temp
[MAX_PATH
];
2547 char *rootname
= NULL
; /* default to current volume */
2548 volume_info_data
* info
;
2553 /* Find the root name of the volume if given. */
2554 if (isalpha (name
[0]) && name
[1] == ':')
2562 else if (IS_DIRECTORY_SEP (name
[0]) && IS_DIRECTORY_SEP (name
[1]))
2569 if (IS_DIRECTORY_SEP (*name
) && --slashes
== 0)
2582 info
= GetCachedVolumeInformation (rootname
);
2585 /* Set global referenced by other functions. */
2586 volume_info
= *info
;
2592 /* Determine if volume is FAT format (ie. only supports short 8.3
2593 names); also set path pointer to start of pathname in name, if
2594 pPath is non-NULL. */
2596 is_fat_volume (const char * name
, const char ** pPath
)
2598 if (get_volume_info (name
, pPath
))
2599 return (volume_info
.maxcomp
== 12);
2603 /* Map filename to a valid 8.3 name if necessary.
2604 The result is a pointer to a static buffer, so CAVEAT EMPTOR! */
2606 map_w32_filename (const char * name
, const char ** pPath
)
2608 static char shortname
[MAX_PATH
];
2609 char * str
= shortname
;
2612 const char * save_name
= name
;
2614 if (strlen (name
) >= MAX_PATH
)
2616 /* Return a filename which will cause callers to fail. */
2617 strcpy (shortname
, "?");
2621 if (is_fat_volume (name
, (const char **)&path
)) /* truncate to 8.3 */
2623 register int left
= 8; /* maximum number of chars in part */
2624 register int extn
= 0; /* extension added? */
2625 register int dots
= 2; /* maximum number of dots allowed */
2628 *str
++ = *name
++; /* skip past UNC header */
2630 while ((c
= *name
++))
2637 *str
++ = (c
== ':' ? ':' : '\\');
2638 extn
= 0; /* reset extension flags */
2639 dots
= 2; /* max 2 dots */
2640 left
= 8; /* max length 8 for main part */
2645 /* Convert path components of the form .xxx to _xxx,
2646 but leave . and .. as they are. This allows .emacs
2647 to be read as _emacs, for example. */
2651 IS_DIRECTORY_SEP (*name
))
2666 extn
= 1; /* we've got an extension */
2667 left
= 3; /* 3 chars in extension */
2671 /* any embedded dots after the first are converted to _ */
2676 case '#': /* don't lose these, they're important */
2678 str
[-1] = c
; /* replace last character of part */
2683 *str
++ = tolower (c
); /* map to lower case (looks nicer) */
2685 dots
= 0; /* started a path component */
2694 strcpy (shortname
, name
);
2695 unixtodos_filename (shortname
);
2699 *pPath
= shortname
+ (path
- save_name
);
2705 is_exec (const char * name
)
2707 char * p
= strrchr (name
, '.');
2710 && (xstrcasecmp (p
, ".exe") == 0 ||
2711 xstrcasecmp (p
, ".com") == 0 ||
2712 xstrcasecmp (p
, ".bat") == 0 ||
2713 xstrcasecmp (p
, ".cmd") == 0));
2716 /* Emulate the Unix directory procedures opendir, closedir,
2717 and readdir. We can't use the procedures supplied in sysdep.c,
2718 so we provide them here. */
2720 struct dirent dir_static
; /* simulated directory contents */
2721 static HANDLE dir_find_handle
= INVALID_HANDLE_VALUE
;
2722 static int dir_is_fat
;
2723 static char dir_pathname
[MAXPATHLEN
+1];
2724 static WIN32_FIND_DATA dir_find_data
;
2726 /* Support shares on a network resource as subdirectories of a read-only
2728 static HANDLE wnet_enum_handle
= INVALID_HANDLE_VALUE
;
2729 static HANDLE
open_unc_volume (const char *);
2730 static char *read_unc_volume (HANDLE
, char *, int);
2731 static void close_unc_volume (HANDLE
);
2734 opendir (char *filename
)
2738 /* Opening is done by FindFirstFile. However, a read is inherent to
2739 this operation, so we defer the open until read time. */
2741 if (dir_find_handle
!= INVALID_HANDLE_VALUE
)
2743 if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
2746 /* Note: We don't support traversal of UNC volumes via symlinks.
2747 Doing so would mean punishing 99.99% of use cases by resolving
2748 all the possible symlinks in FILENAME, recursively. */
2749 if (is_unc_volume (filename
))
2751 wnet_enum_handle
= open_unc_volume (filename
);
2752 if (wnet_enum_handle
== INVALID_HANDLE_VALUE
)
2756 if (!(dirp
= (DIR *) malloc (sizeof (DIR))))
2763 strncpy (dir_pathname
, map_w32_filename (filename
, NULL
), MAXPATHLEN
);
2764 dir_pathname
[MAXPATHLEN
] = '\0';
2765 /* Note: We don't support symlinks to file names on FAT volumes.
2766 Doing so would mean punishing 99.99% of use cases by resolving
2767 all the possible symlinks in FILENAME, recursively. */
2768 dir_is_fat
= is_fat_volume (filename
, NULL
);
2774 closedir (DIR *dirp
)
2776 /* If we have a find-handle open, close it. */
2777 if (dir_find_handle
!= INVALID_HANDLE_VALUE
)
2779 FindClose (dir_find_handle
);
2780 dir_find_handle
= INVALID_HANDLE_VALUE
;
2782 else if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
2784 close_unc_volume (wnet_enum_handle
);
2785 wnet_enum_handle
= INVALID_HANDLE_VALUE
;
2787 xfree ((char *) dirp
);
2793 int downcase
= !NILP (Vw32_downcase_file_names
);
2795 if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
2797 if (!read_unc_volume (wnet_enum_handle
,
2798 dir_find_data
.cFileName
,
2802 /* If we aren't dir_finding, do a find-first, otherwise do a find-next. */
2803 else if (dir_find_handle
== INVALID_HANDLE_VALUE
)
2805 char filename
[MAXNAMLEN
+ 3];
2808 strcpy (filename
, dir_pathname
);
2809 ln
= strlen (filename
) - 1;
2810 if (!IS_DIRECTORY_SEP (filename
[ln
]))
2811 strcat (filename
, "\\");
2812 strcat (filename
, "*");
2814 /* Note: No need to resolve symlinks in FILENAME, because
2815 FindFirst opens the directory that is the target of a
2817 dir_find_handle
= FindFirstFile (filename
, &dir_find_data
);
2819 if (dir_find_handle
== INVALID_HANDLE_VALUE
)
2824 if (!FindNextFile (dir_find_handle
, &dir_find_data
))
2828 /* Emacs never uses this value, so don't bother making it match
2829 value returned by stat(). */
2830 dir_static
.d_ino
= 1;
2832 strcpy (dir_static
.d_name
, dir_find_data
.cFileName
);
2834 /* If the file name in cFileName[] includes `?' characters, it means
2835 the original file name used characters that cannot be represented
2836 by the current ANSI codepage. To avoid total lossage, retrieve
2837 the short 8+3 alias of the long file name. */
2838 if (_mbspbrk (dir_static
.d_name
, "?"))
2840 strcpy (dir_static
.d_name
, dir_find_data
.cAlternateFileName
);
2841 downcase
= 1; /* 8+3 aliases are returned in all caps */
2843 dir_static
.d_namlen
= strlen (dir_static
.d_name
);
2844 dir_static
.d_reclen
= sizeof (struct dirent
) - MAXNAMLEN
+ 3 +
2845 dir_static
.d_namlen
- dir_static
.d_namlen
% 4;
2847 /* If the file name in cFileName[] includes `?' characters, it means
2848 the original file name used characters that cannot be represented
2849 by the current ANSI codepage. To avoid total lossage, retrieve
2850 the short 8+3 alias of the long file name. */
2851 if (_mbspbrk (dir_find_data
.cFileName
, "?"))
2853 strcpy (dir_static
.d_name
, dir_find_data
.cAlternateFileName
);
2854 /* 8+3 aliases are returned in all caps, which could break
2855 various alists that look at filenames' extensions. */
2859 strcpy (dir_static
.d_name
, dir_find_data
.cFileName
);
2860 dir_static
.d_namlen
= strlen (dir_static
.d_name
);
2862 _strlwr (dir_static
.d_name
);
2866 for (p
= dir_static
.d_name
; *p
; p
++)
2867 if (*p
>= 'a' && *p
<= 'z')
2870 _strlwr (dir_static
.d_name
);
2877 open_unc_volume (const char *path
)
2883 nr
.dwScope
= RESOURCE_GLOBALNET
;
2884 nr
.dwType
= RESOURCETYPE_DISK
;
2885 nr
.dwDisplayType
= RESOURCEDISPLAYTYPE_SERVER
;
2886 nr
.dwUsage
= RESOURCEUSAGE_CONTAINER
;
2887 nr
.lpLocalName
= NULL
;
2888 nr
.lpRemoteName
= (LPSTR
)map_w32_filename (path
, NULL
);
2889 nr
.lpComment
= NULL
;
2890 nr
.lpProvider
= NULL
;
2892 result
= WNetOpenEnum (RESOURCE_GLOBALNET
, RESOURCETYPE_DISK
,
2893 RESOURCEUSAGE_CONNECTABLE
, &nr
, &henum
);
2895 if (result
== NO_ERROR
)
2898 return INVALID_HANDLE_VALUE
;
2902 read_unc_volume (HANDLE henum
, char *readbuf
, int size
)
2906 DWORD bufsize
= 512;
2911 buffer
= alloca (bufsize
);
2912 result
= WNetEnumResource (henum
, &count
, buffer
, &bufsize
);
2913 if (result
!= NO_ERROR
)
2916 /* WNetEnumResource returns \\resource\share...skip forward to "share". */
2917 ptr
= ((LPNETRESOURCE
) buffer
)->lpRemoteName
;
2919 while (*ptr
&& !IS_DIRECTORY_SEP (*ptr
)) ptr
++;
2922 strncpy (readbuf
, ptr
, size
);
2927 close_unc_volume (HANDLE henum
)
2929 if (henum
!= INVALID_HANDLE_VALUE
)
2930 WNetCloseEnum (henum
);
2934 unc_volume_file_attributes (const char *path
)
2939 henum
= open_unc_volume (path
);
2940 if (henum
== INVALID_HANDLE_VALUE
)
2943 attrs
= FILE_ATTRIBUTE_READONLY
| FILE_ATTRIBUTE_DIRECTORY
;
2945 close_unc_volume (henum
);
2950 /* Ensure a network connection is authenticated. */
2952 logon_network_drive (const char *path
)
2954 NETRESOURCE resource
;
2955 char share
[MAX_PATH
];
2960 if (IS_DIRECTORY_SEP (path
[0]) && IS_DIRECTORY_SEP (path
[1]))
2961 drvtype
= DRIVE_REMOTE
;
2962 else if (path
[0] == '\0' || path
[1] != ':')
2963 drvtype
= GetDriveType (NULL
);
2970 drvtype
= GetDriveType (drive
);
2973 /* Only logon to networked drives. */
2974 if (drvtype
!= DRIVE_REMOTE
)
2978 strncpy (share
, path
, MAX_PATH
);
2979 /* Truncate to just server and share name. */
2980 for (i
= 2; i
< MAX_PATH
; i
++)
2982 if (IS_DIRECTORY_SEP (share
[i
]) && ++n_slashes
> 3)
2989 resource
.dwType
= RESOURCETYPE_DISK
;
2990 resource
.lpLocalName
= NULL
;
2991 resource
.lpRemoteName
= share
;
2992 resource
.lpProvider
= NULL
;
2994 WNetAddConnection2 (&resource
, NULL
, NULL
, CONNECT_INTERACTIVE
);
2997 /* Emulate faccessat(2). */
2999 faccessat (int dirfd
, const char * path
, int mode
, int flags
)
3003 if (dirfd
!= AT_FDCWD
3004 && !(IS_DIRECTORY_SEP (path
[0])
3005 || IS_DEVICE_SEP (path
[1])))
3011 /* MSVCRT implementation of 'access' doesn't recognize D_OK, and its
3012 newer versions blow up when passed D_OK. */
3013 path
= map_w32_filename (path
, NULL
);
3014 /* If the last element of PATH is a symlink, we need to resolve it
3015 to get the attributes of its target file. Note: any symlinks in
3016 PATH elements other than the last one are transparently resolved
3017 by GetFileAttributes below. */
3018 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) != 0
3019 && (flags
& AT_SYMLINK_NOFOLLOW
) == 0)
3020 path
= chase_symlinks (path
);
3022 if ((attributes
= GetFileAttributes (path
)) == -1)
3024 DWORD w32err
= GetLastError ();
3028 case ERROR_INVALID_NAME
:
3029 case ERROR_BAD_PATHNAME
:
3030 if (is_unc_volume (path
))
3032 attributes
= unc_volume_file_attributes (path
);
3033 if (attributes
== -1)
3041 case ERROR_FILE_NOT_FOUND
:
3042 case ERROR_BAD_NETPATH
:
3051 if ((mode
& X_OK
) != 0
3052 && !(is_exec (path
) || (attributes
& FILE_ATTRIBUTE_DIRECTORY
) != 0))
3057 if ((mode
& W_OK
) != 0 && (attributes
& FILE_ATTRIBUTE_READONLY
) != 0)
3062 if ((mode
& D_OK
) != 0 && (attributes
& FILE_ATTRIBUTE_DIRECTORY
) == 0)
3070 /* Shadow some MSVC runtime functions to map requests for long filenames
3071 to reasonable short names if necessary. This was originally added to
3072 permit running Emacs on NT 3.1 on a FAT partition, which doesn't support
3076 sys_chdir (const char * path
)
3078 return _chdir (map_w32_filename (path
, NULL
));
3082 sys_chmod (const char * path
, int mode
)
3084 path
= chase_symlinks (map_w32_filename (path
, NULL
));
3085 return _chmod (path
, mode
);
3089 sys_chown (const char *path
, uid_t owner
, gid_t group
)
3091 if (sys_chmod (path
, S_IREAD
) == -1) /* check if file exists */
3097 sys_creat (const char * path
, int mode
)
3099 return _creat (map_w32_filename (path
, NULL
), mode
);
3103 sys_fopen (const char * path
, const char * mode
)
3107 const char * mode_save
= mode
;
3109 /* Force all file handles to be non-inheritable. This is necessary to
3110 ensure child processes don't unwittingly inherit handles that might
3111 prevent future file access. */
3115 else if (mode
[0] == 'w' || mode
[0] == 'a')
3116 oflag
= O_WRONLY
| O_CREAT
| O_TRUNC
;
3120 /* Only do simplistic option parsing. */
3124 oflag
&= ~(O_RDONLY
| O_WRONLY
);
3127 else if (mode
[0] == 'b')
3132 else if (mode
[0] == 't')
3139 fd
= _open (map_w32_filename (path
, NULL
), oflag
| _O_NOINHERIT
, 0644);
3143 return _fdopen (fd
, mode_save
);
3146 /* This only works on NTFS volumes, but is useful to have. */
3148 sys_link (const char * old
, const char * new)
3152 char oldname
[MAX_PATH
], newname
[MAX_PATH
];
3154 if (old
== NULL
|| new == NULL
)
3160 strcpy (oldname
, map_w32_filename (old
, NULL
));
3161 strcpy (newname
, map_w32_filename (new, NULL
));
3163 fileh
= CreateFile (oldname
, 0, 0, NULL
, OPEN_EXISTING
,
3164 FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
3165 if (fileh
!= INVALID_HANDLE_VALUE
)
3169 /* Confusingly, the "alternate" stream name field does not apply
3170 when restoring a hard link, and instead contains the actual
3171 stream data for the link (ie. the name of the link to create).
3172 The WIN32_STREAM_ID structure before the cStreamName field is
3173 the stream header, which is then immediately followed by the
3177 WIN32_STREAM_ID wid
;
3178 WCHAR wbuffer
[MAX_PATH
]; /* extra space for link name */
3181 wlen
= MultiByteToWideChar (CP_ACP
, MB_PRECOMPOSED
, newname
, -1,
3182 data
.wid
.cStreamName
, MAX_PATH
);
3185 LPVOID context
= NULL
;
3188 data
.wid
.dwStreamId
= BACKUP_LINK
;
3189 data
.wid
.dwStreamAttributes
= 0;
3190 data
.wid
.Size
.LowPart
= wlen
* sizeof (WCHAR
);
3191 data
.wid
.Size
.HighPart
= 0;
3192 data
.wid
.dwStreamNameSize
= 0;
3194 if (BackupWrite (fileh
, (LPBYTE
)&data
,
3195 offsetof (WIN32_STREAM_ID
, cStreamName
)
3196 + data
.wid
.Size
.LowPart
,
3197 &wbytes
, FALSE
, FALSE
, &context
)
3198 && BackupWrite (fileh
, NULL
, 0, &wbytes
, TRUE
, FALSE
, &context
))
3205 /* Should try mapping GetLastError to errno; for now just
3206 indicate a general error (eg. links not supported). */
3207 errno
= EINVAL
; // perhaps EMLINK?
3211 CloseHandle (fileh
);
3220 sys_mkdir (const char * path
)
3222 return _mkdir (map_w32_filename (path
, NULL
));
3225 /* Because of long name mapping issues, we need to implement this
3226 ourselves. Also, MSVC's _mktemp returns NULL when it can't generate
3227 a unique name, instead of setting the input template to an empty
3230 Standard algorithm seems to be use pid or tid with a letter on the
3231 front (in place of the 6 X's) and cycle through the letters to find a
3232 unique name. We extend that to allow any reasonable character as the
3233 first of the 6 X's. */
3235 sys_mktemp (char * template)
3239 unsigned uid
= GetCurrentThreadId ();
3240 static char first_char
[] = "abcdefghijklmnopqrstuvwyz0123456789!%-_@#";
3242 if (template == NULL
)
3244 p
= template + strlen (template);
3246 /* replace up to the last 5 X's with uid in decimal */
3247 while (--p
>= template && p
[0] == 'X' && --i
>= 0)
3249 p
[0] = '0' + uid
% 10;
3253 if (i
< 0 && p
[0] == 'X')
3258 int save_errno
= errno
;
3259 p
[0] = first_char
[i
];
3260 if (faccessat (AT_FDCWD
, template, F_OK
, AT_EACCESS
) < 0)
3266 while (++i
< sizeof (first_char
));
3269 /* Template is badly formed or else we can't generate a unique name,
3270 so return empty string */
3276 sys_open (const char * path
, int oflag
, int mode
)
3278 const char* mpath
= map_w32_filename (path
, NULL
);
3279 /* Try to open file without _O_CREAT, to be able to write to hidden
3280 and system files. Force all file handles to be
3282 int res
= _open (mpath
, (oflag
& ~_O_CREAT
) | _O_NOINHERIT
, mode
);
3285 return _open (mpath
, oflag
| _O_NOINHERIT
, mode
);
3289 sys_rename (const char * oldname
, const char * newname
)
3292 char temp
[MAX_PATH
];
3296 /* MoveFile on Windows 95 doesn't correctly change the short file name
3297 alias in a number of circumstances (it is not easy to predict when
3298 just by looking at oldname and newname, unfortunately). In these
3299 cases, renaming through a temporary name avoids the problem.
3301 A second problem on Windows 95 is that renaming through a temp name when
3302 newname is uppercase fails (the final long name ends up in
3303 lowercase, although the short alias might be uppercase) UNLESS the
3304 long temp name is not 8.3.
3306 So, on Windows 95 we always rename through a temp name, and we make sure
3307 the temp name has a long extension to ensure correct renaming. */
3309 strcpy (temp
, map_w32_filename (oldname
, NULL
));
3311 /* volume_info is set indirectly by map_w32_filename. */
3312 oldname_dev
= volume_info
.serialnum
;
3314 if (os_subtype
== OS_9X
)
3320 oldname
= map_w32_filename (oldname
, NULL
);
3321 if ((o
= strrchr (oldname
, '\\')))
3324 o
= (char *) oldname
;
3326 if ((p
= strrchr (temp
, '\\')))
3333 /* Force temp name to require a manufactured 8.3 alias - this
3334 seems to make the second rename work properly. */
3335 sprintf (p
, "_.%s.%u", o
, i
);
3337 result
= rename (oldname
, temp
);
3339 /* This loop must surely terminate! */
3340 while (result
< 0 && errno
== EEXIST
);
3345 /* Emulate Unix behavior - newname is deleted if it already exists
3346 (at least if it is a file; don't do this for directories).
3348 Since we mustn't do this if we are just changing the case of the
3349 file name (we would end up deleting the file we are trying to
3350 rename!), we let rename detect if the destination file already
3351 exists - that way we avoid the possible pitfalls of trying to
3352 determine ourselves whether two names really refer to the same
3353 file, which is not always possible in the general case. (Consider
3354 all the permutations of shared or subst'd drives, etc.) */
3356 newname
= map_w32_filename (newname
, NULL
);
3358 /* volume_info is set indirectly by map_w32_filename. */
3359 newname_dev
= volume_info
.serialnum
;
3361 result
= rename (temp
, newname
);
3365 DWORD w32err
= GetLastError ();
3368 && newname_dev
!= oldname_dev
)
3370 /* The implementation of `rename' on Windows does not return
3371 errno = EXDEV when you are moving a directory to a
3372 different storage device (ex. logical disk). It returns
3373 EACCES instead. So here we handle such situations and
3377 if ((attributes
= GetFileAttributes (temp
)) != -1
3378 && (attributes
& FILE_ATTRIBUTE_DIRECTORY
))
3381 else if (errno
== EEXIST
)
3383 if (_chmod (newname
, 0666) != 0)
3385 if (_unlink (newname
) != 0)
3387 result
= rename (temp
, newname
);
3389 else if (w32err
== ERROR_PRIVILEGE_NOT_HELD
3390 && is_symlink (temp
))
3392 /* This is Windows prohibiting the user from creating a
3393 symlink in another place, since that requires
3403 sys_rmdir (const char * path
)
3405 return _rmdir (map_w32_filename (path
, NULL
));
3409 sys_unlink (const char * path
)
3411 path
= map_w32_filename (path
, NULL
);
3413 /* On Unix, unlink works without write permission. */
3414 _chmod (path
, 0666);
3415 return _unlink (path
);
3418 static FILETIME utc_base_ft
;
3419 static ULONGLONG utc_base
; /* In 100ns units */
3420 static int init
= 0;
3422 #define FILETIME_TO_U64(result, ft) \
3424 ULARGE_INTEGER uiTemp; \
3425 uiTemp.LowPart = (ft).dwLowDateTime; \
3426 uiTemp.HighPart = (ft).dwHighDateTime; \
3427 result = uiTemp.QuadPart; \
3431 initialize_utc_base (void)
3433 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
3442 st
.wMilliseconds
= 0;
3444 SystemTimeToFileTime (&st
, &utc_base_ft
);
3445 FILETIME_TO_U64 (utc_base
, utc_base_ft
);
3449 convert_time (FILETIME ft
)
3455 initialize_utc_base ();
3459 if (CompareFileTime (&ft
, &utc_base_ft
) < 0)
3462 FILETIME_TO_U64 (tmp
, ft
);
3463 return (time_t) ((tmp
- utc_base
) / 10000000L);
3467 convert_from_time_t (time_t time
, FILETIME
* pft
)
3473 initialize_utc_base ();
3477 /* time in 100ns units since 1-Jan-1601 */
3478 tmp
.QuadPart
= (ULONGLONG
) time
* 10000000L + utc_base
;
3479 pft
->dwHighDateTime
= tmp
.HighPart
;
3480 pft
->dwLowDateTime
= tmp
.LowPart
;
3484 /* No reason to keep this; faking inode values either by hashing or even
3485 using the file index from GetInformationByHandle, is not perfect and
3486 so by default Emacs doesn't use the inode values on Windows.
3487 Instead, we now determine file-truename correctly (except for
3488 possible drive aliasing etc). */
3490 /* Modified version of "PJW" algorithm (see the "Dragon" compiler book). */
3492 hashval (const unsigned char * str
)
3497 h
= (h
<< 4) + *str
++;
3503 /* Return the hash value of the canonical pathname, excluding the
3504 drive/UNC header, to get a hopefully unique inode number. */
3506 generate_inode_val (const char * name
)
3508 char fullname
[ MAX_PATH
];
3512 /* Get the truly canonical filename, if it exists. (Note: this
3513 doesn't resolve aliasing due to subst commands, or recognize hard
3515 if (!w32_get_long_filename ((char *)name
, fullname
, MAX_PATH
))
3518 parse_root (fullname
, &p
);
3519 /* Normal W32 filesystems are still case insensitive. */
3526 static PSECURITY_DESCRIPTOR
3527 get_file_security_desc_by_handle (HANDLE h
)
3529 PSECURITY_DESCRIPTOR psd
= NULL
;
3531 SECURITY_INFORMATION si
= OWNER_SECURITY_INFORMATION
3532 | GROUP_SECURITY_INFORMATION
/* | DACL_SECURITY_INFORMATION */ ;
3534 err
= get_security_info (h
, SE_FILE_OBJECT
, si
,
3535 NULL
, NULL
, NULL
, NULL
, &psd
);
3536 if (err
!= ERROR_SUCCESS
)
3542 static PSECURITY_DESCRIPTOR
3543 get_file_security_desc_by_name (const char *fname
)
3545 PSECURITY_DESCRIPTOR psd
= NULL
;
3547 SECURITY_INFORMATION si
= OWNER_SECURITY_INFORMATION
3548 | GROUP_SECURITY_INFORMATION
/* | DACL_SECURITY_INFORMATION */ ;
3550 if (!get_file_security (fname
, si
, psd
, 0, &sd_len
))
3552 err
= GetLastError ();
3553 if (err
!= ERROR_INSUFFICIENT_BUFFER
)
3557 psd
= xmalloc (sd_len
);
3558 if (!get_file_security (fname
, si
, psd
, sd_len
, &sd_len
))
3570 unsigned n_subauthorities
;
3572 /* Use the last sub-authority value of the RID, the relative
3573 portion of the SID, as user/group ID. */
3574 n_subauthorities
= *get_sid_sub_authority_count (sid
);
3575 if (n_subauthorities
< 1)
3576 return 0; /* the "World" RID */
3577 return *get_sid_sub_authority (sid
, n_subauthorities
- 1);
3580 /* Caching SID and account values for faster lokup. */
3583 # define FLEXIBLE_ARRAY_MEMBER
3585 # define FLEXIBLE_ARRAY_MEMBER 1
3590 struct w32_id
*next
;
3592 unsigned char sid
[FLEXIBLE_ARRAY_MEMBER
];
3595 static struct w32_id
*w32_idlist
;
3598 w32_cached_id (PSID sid
, unsigned *id
, char *name
)
3600 struct w32_id
*tail
, *found
;
3602 for (found
= NULL
, tail
= w32_idlist
; tail
; tail
= tail
->next
)
3604 if (equal_sid ((PSID
)tail
->sid
, sid
))
3613 strcpy (name
, found
->name
);
3621 w32_add_to_cache (PSID sid
, unsigned id
, char *name
)
3624 struct w32_id
*new_entry
;
3626 /* We don't want to leave behind stale cache from when Emacs was
3630 sid_len
= get_length_sid (sid
);
3631 new_entry
= xmalloc (offsetof (struct w32_id
, sid
) + sid_len
);
3634 new_entry
->rid
= id
;
3635 strcpy (new_entry
->name
, name
);
3636 copy_sid (sid_len
, (PSID
)new_entry
->sid
, sid
);
3637 new_entry
->next
= w32_idlist
;
3638 w32_idlist
= new_entry
;
3647 get_name_and_id (PSECURITY_DESCRIPTOR psd
, const char *fname
,
3648 unsigned *id
, char *nm
, int what
)
3651 char machine
[MAX_COMPUTERNAME_LENGTH
+1];
3653 SID_NAME_USE ignore
;
3655 DWORD name_len
= sizeof (name
);
3657 DWORD domain_len
= sizeof (domain
);
3663 result
= get_security_descriptor_owner (psd
, &sid
, &dflt
);
3664 else if (what
== GID
)
3665 result
= get_security_descriptor_group (psd
, &sid
, &dflt
);
3669 if (!result
|| !is_valid_sid (sid
))
3671 else if (!w32_cached_id (sid
, id
, nm
))
3673 /* If FNAME is a UNC, we need to lookup account on the
3674 specified machine. */
3675 if (IS_DIRECTORY_SEP (fname
[0]) && IS_DIRECTORY_SEP (fname
[1])
3676 && fname
[2] != '\0')
3681 for (s
= fname
+ 2, p
= machine
;
3682 *s
&& !IS_DIRECTORY_SEP (*s
); s
++, p
++)
3688 if (!lookup_account_sid (mp
, sid
, name
, &name_len
,
3689 domain
, &domain_len
, &ignore
)
3690 || name_len
> UNLEN
+1)
3694 *id
= get_rid (sid
);
3696 w32_add_to_cache (sid
, *id
, name
);
3703 get_file_owner_and_group (PSECURITY_DESCRIPTOR psd
,
3707 int dflt_usr
= 0, dflt_grp
= 0;
3716 if (get_name_and_id (psd
, fname
, &st
->st_uid
, st
->st_uname
, UID
))
3718 if (get_name_and_id (psd
, fname
, &st
->st_gid
, st
->st_gname
, GID
))
3721 /* Consider files to belong to current user/group, if we cannot get
3722 more accurate information. */
3725 st
->st_uid
= dflt_passwd
.pw_uid
;
3726 strcpy (st
->st_uname
, dflt_passwd
.pw_name
);
3730 st
->st_gid
= dflt_passwd
.pw_gid
;
3731 strcpy (st
->st_gname
, dflt_group
.gr_name
);
3735 /* Return non-zero if NAME is a potentially slow filesystem. */
3737 is_slow_fs (const char *name
)
3742 if (IS_DIRECTORY_SEP (name
[0]) && IS_DIRECTORY_SEP (name
[1]))
3743 devtype
= DRIVE_REMOTE
; /* assume UNC name is remote */
3744 else if (!(strlen (name
) >= 2 && IS_DEVICE_SEP (name
[1])))
3745 devtype
= GetDriveType (NULL
); /* use root of current drive */
3748 /* GetDriveType needs the root directory of the drive. */
3749 strncpy (drive_root
, name
, 2);
3750 drive_root
[2] = '\\';
3751 drive_root
[3] = '\0';
3752 devtype
= GetDriveType (drive_root
);
3754 return !(devtype
== DRIVE_FIXED
|| devtype
== DRIVE_RAMDISK
);
3757 /* If this is non-zero, the caller wants accurate information about
3758 file's owner and group, which could be expensive to get. */
3759 int w32_stat_get_owner_group
;
3761 /* MSVC stat function can't cope with UNC names and has other bugs, so
3762 replace it with our own. This also allows us to calculate consistent
3763 inode values and owner/group without hacks in the main Emacs code. */
3766 stat_worker (const char * path
, struct stat
* buf
, int follow_symlinks
)
3768 char *name
, *save_name
, *r
;
3769 WIN32_FIND_DATA wfd
;
3771 unsigned __int64 fake_inode
= 0;
3774 int rootdir
= FALSE
;
3775 PSECURITY_DESCRIPTOR psd
= NULL
;
3776 int is_a_symlink
= 0;
3777 DWORD file_flags
= FILE_FLAG_BACKUP_SEMANTICS
;
3778 DWORD access_rights
= 0;
3779 DWORD fattrs
= 0, serialnum
= 0, fs_high
= 0, fs_low
= 0, nlinks
= 1;
3780 FILETIME ctime
, atime
, wtime
;
3782 if (path
== NULL
|| buf
== NULL
)
3788 save_name
= name
= (char *) map_w32_filename (path
, &path
);
3789 /* Must be valid filename, no wild cards or other invalid
3790 characters. We use _mbspbrk to support multibyte strings that
3791 might look to strpbrk as if they included literal *, ?, and other
3792 characters mentioned below that are disallowed by Windows
3794 if (_mbspbrk (name
, "*?|<>\""))
3800 /* Remove trailing directory separator, unless name is the root
3801 directory of a drive or UNC volume in which case ensure there
3802 is a trailing separator. */
3803 len
= strlen (name
);
3804 name
= strcpy (alloca (len
+ 2), name
);
3806 /* Avoid a somewhat costly call to is_symlink if the filesystem
3807 doesn't support symlinks. */
3808 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) != 0)
3809 is_a_symlink
= is_symlink (name
);
3811 /* Plan A: Open the file and get all the necessary information via
3812 the resulting handle. This solves several issues in one blow:
3814 . retrieves attributes for the target of a symlink, if needed
3815 . gets attributes of root directories and symlinks pointing to
3816 root directories, thus avoiding the need for special-casing
3817 these and detecting them by examining the file-name format
3818 . retrieves more accurate attributes (e.g., non-zero size for
3819 some directories, esp. directories that are junction points)
3820 . correctly resolves "c:/..", "/.." and similar file names
3821 . avoids run-time penalties for 99% of use cases
3823 Plan A is always tried first, unless the user asked not to (but
3824 if the file is a symlink and we need to follow links, we try Plan
3825 A even if the user asked not to).
3827 If Plan A fails, we go to Plan B (below), where various
3828 potentially expensive techniques must be used to handle "special"
3829 files such as UNC volumes etc. */
3830 if (!(NILP (Vw32_get_true_file_attributes
)
3831 || (EQ (Vw32_get_true_file_attributes
, Qlocal
) && is_slow_fs (name
)))
3832 /* Following symlinks requires getting the info by handle. */
3833 || (is_a_symlink
&& follow_symlinks
))
3835 BY_HANDLE_FILE_INFORMATION info
;
3837 if (is_a_symlink
&& !follow_symlinks
)
3838 file_flags
|= FILE_FLAG_OPEN_REPARSE_POINT
;
3839 /* READ_CONTROL access rights are required to get security info
3840 by handle. But if the OS doesn't support security in the
3841 first place, we don't need to try. */
3842 if (is_windows_9x () != TRUE
)
3843 access_rights
|= READ_CONTROL
;
3845 fh
= CreateFile (name
, access_rights
, 0, NULL
, OPEN_EXISTING
,
3847 /* If CreateFile fails with READ_CONTROL, try again with zero as
3849 if (fh
== INVALID_HANDLE_VALUE
&& access_rights
)
3850 fh
= CreateFile (name
, 0, 0, NULL
, OPEN_EXISTING
,
3852 if (fh
== INVALID_HANDLE_VALUE
)
3853 goto no_true_file_attributes
;
3855 /* This is more accurate in terms of getting the correct number
3856 of links, but is quite slow (it is noticeable when Emacs is
3857 making a list of file name completions). */
3858 if (GetFileInformationByHandle (fh
, &info
))
3860 nlinks
= info
.nNumberOfLinks
;
3861 /* Might as well use file index to fake inode values, but this
3862 is not guaranteed to be unique unless we keep a handle open
3863 all the time (even then there are situations where it is
3864 not unique). Reputedly, there are at most 48 bits of info
3865 (on NTFS, presumably less on FAT). */
3866 fake_inode
= info
.nFileIndexHigh
;
3868 fake_inode
+= info
.nFileIndexLow
;
3869 serialnum
= info
.dwVolumeSerialNumber
;
3870 fs_high
= info
.nFileSizeHigh
;
3871 fs_low
= info
.nFileSizeLow
;
3872 ctime
= info
.ftCreationTime
;
3873 atime
= info
.ftLastAccessTime
;
3874 wtime
= info
.ftLastWriteTime
;
3875 fattrs
= info
.dwFileAttributes
;
3879 /* We don't go to Plan B here, because it's not clear that
3880 it's a good idea. The only known use case where
3881 CreateFile succeeds, but GetFileInformationByHandle fails
3882 (with ERROR_INVALID_FUNCTION) is for character devices
3883 such as NUL, PRN, etc. For these, switching to Plan B is
3884 a net loss, because we lose the character device
3885 attribute returned by GetFileType below (FindFirstFile
3886 doesn't set that bit in the attributes), and the other
3887 fields don't make sense for character devices anyway.
3888 Emacs doesn't really care for non-file entities in the
3889 context of l?stat, so neither do we. */
3891 /* w32err is assigned so one could put a breakpoint here and
3892 examine its value, when GetFileInformationByHandle
3894 DWORD w32err
= GetLastError ();
3898 case ERROR_FILE_NOT_FOUND
: /* can this ever happen? */
3904 /* Test for a symlink before testing for a directory, since
3905 symlinks to directories have the directory bit set, but we
3906 don't want them to appear as directories. */
3907 if (is_a_symlink
&& !follow_symlinks
)
3908 buf
->st_mode
= S_IFLNK
;
3909 else if (fattrs
& FILE_ATTRIBUTE_DIRECTORY
)
3910 buf
->st_mode
= S_IFDIR
;
3913 DWORD ftype
= GetFileType (fh
);
3917 case FILE_TYPE_DISK
:
3918 buf
->st_mode
= S_IFREG
;
3920 case FILE_TYPE_PIPE
:
3921 buf
->st_mode
= S_IFIFO
;
3923 case FILE_TYPE_CHAR
:
3924 case FILE_TYPE_UNKNOWN
:
3926 buf
->st_mode
= S_IFCHR
;
3929 /* We produce the fallback owner and group data, based on the
3930 current user that runs Emacs, in the following cases:
3932 . caller didn't request owner and group info
3933 . this is Windows 9X
3934 . getting security by handle failed, and we need to produce
3935 information for the target of a symlink (this is better
3936 than producing a potentially misleading info about the
3939 If getting security by handle fails, and we don't need to
3940 resolve symlinks, we try getting security by name. */
3941 if (!w32_stat_get_owner_group
|| is_windows_9x () == TRUE
)
3942 get_file_owner_and_group (NULL
, name
, buf
);
3945 psd
= get_file_security_desc_by_handle (fh
);
3948 get_file_owner_and_group (psd
, name
, buf
);
3951 else if (!(is_a_symlink
&& follow_symlinks
))
3953 psd
= get_file_security_desc_by_name (name
);
3954 get_file_owner_and_group (psd
, name
, buf
);
3958 get_file_owner_and_group (NULL
, name
, buf
);
3964 no_true_file_attributes
:
3965 /* Plan B: Either getting a handle on the file failed, or the
3966 caller explicitly asked us to not bother making this
3967 information more accurate.
3969 Implementation note: In Plan B, we never bother to resolve
3970 symlinks, even if we got here because we tried Plan A and
3971 failed. That's because, even if the caller asked for extra
3972 precision by setting Vw32_get_true_file_attributes to t,
3973 resolving symlinks requires acquiring a file handle to the
3974 symlink, which we already know will fail. And if the user
3975 did not ask for extra precision, resolving symlinks will fly
3976 in the face of that request, since the user then wants the
3977 lightweight version of the code. */
3978 rootdir
= (path
>= save_name
+ len
- 1
3979 && (IS_DIRECTORY_SEP (*path
) || *path
== 0));
3981 /* If name is "c:/.." or "/.." then stat "c:/" or "/". */
3982 r
= IS_DEVICE_SEP (name
[1]) ? &name
[2] : name
;
3983 if (IS_DIRECTORY_SEP (r
[0])
3984 && r
[1] == '.' && r
[2] == '.' && r
[3] == '\0')
3987 /* Note: If NAME is a symlink to the root of a UNC volume
3988 (i.e. "\\SERVER"), we will not detect that here, and we will
3989 return data about the symlink as result of FindFirst below.
3990 This is unfortunate, but that marginal use case does not
3991 justify a call to chase_symlinks which would impose a penalty
3992 on all the other use cases. (We get here for symlinks to
3993 roots of UNC volumes because CreateFile above fails for them,
3994 unlike with symlinks to root directories X:\ of drives.) */
3995 if (is_unc_volume (name
))
3997 fattrs
= unc_volume_file_attributes (name
);
4001 ctime
= atime
= wtime
= utc_base_ft
;
4005 if (!IS_DIRECTORY_SEP (name
[len
-1]))
4006 strcat (name
, "\\");
4007 if (GetDriveType (name
) < 2)
4013 fattrs
= FILE_ATTRIBUTE_DIRECTORY
;
4014 ctime
= atime
= wtime
= utc_base_ft
;
4018 if (IS_DIRECTORY_SEP (name
[len
-1]))
4021 /* (This is hacky, but helps when doing file completions on
4022 network drives.) Optimize by using information available from
4023 active readdir if possible. */
4024 len
= strlen (dir_pathname
);
4025 if (IS_DIRECTORY_SEP (dir_pathname
[len
-1]))
4027 if (dir_find_handle
!= INVALID_HANDLE_VALUE
4028 && !(is_a_symlink
&& follow_symlinks
)
4029 && strnicmp (save_name
, dir_pathname
, len
) == 0
4030 && IS_DIRECTORY_SEP (name
[len
])
4031 && xstrcasecmp (name
+ len
+ 1, dir_static
.d_name
) == 0)
4033 /* This was the last entry returned by readdir. */
4034 wfd
= dir_find_data
;
4038 logon_network_drive (name
);
4040 fh
= FindFirstFile (name
, &wfd
);
4041 if (fh
== INVALID_HANDLE_VALUE
)
4048 /* Note: if NAME is a symlink, the information we get from
4049 FindFirstFile is for the symlink, not its target. */
4050 fattrs
= wfd
.dwFileAttributes
;
4051 ctime
= wfd
.ftCreationTime
;
4052 atime
= wfd
.ftLastAccessTime
;
4053 wtime
= wfd
.ftLastWriteTime
;
4054 fs_high
= wfd
.nFileSizeHigh
;
4055 fs_low
= wfd
.nFileSizeLow
;
4058 serialnum
= volume_info
.serialnum
;
4060 if (is_a_symlink
&& !follow_symlinks
)
4061 buf
->st_mode
= S_IFLNK
;
4062 else if (fattrs
& FILE_ATTRIBUTE_DIRECTORY
)
4063 buf
->st_mode
= S_IFDIR
;
4065 buf
->st_mode
= S_IFREG
;
4067 get_file_owner_and_group (NULL
, name
, buf
);
4071 /* Not sure if there is any point in this. */
4072 if (!NILP (Vw32_generate_fake_inodes
))
4073 fake_inode
= generate_inode_val (name
);
4074 else if (fake_inode
== 0)
4076 /* For want of something better, try to make everything unique. */
4077 static DWORD gen_num
= 0;
4078 fake_inode
= ++gen_num
;
4082 buf
->st_ino
= fake_inode
;
4084 buf
->st_dev
= serialnum
;
4085 buf
->st_rdev
= serialnum
;
4087 buf
->st_size
= fs_high
;
4088 buf
->st_size
<<= 32;
4089 buf
->st_size
+= fs_low
;
4090 buf
->st_nlink
= nlinks
;
4092 /* Convert timestamps to Unix format. */
4093 buf
->st_mtime
= convert_time (wtime
);
4094 buf
->st_atime
= convert_time (atime
);
4095 if (buf
->st_atime
== 0) buf
->st_atime
= buf
->st_mtime
;
4096 buf
->st_ctime
= convert_time (ctime
);
4097 if (buf
->st_ctime
== 0) buf
->st_ctime
= buf
->st_mtime
;
4099 /* determine rwx permissions */
4100 if (is_a_symlink
&& !follow_symlinks
)
4101 permission
= S_IREAD
| S_IWRITE
| S_IEXEC
; /* Posix expectations */
4104 if (fattrs
& FILE_ATTRIBUTE_READONLY
)
4105 permission
= S_IREAD
;
4107 permission
= S_IREAD
| S_IWRITE
;
4109 if (fattrs
& FILE_ATTRIBUTE_DIRECTORY
)
4110 permission
|= S_IEXEC
;
4111 else if (is_exec (name
))
4112 permission
|= S_IEXEC
;
4115 buf
->st_mode
|= permission
| (permission
>> 3) | (permission
>> 6);
4121 stat (const char * path
, struct stat
* buf
)
4123 return stat_worker (path
, buf
, 1);
4127 lstat (const char * path
, struct stat
* buf
)
4129 return stat_worker (path
, buf
, 0);
4132 /* Provide fstat and utime as well as stat for consistent handling of
4135 fstat (int desc
, struct stat
* buf
)
4137 HANDLE fh
= (HANDLE
) _get_osfhandle (desc
);
4138 BY_HANDLE_FILE_INFORMATION info
;
4139 unsigned __int64 fake_inode
;
4142 switch (GetFileType (fh
) & ~FILE_TYPE_REMOTE
)
4144 case FILE_TYPE_DISK
:
4145 buf
->st_mode
= S_IFREG
;
4146 if (!GetFileInformationByHandle (fh
, &info
))
4152 case FILE_TYPE_PIPE
:
4153 buf
->st_mode
= S_IFIFO
;
4155 case FILE_TYPE_CHAR
:
4156 case FILE_TYPE_UNKNOWN
:
4158 buf
->st_mode
= S_IFCHR
;
4160 memset (&info
, 0, sizeof (info
));
4161 info
.dwFileAttributes
= 0;
4162 info
.ftCreationTime
= utc_base_ft
;
4163 info
.ftLastAccessTime
= utc_base_ft
;
4164 info
.ftLastWriteTime
= utc_base_ft
;
4167 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
4168 buf
->st_mode
= S_IFDIR
;
4170 buf
->st_nlink
= info
.nNumberOfLinks
;
4171 /* Might as well use file index to fake inode values, but this
4172 is not guaranteed to be unique unless we keep a handle open
4173 all the time (even then there are situations where it is
4174 not unique). Reputedly, there are at most 48 bits of info
4175 (on NTFS, presumably less on FAT). */
4176 fake_inode
= info
.nFileIndexHigh
;
4178 fake_inode
+= info
.nFileIndexLow
;
4180 /* MSVC defines _ino_t to be short; other libc's might not. */
4181 if (sizeof (buf
->st_ino
) == 2)
4182 buf
->st_ino
= fake_inode
^ (fake_inode
>> 16);
4184 buf
->st_ino
= fake_inode
;
4186 /* Consider files to belong to current user.
4187 FIXME: this should use GetSecurityInfo API, but it is only
4188 available for _WIN32_WINNT >= 0x501. */
4189 buf
->st_uid
= dflt_passwd
.pw_uid
;
4190 buf
->st_gid
= dflt_passwd
.pw_gid
;
4191 strcpy (buf
->st_uname
, dflt_passwd
.pw_name
);
4192 strcpy (buf
->st_gname
, dflt_group
.gr_name
);
4194 buf
->st_dev
= info
.dwVolumeSerialNumber
;
4195 buf
->st_rdev
= info
.dwVolumeSerialNumber
;
4197 buf
->st_size
= info
.nFileSizeHigh
;
4198 buf
->st_size
<<= 32;
4199 buf
->st_size
+= info
.nFileSizeLow
;
4201 /* Convert timestamps to Unix format. */
4202 buf
->st_mtime
= convert_time (info
.ftLastWriteTime
);
4203 buf
->st_atime
= convert_time (info
.ftLastAccessTime
);
4204 if (buf
->st_atime
== 0) buf
->st_atime
= buf
->st_mtime
;
4205 buf
->st_ctime
= convert_time (info
.ftCreationTime
);
4206 if (buf
->st_ctime
== 0) buf
->st_ctime
= buf
->st_mtime
;
4208 /* determine rwx permissions */
4209 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
)
4210 permission
= S_IREAD
;
4212 permission
= S_IREAD
| S_IWRITE
;
4214 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
4215 permission
|= S_IEXEC
;
4218 #if 0 /* no way of knowing the filename */
4219 char * p
= strrchr (name
, '.');
4221 (xstrcasecmp (p
, ".exe") == 0 ||
4222 xstrcasecmp (p
, ".com") == 0 ||
4223 xstrcasecmp (p
, ".bat") == 0 ||
4224 xstrcasecmp (p
, ".cmd") == 0))
4225 permission
|= S_IEXEC
;
4229 buf
->st_mode
|= permission
| (permission
>> 3) | (permission
>> 6);
4235 utime (const char *name
, struct utimbuf
*times
)
4237 struct utimbuf deftime
;
4244 deftime
.modtime
= deftime
.actime
= time (NULL
);
4248 /* Need write access to set times. */
4249 fh
= CreateFile (name
, FILE_WRITE_ATTRIBUTES
,
4250 /* If NAME specifies a directory, FILE_SHARE_DELETE
4251 allows other processes to delete files inside it,
4252 while we have the directory open. */
4253 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
4254 0, OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
4255 if (fh
!= INVALID_HANDLE_VALUE
)
4257 convert_from_time_t (times
->actime
, &atime
);
4258 convert_from_time_t (times
->modtime
, &mtime
);
4259 if (!SetFileTime (fh
, NULL
, &atime
, &mtime
))
4276 /* Symlink-related functions. */
4277 #ifndef SYMBOLIC_LINK_FLAG_DIRECTORY
4278 #define SYMBOLIC_LINK_FLAG_DIRECTORY 0x1
4282 symlink (char const *filename
, char const *linkname
)
4284 char linkfn
[MAX_PATH
], *tgtfn
;
4286 int dir_access
, filename_ends_in_slash
;
4288 /* Diagnostics follows Posix as much as possible. */
4289 if (filename
== NULL
|| linkname
== NULL
)
4299 if (strlen (filename
) > MAX_PATH
|| strlen (linkname
) > MAX_PATH
)
4301 errno
= ENAMETOOLONG
;
4305 strcpy (linkfn
, map_w32_filename (linkname
, NULL
));
4306 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) == 0)
4312 /* Note: since empty FILENAME was already rejected, we can safely
4313 refer to FILENAME[1]. */
4314 if (!(IS_DIRECTORY_SEP (filename
[0]) || IS_DEVICE_SEP (filename
[1])))
4316 /* Non-absolute FILENAME is understood as being relative to
4317 LINKNAME's directory. We need to prepend that directory to
4318 FILENAME to get correct results from faccessat below, since
4319 otherwise it will interpret FILENAME relative to the
4320 directory where the Emacs process runs. Note that
4321 make-symbolic-link always makes sure LINKNAME is a fully
4322 expanded file name. */
4324 char *p
= linkfn
+ strlen (linkfn
);
4326 while (p
> linkfn
&& !IS_ANY_SEP (p
[-1]))
4329 strncpy (tem
, linkfn
, p
- linkfn
);
4330 tem
[p
- linkfn
] = '\0';
4331 strcat (tem
, filename
);
4332 dir_access
= faccessat (AT_FDCWD
, tem
, D_OK
, AT_EACCESS
);
4335 dir_access
= faccessat (AT_FDCWD
, filename
, D_OK
, AT_EACCESS
);
4337 /* Since Windows distinguishes between symlinks to directories and
4338 to files, we provide a kludgy feature: if FILENAME doesn't
4339 exist, but ends in a slash, we create a symlink to directory. If
4340 FILENAME exists and is a directory, we always create a symlink to
4342 filename_ends_in_slash
= IS_DIRECTORY_SEP (filename
[strlen (filename
) - 1]);
4343 if (dir_access
== 0 || filename_ends_in_slash
)
4344 flags
= SYMBOLIC_LINK_FLAG_DIRECTORY
;
4346 tgtfn
= (char *)map_w32_filename (filename
, NULL
);
4347 if (filename_ends_in_slash
)
4348 tgtfn
[strlen (tgtfn
) - 1] = '\0';
4351 if (!create_symbolic_link (linkfn
, tgtfn
, flags
))
4353 /* ENOSYS is set by create_symbolic_link, when it detects that
4354 the OS doesn't support the CreateSymbolicLink API. */
4355 if (errno
!= ENOSYS
)
4357 DWORD w32err
= GetLastError ();
4361 /* ERROR_SUCCESS is sometimes returned when LINKFN and
4362 TGTFN point to the same file name, go figure. */
4364 case ERROR_FILE_EXISTS
:
4367 case ERROR_ACCESS_DENIED
:
4370 case ERROR_FILE_NOT_FOUND
:
4371 case ERROR_PATH_NOT_FOUND
:
4372 case ERROR_BAD_NETPATH
:
4373 case ERROR_INVALID_REPARSE_DATA
:
4376 case ERROR_DIRECTORY
:
4379 case ERROR_PRIVILEGE_NOT_HELD
:
4380 case ERROR_NOT_ALL_ASSIGNED
:
4383 case ERROR_DISK_FULL
:
4396 /* A quick inexpensive test of whether FILENAME identifies a file that
4397 is a symlink. Returns non-zero if it is, zero otherwise. FILENAME
4398 must already be in the normalized form returned by
4401 Note: for repeated operations on many files, it is best to test
4402 whether the underlying volume actually supports symlinks, by
4403 testing the FILE_SUPPORTS_REPARSE_POINTS bit in volume's flags, and
4404 avoid the call to this function if it doesn't. That's because the
4405 call to GetFileAttributes takes a non-negligible time, especially
4406 on non-local or removable filesystems. See stat_worker for an
4407 example of how to do that. */
4409 is_symlink (const char *filename
)
4412 WIN32_FIND_DATA wfd
;
4415 attrs
= GetFileAttributes (filename
);
4418 DWORD w32err
= GetLastError ();
4422 case ERROR_BAD_NETPATH
: /* network share, can't be a symlink */
4424 case ERROR_ACCESS_DENIED
:
4427 case ERROR_FILE_NOT_FOUND
:
4428 case ERROR_PATH_NOT_FOUND
:
4435 if ((attrs
& FILE_ATTRIBUTE_REPARSE_POINT
) == 0)
4437 logon_network_drive (filename
);
4438 fh
= FindFirstFile (filename
, &wfd
);
4439 if (fh
== INVALID_HANDLE_VALUE
)
4442 return (wfd
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) != 0
4443 && (wfd
.dwReserved0
& IO_REPARSE_TAG_SYMLINK
) == IO_REPARSE_TAG_SYMLINK
;
4446 /* If NAME identifies a symbolic link, copy into BUF the file name of
4447 the symlink's target. Copy at most BUF_SIZE bytes, and do NOT
4448 null-terminate the target name, even if it fits. Return the number
4449 of bytes copied, or -1 if NAME is not a symlink or any error was
4450 encountered while resolving it. The file name copied into BUF is
4451 encoded in the current ANSI codepage. */
4453 readlink (const char *name
, char *buf
, size_t buf_size
)
4456 TOKEN_PRIVILEGES privs
;
4457 int restore_privs
= 0;
4472 path
= map_w32_filename (name
, NULL
);
4474 if (strlen (path
) > MAX_PATH
)
4476 errno
= ENAMETOOLONG
;
4481 if (is_windows_9x () == TRUE
4482 || (volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) == 0
4483 || !is_symlink (path
))
4486 errno
= EINVAL
; /* not a symlink */
4490 /* Done with simple tests, now we're in for some _real_ work. */
4491 if (enable_privilege (SE_BACKUP_NAME
, TRUE
, &privs
))
4493 /* Implementation note: From here and onward, don't return early,
4494 since that will fail to restore the original set of privileges of
4495 the calling thread. */
4497 retval
= -1; /* not too optimistic, are we? */
4499 /* Note: In the next call to CreateFile, we use zero as the 2nd
4500 argument because, when the symlink is a hidden/system file,
4501 e.g. 'C:\Users\All Users', GENERIC_READ fails with
4502 ERROR_ACCESS_DENIED. Zero seems to work just fine, both for file
4503 and directory symlinks. */
4504 sh
= CreateFile (path
, 0, 0, NULL
, OPEN_EXISTING
,
4505 FILE_FLAG_OPEN_REPARSE_POINT
| FILE_FLAG_BACKUP_SEMANTICS
,
4507 if (sh
!= INVALID_HANDLE_VALUE
)
4509 BYTE reparse_buf
[MAXIMUM_REPARSE_DATA_BUFFER_SIZE
];
4510 REPARSE_DATA_BUFFER
*reparse_data
= (REPARSE_DATA_BUFFER
*)&reparse_buf
[0];
4513 if (!DeviceIoControl (sh
, FSCTL_GET_REPARSE_POINT
, NULL
, 0,
4514 reparse_buf
, MAXIMUM_REPARSE_DATA_BUFFER_SIZE
,
4517 else if (reparse_data
->ReparseTag
!= IO_REPARSE_TAG_SYMLINK
)
4521 /* Copy the link target name, in wide characters, from
4522 reparse_data, then convert it to multibyte encoding in
4523 the current locale's codepage. */
4525 BYTE lname
[MAX_PATH
];
4528 reparse_data
->SymbolicLinkReparseBuffer
.PrintNameLength
;
4530 reparse_data
->SymbolicLinkReparseBuffer
.PathBuffer
4531 + reparse_data
->SymbolicLinkReparseBuffer
.PrintNameOffset
/sizeof(WCHAR
);
4533 /* According to MSDN, PrintNameLength does not include the
4534 terminating null character. */
4535 lwname
= alloca ((lwname_len
+ 1) * sizeof(WCHAR
));
4536 memcpy (lwname
, lwname_src
, lwname_len
);
4537 lwname
[lwname_len
/sizeof(WCHAR
)] = 0; /* null-terminate */
4539 /* FIXME: Should we use the current file-name coding system
4540 instead of the fixed value of the ANSI codepage? */
4541 lname_len
= WideCharToMultiByte (w32_ansi_code_page
, 0, lwname
, -1,
4542 lname
, MAX_PATH
, NULL
, NULL
);
4545 /* WideCharToMultiByte failed. */
4546 DWORD w32err1
= GetLastError ();
4550 case ERROR_INSUFFICIENT_BUFFER
:
4551 errno
= ENAMETOOLONG
;
4553 case ERROR_INVALID_PARAMETER
:
4556 case ERROR_NO_UNICODE_TRANSLATION
:
4566 size_t size_to_copy
= buf_size
;
4568 BYTE
*pend
= p
+ lname_len
;
4570 /* Normalize like dostounix_filename does, but we don't
4571 want to assume that lname is null-terminated. */
4572 if (*p
&& p
[1] == ':' && *p
>= 'A' && *p
<= 'Z')
4580 /* Testing for null-terminated LNAME is paranoia:
4581 WideCharToMultiByte should always return a
4582 null-terminated string when its 4th argument is -1
4583 and its 3rd argument is null-terminated (which they
4585 if (lname
[lname_len
- 1] == '\0')
4587 if (lname_len
<= buf_size
)
4588 size_to_copy
= lname_len
;
4589 strncpy (buf
, lname
, size_to_copy
);
4591 retval
= size_to_copy
;
4598 /* CreateFile failed. */
4599 DWORD w32err2
= GetLastError ();
4603 case ERROR_FILE_NOT_FOUND
:
4604 case ERROR_PATH_NOT_FOUND
:
4607 case ERROR_ACCESS_DENIED
:
4608 case ERROR_TOO_MANY_OPEN_FILES
:
4618 restore_privilege (&privs
);
4625 /* If FILE is a symlink, return its target (stored in a static
4626 buffer); otherwise return FILE.
4628 This function repeatedly resolves symlinks in the last component of
4629 a chain of symlink file names, as in foo -> bar -> baz -> ...,
4630 until it arrives at a file whose last component is not a symlink,
4631 or some error occurs. It returns the target of the last
4632 successfully resolved symlink in the chain. If it succeeds to
4633 resolve even a single symlink, the value returned is an absolute
4634 file name with backslashes (result of GetFullPathName). By
4635 contrast, if the original FILE is returned, it is unaltered.
4637 Note: This function can set errno even if it succeeds.
4639 Implementation note: we only resolve the last portion ("basename")
4640 of the argument FILE and of each following file in the chain,
4641 disregarding any possible symlinks in its leading directories.
4642 This is because Windows system calls and library functions
4643 transparently resolve symlinks in leading directories and return
4644 correct information, as long as the basename is not a symlink. */
4646 chase_symlinks (const char *file
)
4648 static char target
[MAX_PATH
];
4649 char link
[MAX_PATH
];
4650 ssize_t res
, link_len
;
4653 if (is_windows_9x () == TRUE
|| !is_symlink (file
))
4654 return (char *)file
;
4656 if ((link_len
= GetFullPathName (file
, MAX_PATH
, link
, NULL
)) == 0)
4657 return (char *)file
;
4662 /* Remove trailing slashes, as we want to resolve the last
4663 non-trivial part of the link name. */
4664 while (link_len
> 3 && IS_DIRECTORY_SEP (link
[link_len
-1]))
4665 link
[link_len
--] = '\0';
4667 res
= readlink (link
, target
, MAX_PATH
);
4671 if (!(IS_DEVICE_SEP (target
[1])
4672 || (IS_DIRECTORY_SEP (target
[0]) && IS_DIRECTORY_SEP (target
[1]))))
4674 /* Target is relative. Append it to the directory part of
4675 the symlink, then copy the result back to target. */
4676 char *p
= link
+ link_len
;
4678 while (p
> link
&& !IS_ANY_SEP (p
[-1]))
4681 strcpy (target
, link
);
4683 /* Resolve any "." and ".." to get a fully-qualified file name
4685 link_len
= GetFullPathName (target
, MAX_PATH
, link
, NULL
);
4687 } while (res
> 0 && link_len
> 0 && ++loop_count
<= 100);
4689 if (loop_count
> 100)
4692 if (target
[0] == '\0') /* not a single call to readlink succeeded */
4693 return (char *)file
;
4698 /* Posix ACL emulation. */
4701 acl_valid (acl_t acl
)
4703 return is_valid_security_descriptor ((PSECURITY_DESCRIPTOR
)acl
) ? 0 : -1;
4707 acl_to_text (acl_t acl
, ssize_t
*size
)
4710 SECURITY_INFORMATION flags
=
4711 OWNER_SECURITY_INFORMATION
|
4712 GROUP_SECURITY_INFORMATION
|
4713 DACL_SECURITY_INFORMATION
;
4714 char *retval
= NULL
;
4720 if (convert_sd_to_sddl ((PSECURITY_DESCRIPTOR
)acl
, SDDL_REVISION_1
, flags
, &str_acl
, &local_size
))
4723 /* We don't want to mix heaps, so we duplicate the string in our
4724 heap and free the one allocated by the API. */
4725 retval
= xstrdup (str_acl
);
4728 LocalFree (str_acl
);
4730 else if (errno
!= ENOTSUP
)
4737 acl_from_text (const char *acl_str
)
4739 PSECURITY_DESCRIPTOR psd
, retval
= NULL
;
4745 if (convert_sddl_to_sd (acl_str
, SDDL_REVISION_1
, &psd
, &sd_size
))
4748 retval
= xmalloc (sd_size
);
4749 memcpy (retval
, psd
, sd_size
);
4752 else if (errno
!= ENOTSUP
)
4759 acl_free (void *ptr
)
4766 acl_get_file (const char *fname
, acl_type_t type
)
4768 PSECURITY_DESCRIPTOR psd
= NULL
;
4769 const char *filename
;
4771 if (type
== ACL_TYPE_ACCESS
)
4774 SECURITY_INFORMATION si
=
4775 OWNER_SECURITY_INFORMATION
|
4776 GROUP_SECURITY_INFORMATION
|
4777 DACL_SECURITY_INFORMATION
;
4780 filename
= map_w32_filename (fname
, NULL
);
4781 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) != 0)
4782 fname
= chase_symlinks (filename
);
4787 if (!get_file_security (fname
, si
, psd
, 0, &sd_len
)
4788 && errno
!= ENOTSUP
)
4790 err
= GetLastError ();
4791 if (err
== ERROR_INSUFFICIENT_BUFFER
)
4793 psd
= xmalloc (sd_len
);
4794 if (!get_file_security (fname
, si
, psd
, sd_len
, &sd_len
))
4801 else if (err
== ERROR_FILE_NOT_FOUND
4802 || err
== ERROR_PATH_NOT_FOUND
)
4810 else if (type
!= ACL_TYPE_DEFAULT
)
4817 acl_set_file (const char *fname
, acl_type_t type
, acl_t acl
)
4819 TOKEN_PRIVILEGES old1
, old2
;
4822 int st
= 0, retval
= -1;
4823 SECURITY_INFORMATION flags
= 0;
4829 const char *filename
;
4831 if (acl_valid (acl
) != 0
4832 || (type
!= ACL_TYPE_DEFAULT
&& type
!= ACL_TYPE_ACCESS
))
4838 if (type
== ACL_TYPE_DEFAULT
)
4844 filename
= map_w32_filename (fname
, NULL
);
4845 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) != 0)
4846 fname
= chase_symlinks (filename
);
4850 if (get_security_descriptor_owner ((PSECURITY_DESCRIPTOR
)acl
, &psid
, &dflt
)
4852 flags
|= OWNER_SECURITY_INFORMATION
;
4853 if (get_security_descriptor_group ((PSECURITY_DESCRIPTOR
)acl
, &psid
, &dflt
)
4855 flags
|= GROUP_SECURITY_INFORMATION
;
4856 if (get_security_descriptor_dacl ((PSECURITY_DESCRIPTOR
)acl
, &dacl_present
,
4859 flags
|= DACL_SECURITY_INFORMATION
;
4863 /* According to KB-245153, setting the owner will succeed if either:
4864 (1) the caller is the user who will be the new owner, and has the
4865 SE_TAKE_OWNERSHIP privilege, or
4866 (2) the caller has the SE_RESTORE privilege, in which case she can
4867 set any valid user or group as the owner
4869 We request below both SE_TAKE_OWNERSHIP and SE_RESTORE
4870 privileges, and disregard any failures in obtaining them. If
4871 these privileges cannot be obtained, and do not already exist in
4872 the calling thread's security token, this function could fail
4874 if (enable_privilege (SE_TAKE_OWNERSHIP_NAME
, TRUE
, &old1
))
4876 if (enable_privilege (SE_RESTORE_NAME
, TRUE
, &old2
))
4881 set_file_security ((char *)fname
, flags
, (PSECURITY_DESCRIPTOR
)acl
);
4882 err
= GetLastError ();
4886 restore_privilege (&old2
);
4887 restore_privilege (&old1
);
4891 if (errno
== ENOTSUP
)
4893 else if (err
== ERROR_SUCCESS
)
4898 else if (err
== ERROR_INVALID_OWNER
)
4900 else if (err
== ERROR_FILE_NOT_FOUND
|| err
== ERROR_PATH_NOT_FOUND
)
4907 /* MS-Windows version of careadlinkat (cf. ../lib/careadlinkat.c). We
4908 have a fixed max size for file names, so we don't need the kind of
4909 alloc/malloc/realloc dance the gnulib version does. We also don't
4910 support FD-relative symlinks. */
4912 careadlinkat (int fd
, char const *filename
,
4913 char *buffer
, size_t buffer_size
,
4914 struct allocator
const *alloc
,
4915 ssize_t (*preadlinkat
) (int, char const *, char *, size_t))
4917 char linkname
[MAX_PATH
];
4926 link_size
= preadlinkat (fd
, filename
, linkname
, sizeof(linkname
));
4930 char *retval
= buffer
;
4932 linkname
[link_size
++] = '\0';
4933 if (link_size
> buffer_size
)
4934 retval
= (char *)(alloc
? alloc
->allocate
: xmalloc
) (link_size
);
4936 memcpy (retval
, linkname
, link_size
);
4944 careadlinkatcwd (int fd
, char const *filename
, char *buffer
,
4948 return readlink (filename
, buffer
, buffer_size
);
4952 /* Support for browsing other processes and their attributes. See
4953 process.c for the Lisp bindings. */
4955 /* Helper wrapper functions. */
4957 static HANDLE WINAPI
4958 create_toolhelp32_snapshot (DWORD Flags
, DWORD Ignored
)
4960 static CreateToolhelp32Snapshot_Proc s_pfn_Create_Toolhelp32_Snapshot
= NULL
;
4962 if (g_b_init_create_toolhelp32_snapshot
== 0)
4964 g_b_init_create_toolhelp32_snapshot
= 1;
4965 s_pfn_Create_Toolhelp32_Snapshot
= (CreateToolhelp32Snapshot_Proc
)
4966 GetProcAddress (GetModuleHandle ("kernel32.dll"),
4967 "CreateToolhelp32Snapshot");
4969 if (s_pfn_Create_Toolhelp32_Snapshot
== NULL
)
4971 return INVALID_HANDLE_VALUE
;
4973 return (s_pfn_Create_Toolhelp32_Snapshot (Flags
, Ignored
));
4977 process32_first (HANDLE hSnapshot
, LPPROCESSENTRY32 lppe
)
4979 static Process32First_Proc s_pfn_Process32_First
= NULL
;
4981 if (g_b_init_process32_first
== 0)
4983 g_b_init_process32_first
= 1;
4984 s_pfn_Process32_First
= (Process32First_Proc
)
4985 GetProcAddress (GetModuleHandle ("kernel32.dll"),
4988 if (s_pfn_Process32_First
== NULL
)
4992 return (s_pfn_Process32_First (hSnapshot
, lppe
));
4996 process32_next (HANDLE hSnapshot
, LPPROCESSENTRY32 lppe
)
4998 static Process32Next_Proc s_pfn_Process32_Next
= NULL
;
5000 if (g_b_init_process32_next
== 0)
5002 g_b_init_process32_next
= 1;
5003 s_pfn_Process32_Next
= (Process32Next_Proc
)
5004 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5007 if (s_pfn_Process32_Next
== NULL
)
5011 return (s_pfn_Process32_Next (hSnapshot
, lppe
));
5015 open_thread_token (HANDLE ThreadHandle
,
5016 DWORD DesiredAccess
,
5018 PHANDLE TokenHandle
)
5020 static OpenThreadToken_Proc s_pfn_Open_Thread_Token
= NULL
;
5021 HMODULE hm_advapi32
= NULL
;
5022 if (is_windows_9x () == TRUE
)
5024 SetLastError (ERROR_NOT_SUPPORTED
);
5027 if (g_b_init_open_thread_token
== 0)
5029 g_b_init_open_thread_token
= 1;
5030 hm_advapi32
= LoadLibrary ("Advapi32.dll");
5031 s_pfn_Open_Thread_Token
=
5032 (OpenThreadToken_Proc
) GetProcAddress (hm_advapi32
, "OpenThreadToken");
5034 if (s_pfn_Open_Thread_Token
== NULL
)
5036 SetLastError (ERROR_NOT_SUPPORTED
);
5040 s_pfn_Open_Thread_Token (
5049 impersonate_self (SECURITY_IMPERSONATION_LEVEL ImpersonationLevel
)
5051 static ImpersonateSelf_Proc s_pfn_Impersonate_Self
= NULL
;
5052 HMODULE hm_advapi32
= NULL
;
5053 if (is_windows_9x () == TRUE
)
5057 if (g_b_init_impersonate_self
== 0)
5059 g_b_init_impersonate_self
= 1;
5060 hm_advapi32
= LoadLibrary ("Advapi32.dll");
5061 s_pfn_Impersonate_Self
=
5062 (ImpersonateSelf_Proc
) GetProcAddress (hm_advapi32
, "ImpersonateSelf");
5064 if (s_pfn_Impersonate_Self
== NULL
)
5068 return s_pfn_Impersonate_Self (ImpersonationLevel
);
5072 revert_to_self (void)
5074 static RevertToSelf_Proc s_pfn_Revert_To_Self
= NULL
;
5075 HMODULE hm_advapi32
= NULL
;
5076 if (is_windows_9x () == TRUE
)
5080 if (g_b_init_revert_to_self
== 0)
5082 g_b_init_revert_to_self
= 1;
5083 hm_advapi32
= LoadLibrary ("Advapi32.dll");
5084 s_pfn_Revert_To_Self
=
5085 (RevertToSelf_Proc
) GetProcAddress (hm_advapi32
, "RevertToSelf");
5087 if (s_pfn_Revert_To_Self
== NULL
)
5091 return s_pfn_Revert_To_Self ();
5095 get_process_memory_info (HANDLE h_proc
,
5096 PPROCESS_MEMORY_COUNTERS mem_counters
,
5099 static GetProcessMemoryInfo_Proc s_pfn_Get_Process_Memory_Info
= NULL
;
5100 HMODULE hm_psapi
= NULL
;
5101 if (is_windows_9x () == TRUE
)
5105 if (g_b_init_get_process_memory_info
== 0)
5107 g_b_init_get_process_memory_info
= 1;
5108 hm_psapi
= LoadLibrary ("Psapi.dll");
5110 s_pfn_Get_Process_Memory_Info
= (GetProcessMemoryInfo_Proc
)
5111 GetProcAddress (hm_psapi
, "GetProcessMemoryInfo");
5113 if (s_pfn_Get_Process_Memory_Info
== NULL
)
5117 return s_pfn_Get_Process_Memory_Info (h_proc
, mem_counters
, bufsize
);
5121 get_process_working_set_size (HANDLE h_proc
,
5125 static GetProcessWorkingSetSize_Proc
5126 s_pfn_Get_Process_Working_Set_Size
= NULL
;
5128 if (is_windows_9x () == TRUE
)
5132 if (g_b_init_get_process_working_set_size
== 0)
5134 g_b_init_get_process_working_set_size
= 1;
5135 s_pfn_Get_Process_Working_Set_Size
= (GetProcessWorkingSetSize_Proc
)
5136 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5137 "GetProcessWorkingSetSize");
5139 if (s_pfn_Get_Process_Working_Set_Size
== NULL
)
5143 return s_pfn_Get_Process_Working_Set_Size (h_proc
, minrss
, maxrss
);
5147 global_memory_status (MEMORYSTATUS
*buf
)
5149 static GlobalMemoryStatus_Proc s_pfn_Global_Memory_Status
= NULL
;
5151 if (is_windows_9x () == TRUE
)
5155 if (g_b_init_global_memory_status
== 0)
5157 g_b_init_global_memory_status
= 1;
5158 s_pfn_Global_Memory_Status
= (GlobalMemoryStatus_Proc
)
5159 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5160 "GlobalMemoryStatus");
5162 if (s_pfn_Global_Memory_Status
== NULL
)
5166 return s_pfn_Global_Memory_Status (buf
);
5170 global_memory_status_ex (MEMORY_STATUS_EX
*buf
)
5172 static GlobalMemoryStatusEx_Proc s_pfn_Global_Memory_Status_Ex
= NULL
;
5174 if (is_windows_9x () == TRUE
)
5178 if (g_b_init_global_memory_status_ex
== 0)
5180 g_b_init_global_memory_status_ex
= 1;
5181 s_pfn_Global_Memory_Status_Ex
= (GlobalMemoryStatusEx_Proc
)
5182 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5183 "GlobalMemoryStatusEx");
5185 if (s_pfn_Global_Memory_Status_Ex
== NULL
)
5189 return s_pfn_Global_Memory_Status_Ex (buf
);
5193 list_system_processes (void)
5195 struct gcpro gcpro1
;
5196 Lisp_Object proclist
= Qnil
;
5199 h_snapshot
= create_toolhelp32_snapshot (TH32CS_SNAPPROCESS
, 0);
5201 if (h_snapshot
!= INVALID_HANDLE_VALUE
)
5203 PROCESSENTRY32 proc_entry
;
5209 proc_entry
.dwSize
= sizeof (PROCESSENTRY32
);
5210 for (res
= process32_first (h_snapshot
, &proc_entry
); res
;
5211 res
= process32_next (h_snapshot
, &proc_entry
))
5213 proc_id
= proc_entry
.th32ProcessID
;
5214 proclist
= Fcons (make_fixnum_or_float (proc_id
), proclist
);
5217 CloseHandle (h_snapshot
);
5219 proclist
= Fnreverse (proclist
);
5226 enable_privilege (LPCTSTR priv_name
, BOOL enable_p
, TOKEN_PRIVILEGES
*old_priv
)
5228 TOKEN_PRIVILEGES priv
;
5229 DWORD priv_size
= sizeof (priv
);
5230 DWORD opriv_size
= sizeof (*old_priv
);
5231 HANDLE h_token
= NULL
;
5232 HANDLE h_thread
= GetCurrentThread ();
5236 res
= open_thread_token (h_thread
,
5237 TOKEN_QUERY
| TOKEN_ADJUST_PRIVILEGES
,
5239 if (!res
&& GetLastError () == ERROR_NO_TOKEN
)
5241 if (impersonate_self (SecurityImpersonation
))
5242 res
= open_thread_token (h_thread
,
5243 TOKEN_QUERY
| TOKEN_ADJUST_PRIVILEGES
,
5248 priv
.PrivilegeCount
= 1;
5249 priv
.Privileges
[0].Attributes
= enable_p
? SE_PRIVILEGE_ENABLED
: 0;
5250 LookupPrivilegeValue (NULL
, priv_name
, &priv
.Privileges
[0].Luid
);
5251 if (AdjustTokenPrivileges (h_token
, FALSE
, &priv
, priv_size
,
5252 old_priv
, &opriv_size
)
5253 && GetLastError () != ERROR_NOT_ALL_ASSIGNED
)
5257 CloseHandle (h_token
);
5263 restore_privilege (TOKEN_PRIVILEGES
*priv
)
5265 DWORD priv_size
= sizeof (*priv
);
5266 HANDLE h_token
= NULL
;
5269 if (open_thread_token (GetCurrentThread (),
5270 TOKEN_QUERY
| TOKEN_ADJUST_PRIVILEGES
,
5273 if (AdjustTokenPrivileges (h_token
, FALSE
, priv
, priv_size
, NULL
, NULL
)
5274 && GetLastError () != ERROR_NOT_ALL_ASSIGNED
)
5278 CloseHandle (h_token
);
5284 ltime (ULONGLONG time_100ns
)
5286 ULONGLONG time_sec
= time_100ns
/ 10000000;
5287 int subsec
= time_100ns
% 10000000;
5288 return list4 (make_number (time_sec
>> 16),
5289 make_number (time_sec
& 0xffff),
5290 make_number (subsec
/ 10),
5291 make_number (subsec
% 10 * 100000));
5294 #define U64_TO_LISP_TIME(time) ltime (time)
5297 process_times (HANDLE h_proc
, Lisp_Object
*ctime
, Lisp_Object
*etime
,
5298 Lisp_Object
*stime
, Lisp_Object
*utime
, Lisp_Object
*ttime
,
5301 FILETIME ft_creation
, ft_exit
, ft_kernel
, ft_user
, ft_current
;
5302 ULONGLONG tem1
, tem2
, tem3
, tem
;
5305 || !get_process_times_fn
5306 || !(*get_process_times_fn
) (h_proc
, &ft_creation
, &ft_exit
,
5307 &ft_kernel
, &ft_user
))
5310 GetSystemTimeAsFileTime (&ft_current
);
5312 FILETIME_TO_U64 (tem1
, ft_kernel
);
5313 *stime
= U64_TO_LISP_TIME (tem1
);
5315 FILETIME_TO_U64 (tem2
, ft_user
);
5316 *utime
= U64_TO_LISP_TIME (tem2
);
5319 *ttime
= U64_TO_LISP_TIME (tem3
);
5321 FILETIME_TO_U64 (tem
, ft_creation
);
5322 /* Process no 4 (System) returns zero creation time. */
5325 *ctime
= U64_TO_LISP_TIME (tem
);
5329 FILETIME_TO_U64 (tem3
, ft_current
);
5330 tem
= (tem3
- utc_base
) - tem
;
5332 *etime
= U64_TO_LISP_TIME (tem
);
5336 *pcpu
= 100.0 * (tem1
+ tem2
) / tem
;
5347 system_process_attributes (Lisp_Object pid
)
5349 struct gcpro gcpro1
, gcpro2
, gcpro3
;
5350 Lisp_Object attrs
= Qnil
;
5351 Lisp_Object cmd_str
, decoded_cmd
, tem
;
5352 HANDLE h_snapshot
, h_proc
;
5355 char uname
[UNLEN
+1], gname
[GNLEN
+1], domain
[1025];
5356 DWORD ulength
= sizeof (uname
), dlength
= sizeof (domain
), needed
;
5357 DWORD glength
= sizeof (gname
);
5358 HANDLE token
= NULL
;
5359 SID_NAME_USE user_type
;
5360 unsigned char *buf
= NULL
;
5362 TOKEN_USER user_token
;
5363 TOKEN_PRIMARY_GROUP group_token
;
5366 PROCESS_MEMORY_COUNTERS mem
;
5367 PROCESS_MEMORY_COUNTERS_EX mem_ex
;
5368 SIZE_T minrss
, maxrss
;
5370 MEMORY_STATUS_EX memstex
;
5371 double totphys
= 0.0;
5372 Lisp_Object ctime
, stime
, utime
, etime
, ttime
;
5374 BOOL result
= FALSE
;
5376 CHECK_NUMBER_OR_FLOAT (pid
);
5377 proc_id
= FLOATP (pid
) ? XFLOAT_DATA (pid
) : XINT (pid
);
5379 h_snapshot
= create_toolhelp32_snapshot (TH32CS_SNAPPROCESS
, 0);
5381 GCPRO3 (attrs
, decoded_cmd
, tem
);
5383 if (h_snapshot
!= INVALID_HANDLE_VALUE
)
5388 pe
.dwSize
= sizeof (PROCESSENTRY32
);
5389 for (res
= process32_first (h_snapshot
, &pe
); res
;
5390 res
= process32_next (h_snapshot
, &pe
))
5392 if (proc_id
== pe
.th32ProcessID
)
5395 decoded_cmd
= build_string ("Idle");
5398 /* Decode the command name from locale-specific
5400 cmd_str
= make_unibyte_string (pe
.szExeFile
,
5401 strlen (pe
.szExeFile
));
5403 code_convert_string_norecord (cmd_str
,
5404 Vlocale_coding_system
, 0);
5406 attrs
= Fcons (Fcons (Qcomm
, decoded_cmd
), attrs
);
5407 attrs
= Fcons (Fcons (Qppid
,
5408 make_fixnum_or_float (pe
.th32ParentProcessID
)),
5410 attrs
= Fcons (Fcons (Qpri
, make_number (pe
.pcPriClassBase
)),
5412 attrs
= Fcons (Fcons (Qthcount
,
5413 make_fixnum_or_float (pe
.cntThreads
)),
5420 CloseHandle (h_snapshot
);
5429 h_proc
= OpenProcess (PROCESS_QUERY_INFORMATION
| PROCESS_VM_READ
,
5431 /* If we were denied a handle to the process, try again after
5432 enabling the SeDebugPrivilege in our process. */
5435 TOKEN_PRIVILEGES priv_current
;
5437 if (enable_privilege (SE_DEBUG_NAME
, TRUE
, &priv_current
))
5439 h_proc
= OpenProcess (PROCESS_QUERY_INFORMATION
| PROCESS_VM_READ
,
5441 restore_privilege (&priv_current
);
5447 result
= open_process_token (h_proc
, TOKEN_QUERY
, &token
);
5450 result
= get_token_information (token
, TokenUser
, NULL
, 0, &blen
);
5451 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
5453 buf
= xmalloc (blen
);
5454 result
= get_token_information (token
, TokenUser
,
5455 (LPVOID
)buf
, blen
, &needed
);
5458 memcpy (&user_token
, buf
, sizeof (user_token
));
5459 if (!w32_cached_id (user_token
.User
.Sid
, &euid
, uname
))
5461 euid
= get_rid (user_token
.User
.Sid
);
5462 result
= lookup_account_sid (NULL
, user_token
.User
.Sid
,
5467 w32_add_to_cache (user_token
.User
.Sid
, euid
, uname
);
5470 strcpy (uname
, "unknown");
5474 ulength
= strlen (uname
);
5480 /* Determine a reasonable euid and gid values. */
5481 if (xstrcasecmp ("administrator", uname
) == 0)
5483 euid
= 500; /* well-known Administrator uid */
5484 egid
= 513; /* well-known None gid */
5488 /* Get group id and name. */
5489 result
= get_token_information (token
, TokenPrimaryGroup
,
5490 (LPVOID
)buf
, blen
, &needed
);
5491 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
5493 buf
= xrealloc (buf
, blen
= needed
);
5494 result
= get_token_information (token
, TokenPrimaryGroup
,
5495 (LPVOID
)buf
, blen
, &needed
);
5499 memcpy (&group_token
, buf
, sizeof (group_token
));
5500 if (!w32_cached_id (group_token
.PrimaryGroup
, &egid
, gname
))
5502 egid
= get_rid (group_token
.PrimaryGroup
);
5503 dlength
= sizeof (domain
);
5505 lookup_account_sid (NULL
, group_token
.PrimaryGroup
,
5506 gname
, &glength
, NULL
, &dlength
,
5509 w32_add_to_cache (group_token
.PrimaryGroup
,
5513 strcpy (gname
, "None");
5517 glength
= strlen (gname
);
5525 if (!is_windows_9x ())
5527 /* We couldn't open the process token, presumably because of
5528 insufficient access rights. Assume this process is run
5530 strcpy (uname
, "SYSTEM");
5531 strcpy (gname
, "None");
5532 euid
= 18; /* SYSTEM */
5533 egid
= 513; /* None */
5534 glength
= strlen (gname
);
5535 ulength
= strlen (uname
);
5537 /* If we are running under Windows 9X, where security calls are
5538 not supported, we assume all processes are run by the current
5540 else if (GetUserName (uname
, &ulength
))
5542 if (xstrcasecmp ("administrator", uname
) == 0)
5547 strcpy (gname
, "None");
5548 glength
= strlen (gname
);
5549 ulength
= strlen (uname
);
5555 strcpy (uname
, "administrator");
5556 ulength
= strlen (uname
);
5557 strcpy (gname
, "None");
5558 glength
= strlen (gname
);
5561 CloseHandle (token
);
5564 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (euid
)), attrs
);
5565 tem
= make_unibyte_string (uname
, ulength
);
5566 attrs
= Fcons (Fcons (Quser
,
5567 code_convert_string_norecord (tem
, Vlocale_coding_system
, 0)),
5569 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (egid
)), attrs
);
5570 tem
= make_unibyte_string (gname
, glength
);
5571 attrs
= Fcons (Fcons (Qgroup
,
5572 code_convert_string_norecord (tem
, Vlocale_coding_system
, 0)),
5575 if (global_memory_status_ex (&memstex
))
5576 #if __GNUC__ || (defined (_MSC_VER) && _MSC_VER >= 1300)
5577 totphys
= memstex
.ullTotalPhys
/ 1024.0;
5579 /* Visual Studio 6 cannot convert an unsigned __int64 type to
5580 double, so we need to do this for it... */
5582 DWORD tot_hi
= memstex
.ullTotalPhys
>> 32;
5583 DWORD tot_md
= (memstex
.ullTotalPhys
& 0x00000000ffffffff) >> 10;
5584 DWORD tot_lo
= memstex
.ullTotalPhys
% 1024;
5586 totphys
= tot_hi
* 4194304.0 + tot_md
+ tot_lo
/ 1024.0;
5588 #endif /* __GNUC__ || _MSC_VER >= 1300 */
5589 else if (global_memory_status (&memst
))
5590 totphys
= memst
.dwTotalPhys
/ 1024.0;
5593 && get_process_memory_info (h_proc
, (PROCESS_MEMORY_COUNTERS
*)&mem_ex
,
5596 SIZE_T rss
= mem_ex
.WorkingSetSize
/ 1024;
5598 attrs
= Fcons (Fcons (Qmajflt
,
5599 make_fixnum_or_float (mem_ex
.PageFaultCount
)),
5601 attrs
= Fcons (Fcons (Qvsize
,
5602 make_fixnum_or_float (mem_ex
.PrivateUsage
/ 1024)),
5604 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (rss
)), attrs
);
5606 attrs
= Fcons (Fcons (Qpmem
, make_float (100. * rss
/ totphys
)), attrs
);
5609 && get_process_memory_info (h_proc
, &mem
, sizeof (mem
)))
5611 SIZE_T rss
= mem_ex
.WorkingSetSize
/ 1024;
5613 attrs
= Fcons (Fcons (Qmajflt
,
5614 make_fixnum_or_float (mem
.PageFaultCount
)),
5616 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (rss
)), attrs
);
5618 attrs
= Fcons (Fcons (Qpmem
, make_float (100. * rss
/ totphys
)), attrs
);
5621 && get_process_working_set_size (h_proc
, &minrss
, &maxrss
))
5623 DWORD rss
= maxrss
/ 1024;
5625 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (maxrss
/ 1024)), attrs
);
5627 attrs
= Fcons (Fcons (Qpmem
, make_float (100. * rss
/ totphys
)), attrs
);
5630 if (process_times (h_proc
, &ctime
, &etime
, &stime
, &utime
, &ttime
, &pcpu
))
5632 attrs
= Fcons (Fcons (Qutime
, utime
), attrs
);
5633 attrs
= Fcons (Fcons (Qstime
, stime
), attrs
);
5634 attrs
= Fcons (Fcons (Qtime
, ttime
), attrs
);
5635 attrs
= Fcons (Fcons (Qstart
, ctime
), attrs
);
5636 attrs
= Fcons (Fcons (Qetime
, etime
), attrs
);
5637 attrs
= Fcons (Fcons (Qpcpu
, make_float (pcpu
)), attrs
);
5640 /* FIXME: Retrieve command line by walking the PEB of the process. */
5643 CloseHandle (h_proc
);
5649 /* Wrappers for winsock functions to map between our file descriptors
5650 and winsock's handles; also set h_errno for convenience.
5652 To allow Emacs to run on systems which don't have winsock support
5653 installed, we dynamically link to winsock on startup if present, and
5654 otherwise provide the minimum necessary functionality
5655 (eg. gethostname). */
5657 /* function pointers for relevant socket functions */
5658 int (PASCAL
*pfn_WSAStartup
) (WORD wVersionRequired
, LPWSADATA lpWSAData
);
5659 void (PASCAL
*pfn_WSASetLastError
) (int iError
);
5660 int (PASCAL
*pfn_WSAGetLastError
) (void);
5661 int (PASCAL
*pfn_WSAEventSelect
) (SOCKET s
, HANDLE hEventObject
, long lNetworkEvents
);
5662 HANDLE (PASCAL
*pfn_WSACreateEvent
) (void);
5663 int (PASCAL
*pfn_WSACloseEvent
) (HANDLE hEvent
);
5664 int (PASCAL
*pfn_socket
) (int af
, int type
, int protocol
);
5665 int (PASCAL
*pfn_bind
) (SOCKET s
, const struct sockaddr
*addr
, int namelen
);
5666 int (PASCAL
*pfn_connect
) (SOCKET s
, const struct sockaddr
*addr
, int namelen
);
5667 int (PASCAL
*pfn_ioctlsocket
) (SOCKET s
, long cmd
, u_long
*argp
);
5668 int (PASCAL
*pfn_recv
) (SOCKET s
, char * buf
, int len
, int flags
);
5669 int (PASCAL
*pfn_send
) (SOCKET s
, const char * buf
, int len
, int flags
);
5670 int (PASCAL
*pfn_closesocket
) (SOCKET s
);
5671 int (PASCAL
*pfn_shutdown
) (SOCKET s
, int how
);
5672 int (PASCAL
*pfn_WSACleanup
) (void);
5674 u_short (PASCAL
*pfn_htons
) (u_short hostshort
);
5675 u_short (PASCAL
*pfn_ntohs
) (u_short netshort
);
5676 unsigned long (PASCAL
*pfn_inet_addr
) (const char * cp
);
5677 int (PASCAL
*pfn_gethostname
) (char * name
, int namelen
);
5678 struct hostent
* (PASCAL
*pfn_gethostbyname
) (const char * name
);
5679 struct servent
* (PASCAL
*pfn_getservbyname
) (const char * name
, const char * proto
);
5680 int (PASCAL
*pfn_getpeername
) (SOCKET s
, struct sockaddr
*addr
, int * namelen
);
5681 int (PASCAL
*pfn_setsockopt
) (SOCKET s
, int level
, int optname
,
5682 const char * optval
, int optlen
);
5683 int (PASCAL
*pfn_listen
) (SOCKET s
, int backlog
);
5684 int (PASCAL
*pfn_getsockname
) (SOCKET s
, struct sockaddr
* name
,
5686 SOCKET (PASCAL
*pfn_accept
) (SOCKET s
, struct sockaddr
* addr
, int * addrlen
);
5687 int (PASCAL
*pfn_recvfrom
) (SOCKET s
, char * buf
, int len
, int flags
,
5688 struct sockaddr
* from
, int * fromlen
);
5689 int (PASCAL
*pfn_sendto
) (SOCKET s
, const char * buf
, int len
, int flags
,
5690 const struct sockaddr
* to
, int tolen
);
5692 /* SetHandleInformation is only needed to make sockets non-inheritable. */
5693 BOOL (WINAPI
*pfn_SetHandleInformation
) (HANDLE object
, DWORD mask
, DWORD flags
);
5694 #ifndef HANDLE_FLAG_INHERIT
5695 #define HANDLE_FLAG_INHERIT 1
5699 static int winsock_inuse
;
5704 if (winsock_lib
!= NULL
&& winsock_inuse
== 0)
5706 /* Not sure what would cause WSAENETDOWN, or even if it can happen
5707 after WSAStartup returns successfully, but it seems reasonable
5708 to allow unloading winsock anyway in that case. */
5709 if (pfn_WSACleanup () == 0 ||
5710 pfn_WSAGetLastError () == WSAENETDOWN
)
5712 if (FreeLibrary (winsock_lib
))
5721 init_winsock (int load_now
)
5723 WSADATA winsockData
;
5725 if (winsock_lib
!= NULL
)
5728 pfn_SetHandleInformation
5729 = (void *) GetProcAddress (GetModuleHandle ("kernel32.dll"),
5730 "SetHandleInformation");
5732 winsock_lib
= LoadLibrary ("Ws2_32.dll");
5734 if (winsock_lib
!= NULL
)
5736 /* dynamically link to socket functions */
5738 #define LOAD_PROC(fn) \
5739 if ((pfn_##fn = (void *) GetProcAddress (winsock_lib, #fn)) == NULL) \
5742 LOAD_PROC (WSAStartup
);
5743 LOAD_PROC (WSASetLastError
);
5744 LOAD_PROC (WSAGetLastError
);
5745 LOAD_PROC (WSAEventSelect
);
5746 LOAD_PROC (WSACreateEvent
);
5747 LOAD_PROC (WSACloseEvent
);
5750 LOAD_PROC (connect
);
5751 LOAD_PROC (ioctlsocket
);
5754 LOAD_PROC (closesocket
);
5755 LOAD_PROC (shutdown
);
5758 LOAD_PROC (inet_addr
);
5759 LOAD_PROC (gethostname
);
5760 LOAD_PROC (gethostbyname
);
5761 LOAD_PROC (getservbyname
);
5762 LOAD_PROC (getpeername
);
5763 LOAD_PROC (WSACleanup
);
5764 LOAD_PROC (setsockopt
);
5766 LOAD_PROC (getsockname
);
5768 LOAD_PROC (recvfrom
);
5772 /* specify version 1.1 of winsock */
5773 if (pfn_WSAStartup (0x101, &winsockData
) == 0)
5775 if (winsockData
.wVersion
!= 0x101)
5780 /* Report that winsock exists and is usable, but leave
5781 socket functions disabled. I am assuming that calling
5782 WSAStartup does not require any network interaction,
5783 and in particular does not cause or require a dial-up
5784 connection to be established. */
5787 FreeLibrary (winsock_lib
);
5795 FreeLibrary (winsock_lib
);
5805 /* function to set h_errno for compatibility; map winsock error codes to
5806 normal system codes where they overlap (non-overlapping definitions
5807 are already in <sys/socket.h> */
5811 if (winsock_lib
== NULL
)
5814 h_errno
= pfn_WSAGetLastError ();
5818 case WSAEACCES
: h_errno
= EACCES
; break;
5819 case WSAEBADF
: h_errno
= EBADF
; break;
5820 case WSAEFAULT
: h_errno
= EFAULT
; break;
5821 case WSAEINTR
: h_errno
= EINTR
; break;
5822 case WSAEINVAL
: h_errno
= EINVAL
; break;
5823 case WSAEMFILE
: h_errno
= EMFILE
; break;
5824 case WSAENAMETOOLONG
: h_errno
= ENAMETOOLONG
; break;
5825 case WSAENOTEMPTY
: h_errno
= ENOTEMPTY
; break;
5833 if (h_errno
== 0 && winsock_lib
!= NULL
)
5834 pfn_WSASetLastError (0);
5837 /* Extend strerror to handle the winsock-specific error codes. */
5841 } _wsa_errlist
[] = {
5842 {WSAEINTR
, "Interrupted function call"},
5843 {WSAEBADF
, "Bad file descriptor"},
5844 {WSAEACCES
, "Permission denied"},
5845 {WSAEFAULT
, "Bad address"},
5846 {WSAEINVAL
, "Invalid argument"},
5847 {WSAEMFILE
, "Too many open files"},
5849 {WSAEWOULDBLOCK
, "Resource temporarily unavailable"},
5850 {WSAEINPROGRESS
, "Operation now in progress"},
5851 {WSAEALREADY
, "Operation already in progress"},
5852 {WSAENOTSOCK
, "Socket operation on non-socket"},
5853 {WSAEDESTADDRREQ
, "Destination address required"},
5854 {WSAEMSGSIZE
, "Message too long"},
5855 {WSAEPROTOTYPE
, "Protocol wrong type for socket"},
5856 {WSAENOPROTOOPT
, "Bad protocol option"},
5857 {WSAEPROTONOSUPPORT
, "Protocol not supported"},
5858 {WSAESOCKTNOSUPPORT
, "Socket type not supported"},
5859 {WSAEOPNOTSUPP
, "Operation not supported"},
5860 {WSAEPFNOSUPPORT
, "Protocol family not supported"},
5861 {WSAEAFNOSUPPORT
, "Address family not supported by protocol family"},
5862 {WSAEADDRINUSE
, "Address already in use"},
5863 {WSAEADDRNOTAVAIL
, "Cannot assign requested address"},
5864 {WSAENETDOWN
, "Network is down"},
5865 {WSAENETUNREACH
, "Network is unreachable"},
5866 {WSAENETRESET
, "Network dropped connection on reset"},
5867 {WSAECONNABORTED
, "Software caused connection abort"},
5868 {WSAECONNRESET
, "Connection reset by peer"},
5869 {WSAENOBUFS
, "No buffer space available"},
5870 {WSAEISCONN
, "Socket is already connected"},
5871 {WSAENOTCONN
, "Socket is not connected"},
5872 {WSAESHUTDOWN
, "Cannot send after socket shutdown"},
5873 {WSAETOOMANYREFS
, "Too many references"}, /* not sure */
5874 {WSAETIMEDOUT
, "Connection timed out"},
5875 {WSAECONNREFUSED
, "Connection refused"},
5876 {WSAELOOP
, "Network loop"}, /* not sure */
5877 {WSAENAMETOOLONG
, "Name is too long"},
5878 {WSAEHOSTDOWN
, "Host is down"},
5879 {WSAEHOSTUNREACH
, "No route to host"},
5880 {WSAENOTEMPTY
, "Buffer not empty"}, /* not sure */
5881 {WSAEPROCLIM
, "Too many processes"},
5882 {WSAEUSERS
, "Too many users"}, /* not sure */
5883 {WSAEDQUOT
, "Double quote in host name"}, /* really not sure */
5884 {WSAESTALE
, "Data is stale"}, /* not sure */
5885 {WSAEREMOTE
, "Remote error"}, /* not sure */
5887 {WSASYSNOTREADY
, "Network subsystem is unavailable"},
5888 {WSAVERNOTSUPPORTED
, "WINSOCK.DLL version out of range"},
5889 {WSANOTINITIALISED
, "Winsock not initialized successfully"},
5890 {WSAEDISCON
, "Graceful shutdown in progress"},
5892 {WSAENOMORE
, "No more operations allowed"}, /* not sure */
5893 {WSAECANCELLED
, "Operation cancelled"}, /* not sure */
5894 {WSAEINVALIDPROCTABLE
, "Invalid procedure table from service provider"},
5895 {WSAEINVALIDPROVIDER
, "Invalid service provider version number"},
5896 {WSAEPROVIDERFAILEDINIT
, "Unable to initialize a service provider"},
5897 {WSASYSCALLFAILURE
, "System call failure"},
5898 {WSASERVICE_NOT_FOUND
, "Service not found"}, /* not sure */
5899 {WSATYPE_NOT_FOUND
, "Class type not found"},
5900 {WSA_E_NO_MORE
, "No more resources available"}, /* really not sure */
5901 {WSA_E_CANCELLED
, "Operation already cancelled"}, /* really not sure */
5902 {WSAEREFUSED
, "Operation refused"}, /* not sure */
5905 {WSAHOST_NOT_FOUND
, "Host not found"},
5906 {WSATRY_AGAIN
, "Authoritative host not found during name lookup"},
5907 {WSANO_RECOVERY
, "Non-recoverable error during name lookup"},
5908 {WSANO_DATA
, "Valid name, no data record of requested type"},
5914 sys_strerror (int error_no
)
5917 static char unknown_msg
[40];
5919 if (error_no
>= 0 && error_no
< sys_nerr
)
5920 return sys_errlist
[error_no
];
5922 for (i
= 0; _wsa_errlist
[i
].errnum
>= 0; i
++)
5923 if (_wsa_errlist
[i
].errnum
== error_no
)
5924 return _wsa_errlist
[i
].msg
;
5926 sprintf (unknown_msg
, "Unidentified error: %d", error_no
);
5930 /* [andrewi 3-May-96] I've had conflicting results using both methods,
5931 but I believe the method of keeping the socket handle separate (and
5932 insuring it is not inheritable) is the correct one. */
5934 #define SOCK_HANDLE(fd) ((SOCKET) fd_info[fd].hnd)
5936 static int socket_to_fd (SOCKET s
);
5939 sys_socket (int af
, int type
, int protocol
)
5943 if (winsock_lib
== NULL
)
5946 return INVALID_SOCKET
;
5951 /* call the real socket function */
5952 s
= pfn_socket (af
, type
, protocol
);
5954 if (s
!= INVALID_SOCKET
)
5955 return socket_to_fd (s
);
5961 /* Convert a SOCKET to a file descriptor. */
5963 socket_to_fd (SOCKET s
)
5968 /* Although under NT 3.5 _open_osfhandle will accept a socket
5969 handle, if opened with SO_OPENTYPE == SO_SYNCHRONOUS_NONALERT,
5970 that does not work under NT 3.1. However, we can get the same
5971 effect by using a backdoor function to replace an existing
5972 descriptor handle with the one we want. */
5974 /* allocate a file descriptor (with appropriate flags) */
5975 fd
= _open ("NUL:", _O_RDWR
);
5978 /* Make a non-inheritable copy of the socket handle. Note
5979 that it is possible that sockets aren't actually kernel
5980 handles, which appears to be the case on Windows 9x when
5981 the MS Proxy winsock client is installed. */
5983 /* Apparently there is a bug in NT 3.51 with some service
5984 packs, which prevents using DuplicateHandle to make a
5985 socket handle non-inheritable (causes WSACleanup to
5986 hang). The work-around is to use SetHandleInformation
5987 instead if it is available and implemented. */
5988 if (pfn_SetHandleInformation
)
5990 pfn_SetHandleInformation ((HANDLE
) s
, HANDLE_FLAG_INHERIT
, 0);
5994 HANDLE parent
= GetCurrentProcess ();
5995 HANDLE new_s
= INVALID_HANDLE_VALUE
;
5997 if (DuplicateHandle (parent
,
6003 DUPLICATE_SAME_ACCESS
))
6005 /* It is possible that DuplicateHandle succeeds even
6006 though the socket wasn't really a kernel handle,
6007 because a real handle has the same value. So
6008 test whether the new handle really is a socket. */
6009 long nonblocking
= 0;
6010 if (pfn_ioctlsocket ((SOCKET
) new_s
, FIONBIO
, &nonblocking
) == 0)
6012 pfn_closesocket (s
);
6017 CloseHandle (new_s
);
6022 fd_info
[fd
].hnd
= (HANDLE
) s
;
6024 /* set our own internal flags */
6025 fd_info
[fd
].flags
= FILE_SOCKET
| FILE_BINARY
| FILE_READ
| FILE_WRITE
;
6031 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
6033 /* attach child_process to fd_info */
6034 if (fd_info
[ fd
].cp
!= NULL
)
6036 DebPrint (("sys_socket: fd_info[%d] apparently in use!\n", fd
));
6040 fd_info
[ fd
].cp
= cp
;
6043 winsock_inuse
++; /* count open sockets */
6050 pfn_closesocket (s
);
6056 sys_bind (int s
, const struct sockaddr
* addr
, int namelen
)
6058 if (winsock_lib
== NULL
)
6061 return SOCKET_ERROR
;
6065 if (fd_info
[s
].flags
& FILE_SOCKET
)
6067 int rc
= pfn_bind (SOCK_HANDLE (s
), addr
, namelen
);
6068 if (rc
== SOCKET_ERROR
)
6073 return SOCKET_ERROR
;
6077 sys_connect (int s
, const struct sockaddr
* name
, int namelen
)
6079 if (winsock_lib
== NULL
)
6082 return SOCKET_ERROR
;
6086 if (fd_info
[s
].flags
& FILE_SOCKET
)
6088 int rc
= pfn_connect (SOCK_HANDLE (s
), name
, namelen
);
6089 if (rc
== SOCKET_ERROR
)
6094 return SOCKET_ERROR
;
6098 sys_htons (u_short hostshort
)
6100 return (winsock_lib
!= NULL
) ?
6101 pfn_htons (hostshort
) : hostshort
;
6105 sys_ntohs (u_short netshort
)
6107 return (winsock_lib
!= NULL
) ?
6108 pfn_ntohs (netshort
) : netshort
;
6112 sys_inet_addr (const char * cp
)
6114 return (winsock_lib
!= NULL
) ?
6115 pfn_inet_addr (cp
) : INADDR_NONE
;
6119 sys_gethostname (char * name
, int namelen
)
6121 if (winsock_lib
!= NULL
)
6122 return pfn_gethostname (name
, namelen
);
6124 if (namelen
> MAX_COMPUTERNAME_LENGTH
)
6125 return !GetComputerName (name
, (DWORD
*)&namelen
);
6128 return SOCKET_ERROR
;
6132 sys_gethostbyname (const char * name
)
6134 struct hostent
* host
;
6136 if (winsock_lib
== NULL
)
6143 host
= pfn_gethostbyname (name
);
6150 sys_getservbyname (const char * name
, const char * proto
)
6152 struct servent
* serv
;
6154 if (winsock_lib
== NULL
)
6161 serv
= pfn_getservbyname (name
, proto
);
6168 sys_getpeername (int s
, struct sockaddr
*addr
, int * namelen
)
6170 if (winsock_lib
== NULL
)
6173 return SOCKET_ERROR
;
6177 if (fd_info
[s
].flags
& FILE_SOCKET
)
6179 int rc
= pfn_getpeername (SOCK_HANDLE (s
), addr
, namelen
);
6180 if (rc
== SOCKET_ERROR
)
6185 return SOCKET_ERROR
;
6189 sys_shutdown (int s
, int how
)
6191 if (winsock_lib
== NULL
)
6194 return SOCKET_ERROR
;
6198 if (fd_info
[s
].flags
& FILE_SOCKET
)
6200 int rc
= pfn_shutdown (SOCK_HANDLE (s
), how
);
6201 if (rc
== SOCKET_ERROR
)
6206 return SOCKET_ERROR
;
6210 sys_setsockopt (int s
, int level
, int optname
, const void * optval
, int optlen
)
6212 if (winsock_lib
== NULL
)
6215 return SOCKET_ERROR
;
6219 if (fd_info
[s
].flags
& FILE_SOCKET
)
6221 int rc
= pfn_setsockopt (SOCK_HANDLE (s
), level
, optname
,
6222 (const char *)optval
, optlen
);
6223 if (rc
== SOCKET_ERROR
)
6228 return SOCKET_ERROR
;
6232 sys_listen (int s
, int backlog
)
6234 if (winsock_lib
== NULL
)
6237 return SOCKET_ERROR
;
6241 if (fd_info
[s
].flags
& FILE_SOCKET
)
6243 int rc
= pfn_listen (SOCK_HANDLE (s
), backlog
);
6244 if (rc
== SOCKET_ERROR
)
6247 fd_info
[s
].flags
|= FILE_LISTEN
;
6251 return SOCKET_ERROR
;
6255 sys_getsockname (int s
, struct sockaddr
* name
, int * namelen
)
6257 if (winsock_lib
== NULL
)
6260 return SOCKET_ERROR
;
6264 if (fd_info
[s
].flags
& FILE_SOCKET
)
6266 int rc
= pfn_getsockname (SOCK_HANDLE (s
), name
, namelen
);
6267 if (rc
== SOCKET_ERROR
)
6272 return SOCKET_ERROR
;
6276 sys_accept (int s
, struct sockaddr
* addr
, int * addrlen
)
6278 if (winsock_lib
== NULL
)
6285 if (fd_info
[s
].flags
& FILE_LISTEN
)
6287 SOCKET t
= pfn_accept (SOCK_HANDLE (s
), addr
, addrlen
);
6289 if (t
== INVALID_SOCKET
)
6292 fd
= socket_to_fd (t
);
6294 fd_info
[s
].cp
->status
= STATUS_READ_ACKNOWLEDGED
;
6295 ResetEvent (fd_info
[s
].cp
->char_avail
);
6303 sys_recvfrom (int s
, char * buf
, int len
, int flags
,
6304 struct sockaddr
* from
, int * fromlen
)
6306 if (winsock_lib
== NULL
)
6309 return SOCKET_ERROR
;
6313 if (fd_info
[s
].flags
& FILE_SOCKET
)
6315 int rc
= pfn_recvfrom (SOCK_HANDLE (s
), buf
, len
, flags
, from
, fromlen
);
6316 if (rc
== SOCKET_ERROR
)
6321 return SOCKET_ERROR
;
6325 sys_sendto (int s
, const char * buf
, int len
, int flags
,
6326 const struct sockaddr
* to
, int tolen
)
6328 if (winsock_lib
== NULL
)
6331 return SOCKET_ERROR
;
6335 if (fd_info
[s
].flags
& FILE_SOCKET
)
6337 int rc
= pfn_sendto (SOCK_HANDLE (s
), buf
, len
, flags
, to
, tolen
);
6338 if (rc
== SOCKET_ERROR
)
6343 return SOCKET_ERROR
;
6346 /* Windows does not have an fcntl function. Provide an implementation
6347 solely for making sockets non-blocking. */
6349 fcntl (int s
, int cmd
, int options
)
6351 if (winsock_lib
== NULL
)
6358 if (fd_info
[s
].flags
& FILE_SOCKET
)
6360 if (cmd
== F_SETFL
&& options
== O_NONBLOCK
)
6362 unsigned long nblock
= 1;
6363 int rc
= pfn_ioctlsocket (SOCK_HANDLE (s
), FIONBIO
, &nblock
);
6364 if (rc
== SOCKET_ERROR
)
6366 /* Keep track of the fact that we set this to non-blocking. */
6367 fd_info
[s
].flags
|= FILE_NDELAY
;
6373 return SOCKET_ERROR
;
6377 return SOCKET_ERROR
;
6381 /* Shadow main io functions: we need to handle pipes and sockets more
6382 intelligently, and implement non-blocking mode as well. */
6395 if (fd
< MAXDESC
&& fd_info
[fd
].cp
)
6397 child_process
* cp
= fd_info
[fd
].cp
;
6399 fd_info
[fd
].cp
= NULL
;
6401 if (CHILD_ACTIVE (cp
))
6403 /* if last descriptor to active child_process then cleanup */
6405 for (i
= 0; i
< MAXDESC
; i
++)
6409 if (fd_info
[i
].cp
== cp
)
6414 if (fd_info
[fd
].flags
& FILE_SOCKET
)
6416 if (winsock_lib
== NULL
) emacs_abort ();
6418 pfn_shutdown (SOCK_HANDLE (fd
), 2);
6419 rc
= pfn_closesocket (SOCK_HANDLE (fd
));
6421 winsock_inuse
--; /* count open sockets */
6428 /* Note that sockets do not need special treatment here (at least on
6429 NT and Windows 95 using the standard tcp/ip stacks) - it appears that
6430 closesocket is equivalent to CloseHandle, which is to be expected
6431 because socket handles are fully fledged kernel handles. */
6434 if (rc
== 0 && fd
< MAXDESC
)
6435 fd_info
[fd
].flags
= 0;
6446 if (new_fd
>= 0 && new_fd
< MAXDESC
)
6448 /* duplicate our internal info as well */
6449 fd_info
[new_fd
] = fd_info
[fd
];
6455 sys_dup2 (int src
, int dst
)
6459 if (dst
< 0 || dst
>= MAXDESC
)
6465 /* make sure we close the destination first if it's a pipe or socket */
6466 if (src
!= dst
&& fd_info
[dst
].flags
!= 0)
6469 rc
= _dup2 (src
, dst
);
6472 /* duplicate our internal info as well */
6473 fd_info
[dst
] = fd_info
[src
];
6478 /* Unix pipe() has only one arg */
6480 sys_pipe (int * phandles
)
6485 /* make pipe handles non-inheritable; when we spawn a child, we
6486 replace the relevant handle with an inheritable one. Also put
6487 pipes into binary mode; we will do text mode translation ourselves
6489 rc
= _pipe (phandles
, 0, _O_NOINHERIT
| _O_BINARY
);
6493 /* Protect against overflow, since Windows can open more handles than
6494 our fd_info array has room for. */
6495 if (phandles
[0] >= MAXDESC
|| phandles
[1] >= MAXDESC
)
6497 _close (phandles
[0]);
6498 _close (phandles
[1]);
6503 flags
= FILE_PIPE
| FILE_READ
| FILE_BINARY
;
6504 fd_info
[phandles
[0]].flags
= flags
;
6506 flags
= FILE_PIPE
| FILE_WRITE
| FILE_BINARY
;
6507 fd_info
[phandles
[1]].flags
= flags
;
6514 /* Function to do blocking read of one byte, needed to implement
6515 select. It is only allowed on communication ports, sockets, or
6518 _sys_read_ahead (int fd
)
6523 if (fd
< 0 || fd
>= MAXDESC
)
6524 return STATUS_READ_ERROR
;
6526 cp
= fd_info
[fd
].cp
;
6528 if (cp
== NULL
|| cp
->fd
!= fd
|| cp
->status
!= STATUS_READ_READY
)
6529 return STATUS_READ_ERROR
;
6531 if ((fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SERIAL
| FILE_SOCKET
)) == 0
6532 || (fd_info
[fd
].flags
& FILE_READ
) == 0)
6534 DebPrint (("_sys_read_ahead: internal error: fd %d is not a pipe, serial port, or socket!\n", fd
));
6538 cp
->status
= STATUS_READ_IN_PROGRESS
;
6540 if (fd_info
[fd
].flags
& FILE_PIPE
)
6542 rc
= _read (fd
, &cp
->chr
, sizeof (char));
6544 /* Give subprocess time to buffer some more output for us before
6545 reporting that input is available; we need this because Windows 95
6546 connects DOS programs to pipes by making the pipe appear to be
6547 the normal console stdout - as a result most DOS programs will
6548 write to stdout without buffering, ie. one character at a
6549 time. Even some W32 programs do this - "dir" in a command
6550 shell on NT is very slow if we don't do this. */
6553 int wait
= w32_pipe_read_delay
;
6559 /* Yield remainder of our time slice, effectively giving a
6560 temporary priority boost to the child process. */
6564 else if (fd_info
[fd
].flags
& FILE_SERIAL
)
6566 HANDLE hnd
= fd_info
[fd
].hnd
;
6567 OVERLAPPED
*ovl
= &fd_info
[fd
].cp
->ovl_read
;
6570 /* Configure timeouts for blocking read. */
6571 if (!GetCommTimeouts (hnd
, &ct
))
6572 return STATUS_READ_ERROR
;
6573 ct
.ReadIntervalTimeout
= 0;
6574 ct
.ReadTotalTimeoutMultiplier
= 0;
6575 ct
.ReadTotalTimeoutConstant
= 0;
6576 if (!SetCommTimeouts (hnd
, &ct
))
6577 return STATUS_READ_ERROR
;
6579 if (!ReadFile (hnd
, &cp
->chr
, sizeof (char), (DWORD
*) &rc
, ovl
))
6581 if (GetLastError () != ERROR_IO_PENDING
)
6582 return STATUS_READ_ERROR
;
6583 if (!GetOverlappedResult (hnd
, ovl
, (DWORD
*) &rc
, TRUE
))
6584 return STATUS_READ_ERROR
;
6587 else if (fd_info
[fd
].flags
& FILE_SOCKET
)
6589 unsigned long nblock
= 0;
6590 /* We always want this to block, so temporarily disable NDELAY. */
6591 if (fd_info
[fd
].flags
& FILE_NDELAY
)
6592 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
6594 rc
= pfn_recv (SOCK_HANDLE (fd
), &cp
->chr
, sizeof (char), 0);
6596 if (fd_info
[fd
].flags
& FILE_NDELAY
)
6599 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
6603 if (rc
== sizeof (char))
6604 cp
->status
= STATUS_READ_SUCCEEDED
;
6606 cp
->status
= STATUS_READ_FAILED
;
6612 _sys_wait_accept (int fd
)
6618 if (fd
< 0 || fd
>= MAXDESC
)
6619 return STATUS_READ_ERROR
;
6621 cp
= fd_info
[fd
].cp
;
6623 if (cp
== NULL
|| cp
->fd
!= fd
|| cp
->status
!= STATUS_READ_READY
)
6624 return STATUS_READ_ERROR
;
6626 cp
->status
= STATUS_READ_FAILED
;
6628 hEv
= pfn_WSACreateEvent ();
6629 rc
= pfn_WSAEventSelect (SOCK_HANDLE (fd
), hEv
, FD_ACCEPT
);
6630 if (rc
!= SOCKET_ERROR
)
6632 rc
= WaitForSingleObject (hEv
, INFINITE
);
6633 pfn_WSAEventSelect (SOCK_HANDLE (fd
), NULL
, 0);
6634 if (rc
== WAIT_OBJECT_0
)
6635 cp
->status
= STATUS_READ_SUCCEEDED
;
6637 pfn_WSACloseEvent (hEv
);
6643 sys_read (int fd
, char * buffer
, unsigned int count
)
6648 char * orig_buffer
= buffer
;
6656 if (fd
< MAXDESC
&& fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
| FILE_SERIAL
))
6658 child_process
*cp
= fd_info
[fd
].cp
;
6660 if ((fd_info
[fd
].flags
& FILE_READ
) == 0)
6668 /* re-read CR carried over from last read */
6669 if (fd_info
[fd
].flags
& FILE_LAST_CR
)
6671 if (fd_info
[fd
].flags
& FILE_BINARY
) emacs_abort ();
6675 fd_info
[fd
].flags
&= ~FILE_LAST_CR
;
6678 /* presence of a child_process structure means we are operating in
6679 non-blocking mode - otherwise we just call _read directly.
6680 Note that the child_process structure might be missing because
6681 reap_subprocess has been called; in this case the pipe is
6682 already broken, so calling _read on it is okay. */
6685 int current_status
= cp
->status
;
6687 switch (current_status
)
6689 case STATUS_READ_FAILED
:
6690 case STATUS_READ_ERROR
:
6691 /* report normal EOF if nothing in buffer */
6693 fd_info
[fd
].flags
|= FILE_AT_EOF
;
6696 case STATUS_READ_READY
:
6697 case STATUS_READ_IN_PROGRESS
:
6698 DebPrint (("sys_read called when read is in progress\n"));
6699 errno
= EWOULDBLOCK
;
6702 case STATUS_READ_SUCCEEDED
:
6703 /* consume read-ahead char */
6704 *buffer
++ = cp
->chr
;
6707 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
6708 ResetEvent (cp
->char_avail
);
6710 case STATUS_READ_ACKNOWLEDGED
:
6714 DebPrint (("sys_read: bad status %d\n", current_status
));
6719 if (fd_info
[fd
].flags
& FILE_PIPE
)
6721 PeekNamedPipe ((HANDLE
) _get_osfhandle (fd
), NULL
, 0, NULL
, &waiting
, NULL
);
6722 to_read
= min (waiting
, (DWORD
) count
);
6725 nchars
+= _read (fd
, buffer
, to_read
);
6727 else if (fd_info
[fd
].flags
& FILE_SERIAL
)
6729 HANDLE hnd
= fd_info
[fd
].hnd
;
6730 OVERLAPPED
*ovl
= &fd_info
[fd
].cp
->ovl_read
;
6736 /* Configure timeouts for non-blocking read. */
6737 if (!GetCommTimeouts (hnd
, &ct
))
6742 ct
.ReadIntervalTimeout
= MAXDWORD
;
6743 ct
.ReadTotalTimeoutMultiplier
= 0;
6744 ct
.ReadTotalTimeoutConstant
= 0;
6745 if (!SetCommTimeouts (hnd
, &ct
))
6751 if (!ResetEvent (ovl
->hEvent
))
6756 if (!ReadFile (hnd
, buffer
, count
, (DWORD
*) &rc
, ovl
))
6758 if (GetLastError () != ERROR_IO_PENDING
)
6763 if (!GetOverlappedResult (hnd
, ovl
, (DWORD
*) &rc
, TRUE
))
6772 else /* FILE_SOCKET */
6774 if (winsock_lib
== NULL
) emacs_abort ();
6776 /* do the equivalent of a non-blocking read */
6777 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONREAD
, &waiting
);
6778 if (waiting
== 0 && nchars
== 0)
6780 h_errno
= errno
= EWOULDBLOCK
;
6786 /* always use binary mode for sockets */
6787 int res
= pfn_recv (SOCK_HANDLE (fd
), buffer
, count
, 0);
6788 if (res
== SOCKET_ERROR
)
6790 DebPrint (("sys_read.recv failed with error %d on socket %ld\n",
6791 pfn_WSAGetLastError (), SOCK_HANDLE (fd
)));
6801 int nread
= _read (fd
, buffer
, count
);
6804 else if (nchars
== 0)
6809 fd_info
[fd
].flags
|= FILE_AT_EOF
;
6810 /* Perform text mode translation if required. */
6811 else if ((fd_info
[fd
].flags
& FILE_BINARY
) == 0)
6813 nchars
= crlf_to_lf (nchars
, orig_buffer
);
6814 /* If buffer contains only CR, return that. To be absolutely
6815 sure we should attempt to read the next char, but in
6816 practice a CR to be followed by LF would not appear by
6817 itself in the buffer. */
6818 if (nchars
> 1 && orig_buffer
[nchars
- 1] == 0x0d)
6820 fd_info
[fd
].flags
|= FILE_LAST_CR
;
6826 nchars
= _read (fd
, buffer
, count
);
6831 /* From w32xfns.c */
6832 extern HANDLE interrupt_handle
;
6834 /* For now, don't bother with a non-blocking mode */
6836 sys_write (int fd
, const void * buffer
, unsigned int count
)
6846 if (fd
< MAXDESC
&& fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
| FILE_SERIAL
))
6848 if ((fd_info
[fd
].flags
& FILE_WRITE
) == 0)
6854 /* Perform text mode translation if required. */
6855 if ((fd_info
[fd
].flags
& FILE_BINARY
) == 0)
6857 char * tmpbuf
= alloca (count
* 2);
6858 unsigned char * src
= (void *)buffer
;
6859 unsigned char * dst
= tmpbuf
;
6864 unsigned char *next
;
6865 /* copy next line or remaining bytes */
6866 next
= _memccpy (dst
, src
, '\n', nbytes
);
6869 /* copied one line ending with '\n' */
6870 int copied
= next
- dst
;
6873 /* insert '\r' before '\n' */
6880 /* copied remaining partial line -> now finished */
6887 if (fd
< MAXDESC
&& fd_info
[fd
].flags
& FILE_SERIAL
)
6889 HANDLE hnd
= (HANDLE
) _get_osfhandle (fd
);
6890 OVERLAPPED
*ovl
= &fd_info
[fd
].cp
->ovl_write
;
6891 HANDLE wait_hnd
[2] = { interrupt_handle
, ovl
->hEvent
};
6894 if (!WriteFile (hnd
, buffer
, count
, (DWORD
*) &nchars
, ovl
))
6896 if (GetLastError () != ERROR_IO_PENDING
)
6901 if (detect_input_pending ())
6902 active
= MsgWaitForMultipleObjects (2, wait_hnd
, FALSE
, INFINITE
,
6905 active
= WaitForMultipleObjects (2, wait_hnd
, FALSE
, INFINITE
);
6906 if (active
== WAIT_OBJECT_0
)
6907 { /* User pressed C-g, cancel write, then leave. Don't bother
6908 cleaning up as we may only get stuck in buggy drivers. */
6909 PurgeComm (hnd
, PURGE_TXABORT
| PURGE_TXCLEAR
);
6914 if (active
== WAIT_OBJECT_0
+ 1
6915 && !GetOverlappedResult (hnd
, ovl
, (DWORD
*) &nchars
, TRUE
))
6922 else if (fd
< MAXDESC
&& fd_info
[fd
].flags
& FILE_SOCKET
)
6924 unsigned long nblock
= 0;
6925 if (winsock_lib
== NULL
) emacs_abort ();
6927 /* TODO: implement select() properly so non-blocking I/O works. */
6928 /* For now, make sure the write blocks. */
6929 if (fd_info
[fd
].flags
& FILE_NDELAY
)
6930 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
6932 nchars
= pfn_send (SOCK_HANDLE (fd
), buffer
, count
, 0);
6934 /* Set the socket back to non-blocking if it was before,
6935 for other operations that support it. */
6936 if (fd_info
[fd
].flags
& FILE_NDELAY
)
6939 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
6942 if (nchars
== SOCKET_ERROR
)
6944 DebPrint (("sys_write.send failed with error %d on socket %ld\n",
6945 pfn_WSAGetLastError (), SOCK_HANDLE (fd
)));
6951 /* Some networked filesystems don't like too large writes, so
6952 break them into smaller chunks. See the Comments section of
6953 the MSDN documentation of WriteFile for details behind the
6954 choice of the value of CHUNK below. See also the thread
6955 http://thread.gmane.org/gmane.comp.version-control.git/145294
6956 in the git mailing list. */
6957 const unsigned char *p
= buffer
;
6958 const unsigned chunk
= 30 * 1024 * 1024;
6963 unsigned this_chunk
= count
< chunk
? count
: chunk
;
6964 int n
= _write (fd
, p
, this_chunk
);
6972 else if (n
< this_chunk
)
6982 /* The Windows CRT functions are "optimized for speed", so they don't
6983 check for timezone and DST changes if they were last called less
6984 than 1 minute ago (see http://support.microsoft.com/kb/821231). So
6985 all Emacs features that repeatedly call time functions (e.g.,
6986 display-time) are in real danger of missing timezone and DST
6987 changes. Calling tzset before each localtime call fixes that. */
6989 sys_localtime (const time_t *t
)
6992 return localtime (t
);
6997 /* Try loading LIBRARY_ID from the file(s) specified in
6998 Vdynamic_library_alist. If the library is loaded successfully,
6999 return the handle of the DLL, and record the filename in the
7000 property :loaded-from of LIBRARY_ID. If the library could not be
7001 found, or when it was already loaded (because the handle is not
7002 recorded anywhere, and so is lost after use), return NULL.
7004 We could also save the handle in :loaded-from, but currently
7005 there's no use case for it. */
7007 w32_delayed_load (Lisp_Object library_id
)
7009 HMODULE library_dll
= NULL
;
7011 CHECK_SYMBOL (library_id
);
7013 if (CONSP (Vdynamic_library_alist
)
7014 && NILP (Fassq (library_id
, Vlibrary_cache
)))
7016 Lisp_Object found
= Qnil
;
7017 Lisp_Object dlls
= Fassq (library_id
, Vdynamic_library_alist
);
7020 for (dlls
= XCDR (dlls
); CONSP (dlls
); dlls
= XCDR (dlls
))
7022 CHECK_STRING_CAR (dlls
);
7023 if ((library_dll
= LoadLibrary (SDATA (XCAR (dlls
)))))
7025 char name
[MAX_PATH
];
7028 len
= GetModuleFileNameA (library_dll
, name
, sizeof (name
));
7029 found
= Fcons (XCAR (dlls
),
7031 /* Possibly truncated */
7032 ? make_specified_string (name
, -1, len
, 1)
7038 Fput (library_id
, QCloaded_from
, found
);
7046 check_windows_init_file (void)
7048 /* A common indication that Emacs is not installed properly is when
7049 it cannot find the Windows installation file. If this file does
7050 not exist in the expected place, tell the user. */
7052 if (!noninteractive
&& !inhibit_window_system
7053 /* Vload_path is not yet initialized when we are loading
7055 && NILP (Vpurify_flag
))
7057 Lisp_Object init_file
;
7060 init_file
= build_string ("term/w32-win");
7061 fd
= openp (Vload_path
, init_file
, Fget_load_suffixes (), NULL
, Qnil
);
7064 Lisp_Object load_path_print
= Fprin1_to_string (Vload_path
, Qnil
);
7065 char *init_file_name
= SDATA (init_file
);
7066 char *load_path
= SDATA (load_path_print
);
7067 char *buffer
= alloca (1024
7068 + strlen (init_file_name
)
7069 + strlen (load_path
));
7072 "The Emacs Windows initialization file \"%s.el\" "
7073 "could not be found in your Emacs installation. "
7074 "Emacs checked the following directories for this file:\n"
7076 "When Emacs cannot find this file, it usually means that it "
7077 "was not installed properly, or its distribution file was "
7078 "not unpacked properly.\nSee the README.W32 file in the "
7079 "top-level Emacs directory for more information.",
7080 init_file_name
, load_path
);
7083 "Emacs Abort Dialog",
7084 MB_OK
| MB_ICONEXCLAMATION
| MB_TASKMODAL
);
7085 /* Use the low-level system abort. */
7096 term_ntproc (int ignored
)
7102 /* shutdown the socket interface if necessary */
7109 init_ntproc (int dumping
)
7111 sigset_t initial_mask
= 0;
7113 /* Initialize the socket interface now if available and requested by
7114 the user by defining PRELOAD_WINSOCK; otherwise loading will be
7115 delayed until open-network-stream is called (w32-has-winsock can
7116 also be used to dynamically load or reload winsock).
7118 Conveniently, init_environment is called before us, so
7119 PRELOAD_WINSOCK can be set in the registry. */
7121 /* Always initialize this correctly. */
7124 if (getenv ("PRELOAD_WINSOCK") != NULL
)
7125 init_winsock (TRUE
);
7127 /* Initial preparation for subprocess support: replace our standard
7128 handles with non-inheritable versions. */
7131 HANDLE stdin_save
= INVALID_HANDLE_VALUE
;
7132 HANDLE stdout_save
= INVALID_HANDLE_VALUE
;
7133 HANDLE stderr_save
= INVALID_HANDLE_VALUE
;
7135 parent
= GetCurrentProcess ();
7137 /* ignore errors when duplicating and closing; typically the
7138 handles will be invalid when running as a gui program. */
7139 DuplicateHandle (parent
,
7140 GetStdHandle (STD_INPUT_HANDLE
),
7145 DUPLICATE_SAME_ACCESS
);
7147 DuplicateHandle (parent
,
7148 GetStdHandle (STD_OUTPUT_HANDLE
),
7153 DUPLICATE_SAME_ACCESS
);
7155 DuplicateHandle (parent
,
7156 GetStdHandle (STD_ERROR_HANDLE
),
7161 DUPLICATE_SAME_ACCESS
);
7167 if (stdin_save
!= INVALID_HANDLE_VALUE
)
7168 _open_osfhandle ((intptr_t) stdin_save
, O_TEXT
);
7170 _open ("nul", O_TEXT
| O_NOINHERIT
| O_RDONLY
);
7173 if (stdout_save
!= INVALID_HANDLE_VALUE
)
7174 _open_osfhandle ((intptr_t) stdout_save
, O_TEXT
);
7176 _open ("nul", O_TEXT
| O_NOINHERIT
| O_WRONLY
);
7179 if (stderr_save
!= INVALID_HANDLE_VALUE
)
7180 _open_osfhandle ((intptr_t) stderr_save
, O_TEXT
);
7182 _open ("nul", O_TEXT
| O_NOINHERIT
| O_WRONLY
);
7186 /* unfortunately, atexit depends on implementation of malloc */
7187 /* atexit (term_ntproc); */
7190 /* Make sure we start with all signals unblocked. */
7191 sigprocmask (SIG_SETMASK
, &initial_mask
, NULL
);
7192 signal (SIGABRT
, term_ntproc
);
7196 /* determine which drives are fixed, for GetCachedVolumeInformation */
7198 /* GetDriveType must have trailing backslash. */
7199 char drive
[] = "A:\\";
7201 /* Loop over all possible drive letters */
7202 while (*drive
<= 'Z')
7204 /* Record if this drive letter refers to a fixed drive. */
7205 fixed_drives
[DRIVE_INDEX (*drive
)] =
7206 (GetDriveType (drive
) == DRIVE_FIXED
);
7211 /* Reset the volume info cache. */
7212 volume_cache
= NULL
;
7217 shutdown_handler ensures that buffers' autosave files are
7218 up to date when the user logs off, or the system shuts down.
7221 shutdown_handler (DWORD type
)
7223 /* Ctrl-C and Ctrl-Break are already suppressed, so don't handle them. */
7224 if (type
== CTRL_CLOSE_EVENT
/* User closes console window. */
7225 || type
== CTRL_LOGOFF_EVENT
/* User logs off. */
7226 || type
== CTRL_SHUTDOWN_EVENT
) /* User shutsdown. */
7228 /* Shut down cleanly, making sure autosave files are up to date. */
7229 shut_down_emacs (0, Qnil
);
7232 /* Allow other handlers to handle this signal. */
7237 globals_of_w32 is used to initialize those global variables that
7238 must always be initialized on startup even when the global variable
7239 initialized is non zero (see the function main in emacs.c).
7242 globals_of_w32 (void)
7244 HMODULE kernel32
= GetModuleHandle ("kernel32.dll");
7246 get_process_times_fn
= (GetProcessTimes_Proc
)
7247 GetProcAddress (kernel32
, "GetProcessTimes");
7249 DEFSYM (QCloaded_from
, ":loaded-from");
7251 g_b_init_is_windows_9x
= 0;
7252 g_b_init_open_process_token
= 0;
7253 g_b_init_get_token_information
= 0;
7254 g_b_init_lookup_account_sid
= 0;
7255 g_b_init_get_sid_sub_authority
= 0;
7256 g_b_init_get_sid_sub_authority_count
= 0;
7257 g_b_init_get_security_info
= 0;
7258 g_b_init_get_file_security
= 0;
7259 g_b_init_get_security_descriptor_owner
= 0;
7260 g_b_init_get_security_descriptor_group
= 0;
7261 g_b_init_is_valid_sid
= 0;
7262 g_b_init_create_toolhelp32_snapshot
= 0;
7263 g_b_init_process32_first
= 0;
7264 g_b_init_process32_next
= 0;
7265 g_b_init_open_thread_token
= 0;
7266 g_b_init_impersonate_self
= 0;
7267 g_b_init_revert_to_self
= 0;
7268 g_b_init_get_process_memory_info
= 0;
7269 g_b_init_get_process_working_set_size
= 0;
7270 g_b_init_global_memory_status
= 0;
7271 g_b_init_global_memory_status_ex
= 0;
7272 g_b_init_equal_sid
= 0;
7273 g_b_init_copy_sid
= 0;
7274 g_b_init_get_length_sid
= 0;
7275 g_b_init_get_native_system_info
= 0;
7276 g_b_init_get_system_times
= 0;
7277 g_b_init_create_symbolic_link
= 0;
7278 g_b_init_get_security_descriptor_dacl
= 0;
7279 g_b_init_convert_sd_to_sddl
= 0;
7280 g_b_init_convert_sddl_to_sd
= 0;
7281 g_b_init_is_valid_security_descriptor
= 0;
7282 g_b_init_set_file_security
= 0;
7283 num_of_processors
= 0;
7284 /* The following sets a handler for shutdown notifications for
7285 console apps. This actually applies to Emacs in both console and
7286 GUI modes, since we had to fool windows into thinking emacs is a
7287 console application to get console mode to work. */
7288 SetConsoleCtrlHandler (shutdown_handler
, TRUE
);
7290 /* "None" is the default group name on standalone workstations. */
7291 strcpy (dflt_group_name
, "None");
7293 /* Reset, in case it has some value inherited from dump time. */
7294 w32_stat_get_owner_group
= 0;
7297 /* For make-serial-process */
7299 serial_open (char *port
)
7305 hnd
= CreateFile (port
, GENERIC_READ
| GENERIC_WRITE
, 0, 0,
7306 OPEN_EXISTING
, FILE_FLAG_OVERLAPPED
, 0);
7307 if (hnd
== INVALID_HANDLE_VALUE
)
7308 error ("Could not open %s", port
);
7309 fd
= (int) _open_osfhandle ((intptr_t) hnd
, 0);
7311 error ("Could not open %s", port
);
7315 error ("Could not create child process");
7317 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
7318 fd_info
[ fd
].hnd
= hnd
;
7319 fd_info
[ fd
].flags
|=
7320 FILE_READ
| FILE_WRITE
| FILE_BINARY
| FILE_SERIAL
;
7321 if (fd_info
[ fd
].cp
!= NULL
)
7323 error ("fd_info[fd = %d] is already in use", fd
);
7325 fd_info
[ fd
].cp
= cp
;
7326 cp
->ovl_read
.hEvent
= CreateEvent (NULL
, TRUE
, FALSE
, NULL
);
7327 if (cp
->ovl_read
.hEvent
== NULL
)
7328 error ("Could not create read event");
7329 cp
->ovl_write
.hEvent
= CreateEvent (NULL
, TRUE
, FALSE
, NULL
);
7330 if (cp
->ovl_write
.hEvent
== NULL
)
7331 error ("Could not create write event");
7336 /* For serial-process-configure */
7338 serial_configure (struct Lisp_Process
*p
, Lisp_Object contact
)
7340 Lisp_Object childp2
= Qnil
;
7341 Lisp_Object tem
= Qnil
;
7345 char summary
[4] = "???"; /* This usually becomes "8N1". */
7347 if ((fd_info
[ p
->outfd
].flags
& FILE_SERIAL
) == 0)
7348 error ("Not a serial process");
7349 hnd
= fd_info
[ p
->outfd
].hnd
;
7351 childp2
= Fcopy_sequence (p
->childp
);
7353 /* Initialize timeouts for blocking read and blocking write. */
7354 if (!GetCommTimeouts (hnd
, &ct
))
7355 error ("GetCommTimeouts() failed");
7356 ct
.ReadIntervalTimeout
= 0;
7357 ct
.ReadTotalTimeoutMultiplier
= 0;
7358 ct
.ReadTotalTimeoutConstant
= 0;
7359 ct
.WriteTotalTimeoutMultiplier
= 0;
7360 ct
.WriteTotalTimeoutConstant
= 0;
7361 if (!SetCommTimeouts (hnd
, &ct
))
7362 error ("SetCommTimeouts() failed");
7363 /* Read port attributes and prepare default configuration. */
7364 memset (&dcb
, 0, sizeof (dcb
));
7365 dcb
.DCBlength
= sizeof (DCB
);
7366 if (!GetCommState (hnd
, &dcb
))
7367 error ("GetCommState() failed");
7370 dcb
.fAbortOnError
= FALSE
;
7371 /* dcb.XonLim and dcb.XoffLim are set by GetCommState() */
7376 /* Configure speed. */
7377 if (!NILP (Fplist_member (contact
, QCspeed
)))
7378 tem
= Fplist_get (contact
, QCspeed
);
7380 tem
= Fplist_get (p
->childp
, QCspeed
);
7382 dcb
.BaudRate
= XINT (tem
);
7383 childp2
= Fplist_put (childp2
, QCspeed
, tem
);
7385 /* Configure bytesize. */
7386 if (!NILP (Fplist_member (contact
, QCbytesize
)))
7387 tem
= Fplist_get (contact
, QCbytesize
);
7389 tem
= Fplist_get (p
->childp
, QCbytesize
);
7391 tem
= make_number (8);
7393 if (XINT (tem
) != 7 && XINT (tem
) != 8)
7394 error (":bytesize must be nil (8), 7, or 8");
7395 dcb
.ByteSize
= XINT (tem
);
7396 summary
[0] = XINT (tem
) + '0';
7397 childp2
= Fplist_put (childp2
, QCbytesize
, tem
);
7399 /* Configure parity. */
7400 if (!NILP (Fplist_member (contact
, QCparity
)))
7401 tem
= Fplist_get (contact
, QCparity
);
7403 tem
= Fplist_get (p
->childp
, QCparity
);
7404 if (!NILP (tem
) && !EQ (tem
, Qeven
) && !EQ (tem
, Qodd
))
7405 error (":parity must be nil (no parity), `even', or `odd'");
7406 dcb
.fParity
= FALSE
;
7407 dcb
.Parity
= NOPARITY
;
7408 dcb
.fErrorChar
= FALSE
;
7413 else if (EQ (tem
, Qeven
))
7417 dcb
.Parity
= EVENPARITY
;
7418 dcb
.fErrorChar
= TRUE
;
7420 else if (EQ (tem
, Qodd
))
7424 dcb
.Parity
= ODDPARITY
;
7425 dcb
.fErrorChar
= TRUE
;
7427 childp2
= Fplist_put (childp2
, QCparity
, tem
);
7429 /* Configure stopbits. */
7430 if (!NILP (Fplist_member (contact
, QCstopbits
)))
7431 tem
= Fplist_get (contact
, QCstopbits
);
7433 tem
= Fplist_get (p
->childp
, QCstopbits
);
7435 tem
= make_number (1);
7437 if (XINT (tem
) != 1 && XINT (tem
) != 2)
7438 error (":stopbits must be nil (1 stopbit), 1, or 2");
7439 summary
[2] = XINT (tem
) + '0';
7440 if (XINT (tem
) == 1)
7441 dcb
.StopBits
= ONESTOPBIT
;
7442 else if (XINT (tem
) == 2)
7443 dcb
.StopBits
= TWOSTOPBITS
;
7444 childp2
= Fplist_put (childp2
, QCstopbits
, tem
);
7446 /* Configure flowcontrol. */
7447 if (!NILP (Fplist_member (contact
, QCflowcontrol
)))
7448 tem
= Fplist_get (contact
, QCflowcontrol
);
7450 tem
= Fplist_get (p
->childp
, QCflowcontrol
);
7451 if (!NILP (tem
) && !EQ (tem
, Qhw
) && !EQ (tem
, Qsw
))
7452 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
7453 dcb
.fOutxCtsFlow
= FALSE
;
7454 dcb
.fOutxDsrFlow
= FALSE
;
7455 dcb
.fDtrControl
= DTR_CONTROL_DISABLE
;
7456 dcb
.fDsrSensitivity
= FALSE
;
7457 dcb
.fTXContinueOnXoff
= FALSE
;
7460 dcb
.fRtsControl
= RTS_CONTROL_DISABLE
;
7461 dcb
.XonChar
= 17; /* Control-Q */
7462 dcb
.XoffChar
= 19; /* Control-S */
7465 /* Already configured. */
7467 else if (EQ (tem
, Qhw
))
7469 dcb
.fRtsControl
= RTS_CONTROL_HANDSHAKE
;
7470 dcb
.fOutxCtsFlow
= TRUE
;
7472 else if (EQ (tem
, Qsw
))
7477 childp2
= Fplist_put (childp2
, QCflowcontrol
, tem
);
7479 /* Activate configuration. */
7480 if (!SetCommState (hnd
, &dcb
))
7481 error ("SetCommState() failed");
7483 childp2
= Fplist_put (childp2
, QCsummary
, build_string (summary
));
7484 pset_childp (p
, childp2
);
7490 emacs_gnutls_pull (gnutls_transport_ptr_t p
, void* buf
, size_t sz
)
7495 struct Lisp_Process
*process
= (struct Lisp_Process
*)p
;
7496 int fd
= process
->infd
;
7500 n
= sys_read (fd
, (char*)buf
, sz
);
7507 if (err
== EWOULDBLOCK
)
7509 /* Set a small timeout. */
7510 timeout
= make_emacs_time (1, 0);
7512 FD_SET ((int)fd
, &fdset
);
7514 /* Use select with the timeout to poll the selector. */
7515 sc
= select (fd
+ 1, &fdset
, (SELECT_TYPE
*)0, (SELECT_TYPE
*)0,
7519 continue; /* Try again. */
7521 /* Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN.
7522 Also accept select return 0 as an indicator to EAGAIN. */
7523 if (sc
== 0 || errno
== EWOULDBLOCK
)
7526 err
= errno
; /* Other errors are just passed on. */
7529 emacs_gnutls_transport_set_errno (process
->gnutls_state
, err
);
7536 emacs_gnutls_push (gnutls_transport_ptr_t p
, const void* buf
, size_t sz
)
7538 struct Lisp_Process
*process
= (struct Lisp_Process
*)p
;
7539 int fd
= process
->outfd
;
7540 ssize_t n
= sys_write (fd
, buf
, sz
);
7542 /* 0 or more bytes written means everything went fine. */
7546 /* Negative bytes written means we got an error in errno.
7547 Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
7548 emacs_gnutls_transport_set_errno (process
->gnutls_state
,
7549 errno
== EWOULDBLOCK
? EAGAIN
: errno
);
7553 #endif /* HAVE_GNUTLS */