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, ... */
69 char *sys_ctime (const time_t *);
70 int sys_chdir (const char *);
71 int sys_creat (const char *, int);
72 FILE *sys_fopen (const char *, const char *);
73 int sys_mkdir (const char *);
74 int sys_open (const char *, int, int);
75 int sys_rename (char const *, char const *);
76 int sys_rmdir (const char *);
78 int sys_dup2 (int, int);
79 int sys_read (int, char *, unsigned int);
80 int sys_write (int, const void *, unsigned int);
81 struct tm
*sys_localtime (const time_t *);
84 extern void dynlib_reset_last_error (void);
88 #include "epaths.h" /* for PATH_EXEC */
93 /* MinGW64 defines these in its _mingw.h. */
94 #ifndef _ANONYMOUS_UNION
95 # define _ANONYMOUS_UNION
97 #ifndef _ANONYMOUS_STRUCT
98 # define _ANONYMOUS_STRUCT
101 /* Some versions of compiler define MEMORYSTATUSEX, some don't, so we
102 use a different name to avoid compilation problems. */
103 typedef struct _MEMORY_STATUS_EX
{
106 DWORDLONG ullTotalPhys
;
107 DWORDLONG ullAvailPhys
;
108 DWORDLONG ullTotalPageFile
;
109 DWORDLONG ullAvailPageFile
;
110 DWORDLONG ullTotalVirtual
;
111 DWORDLONG ullAvailVirtual
;
112 DWORDLONG ullAvailExtendedVirtual
;
113 } MEMORY_STATUS_EX
,*LPMEMORY_STATUS_EX
;
115 /* These are here so that GDB would know about these data types. This
116 allows attaching GDB to Emacs when a fatal exception is triggered
117 and Windows pops up the "application needs to be closed" dialog.
118 At that point, _gnu_exception_handler, the top-level exception
119 handler installed by the MinGW startup code, is somewhere on the
120 call-stack of the main thread, so going to that call frame and
121 looking at the argument to _gnu_exception_handler, which is a
122 PEXCEPTION_POINTERS pointer, can reveal the exception code
123 (excptr->ExceptionRecord->ExceptionCode) and the address where the
124 exception happened (excptr->ExceptionRecord->ExceptionAddress), as
125 well as some additional information specific to the exception. */
126 PEXCEPTION_POINTERS excptr
;
127 PEXCEPTION_RECORD excprec
;
133 #include <tlhelp32.h>
138 #if _WIN32_WINNT < 0x0500
139 #if !defined (__MINGW32__) || __W32API_MAJOR_VERSION < 3 || (__W32API_MAJOR_VERSION == 3 && __W32API_MINOR_VERSION < 15)
140 /* This either is not in psapi.h or guarded by higher value of
141 _WIN32_WINNT than what we use. w32api supplied with MinGW 3.15
142 defines it in psapi.h */
143 typedef struct _PROCESS_MEMORY_COUNTERS_EX
{
145 DWORD PageFaultCount
;
146 SIZE_T PeakWorkingSetSize
;
147 SIZE_T WorkingSetSize
;
148 SIZE_T QuotaPeakPagedPoolUsage
;
149 SIZE_T QuotaPagedPoolUsage
;
150 SIZE_T QuotaPeakNonPagedPoolUsage
;
151 SIZE_T QuotaNonPagedPoolUsage
;
152 SIZE_T PagefileUsage
;
153 SIZE_T PeakPagefileUsage
;
155 } PROCESS_MEMORY_COUNTERS_EX
,*PPROCESS_MEMORY_COUNTERS_EX
;
159 #include <winioctl.h>
166 /* This is not in MinGW's sddl.h (but they are in MSVC headers), so we
167 define them by hand if not already defined. */
168 #ifndef SDDL_REVISION_1
169 #define SDDL_REVISION_1 1
170 #endif /* SDDL_REVISION_1 */
172 #if defined(_MSC_VER) || defined(MINGW_W64)
173 /* MSVC and MinGW64 don't provide the definition of
174 REPARSE_DATA_BUFFER and the associated macros, except on ntifs.h,
175 which cannot be included because it triggers conflicts with other
176 Windows API headers. So we define it here by hand. */
178 typedef struct _REPARSE_DATA_BUFFER
{
180 USHORT ReparseDataLength
;
184 USHORT SubstituteNameOffset
;
185 USHORT SubstituteNameLength
;
186 USHORT PrintNameOffset
;
187 USHORT PrintNameLength
;
190 } SymbolicLinkReparseBuffer
;
192 USHORT SubstituteNameOffset
;
193 USHORT SubstituteNameLength
;
194 USHORT PrintNameOffset
;
195 USHORT PrintNameLength
;
197 } MountPointReparseBuffer
;
200 } GenericReparseBuffer
;
202 } REPARSE_DATA_BUFFER
, *PREPARSE_DATA_BUFFER
;
204 #ifndef FILE_DEVICE_FILE_SYSTEM
205 #define FILE_DEVICE_FILE_SYSTEM 9
207 #ifndef METHOD_BUFFERED
208 #define METHOD_BUFFERED 0
210 #ifndef FILE_ANY_ACCESS
211 #define FILE_ANY_ACCESS 0x00000000
214 #define CTL_CODE(t,f,m,a) (((t)<<16)|((a)<<14)|((f)<<2)|(m))
216 /* MinGW64 defines FSCTL_GET_REPARSE_POINT on winioctl.h. */
217 #ifndef FSCTL_GET_REPARSE_POINT
218 #define FSCTL_GET_REPARSE_POINT \
219 CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 42, METHOD_BUFFERED, FILE_ANY_ACCESS)
223 /* TCP connection support. */
224 #include <sys/socket.h>
243 #include <iphlpapi.h> /* should be after winsock2.h */
245 #include <wincrypt.h>
247 #include <c-strcase.h>
248 #include <utimens.h> /* for fdutimens */
252 #include "w32common.h"
253 #include "w32select.h"
254 #include "systime.h" /* for current_timespec, struct timespec */
255 #include "dispextern.h" /* for xstrcasecmp */
256 #include "coding.h" /* for Vlocale_coding_system */
258 #include "careadlinkat.h"
259 #include "allocator.h"
261 /* For Lisp_Process, serial_configure and serial_open. */
265 typedef HRESULT (WINAPI
* ShGetFolderPath_fn
)
266 (IN HWND
, IN
int, IN HANDLE
, IN DWORD
, OUT
char *);
268 static DWORD
get_rid (PSID
);
269 static int is_symlink (const char *);
270 static char * chase_symlinks (const char *);
271 static int enable_privilege (LPCTSTR
, BOOL
, TOKEN_PRIVILEGES
*);
272 static int restore_privilege (TOKEN_PRIVILEGES
*);
273 static BOOL WINAPI
revert_to_self (void);
275 static int sys_access (const char *, int);
276 extern void *e_malloc (size_t);
277 extern int sys_select (int, SELECT_TYPE
*, SELECT_TYPE
*, SELECT_TYPE
*,
278 struct timespec
*, void *);
279 extern int sys_dup (int);
284 /* Initialization states.
286 WARNING: If you add any more such variables for additional APIs,
287 you MUST add initialization for them to globals_of_w32
288 below. This is because these variables might get set
289 to non-NULL values during dumping, but the dumped Emacs
290 cannot reuse those values, because it could be run on a
291 different version of the OS, where API addresses are
293 static BOOL g_b_init_is_windows_9x
;
294 static BOOL g_b_init_open_process_token
;
295 static BOOL g_b_init_get_token_information
;
296 static BOOL g_b_init_lookup_account_sid
;
297 static BOOL g_b_init_get_sid_sub_authority
;
298 static BOOL g_b_init_get_sid_sub_authority_count
;
299 static BOOL g_b_init_get_security_info
;
300 static BOOL g_b_init_get_file_security_w
;
301 static BOOL g_b_init_get_file_security_a
;
302 static BOOL g_b_init_get_security_descriptor_owner
;
303 static BOOL g_b_init_get_security_descriptor_group
;
304 static BOOL g_b_init_is_valid_sid
;
305 static BOOL g_b_init_create_toolhelp32_snapshot
;
306 static BOOL g_b_init_process32_first
;
307 static BOOL g_b_init_process32_next
;
308 static BOOL g_b_init_open_thread_token
;
309 static BOOL g_b_init_impersonate_self
;
310 static BOOL g_b_init_revert_to_self
;
311 static BOOL g_b_init_get_process_memory_info
;
312 static BOOL g_b_init_get_process_working_set_size
;
313 static BOOL g_b_init_global_memory_status
;
314 static BOOL g_b_init_global_memory_status_ex
;
315 static BOOL g_b_init_get_length_sid
;
316 static BOOL g_b_init_equal_sid
;
317 static BOOL g_b_init_copy_sid
;
318 static BOOL g_b_init_get_native_system_info
;
319 static BOOL g_b_init_get_system_times
;
320 static BOOL g_b_init_create_symbolic_link_w
;
321 static BOOL g_b_init_create_symbolic_link_a
;
322 static BOOL g_b_init_get_security_descriptor_dacl
;
323 static BOOL g_b_init_convert_sd_to_sddl
;
324 static BOOL g_b_init_convert_sddl_to_sd
;
325 static BOOL g_b_init_is_valid_security_descriptor
;
326 static BOOL g_b_init_set_file_security_w
;
327 static BOOL g_b_init_set_file_security_a
;
328 static BOOL g_b_init_set_named_security_info_w
;
329 static BOOL g_b_init_set_named_security_info_a
;
330 static BOOL g_b_init_get_adapters_info
;
332 BOOL g_b_init_compare_string_w
;
335 BEGIN: Wrapper functions around OpenProcessToken
336 and other functions in advapi32.dll that are only
337 supported in Windows NT / 2k / XP
339 /* ** Function pointer typedefs ** */
340 typedef BOOL (WINAPI
* OpenProcessToken_Proc
) (
341 HANDLE ProcessHandle
,
343 PHANDLE TokenHandle
);
344 typedef BOOL (WINAPI
* GetTokenInformation_Proc
) (
346 TOKEN_INFORMATION_CLASS TokenInformationClass
,
347 LPVOID TokenInformation
,
348 DWORD TokenInformationLength
,
349 PDWORD ReturnLength
);
350 typedef BOOL (WINAPI
* GetProcessTimes_Proc
) (
351 HANDLE process_handle
,
352 LPFILETIME creation_time
,
353 LPFILETIME exit_time
,
354 LPFILETIME kernel_time
,
355 LPFILETIME user_time
);
357 GetProcessTimes_Proc get_process_times_fn
= NULL
;
360 const char * const LookupAccountSid_Name
= "LookupAccountSidW";
362 const char * const LookupAccountSid_Name
= "LookupAccountSidA";
364 typedef BOOL (WINAPI
* LookupAccountSid_Proc
) (
365 LPCTSTR lpSystemName
,
370 LPDWORD cbDomainName
,
371 PSID_NAME_USE peUse
);
372 typedef PDWORD (WINAPI
* GetSidSubAuthority_Proc
) (
375 typedef PUCHAR (WINAPI
* GetSidSubAuthorityCount_Proc
) (
377 typedef DWORD (WINAPI
* GetSecurityInfo_Proc
) (
379 SE_OBJECT_TYPE ObjectType
,
380 SECURITY_INFORMATION SecurityInfo
,
385 PSECURITY_DESCRIPTOR
*ppSecurityDescriptor
);
386 typedef BOOL (WINAPI
* GetFileSecurityW_Proc
) (
388 SECURITY_INFORMATION RequestedInformation
,
389 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
391 LPDWORD lpnLengthNeeded
);
392 typedef BOOL (WINAPI
* GetFileSecurityA_Proc
) (
394 SECURITY_INFORMATION RequestedInformation
,
395 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
397 LPDWORD lpnLengthNeeded
);
398 typedef BOOL (WINAPI
*SetFileSecurityW_Proc
) (
400 SECURITY_INFORMATION SecurityInformation
,
401 PSECURITY_DESCRIPTOR pSecurityDescriptor
);
402 typedef BOOL (WINAPI
*SetFileSecurityA_Proc
) (
404 SECURITY_INFORMATION SecurityInformation
,
405 PSECURITY_DESCRIPTOR pSecurityDescriptor
);
406 typedef DWORD (WINAPI
*SetNamedSecurityInfoW_Proc
) (
407 LPCWSTR lpObjectName
,
408 SE_OBJECT_TYPE ObjectType
,
409 SECURITY_INFORMATION SecurityInformation
,
414 typedef DWORD (WINAPI
*SetNamedSecurityInfoA_Proc
) (
416 SE_OBJECT_TYPE ObjectType
,
417 SECURITY_INFORMATION SecurityInformation
,
422 typedef BOOL (WINAPI
* GetSecurityDescriptorOwner_Proc
) (
423 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
425 LPBOOL lpbOwnerDefaulted
);
426 typedef BOOL (WINAPI
* GetSecurityDescriptorGroup_Proc
) (
427 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
429 LPBOOL lpbGroupDefaulted
);
430 typedef BOOL (WINAPI
*GetSecurityDescriptorDacl_Proc
) (
431 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
432 LPBOOL lpbDaclPresent
,
434 LPBOOL lpbDaclDefaulted
);
435 typedef BOOL (WINAPI
* IsValidSid_Proc
) (
437 typedef HANDLE (WINAPI
* CreateToolhelp32Snapshot_Proc
) (
439 DWORD th32ProcessID
);
440 typedef BOOL (WINAPI
* Process32First_Proc
) (
442 LPPROCESSENTRY32 lppe
);
443 typedef BOOL (WINAPI
* Process32Next_Proc
) (
445 LPPROCESSENTRY32 lppe
);
446 typedef BOOL (WINAPI
* OpenThreadToken_Proc
) (
450 PHANDLE TokenHandle
);
451 typedef BOOL (WINAPI
* ImpersonateSelf_Proc
) (
452 SECURITY_IMPERSONATION_LEVEL ImpersonationLevel
);
453 typedef BOOL (WINAPI
* RevertToSelf_Proc
) (void);
454 typedef BOOL (WINAPI
* GetProcessMemoryInfo_Proc
) (
456 PPROCESS_MEMORY_COUNTERS ppsmemCounters
,
458 typedef BOOL (WINAPI
* GetProcessWorkingSetSize_Proc
) (
460 PSIZE_T lpMinimumWorkingSetSize
,
461 PSIZE_T lpMaximumWorkingSetSize
);
462 typedef BOOL (WINAPI
* GlobalMemoryStatus_Proc
) (
463 LPMEMORYSTATUS lpBuffer
);
464 typedef BOOL (WINAPI
* GlobalMemoryStatusEx_Proc
) (
465 LPMEMORY_STATUS_EX lpBuffer
);
466 typedef BOOL (WINAPI
* CopySid_Proc
) (
467 DWORD nDestinationSidLength
,
468 PSID pDestinationSid
,
470 typedef BOOL (WINAPI
* EqualSid_Proc
) (
473 typedef DWORD (WINAPI
* GetLengthSid_Proc
) (
475 typedef void (WINAPI
* GetNativeSystemInfo_Proc
) (
476 LPSYSTEM_INFO lpSystemInfo
);
477 typedef BOOL (WINAPI
* GetSystemTimes_Proc
) (
478 LPFILETIME lpIdleTime
,
479 LPFILETIME lpKernelTime
,
480 LPFILETIME lpUserTime
);
481 typedef BOOLEAN (WINAPI
*CreateSymbolicLinkW_Proc
) (
482 LPCWSTR lpSymlinkFileName
,
483 LPCWSTR lpTargetFileName
,
485 typedef BOOLEAN (WINAPI
*CreateSymbolicLinkA_Proc
) (
486 LPCSTR lpSymlinkFileName
,
487 LPCSTR lpTargetFileName
,
489 typedef BOOL (WINAPI
*ConvertStringSecurityDescriptorToSecurityDescriptor_Proc
) (
490 LPCTSTR StringSecurityDescriptor
,
491 DWORD StringSDRevision
,
492 PSECURITY_DESCRIPTOR
*SecurityDescriptor
,
493 PULONG SecurityDescriptorSize
);
494 typedef BOOL (WINAPI
*ConvertSecurityDescriptorToStringSecurityDescriptor_Proc
) (
495 PSECURITY_DESCRIPTOR SecurityDescriptor
,
496 DWORD RequestedStringSDRevision
,
497 SECURITY_INFORMATION SecurityInformation
,
498 LPTSTR
*StringSecurityDescriptor
,
499 PULONG StringSecurityDescriptorLen
);
500 typedef BOOL (WINAPI
*IsValidSecurityDescriptor_Proc
) (PSECURITY_DESCRIPTOR
);
501 typedef DWORD (WINAPI
*GetAdaptersInfo_Proc
) (
502 PIP_ADAPTER_INFO pAdapterInfo
,
505 int (WINAPI
*pMultiByteToWideChar
)(UINT
,DWORD
,LPCSTR
,int,LPWSTR
,int);
506 int (WINAPI
*pWideCharToMultiByte
)(UINT
,DWORD
,LPCWSTR
,int,LPSTR
,int,LPCSTR
,LPBOOL
);
507 DWORD multiByteToWideCharFlags
;
509 /* ** A utility function ** */
513 static BOOL s_b_ret
= 0;
514 OSVERSIONINFO os_ver
;
515 if (g_b_init_is_windows_9x
== 0)
517 g_b_init_is_windows_9x
= 1;
518 ZeroMemory (&os_ver
, sizeof (OSVERSIONINFO
));
519 os_ver
.dwOSVersionInfoSize
= sizeof (OSVERSIONINFO
);
520 if (GetVersionEx (&os_ver
))
522 s_b_ret
= (os_ver
.dwPlatformId
== VER_PLATFORM_WIN32_WINDOWS
);
528 static Lisp_Object
ltime (ULONGLONG
);
530 /* Get total user and system times for get-internal-run-time.
531 Returns a list of integers if the times are provided by the OS
532 (NT derivatives), otherwise it returns the result of current-time. */
533 Lisp_Object
w32_get_internal_run_time (void);
536 w32_get_internal_run_time (void)
538 if (get_process_times_fn
)
540 FILETIME create
, exit
, kernel
, user
;
541 HANDLE proc
= GetCurrentProcess ();
542 if ((*get_process_times_fn
) (proc
, &create
, &exit
, &kernel
, &user
))
544 LARGE_INTEGER user_int
, kernel_int
, total
;
545 user_int
.LowPart
= user
.dwLowDateTime
;
546 user_int
.HighPart
= user
.dwHighDateTime
;
547 kernel_int
.LowPart
= kernel
.dwLowDateTime
;
548 kernel_int
.HighPart
= kernel
.dwHighDateTime
;
549 total
.QuadPart
= user_int
.QuadPart
+ kernel_int
.QuadPart
;
550 return ltime (total
.QuadPart
);
554 return Fcurrent_time ();
557 /* ** The wrapper functions ** */
560 open_process_token (HANDLE ProcessHandle
,
564 static OpenProcessToken_Proc s_pfn_Open_Process_Token
= NULL
;
565 HMODULE hm_advapi32
= NULL
;
566 if (is_windows_9x () == TRUE
)
570 if (g_b_init_open_process_token
== 0)
572 g_b_init_open_process_token
= 1;
573 hm_advapi32
= LoadLibrary ("Advapi32.dll");
574 s_pfn_Open_Process_Token
=
575 (OpenProcessToken_Proc
) GetProcAddress (hm_advapi32
, "OpenProcessToken");
577 if (s_pfn_Open_Process_Token
== NULL
)
582 s_pfn_Open_Process_Token (
590 get_token_information (HANDLE TokenHandle
,
591 TOKEN_INFORMATION_CLASS TokenInformationClass
,
592 LPVOID TokenInformation
,
593 DWORD TokenInformationLength
,
596 static GetTokenInformation_Proc s_pfn_Get_Token_Information
= NULL
;
597 HMODULE hm_advapi32
= NULL
;
598 if (is_windows_9x () == TRUE
)
602 if (g_b_init_get_token_information
== 0)
604 g_b_init_get_token_information
= 1;
605 hm_advapi32
= LoadLibrary ("Advapi32.dll");
606 s_pfn_Get_Token_Information
=
607 (GetTokenInformation_Proc
) GetProcAddress (hm_advapi32
, "GetTokenInformation");
609 if (s_pfn_Get_Token_Information
== NULL
)
614 s_pfn_Get_Token_Information (
616 TokenInformationClass
,
618 TokenInformationLength
,
624 lookup_account_sid (LPCTSTR lpSystemName
,
629 LPDWORD cbDomainName
,
632 static LookupAccountSid_Proc s_pfn_Lookup_Account_Sid
= NULL
;
633 HMODULE hm_advapi32
= NULL
;
634 if (is_windows_9x () == TRUE
)
638 if (g_b_init_lookup_account_sid
== 0)
640 g_b_init_lookup_account_sid
= 1;
641 hm_advapi32
= LoadLibrary ("Advapi32.dll");
642 s_pfn_Lookup_Account_Sid
=
643 (LookupAccountSid_Proc
) GetProcAddress (hm_advapi32
, LookupAccountSid_Name
);
645 if (s_pfn_Lookup_Account_Sid
== NULL
)
650 s_pfn_Lookup_Account_Sid (
662 get_sid_sub_authority (PSID pSid
, DWORD n
)
664 static GetSidSubAuthority_Proc s_pfn_Get_Sid_Sub_Authority
= NULL
;
665 static DWORD zero
= 0U;
666 HMODULE hm_advapi32
= NULL
;
667 if (is_windows_9x () == TRUE
)
671 if (g_b_init_get_sid_sub_authority
== 0)
673 g_b_init_get_sid_sub_authority
= 1;
674 hm_advapi32
= LoadLibrary ("Advapi32.dll");
675 s_pfn_Get_Sid_Sub_Authority
=
676 (GetSidSubAuthority_Proc
) GetProcAddress (
677 hm_advapi32
, "GetSidSubAuthority");
679 if (s_pfn_Get_Sid_Sub_Authority
== NULL
)
683 return (s_pfn_Get_Sid_Sub_Authority (pSid
, n
));
687 get_sid_sub_authority_count (PSID pSid
)
689 static GetSidSubAuthorityCount_Proc s_pfn_Get_Sid_Sub_Authority_Count
= NULL
;
690 static UCHAR zero
= 0U;
691 HMODULE hm_advapi32
= NULL
;
692 if (is_windows_9x () == TRUE
)
696 if (g_b_init_get_sid_sub_authority_count
== 0)
698 g_b_init_get_sid_sub_authority_count
= 1;
699 hm_advapi32
= LoadLibrary ("Advapi32.dll");
700 s_pfn_Get_Sid_Sub_Authority_Count
=
701 (GetSidSubAuthorityCount_Proc
) GetProcAddress (
702 hm_advapi32
, "GetSidSubAuthorityCount");
704 if (s_pfn_Get_Sid_Sub_Authority_Count
== NULL
)
708 return (s_pfn_Get_Sid_Sub_Authority_Count (pSid
));
712 get_security_info (HANDLE handle
,
713 SE_OBJECT_TYPE ObjectType
,
714 SECURITY_INFORMATION SecurityInfo
,
719 PSECURITY_DESCRIPTOR
*ppSecurityDescriptor
)
721 static GetSecurityInfo_Proc s_pfn_Get_Security_Info
= NULL
;
722 HMODULE hm_advapi32
= NULL
;
723 if (is_windows_9x () == TRUE
)
727 if (g_b_init_get_security_info
== 0)
729 g_b_init_get_security_info
= 1;
730 hm_advapi32
= LoadLibrary ("Advapi32.dll");
731 s_pfn_Get_Security_Info
=
732 (GetSecurityInfo_Proc
) GetProcAddress (
733 hm_advapi32
, "GetSecurityInfo");
735 if (s_pfn_Get_Security_Info
== NULL
)
739 return (s_pfn_Get_Security_Info (handle
, ObjectType
, SecurityInfo
,
740 ppsidOwner
, ppsidGroup
, ppDacl
, ppSacl
,
741 ppSecurityDescriptor
));
745 get_file_security (const char *lpFileName
,
746 SECURITY_INFORMATION RequestedInformation
,
747 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
749 LPDWORD lpnLengthNeeded
)
751 static GetFileSecurityA_Proc s_pfn_Get_File_SecurityA
= NULL
;
752 static GetFileSecurityW_Proc s_pfn_Get_File_SecurityW
= NULL
;
753 HMODULE hm_advapi32
= NULL
;
754 if (is_windows_9x () == TRUE
)
759 if (w32_unicode_filenames
)
761 wchar_t filename_w
[MAX_PATH
];
763 if (g_b_init_get_file_security_w
== 0)
765 g_b_init_get_file_security_w
= 1;
766 hm_advapi32
= LoadLibrary ("Advapi32.dll");
767 s_pfn_Get_File_SecurityW
=
768 (GetFileSecurityW_Proc
) GetProcAddress (hm_advapi32
,
771 if (s_pfn_Get_File_SecurityW
== NULL
)
776 filename_to_utf16 (lpFileName
, filename_w
);
777 return (s_pfn_Get_File_SecurityW (filename_w
, RequestedInformation
,
778 pSecurityDescriptor
, nLength
,
783 char filename_a
[MAX_PATH
];
785 if (g_b_init_get_file_security_a
== 0)
787 g_b_init_get_file_security_a
= 1;
788 hm_advapi32
= LoadLibrary ("Advapi32.dll");
789 s_pfn_Get_File_SecurityA
=
790 (GetFileSecurityA_Proc
) GetProcAddress (hm_advapi32
,
793 if (s_pfn_Get_File_SecurityA
== NULL
)
798 filename_to_ansi (lpFileName
, filename_a
);
799 return (s_pfn_Get_File_SecurityA (filename_a
, RequestedInformation
,
800 pSecurityDescriptor
, nLength
,
806 set_file_security (const char *lpFileName
,
807 SECURITY_INFORMATION SecurityInformation
,
808 PSECURITY_DESCRIPTOR pSecurityDescriptor
)
810 static SetFileSecurityW_Proc s_pfn_Set_File_SecurityW
= NULL
;
811 static SetFileSecurityA_Proc s_pfn_Set_File_SecurityA
= NULL
;
812 HMODULE hm_advapi32
= NULL
;
813 if (is_windows_9x () == TRUE
)
818 if (w32_unicode_filenames
)
820 wchar_t filename_w
[MAX_PATH
];
822 if (g_b_init_set_file_security_w
== 0)
824 g_b_init_set_file_security_w
= 1;
825 hm_advapi32
= LoadLibrary ("Advapi32.dll");
826 s_pfn_Set_File_SecurityW
=
827 (SetFileSecurityW_Proc
) GetProcAddress (hm_advapi32
,
830 if (s_pfn_Set_File_SecurityW
== NULL
)
835 filename_to_utf16 (lpFileName
, filename_w
);
836 return (s_pfn_Set_File_SecurityW (filename_w
, SecurityInformation
,
837 pSecurityDescriptor
));
841 char filename_a
[MAX_PATH
];
843 if (g_b_init_set_file_security_a
== 0)
845 g_b_init_set_file_security_a
= 1;
846 hm_advapi32
= LoadLibrary ("Advapi32.dll");
847 s_pfn_Set_File_SecurityA
=
848 (SetFileSecurityA_Proc
) GetProcAddress (hm_advapi32
,
851 if (s_pfn_Set_File_SecurityA
== NULL
)
856 filename_to_ansi (lpFileName
, filename_a
);
857 return (s_pfn_Set_File_SecurityA (filename_a
, SecurityInformation
,
858 pSecurityDescriptor
));
863 set_named_security_info (LPCTSTR lpObjectName
,
864 SE_OBJECT_TYPE ObjectType
,
865 SECURITY_INFORMATION SecurityInformation
,
871 static SetNamedSecurityInfoW_Proc s_pfn_Set_Named_Security_InfoW
= NULL
;
872 static SetNamedSecurityInfoA_Proc s_pfn_Set_Named_Security_InfoA
= NULL
;
873 HMODULE hm_advapi32
= NULL
;
874 if (is_windows_9x () == TRUE
)
879 if (w32_unicode_filenames
)
881 wchar_t filename_w
[MAX_PATH
];
883 if (g_b_init_set_named_security_info_w
== 0)
885 g_b_init_set_named_security_info_w
= 1;
886 hm_advapi32
= LoadLibrary ("Advapi32.dll");
887 s_pfn_Set_Named_Security_InfoW
=
888 (SetNamedSecurityInfoW_Proc
) GetProcAddress (hm_advapi32
,
889 "SetNamedSecurityInfoW");
891 if (s_pfn_Set_Named_Security_InfoW
== NULL
)
896 filename_to_utf16 (lpObjectName
, filename_w
);
897 return (s_pfn_Set_Named_Security_InfoW (filename_w
, ObjectType
,
898 SecurityInformation
, psidOwner
,
899 psidGroup
, pDacl
, pSacl
));
903 char filename_a
[MAX_PATH
];
905 if (g_b_init_set_named_security_info_a
== 0)
907 g_b_init_set_named_security_info_a
= 1;
908 hm_advapi32
= LoadLibrary ("Advapi32.dll");
909 s_pfn_Set_Named_Security_InfoA
=
910 (SetNamedSecurityInfoA_Proc
) GetProcAddress (hm_advapi32
,
911 "SetNamedSecurityInfoA");
913 if (s_pfn_Set_Named_Security_InfoA
== NULL
)
918 filename_to_ansi (lpObjectName
, filename_a
);
919 return (s_pfn_Set_Named_Security_InfoA (filename_a
, ObjectType
,
920 SecurityInformation
, psidOwner
,
921 psidGroup
, pDacl
, pSacl
));
926 get_security_descriptor_owner (PSECURITY_DESCRIPTOR pSecurityDescriptor
,
928 LPBOOL lpbOwnerDefaulted
)
930 static GetSecurityDescriptorOwner_Proc s_pfn_Get_Security_Descriptor_Owner
= NULL
;
931 HMODULE hm_advapi32
= NULL
;
932 if (is_windows_9x () == TRUE
)
937 if (g_b_init_get_security_descriptor_owner
== 0)
939 g_b_init_get_security_descriptor_owner
= 1;
940 hm_advapi32
= LoadLibrary ("Advapi32.dll");
941 s_pfn_Get_Security_Descriptor_Owner
=
942 (GetSecurityDescriptorOwner_Proc
) GetProcAddress (
943 hm_advapi32
, "GetSecurityDescriptorOwner");
945 if (s_pfn_Get_Security_Descriptor_Owner
== NULL
)
950 return (s_pfn_Get_Security_Descriptor_Owner (pSecurityDescriptor
, pOwner
,
955 get_security_descriptor_group (PSECURITY_DESCRIPTOR pSecurityDescriptor
,
957 LPBOOL lpbGroupDefaulted
)
959 static GetSecurityDescriptorGroup_Proc s_pfn_Get_Security_Descriptor_Group
= NULL
;
960 HMODULE hm_advapi32
= NULL
;
961 if (is_windows_9x () == TRUE
)
966 if (g_b_init_get_security_descriptor_group
== 0)
968 g_b_init_get_security_descriptor_group
= 1;
969 hm_advapi32
= LoadLibrary ("Advapi32.dll");
970 s_pfn_Get_Security_Descriptor_Group
=
971 (GetSecurityDescriptorGroup_Proc
) GetProcAddress (
972 hm_advapi32
, "GetSecurityDescriptorGroup");
974 if (s_pfn_Get_Security_Descriptor_Group
== NULL
)
979 return (s_pfn_Get_Security_Descriptor_Group (pSecurityDescriptor
, pGroup
,
984 get_security_descriptor_dacl (PSECURITY_DESCRIPTOR pSecurityDescriptor
,
985 LPBOOL lpbDaclPresent
,
987 LPBOOL lpbDaclDefaulted
)
989 static GetSecurityDescriptorDacl_Proc s_pfn_Get_Security_Descriptor_Dacl
= NULL
;
990 HMODULE hm_advapi32
= NULL
;
991 if (is_windows_9x () == TRUE
)
996 if (g_b_init_get_security_descriptor_dacl
== 0)
998 g_b_init_get_security_descriptor_dacl
= 1;
999 hm_advapi32
= LoadLibrary ("Advapi32.dll");
1000 s_pfn_Get_Security_Descriptor_Dacl
=
1001 (GetSecurityDescriptorDacl_Proc
) GetProcAddress (
1002 hm_advapi32
, "GetSecurityDescriptorDacl");
1004 if (s_pfn_Get_Security_Descriptor_Dacl
== NULL
)
1009 return (s_pfn_Get_Security_Descriptor_Dacl (pSecurityDescriptor
,
1010 lpbDaclPresent
, pDacl
,
1015 is_valid_sid (PSID sid
)
1017 static IsValidSid_Proc s_pfn_Is_Valid_Sid
= NULL
;
1018 HMODULE hm_advapi32
= NULL
;
1019 if (is_windows_9x () == TRUE
)
1023 if (g_b_init_is_valid_sid
== 0)
1025 g_b_init_is_valid_sid
= 1;
1026 hm_advapi32
= LoadLibrary ("Advapi32.dll");
1027 s_pfn_Is_Valid_Sid
=
1028 (IsValidSid_Proc
) GetProcAddress (
1029 hm_advapi32
, "IsValidSid");
1031 if (s_pfn_Is_Valid_Sid
== NULL
)
1035 return (s_pfn_Is_Valid_Sid (sid
));
1039 equal_sid (PSID sid1
, PSID sid2
)
1041 static EqualSid_Proc s_pfn_Equal_Sid
= NULL
;
1042 HMODULE hm_advapi32
= NULL
;
1043 if (is_windows_9x () == TRUE
)
1047 if (g_b_init_equal_sid
== 0)
1049 g_b_init_equal_sid
= 1;
1050 hm_advapi32
= LoadLibrary ("Advapi32.dll");
1052 (EqualSid_Proc
) GetProcAddress (
1053 hm_advapi32
, "EqualSid");
1055 if (s_pfn_Equal_Sid
== NULL
)
1059 return (s_pfn_Equal_Sid (sid1
, sid2
));
1063 get_length_sid (PSID sid
)
1065 static GetLengthSid_Proc s_pfn_Get_Length_Sid
= NULL
;
1066 HMODULE hm_advapi32
= NULL
;
1067 if (is_windows_9x () == TRUE
)
1071 if (g_b_init_get_length_sid
== 0)
1073 g_b_init_get_length_sid
= 1;
1074 hm_advapi32
= LoadLibrary ("Advapi32.dll");
1075 s_pfn_Get_Length_Sid
=
1076 (GetLengthSid_Proc
) GetProcAddress (
1077 hm_advapi32
, "GetLengthSid");
1079 if (s_pfn_Get_Length_Sid
== NULL
)
1083 return (s_pfn_Get_Length_Sid (sid
));
1087 copy_sid (DWORD destlen
, PSID dest
, PSID src
)
1089 static CopySid_Proc s_pfn_Copy_Sid
= NULL
;
1090 HMODULE hm_advapi32
= NULL
;
1091 if (is_windows_9x () == TRUE
)
1095 if (g_b_init_copy_sid
== 0)
1097 g_b_init_copy_sid
= 1;
1098 hm_advapi32
= LoadLibrary ("Advapi32.dll");
1100 (CopySid_Proc
) GetProcAddress (
1101 hm_advapi32
, "CopySid");
1103 if (s_pfn_Copy_Sid
== NULL
)
1107 return (s_pfn_Copy_Sid (destlen
, dest
, src
));
1111 END: Wrapper functions around OpenProcessToken
1112 and other functions in advapi32.dll that are only
1113 supported in Windows NT / 2k / XP
1117 get_native_system_info (LPSYSTEM_INFO lpSystemInfo
)
1119 static GetNativeSystemInfo_Proc s_pfn_Get_Native_System_Info
= NULL
;
1120 if (is_windows_9x () != TRUE
)
1122 if (g_b_init_get_native_system_info
== 0)
1124 g_b_init_get_native_system_info
= 1;
1125 s_pfn_Get_Native_System_Info
=
1126 (GetNativeSystemInfo_Proc
)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1127 "GetNativeSystemInfo");
1129 if (s_pfn_Get_Native_System_Info
!= NULL
)
1130 s_pfn_Get_Native_System_Info (lpSystemInfo
);
1133 lpSystemInfo
->dwNumberOfProcessors
= -1;
1137 get_system_times (LPFILETIME lpIdleTime
,
1138 LPFILETIME lpKernelTime
,
1139 LPFILETIME lpUserTime
)
1141 static GetSystemTimes_Proc s_pfn_Get_System_times
= NULL
;
1142 if (is_windows_9x () == TRUE
)
1146 if (g_b_init_get_system_times
== 0)
1148 g_b_init_get_system_times
= 1;
1149 s_pfn_Get_System_times
=
1150 (GetSystemTimes_Proc
)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1153 if (s_pfn_Get_System_times
== NULL
)
1155 return (s_pfn_Get_System_times (lpIdleTime
, lpKernelTime
, lpUserTime
));
1158 static BOOLEAN WINAPI
1159 create_symbolic_link (LPCSTR lpSymlinkFilename
,
1160 LPCSTR lpTargetFileName
,
1163 static CreateSymbolicLinkW_Proc s_pfn_Create_Symbolic_LinkW
= NULL
;
1164 static CreateSymbolicLinkA_Proc s_pfn_Create_Symbolic_LinkA
= NULL
;
1167 if (is_windows_9x () == TRUE
)
1172 if (w32_unicode_filenames
)
1174 wchar_t symfn_w
[MAX_PATH
], tgtfn_w
[MAX_PATH
];
1176 if (g_b_init_create_symbolic_link_w
== 0)
1178 g_b_init_create_symbolic_link_w
= 1;
1179 s_pfn_Create_Symbolic_LinkW
=
1180 (CreateSymbolicLinkW_Proc
)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1181 "CreateSymbolicLinkW");
1183 if (s_pfn_Create_Symbolic_LinkW
== NULL
)
1189 filename_to_utf16 (lpSymlinkFilename
, symfn_w
);
1190 filename_to_utf16 (lpTargetFileName
, tgtfn_w
);
1191 retval
= s_pfn_Create_Symbolic_LinkW (symfn_w
, tgtfn_w
, dwFlags
);
1192 /* If we were denied creation of the symlink, try again after
1193 enabling the SeCreateSymbolicLinkPrivilege for our process. */
1196 TOKEN_PRIVILEGES priv_current
;
1198 if (enable_privilege (SE_CREATE_SYMBOLIC_LINK_NAME
, TRUE
,
1201 retval
= s_pfn_Create_Symbolic_LinkW (symfn_w
, tgtfn_w
, dwFlags
);
1202 restore_privilege (&priv_current
);
1209 char symfn_a
[MAX_PATH
], tgtfn_a
[MAX_PATH
];
1211 if (g_b_init_create_symbolic_link_a
== 0)
1213 g_b_init_create_symbolic_link_a
= 1;
1214 s_pfn_Create_Symbolic_LinkA
=
1215 (CreateSymbolicLinkA_Proc
)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1216 "CreateSymbolicLinkA");
1218 if (s_pfn_Create_Symbolic_LinkA
== NULL
)
1224 filename_to_ansi (lpSymlinkFilename
, symfn_a
);
1225 filename_to_ansi (lpTargetFileName
, tgtfn_a
);
1226 retval
= s_pfn_Create_Symbolic_LinkA (symfn_a
, tgtfn_a
, dwFlags
);
1227 /* If we were denied creation of the symlink, try again after
1228 enabling the SeCreateSymbolicLinkPrivilege for our process. */
1231 TOKEN_PRIVILEGES priv_current
;
1233 if (enable_privilege (SE_CREATE_SYMBOLIC_LINK_NAME
, TRUE
,
1236 retval
= s_pfn_Create_Symbolic_LinkA (symfn_a
, tgtfn_a
, dwFlags
);
1237 restore_privilege (&priv_current
);
1246 is_valid_security_descriptor (PSECURITY_DESCRIPTOR pSecurityDescriptor
)
1248 static IsValidSecurityDescriptor_Proc s_pfn_Is_Valid_Security_Descriptor_Proc
= NULL
;
1250 if (is_windows_9x () == TRUE
)
1256 if (g_b_init_is_valid_security_descriptor
== 0)
1258 g_b_init_is_valid_security_descriptor
= 1;
1259 s_pfn_Is_Valid_Security_Descriptor_Proc
=
1260 (IsValidSecurityDescriptor_Proc
)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1261 "IsValidSecurityDescriptor");
1263 if (s_pfn_Is_Valid_Security_Descriptor_Proc
== NULL
)
1269 return s_pfn_Is_Valid_Security_Descriptor_Proc (pSecurityDescriptor
);
1273 convert_sd_to_sddl (PSECURITY_DESCRIPTOR SecurityDescriptor
,
1274 DWORD RequestedStringSDRevision
,
1275 SECURITY_INFORMATION SecurityInformation
,
1276 LPTSTR
*StringSecurityDescriptor
,
1277 PULONG StringSecurityDescriptorLen
)
1279 static ConvertSecurityDescriptorToStringSecurityDescriptor_Proc s_pfn_Convert_SD_To_SDDL
= NULL
;
1282 if (is_windows_9x () == TRUE
)
1288 if (g_b_init_convert_sd_to_sddl
== 0)
1290 g_b_init_convert_sd_to_sddl
= 1;
1292 s_pfn_Convert_SD_To_SDDL
=
1293 (ConvertSecurityDescriptorToStringSecurityDescriptor_Proc
)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1294 "ConvertSecurityDescriptorToStringSecurityDescriptorW");
1296 s_pfn_Convert_SD_To_SDDL
=
1297 (ConvertSecurityDescriptorToStringSecurityDescriptor_Proc
)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1298 "ConvertSecurityDescriptorToStringSecurityDescriptorA");
1301 if (s_pfn_Convert_SD_To_SDDL
== NULL
)
1307 retval
= s_pfn_Convert_SD_To_SDDL (SecurityDescriptor
,
1308 RequestedStringSDRevision
,
1309 SecurityInformation
,
1310 StringSecurityDescriptor
,
1311 StringSecurityDescriptorLen
);
1317 convert_sddl_to_sd (LPCTSTR StringSecurityDescriptor
,
1318 DWORD StringSDRevision
,
1319 PSECURITY_DESCRIPTOR
*SecurityDescriptor
,
1320 PULONG SecurityDescriptorSize
)
1322 static ConvertStringSecurityDescriptorToSecurityDescriptor_Proc s_pfn_Convert_SDDL_To_SD
= NULL
;
1325 if (is_windows_9x () == TRUE
)
1331 if (g_b_init_convert_sddl_to_sd
== 0)
1333 g_b_init_convert_sddl_to_sd
= 1;
1335 s_pfn_Convert_SDDL_To_SD
=
1336 (ConvertStringSecurityDescriptorToSecurityDescriptor_Proc
)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1337 "ConvertStringSecurityDescriptorToSecurityDescriptorW");
1339 s_pfn_Convert_SDDL_To_SD
=
1340 (ConvertStringSecurityDescriptorToSecurityDescriptor_Proc
)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1341 "ConvertStringSecurityDescriptorToSecurityDescriptorA");
1344 if (s_pfn_Convert_SDDL_To_SD
== NULL
)
1350 retval
= s_pfn_Convert_SDDL_To_SD (StringSecurityDescriptor
,
1353 SecurityDescriptorSize
);
1359 get_adapters_info (PIP_ADAPTER_INFO pAdapterInfo
, PULONG pOutBufLen
)
1361 static GetAdaptersInfo_Proc s_pfn_Get_Adapters_Info
= NULL
;
1362 HMODULE hm_iphlpapi
= NULL
;
1364 if (is_windows_9x () == TRUE
)
1365 return ERROR_NOT_SUPPORTED
;
1367 if (g_b_init_get_adapters_info
== 0)
1369 g_b_init_get_adapters_info
= 1;
1370 hm_iphlpapi
= LoadLibrary ("Iphlpapi.dll");
1372 s_pfn_Get_Adapters_Info
= (GetAdaptersInfo_Proc
)
1373 GetProcAddress (hm_iphlpapi
, "GetAdaptersInfo");
1375 if (s_pfn_Get_Adapters_Info
== NULL
)
1376 return ERROR_NOT_SUPPORTED
;
1377 return s_pfn_Get_Adapters_Info (pAdapterInfo
, pOutBufLen
);
1382 /* Return 1 if P is a valid pointer to an object of size SIZE. Return
1383 0 if P is NOT a valid pointer. Return -1 if we cannot validate P.
1385 This is called from alloc.c:valid_pointer_p. */
1387 w32_valid_pointer_p (void *p
, int size
)
1390 HANDLE h
= OpenProcess (PROCESS_VM_READ
, FALSE
, GetCurrentProcessId ());
1394 unsigned char *buf
= alloca (size
);
1395 int retval
= ReadProcessMemory (h
, p
, buf
, size
, &done
);
1406 /* Here's an overview of how the Windows build supports file names
1407 that cannot be encoded by the current system codepage.
1409 From the POV of Lisp and layers of C code above the functions here,
1410 Emacs on Windows pretends that its file names are encoded in UTF-8;
1411 see encode_file and decode_file on coding.c. Any file name that is
1412 passed as a unibyte string to C functions defined here is assumed
1413 to be in UTF-8 encoding. Any file name returned by functions
1414 defined here must be in UTF-8 encoding, with only a few exceptions
1415 reserved for a couple of special cases. (Be sure to use
1416 MAX_UTF8_PATH for char arrays that store UTF-8 encoded file names,
1417 as they can be much longer than MAX_PATH!)
1419 The UTF-8 encoded file names cannot be passed to system APIs, as
1420 Windows does not support that. Therefore, they are converted
1421 either to UTF-16 or to the ANSI codepage, depending on the value of
1422 w32-unicode-filenames, before calling any system APIs or CRT library
1423 functions. The default value of that variable is determined by the
1424 OS on which Emacs runs: nil on Windows 9X and t otherwise, but the
1425 user can change that default (although I don't see why would she
1428 The 4 functions defined below, filename_to_utf16, filename_to_ansi,
1429 filename_from_utf16, and filename_from_ansi, are the workhorses of
1430 these conversions. They rely on Windows native APIs
1431 MultiByteToWideChar and WideCharToMultiByte; we cannot use
1432 functions from coding.c here, because they allocate memory, which
1433 is a bad idea on the level of libc, which is what the functions
1434 here emulate. (If you worry about performance due to constant
1435 conversion back and forth from UTF-8 to UTF-16, then don't: first,
1436 it was measured to take only a few microseconds on a not-so-fast
1437 machine, and second, that's exactly what the ANSI APIs we used
1438 before did anyway, because they are just thin wrappers around the
1441 The variables file-name-coding-system and default-file-name-coding-system
1442 still exist, but are actually used only when a file name needs to
1443 be converted to the ANSI codepage. This happens all the time when
1444 w32-unicode-filenames is nil, but can also happen from time to time
1445 when it is t. Otherwise, these variables have no effect on file-name
1446 encoding when w32-unicode-filenames is t; this is similar to
1447 selection-coding-system.
1449 This arrangement works very well, but it has a few gotchas and
1452 . Lisp code that encodes or decodes file names manually should
1453 normally use 'utf-8' as the coding-system on Windows,
1454 disregarding file-name-coding-system. This is a somewhat
1455 unpleasant consequence, but it cannot be avoided. Fortunately,
1456 very few Lisp packages need to do that.
1458 More generally, passing to library functions (e.g., fopen or
1459 opendir) file names already encoded in the ANSI codepage is
1460 explicitly *verboten*, as all those functions, as shadowed and
1461 emulated here, assume they will receive UTF-8 encoded file names.
1463 For the same reasons, no CRT function or Win32 API can be called
1464 directly in Emacs sources, without either converting the file
1465 names from UTF-8 to UTF-16 or ANSI codepage, or going through
1466 some shadowing function defined here.
1468 . Environment variables stored in Vprocess_environment are encoded
1469 in the ANSI codepage, so if getenv/egetenv is used for a variable
1470 whose value is a file name or a list of directories, it needs to
1471 be converted to UTF-8, before it is used as argument to functions
1472 or decoded into a Lisp string.
1474 . File names passed to external libraries, like the image libraries
1475 and GnuTLS, need special handling. These libraries generally
1476 don't support UTF-16 or UTF-8 file names, so they must get file
1477 names encoded in the ANSI codepage. To facilitate using these
1478 libraries with file names that are not encodable in the ANSI
1479 codepage, use the function ansi_encode_filename, which will try
1480 to use the short 8+3 alias of a file name if that file name is
1481 not encodable in the ANSI codepage. See image.c and gnutls.c for
1482 examples of how this should be done.
1484 . Running subprocesses in non-ASCII directories and with non-ASCII
1485 file arguments is limited to the current codepage (even though
1486 Emacs is perfectly capable of finding an executable program file
1487 in a directory whose name cannot be encoded in the current
1488 codepage). This is because the command-line arguments are
1489 encoded _before_ they get to the w32-specific level, and the
1490 encoding is not known in advance (it doesn't have to be the
1491 current ANSI codepage), so w32proc.c functions cannot re-encode
1492 them in UTF-16. This should be fixed, but will also require
1493 changes in cmdproxy. The current limitation is not terribly bad
1494 anyway, since very few, if any, Windows console programs that are
1495 likely to be invoked by Emacs support UTF-16 encoded command
1498 . For similar reasons, server.el and emacsclient are also limited
1499 to the current ANSI codepage for now.
1501 . Emacs itself can only handle command-line arguments encoded in
1502 the current codepage.
1504 . Turning on w32-unicode-filename on Windows 9X (if it at all
1505 works) requires UNICOWS.DLL, which is thus a requirement even in
1506 non-GUI sessions, something the we previously avoided. */
1510 /* Converting file names from UTF-8 to either UTF-16 or the ANSI
1511 codepage defined by file-name-coding-system. */
1513 /* Current codepage for encoding file names. */
1514 static int file_name_codepage
;
1516 /* Produce a Windows ANSI codepage suitable for encoding file names.
1517 Return the information about that codepage in CP_INFO. */
1519 codepage_for_filenames (CPINFO
*cp_info
)
1521 /* A simple cache to avoid calling GetCPInfo every time we need to
1522 encode/decode a file name. The file-name encoding is not
1523 supposed to be changed too frequently, if ever. */
1524 static Lisp_Object last_file_name_encoding
;
1526 Lisp_Object current_encoding
;
1528 current_encoding
= Vfile_name_coding_system
;
1529 if (NILP (current_encoding
))
1530 current_encoding
= Vdefault_file_name_coding_system
;
1532 if (!EQ (last_file_name_encoding
, current_encoding
))
1534 /* Default to the current ANSI codepage. */
1535 file_name_codepage
= w32_ansi_code_page
;
1537 if (NILP (current_encoding
))
1539 char *cpname
= SSDATA (SYMBOL_NAME (current_encoding
));
1540 char *cp
= NULL
, *end
;
1543 if (strncmp (cpname
, "cp", 2) == 0)
1545 else if (strncmp (cpname
, "windows-", 8) == 0)
1551 cpnum
= strtol (cp
, &end
, 10);
1552 if (cpnum
&& *end
== '\0' && end
- cp
>= 2)
1553 file_name_codepage
= cpnum
;
1557 if (!file_name_codepage
)
1558 file_name_codepage
= CP_ACP
; /* CP_ACP = 0, but let's not assume that */
1560 if (!GetCPInfo (file_name_codepage
, &cp
))
1562 file_name_codepage
= CP_ACP
;
1563 if (!GetCPInfo (file_name_codepage
, &cp
))
1570 return file_name_codepage
;
1574 filename_to_utf16 (const char *fn_in
, wchar_t *fn_out
)
1576 int result
= pMultiByteToWideChar (CP_UTF8
, multiByteToWideCharFlags
, fn_in
,
1577 -1, fn_out
, MAX_PATH
);
1581 DWORD err
= GetLastError ();
1585 case ERROR_INVALID_FLAGS
:
1586 case ERROR_INVALID_PARAMETER
:
1589 case ERROR_INSUFFICIENT_BUFFER
:
1590 case ERROR_NO_UNICODE_TRANSLATION
:
1601 filename_from_utf16 (const wchar_t *fn_in
, char *fn_out
)
1603 int result
= pWideCharToMultiByte (CP_UTF8
, 0, fn_in
, -1,
1604 fn_out
, MAX_UTF8_PATH
, NULL
, NULL
);
1608 DWORD err
= GetLastError ();
1612 case ERROR_INVALID_FLAGS
:
1613 case ERROR_INVALID_PARAMETER
:
1616 case ERROR_INSUFFICIENT_BUFFER
:
1617 case ERROR_NO_UNICODE_TRANSLATION
:
1628 filename_to_ansi (const char *fn_in
, char *fn_out
)
1630 wchar_t fn_utf16
[MAX_PATH
];
1632 if (filename_to_utf16 (fn_in
, fn_utf16
) == 0)
1635 int codepage
= codepage_for_filenames (NULL
);
1637 result
= pWideCharToMultiByte (codepage
, 0, fn_utf16
, -1,
1638 fn_out
, MAX_PATH
, NULL
, NULL
);
1641 DWORD err
= GetLastError ();
1645 case ERROR_INVALID_FLAGS
:
1646 case ERROR_INVALID_PARAMETER
:
1649 case ERROR_INSUFFICIENT_BUFFER
:
1650 case ERROR_NO_UNICODE_TRANSLATION
:
1663 filename_from_ansi (const char *fn_in
, char *fn_out
)
1665 wchar_t fn_utf16
[MAX_PATH
];
1666 int codepage
= codepage_for_filenames (NULL
);
1667 int result
= pMultiByteToWideChar (codepage
, multiByteToWideCharFlags
, fn_in
,
1668 -1, fn_utf16
, MAX_PATH
);
1672 DWORD err
= GetLastError ();
1676 case ERROR_INVALID_FLAGS
:
1677 case ERROR_INVALID_PARAMETER
:
1680 case ERROR_INSUFFICIENT_BUFFER
:
1681 case ERROR_NO_UNICODE_TRANSLATION
:
1688 return filename_from_utf16 (fn_utf16
, fn_out
);
1693 /* The directory where we started, in UTF-8. */
1694 static char startup_dir
[MAX_UTF8_PATH
];
1696 /* Get the current working directory. */
1698 getcwd (char *dir
, int dirsize
)
1705 if (dirsize
<= strlen (startup_dir
))
1711 if (GetCurrentDirectory (MAXPATHLEN
, dir
) > 0)
1715 /* Emacs doesn't actually change directory itself, it stays in the
1716 same directory where it was started. */
1717 strcpy (dir
, startup_dir
);
1722 /* Emulate getloadavg. */
1724 struct load_sample
{
1731 /* Number of processors on this machine. */
1732 static unsigned num_of_processors
;
1734 /* We maintain 1-sec samples for the last 16 minutes in a circular buffer. */
1735 static struct load_sample samples
[16*60];
1736 static int first_idx
= -1, last_idx
= -1;
1737 static int max_idx
= ARRAYELTS (samples
);
1742 int next_idx
= from
+ 1;
1744 if (next_idx
>= max_idx
)
1753 int prev_idx
= from
- 1;
1756 prev_idx
= max_idx
- 1;
1762 sample_system_load (ULONGLONG
*idle
, ULONGLONG
*kernel
, ULONGLONG
*user
)
1764 SYSTEM_INFO sysinfo
;
1765 FILETIME ft_idle
, ft_user
, ft_kernel
;
1767 /* Initialize the number of processors on this machine. */
1768 if (num_of_processors
<= 0)
1770 get_native_system_info (&sysinfo
);
1771 num_of_processors
= sysinfo
.dwNumberOfProcessors
;
1772 if (num_of_processors
<= 0)
1774 GetSystemInfo (&sysinfo
);
1775 num_of_processors
= sysinfo
.dwNumberOfProcessors
;
1777 if (num_of_processors
<= 0)
1778 num_of_processors
= 1;
1781 /* TODO: Take into account threads that are ready to run, by
1782 sampling the "\System\Processor Queue Length" performance
1783 counter. The code below accounts only for threads that are
1784 actually running. */
1786 if (get_system_times (&ft_idle
, &ft_kernel
, &ft_user
))
1788 ULARGE_INTEGER uidle
, ukernel
, uuser
;
1790 memcpy (&uidle
, &ft_idle
, sizeof (ft_idle
));
1791 memcpy (&ukernel
, &ft_kernel
, sizeof (ft_kernel
));
1792 memcpy (&uuser
, &ft_user
, sizeof (ft_user
));
1793 *idle
= uidle
.QuadPart
;
1794 *kernel
= ukernel
.QuadPart
;
1795 *user
= uuser
.QuadPart
;
1805 /* Produce the load average for a given time interval, using the
1806 samples in the samples[] array. WHICH can be 0, 1, or 2, meaning
1807 1-minute, 5-minute, or 15-minute average, respectively. */
1811 double retval
= -1.0;
1814 double span
= (which
== 0 ? 1.0 : (which
== 1 ? 5.0 : 15.0)) * 60;
1815 time_t now
= samples
[last_idx
].sample_time
;
1817 if (first_idx
!= last_idx
)
1819 for (idx
= buf_prev (last_idx
); ; idx
= buf_prev (idx
))
1821 tdiff
= difftime (now
, samples
[idx
].sample_time
);
1822 if (tdiff
>= span
- 2*DBL_EPSILON
*now
)
1825 samples
[last_idx
].kernel
+ samples
[last_idx
].user
1826 - (samples
[idx
].kernel
+ samples
[idx
].user
);
1827 long double idl
= samples
[last_idx
].idle
- samples
[idx
].idle
;
1829 retval
= (1.0 - idl
/ sys
) * num_of_processors
;
1832 if (idx
== first_idx
)
1841 getloadavg (double loadavg
[], int nelem
)
1844 ULONGLONG idle
, kernel
, user
;
1845 time_t now
= time (NULL
);
1847 /* If system time jumped back for some reason, delete all samples
1848 whose time is later than the current wall-clock time. This
1849 prevents load average figures from becoming frozen for prolonged
1850 periods of time, when system time is reset backwards. */
1853 while (difftime (now
, samples
[last_idx
].sample_time
) < -1.0)
1855 if (last_idx
== first_idx
)
1857 first_idx
= last_idx
= -1;
1860 last_idx
= buf_prev (last_idx
);
1864 /* Store another sample. We ignore samples that are less than 1 sec
1867 || (difftime (now
, samples
[last_idx
].sample_time
)
1868 >= 1.0 - 2*DBL_EPSILON
*now
))
1870 sample_system_load (&idle
, &kernel
, &user
);
1871 last_idx
= buf_next (last_idx
);
1872 samples
[last_idx
].sample_time
= now
;
1873 samples
[last_idx
].idle
= idle
;
1874 samples
[last_idx
].kernel
= kernel
;
1875 samples
[last_idx
].user
= user
;
1876 /* If the buffer has more that 15 min worth of samples, discard
1878 if (first_idx
== -1)
1879 first_idx
= last_idx
;
1880 while (first_idx
!= last_idx
1881 && (difftime (now
, samples
[first_idx
].sample_time
)
1882 >= 15.0*60 + 2*DBL_EPSILON
*now
))
1883 first_idx
= buf_next (first_idx
);
1886 for (elem
= 0; elem
< nelem
; elem
++)
1888 double avg
= getavg (elem
);
1892 loadavg
[elem
] = avg
;
1898 /* Emulate getpwuid, getpwnam and others. */
1900 #define PASSWD_FIELD_SIZE 256
1902 static char dflt_passwd_name
[PASSWD_FIELD_SIZE
];
1903 static char dflt_passwd_passwd
[PASSWD_FIELD_SIZE
];
1904 static char dflt_passwd_gecos
[PASSWD_FIELD_SIZE
];
1905 static char dflt_passwd_dir
[MAX_UTF8_PATH
];
1906 static char dflt_passwd_shell
[MAX_UTF8_PATH
];
1908 static struct passwd dflt_passwd
=
1920 static char dflt_group_name
[GNLEN
+1];
1922 static struct group dflt_group
=
1924 /* When group information is not available, we return this as the
1925 group for all files. */
1933 return dflt_passwd
.pw_uid
;
1939 /* I could imagine arguing for checking to see whether the user is
1940 in the Administrators group and returning a UID of 0 for that
1941 case, but I don't know how wise that would be in the long run. */
1948 return dflt_passwd
.pw_gid
;
1958 getpwuid (unsigned uid
)
1960 if (uid
== dflt_passwd
.pw_uid
)
1961 return &dflt_passwd
;
1966 getgrgid (gid_t gid
)
1972 getpwnam (char *name
)
1976 pw
= getpwuid (getuid ());
1980 if (xstrcasecmp (name
, pw
->pw_name
))
1987 init_user_info (void)
1989 /* Find the user's real name by opening the process token and
1990 looking up the name associated with the user-sid in that token.
1992 Use the relative portion of the identifier authority value from
1993 the user-sid as the user id value (same for group id using the
1994 primary group sid from the process token). */
1996 char uname
[UNLEN
+1], gname
[GNLEN
+1], domain
[1025];
1997 DWORD ulength
= sizeof (uname
), dlength
= sizeof (domain
), needed
;
1998 DWORD glength
= sizeof (gname
);
1999 HANDLE token
= NULL
;
2000 SID_NAME_USE user_type
;
2001 unsigned char *buf
= NULL
;
2003 TOKEN_USER user_token
;
2004 TOKEN_PRIMARY_GROUP group_token
;
2007 result
= open_process_token (GetCurrentProcess (), TOKEN_QUERY
, &token
);
2010 result
= get_token_information (token
, TokenUser
, NULL
, 0, &blen
);
2011 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
2013 buf
= xmalloc (blen
);
2014 result
= get_token_information (token
, TokenUser
,
2015 (LPVOID
)buf
, blen
, &needed
);
2018 memcpy (&user_token
, buf
, sizeof (user_token
));
2019 result
= lookup_account_sid (NULL
, user_token
.User
.Sid
,
2021 domain
, &dlength
, &user_type
);
2029 strcpy (dflt_passwd
.pw_name
, uname
);
2030 /* Determine a reasonable uid value. */
2031 if (xstrcasecmp ("administrator", uname
) == 0)
2033 dflt_passwd
.pw_uid
= 500; /* well-known Administrator uid */
2034 dflt_passwd
.pw_gid
= 513; /* well-known None gid */
2038 /* Use the last sub-authority value of the RID, the relative
2039 portion of the SID, as user/group ID. */
2040 dflt_passwd
.pw_uid
= get_rid (user_token
.User
.Sid
);
2042 /* Get group id and name. */
2043 result
= get_token_information (token
, TokenPrimaryGroup
,
2044 (LPVOID
)buf
, blen
, &needed
);
2045 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
2047 buf
= xrealloc (buf
, blen
= needed
);
2048 result
= get_token_information (token
, TokenPrimaryGroup
,
2049 (LPVOID
)buf
, blen
, &needed
);
2053 memcpy (&group_token
, buf
, sizeof (group_token
));
2054 dflt_passwd
.pw_gid
= get_rid (group_token
.PrimaryGroup
);
2055 dlength
= sizeof (domain
);
2056 /* If we can get at the real Primary Group name, use that.
2057 Otherwise, the default group name was already set to
2058 "None" in globals_of_w32. */
2059 if (lookup_account_sid (NULL
, group_token
.PrimaryGroup
,
2060 gname
, &glength
, NULL
, &dlength
,
2062 strcpy (dflt_group_name
, gname
);
2065 dflt_passwd
.pw_gid
= dflt_passwd
.pw_uid
;
2068 /* If security calls are not supported (presumably because we
2069 are running under Windows 9X), fallback to this: */
2070 else if (GetUserName (uname
, &ulength
))
2072 strcpy (dflt_passwd
.pw_name
, uname
);
2073 if (xstrcasecmp ("administrator", uname
) == 0)
2074 dflt_passwd
.pw_uid
= 0;
2076 dflt_passwd
.pw_uid
= 123;
2077 dflt_passwd
.pw_gid
= dflt_passwd
.pw_uid
;
2081 strcpy (dflt_passwd
.pw_name
, "unknown");
2082 dflt_passwd
.pw_uid
= 123;
2083 dflt_passwd
.pw_gid
= 123;
2085 dflt_group
.gr_gid
= dflt_passwd
.pw_gid
;
2087 /* Set dir and shell from environment variables. */
2088 if (w32_unicode_filenames
)
2090 wchar_t *home
= _wgetenv (L
"HOME");
2091 wchar_t *shell
= _wgetenv (L
"SHELL");
2093 /* Ensure HOME and SHELL are defined. */
2098 filename_from_utf16 (home
, dflt_passwd
.pw_dir
);
2099 filename_from_utf16 (shell
, dflt_passwd
.pw_shell
);
2103 char *home
= getenv ("HOME");
2104 char *shell
= getenv ("SHELL");
2110 filename_from_ansi (home
, dflt_passwd
.pw_dir
);
2111 filename_from_ansi (shell
, dflt_passwd
.pw_shell
);
2116 CloseHandle (token
);
2119 static HCRYPTPROV w32_crypto_hprov
;
2121 w32_init_crypt_random (void)
2123 if (!CryptAcquireContext (&w32_crypto_hprov
, NULL
, NULL
, PROV_RSA_FULL
,
2124 CRYPT_VERIFYCONTEXT
| CRYPT_SILENT
))
2126 DebPrint (("CryptAcquireContext failed with error %x\n",
2128 w32_crypto_hprov
= 0;
2135 w32_init_random (void *buf
, ptrdiff_t buflen
)
2137 if (!w32_crypto_hprov
)
2138 w32_init_crypt_random ();
2139 if (w32_crypto_hprov
)
2141 if (CryptGenRandom (w32_crypto_hprov
, buflen
, (BYTE
*)buf
))
2150 /* rand () on NT gives us 15 random bits...hack together 30 bits. */
2151 return ((rand () << 15) | rand ());
2160 /* Return the maximum length in bytes of a multibyte character
2161 sequence encoded in the current ANSI codepage. This is required to
2162 correctly walk the encoded file names one character at a time. */
2164 max_filename_mbslen (void)
2168 codepage_for_filenames (&cp_info
);
2169 return cp_info
.MaxCharSize
;
2172 /* Normalize filename by converting in-place all of its path
2173 separators to the separator specified by PATH_SEP. */
2176 normalize_filename (register char *fp
, char path_sep
)
2180 /* Always lower-case drive letters a-z, even if the filesystem
2181 preserves case in filenames.
2182 This is so filenames can be compared by string comparison
2183 functions that are case-sensitive. Even case-preserving filesystems
2184 do not distinguish case in drive letters. */
2187 if (*p2
== ':' && *fp
>= 'A' && *fp
<= 'Z')
2195 if ((*fp
== '/' || *fp
== '\\') && *fp
!= path_sep
)
2201 /* Destructively turn backslashes into slashes. */
2203 dostounix_filename (register char *p
)
2205 normalize_filename (p
, '/');
2208 /* Destructively turn slashes into backslashes. */
2210 unixtodos_filename (register char *p
)
2212 normalize_filename (p
, '\\');
2215 /* Remove all CR's that are followed by a LF.
2216 (From msdos.c...probably should figure out a way to share it,
2217 although this code isn't going to ever change.) */
2219 crlf_to_lf (register int n
, register char *buf
)
2221 unsigned char *np
= (unsigned char *)buf
;
2222 unsigned char *startp
= np
;
2223 char *endp
= buf
+ n
;
2227 while (buf
< endp
- 1)
2231 if (*(++buf
) != 0x0a)
2242 /* Parse the root part of file name, if present. Return length and
2243 optionally store pointer to char after root. */
2245 parse_root (const char * name
, const char ** pPath
)
2247 const char * start
= name
;
2252 /* find the root name of the volume if given */
2253 if (isalpha (name
[0]) && name
[1] == ':')
2255 /* skip past drive specifier */
2257 if (IS_DIRECTORY_SEP (name
[0]))
2260 else if (IS_DIRECTORY_SEP (name
[0]) && IS_DIRECTORY_SEP (name
[1]))
2267 if (IS_DIRECTORY_SEP (*name
) && --slashes
== 0)
2272 if (IS_DIRECTORY_SEP (name
[0]))
2279 return name
- start
;
2282 /* Get long base name for name; name is assumed to be absolute. */
2284 get_long_basename (char * name
, char * buf
, int size
)
2286 HANDLE dir_handle
= INVALID_HANDLE_VALUE
;
2287 char fname_utf8
[MAX_UTF8_PATH
];
2291 /* Must be valid filename, no wild cards or other invalid characters. */
2292 if (strpbrk (name
, "*?|<>\""))
2295 if (w32_unicode_filenames
)
2297 wchar_t fname_utf16
[MAX_PATH
];
2298 WIN32_FIND_DATAW find_data_wide
;
2300 filename_to_utf16 (name
, fname_utf16
);
2301 dir_handle
= FindFirstFileW (fname_utf16
, &find_data_wide
);
2302 if (dir_handle
!= INVALID_HANDLE_VALUE
)
2303 cstatus
= filename_from_utf16 (find_data_wide
.cFileName
, fname_utf8
);
2307 char fname_ansi
[MAX_PATH
];
2308 WIN32_FIND_DATAA find_data_ansi
;
2310 filename_to_ansi (name
, fname_ansi
);
2311 /* If the ANSI name includes ? characters, it is not encodable
2312 in the ANSI codepage. In that case, we deliver the question
2313 marks to the caller; calling FindFirstFileA in this case
2314 could return some unrelated file name in the same
2316 if (_mbspbrk (fname_ansi
, "?"))
2318 /* Find the basename of fname_ansi. */
2319 char *p
= strrchr (fname_ansi
, '\\');
2325 cstatus
= filename_from_ansi (p
, fname_utf8
);
2329 dir_handle
= FindFirstFileA (fname_ansi
, &find_data_ansi
);
2330 if (dir_handle
!= INVALID_HANDLE_VALUE
)
2331 cstatus
= filename_from_ansi (find_data_ansi
.cFileName
, fname_utf8
);
2335 if (cstatus
== 0 && (len
= strlen (fname_utf8
)) < size
)
2336 memcpy (buf
, fname_utf8
, len
+ 1);
2340 if (dir_handle
!= INVALID_HANDLE_VALUE
)
2341 FindClose (dir_handle
);
2346 /* Get long name for file, if possible (assumed to be absolute). */
2348 w32_get_long_filename (const char * name
, char * buf
, int size
)
2353 char full
[ MAX_UTF8_PATH
];
2356 len
= strlen (name
);
2357 if (len
>= MAX_UTF8_PATH
)
2360 /* Use local copy for destructive modification. */
2361 memcpy (full
, name
, len
+1);
2362 unixtodos_filename (full
);
2364 /* Copy root part verbatim. */
2365 len
= parse_root (full
, (const char **)&p
);
2366 memcpy (o
, full
, len
);
2371 while (p
!= NULL
&& *p
)
2374 p
= strchr (q
, '\\');
2376 len
= get_long_basename (full
, o
, size
);
2399 w32_get_short_filename (const char * name
, char * buf
, int size
)
2401 if (w32_unicode_filenames
)
2403 wchar_t name_utf16
[MAX_PATH
], short_name
[MAX_PATH
];
2404 unsigned int retval
;
2406 filename_to_utf16 (name
, name_utf16
);
2407 retval
= GetShortPathNameW (name_utf16
, short_name
, size
);
2408 if (retval
&& retval
< size
)
2409 filename_from_utf16 (short_name
, buf
);
2414 char name_ansi
[MAX_PATH
];
2416 filename_to_ansi (name
, name_ansi
);
2417 return GetShortPathNameA (name_ansi
, buf
, size
);
2421 /* Re-encode FILENAME, a UTF-8 encoded unibyte string, using the
2422 MS-Windows ANSI codepage. If FILENAME includes characters not
2423 supported by the ANSI codepage, return the 8+3 alias of FILENAME,
2424 if it exists. This is needed because the w32 build wants to
2425 support file names outside of the system locale, but image
2426 libraries typically don't support wide (a.k.a. "Unicode") APIs
2427 required for that. */
2430 ansi_encode_filename (Lisp_Object filename
)
2432 Lisp_Object encoded_filename
;
2433 char fname
[MAX_PATH
];
2435 filename_to_ansi (SSDATA (filename
), fname
);
2436 if (_mbspbrk (fname
, "?"))
2438 char shortname
[MAX_PATH
];
2440 if (w32_get_short_filename (SSDATA (filename
), shortname
, MAX_PATH
))
2442 dostounix_filename (shortname
);
2443 encoded_filename
= build_string (shortname
);
2446 encoded_filename
= build_unibyte_string (fname
);
2449 encoded_filename
= build_unibyte_string (fname
);
2450 return encoded_filename
;
2454 is_unc_volume (const char *filename
)
2456 const char *ptr
= filename
;
2458 if (!IS_DIRECTORY_SEP (ptr
[0]) || !IS_DIRECTORY_SEP (ptr
[1]) || !ptr
[2])
2461 if (strpbrk (ptr
+ 2, "*?|<>\"\\/"))
2467 /* Emulate the Posix unsetenv. */
2469 unsetenv (const char *name
)
2474 if (name
== NULL
|| *name
== '\0' || strchr (name
, '=') != NULL
)
2479 name_len
= strlen (name
);
2480 /* MS docs says an environment variable cannot be longer than 32K. */
2481 if (name_len
> 32767)
2486 /* It is safe to use 'alloca' with 32K size, since the stack is at
2487 least 2MB, and we set it to 8MB in the link command line. */
2488 var
= alloca (name_len
+ 2);
2489 strncpy (var
, name
, name_len
);
2490 var
[name_len
++] = '=';
2491 var
[name_len
] = '\0';
2492 return _putenv (var
);
2495 /* MS _putenv doesn't support removing a variable when the argument
2496 does not include the '=' character, so we fix that here. */
2498 sys_putenv (char *str
)
2500 const char *const name_end
= strchr (str
, '=');
2502 if (name_end
== NULL
)
2504 /* Remove the variable from the environment. */
2505 return unsetenv (str
);
2508 return _putenv (str
);
2511 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
2514 w32_get_resource (const char *key
, LPDWORD lpdwtype
)
2517 HKEY hrootkey
= NULL
;
2520 /* Check both the current user and the local machine to see if
2521 we have any resources. */
2523 if (RegOpenKeyEx (HKEY_CURRENT_USER
, REG_ROOT
, 0, KEY_READ
, &hrootkey
) == ERROR_SUCCESS
)
2527 if (RegQueryValueEx (hrootkey
, key
, NULL
, NULL
, NULL
, &cbData
) == ERROR_SUCCESS
2528 && (lpvalue
= xmalloc (cbData
)) != NULL
2529 && RegQueryValueEx (hrootkey
, key
, NULL
, lpdwtype
, lpvalue
, &cbData
) == ERROR_SUCCESS
)
2531 RegCloseKey (hrootkey
);
2537 RegCloseKey (hrootkey
);
2540 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE
, REG_ROOT
, 0, KEY_READ
, &hrootkey
) == ERROR_SUCCESS
)
2544 if (RegQueryValueEx (hrootkey
, key
, NULL
, NULL
, NULL
, &cbData
) == ERROR_SUCCESS
2545 && (lpvalue
= xmalloc (cbData
)) != NULL
2546 && RegQueryValueEx (hrootkey
, key
, NULL
, lpdwtype
, lpvalue
, &cbData
) == ERROR_SUCCESS
)
2548 RegCloseKey (hrootkey
);
2554 RegCloseKey (hrootkey
);
2560 /* The argv[] array holds ANSI-encoded strings, and so this function
2561 works with ANS_encoded strings. */
2563 init_environment (char ** argv
)
2565 static const char * const tempdirs
[] = {
2566 "$TMPDIR", "$TEMP", "$TMP", "c:/"
2571 const int imax
= ARRAYELTS (tempdirs
);
2573 /* Implementation note: This function explicitly works with ANSI
2574 file names, not with UTF-8 encoded file names. This is because
2575 this function pushes variables into the Emacs's environment, and
2576 the environment variables are always assumed to be in the
2577 locale-specific encoding. Do NOT call any functions that accept
2578 UTF-8 file names from this function! */
2580 /* Make sure they have a usable $TMPDIR. Many Emacs functions use
2581 temporary files and assume "/tmp" if $TMPDIR is unset, which
2582 will break on DOS/Windows. Refuse to work if we cannot find
2583 a directory, not even "c:/", usable for that purpose. */
2584 for (i
= 0; i
< imax
; i
++)
2586 const char *tmp
= tempdirs
[i
];
2589 tmp
= getenv (tmp
+ 1);
2590 /* Note that `access' can lie to us if the directory resides on a
2591 read-only filesystem, like CD-ROM or a write-protected floppy.
2592 The only way to be really sure is to actually create a file and
2593 see if it succeeds. But I think that's too much to ask. */
2595 /* MSVCRT's _access crashes with D_OK, so we use our replacement. */
2596 if (tmp
&& sys_access (tmp
, D_OK
) == 0)
2598 char * var
= alloca (strlen (tmp
) + 8);
2599 sprintf (var
, "TMPDIR=%s", tmp
);
2600 _putenv (strdup (var
));
2607 Fcons (build_string ("no usable temporary directories found!!"),
2609 "While setting TMPDIR: ");
2611 /* Check for environment variables and use registry settings if they
2612 don't exist. Fallback on default values where applicable. */
2617 char locale_name
[32];
2618 char default_home
[MAX_PATH
];
2621 static const struct env_entry
2624 const char * def_value
;
2627 /* If the default value is NULL, we will use the value from the
2628 outside environment or the Registry, but will not push the
2629 variable into the Emacs environment if it is defined neither
2630 in the Registry nor in the outside environment. */
2632 {"PRELOAD_WINSOCK", NULL
},
2633 {"emacs_dir", "C:/emacs"},
2634 {"EMACSLOADPATH", NULL
},
2635 {"SHELL", "cmdproxy.exe"}, /* perhaps it is somewhere on PATH */
2636 {"EMACSDATA", NULL
},
2637 {"EMACSPATH", NULL
},
2644 #define N_ENV_VARS ARRAYELTS (dflt_envvars)
2646 /* We need to copy dflt_envvars[] and work on the copy because we
2647 don't want the dumped Emacs to inherit the values of
2648 environment variables we saw during dumping (which could be on
2649 a different system). The defaults above must be left intact. */
2650 struct env_entry env_vars
[N_ENV_VARS
];
2652 for (i
= 0; i
< N_ENV_VARS
; i
++)
2653 env_vars
[i
] = dflt_envvars
[i
];
2655 /* For backwards compatibility, check if a .emacs file exists in C:/
2656 If not, then we can try to default to the appdata directory under the
2657 user's profile, which is more likely to be writable. */
2658 if (sys_access ("C:/.emacs", F_OK
) != 0)
2660 HRESULT profile_result
;
2661 /* Dynamically load ShGetFolderPath, as it won't exist on versions
2662 of Windows 95 and NT4 that have not been updated to include
2664 ShGetFolderPath_fn get_folder_path
;
2665 get_folder_path
= (ShGetFolderPath_fn
)
2666 GetProcAddress (GetModuleHandle ("shell32.dll"), "SHGetFolderPathA");
2668 if (get_folder_path
!= NULL
)
2670 profile_result
= get_folder_path (NULL
, CSIDL_APPDATA
, NULL
,
2673 /* If we can't get the appdata dir, revert to old behavior. */
2674 if (profile_result
== S_OK
)
2676 env_vars
[0].def_value
= default_home
;
2682 /* Get default locale info and use it for LANG. */
2683 if (GetLocaleInfo (LOCALE_USER_DEFAULT
,
2684 LOCALE_SABBREVLANGNAME
| LOCALE_USE_CP_ACP
,
2685 locale_name
, sizeof (locale_name
)))
2687 for (i
= 0; i
< N_ENV_VARS
; i
++)
2689 if (strcmp (env_vars
[i
].name
, "LANG") == 0)
2691 env_vars
[i
].def_value
= locale_name
;
2697 #define SET_ENV_BUF_SIZE (4 * MAX_PATH) /* to cover EMACSLOADPATH */
2699 /* Treat emacs_dir specially: set it unconditionally based on our
2703 char modname
[MAX_PATH
];
2705 if (!GetModuleFileNameA (NULL
, modname
, MAX_PATH
))
2707 if ((p
= _mbsrchr (modname
, '\\')) == NULL
)
2711 if ((p
= _mbsrchr (modname
, '\\'))
2712 /* From bin means installed Emacs, from src means uninstalled. */
2713 && (xstrcasecmp (p
, "\\bin") == 0 || xstrcasecmp (p
, "\\src") == 0))
2715 char buf
[SET_ENV_BUF_SIZE
];
2716 int within_build_tree
= xstrcasecmp (p
, "\\src") == 0;
2719 for (p
= modname
; *p
; p
= CharNext (p
))
2720 if (*p
== '\\') *p
= '/';
2722 _snprintf (buf
, sizeof (buf
)-1, "emacs_dir=%s", modname
);
2723 _putenv (strdup (buf
));
2724 /* If we are running from the Posix-like build tree, define
2725 SHELL to point to our own cmdproxy. The loop below will
2726 then disregard PATH_EXEC and the default value. */
2727 if (within_build_tree
)
2729 _snprintf (buf
, sizeof (buf
) - 1,
2730 "SHELL=%s/nt/cmdproxy.exe", modname
);
2731 _putenv (strdup (buf
));
2736 for (i
= 0; i
< N_ENV_VARS
; i
++)
2738 if (!getenv (env_vars
[i
].name
))
2741 char bufc
[SET_ENV_BUF_SIZE
];
2743 if ((lpval
= w32_get_resource (env_vars
[i
].name
, &dwType
)) == NULL
2744 /* Also ignore empty environment variables. */
2749 if (strcmp (env_vars
[i
].name
, "SHELL") == 0)
2751 /* Look for cmdproxy.exe in every directory in
2752 PATH_EXEC. FIXME: This does not find cmdproxy
2753 in nt/ when we run uninstalled. */
2754 char fname
[MAX_PATH
];
2755 const char *pstart
= PATH_EXEC
, *pend
;
2758 pend
= _mbschr (pstart
, ';');
2760 pend
= pstart
+ strlen (pstart
);
2761 /* Be defensive against series of ;;; characters. */
2764 strncpy (fname
, pstart
, pend
- pstart
);
2765 fname
[pend
- pstart
] = '/';
2766 strcpy (&fname
[pend
- pstart
+ 1], "cmdproxy.exe");
2767 ExpandEnvironmentStrings ((LPSTR
) fname
, bufc
,
2769 if (sys_access (bufc
, F_OK
) == 0)
2782 /* If not found in any directory, use the
2783 default as the last resort. */
2784 lpval
= (char *)env_vars
[i
].def_value
;
2785 dwType
= REG_EXPAND_SZ
;
2791 lpval
= (char *)env_vars
[i
].def_value
;
2792 dwType
= REG_EXPAND_SZ
;
2794 if (strcmp (env_vars
[i
].name
, "HOME") == 0 && !appdata
)
2795 Vdelayed_warnings_list
2796 = Fcons (listn (CONSTYPE_HEAP
, 2,
2797 intern ("initialization"),
2798 build_string ("Setting HOME to C:\\ by default is deprecated")),
2799 Vdelayed_warnings_list
);
2804 char buf1
[SET_ENV_BUF_SIZE
], buf2
[SET_ENV_BUF_SIZE
];
2806 if (dwType
== REG_EXPAND_SZ
)
2807 ExpandEnvironmentStrings ((LPSTR
) lpval
, buf1
, sizeof (buf1
));
2808 else if (dwType
== REG_SZ
)
2809 strcpy (buf1
, (char *)lpval
);
2810 if (dwType
== REG_EXPAND_SZ
|| dwType
== REG_SZ
)
2812 _snprintf (buf2
, sizeof (buf2
)-1, "%s=%s", env_vars
[i
].name
,
2814 _putenv (strdup (buf2
));
2824 /* Rebuild system configuration to reflect invoking system. */
2825 Vsystem_configuration
= build_string (EMACS_CONFIGURATION
);
2827 /* Another special case: on NT, the PATH variable is actually named
2828 "Path" although cmd.exe (perhaps NT itself) arranges for
2829 environment variable lookup and setting to be case insensitive.
2830 However, Emacs assumes a fully case sensitive environment, so we
2831 need to change "Path" to "PATH" to match the expectations of
2832 various elisp packages. We do this by the sneaky method of
2833 modifying the string in the C runtime environ entry.
2835 The same applies to COMSPEC. */
2839 for (envp
= environ
; *envp
; envp
++)
2840 if (_strnicmp (*envp
, "PATH=", 5) == 0)
2841 memcpy (*envp
, "PATH=", 5);
2842 else if (_strnicmp (*envp
, "COMSPEC=", 8) == 0)
2843 memcpy (*envp
, "COMSPEC=", 8);
2846 /* Remember the initial working directory for getcwd. */
2847 /* FIXME: Do we need to resolve possible symlinks in startup_dir?
2848 Does it matter anywhere in Emacs? */
2849 if (w32_unicode_filenames
)
2851 wchar_t wstartup_dir
[MAX_PATH
];
2853 if (!GetCurrentDirectoryW (MAX_PATH
, wstartup_dir
))
2855 filename_from_utf16 (wstartup_dir
, startup_dir
);
2859 char astartup_dir
[MAX_PATH
];
2861 if (!GetCurrentDirectoryA (MAX_PATH
, astartup_dir
))
2863 filename_from_ansi (astartup_dir
, startup_dir
);
2867 static char modname
[MAX_PATH
];
2869 if (!GetModuleFileNameA (NULL
, modname
, MAX_PATH
))
2874 /* Determine if there is a middle mouse button, to allow parse_button
2875 to decide whether right mouse events should be mouse-2 or
2877 w32_num_mouse_buttons
= GetSystemMetrics (SM_CMOUSEBUTTONS
);
2882 /* Called from expand-file-name when default-directory is not a string. */
2885 emacs_root_dir (void)
2887 static char root_dir
[MAX_UTF8_PATH
];
2890 p
= getenv ("emacs_dir");
2893 filename_from_ansi (p
, root_dir
);
2894 root_dir
[parse_root (root_dir
, NULL
)] = '\0';
2895 dostounix_filename (root_dir
);
2899 #include <sys/timeb.h>
2901 /* Emulate gettimeofday (Ulrich Leodolter, 1/11/95). */
2903 gettimeofday (struct timeval
*__restrict tv
, struct timezone
*__restrict tz
)
2908 tv
->tv_sec
= tb
.time
;
2909 tv
->tv_usec
= tb
.millitm
* 1000L;
2910 /* Implementation note: _ftime sometimes doesn't update the dstflag
2911 according to the new timezone when the system timezone is
2912 changed. We could fix that by using GetSystemTime and
2913 GetTimeZoneInformation, but that doesn't seem necessary, since
2914 Emacs always calls gettimeofday with the 2nd argument NULL (see
2915 current_emacs_time). */
2918 tz
->tz_minuteswest
= tb
.timezone
; /* minutes west of Greenwich */
2919 tz
->tz_dsttime
= tb
.dstflag
; /* type of dst correction */
2924 /* Emulate fdutimens. */
2926 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2927 TIMESPEC[0] and TIMESPEC[1], respectively.
2928 FD must be either negative -- in which case it is ignored --
2929 or a file descriptor that is open on FILE.
2930 If FD is nonnegative, then FILE can be NULL, which means
2931 use just futimes instead of utimes.
2932 If TIMESPEC is null, FAIL.
2933 Return 0 on success, -1 (setting errno) on failure. */
2936 fdutimens (int fd
, char const *file
, struct timespec
const timespec
[2])
2943 if (fd
< 0 && !file
)
2948 /* _futime's prototype defines 2nd arg as having the type 'struct
2949 _utimbuf', while utime needs to accept 'struct utimbuf' for
2950 compatibility with Posix. So we need to use 2 different (but
2951 equivalent) types to avoid compiler warnings, sigh. */
2954 struct _utimbuf _ut
;
2956 _ut
.actime
= timespec
[0].tv_sec
;
2957 _ut
.modtime
= timespec
[1].tv_sec
;
2958 return _futime (fd
, &_ut
);
2964 ut
.actime
= timespec
[0].tv_sec
;
2965 ut
.modtime
= timespec
[1].tv_sec
;
2966 /* Call 'utime', which is implemented below, not the MS library
2967 function, which fails on directories. */
2968 return utime (file
, &ut
);
2973 /* ------------------------------------------------------------------------- */
2974 /* IO support and wrapper functions for the Windows API. */
2975 /* ------------------------------------------------------------------------- */
2977 /* Place a wrapper around the MSVC version of ctime. It returns NULL
2978 on network directories, so we handle that case here.
2979 (Ulrich Leodolter, 1/11/95). */
2981 sys_ctime (const time_t *t
)
2983 char *str
= (char *) ctime (t
);
2984 return (str
? str
: (char *)"Sun Jan 01 00:00:00 1970");
2987 /* Emulate sleep...we could have done this with a define, but that
2988 would necessitate including windows.h in the files that used it.
2989 This is much easier. */
2991 sys_sleep (int seconds
)
2993 Sleep (seconds
* 1000);
2996 /* Internal MSVC functions for low-level descriptor munging */
2997 extern int __cdecl
_set_osfhnd (int fd
, long h
);
2998 extern int __cdecl
_free_osfhnd (int fd
);
3000 /* parallel array of private info on file handles */
3001 filedesc fd_info
[ MAXDESC
];
3003 typedef struct volume_info_data
{
3004 struct volume_info_data
* next
;
3006 /* time when info was obtained */
3009 /* actual volume info */
3018 /* Global referenced by various functions. */
3019 static volume_info_data volume_info
;
3021 /* Vector to indicate which drives are local and fixed (for which cached
3022 data never expires). */
3023 static BOOL fixed_drives
[26];
3025 /* Consider cached volume information to be stale if older than 10s,
3026 at least for non-local drives. Info for fixed drives is never stale. */
3027 #define DRIVE_INDEX( c ) ( (c) <= 'Z' ? (c) - 'A' : (c) - 'a' )
3028 #define VOLINFO_STILL_VALID( root_dir, info ) \
3029 ( ( isalpha (root_dir[0]) && \
3030 fixed_drives[ DRIVE_INDEX (root_dir[0]) ] ) \
3031 || GetTickCount () - info->timestamp < 10000 )
3033 /* Cache support functions. */
3035 /* Simple linked list with linear search is sufficient. */
3036 static volume_info_data
*volume_cache
= NULL
;
3038 static volume_info_data
*
3039 lookup_volume_info (char * root_dir
)
3041 volume_info_data
* info
;
3043 for (info
= volume_cache
; info
; info
= info
->next
)
3044 if (xstrcasecmp (info
->root_dir
, root_dir
) == 0)
3050 add_volume_info (char * root_dir
, volume_info_data
* info
)
3052 info
->root_dir
= xstrdup (root_dir
);
3053 unixtodos_filename (info
->root_dir
);
3054 info
->next
= volume_cache
;
3055 volume_cache
= info
;
3059 /* Wrapper for GetVolumeInformation, which uses caching to avoid
3060 performance penalty (~2ms on 486 for local drives, 7.5ms for local
3061 cdrom drive, ~5-10ms or more for remote drives on LAN). */
3062 static volume_info_data
*
3063 GetCachedVolumeInformation (char * root_dir
)
3065 volume_info_data
* info
;
3066 char default_root
[ MAX_UTF8_PATH
];
3067 char name
[MAX_PATH
+1];
3068 char type
[MAX_PATH
+1];
3070 /* NULL for root_dir means use root from current directory. */
3071 if (root_dir
== NULL
)
3073 if (w32_unicode_filenames
)
3075 wchar_t curdirw
[MAX_PATH
];
3077 if (GetCurrentDirectoryW (MAX_PATH
, curdirw
) == 0)
3079 filename_from_utf16 (curdirw
, default_root
);
3083 char curdira
[MAX_PATH
];
3085 if (GetCurrentDirectoryA (MAX_PATH
, curdira
) == 0)
3087 filename_from_ansi (curdira
, default_root
);
3089 parse_root (default_root
, (const char **)&root_dir
);
3091 root_dir
= default_root
;
3094 /* Local fixed drives can be cached permanently. Removable drives
3095 cannot be cached permanently, since the volume name and serial
3096 number (if nothing else) can change. Remote drives should be
3097 treated as if they are removable, since there is no sure way to
3098 tell whether they are or not. Also, the UNC association of drive
3099 letters mapped to remote volumes can be changed at any time (even
3100 by other processes) without notice.
3102 As a compromise, so we can benefit from caching info for remote
3103 volumes, we use a simple expiry mechanism to invalidate cache
3104 entries that are more than ten seconds old. */
3107 /* No point doing this, because WNetGetConnection is even slower than
3108 GetVolumeInformation, consistently taking ~50ms on a 486 (FWIW,
3109 GetDriveType is about the only call of this type which does not
3110 involve network access, and so is extremely quick). */
3112 /* Map drive letter to UNC if remote. */
3113 if (isalpha (root_dir
[0]) && !fixed
[DRIVE_INDEX (root_dir
[0])])
3115 char remote_name
[ 256 ];
3116 char drive
[3] = { root_dir
[0], ':' };
3118 if (WNetGetConnection (drive
, remote_name
, sizeof (remote_name
))
3120 /* do something */ ;
3124 info
= lookup_volume_info (root_dir
);
3126 if (info
== NULL
|| ! VOLINFO_STILL_VALID (root_dir
, info
))
3132 /* Info is not cached, or is stale. */
3133 if (w32_unicode_filenames
)
3135 wchar_t root_w
[MAX_PATH
];
3136 wchar_t name_w
[MAX_PATH
+1];
3137 wchar_t type_w
[MAX_PATH
+1];
3139 filename_to_utf16 (root_dir
, root_w
);
3140 if (!GetVolumeInformationW (root_w
,
3141 name_w
, sizeof (name_w
),
3145 type_w
, sizeof (type_w
)))
3147 /* Hmm... not really 100% correct, as these 2 are not file
3149 filename_from_utf16 (name_w
, name
);
3150 filename_from_utf16 (type_w
, type
);
3154 char root_a
[MAX_PATH
];
3155 char name_a
[MAX_PATH
+1];
3156 char type_a
[MAX_PATH
+1];
3158 filename_to_ansi (root_dir
, root_a
);
3159 if (!GetVolumeInformationA (root_a
,
3160 name_a
, sizeof (name_a
),
3164 type_a
, sizeof (type_a
)))
3166 filename_from_ansi (name_a
, name
);
3167 filename_from_ansi (type_a
, type
);
3170 /* Cache the volume information for future use, overwriting existing
3171 entry if present. */
3174 info
= xmalloc (sizeof (volume_info_data
));
3175 add_volume_info (root_dir
, info
);
3183 info
->name
= xstrdup (name
);
3184 unixtodos_filename (info
->name
);
3185 info
->serialnum
= serialnum
;
3186 info
->maxcomp
= maxcomp
;
3187 info
->flags
= flags
;
3188 info
->type
= xstrdup (type
);
3189 info
->timestamp
= GetTickCount ();
3195 /* Get information on the volume where NAME is held; set path pointer to
3196 start of pathname in NAME (past UNC header\volume header if present),
3197 if pPath is non-NULL.
3199 Note: if NAME includes symlinks, the information is for the volume
3200 of the symlink, not of its target. That's because, even though
3201 GetVolumeInformation returns information about the symlink target
3202 of its argument, we only pass the root directory to
3203 GetVolumeInformation, not the full NAME. */
3205 get_volume_info (const char * name
, const char ** pPath
)
3207 char temp
[MAX_UTF8_PATH
];
3208 char *rootname
= NULL
; /* default to current volume */
3209 volume_info_data
* info
;
3210 int root_len
= parse_root (name
, pPath
);
3215 /* Copy the root name of the volume, if given. */
3218 strncpy (temp
, name
, root_len
);
3219 temp
[root_len
] = '\0';
3220 unixtodos_filename (temp
);
3224 info
= GetCachedVolumeInformation (rootname
);
3227 /* Set global referenced by other functions. */
3228 volume_info
= *info
;
3234 /* Determine if volume is FAT format (ie. only supports short 8.3
3235 names); also set path pointer to start of pathname in name, if
3236 pPath is non-NULL. */
3238 is_fat_volume (const char * name
, const char ** pPath
)
3240 if (get_volume_info (name
, pPath
))
3241 return (volume_info
.maxcomp
== 12);
3245 /* Convert all slashes in a filename to backslashes, and map filename
3246 to a valid 8.3 name if necessary. The result is a pointer to a
3247 static buffer, so CAVEAT EMPTOR! */
3248 const char *map_w32_filename (const char *, const char **);
3251 map_w32_filename (const char * name
, const char ** pPath
)
3253 static char shortname
[MAX_UTF8_PATH
];
3254 char * str
= shortname
;
3257 const char * save_name
= name
;
3259 if (strlen (name
) >= sizeof (shortname
))
3261 /* Return a filename which will cause callers to fail. */
3262 strcpy (shortname
, "?");
3266 if (!fatal_error_in_progress
/* disable fancy processing during crash */
3267 && is_fat_volume (name
, (const char **)&path
)) /* truncate to 8.3 */
3269 register int left
= 8; /* maximum number of chars in part */
3270 register int extn
= 0; /* extension added? */
3271 register int dots
= 2; /* maximum number of dots allowed */
3274 *str
++ = *name
++; /* skip past UNC header */
3276 while ((c
= *name
++))
3283 *str
++ = (c
== ':' ? ':' : '\\');
3284 extn
= 0; /* reset extension flags */
3285 dots
= 2; /* max 2 dots */
3286 left
= 8; /* max length 8 for main part */
3291 /* Convert path components of the form .xxx to _xxx,
3292 but leave . and .. as they are. This allows .emacs
3293 to be read as _emacs, for example. */
3297 IS_DIRECTORY_SEP (*name
))
3312 extn
= 1; /* we've got an extension */
3313 left
= 3; /* 3 chars in extension */
3317 /* any embedded dots after the first are converted to _ */
3322 case '#': /* don't lose these, they're important */
3324 str
[-1] = c
; /* replace last character of part */
3327 if ( left
&& 'A' <= c
&& c
<= 'Z' )
3329 *str
++ = tolower (c
); /* map to lower case (looks nicer) */
3331 dots
= 0; /* started a path component */
3340 strcpy (shortname
, name
);
3341 unixtodos_filename (shortname
);
3345 *pPath
= shortname
+ (path
- save_name
);
3351 is_exec (const char * name
)
3353 char * p
= strrchr (name
, '.');
3356 && (xstrcasecmp (p
, ".exe") == 0 ||
3357 xstrcasecmp (p
, ".com") == 0 ||
3358 xstrcasecmp (p
, ".bat") == 0 ||
3359 xstrcasecmp (p
, ".cmd") == 0));
3362 /* Emulate the Unix directory procedures opendir, closedir, and
3363 readdir. We rename them to sys_* names because some versions of
3364 MinGW startup code call opendir and readdir to glob wildcards, and
3365 the code that calls them doesn't grok UTF-8 encoded file names we
3366 produce in dirent->d_name[]. */
3368 struct dirent dir_static
; /* simulated directory contents */
3369 static HANDLE dir_find_handle
= INVALID_HANDLE_VALUE
;
3370 static int dir_is_fat
;
3371 static char dir_pathname
[MAX_UTF8_PATH
];
3372 static WIN32_FIND_DATAW dir_find_data_w
;
3373 static WIN32_FIND_DATAA dir_find_data_a
;
3374 #define DIR_FIND_DATA_W 1
3375 #define DIR_FIND_DATA_A 2
3376 static int last_dir_find_data
= -1;
3378 /* Support shares on a network resource as subdirectories of a read-only
3380 static HANDLE wnet_enum_handle
= INVALID_HANDLE_VALUE
;
3381 static HANDLE
open_unc_volume (const char *);
3382 static void *read_unc_volume (HANDLE
, wchar_t *, char *, int);
3383 static void close_unc_volume (HANDLE
);
3386 sys_opendir (const char *filename
)
3390 /* Opening is done by FindFirstFile. However, a read is inherent to
3391 this operation, so we defer the open until read time. */
3393 if (dir_find_handle
!= INVALID_HANDLE_VALUE
)
3395 if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
3398 /* Note: We don't support traversal of UNC volumes via symlinks.
3399 Doing so would mean punishing 99.99% of use cases by resolving
3400 all the possible symlinks in FILENAME, recursively. */
3401 if (is_unc_volume (filename
))
3403 wnet_enum_handle
= open_unc_volume (filename
);
3404 if (wnet_enum_handle
== INVALID_HANDLE_VALUE
)
3408 if (!(dirp
= (DIR *) malloc (sizeof (DIR))))
3415 strncpy (dir_pathname
, map_w32_filename (filename
, NULL
), MAX_UTF8_PATH
- 1);
3416 dir_pathname
[MAX_UTF8_PATH
- 1] = '\0';
3417 /* Note: We don't support symlinks to file names on FAT volumes.
3418 Doing so would mean punishing 99.99% of use cases by resolving
3419 all the possible symlinks in FILENAME, recursively. */
3420 dir_is_fat
= is_fat_volume (filename
, NULL
);
3426 sys_closedir (DIR *dirp
)
3428 /* If we have a find-handle open, close it. */
3429 if (dir_find_handle
!= INVALID_HANDLE_VALUE
)
3431 FindClose (dir_find_handle
);
3432 dir_find_handle
= INVALID_HANDLE_VALUE
;
3434 else if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
3436 close_unc_volume (wnet_enum_handle
);
3437 wnet_enum_handle
= INVALID_HANDLE_VALUE
;
3439 xfree ((char *) dirp
);
3443 sys_readdir (DIR *dirp
)
3445 int downcase
= !NILP (Vw32_downcase_file_names
);
3447 if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
3449 if (!read_unc_volume (wnet_enum_handle
,
3450 dir_find_data_w
.cFileName
,
3451 dir_find_data_a
.cFileName
,
3455 /* If we aren't dir_finding, do a find-first, otherwise do a find-next. */
3456 else if (dir_find_handle
== INVALID_HANDLE_VALUE
)
3458 char filename
[MAX_UTF8_PATH
];
3460 bool last_slash
= true;
3462 /* Note: We don't need to worry about dir_pathname being longer
3463 than MAX_UTF8_PATH, as sys_opendir already took care of that
3464 when it called map_w32_filename: that function will put a "?"
3465 in its return value in that case, thus failing all the calls
3467 strcpy (filename
, dir_pathname
);
3468 ln
= strlen (filename
);
3469 if (!IS_DIRECTORY_SEP (filename
[ln
- 1]))
3472 /* Note: No need to resolve symlinks in FILENAME, because
3473 FindFirst opens the directory that is the target of a
3475 if (w32_unicode_filenames
)
3477 wchar_t fnw
[MAX_PATH
+ 2];
3479 filename_to_utf16 (filename
, fnw
);
3481 wcscat (fnw
, L
"\\");
3483 dir_find_handle
= FindFirstFileW (fnw
, &dir_find_data_w
);
3487 char fna
[MAX_PATH
+ 2];
3489 filename_to_ansi (filename
, fna
);
3493 /* If FILENAME is not representable by the current ANSI
3494 codepage, we don't want FindFirstFileA to interpret the
3495 '?' characters as a wildcard. */
3496 if (_mbspbrk (fna
, "?"))
3497 dir_find_handle
= INVALID_HANDLE_VALUE
;
3499 dir_find_handle
= FindFirstFileA (fna
, &dir_find_data_a
);
3502 if (dir_find_handle
== INVALID_HANDLE_VALUE
)
3504 /* Any changes in the value of errno here should be in sync
3505 with what directory_files_internal does when it calls
3507 switch (GetLastError ())
3509 /* Windows uses this value when FindFirstFile finds no
3510 files that match the wildcard. This is not supposed
3511 to happen, since our wildcard is "*", but just in
3512 case, if there's some weird empty directory with not
3513 even "." and ".." entries... */
3514 case ERROR_FILE_NOT_FOUND
:
3519 case ERROR_ACCESS_DENIED
:
3520 case ERROR_NETWORK_ACCESS_DENIED
:
3523 case ERROR_PATH_NOT_FOUND
:
3524 case ERROR_INVALID_DRIVE
:
3525 case ERROR_NOT_READY
:
3526 case ERROR_BAD_NETPATH
:
3527 case ERROR_BAD_NET_NAME
:
3534 else if (w32_unicode_filenames
)
3536 if (!FindNextFileW (dir_find_handle
, &dir_find_data_w
))
3544 if (!FindNextFileA (dir_find_handle
, &dir_find_data_a
))
3551 /* Emacs never uses this value, so don't bother making it match
3552 value returned by stat(). */
3553 dir_static
.d_ino
= 1;
3555 if (w32_unicode_filenames
)
3557 if (downcase
|| dir_is_fat
)
3559 wchar_t tem
[MAX_PATH
];
3561 wcscpy (tem
, dir_find_data_w
.cFileName
);
3563 filename_from_utf16 (tem
, dir_static
.d_name
);
3566 filename_from_utf16 (dir_find_data_w
.cFileName
, dir_static
.d_name
);
3567 last_dir_find_data
= DIR_FIND_DATA_W
;
3573 /* If the file name in cFileName[] includes `?' characters, it
3574 means the original file name used characters that cannot be
3575 represented by the current ANSI codepage. To avoid total
3576 lossage, retrieve the short 8+3 alias of the long file
3578 if (_mbspbrk (dir_find_data_a
.cFileName
, "?"))
3580 strcpy (tem
, dir_find_data_a
.cAlternateFileName
);
3581 /* 8+3 aliases are returned in all caps, which could break
3582 various alists that look at filenames' extensions. */
3585 else if (downcase
|| dir_is_fat
)
3586 strcpy (tem
, dir_find_data_a
.cFileName
);
3588 filename_from_ansi (dir_find_data_a
.cFileName
, dir_static
.d_name
);
3589 if (downcase
|| dir_is_fat
)
3592 filename_from_ansi (tem
, dir_static
.d_name
);
3594 last_dir_find_data
= DIR_FIND_DATA_A
;
3597 dir_static
.d_namlen
= strlen (dir_static
.d_name
);
3598 dir_static
.d_reclen
= sizeof (struct dirent
) - MAX_UTF8_PATH
+ 3 +
3599 dir_static
.d_namlen
- dir_static
.d_namlen
% 4;
3605 open_unc_volume (const char *path
)
3607 const char *fn
= map_w32_filename (path
, NULL
);
3611 if (w32_unicode_filenames
)
3614 wchar_t fnw
[MAX_PATH
];
3616 nrw
.dwScope
= RESOURCE_GLOBALNET
;
3617 nrw
.dwType
= RESOURCETYPE_DISK
;
3618 nrw
.dwDisplayType
= RESOURCEDISPLAYTYPE_SERVER
;
3619 nrw
.dwUsage
= RESOURCEUSAGE_CONTAINER
;
3620 nrw
.lpLocalName
= NULL
;
3621 filename_to_utf16 (fn
, fnw
);
3622 nrw
.lpRemoteName
= fnw
;
3623 nrw
.lpComment
= NULL
;
3624 nrw
.lpProvider
= NULL
;
3626 result
= WNetOpenEnumW (RESOURCE_GLOBALNET
, RESOURCETYPE_DISK
,
3627 RESOURCEUSAGE_CONNECTABLE
, &nrw
, &henum
);
3634 nra
.dwScope
= RESOURCE_GLOBALNET
;
3635 nra
.dwType
= RESOURCETYPE_DISK
;
3636 nra
.dwDisplayType
= RESOURCEDISPLAYTYPE_SERVER
;
3637 nra
.dwUsage
= RESOURCEUSAGE_CONTAINER
;
3638 nra
.lpLocalName
= NULL
;
3639 filename_to_ansi (fn
, fna
);
3640 nra
.lpRemoteName
= fna
;
3641 nra
.lpComment
= NULL
;
3642 nra
.lpProvider
= NULL
;
3644 result
= WNetOpenEnumA (RESOURCE_GLOBALNET
, RESOURCETYPE_DISK
,
3645 RESOURCEUSAGE_CONNECTABLE
, &nra
, &henum
);
3647 if (result
== NO_ERROR
)
3651 /* Make sure directory_files_internal reports a sensible error. */
3653 return INVALID_HANDLE_VALUE
;
3658 read_unc_volume (HANDLE henum
, wchar_t *fname_w
, char *fname_a
, int size
)
3663 DWORD bufsize
= 512;
3667 if (w32_unicode_filenames
)
3672 buffer
= alloca (bufsize
);
3673 result
= WNetEnumResourceW (henum
, &count
, buffer
, &bufsize
);
3674 if (result
!= NO_ERROR
)
3676 /* WNetEnumResource returns \\resource\share...skip forward to "share". */
3677 ptrw
= ((LPNETRESOURCEW
) buffer
)->lpRemoteName
;
3679 while (*ptrw
&& *ptrw
!= L
'/' && *ptrw
!= L
'\\') ptrw
++;
3681 wcsncpy (fname_w
, ptrw
, size
);
3686 int dbcs_p
= max_filename_mbslen () > 1;
3689 buffer
= alloca (bufsize
);
3690 result
= WNetEnumResourceA (henum
, &count
, buffer
, &bufsize
);
3691 if (result
!= NO_ERROR
)
3693 ptra
= ((LPNETRESOURCEA
) buffer
)->lpRemoteName
;
3696 while (*ptra
&& !IS_DIRECTORY_SEP (*ptra
)) ptra
++;
3699 while (*ptra
&& !IS_DIRECTORY_SEP (*ptra
))
3700 ptra
= CharNextExA (file_name_codepage
, ptra
, 0);
3703 strncpy (fname_a
, ptra
, size
);
3711 close_unc_volume (HANDLE henum
)
3713 if (henum
!= INVALID_HANDLE_VALUE
)
3714 WNetCloseEnum (henum
);
3718 unc_volume_file_attributes (const char *path
)
3723 henum
= open_unc_volume (path
);
3724 if (henum
== INVALID_HANDLE_VALUE
)
3727 attrs
= FILE_ATTRIBUTE_READONLY
| FILE_ATTRIBUTE_DIRECTORY
;
3729 close_unc_volume (henum
);
3734 /* Ensure a network connection is authenticated. */
3736 logon_network_drive (const char *path
)
3738 char share
[MAX_UTF8_PATH
];
3745 if (IS_DIRECTORY_SEP (path
[0]) && IS_DIRECTORY_SEP (path
[1]))
3746 drvtype
= DRIVE_REMOTE
;
3747 else if (path
[0] == '\0' || path
[1] != ':')
3748 drvtype
= GetDriveType (NULL
);
3755 drvtype
= GetDriveType (drive
);
3758 /* Only logon to networked drives. */
3759 if (drvtype
!= DRIVE_REMOTE
)
3763 strncpy (share
, path
, MAX_UTF8_PATH
);
3764 /* Truncate to just server and share name. */
3765 for (p
= share
+ 2; *p
&& p
< share
+ MAX_UTF8_PATH
; p
++)
3767 if (IS_DIRECTORY_SEP (*p
) && ++n_slashes
> 3)
3774 if (w32_unicode_filenames
)
3776 NETRESOURCEW resourcew
;
3777 wchar_t share_w
[MAX_PATH
];
3779 resourcew
.dwScope
= RESOURCE_GLOBALNET
;
3780 resourcew
.dwType
= RESOURCETYPE_DISK
;
3781 resourcew
.dwDisplayType
= RESOURCEDISPLAYTYPE_SHARE
;
3782 resourcew
.dwUsage
= RESOURCEUSAGE_CONTAINER
;
3783 resourcew
.lpLocalName
= NULL
;
3784 filename_to_utf16 (share
, share_w
);
3785 resourcew
.lpRemoteName
= share_w
;
3786 resourcew
.lpProvider
= NULL
;
3788 val
= WNetAddConnection2W (&resourcew
, NULL
, NULL
, CONNECT_INTERACTIVE
);
3792 NETRESOURCEA resourcea
;
3793 char share_a
[MAX_PATH
];
3795 resourcea
.dwScope
= RESOURCE_GLOBALNET
;
3796 resourcea
.dwType
= RESOURCETYPE_DISK
;
3797 resourcea
.dwDisplayType
= RESOURCEDISPLAYTYPE_SHARE
;
3798 resourcea
.dwUsage
= RESOURCEUSAGE_CONTAINER
;
3799 resourcea
.lpLocalName
= NULL
;
3800 filename_to_ansi (share
, share_a
);
3801 resourcea
.lpRemoteName
= share_a
;
3802 resourcea
.lpProvider
= NULL
;
3804 val
= WNetAddConnection2A (&resourcea
, NULL
, NULL
, CONNECT_INTERACTIVE
);
3810 case ERROR_ALREADY_ASSIGNED
:
3812 case ERROR_ACCESS_DENIED
:
3813 case ERROR_LOGON_FAILURE
:
3819 case ERROR_BAD_NET_NAME
:
3820 case ERROR_NO_NET_OR_BAD_PATH
:
3821 case ERROR_NO_NETWORK
:
3822 case ERROR_CANCELLED
:
3829 /* Emulate faccessat(2). */
3831 faccessat (int dirfd
, const char * path
, int mode
, int flags
)
3835 if (dirfd
!= AT_FDCWD
3836 && !(IS_DIRECTORY_SEP (path
[0])
3837 || IS_DEVICE_SEP (path
[1])))
3843 /* MSVCRT implementation of 'access' doesn't recognize D_OK, and its
3844 newer versions blow up when passed D_OK. */
3845 path
= map_w32_filename (path
, NULL
);
3846 /* If the last element of PATH is a symlink, we need to resolve it
3847 to get the attributes of its target file. Note: any symlinks in
3848 PATH elements other than the last one are transparently resolved
3849 by GetFileAttributes below. */
3850 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) != 0
3851 && (flags
& AT_SYMLINK_NOFOLLOW
) == 0)
3852 path
= chase_symlinks (path
);
3854 if (w32_unicode_filenames
)
3856 wchar_t path_w
[MAX_PATH
];
3858 filename_to_utf16 (path
, path_w
);
3859 attributes
= GetFileAttributesW (path_w
);
3863 char path_a
[MAX_PATH
];
3865 filename_to_ansi (path
, path_a
);
3866 attributes
= GetFileAttributesA (path_a
);
3869 if (attributes
== -1)
3871 DWORD w32err
= GetLastError ();
3875 case ERROR_INVALID_NAME
:
3876 case ERROR_BAD_PATHNAME
:
3877 if (is_unc_volume (path
))
3879 attributes
= unc_volume_file_attributes (path
);
3880 if (attributes
== -1)
3888 case ERROR_FILE_NOT_FOUND
:
3889 case ERROR_BAD_NETPATH
:
3900 if ((mode
& X_OK
) != 0
3901 && !(is_exec (path
) || (attributes
& FILE_ATTRIBUTE_DIRECTORY
) != 0))
3906 if ((mode
& W_OK
) != 0 && (attributes
& FILE_ATTRIBUTE_READONLY
) != 0)
3911 if ((mode
& D_OK
) != 0 && (attributes
& FILE_ATTRIBUTE_DIRECTORY
) == 0)
3919 /* A special test for DIRNAME being a directory accessible by the
3920 current user. This is needed because the security permissions in
3921 directory's ACLs are not visible in the Posix-style mode bits
3922 returned by 'stat' and in attributes returned by GetFileAttributes.
3923 So a directory would seem like it's readable by the current user,
3924 but will in fact error out with EACCES when they actually try. */
3926 w32_accessible_directory_p (const char *dirname
, ptrdiff_t dirlen
)
3928 char pattern
[MAX_UTF8_PATH
];
3929 bool last_slash
= dirlen
> 0 && IS_DIRECTORY_SEP (dirname
[dirlen
- 1]);
3932 /* Network volumes need a different reading method. */
3933 if (is_unc_volume (dirname
))
3935 void *read_result
= NULL
;
3936 wchar_t fnw
[MAX_PATH
];
3939 dh
= open_unc_volume (dirname
);
3940 if (dh
!= INVALID_HANDLE_VALUE
)
3942 read_result
= read_unc_volume (dh
, fnw
, fna
, MAX_PATH
);
3943 close_unc_volume (dh
);
3945 /* Treat empty volumes as accessible. */
3946 return read_result
!= NULL
|| GetLastError () == ERROR_NO_MORE_ITEMS
;
3949 /* Note: map_w32_filename makes sure DIRNAME is not longer than
3951 strcpy (pattern
, map_w32_filename (dirname
, NULL
));
3953 /* Note: No need to resolve symlinks in FILENAME, because FindFirst
3954 opens the directory that is the target of a symlink. */
3955 if (w32_unicode_filenames
)
3957 wchar_t pat_w
[MAX_PATH
+ 2];
3958 WIN32_FIND_DATAW dfd_w
;
3960 filename_to_utf16 (pattern
, pat_w
);
3962 wcscat (pat_w
, L
"\\");
3963 wcscat (pat_w
, L
"*");
3964 dh
= FindFirstFileW (pat_w
, &dfd_w
);
3968 char pat_a
[MAX_PATH
+ 2];
3969 WIN32_FIND_DATAA dfd_a
;
3971 filename_to_ansi (pattern
, pat_a
);
3973 strcpy (pat_a
, "\\");
3974 strcat (pat_a
, "*");
3975 /* In case DIRNAME cannot be expressed in characters from the
3976 current ANSI codepage. */
3977 if (_mbspbrk (pat_a
, "?"))
3978 dh
= INVALID_HANDLE_VALUE
;
3980 dh
= FindFirstFileA (pat_a
, &dfd_a
);
3983 if (dh
== INVALID_HANDLE_VALUE
)
3989 /* A version of 'access' to be used locally with file names in
3990 locale-specific encoding. Does not resolve symlinks and does not
3991 support file names on FAT12 and FAT16 volumes, but that's OK, since
3992 we only invoke this function for files inside the Emacs source or
3993 installation tree, on directories (so any symlinks should have the
3994 directory bit set), and on short file names such as "C:/.emacs". */
3996 sys_access (const char *fname
, int mode
)
3998 char fname_copy
[MAX_PATH
], *p
;
4001 strcpy (fname_copy
, fname
);
4002 /* Do the equivalent of unixtodos_filename. */
4003 for (p
= fname_copy
; *p
; p
= CharNext (p
))
4007 if ((attributes
= GetFileAttributesA (fname_copy
)) == -1)
4009 DWORD w32err
= GetLastError ();
4013 case ERROR_INVALID_NAME
:
4014 case ERROR_BAD_PATHNAME
:
4015 case ERROR_FILE_NOT_FOUND
:
4016 case ERROR_BAD_NETPATH
:
4025 if ((mode
& X_OK
) != 0
4026 && !(is_exec (fname_copy
)
4027 || (attributes
& FILE_ATTRIBUTE_DIRECTORY
) != 0))
4032 if ((mode
& W_OK
) != 0 && (attributes
& FILE_ATTRIBUTE_READONLY
) != 0)
4037 if ((mode
& D_OK
) != 0 && (attributes
& FILE_ATTRIBUTE_DIRECTORY
) == 0)
4045 /* Shadow some MSVC runtime functions to map requests for long filenames
4046 to reasonable short names if necessary. This was originally added to
4047 permit running Emacs on NT 3.1 on a FAT partition, which doesn't support
4051 sys_chdir (const char * path
)
4053 path
= map_w32_filename (path
, NULL
);
4054 if (w32_unicode_filenames
)
4056 wchar_t newdir_w
[MAX_PATH
];
4058 if (filename_to_utf16 (path
, newdir_w
) == 0)
4059 return _wchdir (newdir_w
);
4064 char newdir_a
[MAX_PATH
];
4066 if (filename_to_ansi (path
, newdir_a
) == 0)
4067 return _chdir (newdir_a
);
4073 sys_chmod (const char * path
, int mode
)
4075 path
= chase_symlinks (map_w32_filename (path
, NULL
));
4076 if (w32_unicode_filenames
)
4078 wchar_t path_w
[MAX_PATH
];
4080 filename_to_utf16 (path
, path_w
);
4081 return _wchmod (path_w
, mode
);
4085 char path_a
[MAX_PATH
];
4087 filename_to_ansi (path
, path_a
);
4088 return _chmod (path_a
, mode
);
4093 sys_creat (const char * path
, int mode
)
4095 path
= map_w32_filename (path
, NULL
);
4096 if (w32_unicode_filenames
)
4098 wchar_t path_w
[MAX_PATH
];
4100 filename_to_utf16 (path
, path_w
);
4101 return _wcreat (path_w
, mode
);
4105 char path_a
[MAX_PATH
];
4107 filename_to_ansi (path
, path_a
);
4108 return _creat (path_a
, mode
);
4113 sys_fopen (const char * path
, const char * mode
)
4117 const char * mode_save
= mode
;
4119 /* Force all file handles to be non-inheritable. This is necessary to
4120 ensure child processes don't unwittingly inherit handles that might
4121 prevent future file access. */
4125 else if (mode
[0] == 'w' || mode
[0] == 'a')
4126 oflag
= O_WRONLY
| O_CREAT
| O_TRUNC
;
4130 /* Only do simplistic option parsing. */
4134 oflag
&= ~(O_RDONLY
| O_WRONLY
);
4137 else if (mode
[0] == 'b')
4142 else if (mode
[0] == 't')
4149 path
= map_w32_filename (path
, NULL
);
4150 if (w32_unicode_filenames
)
4152 wchar_t path_w
[MAX_PATH
];
4154 filename_to_utf16 (path
, path_w
);
4155 fd
= _wopen (path_w
, oflag
| _O_NOINHERIT
, 0644);
4159 char path_a
[MAX_PATH
];
4161 filename_to_ansi (path
, path_a
);
4162 fd
= _open (path_a
, oflag
| _O_NOINHERIT
, 0644);
4167 return _fdopen (fd
, mode_save
);
4170 /* This only works on NTFS volumes, but is useful to have. */
4172 sys_link (const char * old
, const char * new)
4176 char oldname
[MAX_UTF8_PATH
], newname
[MAX_UTF8_PATH
];
4177 wchar_t oldname_w
[MAX_PATH
];
4178 char oldname_a
[MAX_PATH
];
4180 if (old
== NULL
|| new == NULL
)
4186 strcpy (oldname
, map_w32_filename (old
, NULL
));
4187 strcpy (newname
, map_w32_filename (new, NULL
));
4189 if (w32_unicode_filenames
)
4191 filename_to_utf16 (oldname
, oldname_w
);
4192 fileh
= CreateFileW (oldname_w
, 0, 0, NULL
, OPEN_EXISTING
,
4193 FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
4197 filename_to_ansi (oldname
, oldname_a
);
4198 fileh
= CreateFileA (oldname_a
, 0, 0, NULL
, OPEN_EXISTING
,
4199 FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
4201 if (fileh
!= INVALID_HANDLE_VALUE
)
4205 /* Confusingly, the "alternate" stream name field does not apply
4206 when restoring a hard link, and instead contains the actual
4207 stream data for the link (ie. the name of the link to create).
4208 The WIN32_STREAM_ID structure before the cStreamName field is
4209 the stream header, which is then immediately followed by the
4213 WIN32_STREAM_ID wid
;
4214 WCHAR wbuffer
[MAX_PATH
]; /* extra space for link name */
4217 /* We used to pass MB_PRECOMPOSED as the 2nd arg here, but MSDN
4218 indicates that flag is unsupported for CP_UTF8, and OTOH says
4219 it is the default anyway. */
4220 wlen
= pMultiByteToWideChar (CP_UTF8
, 0, newname
, -1,
4221 data
.wid
.cStreamName
, MAX_PATH
);
4224 LPVOID context
= NULL
;
4227 data
.wid
.dwStreamId
= BACKUP_LINK
;
4228 data
.wid
.dwStreamAttributes
= 0;
4229 data
.wid
.Size
.LowPart
= wlen
* sizeof (WCHAR
);
4230 data
.wid
.Size
.HighPart
= 0;
4231 data
.wid
.dwStreamNameSize
= 0;
4233 if (BackupWrite (fileh
, (LPBYTE
)&data
,
4234 offsetof (WIN32_STREAM_ID
, cStreamName
)
4235 + data
.wid
.Size
.LowPart
,
4236 &wbytes
, FALSE
, FALSE
, &context
)
4237 && BackupWrite (fileh
, NULL
, 0, &wbytes
, TRUE
, FALSE
, &context
))
4244 DWORD err
= GetLastError ();
4249 case ERROR_ACCESS_DENIED
:
4250 /* This is what happens when OLDNAME is a directory,
4251 since Windows doesn't support hard links to
4252 directories. Posix says to set errno to EPERM in
4254 if (w32_unicode_filenames
)
4255 attributes
= GetFileAttributesW (oldname_w
);
4257 attributes
= GetFileAttributesA (oldname_a
);
4258 if (attributes
!= -1
4259 && (attributes
& FILE_ATTRIBUTE_DIRECTORY
) != 0)
4261 else if (attributes
== -1
4262 && is_unc_volume (oldname
)
4263 && unc_volume_file_attributes (oldname
) != -1)
4268 case ERROR_TOO_MANY_LINKS
:
4271 case ERROR_NOT_SAME_DEVICE
:
4281 CloseHandle (fileh
);
4290 sys_mkdir (const char * path
)
4292 path
= map_w32_filename (path
, NULL
);
4294 if (w32_unicode_filenames
)
4296 wchar_t path_w
[MAX_PATH
];
4298 filename_to_utf16 (path
, path_w
);
4299 return _wmkdir (path_w
);
4303 char path_a
[MAX_PATH
];
4305 filename_to_ansi (path
, path_a
);
4306 return _mkdir (path_a
);
4311 sys_open (const char * path
, int oflag
, int mode
)
4313 const char* mpath
= map_w32_filename (path
, NULL
);
4316 if (w32_unicode_filenames
)
4318 wchar_t mpath_w
[MAX_PATH
];
4320 filename_to_utf16 (mpath
, mpath_w
);
4321 /* If possible, try to open file without _O_CREAT, to be able to
4322 write to existing hidden and system files. Force all file
4323 handles to be non-inheritable. */
4324 if ((oflag
& (_O_CREAT
| _O_EXCL
)) != (_O_CREAT
| _O_EXCL
))
4325 res
= _wopen (mpath_w
, (oflag
& ~_O_CREAT
) | _O_NOINHERIT
, mode
);
4327 res
= _wopen (mpath_w
, oflag
| _O_NOINHERIT
, mode
);
4331 char mpath_a
[MAX_PATH
];
4333 filename_to_ansi (mpath
, mpath_a
);
4334 if ((oflag
& (_O_CREAT
| _O_EXCL
)) != (_O_CREAT
| _O_EXCL
))
4335 res
= _open (mpath_a
, (oflag
& ~_O_CREAT
) | _O_NOINHERIT
, mode
);
4337 res
= _open (mpath_a
, oflag
| _O_NOINHERIT
, mode
);
4343 /* Implementation of mkostemp for MS-Windows, to avoid race conditions
4346 Standard algorithm for generating a temporary file name seems to be
4347 use pid or tid with a letter on the front (in place of the 6 X's)
4348 and cycle through the letters to find a unique name. We extend
4349 that to allow any reasonable character as the first of the 6 X's,
4350 so that the number of simultaneously used temporary files will be
4354 mkostemp (char * template, int flags
)
4358 unsigned uid
= GetCurrentThreadId ();
4359 int save_errno
= errno
;
4360 static char first_char
[] = "abcdefghijklmnopqrstuvwyz0123456789!%-_@#";
4363 if (template == NULL
)
4366 p
= template + strlen (template);
4368 /* replace up to the last 5 X's with uid in decimal */
4369 while (--p
>= template && p
[0] == 'X' && --i
>= 0)
4371 p
[0] = '0' + uid
% 10;
4375 if (i
< 0 && p
[0] == 'X')
4380 p
[0] = first_char
[i
];
4381 if ((fd
= sys_open (template,
4382 flags
| _O_CREAT
| _O_EXCL
| _O_RDWR
,
4383 S_IRUSR
| S_IWUSR
)) >= 0
4391 while (++i
< sizeof (first_char
));
4394 /* Template is badly formed or else we can't generate a unique name. */
4399 fchmod (int fd
, mode_t mode
)
4405 sys_rename_replace (const char *oldname
, const char *newname
, BOOL force
)
4408 char temp
[MAX_UTF8_PATH
], temp_a
[MAX_PATH
];;
4411 bool have_temp_a
= false;
4413 /* MoveFile on Windows 95 doesn't correctly change the short file name
4414 alias in a number of circumstances (it is not easy to predict when
4415 just by looking at oldname and newname, unfortunately). In these
4416 cases, renaming through a temporary name avoids the problem.
4418 A second problem on Windows 95 is that renaming through a temp name when
4419 newname is uppercase fails (the final long name ends up in
4420 lowercase, although the short alias might be uppercase) UNLESS the
4421 long temp name is not 8.3.
4423 So, on Windows 95 we always rename through a temp name, and we make sure
4424 the temp name has a long extension to ensure correct renaming. */
4426 strcpy (temp
, map_w32_filename (oldname
, NULL
));
4428 /* volume_info is set indirectly by map_w32_filename. */
4429 oldname_dev
= volume_info
.serialnum
;
4431 if (os_subtype
== OS_9X
)
4436 char oldname_a
[MAX_PATH
];
4438 oldname
= map_w32_filename (oldname
, NULL
);
4439 filename_to_ansi (oldname
, oldname_a
);
4440 filename_to_ansi (temp
, temp_a
);
4441 if ((o
= strrchr (oldname_a
, '\\')))
4444 o
= (char *) oldname_a
;
4446 if ((p
= strrchr (temp_a
, '\\')))
4453 /* Force temp name to require a manufactured 8.3 alias - this
4454 seems to make the second rename work properly. */
4455 sprintf (p
, "_.%s.%d", o
, i
);
4457 result
= rename (oldname_a
, temp_a
);
4459 /* This loop must surely terminate! */
4460 while (result
< 0 && errno
== EEXIST
);
4466 /* If FORCE, emulate Unix behavior - newname is deleted if it already exists
4467 (at least if it is a file; don't do this for directories).
4469 Since we mustn't do this if we are just changing the case of the
4470 file name (we would end up deleting the file we are trying to
4471 rename!), we let rename detect if the destination file already
4472 exists - that way we avoid the possible pitfalls of trying to
4473 determine ourselves whether two names really refer to the same
4474 file, which is not always possible in the general case. (Consider
4475 all the permutations of shared or subst'd drives, etc.) */
4477 newname
= map_w32_filename (newname
, NULL
);
4479 /* volume_info is set indirectly by map_w32_filename. */
4480 newname_dev
= volume_info
.serialnum
;
4482 if (w32_unicode_filenames
)
4484 wchar_t temp_w
[MAX_PATH
], newname_w
[MAX_PATH
];
4486 filename_to_utf16 (temp
, temp_w
);
4487 filename_to_utf16 (newname
, newname_w
);
4488 result
= _wrename (temp_w
, newname_w
);
4489 if (result
< 0 && force
)
4491 DWORD w32err
= GetLastError ();
4494 && newname_dev
!= oldname_dev
)
4496 /* The implementation of `rename' on Windows does not return
4497 errno = EXDEV when you are moving a directory to a
4498 different storage device (ex. logical disk). It returns
4499 EACCES instead. So here we handle such situations and
4503 if ((attributes
= GetFileAttributesW (temp_w
)) != -1
4504 && (attributes
& FILE_ATTRIBUTE_DIRECTORY
))
4507 else if (errno
== EEXIST
)
4509 if (_wchmod (newname_w
, 0666) != 0)
4511 if (_wunlink (newname_w
) != 0)
4513 result
= _wrename (temp_w
, newname_w
);
4515 else if (w32err
== ERROR_PRIVILEGE_NOT_HELD
4516 && is_symlink (temp
))
4518 /* This is Windows prohibiting the user from creating a
4519 symlink in another place, since that requires
4527 char newname_a
[MAX_PATH
];
4530 filename_to_ansi (temp
, temp_a
);
4531 filename_to_ansi (newname
, newname_a
);
4532 result
= rename (temp_a
, newname_a
);
4533 if (result
< 0 && force
)
4535 DWORD w32err
= GetLastError ();
4538 && newname_dev
!= oldname_dev
)
4542 if ((attributes
= GetFileAttributesA (temp_a
)) != -1
4543 && (attributes
& FILE_ATTRIBUTE_DIRECTORY
))
4546 else if (errno
== EEXIST
)
4548 if (_chmod (newname_a
, 0666) != 0)
4550 if (_unlink (newname_a
) != 0)
4552 result
= rename (temp_a
, newname_a
);
4554 else if (w32err
== ERROR_PRIVILEGE_NOT_HELD
4555 && is_symlink (temp
))
4564 sys_rename (char const *old
, char const *new)
4566 return sys_rename_replace (old
, new, TRUE
);
4570 sys_rmdir (const char * path
)
4572 path
= map_w32_filename (path
, NULL
);
4574 if (w32_unicode_filenames
)
4576 wchar_t path_w
[MAX_PATH
];
4578 filename_to_utf16 (path
, path_w
);
4579 return _wrmdir (path_w
);
4583 char path_a
[MAX_PATH
];
4585 filename_to_ansi (path
, path_a
);
4586 return _rmdir (path_a
);
4591 sys_unlink (const char * path
)
4595 path
= map_w32_filename (path
, NULL
);
4597 if (w32_unicode_filenames
)
4599 wchar_t path_w
[MAX_PATH
];
4601 filename_to_utf16 (path
, path_w
);
4602 /* On Unix, unlink works without write permission. */
4603 _wchmod (path_w
, 0666);
4604 rmstatus
= _wunlink (path_w
);
4606 /* Symlinks to directories can only be deleted by _rmdir;
4607 _unlink returns EACCES. */
4610 && (is_symlink (path
) & FILE_ATTRIBUTE_DIRECTORY
) != 0)
4611 rmstatus
= _wrmdir (path_w
);
4617 char path_a
[MAX_PATH
];
4619 filename_to_ansi (path
, path_a
);
4620 _chmod (path_a
, 0666);
4621 rmstatus
= _unlink (path_a
);
4625 && (is_symlink (path
) & FILE_ATTRIBUTE_DIRECTORY
) != 0)
4626 rmstatus
= _rmdir (path_a
);
4634 static FILETIME utc_base_ft
;
4635 static ULONGLONG utc_base
; /* In 100ns units */
4636 static int init
= 0;
4638 #define FILETIME_TO_U64(result, ft) \
4640 ULARGE_INTEGER uiTemp; \
4641 uiTemp.LowPart = (ft).dwLowDateTime; \
4642 uiTemp.HighPart = (ft).dwHighDateTime; \
4643 result = uiTemp.QuadPart; \
4647 initialize_utc_base (void)
4649 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
4658 st
.wMilliseconds
= 0;
4660 SystemTimeToFileTime (&st
, &utc_base_ft
);
4661 FILETIME_TO_U64 (utc_base
, utc_base_ft
);
4665 convert_time (FILETIME ft
)
4671 initialize_utc_base ();
4675 if (CompareFileTime (&ft
, &utc_base_ft
) < 0)
4678 FILETIME_TO_U64 (tmp
, ft
);
4679 return (time_t) ((tmp
- utc_base
) / 10000000L);
4683 convert_from_time_t (time_t time
, FILETIME
* pft
)
4689 initialize_utc_base ();
4693 /* time in 100ns units since 1-Jan-1601 */
4694 tmp
.QuadPart
= (ULONGLONG
) time
* 10000000L + utc_base
;
4695 pft
->dwHighDateTime
= tmp
.HighPart
;
4696 pft
->dwLowDateTime
= tmp
.LowPart
;
4699 static PSECURITY_DESCRIPTOR
4700 get_file_security_desc_by_handle (HANDLE h
)
4702 PSECURITY_DESCRIPTOR psd
= NULL
;
4704 SECURITY_INFORMATION si
= OWNER_SECURITY_INFORMATION
4705 | GROUP_SECURITY_INFORMATION
/* | DACL_SECURITY_INFORMATION */ ;
4707 err
= get_security_info (h
, SE_FILE_OBJECT
, si
,
4708 NULL
, NULL
, NULL
, NULL
, &psd
);
4709 if (err
!= ERROR_SUCCESS
)
4715 static PSECURITY_DESCRIPTOR
4716 get_file_security_desc_by_name (const char *fname
)
4718 PSECURITY_DESCRIPTOR psd
= NULL
;
4720 SECURITY_INFORMATION si
= OWNER_SECURITY_INFORMATION
4721 | GROUP_SECURITY_INFORMATION
/* | DACL_SECURITY_INFORMATION */ ;
4723 if (!get_file_security (fname
, si
, psd
, 0, &sd_len
))
4725 err
= GetLastError ();
4726 if (err
!= ERROR_INSUFFICIENT_BUFFER
)
4730 psd
= xmalloc (sd_len
);
4731 if (!get_file_security (fname
, si
, psd
, sd_len
, &sd_len
))
4743 unsigned n_subauthorities
;
4745 /* Use the last sub-authority value of the RID, the relative
4746 portion of the SID, as user/group ID. */
4747 n_subauthorities
= *get_sid_sub_authority_count (sid
);
4748 if (n_subauthorities
< 1)
4749 return 0; /* the "World" RID */
4750 return *get_sid_sub_authority (sid
, n_subauthorities
- 1);
4753 /* Caching SID and account values for faster lokup. */
4757 struct w32_id
*next
;
4759 unsigned char sid
[FLEXIBLE_ARRAY_MEMBER
];
4762 static struct w32_id
*w32_idlist
;
4765 w32_cached_id (PSID sid
, unsigned *id
, char *name
)
4767 struct w32_id
*tail
, *found
;
4769 for (found
= NULL
, tail
= w32_idlist
; tail
; tail
= tail
->next
)
4771 if (equal_sid ((PSID
)tail
->sid
, sid
))
4780 strcpy (name
, found
->name
);
4788 w32_add_to_cache (PSID sid
, unsigned id
, char *name
)
4791 struct w32_id
*new_entry
;
4793 /* We don't want to leave behind stale cache from when Emacs was
4797 sid_len
= get_length_sid (sid
);
4798 new_entry
= xmalloc (offsetof (struct w32_id
, sid
) + sid_len
);
4801 new_entry
->rid
= id
;
4802 strcpy (new_entry
->name
, name
);
4803 copy_sid (sid_len
, (PSID
)new_entry
->sid
, sid
);
4804 new_entry
->next
= w32_idlist
;
4805 w32_idlist
= new_entry
;
4814 get_name_and_id (PSECURITY_DESCRIPTOR psd
, unsigned *id
, char *nm
, int what
)
4818 SID_NAME_USE ignore
;
4820 DWORD name_len
= sizeof (name
);
4822 DWORD domain_len
= sizeof (domain
);
4827 result
= get_security_descriptor_owner (psd
, &sid
, &dflt
);
4828 else if (what
== GID
)
4829 result
= get_security_descriptor_group (psd
, &sid
, &dflt
);
4833 if (!result
|| !is_valid_sid (sid
))
4835 else if (!w32_cached_id (sid
, id
, nm
))
4837 if (!lookup_account_sid (NULL
, sid
, name
, &name_len
,
4838 domain
, &domain_len
, &ignore
)
4839 || name_len
> UNLEN
+1)
4843 *id
= get_rid (sid
);
4845 w32_add_to_cache (sid
, *id
, name
);
4852 get_file_owner_and_group (PSECURITY_DESCRIPTOR psd
, struct stat
*st
)
4854 int dflt_usr
= 0, dflt_grp
= 0;
4863 if (get_name_and_id (psd
, &st
->st_uid
, st
->st_uname
, UID
))
4865 if (get_name_and_id (psd
, &st
->st_gid
, st
->st_gname
, GID
))
4868 /* Consider files to belong to current user/group, if we cannot get
4869 more accurate information. */
4872 st
->st_uid
= dflt_passwd
.pw_uid
;
4873 strcpy (st
->st_uname
, dflt_passwd
.pw_name
);
4877 st
->st_gid
= dflt_passwd
.pw_gid
;
4878 strcpy (st
->st_gname
, dflt_group
.gr_name
);
4882 /* Return non-zero if NAME is a potentially slow filesystem. */
4883 int is_slow_fs (const char *);
4886 is_slow_fs (const char *name
)
4891 if (IS_DIRECTORY_SEP (name
[0]) && IS_DIRECTORY_SEP (name
[1]))
4892 devtype
= DRIVE_REMOTE
; /* assume UNC name is remote */
4893 else if (!(strlen (name
) >= 2 && IS_DEVICE_SEP (name
[1])))
4894 devtype
= GetDriveType (NULL
); /* use root of current drive */
4897 /* GetDriveType needs the root directory of the drive. */
4898 strncpy (drive_root
, name
, 2);
4899 drive_root
[2] = '\\';
4900 drive_root
[3] = '\0';
4901 devtype
= GetDriveType (drive_root
);
4903 return !(devtype
== DRIVE_FIXED
|| devtype
== DRIVE_RAMDISK
);
4906 /* If this is non-zero, the caller wants accurate information about
4907 file's owner and group, which could be expensive to get. dired.c
4908 uses this flag when needed for the job at hand. */
4909 int w32_stat_get_owner_group
;
4911 /* MSVC stat function can't cope with UNC names and has other bugs, so
4912 replace it with our own. This also allows us to calculate consistent
4913 inode values and owner/group without hacks in the main Emacs code,
4914 and support file names encoded in UTF-8. */
4917 stat_worker (const char * path
, struct stat
* buf
, int follow_symlinks
)
4919 char *name
, *save_name
, *r
;
4920 WIN32_FIND_DATAW wfd_w
;
4921 WIN32_FIND_DATAA wfd_a
;
4923 unsigned __int64 fake_inode
= 0;
4926 int rootdir
= FALSE
;
4927 PSECURITY_DESCRIPTOR psd
= NULL
;
4928 int is_a_symlink
= 0;
4929 DWORD file_flags
= FILE_FLAG_BACKUP_SEMANTICS
;
4930 DWORD access_rights
= 0;
4931 DWORD fattrs
= 0, serialnum
= 0, fs_high
= 0, fs_low
= 0, nlinks
= 1;
4932 FILETIME ctime
, atime
, wtime
;
4933 wchar_t name_w
[MAX_PATH
];
4934 char name_a
[MAX_PATH
];
4936 if (path
== NULL
|| buf
== NULL
)
4942 save_name
= name
= (char *) map_w32_filename (path
, &path
);
4943 /* Must be valid filename, no wild cards or other invalid
4945 if (strpbrk (name
, "*?|<>\""))
4951 len
= strlen (name
);
4952 /* Allocate 1 extra byte so that we could append a slash to a root
4953 directory, down below. */
4954 name
= strcpy (alloca (len
+ 2), name
);
4956 /* Avoid a somewhat costly call to is_symlink if the filesystem
4957 doesn't support symlinks. */
4958 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) != 0)
4959 is_a_symlink
= is_symlink (name
);
4961 /* Plan A: Open the file and get all the necessary information via
4962 the resulting handle. This solves several issues in one blow:
4964 . retrieves attributes for the target of a symlink, if needed
4965 . gets attributes of root directories and symlinks pointing to
4966 root directories, thus avoiding the need for special-casing
4967 these and detecting them by examining the file-name format
4968 . retrieves more accurate attributes (e.g., non-zero size for
4969 some directories, esp. directories that are junction points)
4970 . correctly resolves "c:/..", "/.." and similar file names
4971 . avoids run-time penalties for 99% of use cases
4973 Plan A is always tried first, unless the user asked not to (but
4974 if the file is a symlink and we need to follow links, we try Plan
4975 A even if the user asked not to).
4977 If Plan A fails, we go to Plan B (below), where various
4978 potentially expensive techniques must be used to handle "special"
4979 files such as UNC volumes etc. */
4980 if (!(NILP (Vw32_get_true_file_attributes
)
4981 || (EQ (Vw32_get_true_file_attributes
, Qlocal
) && is_slow_fs (name
)))
4982 /* Following symlinks requires getting the info by handle. */
4983 || (is_a_symlink
&& follow_symlinks
))
4985 BY_HANDLE_FILE_INFORMATION info
;
4987 if (is_a_symlink
&& !follow_symlinks
)
4988 file_flags
|= FILE_FLAG_OPEN_REPARSE_POINT
;
4989 /* READ_CONTROL access rights are required to get security info
4990 by handle. But if the OS doesn't support security in the
4991 first place, we don't need to try. */
4992 if (is_windows_9x () != TRUE
)
4993 access_rights
|= READ_CONTROL
;
4995 if (w32_unicode_filenames
)
4997 filename_to_utf16 (name
, name_w
);
4998 fh
= CreateFileW (name_w
, access_rights
, 0, NULL
, OPEN_EXISTING
,
5000 /* If CreateFile fails with READ_CONTROL, try again with
5001 zero as access rights. */
5002 if (fh
== INVALID_HANDLE_VALUE
&& access_rights
)
5003 fh
= CreateFileW (name_w
, 0, 0, NULL
, OPEN_EXISTING
,
5008 filename_to_ansi (name
, name_a
);
5009 fh
= CreateFileA (name_a
, access_rights
, 0, NULL
, OPEN_EXISTING
,
5011 if (fh
== INVALID_HANDLE_VALUE
&& access_rights
)
5012 fh
= CreateFileA (name_a
, 0, 0, NULL
, OPEN_EXISTING
,
5015 if (fh
== INVALID_HANDLE_VALUE
)
5016 goto no_true_file_attributes
;
5018 /* This is more accurate in terms of getting the correct number
5019 of links, but is quite slow (it is noticeable when Emacs is
5020 making a list of file name completions). */
5021 if (GetFileInformationByHandle (fh
, &info
))
5023 nlinks
= info
.nNumberOfLinks
;
5024 /* Might as well use file index to fake inode values, but this
5025 is not guaranteed to be unique unless we keep a handle open
5026 all the time (even then there are situations where it is
5027 not unique). Reputedly, there are at most 48 bits of info
5028 (on NTFS, presumably less on FAT). */
5029 fake_inode
= info
.nFileIndexHigh
;
5031 fake_inode
+= info
.nFileIndexLow
;
5032 serialnum
= info
.dwVolumeSerialNumber
;
5033 fs_high
= info
.nFileSizeHigh
;
5034 fs_low
= info
.nFileSizeLow
;
5035 ctime
= info
.ftCreationTime
;
5036 atime
= info
.ftLastAccessTime
;
5037 wtime
= info
.ftLastWriteTime
;
5038 fattrs
= info
.dwFileAttributes
;
5042 /* We don't go to Plan B here, because it's not clear that
5043 it's a good idea. The only known use case where
5044 CreateFile succeeds, but GetFileInformationByHandle fails
5045 (with ERROR_INVALID_FUNCTION) is for character devices
5046 such as NUL, PRN, etc. For these, switching to Plan B is
5047 a net loss, because we lose the character device
5048 attribute returned by GetFileType below (FindFirstFile
5049 doesn't set that bit in the attributes), and the other
5050 fields don't make sense for character devices anyway.
5051 Emacs doesn't really care for non-file entities in the
5052 context of l?stat, so neither do we. */
5054 /* w32err is assigned so one could put a breakpoint here and
5055 examine its value, when GetFileInformationByHandle
5057 DWORD w32err
= GetLastError ();
5061 case ERROR_FILE_NOT_FOUND
: /* can this ever happen? */
5067 /* Test for a symlink before testing for a directory, since
5068 symlinks to directories have the directory bit set, but we
5069 don't want them to appear as directories. */
5070 if (is_a_symlink
&& !follow_symlinks
)
5071 buf
->st_mode
= S_IFLNK
;
5072 else if (fattrs
& FILE_ATTRIBUTE_DIRECTORY
)
5073 buf
->st_mode
= S_IFDIR
;
5076 DWORD ftype
= GetFileType (fh
);
5080 case FILE_TYPE_DISK
:
5081 buf
->st_mode
= S_IFREG
;
5083 case FILE_TYPE_PIPE
:
5084 buf
->st_mode
= S_IFIFO
;
5086 case FILE_TYPE_CHAR
:
5087 case FILE_TYPE_UNKNOWN
:
5089 buf
->st_mode
= S_IFCHR
;
5092 /* We produce the fallback owner and group data, based on the
5093 current user that runs Emacs, in the following cases:
5095 . caller didn't request owner and group info
5096 . this is Windows 9X
5097 . getting security by handle failed, and we need to produce
5098 information for the target of a symlink (this is better
5099 than producing a potentially misleading info about the
5102 If getting security by handle fails, and we don't need to
5103 resolve symlinks, we try getting security by name. */
5104 if (!w32_stat_get_owner_group
|| is_windows_9x () == TRUE
)
5105 get_file_owner_and_group (NULL
, buf
);
5108 psd
= get_file_security_desc_by_handle (fh
);
5111 get_file_owner_and_group (psd
, buf
);
5114 else if (!(is_a_symlink
&& follow_symlinks
))
5116 psd
= get_file_security_desc_by_name (name
);
5117 get_file_owner_and_group (psd
, buf
);
5121 get_file_owner_and_group (NULL
, buf
);
5127 no_true_file_attributes
:
5128 /* Plan B: Either getting a handle on the file failed, or the
5129 caller explicitly asked us to not bother making this
5130 information more accurate.
5132 Implementation note: In Plan B, we never bother to resolve
5133 symlinks, even if we got here because we tried Plan A and
5134 failed. That's because, even if the caller asked for extra
5135 precision by setting Vw32_get_true_file_attributes to t,
5136 resolving symlinks requires acquiring a file handle to the
5137 symlink, which we already know will fail. And if the user
5138 did not ask for extra precision, resolving symlinks will fly
5139 in the face of that request, since the user then wants the
5140 lightweight version of the code. */
5141 rootdir
= (path
>= save_name
+ len
- 1
5142 && (IS_DIRECTORY_SEP (*path
) || *path
== 0));
5144 /* If name is "c:/.." or "/.." then stat "c:/" or "/". */
5145 r
= IS_DEVICE_SEP (name
[1]) ? &name
[2] : name
;
5146 if (IS_DIRECTORY_SEP (r
[0])
5147 && r
[1] == '.' && r
[2] == '.' && r
[3] == '\0')
5150 /* Note: If NAME is a symlink to the root of a UNC volume
5151 (i.e. "\\SERVER"), we will not detect that here, and we will
5152 return data about the symlink as result of FindFirst below.
5153 This is unfortunate, but that marginal use case does not
5154 justify a call to chase_symlinks which would impose a penalty
5155 on all the other use cases. (We get here for symlinks to
5156 roots of UNC volumes because CreateFile above fails for them,
5157 unlike with symlinks to root directories X:\ of drives.) */
5158 if (is_unc_volume (name
))
5160 fattrs
= unc_volume_file_attributes (name
);
5164 ctime
= atime
= wtime
= utc_base_ft
;
5168 /* Make sure root directories end in a slash. */
5169 if (!IS_DIRECTORY_SEP (name
[len
-1]))
5170 strcpy (name
+ len
, "\\");
5171 if (GetDriveType (name
) < 2)
5177 fattrs
= FILE_ATTRIBUTE_DIRECTORY
;
5178 ctime
= atime
= wtime
= utc_base_ft
;
5184 /* Make sure non-root directories do NOT end in a slash,
5185 otherwise FindFirstFile might fail. */
5186 if (IS_DIRECTORY_SEP (name
[len
-1]))
5189 /* (This is hacky, but helps when doing file completions on
5190 network drives.) Optimize by using information available from
5191 active readdir if possible. */
5192 len
= strlen (dir_pathname
);
5193 if (IS_DIRECTORY_SEP (dir_pathname
[len
-1]))
5195 if (dir_find_handle
!= INVALID_HANDLE_VALUE
5196 && last_dir_find_data
!= -1
5197 && !(is_a_symlink
&& follow_symlinks
)
5198 /* The 2 file-name comparisons below support only ASCII
5199 characters, and will lose (compare not equal) when
5200 the file names include non-ASCII characters that are
5201 the same but for the case. However, doing this
5202 properly involves: (a) converting both file names to
5203 UTF-16, (b) lower-casing both names using CharLowerW,
5204 and (c) comparing the results; this would be quite a
5205 bit slower, whereas Plan B is for users who want
5206 lightweight albeit inaccurate version of 'stat'. */
5207 && c_strncasecmp (save_name
, dir_pathname
, len
) == 0
5208 && IS_DIRECTORY_SEP (name
[len
])
5209 && xstrcasecmp (name
+ len
+ 1, dir_static
.d_name
) == 0)
5211 have_wfd
= last_dir_find_data
;
5212 /* This was the last entry returned by readdir. */
5213 if (last_dir_find_data
== DIR_FIND_DATA_W
)
5214 wfd_w
= dir_find_data_w
;
5216 wfd_a
= dir_find_data_a
;
5220 logon_network_drive (name
);
5222 if (w32_unicode_filenames
)
5224 filename_to_utf16 (name
, name_w
);
5225 fh
= FindFirstFileW (name_w
, &wfd_w
);
5226 have_wfd
= DIR_FIND_DATA_W
;
5230 filename_to_ansi (name
, name_a
);
5231 /* If NAME includes characters not representable by
5232 the current ANSI codepage, filename_to_ansi
5233 usually replaces them with a '?'. We don't want
5234 to let FindFirstFileA interpret those as wildcards,
5235 and "succeed", returning us data from some random
5236 file in the same directory. */
5237 if (_mbspbrk (name_a
, "?"))
5238 fh
= INVALID_HANDLE_VALUE
;
5240 fh
= FindFirstFileA (name_a
, &wfd_a
);
5241 have_wfd
= DIR_FIND_DATA_A
;
5243 if (fh
== INVALID_HANDLE_VALUE
)
5250 /* Note: if NAME is a symlink, the information we get from
5251 FindFirstFile is for the symlink, not its target. */
5252 if (have_wfd
== DIR_FIND_DATA_W
)
5254 fattrs
= wfd_w
.dwFileAttributes
;
5255 ctime
= wfd_w
.ftCreationTime
;
5256 atime
= wfd_w
.ftLastAccessTime
;
5257 wtime
= wfd_w
.ftLastWriteTime
;
5258 fs_high
= wfd_w
.nFileSizeHigh
;
5259 fs_low
= wfd_w
.nFileSizeLow
;
5263 fattrs
= wfd_a
.dwFileAttributes
;
5264 ctime
= wfd_a
.ftCreationTime
;
5265 atime
= wfd_a
.ftLastAccessTime
;
5266 wtime
= wfd_a
.ftLastWriteTime
;
5267 fs_high
= wfd_a
.nFileSizeHigh
;
5268 fs_low
= wfd_a
.nFileSizeLow
;
5272 serialnum
= volume_info
.serialnum
;
5274 if (is_a_symlink
&& !follow_symlinks
)
5275 buf
->st_mode
= S_IFLNK
;
5276 else if (fattrs
& FILE_ATTRIBUTE_DIRECTORY
)
5277 buf
->st_mode
= S_IFDIR
;
5279 buf
->st_mode
= S_IFREG
;
5281 get_file_owner_and_group (NULL
, buf
);
5284 buf
->st_ino
= fake_inode
;
5286 buf
->st_dev
= serialnum
;
5287 buf
->st_rdev
= serialnum
;
5289 buf
->st_size
= fs_high
;
5290 buf
->st_size
<<= 32;
5291 buf
->st_size
+= fs_low
;
5292 buf
->st_nlink
= nlinks
;
5294 /* Convert timestamps to Unix format. */
5295 buf
->st_mtime
= convert_time (wtime
);
5296 buf
->st_atime
= convert_time (atime
);
5297 if (buf
->st_atime
== 0) buf
->st_atime
= buf
->st_mtime
;
5298 buf
->st_ctime
= convert_time (ctime
);
5299 if (buf
->st_ctime
== 0) buf
->st_ctime
= buf
->st_mtime
;
5301 /* determine rwx permissions */
5302 if (is_a_symlink
&& !follow_symlinks
)
5303 permission
= S_IREAD
| S_IWRITE
| S_IEXEC
; /* Posix expectations */
5306 if (fattrs
& FILE_ATTRIBUTE_READONLY
)
5307 permission
= S_IREAD
;
5309 permission
= S_IREAD
| S_IWRITE
;
5311 if (fattrs
& FILE_ATTRIBUTE_DIRECTORY
)
5312 permission
|= S_IEXEC
;
5313 else if (is_exec (name
))
5314 permission
|= S_IEXEC
;
5317 buf
->st_mode
|= permission
| (permission
>> 3) | (permission
>> 6);
5323 stat (const char * path
, struct stat
* buf
)
5325 return stat_worker (path
, buf
, 1);
5329 lstat (const char * path
, struct stat
* buf
)
5331 return stat_worker (path
, buf
, 0);
5335 fstatat (int fd
, char const *name
, struct stat
*st
, int flags
)
5337 /* Rely on a hack: an open directory is modeled as file descriptor 0.
5338 This is good enough for the current usage in Emacs, but is fragile.
5340 FIXME: Add proper support for fdopendir, fstatat, readlinkat.
5341 Gnulib does this and can serve as a model. */
5342 char fullname
[MAX_UTF8_PATH
];
5346 char lastc
= dir_pathname
[strlen (dir_pathname
) - 1];
5348 if (_snprintf (fullname
, sizeof fullname
, "%s%s%s",
5349 dir_pathname
, IS_DIRECTORY_SEP (lastc
) ? "" : "/", name
)
5352 errno
= ENAMETOOLONG
;
5358 return stat_worker (name
, st
, ! (flags
& AT_SYMLINK_NOFOLLOW
));
5361 /* Provide fstat and utime as well as stat for consistent handling of
5364 fstat (int desc
, struct stat
* buf
)
5366 HANDLE fh
= (HANDLE
) _get_osfhandle (desc
);
5367 BY_HANDLE_FILE_INFORMATION info
;
5368 unsigned __int64 fake_inode
;
5371 switch (GetFileType (fh
) & ~FILE_TYPE_REMOTE
)
5373 case FILE_TYPE_DISK
:
5374 buf
->st_mode
= S_IFREG
;
5375 if (!GetFileInformationByHandle (fh
, &info
))
5381 case FILE_TYPE_PIPE
:
5382 buf
->st_mode
= S_IFIFO
;
5384 case FILE_TYPE_CHAR
:
5385 case FILE_TYPE_UNKNOWN
:
5387 buf
->st_mode
= S_IFCHR
;
5389 memset (&info
, 0, sizeof (info
));
5390 info
.dwFileAttributes
= 0;
5391 info
.ftCreationTime
= utc_base_ft
;
5392 info
.ftLastAccessTime
= utc_base_ft
;
5393 info
.ftLastWriteTime
= utc_base_ft
;
5396 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
5397 buf
->st_mode
= S_IFDIR
;
5399 buf
->st_nlink
= info
.nNumberOfLinks
;
5400 /* Might as well use file index to fake inode values, but this
5401 is not guaranteed to be unique unless we keep a handle open
5402 all the time (even then there are situations where it is
5403 not unique). Reputedly, there are at most 48 bits of info
5404 (on NTFS, presumably less on FAT). */
5405 fake_inode
= info
.nFileIndexHigh
;
5407 fake_inode
+= info
.nFileIndexLow
;
5409 /* MSVC defines _ino_t to be short; other libc's might not. */
5410 if (sizeof (buf
->st_ino
) == 2)
5411 buf
->st_ino
= fake_inode
^ (fake_inode
>> 16);
5413 buf
->st_ino
= fake_inode
;
5415 /* If the caller so requested, get the true file owner and group.
5416 Otherwise, consider the file to belong to the current user. */
5417 if (!w32_stat_get_owner_group
|| is_windows_9x () == TRUE
)
5418 get_file_owner_and_group (NULL
, buf
);
5421 PSECURITY_DESCRIPTOR psd
= NULL
;
5423 psd
= get_file_security_desc_by_handle (fh
);
5426 get_file_owner_and_group (psd
, buf
);
5430 get_file_owner_and_group (NULL
, buf
);
5433 buf
->st_dev
= info
.dwVolumeSerialNumber
;
5434 buf
->st_rdev
= info
.dwVolumeSerialNumber
;
5436 buf
->st_size
= info
.nFileSizeHigh
;
5437 buf
->st_size
<<= 32;
5438 buf
->st_size
+= info
.nFileSizeLow
;
5440 /* Convert timestamps to Unix format. */
5441 buf
->st_mtime
= convert_time (info
.ftLastWriteTime
);
5442 buf
->st_atime
= convert_time (info
.ftLastAccessTime
);
5443 if (buf
->st_atime
== 0) buf
->st_atime
= buf
->st_mtime
;
5444 buf
->st_ctime
= convert_time (info
.ftCreationTime
);
5445 if (buf
->st_ctime
== 0) buf
->st_ctime
= buf
->st_mtime
;
5447 /* determine rwx permissions */
5448 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
)
5449 permission
= S_IREAD
;
5451 permission
= S_IREAD
| S_IWRITE
;
5453 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
5454 permission
|= S_IEXEC
;
5457 #if 0 /* no way of knowing the filename */
5458 char * p
= strrchr (name
, '.');
5460 (xstrcasecmp (p
, ".exe") == 0 ||
5461 xstrcasecmp (p
, ".com") == 0 ||
5462 xstrcasecmp (p
, ".bat") == 0 ||
5463 xstrcasecmp (p
, ".cmd") == 0))
5464 permission
|= S_IEXEC
;
5468 buf
->st_mode
|= permission
| (permission
>> 3) | (permission
>> 6);
5473 /* A version of 'utime' which handles directories as well as
5477 utime (const char *name
, struct utimbuf
*times
)
5479 struct utimbuf deftime
;
5486 deftime
.modtime
= deftime
.actime
= time (NULL
);
5490 if (w32_unicode_filenames
)
5492 wchar_t name_utf16
[MAX_PATH
];
5494 if (filename_to_utf16 (name
, name_utf16
) != 0)
5495 return -1; /* errno set by filename_to_utf16 */
5497 /* Need write access to set times. */
5498 fh
= CreateFileW (name_utf16
, FILE_WRITE_ATTRIBUTES
,
5499 /* If NAME specifies a directory, FILE_SHARE_DELETE
5500 allows other processes to delete files inside it,
5501 while we have the directory open. */
5502 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
5503 0, OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
5507 char name_ansi
[MAX_PATH
];
5509 if (filename_to_ansi (name
, name_ansi
) != 0)
5510 return -1; /* errno set by filename_to_ansi */
5512 fh
= CreateFileA (name_ansi
, FILE_WRITE_ATTRIBUTES
,
5513 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
5514 0, OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
5516 if (fh
!= INVALID_HANDLE_VALUE
)
5518 convert_from_time_t (times
->actime
, &atime
);
5519 convert_from_time_t (times
->modtime
, &mtime
);
5520 if (!SetFileTime (fh
, NULL
, &atime
, &mtime
))
5530 DWORD err
= GetLastError ();
5534 case ERROR_FILE_NOT_FOUND
:
5535 case ERROR_PATH_NOT_FOUND
:
5536 case ERROR_INVALID_DRIVE
:
5537 case ERROR_BAD_NETPATH
:
5538 case ERROR_DEV_NOT_EXIST
:
5539 /* ERROR_INVALID_NAME is the error CreateFile sets when the
5540 file name includes ?s, i.e. translation to ANSI failed. */
5541 case ERROR_INVALID_NAME
:
5544 case ERROR_TOO_MANY_OPEN_FILES
:
5547 case ERROR_ACCESS_DENIED
:
5548 case ERROR_SHARING_VIOLATION
:
5561 sys_umask (int mode
)
5563 static int current_mask
;
5564 int retval
, arg
= 0;
5566 /* The only bit we really support is the write bit. Files are
5567 always readable on MS-Windows, and the execute bit does not exist
5569 /* FIXME: if the GROUP and OTHER bits are reset, we should use ACLs
5570 to prevent access by other users on NTFS. */
5571 if ((mode
& S_IWRITE
) != 0)
5574 retval
= _umask (arg
);
5575 /* Merge into the return value the bits they've set the last time,
5576 which msvcrt.dll ignores and never returns. Emacs insists on its
5577 notion of mask being identical to what we return. */
5578 retval
|= (current_mask
& ~S_IWRITE
);
5579 current_mask
= mode
;
5585 /* Symlink-related functions. */
5586 #ifndef SYMBOLIC_LINK_FLAG_DIRECTORY
5587 #define SYMBOLIC_LINK_FLAG_DIRECTORY 0x1
5591 symlink (char const *filename
, char const *linkname
)
5593 char linkfn
[MAX_UTF8_PATH
], *tgtfn
;
5595 int dir_access
, filename_ends_in_slash
;
5597 /* Diagnostics follows Posix as much as possible. */
5598 if (filename
== NULL
|| linkname
== NULL
)
5608 if (strlen (filename
) > MAX_UTF8_PATH
|| strlen (linkname
) > MAX_UTF8_PATH
)
5610 errno
= ENAMETOOLONG
;
5614 strcpy (linkfn
, map_w32_filename (linkname
, NULL
));
5615 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) == 0)
5621 /* Note: since empty FILENAME was already rejected, we can safely
5622 refer to FILENAME[1]. */
5623 if (!(IS_DIRECTORY_SEP (filename
[0]) || IS_DEVICE_SEP (filename
[1])))
5625 /* Non-absolute FILENAME is understood as being relative to
5626 LINKNAME's directory. We need to prepend that directory to
5627 FILENAME to get correct results from faccessat below, since
5628 otherwise it will interpret FILENAME relative to the
5629 directory where the Emacs process runs. Note that
5630 make-symbolic-link always makes sure LINKNAME is a fully
5631 expanded file name. */
5632 char tem
[MAX_UTF8_PATH
];
5633 char *p
= linkfn
+ strlen (linkfn
);
5635 while (p
> linkfn
&& !IS_ANY_SEP (p
[-1]))
5638 strncpy (tem
, linkfn
, p
- linkfn
);
5639 strcpy (tem
+ (p
- linkfn
), filename
);
5640 dir_access
= faccessat (AT_FDCWD
, tem
, D_OK
, AT_EACCESS
);
5643 dir_access
= faccessat (AT_FDCWD
, filename
, D_OK
, AT_EACCESS
);
5645 /* Since Windows distinguishes between symlinks to directories and
5646 to files, we provide a kludgy feature: if FILENAME doesn't
5647 exist, but ends in a slash, we create a symlink to directory. If
5648 FILENAME exists and is a directory, we always create a symlink to
5650 filename_ends_in_slash
= IS_DIRECTORY_SEP (filename
[strlen (filename
) - 1]);
5651 if (dir_access
== 0 || filename_ends_in_slash
)
5652 flags
= SYMBOLIC_LINK_FLAG_DIRECTORY
;
5654 tgtfn
= (char *)map_w32_filename (filename
, NULL
);
5655 if (filename_ends_in_slash
)
5656 tgtfn
[strlen (tgtfn
) - 1] = '\0';
5659 if (!create_symbolic_link (linkfn
, tgtfn
, flags
))
5661 /* ENOSYS is set by create_symbolic_link, when it detects that
5662 the OS doesn't support the CreateSymbolicLink API. */
5663 if (errno
!= ENOSYS
)
5665 DWORD w32err
= GetLastError ();
5669 /* ERROR_SUCCESS is sometimes returned when LINKFN and
5670 TGTFN point to the same file name, go figure. */
5672 case ERROR_FILE_EXISTS
:
5675 case ERROR_ACCESS_DENIED
:
5678 case ERROR_FILE_NOT_FOUND
:
5679 case ERROR_PATH_NOT_FOUND
:
5680 case ERROR_BAD_NETPATH
:
5681 case ERROR_INVALID_REPARSE_DATA
:
5684 case ERROR_DIRECTORY
:
5687 case ERROR_PRIVILEGE_NOT_HELD
:
5688 case ERROR_NOT_ALL_ASSIGNED
:
5691 case ERROR_DISK_FULL
:
5704 /* A quick inexpensive test of whether FILENAME identifies a file that
5705 is a symlink. Returns non-zero if it is, zero otherwise. FILENAME
5706 must already be in the normalized form returned by
5707 map_w32_filename. If the symlink is to a directory, the
5708 FILE_ATTRIBUTE_DIRECTORY bit will be set in the return value.
5710 Note: for repeated operations on many files, it is best to test
5711 whether the underlying volume actually supports symlinks, by
5712 testing the FILE_SUPPORTS_REPARSE_POINTS bit in volume's flags, and
5713 avoid the call to this function if it doesn't. That's because the
5714 call to GetFileAttributes takes a non-negligible time, especially
5715 on non-local or removable filesystems. See stat_worker for an
5716 example of how to do that. */
5718 is_symlink (const char *filename
)
5721 wchar_t filename_w
[MAX_PATH
];
5722 char filename_a
[MAX_PATH
];
5723 WIN32_FIND_DATAW wfdw
;
5724 WIN32_FIND_DATAA wfda
;
5726 int attrs_mean_symlink
;
5728 if (w32_unicode_filenames
)
5730 filename_to_utf16 (filename
, filename_w
);
5731 attrs
= GetFileAttributesW (filename_w
);
5735 filename_to_ansi (filename
, filename_a
);
5736 attrs
= GetFileAttributesA (filename_a
);
5740 DWORD w32err
= GetLastError ();
5744 case ERROR_BAD_NETPATH
: /* network share, can't be a symlink */
5746 case ERROR_ACCESS_DENIED
:
5749 case ERROR_FILE_NOT_FOUND
:
5750 case ERROR_PATH_NOT_FOUND
:
5757 if ((attrs
& FILE_ATTRIBUTE_REPARSE_POINT
) == 0)
5759 logon_network_drive (filename
);
5760 if (w32_unicode_filenames
)
5762 fh
= FindFirstFileW (filename_w
, &wfdw
);
5763 attrs_mean_symlink
=
5764 (wfdw
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) != 0
5765 && (wfdw
.dwReserved0
& IO_REPARSE_TAG_SYMLINK
) == IO_REPARSE_TAG_SYMLINK
;
5766 if (attrs_mean_symlink
)
5767 attrs_mean_symlink
|= (wfdw
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
);
5769 else if (_mbspbrk (filename_a
, "?"))
5771 /* filename_to_ansi failed to convert the file name. */
5777 fh
= FindFirstFileA (filename_a
, &wfda
);
5778 attrs_mean_symlink
=
5779 (wfda
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) != 0
5780 && (wfda
.dwReserved0
& IO_REPARSE_TAG_SYMLINK
) == IO_REPARSE_TAG_SYMLINK
;
5781 if (attrs_mean_symlink
)
5782 attrs_mean_symlink
|= (wfda
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
);
5784 if (fh
== INVALID_HANDLE_VALUE
)
5787 return attrs_mean_symlink
;
5790 /* If NAME identifies a symbolic link, copy into BUF the file name of
5791 the symlink's target. Copy at most BUF_SIZE bytes, and do NOT
5792 null-terminate the target name, even if it fits. Return the number
5793 of bytes copied, or -1 if NAME is not a symlink or any error was
5794 encountered while resolving it. The file name copied into BUF is
5795 encoded in the current ANSI codepage. */
5797 readlink (const char *name
, char *buf
, size_t buf_size
)
5800 TOKEN_PRIVILEGES privs
;
5801 int restore_privs
= 0;
5804 char resolved
[MAX_UTF8_PATH
];
5817 path
= map_w32_filename (name
, NULL
);
5819 if (strlen (path
) > MAX_UTF8_PATH
)
5821 errno
= ENAMETOOLONG
;
5826 if (is_windows_9x () == TRUE
5827 || (volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) == 0
5828 || !is_symlink (path
))
5831 errno
= EINVAL
; /* not a symlink */
5835 /* Done with simple tests, now we're in for some _real_ work. */
5836 if (enable_privilege (SE_BACKUP_NAME
, TRUE
, &privs
))
5838 /* Implementation note: From here and onward, don't return early,
5839 since that will fail to restore the original set of privileges of
5840 the calling thread. */
5842 retval
= -1; /* not too optimistic, are we? */
5844 /* Note: In the next call to CreateFile, we use zero as the 2nd
5845 argument because, when the symlink is a hidden/system file,
5846 e.g. 'C:\Users\All Users', GENERIC_READ fails with
5847 ERROR_ACCESS_DENIED. Zero seems to work just fine, both for file
5848 and directory symlinks. */
5849 if (w32_unicode_filenames
)
5851 wchar_t path_w
[MAX_PATH
];
5853 filename_to_utf16 (path
, path_w
);
5854 sh
= CreateFileW (path_w
, 0, 0, NULL
, OPEN_EXISTING
,
5855 FILE_FLAG_OPEN_REPARSE_POINT
5856 | FILE_FLAG_BACKUP_SEMANTICS
,
5861 char path_a
[MAX_PATH
];
5863 filename_to_ansi (path
, path_a
);
5864 sh
= CreateFileA (path_a
, 0, 0, NULL
, OPEN_EXISTING
,
5865 FILE_FLAG_OPEN_REPARSE_POINT
5866 | FILE_FLAG_BACKUP_SEMANTICS
,
5869 if (sh
!= INVALID_HANDLE_VALUE
)
5871 BYTE reparse_buf
[MAXIMUM_REPARSE_DATA_BUFFER_SIZE
];
5872 REPARSE_DATA_BUFFER
*reparse_data
= (REPARSE_DATA_BUFFER
*)&reparse_buf
[0];
5875 if (!DeviceIoControl (sh
, FSCTL_GET_REPARSE_POINT
, NULL
, 0,
5876 reparse_buf
, MAXIMUM_REPARSE_DATA_BUFFER_SIZE
,
5879 else if (reparse_data
->ReparseTag
!= IO_REPARSE_TAG_SYMLINK
)
5883 /* Copy the link target name, in wide characters, from
5884 reparse_data, then convert it to multibyte encoding in
5885 the current locale's codepage. */
5889 reparse_data
->SymbolicLinkReparseBuffer
.PrintNameLength
;
5891 reparse_data
->SymbolicLinkReparseBuffer
.PathBuffer
5892 + reparse_data
->SymbolicLinkReparseBuffer
.PrintNameOffset
/sizeof(WCHAR
);
5893 size_t size_to_copy
= buf_size
;
5895 /* According to MSDN, PrintNameLength does not include the
5896 terminating null character. */
5897 lwname
= alloca ((lwname_len
+ 1) * sizeof(WCHAR
));
5898 memcpy (lwname
, lwname_src
, lwname_len
);
5899 lwname
[lwname_len
/sizeof(WCHAR
)] = 0; /* null-terminate */
5900 filename_from_utf16 (lwname
, resolved
);
5901 dostounix_filename (resolved
);
5902 lname_size
= strlen (resolved
) + 1;
5903 if (lname_size
<= buf_size
)
5904 size_to_copy
= lname_size
;
5905 strncpy (buf
, resolved
, size_to_copy
);
5907 retval
= size_to_copy
;
5913 /* CreateFile failed. */
5914 DWORD w32err2
= GetLastError ();
5918 case ERROR_FILE_NOT_FOUND
:
5919 case ERROR_PATH_NOT_FOUND
:
5922 case ERROR_ACCESS_DENIED
:
5923 case ERROR_TOO_MANY_OPEN_FILES
:
5933 restore_privilege (&privs
);
5941 readlinkat (int fd
, char const *name
, char *buffer
,
5944 /* Rely on a hack: an open directory is modeled as file descriptor 0,
5945 as in fstatat. FIXME: Add proper support for readlinkat. */
5946 char fullname
[MAX_UTF8_PATH
];
5950 if (_snprintf (fullname
, sizeof fullname
, "%s/%s", dir_pathname
, name
)
5953 errno
= ENAMETOOLONG
;
5959 return readlink (name
, buffer
, buffer_size
);
5962 /* If FILE is a symlink, return its target (stored in a static
5963 buffer); otherwise return FILE.
5965 This function repeatedly resolves symlinks in the last component of
5966 a chain of symlink file names, as in foo -> bar -> baz -> ...,
5967 until it arrives at a file whose last component is not a symlink,
5968 or some error occurs. It returns the target of the last
5969 successfully resolved symlink in the chain. If it succeeds to
5970 resolve even a single symlink, the value returned is an absolute
5971 file name with backslashes (result of GetFullPathName). By
5972 contrast, if the original FILE is returned, it is unaltered.
5974 Note: This function can set errno even if it succeeds.
5976 Implementation note: we only resolve the last portion ("basename")
5977 of the argument FILE and of each following file in the chain,
5978 disregarding any possible symlinks in its leading directories.
5979 This is because Windows system calls and library functions
5980 transparently resolve symlinks in leading directories and return
5981 correct information, as long as the basename is not a symlink. */
5983 chase_symlinks (const char *file
)
5985 static char target
[MAX_UTF8_PATH
];
5986 char link
[MAX_UTF8_PATH
];
5987 wchar_t target_w
[MAX_PATH
], link_w
[MAX_PATH
];
5988 char target_a
[MAX_PATH
], link_a
[MAX_PATH
];
5989 ssize_t res
, link_len
;
5992 if (is_windows_9x () == TRUE
|| !is_symlink (file
))
5993 return (char *)file
;
5995 if (w32_unicode_filenames
)
5997 wchar_t file_w
[MAX_PATH
];
5999 filename_to_utf16 (file
, file_w
);
6000 if (GetFullPathNameW (file_w
, MAX_PATH
, link_w
, NULL
) == 0)
6001 return (char *)file
;
6002 filename_from_utf16 (link_w
, link
);
6006 char file_a
[MAX_PATH
];
6008 filename_to_ansi (file
, file_a
);
6009 if (GetFullPathNameA (file_a
, MAX_PATH
, link_a
, NULL
) == 0)
6010 return (char *)file
;
6011 filename_from_ansi (link_a
, link
);
6013 link_len
= strlen (link
);
6018 /* Remove trailing slashes, as we want to resolve the last
6019 non-trivial part of the link name. */
6020 while (link_len
> 3 && IS_DIRECTORY_SEP (link
[link_len
-1]))
6021 link
[link_len
--] = '\0';
6023 res
= readlink (link
, target
, MAX_UTF8_PATH
);
6027 if (!(IS_DEVICE_SEP (target
[1])
6028 || (IS_DIRECTORY_SEP (target
[0]) && IS_DIRECTORY_SEP (target
[1]))))
6030 /* Target is relative. Append it to the directory part of
6031 the symlink, then copy the result back to target. */
6032 char *p
= link
+ link_len
;
6034 while (p
> link
&& !IS_ANY_SEP (p
[-1]))
6037 strcpy (target
, link
);
6039 /* Resolve any "." and ".." to get a fully-qualified file name
6041 if (w32_unicode_filenames
)
6043 filename_to_utf16 (target
, target_w
);
6044 link_len
= GetFullPathNameW (target_w
, MAX_PATH
, link_w
, NULL
);
6046 filename_from_utf16 (link_w
, link
);
6050 filename_to_ansi (target
, target_a
);
6051 link_len
= GetFullPathNameA (target_a
, MAX_PATH
, link_a
, NULL
);
6053 filename_from_ansi (link_a
, link
);
6055 link_len
= strlen (link
);
6057 } while (res
> 0 && link_len
> 0 && ++loop_count
<= 100);
6059 if (loop_count
> 100)
6062 if (target
[0] == '\0') /* not a single call to readlink succeeded */
6063 return (char *)file
;
6068 /* Posix ACL emulation. */
6071 acl_valid (acl_t acl
)
6073 return is_valid_security_descriptor ((PSECURITY_DESCRIPTOR
)acl
) ? 0 : -1;
6077 acl_to_text (acl_t acl
, ssize_t
*size
)
6080 SECURITY_INFORMATION flags
=
6081 OWNER_SECURITY_INFORMATION
|
6082 GROUP_SECURITY_INFORMATION
|
6083 DACL_SECURITY_INFORMATION
;
6084 char *retval
= NULL
;
6090 if (convert_sd_to_sddl ((PSECURITY_DESCRIPTOR
)acl
, SDDL_REVISION_1
, flags
, &str_acl
, &local_size
))
6093 /* We don't want to mix heaps, so we duplicate the string in our
6094 heap and free the one allocated by the API. */
6095 retval
= xstrdup (str_acl
);
6098 LocalFree (str_acl
);
6100 else if (errno
!= ENOTSUP
)
6107 acl_from_text (const char *acl_str
)
6109 PSECURITY_DESCRIPTOR psd
, retval
= NULL
;
6115 if (convert_sddl_to_sd (acl_str
, SDDL_REVISION_1
, &psd
, &sd_size
))
6118 retval
= xmalloc (sd_size
);
6119 memcpy (retval
, psd
, sd_size
);
6122 else if (errno
!= ENOTSUP
)
6129 acl_free (void *ptr
)
6136 acl_get_file (const char *fname
, acl_type_t type
)
6138 PSECURITY_DESCRIPTOR psd
= NULL
;
6139 const char *filename
;
6141 if (type
== ACL_TYPE_ACCESS
)
6144 SECURITY_INFORMATION si
=
6145 OWNER_SECURITY_INFORMATION
|
6146 GROUP_SECURITY_INFORMATION
|
6147 DACL_SECURITY_INFORMATION
;
6150 filename
= map_w32_filename (fname
, NULL
);
6151 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) != 0)
6152 fname
= chase_symlinks (filename
);
6157 if (!get_file_security (fname
, si
, psd
, 0, &sd_len
)
6158 && errno
!= ENOTSUP
)
6160 err
= GetLastError ();
6161 if (err
== ERROR_INSUFFICIENT_BUFFER
)
6163 psd
= xmalloc (sd_len
);
6164 if (!get_file_security (fname
, si
, psd
, sd_len
, &sd_len
))
6171 else if (err
== ERROR_FILE_NOT_FOUND
6172 || err
== ERROR_PATH_NOT_FOUND
6173 /* ERROR_INVALID_NAME is what we get if
6174 w32-unicode-filenames is nil and the file cannot
6175 be encoded in the current ANSI codepage. */
6176 || err
== ERROR_INVALID_NAME
)
6184 else if (type
!= ACL_TYPE_DEFAULT
)
6191 acl_set_file (const char *fname
, acl_type_t type
, acl_t acl
)
6193 TOKEN_PRIVILEGES old1
, old2
;
6195 int st
= 0, retval
= -1;
6196 SECURITY_INFORMATION flags
= 0;
6197 PSID psidOwner
, psidGroup
;
6202 const char *filename
;
6204 if (acl_valid (acl
) != 0
6205 || (type
!= ACL_TYPE_DEFAULT
&& type
!= ACL_TYPE_ACCESS
))
6211 if (type
== ACL_TYPE_DEFAULT
)
6217 filename
= map_w32_filename (fname
, NULL
);
6218 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) != 0)
6219 fname
= chase_symlinks (filename
);
6223 if (get_security_descriptor_owner ((PSECURITY_DESCRIPTOR
)acl
, &psidOwner
,
6226 flags
|= OWNER_SECURITY_INFORMATION
;
6227 if (get_security_descriptor_group ((PSECURITY_DESCRIPTOR
)acl
, &psidGroup
,
6230 flags
|= GROUP_SECURITY_INFORMATION
;
6231 if (get_security_descriptor_dacl ((PSECURITY_DESCRIPTOR
)acl
, &dacl_present
,
6234 flags
|= DACL_SECURITY_INFORMATION
;
6238 /* According to KB-245153, setting the owner will succeed if either:
6239 (1) the caller is the user who will be the new owner, and has the
6240 SE_TAKE_OWNERSHIP privilege, or
6241 (2) the caller has the SE_RESTORE privilege, in which case she can
6242 set any valid user or group as the owner
6244 We request below both SE_TAKE_OWNERSHIP and SE_RESTORE
6245 privileges, and disregard any failures in obtaining them. If
6246 these privileges cannot be obtained, and do not already exist in
6247 the calling thread's security token, this function could fail
6249 if (enable_privilege (SE_TAKE_OWNERSHIP_NAME
, TRUE
, &old1
))
6251 if (enable_privilege (SE_RESTORE_NAME
, TRUE
, &old2
))
6256 /* SetFileSecurity is deprecated by MS, and sometimes fails when
6257 DACL inheritance is involved, but it seems to preserve ownership
6258 better than SetNamedSecurityInfo, which is important e.g., in
6260 if (!set_file_security (fname
, flags
, (PSECURITY_DESCRIPTOR
)acl
))
6262 err
= GetLastError ();
6264 if (errno
!= ENOTSUP
)
6265 err
= set_named_security_info (fname
, SE_FILE_OBJECT
, flags
,
6266 psidOwner
, psidGroup
, pacl
, NULL
);
6269 err
= ERROR_SUCCESS
;
6270 if (err
!= ERROR_SUCCESS
)
6272 if (errno
== ENOTSUP
)
6274 else if (err
== ERROR_INVALID_OWNER
6275 || err
== ERROR_NOT_ALL_ASSIGNED
6276 || err
== ERROR_ACCESS_DENIED
)
6278 /* Maybe the requested ACL and the one the file already has
6279 are identical, in which case we can silently ignore the
6280 failure. (And no, Windows doesn't.) */
6281 acl_t current_acl
= acl_get_file (fname
, ACL_TYPE_ACCESS
);
6286 char *acl_from
= acl_to_text (current_acl
, NULL
);
6287 char *acl_to
= acl_to_text (acl
, NULL
);
6289 if (acl_from
&& acl_to
&& xstrcasecmp (acl_from
, acl_to
) == 0)
6295 acl_free (acl_from
);
6298 acl_free (current_acl
);
6301 else if (err
== ERROR_FILE_NOT_FOUND
6302 || err
== ERROR_PATH_NOT_FOUND
6303 /* ERROR_INVALID_NAME is what we get if
6304 w32-unicode-filenames is nil and the file cannot be
6305 encoded in the current ANSI codepage. */
6306 || err
== ERROR_INVALID_NAME
)
6320 restore_privilege (&old2
);
6321 restore_privilege (&old1
);
6329 /* MS-Windows version of careadlinkat (cf. ../lib/careadlinkat.c). We
6330 have a fixed max size for file names, so we don't need the kind of
6331 alloc/malloc/realloc dance the gnulib version does. We also don't
6332 support FD-relative symlinks. */
6334 careadlinkat (int fd
, char const *filename
,
6335 char *buffer
, size_t buffer_size
,
6336 struct allocator
const *alloc
,
6337 ssize_t (*preadlinkat
) (int, char const *, char *, size_t))
6339 char linkname
[MAX_UTF8_PATH
];
6342 link_size
= preadlinkat (fd
, filename
, linkname
, sizeof(linkname
));
6346 char *retval
= buffer
;
6348 linkname
[link_size
++] = '\0';
6349 if (link_size
> buffer_size
)
6350 retval
= (char *)(alloc
? alloc
->allocate
: xmalloc
) (link_size
);
6352 memcpy (retval
, linkname
, link_size
);
6360 w32_copy_file (const char *from
, const char *to
,
6361 int keep_time
, int preserve_ownership
, int copy_acls
)
6365 wchar_t from_w
[MAX_PATH
], to_w
[MAX_PATH
];
6366 char from_a
[MAX_PATH
], to_a
[MAX_PATH
];
6368 /* We ignore preserve_ownership for now. */
6369 preserve_ownership
= preserve_ownership
;
6373 acl
= acl_get_file (from
, ACL_TYPE_ACCESS
);
6374 if (acl
== NULL
&& acl_errno_valid (errno
))
6377 if (w32_unicode_filenames
)
6379 filename_to_utf16 (from
, from_w
);
6380 filename_to_utf16 (to
, to_w
);
6381 copy_result
= CopyFileW (from_w
, to_w
, FALSE
);
6385 filename_to_ansi (from
, from_a
);
6386 filename_to_ansi (to
, to_a
);
6387 copy_result
= CopyFileA (from_a
, to_a
, FALSE
);
6391 /* CopyFile doesn't set errno when it fails. By far the most
6392 "popular" reason is that the target is read-only. */
6393 DWORD err
= GetLastError ();
6397 case ERROR_FILE_NOT_FOUND
:
6400 case ERROR_ACCESS_DENIED
:
6403 case ERROR_ENCRYPTION_FAILED
:
6415 /* CopyFile retains the timestamp by default. However, see
6416 "Community Additions" for CopyFile: it sounds like that is not
6417 entirely true. Testing on Windows XP confirms that modified time
6418 is copied, but creation and last-access times are not.
6420 else if (!keep_time
)
6422 struct timespec now
;
6425 if (w32_unicode_filenames
)
6427 /* Ensure file is writable while its times are set. */
6428 attributes
= GetFileAttributesW (to_w
);
6429 SetFileAttributesW (to_w
, attributes
& ~FILE_ATTRIBUTE_READONLY
);
6430 now
= current_timespec ();
6431 if (set_file_times (-1, to
, now
, now
))
6433 /* Restore original attributes. */
6434 SetFileAttributesW (to_w
, attributes
);
6439 /* Restore original attributes. */
6440 SetFileAttributesW (to_w
, attributes
);
6444 attributes
= GetFileAttributesA (to_a
);
6445 SetFileAttributesA (to_a
, attributes
& ~FILE_ATTRIBUTE_READONLY
);
6446 now
= current_timespec ();
6447 if (set_file_times (-1, to
, now
, now
))
6449 SetFileAttributesA (to_a
, attributes
);
6454 SetFileAttributesA (to_a
, attributes
);
6460 acl_set_file (to
, ACL_TYPE_ACCESS
, acl
) != 0;
6462 if (fail
&& acl_errno_valid (errno
))
6470 /* Support for browsing other processes and their attributes. See
6471 process.c for the Lisp bindings. */
6473 /* Helper wrapper functions. */
6475 static HANDLE WINAPI
6476 create_toolhelp32_snapshot (DWORD Flags
, DWORD Ignored
)
6478 static CreateToolhelp32Snapshot_Proc s_pfn_Create_Toolhelp32_Snapshot
= NULL
;
6480 if (g_b_init_create_toolhelp32_snapshot
== 0)
6482 g_b_init_create_toolhelp32_snapshot
= 1;
6483 s_pfn_Create_Toolhelp32_Snapshot
= (CreateToolhelp32Snapshot_Proc
)
6484 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6485 "CreateToolhelp32Snapshot");
6487 if (s_pfn_Create_Toolhelp32_Snapshot
== NULL
)
6489 return INVALID_HANDLE_VALUE
;
6491 return (s_pfn_Create_Toolhelp32_Snapshot (Flags
, Ignored
));
6495 process32_first (HANDLE hSnapshot
, LPPROCESSENTRY32 lppe
)
6497 static Process32First_Proc s_pfn_Process32_First
= NULL
;
6499 if (g_b_init_process32_first
== 0)
6501 g_b_init_process32_first
= 1;
6502 s_pfn_Process32_First
= (Process32First_Proc
)
6503 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6506 if (s_pfn_Process32_First
== NULL
)
6510 return (s_pfn_Process32_First (hSnapshot
, lppe
));
6514 process32_next (HANDLE hSnapshot
, LPPROCESSENTRY32 lppe
)
6516 static Process32Next_Proc s_pfn_Process32_Next
= NULL
;
6518 if (g_b_init_process32_next
== 0)
6520 g_b_init_process32_next
= 1;
6521 s_pfn_Process32_Next
= (Process32Next_Proc
)
6522 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6525 if (s_pfn_Process32_Next
== NULL
)
6529 return (s_pfn_Process32_Next (hSnapshot
, lppe
));
6533 open_thread_token (HANDLE ThreadHandle
,
6534 DWORD DesiredAccess
,
6536 PHANDLE TokenHandle
)
6538 static OpenThreadToken_Proc s_pfn_Open_Thread_Token
= NULL
;
6539 HMODULE hm_advapi32
= NULL
;
6540 if (is_windows_9x () == TRUE
)
6542 SetLastError (ERROR_NOT_SUPPORTED
);
6545 if (g_b_init_open_thread_token
== 0)
6547 g_b_init_open_thread_token
= 1;
6548 hm_advapi32
= LoadLibrary ("Advapi32.dll");
6549 s_pfn_Open_Thread_Token
=
6550 (OpenThreadToken_Proc
) GetProcAddress (hm_advapi32
, "OpenThreadToken");
6552 if (s_pfn_Open_Thread_Token
== NULL
)
6554 SetLastError (ERROR_NOT_SUPPORTED
);
6558 s_pfn_Open_Thread_Token (
6567 impersonate_self (SECURITY_IMPERSONATION_LEVEL ImpersonationLevel
)
6569 static ImpersonateSelf_Proc s_pfn_Impersonate_Self
= NULL
;
6570 HMODULE hm_advapi32
= NULL
;
6571 if (is_windows_9x () == TRUE
)
6575 if (g_b_init_impersonate_self
== 0)
6577 g_b_init_impersonate_self
= 1;
6578 hm_advapi32
= LoadLibrary ("Advapi32.dll");
6579 s_pfn_Impersonate_Self
=
6580 (ImpersonateSelf_Proc
) GetProcAddress (hm_advapi32
, "ImpersonateSelf");
6582 if (s_pfn_Impersonate_Self
== NULL
)
6586 return s_pfn_Impersonate_Self (ImpersonationLevel
);
6590 revert_to_self (void)
6592 static RevertToSelf_Proc s_pfn_Revert_To_Self
= NULL
;
6593 HMODULE hm_advapi32
= NULL
;
6594 if (is_windows_9x () == TRUE
)
6598 if (g_b_init_revert_to_self
== 0)
6600 g_b_init_revert_to_self
= 1;
6601 hm_advapi32
= LoadLibrary ("Advapi32.dll");
6602 s_pfn_Revert_To_Self
=
6603 (RevertToSelf_Proc
) GetProcAddress (hm_advapi32
, "RevertToSelf");
6605 if (s_pfn_Revert_To_Self
== NULL
)
6609 return s_pfn_Revert_To_Self ();
6613 get_process_memory_info (HANDLE h_proc
,
6614 PPROCESS_MEMORY_COUNTERS mem_counters
,
6617 static GetProcessMemoryInfo_Proc s_pfn_Get_Process_Memory_Info
= NULL
;
6618 HMODULE hm_psapi
= NULL
;
6619 if (is_windows_9x () == TRUE
)
6623 if (g_b_init_get_process_memory_info
== 0)
6625 g_b_init_get_process_memory_info
= 1;
6626 hm_psapi
= LoadLibrary ("Psapi.dll");
6628 s_pfn_Get_Process_Memory_Info
= (GetProcessMemoryInfo_Proc
)
6629 GetProcAddress (hm_psapi
, "GetProcessMemoryInfo");
6631 if (s_pfn_Get_Process_Memory_Info
== NULL
)
6635 return s_pfn_Get_Process_Memory_Info (h_proc
, mem_counters
, bufsize
);
6639 get_process_working_set_size (HANDLE h_proc
,
6643 static GetProcessWorkingSetSize_Proc
6644 s_pfn_Get_Process_Working_Set_Size
= NULL
;
6646 if (is_windows_9x () == TRUE
)
6650 if (g_b_init_get_process_working_set_size
== 0)
6652 g_b_init_get_process_working_set_size
= 1;
6653 s_pfn_Get_Process_Working_Set_Size
= (GetProcessWorkingSetSize_Proc
)
6654 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6655 "GetProcessWorkingSetSize");
6657 if (s_pfn_Get_Process_Working_Set_Size
== NULL
)
6661 return s_pfn_Get_Process_Working_Set_Size (h_proc
, minrss
, maxrss
);
6665 global_memory_status (MEMORYSTATUS
*buf
)
6667 static GlobalMemoryStatus_Proc s_pfn_Global_Memory_Status
= NULL
;
6669 if (is_windows_9x () == TRUE
)
6673 if (g_b_init_global_memory_status
== 0)
6675 g_b_init_global_memory_status
= 1;
6676 s_pfn_Global_Memory_Status
= (GlobalMemoryStatus_Proc
)
6677 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6678 "GlobalMemoryStatus");
6680 if (s_pfn_Global_Memory_Status
== NULL
)
6684 return s_pfn_Global_Memory_Status (buf
);
6688 global_memory_status_ex (MEMORY_STATUS_EX
*buf
)
6690 static GlobalMemoryStatusEx_Proc s_pfn_Global_Memory_Status_Ex
= NULL
;
6692 if (is_windows_9x () == TRUE
)
6696 if (g_b_init_global_memory_status_ex
== 0)
6698 g_b_init_global_memory_status_ex
= 1;
6699 s_pfn_Global_Memory_Status_Ex
= (GlobalMemoryStatusEx_Proc
)
6700 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6701 "GlobalMemoryStatusEx");
6703 if (s_pfn_Global_Memory_Status_Ex
== NULL
)
6707 return s_pfn_Global_Memory_Status_Ex (buf
);
6711 list_system_processes (void)
6713 Lisp_Object proclist
= Qnil
;
6716 h_snapshot
= create_toolhelp32_snapshot (TH32CS_SNAPPROCESS
, 0);
6718 if (h_snapshot
!= INVALID_HANDLE_VALUE
)
6720 PROCESSENTRY32 proc_entry
;
6724 proc_entry
.dwSize
= sizeof (PROCESSENTRY32
);
6725 for (res
= process32_first (h_snapshot
, &proc_entry
); res
;
6726 res
= process32_next (h_snapshot
, &proc_entry
))
6728 proc_id
= proc_entry
.th32ProcessID
;
6729 proclist
= Fcons (make_fixnum_or_float (proc_id
), proclist
);
6732 CloseHandle (h_snapshot
);
6733 proclist
= Fnreverse (proclist
);
6740 enable_privilege (LPCTSTR priv_name
, BOOL enable_p
, TOKEN_PRIVILEGES
*old_priv
)
6742 TOKEN_PRIVILEGES priv
;
6743 DWORD priv_size
= sizeof (priv
);
6744 DWORD opriv_size
= sizeof (*old_priv
);
6745 HANDLE h_token
= NULL
;
6746 HANDLE h_thread
= GetCurrentThread ();
6750 res
= open_thread_token (h_thread
,
6751 TOKEN_QUERY
| TOKEN_ADJUST_PRIVILEGES
,
6753 if (!res
&& GetLastError () == ERROR_NO_TOKEN
)
6755 if (impersonate_self (SecurityImpersonation
))
6756 res
= open_thread_token (h_thread
,
6757 TOKEN_QUERY
| TOKEN_ADJUST_PRIVILEGES
,
6762 priv
.PrivilegeCount
= 1;
6763 priv
.Privileges
[0].Attributes
= enable_p
? SE_PRIVILEGE_ENABLED
: 0;
6764 LookupPrivilegeValue (NULL
, priv_name
, &priv
.Privileges
[0].Luid
);
6765 if (AdjustTokenPrivileges (h_token
, FALSE
, &priv
, priv_size
,
6766 old_priv
, &opriv_size
)
6767 && GetLastError () != ERROR_NOT_ALL_ASSIGNED
)
6771 CloseHandle (h_token
);
6777 restore_privilege (TOKEN_PRIVILEGES
*priv
)
6779 DWORD priv_size
= sizeof (*priv
);
6780 HANDLE h_token
= NULL
;
6783 if (open_thread_token (GetCurrentThread (),
6784 TOKEN_QUERY
| TOKEN_ADJUST_PRIVILEGES
,
6787 if (AdjustTokenPrivileges (h_token
, FALSE
, priv
, priv_size
, NULL
, NULL
)
6788 && GetLastError () != ERROR_NOT_ALL_ASSIGNED
)
6792 CloseHandle (h_token
);
6798 ltime (ULONGLONG time_100ns
)
6800 ULONGLONG time_sec
= time_100ns
/ 10000000;
6801 int subsec
= time_100ns
% 10000000;
6802 return list4i (time_sec
>> 16, time_sec
& 0xffff,
6803 subsec
/ 10, subsec
% 10 * 100000);
6806 #define U64_TO_LISP_TIME(time) ltime (time)
6809 process_times (HANDLE h_proc
, Lisp_Object
*ctime
, Lisp_Object
*etime
,
6810 Lisp_Object
*stime
, Lisp_Object
*utime
, Lisp_Object
*ttime
,
6813 FILETIME ft_creation
, ft_exit
, ft_kernel
, ft_user
, ft_current
;
6814 ULONGLONG tem1
, tem2
, tem3
, tem
;
6817 || !get_process_times_fn
6818 || !(*get_process_times_fn
) (h_proc
, &ft_creation
, &ft_exit
,
6819 &ft_kernel
, &ft_user
))
6822 GetSystemTimeAsFileTime (&ft_current
);
6824 FILETIME_TO_U64 (tem1
, ft_kernel
);
6825 *stime
= U64_TO_LISP_TIME (tem1
);
6827 FILETIME_TO_U64 (tem2
, ft_user
);
6828 *utime
= U64_TO_LISP_TIME (tem2
);
6831 *ttime
= U64_TO_LISP_TIME (tem3
);
6833 FILETIME_TO_U64 (tem
, ft_creation
);
6834 /* Process no 4 (System) returns zero creation time. */
6837 *ctime
= U64_TO_LISP_TIME (tem
);
6841 FILETIME_TO_U64 (tem3
, ft_current
);
6842 tem
= (tem3
- utc_base
) - tem
;
6844 *etime
= U64_TO_LISP_TIME (tem
);
6848 *pcpu
= 100.0 * (tem1
+ tem2
) / tem
;
6859 system_process_attributes (Lisp_Object pid
)
6861 Lisp_Object attrs
= Qnil
;
6862 Lisp_Object cmd_str
, decoded_cmd
, tem
;
6863 HANDLE h_snapshot
, h_proc
;
6866 char uname
[UNLEN
+1], gname
[GNLEN
+1], domain
[1025];
6867 DWORD ulength
= sizeof (uname
), dlength
= sizeof (domain
), needed
;
6868 DWORD glength
= sizeof (gname
);
6869 HANDLE token
= NULL
;
6870 SID_NAME_USE user_type
;
6871 unsigned char *buf
= NULL
;
6873 TOKEN_USER user_token
;
6874 TOKEN_PRIMARY_GROUP group_token
;
6877 PROCESS_MEMORY_COUNTERS mem
;
6878 PROCESS_MEMORY_COUNTERS_EX mem_ex
;
6879 SIZE_T minrss
, maxrss
;
6881 MEMORY_STATUS_EX memstex
;
6882 double totphys
= 0.0;
6883 Lisp_Object ctime
, stime
, utime
, etime
, ttime
;
6885 BOOL result
= FALSE
;
6887 CHECK_NUMBER_OR_FLOAT (pid
);
6888 proc_id
= FLOATP (pid
) ? XFLOAT_DATA (pid
) : XINT (pid
);
6890 h_snapshot
= create_toolhelp32_snapshot (TH32CS_SNAPPROCESS
, 0);
6892 if (h_snapshot
!= INVALID_HANDLE_VALUE
)
6897 pe
.dwSize
= sizeof (PROCESSENTRY32
);
6898 for (res
= process32_first (h_snapshot
, &pe
); res
;
6899 res
= process32_next (h_snapshot
, &pe
))
6901 if (proc_id
== pe
.th32ProcessID
)
6904 decoded_cmd
= build_string ("Idle");
6907 /* Decode the command name from locale-specific
6909 cmd_str
= build_unibyte_string (pe
.szExeFile
);
6912 code_convert_string_norecord (cmd_str
,
6913 Vlocale_coding_system
, 0);
6915 attrs
= Fcons (Fcons (Qcomm
, decoded_cmd
), attrs
);
6916 attrs
= Fcons (Fcons (Qppid
,
6917 make_fixnum_or_float (pe
.th32ParentProcessID
)),
6919 attrs
= Fcons (Fcons (Qpri
, make_number (pe
.pcPriClassBase
)),
6921 attrs
= Fcons (Fcons (Qthcount
,
6922 make_fixnum_or_float (pe
.cntThreads
)),
6929 CloseHandle (h_snapshot
);
6935 h_proc
= OpenProcess (PROCESS_QUERY_INFORMATION
| PROCESS_VM_READ
,
6937 /* If we were denied a handle to the process, try again after
6938 enabling the SeDebugPrivilege in our process. */
6941 TOKEN_PRIVILEGES priv_current
;
6943 if (enable_privilege (SE_DEBUG_NAME
, TRUE
, &priv_current
))
6945 h_proc
= OpenProcess (PROCESS_QUERY_INFORMATION
| PROCESS_VM_READ
,
6947 restore_privilege (&priv_current
);
6953 result
= open_process_token (h_proc
, TOKEN_QUERY
, &token
);
6956 result
= get_token_information (token
, TokenUser
, NULL
, 0, &blen
);
6957 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
6959 buf
= xmalloc (blen
);
6960 result
= get_token_information (token
, TokenUser
,
6961 (LPVOID
)buf
, blen
, &needed
);
6964 memcpy (&user_token
, buf
, sizeof (user_token
));
6965 if (!w32_cached_id (user_token
.User
.Sid
, &euid
, uname
))
6967 euid
= get_rid (user_token
.User
.Sid
);
6968 result
= lookup_account_sid (NULL
, user_token
.User
.Sid
,
6973 w32_add_to_cache (user_token
.User
.Sid
, euid
, uname
);
6976 strcpy (uname
, "unknown");
6980 ulength
= strlen (uname
);
6986 /* Determine a reasonable euid and gid values. */
6987 if (xstrcasecmp ("administrator", uname
) == 0)
6989 euid
= 500; /* well-known Administrator uid */
6990 egid
= 513; /* well-known None gid */
6994 /* Get group id and name. */
6995 result
= get_token_information (token
, TokenPrimaryGroup
,
6996 (LPVOID
)buf
, blen
, &needed
);
6997 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
6999 buf
= xrealloc (buf
, blen
= needed
);
7000 result
= get_token_information (token
, TokenPrimaryGroup
,
7001 (LPVOID
)buf
, blen
, &needed
);
7005 memcpy (&group_token
, buf
, sizeof (group_token
));
7006 if (!w32_cached_id (group_token
.PrimaryGroup
, &egid
, gname
))
7008 egid
= get_rid (group_token
.PrimaryGroup
);
7009 dlength
= sizeof (domain
);
7011 lookup_account_sid (NULL
, group_token
.PrimaryGroup
,
7012 gname
, &glength
, NULL
, &dlength
,
7015 w32_add_to_cache (group_token
.PrimaryGroup
,
7019 strcpy (gname
, "None");
7023 glength
= strlen (gname
);
7031 if (!is_windows_9x ())
7033 /* We couldn't open the process token, presumably because of
7034 insufficient access rights. Assume this process is run
7036 strcpy (uname
, "SYSTEM");
7037 strcpy (gname
, "None");
7038 euid
= 18; /* SYSTEM */
7039 egid
= 513; /* None */
7040 glength
= strlen (gname
);
7041 ulength
= strlen (uname
);
7043 /* If we are running under Windows 9X, where security calls are
7044 not supported, we assume all processes are run by the current
7046 else if (GetUserName (uname
, &ulength
))
7048 if (xstrcasecmp ("administrator", uname
) == 0)
7053 strcpy (gname
, "None");
7054 glength
= strlen (gname
);
7055 ulength
= strlen (uname
);
7061 strcpy (uname
, "administrator");
7062 ulength
= strlen (uname
);
7063 strcpy (gname
, "None");
7064 glength
= strlen (gname
);
7067 CloseHandle (token
);
7070 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (euid
)), attrs
);
7071 tem
= make_unibyte_string (uname
, ulength
);
7072 attrs
= Fcons (Fcons (Quser
,
7073 code_convert_string_norecord (tem
, Vlocale_coding_system
, 0)),
7075 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (egid
)), attrs
);
7076 tem
= make_unibyte_string (gname
, glength
);
7077 attrs
= Fcons (Fcons (Qgroup
,
7078 code_convert_string_norecord (tem
, Vlocale_coding_system
, 0)),
7081 if (global_memory_status_ex (&memstex
))
7082 #if __GNUC__ || (defined (_MSC_VER) && _MSC_VER >= 1300)
7083 totphys
= memstex
.ullTotalPhys
/ 1024.0;
7085 /* Visual Studio 6 cannot convert an unsigned __int64 type to
7086 double, so we need to do this for it... */
7088 DWORD tot_hi
= memstex
.ullTotalPhys
>> 32;
7089 DWORD tot_md
= (memstex
.ullTotalPhys
& 0x00000000ffffffff) >> 10;
7090 DWORD tot_lo
= memstex
.ullTotalPhys
% 1024;
7092 totphys
= tot_hi
* 4194304.0 + tot_md
+ tot_lo
/ 1024.0;
7094 #endif /* __GNUC__ || _MSC_VER >= 1300 */
7095 else if (global_memory_status (&memst
))
7096 totphys
= memst
.dwTotalPhys
/ 1024.0;
7099 && get_process_memory_info (h_proc
, (PROCESS_MEMORY_COUNTERS
*)&mem_ex
,
7102 SIZE_T rss
= mem_ex
.WorkingSetSize
/ 1024;
7104 attrs
= Fcons (Fcons (Qmajflt
,
7105 make_fixnum_or_float (mem_ex
.PageFaultCount
)),
7107 attrs
= Fcons (Fcons (Qvsize
,
7108 make_fixnum_or_float (mem_ex
.PrivateUsage
/ 1024)),
7110 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (rss
)), attrs
);
7112 attrs
= Fcons (Fcons (Qpmem
, make_float (100. * rss
/ totphys
)), attrs
);
7115 && get_process_memory_info (h_proc
, &mem
, sizeof (mem
)))
7117 SIZE_T rss
= mem_ex
.WorkingSetSize
/ 1024;
7119 attrs
= Fcons (Fcons (Qmajflt
,
7120 make_fixnum_or_float (mem
.PageFaultCount
)),
7122 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (rss
)), attrs
);
7124 attrs
= Fcons (Fcons (Qpmem
, make_float (100. * rss
/ totphys
)), attrs
);
7127 && get_process_working_set_size (h_proc
, &minrss
, &maxrss
))
7129 DWORD rss
= maxrss
/ 1024;
7131 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (maxrss
/ 1024)), attrs
);
7133 attrs
= Fcons (Fcons (Qpmem
, make_float (100. * rss
/ totphys
)), attrs
);
7136 if (process_times (h_proc
, &ctime
, &etime
, &stime
, &utime
, &ttime
, &pcpu
))
7138 attrs
= Fcons (Fcons (Qutime
, utime
), attrs
);
7139 attrs
= Fcons (Fcons (Qstime
, stime
), attrs
);
7140 attrs
= Fcons (Fcons (Qtime
, ttime
), attrs
);
7141 attrs
= Fcons (Fcons (Qstart
, ctime
), attrs
);
7142 attrs
= Fcons (Fcons (Qetime
, etime
), attrs
);
7143 attrs
= Fcons (Fcons (Qpcpu
, make_float (pcpu
)), attrs
);
7146 /* FIXME: Retrieve command line by walking the PEB of the process. */
7149 CloseHandle (h_proc
);
7154 w32_memory_info (unsigned long long *totalram
, unsigned long long *freeram
,
7155 unsigned long long *totalswap
, unsigned long long *freeswap
)
7158 MEMORY_STATUS_EX memstex
;
7160 /* Use GlobalMemoryStatusEx if available, as it can report more than
7162 if (global_memory_status_ex (&memstex
))
7164 *totalram
= memstex
.ullTotalPhys
;
7165 *freeram
= memstex
.ullAvailPhys
;
7166 *totalswap
= memstex
.ullTotalPageFile
;
7167 *freeswap
= memstex
.ullAvailPageFile
;
7170 else if (global_memory_status (&memst
))
7172 *totalram
= memst
.dwTotalPhys
;
7173 *freeram
= memst
.dwAvailPhys
;
7174 *totalswap
= memst
.dwTotalPageFile
;
7175 *freeswap
= memst
.dwAvailPageFile
;
7183 /* Wrappers for winsock functions to map between our file descriptors
7184 and winsock's handles; also set h_errno for convenience.
7186 To allow Emacs to run on systems which don't have winsock support
7187 installed, we dynamically link to winsock on startup if present, and
7188 otherwise provide the minimum necessary functionality
7189 (eg. gethostname). */
7191 /* function pointers for relevant socket functions */
7192 int (PASCAL
*pfn_WSAStartup
) (WORD wVersionRequired
, LPWSADATA lpWSAData
);
7193 void (PASCAL
*pfn_WSASetLastError
) (int iError
);
7194 int (PASCAL
*pfn_WSAGetLastError
) (void);
7195 int (PASCAL
*pfn_WSAEventSelect
) (SOCKET s
, HANDLE hEventObject
, long lNetworkEvents
);
7196 int (PASCAL
*pfn_WSAEnumNetworkEvents
) (SOCKET s
, HANDLE hEventObject
,
7197 WSANETWORKEVENTS
*NetworkEvents
);
7199 HANDLE (PASCAL
*pfn_WSACreateEvent
) (void);
7200 int (PASCAL
*pfn_WSACloseEvent
) (HANDLE hEvent
);
7201 int (PASCAL
*pfn_socket
) (int af
, int type
, int protocol
);
7202 int (PASCAL
*pfn_bind
) (SOCKET s
, const struct sockaddr
*addr
, int namelen
);
7203 int (PASCAL
*pfn_connect
) (SOCKET s
, const struct sockaddr
*addr
, int namelen
);
7204 int (PASCAL
*pfn_ioctlsocket
) (SOCKET s
, long cmd
, u_long
*argp
);
7205 int (PASCAL
*pfn_recv
) (SOCKET s
, char * buf
, int len
, int flags
);
7206 int (PASCAL
*pfn_send
) (SOCKET s
, const char * buf
, int len
, int flags
);
7207 int (PASCAL
*pfn_closesocket
) (SOCKET s
);
7208 int (PASCAL
*pfn_shutdown
) (SOCKET s
, int how
);
7209 int (PASCAL
*pfn_WSACleanup
) (void);
7211 u_short (PASCAL
*pfn_htons
) (u_short hostshort
);
7212 u_short (PASCAL
*pfn_ntohs
) (u_short netshort
);
7213 unsigned long (PASCAL
*pfn_inet_addr
) (const char * cp
);
7214 int (PASCAL
*pfn_gethostname
) (char * name
, int namelen
);
7215 struct hostent
* (PASCAL
*pfn_gethostbyname
) (const char * name
);
7216 struct servent
* (PASCAL
*pfn_getservbyname
) (const char * name
, const char * proto
);
7217 int (PASCAL
*pfn_getpeername
) (SOCKET s
, struct sockaddr
*addr
, int * namelen
);
7218 int (PASCAL
*pfn_setsockopt
) (SOCKET s
, int level
, int optname
,
7219 const char * optval
, int optlen
);
7220 int (PASCAL
*pfn_listen
) (SOCKET s
, int backlog
);
7221 int (PASCAL
*pfn_getsockname
) (SOCKET s
, struct sockaddr
* name
,
7223 SOCKET (PASCAL
*pfn_accept
) (SOCKET s
, struct sockaddr
* addr
, int * addrlen
);
7224 int (PASCAL
*pfn_recvfrom
) (SOCKET s
, char * buf
, int len
, int flags
,
7225 struct sockaddr
* from
, int * fromlen
);
7226 int (PASCAL
*pfn_sendto
) (SOCKET s
, const char * buf
, int len
, int flags
,
7227 const struct sockaddr
* to
, int tolen
);
7229 int (PASCAL
*pfn_getaddrinfo
) (const char *, const char *,
7230 const struct addrinfo
*, struct addrinfo
**);
7231 void (PASCAL
*pfn_freeaddrinfo
) (struct addrinfo
*);
7233 /* SetHandleInformation is only needed to make sockets non-inheritable. */
7234 BOOL (WINAPI
*pfn_SetHandleInformation
) (HANDLE object
, DWORD mask
, DWORD flags
);
7235 #ifndef HANDLE_FLAG_INHERIT
7236 #define HANDLE_FLAG_INHERIT 1
7240 static int winsock_inuse
;
7242 BOOL
term_winsock (void);
7247 if (winsock_lib
!= NULL
&& winsock_inuse
== 0)
7249 release_listen_threads ();
7250 /* Not sure what would cause WSAENETDOWN, or even if it can happen
7251 after WSAStartup returns successfully, but it seems reasonable
7252 to allow unloading winsock anyway in that case. */
7253 if (pfn_WSACleanup () == 0 ||
7254 pfn_WSAGetLastError () == WSAENETDOWN
)
7256 if (FreeLibrary (winsock_lib
))
7265 init_winsock (int load_now
)
7267 WSADATA winsockData
;
7269 if (winsock_lib
!= NULL
)
7272 pfn_SetHandleInformation
7273 = (void *) GetProcAddress (GetModuleHandle ("kernel32.dll"),
7274 "SetHandleInformation");
7276 winsock_lib
= LoadLibrary ("Ws2_32.dll");
7278 if (winsock_lib
!= NULL
)
7280 /* dynamically link to socket functions */
7282 #define LOAD_PROC(fn) \
7283 if ((pfn_##fn = (void *) GetProcAddress (winsock_lib, #fn)) == NULL) \
7286 LOAD_PROC (WSAStartup
);
7287 LOAD_PROC (WSASetLastError
);
7288 LOAD_PROC (WSAGetLastError
);
7289 LOAD_PROC (WSAEventSelect
);
7290 LOAD_PROC (WSAEnumNetworkEvents
);
7291 LOAD_PROC (WSACreateEvent
);
7292 LOAD_PROC (WSACloseEvent
);
7295 LOAD_PROC (connect
);
7296 LOAD_PROC (ioctlsocket
);
7299 LOAD_PROC (closesocket
);
7300 LOAD_PROC (shutdown
);
7303 LOAD_PROC (inet_addr
);
7304 LOAD_PROC (gethostname
);
7305 LOAD_PROC (gethostbyname
);
7306 LOAD_PROC (getservbyname
);
7307 LOAD_PROC (getpeername
);
7308 LOAD_PROC (WSACleanup
);
7309 LOAD_PROC (setsockopt
);
7311 LOAD_PROC (getsockname
);
7313 LOAD_PROC (recvfrom
);
7317 /* Try loading functions not available before XP. */
7318 pfn_getaddrinfo
= (void *) GetProcAddress (winsock_lib
, "getaddrinfo");
7319 pfn_freeaddrinfo
= (void *) GetProcAddress (winsock_lib
, "freeaddrinfo");
7320 /* Paranoia: these two functions should go together, so if one
7321 is absent, we cannot use the other. */
7322 if (pfn_getaddrinfo
== NULL
)
7323 pfn_freeaddrinfo
= NULL
;
7324 else if (pfn_freeaddrinfo
== NULL
)
7325 pfn_getaddrinfo
= NULL
;
7327 /* specify version 1.1 of winsock */
7328 if (pfn_WSAStartup (0x101, &winsockData
) == 0)
7330 if (winsockData
.wVersion
!= 0x101)
7335 /* Report that winsock exists and is usable, but leave
7336 socket functions disabled. I am assuming that calling
7337 WSAStartup does not require any network interaction,
7338 and in particular does not cause or require a dial-up
7339 connection to be established. */
7342 FreeLibrary (winsock_lib
);
7350 FreeLibrary (winsock_lib
);
7360 /* Function to map winsock error codes to errno codes for those errno
7361 code defined in errno.h (errno values not defined by errno.h are
7362 already in nt/inc/sys/socket.h). */
7369 if (winsock_lib
== NULL
)
7372 wsa_err
= pfn_WSAGetLastError ();
7376 case WSAEACCES
: errno
= EACCES
; break;
7377 case WSAEBADF
: errno
= EBADF
; break;
7378 case WSAEFAULT
: errno
= EFAULT
; break;
7379 case WSAEINTR
: errno
= EINTR
; break;
7380 case WSAEINVAL
: errno
= EINVAL
; break;
7381 case WSAEMFILE
: errno
= EMFILE
; break;
7382 case WSAENAMETOOLONG
: errno
= ENAMETOOLONG
; break;
7383 case WSAENOTEMPTY
: errno
= ENOTEMPTY
; break;
7384 case WSAEWOULDBLOCK
: errno
= EWOULDBLOCK
; break;
7385 case WSAENOTCONN
: errno
= ENOTCONN
; break;
7386 default: errno
= wsa_err
; break;
7394 if (winsock_lib
!= NULL
)
7395 pfn_WSASetLastError (0);
7398 /* Extend strerror to handle the winsock-specific error codes. */
7402 } _wsa_errlist
[] = {
7403 {WSAEINTR
, "Interrupted function call"},
7404 {WSAEBADF
, "Bad file descriptor"},
7405 {WSAEACCES
, "Permission denied"},
7406 {WSAEFAULT
, "Bad address"},
7407 {WSAEINVAL
, "Invalid argument"},
7408 {WSAEMFILE
, "Too many open files"},
7410 {WSAEWOULDBLOCK
, "Resource temporarily unavailable"},
7411 {WSAEINPROGRESS
, "Operation now in progress"},
7412 {WSAEALREADY
, "Operation already in progress"},
7413 {WSAENOTSOCK
, "Socket operation on non-socket"},
7414 {WSAEDESTADDRREQ
, "Destination address required"},
7415 {WSAEMSGSIZE
, "Message too long"},
7416 {WSAEPROTOTYPE
, "Protocol wrong type for socket"},
7417 {WSAENOPROTOOPT
, "Bad protocol option"},
7418 {WSAEPROTONOSUPPORT
, "Protocol not supported"},
7419 {WSAESOCKTNOSUPPORT
, "Socket type not supported"},
7420 {WSAEOPNOTSUPP
, "Operation not supported"},
7421 {WSAEPFNOSUPPORT
, "Protocol family not supported"},
7422 {WSAEAFNOSUPPORT
, "Address family not supported by protocol family"},
7423 {WSAEADDRINUSE
, "Address already in use"},
7424 {WSAEADDRNOTAVAIL
, "Cannot assign requested address"},
7425 {WSAENETDOWN
, "Network is down"},
7426 {WSAENETUNREACH
, "Network is unreachable"},
7427 {WSAENETRESET
, "Network dropped connection on reset"},
7428 {WSAECONNABORTED
, "Software caused connection abort"},
7429 {WSAECONNRESET
, "Connection reset by peer"},
7430 {WSAENOBUFS
, "No buffer space available"},
7431 {WSAEISCONN
, "Socket is already connected"},
7432 {WSAENOTCONN
, "Socket is not connected"},
7433 {WSAESHUTDOWN
, "Cannot send after socket shutdown"},
7434 {WSAETOOMANYREFS
, "Too many references"}, /* not sure */
7435 {WSAETIMEDOUT
, "Connection timed out"},
7436 {WSAECONNREFUSED
, "Connection refused"},
7437 {WSAELOOP
, "Network loop"}, /* not sure */
7438 {WSAENAMETOOLONG
, "Name is too long"},
7439 {WSAEHOSTDOWN
, "Host is down"},
7440 {WSAEHOSTUNREACH
, "No route to host"},
7441 {WSAENOTEMPTY
, "Buffer not empty"}, /* not sure */
7442 {WSAEPROCLIM
, "Too many processes"},
7443 {WSAEUSERS
, "Too many users"}, /* not sure */
7444 {WSAEDQUOT
, "Double quote in host name"}, /* really not sure */
7445 {WSAESTALE
, "Data is stale"}, /* not sure */
7446 {WSAEREMOTE
, "Remote error"}, /* not sure */
7448 {WSASYSNOTREADY
, "Network subsystem is unavailable"},
7449 {WSAVERNOTSUPPORTED
, "WINSOCK.DLL version out of range"},
7450 {WSANOTINITIALISED
, "Winsock not initialized successfully"},
7451 {WSAEDISCON
, "Graceful shutdown in progress"},
7453 {WSAENOMORE
, "No more operations allowed"}, /* not sure */
7454 {WSAECANCELLED
, "Operation cancelled"}, /* not sure */
7455 {WSAEINVALIDPROCTABLE
, "Invalid procedure table from service provider"},
7456 {WSAEINVALIDPROVIDER
, "Invalid service provider version number"},
7457 {WSAEPROVIDERFAILEDINIT
, "Unable to initialize a service provider"},
7458 {WSASYSCALLFAILURE
, "System call failure"},
7459 {WSASERVICE_NOT_FOUND
, "Service not found"}, /* not sure */
7460 {WSATYPE_NOT_FOUND
, "Class type not found"},
7461 {WSA_E_NO_MORE
, "No more resources available"}, /* really not sure */
7462 {WSA_E_CANCELLED
, "Operation already cancelled"}, /* really not sure */
7463 {WSAEREFUSED
, "Operation refused"}, /* not sure */
7466 {WSAHOST_NOT_FOUND
, "Host not found"},
7467 {WSATRY_AGAIN
, "Authoritative host not found during name lookup"},
7468 {WSANO_RECOVERY
, "Non-recoverable error during name lookup"},
7469 {WSANO_DATA
, "Valid name, no data record of requested type"},
7475 sys_strerror (int error_no
)
7478 static char unknown_msg
[40];
7480 if (error_no
>= 0 && error_no
< sys_nerr
)
7481 return sys_errlist
[error_no
];
7483 for (i
= 0; _wsa_errlist
[i
].errnum
>= 0; i
++)
7484 if (_wsa_errlist
[i
].errnum
== error_no
)
7485 return (char *)_wsa_errlist
[i
].msg
;
7487 sprintf (unknown_msg
, "Unidentified error: %d", error_no
);
7491 /* [andrewi 3-May-96] I've had conflicting results using both methods,
7492 but I believe the method of keeping the socket handle separate (and
7493 insuring it is not inheritable) is the correct one. */
7495 #define SOCK_HANDLE(fd) ((SOCKET) fd_info[fd].hnd)
7497 static int socket_to_fd (SOCKET s
);
7500 sys_socket (int af
, int type
, int protocol
)
7504 if (winsock_lib
== NULL
)
7512 /* call the real socket function */
7513 s
= pfn_socket (af
, type
, protocol
);
7515 if (s
!= INVALID_SOCKET
)
7516 return socket_to_fd (s
);
7522 /* Convert a SOCKET to a file descriptor. */
7524 socket_to_fd (SOCKET s
)
7529 /* Although under NT 3.5 _open_osfhandle will accept a socket
7530 handle, if opened with SO_OPENTYPE == SO_SYNCHRONOUS_NONALERT,
7531 that does not work under NT 3.1. However, we can get the same
7532 effect by using a backdoor function to replace an existing
7533 descriptor handle with the one we want. */
7535 /* allocate a file descriptor (with appropriate flags) */
7536 fd
= _open ("NUL:", _O_RDWR
);
7539 /* Make a non-inheritable copy of the socket handle. Note
7540 that it is possible that sockets aren't actually kernel
7541 handles, which appears to be the case on Windows 9x when
7542 the MS Proxy winsock client is installed. */
7544 /* Apparently there is a bug in NT 3.51 with some service
7545 packs, which prevents using DuplicateHandle to make a
7546 socket handle non-inheritable (causes WSACleanup to
7547 hang). The work-around is to use SetHandleInformation
7548 instead if it is available and implemented. */
7549 if (pfn_SetHandleInformation
)
7551 pfn_SetHandleInformation ((HANDLE
) s
, HANDLE_FLAG_INHERIT
, 0);
7555 HANDLE parent
= GetCurrentProcess ();
7556 HANDLE new_s
= INVALID_HANDLE_VALUE
;
7558 if (DuplicateHandle (parent
,
7564 DUPLICATE_SAME_ACCESS
))
7566 /* It is possible that DuplicateHandle succeeds even
7567 though the socket wasn't really a kernel handle,
7568 because a real handle has the same value. So
7569 test whether the new handle really is a socket. */
7570 unsigned long nonblocking
= 0;
7571 if (pfn_ioctlsocket ((SOCKET
) new_s
, FIONBIO
, &nonblocking
) == 0)
7573 pfn_closesocket (s
);
7578 CloseHandle (new_s
);
7583 eassert (fd
< MAXDESC
);
7584 fd_info
[fd
].hnd
= (HANDLE
) s
;
7586 /* set our own internal flags */
7587 fd_info
[fd
].flags
= FILE_SOCKET
| FILE_BINARY
| FILE_READ
| FILE_WRITE
;
7593 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
7595 /* attach child_process to fd_info */
7596 if (fd_info
[ fd
].cp
!= NULL
)
7598 DebPrint (("sys_socket: fd_info[%d] apparently in use!\n", fd
));
7602 fd_info
[ fd
].cp
= cp
;
7605 winsock_inuse
++; /* count open sockets */
7613 pfn_closesocket (s
);
7619 sys_bind (int s
, const struct sockaddr
* addr
, int namelen
)
7621 if (winsock_lib
== NULL
)
7624 return SOCKET_ERROR
;
7628 if (fd_info
[s
].flags
& FILE_SOCKET
)
7630 int rc
= pfn_bind (SOCK_HANDLE (s
), addr
, namelen
);
7631 if (rc
== SOCKET_ERROR
)
7636 return SOCKET_ERROR
;
7640 sys_connect (int s
, const struct sockaddr
* name
, int namelen
)
7642 if (winsock_lib
== NULL
)
7645 return SOCKET_ERROR
;
7649 if (fd_info
[s
].flags
& FILE_SOCKET
)
7651 int rc
= pfn_connect (SOCK_HANDLE (s
), name
, namelen
);
7652 if (rc
== SOCKET_ERROR
)
7655 /* If this is a non-blocking 'connect', set the bit in flags
7656 that will tell reader_thread to wait for connection
7657 before trying to read. */
7658 if (errno
== EWOULDBLOCK
&& (fd_info
[s
].flags
& FILE_NDELAY
) != 0)
7660 errno
= EINPROGRESS
; /* that's what process.c expects */
7661 fd_info
[s
].flags
|= FILE_CONNECT
;
7667 return SOCKET_ERROR
;
7671 sys_htons (u_short hostshort
)
7673 return (winsock_lib
!= NULL
) ?
7674 pfn_htons (hostshort
) : hostshort
;
7678 sys_ntohs (u_short netshort
)
7680 return (winsock_lib
!= NULL
) ?
7681 pfn_ntohs (netshort
) : netshort
;
7685 sys_inet_addr (const char * cp
)
7687 return (winsock_lib
!= NULL
) ?
7688 pfn_inet_addr (cp
) : INADDR_NONE
;
7692 sys_gethostname (char * name
, int namelen
)
7694 if (winsock_lib
!= NULL
)
7699 retval
= pfn_gethostname (name
, namelen
);
7700 if (retval
== SOCKET_ERROR
)
7705 if (namelen
> MAX_COMPUTERNAME_LENGTH
)
7706 return !GetComputerName (name
, (DWORD
*)&namelen
);
7709 return SOCKET_ERROR
;
7713 sys_gethostbyname (const char * name
)
7715 struct hostent
* host
;
7716 int h_err
= h_errno
;
7718 if (winsock_lib
== NULL
)
7720 h_errno
= NO_RECOVERY
;
7726 host
= pfn_gethostbyname (name
);
7738 sys_getservbyname (const char * name
, const char * proto
)
7740 struct servent
* serv
;
7742 if (winsock_lib
== NULL
)
7749 serv
= pfn_getservbyname (name
, proto
);
7756 sys_getpeername (int s
, struct sockaddr
*addr
, int * namelen
)
7758 if (winsock_lib
== NULL
)
7761 return SOCKET_ERROR
;
7765 if (fd_info
[s
].flags
& FILE_SOCKET
)
7767 int rc
= pfn_getpeername (SOCK_HANDLE (s
), addr
, namelen
);
7768 if (rc
== SOCKET_ERROR
)
7773 return SOCKET_ERROR
;
7777 sys_getaddrinfo (const char *node
, const char *service
,
7778 const struct addrinfo
*hints
, struct addrinfo
**res
)
7782 if (winsock_lib
== NULL
)
7785 return SOCKET_ERROR
;
7789 if (pfn_getaddrinfo
)
7790 rc
= pfn_getaddrinfo (node
, service
, hints
, res
);
7794 struct hostent
*host_info
;
7795 struct gai_storage
{
7796 struct addrinfo addrinfo
;
7797 struct sockaddr_in sockaddr_in
;
7800 /* We don't (yet) support any flags, as Emacs doesn't need that. */
7801 if (hints
&& hints
->ai_flags
!= 0)
7803 /* NODE cannot be NULL, since process.c has fallbacks for that. */
7805 return WSAHOST_NOT_FOUND
;
7809 const char *protocol
=
7810 (hints
&& hints
->ai_socktype
== SOCK_DGRAM
) ? "udp" : "tcp";
7811 struct servent
*srv
= sys_getservbyname (service
, protocol
);
7815 else if (*service
>= '0' && *service
<= '9')
7819 port
= strtoul (service
, &endp
, 10);
7820 if (*endp
|| port
> 65536)
7821 return WSAHOST_NOT_FOUND
;
7822 port
= sys_htons ((unsigned short) port
);
7825 return WSAHOST_NOT_FOUND
;
7828 gai_storage
= xzalloc (sizeof *gai_storage
);
7829 gai_storage
->sockaddr_in
.sin_port
= port
;
7830 host_info
= sys_gethostbyname (node
);
7833 memcpy (&gai_storage
->sockaddr_in
.sin_addr
,
7834 host_info
->h_addr
, host_info
->h_length
);
7835 gai_storage
->sockaddr_in
.sin_family
= host_info
->h_addrtype
;
7839 /* Attempt to interpret host as numeric inet address. */
7840 unsigned long numeric_addr
= sys_inet_addr (node
);
7842 if (numeric_addr
== -1)
7845 return WSAHOST_NOT_FOUND
;
7848 memcpy (&gai_storage
->sockaddr_in
.sin_addr
, &numeric_addr
,
7849 sizeof (gai_storage
->sockaddr_in
.sin_addr
));
7850 gai_storage
->sockaddr_in
.sin_family
= (hints
) ? hints
->ai_family
: 0;
7853 gai_storage
->addrinfo
.ai_addr
=
7854 (struct sockaddr
*)&gai_storage
->sockaddr_in
;
7855 gai_storage
->addrinfo
.ai_addrlen
= sizeof (gai_storage
->sockaddr_in
);
7856 gai_storage
->addrinfo
.ai_protocol
= (hints
) ? hints
->ai_protocol
: 0;
7857 gai_storage
->addrinfo
.ai_socktype
= (hints
) ? hints
->ai_socktype
: 0;
7858 gai_storage
->addrinfo
.ai_family
= gai_storage
->sockaddr_in
.sin_family
;
7859 gai_storage
->addrinfo
.ai_next
= NULL
;
7861 *res
= &gai_storage
->addrinfo
;
7869 sys_freeaddrinfo (struct addrinfo
*ai
)
7871 if (winsock_lib
== NULL
)
7878 if (pfn_freeaddrinfo
)
7879 pfn_freeaddrinfo (ai
);
7882 eassert (ai
->ai_next
== NULL
);
7888 sys_shutdown (int s
, int how
)
7890 if (winsock_lib
== NULL
)
7893 return SOCKET_ERROR
;
7897 if (fd_info
[s
].flags
& FILE_SOCKET
)
7899 int rc
= pfn_shutdown (SOCK_HANDLE (s
), how
);
7900 if (rc
== SOCKET_ERROR
)
7905 return SOCKET_ERROR
;
7909 sys_setsockopt (int s
, int level
, int optname
, const void * optval
, int optlen
)
7911 if (winsock_lib
== NULL
)
7914 return SOCKET_ERROR
;
7918 if (fd_info
[s
].flags
& FILE_SOCKET
)
7920 int rc
= pfn_setsockopt (SOCK_HANDLE (s
), level
, optname
,
7921 (const char *)optval
, optlen
);
7922 if (rc
== SOCKET_ERROR
)
7927 return SOCKET_ERROR
;
7931 sys_listen (int s
, int backlog
)
7933 if (winsock_lib
== NULL
)
7936 return SOCKET_ERROR
;
7940 if (fd_info
[s
].flags
& FILE_SOCKET
)
7942 int rc
= pfn_listen (SOCK_HANDLE (s
), backlog
);
7943 if (rc
== SOCKET_ERROR
)
7946 fd_info
[s
].flags
|= FILE_LISTEN
;
7950 return SOCKET_ERROR
;
7954 sys_getsockname (int s
, struct sockaddr
* name
, int * namelen
)
7956 if (winsock_lib
== NULL
)
7959 return SOCKET_ERROR
;
7963 if (fd_info
[s
].flags
& FILE_SOCKET
)
7965 int rc
= pfn_getsockname (SOCK_HANDLE (s
), name
, namelen
);
7966 if (rc
== SOCKET_ERROR
)
7971 return SOCKET_ERROR
;
7975 sys_accept (int s
, struct sockaddr
* addr
, int * addrlen
)
7977 if (winsock_lib
== NULL
)
7984 if (fd_info
[s
].flags
& FILE_LISTEN
)
7986 SOCKET t
= pfn_accept (SOCK_HANDLE (s
), addr
, addrlen
);
7988 if (t
== INVALID_SOCKET
)
7991 fd
= socket_to_fd (t
);
7995 fd_info
[s
].cp
->status
= STATUS_READ_ACKNOWLEDGED
;
7996 ResetEvent (fd_info
[s
].cp
->char_avail
);
8005 sys_recvfrom (int s
, char * buf
, int len
, int flags
,
8006 struct sockaddr
* from
, int * fromlen
)
8008 if (winsock_lib
== NULL
)
8011 return SOCKET_ERROR
;
8015 if (fd_info
[s
].flags
& FILE_SOCKET
)
8017 int rc
= pfn_recvfrom (SOCK_HANDLE (s
), buf
, len
, flags
, from
, fromlen
);
8018 if (rc
== SOCKET_ERROR
)
8023 return SOCKET_ERROR
;
8027 sys_sendto (int s
, const char * buf
, int len
, int flags
,
8028 const struct sockaddr
* to
, int tolen
)
8030 if (winsock_lib
== NULL
)
8033 return SOCKET_ERROR
;
8037 if (fd_info
[s
].flags
& FILE_SOCKET
)
8039 int rc
= pfn_sendto (SOCK_HANDLE (s
), buf
, len
, flags
, to
, tolen
);
8040 if (rc
== SOCKET_ERROR
)
8045 return SOCKET_ERROR
;
8048 /* Windows does not have an fcntl function. Provide an implementation
8049 good enough for Emacs. */
8051 fcntl (int s
, int cmd
, int options
)
8053 /* In the w32 Emacs port, fcntl (fd, F_DUPFD_CLOEXEC, fd1) is always
8054 invoked in a context where fd1 is closed and all descriptors less
8055 than fd1 are open, so sys_dup is an adequate implementation. */
8056 if (cmd
== F_DUPFD_CLOEXEC
)
8060 if (fd_info
[s
].flags
& FILE_SOCKET
)
8062 if (winsock_lib
== NULL
)
8068 if (cmd
== F_SETFL
&& options
== O_NONBLOCK
)
8070 unsigned long nblock
= 1;
8071 int rc
= pfn_ioctlsocket (SOCK_HANDLE (s
), FIONBIO
, &nblock
);
8072 if (rc
== SOCKET_ERROR
)
8074 /* Keep track of the fact that we set this to non-blocking. */
8075 fd_info
[s
].flags
|= FILE_NDELAY
;
8081 return SOCKET_ERROR
;
8084 else if ((fd_info
[s
].flags
& (FILE_PIPE
| FILE_WRITE
))
8085 == (FILE_PIPE
| FILE_WRITE
))
8087 /* Force our writes to pipes be non-blocking. */
8088 if (cmd
== F_SETFL
&& options
== O_NONBLOCK
)
8090 HANDLE h
= (HANDLE
)_get_osfhandle (s
);
8091 DWORD pipe_mode
= PIPE_NOWAIT
;
8093 if (!SetNamedPipeHandleState (h
, &pipe_mode
, NULL
, NULL
))
8095 DebPrint (("SetNamedPipeHandleState: %lu\n", GetLastError ()));
8096 return SOCKET_ERROR
;
8098 fd_info
[s
].flags
|= FILE_NDELAY
;
8104 return SOCKET_ERROR
;
8108 return SOCKET_ERROR
;
8112 /* Shadow main io functions: we need to handle pipes and sockets more
8126 if (fd
< MAXDESC
&& fd_info
[fd
].cp
)
8128 child_process
* cp
= fd_info
[fd
].cp
;
8130 fd_info
[fd
].cp
= NULL
;
8132 if (CHILD_ACTIVE (cp
))
8134 /* if last descriptor to active child_process then cleanup */
8136 for (i
= 0; i
< MAXDESC
; i
++)
8140 if (fd_info
[i
].cp
== cp
)
8145 if (fd_info
[fd
].flags
& FILE_SOCKET
)
8147 if (winsock_lib
== NULL
) emacs_abort ();
8149 pfn_shutdown (SOCK_HANDLE (fd
), 2);
8150 rc
= pfn_closesocket (SOCK_HANDLE (fd
));
8152 winsock_inuse
--; /* count open sockets */
8154 /* If the process handle is NULL, it's either a socket
8155 or serial connection, or a subprocess that was
8156 already reaped by reap_subprocess, but whose
8157 resources were not yet freed, because its output was
8158 not fully read yet by the time it was reaped. (This
8159 usually happens with async subprocesses whose output
8160 is being read by Emacs.) Otherwise, this process was
8161 not reaped yet, so we set its FD to a negative value
8162 to make sure sys_select will eventually get to
8163 calling the SIGCHLD handler for it, which will then
8164 invoke waitpid and reap_subprocess. */
8165 if (cp
->procinfo
.hProcess
== NULL
)
8173 if (fd
>= 0 && fd
< MAXDESC
)
8174 fd_info
[fd
].flags
= 0;
8176 /* Note that sockets do not need special treatment here (at least on
8177 NT and Windows 95 using the standard tcp/ip stacks) - it appears that
8178 closesocket is equivalent to CloseHandle, which is to be expected
8179 because socket handles are fully fledged kernel handles. */
8191 if (new_fd
>= 0 && new_fd
< MAXDESC
)
8193 /* duplicate our internal info as well */
8194 fd_info
[new_fd
] = fd_info
[fd
];
8200 sys_dup2 (int src
, int dst
)
8204 if (dst
< 0 || dst
>= MAXDESC
)
8210 /* MS _dup2 seems to have weird side effect when invoked with 2
8211 identical arguments: an attempt to fclose the corresponding stdio
8212 stream after that hangs (we do close standard streams in
8213 init_ntproc). Attempt to avoid that by not calling _dup2 that
8214 way: if SRC is valid, we know that dup2 should be a no-op, so do
8215 nothing and return DST. */
8218 if ((HANDLE
)_get_osfhandle (src
) == INVALID_HANDLE_VALUE
)
8226 /* Make sure we close the destination first if it's a pipe or socket. */
8227 if (fd_info
[dst
].flags
!= 0)
8230 rc
= _dup2 (src
, dst
);
8233 /* Duplicate our internal info as well. */
8234 fd_info
[dst
] = fd_info
[src
];
8236 return rc
== 0 ? dst
: rc
;
8240 pipe2 (int * phandles
, int pipe2_flags
)
8244 unsigned pipe_size
= 0;
8246 eassert (pipe2_flags
== (O_BINARY
| O_CLOEXEC
));
8248 /* Allow Lisp to override the default buffer size of the pipe. */
8249 if (w32_pipe_buffer_size
> 0 && w32_pipe_buffer_size
< UINT_MAX
)
8250 pipe_size
= w32_pipe_buffer_size
;
8252 /* make pipe handles non-inheritable; when we spawn a child, we
8253 replace the relevant handle with an inheritable one. Also put
8254 pipes into binary mode; we will do text mode translation ourselves
8256 rc
= _pipe (phandles
, pipe_size
, _O_NOINHERIT
| _O_BINARY
);
8260 /* Protect against overflow, since Windows can open more handles than
8261 our fd_info array has room for. */
8262 if (phandles
[0] >= MAXDESC
|| phandles
[1] >= MAXDESC
)
8264 _close (phandles
[0]);
8265 _close (phandles
[1]);
8271 flags
= FILE_PIPE
| FILE_READ
| FILE_BINARY
;
8272 fd_info
[phandles
[0]].flags
= flags
;
8274 flags
= FILE_PIPE
| FILE_WRITE
| FILE_BINARY
;
8275 fd_info
[phandles
[1]].flags
= flags
;
8282 /* Function to do blocking read of one byte, needed to implement
8283 select. It is only allowed on communication ports, sockets, or
8286 _sys_read_ahead (int fd
)
8291 if (fd
< 0 || fd
>= MAXDESC
)
8292 return STATUS_READ_ERROR
;
8294 cp
= fd_info
[fd
].cp
;
8296 if (cp
== NULL
|| cp
->fd
!= fd
|| cp
->status
!= STATUS_READ_READY
)
8297 return STATUS_READ_ERROR
;
8299 if ((fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SERIAL
| FILE_SOCKET
)) == 0
8300 || (fd_info
[fd
].flags
& FILE_READ
) == 0)
8302 DebPrint (("_sys_read_ahead: internal error: fd %d is not a pipe, serial port, or socket!\n", fd
));
8306 if ((fd_info
[fd
].flags
& FILE_CONNECT
) != 0)
8307 DebPrint (("_sys_read_ahead: read requested from fd %d, which waits for async connect!\n", fd
));
8308 cp
->status
= STATUS_READ_IN_PROGRESS
;
8310 if (fd_info
[fd
].flags
& FILE_PIPE
)
8312 rc
= _read (fd
, &cp
->chr
, sizeof (char));
8314 /* Give subprocess time to buffer some more output for us before
8315 reporting that input is available; we need this because Windows 95
8316 connects DOS programs to pipes by making the pipe appear to be
8317 the normal console stdout - as a result most DOS programs will
8318 write to stdout without buffering, ie. one character at a
8319 time. Even some W32 programs do this - "dir" in a command
8320 shell on NT is very slow if we don't do this. */
8323 int wait
= w32_pipe_read_delay
;
8329 /* Yield remainder of our time slice, effectively giving a
8330 temporary priority boost to the child process. */
8334 else if (fd_info
[fd
].flags
& FILE_SERIAL
)
8336 HANDLE hnd
= fd_info
[fd
].hnd
;
8337 OVERLAPPED
*ovl
= &fd_info
[fd
].cp
->ovl_read
;
8340 /* Configure timeouts for blocking read. */
8341 if (!GetCommTimeouts (hnd
, &ct
))
8343 cp
->status
= STATUS_READ_ERROR
;
8344 return STATUS_READ_ERROR
;
8346 ct
.ReadIntervalTimeout
= 0;
8347 ct
.ReadTotalTimeoutMultiplier
= 0;
8348 ct
.ReadTotalTimeoutConstant
= 0;
8349 if (!SetCommTimeouts (hnd
, &ct
))
8351 cp
->status
= STATUS_READ_ERROR
;
8352 return STATUS_READ_ERROR
;
8355 if (!ReadFile (hnd
, &cp
->chr
, sizeof (char), (DWORD
*) &rc
, ovl
))
8357 if (GetLastError () != ERROR_IO_PENDING
)
8359 cp
->status
= STATUS_READ_ERROR
;
8360 return STATUS_READ_ERROR
;
8362 if (!GetOverlappedResult (hnd
, ovl
, (DWORD
*) &rc
, TRUE
))
8364 cp
->status
= STATUS_READ_ERROR
;
8365 return STATUS_READ_ERROR
;
8369 else if (fd_info
[fd
].flags
& FILE_SOCKET
)
8371 unsigned long nblock
= 0;
8372 /* We always want this to block, so temporarily disable NDELAY. */
8373 if (fd_info
[fd
].flags
& FILE_NDELAY
)
8374 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
8376 rc
= pfn_recv (SOCK_HANDLE (fd
), &cp
->chr
, sizeof (char), 0);
8378 if (fd_info
[fd
].flags
& FILE_NDELAY
)
8381 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
8385 if (rc
== sizeof (char))
8386 cp
->status
= STATUS_READ_SUCCEEDED
;
8388 cp
->status
= STATUS_READ_FAILED
;
8394 _sys_wait_accept (int fd
)
8400 if (fd
< 0 || fd
>= MAXDESC
)
8401 return STATUS_READ_ERROR
;
8403 cp
= fd_info
[fd
].cp
;
8405 if (cp
== NULL
|| cp
->fd
!= fd
|| cp
->status
!= STATUS_READ_READY
)
8406 return STATUS_READ_ERROR
;
8408 cp
->status
= STATUS_READ_FAILED
;
8410 hEv
= pfn_WSACreateEvent ();
8411 rc
= pfn_WSAEventSelect (SOCK_HANDLE (fd
), hEv
, FD_ACCEPT
);
8412 if (rc
!= SOCKET_ERROR
)
8415 rc
= WaitForSingleObject (hEv
, 500);
8417 } while (rc
== WAIT_TIMEOUT
8418 && cp
->status
!= STATUS_READ_ERROR
8420 pfn_WSAEventSelect (SOCK_HANDLE (fd
), NULL
, 0);
8421 if (rc
== WAIT_OBJECT_0
)
8422 cp
->status
= STATUS_READ_SUCCEEDED
;
8424 pfn_WSACloseEvent (hEv
);
8430 _sys_wait_connect (int fd
)
8436 if (fd
< 0 || fd
>= MAXDESC
)
8437 return STATUS_READ_ERROR
;
8439 cp
= fd_info
[fd
].cp
;
8440 if (cp
== NULL
|| cp
->fd
!= fd
|| cp
->status
!= STATUS_READ_READY
)
8441 return STATUS_READ_ERROR
;
8443 cp
->status
= STATUS_READ_FAILED
;
8445 hEv
= pfn_WSACreateEvent ();
8446 rc
= pfn_WSAEventSelect (SOCK_HANDLE (fd
), hEv
, FD_CONNECT
);
8447 if (rc
!= SOCKET_ERROR
)
8450 rc
= WaitForSingleObject (hEv
, 500);
8452 } while (rc
== WAIT_TIMEOUT
8453 && cp
->status
!= STATUS_READ_ERROR
8455 if (rc
== WAIT_OBJECT_0
)
8457 /* We've got an event, but it could be a successful
8458 connection, or it could be a failure. Find out
8460 WSANETWORKEVENTS events
;
8462 pfn_WSAEnumNetworkEvents (SOCK_HANDLE (fd
), hEv
, &events
);
8463 if ((events
.lNetworkEvents
& FD_CONNECT
) != 0
8464 && events
.iErrorCode
[FD_CONNECT_BIT
])
8466 cp
->status
= STATUS_CONNECT_FAILED
;
8467 cp
->errcode
= events
.iErrorCode
[FD_CONNECT_BIT
];
8471 cp
->status
= STATUS_READ_SUCCEEDED
;
8475 pfn_WSAEventSelect (SOCK_HANDLE (fd
), NULL
, 0);
8478 pfn_WSACloseEvent (hEv
);
8484 sys_read (int fd
, char * buffer
, unsigned int count
)
8489 char * orig_buffer
= buffer
;
8497 if (fd
< MAXDESC
&& fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
| FILE_SERIAL
))
8499 child_process
*cp
= fd_info
[fd
].cp
;
8501 if ((fd_info
[fd
].flags
& FILE_READ
) == 0)
8509 /* re-read CR carried over from last read */
8510 if (fd_info
[fd
].flags
& FILE_LAST_CR
)
8512 if (fd_info
[fd
].flags
& FILE_BINARY
) emacs_abort ();
8516 fd_info
[fd
].flags
&= ~FILE_LAST_CR
;
8519 /* presence of a child_process structure means we are operating in
8520 non-blocking mode - otherwise we just call _read directly.
8521 Note that the child_process structure might be missing because
8522 reap_subprocess has been called; in this case the pipe is
8523 already broken, so calling _read on it is okay. */
8526 int current_status
= cp
->status
;
8528 switch (current_status
)
8530 case STATUS_READ_FAILED
:
8531 case STATUS_READ_ERROR
:
8532 /* report normal EOF if nothing in buffer */
8534 fd_info
[fd
].flags
|= FILE_AT_EOF
;
8537 case STATUS_READ_READY
:
8538 case STATUS_READ_IN_PROGRESS
:
8540 /* This happens all the time during GnuTLS handshake
8541 with the remote, evidently because GnuTLS waits for
8542 the read to complete by retrying the read operation
8543 upon EAGAIN. So I'm disabling the DebPrint to avoid
8544 wasting cycles on something that is not a real
8545 problem. Enable if you need to debug something that
8547 DebPrint (("sys_read called when read is in progress %d\n",
8550 errno
= EWOULDBLOCK
;
8553 case STATUS_READ_SUCCEEDED
:
8554 /* consume read-ahead char */
8555 *buffer
++ = cp
->chr
;
8558 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
8559 ResetEvent (cp
->char_avail
);
8561 case STATUS_READ_ACKNOWLEDGED
:
8562 case STATUS_CONNECT_FAILED
:
8566 DebPrint (("sys_read: bad status %d\n", current_status
));
8571 if (fd_info
[fd
].flags
& FILE_PIPE
)
8573 PeekNamedPipe ((HANDLE
) _get_osfhandle (fd
), NULL
, 0, NULL
, &waiting
, NULL
);
8574 to_read
= min (waiting
, (DWORD
) count
);
8577 nchars
+= _read (fd
, buffer
, to_read
);
8579 else if (fd_info
[fd
].flags
& FILE_SERIAL
)
8581 HANDLE hnd
= fd_info
[fd
].hnd
;
8582 OVERLAPPED
*ovl
= &fd_info
[fd
].cp
->ovl_read
;
8588 /* Configure timeouts for non-blocking read. */
8589 if (!GetCommTimeouts (hnd
, &ct
))
8594 ct
.ReadIntervalTimeout
= MAXDWORD
;
8595 ct
.ReadTotalTimeoutMultiplier
= 0;
8596 ct
.ReadTotalTimeoutConstant
= 0;
8597 if (!SetCommTimeouts (hnd
, &ct
))
8603 if (!ResetEvent (ovl
->hEvent
))
8608 if (!ReadFile (hnd
, buffer
, count
, (DWORD
*) &rc
, ovl
))
8610 if (GetLastError () != ERROR_IO_PENDING
)
8615 if (!GetOverlappedResult (hnd
, ovl
, (DWORD
*) &rc
, TRUE
))
8624 else /* FILE_SOCKET */
8626 if (winsock_lib
== NULL
) emacs_abort ();
8628 /* When a non-blocking 'connect' call fails,
8629 wait_reading_process_output detects this by calling
8630 'getpeername', and then attempts to obtain the connection
8631 error code by trying to read 1 byte from the socket. If
8632 we try to serve that read by calling 'recv' below, the
8633 error we get is a generic WSAENOTCONN, not the actual
8634 connection error. So instead, we use the actual error
8635 code stashed by '_sys_wait_connect' in cp->errcode.
8636 Alternatively, we could have used 'getsockopt', like on
8637 GNU/Linux, but: (a) I have no idea whether the winsock
8638 version could hang, as it does "on some systems" (see the
8639 comment in process.c); and (b) 'getsockopt' on Windows is
8640 documented to clear the socket error for the entire
8641 process, which I'm not sure is TRT; FIXME. */
8642 if (current_status
== STATUS_CONNECT_FAILED
8643 && (fd_info
[fd
].flags
& FILE_CONNECT
) != 0
8644 && cp
->errcode
!= 0)
8646 pfn_WSASetLastError (cp
->errcode
);
8650 /* Do the equivalent of a non-blocking read. */
8651 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONREAD
, &waiting
);
8652 if (waiting
== 0 && nchars
== 0)
8654 errno
= EWOULDBLOCK
;
8660 /* always use binary mode for sockets */
8661 int res
= pfn_recv (SOCK_HANDLE (fd
), buffer
, count
, 0);
8662 if (res
== SOCKET_ERROR
)
8665 DebPrint (("sys_read.recv failed with error %d on socket %ld\n",
8666 errno
, SOCK_HANDLE (fd
)));
8675 int nread
= _read (fd
, buffer
, count
);
8678 else if (nchars
== 0)
8683 fd_info
[fd
].flags
|= FILE_AT_EOF
;
8684 /* Perform text mode translation if required. */
8685 else if ((fd_info
[fd
].flags
& FILE_BINARY
) == 0)
8687 nchars
= crlf_to_lf (nchars
, orig_buffer
);
8688 /* If buffer contains only CR, return that. To be absolutely
8689 sure we should attempt to read the next char, but in
8690 practice a CR to be followed by LF would not appear by
8691 itself in the buffer. */
8692 if (nchars
> 1 && orig_buffer
[nchars
- 1] == 0x0d)
8694 fd_info
[fd
].flags
|= FILE_LAST_CR
;
8700 nchars
= _read (fd
, buffer
, count
);
8705 /* From w32xfns.c */
8706 extern HANDLE interrupt_handle
;
8709 sys_write (int fd
, const void * buffer
, unsigned int count
)
8720 if (fd
< MAXDESC
&& fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
| FILE_SERIAL
))
8722 if ((fd_info
[fd
].flags
& FILE_WRITE
) == 0)
8728 /* Perform text mode translation if required. */
8729 if ((fd_info
[fd
].flags
& FILE_BINARY
) == 0)
8732 const unsigned char * src
= buffer
;
8733 unsigned char * dst
;
8736 SAFE_NALLOCA (tmpbuf
, 2, count
);
8737 dst
= (unsigned char *)tmpbuf
;
8741 unsigned char *next
;
8742 /* Copy next line or remaining bytes. */
8743 next
= _memccpy (dst
, src
, '\n', nbytes
);
8746 /* Copied one line ending with '\n'. */
8747 int copied
= next
- dst
;
8750 /* Insert '\r' before '\n'. */
8757 /* Copied remaining partial line -> now finished. */
8764 if (fd
< MAXDESC
&& fd_info
[fd
].flags
& FILE_SERIAL
)
8766 HANDLE hnd
= (HANDLE
) _get_osfhandle (fd
);
8767 OVERLAPPED
*ovl
= &fd_info
[fd
].cp
->ovl_write
;
8768 HANDLE wait_hnd
[2] = { interrupt_handle
, ovl
->hEvent
};
8771 /* This is async (a.k.a. "overlapped") I/O, so the return value
8772 of FALSE from WriteFile means either an error or the output
8773 will be completed asynchronously (ERROR_IO_PENDING). */
8774 if (!WriteFile (hnd
, buffer
, count
, (DWORD
*) &nchars
, ovl
))
8776 if (GetLastError () != ERROR_IO_PENDING
)
8783 /* Wait for the write to complete, and watch C-g while
8785 if (detect_input_pending ())
8786 active
= MsgWaitForMultipleObjects (2, wait_hnd
, FALSE
,
8787 INFINITE
, QS_ALLINPUT
);
8789 active
= WaitForMultipleObjects (2, wait_hnd
, FALSE
, INFINITE
);
8793 /* User pressed C-g, cancel write, then leave.
8794 Don't bother cleaning up as we may only get stuck
8795 in buggy drivers. */
8796 PurgeComm (hnd
, PURGE_TXABORT
| PURGE_TXCLEAR
);
8798 errno
= EIO
; /* Why not EINTR? */
8801 case WAIT_OBJECT_0
+ 1:
8802 if (!GetOverlappedResult (hnd
, ovl
, (DWORD
*) &nchars
, TRUE
))
8812 else if (fd
< MAXDESC
&& fd_info
[fd
].flags
& FILE_SOCKET
)
8814 unsigned long nblock
= 0;
8815 if (winsock_lib
== NULL
) emacs_abort ();
8817 child_process
*cp
= fd_info
[fd
].cp
;
8819 /* If this is a non-blocking socket whose connection is in
8820 progress or terminated with an error already, return the
8821 proper error code to the caller. */
8822 if (cp
!= NULL
&& (fd_info
[fd
].flags
& FILE_CONNECT
) != 0)
8824 /* In case connection is in progress, ENOTCONN that would
8825 result from calling pfn_send is not what callers expect. */
8826 if (cp
->status
!= STATUS_CONNECT_FAILED
)
8828 errno
= EWOULDBLOCK
;
8831 /* In case connection failed, use the actual error code
8832 stashed by '_sys_wait_connect' in cp->errcode. */
8833 else if (cp
->errcode
!= 0)
8835 pfn_WSASetLastError (cp
->errcode
);
8841 /* TODO: implement select() properly so non-blocking I/O works. */
8842 /* For now, make sure the write blocks. */
8843 if (fd_info
[fd
].flags
& FILE_NDELAY
)
8844 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
8846 nchars
= pfn_send (SOCK_HANDLE (fd
), buffer
, count
, 0);
8848 if (nchars
== SOCKET_ERROR
)
8851 DebPrint (("sys_write.send failed with error %d on socket %ld\n",
8852 pfn_WSAGetLastError (), SOCK_HANDLE (fd
)));
8855 /* Set the socket back to non-blocking if it was before,
8856 for other operations that support it. */
8857 if (fd_info
[fd
].flags
& FILE_NDELAY
)
8860 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
8865 /* Some networked filesystems don't like too large writes, so
8866 break them into smaller chunks. See the Comments section of
8867 the MSDN documentation of WriteFile for details behind the
8868 choice of the value of CHUNK below. See also the thread
8869 http://thread.gmane.org/gmane.comp.version-control.git/145294
8870 in the git mailing list. */
8871 const unsigned char *p
= buffer
;
8872 const bool is_pipe
= (fd
< MAXDESC
8873 && ((fd_info
[fd
].flags
& (FILE_PIPE
| FILE_NDELAY
))
8874 == (FILE_PIPE
| FILE_NDELAY
)));
8875 /* Some programs, notably Node.js's node.exe, seem to never
8876 completely empty the pipe, so writing more than the size of
8877 the pipe's buffer always returns ENOSPC, and we loop forever
8878 between send_process and here. As a workaround, write no
8879 more than the pipe's buffer can hold. */
8880 DWORD pipe_buffer_size
;
8883 if (!GetNamedPipeInfo ((HANDLE
)_get_osfhandle (fd
),
8884 NULL
, &pipe_buffer_size
, NULL
, NULL
))
8886 DebPrint (("GetNamedPipeInfo: error %u\n", GetLastError ()));
8887 pipe_buffer_size
= 4096;
8890 const unsigned chunk
= is_pipe
? pipe_buffer_size
: 30 * 1024 * 1024;
8896 unsigned this_chunk
= count
< chunk
? count
: chunk
;
8897 int n
= _write (fd
, p
, this_chunk
);
8903 /* When there's no buffer space in a pipe that is in the
8904 non-blocking mode, _write returns ENOSPC. We return
8905 EAGAIN instead, which should trigger the logic in
8906 send_process that enters waiting loop and calls
8907 wait_reading_process_output to allow process input to
8908 be accepted during the wait. Those calls to
8909 wait_reading_process_output allow sys_select to
8910 notice when process input becomes available, thus
8911 avoiding deadlock whereby each side of the pipe is
8912 blocked on write, waiting for the other party to read
8913 its end of the pipe. */
8914 if (errno
== ENOSPC
&& is_pipe
)
8920 else if (n
< this_chunk
)
8932 /* Emulation of SIOCGIFCONF and getifaddrs, see process.c. */
8934 /* Return information about network interface IFNAME, or about all
8935 interfaces (if IFNAME is nil). */
8937 network_interface_get_info (Lisp_Object ifname
)
8939 ULONG ainfo_len
= sizeof (IP_ADAPTER_INFO
);
8940 IP_ADAPTER_INFO
*adapter
, *ainfo
= xmalloc (ainfo_len
);
8941 DWORD retval
= get_adapters_info (ainfo
, &ainfo_len
);
8942 Lisp_Object res
= Qnil
;
8944 if (retval
== ERROR_BUFFER_OVERFLOW
)
8946 ainfo
= xrealloc (ainfo
, ainfo_len
);
8947 retval
= get_adapters_info (ainfo
, &ainfo_len
);
8950 if (retval
== ERROR_SUCCESS
)
8952 int eth_count
= 0, tr_count
= 0, fddi_count
= 0, ppp_count
= 0;
8953 int sl_count
= 0, wlan_count
= 0, lo_count
= 0, ifx_count
= 0;
8955 struct sockaddr_in sa
;
8957 /* For the below, we need some winsock functions, so make sure
8958 the winsock DLL is loaded. If we cannot successfully load
8959 it, they will have no use of the information we provide,
8961 if (!winsock_lib
&& !init_winsock (1))
8964 for (adapter
= ainfo
; adapter
; adapter
= adapter
->Next
)
8966 char namebuf
[MAX_ADAPTER_NAME_LENGTH
+ 4];
8968 /* Present Unix-compatible interface names, instead of the
8969 Windows names, which are really GUIDs not readable by
8971 static const char *ifmt
[] = {
8972 "eth%d", "tr%d", "fddi%d", "ppp%d", "sl%d", "wlan%d",
8987 switch (adapter
->Type
)
8989 case MIB_IF_TYPE_ETHERNET
:
8990 /* Windows before Vista reports wireless adapters as
8991 Ethernet. Work around by looking at the Description
8993 if (strstr (adapter
->Description
, "Wireless "))
8996 if_num
= wlan_count
++;
9000 ifmt_idx
= ETHERNET
;
9001 if_num
= eth_count
++;
9004 case MIB_IF_TYPE_TOKENRING
:
9005 ifmt_idx
= TOKENRING
;
9006 if_num
= tr_count
++;
9008 case MIB_IF_TYPE_FDDI
:
9010 if_num
= fddi_count
++;
9012 case MIB_IF_TYPE_PPP
:
9014 if_num
= ppp_count
++;
9016 case MIB_IF_TYPE_SLIP
:
9018 if_num
= sl_count
++;
9020 case IF_TYPE_IEEE80211
:
9022 if_num
= wlan_count
++;
9024 case MIB_IF_TYPE_LOOPBACK
:
9027 ifmt_idx
= LOOPBACK
;
9028 if_num
= lo_count
++;
9034 ifmt_idx
= OTHER_IF
;
9035 if_num
= ifx_count
++;
9038 if (ifmt_idx
== NONE
)
9040 sprintf (namebuf
, ifmt
[ifmt_idx
], if_num
);
9042 sa
.sin_family
= AF_INET
;
9043 ip_addr
= sys_inet_addr (adapter
->IpAddressList
.IpAddress
.String
);
9044 if (ip_addr
== INADDR_NONE
)
9046 /* Bogus address, skip this interface. */
9049 sa
.sin_addr
.s_addr
= ip_addr
;
9052 res
= Fcons (Fcons (build_string (namebuf
),
9053 conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
9054 sizeof (struct sockaddr
))),
9056 else if (strcmp (namebuf
, SSDATA (ifname
)) == 0)
9058 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
9059 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
9060 Lisp_Object flags
= Qnil
;
9064 /* Flags. We guess most of them by type, since the
9065 Windows flags are different and hard to get by. */
9066 flags
= Fcons (intern ("up"), flags
);
9067 if (ifmt_idx
== ETHERNET
|| ifmt_idx
== WLAN
)
9069 flags
= Fcons (intern ("broadcast"), flags
);
9070 flags
= Fcons (intern ("multicast"), flags
);
9072 flags
= Fcons (intern ("running"), flags
);
9073 if (ifmt_idx
== PPP
)
9075 flags
= Fcons (intern ("pointopoint"), flags
);
9076 flags
= Fcons (intern ("noarp"), flags
);
9078 if (adapter
->HaveWins
)
9079 flags
= Fcons (intern ("WINS"), flags
);
9080 if (adapter
->DhcpEnabled
)
9081 flags
= Fcons (intern ("dynamic"), flags
);
9083 res
= Fcons (flags
, res
);
9085 /* Hardware address and its family. */
9086 for (n
= 0; n
< adapter
->AddressLength
; n
++)
9087 p
->contents
[n
] = make_number ((int) adapter
->Address
[n
]);
9088 /* Windows does not support AF_LINK or AF_PACKET family
9089 of addresses. Use an arbitrary family number that is
9090 identical to what GNU/Linux returns. */
9091 res
= Fcons (Fcons (make_number (1), hwaddr
), res
);
9094 sa
.sin_family
= AF_INET
;
9095 net_mask
= sys_inet_addr (adapter
->IpAddressList
.IpMask
.String
);
9096 if (net_mask
!= INADDR_NONE
)
9098 sa
.sin_addr
.s_addr
= net_mask
;
9100 res
= Fcons (conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
9101 sizeof (struct sockaddr
)),
9105 res
= Fcons (Qnil
, res
);
9107 sa
.sin_family
= AF_INET
;
9108 if (ip_addr
!= INADDR_NONE
)
9110 /* Broadcast address is only reported by
9111 GetAdaptersAddresses, which is of limited
9112 availability. Generate it on our own. */
9113 u_long bcast_addr
= (ip_addr
& net_mask
) | ~net_mask
;
9115 sa
.sin_addr
.s_addr
= bcast_addr
;
9117 res
= Fcons (conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
9118 sizeof (struct sockaddr
)),
9122 sa
.sin_addr
.s_addr
= ip_addr
;
9124 res
= Fcons (conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
9125 sizeof (struct sockaddr
)),
9129 res
= Fcons (Qnil
, Fcons (Qnil
, res
));
9132 /* GetAdaptersInfo is documented to not report loopback
9133 interfaces, so we generate one out of thin air. */
9136 sa
.sin_family
= AF_INET
;
9140 sa
.sin_addr
.s_addr
= sys_inet_addr ("127.0.0.1");
9141 res
= Fcons (Fcons (build_string ("lo"),
9142 conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
9143 sizeof (struct sockaddr
))),
9146 else if (strcmp (SSDATA (ifname
), "lo") == 0)
9148 res
= Fcons (Fcons (intern ("running"),
9149 Fcons (intern ("loopback"),
9150 Fcons (intern ("up"), Qnil
))), Qnil
);
9151 /* 772 is what 3 different GNU/Linux systems report for
9152 the loopback interface. */
9153 res
= Fcons (Fcons (make_number (772),
9154 Fmake_vector (make_number (6),
9157 sa
.sin_addr
.s_addr
= sys_inet_addr ("255.0.0.0");
9158 res
= Fcons (conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
9159 sizeof (struct sockaddr
)),
9161 sa
.sin_addr
.s_addr
= sys_inet_addr ("0.0.0.0");
9162 res
= Fcons (conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
9163 sizeof (struct sockaddr
)),
9165 sa
.sin_addr
.s_addr
= sys_inet_addr ("127.0.0.1");
9166 res
= Fcons (conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
9167 sizeof (struct sockaddr
)),
9180 network_interface_list (void)
9182 return network_interface_get_info (Qnil
);
9186 network_interface_info (Lisp_Object ifname
)
9188 CHECK_STRING (ifname
);
9189 return network_interface_get_info (ifname
);
9193 /* The Windows CRT functions are "optimized for speed", so they don't
9194 check for timezone and DST changes if they were last called less
9195 than 1 minute ago (see http://support.microsoft.com/kb/821231). So
9196 all Emacs features that repeatedly call time functions (e.g.,
9197 display-time) are in real danger of missing timezone and DST
9198 changes. Calling tzset before each localtime call fixes that. */
9200 sys_localtime (const time_t *t
)
9203 return localtime (t
);
9208 /* Try loading LIBRARY_ID from the file(s) specified in
9209 Vdynamic_library_alist. If the library is loaded successfully,
9210 return the handle of the DLL, and record the filename in the
9211 property :loaded-from of LIBRARY_ID. If the library could not be
9212 found, or when it was already loaded (because the handle is not
9213 recorded anywhere, and so is lost after use), return NULL.
9215 We could also save the handle in :loaded-from, but currently
9216 there's no use case for it. */
9218 w32_delayed_load (Lisp_Object library_id
)
9220 HMODULE dll_handle
= NULL
;
9222 CHECK_SYMBOL (library_id
);
9224 if (CONSP (Vdynamic_library_alist
)
9225 && NILP (Fassq (library_id
, Vlibrary_cache
)))
9227 Lisp_Object found
= Qnil
;
9228 Lisp_Object dlls
= Fassq (library_id
, Vdynamic_library_alist
);
9231 for (dlls
= XCDR (dlls
); CONSP (dlls
); dlls
= XCDR (dlls
))
9233 Lisp_Object dll
= XCAR (dlls
);
9234 char name
[MAX_UTF8_PATH
];
9238 dll
= ENCODE_FILE (dll
);
9239 if (w32_unicode_filenames
)
9241 wchar_t name_w
[MAX_PATH
];
9243 filename_to_utf16 (SSDATA (dll
), name_w
);
9244 dll_handle
= LoadLibraryW (name_w
);
9247 res
= GetModuleFileNameW (dll_handle
, name_w
,
9250 filename_from_utf16 (name_w
, name
);
9255 char name_a
[MAX_PATH
];
9257 filename_to_ansi (SSDATA (dll
), name_a
);
9258 dll_handle
= LoadLibraryA (name_a
);
9261 res
= GetModuleFileNameA (dll_handle
, name_a
,
9264 filename_from_ansi (name_a
, name
);
9269 ptrdiff_t len
= strlen (name
);
9272 /* Possibly truncated */
9273 ? make_specified_string (name
, -1, len
, 1)
9275 /* This prevents thread start and end notifications
9276 from being sent to the DLL, for every thread we
9277 start. We don't need those notifications because
9278 threads we create never use any of these DLLs, only
9279 the main thread uses them. This is supposed to
9280 speed up thread creation. */
9281 DisableThreadLibraryCalls (dll_handle
);
9286 Fput (library_id
, QCloaded_from
, found
);
9294 check_windows_init_file (void)
9296 /* A common indication that Emacs is not installed properly is when
9297 it cannot find the Windows installation file. If this file does
9298 not exist in the expected place, tell the user. */
9300 if (!noninteractive
&& !inhibit_window_system
9301 /* Vload_path is not yet initialized when we are loading
9303 && NILP (Vpurify_flag
))
9305 Lisp_Object init_file
;
9308 /* Implementation note: this function runs early during Emacs
9309 startup, before startup.el is run. So Vload_path is still in
9310 its initial unibyte form, but it holds UTF-8 encoded file
9311 names, since init_callproc was already called. So we do not
9312 need to ENCODE_FILE here, but we do need to convert the file
9313 names from UTF-8 to ANSI. */
9314 init_file
= build_string ("term/w32-win");
9315 fd
= openp (Vload_path
, init_file
, Fget_load_suffixes (), NULL
, Qnil
, 0);
9318 Lisp_Object load_path_print
= Fprin1_to_string (Vload_path
, Qnil
);
9319 char *init_file_name
= SSDATA (init_file
);
9320 char *load_path
= SSDATA (load_path_print
);
9321 char *buffer
= alloca (1024
9322 + strlen (init_file_name
)
9323 + strlen (load_path
));
9328 "The Emacs Windows initialization file \"%s.el\" "
9329 "could not be found in your Emacs installation. "
9330 "Emacs checked the following directories for this file:\n"
9332 "When Emacs cannot find this file, it usually means that it "
9333 "was not installed properly, or its distribution file was "
9334 "not unpacked properly.\nSee the README.W32 file in the "
9335 "top-level Emacs directory for more information.",
9336 init_file_name
, load_path
);
9337 needed
= pMultiByteToWideChar (CP_UTF8
, multiByteToWideCharFlags
,
9338 buffer
, -1, NULL
, 0);
9341 wchar_t *msg_w
= alloca ((needed
+ 1) * sizeof (wchar_t));
9343 pMultiByteToWideChar (CP_UTF8
, multiByteToWideCharFlags
, buffer
,
9345 needed
= pWideCharToMultiByte (CP_ACP
, 0, msg_w
, -1,
9346 NULL
, 0, NULL
, NULL
);
9349 char *msg_a
= alloca (needed
+ 1);
9351 pWideCharToMultiByte (CP_ACP
, 0, msg_w
, -1, msg_a
, needed
,
9358 "Emacs Abort Dialog",
9359 MB_OK
| MB_ICONEXCLAMATION
| MB_TASKMODAL
);
9360 /* Use the low-level system abort. */
9371 term_ntproc (int ignored
)
9377 /* shutdown the socket interface if necessary */
9384 init_ntproc (int dumping
)
9386 sigset_t initial_mask
= 0;
9388 /* Initialize the socket interface now if available and requested by
9389 the user by defining PRELOAD_WINSOCK; otherwise loading will be
9390 delayed until open-network-stream is called (w32-has-winsock can
9391 also be used to dynamically load or reload winsock).
9393 Conveniently, init_environment is called before us, so
9394 PRELOAD_WINSOCK can be set in the registry. */
9396 /* Always initialize this correctly. */
9399 if (getenv ("PRELOAD_WINSOCK") != NULL
)
9400 init_winsock (TRUE
);
9402 /* Initial preparation for subprocess support: replace our standard
9403 handles with non-inheritable versions. */
9406 HANDLE stdin_save
= INVALID_HANDLE_VALUE
;
9407 HANDLE stdout_save
= INVALID_HANDLE_VALUE
;
9408 HANDLE stderr_save
= INVALID_HANDLE_VALUE
;
9410 parent
= GetCurrentProcess ();
9412 /* ignore errors when duplicating and closing; typically the
9413 handles will be invalid when running as a gui program. */
9414 DuplicateHandle (parent
,
9415 GetStdHandle (STD_INPUT_HANDLE
),
9420 DUPLICATE_SAME_ACCESS
);
9422 DuplicateHandle (parent
,
9423 GetStdHandle (STD_OUTPUT_HANDLE
),
9428 DUPLICATE_SAME_ACCESS
);
9430 DuplicateHandle (parent
,
9431 GetStdHandle (STD_ERROR_HANDLE
),
9436 DUPLICATE_SAME_ACCESS
);
9442 if (stdin_save
!= INVALID_HANDLE_VALUE
)
9443 _open_osfhandle ((intptr_t) stdin_save
, O_TEXT
);
9445 _open ("nul", O_TEXT
| O_NOINHERIT
| O_RDONLY
);
9448 if (stdout_save
!= INVALID_HANDLE_VALUE
)
9449 _open_osfhandle ((intptr_t) stdout_save
, O_TEXT
);
9451 _open ("nul", O_TEXT
| O_NOINHERIT
| O_WRONLY
);
9454 if (stderr_save
!= INVALID_HANDLE_VALUE
)
9455 _open_osfhandle ((intptr_t) stderr_save
, O_TEXT
);
9457 _open ("nul", O_TEXT
| O_NOINHERIT
| O_WRONLY
);
9461 /* unfortunately, atexit depends on implementation of malloc */
9462 /* atexit (term_ntproc); */
9465 /* Make sure we start with all signals unblocked. */
9466 sigprocmask (SIG_SETMASK
, &initial_mask
, NULL
);
9467 signal (SIGABRT
, term_ntproc
);
9471 /* determine which drives are fixed, for GetCachedVolumeInformation */
9473 /* GetDriveType must have trailing backslash. */
9474 char drive
[] = "A:\\";
9476 /* Loop over all possible drive letters */
9477 while (*drive
<= 'Z')
9479 /* Record if this drive letter refers to a fixed drive. */
9480 fixed_drives
[DRIVE_INDEX (*drive
)] =
9481 (GetDriveType (drive
) == DRIVE_FIXED
);
9486 /* Reset the volume info cache. */
9487 volume_cache
= NULL
;
9492 shutdown_handler ensures that buffers' autosave files are
9493 up to date when the user logs off, or the system shuts down.
9496 shutdown_handler (DWORD type
)
9498 /* Ctrl-C and Ctrl-Break are already suppressed, so don't handle them. */
9499 if (type
== CTRL_CLOSE_EVENT
/* User closes console window. */
9500 || type
== CTRL_LOGOFF_EVENT
/* User logs off. */
9501 || type
== CTRL_SHUTDOWN_EVENT
) /* User shutsdown. */
9503 /* Shut down cleanly, making sure autosave files are up to date. */
9504 shut_down_emacs (0, Qnil
);
9507 /* Allow other handlers to handle this signal. */
9511 /* On Windows 9X, load UNICOWS.DLL and return its handle, or die. On
9512 NT, return a handle to GDI32.DLL. */
9514 maybe_load_unicows_dll (void)
9516 if (os_subtype
== OS_9X
)
9518 HANDLE ret
= LoadLibrary ("Unicows.dll");
9521 /* These two functions are present on Windows 9X as stubs
9522 that always fail. We need the real implementations from
9523 UNICOWS.DLL, so we must call these functions through
9524 pointers, and assign the correct addresses to these
9525 pointers at program startup (see emacs.c, which calls
9526 this function early on). */
9527 pMultiByteToWideChar
=
9528 (MultiByteToWideChar_Proc
)GetProcAddress (ret
, "MultiByteToWideChar");
9529 pWideCharToMultiByte
=
9530 (WideCharToMultiByte_Proc
)GetProcAddress (ret
, "WideCharToMultiByte");
9531 multiByteToWideCharFlags
= MB_ERR_INVALID_CHARS
;
9538 button
= MessageBox (NULL
,
9539 "Emacs cannot load the UNICOWS.DLL library.\n"
9540 "This library is essential for using Emacs\n"
9541 "on this system. You need to install it.\n\n"
9542 "Emacs will exit when you click OK.",
9543 "Emacs cannot load UNICOWS.DLL",
9544 MB_ICONERROR
| MB_TASKMODAL
9545 | MB_SETFOREGROUND
| MB_OK
);
9556 /* On NT family of Windows, these two functions are always
9557 linked in, so we just assign their addresses to the 2
9558 pointers; no need for the LoadLibrary dance. */
9559 pMultiByteToWideChar
= MultiByteToWideChar
;
9560 pWideCharToMultiByte
= WideCharToMultiByte
;
9561 /* On NT 4.0, though, MB_ERR_INVALID_CHARS is not supported. */
9562 if (w32_major_version
< 5)
9563 multiByteToWideCharFlags
= 0;
9565 multiByteToWideCharFlags
= MB_ERR_INVALID_CHARS
;
9566 return LoadLibrary ("Gdi32.dll");
9571 globals_of_w32 is used to initialize those global variables that
9572 must always be initialized on startup even when the global variable
9573 initialized is non zero (see the function main in emacs.c).
9576 globals_of_w32 (void)
9578 HMODULE kernel32
= GetModuleHandle ("kernel32.dll");
9580 get_process_times_fn
= (GetProcessTimes_Proc
)
9581 GetProcAddress (kernel32
, "GetProcessTimes");
9583 DEFSYM (QCloaded_from
, ":loaded-from");
9585 g_b_init_is_windows_9x
= 0;
9586 g_b_init_open_process_token
= 0;
9587 g_b_init_get_token_information
= 0;
9588 g_b_init_lookup_account_sid
= 0;
9589 g_b_init_get_sid_sub_authority
= 0;
9590 g_b_init_get_sid_sub_authority_count
= 0;
9591 g_b_init_get_security_info
= 0;
9592 g_b_init_get_file_security_w
= 0;
9593 g_b_init_get_file_security_a
= 0;
9594 g_b_init_get_security_descriptor_owner
= 0;
9595 g_b_init_get_security_descriptor_group
= 0;
9596 g_b_init_is_valid_sid
= 0;
9597 g_b_init_create_toolhelp32_snapshot
= 0;
9598 g_b_init_process32_first
= 0;
9599 g_b_init_process32_next
= 0;
9600 g_b_init_open_thread_token
= 0;
9601 g_b_init_impersonate_self
= 0;
9602 g_b_init_revert_to_self
= 0;
9603 g_b_init_get_process_memory_info
= 0;
9604 g_b_init_get_process_working_set_size
= 0;
9605 g_b_init_global_memory_status
= 0;
9606 g_b_init_global_memory_status_ex
= 0;
9607 g_b_init_equal_sid
= 0;
9608 g_b_init_copy_sid
= 0;
9609 g_b_init_get_length_sid
= 0;
9610 g_b_init_get_native_system_info
= 0;
9611 g_b_init_get_system_times
= 0;
9612 g_b_init_create_symbolic_link_w
= 0;
9613 g_b_init_create_symbolic_link_a
= 0;
9614 g_b_init_get_security_descriptor_dacl
= 0;
9615 g_b_init_convert_sd_to_sddl
= 0;
9616 g_b_init_convert_sddl_to_sd
= 0;
9617 g_b_init_is_valid_security_descriptor
= 0;
9618 g_b_init_set_file_security_w
= 0;
9619 g_b_init_set_file_security_a
= 0;
9620 g_b_init_set_named_security_info_w
= 0;
9621 g_b_init_set_named_security_info_a
= 0;
9622 g_b_init_get_adapters_info
= 0;
9623 g_b_init_compare_string_w
= 0;
9624 num_of_processors
= 0;
9625 /* The following sets a handler for shutdown notifications for
9626 console apps. This actually applies to Emacs in both console and
9627 GUI modes, since we had to fool windows into thinking emacs is a
9628 console application to get console mode to work. */
9629 SetConsoleCtrlHandler (shutdown_handler
, TRUE
);
9631 /* "None" is the default group name on standalone workstations. */
9632 strcpy (dflt_group_name
, "None");
9634 /* Reset, in case it has some value inherited from dump time. */
9635 w32_stat_get_owner_group
= 0;
9637 /* If w32_unicode_filenames is non-zero, we will be using Unicode
9638 (a.k.a. "wide") APIs to invoke functions that accept file
9640 if (is_windows_9x ())
9641 w32_unicode_filenames
= 0;
9643 w32_unicode_filenames
= 1;
9646 dynlib_reset_last_error ();
9649 w32_crypto_hprov
= (HCRYPTPROV
)0;
9652 /* For make-serial-process */
9654 serial_open (Lisp_Object port_obj
)
9656 char *port
= SSDATA (port_obj
);
9661 hnd
= CreateFile (port
, GENERIC_READ
| GENERIC_WRITE
, 0, 0,
9662 OPEN_EXISTING
, FILE_FLAG_OVERLAPPED
, 0);
9663 if (hnd
== INVALID_HANDLE_VALUE
)
9664 error ("Could not open %s", port
);
9665 fd
= (int) _open_osfhandle ((intptr_t) hnd
, 0);
9667 error ("Could not open %s", port
);
9671 error ("Could not create child process");
9673 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
9674 fd_info
[ fd
].hnd
= hnd
;
9675 fd_info
[ fd
].flags
|=
9676 FILE_READ
| FILE_WRITE
| FILE_BINARY
| FILE_SERIAL
;
9677 if (fd_info
[ fd
].cp
!= NULL
)
9679 error ("fd_info[fd = %d] is already in use", fd
);
9681 fd_info
[ fd
].cp
= cp
;
9682 cp
->ovl_read
.hEvent
= CreateEvent (NULL
, TRUE
, FALSE
, NULL
);
9683 if (cp
->ovl_read
.hEvent
== NULL
)
9684 error ("Could not create read event");
9685 cp
->ovl_write
.hEvent
= CreateEvent (NULL
, TRUE
, FALSE
, NULL
);
9686 if (cp
->ovl_write
.hEvent
== NULL
)
9687 error ("Could not create write event");
9692 /* For serial-process-configure */
9694 serial_configure (struct Lisp_Process
*p
, Lisp_Object contact
)
9696 Lisp_Object childp2
= Qnil
;
9697 Lisp_Object tem
= Qnil
;
9701 char summary
[4] = "???"; /* This usually becomes "8N1". */
9703 if ((fd_info
[ p
->outfd
].flags
& FILE_SERIAL
) == 0)
9704 error ("Not a serial process");
9705 hnd
= fd_info
[ p
->outfd
].hnd
;
9707 childp2
= Fcopy_sequence (p
->childp
);
9709 /* Initialize timeouts for blocking read and blocking write. */
9710 if (!GetCommTimeouts (hnd
, &ct
))
9711 error ("GetCommTimeouts() failed");
9712 ct
.ReadIntervalTimeout
= 0;
9713 ct
.ReadTotalTimeoutMultiplier
= 0;
9714 ct
.ReadTotalTimeoutConstant
= 0;
9715 ct
.WriteTotalTimeoutMultiplier
= 0;
9716 ct
.WriteTotalTimeoutConstant
= 0;
9717 if (!SetCommTimeouts (hnd
, &ct
))
9718 error ("SetCommTimeouts() failed");
9719 /* Read port attributes and prepare default configuration. */
9720 memset (&dcb
, 0, sizeof (dcb
));
9721 dcb
.DCBlength
= sizeof (DCB
);
9722 if (!GetCommState (hnd
, &dcb
))
9723 error ("GetCommState() failed");
9726 dcb
.fAbortOnError
= FALSE
;
9727 /* dcb.XonLim and dcb.XoffLim are set by GetCommState() */
9732 /* Configure speed. */
9733 if (!NILP (Fplist_member (contact
, QCspeed
)))
9734 tem
= Fplist_get (contact
, QCspeed
);
9736 tem
= Fplist_get (p
->childp
, QCspeed
);
9738 dcb
.BaudRate
= XINT (tem
);
9739 childp2
= Fplist_put (childp2
, QCspeed
, tem
);
9741 /* Configure bytesize. */
9742 if (!NILP (Fplist_member (contact
, QCbytesize
)))
9743 tem
= Fplist_get (contact
, QCbytesize
);
9745 tem
= Fplist_get (p
->childp
, QCbytesize
);
9747 tem
= make_number (8);
9749 if (XINT (tem
) != 7 && XINT (tem
) != 8)
9750 error (":bytesize must be nil (8), 7, or 8");
9751 dcb
.ByteSize
= XINT (tem
);
9752 summary
[0] = XINT (tem
) + '0';
9753 childp2
= Fplist_put (childp2
, QCbytesize
, tem
);
9755 /* Configure parity. */
9756 if (!NILP (Fplist_member (contact
, QCparity
)))
9757 tem
= Fplist_get (contact
, QCparity
);
9759 tem
= Fplist_get (p
->childp
, QCparity
);
9760 if (!NILP (tem
) && !EQ (tem
, Qeven
) && !EQ (tem
, Qodd
))
9761 error (":parity must be nil (no parity), `even', or `odd'");
9762 dcb
.fParity
= FALSE
;
9763 dcb
.Parity
= NOPARITY
;
9764 dcb
.fErrorChar
= FALSE
;
9769 else if (EQ (tem
, Qeven
))
9773 dcb
.Parity
= EVENPARITY
;
9774 dcb
.fErrorChar
= TRUE
;
9776 else if (EQ (tem
, Qodd
))
9780 dcb
.Parity
= ODDPARITY
;
9781 dcb
.fErrorChar
= TRUE
;
9783 childp2
= Fplist_put (childp2
, QCparity
, tem
);
9785 /* Configure stopbits. */
9786 if (!NILP (Fplist_member (contact
, QCstopbits
)))
9787 tem
= Fplist_get (contact
, QCstopbits
);
9789 tem
= Fplist_get (p
->childp
, QCstopbits
);
9791 tem
= make_number (1);
9793 if (XINT (tem
) != 1 && XINT (tem
) != 2)
9794 error (":stopbits must be nil (1 stopbit), 1, or 2");
9795 summary
[2] = XINT (tem
) + '0';
9796 if (XINT (tem
) == 1)
9797 dcb
.StopBits
= ONESTOPBIT
;
9798 else if (XINT (tem
) == 2)
9799 dcb
.StopBits
= TWOSTOPBITS
;
9800 childp2
= Fplist_put (childp2
, QCstopbits
, tem
);
9802 /* Configure flowcontrol. */
9803 if (!NILP (Fplist_member (contact
, QCflowcontrol
)))
9804 tem
= Fplist_get (contact
, QCflowcontrol
);
9806 tem
= Fplist_get (p
->childp
, QCflowcontrol
);
9807 if (!NILP (tem
) && !EQ (tem
, Qhw
) && !EQ (tem
, Qsw
))
9808 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
9809 dcb
.fOutxCtsFlow
= FALSE
;
9810 dcb
.fOutxDsrFlow
= FALSE
;
9811 dcb
.fDtrControl
= DTR_CONTROL_DISABLE
;
9812 dcb
.fDsrSensitivity
= FALSE
;
9813 dcb
.fTXContinueOnXoff
= FALSE
;
9816 dcb
.fRtsControl
= RTS_CONTROL_DISABLE
;
9817 dcb
.XonChar
= 17; /* Control-Q */
9818 dcb
.XoffChar
= 19; /* Control-S */
9821 /* Already configured. */
9823 else if (EQ (tem
, Qhw
))
9825 dcb
.fRtsControl
= RTS_CONTROL_HANDSHAKE
;
9826 dcb
.fOutxCtsFlow
= TRUE
;
9828 else if (EQ (tem
, Qsw
))
9833 childp2
= Fplist_put (childp2
, QCflowcontrol
, tem
);
9835 /* Activate configuration. */
9836 if (!SetCommState (hnd
, &dcb
))
9837 error ("SetCommState() failed");
9839 childp2
= Fplist_put (childp2
, QCsummary
, build_string (summary
));
9840 pset_childp (p
, childp2
);
9843 /* For make-pipe-process */
9845 register_aux_fd (int infd
)
9851 error ("Could not create child process");
9853 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
9855 if (fd_info
[ infd
].cp
!= NULL
)
9857 error ("fd_info[fd = %d] is already in use", infd
);
9859 fd_info
[ infd
].cp
= cp
;
9860 fd_info
[ infd
].hnd
= (HANDLE
) _get_osfhandle (infd
);
9866 emacs_gnutls_pull (gnutls_transport_ptr_t p
, void* buf
, size_t sz
)
9869 struct Lisp_Process
*process
= (struct Lisp_Process
*)p
;
9870 int fd
= process
->infd
;
9872 n
= sys_read (fd
, (char*)buf
, sz
);
9879 /* Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
9880 if (err
== EWOULDBLOCK
)
9883 emacs_gnutls_transport_set_errno (process
->gnutls_state
, err
);
9889 emacs_gnutls_push (gnutls_transport_ptr_t p
, const void* buf
, size_t sz
)
9891 struct Lisp_Process
*process
= (struct Lisp_Process
*)p
;
9892 int fd
= process
->outfd
;
9893 ssize_t n
= sys_write (fd
, buf
, sz
);
9895 /* 0 or more bytes written means everything went fine. */
9899 /* Negative bytes written means we got an error in errno.
9900 Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
9901 emacs_gnutls_transport_set_errno (process
->gnutls_state
,
9902 errno
== EWOULDBLOCK
? EAGAIN
: errno
);
9906 #endif /* HAVE_GNUTLS */