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
2777 (listn (CONSTYPE_HEAP
, 2,
2778 intern ("initialization"), build_string
2779 ("Use of `C:\\.emacs' without defining `HOME'\n"
2780 "in the environment is deprecated, "
2781 "see `Windows HOME' in the Emacs manual.")),
2782 Vdelayed_warnings_list
);
2787 char buf1
[SET_ENV_BUF_SIZE
], buf2
[SET_ENV_BUF_SIZE
];
2789 if (dwType
== REG_EXPAND_SZ
)
2790 ExpandEnvironmentStrings ((LPSTR
) lpval
, buf1
, sizeof (buf1
));
2791 else if (dwType
== REG_SZ
)
2792 strcpy (buf1
, lpval
);
2793 if (dwType
== REG_EXPAND_SZ
|| dwType
== REG_SZ
)
2795 _snprintf (buf2
, sizeof (buf2
)-1, "%s=%s", env_vars
[i
].name
,
2797 _putenv (strdup (buf2
));
2807 /* Rebuild system configuration to reflect invoking system. */
2808 Vsystem_configuration
= build_string (EMACS_CONFIGURATION
);
2810 /* Another special case: on NT, the PATH variable is actually named
2811 "Path" although cmd.exe (perhaps NT itself) arranges for
2812 environment variable lookup and setting to be case insensitive.
2813 However, Emacs assumes a fully case sensitive environment, so we
2814 need to change "Path" to "PATH" to match the expectations of
2815 various elisp packages. We do this by the sneaky method of
2816 modifying the string in the C runtime environ entry.
2818 The same applies to COMSPEC. */
2822 for (envp
= environ
; *envp
; envp
++)
2823 if (_strnicmp (*envp
, "PATH=", 5) == 0)
2824 memcpy (*envp
, "PATH=", 5);
2825 else if (_strnicmp (*envp
, "COMSPEC=", 8) == 0)
2826 memcpy (*envp
, "COMSPEC=", 8);
2829 /* Remember the initial working directory for getcwd. */
2830 /* FIXME: Do we need to resolve possible symlinks in startup_dir?
2831 Does it matter anywhere in Emacs? */
2832 if (w32_unicode_filenames
)
2834 wchar_t wstartup_dir
[MAX_PATH
];
2836 if (!GetCurrentDirectoryW (MAX_PATH
, wstartup_dir
))
2838 filename_from_utf16 (wstartup_dir
, startup_dir
);
2842 char astartup_dir
[MAX_PATH
];
2844 if (!GetCurrentDirectoryA (MAX_PATH
, astartup_dir
))
2846 filename_from_ansi (astartup_dir
, startup_dir
);
2850 static char modname
[MAX_PATH
];
2852 if (!GetModuleFileNameA (NULL
, modname
, MAX_PATH
))
2857 /* Determine if there is a middle mouse button, to allow parse_button
2858 to decide whether right mouse events should be mouse-2 or
2860 w32_num_mouse_buttons
= GetSystemMetrics (SM_CMOUSEBUTTONS
);
2865 /* Called from expand-file-name when default-directory is not a string. */
2868 emacs_root_dir (void)
2870 static char root_dir
[MAX_UTF8_PATH
];
2873 p
= getenv ("emacs_dir");
2876 filename_from_ansi (p
, root_dir
);
2877 root_dir
[parse_root (root_dir
, NULL
)] = '\0';
2878 dostounix_filename (root_dir
);
2882 #include <sys/timeb.h>
2884 /* Emulate gettimeofday (Ulrich Leodolter, 1/11/95). */
2886 gettimeofday (struct timeval
*__restrict tv
, struct timezone
*__restrict tz
)
2891 tv
->tv_sec
= tb
.time
;
2892 tv
->tv_usec
= tb
.millitm
* 1000L;
2893 /* Implementation note: _ftime sometimes doesn't update the dstflag
2894 according to the new timezone when the system timezone is
2895 changed. We could fix that by using GetSystemTime and
2896 GetTimeZoneInformation, but that doesn't seem necessary, since
2897 Emacs always calls gettimeofday with the 2nd argument NULL (see
2898 current_emacs_time). */
2901 tz
->tz_minuteswest
= tb
.timezone
; /* minutes west of Greenwich */
2902 tz
->tz_dsttime
= tb
.dstflag
; /* type of dst correction */
2907 /* Emulate fdutimens. */
2909 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2910 TIMESPEC[0] and TIMESPEC[1], respectively.
2911 FD must be either negative -- in which case it is ignored --
2912 or a file descriptor that is open on FILE.
2913 If FD is nonnegative, then FILE can be NULL, which means
2914 use just futimes instead of utimes.
2915 If TIMESPEC is null, FAIL.
2916 Return 0 on success, -1 (setting errno) on failure. */
2919 fdutimens (int fd
, char const *file
, struct timespec
const timespec
[2])
2926 if (fd
< 0 && !file
)
2931 /* _futime's prototype defines 2nd arg as having the type 'struct
2932 _utimbuf', while utime needs to accept 'struct utimbuf' for
2933 compatibility with Posix. So we need to use 2 different (but
2934 equivalent) types to avoid compiler warnings, sigh. */
2937 struct _utimbuf _ut
;
2939 _ut
.actime
= timespec
[0].tv_sec
;
2940 _ut
.modtime
= timespec
[1].tv_sec
;
2941 return _futime (fd
, &_ut
);
2947 ut
.actime
= timespec
[0].tv_sec
;
2948 ut
.modtime
= timespec
[1].tv_sec
;
2949 /* Call 'utime', which is implemented below, not the MS library
2950 function, which fails on directories. */
2951 return utime (file
, &ut
);
2956 /* ------------------------------------------------------------------------- */
2957 /* IO support and wrapper functions for the Windows API. */
2958 /* ------------------------------------------------------------------------- */
2960 /* Place a wrapper around the MSVC version of ctime. It returns NULL
2961 on network directories, so we handle that case here.
2962 (Ulrich Leodolter, 1/11/95). */
2964 sys_ctime (const time_t *t
)
2966 char *str
= (char *) ctime (t
);
2967 return (str
? str
: "Sun Jan 01 00:00:00 1970");
2970 /* Emulate sleep...we could have done this with a define, but that
2971 would necessitate including windows.h in the files that used it.
2972 This is much easier. */
2974 sys_sleep (int seconds
)
2976 Sleep (seconds
* 1000);
2979 /* Internal MSVC functions for low-level descriptor munging */
2980 extern int __cdecl
_set_osfhnd (int fd
, long h
);
2981 extern int __cdecl
_free_osfhnd (int fd
);
2983 /* parallel array of private info on file handles */
2984 filedesc fd_info
[ MAXDESC
];
2986 typedef struct volume_info_data
{
2987 struct volume_info_data
* next
;
2989 /* time when info was obtained */
2992 /* actual volume info */
3001 /* Global referenced by various functions. */
3002 static volume_info_data volume_info
;
3004 /* Vector to indicate which drives are local and fixed (for which cached
3005 data never expires). */
3006 static BOOL fixed_drives
[26];
3008 /* Consider cached volume information to be stale if older than 10s,
3009 at least for non-local drives. Info for fixed drives is never stale. */
3010 #define DRIVE_INDEX( c ) ( (c) <= 'Z' ? (c) - 'A' : (c) - 'a' )
3011 #define VOLINFO_STILL_VALID( root_dir, info ) \
3012 ( ( isalpha (root_dir[0]) && \
3013 fixed_drives[ DRIVE_INDEX (root_dir[0]) ] ) \
3014 || GetTickCount () - info->timestamp < 10000 )
3016 /* Cache support functions. */
3018 /* Simple linked list with linear search is sufficient. */
3019 static volume_info_data
*volume_cache
= NULL
;
3021 static volume_info_data
*
3022 lookup_volume_info (char * root_dir
)
3024 volume_info_data
* info
;
3026 for (info
= volume_cache
; info
; info
= info
->next
)
3027 if (xstrcasecmp (info
->root_dir
, root_dir
) == 0)
3033 add_volume_info (char * root_dir
, volume_info_data
* info
)
3035 info
->root_dir
= xstrdup (root_dir
);
3036 unixtodos_filename (info
->root_dir
);
3037 info
->next
= volume_cache
;
3038 volume_cache
= info
;
3042 /* Wrapper for GetVolumeInformation, which uses caching to avoid
3043 performance penalty (~2ms on 486 for local drives, 7.5ms for local
3044 cdrom drive, ~5-10ms or more for remote drives on LAN). */
3045 static volume_info_data
*
3046 GetCachedVolumeInformation (char * root_dir
)
3048 volume_info_data
* info
;
3049 char default_root
[ MAX_UTF8_PATH
];
3050 char name
[MAX_PATH
+1];
3051 char type
[MAX_PATH
+1];
3053 /* NULL for root_dir means use root from current directory. */
3054 if (root_dir
== NULL
)
3056 if (w32_unicode_filenames
)
3058 wchar_t curdirw
[MAX_PATH
];
3060 if (GetCurrentDirectoryW (MAX_PATH
, curdirw
) == 0)
3062 filename_from_utf16 (curdirw
, default_root
);
3066 char curdira
[MAX_PATH
];
3068 if (GetCurrentDirectoryA (MAX_PATH
, curdira
) == 0)
3070 filename_from_ansi (curdira
, default_root
);
3072 parse_root (default_root
, (const char **)&root_dir
);
3074 root_dir
= default_root
;
3077 /* Local fixed drives can be cached permanently. Removable drives
3078 cannot be cached permanently, since the volume name and serial
3079 number (if nothing else) can change. Remote drives should be
3080 treated as if they are removable, since there is no sure way to
3081 tell whether they are or not. Also, the UNC association of drive
3082 letters mapped to remote volumes can be changed at any time (even
3083 by other processes) without notice.
3085 As a compromise, so we can benefit from caching info for remote
3086 volumes, we use a simple expiry mechanism to invalidate cache
3087 entries that are more than ten seconds old. */
3090 /* No point doing this, because WNetGetConnection is even slower than
3091 GetVolumeInformation, consistently taking ~50ms on a 486 (FWIW,
3092 GetDriveType is about the only call of this type which does not
3093 involve network access, and so is extremely quick). */
3095 /* Map drive letter to UNC if remote. */
3096 if (isalpha (root_dir
[0]) && !fixed
[DRIVE_INDEX (root_dir
[0])])
3098 char remote_name
[ 256 ];
3099 char drive
[3] = { root_dir
[0], ':' };
3101 if (WNetGetConnection (drive
, remote_name
, sizeof (remote_name
))
3103 /* do something */ ;
3107 info
= lookup_volume_info (root_dir
);
3109 if (info
== NULL
|| ! VOLINFO_STILL_VALID (root_dir
, info
))
3115 /* Info is not cached, or is stale. */
3116 if (w32_unicode_filenames
)
3118 wchar_t root_w
[MAX_PATH
];
3119 wchar_t name_w
[MAX_PATH
+1];
3120 wchar_t type_w
[MAX_PATH
+1];
3122 filename_to_utf16 (root_dir
, root_w
);
3123 if (!GetVolumeInformationW (root_w
,
3124 name_w
, sizeof (name_w
),
3128 type_w
, sizeof (type_w
)))
3130 /* Hmm... not really 100% correct, as these 2 are not file
3132 filename_from_utf16 (name_w
, name
);
3133 filename_from_utf16 (type_w
, type
);
3137 char root_a
[MAX_PATH
];
3138 char name_a
[MAX_PATH
+1];
3139 char type_a
[MAX_PATH
+1];
3141 filename_to_ansi (root_dir
, root_a
);
3142 if (!GetVolumeInformationA (root_a
,
3143 name_a
, sizeof (name_a
),
3147 type_a
, sizeof (type_a
)))
3149 filename_from_ansi (name_a
, name
);
3150 filename_from_ansi (type_a
, type
);
3153 /* Cache the volume information for future use, overwriting existing
3154 entry if present. */
3157 info
= xmalloc (sizeof (volume_info_data
));
3158 add_volume_info (root_dir
, info
);
3166 info
->name
= xstrdup (name
);
3167 unixtodos_filename (info
->name
);
3168 info
->serialnum
= serialnum
;
3169 info
->maxcomp
= maxcomp
;
3170 info
->flags
= flags
;
3171 info
->type
= xstrdup (type
);
3172 info
->timestamp
= GetTickCount ();
3178 /* Get information on the volume where NAME is held; set path pointer to
3179 start of pathname in NAME (past UNC header\volume header if present),
3180 if pPath is non-NULL.
3182 Note: if NAME includes symlinks, the information is for the volume
3183 of the symlink, not of its target. That's because, even though
3184 GetVolumeInformation returns information about the symlink target
3185 of its argument, we only pass the root directory to
3186 GetVolumeInformation, not the full NAME. */
3188 get_volume_info (const char * name
, const char ** pPath
)
3190 char temp
[MAX_UTF8_PATH
];
3191 char *rootname
= NULL
; /* default to current volume */
3192 volume_info_data
* info
;
3193 int root_len
= parse_root (name
, pPath
);
3198 /* Copy the root name of the volume, if given. */
3201 strncpy (temp
, name
, root_len
);
3202 temp
[root_len
] = '\0';
3203 unixtodos_filename (temp
);
3207 info
= GetCachedVolumeInformation (rootname
);
3210 /* Set global referenced by other functions. */
3211 volume_info
= *info
;
3217 /* Determine if volume is FAT format (ie. only supports short 8.3
3218 names); also set path pointer to start of pathname in name, if
3219 pPath is non-NULL. */
3221 is_fat_volume (const char * name
, const char ** pPath
)
3223 if (get_volume_info (name
, pPath
))
3224 return (volume_info
.maxcomp
== 12);
3228 /* Convert all slashes in a filename to backslashes, and map filename
3229 to a valid 8.3 name if necessary. The result is a pointer to a
3230 static buffer, so CAVEAT EMPTOR! */
3232 map_w32_filename (const char * name
, const char ** pPath
)
3234 static char shortname
[MAX_UTF8_PATH
];
3235 char * str
= shortname
;
3238 const char * save_name
= name
;
3240 if (strlen (name
) >= sizeof (shortname
))
3242 /* Return a filename which will cause callers to fail. */
3243 strcpy (shortname
, "?");
3247 if (!fatal_error_in_progress
/* disable fancy processing during crash */
3248 && is_fat_volume (name
, (const char **)&path
)) /* truncate to 8.3 */
3250 register int left
= 8; /* maximum number of chars in part */
3251 register int extn
= 0; /* extension added? */
3252 register int dots
= 2; /* maximum number of dots allowed */
3255 *str
++ = *name
++; /* skip past UNC header */
3257 while ((c
= *name
++))
3264 *str
++ = (c
== ':' ? ':' : '\\');
3265 extn
= 0; /* reset extension flags */
3266 dots
= 2; /* max 2 dots */
3267 left
= 8; /* max length 8 for main part */
3272 /* Convert path components of the form .xxx to _xxx,
3273 but leave . and .. as they are. This allows .emacs
3274 to be read as _emacs, for example. */
3278 IS_DIRECTORY_SEP (*name
))
3293 extn
= 1; /* we've got an extension */
3294 left
= 3; /* 3 chars in extension */
3298 /* any embedded dots after the first are converted to _ */
3303 case '#': /* don't lose these, they're important */
3305 str
[-1] = c
; /* replace last character of part */
3308 if ( left
&& 'A' <= c
&& c
<= 'Z' )
3310 *str
++ = tolower (c
); /* map to lower case (looks nicer) */
3312 dots
= 0; /* started a path component */
3321 strcpy (shortname
, name
);
3322 unixtodos_filename (shortname
);
3326 *pPath
= shortname
+ (path
- save_name
);
3332 is_exec (const char * name
)
3334 char * p
= strrchr (name
, '.');
3337 && (xstrcasecmp (p
, ".exe") == 0 ||
3338 xstrcasecmp (p
, ".com") == 0 ||
3339 xstrcasecmp (p
, ".bat") == 0 ||
3340 xstrcasecmp (p
, ".cmd") == 0));
3343 /* Emulate the Unix directory procedures opendir, closedir, and
3344 readdir. We rename them to sys_* names because some versions of
3345 MinGW startup code call opendir and readdir to glob wildcards, and
3346 the code that calls them doesn't grok UTF-8 encoded file names we
3347 produce in dirent->d_name[]. */
3349 struct dirent dir_static
; /* simulated directory contents */
3350 static HANDLE dir_find_handle
= INVALID_HANDLE_VALUE
;
3351 static int dir_is_fat
;
3352 static char dir_pathname
[MAX_UTF8_PATH
];
3353 static WIN32_FIND_DATAW dir_find_data_w
;
3354 static WIN32_FIND_DATAA dir_find_data_a
;
3355 #define DIR_FIND_DATA_W 1
3356 #define DIR_FIND_DATA_A 2
3357 static int last_dir_find_data
= -1;
3359 /* Support shares on a network resource as subdirectories of a read-only
3361 static HANDLE wnet_enum_handle
= INVALID_HANDLE_VALUE
;
3362 static HANDLE
open_unc_volume (const char *);
3363 static void *read_unc_volume (HANDLE
, wchar_t *, char *, int);
3364 static void close_unc_volume (HANDLE
);
3367 sys_opendir (const char *filename
)
3371 /* Opening is done by FindFirstFile. However, a read is inherent to
3372 this operation, so we defer the open until read time. */
3374 if (dir_find_handle
!= INVALID_HANDLE_VALUE
)
3376 if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
3379 /* Note: We don't support traversal of UNC volumes via symlinks.
3380 Doing so would mean punishing 99.99% of use cases by resolving
3381 all the possible symlinks in FILENAME, recursively. */
3382 if (is_unc_volume (filename
))
3384 wnet_enum_handle
= open_unc_volume (filename
);
3385 if (wnet_enum_handle
== INVALID_HANDLE_VALUE
)
3389 if (!(dirp
= (DIR *) malloc (sizeof (DIR))))
3396 strncpy (dir_pathname
, map_w32_filename (filename
, NULL
), MAX_UTF8_PATH
- 1);
3397 dir_pathname
[MAX_UTF8_PATH
- 1] = '\0';
3398 /* Note: We don't support symlinks to file names on FAT volumes.
3399 Doing so would mean punishing 99.99% of use cases by resolving
3400 all the possible symlinks in FILENAME, recursively. */
3401 dir_is_fat
= is_fat_volume (filename
, NULL
);
3407 sys_closedir (DIR *dirp
)
3409 /* If we have a find-handle open, close it. */
3410 if (dir_find_handle
!= INVALID_HANDLE_VALUE
)
3412 FindClose (dir_find_handle
);
3413 dir_find_handle
= INVALID_HANDLE_VALUE
;
3415 else if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
3417 close_unc_volume (wnet_enum_handle
);
3418 wnet_enum_handle
= INVALID_HANDLE_VALUE
;
3420 xfree ((char *) dirp
);
3424 sys_readdir (DIR *dirp
)
3426 int downcase
= !NILP (Vw32_downcase_file_names
);
3428 if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
3430 if (!read_unc_volume (wnet_enum_handle
,
3431 dir_find_data_w
.cFileName
,
3432 dir_find_data_a
.cFileName
,
3436 /* If we aren't dir_finding, do a find-first, otherwise do a find-next. */
3437 else if (dir_find_handle
== INVALID_HANDLE_VALUE
)
3439 char filename
[MAX_UTF8_PATH
];
3441 bool last_slash
= true;
3443 /* Note: We don't need to worry about dir_pathname being longer
3444 than MAX_UTF8_PATH, as sys_opendir already took care of that
3445 when it called map_w32_filename: that function will put a "?"
3446 in its return value in that case, thus failing all the calls
3448 strcpy (filename
, dir_pathname
);
3449 ln
= strlen (filename
);
3450 if (!IS_DIRECTORY_SEP (filename
[ln
- 1]))
3453 /* Note: No need to resolve symlinks in FILENAME, because
3454 FindFirst opens the directory that is the target of a
3456 if (w32_unicode_filenames
)
3458 wchar_t fnw
[MAX_PATH
+ 2];
3460 filename_to_utf16 (filename
, fnw
);
3462 wcscat (fnw
, L
"\\");
3464 dir_find_handle
= FindFirstFileW (fnw
, &dir_find_data_w
);
3468 char fna
[MAX_PATH
+ 2];
3470 filename_to_ansi (filename
, fna
);
3474 /* If FILENAME is not representable by the current ANSI
3475 codepage, we don't want FindFirstFileA to interpret the
3476 '?' characters as a wildcard. */
3477 if (_mbspbrk (fna
, "?"))
3478 dir_find_handle
= INVALID_HANDLE_VALUE
;
3480 dir_find_handle
= FindFirstFileA (fna
, &dir_find_data_a
);
3483 if (dir_find_handle
== INVALID_HANDLE_VALUE
)
3485 /* Any changes in the value of errno here should be in sync
3486 with what directory_files_internal does when it calls
3488 switch (GetLastError ())
3490 /* Windows uses this value when FindFirstFile finds no
3491 files that match the wildcard. This is not supposed
3492 to happen, since our wildcard is "*", but just in
3493 case, if there's some weird empty directory with not
3494 even "." and ".." entries... */
3495 case ERROR_FILE_NOT_FOUND
:
3500 case ERROR_ACCESS_DENIED
:
3501 case ERROR_NETWORK_ACCESS_DENIED
:
3504 case ERROR_PATH_NOT_FOUND
:
3505 case ERROR_INVALID_DRIVE
:
3506 case ERROR_NOT_READY
:
3507 case ERROR_BAD_NETPATH
:
3508 case ERROR_BAD_NET_NAME
:
3515 else if (w32_unicode_filenames
)
3517 if (!FindNextFileW (dir_find_handle
, &dir_find_data_w
))
3525 if (!FindNextFileA (dir_find_handle
, &dir_find_data_a
))
3532 /* Emacs never uses this value, so don't bother making it match
3533 value returned by stat(). */
3534 dir_static
.d_ino
= 1;
3536 if (w32_unicode_filenames
)
3538 if (downcase
|| dir_is_fat
)
3540 wchar_t tem
[MAX_PATH
];
3542 wcscpy (tem
, dir_find_data_w
.cFileName
);
3544 filename_from_utf16 (tem
, dir_static
.d_name
);
3547 filename_from_utf16 (dir_find_data_w
.cFileName
, dir_static
.d_name
);
3548 last_dir_find_data
= DIR_FIND_DATA_W
;
3554 /* If the file name in cFileName[] includes `?' characters, it
3555 means the original file name used characters that cannot be
3556 represented by the current ANSI codepage. To avoid total
3557 lossage, retrieve the short 8+3 alias of the long file
3559 if (_mbspbrk (dir_find_data_a
.cFileName
, "?"))
3561 strcpy (tem
, dir_find_data_a
.cAlternateFileName
);
3562 /* 8+3 aliases are returned in all caps, which could break
3563 various alists that look at filenames' extensions. */
3566 else if (downcase
|| dir_is_fat
)
3567 strcpy (tem
, dir_find_data_a
.cFileName
);
3569 filename_from_ansi (dir_find_data_a
.cFileName
, dir_static
.d_name
);
3570 if (downcase
|| dir_is_fat
)
3573 filename_from_ansi (tem
, dir_static
.d_name
);
3575 last_dir_find_data
= DIR_FIND_DATA_A
;
3578 dir_static
.d_namlen
= strlen (dir_static
.d_name
);
3579 dir_static
.d_reclen
= sizeof (struct dirent
) - MAX_UTF8_PATH
+ 3 +
3580 dir_static
.d_namlen
- dir_static
.d_namlen
% 4;
3586 open_unc_volume (const char *path
)
3588 const char *fn
= map_w32_filename (path
, NULL
);
3592 if (w32_unicode_filenames
)
3595 wchar_t fnw
[MAX_PATH
];
3597 nrw
.dwScope
= RESOURCE_GLOBALNET
;
3598 nrw
.dwType
= RESOURCETYPE_DISK
;
3599 nrw
.dwDisplayType
= RESOURCEDISPLAYTYPE_SERVER
;
3600 nrw
.dwUsage
= RESOURCEUSAGE_CONTAINER
;
3601 nrw
.lpLocalName
= NULL
;
3602 filename_to_utf16 (fn
, fnw
);
3603 nrw
.lpRemoteName
= fnw
;
3604 nrw
.lpComment
= NULL
;
3605 nrw
.lpProvider
= NULL
;
3607 result
= WNetOpenEnumW (RESOURCE_GLOBALNET
, RESOURCETYPE_DISK
,
3608 RESOURCEUSAGE_CONNECTABLE
, &nrw
, &henum
);
3615 nra
.dwScope
= RESOURCE_GLOBALNET
;
3616 nra
.dwType
= RESOURCETYPE_DISK
;
3617 nra
.dwDisplayType
= RESOURCEDISPLAYTYPE_SERVER
;
3618 nra
.dwUsage
= RESOURCEUSAGE_CONTAINER
;
3619 nra
.lpLocalName
= NULL
;
3620 filename_to_ansi (fn
, fna
);
3621 nra
.lpRemoteName
= fna
;
3622 nra
.lpComment
= NULL
;
3623 nra
.lpProvider
= NULL
;
3625 result
= WNetOpenEnumA (RESOURCE_GLOBALNET
, RESOURCETYPE_DISK
,
3626 RESOURCEUSAGE_CONNECTABLE
, &nra
, &henum
);
3628 if (result
== NO_ERROR
)
3632 /* Make sure directory_files_internal reports a sensible error. */
3634 return INVALID_HANDLE_VALUE
;
3639 read_unc_volume (HANDLE henum
, wchar_t *fname_w
, char *fname_a
, int size
)
3644 DWORD bufsize
= 512;
3648 if (w32_unicode_filenames
)
3653 buffer
= alloca (bufsize
);
3654 result
= WNetEnumResourceW (henum
, &count
, buffer
, &bufsize
);
3655 if (result
!= NO_ERROR
)
3657 /* WNetEnumResource returns \\resource\share...skip forward to "share". */
3658 ptrw
= ((LPNETRESOURCEW
) buffer
)->lpRemoteName
;
3660 while (*ptrw
&& *ptrw
!= L
'/' && *ptrw
!= L
'\\') ptrw
++;
3662 wcsncpy (fname_w
, ptrw
, size
);
3667 int dbcs_p
= max_filename_mbslen () > 1;
3670 buffer
= alloca (bufsize
);
3671 result
= WNetEnumResourceA (henum
, &count
, buffer
, &bufsize
);
3672 if (result
!= NO_ERROR
)
3674 ptra
= ((LPNETRESOURCEA
) buffer
)->lpRemoteName
;
3677 while (*ptra
&& !IS_DIRECTORY_SEP (*ptra
)) ptra
++;
3680 while (*ptra
&& !IS_DIRECTORY_SEP (*ptra
))
3681 ptra
= CharNextExA (file_name_codepage
, ptra
, 0);
3684 strncpy (fname_a
, ptra
, size
);
3692 close_unc_volume (HANDLE henum
)
3694 if (henum
!= INVALID_HANDLE_VALUE
)
3695 WNetCloseEnum (henum
);
3699 unc_volume_file_attributes (const char *path
)
3704 henum
= open_unc_volume (path
);
3705 if (henum
== INVALID_HANDLE_VALUE
)
3708 attrs
= FILE_ATTRIBUTE_READONLY
| FILE_ATTRIBUTE_DIRECTORY
;
3710 close_unc_volume (henum
);
3715 /* Ensure a network connection is authenticated. */
3717 logon_network_drive (const char *path
)
3719 char share
[MAX_UTF8_PATH
];
3726 if (IS_DIRECTORY_SEP (path
[0]) && IS_DIRECTORY_SEP (path
[1]))
3727 drvtype
= DRIVE_REMOTE
;
3728 else if (path
[0] == '\0' || path
[1] != ':')
3729 drvtype
= GetDriveType (NULL
);
3736 drvtype
= GetDriveType (drive
);
3739 /* Only logon to networked drives. */
3740 if (drvtype
!= DRIVE_REMOTE
)
3744 strncpy (share
, path
, MAX_UTF8_PATH
);
3745 /* Truncate to just server and share name. */
3746 for (p
= share
+ 2; *p
&& p
< share
+ MAX_UTF8_PATH
; p
++)
3748 if (IS_DIRECTORY_SEP (*p
) && ++n_slashes
> 3)
3755 if (w32_unicode_filenames
)
3757 NETRESOURCEW resourcew
;
3758 wchar_t share_w
[MAX_PATH
];
3760 resourcew
.dwScope
= RESOURCE_GLOBALNET
;
3761 resourcew
.dwType
= RESOURCETYPE_DISK
;
3762 resourcew
.dwDisplayType
= RESOURCEDISPLAYTYPE_SHARE
;
3763 resourcew
.dwUsage
= RESOURCEUSAGE_CONTAINER
;
3764 resourcew
.lpLocalName
= NULL
;
3765 filename_to_utf16 (share
, share_w
);
3766 resourcew
.lpRemoteName
= share_w
;
3767 resourcew
.lpProvider
= NULL
;
3769 val
= WNetAddConnection2W (&resourcew
, NULL
, NULL
, CONNECT_INTERACTIVE
);
3773 NETRESOURCEA resourcea
;
3774 char share_a
[MAX_PATH
];
3776 resourcea
.dwScope
= RESOURCE_GLOBALNET
;
3777 resourcea
.dwType
= RESOURCETYPE_DISK
;
3778 resourcea
.dwDisplayType
= RESOURCEDISPLAYTYPE_SHARE
;
3779 resourcea
.dwUsage
= RESOURCEUSAGE_CONTAINER
;
3780 resourcea
.lpLocalName
= NULL
;
3781 filename_to_ansi (share
, share_a
);
3782 resourcea
.lpRemoteName
= share_a
;
3783 resourcea
.lpProvider
= NULL
;
3785 val
= WNetAddConnection2A (&resourcea
, NULL
, NULL
, CONNECT_INTERACTIVE
);
3791 case ERROR_ALREADY_ASSIGNED
:
3793 case ERROR_ACCESS_DENIED
:
3794 case ERROR_LOGON_FAILURE
:
3800 case ERROR_BAD_NET_NAME
:
3801 case ERROR_NO_NET_OR_BAD_PATH
:
3802 case ERROR_NO_NETWORK
:
3803 case ERROR_CANCELLED
:
3810 /* Emulate faccessat(2). */
3812 faccessat (int dirfd
, const char * path
, int mode
, int flags
)
3816 if (dirfd
!= AT_FDCWD
3817 && !(IS_DIRECTORY_SEP (path
[0])
3818 || IS_DEVICE_SEP (path
[1])))
3824 /* MSVCRT implementation of 'access' doesn't recognize D_OK, and its
3825 newer versions blow up when passed D_OK. */
3826 path
= map_w32_filename (path
, NULL
);
3827 /* If the last element of PATH is a symlink, we need to resolve it
3828 to get the attributes of its target file. Note: any symlinks in
3829 PATH elements other than the last one are transparently resolved
3830 by GetFileAttributes below. */
3831 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) != 0
3832 && (flags
& AT_SYMLINK_NOFOLLOW
) == 0)
3833 path
= chase_symlinks (path
);
3835 if (w32_unicode_filenames
)
3837 wchar_t path_w
[MAX_PATH
];
3839 filename_to_utf16 (path
, path_w
);
3840 attributes
= GetFileAttributesW (path_w
);
3844 char path_a
[MAX_PATH
];
3846 filename_to_ansi (path
, path_a
);
3847 attributes
= GetFileAttributesA (path_a
);
3850 if (attributes
== -1)
3852 DWORD w32err
= GetLastError ();
3856 case ERROR_INVALID_NAME
:
3857 case ERROR_BAD_PATHNAME
:
3858 if (is_unc_volume (path
))
3860 attributes
= unc_volume_file_attributes (path
);
3861 if (attributes
== -1)
3869 case ERROR_FILE_NOT_FOUND
:
3870 case ERROR_BAD_NETPATH
:
3881 if ((mode
& X_OK
) != 0
3882 && !(is_exec (path
) || (attributes
& FILE_ATTRIBUTE_DIRECTORY
) != 0))
3887 if ((mode
& W_OK
) != 0 && (attributes
& FILE_ATTRIBUTE_READONLY
) != 0)
3892 if ((mode
& D_OK
) != 0 && (attributes
& FILE_ATTRIBUTE_DIRECTORY
) == 0)
3900 /* A special test for DIRNAME being a directory accessible by the
3901 current user. This is needed because the security permissions in
3902 directory's ACLs are not visible in the Posix-style mode bits
3903 returned by 'stat' and in attributes returned by GetFileAttributes.
3904 So a directory would seem like it's readable by the current user,
3905 but will in fact error out with EACCES when they actually try. */
3907 w32_accessible_directory_p (const char *dirname
, ptrdiff_t dirlen
)
3909 char pattern
[MAX_UTF8_PATH
];
3910 bool last_slash
= dirlen
> 0 && IS_DIRECTORY_SEP (dirname
[dirlen
- 1]);
3913 /* Network volumes need a different reading method. */
3914 if (is_unc_volume (dirname
))
3916 void *read_result
= NULL
;
3917 wchar_t fnw
[MAX_PATH
];
3920 dh
= open_unc_volume (dirname
);
3921 if (dh
!= INVALID_HANDLE_VALUE
)
3923 read_result
= read_unc_volume (dh
, fnw
, fna
, MAX_PATH
);
3924 close_unc_volume (dh
);
3926 /* Treat empty volumes as accessible. */
3927 return read_result
!= NULL
|| GetLastError () == ERROR_NO_MORE_ITEMS
;
3930 /* Note: map_w32_filename makes sure DIRNAME is not longer than
3932 strcpy (pattern
, map_w32_filename (dirname
, NULL
));
3934 /* Note: No need to resolve symlinks in FILENAME, because FindFirst
3935 opens the directory that is the target of a symlink. */
3936 if (w32_unicode_filenames
)
3938 wchar_t pat_w
[MAX_PATH
+ 2];
3939 WIN32_FIND_DATAW dfd_w
;
3941 filename_to_utf16 (pattern
, pat_w
);
3943 wcscat (pat_w
, L
"\\");
3944 wcscat (pat_w
, L
"*");
3945 dh
= FindFirstFileW (pat_w
, &dfd_w
);
3949 char pat_a
[MAX_PATH
+ 2];
3950 WIN32_FIND_DATAA dfd_a
;
3952 filename_to_ansi (pattern
, pat_a
);
3954 strcpy (pat_a
, "\\");
3955 strcat (pat_a
, "*");
3956 /* In case DIRNAME cannot be expressed in characters from the
3957 current ANSI codepage. */
3958 if (_mbspbrk (pat_a
, "?"))
3959 dh
= INVALID_HANDLE_VALUE
;
3961 dh
= FindFirstFileA (pat_a
, &dfd_a
);
3964 if (dh
== INVALID_HANDLE_VALUE
)
3970 /* A version of 'access' to be used locally with file names in
3971 locale-specific encoding. Does not resolve symlinks and does not
3972 support file names on FAT12 and FAT16 volumes, but that's OK, since
3973 we only invoke this function for files inside the Emacs source or
3974 installation tree, on directories (so any symlinks should have the
3975 directory bit set), and on short file names such as "C:/.emacs". */
3977 sys_access (const char *fname
, int mode
)
3979 char fname_copy
[MAX_PATH
], *p
;
3982 strcpy (fname_copy
, fname
);
3983 /* Do the equivalent of unixtodos_filename. */
3984 for (p
= fname_copy
; *p
; p
= CharNext (p
))
3988 if ((attributes
= GetFileAttributesA (fname_copy
)) == -1)
3990 DWORD w32err
= GetLastError ();
3994 case ERROR_INVALID_NAME
:
3995 case ERROR_BAD_PATHNAME
:
3996 case ERROR_FILE_NOT_FOUND
:
3997 case ERROR_BAD_NETPATH
:
4006 if ((mode
& X_OK
) != 0
4007 && !(is_exec (fname_copy
)
4008 || (attributes
& FILE_ATTRIBUTE_DIRECTORY
) != 0))
4013 if ((mode
& W_OK
) != 0 && (attributes
& FILE_ATTRIBUTE_READONLY
) != 0)
4018 if ((mode
& D_OK
) != 0 && (attributes
& FILE_ATTRIBUTE_DIRECTORY
) == 0)
4026 /* Shadow some MSVC runtime functions to map requests for long filenames
4027 to reasonable short names if necessary. This was originally added to
4028 permit running Emacs on NT 3.1 on a FAT partition, which doesn't support
4032 sys_chdir (const char * path
)
4034 path
= map_w32_filename (path
, NULL
);
4035 if (w32_unicode_filenames
)
4037 wchar_t newdir_w
[MAX_PATH
];
4039 if (filename_to_utf16 (path
, newdir_w
) == 0)
4040 return _wchdir (newdir_w
);
4045 char newdir_a
[MAX_PATH
];
4047 if (filename_to_ansi (path
, newdir_a
) == 0)
4048 return _chdir (newdir_a
);
4054 sys_chmod (const char * path
, int mode
)
4056 path
= chase_symlinks (map_w32_filename (path
, NULL
));
4057 if (w32_unicode_filenames
)
4059 wchar_t path_w
[MAX_PATH
];
4061 filename_to_utf16 (path
, path_w
);
4062 return _wchmod (path_w
, mode
);
4066 char path_a
[MAX_PATH
];
4068 filename_to_ansi (path
, path_a
);
4069 return _chmod (path_a
, mode
);
4074 sys_creat (const char * path
, int mode
)
4076 path
= map_w32_filename (path
, NULL
);
4077 if (w32_unicode_filenames
)
4079 wchar_t path_w
[MAX_PATH
];
4081 filename_to_utf16 (path
, path_w
);
4082 return _wcreat (path_w
, mode
);
4086 char path_a
[MAX_PATH
];
4088 filename_to_ansi (path
, path_a
);
4089 return _creat (path_a
, mode
);
4094 sys_fopen (const char * path
, const char * mode
)
4098 const char * mode_save
= mode
;
4100 /* Force all file handles to be non-inheritable. This is necessary to
4101 ensure child processes don't unwittingly inherit handles that might
4102 prevent future file access. */
4106 else if (mode
[0] == 'w' || mode
[0] == 'a')
4107 oflag
= O_WRONLY
| O_CREAT
| O_TRUNC
;
4111 /* Only do simplistic option parsing. */
4115 oflag
&= ~(O_RDONLY
| O_WRONLY
);
4118 else if (mode
[0] == 'b')
4123 else if (mode
[0] == 't')
4130 path
= map_w32_filename (path
, NULL
);
4131 if (w32_unicode_filenames
)
4133 wchar_t path_w
[MAX_PATH
];
4135 filename_to_utf16 (path
, path_w
);
4136 fd
= _wopen (path_w
, oflag
| _O_NOINHERIT
, 0644);
4140 char path_a
[MAX_PATH
];
4142 filename_to_ansi (path
, path_a
);
4143 fd
= _open (path_a
, oflag
| _O_NOINHERIT
, 0644);
4148 return _fdopen (fd
, mode_save
);
4151 /* This only works on NTFS volumes, but is useful to have. */
4153 sys_link (const char * old
, const char * new)
4157 char oldname
[MAX_UTF8_PATH
], newname
[MAX_UTF8_PATH
];
4158 wchar_t oldname_w
[MAX_PATH
];
4159 char oldname_a
[MAX_PATH
];
4161 if (old
== NULL
|| new == NULL
)
4167 strcpy (oldname
, map_w32_filename (old
, NULL
));
4168 strcpy (newname
, map_w32_filename (new, NULL
));
4170 if (w32_unicode_filenames
)
4172 filename_to_utf16 (oldname
, oldname_w
);
4173 fileh
= CreateFileW (oldname_w
, 0, 0, NULL
, OPEN_EXISTING
,
4174 FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
4178 filename_to_ansi (oldname
, oldname_a
);
4179 fileh
= CreateFileA (oldname_a
, 0, 0, NULL
, OPEN_EXISTING
,
4180 FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
4182 if (fileh
!= INVALID_HANDLE_VALUE
)
4186 /* Confusingly, the "alternate" stream name field does not apply
4187 when restoring a hard link, and instead contains the actual
4188 stream data for the link (ie. the name of the link to create).
4189 The WIN32_STREAM_ID structure before the cStreamName field is
4190 the stream header, which is then immediately followed by the
4194 WIN32_STREAM_ID wid
;
4195 WCHAR wbuffer
[MAX_PATH
]; /* extra space for link name */
4198 /* We used to pass MB_PRECOMPOSED as the 2nd arg here, but MSDN
4199 indicates that flag is unsupported for CP_UTF8, and OTOH says
4200 it is the default anyway. */
4201 wlen
= pMultiByteToWideChar (CP_UTF8
, 0, newname
, -1,
4202 data
.wid
.cStreamName
, MAX_PATH
);
4205 LPVOID context
= NULL
;
4208 data
.wid
.dwStreamId
= BACKUP_LINK
;
4209 data
.wid
.dwStreamAttributes
= 0;
4210 data
.wid
.Size
.LowPart
= wlen
* sizeof (WCHAR
);
4211 data
.wid
.Size
.HighPart
= 0;
4212 data
.wid
.dwStreamNameSize
= 0;
4214 if (BackupWrite (fileh
, (LPBYTE
)&data
,
4215 offsetof (WIN32_STREAM_ID
, cStreamName
)
4216 + data
.wid
.Size
.LowPart
,
4217 &wbytes
, FALSE
, FALSE
, &context
)
4218 && BackupWrite (fileh
, NULL
, 0, &wbytes
, TRUE
, FALSE
, &context
))
4225 DWORD err
= GetLastError ();
4230 case ERROR_ACCESS_DENIED
:
4231 /* This is what happens when OLDNAME is a directory,
4232 since Windows doesn't support hard links to
4233 directories. Posix says to set errno to EPERM in
4235 if (w32_unicode_filenames
)
4236 attributes
= GetFileAttributesW (oldname_w
);
4238 attributes
= GetFileAttributesA (oldname_a
);
4239 if (attributes
!= -1
4240 && (attributes
& FILE_ATTRIBUTE_DIRECTORY
) != 0)
4242 else if (attributes
== -1
4243 && is_unc_volume (oldname
)
4244 && unc_volume_file_attributes (oldname
) != -1)
4249 case ERROR_TOO_MANY_LINKS
:
4252 case ERROR_NOT_SAME_DEVICE
:
4262 CloseHandle (fileh
);
4271 sys_mkdir (const char * path
)
4273 path
= map_w32_filename (path
, NULL
);
4275 if (w32_unicode_filenames
)
4277 wchar_t path_w
[MAX_PATH
];
4279 filename_to_utf16 (path
, path_w
);
4280 return _wmkdir (path_w
);
4284 char path_a
[MAX_PATH
];
4286 filename_to_ansi (path
, path_a
);
4287 return _mkdir (path_a
);
4292 sys_open (const char * path
, int oflag
, int mode
)
4294 const char* mpath
= map_w32_filename (path
, NULL
);
4297 if (w32_unicode_filenames
)
4299 wchar_t mpath_w
[MAX_PATH
];
4301 filename_to_utf16 (mpath
, mpath_w
);
4302 /* If possible, try to open file without _O_CREAT, to be able to
4303 write to existing hidden and system files. Force all file
4304 handles to be non-inheritable. */
4305 if ((oflag
& (_O_CREAT
| _O_EXCL
)) != (_O_CREAT
| _O_EXCL
))
4306 res
= _wopen (mpath_w
, (oflag
& ~_O_CREAT
) | _O_NOINHERIT
, mode
);
4308 res
= _wopen (mpath_w
, oflag
| _O_NOINHERIT
, mode
);
4312 char mpath_a
[MAX_PATH
];
4314 filename_to_ansi (mpath
, mpath_a
);
4315 if ((oflag
& (_O_CREAT
| _O_EXCL
)) != (_O_CREAT
| _O_EXCL
))
4316 res
= _open (mpath_a
, (oflag
& ~_O_CREAT
) | _O_NOINHERIT
, mode
);
4318 res
= _open (mpath_a
, oflag
| _O_NOINHERIT
, mode
);
4324 /* Implementation of mkostemp for MS-Windows, to avoid race conditions
4327 Standard algorithm for generating a temporary file name seems to be
4328 use pid or tid with a letter on the front (in place of the 6 X's)
4329 and cycle through the letters to find a unique name. We extend
4330 that to allow any reasonable character as the first of the 6 X's,
4331 so that the number of simultaneously used temporary files will be
4335 mkostemp (char * template, int flags
)
4339 unsigned uid
= GetCurrentThreadId ();
4340 int save_errno
= errno
;
4341 static char first_char
[] = "abcdefghijklmnopqrstuvwyz0123456789!%-_@#";
4344 if (template == NULL
)
4347 p
= template + strlen (template);
4349 /* replace up to the last 5 X's with uid in decimal */
4350 while (--p
>= template && p
[0] == 'X' && --i
>= 0)
4352 p
[0] = '0' + uid
% 10;
4356 if (i
< 0 && p
[0] == 'X')
4361 p
[0] = first_char
[i
];
4362 if ((fd
= sys_open (template,
4363 flags
| _O_CREAT
| _O_EXCL
| _O_RDWR
,
4364 S_IRUSR
| S_IWUSR
)) >= 0
4372 while (++i
< sizeof (first_char
));
4375 /* Template is badly formed or else we can't generate a unique name. */
4380 fchmod (int fd
, mode_t mode
)
4386 sys_rename_replace (const char *oldname
, const char *newname
, BOOL force
)
4389 char temp
[MAX_UTF8_PATH
], temp_a
[MAX_PATH
];;
4392 bool have_temp_a
= false;
4394 /* MoveFile on Windows 95 doesn't correctly change the short file name
4395 alias in a number of circumstances (it is not easy to predict when
4396 just by looking at oldname and newname, unfortunately). In these
4397 cases, renaming through a temporary name avoids the problem.
4399 A second problem on Windows 95 is that renaming through a temp name when
4400 newname is uppercase fails (the final long name ends up in
4401 lowercase, although the short alias might be uppercase) UNLESS the
4402 long temp name is not 8.3.
4404 So, on Windows 95 we always rename through a temp name, and we make sure
4405 the temp name has a long extension to ensure correct renaming. */
4407 strcpy (temp
, map_w32_filename (oldname
, NULL
));
4409 /* volume_info is set indirectly by map_w32_filename. */
4410 oldname_dev
= volume_info
.serialnum
;
4412 if (os_subtype
== OS_9X
)
4417 char oldname_a
[MAX_PATH
];
4419 oldname
= map_w32_filename (oldname
, NULL
);
4420 filename_to_ansi (oldname
, oldname_a
);
4421 filename_to_ansi (temp
, temp_a
);
4422 if ((o
= strrchr (oldname_a
, '\\')))
4425 o
= (char *) oldname_a
;
4427 if ((p
= strrchr (temp_a
, '\\')))
4434 /* Force temp name to require a manufactured 8.3 alias - this
4435 seems to make the second rename work properly. */
4436 sprintf (p
, "_.%s.%u", o
, i
);
4438 result
= rename (oldname_a
, temp_a
);
4440 /* This loop must surely terminate! */
4441 while (result
< 0 && errno
== EEXIST
);
4447 /* If FORCE, emulate Unix behavior - newname is deleted if it already exists
4448 (at least if it is a file; don't do this for directories).
4450 Since we mustn't do this if we are just changing the case of the
4451 file name (we would end up deleting the file we are trying to
4452 rename!), we let rename detect if the destination file already
4453 exists - that way we avoid the possible pitfalls of trying to
4454 determine ourselves whether two names really refer to the same
4455 file, which is not always possible in the general case. (Consider
4456 all the permutations of shared or subst'd drives, etc.) */
4458 newname
= map_w32_filename (newname
, NULL
);
4460 /* volume_info is set indirectly by map_w32_filename. */
4461 newname_dev
= volume_info
.serialnum
;
4463 if (w32_unicode_filenames
)
4465 wchar_t temp_w
[MAX_PATH
], newname_w
[MAX_PATH
];
4467 filename_to_utf16 (temp
, temp_w
);
4468 filename_to_utf16 (newname
, newname_w
);
4469 result
= _wrename (temp_w
, newname_w
);
4470 if (result
< 0 && force
)
4472 DWORD w32err
= GetLastError ();
4475 && newname_dev
!= oldname_dev
)
4477 /* The implementation of `rename' on Windows does not return
4478 errno = EXDEV when you are moving a directory to a
4479 different storage device (ex. logical disk). It returns
4480 EACCES instead. So here we handle such situations and
4484 if ((attributes
= GetFileAttributesW (temp_w
)) != -1
4485 && (attributes
& FILE_ATTRIBUTE_DIRECTORY
))
4488 else if (errno
== EEXIST
)
4490 if (_wchmod (newname_w
, 0666) != 0)
4492 if (_wunlink (newname_w
) != 0)
4494 result
= _wrename (temp_w
, newname_w
);
4496 else if (w32err
== ERROR_PRIVILEGE_NOT_HELD
4497 && is_symlink (temp
))
4499 /* This is Windows prohibiting the user from creating a
4500 symlink in another place, since that requires
4508 char newname_a
[MAX_PATH
];
4511 filename_to_ansi (temp
, temp_a
);
4512 filename_to_ansi (newname
, newname_a
);
4513 result
= rename (temp_a
, newname_a
);
4514 if (result
< 0 && force
)
4516 DWORD w32err
= GetLastError ();
4519 && newname_dev
!= oldname_dev
)
4523 if ((attributes
= GetFileAttributesA (temp_a
)) != -1
4524 && (attributes
& FILE_ATTRIBUTE_DIRECTORY
))
4527 else if (errno
== EEXIST
)
4529 if (_chmod (newname_a
, 0666) != 0)
4531 if (_unlink (newname_a
) != 0)
4533 result
= rename (temp_a
, newname_a
);
4535 else if (w32err
== ERROR_PRIVILEGE_NOT_HELD
4536 && is_symlink (temp
))
4545 sys_rename (char const *old
, char const *new)
4547 return sys_rename_replace (old
, new, TRUE
);
4551 sys_rmdir (const char * path
)
4553 path
= map_w32_filename (path
, NULL
);
4555 if (w32_unicode_filenames
)
4557 wchar_t path_w
[MAX_PATH
];
4559 filename_to_utf16 (path
, path_w
);
4560 return _wrmdir (path_w
);
4564 char path_a
[MAX_PATH
];
4566 filename_to_ansi (path
, path_a
);
4567 return _rmdir (path_a
);
4572 sys_unlink (const char * path
)
4576 path
= map_w32_filename (path
, NULL
);
4578 if (w32_unicode_filenames
)
4580 wchar_t path_w
[MAX_PATH
];
4582 filename_to_utf16 (path
, path_w
);
4583 /* On Unix, unlink works without write permission. */
4584 _wchmod (path_w
, 0666);
4585 rmstatus
= _wunlink (path_w
);
4587 /* Symlinks to directories can only be deleted by _rmdir;
4588 _unlink returns EACCES. */
4591 && (is_symlink (path
) & FILE_ATTRIBUTE_DIRECTORY
) != 0)
4592 rmstatus
= _wrmdir (path_w
);
4598 char path_a
[MAX_PATH
];
4600 filename_to_ansi (path
, path_a
);
4601 _chmod (path_a
, 0666);
4602 rmstatus
= _unlink (path_a
);
4606 && (is_symlink (path
) & FILE_ATTRIBUTE_DIRECTORY
) != 0)
4607 rmstatus
= _rmdir (path_a
);
4615 static FILETIME utc_base_ft
;
4616 static ULONGLONG utc_base
; /* In 100ns units */
4617 static int init
= 0;
4619 #define FILETIME_TO_U64(result, ft) \
4621 ULARGE_INTEGER uiTemp; \
4622 uiTemp.LowPart = (ft).dwLowDateTime; \
4623 uiTemp.HighPart = (ft).dwHighDateTime; \
4624 result = uiTemp.QuadPart; \
4628 initialize_utc_base (void)
4630 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
4639 st
.wMilliseconds
= 0;
4641 SystemTimeToFileTime (&st
, &utc_base_ft
);
4642 FILETIME_TO_U64 (utc_base
, utc_base_ft
);
4646 convert_time (FILETIME ft
)
4652 initialize_utc_base ();
4656 if (CompareFileTime (&ft
, &utc_base_ft
) < 0)
4659 FILETIME_TO_U64 (tmp
, ft
);
4660 return (time_t) ((tmp
- utc_base
) / 10000000L);
4664 convert_from_time_t (time_t time
, FILETIME
* pft
)
4670 initialize_utc_base ();
4674 /* time in 100ns units since 1-Jan-1601 */
4675 tmp
.QuadPart
= (ULONGLONG
) time
* 10000000L + utc_base
;
4676 pft
->dwHighDateTime
= tmp
.HighPart
;
4677 pft
->dwLowDateTime
= tmp
.LowPart
;
4680 static PSECURITY_DESCRIPTOR
4681 get_file_security_desc_by_handle (HANDLE h
)
4683 PSECURITY_DESCRIPTOR psd
= NULL
;
4685 SECURITY_INFORMATION si
= OWNER_SECURITY_INFORMATION
4686 | GROUP_SECURITY_INFORMATION
/* | DACL_SECURITY_INFORMATION */ ;
4688 err
= get_security_info (h
, SE_FILE_OBJECT
, si
,
4689 NULL
, NULL
, NULL
, NULL
, &psd
);
4690 if (err
!= ERROR_SUCCESS
)
4696 static PSECURITY_DESCRIPTOR
4697 get_file_security_desc_by_name (const char *fname
)
4699 PSECURITY_DESCRIPTOR psd
= NULL
;
4701 SECURITY_INFORMATION si
= OWNER_SECURITY_INFORMATION
4702 | GROUP_SECURITY_INFORMATION
/* | DACL_SECURITY_INFORMATION */ ;
4704 if (!get_file_security (fname
, si
, psd
, 0, &sd_len
))
4706 err
= GetLastError ();
4707 if (err
!= ERROR_INSUFFICIENT_BUFFER
)
4711 psd
= xmalloc (sd_len
);
4712 if (!get_file_security (fname
, si
, psd
, sd_len
, &sd_len
))
4724 unsigned n_subauthorities
;
4726 /* Use the last sub-authority value of the RID, the relative
4727 portion of the SID, as user/group ID. */
4728 n_subauthorities
= *get_sid_sub_authority_count (sid
);
4729 if (n_subauthorities
< 1)
4730 return 0; /* the "World" RID */
4731 return *get_sid_sub_authority (sid
, n_subauthorities
- 1);
4734 /* Caching SID and account values for faster lokup. */
4738 struct w32_id
*next
;
4740 unsigned char sid
[FLEXIBLE_ARRAY_MEMBER
];
4743 static struct w32_id
*w32_idlist
;
4746 w32_cached_id (PSID sid
, unsigned *id
, char *name
)
4748 struct w32_id
*tail
, *found
;
4750 for (found
= NULL
, tail
= w32_idlist
; tail
; tail
= tail
->next
)
4752 if (equal_sid ((PSID
)tail
->sid
, sid
))
4761 strcpy (name
, found
->name
);
4769 w32_add_to_cache (PSID sid
, unsigned id
, char *name
)
4772 struct w32_id
*new_entry
;
4774 /* We don't want to leave behind stale cache from when Emacs was
4778 sid_len
= get_length_sid (sid
);
4779 new_entry
= xmalloc (offsetof (struct w32_id
, sid
) + sid_len
);
4782 new_entry
->rid
= id
;
4783 strcpy (new_entry
->name
, name
);
4784 copy_sid (sid_len
, (PSID
)new_entry
->sid
, sid
);
4785 new_entry
->next
= w32_idlist
;
4786 w32_idlist
= new_entry
;
4795 get_name_and_id (PSECURITY_DESCRIPTOR psd
, unsigned *id
, char *nm
, int what
)
4799 SID_NAME_USE ignore
;
4801 DWORD name_len
= sizeof (name
);
4803 DWORD domain_len
= sizeof (domain
);
4808 result
= get_security_descriptor_owner (psd
, &sid
, &dflt
);
4809 else if (what
== GID
)
4810 result
= get_security_descriptor_group (psd
, &sid
, &dflt
);
4814 if (!result
|| !is_valid_sid (sid
))
4816 else if (!w32_cached_id (sid
, id
, nm
))
4818 if (!lookup_account_sid (NULL
, sid
, name
, &name_len
,
4819 domain
, &domain_len
, &ignore
)
4820 || name_len
> UNLEN
+1)
4824 *id
= get_rid (sid
);
4826 w32_add_to_cache (sid
, *id
, name
);
4833 get_file_owner_and_group (PSECURITY_DESCRIPTOR psd
, struct stat
*st
)
4835 int dflt_usr
= 0, dflt_grp
= 0;
4844 if (get_name_and_id (psd
, &st
->st_uid
, st
->st_uname
, UID
))
4846 if (get_name_and_id (psd
, &st
->st_gid
, st
->st_gname
, GID
))
4849 /* Consider files to belong to current user/group, if we cannot get
4850 more accurate information. */
4853 st
->st_uid
= dflt_passwd
.pw_uid
;
4854 strcpy (st
->st_uname
, dflt_passwd
.pw_name
);
4858 st
->st_gid
= dflt_passwd
.pw_gid
;
4859 strcpy (st
->st_gname
, dflt_group
.gr_name
);
4863 /* Return non-zero if NAME is a potentially slow filesystem. */
4865 is_slow_fs (const char *name
)
4870 if (IS_DIRECTORY_SEP (name
[0]) && IS_DIRECTORY_SEP (name
[1]))
4871 devtype
= DRIVE_REMOTE
; /* assume UNC name is remote */
4872 else if (!(strlen (name
) >= 2 && IS_DEVICE_SEP (name
[1])))
4873 devtype
= GetDriveType (NULL
); /* use root of current drive */
4876 /* GetDriveType needs the root directory of the drive. */
4877 strncpy (drive_root
, name
, 2);
4878 drive_root
[2] = '\\';
4879 drive_root
[3] = '\0';
4880 devtype
= GetDriveType (drive_root
);
4882 return !(devtype
== DRIVE_FIXED
|| devtype
== DRIVE_RAMDISK
);
4885 /* If this is non-zero, the caller wants accurate information about
4886 file's owner and group, which could be expensive to get. dired.c
4887 uses this flag when needed for the job at hand. */
4888 int w32_stat_get_owner_group
;
4890 /* MSVC stat function can't cope with UNC names and has other bugs, so
4891 replace it with our own. This also allows us to calculate consistent
4892 inode values and owner/group without hacks in the main Emacs code,
4893 and support file names encoded in UTF-8. */
4896 stat_worker (const char * path
, struct stat
* buf
, int follow_symlinks
)
4898 char *name
, *save_name
, *r
;
4899 WIN32_FIND_DATAW wfd_w
;
4900 WIN32_FIND_DATAA wfd_a
;
4902 unsigned __int64 fake_inode
= 0;
4905 int rootdir
= FALSE
;
4906 PSECURITY_DESCRIPTOR psd
= NULL
;
4907 int is_a_symlink
= 0;
4908 DWORD file_flags
= FILE_FLAG_BACKUP_SEMANTICS
;
4909 DWORD access_rights
= 0;
4910 DWORD fattrs
= 0, serialnum
= 0, fs_high
= 0, fs_low
= 0, nlinks
= 1;
4911 FILETIME ctime
, atime
, wtime
;
4912 wchar_t name_w
[MAX_PATH
];
4913 char name_a
[MAX_PATH
];
4915 if (path
== NULL
|| buf
== NULL
)
4921 save_name
= name
= (char *) map_w32_filename (path
, &path
);
4922 /* Must be valid filename, no wild cards or other invalid
4924 if (strpbrk (name
, "*?|<>\""))
4930 len
= strlen (name
);
4931 /* Allocate 1 extra byte so that we could append a slash to a root
4932 directory, down below. */
4933 name
= strcpy (alloca (len
+ 2), name
);
4935 /* Avoid a somewhat costly call to is_symlink if the filesystem
4936 doesn't support symlinks. */
4937 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) != 0)
4938 is_a_symlink
= is_symlink (name
);
4940 /* Plan A: Open the file and get all the necessary information via
4941 the resulting handle. This solves several issues in one blow:
4943 . retrieves attributes for the target of a symlink, if needed
4944 . gets attributes of root directories and symlinks pointing to
4945 root directories, thus avoiding the need for special-casing
4946 these and detecting them by examining the file-name format
4947 . retrieves more accurate attributes (e.g., non-zero size for
4948 some directories, esp. directories that are junction points)
4949 . correctly resolves "c:/..", "/.." and similar file names
4950 . avoids run-time penalties for 99% of use cases
4952 Plan A is always tried first, unless the user asked not to (but
4953 if the file is a symlink and we need to follow links, we try Plan
4954 A even if the user asked not to).
4956 If Plan A fails, we go to Plan B (below), where various
4957 potentially expensive techniques must be used to handle "special"
4958 files such as UNC volumes etc. */
4959 if (!(NILP (Vw32_get_true_file_attributes
)
4960 || (EQ (Vw32_get_true_file_attributes
, Qlocal
) && is_slow_fs (name
)))
4961 /* Following symlinks requires getting the info by handle. */
4962 || (is_a_symlink
&& follow_symlinks
))
4964 BY_HANDLE_FILE_INFORMATION info
;
4966 if (is_a_symlink
&& !follow_symlinks
)
4967 file_flags
|= FILE_FLAG_OPEN_REPARSE_POINT
;
4968 /* READ_CONTROL access rights are required to get security info
4969 by handle. But if the OS doesn't support security in the
4970 first place, we don't need to try. */
4971 if (is_windows_9x () != TRUE
)
4972 access_rights
|= READ_CONTROL
;
4974 if (w32_unicode_filenames
)
4976 filename_to_utf16 (name
, name_w
);
4977 fh
= CreateFileW (name_w
, access_rights
, 0, NULL
, OPEN_EXISTING
,
4979 /* If CreateFile fails with READ_CONTROL, try again with
4980 zero as access rights. */
4981 if (fh
== INVALID_HANDLE_VALUE
&& access_rights
)
4982 fh
= CreateFileW (name_w
, 0, 0, NULL
, OPEN_EXISTING
,
4987 filename_to_ansi (name
, name_a
);
4988 fh
= CreateFileA (name_a
, access_rights
, 0, NULL
, OPEN_EXISTING
,
4990 if (fh
== INVALID_HANDLE_VALUE
&& access_rights
)
4991 fh
= CreateFileA (name_a
, 0, 0, NULL
, OPEN_EXISTING
,
4994 if (fh
== INVALID_HANDLE_VALUE
)
4995 goto no_true_file_attributes
;
4997 /* This is more accurate in terms of getting the correct number
4998 of links, but is quite slow (it is noticeable when Emacs is
4999 making a list of file name completions). */
5000 if (GetFileInformationByHandle (fh
, &info
))
5002 nlinks
= info
.nNumberOfLinks
;
5003 /* Might as well use file index to fake inode values, but this
5004 is not guaranteed to be unique unless we keep a handle open
5005 all the time (even then there are situations where it is
5006 not unique). Reputedly, there are at most 48 bits of info
5007 (on NTFS, presumably less on FAT). */
5008 fake_inode
= info
.nFileIndexHigh
;
5010 fake_inode
+= info
.nFileIndexLow
;
5011 serialnum
= info
.dwVolumeSerialNumber
;
5012 fs_high
= info
.nFileSizeHigh
;
5013 fs_low
= info
.nFileSizeLow
;
5014 ctime
= info
.ftCreationTime
;
5015 atime
= info
.ftLastAccessTime
;
5016 wtime
= info
.ftLastWriteTime
;
5017 fattrs
= info
.dwFileAttributes
;
5021 /* We don't go to Plan B here, because it's not clear that
5022 it's a good idea. The only known use case where
5023 CreateFile succeeds, but GetFileInformationByHandle fails
5024 (with ERROR_INVALID_FUNCTION) is for character devices
5025 such as NUL, PRN, etc. For these, switching to Plan B is
5026 a net loss, because we lose the character device
5027 attribute returned by GetFileType below (FindFirstFile
5028 doesn't set that bit in the attributes), and the other
5029 fields don't make sense for character devices anyway.
5030 Emacs doesn't really care for non-file entities in the
5031 context of l?stat, so neither do we. */
5033 /* w32err is assigned so one could put a breakpoint here and
5034 examine its value, when GetFileInformationByHandle
5036 DWORD w32err
= GetLastError ();
5040 case ERROR_FILE_NOT_FOUND
: /* can this ever happen? */
5046 /* Test for a symlink before testing for a directory, since
5047 symlinks to directories have the directory bit set, but we
5048 don't want them to appear as directories. */
5049 if (is_a_symlink
&& !follow_symlinks
)
5050 buf
->st_mode
= S_IFLNK
;
5051 else if (fattrs
& FILE_ATTRIBUTE_DIRECTORY
)
5052 buf
->st_mode
= S_IFDIR
;
5055 DWORD ftype
= GetFileType (fh
);
5059 case FILE_TYPE_DISK
:
5060 buf
->st_mode
= S_IFREG
;
5062 case FILE_TYPE_PIPE
:
5063 buf
->st_mode
= S_IFIFO
;
5065 case FILE_TYPE_CHAR
:
5066 case FILE_TYPE_UNKNOWN
:
5068 buf
->st_mode
= S_IFCHR
;
5071 /* We produce the fallback owner and group data, based on the
5072 current user that runs Emacs, in the following cases:
5074 . caller didn't request owner and group info
5075 . this is Windows 9X
5076 . getting security by handle failed, and we need to produce
5077 information for the target of a symlink (this is better
5078 than producing a potentially misleading info about the
5081 If getting security by handle fails, and we don't need to
5082 resolve symlinks, we try getting security by name. */
5083 if (!w32_stat_get_owner_group
|| is_windows_9x () == TRUE
)
5084 get_file_owner_and_group (NULL
, buf
);
5087 psd
= get_file_security_desc_by_handle (fh
);
5090 get_file_owner_and_group (psd
, buf
);
5093 else if (!(is_a_symlink
&& follow_symlinks
))
5095 psd
= get_file_security_desc_by_name (name
);
5096 get_file_owner_and_group (psd
, buf
);
5100 get_file_owner_and_group (NULL
, buf
);
5106 no_true_file_attributes
:
5107 /* Plan B: Either getting a handle on the file failed, or the
5108 caller explicitly asked us to not bother making this
5109 information more accurate.
5111 Implementation note: In Plan B, we never bother to resolve
5112 symlinks, even if we got here because we tried Plan A and
5113 failed. That's because, even if the caller asked for extra
5114 precision by setting Vw32_get_true_file_attributes to t,
5115 resolving symlinks requires acquiring a file handle to the
5116 symlink, which we already know will fail. And if the user
5117 did not ask for extra precision, resolving symlinks will fly
5118 in the face of that request, since the user then wants the
5119 lightweight version of the code. */
5120 rootdir
= (path
>= save_name
+ len
- 1
5121 && (IS_DIRECTORY_SEP (*path
) || *path
== 0));
5123 /* If name is "c:/.." or "/.." then stat "c:/" or "/". */
5124 r
= IS_DEVICE_SEP (name
[1]) ? &name
[2] : name
;
5125 if (IS_DIRECTORY_SEP (r
[0])
5126 && r
[1] == '.' && r
[2] == '.' && r
[3] == '\0')
5129 /* Note: If NAME is a symlink to the root of a UNC volume
5130 (i.e. "\\SERVER"), we will not detect that here, and we will
5131 return data about the symlink as result of FindFirst below.
5132 This is unfortunate, but that marginal use case does not
5133 justify a call to chase_symlinks which would impose a penalty
5134 on all the other use cases. (We get here for symlinks to
5135 roots of UNC volumes because CreateFile above fails for them,
5136 unlike with symlinks to root directories X:\ of drives.) */
5137 if (is_unc_volume (name
))
5139 fattrs
= unc_volume_file_attributes (name
);
5143 ctime
= atime
= wtime
= utc_base_ft
;
5147 /* Make sure root directories end in a slash. */
5148 if (!IS_DIRECTORY_SEP (name
[len
-1]))
5149 strcpy (name
+ len
, "\\");
5150 if (GetDriveType (name
) < 2)
5156 fattrs
= FILE_ATTRIBUTE_DIRECTORY
;
5157 ctime
= atime
= wtime
= utc_base_ft
;
5163 /* Make sure non-root directories do NOT end in a slash,
5164 otherwise FindFirstFile might fail. */
5165 if (IS_DIRECTORY_SEP (name
[len
-1]))
5168 /* (This is hacky, but helps when doing file completions on
5169 network drives.) Optimize by using information available from
5170 active readdir if possible. */
5171 len
= strlen (dir_pathname
);
5172 if (IS_DIRECTORY_SEP (dir_pathname
[len
-1]))
5174 if (dir_find_handle
!= INVALID_HANDLE_VALUE
5175 && last_dir_find_data
!= -1
5176 && !(is_a_symlink
&& follow_symlinks
)
5177 /* The 2 file-name comparisons below support only ASCII
5178 characters, and will lose (compare not equal) when
5179 the file names include non-ASCII characters that are
5180 the same but for the case. However, doing this
5181 properly involves: (a) converting both file names to
5182 UTF-16, (b) lower-casing both names using CharLowerW,
5183 and (c) comparing the results; this would be quite a
5184 bit slower, whereas Plan B is for users who want
5185 lightweight albeit inaccurate version of 'stat'. */
5186 && c_strncasecmp (save_name
, dir_pathname
, len
) == 0
5187 && IS_DIRECTORY_SEP (name
[len
])
5188 && xstrcasecmp (name
+ len
+ 1, dir_static
.d_name
) == 0)
5190 have_wfd
= last_dir_find_data
;
5191 /* This was the last entry returned by readdir. */
5192 if (last_dir_find_data
== DIR_FIND_DATA_W
)
5193 wfd_w
= dir_find_data_w
;
5195 wfd_a
= dir_find_data_a
;
5199 logon_network_drive (name
);
5201 if (w32_unicode_filenames
)
5203 filename_to_utf16 (name
, name_w
);
5204 fh
= FindFirstFileW (name_w
, &wfd_w
);
5205 have_wfd
= DIR_FIND_DATA_W
;
5209 filename_to_ansi (name
, name_a
);
5210 /* If NAME includes characters not representable by
5211 the current ANSI codepage, filename_to_ansi
5212 usually replaces them with a '?'. We don't want
5213 to let FindFirstFileA interpret those as wildcards,
5214 and "succeed", returning us data from some random
5215 file in the same directory. */
5216 if (_mbspbrk (name_a
, "?"))
5217 fh
= INVALID_HANDLE_VALUE
;
5219 fh
= FindFirstFileA (name_a
, &wfd_a
);
5220 have_wfd
= DIR_FIND_DATA_A
;
5222 if (fh
== INVALID_HANDLE_VALUE
)
5229 /* Note: if NAME is a symlink, the information we get from
5230 FindFirstFile is for the symlink, not its target. */
5231 if (have_wfd
== DIR_FIND_DATA_W
)
5233 fattrs
= wfd_w
.dwFileAttributes
;
5234 ctime
= wfd_w
.ftCreationTime
;
5235 atime
= wfd_w
.ftLastAccessTime
;
5236 wtime
= wfd_w
.ftLastWriteTime
;
5237 fs_high
= wfd_w
.nFileSizeHigh
;
5238 fs_low
= wfd_w
.nFileSizeLow
;
5242 fattrs
= wfd_a
.dwFileAttributes
;
5243 ctime
= wfd_a
.ftCreationTime
;
5244 atime
= wfd_a
.ftLastAccessTime
;
5245 wtime
= wfd_a
.ftLastWriteTime
;
5246 fs_high
= wfd_a
.nFileSizeHigh
;
5247 fs_low
= wfd_a
.nFileSizeLow
;
5251 serialnum
= volume_info
.serialnum
;
5253 if (is_a_symlink
&& !follow_symlinks
)
5254 buf
->st_mode
= S_IFLNK
;
5255 else if (fattrs
& FILE_ATTRIBUTE_DIRECTORY
)
5256 buf
->st_mode
= S_IFDIR
;
5258 buf
->st_mode
= S_IFREG
;
5260 get_file_owner_and_group (NULL
, buf
);
5263 buf
->st_ino
= fake_inode
;
5265 buf
->st_dev
= serialnum
;
5266 buf
->st_rdev
= serialnum
;
5268 buf
->st_size
= fs_high
;
5269 buf
->st_size
<<= 32;
5270 buf
->st_size
+= fs_low
;
5271 buf
->st_nlink
= nlinks
;
5273 /* Convert timestamps to Unix format. */
5274 buf
->st_mtime
= convert_time (wtime
);
5275 buf
->st_atime
= convert_time (atime
);
5276 if (buf
->st_atime
== 0) buf
->st_atime
= buf
->st_mtime
;
5277 buf
->st_ctime
= convert_time (ctime
);
5278 if (buf
->st_ctime
== 0) buf
->st_ctime
= buf
->st_mtime
;
5280 /* determine rwx permissions */
5281 if (is_a_symlink
&& !follow_symlinks
)
5282 permission
= S_IREAD
| S_IWRITE
| S_IEXEC
; /* Posix expectations */
5285 if (fattrs
& FILE_ATTRIBUTE_READONLY
)
5286 permission
= S_IREAD
;
5288 permission
= S_IREAD
| S_IWRITE
;
5290 if (fattrs
& FILE_ATTRIBUTE_DIRECTORY
)
5291 permission
|= S_IEXEC
;
5292 else if (is_exec (name
))
5293 permission
|= S_IEXEC
;
5296 buf
->st_mode
|= permission
| (permission
>> 3) | (permission
>> 6);
5302 stat (const char * path
, struct stat
* buf
)
5304 return stat_worker (path
, buf
, 1);
5308 lstat (const char * path
, struct stat
* buf
)
5310 return stat_worker (path
, buf
, 0);
5314 fstatat (int fd
, char const *name
, struct stat
*st
, int flags
)
5316 /* Rely on a hack: an open directory is modeled as file descriptor 0.
5317 This is good enough for the current usage in Emacs, but is fragile.
5319 FIXME: Add proper support for fdopendir, fstatat, readlinkat.
5320 Gnulib does this and can serve as a model. */
5321 char fullname
[MAX_UTF8_PATH
];
5325 char lastc
= dir_pathname
[strlen (dir_pathname
) - 1];
5327 if (_snprintf (fullname
, sizeof fullname
, "%s%s%s",
5328 dir_pathname
, IS_DIRECTORY_SEP (lastc
) ? "" : "/", name
)
5331 errno
= ENAMETOOLONG
;
5337 return stat_worker (name
, st
, ! (flags
& AT_SYMLINK_NOFOLLOW
));
5340 /* Provide fstat and utime as well as stat for consistent handling of
5343 fstat (int desc
, struct stat
* buf
)
5345 HANDLE fh
= (HANDLE
) _get_osfhandle (desc
);
5346 BY_HANDLE_FILE_INFORMATION info
;
5347 unsigned __int64 fake_inode
;
5350 switch (GetFileType (fh
) & ~FILE_TYPE_REMOTE
)
5352 case FILE_TYPE_DISK
:
5353 buf
->st_mode
= S_IFREG
;
5354 if (!GetFileInformationByHandle (fh
, &info
))
5360 case FILE_TYPE_PIPE
:
5361 buf
->st_mode
= S_IFIFO
;
5363 case FILE_TYPE_CHAR
:
5364 case FILE_TYPE_UNKNOWN
:
5366 buf
->st_mode
= S_IFCHR
;
5368 memset (&info
, 0, sizeof (info
));
5369 info
.dwFileAttributes
= 0;
5370 info
.ftCreationTime
= utc_base_ft
;
5371 info
.ftLastAccessTime
= utc_base_ft
;
5372 info
.ftLastWriteTime
= utc_base_ft
;
5375 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
5376 buf
->st_mode
= S_IFDIR
;
5378 buf
->st_nlink
= info
.nNumberOfLinks
;
5379 /* Might as well use file index to fake inode values, but this
5380 is not guaranteed to be unique unless we keep a handle open
5381 all the time (even then there are situations where it is
5382 not unique). Reputedly, there are at most 48 bits of info
5383 (on NTFS, presumably less on FAT). */
5384 fake_inode
= info
.nFileIndexHigh
;
5386 fake_inode
+= info
.nFileIndexLow
;
5388 /* MSVC defines _ino_t to be short; other libc's might not. */
5389 if (sizeof (buf
->st_ino
) == 2)
5390 buf
->st_ino
= fake_inode
^ (fake_inode
>> 16);
5392 buf
->st_ino
= fake_inode
;
5394 /* If the caller so requested, get the true file owner and group.
5395 Otherwise, consider the file to belong to the current user. */
5396 if (!w32_stat_get_owner_group
|| is_windows_9x () == TRUE
)
5397 get_file_owner_and_group (NULL
, buf
);
5400 PSECURITY_DESCRIPTOR psd
= NULL
;
5402 psd
= get_file_security_desc_by_handle (fh
);
5405 get_file_owner_and_group (psd
, buf
);
5409 get_file_owner_and_group (NULL
, buf
);
5412 buf
->st_dev
= info
.dwVolumeSerialNumber
;
5413 buf
->st_rdev
= info
.dwVolumeSerialNumber
;
5415 buf
->st_size
= info
.nFileSizeHigh
;
5416 buf
->st_size
<<= 32;
5417 buf
->st_size
+= info
.nFileSizeLow
;
5419 /* Convert timestamps to Unix format. */
5420 buf
->st_mtime
= convert_time (info
.ftLastWriteTime
);
5421 buf
->st_atime
= convert_time (info
.ftLastAccessTime
);
5422 if (buf
->st_atime
== 0) buf
->st_atime
= buf
->st_mtime
;
5423 buf
->st_ctime
= convert_time (info
.ftCreationTime
);
5424 if (buf
->st_ctime
== 0) buf
->st_ctime
= buf
->st_mtime
;
5426 /* determine rwx permissions */
5427 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
)
5428 permission
= S_IREAD
;
5430 permission
= S_IREAD
| S_IWRITE
;
5432 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
5433 permission
|= S_IEXEC
;
5436 #if 0 /* no way of knowing the filename */
5437 char * p
= strrchr (name
, '.');
5439 (xstrcasecmp (p
, ".exe") == 0 ||
5440 xstrcasecmp (p
, ".com") == 0 ||
5441 xstrcasecmp (p
, ".bat") == 0 ||
5442 xstrcasecmp (p
, ".cmd") == 0))
5443 permission
|= S_IEXEC
;
5447 buf
->st_mode
|= permission
| (permission
>> 3) | (permission
>> 6);
5452 /* A version of 'utime' which handles directories as well as
5456 utime (const char *name
, struct utimbuf
*times
)
5458 struct utimbuf deftime
;
5465 deftime
.modtime
= deftime
.actime
= time (NULL
);
5469 if (w32_unicode_filenames
)
5471 wchar_t name_utf16
[MAX_PATH
];
5473 if (filename_to_utf16 (name
, name_utf16
) != 0)
5474 return -1; /* errno set by filename_to_utf16 */
5476 /* Need write access to set times. */
5477 fh
= CreateFileW (name_utf16
, FILE_WRITE_ATTRIBUTES
,
5478 /* If NAME specifies a directory, FILE_SHARE_DELETE
5479 allows other processes to delete files inside it,
5480 while we have the directory open. */
5481 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
5482 0, OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
5486 char name_ansi
[MAX_PATH
];
5488 if (filename_to_ansi (name
, name_ansi
) != 0)
5489 return -1; /* errno set by filename_to_ansi */
5491 fh
= CreateFileA (name_ansi
, FILE_WRITE_ATTRIBUTES
,
5492 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
5493 0, OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
5495 if (fh
!= INVALID_HANDLE_VALUE
)
5497 convert_from_time_t (times
->actime
, &atime
);
5498 convert_from_time_t (times
->modtime
, &mtime
);
5499 if (!SetFileTime (fh
, NULL
, &atime
, &mtime
))
5509 DWORD err
= GetLastError ();
5513 case ERROR_FILE_NOT_FOUND
:
5514 case ERROR_PATH_NOT_FOUND
:
5515 case ERROR_INVALID_DRIVE
:
5516 case ERROR_BAD_NETPATH
:
5517 case ERROR_DEV_NOT_EXIST
:
5518 /* ERROR_INVALID_NAME is the error CreateFile sets when the
5519 file name includes ?s, i.e. translation to ANSI failed. */
5520 case ERROR_INVALID_NAME
:
5523 case ERROR_TOO_MANY_OPEN_FILES
:
5526 case ERROR_ACCESS_DENIED
:
5527 case ERROR_SHARING_VIOLATION
:
5540 sys_umask (int mode
)
5542 static int current_mask
;
5543 int retval
, arg
= 0;
5545 /* The only bit we really support is the write bit. Files are
5546 always readable on MS-Windows, and the execute bit does not exist
5548 /* FIXME: if the GROUP and OTHER bits are reset, we should use ACLs
5549 to prevent access by other users on NTFS. */
5550 if ((mode
& S_IWRITE
) != 0)
5553 retval
= _umask (arg
);
5554 /* Merge into the return value the bits they've set the last time,
5555 which msvcrt.dll ignores and never returns. Emacs insists on its
5556 notion of mask being identical to what we return. */
5557 retval
|= (current_mask
& ~S_IWRITE
);
5558 current_mask
= mode
;
5564 /* Symlink-related functions. */
5565 #ifndef SYMBOLIC_LINK_FLAG_DIRECTORY
5566 #define SYMBOLIC_LINK_FLAG_DIRECTORY 0x1
5570 symlink (char const *filename
, char const *linkname
)
5572 char linkfn
[MAX_UTF8_PATH
], *tgtfn
;
5574 int dir_access
, filename_ends_in_slash
;
5576 /* Diagnostics follows Posix as much as possible. */
5577 if (filename
== NULL
|| linkname
== NULL
)
5587 if (strlen (filename
) > MAX_UTF8_PATH
|| strlen (linkname
) > MAX_UTF8_PATH
)
5589 errno
= ENAMETOOLONG
;
5593 strcpy (linkfn
, map_w32_filename (linkname
, NULL
));
5594 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) == 0)
5600 /* Note: since empty FILENAME was already rejected, we can safely
5601 refer to FILENAME[1]. */
5602 if (!(IS_DIRECTORY_SEP (filename
[0]) || IS_DEVICE_SEP (filename
[1])))
5604 /* Non-absolute FILENAME is understood as being relative to
5605 LINKNAME's directory. We need to prepend that directory to
5606 FILENAME to get correct results from faccessat below, since
5607 otherwise it will interpret FILENAME relative to the
5608 directory where the Emacs process runs. Note that
5609 make-symbolic-link always makes sure LINKNAME is a fully
5610 expanded file name. */
5611 char tem
[MAX_UTF8_PATH
];
5612 char *p
= linkfn
+ strlen (linkfn
);
5614 while (p
> linkfn
&& !IS_ANY_SEP (p
[-1]))
5617 strncpy (tem
, linkfn
, p
- linkfn
);
5618 strcpy (tem
+ (p
- linkfn
), filename
);
5619 dir_access
= faccessat (AT_FDCWD
, tem
, D_OK
, AT_EACCESS
);
5622 dir_access
= faccessat (AT_FDCWD
, filename
, D_OK
, AT_EACCESS
);
5624 /* Since Windows distinguishes between symlinks to directories and
5625 to files, we provide a kludgy feature: if FILENAME doesn't
5626 exist, but ends in a slash, we create a symlink to directory. If
5627 FILENAME exists and is a directory, we always create a symlink to
5629 filename_ends_in_slash
= IS_DIRECTORY_SEP (filename
[strlen (filename
) - 1]);
5630 if (dir_access
== 0 || filename_ends_in_slash
)
5631 flags
= SYMBOLIC_LINK_FLAG_DIRECTORY
;
5633 tgtfn
= (char *)map_w32_filename (filename
, NULL
);
5634 if (filename_ends_in_slash
)
5635 tgtfn
[strlen (tgtfn
) - 1] = '\0';
5638 if (!create_symbolic_link (linkfn
, tgtfn
, flags
))
5640 /* ENOSYS is set by create_symbolic_link, when it detects that
5641 the OS doesn't support the CreateSymbolicLink API. */
5642 if (errno
!= ENOSYS
)
5644 DWORD w32err
= GetLastError ();
5648 /* ERROR_SUCCESS is sometimes returned when LINKFN and
5649 TGTFN point to the same file name, go figure. */
5651 case ERROR_FILE_EXISTS
:
5654 case ERROR_ACCESS_DENIED
:
5657 case ERROR_FILE_NOT_FOUND
:
5658 case ERROR_PATH_NOT_FOUND
:
5659 case ERROR_BAD_NETPATH
:
5660 case ERROR_INVALID_REPARSE_DATA
:
5663 case ERROR_DIRECTORY
:
5666 case ERROR_PRIVILEGE_NOT_HELD
:
5667 case ERROR_NOT_ALL_ASSIGNED
:
5670 case ERROR_DISK_FULL
:
5683 /* A quick inexpensive test of whether FILENAME identifies a file that
5684 is a symlink. Returns non-zero if it is, zero otherwise. FILENAME
5685 must already be in the normalized form returned by
5686 map_w32_filename. If the symlink is to a directory, the
5687 FILE_ATTRIBUTE_DIRECTORY bit will be set in the return value.
5689 Note: for repeated operations on many files, it is best to test
5690 whether the underlying volume actually supports symlinks, by
5691 testing the FILE_SUPPORTS_REPARSE_POINTS bit in volume's flags, and
5692 avoid the call to this function if it doesn't. That's because the
5693 call to GetFileAttributes takes a non-negligible time, especially
5694 on non-local or removable filesystems. See stat_worker for an
5695 example of how to do that. */
5697 is_symlink (const char *filename
)
5700 wchar_t filename_w
[MAX_PATH
];
5701 char filename_a
[MAX_PATH
];
5702 WIN32_FIND_DATAW wfdw
;
5703 WIN32_FIND_DATAA wfda
;
5705 int attrs_mean_symlink
;
5707 if (w32_unicode_filenames
)
5709 filename_to_utf16 (filename
, filename_w
);
5710 attrs
= GetFileAttributesW (filename_w
);
5714 filename_to_ansi (filename
, filename_a
);
5715 attrs
= GetFileAttributesA (filename_a
);
5719 DWORD w32err
= GetLastError ();
5723 case ERROR_BAD_NETPATH
: /* network share, can't be a symlink */
5725 case ERROR_ACCESS_DENIED
:
5728 case ERROR_FILE_NOT_FOUND
:
5729 case ERROR_PATH_NOT_FOUND
:
5736 if ((attrs
& FILE_ATTRIBUTE_REPARSE_POINT
) == 0)
5738 logon_network_drive (filename
);
5739 if (w32_unicode_filenames
)
5741 fh
= FindFirstFileW (filename_w
, &wfdw
);
5742 attrs_mean_symlink
=
5743 (wfdw
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) != 0
5744 && (wfdw
.dwReserved0
& IO_REPARSE_TAG_SYMLINK
) == IO_REPARSE_TAG_SYMLINK
;
5745 if (attrs_mean_symlink
)
5746 attrs_mean_symlink
|= (wfdw
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
);
5748 else if (_mbspbrk (filename_a
, "?"))
5750 /* filename_to_ansi failed to convert the file name. */
5756 fh
= FindFirstFileA (filename_a
, &wfda
);
5757 attrs_mean_symlink
=
5758 (wfda
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) != 0
5759 && (wfda
.dwReserved0
& IO_REPARSE_TAG_SYMLINK
) == IO_REPARSE_TAG_SYMLINK
;
5760 if (attrs_mean_symlink
)
5761 attrs_mean_symlink
|= (wfda
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
);
5763 if (fh
== INVALID_HANDLE_VALUE
)
5766 return attrs_mean_symlink
;
5769 /* If NAME identifies a symbolic link, copy into BUF the file name of
5770 the symlink's target. Copy at most BUF_SIZE bytes, and do NOT
5771 null-terminate the target name, even if it fits. Return the number
5772 of bytes copied, or -1 if NAME is not a symlink or any error was
5773 encountered while resolving it. The file name copied into BUF is
5774 encoded in the current ANSI codepage. */
5776 readlink (const char *name
, char *buf
, size_t buf_size
)
5779 TOKEN_PRIVILEGES privs
;
5780 int restore_privs
= 0;
5783 char resolved
[MAX_UTF8_PATH
];
5796 path
= map_w32_filename (name
, NULL
);
5798 if (strlen (path
) > MAX_UTF8_PATH
)
5800 errno
= ENAMETOOLONG
;
5805 if (is_windows_9x () == TRUE
5806 || (volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) == 0
5807 || !is_symlink (path
))
5810 errno
= EINVAL
; /* not a symlink */
5814 /* Done with simple tests, now we're in for some _real_ work. */
5815 if (enable_privilege (SE_BACKUP_NAME
, TRUE
, &privs
))
5817 /* Implementation note: From here and onward, don't return early,
5818 since that will fail to restore the original set of privileges of
5819 the calling thread. */
5821 retval
= -1; /* not too optimistic, are we? */
5823 /* Note: In the next call to CreateFile, we use zero as the 2nd
5824 argument because, when the symlink is a hidden/system file,
5825 e.g. 'C:\Users\All Users', GENERIC_READ fails with
5826 ERROR_ACCESS_DENIED. Zero seems to work just fine, both for file
5827 and directory symlinks. */
5828 if (w32_unicode_filenames
)
5830 wchar_t path_w
[MAX_PATH
];
5832 filename_to_utf16 (path
, path_w
);
5833 sh
= CreateFileW (path_w
, 0, 0, NULL
, OPEN_EXISTING
,
5834 FILE_FLAG_OPEN_REPARSE_POINT
5835 | FILE_FLAG_BACKUP_SEMANTICS
,
5840 char path_a
[MAX_PATH
];
5842 filename_to_ansi (path
, path_a
);
5843 sh
= CreateFileA (path_a
, 0, 0, NULL
, OPEN_EXISTING
,
5844 FILE_FLAG_OPEN_REPARSE_POINT
5845 | FILE_FLAG_BACKUP_SEMANTICS
,
5848 if (sh
!= INVALID_HANDLE_VALUE
)
5850 BYTE reparse_buf
[MAXIMUM_REPARSE_DATA_BUFFER_SIZE
];
5851 REPARSE_DATA_BUFFER
*reparse_data
= (REPARSE_DATA_BUFFER
*)&reparse_buf
[0];
5854 if (!DeviceIoControl (sh
, FSCTL_GET_REPARSE_POINT
, NULL
, 0,
5855 reparse_buf
, MAXIMUM_REPARSE_DATA_BUFFER_SIZE
,
5858 else if (reparse_data
->ReparseTag
!= IO_REPARSE_TAG_SYMLINK
)
5862 /* Copy the link target name, in wide characters, from
5863 reparse_data, then convert it to multibyte encoding in
5864 the current locale's codepage. */
5868 reparse_data
->SymbolicLinkReparseBuffer
.PrintNameLength
;
5870 reparse_data
->SymbolicLinkReparseBuffer
.PathBuffer
5871 + reparse_data
->SymbolicLinkReparseBuffer
.PrintNameOffset
/sizeof(WCHAR
);
5872 size_t size_to_copy
= buf_size
;
5874 /* According to MSDN, PrintNameLength does not include the
5875 terminating null character. */
5876 lwname
= alloca ((lwname_len
+ 1) * sizeof(WCHAR
));
5877 memcpy (lwname
, lwname_src
, lwname_len
);
5878 lwname
[lwname_len
/sizeof(WCHAR
)] = 0; /* null-terminate */
5879 filename_from_utf16 (lwname
, resolved
);
5880 dostounix_filename (resolved
);
5881 lname_size
= strlen (resolved
) + 1;
5882 if (lname_size
<= buf_size
)
5883 size_to_copy
= lname_size
;
5884 strncpy (buf
, resolved
, size_to_copy
);
5886 retval
= size_to_copy
;
5892 /* CreateFile failed. */
5893 DWORD w32err2
= GetLastError ();
5897 case ERROR_FILE_NOT_FOUND
:
5898 case ERROR_PATH_NOT_FOUND
:
5901 case ERROR_ACCESS_DENIED
:
5902 case ERROR_TOO_MANY_OPEN_FILES
:
5912 restore_privilege (&privs
);
5920 readlinkat (int fd
, char const *name
, char *buffer
,
5923 /* Rely on a hack: an open directory is modeled as file descriptor 0,
5924 as in fstatat. FIXME: Add proper support for readlinkat. */
5925 char fullname
[MAX_UTF8_PATH
];
5929 if (_snprintf (fullname
, sizeof fullname
, "%s/%s", dir_pathname
, name
)
5932 errno
= ENAMETOOLONG
;
5938 return readlink (name
, buffer
, buffer_size
);
5941 /* If FILE is a symlink, return its target (stored in a static
5942 buffer); otherwise return FILE.
5944 This function repeatedly resolves symlinks in the last component of
5945 a chain of symlink file names, as in foo -> bar -> baz -> ...,
5946 until it arrives at a file whose last component is not a symlink,
5947 or some error occurs. It returns the target of the last
5948 successfully resolved symlink in the chain. If it succeeds to
5949 resolve even a single symlink, the value returned is an absolute
5950 file name with backslashes (result of GetFullPathName). By
5951 contrast, if the original FILE is returned, it is unaltered.
5953 Note: This function can set errno even if it succeeds.
5955 Implementation note: we only resolve the last portion ("basename")
5956 of the argument FILE and of each following file in the chain,
5957 disregarding any possible symlinks in its leading directories.
5958 This is because Windows system calls and library functions
5959 transparently resolve symlinks in leading directories and return
5960 correct information, as long as the basename is not a symlink. */
5962 chase_symlinks (const char *file
)
5964 static char target
[MAX_UTF8_PATH
];
5965 char link
[MAX_UTF8_PATH
];
5966 wchar_t target_w
[MAX_PATH
], link_w
[MAX_PATH
];
5967 char target_a
[MAX_PATH
], link_a
[MAX_PATH
];
5968 ssize_t res
, link_len
;
5971 if (is_windows_9x () == TRUE
|| !is_symlink (file
))
5972 return (char *)file
;
5974 if (w32_unicode_filenames
)
5976 wchar_t file_w
[MAX_PATH
];
5978 filename_to_utf16 (file
, file_w
);
5979 if (GetFullPathNameW (file_w
, MAX_PATH
, link_w
, NULL
) == 0)
5980 return (char *)file
;
5981 filename_from_utf16 (link_w
, link
);
5985 char file_a
[MAX_PATH
];
5987 filename_to_ansi (file
, file_a
);
5988 if (GetFullPathNameA (file_a
, MAX_PATH
, link_a
, NULL
) == 0)
5989 return (char *)file
;
5990 filename_from_ansi (link_a
, link
);
5992 link_len
= strlen (link
);
5997 /* Remove trailing slashes, as we want to resolve the last
5998 non-trivial part of the link name. */
5999 while (link_len
> 3 && IS_DIRECTORY_SEP (link
[link_len
-1]))
6000 link
[link_len
--] = '\0';
6002 res
= readlink (link
, target
, MAX_UTF8_PATH
);
6006 if (!(IS_DEVICE_SEP (target
[1])
6007 || (IS_DIRECTORY_SEP (target
[0]) && IS_DIRECTORY_SEP (target
[1]))))
6009 /* Target is relative. Append it to the directory part of
6010 the symlink, then copy the result back to target. */
6011 char *p
= link
+ link_len
;
6013 while (p
> link
&& !IS_ANY_SEP (p
[-1]))
6016 strcpy (target
, link
);
6018 /* Resolve any "." and ".." to get a fully-qualified file name
6020 if (w32_unicode_filenames
)
6022 filename_to_utf16 (target
, target_w
);
6023 link_len
= GetFullPathNameW (target_w
, MAX_PATH
, link_w
, NULL
);
6025 filename_from_utf16 (link_w
, link
);
6029 filename_to_ansi (target
, target_a
);
6030 link_len
= GetFullPathNameA (target_a
, MAX_PATH
, link_a
, NULL
);
6032 filename_from_ansi (link_a
, link
);
6034 link_len
= strlen (link
);
6036 } while (res
> 0 && link_len
> 0 && ++loop_count
<= 100);
6038 if (loop_count
> 100)
6041 if (target
[0] == '\0') /* not a single call to readlink succeeded */
6042 return (char *)file
;
6047 /* Posix ACL emulation. */
6050 acl_valid (acl_t acl
)
6052 return is_valid_security_descriptor ((PSECURITY_DESCRIPTOR
)acl
) ? 0 : -1;
6056 acl_to_text (acl_t acl
, ssize_t
*size
)
6059 SECURITY_INFORMATION flags
=
6060 OWNER_SECURITY_INFORMATION
|
6061 GROUP_SECURITY_INFORMATION
|
6062 DACL_SECURITY_INFORMATION
;
6063 char *retval
= NULL
;
6069 if (convert_sd_to_sddl ((PSECURITY_DESCRIPTOR
)acl
, SDDL_REVISION_1
, flags
, &str_acl
, &local_size
))
6072 /* We don't want to mix heaps, so we duplicate the string in our
6073 heap and free the one allocated by the API. */
6074 retval
= xstrdup (str_acl
);
6077 LocalFree (str_acl
);
6079 else if (errno
!= ENOTSUP
)
6086 acl_from_text (const char *acl_str
)
6088 PSECURITY_DESCRIPTOR psd
, retval
= NULL
;
6094 if (convert_sddl_to_sd (acl_str
, SDDL_REVISION_1
, &psd
, &sd_size
))
6097 retval
= xmalloc (sd_size
);
6098 memcpy (retval
, psd
, sd_size
);
6101 else if (errno
!= ENOTSUP
)
6108 acl_free (void *ptr
)
6115 acl_get_file (const char *fname
, acl_type_t type
)
6117 PSECURITY_DESCRIPTOR psd
= NULL
;
6118 const char *filename
;
6120 if (type
== ACL_TYPE_ACCESS
)
6123 SECURITY_INFORMATION si
=
6124 OWNER_SECURITY_INFORMATION
|
6125 GROUP_SECURITY_INFORMATION
|
6126 DACL_SECURITY_INFORMATION
;
6129 filename
= map_w32_filename (fname
, NULL
);
6130 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) != 0)
6131 fname
= chase_symlinks (filename
);
6136 if (!get_file_security (fname
, si
, psd
, 0, &sd_len
)
6137 && errno
!= ENOTSUP
)
6139 err
= GetLastError ();
6140 if (err
== ERROR_INSUFFICIENT_BUFFER
)
6142 psd
= xmalloc (sd_len
);
6143 if (!get_file_security (fname
, si
, psd
, sd_len
, &sd_len
))
6150 else if (err
== ERROR_FILE_NOT_FOUND
6151 || err
== ERROR_PATH_NOT_FOUND
6152 /* ERROR_INVALID_NAME is what we get if
6153 w32-unicode-filenames is nil and the file cannot
6154 be encoded in the current ANSI codepage. */
6155 || err
== ERROR_INVALID_NAME
)
6163 else if (type
!= ACL_TYPE_DEFAULT
)
6170 acl_set_file (const char *fname
, acl_type_t type
, acl_t acl
)
6172 TOKEN_PRIVILEGES old1
, old2
;
6174 int st
= 0, retval
= -1;
6175 SECURITY_INFORMATION flags
= 0;
6176 PSID psidOwner
, psidGroup
;
6181 const char *filename
;
6183 if (acl_valid (acl
) != 0
6184 || (type
!= ACL_TYPE_DEFAULT
&& type
!= ACL_TYPE_ACCESS
))
6190 if (type
== ACL_TYPE_DEFAULT
)
6196 filename
= map_w32_filename (fname
, NULL
);
6197 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) != 0)
6198 fname
= chase_symlinks (filename
);
6202 if (get_security_descriptor_owner ((PSECURITY_DESCRIPTOR
)acl
, &psidOwner
,
6205 flags
|= OWNER_SECURITY_INFORMATION
;
6206 if (get_security_descriptor_group ((PSECURITY_DESCRIPTOR
)acl
, &psidGroup
,
6209 flags
|= GROUP_SECURITY_INFORMATION
;
6210 if (get_security_descriptor_dacl ((PSECURITY_DESCRIPTOR
)acl
, &dacl_present
,
6213 flags
|= DACL_SECURITY_INFORMATION
;
6217 /* According to KB-245153, setting the owner will succeed if either:
6218 (1) the caller is the user who will be the new owner, and has the
6219 SE_TAKE_OWNERSHIP privilege, or
6220 (2) the caller has the SE_RESTORE privilege, in which case she can
6221 set any valid user or group as the owner
6223 We request below both SE_TAKE_OWNERSHIP and SE_RESTORE
6224 privileges, and disregard any failures in obtaining them. If
6225 these privileges cannot be obtained, and do not already exist in
6226 the calling thread's security token, this function could fail
6228 if (enable_privilege (SE_TAKE_OWNERSHIP_NAME
, TRUE
, &old1
))
6230 if (enable_privilege (SE_RESTORE_NAME
, TRUE
, &old2
))
6235 /* SetFileSecurity is deprecated by MS, and sometimes fails when
6236 DACL inheritance is involved, but it seems to preserve ownership
6237 better than SetNamedSecurityInfo, which is important e.g., in
6239 if (!set_file_security (fname
, flags
, (PSECURITY_DESCRIPTOR
)acl
))
6241 err
= GetLastError ();
6243 if (errno
!= ENOTSUP
)
6244 err
= set_named_security_info (fname
, SE_FILE_OBJECT
, flags
,
6245 psidOwner
, psidGroup
, pacl
, NULL
);
6248 err
= ERROR_SUCCESS
;
6249 if (err
!= ERROR_SUCCESS
)
6251 if (errno
== ENOTSUP
)
6253 else if (err
== ERROR_INVALID_OWNER
6254 || err
== ERROR_NOT_ALL_ASSIGNED
6255 || err
== ERROR_ACCESS_DENIED
)
6257 /* Maybe the requested ACL and the one the file already has
6258 are identical, in which case we can silently ignore the
6259 failure. (And no, Windows doesn't.) */
6260 acl_t current_acl
= acl_get_file (fname
, ACL_TYPE_ACCESS
);
6265 char *acl_from
= acl_to_text (current_acl
, NULL
);
6266 char *acl_to
= acl_to_text (acl
, NULL
);
6268 if (acl_from
&& acl_to
&& xstrcasecmp (acl_from
, acl_to
) == 0)
6274 acl_free (acl_from
);
6277 acl_free (current_acl
);
6280 else if (err
== ERROR_FILE_NOT_FOUND
6281 || err
== ERROR_PATH_NOT_FOUND
6282 /* ERROR_INVALID_NAME is what we get if
6283 w32-unicode-filenames is nil and the file cannot be
6284 encoded in the current ANSI codepage. */
6285 || err
== ERROR_INVALID_NAME
)
6299 restore_privilege (&old2
);
6300 restore_privilege (&old1
);
6308 /* MS-Windows version of careadlinkat (cf. ../lib/careadlinkat.c). We
6309 have a fixed max size for file names, so we don't need the kind of
6310 alloc/malloc/realloc dance the gnulib version does. We also don't
6311 support FD-relative symlinks. */
6313 careadlinkat (int fd
, char const *filename
,
6314 char *buffer
, size_t buffer_size
,
6315 struct allocator
const *alloc
,
6316 ssize_t (*preadlinkat
) (int, char const *, char *, size_t))
6318 char linkname
[MAX_UTF8_PATH
];
6321 link_size
= preadlinkat (fd
, filename
, linkname
, sizeof(linkname
));
6325 char *retval
= buffer
;
6327 linkname
[link_size
++] = '\0';
6328 if (link_size
> buffer_size
)
6329 retval
= (char *)(alloc
? alloc
->allocate
: xmalloc
) (link_size
);
6331 memcpy (retval
, linkname
, link_size
);
6339 w32_copy_file (const char *from
, const char *to
,
6340 int keep_time
, int preserve_ownership
, int copy_acls
)
6344 wchar_t from_w
[MAX_PATH
], to_w
[MAX_PATH
];
6345 char from_a
[MAX_PATH
], to_a
[MAX_PATH
];
6347 /* We ignore preserve_ownership for now. */
6348 preserve_ownership
= preserve_ownership
;
6352 acl
= acl_get_file (from
, ACL_TYPE_ACCESS
);
6353 if (acl
== NULL
&& acl_errno_valid (errno
))
6356 if (w32_unicode_filenames
)
6358 filename_to_utf16 (from
, from_w
);
6359 filename_to_utf16 (to
, to_w
);
6360 copy_result
= CopyFileW (from_w
, to_w
, FALSE
);
6364 filename_to_ansi (from
, from_a
);
6365 filename_to_ansi (to
, to_a
);
6366 copy_result
= CopyFileA (from_a
, to_a
, FALSE
);
6370 /* CopyFile doesn't set errno when it fails. By far the most
6371 "popular" reason is that the target is read-only. */
6372 DWORD err
= GetLastError ();
6376 case ERROR_FILE_NOT_FOUND
:
6379 case ERROR_ACCESS_DENIED
:
6382 case ERROR_ENCRYPTION_FAILED
:
6394 /* CopyFile retains the timestamp by default. However, see
6395 "Community Additions" for CopyFile: it sounds like that is not
6396 entirely true. Testing on Windows XP confirms that modified time
6397 is copied, but creation and last-access times are not.
6399 else if (!keep_time
)
6401 struct timespec now
;
6404 if (w32_unicode_filenames
)
6406 /* Ensure file is writable while its times are set. */
6407 attributes
= GetFileAttributesW (to_w
);
6408 SetFileAttributesW (to_w
, attributes
& ~FILE_ATTRIBUTE_READONLY
);
6409 now
= current_timespec ();
6410 if (set_file_times (-1, to
, now
, now
))
6412 /* Restore original attributes. */
6413 SetFileAttributesW (to_w
, attributes
);
6418 /* Restore original attributes. */
6419 SetFileAttributesW (to_w
, attributes
);
6423 attributes
= GetFileAttributesA (to_a
);
6424 SetFileAttributesA (to_a
, attributes
& ~FILE_ATTRIBUTE_READONLY
);
6425 now
= current_timespec ();
6426 if (set_file_times (-1, to
, now
, now
))
6428 SetFileAttributesA (to_a
, attributes
);
6433 SetFileAttributesA (to_a
, attributes
);
6439 acl_set_file (to
, ACL_TYPE_ACCESS
, acl
) != 0;
6441 if (fail
&& acl_errno_valid (errno
))
6449 /* Support for browsing other processes and their attributes. See
6450 process.c for the Lisp bindings. */
6452 /* Helper wrapper functions. */
6454 static HANDLE WINAPI
6455 create_toolhelp32_snapshot (DWORD Flags
, DWORD Ignored
)
6457 static CreateToolhelp32Snapshot_Proc s_pfn_Create_Toolhelp32_Snapshot
= NULL
;
6459 if (g_b_init_create_toolhelp32_snapshot
== 0)
6461 g_b_init_create_toolhelp32_snapshot
= 1;
6462 s_pfn_Create_Toolhelp32_Snapshot
= (CreateToolhelp32Snapshot_Proc
)
6463 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6464 "CreateToolhelp32Snapshot");
6466 if (s_pfn_Create_Toolhelp32_Snapshot
== NULL
)
6468 return INVALID_HANDLE_VALUE
;
6470 return (s_pfn_Create_Toolhelp32_Snapshot (Flags
, Ignored
));
6474 process32_first (HANDLE hSnapshot
, LPPROCESSENTRY32 lppe
)
6476 static Process32First_Proc s_pfn_Process32_First
= NULL
;
6478 if (g_b_init_process32_first
== 0)
6480 g_b_init_process32_first
= 1;
6481 s_pfn_Process32_First
= (Process32First_Proc
)
6482 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6485 if (s_pfn_Process32_First
== NULL
)
6489 return (s_pfn_Process32_First (hSnapshot
, lppe
));
6493 process32_next (HANDLE hSnapshot
, LPPROCESSENTRY32 lppe
)
6495 static Process32Next_Proc s_pfn_Process32_Next
= NULL
;
6497 if (g_b_init_process32_next
== 0)
6499 g_b_init_process32_next
= 1;
6500 s_pfn_Process32_Next
= (Process32Next_Proc
)
6501 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6504 if (s_pfn_Process32_Next
== NULL
)
6508 return (s_pfn_Process32_Next (hSnapshot
, lppe
));
6512 open_thread_token (HANDLE ThreadHandle
,
6513 DWORD DesiredAccess
,
6515 PHANDLE TokenHandle
)
6517 static OpenThreadToken_Proc s_pfn_Open_Thread_Token
= NULL
;
6518 HMODULE hm_advapi32
= NULL
;
6519 if (is_windows_9x () == TRUE
)
6521 SetLastError (ERROR_NOT_SUPPORTED
);
6524 if (g_b_init_open_thread_token
== 0)
6526 g_b_init_open_thread_token
= 1;
6527 hm_advapi32
= LoadLibrary ("Advapi32.dll");
6528 s_pfn_Open_Thread_Token
=
6529 (OpenThreadToken_Proc
) GetProcAddress (hm_advapi32
, "OpenThreadToken");
6531 if (s_pfn_Open_Thread_Token
== NULL
)
6533 SetLastError (ERROR_NOT_SUPPORTED
);
6537 s_pfn_Open_Thread_Token (
6546 impersonate_self (SECURITY_IMPERSONATION_LEVEL ImpersonationLevel
)
6548 static ImpersonateSelf_Proc s_pfn_Impersonate_Self
= NULL
;
6549 HMODULE hm_advapi32
= NULL
;
6550 if (is_windows_9x () == TRUE
)
6554 if (g_b_init_impersonate_self
== 0)
6556 g_b_init_impersonate_self
= 1;
6557 hm_advapi32
= LoadLibrary ("Advapi32.dll");
6558 s_pfn_Impersonate_Self
=
6559 (ImpersonateSelf_Proc
) GetProcAddress (hm_advapi32
, "ImpersonateSelf");
6561 if (s_pfn_Impersonate_Self
== NULL
)
6565 return s_pfn_Impersonate_Self (ImpersonationLevel
);
6569 revert_to_self (void)
6571 static RevertToSelf_Proc s_pfn_Revert_To_Self
= NULL
;
6572 HMODULE hm_advapi32
= NULL
;
6573 if (is_windows_9x () == TRUE
)
6577 if (g_b_init_revert_to_self
== 0)
6579 g_b_init_revert_to_self
= 1;
6580 hm_advapi32
= LoadLibrary ("Advapi32.dll");
6581 s_pfn_Revert_To_Self
=
6582 (RevertToSelf_Proc
) GetProcAddress (hm_advapi32
, "RevertToSelf");
6584 if (s_pfn_Revert_To_Self
== NULL
)
6588 return s_pfn_Revert_To_Self ();
6592 get_process_memory_info (HANDLE h_proc
,
6593 PPROCESS_MEMORY_COUNTERS mem_counters
,
6596 static GetProcessMemoryInfo_Proc s_pfn_Get_Process_Memory_Info
= NULL
;
6597 HMODULE hm_psapi
= NULL
;
6598 if (is_windows_9x () == TRUE
)
6602 if (g_b_init_get_process_memory_info
== 0)
6604 g_b_init_get_process_memory_info
= 1;
6605 hm_psapi
= LoadLibrary ("Psapi.dll");
6607 s_pfn_Get_Process_Memory_Info
= (GetProcessMemoryInfo_Proc
)
6608 GetProcAddress (hm_psapi
, "GetProcessMemoryInfo");
6610 if (s_pfn_Get_Process_Memory_Info
== NULL
)
6614 return s_pfn_Get_Process_Memory_Info (h_proc
, mem_counters
, bufsize
);
6618 get_process_working_set_size (HANDLE h_proc
,
6622 static GetProcessWorkingSetSize_Proc
6623 s_pfn_Get_Process_Working_Set_Size
= NULL
;
6625 if (is_windows_9x () == TRUE
)
6629 if (g_b_init_get_process_working_set_size
== 0)
6631 g_b_init_get_process_working_set_size
= 1;
6632 s_pfn_Get_Process_Working_Set_Size
= (GetProcessWorkingSetSize_Proc
)
6633 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6634 "GetProcessWorkingSetSize");
6636 if (s_pfn_Get_Process_Working_Set_Size
== NULL
)
6640 return s_pfn_Get_Process_Working_Set_Size (h_proc
, minrss
, maxrss
);
6644 global_memory_status (MEMORYSTATUS
*buf
)
6646 static GlobalMemoryStatus_Proc s_pfn_Global_Memory_Status
= NULL
;
6648 if (is_windows_9x () == TRUE
)
6652 if (g_b_init_global_memory_status
== 0)
6654 g_b_init_global_memory_status
= 1;
6655 s_pfn_Global_Memory_Status
= (GlobalMemoryStatus_Proc
)
6656 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6657 "GlobalMemoryStatus");
6659 if (s_pfn_Global_Memory_Status
== NULL
)
6663 return s_pfn_Global_Memory_Status (buf
);
6667 global_memory_status_ex (MEMORY_STATUS_EX
*buf
)
6669 static GlobalMemoryStatusEx_Proc s_pfn_Global_Memory_Status_Ex
= NULL
;
6671 if (is_windows_9x () == TRUE
)
6675 if (g_b_init_global_memory_status_ex
== 0)
6677 g_b_init_global_memory_status_ex
= 1;
6678 s_pfn_Global_Memory_Status_Ex
= (GlobalMemoryStatusEx_Proc
)
6679 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6680 "GlobalMemoryStatusEx");
6682 if (s_pfn_Global_Memory_Status_Ex
== NULL
)
6686 return s_pfn_Global_Memory_Status_Ex (buf
);
6690 list_system_processes (void)
6692 Lisp_Object proclist
= Qnil
;
6695 h_snapshot
= create_toolhelp32_snapshot (TH32CS_SNAPPROCESS
, 0);
6697 if (h_snapshot
!= INVALID_HANDLE_VALUE
)
6699 PROCESSENTRY32 proc_entry
;
6703 proc_entry
.dwSize
= sizeof (PROCESSENTRY32
);
6704 for (res
= process32_first (h_snapshot
, &proc_entry
); res
;
6705 res
= process32_next (h_snapshot
, &proc_entry
))
6707 proc_id
= proc_entry
.th32ProcessID
;
6708 proclist
= Fcons (make_fixnum_or_float (proc_id
), proclist
);
6711 CloseHandle (h_snapshot
);
6712 proclist
= Fnreverse (proclist
);
6719 enable_privilege (LPCTSTR priv_name
, BOOL enable_p
, TOKEN_PRIVILEGES
*old_priv
)
6721 TOKEN_PRIVILEGES priv
;
6722 DWORD priv_size
= sizeof (priv
);
6723 DWORD opriv_size
= sizeof (*old_priv
);
6724 HANDLE h_token
= NULL
;
6725 HANDLE h_thread
= GetCurrentThread ();
6729 res
= open_thread_token (h_thread
,
6730 TOKEN_QUERY
| TOKEN_ADJUST_PRIVILEGES
,
6732 if (!res
&& GetLastError () == ERROR_NO_TOKEN
)
6734 if (impersonate_self (SecurityImpersonation
))
6735 res
= open_thread_token (h_thread
,
6736 TOKEN_QUERY
| TOKEN_ADJUST_PRIVILEGES
,
6741 priv
.PrivilegeCount
= 1;
6742 priv
.Privileges
[0].Attributes
= enable_p
? SE_PRIVILEGE_ENABLED
: 0;
6743 LookupPrivilegeValue (NULL
, priv_name
, &priv
.Privileges
[0].Luid
);
6744 if (AdjustTokenPrivileges (h_token
, FALSE
, &priv
, priv_size
,
6745 old_priv
, &opriv_size
)
6746 && GetLastError () != ERROR_NOT_ALL_ASSIGNED
)
6750 CloseHandle (h_token
);
6756 restore_privilege (TOKEN_PRIVILEGES
*priv
)
6758 DWORD priv_size
= sizeof (*priv
);
6759 HANDLE h_token
= NULL
;
6762 if (open_thread_token (GetCurrentThread (),
6763 TOKEN_QUERY
| TOKEN_ADJUST_PRIVILEGES
,
6766 if (AdjustTokenPrivileges (h_token
, FALSE
, priv
, priv_size
, NULL
, NULL
)
6767 && GetLastError () != ERROR_NOT_ALL_ASSIGNED
)
6771 CloseHandle (h_token
);
6777 ltime (ULONGLONG time_100ns
)
6779 ULONGLONG time_sec
= time_100ns
/ 10000000;
6780 int subsec
= time_100ns
% 10000000;
6781 return list4i (time_sec
>> 16, time_sec
& 0xffff,
6782 subsec
/ 10, subsec
% 10 * 100000);
6785 #define U64_TO_LISP_TIME(time) ltime (time)
6788 process_times (HANDLE h_proc
, Lisp_Object
*ctime
, Lisp_Object
*etime
,
6789 Lisp_Object
*stime
, Lisp_Object
*utime
, Lisp_Object
*ttime
,
6792 FILETIME ft_creation
, ft_exit
, ft_kernel
, ft_user
, ft_current
;
6793 ULONGLONG tem1
, tem2
, tem3
, tem
;
6796 || !get_process_times_fn
6797 || !(*get_process_times_fn
) (h_proc
, &ft_creation
, &ft_exit
,
6798 &ft_kernel
, &ft_user
))
6801 GetSystemTimeAsFileTime (&ft_current
);
6803 FILETIME_TO_U64 (tem1
, ft_kernel
);
6804 *stime
= U64_TO_LISP_TIME (tem1
);
6806 FILETIME_TO_U64 (tem2
, ft_user
);
6807 *utime
= U64_TO_LISP_TIME (tem2
);
6810 *ttime
= U64_TO_LISP_TIME (tem3
);
6812 FILETIME_TO_U64 (tem
, ft_creation
);
6813 /* Process no 4 (System) returns zero creation time. */
6816 *ctime
= U64_TO_LISP_TIME (tem
);
6820 FILETIME_TO_U64 (tem3
, ft_current
);
6821 tem
= (tem3
- utc_base
) - tem
;
6823 *etime
= U64_TO_LISP_TIME (tem
);
6827 *pcpu
= 100.0 * (tem1
+ tem2
) / tem
;
6838 system_process_attributes (Lisp_Object pid
)
6840 Lisp_Object attrs
= Qnil
;
6841 Lisp_Object cmd_str
, decoded_cmd
, tem
;
6842 HANDLE h_snapshot
, h_proc
;
6845 char uname
[UNLEN
+1], gname
[GNLEN
+1], domain
[1025];
6846 DWORD ulength
= sizeof (uname
), dlength
= sizeof (domain
), needed
;
6847 DWORD glength
= sizeof (gname
);
6848 HANDLE token
= NULL
;
6849 SID_NAME_USE user_type
;
6850 unsigned char *buf
= NULL
;
6852 TOKEN_USER user_token
;
6853 TOKEN_PRIMARY_GROUP group_token
;
6856 PROCESS_MEMORY_COUNTERS mem
;
6857 PROCESS_MEMORY_COUNTERS_EX mem_ex
;
6858 SIZE_T minrss
, maxrss
;
6860 MEMORY_STATUS_EX memstex
;
6861 double totphys
= 0.0;
6862 Lisp_Object ctime
, stime
, utime
, etime
, ttime
;
6864 BOOL result
= FALSE
;
6866 CHECK_NUMBER_OR_FLOAT (pid
);
6867 proc_id
= FLOATP (pid
) ? XFLOAT_DATA (pid
) : XINT (pid
);
6869 h_snapshot
= create_toolhelp32_snapshot (TH32CS_SNAPPROCESS
, 0);
6871 if (h_snapshot
!= INVALID_HANDLE_VALUE
)
6876 pe
.dwSize
= sizeof (PROCESSENTRY32
);
6877 for (res
= process32_first (h_snapshot
, &pe
); res
;
6878 res
= process32_next (h_snapshot
, &pe
))
6880 if (proc_id
== pe
.th32ProcessID
)
6883 decoded_cmd
= build_string ("Idle");
6886 /* Decode the command name from locale-specific
6888 cmd_str
= build_unibyte_string (pe
.szExeFile
);
6891 code_convert_string_norecord (cmd_str
,
6892 Vlocale_coding_system
, 0);
6894 attrs
= Fcons (Fcons (Qcomm
, decoded_cmd
), attrs
);
6895 attrs
= Fcons (Fcons (Qppid
,
6896 make_fixnum_or_float (pe
.th32ParentProcessID
)),
6898 attrs
= Fcons (Fcons (Qpri
, make_number (pe
.pcPriClassBase
)),
6900 attrs
= Fcons (Fcons (Qthcount
,
6901 make_fixnum_or_float (pe
.cntThreads
)),
6908 CloseHandle (h_snapshot
);
6914 h_proc
= OpenProcess (PROCESS_QUERY_INFORMATION
| PROCESS_VM_READ
,
6916 /* If we were denied a handle to the process, try again after
6917 enabling the SeDebugPrivilege in our process. */
6920 TOKEN_PRIVILEGES priv_current
;
6922 if (enable_privilege (SE_DEBUG_NAME
, TRUE
, &priv_current
))
6924 h_proc
= OpenProcess (PROCESS_QUERY_INFORMATION
| PROCESS_VM_READ
,
6926 restore_privilege (&priv_current
);
6932 result
= open_process_token (h_proc
, TOKEN_QUERY
, &token
);
6935 result
= get_token_information (token
, TokenUser
, NULL
, 0, &blen
);
6936 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
6938 buf
= xmalloc (blen
);
6939 result
= get_token_information (token
, TokenUser
,
6940 (LPVOID
)buf
, blen
, &needed
);
6943 memcpy (&user_token
, buf
, sizeof (user_token
));
6944 if (!w32_cached_id (user_token
.User
.Sid
, &euid
, uname
))
6946 euid
= get_rid (user_token
.User
.Sid
);
6947 result
= lookup_account_sid (NULL
, user_token
.User
.Sid
,
6952 w32_add_to_cache (user_token
.User
.Sid
, euid
, uname
);
6955 strcpy (uname
, "unknown");
6959 ulength
= strlen (uname
);
6965 /* Determine a reasonable euid and gid values. */
6966 if (xstrcasecmp ("administrator", uname
) == 0)
6968 euid
= 500; /* well-known Administrator uid */
6969 egid
= 513; /* well-known None gid */
6973 /* Get group id and name. */
6974 result
= get_token_information (token
, TokenPrimaryGroup
,
6975 (LPVOID
)buf
, blen
, &needed
);
6976 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
6978 buf
= xrealloc (buf
, blen
= needed
);
6979 result
= get_token_information (token
, TokenPrimaryGroup
,
6980 (LPVOID
)buf
, blen
, &needed
);
6984 memcpy (&group_token
, buf
, sizeof (group_token
));
6985 if (!w32_cached_id (group_token
.PrimaryGroup
, &egid
, gname
))
6987 egid
= get_rid (group_token
.PrimaryGroup
);
6988 dlength
= sizeof (domain
);
6990 lookup_account_sid (NULL
, group_token
.PrimaryGroup
,
6991 gname
, &glength
, NULL
, &dlength
,
6994 w32_add_to_cache (group_token
.PrimaryGroup
,
6998 strcpy (gname
, "None");
7002 glength
= strlen (gname
);
7010 if (!is_windows_9x ())
7012 /* We couldn't open the process token, presumably because of
7013 insufficient access rights. Assume this process is run
7015 strcpy (uname
, "SYSTEM");
7016 strcpy (gname
, "None");
7017 euid
= 18; /* SYSTEM */
7018 egid
= 513; /* None */
7019 glength
= strlen (gname
);
7020 ulength
= strlen (uname
);
7022 /* If we are running under Windows 9X, where security calls are
7023 not supported, we assume all processes are run by the current
7025 else if (GetUserName (uname
, &ulength
))
7027 if (xstrcasecmp ("administrator", uname
) == 0)
7032 strcpy (gname
, "None");
7033 glength
= strlen (gname
);
7034 ulength
= strlen (uname
);
7040 strcpy (uname
, "administrator");
7041 ulength
= strlen (uname
);
7042 strcpy (gname
, "None");
7043 glength
= strlen (gname
);
7046 CloseHandle (token
);
7049 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (euid
)), attrs
);
7050 tem
= make_unibyte_string (uname
, ulength
);
7051 attrs
= Fcons (Fcons (Quser
,
7052 code_convert_string_norecord (tem
, Vlocale_coding_system
, 0)),
7054 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (egid
)), attrs
);
7055 tem
= make_unibyte_string (gname
, glength
);
7056 attrs
= Fcons (Fcons (Qgroup
,
7057 code_convert_string_norecord (tem
, Vlocale_coding_system
, 0)),
7060 if (global_memory_status_ex (&memstex
))
7061 #if __GNUC__ || (defined (_MSC_VER) && _MSC_VER >= 1300)
7062 totphys
= memstex
.ullTotalPhys
/ 1024.0;
7064 /* Visual Studio 6 cannot convert an unsigned __int64 type to
7065 double, so we need to do this for it... */
7067 DWORD tot_hi
= memstex
.ullTotalPhys
>> 32;
7068 DWORD tot_md
= (memstex
.ullTotalPhys
& 0x00000000ffffffff) >> 10;
7069 DWORD tot_lo
= memstex
.ullTotalPhys
% 1024;
7071 totphys
= tot_hi
* 4194304.0 + tot_md
+ tot_lo
/ 1024.0;
7073 #endif /* __GNUC__ || _MSC_VER >= 1300 */
7074 else if (global_memory_status (&memst
))
7075 totphys
= memst
.dwTotalPhys
/ 1024.0;
7078 && get_process_memory_info (h_proc
, (PROCESS_MEMORY_COUNTERS
*)&mem_ex
,
7081 SIZE_T rss
= mem_ex
.WorkingSetSize
/ 1024;
7083 attrs
= Fcons (Fcons (Qmajflt
,
7084 make_fixnum_or_float (mem_ex
.PageFaultCount
)),
7086 attrs
= Fcons (Fcons (Qvsize
,
7087 make_fixnum_or_float (mem_ex
.PrivateUsage
/ 1024)),
7089 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (rss
)), attrs
);
7091 attrs
= Fcons (Fcons (Qpmem
, make_float (100. * rss
/ totphys
)), attrs
);
7094 && get_process_memory_info (h_proc
, &mem
, sizeof (mem
)))
7096 SIZE_T rss
= mem_ex
.WorkingSetSize
/ 1024;
7098 attrs
= Fcons (Fcons (Qmajflt
,
7099 make_fixnum_or_float (mem
.PageFaultCount
)),
7101 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (rss
)), attrs
);
7103 attrs
= Fcons (Fcons (Qpmem
, make_float (100. * rss
/ totphys
)), attrs
);
7106 && get_process_working_set_size (h_proc
, &minrss
, &maxrss
))
7108 DWORD rss
= maxrss
/ 1024;
7110 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (maxrss
/ 1024)), attrs
);
7112 attrs
= Fcons (Fcons (Qpmem
, make_float (100. * rss
/ totphys
)), attrs
);
7115 if (process_times (h_proc
, &ctime
, &etime
, &stime
, &utime
, &ttime
, &pcpu
))
7117 attrs
= Fcons (Fcons (Qutime
, utime
), attrs
);
7118 attrs
= Fcons (Fcons (Qstime
, stime
), attrs
);
7119 attrs
= Fcons (Fcons (Qtime
, ttime
), attrs
);
7120 attrs
= Fcons (Fcons (Qstart
, ctime
), attrs
);
7121 attrs
= Fcons (Fcons (Qetime
, etime
), attrs
);
7122 attrs
= Fcons (Fcons (Qpcpu
, make_float (pcpu
)), attrs
);
7125 /* FIXME: Retrieve command line by walking the PEB of the process. */
7128 CloseHandle (h_proc
);
7133 w32_memory_info (unsigned long long *totalram
, unsigned long long *freeram
,
7134 unsigned long long *totalswap
, unsigned long long *freeswap
)
7137 MEMORY_STATUS_EX memstex
;
7139 /* Use GlobalMemoryStatusEx if available, as it can report more than
7141 if (global_memory_status_ex (&memstex
))
7143 *totalram
= memstex
.ullTotalPhys
;
7144 *freeram
= memstex
.ullAvailPhys
;
7145 *totalswap
= memstex
.ullTotalPageFile
;
7146 *freeswap
= memstex
.ullAvailPageFile
;
7149 else if (global_memory_status (&memst
))
7151 *totalram
= memst
.dwTotalPhys
;
7152 *freeram
= memst
.dwAvailPhys
;
7153 *totalswap
= memst
.dwTotalPageFile
;
7154 *freeswap
= memst
.dwAvailPageFile
;
7162 /* Wrappers for winsock functions to map between our file descriptors
7163 and winsock's handles; also set h_errno for convenience.
7165 To allow Emacs to run on systems which don't have winsock support
7166 installed, we dynamically link to winsock on startup if present, and
7167 otherwise provide the minimum necessary functionality
7168 (eg. gethostname). */
7170 /* function pointers for relevant socket functions */
7171 int (PASCAL
*pfn_WSAStartup
) (WORD wVersionRequired
, LPWSADATA lpWSAData
);
7172 void (PASCAL
*pfn_WSASetLastError
) (int iError
);
7173 int (PASCAL
*pfn_WSAGetLastError
) (void);
7174 int (PASCAL
*pfn_WSAEventSelect
) (SOCKET s
, HANDLE hEventObject
, long lNetworkEvents
);
7175 int (PASCAL
*pfn_WSAEnumNetworkEvents
) (SOCKET s
, HANDLE hEventObject
,
7176 WSANETWORKEVENTS
*NetworkEvents
);
7178 HANDLE (PASCAL
*pfn_WSACreateEvent
) (void);
7179 int (PASCAL
*pfn_WSACloseEvent
) (HANDLE hEvent
);
7180 int (PASCAL
*pfn_socket
) (int af
, int type
, int protocol
);
7181 int (PASCAL
*pfn_bind
) (SOCKET s
, const struct sockaddr
*addr
, int namelen
);
7182 int (PASCAL
*pfn_connect
) (SOCKET s
, const struct sockaddr
*addr
, int namelen
);
7183 int (PASCAL
*pfn_ioctlsocket
) (SOCKET s
, long cmd
, u_long
*argp
);
7184 int (PASCAL
*pfn_recv
) (SOCKET s
, char * buf
, int len
, int flags
);
7185 int (PASCAL
*pfn_send
) (SOCKET s
, const char * buf
, int len
, int flags
);
7186 int (PASCAL
*pfn_closesocket
) (SOCKET s
);
7187 int (PASCAL
*pfn_shutdown
) (SOCKET s
, int how
);
7188 int (PASCAL
*pfn_WSACleanup
) (void);
7190 u_short (PASCAL
*pfn_htons
) (u_short hostshort
);
7191 u_short (PASCAL
*pfn_ntohs
) (u_short netshort
);
7192 unsigned long (PASCAL
*pfn_inet_addr
) (const char * cp
);
7193 int (PASCAL
*pfn_gethostname
) (char * name
, int namelen
);
7194 struct hostent
* (PASCAL
*pfn_gethostbyname
) (const char * name
);
7195 struct servent
* (PASCAL
*pfn_getservbyname
) (const char * name
, const char * proto
);
7196 int (PASCAL
*pfn_getpeername
) (SOCKET s
, struct sockaddr
*addr
, int * namelen
);
7197 int (PASCAL
*pfn_setsockopt
) (SOCKET s
, int level
, int optname
,
7198 const char * optval
, int optlen
);
7199 int (PASCAL
*pfn_listen
) (SOCKET s
, int backlog
);
7200 int (PASCAL
*pfn_getsockname
) (SOCKET s
, struct sockaddr
* name
,
7202 SOCKET (PASCAL
*pfn_accept
) (SOCKET s
, struct sockaddr
* addr
, int * addrlen
);
7203 int (PASCAL
*pfn_recvfrom
) (SOCKET s
, char * buf
, int len
, int flags
,
7204 struct sockaddr
* from
, int * fromlen
);
7205 int (PASCAL
*pfn_sendto
) (SOCKET s
, const char * buf
, int len
, int flags
,
7206 const struct sockaddr
* to
, int tolen
);
7208 /* SetHandleInformation is only needed to make sockets non-inheritable. */
7209 BOOL (WINAPI
*pfn_SetHandleInformation
) (HANDLE object
, DWORD mask
, DWORD flags
);
7210 #ifndef HANDLE_FLAG_INHERIT
7211 #define HANDLE_FLAG_INHERIT 1
7215 static int winsock_inuse
;
7220 if (winsock_lib
!= NULL
&& winsock_inuse
== 0)
7222 release_listen_threads ();
7223 /* Not sure what would cause WSAENETDOWN, or even if it can happen
7224 after WSAStartup returns successfully, but it seems reasonable
7225 to allow unloading winsock anyway in that case. */
7226 if (pfn_WSACleanup () == 0 ||
7227 pfn_WSAGetLastError () == WSAENETDOWN
)
7229 if (FreeLibrary (winsock_lib
))
7238 init_winsock (int load_now
)
7240 WSADATA winsockData
;
7242 if (winsock_lib
!= NULL
)
7245 pfn_SetHandleInformation
7246 = (void *) GetProcAddress (GetModuleHandle ("kernel32.dll"),
7247 "SetHandleInformation");
7249 winsock_lib
= LoadLibrary ("Ws2_32.dll");
7251 if (winsock_lib
!= NULL
)
7253 /* dynamically link to socket functions */
7255 #define LOAD_PROC(fn) \
7256 if ((pfn_##fn = (void *) GetProcAddress (winsock_lib, #fn)) == NULL) \
7259 LOAD_PROC (WSAStartup
);
7260 LOAD_PROC (WSASetLastError
);
7261 LOAD_PROC (WSAGetLastError
);
7262 LOAD_PROC (WSAEventSelect
);
7263 LOAD_PROC (WSAEnumNetworkEvents
);
7264 LOAD_PROC (WSACreateEvent
);
7265 LOAD_PROC (WSACloseEvent
);
7268 LOAD_PROC (connect
);
7269 LOAD_PROC (ioctlsocket
);
7272 LOAD_PROC (closesocket
);
7273 LOAD_PROC (shutdown
);
7276 LOAD_PROC (inet_addr
);
7277 LOAD_PROC (gethostname
);
7278 LOAD_PROC (gethostbyname
);
7279 LOAD_PROC (getservbyname
);
7280 LOAD_PROC (getpeername
);
7281 LOAD_PROC (WSACleanup
);
7282 LOAD_PROC (setsockopt
);
7284 LOAD_PROC (getsockname
);
7286 LOAD_PROC (recvfrom
);
7290 /* specify version 1.1 of winsock */
7291 if (pfn_WSAStartup (0x101, &winsockData
) == 0)
7293 if (winsockData
.wVersion
!= 0x101)
7298 /* Report that winsock exists and is usable, but leave
7299 socket functions disabled. I am assuming that calling
7300 WSAStartup does not require any network interaction,
7301 and in particular does not cause or require a dial-up
7302 connection to be established. */
7305 FreeLibrary (winsock_lib
);
7313 FreeLibrary (winsock_lib
);
7323 /* Function to map winsock error codes to errno codes for those errno
7324 code defined in errno.h (errno values not defined by errno.h are
7325 already in nt/inc/sys/socket.h). */
7332 if (winsock_lib
== NULL
)
7335 wsa_err
= pfn_WSAGetLastError ();
7339 case WSAEACCES
: errno
= EACCES
; break;
7340 case WSAEBADF
: errno
= EBADF
; break;
7341 case WSAEFAULT
: errno
= EFAULT
; break;
7342 case WSAEINTR
: errno
= EINTR
; break;
7343 case WSAEINVAL
: errno
= EINVAL
; break;
7344 case WSAEMFILE
: errno
= EMFILE
; break;
7345 case WSAENAMETOOLONG
: errno
= ENAMETOOLONG
; break;
7346 case WSAENOTEMPTY
: errno
= ENOTEMPTY
; break;
7347 case WSAEWOULDBLOCK
: errno
= EWOULDBLOCK
; break;
7348 case WSAENOTCONN
: errno
= ENOTCONN
; break;
7349 default: errno
= wsa_err
; break;
7357 if (winsock_lib
!= NULL
)
7358 pfn_WSASetLastError (0);
7361 /* Extend strerror to handle the winsock-specific error codes. */
7365 } _wsa_errlist
[] = {
7366 {WSAEINTR
, "Interrupted function call"},
7367 {WSAEBADF
, "Bad file descriptor"},
7368 {WSAEACCES
, "Permission denied"},
7369 {WSAEFAULT
, "Bad address"},
7370 {WSAEINVAL
, "Invalid argument"},
7371 {WSAEMFILE
, "Too many open files"},
7373 {WSAEWOULDBLOCK
, "Resource temporarily unavailable"},
7374 {WSAEINPROGRESS
, "Operation now in progress"},
7375 {WSAEALREADY
, "Operation already in progress"},
7376 {WSAENOTSOCK
, "Socket operation on non-socket"},
7377 {WSAEDESTADDRREQ
, "Destination address required"},
7378 {WSAEMSGSIZE
, "Message too long"},
7379 {WSAEPROTOTYPE
, "Protocol wrong type for socket"},
7380 {WSAENOPROTOOPT
, "Bad protocol option"},
7381 {WSAEPROTONOSUPPORT
, "Protocol not supported"},
7382 {WSAESOCKTNOSUPPORT
, "Socket type not supported"},
7383 {WSAEOPNOTSUPP
, "Operation not supported"},
7384 {WSAEPFNOSUPPORT
, "Protocol family not supported"},
7385 {WSAEAFNOSUPPORT
, "Address family not supported by protocol family"},
7386 {WSAEADDRINUSE
, "Address already in use"},
7387 {WSAEADDRNOTAVAIL
, "Cannot assign requested address"},
7388 {WSAENETDOWN
, "Network is down"},
7389 {WSAENETUNREACH
, "Network is unreachable"},
7390 {WSAENETRESET
, "Network dropped connection on reset"},
7391 {WSAECONNABORTED
, "Software caused connection abort"},
7392 {WSAECONNRESET
, "Connection reset by peer"},
7393 {WSAENOBUFS
, "No buffer space available"},
7394 {WSAEISCONN
, "Socket is already connected"},
7395 {WSAENOTCONN
, "Socket is not connected"},
7396 {WSAESHUTDOWN
, "Cannot send after socket shutdown"},
7397 {WSAETOOMANYREFS
, "Too many references"}, /* not sure */
7398 {WSAETIMEDOUT
, "Connection timed out"},
7399 {WSAECONNREFUSED
, "Connection refused"},
7400 {WSAELOOP
, "Network loop"}, /* not sure */
7401 {WSAENAMETOOLONG
, "Name is too long"},
7402 {WSAEHOSTDOWN
, "Host is down"},
7403 {WSAEHOSTUNREACH
, "No route to host"},
7404 {WSAENOTEMPTY
, "Buffer not empty"}, /* not sure */
7405 {WSAEPROCLIM
, "Too many processes"},
7406 {WSAEUSERS
, "Too many users"}, /* not sure */
7407 {WSAEDQUOT
, "Double quote in host name"}, /* really not sure */
7408 {WSAESTALE
, "Data is stale"}, /* not sure */
7409 {WSAEREMOTE
, "Remote error"}, /* not sure */
7411 {WSASYSNOTREADY
, "Network subsystem is unavailable"},
7412 {WSAVERNOTSUPPORTED
, "WINSOCK.DLL version out of range"},
7413 {WSANOTINITIALISED
, "Winsock not initialized successfully"},
7414 {WSAEDISCON
, "Graceful shutdown in progress"},
7416 {WSAENOMORE
, "No more operations allowed"}, /* not sure */
7417 {WSAECANCELLED
, "Operation cancelled"}, /* not sure */
7418 {WSAEINVALIDPROCTABLE
, "Invalid procedure table from service provider"},
7419 {WSAEINVALIDPROVIDER
, "Invalid service provider version number"},
7420 {WSAEPROVIDERFAILEDINIT
, "Unable to initialize a service provider"},
7421 {WSASYSCALLFAILURE
, "System call failure"},
7422 {WSASERVICE_NOT_FOUND
, "Service not found"}, /* not sure */
7423 {WSATYPE_NOT_FOUND
, "Class type not found"},
7424 {WSA_E_NO_MORE
, "No more resources available"}, /* really not sure */
7425 {WSA_E_CANCELLED
, "Operation already cancelled"}, /* really not sure */
7426 {WSAEREFUSED
, "Operation refused"}, /* not sure */
7429 {WSAHOST_NOT_FOUND
, "Host not found"},
7430 {WSATRY_AGAIN
, "Authoritative host not found during name lookup"},
7431 {WSANO_RECOVERY
, "Non-recoverable error during name lookup"},
7432 {WSANO_DATA
, "Valid name, no data record of requested type"},
7438 sys_strerror (int error_no
)
7441 static char unknown_msg
[40];
7443 if (error_no
>= 0 && error_no
< sys_nerr
)
7444 return sys_errlist
[error_no
];
7446 for (i
= 0; _wsa_errlist
[i
].errnum
>= 0; i
++)
7447 if (_wsa_errlist
[i
].errnum
== error_no
)
7448 return _wsa_errlist
[i
].msg
;
7450 sprintf (unknown_msg
, "Unidentified error: %d", error_no
);
7454 /* [andrewi 3-May-96] I've had conflicting results using both methods,
7455 but I believe the method of keeping the socket handle separate (and
7456 insuring it is not inheritable) is the correct one. */
7458 #define SOCK_HANDLE(fd) ((SOCKET) fd_info[fd].hnd)
7460 static int socket_to_fd (SOCKET s
);
7463 sys_socket (int af
, int type
, int protocol
)
7467 if (winsock_lib
== NULL
)
7475 /* call the real socket function */
7476 s
= pfn_socket (af
, type
, protocol
);
7478 if (s
!= INVALID_SOCKET
)
7479 return socket_to_fd (s
);
7485 /* Convert a SOCKET to a file descriptor. */
7487 socket_to_fd (SOCKET s
)
7492 /* Although under NT 3.5 _open_osfhandle will accept a socket
7493 handle, if opened with SO_OPENTYPE == SO_SYNCHRONOUS_NONALERT,
7494 that does not work under NT 3.1. However, we can get the same
7495 effect by using a backdoor function to replace an existing
7496 descriptor handle with the one we want. */
7498 /* allocate a file descriptor (with appropriate flags) */
7499 fd
= _open ("NUL:", _O_RDWR
);
7502 /* Make a non-inheritable copy of the socket handle. Note
7503 that it is possible that sockets aren't actually kernel
7504 handles, which appears to be the case on Windows 9x when
7505 the MS Proxy winsock client is installed. */
7507 /* Apparently there is a bug in NT 3.51 with some service
7508 packs, which prevents using DuplicateHandle to make a
7509 socket handle non-inheritable (causes WSACleanup to
7510 hang). The work-around is to use SetHandleInformation
7511 instead if it is available and implemented. */
7512 if (pfn_SetHandleInformation
)
7514 pfn_SetHandleInformation ((HANDLE
) s
, HANDLE_FLAG_INHERIT
, 0);
7518 HANDLE parent
= GetCurrentProcess ();
7519 HANDLE new_s
= INVALID_HANDLE_VALUE
;
7521 if (DuplicateHandle (parent
,
7527 DUPLICATE_SAME_ACCESS
))
7529 /* It is possible that DuplicateHandle succeeds even
7530 though the socket wasn't really a kernel handle,
7531 because a real handle has the same value. So
7532 test whether the new handle really is a socket. */
7533 unsigned long nonblocking
= 0;
7534 if (pfn_ioctlsocket ((SOCKET
) new_s
, FIONBIO
, &nonblocking
) == 0)
7536 pfn_closesocket (s
);
7541 CloseHandle (new_s
);
7546 eassert (fd
< MAXDESC
);
7547 fd_info
[fd
].hnd
= (HANDLE
) s
;
7549 /* set our own internal flags */
7550 fd_info
[fd
].flags
= FILE_SOCKET
| FILE_BINARY
| FILE_READ
| FILE_WRITE
;
7556 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
7558 /* attach child_process to fd_info */
7559 if (fd_info
[ fd
].cp
!= NULL
)
7561 DebPrint (("sys_socket: fd_info[%d] apparently in use!\n", fd
));
7565 fd_info
[ fd
].cp
= cp
;
7568 winsock_inuse
++; /* count open sockets */
7576 pfn_closesocket (s
);
7582 sys_bind (int s
, const struct sockaddr
* addr
, int namelen
)
7584 if (winsock_lib
== NULL
)
7587 return SOCKET_ERROR
;
7591 if (fd_info
[s
].flags
& FILE_SOCKET
)
7593 int rc
= pfn_bind (SOCK_HANDLE (s
), addr
, namelen
);
7594 if (rc
== SOCKET_ERROR
)
7599 return SOCKET_ERROR
;
7603 sys_connect (int s
, const struct sockaddr
* name
, int namelen
)
7605 if (winsock_lib
== NULL
)
7608 return SOCKET_ERROR
;
7612 if (fd_info
[s
].flags
& FILE_SOCKET
)
7614 int rc
= pfn_connect (SOCK_HANDLE (s
), name
, namelen
);
7615 if (rc
== SOCKET_ERROR
)
7618 /* If this is a non-blocking 'connect', set the bit in flags
7619 that will tell reader_thread to wait for connection
7620 before trying to read. */
7621 if (errno
== EWOULDBLOCK
&& (fd_info
[s
].flags
& FILE_NDELAY
) != 0)
7623 errno
= EINPROGRESS
; /* that's what process.c expects */
7624 fd_info
[s
].flags
|= FILE_CONNECT
;
7630 return SOCKET_ERROR
;
7634 sys_htons (u_short hostshort
)
7636 return (winsock_lib
!= NULL
) ?
7637 pfn_htons (hostshort
) : hostshort
;
7641 sys_ntohs (u_short netshort
)
7643 return (winsock_lib
!= NULL
) ?
7644 pfn_ntohs (netshort
) : netshort
;
7648 sys_inet_addr (const char * cp
)
7650 return (winsock_lib
!= NULL
) ?
7651 pfn_inet_addr (cp
) : INADDR_NONE
;
7655 sys_gethostname (char * name
, int namelen
)
7657 if (winsock_lib
!= NULL
)
7662 retval
= pfn_gethostname (name
, namelen
);
7663 if (retval
== SOCKET_ERROR
)
7668 if (namelen
> MAX_COMPUTERNAME_LENGTH
)
7669 return !GetComputerName (name
, (DWORD
*)&namelen
);
7672 return SOCKET_ERROR
;
7676 sys_gethostbyname (const char * name
)
7678 struct hostent
* host
;
7679 int h_err
= h_errno
;
7681 if (winsock_lib
== NULL
)
7683 h_errno
= NO_RECOVERY
;
7689 host
= pfn_gethostbyname (name
);
7701 sys_getservbyname (const char * name
, const char * proto
)
7703 struct servent
* serv
;
7705 if (winsock_lib
== NULL
)
7712 serv
= pfn_getservbyname (name
, proto
);
7719 sys_getpeername (int s
, struct sockaddr
*addr
, int * namelen
)
7721 if (winsock_lib
== NULL
)
7724 return SOCKET_ERROR
;
7728 if (fd_info
[s
].flags
& FILE_SOCKET
)
7730 int rc
= pfn_getpeername (SOCK_HANDLE (s
), addr
, namelen
);
7731 if (rc
== SOCKET_ERROR
)
7736 return SOCKET_ERROR
;
7740 sys_shutdown (int s
, int how
)
7742 if (winsock_lib
== NULL
)
7745 return SOCKET_ERROR
;
7749 if (fd_info
[s
].flags
& FILE_SOCKET
)
7751 int rc
= pfn_shutdown (SOCK_HANDLE (s
), how
);
7752 if (rc
== SOCKET_ERROR
)
7757 return SOCKET_ERROR
;
7761 sys_setsockopt (int s
, int level
, int optname
, const void * optval
, int optlen
)
7763 if (winsock_lib
== NULL
)
7766 return SOCKET_ERROR
;
7770 if (fd_info
[s
].flags
& FILE_SOCKET
)
7772 int rc
= pfn_setsockopt (SOCK_HANDLE (s
), level
, optname
,
7773 (const char *)optval
, optlen
);
7774 if (rc
== SOCKET_ERROR
)
7779 return SOCKET_ERROR
;
7783 sys_listen (int s
, int backlog
)
7785 if (winsock_lib
== NULL
)
7788 return SOCKET_ERROR
;
7792 if (fd_info
[s
].flags
& FILE_SOCKET
)
7794 int rc
= pfn_listen (SOCK_HANDLE (s
), backlog
);
7795 if (rc
== SOCKET_ERROR
)
7798 fd_info
[s
].flags
|= FILE_LISTEN
;
7802 return SOCKET_ERROR
;
7806 sys_getsockname (int s
, struct sockaddr
* name
, int * namelen
)
7808 if (winsock_lib
== NULL
)
7811 return SOCKET_ERROR
;
7815 if (fd_info
[s
].flags
& FILE_SOCKET
)
7817 int rc
= pfn_getsockname (SOCK_HANDLE (s
), name
, namelen
);
7818 if (rc
== SOCKET_ERROR
)
7823 return SOCKET_ERROR
;
7827 sys_accept (int s
, struct sockaddr
* addr
, int * addrlen
)
7829 if (winsock_lib
== NULL
)
7836 if (fd_info
[s
].flags
& FILE_LISTEN
)
7838 SOCKET t
= pfn_accept (SOCK_HANDLE (s
), addr
, addrlen
);
7840 if (t
== INVALID_SOCKET
)
7843 fd
= socket_to_fd (t
);
7847 fd_info
[s
].cp
->status
= STATUS_READ_ACKNOWLEDGED
;
7848 ResetEvent (fd_info
[s
].cp
->char_avail
);
7857 sys_recvfrom (int s
, char * buf
, int len
, int flags
,
7858 struct sockaddr
* from
, int * fromlen
)
7860 if (winsock_lib
== NULL
)
7863 return SOCKET_ERROR
;
7867 if (fd_info
[s
].flags
& FILE_SOCKET
)
7869 int rc
= pfn_recvfrom (SOCK_HANDLE (s
), buf
, len
, flags
, from
, fromlen
);
7870 if (rc
== SOCKET_ERROR
)
7875 return SOCKET_ERROR
;
7879 sys_sendto (int s
, const char * buf
, int len
, int flags
,
7880 const struct sockaddr
* to
, int tolen
)
7882 if (winsock_lib
== NULL
)
7885 return SOCKET_ERROR
;
7889 if (fd_info
[s
].flags
& FILE_SOCKET
)
7891 int rc
= pfn_sendto (SOCK_HANDLE (s
), buf
, len
, flags
, to
, tolen
);
7892 if (rc
== SOCKET_ERROR
)
7897 return SOCKET_ERROR
;
7900 /* Windows does not have an fcntl function. Provide an implementation
7901 good enough for Emacs. */
7903 fcntl (int s
, int cmd
, int options
)
7905 /* In the w32 Emacs port, fcntl (fd, F_DUPFD_CLOEXEC, fd1) is always
7906 invoked in a context where fd1 is closed and all descriptors less
7907 than fd1 are open, so sys_dup is an adequate implementation. */
7908 if (cmd
== F_DUPFD_CLOEXEC
)
7912 if (fd_info
[s
].flags
& FILE_SOCKET
)
7914 if (winsock_lib
== NULL
)
7920 if (cmd
== F_SETFL
&& options
== O_NONBLOCK
)
7922 unsigned long nblock
= 1;
7923 int rc
= pfn_ioctlsocket (SOCK_HANDLE (s
), FIONBIO
, &nblock
);
7924 if (rc
== SOCKET_ERROR
)
7926 /* Keep track of the fact that we set this to non-blocking. */
7927 fd_info
[s
].flags
|= FILE_NDELAY
;
7933 return SOCKET_ERROR
;
7936 else if ((fd_info
[s
].flags
& (FILE_PIPE
| FILE_WRITE
))
7937 == (FILE_PIPE
| FILE_WRITE
))
7939 /* Force our writes to pipes be non-blocking. */
7940 if (cmd
== F_SETFL
&& options
== O_NONBLOCK
)
7942 HANDLE h
= (HANDLE
)_get_osfhandle (s
);
7943 DWORD pipe_mode
= PIPE_NOWAIT
;
7945 if (!SetNamedPipeHandleState (h
, &pipe_mode
, NULL
, NULL
))
7947 DebPrint (("SetNamedPipeHandleState: %lu\n", GetLastError ()));
7948 return SOCKET_ERROR
;
7950 fd_info
[s
].flags
|= FILE_NDELAY
;
7956 return SOCKET_ERROR
;
7960 return SOCKET_ERROR
;
7964 /* Shadow main io functions: we need to handle pipes and sockets more
7978 if (fd
< MAXDESC
&& fd_info
[fd
].cp
)
7980 child_process
* cp
= fd_info
[fd
].cp
;
7982 fd_info
[fd
].cp
= NULL
;
7984 if (CHILD_ACTIVE (cp
))
7986 /* if last descriptor to active child_process then cleanup */
7988 for (i
= 0; i
< MAXDESC
; i
++)
7992 if (fd_info
[i
].cp
== cp
)
7997 if (fd_info
[fd
].flags
& FILE_SOCKET
)
7999 if (winsock_lib
== NULL
) emacs_abort ();
8001 pfn_shutdown (SOCK_HANDLE (fd
), 2);
8002 rc
= pfn_closesocket (SOCK_HANDLE (fd
));
8004 winsock_inuse
--; /* count open sockets */
8006 /* If the process handle is NULL, it's either a socket
8007 or serial connection, or a subprocess that was
8008 already reaped by reap_subprocess, but whose
8009 resources were not yet freed, because its output was
8010 not fully read yet by the time it was reaped. (This
8011 usually happens with async subprocesses whose output
8012 is being read by Emacs.) Otherwise, this process was
8013 not reaped yet, so we set its FD to a negative value
8014 to make sure sys_select will eventually get to
8015 calling the SIGCHLD handler for it, which will then
8016 invoke waitpid and reap_subprocess. */
8017 if (cp
->procinfo
.hProcess
== NULL
)
8025 if (fd
>= 0 && fd
< MAXDESC
)
8026 fd_info
[fd
].flags
= 0;
8028 /* Note that sockets do not need special treatment here (at least on
8029 NT and Windows 95 using the standard tcp/ip stacks) - it appears that
8030 closesocket is equivalent to CloseHandle, which is to be expected
8031 because socket handles are fully fledged kernel handles. */
8043 if (new_fd
>= 0 && new_fd
< MAXDESC
)
8045 /* duplicate our internal info as well */
8046 fd_info
[new_fd
] = fd_info
[fd
];
8052 sys_dup2 (int src
, int dst
)
8056 if (dst
< 0 || dst
>= MAXDESC
)
8062 /* make sure we close the destination first if it's a pipe or socket */
8063 if (src
!= dst
&& fd_info
[dst
].flags
!= 0)
8066 rc
= _dup2 (src
, dst
);
8069 /* duplicate our internal info as well */
8070 fd_info
[dst
] = fd_info
[src
];
8076 pipe2 (int * phandles
, int pipe2_flags
)
8080 unsigned pipe_size
= 0;
8082 eassert (pipe2_flags
== (O_BINARY
| O_CLOEXEC
));
8084 /* Allow Lisp to override the default buffer size of the pipe. */
8085 if (w32_pipe_buffer_size
> 0 && w32_pipe_buffer_size
< UINT_MAX
)
8086 pipe_size
= w32_pipe_buffer_size
;
8088 /* make pipe handles non-inheritable; when we spawn a child, we
8089 replace the relevant handle with an inheritable one. Also put
8090 pipes into binary mode; we will do text mode translation ourselves
8092 rc
= _pipe (phandles
, pipe_size
, _O_NOINHERIT
| _O_BINARY
);
8096 /* Protect against overflow, since Windows can open more handles than
8097 our fd_info array has room for. */
8098 if (phandles
[0] >= MAXDESC
|| phandles
[1] >= MAXDESC
)
8100 _close (phandles
[0]);
8101 _close (phandles
[1]);
8107 flags
= FILE_PIPE
| FILE_READ
| FILE_BINARY
;
8108 fd_info
[phandles
[0]].flags
= flags
;
8110 flags
= FILE_PIPE
| FILE_WRITE
| FILE_BINARY
;
8111 fd_info
[phandles
[1]].flags
= flags
;
8118 /* Function to do blocking read of one byte, needed to implement
8119 select. It is only allowed on communication ports, sockets, or
8122 _sys_read_ahead (int fd
)
8127 if (fd
< 0 || fd
>= MAXDESC
)
8128 return STATUS_READ_ERROR
;
8130 cp
= fd_info
[fd
].cp
;
8132 if (cp
== NULL
|| cp
->fd
!= fd
|| cp
->status
!= STATUS_READ_READY
)
8133 return STATUS_READ_ERROR
;
8135 if ((fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SERIAL
| FILE_SOCKET
)) == 0
8136 || (fd_info
[fd
].flags
& FILE_READ
) == 0)
8138 DebPrint (("_sys_read_ahead: internal error: fd %d is not a pipe, serial port, or socket!\n", fd
));
8142 if ((fd_info
[fd
].flags
& FILE_CONNECT
) != 0)
8143 DebPrint (("_sys_read_ahead: read requested from fd %d, which waits for async connect!\n", fd
));
8144 cp
->status
= STATUS_READ_IN_PROGRESS
;
8146 if (fd_info
[fd
].flags
& FILE_PIPE
)
8148 rc
= _read (fd
, &cp
->chr
, sizeof (char));
8150 /* Give subprocess time to buffer some more output for us before
8151 reporting that input is available; we need this because Windows 95
8152 connects DOS programs to pipes by making the pipe appear to be
8153 the normal console stdout - as a result most DOS programs will
8154 write to stdout without buffering, ie. one character at a
8155 time. Even some W32 programs do this - "dir" in a command
8156 shell on NT is very slow if we don't do this. */
8159 int wait
= w32_pipe_read_delay
;
8165 /* Yield remainder of our time slice, effectively giving a
8166 temporary priority boost to the child process. */
8170 else if (fd_info
[fd
].flags
& FILE_SERIAL
)
8172 HANDLE hnd
= fd_info
[fd
].hnd
;
8173 OVERLAPPED
*ovl
= &fd_info
[fd
].cp
->ovl_read
;
8176 /* Configure timeouts for blocking read. */
8177 if (!GetCommTimeouts (hnd
, &ct
))
8179 cp
->status
= STATUS_READ_ERROR
;
8180 return STATUS_READ_ERROR
;
8182 ct
.ReadIntervalTimeout
= 0;
8183 ct
.ReadTotalTimeoutMultiplier
= 0;
8184 ct
.ReadTotalTimeoutConstant
= 0;
8185 if (!SetCommTimeouts (hnd
, &ct
))
8187 cp
->status
= STATUS_READ_ERROR
;
8188 return STATUS_READ_ERROR
;
8191 if (!ReadFile (hnd
, &cp
->chr
, sizeof (char), (DWORD
*) &rc
, ovl
))
8193 if (GetLastError () != ERROR_IO_PENDING
)
8195 cp
->status
= STATUS_READ_ERROR
;
8196 return STATUS_READ_ERROR
;
8198 if (!GetOverlappedResult (hnd
, ovl
, (DWORD
*) &rc
, TRUE
))
8200 cp
->status
= STATUS_READ_ERROR
;
8201 return STATUS_READ_ERROR
;
8205 else if (fd_info
[fd
].flags
& FILE_SOCKET
)
8207 unsigned long nblock
= 0;
8208 /* We always want this to block, so temporarily disable NDELAY. */
8209 if (fd_info
[fd
].flags
& FILE_NDELAY
)
8210 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
8212 rc
= pfn_recv (SOCK_HANDLE (fd
), &cp
->chr
, sizeof (char), 0);
8214 if (fd_info
[fd
].flags
& FILE_NDELAY
)
8217 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
8221 if (rc
== sizeof (char))
8222 cp
->status
= STATUS_READ_SUCCEEDED
;
8224 cp
->status
= STATUS_READ_FAILED
;
8230 _sys_wait_accept (int fd
)
8236 if (fd
< 0 || fd
>= MAXDESC
)
8237 return STATUS_READ_ERROR
;
8239 cp
= fd_info
[fd
].cp
;
8241 if (cp
== NULL
|| cp
->fd
!= fd
|| cp
->status
!= STATUS_READ_READY
)
8242 return STATUS_READ_ERROR
;
8244 cp
->status
= STATUS_READ_FAILED
;
8246 hEv
= pfn_WSACreateEvent ();
8247 rc
= pfn_WSAEventSelect (SOCK_HANDLE (fd
), hEv
, FD_ACCEPT
);
8248 if (rc
!= SOCKET_ERROR
)
8251 rc
= WaitForSingleObject (hEv
, 500);
8253 } while (rc
== WAIT_TIMEOUT
8254 && cp
->status
!= STATUS_READ_ERROR
8256 pfn_WSAEventSelect (SOCK_HANDLE (fd
), NULL
, 0);
8257 if (rc
== WAIT_OBJECT_0
)
8258 cp
->status
= STATUS_READ_SUCCEEDED
;
8260 pfn_WSACloseEvent (hEv
);
8266 _sys_wait_connect (int fd
)
8272 if (fd
< 0 || fd
>= MAXDESC
)
8273 return STATUS_READ_ERROR
;
8275 cp
= fd_info
[fd
].cp
;
8276 if (cp
== NULL
|| cp
->fd
!= fd
|| cp
->status
!= STATUS_READ_READY
)
8277 return STATUS_READ_ERROR
;
8279 cp
->status
= STATUS_READ_FAILED
;
8281 hEv
= pfn_WSACreateEvent ();
8282 rc
= pfn_WSAEventSelect (SOCK_HANDLE (fd
), hEv
, FD_CONNECT
);
8283 if (rc
!= SOCKET_ERROR
)
8286 rc
= WaitForSingleObject (hEv
, 500);
8288 } while (rc
== WAIT_TIMEOUT
8289 && cp
->status
!= STATUS_READ_ERROR
8291 if (rc
== WAIT_OBJECT_0
)
8293 /* We've got an event, but it could be a successful
8294 connection, or it could be a failure. Find out
8296 WSANETWORKEVENTS events
;
8298 pfn_WSAEnumNetworkEvents (SOCK_HANDLE (fd
), hEv
, &events
);
8299 if ((events
.lNetworkEvents
& FD_CONNECT
) != 0
8300 && events
.iErrorCode
[FD_CONNECT_BIT
])
8302 cp
->status
= STATUS_CONNECT_FAILED
;
8303 cp
->errcode
= events
.iErrorCode
[FD_CONNECT_BIT
];
8307 cp
->status
= STATUS_READ_SUCCEEDED
;
8311 pfn_WSAEventSelect (SOCK_HANDLE (fd
), NULL
, 0);
8314 pfn_WSACloseEvent (hEv
);
8320 sys_read (int fd
, char * buffer
, unsigned int count
)
8325 char * orig_buffer
= buffer
;
8333 if (fd
< MAXDESC
&& fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
| FILE_SERIAL
))
8335 child_process
*cp
= fd_info
[fd
].cp
;
8337 if ((fd_info
[fd
].flags
& FILE_READ
) == 0)
8345 /* re-read CR carried over from last read */
8346 if (fd_info
[fd
].flags
& FILE_LAST_CR
)
8348 if (fd_info
[fd
].flags
& FILE_BINARY
) emacs_abort ();
8352 fd_info
[fd
].flags
&= ~FILE_LAST_CR
;
8355 /* presence of a child_process structure means we are operating in
8356 non-blocking mode - otherwise we just call _read directly.
8357 Note that the child_process structure might be missing because
8358 reap_subprocess has been called; in this case the pipe is
8359 already broken, so calling _read on it is okay. */
8362 int current_status
= cp
->status
;
8364 switch (current_status
)
8366 case STATUS_READ_FAILED
:
8367 case STATUS_READ_ERROR
:
8368 /* report normal EOF if nothing in buffer */
8370 fd_info
[fd
].flags
|= FILE_AT_EOF
;
8373 case STATUS_READ_READY
:
8374 case STATUS_READ_IN_PROGRESS
:
8376 /* This happens all the time during GnuTLS handshake
8377 with the remote, evidently because GnuTLS waits for
8378 the read to complete by retrying the read operation
8379 upon EAGAIN. So I'm disabling the DebPrint to avoid
8380 wasting cycles on something that is not a real
8381 problem. Enable if you need to debug something that
8383 DebPrint (("sys_read called when read is in progress %d\n",
8386 errno
= EWOULDBLOCK
;
8389 case STATUS_READ_SUCCEEDED
:
8390 /* consume read-ahead char */
8391 *buffer
++ = cp
->chr
;
8394 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
8395 ResetEvent (cp
->char_avail
);
8397 case STATUS_READ_ACKNOWLEDGED
:
8398 case STATUS_CONNECT_FAILED
:
8402 DebPrint (("sys_read: bad status %d\n", current_status
));
8407 if (fd_info
[fd
].flags
& FILE_PIPE
)
8409 PeekNamedPipe ((HANDLE
) _get_osfhandle (fd
), NULL
, 0, NULL
, &waiting
, NULL
);
8410 to_read
= min (waiting
, (DWORD
) count
);
8413 nchars
+= _read (fd
, buffer
, to_read
);
8415 else if (fd_info
[fd
].flags
& FILE_SERIAL
)
8417 HANDLE hnd
= fd_info
[fd
].hnd
;
8418 OVERLAPPED
*ovl
= &fd_info
[fd
].cp
->ovl_read
;
8424 /* Configure timeouts for non-blocking read. */
8425 if (!GetCommTimeouts (hnd
, &ct
))
8430 ct
.ReadIntervalTimeout
= MAXDWORD
;
8431 ct
.ReadTotalTimeoutMultiplier
= 0;
8432 ct
.ReadTotalTimeoutConstant
= 0;
8433 if (!SetCommTimeouts (hnd
, &ct
))
8439 if (!ResetEvent (ovl
->hEvent
))
8444 if (!ReadFile (hnd
, buffer
, count
, (DWORD
*) &rc
, ovl
))
8446 if (GetLastError () != ERROR_IO_PENDING
)
8451 if (!GetOverlappedResult (hnd
, ovl
, (DWORD
*) &rc
, TRUE
))
8460 else /* FILE_SOCKET */
8462 if (winsock_lib
== NULL
) emacs_abort ();
8464 /* When a non-blocking 'connect' call fails,
8465 wait_reading_process_output detects this by calling
8466 'getpeername', and then attempts to obtain the connection
8467 error code by trying to read 1 byte from the socket. If
8468 we try to serve that read by calling 'recv' below, the
8469 error we get is a generic WSAENOTCONN, not the actual
8470 connection error. So instead, we use the actual error
8471 code stashed by '_sys_wait_connect' in cp->errcode.
8472 Alternatively, we could have used 'getsockopt', like on
8473 GNU/Linux, but: (a) I have no idea whether the winsock
8474 version could hang, as it does "on some systems" (see the
8475 comment in process.c); and (b) 'getsockopt' on Windows is
8476 documented to clear the socket error for the entire
8477 process, which I'm not sure is TRT; FIXME. */
8478 if (current_status
== STATUS_CONNECT_FAILED
8479 && (fd_info
[fd
].flags
& FILE_CONNECT
) != 0
8480 && cp
->errcode
!= 0)
8482 pfn_WSASetLastError (cp
->errcode
);
8486 /* Do the equivalent of a non-blocking read. */
8487 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONREAD
, &waiting
);
8488 if (waiting
== 0 && nchars
== 0)
8490 errno
= EWOULDBLOCK
;
8496 /* always use binary mode for sockets */
8497 int res
= pfn_recv (SOCK_HANDLE (fd
), buffer
, count
, 0);
8498 if (res
== SOCKET_ERROR
)
8501 DebPrint (("sys_read.recv failed with error %d on socket %ld\n",
8502 errno
, SOCK_HANDLE (fd
)));
8511 int nread
= _read (fd
, buffer
, count
);
8514 else if (nchars
== 0)
8519 fd_info
[fd
].flags
|= FILE_AT_EOF
;
8520 /* Perform text mode translation if required. */
8521 else if ((fd_info
[fd
].flags
& FILE_BINARY
) == 0)
8523 nchars
= crlf_to_lf (nchars
, orig_buffer
);
8524 /* If buffer contains only CR, return that. To be absolutely
8525 sure we should attempt to read the next char, but in
8526 practice a CR to be followed by LF would not appear by
8527 itself in the buffer. */
8528 if (nchars
> 1 && orig_buffer
[nchars
- 1] == 0x0d)
8530 fd_info
[fd
].flags
|= FILE_LAST_CR
;
8536 nchars
= _read (fd
, buffer
, count
);
8541 /* From w32xfns.c */
8542 extern HANDLE interrupt_handle
;
8545 sys_write (int fd
, const void * buffer
, unsigned int count
)
8556 if (fd
< MAXDESC
&& fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
| FILE_SERIAL
))
8558 if ((fd_info
[fd
].flags
& FILE_WRITE
) == 0)
8564 /* Perform text mode translation if required. */
8565 if ((fd_info
[fd
].flags
& FILE_BINARY
) == 0)
8568 const unsigned char * src
= buffer
;
8569 unsigned char * dst
;
8572 SAFE_NALLOCA (tmpbuf
, 2, count
);
8573 dst
= (unsigned char *)tmpbuf
;
8577 unsigned char *next
;
8578 /* Copy next line or remaining bytes. */
8579 next
= _memccpy (dst
, src
, '\n', nbytes
);
8582 /* Copied one line ending with '\n'. */
8583 int copied
= next
- dst
;
8586 /* Insert '\r' before '\n'. */
8593 /* Copied remaining partial line -> now finished. */
8600 if (fd
< MAXDESC
&& fd_info
[fd
].flags
& FILE_SERIAL
)
8602 HANDLE hnd
= (HANDLE
) _get_osfhandle (fd
);
8603 OVERLAPPED
*ovl
= &fd_info
[fd
].cp
->ovl_write
;
8604 HANDLE wait_hnd
[2] = { interrupt_handle
, ovl
->hEvent
};
8607 /* This is async (a.k.a. "overlapped") I/O, so the return value
8608 of FALSE from WriteFile means either an error or the output
8609 will be completed asynchronously (ERROR_IO_PENDING). */
8610 if (!WriteFile (hnd
, buffer
, count
, (DWORD
*) &nchars
, ovl
))
8612 if (GetLastError () != ERROR_IO_PENDING
)
8619 /* Wait for the write to complete, and watch C-g while
8621 if (detect_input_pending ())
8622 active
= MsgWaitForMultipleObjects (2, wait_hnd
, FALSE
,
8623 INFINITE
, QS_ALLINPUT
);
8625 active
= WaitForMultipleObjects (2, wait_hnd
, FALSE
, INFINITE
);
8629 /* User pressed C-g, cancel write, then leave.
8630 Don't bother cleaning up as we may only get stuck
8631 in buggy drivers. */
8632 PurgeComm (hnd
, PURGE_TXABORT
| PURGE_TXCLEAR
);
8634 errno
= EIO
; /* Why not EINTR? */
8637 case WAIT_OBJECT_0
+ 1:
8638 if (!GetOverlappedResult (hnd
, ovl
, (DWORD
*) &nchars
, TRUE
))
8648 else if (fd
< MAXDESC
&& fd_info
[fd
].flags
& FILE_SOCKET
)
8650 unsigned long nblock
= 0;
8651 if (winsock_lib
== NULL
) emacs_abort ();
8653 /* TODO: implement select() properly so non-blocking I/O works. */
8654 /* For now, make sure the write blocks. */
8655 if (fd_info
[fd
].flags
& FILE_NDELAY
)
8656 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
8658 nchars
= pfn_send (SOCK_HANDLE (fd
), buffer
, count
, 0);
8660 /* Set the socket back to non-blocking if it was before,
8661 for other operations that support it. */
8662 if (fd_info
[fd
].flags
& FILE_NDELAY
)
8665 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
8668 if (nchars
== SOCKET_ERROR
)
8670 DebPrint (("sys_write.send failed with error %d on socket %ld\n",
8671 pfn_WSAGetLastError (), SOCK_HANDLE (fd
)));
8677 /* Some networked filesystems don't like too large writes, so
8678 break them into smaller chunks. See the Comments section of
8679 the MSDN documentation of WriteFile for details behind the
8680 choice of the value of CHUNK below. See also the thread
8681 http://thread.gmane.org/gmane.comp.version-control.git/145294
8682 in the git mailing list. */
8683 const unsigned char *p
= buffer
;
8684 const bool is_pipe
= (fd
< MAXDESC
8685 && ((fd_info
[fd
].flags
& (FILE_PIPE
| FILE_NDELAY
))
8686 == (FILE_PIPE
| FILE_NDELAY
)));
8687 /* Some programs, notably Node.js's node.exe, seem to never
8688 completely empty the pipe, so writing more than the size of
8689 the pipe's buffer always returns ENOSPC, and we loop forever
8690 between send_process and here. As a workaround, write no
8691 more than the pipe's buffer can hold. */
8692 DWORD pipe_buffer_size
;
8695 if (!GetNamedPipeInfo ((HANDLE
)_get_osfhandle (fd
),
8696 NULL
, &pipe_buffer_size
, NULL
, NULL
))
8698 DebPrint (("GetNamedPipeInfo: error %u\n", GetLastError ()));
8699 pipe_buffer_size
= 4096;
8702 const unsigned chunk
= is_pipe
? pipe_buffer_size
: 30 * 1024 * 1024;
8708 unsigned this_chunk
= count
< chunk
? count
: chunk
;
8709 int n
= _write (fd
, p
, this_chunk
);
8715 /* When there's no buffer space in a pipe that is in the
8716 non-blocking mode, _write returns ENOSPC. We return
8717 EAGAIN instead, which should trigger the logic in
8718 send_process that enters waiting loop and calls
8719 wait_reading_process_output to allow process input to
8720 be accepted during the wait. Those calls to
8721 wait_reading_process_output allow sys_select to
8722 notice when process input becomes available, thus
8723 avoiding deadlock whereby each side of the pipe is
8724 blocked on write, waiting for the other party to read
8725 its end of the pipe. */
8726 if (errno
== ENOSPC
&& is_pipe
)
8732 else if (n
< this_chunk
)
8744 /* Emulation of SIOCGIFCONF and getifaddrs, see process.c. */
8746 extern Lisp_Object
conv_sockaddr_to_lisp (struct sockaddr
*, int);
8748 /* Return information about network interface IFNAME, or about all
8749 interfaces (if IFNAME is nil). */
8751 network_interface_get_info (Lisp_Object ifname
)
8753 ULONG ainfo_len
= sizeof (IP_ADAPTER_INFO
);
8754 IP_ADAPTER_INFO
*adapter
, *ainfo
= xmalloc (ainfo_len
);
8755 DWORD retval
= get_adapters_info (ainfo
, &ainfo_len
);
8756 Lisp_Object res
= Qnil
;
8758 if (retval
== ERROR_BUFFER_OVERFLOW
)
8760 ainfo
= xrealloc (ainfo
, ainfo_len
);
8761 retval
= get_adapters_info (ainfo
, &ainfo_len
);
8764 if (retval
== ERROR_SUCCESS
)
8766 int eth_count
= 0, tr_count
= 0, fddi_count
= 0, ppp_count
= 0;
8767 int sl_count
= 0, wlan_count
= 0, lo_count
= 0, ifx_count
= 0;
8769 struct sockaddr_in sa
;
8771 /* For the below, we need some winsock functions, so make sure
8772 the winsock DLL is loaded. If we cannot successfully load
8773 it, they will have no use of the information we provide,
8775 if (!winsock_lib
&& !init_winsock (1))
8778 for (adapter
= ainfo
; adapter
; adapter
= adapter
->Next
)
8780 char namebuf
[MAX_ADAPTER_NAME_LENGTH
+ 4];
8782 /* Present Unix-compatible interface names, instead of the
8783 Windows names, which are really GUIDs not readable by
8785 static const char *ifmt
[] = {
8786 "eth%d", "tr%d", "fddi%d", "ppp%d", "sl%d", "wlan%d",
8801 switch (adapter
->Type
)
8803 case MIB_IF_TYPE_ETHERNET
:
8804 /* Windows before Vista reports wireless adapters as
8805 Ethernet. Work around by looking at the Description
8807 if (strstr (adapter
->Description
, "Wireless "))
8810 if_num
= wlan_count
++;
8814 ifmt_idx
= ETHERNET
;
8815 if_num
= eth_count
++;
8818 case MIB_IF_TYPE_TOKENRING
:
8819 ifmt_idx
= TOKENRING
;
8820 if_num
= tr_count
++;
8822 case MIB_IF_TYPE_FDDI
:
8824 if_num
= fddi_count
++;
8826 case MIB_IF_TYPE_PPP
:
8828 if_num
= ppp_count
++;
8830 case MIB_IF_TYPE_SLIP
:
8832 if_num
= sl_count
++;
8834 case IF_TYPE_IEEE80211
:
8836 if_num
= wlan_count
++;
8838 case MIB_IF_TYPE_LOOPBACK
:
8841 ifmt_idx
= LOOPBACK
;
8842 if_num
= lo_count
++;
8848 ifmt_idx
= OTHER_IF
;
8849 if_num
= ifx_count
++;
8852 if (ifmt_idx
== NONE
)
8854 sprintf (namebuf
, ifmt
[ifmt_idx
], if_num
);
8856 sa
.sin_family
= AF_INET
;
8857 ip_addr
= sys_inet_addr (adapter
->IpAddressList
.IpAddress
.String
);
8858 if (ip_addr
== INADDR_NONE
)
8860 /* Bogus address, skip this interface. */
8863 sa
.sin_addr
.s_addr
= ip_addr
;
8866 res
= Fcons (Fcons (build_string (namebuf
),
8867 conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
8868 sizeof (struct sockaddr
))),
8870 else if (strcmp (namebuf
, SSDATA (ifname
)) == 0)
8872 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
8873 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
8874 Lisp_Object flags
= Qnil
;
8878 /* Flags. We guess most of them by type, since the
8879 Windows flags are different and hard to get by. */
8880 flags
= Fcons (intern ("up"), flags
);
8881 if (ifmt_idx
== ETHERNET
|| ifmt_idx
== WLAN
)
8883 flags
= Fcons (intern ("broadcast"), flags
);
8884 flags
= Fcons (intern ("multicast"), flags
);
8886 flags
= Fcons (intern ("running"), flags
);
8887 if (ifmt_idx
== PPP
)
8889 flags
= Fcons (intern ("pointopoint"), flags
);
8890 flags
= Fcons (intern ("noarp"), flags
);
8892 if (adapter
->HaveWins
)
8893 flags
= Fcons (intern ("WINS"), flags
);
8894 if (adapter
->DhcpEnabled
)
8895 flags
= Fcons (intern ("dynamic"), flags
);
8897 res
= Fcons (flags
, res
);
8899 /* Hardware address and its family. */
8900 for (n
= 0; n
< adapter
->AddressLength
; n
++)
8901 p
->contents
[n
] = make_number ((int) adapter
->Address
[n
]);
8902 /* Windows does not support AF_LINK or AF_PACKET family
8903 of addresses. Use an arbitrary family number that is
8904 identical to what GNU/Linux returns. */
8905 res
= Fcons (Fcons (make_number (1), hwaddr
), res
);
8908 sa
.sin_family
= AF_INET
;
8909 net_mask
= sys_inet_addr (adapter
->IpAddressList
.IpMask
.String
);
8910 if (net_mask
!= INADDR_NONE
)
8912 sa
.sin_addr
.s_addr
= net_mask
;
8914 res
= Fcons (conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
8915 sizeof (struct sockaddr
)),
8919 res
= Fcons (Qnil
, res
);
8921 sa
.sin_family
= AF_INET
;
8922 if (ip_addr
!= INADDR_NONE
)
8924 /* Broadcast address is only reported by
8925 GetAdaptersAddresses, which is of limited
8926 availability. Generate it on our own. */
8927 u_long bcast_addr
= (ip_addr
& net_mask
) | ~net_mask
;
8929 sa
.sin_addr
.s_addr
= bcast_addr
;
8931 res
= Fcons (conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
8932 sizeof (struct sockaddr
)),
8936 sa
.sin_addr
.s_addr
= ip_addr
;
8938 res
= Fcons (conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
8939 sizeof (struct sockaddr
)),
8943 res
= Fcons (Qnil
, Fcons (Qnil
, res
));
8946 /* GetAdaptersInfo is documented to not report loopback
8947 interfaces, so we generate one out of thin air. */
8950 sa
.sin_family
= AF_INET
;
8954 sa
.sin_addr
.s_addr
= sys_inet_addr ("127.0.0.1");
8955 res
= Fcons (Fcons (build_string ("lo"),
8956 conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
8957 sizeof (struct sockaddr
))),
8960 else if (strcmp (SSDATA (ifname
), "lo") == 0)
8962 res
= Fcons (Fcons (intern ("running"),
8963 Fcons (intern ("loopback"),
8964 Fcons (intern ("up"), Qnil
))), Qnil
);
8965 /* 772 is what 3 different GNU/Linux systems report for
8966 the loopback interface. */
8967 res
= Fcons (Fcons (make_number (772),
8968 Fmake_vector (make_number (6),
8971 sa
.sin_addr
.s_addr
= sys_inet_addr ("255.0.0.0");
8972 res
= Fcons (conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
8973 sizeof (struct sockaddr
)),
8975 sa
.sin_addr
.s_addr
= sys_inet_addr ("0.0.0.0");
8976 res
= Fcons (conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
8977 sizeof (struct sockaddr
)),
8979 sa
.sin_addr
.s_addr
= sys_inet_addr ("127.0.0.1");
8980 res
= Fcons (conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
8981 sizeof (struct sockaddr
)),
8994 network_interface_list (void)
8996 return network_interface_get_info (Qnil
);
9000 network_interface_info (Lisp_Object ifname
)
9002 CHECK_STRING (ifname
);
9003 return network_interface_get_info (ifname
);
9007 /* The Windows CRT functions are "optimized for speed", so they don't
9008 check for timezone and DST changes if they were last called less
9009 than 1 minute ago (see http://support.microsoft.com/kb/821231). So
9010 all Emacs features that repeatedly call time functions (e.g.,
9011 display-time) are in real danger of missing timezone and DST
9012 changes. Calling tzset before each localtime call fixes that. */
9014 sys_localtime (const time_t *t
)
9017 return localtime (t
);
9022 /* Try loading LIBRARY_ID from the file(s) specified in
9023 Vdynamic_library_alist. If the library is loaded successfully,
9024 return the handle of the DLL, and record the filename in the
9025 property :loaded-from of LIBRARY_ID. If the library could not be
9026 found, or when it was already loaded (because the handle is not
9027 recorded anywhere, and so is lost after use), return NULL.
9029 We could also save the handle in :loaded-from, but currently
9030 there's no use case for it. */
9032 w32_delayed_load (Lisp_Object library_id
)
9034 HMODULE dll_handle
= NULL
;
9036 CHECK_SYMBOL (library_id
);
9038 if (CONSP (Vdynamic_library_alist
)
9039 && NILP (Fassq (library_id
, Vlibrary_cache
)))
9041 Lisp_Object found
= Qnil
;
9042 Lisp_Object dlls
= Fassq (library_id
, Vdynamic_library_alist
);
9045 for (dlls
= XCDR (dlls
); CONSP (dlls
); dlls
= XCDR (dlls
))
9047 Lisp_Object dll
= XCAR (dlls
);
9048 char name
[MAX_UTF8_PATH
];
9052 dll
= ENCODE_FILE (dll
);
9053 if (w32_unicode_filenames
)
9055 wchar_t name_w
[MAX_PATH
];
9057 filename_to_utf16 (SSDATA (dll
), name_w
);
9058 dll_handle
= LoadLibraryW (name_w
);
9061 res
= GetModuleFileNameW (dll_handle
, name_w
,
9064 filename_from_utf16 (name_w
, name
);
9069 char name_a
[MAX_PATH
];
9071 filename_to_ansi (SSDATA (dll
), name_a
);
9072 dll_handle
= LoadLibraryA (name_a
);
9075 res
= GetModuleFileNameA (dll_handle
, name_a
,
9078 filename_from_ansi (name_a
, name
);
9083 ptrdiff_t len
= strlen (name
);
9086 /* Possibly truncated */
9087 ? make_specified_string (name
, -1, len
, 1)
9089 /* This prevents thread start and end notifications
9090 from being sent to the DLL, for every thread we
9091 start. We don't need those notifications because
9092 threads we create never use any of these DLLs, only
9093 the main thread uses them. This is supposed to
9094 speed up thread creation. */
9095 DisableThreadLibraryCalls (dll_handle
);
9100 Fput (library_id
, QCloaded_from
, found
);
9108 check_windows_init_file (void)
9110 /* A common indication that Emacs is not installed properly is when
9111 it cannot find the Windows installation file. If this file does
9112 not exist in the expected place, tell the user. */
9114 if (!noninteractive
&& !inhibit_window_system
9115 /* Vload_path is not yet initialized when we are loading
9117 && NILP (Vpurify_flag
))
9119 Lisp_Object init_file
;
9122 /* Implementation note: this function runs early during Emacs
9123 startup, before startup.el is run. So Vload_path is still in
9124 its initial unibyte form, but it holds UTF-8 encoded file
9125 names, since init_callproc was already called. So we do not
9126 need to ENCODE_FILE here, but we do need to convert the file
9127 names from UTF-8 to ANSI. */
9128 init_file
= build_string ("term/w32-win");
9129 fd
= openp (Vload_path
, init_file
, Fget_load_suffixes (), NULL
, Qnil
, 0);
9132 Lisp_Object load_path_print
= Fprin1_to_string (Vload_path
, Qnil
);
9133 char *init_file_name
= SSDATA (init_file
);
9134 char *load_path
= SSDATA (load_path_print
);
9135 char *buffer
= alloca (1024
9136 + strlen (init_file_name
)
9137 + strlen (load_path
));
9142 "The Emacs Windows initialization file \"%s.el\" "
9143 "could not be found in your Emacs installation. "
9144 "Emacs checked the following directories for this file:\n"
9146 "When Emacs cannot find this file, it usually means that it "
9147 "was not installed properly, or its distribution file was "
9148 "not unpacked properly.\nSee the README.W32 file in the "
9149 "top-level Emacs directory for more information.",
9150 init_file_name
, load_path
);
9151 needed
= pMultiByteToWideChar (CP_UTF8
, multiByteToWideCharFlags
,
9152 buffer
, -1, NULL
, 0);
9155 wchar_t *msg_w
= alloca ((needed
+ 1) * sizeof (wchar_t));
9157 pMultiByteToWideChar (CP_UTF8
, multiByteToWideCharFlags
, buffer
,
9159 needed
= pWideCharToMultiByte (CP_ACP
, 0, msg_w
, -1,
9160 NULL
, 0, NULL
, NULL
);
9163 char *msg_a
= alloca (needed
+ 1);
9165 pWideCharToMultiByte (CP_ACP
, 0, msg_w
, -1, msg_a
, needed
,
9172 "Emacs Abort Dialog",
9173 MB_OK
| MB_ICONEXCLAMATION
| MB_TASKMODAL
);
9174 /* Use the low-level system abort. */
9185 term_ntproc (int ignored
)
9191 /* shutdown the socket interface if necessary */
9198 init_ntproc (int dumping
)
9200 sigset_t initial_mask
= 0;
9202 /* Initialize the socket interface now if available and requested by
9203 the user by defining PRELOAD_WINSOCK; otherwise loading will be
9204 delayed until open-network-stream is called (w32-has-winsock can
9205 also be used to dynamically load or reload winsock).
9207 Conveniently, init_environment is called before us, so
9208 PRELOAD_WINSOCK can be set in the registry. */
9210 /* Always initialize this correctly. */
9213 if (getenv ("PRELOAD_WINSOCK") != NULL
)
9214 init_winsock (TRUE
);
9216 /* Initial preparation for subprocess support: replace our standard
9217 handles with non-inheritable versions. */
9220 HANDLE stdin_save
= INVALID_HANDLE_VALUE
;
9221 HANDLE stdout_save
= INVALID_HANDLE_VALUE
;
9222 HANDLE stderr_save
= INVALID_HANDLE_VALUE
;
9224 parent
= GetCurrentProcess ();
9226 /* ignore errors when duplicating and closing; typically the
9227 handles will be invalid when running as a gui program. */
9228 DuplicateHandle (parent
,
9229 GetStdHandle (STD_INPUT_HANDLE
),
9234 DUPLICATE_SAME_ACCESS
);
9236 DuplicateHandle (parent
,
9237 GetStdHandle (STD_OUTPUT_HANDLE
),
9242 DUPLICATE_SAME_ACCESS
);
9244 DuplicateHandle (parent
,
9245 GetStdHandle (STD_ERROR_HANDLE
),
9250 DUPLICATE_SAME_ACCESS
);
9256 if (stdin_save
!= INVALID_HANDLE_VALUE
)
9257 _open_osfhandle ((intptr_t) stdin_save
, O_TEXT
);
9259 _open ("nul", O_TEXT
| O_NOINHERIT
| O_RDONLY
);
9262 if (stdout_save
!= INVALID_HANDLE_VALUE
)
9263 _open_osfhandle ((intptr_t) stdout_save
, O_TEXT
);
9265 _open ("nul", O_TEXT
| O_NOINHERIT
| O_WRONLY
);
9268 if (stderr_save
!= INVALID_HANDLE_VALUE
)
9269 _open_osfhandle ((intptr_t) stderr_save
, O_TEXT
);
9271 _open ("nul", O_TEXT
| O_NOINHERIT
| O_WRONLY
);
9275 /* unfortunately, atexit depends on implementation of malloc */
9276 /* atexit (term_ntproc); */
9279 /* Make sure we start with all signals unblocked. */
9280 sigprocmask (SIG_SETMASK
, &initial_mask
, NULL
);
9281 signal (SIGABRT
, term_ntproc
);
9285 /* determine which drives are fixed, for GetCachedVolumeInformation */
9287 /* GetDriveType must have trailing backslash. */
9288 char drive
[] = "A:\\";
9290 /* Loop over all possible drive letters */
9291 while (*drive
<= 'Z')
9293 /* Record if this drive letter refers to a fixed drive. */
9294 fixed_drives
[DRIVE_INDEX (*drive
)] =
9295 (GetDriveType (drive
) == DRIVE_FIXED
);
9300 /* Reset the volume info cache. */
9301 volume_cache
= NULL
;
9306 shutdown_handler ensures that buffers' autosave files are
9307 up to date when the user logs off, or the system shuts down.
9310 shutdown_handler (DWORD type
)
9312 /* Ctrl-C and Ctrl-Break are already suppressed, so don't handle them. */
9313 if (type
== CTRL_CLOSE_EVENT
/* User closes console window. */
9314 || type
== CTRL_LOGOFF_EVENT
/* User logs off. */
9315 || type
== CTRL_SHUTDOWN_EVENT
) /* User shutsdown. */
9317 /* Shut down cleanly, making sure autosave files are up to date. */
9318 shut_down_emacs (0, Qnil
);
9321 /* Allow other handlers to handle this signal. */
9325 /* On Windows 9X, load UNICOWS.DLL and return its handle, or die. On
9326 NT, return a handle to GDI32.DLL. */
9328 maybe_load_unicows_dll (void)
9330 if (os_subtype
== OS_9X
)
9332 HANDLE ret
= LoadLibrary ("Unicows.dll");
9335 /* These two functions are present on Windows 9X as stubs
9336 that always fail. We need the real implementations from
9337 UNICOWS.DLL, so we must call these functions through
9338 pointers, and assign the correct addresses to these
9339 pointers at program startup (see emacs.c, which calls
9340 this function early on). */
9341 pMultiByteToWideChar
=
9342 (MultiByteToWideChar_Proc
)GetProcAddress (ret
, "MultiByteToWideChar");
9343 pWideCharToMultiByte
=
9344 (WideCharToMultiByte_Proc
)GetProcAddress (ret
, "WideCharToMultiByte");
9345 multiByteToWideCharFlags
= MB_ERR_INVALID_CHARS
;
9352 button
= MessageBox (NULL
,
9353 "Emacs cannot load the UNICOWS.DLL library.\n"
9354 "This library is essential for using Emacs\n"
9355 "on this system. You need to install it.\n\n"
9356 "Emacs will exit when you click OK.",
9357 "Emacs cannot load UNICOWS.DLL",
9358 MB_ICONERROR
| MB_TASKMODAL
9359 | MB_SETFOREGROUND
| MB_OK
);
9370 /* On NT family of Windows, these two functions are always
9371 linked in, so we just assign their addresses to the 2
9372 pointers; no need for the LoadLibrary dance. */
9373 pMultiByteToWideChar
= MultiByteToWideChar
;
9374 pWideCharToMultiByte
= WideCharToMultiByte
;
9375 /* On NT 4.0, though, MB_ERR_INVALID_CHARS is not supported. */
9376 if (w32_major_version
< 5)
9377 multiByteToWideCharFlags
= 0;
9379 multiByteToWideCharFlags
= MB_ERR_INVALID_CHARS
;
9380 return LoadLibrary ("Gdi32.dll");
9385 globals_of_w32 is used to initialize those global variables that
9386 must always be initialized on startup even when the global variable
9387 initialized is non zero (see the function main in emacs.c).
9390 globals_of_w32 (void)
9392 HMODULE kernel32
= GetModuleHandle ("kernel32.dll");
9394 get_process_times_fn
= (GetProcessTimes_Proc
)
9395 GetProcAddress (kernel32
, "GetProcessTimes");
9397 DEFSYM (QCloaded_from
, ":loaded-from");
9399 g_b_init_is_windows_9x
= 0;
9400 g_b_init_open_process_token
= 0;
9401 g_b_init_get_token_information
= 0;
9402 g_b_init_lookup_account_sid
= 0;
9403 g_b_init_get_sid_sub_authority
= 0;
9404 g_b_init_get_sid_sub_authority_count
= 0;
9405 g_b_init_get_security_info
= 0;
9406 g_b_init_get_file_security_w
= 0;
9407 g_b_init_get_file_security_a
= 0;
9408 g_b_init_get_security_descriptor_owner
= 0;
9409 g_b_init_get_security_descriptor_group
= 0;
9410 g_b_init_is_valid_sid
= 0;
9411 g_b_init_create_toolhelp32_snapshot
= 0;
9412 g_b_init_process32_first
= 0;
9413 g_b_init_process32_next
= 0;
9414 g_b_init_open_thread_token
= 0;
9415 g_b_init_impersonate_self
= 0;
9416 g_b_init_revert_to_self
= 0;
9417 g_b_init_get_process_memory_info
= 0;
9418 g_b_init_get_process_working_set_size
= 0;
9419 g_b_init_global_memory_status
= 0;
9420 g_b_init_global_memory_status_ex
= 0;
9421 g_b_init_equal_sid
= 0;
9422 g_b_init_copy_sid
= 0;
9423 g_b_init_get_length_sid
= 0;
9424 g_b_init_get_native_system_info
= 0;
9425 g_b_init_get_system_times
= 0;
9426 g_b_init_create_symbolic_link_w
= 0;
9427 g_b_init_create_symbolic_link_a
= 0;
9428 g_b_init_get_security_descriptor_dacl
= 0;
9429 g_b_init_convert_sd_to_sddl
= 0;
9430 g_b_init_convert_sddl_to_sd
= 0;
9431 g_b_init_is_valid_security_descriptor
= 0;
9432 g_b_init_set_file_security_w
= 0;
9433 g_b_init_set_file_security_a
= 0;
9434 g_b_init_set_named_security_info_w
= 0;
9435 g_b_init_set_named_security_info_a
= 0;
9436 g_b_init_get_adapters_info
= 0;
9437 g_b_init_compare_string_w
= 0;
9438 num_of_processors
= 0;
9439 /* The following sets a handler for shutdown notifications for
9440 console apps. This actually applies to Emacs in both console and
9441 GUI modes, since we had to fool windows into thinking emacs is a
9442 console application to get console mode to work. */
9443 SetConsoleCtrlHandler (shutdown_handler
, TRUE
);
9445 /* "None" is the default group name on standalone workstations. */
9446 strcpy (dflt_group_name
, "None");
9448 /* Reset, in case it has some value inherited from dump time. */
9449 w32_stat_get_owner_group
= 0;
9451 /* If w32_unicode_filenames is non-zero, we will be using Unicode
9452 (a.k.a. "wide") APIs to invoke functions that accept file
9454 if (is_windows_9x ())
9455 w32_unicode_filenames
= 0;
9457 w32_unicode_filenames
= 1;
9460 extern void dynlib_reset_last_error (void);
9461 dynlib_reset_last_error ();
9464 w32_crypto_hprov
= (HCRYPTPROV
)0;
9467 /* For make-serial-process */
9469 serial_open (Lisp_Object port_obj
)
9471 char *port
= SSDATA (port_obj
);
9476 hnd
= CreateFile (port
, GENERIC_READ
| GENERIC_WRITE
, 0, 0,
9477 OPEN_EXISTING
, FILE_FLAG_OVERLAPPED
, 0);
9478 if (hnd
== INVALID_HANDLE_VALUE
)
9479 error ("Could not open %s", port
);
9480 fd
= (int) _open_osfhandle ((intptr_t) hnd
, 0);
9482 error ("Could not open %s", port
);
9486 error ("Could not create child process");
9488 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
9489 fd_info
[ fd
].hnd
= hnd
;
9490 fd_info
[ fd
].flags
|=
9491 FILE_READ
| FILE_WRITE
| FILE_BINARY
| FILE_SERIAL
;
9492 if (fd_info
[ fd
].cp
!= NULL
)
9494 error ("fd_info[fd = %d] is already in use", fd
);
9496 fd_info
[ fd
].cp
= cp
;
9497 cp
->ovl_read
.hEvent
= CreateEvent (NULL
, TRUE
, FALSE
, NULL
);
9498 if (cp
->ovl_read
.hEvent
== NULL
)
9499 error ("Could not create read event");
9500 cp
->ovl_write
.hEvent
= CreateEvent (NULL
, TRUE
, FALSE
, NULL
);
9501 if (cp
->ovl_write
.hEvent
== NULL
)
9502 error ("Could not create write event");
9507 /* For serial-process-configure */
9509 serial_configure (struct Lisp_Process
*p
, Lisp_Object contact
)
9511 Lisp_Object childp2
= Qnil
;
9512 Lisp_Object tem
= Qnil
;
9516 char summary
[4] = "???"; /* This usually becomes "8N1". */
9518 if ((fd_info
[ p
->outfd
].flags
& FILE_SERIAL
) == 0)
9519 error ("Not a serial process");
9520 hnd
= fd_info
[ p
->outfd
].hnd
;
9522 childp2
= Fcopy_sequence (p
->childp
);
9524 /* Initialize timeouts for blocking read and blocking write. */
9525 if (!GetCommTimeouts (hnd
, &ct
))
9526 error ("GetCommTimeouts() failed");
9527 ct
.ReadIntervalTimeout
= 0;
9528 ct
.ReadTotalTimeoutMultiplier
= 0;
9529 ct
.ReadTotalTimeoutConstant
= 0;
9530 ct
.WriteTotalTimeoutMultiplier
= 0;
9531 ct
.WriteTotalTimeoutConstant
= 0;
9532 if (!SetCommTimeouts (hnd
, &ct
))
9533 error ("SetCommTimeouts() failed");
9534 /* Read port attributes and prepare default configuration. */
9535 memset (&dcb
, 0, sizeof (dcb
));
9536 dcb
.DCBlength
= sizeof (DCB
);
9537 if (!GetCommState (hnd
, &dcb
))
9538 error ("GetCommState() failed");
9541 dcb
.fAbortOnError
= FALSE
;
9542 /* dcb.XonLim and dcb.XoffLim are set by GetCommState() */
9547 /* Configure speed. */
9548 if (!NILP (Fplist_member (contact
, QCspeed
)))
9549 tem
= Fplist_get (contact
, QCspeed
);
9551 tem
= Fplist_get (p
->childp
, QCspeed
);
9553 dcb
.BaudRate
= XINT (tem
);
9554 childp2
= Fplist_put (childp2
, QCspeed
, tem
);
9556 /* Configure bytesize. */
9557 if (!NILP (Fplist_member (contact
, QCbytesize
)))
9558 tem
= Fplist_get (contact
, QCbytesize
);
9560 tem
= Fplist_get (p
->childp
, QCbytesize
);
9562 tem
= make_number (8);
9564 if (XINT (tem
) != 7 && XINT (tem
) != 8)
9565 error (":bytesize must be nil (8), 7, or 8");
9566 dcb
.ByteSize
= XINT (tem
);
9567 summary
[0] = XINT (tem
) + '0';
9568 childp2
= Fplist_put (childp2
, QCbytesize
, tem
);
9570 /* Configure parity. */
9571 if (!NILP (Fplist_member (contact
, QCparity
)))
9572 tem
= Fplist_get (contact
, QCparity
);
9574 tem
= Fplist_get (p
->childp
, QCparity
);
9575 if (!NILP (tem
) && !EQ (tem
, Qeven
) && !EQ (tem
, Qodd
))
9576 error (":parity must be nil (no parity), `even', or `odd'");
9577 dcb
.fParity
= FALSE
;
9578 dcb
.Parity
= NOPARITY
;
9579 dcb
.fErrorChar
= FALSE
;
9584 else if (EQ (tem
, Qeven
))
9588 dcb
.Parity
= EVENPARITY
;
9589 dcb
.fErrorChar
= TRUE
;
9591 else if (EQ (tem
, Qodd
))
9595 dcb
.Parity
= ODDPARITY
;
9596 dcb
.fErrorChar
= TRUE
;
9598 childp2
= Fplist_put (childp2
, QCparity
, tem
);
9600 /* Configure stopbits. */
9601 if (!NILP (Fplist_member (contact
, QCstopbits
)))
9602 tem
= Fplist_get (contact
, QCstopbits
);
9604 tem
= Fplist_get (p
->childp
, QCstopbits
);
9606 tem
= make_number (1);
9608 if (XINT (tem
) != 1 && XINT (tem
) != 2)
9609 error (":stopbits must be nil (1 stopbit), 1, or 2");
9610 summary
[2] = XINT (tem
) + '0';
9611 if (XINT (tem
) == 1)
9612 dcb
.StopBits
= ONESTOPBIT
;
9613 else if (XINT (tem
) == 2)
9614 dcb
.StopBits
= TWOSTOPBITS
;
9615 childp2
= Fplist_put (childp2
, QCstopbits
, tem
);
9617 /* Configure flowcontrol. */
9618 if (!NILP (Fplist_member (contact
, QCflowcontrol
)))
9619 tem
= Fplist_get (contact
, QCflowcontrol
);
9621 tem
= Fplist_get (p
->childp
, QCflowcontrol
);
9622 if (!NILP (tem
) && !EQ (tem
, Qhw
) && !EQ (tem
, Qsw
))
9623 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
9624 dcb
.fOutxCtsFlow
= FALSE
;
9625 dcb
.fOutxDsrFlow
= FALSE
;
9626 dcb
.fDtrControl
= DTR_CONTROL_DISABLE
;
9627 dcb
.fDsrSensitivity
= FALSE
;
9628 dcb
.fTXContinueOnXoff
= FALSE
;
9631 dcb
.fRtsControl
= RTS_CONTROL_DISABLE
;
9632 dcb
.XonChar
= 17; /* Control-Q */
9633 dcb
.XoffChar
= 19; /* Control-S */
9636 /* Already configured. */
9638 else if (EQ (tem
, Qhw
))
9640 dcb
.fRtsControl
= RTS_CONTROL_HANDSHAKE
;
9641 dcb
.fOutxCtsFlow
= TRUE
;
9643 else if (EQ (tem
, Qsw
))
9648 childp2
= Fplist_put (childp2
, QCflowcontrol
, tem
);
9650 /* Activate configuration. */
9651 if (!SetCommState (hnd
, &dcb
))
9652 error ("SetCommState() failed");
9654 childp2
= Fplist_put (childp2
, QCsummary
, build_string (summary
));
9655 pset_childp (p
, childp2
);
9658 /* For make-pipe-process */
9660 register_aux_fd (int infd
)
9666 error ("Could not create child process");
9668 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
9670 if (fd_info
[ infd
].cp
!= NULL
)
9672 error ("fd_info[fd = %d] is already in use", infd
);
9674 fd_info
[ infd
].cp
= cp
;
9675 fd_info
[ infd
].hnd
= (HANDLE
) _get_osfhandle (infd
);
9681 emacs_gnutls_pull (gnutls_transport_ptr_t p
, void* buf
, size_t sz
)
9684 struct Lisp_Process
*process
= (struct Lisp_Process
*)p
;
9685 int fd
= process
->infd
;
9687 n
= sys_read (fd
, (char*)buf
, sz
);
9694 /* Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
9695 if (err
== EWOULDBLOCK
)
9698 emacs_gnutls_transport_set_errno (process
->gnutls_state
, err
);
9704 emacs_gnutls_push (gnutls_transport_ptr_t p
, const void* buf
, size_t sz
)
9706 struct Lisp_Process
*process
= (struct Lisp_Process
*)p
;
9707 int fd
= process
->outfd
;
9708 ssize_t n
= sys_write (fd
, buf
, sz
);
9710 /* 0 or more bytes written means everything went fine. */
9714 /* Negative bytes written means we got an error in errno.
9715 Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
9716 emacs_gnutls_transport_set_errno (process
->gnutls_state
,
9717 errno
== EWOULDBLOCK
? EAGAIN
: errno
);
9721 #endif /* HAVE_GNUTLS */