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
22 #include <stddef.h> /* for offsetof */
25 #include <float.h> /* for DBL_EPSILON */
33 #include <sys/utime.h>
37 /* must include CRT headers *before* config.h */
40 #include <mbstring.h> /* for _mbspbrk, _mbslwr, _mbsrchr, ... */
73 #define _ANONYMOUS_UNION
74 #define _ANONYMOUS_STRUCT
77 /* Some versions of compiler define MEMORYSTATUSEX, some don't, so we
78 use a different name to avoid compilation problems. */
79 typedef struct _MEMORY_STATUS_EX
{
82 DWORDLONG ullTotalPhys
;
83 DWORDLONG ullAvailPhys
;
84 DWORDLONG ullTotalPageFile
;
85 DWORDLONG ullAvailPageFile
;
86 DWORDLONG ullTotalVirtual
;
87 DWORDLONG ullAvailVirtual
;
88 DWORDLONG ullAvailExtendedVirtual
;
89 } MEMORY_STATUS_EX
,*LPMEMORY_STATUS_EX
;
99 #if !defined (__MINGW32__) || __W32API_MAJOR_VERSION < 3 || (__W32API_MAJOR_VERSION == 3 && __W32API_MINOR_VERSION < 15)
100 /* This either is not in psapi.h or guarded by higher value of
101 _WIN32_WINNT than what we use. w32api supplied with MinGW 3.15
102 defines it in psapi.h */
103 typedef struct _PROCESS_MEMORY_COUNTERS_EX
{
105 DWORD PageFaultCount
;
106 SIZE_T PeakWorkingSetSize
;
107 SIZE_T WorkingSetSize
;
108 SIZE_T QuotaPeakPagedPoolUsage
;
109 SIZE_T QuotaPagedPoolUsage
;
110 SIZE_T QuotaPeakNonPagedPoolUsage
;
111 SIZE_T QuotaNonPagedPoolUsage
;
112 SIZE_T PagefileUsage
;
113 SIZE_T PeakPagefileUsage
;
115 } PROCESS_MEMORY_COUNTERS_EX
,*PPROCESS_MEMORY_COUNTERS_EX
;
118 #include <winioctl.h>
124 /* This is not in MinGW's sddl.h (but they are in MSVC headers), so we
125 define them by hand if not already defined. */
126 #ifndef SDDL_REVISION_1
127 #define SDDL_REVISION_1 1
128 #endif /* SDDL_REVISION_1 */
131 /* MSVC doesn't provide the definition of REPARSE_DATA_BUFFER and the
132 associated macros, except on ntifs.h, which cannot be included
133 because it triggers conflicts with other Windows API headers. So
134 we define it here by hand. */
136 typedef struct _REPARSE_DATA_BUFFER
{
138 USHORT ReparseDataLength
;
142 USHORT SubstituteNameOffset
;
143 USHORT SubstituteNameLength
;
144 USHORT PrintNameOffset
;
145 USHORT PrintNameLength
;
148 } SymbolicLinkReparseBuffer
;
150 USHORT SubstituteNameOffset
;
151 USHORT SubstituteNameLength
;
152 USHORT PrintNameOffset
;
153 USHORT PrintNameLength
;
155 } MountPointReparseBuffer
;
158 } GenericReparseBuffer
;
160 } REPARSE_DATA_BUFFER
, *PREPARSE_DATA_BUFFER
;
162 #ifndef FILE_DEVICE_FILE_SYSTEM
163 #define FILE_DEVICE_FILE_SYSTEM 9
165 #ifndef METHOD_BUFFERED
166 #define METHOD_BUFFERED 0
168 #ifndef FILE_ANY_ACCESS
169 #define FILE_ANY_ACCESS 0x00000000
172 #define CTL_CODE(t,f,m,a) (((t)<<16)|((a)<<14)|((f)<<2)|(m))
174 #define FSCTL_GET_REPARSE_POINT \
175 CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 42, METHOD_BUFFERED, FILE_ANY_ACCESS)
178 /* TCP connection support. */
179 #include <sys/socket.h>
200 #include "w32common.h"
202 #include "w32select.h"
204 #include "dispextern.h" /* for xstrcasecmp */
205 #include "coding.h" /* for Vlocale_coding_system */
207 #include "careadlinkat.h"
208 #include "allocator.h"
210 /* For serial_configure and serial_open. */
213 typedef HRESULT (WINAPI
* ShGetFolderPath_fn
)
214 (IN HWND
, IN
int, IN HANDLE
, IN DWORD
, OUT
char *);
216 Lisp_Object QCloaded_from
;
218 void globals_of_w32 (void);
219 static DWORD
get_rid (PSID
);
220 static int is_symlink (const char *);
221 static char * chase_symlinks (const char *);
222 static int enable_privilege (LPCTSTR
, BOOL
, TOKEN_PRIVILEGES
*);
223 static int restore_privilege (TOKEN_PRIVILEGES
*);
224 static BOOL WINAPI
revert_to_self (void);
226 extern int sys_access (const char *, int);
227 extern void *e_malloc (size_t);
228 extern int sys_select (int, SELECT_TYPE
*, SELECT_TYPE
*, SELECT_TYPE
*,
229 EMACS_TIME
*, void *);
233 /* Initialization states.
235 WARNING: If you add any more such variables for additional APIs,
236 you MUST add initialization for them to globals_of_w32
237 below. This is because these variables might get set
238 to non-NULL values during dumping, but the dumped Emacs
239 cannot reuse those values, because it could be run on a
240 different version of the OS, where API addresses are
242 static BOOL g_b_init_is_windows_9x
;
243 static BOOL g_b_init_open_process_token
;
244 static BOOL g_b_init_get_token_information
;
245 static BOOL g_b_init_lookup_account_sid
;
246 static BOOL g_b_init_get_sid_sub_authority
;
247 static BOOL g_b_init_get_sid_sub_authority_count
;
248 static BOOL g_b_init_get_security_info
;
249 static BOOL g_b_init_get_file_security
;
250 static BOOL g_b_init_get_security_descriptor_owner
;
251 static BOOL g_b_init_get_security_descriptor_group
;
252 static BOOL g_b_init_is_valid_sid
;
253 static BOOL g_b_init_create_toolhelp32_snapshot
;
254 static BOOL g_b_init_process32_first
;
255 static BOOL g_b_init_process32_next
;
256 static BOOL g_b_init_open_thread_token
;
257 static BOOL g_b_init_impersonate_self
;
258 static BOOL g_b_init_revert_to_self
;
259 static BOOL g_b_init_get_process_memory_info
;
260 static BOOL g_b_init_get_process_working_set_size
;
261 static BOOL g_b_init_global_memory_status
;
262 static BOOL g_b_init_global_memory_status_ex
;
263 static BOOL g_b_init_get_length_sid
;
264 static BOOL g_b_init_equal_sid
;
265 static BOOL g_b_init_copy_sid
;
266 static BOOL g_b_init_get_native_system_info
;
267 static BOOL g_b_init_get_system_times
;
268 static BOOL g_b_init_create_symbolic_link
;
269 static BOOL g_b_init_get_security_descriptor_dacl
;
270 static BOOL g_b_init_convert_sd_to_sddl
;
271 static BOOL g_b_init_convert_sddl_to_sd
;
272 static BOOL g_b_init_is_valid_security_descriptor
;
273 static BOOL g_b_init_set_file_security
;
276 BEGIN: Wrapper functions around OpenProcessToken
277 and other functions in advapi32.dll that are only
278 supported in Windows NT / 2k / XP
280 /* ** Function pointer typedefs ** */
281 typedef BOOL (WINAPI
* OpenProcessToken_Proc
) (
282 HANDLE ProcessHandle
,
284 PHANDLE TokenHandle
);
285 typedef BOOL (WINAPI
* GetTokenInformation_Proc
) (
287 TOKEN_INFORMATION_CLASS TokenInformationClass
,
288 LPVOID TokenInformation
,
289 DWORD TokenInformationLength
,
290 PDWORD ReturnLength
);
291 typedef BOOL (WINAPI
* GetProcessTimes_Proc
) (
292 HANDLE process_handle
,
293 LPFILETIME creation_time
,
294 LPFILETIME exit_time
,
295 LPFILETIME kernel_time
,
296 LPFILETIME user_time
);
298 GetProcessTimes_Proc get_process_times_fn
= NULL
;
301 const char * const LookupAccountSid_Name
= "LookupAccountSidW";
302 const char * const GetFileSecurity_Name
= "GetFileSecurityW";
303 const char * const SetFileSecurity_Name
= "SetFileSecurityW";
305 const char * const LookupAccountSid_Name
= "LookupAccountSidA";
306 const char * const GetFileSecurity_Name
= "GetFileSecurityA";
307 const char * const SetFileSecurity_Name
= "SetFileSecurityA";
309 typedef BOOL (WINAPI
* LookupAccountSid_Proc
) (
310 LPCTSTR lpSystemName
,
315 LPDWORD cbDomainName
,
316 PSID_NAME_USE peUse
);
317 typedef PDWORD (WINAPI
* GetSidSubAuthority_Proc
) (
320 typedef PUCHAR (WINAPI
* GetSidSubAuthorityCount_Proc
) (
322 typedef DWORD (WINAPI
* GetSecurityInfo_Proc
) (
324 SE_OBJECT_TYPE ObjectType
,
325 SECURITY_INFORMATION SecurityInfo
,
330 PSECURITY_DESCRIPTOR
*ppSecurityDescriptor
);
331 typedef BOOL (WINAPI
* GetFileSecurity_Proc
) (
333 SECURITY_INFORMATION RequestedInformation
,
334 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
336 LPDWORD lpnLengthNeeded
);
337 typedef BOOL (WINAPI
*SetFileSecurity_Proc
) (
339 SECURITY_INFORMATION SecurityInformation
,
340 PSECURITY_DESCRIPTOR pSecurityDescriptor
);
341 typedef BOOL (WINAPI
* GetSecurityDescriptorOwner_Proc
) (
342 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
344 LPBOOL lpbOwnerDefaulted
);
345 typedef BOOL (WINAPI
* GetSecurityDescriptorGroup_Proc
) (
346 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
348 LPBOOL lpbGroupDefaulted
);
349 typedef BOOL (WINAPI
*GetSecurityDescriptorDacl_Proc
) (
350 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
351 LPBOOL lpbDaclPresent
,
353 LPBOOL lpbDaclDefaulted
);
354 typedef BOOL (WINAPI
* IsValidSid_Proc
) (
356 typedef HANDLE (WINAPI
* CreateToolhelp32Snapshot_Proc
) (
358 DWORD th32ProcessID
);
359 typedef BOOL (WINAPI
* Process32First_Proc
) (
361 LPPROCESSENTRY32 lppe
);
362 typedef BOOL (WINAPI
* Process32Next_Proc
) (
364 LPPROCESSENTRY32 lppe
);
365 typedef BOOL (WINAPI
* OpenThreadToken_Proc
) (
369 PHANDLE TokenHandle
);
370 typedef BOOL (WINAPI
* ImpersonateSelf_Proc
) (
371 SECURITY_IMPERSONATION_LEVEL ImpersonationLevel
);
372 typedef BOOL (WINAPI
* RevertToSelf_Proc
) (void);
373 typedef BOOL (WINAPI
* GetProcessMemoryInfo_Proc
) (
375 PPROCESS_MEMORY_COUNTERS ppsmemCounters
,
377 typedef BOOL (WINAPI
* GetProcessWorkingSetSize_Proc
) (
379 PSIZE_T lpMinimumWorkingSetSize
,
380 PSIZE_T lpMaximumWorkingSetSize
);
381 typedef BOOL (WINAPI
* GlobalMemoryStatus_Proc
) (
382 LPMEMORYSTATUS lpBuffer
);
383 typedef BOOL (WINAPI
* GlobalMemoryStatusEx_Proc
) (
384 LPMEMORY_STATUS_EX lpBuffer
);
385 typedef BOOL (WINAPI
* CopySid_Proc
) (
386 DWORD nDestinationSidLength
,
387 PSID pDestinationSid
,
389 typedef BOOL (WINAPI
* EqualSid_Proc
) (
392 typedef DWORD (WINAPI
* GetLengthSid_Proc
) (
394 typedef void (WINAPI
* GetNativeSystemInfo_Proc
) (
395 LPSYSTEM_INFO lpSystemInfo
);
396 typedef BOOL (WINAPI
* GetSystemTimes_Proc
) (
397 LPFILETIME lpIdleTime
,
398 LPFILETIME lpKernelTime
,
399 LPFILETIME lpUserTime
);
400 typedef BOOLEAN (WINAPI
*CreateSymbolicLink_Proc
) (
401 LPTSTR lpSymlinkFileName
,
402 LPTSTR lpTargetFileName
,
404 typedef BOOL (WINAPI
*ConvertStringSecurityDescriptorToSecurityDescriptor_Proc
) (
405 LPCTSTR StringSecurityDescriptor
,
406 DWORD StringSDRevision
,
407 PSECURITY_DESCRIPTOR
*SecurityDescriptor
,
408 PULONG SecurityDescriptorSize
);
409 typedef BOOL (WINAPI
*ConvertSecurityDescriptorToStringSecurityDescriptor_Proc
) (
410 PSECURITY_DESCRIPTOR SecurityDescriptor
,
411 DWORD RequestedStringSDRevision
,
412 SECURITY_INFORMATION SecurityInformation
,
413 LPTSTR
*StringSecurityDescriptor
,
414 PULONG StringSecurityDescriptorLen
);
415 typedef BOOL (WINAPI
*IsValidSecurityDescriptor_Proc
) (PSECURITY_DESCRIPTOR
);
417 /* ** A utility function ** */
421 static BOOL s_b_ret
= 0;
422 OSVERSIONINFO os_ver
;
423 if (g_b_init_is_windows_9x
== 0)
425 g_b_init_is_windows_9x
= 1;
426 ZeroMemory (&os_ver
, sizeof (OSVERSIONINFO
));
427 os_ver
.dwOSVersionInfoSize
= sizeof (OSVERSIONINFO
);
428 if (GetVersionEx (&os_ver
))
430 s_b_ret
= (os_ver
.dwPlatformId
== VER_PLATFORM_WIN32_WINDOWS
);
436 static Lisp_Object
ltime (ULONGLONG
);
438 /* Get total user and system times for get-internal-run-time.
439 Returns a list of integers if the times are provided by the OS
440 (NT derivatives), otherwise it returns the result of current-time. */
442 w32_get_internal_run_time (void)
444 if (get_process_times_fn
)
446 FILETIME create
, exit
, kernel
, user
;
447 HANDLE proc
= GetCurrentProcess ();
448 if ((*get_process_times_fn
) (proc
, &create
, &exit
, &kernel
, &user
))
450 LARGE_INTEGER user_int
, kernel_int
, total
;
451 user_int
.LowPart
= user
.dwLowDateTime
;
452 user_int
.HighPart
= user
.dwHighDateTime
;
453 kernel_int
.LowPart
= kernel
.dwLowDateTime
;
454 kernel_int
.HighPart
= kernel
.dwHighDateTime
;
455 total
.QuadPart
= user_int
.QuadPart
+ kernel_int
.QuadPart
;
456 return ltime (total
.QuadPart
);
460 return Fcurrent_time ();
463 /* ** The wrapper functions ** */
466 open_process_token (HANDLE ProcessHandle
,
470 static OpenProcessToken_Proc s_pfn_Open_Process_Token
= NULL
;
471 HMODULE hm_advapi32
= NULL
;
472 if (is_windows_9x () == TRUE
)
476 if (g_b_init_open_process_token
== 0)
478 g_b_init_open_process_token
= 1;
479 hm_advapi32
= LoadLibrary ("Advapi32.dll");
480 s_pfn_Open_Process_Token
=
481 (OpenProcessToken_Proc
) GetProcAddress (hm_advapi32
, "OpenProcessToken");
483 if (s_pfn_Open_Process_Token
== NULL
)
488 s_pfn_Open_Process_Token (
496 get_token_information (HANDLE TokenHandle
,
497 TOKEN_INFORMATION_CLASS TokenInformationClass
,
498 LPVOID TokenInformation
,
499 DWORD TokenInformationLength
,
502 static GetTokenInformation_Proc s_pfn_Get_Token_Information
= NULL
;
503 HMODULE hm_advapi32
= NULL
;
504 if (is_windows_9x () == TRUE
)
508 if (g_b_init_get_token_information
== 0)
510 g_b_init_get_token_information
= 1;
511 hm_advapi32
= LoadLibrary ("Advapi32.dll");
512 s_pfn_Get_Token_Information
=
513 (GetTokenInformation_Proc
) GetProcAddress (hm_advapi32
, "GetTokenInformation");
515 if (s_pfn_Get_Token_Information
== NULL
)
520 s_pfn_Get_Token_Information (
522 TokenInformationClass
,
524 TokenInformationLength
,
530 lookup_account_sid (LPCTSTR lpSystemName
,
535 LPDWORD cbDomainName
,
538 static LookupAccountSid_Proc s_pfn_Lookup_Account_Sid
= NULL
;
539 HMODULE hm_advapi32
= NULL
;
540 if (is_windows_9x () == TRUE
)
544 if (g_b_init_lookup_account_sid
== 0)
546 g_b_init_lookup_account_sid
= 1;
547 hm_advapi32
= LoadLibrary ("Advapi32.dll");
548 s_pfn_Lookup_Account_Sid
=
549 (LookupAccountSid_Proc
) GetProcAddress (hm_advapi32
, LookupAccountSid_Name
);
551 if (s_pfn_Lookup_Account_Sid
== NULL
)
556 s_pfn_Lookup_Account_Sid (
568 get_sid_sub_authority (PSID pSid
, DWORD n
)
570 static GetSidSubAuthority_Proc s_pfn_Get_Sid_Sub_Authority
= NULL
;
571 static DWORD zero
= 0U;
572 HMODULE hm_advapi32
= NULL
;
573 if (is_windows_9x () == TRUE
)
577 if (g_b_init_get_sid_sub_authority
== 0)
579 g_b_init_get_sid_sub_authority
= 1;
580 hm_advapi32
= LoadLibrary ("Advapi32.dll");
581 s_pfn_Get_Sid_Sub_Authority
=
582 (GetSidSubAuthority_Proc
) GetProcAddress (
583 hm_advapi32
, "GetSidSubAuthority");
585 if (s_pfn_Get_Sid_Sub_Authority
== NULL
)
589 return (s_pfn_Get_Sid_Sub_Authority (pSid
, n
));
593 get_sid_sub_authority_count (PSID pSid
)
595 static GetSidSubAuthorityCount_Proc s_pfn_Get_Sid_Sub_Authority_Count
= NULL
;
596 static UCHAR zero
= 0U;
597 HMODULE hm_advapi32
= NULL
;
598 if (is_windows_9x () == TRUE
)
602 if (g_b_init_get_sid_sub_authority_count
== 0)
604 g_b_init_get_sid_sub_authority_count
= 1;
605 hm_advapi32
= LoadLibrary ("Advapi32.dll");
606 s_pfn_Get_Sid_Sub_Authority_Count
=
607 (GetSidSubAuthorityCount_Proc
) GetProcAddress (
608 hm_advapi32
, "GetSidSubAuthorityCount");
610 if (s_pfn_Get_Sid_Sub_Authority_Count
== NULL
)
614 return (s_pfn_Get_Sid_Sub_Authority_Count (pSid
));
618 get_security_info (HANDLE handle
,
619 SE_OBJECT_TYPE ObjectType
,
620 SECURITY_INFORMATION SecurityInfo
,
625 PSECURITY_DESCRIPTOR
*ppSecurityDescriptor
)
627 static GetSecurityInfo_Proc s_pfn_Get_Security_Info
= NULL
;
628 HMODULE hm_advapi32
= NULL
;
629 if (is_windows_9x () == TRUE
)
633 if (g_b_init_get_security_info
== 0)
635 g_b_init_get_security_info
= 1;
636 hm_advapi32
= LoadLibrary ("Advapi32.dll");
637 s_pfn_Get_Security_Info
=
638 (GetSecurityInfo_Proc
) GetProcAddress (
639 hm_advapi32
, "GetSecurityInfo");
641 if (s_pfn_Get_Security_Info
== NULL
)
645 return (s_pfn_Get_Security_Info (handle
, ObjectType
, SecurityInfo
,
646 ppsidOwner
, ppsidGroup
, ppDacl
, ppSacl
,
647 ppSecurityDescriptor
));
651 get_file_security (LPCTSTR lpFileName
,
652 SECURITY_INFORMATION RequestedInformation
,
653 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
655 LPDWORD lpnLengthNeeded
)
657 static GetFileSecurity_Proc s_pfn_Get_File_Security
= NULL
;
658 HMODULE hm_advapi32
= NULL
;
659 if (is_windows_9x () == TRUE
)
664 if (g_b_init_get_file_security
== 0)
666 g_b_init_get_file_security
= 1;
667 hm_advapi32
= LoadLibrary ("Advapi32.dll");
668 s_pfn_Get_File_Security
=
669 (GetFileSecurity_Proc
) GetProcAddress (
670 hm_advapi32
, GetFileSecurity_Name
);
672 if (s_pfn_Get_File_Security
== NULL
)
677 return (s_pfn_Get_File_Security (lpFileName
, RequestedInformation
,
678 pSecurityDescriptor
, nLength
,
683 set_file_security (LPCTSTR lpFileName
,
684 SECURITY_INFORMATION SecurityInformation
,
685 PSECURITY_DESCRIPTOR pSecurityDescriptor
)
687 static SetFileSecurity_Proc s_pfn_Set_File_Security
= NULL
;
688 HMODULE hm_advapi32
= NULL
;
689 if (is_windows_9x () == TRUE
)
694 if (g_b_init_set_file_security
== 0)
696 g_b_init_set_file_security
= 1;
697 hm_advapi32
= LoadLibrary ("Advapi32.dll");
698 s_pfn_Set_File_Security
=
699 (SetFileSecurity_Proc
) GetProcAddress (
700 hm_advapi32
, SetFileSecurity_Name
);
702 if (s_pfn_Set_File_Security
== NULL
)
707 return (s_pfn_Set_File_Security (lpFileName
, SecurityInformation
,
708 pSecurityDescriptor
));
712 get_security_descriptor_owner (PSECURITY_DESCRIPTOR pSecurityDescriptor
,
714 LPBOOL lpbOwnerDefaulted
)
716 static GetSecurityDescriptorOwner_Proc s_pfn_Get_Security_Descriptor_Owner
= NULL
;
717 HMODULE hm_advapi32
= NULL
;
718 if (is_windows_9x () == TRUE
)
723 if (g_b_init_get_security_descriptor_owner
== 0)
725 g_b_init_get_security_descriptor_owner
= 1;
726 hm_advapi32
= LoadLibrary ("Advapi32.dll");
727 s_pfn_Get_Security_Descriptor_Owner
=
728 (GetSecurityDescriptorOwner_Proc
) GetProcAddress (
729 hm_advapi32
, "GetSecurityDescriptorOwner");
731 if (s_pfn_Get_Security_Descriptor_Owner
== NULL
)
736 return (s_pfn_Get_Security_Descriptor_Owner (pSecurityDescriptor
, pOwner
,
741 get_security_descriptor_group (PSECURITY_DESCRIPTOR pSecurityDescriptor
,
743 LPBOOL lpbGroupDefaulted
)
745 static GetSecurityDescriptorGroup_Proc s_pfn_Get_Security_Descriptor_Group
= NULL
;
746 HMODULE hm_advapi32
= NULL
;
747 if (is_windows_9x () == TRUE
)
752 if (g_b_init_get_security_descriptor_group
== 0)
754 g_b_init_get_security_descriptor_group
= 1;
755 hm_advapi32
= LoadLibrary ("Advapi32.dll");
756 s_pfn_Get_Security_Descriptor_Group
=
757 (GetSecurityDescriptorGroup_Proc
) GetProcAddress (
758 hm_advapi32
, "GetSecurityDescriptorGroup");
760 if (s_pfn_Get_Security_Descriptor_Group
== NULL
)
765 return (s_pfn_Get_Security_Descriptor_Group (pSecurityDescriptor
, pGroup
,
770 get_security_descriptor_dacl (PSECURITY_DESCRIPTOR pSecurityDescriptor
,
771 LPBOOL lpbDaclPresent
,
773 LPBOOL lpbDaclDefaulted
)
775 static GetSecurityDescriptorDacl_Proc s_pfn_Get_Security_Descriptor_Dacl
= NULL
;
776 HMODULE hm_advapi32
= NULL
;
777 if (is_windows_9x () == TRUE
)
782 if (g_b_init_get_security_descriptor_dacl
== 0)
784 g_b_init_get_security_descriptor_dacl
= 1;
785 hm_advapi32
= LoadLibrary ("Advapi32.dll");
786 s_pfn_Get_Security_Descriptor_Dacl
=
787 (GetSecurityDescriptorDacl_Proc
) GetProcAddress (
788 hm_advapi32
, "GetSecurityDescriptorDacl");
790 if (s_pfn_Get_Security_Descriptor_Dacl
== NULL
)
795 return (s_pfn_Get_Security_Descriptor_Dacl (pSecurityDescriptor
,
796 lpbDaclPresent
, pDacl
,
801 is_valid_sid (PSID sid
)
803 static IsValidSid_Proc s_pfn_Is_Valid_Sid
= NULL
;
804 HMODULE hm_advapi32
= NULL
;
805 if (is_windows_9x () == TRUE
)
809 if (g_b_init_is_valid_sid
== 0)
811 g_b_init_is_valid_sid
= 1;
812 hm_advapi32
= LoadLibrary ("Advapi32.dll");
814 (IsValidSid_Proc
) GetProcAddress (
815 hm_advapi32
, "IsValidSid");
817 if (s_pfn_Is_Valid_Sid
== NULL
)
821 return (s_pfn_Is_Valid_Sid (sid
));
825 equal_sid (PSID sid1
, PSID sid2
)
827 static EqualSid_Proc s_pfn_Equal_Sid
= NULL
;
828 HMODULE hm_advapi32
= NULL
;
829 if (is_windows_9x () == TRUE
)
833 if (g_b_init_equal_sid
== 0)
835 g_b_init_equal_sid
= 1;
836 hm_advapi32
= LoadLibrary ("Advapi32.dll");
838 (EqualSid_Proc
) GetProcAddress (
839 hm_advapi32
, "EqualSid");
841 if (s_pfn_Equal_Sid
== NULL
)
845 return (s_pfn_Equal_Sid (sid1
, sid2
));
849 get_length_sid (PSID sid
)
851 static GetLengthSid_Proc s_pfn_Get_Length_Sid
= NULL
;
852 HMODULE hm_advapi32
= NULL
;
853 if (is_windows_9x () == TRUE
)
857 if (g_b_init_get_length_sid
== 0)
859 g_b_init_get_length_sid
= 1;
860 hm_advapi32
= LoadLibrary ("Advapi32.dll");
861 s_pfn_Get_Length_Sid
=
862 (GetLengthSid_Proc
) GetProcAddress (
863 hm_advapi32
, "GetLengthSid");
865 if (s_pfn_Get_Length_Sid
== NULL
)
869 return (s_pfn_Get_Length_Sid (sid
));
873 copy_sid (DWORD destlen
, PSID dest
, PSID src
)
875 static CopySid_Proc s_pfn_Copy_Sid
= NULL
;
876 HMODULE hm_advapi32
= NULL
;
877 if (is_windows_9x () == TRUE
)
881 if (g_b_init_copy_sid
== 0)
883 g_b_init_copy_sid
= 1;
884 hm_advapi32
= LoadLibrary ("Advapi32.dll");
886 (CopySid_Proc
) GetProcAddress (
887 hm_advapi32
, "CopySid");
889 if (s_pfn_Copy_Sid
== NULL
)
893 return (s_pfn_Copy_Sid (destlen
, dest
, src
));
897 END: Wrapper functions around OpenProcessToken
898 and other functions in advapi32.dll that are only
899 supported in Windows NT / 2k / XP
903 get_native_system_info (LPSYSTEM_INFO lpSystemInfo
)
905 static GetNativeSystemInfo_Proc s_pfn_Get_Native_System_Info
= NULL
;
906 if (is_windows_9x () != TRUE
)
908 if (g_b_init_get_native_system_info
== 0)
910 g_b_init_get_native_system_info
= 1;
911 s_pfn_Get_Native_System_Info
=
912 (GetNativeSystemInfo_Proc
)GetProcAddress (GetModuleHandle ("kernel32.dll"),
913 "GetNativeSystemInfo");
915 if (s_pfn_Get_Native_System_Info
!= NULL
)
916 s_pfn_Get_Native_System_Info (lpSystemInfo
);
919 lpSystemInfo
->dwNumberOfProcessors
= -1;
923 get_system_times (LPFILETIME lpIdleTime
,
924 LPFILETIME lpKernelTime
,
925 LPFILETIME lpUserTime
)
927 static GetSystemTimes_Proc s_pfn_Get_System_times
= NULL
;
928 if (is_windows_9x () == TRUE
)
932 if (g_b_init_get_system_times
== 0)
934 g_b_init_get_system_times
= 1;
935 s_pfn_Get_System_times
=
936 (GetSystemTimes_Proc
)GetProcAddress (GetModuleHandle ("kernel32.dll"),
939 if (s_pfn_Get_System_times
== NULL
)
941 return (s_pfn_Get_System_times (lpIdleTime
, lpKernelTime
, lpUserTime
));
944 static BOOLEAN WINAPI
945 create_symbolic_link (LPTSTR lpSymlinkFilename
,
946 LPTSTR lpTargetFileName
,
949 static CreateSymbolicLink_Proc s_pfn_Create_Symbolic_Link
= NULL
;
952 if (is_windows_9x () == TRUE
)
957 if (g_b_init_create_symbolic_link
== 0)
959 g_b_init_create_symbolic_link
= 1;
961 s_pfn_Create_Symbolic_Link
=
962 (CreateSymbolicLink_Proc
)GetProcAddress (GetModuleHandle ("kernel32.dll"),
963 "CreateSymbolicLinkW");
965 s_pfn_Create_Symbolic_Link
=
966 (CreateSymbolicLink_Proc
)GetProcAddress (GetModuleHandle ("kernel32.dll"),
967 "CreateSymbolicLinkA");
970 if (s_pfn_Create_Symbolic_Link
== NULL
)
976 retval
= s_pfn_Create_Symbolic_Link (lpSymlinkFilename
, lpTargetFileName
,
978 /* If we were denied creation of the symlink, try again after
979 enabling the SeCreateSymbolicLinkPrivilege for our process. */
982 TOKEN_PRIVILEGES priv_current
;
984 if (enable_privilege (SE_CREATE_SYMBOLIC_LINK_NAME
, TRUE
, &priv_current
))
986 retval
= s_pfn_Create_Symbolic_Link (lpSymlinkFilename
, lpTargetFileName
,
988 restore_privilege (&priv_current
);
996 is_valid_security_descriptor (PSECURITY_DESCRIPTOR pSecurityDescriptor
)
998 static IsValidSecurityDescriptor_Proc s_pfn_Is_Valid_Security_Descriptor_Proc
= NULL
;
1000 if (is_windows_9x () == TRUE
)
1006 if (g_b_init_is_valid_security_descriptor
== 0)
1008 g_b_init_is_valid_security_descriptor
= 1;
1009 s_pfn_Is_Valid_Security_Descriptor_Proc
=
1010 (IsValidSecurityDescriptor_Proc
)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1011 "IsValidSecurityDescriptor");
1013 if (s_pfn_Is_Valid_Security_Descriptor_Proc
== NULL
)
1019 return s_pfn_Is_Valid_Security_Descriptor_Proc (pSecurityDescriptor
);
1023 convert_sd_to_sddl (PSECURITY_DESCRIPTOR SecurityDescriptor
,
1024 DWORD RequestedStringSDRevision
,
1025 SECURITY_INFORMATION SecurityInformation
,
1026 LPTSTR
*StringSecurityDescriptor
,
1027 PULONG StringSecurityDescriptorLen
)
1029 static ConvertSecurityDescriptorToStringSecurityDescriptor_Proc s_pfn_Convert_SD_To_SDDL
= NULL
;
1032 if (is_windows_9x () == TRUE
)
1038 if (g_b_init_convert_sd_to_sddl
== 0)
1040 g_b_init_convert_sd_to_sddl
= 1;
1042 s_pfn_Convert_SD_To_SDDL
=
1043 (ConvertSecurityDescriptorToStringSecurityDescriptor_Proc
)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1044 "ConvertSecurityDescriptorToStringSecurityDescriptorW");
1046 s_pfn_Convert_SD_To_SDDL
=
1047 (ConvertSecurityDescriptorToStringSecurityDescriptor_Proc
)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1048 "ConvertSecurityDescriptorToStringSecurityDescriptorA");
1051 if (s_pfn_Convert_SD_To_SDDL
== NULL
)
1057 retval
= s_pfn_Convert_SD_To_SDDL (SecurityDescriptor
,
1058 RequestedStringSDRevision
,
1059 SecurityInformation
,
1060 StringSecurityDescriptor
,
1061 StringSecurityDescriptorLen
);
1067 convert_sddl_to_sd (LPCTSTR StringSecurityDescriptor
,
1068 DWORD StringSDRevision
,
1069 PSECURITY_DESCRIPTOR
*SecurityDescriptor
,
1070 PULONG SecurityDescriptorSize
)
1072 static ConvertStringSecurityDescriptorToSecurityDescriptor_Proc s_pfn_Convert_SDDL_To_SD
= NULL
;
1075 if (is_windows_9x () == TRUE
)
1081 if (g_b_init_convert_sddl_to_sd
== 0)
1083 g_b_init_convert_sddl_to_sd
= 1;
1085 s_pfn_Convert_SDDL_To_SD
=
1086 (ConvertStringSecurityDescriptorToSecurityDescriptor_Proc
)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1087 "ConvertStringSecurityDescriptorToSecurityDescriptorW");
1089 s_pfn_Convert_SDDL_To_SD
=
1090 (ConvertStringSecurityDescriptorToSecurityDescriptor_Proc
)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1091 "ConvertStringSecurityDescriptorToSecurityDescriptorA");
1094 if (s_pfn_Convert_SDDL_To_SD
== NULL
)
1100 retval
= s_pfn_Convert_SDDL_To_SD (StringSecurityDescriptor
,
1103 SecurityDescriptorSize
);
1110 /* Return 1 if P is a valid pointer to an object of size SIZE. Return
1111 0 if P is NOT a valid pointer. Return -1 if we cannot validate P.
1113 This is called from alloc.c:valid_pointer_p. */
1115 w32_valid_pointer_p (void *p
, int size
)
1118 HANDLE h
= OpenProcess (PROCESS_VM_READ
, FALSE
, GetCurrentProcessId ());
1122 unsigned char *buf
= alloca (size
);
1123 int retval
= ReadProcessMemory (h
, p
, buf
, size
, &done
);
1132 static char startup_dir
[MAXPATHLEN
];
1134 /* Get the current working directory. */
1136 getcwd (char *dir
, int dirsize
)
1143 if (dirsize
<= strlen (startup_dir
))
1149 if (GetCurrentDirectory (MAXPATHLEN
, dir
) > 0)
1153 /* Emacs doesn't actually change directory itself, it stays in the
1154 same directory where it was started. */
1155 strcpy (dir
, startup_dir
);
1160 /* Emulate getloadavg. */
1162 struct load_sample
{
1169 /* Number of processors on this machine. */
1170 static unsigned num_of_processors
;
1172 /* We maintain 1-sec samples for the last 16 minutes in a circular buffer. */
1173 static struct load_sample samples
[16*60];
1174 static int first_idx
= -1, last_idx
= -1;
1175 static int max_idx
= sizeof (samples
) / sizeof (samples
[0]);
1180 int next_idx
= from
+ 1;
1182 if (next_idx
>= max_idx
)
1191 int prev_idx
= from
- 1;
1194 prev_idx
= max_idx
- 1;
1200 sample_system_load (ULONGLONG
*idle
, ULONGLONG
*kernel
, ULONGLONG
*user
)
1202 SYSTEM_INFO sysinfo
;
1203 FILETIME ft_idle
, ft_user
, ft_kernel
;
1205 /* Initialize the number of processors on this machine. */
1206 if (num_of_processors
<= 0)
1208 get_native_system_info (&sysinfo
);
1209 num_of_processors
= sysinfo
.dwNumberOfProcessors
;
1210 if (num_of_processors
<= 0)
1212 GetSystemInfo (&sysinfo
);
1213 num_of_processors
= sysinfo
.dwNumberOfProcessors
;
1215 if (num_of_processors
<= 0)
1216 num_of_processors
= 1;
1219 /* TODO: Take into account threads that are ready to run, by
1220 sampling the "\System\Processor Queue Length" performance
1221 counter. The code below accounts only for threads that are
1222 actually running. */
1224 if (get_system_times (&ft_idle
, &ft_kernel
, &ft_user
))
1226 ULARGE_INTEGER uidle
, ukernel
, uuser
;
1228 memcpy (&uidle
, &ft_idle
, sizeof (ft_idle
));
1229 memcpy (&ukernel
, &ft_kernel
, sizeof (ft_kernel
));
1230 memcpy (&uuser
, &ft_user
, sizeof (ft_user
));
1231 *idle
= uidle
.QuadPart
;
1232 *kernel
= ukernel
.QuadPart
;
1233 *user
= uuser
.QuadPart
;
1243 /* Produce the load average for a given time interval, using the
1244 samples in the samples[] array. WHICH can be 0, 1, or 2, meaning
1245 1-minute, 5-minute, or 15-minute average, respectively. */
1249 double retval
= -1.0;
1252 double span
= (which
== 0 ? 1.0 : (which
== 1 ? 5.0 : 15.0)) * 60;
1253 time_t now
= samples
[last_idx
].sample_time
;
1255 if (first_idx
!= last_idx
)
1257 for (idx
= buf_prev (last_idx
); ; idx
= buf_prev (idx
))
1259 tdiff
= difftime (now
, samples
[idx
].sample_time
);
1260 if (tdiff
>= span
- 2*DBL_EPSILON
*now
)
1263 samples
[last_idx
].kernel
+ samples
[last_idx
].user
1264 - (samples
[idx
].kernel
+ samples
[idx
].user
);
1265 long double idl
= samples
[last_idx
].idle
- samples
[idx
].idle
;
1267 retval
= (1.0 - idl
/ sys
) * num_of_processors
;
1270 if (idx
== first_idx
)
1279 getloadavg (double loadavg
[], int nelem
)
1282 ULONGLONG idle
, kernel
, user
;
1283 time_t now
= time (NULL
);
1285 /* Store another sample. We ignore samples that are less than 1 sec
1287 if (difftime (now
, samples
[last_idx
].sample_time
) >= 1.0 - 2*DBL_EPSILON
*now
)
1289 sample_system_load (&idle
, &kernel
, &user
);
1290 last_idx
= buf_next (last_idx
);
1291 samples
[last_idx
].sample_time
= now
;
1292 samples
[last_idx
].idle
= idle
;
1293 samples
[last_idx
].kernel
= kernel
;
1294 samples
[last_idx
].user
= user
;
1295 /* If the buffer has more that 15 min worth of samples, discard
1297 if (first_idx
== -1)
1298 first_idx
= last_idx
;
1299 while (first_idx
!= last_idx
1300 && (difftime (now
, samples
[first_idx
].sample_time
)
1301 >= 15.0*60 + 2*DBL_EPSILON
*now
))
1302 first_idx
= buf_next (first_idx
);
1305 for (elem
= 0; elem
< nelem
; elem
++)
1307 double avg
= getavg (elem
);
1311 loadavg
[elem
] = avg
;
1317 /* Emulate getpwuid, getpwnam and others. */
1319 #define PASSWD_FIELD_SIZE 256
1321 static char dflt_passwd_name
[PASSWD_FIELD_SIZE
];
1322 static char dflt_passwd_passwd
[PASSWD_FIELD_SIZE
];
1323 static char dflt_passwd_gecos
[PASSWD_FIELD_SIZE
];
1324 static char dflt_passwd_dir
[PASSWD_FIELD_SIZE
];
1325 static char dflt_passwd_shell
[PASSWD_FIELD_SIZE
];
1327 static struct passwd dflt_passwd
=
1339 static char dflt_group_name
[GNLEN
+1];
1341 static struct group dflt_group
=
1343 /* When group information is not available, we return this as the
1344 group for all files. */
1352 return dflt_passwd
.pw_uid
;
1358 /* I could imagine arguing for checking to see whether the user is
1359 in the Administrators group and returning a UID of 0 for that
1360 case, but I don't know how wise that would be in the long run. */
1367 return dflt_passwd
.pw_gid
;
1377 getpwuid (unsigned uid
)
1379 if (uid
== dflt_passwd
.pw_uid
)
1380 return &dflt_passwd
;
1385 getgrgid (gid_t gid
)
1391 getpwnam (char *name
)
1395 pw
= getpwuid (getuid ());
1399 if (xstrcasecmp (name
, pw
->pw_name
))
1406 init_user_info (void)
1408 /* Find the user's real name by opening the process token and
1409 looking up the name associated with the user-sid in that token.
1411 Use the relative portion of the identifier authority value from
1412 the user-sid as the user id value (same for group id using the
1413 primary group sid from the process token). */
1415 char uname
[UNLEN
+1], gname
[GNLEN
+1], domain
[1025];
1416 DWORD ulength
= sizeof (uname
), dlength
= sizeof (domain
), needed
;
1417 DWORD glength
= sizeof (gname
);
1418 HANDLE token
= NULL
;
1419 SID_NAME_USE user_type
;
1420 unsigned char *buf
= NULL
;
1422 TOKEN_USER user_token
;
1423 TOKEN_PRIMARY_GROUP group_token
;
1426 result
= open_process_token (GetCurrentProcess (), TOKEN_QUERY
, &token
);
1429 result
= get_token_information (token
, TokenUser
, NULL
, 0, &blen
);
1430 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
1432 buf
= xmalloc (blen
);
1433 result
= get_token_information (token
, TokenUser
,
1434 (LPVOID
)buf
, blen
, &needed
);
1437 memcpy (&user_token
, buf
, sizeof (user_token
));
1438 result
= lookup_account_sid (NULL
, user_token
.User
.Sid
,
1440 domain
, &dlength
, &user_type
);
1448 strcpy (dflt_passwd
.pw_name
, uname
);
1449 /* Determine a reasonable uid value. */
1450 if (xstrcasecmp ("administrator", uname
) == 0)
1452 dflt_passwd
.pw_uid
= 500; /* well-known Administrator uid */
1453 dflt_passwd
.pw_gid
= 513; /* well-known None gid */
1457 /* Use the last sub-authority value of the RID, the relative
1458 portion of the SID, as user/group ID. */
1459 dflt_passwd
.pw_uid
= get_rid (user_token
.User
.Sid
);
1461 /* Get group id and name. */
1462 result
= get_token_information (token
, TokenPrimaryGroup
,
1463 (LPVOID
)buf
, blen
, &needed
);
1464 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
1466 buf
= xrealloc (buf
, blen
= needed
);
1467 result
= get_token_information (token
, TokenPrimaryGroup
,
1468 (LPVOID
)buf
, blen
, &needed
);
1472 memcpy (&group_token
, buf
, sizeof (group_token
));
1473 dflt_passwd
.pw_gid
= get_rid (group_token
.PrimaryGroup
);
1474 dlength
= sizeof (domain
);
1475 /* If we can get at the real Primary Group name, use that.
1476 Otherwise, the default group name was already set to
1477 "None" in globals_of_w32. */
1478 if (lookup_account_sid (NULL
, group_token
.PrimaryGroup
,
1479 gname
, &glength
, NULL
, &dlength
,
1481 strcpy (dflt_group_name
, gname
);
1484 dflt_passwd
.pw_gid
= dflt_passwd
.pw_uid
;
1487 /* If security calls are not supported (presumably because we
1488 are running under Windows 9X), fallback to this: */
1489 else if (GetUserName (uname
, &ulength
))
1491 strcpy (dflt_passwd
.pw_name
, uname
);
1492 if (xstrcasecmp ("administrator", uname
) == 0)
1493 dflt_passwd
.pw_uid
= 0;
1495 dflt_passwd
.pw_uid
= 123;
1496 dflt_passwd
.pw_gid
= dflt_passwd
.pw_uid
;
1500 strcpy (dflt_passwd
.pw_name
, "unknown");
1501 dflt_passwd
.pw_uid
= 123;
1502 dflt_passwd
.pw_gid
= 123;
1504 dflt_group
.gr_gid
= dflt_passwd
.pw_gid
;
1506 /* Ensure HOME and SHELL are defined. */
1507 if (getenv ("HOME") == NULL
)
1509 if (getenv ("SHELL") == NULL
)
1512 /* Set dir and shell from environment variables. */
1513 strcpy (dflt_passwd
.pw_dir
, getenv ("HOME"));
1514 strcpy (dflt_passwd
.pw_shell
, getenv ("SHELL"));
1518 CloseHandle (token
);
1524 /* rand () on NT gives us 15 random bits...hack together 30 bits. */
1525 return ((rand () << 15) | rand ());
1534 /* Current codepage for encoding file names. */
1535 static int file_name_codepage
;
1537 /* Return the maximum length in bytes of a multibyte character
1538 sequence encoded in the current ANSI codepage. This is required to
1539 correctly walk the encoded file names one character at a time. */
1541 max_filename_mbslen (void)
1543 /* A simple cache to avoid calling GetCPInfo every time we need to
1544 normalize a file name. The file-name encoding is not supposed to
1545 be changed too frequently, if ever. */
1546 static Lisp_Object last_file_name_encoding
;
1547 static int last_max_mbslen
;
1548 Lisp_Object current_encoding
;
1550 current_encoding
= Vfile_name_coding_system
;
1551 if (NILP (current_encoding
))
1552 current_encoding
= Vdefault_file_name_coding_system
;
1554 if (!EQ (last_file_name_encoding
, current_encoding
))
1558 last_file_name_encoding
= current_encoding
;
1559 /* Default to the current ANSI codepage. */
1560 file_name_codepage
= w32_ansi_code_page
;
1561 if (!NILP (current_encoding
))
1563 char *cpname
= SDATA (SYMBOL_NAME (current_encoding
));
1564 char *cp
= NULL
, *end
;
1567 if (strncmp (cpname
, "cp", 2) == 0)
1569 else if (strncmp (cpname
, "windows-", 8) == 0)
1575 cpnum
= strtol (cp
, &end
, 10);
1576 if (cpnum
&& *end
== '\0' && end
- cp
>= 2)
1577 file_name_codepage
= cpnum
;
1581 if (!file_name_codepage
)
1582 file_name_codepage
= CP_ACP
; /* CP_ACP = 0, but let's not assume that */
1584 if (!GetCPInfo (file_name_codepage
, &cp_info
))
1586 file_name_codepage
= CP_ACP
;
1587 if (!GetCPInfo (file_name_codepage
, &cp_info
))
1590 last_max_mbslen
= cp_info
.MaxCharSize
;
1593 return last_max_mbslen
;
1596 /* Normalize filename by converting all path separators to
1597 the specified separator. Also conditionally convert upper
1598 case path name components to lower case. */
1601 normalize_filename (register char *fp
, char path_sep
, int multibyte
)
1605 int dbcs_p
= max_filename_mbslen () > 1;
1607 /* Multibyte file names are in the Emacs internal representation, so
1608 we can traverse them by bytes with no problems. */
1612 /* Always lower-case drive letters a-z, even if the filesystem
1613 preserves case in filenames.
1614 This is so filenames can be compared by string comparison
1615 functions that are case-sensitive. Even case-preserving filesystems
1616 do not distinguish case in drive letters. */
1618 p2
= CharNextExA (file_name_codepage
, fp
, 0);
1622 if (*p2
== ':' && *fp
>= 'A' && *fp
<= 'Z')
1628 if (multibyte
|| NILP (Vw32_downcase_file_names
))
1632 if (*fp
== '/' || *fp
== '\\')
1637 fp
= CharNextExA (file_name_codepage
, fp
, 0);
1642 sep
= path_sep
; /* convert to this path separator */
1643 elem
= fp
; /* start of current path element */
1646 if (*fp
>= 'a' && *fp
<= 'z')
1647 elem
= 0; /* don't convert this element */
1649 if (*fp
== 0 || *fp
== ':')
1651 sep
= *fp
; /* restore current separator (or 0) */
1652 *fp
= '/'; /* after conversion of this element */
1655 if (*fp
== '/' || *fp
== '\\')
1657 if (elem
&& elem
!= fp
)
1659 *fp
= 0; /* temporary end of string */
1660 _mbslwr (elem
); /* while we convert to lower case */
1662 *fp
= sep
; /* convert (or restore) path separator */
1663 elem
= fp
+ 1; /* next element starts after separator */
1671 fp
= CharNextExA (file_name_codepage
, fp
, 0);
1676 /* Destructively turn backslashes into slashes. MULTIBYTE non-zero
1677 means the file name is a multibyte string in Emacs's internal
1680 dostounix_filename (register char *p
, int multibyte
)
1682 normalize_filename (p
, '/', multibyte
);
1685 /* Destructively turn slashes into backslashes. */
1687 unixtodos_filename (register char *p
)
1689 normalize_filename (p
, '\\', 0);
1692 /* Remove all CR's that are followed by a LF.
1693 (From msdos.c...probably should figure out a way to share it,
1694 although this code isn't going to ever change.) */
1696 crlf_to_lf (register int n
, register unsigned char *buf
)
1698 unsigned char *np
= buf
;
1699 unsigned char *startp
= buf
;
1700 unsigned char *endp
= buf
+ n
;
1704 while (buf
< endp
- 1)
1708 if (*(++buf
) != 0x0a)
1719 /* Parse the root part of file name, if present. Return length and
1720 optionally store pointer to char after root. */
1722 parse_root (char * name
, char ** pPath
)
1724 char * start
= name
;
1729 /* find the root name of the volume if given */
1730 if (isalpha (name
[0]) && name
[1] == ':')
1732 /* skip past drive specifier */
1734 if (IS_DIRECTORY_SEP (name
[0]))
1737 else if (IS_DIRECTORY_SEP (name
[0]) && IS_DIRECTORY_SEP (name
[1]))
1740 int dbcs_p
= max_filename_mbslen () > 1;
1745 if (IS_DIRECTORY_SEP (*name
) && --slashes
== 0)
1748 name
= CharNextExA (file_name_codepage
, name
, 0);
1753 if (IS_DIRECTORY_SEP (name
[0]))
1760 return name
- start
;
1763 /* Get long base name for name; name is assumed to be absolute. */
1765 get_long_basename (char * name
, char * buf
, int size
)
1767 WIN32_FIND_DATA find_data
;
1771 /* must be valid filename, no wild cards or other invalid characters */
1772 if (_mbspbrk (name
, "*?|<>\""))
1775 dir_handle
= FindFirstFile (name
, &find_data
);
1776 if (dir_handle
!= INVALID_HANDLE_VALUE
)
1778 if ((len
= strlen (find_data
.cFileName
)) < size
)
1779 memcpy (buf
, find_data
.cFileName
, len
+ 1);
1782 FindClose (dir_handle
);
1787 /* Get long name for file, if possible (assumed to be absolute). */
1789 w32_get_long_filename (char * name
, char * buf
, int size
)
1794 char full
[ MAX_PATH
];
1797 len
= strlen (name
);
1798 if (len
>= MAX_PATH
)
1801 /* Use local copy for destructive modification. */
1802 memcpy (full
, name
, len
+1);
1803 unixtodos_filename (full
);
1805 /* Copy root part verbatim. */
1806 len
= parse_root (full
, &p
);
1807 memcpy (o
, full
, len
);
1812 while (p
!= NULL
&& *p
)
1815 p
= _mbschr (q
, '\\');
1817 len
= get_long_basename (full
, o
, size
);
1840 is_unc_volume (const char *filename
)
1842 const char *ptr
= filename
;
1844 if (!IS_DIRECTORY_SEP (ptr
[0]) || !IS_DIRECTORY_SEP (ptr
[1]) || !ptr
[2])
1847 if (_mbspbrk (ptr
+ 2, "*?|<>\"\\/"))
1853 /* Emulate the Posix unsetenv. */
1855 unsetenv (const char *name
)
1861 if (name
== NULL
|| *name
== '\0' || strchr (name
, '=') != NULL
)
1866 name_len
= strlen (name
);
1867 /* MS docs says an environment variable cannot be longer than 32K. */
1868 if (name_len
> 32767)
1873 /* It is safe to use 'alloca' with 32K size, since the stack is at
1874 least 2MB, and we set it to 8MB in the link command line. */
1875 var
= alloca (name_len
+ 2);
1876 strncpy (var
, name
, name_len
);
1877 var
[name_len
++] = '=';
1878 var
[name_len
] = '\0';
1879 return _putenv (var
);
1882 /* MS _putenv doesn't support removing a variable when the argument
1883 does not include the '=' character, so we fix that here. */
1885 sys_putenv (char *str
)
1887 const char *const name_end
= strchr (str
, '=');
1889 if (name_end
== NULL
)
1891 /* Remove the variable from the environment. */
1892 return unsetenv (str
);
1895 return _putenv (str
);
1898 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
1901 w32_get_resource (char *key
, LPDWORD lpdwtype
)
1904 HKEY hrootkey
= NULL
;
1907 /* Check both the current user and the local machine to see if
1908 we have any resources. */
1910 if (RegOpenKeyEx (HKEY_CURRENT_USER
, REG_ROOT
, 0, KEY_READ
, &hrootkey
) == ERROR_SUCCESS
)
1914 if (RegQueryValueEx (hrootkey
, key
, NULL
, NULL
, NULL
, &cbData
) == ERROR_SUCCESS
1915 && (lpvalue
= xmalloc (cbData
)) != NULL
1916 && RegQueryValueEx (hrootkey
, key
, NULL
, lpdwtype
, lpvalue
, &cbData
) == ERROR_SUCCESS
)
1918 RegCloseKey (hrootkey
);
1924 RegCloseKey (hrootkey
);
1927 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE
, REG_ROOT
, 0, KEY_READ
, &hrootkey
) == ERROR_SUCCESS
)
1931 if (RegQueryValueEx (hrootkey
, key
, NULL
, NULL
, NULL
, &cbData
) == ERROR_SUCCESS
1932 && (lpvalue
= xmalloc (cbData
)) != NULL
1933 && RegQueryValueEx (hrootkey
, key
, NULL
, lpdwtype
, lpvalue
, &cbData
) == ERROR_SUCCESS
)
1935 RegCloseKey (hrootkey
);
1941 RegCloseKey (hrootkey
);
1947 char *get_emacs_configuration (void);
1950 init_environment (char ** argv
)
1952 static const char * const tempdirs
[] = {
1953 "$TMPDIR", "$TEMP", "$TMP", "c:/"
1958 const int imax
= sizeof (tempdirs
) / sizeof (tempdirs
[0]);
1960 /* Make sure they have a usable $TMPDIR. Many Emacs functions use
1961 temporary files and assume "/tmp" if $TMPDIR is unset, which
1962 will break on DOS/Windows. Refuse to work if we cannot find
1963 a directory, not even "c:/", usable for that purpose. */
1964 for (i
= 0; i
< imax
; i
++)
1966 const char *tmp
= tempdirs
[i
];
1969 tmp
= getenv (tmp
+ 1);
1970 /* Note that `access' can lie to us if the directory resides on a
1971 read-only filesystem, like CD-ROM or a write-protected floppy.
1972 The only way to be really sure is to actually create a file and
1973 see if it succeeds. But I think that's too much to ask. */
1975 /* MSVCRT's _access crashes with D_OK. */
1976 if (tmp
&& faccessat (AT_FDCWD
, tmp
, D_OK
, AT_EACCESS
) == 0)
1978 char * var
= alloca (strlen (tmp
) + 8);
1979 sprintf (var
, "TMPDIR=%s", tmp
);
1980 _putenv (strdup (var
));
1987 Fcons (build_string ("no usable temporary directories found!!"),
1989 "While setting TMPDIR: ");
1991 /* Check for environment variables and use registry settings if they
1992 don't exist. Fallback on default values where applicable. */
1997 char locale_name
[32];
1998 char default_home
[MAX_PATH
];
2001 static const struct env_entry
2007 /* If the default value is NULL, we will use the value from the
2008 outside environment or the Registry, but will not push the
2009 variable into the Emacs environment if it is defined neither
2010 in the Registry nor in the outside environment. */
2012 {"PRELOAD_WINSOCK", NULL
},
2013 {"emacs_dir", "C:/emacs"},
2014 {"EMACSLOADPATH", NULL
},
2015 {"SHELL", "%emacs_dir%/bin/cmdproxy.exe"},
2016 {"EMACSDATA", NULL
},
2017 {"EMACSPATH", NULL
},
2024 #define N_ENV_VARS sizeof (dflt_envvars)/sizeof (dflt_envvars[0])
2026 /* We need to copy dflt_envvars[] and work on the copy because we
2027 don't want the dumped Emacs to inherit the values of
2028 environment variables we saw during dumping (which could be on
2029 a different system). The defaults above must be left intact. */
2030 struct env_entry env_vars
[N_ENV_VARS
];
2032 for (i
= 0; i
< N_ENV_VARS
; i
++)
2033 env_vars
[i
] = dflt_envvars
[i
];
2035 /* For backwards compatibility, check if a .emacs file exists in C:/
2036 If not, then we can try to default to the appdata directory under the
2037 user's profile, which is more likely to be writable. */
2038 if (!check_existing ("C:/.emacs"))
2040 HRESULT profile_result
;
2041 /* Dynamically load ShGetFolderPath, as it won't exist on versions
2042 of Windows 95 and NT4 that have not been updated to include
2044 ShGetFolderPath_fn get_folder_path
;
2045 get_folder_path
= (ShGetFolderPath_fn
)
2046 GetProcAddress (GetModuleHandle ("shell32.dll"), "SHGetFolderPathA");
2048 if (get_folder_path
!= NULL
)
2050 profile_result
= get_folder_path (NULL
, CSIDL_APPDATA
, NULL
,
2053 /* If we can't get the appdata dir, revert to old behavior. */
2054 if (profile_result
== S_OK
)
2056 env_vars
[0].def_value
= default_home
;
2062 /* Get default locale info and use it for LANG. */
2063 if (GetLocaleInfo (LOCALE_USER_DEFAULT
,
2064 LOCALE_SABBREVLANGNAME
| LOCALE_USE_CP_ACP
,
2065 locale_name
, sizeof (locale_name
)))
2067 for (i
= 0; i
< N_ENV_VARS
; i
++)
2069 if (strcmp (env_vars
[i
].name
, "LANG") == 0)
2071 env_vars
[i
].def_value
= locale_name
;
2077 #define SET_ENV_BUF_SIZE (4 * MAX_PATH) /* to cover EMACSLOADPATH */
2079 /* Treat emacs_dir specially: set it unconditionally based on our
2083 char modname
[MAX_PATH
];
2085 if (!GetModuleFileName (NULL
, modname
, MAX_PATH
))
2087 if ((p
= _mbsrchr (modname
, '\\')) == NULL
)
2091 if ((p
= _mbsrchr (modname
, '\\')) && xstrcasecmp (p
, "\\bin") == 0)
2093 char buf
[SET_ENV_BUF_SIZE
];
2096 for (p
= modname
; *p
; p
= CharNext (p
))
2097 if (*p
== '\\') *p
= '/';
2099 _snprintf (buf
, sizeof (buf
)-1, "emacs_dir=%s", modname
);
2100 _putenv (strdup (buf
));
2102 /* Handle running emacs from the build directory: src/oo-spd/i386/ */
2104 /* FIXME: should use substring of get_emacs_configuration ().
2105 But I don't think the Windows build supports alpha, mips etc
2106 anymore, so have taken the easy option for now. */
2107 else if (p
&& (xstrcasecmp (p
, "\\i386") == 0
2108 || xstrcasecmp (p
, "\\AMD64") == 0))
2111 p
= _mbsrchr (modname
, '\\');
2115 p
= _mbsrchr (modname
, '\\');
2116 if (p
&& xstrcasecmp (p
, "\\src") == 0)
2118 char buf
[SET_ENV_BUF_SIZE
];
2121 for (p
= modname
; *p
; p
= CharNext (p
))
2122 if (*p
== '\\') *p
= '/';
2124 _snprintf (buf
, sizeof (buf
)-1, "emacs_dir=%s", modname
);
2125 _putenv (strdup (buf
));
2131 for (i
= 0; i
< N_ENV_VARS
; i
++)
2133 if (!getenv (env_vars
[i
].name
))
2137 if ((lpval
= w32_get_resource (env_vars
[i
].name
, &dwType
)) == NULL
2138 /* Also ignore empty environment variables. */
2142 lpval
= env_vars
[i
].def_value
;
2143 dwType
= REG_EXPAND_SZ
;
2145 if (!strcmp (env_vars
[i
].name
, "HOME") && !appdata
)
2146 Vdelayed_warnings_list
2147 = Fcons (listn (CONSTYPE_HEAP
, 2,
2148 intern ("initialization"),
2149 build_string ("Setting HOME to C:\\ by default is deprecated")),
2150 Vdelayed_warnings_list
);
2155 char buf1
[SET_ENV_BUF_SIZE
], buf2
[SET_ENV_BUF_SIZE
];
2157 if (dwType
== REG_EXPAND_SZ
)
2158 ExpandEnvironmentStrings ((LPSTR
) lpval
, buf1
, sizeof (buf1
));
2159 else if (dwType
== REG_SZ
)
2160 strcpy (buf1
, lpval
);
2161 if (dwType
== REG_EXPAND_SZ
|| dwType
== REG_SZ
)
2163 _snprintf (buf2
, sizeof (buf2
)-1, "%s=%s", env_vars
[i
].name
,
2165 _putenv (strdup (buf2
));
2175 /* Rebuild system configuration to reflect invoking system. */
2176 Vsystem_configuration
= build_string (EMACS_CONFIGURATION
);
2178 /* Another special case: on NT, the PATH variable is actually named
2179 "Path" although cmd.exe (perhaps NT itself) arranges for
2180 environment variable lookup and setting to be case insensitive.
2181 However, Emacs assumes a fully case sensitive environment, so we
2182 need to change "Path" to "PATH" to match the expectations of
2183 various elisp packages. We do this by the sneaky method of
2184 modifying the string in the C runtime environ entry.
2186 The same applies to COMSPEC. */
2190 for (envp
= environ
; *envp
; envp
++)
2191 if (_strnicmp (*envp
, "PATH=", 5) == 0)
2192 memcpy (*envp
, "PATH=", 5);
2193 else if (_strnicmp (*envp
, "COMSPEC=", 8) == 0)
2194 memcpy (*envp
, "COMSPEC=", 8);
2197 /* Remember the initial working directory for getcwd. */
2198 /* FIXME: Do we need to resolve possible symlinks in startup_dir?
2199 Does it matter anywhere in Emacs? */
2200 if (!GetCurrentDirectory (MAXPATHLEN
, startup_dir
))
2204 static char modname
[MAX_PATH
];
2206 if (!GetModuleFileName (NULL
, modname
, MAX_PATH
))
2211 /* Determine if there is a middle mouse button, to allow parse_button
2212 to decide whether right mouse events should be mouse-2 or
2214 w32_num_mouse_buttons
= GetSystemMetrics (SM_CMOUSEBUTTONS
);
2219 /* Called from expand-file-name when default-directory is not a string. */
2222 emacs_root_dir (void)
2224 static char root_dir
[FILENAME_MAX
];
2227 p
= getenv ("emacs_dir");
2230 strcpy (root_dir
, p
);
2231 root_dir
[parse_root (root_dir
, NULL
)] = '\0';
2232 dostounix_filename (root_dir
, 0);
2236 /* We don't have scripts to automatically determine the system configuration
2237 for Emacs before it's compiled, and we don't want to have to make the
2238 user enter it, so we define EMACS_CONFIGURATION to invoke this runtime
2242 get_emacs_configuration (void)
2244 char *arch
, *oem
, *os
;
2246 static char configuration_buffer
[32];
2248 /* Determine the processor type. */
2249 switch (get_processor_type ())
2252 #ifdef PROCESSOR_INTEL_386
2253 case PROCESSOR_INTEL_386
:
2254 case PROCESSOR_INTEL_486
:
2255 case PROCESSOR_INTEL_PENTIUM
:
2263 #ifdef PROCESSOR_AMD_X8664
2264 case PROCESSOR_AMD_X8664
:
2269 #ifdef PROCESSOR_MIPS_R2000
2270 case PROCESSOR_MIPS_R2000
:
2271 case PROCESSOR_MIPS_R3000
:
2272 case PROCESSOR_MIPS_R4000
:
2277 #ifdef PROCESSOR_ALPHA_21064
2278 case PROCESSOR_ALPHA_21064
:
2288 /* Use the OEM field to reflect the compiler/library combination. */
2290 #define COMPILER_NAME "msvc"
2293 #define COMPILER_NAME "mingw"
2295 #define COMPILER_NAME "unknown"
2298 oem
= COMPILER_NAME
;
2300 switch (osinfo_cache
.dwPlatformId
) {
2301 case VER_PLATFORM_WIN32_NT
:
2303 build_num
= osinfo_cache
.dwBuildNumber
;
2305 case VER_PLATFORM_WIN32_WINDOWS
:
2306 if (osinfo_cache
.dwMinorVersion
== 0) {
2311 build_num
= LOWORD (osinfo_cache
.dwBuildNumber
);
2313 case VER_PLATFORM_WIN32s
:
2314 /* Not supported, should not happen. */
2316 build_num
= LOWORD (osinfo_cache
.dwBuildNumber
);
2324 if (osinfo_cache
.dwPlatformId
== VER_PLATFORM_WIN32_NT
) {
2325 sprintf (configuration_buffer
, "%s-%s-%s%d.%d.%d", arch
, oem
, os
,
2326 get_w32_major_version (), get_w32_minor_version (), build_num
);
2328 sprintf (configuration_buffer
, "%s-%s-%s.%d", arch
, oem
, os
, build_num
);
2331 return configuration_buffer
;
2335 get_emacs_configuration_options (void)
2337 static char *options_buffer
;
2338 char cv
[32]; /* Enough for COMPILER_VERSION. */
2340 cv
, /* To be filled later. */
2344 #ifdef ENABLE_CHECKING
2345 " --enable-checking",
2347 /* configure.bat already sets USER_CFLAGS and USER_LDFLAGS
2348 with a starting space to save work here. */
2350 " --cflags", USER_CFLAGS
,
2353 " --ldflags", USER_LDFLAGS
,
2360 /* Work out the effective configure options for this build. */
2362 #define COMPILER_VERSION "--with-msvc (%d.%02d)", _MSC_VER / 100, _MSC_VER % 100
2365 #define COMPILER_VERSION "--with-gcc (%d.%d)", __GNUC__, __GNUC_MINOR__
2367 #define COMPILER_VERSION ""
2371 if (_snprintf (cv
, sizeof (cv
) - 1, COMPILER_VERSION
) < 0)
2372 return "Error: not enough space for compiler version";
2373 cv
[sizeof (cv
) - 1] = '\0';
2375 for (i
= 0; options
[i
]; i
++)
2376 size
+= strlen (options
[i
]);
2378 options_buffer
= xmalloc (size
+ 1);
2379 options_buffer
[0] = '\0';
2381 for (i
= 0; options
[i
]; i
++)
2382 strcat (options_buffer
, options
[i
]);
2384 return options_buffer
;
2388 #include <sys/timeb.h>
2390 /* Emulate gettimeofday (Ulrich Leodolter, 1/11/95). */
2392 gettimeofday (struct timeval
*tv
, struct timezone
*tz
)
2397 tv
->tv_sec
= tb
.time
;
2398 tv
->tv_usec
= tb
.millitm
* 1000L;
2399 /* Implementation note: _ftime sometimes doesn't update the dstflag
2400 according to the new timezone when the system timezone is
2401 changed. We could fix that by using GetSystemTime and
2402 GetTimeZoneInformation, but that doesn't seem necessary, since
2403 Emacs always calls gettimeofday with the 2nd argument NULL (see
2404 current_emacs_time). */
2407 tz
->tz_minuteswest
= tb
.timezone
; /* minutes west of Greenwich */
2408 tz
->tz_dsttime
= tb
.dstflag
; /* type of dst correction */
2412 /* Emulate fdutimens. */
2414 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2415 TIMESPEC[0] and TIMESPEC[1], respectively.
2416 FD must be either negative -- in which case it is ignored --
2417 or a file descriptor that is open on FILE.
2418 If FD is nonnegative, then FILE can be NULL, which means
2419 use just futimes instead of utimes.
2420 If TIMESPEC is null, FAIL.
2421 Return 0 on success, -1 (setting errno) on failure. */
2424 fdutimens (int fd
, char const *file
, struct timespec
const timespec
[2])
2433 if (fd
< 0 && !file
)
2438 ut
.actime
= timespec
[0].tv_sec
;
2439 ut
.modtime
= timespec
[1].tv_sec
;
2441 return _futime (fd
, &ut
);
2443 return _utime (file
, &ut
);
2447 /* ------------------------------------------------------------------------- */
2448 /* IO support and wrapper functions for the Windows API. */
2449 /* ------------------------------------------------------------------------- */
2451 /* Place a wrapper around the MSVC version of ctime. It returns NULL
2452 on network directories, so we handle that case here.
2453 (Ulrich Leodolter, 1/11/95). */
2455 sys_ctime (const time_t *t
)
2457 char *str
= (char *) ctime (t
);
2458 return (str
? str
: "Sun Jan 01 00:00:00 1970");
2461 /* Emulate sleep...we could have done this with a define, but that
2462 would necessitate including windows.h in the files that used it.
2463 This is much easier. */
2465 sys_sleep (int seconds
)
2467 Sleep (seconds
* 1000);
2470 /* Internal MSVC functions for low-level descriptor munging */
2471 extern int __cdecl
_set_osfhnd (int fd
, long h
);
2472 extern int __cdecl
_free_osfhnd (int fd
);
2474 /* parallel array of private info on file handles */
2475 filedesc fd_info
[ MAXDESC
];
2477 typedef struct volume_info_data
{
2478 struct volume_info_data
* next
;
2480 /* time when info was obtained */
2483 /* actual volume info */
2492 /* Global referenced by various functions. */
2493 static volume_info_data volume_info
;
2495 /* Vector to indicate which drives are local and fixed (for which cached
2496 data never expires). */
2497 static BOOL fixed_drives
[26];
2499 /* Consider cached volume information to be stale if older than 10s,
2500 at least for non-local drives. Info for fixed drives is never stale. */
2501 #define DRIVE_INDEX( c ) ( (c) <= 'Z' ? (c) - 'A' : (c) - 'a' )
2502 #define VOLINFO_STILL_VALID( root_dir, info ) \
2503 ( ( isalpha (root_dir[0]) && \
2504 fixed_drives[ DRIVE_INDEX (root_dir[0]) ] ) \
2505 || GetTickCount () - info->timestamp < 10000 )
2507 /* Cache support functions. */
2509 /* Simple linked list with linear search is sufficient. */
2510 static volume_info_data
*volume_cache
= NULL
;
2512 static volume_info_data
*
2513 lookup_volume_info (char * root_dir
)
2515 volume_info_data
* info
;
2517 for (info
= volume_cache
; info
; info
= info
->next
)
2518 if (xstrcasecmp (info
->root_dir
, root_dir
) == 0)
2524 add_volume_info (char * root_dir
, volume_info_data
* info
)
2526 info
->root_dir
= xstrdup (root_dir
);
2527 info
->next
= volume_cache
;
2528 volume_cache
= info
;
2532 /* Wrapper for GetVolumeInformation, which uses caching to avoid
2533 performance penalty (~2ms on 486 for local drives, 7.5ms for local
2534 cdrom drive, ~5-10ms or more for remote drives on LAN). */
2535 static volume_info_data
*
2536 GetCachedVolumeInformation (char * root_dir
)
2538 volume_info_data
* info
;
2539 char default_root
[ MAX_PATH
];
2541 /* NULL for root_dir means use root from current directory. */
2542 if (root_dir
== NULL
)
2544 if (GetCurrentDirectory (MAX_PATH
, default_root
) == 0)
2546 parse_root (default_root
, &root_dir
);
2548 root_dir
= default_root
;
2551 /* Local fixed drives can be cached permanently. Removable drives
2552 cannot be cached permanently, since the volume name and serial
2553 number (if nothing else) can change. Remote drives should be
2554 treated as if they are removable, since there is no sure way to
2555 tell whether they are or not. Also, the UNC association of drive
2556 letters mapped to remote volumes can be changed at any time (even
2557 by other processes) without notice.
2559 As a compromise, so we can benefit from caching info for remote
2560 volumes, we use a simple expiry mechanism to invalidate cache
2561 entries that are more than ten seconds old. */
2564 /* No point doing this, because WNetGetConnection is even slower than
2565 GetVolumeInformation, consistently taking ~50ms on a 486 (FWIW,
2566 GetDriveType is about the only call of this type which does not
2567 involve network access, and so is extremely quick). */
2569 /* Map drive letter to UNC if remote. */
2570 if (isalpha (root_dir
[0]) && !fixed
[DRIVE_INDEX (root_dir
[0])])
2572 char remote_name
[ 256 ];
2573 char drive
[3] = { root_dir
[0], ':' };
2575 if (WNetGetConnection (drive
, remote_name
, sizeof (remote_name
))
2577 /* do something */ ;
2581 info
= lookup_volume_info (root_dir
);
2583 if (info
== NULL
|| ! VOLINFO_STILL_VALID (root_dir
, info
))
2591 /* Info is not cached, or is stale. */
2592 if (!GetVolumeInformation (root_dir
,
2593 name
, sizeof (name
),
2597 type
, sizeof (type
)))
2600 /* Cache the volume information for future use, overwriting existing
2601 entry if present. */
2604 info
= xmalloc (sizeof (volume_info_data
));
2605 add_volume_info (root_dir
, info
);
2613 info
->name
= xstrdup (name
);
2614 info
->serialnum
= serialnum
;
2615 info
->maxcomp
= maxcomp
;
2616 info
->flags
= flags
;
2617 info
->type
= xstrdup (type
);
2618 info
->timestamp
= GetTickCount ();
2624 /* Get information on the volume where NAME is held; set path pointer to
2625 start of pathname in NAME (past UNC header\volume header if present),
2626 if pPath is non-NULL.
2628 Note: if NAME includes symlinks, the information is for the volume
2629 of the symlink, not of its target. That's because, even though
2630 GetVolumeInformation returns information about the symlink target
2631 of its argument, we only pass the root directory to
2632 GetVolumeInformation, not the full NAME. */
2634 get_volume_info (const char * name
, const char ** pPath
)
2636 char temp
[MAX_PATH
];
2637 char *rootname
= NULL
; /* default to current volume */
2638 volume_info_data
* info
;
2643 /* Find the root name of the volume if given. */
2644 if (isalpha (name
[0]) && name
[1] == ':')
2652 else if (IS_DIRECTORY_SEP (name
[0]) && IS_DIRECTORY_SEP (name
[1]))
2656 int dbcs_p
= max_filename_mbslen () > 1;
2661 if (IS_DIRECTORY_SEP (*name
) && --slashes
== 0)
2667 const char *p
= name
;
2669 name
= CharNextExA (file_name_codepage
, name
, 0);
2670 memcpy (str
, p
, name
- p
);
2683 info
= GetCachedVolumeInformation (rootname
);
2686 /* Set global referenced by other functions. */
2687 volume_info
= *info
;
2693 /* Determine if volume is FAT format (ie. only supports short 8.3
2694 names); also set path pointer to start of pathname in name, if
2695 pPath is non-NULL. */
2697 is_fat_volume (const char * name
, const char ** pPath
)
2699 if (get_volume_info (name
, pPath
))
2700 return (volume_info
.maxcomp
== 12);
2704 /* Map filename to a valid 8.3 name if necessary.
2705 The result is a pointer to a static buffer, so CAVEAT EMPTOR! */
2707 map_w32_filename (const char * name
, const char ** pPath
)
2709 static char shortname
[MAX_PATH
];
2710 char * str
= shortname
;
2713 const char * save_name
= name
;
2715 if (strlen (name
) >= MAX_PATH
)
2717 /* Return a filename which will cause callers to fail. */
2718 strcpy (shortname
, "?");
2722 if (is_fat_volume (name
, (const char **)&path
)) /* truncate to 8.3 */
2724 register int left
= 8; /* maximum number of chars in part */
2725 register int extn
= 0; /* extension added? */
2726 register int dots
= 2; /* maximum number of dots allowed */
2729 *str
++ = *name
++; /* skip past UNC header */
2731 while ((c
= *name
++))
2738 *str
++ = (c
== ':' ? ':' : '\\');
2739 extn
= 0; /* reset extension flags */
2740 dots
= 2; /* max 2 dots */
2741 left
= 8; /* max length 8 for main part */
2746 /* Convert path components of the form .xxx to _xxx,
2747 but leave . and .. as they are. This allows .emacs
2748 to be read as _emacs, for example. */
2752 IS_DIRECTORY_SEP (*name
))
2767 extn
= 1; /* we've got an extension */
2768 left
= 3; /* 3 chars in extension */
2772 /* any embedded dots after the first are converted to _ */
2777 case '#': /* don't lose these, they're important */
2779 str
[-1] = c
; /* replace last character of part */
2784 *str
++ = tolower (c
); /* map to lower case (looks nicer) */
2786 dots
= 0; /* started a path component */
2795 strcpy (shortname
, name
);
2796 unixtodos_filename (shortname
);
2800 *pPath
= shortname
+ (path
- save_name
);
2806 is_exec (const char * name
)
2808 char * p
= strrchr (name
, '.');
2811 && (xstrcasecmp (p
, ".exe") == 0 ||
2812 xstrcasecmp (p
, ".com") == 0 ||
2813 xstrcasecmp (p
, ".bat") == 0 ||
2814 xstrcasecmp (p
, ".cmd") == 0));
2817 /* Emulate the Unix directory procedures opendir, closedir,
2818 and readdir. We can't use the procedures supplied in sysdep.c,
2819 so we provide them here. */
2821 struct dirent dir_static
; /* simulated directory contents */
2822 static HANDLE dir_find_handle
= INVALID_HANDLE_VALUE
;
2823 static int dir_is_fat
;
2824 static char dir_pathname
[MAXPATHLEN
+1];
2825 static WIN32_FIND_DATA dir_find_data
;
2827 /* Support shares on a network resource as subdirectories of a read-only
2829 static HANDLE wnet_enum_handle
= INVALID_HANDLE_VALUE
;
2830 static HANDLE
open_unc_volume (const char *);
2831 static char *read_unc_volume (HANDLE
, char *, int);
2832 static void close_unc_volume (HANDLE
);
2835 opendir (const char *filename
)
2839 /* Opening is done by FindFirstFile. However, a read is inherent to
2840 this operation, so we defer the open until read time. */
2842 if (dir_find_handle
!= INVALID_HANDLE_VALUE
)
2844 if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
2847 /* Note: We don't support traversal of UNC volumes via symlinks.
2848 Doing so would mean punishing 99.99% of use cases by resolving
2849 all the possible symlinks in FILENAME, recursively. */
2850 if (is_unc_volume (filename
))
2852 wnet_enum_handle
= open_unc_volume (filename
);
2853 if (wnet_enum_handle
== INVALID_HANDLE_VALUE
)
2857 if (!(dirp
= (DIR *) malloc (sizeof (DIR))))
2864 strncpy (dir_pathname
, map_w32_filename (filename
, NULL
), MAXPATHLEN
);
2865 dir_pathname
[MAXPATHLEN
] = '\0';
2866 /* Note: We don't support symlinks to file names on FAT volumes.
2867 Doing so would mean punishing 99.99% of use cases by resolving
2868 all the possible symlinks in FILENAME, recursively. */
2869 dir_is_fat
= is_fat_volume (filename
, NULL
);
2875 closedir (DIR *dirp
)
2877 /* If we have a find-handle open, close it. */
2878 if (dir_find_handle
!= INVALID_HANDLE_VALUE
)
2880 FindClose (dir_find_handle
);
2881 dir_find_handle
= INVALID_HANDLE_VALUE
;
2883 else if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
2885 close_unc_volume (wnet_enum_handle
);
2886 wnet_enum_handle
= INVALID_HANDLE_VALUE
;
2888 xfree ((char *) dirp
);
2894 int downcase
= !NILP (Vw32_downcase_file_names
);
2896 if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
2898 if (!read_unc_volume (wnet_enum_handle
,
2899 dir_find_data
.cFileName
,
2903 /* If we aren't dir_finding, do a find-first, otherwise do a find-next. */
2904 else if (dir_find_handle
== INVALID_HANDLE_VALUE
)
2906 char filename
[MAXNAMLEN
+ 3];
2908 int dbcs_p
= max_filename_mbslen () > 1;
2910 strcpy (filename
, dir_pathname
);
2911 ln
= strlen (filename
) - 1;
2914 if (!IS_DIRECTORY_SEP (filename
[ln
]))
2915 strcat (filename
, "\\");
2919 char *end
= filename
+ ln
+ 1;
2920 char *last_char
= CharPrevExA (file_name_codepage
, filename
, end
, 0);
2922 if (!IS_DIRECTORY_SEP (*last_char
))
2923 strcat (filename
, "\\");
2925 strcat (filename
, "*");
2927 /* Note: No need to resolve symlinks in FILENAME, because
2928 FindFirst opens the directory that is the target of a
2930 dir_find_handle
= FindFirstFile (filename
, &dir_find_data
);
2932 if (dir_find_handle
== INVALID_HANDLE_VALUE
)
2937 if (!FindNextFile (dir_find_handle
, &dir_find_data
))
2941 /* Emacs never uses this value, so don't bother making it match
2942 value returned by stat(). */
2943 dir_static
.d_ino
= 1;
2945 strcpy (dir_static
.d_name
, dir_find_data
.cFileName
);
2947 /* If the file name in cFileName[] includes `?' characters, it means
2948 the original file name used characters that cannot be represented
2949 by the current ANSI codepage. To avoid total lossage, retrieve
2950 the short 8+3 alias of the long file name. */
2951 if (_mbspbrk (dir_static
.d_name
, "?"))
2953 strcpy (dir_static
.d_name
, dir_find_data
.cAlternateFileName
);
2954 downcase
= 1; /* 8+3 aliases are returned in all caps */
2956 dir_static
.d_namlen
= strlen (dir_static
.d_name
);
2957 dir_static
.d_reclen
= sizeof (struct dirent
) - MAXNAMLEN
+ 3 +
2958 dir_static
.d_namlen
- dir_static
.d_namlen
% 4;
2960 /* If the file name in cFileName[] includes `?' characters, it means
2961 the original file name used characters that cannot be represented
2962 by the current ANSI codepage. To avoid total lossage, retrieve
2963 the short 8+3 alias of the long file name. */
2964 if (_mbspbrk (dir_find_data
.cFileName
, "?"))
2966 strcpy (dir_static
.d_name
, dir_find_data
.cAlternateFileName
);
2967 /* 8+3 aliases are returned in all caps, which could break
2968 various alists that look at filenames' extensions. */
2972 strcpy (dir_static
.d_name
, dir_find_data
.cFileName
);
2973 dir_static
.d_namlen
= strlen (dir_static
.d_name
);
2975 _mbslwr (dir_static
.d_name
);
2979 int dbcs_p
= max_filename_mbslen () > 1;
2980 for (p
= dir_static
.d_name
; *p
; )
2982 if (*p
>= 'a' && *p
<= 'z')
2985 p
= CharNextExA (file_name_codepage
, p
, 0);
2990 _mbslwr (dir_static
.d_name
);
2997 open_unc_volume (const char *path
)
3003 nr
.dwScope
= RESOURCE_GLOBALNET
;
3004 nr
.dwType
= RESOURCETYPE_DISK
;
3005 nr
.dwDisplayType
= RESOURCEDISPLAYTYPE_SERVER
;
3006 nr
.dwUsage
= RESOURCEUSAGE_CONTAINER
;
3007 nr
.lpLocalName
= NULL
;
3008 nr
.lpRemoteName
= (LPSTR
)map_w32_filename (path
, NULL
);
3009 nr
.lpComment
= NULL
;
3010 nr
.lpProvider
= NULL
;
3012 result
= WNetOpenEnum (RESOURCE_GLOBALNET
, RESOURCETYPE_DISK
,
3013 RESOURCEUSAGE_CONNECTABLE
, &nr
, &henum
);
3015 if (result
== NO_ERROR
)
3018 return INVALID_HANDLE_VALUE
;
3022 read_unc_volume (HANDLE henum
, char *readbuf
, int size
)
3026 DWORD bufsize
= 512;
3029 int dbcs_p
= max_filename_mbslen () > 1;
3032 buffer
= alloca (bufsize
);
3033 result
= WNetEnumResource (henum
, &count
, buffer
, &bufsize
);
3034 if (result
!= NO_ERROR
)
3037 /* WNetEnumResource returns \\resource\share...skip forward to "share". */
3038 ptr
= ((LPNETRESOURCE
) buffer
)->lpRemoteName
;
3041 while (*ptr
&& !IS_DIRECTORY_SEP (*ptr
)) ptr
++;
3044 while (*ptr
&& !IS_DIRECTORY_SEP (*ptr
))
3045 ptr
= CharNextExA (file_name_codepage
, ptr
, 0);
3049 strncpy (readbuf
, ptr
, size
);
3054 close_unc_volume (HANDLE henum
)
3056 if (henum
!= INVALID_HANDLE_VALUE
)
3057 WNetCloseEnum (henum
);
3061 unc_volume_file_attributes (const char *path
)
3066 henum
= open_unc_volume (path
);
3067 if (henum
== INVALID_HANDLE_VALUE
)
3070 attrs
= FILE_ATTRIBUTE_READONLY
| FILE_ATTRIBUTE_DIRECTORY
;
3072 close_unc_volume (henum
);
3077 /* Ensure a network connection is authenticated. */
3079 logon_network_drive (const char *path
)
3081 NETRESOURCE resource
;
3082 char share
[MAX_PATH
];
3089 if (IS_DIRECTORY_SEP (path
[0]) && IS_DIRECTORY_SEP (path
[1]))
3090 drvtype
= DRIVE_REMOTE
;
3091 else if (path
[0] == '\0' || path
[1] != ':')
3092 drvtype
= GetDriveType (NULL
);
3099 drvtype
= GetDriveType (drive
);
3102 /* Only logon to networked drives. */
3103 if (drvtype
!= DRIVE_REMOTE
)
3107 strncpy (share
, path
, MAX_PATH
);
3108 /* Truncate to just server and share name. */
3109 dbcs_p
= max_filename_mbslen () > 1;
3110 for (p
= share
+ 2; *p
&& p
< share
+ MAX_PATH
; )
3112 if (IS_DIRECTORY_SEP (*p
) && ++n_slashes
> 3)
3118 p
= CharNextExA (file_name_codepage
, p
, 0);
3123 resource
.dwType
= RESOURCETYPE_DISK
;
3124 resource
.lpLocalName
= NULL
;
3125 resource
.lpRemoteName
= share
;
3126 resource
.lpProvider
= NULL
;
3128 WNetAddConnection2 (&resource
, NULL
, NULL
, CONNECT_INTERACTIVE
);
3131 /* Emulate faccessat(2). */
3133 faccessat (int dirfd
, const char * path
, int mode
, int flags
)
3137 if (dirfd
!= AT_FDCWD
3138 && !(IS_DIRECTORY_SEP (path
[0])
3139 || IS_DEVICE_SEP (path
[1])))
3145 /* MSVCRT implementation of 'access' doesn't recognize D_OK, and its
3146 newer versions blow up when passed D_OK. */
3147 path
= map_w32_filename (path
, NULL
);
3148 /* If the last element of PATH is a symlink, we need to resolve it
3149 to get the attributes of its target file. Note: any symlinks in
3150 PATH elements other than the last one are transparently resolved
3151 by GetFileAttributes below. */
3152 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) != 0
3153 && (flags
& AT_SYMLINK_NOFOLLOW
) == 0)
3154 path
= chase_symlinks (path
);
3156 if ((attributes
= GetFileAttributes (path
)) == -1)
3158 DWORD w32err
= GetLastError ();
3162 case ERROR_INVALID_NAME
:
3163 case ERROR_BAD_PATHNAME
:
3164 if (is_unc_volume (path
))
3166 attributes
= unc_volume_file_attributes (path
);
3167 if (attributes
== -1)
3175 case ERROR_FILE_NOT_FOUND
:
3176 case ERROR_BAD_NETPATH
:
3185 if ((mode
& X_OK
) != 0
3186 && !(is_exec (path
) || (attributes
& FILE_ATTRIBUTE_DIRECTORY
) != 0))
3191 if ((mode
& W_OK
) != 0 && (attributes
& FILE_ATTRIBUTE_READONLY
) != 0)
3196 if ((mode
& D_OK
) != 0 && (attributes
& FILE_ATTRIBUTE_DIRECTORY
) == 0)
3204 /* Shadow some MSVC runtime functions to map requests for long filenames
3205 to reasonable short names if necessary. This was originally added to
3206 permit running Emacs on NT 3.1 on a FAT partition, which doesn't support
3210 sys_chdir (const char * path
)
3212 return _chdir (map_w32_filename (path
, NULL
));
3216 sys_chmod (const char * path
, int mode
)
3218 path
= chase_symlinks (map_w32_filename (path
, NULL
));
3219 return _chmod (path
, mode
);
3223 sys_creat (const char * path
, int mode
)
3225 return _creat (map_w32_filename (path
, NULL
), mode
);
3229 sys_fopen (const char * path
, const char * mode
)
3233 const char * mode_save
= mode
;
3235 /* Force all file handles to be non-inheritable. This is necessary to
3236 ensure child processes don't unwittingly inherit handles that might
3237 prevent future file access. */
3241 else if (mode
[0] == 'w' || mode
[0] == 'a')
3242 oflag
= O_WRONLY
| O_CREAT
| O_TRUNC
;
3246 /* Only do simplistic option parsing. */
3250 oflag
&= ~(O_RDONLY
| O_WRONLY
);
3253 else if (mode
[0] == 'b')
3258 else if (mode
[0] == 't')
3265 fd
= _open (map_w32_filename (path
, NULL
), oflag
| _O_NOINHERIT
, 0644);
3269 return _fdopen (fd
, mode_save
);
3272 /* This only works on NTFS volumes, but is useful to have. */
3274 sys_link (const char * old
, const char * new)
3278 char oldname
[MAX_PATH
], newname
[MAX_PATH
];
3280 if (old
== NULL
|| new == NULL
)
3286 strcpy (oldname
, map_w32_filename (old
, NULL
));
3287 strcpy (newname
, map_w32_filename (new, NULL
));
3289 fileh
= CreateFile (oldname
, 0, 0, NULL
, OPEN_EXISTING
,
3290 FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
3291 if (fileh
!= INVALID_HANDLE_VALUE
)
3295 /* Confusingly, the "alternate" stream name field does not apply
3296 when restoring a hard link, and instead contains the actual
3297 stream data for the link (ie. the name of the link to create).
3298 The WIN32_STREAM_ID structure before the cStreamName field is
3299 the stream header, which is then immediately followed by the
3303 WIN32_STREAM_ID wid
;
3304 WCHAR wbuffer
[MAX_PATH
]; /* extra space for link name */
3307 wlen
= MultiByteToWideChar (CP_ACP
, MB_PRECOMPOSED
, newname
, -1,
3308 data
.wid
.cStreamName
, MAX_PATH
);
3311 LPVOID context
= NULL
;
3314 data
.wid
.dwStreamId
= BACKUP_LINK
;
3315 data
.wid
.dwStreamAttributes
= 0;
3316 data
.wid
.Size
.LowPart
= wlen
* sizeof (WCHAR
);
3317 data
.wid
.Size
.HighPart
= 0;
3318 data
.wid
.dwStreamNameSize
= 0;
3320 if (BackupWrite (fileh
, (LPBYTE
)&data
,
3321 offsetof (WIN32_STREAM_ID
, cStreamName
)
3322 + data
.wid
.Size
.LowPart
,
3323 &wbytes
, FALSE
, FALSE
, &context
)
3324 && BackupWrite (fileh
, NULL
, 0, &wbytes
, TRUE
, FALSE
, &context
))
3331 /* Should try mapping GetLastError to errno; for now just
3332 indicate a general error (eg. links not supported). */
3333 errno
= EINVAL
; // perhaps EMLINK?
3337 CloseHandle (fileh
);
3346 sys_mkdir (const char * path
)
3348 return _mkdir (map_w32_filename (path
, NULL
));
3351 /* Because of long name mapping issues, we need to implement this
3352 ourselves. Also, MSVC's _mktemp returns NULL when it can't generate
3353 a unique name, instead of setting the input template to an empty
3356 Standard algorithm seems to be use pid or tid with a letter on the
3357 front (in place of the 6 X's) and cycle through the letters to find a
3358 unique name. We extend that to allow any reasonable character as the
3359 first of the 6 X's. */
3361 sys_mktemp (char * template)
3365 unsigned uid
= GetCurrentThreadId ();
3366 static char first_char
[] = "abcdefghijklmnopqrstuvwyz0123456789!%-_@#";
3368 if (template == NULL
)
3370 p
= template + strlen (template);
3372 /* replace up to the last 5 X's with uid in decimal */
3373 while (--p
>= template && p
[0] == 'X' && --i
>= 0)
3375 p
[0] = '0' + uid
% 10;
3379 if (i
< 0 && p
[0] == 'X')
3384 int save_errno
= errno
;
3385 p
[0] = first_char
[i
];
3386 if (faccessat (AT_FDCWD
, template, F_OK
, AT_EACCESS
) < 0)
3392 while (++i
< sizeof (first_char
));
3395 /* Template is badly formed or else we can't generate a unique name,
3396 so return empty string */
3402 sys_open (const char * path
, int oflag
, int mode
)
3404 const char* mpath
= map_w32_filename (path
, NULL
);
3407 /* If possible, try to open file without _O_CREAT, to be able to
3408 write to existing hidden and system files. Force all file
3409 handles to be non-inheritable. */
3410 if ((oflag
& (_O_CREAT
| _O_EXCL
)) != (_O_CREAT
| _O_EXCL
))
3411 res
= _open (mpath
, (oflag
& ~_O_CREAT
) | _O_NOINHERIT
, mode
);
3413 res
= _open (mpath
, oflag
| _O_NOINHERIT
, mode
);
3419 sys_rename (const char * oldname
, const char * newname
)
3422 char temp
[MAX_PATH
];
3426 /* MoveFile on Windows 95 doesn't correctly change the short file name
3427 alias in a number of circumstances (it is not easy to predict when
3428 just by looking at oldname and newname, unfortunately). In these
3429 cases, renaming through a temporary name avoids the problem.
3431 A second problem on Windows 95 is that renaming through a temp name when
3432 newname is uppercase fails (the final long name ends up in
3433 lowercase, although the short alias might be uppercase) UNLESS the
3434 long temp name is not 8.3.
3436 So, on Windows 95 we always rename through a temp name, and we make sure
3437 the temp name has a long extension to ensure correct renaming. */
3439 strcpy (temp
, map_w32_filename (oldname
, NULL
));
3441 /* volume_info is set indirectly by map_w32_filename. */
3442 oldname_dev
= volume_info
.serialnum
;
3444 if (os_subtype
== OS_9X
)
3450 oldname
= map_w32_filename (oldname
, NULL
);
3451 if ((o
= strrchr (oldname
, '\\')))
3454 o
= (char *) oldname
;
3456 if ((p
= strrchr (temp
, '\\')))
3463 /* Force temp name to require a manufactured 8.3 alias - this
3464 seems to make the second rename work properly. */
3465 sprintf (p
, "_.%s.%u", o
, i
);
3467 result
= rename (oldname
, temp
);
3469 /* This loop must surely terminate! */
3470 while (result
< 0 && errno
== EEXIST
);
3475 /* Emulate Unix behavior - newname is deleted if it already exists
3476 (at least if it is a file; don't do this for directories).
3478 Since we mustn't do this if we are just changing the case of the
3479 file name (we would end up deleting the file we are trying to
3480 rename!), we let rename detect if the destination file already
3481 exists - that way we avoid the possible pitfalls of trying to
3482 determine ourselves whether two names really refer to the same
3483 file, which is not always possible in the general case. (Consider
3484 all the permutations of shared or subst'd drives, etc.) */
3486 newname
= map_w32_filename (newname
, NULL
);
3488 /* volume_info is set indirectly by map_w32_filename. */
3489 newname_dev
= volume_info
.serialnum
;
3491 result
= rename (temp
, newname
);
3495 DWORD w32err
= GetLastError ();
3498 && newname_dev
!= oldname_dev
)
3500 /* The implementation of `rename' on Windows does not return
3501 errno = EXDEV when you are moving a directory to a
3502 different storage device (ex. logical disk). It returns
3503 EACCES instead. So here we handle such situations and
3507 if ((attributes
= GetFileAttributes (temp
)) != -1
3508 && (attributes
& FILE_ATTRIBUTE_DIRECTORY
))
3511 else if (errno
== EEXIST
)
3513 if (_chmod (newname
, 0666) != 0)
3515 if (_unlink (newname
) != 0)
3517 result
= rename (temp
, newname
);
3519 else if (w32err
== ERROR_PRIVILEGE_NOT_HELD
3520 && is_symlink (temp
))
3522 /* This is Windows prohibiting the user from creating a
3523 symlink in another place, since that requires
3533 sys_rmdir (const char * path
)
3535 return _rmdir (map_w32_filename (path
, NULL
));
3539 sys_unlink (const char * path
)
3541 path
= map_w32_filename (path
, NULL
);
3543 /* On Unix, unlink works without write permission. */
3544 _chmod (path
, 0666);
3545 return _unlink (path
);
3548 static FILETIME utc_base_ft
;
3549 static ULONGLONG utc_base
; /* In 100ns units */
3550 static int init
= 0;
3552 #define FILETIME_TO_U64(result, ft) \
3554 ULARGE_INTEGER uiTemp; \
3555 uiTemp.LowPart = (ft).dwLowDateTime; \
3556 uiTemp.HighPart = (ft).dwHighDateTime; \
3557 result = uiTemp.QuadPart; \
3561 initialize_utc_base (void)
3563 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
3572 st
.wMilliseconds
= 0;
3574 SystemTimeToFileTime (&st
, &utc_base_ft
);
3575 FILETIME_TO_U64 (utc_base
, utc_base_ft
);
3579 convert_time (FILETIME ft
)
3585 initialize_utc_base ();
3589 if (CompareFileTime (&ft
, &utc_base_ft
) < 0)
3592 FILETIME_TO_U64 (tmp
, ft
);
3593 return (time_t) ((tmp
- utc_base
) / 10000000L);
3597 convert_from_time_t (time_t time
, FILETIME
* pft
)
3603 initialize_utc_base ();
3607 /* time in 100ns units since 1-Jan-1601 */
3608 tmp
.QuadPart
= (ULONGLONG
) time
* 10000000L + utc_base
;
3609 pft
->dwHighDateTime
= tmp
.HighPart
;
3610 pft
->dwLowDateTime
= tmp
.LowPart
;
3614 /* No reason to keep this; faking inode values either by hashing or even
3615 using the file index from GetInformationByHandle, is not perfect and
3616 so by default Emacs doesn't use the inode values on Windows.
3617 Instead, we now determine file-truename correctly (except for
3618 possible drive aliasing etc). */
3620 /* Modified version of "PJW" algorithm (see the "Dragon" compiler book). */
3622 hashval (const unsigned char * str
)
3627 h
= (h
<< 4) + *str
++;
3633 /* Return the hash value of the canonical pathname, excluding the
3634 drive/UNC header, to get a hopefully unique inode number. */
3636 generate_inode_val (const char * name
)
3638 char fullname
[ MAX_PATH
];
3642 /* Get the truly canonical filename, if it exists. (Note: this
3643 doesn't resolve aliasing due to subst commands, or recognize hard
3645 if (!w32_get_long_filename ((char *)name
, fullname
, MAX_PATH
))
3648 parse_root (fullname
, &p
);
3649 /* Normal W32 filesystems are still case insensitive. */
3656 static PSECURITY_DESCRIPTOR
3657 get_file_security_desc_by_handle (HANDLE h
)
3659 PSECURITY_DESCRIPTOR psd
= NULL
;
3661 SECURITY_INFORMATION si
= OWNER_SECURITY_INFORMATION
3662 | GROUP_SECURITY_INFORMATION
/* | DACL_SECURITY_INFORMATION */ ;
3664 err
= get_security_info (h
, SE_FILE_OBJECT
, si
,
3665 NULL
, NULL
, NULL
, NULL
, &psd
);
3666 if (err
!= ERROR_SUCCESS
)
3672 static PSECURITY_DESCRIPTOR
3673 get_file_security_desc_by_name (const char *fname
)
3675 PSECURITY_DESCRIPTOR psd
= NULL
;
3677 SECURITY_INFORMATION si
= OWNER_SECURITY_INFORMATION
3678 | GROUP_SECURITY_INFORMATION
/* | DACL_SECURITY_INFORMATION */ ;
3680 if (!get_file_security (fname
, si
, psd
, 0, &sd_len
))
3682 err
= GetLastError ();
3683 if (err
!= ERROR_INSUFFICIENT_BUFFER
)
3687 psd
= xmalloc (sd_len
);
3688 if (!get_file_security (fname
, si
, psd
, sd_len
, &sd_len
))
3700 unsigned n_subauthorities
;
3702 /* Use the last sub-authority value of the RID, the relative
3703 portion of the SID, as user/group ID. */
3704 n_subauthorities
= *get_sid_sub_authority_count (sid
);
3705 if (n_subauthorities
< 1)
3706 return 0; /* the "World" RID */
3707 return *get_sid_sub_authority (sid
, n_subauthorities
- 1);
3710 /* Caching SID and account values for faster lokup. */
3713 # define FLEXIBLE_ARRAY_MEMBER
3715 # define FLEXIBLE_ARRAY_MEMBER 1
3720 struct w32_id
*next
;
3722 unsigned char sid
[FLEXIBLE_ARRAY_MEMBER
];
3725 static struct w32_id
*w32_idlist
;
3728 w32_cached_id (PSID sid
, unsigned *id
, char *name
)
3730 struct w32_id
*tail
, *found
;
3732 for (found
= NULL
, tail
= w32_idlist
; tail
; tail
= tail
->next
)
3734 if (equal_sid ((PSID
)tail
->sid
, sid
))
3743 strcpy (name
, found
->name
);
3751 w32_add_to_cache (PSID sid
, unsigned id
, char *name
)
3754 struct w32_id
*new_entry
;
3756 /* We don't want to leave behind stale cache from when Emacs was
3760 sid_len
= get_length_sid (sid
);
3761 new_entry
= xmalloc (offsetof (struct w32_id
, sid
) + sid_len
);
3764 new_entry
->rid
= id
;
3765 strcpy (new_entry
->name
, name
);
3766 copy_sid (sid_len
, (PSID
)new_entry
->sid
, sid
);
3767 new_entry
->next
= w32_idlist
;
3768 w32_idlist
= new_entry
;
3777 get_name_and_id (PSECURITY_DESCRIPTOR psd
, unsigned *id
, char *nm
, int what
)
3781 SID_NAME_USE ignore
;
3783 DWORD name_len
= sizeof (name
);
3785 DWORD domain_len
= sizeof (domain
);
3790 result
= get_security_descriptor_owner (psd
, &sid
, &dflt
);
3791 else if (what
== GID
)
3792 result
= get_security_descriptor_group (psd
, &sid
, &dflt
);
3796 if (!result
|| !is_valid_sid (sid
))
3798 else if (!w32_cached_id (sid
, id
, nm
))
3800 if (!lookup_account_sid (NULL
, sid
, name
, &name_len
,
3801 domain
, &domain_len
, &ignore
)
3802 || name_len
> UNLEN
+1)
3806 *id
= get_rid (sid
);
3808 w32_add_to_cache (sid
, *id
, name
);
3815 get_file_owner_and_group (PSECURITY_DESCRIPTOR psd
, struct stat
*st
)
3817 int dflt_usr
= 0, dflt_grp
= 0;
3826 if (get_name_and_id (psd
, &st
->st_uid
, st
->st_uname
, UID
))
3828 if (get_name_and_id (psd
, &st
->st_gid
, st
->st_gname
, GID
))
3831 /* Consider files to belong to current user/group, if we cannot get
3832 more accurate information. */
3835 st
->st_uid
= dflt_passwd
.pw_uid
;
3836 strcpy (st
->st_uname
, dflt_passwd
.pw_name
);
3840 st
->st_gid
= dflt_passwd
.pw_gid
;
3841 strcpy (st
->st_gname
, dflt_group
.gr_name
);
3845 /* Return non-zero if NAME is a potentially slow filesystem. */
3847 is_slow_fs (const char *name
)
3852 if (IS_DIRECTORY_SEP (name
[0]) && IS_DIRECTORY_SEP (name
[1]))
3853 devtype
= DRIVE_REMOTE
; /* assume UNC name is remote */
3854 else if (!(strlen (name
) >= 2 && IS_DEVICE_SEP (name
[1])))
3855 devtype
= GetDriveType (NULL
); /* use root of current drive */
3858 /* GetDriveType needs the root directory of the drive. */
3859 strncpy (drive_root
, name
, 2);
3860 drive_root
[2] = '\\';
3861 drive_root
[3] = '\0';
3862 devtype
= GetDriveType (drive_root
);
3864 return !(devtype
== DRIVE_FIXED
|| devtype
== DRIVE_RAMDISK
);
3867 /* If this is non-zero, the caller wants accurate information about
3868 file's owner and group, which could be expensive to get. */
3869 int w32_stat_get_owner_group
;
3871 /* MSVC stat function can't cope with UNC names and has other bugs, so
3872 replace it with our own. This also allows us to calculate consistent
3873 inode values and owner/group without hacks in the main Emacs code. */
3876 stat_worker (const char * path
, struct stat
* buf
, int follow_symlinks
)
3878 char *name
, *save_name
, *r
;
3879 WIN32_FIND_DATA wfd
;
3881 unsigned __int64 fake_inode
= 0;
3884 int rootdir
= FALSE
;
3885 PSECURITY_DESCRIPTOR psd
= NULL
;
3886 int is_a_symlink
= 0;
3887 DWORD file_flags
= FILE_FLAG_BACKUP_SEMANTICS
;
3888 DWORD access_rights
= 0;
3889 DWORD fattrs
= 0, serialnum
= 0, fs_high
= 0, fs_low
= 0, nlinks
= 1;
3890 FILETIME ctime
, atime
, wtime
;
3893 if (path
== NULL
|| buf
== NULL
)
3899 save_name
= name
= (char *) map_w32_filename (path
, &path
);
3900 /* Must be valid filename, no wild cards or other invalid
3901 characters. We use _mbspbrk to support multibyte strings that
3902 might look to strpbrk as if they included literal *, ?, and other
3903 characters mentioned below that are disallowed by Windows
3905 if (_mbspbrk (name
, "*?|<>\""))
3911 /* Remove trailing directory separator, unless name is the root
3912 directory of a drive or UNC volume in which case ensure there
3913 is a trailing separator. */
3914 len
= strlen (name
);
3915 name
= strcpy (alloca (len
+ 2), name
);
3917 /* Avoid a somewhat costly call to is_symlink if the filesystem
3918 doesn't support symlinks. */
3919 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) != 0)
3920 is_a_symlink
= is_symlink (name
);
3922 /* Plan A: Open the file and get all the necessary information via
3923 the resulting handle. This solves several issues in one blow:
3925 . retrieves attributes for the target of a symlink, if needed
3926 . gets attributes of root directories and symlinks pointing to
3927 root directories, thus avoiding the need for special-casing
3928 these and detecting them by examining the file-name format
3929 . retrieves more accurate attributes (e.g., non-zero size for
3930 some directories, esp. directories that are junction points)
3931 . correctly resolves "c:/..", "/.." and similar file names
3932 . avoids run-time penalties for 99% of use cases
3934 Plan A is always tried first, unless the user asked not to (but
3935 if the file is a symlink and we need to follow links, we try Plan
3936 A even if the user asked not to).
3938 If Plan A fails, we go to Plan B (below), where various
3939 potentially expensive techniques must be used to handle "special"
3940 files such as UNC volumes etc. */
3941 if (!(NILP (Vw32_get_true_file_attributes
)
3942 || (EQ (Vw32_get_true_file_attributes
, Qlocal
) && is_slow_fs (name
)))
3943 /* Following symlinks requires getting the info by handle. */
3944 || (is_a_symlink
&& follow_symlinks
))
3946 BY_HANDLE_FILE_INFORMATION info
;
3948 if (is_a_symlink
&& !follow_symlinks
)
3949 file_flags
|= FILE_FLAG_OPEN_REPARSE_POINT
;
3950 /* READ_CONTROL access rights are required to get security info
3951 by handle. But if the OS doesn't support security in the
3952 first place, we don't need to try. */
3953 if (is_windows_9x () != TRUE
)
3954 access_rights
|= READ_CONTROL
;
3956 fh
= CreateFile (name
, access_rights
, 0, NULL
, OPEN_EXISTING
,
3958 /* If CreateFile fails with READ_CONTROL, try again with zero as
3960 if (fh
== INVALID_HANDLE_VALUE
&& access_rights
)
3961 fh
= CreateFile (name
, 0, 0, NULL
, OPEN_EXISTING
,
3963 if (fh
== INVALID_HANDLE_VALUE
)
3964 goto no_true_file_attributes
;
3966 /* This is more accurate in terms of getting the correct number
3967 of links, but is quite slow (it is noticeable when Emacs is
3968 making a list of file name completions). */
3969 if (GetFileInformationByHandle (fh
, &info
))
3971 nlinks
= info
.nNumberOfLinks
;
3972 /* Might as well use file index to fake inode values, but this
3973 is not guaranteed to be unique unless we keep a handle open
3974 all the time (even then there are situations where it is
3975 not unique). Reputedly, there are at most 48 bits of info
3976 (on NTFS, presumably less on FAT). */
3977 fake_inode
= info
.nFileIndexHigh
;
3979 fake_inode
+= info
.nFileIndexLow
;
3980 serialnum
= info
.dwVolumeSerialNumber
;
3981 fs_high
= info
.nFileSizeHigh
;
3982 fs_low
= info
.nFileSizeLow
;
3983 ctime
= info
.ftCreationTime
;
3984 atime
= info
.ftLastAccessTime
;
3985 wtime
= info
.ftLastWriteTime
;
3986 fattrs
= info
.dwFileAttributes
;
3990 /* We don't go to Plan B here, because it's not clear that
3991 it's a good idea. The only known use case where
3992 CreateFile succeeds, but GetFileInformationByHandle fails
3993 (with ERROR_INVALID_FUNCTION) is for character devices
3994 such as NUL, PRN, etc. For these, switching to Plan B is
3995 a net loss, because we lose the character device
3996 attribute returned by GetFileType below (FindFirstFile
3997 doesn't set that bit in the attributes), and the other
3998 fields don't make sense for character devices anyway.
3999 Emacs doesn't really care for non-file entities in the
4000 context of l?stat, so neither do we. */
4002 /* w32err is assigned so one could put a breakpoint here and
4003 examine its value, when GetFileInformationByHandle
4005 DWORD w32err
= GetLastError ();
4009 case ERROR_FILE_NOT_FOUND
: /* can this ever happen? */
4015 /* Test for a symlink before testing for a directory, since
4016 symlinks to directories have the directory bit set, but we
4017 don't want them to appear as directories. */
4018 if (is_a_symlink
&& !follow_symlinks
)
4019 buf
->st_mode
= S_IFLNK
;
4020 else if (fattrs
& FILE_ATTRIBUTE_DIRECTORY
)
4021 buf
->st_mode
= S_IFDIR
;
4024 DWORD ftype
= GetFileType (fh
);
4028 case FILE_TYPE_DISK
:
4029 buf
->st_mode
= S_IFREG
;
4031 case FILE_TYPE_PIPE
:
4032 buf
->st_mode
= S_IFIFO
;
4034 case FILE_TYPE_CHAR
:
4035 case FILE_TYPE_UNKNOWN
:
4037 buf
->st_mode
= S_IFCHR
;
4040 /* We produce the fallback owner and group data, based on the
4041 current user that runs Emacs, in the following cases:
4043 . caller didn't request owner and group info
4044 . this is Windows 9X
4045 . getting security by handle failed, and we need to produce
4046 information for the target of a symlink (this is better
4047 than producing a potentially misleading info about the
4050 If getting security by handle fails, and we don't need to
4051 resolve symlinks, we try getting security by name. */
4052 if (!w32_stat_get_owner_group
|| is_windows_9x () == TRUE
)
4053 get_file_owner_and_group (NULL
, buf
);
4056 psd
= get_file_security_desc_by_handle (fh
);
4059 get_file_owner_and_group (psd
, buf
);
4062 else if (!(is_a_symlink
&& follow_symlinks
))
4064 psd
= get_file_security_desc_by_name (name
);
4065 get_file_owner_and_group (psd
, buf
);
4069 get_file_owner_and_group (NULL
, buf
);
4075 no_true_file_attributes
:
4076 /* Plan B: Either getting a handle on the file failed, or the
4077 caller explicitly asked us to not bother making this
4078 information more accurate.
4080 Implementation note: In Plan B, we never bother to resolve
4081 symlinks, even if we got here because we tried Plan A and
4082 failed. That's because, even if the caller asked for extra
4083 precision by setting Vw32_get_true_file_attributes to t,
4084 resolving symlinks requires acquiring a file handle to the
4085 symlink, which we already know will fail. And if the user
4086 did not ask for extra precision, resolving symlinks will fly
4087 in the face of that request, since the user then wants the
4088 lightweight version of the code. */
4089 dbcs_p
= max_filename_mbslen () > 1;
4090 rootdir
= (path
>= save_name
+ len
- 1
4091 && (IS_DIRECTORY_SEP (*path
) || *path
== 0));
4093 /* If name is "c:/.." or "/.." then stat "c:/" or "/". */
4094 r
= IS_DEVICE_SEP (name
[1]) ? &name
[2] : name
;
4095 if (IS_DIRECTORY_SEP (r
[0])
4096 && r
[1] == '.' && r
[2] == '.' && r
[3] == '\0')
4099 /* Note: If NAME is a symlink to the root of a UNC volume
4100 (i.e. "\\SERVER"), we will not detect that here, and we will
4101 return data about the symlink as result of FindFirst below.
4102 This is unfortunate, but that marginal use case does not
4103 justify a call to chase_symlinks which would impose a penalty
4104 on all the other use cases. (We get here for symlinks to
4105 roots of UNC volumes because CreateFile above fails for them,
4106 unlike with symlinks to root directories X:\ of drives.) */
4107 if (is_unc_volume (name
))
4109 fattrs
= unc_volume_file_attributes (name
);
4113 ctime
= atime
= wtime
= utc_base_ft
;
4119 if (!IS_DIRECTORY_SEP (name
[len
-1]))
4120 strcat (name
, "\\");
4124 char *end
= name
+ len
;
4125 char *n
= CharPrevExA (file_name_codepage
, name
, end
, 0);
4127 if (!IS_DIRECTORY_SEP (*n
))
4128 strcat (name
, "\\");
4130 if (GetDriveType (name
) < 2)
4136 fattrs
= FILE_ATTRIBUTE_DIRECTORY
;
4137 ctime
= atime
= wtime
= utc_base_ft
;
4143 if (IS_DIRECTORY_SEP (name
[len
-1]))
4148 char *end
= name
+ len
;
4149 char *n
= CharPrevExA (file_name_codepage
, name
, end
, 0);
4151 if (IS_DIRECTORY_SEP (*n
))
4155 /* (This is hacky, but helps when doing file completions on
4156 network drives.) Optimize by using information available from
4157 active readdir if possible. */
4158 len
= strlen (dir_pathname
);
4161 if (IS_DIRECTORY_SEP (dir_pathname
[len
-1]))
4166 char *end
= dir_pathname
+ len
;
4167 char *n
= CharPrevExA (file_name_codepage
, dir_pathname
, end
, 0);
4169 if (IS_DIRECTORY_SEP (*n
))
4172 if (dir_find_handle
!= INVALID_HANDLE_VALUE
4173 && !(is_a_symlink
&& follow_symlinks
)
4174 && strnicmp (save_name
, dir_pathname
, len
) == 0
4175 && IS_DIRECTORY_SEP (name
[len
])
4176 && xstrcasecmp (name
+ len
+ 1, dir_static
.d_name
) == 0)
4178 /* This was the last entry returned by readdir. */
4179 wfd
= dir_find_data
;
4183 logon_network_drive (name
);
4185 fh
= FindFirstFile (name
, &wfd
);
4186 if (fh
== INVALID_HANDLE_VALUE
)
4193 /* Note: if NAME is a symlink, the information we get from
4194 FindFirstFile is for the symlink, not its target. */
4195 fattrs
= wfd
.dwFileAttributes
;
4196 ctime
= wfd
.ftCreationTime
;
4197 atime
= wfd
.ftLastAccessTime
;
4198 wtime
= wfd
.ftLastWriteTime
;
4199 fs_high
= wfd
.nFileSizeHigh
;
4200 fs_low
= wfd
.nFileSizeLow
;
4203 serialnum
= volume_info
.serialnum
;
4205 if (is_a_symlink
&& !follow_symlinks
)
4206 buf
->st_mode
= S_IFLNK
;
4207 else if (fattrs
& FILE_ATTRIBUTE_DIRECTORY
)
4208 buf
->st_mode
= S_IFDIR
;
4210 buf
->st_mode
= S_IFREG
;
4212 get_file_owner_and_group (NULL
, buf
);
4216 /* Not sure if there is any point in this. */
4217 if (!NILP (Vw32_generate_fake_inodes
))
4218 fake_inode
= generate_inode_val (name
);
4219 else if (fake_inode
== 0)
4221 /* For want of something better, try to make everything unique. */
4222 static DWORD gen_num
= 0;
4223 fake_inode
= ++gen_num
;
4227 buf
->st_ino
= fake_inode
;
4229 buf
->st_dev
= serialnum
;
4230 buf
->st_rdev
= serialnum
;
4232 buf
->st_size
= fs_high
;
4233 buf
->st_size
<<= 32;
4234 buf
->st_size
+= fs_low
;
4235 buf
->st_nlink
= nlinks
;
4237 /* Convert timestamps to Unix format. */
4238 buf
->st_mtime
= convert_time (wtime
);
4239 buf
->st_atime
= convert_time (atime
);
4240 if (buf
->st_atime
== 0) buf
->st_atime
= buf
->st_mtime
;
4241 buf
->st_ctime
= convert_time (ctime
);
4242 if (buf
->st_ctime
== 0) buf
->st_ctime
= buf
->st_mtime
;
4244 /* determine rwx permissions */
4245 if (is_a_symlink
&& !follow_symlinks
)
4246 permission
= S_IREAD
| S_IWRITE
| S_IEXEC
; /* Posix expectations */
4249 if (fattrs
& FILE_ATTRIBUTE_READONLY
)
4250 permission
= S_IREAD
;
4252 permission
= S_IREAD
| S_IWRITE
;
4254 if (fattrs
& FILE_ATTRIBUTE_DIRECTORY
)
4255 permission
|= S_IEXEC
;
4256 else if (is_exec (name
))
4257 permission
|= S_IEXEC
;
4260 buf
->st_mode
|= permission
| (permission
>> 3) | (permission
>> 6);
4266 stat (const char * path
, struct stat
* buf
)
4268 return stat_worker (path
, buf
, 1);
4272 lstat (const char * path
, struct stat
* buf
)
4274 return stat_worker (path
, buf
, 0);
4278 fstatat (int fd
, char const *name
, struct stat
*st
, int flags
)
4280 /* Rely on a hack: an open directory is modeled as file descriptor 0.
4281 This is good enough for the current usage in Emacs, but is fragile.
4283 FIXME: Add proper support for fdopendir, fstatat, readlinkat.
4284 Gnulib does this and can serve as a model. */
4285 char fullname
[MAX_PATH
];
4289 if (_snprintf (fullname
, sizeof fullname
, "%s/%s", dir_pathname
, name
)
4292 errno
= ENAMETOOLONG
;
4298 return stat_worker (name
, st
, ! (flags
& AT_SYMLINK_NOFOLLOW
));
4301 /* Provide fstat and utime as well as stat for consistent handling of
4304 fstat (int desc
, struct stat
* buf
)
4306 HANDLE fh
= (HANDLE
) _get_osfhandle (desc
);
4307 BY_HANDLE_FILE_INFORMATION info
;
4308 unsigned __int64 fake_inode
;
4311 switch (GetFileType (fh
) & ~FILE_TYPE_REMOTE
)
4313 case FILE_TYPE_DISK
:
4314 buf
->st_mode
= S_IFREG
;
4315 if (!GetFileInformationByHandle (fh
, &info
))
4321 case FILE_TYPE_PIPE
:
4322 buf
->st_mode
= S_IFIFO
;
4324 case FILE_TYPE_CHAR
:
4325 case FILE_TYPE_UNKNOWN
:
4327 buf
->st_mode
= S_IFCHR
;
4329 memset (&info
, 0, sizeof (info
));
4330 info
.dwFileAttributes
= 0;
4331 info
.ftCreationTime
= utc_base_ft
;
4332 info
.ftLastAccessTime
= utc_base_ft
;
4333 info
.ftLastWriteTime
= utc_base_ft
;
4336 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
4337 buf
->st_mode
= S_IFDIR
;
4339 buf
->st_nlink
= info
.nNumberOfLinks
;
4340 /* Might as well use file index to fake inode values, but this
4341 is not guaranteed to be unique unless we keep a handle open
4342 all the time (even then there are situations where it is
4343 not unique). Reputedly, there are at most 48 bits of info
4344 (on NTFS, presumably less on FAT). */
4345 fake_inode
= info
.nFileIndexHigh
;
4347 fake_inode
+= info
.nFileIndexLow
;
4349 /* MSVC defines _ino_t to be short; other libc's might not. */
4350 if (sizeof (buf
->st_ino
) == 2)
4351 buf
->st_ino
= fake_inode
^ (fake_inode
>> 16);
4353 buf
->st_ino
= fake_inode
;
4355 /* If the caller so requested, get the true file owner and group.
4356 Otherwise, consider the file to belong to the current user. */
4357 if (!w32_stat_get_owner_group
|| is_windows_9x () == TRUE
)
4358 get_file_owner_and_group (NULL
, buf
);
4361 PSECURITY_DESCRIPTOR psd
= NULL
;
4363 psd
= get_file_security_desc_by_handle (fh
);
4366 get_file_owner_and_group (psd
, buf
);
4370 get_file_owner_and_group (NULL
, buf
);
4373 buf
->st_dev
= info
.dwVolumeSerialNumber
;
4374 buf
->st_rdev
= info
.dwVolumeSerialNumber
;
4376 buf
->st_size
= info
.nFileSizeHigh
;
4377 buf
->st_size
<<= 32;
4378 buf
->st_size
+= info
.nFileSizeLow
;
4380 /* Convert timestamps to Unix format. */
4381 buf
->st_mtime
= convert_time (info
.ftLastWriteTime
);
4382 buf
->st_atime
= convert_time (info
.ftLastAccessTime
);
4383 if (buf
->st_atime
== 0) buf
->st_atime
= buf
->st_mtime
;
4384 buf
->st_ctime
= convert_time (info
.ftCreationTime
);
4385 if (buf
->st_ctime
== 0) buf
->st_ctime
= buf
->st_mtime
;
4387 /* determine rwx permissions */
4388 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
)
4389 permission
= S_IREAD
;
4391 permission
= S_IREAD
| S_IWRITE
;
4393 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
4394 permission
|= S_IEXEC
;
4397 #if 0 /* no way of knowing the filename */
4398 char * p
= strrchr (name
, '.');
4400 (xstrcasecmp (p
, ".exe") == 0 ||
4401 xstrcasecmp (p
, ".com") == 0 ||
4402 xstrcasecmp (p
, ".bat") == 0 ||
4403 xstrcasecmp (p
, ".cmd") == 0))
4404 permission
|= S_IEXEC
;
4408 buf
->st_mode
|= permission
| (permission
>> 3) | (permission
>> 6);
4414 utime (const char *name
, struct utimbuf
*times
)
4416 struct utimbuf deftime
;
4423 deftime
.modtime
= deftime
.actime
= time (NULL
);
4427 /* Need write access to set times. */
4428 fh
= CreateFile (name
, FILE_WRITE_ATTRIBUTES
,
4429 /* If NAME specifies a directory, FILE_SHARE_DELETE
4430 allows other processes to delete files inside it,
4431 while we have the directory open. */
4432 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
4433 0, OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
4434 if (fh
!= INVALID_HANDLE_VALUE
)
4436 convert_from_time_t (times
->actime
, &atime
);
4437 convert_from_time_t (times
->modtime
, &mtime
);
4438 if (!SetFileTime (fh
, NULL
, &atime
, &mtime
))
4455 /* Symlink-related functions. */
4456 #ifndef SYMBOLIC_LINK_FLAG_DIRECTORY
4457 #define SYMBOLIC_LINK_FLAG_DIRECTORY 0x1
4461 symlink (char const *filename
, char const *linkname
)
4463 char linkfn
[MAX_PATH
], *tgtfn
;
4465 int dir_access
, filename_ends_in_slash
;
4468 /* Diagnostics follows Posix as much as possible. */
4469 if (filename
== NULL
|| linkname
== NULL
)
4479 if (strlen (filename
) > MAX_PATH
|| strlen (linkname
) > MAX_PATH
)
4481 errno
= ENAMETOOLONG
;
4485 strcpy (linkfn
, map_w32_filename (linkname
, NULL
));
4486 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) == 0)
4492 dbcs_p
= max_filename_mbslen () > 1;
4494 /* Note: since empty FILENAME was already rejected, we can safely
4495 refer to FILENAME[1]. */
4496 if (!(IS_DIRECTORY_SEP (filename
[0]) || IS_DEVICE_SEP (filename
[1])))
4498 /* Non-absolute FILENAME is understood as being relative to
4499 LINKNAME's directory. We need to prepend that directory to
4500 FILENAME to get correct results from faccessat below, since
4501 otherwise it will interpret FILENAME relative to the
4502 directory where the Emacs process runs. Note that
4503 make-symbolic-link always makes sure LINKNAME is a fully
4504 expanded file name. */
4506 char *p
= linkfn
+ strlen (linkfn
);
4510 while (p
> linkfn
&& !IS_ANY_SEP (p
[-1]))
4515 char *p1
= CharPrevExA (file_name_codepage
, linkfn
, p
, 0);
4517 while (p
> linkfn
&& !IS_ANY_SEP (*p1
))
4520 p1
= CharPrevExA (file_name_codepage
, linkfn
, p1
, 0);
4524 strncpy (tem
, linkfn
, p
- linkfn
);
4525 tem
[p
- linkfn
] = '\0';
4526 strcat (tem
, filename
);
4527 dir_access
= faccessat (AT_FDCWD
, tem
, D_OK
, AT_EACCESS
);
4530 dir_access
= faccessat (AT_FDCWD
, filename
, D_OK
, AT_EACCESS
);
4532 /* Since Windows distinguishes between symlinks to directories and
4533 to files, we provide a kludgy feature: if FILENAME doesn't
4534 exist, but ends in a slash, we create a symlink to directory. If
4535 FILENAME exists and is a directory, we always create a symlink to
4538 filename_ends_in_slash
= IS_DIRECTORY_SEP (filename
[strlen (filename
) - 1]);
4541 const char *end
= filename
+ strlen (filename
);
4542 const char *n
= CharPrevExA (file_name_codepage
, filename
, end
, 0);
4544 filename_ends_in_slash
= IS_DIRECTORY_SEP (*n
);
4546 if (dir_access
== 0 || filename_ends_in_slash
)
4547 flags
= SYMBOLIC_LINK_FLAG_DIRECTORY
;
4549 tgtfn
= (char *)map_w32_filename (filename
, NULL
);
4550 if (filename_ends_in_slash
)
4551 tgtfn
[strlen (tgtfn
) - 1] = '\0';
4554 if (!create_symbolic_link (linkfn
, tgtfn
, flags
))
4556 /* ENOSYS is set by create_symbolic_link, when it detects that
4557 the OS doesn't support the CreateSymbolicLink API. */
4558 if (errno
!= ENOSYS
)
4560 DWORD w32err
= GetLastError ();
4564 /* ERROR_SUCCESS is sometimes returned when LINKFN and
4565 TGTFN point to the same file name, go figure. */
4567 case ERROR_FILE_EXISTS
:
4570 case ERROR_ACCESS_DENIED
:
4573 case ERROR_FILE_NOT_FOUND
:
4574 case ERROR_PATH_NOT_FOUND
:
4575 case ERROR_BAD_NETPATH
:
4576 case ERROR_INVALID_REPARSE_DATA
:
4579 case ERROR_DIRECTORY
:
4582 case ERROR_PRIVILEGE_NOT_HELD
:
4583 case ERROR_NOT_ALL_ASSIGNED
:
4586 case ERROR_DISK_FULL
:
4599 /* A quick inexpensive test of whether FILENAME identifies a file that
4600 is a symlink. Returns non-zero if it is, zero otherwise. FILENAME
4601 must already be in the normalized form returned by
4604 Note: for repeated operations on many files, it is best to test
4605 whether the underlying volume actually supports symlinks, by
4606 testing the FILE_SUPPORTS_REPARSE_POINTS bit in volume's flags, and
4607 avoid the call to this function if it doesn't. That's because the
4608 call to GetFileAttributes takes a non-negligible time, especially
4609 on non-local or removable filesystems. See stat_worker for an
4610 example of how to do that. */
4612 is_symlink (const char *filename
)
4615 WIN32_FIND_DATA wfd
;
4618 attrs
= GetFileAttributes (filename
);
4621 DWORD w32err
= GetLastError ();
4625 case ERROR_BAD_NETPATH
: /* network share, can't be a symlink */
4627 case ERROR_ACCESS_DENIED
:
4630 case ERROR_FILE_NOT_FOUND
:
4631 case ERROR_PATH_NOT_FOUND
:
4638 if ((attrs
& FILE_ATTRIBUTE_REPARSE_POINT
) == 0)
4640 logon_network_drive (filename
);
4641 fh
= FindFirstFile (filename
, &wfd
);
4642 if (fh
== INVALID_HANDLE_VALUE
)
4645 return (wfd
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) != 0
4646 && (wfd
.dwReserved0
& IO_REPARSE_TAG_SYMLINK
) == IO_REPARSE_TAG_SYMLINK
;
4649 /* If NAME identifies a symbolic link, copy into BUF the file name of
4650 the symlink's target. Copy at most BUF_SIZE bytes, and do NOT
4651 null-terminate the target name, even if it fits. Return the number
4652 of bytes copied, or -1 if NAME is not a symlink or any error was
4653 encountered while resolving it. The file name copied into BUF is
4654 encoded in the current ANSI codepage. */
4656 readlink (const char *name
, char *buf
, size_t buf_size
)
4659 TOKEN_PRIVILEGES privs
;
4660 int restore_privs
= 0;
4675 path
= map_w32_filename (name
, NULL
);
4677 if (strlen (path
) > MAX_PATH
)
4679 errno
= ENAMETOOLONG
;
4684 if (is_windows_9x () == TRUE
4685 || (volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) == 0
4686 || !is_symlink (path
))
4689 errno
= EINVAL
; /* not a symlink */
4693 /* Done with simple tests, now we're in for some _real_ work. */
4694 if (enable_privilege (SE_BACKUP_NAME
, TRUE
, &privs
))
4696 /* Implementation note: From here and onward, don't return early,
4697 since that will fail to restore the original set of privileges of
4698 the calling thread. */
4700 retval
= -1; /* not too optimistic, are we? */
4702 /* Note: In the next call to CreateFile, we use zero as the 2nd
4703 argument because, when the symlink is a hidden/system file,
4704 e.g. 'C:\Users\All Users', GENERIC_READ fails with
4705 ERROR_ACCESS_DENIED. Zero seems to work just fine, both for file
4706 and directory symlinks. */
4707 sh
= CreateFile (path
, 0, 0, NULL
, OPEN_EXISTING
,
4708 FILE_FLAG_OPEN_REPARSE_POINT
| FILE_FLAG_BACKUP_SEMANTICS
,
4710 if (sh
!= INVALID_HANDLE_VALUE
)
4712 BYTE reparse_buf
[MAXIMUM_REPARSE_DATA_BUFFER_SIZE
];
4713 REPARSE_DATA_BUFFER
*reparse_data
= (REPARSE_DATA_BUFFER
*)&reparse_buf
[0];
4716 if (!DeviceIoControl (sh
, FSCTL_GET_REPARSE_POINT
, NULL
, 0,
4717 reparse_buf
, MAXIMUM_REPARSE_DATA_BUFFER_SIZE
,
4720 else if (reparse_data
->ReparseTag
!= IO_REPARSE_TAG_SYMLINK
)
4724 /* Copy the link target name, in wide characters, from
4725 reparse_data, then convert it to multibyte encoding in
4726 the current locale's codepage. */
4728 BYTE lname
[MAX_PATH
];
4731 reparse_data
->SymbolicLinkReparseBuffer
.PrintNameLength
;
4733 reparse_data
->SymbolicLinkReparseBuffer
.PathBuffer
4734 + reparse_data
->SymbolicLinkReparseBuffer
.PrintNameOffset
/sizeof(WCHAR
);
4735 /* This updates file_name_codepage which we need below. */
4736 int dbcs_p
= max_filename_mbslen () > 1;
4738 /* According to MSDN, PrintNameLength does not include the
4739 terminating null character. */
4740 lwname
= alloca ((lwname_len
+ 1) * sizeof(WCHAR
));
4741 memcpy (lwname
, lwname_src
, lwname_len
);
4742 lwname
[lwname_len
/sizeof(WCHAR
)] = 0; /* null-terminate */
4744 lname_len
= WideCharToMultiByte (file_name_codepage
, 0, lwname
, -1,
4745 lname
, MAX_PATH
, NULL
, NULL
);
4748 /* WideCharToMultiByte failed. */
4749 DWORD w32err1
= GetLastError ();
4753 case ERROR_INSUFFICIENT_BUFFER
:
4754 errno
= ENAMETOOLONG
;
4756 case ERROR_INVALID_PARAMETER
:
4759 case ERROR_NO_UNICODE_TRANSLATION
:
4769 size_t size_to_copy
= buf_size
;
4770 BYTE
*p
= lname
, *p2
;
4771 BYTE
*pend
= p
+ lname_len
;
4773 /* Normalize like dostounix_filename does, but we don't
4774 want to assume that lname is null-terminated. */
4776 p2
= CharNextExA (file_name_codepage
, p
, 0);
4779 if (*p
&& *p2
== ':' && *p
>= 'A' && *p
<= 'Z')
4790 p
= CharNextExA (file_name_codepage
, p
, 0);
4791 /* CharNextExA doesn't advance at null character. */
4798 /* Testing for null-terminated LNAME is paranoia:
4799 WideCharToMultiByte should always return a
4800 null-terminated string when its 4th argument is -1
4801 and its 3rd argument is null-terminated (which they
4803 if (lname
[lname_len
- 1] == '\0')
4805 if (lname_len
<= buf_size
)
4806 size_to_copy
= lname_len
;
4807 strncpy (buf
, lname
, size_to_copy
);
4809 retval
= size_to_copy
;
4816 /* CreateFile failed. */
4817 DWORD w32err2
= GetLastError ();
4821 case ERROR_FILE_NOT_FOUND
:
4822 case ERROR_PATH_NOT_FOUND
:
4825 case ERROR_ACCESS_DENIED
:
4826 case ERROR_TOO_MANY_OPEN_FILES
:
4836 restore_privilege (&privs
);
4844 readlinkat (int fd
, char const *name
, char *buffer
,
4847 /* Rely on a hack: an open directory is modeled as file descriptor 0,
4848 as in fstatat. FIXME: Add proper support for readlinkat. */
4849 char fullname
[MAX_PATH
];
4853 if (_snprintf (fullname
, sizeof fullname
, "%s/%s", dir_pathname
, name
)
4856 errno
= ENAMETOOLONG
;
4862 return readlink (name
, buffer
, buffer_size
);
4865 /* If FILE is a symlink, return its target (stored in a static
4866 buffer); otherwise return FILE.
4868 This function repeatedly resolves symlinks in the last component of
4869 a chain of symlink file names, as in foo -> bar -> baz -> ...,
4870 until it arrives at a file whose last component is not a symlink,
4871 or some error occurs. It returns the target of the last
4872 successfully resolved symlink in the chain. If it succeeds to
4873 resolve even a single symlink, the value returned is an absolute
4874 file name with backslashes (result of GetFullPathName). By
4875 contrast, if the original FILE is returned, it is unaltered.
4877 Note: This function can set errno even if it succeeds.
4879 Implementation note: we only resolve the last portion ("basename")
4880 of the argument FILE and of each following file in the chain,
4881 disregarding any possible symlinks in its leading directories.
4882 This is because Windows system calls and library functions
4883 transparently resolve symlinks in leading directories and return
4884 correct information, as long as the basename is not a symlink. */
4886 chase_symlinks (const char *file
)
4888 static char target
[MAX_PATH
];
4889 char link
[MAX_PATH
];
4890 ssize_t res
, link_len
;
4894 if (is_windows_9x () == TRUE
|| !is_symlink (file
))
4895 return (char *)file
;
4897 if ((link_len
= GetFullPathName (file
, MAX_PATH
, link
, NULL
)) == 0)
4898 return (char *)file
;
4900 dbcs_p
= max_filename_mbslen () > 1;
4904 /* Remove trailing slashes, as we want to resolve the last
4905 non-trivial part of the link name. */
4908 while (link_len
> 3 && IS_DIRECTORY_SEP (link
[link_len
-1]))
4909 link
[link_len
--] = '\0';
4911 else if (link_len
> 3)
4913 char *n
= CharPrevExA (file_name_codepage
, link
, link
+ link_len
, 0);
4915 while (n
>= link
+ 2 && IS_DIRECTORY_SEP (*n
))
4918 n
= CharPrevExA (file_name_codepage
, link
, n
, 0);
4922 res
= readlink (link
, target
, MAX_PATH
);
4926 if (!(IS_DEVICE_SEP (target
[1])
4927 || (IS_DIRECTORY_SEP (target
[0]) && IS_DIRECTORY_SEP (target
[1]))))
4929 /* Target is relative. Append it to the directory part of
4930 the symlink, then copy the result back to target. */
4931 char *p
= link
+ link_len
;
4935 while (p
> link
&& !IS_ANY_SEP (p
[-1]))
4940 char *p1
= CharPrevExA (file_name_codepage
, link
, p
, 0);
4942 while (p
> link
&& !IS_ANY_SEP (*p1
))
4945 p1
= CharPrevExA (file_name_codepage
, link
, p1
, 0);
4949 strcpy (target
, link
);
4951 /* Resolve any "." and ".." to get a fully-qualified file name
4953 link_len
= GetFullPathName (target
, MAX_PATH
, link
, NULL
);
4955 } while (res
> 0 && link_len
> 0 && ++loop_count
<= 100);
4957 if (loop_count
> 100)
4960 if (target
[0] == '\0') /* not a single call to readlink succeeded */
4961 return (char *)file
;
4966 /* Posix ACL emulation. */
4969 acl_valid (acl_t acl
)
4971 return is_valid_security_descriptor ((PSECURITY_DESCRIPTOR
)acl
) ? 0 : -1;
4975 acl_to_text (acl_t acl
, ssize_t
*size
)
4978 SECURITY_INFORMATION flags
=
4979 OWNER_SECURITY_INFORMATION
|
4980 GROUP_SECURITY_INFORMATION
|
4981 DACL_SECURITY_INFORMATION
;
4982 char *retval
= NULL
;
4988 if (convert_sd_to_sddl ((PSECURITY_DESCRIPTOR
)acl
, SDDL_REVISION_1
, flags
, &str_acl
, &local_size
))
4991 /* We don't want to mix heaps, so we duplicate the string in our
4992 heap and free the one allocated by the API. */
4993 retval
= xstrdup (str_acl
);
4996 LocalFree (str_acl
);
4998 else if (errno
!= ENOTSUP
)
5005 acl_from_text (const char *acl_str
)
5007 PSECURITY_DESCRIPTOR psd
, retval
= NULL
;
5013 if (convert_sddl_to_sd (acl_str
, SDDL_REVISION_1
, &psd
, &sd_size
))
5016 retval
= xmalloc (sd_size
);
5017 memcpy (retval
, psd
, sd_size
);
5020 else if (errno
!= ENOTSUP
)
5027 acl_free (void *ptr
)
5034 acl_get_file (const char *fname
, acl_type_t type
)
5036 PSECURITY_DESCRIPTOR psd
= NULL
;
5037 const char *filename
;
5039 if (type
== ACL_TYPE_ACCESS
)
5042 SECURITY_INFORMATION si
=
5043 OWNER_SECURITY_INFORMATION
|
5044 GROUP_SECURITY_INFORMATION
|
5045 DACL_SECURITY_INFORMATION
;
5048 filename
= map_w32_filename (fname
, NULL
);
5049 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) != 0)
5050 fname
= chase_symlinks (filename
);
5055 if (!get_file_security (fname
, si
, psd
, 0, &sd_len
)
5056 && errno
!= ENOTSUP
)
5058 err
= GetLastError ();
5059 if (err
== ERROR_INSUFFICIENT_BUFFER
)
5061 psd
= xmalloc (sd_len
);
5062 if (!get_file_security (fname
, si
, psd
, sd_len
, &sd_len
))
5069 else if (err
== ERROR_FILE_NOT_FOUND
5070 || err
== ERROR_PATH_NOT_FOUND
)
5078 else if (type
!= ACL_TYPE_DEFAULT
)
5085 acl_set_file (const char *fname
, acl_type_t type
, acl_t acl
)
5087 TOKEN_PRIVILEGES old1
, old2
;
5089 int st
= 0, retval
= -1;
5090 SECURITY_INFORMATION flags
= 0;
5096 const char *filename
;
5098 if (acl_valid (acl
) != 0
5099 || (type
!= ACL_TYPE_DEFAULT
&& type
!= ACL_TYPE_ACCESS
))
5105 if (type
== ACL_TYPE_DEFAULT
)
5111 filename
= map_w32_filename (fname
, NULL
);
5112 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) != 0)
5113 fname
= chase_symlinks (filename
);
5117 if (get_security_descriptor_owner ((PSECURITY_DESCRIPTOR
)acl
, &psid
, &dflt
)
5119 flags
|= OWNER_SECURITY_INFORMATION
;
5120 if (get_security_descriptor_group ((PSECURITY_DESCRIPTOR
)acl
, &psid
, &dflt
)
5122 flags
|= GROUP_SECURITY_INFORMATION
;
5123 if (get_security_descriptor_dacl ((PSECURITY_DESCRIPTOR
)acl
, &dacl_present
,
5126 flags
|= DACL_SECURITY_INFORMATION
;
5130 /* According to KB-245153, setting the owner will succeed if either:
5131 (1) the caller is the user who will be the new owner, and has the
5132 SE_TAKE_OWNERSHIP privilege, or
5133 (2) the caller has the SE_RESTORE privilege, in which case she can
5134 set any valid user or group as the owner
5136 We request below both SE_TAKE_OWNERSHIP and SE_RESTORE
5137 privileges, and disregard any failures in obtaining them. If
5138 these privileges cannot be obtained, and do not already exist in
5139 the calling thread's security token, this function could fail
5141 if (enable_privilege (SE_TAKE_OWNERSHIP_NAME
, TRUE
, &old1
))
5143 if (enable_privilege (SE_RESTORE_NAME
, TRUE
, &old2
))
5148 if (!set_file_security ((char *)fname
, flags
, (PSECURITY_DESCRIPTOR
)acl
))
5150 err
= GetLastError ();
5152 if (errno
== ENOTSUP
)
5154 else if (err
== ERROR_INVALID_OWNER
5155 || err
== ERROR_NOT_ALL_ASSIGNED
5156 || err
== ERROR_ACCESS_DENIED
)
5158 /* Maybe the requested ACL and the one the file already has
5159 are identical, in which case we can silently ignore the
5160 failure. (And no, Windows doesn't.) */
5161 acl_t current_acl
= acl_get_file (fname
, ACL_TYPE_ACCESS
);
5166 char *acl_from
= acl_to_text (current_acl
, NULL
);
5167 char *acl_to
= acl_to_text (acl
, NULL
);
5169 if (acl_from
&& acl_to
&& xstrcasecmp (acl_from
, acl_to
) == 0)
5175 acl_free (acl_from
);
5178 acl_free (current_acl
);
5181 else if (err
== ERROR_FILE_NOT_FOUND
|| err
== ERROR_PATH_NOT_FOUND
)
5195 restore_privilege (&old2
);
5196 restore_privilege (&old1
);
5204 /* MS-Windows version of careadlinkat (cf. ../lib/careadlinkat.c). We
5205 have a fixed max size for file names, so we don't need the kind of
5206 alloc/malloc/realloc dance the gnulib version does. We also don't
5207 support FD-relative symlinks. */
5209 careadlinkat (int fd
, char const *filename
,
5210 char *buffer
, size_t buffer_size
,
5211 struct allocator
const *alloc
,
5212 ssize_t (*preadlinkat
) (int, char const *, char *, size_t))
5214 char linkname
[MAX_PATH
];
5217 link_size
= preadlinkat (fd
, filename
, linkname
, sizeof(linkname
));
5221 char *retval
= buffer
;
5223 linkname
[link_size
++] = '\0';
5224 if (link_size
> buffer_size
)
5225 retval
= (char *)(alloc
? alloc
->allocate
: xmalloc
) (link_size
);
5227 memcpy (retval
, linkname
, link_size
);
5235 /* Support for browsing other processes and their attributes. See
5236 process.c for the Lisp bindings. */
5238 /* Helper wrapper functions. */
5240 static HANDLE WINAPI
5241 create_toolhelp32_snapshot (DWORD Flags
, DWORD Ignored
)
5243 static CreateToolhelp32Snapshot_Proc s_pfn_Create_Toolhelp32_Snapshot
= NULL
;
5245 if (g_b_init_create_toolhelp32_snapshot
== 0)
5247 g_b_init_create_toolhelp32_snapshot
= 1;
5248 s_pfn_Create_Toolhelp32_Snapshot
= (CreateToolhelp32Snapshot_Proc
)
5249 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5250 "CreateToolhelp32Snapshot");
5252 if (s_pfn_Create_Toolhelp32_Snapshot
== NULL
)
5254 return INVALID_HANDLE_VALUE
;
5256 return (s_pfn_Create_Toolhelp32_Snapshot (Flags
, Ignored
));
5260 process32_first (HANDLE hSnapshot
, LPPROCESSENTRY32 lppe
)
5262 static Process32First_Proc s_pfn_Process32_First
= NULL
;
5264 if (g_b_init_process32_first
== 0)
5266 g_b_init_process32_first
= 1;
5267 s_pfn_Process32_First
= (Process32First_Proc
)
5268 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5271 if (s_pfn_Process32_First
== NULL
)
5275 return (s_pfn_Process32_First (hSnapshot
, lppe
));
5279 process32_next (HANDLE hSnapshot
, LPPROCESSENTRY32 lppe
)
5281 static Process32Next_Proc s_pfn_Process32_Next
= NULL
;
5283 if (g_b_init_process32_next
== 0)
5285 g_b_init_process32_next
= 1;
5286 s_pfn_Process32_Next
= (Process32Next_Proc
)
5287 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5290 if (s_pfn_Process32_Next
== NULL
)
5294 return (s_pfn_Process32_Next (hSnapshot
, lppe
));
5298 open_thread_token (HANDLE ThreadHandle
,
5299 DWORD DesiredAccess
,
5301 PHANDLE TokenHandle
)
5303 static OpenThreadToken_Proc s_pfn_Open_Thread_Token
= NULL
;
5304 HMODULE hm_advapi32
= NULL
;
5305 if (is_windows_9x () == TRUE
)
5307 SetLastError (ERROR_NOT_SUPPORTED
);
5310 if (g_b_init_open_thread_token
== 0)
5312 g_b_init_open_thread_token
= 1;
5313 hm_advapi32
= LoadLibrary ("Advapi32.dll");
5314 s_pfn_Open_Thread_Token
=
5315 (OpenThreadToken_Proc
) GetProcAddress (hm_advapi32
, "OpenThreadToken");
5317 if (s_pfn_Open_Thread_Token
== NULL
)
5319 SetLastError (ERROR_NOT_SUPPORTED
);
5323 s_pfn_Open_Thread_Token (
5332 impersonate_self (SECURITY_IMPERSONATION_LEVEL ImpersonationLevel
)
5334 static ImpersonateSelf_Proc s_pfn_Impersonate_Self
= NULL
;
5335 HMODULE hm_advapi32
= NULL
;
5336 if (is_windows_9x () == TRUE
)
5340 if (g_b_init_impersonate_self
== 0)
5342 g_b_init_impersonate_self
= 1;
5343 hm_advapi32
= LoadLibrary ("Advapi32.dll");
5344 s_pfn_Impersonate_Self
=
5345 (ImpersonateSelf_Proc
) GetProcAddress (hm_advapi32
, "ImpersonateSelf");
5347 if (s_pfn_Impersonate_Self
== NULL
)
5351 return s_pfn_Impersonate_Self (ImpersonationLevel
);
5355 revert_to_self (void)
5357 static RevertToSelf_Proc s_pfn_Revert_To_Self
= NULL
;
5358 HMODULE hm_advapi32
= NULL
;
5359 if (is_windows_9x () == TRUE
)
5363 if (g_b_init_revert_to_self
== 0)
5365 g_b_init_revert_to_self
= 1;
5366 hm_advapi32
= LoadLibrary ("Advapi32.dll");
5367 s_pfn_Revert_To_Self
=
5368 (RevertToSelf_Proc
) GetProcAddress (hm_advapi32
, "RevertToSelf");
5370 if (s_pfn_Revert_To_Self
== NULL
)
5374 return s_pfn_Revert_To_Self ();
5378 get_process_memory_info (HANDLE h_proc
,
5379 PPROCESS_MEMORY_COUNTERS mem_counters
,
5382 static GetProcessMemoryInfo_Proc s_pfn_Get_Process_Memory_Info
= NULL
;
5383 HMODULE hm_psapi
= NULL
;
5384 if (is_windows_9x () == TRUE
)
5388 if (g_b_init_get_process_memory_info
== 0)
5390 g_b_init_get_process_memory_info
= 1;
5391 hm_psapi
= LoadLibrary ("Psapi.dll");
5393 s_pfn_Get_Process_Memory_Info
= (GetProcessMemoryInfo_Proc
)
5394 GetProcAddress (hm_psapi
, "GetProcessMemoryInfo");
5396 if (s_pfn_Get_Process_Memory_Info
== NULL
)
5400 return s_pfn_Get_Process_Memory_Info (h_proc
, mem_counters
, bufsize
);
5404 get_process_working_set_size (HANDLE h_proc
,
5408 static GetProcessWorkingSetSize_Proc
5409 s_pfn_Get_Process_Working_Set_Size
= NULL
;
5411 if (is_windows_9x () == TRUE
)
5415 if (g_b_init_get_process_working_set_size
== 0)
5417 g_b_init_get_process_working_set_size
= 1;
5418 s_pfn_Get_Process_Working_Set_Size
= (GetProcessWorkingSetSize_Proc
)
5419 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5420 "GetProcessWorkingSetSize");
5422 if (s_pfn_Get_Process_Working_Set_Size
== NULL
)
5426 return s_pfn_Get_Process_Working_Set_Size (h_proc
, minrss
, maxrss
);
5430 global_memory_status (MEMORYSTATUS
*buf
)
5432 static GlobalMemoryStatus_Proc s_pfn_Global_Memory_Status
= NULL
;
5434 if (is_windows_9x () == TRUE
)
5438 if (g_b_init_global_memory_status
== 0)
5440 g_b_init_global_memory_status
= 1;
5441 s_pfn_Global_Memory_Status
= (GlobalMemoryStatus_Proc
)
5442 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5443 "GlobalMemoryStatus");
5445 if (s_pfn_Global_Memory_Status
== NULL
)
5449 return s_pfn_Global_Memory_Status (buf
);
5453 global_memory_status_ex (MEMORY_STATUS_EX
*buf
)
5455 static GlobalMemoryStatusEx_Proc s_pfn_Global_Memory_Status_Ex
= NULL
;
5457 if (is_windows_9x () == TRUE
)
5461 if (g_b_init_global_memory_status_ex
== 0)
5463 g_b_init_global_memory_status_ex
= 1;
5464 s_pfn_Global_Memory_Status_Ex
= (GlobalMemoryStatusEx_Proc
)
5465 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5466 "GlobalMemoryStatusEx");
5468 if (s_pfn_Global_Memory_Status_Ex
== NULL
)
5472 return s_pfn_Global_Memory_Status_Ex (buf
);
5476 list_system_processes (void)
5478 struct gcpro gcpro1
;
5479 Lisp_Object proclist
= Qnil
;
5482 h_snapshot
= create_toolhelp32_snapshot (TH32CS_SNAPPROCESS
, 0);
5484 if (h_snapshot
!= INVALID_HANDLE_VALUE
)
5486 PROCESSENTRY32 proc_entry
;
5492 proc_entry
.dwSize
= sizeof (PROCESSENTRY32
);
5493 for (res
= process32_first (h_snapshot
, &proc_entry
); res
;
5494 res
= process32_next (h_snapshot
, &proc_entry
))
5496 proc_id
= proc_entry
.th32ProcessID
;
5497 proclist
= Fcons (make_fixnum_or_float (proc_id
), proclist
);
5500 CloseHandle (h_snapshot
);
5502 proclist
= Fnreverse (proclist
);
5509 enable_privilege (LPCTSTR priv_name
, BOOL enable_p
, TOKEN_PRIVILEGES
*old_priv
)
5511 TOKEN_PRIVILEGES priv
;
5512 DWORD priv_size
= sizeof (priv
);
5513 DWORD opriv_size
= sizeof (*old_priv
);
5514 HANDLE h_token
= NULL
;
5515 HANDLE h_thread
= GetCurrentThread ();
5519 res
= open_thread_token (h_thread
,
5520 TOKEN_QUERY
| TOKEN_ADJUST_PRIVILEGES
,
5522 if (!res
&& GetLastError () == ERROR_NO_TOKEN
)
5524 if (impersonate_self (SecurityImpersonation
))
5525 res
= open_thread_token (h_thread
,
5526 TOKEN_QUERY
| TOKEN_ADJUST_PRIVILEGES
,
5531 priv
.PrivilegeCount
= 1;
5532 priv
.Privileges
[0].Attributes
= enable_p
? SE_PRIVILEGE_ENABLED
: 0;
5533 LookupPrivilegeValue (NULL
, priv_name
, &priv
.Privileges
[0].Luid
);
5534 if (AdjustTokenPrivileges (h_token
, FALSE
, &priv
, priv_size
,
5535 old_priv
, &opriv_size
)
5536 && GetLastError () != ERROR_NOT_ALL_ASSIGNED
)
5540 CloseHandle (h_token
);
5546 restore_privilege (TOKEN_PRIVILEGES
*priv
)
5548 DWORD priv_size
= sizeof (*priv
);
5549 HANDLE h_token
= NULL
;
5552 if (open_thread_token (GetCurrentThread (),
5553 TOKEN_QUERY
| TOKEN_ADJUST_PRIVILEGES
,
5556 if (AdjustTokenPrivileges (h_token
, FALSE
, priv
, priv_size
, NULL
, NULL
)
5557 && GetLastError () != ERROR_NOT_ALL_ASSIGNED
)
5561 CloseHandle (h_token
);
5567 ltime (ULONGLONG time_100ns
)
5569 ULONGLONG time_sec
= time_100ns
/ 10000000;
5570 int subsec
= time_100ns
% 10000000;
5571 return list4 (make_number (time_sec
>> 16),
5572 make_number (time_sec
& 0xffff),
5573 make_number (subsec
/ 10),
5574 make_number (subsec
% 10 * 100000));
5577 #define U64_TO_LISP_TIME(time) ltime (time)
5580 process_times (HANDLE h_proc
, Lisp_Object
*ctime
, Lisp_Object
*etime
,
5581 Lisp_Object
*stime
, Lisp_Object
*utime
, Lisp_Object
*ttime
,
5584 FILETIME ft_creation
, ft_exit
, ft_kernel
, ft_user
, ft_current
;
5585 ULONGLONG tem1
, tem2
, tem3
, tem
;
5588 || !get_process_times_fn
5589 || !(*get_process_times_fn
) (h_proc
, &ft_creation
, &ft_exit
,
5590 &ft_kernel
, &ft_user
))
5593 GetSystemTimeAsFileTime (&ft_current
);
5595 FILETIME_TO_U64 (tem1
, ft_kernel
);
5596 *stime
= U64_TO_LISP_TIME (tem1
);
5598 FILETIME_TO_U64 (tem2
, ft_user
);
5599 *utime
= U64_TO_LISP_TIME (tem2
);
5602 *ttime
= U64_TO_LISP_TIME (tem3
);
5604 FILETIME_TO_U64 (tem
, ft_creation
);
5605 /* Process no 4 (System) returns zero creation time. */
5608 *ctime
= U64_TO_LISP_TIME (tem
);
5612 FILETIME_TO_U64 (tem3
, ft_current
);
5613 tem
= (tem3
- utc_base
) - tem
;
5615 *etime
= U64_TO_LISP_TIME (tem
);
5619 *pcpu
= 100.0 * (tem1
+ tem2
) / tem
;
5630 system_process_attributes (Lisp_Object pid
)
5632 struct gcpro gcpro1
, gcpro2
, gcpro3
;
5633 Lisp_Object attrs
= Qnil
;
5634 Lisp_Object cmd_str
, decoded_cmd
, tem
;
5635 HANDLE h_snapshot
, h_proc
;
5638 char uname
[UNLEN
+1], gname
[GNLEN
+1], domain
[1025];
5639 DWORD ulength
= sizeof (uname
), dlength
= sizeof (domain
), needed
;
5640 DWORD glength
= sizeof (gname
);
5641 HANDLE token
= NULL
;
5642 SID_NAME_USE user_type
;
5643 unsigned char *buf
= NULL
;
5645 TOKEN_USER user_token
;
5646 TOKEN_PRIMARY_GROUP group_token
;
5649 PROCESS_MEMORY_COUNTERS mem
;
5650 PROCESS_MEMORY_COUNTERS_EX mem_ex
;
5651 SIZE_T minrss
, maxrss
;
5653 MEMORY_STATUS_EX memstex
;
5654 double totphys
= 0.0;
5655 Lisp_Object ctime
, stime
, utime
, etime
, ttime
;
5657 BOOL result
= FALSE
;
5659 CHECK_NUMBER_OR_FLOAT (pid
);
5660 proc_id
= FLOATP (pid
) ? XFLOAT_DATA (pid
) : XINT (pid
);
5662 h_snapshot
= create_toolhelp32_snapshot (TH32CS_SNAPPROCESS
, 0);
5664 GCPRO3 (attrs
, decoded_cmd
, tem
);
5666 if (h_snapshot
!= INVALID_HANDLE_VALUE
)
5671 pe
.dwSize
= sizeof (PROCESSENTRY32
);
5672 for (res
= process32_first (h_snapshot
, &pe
); res
;
5673 res
= process32_next (h_snapshot
, &pe
))
5675 if (proc_id
== pe
.th32ProcessID
)
5678 decoded_cmd
= build_string ("Idle");
5681 /* Decode the command name from locale-specific
5683 cmd_str
= make_unibyte_string (pe
.szExeFile
,
5684 strlen (pe
.szExeFile
));
5686 code_convert_string_norecord (cmd_str
,
5687 Vlocale_coding_system
, 0);
5689 attrs
= Fcons (Fcons (Qcomm
, decoded_cmd
), attrs
);
5690 attrs
= Fcons (Fcons (Qppid
,
5691 make_fixnum_or_float (pe
.th32ParentProcessID
)),
5693 attrs
= Fcons (Fcons (Qpri
, make_number (pe
.pcPriClassBase
)),
5695 attrs
= Fcons (Fcons (Qthcount
,
5696 make_fixnum_or_float (pe
.cntThreads
)),
5703 CloseHandle (h_snapshot
);
5712 h_proc
= OpenProcess (PROCESS_QUERY_INFORMATION
| PROCESS_VM_READ
,
5714 /* If we were denied a handle to the process, try again after
5715 enabling the SeDebugPrivilege in our process. */
5718 TOKEN_PRIVILEGES priv_current
;
5720 if (enable_privilege (SE_DEBUG_NAME
, TRUE
, &priv_current
))
5722 h_proc
= OpenProcess (PROCESS_QUERY_INFORMATION
| PROCESS_VM_READ
,
5724 restore_privilege (&priv_current
);
5730 result
= open_process_token (h_proc
, TOKEN_QUERY
, &token
);
5733 result
= get_token_information (token
, TokenUser
, NULL
, 0, &blen
);
5734 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
5736 buf
= xmalloc (blen
);
5737 result
= get_token_information (token
, TokenUser
,
5738 (LPVOID
)buf
, blen
, &needed
);
5741 memcpy (&user_token
, buf
, sizeof (user_token
));
5742 if (!w32_cached_id (user_token
.User
.Sid
, &euid
, uname
))
5744 euid
= get_rid (user_token
.User
.Sid
);
5745 result
= lookup_account_sid (NULL
, user_token
.User
.Sid
,
5750 w32_add_to_cache (user_token
.User
.Sid
, euid
, uname
);
5753 strcpy (uname
, "unknown");
5757 ulength
= strlen (uname
);
5763 /* Determine a reasonable euid and gid values. */
5764 if (xstrcasecmp ("administrator", uname
) == 0)
5766 euid
= 500; /* well-known Administrator uid */
5767 egid
= 513; /* well-known None gid */
5771 /* Get group id and name. */
5772 result
= get_token_information (token
, TokenPrimaryGroup
,
5773 (LPVOID
)buf
, blen
, &needed
);
5774 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
5776 buf
= xrealloc (buf
, blen
= needed
);
5777 result
= get_token_information (token
, TokenPrimaryGroup
,
5778 (LPVOID
)buf
, blen
, &needed
);
5782 memcpy (&group_token
, buf
, sizeof (group_token
));
5783 if (!w32_cached_id (group_token
.PrimaryGroup
, &egid
, gname
))
5785 egid
= get_rid (group_token
.PrimaryGroup
);
5786 dlength
= sizeof (domain
);
5788 lookup_account_sid (NULL
, group_token
.PrimaryGroup
,
5789 gname
, &glength
, NULL
, &dlength
,
5792 w32_add_to_cache (group_token
.PrimaryGroup
,
5796 strcpy (gname
, "None");
5800 glength
= strlen (gname
);
5808 if (!is_windows_9x ())
5810 /* We couldn't open the process token, presumably because of
5811 insufficient access rights. Assume this process is run
5813 strcpy (uname
, "SYSTEM");
5814 strcpy (gname
, "None");
5815 euid
= 18; /* SYSTEM */
5816 egid
= 513; /* None */
5817 glength
= strlen (gname
);
5818 ulength
= strlen (uname
);
5820 /* If we are running under Windows 9X, where security calls are
5821 not supported, we assume all processes are run by the current
5823 else if (GetUserName (uname
, &ulength
))
5825 if (xstrcasecmp ("administrator", uname
) == 0)
5830 strcpy (gname
, "None");
5831 glength
= strlen (gname
);
5832 ulength
= strlen (uname
);
5838 strcpy (uname
, "administrator");
5839 ulength
= strlen (uname
);
5840 strcpy (gname
, "None");
5841 glength
= strlen (gname
);
5844 CloseHandle (token
);
5847 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (euid
)), attrs
);
5848 tem
= make_unibyte_string (uname
, ulength
);
5849 attrs
= Fcons (Fcons (Quser
,
5850 code_convert_string_norecord (tem
, Vlocale_coding_system
, 0)),
5852 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (egid
)), attrs
);
5853 tem
= make_unibyte_string (gname
, glength
);
5854 attrs
= Fcons (Fcons (Qgroup
,
5855 code_convert_string_norecord (tem
, Vlocale_coding_system
, 0)),
5858 if (global_memory_status_ex (&memstex
))
5859 #if __GNUC__ || (defined (_MSC_VER) && _MSC_VER >= 1300)
5860 totphys
= memstex
.ullTotalPhys
/ 1024.0;
5862 /* Visual Studio 6 cannot convert an unsigned __int64 type to
5863 double, so we need to do this for it... */
5865 DWORD tot_hi
= memstex
.ullTotalPhys
>> 32;
5866 DWORD tot_md
= (memstex
.ullTotalPhys
& 0x00000000ffffffff) >> 10;
5867 DWORD tot_lo
= memstex
.ullTotalPhys
% 1024;
5869 totphys
= tot_hi
* 4194304.0 + tot_md
+ tot_lo
/ 1024.0;
5871 #endif /* __GNUC__ || _MSC_VER >= 1300 */
5872 else if (global_memory_status (&memst
))
5873 totphys
= memst
.dwTotalPhys
/ 1024.0;
5876 && get_process_memory_info (h_proc
, (PROCESS_MEMORY_COUNTERS
*)&mem_ex
,
5879 SIZE_T rss
= mem_ex
.WorkingSetSize
/ 1024;
5881 attrs
= Fcons (Fcons (Qmajflt
,
5882 make_fixnum_or_float (mem_ex
.PageFaultCount
)),
5884 attrs
= Fcons (Fcons (Qvsize
,
5885 make_fixnum_or_float (mem_ex
.PrivateUsage
/ 1024)),
5887 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (rss
)), attrs
);
5889 attrs
= Fcons (Fcons (Qpmem
, make_float (100. * rss
/ totphys
)), attrs
);
5892 && get_process_memory_info (h_proc
, &mem
, sizeof (mem
)))
5894 SIZE_T rss
= mem_ex
.WorkingSetSize
/ 1024;
5896 attrs
= Fcons (Fcons (Qmajflt
,
5897 make_fixnum_or_float (mem
.PageFaultCount
)),
5899 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (rss
)), attrs
);
5901 attrs
= Fcons (Fcons (Qpmem
, make_float (100. * rss
/ totphys
)), attrs
);
5904 && get_process_working_set_size (h_proc
, &minrss
, &maxrss
))
5906 DWORD rss
= maxrss
/ 1024;
5908 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (maxrss
/ 1024)), attrs
);
5910 attrs
= Fcons (Fcons (Qpmem
, make_float (100. * rss
/ totphys
)), attrs
);
5913 if (process_times (h_proc
, &ctime
, &etime
, &stime
, &utime
, &ttime
, &pcpu
))
5915 attrs
= Fcons (Fcons (Qutime
, utime
), attrs
);
5916 attrs
= Fcons (Fcons (Qstime
, stime
), attrs
);
5917 attrs
= Fcons (Fcons (Qtime
, ttime
), attrs
);
5918 attrs
= Fcons (Fcons (Qstart
, ctime
), attrs
);
5919 attrs
= Fcons (Fcons (Qetime
, etime
), attrs
);
5920 attrs
= Fcons (Fcons (Qpcpu
, make_float (pcpu
)), attrs
);
5923 /* FIXME: Retrieve command line by walking the PEB of the process. */
5926 CloseHandle (h_proc
);
5932 /* Wrappers for winsock functions to map between our file descriptors
5933 and winsock's handles; also set h_errno for convenience.
5935 To allow Emacs to run on systems which don't have winsock support
5936 installed, we dynamically link to winsock on startup if present, and
5937 otherwise provide the minimum necessary functionality
5938 (eg. gethostname). */
5940 /* function pointers for relevant socket functions */
5941 int (PASCAL
*pfn_WSAStartup
) (WORD wVersionRequired
, LPWSADATA lpWSAData
);
5942 void (PASCAL
*pfn_WSASetLastError
) (int iError
);
5943 int (PASCAL
*pfn_WSAGetLastError
) (void);
5944 int (PASCAL
*pfn_WSAEventSelect
) (SOCKET s
, HANDLE hEventObject
, long lNetworkEvents
);
5945 HANDLE (PASCAL
*pfn_WSACreateEvent
) (void);
5946 int (PASCAL
*pfn_WSACloseEvent
) (HANDLE hEvent
);
5947 int (PASCAL
*pfn_socket
) (int af
, int type
, int protocol
);
5948 int (PASCAL
*pfn_bind
) (SOCKET s
, const struct sockaddr
*addr
, int namelen
);
5949 int (PASCAL
*pfn_connect
) (SOCKET s
, const struct sockaddr
*addr
, int namelen
);
5950 int (PASCAL
*pfn_ioctlsocket
) (SOCKET s
, long cmd
, u_long
*argp
);
5951 int (PASCAL
*pfn_recv
) (SOCKET s
, char * buf
, int len
, int flags
);
5952 int (PASCAL
*pfn_send
) (SOCKET s
, const char * buf
, int len
, int flags
);
5953 int (PASCAL
*pfn_closesocket
) (SOCKET s
);
5954 int (PASCAL
*pfn_shutdown
) (SOCKET s
, int how
);
5955 int (PASCAL
*pfn_WSACleanup
) (void);
5957 u_short (PASCAL
*pfn_htons
) (u_short hostshort
);
5958 u_short (PASCAL
*pfn_ntohs
) (u_short netshort
);
5959 unsigned long (PASCAL
*pfn_inet_addr
) (const char * cp
);
5960 int (PASCAL
*pfn_gethostname
) (char * name
, int namelen
);
5961 struct hostent
* (PASCAL
*pfn_gethostbyname
) (const char * name
);
5962 struct servent
* (PASCAL
*pfn_getservbyname
) (const char * name
, const char * proto
);
5963 int (PASCAL
*pfn_getpeername
) (SOCKET s
, struct sockaddr
*addr
, int * namelen
);
5964 int (PASCAL
*pfn_setsockopt
) (SOCKET s
, int level
, int optname
,
5965 const char * optval
, int optlen
);
5966 int (PASCAL
*pfn_listen
) (SOCKET s
, int backlog
);
5967 int (PASCAL
*pfn_getsockname
) (SOCKET s
, struct sockaddr
* name
,
5969 SOCKET (PASCAL
*pfn_accept
) (SOCKET s
, struct sockaddr
* addr
, int * addrlen
);
5970 int (PASCAL
*pfn_recvfrom
) (SOCKET s
, char * buf
, int len
, int flags
,
5971 struct sockaddr
* from
, int * fromlen
);
5972 int (PASCAL
*pfn_sendto
) (SOCKET s
, const char * buf
, int len
, int flags
,
5973 const struct sockaddr
* to
, int tolen
);
5975 /* SetHandleInformation is only needed to make sockets non-inheritable. */
5976 BOOL (WINAPI
*pfn_SetHandleInformation
) (HANDLE object
, DWORD mask
, DWORD flags
);
5977 #ifndef HANDLE_FLAG_INHERIT
5978 #define HANDLE_FLAG_INHERIT 1
5982 static int winsock_inuse
;
5987 if (winsock_lib
!= NULL
&& winsock_inuse
== 0)
5989 /* Not sure what would cause WSAENETDOWN, or even if it can happen
5990 after WSAStartup returns successfully, but it seems reasonable
5991 to allow unloading winsock anyway in that case. */
5992 if (pfn_WSACleanup () == 0 ||
5993 pfn_WSAGetLastError () == WSAENETDOWN
)
5995 if (FreeLibrary (winsock_lib
))
6004 init_winsock (int load_now
)
6006 WSADATA winsockData
;
6008 if (winsock_lib
!= NULL
)
6011 pfn_SetHandleInformation
6012 = (void *) GetProcAddress (GetModuleHandle ("kernel32.dll"),
6013 "SetHandleInformation");
6015 winsock_lib
= LoadLibrary ("Ws2_32.dll");
6017 if (winsock_lib
!= NULL
)
6019 /* dynamically link to socket functions */
6021 #define LOAD_PROC(fn) \
6022 if ((pfn_##fn = (void *) GetProcAddress (winsock_lib, #fn)) == NULL) \
6025 LOAD_PROC (WSAStartup
);
6026 LOAD_PROC (WSASetLastError
);
6027 LOAD_PROC (WSAGetLastError
);
6028 LOAD_PROC (WSAEventSelect
);
6029 LOAD_PROC (WSACreateEvent
);
6030 LOAD_PROC (WSACloseEvent
);
6033 LOAD_PROC (connect
);
6034 LOAD_PROC (ioctlsocket
);
6037 LOAD_PROC (closesocket
);
6038 LOAD_PROC (shutdown
);
6041 LOAD_PROC (inet_addr
);
6042 LOAD_PROC (gethostname
);
6043 LOAD_PROC (gethostbyname
);
6044 LOAD_PROC (getservbyname
);
6045 LOAD_PROC (getpeername
);
6046 LOAD_PROC (WSACleanup
);
6047 LOAD_PROC (setsockopt
);
6049 LOAD_PROC (getsockname
);
6051 LOAD_PROC (recvfrom
);
6055 /* specify version 1.1 of winsock */
6056 if (pfn_WSAStartup (0x101, &winsockData
) == 0)
6058 if (winsockData
.wVersion
!= 0x101)
6063 /* Report that winsock exists and is usable, but leave
6064 socket functions disabled. I am assuming that calling
6065 WSAStartup does not require any network interaction,
6066 and in particular does not cause or require a dial-up
6067 connection to be established. */
6070 FreeLibrary (winsock_lib
);
6078 FreeLibrary (winsock_lib
);
6088 /* Function to map winsock error codes to errno codes for those errno
6089 code defined in errno.h (errno values not defined by errno.h are
6090 already in nt/inc/sys/socket.h). */
6097 if (winsock_lib
== NULL
)
6100 wsa_err
= pfn_WSAGetLastError ();
6104 case WSAEACCES
: errno
= EACCES
; break;
6105 case WSAEBADF
: errno
= EBADF
; break;
6106 case WSAEFAULT
: errno
= EFAULT
; break;
6107 case WSAEINTR
: errno
= EINTR
; break;
6108 case WSAEINVAL
: errno
= EINVAL
; break;
6109 case WSAEMFILE
: errno
= EMFILE
; break;
6110 case WSAENAMETOOLONG
: errno
= ENAMETOOLONG
; break;
6111 case WSAENOTEMPTY
: errno
= ENOTEMPTY
; break;
6112 default: errno
= wsa_err
; break;
6120 if (winsock_lib
!= NULL
)
6121 pfn_WSASetLastError (0);
6124 /* Extend strerror to handle the winsock-specific error codes. */
6128 } _wsa_errlist
[] = {
6129 {WSAEINTR
, "Interrupted function call"},
6130 {WSAEBADF
, "Bad file descriptor"},
6131 {WSAEACCES
, "Permission denied"},
6132 {WSAEFAULT
, "Bad address"},
6133 {WSAEINVAL
, "Invalid argument"},
6134 {WSAEMFILE
, "Too many open files"},
6136 {WSAEWOULDBLOCK
, "Resource temporarily unavailable"},
6137 {WSAEINPROGRESS
, "Operation now in progress"},
6138 {WSAEALREADY
, "Operation already in progress"},
6139 {WSAENOTSOCK
, "Socket operation on non-socket"},
6140 {WSAEDESTADDRREQ
, "Destination address required"},
6141 {WSAEMSGSIZE
, "Message too long"},
6142 {WSAEPROTOTYPE
, "Protocol wrong type for socket"},
6143 {WSAENOPROTOOPT
, "Bad protocol option"},
6144 {WSAEPROTONOSUPPORT
, "Protocol not supported"},
6145 {WSAESOCKTNOSUPPORT
, "Socket type not supported"},
6146 {WSAEOPNOTSUPP
, "Operation not supported"},
6147 {WSAEPFNOSUPPORT
, "Protocol family not supported"},
6148 {WSAEAFNOSUPPORT
, "Address family not supported by protocol family"},
6149 {WSAEADDRINUSE
, "Address already in use"},
6150 {WSAEADDRNOTAVAIL
, "Cannot assign requested address"},
6151 {WSAENETDOWN
, "Network is down"},
6152 {WSAENETUNREACH
, "Network is unreachable"},
6153 {WSAENETRESET
, "Network dropped connection on reset"},
6154 {WSAECONNABORTED
, "Software caused connection abort"},
6155 {WSAECONNRESET
, "Connection reset by peer"},
6156 {WSAENOBUFS
, "No buffer space available"},
6157 {WSAEISCONN
, "Socket is already connected"},
6158 {WSAENOTCONN
, "Socket is not connected"},
6159 {WSAESHUTDOWN
, "Cannot send after socket shutdown"},
6160 {WSAETOOMANYREFS
, "Too many references"}, /* not sure */
6161 {WSAETIMEDOUT
, "Connection timed out"},
6162 {WSAECONNREFUSED
, "Connection refused"},
6163 {WSAELOOP
, "Network loop"}, /* not sure */
6164 {WSAENAMETOOLONG
, "Name is too long"},
6165 {WSAEHOSTDOWN
, "Host is down"},
6166 {WSAEHOSTUNREACH
, "No route to host"},
6167 {WSAENOTEMPTY
, "Buffer not empty"}, /* not sure */
6168 {WSAEPROCLIM
, "Too many processes"},
6169 {WSAEUSERS
, "Too many users"}, /* not sure */
6170 {WSAEDQUOT
, "Double quote in host name"}, /* really not sure */
6171 {WSAESTALE
, "Data is stale"}, /* not sure */
6172 {WSAEREMOTE
, "Remote error"}, /* not sure */
6174 {WSASYSNOTREADY
, "Network subsystem is unavailable"},
6175 {WSAVERNOTSUPPORTED
, "WINSOCK.DLL version out of range"},
6176 {WSANOTINITIALISED
, "Winsock not initialized successfully"},
6177 {WSAEDISCON
, "Graceful shutdown in progress"},
6179 {WSAENOMORE
, "No more operations allowed"}, /* not sure */
6180 {WSAECANCELLED
, "Operation cancelled"}, /* not sure */
6181 {WSAEINVALIDPROCTABLE
, "Invalid procedure table from service provider"},
6182 {WSAEINVALIDPROVIDER
, "Invalid service provider version number"},
6183 {WSAEPROVIDERFAILEDINIT
, "Unable to initialize a service provider"},
6184 {WSASYSCALLFAILURE
, "System call failure"},
6185 {WSASERVICE_NOT_FOUND
, "Service not found"}, /* not sure */
6186 {WSATYPE_NOT_FOUND
, "Class type not found"},
6187 {WSA_E_NO_MORE
, "No more resources available"}, /* really not sure */
6188 {WSA_E_CANCELLED
, "Operation already cancelled"}, /* really not sure */
6189 {WSAEREFUSED
, "Operation refused"}, /* not sure */
6192 {WSAHOST_NOT_FOUND
, "Host not found"},
6193 {WSATRY_AGAIN
, "Authoritative host not found during name lookup"},
6194 {WSANO_RECOVERY
, "Non-recoverable error during name lookup"},
6195 {WSANO_DATA
, "Valid name, no data record of requested type"},
6201 sys_strerror (int error_no
)
6204 static char unknown_msg
[40];
6206 if (error_no
>= 0 && error_no
< sys_nerr
)
6207 return sys_errlist
[error_no
];
6209 for (i
= 0; _wsa_errlist
[i
].errnum
>= 0; i
++)
6210 if (_wsa_errlist
[i
].errnum
== error_no
)
6211 return _wsa_errlist
[i
].msg
;
6213 sprintf (unknown_msg
, "Unidentified error: %d", error_no
);
6217 /* [andrewi 3-May-96] I've had conflicting results using both methods,
6218 but I believe the method of keeping the socket handle separate (and
6219 insuring it is not inheritable) is the correct one. */
6221 #define SOCK_HANDLE(fd) ((SOCKET) fd_info[fd].hnd)
6223 static int socket_to_fd (SOCKET s
);
6226 sys_socket (int af
, int type
, int protocol
)
6230 if (winsock_lib
== NULL
)
6233 return INVALID_SOCKET
;
6238 /* call the real socket function */
6239 s
= pfn_socket (af
, type
, protocol
);
6241 if (s
!= INVALID_SOCKET
)
6242 return socket_to_fd (s
);
6248 /* Convert a SOCKET to a file descriptor. */
6250 socket_to_fd (SOCKET s
)
6255 /* Although under NT 3.5 _open_osfhandle will accept a socket
6256 handle, if opened with SO_OPENTYPE == SO_SYNCHRONOUS_NONALERT,
6257 that does not work under NT 3.1. However, we can get the same
6258 effect by using a backdoor function to replace an existing
6259 descriptor handle with the one we want. */
6261 /* allocate a file descriptor (with appropriate flags) */
6262 fd
= _open ("NUL:", _O_RDWR
);
6265 /* Make a non-inheritable copy of the socket handle. Note
6266 that it is possible that sockets aren't actually kernel
6267 handles, which appears to be the case on Windows 9x when
6268 the MS Proxy winsock client is installed. */
6270 /* Apparently there is a bug in NT 3.51 with some service
6271 packs, which prevents using DuplicateHandle to make a
6272 socket handle non-inheritable (causes WSACleanup to
6273 hang). The work-around is to use SetHandleInformation
6274 instead if it is available and implemented. */
6275 if (pfn_SetHandleInformation
)
6277 pfn_SetHandleInformation ((HANDLE
) s
, HANDLE_FLAG_INHERIT
, 0);
6281 HANDLE parent
= GetCurrentProcess ();
6282 HANDLE new_s
= INVALID_HANDLE_VALUE
;
6284 if (DuplicateHandle (parent
,
6290 DUPLICATE_SAME_ACCESS
))
6292 /* It is possible that DuplicateHandle succeeds even
6293 though the socket wasn't really a kernel handle,
6294 because a real handle has the same value. So
6295 test whether the new handle really is a socket. */
6296 long nonblocking
= 0;
6297 if (pfn_ioctlsocket ((SOCKET
) new_s
, FIONBIO
, &nonblocking
) == 0)
6299 pfn_closesocket (s
);
6304 CloseHandle (new_s
);
6309 eassert (fd
< MAXDESC
);
6310 fd_info
[fd
].hnd
= (HANDLE
) s
;
6312 /* set our own internal flags */
6313 fd_info
[fd
].flags
= FILE_SOCKET
| FILE_BINARY
| FILE_READ
| FILE_WRITE
;
6319 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
6321 /* attach child_process to fd_info */
6322 if (fd_info
[ fd
].cp
!= NULL
)
6324 DebPrint (("sys_socket: fd_info[%d] apparently in use!\n", fd
));
6328 fd_info
[ fd
].cp
= cp
;
6331 winsock_inuse
++; /* count open sockets */
6339 pfn_closesocket (s
);
6345 sys_bind (int s
, const struct sockaddr
* addr
, int namelen
)
6347 if (winsock_lib
== NULL
)
6350 return SOCKET_ERROR
;
6354 if (fd_info
[s
].flags
& FILE_SOCKET
)
6356 int rc
= pfn_bind (SOCK_HANDLE (s
), addr
, namelen
);
6357 if (rc
== SOCKET_ERROR
)
6362 return SOCKET_ERROR
;
6366 sys_connect (int s
, const struct sockaddr
* name
, int namelen
)
6368 if (winsock_lib
== NULL
)
6371 return SOCKET_ERROR
;
6375 if (fd_info
[s
].flags
& FILE_SOCKET
)
6377 int rc
= pfn_connect (SOCK_HANDLE (s
), name
, namelen
);
6378 if (rc
== SOCKET_ERROR
)
6383 return SOCKET_ERROR
;
6387 sys_htons (u_short hostshort
)
6389 return (winsock_lib
!= NULL
) ?
6390 pfn_htons (hostshort
) : hostshort
;
6394 sys_ntohs (u_short netshort
)
6396 return (winsock_lib
!= NULL
) ?
6397 pfn_ntohs (netshort
) : netshort
;
6401 sys_inet_addr (const char * cp
)
6403 return (winsock_lib
!= NULL
) ?
6404 pfn_inet_addr (cp
) : INADDR_NONE
;
6408 sys_gethostname (char * name
, int namelen
)
6410 if (winsock_lib
!= NULL
)
6415 retval
= pfn_gethostname (name
, namelen
);
6416 if (retval
== SOCKET_ERROR
)
6421 if (namelen
> MAX_COMPUTERNAME_LENGTH
)
6422 return !GetComputerName (name
, (DWORD
*)&namelen
);
6425 return SOCKET_ERROR
;
6429 sys_gethostbyname (const char * name
)
6431 struct hostent
* host
;
6432 int h_err
= h_errno
;
6434 if (winsock_lib
== NULL
)
6436 h_errno
= NO_RECOVERY
;
6442 host
= pfn_gethostbyname (name
);
6454 sys_getservbyname (const char * name
, const char * proto
)
6456 struct servent
* serv
;
6458 if (winsock_lib
== NULL
)
6465 serv
= pfn_getservbyname (name
, proto
);
6472 sys_getpeername (int s
, struct sockaddr
*addr
, int * namelen
)
6474 if (winsock_lib
== NULL
)
6477 return SOCKET_ERROR
;
6481 if (fd_info
[s
].flags
& FILE_SOCKET
)
6483 int rc
= pfn_getpeername (SOCK_HANDLE (s
), addr
, namelen
);
6484 if (rc
== SOCKET_ERROR
)
6489 return SOCKET_ERROR
;
6493 sys_shutdown (int s
, int how
)
6495 if (winsock_lib
== NULL
)
6498 return SOCKET_ERROR
;
6502 if (fd_info
[s
].flags
& FILE_SOCKET
)
6504 int rc
= pfn_shutdown (SOCK_HANDLE (s
), how
);
6505 if (rc
== SOCKET_ERROR
)
6510 return SOCKET_ERROR
;
6514 sys_setsockopt (int s
, int level
, int optname
, const void * optval
, int optlen
)
6516 if (winsock_lib
== NULL
)
6519 return SOCKET_ERROR
;
6523 if (fd_info
[s
].flags
& FILE_SOCKET
)
6525 int rc
= pfn_setsockopt (SOCK_HANDLE (s
), level
, optname
,
6526 (const char *)optval
, optlen
);
6527 if (rc
== SOCKET_ERROR
)
6532 return SOCKET_ERROR
;
6536 sys_listen (int s
, int backlog
)
6538 if (winsock_lib
== NULL
)
6541 return SOCKET_ERROR
;
6545 if (fd_info
[s
].flags
& FILE_SOCKET
)
6547 int rc
= pfn_listen (SOCK_HANDLE (s
), backlog
);
6548 if (rc
== SOCKET_ERROR
)
6551 fd_info
[s
].flags
|= FILE_LISTEN
;
6555 return SOCKET_ERROR
;
6559 sys_getsockname (int s
, struct sockaddr
* name
, int * namelen
)
6561 if (winsock_lib
== NULL
)
6564 return SOCKET_ERROR
;
6568 if (fd_info
[s
].flags
& FILE_SOCKET
)
6570 int rc
= pfn_getsockname (SOCK_HANDLE (s
), name
, namelen
);
6571 if (rc
== SOCKET_ERROR
)
6576 return SOCKET_ERROR
;
6580 sys_accept (int s
, struct sockaddr
* addr
, int * addrlen
)
6582 if (winsock_lib
== NULL
)
6589 if (fd_info
[s
].flags
& FILE_LISTEN
)
6591 SOCKET t
= pfn_accept (SOCK_HANDLE (s
), addr
, addrlen
);
6593 if (t
== INVALID_SOCKET
)
6596 fd
= socket_to_fd (t
);
6600 fd_info
[s
].cp
->status
= STATUS_READ_ACKNOWLEDGED
;
6601 ResetEvent (fd_info
[s
].cp
->char_avail
);
6610 sys_recvfrom (int s
, char * buf
, int len
, int flags
,
6611 struct sockaddr
* from
, int * fromlen
)
6613 if (winsock_lib
== NULL
)
6616 return SOCKET_ERROR
;
6620 if (fd_info
[s
].flags
& FILE_SOCKET
)
6622 int rc
= pfn_recvfrom (SOCK_HANDLE (s
), buf
, len
, flags
, from
, fromlen
);
6623 if (rc
== SOCKET_ERROR
)
6628 return SOCKET_ERROR
;
6632 sys_sendto (int s
, const char * buf
, int len
, int flags
,
6633 const struct sockaddr
* to
, int tolen
)
6635 if (winsock_lib
== NULL
)
6638 return SOCKET_ERROR
;
6642 if (fd_info
[s
].flags
& FILE_SOCKET
)
6644 int rc
= pfn_sendto (SOCK_HANDLE (s
), buf
, len
, flags
, to
, tolen
);
6645 if (rc
== SOCKET_ERROR
)
6650 return SOCKET_ERROR
;
6653 /* Windows does not have an fcntl function. Provide an implementation
6654 solely for making sockets non-blocking. */
6656 fcntl (int s
, int cmd
, int options
)
6658 if (winsock_lib
== NULL
)
6665 if (fd_info
[s
].flags
& FILE_SOCKET
)
6667 if (cmd
== F_SETFL
&& options
== O_NONBLOCK
)
6669 unsigned long nblock
= 1;
6670 int rc
= pfn_ioctlsocket (SOCK_HANDLE (s
), FIONBIO
, &nblock
);
6671 if (rc
== SOCKET_ERROR
)
6673 /* Keep track of the fact that we set this to non-blocking. */
6674 fd_info
[s
].flags
|= FILE_NDELAY
;
6680 return SOCKET_ERROR
;
6684 return SOCKET_ERROR
;
6688 /* Shadow main io functions: we need to handle pipes and sockets more
6689 intelligently, and implement non-blocking mode as well. */
6702 if (fd
< MAXDESC
&& fd_info
[fd
].cp
)
6704 child_process
* cp
= fd_info
[fd
].cp
;
6706 fd_info
[fd
].cp
= NULL
;
6708 if (CHILD_ACTIVE (cp
))
6710 /* if last descriptor to active child_process then cleanup */
6712 for (i
= 0; i
< MAXDESC
; i
++)
6716 if (fd_info
[i
].cp
== cp
)
6721 if (fd_info
[fd
].flags
& FILE_SOCKET
)
6723 if (winsock_lib
== NULL
) emacs_abort ();
6725 pfn_shutdown (SOCK_HANDLE (fd
), 2);
6726 rc
= pfn_closesocket (SOCK_HANDLE (fd
));
6728 winsock_inuse
--; /* count open sockets */
6730 /* If the process handle is NULL, it's either a socket
6731 or serial connection, or a subprocess that was
6732 already reaped by reap_subprocess, but whose
6733 resources were not yet freed, because its output was
6734 not fully read yet by the time it was reaped. (This
6735 usually happens with async subprocesses whose output
6736 is being read by Emacs.) Otherwise, this process was
6737 not reaped yet, so we set its FD to a negative value
6738 to make sure sys_select will eventually get to
6739 calling the SIGCHLD handler for it, which will then
6740 invoke waitpid and reap_subprocess. */
6741 if (cp
->procinfo
.hProcess
== NULL
)
6749 if (fd
>= 0 && fd
< MAXDESC
)
6750 fd_info
[fd
].flags
= 0;
6752 /* Note that sockets do not need special treatment here (at least on
6753 NT and Windows 95 using the standard tcp/ip stacks) - it appears that
6754 closesocket is equivalent to CloseHandle, which is to be expected
6755 because socket handles are fully fledged kernel handles. */
6767 if (new_fd
>= 0 && new_fd
< MAXDESC
)
6769 /* duplicate our internal info as well */
6770 fd_info
[new_fd
] = fd_info
[fd
];
6776 sys_dup2 (int src
, int dst
)
6780 if (dst
< 0 || dst
>= MAXDESC
)
6786 /* make sure we close the destination first if it's a pipe or socket */
6787 if (src
!= dst
&& fd_info
[dst
].flags
!= 0)
6790 rc
= _dup2 (src
, dst
);
6793 /* duplicate our internal info as well */
6794 fd_info
[dst
] = fd_info
[src
];
6799 /* Unix pipe() has only one arg */
6801 sys_pipe (int * phandles
)
6806 /* make pipe handles non-inheritable; when we spawn a child, we
6807 replace the relevant handle with an inheritable one. Also put
6808 pipes into binary mode; we will do text mode translation ourselves
6810 rc
= _pipe (phandles
, 0, _O_NOINHERIT
| _O_BINARY
);
6814 /* Protect against overflow, since Windows can open more handles than
6815 our fd_info array has room for. */
6816 if (phandles
[0] >= MAXDESC
|| phandles
[1] >= MAXDESC
)
6818 _close (phandles
[0]);
6819 _close (phandles
[1]);
6825 flags
= FILE_PIPE
| FILE_READ
| FILE_BINARY
;
6826 fd_info
[phandles
[0]].flags
= flags
;
6828 flags
= FILE_PIPE
| FILE_WRITE
| FILE_BINARY
;
6829 fd_info
[phandles
[1]].flags
= flags
;
6836 /* Function to do blocking read of one byte, needed to implement
6837 select. It is only allowed on communication ports, sockets, or
6840 _sys_read_ahead (int fd
)
6845 if (fd
< 0 || fd
>= MAXDESC
)
6846 return STATUS_READ_ERROR
;
6848 cp
= fd_info
[fd
].cp
;
6850 if (cp
== NULL
|| cp
->fd
!= fd
|| cp
->status
!= STATUS_READ_READY
)
6851 return STATUS_READ_ERROR
;
6853 if ((fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SERIAL
| FILE_SOCKET
)) == 0
6854 || (fd_info
[fd
].flags
& FILE_READ
) == 0)
6856 DebPrint (("_sys_read_ahead: internal error: fd %d is not a pipe, serial port, or socket!\n", fd
));
6860 cp
->status
= STATUS_READ_IN_PROGRESS
;
6862 if (fd_info
[fd
].flags
& FILE_PIPE
)
6864 rc
= _read (fd
, &cp
->chr
, sizeof (char));
6866 /* Give subprocess time to buffer some more output for us before
6867 reporting that input is available; we need this because Windows 95
6868 connects DOS programs to pipes by making the pipe appear to be
6869 the normal console stdout - as a result most DOS programs will
6870 write to stdout without buffering, ie. one character at a
6871 time. Even some W32 programs do this - "dir" in a command
6872 shell on NT is very slow if we don't do this. */
6875 int wait
= w32_pipe_read_delay
;
6881 /* Yield remainder of our time slice, effectively giving a
6882 temporary priority boost to the child process. */
6886 else if (fd_info
[fd
].flags
& FILE_SERIAL
)
6888 HANDLE hnd
= fd_info
[fd
].hnd
;
6889 OVERLAPPED
*ovl
= &fd_info
[fd
].cp
->ovl_read
;
6892 /* Configure timeouts for blocking read. */
6893 if (!GetCommTimeouts (hnd
, &ct
))
6895 cp
->status
= STATUS_READ_ERROR
;
6896 return STATUS_READ_ERROR
;
6898 ct
.ReadIntervalTimeout
= 0;
6899 ct
.ReadTotalTimeoutMultiplier
= 0;
6900 ct
.ReadTotalTimeoutConstant
= 0;
6901 if (!SetCommTimeouts (hnd
, &ct
))
6903 cp
->status
= STATUS_READ_ERROR
;
6904 return STATUS_READ_ERROR
;
6907 if (!ReadFile (hnd
, &cp
->chr
, sizeof (char), (DWORD
*) &rc
, ovl
))
6909 if (GetLastError () != ERROR_IO_PENDING
)
6911 cp
->status
= STATUS_READ_ERROR
;
6912 return STATUS_READ_ERROR
;
6914 if (!GetOverlappedResult (hnd
, ovl
, (DWORD
*) &rc
, TRUE
))
6916 cp
->status
= STATUS_READ_ERROR
;
6917 return STATUS_READ_ERROR
;
6921 else if (fd_info
[fd
].flags
& FILE_SOCKET
)
6923 unsigned long nblock
= 0;
6924 /* We always want this to block, so temporarily disable NDELAY. */
6925 if (fd_info
[fd
].flags
& FILE_NDELAY
)
6926 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
6928 rc
= pfn_recv (SOCK_HANDLE (fd
), &cp
->chr
, sizeof (char), 0);
6930 if (fd_info
[fd
].flags
& FILE_NDELAY
)
6933 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
6937 if (rc
== sizeof (char))
6938 cp
->status
= STATUS_READ_SUCCEEDED
;
6940 cp
->status
= STATUS_READ_FAILED
;
6946 _sys_wait_accept (int fd
)
6952 if (fd
< 0 || fd
>= MAXDESC
)
6953 return STATUS_READ_ERROR
;
6955 cp
= fd_info
[fd
].cp
;
6957 if (cp
== NULL
|| cp
->fd
!= fd
|| cp
->status
!= STATUS_READ_READY
)
6958 return STATUS_READ_ERROR
;
6960 cp
->status
= STATUS_READ_FAILED
;
6962 hEv
= pfn_WSACreateEvent ();
6963 rc
= pfn_WSAEventSelect (SOCK_HANDLE (fd
), hEv
, FD_ACCEPT
);
6964 if (rc
!= SOCKET_ERROR
)
6966 rc
= WaitForSingleObject (hEv
, INFINITE
);
6967 pfn_WSAEventSelect (SOCK_HANDLE (fd
), NULL
, 0);
6968 if (rc
== WAIT_OBJECT_0
)
6969 cp
->status
= STATUS_READ_SUCCEEDED
;
6971 pfn_WSACloseEvent (hEv
);
6977 sys_read (int fd
, char * buffer
, unsigned int count
)
6982 char * orig_buffer
= buffer
;
6990 if (fd
< MAXDESC
&& fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
| FILE_SERIAL
))
6992 child_process
*cp
= fd_info
[fd
].cp
;
6994 if ((fd_info
[fd
].flags
& FILE_READ
) == 0)
7002 /* re-read CR carried over from last read */
7003 if (fd_info
[fd
].flags
& FILE_LAST_CR
)
7005 if (fd_info
[fd
].flags
& FILE_BINARY
) emacs_abort ();
7009 fd_info
[fd
].flags
&= ~FILE_LAST_CR
;
7012 /* presence of a child_process structure means we are operating in
7013 non-blocking mode - otherwise we just call _read directly.
7014 Note that the child_process structure might be missing because
7015 reap_subprocess has been called; in this case the pipe is
7016 already broken, so calling _read on it is okay. */
7019 int current_status
= cp
->status
;
7021 switch (current_status
)
7023 case STATUS_READ_FAILED
:
7024 case STATUS_READ_ERROR
:
7025 /* report normal EOF if nothing in buffer */
7027 fd_info
[fd
].flags
|= FILE_AT_EOF
;
7030 case STATUS_READ_READY
:
7031 case STATUS_READ_IN_PROGRESS
:
7032 DebPrint (("sys_read called when read is in progress\n"));
7033 errno
= EWOULDBLOCK
;
7036 case STATUS_READ_SUCCEEDED
:
7037 /* consume read-ahead char */
7038 *buffer
++ = cp
->chr
;
7041 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
7042 ResetEvent (cp
->char_avail
);
7044 case STATUS_READ_ACKNOWLEDGED
:
7048 DebPrint (("sys_read: bad status %d\n", current_status
));
7053 if (fd_info
[fd
].flags
& FILE_PIPE
)
7055 PeekNamedPipe ((HANDLE
) _get_osfhandle (fd
), NULL
, 0, NULL
, &waiting
, NULL
);
7056 to_read
= min (waiting
, (DWORD
) count
);
7059 nchars
+= _read (fd
, buffer
, to_read
);
7061 else if (fd_info
[fd
].flags
& FILE_SERIAL
)
7063 HANDLE hnd
= fd_info
[fd
].hnd
;
7064 OVERLAPPED
*ovl
= &fd_info
[fd
].cp
->ovl_read
;
7070 /* Configure timeouts for non-blocking read. */
7071 if (!GetCommTimeouts (hnd
, &ct
))
7076 ct
.ReadIntervalTimeout
= MAXDWORD
;
7077 ct
.ReadTotalTimeoutMultiplier
= 0;
7078 ct
.ReadTotalTimeoutConstant
= 0;
7079 if (!SetCommTimeouts (hnd
, &ct
))
7085 if (!ResetEvent (ovl
->hEvent
))
7090 if (!ReadFile (hnd
, buffer
, count
, (DWORD
*) &rc
, ovl
))
7092 if (GetLastError () != ERROR_IO_PENDING
)
7097 if (!GetOverlappedResult (hnd
, ovl
, (DWORD
*) &rc
, TRUE
))
7106 else /* FILE_SOCKET */
7108 if (winsock_lib
== NULL
) emacs_abort ();
7110 /* do the equivalent of a non-blocking read */
7111 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONREAD
, &waiting
);
7112 if (waiting
== 0 && nchars
== 0)
7114 errno
= EWOULDBLOCK
;
7120 /* always use binary mode for sockets */
7121 int res
= pfn_recv (SOCK_HANDLE (fd
), buffer
, count
, 0);
7122 if (res
== SOCKET_ERROR
)
7124 DebPrint (("sys_read.recv failed with error %d on socket %ld\n",
7125 pfn_WSAGetLastError (), SOCK_HANDLE (fd
)));
7135 int nread
= _read (fd
, buffer
, count
);
7138 else if (nchars
== 0)
7143 fd_info
[fd
].flags
|= FILE_AT_EOF
;
7144 /* Perform text mode translation if required. */
7145 else if ((fd_info
[fd
].flags
& FILE_BINARY
) == 0)
7147 nchars
= crlf_to_lf (nchars
, orig_buffer
);
7148 /* If buffer contains only CR, return that. To be absolutely
7149 sure we should attempt to read the next char, but in
7150 practice a CR to be followed by LF would not appear by
7151 itself in the buffer. */
7152 if (nchars
> 1 && orig_buffer
[nchars
- 1] == 0x0d)
7154 fd_info
[fd
].flags
|= FILE_LAST_CR
;
7160 nchars
= _read (fd
, buffer
, count
);
7165 /* From w32xfns.c */
7166 extern HANDLE interrupt_handle
;
7168 /* For now, don't bother with a non-blocking mode */
7170 sys_write (int fd
, const void * buffer
, unsigned int count
)
7180 if (fd
< MAXDESC
&& fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
| FILE_SERIAL
))
7182 if ((fd_info
[fd
].flags
& FILE_WRITE
) == 0)
7188 /* Perform text mode translation if required. */
7189 if ((fd_info
[fd
].flags
& FILE_BINARY
) == 0)
7191 char * tmpbuf
= alloca (count
* 2);
7192 unsigned char * src
= (void *)buffer
;
7193 unsigned char * dst
= tmpbuf
;
7198 unsigned char *next
;
7199 /* copy next line or remaining bytes */
7200 next
= _memccpy (dst
, src
, '\n', nbytes
);
7203 /* copied one line ending with '\n' */
7204 int copied
= next
- dst
;
7207 /* insert '\r' before '\n' */
7214 /* copied remaining partial line -> now finished */
7221 if (fd
< MAXDESC
&& fd_info
[fd
].flags
& FILE_SERIAL
)
7223 HANDLE hnd
= (HANDLE
) _get_osfhandle (fd
);
7224 OVERLAPPED
*ovl
= &fd_info
[fd
].cp
->ovl_write
;
7225 HANDLE wait_hnd
[2] = { interrupt_handle
, ovl
->hEvent
};
7228 if (!WriteFile (hnd
, buffer
, count
, (DWORD
*) &nchars
, ovl
))
7230 if (GetLastError () != ERROR_IO_PENDING
)
7235 if (detect_input_pending ())
7236 active
= MsgWaitForMultipleObjects (2, wait_hnd
, FALSE
, INFINITE
,
7239 active
= WaitForMultipleObjects (2, wait_hnd
, FALSE
, INFINITE
);
7240 if (active
== WAIT_OBJECT_0
)
7241 { /* User pressed C-g, cancel write, then leave. Don't bother
7242 cleaning up as we may only get stuck in buggy drivers. */
7243 PurgeComm (hnd
, PURGE_TXABORT
| PURGE_TXCLEAR
);
7248 if (active
== WAIT_OBJECT_0
+ 1
7249 && !GetOverlappedResult (hnd
, ovl
, (DWORD
*) &nchars
, TRUE
))
7256 else if (fd
< MAXDESC
&& fd_info
[fd
].flags
& FILE_SOCKET
)
7258 unsigned long nblock
= 0;
7259 if (winsock_lib
== NULL
) emacs_abort ();
7261 /* TODO: implement select() properly so non-blocking I/O works. */
7262 /* For now, make sure the write blocks. */
7263 if (fd_info
[fd
].flags
& FILE_NDELAY
)
7264 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
7266 nchars
= pfn_send (SOCK_HANDLE (fd
), buffer
, count
, 0);
7268 /* Set the socket back to non-blocking if it was before,
7269 for other operations that support it. */
7270 if (fd_info
[fd
].flags
& FILE_NDELAY
)
7273 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
7276 if (nchars
== SOCKET_ERROR
)
7278 DebPrint (("sys_write.send failed with error %d on socket %ld\n",
7279 pfn_WSAGetLastError (), SOCK_HANDLE (fd
)));
7285 /* Some networked filesystems don't like too large writes, so
7286 break them into smaller chunks. See the Comments section of
7287 the MSDN documentation of WriteFile for details behind the
7288 choice of the value of CHUNK below. See also the thread
7289 http://thread.gmane.org/gmane.comp.version-control.git/145294
7290 in the git mailing list. */
7291 const unsigned char *p
= buffer
;
7292 const unsigned chunk
= 30 * 1024 * 1024;
7297 unsigned this_chunk
= count
< chunk
? count
: chunk
;
7298 int n
= _write (fd
, p
, this_chunk
);
7306 else if (n
< this_chunk
)
7316 /* The Windows CRT functions are "optimized for speed", so they don't
7317 check for timezone and DST changes if they were last called less
7318 than 1 minute ago (see http://support.microsoft.com/kb/821231). So
7319 all Emacs features that repeatedly call time functions (e.g.,
7320 display-time) are in real danger of missing timezone and DST
7321 changes. Calling tzset before each localtime call fixes that. */
7323 sys_localtime (const time_t *t
)
7326 return localtime (t
);
7331 /* Try loading LIBRARY_ID from the file(s) specified in
7332 Vdynamic_library_alist. If the library is loaded successfully,
7333 return the handle of the DLL, and record the filename in the
7334 property :loaded-from of LIBRARY_ID. If the library could not be
7335 found, or when it was already loaded (because the handle is not
7336 recorded anywhere, and so is lost after use), return NULL.
7338 We could also save the handle in :loaded-from, but currently
7339 there's no use case for it. */
7341 w32_delayed_load (Lisp_Object library_id
)
7343 HMODULE library_dll
= NULL
;
7345 CHECK_SYMBOL (library_id
);
7347 if (CONSP (Vdynamic_library_alist
)
7348 && NILP (Fassq (library_id
, Vlibrary_cache
)))
7350 Lisp_Object found
= Qnil
;
7351 Lisp_Object dlls
= Fassq (library_id
, Vdynamic_library_alist
);
7354 for (dlls
= XCDR (dlls
); CONSP (dlls
); dlls
= XCDR (dlls
))
7356 CHECK_STRING_CAR (dlls
);
7357 if ((library_dll
= LoadLibrary (SDATA (XCAR (dlls
)))))
7359 char name
[MAX_PATH
];
7362 len
= GetModuleFileNameA (library_dll
, name
, sizeof (name
));
7363 found
= Fcons (XCAR (dlls
),
7365 /* Possibly truncated */
7366 ? make_specified_string (name
, -1, len
, 1)
7372 Fput (library_id
, QCloaded_from
, found
);
7380 check_windows_init_file (void)
7382 /* A common indication that Emacs is not installed properly is when
7383 it cannot find the Windows installation file. If this file does
7384 not exist in the expected place, tell the user. */
7386 if (!noninteractive
&& !inhibit_window_system
7387 /* Vload_path is not yet initialized when we are loading
7389 && NILP (Vpurify_flag
))
7391 Lisp_Object init_file
;
7394 init_file
= build_string ("term/w32-win");
7395 fd
= openp (Vload_path
, init_file
, Fget_load_suffixes (), NULL
, Qnil
);
7398 Lisp_Object load_path_print
= Fprin1_to_string (Vload_path
, Qnil
);
7399 char *init_file_name
= SDATA (init_file
);
7400 char *load_path
= SDATA (load_path_print
);
7401 char *buffer
= alloca (1024
7402 + strlen (init_file_name
)
7403 + strlen (load_path
));
7406 "The Emacs Windows initialization file \"%s.el\" "
7407 "could not be found in your Emacs installation. "
7408 "Emacs checked the following directories for this file:\n"
7410 "When Emacs cannot find this file, it usually means that it "
7411 "was not installed properly, or its distribution file was "
7412 "not unpacked properly.\nSee the README.W32 file in the "
7413 "top-level Emacs directory for more information.",
7414 init_file_name
, load_path
);
7417 "Emacs Abort Dialog",
7418 MB_OK
| MB_ICONEXCLAMATION
| MB_TASKMODAL
);
7419 /* Use the low-level system abort. */
7430 term_ntproc (int ignored
)
7436 /* shutdown the socket interface if necessary */
7443 init_ntproc (int dumping
)
7445 sigset_t initial_mask
= 0;
7447 /* Initialize the socket interface now if available and requested by
7448 the user by defining PRELOAD_WINSOCK; otherwise loading will be
7449 delayed until open-network-stream is called (w32-has-winsock can
7450 also be used to dynamically load or reload winsock).
7452 Conveniently, init_environment is called before us, so
7453 PRELOAD_WINSOCK can be set in the registry. */
7455 /* Always initialize this correctly. */
7458 if (getenv ("PRELOAD_WINSOCK") != NULL
)
7459 init_winsock (TRUE
);
7461 /* Initial preparation for subprocess support: replace our standard
7462 handles with non-inheritable versions. */
7465 HANDLE stdin_save
= INVALID_HANDLE_VALUE
;
7466 HANDLE stdout_save
= INVALID_HANDLE_VALUE
;
7467 HANDLE stderr_save
= INVALID_HANDLE_VALUE
;
7469 parent
= GetCurrentProcess ();
7471 /* ignore errors when duplicating and closing; typically the
7472 handles will be invalid when running as a gui program. */
7473 DuplicateHandle (parent
,
7474 GetStdHandle (STD_INPUT_HANDLE
),
7479 DUPLICATE_SAME_ACCESS
);
7481 DuplicateHandle (parent
,
7482 GetStdHandle (STD_OUTPUT_HANDLE
),
7487 DUPLICATE_SAME_ACCESS
);
7489 DuplicateHandle (parent
,
7490 GetStdHandle (STD_ERROR_HANDLE
),
7495 DUPLICATE_SAME_ACCESS
);
7501 if (stdin_save
!= INVALID_HANDLE_VALUE
)
7502 _open_osfhandle ((intptr_t) stdin_save
, O_TEXT
);
7504 _open ("nul", O_TEXT
| O_NOINHERIT
| O_RDONLY
);
7507 if (stdout_save
!= INVALID_HANDLE_VALUE
)
7508 _open_osfhandle ((intptr_t) stdout_save
, O_TEXT
);
7510 _open ("nul", O_TEXT
| O_NOINHERIT
| O_WRONLY
);
7513 if (stderr_save
!= INVALID_HANDLE_VALUE
)
7514 _open_osfhandle ((intptr_t) stderr_save
, O_TEXT
);
7516 _open ("nul", O_TEXT
| O_NOINHERIT
| O_WRONLY
);
7520 /* unfortunately, atexit depends on implementation of malloc */
7521 /* atexit (term_ntproc); */
7524 /* Make sure we start with all signals unblocked. */
7525 sigprocmask (SIG_SETMASK
, &initial_mask
, NULL
);
7526 signal (SIGABRT
, term_ntproc
);
7530 /* determine which drives are fixed, for GetCachedVolumeInformation */
7532 /* GetDriveType must have trailing backslash. */
7533 char drive
[] = "A:\\";
7535 /* Loop over all possible drive letters */
7536 while (*drive
<= 'Z')
7538 /* Record if this drive letter refers to a fixed drive. */
7539 fixed_drives
[DRIVE_INDEX (*drive
)] =
7540 (GetDriveType (drive
) == DRIVE_FIXED
);
7545 /* Reset the volume info cache. */
7546 volume_cache
= NULL
;
7551 shutdown_handler ensures that buffers' autosave files are
7552 up to date when the user logs off, or the system shuts down.
7555 shutdown_handler (DWORD type
)
7557 /* Ctrl-C and Ctrl-Break are already suppressed, so don't handle them. */
7558 if (type
== CTRL_CLOSE_EVENT
/* User closes console window. */
7559 || type
== CTRL_LOGOFF_EVENT
/* User logs off. */
7560 || type
== CTRL_SHUTDOWN_EVENT
) /* User shutsdown. */
7562 /* Shut down cleanly, making sure autosave files are up to date. */
7563 shut_down_emacs (0, Qnil
);
7566 /* Allow other handlers to handle this signal. */
7571 globals_of_w32 is used to initialize those global variables that
7572 must always be initialized on startup even when the global variable
7573 initialized is non zero (see the function main in emacs.c).
7576 globals_of_w32 (void)
7578 HMODULE kernel32
= GetModuleHandle ("kernel32.dll");
7580 get_process_times_fn
= (GetProcessTimes_Proc
)
7581 GetProcAddress (kernel32
, "GetProcessTimes");
7583 DEFSYM (QCloaded_from
, ":loaded-from");
7585 g_b_init_is_windows_9x
= 0;
7586 g_b_init_open_process_token
= 0;
7587 g_b_init_get_token_information
= 0;
7588 g_b_init_lookup_account_sid
= 0;
7589 g_b_init_get_sid_sub_authority
= 0;
7590 g_b_init_get_sid_sub_authority_count
= 0;
7591 g_b_init_get_security_info
= 0;
7592 g_b_init_get_file_security
= 0;
7593 g_b_init_get_security_descriptor_owner
= 0;
7594 g_b_init_get_security_descriptor_group
= 0;
7595 g_b_init_is_valid_sid
= 0;
7596 g_b_init_create_toolhelp32_snapshot
= 0;
7597 g_b_init_process32_first
= 0;
7598 g_b_init_process32_next
= 0;
7599 g_b_init_open_thread_token
= 0;
7600 g_b_init_impersonate_self
= 0;
7601 g_b_init_revert_to_self
= 0;
7602 g_b_init_get_process_memory_info
= 0;
7603 g_b_init_get_process_working_set_size
= 0;
7604 g_b_init_global_memory_status
= 0;
7605 g_b_init_global_memory_status_ex
= 0;
7606 g_b_init_equal_sid
= 0;
7607 g_b_init_copy_sid
= 0;
7608 g_b_init_get_length_sid
= 0;
7609 g_b_init_get_native_system_info
= 0;
7610 g_b_init_get_system_times
= 0;
7611 g_b_init_create_symbolic_link
= 0;
7612 g_b_init_get_security_descriptor_dacl
= 0;
7613 g_b_init_convert_sd_to_sddl
= 0;
7614 g_b_init_convert_sddl_to_sd
= 0;
7615 g_b_init_is_valid_security_descriptor
= 0;
7616 g_b_init_set_file_security
= 0;
7617 num_of_processors
= 0;
7618 /* The following sets a handler for shutdown notifications for
7619 console apps. This actually applies to Emacs in both console and
7620 GUI modes, since we had to fool windows into thinking emacs is a
7621 console application to get console mode to work. */
7622 SetConsoleCtrlHandler (shutdown_handler
, TRUE
);
7624 /* "None" is the default group name on standalone workstations. */
7625 strcpy (dflt_group_name
, "None");
7627 /* Reset, in case it has some value inherited from dump time. */
7628 w32_stat_get_owner_group
= 0;
7631 /* For make-serial-process */
7633 serial_open (char *port
)
7639 hnd
= CreateFile (port
, GENERIC_READ
| GENERIC_WRITE
, 0, 0,
7640 OPEN_EXISTING
, FILE_FLAG_OVERLAPPED
, 0);
7641 if (hnd
== INVALID_HANDLE_VALUE
)
7642 error ("Could not open %s", port
);
7643 fd
= (int) _open_osfhandle ((intptr_t) hnd
, 0);
7645 error ("Could not open %s", port
);
7649 error ("Could not create child process");
7651 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
7652 fd_info
[ fd
].hnd
= hnd
;
7653 fd_info
[ fd
].flags
|=
7654 FILE_READ
| FILE_WRITE
| FILE_BINARY
| FILE_SERIAL
;
7655 if (fd_info
[ fd
].cp
!= NULL
)
7657 error ("fd_info[fd = %d] is already in use", fd
);
7659 fd_info
[ fd
].cp
= cp
;
7660 cp
->ovl_read
.hEvent
= CreateEvent (NULL
, TRUE
, FALSE
, NULL
);
7661 if (cp
->ovl_read
.hEvent
== NULL
)
7662 error ("Could not create read event");
7663 cp
->ovl_write
.hEvent
= CreateEvent (NULL
, TRUE
, FALSE
, NULL
);
7664 if (cp
->ovl_write
.hEvent
== NULL
)
7665 error ("Could not create write event");
7670 /* For serial-process-configure */
7672 serial_configure (struct Lisp_Process
*p
, Lisp_Object contact
)
7674 Lisp_Object childp2
= Qnil
;
7675 Lisp_Object tem
= Qnil
;
7679 char summary
[4] = "???"; /* This usually becomes "8N1". */
7681 if ((fd_info
[ p
->outfd
].flags
& FILE_SERIAL
) == 0)
7682 error ("Not a serial process");
7683 hnd
= fd_info
[ p
->outfd
].hnd
;
7685 childp2
= Fcopy_sequence (p
->childp
);
7687 /* Initialize timeouts for blocking read and blocking write. */
7688 if (!GetCommTimeouts (hnd
, &ct
))
7689 error ("GetCommTimeouts() failed");
7690 ct
.ReadIntervalTimeout
= 0;
7691 ct
.ReadTotalTimeoutMultiplier
= 0;
7692 ct
.ReadTotalTimeoutConstant
= 0;
7693 ct
.WriteTotalTimeoutMultiplier
= 0;
7694 ct
.WriteTotalTimeoutConstant
= 0;
7695 if (!SetCommTimeouts (hnd
, &ct
))
7696 error ("SetCommTimeouts() failed");
7697 /* Read port attributes and prepare default configuration. */
7698 memset (&dcb
, 0, sizeof (dcb
));
7699 dcb
.DCBlength
= sizeof (DCB
);
7700 if (!GetCommState (hnd
, &dcb
))
7701 error ("GetCommState() failed");
7704 dcb
.fAbortOnError
= FALSE
;
7705 /* dcb.XonLim and dcb.XoffLim are set by GetCommState() */
7710 /* Configure speed. */
7711 if (!NILP (Fplist_member (contact
, QCspeed
)))
7712 tem
= Fplist_get (contact
, QCspeed
);
7714 tem
= Fplist_get (p
->childp
, QCspeed
);
7716 dcb
.BaudRate
= XINT (tem
);
7717 childp2
= Fplist_put (childp2
, QCspeed
, tem
);
7719 /* Configure bytesize. */
7720 if (!NILP (Fplist_member (contact
, QCbytesize
)))
7721 tem
= Fplist_get (contact
, QCbytesize
);
7723 tem
= Fplist_get (p
->childp
, QCbytesize
);
7725 tem
= make_number (8);
7727 if (XINT (tem
) != 7 && XINT (tem
) != 8)
7728 error (":bytesize must be nil (8), 7, or 8");
7729 dcb
.ByteSize
= XINT (tem
);
7730 summary
[0] = XINT (tem
) + '0';
7731 childp2
= Fplist_put (childp2
, QCbytesize
, tem
);
7733 /* Configure parity. */
7734 if (!NILP (Fplist_member (contact
, QCparity
)))
7735 tem
= Fplist_get (contact
, QCparity
);
7737 tem
= Fplist_get (p
->childp
, QCparity
);
7738 if (!NILP (tem
) && !EQ (tem
, Qeven
) && !EQ (tem
, Qodd
))
7739 error (":parity must be nil (no parity), `even', or `odd'");
7740 dcb
.fParity
= FALSE
;
7741 dcb
.Parity
= NOPARITY
;
7742 dcb
.fErrorChar
= FALSE
;
7747 else if (EQ (tem
, Qeven
))
7751 dcb
.Parity
= EVENPARITY
;
7752 dcb
.fErrorChar
= TRUE
;
7754 else if (EQ (tem
, Qodd
))
7758 dcb
.Parity
= ODDPARITY
;
7759 dcb
.fErrorChar
= TRUE
;
7761 childp2
= Fplist_put (childp2
, QCparity
, tem
);
7763 /* Configure stopbits. */
7764 if (!NILP (Fplist_member (contact
, QCstopbits
)))
7765 tem
= Fplist_get (contact
, QCstopbits
);
7767 tem
= Fplist_get (p
->childp
, QCstopbits
);
7769 tem
= make_number (1);
7771 if (XINT (tem
) != 1 && XINT (tem
) != 2)
7772 error (":stopbits must be nil (1 stopbit), 1, or 2");
7773 summary
[2] = XINT (tem
) + '0';
7774 if (XINT (tem
) == 1)
7775 dcb
.StopBits
= ONESTOPBIT
;
7776 else if (XINT (tem
) == 2)
7777 dcb
.StopBits
= TWOSTOPBITS
;
7778 childp2
= Fplist_put (childp2
, QCstopbits
, tem
);
7780 /* Configure flowcontrol. */
7781 if (!NILP (Fplist_member (contact
, QCflowcontrol
)))
7782 tem
= Fplist_get (contact
, QCflowcontrol
);
7784 tem
= Fplist_get (p
->childp
, QCflowcontrol
);
7785 if (!NILP (tem
) && !EQ (tem
, Qhw
) && !EQ (tem
, Qsw
))
7786 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
7787 dcb
.fOutxCtsFlow
= FALSE
;
7788 dcb
.fOutxDsrFlow
= FALSE
;
7789 dcb
.fDtrControl
= DTR_CONTROL_DISABLE
;
7790 dcb
.fDsrSensitivity
= FALSE
;
7791 dcb
.fTXContinueOnXoff
= FALSE
;
7794 dcb
.fRtsControl
= RTS_CONTROL_DISABLE
;
7795 dcb
.XonChar
= 17; /* Control-Q */
7796 dcb
.XoffChar
= 19; /* Control-S */
7799 /* Already configured. */
7801 else if (EQ (tem
, Qhw
))
7803 dcb
.fRtsControl
= RTS_CONTROL_HANDSHAKE
;
7804 dcb
.fOutxCtsFlow
= TRUE
;
7806 else if (EQ (tem
, Qsw
))
7811 childp2
= Fplist_put (childp2
, QCflowcontrol
, tem
);
7813 /* Activate configuration. */
7814 if (!SetCommState (hnd
, &dcb
))
7815 error ("SetCommState() failed");
7817 childp2
= Fplist_put (childp2
, QCsummary
, build_string (summary
));
7818 pset_childp (p
, childp2
);
7824 emacs_gnutls_pull (gnutls_transport_ptr_t p
, void* buf
, size_t sz
)
7829 struct Lisp_Process
*process
= (struct Lisp_Process
*)p
;
7830 int fd
= process
->infd
;
7832 n
= sys_read (fd
, (char*)buf
, sz
);
7839 /* Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
7840 if (err
== EWOULDBLOCK
)
7843 emacs_gnutls_transport_set_errno (process
->gnutls_state
, err
);
7849 emacs_gnutls_push (gnutls_transport_ptr_t p
, const void* buf
, size_t sz
)
7851 struct Lisp_Process
*process
= (struct Lisp_Process
*)p
;
7852 int fd
= process
->outfd
;
7853 ssize_t n
= sys_write (fd
, buf
, sz
);
7855 /* 0 or more bytes written means everything went fine. */
7859 /* Negative bytes written means we got an error in errno.
7860 Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
7861 emacs_gnutls_transport_set_errno (process
->gnutls_state
,
7862 errno
== EWOULDBLOCK
? EAGAIN
: errno
);
7866 #endif /* HAVE_GNUTLS */