1 /* Utility and Unix shadow routines for GNU Emacs on the Microsoft Windows API.
3 Copyright (C) 1994-1995, 2000-2016 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or (at
10 your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
21 Geoff Voelker (voelker@cs.washington.edu) 7-29-94
24 #include <mingw_time.h>
25 #include <stddef.h> /* for offsetof */
28 #include <float.h> /* for DBL_EPSILON */
35 #include <time.h> /* must be before nt/inc/sys/time.h, for MinGW64 */
37 #include <sys/utime.h>
40 /* must include CRT headers *before* config.h */
43 #include <mbstring.h> /* for _mbspbrk, _mbslwr, _mbsrchr, ... */
70 #include "epaths.h" /* for PATH_EXEC */
75 /* MinGW64 defines these in its _mingw.h. */
76 #ifndef _ANONYMOUS_UNION
77 # define _ANONYMOUS_UNION
79 #ifndef _ANONYMOUS_STRUCT
80 # define _ANONYMOUS_STRUCT
83 /* Some versions of compiler define MEMORYSTATUSEX, some don't, so we
84 use a different name to avoid compilation problems. */
85 typedef struct _MEMORY_STATUS_EX
{
88 DWORDLONG ullTotalPhys
;
89 DWORDLONG ullAvailPhys
;
90 DWORDLONG ullTotalPageFile
;
91 DWORDLONG ullAvailPageFile
;
92 DWORDLONG ullTotalVirtual
;
93 DWORDLONG ullAvailVirtual
;
94 DWORDLONG ullAvailExtendedVirtual
;
95 } MEMORY_STATUS_EX
,*LPMEMORY_STATUS_EX
;
97 /* These are here so that GDB would know about these data types. This
98 allows attaching GDB to Emacs when a fatal exception is triggered
99 and Windows pops up the "application needs to be closed" dialog.
100 At that point, _gnu_exception_handler, the top-level exception
101 handler installed by the MinGW startup code, is somewhere on the
102 call-stack of the main thread, so going to that call frame and
103 looking at the argument to _gnu_exception_handler, which is a
104 PEXCEPTION_POINTERS pointer, can reveal the exception code
105 (excptr->ExceptionRecord->ExceptionCode) and the address where the
106 exception happened (excptr->ExceptionRecord->ExceptionAddress), as
107 well as some additional information specific to the exception. */
108 PEXCEPTION_POINTERS excptr
;
109 PEXCEPTION_RECORD excprec
;
115 #include <tlhelp32.h>
120 #if _WIN32_WINNT < 0x0500
121 #if !defined (__MINGW32__) || __W32API_MAJOR_VERSION < 3 || (__W32API_MAJOR_VERSION == 3 && __W32API_MINOR_VERSION < 15)
122 /* This either is not in psapi.h or guarded by higher value of
123 _WIN32_WINNT than what we use. w32api supplied with MinGW 3.15
124 defines it in psapi.h */
125 typedef struct _PROCESS_MEMORY_COUNTERS_EX
{
127 DWORD PageFaultCount
;
128 SIZE_T PeakWorkingSetSize
;
129 SIZE_T WorkingSetSize
;
130 SIZE_T QuotaPeakPagedPoolUsage
;
131 SIZE_T QuotaPagedPoolUsage
;
132 SIZE_T QuotaPeakNonPagedPoolUsage
;
133 SIZE_T QuotaNonPagedPoolUsage
;
134 SIZE_T PagefileUsage
;
135 SIZE_T PeakPagefileUsage
;
137 } PROCESS_MEMORY_COUNTERS_EX
,*PPROCESS_MEMORY_COUNTERS_EX
;
141 #include <winioctl.h>
148 /* This is not in MinGW's sddl.h (but they are in MSVC headers), so we
149 define them by hand if not already defined. */
150 #ifndef SDDL_REVISION_1
151 #define SDDL_REVISION_1 1
152 #endif /* SDDL_REVISION_1 */
154 #if defined(_MSC_VER) || defined(MINGW_W64)
155 /* MSVC and MinGW64 don't provide the definition of
156 REPARSE_DATA_BUFFER and the associated macros, except on ntifs.h,
157 which cannot be included because it triggers conflicts with other
158 Windows API headers. So we define it here by hand. */
160 typedef struct _REPARSE_DATA_BUFFER
{
162 USHORT ReparseDataLength
;
166 USHORT SubstituteNameOffset
;
167 USHORT SubstituteNameLength
;
168 USHORT PrintNameOffset
;
169 USHORT PrintNameLength
;
172 } SymbolicLinkReparseBuffer
;
174 USHORT SubstituteNameOffset
;
175 USHORT SubstituteNameLength
;
176 USHORT PrintNameOffset
;
177 USHORT PrintNameLength
;
179 } MountPointReparseBuffer
;
182 } GenericReparseBuffer
;
184 } REPARSE_DATA_BUFFER
, *PREPARSE_DATA_BUFFER
;
186 #ifndef FILE_DEVICE_FILE_SYSTEM
187 #define FILE_DEVICE_FILE_SYSTEM 9
189 #ifndef METHOD_BUFFERED
190 #define METHOD_BUFFERED 0
192 #ifndef FILE_ANY_ACCESS
193 #define FILE_ANY_ACCESS 0x00000000
196 #define CTL_CODE(t,f,m,a) (((t)<<16)|((a)<<14)|((f)<<2)|(m))
198 /* MinGW64 defines FSCTL_GET_REPARSE_POINT on winioctl.h. */
199 #ifndef FSCTL_GET_REPARSE_POINT
200 #define FSCTL_GET_REPARSE_POINT \
201 CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 42, METHOD_BUFFERED, FILE_ANY_ACCESS)
205 /* TCP connection support. */
206 #include <sys/socket.h>
225 #include <iphlpapi.h> /* should be after winsock2.h */
227 #include <wincrypt.h>
229 #include <c-strcase.h>
233 #include "w32common.h"
234 #include "w32select.h"
235 #include "systime.h" /* for current_timespec, struct timespec */
236 #include "dispextern.h" /* for xstrcasecmp */
237 #include "coding.h" /* for Vlocale_coding_system */
239 #include "careadlinkat.h"
240 #include "allocator.h"
242 /* For Lisp_Process, serial_configure and serial_open. */
246 typedef HRESULT (WINAPI
* ShGetFolderPath_fn
)
247 (IN HWND
, IN
int, IN HANDLE
, IN DWORD
, OUT
char *);
249 void globals_of_w32 (void);
250 static DWORD
get_rid (PSID
);
251 static int is_symlink (const char *);
252 static char * chase_symlinks (const char *);
253 static int enable_privilege (LPCTSTR
, BOOL
, TOKEN_PRIVILEGES
*);
254 static int restore_privilege (TOKEN_PRIVILEGES
*);
255 static BOOL WINAPI
revert_to_self (void);
257 static int sys_access (const char *, int);
258 extern void *e_malloc (size_t);
259 extern int sys_select (int, SELECT_TYPE
*, SELECT_TYPE
*, SELECT_TYPE
*,
260 struct timespec
*, void *);
261 extern int sys_dup (int);
266 /* Initialization states.
268 WARNING: If you add any more such variables for additional APIs,
269 you MUST add initialization for them to globals_of_w32
270 below. This is because these variables might get set
271 to non-NULL values during dumping, but the dumped Emacs
272 cannot reuse those values, because it could be run on a
273 different version of the OS, where API addresses are
275 static BOOL g_b_init_is_windows_9x
;
276 static BOOL g_b_init_open_process_token
;
277 static BOOL g_b_init_get_token_information
;
278 static BOOL g_b_init_lookup_account_sid
;
279 static BOOL g_b_init_get_sid_sub_authority
;
280 static BOOL g_b_init_get_sid_sub_authority_count
;
281 static BOOL g_b_init_get_security_info
;
282 static BOOL g_b_init_get_file_security_w
;
283 static BOOL g_b_init_get_file_security_a
;
284 static BOOL g_b_init_get_security_descriptor_owner
;
285 static BOOL g_b_init_get_security_descriptor_group
;
286 static BOOL g_b_init_is_valid_sid
;
287 static BOOL g_b_init_create_toolhelp32_snapshot
;
288 static BOOL g_b_init_process32_first
;
289 static BOOL g_b_init_process32_next
;
290 static BOOL g_b_init_open_thread_token
;
291 static BOOL g_b_init_impersonate_self
;
292 static BOOL g_b_init_revert_to_self
;
293 static BOOL g_b_init_get_process_memory_info
;
294 static BOOL g_b_init_get_process_working_set_size
;
295 static BOOL g_b_init_global_memory_status
;
296 static BOOL g_b_init_global_memory_status_ex
;
297 static BOOL g_b_init_get_length_sid
;
298 static BOOL g_b_init_equal_sid
;
299 static BOOL g_b_init_copy_sid
;
300 static BOOL g_b_init_get_native_system_info
;
301 static BOOL g_b_init_get_system_times
;
302 static BOOL g_b_init_create_symbolic_link_w
;
303 static BOOL g_b_init_create_symbolic_link_a
;
304 static BOOL g_b_init_get_security_descriptor_dacl
;
305 static BOOL g_b_init_convert_sd_to_sddl
;
306 static BOOL g_b_init_convert_sddl_to_sd
;
307 static BOOL g_b_init_is_valid_security_descriptor
;
308 static BOOL g_b_init_set_file_security_w
;
309 static BOOL g_b_init_set_file_security_a
;
310 static BOOL g_b_init_set_named_security_info_w
;
311 static BOOL g_b_init_set_named_security_info_a
;
312 static BOOL g_b_init_get_adapters_info
;
314 BOOL g_b_init_compare_string_w
;
317 BEGIN: Wrapper functions around OpenProcessToken
318 and other functions in advapi32.dll that are only
319 supported in Windows NT / 2k / XP
321 /* ** Function pointer typedefs ** */
322 typedef BOOL (WINAPI
* OpenProcessToken_Proc
) (
323 HANDLE ProcessHandle
,
325 PHANDLE TokenHandle
);
326 typedef BOOL (WINAPI
* GetTokenInformation_Proc
) (
328 TOKEN_INFORMATION_CLASS TokenInformationClass
,
329 LPVOID TokenInformation
,
330 DWORD TokenInformationLength
,
331 PDWORD ReturnLength
);
332 typedef BOOL (WINAPI
* GetProcessTimes_Proc
) (
333 HANDLE process_handle
,
334 LPFILETIME creation_time
,
335 LPFILETIME exit_time
,
336 LPFILETIME kernel_time
,
337 LPFILETIME user_time
);
339 GetProcessTimes_Proc get_process_times_fn
= NULL
;
342 const char * const LookupAccountSid_Name
= "LookupAccountSidW";
344 const char * const LookupAccountSid_Name
= "LookupAccountSidA";
346 typedef BOOL (WINAPI
* LookupAccountSid_Proc
) (
347 LPCTSTR lpSystemName
,
352 LPDWORD cbDomainName
,
353 PSID_NAME_USE peUse
);
354 typedef PDWORD (WINAPI
* GetSidSubAuthority_Proc
) (
357 typedef PUCHAR (WINAPI
* GetSidSubAuthorityCount_Proc
) (
359 typedef DWORD (WINAPI
* GetSecurityInfo_Proc
) (
361 SE_OBJECT_TYPE ObjectType
,
362 SECURITY_INFORMATION SecurityInfo
,
367 PSECURITY_DESCRIPTOR
*ppSecurityDescriptor
);
368 typedef BOOL (WINAPI
* GetFileSecurityW_Proc
) (
370 SECURITY_INFORMATION RequestedInformation
,
371 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
373 LPDWORD lpnLengthNeeded
);
374 typedef BOOL (WINAPI
* GetFileSecurityA_Proc
) (
376 SECURITY_INFORMATION RequestedInformation
,
377 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
379 LPDWORD lpnLengthNeeded
);
380 typedef BOOL (WINAPI
*SetFileSecurityW_Proc
) (
382 SECURITY_INFORMATION SecurityInformation
,
383 PSECURITY_DESCRIPTOR pSecurityDescriptor
);
384 typedef BOOL (WINAPI
*SetFileSecurityA_Proc
) (
386 SECURITY_INFORMATION SecurityInformation
,
387 PSECURITY_DESCRIPTOR pSecurityDescriptor
);
388 typedef DWORD (WINAPI
*SetNamedSecurityInfoW_Proc
) (
389 LPCWSTR lpObjectName
,
390 SE_OBJECT_TYPE ObjectType
,
391 SECURITY_INFORMATION SecurityInformation
,
396 typedef DWORD (WINAPI
*SetNamedSecurityInfoA_Proc
) (
398 SE_OBJECT_TYPE ObjectType
,
399 SECURITY_INFORMATION SecurityInformation
,
404 typedef BOOL (WINAPI
* GetSecurityDescriptorOwner_Proc
) (
405 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
407 LPBOOL lpbOwnerDefaulted
);
408 typedef BOOL (WINAPI
* GetSecurityDescriptorGroup_Proc
) (
409 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
411 LPBOOL lpbGroupDefaulted
);
412 typedef BOOL (WINAPI
*GetSecurityDescriptorDacl_Proc
) (
413 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
414 LPBOOL lpbDaclPresent
,
416 LPBOOL lpbDaclDefaulted
);
417 typedef BOOL (WINAPI
* IsValidSid_Proc
) (
419 typedef HANDLE (WINAPI
* CreateToolhelp32Snapshot_Proc
) (
421 DWORD th32ProcessID
);
422 typedef BOOL (WINAPI
* Process32First_Proc
) (
424 LPPROCESSENTRY32 lppe
);
425 typedef BOOL (WINAPI
* Process32Next_Proc
) (
427 LPPROCESSENTRY32 lppe
);
428 typedef BOOL (WINAPI
* OpenThreadToken_Proc
) (
432 PHANDLE TokenHandle
);
433 typedef BOOL (WINAPI
* ImpersonateSelf_Proc
) (
434 SECURITY_IMPERSONATION_LEVEL ImpersonationLevel
);
435 typedef BOOL (WINAPI
* RevertToSelf_Proc
) (void);
436 typedef BOOL (WINAPI
* GetProcessMemoryInfo_Proc
) (
438 PPROCESS_MEMORY_COUNTERS ppsmemCounters
,
440 typedef BOOL (WINAPI
* GetProcessWorkingSetSize_Proc
) (
442 PSIZE_T lpMinimumWorkingSetSize
,
443 PSIZE_T lpMaximumWorkingSetSize
);
444 typedef BOOL (WINAPI
* GlobalMemoryStatus_Proc
) (
445 LPMEMORYSTATUS lpBuffer
);
446 typedef BOOL (WINAPI
* GlobalMemoryStatusEx_Proc
) (
447 LPMEMORY_STATUS_EX lpBuffer
);
448 typedef BOOL (WINAPI
* CopySid_Proc
) (
449 DWORD nDestinationSidLength
,
450 PSID pDestinationSid
,
452 typedef BOOL (WINAPI
* EqualSid_Proc
) (
455 typedef DWORD (WINAPI
* GetLengthSid_Proc
) (
457 typedef void (WINAPI
* GetNativeSystemInfo_Proc
) (
458 LPSYSTEM_INFO lpSystemInfo
);
459 typedef BOOL (WINAPI
* GetSystemTimes_Proc
) (
460 LPFILETIME lpIdleTime
,
461 LPFILETIME lpKernelTime
,
462 LPFILETIME lpUserTime
);
463 typedef BOOLEAN (WINAPI
*CreateSymbolicLinkW_Proc
) (
464 LPCWSTR lpSymlinkFileName
,
465 LPCWSTR lpTargetFileName
,
467 typedef BOOLEAN (WINAPI
*CreateSymbolicLinkA_Proc
) (
468 LPCSTR lpSymlinkFileName
,
469 LPCSTR lpTargetFileName
,
471 typedef BOOL (WINAPI
*ConvertStringSecurityDescriptorToSecurityDescriptor_Proc
) (
472 LPCTSTR StringSecurityDescriptor
,
473 DWORD StringSDRevision
,
474 PSECURITY_DESCRIPTOR
*SecurityDescriptor
,
475 PULONG SecurityDescriptorSize
);
476 typedef BOOL (WINAPI
*ConvertSecurityDescriptorToStringSecurityDescriptor_Proc
) (
477 PSECURITY_DESCRIPTOR SecurityDescriptor
,
478 DWORD RequestedStringSDRevision
,
479 SECURITY_INFORMATION SecurityInformation
,
480 LPTSTR
*StringSecurityDescriptor
,
481 PULONG StringSecurityDescriptorLen
);
482 typedef BOOL (WINAPI
*IsValidSecurityDescriptor_Proc
) (PSECURITY_DESCRIPTOR
);
483 typedef DWORD (WINAPI
*GetAdaptersInfo_Proc
) (
484 PIP_ADAPTER_INFO pAdapterInfo
,
487 int (WINAPI
*pMultiByteToWideChar
)(UINT
,DWORD
,LPCSTR
,int,LPWSTR
,int);
488 int (WINAPI
*pWideCharToMultiByte
)(UINT
,DWORD
,LPCWSTR
,int,LPSTR
,int,LPCSTR
,LPBOOL
);
489 DWORD multiByteToWideCharFlags
;
491 /* ** A utility function ** */
495 static BOOL s_b_ret
= 0;
496 OSVERSIONINFO os_ver
;
497 if (g_b_init_is_windows_9x
== 0)
499 g_b_init_is_windows_9x
= 1;
500 ZeroMemory (&os_ver
, sizeof (OSVERSIONINFO
));
501 os_ver
.dwOSVersionInfoSize
= sizeof (OSVERSIONINFO
);
502 if (GetVersionEx (&os_ver
))
504 s_b_ret
= (os_ver
.dwPlatformId
== VER_PLATFORM_WIN32_WINDOWS
);
510 static Lisp_Object
ltime (ULONGLONG
);
512 /* Get total user and system times for get-internal-run-time.
513 Returns a list of integers if the times are provided by the OS
514 (NT derivatives), otherwise it returns the result of current-time. */
516 w32_get_internal_run_time (void)
518 if (get_process_times_fn
)
520 FILETIME create
, exit
, kernel
, user
;
521 HANDLE proc
= GetCurrentProcess ();
522 if ((*get_process_times_fn
) (proc
, &create
, &exit
, &kernel
, &user
))
524 LARGE_INTEGER user_int
, kernel_int
, total
;
525 user_int
.LowPart
= user
.dwLowDateTime
;
526 user_int
.HighPart
= user
.dwHighDateTime
;
527 kernel_int
.LowPart
= kernel
.dwLowDateTime
;
528 kernel_int
.HighPart
= kernel
.dwHighDateTime
;
529 total
.QuadPart
= user_int
.QuadPart
+ kernel_int
.QuadPart
;
530 return ltime (total
.QuadPart
);
534 return Fcurrent_time ();
537 /* ** The wrapper functions ** */
540 open_process_token (HANDLE ProcessHandle
,
544 static OpenProcessToken_Proc s_pfn_Open_Process_Token
= NULL
;
545 HMODULE hm_advapi32
= NULL
;
546 if (is_windows_9x () == TRUE
)
550 if (g_b_init_open_process_token
== 0)
552 g_b_init_open_process_token
= 1;
553 hm_advapi32
= LoadLibrary ("Advapi32.dll");
554 s_pfn_Open_Process_Token
=
555 (OpenProcessToken_Proc
) GetProcAddress (hm_advapi32
, "OpenProcessToken");
557 if (s_pfn_Open_Process_Token
== NULL
)
562 s_pfn_Open_Process_Token (
570 get_token_information (HANDLE TokenHandle
,
571 TOKEN_INFORMATION_CLASS TokenInformationClass
,
572 LPVOID TokenInformation
,
573 DWORD TokenInformationLength
,
576 static GetTokenInformation_Proc s_pfn_Get_Token_Information
= NULL
;
577 HMODULE hm_advapi32
= NULL
;
578 if (is_windows_9x () == TRUE
)
582 if (g_b_init_get_token_information
== 0)
584 g_b_init_get_token_information
= 1;
585 hm_advapi32
= LoadLibrary ("Advapi32.dll");
586 s_pfn_Get_Token_Information
=
587 (GetTokenInformation_Proc
) GetProcAddress (hm_advapi32
, "GetTokenInformation");
589 if (s_pfn_Get_Token_Information
== NULL
)
594 s_pfn_Get_Token_Information (
596 TokenInformationClass
,
598 TokenInformationLength
,
604 lookup_account_sid (LPCTSTR lpSystemName
,
609 LPDWORD cbDomainName
,
612 static LookupAccountSid_Proc s_pfn_Lookup_Account_Sid
= NULL
;
613 HMODULE hm_advapi32
= NULL
;
614 if (is_windows_9x () == TRUE
)
618 if (g_b_init_lookup_account_sid
== 0)
620 g_b_init_lookup_account_sid
= 1;
621 hm_advapi32
= LoadLibrary ("Advapi32.dll");
622 s_pfn_Lookup_Account_Sid
=
623 (LookupAccountSid_Proc
) GetProcAddress (hm_advapi32
, LookupAccountSid_Name
);
625 if (s_pfn_Lookup_Account_Sid
== NULL
)
630 s_pfn_Lookup_Account_Sid (
642 get_sid_sub_authority (PSID pSid
, DWORD n
)
644 static GetSidSubAuthority_Proc s_pfn_Get_Sid_Sub_Authority
= NULL
;
645 static DWORD zero
= 0U;
646 HMODULE hm_advapi32
= NULL
;
647 if (is_windows_9x () == TRUE
)
651 if (g_b_init_get_sid_sub_authority
== 0)
653 g_b_init_get_sid_sub_authority
= 1;
654 hm_advapi32
= LoadLibrary ("Advapi32.dll");
655 s_pfn_Get_Sid_Sub_Authority
=
656 (GetSidSubAuthority_Proc
) GetProcAddress (
657 hm_advapi32
, "GetSidSubAuthority");
659 if (s_pfn_Get_Sid_Sub_Authority
== NULL
)
663 return (s_pfn_Get_Sid_Sub_Authority (pSid
, n
));
667 get_sid_sub_authority_count (PSID pSid
)
669 static GetSidSubAuthorityCount_Proc s_pfn_Get_Sid_Sub_Authority_Count
= NULL
;
670 static UCHAR zero
= 0U;
671 HMODULE hm_advapi32
= NULL
;
672 if (is_windows_9x () == TRUE
)
676 if (g_b_init_get_sid_sub_authority_count
== 0)
678 g_b_init_get_sid_sub_authority_count
= 1;
679 hm_advapi32
= LoadLibrary ("Advapi32.dll");
680 s_pfn_Get_Sid_Sub_Authority_Count
=
681 (GetSidSubAuthorityCount_Proc
) GetProcAddress (
682 hm_advapi32
, "GetSidSubAuthorityCount");
684 if (s_pfn_Get_Sid_Sub_Authority_Count
== NULL
)
688 return (s_pfn_Get_Sid_Sub_Authority_Count (pSid
));
692 get_security_info (HANDLE handle
,
693 SE_OBJECT_TYPE ObjectType
,
694 SECURITY_INFORMATION SecurityInfo
,
699 PSECURITY_DESCRIPTOR
*ppSecurityDescriptor
)
701 static GetSecurityInfo_Proc s_pfn_Get_Security_Info
= NULL
;
702 HMODULE hm_advapi32
= NULL
;
703 if (is_windows_9x () == TRUE
)
707 if (g_b_init_get_security_info
== 0)
709 g_b_init_get_security_info
= 1;
710 hm_advapi32
= LoadLibrary ("Advapi32.dll");
711 s_pfn_Get_Security_Info
=
712 (GetSecurityInfo_Proc
) GetProcAddress (
713 hm_advapi32
, "GetSecurityInfo");
715 if (s_pfn_Get_Security_Info
== NULL
)
719 return (s_pfn_Get_Security_Info (handle
, ObjectType
, SecurityInfo
,
720 ppsidOwner
, ppsidGroup
, ppDacl
, ppSacl
,
721 ppSecurityDescriptor
));
725 get_file_security (const char *lpFileName
,
726 SECURITY_INFORMATION RequestedInformation
,
727 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
729 LPDWORD lpnLengthNeeded
)
731 static GetFileSecurityA_Proc s_pfn_Get_File_SecurityA
= NULL
;
732 static GetFileSecurityW_Proc s_pfn_Get_File_SecurityW
= NULL
;
733 HMODULE hm_advapi32
= NULL
;
734 if (is_windows_9x () == TRUE
)
739 if (w32_unicode_filenames
)
741 wchar_t filename_w
[MAX_PATH
];
743 if (g_b_init_get_file_security_w
== 0)
745 g_b_init_get_file_security_w
= 1;
746 hm_advapi32
= LoadLibrary ("Advapi32.dll");
747 s_pfn_Get_File_SecurityW
=
748 (GetFileSecurityW_Proc
) GetProcAddress (hm_advapi32
,
751 if (s_pfn_Get_File_SecurityW
== NULL
)
756 filename_to_utf16 (lpFileName
, filename_w
);
757 return (s_pfn_Get_File_SecurityW (filename_w
, RequestedInformation
,
758 pSecurityDescriptor
, nLength
,
763 char filename_a
[MAX_PATH
];
765 if (g_b_init_get_file_security_a
== 0)
767 g_b_init_get_file_security_a
= 1;
768 hm_advapi32
= LoadLibrary ("Advapi32.dll");
769 s_pfn_Get_File_SecurityA
=
770 (GetFileSecurityA_Proc
) GetProcAddress (hm_advapi32
,
773 if (s_pfn_Get_File_SecurityA
== NULL
)
778 filename_to_ansi (lpFileName
, filename_a
);
779 return (s_pfn_Get_File_SecurityA (filename_a
, RequestedInformation
,
780 pSecurityDescriptor
, nLength
,
786 set_file_security (const char *lpFileName
,
787 SECURITY_INFORMATION SecurityInformation
,
788 PSECURITY_DESCRIPTOR pSecurityDescriptor
)
790 static SetFileSecurityW_Proc s_pfn_Set_File_SecurityW
= NULL
;
791 static SetFileSecurityA_Proc s_pfn_Set_File_SecurityA
= NULL
;
792 HMODULE hm_advapi32
= NULL
;
793 if (is_windows_9x () == TRUE
)
798 if (w32_unicode_filenames
)
800 wchar_t filename_w
[MAX_PATH
];
802 if (g_b_init_set_file_security_w
== 0)
804 g_b_init_set_file_security_w
= 1;
805 hm_advapi32
= LoadLibrary ("Advapi32.dll");
806 s_pfn_Set_File_SecurityW
=
807 (SetFileSecurityW_Proc
) GetProcAddress (hm_advapi32
,
810 if (s_pfn_Set_File_SecurityW
== NULL
)
815 filename_to_utf16 (lpFileName
, filename_w
);
816 return (s_pfn_Set_File_SecurityW (filename_w
, SecurityInformation
,
817 pSecurityDescriptor
));
821 char filename_a
[MAX_PATH
];
823 if (g_b_init_set_file_security_a
== 0)
825 g_b_init_set_file_security_a
= 1;
826 hm_advapi32
= LoadLibrary ("Advapi32.dll");
827 s_pfn_Set_File_SecurityA
=
828 (SetFileSecurityA_Proc
) GetProcAddress (hm_advapi32
,
831 if (s_pfn_Set_File_SecurityA
== NULL
)
836 filename_to_ansi (lpFileName
, filename_a
);
837 return (s_pfn_Set_File_SecurityA (filename_a
, SecurityInformation
,
838 pSecurityDescriptor
));
843 set_named_security_info (LPCTSTR lpObjectName
,
844 SE_OBJECT_TYPE ObjectType
,
845 SECURITY_INFORMATION SecurityInformation
,
851 static SetNamedSecurityInfoW_Proc s_pfn_Set_Named_Security_InfoW
= NULL
;
852 static SetNamedSecurityInfoA_Proc s_pfn_Set_Named_Security_InfoA
= NULL
;
853 HMODULE hm_advapi32
= NULL
;
854 if (is_windows_9x () == TRUE
)
859 if (w32_unicode_filenames
)
861 wchar_t filename_w
[MAX_PATH
];
863 if (g_b_init_set_named_security_info_w
== 0)
865 g_b_init_set_named_security_info_w
= 1;
866 hm_advapi32
= LoadLibrary ("Advapi32.dll");
867 s_pfn_Set_Named_Security_InfoW
=
868 (SetNamedSecurityInfoW_Proc
) GetProcAddress (hm_advapi32
,
869 "SetNamedSecurityInfoW");
871 if (s_pfn_Set_Named_Security_InfoW
== NULL
)
876 filename_to_utf16 (lpObjectName
, filename_w
);
877 return (s_pfn_Set_Named_Security_InfoW (filename_w
, ObjectType
,
878 SecurityInformation
, psidOwner
,
879 psidGroup
, pDacl
, pSacl
));
883 char filename_a
[MAX_PATH
];
885 if (g_b_init_set_named_security_info_a
== 0)
887 g_b_init_set_named_security_info_a
= 1;
888 hm_advapi32
= LoadLibrary ("Advapi32.dll");
889 s_pfn_Set_Named_Security_InfoA
=
890 (SetNamedSecurityInfoA_Proc
) GetProcAddress (hm_advapi32
,
891 "SetNamedSecurityInfoA");
893 if (s_pfn_Set_Named_Security_InfoA
== NULL
)
898 filename_to_ansi (lpObjectName
, filename_a
);
899 return (s_pfn_Set_Named_Security_InfoA (filename_a
, ObjectType
,
900 SecurityInformation
, psidOwner
,
901 psidGroup
, pDacl
, pSacl
));
906 get_security_descriptor_owner (PSECURITY_DESCRIPTOR pSecurityDescriptor
,
908 LPBOOL lpbOwnerDefaulted
)
910 static GetSecurityDescriptorOwner_Proc s_pfn_Get_Security_Descriptor_Owner
= NULL
;
911 HMODULE hm_advapi32
= NULL
;
912 if (is_windows_9x () == TRUE
)
917 if (g_b_init_get_security_descriptor_owner
== 0)
919 g_b_init_get_security_descriptor_owner
= 1;
920 hm_advapi32
= LoadLibrary ("Advapi32.dll");
921 s_pfn_Get_Security_Descriptor_Owner
=
922 (GetSecurityDescriptorOwner_Proc
) GetProcAddress (
923 hm_advapi32
, "GetSecurityDescriptorOwner");
925 if (s_pfn_Get_Security_Descriptor_Owner
== NULL
)
930 return (s_pfn_Get_Security_Descriptor_Owner (pSecurityDescriptor
, pOwner
,
935 get_security_descriptor_group (PSECURITY_DESCRIPTOR pSecurityDescriptor
,
937 LPBOOL lpbGroupDefaulted
)
939 static GetSecurityDescriptorGroup_Proc s_pfn_Get_Security_Descriptor_Group
= NULL
;
940 HMODULE hm_advapi32
= NULL
;
941 if (is_windows_9x () == TRUE
)
946 if (g_b_init_get_security_descriptor_group
== 0)
948 g_b_init_get_security_descriptor_group
= 1;
949 hm_advapi32
= LoadLibrary ("Advapi32.dll");
950 s_pfn_Get_Security_Descriptor_Group
=
951 (GetSecurityDescriptorGroup_Proc
) GetProcAddress (
952 hm_advapi32
, "GetSecurityDescriptorGroup");
954 if (s_pfn_Get_Security_Descriptor_Group
== NULL
)
959 return (s_pfn_Get_Security_Descriptor_Group (pSecurityDescriptor
, pGroup
,
964 get_security_descriptor_dacl (PSECURITY_DESCRIPTOR pSecurityDescriptor
,
965 LPBOOL lpbDaclPresent
,
967 LPBOOL lpbDaclDefaulted
)
969 static GetSecurityDescriptorDacl_Proc s_pfn_Get_Security_Descriptor_Dacl
= NULL
;
970 HMODULE hm_advapi32
= NULL
;
971 if (is_windows_9x () == TRUE
)
976 if (g_b_init_get_security_descriptor_dacl
== 0)
978 g_b_init_get_security_descriptor_dacl
= 1;
979 hm_advapi32
= LoadLibrary ("Advapi32.dll");
980 s_pfn_Get_Security_Descriptor_Dacl
=
981 (GetSecurityDescriptorDacl_Proc
) GetProcAddress (
982 hm_advapi32
, "GetSecurityDescriptorDacl");
984 if (s_pfn_Get_Security_Descriptor_Dacl
== NULL
)
989 return (s_pfn_Get_Security_Descriptor_Dacl (pSecurityDescriptor
,
990 lpbDaclPresent
, pDacl
,
995 is_valid_sid (PSID sid
)
997 static IsValidSid_Proc s_pfn_Is_Valid_Sid
= NULL
;
998 HMODULE hm_advapi32
= NULL
;
999 if (is_windows_9x () == TRUE
)
1003 if (g_b_init_is_valid_sid
== 0)
1005 g_b_init_is_valid_sid
= 1;
1006 hm_advapi32
= LoadLibrary ("Advapi32.dll");
1007 s_pfn_Is_Valid_Sid
=
1008 (IsValidSid_Proc
) GetProcAddress (
1009 hm_advapi32
, "IsValidSid");
1011 if (s_pfn_Is_Valid_Sid
== NULL
)
1015 return (s_pfn_Is_Valid_Sid (sid
));
1019 equal_sid (PSID sid1
, PSID sid2
)
1021 static EqualSid_Proc s_pfn_Equal_Sid
= NULL
;
1022 HMODULE hm_advapi32
= NULL
;
1023 if (is_windows_9x () == TRUE
)
1027 if (g_b_init_equal_sid
== 0)
1029 g_b_init_equal_sid
= 1;
1030 hm_advapi32
= LoadLibrary ("Advapi32.dll");
1032 (EqualSid_Proc
) GetProcAddress (
1033 hm_advapi32
, "EqualSid");
1035 if (s_pfn_Equal_Sid
== NULL
)
1039 return (s_pfn_Equal_Sid (sid1
, sid2
));
1043 get_length_sid (PSID sid
)
1045 static GetLengthSid_Proc s_pfn_Get_Length_Sid
= NULL
;
1046 HMODULE hm_advapi32
= NULL
;
1047 if (is_windows_9x () == TRUE
)
1051 if (g_b_init_get_length_sid
== 0)
1053 g_b_init_get_length_sid
= 1;
1054 hm_advapi32
= LoadLibrary ("Advapi32.dll");
1055 s_pfn_Get_Length_Sid
=
1056 (GetLengthSid_Proc
) GetProcAddress (
1057 hm_advapi32
, "GetLengthSid");
1059 if (s_pfn_Get_Length_Sid
== NULL
)
1063 return (s_pfn_Get_Length_Sid (sid
));
1067 copy_sid (DWORD destlen
, PSID dest
, PSID src
)
1069 static CopySid_Proc s_pfn_Copy_Sid
= NULL
;
1070 HMODULE hm_advapi32
= NULL
;
1071 if (is_windows_9x () == TRUE
)
1075 if (g_b_init_copy_sid
== 0)
1077 g_b_init_copy_sid
= 1;
1078 hm_advapi32
= LoadLibrary ("Advapi32.dll");
1080 (CopySid_Proc
) GetProcAddress (
1081 hm_advapi32
, "CopySid");
1083 if (s_pfn_Copy_Sid
== NULL
)
1087 return (s_pfn_Copy_Sid (destlen
, dest
, src
));
1091 END: Wrapper functions around OpenProcessToken
1092 and other functions in advapi32.dll that are only
1093 supported in Windows NT / 2k / XP
1097 get_native_system_info (LPSYSTEM_INFO lpSystemInfo
)
1099 static GetNativeSystemInfo_Proc s_pfn_Get_Native_System_Info
= NULL
;
1100 if (is_windows_9x () != TRUE
)
1102 if (g_b_init_get_native_system_info
== 0)
1104 g_b_init_get_native_system_info
= 1;
1105 s_pfn_Get_Native_System_Info
=
1106 (GetNativeSystemInfo_Proc
)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1107 "GetNativeSystemInfo");
1109 if (s_pfn_Get_Native_System_Info
!= NULL
)
1110 s_pfn_Get_Native_System_Info (lpSystemInfo
);
1113 lpSystemInfo
->dwNumberOfProcessors
= -1;
1117 get_system_times (LPFILETIME lpIdleTime
,
1118 LPFILETIME lpKernelTime
,
1119 LPFILETIME lpUserTime
)
1121 static GetSystemTimes_Proc s_pfn_Get_System_times
= NULL
;
1122 if (is_windows_9x () == TRUE
)
1126 if (g_b_init_get_system_times
== 0)
1128 g_b_init_get_system_times
= 1;
1129 s_pfn_Get_System_times
=
1130 (GetSystemTimes_Proc
)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1133 if (s_pfn_Get_System_times
== NULL
)
1135 return (s_pfn_Get_System_times (lpIdleTime
, lpKernelTime
, lpUserTime
));
1138 static BOOLEAN WINAPI
1139 create_symbolic_link (LPCSTR lpSymlinkFilename
,
1140 LPCSTR lpTargetFileName
,
1143 static CreateSymbolicLinkW_Proc s_pfn_Create_Symbolic_LinkW
= NULL
;
1144 static CreateSymbolicLinkA_Proc s_pfn_Create_Symbolic_LinkA
= NULL
;
1147 if (is_windows_9x () == TRUE
)
1152 if (w32_unicode_filenames
)
1154 wchar_t symfn_w
[MAX_PATH
], tgtfn_w
[MAX_PATH
];
1156 if (g_b_init_create_symbolic_link_w
== 0)
1158 g_b_init_create_symbolic_link_w
= 1;
1159 s_pfn_Create_Symbolic_LinkW
=
1160 (CreateSymbolicLinkW_Proc
)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1161 "CreateSymbolicLinkW");
1163 if (s_pfn_Create_Symbolic_LinkW
== NULL
)
1169 filename_to_utf16 (lpSymlinkFilename
, symfn_w
);
1170 filename_to_utf16 (lpTargetFileName
, tgtfn_w
);
1171 retval
= s_pfn_Create_Symbolic_LinkW (symfn_w
, tgtfn_w
, dwFlags
);
1172 /* If we were denied creation of the symlink, try again after
1173 enabling the SeCreateSymbolicLinkPrivilege for our process. */
1176 TOKEN_PRIVILEGES priv_current
;
1178 if (enable_privilege (SE_CREATE_SYMBOLIC_LINK_NAME
, TRUE
,
1181 retval
= s_pfn_Create_Symbolic_LinkW (symfn_w
, tgtfn_w
, dwFlags
);
1182 restore_privilege (&priv_current
);
1189 char symfn_a
[MAX_PATH
], tgtfn_a
[MAX_PATH
];
1191 if (g_b_init_create_symbolic_link_a
== 0)
1193 g_b_init_create_symbolic_link_a
= 1;
1194 s_pfn_Create_Symbolic_LinkA
=
1195 (CreateSymbolicLinkA_Proc
)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1196 "CreateSymbolicLinkA");
1198 if (s_pfn_Create_Symbolic_LinkA
== NULL
)
1204 filename_to_ansi (lpSymlinkFilename
, symfn_a
);
1205 filename_to_ansi (lpTargetFileName
, tgtfn_a
);
1206 retval
= s_pfn_Create_Symbolic_LinkA (symfn_a
, tgtfn_a
, dwFlags
);
1207 /* If we were denied creation of the symlink, try again after
1208 enabling the SeCreateSymbolicLinkPrivilege for our process. */
1211 TOKEN_PRIVILEGES priv_current
;
1213 if (enable_privilege (SE_CREATE_SYMBOLIC_LINK_NAME
, TRUE
,
1216 retval
= s_pfn_Create_Symbolic_LinkA (symfn_a
, tgtfn_a
, dwFlags
);
1217 restore_privilege (&priv_current
);
1226 is_valid_security_descriptor (PSECURITY_DESCRIPTOR pSecurityDescriptor
)
1228 static IsValidSecurityDescriptor_Proc s_pfn_Is_Valid_Security_Descriptor_Proc
= NULL
;
1230 if (is_windows_9x () == TRUE
)
1236 if (g_b_init_is_valid_security_descriptor
== 0)
1238 g_b_init_is_valid_security_descriptor
= 1;
1239 s_pfn_Is_Valid_Security_Descriptor_Proc
=
1240 (IsValidSecurityDescriptor_Proc
)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1241 "IsValidSecurityDescriptor");
1243 if (s_pfn_Is_Valid_Security_Descriptor_Proc
== NULL
)
1249 return s_pfn_Is_Valid_Security_Descriptor_Proc (pSecurityDescriptor
);
1253 convert_sd_to_sddl (PSECURITY_DESCRIPTOR SecurityDescriptor
,
1254 DWORD RequestedStringSDRevision
,
1255 SECURITY_INFORMATION SecurityInformation
,
1256 LPTSTR
*StringSecurityDescriptor
,
1257 PULONG StringSecurityDescriptorLen
)
1259 static ConvertSecurityDescriptorToStringSecurityDescriptor_Proc s_pfn_Convert_SD_To_SDDL
= NULL
;
1262 if (is_windows_9x () == TRUE
)
1268 if (g_b_init_convert_sd_to_sddl
== 0)
1270 g_b_init_convert_sd_to_sddl
= 1;
1272 s_pfn_Convert_SD_To_SDDL
=
1273 (ConvertSecurityDescriptorToStringSecurityDescriptor_Proc
)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1274 "ConvertSecurityDescriptorToStringSecurityDescriptorW");
1276 s_pfn_Convert_SD_To_SDDL
=
1277 (ConvertSecurityDescriptorToStringSecurityDescriptor_Proc
)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1278 "ConvertSecurityDescriptorToStringSecurityDescriptorA");
1281 if (s_pfn_Convert_SD_To_SDDL
== NULL
)
1287 retval
= s_pfn_Convert_SD_To_SDDL (SecurityDescriptor
,
1288 RequestedStringSDRevision
,
1289 SecurityInformation
,
1290 StringSecurityDescriptor
,
1291 StringSecurityDescriptorLen
);
1297 convert_sddl_to_sd (LPCTSTR StringSecurityDescriptor
,
1298 DWORD StringSDRevision
,
1299 PSECURITY_DESCRIPTOR
*SecurityDescriptor
,
1300 PULONG SecurityDescriptorSize
)
1302 static ConvertStringSecurityDescriptorToSecurityDescriptor_Proc s_pfn_Convert_SDDL_To_SD
= NULL
;
1305 if (is_windows_9x () == TRUE
)
1311 if (g_b_init_convert_sddl_to_sd
== 0)
1313 g_b_init_convert_sddl_to_sd
= 1;
1315 s_pfn_Convert_SDDL_To_SD
=
1316 (ConvertStringSecurityDescriptorToSecurityDescriptor_Proc
)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1317 "ConvertStringSecurityDescriptorToSecurityDescriptorW");
1319 s_pfn_Convert_SDDL_To_SD
=
1320 (ConvertStringSecurityDescriptorToSecurityDescriptor_Proc
)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1321 "ConvertStringSecurityDescriptorToSecurityDescriptorA");
1324 if (s_pfn_Convert_SDDL_To_SD
== NULL
)
1330 retval
= s_pfn_Convert_SDDL_To_SD (StringSecurityDescriptor
,
1333 SecurityDescriptorSize
);
1339 get_adapters_info (PIP_ADAPTER_INFO pAdapterInfo
, PULONG pOutBufLen
)
1341 static GetAdaptersInfo_Proc s_pfn_Get_Adapters_Info
= NULL
;
1342 HMODULE hm_iphlpapi
= NULL
;
1344 if (is_windows_9x () == TRUE
)
1345 return ERROR_NOT_SUPPORTED
;
1347 if (g_b_init_get_adapters_info
== 0)
1349 g_b_init_get_adapters_info
= 1;
1350 hm_iphlpapi
= LoadLibrary ("Iphlpapi.dll");
1352 s_pfn_Get_Adapters_Info
= (GetAdaptersInfo_Proc
)
1353 GetProcAddress (hm_iphlpapi
, "GetAdaptersInfo");
1355 if (s_pfn_Get_Adapters_Info
== NULL
)
1356 return ERROR_NOT_SUPPORTED
;
1357 return s_pfn_Get_Adapters_Info (pAdapterInfo
, pOutBufLen
);
1362 /* Return 1 if P is a valid pointer to an object of size SIZE. Return
1363 0 if P is NOT a valid pointer. Return -1 if we cannot validate P.
1365 This is called from alloc.c:valid_pointer_p. */
1367 w32_valid_pointer_p (void *p
, int size
)
1370 HANDLE h
= OpenProcess (PROCESS_VM_READ
, FALSE
, GetCurrentProcessId ());
1374 unsigned char *buf
= alloca (size
);
1375 int retval
= ReadProcessMemory (h
, p
, buf
, size
, &done
);
1386 /* Here's an overview of how the Windows build supports file names
1387 that cannot be encoded by the current system codepage.
1389 From the POV of Lisp and layers of C code above the functions here,
1390 Emacs on Windows pretends that its file names are encoded in UTF-8;
1391 see encode_file and decode_file on coding.c. Any file name that is
1392 passed as a unibyte string to C functions defined here is assumed
1393 to be in UTF-8 encoding. Any file name returned by functions
1394 defined here must be in UTF-8 encoding, with only a few exceptions
1395 reserved for a couple of special cases. (Be sure to use
1396 MAX_UTF8_PATH for char arrays that store UTF-8 encoded file names,
1397 as they can be much longer than MAX_PATH!)
1399 The UTF-8 encoded file names cannot be passed to system APIs, as
1400 Windows does not support that. Therefore, they are converted
1401 either to UTF-16 or to the ANSI codepage, depending on the value of
1402 w32-unicode-filenames, before calling any system APIs or CRT library
1403 functions. The default value of that variable is determined by the
1404 OS on which Emacs runs: nil on Windows 9X and t otherwise, but the
1405 user can change that default (although I don't see why would she
1408 The 4 functions defined below, filename_to_utf16, filename_to_ansi,
1409 filename_from_utf16, and filename_from_ansi, are the workhorses of
1410 these conversions. They rely on Windows native APIs
1411 MultiByteToWideChar and WideCharToMultiByte; we cannot use
1412 functions from coding.c here, because they allocate memory, which
1413 is a bad idea on the level of libc, which is what the functions
1414 here emulate. (If you worry about performance due to constant
1415 conversion back and forth from UTF-8 to UTF-16, then don't: first,
1416 it was measured to take only a few microseconds on a not-so-fast
1417 machine, and second, that's exactly what the ANSI APIs we used
1418 before did anyway, because they are just thin wrappers around the
1421 The variables file-name-coding-system and default-file-name-coding-system
1422 still exist, but are actually used only when a file name needs to
1423 be converted to the ANSI codepage. This happens all the time when
1424 w32-unicode-filenames is nil, but can also happen from time to time
1425 when it is t. Otherwise, these variables have no effect on file-name
1426 encoding when w32-unicode-filenames is t; this is similar to
1427 selection-coding-system.
1429 This arrangement works very well, but it has a few gotchas and
1432 . Lisp code that encodes or decodes file names manually should
1433 normally use 'utf-8' as the coding-system on Windows,
1434 disregarding file-name-coding-system. This is a somewhat
1435 unpleasant consequence, but it cannot be avoided. Fortunately,
1436 very few Lisp packages need to do that.
1438 More generally, passing to library functions (e.g., fopen or
1439 opendir) file names already encoded in the ANSI codepage is
1440 explicitly *verboten*, as all those functions, as shadowed and
1441 emulated here, assume they will receive UTF-8 encoded file names.
1443 For the same reasons, no CRT function or Win32 API can be called
1444 directly in Emacs sources, without either converting the file
1445 names from UTF-8 to UTF-16 or ANSI codepage, or going through
1446 some shadowing function defined here.
1448 . Environment variables stored in Vprocess_environment are encoded
1449 in the ANSI codepage, so if getenv/egetenv is used for a variable
1450 whose value is a file name or a list of directories, it needs to
1451 be converted to UTF-8, before it is used as argument to functions
1452 or decoded into a Lisp string.
1454 . File names passed to external libraries, like the image libraries
1455 and GnuTLS, need special handling. These libraries generally
1456 don't support UTF-16 or UTF-8 file names, so they must get file
1457 names encoded in the ANSI codepage. To facilitate using these
1458 libraries with file names that are not encodable in the ANSI
1459 codepage, use the function ansi_encode_filename, which will try
1460 to use the short 8+3 alias of a file name if that file name is
1461 not encodable in the ANSI codepage. See image.c and gnutls.c for
1462 examples of how this should be done.
1464 . Running subprocesses in non-ASCII directories and with non-ASCII
1465 file arguments is limited to the current codepage (even though
1466 Emacs is perfectly capable of finding an executable program file
1467 in a directory whose name cannot be encoded in the current
1468 codepage). This is because the command-line arguments are
1469 encoded _before_ they get to the w32-specific level, and the
1470 encoding is not known in advance (it doesn't have to be the
1471 current ANSI codepage), so w32proc.c functions cannot re-encode
1472 them in UTF-16. This should be fixed, but will also require
1473 changes in cmdproxy. The current limitation is not terribly bad
1474 anyway, since very few, if any, Windows console programs that are
1475 likely to be invoked by Emacs support UTF-16 encoded command
1478 . For similar reasons, server.el and emacsclient are also limited
1479 to the current ANSI codepage for now.
1481 . Emacs itself can only handle command-line arguments encoded in
1482 the current codepage.
1484 . Turning on w32-unicode-filename on Windows 9X (if it at all
1485 works) requires UNICOWS.DLL, which is thus a requirement even in
1486 non-GUI sessions, something the we previously avoided. */
1490 /* Converting file names from UTF-8 to either UTF-16 or the ANSI
1491 codepage defined by file-name-coding-system. */
1493 /* Current codepage for encoding file names. */
1494 static int file_name_codepage
;
1496 /* Produce a Windows ANSI codepage suitable for encoding file names.
1497 Return the information about that codepage in CP_INFO. */
1499 codepage_for_filenames (CPINFO
*cp_info
)
1501 /* A simple cache to avoid calling GetCPInfo every time we need to
1502 encode/decode a file name. The file-name encoding is not
1503 supposed to be changed too frequently, if ever. */
1504 static Lisp_Object last_file_name_encoding
;
1506 Lisp_Object current_encoding
;
1508 current_encoding
= Vfile_name_coding_system
;
1509 if (NILP (current_encoding
))
1510 current_encoding
= Vdefault_file_name_coding_system
;
1512 if (!EQ (last_file_name_encoding
, current_encoding
))
1514 /* Default to the current ANSI codepage. */
1515 file_name_codepage
= w32_ansi_code_page
;
1517 if (NILP (current_encoding
))
1519 char *cpname
= SSDATA (SYMBOL_NAME (current_encoding
));
1520 char *cp
= NULL
, *end
;
1523 if (strncmp (cpname
, "cp", 2) == 0)
1525 else if (strncmp (cpname
, "windows-", 8) == 0)
1531 cpnum
= strtol (cp
, &end
, 10);
1532 if (cpnum
&& *end
== '\0' && end
- cp
>= 2)
1533 file_name_codepage
= cpnum
;
1537 if (!file_name_codepage
)
1538 file_name_codepage
= CP_ACP
; /* CP_ACP = 0, but let's not assume that */
1540 if (!GetCPInfo (file_name_codepage
, &cp
))
1542 file_name_codepage
= CP_ACP
;
1543 if (!GetCPInfo (file_name_codepage
, &cp
))
1550 return file_name_codepage
;
1554 filename_to_utf16 (const char *fn_in
, wchar_t *fn_out
)
1556 int result
= pMultiByteToWideChar (CP_UTF8
, multiByteToWideCharFlags
, fn_in
,
1557 -1, fn_out
, MAX_PATH
);
1561 DWORD err
= GetLastError ();
1565 case ERROR_INVALID_FLAGS
:
1566 case ERROR_INVALID_PARAMETER
:
1569 case ERROR_INSUFFICIENT_BUFFER
:
1570 case ERROR_NO_UNICODE_TRANSLATION
:
1581 filename_from_utf16 (const wchar_t *fn_in
, char *fn_out
)
1583 int result
= pWideCharToMultiByte (CP_UTF8
, 0, fn_in
, -1,
1584 fn_out
, MAX_UTF8_PATH
, NULL
, NULL
);
1588 DWORD err
= GetLastError ();
1592 case ERROR_INVALID_FLAGS
:
1593 case ERROR_INVALID_PARAMETER
:
1596 case ERROR_INSUFFICIENT_BUFFER
:
1597 case ERROR_NO_UNICODE_TRANSLATION
:
1608 filename_to_ansi (const char *fn_in
, char *fn_out
)
1610 wchar_t fn_utf16
[MAX_PATH
];
1612 if (filename_to_utf16 (fn_in
, fn_utf16
) == 0)
1615 int codepage
= codepage_for_filenames (NULL
);
1617 result
= pWideCharToMultiByte (codepage
, 0, fn_utf16
, -1,
1618 fn_out
, MAX_PATH
, NULL
, NULL
);
1621 DWORD err
= GetLastError ();
1625 case ERROR_INVALID_FLAGS
:
1626 case ERROR_INVALID_PARAMETER
:
1629 case ERROR_INSUFFICIENT_BUFFER
:
1630 case ERROR_NO_UNICODE_TRANSLATION
:
1643 filename_from_ansi (const char *fn_in
, char *fn_out
)
1645 wchar_t fn_utf16
[MAX_PATH
];
1646 int codepage
= codepage_for_filenames (NULL
);
1647 int result
= pMultiByteToWideChar (codepage
, multiByteToWideCharFlags
, fn_in
,
1648 -1, fn_utf16
, MAX_PATH
);
1652 DWORD err
= GetLastError ();
1656 case ERROR_INVALID_FLAGS
:
1657 case ERROR_INVALID_PARAMETER
:
1660 case ERROR_INSUFFICIENT_BUFFER
:
1661 case ERROR_NO_UNICODE_TRANSLATION
:
1668 return filename_from_utf16 (fn_utf16
, fn_out
);
1673 /* The directory where we started, in UTF-8. */
1674 static char startup_dir
[MAX_UTF8_PATH
];
1676 /* Get the current working directory. */
1678 getcwd (char *dir
, int dirsize
)
1685 if (dirsize
<= strlen (startup_dir
))
1691 if (GetCurrentDirectory (MAXPATHLEN
, dir
) > 0)
1695 /* Emacs doesn't actually change directory itself, it stays in the
1696 same directory where it was started. */
1697 strcpy (dir
, startup_dir
);
1702 /* Emulate getloadavg. */
1704 struct load_sample
{
1711 /* Number of processors on this machine. */
1712 static unsigned num_of_processors
;
1714 /* We maintain 1-sec samples for the last 16 minutes in a circular buffer. */
1715 static struct load_sample samples
[16*60];
1716 static int first_idx
= -1, last_idx
= -1;
1717 static int max_idx
= ARRAYELTS (samples
);
1722 int next_idx
= from
+ 1;
1724 if (next_idx
>= max_idx
)
1733 int prev_idx
= from
- 1;
1736 prev_idx
= max_idx
- 1;
1742 sample_system_load (ULONGLONG
*idle
, ULONGLONG
*kernel
, ULONGLONG
*user
)
1744 SYSTEM_INFO sysinfo
;
1745 FILETIME ft_idle
, ft_user
, ft_kernel
;
1747 /* Initialize the number of processors on this machine. */
1748 if (num_of_processors
<= 0)
1750 get_native_system_info (&sysinfo
);
1751 num_of_processors
= sysinfo
.dwNumberOfProcessors
;
1752 if (num_of_processors
<= 0)
1754 GetSystemInfo (&sysinfo
);
1755 num_of_processors
= sysinfo
.dwNumberOfProcessors
;
1757 if (num_of_processors
<= 0)
1758 num_of_processors
= 1;
1761 /* TODO: Take into account threads that are ready to run, by
1762 sampling the "\System\Processor Queue Length" performance
1763 counter. The code below accounts only for threads that are
1764 actually running. */
1766 if (get_system_times (&ft_idle
, &ft_kernel
, &ft_user
))
1768 ULARGE_INTEGER uidle
, ukernel
, uuser
;
1770 memcpy (&uidle
, &ft_idle
, sizeof (ft_idle
));
1771 memcpy (&ukernel
, &ft_kernel
, sizeof (ft_kernel
));
1772 memcpy (&uuser
, &ft_user
, sizeof (ft_user
));
1773 *idle
= uidle
.QuadPart
;
1774 *kernel
= ukernel
.QuadPart
;
1775 *user
= uuser
.QuadPart
;
1785 /* Produce the load average for a given time interval, using the
1786 samples in the samples[] array. WHICH can be 0, 1, or 2, meaning
1787 1-minute, 5-minute, or 15-minute average, respectively. */
1791 double retval
= -1.0;
1794 double span
= (which
== 0 ? 1.0 : (which
== 1 ? 5.0 : 15.0)) * 60;
1795 time_t now
= samples
[last_idx
].sample_time
;
1797 if (first_idx
!= last_idx
)
1799 for (idx
= buf_prev (last_idx
); ; idx
= buf_prev (idx
))
1801 tdiff
= difftime (now
, samples
[idx
].sample_time
);
1802 if (tdiff
>= span
- 2*DBL_EPSILON
*now
)
1805 samples
[last_idx
].kernel
+ samples
[last_idx
].user
1806 - (samples
[idx
].kernel
+ samples
[idx
].user
);
1807 long double idl
= samples
[last_idx
].idle
- samples
[idx
].idle
;
1809 retval
= (1.0 - idl
/ sys
) * num_of_processors
;
1812 if (idx
== first_idx
)
1821 getloadavg (double loadavg
[], int nelem
)
1824 ULONGLONG idle
, kernel
, user
;
1825 time_t now
= time (NULL
);
1827 /* If system time jumped back for some reason, delete all samples
1828 whose time is later than the current wall-clock time. This
1829 prevents load average figures from becoming frozen for prolonged
1830 periods of time, when system time is reset backwards. */
1833 while (difftime (now
, samples
[last_idx
].sample_time
) < -1.0)
1835 if (last_idx
== first_idx
)
1837 first_idx
= last_idx
= -1;
1840 last_idx
= buf_prev (last_idx
);
1844 /* Store another sample. We ignore samples that are less than 1 sec
1847 || (difftime (now
, samples
[last_idx
].sample_time
)
1848 >= 1.0 - 2*DBL_EPSILON
*now
))
1850 sample_system_load (&idle
, &kernel
, &user
);
1851 last_idx
= buf_next (last_idx
);
1852 samples
[last_idx
].sample_time
= now
;
1853 samples
[last_idx
].idle
= idle
;
1854 samples
[last_idx
].kernel
= kernel
;
1855 samples
[last_idx
].user
= user
;
1856 /* If the buffer has more that 15 min worth of samples, discard
1858 if (first_idx
== -1)
1859 first_idx
= last_idx
;
1860 while (first_idx
!= last_idx
1861 && (difftime (now
, samples
[first_idx
].sample_time
)
1862 >= 15.0*60 + 2*DBL_EPSILON
*now
))
1863 first_idx
= buf_next (first_idx
);
1866 for (elem
= 0; elem
< nelem
; elem
++)
1868 double avg
= getavg (elem
);
1872 loadavg
[elem
] = avg
;
1878 /* Emulate getpwuid, getpwnam and others. */
1880 #define PASSWD_FIELD_SIZE 256
1882 static char dflt_passwd_name
[PASSWD_FIELD_SIZE
];
1883 static char dflt_passwd_passwd
[PASSWD_FIELD_SIZE
];
1884 static char dflt_passwd_gecos
[PASSWD_FIELD_SIZE
];
1885 static char dflt_passwd_dir
[MAX_UTF8_PATH
];
1886 static char dflt_passwd_shell
[MAX_UTF8_PATH
];
1888 static struct passwd dflt_passwd
=
1900 static char dflt_group_name
[GNLEN
+1];
1902 static struct group dflt_group
=
1904 /* When group information is not available, we return this as the
1905 group for all files. */
1913 return dflt_passwd
.pw_uid
;
1919 /* I could imagine arguing for checking to see whether the user is
1920 in the Administrators group and returning a UID of 0 for that
1921 case, but I don't know how wise that would be in the long run. */
1928 return dflt_passwd
.pw_gid
;
1938 getpwuid (unsigned uid
)
1940 if (uid
== dflt_passwd
.pw_uid
)
1941 return &dflt_passwd
;
1946 getgrgid (gid_t gid
)
1952 getpwnam (char *name
)
1956 pw
= getpwuid (getuid ());
1960 if (xstrcasecmp (name
, pw
->pw_name
))
1967 init_user_info (void)
1969 /* Find the user's real name by opening the process token and
1970 looking up the name associated with the user-sid in that token.
1972 Use the relative portion of the identifier authority value from
1973 the user-sid as the user id value (same for group id using the
1974 primary group sid from the process token). */
1976 char uname
[UNLEN
+1], gname
[GNLEN
+1], domain
[1025];
1977 DWORD ulength
= sizeof (uname
), dlength
= sizeof (domain
), needed
;
1978 DWORD glength
= sizeof (gname
);
1979 HANDLE token
= NULL
;
1980 SID_NAME_USE user_type
;
1981 unsigned char *buf
= NULL
;
1983 TOKEN_USER user_token
;
1984 TOKEN_PRIMARY_GROUP group_token
;
1987 result
= open_process_token (GetCurrentProcess (), TOKEN_QUERY
, &token
);
1990 result
= get_token_information (token
, TokenUser
, NULL
, 0, &blen
);
1991 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
1993 buf
= xmalloc (blen
);
1994 result
= get_token_information (token
, TokenUser
,
1995 (LPVOID
)buf
, blen
, &needed
);
1998 memcpy (&user_token
, buf
, sizeof (user_token
));
1999 result
= lookup_account_sid (NULL
, user_token
.User
.Sid
,
2001 domain
, &dlength
, &user_type
);
2009 strcpy (dflt_passwd
.pw_name
, uname
);
2010 /* Determine a reasonable uid value. */
2011 if (xstrcasecmp ("administrator", uname
) == 0)
2013 dflt_passwd
.pw_uid
= 500; /* well-known Administrator uid */
2014 dflt_passwd
.pw_gid
= 513; /* well-known None gid */
2018 /* Use the last sub-authority value of the RID, the relative
2019 portion of the SID, as user/group ID. */
2020 dflt_passwd
.pw_uid
= get_rid (user_token
.User
.Sid
);
2022 /* Get group id and name. */
2023 result
= get_token_information (token
, TokenPrimaryGroup
,
2024 (LPVOID
)buf
, blen
, &needed
);
2025 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
2027 buf
= xrealloc (buf
, blen
= needed
);
2028 result
= get_token_information (token
, TokenPrimaryGroup
,
2029 (LPVOID
)buf
, blen
, &needed
);
2033 memcpy (&group_token
, buf
, sizeof (group_token
));
2034 dflt_passwd
.pw_gid
= get_rid (group_token
.PrimaryGroup
);
2035 dlength
= sizeof (domain
);
2036 /* If we can get at the real Primary Group name, use that.
2037 Otherwise, the default group name was already set to
2038 "None" in globals_of_w32. */
2039 if (lookup_account_sid (NULL
, group_token
.PrimaryGroup
,
2040 gname
, &glength
, NULL
, &dlength
,
2042 strcpy (dflt_group_name
, gname
);
2045 dflt_passwd
.pw_gid
= dflt_passwd
.pw_uid
;
2048 /* If security calls are not supported (presumably because we
2049 are running under Windows 9X), fallback to this: */
2050 else if (GetUserName (uname
, &ulength
))
2052 strcpy (dflt_passwd
.pw_name
, uname
);
2053 if (xstrcasecmp ("administrator", uname
) == 0)
2054 dflt_passwd
.pw_uid
= 0;
2056 dflt_passwd
.pw_uid
= 123;
2057 dflt_passwd
.pw_gid
= dflt_passwd
.pw_uid
;
2061 strcpy (dflt_passwd
.pw_name
, "unknown");
2062 dflt_passwd
.pw_uid
= 123;
2063 dflt_passwd
.pw_gid
= 123;
2065 dflt_group
.gr_gid
= dflt_passwd
.pw_gid
;
2067 /* Set dir and shell from environment variables. */
2068 if (w32_unicode_filenames
)
2070 wchar_t *home
= _wgetenv (L
"HOME");
2071 wchar_t *shell
= _wgetenv (L
"SHELL");
2073 /* Ensure HOME and SHELL are defined. */
2078 filename_from_utf16 (home
, dflt_passwd
.pw_dir
);
2079 filename_from_utf16 (shell
, dflt_passwd
.pw_shell
);
2083 char *home
= getenv ("HOME");
2084 char *shell
= getenv ("SHELL");
2090 filename_from_ansi (home
, dflt_passwd
.pw_dir
);
2091 filename_from_ansi (shell
, dflt_passwd
.pw_shell
);
2096 CloseHandle (token
);
2099 static HCRYPTPROV w32_crypto_hprov
;
2101 w32_init_crypt_random (void)
2103 if (!CryptAcquireContext (&w32_crypto_hprov
, NULL
, NULL
, PROV_RSA_FULL
,
2104 CRYPT_VERIFYCONTEXT
| CRYPT_SILENT
))
2106 DebPrint (("CryptAcquireContext failed with error %x\n",
2108 w32_crypto_hprov
= 0;
2115 w32_init_random (void *buf
, ptrdiff_t buflen
)
2117 if (!w32_crypto_hprov
)
2118 w32_init_crypt_random ();
2119 if (w32_crypto_hprov
)
2121 if (CryptGenRandom (w32_crypto_hprov
, buflen
, (BYTE
*)buf
))
2130 /* rand () on NT gives us 15 random bits...hack together 30 bits. */
2131 return ((rand () << 15) | rand ());
2140 /* Return the maximum length in bytes of a multibyte character
2141 sequence encoded in the current ANSI codepage. This is required to
2142 correctly walk the encoded file names one character at a time. */
2144 max_filename_mbslen (void)
2148 codepage_for_filenames (&cp_info
);
2149 return cp_info
.MaxCharSize
;
2152 /* Normalize filename by converting in-place all of its path
2153 separators to the separator specified by PATH_SEP. */
2156 normalize_filename (register char *fp
, char path_sep
)
2160 /* Always lower-case drive letters a-z, even if the filesystem
2161 preserves case in filenames.
2162 This is so filenames can be compared by string comparison
2163 functions that are case-sensitive. Even case-preserving filesystems
2164 do not distinguish case in drive letters. */
2167 if (*p2
== ':' && *fp
>= 'A' && *fp
<= 'Z')
2175 if ((*fp
== '/' || *fp
== '\\') && *fp
!= path_sep
)
2181 /* Destructively turn backslashes into slashes. */
2183 dostounix_filename (register char *p
)
2185 normalize_filename (p
, '/');
2188 /* Destructively turn slashes into backslashes. */
2190 unixtodos_filename (register char *p
)
2192 normalize_filename (p
, '\\');
2195 /* Remove all CR's that are followed by a LF.
2196 (From msdos.c...probably should figure out a way to share it,
2197 although this code isn't going to ever change.) */
2199 crlf_to_lf (register int n
, register char *buf
)
2201 unsigned char *np
= (unsigned char *)buf
;
2202 unsigned char *startp
= np
;
2203 char *endp
= buf
+ n
;
2207 while (buf
< endp
- 1)
2211 if (*(++buf
) != 0x0a)
2222 /* Parse the root part of file name, if present. Return length and
2223 optionally store pointer to char after root. */
2225 parse_root (const char * name
, const char ** pPath
)
2227 const char * start
= name
;
2232 /* find the root name of the volume if given */
2233 if (isalpha (name
[0]) && name
[1] == ':')
2235 /* skip past drive specifier */
2237 if (IS_DIRECTORY_SEP (name
[0]))
2240 else if (IS_DIRECTORY_SEP (name
[0]) && IS_DIRECTORY_SEP (name
[1]))
2247 if (IS_DIRECTORY_SEP (*name
) && --slashes
== 0)
2252 if (IS_DIRECTORY_SEP (name
[0]))
2259 return name
- start
;
2262 /* Get long base name for name; name is assumed to be absolute. */
2264 get_long_basename (char * name
, char * buf
, int size
)
2266 HANDLE dir_handle
= INVALID_HANDLE_VALUE
;
2267 char fname_utf8
[MAX_UTF8_PATH
];
2271 /* Must be valid filename, no wild cards or other invalid characters. */
2272 if (strpbrk (name
, "*?|<>\""))
2275 if (w32_unicode_filenames
)
2277 wchar_t fname_utf16
[MAX_PATH
];
2278 WIN32_FIND_DATAW find_data_wide
;
2280 filename_to_utf16 (name
, fname_utf16
);
2281 dir_handle
= FindFirstFileW (fname_utf16
, &find_data_wide
);
2282 if (dir_handle
!= INVALID_HANDLE_VALUE
)
2283 cstatus
= filename_from_utf16 (find_data_wide
.cFileName
, fname_utf8
);
2287 char fname_ansi
[MAX_PATH
];
2288 WIN32_FIND_DATAA find_data_ansi
;
2290 filename_to_ansi (name
, fname_ansi
);
2291 /* If the ANSI name includes ? characters, it is not encodable
2292 in the ANSI codepage. In that case, we deliver the question
2293 marks to the caller; calling FindFirstFileA in this case
2294 could return some unrelated file name in the same
2296 if (_mbspbrk (fname_ansi
, "?"))
2298 /* Find the basename of fname_ansi. */
2299 char *p
= strrchr (fname_ansi
, '\\');
2305 cstatus
= filename_from_ansi (p
, fname_utf8
);
2309 dir_handle
= FindFirstFileA (fname_ansi
, &find_data_ansi
);
2310 if (dir_handle
!= INVALID_HANDLE_VALUE
)
2311 cstatus
= filename_from_ansi (find_data_ansi
.cFileName
, fname_utf8
);
2315 if (cstatus
== 0 && (len
= strlen (fname_utf8
)) < size
)
2316 memcpy (buf
, fname_utf8
, len
+ 1);
2320 if (dir_handle
!= INVALID_HANDLE_VALUE
)
2321 FindClose (dir_handle
);
2326 /* Get long name for file, if possible (assumed to be absolute). */
2328 w32_get_long_filename (const char * name
, char * buf
, int size
)
2333 char full
[ MAX_UTF8_PATH
];
2336 len
= strlen (name
);
2337 if (len
>= MAX_UTF8_PATH
)
2340 /* Use local copy for destructive modification. */
2341 memcpy (full
, name
, len
+1);
2342 unixtodos_filename (full
);
2344 /* Copy root part verbatim. */
2345 len
= parse_root (full
, (const char **)&p
);
2346 memcpy (o
, full
, len
);
2351 while (p
!= NULL
&& *p
)
2354 p
= strchr (q
, '\\');
2356 len
= get_long_basename (full
, o
, size
);
2379 w32_get_short_filename (const char * name
, char * buf
, int size
)
2381 if (w32_unicode_filenames
)
2383 wchar_t name_utf16
[MAX_PATH
], short_name
[MAX_PATH
];
2384 unsigned int retval
;
2386 filename_to_utf16 (name
, name_utf16
);
2387 retval
= GetShortPathNameW (name_utf16
, short_name
, size
);
2388 if (retval
&& retval
< size
)
2389 filename_from_utf16 (short_name
, buf
);
2394 char name_ansi
[MAX_PATH
];
2396 filename_to_ansi (name
, name_ansi
);
2397 return GetShortPathNameA (name_ansi
, buf
, size
);
2401 /* Re-encode FILENAME, a UTF-8 encoded unibyte string, using the
2402 MS-Windows ANSI codepage. If FILENAME includes characters not
2403 supported by the ANSI codepage, return the 8+3 alias of FILENAME,
2404 if it exists. This is needed because the w32 build wants to
2405 support file names outside of the system locale, but image
2406 libraries typically don't support wide (a.k.a. "Unicode") APIs
2407 required for that. */
2410 ansi_encode_filename (Lisp_Object filename
)
2412 Lisp_Object encoded_filename
;
2413 char fname
[MAX_PATH
];
2415 filename_to_ansi (SSDATA (filename
), fname
);
2416 if (_mbspbrk (fname
, "?"))
2418 char shortname
[MAX_PATH
];
2420 if (w32_get_short_filename (SSDATA (filename
), shortname
, MAX_PATH
))
2422 dostounix_filename (shortname
);
2423 encoded_filename
= build_string (shortname
);
2426 encoded_filename
= build_unibyte_string (fname
);
2429 encoded_filename
= build_unibyte_string (fname
);
2430 return encoded_filename
;
2434 is_unc_volume (const char *filename
)
2436 const char *ptr
= filename
;
2438 if (!IS_DIRECTORY_SEP (ptr
[0]) || !IS_DIRECTORY_SEP (ptr
[1]) || !ptr
[2])
2441 if (strpbrk (ptr
+ 2, "*?|<>\"\\/"))
2447 /* Emulate the Posix unsetenv. */
2449 unsetenv (const char *name
)
2454 if (name
== NULL
|| *name
== '\0' || strchr (name
, '=') != NULL
)
2459 name_len
= strlen (name
);
2460 /* MS docs says an environment variable cannot be longer than 32K. */
2461 if (name_len
> 32767)
2466 /* It is safe to use 'alloca' with 32K size, since the stack is at
2467 least 2MB, and we set it to 8MB in the link command line. */
2468 var
= alloca (name_len
+ 2);
2469 strncpy (var
, name
, name_len
);
2470 var
[name_len
++] = '=';
2471 var
[name_len
] = '\0';
2472 return _putenv (var
);
2475 /* MS _putenv doesn't support removing a variable when the argument
2476 does not include the '=' character, so we fix that here. */
2478 sys_putenv (char *str
)
2480 const char *const name_end
= strchr (str
, '=');
2482 if (name_end
== NULL
)
2484 /* Remove the variable from the environment. */
2485 return unsetenv (str
);
2488 return _putenv (str
);
2491 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
2494 w32_get_resource (char *key
, LPDWORD lpdwtype
)
2497 HKEY hrootkey
= NULL
;
2500 /* Check both the current user and the local machine to see if
2501 we have any resources. */
2503 if (RegOpenKeyEx (HKEY_CURRENT_USER
, REG_ROOT
, 0, KEY_READ
, &hrootkey
) == ERROR_SUCCESS
)
2507 if (RegQueryValueEx (hrootkey
, key
, NULL
, NULL
, NULL
, &cbData
) == ERROR_SUCCESS
2508 && (lpvalue
= xmalloc (cbData
)) != NULL
2509 && RegQueryValueEx (hrootkey
, key
, NULL
, lpdwtype
, lpvalue
, &cbData
) == ERROR_SUCCESS
)
2511 RegCloseKey (hrootkey
);
2517 RegCloseKey (hrootkey
);
2520 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE
, REG_ROOT
, 0, KEY_READ
, &hrootkey
) == ERROR_SUCCESS
)
2524 if (RegQueryValueEx (hrootkey
, key
, NULL
, NULL
, NULL
, &cbData
) == ERROR_SUCCESS
2525 && (lpvalue
= xmalloc (cbData
)) != NULL
2526 && RegQueryValueEx (hrootkey
, key
, NULL
, lpdwtype
, lpvalue
, &cbData
) == ERROR_SUCCESS
)
2528 RegCloseKey (hrootkey
);
2534 RegCloseKey (hrootkey
);
2540 /* The argv[] array holds ANSI-encoded strings, and so this function
2541 works with ANS_encoded strings. */
2543 init_environment (char ** argv
)
2545 static const char * const tempdirs
[] = {
2546 "$TMPDIR", "$TEMP", "$TMP", "c:/"
2551 const int imax
= ARRAYELTS (tempdirs
);
2553 /* Implementation note: This function explicitly works with ANSI
2554 file names, not with UTF-8 encoded file names. This is because
2555 this function pushes variables into the Emacs's environment, and
2556 the environment variables are always assumed to be in the
2557 locale-specific encoding. Do NOT call any functions that accept
2558 UTF-8 file names from this function! */
2560 /* Make sure they have a usable $TMPDIR. Many Emacs functions use
2561 temporary files and assume "/tmp" if $TMPDIR is unset, which
2562 will break on DOS/Windows. Refuse to work if we cannot find
2563 a directory, not even "c:/", usable for that purpose. */
2564 for (i
= 0; i
< imax
; i
++)
2566 const char *tmp
= tempdirs
[i
];
2569 tmp
= getenv (tmp
+ 1);
2570 /* Note that `access' can lie to us if the directory resides on a
2571 read-only filesystem, like CD-ROM or a write-protected floppy.
2572 The only way to be really sure is to actually create a file and
2573 see if it succeeds. But I think that's too much to ask. */
2575 /* MSVCRT's _access crashes with D_OK, so we use our replacement. */
2576 if (tmp
&& sys_access (tmp
, D_OK
) == 0)
2578 char * var
= alloca (strlen (tmp
) + 8);
2579 sprintf (var
, "TMPDIR=%s", tmp
);
2580 _putenv (strdup (var
));
2587 Fcons (build_string ("no usable temporary directories found!!"),
2589 "While setting TMPDIR: ");
2591 /* Check for environment variables and use registry settings if they
2592 don't exist. Fallback on default values where applicable. */
2597 char locale_name
[32];
2598 char default_home
[MAX_PATH
];
2601 static const struct env_entry
2607 /* If the default value is NULL, we will use the value from the
2608 outside environment or the Registry, but will not push the
2609 variable into the Emacs environment if it is defined neither
2610 in the Registry nor in the outside environment. */
2612 {"PRELOAD_WINSOCK", NULL
},
2613 {"emacs_dir", "C:/emacs"},
2614 {"EMACSLOADPATH", NULL
},
2615 {"SHELL", "cmdproxy.exe"}, /* perhaps it is somewhere on PATH */
2616 {"EMACSDATA", NULL
},
2617 {"EMACSPATH", NULL
},
2624 #define N_ENV_VARS ARRAYELTS (dflt_envvars)
2626 /* We need to copy dflt_envvars[] and work on the copy because we
2627 don't want the dumped Emacs to inherit the values of
2628 environment variables we saw during dumping (which could be on
2629 a different system). The defaults above must be left intact. */
2630 struct env_entry env_vars
[N_ENV_VARS
];
2632 for (i
= 0; i
< N_ENV_VARS
; i
++)
2633 env_vars
[i
] = dflt_envvars
[i
];
2635 /* For backwards compatibility, check if a .emacs file exists in C:/
2636 If not, then we can try to default to the appdata directory under the
2637 user's profile, which is more likely to be writable. */
2638 if (sys_access ("C:/.emacs", F_OK
) != 0)
2640 HRESULT profile_result
;
2641 /* Dynamically load ShGetFolderPath, as it won't exist on versions
2642 of Windows 95 and NT4 that have not been updated to include
2644 ShGetFolderPath_fn get_folder_path
;
2645 get_folder_path
= (ShGetFolderPath_fn
)
2646 GetProcAddress (GetModuleHandle ("shell32.dll"), "SHGetFolderPathA");
2648 if (get_folder_path
!= NULL
)
2650 profile_result
= get_folder_path (NULL
, CSIDL_APPDATA
, NULL
,
2653 /* If we can't get the appdata dir, revert to old behavior. */
2654 if (profile_result
== S_OK
)
2656 env_vars
[0].def_value
= default_home
;
2662 /* Get default locale info and use it for LANG. */
2663 if (GetLocaleInfo (LOCALE_USER_DEFAULT
,
2664 LOCALE_SABBREVLANGNAME
| LOCALE_USE_CP_ACP
,
2665 locale_name
, sizeof (locale_name
)))
2667 for (i
= 0; i
< N_ENV_VARS
; i
++)
2669 if (strcmp (env_vars
[i
].name
, "LANG") == 0)
2671 env_vars
[i
].def_value
= locale_name
;
2677 #define SET_ENV_BUF_SIZE (4 * MAX_PATH) /* to cover EMACSLOADPATH */
2679 /* Treat emacs_dir specially: set it unconditionally based on our
2683 char modname
[MAX_PATH
];
2685 if (!GetModuleFileNameA (NULL
, modname
, MAX_PATH
))
2687 if ((p
= _mbsrchr (modname
, '\\')) == NULL
)
2691 if ((p
= _mbsrchr (modname
, '\\'))
2692 /* From bin means installed Emacs, from src means uninstalled. */
2693 && (xstrcasecmp (p
, "\\bin") == 0 || xstrcasecmp (p
, "\\src") == 0))
2695 char buf
[SET_ENV_BUF_SIZE
];
2696 int within_build_tree
= xstrcasecmp (p
, "\\src") == 0;
2699 for (p
= modname
; *p
; p
= CharNext (p
))
2700 if (*p
== '\\') *p
= '/';
2702 _snprintf (buf
, sizeof (buf
)-1, "emacs_dir=%s", modname
);
2703 _putenv (strdup (buf
));
2704 /* If we are running from the Posix-like build tree, define
2705 SHELL to point to our own cmdproxy. The loop below will
2706 then disregard PATH_EXEC and the default value. */
2707 if (within_build_tree
)
2709 _snprintf (buf
, sizeof (buf
) - 1,
2710 "SHELL=%s/nt/cmdproxy.exe", modname
);
2711 _putenv (strdup (buf
));
2716 for (i
= 0; i
< N_ENV_VARS
; i
++)
2718 if (!getenv (env_vars
[i
].name
))
2721 char bufc
[SET_ENV_BUF_SIZE
];
2723 if ((lpval
= w32_get_resource (env_vars
[i
].name
, &dwType
)) == NULL
2724 /* Also ignore empty environment variables. */
2729 if (strcmp (env_vars
[i
].name
, "SHELL") == 0)
2731 /* Look for cmdproxy.exe in every directory in
2732 PATH_EXEC. FIXME: This does not find cmdproxy
2733 in nt/ when we run uninstalled. */
2734 char fname
[MAX_PATH
];
2735 const char *pstart
= PATH_EXEC
, *pend
;
2738 pend
= _mbschr (pstart
, ';');
2740 pend
= pstart
+ strlen (pstart
);
2741 /* Be defensive against series of ;;; characters. */
2744 strncpy (fname
, pstart
, pend
- pstart
);
2745 fname
[pend
- pstart
] = '/';
2746 strcpy (&fname
[pend
- pstart
+ 1], "cmdproxy.exe");
2747 ExpandEnvironmentStrings ((LPSTR
) fname
, bufc
,
2749 if (sys_access (bufc
, F_OK
) == 0)
2762 /* If not found in any directory, use the
2763 default as the last resort. */
2764 lpval
= env_vars
[i
].def_value
;
2765 dwType
= REG_EXPAND_SZ
;
2771 lpval
= env_vars
[i
].def_value
;
2772 dwType
= REG_EXPAND_SZ
;
2774 if (strcmp (env_vars
[i
].name
, "HOME") == 0 && !appdata
)
2775 Vdelayed_warnings_list
2776 = Fcons (listn (CONSTYPE_HEAP
, 2,
2777 intern ("initialization"),
2778 build_string ("Setting HOME to C:\\ by default is deprecated")),
2779 Vdelayed_warnings_list
);
2784 char buf1
[SET_ENV_BUF_SIZE
], buf2
[SET_ENV_BUF_SIZE
];
2786 if (dwType
== REG_EXPAND_SZ
)
2787 ExpandEnvironmentStrings ((LPSTR
) lpval
, buf1
, sizeof (buf1
));
2788 else if (dwType
== REG_SZ
)
2789 strcpy (buf1
, lpval
);
2790 if (dwType
== REG_EXPAND_SZ
|| dwType
== REG_SZ
)
2792 _snprintf (buf2
, sizeof (buf2
)-1, "%s=%s", env_vars
[i
].name
,
2794 _putenv (strdup (buf2
));
2804 /* Rebuild system configuration to reflect invoking system. */
2805 Vsystem_configuration
= build_string (EMACS_CONFIGURATION
);
2807 /* Another special case: on NT, the PATH variable is actually named
2808 "Path" although cmd.exe (perhaps NT itself) arranges for
2809 environment variable lookup and setting to be case insensitive.
2810 However, Emacs assumes a fully case sensitive environment, so we
2811 need to change "Path" to "PATH" to match the expectations of
2812 various elisp packages. We do this by the sneaky method of
2813 modifying the string in the C runtime environ entry.
2815 The same applies to COMSPEC. */
2819 for (envp
= environ
; *envp
; envp
++)
2820 if (_strnicmp (*envp
, "PATH=", 5) == 0)
2821 memcpy (*envp
, "PATH=", 5);
2822 else if (_strnicmp (*envp
, "COMSPEC=", 8) == 0)
2823 memcpy (*envp
, "COMSPEC=", 8);
2826 /* Remember the initial working directory for getcwd. */
2827 /* FIXME: Do we need to resolve possible symlinks in startup_dir?
2828 Does it matter anywhere in Emacs? */
2829 if (w32_unicode_filenames
)
2831 wchar_t wstartup_dir
[MAX_PATH
];
2833 if (!GetCurrentDirectoryW (MAX_PATH
, wstartup_dir
))
2835 filename_from_utf16 (wstartup_dir
, startup_dir
);
2839 char astartup_dir
[MAX_PATH
];
2841 if (!GetCurrentDirectoryA (MAX_PATH
, astartup_dir
))
2843 filename_from_ansi (astartup_dir
, startup_dir
);
2847 static char modname
[MAX_PATH
];
2849 if (!GetModuleFileNameA (NULL
, modname
, MAX_PATH
))
2854 /* Determine if there is a middle mouse button, to allow parse_button
2855 to decide whether right mouse events should be mouse-2 or
2857 w32_num_mouse_buttons
= GetSystemMetrics (SM_CMOUSEBUTTONS
);
2862 /* Called from expand-file-name when default-directory is not a string. */
2865 emacs_root_dir (void)
2867 static char root_dir
[MAX_UTF8_PATH
];
2870 p
= getenv ("emacs_dir");
2873 filename_from_ansi (p
, root_dir
);
2874 root_dir
[parse_root (root_dir
, NULL
)] = '\0';
2875 dostounix_filename (root_dir
);
2879 #include <sys/timeb.h>
2881 /* Emulate gettimeofday (Ulrich Leodolter, 1/11/95). */
2883 gettimeofday (struct timeval
*__restrict tv
, struct timezone
*__restrict tz
)
2888 tv
->tv_sec
= tb
.time
;
2889 tv
->tv_usec
= tb
.millitm
* 1000L;
2890 /* Implementation note: _ftime sometimes doesn't update the dstflag
2891 according to the new timezone when the system timezone is
2892 changed. We could fix that by using GetSystemTime and
2893 GetTimeZoneInformation, but that doesn't seem necessary, since
2894 Emacs always calls gettimeofday with the 2nd argument NULL (see
2895 current_emacs_time). */
2898 tz
->tz_minuteswest
= tb
.timezone
; /* minutes west of Greenwich */
2899 tz
->tz_dsttime
= tb
.dstflag
; /* type of dst correction */
2904 /* Emulate fdutimens. */
2906 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2907 TIMESPEC[0] and TIMESPEC[1], respectively.
2908 FD must be either negative -- in which case it is ignored --
2909 or a file descriptor that is open on FILE.
2910 If FD is nonnegative, then FILE can be NULL, which means
2911 use just futimes instead of utimes.
2912 If TIMESPEC is null, FAIL.
2913 Return 0 on success, -1 (setting errno) on failure. */
2916 fdutimens (int fd
, char const *file
, struct timespec
const timespec
[2])
2923 if (fd
< 0 && !file
)
2928 /* _futime's prototype defines 2nd arg as having the type 'struct
2929 _utimbuf', while utime needs to accept 'struct utimbuf' for
2930 compatibility with Posix. So we need to use 2 different (but
2931 equivalent) types to avoid compiler warnings, sigh. */
2934 struct _utimbuf _ut
;
2936 _ut
.actime
= timespec
[0].tv_sec
;
2937 _ut
.modtime
= timespec
[1].tv_sec
;
2938 return _futime (fd
, &_ut
);
2944 ut
.actime
= timespec
[0].tv_sec
;
2945 ut
.modtime
= timespec
[1].tv_sec
;
2946 /* Call 'utime', which is implemented below, not the MS library
2947 function, which fails on directories. */
2948 return utime (file
, &ut
);
2953 /* ------------------------------------------------------------------------- */
2954 /* IO support and wrapper functions for the Windows API. */
2955 /* ------------------------------------------------------------------------- */
2957 /* Place a wrapper around the MSVC version of ctime. It returns NULL
2958 on network directories, so we handle that case here.
2959 (Ulrich Leodolter, 1/11/95). */
2961 sys_ctime (const time_t *t
)
2963 char *str
= (char *) ctime (t
);
2964 return (str
? str
: "Sun Jan 01 00:00:00 1970");
2967 /* Emulate sleep...we could have done this with a define, but that
2968 would necessitate including windows.h in the files that used it.
2969 This is much easier. */
2971 sys_sleep (int seconds
)
2973 Sleep (seconds
* 1000);
2976 /* Internal MSVC functions for low-level descriptor munging */
2977 extern int __cdecl
_set_osfhnd (int fd
, long h
);
2978 extern int __cdecl
_free_osfhnd (int fd
);
2980 /* parallel array of private info on file handles */
2981 filedesc fd_info
[ MAXDESC
];
2983 typedef struct volume_info_data
{
2984 struct volume_info_data
* next
;
2986 /* time when info was obtained */
2989 /* actual volume info */
2998 /* Global referenced by various functions. */
2999 static volume_info_data volume_info
;
3001 /* Vector to indicate which drives are local and fixed (for which cached
3002 data never expires). */
3003 static BOOL fixed_drives
[26];
3005 /* Consider cached volume information to be stale if older than 10s,
3006 at least for non-local drives. Info for fixed drives is never stale. */
3007 #define DRIVE_INDEX( c ) ( (c) <= 'Z' ? (c) - 'A' : (c) - 'a' )
3008 #define VOLINFO_STILL_VALID( root_dir, info ) \
3009 ( ( isalpha (root_dir[0]) && \
3010 fixed_drives[ DRIVE_INDEX (root_dir[0]) ] ) \
3011 || GetTickCount () - info->timestamp < 10000 )
3013 /* Cache support functions. */
3015 /* Simple linked list with linear search is sufficient. */
3016 static volume_info_data
*volume_cache
= NULL
;
3018 static volume_info_data
*
3019 lookup_volume_info (char * root_dir
)
3021 volume_info_data
* info
;
3023 for (info
= volume_cache
; info
; info
= info
->next
)
3024 if (xstrcasecmp (info
->root_dir
, root_dir
) == 0)
3030 add_volume_info (char * root_dir
, volume_info_data
* info
)
3032 info
->root_dir
= xstrdup (root_dir
);
3033 unixtodos_filename (info
->root_dir
);
3034 info
->next
= volume_cache
;
3035 volume_cache
= info
;
3039 /* Wrapper for GetVolumeInformation, which uses caching to avoid
3040 performance penalty (~2ms on 486 for local drives, 7.5ms for local
3041 cdrom drive, ~5-10ms or more for remote drives on LAN). */
3042 static volume_info_data
*
3043 GetCachedVolumeInformation (char * root_dir
)
3045 volume_info_data
* info
;
3046 char default_root
[ MAX_UTF8_PATH
];
3047 char name
[MAX_PATH
+1];
3048 char type
[MAX_PATH
+1];
3050 /* NULL for root_dir means use root from current directory. */
3051 if (root_dir
== NULL
)
3053 if (w32_unicode_filenames
)
3055 wchar_t curdirw
[MAX_PATH
];
3057 if (GetCurrentDirectoryW (MAX_PATH
, curdirw
) == 0)
3059 filename_from_utf16 (curdirw
, default_root
);
3063 char curdira
[MAX_PATH
];
3065 if (GetCurrentDirectoryA (MAX_PATH
, curdira
) == 0)
3067 filename_from_ansi (curdira
, default_root
);
3069 parse_root (default_root
, (const char **)&root_dir
);
3071 root_dir
= default_root
;
3074 /* Local fixed drives can be cached permanently. Removable drives
3075 cannot be cached permanently, since the volume name and serial
3076 number (if nothing else) can change. Remote drives should be
3077 treated as if they are removable, since there is no sure way to
3078 tell whether they are or not. Also, the UNC association of drive
3079 letters mapped to remote volumes can be changed at any time (even
3080 by other processes) without notice.
3082 As a compromise, so we can benefit from caching info for remote
3083 volumes, we use a simple expiry mechanism to invalidate cache
3084 entries that are more than ten seconds old. */
3087 /* No point doing this, because WNetGetConnection is even slower than
3088 GetVolumeInformation, consistently taking ~50ms on a 486 (FWIW,
3089 GetDriveType is about the only call of this type which does not
3090 involve network access, and so is extremely quick). */
3092 /* Map drive letter to UNC if remote. */
3093 if (isalpha (root_dir
[0]) && !fixed
[DRIVE_INDEX (root_dir
[0])])
3095 char remote_name
[ 256 ];
3096 char drive
[3] = { root_dir
[0], ':' };
3098 if (WNetGetConnection (drive
, remote_name
, sizeof (remote_name
))
3100 /* do something */ ;
3104 info
= lookup_volume_info (root_dir
);
3106 if (info
== NULL
|| ! VOLINFO_STILL_VALID (root_dir
, info
))
3112 /* Info is not cached, or is stale. */
3113 if (w32_unicode_filenames
)
3115 wchar_t root_w
[MAX_PATH
];
3116 wchar_t name_w
[MAX_PATH
+1];
3117 wchar_t type_w
[MAX_PATH
+1];
3119 filename_to_utf16 (root_dir
, root_w
);
3120 if (!GetVolumeInformationW (root_w
,
3121 name_w
, sizeof (name_w
),
3125 type_w
, sizeof (type_w
)))
3127 /* Hmm... not really 100% correct, as these 2 are not file
3129 filename_from_utf16 (name_w
, name
);
3130 filename_from_utf16 (type_w
, type
);
3134 char root_a
[MAX_PATH
];
3135 char name_a
[MAX_PATH
+1];
3136 char type_a
[MAX_PATH
+1];
3138 filename_to_ansi (root_dir
, root_a
);
3139 if (!GetVolumeInformationA (root_a
,
3140 name_a
, sizeof (name_a
),
3144 type_a
, sizeof (type_a
)))
3146 filename_from_ansi (name_a
, name
);
3147 filename_from_ansi (type_a
, type
);
3150 /* Cache the volume information for future use, overwriting existing
3151 entry if present. */
3154 info
= xmalloc (sizeof (volume_info_data
));
3155 add_volume_info (root_dir
, info
);
3163 info
->name
= xstrdup (name
);
3164 unixtodos_filename (info
->name
);
3165 info
->serialnum
= serialnum
;
3166 info
->maxcomp
= maxcomp
;
3167 info
->flags
= flags
;
3168 info
->type
= xstrdup (type
);
3169 info
->timestamp
= GetTickCount ();
3175 /* Get information on the volume where NAME is held; set path pointer to
3176 start of pathname in NAME (past UNC header\volume header if present),
3177 if pPath is non-NULL.
3179 Note: if NAME includes symlinks, the information is for the volume
3180 of the symlink, not of its target. That's because, even though
3181 GetVolumeInformation returns information about the symlink target
3182 of its argument, we only pass the root directory to
3183 GetVolumeInformation, not the full NAME. */
3185 get_volume_info (const char * name
, const char ** pPath
)
3187 char temp
[MAX_UTF8_PATH
];
3188 char *rootname
= NULL
; /* default to current volume */
3189 volume_info_data
* info
;
3190 int root_len
= parse_root (name
, pPath
);
3195 /* Copy the root name of the volume, if given. */
3198 strncpy (temp
, name
, root_len
);
3199 temp
[root_len
] = '\0';
3200 unixtodos_filename (temp
);
3204 info
= GetCachedVolumeInformation (rootname
);
3207 /* Set global referenced by other functions. */
3208 volume_info
= *info
;
3214 /* Determine if volume is FAT format (ie. only supports short 8.3
3215 names); also set path pointer to start of pathname in name, if
3216 pPath is non-NULL. */
3218 is_fat_volume (const char * name
, const char ** pPath
)
3220 if (get_volume_info (name
, pPath
))
3221 return (volume_info
.maxcomp
== 12);
3225 /* Convert all slashes in a filename to backslashes, and map filename
3226 to a valid 8.3 name if necessary. The result is a pointer to a
3227 static buffer, so CAVEAT EMPTOR! */
3229 map_w32_filename (const char * name
, const char ** pPath
)
3231 static char shortname
[MAX_UTF8_PATH
];
3232 char * str
= shortname
;
3235 const char * save_name
= name
;
3237 if (strlen (name
) >= sizeof (shortname
))
3239 /* Return a filename which will cause callers to fail. */
3240 strcpy (shortname
, "?");
3244 if (!fatal_error_in_progress
/* disable fancy processing during crash */
3245 && is_fat_volume (name
, (const char **)&path
)) /* truncate to 8.3 */
3247 register int left
= 8; /* maximum number of chars in part */
3248 register int extn
= 0; /* extension added? */
3249 register int dots
= 2; /* maximum number of dots allowed */
3252 *str
++ = *name
++; /* skip past UNC header */
3254 while ((c
= *name
++))
3261 *str
++ = (c
== ':' ? ':' : '\\');
3262 extn
= 0; /* reset extension flags */
3263 dots
= 2; /* max 2 dots */
3264 left
= 8; /* max length 8 for main part */
3269 /* Convert path components of the form .xxx to _xxx,
3270 but leave . and .. as they are. This allows .emacs
3271 to be read as _emacs, for example. */
3275 IS_DIRECTORY_SEP (*name
))
3290 extn
= 1; /* we've got an extension */
3291 left
= 3; /* 3 chars in extension */
3295 /* any embedded dots after the first are converted to _ */
3300 case '#': /* don't lose these, they're important */
3302 str
[-1] = c
; /* replace last character of part */
3305 if ( left
&& 'A' <= c
&& c
<= 'Z' )
3307 *str
++ = tolower (c
); /* map to lower case (looks nicer) */
3309 dots
= 0; /* started a path component */
3318 strcpy (shortname
, name
);
3319 unixtodos_filename (shortname
);
3323 *pPath
= shortname
+ (path
- save_name
);
3329 is_exec (const char * name
)
3331 char * p
= strrchr (name
, '.');
3334 && (xstrcasecmp (p
, ".exe") == 0 ||
3335 xstrcasecmp (p
, ".com") == 0 ||
3336 xstrcasecmp (p
, ".bat") == 0 ||
3337 xstrcasecmp (p
, ".cmd") == 0));
3340 /* Emulate the Unix directory procedures opendir, closedir, and
3341 readdir. We rename them to sys_* names because some versions of
3342 MinGW startup code call opendir and readdir to glob wildcards, and
3343 the code that calls them doesn't grok UTF-8 encoded file names we
3344 produce in dirent->d_name[]. */
3346 struct dirent dir_static
; /* simulated directory contents */
3347 static HANDLE dir_find_handle
= INVALID_HANDLE_VALUE
;
3348 static int dir_is_fat
;
3349 static char dir_pathname
[MAX_UTF8_PATH
];
3350 static WIN32_FIND_DATAW dir_find_data_w
;
3351 static WIN32_FIND_DATAA dir_find_data_a
;
3352 #define DIR_FIND_DATA_W 1
3353 #define DIR_FIND_DATA_A 2
3354 static int last_dir_find_data
= -1;
3356 /* Support shares on a network resource as subdirectories of a read-only
3358 static HANDLE wnet_enum_handle
= INVALID_HANDLE_VALUE
;
3359 static HANDLE
open_unc_volume (const char *);
3360 static void *read_unc_volume (HANDLE
, wchar_t *, char *, int);
3361 static void close_unc_volume (HANDLE
);
3364 sys_opendir (const char *filename
)
3368 /* Opening is done by FindFirstFile. However, a read is inherent to
3369 this operation, so we defer the open until read time. */
3371 if (dir_find_handle
!= INVALID_HANDLE_VALUE
)
3373 if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
3376 /* Note: We don't support traversal of UNC volumes via symlinks.
3377 Doing so would mean punishing 99.99% of use cases by resolving
3378 all the possible symlinks in FILENAME, recursively. */
3379 if (is_unc_volume (filename
))
3381 wnet_enum_handle
= open_unc_volume (filename
);
3382 if (wnet_enum_handle
== INVALID_HANDLE_VALUE
)
3386 if (!(dirp
= (DIR *) malloc (sizeof (DIR))))
3393 strncpy (dir_pathname
, map_w32_filename (filename
, NULL
), MAX_UTF8_PATH
- 1);
3394 dir_pathname
[MAX_UTF8_PATH
- 1] = '\0';
3395 /* Note: We don't support symlinks to file names on FAT volumes.
3396 Doing so would mean punishing 99.99% of use cases by resolving
3397 all the possible symlinks in FILENAME, recursively. */
3398 dir_is_fat
= is_fat_volume (filename
, NULL
);
3404 sys_closedir (DIR *dirp
)
3406 /* If we have a find-handle open, close it. */
3407 if (dir_find_handle
!= INVALID_HANDLE_VALUE
)
3409 FindClose (dir_find_handle
);
3410 dir_find_handle
= INVALID_HANDLE_VALUE
;
3412 else if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
3414 close_unc_volume (wnet_enum_handle
);
3415 wnet_enum_handle
= INVALID_HANDLE_VALUE
;
3417 xfree ((char *) dirp
);
3421 sys_readdir (DIR *dirp
)
3423 int downcase
= !NILP (Vw32_downcase_file_names
);
3425 if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
3427 if (!read_unc_volume (wnet_enum_handle
,
3428 dir_find_data_w
.cFileName
,
3429 dir_find_data_a
.cFileName
,
3433 /* If we aren't dir_finding, do a find-first, otherwise do a find-next. */
3434 else if (dir_find_handle
== INVALID_HANDLE_VALUE
)
3436 char filename
[MAX_UTF8_PATH
];
3438 bool last_slash
= true;
3440 /* Note: We don't need to worry about dir_pathname being longer
3441 than MAX_UTF8_PATH, as sys_opendir already took care of that
3442 when it called map_w32_filename: that function will put a "?"
3443 in its return value in that case, thus failing all the calls
3445 strcpy (filename
, dir_pathname
);
3446 ln
= strlen (filename
);
3447 if (!IS_DIRECTORY_SEP (filename
[ln
- 1]))
3450 /* Note: No need to resolve symlinks in FILENAME, because
3451 FindFirst opens the directory that is the target of a
3453 if (w32_unicode_filenames
)
3455 wchar_t fnw
[MAX_PATH
+ 2];
3457 filename_to_utf16 (filename
, fnw
);
3459 wcscat (fnw
, L
"\\");
3461 dir_find_handle
= FindFirstFileW (fnw
, &dir_find_data_w
);
3465 char fna
[MAX_PATH
+ 2];
3467 filename_to_ansi (filename
, fna
);
3471 /* If FILENAME is not representable by the current ANSI
3472 codepage, we don't want FindFirstFileA to interpret the
3473 '?' characters as a wildcard. */
3474 if (_mbspbrk (fna
, "?"))
3475 dir_find_handle
= INVALID_HANDLE_VALUE
;
3477 dir_find_handle
= FindFirstFileA (fna
, &dir_find_data_a
);
3480 if (dir_find_handle
== INVALID_HANDLE_VALUE
)
3482 /* Any changes in the value of errno here should be in sync
3483 with what directory_files_internal does when it calls
3485 switch (GetLastError ())
3487 /* Windows uses this value when FindFirstFile finds no
3488 files that match the wildcard. This is not supposed
3489 to happen, since our wildcard is "*", but just in
3490 case, if there's some weird empty directory with not
3491 even "." and ".." entries... */
3492 case ERROR_FILE_NOT_FOUND
:
3497 case ERROR_ACCESS_DENIED
:
3498 case ERROR_NETWORK_ACCESS_DENIED
:
3501 case ERROR_PATH_NOT_FOUND
:
3502 case ERROR_INVALID_DRIVE
:
3503 case ERROR_NOT_READY
:
3504 case ERROR_BAD_NETPATH
:
3505 case ERROR_BAD_NET_NAME
:
3512 else if (w32_unicode_filenames
)
3514 if (!FindNextFileW (dir_find_handle
, &dir_find_data_w
))
3522 if (!FindNextFileA (dir_find_handle
, &dir_find_data_a
))
3529 /* Emacs never uses this value, so don't bother making it match
3530 value returned by stat(). */
3531 dir_static
.d_ino
= 1;
3533 if (w32_unicode_filenames
)
3535 if (downcase
|| dir_is_fat
)
3537 wchar_t tem
[MAX_PATH
];
3539 wcscpy (tem
, dir_find_data_w
.cFileName
);
3541 filename_from_utf16 (tem
, dir_static
.d_name
);
3544 filename_from_utf16 (dir_find_data_w
.cFileName
, dir_static
.d_name
);
3545 last_dir_find_data
= DIR_FIND_DATA_W
;
3551 /* If the file name in cFileName[] includes `?' characters, it
3552 means the original file name used characters that cannot be
3553 represented by the current ANSI codepage. To avoid total
3554 lossage, retrieve the short 8+3 alias of the long file
3556 if (_mbspbrk (dir_find_data_a
.cFileName
, "?"))
3558 strcpy (tem
, dir_find_data_a
.cAlternateFileName
);
3559 /* 8+3 aliases are returned in all caps, which could break
3560 various alists that look at filenames' extensions. */
3563 else if (downcase
|| dir_is_fat
)
3564 strcpy (tem
, dir_find_data_a
.cFileName
);
3566 filename_from_ansi (dir_find_data_a
.cFileName
, dir_static
.d_name
);
3567 if (downcase
|| dir_is_fat
)
3570 filename_from_ansi (tem
, dir_static
.d_name
);
3572 last_dir_find_data
= DIR_FIND_DATA_A
;
3575 dir_static
.d_namlen
= strlen (dir_static
.d_name
);
3576 dir_static
.d_reclen
= sizeof (struct dirent
) - MAX_UTF8_PATH
+ 3 +
3577 dir_static
.d_namlen
- dir_static
.d_namlen
% 4;
3583 open_unc_volume (const char *path
)
3585 const char *fn
= map_w32_filename (path
, NULL
);
3589 if (w32_unicode_filenames
)
3592 wchar_t fnw
[MAX_PATH
];
3594 nrw
.dwScope
= RESOURCE_GLOBALNET
;
3595 nrw
.dwType
= RESOURCETYPE_DISK
;
3596 nrw
.dwDisplayType
= RESOURCEDISPLAYTYPE_SERVER
;
3597 nrw
.dwUsage
= RESOURCEUSAGE_CONTAINER
;
3598 nrw
.lpLocalName
= NULL
;
3599 filename_to_utf16 (fn
, fnw
);
3600 nrw
.lpRemoteName
= fnw
;
3601 nrw
.lpComment
= NULL
;
3602 nrw
.lpProvider
= NULL
;
3604 result
= WNetOpenEnumW (RESOURCE_GLOBALNET
, RESOURCETYPE_DISK
,
3605 RESOURCEUSAGE_CONNECTABLE
, &nrw
, &henum
);
3612 nra
.dwScope
= RESOURCE_GLOBALNET
;
3613 nra
.dwType
= RESOURCETYPE_DISK
;
3614 nra
.dwDisplayType
= RESOURCEDISPLAYTYPE_SERVER
;
3615 nra
.dwUsage
= RESOURCEUSAGE_CONTAINER
;
3616 nra
.lpLocalName
= NULL
;
3617 filename_to_ansi (fn
, fna
);
3618 nra
.lpRemoteName
= fna
;
3619 nra
.lpComment
= NULL
;
3620 nra
.lpProvider
= NULL
;
3622 result
= WNetOpenEnumA (RESOURCE_GLOBALNET
, RESOURCETYPE_DISK
,
3623 RESOURCEUSAGE_CONNECTABLE
, &nra
, &henum
);
3625 if (result
== NO_ERROR
)
3629 /* Make sure directory_files_internal reports a sensible error. */
3631 return INVALID_HANDLE_VALUE
;
3636 read_unc_volume (HANDLE henum
, wchar_t *fname_w
, char *fname_a
, int size
)
3641 DWORD bufsize
= 512;
3645 if (w32_unicode_filenames
)
3650 buffer
= alloca (bufsize
);
3651 result
= WNetEnumResourceW (henum
, &count
, buffer
, &bufsize
);
3652 if (result
!= NO_ERROR
)
3654 /* WNetEnumResource returns \\resource\share...skip forward to "share". */
3655 ptrw
= ((LPNETRESOURCEW
) buffer
)->lpRemoteName
;
3657 while (*ptrw
&& *ptrw
!= L
'/' && *ptrw
!= L
'\\') ptrw
++;
3659 wcsncpy (fname_w
, ptrw
, size
);
3664 int dbcs_p
= max_filename_mbslen () > 1;
3667 buffer
= alloca (bufsize
);
3668 result
= WNetEnumResourceA (henum
, &count
, buffer
, &bufsize
);
3669 if (result
!= NO_ERROR
)
3671 ptra
= ((LPNETRESOURCEA
) buffer
)->lpRemoteName
;
3674 while (*ptra
&& !IS_DIRECTORY_SEP (*ptra
)) ptra
++;
3677 while (*ptra
&& !IS_DIRECTORY_SEP (*ptra
))
3678 ptra
= CharNextExA (file_name_codepage
, ptra
, 0);
3681 strncpy (fname_a
, ptra
, size
);
3689 close_unc_volume (HANDLE henum
)
3691 if (henum
!= INVALID_HANDLE_VALUE
)
3692 WNetCloseEnum (henum
);
3696 unc_volume_file_attributes (const char *path
)
3701 henum
= open_unc_volume (path
);
3702 if (henum
== INVALID_HANDLE_VALUE
)
3705 attrs
= FILE_ATTRIBUTE_READONLY
| FILE_ATTRIBUTE_DIRECTORY
;
3707 close_unc_volume (henum
);
3712 /* Ensure a network connection is authenticated. */
3714 logon_network_drive (const char *path
)
3716 char share
[MAX_UTF8_PATH
];
3723 if (IS_DIRECTORY_SEP (path
[0]) && IS_DIRECTORY_SEP (path
[1]))
3724 drvtype
= DRIVE_REMOTE
;
3725 else if (path
[0] == '\0' || path
[1] != ':')
3726 drvtype
= GetDriveType (NULL
);
3733 drvtype
= GetDriveType (drive
);
3736 /* Only logon to networked drives. */
3737 if (drvtype
!= DRIVE_REMOTE
)
3741 strncpy (share
, path
, MAX_UTF8_PATH
);
3742 /* Truncate to just server and share name. */
3743 for (p
= share
+ 2; *p
&& p
< share
+ MAX_UTF8_PATH
; p
++)
3745 if (IS_DIRECTORY_SEP (*p
) && ++n_slashes
> 3)
3752 if (w32_unicode_filenames
)
3754 NETRESOURCEW resourcew
;
3755 wchar_t share_w
[MAX_PATH
];
3757 resourcew
.dwScope
= RESOURCE_GLOBALNET
;
3758 resourcew
.dwType
= RESOURCETYPE_DISK
;
3759 resourcew
.dwDisplayType
= RESOURCEDISPLAYTYPE_SHARE
;
3760 resourcew
.dwUsage
= RESOURCEUSAGE_CONTAINER
;
3761 resourcew
.lpLocalName
= NULL
;
3762 filename_to_utf16 (share
, share_w
);
3763 resourcew
.lpRemoteName
= share_w
;
3764 resourcew
.lpProvider
= NULL
;
3766 val
= WNetAddConnection2W (&resourcew
, NULL
, NULL
, CONNECT_INTERACTIVE
);
3770 NETRESOURCEA resourcea
;
3771 char share_a
[MAX_PATH
];
3773 resourcea
.dwScope
= RESOURCE_GLOBALNET
;
3774 resourcea
.dwType
= RESOURCETYPE_DISK
;
3775 resourcea
.dwDisplayType
= RESOURCEDISPLAYTYPE_SHARE
;
3776 resourcea
.dwUsage
= RESOURCEUSAGE_CONTAINER
;
3777 resourcea
.lpLocalName
= NULL
;
3778 filename_to_ansi (share
, share_a
);
3779 resourcea
.lpRemoteName
= share_a
;
3780 resourcea
.lpProvider
= NULL
;
3782 val
= WNetAddConnection2A (&resourcea
, NULL
, NULL
, CONNECT_INTERACTIVE
);
3788 case ERROR_ALREADY_ASSIGNED
:
3790 case ERROR_ACCESS_DENIED
:
3791 case ERROR_LOGON_FAILURE
:
3797 case ERROR_BAD_NET_NAME
:
3798 case ERROR_NO_NET_OR_BAD_PATH
:
3799 case ERROR_NO_NETWORK
:
3800 case ERROR_CANCELLED
:
3807 /* Emulate faccessat(2). */
3809 faccessat (int dirfd
, const char * path
, int mode
, int flags
)
3813 if (dirfd
!= AT_FDCWD
3814 && !(IS_DIRECTORY_SEP (path
[0])
3815 || IS_DEVICE_SEP (path
[1])))
3821 /* MSVCRT implementation of 'access' doesn't recognize D_OK, and its
3822 newer versions blow up when passed D_OK. */
3823 path
= map_w32_filename (path
, NULL
);
3824 /* If the last element of PATH is a symlink, we need to resolve it
3825 to get the attributes of its target file. Note: any symlinks in
3826 PATH elements other than the last one are transparently resolved
3827 by GetFileAttributes below. */
3828 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) != 0
3829 && (flags
& AT_SYMLINK_NOFOLLOW
) == 0)
3830 path
= chase_symlinks (path
);
3832 if (w32_unicode_filenames
)
3834 wchar_t path_w
[MAX_PATH
];
3836 filename_to_utf16 (path
, path_w
);
3837 attributes
= GetFileAttributesW (path_w
);
3841 char path_a
[MAX_PATH
];
3843 filename_to_ansi (path
, path_a
);
3844 attributes
= GetFileAttributesA (path_a
);
3847 if (attributes
== -1)
3849 DWORD w32err
= GetLastError ();
3853 case ERROR_INVALID_NAME
:
3854 case ERROR_BAD_PATHNAME
:
3855 if (is_unc_volume (path
))
3857 attributes
= unc_volume_file_attributes (path
);
3858 if (attributes
== -1)
3866 case ERROR_FILE_NOT_FOUND
:
3867 case ERROR_BAD_NETPATH
:
3878 if ((mode
& X_OK
) != 0
3879 && !(is_exec (path
) || (attributes
& FILE_ATTRIBUTE_DIRECTORY
) != 0))
3884 if ((mode
& W_OK
) != 0 && (attributes
& FILE_ATTRIBUTE_READONLY
) != 0)
3889 if ((mode
& D_OK
) != 0 && (attributes
& FILE_ATTRIBUTE_DIRECTORY
) == 0)
3897 /* A special test for DIRNAME being a directory accessible by the
3898 current user. This is needed because the security permissions in
3899 directory's ACLs are not visible in the Posix-style mode bits
3900 returned by 'stat' and in attributes returned by GetFileAttributes.
3901 So a directory would seem like it's readable by the current user,
3902 but will in fact error out with EACCES when they actually try. */
3904 w32_accessible_directory_p (const char *dirname
, ptrdiff_t dirlen
)
3906 char pattern
[MAX_UTF8_PATH
];
3907 bool last_slash
= dirlen
> 0 && IS_DIRECTORY_SEP (dirname
[dirlen
- 1]);
3910 /* Network volumes need a different reading method. */
3911 if (is_unc_volume (dirname
))
3913 void *read_result
= NULL
;
3914 wchar_t fnw
[MAX_PATH
];
3917 dh
= open_unc_volume (dirname
);
3918 if (dh
!= INVALID_HANDLE_VALUE
)
3920 read_result
= read_unc_volume (dh
, fnw
, fna
, MAX_PATH
);
3921 close_unc_volume (dh
);
3923 /* Treat empty volumes as accessible. */
3924 return read_result
!= NULL
|| GetLastError () == ERROR_NO_MORE_ITEMS
;
3927 /* Note: map_w32_filename makes sure DIRNAME is not longer than
3929 strcpy (pattern
, map_w32_filename (dirname
, NULL
));
3931 /* Note: No need to resolve symlinks in FILENAME, because FindFirst
3932 opens the directory that is the target of a symlink. */
3933 if (w32_unicode_filenames
)
3935 wchar_t pat_w
[MAX_PATH
+ 2];
3936 WIN32_FIND_DATAW dfd_w
;
3938 filename_to_utf16 (pattern
, pat_w
);
3940 wcscat (pat_w
, L
"\\");
3941 wcscat (pat_w
, L
"*");
3942 dh
= FindFirstFileW (pat_w
, &dfd_w
);
3946 char pat_a
[MAX_PATH
+ 2];
3947 WIN32_FIND_DATAA dfd_a
;
3949 filename_to_ansi (pattern
, pat_a
);
3951 strcpy (pat_a
, "\\");
3952 strcat (pat_a
, "*");
3953 /* In case DIRNAME cannot be expressed in characters from the
3954 current ANSI codepage. */
3955 if (_mbspbrk (pat_a
, "?"))
3956 dh
= INVALID_HANDLE_VALUE
;
3958 dh
= FindFirstFileA (pat_a
, &dfd_a
);
3961 if (dh
== INVALID_HANDLE_VALUE
)
3967 /* A version of 'access' to be used locally with file names in
3968 locale-specific encoding. Does not resolve symlinks and does not
3969 support file names on FAT12 and FAT16 volumes, but that's OK, since
3970 we only invoke this function for files inside the Emacs source or
3971 installation tree, on directories (so any symlinks should have the
3972 directory bit set), and on short file names such as "C:/.emacs". */
3974 sys_access (const char *fname
, int mode
)
3976 char fname_copy
[MAX_PATH
], *p
;
3979 strcpy (fname_copy
, fname
);
3980 /* Do the equivalent of unixtodos_filename. */
3981 for (p
= fname_copy
; *p
; p
= CharNext (p
))
3985 if ((attributes
= GetFileAttributesA (fname_copy
)) == -1)
3987 DWORD w32err
= GetLastError ();
3991 case ERROR_INVALID_NAME
:
3992 case ERROR_BAD_PATHNAME
:
3993 case ERROR_FILE_NOT_FOUND
:
3994 case ERROR_BAD_NETPATH
:
4003 if ((mode
& X_OK
) != 0
4004 && !(is_exec (fname_copy
)
4005 || (attributes
& FILE_ATTRIBUTE_DIRECTORY
) != 0))
4010 if ((mode
& W_OK
) != 0 && (attributes
& FILE_ATTRIBUTE_READONLY
) != 0)
4015 if ((mode
& D_OK
) != 0 && (attributes
& FILE_ATTRIBUTE_DIRECTORY
) == 0)
4023 /* Shadow some MSVC runtime functions to map requests for long filenames
4024 to reasonable short names if necessary. This was originally added to
4025 permit running Emacs on NT 3.1 on a FAT partition, which doesn't support
4029 sys_chdir (const char * path
)
4031 path
= map_w32_filename (path
, NULL
);
4032 if (w32_unicode_filenames
)
4034 wchar_t newdir_w
[MAX_PATH
];
4036 if (filename_to_utf16 (path
, newdir_w
) == 0)
4037 return _wchdir (newdir_w
);
4042 char newdir_a
[MAX_PATH
];
4044 if (filename_to_ansi (path
, newdir_a
) == 0)
4045 return _chdir (newdir_a
);
4051 sys_chmod (const char * path
, int mode
)
4053 path
= chase_symlinks (map_w32_filename (path
, NULL
));
4054 if (w32_unicode_filenames
)
4056 wchar_t path_w
[MAX_PATH
];
4058 filename_to_utf16 (path
, path_w
);
4059 return _wchmod (path_w
, mode
);
4063 char path_a
[MAX_PATH
];
4065 filename_to_ansi (path
, path_a
);
4066 return _chmod (path_a
, mode
);
4071 sys_creat (const char * path
, int mode
)
4073 path
= map_w32_filename (path
, NULL
);
4074 if (w32_unicode_filenames
)
4076 wchar_t path_w
[MAX_PATH
];
4078 filename_to_utf16 (path
, path_w
);
4079 return _wcreat (path_w
, mode
);
4083 char path_a
[MAX_PATH
];
4085 filename_to_ansi (path
, path_a
);
4086 return _creat (path_a
, mode
);
4091 sys_fopen (const char * path
, const char * mode
)
4095 const char * mode_save
= mode
;
4097 /* Force all file handles to be non-inheritable. This is necessary to
4098 ensure child processes don't unwittingly inherit handles that might
4099 prevent future file access. */
4103 else if (mode
[0] == 'w' || mode
[0] == 'a')
4104 oflag
= O_WRONLY
| O_CREAT
| O_TRUNC
;
4108 /* Only do simplistic option parsing. */
4112 oflag
&= ~(O_RDONLY
| O_WRONLY
);
4115 else if (mode
[0] == 'b')
4120 else if (mode
[0] == 't')
4127 path
= map_w32_filename (path
, NULL
);
4128 if (w32_unicode_filenames
)
4130 wchar_t path_w
[MAX_PATH
];
4132 filename_to_utf16 (path
, path_w
);
4133 fd
= _wopen (path_w
, oflag
| _O_NOINHERIT
, 0644);
4137 char path_a
[MAX_PATH
];
4139 filename_to_ansi (path
, path_a
);
4140 fd
= _open (path_a
, oflag
| _O_NOINHERIT
, 0644);
4145 return _fdopen (fd
, mode_save
);
4148 /* This only works on NTFS volumes, but is useful to have. */
4150 sys_link (const char * old
, const char * new)
4154 char oldname
[MAX_UTF8_PATH
], newname
[MAX_UTF8_PATH
];
4155 wchar_t oldname_w
[MAX_PATH
];
4156 char oldname_a
[MAX_PATH
];
4158 if (old
== NULL
|| new == NULL
)
4164 strcpy (oldname
, map_w32_filename (old
, NULL
));
4165 strcpy (newname
, map_w32_filename (new, NULL
));
4167 if (w32_unicode_filenames
)
4169 filename_to_utf16 (oldname
, oldname_w
);
4170 fileh
= CreateFileW (oldname_w
, 0, 0, NULL
, OPEN_EXISTING
,
4171 FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
4175 filename_to_ansi (oldname
, oldname_a
);
4176 fileh
= CreateFileA (oldname_a
, 0, 0, NULL
, OPEN_EXISTING
,
4177 FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
4179 if (fileh
!= INVALID_HANDLE_VALUE
)
4183 /* Confusingly, the "alternate" stream name field does not apply
4184 when restoring a hard link, and instead contains the actual
4185 stream data for the link (ie. the name of the link to create).
4186 The WIN32_STREAM_ID structure before the cStreamName field is
4187 the stream header, which is then immediately followed by the
4191 WIN32_STREAM_ID wid
;
4192 WCHAR wbuffer
[MAX_PATH
]; /* extra space for link name */
4195 /* We used to pass MB_PRECOMPOSED as the 2nd arg here, but MSDN
4196 indicates that flag is unsupported for CP_UTF8, and OTOH says
4197 it is the default anyway. */
4198 wlen
= pMultiByteToWideChar (CP_UTF8
, 0, newname
, -1,
4199 data
.wid
.cStreamName
, MAX_PATH
);
4202 LPVOID context
= NULL
;
4205 data
.wid
.dwStreamId
= BACKUP_LINK
;
4206 data
.wid
.dwStreamAttributes
= 0;
4207 data
.wid
.Size
.LowPart
= wlen
* sizeof (WCHAR
);
4208 data
.wid
.Size
.HighPart
= 0;
4209 data
.wid
.dwStreamNameSize
= 0;
4211 if (BackupWrite (fileh
, (LPBYTE
)&data
,
4212 offsetof (WIN32_STREAM_ID
, cStreamName
)
4213 + data
.wid
.Size
.LowPart
,
4214 &wbytes
, FALSE
, FALSE
, &context
)
4215 && BackupWrite (fileh
, NULL
, 0, &wbytes
, TRUE
, FALSE
, &context
))
4222 DWORD err
= GetLastError ();
4227 case ERROR_ACCESS_DENIED
:
4228 /* This is what happens when OLDNAME is a directory,
4229 since Windows doesn't support hard links to
4230 directories. Posix says to set errno to EPERM in
4232 if (w32_unicode_filenames
)
4233 attributes
= GetFileAttributesW (oldname_w
);
4235 attributes
= GetFileAttributesA (oldname_a
);
4236 if (attributes
!= -1
4237 && (attributes
& FILE_ATTRIBUTE_DIRECTORY
) != 0)
4239 else if (attributes
== -1
4240 && is_unc_volume (oldname
)
4241 && unc_volume_file_attributes (oldname
) != -1)
4246 case ERROR_TOO_MANY_LINKS
:
4249 case ERROR_NOT_SAME_DEVICE
:
4259 CloseHandle (fileh
);
4268 sys_mkdir (const char * path
)
4270 path
= map_w32_filename (path
, NULL
);
4272 if (w32_unicode_filenames
)
4274 wchar_t path_w
[MAX_PATH
];
4276 filename_to_utf16 (path
, path_w
);
4277 return _wmkdir (path_w
);
4281 char path_a
[MAX_PATH
];
4283 filename_to_ansi (path
, path_a
);
4284 return _mkdir (path_a
);
4289 sys_open (const char * path
, int oflag
, int mode
)
4291 const char* mpath
= map_w32_filename (path
, NULL
);
4294 if (w32_unicode_filenames
)
4296 wchar_t mpath_w
[MAX_PATH
];
4298 filename_to_utf16 (mpath
, mpath_w
);
4299 /* If possible, try to open file without _O_CREAT, to be able to
4300 write to existing hidden and system files. Force all file
4301 handles to be non-inheritable. */
4302 if ((oflag
& (_O_CREAT
| _O_EXCL
)) != (_O_CREAT
| _O_EXCL
))
4303 res
= _wopen (mpath_w
, (oflag
& ~_O_CREAT
) | _O_NOINHERIT
, mode
);
4305 res
= _wopen (mpath_w
, oflag
| _O_NOINHERIT
, mode
);
4309 char mpath_a
[MAX_PATH
];
4311 filename_to_ansi (mpath
, mpath_a
);
4312 if ((oflag
& (_O_CREAT
| _O_EXCL
)) != (_O_CREAT
| _O_EXCL
))
4313 res
= _open (mpath_a
, (oflag
& ~_O_CREAT
) | _O_NOINHERIT
, mode
);
4315 res
= _open (mpath_a
, oflag
| _O_NOINHERIT
, mode
);
4321 /* Implementation of mkostemp for MS-Windows, to avoid race conditions
4324 Standard algorithm for generating a temporary file name seems to be
4325 use pid or tid with a letter on the front (in place of the 6 X's)
4326 and cycle through the letters to find a unique name. We extend
4327 that to allow any reasonable character as the first of the 6 X's,
4328 so that the number of simultaneously used temporary files will be
4332 mkostemp (char * template, int flags
)
4336 unsigned uid
= GetCurrentThreadId ();
4337 int save_errno
= errno
;
4338 static char first_char
[] = "abcdefghijklmnopqrstuvwyz0123456789!%-_@#";
4341 if (template == NULL
)
4344 p
= template + strlen (template);
4346 /* replace up to the last 5 X's with uid in decimal */
4347 while (--p
>= template && p
[0] == 'X' && --i
>= 0)
4349 p
[0] = '0' + uid
% 10;
4353 if (i
< 0 && p
[0] == 'X')
4358 p
[0] = first_char
[i
];
4359 if ((fd
= sys_open (template,
4360 flags
| _O_CREAT
| _O_EXCL
| _O_RDWR
,
4361 S_IRUSR
| S_IWUSR
)) >= 0
4369 while (++i
< sizeof (first_char
));
4372 /* Template is badly formed or else we can't generate a unique name. */
4377 fchmod (int fd
, mode_t mode
)
4383 sys_rename_replace (const char *oldname
, const char *newname
, BOOL force
)
4386 char temp
[MAX_UTF8_PATH
], temp_a
[MAX_PATH
];;
4389 bool have_temp_a
= false;
4391 /* MoveFile on Windows 95 doesn't correctly change the short file name
4392 alias in a number of circumstances (it is not easy to predict when
4393 just by looking at oldname and newname, unfortunately). In these
4394 cases, renaming through a temporary name avoids the problem.
4396 A second problem on Windows 95 is that renaming through a temp name when
4397 newname is uppercase fails (the final long name ends up in
4398 lowercase, although the short alias might be uppercase) UNLESS the
4399 long temp name is not 8.3.
4401 So, on Windows 95 we always rename through a temp name, and we make sure
4402 the temp name has a long extension to ensure correct renaming. */
4404 strcpy (temp
, map_w32_filename (oldname
, NULL
));
4406 /* volume_info is set indirectly by map_w32_filename. */
4407 oldname_dev
= volume_info
.serialnum
;
4409 if (os_subtype
== OS_9X
)
4414 char oldname_a
[MAX_PATH
];
4416 oldname
= map_w32_filename (oldname
, NULL
);
4417 filename_to_ansi (oldname
, oldname_a
);
4418 filename_to_ansi (temp
, temp_a
);
4419 if ((o
= strrchr (oldname_a
, '\\')))
4422 o
= (char *) oldname_a
;
4424 if ((p
= strrchr (temp_a
, '\\')))
4431 /* Force temp name to require a manufactured 8.3 alias - this
4432 seems to make the second rename work properly. */
4433 sprintf (p
, "_.%s.%u", o
, i
);
4435 result
= rename (oldname_a
, temp_a
);
4437 /* This loop must surely terminate! */
4438 while (result
< 0 && errno
== EEXIST
);
4444 /* If FORCE, emulate Unix behavior - newname is deleted if it already exists
4445 (at least if it is a file; don't do this for directories).
4447 Since we mustn't do this if we are just changing the case of the
4448 file name (we would end up deleting the file we are trying to
4449 rename!), we let rename detect if the destination file already
4450 exists - that way we avoid the possible pitfalls of trying to
4451 determine ourselves whether two names really refer to the same
4452 file, which is not always possible in the general case. (Consider
4453 all the permutations of shared or subst'd drives, etc.) */
4455 newname
= map_w32_filename (newname
, NULL
);
4457 /* volume_info is set indirectly by map_w32_filename. */
4458 newname_dev
= volume_info
.serialnum
;
4460 if (w32_unicode_filenames
)
4462 wchar_t temp_w
[MAX_PATH
], newname_w
[MAX_PATH
];
4464 filename_to_utf16 (temp
, temp_w
);
4465 filename_to_utf16 (newname
, newname_w
);
4466 result
= _wrename (temp_w
, newname_w
);
4467 if (result
< 0 && force
)
4469 DWORD w32err
= GetLastError ();
4472 && newname_dev
!= oldname_dev
)
4474 /* The implementation of `rename' on Windows does not return
4475 errno = EXDEV when you are moving a directory to a
4476 different storage device (ex. logical disk). It returns
4477 EACCES instead. So here we handle such situations and
4481 if ((attributes
= GetFileAttributesW (temp_w
)) != -1
4482 && (attributes
& FILE_ATTRIBUTE_DIRECTORY
))
4485 else if (errno
== EEXIST
)
4487 if (_wchmod (newname_w
, 0666) != 0)
4489 if (_wunlink (newname_w
) != 0)
4491 result
= _wrename (temp_w
, newname_w
);
4493 else if (w32err
== ERROR_PRIVILEGE_NOT_HELD
4494 && is_symlink (temp
))
4496 /* This is Windows prohibiting the user from creating a
4497 symlink in another place, since that requires
4505 char newname_a
[MAX_PATH
];
4508 filename_to_ansi (temp
, temp_a
);
4509 filename_to_ansi (newname
, newname_a
);
4510 result
= rename (temp_a
, newname_a
);
4511 if (result
< 0 && force
)
4513 DWORD w32err
= GetLastError ();
4516 && newname_dev
!= oldname_dev
)
4520 if ((attributes
= GetFileAttributesA (temp_a
)) != -1
4521 && (attributes
& FILE_ATTRIBUTE_DIRECTORY
))
4524 else if (errno
== EEXIST
)
4526 if (_chmod (newname_a
, 0666) != 0)
4528 if (_unlink (newname_a
) != 0)
4530 result
= rename (temp_a
, newname_a
);
4532 else if (w32err
== ERROR_PRIVILEGE_NOT_HELD
4533 && is_symlink (temp
))
4542 sys_rename (char const *old
, char const *new)
4544 return sys_rename_replace (old
, new, TRUE
);
4548 sys_rmdir (const char * path
)
4550 path
= map_w32_filename (path
, NULL
);
4552 if (w32_unicode_filenames
)
4554 wchar_t path_w
[MAX_PATH
];
4556 filename_to_utf16 (path
, path_w
);
4557 return _wrmdir (path_w
);
4561 char path_a
[MAX_PATH
];
4563 filename_to_ansi (path
, path_a
);
4564 return _rmdir (path_a
);
4569 sys_unlink (const char * path
)
4573 path
= map_w32_filename (path
, NULL
);
4575 if (w32_unicode_filenames
)
4577 wchar_t path_w
[MAX_PATH
];
4579 filename_to_utf16 (path
, path_w
);
4580 /* On Unix, unlink works without write permission. */
4581 _wchmod (path_w
, 0666);
4582 rmstatus
= _wunlink (path_w
);
4584 /* Symlinks to directories can only be deleted by _rmdir;
4585 _unlink returns EACCES. */
4588 && (is_symlink (path
) & FILE_ATTRIBUTE_DIRECTORY
) != 0)
4589 rmstatus
= _wrmdir (path_w
);
4595 char path_a
[MAX_PATH
];
4597 filename_to_ansi (path
, path_a
);
4598 _chmod (path_a
, 0666);
4599 rmstatus
= _unlink (path_a
);
4603 && (is_symlink (path
) & FILE_ATTRIBUTE_DIRECTORY
) != 0)
4604 rmstatus
= _rmdir (path_a
);
4612 static FILETIME utc_base_ft
;
4613 static ULONGLONG utc_base
; /* In 100ns units */
4614 static int init
= 0;
4616 #define FILETIME_TO_U64(result, ft) \
4618 ULARGE_INTEGER uiTemp; \
4619 uiTemp.LowPart = (ft).dwLowDateTime; \
4620 uiTemp.HighPart = (ft).dwHighDateTime; \
4621 result = uiTemp.QuadPart; \
4625 initialize_utc_base (void)
4627 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
4636 st
.wMilliseconds
= 0;
4638 SystemTimeToFileTime (&st
, &utc_base_ft
);
4639 FILETIME_TO_U64 (utc_base
, utc_base_ft
);
4643 convert_time (FILETIME ft
)
4649 initialize_utc_base ();
4653 if (CompareFileTime (&ft
, &utc_base_ft
) < 0)
4656 FILETIME_TO_U64 (tmp
, ft
);
4657 return (time_t) ((tmp
- utc_base
) / 10000000L);
4661 convert_from_time_t (time_t time
, FILETIME
* pft
)
4667 initialize_utc_base ();
4671 /* time in 100ns units since 1-Jan-1601 */
4672 tmp
.QuadPart
= (ULONGLONG
) time
* 10000000L + utc_base
;
4673 pft
->dwHighDateTime
= tmp
.HighPart
;
4674 pft
->dwLowDateTime
= tmp
.LowPart
;
4677 static PSECURITY_DESCRIPTOR
4678 get_file_security_desc_by_handle (HANDLE h
)
4680 PSECURITY_DESCRIPTOR psd
= NULL
;
4682 SECURITY_INFORMATION si
= OWNER_SECURITY_INFORMATION
4683 | GROUP_SECURITY_INFORMATION
/* | DACL_SECURITY_INFORMATION */ ;
4685 err
= get_security_info (h
, SE_FILE_OBJECT
, si
,
4686 NULL
, NULL
, NULL
, NULL
, &psd
);
4687 if (err
!= ERROR_SUCCESS
)
4693 static PSECURITY_DESCRIPTOR
4694 get_file_security_desc_by_name (const char *fname
)
4696 PSECURITY_DESCRIPTOR psd
= NULL
;
4698 SECURITY_INFORMATION si
= OWNER_SECURITY_INFORMATION
4699 | GROUP_SECURITY_INFORMATION
/* | DACL_SECURITY_INFORMATION */ ;
4701 if (!get_file_security (fname
, si
, psd
, 0, &sd_len
))
4703 err
= GetLastError ();
4704 if (err
!= ERROR_INSUFFICIENT_BUFFER
)
4708 psd
= xmalloc (sd_len
);
4709 if (!get_file_security (fname
, si
, psd
, sd_len
, &sd_len
))
4721 unsigned n_subauthorities
;
4723 /* Use the last sub-authority value of the RID, the relative
4724 portion of the SID, as user/group ID. */
4725 n_subauthorities
= *get_sid_sub_authority_count (sid
);
4726 if (n_subauthorities
< 1)
4727 return 0; /* the "World" RID */
4728 return *get_sid_sub_authority (sid
, n_subauthorities
- 1);
4731 /* Caching SID and account values for faster lokup. */
4735 struct w32_id
*next
;
4737 unsigned char sid
[FLEXIBLE_ARRAY_MEMBER
];
4740 static struct w32_id
*w32_idlist
;
4743 w32_cached_id (PSID sid
, unsigned *id
, char *name
)
4745 struct w32_id
*tail
, *found
;
4747 for (found
= NULL
, tail
= w32_idlist
; tail
; tail
= tail
->next
)
4749 if (equal_sid ((PSID
)tail
->sid
, sid
))
4758 strcpy (name
, found
->name
);
4766 w32_add_to_cache (PSID sid
, unsigned id
, char *name
)
4769 struct w32_id
*new_entry
;
4771 /* We don't want to leave behind stale cache from when Emacs was
4775 sid_len
= get_length_sid (sid
);
4776 new_entry
= xmalloc (offsetof (struct w32_id
, sid
) + sid_len
);
4779 new_entry
->rid
= id
;
4780 strcpy (new_entry
->name
, name
);
4781 copy_sid (sid_len
, (PSID
)new_entry
->sid
, sid
);
4782 new_entry
->next
= w32_idlist
;
4783 w32_idlist
= new_entry
;
4792 get_name_and_id (PSECURITY_DESCRIPTOR psd
, unsigned *id
, char *nm
, int what
)
4796 SID_NAME_USE ignore
;
4798 DWORD name_len
= sizeof (name
);
4800 DWORD domain_len
= sizeof (domain
);
4805 result
= get_security_descriptor_owner (psd
, &sid
, &dflt
);
4806 else if (what
== GID
)
4807 result
= get_security_descriptor_group (psd
, &sid
, &dflt
);
4811 if (!result
|| !is_valid_sid (sid
))
4813 else if (!w32_cached_id (sid
, id
, nm
))
4815 if (!lookup_account_sid (NULL
, sid
, name
, &name_len
,
4816 domain
, &domain_len
, &ignore
)
4817 || name_len
> UNLEN
+1)
4821 *id
= get_rid (sid
);
4823 w32_add_to_cache (sid
, *id
, name
);
4830 get_file_owner_and_group (PSECURITY_DESCRIPTOR psd
, struct stat
*st
)
4832 int dflt_usr
= 0, dflt_grp
= 0;
4841 if (get_name_and_id (psd
, &st
->st_uid
, st
->st_uname
, UID
))
4843 if (get_name_and_id (psd
, &st
->st_gid
, st
->st_gname
, GID
))
4846 /* Consider files to belong to current user/group, if we cannot get
4847 more accurate information. */
4850 st
->st_uid
= dflt_passwd
.pw_uid
;
4851 strcpy (st
->st_uname
, dflt_passwd
.pw_name
);
4855 st
->st_gid
= dflt_passwd
.pw_gid
;
4856 strcpy (st
->st_gname
, dflt_group
.gr_name
);
4860 /* Return non-zero if NAME is a potentially slow filesystem. */
4862 is_slow_fs (const char *name
)
4867 if (IS_DIRECTORY_SEP (name
[0]) && IS_DIRECTORY_SEP (name
[1]))
4868 devtype
= DRIVE_REMOTE
; /* assume UNC name is remote */
4869 else if (!(strlen (name
) >= 2 && IS_DEVICE_SEP (name
[1])))
4870 devtype
= GetDriveType (NULL
); /* use root of current drive */
4873 /* GetDriveType needs the root directory of the drive. */
4874 strncpy (drive_root
, name
, 2);
4875 drive_root
[2] = '\\';
4876 drive_root
[3] = '\0';
4877 devtype
= GetDriveType (drive_root
);
4879 return !(devtype
== DRIVE_FIXED
|| devtype
== DRIVE_RAMDISK
);
4882 /* If this is non-zero, the caller wants accurate information about
4883 file's owner and group, which could be expensive to get. dired.c
4884 uses this flag when needed for the job at hand. */
4885 int w32_stat_get_owner_group
;
4887 /* MSVC stat function can't cope with UNC names and has other bugs, so
4888 replace it with our own. This also allows us to calculate consistent
4889 inode values and owner/group without hacks in the main Emacs code,
4890 and support file names encoded in UTF-8. */
4893 stat_worker (const char * path
, struct stat
* buf
, int follow_symlinks
)
4895 char *name
, *save_name
, *r
;
4896 WIN32_FIND_DATAW wfd_w
;
4897 WIN32_FIND_DATAA wfd_a
;
4899 unsigned __int64 fake_inode
= 0;
4902 int rootdir
= FALSE
;
4903 PSECURITY_DESCRIPTOR psd
= NULL
;
4904 int is_a_symlink
= 0;
4905 DWORD file_flags
= FILE_FLAG_BACKUP_SEMANTICS
;
4906 DWORD access_rights
= 0;
4907 DWORD fattrs
= 0, serialnum
= 0, fs_high
= 0, fs_low
= 0, nlinks
= 1;
4908 FILETIME ctime
, atime
, wtime
;
4909 wchar_t name_w
[MAX_PATH
];
4910 char name_a
[MAX_PATH
];
4912 if (path
== NULL
|| buf
== NULL
)
4918 save_name
= name
= (char *) map_w32_filename (path
, &path
);
4919 /* Must be valid filename, no wild cards or other invalid
4921 if (strpbrk (name
, "*?|<>\""))
4927 len
= strlen (name
);
4928 /* Allocate 1 extra byte so that we could append a slash to a root
4929 directory, down below. */
4930 name
= strcpy (alloca (len
+ 2), name
);
4932 /* Avoid a somewhat costly call to is_symlink if the filesystem
4933 doesn't support symlinks. */
4934 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) != 0)
4935 is_a_symlink
= is_symlink (name
);
4937 /* Plan A: Open the file and get all the necessary information via
4938 the resulting handle. This solves several issues in one blow:
4940 . retrieves attributes for the target of a symlink, if needed
4941 . gets attributes of root directories and symlinks pointing to
4942 root directories, thus avoiding the need for special-casing
4943 these and detecting them by examining the file-name format
4944 . retrieves more accurate attributes (e.g., non-zero size for
4945 some directories, esp. directories that are junction points)
4946 . correctly resolves "c:/..", "/.." and similar file names
4947 . avoids run-time penalties for 99% of use cases
4949 Plan A is always tried first, unless the user asked not to (but
4950 if the file is a symlink and we need to follow links, we try Plan
4951 A even if the user asked not to).
4953 If Plan A fails, we go to Plan B (below), where various
4954 potentially expensive techniques must be used to handle "special"
4955 files such as UNC volumes etc. */
4956 if (!(NILP (Vw32_get_true_file_attributes
)
4957 || (EQ (Vw32_get_true_file_attributes
, Qlocal
) && is_slow_fs (name
)))
4958 /* Following symlinks requires getting the info by handle. */
4959 || (is_a_symlink
&& follow_symlinks
))
4961 BY_HANDLE_FILE_INFORMATION info
;
4963 if (is_a_symlink
&& !follow_symlinks
)
4964 file_flags
|= FILE_FLAG_OPEN_REPARSE_POINT
;
4965 /* READ_CONTROL access rights are required to get security info
4966 by handle. But if the OS doesn't support security in the
4967 first place, we don't need to try. */
4968 if (is_windows_9x () != TRUE
)
4969 access_rights
|= READ_CONTROL
;
4971 if (w32_unicode_filenames
)
4973 filename_to_utf16 (name
, name_w
);
4974 fh
= CreateFileW (name_w
, access_rights
, 0, NULL
, OPEN_EXISTING
,
4976 /* If CreateFile fails with READ_CONTROL, try again with
4977 zero as access rights. */
4978 if (fh
== INVALID_HANDLE_VALUE
&& access_rights
)
4979 fh
= CreateFileW (name_w
, 0, 0, NULL
, OPEN_EXISTING
,
4984 filename_to_ansi (name
, name_a
);
4985 fh
= CreateFileA (name_a
, access_rights
, 0, NULL
, OPEN_EXISTING
,
4987 if (fh
== INVALID_HANDLE_VALUE
&& access_rights
)
4988 fh
= CreateFileA (name_a
, 0, 0, NULL
, OPEN_EXISTING
,
4991 if (fh
== INVALID_HANDLE_VALUE
)
4992 goto no_true_file_attributes
;
4994 /* This is more accurate in terms of getting the correct number
4995 of links, but is quite slow (it is noticeable when Emacs is
4996 making a list of file name completions). */
4997 if (GetFileInformationByHandle (fh
, &info
))
4999 nlinks
= info
.nNumberOfLinks
;
5000 /* Might as well use file index to fake inode values, but this
5001 is not guaranteed to be unique unless we keep a handle open
5002 all the time (even then there are situations where it is
5003 not unique). Reputedly, there are at most 48 bits of info
5004 (on NTFS, presumably less on FAT). */
5005 fake_inode
= info
.nFileIndexHigh
;
5007 fake_inode
+= info
.nFileIndexLow
;
5008 serialnum
= info
.dwVolumeSerialNumber
;
5009 fs_high
= info
.nFileSizeHigh
;
5010 fs_low
= info
.nFileSizeLow
;
5011 ctime
= info
.ftCreationTime
;
5012 atime
= info
.ftLastAccessTime
;
5013 wtime
= info
.ftLastWriteTime
;
5014 fattrs
= info
.dwFileAttributes
;
5018 /* We don't go to Plan B here, because it's not clear that
5019 it's a good idea. The only known use case where
5020 CreateFile succeeds, but GetFileInformationByHandle fails
5021 (with ERROR_INVALID_FUNCTION) is for character devices
5022 such as NUL, PRN, etc. For these, switching to Plan B is
5023 a net loss, because we lose the character device
5024 attribute returned by GetFileType below (FindFirstFile
5025 doesn't set that bit in the attributes), and the other
5026 fields don't make sense for character devices anyway.
5027 Emacs doesn't really care for non-file entities in the
5028 context of l?stat, so neither do we. */
5030 /* w32err is assigned so one could put a breakpoint here and
5031 examine its value, when GetFileInformationByHandle
5033 DWORD w32err
= GetLastError ();
5037 case ERROR_FILE_NOT_FOUND
: /* can this ever happen? */
5043 /* Test for a symlink before testing for a directory, since
5044 symlinks to directories have the directory bit set, but we
5045 don't want them to appear as directories. */
5046 if (is_a_symlink
&& !follow_symlinks
)
5047 buf
->st_mode
= S_IFLNK
;
5048 else if (fattrs
& FILE_ATTRIBUTE_DIRECTORY
)
5049 buf
->st_mode
= S_IFDIR
;
5052 DWORD ftype
= GetFileType (fh
);
5056 case FILE_TYPE_DISK
:
5057 buf
->st_mode
= S_IFREG
;
5059 case FILE_TYPE_PIPE
:
5060 buf
->st_mode
= S_IFIFO
;
5062 case FILE_TYPE_CHAR
:
5063 case FILE_TYPE_UNKNOWN
:
5065 buf
->st_mode
= S_IFCHR
;
5068 /* We produce the fallback owner and group data, based on the
5069 current user that runs Emacs, in the following cases:
5071 . caller didn't request owner and group info
5072 . this is Windows 9X
5073 . getting security by handle failed, and we need to produce
5074 information for the target of a symlink (this is better
5075 than producing a potentially misleading info about the
5078 If getting security by handle fails, and we don't need to
5079 resolve symlinks, we try getting security by name. */
5080 if (!w32_stat_get_owner_group
|| is_windows_9x () == TRUE
)
5081 get_file_owner_and_group (NULL
, buf
);
5084 psd
= get_file_security_desc_by_handle (fh
);
5087 get_file_owner_and_group (psd
, buf
);
5090 else if (!(is_a_symlink
&& follow_symlinks
))
5092 psd
= get_file_security_desc_by_name (name
);
5093 get_file_owner_and_group (psd
, buf
);
5097 get_file_owner_and_group (NULL
, buf
);
5103 no_true_file_attributes
:
5104 /* Plan B: Either getting a handle on the file failed, or the
5105 caller explicitly asked us to not bother making this
5106 information more accurate.
5108 Implementation note: In Plan B, we never bother to resolve
5109 symlinks, even if we got here because we tried Plan A and
5110 failed. That's because, even if the caller asked for extra
5111 precision by setting Vw32_get_true_file_attributes to t,
5112 resolving symlinks requires acquiring a file handle to the
5113 symlink, which we already know will fail. And if the user
5114 did not ask for extra precision, resolving symlinks will fly
5115 in the face of that request, since the user then wants the
5116 lightweight version of the code. */
5117 rootdir
= (path
>= save_name
+ len
- 1
5118 && (IS_DIRECTORY_SEP (*path
) || *path
== 0));
5120 /* If name is "c:/.." or "/.." then stat "c:/" or "/". */
5121 r
= IS_DEVICE_SEP (name
[1]) ? &name
[2] : name
;
5122 if (IS_DIRECTORY_SEP (r
[0])
5123 && r
[1] == '.' && r
[2] == '.' && r
[3] == '\0')
5126 /* Note: If NAME is a symlink to the root of a UNC volume
5127 (i.e. "\\SERVER"), we will not detect that here, and we will
5128 return data about the symlink as result of FindFirst below.
5129 This is unfortunate, but that marginal use case does not
5130 justify a call to chase_symlinks which would impose a penalty
5131 on all the other use cases. (We get here for symlinks to
5132 roots of UNC volumes because CreateFile above fails for them,
5133 unlike with symlinks to root directories X:\ of drives.) */
5134 if (is_unc_volume (name
))
5136 fattrs
= unc_volume_file_attributes (name
);
5140 ctime
= atime
= wtime
= utc_base_ft
;
5144 /* Make sure root directories end in a slash. */
5145 if (!IS_DIRECTORY_SEP (name
[len
-1]))
5146 strcpy (name
+ len
, "\\");
5147 if (GetDriveType (name
) < 2)
5153 fattrs
= FILE_ATTRIBUTE_DIRECTORY
;
5154 ctime
= atime
= wtime
= utc_base_ft
;
5160 /* Make sure non-root directories do NOT end in a slash,
5161 otherwise FindFirstFile might fail. */
5162 if (IS_DIRECTORY_SEP (name
[len
-1]))
5165 /* (This is hacky, but helps when doing file completions on
5166 network drives.) Optimize by using information available from
5167 active readdir if possible. */
5168 len
= strlen (dir_pathname
);
5169 if (IS_DIRECTORY_SEP (dir_pathname
[len
-1]))
5171 if (dir_find_handle
!= INVALID_HANDLE_VALUE
5172 && last_dir_find_data
!= -1
5173 && !(is_a_symlink
&& follow_symlinks
)
5174 /* The 2 file-name comparisons below support only ASCII
5175 characters, and will lose (compare not equal) when
5176 the file names include non-ASCII characters that are
5177 the same but for the case. However, doing this
5178 properly involves: (a) converting both file names to
5179 UTF-16, (b) lower-casing both names using CharLowerW,
5180 and (c) comparing the results; this would be quite a
5181 bit slower, whereas Plan B is for users who want
5182 lightweight albeit inaccurate version of 'stat'. */
5183 && c_strncasecmp (save_name
, dir_pathname
, len
) == 0
5184 && IS_DIRECTORY_SEP (name
[len
])
5185 && xstrcasecmp (name
+ len
+ 1, dir_static
.d_name
) == 0)
5187 have_wfd
= last_dir_find_data
;
5188 /* This was the last entry returned by readdir. */
5189 if (last_dir_find_data
== DIR_FIND_DATA_W
)
5190 wfd_w
= dir_find_data_w
;
5192 wfd_a
= dir_find_data_a
;
5196 logon_network_drive (name
);
5198 if (w32_unicode_filenames
)
5200 filename_to_utf16 (name
, name_w
);
5201 fh
= FindFirstFileW (name_w
, &wfd_w
);
5202 have_wfd
= DIR_FIND_DATA_W
;
5206 filename_to_ansi (name
, name_a
);
5207 /* If NAME includes characters not representable by
5208 the current ANSI codepage, filename_to_ansi
5209 usually replaces them with a '?'. We don't want
5210 to let FindFirstFileA interpret those as wildcards,
5211 and "succeed", returning us data from some random
5212 file in the same directory. */
5213 if (_mbspbrk (name_a
, "?"))
5214 fh
= INVALID_HANDLE_VALUE
;
5216 fh
= FindFirstFileA (name_a
, &wfd_a
);
5217 have_wfd
= DIR_FIND_DATA_A
;
5219 if (fh
== INVALID_HANDLE_VALUE
)
5226 /* Note: if NAME is a symlink, the information we get from
5227 FindFirstFile is for the symlink, not its target. */
5228 if (have_wfd
== DIR_FIND_DATA_W
)
5230 fattrs
= wfd_w
.dwFileAttributes
;
5231 ctime
= wfd_w
.ftCreationTime
;
5232 atime
= wfd_w
.ftLastAccessTime
;
5233 wtime
= wfd_w
.ftLastWriteTime
;
5234 fs_high
= wfd_w
.nFileSizeHigh
;
5235 fs_low
= wfd_w
.nFileSizeLow
;
5239 fattrs
= wfd_a
.dwFileAttributes
;
5240 ctime
= wfd_a
.ftCreationTime
;
5241 atime
= wfd_a
.ftLastAccessTime
;
5242 wtime
= wfd_a
.ftLastWriteTime
;
5243 fs_high
= wfd_a
.nFileSizeHigh
;
5244 fs_low
= wfd_a
.nFileSizeLow
;
5248 serialnum
= volume_info
.serialnum
;
5250 if (is_a_symlink
&& !follow_symlinks
)
5251 buf
->st_mode
= S_IFLNK
;
5252 else if (fattrs
& FILE_ATTRIBUTE_DIRECTORY
)
5253 buf
->st_mode
= S_IFDIR
;
5255 buf
->st_mode
= S_IFREG
;
5257 get_file_owner_and_group (NULL
, buf
);
5260 buf
->st_ino
= fake_inode
;
5262 buf
->st_dev
= serialnum
;
5263 buf
->st_rdev
= serialnum
;
5265 buf
->st_size
= fs_high
;
5266 buf
->st_size
<<= 32;
5267 buf
->st_size
+= fs_low
;
5268 buf
->st_nlink
= nlinks
;
5270 /* Convert timestamps to Unix format. */
5271 buf
->st_mtime
= convert_time (wtime
);
5272 buf
->st_atime
= convert_time (atime
);
5273 if (buf
->st_atime
== 0) buf
->st_atime
= buf
->st_mtime
;
5274 buf
->st_ctime
= convert_time (ctime
);
5275 if (buf
->st_ctime
== 0) buf
->st_ctime
= buf
->st_mtime
;
5277 /* determine rwx permissions */
5278 if (is_a_symlink
&& !follow_symlinks
)
5279 permission
= S_IREAD
| S_IWRITE
| S_IEXEC
; /* Posix expectations */
5282 if (fattrs
& FILE_ATTRIBUTE_READONLY
)
5283 permission
= S_IREAD
;
5285 permission
= S_IREAD
| S_IWRITE
;
5287 if (fattrs
& FILE_ATTRIBUTE_DIRECTORY
)
5288 permission
|= S_IEXEC
;
5289 else if (is_exec (name
))
5290 permission
|= S_IEXEC
;
5293 buf
->st_mode
|= permission
| (permission
>> 3) | (permission
>> 6);
5299 stat (const char * path
, struct stat
* buf
)
5301 return stat_worker (path
, buf
, 1);
5305 lstat (const char * path
, struct stat
* buf
)
5307 return stat_worker (path
, buf
, 0);
5311 fstatat (int fd
, char const *name
, struct stat
*st
, int flags
)
5313 /* Rely on a hack: an open directory is modeled as file descriptor 0.
5314 This is good enough for the current usage in Emacs, but is fragile.
5316 FIXME: Add proper support for fdopendir, fstatat, readlinkat.
5317 Gnulib does this and can serve as a model. */
5318 char fullname
[MAX_UTF8_PATH
];
5322 char lastc
= dir_pathname
[strlen (dir_pathname
) - 1];
5324 if (_snprintf (fullname
, sizeof fullname
, "%s%s%s",
5325 dir_pathname
, IS_DIRECTORY_SEP (lastc
) ? "" : "/", name
)
5328 errno
= ENAMETOOLONG
;
5334 return stat_worker (name
, st
, ! (flags
& AT_SYMLINK_NOFOLLOW
));
5337 /* Provide fstat and utime as well as stat for consistent handling of
5340 fstat (int desc
, struct stat
* buf
)
5342 HANDLE fh
= (HANDLE
) _get_osfhandle (desc
);
5343 BY_HANDLE_FILE_INFORMATION info
;
5344 unsigned __int64 fake_inode
;
5347 switch (GetFileType (fh
) & ~FILE_TYPE_REMOTE
)
5349 case FILE_TYPE_DISK
:
5350 buf
->st_mode
= S_IFREG
;
5351 if (!GetFileInformationByHandle (fh
, &info
))
5357 case FILE_TYPE_PIPE
:
5358 buf
->st_mode
= S_IFIFO
;
5360 case FILE_TYPE_CHAR
:
5361 case FILE_TYPE_UNKNOWN
:
5363 buf
->st_mode
= S_IFCHR
;
5365 memset (&info
, 0, sizeof (info
));
5366 info
.dwFileAttributes
= 0;
5367 info
.ftCreationTime
= utc_base_ft
;
5368 info
.ftLastAccessTime
= utc_base_ft
;
5369 info
.ftLastWriteTime
= utc_base_ft
;
5372 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
5373 buf
->st_mode
= S_IFDIR
;
5375 buf
->st_nlink
= info
.nNumberOfLinks
;
5376 /* Might as well use file index to fake inode values, but this
5377 is not guaranteed to be unique unless we keep a handle open
5378 all the time (even then there are situations where it is
5379 not unique). Reputedly, there are at most 48 bits of info
5380 (on NTFS, presumably less on FAT). */
5381 fake_inode
= info
.nFileIndexHigh
;
5383 fake_inode
+= info
.nFileIndexLow
;
5385 /* MSVC defines _ino_t to be short; other libc's might not. */
5386 if (sizeof (buf
->st_ino
) == 2)
5387 buf
->st_ino
= fake_inode
^ (fake_inode
>> 16);
5389 buf
->st_ino
= fake_inode
;
5391 /* If the caller so requested, get the true file owner and group.
5392 Otherwise, consider the file to belong to the current user. */
5393 if (!w32_stat_get_owner_group
|| is_windows_9x () == TRUE
)
5394 get_file_owner_and_group (NULL
, buf
);
5397 PSECURITY_DESCRIPTOR psd
= NULL
;
5399 psd
= get_file_security_desc_by_handle (fh
);
5402 get_file_owner_and_group (psd
, buf
);
5406 get_file_owner_and_group (NULL
, buf
);
5409 buf
->st_dev
= info
.dwVolumeSerialNumber
;
5410 buf
->st_rdev
= info
.dwVolumeSerialNumber
;
5412 buf
->st_size
= info
.nFileSizeHigh
;
5413 buf
->st_size
<<= 32;
5414 buf
->st_size
+= info
.nFileSizeLow
;
5416 /* Convert timestamps to Unix format. */
5417 buf
->st_mtime
= convert_time (info
.ftLastWriteTime
);
5418 buf
->st_atime
= convert_time (info
.ftLastAccessTime
);
5419 if (buf
->st_atime
== 0) buf
->st_atime
= buf
->st_mtime
;
5420 buf
->st_ctime
= convert_time (info
.ftCreationTime
);
5421 if (buf
->st_ctime
== 0) buf
->st_ctime
= buf
->st_mtime
;
5423 /* determine rwx permissions */
5424 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
)
5425 permission
= S_IREAD
;
5427 permission
= S_IREAD
| S_IWRITE
;
5429 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
5430 permission
|= S_IEXEC
;
5433 #if 0 /* no way of knowing the filename */
5434 char * p
= strrchr (name
, '.');
5436 (xstrcasecmp (p
, ".exe") == 0 ||
5437 xstrcasecmp (p
, ".com") == 0 ||
5438 xstrcasecmp (p
, ".bat") == 0 ||
5439 xstrcasecmp (p
, ".cmd") == 0))
5440 permission
|= S_IEXEC
;
5444 buf
->st_mode
|= permission
| (permission
>> 3) | (permission
>> 6);
5449 /* A version of 'utime' which handles directories as well as
5453 utime (const char *name
, struct utimbuf
*times
)
5455 struct utimbuf deftime
;
5462 deftime
.modtime
= deftime
.actime
= time (NULL
);
5466 if (w32_unicode_filenames
)
5468 wchar_t name_utf16
[MAX_PATH
];
5470 if (filename_to_utf16 (name
, name_utf16
) != 0)
5471 return -1; /* errno set by filename_to_utf16 */
5473 /* Need write access to set times. */
5474 fh
= CreateFileW (name_utf16
, FILE_WRITE_ATTRIBUTES
,
5475 /* If NAME specifies a directory, FILE_SHARE_DELETE
5476 allows other processes to delete files inside it,
5477 while we have the directory open. */
5478 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
5479 0, OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
5483 char name_ansi
[MAX_PATH
];
5485 if (filename_to_ansi (name
, name_ansi
) != 0)
5486 return -1; /* errno set by filename_to_ansi */
5488 fh
= CreateFileA (name_ansi
, FILE_WRITE_ATTRIBUTES
,
5489 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
5490 0, OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
5492 if (fh
!= INVALID_HANDLE_VALUE
)
5494 convert_from_time_t (times
->actime
, &atime
);
5495 convert_from_time_t (times
->modtime
, &mtime
);
5496 if (!SetFileTime (fh
, NULL
, &atime
, &mtime
))
5506 DWORD err
= GetLastError ();
5510 case ERROR_FILE_NOT_FOUND
:
5511 case ERROR_PATH_NOT_FOUND
:
5512 case ERROR_INVALID_DRIVE
:
5513 case ERROR_BAD_NETPATH
:
5514 case ERROR_DEV_NOT_EXIST
:
5515 /* ERROR_INVALID_NAME is the error CreateFile sets when the
5516 file name includes ?s, i.e. translation to ANSI failed. */
5517 case ERROR_INVALID_NAME
:
5520 case ERROR_TOO_MANY_OPEN_FILES
:
5523 case ERROR_ACCESS_DENIED
:
5524 case ERROR_SHARING_VIOLATION
:
5537 sys_umask (int mode
)
5539 static int current_mask
;
5540 int retval
, arg
= 0;
5542 /* The only bit we really support is the write bit. Files are
5543 always readable on MS-Windows, and the execute bit does not exist
5545 /* FIXME: if the GROUP and OTHER bits are reset, we should use ACLs
5546 to prevent access by other users on NTFS. */
5547 if ((mode
& S_IWRITE
) != 0)
5550 retval
= _umask (arg
);
5551 /* Merge into the return value the bits they've set the last time,
5552 which msvcrt.dll ignores and never returns. Emacs insists on its
5553 notion of mask being identical to what we return. */
5554 retval
|= (current_mask
& ~S_IWRITE
);
5555 current_mask
= mode
;
5561 /* Symlink-related functions. */
5562 #ifndef SYMBOLIC_LINK_FLAG_DIRECTORY
5563 #define SYMBOLIC_LINK_FLAG_DIRECTORY 0x1
5567 symlink (char const *filename
, char const *linkname
)
5569 char linkfn
[MAX_UTF8_PATH
], *tgtfn
;
5571 int dir_access
, filename_ends_in_slash
;
5573 /* Diagnostics follows Posix as much as possible. */
5574 if (filename
== NULL
|| linkname
== NULL
)
5584 if (strlen (filename
) > MAX_UTF8_PATH
|| strlen (linkname
) > MAX_UTF8_PATH
)
5586 errno
= ENAMETOOLONG
;
5590 strcpy (linkfn
, map_w32_filename (linkname
, NULL
));
5591 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) == 0)
5597 /* Note: since empty FILENAME was already rejected, we can safely
5598 refer to FILENAME[1]. */
5599 if (!(IS_DIRECTORY_SEP (filename
[0]) || IS_DEVICE_SEP (filename
[1])))
5601 /* Non-absolute FILENAME is understood as being relative to
5602 LINKNAME's directory. We need to prepend that directory to
5603 FILENAME to get correct results from faccessat below, since
5604 otherwise it will interpret FILENAME relative to the
5605 directory where the Emacs process runs. Note that
5606 make-symbolic-link always makes sure LINKNAME is a fully
5607 expanded file name. */
5608 char tem
[MAX_UTF8_PATH
];
5609 char *p
= linkfn
+ strlen (linkfn
);
5611 while (p
> linkfn
&& !IS_ANY_SEP (p
[-1]))
5614 strncpy (tem
, linkfn
, p
- linkfn
);
5615 strcpy (tem
+ (p
- linkfn
), filename
);
5616 dir_access
= faccessat (AT_FDCWD
, tem
, D_OK
, AT_EACCESS
);
5619 dir_access
= faccessat (AT_FDCWD
, filename
, D_OK
, AT_EACCESS
);
5621 /* Since Windows distinguishes between symlinks to directories and
5622 to files, we provide a kludgy feature: if FILENAME doesn't
5623 exist, but ends in a slash, we create a symlink to directory. If
5624 FILENAME exists and is a directory, we always create a symlink to
5626 filename_ends_in_slash
= IS_DIRECTORY_SEP (filename
[strlen (filename
) - 1]);
5627 if (dir_access
== 0 || filename_ends_in_slash
)
5628 flags
= SYMBOLIC_LINK_FLAG_DIRECTORY
;
5630 tgtfn
= (char *)map_w32_filename (filename
, NULL
);
5631 if (filename_ends_in_slash
)
5632 tgtfn
[strlen (tgtfn
) - 1] = '\0';
5635 if (!create_symbolic_link (linkfn
, tgtfn
, flags
))
5637 /* ENOSYS is set by create_symbolic_link, when it detects that
5638 the OS doesn't support the CreateSymbolicLink API. */
5639 if (errno
!= ENOSYS
)
5641 DWORD w32err
= GetLastError ();
5645 /* ERROR_SUCCESS is sometimes returned when LINKFN and
5646 TGTFN point to the same file name, go figure. */
5648 case ERROR_FILE_EXISTS
:
5651 case ERROR_ACCESS_DENIED
:
5654 case ERROR_FILE_NOT_FOUND
:
5655 case ERROR_PATH_NOT_FOUND
:
5656 case ERROR_BAD_NETPATH
:
5657 case ERROR_INVALID_REPARSE_DATA
:
5660 case ERROR_DIRECTORY
:
5663 case ERROR_PRIVILEGE_NOT_HELD
:
5664 case ERROR_NOT_ALL_ASSIGNED
:
5667 case ERROR_DISK_FULL
:
5680 /* A quick inexpensive test of whether FILENAME identifies a file that
5681 is a symlink. Returns non-zero if it is, zero otherwise. FILENAME
5682 must already be in the normalized form returned by
5683 map_w32_filename. If the symlink is to a directory, the
5684 FILE_ATTRIBUTE_DIRECTORY bit will be set in the return value.
5686 Note: for repeated operations on many files, it is best to test
5687 whether the underlying volume actually supports symlinks, by
5688 testing the FILE_SUPPORTS_REPARSE_POINTS bit in volume's flags, and
5689 avoid the call to this function if it doesn't. That's because the
5690 call to GetFileAttributes takes a non-negligible time, especially
5691 on non-local or removable filesystems. See stat_worker for an
5692 example of how to do that. */
5694 is_symlink (const char *filename
)
5697 wchar_t filename_w
[MAX_PATH
];
5698 char filename_a
[MAX_PATH
];
5699 WIN32_FIND_DATAW wfdw
;
5700 WIN32_FIND_DATAA wfda
;
5702 int attrs_mean_symlink
;
5704 if (w32_unicode_filenames
)
5706 filename_to_utf16 (filename
, filename_w
);
5707 attrs
= GetFileAttributesW (filename_w
);
5711 filename_to_ansi (filename
, filename_a
);
5712 attrs
= GetFileAttributesA (filename_a
);
5716 DWORD w32err
= GetLastError ();
5720 case ERROR_BAD_NETPATH
: /* network share, can't be a symlink */
5722 case ERROR_ACCESS_DENIED
:
5725 case ERROR_FILE_NOT_FOUND
:
5726 case ERROR_PATH_NOT_FOUND
:
5733 if ((attrs
& FILE_ATTRIBUTE_REPARSE_POINT
) == 0)
5735 logon_network_drive (filename
);
5736 if (w32_unicode_filenames
)
5738 fh
= FindFirstFileW (filename_w
, &wfdw
);
5739 attrs_mean_symlink
=
5740 (wfdw
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) != 0
5741 && (wfdw
.dwReserved0
& IO_REPARSE_TAG_SYMLINK
) == IO_REPARSE_TAG_SYMLINK
;
5742 if (attrs_mean_symlink
)
5743 attrs_mean_symlink
|= (wfdw
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
);
5745 else if (_mbspbrk (filename_a
, "?"))
5747 /* filename_to_ansi failed to convert the file name. */
5753 fh
= FindFirstFileA (filename_a
, &wfda
);
5754 attrs_mean_symlink
=
5755 (wfda
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) != 0
5756 && (wfda
.dwReserved0
& IO_REPARSE_TAG_SYMLINK
) == IO_REPARSE_TAG_SYMLINK
;
5757 if (attrs_mean_symlink
)
5758 attrs_mean_symlink
|= (wfda
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
);
5760 if (fh
== INVALID_HANDLE_VALUE
)
5763 return attrs_mean_symlink
;
5766 /* If NAME identifies a symbolic link, copy into BUF the file name of
5767 the symlink's target. Copy at most BUF_SIZE bytes, and do NOT
5768 null-terminate the target name, even if it fits. Return the number
5769 of bytes copied, or -1 if NAME is not a symlink or any error was
5770 encountered while resolving it. The file name copied into BUF is
5771 encoded in the current ANSI codepage. */
5773 readlink (const char *name
, char *buf
, size_t buf_size
)
5776 TOKEN_PRIVILEGES privs
;
5777 int restore_privs
= 0;
5780 char resolved
[MAX_UTF8_PATH
];
5793 path
= map_w32_filename (name
, NULL
);
5795 if (strlen (path
) > MAX_UTF8_PATH
)
5797 errno
= ENAMETOOLONG
;
5802 if (is_windows_9x () == TRUE
5803 || (volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) == 0
5804 || !is_symlink (path
))
5807 errno
= EINVAL
; /* not a symlink */
5811 /* Done with simple tests, now we're in for some _real_ work. */
5812 if (enable_privilege (SE_BACKUP_NAME
, TRUE
, &privs
))
5814 /* Implementation note: From here and onward, don't return early,
5815 since that will fail to restore the original set of privileges of
5816 the calling thread. */
5818 retval
= -1; /* not too optimistic, are we? */
5820 /* Note: In the next call to CreateFile, we use zero as the 2nd
5821 argument because, when the symlink is a hidden/system file,
5822 e.g. 'C:\Users\All Users', GENERIC_READ fails with
5823 ERROR_ACCESS_DENIED. Zero seems to work just fine, both for file
5824 and directory symlinks. */
5825 if (w32_unicode_filenames
)
5827 wchar_t path_w
[MAX_PATH
];
5829 filename_to_utf16 (path
, path_w
);
5830 sh
= CreateFileW (path_w
, 0, 0, NULL
, OPEN_EXISTING
,
5831 FILE_FLAG_OPEN_REPARSE_POINT
5832 | FILE_FLAG_BACKUP_SEMANTICS
,
5837 char path_a
[MAX_PATH
];
5839 filename_to_ansi (path
, path_a
);
5840 sh
= CreateFileA (path_a
, 0, 0, NULL
, OPEN_EXISTING
,
5841 FILE_FLAG_OPEN_REPARSE_POINT
5842 | FILE_FLAG_BACKUP_SEMANTICS
,
5845 if (sh
!= INVALID_HANDLE_VALUE
)
5847 BYTE reparse_buf
[MAXIMUM_REPARSE_DATA_BUFFER_SIZE
];
5848 REPARSE_DATA_BUFFER
*reparse_data
= (REPARSE_DATA_BUFFER
*)&reparse_buf
[0];
5851 if (!DeviceIoControl (sh
, FSCTL_GET_REPARSE_POINT
, NULL
, 0,
5852 reparse_buf
, MAXIMUM_REPARSE_DATA_BUFFER_SIZE
,
5855 else if (reparse_data
->ReparseTag
!= IO_REPARSE_TAG_SYMLINK
)
5859 /* Copy the link target name, in wide characters, from
5860 reparse_data, then convert it to multibyte encoding in
5861 the current locale's codepage. */
5865 reparse_data
->SymbolicLinkReparseBuffer
.PrintNameLength
;
5867 reparse_data
->SymbolicLinkReparseBuffer
.PathBuffer
5868 + reparse_data
->SymbolicLinkReparseBuffer
.PrintNameOffset
/sizeof(WCHAR
);
5869 size_t size_to_copy
= buf_size
;
5871 /* According to MSDN, PrintNameLength does not include the
5872 terminating null character. */
5873 lwname
= alloca ((lwname_len
+ 1) * sizeof(WCHAR
));
5874 memcpy (lwname
, lwname_src
, lwname_len
);
5875 lwname
[lwname_len
/sizeof(WCHAR
)] = 0; /* null-terminate */
5876 filename_from_utf16 (lwname
, resolved
);
5877 dostounix_filename (resolved
);
5878 lname_size
= strlen (resolved
) + 1;
5879 if (lname_size
<= buf_size
)
5880 size_to_copy
= lname_size
;
5881 strncpy (buf
, resolved
, size_to_copy
);
5883 retval
= size_to_copy
;
5889 /* CreateFile failed. */
5890 DWORD w32err2
= GetLastError ();
5894 case ERROR_FILE_NOT_FOUND
:
5895 case ERROR_PATH_NOT_FOUND
:
5898 case ERROR_ACCESS_DENIED
:
5899 case ERROR_TOO_MANY_OPEN_FILES
:
5909 restore_privilege (&privs
);
5917 readlinkat (int fd
, char const *name
, char *buffer
,
5920 /* Rely on a hack: an open directory is modeled as file descriptor 0,
5921 as in fstatat. FIXME: Add proper support for readlinkat. */
5922 char fullname
[MAX_UTF8_PATH
];
5926 if (_snprintf (fullname
, sizeof fullname
, "%s/%s", dir_pathname
, name
)
5929 errno
= ENAMETOOLONG
;
5935 return readlink (name
, buffer
, buffer_size
);
5938 /* If FILE is a symlink, return its target (stored in a static
5939 buffer); otherwise return FILE.
5941 This function repeatedly resolves symlinks in the last component of
5942 a chain of symlink file names, as in foo -> bar -> baz -> ...,
5943 until it arrives at a file whose last component is not a symlink,
5944 or some error occurs. It returns the target of the last
5945 successfully resolved symlink in the chain. If it succeeds to
5946 resolve even a single symlink, the value returned is an absolute
5947 file name with backslashes (result of GetFullPathName). By
5948 contrast, if the original FILE is returned, it is unaltered.
5950 Note: This function can set errno even if it succeeds.
5952 Implementation note: we only resolve the last portion ("basename")
5953 of the argument FILE and of each following file in the chain,
5954 disregarding any possible symlinks in its leading directories.
5955 This is because Windows system calls and library functions
5956 transparently resolve symlinks in leading directories and return
5957 correct information, as long as the basename is not a symlink. */
5959 chase_symlinks (const char *file
)
5961 static char target
[MAX_UTF8_PATH
];
5962 char link
[MAX_UTF8_PATH
];
5963 wchar_t target_w
[MAX_PATH
], link_w
[MAX_PATH
];
5964 char target_a
[MAX_PATH
], link_a
[MAX_PATH
];
5965 ssize_t res
, link_len
;
5968 if (is_windows_9x () == TRUE
|| !is_symlink (file
))
5969 return (char *)file
;
5971 if (w32_unicode_filenames
)
5973 wchar_t file_w
[MAX_PATH
];
5975 filename_to_utf16 (file
, file_w
);
5976 if (GetFullPathNameW (file_w
, MAX_PATH
, link_w
, NULL
) == 0)
5977 return (char *)file
;
5978 filename_from_utf16 (link_w
, link
);
5982 char file_a
[MAX_PATH
];
5984 filename_to_ansi (file
, file_a
);
5985 if (GetFullPathNameA (file_a
, MAX_PATH
, link_a
, NULL
) == 0)
5986 return (char *)file
;
5987 filename_from_ansi (link_a
, link
);
5989 link_len
= strlen (link
);
5994 /* Remove trailing slashes, as we want to resolve the last
5995 non-trivial part of the link name. */
5996 while (link_len
> 3 && IS_DIRECTORY_SEP (link
[link_len
-1]))
5997 link
[link_len
--] = '\0';
5999 res
= readlink (link
, target
, MAX_UTF8_PATH
);
6003 if (!(IS_DEVICE_SEP (target
[1])
6004 || (IS_DIRECTORY_SEP (target
[0]) && IS_DIRECTORY_SEP (target
[1]))))
6006 /* Target is relative. Append it to the directory part of
6007 the symlink, then copy the result back to target. */
6008 char *p
= link
+ link_len
;
6010 while (p
> link
&& !IS_ANY_SEP (p
[-1]))
6013 strcpy (target
, link
);
6015 /* Resolve any "." and ".." to get a fully-qualified file name
6017 if (w32_unicode_filenames
)
6019 filename_to_utf16 (target
, target_w
);
6020 link_len
= GetFullPathNameW (target_w
, MAX_PATH
, link_w
, NULL
);
6022 filename_from_utf16 (link_w
, link
);
6026 filename_to_ansi (target
, target_a
);
6027 link_len
= GetFullPathNameA (target_a
, MAX_PATH
, link_a
, NULL
);
6029 filename_from_ansi (link_a
, link
);
6031 link_len
= strlen (link
);
6033 } while (res
> 0 && link_len
> 0 && ++loop_count
<= 100);
6035 if (loop_count
> 100)
6038 if (target
[0] == '\0') /* not a single call to readlink succeeded */
6039 return (char *)file
;
6044 /* Posix ACL emulation. */
6047 acl_valid (acl_t acl
)
6049 return is_valid_security_descriptor ((PSECURITY_DESCRIPTOR
)acl
) ? 0 : -1;
6053 acl_to_text (acl_t acl
, ssize_t
*size
)
6056 SECURITY_INFORMATION flags
=
6057 OWNER_SECURITY_INFORMATION
|
6058 GROUP_SECURITY_INFORMATION
|
6059 DACL_SECURITY_INFORMATION
;
6060 char *retval
= NULL
;
6066 if (convert_sd_to_sddl ((PSECURITY_DESCRIPTOR
)acl
, SDDL_REVISION_1
, flags
, &str_acl
, &local_size
))
6069 /* We don't want to mix heaps, so we duplicate the string in our
6070 heap and free the one allocated by the API. */
6071 retval
= xstrdup (str_acl
);
6074 LocalFree (str_acl
);
6076 else if (errno
!= ENOTSUP
)
6083 acl_from_text (const char *acl_str
)
6085 PSECURITY_DESCRIPTOR psd
, retval
= NULL
;
6091 if (convert_sddl_to_sd (acl_str
, SDDL_REVISION_1
, &psd
, &sd_size
))
6094 retval
= xmalloc (sd_size
);
6095 memcpy (retval
, psd
, sd_size
);
6098 else if (errno
!= ENOTSUP
)
6105 acl_free (void *ptr
)
6112 acl_get_file (const char *fname
, acl_type_t type
)
6114 PSECURITY_DESCRIPTOR psd
= NULL
;
6115 const char *filename
;
6117 if (type
== ACL_TYPE_ACCESS
)
6120 SECURITY_INFORMATION si
=
6121 OWNER_SECURITY_INFORMATION
|
6122 GROUP_SECURITY_INFORMATION
|
6123 DACL_SECURITY_INFORMATION
;
6126 filename
= map_w32_filename (fname
, NULL
);
6127 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) != 0)
6128 fname
= chase_symlinks (filename
);
6133 if (!get_file_security (fname
, si
, psd
, 0, &sd_len
)
6134 && errno
!= ENOTSUP
)
6136 err
= GetLastError ();
6137 if (err
== ERROR_INSUFFICIENT_BUFFER
)
6139 psd
= xmalloc (sd_len
);
6140 if (!get_file_security (fname
, si
, psd
, sd_len
, &sd_len
))
6147 else if (err
== ERROR_FILE_NOT_FOUND
6148 || err
== ERROR_PATH_NOT_FOUND
6149 /* ERROR_INVALID_NAME is what we get if
6150 w32-unicode-filenames is nil and the file cannot
6151 be encoded in the current ANSI codepage. */
6152 || err
== ERROR_INVALID_NAME
)
6160 else if (type
!= ACL_TYPE_DEFAULT
)
6167 acl_set_file (const char *fname
, acl_type_t type
, acl_t acl
)
6169 TOKEN_PRIVILEGES old1
, old2
;
6171 int st
= 0, retval
= -1;
6172 SECURITY_INFORMATION flags
= 0;
6173 PSID psidOwner
, psidGroup
;
6178 const char *filename
;
6180 if (acl_valid (acl
) != 0
6181 || (type
!= ACL_TYPE_DEFAULT
&& type
!= ACL_TYPE_ACCESS
))
6187 if (type
== ACL_TYPE_DEFAULT
)
6193 filename
= map_w32_filename (fname
, NULL
);
6194 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) != 0)
6195 fname
= chase_symlinks (filename
);
6199 if (get_security_descriptor_owner ((PSECURITY_DESCRIPTOR
)acl
, &psidOwner
,
6202 flags
|= OWNER_SECURITY_INFORMATION
;
6203 if (get_security_descriptor_group ((PSECURITY_DESCRIPTOR
)acl
, &psidGroup
,
6206 flags
|= GROUP_SECURITY_INFORMATION
;
6207 if (get_security_descriptor_dacl ((PSECURITY_DESCRIPTOR
)acl
, &dacl_present
,
6210 flags
|= DACL_SECURITY_INFORMATION
;
6214 /* According to KB-245153, setting the owner will succeed if either:
6215 (1) the caller is the user who will be the new owner, and has the
6216 SE_TAKE_OWNERSHIP privilege, or
6217 (2) the caller has the SE_RESTORE privilege, in which case she can
6218 set any valid user or group as the owner
6220 We request below both SE_TAKE_OWNERSHIP and SE_RESTORE
6221 privileges, and disregard any failures in obtaining them. If
6222 these privileges cannot be obtained, and do not already exist in
6223 the calling thread's security token, this function could fail
6225 if (enable_privilege (SE_TAKE_OWNERSHIP_NAME
, TRUE
, &old1
))
6227 if (enable_privilege (SE_RESTORE_NAME
, TRUE
, &old2
))
6232 /* SetFileSecurity is deprecated by MS, and sometimes fails when
6233 DACL inheritance is involved, but it seems to preserve ownership
6234 better than SetNamedSecurityInfo, which is important e.g., in
6236 if (!set_file_security (fname
, flags
, (PSECURITY_DESCRIPTOR
)acl
))
6238 err
= GetLastError ();
6240 if (errno
!= ENOTSUP
)
6241 err
= set_named_security_info (fname
, SE_FILE_OBJECT
, flags
,
6242 psidOwner
, psidGroup
, pacl
, NULL
);
6245 err
= ERROR_SUCCESS
;
6246 if (err
!= ERROR_SUCCESS
)
6248 if (errno
== ENOTSUP
)
6250 else if (err
== ERROR_INVALID_OWNER
6251 || err
== ERROR_NOT_ALL_ASSIGNED
6252 || err
== ERROR_ACCESS_DENIED
)
6254 /* Maybe the requested ACL and the one the file already has
6255 are identical, in which case we can silently ignore the
6256 failure. (And no, Windows doesn't.) */
6257 acl_t current_acl
= acl_get_file (fname
, ACL_TYPE_ACCESS
);
6262 char *acl_from
= acl_to_text (current_acl
, NULL
);
6263 char *acl_to
= acl_to_text (acl
, NULL
);
6265 if (acl_from
&& acl_to
&& xstrcasecmp (acl_from
, acl_to
) == 0)
6271 acl_free (acl_from
);
6274 acl_free (current_acl
);
6277 else if (err
== ERROR_FILE_NOT_FOUND
6278 || err
== ERROR_PATH_NOT_FOUND
6279 /* ERROR_INVALID_NAME is what we get if
6280 w32-unicode-filenames is nil and the file cannot be
6281 encoded in the current ANSI codepage. */
6282 || err
== ERROR_INVALID_NAME
)
6296 restore_privilege (&old2
);
6297 restore_privilege (&old1
);
6305 /* MS-Windows version of careadlinkat (cf. ../lib/careadlinkat.c). We
6306 have a fixed max size for file names, so we don't need the kind of
6307 alloc/malloc/realloc dance the gnulib version does. We also don't
6308 support FD-relative symlinks. */
6310 careadlinkat (int fd
, char const *filename
,
6311 char *buffer
, size_t buffer_size
,
6312 struct allocator
const *alloc
,
6313 ssize_t (*preadlinkat
) (int, char const *, char *, size_t))
6315 char linkname
[MAX_UTF8_PATH
];
6318 link_size
= preadlinkat (fd
, filename
, linkname
, sizeof(linkname
));
6322 char *retval
= buffer
;
6324 linkname
[link_size
++] = '\0';
6325 if (link_size
> buffer_size
)
6326 retval
= (char *)(alloc
? alloc
->allocate
: xmalloc
) (link_size
);
6328 memcpy (retval
, linkname
, link_size
);
6336 w32_copy_file (const char *from
, const char *to
,
6337 int keep_time
, int preserve_ownership
, int copy_acls
)
6341 wchar_t from_w
[MAX_PATH
], to_w
[MAX_PATH
];
6342 char from_a
[MAX_PATH
], to_a
[MAX_PATH
];
6344 /* We ignore preserve_ownership for now. */
6345 preserve_ownership
= preserve_ownership
;
6349 acl
= acl_get_file (from
, ACL_TYPE_ACCESS
);
6350 if (acl
== NULL
&& acl_errno_valid (errno
))
6353 if (w32_unicode_filenames
)
6355 filename_to_utf16 (from
, from_w
);
6356 filename_to_utf16 (to
, to_w
);
6357 copy_result
= CopyFileW (from_w
, to_w
, FALSE
);
6361 filename_to_ansi (from
, from_a
);
6362 filename_to_ansi (to
, to_a
);
6363 copy_result
= CopyFileA (from_a
, to_a
, FALSE
);
6367 /* CopyFile doesn't set errno when it fails. By far the most
6368 "popular" reason is that the target is read-only. */
6369 DWORD err
= GetLastError ();
6373 case ERROR_FILE_NOT_FOUND
:
6376 case ERROR_ACCESS_DENIED
:
6379 case ERROR_ENCRYPTION_FAILED
:
6391 /* CopyFile retains the timestamp by default. However, see
6392 "Community Additions" for CopyFile: it sounds like that is not
6393 entirely true. Testing on Windows XP confirms that modified time
6394 is copied, but creation and last-access times are not.
6396 else if (!keep_time
)
6398 struct timespec now
;
6401 if (w32_unicode_filenames
)
6403 /* Ensure file is writable while its times are set. */
6404 attributes
= GetFileAttributesW (to_w
);
6405 SetFileAttributesW (to_w
, attributes
& ~FILE_ATTRIBUTE_READONLY
);
6406 now
= current_timespec ();
6407 if (set_file_times (-1, to
, now
, now
))
6409 /* Restore original attributes. */
6410 SetFileAttributesW (to_w
, attributes
);
6415 /* Restore original attributes. */
6416 SetFileAttributesW (to_w
, attributes
);
6420 attributes
= GetFileAttributesA (to_a
);
6421 SetFileAttributesA (to_a
, attributes
& ~FILE_ATTRIBUTE_READONLY
);
6422 now
= current_timespec ();
6423 if (set_file_times (-1, to
, now
, now
))
6425 SetFileAttributesA (to_a
, attributes
);
6430 SetFileAttributesA (to_a
, attributes
);
6436 acl_set_file (to
, ACL_TYPE_ACCESS
, acl
) != 0;
6438 if (fail
&& acl_errno_valid (errno
))
6446 /* Support for browsing other processes and their attributes. See
6447 process.c for the Lisp bindings. */
6449 /* Helper wrapper functions. */
6451 static HANDLE WINAPI
6452 create_toolhelp32_snapshot (DWORD Flags
, DWORD Ignored
)
6454 static CreateToolhelp32Snapshot_Proc s_pfn_Create_Toolhelp32_Snapshot
= NULL
;
6456 if (g_b_init_create_toolhelp32_snapshot
== 0)
6458 g_b_init_create_toolhelp32_snapshot
= 1;
6459 s_pfn_Create_Toolhelp32_Snapshot
= (CreateToolhelp32Snapshot_Proc
)
6460 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6461 "CreateToolhelp32Snapshot");
6463 if (s_pfn_Create_Toolhelp32_Snapshot
== NULL
)
6465 return INVALID_HANDLE_VALUE
;
6467 return (s_pfn_Create_Toolhelp32_Snapshot (Flags
, Ignored
));
6471 process32_first (HANDLE hSnapshot
, LPPROCESSENTRY32 lppe
)
6473 static Process32First_Proc s_pfn_Process32_First
= NULL
;
6475 if (g_b_init_process32_first
== 0)
6477 g_b_init_process32_first
= 1;
6478 s_pfn_Process32_First
= (Process32First_Proc
)
6479 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6482 if (s_pfn_Process32_First
== NULL
)
6486 return (s_pfn_Process32_First (hSnapshot
, lppe
));
6490 process32_next (HANDLE hSnapshot
, LPPROCESSENTRY32 lppe
)
6492 static Process32Next_Proc s_pfn_Process32_Next
= NULL
;
6494 if (g_b_init_process32_next
== 0)
6496 g_b_init_process32_next
= 1;
6497 s_pfn_Process32_Next
= (Process32Next_Proc
)
6498 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6501 if (s_pfn_Process32_Next
== NULL
)
6505 return (s_pfn_Process32_Next (hSnapshot
, lppe
));
6509 open_thread_token (HANDLE ThreadHandle
,
6510 DWORD DesiredAccess
,
6512 PHANDLE TokenHandle
)
6514 static OpenThreadToken_Proc s_pfn_Open_Thread_Token
= NULL
;
6515 HMODULE hm_advapi32
= NULL
;
6516 if (is_windows_9x () == TRUE
)
6518 SetLastError (ERROR_NOT_SUPPORTED
);
6521 if (g_b_init_open_thread_token
== 0)
6523 g_b_init_open_thread_token
= 1;
6524 hm_advapi32
= LoadLibrary ("Advapi32.dll");
6525 s_pfn_Open_Thread_Token
=
6526 (OpenThreadToken_Proc
) GetProcAddress (hm_advapi32
, "OpenThreadToken");
6528 if (s_pfn_Open_Thread_Token
== NULL
)
6530 SetLastError (ERROR_NOT_SUPPORTED
);
6534 s_pfn_Open_Thread_Token (
6543 impersonate_self (SECURITY_IMPERSONATION_LEVEL ImpersonationLevel
)
6545 static ImpersonateSelf_Proc s_pfn_Impersonate_Self
= NULL
;
6546 HMODULE hm_advapi32
= NULL
;
6547 if (is_windows_9x () == TRUE
)
6551 if (g_b_init_impersonate_self
== 0)
6553 g_b_init_impersonate_self
= 1;
6554 hm_advapi32
= LoadLibrary ("Advapi32.dll");
6555 s_pfn_Impersonate_Self
=
6556 (ImpersonateSelf_Proc
) GetProcAddress (hm_advapi32
, "ImpersonateSelf");
6558 if (s_pfn_Impersonate_Self
== NULL
)
6562 return s_pfn_Impersonate_Self (ImpersonationLevel
);
6566 revert_to_self (void)
6568 static RevertToSelf_Proc s_pfn_Revert_To_Self
= NULL
;
6569 HMODULE hm_advapi32
= NULL
;
6570 if (is_windows_9x () == TRUE
)
6574 if (g_b_init_revert_to_self
== 0)
6576 g_b_init_revert_to_self
= 1;
6577 hm_advapi32
= LoadLibrary ("Advapi32.dll");
6578 s_pfn_Revert_To_Self
=
6579 (RevertToSelf_Proc
) GetProcAddress (hm_advapi32
, "RevertToSelf");
6581 if (s_pfn_Revert_To_Self
== NULL
)
6585 return s_pfn_Revert_To_Self ();
6589 get_process_memory_info (HANDLE h_proc
,
6590 PPROCESS_MEMORY_COUNTERS mem_counters
,
6593 static GetProcessMemoryInfo_Proc s_pfn_Get_Process_Memory_Info
= NULL
;
6594 HMODULE hm_psapi
= NULL
;
6595 if (is_windows_9x () == TRUE
)
6599 if (g_b_init_get_process_memory_info
== 0)
6601 g_b_init_get_process_memory_info
= 1;
6602 hm_psapi
= LoadLibrary ("Psapi.dll");
6604 s_pfn_Get_Process_Memory_Info
= (GetProcessMemoryInfo_Proc
)
6605 GetProcAddress (hm_psapi
, "GetProcessMemoryInfo");
6607 if (s_pfn_Get_Process_Memory_Info
== NULL
)
6611 return s_pfn_Get_Process_Memory_Info (h_proc
, mem_counters
, bufsize
);
6615 get_process_working_set_size (HANDLE h_proc
,
6619 static GetProcessWorkingSetSize_Proc
6620 s_pfn_Get_Process_Working_Set_Size
= NULL
;
6622 if (is_windows_9x () == TRUE
)
6626 if (g_b_init_get_process_working_set_size
== 0)
6628 g_b_init_get_process_working_set_size
= 1;
6629 s_pfn_Get_Process_Working_Set_Size
= (GetProcessWorkingSetSize_Proc
)
6630 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6631 "GetProcessWorkingSetSize");
6633 if (s_pfn_Get_Process_Working_Set_Size
== NULL
)
6637 return s_pfn_Get_Process_Working_Set_Size (h_proc
, minrss
, maxrss
);
6641 global_memory_status (MEMORYSTATUS
*buf
)
6643 static GlobalMemoryStatus_Proc s_pfn_Global_Memory_Status
= NULL
;
6645 if (is_windows_9x () == TRUE
)
6649 if (g_b_init_global_memory_status
== 0)
6651 g_b_init_global_memory_status
= 1;
6652 s_pfn_Global_Memory_Status
= (GlobalMemoryStatus_Proc
)
6653 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6654 "GlobalMemoryStatus");
6656 if (s_pfn_Global_Memory_Status
== NULL
)
6660 return s_pfn_Global_Memory_Status (buf
);
6664 global_memory_status_ex (MEMORY_STATUS_EX
*buf
)
6666 static GlobalMemoryStatusEx_Proc s_pfn_Global_Memory_Status_Ex
= NULL
;
6668 if (is_windows_9x () == TRUE
)
6672 if (g_b_init_global_memory_status_ex
== 0)
6674 g_b_init_global_memory_status_ex
= 1;
6675 s_pfn_Global_Memory_Status_Ex
= (GlobalMemoryStatusEx_Proc
)
6676 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6677 "GlobalMemoryStatusEx");
6679 if (s_pfn_Global_Memory_Status_Ex
== NULL
)
6683 return s_pfn_Global_Memory_Status_Ex (buf
);
6687 list_system_processes (void)
6689 Lisp_Object proclist
= Qnil
;
6692 h_snapshot
= create_toolhelp32_snapshot (TH32CS_SNAPPROCESS
, 0);
6694 if (h_snapshot
!= INVALID_HANDLE_VALUE
)
6696 PROCESSENTRY32 proc_entry
;
6700 proc_entry
.dwSize
= sizeof (PROCESSENTRY32
);
6701 for (res
= process32_first (h_snapshot
, &proc_entry
); res
;
6702 res
= process32_next (h_snapshot
, &proc_entry
))
6704 proc_id
= proc_entry
.th32ProcessID
;
6705 proclist
= Fcons (make_fixnum_or_float (proc_id
), proclist
);
6708 CloseHandle (h_snapshot
);
6709 proclist
= Fnreverse (proclist
);
6716 enable_privilege (LPCTSTR priv_name
, BOOL enable_p
, TOKEN_PRIVILEGES
*old_priv
)
6718 TOKEN_PRIVILEGES priv
;
6719 DWORD priv_size
= sizeof (priv
);
6720 DWORD opriv_size
= sizeof (*old_priv
);
6721 HANDLE h_token
= NULL
;
6722 HANDLE h_thread
= GetCurrentThread ();
6726 res
= open_thread_token (h_thread
,
6727 TOKEN_QUERY
| TOKEN_ADJUST_PRIVILEGES
,
6729 if (!res
&& GetLastError () == ERROR_NO_TOKEN
)
6731 if (impersonate_self (SecurityImpersonation
))
6732 res
= open_thread_token (h_thread
,
6733 TOKEN_QUERY
| TOKEN_ADJUST_PRIVILEGES
,
6738 priv
.PrivilegeCount
= 1;
6739 priv
.Privileges
[0].Attributes
= enable_p
? SE_PRIVILEGE_ENABLED
: 0;
6740 LookupPrivilegeValue (NULL
, priv_name
, &priv
.Privileges
[0].Luid
);
6741 if (AdjustTokenPrivileges (h_token
, FALSE
, &priv
, priv_size
,
6742 old_priv
, &opriv_size
)
6743 && GetLastError () != ERROR_NOT_ALL_ASSIGNED
)
6747 CloseHandle (h_token
);
6753 restore_privilege (TOKEN_PRIVILEGES
*priv
)
6755 DWORD priv_size
= sizeof (*priv
);
6756 HANDLE h_token
= NULL
;
6759 if (open_thread_token (GetCurrentThread (),
6760 TOKEN_QUERY
| TOKEN_ADJUST_PRIVILEGES
,
6763 if (AdjustTokenPrivileges (h_token
, FALSE
, priv
, priv_size
, NULL
, NULL
)
6764 && GetLastError () != ERROR_NOT_ALL_ASSIGNED
)
6768 CloseHandle (h_token
);
6774 ltime (ULONGLONG time_100ns
)
6776 ULONGLONG time_sec
= time_100ns
/ 10000000;
6777 int subsec
= time_100ns
% 10000000;
6778 return list4i (time_sec
>> 16, time_sec
& 0xffff,
6779 subsec
/ 10, subsec
% 10 * 100000);
6782 #define U64_TO_LISP_TIME(time) ltime (time)
6785 process_times (HANDLE h_proc
, Lisp_Object
*ctime
, Lisp_Object
*etime
,
6786 Lisp_Object
*stime
, Lisp_Object
*utime
, Lisp_Object
*ttime
,
6789 FILETIME ft_creation
, ft_exit
, ft_kernel
, ft_user
, ft_current
;
6790 ULONGLONG tem1
, tem2
, tem3
, tem
;
6793 || !get_process_times_fn
6794 || !(*get_process_times_fn
) (h_proc
, &ft_creation
, &ft_exit
,
6795 &ft_kernel
, &ft_user
))
6798 GetSystemTimeAsFileTime (&ft_current
);
6800 FILETIME_TO_U64 (tem1
, ft_kernel
);
6801 *stime
= U64_TO_LISP_TIME (tem1
);
6803 FILETIME_TO_U64 (tem2
, ft_user
);
6804 *utime
= U64_TO_LISP_TIME (tem2
);
6807 *ttime
= U64_TO_LISP_TIME (tem3
);
6809 FILETIME_TO_U64 (tem
, ft_creation
);
6810 /* Process no 4 (System) returns zero creation time. */
6813 *ctime
= U64_TO_LISP_TIME (tem
);
6817 FILETIME_TO_U64 (tem3
, ft_current
);
6818 tem
= (tem3
- utc_base
) - tem
;
6820 *etime
= U64_TO_LISP_TIME (tem
);
6824 *pcpu
= 100.0 * (tem1
+ tem2
) / tem
;
6835 system_process_attributes (Lisp_Object pid
)
6837 Lisp_Object attrs
= Qnil
;
6838 Lisp_Object cmd_str
, decoded_cmd
, tem
;
6839 HANDLE h_snapshot
, h_proc
;
6842 char uname
[UNLEN
+1], gname
[GNLEN
+1], domain
[1025];
6843 DWORD ulength
= sizeof (uname
), dlength
= sizeof (domain
), needed
;
6844 DWORD glength
= sizeof (gname
);
6845 HANDLE token
= NULL
;
6846 SID_NAME_USE user_type
;
6847 unsigned char *buf
= NULL
;
6849 TOKEN_USER user_token
;
6850 TOKEN_PRIMARY_GROUP group_token
;
6853 PROCESS_MEMORY_COUNTERS mem
;
6854 PROCESS_MEMORY_COUNTERS_EX mem_ex
;
6855 SIZE_T minrss
, maxrss
;
6857 MEMORY_STATUS_EX memstex
;
6858 double totphys
= 0.0;
6859 Lisp_Object ctime
, stime
, utime
, etime
, ttime
;
6861 BOOL result
= FALSE
;
6863 CHECK_NUMBER_OR_FLOAT (pid
);
6864 proc_id
= FLOATP (pid
) ? XFLOAT_DATA (pid
) : XINT (pid
);
6866 h_snapshot
= create_toolhelp32_snapshot (TH32CS_SNAPPROCESS
, 0);
6868 if (h_snapshot
!= INVALID_HANDLE_VALUE
)
6873 pe
.dwSize
= sizeof (PROCESSENTRY32
);
6874 for (res
= process32_first (h_snapshot
, &pe
); res
;
6875 res
= process32_next (h_snapshot
, &pe
))
6877 if (proc_id
== pe
.th32ProcessID
)
6880 decoded_cmd
= build_string ("Idle");
6883 /* Decode the command name from locale-specific
6885 cmd_str
= build_unibyte_string (pe
.szExeFile
);
6888 code_convert_string_norecord (cmd_str
,
6889 Vlocale_coding_system
, 0);
6891 attrs
= Fcons (Fcons (Qcomm
, decoded_cmd
), attrs
);
6892 attrs
= Fcons (Fcons (Qppid
,
6893 make_fixnum_or_float (pe
.th32ParentProcessID
)),
6895 attrs
= Fcons (Fcons (Qpri
, make_number (pe
.pcPriClassBase
)),
6897 attrs
= Fcons (Fcons (Qthcount
,
6898 make_fixnum_or_float (pe
.cntThreads
)),
6905 CloseHandle (h_snapshot
);
6911 h_proc
= OpenProcess (PROCESS_QUERY_INFORMATION
| PROCESS_VM_READ
,
6913 /* If we were denied a handle to the process, try again after
6914 enabling the SeDebugPrivilege in our process. */
6917 TOKEN_PRIVILEGES priv_current
;
6919 if (enable_privilege (SE_DEBUG_NAME
, TRUE
, &priv_current
))
6921 h_proc
= OpenProcess (PROCESS_QUERY_INFORMATION
| PROCESS_VM_READ
,
6923 restore_privilege (&priv_current
);
6929 result
= open_process_token (h_proc
, TOKEN_QUERY
, &token
);
6932 result
= get_token_information (token
, TokenUser
, NULL
, 0, &blen
);
6933 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
6935 buf
= xmalloc (blen
);
6936 result
= get_token_information (token
, TokenUser
,
6937 (LPVOID
)buf
, blen
, &needed
);
6940 memcpy (&user_token
, buf
, sizeof (user_token
));
6941 if (!w32_cached_id (user_token
.User
.Sid
, &euid
, uname
))
6943 euid
= get_rid (user_token
.User
.Sid
);
6944 result
= lookup_account_sid (NULL
, user_token
.User
.Sid
,
6949 w32_add_to_cache (user_token
.User
.Sid
, euid
, uname
);
6952 strcpy (uname
, "unknown");
6956 ulength
= strlen (uname
);
6962 /* Determine a reasonable euid and gid values. */
6963 if (xstrcasecmp ("administrator", uname
) == 0)
6965 euid
= 500; /* well-known Administrator uid */
6966 egid
= 513; /* well-known None gid */
6970 /* Get group id and name. */
6971 result
= get_token_information (token
, TokenPrimaryGroup
,
6972 (LPVOID
)buf
, blen
, &needed
);
6973 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
6975 buf
= xrealloc (buf
, blen
= needed
);
6976 result
= get_token_information (token
, TokenPrimaryGroup
,
6977 (LPVOID
)buf
, blen
, &needed
);
6981 memcpy (&group_token
, buf
, sizeof (group_token
));
6982 if (!w32_cached_id (group_token
.PrimaryGroup
, &egid
, gname
))
6984 egid
= get_rid (group_token
.PrimaryGroup
);
6985 dlength
= sizeof (domain
);
6987 lookup_account_sid (NULL
, group_token
.PrimaryGroup
,
6988 gname
, &glength
, NULL
, &dlength
,
6991 w32_add_to_cache (group_token
.PrimaryGroup
,
6995 strcpy (gname
, "None");
6999 glength
= strlen (gname
);
7007 if (!is_windows_9x ())
7009 /* We couldn't open the process token, presumably because of
7010 insufficient access rights. Assume this process is run
7012 strcpy (uname
, "SYSTEM");
7013 strcpy (gname
, "None");
7014 euid
= 18; /* SYSTEM */
7015 egid
= 513; /* None */
7016 glength
= strlen (gname
);
7017 ulength
= strlen (uname
);
7019 /* If we are running under Windows 9X, where security calls are
7020 not supported, we assume all processes are run by the current
7022 else if (GetUserName (uname
, &ulength
))
7024 if (xstrcasecmp ("administrator", uname
) == 0)
7029 strcpy (gname
, "None");
7030 glength
= strlen (gname
);
7031 ulength
= strlen (uname
);
7037 strcpy (uname
, "administrator");
7038 ulength
= strlen (uname
);
7039 strcpy (gname
, "None");
7040 glength
= strlen (gname
);
7043 CloseHandle (token
);
7046 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (euid
)), attrs
);
7047 tem
= make_unibyte_string (uname
, ulength
);
7048 attrs
= Fcons (Fcons (Quser
,
7049 code_convert_string_norecord (tem
, Vlocale_coding_system
, 0)),
7051 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (egid
)), attrs
);
7052 tem
= make_unibyte_string (gname
, glength
);
7053 attrs
= Fcons (Fcons (Qgroup
,
7054 code_convert_string_norecord (tem
, Vlocale_coding_system
, 0)),
7057 if (global_memory_status_ex (&memstex
))
7058 #if __GNUC__ || (defined (_MSC_VER) && _MSC_VER >= 1300)
7059 totphys
= memstex
.ullTotalPhys
/ 1024.0;
7061 /* Visual Studio 6 cannot convert an unsigned __int64 type to
7062 double, so we need to do this for it... */
7064 DWORD tot_hi
= memstex
.ullTotalPhys
>> 32;
7065 DWORD tot_md
= (memstex
.ullTotalPhys
& 0x00000000ffffffff) >> 10;
7066 DWORD tot_lo
= memstex
.ullTotalPhys
% 1024;
7068 totphys
= tot_hi
* 4194304.0 + tot_md
+ tot_lo
/ 1024.0;
7070 #endif /* __GNUC__ || _MSC_VER >= 1300 */
7071 else if (global_memory_status (&memst
))
7072 totphys
= memst
.dwTotalPhys
/ 1024.0;
7075 && get_process_memory_info (h_proc
, (PROCESS_MEMORY_COUNTERS
*)&mem_ex
,
7078 SIZE_T rss
= mem_ex
.WorkingSetSize
/ 1024;
7080 attrs
= Fcons (Fcons (Qmajflt
,
7081 make_fixnum_or_float (mem_ex
.PageFaultCount
)),
7083 attrs
= Fcons (Fcons (Qvsize
,
7084 make_fixnum_or_float (mem_ex
.PrivateUsage
/ 1024)),
7086 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (rss
)), attrs
);
7088 attrs
= Fcons (Fcons (Qpmem
, make_float (100. * rss
/ totphys
)), attrs
);
7091 && get_process_memory_info (h_proc
, &mem
, sizeof (mem
)))
7093 SIZE_T rss
= mem_ex
.WorkingSetSize
/ 1024;
7095 attrs
= Fcons (Fcons (Qmajflt
,
7096 make_fixnum_or_float (mem
.PageFaultCount
)),
7098 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (rss
)), attrs
);
7100 attrs
= Fcons (Fcons (Qpmem
, make_float (100. * rss
/ totphys
)), attrs
);
7103 && get_process_working_set_size (h_proc
, &minrss
, &maxrss
))
7105 DWORD rss
= maxrss
/ 1024;
7107 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (maxrss
/ 1024)), attrs
);
7109 attrs
= Fcons (Fcons (Qpmem
, make_float (100. * rss
/ totphys
)), attrs
);
7112 if (process_times (h_proc
, &ctime
, &etime
, &stime
, &utime
, &ttime
, &pcpu
))
7114 attrs
= Fcons (Fcons (Qutime
, utime
), attrs
);
7115 attrs
= Fcons (Fcons (Qstime
, stime
), attrs
);
7116 attrs
= Fcons (Fcons (Qtime
, ttime
), attrs
);
7117 attrs
= Fcons (Fcons (Qstart
, ctime
), attrs
);
7118 attrs
= Fcons (Fcons (Qetime
, etime
), attrs
);
7119 attrs
= Fcons (Fcons (Qpcpu
, make_float (pcpu
)), attrs
);
7122 /* FIXME: Retrieve command line by walking the PEB of the process. */
7125 CloseHandle (h_proc
);
7130 w32_memory_info (unsigned long long *totalram
, unsigned long long *freeram
,
7131 unsigned long long *totalswap
, unsigned long long *freeswap
)
7134 MEMORY_STATUS_EX memstex
;
7136 /* Use GlobalMemoryStatusEx if available, as it can report more than
7138 if (global_memory_status_ex (&memstex
))
7140 *totalram
= memstex
.ullTotalPhys
;
7141 *freeram
= memstex
.ullAvailPhys
;
7142 *totalswap
= memstex
.ullTotalPageFile
;
7143 *freeswap
= memstex
.ullAvailPageFile
;
7146 else if (global_memory_status (&memst
))
7148 *totalram
= memst
.dwTotalPhys
;
7149 *freeram
= memst
.dwAvailPhys
;
7150 *totalswap
= memst
.dwTotalPageFile
;
7151 *freeswap
= memst
.dwAvailPageFile
;
7159 /* Wrappers for winsock functions to map between our file descriptors
7160 and winsock's handles; also set h_errno for convenience.
7162 To allow Emacs to run on systems which don't have winsock support
7163 installed, we dynamically link to winsock on startup if present, and
7164 otherwise provide the minimum necessary functionality
7165 (eg. gethostname). */
7167 /* function pointers for relevant socket functions */
7168 int (PASCAL
*pfn_WSAStartup
) (WORD wVersionRequired
, LPWSADATA lpWSAData
);
7169 void (PASCAL
*pfn_WSASetLastError
) (int iError
);
7170 int (PASCAL
*pfn_WSAGetLastError
) (void);
7171 int (PASCAL
*pfn_WSAEventSelect
) (SOCKET s
, HANDLE hEventObject
, long lNetworkEvents
);
7172 int (PASCAL
*pfn_WSAEnumNetworkEvents
) (SOCKET s
, HANDLE hEventObject
,
7173 WSANETWORKEVENTS
*NetworkEvents
);
7175 HANDLE (PASCAL
*pfn_WSACreateEvent
) (void);
7176 int (PASCAL
*pfn_WSACloseEvent
) (HANDLE hEvent
);
7177 int (PASCAL
*pfn_socket
) (int af
, int type
, int protocol
);
7178 int (PASCAL
*pfn_bind
) (SOCKET s
, const struct sockaddr
*addr
, int namelen
);
7179 int (PASCAL
*pfn_connect
) (SOCKET s
, const struct sockaddr
*addr
, int namelen
);
7180 int (PASCAL
*pfn_ioctlsocket
) (SOCKET s
, long cmd
, u_long
*argp
);
7181 int (PASCAL
*pfn_recv
) (SOCKET s
, char * buf
, int len
, int flags
);
7182 int (PASCAL
*pfn_send
) (SOCKET s
, const char * buf
, int len
, int flags
);
7183 int (PASCAL
*pfn_closesocket
) (SOCKET s
);
7184 int (PASCAL
*pfn_shutdown
) (SOCKET s
, int how
);
7185 int (PASCAL
*pfn_WSACleanup
) (void);
7187 u_short (PASCAL
*pfn_htons
) (u_short hostshort
);
7188 u_short (PASCAL
*pfn_ntohs
) (u_short netshort
);
7189 unsigned long (PASCAL
*pfn_inet_addr
) (const char * cp
);
7190 int (PASCAL
*pfn_gethostname
) (char * name
, int namelen
);
7191 struct hostent
* (PASCAL
*pfn_gethostbyname
) (const char * name
);
7192 struct servent
* (PASCAL
*pfn_getservbyname
) (const char * name
, const char * proto
);
7193 int (PASCAL
*pfn_getpeername
) (SOCKET s
, struct sockaddr
*addr
, int * namelen
);
7194 int (PASCAL
*pfn_setsockopt
) (SOCKET s
, int level
, int optname
,
7195 const char * optval
, int optlen
);
7196 int (PASCAL
*pfn_listen
) (SOCKET s
, int backlog
);
7197 int (PASCAL
*pfn_getsockname
) (SOCKET s
, struct sockaddr
* name
,
7199 SOCKET (PASCAL
*pfn_accept
) (SOCKET s
, struct sockaddr
* addr
, int * addrlen
);
7200 int (PASCAL
*pfn_recvfrom
) (SOCKET s
, char * buf
, int len
, int flags
,
7201 struct sockaddr
* from
, int * fromlen
);
7202 int (PASCAL
*pfn_sendto
) (SOCKET s
, const char * buf
, int len
, int flags
,
7203 const struct sockaddr
* to
, int tolen
);
7205 int (PASCAL
*pfn_getaddrinfo
) (const char *, const char *,
7206 const struct addrinfo
*, struct addrinfo
**);
7207 void (PASCAL
*pfn_freeaddrinfo
) (struct addrinfo
*);
7209 /* SetHandleInformation is only needed to make sockets non-inheritable. */
7210 BOOL (WINAPI
*pfn_SetHandleInformation
) (HANDLE object
, DWORD mask
, DWORD flags
);
7211 #ifndef HANDLE_FLAG_INHERIT
7212 #define HANDLE_FLAG_INHERIT 1
7216 static int winsock_inuse
;
7221 if (winsock_lib
!= NULL
&& winsock_inuse
== 0)
7223 release_listen_threads ();
7224 /* Not sure what would cause WSAENETDOWN, or even if it can happen
7225 after WSAStartup returns successfully, but it seems reasonable
7226 to allow unloading winsock anyway in that case. */
7227 if (pfn_WSACleanup () == 0 ||
7228 pfn_WSAGetLastError () == WSAENETDOWN
)
7230 if (FreeLibrary (winsock_lib
))
7239 init_winsock (int load_now
)
7241 WSADATA winsockData
;
7243 if (winsock_lib
!= NULL
)
7246 pfn_SetHandleInformation
7247 = (void *) GetProcAddress (GetModuleHandle ("kernel32.dll"),
7248 "SetHandleInformation");
7250 winsock_lib
= LoadLibrary ("Ws2_32.dll");
7252 if (winsock_lib
!= NULL
)
7254 /* dynamically link to socket functions */
7256 #define LOAD_PROC(fn) \
7257 if ((pfn_##fn = (void *) GetProcAddress (winsock_lib, #fn)) == NULL) \
7260 LOAD_PROC (WSAStartup
);
7261 LOAD_PROC (WSASetLastError
);
7262 LOAD_PROC (WSAGetLastError
);
7263 LOAD_PROC (WSAEventSelect
);
7264 LOAD_PROC (WSAEnumNetworkEvents
);
7265 LOAD_PROC (WSACreateEvent
);
7266 LOAD_PROC (WSACloseEvent
);
7269 LOAD_PROC (connect
);
7270 LOAD_PROC (ioctlsocket
);
7273 LOAD_PROC (closesocket
);
7274 LOAD_PROC (shutdown
);
7277 LOAD_PROC (inet_addr
);
7278 LOAD_PROC (gethostname
);
7279 LOAD_PROC (gethostbyname
);
7280 LOAD_PROC (getservbyname
);
7281 LOAD_PROC (getpeername
);
7282 LOAD_PROC (WSACleanup
);
7283 LOAD_PROC (setsockopt
);
7285 LOAD_PROC (getsockname
);
7287 LOAD_PROC (recvfrom
);
7291 /* Try loading functions not available before XP. */
7292 pfn_getaddrinfo
= (void *) GetProcAddress (winsock_lib
, "getaddrinfo");
7293 pfn_freeaddrinfo
= (void *) GetProcAddress (winsock_lib
, "freeaddrinfo");
7294 /* Paranoia: these two functions should go together, so if one
7295 is absent, we cannot use the other. */
7296 if (pfn_getaddrinfo
== NULL
)
7297 pfn_freeaddrinfo
= NULL
;
7298 else if (pfn_freeaddrinfo
== NULL
)
7299 pfn_getaddrinfo
= NULL
;
7301 /* specify version 1.1 of winsock */
7302 if (pfn_WSAStartup (0x101, &winsockData
) == 0)
7304 if (winsockData
.wVersion
!= 0x101)
7309 /* Report that winsock exists and is usable, but leave
7310 socket functions disabled. I am assuming that calling
7311 WSAStartup does not require any network interaction,
7312 and in particular does not cause or require a dial-up
7313 connection to be established. */
7316 FreeLibrary (winsock_lib
);
7324 FreeLibrary (winsock_lib
);
7334 /* Function to map winsock error codes to errno codes for those errno
7335 code defined in errno.h (errno values not defined by errno.h are
7336 already in nt/inc/sys/socket.h). */
7343 if (winsock_lib
== NULL
)
7346 wsa_err
= pfn_WSAGetLastError ();
7350 case WSAEACCES
: errno
= EACCES
; break;
7351 case WSAEBADF
: errno
= EBADF
; break;
7352 case WSAEFAULT
: errno
= EFAULT
; break;
7353 case WSAEINTR
: errno
= EINTR
; break;
7354 case WSAEINVAL
: errno
= EINVAL
; break;
7355 case WSAEMFILE
: errno
= EMFILE
; break;
7356 case WSAENAMETOOLONG
: errno
= ENAMETOOLONG
; break;
7357 case WSAENOTEMPTY
: errno
= ENOTEMPTY
; break;
7358 case WSAEWOULDBLOCK
: errno
= EWOULDBLOCK
; break;
7359 case WSAENOTCONN
: errno
= ENOTCONN
; break;
7360 default: errno
= wsa_err
; break;
7368 if (winsock_lib
!= NULL
)
7369 pfn_WSASetLastError (0);
7372 /* Extend strerror to handle the winsock-specific error codes. */
7376 } _wsa_errlist
[] = {
7377 {WSAEINTR
, "Interrupted function call"},
7378 {WSAEBADF
, "Bad file descriptor"},
7379 {WSAEACCES
, "Permission denied"},
7380 {WSAEFAULT
, "Bad address"},
7381 {WSAEINVAL
, "Invalid argument"},
7382 {WSAEMFILE
, "Too many open files"},
7384 {WSAEWOULDBLOCK
, "Resource temporarily unavailable"},
7385 {WSAEINPROGRESS
, "Operation now in progress"},
7386 {WSAEALREADY
, "Operation already in progress"},
7387 {WSAENOTSOCK
, "Socket operation on non-socket"},
7388 {WSAEDESTADDRREQ
, "Destination address required"},
7389 {WSAEMSGSIZE
, "Message too long"},
7390 {WSAEPROTOTYPE
, "Protocol wrong type for socket"},
7391 {WSAENOPROTOOPT
, "Bad protocol option"},
7392 {WSAEPROTONOSUPPORT
, "Protocol not supported"},
7393 {WSAESOCKTNOSUPPORT
, "Socket type not supported"},
7394 {WSAEOPNOTSUPP
, "Operation not supported"},
7395 {WSAEPFNOSUPPORT
, "Protocol family not supported"},
7396 {WSAEAFNOSUPPORT
, "Address family not supported by protocol family"},
7397 {WSAEADDRINUSE
, "Address already in use"},
7398 {WSAEADDRNOTAVAIL
, "Cannot assign requested address"},
7399 {WSAENETDOWN
, "Network is down"},
7400 {WSAENETUNREACH
, "Network is unreachable"},
7401 {WSAENETRESET
, "Network dropped connection on reset"},
7402 {WSAECONNABORTED
, "Software caused connection abort"},
7403 {WSAECONNRESET
, "Connection reset by peer"},
7404 {WSAENOBUFS
, "No buffer space available"},
7405 {WSAEISCONN
, "Socket is already connected"},
7406 {WSAENOTCONN
, "Socket is not connected"},
7407 {WSAESHUTDOWN
, "Cannot send after socket shutdown"},
7408 {WSAETOOMANYREFS
, "Too many references"}, /* not sure */
7409 {WSAETIMEDOUT
, "Connection timed out"},
7410 {WSAECONNREFUSED
, "Connection refused"},
7411 {WSAELOOP
, "Network loop"}, /* not sure */
7412 {WSAENAMETOOLONG
, "Name is too long"},
7413 {WSAEHOSTDOWN
, "Host is down"},
7414 {WSAEHOSTUNREACH
, "No route to host"},
7415 {WSAENOTEMPTY
, "Buffer not empty"}, /* not sure */
7416 {WSAEPROCLIM
, "Too many processes"},
7417 {WSAEUSERS
, "Too many users"}, /* not sure */
7418 {WSAEDQUOT
, "Double quote in host name"}, /* really not sure */
7419 {WSAESTALE
, "Data is stale"}, /* not sure */
7420 {WSAEREMOTE
, "Remote error"}, /* not sure */
7422 {WSASYSNOTREADY
, "Network subsystem is unavailable"},
7423 {WSAVERNOTSUPPORTED
, "WINSOCK.DLL version out of range"},
7424 {WSANOTINITIALISED
, "Winsock not initialized successfully"},
7425 {WSAEDISCON
, "Graceful shutdown in progress"},
7427 {WSAENOMORE
, "No more operations allowed"}, /* not sure */
7428 {WSAECANCELLED
, "Operation cancelled"}, /* not sure */
7429 {WSAEINVALIDPROCTABLE
, "Invalid procedure table from service provider"},
7430 {WSAEINVALIDPROVIDER
, "Invalid service provider version number"},
7431 {WSAEPROVIDERFAILEDINIT
, "Unable to initialize a service provider"},
7432 {WSASYSCALLFAILURE
, "System call failure"},
7433 {WSASERVICE_NOT_FOUND
, "Service not found"}, /* not sure */
7434 {WSATYPE_NOT_FOUND
, "Class type not found"},
7435 {WSA_E_NO_MORE
, "No more resources available"}, /* really not sure */
7436 {WSA_E_CANCELLED
, "Operation already cancelled"}, /* really not sure */
7437 {WSAEREFUSED
, "Operation refused"}, /* not sure */
7440 {WSAHOST_NOT_FOUND
, "Host not found"},
7441 {WSATRY_AGAIN
, "Authoritative host not found during name lookup"},
7442 {WSANO_RECOVERY
, "Non-recoverable error during name lookup"},
7443 {WSANO_DATA
, "Valid name, no data record of requested type"},
7449 sys_strerror (int error_no
)
7452 static char unknown_msg
[40];
7454 if (error_no
>= 0 && error_no
< sys_nerr
)
7455 return sys_errlist
[error_no
];
7457 for (i
= 0; _wsa_errlist
[i
].errnum
>= 0; i
++)
7458 if (_wsa_errlist
[i
].errnum
== error_no
)
7459 return _wsa_errlist
[i
].msg
;
7461 sprintf (unknown_msg
, "Unidentified error: %d", error_no
);
7465 /* [andrewi 3-May-96] I've had conflicting results using both methods,
7466 but I believe the method of keeping the socket handle separate (and
7467 insuring it is not inheritable) is the correct one. */
7469 #define SOCK_HANDLE(fd) ((SOCKET) fd_info[fd].hnd)
7471 static int socket_to_fd (SOCKET s
);
7474 sys_socket (int af
, int type
, int protocol
)
7478 if (winsock_lib
== NULL
)
7486 /* call the real socket function */
7487 s
= pfn_socket (af
, type
, protocol
);
7489 if (s
!= INVALID_SOCKET
)
7490 return socket_to_fd (s
);
7496 /* Convert a SOCKET to a file descriptor. */
7498 socket_to_fd (SOCKET s
)
7503 /* Although under NT 3.5 _open_osfhandle will accept a socket
7504 handle, if opened with SO_OPENTYPE == SO_SYNCHRONOUS_NONALERT,
7505 that does not work under NT 3.1. However, we can get the same
7506 effect by using a backdoor function to replace an existing
7507 descriptor handle with the one we want. */
7509 /* allocate a file descriptor (with appropriate flags) */
7510 fd
= _open ("NUL:", _O_RDWR
);
7513 /* Make a non-inheritable copy of the socket handle. Note
7514 that it is possible that sockets aren't actually kernel
7515 handles, which appears to be the case on Windows 9x when
7516 the MS Proxy winsock client is installed. */
7518 /* Apparently there is a bug in NT 3.51 with some service
7519 packs, which prevents using DuplicateHandle to make a
7520 socket handle non-inheritable (causes WSACleanup to
7521 hang). The work-around is to use SetHandleInformation
7522 instead if it is available and implemented. */
7523 if (pfn_SetHandleInformation
)
7525 pfn_SetHandleInformation ((HANDLE
) s
, HANDLE_FLAG_INHERIT
, 0);
7529 HANDLE parent
= GetCurrentProcess ();
7530 HANDLE new_s
= INVALID_HANDLE_VALUE
;
7532 if (DuplicateHandle (parent
,
7538 DUPLICATE_SAME_ACCESS
))
7540 /* It is possible that DuplicateHandle succeeds even
7541 though the socket wasn't really a kernel handle,
7542 because a real handle has the same value. So
7543 test whether the new handle really is a socket. */
7544 unsigned long nonblocking
= 0;
7545 if (pfn_ioctlsocket ((SOCKET
) new_s
, FIONBIO
, &nonblocking
) == 0)
7547 pfn_closesocket (s
);
7552 CloseHandle (new_s
);
7557 eassert (fd
< MAXDESC
);
7558 fd_info
[fd
].hnd
= (HANDLE
) s
;
7560 /* set our own internal flags */
7561 fd_info
[fd
].flags
= FILE_SOCKET
| FILE_BINARY
| FILE_READ
| FILE_WRITE
;
7567 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
7569 /* attach child_process to fd_info */
7570 if (fd_info
[ fd
].cp
!= NULL
)
7572 DebPrint (("sys_socket: fd_info[%d] apparently in use!\n", fd
));
7576 fd_info
[ fd
].cp
= cp
;
7579 winsock_inuse
++; /* count open sockets */
7587 pfn_closesocket (s
);
7593 sys_bind (int s
, const struct sockaddr
* addr
, int namelen
)
7595 if (winsock_lib
== NULL
)
7598 return SOCKET_ERROR
;
7602 if (fd_info
[s
].flags
& FILE_SOCKET
)
7604 int rc
= pfn_bind (SOCK_HANDLE (s
), addr
, namelen
);
7605 if (rc
== SOCKET_ERROR
)
7610 return SOCKET_ERROR
;
7614 sys_connect (int s
, const struct sockaddr
* name
, int namelen
)
7616 if (winsock_lib
== NULL
)
7619 return SOCKET_ERROR
;
7623 if (fd_info
[s
].flags
& FILE_SOCKET
)
7625 int rc
= pfn_connect (SOCK_HANDLE (s
), name
, namelen
);
7626 if (rc
== SOCKET_ERROR
)
7629 /* If this is a non-blocking 'connect', set the bit in flags
7630 that will tell reader_thread to wait for connection
7631 before trying to read. */
7632 if (errno
== EWOULDBLOCK
&& (fd_info
[s
].flags
& FILE_NDELAY
) != 0)
7634 errno
= EINPROGRESS
; /* that's what process.c expects */
7635 fd_info
[s
].flags
|= FILE_CONNECT
;
7641 return SOCKET_ERROR
;
7645 sys_htons (u_short hostshort
)
7647 return (winsock_lib
!= NULL
) ?
7648 pfn_htons (hostshort
) : hostshort
;
7652 sys_ntohs (u_short netshort
)
7654 return (winsock_lib
!= NULL
) ?
7655 pfn_ntohs (netshort
) : netshort
;
7659 sys_inet_addr (const char * cp
)
7661 return (winsock_lib
!= NULL
) ?
7662 pfn_inet_addr (cp
) : INADDR_NONE
;
7666 sys_gethostname (char * name
, int namelen
)
7668 if (winsock_lib
!= NULL
)
7673 retval
= pfn_gethostname (name
, namelen
);
7674 if (retval
== SOCKET_ERROR
)
7679 if (namelen
> MAX_COMPUTERNAME_LENGTH
)
7680 return !GetComputerName (name
, (DWORD
*)&namelen
);
7683 return SOCKET_ERROR
;
7687 sys_gethostbyname (const char * name
)
7689 struct hostent
* host
;
7690 int h_err
= h_errno
;
7692 if (winsock_lib
== NULL
)
7694 h_errno
= NO_RECOVERY
;
7700 host
= pfn_gethostbyname (name
);
7712 sys_getservbyname (const char * name
, const char * proto
)
7714 struct servent
* serv
;
7716 if (winsock_lib
== NULL
)
7723 serv
= pfn_getservbyname (name
, proto
);
7730 sys_getpeername (int s
, struct sockaddr
*addr
, int * namelen
)
7732 if (winsock_lib
== NULL
)
7735 return SOCKET_ERROR
;
7739 if (fd_info
[s
].flags
& FILE_SOCKET
)
7741 int rc
= pfn_getpeername (SOCK_HANDLE (s
), addr
, namelen
);
7742 if (rc
== SOCKET_ERROR
)
7747 return SOCKET_ERROR
;
7751 sys_getaddrinfo (const char *node
, const char *service
,
7752 const struct addrinfo
*hints
, struct addrinfo
**res
)
7756 if (winsock_lib
== NULL
)
7759 return SOCKET_ERROR
;
7763 if (pfn_getaddrinfo
)
7764 rc
= pfn_getaddrinfo (node
, service
, hints
, res
);
7768 struct hostent
*host_info
;
7769 struct gai_storage
{
7770 struct addrinfo addrinfo
;
7771 struct sockaddr_in sockaddr_in
;
7774 /* We don't (yet) support any flags, as Emacs doesn't need that. */
7775 if (hints
&& hints
->ai_flags
!= 0)
7777 /* NODE cannot be NULL, since process.c has fallbacks for that. */
7779 return WSAHOST_NOT_FOUND
;
7783 const char *protocol
=
7784 (hints
&& hints
->ai_socktype
== SOCK_DGRAM
) ? "udp" : "tcp";
7785 struct servent
*srv
= sys_getservbyname (service
, protocol
);
7789 else if (*service
>= '0' && *service
<= '9')
7793 port
= strtoul (service
, &endp
, 10);
7794 if (*endp
|| port
> 65536)
7795 return WSAHOST_NOT_FOUND
;
7796 port
= sys_htons ((unsigned short) port
);
7799 return WSAHOST_NOT_FOUND
;
7802 gai_storage
= xzalloc (sizeof *gai_storage
);
7803 gai_storage
->sockaddr_in
.sin_port
= port
;
7804 host_info
= sys_gethostbyname (node
);
7807 memcpy (&gai_storage
->sockaddr_in
.sin_addr
,
7808 host_info
->h_addr
, host_info
->h_length
);
7809 gai_storage
->sockaddr_in
.sin_family
= host_info
->h_addrtype
;
7813 /* Attempt to interpret host as numeric inet address. */
7814 unsigned long numeric_addr
= sys_inet_addr (node
);
7816 if (numeric_addr
== -1)
7819 return WSAHOST_NOT_FOUND
;
7822 memcpy (&gai_storage
->sockaddr_in
.sin_addr
, &numeric_addr
,
7823 sizeof (gai_storage
->sockaddr_in
.sin_addr
));
7824 gai_storage
->sockaddr_in
.sin_family
= (hints
) ? hints
->ai_family
: 0;
7827 gai_storage
->addrinfo
.ai_addr
=
7828 (struct sockaddr
*)&gai_storage
->sockaddr_in
;
7829 gai_storage
->addrinfo
.ai_addrlen
= sizeof (gai_storage
->sockaddr_in
);
7830 gai_storage
->addrinfo
.ai_protocol
= (hints
) ? hints
->ai_protocol
: 0;
7831 gai_storage
->addrinfo
.ai_socktype
= (hints
) ? hints
->ai_socktype
: 0;
7832 gai_storage
->addrinfo
.ai_family
= gai_storage
->sockaddr_in
.sin_family
;
7833 gai_storage
->addrinfo
.ai_next
= NULL
;
7835 *res
= &gai_storage
->addrinfo
;
7843 sys_freeaddrinfo (struct addrinfo
*ai
)
7845 if (winsock_lib
== NULL
)
7852 if (pfn_freeaddrinfo
)
7853 pfn_freeaddrinfo (ai
);
7856 eassert (ai
->ai_next
== NULL
);
7862 sys_shutdown (int s
, int how
)
7864 if (winsock_lib
== NULL
)
7867 return SOCKET_ERROR
;
7871 if (fd_info
[s
].flags
& FILE_SOCKET
)
7873 int rc
= pfn_shutdown (SOCK_HANDLE (s
), how
);
7874 if (rc
== SOCKET_ERROR
)
7879 return SOCKET_ERROR
;
7883 sys_setsockopt (int s
, int level
, int optname
, const void * optval
, int optlen
)
7885 if (winsock_lib
== NULL
)
7888 return SOCKET_ERROR
;
7892 if (fd_info
[s
].flags
& FILE_SOCKET
)
7894 int rc
= pfn_setsockopt (SOCK_HANDLE (s
), level
, optname
,
7895 (const char *)optval
, optlen
);
7896 if (rc
== SOCKET_ERROR
)
7901 return SOCKET_ERROR
;
7905 sys_listen (int s
, int backlog
)
7907 if (winsock_lib
== NULL
)
7910 return SOCKET_ERROR
;
7914 if (fd_info
[s
].flags
& FILE_SOCKET
)
7916 int rc
= pfn_listen (SOCK_HANDLE (s
), backlog
);
7917 if (rc
== SOCKET_ERROR
)
7920 fd_info
[s
].flags
|= FILE_LISTEN
;
7924 return SOCKET_ERROR
;
7928 sys_getsockname (int s
, struct sockaddr
* name
, int * namelen
)
7930 if (winsock_lib
== NULL
)
7933 return SOCKET_ERROR
;
7937 if (fd_info
[s
].flags
& FILE_SOCKET
)
7939 int rc
= pfn_getsockname (SOCK_HANDLE (s
), name
, namelen
);
7940 if (rc
== SOCKET_ERROR
)
7945 return SOCKET_ERROR
;
7949 sys_accept (int s
, struct sockaddr
* addr
, int * addrlen
)
7951 if (winsock_lib
== NULL
)
7958 if (fd_info
[s
].flags
& FILE_LISTEN
)
7960 SOCKET t
= pfn_accept (SOCK_HANDLE (s
), addr
, addrlen
);
7962 if (t
== INVALID_SOCKET
)
7965 fd
= socket_to_fd (t
);
7969 fd_info
[s
].cp
->status
= STATUS_READ_ACKNOWLEDGED
;
7970 ResetEvent (fd_info
[s
].cp
->char_avail
);
7979 sys_recvfrom (int s
, char * buf
, int len
, int flags
,
7980 struct sockaddr
* from
, int * fromlen
)
7982 if (winsock_lib
== NULL
)
7985 return SOCKET_ERROR
;
7989 if (fd_info
[s
].flags
& FILE_SOCKET
)
7991 int rc
= pfn_recvfrom (SOCK_HANDLE (s
), buf
, len
, flags
, from
, fromlen
);
7992 if (rc
== SOCKET_ERROR
)
7997 return SOCKET_ERROR
;
8001 sys_sendto (int s
, const char * buf
, int len
, int flags
,
8002 const struct sockaddr
* to
, int tolen
)
8004 if (winsock_lib
== NULL
)
8007 return SOCKET_ERROR
;
8011 if (fd_info
[s
].flags
& FILE_SOCKET
)
8013 int rc
= pfn_sendto (SOCK_HANDLE (s
), buf
, len
, flags
, to
, tolen
);
8014 if (rc
== SOCKET_ERROR
)
8019 return SOCKET_ERROR
;
8022 /* Windows does not have an fcntl function. Provide an implementation
8023 good enough for Emacs. */
8025 fcntl (int s
, int cmd
, int options
)
8027 /* In the w32 Emacs port, fcntl (fd, F_DUPFD_CLOEXEC, fd1) is always
8028 invoked in a context where fd1 is closed and all descriptors less
8029 than fd1 are open, so sys_dup is an adequate implementation. */
8030 if (cmd
== F_DUPFD_CLOEXEC
)
8034 if (fd_info
[s
].flags
& FILE_SOCKET
)
8036 if (winsock_lib
== NULL
)
8042 if (cmd
== F_SETFL
&& options
== O_NONBLOCK
)
8044 unsigned long nblock
= 1;
8045 int rc
= pfn_ioctlsocket (SOCK_HANDLE (s
), FIONBIO
, &nblock
);
8046 if (rc
== SOCKET_ERROR
)
8048 /* Keep track of the fact that we set this to non-blocking. */
8049 fd_info
[s
].flags
|= FILE_NDELAY
;
8055 return SOCKET_ERROR
;
8058 else if ((fd_info
[s
].flags
& (FILE_PIPE
| FILE_WRITE
))
8059 == (FILE_PIPE
| FILE_WRITE
))
8061 /* Force our writes to pipes be non-blocking. */
8062 if (cmd
== F_SETFL
&& options
== O_NONBLOCK
)
8064 HANDLE h
= (HANDLE
)_get_osfhandle (s
);
8065 DWORD pipe_mode
= PIPE_NOWAIT
;
8067 if (!SetNamedPipeHandleState (h
, &pipe_mode
, NULL
, NULL
))
8069 DebPrint (("SetNamedPipeHandleState: %lu\n", GetLastError ()));
8070 return SOCKET_ERROR
;
8072 fd_info
[s
].flags
|= FILE_NDELAY
;
8078 return SOCKET_ERROR
;
8082 return SOCKET_ERROR
;
8086 /* Shadow main io functions: we need to handle pipes and sockets more
8100 if (fd
< MAXDESC
&& fd_info
[fd
].cp
)
8102 child_process
* cp
= fd_info
[fd
].cp
;
8104 fd_info
[fd
].cp
= NULL
;
8106 if (CHILD_ACTIVE (cp
))
8108 /* if last descriptor to active child_process then cleanup */
8110 for (i
= 0; i
< MAXDESC
; i
++)
8114 if (fd_info
[i
].cp
== cp
)
8119 if (fd_info
[fd
].flags
& FILE_SOCKET
)
8121 if (winsock_lib
== NULL
) emacs_abort ();
8123 pfn_shutdown (SOCK_HANDLE (fd
), 2);
8124 rc
= pfn_closesocket (SOCK_HANDLE (fd
));
8126 winsock_inuse
--; /* count open sockets */
8128 /* If the process handle is NULL, it's either a socket
8129 or serial connection, or a subprocess that was
8130 already reaped by reap_subprocess, but whose
8131 resources were not yet freed, because its output was
8132 not fully read yet by the time it was reaped. (This
8133 usually happens with async subprocesses whose output
8134 is being read by Emacs.) Otherwise, this process was
8135 not reaped yet, so we set its FD to a negative value
8136 to make sure sys_select will eventually get to
8137 calling the SIGCHLD handler for it, which will then
8138 invoke waitpid and reap_subprocess. */
8139 if (cp
->procinfo
.hProcess
== NULL
)
8147 if (fd
>= 0 && fd
< MAXDESC
)
8148 fd_info
[fd
].flags
= 0;
8150 /* Note that sockets do not need special treatment here (at least on
8151 NT and Windows 95 using the standard tcp/ip stacks) - it appears that
8152 closesocket is equivalent to CloseHandle, which is to be expected
8153 because socket handles are fully fledged kernel handles. */
8165 if (new_fd
>= 0 && new_fd
< MAXDESC
)
8167 /* duplicate our internal info as well */
8168 fd_info
[new_fd
] = fd_info
[fd
];
8174 sys_dup2 (int src
, int dst
)
8178 if (dst
< 0 || dst
>= MAXDESC
)
8184 /* MS _dup2 seems to have weird side effect when invoked with 2
8185 identical arguments: an attempt to fclose the corresponding stdio
8186 stream after that hangs (we do close standard streams in
8187 init_ntproc). Attempt to avoid that by not calling _dup2 that
8188 way: if SRC is valid, we know that dup2 should be a no-op, so do
8189 nothing and return DST. */
8192 if ((HANDLE
)_get_osfhandle (src
) == INVALID_HANDLE_VALUE
)
8200 /* Make sure we close the destination first if it's a pipe or socket. */
8201 if (fd_info
[dst
].flags
!= 0)
8204 rc
= _dup2 (src
, dst
);
8207 /* Duplicate our internal info as well. */
8208 fd_info
[dst
] = fd_info
[src
];
8210 return rc
== 0 ? dst
: rc
;
8214 pipe2 (int * phandles
, int pipe2_flags
)
8218 unsigned pipe_size
= 0;
8220 eassert (pipe2_flags
== (O_BINARY
| O_CLOEXEC
));
8222 /* Allow Lisp to override the default buffer size of the pipe. */
8223 if (w32_pipe_buffer_size
> 0 && w32_pipe_buffer_size
< UINT_MAX
)
8224 pipe_size
= w32_pipe_buffer_size
;
8226 /* make pipe handles non-inheritable; when we spawn a child, we
8227 replace the relevant handle with an inheritable one. Also put
8228 pipes into binary mode; we will do text mode translation ourselves
8230 rc
= _pipe (phandles
, pipe_size
, _O_NOINHERIT
| _O_BINARY
);
8234 /* Protect against overflow, since Windows can open more handles than
8235 our fd_info array has room for. */
8236 if (phandles
[0] >= MAXDESC
|| phandles
[1] >= MAXDESC
)
8238 _close (phandles
[0]);
8239 _close (phandles
[1]);
8245 flags
= FILE_PIPE
| FILE_READ
| FILE_BINARY
;
8246 fd_info
[phandles
[0]].flags
= flags
;
8248 flags
= FILE_PIPE
| FILE_WRITE
| FILE_BINARY
;
8249 fd_info
[phandles
[1]].flags
= flags
;
8256 /* Function to do blocking read of one byte, needed to implement
8257 select. It is only allowed on communication ports, sockets, or
8260 _sys_read_ahead (int fd
)
8265 if (fd
< 0 || fd
>= MAXDESC
)
8266 return STATUS_READ_ERROR
;
8268 cp
= fd_info
[fd
].cp
;
8270 if (cp
== NULL
|| cp
->fd
!= fd
|| cp
->status
!= STATUS_READ_READY
)
8271 return STATUS_READ_ERROR
;
8273 if ((fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SERIAL
| FILE_SOCKET
)) == 0
8274 || (fd_info
[fd
].flags
& FILE_READ
) == 0)
8276 DebPrint (("_sys_read_ahead: internal error: fd %d is not a pipe, serial port, or socket!\n", fd
));
8280 if ((fd_info
[fd
].flags
& FILE_CONNECT
) != 0)
8281 DebPrint (("_sys_read_ahead: read requested from fd %d, which waits for async connect!\n", fd
));
8282 cp
->status
= STATUS_READ_IN_PROGRESS
;
8284 if (fd_info
[fd
].flags
& FILE_PIPE
)
8286 rc
= _read (fd
, &cp
->chr
, sizeof (char));
8288 /* Give subprocess time to buffer some more output for us before
8289 reporting that input is available; we need this because Windows 95
8290 connects DOS programs to pipes by making the pipe appear to be
8291 the normal console stdout - as a result most DOS programs will
8292 write to stdout without buffering, ie. one character at a
8293 time. Even some W32 programs do this - "dir" in a command
8294 shell on NT is very slow if we don't do this. */
8297 int wait
= w32_pipe_read_delay
;
8303 /* Yield remainder of our time slice, effectively giving a
8304 temporary priority boost to the child process. */
8308 else if (fd_info
[fd
].flags
& FILE_SERIAL
)
8310 HANDLE hnd
= fd_info
[fd
].hnd
;
8311 OVERLAPPED
*ovl
= &fd_info
[fd
].cp
->ovl_read
;
8314 /* Configure timeouts for blocking read. */
8315 if (!GetCommTimeouts (hnd
, &ct
))
8317 cp
->status
= STATUS_READ_ERROR
;
8318 return STATUS_READ_ERROR
;
8320 ct
.ReadIntervalTimeout
= 0;
8321 ct
.ReadTotalTimeoutMultiplier
= 0;
8322 ct
.ReadTotalTimeoutConstant
= 0;
8323 if (!SetCommTimeouts (hnd
, &ct
))
8325 cp
->status
= STATUS_READ_ERROR
;
8326 return STATUS_READ_ERROR
;
8329 if (!ReadFile (hnd
, &cp
->chr
, sizeof (char), (DWORD
*) &rc
, ovl
))
8331 if (GetLastError () != ERROR_IO_PENDING
)
8333 cp
->status
= STATUS_READ_ERROR
;
8334 return STATUS_READ_ERROR
;
8336 if (!GetOverlappedResult (hnd
, ovl
, (DWORD
*) &rc
, TRUE
))
8338 cp
->status
= STATUS_READ_ERROR
;
8339 return STATUS_READ_ERROR
;
8343 else if (fd_info
[fd
].flags
& FILE_SOCKET
)
8345 unsigned long nblock
= 0;
8346 /* We always want this to block, so temporarily disable NDELAY. */
8347 if (fd_info
[fd
].flags
& FILE_NDELAY
)
8348 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
8350 rc
= pfn_recv (SOCK_HANDLE (fd
), &cp
->chr
, sizeof (char), 0);
8352 if (fd_info
[fd
].flags
& FILE_NDELAY
)
8355 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
8359 if (rc
== sizeof (char))
8360 cp
->status
= STATUS_READ_SUCCEEDED
;
8362 cp
->status
= STATUS_READ_FAILED
;
8368 _sys_wait_accept (int fd
)
8374 if (fd
< 0 || fd
>= MAXDESC
)
8375 return STATUS_READ_ERROR
;
8377 cp
= fd_info
[fd
].cp
;
8379 if (cp
== NULL
|| cp
->fd
!= fd
|| cp
->status
!= STATUS_READ_READY
)
8380 return STATUS_READ_ERROR
;
8382 cp
->status
= STATUS_READ_FAILED
;
8384 hEv
= pfn_WSACreateEvent ();
8385 rc
= pfn_WSAEventSelect (SOCK_HANDLE (fd
), hEv
, FD_ACCEPT
);
8386 if (rc
!= SOCKET_ERROR
)
8389 rc
= WaitForSingleObject (hEv
, 500);
8391 } while (rc
== WAIT_TIMEOUT
8392 && cp
->status
!= STATUS_READ_ERROR
8394 pfn_WSAEventSelect (SOCK_HANDLE (fd
), NULL
, 0);
8395 if (rc
== WAIT_OBJECT_0
)
8396 cp
->status
= STATUS_READ_SUCCEEDED
;
8398 pfn_WSACloseEvent (hEv
);
8404 _sys_wait_connect (int fd
)
8410 if (fd
< 0 || fd
>= MAXDESC
)
8411 return STATUS_READ_ERROR
;
8413 cp
= fd_info
[fd
].cp
;
8414 if (cp
== NULL
|| cp
->fd
!= fd
|| cp
->status
!= STATUS_READ_READY
)
8415 return STATUS_READ_ERROR
;
8417 cp
->status
= STATUS_READ_FAILED
;
8419 hEv
= pfn_WSACreateEvent ();
8420 rc
= pfn_WSAEventSelect (SOCK_HANDLE (fd
), hEv
, FD_CONNECT
);
8421 if (rc
!= SOCKET_ERROR
)
8424 rc
= WaitForSingleObject (hEv
, 500);
8426 } while (rc
== WAIT_TIMEOUT
8427 && cp
->status
!= STATUS_READ_ERROR
8429 if (rc
== WAIT_OBJECT_0
)
8431 /* We've got an event, but it could be a successful
8432 connection, or it could be a failure. Find out
8434 WSANETWORKEVENTS events
;
8436 pfn_WSAEnumNetworkEvents (SOCK_HANDLE (fd
), hEv
, &events
);
8437 if ((events
.lNetworkEvents
& FD_CONNECT
) != 0
8438 && events
.iErrorCode
[FD_CONNECT_BIT
])
8440 cp
->status
= STATUS_CONNECT_FAILED
;
8441 cp
->errcode
= events
.iErrorCode
[FD_CONNECT_BIT
];
8445 cp
->status
= STATUS_READ_SUCCEEDED
;
8449 pfn_WSAEventSelect (SOCK_HANDLE (fd
), NULL
, 0);
8452 pfn_WSACloseEvent (hEv
);
8458 sys_read (int fd
, char * buffer
, unsigned int count
)
8463 char * orig_buffer
= buffer
;
8471 if (fd
< MAXDESC
&& fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
| FILE_SERIAL
))
8473 child_process
*cp
= fd_info
[fd
].cp
;
8475 if ((fd_info
[fd
].flags
& FILE_READ
) == 0)
8483 /* re-read CR carried over from last read */
8484 if (fd_info
[fd
].flags
& FILE_LAST_CR
)
8486 if (fd_info
[fd
].flags
& FILE_BINARY
) emacs_abort ();
8490 fd_info
[fd
].flags
&= ~FILE_LAST_CR
;
8493 /* presence of a child_process structure means we are operating in
8494 non-blocking mode - otherwise we just call _read directly.
8495 Note that the child_process structure might be missing because
8496 reap_subprocess has been called; in this case the pipe is
8497 already broken, so calling _read on it is okay. */
8500 int current_status
= cp
->status
;
8502 switch (current_status
)
8504 case STATUS_READ_FAILED
:
8505 case STATUS_READ_ERROR
:
8506 /* report normal EOF if nothing in buffer */
8508 fd_info
[fd
].flags
|= FILE_AT_EOF
;
8511 case STATUS_READ_READY
:
8512 case STATUS_READ_IN_PROGRESS
:
8514 /* This happens all the time during GnuTLS handshake
8515 with the remote, evidently because GnuTLS waits for
8516 the read to complete by retrying the read operation
8517 upon EAGAIN. So I'm disabling the DebPrint to avoid
8518 wasting cycles on something that is not a real
8519 problem. Enable if you need to debug something that
8521 DebPrint (("sys_read called when read is in progress %d\n",
8524 errno
= EWOULDBLOCK
;
8527 case STATUS_READ_SUCCEEDED
:
8528 /* consume read-ahead char */
8529 *buffer
++ = cp
->chr
;
8532 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
8533 ResetEvent (cp
->char_avail
);
8535 case STATUS_READ_ACKNOWLEDGED
:
8536 case STATUS_CONNECT_FAILED
:
8540 DebPrint (("sys_read: bad status %d\n", current_status
));
8545 if (fd_info
[fd
].flags
& FILE_PIPE
)
8547 PeekNamedPipe ((HANDLE
) _get_osfhandle (fd
), NULL
, 0, NULL
, &waiting
, NULL
);
8548 to_read
= min (waiting
, (DWORD
) count
);
8551 nchars
+= _read (fd
, buffer
, to_read
);
8553 else if (fd_info
[fd
].flags
& FILE_SERIAL
)
8555 HANDLE hnd
= fd_info
[fd
].hnd
;
8556 OVERLAPPED
*ovl
= &fd_info
[fd
].cp
->ovl_read
;
8562 /* Configure timeouts for non-blocking read. */
8563 if (!GetCommTimeouts (hnd
, &ct
))
8568 ct
.ReadIntervalTimeout
= MAXDWORD
;
8569 ct
.ReadTotalTimeoutMultiplier
= 0;
8570 ct
.ReadTotalTimeoutConstant
= 0;
8571 if (!SetCommTimeouts (hnd
, &ct
))
8577 if (!ResetEvent (ovl
->hEvent
))
8582 if (!ReadFile (hnd
, buffer
, count
, (DWORD
*) &rc
, ovl
))
8584 if (GetLastError () != ERROR_IO_PENDING
)
8589 if (!GetOverlappedResult (hnd
, ovl
, (DWORD
*) &rc
, TRUE
))
8598 else /* FILE_SOCKET */
8600 if (winsock_lib
== NULL
) emacs_abort ();
8602 /* When a non-blocking 'connect' call fails,
8603 wait_reading_process_output detects this by calling
8604 'getpeername', and then attempts to obtain the connection
8605 error code by trying to read 1 byte from the socket. If
8606 we try to serve that read by calling 'recv' below, the
8607 error we get is a generic WSAENOTCONN, not the actual
8608 connection error. So instead, we use the actual error
8609 code stashed by '_sys_wait_connect' in cp->errcode.
8610 Alternatively, we could have used 'getsockopt', like on
8611 GNU/Linux, but: (a) I have no idea whether the winsock
8612 version could hang, as it does "on some systems" (see the
8613 comment in process.c); and (b) 'getsockopt' on Windows is
8614 documented to clear the socket error for the entire
8615 process, which I'm not sure is TRT; FIXME. */
8616 if (current_status
== STATUS_CONNECT_FAILED
8617 && (fd_info
[fd
].flags
& FILE_CONNECT
) != 0
8618 && cp
->errcode
!= 0)
8620 pfn_WSASetLastError (cp
->errcode
);
8624 /* Do the equivalent of a non-blocking read. */
8625 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONREAD
, &waiting
);
8626 if (waiting
== 0 && nchars
== 0)
8628 errno
= EWOULDBLOCK
;
8634 /* always use binary mode for sockets */
8635 int res
= pfn_recv (SOCK_HANDLE (fd
), buffer
, count
, 0);
8636 if (res
== SOCKET_ERROR
)
8639 DebPrint (("sys_read.recv failed with error %d on socket %ld\n",
8640 errno
, SOCK_HANDLE (fd
)));
8649 int nread
= _read (fd
, buffer
, count
);
8652 else if (nchars
== 0)
8657 fd_info
[fd
].flags
|= FILE_AT_EOF
;
8658 /* Perform text mode translation if required. */
8659 else if ((fd_info
[fd
].flags
& FILE_BINARY
) == 0)
8661 nchars
= crlf_to_lf (nchars
, orig_buffer
);
8662 /* If buffer contains only CR, return that. To be absolutely
8663 sure we should attempt to read the next char, but in
8664 practice a CR to be followed by LF would not appear by
8665 itself in the buffer. */
8666 if (nchars
> 1 && orig_buffer
[nchars
- 1] == 0x0d)
8668 fd_info
[fd
].flags
|= FILE_LAST_CR
;
8674 nchars
= _read (fd
, buffer
, count
);
8679 /* From w32xfns.c */
8680 extern HANDLE interrupt_handle
;
8683 sys_write (int fd
, const void * buffer
, unsigned int count
)
8694 if (fd
< MAXDESC
&& fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
| FILE_SERIAL
))
8696 if ((fd_info
[fd
].flags
& FILE_WRITE
) == 0)
8702 /* Perform text mode translation if required. */
8703 if ((fd_info
[fd
].flags
& FILE_BINARY
) == 0)
8706 const unsigned char * src
= buffer
;
8707 unsigned char * dst
;
8710 SAFE_NALLOCA (tmpbuf
, 2, count
);
8711 dst
= (unsigned char *)tmpbuf
;
8715 unsigned char *next
;
8716 /* Copy next line or remaining bytes. */
8717 next
= _memccpy (dst
, src
, '\n', nbytes
);
8720 /* Copied one line ending with '\n'. */
8721 int copied
= next
- dst
;
8724 /* Insert '\r' before '\n'. */
8731 /* Copied remaining partial line -> now finished. */
8738 if (fd
< MAXDESC
&& fd_info
[fd
].flags
& FILE_SERIAL
)
8740 HANDLE hnd
= (HANDLE
) _get_osfhandle (fd
);
8741 OVERLAPPED
*ovl
= &fd_info
[fd
].cp
->ovl_write
;
8742 HANDLE wait_hnd
[2] = { interrupt_handle
, ovl
->hEvent
};
8745 /* This is async (a.k.a. "overlapped") I/O, so the return value
8746 of FALSE from WriteFile means either an error or the output
8747 will be completed asynchronously (ERROR_IO_PENDING). */
8748 if (!WriteFile (hnd
, buffer
, count
, (DWORD
*) &nchars
, ovl
))
8750 if (GetLastError () != ERROR_IO_PENDING
)
8757 /* Wait for the write to complete, and watch C-g while
8759 if (detect_input_pending ())
8760 active
= MsgWaitForMultipleObjects (2, wait_hnd
, FALSE
,
8761 INFINITE
, QS_ALLINPUT
);
8763 active
= WaitForMultipleObjects (2, wait_hnd
, FALSE
, INFINITE
);
8767 /* User pressed C-g, cancel write, then leave.
8768 Don't bother cleaning up as we may only get stuck
8769 in buggy drivers. */
8770 PurgeComm (hnd
, PURGE_TXABORT
| PURGE_TXCLEAR
);
8772 errno
= EIO
; /* Why not EINTR? */
8775 case WAIT_OBJECT_0
+ 1:
8776 if (!GetOverlappedResult (hnd
, ovl
, (DWORD
*) &nchars
, TRUE
))
8786 else if (fd
< MAXDESC
&& fd_info
[fd
].flags
& FILE_SOCKET
)
8788 unsigned long nblock
= 0;
8789 if (winsock_lib
== NULL
) emacs_abort ();
8791 child_process
*cp
= fd_info
[fd
].cp
;
8793 /* If this is a non-blocking socket whose connection is in
8794 progress or terminated with an error already, return the
8795 proper error code to the caller. */
8796 if (cp
!= NULL
&& (fd_info
[fd
].flags
& FILE_CONNECT
) != 0)
8798 /* In case connection is in progress, ENOTCONN that would
8799 result from calling pfn_send is not what callers expect. */
8800 if (cp
->status
!= STATUS_CONNECT_FAILED
)
8802 errno
= EWOULDBLOCK
;
8805 /* In case connection failed, use the actual error code
8806 stashed by '_sys_wait_connect' in cp->errcode. */
8807 else if (cp
->errcode
!= 0)
8809 pfn_WSASetLastError (cp
->errcode
);
8815 /* TODO: implement select() properly so non-blocking I/O works. */
8816 /* For now, make sure the write blocks. */
8817 if (fd_info
[fd
].flags
& FILE_NDELAY
)
8818 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
8820 nchars
= pfn_send (SOCK_HANDLE (fd
), buffer
, count
, 0);
8822 if (nchars
== SOCKET_ERROR
)
8825 DebPrint (("sys_write.send failed with error %d on socket %ld\n",
8826 pfn_WSAGetLastError (), SOCK_HANDLE (fd
)));
8829 /* Set the socket back to non-blocking if it was before,
8830 for other operations that support it. */
8831 if (fd_info
[fd
].flags
& FILE_NDELAY
)
8834 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
8839 /* Some networked filesystems don't like too large writes, so
8840 break them into smaller chunks. See the Comments section of
8841 the MSDN documentation of WriteFile for details behind the
8842 choice of the value of CHUNK below. See also the thread
8843 http://thread.gmane.org/gmane.comp.version-control.git/145294
8844 in the git mailing list. */
8845 const unsigned char *p
= buffer
;
8846 const bool is_pipe
= (fd
< MAXDESC
8847 && ((fd_info
[fd
].flags
& (FILE_PIPE
| FILE_NDELAY
))
8848 == (FILE_PIPE
| FILE_NDELAY
)));
8849 /* Some programs, notably Node.js's node.exe, seem to never
8850 completely empty the pipe, so writing more than the size of
8851 the pipe's buffer always returns ENOSPC, and we loop forever
8852 between send_process and here. As a workaround, write no
8853 more than the pipe's buffer can hold. */
8854 DWORD pipe_buffer_size
;
8857 if (!GetNamedPipeInfo ((HANDLE
)_get_osfhandle (fd
),
8858 NULL
, &pipe_buffer_size
, NULL
, NULL
))
8860 DebPrint (("GetNamedPipeInfo: error %u\n", GetLastError ()));
8861 pipe_buffer_size
= 4096;
8864 const unsigned chunk
= is_pipe
? pipe_buffer_size
: 30 * 1024 * 1024;
8870 unsigned this_chunk
= count
< chunk
? count
: chunk
;
8871 int n
= _write (fd
, p
, this_chunk
);
8877 /* When there's no buffer space in a pipe that is in the
8878 non-blocking mode, _write returns ENOSPC. We return
8879 EAGAIN instead, which should trigger the logic in
8880 send_process that enters waiting loop and calls
8881 wait_reading_process_output to allow process input to
8882 be accepted during the wait. Those calls to
8883 wait_reading_process_output allow sys_select to
8884 notice when process input becomes available, thus
8885 avoiding deadlock whereby each side of the pipe is
8886 blocked on write, waiting for the other party to read
8887 its end of the pipe. */
8888 if (errno
== ENOSPC
&& is_pipe
)
8894 else if (n
< this_chunk
)
8906 /* Emulation of SIOCGIFCONF and getifaddrs, see process.c. */
8908 extern Lisp_Object
conv_sockaddr_to_lisp (struct sockaddr
*, ptrdiff_t);
8910 /* Return information about network interface IFNAME, or about all
8911 interfaces (if IFNAME is nil). */
8913 network_interface_get_info (Lisp_Object ifname
)
8915 ULONG ainfo_len
= sizeof (IP_ADAPTER_INFO
);
8916 IP_ADAPTER_INFO
*adapter
, *ainfo
= xmalloc (ainfo_len
);
8917 DWORD retval
= get_adapters_info (ainfo
, &ainfo_len
);
8918 Lisp_Object res
= Qnil
;
8920 if (retval
== ERROR_BUFFER_OVERFLOW
)
8922 ainfo
= xrealloc (ainfo
, ainfo_len
);
8923 retval
= get_adapters_info (ainfo
, &ainfo_len
);
8926 if (retval
== ERROR_SUCCESS
)
8928 int eth_count
= 0, tr_count
= 0, fddi_count
= 0, ppp_count
= 0;
8929 int sl_count
= 0, wlan_count
= 0, lo_count
= 0, ifx_count
= 0;
8931 struct sockaddr_in sa
;
8933 /* For the below, we need some winsock functions, so make sure
8934 the winsock DLL is loaded. If we cannot successfully load
8935 it, they will have no use of the information we provide,
8937 if (!winsock_lib
&& !init_winsock (1))
8940 for (adapter
= ainfo
; adapter
; adapter
= adapter
->Next
)
8942 char namebuf
[MAX_ADAPTER_NAME_LENGTH
+ 4];
8944 /* Present Unix-compatible interface names, instead of the
8945 Windows names, which are really GUIDs not readable by
8947 static const char *ifmt
[] = {
8948 "eth%d", "tr%d", "fddi%d", "ppp%d", "sl%d", "wlan%d",
8963 switch (adapter
->Type
)
8965 case MIB_IF_TYPE_ETHERNET
:
8966 /* Windows before Vista reports wireless adapters as
8967 Ethernet. Work around by looking at the Description
8969 if (strstr (adapter
->Description
, "Wireless "))
8972 if_num
= wlan_count
++;
8976 ifmt_idx
= ETHERNET
;
8977 if_num
= eth_count
++;
8980 case MIB_IF_TYPE_TOKENRING
:
8981 ifmt_idx
= TOKENRING
;
8982 if_num
= tr_count
++;
8984 case MIB_IF_TYPE_FDDI
:
8986 if_num
= fddi_count
++;
8988 case MIB_IF_TYPE_PPP
:
8990 if_num
= ppp_count
++;
8992 case MIB_IF_TYPE_SLIP
:
8994 if_num
= sl_count
++;
8996 case IF_TYPE_IEEE80211
:
8998 if_num
= wlan_count
++;
9000 case MIB_IF_TYPE_LOOPBACK
:
9003 ifmt_idx
= LOOPBACK
;
9004 if_num
= lo_count
++;
9010 ifmt_idx
= OTHER_IF
;
9011 if_num
= ifx_count
++;
9014 if (ifmt_idx
== NONE
)
9016 sprintf (namebuf
, ifmt
[ifmt_idx
], if_num
);
9018 sa
.sin_family
= AF_INET
;
9019 ip_addr
= sys_inet_addr (adapter
->IpAddressList
.IpAddress
.String
);
9020 if (ip_addr
== INADDR_NONE
)
9022 /* Bogus address, skip this interface. */
9025 sa
.sin_addr
.s_addr
= ip_addr
;
9028 res
= Fcons (Fcons (build_string (namebuf
),
9029 conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
9030 sizeof (struct sockaddr
))),
9032 else if (strcmp (namebuf
, SSDATA (ifname
)) == 0)
9034 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
9035 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
9036 Lisp_Object flags
= Qnil
;
9040 /* Flags. We guess most of them by type, since the
9041 Windows flags are different and hard to get by. */
9042 flags
= Fcons (intern ("up"), flags
);
9043 if (ifmt_idx
== ETHERNET
|| ifmt_idx
== WLAN
)
9045 flags
= Fcons (intern ("broadcast"), flags
);
9046 flags
= Fcons (intern ("multicast"), flags
);
9048 flags
= Fcons (intern ("running"), flags
);
9049 if (ifmt_idx
== PPP
)
9051 flags
= Fcons (intern ("pointopoint"), flags
);
9052 flags
= Fcons (intern ("noarp"), flags
);
9054 if (adapter
->HaveWins
)
9055 flags
= Fcons (intern ("WINS"), flags
);
9056 if (adapter
->DhcpEnabled
)
9057 flags
= Fcons (intern ("dynamic"), flags
);
9059 res
= Fcons (flags
, res
);
9061 /* Hardware address and its family. */
9062 for (n
= 0; n
< adapter
->AddressLength
; n
++)
9063 p
->contents
[n
] = make_number ((int) adapter
->Address
[n
]);
9064 /* Windows does not support AF_LINK or AF_PACKET family
9065 of addresses. Use an arbitrary family number that is
9066 identical to what GNU/Linux returns. */
9067 res
= Fcons (Fcons (make_number (1), hwaddr
), res
);
9070 sa
.sin_family
= AF_INET
;
9071 net_mask
= sys_inet_addr (adapter
->IpAddressList
.IpMask
.String
);
9072 if (net_mask
!= INADDR_NONE
)
9074 sa
.sin_addr
.s_addr
= net_mask
;
9076 res
= Fcons (conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
9077 sizeof (struct sockaddr
)),
9081 res
= Fcons (Qnil
, res
);
9083 sa
.sin_family
= AF_INET
;
9084 if (ip_addr
!= INADDR_NONE
)
9086 /* Broadcast address is only reported by
9087 GetAdaptersAddresses, which is of limited
9088 availability. Generate it on our own. */
9089 u_long bcast_addr
= (ip_addr
& net_mask
) | ~net_mask
;
9091 sa
.sin_addr
.s_addr
= bcast_addr
;
9093 res
= Fcons (conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
9094 sizeof (struct sockaddr
)),
9098 sa
.sin_addr
.s_addr
= ip_addr
;
9100 res
= Fcons (conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
9101 sizeof (struct sockaddr
)),
9105 res
= Fcons (Qnil
, Fcons (Qnil
, res
));
9108 /* GetAdaptersInfo is documented to not report loopback
9109 interfaces, so we generate one out of thin air. */
9112 sa
.sin_family
= AF_INET
;
9116 sa
.sin_addr
.s_addr
= sys_inet_addr ("127.0.0.1");
9117 res
= Fcons (Fcons (build_string ("lo"),
9118 conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
9119 sizeof (struct sockaddr
))),
9122 else if (strcmp (SSDATA (ifname
), "lo") == 0)
9124 res
= Fcons (Fcons (intern ("running"),
9125 Fcons (intern ("loopback"),
9126 Fcons (intern ("up"), Qnil
))), Qnil
);
9127 /* 772 is what 3 different GNU/Linux systems report for
9128 the loopback interface. */
9129 res
= Fcons (Fcons (make_number (772),
9130 Fmake_vector (make_number (6),
9133 sa
.sin_addr
.s_addr
= sys_inet_addr ("255.0.0.0");
9134 res
= Fcons (conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
9135 sizeof (struct sockaddr
)),
9137 sa
.sin_addr
.s_addr
= sys_inet_addr ("0.0.0.0");
9138 res
= Fcons (conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
9139 sizeof (struct sockaddr
)),
9141 sa
.sin_addr
.s_addr
= sys_inet_addr ("127.0.0.1");
9142 res
= Fcons (conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
9143 sizeof (struct sockaddr
)),
9156 network_interface_list (void)
9158 return network_interface_get_info (Qnil
);
9162 network_interface_info (Lisp_Object ifname
)
9164 CHECK_STRING (ifname
);
9165 return network_interface_get_info (ifname
);
9169 /* The Windows CRT functions are "optimized for speed", so they don't
9170 check for timezone and DST changes if they were last called less
9171 than 1 minute ago (see http://support.microsoft.com/kb/821231). So
9172 all Emacs features that repeatedly call time functions (e.g.,
9173 display-time) are in real danger of missing timezone and DST
9174 changes. Calling tzset before each localtime call fixes that. */
9176 sys_localtime (const time_t *t
)
9179 return localtime (t
);
9184 /* Try loading LIBRARY_ID from the file(s) specified in
9185 Vdynamic_library_alist. If the library is loaded successfully,
9186 return the handle of the DLL, and record the filename in the
9187 property :loaded-from of LIBRARY_ID. If the library could not be
9188 found, or when it was already loaded (because the handle is not
9189 recorded anywhere, and so is lost after use), return NULL.
9191 We could also save the handle in :loaded-from, but currently
9192 there's no use case for it. */
9194 w32_delayed_load (Lisp_Object library_id
)
9196 HMODULE dll_handle
= NULL
;
9198 CHECK_SYMBOL (library_id
);
9200 if (CONSP (Vdynamic_library_alist
)
9201 && NILP (Fassq (library_id
, Vlibrary_cache
)))
9203 Lisp_Object found
= Qnil
;
9204 Lisp_Object dlls
= Fassq (library_id
, Vdynamic_library_alist
);
9207 for (dlls
= XCDR (dlls
); CONSP (dlls
); dlls
= XCDR (dlls
))
9209 Lisp_Object dll
= XCAR (dlls
);
9210 char name
[MAX_UTF8_PATH
];
9214 dll
= ENCODE_FILE (dll
);
9215 if (w32_unicode_filenames
)
9217 wchar_t name_w
[MAX_PATH
];
9219 filename_to_utf16 (SSDATA (dll
), name_w
);
9220 dll_handle
= LoadLibraryW (name_w
);
9223 res
= GetModuleFileNameW (dll_handle
, name_w
,
9226 filename_from_utf16 (name_w
, name
);
9231 char name_a
[MAX_PATH
];
9233 filename_to_ansi (SSDATA (dll
), name_a
);
9234 dll_handle
= LoadLibraryA (name_a
);
9237 res
= GetModuleFileNameA (dll_handle
, name_a
,
9240 filename_from_ansi (name_a
, name
);
9245 ptrdiff_t len
= strlen (name
);
9248 /* Possibly truncated */
9249 ? make_specified_string (name
, -1, len
, 1)
9251 /* This prevents thread start and end notifications
9252 from being sent to the DLL, for every thread we
9253 start. We don't need those notifications because
9254 threads we create never use any of these DLLs, only
9255 the main thread uses them. This is supposed to
9256 speed up thread creation. */
9257 DisableThreadLibraryCalls (dll_handle
);
9262 Fput (library_id
, QCloaded_from
, found
);
9270 check_windows_init_file (void)
9272 /* A common indication that Emacs is not installed properly is when
9273 it cannot find the Windows installation file. If this file does
9274 not exist in the expected place, tell the user. */
9276 if (!noninteractive
&& !inhibit_window_system
9277 /* Vload_path is not yet initialized when we are loading
9279 && NILP (Vpurify_flag
))
9281 Lisp_Object init_file
;
9284 /* Implementation note: this function runs early during Emacs
9285 startup, before startup.el is run. So Vload_path is still in
9286 its initial unibyte form, but it holds UTF-8 encoded file
9287 names, since init_callproc was already called. So we do not
9288 need to ENCODE_FILE here, but we do need to convert the file
9289 names from UTF-8 to ANSI. */
9290 init_file
= build_string ("term/w32-win");
9291 fd
= openp (Vload_path
, init_file
, Fget_load_suffixes (), NULL
, Qnil
, 0);
9294 Lisp_Object load_path_print
= Fprin1_to_string (Vload_path
, Qnil
);
9295 char *init_file_name
= SSDATA (init_file
);
9296 char *load_path
= SSDATA (load_path_print
);
9297 char *buffer
= alloca (1024
9298 + strlen (init_file_name
)
9299 + strlen (load_path
));
9304 "The Emacs Windows initialization file \"%s.el\" "
9305 "could not be found in your Emacs installation. "
9306 "Emacs checked the following directories for this file:\n"
9308 "When Emacs cannot find this file, it usually means that it "
9309 "was not installed properly, or its distribution file was "
9310 "not unpacked properly.\nSee the README.W32 file in the "
9311 "top-level Emacs directory for more information.",
9312 init_file_name
, load_path
);
9313 needed
= pMultiByteToWideChar (CP_UTF8
, multiByteToWideCharFlags
,
9314 buffer
, -1, NULL
, 0);
9317 wchar_t *msg_w
= alloca ((needed
+ 1) * sizeof (wchar_t));
9319 pMultiByteToWideChar (CP_UTF8
, multiByteToWideCharFlags
, buffer
,
9321 needed
= pWideCharToMultiByte (CP_ACP
, 0, msg_w
, -1,
9322 NULL
, 0, NULL
, NULL
);
9325 char *msg_a
= alloca (needed
+ 1);
9327 pWideCharToMultiByte (CP_ACP
, 0, msg_w
, -1, msg_a
, needed
,
9334 "Emacs Abort Dialog",
9335 MB_OK
| MB_ICONEXCLAMATION
| MB_TASKMODAL
);
9336 /* Use the low-level system abort. */
9347 term_ntproc (int ignored
)
9353 /* shutdown the socket interface if necessary */
9360 init_ntproc (int dumping
)
9362 sigset_t initial_mask
= 0;
9364 /* Initialize the socket interface now if available and requested by
9365 the user by defining PRELOAD_WINSOCK; otherwise loading will be
9366 delayed until open-network-stream is called (w32-has-winsock can
9367 also be used to dynamically load or reload winsock).
9369 Conveniently, init_environment is called before us, so
9370 PRELOAD_WINSOCK can be set in the registry. */
9372 /* Always initialize this correctly. */
9375 if (getenv ("PRELOAD_WINSOCK") != NULL
)
9376 init_winsock (TRUE
);
9378 /* Initial preparation for subprocess support: replace our standard
9379 handles with non-inheritable versions. */
9382 HANDLE stdin_save
= INVALID_HANDLE_VALUE
;
9383 HANDLE stdout_save
= INVALID_HANDLE_VALUE
;
9384 HANDLE stderr_save
= INVALID_HANDLE_VALUE
;
9386 parent
= GetCurrentProcess ();
9388 /* ignore errors when duplicating and closing; typically the
9389 handles will be invalid when running as a gui program. */
9390 DuplicateHandle (parent
,
9391 GetStdHandle (STD_INPUT_HANDLE
),
9396 DUPLICATE_SAME_ACCESS
);
9398 DuplicateHandle (parent
,
9399 GetStdHandle (STD_OUTPUT_HANDLE
),
9404 DUPLICATE_SAME_ACCESS
);
9406 DuplicateHandle (parent
,
9407 GetStdHandle (STD_ERROR_HANDLE
),
9412 DUPLICATE_SAME_ACCESS
);
9418 if (stdin_save
!= INVALID_HANDLE_VALUE
)
9419 _open_osfhandle ((intptr_t) stdin_save
, O_TEXT
);
9421 _open ("nul", O_TEXT
| O_NOINHERIT
| O_RDONLY
);
9424 if (stdout_save
!= INVALID_HANDLE_VALUE
)
9425 _open_osfhandle ((intptr_t) stdout_save
, O_TEXT
);
9427 _open ("nul", O_TEXT
| O_NOINHERIT
| O_WRONLY
);
9430 if (stderr_save
!= INVALID_HANDLE_VALUE
)
9431 _open_osfhandle ((intptr_t) stderr_save
, O_TEXT
);
9433 _open ("nul", O_TEXT
| O_NOINHERIT
| O_WRONLY
);
9437 /* unfortunately, atexit depends on implementation of malloc */
9438 /* atexit (term_ntproc); */
9441 /* Make sure we start with all signals unblocked. */
9442 sigprocmask (SIG_SETMASK
, &initial_mask
, NULL
);
9443 signal (SIGABRT
, term_ntproc
);
9447 /* determine which drives are fixed, for GetCachedVolumeInformation */
9449 /* GetDriveType must have trailing backslash. */
9450 char drive
[] = "A:\\";
9452 /* Loop over all possible drive letters */
9453 while (*drive
<= 'Z')
9455 /* Record if this drive letter refers to a fixed drive. */
9456 fixed_drives
[DRIVE_INDEX (*drive
)] =
9457 (GetDriveType (drive
) == DRIVE_FIXED
);
9462 /* Reset the volume info cache. */
9463 volume_cache
= NULL
;
9468 shutdown_handler ensures that buffers' autosave files are
9469 up to date when the user logs off, or the system shuts down.
9472 shutdown_handler (DWORD type
)
9474 /* Ctrl-C and Ctrl-Break are already suppressed, so don't handle them. */
9475 if (type
== CTRL_CLOSE_EVENT
/* User closes console window. */
9476 || type
== CTRL_LOGOFF_EVENT
/* User logs off. */
9477 || type
== CTRL_SHUTDOWN_EVENT
) /* User shutsdown. */
9479 /* Shut down cleanly, making sure autosave files are up to date. */
9480 shut_down_emacs (0, Qnil
);
9483 /* Allow other handlers to handle this signal. */
9487 /* On Windows 9X, load UNICOWS.DLL and return its handle, or die. On
9488 NT, return a handle to GDI32.DLL. */
9490 maybe_load_unicows_dll (void)
9492 if (os_subtype
== OS_9X
)
9494 HANDLE ret
= LoadLibrary ("Unicows.dll");
9497 /* These two functions are present on Windows 9X as stubs
9498 that always fail. We need the real implementations from
9499 UNICOWS.DLL, so we must call these functions through
9500 pointers, and assign the correct addresses to these
9501 pointers at program startup (see emacs.c, which calls
9502 this function early on). */
9503 pMultiByteToWideChar
=
9504 (MultiByteToWideChar_Proc
)GetProcAddress (ret
, "MultiByteToWideChar");
9505 pWideCharToMultiByte
=
9506 (WideCharToMultiByte_Proc
)GetProcAddress (ret
, "WideCharToMultiByte");
9507 multiByteToWideCharFlags
= MB_ERR_INVALID_CHARS
;
9514 button
= MessageBox (NULL
,
9515 "Emacs cannot load the UNICOWS.DLL library.\n"
9516 "This library is essential for using Emacs\n"
9517 "on this system. You need to install it.\n\n"
9518 "Emacs will exit when you click OK.",
9519 "Emacs cannot load UNICOWS.DLL",
9520 MB_ICONERROR
| MB_TASKMODAL
9521 | MB_SETFOREGROUND
| MB_OK
);
9532 /* On NT family of Windows, these two functions are always
9533 linked in, so we just assign their addresses to the 2
9534 pointers; no need for the LoadLibrary dance. */
9535 pMultiByteToWideChar
= MultiByteToWideChar
;
9536 pWideCharToMultiByte
= WideCharToMultiByte
;
9537 /* On NT 4.0, though, MB_ERR_INVALID_CHARS is not supported. */
9538 if (w32_major_version
< 5)
9539 multiByteToWideCharFlags
= 0;
9541 multiByteToWideCharFlags
= MB_ERR_INVALID_CHARS
;
9542 return LoadLibrary ("Gdi32.dll");
9547 globals_of_w32 is used to initialize those global variables that
9548 must always be initialized on startup even when the global variable
9549 initialized is non zero (see the function main in emacs.c).
9552 globals_of_w32 (void)
9554 HMODULE kernel32
= GetModuleHandle ("kernel32.dll");
9556 get_process_times_fn
= (GetProcessTimes_Proc
)
9557 GetProcAddress (kernel32
, "GetProcessTimes");
9559 DEFSYM (QCloaded_from
, ":loaded-from");
9561 g_b_init_is_windows_9x
= 0;
9562 g_b_init_open_process_token
= 0;
9563 g_b_init_get_token_information
= 0;
9564 g_b_init_lookup_account_sid
= 0;
9565 g_b_init_get_sid_sub_authority
= 0;
9566 g_b_init_get_sid_sub_authority_count
= 0;
9567 g_b_init_get_security_info
= 0;
9568 g_b_init_get_file_security_w
= 0;
9569 g_b_init_get_file_security_a
= 0;
9570 g_b_init_get_security_descriptor_owner
= 0;
9571 g_b_init_get_security_descriptor_group
= 0;
9572 g_b_init_is_valid_sid
= 0;
9573 g_b_init_create_toolhelp32_snapshot
= 0;
9574 g_b_init_process32_first
= 0;
9575 g_b_init_process32_next
= 0;
9576 g_b_init_open_thread_token
= 0;
9577 g_b_init_impersonate_self
= 0;
9578 g_b_init_revert_to_self
= 0;
9579 g_b_init_get_process_memory_info
= 0;
9580 g_b_init_get_process_working_set_size
= 0;
9581 g_b_init_global_memory_status
= 0;
9582 g_b_init_global_memory_status_ex
= 0;
9583 g_b_init_equal_sid
= 0;
9584 g_b_init_copy_sid
= 0;
9585 g_b_init_get_length_sid
= 0;
9586 g_b_init_get_native_system_info
= 0;
9587 g_b_init_get_system_times
= 0;
9588 g_b_init_create_symbolic_link_w
= 0;
9589 g_b_init_create_symbolic_link_a
= 0;
9590 g_b_init_get_security_descriptor_dacl
= 0;
9591 g_b_init_convert_sd_to_sddl
= 0;
9592 g_b_init_convert_sddl_to_sd
= 0;
9593 g_b_init_is_valid_security_descriptor
= 0;
9594 g_b_init_set_file_security_w
= 0;
9595 g_b_init_set_file_security_a
= 0;
9596 g_b_init_set_named_security_info_w
= 0;
9597 g_b_init_set_named_security_info_a
= 0;
9598 g_b_init_get_adapters_info
= 0;
9599 g_b_init_compare_string_w
= 0;
9600 num_of_processors
= 0;
9601 /* The following sets a handler for shutdown notifications for
9602 console apps. This actually applies to Emacs in both console and
9603 GUI modes, since we had to fool windows into thinking emacs is a
9604 console application to get console mode to work. */
9605 SetConsoleCtrlHandler (shutdown_handler
, TRUE
);
9607 /* "None" is the default group name on standalone workstations. */
9608 strcpy (dflt_group_name
, "None");
9610 /* Reset, in case it has some value inherited from dump time. */
9611 w32_stat_get_owner_group
= 0;
9613 /* If w32_unicode_filenames is non-zero, we will be using Unicode
9614 (a.k.a. "wide") APIs to invoke functions that accept file
9616 if (is_windows_9x ())
9617 w32_unicode_filenames
= 0;
9619 w32_unicode_filenames
= 1;
9622 extern void dynlib_reset_last_error (void);
9623 dynlib_reset_last_error ();
9626 w32_crypto_hprov
= (HCRYPTPROV
)0;
9629 /* For make-serial-process */
9631 serial_open (Lisp_Object port_obj
)
9633 char *port
= SSDATA (port_obj
);
9638 hnd
= CreateFile (port
, GENERIC_READ
| GENERIC_WRITE
, 0, 0,
9639 OPEN_EXISTING
, FILE_FLAG_OVERLAPPED
, 0);
9640 if (hnd
== INVALID_HANDLE_VALUE
)
9641 error ("Could not open %s", port
);
9642 fd
= (int) _open_osfhandle ((intptr_t) hnd
, 0);
9644 error ("Could not open %s", port
);
9648 error ("Could not create child process");
9650 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
9651 fd_info
[ fd
].hnd
= hnd
;
9652 fd_info
[ fd
].flags
|=
9653 FILE_READ
| FILE_WRITE
| FILE_BINARY
| FILE_SERIAL
;
9654 if (fd_info
[ fd
].cp
!= NULL
)
9656 error ("fd_info[fd = %d] is already in use", fd
);
9658 fd_info
[ fd
].cp
= cp
;
9659 cp
->ovl_read
.hEvent
= CreateEvent (NULL
, TRUE
, FALSE
, NULL
);
9660 if (cp
->ovl_read
.hEvent
== NULL
)
9661 error ("Could not create read event");
9662 cp
->ovl_write
.hEvent
= CreateEvent (NULL
, TRUE
, FALSE
, NULL
);
9663 if (cp
->ovl_write
.hEvent
== NULL
)
9664 error ("Could not create write event");
9669 /* For serial-process-configure */
9671 serial_configure (struct Lisp_Process
*p
, Lisp_Object contact
)
9673 Lisp_Object childp2
= Qnil
;
9674 Lisp_Object tem
= Qnil
;
9678 char summary
[4] = "???"; /* This usually becomes "8N1". */
9680 if ((fd_info
[ p
->outfd
].flags
& FILE_SERIAL
) == 0)
9681 error ("Not a serial process");
9682 hnd
= fd_info
[ p
->outfd
].hnd
;
9684 childp2
= Fcopy_sequence (p
->childp
);
9686 /* Initialize timeouts for blocking read and blocking write. */
9687 if (!GetCommTimeouts (hnd
, &ct
))
9688 error ("GetCommTimeouts() failed");
9689 ct
.ReadIntervalTimeout
= 0;
9690 ct
.ReadTotalTimeoutMultiplier
= 0;
9691 ct
.ReadTotalTimeoutConstant
= 0;
9692 ct
.WriteTotalTimeoutMultiplier
= 0;
9693 ct
.WriteTotalTimeoutConstant
= 0;
9694 if (!SetCommTimeouts (hnd
, &ct
))
9695 error ("SetCommTimeouts() failed");
9696 /* Read port attributes and prepare default configuration. */
9697 memset (&dcb
, 0, sizeof (dcb
));
9698 dcb
.DCBlength
= sizeof (DCB
);
9699 if (!GetCommState (hnd
, &dcb
))
9700 error ("GetCommState() failed");
9703 dcb
.fAbortOnError
= FALSE
;
9704 /* dcb.XonLim and dcb.XoffLim are set by GetCommState() */
9709 /* Configure speed. */
9710 if (!NILP (Fplist_member (contact
, QCspeed
)))
9711 tem
= Fplist_get (contact
, QCspeed
);
9713 tem
= Fplist_get (p
->childp
, QCspeed
);
9715 dcb
.BaudRate
= XINT (tem
);
9716 childp2
= Fplist_put (childp2
, QCspeed
, tem
);
9718 /* Configure bytesize. */
9719 if (!NILP (Fplist_member (contact
, QCbytesize
)))
9720 tem
= Fplist_get (contact
, QCbytesize
);
9722 tem
= Fplist_get (p
->childp
, QCbytesize
);
9724 tem
= make_number (8);
9726 if (XINT (tem
) != 7 && XINT (tem
) != 8)
9727 error (":bytesize must be nil (8), 7, or 8");
9728 dcb
.ByteSize
= XINT (tem
);
9729 summary
[0] = XINT (tem
) + '0';
9730 childp2
= Fplist_put (childp2
, QCbytesize
, tem
);
9732 /* Configure parity. */
9733 if (!NILP (Fplist_member (contact
, QCparity
)))
9734 tem
= Fplist_get (contact
, QCparity
);
9736 tem
= Fplist_get (p
->childp
, QCparity
);
9737 if (!NILP (tem
) && !EQ (tem
, Qeven
) && !EQ (tem
, Qodd
))
9738 error (":parity must be nil (no parity), `even', or `odd'");
9739 dcb
.fParity
= FALSE
;
9740 dcb
.Parity
= NOPARITY
;
9741 dcb
.fErrorChar
= FALSE
;
9746 else if (EQ (tem
, Qeven
))
9750 dcb
.Parity
= EVENPARITY
;
9751 dcb
.fErrorChar
= TRUE
;
9753 else if (EQ (tem
, Qodd
))
9757 dcb
.Parity
= ODDPARITY
;
9758 dcb
.fErrorChar
= TRUE
;
9760 childp2
= Fplist_put (childp2
, QCparity
, tem
);
9762 /* Configure stopbits. */
9763 if (!NILP (Fplist_member (contact
, QCstopbits
)))
9764 tem
= Fplist_get (contact
, QCstopbits
);
9766 tem
= Fplist_get (p
->childp
, QCstopbits
);
9768 tem
= make_number (1);
9770 if (XINT (tem
) != 1 && XINT (tem
) != 2)
9771 error (":stopbits must be nil (1 stopbit), 1, or 2");
9772 summary
[2] = XINT (tem
) + '0';
9773 if (XINT (tem
) == 1)
9774 dcb
.StopBits
= ONESTOPBIT
;
9775 else if (XINT (tem
) == 2)
9776 dcb
.StopBits
= TWOSTOPBITS
;
9777 childp2
= Fplist_put (childp2
, QCstopbits
, tem
);
9779 /* Configure flowcontrol. */
9780 if (!NILP (Fplist_member (contact
, QCflowcontrol
)))
9781 tem
= Fplist_get (contact
, QCflowcontrol
);
9783 tem
= Fplist_get (p
->childp
, QCflowcontrol
);
9784 if (!NILP (tem
) && !EQ (tem
, Qhw
) && !EQ (tem
, Qsw
))
9785 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
9786 dcb
.fOutxCtsFlow
= FALSE
;
9787 dcb
.fOutxDsrFlow
= FALSE
;
9788 dcb
.fDtrControl
= DTR_CONTROL_DISABLE
;
9789 dcb
.fDsrSensitivity
= FALSE
;
9790 dcb
.fTXContinueOnXoff
= FALSE
;
9793 dcb
.fRtsControl
= RTS_CONTROL_DISABLE
;
9794 dcb
.XonChar
= 17; /* Control-Q */
9795 dcb
.XoffChar
= 19; /* Control-S */
9798 /* Already configured. */
9800 else if (EQ (tem
, Qhw
))
9802 dcb
.fRtsControl
= RTS_CONTROL_HANDSHAKE
;
9803 dcb
.fOutxCtsFlow
= TRUE
;
9805 else if (EQ (tem
, Qsw
))
9810 childp2
= Fplist_put (childp2
, QCflowcontrol
, tem
);
9812 /* Activate configuration. */
9813 if (!SetCommState (hnd
, &dcb
))
9814 error ("SetCommState() failed");
9816 childp2
= Fplist_put (childp2
, QCsummary
, build_string (summary
));
9817 pset_childp (p
, childp2
);
9820 /* For make-pipe-process */
9822 register_aux_fd (int infd
)
9828 error ("Could not create child process");
9830 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
9832 if (fd_info
[ infd
].cp
!= NULL
)
9834 error ("fd_info[fd = %d] is already in use", infd
);
9836 fd_info
[ infd
].cp
= cp
;
9837 fd_info
[ infd
].hnd
= (HANDLE
) _get_osfhandle (infd
);
9843 emacs_gnutls_pull (gnutls_transport_ptr_t p
, void* buf
, size_t sz
)
9846 struct Lisp_Process
*process
= (struct Lisp_Process
*)p
;
9847 int fd
= process
->infd
;
9849 n
= sys_read (fd
, (char*)buf
, sz
);
9856 /* Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
9857 if (err
== EWOULDBLOCK
)
9860 emacs_gnutls_transport_set_errno (process
->gnutls_state
, err
);
9866 emacs_gnutls_push (gnutls_transport_ptr_t p
, const void* buf
, size_t sz
)
9868 struct Lisp_Process
*process
= (struct Lisp_Process
*)p
;
9869 int fd
= process
->outfd
;
9870 ssize_t n
= sys_write (fd
, buf
, sz
);
9872 /* 0 or more bytes written means everything went fine. */
9876 /* Negative bytes written means we got an error in errno.
9877 Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
9878 emacs_gnutls_transport_set_errno (process
->gnutls_state
,
9879 errno
== EWOULDBLOCK
? EAGAIN
: errno
);
9883 #endif /* HAVE_GNUTLS */