1 /* Utility and Unix shadow routines for GNU Emacs on the Microsoft Windows API.
2 Copyright (C) 1994-1995, 2000-2013 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
23 #include <mingw_time.h>
24 #include <stddef.h> /* for offsetof */
27 #include <float.h> /* for DBL_EPSILON */
34 #include <time.h> /* must be before nt/inc/sys/time.h, for MinGW64 */
36 #include <sys/utime.h>
39 /* must include CRT headers *before* config.h */
42 #include <mbstring.h> /* for _mbspbrk, _mbslwr, _mbsrchr, ... */
69 #include "epaths.h" /* for SHELL */
74 /* MinGW64 (_W64) defines these in its _mingw.h. */
75 #if defined(__GNUC__) && !defined(_W64)
76 #define _ANONYMOUS_UNION
77 #define _ANONYMOUS_STRUCT
80 /* Some versions of compiler define MEMORYSTATUSEX, some don't, so we
81 use a different name to avoid compilation problems. */
82 typedef struct _MEMORY_STATUS_EX
{
85 DWORDLONG ullTotalPhys
;
86 DWORDLONG ullAvailPhys
;
87 DWORDLONG ullTotalPageFile
;
88 DWORDLONG ullAvailPageFile
;
89 DWORDLONG ullTotalVirtual
;
90 DWORDLONG ullAvailVirtual
;
91 DWORDLONG ullAvailExtendedVirtual
;
92 } MEMORY_STATUS_EX
,*LPMEMORY_STATUS_EX
;
94 /* These are here so that GDB would know about these data types. This
95 allows to attach GDB to Emacs when a fatal exception is triggered
96 and Windows pops up the "application needs to be closed" dialog.
97 At that point, _gnu_exception_handler, the top-level exception
98 handler installed by the MinGW startup code, is somewhere on the
99 call-stack of the main thread, so going to that call frame and
100 looking at the argument to _gnu_exception_handler, which is a
101 PEXCEPTION_POINTERS pointer, can reveal the exception code
102 (excptr->ExceptionRecord->ExceptionCode) and the address where the
103 exception happened (excptr->ExceptionRecord->ExceptionAddress), as
104 well as some additional information specific to the exception. */
105 PEXCEPTION_POINTERS excptr
;
106 PEXCEPTION_RECORD excprec
;
112 #include <tlhelp32.h>
117 #if _WIN32_WINNT < 0x0500
118 #if !defined (__MINGW32__) || __W32API_MAJOR_VERSION < 3 || (__W32API_MAJOR_VERSION == 3 && __W32API_MINOR_VERSION < 15)
119 /* This either is not in psapi.h or guarded by higher value of
120 _WIN32_WINNT than what we use. w32api supplied with MinGW 3.15
121 defines it in psapi.h */
122 typedef struct _PROCESS_MEMORY_COUNTERS_EX
{
124 DWORD PageFaultCount
;
125 SIZE_T PeakWorkingSetSize
;
126 SIZE_T WorkingSetSize
;
127 SIZE_T QuotaPeakPagedPoolUsage
;
128 SIZE_T QuotaPagedPoolUsage
;
129 SIZE_T QuotaPeakNonPagedPoolUsage
;
130 SIZE_T QuotaNonPagedPoolUsage
;
131 SIZE_T PagefileUsage
;
132 SIZE_T PeakPagefileUsage
;
134 } PROCESS_MEMORY_COUNTERS_EX
,*PPROCESS_MEMORY_COUNTERS_EX
;
138 #include <winioctl.h>
144 /* This is not in MinGW's sddl.h (but they are in MSVC headers), so we
145 define them by hand if not already defined. */
146 #ifndef SDDL_REVISION_1
147 #define SDDL_REVISION_1 1
148 #endif /* SDDL_REVISION_1 */
150 #if defined(_MSC_VER) || defined(_W64)
151 /* MSVC and MinGW64 don't provide the definition of
152 REPARSE_DATA_BUFFER and the associated macros, except on ntifs.h,
153 which cannot be included because it triggers conflicts with other
154 Windows API headers. So we define it here by hand. */
156 typedef struct _REPARSE_DATA_BUFFER
{
158 USHORT ReparseDataLength
;
162 USHORT SubstituteNameOffset
;
163 USHORT SubstituteNameLength
;
164 USHORT PrintNameOffset
;
165 USHORT PrintNameLength
;
168 } SymbolicLinkReparseBuffer
;
170 USHORT SubstituteNameOffset
;
171 USHORT SubstituteNameLength
;
172 USHORT PrintNameOffset
;
173 USHORT PrintNameLength
;
175 } MountPointReparseBuffer
;
178 } GenericReparseBuffer
;
180 } REPARSE_DATA_BUFFER
, *PREPARSE_DATA_BUFFER
;
182 #ifndef FILE_DEVICE_FILE_SYSTEM
183 #define FILE_DEVICE_FILE_SYSTEM 9
185 #ifndef METHOD_BUFFERED
186 #define METHOD_BUFFERED 0
188 #ifndef FILE_ANY_ACCESS
189 #define FILE_ANY_ACCESS 0x00000000
192 #define CTL_CODE(t,f,m,a) (((t)<<16)|((a)<<14)|((f)<<2)|(m))
194 /* MinGW64 defines FSCTL_GET_REPARSE_POINT on winioctl.h. */
195 #ifndef FSCTL_GET_REPARSE_POINT
196 #define FSCTL_GET_REPARSE_POINT \
197 CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 42, METHOD_BUFFERED, FILE_ANY_ACCESS)
201 /* TCP connection support. */
202 #include <sys/socket.h>
221 #include <iphlpapi.h> /* should be after winsock2.h */
225 #include "w32common.h"
227 #include "w32select.h"
229 #include "dispextern.h" /* for xstrcasecmp */
230 #include "coding.h" /* for Vlocale_coding_system */
232 #include "careadlinkat.h"
233 #include "allocator.h"
235 /* For serial_configure and serial_open. */
238 typedef HRESULT (WINAPI
* ShGetFolderPath_fn
)
239 (IN HWND
, IN
int, IN HANDLE
, IN DWORD
, OUT
char *);
241 Lisp_Object QCloaded_from
;
243 void globals_of_w32 (void);
244 static DWORD
get_rid (PSID
);
245 static int is_symlink (const char *);
246 static char * chase_symlinks (const char *);
247 static int enable_privilege (LPCTSTR
, BOOL
, TOKEN_PRIVILEGES
*);
248 static int restore_privilege (TOKEN_PRIVILEGES
*);
249 static BOOL WINAPI
revert_to_self (void);
251 extern int sys_access (const char *, int);
252 extern void *e_malloc (size_t);
253 extern int sys_select (int, SELECT_TYPE
*, SELECT_TYPE
*, SELECT_TYPE
*,
254 struct timespec
*, void *);
255 extern int sys_dup (int);
260 /* Initialization states.
262 WARNING: If you add any more such variables for additional APIs,
263 you MUST add initialization for them to globals_of_w32
264 below. This is because these variables might get set
265 to non-NULL values during dumping, but the dumped Emacs
266 cannot reuse those values, because it could be run on a
267 different version of the OS, where API addresses are
269 static BOOL g_b_init_is_windows_9x
;
270 static BOOL g_b_init_open_process_token
;
271 static BOOL g_b_init_get_token_information
;
272 static BOOL g_b_init_lookup_account_sid
;
273 static BOOL g_b_init_get_sid_sub_authority
;
274 static BOOL g_b_init_get_sid_sub_authority_count
;
275 static BOOL g_b_init_get_security_info
;
276 static BOOL g_b_init_get_file_security
;
277 static BOOL g_b_init_get_security_descriptor_owner
;
278 static BOOL g_b_init_get_security_descriptor_group
;
279 static BOOL g_b_init_is_valid_sid
;
280 static BOOL g_b_init_create_toolhelp32_snapshot
;
281 static BOOL g_b_init_process32_first
;
282 static BOOL g_b_init_process32_next
;
283 static BOOL g_b_init_open_thread_token
;
284 static BOOL g_b_init_impersonate_self
;
285 static BOOL g_b_init_revert_to_self
;
286 static BOOL g_b_init_get_process_memory_info
;
287 static BOOL g_b_init_get_process_working_set_size
;
288 static BOOL g_b_init_global_memory_status
;
289 static BOOL g_b_init_global_memory_status_ex
;
290 static BOOL g_b_init_get_length_sid
;
291 static BOOL g_b_init_equal_sid
;
292 static BOOL g_b_init_copy_sid
;
293 static BOOL g_b_init_get_native_system_info
;
294 static BOOL g_b_init_get_system_times
;
295 static BOOL g_b_init_create_symbolic_link
;
296 static BOOL g_b_init_get_security_descriptor_dacl
;
297 static BOOL g_b_init_convert_sd_to_sddl
;
298 static BOOL g_b_init_convert_sddl_to_sd
;
299 static BOOL g_b_init_is_valid_security_descriptor
;
300 static BOOL g_b_init_set_file_security
;
301 static BOOL g_b_init_get_adapters_info
;
304 BEGIN: Wrapper functions around OpenProcessToken
305 and other functions in advapi32.dll that are only
306 supported in Windows NT / 2k / XP
308 /* ** Function pointer typedefs ** */
309 typedef BOOL (WINAPI
* OpenProcessToken_Proc
) (
310 HANDLE ProcessHandle
,
312 PHANDLE TokenHandle
);
313 typedef BOOL (WINAPI
* GetTokenInformation_Proc
) (
315 TOKEN_INFORMATION_CLASS TokenInformationClass
,
316 LPVOID TokenInformation
,
317 DWORD TokenInformationLength
,
318 PDWORD ReturnLength
);
319 typedef BOOL (WINAPI
* GetProcessTimes_Proc
) (
320 HANDLE process_handle
,
321 LPFILETIME creation_time
,
322 LPFILETIME exit_time
,
323 LPFILETIME kernel_time
,
324 LPFILETIME user_time
);
326 GetProcessTimes_Proc get_process_times_fn
= NULL
;
329 const char * const LookupAccountSid_Name
= "LookupAccountSidW";
330 const char * const GetFileSecurity_Name
= "GetFileSecurityW";
331 const char * const SetFileSecurity_Name
= "SetFileSecurityW";
333 const char * const LookupAccountSid_Name
= "LookupAccountSidA";
334 const char * const GetFileSecurity_Name
= "GetFileSecurityA";
335 const char * const SetFileSecurity_Name
= "SetFileSecurityA";
337 typedef BOOL (WINAPI
* LookupAccountSid_Proc
) (
338 LPCTSTR lpSystemName
,
343 LPDWORD cbDomainName
,
344 PSID_NAME_USE peUse
);
345 typedef PDWORD (WINAPI
* GetSidSubAuthority_Proc
) (
348 typedef PUCHAR (WINAPI
* GetSidSubAuthorityCount_Proc
) (
350 typedef DWORD (WINAPI
* GetSecurityInfo_Proc
) (
352 SE_OBJECT_TYPE ObjectType
,
353 SECURITY_INFORMATION SecurityInfo
,
358 PSECURITY_DESCRIPTOR
*ppSecurityDescriptor
);
359 typedef BOOL (WINAPI
* GetFileSecurity_Proc
) (
361 SECURITY_INFORMATION RequestedInformation
,
362 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
364 LPDWORD lpnLengthNeeded
);
365 typedef BOOL (WINAPI
*SetFileSecurity_Proc
) (
367 SECURITY_INFORMATION SecurityInformation
,
368 PSECURITY_DESCRIPTOR pSecurityDescriptor
);
369 typedef BOOL (WINAPI
* GetSecurityDescriptorOwner_Proc
) (
370 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
372 LPBOOL lpbOwnerDefaulted
);
373 typedef BOOL (WINAPI
* GetSecurityDescriptorGroup_Proc
) (
374 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
376 LPBOOL lpbGroupDefaulted
);
377 typedef BOOL (WINAPI
*GetSecurityDescriptorDacl_Proc
) (
378 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
379 LPBOOL lpbDaclPresent
,
381 LPBOOL lpbDaclDefaulted
);
382 typedef BOOL (WINAPI
* IsValidSid_Proc
) (
384 typedef HANDLE (WINAPI
* CreateToolhelp32Snapshot_Proc
) (
386 DWORD th32ProcessID
);
387 typedef BOOL (WINAPI
* Process32First_Proc
) (
389 LPPROCESSENTRY32 lppe
);
390 typedef BOOL (WINAPI
* Process32Next_Proc
) (
392 LPPROCESSENTRY32 lppe
);
393 typedef BOOL (WINAPI
* OpenThreadToken_Proc
) (
397 PHANDLE TokenHandle
);
398 typedef BOOL (WINAPI
* ImpersonateSelf_Proc
) (
399 SECURITY_IMPERSONATION_LEVEL ImpersonationLevel
);
400 typedef BOOL (WINAPI
* RevertToSelf_Proc
) (void);
401 typedef BOOL (WINAPI
* GetProcessMemoryInfo_Proc
) (
403 PPROCESS_MEMORY_COUNTERS ppsmemCounters
,
405 typedef BOOL (WINAPI
* GetProcessWorkingSetSize_Proc
) (
407 PSIZE_T lpMinimumWorkingSetSize
,
408 PSIZE_T lpMaximumWorkingSetSize
);
409 typedef BOOL (WINAPI
* GlobalMemoryStatus_Proc
) (
410 LPMEMORYSTATUS lpBuffer
);
411 typedef BOOL (WINAPI
* GlobalMemoryStatusEx_Proc
) (
412 LPMEMORY_STATUS_EX lpBuffer
);
413 typedef BOOL (WINAPI
* CopySid_Proc
) (
414 DWORD nDestinationSidLength
,
415 PSID pDestinationSid
,
417 typedef BOOL (WINAPI
* EqualSid_Proc
) (
420 typedef DWORD (WINAPI
* GetLengthSid_Proc
) (
422 typedef void (WINAPI
* GetNativeSystemInfo_Proc
) (
423 LPSYSTEM_INFO lpSystemInfo
);
424 typedef BOOL (WINAPI
* GetSystemTimes_Proc
) (
425 LPFILETIME lpIdleTime
,
426 LPFILETIME lpKernelTime
,
427 LPFILETIME lpUserTime
);
428 typedef BOOLEAN (WINAPI
*CreateSymbolicLink_Proc
) (
429 LPTSTR lpSymlinkFileName
,
430 LPTSTR lpTargetFileName
,
432 typedef BOOL (WINAPI
*ConvertStringSecurityDescriptorToSecurityDescriptor_Proc
) (
433 LPCTSTR StringSecurityDescriptor
,
434 DWORD StringSDRevision
,
435 PSECURITY_DESCRIPTOR
*SecurityDescriptor
,
436 PULONG SecurityDescriptorSize
);
437 typedef BOOL (WINAPI
*ConvertSecurityDescriptorToStringSecurityDescriptor_Proc
) (
438 PSECURITY_DESCRIPTOR SecurityDescriptor
,
439 DWORD RequestedStringSDRevision
,
440 SECURITY_INFORMATION SecurityInformation
,
441 LPTSTR
*StringSecurityDescriptor
,
442 PULONG StringSecurityDescriptorLen
);
443 typedef BOOL (WINAPI
*IsValidSecurityDescriptor_Proc
) (PSECURITY_DESCRIPTOR
);
444 typedef DWORD (WINAPI
*GetAdaptersInfo_Proc
) (
445 PIP_ADAPTER_INFO pAdapterInfo
,
448 /* ** A utility function ** */
452 static BOOL s_b_ret
= 0;
453 OSVERSIONINFO os_ver
;
454 if (g_b_init_is_windows_9x
== 0)
456 g_b_init_is_windows_9x
= 1;
457 ZeroMemory (&os_ver
, sizeof (OSVERSIONINFO
));
458 os_ver
.dwOSVersionInfoSize
= sizeof (OSVERSIONINFO
);
459 if (GetVersionEx (&os_ver
))
461 s_b_ret
= (os_ver
.dwPlatformId
== VER_PLATFORM_WIN32_WINDOWS
);
467 static Lisp_Object
ltime (ULONGLONG
);
469 /* Get total user and system times for get-internal-run-time.
470 Returns a list of integers if the times are provided by the OS
471 (NT derivatives), otherwise it returns the result of current-time. */
473 w32_get_internal_run_time (void)
475 if (get_process_times_fn
)
477 FILETIME create
, exit
, kernel
, user
;
478 HANDLE proc
= GetCurrentProcess ();
479 if ((*get_process_times_fn
) (proc
, &create
, &exit
, &kernel
, &user
))
481 LARGE_INTEGER user_int
, kernel_int
, total
;
482 user_int
.LowPart
= user
.dwLowDateTime
;
483 user_int
.HighPart
= user
.dwHighDateTime
;
484 kernel_int
.LowPart
= kernel
.dwLowDateTime
;
485 kernel_int
.HighPart
= kernel
.dwHighDateTime
;
486 total
.QuadPart
= user_int
.QuadPart
+ kernel_int
.QuadPart
;
487 return ltime (total
.QuadPart
);
491 return Fcurrent_time ();
494 /* ** The wrapper functions ** */
497 open_process_token (HANDLE ProcessHandle
,
501 static OpenProcessToken_Proc s_pfn_Open_Process_Token
= NULL
;
502 HMODULE hm_advapi32
= NULL
;
503 if (is_windows_9x () == TRUE
)
507 if (g_b_init_open_process_token
== 0)
509 g_b_init_open_process_token
= 1;
510 hm_advapi32
= LoadLibrary ("Advapi32.dll");
511 s_pfn_Open_Process_Token
=
512 (OpenProcessToken_Proc
) GetProcAddress (hm_advapi32
, "OpenProcessToken");
514 if (s_pfn_Open_Process_Token
== NULL
)
519 s_pfn_Open_Process_Token (
527 get_token_information (HANDLE TokenHandle
,
528 TOKEN_INFORMATION_CLASS TokenInformationClass
,
529 LPVOID TokenInformation
,
530 DWORD TokenInformationLength
,
533 static GetTokenInformation_Proc s_pfn_Get_Token_Information
= NULL
;
534 HMODULE hm_advapi32
= NULL
;
535 if (is_windows_9x () == TRUE
)
539 if (g_b_init_get_token_information
== 0)
541 g_b_init_get_token_information
= 1;
542 hm_advapi32
= LoadLibrary ("Advapi32.dll");
543 s_pfn_Get_Token_Information
=
544 (GetTokenInformation_Proc
) GetProcAddress (hm_advapi32
, "GetTokenInformation");
546 if (s_pfn_Get_Token_Information
== NULL
)
551 s_pfn_Get_Token_Information (
553 TokenInformationClass
,
555 TokenInformationLength
,
561 lookup_account_sid (LPCTSTR lpSystemName
,
566 LPDWORD cbDomainName
,
569 static LookupAccountSid_Proc s_pfn_Lookup_Account_Sid
= NULL
;
570 HMODULE hm_advapi32
= NULL
;
571 if (is_windows_9x () == TRUE
)
575 if (g_b_init_lookup_account_sid
== 0)
577 g_b_init_lookup_account_sid
= 1;
578 hm_advapi32
= LoadLibrary ("Advapi32.dll");
579 s_pfn_Lookup_Account_Sid
=
580 (LookupAccountSid_Proc
) GetProcAddress (hm_advapi32
, LookupAccountSid_Name
);
582 if (s_pfn_Lookup_Account_Sid
== NULL
)
587 s_pfn_Lookup_Account_Sid (
599 get_sid_sub_authority (PSID pSid
, DWORD n
)
601 static GetSidSubAuthority_Proc s_pfn_Get_Sid_Sub_Authority
= NULL
;
602 static DWORD zero
= 0U;
603 HMODULE hm_advapi32
= NULL
;
604 if (is_windows_9x () == TRUE
)
608 if (g_b_init_get_sid_sub_authority
== 0)
610 g_b_init_get_sid_sub_authority
= 1;
611 hm_advapi32
= LoadLibrary ("Advapi32.dll");
612 s_pfn_Get_Sid_Sub_Authority
=
613 (GetSidSubAuthority_Proc
) GetProcAddress (
614 hm_advapi32
, "GetSidSubAuthority");
616 if (s_pfn_Get_Sid_Sub_Authority
== NULL
)
620 return (s_pfn_Get_Sid_Sub_Authority (pSid
, n
));
624 get_sid_sub_authority_count (PSID pSid
)
626 static GetSidSubAuthorityCount_Proc s_pfn_Get_Sid_Sub_Authority_Count
= NULL
;
627 static UCHAR zero
= 0U;
628 HMODULE hm_advapi32
= NULL
;
629 if (is_windows_9x () == TRUE
)
633 if (g_b_init_get_sid_sub_authority_count
== 0)
635 g_b_init_get_sid_sub_authority_count
= 1;
636 hm_advapi32
= LoadLibrary ("Advapi32.dll");
637 s_pfn_Get_Sid_Sub_Authority_Count
=
638 (GetSidSubAuthorityCount_Proc
) GetProcAddress (
639 hm_advapi32
, "GetSidSubAuthorityCount");
641 if (s_pfn_Get_Sid_Sub_Authority_Count
== NULL
)
645 return (s_pfn_Get_Sid_Sub_Authority_Count (pSid
));
649 get_security_info (HANDLE handle
,
650 SE_OBJECT_TYPE ObjectType
,
651 SECURITY_INFORMATION SecurityInfo
,
656 PSECURITY_DESCRIPTOR
*ppSecurityDescriptor
)
658 static GetSecurityInfo_Proc s_pfn_Get_Security_Info
= NULL
;
659 HMODULE hm_advapi32
= NULL
;
660 if (is_windows_9x () == TRUE
)
664 if (g_b_init_get_security_info
== 0)
666 g_b_init_get_security_info
= 1;
667 hm_advapi32
= LoadLibrary ("Advapi32.dll");
668 s_pfn_Get_Security_Info
=
669 (GetSecurityInfo_Proc
) GetProcAddress (
670 hm_advapi32
, "GetSecurityInfo");
672 if (s_pfn_Get_Security_Info
== NULL
)
676 return (s_pfn_Get_Security_Info (handle
, ObjectType
, SecurityInfo
,
677 ppsidOwner
, ppsidGroup
, ppDacl
, ppSacl
,
678 ppSecurityDescriptor
));
682 get_file_security (LPCTSTR lpFileName
,
683 SECURITY_INFORMATION RequestedInformation
,
684 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
686 LPDWORD lpnLengthNeeded
)
688 static GetFileSecurity_Proc s_pfn_Get_File_Security
= NULL
;
689 HMODULE hm_advapi32
= NULL
;
690 if (is_windows_9x () == TRUE
)
695 if (g_b_init_get_file_security
== 0)
697 g_b_init_get_file_security
= 1;
698 hm_advapi32
= LoadLibrary ("Advapi32.dll");
699 s_pfn_Get_File_Security
=
700 (GetFileSecurity_Proc
) GetProcAddress (
701 hm_advapi32
, GetFileSecurity_Name
);
703 if (s_pfn_Get_File_Security
== NULL
)
708 return (s_pfn_Get_File_Security (lpFileName
, RequestedInformation
,
709 pSecurityDescriptor
, nLength
,
714 set_file_security (LPCTSTR lpFileName
,
715 SECURITY_INFORMATION SecurityInformation
,
716 PSECURITY_DESCRIPTOR pSecurityDescriptor
)
718 static SetFileSecurity_Proc s_pfn_Set_File_Security
= NULL
;
719 HMODULE hm_advapi32
= NULL
;
720 if (is_windows_9x () == TRUE
)
725 if (g_b_init_set_file_security
== 0)
727 g_b_init_set_file_security
= 1;
728 hm_advapi32
= LoadLibrary ("Advapi32.dll");
729 s_pfn_Set_File_Security
=
730 (SetFileSecurity_Proc
) GetProcAddress (
731 hm_advapi32
, SetFileSecurity_Name
);
733 if (s_pfn_Set_File_Security
== NULL
)
738 return (s_pfn_Set_File_Security (lpFileName
, SecurityInformation
,
739 pSecurityDescriptor
));
743 get_security_descriptor_owner (PSECURITY_DESCRIPTOR pSecurityDescriptor
,
745 LPBOOL lpbOwnerDefaulted
)
747 static GetSecurityDescriptorOwner_Proc s_pfn_Get_Security_Descriptor_Owner
= NULL
;
748 HMODULE hm_advapi32
= NULL
;
749 if (is_windows_9x () == TRUE
)
754 if (g_b_init_get_security_descriptor_owner
== 0)
756 g_b_init_get_security_descriptor_owner
= 1;
757 hm_advapi32
= LoadLibrary ("Advapi32.dll");
758 s_pfn_Get_Security_Descriptor_Owner
=
759 (GetSecurityDescriptorOwner_Proc
) GetProcAddress (
760 hm_advapi32
, "GetSecurityDescriptorOwner");
762 if (s_pfn_Get_Security_Descriptor_Owner
== NULL
)
767 return (s_pfn_Get_Security_Descriptor_Owner (pSecurityDescriptor
, pOwner
,
772 get_security_descriptor_group (PSECURITY_DESCRIPTOR pSecurityDescriptor
,
774 LPBOOL lpbGroupDefaulted
)
776 static GetSecurityDescriptorGroup_Proc s_pfn_Get_Security_Descriptor_Group
= NULL
;
777 HMODULE hm_advapi32
= NULL
;
778 if (is_windows_9x () == TRUE
)
783 if (g_b_init_get_security_descriptor_group
== 0)
785 g_b_init_get_security_descriptor_group
= 1;
786 hm_advapi32
= LoadLibrary ("Advapi32.dll");
787 s_pfn_Get_Security_Descriptor_Group
=
788 (GetSecurityDescriptorGroup_Proc
) GetProcAddress (
789 hm_advapi32
, "GetSecurityDescriptorGroup");
791 if (s_pfn_Get_Security_Descriptor_Group
== NULL
)
796 return (s_pfn_Get_Security_Descriptor_Group (pSecurityDescriptor
, pGroup
,
801 get_security_descriptor_dacl (PSECURITY_DESCRIPTOR pSecurityDescriptor
,
802 LPBOOL lpbDaclPresent
,
804 LPBOOL lpbDaclDefaulted
)
806 static GetSecurityDescriptorDacl_Proc s_pfn_Get_Security_Descriptor_Dacl
= NULL
;
807 HMODULE hm_advapi32
= NULL
;
808 if (is_windows_9x () == TRUE
)
813 if (g_b_init_get_security_descriptor_dacl
== 0)
815 g_b_init_get_security_descriptor_dacl
= 1;
816 hm_advapi32
= LoadLibrary ("Advapi32.dll");
817 s_pfn_Get_Security_Descriptor_Dacl
=
818 (GetSecurityDescriptorDacl_Proc
) GetProcAddress (
819 hm_advapi32
, "GetSecurityDescriptorDacl");
821 if (s_pfn_Get_Security_Descriptor_Dacl
== NULL
)
826 return (s_pfn_Get_Security_Descriptor_Dacl (pSecurityDescriptor
,
827 lpbDaclPresent
, pDacl
,
832 is_valid_sid (PSID sid
)
834 static IsValidSid_Proc s_pfn_Is_Valid_Sid
= NULL
;
835 HMODULE hm_advapi32
= NULL
;
836 if (is_windows_9x () == TRUE
)
840 if (g_b_init_is_valid_sid
== 0)
842 g_b_init_is_valid_sid
= 1;
843 hm_advapi32
= LoadLibrary ("Advapi32.dll");
845 (IsValidSid_Proc
) GetProcAddress (
846 hm_advapi32
, "IsValidSid");
848 if (s_pfn_Is_Valid_Sid
== NULL
)
852 return (s_pfn_Is_Valid_Sid (sid
));
856 equal_sid (PSID sid1
, PSID sid2
)
858 static EqualSid_Proc s_pfn_Equal_Sid
= NULL
;
859 HMODULE hm_advapi32
= NULL
;
860 if (is_windows_9x () == TRUE
)
864 if (g_b_init_equal_sid
== 0)
866 g_b_init_equal_sid
= 1;
867 hm_advapi32
= LoadLibrary ("Advapi32.dll");
869 (EqualSid_Proc
) GetProcAddress (
870 hm_advapi32
, "EqualSid");
872 if (s_pfn_Equal_Sid
== NULL
)
876 return (s_pfn_Equal_Sid (sid1
, sid2
));
880 get_length_sid (PSID sid
)
882 static GetLengthSid_Proc s_pfn_Get_Length_Sid
= NULL
;
883 HMODULE hm_advapi32
= NULL
;
884 if (is_windows_9x () == TRUE
)
888 if (g_b_init_get_length_sid
== 0)
890 g_b_init_get_length_sid
= 1;
891 hm_advapi32
= LoadLibrary ("Advapi32.dll");
892 s_pfn_Get_Length_Sid
=
893 (GetLengthSid_Proc
) GetProcAddress (
894 hm_advapi32
, "GetLengthSid");
896 if (s_pfn_Get_Length_Sid
== NULL
)
900 return (s_pfn_Get_Length_Sid (sid
));
904 copy_sid (DWORD destlen
, PSID dest
, PSID src
)
906 static CopySid_Proc s_pfn_Copy_Sid
= NULL
;
907 HMODULE hm_advapi32
= NULL
;
908 if (is_windows_9x () == TRUE
)
912 if (g_b_init_copy_sid
== 0)
914 g_b_init_copy_sid
= 1;
915 hm_advapi32
= LoadLibrary ("Advapi32.dll");
917 (CopySid_Proc
) GetProcAddress (
918 hm_advapi32
, "CopySid");
920 if (s_pfn_Copy_Sid
== NULL
)
924 return (s_pfn_Copy_Sid (destlen
, dest
, src
));
928 END: Wrapper functions around OpenProcessToken
929 and other functions in advapi32.dll that are only
930 supported in Windows NT / 2k / XP
934 get_native_system_info (LPSYSTEM_INFO lpSystemInfo
)
936 static GetNativeSystemInfo_Proc s_pfn_Get_Native_System_Info
= NULL
;
937 if (is_windows_9x () != TRUE
)
939 if (g_b_init_get_native_system_info
== 0)
941 g_b_init_get_native_system_info
= 1;
942 s_pfn_Get_Native_System_Info
=
943 (GetNativeSystemInfo_Proc
)GetProcAddress (GetModuleHandle ("kernel32.dll"),
944 "GetNativeSystemInfo");
946 if (s_pfn_Get_Native_System_Info
!= NULL
)
947 s_pfn_Get_Native_System_Info (lpSystemInfo
);
950 lpSystemInfo
->dwNumberOfProcessors
= -1;
954 get_system_times (LPFILETIME lpIdleTime
,
955 LPFILETIME lpKernelTime
,
956 LPFILETIME lpUserTime
)
958 static GetSystemTimes_Proc s_pfn_Get_System_times
= NULL
;
959 if (is_windows_9x () == TRUE
)
963 if (g_b_init_get_system_times
== 0)
965 g_b_init_get_system_times
= 1;
966 s_pfn_Get_System_times
=
967 (GetSystemTimes_Proc
)GetProcAddress (GetModuleHandle ("kernel32.dll"),
970 if (s_pfn_Get_System_times
== NULL
)
972 return (s_pfn_Get_System_times (lpIdleTime
, lpKernelTime
, lpUserTime
));
975 static BOOLEAN WINAPI
976 create_symbolic_link (LPTSTR lpSymlinkFilename
,
977 LPTSTR lpTargetFileName
,
980 static CreateSymbolicLink_Proc s_pfn_Create_Symbolic_Link
= NULL
;
983 if (is_windows_9x () == TRUE
)
988 if (g_b_init_create_symbolic_link
== 0)
990 g_b_init_create_symbolic_link
= 1;
992 s_pfn_Create_Symbolic_Link
=
993 (CreateSymbolicLink_Proc
)GetProcAddress (GetModuleHandle ("kernel32.dll"),
994 "CreateSymbolicLinkW");
996 s_pfn_Create_Symbolic_Link
=
997 (CreateSymbolicLink_Proc
)GetProcAddress (GetModuleHandle ("kernel32.dll"),
998 "CreateSymbolicLinkA");
1001 if (s_pfn_Create_Symbolic_Link
== NULL
)
1007 retval
= s_pfn_Create_Symbolic_Link (lpSymlinkFilename
, lpTargetFileName
,
1009 /* If we were denied creation of the symlink, try again after
1010 enabling the SeCreateSymbolicLinkPrivilege for our process. */
1013 TOKEN_PRIVILEGES priv_current
;
1015 if (enable_privilege (SE_CREATE_SYMBOLIC_LINK_NAME
, TRUE
, &priv_current
))
1017 retval
= s_pfn_Create_Symbolic_Link (lpSymlinkFilename
, lpTargetFileName
,
1019 restore_privilege (&priv_current
);
1027 is_valid_security_descriptor (PSECURITY_DESCRIPTOR pSecurityDescriptor
)
1029 static IsValidSecurityDescriptor_Proc s_pfn_Is_Valid_Security_Descriptor_Proc
= NULL
;
1031 if (is_windows_9x () == TRUE
)
1037 if (g_b_init_is_valid_security_descriptor
== 0)
1039 g_b_init_is_valid_security_descriptor
= 1;
1040 s_pfn_Is_Valid_Security_Descriptor_Proc
=
1041 (IsValidSecurityDescriptor_Proc
)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1042 "IsValidSecurityDescriptor");
1044 if (s_pfn_Is_Valid_Security_Descriptor_Proc
== NULL
)
1050 return s_pfn_Is_Valid_Security_Descriptor_Proc (pSecurityDescriptor
);
1054 convert_sd_to_sddl (PSECURITY_DESCRIPTOR SecurityDescriptor
,
1055 DWORD RequestedStringSDRevision
,
1056 SECURITY_INFORMATION SecurityInformation
,
1057 LPTSTR
*StringSecurityDescriptor
,
1058 PULONG StringSecurityDescriptorLen
)
1060 static ConvertSecurityDescriptorToStringSecurityDescriptor_Proc s_pfn_Convert_SD_To_SDDL
= NULL
;
1063 if (is_windows_9x () == TRUE
)
1069 if (g_b_init_convert_sd_to_sddl
== 0)
1071 g_b_init_convert_sd_to_sddl
= 1;
1073 s_pfn_Convert_SD_To_SDDL
=
1074 (ConvertSecurityDescriptorToStringSecurityDescriptor_Proc
)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1075 "ConvertSecurityDescriptorToStringSecurityDescriptorW");
1077 s_pfn_Convert_SD_To_SDDL
=
1078 (ConvertSecurityDescriptorToStringSecurityDescriptor_Proc
)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1079 "ConvertSecurityDescriptorToStringSecurityDescriptorA");
1082 if (s_pfn_Convert_SD_To_SDDL
== NULL
)
1088 retval
= s_pfn_Convert_SD_To_SDDL (SecurityDescriptor
,
1089 RequestedStringSDRevision
,
1090 SecurityInformation
,
1091 StringSecurityDescriptor
,
1092 StringSecurityDescriptorLen
);
1098 convert_sddl_to_sd (LPCTSTR StringSecurityDescriptor
,
1099 DWORD StringSDRevision
,
1100 PSECURITY_DESCRIPTOR
*SecurityDescriptor
,
1101 PULONG SecurityDescriptorSize
)
1103 static ConvertStringSecurityDescriptorToSecurityDescriptor_Proc s_pfn_Convert_SDDL_To_SD
= NULL
;
1106 if (is_windows_9x () == TRUE
)
1112 if (g_b_init_convert_sddl_to_sd
== 0)
1114 g_b_init_convert_sddl_to_sd
= 1;
1116 s_pfn_Convert_SDDL_To_SD
=
1117 (ConvertStringSecurityDescriptorToSecurityDescriptor_Proc
)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1118 "ConvertStringSecurityDescriptorToSecurityDescriptorW");
1120 s_pfn_Convert_SDDL_To_SD
=
1121 (ConvertStringSecurityDescriptorToSecurityDescriptor_Proc
)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1122 "ConvertStringSecurityDescriptorToSecurityDescriptorA");
1125 if (s_pfn_Convert_SDDL_To_SD
== NULL
)
1131 retval
= s_pfn_Convert_SDDL_To_SD (StringSecurityDescriptor
,
1134 SecurityDescriptorSize
);
1140 get_adapters_info (PIP_ADAPTER_INFO pAdapterInfo
, PULONG pOutBufLen
)
1142 static GetAdaptersInfo_Proc s_pfn_Get_Adapters_Info
= NULL
;
1143 HMODULE hm_iphlpapi
= NULL
;
1145 if (is_windows_9x () == TRUE
)
1146 return ERROR_NOT_SUPPORTED
;
1148 if (g_b_init_get_adapters_info
== 0)
1150 g_b_init_get_adapters_info
= 1;
1151 hm_iphlpapi
= LoadLibrary ("Iphlpapi.dll");
1153 s_pfn_Get_Adapters_Info
= (GetAdaptersInfo_Proc
)
1154 GetProcAddress (hm_iphlpapi
, "GetAdaptersInfo");
1156 if (s_pfn_Get_Adapters_Info
== NULL
)
1157 return ERROR_NOT_SUPPORTED
;
1158 return s_pfn_Get_Adapters_Info (pAdapterInfo
, pOutBufLen
);
1163 /* Return 1 if P is a valid pointer to an object of size SIZE. Return
1164 0 if P is NOT a valid pointer. Return -1 if we cannot validate P.
1166 This is called from alloc.c:valid_pointer_p. */
1168 w32_valid_pointer_p (void *p
, int size
)
1171 HANDLE h
= OpenProcess (PROCESS_VM_READ
, FALSE
, GetCurrentProcessId ());
1175 unsigned char *buf
= alloca (size
);
1176 int retval
= ReadProcessMemory (h
, p
, buf
, size
, &done
);
1185 static char startup_dir
[MAXPATHLEN
];
1187 /* Get the current working directory. */
1189 getcwd (char *dir
, int dirsize
)
1196 if (dirsize
<= strlen (startup_dir
))
1202 if (GetCurrentDirectory (MAXPATHLEN
, dir
) > 0)
1206 /* Emacs doesn't actually change directory itself, it stays in the
1207 same directory where it was started. */
1208 strcpy (dir
, startup_dir
);
1213 /* Emulate getloadavg. */
1215 struct load_sample
{
1222 /* Number of processors on this machine. */
1223 static unsigned num_of_processors
;
1225 /* We maintain 1-sec samples for the last 16 minutes in a circular buffer. */
1226 static struct load_sample samples
[16*60];
1227 static int first_idx
= -1, last_idx
= -1;
1228 static int max_idx
= sizeof (samples
) / sizeof (samples
[0]);
1233 int next_idx
= from
+ 1;
1235 if (next_idx
>= max_idx
)
1244 int prev_idx
= from
- 1;
1247 prev_idx
= max_idx
- 1;
1253 sample_system_load (ULONGLONG
*idle
, ULONGLONG
*kernel
, ULONGLONG
*user
)
1255 SYSTEM_INFO sysinfo
;
1256 FILETIME ft_idle
, ft_user
, ft_kernel
;
1258 /* Initialize the number of processors on this machine. */
1259 if (num_of_processors
<= 0)
1261 get_native_system_info (&sysinfo
);
1262 num_of_processors
= sysinfo
.dwNumberOfProcessors
;
1263 if (num_of_processors
<= 0)
1265 GetSystemInfo (&sysinfo
);
1266 num_of_processors
= sysinfo
.dwNumberOfProcessors
;
1268 if (num_of_processors
<= 0)
1269 num_of_processors
= 1;
1272 /* TODO: Take into account threads that are ready to run, by
1273 sampling the "\System\Processor Queue Length" performance
1274 counter. The code below accounts only for threads that are
1275 actually running. */
1277 if (get_system_times (&ft_idle
, &ft_kernel
, &ft_user
))
1279 ULARGE_INTEGER uidle
, ukernel
, uuser
;
1281 memcpy (&uidle
, &ft_idle
, sizeof (ft_idle
));
1282 memcpy (&ukernel
, &ft_kernel
, sizeof (ft_kernel
));
1283 memcpy (&uuser
, &ft_user
, sizeof (ft_user
));
1284 *idle
= uidle
.QuadPart
;
1285 *kernel
= ukernel
.QuadPart
;
1286 *user
= uuser
.QuadPart
;
1296 /* Produce the load average for a given time interval, using the
1297 samples in the samples[] array. WHICH can be 0, 1, or 2, meaning
1298 1-minute, 5-minute, or 15-minute average, respectively. */
1302 double retval
= -1.0;
1305 double span
= (which
== 0 ? 1.0 : (which
== 1 ? 5.0 : 15.0)) * 60;
1306 time_t now
= samples
[last_idx
].sample_time
;
1308 if (first_idx
!= last_idx
)
1310 for (idx
= buf_prev (last_idx
); ; idx
= buf_prev (idx
))
1312 tdiff
= difftime (now
, samples
[idx
].sample_time
);
1313 if (tdiff
>= span
- 2*DBL_EPSILON
*now
)
1316 samples
[last_idx
].kernel
+ samples
[last_idx
].user
1317 - (samples
[idx
].kernel
+ samples
[idx
].user
);
1318 long double idl
= samples
[last_idx
].idle
- samples
[idx
].idle
;
1320 retval
= (1.0 - idl
/ sys
) * num_of_processors
;
1323 if (idx
== first_idx
)
1332 getloadavg (double loadavg
[], int nelem
)
1335 ULONGLONG idle
, kernel
, user
;
1336 time_t now
= time (NULL
);
1338 /* Store another sample. We ignore samples that are less than 1 sec
1340 if (difftime (now
, samples
[last_idx
].sample_time
) >= 1.0 - 2*DBL_EPSILON
*now
)
1342 sample_system_load (&idle
, &kernel
, &user
);
1343 last_idx
= buf_next (last_idx
);
1344 samples
[last_idx
].sample_time
= now
;
1345 samples
[last_idx
].idle
= idle
;
1346 samples
[last_idx
].kernel
= kernel
;
1347 samples
[last_idx
].user
= user
;
1348 /* If the buffer has more that 15 min worth of samples, discard
1350 if (first_idx
== -1)
1351 first_idx
= last_idx
;
1352 while (first_idx
!= last_idx
1353 && (difftime (now
, samples
[first_idx
].sample_time
)
1354 >= 15.0*60 + 2*DBL_EPSILON
*now
))
1355 first_idx
= buf_next (first_idx
);
1358 for (elem
= 0; elem
< nelem
; elem
++)
1360 double avg
= getavg (elem
);
1364 loadavg
[elem
] = avg
;
1370 /* Emulate getpwuid, getpwnam and others. */
1372 #define PASSWD_FIELD_SIZE 256
1374 static char dflt_passwd_name
[PASSWD_FIELD_SIZE
];
1375 static char dflt_passwd_passwd
[PASSWD_FIELD_SIZE
];
1376 static char dflt_passwd_gecos
[PASSWD_FIELD_SIZE
];
1377 static char dflt_passwd_dir
[PASSWD_FIELD_SIZE
];
1378 static char dflt_passwd_shell
[PASSWD_FIELD_SIZE
];
1380 static struct passwd dflt_passwd
=
1392 static char dflt_group_name
[GNLEN
+1];
1394 static struct group dflt_group
=
1396 /* When group information is not available, we return this as the
1397 group for all files. */
1405 return dflt_passwd
.pw_uid
;
1411 /* I could imagine arguing for checking to see whether the user is
1412 in the Administrators group and returning a UID of 0 for that
1413 case, but I don't know how wise that would be in the long run. */
1420 return dflt_passwd
.pw_gid
;
1430 getpwuid (unsigned uid
)
1432 if (uid
== dflt_passwd
.pw_uid
)
1433 return &dflt_passwd
;
1438 getgrgid (gid_t gid
)
1444 getpwnam (char *name
)
1448 pw
= getpwuid (getuid ());
1452 if (xstrcasecmp (name
, pw
->pw_name
))
1459 init_user_info (void)
1461 /* Find the user's real name by opening the process token and
1462 looking up the name associated with the user-sid in that token.
1464 Use the relative portion of the identifier authority value from
1465 the user-sid as the user id value (same for group id using the
1466 primary group sid from the process token). */
1468 char uname
[UNLEN
+1], gname
[GNLEN
+1], domain
[1025];
1469 DWORD ulength
= sizeof (uname
), dlength
= sizeof (domain
), needed
;
1470 DWORD glength
= sizeof (gname
);
1471 HANDLE token
= NULL
;
1472 SID_NAME_USE user_type
;
1473 unsigned char *buf
= NULL
;
1475 TOKEN_USER user_token
;
1476 TOKEN_PRIMARY_GROUP group_token
;
1479 result
= open_process_token (GetCurrentProcess (), TOKEN_QUERY
, &token
);
1482 result
= get_token_information (token
, TokenUser
, NULL
, 0, &blen
);
1483 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
1485 buf
= xmalloc (blen
);
1486 result
= get_token_information (token
, TokenUser
,
1487 (LPVOID
)buf
, blen
, &needed
);
1490 memcpy (&user_token
, buf
, sizeof (user_token
));
1491 result
= lookup_account_sid (NULL
, user_token
.User
.Sid
,
1493 domain
, &dlength
, &user_type
);
1501 strcpy (dflt_passwd
.pw_name
, uname
);
1502 /* Determine a reasonable uid value. */
1503 if (xstrcasecmp ("administrator", uname
) == 0)
1505 dflt_passwd
.pw_uid
= 500; /* well-known Administrator uid */
1506 dflt_passwd
.pw_gid
= 513; /* well-known None gid */
1510 /* Use the last sub-authority value of the RID, the relative
1511 portion of the SID, as user/group ID. */
1512 dflt_passwd
.pw_uid
= get_rid (user_token
.User
.Sid
);
1514 /* Get group id and name. */
1515 result
= get_token_information (token
, TokenPrimaryGroup
,
1516 (LPVOID
)buf
, blen
, &needed
);
1517 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
1519 buf
= xrealloc (buf
, blen
= needed
);
1520 result
= get_token_information (token
, TokenPrimaryGroup
,
1521 (LPVOID
)buf
, blen
, &needed
);
1525 memcpy (&group_token
, buf
, sizeof (group_token
));
1526 dflt_passwd
.pw_gid
= get_rid (group_token
.PrimaryGroup
);
1527 dlength
= sizeof (domain
);
1528 /* If we can get at the real Primary Group name, use that.
1529 Otherwise, the default group name was already set to
1530 "None" in globals_of_w32. */
1531 if (lookup_account_sid (NULL
, group_token
.PrimaryGroup
,
1532 gname
, &glength
, NULL
, &dlength
,
1534 strcpy (dflt_group_name
, gname
);
1537 dflt_passwd
.pw_gid
= dflt_passwd
.pw_uid
;
1540 /* If security calls are not supported (presumably because we
1541 are running under Windows 9X), fallback to this: */
1542 else if (GetUserName (uname
, &ulength
))
1544 strcpy (dflt_passwd
.pw_name
, uname
);
1545 if (xstrcasecmp ("administrator", uname
) == 0)
1546 dflt_passwd
.pw_uid
= 0;
1548 dflt_passwd
.pw_uid
= 123;
1549 dflt_passwd
.pw_gid
= dflt_passwd
.pw_uid
;
1553 strcpy (dflt_passwd
.pw_name
, "unknown");
1554 dflt_passwd
.pw_uid
= 123;
1555 dflt_passwd
.pw_gid
= 123;
1557 dflt_group
.gr_gid
= dflt_passwd
.pw_gid
;
1559 /* Ensure HOME and SHELL are defined. */
1560 if (getenv ("HOME") == NULL
)
1562 if (getenv ("SHELL") == NULL
)
1565 /* Set dir and shell from environment variables. */
1566 strcpy (dflt_passwd
.pw_dir
, getenv ("HOME"));
1567 strcpy (dflt_passwd
.pw_shell
, getenv ("SHELL"));
1571 CloseHandle (token
);
1577 /* rand () on NT gives us 15 random bits...hack together 30 bits. */
1578 return ((rand () << 15) | rand ());
1587 /* Current codepage for encoding file names. */
1588 static int file_name_codepage
;
1590 /* Return the maximum length in bytes of a multibyte character
1591 sequence encoded in the current ANSI codepage. This is required to
1592 correctly walk the encoded file names one character at a time. */
1594 max_filename_mbslen (void)
1596 /* A simple cache to avoid calling GetCPInfo every time we need to
1597 normalize a file name. The file-name encoding is not supposed to
1598 be changed too frequently, if ever. */
1599 static Lisp_Object last_file_name_encoding
;
1600 static int last_max_mbslen
;
1601 Lisp_Object current_encoding
;
1603 current_encoding
= Vfile_name_coding_system
;
1604 if (NILP (current_encoding
))
1605 current_encoding
= Vdefault_file_name_coding_system
;
1607 if (!EQ (last_file_name_encoding
, current_encoding
))
1611 last_file_name_encoding
= current_encoding
;
1612 /* Default to the current ANSI codepage. */
1613 file_name_codepage
= w32_ansi_code_page
;
1614 if (!NILP (current_encoding
))
1616 char *cpname
= SDATA (SYMBOL_NAME (current_encoding
));
1617 char *cp
= NULL
, *end
;
1620 if (strncmp (cpname
, "cp", 2) == 0)
1622 else if (strncmp (cpname
, "windows-", 8) == 0)
1628 cpnum
= strtol (cp
, &end
, 10);
1629 if (cpnum
&& *end
== '\0' && end
- cp
>= 2)
1630 file_name_codepage
= cpnum
;
1634 if (!file_name_codepage
)
1635 file_name_codepage
= CP_ACP
; /* CP_ACP = 0, but let's not assume that */
1637 if (!GetCPInfo (file_name_codepage
, &cp_info
))
1639 file_name_codepage
= CP_ACP
;
1640 if (!GetCPInfo (file_name_codepage
, &cp_info
))
1643 last_max_mbslen
= cp_info
.MaxCharSize
;
1646 return last_max_mbslen
;
1649 /* Normalize filename by converting all path separators to
1650 the specified separator. Also conditionally convert upper
1651 case path name components to lower case. */
1654 normalize_filename (register char *fp
, char path_sep
, int multibyte
)
1658 int dbcs_p
= max_filename_mbslen () > 1;
1660 /* Multibyte file names are in the Emacs internal representation, so
1661 we can traverse them by bytes with no problems. */
1665 /* Always lower-case drive letters a-z, even if the filesystem
1666 preserves case in filenames.
1667 This is so filenames can be compared by string comparison
1668 functions that are case-sensitive. Even case-preserving filesystems
1669 do not distinguish case in drive letters. */
1671 p2
= CharNextExA (file_name_codepage
, fp
, 0);
1675 if (*p2
== ':' && *fp
>= 'A' && *fp
<= 'Z')
1681 if (multibyte
|| NILP (Vw32_downcase_file_names
))
1685 if (*fp
== '/' || *fp
== '\\')
1690 fp
= CharNextExA (file_name_codepage
, fp
, 0);
1695 sep
= path_sep
; /* convert to this path separator */
1696 elem
= fp
; /* start of current path element */
1699 if (*fp
>= 'a' && *fp
<= 'z')
1700 elem
= 0; /* don't convert this element */
1702 if (*fp
== 0 || *fp
== ':')
1704 sep
= *fp
; /* restore current separator (or 0) */
1705 *fp
= '/'; /* after conversion of this element */
1708 if (*fp
== '/' || *fp
== '\\')
1710 if (elem
&& elem
!= fp
)
1712 *fp
= 0; /* temporary end of string */
1713 _mbslwr (elem
); /* while we convert to lower case */
1715 *fp
= sep
; /* convert (or restore) path separator */
1716 elem
= fp
+ 1; /* next element starts after separator */
1724 fp
= CharNextExA (file_name_codepage
, fp
, 0);
1729 /* Destructively turn backslashes into slashes. MULTIBYTE non-zero
1730 means the file name is a multibyte string in Emacs's internal
1733 dostounix_filename (register char *p
, int multibyte
)
1735 normalize_filename (p
, '/', multibyte
);
1738 /* Destructively turn slashes into backslashes. */
1740 unixtodos_filename (register char *p
)
1742 normalize_filename (p
, '\\', 0);
1745 /* Remove all CR's that are followed by a LF.
1746 (From msdos.c...probably should figure out a way to share it,
1747 although this code isn't going to ever change.) */
1749 crlf_to_lf (register int n
, register unsigned char *buf
)
1751 unsigned char *np
= buf
;
1752 unsigned char *startp
= buf
;
1753 unsigned char *endp
= buf
+ n
;
1757 while (buf
< endp
- 1)
1761 if (*(++buf
) != 0x0a)
1772 /* Parse the root part of file name, if present. Return length and
1773 optionally store pointer to char after root. */
1775 parse_root (char * name
, char ** pPath
)
1777 char * start
= name
;
1782 /* find the root name of the volume if given */
1783 if (isalpha (name
[0]) && name
[1] == ':')
1785 /* skip past drive specifier */
1787 if (IS_DIRECTORY_SEP (name
[0]))
1790 else if (IS_DIRECTORY_SEP (name
[0]) && IS_DIRECTORY_SEP (name
[1]))
1793 int dbcs_p
= max_filename_mbslen () > 1;
1798 if (IS_DIRECTORY_SEP (*name
) && --slashes
== 0)
1801 name
= CharNextExA (file_name_codepage
, name
, 0);
1806 if (IS_DIRECTORY_SEP (name
[0]))
1813 return name
- start
;
1816 /* Get long base name for name; name is assumed to be absolute. */
1818 get_long_basename (char * name
, char * buf
, int size
)
1820 WIN32_FIND_DATA find_data
;
1824 /* must be valid filename, no wild cards or other invalid characters */
1825 if (_mbspbrk (name
, "*?|<>\""))
1828 dir_handle
= FindFirstFile (name
, &find_data
);
1829 if (dir_handle
!= INVALID_HANDLE_VALUE
)
1831 if ((len
= strlen (find_data
.cFileName
)) < size
)
1832 memcpy (buf
, find_data
.cFileName
, len
+ 1);
1835 FindClose (dir_handle
);
1840 /* Get long name for file, if possible (assumed to be absolute). */
1842 w32_get_long_filename (char * name
, char * buf
, int size
)
1847 char full
[ MAX_PATH
];
1850 len
= strlen (name
);
1851 if (len
>= MAX_PATH
)
1854 /* Use local copy for destructive modification. */
1855 memcpy (full
, name
, len
+1);
1856 unixtodos_filename (full
);
1858 /* Copy root part verbatim. */
1859 len
= parse_root (full
, &p
);
1860 memcpy (o
, full
, len
);
1865 while (p
!= NULL
&& *p
)
1868 p
= _mbschr (q
, '\\');
1870 len
= get_long_basename (full
, o
, size
);
1893 is_unc_volume (const char *filename
)
1895 const char *ptr
= filename
;
1897 if (!IS_DIRECTORY_SEP (ptr
[0]) || !IS_DIRECTORY_SEP (ptr
[1]) || !ptr
[2])
1900 if (_mbspbrk (ptr
+ 2, "*?|<>\"\\/"))
1906 /* Emulate the Posix unsetenv. */
1908 unsetenv (const char *name
)
1914 if (name
== NULL
|| *name
== '\0' || strchr (name
, '=') != NULL
)
1919 name_len
= strlen (name
);
1920 /* MS docs says an environment variable cannot be longer than 32K. */
1921 if (name_len
> 32767)
1926 /* It is safe to use 'alloca' with 32K size, since the stack is at
1927 least 2MB, and we set it to 8MB in the link command line. */
1928 var
= alloca (name_len
+ 2);
1929 strncpy (var
, name
, name_len
);
1930 var
[name_len
++] = '=';
1931 var
[name_len
] = '\0';
1932 return _putenv (var
);
1935 /* MS _putenv doesn't support removing a variable when the argument
1936 does not include the '=' character, so we fix that here. */
1938 sys_putenv (char *str
)
1940 const char *const name_end
= strchr (str
, '=');
1942 if (name_end
== NULL
)
1944 /* Remove the variable from the environment. */
1945 return unsetenv (str
);
1948 return _putenv (str
);
1951 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
1954 w32_get_resource (char *key
, LPDWORD lpdwtype
)
1957 HKEY hrootkey
= NULL
;
1960 /* Check both the current user and the local machine to see if
1961 we have any resources. */
1963 if (RegOpenKeyEx (HKEY_CURRENT_USER
, REG_ROOT
, 0, KEY_READ
, &hrootkey
) == ERROR_SUCCESS
)
1967 if (RegQueryValueEx (hrootkey
, key
, NULL
, NULL
, NULL
, &cbData
) == ERROR_SUCCESS
1968 && (lpvalue
= xmalloc (cbData
)) != NULL
1969 && RegQueryValueEx (hrootkey
, key
, NULL
, lpdwtype
, lpvalue
, &cbData
) == ERROR_SUCCESS
)
1971 RegCloseKey (hrootkey
);
1977 RegCloseKey (hrootkey
);
1980 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE
, REG_ROOT
, 0, KEY_READ
, &hrootkey
) == ERROR_SUCCESS
)
1984 if (RegQueryValueEx (hrootkey
, key
, NULL
, NULL
, NULL
, &cbData
) == ERROR_SUCCESS
1985 && (lpvalue
= xmalloc (cbData
)) != NULL
1986 && RegQueryValueEx (hrootkey
, key
, NULL
, lpdwtype
, lpvalue
, &cbData
) == ERROR_SUCCESS
)
1988 RegCloseKey (hrootkey
);
1994 RegCloseKey (hrootkey
);
2000 char *get_emacs_configuration (void);
2003 init_environment (char ** argv
)
2005 static const char * const tempdirs
[] = {
2006 "$TMPDIR", "$TEMP", "$TMP", "c:/"
2011 const int imax
= sizeof (tempdirs
) / sizeof (tempdirs
[0]);
2013 /* Make sure they have a usable $TMPDIR. Many Emacs functions use
2014 temporary files and assume "/tmp" if $TMPDIR is unset, which
2015 will break on DOS/Windows. Refuse to work if we cannot find
2016 a directory, not even "c:/", usable for that purpose. */
2017 for (i
= 0; i
< imax
; i
++)
2019 const char *tmp
= tempdirs
[i
];
2022 tmp
= getenv (tmp
+ 1);
2023 /* Note that `access' can lie to us if the directory resides on a
2024 read-only filesystem, like CD-ROM or a write-protected floppy.
2025 The only way to be really sure is to actually create a file and
2026 see if it succeeds. But I think that's too much to ask. */
2028 /* MSVCRT's _access crashes with D_OK. */
2029 if (tmp
&& faccessat (AT_FDCWD
, tmp
, D_OK
, AT_EACCESS
) == 0)
2031 char * var
= alloca (strlen (tmp
) + 8);
2032 sprintf (var
, "TMPDIR=%s", tmp
);
2033 _putenv (strdup (var
));
2040 Fcons (build_string ("no usable temporary directories found!!"),
2042 "While setting TMPDIR: ");
2044 /* Check for environment variables and use registry settings if they
2045 don't exist. Fallback on default values where applicable. */
2050 char locale_name
[32];
2051 char default_home
[MAX_PATH
];
2054 static const struct env_entry
2060 /* If the default value is NULL, we will use the value from the
2061 outside environment or the Registry, but will not push the
2062 variable into the Emacs environment if it is defined neither
2063 in the Registry nor in the outside environment. */
2065 {"PRELOAD_WINSOCK", NULL
},
2066 {"emacs_dir", "C:/emacs"},
2067 {"EMACSLOADPATH", NULL
},
2068 {"SHELL", "cmdproxy.exe"}, /* perhaps it is somewhere on PATH */
2069 {"EMACSDATA", NULL
},
2070 {"EMACSPATH", NULL
},
2077 #define N_ENV_VARS sizeof (dflt_envvars)/sizeof (dflt_envvars[0])
2079 /* We need to copy dflt_envvars[] and work on the copy because we
2080 don't want the dumped Emacs to inherit the values of
2081 environment variables we saw during dumping (which could be on
2082 a different system). The defaults above must be left intact. */
2083 struct env_entry env_vars
[N_ENV_VARS
];
2085 for (i
= 0; i
< N_ENV_VARS
; i
++)
2086 env_vars
[i
] = dflt_envvars
[i
];
2088 /* For backwards compatibility, check if a .emacs file exists in C:/
2089 If not, then we can try to default to the appdata directory under the
2090 user's profile, which is more likely to be writable. */
2091 if (faccessat (AT_FDCWD
, "C:/.emacs", F_OK
, AT_EACCESS
) != 0)
2093 HRESULT profile_result
;
2094 /* Dynamically load ShGetFolderPath, as it won't exist on versions
2095 of Windows 95 and NT4 that have not been updated to include
2097 ShGetFolderPath_fn get_folder_path
;
2098 get_folder_path
= (ShGetFolderPath_fn
)
2099 GetProcAddress (GetModuleHandle ("shell32.dll"), "SHGetFolderPathA");
2101 if (get_folder_path
!= NULL
)
2103 profile_result
= get_folder_path (NULL
, CSIDL_APPDATA
, NULL
,
2106 /* If we can't get the appdata dir, revert to old behavior. */
2107 if (profile_result
== S_OK
)
2109 env_vars
[0].def_value
= default_home
;
2115 /* Get default locale info and use it for LANG. */
2116 if (GetLocaleInfo (LOCALE_USER_DEFAULT
,
2117 LOCALE_SABBREVLANGNAME
| LOCALE_USE_CP_ACP
,
2118 locale_name
, sizeof (locale_name
)))
2120 for (i
= 0; i
< N_ENV_VARS
; i
++)
2122 if (strcmp (env_vars
[i
].name
, "LANG") == 0)
2124 env_vars
[i
].def_value
= locale_name
;
2130 #define SET_ENV_BUF_SIZE (4 * MAX_PATH) /* to cover EMACSLOADPATH */
2132 /* Treat emacs_dir specially: set it unconditionally based on our
2136 char modname
[MAX_PATH
];
2138 if (!GetModuleFileName (NULL
, modname
, MAX_PATH
))
2140 if ((p
= _mbsrchr (modname
, '\\')) == NULL
)
2144 if ((p
= _mbsrchr (modname
, '\\'))
2145 /* From bin means installed Emacs, from src means uninstalled. */
2146 && (xstrcasecmp (p
, "\\bin") == 0 || xstrcasecmp (p
, "\\src") == 0))
2148 char buf
[SET_ENV_BUF_SIZE
];
2149 int within_build_tree
= xstrcasecmp (p
, "\\src") == 0;
2152 for (p
= modname
; *p
; p
= CharNext (p
))
2153 if (*p
== '\\') *p
= '/';
2155 _snprintf (buf
, sizeof (buf
)-1, "emacs_dir=%s", modname
);
2156 _putenv (strdup (buf
));
2157 /* If we are running from the Posix-like build tree, define
2158 SHELL to point to our own cmdproxy. The loop below will
2159 then disregard PATH_EXEC and the default value. */
2160 if (within_build_tree
)
2162 _snprintf (buf
, sizeof (buf
) - 1,
2163 "SHELL=%s/nt/cmdproxy.exe", modname
);
2164 _putenv (strdup (buf
));
2167 /* Handle running emacs from the build directory: src/oo-spd/i386/ */
2169 /* FIXME: should use substring of get_emacs_configuration ().
2170 But I don't think the Windows build supports alpha, mips etc
2171 anymore, so have taken the easy option for now. */
2172 else if (p
&& (xstrcasecmp (p
, "\\i386") == 0
2173 || xstrcasecmp (p
, "\\AMD64") == 0))
2176 p
= _mbsrchr (modname
, '\\');
2180 p
= _mbsrchr (modname
, '\\');
2181 if (p
&& xstrcasecmp (p
, "\\src") == 0)
2183 char buf
[SET_ENV_BUF_SIZE
];
2186 for (p
= modname
; *p
; p
= CharNext (p
))
2187 if (*p
== '\\') *p
= '/';
2189 _snprintf (buf
, sizeof (buf
)-1, "emacs_dir=%s", modname
);
2190 _putenv (strdup (buf
));
2196 for (i
= 0; i
< N_ENV_VARS
; i
++)
2198 if (!getenv (env_vars
[i
].name
))
2201 char bufc
[SET_ENV_BUF_SIZE
];
2203 if ((lpval
= w32_get_resource (env_vars
[i
].name
, &dwType
)) == NULL
2204 /* Also ignore empty environment variables. */
2209 if (strcmp (env_vars
[i
].name
, "SHELL") == 0)
2211 /* Look for cmdproxy.exe in every directory in
2212 PATH_EXEC. FIXME: This does not find cmdproxy
2213 in nt/ when we run uninstalled. */
2214 char fname
[MAX_PATH
];
2215 const char *pstart
= PATH_EXEC
, *pend
;
2218 pend
= _mbschr (pstart
, ';');
2220 pend
= pstart
+ strlen (pstart
);
2221 /* Be defensive against series of ;;; characters. */
2224 strncpy (fname
, pstart
, pend
- pstart
);
2225 fname
[pend
- pstart
] = '/';
2226 strcpy (&fname
[pend
- pstart
+ 1], "cmdproxy.exe");
2227 ExpandEnvironmentStrings ((LPSTR
) fname
, bufc
,
2229 if (faccessat (AT_FDCWD
, bufc
, F_OK
, AT_EACCESS
)
2243 /* If not found in any directory, use the
2244 default as the last resort. */
2245 lpval
= env_vars
[i
].def_value
;
2246 dwType
= REG_EXPAND_SZ
;
2252 lpval
= env_vars
[i
].def_value
;
2253 dwType
= REG_EXPAND_SZ
;
2255 if (strcmp (env_vars
[i
].name
, "HOME") == 0 && !appdata
)
2256 Vdelayed_warnings_list
2257 = Fcons (listn (CONSTYPE_HEAP
, 2,
2258 intern ("initialization"),
2259 build_string ("Setting HOME to C:\\ by default is deprecated")),
2260 Vdelayed_warnings_list
);
2265 char buf1
[SET_ENV_BUF_SIZE
], buf2
[SET_ENV_BUF_SIZE
];
2267 if (dwType
== REG_EXPAND_SZ
)
2268 ExpandEnvironmentStrings ((LPSTR
) lpval
, buf1
, sizeof (buf1
));
2269 else if (dwType
== REG_SZ
)
2270 strcpy (buf1
, lpval
);
2271 if (dwType
== REG_EXPAND_SZ
|| dwType
== REG_SZ
)
2273 _snprintf (buf2
, sizeof (buf2
)-1, "%s=%s", env_vars
[i
].name
,
2275 _putenv (strdup (buf2
));
2285 /* Rebuild system configuration to reflect invoking system. */
2286 Vsystem_configuration
= build_string (EMACS_CONFIGURATION
);
2288 /* Another special case: on NT, the PATH variable is actually named
2289 "Path" although cmd.exe (perhaps NT itself) arranges for
2290 environment variable lookup and setting to be case insensitive.
2291 However, Emacs assumes a fully case sensitive environment, so we
2292 need to change "Path" to "PATH" to match the expectations of
2293 various elisp packages. We do this by the sneaky method of
2294 modifying the string in the C runtime environ entry.
2296 The same applies to COMSPEC. */
2300 for (envp
= environ
; *envp
; envp
++)
2301 if (_strnicmp (*envp
, "PATH=", 5) == 0)
2302 memcpy (*envp
, "PATH=", 5);
2303 else if (_strnicmp (*envp
, "COMSPEC=", 8) == 0)
2304 memcpy (*envp
, "COMSPEC=", 8);
2307 /* Remember the initial working directory for getcwd. */
2308 /* FIXME: Do we need to resolve possible symlinks in startup_dir?
2309 Does it matter anywhere in Emacs? */
2310 if (!GetCurrentDirectory (MAXPATHLEN
, startup_dir
))
2314 static char modname
[MAX_PATH
];
2316 if (!GetModuleFileName (NULL
, modname
, MAX_PATH
))
2321 /* Determine if there is a middle mouse button, to allow parse_button
2322 to decide whether right mouse events should be mouse-2 or
2324 w32_num_mouse_buttons
= GetSystemMetrics (SM_CMOUSEBUTTONS
);
2329 /* Called from expand-file-name when default-directory is not a string. */
2332 emacs_root_dir (void)
2334 static char root_dir
[FILENAME_MAX
];
2337 p
= getenv ("emacs_dir");
2340 strcpy (root_dir
, p
);
2341 root_dir
[parse_root (root_dir
, NULL
)] = '\0';
2342 dostounix_filename (root_dir
, 0);
2346 /* We don't have scripts to automatically determine the system configuration
2347 for Emacs before it's compiled, and we don't want to have to make the
2348 user enter it, so we define EMACS_CONFIGURATION to invoke this runtime
2352 get_emacs_configuration (void)
2354 char *arch
, *oem
, *os
;
2356 static char configuration_buffer
[32];
2358 /* Determine the processor type. */
2359 switch (get_processor_type ())
2362 #ifdef PROCESSOR_INTEL_386
2363 case PROCESSOR_INTEL_386
:
2364 case PROCESSOR_INTEL_486
:
2365 case PROCESSOR_INTEL_PENTIUM
:
2373 #ifdef PROCESSOR_AMD_X8664
2374 case PROCESSOR_AMD_X8664
:
2379 #ifdef PROCESSOR_MIPS_R2000
2380 case PROCESSOR_MIPS_R2000
:
2381 case PROCESSOR_MIPS_R3000
:
2382 case PROCESSOR_MIPS_R4000
:
2387 #ifdef PROCESSOR_ALPHA_21064
2388 case PROCESSOR_ALPHA_21064
:
2398 /* Use the OEM field to reflect the compiler/library combination. */
2400 #define COMPILER_NAME "msvc"
2403 #define COMPILER_NAME "mingw"
2405 #define COMPILER_NAME "unknown"
2408 oem
= COMPILER_NAME
;
2410 switch (osinfo_cache
.dwPlatformId
) {
2411 case VER_PLATFORM_WIN32_NT
:
2413 build_num
= osinfo_cache
.dwBuildNumber
;
2415 case VER_PLATFORM_WIN32_WINDOWS
:
2416 if (osinfo_cache
.dwMinorVersion
== 0) {
2421 build_num
= LOWORD (osinfo_cache
.dwBuildNumber
);
2423 case VER_PLATFORM_WIN32s
:
2424 /* Not supported, should not happen. */
2426 build_num
= LOWORD (osinfo_cache
.dwBuildNumber
);
2434 if (osinfo_cache
.dwPlatformId
== VER_PLATFORM_WIN32_NT
) {
2435 sprintf (configuration_buffer
, "%s-%s-%s%d.%d.%d", arch
, oem
, os
,
2436 get_w32_major_version (), get_w32_minor_version (), build_num
);
2438 sprintf (configuration_buffer
, "%s-%s-%s.%d", arch
, oem
, os
, build_num
);
2441 return configuration_buffer
;
2445 get_emacs_configuration_options (void)
2447 static char *options_buffer
;
2448 char cv
[32]; /* Enough for COMPILER_VERSION. */
2450 cv
, /* To be filled later. */
2454 #ifdef ENABLE_CHECKING
2455 " --enable-checking",
2457 /* configure.bat already sets USER_CFLAGS and USER_LDFLAGS
2458 with a starting space to save work here. */
2460 " --cflags", USER_CFLAGS
,
2463 " --ldflags", USER_LDFLAGS
,
2470 /* Work out the effective configure options for this build. */
2472 #define COMPILER_VERSION "--with-msvc (%d.%02d)", _MSC_VER / 100, _MSC_VER % 100
2475 #define COMPILER_VERSION "--with-gcc (%d.%d)", __GNUC__, __GNUC_MINOR__
2477 #define COMPILER_VERSION ""
2481 if (_snprintf (cv
, sizeof (cv
) - 1, COMPILER_VERSION
) < 0)
2482 return "Error: not enough space for compiler version";
2483 cv
[sizeof (cv
) - 1] = '\0';
2485 for (i
= 0; options
[i
]; i
++)
2486 size
+= strlen (options
[i
]);
2488 options_buffer
= xmalloc (size
+ 1);
2489 options_buffer
[0] = '\0';
2491 for (i
= 0; options
[i
]; i
++)
2492 strcat (options_buffer
, options
[i
]);
2494 return options_buffer
;
2498 #include <sys/timeb.h>
2500 /* Emulate gettimeofday (Ulrich Leodolter, 1/11/95). */
2502 gettimeofday (struct timeval
*__restrict tv
, struct timezone
*__restrict tz
)
2507 tv
->tv_sec
= tb
.time
;
2508 tv
->tv_usec
= tb
.millitm
* 1000L;
2509 /* Implementation note: _ftime sometimes doesn't update the dstflag
2510 according to the new timezone when the system timezone is
2511 changed. We could fix that by using GetSystemTime and
2512 GetTimeZoneInformation, but that doesn't seem necessary, since
2513 Emacs always calls gettimeofday with the 2nd argument NULL (see
2514 current_emacs_time). */
2517 tz
->tz_minuteswest
= tb
.timezone
; /* minutes west of Greenwich */
2518 tz
->tz_dsttime
= tb
.dstflag
; /* type of dst correction */
2523 /* Emulate fdutimens. */
2525 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2526 TIMESPEC[0] and TIMESPEC[1], respectively.
2527 FD must be either negative -- in which case it is ignored --
2528 or a file descriptor that is open on FILE.
2529 If FD is nonnegative, then FILE can be NULL, which means
2530 use just futimes instead of utimes.
2531 If TIMESPEC is null, FAIL.
2532 Return 0 on success, -1 (setting errno) on failure. */
2535 fdutimens (int fd
, char const *file
, struct timespec
const timespec
[2])
2542 if (fd
< 0 && !file
)
2547 /* _futime's prototype defines 2nd arg as having the type 'struct
2548 _utimbuf', while utime needs to accept 'struct utimbuf' for
2549 compatibility with Posix. So we need to use 2 different (but
2550 equivalent) types to avoid compiler warnings, sigh. */
2553 struct _utimbuf _ut
;
2555 _ut
.actime
= timespec
[0].tv_sec
;
2556 _ut
.modtime
= timespec
[1].tv_sec
;
2557 return _futime (fd
, &_ut
);
2563 ut
.actime
= timespec
[0].tv_sec
;
2564 ut
.modtime
= timespec
[1].tv_sec
;
2565 /* Call 'utime', which is implemented below, not the MS library
2566 function, which fails on directories. */
2567 return utime (file
, &ut
);
2572 /* ------------------------------------------------------------------------- */
2573 /* IO support and wrapper functions for the Windows API. */
2574 /* ------------------------------------------------------------------------- */
2576 /* Place a wrapper around the MSVC version of ctime. It returns NULL
2577 on network directories, so we handle that case here.
2578 (Ulrich Leodolter, 1/11/95). */
2580 sys_ctime (const time_t *t
)
2582 char *str
= (char *) ctime (t
);
2583 return (str
? str
: "Sun Jan 01 00:00:00 1970");
2586 /* Emulate sleep...we could have done this with a define, but that
2587 would necessitate including windows.h in the files that used it.
2588 This is much easier. */
2590 sys_sleep (int seconds
)
2592 Sleep (seconds
* 1000);
2595 /* Internal MSVC functions for low-level descriptor munging */
2596 extern int __cdecl
_set_osfhnd (int fd
, long h
);
2597 extern int __cdecl
_free_osfhnd (int fd
);
2599 /* parallel array of private info on file handles */
2600 filedesc fd_info
[ MAXDESC
];
2602 typedef struct volume_info_data
{
2603 struct volume_info_data
* next
;
2605 /* time when info was obtained */
2608 /* actual volume info */
2617 /* Global referenced by various functions. */
2618 static volume_info_data volume_info
;
2620 /* Vector to indicate which drives are local and fixed (for which cached
2621 data never expires). */
2622 static BOOL fixed_drives
[26];
2624 /* Consider cached volume information to be stale if older than 10s,
2625 at least for non-local drives. Info for fixed drives is never stale. */
2626 #define DRIVE_INDEX( c ) ( (c) <= 'Z' ? (c) - 'A' : (c) - 'a' )
2627 #define VOLINFO_STILL_VALID( root_dir, info ) \
2628 ( ( isalpha (root_dir[0]) && \
2629 fixed_drives[ DRIVE_INDEX (root_dir[0]) ] ) \
2630 || GetTickCount () - info->timestamp < 10000 )
2632 /* Cache support functions. */
2634 /* Simple linked list with linear search is sufficient. */
2635 static volume_info_data
*volume_cache
= NULL
;
2637 static volume_info_data
*
2638 lookup_volume_info (char * root_dir
)
2640 volume_info_data
* info
;
2642 for (info
= volume_cache
; info
; info
= info
->next
)
2643 if (xstrcasecmp (info
->root_dir
, root_dir
) == 0)
2649 add_volume_info (char * root_dir
, volume_info_data
* info
)
2651 info
->root_dir
= xstrdup (root_dir
);
2652 info
->next
= volume_cache
;
2653 volume_cache
= info
;
2657 /* Wrapper for GetVolumeInformation, which uses caching to avoid
2658 performance penalty (~2ms on 486 for local drives, 7.5ms for local
2659 cdrom drive, ~5-10ms or more for remote drives on LAN). */
2660 static volume_info_data
*
2661 GetCachedVolumeInformation (char * root_dir
)
2663 volume_info_data
* info
;
2664 char default_root
[ MAX_PATH
];
2666 /* NULL for root_dir means use root from current directory. */
2667 if (root_dir
== NULL
)
2669 if (GetCurrentDirectory (MAX_PATH
, default_root
) == 0)
2671 parse_root (default_root
, &root_dir
);
2673 root_dir
= default_root
;
2676 /* Local fixed drives can be cached permanently. Removable drives
2677 cannot be cached permanently, since the volume name and serial
2678 number (if nothing else) can change. Remote drives should be
2679 treated as if they are removable, since there is no sure way to
2680 tell whether they are or not. Also, the UNC association of drive
2681 letters mapped to remote volumes can be changed at any time (even
2682 by other processes) without notice.
2684 As a compromise, so we can benefit from caching info for remote
2685 volumes, we use a simple expiry mechanism to invalidate cache
2686 entries that are more than ten seconds old. */
2689 /* No point doing this, because WNetGetConnection is even slower than
2690 GetVolumeInformation, consistently taking ~50ms on a 486 (FWIW,
2691 GetDriveType is about the only call of this type which does not
2692 involve network access, and so is extremely quick). */
2694 /* Map drive letter to UNC if remote. */
2695 if (isalpha (root_dir
[0]) && !fixed
[DRIVE_INDEX (root_dir
[0])])
2697 char remote_name
[ 256 ];
2698 char drive
[3] = { root_dir
[0], ':' };
2700 if (WNetGetConnection (drive
, remote_name
, sizeof (remote_name
))
2702 /* do something */ ;
2706 info
= lookup_volume_info (root_dir
);
2708 if (info
== NULL
|| ! VOLINFO_STILL_VALID (root_dir
, info
))
2716 /* Info is not cached, or is stale. */
2717 if (!GetVolumeInformation (root_dir
,
2718 name
, sizeof (name
),
2722 type
, sizeof (type
)))
2725 /* Cache the volume information for future use, overwriting existing
2726 entry if present. */
2729 info
= xmalloc (sizeof (volume_info_data
));
2730 add_volume_info (root_dir
, info
);
2738 info
->name
= xstrdup (name
);
2739 info
->serialnum
= serialnum
;
2740 info
->maxcomp
= maxcomp
;
2741 info
->flags
= flags
;
2742 info
->type
= xstrdup (type
);
2743 info
->timestamp
= GetTickCount ();
2749 /* Get information on the volume where NAME is held; set path pointer to
2750 start of pathname in NAME (past UNC header\volume header if present),
2751 if pPath is non-NULL.
2753 Note: if NAME includes symlinks, the information is for the volume
2754 of the symlink, not of its target. That's because, even though
2755 GetVolumeInformation returns information about the symlink target
2756 of its argument, we only pass the root directory to
2757 GetVolumeInformation, not the full NAME. */
2759 get_volume_info (const char * name
, const char ** pPath
)
2761 char temp
[MAX_PATH
];
2762 char *rootname
= NULL
; /* default to current volume */
2763 volume_info_data
* info
;
2768 /* Find the root name of the volume if given. */
2769 if (isalpha (name
[0]) && name
[1] == ':')
2777 else if (IS_DIRECTORY_SEP (name
[0]) && IS_DIRECTORY_SEP (name
[1]))
2781 int dbcs_p
= max_filename_mbslen () > 1;
2786 if (IS_DIRECTORY_SEP (*name
) && --slashes
== 0)
2792 const char *p
= name
;
2794 name
= CharNextExA (file_name_codepage
, name
, 0);
2795 memcpy (str
, p
, name
- p
);
2808 info
= GetCachedVolumeInformation (rootname
);
2811 /* Set global referenced by other functions. */
2812 volume_info
= *info
;
2818 /* Determine if volume is FAT format (ie. only supports short 8.3
2819 names); also set path pointer to start of pathname in name, if
2820 pPath is non-NULL. */
2822 is_fat_volume (const char * name
, const char ** pPath
)
2824 if (get_volume_info (name
, pPath
))
2825 return (volume_info
.maxcomp
== 12);
2829 /* Map filename to a valid 8.3 name if necessary.
2830 The result is a pointer to a static buffer, so CAVEAT EMPTOR! */
2832 map_w32_filename (const char * name
, const char ** pPath
)
2834 static char shortname
[MAX_PATH
];
2835 char * str
= shortname
;
2838 const char * save_name
= name
;
2840 if (strlen (name
) >= MAX_PATH
)
2842 /* Return a filename which will cause callers to fail. */
2843 strcpy (shortname
, "?");
2847 if (is_fat_volume (name
, (const char **)&path
)) /* truncate to 8.3 */
2849 register int left
= 8; /* maximum number of chars in part */
2850 register int extn
= 0; /* extension added? */
2851 register int dots
= 2; /* maximum number of dots allowed */
2854 *str
++ = *name
++; /* skip past UNC header */
2856 while ((c
= *name
++))
2863 *str
++ = (c
== ':' ? ':' : '\\');
2864 extn
= 0; /* reset extension flags */
2865 dots
= 2; /* max 2 dots */
2866 left
= 8; /* max length 8 for main part */
2871 /* Convert path components of the form .xxx to _xxx,
2872 but leave . and .. as they are. This allows .emacs
2873 to be read as _emacs, for example. */
2877 IS_DIRECTORY_SEP (*name
))
2892 extn
= 1; /* we've got an extension */
2893 left
= 3; /* 3 chars in extension */
2897 /* any embedded dots after the first are converted to _ */
2902 case '#': /* don't lose these, they're important */
2904 str
[-1] = c
; /* replace last character of part */
2909 *str
++ = tolower (c
); /* map to lower case (looks nicer) */
2911 dots
= 0; /* started a path component */
2920 strcpy (shortname
, name
);
2921 unixtodos_filename (shortname
);
2925 *pPath
= shortname
+ (path
- save_name
);
2931 is_exec (const char * name
)
2933 char * p
= strrchr (name
, '.');
2936 && (xstrcasecmp (p
, ".exe") == 0 ||
2937 xstrcasecmp (p
, ".com") == 0 ||
2938 xstrcasecmp (p
, ".bat") == 0 ||
2939 xstrcasecmp (p
, ".cmd") == 0));
2942 /* Emulate the Unix directory procedures opendir, closedir,
2943 and readdir. We can't use the procedures supplied in sysdep.c,
2944 so we provide them here. */
2946 struct dirent dir_static
; /* simulated directory contents */
2947 static HANDLE dir_find_handle
= INVALID_HANDLE_VALUE
;
2948 static int dir_is_fat
;
2949 static char dir_pathname
[MAXPATHLEN
+1];
2950 static WIN32_FIND_DATA dir_find_data
;
2952 /* Support shares on a network resource as subdirectories of a read-only
2954 static HANDLE wnet_enum_handle
= INVALID_HANDLE_VALUE
;
2955 static HANDLE
open_unc_volume (const char *);
2956 static char *read_unc_volume (HANDLE
, char *, int);
2957 static void close_unc_volume (HANDLE
);
2960 opendir (const char *filename
)
2964 /* Opening is done by FindFirstFile. However, a read is inherent to
2965 this operation, so we defer the open until read time. */
2967 if (dir_find_handle
!= INVALID_HANDLE_VALUE
)
2969 if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
2972 /* Note: We don't support traversal of UNC volumes via symlinks.
2973 Doing so would mean punishing 99.99% of use cases by resolving
2974 all the possible symlinks in FILENAME, recursively. */
2975 if (is_unc_volume (filename
))
2977 wnet_enum_handle
= open_unc_volume (filename
);
2978 if (wnet_enum_handle
== INVALID_HANDLE_VALUE
)
2982 if (!(dirp
= (DIR *) malloc (sizeof (DIR))))
2989 strncpy (dir_pathname
, map_w32_filename (filename
, NULL
), MAXPATHLEN
);
2990 dir_pathname
[MAXPATHLEN
] = '\0';
2991 /* Note: We don't support symlinks to file names on FAT volumes.
2992 Doing so would mean punishing 99.99% of use cases by resolving
2993 all the possible symlinks in FILENAME, recursively. */
2994 dir_is_fat
= is_fat_volume (filename
, NULL
);
3000 closedir (DIR *dirp
)
3002 /* If we have a find-handle open, close it. */
3003 if (dir_find_handle
!= INVALID_HANDLE_VALUE
)
3005 FindClose (dir_find_handle
);
3006 dir_find_handle
= INVALID_HANDLE_VALUE
;
3008 else if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
3010 close_unc_volume (wnet_enum_handle
);
3011 wnet_enum_handle
= INVALID_HANDLE_VALUE
;
3013 xfree ((char *) dirp
);
3019 int downcase
= !NILP (Vw32_downcase_file_names
);
3021 if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
3023 if (!read_unc_volume (wnet_enum_handle
,
3024 dir_find_data
.cFileName
,
3028 /* If we aren't dir_finding, do a find-first, otherwise do a find-next. */
3029 else if (dir_find_handle
== INVALID_HANDLE_VALUE
)
3031 char filename
[MAXNAMLEN
+ 3];
3033 int dbcs_p
= max_filename_mbslen () > 1;
3035 strcpy (filename
, dir_pathname
);
3036 ln
= strlen (filename
) - 1;
3039 if (!IS_DIRECTORY_SEP (filename
[ln
]))
3040 strcat (filename
, "\\");
3044 char *end
= filename
+ ln
+ 1;
3045 char *last_char
= CharPrevExA (file_name_codepage
, filename
, end
, 0);
3047 if (!IS_DIRECTORY_SEP (*last_char
))
3048 strcat (filename
, "\\");
3050 strcat (filename
, "*");
3052 /* Note: No need to resolve symlinks in FILENAME, because
3053 FindFirst opens the directory that is the target of a
3055 dir_find_handle
= FindFirstFile (filename
, &dir_find_data
);
3057 if (dir_find_handle
== INVALID_HANDLE_VALUE
)
3062 if (!FindNextFile (dir_find_handle
, &dir_find_data
))
3066 /* Emacs never uses this value, so don't bother making it match
3067 value returned by stat(). */
3068 dir_static
.d_ino
= 1;
3070 strcpy (dir_static
.d_name
, dir_find_data
.cFileName
);
3072 /* If the file name in cFileName[] includes `?' characters, it means
3073 the original file name used characters that cannot be represented
3074 by the current ANSI codepage. To avoid total lossage, retrieve
3075 the short 8+3 alias of the long file name. */
3076 if (_mbspbrk (dir_static
.d_name
, "?"))
3078 strcpy (dir_static
.d_name
, dir_find_data
.cAlternateFileName
);
3079 downcase
= 1; /* 8+3 aliases are returned in all caps */
3081 dir_static
.d_namlen
= strlen (dir_static
.d_name
);
3082 dir_static
.d_reclen
= sizeof (struct dirent
) - MAXNAMLEN
+ 3 +
3083 dir_static
.d_namlen
- dir_static
.d_namlen
% 4;
3085 /* If the file name in cFileName[] includes `?' characters, it means
3086 the original file name used characters that cannot be represented
3087 by the current ANSI codepage. To avoid total lossage, retrieve
3088 the short 8+3 alias of the long file name. */
3089 if (_mbspbrk (dir_find_data
.cFileName
, "?"))
3091 strcpy (dir_static
.d_name
, dir_find_data
.cAlternateFileName
);
3092 /* 8+3 aliases are returned in all caps, which could break
3093 various alists that look at filenames' extensions. */
3097 strcpy (dir_static
.d_name
, dir_find_data
.cFileName
);
3098 dir_static
.d_namlen
= strlen (dir_static
.d_name
);
3100 _mbslwr (dir_static
.d_name
);
3104 int dbcs_p
= max_filename_mbslen () > 1;
3105 for (p
= dir_static
.d_name
; *p
; )
3107 if (*p
>= 'a' && *p
<= 'z')
3110 p
= CharNextExA (file_name_codepage
, p
, 0);
3115 _mbslwr (dir_static
.d_name
);
3122 open_unc_volume (const char *path
)
3128 nr
.dwScope
= RESOURCE_GLOBALNET
;
3129 nr
.dwType
= RESOURCETYPE_DISK
;
3130 nr
.dwDisplayType
= RESOURCEDISPLAYTYPE_SERVER
;
3131 nr
.dwUsage
= RESOURCEUSAGE_CONTAINER
;
3132 nr
.lpLocalName
= NULL
;
3133 nr
.lpRemoteName
= (LPSTR
)map_w32_filename (path
, NULL
);
3134 nr
.lpComment
= NULL
;
3135 nr
.lpProvider
= NULL
;
3137 result
= WNetOpenEnum (RESOURCE_GLOBALNET
, RESOURCETYPE_DISK
,
3138 RESOURCEUSAGE_CONNECTABLE
, &nr
, &henum
);
3140 if (result
== NO_ERROR
)
3143 return INVALID_HANDLE_VALUE
;
3147 read_unc_volume (HANDLE henum
, char *readbuf
, int size
)
3151 DWORD bufsize
= 512;
3154 int dbcs_p
= max_filename_mbslen () > 1;
3157 buffer
= alloca (bufsize
);
3158 result
= WNetEnumResource (henum
, &count
, buffer
, &bufsize
);
3159 if (result
!= NO_ERROR
)
3162 /* WNetEnumResource returns \\resource\share...skip forward to "share". */
3163 ptr
= ((LPNETRESOURCE
) buffer
)->lpRemoteName
;
3166 while (*ptr
&& !IS_DIRECTORY_SEP (*ptr
)) ptr
++;
3169 while (*ptr
&& !IS_DIRECTORY_SEP (*ptr
))
3170 ptr
= CharNextExA (file_name_codepage
, ptr
, 0);
3174 strncpy (readbuf
, ptr
, size
);
3179 close_unc_volume (HANDLE henum
)
3181 if (henum
!= INVALID_HANDLE_VALUE
)
3182 WNetCloseEnum (henum
);
3186 unc_volume_file_attributes (const char *path
)
3191 henum
= open_unc_volume (path
);
3192 if (henum
== INVALID_HANDLE_VALUE
)
3195 attrs
= FILE_ATTRIBUTE_READONLY
| FILE_ATTRIBUTE_DIRECTORY
;
3197 close_unc_volume (henum
);
3202 /* Ensure a network connection is authenticated. */
3204 logon_network_drive (const char *path
)
3206 NETRESOURCE resource
;
3207 char share
[MAX_PATH
];
3214 if (IS_DIRECTORY_SEP (path
[0]) && IS_DIRECTORY_SEP (path
[1]))
3215 drvtype
= DRIVE_REMOTE
;
3216 else if (path
[0] == '\0' || path
[1] != ':')
3217 drvtype
= GetDriveType (NULL
);
3224 drvtype
= GetDriveType (drive
);
3227 /* Only logon to networked drives. */
3228 if (drvtype
!= DRIVE_REMOTE
)
3232 strncpy (share
, path
, MAX_PATH
);
3233 /* Truncate to just server and share name. */
3234 dbcs_p
= max_filename_mbslen () > 1;
3235 for (p
= share
+ 2; *p
&& p
< share
+ MAX_PATH
; )
3237 if (IS_DIRECTORY_SEP (*p
) && ++n_slashes
> 3)
3243 p
= CharNextExA (file_name_codepage
, p
, 0);
3248 resource
.dwType
= RESOURCETYPE_DISK
;
3249 resource
.lpLocalName
= NULL
;
3250 resource
.lpRemoteName
= share
;
3251 resource
.lpProvider
= NULL
;
3253 WNetAddConnection2 (&resource
, NULL
, NULL
, CONNECT_INTERACTIVE
);
3256 /* Emulate faccessat(2). */
3258 faccessat (int dirfd
, const char * path
, int mode
, int flags
)
3262 if (dirfd
!= AT_FDCWD
3263 && !(IS_DIRECTORY_SEP (path
[0])
3264 || IS_DEVICE_SEP (path
[1])))
3270 /* MSVCRT implementation of 'access' doesn't recognize D_OK, and its
3271 newer versions blow up when passed D_OK. */
3272 path
= map_w32_filename (path
, NULL
);
3273 /* If the last element of PATH is a symlink, we need to resolve it
3274 to get the attributes of its target file. Note: any symlinks in
3275 PATH elements other than the last one are transparently resolved
3276 by GetFileAttributes below. */
3277 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) != 0
3278 && (flags
& AT_SYMLINK_NOFOLLOW
) == 0)
3279 path
= chase_symlinks (path
);
3281 if ((attributes
= GetFileAttributes (path
)) == -1)
3283 DWORD w32err
= GetLastError ();
3287 case ERROR_INVALID_NAME
:
3288 case ERROR_BAD_PATHNAME
:
3289 if (is_unc_volume (path
))
3291 attributes
= unc_volume_file_attributes (path
);
3292 if (attributes
== -1)
3300 case ERROR_FILE_NOT_FOUND
:
3301 case ERROR_BAD_NETPATH
:
3310 if ((mode
& X_OK
) != 0
3311 && !(is_exec (path
) || (attributes
& FILE_ATTRIBUTE_DIRECTORY
) != 0))
3316 if ((mode
& W_OK
) != 0 && (attributes
& FILE_ATTRIBUTE_READONLY
) != 0)
3321 if ((mode
& D_OK
) != 0 && (attributes
& FILE_ATTRIBUTE_DIRECTORY
) == 0)
3329 /* Shadow some MSVC runtime functions to map requests for long filenames
3330 to reasonable short names if necessary. This was originally added to
3331 permit running Emacs on NT 3.1 on a FAT partition, which doesn't support
3335 sys_chdir (const char * path
)
3337 return _chdir (map_w32_filename (path
, NULL
));
3341 sys_chmod (const char * path
, int mode
)
3343 path
= chase_symlinks (map_w32_filename (path
, NULL
));
3344 return _chmod (path
, mode
);
3348 sys_creat (const char * path
, int mode
)
3350 return _creat (map_w32_filename (path
, NULL
), mode
);
3354 sys_fopen (const char * path
, const char * mode
)
3358 const char * mode_save
= mode
;
3360 /* Force all file handles to be non-inheritable. This is necessary to
3361 ensure child processes don't unwittingly inherit handles that might
3362 prevent future file access. */
3366 else if (mode
[0] == 'w' || mode
[0] == 'a')
3367 oflag
= O_WRONLY
| O_CREAT
| O_TRUNC
;
3371 /* Only do simplistic option parsing. */
3375 oflag
&= ~(O_RDONLY
| O_WRONLY
);
3378 else if (mode
[0] == 'b')
3383 else if (mode
[0] == 't')
3390 fd
= _open (map_w32_filename (path
, NULL
), oflag
| _O_NOINHERIT
, 0644);
3394 return _fdopen (fd
, mode_save
);
3397 /* This only works on NTFS volumes, but is useful to have. */
3399 sys_link (const char * old
, const char * new)
3403 char oldname
[MAX_PATH
], newname
[MAX_PATH
];
3405 if (old
== NULL
|| new == NULL
)
3411 strcpy (oldname
, map_w32_filename (old
, NULL
));
3412 strcpy (newname
, map_w32_filename (new, NULL
));
3414 fileh
= CreateFile (oldname
, 0, 0, NULL
, OPEN_EXISTING
,
3415 FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
3416 if (fileh
!= INVALID_HANDLE_VALUE
)
3420 /* Confusingly, the "alternate" stream name field does not apply
3421 when restoring a hard link, and instead contains the actual
3422 stream data for the link (ie. the name of the link to create).
3423 The WIN32_STREAM_ID structure before the cStreamName field is
3424 the stream header, which is then immediately followed by the
3428 WIN32_STREAM_ID wid
;
3429 WCHAR wbuffer
[MAX_PATH
]; /* extra space for link name */
3432 wlen
= MultiByteToWideChar (CP_ACP
, MB_PRECOMPOSED
, newname
, -1,
3433 data
.wid
.cStreamName
, MAX_PATH
);
3436 LPVOID context
= NULL
;
3439 data
.wid
.dwStreamId
= BACKUP_LINK
;
3440 data
.wid
.dwStreamAttributes
= 0;
3441 data
.wid
.Size
.LowPart
= wlen
* sizeof (WCHAR
);
3442 data
.wid
.Size
.HighPart
= 0;
3443 data
.wid
.dwStreamNameSize
= 0;
3445 if (BackupWrite (fileh
, (LPBYTE
)&data
,
3446 offsetof (WIN32_STREAM_ID
, cStreamName
)
3447 + data
.wid
.Size
.LowPart
,
3448 &wbytes
, FALSE
, FALSE
, &context
)
3449 && BackupWrite (fileh
, NULL
, 0, &wbytes
, TRUE
, FALSE
, &context
))
3456 /* Should try mapping GetLastError to errno; for now just
3457 indicate a general error (eg. links not supported). */
3458 errno
= EINVAL
; // perhaps EMLINK?
3462 CloseHandle (fileh
);
3471 sys_mkdir (const char * path
)
3473 return _mkdir (map_w32_filename (path
, NULL
));
3477 sys_open (const char * path
, int oflag
, int mode
)
3479 const char* mpath
= map_w32_filename (path
, NULL
);
3482 /* If possible, try to open file without _O_CREAT, to be able to
3483 write to existing hidden and system files. Force all file
3484 handles to be non-inheritable. */
3485 if ((oflag
& (_O_CREAT
| _O_EXCL
)) != (_O_CREAT
| _O_EXCL
))
3486 res
= _open (mpath
, (oflag
& ~_O_CREAT
) | _O_NOINHERIT
, mode
);
3488 res
= _open (mpath
, oflag
| _O_NOINHERIT
, mode
);
3493 /* Implementation of mkostemp for MS-Windows, to avoid race conditions
3496 Standard algorithm for generating a temporary file name seems to be
3497 use pid or tid with a letter on the front (in place of the 6 X's)
3498 and cycle through the letters to find a unique name. We extend
3499 that to allow any reasonable character as the first of the 6 X's,
3500 so that the number of simultaneously used temporary files will be
3504 mkostemp (char * template, int flags
)
3508 unsigned uid
= GetCurrentThreadId ();
3509 int save_errno
= errno
;
3510 static char first_char
[] = "abcdefghijklmnopqrstuvwyz0123456789!%-_@#";
3513 if (template == NULL
)
3516 p
= template + strlen (template);
3518 /* replace up to the last 5 X's with uid in decimal */
3519 while (--p
>= template && p
[0] == 'X' && --i
>= 0)
3521 p
[0] = '0' + uid
% 10;
3525 if (i
< 0 && p
[0] == 'X')
3530 p
[0] = first_char
[i
];
3531 if ((fd
= sys_open (template,
3532 flags
| _O_CREAT
| _O_EXCL
| _O_RDWR
,
3533 S_IRUSR
| S_IWUSR
)) >= 0
3541 while (++i
< sizeof (first_char
));
3544 /* Template is badly formed or else we can't generate a unique name. */
3549 fchmod (int fd
, mode_t mode
)
3555 sys_rename_replace (const char *oldname
, const char *newname
, BOOL force
)
3558 char temp
[MAX_PATH
];
3562 /* MoveFile on Windows 95 doesn't correctly change the short file name
3563 alias in a number of circumstances (it is not easy to predict when
3564 just by looking at oldname and newname, unfortunately). In these
3565 cases, renaming through a temporary name avoids the problem.
3567 A second problem on Windows 95 is that renaming through a temp name when
3568 newname is uppercase fails (the final long name ends up in
3569 lowercase, although the short alias might be uppercase) UNLESS the
3570 long temp name is not 8.3.
3572 So, on Windows 95 we always rename through a temp name, and we make sure
3573 the temp name has a long extension to ensure correct renaming. */
3575 strcpy (temp
, map_w32_filename (oldname
, NULL
));
3577 /* volume_info is set indirectly by map_w32_filename. */
3578 oldname_dev
= volume_info
.serialnum
;
3580 if (os_subtype
== OS_9X
)
3586 oldname
= map_w32_filename (oldname
, NULL
);
3587 if ((o
= strrchr (oldname
, '\\')))
3590 o
= (char *) oldname
;
3592 if ((p
= strrchr (temp
, '\\')))
3599 /* Force temp name to require a manufactured 8.3 alias - this
3600 seems to make the second rename work properly. */
3601 sprintf (p
, "_.%s.%u", o
, i
);
3603 result
= rename (oldname
, temp
);
3605 /* This loop must surely terminate! */
3606 while (result
< 0 && errno
== EEXIST
);
3611 /* If FORCE, emulate Unix behavior - newname is deleted if it already exists
3612 (at least if it is a file; don't do this for directories).
3614 Since we mustn't do this if we are just changing the case of the
3615 file name (we would end up deleting the file we are trying to
3616 rename!), we let rename detect if the destination file already
3617 exists - that way we avoid the possible pitfalls of trying to
3618 determine ourselves whether two names really refer to the same
3619 file, which is not always possible in the general case. (Consider
3620 all the permutations of shared or subst'd drives, etc.) */
3622 newname
= map_w32_filename (newname
, NULL
);
3624 /* volume_info is set indirectly by map_w32_filename. */
3625 newname_dev
= volume_info
.serialnum
;
3627 result
= rename (temp
, newname
);
3629 if (result
< 0 && force
)
3631 DWORD w32err
= GetLastError ();
3634 && newname_dev
!= oldname_dev
)
3636 /* The implementation of `rename' on Windows does not return
3637 errno = EXDEV when you are moving a directory to a
3638 different storage device (ex. logical disk). It returns
3639 EACCES instead. So here we handle such situations and
3643 if ((attributes
= GetFileAttributes (temp
)) != -1
3644 && (attributes
& FILE_ATTRIBUTE_DIRECTORY
))
3647 else if (errno
== EEXIST
)
3649 if (_chmod (newname
, 0666) != 0)
3651 if (_unlink (newname
) != 0)
3653 result
= rename (temp
, newname
);
3655 else if (w32err
== ERROR_PRIVILEGE_NOT_HELD
3656 && is_symlink (temp
))
3658 /* This is Windows prohibiting the user from creating a
3659 symlink in another place, since that requires
3669 sys_rename (char const *old
, char const *new)
3671 return sys_rename_replace (old
, new, TRUE
);
3675 sys_rmdir (const char * path
)
3677 return _rmdir (map_w32_filename (path
, NULL
));
3681 sys_unlink (const char * path
)
3683 path
= map_w32_filename (path
, NULL
);
3685 /* On Unix, unlink works without write permission. */
3686 _chmod (path
, 0666);
3687 return _unlink (path
);
3690 static FILETIME utc_base_ft
;
3691 static ULONGLONG utc_base
; /* In 100ns units */
3692 static int init
= 0;
3694 #define FILETIME_TO_U64(result, ft) \
3696 ULARGE_INTEGER uiTemp; \
3697 uiTemp.LowPart = (ft).dwLowDateTime; \
3698 uiTemp.HighPart = (ft).dwHighDateTime; \
3699 result = uiTemp.QuadPart; \
3703 initialize_utc_base (void)
3705 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
3714 st
.wMilliseconds
= 0;
3716 SystemTimeToFileTime (&st
, &utc_base_ft
);
3717 FILETIME_TO_U64 (utc_base
, utc_base_ft
);
3721 convert_time (FILETIME ft
)
3727 initialize_utc_base ();
3731 if (CompareFileTime (&ft
, &utc_base_ft
) < 0)
3734 FILETIME_TO_U64 (tmp
, ft
);
3735 return (time_t) ((tmp
- utc_base
) / 10000000L);
3739 convert_from_time_t (time_t time
, FILETIME
* pft
)
3745 initialize_utc_base ();
3749 /* time in 100ns units since 1-Jan-1601 */
3750 tmp
.QuadPart
= (ULONGLONG
) time
* 10000000L + utc_base
;
3751 pft
->dwHighDateTime
= tmp
.HighPart
;
3752 pft
->dwLowDateTime
= tmp
.LowPart
;
3756 /* No reason to keep this; faking inode values either by hashing or even
3757 using the file index from GetInformationByHandle, is not perfect and
3758 so by default Emacs doesn't use the inode values on Windows.
3759 Instead, we now determine file-truename correctly (except for
3760 possible drive aliasing etc). */
3762 /* Modified version of "PJW" algorithm (see the "Dragon" compiler book). */
3764 hashval (const unsigned char * str
)
3769 h
= (h
<< 4) + *str
++;
3775 /* Return the hash value of the canonical pathname, excluding the
3776 drive/UNC header, to get a hopefully unique inode number. */
3778 generate_inode_val (const char * name
)
3780 char fullname
[ MAX_PATH
];
3784 /* Get the truly canonical filename, if it exists. (Note: this
3785 doesn't resolve aliasing due to subst commands, or recognize hard
3787 if (!w32_get_long_filename ((char *)name
, fullname
, MAX_PATH
))
3790 parse_root (fullname
, &p
);
3791 /* Normal W32 filesystems are still case insensitive. */
3798 static PSECURITY_DESCRIPTOR
3799 get_file_security_desc_by_handle (HANDLE h
)
3801 PSECURITY_DESCRIPTOR psd
= NULL
;
3803 SECURITY_INFORMATION si
= OWNER_SECURITY_INFORMATION
3804 | GROUP_SECURITY_INFORMATION
/* | DACL_SECURITY_INFORMATION */ ;
3806 err
= get_security_info (h
, SE_FILE_OBJECT
, si
,
3807 NULL
, NULL
, NULL
, NULL
, &psd
);
3808 if (err
!= ERROR_SUCCESS
)
3814 static PSECURITY_DESCRIPTOR
3815 get_file_security_desc_by_name (const char *fname
)
3817 PSECURITY_DESCRIPTOR psd
= NULL
;
3819 SECURITY_INFORMATION si
= OWNER_SECURITY_INFORMATION
3820 | GROUP_SECURITY_INFORMATION
/* | DACL_SECURITY_INFORMATION */ ;
3822 if (!get_file_security (fname
, si
, psd
, 0, &sd_len
))
3824 err
= GetLastError ();
3825 if (err
!= ERROR_INSUFFICIENT_BUFFER
)
3829 psd
= xmalloc (sd_len
);
3830 if (!get_file_security (fname
, si
, psd
, sd_len
, &sd_len
))
3842 unsigned n_subauthorities
;
3844 /* Use the last sub-authority value of the RID, the relative
3845 portion of the SID, as user/group ID. */
3846 n_subauthorities
= *get_sid_sub_authority_count (sid
);
3847 if (n_subauthorities
< 1)
3848 return 0; /* the "World" RID */
3849 return *get_sid_sub_authority (sid
, n_subauthorities
- 1);
3852 /* Caching SID and account values for faster lokup. */
3856 struct w32_id
*next
;
3858 unsigned char sid
[FLEXIBLE_ARRAY_MEMBER
];
3861 static struct w32_id
*w32_idlist
;
3864 w32_cached_id (PSID sid
, unsigned *id
, char *name
)
3866 struct w32_id
*tail
, *found
;
3868 for (found
= NULL
, tail
= w32_idlist
; tail
; tail
= tail
->next
)
3870 if (equal_sid ((PSID
)tail
->sid
, sid
))
3879 strcpy (name
, found
->name
);
3887 w32_add_to_cache (PSID sid
, unsigned id
, char *name
)
3890 struct w32_id
*new_entry
;
3892 /* We don't want to leave behind stale cache from when Emacs was
3896 sid_len
= get_length_sid (sid
);
3897 new_entry
= xmalloc (offsetof (struct w32_id
, sid
) + sid_len
);
3900 new_entry
->rid
= id
;
3901 strcpy (new_entry
->name
, name
);
3902 copy_sid (sid_len
, (PSID
)new_entry
->sid
, sid
);
3903 new_entry
->next
= w32_idlist
;
3904 w32_idlist
= new_entry
;
3913 get_name_and_id (PSECURITY_DESCRIPTOR psd
, unsigned *id
, char *nm
, int what
)
3917 SID_NAME_USE ignore
;
3919 DWORD name_len
= sizeof (name
);
3921 DWORD domain_len
= sizeof (domain
);
3926 result
= get_security_descriptor_owner (psd
, &sid
, &dflt
);
3927 else if (what
== GID
)
3928 result
= get_security_descriptor_group (psd
, &sid
, &dflt
);
3932 if (!result
|| !is_valid_sid (sid
))
3934 else if (!w32_cached_id (sid
, id
, nm
))
3936 if (!lookup_account_sid (NULL
, sid
, name
, &name_len
,
3937 domain
, &domain_len
, &ignore
)
3938 || name_len
> UNLEN
+1)
3942 *id
= get_rid (sid
);
3944 w32_add_to_cache (sid
, *id
, name
);
3951 get_file_owner_and_group (PSECURITY_DESCRIPTOR psd
, struct stat
*st
)
3953 int dflt_usr
= 0, dflt_grp
= 0;
3962 if (get_name_and_id (psd
, &st
->st_uid
, st
->st_uname
, UID
))
3964 if (get_name_and_id (psd
, &st
->st_gid
, st
->st_gname
, GID
))
3967 /* Consider files to belong to current user/group, if we cannot get
3968 more accurate information. */
3971 st
->st_uid
= dflt_passwd
.pw_uid
;
3972 strcpy (st
->st_uname
, dflt_passwd
.pw_name
);
3976 st
->st_gid
= dflt_passwd
.pw_gid
;
3977 strcpy (st
->st_gname
, dflt_group
.gr_name
);
3981 /* Return non-zero if NAME is a potentially slow filesystem. */
3983 is_slow_fs (const char *name
)
3988 if (IS_DIRECTORY_SEP (name
[0]) && IS_DIRECTORY_SEP (name
[1]))
3989 devtype
= DRIVE_REMOTE
; /* assume UNC name is remote */
3990 else if (!(strlen (name
) >= 2 && IS_DEVICE_SEP (name
[1])))
3991 devtype
= GetDriveType (NULL
); /* use root of current drive */
3994 /* GetDriveType needs the root directory of the drive. */
3995 strncpy (drive_root
, name
, 2);
3996 drive_root
[2] = '\\';
3997 drive_root
[3] = '\0';
3998 devtype
= GetDriveType (drive_root
);
4000 return !(devtype
== DRIVE_FIXED
|| devtype
== DRIVE_RAMDISK
);
4003 /* If this is non-zero, the caller wants accurate information about
4004 file's owner and group, which could be expensive to get. */
4005 int w32_stat_get_owner_group
;
4007 /* MSVC stat function can't cope with UNC names and has other bugs, so
4008 replace it with our own. This also allows us to calculate consistent
4009 inode values and owner/group without hacks in the main Emacs code. */
4012 stat_worker (const char * path
, struct stat
* buf
, int follow_symlinks
)
4014 char *name
, *save_name
, *r
;
4015 WIN32_FIND_DATA wfd
;
4017 unsigned __int64 fake_inode
= 0;
4020 int rootdir
= FALSE
;
4021 PSECURITY_DESCRIPTOR psd
= NULL
;
4022 int is_a_symlink
= 0;
4023 DWORD file_flags
= FILE_FLAG_BACKUP_SEMANTICS
;
4024 DWORD access_rights
= 0;
4025 DWORD fattrs
= 0, serialnum
= 0, fs_high
= 0, fs_low
= 0, nlinks
= 1;
4026 FILETIME ctime
, atime
, wtime
;
4029 if (path
== NULL
|| buf
== NULL
)
4035 save_name
= name
= (char *) map_w32_filename (path
, &path
);
4036 /* Must be valid filename, no wild cards or other invalid
4037 characters. We use _mbspbrk to support multibyte strings that
4038 might look to strpbrk as if they included literal *, ?, and other
4039 characters mentioned below that are disallowed by Windows
4041 if (_mbspbrk (name
, "*?|<>\""))
4047 /* Remove trailing directory separator, unless name is the root
4048 directory of a drive or UNC volume in which case ensure there
4049 is a trailing separator. */
4050 len
= strlen (name
);
4051 name
= strcpy (alloca (len
+ 2), name
);
4053 /* Avoid a somewhat costly call to is_symlink if the filesystem
4054 doesn't support symlinks. */
4055 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) != 0)
4056 is_a_symlink
= is_symlink (name
);
4058 /* Plan A: Open the file and get all the necessary information via
4059 the resulting handle. This solves several issues in one blow:
4061 . retrieves attributes for the target of a symlink, if needed
4062 . gets attributes of root directories and symlinks pointing to
4063 root directories, thus avoiding the need for special-casing
4064 these and detecting them by examining the file-name format
4065 . retrieves more accurate attributes (e.g., non-zero size for
4066 some directories, esp. directories that are junction points)
4067 . correctly resolves "c:/..", "/.." and similar file names
4068 . avoids run-time penalties for 99% of use cases
4070 Plan A is always tried first, unless the user asked not to (but
4071 if the file is a symlink and we need to follow links, we try Plan
4072 A even if the user asked not to).
4074 If Plan A fails, we go to Plan B (below), where various
4075 potentially expensive techniques must be used to handle "special"
4076 files such as UNC volumes etc. */
4077 if (!(NILP (Vw32_get_true_file_attributes
)
4078 || (EQ (Vw32_get_true_file_attributes
, Qlocal
) && is_slow_fs (name
)))
4079 /* Following symlinks requires getting the info by handle. */
4080 || (is_a_symlink
&& follow_symlinks
))
4082 BY_HANDLE_FILE_INFORMATION info
;
4084 if (is_a_symlink
&& !follow_symlinks
)
4085 file_flags
|= FILE_FLAG_OPEN_REPARSE_POINT
;
4086 /* READ_CONTROL access rights are required to get security info
4087 by handle. But if the OS doesn't support security in the
4088 first place, we don't need to try. */
4089 if (is_windows_9x () != TRUE
)
4090 access_rights
|= READ_CONTROL
;
4092 fh
= CreateFile (name
, access_rights
, 0, NULL
, OPEN_EXISTING
,
4094 /* If CreateFile fails with READ_CONTROL, try again with zero as
4096 if (fh
== INVALID_HANDLE_VALUE
&& access_rights
)
4097 fh
= CreateFile (name
, 0, 0, NULL
, OPEN_EXISTING
,
4099 if (fh
== INVALID_HANDLE_VALUE
)
4100 goto no_true_file_attributes
;
4102 /* This is more accurate in terms of getting the correct number
4103 of links, but is quite slow (it is noticeable when Emacs is
4104 making a list of file name completions). */
4105 if (GetFileInformationByHandle (fh
, &info
))
4107 nlinks
= info
.nNumberOfLinks
;
4108 /* Might as well use file index to fake inode values, but this
4109 is not guaranteed to be unique unless we keep a handle open
4110 all the time (even then there are situations where it is
4111 not unique). Reputedly, there are at most 48 bits of info
4112 (on NTFS, presumably less on FAT). */
4113 fake_inode
= info
.nFileIndexHigh
;
4115 fake_inode
+= info
.nFileIndexLow
;
4116 serialnum
= info
.dwVolumeSerialNumber
;
4117 fs_high
= info
.nFileSizeHigh
;
4118 fs_low
= info
.nFileSizeLow
;
4119 ctime
= info
.ftCreationTime
;
4120 atime
= info
.ftLastAccessTime
;
4121 wtime
= info
.ftLastWriteTime
;
4122 fattrs
= info
.dwFileAttributes
;
4126 /* We don't go to Plan B here, because it's not clear that
4127 it's a good idea. The only known use case where
4128 CreateFile succeeds, but GetFileInformationByHandle fails
4129 (with ERROR_INVALID_FUNCTION) is for character devices
4130 such as NUL, PRN, etc. For these, switching to Plan B is
4131 a net loss, because we lose the character device
4132 attribute returned by GetFileType below (FindFirstFile
4133 doesn't set that bit in the attributes), and the other
4134 fields don't make sense for character devices anyway.
4135 Emacs doesn't really care for non-file entities in the
4136 context of l?stat, so neither do we. */
4138 /* w32err is assigned so one could put a breakpoint here and
4139 examine its value, when GetFileInformationByHandle
4141 DWORD w32err
= GetLastError ();
4145 case ERROR_FILE_NOT_FOUND
: /* can this ever happen? */
4151 /* Test for a symlink before testing for a directory, since
4152 symlinks to directories have the directory bit set, but we
4153 don't want them to appear as directories. */
4154 if (is_a_symlink
&& !follow_symlinks
)
4155 buf
->st_mode
= S_IFLNK
;
4156 else if (fattrs
& FILE_ATTRIBUTE_DIRECTORY
)
4157 buf
->st_mode
= S_IFDIR
;
4160 DWORD ftype
= GetFileType (fh
);
4164 case FILE_TYPE_DISK
:
4165 buf
->st_mode
= S_IFREG
;
4167 case FILE_TYPE_PIPE
:
4168 buf
->st_mode
= S_IFIFO
;
4170 case FILE_TYPE_CHAR
:
4171 case FILE_TYPE_UNKNOWN
:
4173 buf
->st_mode
= S_IFCHR
;
4176 /* We produce the fallback owner and group data, based on the
4177 current user that runs Emacs, in the following cases:
4179 . caller didn't request owner and group info
4180 . this is Windows 9X
4181 . getting security by handle failed, and we need to produce
4182 information for the target of a symlink (this is better
4183 than producing a potentially misleading info about the
4186 If getting security by handle fails, and we don't need to
4187 resolve symlinks, we try getting security by name. */
4188 if (!w32_stat_get_owner_group
|| is_windows_9x () == TRUE
)
4189 get_file_owner_and_group (NULL
, buf
);
4192 psd
= get_file_security_desc_by_handle (fh
);
4195 get_file_owner_and_group (psd
, buf
);
4198 else if (!(is_a_symlink
&& follow_symlinks
))
4200 psd
= get_file_security_desc_by_name (name
);
4201 get_file_owner_and_group (psd
, buf
);
4205 get_file_owner_and_group (NULL
, buf
);
4211 no_true_file_attributes
:
4212 /* Plan B: Either getting a handle on the file failed, or the
4213 caller explicitly asked us to not bother making this
4214 information more accurate.
4216 Implementation note: In Plan B, we never bother to resolve
4217 symlinks, even if we got here because we tried Plan A and
4218 failed. That's because, even if the caller asked for extra
4219 precision by setting Vw32_get_true_file_attributes to t,
4220 resolving symlinks requires acquiring a file handle to the
4221 symlink, which we already know will fail. And if the user
4222 did not ask for extra precision, resolving symlinks will fly
4223 in the face of that request, since the user then wants the
4224 lightweight version of the code. */
4225 dbcs_p
= max_filename_mbslen () > 1;
4226 rootdir
= (path
>= save_name
+ len
- 1
4227 && (IS_DIRECTORY_SEP (*path
) || *path
== 0));
4229 /* If name is "c:/.." or "/.." then stat "c:/" or "/". */
4230 r
= IS_DEVICE_SEP (name
[1]) ? &name
[2] : name
;
4231 if (IS_DIRECTORY_SEP (r
[0])
4232 && r
[1] == '.' && r
[2] == '.' && r
[3] == '\0')
4235 /* Note: If NAME is a symlink to the root of a UNC volume
4236 (i.e. "\\SERVER"), we will not detect that here, and we will
4237 return data about the symlink as result of FindFirst below.
4238 This is unfortunate, but that marginal use case does not
4239 justify a call to chase_symlinks which would impose a penalty
4240 on all the other use cases. (We get here for symlinks to
4241 roots of UNC volumes because CreateFile above fails for them,
4242 unlike with symlinks to root directories X:\ of drives.) */
4243 if (is_unc_volume (name
))
4245 fattrs
= unc_volume_file_attributes (name
);
4249 ctime
= atime
= wtime
= utc_base_ft
;
4255 if (!IS_DIRECTORY_SEP (name
[len
-1]))
4256 strcat (name
, "\\");
4260 char *end
= name
+ len
;
4261 char *n
= CharPrevExA (file_name_codepage
, name
, end
, 0);
4263 if (!IS_DIRECTORY_SEP (*n
))
4264 strcat (name
, "\\");
4266 if (GetDriveType (name
) < 2)
4272 fattrs
= FILE_ATTRIBUTE_DIRECTORY
;
4273 ctime
= atime
= wtime
= utc_base_ft
;
4279 if (IS_DIRECTORY_SEP (name
[len
-1]))
4284 char *end
= name
+ len
;
4285 char *n
= CharPrevExA (file_name_codepage
, name
, end
, 0);
4287 if (IS_DIRECTORY_SEP (*n
))
4291 /* (This is hacky, but helps when doing file completions on
4292 network drives.) Optimize by using information available from
4293 active readdir if possible. */
4294 len
= strlen (dir_pathname
);
4297 if (IS_DIRECTORY_SEP (dir_pathname
[len
-1]))
4302 char *end
= dir_pathname
+ len
;
4303 char *n
= CharPrevExA (file_name_codepage
, dir_pathname
, end
, 0);
4305 if (IS_DIRECTORY_SEP (*n
))
4308 if (dir_find_handle
!= INVALID_HANDLE_VALUE
4309 && !(is_a_symlink
&& follow_symlinks
)
4310 && strnicmp (save_name
, dir_pathname
, len
) == 0
4311 && IS_DIRECTORY_SEP (name
[len
])
4312 && xstrcasecmp (name
+ len
+ 1, dir_static
.d_name
) == 0)
4314 /* This was the last entry returned by readdir. */
4315 wfd
= dir_find_data
;
4319 logon_network_drive (name
);
4321 fh
= FindFirstFile (name
, &wfd
);
4322 if (fh
== INVALID_HANDLE_VALUE
)
4329 /* Note: if NAME is a symlink, the information we get from
4330 FindFirstFile is for the symlink, not its target. */
4331 fattrs
= wfd
.dwFileAttributes
;
4332 ctime
= wfd
.ftCreationTime
;
4333 atime
= wfd
.ftLastAccessTime
;
4334 wtime
= wfd
.ftLastWriteTime
;
4335 fs_high
= wfd
.nFileSizeHigh
;
4336 fs_low
= wfd
.nFileSizeLow
;
4339 serialnum
= volume_info
.serialnum
;
4341 if (is_a_symlink
&& !follow_symlinks
)
4342 buf
->st_mode
= S_IFLNK
;
4343 else if (fattrs
& FILE_ATTRIBUTE_DIRECTORY
)
4344 buf
->st_mode
= S_IFDIR
;
4346 buf
->st_mode
= S_IFREG
;
4348 get_file_owner_and_group (NULL
, buf
);
4352 /* Not sure if there is any point in this. */
4353 if (!NILP (Vw32_generate_fake_inodes
))
4354 fake_inode
= generate_inode_val (name
);
4355 else if (fake_inode
== 0)
4357 /* For want of something better, try to make everything unique. */
4358 static DWORD gen_num
= 0;
4359 fake_inode
= ++gen_num
;
4363 buf
->st_ino
= fake_inode
;
4365 buf
->st_dev
= serialnum
;
4366 buf
->st_rdev
= serialnum
;
4368 buf
->st_size
= fs_high
;
4369 buf
->st_size
<<= 32;
4370 buf
->st_size
+= fs_low
;
4371 buf
->st_nlink
= nlinks
;
4373 /* Convert timestamps to Unix format. */
4374 buf
->st_mtime
= convert_time (wtime
);
4375 buf
->st_atime
= convert_time (atime
);
4376 if (buf
->st_atime
== 0) buf
->st_atime
= buf
->st_mtime
;
4377 buf
->st_ctime
= convert_time (ctime
);
4378 if (buf
->st_ctime
== 0) buf
->st_ctime
= buf
->st_mtime
;
4380 /* determine rwx permissions */
4381 if (is_a_symlink
&& !follow_symlinks
)
4382 permission
= S_IREAD
| S_IWRITE
| S_IEXEC
; /* Posix expectations */
4385 if (fattrs
& FILE_ATTRIBUTE_READONLY
)
4386 permission
= S_IREAD
;
4388 permission
= S_IREAD
| S_IWRITE
;
4390 if (fattrs
& FILE_ATTRIBUTE_DIRECTORY
)
4391 permission
|= S_IEXEC
;
4392 else if (is_exec (name
))
4393 permission
|= S_IEXEC
;
4396 buf
->st_mode
|= permission
| (permission
>> 3) | (permission
>> 6);
4402 stat (const char * path
, struct stat
* buf
)
4404 return stat_worker (path
, buf
, 1);
4408 lstat (const char * path
, struct stat
* buf
)
4410 return stat_worker (path
, buf
, 0);
4414 fstatat (int fd
, char const *name
, struct stat
*st
, int flags
)
4416 /* Rely on a hack: an open directory is modeled as file descriptor 0.
4417 This is good enough for the current usage in Emacs, but is fragile.
4419 FIXME: Add proper support for fdopendir, fstatat, readlinkat.
4420 Gnulib does this and can serve as a model. */
4421 char fullname
[MAX_PATH
];
4425 if (_snprintf (fullname
, sizeof fullname
, "%s/%s", dir_pathname
, name
)
4428 errno
= ENAMETOOLONG
;
4434 return stat_worker (name
, st
, ! (flags
& AT_SYMLINK_NOFOLLOW
));
4437 /* Provide fstat and utime as well as stat for consistent handling of
4440 fstat (int desc
, struct stat
* buf
)
4442 HANDLE fh
= (HANDLE
) _get_osfhandle (desc
);
4443 BY_HANDLE_FILE_INFORMATION info
;
4444 unsigned __int64 fake_inode
;
4447 switch (GetFileType (fh
) & ~FILE_TYPE_REMOTE
)
4449 case FILE_TYPE_DISK
:
4450 buf
->st_mode
= S_IFREG
;
4451 if (!GetFileInformationByHandle (fh
, &info
))
4457 case FILE_TYPE_PIPE
:
4458 buf
->st_mode
= S_IFIFO
;
4460 case FILE_TYPE_CHAR
:
4461 case FILE_TYPE_UNKNOWN
:
4463 buf
->st_mode
= S_IFCHR
;
4465 memset (&info
, 0, sizeof (info
));
4466 info
.dwFileAttributes
= 0;
4467 info
.ftCreationTime
= utc_base_ft
;
4468 info
.ftLastAccessTime
= utc_base_ft
;
4469 info
.ftLastWriteTime
= utc_base_ft
;
4472 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
4473 buf
->st_mode
= S_IFDIR
;
4475 buf
->st_nlink
= info
.nNumberOfLinks
;
4476 /* Might as well use file index to fake inode values, but this
4477 is not guaranteed to be unique unless we keep a handle open
4478 all the time (even then there are situations where it is
4479 not unique). Reputedly, there are at most 48 bits of info
4480 (on NTFS, presumably less on FAT). */
4481 fake_inode
= info
.nFileIndexHigh
;
4483 fake_inode
+= info
.nFileIndexLow
;
4485 /* MSVC defines _ino_t to be short; other libc's might not. */
4486 if (sizeof (buf
->st_ino
) == 2)
4487 buf
->st_ino
= fake_inode
^ (fake_inode
>> 16);
4489 buf
->st_ino
= fake_inode
;
4491 /* If the caller so requested, get the true file owner and group.
4492 Otherwise, consider the file to belong to the current user. */
4493 if (!w32_stat_get_owner_group
|| is_windows_9x () == TRUE
)
4494 get_file_owner_and_group (NULL
, buf
);
4497 PSECURITY_DESCRIPTOR psd
= NULL
;
4499 psd
= get_file_security_desc_by_handle (fh
);
4502 get_file_owner_and_group (psd
, buf
);
4506 get_file_owner_and_group (NULL
, buf
);
4509 buf
->st_dev
= info
.dwVolumeSerialNumber
;
4510 buf
->st_rdev
= info
.dwVolumeSerialNumber
;
4512 buf
->st_size
= info
.nFileSizeHigh
;
4513 buf
->st_size
<<= 32;
4514 buf
->st_size
+= info
.nFileSizeLow
;
4516 /* Convert timestamps to Unix format. */
4517 buf
->st_mtime
= convert_time (info
.ftLastWriteTime
);
4518 buf
->st_atime
= convert_time (info
.ftLastAccessTime
);
4519 if (buf
->st_atime
== 0) buf
->st_atime
= buf
->st_mtime
;
4520 buf
->st_ctime
= convert_time (info
.ftCreationTime
);
4521 if (buf
->st_ctime
== 0) buf
->st_ctime
= buf
->st_mtime
;
4523 /* determine rwx permissions */
4524 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
)
4525 permission
= S_IREAD
;
4527 permission
= S_IREAD
| S_IWRITE
;
4529 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
4530 permission
|= S_IEXEC
;
4533 #if 0 /* no way of knowing the filename */
4534 char * p
= strrchr (name
, '.');
4536 (xstrcasecmp (p
, ".exe") == 0 ||
4537 xstrcasecmp (p
, ".com") == 0 ||
4538 xstrcasecmp (p
, ".bat") == 0 ||
4539 xstrcasecmp (p
, ".cmd") == 0))
4540 permission
|= S_IEXEC
;
4544 buf
->st_mode
|= permission
| (permission
>> 3) | (permission
>> 6);
4549 /* A version of 'utime' which handles directories as well as
4553 utime (const char *name
, struct utimbuf
*times
)
4555 struct utimbuf deftime
;
4562 deftime
.modtime
= deftime
.actime
= time (NULL
);
4566 /* Need write access to set times. */
4567 fh
= CreateFile (name
, FILE_WRITE_ATTRIBUTES
,
4568 /* If NAME specifies a directory, FILE_SHARE_DELETE
4569 allows other processes to delete files inside it,
4570 while we have the directory open. */
4571 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
4572 0, OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
4573 if (fh
!= INVALID_HANDLE_VALUE
)
4575 convert_from_time_t (times
->actime
, &atime
);
4576 convert_from_time_t (times
->modtime
, &mtime
);
4577 if (!SetFileTime (fh
, NULL
, &atime
, &mtime
))
4594 /* Symlink-related functions. */
4595 #ifndef SYMBOLIC_LINK_FLAG_DIRECTORY
4596 #define SYMBOLIC_LINK_FLAG_DIRECTORY 0x1
4600 symlink (char const *filename
, char const *linkname
)
4602 char linkfn
[MAX_PATH
], *tgtfn
;
4604 int dir_access
, filename_ends_in_slash
;
4607 /* Diagnostics follows Posix as much as possible. */
4608 if (filename
== NULL
|| linkname
== NULL
)
4618 if (strlen (filename
) > MAX_PATH
|| strlen (linkname
) > MAX_PATH
)
4620 errno
= ENAMETOOLONG
;
4624 strcpy (linkfn
, map_w32_filename (linkname
, NULL
));
4625 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) == 0)
4631 dbcs_p
= max_filename_mbslen () > 1;
4633 /* Note: since empty FILENAME was already rejected, we can safely
4634 refer to FILENAME[1]. */
4635 if (!(IS_DIRECTORY_SEP (filename
[0]) || IS_DEVICE_SEP (filename
[1])))
4637 /* Non-absolute FILENAME is understood as being relative to
4638 LINKNAME's directory. We need to prepend that directory to
4639 FILENAME to get correct results from faccessat below, since
4640 otherwise it will interpret FILENAME relative to the
4641 directory where the Emacs process runs. Note that
4642 make-symbolic-link always makes sure LINKNAME is a fully
4643 expanded file name. */
4645 char *p
= linkfn
+ strlen (linkfn
);
4649 while (p
> linkfn
&& !IS_ANY_SEP (p
[-1]))
4654 char *p1
= CharPrevExA (file_name_codepage
, linkfn
, p
, 0);
4656 while (p
> linkfn
&& !IS_ANY_SEP (*p1
))
4659 p1
= CharPrevExA (file_name_codepage
, linkfn
, p1
, 0);
4663 strncpy (tem
, linkfn
, p
- linkfn
);
4664 tem
[p
- linkfn
] = '\0';
4665 strcat (tem
, filename
);
4666 dir_access
= faccessat (AT_FDCWD
, tem
, D_OK
, AT_EACCESS
);
4669 dir_access
= faccessat (AT_FDCWD
, filename
, D_OK
, AT_EACCESS
);
4671 /* Since Windows distinguishes between symlinks to directories and
4672 to files, we provide a kludgy feature: if FILENAME doesn't
4673 exist, but ends in a slash, we create a symlink to directory. If
4674 FILENAME exists and is a directory, we always create a symlink to
4677 filename_ends_in_slash
= IS_DIRECTORY_SEP (filename
[strlen (filename
) - 1]);
4680 const char *end
= filename
+ strlen (filename
);
4681 const char *n
= CharPrevExA (file_name_codepage
, filename
, end
, 0);
4683 filename_ends_in_slash
= IS_DIRECTORY_SEP (*n
);
4685 if (dir_access
== 0 || filename_ends_in_slash
)
4686 flags
= SYMBOLIC_LINK_FLAG_DIRECTORY
;
4688 tgtfn
= (char *)map_w32_filename (filename
, NULL
);
4689 if (filename_ends_in_slash
)
4690 tgtfn
[strlen (tgtfn
) - 1] = '\0';
4693 if (!create_symbolic_link (linkfn
, tgtfn
, flags
))
4695 /* ENOSYS is set by create_symbolic_link, when it detects that
4696 the OS doesn't support the CreateSymbolicLink API. */
4697 if (errno
!= ENOSYS
)
4699 DWORD w32err
= GetLastError ();
4703 /* ERROR_SUCCESS is sometimes returned when LINKFN and
4704 TGTFN point to the same file name, go figure. */
4706 case ERROR_FILE_EXISTS
:
4709 case ERROR_ACCESS_DENIED
:
4712 case ERROR_FILE_NOT_FOUND
:
4713 case ERROR_PATH_NOT_FOUND
:
4714 case ERROR_BAD_NETPATH
:
4715 case ERROR_INVALID_REPARSE_DATA
:
4718 case ERROR_DIRECTORY
:
4721 case ERROR_PRIVILEGE_NOT_HELD
:
4722 case ERROR_NOT_ALL_ASSIGNED
:
4725 case ERROR_DISK_FULL
:
4738 /* A quick inexpensive test of whether FILENAME identifies a file that
4739 is a symlink. Returns non-zero if it is, zero otherwise. FILENAME
4740 must already be in the normalized form returned by
4743 Note: for repeated operations on many files, it is best to test
4744 whether the underlying volume actually supports symlinks, by
4745 testing the FILE_SUPPORTS_REPARSE_POINTS bit in volume's flags, and
4746 avoid the call to this function if it doesn't. That's because the
4747 call to GetFileAttributes takes a non-negligible time, especially
4748 on non-local or removable filesystems. See stat_worker for an
4749 example of how to do that. */
4751 is_symlink (const char *filename
)
4754 WIN32_FIND_DATA wfd
;
4757 attrs
= GetFileAttributes (filename
);
4760 DWORD w32err
= GetLastError ();
4764 case ERROR_BAD_NETPATH
: /* network share, can't be a symlink */
4766 case ERROR_ACCESS_DENIED
:
4769 case ERROR_FILE_NOT_FOUND
:
4770 case ERROR_PATH_NOT_FOUND
:
4777 if ((attrs
& FILE_ATTRIBUTE_REPARSE_POINT
) == 0)
4779 logon_network_drive (filename
);
4780 fh
= FindFirstFile (filename
, &wfd
);
4781 if (fh
== INVALID_HANDLE_VALUE
)
4784 return (wfd
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) != 0
4785 && (wfd
.dwReserved0
& IO_REPARSE_TAG_SYMLINK
) == IO_REPARSE_TAG_SYMLINK
;
4788 /* If NAME identifies a symbolic link, copy into BUF the file name of
4789 the symlink's target. Copy at most BUF_SIZE bytes, and do NOT
4790 null-terminate the target name, even if it fits. Return the number
4791 of bytes copied, or -1 if NAME is not a symlink or any error was
4792 encountered while resolving it. The file name copied into BUF is
4793 encoded in the current ANSI codepage. */
4795 readlink (const char *name
, char *buf
, size_t buf_size
)
4798 TOKEN_PRIVILEGES privs
;
4799 int restore_privs
= 0;
4814 path
= map_w32_filename (name
, NULL
);
4816 if (strlen (path
) > MAX_PATH
)
4818 errno
= ENAMETOOLONG
;
4823 if (is_windows_9x () == TRUE
4824 || (volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) == 0
4825 || !is_symlink (path
))
4828 errno
= EINVAL
; /* not a symlink */
4832 /* Done with simple tests, now we're in for some _real_ work. */
4833 if (enable_privilege (SE_BACKUP_NAME
, TRUE
, &privs
))
4835 /* Implementation note: From here and onward, don't return early,
4836 since that will fail to restore the original set of privileges of
4837 the calling thread. */
4839 retval
= -1; /* not too optimistic, are we? */
4841 /* Note: In the next call to CreateFile, we use zero as the 2nd
4842 argument because, when the symlink is a hidden/system file,
4843 e.g. 'C:\Users\All Users', GENERIC_READ fails with
4844 ERROR_ACCESS_DENIED. Zero seems to work just fine, both for file
4845 and directory symlinks. */
4846 sh
= CreateFile (path
, 0, 0, NULL
, OPEN_EXISTING
,
4847 FILE_FLAG_OPEN_REPARSE_POINT
| FILE_FLAG_BACKUP_SEMANTICS
,
4849 if (sh
!= INVALID_HANDLE_VALUE
)
4851 BYTE reparse_buf
[MAXIMUM_REPARSE_DATA_BUFFER_SIZE
];
4852 REPARSE_DATA_BUFFER
*reparse_data
= (REPARSE_DATA_BUFFER
*)&reparse_buf
[0];
4855 if (!DeviceIoControl (sh
, FSCTL_GET_REPARSE_POINT
, NULL
, 0,
4856 reparse_buf
, MAXIMUM_REPARSE_DATA_BUFFER_SIZE
,
4859 else if (reparse_data
->ReparseTag
!= IO_REPARSE_TAG_SYMLINK
)
4863 /* Copy the link target name, in wide characters, from
4864 reparse_data, then convert it to multibyte encoding in
4865 the current locale's codepage. */
4867 BYTE lname
[MAX_PATH
];
4870 reparse_data
->SymbolicLinkReparseBuffer
.PrintNameLength
;
4872 reparse_data
->SymbolicLinkReparseBuffer
.PathBuffer
4873 + reparse_data
->SymbolicLinkReparseBuffer
.PrintNameOffset
/sizeof(WCHAR
);
4874 /* This updates file_name_codepage which we need below. */
4875 int dbcs_p
= max_filename_mbslen () > 1;
4877 /* According to MSDN, PrintNameLength does not include the
4878 terminating null character. */
4879 lwname
= alloca ((lwname_len
+ 1) * sizeof(WCHAR
));
4880 memcpy (lwname
, lwname_src
, lwname_len
);
4881 lwname
[lwname_len
/sizeof(WCHAR
)] = 0; /* null-terminate */
4883 lname_len
= WideCharToMultiByte (file_name_codepage
, 0, lwname
, -1,
4884 lname
, MAX_PATH
, NULL
, NULL
);
4887 /* WideCharToMultiByte failed. */
4888 DWORD w32err1
= GetLastError ();
4892 case ERROR_INSUFFICIENT_BUFFER
:
4893 errno
= ENAMETOOLONG
;
4895 case ERROR_INVALID_PARAMETER
:
4898 case ERROR_NO_UNICODE_TRANSLATION
:
4908 size_t size_to_copy
= buf_size
;
4909 BYTE
*p
= lname
, *p2
;
4910 BYTE
*pend
= p
+ lname_len
;
4912 /* Normalize like dostounix_filename does, but we don't
4913 want to assume that lname is null-terminated. */
4915 p2
= CharNextExA (file_name_codepage
, p
, 0);
4918 if (*p
&& *p2
== ':' && *p
>= 'A' && *p
<= 'Z')
4929 p
= CharNextExA (file_name_codepage
, p
, 0);
4930 /* CharNextExA doesn't advance at null character. */
4937 /* Testing for null-terminated LNAME is paranoia:
4938 WideCharToMultiByte should always return a
4939 null-terminated string when its 4th argument is -1
4940 and its 3rd argument is null-terminated (which they
4942 if (lname
[lname_len
- 1] == '\0')
4944 if (lname_len
<= buf_size
)
4945 size_to_copy
= lname_len
;
4946 strncpy (buf
, lname
, size_to_copy
);
4948 retval
= size_to_copy
;
4955 /* CreateFile failed. */
4956 DWORD w32err2
= GetLastError ();
4960 case ERROR_FILE_NOT_FOUND
:
4961 case ERROR_PATH_NOT_FOUND
:
4964 case ERROR_ACCESS_DENIED
:
4965 case ERROR_TOO_MANY_OPEN_FILES
:
4975 restore_privilege (&privs
);
4983 readlinkat (int fd
, char const *name
, char *buffer
,
4986 /* Rely on a hack: an open directory is modeled as file descriptor 0,
4987 as in fstatat. FIXME: Add proper support for readlinkat. */
4988 char fullname
[MAX_PATH
];
4992 if (_snprintf (fullname
, sizeof fullname
, "%s/%s", dir_pathname
, name
)
4995 errno
= ENAMETOOLONG
;
5001 return readlink (name
, buffer
, buffer_size
);
5004 /* If FILE is a symlink, return its target (stored in a static
5005 buffer); otherwise return FILE.
5007 This function repeatedly resolves symlinks in the last component of
5008 a chain of symlink file names, as in foo -> bar -> baz -> ...,
5009 until it arrives at a file whose last component is not a symlink,
5010 or some error occurs. It returns the target of the last
5011 successfully resolved symlink in the chain. If it succeeds to
5012 resolve even a single symlink, the value returned is an absolute
5013 file name with backslashes (result of GetFullPathName). By
5014 contrast, if the original FILE is returned, it is unaltered.
5016 Note: This function can set errno even if it succeeds.
5018 Implementation note: we only resolve the last portion ("basename")
5019 of the argument FILE and of each following file in the chain,
5020 disregarding any possible symlinks in its leading directories.
5021 This is because Windows system calls and library functions
5022 transparently resolve symlinks in leading directories and return
5023 correct information, as long as the basename is not a symlink. */
5025 chase_symlinks (const char *file
)
5027 static char target
[MAX_PATH
];
5028 char link
[MAX_PATH
];
5029 ssize_t res
, link_len
;
5033 if (is_windows_9x () == TRUE
|| !is_symlink (file
))
5034 return (char *)file
;
5036 if ((link_len
= GetFullPathName (file
, MAX_PATH
, link
, NULL
)) == 0)
5037 return (char *)file
;
5039 dbcs_p
= max_filename_mbslen () > 1;
5043 /* Remove trailing slashes, as we want to resolve the last
5044 non-trivial part of the link name. */
5047 while (link_len
> 3 && IS_DIRECTORY_SEP (link
[link_len
-1]))
5048 link
[link_len
--] = '\0';
5050 else if (link_len
> 3)
5052 char *n
= CharPrevExA (file_name_codepage
, link
, link
+ link_len
, 0);
5054 while (n
>= link
+ 2 && IS_DIRECTORY_SEP (*n
))
5057 n
= CharPrevExA (file_name_codepage
, link
, n
, 0);
5061 res
= readlink (link
, target
, MAX_PATH
);
5065 if (!(IS_DEVICE_SEP (target
[1])
5066 || (IS_DIRECTORY_SEP (target
[0]) && IS_DIRECTORY_SEP (target
[1]))))
5068 /* Target is relative. Append it to the directory part of
5069 the symlink, then copy the result back to target. */
5070 char *p
= link
+ link_len
;
5074 while (p
> link
&& !IS_ANY_SEP (p
[-1]))
5079 char *p1
= CharPrevExA (file_name_codepage
, link
, p
, 0);
5081 while (p
> link
&& !IS_ANY_SEP (*p1
))
5084 p1
= CharPrevExA (file_name_codepage
, link
, p1
, 0);
5088 strcpy (target
, link
);
5090 /* Resolve any "." and ".." to get a fully-qualified file name
5092 link_len
= GetFullPathName (target
, MAX_PATH
, link
, NULL
);
5094 } while (res
> 0 && link_len
> 0 && ++loop_count
<= 100);
5096 if (loop_count
> 100)
5099 if (target
[0] == '\0') /* not a single call to readlink succeeded */
5100 return (char *)file
;
5105 /* Posix ACL emulation. */
5108 acl_valid (acl_t acl
)
5110 return is_valid_security_descriptor ((PSECURITY_DESCRIPTOR
)acl
) ? 0 : -1;
5114 acl_to_text (acl_t acl
, ssize_t
*size
)
5117 SECURITY_INFORMATION flags
=
5118 OWNER_SECURITY_INFORMATION
|
5119 GROUP_SECURITY_INFORMATION
|
5120 DACL_SECURITY_INFORMATION
;
5121 char *retval
= NULL
;
5127 if (convert_sd_to_sddl ((PSECURITY_DESCRIPTOR
)acl
, SDDL_REVISION_1
, flags
, &str_acl
, &local_size
))
5130 /* We don't want to mix heaps, so we duplicate the string in our
5131 heap and free the one allocated by the API. */
5132 retval
= xstrdup (str_acl
);
5135 LocalFree (str_acl
);
5137 else if (errno
!= ENOTSUP
)
5144 acl_from_text (const char *acl_str
)
5146 PSECURITY_DESCRIPTOR psd
, retval
= NULL
;
5152 if (convert_sddl_to_sd (acl_str
, SDDL_REVISION_1
, &psd
, &sd_size
))
5155 retval
= xmalloc (sd_size
);
5156 memcpy (retval
, psd
, sd_size
);
5159 else if (errno
!= ENOTSUP
)
5166 acl_free (void *ptr
)
5173 acl_get_file (const char *fname
, acl_type_t type
)
5175 PSECURITY_DESCRIPTOR psd
= NULL
;
5176 const char *filename
;
5178 if (type
== ACL_TYPE_ACCESS
)
5181 SECURITY_INFORMATION si
=
5182 OWNER_SECURITY_INFORMATION
|
5183 GROUP_SECURITY_INFORMATION
|
5184 DACL_SECURITY_INFORMATION
;
5187 filename
= map_w32_filename (fname
, NULL
);
5188 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) != 0)
5189 fname
= chase_symlinks (filename
);
5194 if (!get_file_security (fname
, si
, psd
, 0, &sd_len
)
5195 && errno
!= ENOTSUP
)
5197 err
= GetLastError ();
5198 if (err
== ERROR_INSUFFICIENT_BUFFER
)
5200 psd
= xmalloc (sd_len
);
5201 if (!get_file_security (fname
, si
, psd
, sd_len
, &sd_len
))
5208 else if (err
== ERROR_FILE_NOT_FOUND
5209 || err
== ERROR_PATH_NOT_FOUND
)
5217 else if (type
!= ACL_TYPE_DEFAULT
)
5224 acl_set_file (const char *fname
, acl_type_t type
, acl_t acl
)
5226 TOKEN_PRIVILEGES old1
, old2
;
5228 int st
= 0, retval
= -1;
5229 SECURITY_INFORMATION flags
= 0;
5235 const char *filename
;
5237 if (acl_valid (acl
) != 0
5238 || (type
!= ACL_TYPE_DEFAULT
&& type
!= ACL_TYPE_ACCESS
))
5244 if (type
== ACL_TYPE_DEFAULT
)
5250 filename
= map_w32_filename (fname
, NULL
);
5251 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) != 0)
5252 fname
= chase_symlinks (filename
);
5256 if (get_security_descriptor_owner ((PSECURITY_DESCRIPTOR
)acl
, &psid
, &dflt
)
5258 flags
|= OWNER_SECURITY_INFORMATION
;
5259 if (get_security_descriptor_group ((PSECURITY_DESCRIPTOR
)acl
, &psid
, &dflt
)
5261 flags
|= GROUP_SECURITY_INFORMATION
;
5262 if (get_security_descriptor_dacl ((PSECURITY_DESCRIPTOR
)acl
, &dacl_present
,
5265 flags
|= DACL_SECURITY_INFORMATION
;
5269 /* According to KB-245153, setting the owner will succeed if either:
5270 (1) the caller is the user who will be the new owner, and has the
5271 SE_TAKE_OWNERSHIP privilege, or
5272 (2) the caller has the SE_RESTORE privilege, in which case she can
5273 set any valid user or group as the owner
5275 We request below both SE_TAKE_OWNERSHIP and SE_RESTORE
5276 privileges, and disregard any failures in obtaining them. If
5277 these privileges cannot be obtained, and do not already exist in
5278 the calling thread's security token, this function could fail
5280 if (enable_privilege (SE_TAKE_OWNERSHIP_NAME
, TRUE
, &old1
))
5282 if (enable_privilege (SE_RESTORE_NAME
, TRUE
, &old2
))
5287 if (!set_file_security ((char *)fname
, flags
, (PSECURITY_DESCRIPTOR
)acl
))
5289 err
= GetLastError ();
5291 if (errno
== ENOTSUP
)
5293 else if (err
== ERROR_INVALID_OWNER
5294 || err
== ERROR_NOT_ALL_ASSIGNED
5295 || err
== ERROR_ACCESS_DENIED
)
5297 /* Maybe the requested ACL and the one the file already has
5298 are identical, in which case we can silently ignore the
5299 failure. (And no, Windows doesn't.) */
5300 acl_t current_acl
= acl_get_file (fname
, ACL_TYPE_ACCESS
);
5305 char *acl_from
= acl_to_text (current_acl
, NULL
);
5306 char *acl_to
= acl_to_text (acl
, NULL
);
5308 if (acl_from
&& acl_to
&& xstrcasecmp (acl_from
, acl_to
) == 0)
5314 acl_free (acl_from
);
5317 acl_free (current_acl
);
5320 else if (err
== ERROR_FILE_NOT_FOUND
|| err
== ERROR_PATH_NOT_FOUND
)
5334 restore_privilege (&old2
);
5335 restore_privilege (&old1
);
5343 /* MS-Windows version of careadlinkat (cf. ../lib/careadlinkat.c). We
5344 have a fixed max size for file names, so we don't need the kind of
5345 alloc/malloc/realloc dance the gnulib version does. We also don't
5346 support FD-relative symlinks. */
5348 careadlinkat (int fd
, char const *filename
,
5349 char *buffer
, size_t buffer_size
,
5350 struct allocator
const *alloc
,
5351 ssize_t (*preadlinkat
) (int, char const *, char *, size_t))
5353 char linkname
[MAX_PATH
];
5356 link_size
= preadlinkat (fd
, filename
, linkname
, sizeof(linkname
));
5360 char *retval
= buffer
;
5362 linkname
[link_size
++] = '\0';
5363 if (link_size
> buffer_size
)
5364 retval
= (char *)(alloc
? alloc
->allocate
: xmalloc
) (link_size
);
5366 memcpy (retval
, linkname
, link_size
);
5374 /* Support for browsing other processes and their attributes. See
5375 process.c for the Lisp bindings. */
5377 /* Helper wrapper functions. */
5379 static HANDLE WINAPI
5380 create_toolhelp32_snapshot (DWORD Flags
, DWORD Ignored
)
5382 static CreateToolhelp32Snapshot_Proc s_pfn_Create_Toolhelp32_Snapshot
= NULL
;
5384 if (g_b_init_create_toolhelp32_snapshot
== 0)
5386 g_b_init_create_toolhelp32_snapshot
= 1;
5387 s_pfn_Create_Toolhelp32_Snapshot
= (CreateToolhelp32Snapshot_Proc
)
5388 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5389 "CreateToolhelp32Snapshot");
5391 if (s_pfn_Create_Toolhelp32_Snapshot
== NULL
)
5393 return INVALID_HANDLE_VALUE
;
5395 return (s_pfn_Create_Toolhelp32_Snapshot (Flags
, Ignored
));
5399 process32_first (HANDLE hSnapshot
, LPPROCESSENTRY32 lppe
)
5401 static Process32First_Proc s_pfn_Process32_First
= NULL
;
5403 if (g_b_init_process32_first
== 0)
5405 g_b_init_process32_first
= 1;
5406 s_pfn_Process32_First
= (Process32First_Proc
)
5407 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5410 if (s_pfn_Process32_First
== NULL
)
5414 return (s_pfn_Process32_First (hSnapshot
, lppe
));
5418 process32_next (HANDLE hSnapshot
, LPPROCESSENTRY32 lppe
)
5420 static Process32Next_Proc s_pfn_Process32_Next
= NULL
;
5422 if (g_b_init_process32_next
== 0)
5424 g_b_init_process32_next
= 1;
5425 s_pfn_Process32_Next
= (Process32Next_Proc
)
5426 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5429 if (s_pfn_Process32_Next
== NULL
)
5433 return (s_pfn_Process32_Next (hSnapshot
, lppe
));
5437 open_thread_token (HANDLE ThreadHandle
,
5438 DWORD DesiredAccess
,
5440 PHANDLE TokenHandle
)
5442 static OpenThreadToken_Proc s_pfn_Open_Thread_Token
= NULL
;
5443 HMODULE hm_advapi32
= NULL
;
5444 if (is_windows_9x () == TRUE
)
5446 SetLastError (ERROR_NOT_SUPPORTED
);
5449 if (g_b_init_open_thread_token
== 0)
5451 g_b_init_open_thread_token
= 1;
5452 hm_advapi32
= LoadLibrary ("Advapi32.dll");
5453 s_pfn_Open_Thread_Token
=
5454 (OpenThreadToken_Proc
) GetProcAddress (hm_advapi32
, "OpenThreadToken");
5456 if (s_pfn_Open_Thread_Token
== NULL
)
5458 SetLastError (ERROR_NOT_SUPPORTED
);
5462 s_pfn_Open_Thread_Token (
5471 impersonate_self (SECURITY_IMPERSONATION_LEVEL ImpersonationLevel
)
5473 static ImpersonateSelf_Proc s_pfn_Impersonate_Self
= NULL
;
5474 HMODULE hm_advapi32
= NULL
;
5475 if (is_windows_9x () == TRUE
)
5479 if (g_b_init_impersonate_self
== 0)
5481 g_b_init_impersonate_self
= 1;
5482 hm_advapi32
= LoadLibrary ("Advapi32.dll");
5483 s_pfn_Impersonate_Self
=
5484 (ImpersonateSelf_Proc
) GetProcAddress (hm_advapi32
, "ImpersonateSelf");
5486 if (s_pfn_Impersonate_Self
== NULL
)
5490 return s_pfn_Impersonate_Self (ImpersonationLevel
);
5494 revert_to_self (void)
5496 static RevertToSelf_Proc s_pfn_Revert_To_Self
= NULL
;
5497 HMODULE hm_advapi32
= NULL
;
5498 if (is_windows_9x () == TRUE
)
5502 if (g_b_init_revert_to_self
== 0)
5504 g_b_init_revert_to_self
= 1;
5505 hm_advapi32
= LoadLibrary ("Advapi32.dll");
5506 s_pfn_Revert_To_Self
=
5507 (RevertToSelf_Proc
) GetProcAddress (hm_advapi32
, "RevertToSelf");
5509 if (s_pfn_Revert_To_Self
== NULL
)
5513 return s_pfn_Revert_To_Self ();
5517 get_process_memory_info (HANDLE h_proc
,
5518 PPROCESS_MEMORY_COUNTERS mem_counters
,
5521 static GetProcessMemoryInfo_Proc s_pfn_Get_Process_Memory_Info
= NULL
;
5522 HMODULE hm_psapi
= NULL
;
5523 if (is_windows_9x () == TRUE
)
5527 if (g_b_init_get_process_memory_info
== 0)
5529 g_b_init_get_process_memory_info
= 1;
5530 hm_psapi
= LoadLibrary ("Psapi.dll");
5532 s_pfn_Get_Process_Memory_Info
= (GetProcessMemoryInfo_Proc
)
5533 GetProcAddress (hm_psapi
, "GetProcessMemoryInfo");
5535 if (s_pfn_Get_Process_Memory_Info
== NULL
)
5539 return s_pfn_Get_Process_Memory_Info (h_proc
, mem_counters
, bufsize
);
5543 get_process_working_set_size (HANDLE h_proc
,
5547 static GetProcessWorkingSetSize_Proc
5548 s_pfn_Get_Process_Working_Set_Size
= NULL
;
5550 if (is_windows_9x () == TRUE
)
5554 if (g_b_init_get_process_working_set_size
== 0)
5556 g_b_init_get_process_working_set_size
= 1;
5557 s_pfn_Get_Process_Working_Set_Size
= (GetProcessWorkingSetSize_Proc
)
5558 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5559 "GetProcessWorkingSetSize");
5561 if (s_pfn_Get_Process_Working_Set_Size
== NULL
)
5565 return s_pfn_Get_Process_Working_Set_Size (h_proc
, minrss
, maxrss
);
5569 global_memory_status (MEMORYSTATUS
*buf
)
5571 static GlobalMemoryStatus_Proc s_pfn_Global_Memory_Status
= NULL
;
5573 if (is_windows_9x () == TRUE
)
5577 if (g_b_init_global_memory_status
== 0)
5579 g_b_init_global_memory_status
= 1;
5580 s_pfn_Global_Memory_Status
= (GlobalMemoryStatus_Proc
)
5581 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5582 "GlobalMemoryStatus");
5584 if (s_pfn_Global_Memory_Status
== NULL
)
5588 return s_pfn_Global_Memory_Status (buf
);
5592 global_memory_status_ex (MEMORY_STATUS_EX
*buf
)
5594 static GlobalMemoryStatusEx_Proc s_pfn_Global_Memory_Status_Ex
= NULL
;
5596 if (is_windows_9x () == TRUE
)
5600 if (g_b_init_global_memory_status_ex
== 0)
5602 g_b_init_global_memory_status_ex
= 1;
5603 s_pfn_Global_Memory_Status_Ex
= (GlobalMemoryStatusEx_Proc
)
5604 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5605 "GlobalMemoryStatusEx");
5607 if (s_pfn_Global_Memory_Status_Ex
== NULL
)
5611 return s_pfn_Global_Memory_Status_Ex (buf
);
5615 list_system_processes (void)
5617 struct gcpro gcpro1
;
5618 Lisp_Object proclist
= Qnil
;
5621 h_snapshot
= create_toolhelp32_snapshot (TH32CS_SNAPPROCESS
, 0);
5623 if (h_snapshot
!= INVALID_HANDLE_VALUE
)
5625 PROCESSENTRY32 proc_entry
;
5631 proc_entry
.dwSize
= sizeof (PROCESSENTRY32
);
5632 for (res
= process32_first (h_snapshot
, &proc_entry
); res
;
5633 res
= process32_next (h_snapshot
, &proc_entry
))
5635 proc_id
= proc_entry
.th32ProcessID
;
5636 proclist
= Fcons (make_fixnum_or_float (proc_id
), proclist
);
5639 CloseHandle (h_snapshot
);
5641 proclist
= Fnreverse (proclist
);
5648 enable_privilege (LPCTSTR priv_name
, BOOL enable_p
, TOKEN_PRIVILEGES
*old_priv
)
5650 TOKEN_PRIVILEGES priv
;
5651 DWORD priv_size
= sizeof (priv
);
5652 DWORD opriv_size
= sizeof (*old_priv
);
5653 HANDLE h_token
= NULL
;
5654 HANDLE h_thread
= GetCurrentThread ();
5658 res
= open_thread_token (h_thread
,
5659 TOKEN_QUERY
| TOKEN_ADJUST_PRIVILEGES
,
5661 if (!res
&& GetLastError () == ERROR_NO_TOKEN
)
5663 if (impersonate_self (SecurityImpersonation
))
5664 res
= open_thread_token (h_thread
,
5665 TOKEN_QUERY
| TOKEN_ADJUST_PRIVILEGES
,
5670 priv
.PrivilegeCount
= 1;
5671 priv
.Privileges
[0].Attributes
= enable_p
? SE_PRIVILEGE_ENABLED
: 0;
5672 LookupPrivilegeValue (NULL
, priv_name
, &priv
.Privileges
[0].Luid
);
5673 if (AdjustTokenPrivileges (h_token
, FALSE
, &priv
, priv_size
,
5674 old_priv
, &opriv_size
)
5675 && GetLastError () != ERROR_NOT_ALL_ASSIGNED
)
5679 CloseHandle (h_token
);
5685 restore_privilege (TOKEN_PRIVILEGES
*priv
)
5687 DWORD priv_size
= sizeof (*priv
);
5688 HANDLE h_token
= NULL
;
5691 if (open_thread_token (GetCurrentThread (),
5692 TOKEN_QUERY
| TOKEN_ADJUST_PRIVILEGES
,
5695 if (AdjustTokenPrivileges (h_token
, FALSE
, priv
, priv_size
, NULL
, NULL
)
5696 && GetLastError () != ERROR_NOT_ALL_ASSIGNED
)
5700 CloseHandle (h_token
);
5706 ltime (ULONGLONG time_100ns
)
5708 ULONGLONG time_sec
= time_100ns
/ 10000000;
5709 int subsec
= time_100ns
% 10000000;
5710 return list4i (time_sec
>> 16, time_sec
& 0xffff,
5711 subsec
/ 10, subsec
% 10 * 100000);
5714 #define U64_TO_LISP_TIME(time) ltime (time)
5717 process_times (HANDLE h_proc
, Lisp_Object
*ctime
, Lisp_Object
*etime
,
5718 Lisp_Object
*stime
, Lisp_Object
*utime
, Lisp_Object
*ttime
,
5721 FILETIME ft_creation
, ft_exit
, ft_kernel
, ft_user
, ft_current
;
5722 ULONGLONG tem1
, tem2
, tem3
, tem
;
5725 || !get_process_times_fn
5726 || !(*get_process_times_fn
) (h_proc
, &ft_creation
, &ft_exit
,
5727 &ft_kernel
, &ft_user
))
5730 GetSystemTimeAsFileTime (&ft_current
);
5732 FILETIME_TO_U64 (tem1
, ft_kernel
);
5733 *stime
= U64_TO_LISP_TIME (tem1
);
5735 FILETIME_TO_U64 (tem2
, ft_user
);
5736 *utime
= U64_TO_LISP_TIME (tem2
);
5739 *ttime
= U64_TO_LISP_TIME (tem3
);
5741 FILETIME_TO_U64 (tem
, ft_creation
);
5742 /* Process no 4 (System) returns zero creation time. */
5745 *ctime
= U64_TO_LISP_TIME (tem
);
5749 FILETIME_TO_U64 (tem3
, ft_current
);
5750 tem
= (tem3
- utc_base
) - tem
;
5752 *etime
= U64_TO_LISP_TIME (tem
);
5756 *pcpu
= 100.0 * (tem1
+ tem2
) / tem
;
5767 system_process_attributes (Lisp_Object pid
)
5769 struct gcpro gcpro1
, gcpro2
, gcpro3
;
5770 Lisp_Object attrs
= Qnil
;
5771 Lisp_Object cmd_str
, decoded_cmd
, tem
;
5772 HANDLE h_snapshot
, h_proc
;
5775 char uname
[UNLEN
+1], gname
[GNLEN
+1], domain
[1025];
5776 DWORD ulength
= sizeof (uname
), dlength
= sizeof (domain
), needed
;
5777 DWORD glength
= sizeof (gname
);
5778 HANDLE token
= NULL
;
5779 SID_NAME_USE user_type
;
5780 unsigned char *buf
= NULL
;
5782 TOKEN_USER user_token
;
5783 TOKEN_PRIMARY_GROUP group_token
;
5786 PROCESS_MEMORY_COUNTERS mem
;
5787 PROCESS_MEMORY_COUNTERS_EX mem_ex
;
5788 SIZE_T minrss
, maxrss
;
5790 MEMORY_STATUS_EX memstex
;
5791 double totphys
= 0.0;
5792 Lisp_Object ctime
, stime
, utime
, etime
, ttime
;
5794 BOOL result
= FALSE
;
5796 CHECK_NUMBER_OR_FLOAT (pid
);
5797 proc_id
= FLOATP (pid
) ? XFLOAT_DATA (pid
) : XINT (pid
);
5799 h_snapshot
= create_toolhelp32_snapshot (TH32CS_SNAPPROCESS
, 0);
5801 GCPRO3 (attrs
, decoded_cmd
, tem
);
5803 if (h_snapshot
!= INVALID_HANDLE_VALUE
)
5808 pe
.dwSize
= sizeof (PROCESSENTRY32
);
5809 for (res
= process32_first (h_snapshot
, &pe
); res
;
5810 res
= process32_next (h_snapshot
, &pe
))
5812 if (proc_id
== pe
.th32ProcessID
)
5815 decoded_cmd
= build_string ("Idle");
5818 /* Decode the command name from locale-specific
5820 cmd_str
= build_unibyte_string (pe
.szExeFile
);
5823 code_convert_string_norecord (cmd_str
,
5824 Vlocale_coding_system
, 0);
5826 attrs
= Fcons (Fcons (Qcomm
, decoded_cmd
), attrs
);
5827 attrs
= Fcons (Fcons (Qppid
,
5828 make_fixnum_or_float (pe
.th32ParentProcessID
)),
5830 attrs
= Fcons (Fcons (Qpri
, make_number (pe
.pcPriClassBase
)),
5832 attrs
= Fcons (Fcons (Qthcount
,
5833 make_fixnum_or_float (pe
.cntThreads
)),
5840 CloseHandle (h_snapshot
);
5849 h_proc
= OpenProcess (PROCESS_QUERY_INFORMATION
| PROCESS_VM_READ
,
5851 /* If we were denied a handle to the process, try again after
5852 enabling the SeDebugPrivilege in our process. */
5855 TOKEN_PRIVILEGES priv_current
;
5857 if (enable_privilege (SE_DEBUG_NAME
, TRUE
, &priv_current
))
5859 h_proc
= OpenProcess (PROCESS_QUERY_INFORMATION
| PROCESS_VM_READ
,
5861 restore_privilege (&priv_current
);
5867 result
= open_process_token (h_proc
, TOKEN_QUERY
, &token
);
5870 result
= get_token_information (token
, TokenUser
, NULL
, 0, &blen
);
5871 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
5873 buf
= xmalloc (blen
);
5874 result
= get_token_information (token
, TokenUser
,
5875 (LPVOID
)buf
, blen
, &needed
);
5878 memcpy (&user_token
, buf
, sizeof (user_token
));
5879 if (!w32_cached_id (user_token
.User
.Sid
, &euid
, uname
))
5881 euid
= get_rid (user_token
.User
.Sid
);
5882 result
= lookup_account_sid (NULL
, user_token
.User
.Sid
,
5887 w32_add_to_cache (user_token
.User
.Sid
, euid
, uname
);
5890 strcpy (uname
, "unknown");
5894 ulength
= strlen (uname
);
5900 /* Determine a reasonable euid and gid values. */
5901 if (xstrcasecmp ("administrator", uname
) == 0)
5903 euid
= 500; /* well-known Administrator uid */
5904 egid
= 513; /* well-known None gid */
5908 /* Get group id and name. */
5909 result
= get_token_information (token
, TokenPrimaryGroup
,
5910 (LPVOID
)buf
, blen
, &needed
);
5911 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
5913 buf
= xrealloc (buf
, blen
= needed
);
5914 result
= get_token_information (token
, TokenPrimaryGroup
,
5915 (LPVOID
)buf
, blen
, &needed
);
5919 memcpy (&group_token
, buf
, sizeof (group_token
));
5920 if (!w32_cached_id (group_token
.PrimaryGroup
, &egid
, gname
))
5922 egid
= get_rid (group_token
.PrimaryGroup
);
5923 dlength
= sizeof (domain
);
5925 lookup_account_sid (NULL
, group_token
.PrimaryGroup
,
5926 gname
, &glength
, NULL
, &dlength
,
5929 w32_add_to_cache (group_token
.PrimaryGroup
,
5933 strcpy (gname
, "None");
5937 glength
= strlen (gname
);
5945 if (!is_windows_9x ())
5947 /* We couldn't open the process token, presumably because of
5948 insufficient access rights. Assume this process is run
5950 strcpy (uname
, "SYSTEM");
5951 strcpy (gname
, "None");
5952 euid
= 18; /* SYSTEM */
5953 egid
= 513; /* None */
5954 glength
= strlen (gname
);
5955 ulength
= strlen (uname
);
5957 /* If we are running under Windows 9X, where security calls are
5958 not supported, we assume all processes are run by the current
5960 else if (GetUserName (uname
, &ulength
))
5962 if (xstrcasecmp ("administrator", uname
) == 0)
5967 strcpy (gname
, "None");
5968 glength
= strlen (gname
);
5969 ulength
= strlen (uname
);
5975 strcpy (uname
, "administrator");
5976 ulength
= strlen (uname
);
5977 strcpy (gname
, "None");
5978 glength
= strlen (gname
);
5981 CloseHandle (token
);
5984 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (euid
)), attrs
);
5985 tem
= make_unibyte_string (uname
, ulength
);
5986 attrs
= Fcons (Fcons (Quser
,
5987 code_convert_string_norecord (tem
, Vlocale_coding_system
, 0)),
5989 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (egid
)), attrs
);
5990 tem
= make_unibyte_string (gname
, glength
);
5991 attrs
= Fcons (Fcons (Qgroup
,
5992 code_convert_string_norecord (tem
, Vlocale_coding_system
, 0)),
5995 if (global_memory_status_ex (&memstex
))
5996 #if __GNUC__ || (defined (_MSC_VER) && _MSC_VER >= 1300)
5997 totphys
= memstex
.ullTotalPhys
/ 1024.0;
5999 /* Visual Studio 6 cannot convert an unsigned __int64 type to
6000 double, so we need to do this for it... */
6002 DWORD tot_hi
= memstex
.ullTotalPhys
>> 32;
6003 DWORD tot_md
= (memstex
.ullTotalPhys
& 0x00000000ffffffff) >> 10;
6004 DWORD tot_lo
= memstex
.ullTotalPhys
% 1024;
6006 totphys
= tot_hi
* 4194304.0 + tot_md
+ tot_lo
/ 1024.0;
6008 #endif /* __GNUC__ || _MSC_VER >= 1300 */
6009 else if (global_memory_status (&memst
))
6010 totphys
= memst
.dwTotalPhys
/ 1024.0;
6013 && get_process_memory_info (h_proc
, (PROCESS_MEMORY_COUNTERS
*)&mem_ex
,
6016 SIZE_T rss
= mem_ex
.WorkingSetSize
/ 1024;
6018 attrs
= Fcons (Fcons (Qmajflt
,
6019 make_fixnum_or_float (mem_ex
.PageFaultCount
)),
6021 attrs
= Fcons (Fcons (Qvsize
,
6022 make_fixnum_or_float (mem_ex
.PrivateUsage
/ 1024)),
6024 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (rss
)), attrs
);
6026 attrs
= Fcons (Fcons (Qpmem
, make_float (100. * rss
/ totphys
)), attrs
);
6029 && get_process_memory_info (h_proc
, &mem
, sizeof (mem
)))
6031 SIZE_T rss
= mem_ex
.WorkingSetSize
/ 1024;
6033 attrs
= Fcons (Fcons (Qmajflt
,
6034 make_fixnum_or_float (mem
.PageFaultCount
)),
6036 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (rss
)), attrs
);
6038 attrs
= Fcons (Fcons (Qpmem
, make_float (100. * rss
/ totphys
)), attrs
);
6041 && get_process_working_set_size (h_proc
, &minrss
, &maxrss
))
6043 DWORD rss
= maxrss
/ 1024;
6045 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (maxrss
/ 1024)), attrs
);
6047 attrs
= Fcons (Fcons (Qpmem
, make_float (100. * rss
/ totphys
)), attrs
);
6050 if (process_times (h_proc
, &ctime
, &etime
, &stime
, &utime
, &ttime
, &pcpu
))
6052 attrs
= Fcons (Fcons (Qutime
, utime
), attrs
);
6053 attrs
= Fcons (Fcons (Qstime
, stime
), attrs
);
6054 attrs
= Fcons (Fcons (Qtime
, ttime
), attrs
);
6055 attrs
= Fcons (Fcons (Qstart
, ctime
), attrs
);
6056 attrs
= Fcons (Fcons (Qetime
, etime
), attrs
);
6057 attrs
= Fcons (Fcons (Qpcpu
, make_float (pcpu
)), attrs
);
6060 /* FIXME: Retrieve command line by walking the PEB of the process. */
6063 CloseHandle (h_proc
);
6069 /* Wrappers for winsock functions to map between our file descriptors
6070 and winsock's handles; also set h_errno for convenience.
6072 To allow Emacs to run on systems which don't have winsock support
6073 installed, we dynamically link to winsock on startup if present, and
6074 otherwise provide the minimum necessary functionality
6075 (eg. gethostname). */
6077 /* function pointers for relevant socket functions */
6078 int (PASCAL
*pfn_WSAStartup
) (WORD wVersionRequired
, LPWSADATA lpWSAData
);
6079 void (PASCAL
*pfn_WSASetLastError
) (int iError
);
6080 int (PASCAL
*pfn_WSAGetLastError
) (void);
6081 int (PASCAL
*pfn_WSAEventSelect
) (SOCKET s
, HANDLE hEventObject
, long lNetworkEvents
);
6082 HANDLE (PASCAL
*pfn_WSACreateEvent
) (void);
6083 int (PASCAL
*pfn_WSACloseEvent
) (HANDLE hEvent
);
6084 int (PASCAL
*pfn_socket
) (int af
, int type
, int protocol
);
6085 int (PASCAL
*pfn_bind
) (SOCKET s
, const struct sockaddr
*addr
, int namelen
);
6086 int (PASCAL
*pfn_connect
) (SOCKET s
, const struct sockaddr
*addr
, int namelen
);
6087 int (PASCAL
*pfn_ioctlsocket
) (SOCKET s
, long cmd
, u_long
*argp
);
6088 int (PASCAL
*pfn_recv
) (SOCKET s
, char * buf
, int len
, int flags
);
6089 int (PASCAL
*pfn_send
) (SOCKET s
, const char * buf
, int len
, int flags
);
6090 int (PASCAL
*pfn_closesocket
) (SOCKET s
);
6091 int (PASCAL
*pfn_shutdown
) (SOCKET s
, int how
);
6092 int (PASCAL
*pfn_WSACleanup
) (void);
6094 u_short (PASCAL
*pfn_htons
) (u_short hostshort
);
6095 u_short (PASCAL
*pfn_ntohs
) (u_short netshort
);
6096 unsigned long (PASCAL
*pfn_inet_addr
) (const char * cp
);
6097 int (PASCAL
*pfn_gethostname
) (char * name
, int namelen
);
6098 struct hostent
* (PASCAL
*pfn_gethostbyname
) (const char * name
);
6099 struct servent
* (PASCAL
*pfn_getservbyname
) (const char * name
, const char * proto
);
6100 int (PASCAL
*pfn_getpeername
) (SOCKET s
, struct sockaddr
*addr
, int * namelen
);
6101 int (PASCAL
*pfn_setsockopt
) (SOCKET s
, int level
, int optname
,
6102 const char * optval
, int optlen
);
6103 int (PASCAL
*pfn_listen
) (SOCKET s
, int backlog
);
6104 int (PASCAL
*pfn_getsockname
) (SOCKET s
, struct sockaddr
* name
,
6106 SOCKET (PASCAL
*pfn_accept
) (SOCKET s
, struct sockaddr
* addr
, int * addrlen
);
6107 int (PASCAL
*pfn_recvfrom
) (SOCKET s
, char * buf
, int len
, int flags
,
6108 struct sockaddr
* from
, int * fromlen
);
6109 int (PASCAL
*pfn_sendto
) (SOCKET s
, const char * buf
, int len
, int flags
,
6110 const struct sockaddr
* to
, int tolen
);
6112 /* SetHandleInformation is only needed to make sockets non-inheritable. */
6113 BOOL (WINAPI
*pfn_SetHandleInformation
) (HANDLE object
, DWORD mask
, DWORD flags
);
6114 #ifndef HANDLE_FLAG_INHERIT
6115 #define HANDLE_FLAG_INHERIT 1
6119 static int winsock_inuse
;
6124 if (winsock_lib
!= NULL
&& winsock_inuse
== 0)
6126 release_listen_threads ();
6127 /* Not sure what would cause WSAENETDOWN, or even if it can happen
6128 after WSAStartup returns successfully, but it seems reasonable
6129 to allow unloading winsock anyway in that case. */
6130 if (pfn_WSACleanup () == 0 ||
6131 pfn_WSAGetLastError () == WSAENETDOWN
)
6133 if (FreeLibrary (winsock_lib
))
6142 init_winsock (int load_now
)
6144 WSADATA winsockData
;
6146 if (winsock_lib
!= NULL
)
6149 pfn_SetHandleInformation
6150 = (void *) GetProcAddress (GetModuleHandle ("kernel32.dll"),
6151 "SetHandleInformation");
6153 winsock_lib
= LoadLibrary ("Ws2_32.dll");
6155 if (winsock_lib
!= NULL
)
6157 /* dynamically link to socket functions */
6159 #define LOAD_PROC(fn) \
6160 if ((pfn_##fn = (void *) GetProcAddress (winsock_lib, #fn)) == NULL) \
6163 LOAD_PROC (WSAStartup
);
6164 LOAD_PROC (WSASetLastError
);
6165 LOAD_PROC (WSAGetLastError
);
6166 LOAD_PROC (WSAEventSelect
);
6167 LOAD_PROC (WSACreateEvent
);
6168 LOAD_PROC (WSACloseEvent
);
6171 LOAD_PROC (connect
);
6172 LOAD_PROC (ioctlsocket
);
6175 LOAD_PROC (closesocket
);
6176 LOAD_PROC (shutdown
);
6179 LOAD_PROC (inet_addr
);
6180 LOAD_PROC (gethostname
);
6181 LOAD_PROC (gethostbyname
);
6182 LOAD_PROC (getservbyname
);
6183 LOAD_PROC (getpeername
);
6184 LOAD_PROC (WSACleanup
);
6185 LOAD_PROC (setsockopt
);
6187 LOAD_PROC (getsockname
);
6189 LOAD_PROC (recvfrom
);
6193 /* specify version 1.1 of winsock */
6194 if (pfn_WSAStartup (0x101, &winsockData
) == 0)
6196 if (winsockData
.wVersion
!= 0x101)
6201 /* Report that winsock exists and is usable, but leave
6202 socket functions disabled. I am assuming that calling
6203 WSAStartup does not require any network interaction,
6204 and in particular does not cause or require a dial-up
6205 connection to be established. */
6208 FreeLibrary (winsock_lib
);
6216 FreeLibrary (winsock_lib
);
6226 /* Function to map winsock error codes to errno codes for those errno
6227 code defined in errno.h (errno values not defined by errno.h are
6228 already in nt/inc/sys/socket.h). */
6235 if (winsock_lib
== NULL
)
6238 wsa_err
= pfn_WSAGetLastError ();
6242 case WSAEACCES
: errno
= EACCES
; break;
6243 case WSAEBADF
: errno
= EBADF
; break;
6244 case WSAEFAULT
: errno
= EFAULT
; break;
6245 case WSAEINTR
: errno
= EINTR
; break;
6246 case WSAEINVAL
: errno
= EINVAL
; break;
6247 case WSAEMFILE
: errno
= EMFILE
; break;
6248 case WSAENAMETOOLONG
: errno
= ENAMETOOLONG
; break;
6249 case WSAENOTEMPTY
: errno
= ENOTEMPTY
; break;
6250 default: errno
= wsa_err
; break;
6258 if (winsock_lib
!= NULL
)
6259 pfn_WSASetLastError (0);
6262 /* Extend strerror to handle the winsock-specific error codes. */
6266 } _wsa_errlist
[] = {
6267 {WSAEINTR
, "Interrupted function call"},
6268 {WSAEBADF
, "Bad file descriptor"},
6269 {WSAEACCES
, "Permission denied"},
6270 {WSAEFAULT
, "Bad address"},
6271 {WSAEINVAL
, "Invalid argument"},
6272 {WSAEMFILE
, "Too many open files"},
6274 {WSAEWOULDBLOCK
, "Resource temporarily unavailable"},
6275 {WSAEINPROGRESS
, "Operation now in progress"},
6276 {WSAEALREADY
, "Operation already in progress"},
6277 {WSAENOTSOCK
, "Socket operation on non-socket"},
6278 {WSAEDESTADDRREQ
, "Destination address required"},
6279 {WSAEMSGSIZE
, "Message too long"},
6280 {WSAEPROTOTYPE
, "Protocol wrong type for socket"},
6281 {WSAENOPROTOOPT
, "Bad protocol option"},
6282 {WSAEPROTONOSUPPORT
, "Protocol not supported"},
6283 {WSAESOCKTNOSUPPORT
, "Socket type not supported"},
6284 {WSAEOPNOTSUPP
, "Operation not supported"},
6285 {WSAEPFNOSUPPORT
, "Protocol family not supported"},
6286 {WSAEAFNOSUPPORT
, "Address family not supported by protocol family"},
6287 {WSAEADDRINUSE
, "Address already in use"},
6288 {WSAEADDRNOTAVAIL
, "Cannot assign requested address"},
6289 {WSAENETDOWN
, "Network is down"},
6290 {WSAENETUNREACH
, "Network is unreachable"},
6291 {WSAENETRESET
, "Network dropped connection on reset"},
6292 {WSAECONNABORTED
, "Software caused connection abort"},
6293 {WSAECONNRESET
, "Connection reset by peer"},
6294 {WSAENOBUFS
, "No buffer space available"},
6295 {WSAEISCONN
, "Socket is already connected"},
6296 {WSAENOTCONN
, "Socket is not connected"},
6297 {WSAESHUTDOWN
, "Cannot send after socket shutdown"},
6298 {WSAETOOMANYREFS
, "Too many references"}, /* not sure */
6299 {WSAETIMEDOUT
, "Connection timed out"},
6300 {WSAECONNREFUSED
, "Connection refused"},
6301 {WSAELOOP
, "Network loop"}, /* not sure */
6302 {WSAENAMETOOLONG
, "Name is too long"},
6303 {WSAEHOSTDOWN
, "Host is down"},
6304 {WSAEHOSTUNREACH
, "No route to host"},
6305 {WSAENOTEMPTY
, "Buffer not empty"}, /* not sure */
6306 {WSAEPROCLIM
, "Too many processes"},
6307 {WSAEUSERS
, "Too many users"}, /* not sure */
6308 {WSAEDQUOT
, "Double quote in host name"}, /* really not sure */
6309 {WSAESTALE
, "Data is stale"}, /* not sure */
6310 {WSAEREMOTE
, "Remote error"}, /* not sure */
6312 {WSASYSNOTREADY
, "Network subsystem is unavailable"},
6313 {WSAVERNOTSUPPORTED
, "WINSOCK.DLL version out of range"},
6314 {WSANOTINITIALISED
, "Winsock not initialized successfully"},
6315 {WSAEDISCON
, "Graceful shutdown in progress"},
6317 {WSAENOMORE
, "No more operations allowed"}, /* not sure */
6318 {WSAECANCELLED
, "Operation cancelled"}, /* not sure */
6319 {WSAEINVALIDPROCTABLE
, "Invalid procedure table from service provider"},
6320 {WSAEINVALIDPROVIDER
, "Invalid service provider version number"},
6321 {WSAEPROVIDERFAILEDINIT
, "Unable to initialize a service provider"},
6322 {WSASYSCALLFAILURE
, "System call failure"},
6323 {WSASERVICE_NOT_FOUND
, "Service not found"}, /* not sure */
6324 {WSATYPE_NOT_FOUND
, "Class type not found"},
6325 {WSA_E_NO_MORE
, "No more resources available"}, /* really not sure */
6326 {WSA_E_CANCELLED
, "Operation already cancelled"}, /* really not sure */
6327 {WSAEREFUSED
, "Operation refused"}, /* not sure */
6330 {WSAHOST_NOT_FOUND
, "Host not found"},
6331 {WSATRY_AGAIN
, "Authoritative host not found during name lookup"},
6332 {WSANO_RECOVERY
, "Non-recoverable error during name lookup"},
6333 {WSANO_DATA
, "Valid name, no data record of requested type"},
6339 sys_strerror (int error_no
)
6342 static char unknown_msg
[40];
6344 if (error_no
>= 0 && error_no
< sys_nerr
)
6345 return sys_errlist
[error_no
];
6347 for (i
= 0; _wsa_errlist
[i
].errnum
>= 0; i
++)
6348 if (_wsa_errlist
[i
].errnum
== error_no
)
6349 return _wsa_errlist
[i
].msg
;
6351 sprintf (unknown_msg
, "Unidentified error: %d", error_no
);
6355 /* [andrewi 3-May-96] I've had conflicting results using both methods,
6356 but I believe the method of keeping the socket handle separate (and
6357 insuring it is not inheritable) is the correct one. */
6359 #define SOCK_HANDLE(fd) ((SOCKET) fd_info[fd].hnd)
6361 static int socket_to_fd (SOCKET s
);
6364 sys_socket (int af
, int type
, int protocol
)
6368 if (winsock_lib
== NULL
)
6371 return INVALID_SOCKET
;
6376 /* call the real socket function */
6377 s
= pfn_socket (af
, type
, protocol
);
6379 if (s
!= INVALID_SOCKET
)
6380 return socket_to_fd (s
);
6386 /* Convert a SOCKET to a file descriptor. */
6388 socket_to_fd (SOCKET s
)
6393 /* Although under NT 3.5 _open_osfhandle will accept a socket
6394 handle, if opened with SO_OPENTYPE == SO_SYNCHRONOUS_NONALERT,
6395 that does not work under NT 3.1. However, we can get the same
6396 effect by using a backdoor function to replace an existing
6397 descriptor handle with the one we want. */
6399 /* allocate a file descriptor (with appropriate flags) */
6400 fd
= _open ("NUL:", _O_RDWR
);
6403 /* Make a non-inheritable copy of the socket handle. Note
6404 that it is possible that sockets aren't actually kernel
6405 handles, which appears to be the case on Windows 9x when
6406 the MS Proxy winsock client is installed. */
6408 /* Apparently there is a bug in NT 3.51 with some service
6409 packs, which prevents using DuplicateHandle to make a
6410 socket handle non-inheritable (causes WSACleanup to
6411 hang). The work-around is to use SetHandleInformation
6412 instead if it is available and implemented. */
6413 if (pfn_SetHandleInformation
)
6415 pfn_SetHandleInformation ((HANDLE
) s
, HANDLE_FLAG_INHERIT
, 0);
6419 HANDLE parent
= GetCurrentProcess ();
6420 HANDLE new_s
= INVALID_HANDLE_VALUE
;
6422 if (DuplicateHandle (parent
,
6428 DUPLICATE_SAME_ACCESS
))
6430 /* It is possible that DuplicateHandle succeeds even
6431 though the socket wasn't really a kernel handle,
6432 because a real handle has the same value. So
6433 test whether the new handle really is a socket. */
6434 long nonblocking
= 0;
6435 if (pfn_ioctlsocket ((SOCKET
) new_s
, FIONBIO
, &nonblocking
) == 0)
6437 pfn_closesocket (s
);
6442 CloseHandle (new_s
);
6447 eassert (fd
< MAXDESC
);
6448 fd_info
[fd
].hnd
= (HANDLE
) s
;
6450 /* set our own internal flags */
6451 fd_info
[fd
].flags
= FILE_SOCKET
| FILE_BINARY
| FILE_READ
| FILE_WRITE
;
6457 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
6459 /* attach child_process to fd_info */
6460 if (fd_info
[ fd
].cp
!= NULL
)
6462 DebPrint (("sys_socket: fd_info[%d] apparently in use!\n", fd
));
6466 fd_info
[ fd
].cp
= cp
;
6469 winsock_inuse
++; /* count open sockets */
6477 pfn_closesocket (s
);
6483 sys_bind (int s
, const struct sockaddr
* addr
, int namelen
)
6485 if (winsock_lib
== NULL
)
6488 return SOCKET_ERROR
;
6492 if (fd_info
[s
].flags
& FILE_SOCKET
)
6494 int rc
= pfn_bind (SOCK_HANDLE (s
), addr
, namelen
);
6495 if (rc
== SOCKET_ERROR
)
6500 return SOCKET_ERROR
;
6504 sys_connect (int s
, const struct sockaddr
* name
, int namelen
)
6506 if (winsock_lib
== NULL
)
6509 return SOCKET_ERROR
;
6513 if (fd_info
[s
].flags
& FILE_SOCKET
)
6515 int rc
= pfn_connect (SOCK_HANDLE (s
), name
, namelen
);
6516 if (rc
== SOCKET_ERROR
)
6521 return SOCKET_ERROR
;
6525 sys_htons (u_short hostshort
)
6527 return (winsock_lib
!= NULL
) ?
6528 pfn_htons (hostshort
) : hostshort
;
6532 sys_ntohs (u_short netshort
)
6534 return (winsock_lib
!= NULL
) ?
6535 pfn_ntohs (netshort
) : netshort
;
6539 sys_inet_addr (const char * cp
)
6541 return (winsock_lib
!= NULL
) ?
6542 pfn_inet_addr (cp
) : INADDR_NONE
;
6546 sys_gethostname (char * name
, int namelen
)
6548 if (winsock_lib
!= NULL
)
6553 retval
= pfn_gethostname (name
, namelen
);
6554 if (retval
== SOCKET_ERROR
)
6559 if (namelen
> MAX_COMPUTERNAME_LENGTH
)
6560 return !GetComputerName (name
, (DWORD
*)&namelen
);
6563 return SOCKET_ERROR
;
6567 sys_gethostbyname (const char * name
)
6569 struct hostent
* host
;
6570 int h_err
= h_errno
;
6572 if (winsock_lib
== NULL
)
6574 h_errno
= NO_RECOVERY
;
6580 host
= pfn_gethostbyname (name
);
6592 sys_getservbyname (const char * name
, const char * proto
)
6594 struct servent
* serv
;
6596 if (winsock_lib
== NULL
)
6603 serv
= pfn_getservbyname (name
, proto
);
6610 sys_getpeername (int s
, struct sockaddr
*addr
, int * namelen
)
6612 if (winsock_lib
== NULL
)
6615 return SOCKET_ERROR
;
6619 if (fd_info
[s
].flags
& FILE_SOCKET
)
6621 int rc
= pfn_getpeername (SOCK_HANDLE (s
), addr
, namelen
);
6622 if (rc
== SOCKET_ERROR
)
6627 return SOCKET_ERROR
;
6631 sys_shutdown (int s
, int how
)
6633 if (winsock_lib
== NULL
)
6636 return SOCKET_ERROR
;
6640 if (fd_info
[s
].flags
& FILE_SOCKET
)
6642 int rc
= pfn_shutdown (SOCK_HANDLE (s
), how
);
6643 if (rc
== SOCKET_ERROR
)
6648 return SOCKET_ERROR
;
6652 sys_setsockopt (int s
, int level
, int optname
, const void * optval
, int optlen
)
6654 if (winsock_lib
== NULL
)
6657 return SOCKET_ERROR
;
6661 if (fd_info
[s
].flags
& FILE_SOCKET
)
6663 int rc
= pfn_setsockopt (SOCK_HANDLE (s
), level
, optname
,
6664 (const char *)optval
, optlen
);
6665 if (rc
== SOCKET_ERROR
)
6670 return SOCKET_ERROR
;
6674 sys_listen (int s
, int backlog
)
6676 if (winsock_lib
== NULL
)
6679 return SOCKET_ERROR
;
6683 if (fd_info
[s
].flags
& FILE_SOCKET
)
6685 int rc
= pfn_listen (SOCK_HANDLE (s
), backlog
);
6686 if (rc
== SOCKET_ERROR
)
6689 fd_info
[s
].flags
|= FILE_LISTEN
;
6693 return SOCKET_ERROR
;
6697 sys_getsockname (int s
, struct sockaddr
* name
, int * namelen
)
6699 if (winsock_lib
== NULL
)
6702 return SOCKET_ERROR
;
6706 if (fd_info
[s
].flags
& FILE_SOCKET
)
6708 int rc
= pfn_getsockname (SOCK_HANDLE (s
), name
, namelen
);
6709 if (rc
== SOCKET_ERROR
)
6714 return SOCKET_ERROR
;
6718 sys_accept (int s
, struct sockaddr
* addr
, int * addrlen
)
6720 if (winsock_lib
== NULL
)
6727 if (fd_info
[s
].flags
& FILE_LISTEN
)
6729 SOCKET t
= pfn_accept (SOCK_HANDLE (s
), addr
, addrlen
);
6731 if (t
== INVALID_SOCKET
)
6734 fd
= socket_to_fd (t
);
6738 fd_info
[s
].cp
->status
= STATUS_READ_ACKNOWLEDGED
;
6739 ResetEvent (fd_info
[s
].cp
->char_avail
);
6748 sys_recvfrom (int s
, char * buf
, int len
, int flags
,
6749 struct sockaddr
* from
, int * fromlen
)
6751 if (winsock_lib
== NULL
)
6754 return SOCKET_ERROR
;
6758 if (fd_info
[s
].flags
& FILE_SOCKET
)
6760 int rc
= pfn_recvfrom (SOCK_HANDLE (s
), buf
, len
, flags
, from
, fromlen
);
6761 if (rc
== SOCKET_ERROR
)
6766 return SOCKET_ERROR
;
6770 sys_sendto (int s
, const char * buf
, int len
, int flags
,
6771 const struct sockaddr
* to
, int tolen
)
6773 if (winsock_lib
== NULL
)
6776 return SOCKET_ERROR
;
6780 if (fd_info
[s
].flags
& FILE_SOCKET
)
6782 int rc
= pfn_sendto (SOCK_HANDLE (s
), buf
, len
, flags
, to
, tolen
);
6783 if (rc
== SOCKET_ERROR
)
6788 return SOCKET_ERROR
;
6791 /* Windows does not have an fcntl function. Provide an implementation
6792 good enough for Emacs. */
6794 fcntl (int s
, int cmd
, int options
)
6796 /* In the w32 Emacs port, fcntl (fd, F_DUPFD_CLOEXEC, fd1) is always
6797 invoked in a context where fd1 is closed and all descriptors less
6798 than fd1 are open, so sys_dup is an adequate implementation. */
6799 if (cmd
== F_DUPFD_CLOEXEC
)
6802 if (winsock_lib
== NULL
)
6809 if (fd_info
[s
].flags
& FILE_SOCKET
)
6811 if (cmd
== F_SETFL
&& options
== O_NONBLOCK
)
6813 unsigned long nblock
= 1;
6814 int rc
= pfn_ioctlsocket (SOCK_HANDLE (s
), FIONBIO
, &nblock
);
6815 if (rc
== SOCKET_ERROR
)
6817 /* Keep track of the fact that we set this to non-blocking. */
6818 fd_info
[s
].flags
|= FILE_NDELAY
;
6824 return SOCKET_ERROR
;
6828 return SOCKET_ERROR
;
6832 /* Shadow main io functions: we need to handle pipes and sockets more
6833 intelligently, and implement non-blocking mode as well. */
6846 if (fd
< MAXDESC
&& fd_info
[fd
].cp
)
6848 child_process
* cp
= fd_info
[fd
].cp
;
6850 fd_info
[fd
].cp
= NULL
;
6852 if (CHILD_ACTIVE (cp
))
6854 /* if last descriptor to active child_process then cleanup */
6856 for (i
= 0; i
< MAXDESC
; i
++)
6860 if (fd_info
[i
].cp
== cp
)
6865 if (fd_info
[fd
].flags
& FILE_SOCKET
)
6867 if (winsock_lib
== NULL
) emacs_abort ();
6869 pfn_shutdown (SOCK_HANDLE (fd
), 2);
6870 rc
= pfn_closesocket (SOCK_HANDLE (fd
));
6872 winsock_inuse
--; /* count open sockets */
6874 /* If the process handle is NULL, it's either a socket
6875 or serial connection, or a subprocess that was
6876 already reaped by reap_subprocess, but whose
6877 resources were not yet freed, because its output was
6878 not fully read yet by the time it was reaped. (This
6879 usually happens with async subprocesses whose output
6880 is being read by Emacs.) Otherwise, this process was
6881 not reaped yet, so we set its FD to a negative value
6882 to make sure sys_select will eventually get to
6883 calling the SIGCHLD handler for it, which will then
6884 invoke waitpid and reap_subprocess. */
6885 if (cp
->procinfo
.hProcess
== NULL
)
6893 if (fd
>= 0 && fd
< MAXDESC
)
6894 fd_info
[fd
].flags
= 0;
6896 /* Note that sockets do not need special treatment here (at least on
6897 NT and Windows 95 using the standard tcp/ip stacks) - it appears that
6898 closesocket is equivalent to CloseHandle, which is to be expected
6899 because socket handles are fully fledged kernel handles. */
6911 if (new_fd
>= 0 && new_fd
< MAXDESC
)
6913 /* duplicate our internal info as well */
6914 fd_info
[new_fd
] = fd_info
[fd
];
6920 sys_dup2 (int src
, int dst
)
6924 if (dst
< 0 || dst
>= MAXDESC
)
6930 /* make sure we close the destination first if it's a pipe or socket */
6931 if (src
!= dst
&& fd_info
[dst
].flags
!= 0)
6934 rc
= _dup2 (src
, dst
);
6937 /* duplicate our internal info as well */
6938 fd_info
[dst
] = fd_info
[src
];
6944 pipe2 (int * phandles
, int pipe2_flags
)
6949 eassert (pipe2_flags
== O_CLOEXEC
);
6951 /* make pipe handles non-inheritable; when we spawn a child, we
6952 replace the relevant handle with an inheritable one. Also put
6953 pipes into binary mode; we will do text mode translation ourselves
6955 rc
= _pipe (phandles
, 0, _O_NOINHERIT
| _O_BINARY
);
6959 /* Protect against overflow, since Windows can open more handles than
6960 our fd_info array has room for. */
6961 if (phandles
[0] >= MAXDESC
|| phandles
[1] >= MAXDESC
)
6963 _close (phandles
[0]);
6964 _close (phandles
[1]);
6970 flags
= FILE_PIPE
| FILE_READ
| FILE_BINARY
;
6971 fd_info
[phandles
[0]].flags
= flags
;
6973 flags
= FILE_PIPE
| FILE_WRITE
| FILE_BINARY
;
6974 fd_info
[phandles
[1]].flags
= flags
;
6981 /* Function to do blocking read of one byte, needed to implement
6982 select. It is only allowed on communication ports, sockets, or
6985 _sys_read_ahead (int fd
)
6990 if (fd
< 0 || fd
>= MAXDESC
)
6991 return STATUS_READ_ERROR
;
6993 cp
= fd_info
[fd
].cp
;
6995 if (cp
== NULL
|| cp
->fd
!= fd
|| cp
->status
!= STATUS_READ_READY
)
6996 return STATUS_READ_ERROR
;
6998 if ((fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SERIAL
| FILE_SOCKET
)) == 0
6999 || (fd_info
[fd
].flags
& FILE_READ
) == 0)
7001 DebPrint (("_sys_read_ahead: internal error: fd %d is not a pipe, serial port, or socket!\n", fd
));
7005 cp
->status
= STATUS_READ_IN_PROGRESS
;
7007 if (fd_info
[fd
].flags
& FILE_PIPE
)
7009 rc
= _read (fd
, &cp
->chr
, sizeof (char));
7011 /* Give subprocess time to buffer some more output for us before
7012 reporting that input is available; we need this because Windows 95
7013 connects DOS programs to pipes by making the pipe appear to be
7014 the normal console stdout - as a result most DOS programs will
7015 write to stdout without buffering, ie. one character at a
7016 time. Even some W32 programs do this - "dir" in a command
7017 shell on NT is very slow if we don't do this. */
7020 int wait
= w32_pipe_read_delay
;
7026 /* Yield remainder of our time slice, effectively giving a
7027 temporary priority boost to the child process. */
7031 else if (fd_info
[fd
].flags
& FILE_SERIAL
)
7033 HANDLE hnd
= fd_info
[fd
].hnd
;
7034 OVERLAPPED
*ovl
= &fd_info
[fd
].cp
->ovl_read
;
7037 /* Configure timeouts for blocking read. */
7038 if (!GetCommTimeouts (hnd
, &ct
))
7040 cp
->status
= STATUS_READ_ERROR
;
7041 return STATUS_READ_ERROR
;
7043 ct
.ReadIntervalTimeout
= 0;
7044 ct
.ReadTotalTimeoutMultiplier
= 0;
7045 ct
.ReadTotalTimeoutConstant
= 0;
7046 if (!SetCommTimeouts (hnd
, &ct
))
7048 cp
->status
= STATUS_READ_ERROR
;
7049 return STATUS_READ_ERROR
;
7052 if (!ReadFile (hnd
, &cp
->chr
, sizeof (char), (DWORD
*) &rc
, ovl
))
7054 if (GetLastError () != ERROR_IO_PENDING
)
7056 cp
->status
= STATUS_READ_ERROR
;
7057 return STATUS_READ_ERROR
;
7059 if (!GetOverlappedResult (hnd
, ovl
, (DWORD
*) &rc
, TRUE
))
7061 cp
->status
= STATUS_READ_ERROR
;
7062 return STATUS_READ_ERROR
;
7066 else if (fd_info
[fd
].flags
& FILE_SOCKET
)
7068 unsigned long nblock
= 0;
7069 /* We always want this to block, so temporarily disable NDELAY. */
7070 if (fd_info
[fd
].flags
& FILE_NDELAY
)
7071 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
7073 rc
= pfn_recv (SOCK_HANDLE (fd
), &cp
->chr
, sizeof (char), 0);
7075 if (fd_info
[fd
].flags
& FILE_NDELAY
)
7078 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
7082 if (rc
== sizeof (char))
7083 cp
->status
= STATUS_READ_SUCCEEDED
;
7085 cp
->status
= STATUS_READ_FAILED
;
7091 _sys_wait_accept (int fd
)
7097 if (fd
< 0 || fd
>= MAXDESC
)
7098 return STATUS_READ_ERROR
;
7100 cp
= fd_info
[fd
].cp
;
7102 if (cp
== NULL
|| cp
->fd
!= fd
|| cp
->status
!= STATUS_READ_READY
)
7103 return STATUS_READ_ERROR
;
7105 cp
->status
= STATUS_READ_FAILED
;
7107 hEv
= pfn_WSACreateEvent ();
7108 rc
= pfn_WSAEventSelect (SOCK_HANDLE (fd
), hEv
, FD_ACCEPT
);
7109 if (rc
!= SOCKET_ERROR
)
7112 rc
= WaitForSingleObject (hEv
, 500);
7114 } while (rc
== WAIT_TIMEOUT
7115 && cp
->status
!= STATUS_READ_ERROR
7117 pfn_WSAEventSelect (SOCK_HANDLE (fd
), NULL
, 0);
7118 if (rc
== WAIT_OBJECT_0
)
7119 cp
->status
= STATUS_READ_SUCCEEDED
;
7121 pfn_WSACloseEvent (hEv
);
7127 sys_read (int fd
, char * buffer
, unsigned int count
)
7132 char * orig_buffer
= buffer
;
7140 if (fd
< MAXDESC
&& fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
| FILE_SERIAL
))
7142 child_process
*cp
= fd_info
[fd
].cp
;
7144 if ((fd_info
[fd
].flags
& FILE_READ
) == 0)
7152 /* re-read CR carried over from last read */
7153 if (fd_info
[fd
].flags
& FILE_LAST_CR
)
7155 if (fd_info
[fd
].flags
& FILE_BINARY
) emacs_abort ();
7159 fd_info
[fd
].flags
&= ~FILE_LAST_CR
;
7162 /* presence of a child_process structure means we are operating in
7163 non-blocking mode - otherwise we just call _read directly.
7164 Note that the child_process structure might be missing because
7165 reap_subprocess has been called; in this case the pipe is
7166 already broken, so calling _read on it is okay. */
7169 int current_status
= cp
->status
;
7171 switch (current_status
)
7173 case STATUS_READ_FAILED
:
7174 case STATUS_READ_ERROR
:
7175 /* report normal EOF if nothing in buffer */
7177 fd_info
[fd
].flags
|= FILE_AT_EOF
;
7180 case STATUS_READ_READY
:
7181 case STATUS_READ_IN_PROGRESS
:
7182 DebPrint (("sys_read called when read is in progress\n"));
7183 errno
= EWOULDBLOCK
;
7186 case STATUS_READ_SUCCEEDED
:
7187 /* consume read-ahead char */
7188 *buffer
++ = cp
->chr
;
7191 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
7192 ResetEvent (cp
->char_avail
);
7194 case STATUS_READ_ACKNOWLEDGED
:
7198 DebPrint (("sys_read: bad status %d\n", current_status
));
7203 if (fd_info
[fd
].flags
& FILE_PIPE
)
7205 PeekNamedPipe ((HANDLE
) _get_osfhandle (fd
), NULL
, 0, NULL
, &waiting
, NULL
);
7206 to_read
= min (waiting
, (DWORD
) count
);
7209 nchars
+= _read (fd
, buffer
, to_read
);
7211 else if (fd_info
[fd
].flags
& FILE_SERIAL
)
7213 HANDLE hnd
= fd_info
[fd
].hnd
;
7214 OVERLAPPED
*ovl
= &fd_info
[fd
].cp
->ovl_read
;
7220 /* Configure timeouts for non-blocking read. */
7221 if (!GetCommTimeouts (hnd
, &ct
))
7226 ct
.ReadIntervalTimeout
= MAXDWORD
;
7227 ct
.ReadTotalTimeoutMultiplier
= 0;
7228 ct
.ReadTotalTimeoutConstant
= 0;
7229 if (!SetCommTimeouts (hnd
, &ct
))
7235 if (!ResetEvent (ovl
->hEvent
))
7240 if (!ReadFile (hnd
, buffer
, count
, (DWORD
*) &rc
, ovl
))
7242 if (GetLastError () != ERROR_IO_PENDING
)
7247 if (!GetOverlappedResult (hnd
, ovl
, (DWORD
*) &rc
, TRUE
))
7256 else /* FILE_SOCKET */
7258 if (winsock_lib
== NULL
) emacs_abort ();
7260 /* do the equivalent of a non-blocking read */
7261 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONREAD
, &waiting
);
7262 if (waiting
== 0 && nchars
== 0)
7264 errno
= EWOULDBLOCK
;
7270 /* always use binary mode for sockets */
7271 int res
= pfn_recv (SOCK_HANDLE (fd
), buffer
, count
, 0);
7272 if (res
== SOCKET_ERROR
)
7274 DebPrint (("sys_read.recv failed with error %d on socket %ld\n",
7275 pfn_WSAGetLastError (), SOCK_HANDLE (fd
)));
7285 int nread
= _read (fd
, buffer
, count
);
7288 else if (nchars
== 0)
7293 fd_info
[fd
].flags
|= FILE_AT_EOF
;
7294 /* Perform text mode translation if required. */
7295 else if ((fd_info
[fd
].flags
& FILE_BINARY
) == 0)
7297 nchars
= crlf_to_lf (nchars
, orig_buffer
);
7298 /* If buffer contains only CR, return that. To be absolutely
7299 sure we should attempt to read the next char, but in
7300 practice a CR to be followed by LF would not appear by
7301 itself in the buffer. */
7302 if (nchars
> 1 && orig_buffer
[nchars
- 1] == 0x0d)
7304 fd_info
[fd
].flags
|= FILE_LAST_CR
;
7310 nchars
= _read (fd
, buffer
, count
);
7315 /* From w32xfns.c */
7316 extern HANDLE interrupt_handle
;
7318 /* For now, don't bother with a non-blocking mode */
7320 sys_write (int fd
, const void * buffer
, unsigned int count
)
7330 if (fd
< MAXDESC
&& fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
| FILE_SERIAL
))
7332 if ((fd_info
[fd
].flags
& FILE_WRITE
) == 0)
7338 /* Perform text mode translation if required. */
7339 if ((fd_info
[fd
].flags
& FILE_BINARY
) == 0)
7341 char * tmpbuf
= alloca (count
* 2);
7342 unsigned char * src
= (void *)buffer
;
7343 unsigned char * dst
= tmpbuf
;
7348 unsigned char *next
;
7349 /* copy next line or remaining bytes */
7350 next
= _memccpy (dst
, src
, '\n', nbytes
);
7353 /* copied one line ending with '\n' */
7354 int copied
= next
- dst
;
7357 /* insert '\r' before '\n' */
7364 /* copied remaining partial line -> now finished */
7371 if (fd
< MAXDESC
&& fd_info
[fd
].flags
& FILE_SERIAL
)
7373 HANDLE hnd
= (HANDLE
) _get_osfhandle (fd
);
7374 OVERLAPPED
*ovl
= &fd_info
[fd
].cp
->ovl_write
;
7375 HANDLE wait_hnd
[2] = { interrupt_handle
, ovl
->hEvent
};
7378 if (!WriteFile (hnd
, buffer
, count
, (DWORD
*) &nchars
, ovl
))
7380 if (GetLastError () != ERROR_IO_PENDING
)
7385 if (detect_input_pending ())
7386 active
= MsgWaitForMultipleObjects (2, wait_hnd
, FALSE
, INFINITE
,
7389 active
= WaitForMultipleObjects (2, wait_hnd
, FALSE
, INFINITE
);
7390 if (active
== WAIT_OBJECT_0
)
7391 { /* User pressed C-g, cancel write, then leave. Don't bother
7392 cleaning up as we may only get stuck in buggy drivers. */
7393 PurgeComm (hnd
, PURGE_TXABORT
| PURGE_TXCLEAR
);
7398 if (active
== WAIT_OBJECT_0
+ 1
7399 && !GetOverlappedResult (hnd
, ovl
, (DWORD
*) &nchars
, TRUE
))
7406 else if (fd
< MAXDESC
&& fd_info
[fd
].flags
& FILE_SOCKET
)
7408 unsigned long nblock
= 0;
7409 if (winsock_lib
== NULL
) emacs_abort ();
7411 /* TODO: implement select() properly so non-blocking I/O works. */
7412 /* For now, make sure the write blocks. */
7413 if (fd_info
[fd
].flags
& FILE_NDELAY
)
7414 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
7416 nchars
= pfn_send (SOCK_HANDLE (fd
), buffer
, count
, 0);
7418 /* Set the socket back to non-blocking if it was before,
7419 for other operations that support it. */
7420 if (fd_info
[fd
].flags
& FILE_NDELAY
)
7423 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
7426 if (nchars
== SOCKET_ERROR
)
7428 DebPrint (("sys_write.send failed with error %d on socket %ld\n",
7429 pfn_WSAGetLastError (), SOCK_HANDLE (fd
)));
7435 /* Some networked filesystems don't like too large writes, so
7436 break them into smaller chunks. See the Comments section of
7437 the MSDN documentation of WriteFile for details behind the
7438 choice of the value of CHUNK below. See also the thread
7439 http://thread.gmane.org/gmane.comp.version-control.git/145294
7440 in the git mailing list. */
7441 const unsigned char *p
= buffer
;
7442 const unsigned chunk
= 30 * 1024 * 1024;
7447 unsigned this_chunk
= count
< chunk
? count
: chunk
;
7448 int n
= _write (fd
, p
, this_chunk
);
7456 else if (n
< this_chunk
)
7467 /* Emulation of SIOCGIFCONF and getifaddrs, see process.c. */
7469 extern Lisp_Object
conv_sockaddr_to_lisp (struct sockaddr
*, int);
7471 /* Return information about network interface IFNAME, or about all
7472 interfaces (if IFNAME is nil). */
7474 network_interface_get_info (Lisp_Object ifname
)
7476 ULONG ainfo_len
= sizeof (IP_ADAPTER_INFO
);
7477 IP_ADAPTER_INFO
*adapter
, *ainfo
= xmalloc (ainfo_len
);
7478 DWORD retval
= get_adapters_info (ainfo
, &ainfo_len
);
7479 Lisp_Object res
= Qnil
;
7481 if (retval
== ERROR_BUFFER_OVERFLOW
)
7483 ainfo
= xrealloc (ainfo
, ainfo_len
);
7484 retval
= get_adapters_info (ainfo
, &ainfo_len
);
7487 if (retval
== ERROR_SUCCESS
)
7489 int eth_count
= 0, tr_count
= 0, fddi_count
= 0, ppp_count
= 0;
7490 int sl_count
= 0, wlan_count
= 0, lo_count
= 0, ifx_count
= 0;
7492 struct sockaddr_in sa
;
7494 /* For the below, we need some winsock functions, so make sure
7495 the winsock DLL is loaded. If we cannot successfully load
7496 it, they will have no use of the information we provide,
7498 if (!winsock_lib
&& !init_winsock (1))
7501 for (adapter
= ainfo
; adapter
; adapter
= adapter
->Next
)
7503 char namebuf
[MAX_ADAPTER_NAME_LENGTH
+ 4];
7505 /* Present Unix-compatible interface names, instead of the
7506 Windows names, which are really GUIDs not readable by
7508 static const char *ifmt
[] = {
7509 "eth%d", "tr%d", "fddi%d", "ppp%d", "sl%d", "wlan%d",
7524 switch (adapter
->Type
)
7526 case MIB_IF_TYPE_ETHERNET
:
7527 /* Windows before Vista reports wireless adapters as
7528 Ethernet. Work around by looking at the Description
7530 if (strstr (adapter
->Description
, "Wireless "))
7533 if_num
= wlan_count
++;
7537 ifmt_idx
= ETHERNET
;
7538 if_num
= eth_count
++;
7541 case MIB_IF_TYPE_TOKENRING
:
7542 ifmt_idx
= TOKENRING
;
7543 if_num
= tr_count
++;
7545 case MIB_IF_TYPE_FDDI
:
7547 if_num
= fddi_count
++;
7549 case MIB_IF_TYPE_PPP
:
7551 if_num
= ppp_count
++;
7553 case MIB_IF_TYPE_SLIP
:
7555 if_num
= sl_count
++;
7557 case IF_TYPE_IEEE80211
:
7559 if_num
= wlan_count
++;
7561 case MIB_IF_TYPE_LOOPBACK
:
7564 ifmt_idx
= LOOPBACK
;
7565 if_num
= lo_count
++;
7571 ifmt_idx
= OTHER_IF
;
7572 if_num
= ifx_count
++;
7575 if (ifmt_idx
== NONE
)
7577 sprintf (namebuf
, ifmt
[ifmt_idx
], if_num
);
7579 sa
.sin_family
= AF_INET
;
7580 ip_addr
= sys_inet_addr (adapter
->IpAddressList
.IpAddress
.String
);
7581 if (ip_addr
== INADDR_NONE
)
7583 /* Bogus address, skip this interface. */
7586 sa
.sin_addr
.s_addr
= ip_addr
;
7589 res
= Fcons (Fcons (build_string (namebuf
),
7590 conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
7591 sizeof (struct sockaddr
))),
7593 else if (strcmp (namebuf
, SSDATA (ifname
)) == 0)
7595 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
7596 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
7597 Lisp_Object flags
= Qnil
;
7601 /* Flags. We guess most of them by type, since the
7602 Windows flags are different and hard to get by. */
7603 flags
= Fcons (intern ("up"), flags
);
7604 if (ifmt_idx
== ETHERNET
|| ifmt_idx
== WLAN
)
7606 flags
= Fcons (intern ("broadcast"), flags
);
7607 flags
= Fcons (intern ("multicast"), flags
);
7609 flags
= Fcons (intern ("running"), flags
);
7610 if (ifmt_idx
== PPP
)
7612 flags
= Fcons (intern ("pointopoint"), flags
);
7613 flags
= Fcons (intern ("noarp"), flags
);
7615 if (adapter
->HaveWins
)
7616 flags
= Fcons (intern ("WINS"), flags
);
7617 if (adapter
->DhcpEnabled
)
7618 flags
= Fcons (intern ("dynamic"), flags
);
7620 res
= Fcons (flags
, res
);
7622 /* Hardware address and its family. */
7623 for (n
= 0; n
< adapter
->AddressLength
; n
++)
7624 p
->contents
[n
] = make_number ((int) adapter
->Address
[n
]);
7625 /* Windows does not support AF_LINK or AF_PACKET family
7626 of addresses. Use an arbitrary family number that is
7627 identical to what GNU/Linux returns. */
7628 res
= Fcons (Fcons (make_number (1), hwaddr
), res
);
7631 sa
.sin_family
= AF_INET
;
7632 net_mask
= sys_inet_addr (adapter
->IpAddressList
.IpMask
.String
);
7633 if (net_mask
!= INADDR_NONE
)
7635 sa
.sin_addr
.s_addr
= net_mask
;
7637 res
= Fcons (conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
7638 sizeof (struct sockaddr
)),
7642 res
= Fcons (Qnil
, res
);
7644 sa
.sin_family
= AF_INET
;
7645 if (ip_addr
!= INADDR_NONE
)
7647 /* Broadcast address is only reported by
7648 GetAdaptersAddresses, which is of limited
7649 availability. Generate it on our own. */
7650 u_long bcast_addr
= (ip_addr
& net_mask
) | ~net_mask
;
7652 sa
.sin_addr
.s_addr
= bcast_addr
;
7654 res
= Fcons (conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
7655 sizeof (struct sockaddr
)),
7659 sa
.sin_addr
.s_addr
= ip_addr
;
7661 res
= Fcons (conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
7662 sizeof (struct sockaddr
)),
7666 res
= Fcons (Qnil
, Fcons (Qnil
, res
));
7669 /* GetAdaptersInfo is documented to not report loopback
7670 interfaces, so we generate one out of thin air. */
7673 sa
.sin_family
= AF_INET
;
7677 sa
.sin_addr
.s_addr
= sys_inet_addr ("127.0.0.1");
7678 res
= Fcons (Fcons (build_string ("lo"),
7679 conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
7680 sizeof (struct sockaddr
))),
7683 else if (strcmp (SSDATA (ifname
), "lo") == 0)
7685 res
= Fcons (Fcons (intern ("running"),
7686 Fcons (intern ("loopback"),
7687 Fcons (intern ("up"), Qnil
))), Qnil
);
7688 /* 772 is what 3 different GNU/Linux systems report for
7689 the loopback interface. */
7690 res
= Fcons (Fcons (make_number (772),
7691 Fmake_vector (make_number (6),
7694 sa
.sin_addr
.s_addr
= sys_inet_addr ("255.0.0.0");
7695 res
= Fcons (conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
7696 sizeof (struct sockaddr
)),
7698 sa
.sin_addr
.s_addr
= sys_inet_addr ("0.0.0.0");
7699 res
= Fcons (conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
7700 sizeof (struct sockaddr
)),
7702 sa
.sin_addr
.s_addr
= sys_inet_addr ("127.0.0.1");
7703 res
= Fcons (conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
7704 sizeof (struct sockaddr
)),
7717 network_interface_list (void)
7719 return network_interface_get_info (Qnil
);
7723 network_interface_info (Lisp_Object ifname
)
7725 return network_interface_get_info (ifname
);
7729 /* The Windows CRT functions are "optimized for speed", so they don't
7730 check for timezone and DST changes if they were last called less
7731 than 1 minute ago (see http://support.microsoft.com/kb/821231). So
7732 all Emacs features that repeatedly call time functions (e.g.,
7733 display-time) are in real danger of missing timezone and DST
7734 changes. Calling tzset before each localtime call fixes that. */
7736 sys_localtime (const time_t *t
)
7739 return localtime (t
);
7744 /* Try loading LIBRARY_ID from the file(s) specified in
7745 Vdynamic_library_alist. If the library is loaded successfully,
7746 return the handle of the DLL, and record the filename in the
7747 property :loaded-from of LIBRARY_ID. If the library could not be
7748 found, or when it was already loaded (because the handle is not
7749 recorded anywhere, and so is lost after use), return NULL.
7751 We could also save the handle in :loaded-from, but currently
7752 there's no use case for it. */
7754 w32_delayed_load (Lisp_Object library_id
)
7756 HMODULE library_dll
= NULL
;
7758 CHECK_SYMBOL (library_id
);
7760 if (CONSP (Vdynamic_library_alist
)
7761 && NILP (Fassq (library_id
, Vlibrary_cache
)))
7763 Lisp_Object found
= Qnil
;
7764 Lisp_Object dlls
= Fassq (library_id
, Vdynamic_library_alist
);
7767 for (dlls
= XCDR (dlls
); CONSP (dlls
); dlls
= XCDR (dlls
))
7769 CHECK_STRING_CAR (dlls
);
7770 if ((library_dll
= LoadLibrary (SDATA (XCAR (dlls
)))))
7772 char name
[MAX_PATH
];
7775 len
= GetModuleFileNameA (library_dll
, name
, sizeof (name
));
7776 found
= Fcons (XCAR (dlls
),
7778 /* Possibly truncated */
7779 ? make_specified_string (name
, -1, len
, 1)
7785 Fput (library_id
, QCloaded_from
, found
);
7793 check_windows_init_file (void)
7795 /* A common indication that Emacs is not installed properly is when
7796 it cannot find the Windows installation file. If this file does
7797 not exist in the expected place, tell the user. */
7799 if (!noninteractive
&& !inhibit_window_system
7800 /* Vload_path is not yet initialized when we are loading
7802 && NILP (Vpurify_flag
))
7804 Lisp_Object init_file
;
7807 init_file
= build_string ("term/w32-win");
7808 fd
= openp (Vload_path
, init_file
, Fget_load_suffixes (), NULL
, Qnil
);
7811 Lisp_Object load_path_print
= Fprin1_to_string (Vload_path
, Qnil
);
7812 char *init_file_name
= SDATA (init_file
);
7813 char *load_path
= SDATA (load_path_print
);
7814 char *buffer
= alloca (1024
7815 + strlen (init_file_name
)
7816 + strlen (load_path
));
7819 "The Emacs Windows initialization file \"%s.el\" "
7820 "could not be found in your Emacs installation. "
7821 "Emacs checked the following directories for this file:\n"
7823 "When Emacs cannot find this file, it usually means that it "
7824 "was not installed properly, or its distribution file was "
7825 "not unpacked properly.\nSee the README.W32 file in the "
7826 "top-level Emacs directory for more information.",
7827 init_file_name
, load_path
);
7830 "Emacs Abort Dialog",
7831 MB_OK
| MB_ICONEXCLAMATION
| MB_TASKMODAL
);
7832 /* Use the low-level system abort. */
7843 term_ntproc (int ignored
)
7849 /* shutdown the socket interface if necessary */
7856 init_ntproc (int dumping
)
7858 sigset_t initial_mask
= 0;
7860 /* Initialize the socket interface now if available and requested by
7861 the user by defining PRELOAD_WINSOCK; otherwise loading will be
7862 delayed until open-network-stream is called (w32-has-winsock can
7863 also be used to dynamically load or reload winsock).
7865 Conveniently, init_environment is called before us, so
7866 PRELOAD_WINSOCK can be set in the registry. */
7868 /* Always initialize this correctly. */
7871 if (getenv ("PRELOAD_WINSOCK") != NULL
)
7872 init_winsock (TRUE
);
7874 /* Initial preparation for subprocess support: replace our standard
7875 handles with non-inheritable versions. */
7878 HANDLE stdin_save
= INVALID_HANDLE_VALUE
;
7879 HANDLE stdout_save
= INVALID_HANDLE_VALUE
;
7880 HANDLE stderr_save
= INVALID_HANDLE_VALUE
;
7882 parent
= GetCurrentProcess ();
7884 /* ignore errors when duplicating and closing; typically the
7885 handles will be invalid when running as a gui program. */
7886 DuplicateHandle (parent
,
7887 GetStdHandle (STD_INPUT_HANDLE
),
7892 DUPLICATE_SAME_ACCESS
);
7894 DuplicateHandle (parent
,
7895 GetStdHandle (STD_OUTPUT_HANDLE
),
7900 DUPLICATE_SAME_ACCESS
);
7902 DuplicateHandle (parent
,
7903 GetStdHandle (STD_ERROR_HANDLE
),
7908 DUPLICATE_SAME_ACCESS
);
7914 if (stdin_save
!= INVALID_HANDLE_VALUE
)
7915 _open_osfhandle ((intptr_t) stdin_save
, O_TEXT
);
7917 _open ("nul", O_TEXT
| O_NOINHERIT
| O_RDONLY
);
7920 if (stdout_save
!= INVALID_HANDLE_VALUE
)
7921 _open_osfhandle ((intptr_t) stdout_save
, O_TEXT
);
7923 _open ("nul", O_TEXT
| O_NOINHERIT
| O_WRONLY
);
7926 if (stderr_save
!= INVALID_HANDLE_VALUE
)
7927 _open_osfhandle ((intptr_t) stderr_save
, O_TEXT
);
7929 _open ("nul", O_TEXT
| O_NOINHERIT
| O_WRONLY
);
7933 /* unfortunately, atexit depends on implementation of malloc */
7934 /* atexit (term_ntproc); */
7937 /* Make sure we start with all signals unblocked. */
7938 sigprocmask (SIG_SETMASK
, &initial_mask
, NULL
);
7939 signal (SIGABRT
, term_ntproc
);
7943 /* determine which drives are fixed, for GetCachedVolumeInformation */
7945 /* GetDriveType must have trailing backslash. */
7946 char drive
[] = "A:\\";
7948 /* Loop over all possible drive letters */
7949 while (*drive
<= 'Z')
7951 /* Record if this drive letter refers to a fixed drive. */
7952 fixed_drives
[DRIVE_INDEX (*drive
)] =
7953 (GetDriveType (drive
) == DRIVE_FIXED
);
7958 /* Reset the volume info cache. */
7959 volume_cache
= NULL
;
7964 shutdown_handler ensures that buffers' autosave files are
7965 up to date when the user logs off, or the system shuts down.
7968 shutdown_handler (DWORD type
)
7970 /* Ctrl-C and Ctrl-Break are already suppressed, so don't handle them. */
7971 if (type
== CTRL_CLOSE_EVENT
/* User closes console window. */
7972 || type
== CTRL_LOGOFF_EVENT
/* User logs off. */
7973 || type
== CTRL_SHUTDOWN_EVENT
) /* User shutsdown. */
7975 /* Shut down cleanly, making sure autosave files are up to date. */
7976 shut_down_emacs (0, Qnil
);
7979 /* Allow other handlers to handle this signal. */
7984 globals_of_w32 is used to initialize those global variables that
7985 must always be initialized on startup even when the global variable
7986 initialized is non zero (see the function main in emacs.c).
7989 globals_of_w32 (void)
7991 HMODULE kernel32
= GetModuleHandle ("kernel32.dll");
7993 get_process_times_fn
= (GetProcessTimes_Proc
)
7994 GetProcAddress (kernel32
, "GetProcessTimes");
7996 DEFSYM (QCloaded_from
, ":loaded-from");
7998 g_b_init_is_windows_9x
= 0;
7999 g_b_init_open_process_token
= 0;
8000 g_b_init_get_token_information
= 0;
8001 g_b_init_lookup_account_sid
= 0;
8002 g_b_init_get_sid_sub_authority
= 0;
8003 g_b_init_get_sid_sub_authority_count
= 0;
8004 g_b_init_get_security_info
= 0;
8005 g_b_init_get_file_security
= 0;
8006 g_b_init_get_security_descriptor_owner
= 0;
8007 g_b_init_get_security_descriptor_group
= 0;
8008 g_b_init_is_valid_sid
= 0;
8009 g_b_init_create_toolhelp32_snapshot
= 0;
8010 g_b_init_process32_first
= 0;
8011 g_b_init_process32_next
= 0;
8012 g_b_init_open_thread_token
= 0;
8013 g_b_init_impersonate_self
= 0;
8014 g_b_init_revert_to_self
= 0;
8015 g_b_init_get_process_memory_info
= 0;
8016 g_b_init_get_process_working_set_size
= 0;
8017 g_b_init_global_memory_status
= 0;
8018 g_b_init_global_memory_status_ex
= 0;
8019 g_b_init_equal_sid
= 0;
8020 g_b_init_copy_sid
= 0;
8021 g_b_init_get_length_sid
= 0;
8022 g_b_init_get_native_system_info
= 0;
8023 g_b_init_get_system_times
= 0;
8024 g_b_init_create_symbolic_link
= 0;
8025 g_b_init_get_security_descriptor_dacl
= 0;
8026 g_b_init_convert_sd_to_sddl
= 0;
8027 g_b_init_convert_sddl_to_sd
= 0;
8028 g_b_init_is_valid_security_descriptor
= 0;
8029 g_b_init_set_file_security
= 0;
8030 g_b_init_get_adapters_info
= 0;
8031 num_of_processors
= 0;
8032 /* The following sets a handler for shutdown notifications for
8033 console apps. This actually applies to Emacs in both console and
8034 GUI modes, since we had to fool windows into thinking emacs is a
8035 console application to get console mode to work. */
8036 SetConsoleCtrlHandler (shutdown_handler
, TRUE
);
8038 /* "None" is the default group name on standalone workstations. */
8039 strcpy (dflt_group_name
, "None");
8041 /* Reset, in case it has some value inherited from dump time. */
8042 w32_stat_get_owner_group
= 0;
8045 /* For make-serial-process */
8047 serial_open (Lisp_Object port_obj
)
8049 char *port
= SSDATA (port_obj
);
8054 hnd
= CreateFile (port
, GENERIC_READ
| GENERIC_WRITE
, 0, 0,
8055 OPEN_EXISTING
, FILE_FLAG_OVERLAPPED
, 0);
8056 if (hnd
== INVALID_HANDLE_VALUE
)
8057 error ("Could not open %s", port
);
8058 fd
= (int) _open_osfhandle ((intptr_t) hnd
, 0);
8060 error ("Could not open %s", port
);
8064 error ("Could not create child process");
8066 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
8067 fd_info
[ fd
].hnd
= hnd
;
8068 fd_info
[ fd
].flags
|=
8069 FILE_READ
| FILE_WRITE
| FILE_BINARY
| FILE_SERIAL
;
8070 if (fd_info
[ fd
].cp
!= NULL
)
8072 error ("fd_info[fd = %d] is already in use", fd
);
8074 fd_info
[ fd
].cp
= cp
;
8075 cp
->ovl_read
.hEvent
= CreateEvent (NULL
, TRUE
, FALSE
, NULL
);
8076 if (cp
->ovl_read
.hEvent
== NULL
)
8077 error ("Could not create read event");
8078 cp
->ovl_write
.hEvent
= CreateEvent (NULL
, TRUE
, FALSE
, NULL
);
8079 if (cp
->ovl_write
.hEvent
== NULL
)
8080 error ("Could not create write event");
8085 /* For serial-process-configure */
8087 serial_configure (struct Lisp_Process
*p
, Lisp_Object contact
)
8089 Lisp_Object childp2
= Qnil
;
8090 Lisp_Object tem
= Qnil
;
8094 char summary
[4] = "???"; /* This usually becomes "8N1". */
8096 if ((fd_info
[ p
->outfd
].flags
& FILE_SERIAL
) == 0)
8097 error ("Not a serial process");
8098 hnd
= fd_info
[ p
->outfd
].hnd
;
8100 childp2
= Fcopy_sequence (p
->childp
);
8102 /* Initialize timeouts for blocking read and blocking write. */
8103 if (!GetCommTimeouts (hnd
, &ct
))
8104 error ("GetCommTimeouts() failed");
8105 ct
.ReadIntervalTimeout
= 0;
8106 ct
.ReadTotalTimeoutMultiplier
= 0;
8107 ct
.ReadTotalTimeoutConstant
= 0;
8108 ct
.WriteTotalTimeoutMultiplier
= 0;
8109 ct
.WriteTotalTimeoutConstant
= 0;
8110 if (!SetCommTimeouts (hnd
, &ct
))
8111 error ("SetCommTimeouts() failed");
8112 /* Read port attributes and prepare default configuration. */
8113 memset (&dcb
, 0, sizeof (dcb
));
8114 dcb
.DCBlength
= sizeof (DCB
);
8115 if (!GetCommState (hnd
, &dcb
))
8116 error ("GetCommState() failed");
8119 dcb
.fAbortOnError
= FALSE
;
8120 /* dcb.XonLim and dcb.XoffLim are set by GetCommState() */
8125 /* Configure speed. */
8126 if (!NILP (Fplist_member (contact
, QCspeed
)))
8127 tem
= Fplist_get (contact
, QCspeed
);
8129 tem
= Fplist_get (p
->childp
, QCspeed
);
8131 dcb
.BaudRate
= XINT (tem
);
8132 childp2
= Fplist_put (childp2
, QCspeed
, tem
);
8134 /* Configure bytesize. */
8135 if (!NILP (Fplist_member (contact
, QCbytesize
)))
8136 tem
= Fplist_get (contact
, QCbytesize
);
8138 tem
= Fplist_get (p
->childp
, QCbytesize
);
8140 tem
= make_number (8);
8142 if (XINT (tem
) != 7 && XINT (tem
) != 8)
8143 error (":bytesize must be nil (8), 7, or 8");
8144 dcb
.ByteSize
= XINT (tem
);
8145 summary
[0] = XINT (tem
) + '0';
8146 childp2
= Fplist_put (childp2
, QCbytesize
, tem
);
8148 /* Configure parity. */
8149 if (!NILP (Fplist_member (contact
, QCparity
)))
8150 tem
= Fplist_get (contact
, QCparity
);
8152 tem
= Fplist_get (p
->childp
, QCparity
);
8153 if (!NILP (tem
) && !EQ (tem
, Qeven
) && !EQ (tem
, Qodd
))
8154 error (":parity must be nil (no parity), `even', or `odd'");
8155 dcb
.fParity
= FALSE
;
8156 dcb
.Parity
= NOPARITY
;
8157 dcb
.fErrorChar
= FALSE
;
8162 else if (EQ (tem
, Qeven
))
8166 dcb
.Parity
= EVENPARITY
;
8167 dcb
.fErrorChar
= TRUE
;
8169 else if (EQ (tem
, Qodd
))
8173 dcb
.Parity
= ODDPARITY
;
8174 dcb
.fErrorChar
= TRUE
;
8176 childp2
= Fplist_put (childp2
, QCparity
, tem
);
8178 /* Configure stopbits. */
8179 if (!NILP (Fplist_member (contact
, QCstopbits
)))
8180 tem
= Fplist_get (contact
, QCstopbits
);
8182 tem
= Fplist_get (p
->childp
, QCstopbits
);
8184 tem
= make_number (1);
8186 if (XINT (tem
) != 1 && XINT (tem
) != 2)
8187 error (":stopbits must be nil (1 stopbit), 1, or 2");
8188 summary
[2] = XINT (tem
) + '0';
8189 if (XINT (tem
) == 1)
8190 dcb
.StopBits
= ONESTOPBIT
;
8191 else if (XINT (tem
) == 2)
8192 dcb
.StopBits
= TWOSTOPBITS
;
8193 childp2
= Fplist_put (childp2
, QCstopbits
, tem
);
8195 /* Configure flowcontrol. */
8196 if (!NILP (Fplist_member (contact
, QCflowcontrol
)))
8197 tem
= Fplist_get (contact
, QCflowcontrol
);
8199 tem
= Fplist_get (p
->childp
, QCflowcontrol
);
8200 if (!NILP (tem
) && !EQ (tem
, Qhw
) && !EQ (tem
, Qsw
))
8201 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
8202 dcb
.fOutxCtsFlow
= FALSE
;
8203 dcb
.fOutxDsrFlow
= FALSE
;
8204 dcb
.fDtrControl
= DTR_CONTROL_DISABLE
;
8205 dcb
.fDsrSensitivity
= FALSE
;
8206 dcb
.fTXContinueOnXoff
= FALSE
;
8209 dcb
.fRtsControl
= RTS_CONTROL_DISABLE
;
8210 dcb
.XonChar
= 17; /* Control-Q */
8211 dcb
.XoffChar
= 19; /* Control-S */
8214 /* Already configured. */
8216 else if (EQ (tem
, Qhw
))
8218 dcb
.fRtsControl
= RTS_CONTROL_HANDSHAKE
;
8219 dcb
.fOutxCtsFlow
= TRUE
;
8221 else if (EQ (tem
, Qsw
))
8226 childp2
= Fplist_put (childp2
, QCflowcontrol
, tem
);
8228 /* Activate configuration. */
8229 if (!SetCommState (hnd
, &dcb
))
8230 error ("SetCommState() failed");
8232 childp2
= Fplist_put (childp2
, QCsummary
, build_string (summary
));
8233 pset_childp (p
, childp2
);
8239 emacs_gnutls_pull (gnutls_transport_ptr_t p
, void* buf
, size_t sz
)
8243 struct timespec timeout
;
8244 struct Lisp_Process
*process
= (struct Lisp_Process
*)p
;
8245 int fd
= process
->infd
;
8247 n
= sys_read (fd
, (char*)buf
, sz
);
8254 /* Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
8255 if (err
== EWOULDBLOCK
)
8258 emacs_gnutls_transport_set_errno (process
->gnutls_state
, err
);
8264 emacs_gnutls_push (gnutls_transport_ptr_t p
, const void* buf
, size_t sz
)
8266 struct Lisp_Process
*process
= (struct Lisp_Process
*)p
;
8267 int fd
= process
->outfd
;
8268 ssize_t n
= sys_write (fd
, buf
, sz
);
8270 /* 0 or more bytes written means everything went fine. */
8274 /* Negative bytes written means we got an error in errno.
8275 Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
8276 emacs_gnutls_transport_set_errno (process
->gnutls_state
,
8277 errno
== EWOULDBLOCK
? EAGAIN
: errno
);
8281 #endif /* HAVE_GNUTLS */