1 /* Utility and Unix shadow routines for GNU Emacs on the Microsoft Windows API.
3 Copyright (C) 1994-1995, 2000-2014 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
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
21 Geoff Voelker (voelker@cs.washington.edu) 7-29-94
24 #include <mingw_time.h>
25 #include <stddef.h> /* for offsetof */
28 #include <float.h> /* for DBL_EPSILON */
35 #include <time.h> /* must be before nt/inc/sys/time.h, for MinGW64 */
37 #include <sys/utime.h>
40 /* must include CRT headers *before* config.h */
43 #include <mbstring.h> /* for _mbspbrk, _mbslwr, _mbsrchr, ... */
70 #include "epaths.h" /* for SHELL */
75 /* MinGW64 (_W64) defines these in its _mingw.h. */
76 #if defined(__GNUC__) && !defined(_W64)
77 #define _ANONYMOUS_UNION
78 #define _ANONYMOUS_STRUCT
81 /* Some versions of compiler define MEMORYSTATUSEX, some don't, so we
82 use a different name to avoid compilation problems. */
83 typedef struct _MEMORY_STATUS_EX
{
86 DWORDLONG ullTotalPhys
;
87 DWORDLONG ullAvailPhys
;
88 DWORDLONG ullTotalPageFile
;
89 DWORDLONG ullAvailPageFile
;
90 DWORDLONG ullTotalVirtual
;
91 DWORDLONG ullAvailVirtual
;
92 DWORDLONG ullAvailExtendedVirtual
;
93 } MEMORY_STATUS_EX
,*LPMEMORY_STATUS_EX
;
95 /* These are here so that GDB would know about these data types. This
96 allows to attach GDB to Emacs when a fatal exception is triggered
97 and Windows pops up the "application needs to be closed" dialog.
98 At that point, _gnu_exception_handler, the top-level exception
99 handler installed by the MinGW startup code, is somewhere on the
100 call-stack of the main thread, so going to that call frame and
101 looking at the argument to _gnu_exception_handler, which is a
102 PEXCEPTION_POINTERS pointer, can reveal the exception code
103 (excptr->ExceptionRecord->ExceptionCode) and the address where the
104 exception happened (excptr->ExceptionRecord->ExceptionAddress), as
105 well as some additional information specific to the exception. */
106 PEXCEPTION_POINTERS excptr
;
107 PEXCEPTION_RECORD excprec
;
113 #include <tlhelp32.h>
118 #if _WIN32_WINNT < 0x0500
119 #if !defined (__MINGW32__) || __W32API_MAJOR_VERSION < 3 || (__W32API_MAJOR_VERSION == 3 && __W32API_MINOR_VERSION < 15)
120 /* This either is not in psapi.h or guarded by higher value of
121 _WIN32_WINNT than what we use. w32api supplied with MinGW 3.15
122 defines it in psapi.h */
123 typedef struct _PROCESS_MEMORY_COUNTERS_EX
{
125 DWORD PageFaultCount
;
126 SIZE_T PeakWorkingSetSize
;
127 SIZE_T WorkingSetSize
;
128 SIZE_T QuotaPeakPagedPoolUsage
;
129 SIZE_T QuotaPagedPoolUsage
;
130 SIZE_T QuotaPeakNonPagedPoolUsage
;
131 SIZE_T QuotaNonPagedPoolUsage
;
132 SIZE_T PagefileUsage
;
133 SIZE_T PeakPagefileUsage
;
135 } PROCESS_MEMORY_COUNTERS_EX
,*PPROCESS_MEMORY_COUNTERS_EX
;
139 #include <winioctl.h>
146 /* This is not in MinGW's sddl.h (but they are in MSVC headers), so we
147 define them by hand if not already defined. */
148 #ifndef SDDL_REVISION_1
149 #define SDDL_REVISION_1 1
150 #endif /* SDDL_REVISION_1 */
152 #if defined(_MSC_VER) || defined(_W64)
153 /* MSVC and MinGW64 don't provide the definition of
154 REPARSE_DATA_BUFFER and the associated macros, except on ntifs.h,
155 which cannot be included because it triggers conflicts with other
156 Windows API headers. So we define it here by hand. */
158 typedef struct _REPARSE_DATA_BUFFER
{
160 USHORT ReparseDataLength
;
164 USHORT SubstituteNameOffset
;
165 USHORT SubstituteNameLength
;
166 USHORT PrintNameOffset
;
167 USHORT PrintNameLength
;
170 } SymbolicLinkReparseBuffer
;
172 USHORT SubstituteNameOffset
;
173 USHORT SubstituteNameLength
;
174 USHORT PrintNameOffset
;
175 USHORT PrintNameLength
;
177 } MountPointReparseBuffer
;
180 } GenericReparseBuffer
;
182 } REPARSE_DATA_BUFFER
, *PREPARSE_DATA_BUFFER
;
184 #ifndef FILE_DEVICE_FILE_SYSTEM
185 #define FILE_DEVICE_FILE_SYSTEM 9
187 #ifndef METHOD_BUFFERED
188 #define METHOD_BUFFERED 0
190 #ifndef FILE_ANY_ACCESS
191 #define FILE_ANY_ACCESS 0x00000000
194 #define CTL_CODE(t,f,m,a) (((t)<<16)|((a)<<14)|((f)<<2)|(m))
196 /* MinGW64 defines FSCTL_GET_REPARSE_POINT on winioctl.h. */
197 #ifndef FSCTL_GET_REPARSE_POINT
198 #define FSCTL_GET_REPARSE_POINT \
199 CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 42, METHOD_BUFFERED, FILE_ANY_ACCESS)
203 /* TCP connection support. */
204 #include <sys/socket.h>
223 #include <iphlpapi.h> /* should be after winsock2.h */
227 #include "w32common.h"
229 #include "w32select.h"
231 #include "dispextern.h" /* for xstrcasecmp */
232 #include "coding.h" /* for Vlocale_coding_system */
234 #include "careadlinkat.h"
235 #include "allocator.h"
237 /* For serial_configure and serial_open. */
240 typedef HRESULT (WINAPI
* ShGetFolderPath_fn
)
241 (IN HWND
, IN
int, IN HANDLE
, IN DWORD
, OUT
char *);
243 Lisp_Object QCloaded_from
;
245 void globals_of_w32 (void);
246 static DWORD
get_rid (PSID
);
247 static int is_symlink (const char *);
248 static char * chase_symlinks (const char *);
249 static int enable_privilege (LPCTSTR
, BOOL
, TOKEN_PRIVILEGES
*);
250 static int restore_privilege (TOKEN_PRIVILEGES
*);
251 static BOOL WINAPI
revert_to_self (void);
253 static int sys_access (const char *, int);
254 extern void *e_malloc (size_t);
255 extern int sys_select (int, SELECT_TYPE
*, SELECT_TYPE
*, SELECT_TYPE
*,
256 struct timespec
*, void *);
257 extern int sys_dup (int);
262 /* Initialization states.
264 WARNING: If you add any more such variables for additional APIs,
265 you MUST add initialization for them to globals_of_w32
266 below. This is because these variables might get set
267 to non-NULL values during dumping, but the dumped Emacs
268 cannot reuse those values, because it could be run on a
269 different version of the OS, where API addresses are
271 static BOOL g_b_init_is_windows_9x
;
272 static BOOL g_b_init_open_process_token
;
273 static BOOL g_b_init_get_token_information
;
274 static BOOL g_b_init_lookup_account_sid
;
275 static BOOL g_b_init_get_sid_sub_authority
;
276 static BOOL g_b_init_get_sid_sub_authority_count
;
277 static BOOL g_b_init_get_security_info
;
278 static BOOL g_b_init_get_file_security_w
;
279 static BOOL g_b_init_get_file_security_a
;
280 static BOOL g_b_init_get_security_descriptor_owner
;
281 static BOOL g_b_init_get_security_descriptor_group
;
282 static BOOL g_b_init_is_valid_sid
;
283 static BOOL g_b_init_create_toolhelp32_snapshot
;
284 static BOOL g_b_init_process32_first
;
285 static BOOL g_b_init_process32_next
;
286 static BOOL g_b_init_open_thread_token
;
287 static BOOL g_b_init_impersonate_self
;
288 static BOOL g_b_init_revert_to_self
;
289 static BOOL g_b_init_get_process_memory_info
;
290 static BOOL g_b_init_get_process_working_set_size
;
291 static BOOL g_b_init_global_memory_status
;
292 static BOOL g_b_init_global_memory_status_ex
;
293 static BOOL g_b_init_get_length_sid
;
294 static BOOL g_b_init_equal_sid
;
295 static BOOL g_b_init_copy_sid
;
296 static BOOL g_b_init_get_native_system_info
;
297 static BOOL g_b_init_get_system_times
;
298 static BOOL g_b_init_create_symbolic_link_w
;
299 static BOOL g_b_init_create_symbolic_link_a
;
300 static BOOL g_b_init_get_security_descriptor_dacl
;
301 static BOOL g_b_init_convert_sd_to_sddl
;
302 static BOOL g_b_init_convert_sddl_to_sd
;
303 static BOOL g_b_init_is_valid_security_descriptor
;
304 static BOOL g_b_init_set_file_security_w
;
305 static BOOL g_b_init_set_file_security_a
;
306 static BOOL g_b_init_set_named_security_info_w
;
307 static BOOL g_b_init_set_named_security_info_a
;
308 static BOOL g_b_init_get_adapters_info
;
311 BEGIN: Wrapper functions around OpenProcessToken
312 and other functions in advapi32.dll that are only
313 supported in Windows NT / 2k / XP
315 /* ** Function pointer typedefs ** */
316 typedef BOOL (WINAPI
* OpenProcessToken_Proc
) (
317 HANDLE ProcessHandle
,
319 PHANDLE TokenHandle
);
320 typedef BOOL (WINAPI
* GetTokenInformation_Proc
) (
322 TOKEN_INFORMATION_CLASS TokenInformationClass
,
323 LPVOID TokenInformation
,
324 DWORD TokenInformationLength
,
325 PDWORD ReturnLength
);
326 typedef BOOL (WINAPI
* GetProcessTimes_Proc
) (
327 HANDLE process_handle
,
328 LPFILETIME creation_time
,
329 LPFILETIME exit_time
,
330 LPFILETIME kernel_time
,
331 LPFILETIME user_time
);
333 GetProcessTimes_Proc get_process_times_fn
= NULL
;
336 const char * const LookupAccountSid_Name
= "LookupAccountSidW";
338 const char * const LookupAccountSid_Name
= "LookupAccountSidA";
340 typedef BOOL (WINAPI
* LookupAccountSid_Proc
) (
341 LPCTSTR lpSystemName
,
346 LPDWORD cbDomainName
,
347 PSID_NAME_USE peUse
);
348 typedef PDWORD (WINAPI
* GetSidSubAuthority_Proc
) (
351 typedef PUCHAR (WINAPI
* GetSidSubAuthorityCount_Proc
) (
353 typedef DWORD (WINAPI
* GetSecurityInfo_Proc
) (
355 SE_OBJECT_TYPE ObjectType
,
356 SECURITY_INFORMATION SecurityInfo
,
361 PSECURITY_DESCRIPTOR
*ppSecurityDescriptor
);
362 typedef BOOL (WINAPI
* GetFileSecurityW_Proc
) (
364 SECURITY_INFORMATION RequestedInformation
,
365 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
367 LPDWORD lpnLengthNeeded
);
368 typedef BOOL (WINAPI
* GetFileSecurityA_Proc
) (
370 SECURITY_INFORMATION RequestedInformation
,
371 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
373 LPDWORD lpnLengthNeeded
);
374 typedef BOOL (WINAPI
*SetFileSecurityW_Proc
) (
376 SECURITY_INFORMATION SecurityInformation
,
377 PSECURITY_DESCRIPTOR pSecurityDescriptor
);
378 typedef BOOL (WINAPI
*SetFileSecurityA_Proc
) (
380 SECURITY_INFORMATION SecurityInformation
,
381 PSECURITY_DESCRIPTOR pSecurityDescriptor
);
382 typedef DWORD (WINAPI
*SetNamedSecurityInfoW_Proc
) (
383 LPCWSTR lpObjectName
,
384 SE_OBJECT_TYPE ObjectType
,
385 SECURITY_INFORMATION SecurityInformation
,
390 typedef DWORD (WINAPI
*SetNamedSecurityInfoA_Proc
) (
392 SE_OBJECT_TYPE ObjectType
,
393 SECURITY_INFORMATION SecurityInformation
,
398 typedef BOOL (WINAPI
* GetSecurityDescriptorOwner_Proc
) (
399 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
401 LPBOOL lpbOwnerDefaulted
);
402 typedef BOOL (WINAPI
* GetSecurityDescriptorGroup_Proc
) (
403 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
405 LPBOOL lpbGroupDefaulted
);
406 typedef BOOL (WINAPI
*GetSecurityDescriptorDacl_Proc
) (
407 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
408 LPBOOL lpbDaclPresent
,
410 LPBOOL lpbDaclDefaulted
);
411 typedef BOOL (WINAPI
* IsValidSid_Proc
) (
413 typedef HANDLE (WINAPI
* CreateToolhelp32Snapshot_Proc
) (
415 DWORD th32ProcessID
);
416 typedef BOOL (WINAPI
* Process32First_Proc
) (
418 LPPROCESSENTRY32 lppe
);
419 typedef BOOL (WINAPI
* Process32Next_Proc
) (
421 LPPROCESSENTRY32 lppe
);
422 typedef BOOL (WINAPI
* OpenThreadToken_Proc
) (
426 PHANDLE TokenHandle
);
427 typedef BOOL (WINAPI
* ImpersonateSelf_Proc
) (
428 SECURITY_IMPERSONATION_LEVEL ImpersonationLevel
);
429 typedef BOOL (WINAPI
* RevertToSelf_Proc
) (void);
430 typedef BOOL (WINAPI
* GetProcessMemoryInfo_Proc
) (
432 PPROCESS_MEMORY_COUNTERS ppsmemCounters
,
434 typedef BOOL (WINAPI
* GetProcessWorkingSetSize_Proc
) (
436 PSIZE_T lpMinimumWorkingSetSize
,
437 PSIZE_T lpMaximumWorkingSetSize
);
438 typedef BOOL (WINAPI
* GlobalMemoryStatus_Proc
) (
439 LPMEMORYSTATUS lpBuffer
);
440 typedef BOOL (WINAPI
* GlobalMemoryStatusEx_Proc
) (
441 LPMEMORY_STATUS_EX lpBuffer
);
442 typedef BOOL (WINAPI
* CopySid_Proc
) (
443 DWORD nDestinationSidLength
,
444 PSID pDestinationSid
,
446 typedef BOOL (WINAPI
* EqualSid_Proc
) (
449 typedef DWORD (WINAPI
* GetLengthSid_Proc
) (
451 typedef void (WINAPI
* GetNativeSystemInfo_Proc
) (
452 LPSYSTEM_INFO lpSystemInfo
);
453 typedef BOOL (WINAPI
* GetSystemTimes_Proc
) (
454 LPFILETIME lpIdleTime
,
455 LPFILETIME lpKernelTime
,
456 LPFILETIME lpUserTime
);
457 typedef BOOLEAN (WINAPI
*CreateSymbolicLinkW_Proc
) (
458 LPCWSTR lpSymlinkFileName
,
459 LPCWSTR lpTargetFileName
,
461 typedef BOOLEAN (WINAPI
*CreateSymbolicLinkA_Proc
) (
462 LPCSTR lpSymlinkFileName
,
463 LPCSTR lpTargetFileName
,
465 typedef BOOL (WINAPI
*ConvertStringSecurityDescriptorToSecurityDescriptor_Proc
) (
466 LPCTSTR StringSecurityDescriptor
,
467 DWORD StringSDRevision
,
468 PSECURITY_DESCRIPTOR
*SecurityDescriptor
,
469 PULONG SecurityDescriptorSize
);
470 typedef BOOL (WINAPI
*ConvertSecurityDescriptorToStringSecurityDescriptor_Proc
) (
471 PSECURITY_DESCRIPTOR SecurityDescriptor
,
472 DWORD RequestedStringSDRevision
,
473 SECURITY_INFORMATION SecurityInformation
,
474 LPTSTR
*StringSecurityDescriptor
,
475 PULONG StringSecurityDescriptorLen
);
476 typedef BOOL (WINAPI
*IsValidSecurityDescriptor_Proc
) (PSECURITY_DESCRIPTOR
);
477 typedef DWORD (WINAPI
*GetAdaptersInfo_Proc
) (
478 PIP_ADAPTER_INFO pAdapterInfo
,
481 int (WINAPI
*pMultiByteToWideChar
)(UINT
,DWORD
,LPCSTR
,int,LPWSTR
,int);
482 int (WINAPI
*pWideCharToMultiByte
)(UINT
,DWORD
,LPCWSTR
,int,LPSTR
,int,LPCSTR
,LPBOOL
);
484 /* ** A utility function ** */
488 static BOOL s_b_ret
= 0;
489 OSVERSIONINFO os_ver
;
490 if (g_b_init_is_windows_9x
== 0)
492 g_b_init_is_windows_9x
= 1;
493 ZeroMemory (&os_ver
, sizeof (OSVERSIONINFO
));
494 os_ver
.dwOSVersionInfoSize
= sizeof (OSVERSIONINFO
);
495 if (GetVersionEx (&os_ver
))
497 s_b_ret
= (os_ver
.dwPlatformId
== VER_PLATFORM_WIN32_WINDOWS
);
503 static Lisp_Object
ltime (ULONGLONG
);
505 /* Get total user and system times for get-internal-run-time.
506 Returns a list of integers if the times are provided by the OS
507 (NT derivatives), otherwise it returns the result of current-time. */
509 w32_get_internal_run_time (void)
511 if (get_process_times_fn
)
513 FILETIME create
, exit
, kernel
, user
;
514 HANDLE proc
= GetCurrentProcess ();
515 if ((*get_process_times_fn
) (proc
, &create
, &exit
, &kernel
, &user
))
517 LARGE_INTEGER user_int
, kernel_int
, total
;
518 user_int
.LowPart
= user
.dwLowDateTime
;
519 user_int
.HighPart
= user
.dwHighDateTime
;
520 kernel_int
.LowPart
= kernel
.dwLowDateTime
;
521 kernel_int
.HighPart
= kernel
.dwHighDateTime
;
522 total
.QuadPart
= user_int
.QuadPart
+ kernel_int
.QuadPart
;
523 return ltime (total
.QuadPart
);
527 return Fcurrent_time ();
530 /* ** The wrapper functions ** */
533 open_process_token (HANDLE ProcessHandle
,
537 static OpenProcessToken_Proc s_pfn_Open_Process_Token
= NULL
;
538 HMODULE hm_advapi32
= NULL
;
539 if (is_windows_9x () == TRUE
)
543 if (g_b_init_open_process_token
== 0)
545 g_b_init_open_process_token
= 1;
546 hm_advapi32
= LoadLibrary ("Advapi32.dll");
547 s_pfn_Open_Process_Token
=
548 (OpenProcessToken_Proc
) GetProcAddress (hm_advapi32
, "OpenProcessToken");
550 if (s_pfn_Open_Process_Token
== NULL
)
555 s_pfn_Open_Process_Token (
563 get_token_information (HANDLE TokenHandle
,
564 TOKEN_INFORMATION_CLASS TokenInformationClass
,
565 LPVOID TokenInformation
,
566 DWORD TokenInformationLength
,
569 static GetTokenInformation_Proc s_pfn_Get_Token_Information
= NULL
;
570 HMODULE hm_advapi32
= NULL
;
571 if (is_windows_9x () == TRUE
)
575 if (g_b_init_get_token_information
== 0)
577 g_b_init_get_token_information
= 1;
578 hm_advapi32
= LoadLibrary ("Advapi32.dll");
579 s_pfn_Get_Token_Information
=
580 (GetTokenInformation_Proc
) GetProcAddress (hm_advapi32
, "GetTokenInformation");
582 if (s_pfn_Get_Token_Information
== NULL
)
587 s_pfn_Get_Token_Information (
589 TokenInformationClass
,
591 TokenInformationLength
,
597 lookup_account_sid (LPCTSTR lpSystemName
,
602 LPDWORD cbDomainName
,
605 static LookupAccountSid_Proc s_pfn_Lookup_Account_Sid
= NULL
;
606 HMODULE hm_advapi32
= NULL
;
607 if (is_windows_9x () == TRUE
)
611 if (g_b_init_lookup_account_sid
== 0)
613 g_b_init_lookup_account_sid
= 1;
614 hm_advapi32
= LoadLibrary ("Advapi32.dll");
615 s_pfn_Lookup_Account_Sid
=
616 (LookupAccountSid_Proc
) GetProcAddress (hm_advapi32
, LookupAccountSid_Name
);
618 if (s_pfn_Lookup_Account_Sid
== NULL
)
623 s_pfn_Lookup_Account_Sid (
635 get_sid_sub_authority (PSID pSid
, DWORD n
)
637 static GetSidSubAuthority_Proc s_pfn_Get_Sid_Sub_Authority
= NULL
;
638 static DWORD zero
= 0U;
639 HMODULE hm_advapi32
= NULL
;
640 if (is_windows_9x () == TRUE
)
644 if (g_b_init_get_sid_sub_authority
== 0)
646 g_b_init_get_sid_sub_authority
= 1;
647 hm_advapi32
= LoadLibrary ("Advapi32.dll");
648 s_pfn_Get_Sid_Sub_Authority
=
649 (GetSidSubAuthority_Proc
) GetProcAddress (
650 hm_advapi32
, "GetSidSubAuthority");
652 if (s_pfn_Get_Sid_Sub_Authority
== NULL
)
656 return (s_pfn_Get_Sid_Sub_Authority (pSid
, n
));
660 get_sid_sub_authority_count (PSID pSid
)
662 static GetSidSubAuthorityCount_Proc s_pfn_Get_Sid_Sub_Authority_Count
= NULL
;
663 static UCHAR zero
= 0U;
664 HMODULE hm_advapi32
= NULL
;
665 if (is_windows_9x () == TRUE
)
669 if (g_b_init_get_sid_sub_authority_count
== 0)
671 g_b_init_get_sid_sub_authority_count
= 1;
672 hm_advapi32
= LoadLibrary ("Advapi32.dll");
673 s_pfn_Get_Sid_Sub_Authority_Count
=
674 (GetSidSubAuthorityCount_Proc
) GetProcAddress (
675 hm_advapi32
, "GetSidSubAuthorityCount");
677 if (s_pfn_Get_Sid_Sub_Authority_Count
== NULL
)
681 return (s_pfn_Get_Sid_Sub_Authority_Count (pSid
));
685 get_security_info (HANDLE handle
,
686 SE_OBJECT_TYPE ObjectType
,
687 SECURITY_INFORMATION SecurityInfo
,
692 PSECURITY_DESCRIPTOR
*ppSecurityDescriptor
)
694 static GetSecurityInfo_Proc s_pfn_Get_Security_Info
= NULL
;
695 HMODULE hm_advapi32
= NULL
;
696 if (is_windows_9x () == TRUE
)
700 if (g_b_init_get_security_info
== 0)
702 g_b_init_get_security_info
= 1;
703 hm_advapi32
= LoadLibrary ("Advapi32.dll");
704 s_pfn_Get_Security_Info
=
705 (GetSecurityInfo_Proc
) GetProcAddress (
706 hm_advapi32
, "GetSecurityInfo");
708 if (s_pfn_Get_Security_Info
== NULL
)
712 return (s_pfn_Get_Security_Info (handle
, ObjectType
, SecurityInfo
,
713 ppsidOwner
, ppsidGroup
, ppDacl
, ppSacl
,
714 ppSecurityDescriptor
));
718 get_file_security (const char *lpFileName
,
719 SECURITY_INFORMATION RequestedInformation
,
720 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
722 LPDWORD lpnLengthNeeded
)
724 static GetFileSecurityA_Proc s_pfn_Get_File_SecurityA
= NULL
;
725 static GetFileSecurityW_Proc s_pfn_Get_File_SecurityW
= NULL
;
726 HMODULE hm_advapi32
= NULL
;
727 if (is_windows_9x () == TRUE
)
732 if (w32_unicode_filenames
)
734 wchar_t filename_w
[MAX_PATH
];
736 if (g_b_init_get_file_security_w
== 0)
738 g_b_init_get_file_security_w
= 1;
739 hm_advapi32
= LoadLibrary ("Advapi32.dll");
740 s_pfn_Get_File_SecurityW
=
741 (GetFileSecurityW_Proc
) GetProcAddress (hm_advapi32
,
744 if (s_pfn_Get_File_SecurityW
== NULL
)
749 filename_to_utf16 (lpFileName
, filename_w
);
750 return (s_pfn_Get_File_SecurityW (filename_w
, RequestedInformation
,
751 pSecurityDescriptor
, nLength
,
756 char filename_a
[MAX_PATH
];
758 if (g_b_init_get_file_security_a
== 0)
760 g_b_init_get_file_security_a
= 1;
761 hm_advapi32
= LoadLibrary ("Advapi32.dll");
762 s_pfn_Get_File_SecurityA
=
763 (GetFileSecurityA_Proc
) GetProcAddress (hm_advapi32
,
766 if (s_pfn_Get_File_SecurityA
== NULL
)
771 filename_to_ansi (lpFileName
, filename_a
);
772 return (s_pfn_Get_File_SecurityA (filename_a
, RequestedInformation
,
773 pSecurityDescriptor
, nLength
,
779 set_file_security (const char *lpFileName
,
780 SECURITY_INFORMATION SecurityInformation
,
781 PSECURITY_DESCRIPTOR pSecurityDescriptor
)
783 static SetFileSecurityW_Proc s_pfn_Set_File_SecurityW
= NULL
;
784 static SetFileSecurityA_Proc s_pfn_Set_File_SecurityA
= NULL
;
785 HMODULE hm_advapi32
= NULL
;
786 if (is_windows_9x () == TRUE
)
791 if (w32_unicode_filenames
)
793 wchar_t filename_w
[MAX_PATH
];
795 if (g_b_init_set_file_security_w
== 0)
797 g_b_init_set_file_security_w
= 1;
798 hm_advapi32
= LoadLibrary ("Advapi32.dll");
799 s_pfn_Set_File_SecurityW
=
800 (SetFileSecurityW_Proc
) GetProcAddress (hm_advapi32
,
803 if (s_pfn_Set_File_SecurityW
== NULL
)
808 filename_to_utf16 (lpFileName
, filename_w
);
809 return (s_pfn_Set_File_SecurityW (filename_w
, SecurityInformation
,
810 pSecurityDescriptor
));
814 char filename_a
[MAX_PATH
];
816 if (g_b_init_set_file_security_a
== 0)
818 g_b_init_set_file_security_a
= 1;
819 hm_advapi32
= LoadLibrary ("Advapi32.dll");
820 s_pfn_Set_File_SecurityA
=
821 (SetFileSecurityA_Proc
) GetProcAddress (hm_advapi32
,
824 if (s_pfn_Set_File_SecurityA
== NULL
)
829 filename_to_ansi (lpFileName
, filename_a
);
830 return (s_pfn_Set_File_SecurityA (filename_a
, SecurityInformation
,
831 pSecurityDescriptor
));
836 set_named_security_info (LPCTSTR lpObjectName
,
837 SE_OBJECT_TYPE ObjectType
,
838 SECURITY_INFORMATION SecurityInformation
,
844 static SetNamedSecurityInfoW_Proc s_pfn_Set_Named_Security_InfoW
= NULL
;
845 static SetNamedSecurityInfoA_Proc s_pfn_Set_Named_Security_InfoA
= NULL
;
846 HMODULE hm_advapi32
= NULL
;
847 if (is_windows_9x () == TRUE
)
852 if (w32_unicode_filenames
)
854 wchar_t filename_w
[MAX_PATH
];
856 if (g_b_init_set_named_security_info_w
== 0)
858 g_b_init_set_named_security_info_w
= 1;
859 hm_advapi32
= LoadLibrary ("Advapi32.dll");
860 s_pfn_Set_Named_Security_InfoW
=
861 (SetNamedSecurityInfoW_Proc
) GetProcAddress (hm_advapi32
,
862 "SetNamedSecurityInfoW");
864 if (s_pfn_Set_Named_Security_InfoW
== NULL
)
869 filename_to_utf16 (lpObjectName
, filename_w
);
870 return (s_pfn_Set_Named_Security_InfoW (filename_w
, ObjectType
,
871 SecurityInformation
, psidOwner
,
872 psidGroup
, pDacl
, pSacl
));
876 char filename_a
[MAX_PATH
];
878 if (g_b_init_set_named_security_info_a
== 0)
880 g_b_init_set_named_security_info_a
= 1;
881 hm_advapi32
= LoadLibrary ("Advapi32.dll");
882 s_pfn_Set_Named_Security_InfoA
=
883 (SetNamedSecurityInfoA_Proc
) GetProcAddress (hm_advapi32
,
884 "SetNamedSecurityInfoA");
886 if (s_pfn_Set_Named_Security_InfoA
== NULL
)
891 filename_to_ansi (lpObjectName
, filename_a
);
892 return (s_pfn_Set_Named_Security_InfoA (filename_a
, ObjectType
,
893 SecurityInformation
, psidOwner
,
894 psidGroup
, pDacl
, pSacl
));
899 get_security_descriptor_owner (PSECURITY_DESCRIPTOR pSecurityDescriptor
,
901 LPBOOL lpbOwnerDefaulted
)
903 static GetSecurityDescriptorOwner_Proc s_pfn_Get_Security_Descriptor_Owner
= NULL
;
904 HMODULE hm_advapi32
= NULL
;
905 if (is_windows_9x () == TRUE
)
910 if (g_b_init_get_security_descriptor_owner
== 0)
912 g_b_init_get_security_descriptor_owner
= 1;
913 hm_advapi32
= LoadLibrary ("Advapi32.dll");
914 s_pfn_Get_Security_Descriptor_Owner
=
915 (GetSecurityDescriptorOwner_Proc
) GetProcAddress (
916 hm_advapi32
, "GetSecurityDescriptorOwner");
918 if (s_pfn_Get_Security_Descriptor_Owner
== NULL
)
923 return (s_pfn_Get_Security_Descriptor_Owner (pSecurityDescriptor
, pOwner
,
928 get_security_descriptor_group (PSECURITY_DESCRIPTOR pSecurityDescriptor
,
930 LPBOOL lpbGroupDefaulted
)
932 static GetSecurityDescriptorGroup_Proc s_pfn_Get_Security_Descriptor_Group
= NULL
;
933 HMODULE hm_advapi32
= NULL
;
934 if (is_windows_9x () == TRUE
)
939 if (g_b_init_get_security_descriptor_group
== 0)
941 g_b_init_get_security_descriptor_group
= 1;
942 hm_advapi32
= LoadLibrary ("Advapi32.dll");
943 s_pfn_Get_Security_Descriptor_Group
=
944 (GetSecurityDescriptorGroup_Proc
) GetProcAddress (
945 hm_advapi32
, "GetSecurityDescriptorGroup");
947 if (s_pfn_Get_Security_Descriptor_Group
== NULL
)
952 return (s_pfn_Get_Security_Descriptor_Group (pSecurityDescriptor
, pGroup
,
957 get_security_descriptor_dacl (PSECURITY_DESCRIPTOR pSecurityDescriptor
,
958 LPBOOL lpbDaclPresent
,
960 LPBOOL lpbDaclDefaulted
)
962 static GetSecurityDescriptorDacl_Proc s_pfn_Get_Security_Descriptor_Dacl
= NULL
;
963 HMODULE hm_advapi32
= NULL
;
964 if (is_windows_9x () == TRUE
)
969 if (g_b_init_get_security_descriptor_dacl
== 0)
971 g_b_init_get_security_descriptor_dacl
= 1;
972 hm_advapi32
= LoadLibrary ("Advapi32.dll");
973 s_pfn_Get_Security_Descriptor_Dacl
=
974 (GetSecurityDescriptorDacl_Proc
) GetProcAddress (
975 hm_advapi32
, "GetSecurityDescriptorDacl");
977 if (s_pfn_Get_Security_Descriptor_Dacl
== NULL
)
982 return (s_pfn_Get_Security_Descriptor_Dacl (pSecurityDescriptor
,
983 lpbDaclPresent
, pDacl
,
988 is_valid_sid (PSID sid
)
990 static IsValidSid_Proc s_pfn_Is_Valid_Sid
= NULL
;
991 HMODULE hm_advapi32
= NULL
;
992 if (is_windows_9x () == TRUE
)
996 if (g_b_init_is_valid_sid
== 0)
998 g_b_init_is_valid_sid
= 1;
999 hm_advapi32
= LoadLibrary ("Advapi32.dll");
1000 s_pfn_Is_Valid_Sid
=
1001 (IsValidSid_Proc
) GetProcAddress (
1002 hm_advapi32
, "IsValidSid");
1004 if (s_pfn_Is_Valid_Sid
== NULL
)
1008 return (s_pfn_Is_Valid_Sid (sid
));
1012 equal_sid (PSID sid1
, PSID sid2
)
1014 static EqualSid_Proc s_pfn_Equal_Sid
= NULL
;
1015 HMODULE hm_advapi32
= NULL
;
1016 if (is_windows_9x () == TRUE
)
1020 if (g_b_init_equal_sid
== 0)
1022 g_b_init_equal_sid
= 1;
1023 hm_advapi32
= LoadLibrary ("Advapi32.dll");
1025 (EqualSid_Proc
) GetProcAddress (
1026 hm_advapi32
, "EqualSid");
1028 if (s_pfn_Equal_Sid
== NULL
)
1032 return (s_pfn_Equal_Sid (sid1
, sid2
));
1036 get_length_sid (PSID sid
)
1038 static GetLengthSid_Proc s_pfn_Get_Length_Sid
= NULL
;
1039 HMODULE hm_advapi32
= NULL
;
1040 if (is_windows_9x () == TRUE
)
1044 if (g_b_init_get_length_sid
== 0)
1046 g_b_init_get_length_sid
= 1;
1047 hm_advapi32
= LoadLibrary ("Advapi32.dll");
1048 s_pfn_Get_Length_Sid
=
1049 (GetLengthSid_Proc
) GetProcAddress (
1050 hm_advapi32
, "GetLengthSid");
1052 if (s_pfn_Get_Length_Sid
== NULL
)
1056 return (s_pfn_Get_Length_Sid (sid
));
1060 copy_sid (DWORD destlen
, PSID dest
, PSID src
)
1062 static CopySid_Proc s_pfn_Copy_Sid
= NULL
;
1063 HMODULE hm_advapi32
= NULL
;
1064 if (is_windows_9x () == TRUE
)
1068 if (g_b_init_copy_sid
== 0)
1070 g_b_init_copy_sid
= 1;
1071 hm_advapi32
= LoadLibrary ("Advapi32.dll");
1073 (CopySid_Proc
) GetProcAddress (
1074 hm_advapi32
, "CopySid");
1076 if (s_pfn_Copy_Sid
== NULL
)
1080 return (s_pfn_Copy_Sid (destlen
, dest
, src
));
1084 END: Wrapper functions around OpenProcessToken
1085 and other functions in advapi32.dll that are only
1086 supported in Windows NT / 2k / XP
1090 get_native_system_info (LPSYSTEM_INFO lpSystemInfo
)
1092 static GetNativeSystemInfo_Proc s_pfn_Get_Native_System_Info
= NULL
;
1093 if (is_windows_9x () != TRUE
)
1095 if (g_b_init_get_native_system_info
== 0)
1097 g_b_init_get_native_system_info
= 1;
1098 s_pfn_Get_Native_System_Info
=
1099 (GetNativeSystemInfo_Proc
)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1100 "GetNativeSystemInfo");
1102 if (s_pfn_Get_Native_System_Info
!= NULL
)
1103 s_pfn_Get_Native_System_Info (lpSystemInfo
);
1106 lpSystemInfo
->dwNumberOfProcessors
= -1;
1110 get_system_times (LPFILETIME lpIdleTime
,
1111 LPFILETIME lpKernelTime
,
1112 LPFILETIME lpUserTime
)
1114 static GetSystemTimes_Proc s_pfn_Get_System_times
= NULL
;
1115 if (is_windows_9x () == TRUE
)
1119 if (g_b_init_get_system_times
== 0)
1121 g_b_init_get_system_times
= 1;
1122 s_pfn_Get_System_times
=
1123 (GetSystemTimes_Proc
)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1126 if (s_pfn_Get_System_times
== NULL
)
1128 return (s_pfn_Get_System_times (lpIdleTime
, lpKernelTime
, lpUserTime
));
1131 static BOOLEAN WINAPI
1132 create_symbolic_link (LPCSTR lpSymlinkFilename
,
1133 LPCSTR lpTargetFileName
,
1136 static CreateSymbolicLinkW_Proc s_pfn_Create_Symbolic_LinkW
= NULL
;
1137 static CreateSymbolicLinkA_Proc s_pfn_Create_Symbolic_LinkA
= NULL
;
1140 if (is_windows_9x () == TRUE
)
1145 if (w32_unicode_filenames
)
1147 wchar_t symfn_w
[MAX_PATH
], tgtfn_w
[MAX_PATH
];
1149 if (g_b_init_create_symbolic_link_w
== 0)
1151 g_b_init_create_symbolic_link_w
= 1;
1152 s_pfn_Create_Symbolic_LinkW
=
1153 (CreateSymbolicLinkW_Proc
)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1154 "CreateSymbolicLinkW");
1156 if (s_pfn_Create_Symbolic_LinkW
== NULL
)
1162 filename_to_utf16 (lpSymlinkFilename
, symfn_w
);
1163 filename_to_utf16 (lpTargetFileName
, tgtfn_w
);
1164 retval
= s_pfn_Create_Symbolic_LinkW (symfn_w
, tgtfn_w
, dwFlags
);
1165 /* If we were denied creation of the symlink, try again after
1166 enabling the SeCreateSymbolicLinkPrivilege for our process. */
1169 TOKEN_PRIVILEGES priv_current
;
1171 if (enable_privilege (SE_CREATE_SYMBOLIC_LINK_NAME
, TRUE
,
1174 retval
= s_pfn_Create_Symbolic_LinkW (symfn_w
, tgtfn_w
, dwFlags
);
1175 restore_privilege (&priv_current
);
1182 char symfn_a
[MAX_PATH
], tgtfn_a
[MAX_PATH
];
1184 if (g_b_init_create_symbolic_link_a
== 0)
1186 g_b_init_create_symbolic_link_a
= 1;
1187 s_pfn_Create_Symbolic_LinkA
=
1188 (CreateSymbolicLinkA_Proc
)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1189 "CreateSymbolicLinkA");
1191 if (s_pfn_Create_Symbolic_LinkA
== NULL
)
1197 filename_to_ansi (lpSymlinkFilename
, symfn_a
);
1198 filename_to_ansi (lpTargetFileName
, tgtfn_a
);
1199 retval
= s_pfn_Create_Symbolic_LinkA (symfn_a
, tgtfn_a
, dwFlags
);
1200 /* If we were denied creation of the symlink, try again after
1201 enabling the SeCreateSymbolicLinkPrivilege for our process. */
1204 TOKEN_PRIVILEGES priv_current
;
1206 if (enable_privilege (SE_CREATE_SYMBOLIC_LINK_NAME
, TRUE
,
1209 retval
= s_pfn_Create_Symbolic_LinkA (symfn_a
, tgtfn_a
, dwFlags
);
1210 restore_privilege (&priv_current
);
1219 is_valid_security_descriptor (PSECURITY_DESCRIPTOR pSecurityDescriptor
)
1221 static IsValidSecurityDescriptor_Proc s_pfn_Is_Valid_Security_Descriptor_Proc
= NULL
;
1223 if (is_windows_9x () == TRUE
)
1229 if (g_b_init_is_valid_security_descriptor
== 0)
1231 g_b_init_is_valid_security_descriptor
= 1;
1232 s_pfn_Is_Valid_Security_Descriptor_Proc
=
1233 (IsValidSecurityDescriptor_Proc
)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1234 "IsValidSecurityDescriptor");
1236 if (s_pfn_Is_Valid_Security_Descriptor_Proc
== NULL
)
1242 return s_pfn_Is_Valid_Security_Descriptor_Proc (pSecurityDescriptor
);
1246 convert_sd_to_sddl (PSECURITY_DESCRIPTOR SecurityDescriptor
,
1247 DWORD RequestedStringSDRevision
,
1248 SECURITY_INFORMATION SecurityInformation
,
1249 LPTSTR
*StringSecurityDescriptor
,
1250 PULONG StringSecurityDescriptorLen
)
1252 static ConvertSecurityDescriptorToStringSecurityDescriptor_Proc s_pfn_Convert_SD_To_SDDL
= NULL
;
1255 if (is_windows_9x () == TRUE
)
1261 if (g_b_init_convert_sd_to_sddl
== 0)
1263 g_b_init_convert_sd_to_sddl
= 1;
1265 s_pfn_Convert_SD_To_SDDL
=
1266 (ConvertSecurityDescriptorToStringSecurityDescriptor_Proc
)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1267 "ConvertSecurityDescriptorToStringSecurityDescriptorW");
1269 s_pfn_Convert_SD_To_SDDL
=
1270 (ConvertSecurityDescriptorToStringSecurityDescriptor_Proc
)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1271 "ConvertSecurityDescriptorToStringSecurityDescriptorA");
1274 if (s_pfn_Convert_SD_To_SDDL
== NULL
)
1280 retval
= s_pfn_Convert_SD_To_SDDL (SecurityDescriptor
,
1281 RequestedStringSDRevision
,
1282 SecurityInformation
,
1283 StringSecurityDescriptor
,
1284 StringSecurityDescriptorLen
);
1290 convert_sddl_to_sd (LPCTSTR StringSecurityDescriptor
,
1291 DWORD StringSDRevision
,
1292 PSECURITY_DESCRIPTOR
*SecurityDescriptor
,
1293 PULONG SecurityDescriptorSize
)
1295 static ConvertStringSecurityDescriptorToSecurityDescriptor_Proc s_pfn_Convert_SDDL_To_SD
= NULL
;
1298 if (is_windows_9x () == TRUE
)
1304 if (g_b_init_convert_sddl_to_sd
== 0)
1306 g_b_init_convert_sddl_to_sd
= 1;
1308 s_pfn_Convert_SDDL_To_SD
=
1309 (ConvertStringSecurityDescriptorToSecurityDescriptor_Proc
)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1310 "ConvertStringSecurityDescriptorToSecurityDescriptorW");
1312 s_pfn_Convert_SDDL_To_SD
=
1313 (ConvertStringSecurityDescriptorToSecurityDescriptor_Proc
)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1314 "ConvertStringSecurityDescriptorToSecurityDescriptorA");
1317 if (s_pfn_Convert_SDDL_To_SD
== NULL
)
1323 retval
= s_pfn_Convert_SDDL_To_SD (StringSecurityDescriptor
,
1326 SecurityDescriptorSize
);
1332 get_adapters_info (PIP_ADAPTER_INFO pAdapterInfo
, PULONG pOutBufLen
)
1334 static GetAdaptersInfo_Proc s_pfn_Get_Adapters_Info
= NULL
;
1335 HMODULE hm_iphlpapi
= NULL
;
1337 if (is_windows_9x () == TRUE
)
1338 return ERROR_NOT_SUPPORTED
;
1340 if (g_b_init_get_adapters_info
== 0)
1342 g_b_init_get_adapters_info
= 1;
1343 hm_iphlpapi
= LoadLibrary ("Iphlpapi.dll");
1345 s_pfn_Get_Adapters_Info
= (GetAdaptersInfo_Proc
)
1346 GetProcAddress (hm_iphlpapi
, "GetAdaptersInfo");
1348 if (s_pfn_Get_Adapters_Info
== NULL
)
1349 return ERROR_NOT_SUPPORTED
;
1350 return s_pfn_Get_Adapters_Info (pAdapterInfo
, pOutBufLen
);
1355 /* Return 1 if P is a valid pointer to an object of size SIZE. Return
1356 0 if P is NOT a valid pointer. Return -1 if we cannot validate P.
1358 This is called from alloc.c:valid_pointer_p. */
1360 w32_valid_pointer_p (void *p
, int size
)
1363 HANDLE h
= OpenProcess (PROCESS_VM_READ
, FALSE
, GetCurrentProcessId ());
1367 unsigned char *buf
= alloca (size
);
1368 int retval
= ReadProcessMemory (h
, p
, buf
, size
, &done
);
1379 /* Here's an overview of how the Windows build supports file names
1380 that cannot be encoded by the current system codepage.
1382 From the POV of Lisp and layers of C code above the functions here,
1383 Emacs on Windows pretends that its file names are encoded in UTF-8;
1384 see encode_file and decode_file on coding.c. Any file name that is
1385 passed as a unibyte string to C functions defined here is assumed
1386 to be in UTF-8 encoding. Any file name returned by functions
1387 defined here must be in UTF-8 encoding, with only a few exceptions
1388 reserved for a couple of special cases. (Be sure to use
1389 MAX_UTF8_PATH for char arrays that store UTF-8 encoded file names,
1390 as they can be much longer than MAX_PATH!)
1392 The UTF-8 encoded file names cannot be passed to system APIs, as
1393 Windows does not support that. Therefore, they are converted
1394 either to UTF-16 or to the ANSI codepage, depending on the value of
1395 w32-unicode-filenames, before calling any system APIs or CRT library
1396 functions. The default value of that variable is determined by the
1397 OS on which Emacs runs: nil on Windows 9X and t otherwise, but the
1398 user can change that default (although I don't see why would she
1401 The 4 functions defined below, filename_to_utf16, filename_to_ansi,
1402 filename_from_utf16, and filename_from_ansi, are the workhorses of
1403 these conversions. They rely on Windows native APIs
1404 MultiByteToWideChar and WideCharToMultiByte; we cannot use
1405 functions from coding.c here, because they allocate memory, which
1406 is a bad idea on the level of libc, which is what the functions
1407 here emulate. (If you worry about performance due to constant
1408 conversion back and forth from UTF-8 to UTF-16, then don't: first,
1409 it was measured to take only a few microseconds on a not-so-fast
1410 machine, and second, that's exactly what the ANSI APIs we used
1411 before did anyway, because they are just thin wrappers around the
1414 The variables file-name-coding-system and default-file-name-coding-system
1415 still exist, but are actually used only when a file name needs to
1416 be converted to the ANSI codepage. This happens all the time when
1417 w32-unicode-filenames is nil, but can also happen from time to time
1418 when it is t. Otherwise, these variables have no effect on file-name
1419 encoding when w32-unicode-filenames is t; this is similar to
1420 selection-coding-system.
1422 This arrangement works very well, but it has a few gotchas and
1425 . Lisp code that encodes or decodes file names manually should
1426 normally use 'utf-8' as the coding-system on Windows,
1427 disregarding file-name-coding-system. This is a somewhat
1428 unpleasant consequence, but it cannot be avoided. Fortunately,
1429 very few Lisp packages need to do that.
1431 More generally, passing to library functions (e.g., fopen or
1432 opendir) file names already encoded in the ANSI codepage is
1433 explicitly *verboten*, as all those functions, as shadowed and
1434 emulated here, assume they will receive UTF-8 encoded file names.
1436 For the same reasons, no CRT function or Win32 API can be called
1437 directly in Emacs sources, without either converting the file
1438 names from UTF-8 to UTF-16 or ANSI codepage, or going through
1439 some shadowing function defined here.
1441 . Environment variables stored in Vprocess_environment are encoded
1442 in the ANSI codepage, so if getenv/egetenv is used for a variable
1443 whose value is a file name or a list of directories, it needs to
1444 be converted to UTF-8, before it is used as argument to functions
1445 or decoded into a Lisp string.
1447 . File names passed to external libraries, like the image libraries
1448 and GnuTLS, need special handling. These libraries generally
1449 don't support UTF-16 or UTF-8 file names, so they must get file
1450 names encoded in the ANSI codepage. To facilitate using these
1451 libraries with file names that are not encodable in the ANSI
1452 codepage, use the function ansi_encode_filename, which will try
1453 to use the short 8+3 alias of a file name if that file name is
1454 not encodable in the ANSI codepage. See image.c and gnutls.c for
1455 examples of how this should be done.
1457 . Running subprocesses in non-ASCII directories and with non-ASCII
1458 file arguments is limited to the current codepage (even though
1459 Emacs is perfectly capable of finding an executable program file
1460 in a directory whose name cannot be encoded in the current
1461 codepage). This is because the command-line arguments are
1462 encoded _before_ they get to the w32-specific level, and the
1463 encoding is not known in advance (it doesn't have to be the
1464 current ANSI codepage), so w32proc.c functions cannot re-encode
1465 them in UTF-16. This should be fixed, but will also require
1466 changes in cmdproxy. The current limitation is not terribly bad
1467 anyway, since very few, if any, Windows console programs that are
1468 likely to be invoked by Emacs support UTF-16 encoded command
1471 . For similar reasons, server.el and emacsclient are also limited
1472 to the current ANSI codepage for now.
1474 . Emacs itself can only handle command-line arguments encoded in
1475 the current codepage.
1477 . Turning on w32-unicode-filename on Windows 9X (if it at all
1478 works) requires UNICOWS.DLL, which is thus a requirement even in
1479 non-GUI sessions, something the we previously avoided. */
1483 /* Converting file names from UTF-8 to either UTF-16 or the ANSI
1484 codepage defined by file-name-coding-system. */
1486 /* Current codepage for encoding file names. */
1487 static int file_name_codepage
;
1489 /* Produce a Windows ANSI codepage suitable for encoding file names.
1490 Return the information about that codepage in CP_INFO. */
1492 codepage_for_filenames (CPINFO
*cp_info
)
1494 /* A simple cache to avoid calling GetCPInfo every time we need to
1495 encode/decode a file name. The file-name encoding is not
1496 supposed to be changed too frequently, if ever. */
1497 static Lisp_Object last_file_name_encoding
;
1499 Lisp_Object current_encoding
;
1501 current_encoding
= Vfile_name_coding_system
;
1502 if (NILP (current_encoding
))
1503 current_encoding
= Vdefault_file_name_coding_system
;
1505 if (!EQ (last_file_name_encoding
, current_encoding
))
1507 /* Default to the current ANSI codepage. */
1508 file_name_codepage
= w32_ansi_code_page
;
1510 if (NILP (current_encoding
))
1512 char *cpname
= SDATA (SYMBOL_NAME (current_encoding
));
1513 char *cp
= NULL
, *end
;
1516 if (strncmp (cpname
, "cp", 2) == 0)
1518 else if (strncmp (cpname
, "windows-", 8) == 0)
1524 cpnum
= strtol (cp
, &end
, 10);
1525 if (cpnum
&& *end
== '\0' && end
- cp
>= 2)
1526 file_name_codepage
= cpnum
;
1530 if (!file_name_codepage
)
1531 file_name_codepage
= CP_ACP
; /* CP_ACP = 0, but let's not assume that */
1533 if (!GetCPInfo (file_name_codepage
, &cp
))
1535 file_name_codepage
= CP_ACP
;
1536 if (!GetCPInfo (file_name_codepage
, &cp
))
1543 return file_name_codepage
;
1547 filename_to_utf16 (const char *fn_in
, wchar_t *fn_out
)
1549 int result
= pMultiByteToWideChar (CP_UTF8
, MB_ERR_INVALID_CHARS
, fn_in
, -1,
1554 DWORD err
= GetLastError ();
1558 case ERROR_INVALID_FLAGS
:
1559 case ERROR_INVALID_PARAMETER
:
1562 case ERROR_INSUFFICIENT_BUFFER
:
1563 case ERROR_NO_UNICODE_TRANSLATION
:
1574 filename_from_utf16 (const wchar_t *fn_in
, char *fn_out
)
1576 int result
= pWideCharToMultiByte (CP_UTF8
, 0, fn_in
, -1,
1577 fn_out
, MAX_UTF8_PATH
, NULL
, NULL
);
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_to_ansi (const char *fn_in
, char *fn_out
)
1603 wchar_t fn_utf16
[MAX_PATH
];
1605 if (filename_to_utf16 (fn_in
, fn_utf16
) == 0)
1608 int codepage
= codepage_for_filenames (NULL
);
1610 result
= pWideCharToMultiByte (codepage
, 0, fn_utf16
, -1,
1611 fn_out
, MAX_PATH
, NULL
, NULL
);
1614 DWORD err
= GetLastError ();
1618 case ERROR_INVALID_FLAGS
:
1619 case ERROR_INVALID_PARAMETER
:
1622 case ERROR_INSUFFICIENT_BUFFER
:
1623 case ERROR_NO_UNICODE_TRANSLATION
:
1636 filename_from_ansi (const char *fn_in
, char *fn_out
)
1638 wchar_t fn_utf16
[MAX_PATH
];
1639 int codepage
= codepage_for_filenames (NULL
);
1640 int result
= pMultiByteToWideChar (codepage
, MB_ERR_INVALID_CHARS
, fn_in
, -1,
1641 fn_utf16
, MAX_PATH
);
1645 DWORD err
= GetLastError ();
1649 case ERROR_INVALID_FLAGS
:
1650 case ERROR_INVALID_PARAMETER
:
1653 case ERROR_INSUFFICIENT_BUFFER
:
1654 case ERROR_NO_UNICODE_TRANSLATION
:
1661 return filename_from_utf16 (fn_utf16
, fn_out
);
1666 /* The directory where we started, in UTF-8. */
1667 static char startup_dir
[MAX_UTF8_PATH
];
1669 /* Get the current working directory. */
1671 getcwd (char *dir
, int dirsize
)
1678 if (dirsize
<= strlen (startup_dir
))
1684 if (GetCurrentDirectory (MAXPATHLEN
, dir
) > 0)
1688 /* Emacs doesn't actually change directory itself, it stays in the
1689 same directory where it was started. */
1690 strcpy (dir
, startup_dir
);
1695 /* Emulate getloadavg. */
1697 struct load_sample
{
1704 /* Number of processors on this machine. */
1705 static unsigned num_of_processors
;
1707 /* We maintain 1-sec samples for the last 16 minutes in a circular buffer. */
1708 static struct load_sample samples
[16*60];
1709 static int first_idx
= -1, last_idx
= -1;
1710 static int max_idx
= sizeof (samples
) / sizeof (samples
[0]);
1715 int next_idx
= from
+ 1;
1717 if (next_idx
>= max_idx
)
1726 int prev_idx
= from
- 1;
1729 prev_idx
= max_idx
- 1;
1735 sample_system_load (ULONGLONG
*idle
, ULONGLONG
*kernel
, ULONGLONG
*user
)
1737 SYSTEM_INFO sysinfo
;
1738 FILETIME ft_idle
, ft_user
, ft_kernel
;
1740 /* Initialize the number of processors on this machine. */
1741 if (num_of_processors
<= 0)
1743 get_native_system_info (&sysinfo
);
1744 num_of_processors
= sysinfo
.dwNumberOfProcessors
;
1745 if (num_of_processors
<= 0)
1747 GetSystemInfo (&sysinfo
);
1748 num_of_processors
= sysinfo
.dwNumberOfProcessors
;
1750 if (num_of_processors
<= 0)
1751 num_of_processors
= 1;
1754 /* TODO: Take into account threads that are ready to run, by
1755 sampling the "\System\Processor Queue Length" performance
1756 counter. The code below accounts only for threads that are
1757 actually running. */
1759 if (get_system_times (&ft_idle
, &ft_kernel
, &ft_user
))
1761 ULARGE_INTEGER uidle
, ukernel
, uuser
;
1763 memcpy (&uidle
, &ft_idle
, sizeof (ft_idle
));
1764 memcpy (&ukernel
, &ft_kernel
, sizeof (ft_kernel
));
1765 memcpy (&uuser
, &ft_user
, sizeof (ft_user
));
1766 *idle
= uidle
.QuadPart
;
1767 *kernel
= ukernel
.QuadPart
;
1768 *user
= uuser
.QuadPart
;
1778 /* Produce the load average for a given time interval, using the
1779 samples in the samples[] array. WHICH can be 0, 1, or 2, meaning
1780 1-minute, 5-minute, or 15-minute average, respectively. */
1784 double retval
= -1.0;
1787 double span
= (which
== 0 ? 1.0 : (which
== 1 ? 5.0 : 15.0)) * 60;
1788 time_t now
= samples
[last_idx
].sample_time
;
1790 if (first_idx
!= last_idx
)
1792 for (idx
= buf_prev (last_idx
); ; idx
= buf_prev (idx
))
1794 tdiff
= difftime (now
, samples
[idx
].sample_time
);
1795 if (tdiff
>= span
- 2*DBL_EPSILON
*now
)
1798 samples
[last_idx
].kernel
+ samples
[last_idx
].user
1799 - (samples
[idx
].kernel
+ samples
[idx
].user
);
1800 long double idl
= samples
[last_idx
].idle
- samples
[idx
].idle
;
1802 retval
= (1.0 - idl
/ sys
) * num_of_processors
;
1805 if (idx
== first_idx
)
1814 getloadavg (double loadavg
[], int nelem
)
1817 ULONGLONG idle
, kernel
, user
;
1818 time_t now
= time (NULL
);
1820 /* If system time jumped back for some reason, delete all samples
1821 whose time is later than the current wall-clock time. This
1822 prevents load average figures from becoming frozen for prolonged
1823 periods of time, when system time is reset backwards. */
1826 while (difftime (now
, samples
[last_idx
].sample_time
) < -1.0)
1828 if (last_idx
== first_idx
)
1830 first_idx
= last_idx
= -1;
1833 last_idx
= buf_prev (last_idx
);
1837 /* Store another sample. We ignore samples that are less than 1 sec
1840 || (difftime (now
, samples
[last_idx
].sample_time
)
1841 >= 1.0 - 2*DBL_EPSILON
*now
))
1843 sample_system_load (&idle
, &kernel
, &user
);
1844 last_idx
= buf_next (last_idx
);
1845 samples
[last_idx
].sample_time
= now
;
1846 samples
[last_idx
].idle
= idle
;
1847 samples
[last_idx
].kernel
= kernel
;
1848 samples
[last_idx
].user
= user
;
1849 /* If the buffer has more that 15 min worth of samples, discard
1851 if (first_idx
== -1)
1852 first_idx
= last_idx
;
1853 while (first_idx
!= last_idx
1854 && (difftime (now
, samples
[first_idx
].sample_time
)
1855 >= 15.0*60 + 2*DBL_EPSILON
*now
))
1856 first_idx
= buf_next (first_idx
);
1859 for (elem
= 0; elem
< nelem
; elem
++)
1861 double avg
= getavg (elem
);
1865 loadavg
[elem
] = avg
;
1871 /* Emulate getpwuid, getpwnam and others. */
1873 #define PASSWD_FIELD_SIZE 256
1875 static char dflt_passwd_name
[PASSWD_FIELD_SIZE
];
1876 static char dflt_passwd_passwd
[PASSWD_FIELD_SIZE
];
1877 static char dflt_passwd_gecos
[PASSWD_FIELD_SIZE
];
1878 static char dflt_passwd_dir
[MAX_UTF8_PATH
];
1879 static char dflt_passwd_shell
[MAX_UTF8_PATH
];
1881 static struct passwd dflt_passwd
=
1893 static char dflt_group_name
[GNLEN
+1];
1895 static struct group dflt_group
=
1897 /* When group information is not available, we return this as the
1898 group for all files. */
1906 return dflt_passwd
.pw_uid
;
1912 /* I could imagine arguing for checking to see whether the user is
1913 in the Administrators group and returning a UID of 0 for that
1914 case, but I don't know how wise that would be in the long run. */
1921 return dflt_passwd
.pw_gid
;
1931 getpwuid (unsigned uid
)
1933 if (uid
== dflt_passwd
.pw_uid
)
1934 return &dflt_passwd
;
1939 getgrgid (gid_t gid
)
1945 getpwnam (char *name
)
1949 pw
= getpwuid (getuid ());
1953 if (xstrcasecmp (name
, pw
->pw_name
))
1960 init_user_info (void)
1962 /* Find the user's real name by opening the process token and
1963 looking up the name associated with the user-sid in that token.
1965 Use the relative portion of the identifier authority value from
1966 the user-sid as the user id value (same for group id using the
1967 primary group sid from the process token). */
1969 char uname
[UNLEN
+1], gname
[GNLEN
+1], domain
[1025];
1970 DWORD ulength
= sizeof (uname
), dlength
= sizeof (domain
), needed
;
1971 DWORD glength
= sizeof (gname
);
1972 HANDLE token
= NULL
;
1973 SID_NAME_USE user_type
;
1974 unsigned char *buf
= NULL
;
1976 TOKEN_USER user_token
;
1977 TOKEN_PRIMARY_GROUP group_token
;
1980 result
= open_process_token (GetCurrentProcess (), TOKEN_QUERY
, &token
);
1983 result
= get_token_information (token
, TokenUser
, NULL
, 0, &blen
);
1984 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
1986 buf
= xmalloc (blen
);
1987 result
= get_token_information (token
, TokenUser
,
1988 (LPVOID
)buf
, blen
, &needed
);
1991 memcpy (&user_token
, buf
, sizeof (user_token
));
1992 result
= lookup_account_sid (NULL
, user_token
.User
.Sid
,
1994 domain
, &dlength
, &user_type
);
2002 strcpy (dflt_passwd
.pw_name
, uname
);
2003 /* Determine a reasonable uid value. */
2004 if (xstrcasecmp ("administrator", uname
) == 0)
2006 dflt_passwd
.pw_uid
= 500; /* well-known Administrator uid */
2007 dflt_passwd
.pw_gid
= 513; /* well-known None gid */
2011 /* Use the last sub-authority value of the RID, the relative
2012 portion of the SID, as user/group ID. */
2013 dflt_passwd
.pw_uid
= get_rid (user_token
.User
.Sid
);
2015 /* Get group id and name. */
2016 result
= get_token_information (token
, TokenPrimaryGroup
,
2017 (LPVOID
)buf
, blen
, &needed
);
2018 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
2020 buf
= xrealloc (buf
, blen
= needed
);
2021 result
= get_token_information (token
, TokenPrimaryGroup
,
2022 (LPVOID
)buf
, blen
, &needed
);
2026 memcpy (&group_token
, buf
, sizeof (group_token
));
2027 dflt_passwd
.pw_gid
= get_rid (group_token
.PrimaryGroup
);
2028 dlength
= sizeof (domain
);
2029 /* If we can get at the real Primary Group name, use that.
2030 Otherwise, the default group name was already set to
2031 "None" in globals_of_w32. */
2032 if (lookup_account_sid (NULL
, group_token
.PrimaryGroup
,
2033 gname
, &glength
, NULL
, &dlength
,
2035 strcpy (dflt_group_name
, gname
);
2038 dflt_passwd
.pw_gid
= dflt_passwd
.pw_uid
;
2041 /* If security calls are not supported (presumably because we
2042 are running under Windows 9X), fallback to this: */
2043 else if (GetUserName (uname
, &ulength
))
2045 strcpy (dflt_passwd
.pw_name
, uname
);
2046 if (xstrcasecmp ("administrator", uname
) == 0)
2047 dflt_passwd
.pw_uid
= 0;
2049 dflt_passwd
.pw_uid
= 123;
2050 dflt_passwd
.pw_gid
= dflt_passwd
.pw_uid
;
2054 strcpy (dflt_passwd
.pw_name
, "unknown");
2055 dflt_passwd
.pw_uid
= 123;
2056 dflt_passwd
.pw_gid
= 123;
2058 dflt_group
.gr_gid
= dflt_passwd
.pw_gid
;
2060 /* Set dir and shell from environment variables. */
2061 if (w32_unicode_filenames
)
2063 wchar_t *home
= _wgetenv (L
"HOME");
2064 wchar_t *shell
= _wgetenv (L
"SHELL");
2066 /* Ensure HOME and SHELL are defined. */
2071 filename_from_utf16 (home
, dflt_passwd
.pw_dir
);
2072 filename_from_utf16 (shell
, dflt_passwd
.pw_shell
);
2076 char *home
= getenv ("HOME");
2077 char *shell
= getenv ("SHELL");
2083 filename_from_ansi (home
, dflt_passwd
.pw_dir
);
2084 filename_from_ansi (shell
, dflt_passwd
.pw_shell
);
2089 CloseHandle (token
);
2095 /* rand () on NT gives us 15 random bits...hack together 30 bits. */
2096 return ((rand () << 15) | rand ());
2105 /* Return the maximum length in bytes of a multibyte character
2106 sequence encoded in the current ANSI codepage. This is required to
2107 correctly walk the encoded file names one character at a time. */
2109 max_filename_mbslen (void)
2113 codepage_for_filenames (&cp_info
);
2114 return cp_info
.MaxCharSize
;
2117 /* Normalize filename by converting in-place all of its path
2118 separators to the separator specified by PATH_SEP. */
2121 normalize_filename (register char *fp
, char path_sep
)
2125 /* Always lower-case drive letters a-z, even if the filesystem
2126 preserves case in filenames.
2127 This is so filenames can be compared by string comparison
2128 functions that are case-sensitive. Even case-preserving filesystems
2129 do not distinguish case in drive letters. */
2132 if (*p2
== ':' && *fp
>= 'A' && *fp
<= 'Z')
2140 if ((*fp
== '/' || *fp
== '\\') && *fp
!= path_sep
)
2146 /* Destructively turn backslashes into slashes. */
2148 dostounix_filename (register char *p
)
2150 normalize_filename (p
, '/');
2153 /* Destructively turn slashes into backslashes. */
2155 unixtodos_filename (register char *p
)
2157 normalize_filename (p
, '\\');
2160 /* Remove all CR's that are followed by a LF.
2161 (From msdos.c...probably should figure out a way to share it,
2162 although this code isn't going to ever change.) */
2164 crlf_to_lf (register int n
, register unsigned char *buf
)
2166 unsigned char *np
= buf
;
2167 unsigned char *startp
= buf
;
2168 unsigned char *endp
= buf
+ n
;
2172 while (buf
< endp
- 1)
2176 if (*(++buf
) != 0x0a)
2187 /* Parse the root part of file name, if present. Return length and
2188 optionally store pointer to char after root. */
2190 parse_root (const char * name
, const char ** pPath
)
2192 const char * start
= name
;
2197 /* find the root name of the volume if given */
2198 if (isalpha (name
[0]) && name
[1] == ':')
2200 /* skip past drive specifier */
2202 if (IS_DIRECTORY_SEP (name
[0]))
2205 else if (IS_DIRECTORY_SEP (name
[0]) && IS_DIRECTORY_SEP (name
[1]))
2212 if (IS_DIRECTORY_SEP (*name
) && --slashes
== 0)
2217 if (IS_DIRECTORY_SEP (name
[0]))
2224 return name
- start
;
2227 /* Get long base name for name; name is assumed to be absolute. */
2229 get_long_basename (char * name
, char * buf
, int size
)
2231 HANDLE dir_handle
= INVALID_HANDLE_VALUE
;
2232 char fname_utf8
[MAX_UTF8_PATH
];
2236 /* Must be valid filename, no wild cards or other invalid characters. */
2237 if (strpbrk (name
, "*?|<>\""))
2240 if (w32_unicode_filenames
)
2242 wchar_t fname_utf16
[MAX_PATH
];
2243 WIN32_FIND_DATAW find_data_wide
;
2245 filename_to_utf16 (name
, fname_utf16
);
2246 dir_handle
= FindFirstFileW (fname_utf16
, &find_data_wide
);
2247 if (dir_handle
!= INVALID_HANDLE_VALUE
)
2248 cstatus
= filename_from_utf16 (find_data_wide
.cFileName
, fname_utf8
);
2252 char fname_ansi
[MAX_PATH
];
2253 WIN32_FIND_DATAA find_data_ansi
;
2255 filename_to_ansi (name
, fname_ansi
);
2256 /* If the ANSI name includes ? characters, it is not encodable
2257 in the ANSI codepage. In that case, we deliver the question
2258 marks to the caller; calling FindFirstFileA in this case
2259 could return some unrelated file name in the same
2261 if (_mbspbrk (fname_ansi
, "?"))
2263 /* Find the basename of fname_ansi. */
2264 char *p
= strrchr (fname_ansi
, '\\');
2270 cstatus
= filename_from_ansi (p
, fname_utf8
);
2274 dir_handle
= FindFirstFileA (fname_ansi
, &find_data_ansi
);
2275 if (dir_handle
!= INVALID_HANDLE_VALUE
)
2276 cstatus
= filename_from_ansi (find_data_ansi
.cFileName
, fname_utf8
);
2280 if (cstatus
== 0 && (len
= strlen (fname_utf8
)) < size
)
2281 memcpy (buf
, fname_utf8
, len
+ 1);
2285 if (dir_handle
!= INVALID_HANDLE_VALUE
)
2286 FindClose (dir_handle
);
2291 /* Get long name for file, if possible (assumed to be absolute). */
2293 w32_get_long_filename (char * name
, char * buf
, int size
)
2298 char full
[ MAX_UTF8_PATH
];
2301 len
= strlen (name
);
2302 if (len
>= MAX_UTF8_PATH
)
2305 /* Use local copy for destructive modification. */
2306 memcpy (full
, name
, len
+1);
2307 unixtodos_filename (full
);
2309 /* Copy root part verbatim. */
2310 len
= parse_root (full
, (const char **)&p
);
2311 memcpy (o
, full
, len
);
2316 while (p
!= NULL
&& *p
)
2319 p
= strchr (q
, '\\');
2321 len
= get_long_basename (full
, o
, size
);
2344 w32_get_short_filename (char * name
, char * buf
, int size
)
2346 if (w32_unicode_filenames
)
2348 wchar_t name_utf16
[MAX_PATH
], short_name
[MAX_PATH
];
2349 unsigned int retval
;
2351 filename_to_utf16 (name
, name_utf16
);
2352 retval
= GetShortPathNameW (name_utf16
, short_name
, size
);
2353 if (retval
&& retval
< size
)
2354 filename_from_utf16 (short_name
, buf
);
2359 char name_ansi
[MAX_PATH
];
2361 filename_to_ansi (name
, name_ansi
);
2362 return GetShortPathNameA (name_ansi
, buf
, size
);
2366 /* Re-encode FILENAME, a UTF-8 encoded unibyte string, using the
2367 MS-Windows ANSI codepage. If FILENAME includes characters not
2368 supported by the ANSI codepage, return the 8+3 alias of FILENAME,
2369 if it exists. This is needed because the w32 build wants to
2370 support file names outside of the system locale, but image
2371 libraries typically don't support wide (a.k.a. "Unicode") APIs
2372 required for that. */
2375 ansi_encode_filename (Lisp_Object filename
)
2377 Lisp_Object encoded_filename
;
2378 char fname
[MAX_PATH
];
2380 filename_to_ansi (SSDATA (filename
), fname
);
2381 if (_mbspbrk (fname
, "?"))
2383 char shortname
[MAX_PATH
];
2385 if (w32_get_short_filename (SDATA (filename
), shortname
, MAX_PATH
))
2387 dostounix_filename (shortname
);
2388 encoded_filename
= build_string (shortname
);
2392 encoded_filename
= build_unibyte_string (fname
);
2393 return encoded_filename
;
2397 is_unc_volume (const char *filename
)
2399 const char *ptr
= filename
;
2401 if (!IS_DIRECTORY_SEP (ptr
[0]) || !IS_DIRECTORY_SEP (ptr
[1]) || !ptr
[2])
2404 if (strpbrk (ptr
+ 2, "*?|<>\"\\/"))
2410 /* Emulate the Posix unsetenv. */
2412 unsetenv (const char *name
)
2418 if (name
== NULL
|| *name
== '\0' || strchr (name
, '=') != NULL
)
2423 name_len
= strlen (name
);
2424 /* MS docs says an environment variable cannot be longer than 32K. */
2425 if (name_len
> 32767)
2430 /* It is safe to use 'alloca' with 32K size, since the stack is at
2431 least 2MB, and we set it to 8MB in the link command line. */
2432 var
= alloca (name_len
+ 2);
2433 strncpy (var
, name
, name_len
);
2434 var
[name_len
++] = '=';
2435 var
[name_len
] = '\0';
2436 return _putenv (var
);
2439 /* MS _putenv doesn't support removing a variable when the argument
2440 does not include the '=' character, so we fix that here. */
2442 sys_putenv (char *str
)
2444 const char *const name_end
= strchr (str
, '=');
2446 if (name_end
== NULL
)
2448 /* Remove the variable from the environment. */
2449 return unsetenv (str
);
2452 return _putenv (str
);
2455 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
2458 w32_get_resource (char *key
, LPDWORD lpdwtype
)
2461 HKEY hrootkey
= NULL
;
2464 /* Check both the current user and the local machine to see if
2465 we have any resources. */
2467 if (RegOpenKeyEx (HKEY_CURRENT_USER
, REG_ROOT
, 0, KEY_READ
, &hrootkey
) == ERROR_SUCCESS
)
2471 if (RegQueryValueEx (hrootkey
, key
, NULL
, NULL
, NULL
, &cbData
) == ERROR_SUCCESS
2472 && (lpvalue
= xmalloc (cbData
)) != NULL
2473 && RegQueryValueEx (hrootkey
, key
, NULL
, lpdwtype
, lpvalue
, &cbData
) == ERROR_SUCCESS
)
2475 RegCloseKey (hrootkey
);
2481 RegCloseKey (hrootkey
);
2484 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE
, REG_ROOT
, 0, KEY_READ
, &hrootkey
) == ERROR_SUCCESS
)
2488 if (RegQueryValueEx (hrootkey
, key
, NULL
, NULL
, NULL
, &cbData
) == ERROR_SUCCESS
2489 && (lpvalue
= xmalloc (cbData
)) != NULL
2490 && RegQueryValueEx (hrootkey
, key
, NULL
, lpdwtype
, lpvalue
, &cbData
) == ERROR_SUCCESS
)
2492 RegCloseKey (hrootkey
);
2498 RegCloseKey (hrootkey
);
2504 /* The argv[] array holds ANSI-encoded strings, and so this function
2505 works with ANS_encoded strings. */
2507 init_environment (char ** argv
)
2509 static const char * const tempdirs
[] = {
2510 "$TMPDIR", "$TEMP", "$TMP", "c:/"
2515 const int imax
= sizeof (tempdirs
) / sizeof (tempdirs
[0]);
2517 /* Implementation note: This function explicitly works with ANSI
2518 file names, not with UTF-8 encoded file names. This is because
2519 this function pushes variables into the Emacs's environment, and
2520 the environment variables are always assumed to be in the
2521 locale-specific encoding. Do NOT call any functions that accept
2522 UTF-8 file names from this function! */
2524 /* Make sure they have a usable $TMPDIR. Many Emacs functions use
2525 temporary files and assume "/tmp" if $TMPDIR is unset, which
2526 will break on DOS/Windows. Refuse to work if we cannot find
2527 a directory, not even "c:/", usable for that purpose. */
2528 for (i
= 0; i
< imax
; i
++)
2530 const char *tmp
= tempdirs
[i
];
2533 tmp
= getenv (tmp
+ 1);
2534 /* Note that `access' can lie to us if the directory resides on a
2535 read-only filesystem, like CD-ROM or a write-protected floppy.
2536 The only way to be really sure is to actually create a file and
2537 see if it succeeds. But I think that's too much to ask. */
2539 /* MSVCRT's _access crashes with D_OK, so we use our replacement. */
2540 if (tmp
&& sys_access (tmp
, D_OK
) == 0)
2542 char * var
= alloca (strlen (tmp
) + 8);
2543 sprintf (var
, "TMPDIR=%s", tmp
);
2544 _putenv (strdup (var
));
2551 Fcons (build_string ("no usable temporary directories found!!"),
2553 "While setting TMPDIR: ");
2555 /* Check for environment variables and use registry settings if they
2556 don't exist. Fallback on default values where applicable. */
2561 char locale_name
[32];
2562 char default_home
[MAX_PATH
];
2565 static const struct env_entry
2571 /* If the default value is NULL, we will use the value from the
2572 outside environment or the Registry, but will not push the
2573 variable into the Emacs environment if it is defined neither
2574 in the Registry nor in the outside environment. */
2576 {"PRELOAD_WINSOCK", NULL
},
2577 {"emacs_dir", "C:/emacs"},
2578 {"EMACSLOADPATH", NULL
},
2579 {"SHELL", "cmdproxy.exe"}, /* perhaps it is somewhere on PATH */
2580 {"EMACSDATA", NULL
},
2581 {"EMACSPATH", NULL
},
2588 #define N_ENV_VARS sizeof (dflt_envvars)/sizeof (dflt_envvars[0])
2590 /* We need to copy dflt_envvars[] and work on the copy because we
2591 don't want the dumped Emacs to inherit the values of
2592 environment variables we saw during dumping (which could be on
2593 a different system). The defaults above must be left intact. */
2594 struct env_entry env_vars
[N_ENV_VARS
];
2596 for (i
= 0; i
< N_ENV_VARS
; i
++)
2597 env_vars
[i
] = dflt_envvars
[i
];
2599 /* For backwards compatibility, check if a .emacs file exists in C:/
2600 If not, then we can try to default to the appdata directory under the
2601 user's profile, which is more likely to be writable. */
2602 if (sys_access ("C:/.emacs", F_OK
) != 0)
2604 HRESULT profile_result
;
2605 /* Dynamically load ShGetFolderPath, as it won't exist on versions
2606 of Windows 95 and NT4 that have not been updated to include
2608 ShGetFolderPath_fn get_folder_path
;
2609 get_folder_path
= (ShGetFolderPath_fn
)
2610 GetProcAddress (GetModuleHandle ("shell32.dll"), "SHGetFolderPathA");
2612 if (get_folder_path
!= NULL
)
2614 profile_result
= get_folder_path (NULL
, CSIDL_APPDATA
, NULL
,
2617 /* If we can't get the appdata dir, revert to old behavior. */
2618 if (profile_result
== S_OK
)
2620 env_vars
[0].def_value
= default_home
;
2626 /* Get default locale info and use it for LANG. */
2627 if (GetLocaleInfo (LOCALE_USER_DEFAULT
,
2628 LOCALE_SABBREVLANGNAME
| LOCALE_USE_CP_ACP
,
2629 locale_name
, sizeof (locale_name
)))
2631 for (i
= 0; i
< N_ENV_VARS
; i
++)
2633 if (strcmp (env_vars
[i
].name
, "LANG") == 0)
2635 env_vars
[i
].def_value
= locale_name
;
2641 #define SET_ENV_BUF_SIZE (4 * MAX_PATH) /* to cover EMACSLOADPATH */
2643 /* Treat emacs_dir specially: set it unconditionally based on our
2647 char modname
[MAX_PATH
];
2649 if (!GetModuleFileNameA (NULL
, modname
, MAX_PATH
))
2651 if ((p
= _mbsrchr (modname
, '\\')) == NULL
)
2655 if ((p
= _mbsrchr (modname
, '\\'))
2656 /* From bin means installed Emacs, from src means uninstalled. */
2657 && (xstrcasecmp (p
, "\\bin") == 0 || xstrcasecmp (p
, "\\src") == 0))
2659 char buf
[SET_ENV_BUF_SIZE
];
2660 int within_build_tree
= xstrcasecmp (p
, "\\src") == 0;
2663 for (p
= modname
; *p
; p
= CharNext (p
))
2664 if (*p
== '\\') *p
= '/';
2666 _snprintf (buf
, sizeof (buf
)-1, "emacs_dir=%s", modname
);
2667 _putenv (strdup (buf
));
2668 /* If we are running from the Posix-like build tree, define
2669 SHELL to point to our own cmdproxy. The loop below will
2670 then disregard PATH_EXEC and the default value. */
2671 if (within_build_tree
)
2673 _snprintf (buf
, sizeof (buf
) - 1,
2674 "SHELL=%s/nt/cmdproxy.exe", modname
);
2675 _putenv (strdup (buf
));
2680 for (i
= 0; i
< N_ENV_VARS
; i
++)
2682 if (!getenv (env_vars
[i
].name
))
2685 char bufc
[SET_ENV_BUF_SIZE
];
2687 if ((lpval
= w32_get_resource (env_vars
[i
].name
, &dwType
)) == NULL
2688 /* Also ignore empty environment variables. */
2693 if (strcmp (env_vars
[i
].name
, "SHELL") == 0)
2695 /* Look for cmdproxy.exe in every directory in
2696 PATH_EXEC. FIXME: This does not find cmdproxy
2697 in nt/ when we run uninstalled. */
2698 char fname
[MAX_PATH
];
2699 const char *pstart
= PATH_EXEC
, *pend
;
2702 pend
= _mbschr (pstart
, ';');
2704 pend
= pstart
+ strlen (pstart
);
2705 /* Be defensive against series of ;;; characters. */
2708 strncpy (fname
, pstart
, pend
- pstart
);
2709 fname
[pend
- pstart
] = '/';
2710 strcpy (&fname
[pend
- pstart
+ 1], "cmdproxy.exe");
2711 ExpandEnvironmentStrings ((LPSTR
) fname
, bufc
,
2713 if (sys_access (bufc
, F_OK
) == 0)
2726 /* If not found in any directory, use the
2727 default as the last resort. */
2728 lpval
= env_vars
[i
].def_value
;
2729 dwType
= REG_EXPAND_SZ
;
2735 lpval
= env_vars
[i
].def_value
;
2736 dwType
= REG_EXPAND_SZ
;
2738 if (strcmp (env_vars
[i
].name
, "HOME") == 0 && !appdata
)
2739 Vdelayed_warnings_list
2740 = Fcons (listn (CONSTYPE_HEAP
, 2,
2741 intern ("initialization"),
2742 build_string ("Setting HOME to C:\\ by default is deprecated")),
2743 Vdelayed_warnings_list
);
2748 char buf1
[SET_ENV_BUF_SIZE
], buf2
[SET_ENV_BUF_SIZE
];
2750 if (dwType
== REG_EXPAND_SZ
)
2751 ExpandEnvironmentStrings ((LPSTR
) lpval
, buf1
, sizeof (buf1
));
2752 else if (dwType
== REG_SZ
)
2753 strcpy (buf1
, lpval
);
2754 if (dwType
== REG_EXPAND_SZ
|| dwType
== REG_SZ
)
2756 _snprintf (buf2
, sizeof (buf2
)-1, "%s=%s", env_vars
[i
].name
,
2758 _putenv (strdup (buf2
));
2768 /* Rebuild system configuration to reflect invoking system. */
2769 Vsystem_configuration
= build_string (EMACS_CONFIGURATION
);
2771 /* Another special case: on NT, the PATH variable is actually named
2772 "Path" although cmd.exe (perhaps NT itself) arranges for
2773 environment variable lookup and setting to be case insensitive.
2774 However, Emacs assumes a fully case sensitive environment, so we
2775 need to change "Path" to "PATH" to match the expectations of
2776 various elisp packages. We do this by the sneaky method of
2777 modifying the string in the C runtime environ entry.
2779 The same applies to COMSPEC. */
2783 for (envp
= environ
; *envp
; envp
++)
2784 if (_strnicmp (*envp
, "PATH=", 5) == 0)
2785 memcpy (*envp
, "PATH=", 5);
2786 else if (_strnicmp (*envp
, "COMSPEC=", 8) == 0)
2787 memcpy (*envp
, "COMSPEC=", 8);
2790 /* Remember the initial working directory for getcwd. */
2791 /* FIXME: Do we need to resolve possible symlinks in startup_dir?
2792 Does it matter anywhere in Emacs? */
2793 if (w32_unicode_filenames
)
2795 wchar_t wstartup_dir
[MAX_PATH
];
2797 if (!GetCurrentDirectoryW (MAX_PATH
, wstartup_dir
))
2799 filename_from_utf16 (wstartup_dir
, startup_dir
);
2803 char astartup_dir
[MAX_PATH
];
2805 if (!GetCurrentDirectoryA (MAX_PATH
, astartup_dir
))
2807 filename_from_ansi (astartup_dir
, startup_dir
);
2811 static char modname
[MAX_PATH
];
2813 if (!GetModuleFileNameA (NULL
, modname
, MAX_PATH
))
2818 /* Determine if there is a middle mouse button, to allow parse_button
2819 to decide whether right mouse events should be mouse-2 or
2821 w32_num_mouse_buttons
= GetSystemMetrics (SM_CMOUSEBUTTONS
);
2826 /* Called from expand-file-name when default-directory is not a string. */
2829 emacs_root_dir (void)
2831 static char root_dir
[MAX_UTF8_PATH
];
2834 p
= getenv ("emacs_dir");
2837 filename_from_ansi (p
, root_dir
);
2838 root_dir
[parse_root (root_dir
, NULL
)] = '\0';
2839 dostounix_filename (root_dir
);
2843 #include <sys/timeb.h>
2845 /* Emulate gettimeofday (Ulrich Leodolter, 1/11/95). */
2847 gettimeofday (struct timeval
*__restrict tv
, struct timezone
*__restrict tz
)
2852 tv
->tv_sec
= tb
.time
;
2853 tv
->tv_usec
= tb
.millitm
* 1000L;
2854 /* Implementation note: _ftime sometimes doesn't update the dstflag
2855 according to the new timezone when the system timezone is
2856 changed. We could fix that by using GetSystemTime and
2857 GetTimeZoneInformation, but that doesn't seem necessary, since
2858 Emacs always calls gettimeofday with the 2nd argument NULL (see
2859 current_emacs_time). */
2862 tz
->tz_minuteswest
= tb
.timezone
; /* minutes west of Greenwich */
2863 tz
->tz_dsttime
= tb
.dstflag
; /* type of dst correction */
2868 /* Emulate fdutimens. */
2870 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2871 TIMESPEC[0] and TIMESPEC[1], respectively.
2872 FD must be either negative -- in which case it is ignored --
2873 or a file descriptor that is open on FILE.
2874 If FD is nonnegative, then FILE can be NULL, which means
2875 use just futimes instead of utimes.
2876 If TIMESPEC is null, FAIL.
2877 Return 0 on success, -1 (setting errno) on failure. */
2880 fdutimens (int fd
, char const *file
, struct timespec
const timespec
[2])
2887 if (fd
< 0 && !file
)
2892 /* _futime's prototype defines 2nd arg as having the type 'struct
2893 _utimbuf', while utime needs to accept 'struct utimbuf' for
2894 compatibility with Posix. So we need to use 2 different (but
2895 equivalent) types to avoid compiler warnings, sigh. */
2898 struct _utimbuf _ut
;
2900 _ut
.actime
= timespec
[0].tv_sec
;
2901 _ut
.modtime
= timespec
[1].tv_sec
;
2902 return _futime (fd
, &_ut
);
2908 ut
.actime
= timespec
[0].tv_sec
;
2909 ut
.modtime
= timespec
[1].tv_sec
;
2910 /* Call 'utime', which is implemented below, not the MS library
2911 function, which fails on directories. */
2912 return utime (file
, &ut
);
2917 /* ------------------------------------------------------------------------- */
2918 /* IO support and wrapper functions for the Windows API. */
2919 /* ------------------------------------------------------------------------- */
2921 /* Place a wrapper around the MSVC version of ctime. It returns NULL
2922 on network directories, so we handle that case here.
2923 (Ulrich Leodolter, 1/11/95). */
2925 sys_ctime (const time_t *t
)
2927 char *str
= (char *) ctime (t
);
2928 return (str
? str
: "Sun Jan 01 00:00:00 1970");
2931 /* Emulate sleep...we could have done this with a define, but that
2932 would necessitate including windows.h in the files that used it.
2933 This is much easier. */
2935 sys_sleep (int seconds
)
2937 Sleep (seconds
* 1000);
2940 /* Internal MSVC functions for low-level descriptor munging */
2941 extern int __cdecl
_set_osfhnd (int fd
, long h
);
2942 extern int __cdecl
_free_osfhnd (int fd
);
2944 /* parallel array of private info on file handles */
2945 filedesc fd_info
[ MAXDESC
];
2947 typedef struct volume_info_data
{
2948 struct volume_info_data
* next
;
2950 /* time when info was obtained */
2953 /* actual volume info */
2962 /* Global referenced by various functions. */
2963 static volume_info_data volume_info
;
2965 /* Vector to indicate which drives are local and fixed (for which cached
2966 data never expires). */
2967 static BOOL fixed_drives
[26];
2969 /* Consider cached volume information to be stale if older than 10s,
2970 at least for non-local drives. Info for fixed drives is never stale. */
2971 #define DRIVE_INDEX( c ) ( (c) <= 'Z' ? (c) - 'A' : (c) - 'a' )
2972 #define VOLINFO_STILL_VALID( root_dir, info ) \
2973 ( ( isalpha (root_dir[0]) && \
2974 fixed_drives[ DRIVE_INDEX (root_dir[0]) ] ) \
2975 || GetTickCount () - info->timestamp < 10000 )
2977 /* Cache support functions. */
2979 /* Simple linked list with linear search is sufficient. */
2980 static volume_info_data
*volume_cache
= NULL
;
2982 static volume_info_data
*
2983 lookup_volume_info (char * root_dir
)
2985 volume_info_data
* info
;
2987 for (info
= volume_cache
; info
; info
= info
->next
)
2988 if (xstrcasecmp (info
->root_dir
, root_dir
) == 0)
2994 add_volume_info (char * root_dir
, volume_info_data
* info
)
2996 info
->root_dir
= xstrdup (root_dir
);
2997 unixtodos_filename (info
->root_dir
);
2998 info
->next
= volume_cache
;
2999 volume_cache
= info
;
3003 /* Wrapper for GetVolumeInformation, which uses caching to avoid
3004 performance penalty (~2ms on 486 for local drives, 7.5ms for local
3005 cdrom drive, ~5-10ms or more for remote drives on LAN). */
3006 static volume_info_data
*
3007 GetCachedVolumeInformation (char * root_dir
)
3009 volume_info_data
* info
;
3010 char default_root
[ MAX_UTF8_PATH
];
3011 char name
[MAX_PATH
+1];
3012 char type
[MAX_PATH
+1];
3014 /* NULL for root_dir means use root from current directory. */
3015 if (root_dir
== NULL
)
3017 if (w32_unicode_filenames
)
3019 wchar_t curdirw
[MAX_PATH
];
3021 if (GetCurrentDirectoryW (MAX_PATH
, curdirw
) == 0)
3023 filename_from_utf16 (curdirw
, default_root
);
3027 char curdira
[MAX_PATH
];
3029 if (GetCurrentDirectoryA (MAX_PATH
, curdira
) == 0)
3031 filename_from_ansi (curdira
, default_root
);
3033 parse_root (default_root
, (const char **)&root_dir
);
3035 root_dir
= default_root
;
3038 /* Local fixed drives can be cached permanently. Removable drives
3039 cannot be cached permanently, since the volume name and serial
3040 number (if nothing else) can change. Remote drives should be
3041 treated as if they are removable, since there is no sure way to
3042 tell whether they are or not. Also, the UNC association of drive
3043 letters mapped to remote volumes can be changed at any time (even
3044 by other processes) without notice.
3046 As a compromise, so we can benefit from caching info for remote
3047 volumes, we use a simple expiry mechanism to invalidate cache
3048 entries that are more than ten seconds old. */
3051 /* No point doing this, because WNetGetConnection is even slower than
3052 GetVolumeInformation, consistently taking ~50ms on a 486 (FWIW,
3053 GetDriveType is about the only call of this type which does not
3054 involve network access, and so is extremely quick). */
3056 /* Map drive letter to UNC if remote. */
3057 if (isalpha (root_dir
[0]) && !fixed
[DRIVE_INDEX (root_dir
[0])])
3059 char remote_name
[ 256 ];
3060 char drive
[3] = { root_dir
[0], ':' };
3062 if (WNetGetConnection (drive
, remote_name
, sizeof (remote_name
))
3064 /* do something */ ;
3068 info
= lookup_volume_info (root_dir
);
3070 if (info
== NULL
|| ! VOLINFO_STILL_VALID (root_dir
, info
))
3076 /* Info is not cached, or is stale. */
3077 if (w32_unicode_filenames
)
3079 wchar_t root_w
[MAX_PATH
];
3080 wchar_t name_w
[MAX_PATH
+1];
3081 wchar_t type_w
[MAX_PATH
+1];
3083 filename_to_utf16 (root_dir
, root_w
);
3084 if (!GetVolumeInformationW (root_w
,
3085 name_w
, sizeof (name_w
),
3089 type_w
, sizeof (type_w
)))
3091 /* Hmm... not really 100% correct, as these 2 are not file
3093 filename_from_utf16 (name_w
, name
);
3094 filename_from_utf16 (type_w
, type
);
3098 char root_a
[MAX_PATH
];
3099 char name_a
[MAX_PATH
+1];
3100 char type_a
[MAX_PATH
+1];
3102 filename_to_ansi (root_dir
, root_a
);
3103 if (!GetVolumeInformationA (root_a
,
3104 name_a
, sizeof (name_a
),
3108 type_a
, sizeof (type_a
)))
3110 filename_from_ansi (name_a
, name
);
3111 filename_from_ansi (type_a
, type
);
3114 /* Cache the volume information for future use, overwriting existing
3115 entry if present. */
3118 info
= xmalloc (sizeof (volume_info_data
));
3119 add_volume_info (root_dir
, info
);
3127 info
->name
= xstrdup (name
);
3128 unixtodos_filename (info
->name
);
3129 info
->serialnum
= serialnum
;
3130 info
->maxcomp
= maxcomp
;
3131 info
->flags
= flags
;
3132 info
->type
= xstrdup (type
);
3133 info
->timestamp
= GetTickCount ();
3139 /* Get information on the volume where NAME is held; set path pointer to
3140 start of pathname in NAME (past UNC header\volume header if present),
3141 if pPath is non-NULL.
3143 Note: if NAME includes symlinks, the information is for the volume
3144 of the symlink, not of its target. That's because, even though
3145 GetVolumeInformation returns information about the symlink target
3146 of its argument, we only pass the root directory to
3147 GetVolumeInformation, not the full NAME. */
3149 get_volume_info (const char * name
, const char ** pPath
)
3151 char temp
[MAX_UTF8_PATH
];
3152 char *rootname
= NULL
; /* default to current volume */
3153 volume_info_data
* info
;
3154 int root_len
= parse_root (name
, pPath
);
3159 /* Copy the root name of the volume, if given. */
3162 strncpy (temp
, name
, root_len
);
3163 temp
[root_len
] = '\0';
3164 unixtodos_filename (temp
);
3168 info
= GetCachedVolumeInformation (rootname
);
3171 /* Set global referenced by other functions. */
3172 volume_info
= *info
;
3178 /* Determine if volume is FAT format (ie. only supports short 8.3
3179 names); also set path pointer to start of pathname in name, if
3180 pPath is non-NULL. */
3182 is_fat_volume (const char * name
, const char ** pPath
)
3184 if (get_volume_info (name
, pPath
))
3185 return (volume_info
.maxcomp
== 12);
3189 /* Convert all slashes in a filename to backslashes, and map filename
3190 to a valid 8.3 name if necessary. The result is a pointer to a
3191 static buffer, so CAVEAT EMPTOR! */
3193 map_w32_filename (const char * name
, const char ** pPath
)
3195 static char shortname
[MAX_UTF8_PATH
];
3196 char * str
= shortname
;
3199 const char * save_name
= name
;
3201 if (strlen (name
) >= sizeof (shortname
))
3203 /* Return a filename which will cause callers to fail. */
3204 strcpy (shortname
, "?");
3208 if (is_fat_volume (name
, (const char **)&path
)) /* truncate to 8.3 */
3210 register int left
= 8; /* maximum number of chars in part */
3211 register int extn
= 0; /* extension added? */
3212 register int dots
= 2; /* maximum number of dots allowed */
3215 *str
++ = *name
++; /* skip past UNC header */
3217 while ((c
= *name
++))
3224 *str
++ = (c
== ':' ? ':' : '\\');
3225 extn
= 0; /* reset extension flags */
3226 dots
= 2; /* max 2 dots */
3227 left
= 8; /* max length 8 for main part */
3232 /* Convert path components of the form .xxx to _xxx,
3233 but leave . and .. as they are. This allows .emacs
3234 to be read as _emacs, for example. */
3238 IS_DIRECTORY_SEP (*name
))
3253 extn
= 1; /* we've got an extension */
3254 left
= 3; /* 3 chars in extension */
3258 /* any embedded dots after the first are converted to _ */
3263 case '#': /* don't lose these, they're important */
3265 str
[-1] = c
; /* replace last character of part */
3268 if ( left
&& 'A' <= c
&& c
<= 'Z' )
3270 *str
++ = tolower (c
); /* map to lower case (looks nicer) */
3272 dots
= 0; /* started a path component */
3281 strcpy (shortname
, name
);
3282 unixtodos_filename (shortname
);
3286 *pPath
= shortname
+ (path
- save_name
);
3292 is_exec (const char * name
)
3294 char * p
= strrchr (name
, '.');
3297 && (xstrcasecmp (p
, ".exe") == 0 ||
3298 xstrcasecmp (p
, ".com") == 0 ||
3299 xstrcasecmp (p
, ".bat") == 0 ||
3300 xstrcasecmp (p
, ".cmd") == 0));
3303 /* Emulate the Unix directory procedures opendir, closedir, and
3304 readdir. We rename them to sys_* names because some versions of
3305 MinGW startup code call opendir and readdir to glob wildcards, and
3306 the code that calls them doesn't grok UTF-8 encoded file names we
3307 produce in dirent->d_name[]. */
3309 struct dirent dir_static
; /* simulated directory contents */
3310 static HANDLE dir_find_handle
= INVALID_HANDLE_VALUE
;
3311 static int dir_is_fat
;
3312 static char dir_pathname
[MAX_UTF8_PATH
];
3313 static WIN32_FIND_DATAW dir_find_data_w
;
3314 static WIN32_FIND_DATAA dir_find_data_a
;
3315 #define DIR_FIND_DATA_W 1
3316 #define DIR_FIND_DATA_A 2
3317 static int last_dir_find_data
= -1;
3319 /* Support shares on a network resource as subdirectories of a read-only
3321 static HANDLE wnet_enum_handle
= INVALID_HANDLE_VALUE
;
3322 static HANDLE
open_unc_volume (const char *);
3323 static void *read_unc_volume (HANDLE
, wchar_t *, char *, int);
3324 static void close_unc_volume (HANDLE
);
3327 sys_opendir (const char *filename
)
3331 /* Opening is done by FindFirstFile. However, a read is inherent to
3332 this operation, so we defer the open until read time. */
3334 if (dir_find_handle
!= INVALID_HANDLE_VALUE
)
3336 if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
3339 /* Note: We don't support traversal of UNC volumes via symlinks.
3340 Doing so would mean punishing 99.99% of use cases by resolving
3341 all the possible symlinks in FILENAME, recursively. */
3342 if (is_unc_volume (filename
))
3344 wnet_enum_handle
= open_unc_volume (filename
);
3345 if (wnet_enum_handle
== INVALID_HANDLE_VALUE
)
3349 if (!(dirp
= (DIR *) malloc (sizeof (DIR))))
3356 strncpy (dir_pathname
, map_w32_filename (filename
, NULL
), MAX_UTF8_PATH
- 1);
3357 dir_pathname
[MAX_UTF8_PATH
- 1] = '\0';
3358 /* Note: We don't support symlinks to file names on FAT volumes.
3359 Doing so would mean punishing 99.99% of use cases by resolving
3360 all the possible symlinks in FILENAME, recursively. */
3361 dir_is_fat
= is_fat_volume (filename
, NULL
);
3367 sys_closedir (DIR *dirp
)
3369 /* If we have a find-handle open, close it. */
3370 if (dir_find_handle
!= INVALID_HANDLE_VALUE
)
3372 FindClose (dir_find_handle
);
3373 dir_find_handle
= INVALID_HANDLE_VALUE
;
3375 else if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
3377 close_unc_volume (wnet_enum_handle
);
3378 wnet_enum_handle
= INVALID_HANDLE_VALUE
;
3380 xfree ((char *) dirp
);
3384 sys_readdir (DIR *dirp
)
3386 int downcase
= !NILP (Vw32_downcase_file_names
);
3388 if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
3390 if (!read_unc_volume (wnet_enum_handle
,
3391 dir_find_data_w
.cFileName
,
3392 dir_find_data_a
.cFileName
,
3396 /* If we aren't dir_finding, do a find-first, otherwise do a find-next. */
3397 else if (dir_find_handle
== INVALID_HANDLE_VALUE
)
3399 char filename
[MAX_UTF8_PATH
+ 2];
3402 strcpy (filename
, dir_pathname
);
3403 ln
= strlen (filename
) - 1;
3404 if (!IS_DIRECTORY_SEP (filename
[ln
]))
3405 strcat (filename
, "\\");
3406 strcat (filename
, "*");
3408 /* Note: No need to resolve symlinks in FILENAME, because
3409 FindFirst opens the directory that is the target of a
3411 if (w32_unicode_filenames
)
3413 wchar_t fnw
[MAX_PATH
];
3415 filename_to_utf16 (filename
, fnw
);
3416 dir_find_handle
= FindFirstFileW (fnw
, &dir_find_data_w
);
3422 filename_to_ansi (filename
, fna
);
3423 /* If FILENAME is not representable by the current ANSI
3424 codepage, we don't want FindFirstFileA to interpret the
3425 '?' characters as a wildcard. */
3426 if (_mbspbrk (fna
, "?"))
3427 dir_find_handle
= INVALID_HANDLE_VALUE
;
3429 dir_find_handle
= FindFirstFileA (fna
, &dir_find_data_a
);
3432 if (dir_find_handle
== INVALID_HANDLE_VALUE
)
3435 else if (w32_unicode_filenames
)
3437 if (!FindNextFileW (dir_find_handle
, &dir_find_data_w
))
3442 if (!FindNextFileA (dir_find_handle
, &dir_find_data_a
))
3446 /* Emacs never uses this value, so don't bother making it match
3447 value returned by stat(). */
3448 dir_static
.d_ino
= 1;
3450 if (w32_unicode_filenames
)
3452 if (downcase
|| dir_is_fat
)
3454 wchar_t tem
[MAX_PATH
];
3456 wcscpy (tem
, dir_find_data_w
.cFileName
);
3458 filename_from_utf16 (tem
, dir_static
.d_name
);
3461 filename_from_utf16 (dir_find_data_w
.cFileName
, dir_static
.d_name
);
3462 last_dir_find_data
= DIR_FIND_DATA_W
;
3468 /* If the file name in cFileName[] includes `?' characters, it
3469 means the original file name used characters that cannot be
3470 represented by the current ANSI codepage. To avoid total
3471 lossage, retrieve the short 8+3 alias of the long file
3473 if (_mbspbrk (dir_find_data_a
.cFileName
, "?"))
3475 strcpy (tem
, dir_find_data_a
.cAlternateFileName
);
3476 /* 8+3 aliases are returned in all caps, which could break
3477 various alists that look at filenames' extensions. */
3480 else if (downcase
|| dir_is_fat
)
3481 strcpy (tem
, dir_find_data_a
.cFileName
);
3483 filename_from_ansi (dir_find_data_a
.cFileName
, dir_static
.d_name
);
3484 if (downcase
|| dir_is_fat
)
3487 filename_from_ansi (tem
, dir_static
.d_name
);
3489 last_dir_find_data
= DIR_FIND_DATA_A
;
3492 dir_static
.d_namlen
= strlen (dir_static
.d_name
);
3493 dir_static
.d_reclen
= sizeof (struct dirent
) - MAX_UTF8_PATH
+ 3 +
3494 dir_static
.d_namlen
- dir_static
.d_namlen
% 4;
3500 open_unc_volume (const char *path
)
3502 const char *fn
= map_w32_filename (path
, NULL
);
3506 if (w32_unicode_filenames
)
3509 wchar_t fnw
[MAX_PATH
];
3511 nrw
.dwScope
= RESOURCE_GLOBALNET
;
3512 nrw
.dwType
= RESOURCETYPE_DISK
;
3513 nrw
.dwDisplayType
= RESOURCEDISPLAYTYPE_SERVER
;
3514 nrw
.dwUsage
= RESOURCEUSAGE_CONTAINER
;
3515 nrw
.lpLocalName
= NULL
;
3516 filename_to_utf16 (fn
, fnw
);
3517 nrw
.lpRemoteName
= fnw
;
3518 nrw
.lpComment
= NULL
;
3519 nrw
.lpProvider
= NULL
;
3521 result
= WNetOpenEnumW (RESOURCE_GLOBALNET
, RESOURCETYPE_DISK
,
3522 RESOURCEUSAGE_CONNECTABLE
, &nrw
, &henum
);
3529 nra
.dwScope
= RESOURCE_GLOBALNET
;
3530 nra
.dwType
= RESOURCETYPE_DISK
;
3531 nra
.dwDisplayType
= RESOURCEDISPLAYTYPE_SERVER
;
3532 nra
.dwUsage
= RESOURCEUSAGE_CONTAINER
;
3533 nra
.lpLocalName
= NULL
;
3534 filename_to_ansi (fn
, fna
);
3535 nra
.lpRemoteName
= fna
;
3536 nra
.lpComment
= NULL
;
3537 nra
.lpProvider
= NULL
;
3539 result
= WNetOpenEnumA (RESOURCE_GLOBALNET
, RESOURCETYPE_DISK
,
3540 RESOURCEUSAGE_CONNECTABLE
, &nra
, &henum
);
3542 if (result
== NO_ERROR
)
3545 return INVALID_HANDLE_VALUE
;
3549 read_unc_volume (HANDLE henum
, wchar_t *fname_w
, char *fname_a
, int size
)
3554 DWORD bufsize
= 512;
3558 if (w32_unicode_filenames
)
3563 buffer
= alloca (bufsize
);
3564 result
= WNetEnumResourceW (henum
, &count
, buffer
, &bufsize
);
3565 if (result
!= NO_ERROR
)
3567 /* WNetEnumResource returns \\resource\share...skip forward to "share". */
3568 ptrw
= ((LPNETRESOURCEW
) buffer
)->lpRemoteName
;
3570 while (*ptrw
&& *ptrw
!= L
'/' && *ptrw
!= L
'\\') ptrw
++;
3572 wcsncpy (fname_w
, ptrw
, size
);
3577 int dbcs_p
= max_filename_mbslen () > 1;
3580 buffer
= alloca (bufsize
);
3581 result
= WNetEnumResourceA (henum
, &count
, buffer
, &bufsize
);
3582 if (result
!= NO_ERROR
)
3584 ptra
= ((LPNETRESOURCEA
) buffer
)->lpRemoteName
;
3587 while (*ptra
&& !IS_DIRECTORY_SEP (*ptra
)) ptra
++;
3590 while (*ptra
&& !IS_DIRECTORY_SEP (*ptra
))
3591 ptra
= CharNextExA (file_name_codepage
, ptra
, 0);
3594 strncpy (fname_a
, ptra
, size
);
3602 close_unc_volume (HANDLE henum
)
3604 if (henum
!= INVALID_HANDLE_VALUE
)
3605 WNetCloseEnum (henum
);
3609 unc_volume_file_attributes (const char *path
)
3614 henum
= open_unc_volume (path
);
3615 if (henum
== INVALID_HANDLE_VALUE
)
3618 attrs
= FILE_ATTRIBUTE_READONLY
| FILE_ATTRIBUTE_DIRECTORY
;
3620 close_unc_volume (henum
);
3625 /* Ensure a network connection is authenticated. */
3627 logon_network_drive (const char *path
)
3629 char share
[MAX_UTF8_PATH
];
3636 if (IS_DIRECTORY_SEP (path
[0]) && IS_DIRECTORY_SEP (path
[1]))
3637 drvtype
= DRIVE_REMOTE
;
3638 else if (path
[0] == '\0' || path
[1] != ':')
3639 drvtype
= GetDriveType (NULL
);
3646 drvtype
= GetDriveType (drive
);
3649 /* Only logon to networked drives. */
3650 if (drvtype
!= DRIVE_REMOTE
)
3654 strncpy (share
, path
, MAX_UTF8_PATH
);
3655 /* Truncate to just server and share name. */
3656 for (p
= share
+ 2; *p
&& p
< share
+ MAX_UTF8_PATH
; p
++)
3658 if (IS_DIRECTORY_SEP (*p
) && ++n_slashes
> 3)
3665 if (w32_unicode_filenames
)
3667 NETRESOURCEW resourcew
;
3668 wchar_t share_w
[MAX_PATH
];
3670 resourcew
.dwScope
= RESOURCE_GLOBALNET
;
3671 resourcew
.dwType
= RESOURCETYPE_DISK
;
3672 resourcew
.dwDisplayType
= RESOURCEDISPLAYTYPE_SHARE
;
3673 resourcew
.dwUsage
= RESOURCEUSAGE_CONTAINER
;
3674 resourcew
.lpLocalName
= NULL
;
3675 filename_to_utf16 (share
, share_w
);
3676 resourcew
.lpRemoteName
= share_w
;
3677 resourcew
.lpProvider
= NULL
;
3679 val
= WNetAddConnection2W (&resourcew
, NULL
, NULL
, CONNECT_INTERACTIVE
);
3683 NETRESOURCEA resourcea
;
3684 char share_a
[MAX_PATH
];
3686 resourcea
.dwScope
= RESOURCE_GLOBALNET
;
3687 resourcea
.dwType
= RESOURCETYPE_DISK
;
3688 resourcea
.dwDisplayType
= RESOURCEDISPLAYTYPE_SHARE
;
3689 resourcea
.dwUsage
= RESOURCEUSAGE_CONTAINER
;
3690 resourcea
.lpLocalName
= NULL
;
3691 filename_to_ansi (share
, share_a
);
3692 resourcea
.lpRemoteName
= share_a
;
3693 resourcea
.lpProvider
= NULL
;
3695 val
= WNetAddConnection2A (&resourcea
, NULL
, NULL
, CONNECT_INTERACTIVE
);
3701 case ERROR_ALREADY_ASSIGNED
:
3703 case ERROR_ACCESS_DENIED
:
3704 case ERROR_LOGON_FAILURE
:
3710 case ERROR_BAD_NET_NAME
:
3711 case ERROR_NO_NET_OR_BAD_PATH
:
3712 case ERROR_NO_NETWORK
:
3713 case ERROR_CANCELLED
:
3720 /* Emulate faccessat(2). */
3722 faccessat (int dirfd
, const char * path
, int mode
, int flags
)
3726 if (dirfd
!= AT_FDCWD
3727 && !(IS_DIRECTORY_SEP (path
[0])
3728 || IS_DEVICE_SEP (path
[1])))
3734 /* MSVCRT implementation of 'access' doesn't recognize D_OK, and its
3735 newer versions blow up when passed D_OK. */
3736 path
= map_w32_filename (path
, NULL
);
3737 /* If the last element of PATH is a symlink, we need to resolve it
3738 to get the attributes of its target file. Note: any symlinks in
3739 PATH elements other than the last one are transparently resolved
3740 by GetFileAttributes below. */
3741 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) != 0
3742 && (flags
& AT_SYMLINK_NOFOLLOW
) == 0)
3743 path
= chase_symlinks (path
);
3745 if (w32_unicode_filenames
)
3747 wchar_t path_w
[MAX_PATH
];
3749 filename_to_utf16 (path
, path_w
);
3750 attributes
= GetFileAttributesW (path_w
);
3754 char path_a
[MAX_PATH
];
3756 filename_to_ansi (path
, path_a
);
3757 attributes
= GetFileAttributesA (path_a
);
3760 if (attributes
== -1)
3762 DWORD w32err
= GetLastError ();
3766 case ERROR_INVALID_NAME
:
3767 case ERROR_BAD_PATHNAME
:
3768 if (is_unc_volume (path
))
3770 attributes
= unc_volume_file_attributes (path
);
3771 if (attributes
== -1)
3779 case ERROR_FILE_NOT_FOUND
:
3780 case ERROR_BAD_NETPATH
:
3789 if ((mode
& X_OK
) != 0
3790 && !(is_exec (path
) || (attributes
& FILE_ATTRIBUTE_DIRECTORY
) != 0))
3795 if ((mode
& W_OK
) != 0 && (attributes
& FILE_ATTRIBUTE_READONLY
) != 0)
3800 if ((mode
& D_OK
) != 0 && (attributes
& FILE_ATTRIBUTE_DIRECTORY
) == 0)
3808 /* A version of 'access' to be used locally with file names in
3809 locale-specific encoding. Does not resolve symlinks and does not
3810 support file names on FAT12 and FAT16 volumes, but that's OK, since
3811 we only invoke this function for files inside the Emacs source or
3812 installation tree, on directories (so any symlinks should have the
3813 directory bit set), and on short file names such as "C:/.emacs". */
3815 sys_access (const char *fname
, int mode
)
3817 char fname_copy
[MAX_PATH
], *p
;
3820 strcpy (fname_copy
, fname
);
3821 /* Do the equivalent of unixtodos_filename. */
3822 for (p
= fname_copy
; *p
; p
= CharNext (p
))
3826 if ((attributes
= GetFileAttributesA (fname_copy
)) == -1)
3828 DWORD w32err
= GetLastError ();
3832 case ERROR_INVALID_NAME
:
3833 case ERROR_BAD_PATHNAME
:
3834 case ERROR_FILE_NOT_FOUND
:
3835 case ERROR_BAD_NETPATH
:
3844 if ((mode
& X_OK
) != 0
3845 && !(is_exec (fname_copy
)
3846 || (attributes
& FILE_ATTRIBUTE_DIRECTORY
) != 0))
3851 if ((mode
& W_OK
) != 0 && (attributes
& FILE_ATTRIBUTE_READONLY
) != 0)
3856 if ((mode
& D_OK
) != 0 && (attributes
& FILE_ATTRIBUTE_DIRECTORY
) == 0)
3864 /* Shadow some MSVC runtime functions to map requests for long filenames
3865 to reasonable short names if necessary. This was originally added to
3866 permit running Emacs on NT 3.1 on a FAT partition, which doesn't support
3870 sys_chdir (const char * path
)
3872 path
= map_w32_filename (path
, NULL
);
3873 if (w32_unicode_filenames
)
3875 wchar_t newdir_w
[MAX_PATH
];
3877 if (filename_to_utf16 (path
, newdir_w
) == 0)
3878 return _wchdir (newdir_w
);
3883 char newdir_a
[MAX_PATH
];
3885 if (filename_to_ansi (path
, newdir_a
) == 0)
3886 return _chdir (newdir_a
);
3892 sys_chmod (const char * path
, int mode
)
3894 path
= chase_symlinks (map_w32_filename (path
, NULL
));
3895 if (w32_unicode_filenames
)
3897 wchar_t path_w
[MAX_PATH
];
3899 filename_to_utf16 (path
, path_w
);
3900 return _wchmod (path_w
, mode
);
3904 char path_a
[MAX_PATH
];
3906 filename_to_ansi (path
, path_a
);
3907 return _chmod (path_a
, mode
);
3912 sys_creat (const char * path
, int mode
)
3914 path
= map_w32_filename (path
, NULL
);
3915 if (w32_unicode_filenames
)
3917 wchar_t path_w
[MAX_PATH
];
3919 filename_to_utf16 (path
, path_w
);
3920 return _wcreat (path_w
, mode
);
3924 char path_a
[MAX_PATH
];
3926 filename_to_ansi (path
, path_a
);
3927 return _creat (path_a
, mode
);
3932 sys_fopen (const char * path
, const char * mode
)
3936 const char * mode_save
= mode
;
3938 /* Force all file handles to be non-inheritable. This is necessary to
3939 ensure child processes don't unwittingly inherit handles that might
3940 prevent future file access. */
3944 else if (mode
[0] == 'w' || mode
[0] == 'a')
3945 oflag
= O_WRONLY
| O_CREAT
| O_TRUNC
;
3949 /* Only do simplistic option parsing. */
3953 oflag
&= ~(O_RDONLY
| O_WRONLY
);
3956 else if (mode
[0] == 'b')
3961 else if (mode
[0] == 't')
3968 path
= map_w32_filename (path
, NULL
);
3969 if (w32_unicode_filenames
)
3971 wchar_t path_w
[MAX_PATH
];
3973 filename_to_utf16 (path
, path_w
);
3974 fd
= _wopen (path_w
, oflag
| _O_NOINHERIT
, 0644);
3978 char path_a
[MAX_PATH
];
3980 filename_to_ansi (path
, path_a
);
3981 fd
= _open (path_a
, oflag
| _O_NOINHERIT
, 0644);
3986 return _fdopen (fd
, mode_save
);
3989 /* This only works on NTFS volumes, but is useful to have. */
3991 sys_link (const char * old
, const char * new)
3995 char oldname
[MAX_UTF8_PATH
], newname
[MAX_UTF8_PATH
];
3996 wchar_t oldname_w
[MAX_PATH
];
3997 char oldname_a
[MAX_PATH
];
3999 if (old
== NULL
|| new == NULL
)
4005 strcpy (oldname
, map_w32_filename (old
, NULL
));
4006 strcpy (newname
, map_w32_filename (new, NULL
));
4008 if (w32_unicode_filenames
)
4010 filename_to_utf16 (oldname
, oldname_w
);
4011 fileh
= CreateFileW (oldname_w
, 0, 0, NULL
, OPEN_EXISTING
,
4012 FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
4016 filename_to_ansi (oldname
, oldname_a
);
4017 fileh
= CreateFileA (oldname_a
, 0, 0, NULL
, OPEN_EXISTING
,
4018 FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
4020 if (fileh
!= INVALID_HANDLE_VALUE
)
4024 /* Confusingly, the "alternate" stream name field does not apply
4025 when restoring a hard link, and instead contains the actual
4026 stream data for the link (ie. the name of the link to create).
4027 The WIN32_STREAM_ID structure before the cStreamName field is
4028 the stream header, which is then immediately followed by the
4032 WIN32_STREAM_ID wid
;
4033 WCHAR wbuffer
[MAX_PATH
]; /* extra space for link name */
4036 /* We used to pass MB_PRECOMPOSED as the 2nd arg here, but MSDN
4037 indicates that flag is unsupported for CP_UTF8, and OTOH says
4038 it is the default anyway. */
4039 wlen
= pMultiByteToWideChar (CP_UTF8
, 0, newname
, -1,
4040 data
.wid
.cStreamName
, MAX_PATH
);
4043 LPVOID context
= NULL
;
4046 data
.wid
.dwStreamId
= BACKUP_LINK
;
4047 data
.wid
.dwStreamAttributes
= 0;
4048 data
.wid
.Size
.LowPart
= wlen
* sizeof (WCHAR
);
4049 data
.wid
.Size
.HighPart
= 0;
4050 data
.wid
.dwStreamNameSize
= 0;
4052 if (BackupWrite (fileh
, (LPBYTE
)&data
,
4053 offsetof (WIN32_STREAM_ID
, cStreamName
)
4054 + data
.wid
.Size
.LowPart
,
4055 &wbytes
, FALSE
, FALSE
, &context
)
4056 && BackupWrite (fileh
, NULL
, 0, &wbytes
, TRUE
, FALSE
, &context
))
4063 DWORD err
= GetLastError ();
4068 case ERROR_ACCESS_DENIED
:
4069 /* This is what happens when OLDNAME is a directory,
4070 since Windows doesn't support hard links to
4071 directories. Posix says to set errno to EPERM in
4073 if (w32_unicode_filenames
)
4074 attributes
= GetFileAttributesW (oldname_w
);
4076 attributes
= GetFileAttributesA (oldname_a
);
4077 if (attributes
!= -1
4078 && (attributes
& FILE_ATTRIBUTE_DIRECTORY
) != 0)
4080 else if (attributes
== -1
4081 && is_unc_volume (oldname
)
4082 && unc_volume_file_attributes (oldname
) != -1)
4087 case ERROR_TOO_MANY_LINKS
:
4090 case ERROR_NOT_SAME_DEVICE
:
4100 CloseHandle (fileh
);
4109 sys_mkdir (const char * path
)
4111 path
= map_w32_filename (path
, NULL
);
4113 if (w32_unicode_filenames
)
4115 wchar_t path_w
[MAX_PATH
];
4117 filename_to_utf16 (path
, path_w
);
4118 return _wmkdir (path_w
);
4122 char path_a
[MAX_PATH
];
4124 filename_to_ansi (path
, path_a
);
4125 return _mkdir (path_a
);
4130 sys_open (const char * path
, int oflag
, int mode
)
4132 const char* mpath
= map_w32_filename (path
, NULL
);
4135 if (w32_unicode_filenames
)
4137 wchar_t mpath_w
[MAX_PATH
];
4139 filename_to_utf16 (mpath
, mpath_w
);
4140 /* If possible, try to open file without _O_CREAT, to be able to
4141 write to existing hidden and system files. Force all file
4142 handles to be non-inheritable. */
4143 if ((oflag
& (_O_CREAT
| _O_EXCL
)) != (_O_CREAT
| _O_EXCL
))
4144 res
= _wopen (mpath_w
, (oflag
& ~_O_CREAT
) | _O_NOINHERIT
, mode
);
4146 res
= _wopen (mpath_w
, oflag
| _O_NOINHERIT
, mode
);
4150 char mpath_a
[MAX_PATH
];
4152 filename_to_ansi (mpath
, mpath_a
);
4153 if ((oflag
& (_O_CREAT
| _O_EXCL
)) != (_O_CREAT
| _O_EXCL
))
4154 res
= _open (mpath_a
, (oflag
& ~_O_CREAT
) | _O_NOINHERIT
, mode
);
4156 res
= _open (mpath_a
, oflag
| _O_NOINHERIT
, mode
);
4162 /* Implementation of mkostemp for MS-Windows, to avoid race conditions
4165 Standard algorithm for generating a temporary file name seems to be
4166 use pid or tid with a letter on the front (in place of the 6 X's)
4167 and cycle through the letters to find a unique name. We extend
4168 that to allow any reasonable character as the first of the 6 X's,
4169 so that the number of simultaneously used temporary files will be
4173 mkostemp (char * template, int flags
)
4177 unsigned uid
= GetCurrentThreadId ();
4178 int save_errno
= errno
;
4179 static char first_char
[] = "abcdefghijklmnopqrstuvwyz0123456789!%-_@#";
4182 if (template == NULL
)
4185 p
= template + strlen (template);
4187 /* replace up to the last 5 X's with uid in decimal */
4188 while (--p
>= template && p
[0] == 'X' && --i
>= 0)
4190 p
[0] = '0' + uid
% 10;
4194 if (i
< 0 && p
[0] == 'X')
4199 p
[0] = first_char
[i
];
4200 if ((fd
= sys_open (template,
4201 flags
| _O_CREAT
| _O_EXCL
| _O_RDWR
,
4202 S_IRUSR
| S_IWUSR
)) >= 0
4210 while (++i
< sizeof (first_char
));
4213 /* Template is badly formed or else we can't generate a unique name. */
4218 fchmod (int fd
, mode_t mode
)
4224 sys_rename_replace (const char *oldname
, const char *newname
, BOOL force
)
4227 char temp
[MAX_UTF8_PATH
], temp_a
[MAX_PATH
];;
4230 bool have_temp_a
= false;
4232 /* MoveFile on Windows 95 doesn't correctly change the short file name
4233 alias in a number of circumstances (it is not easy to predict when
4234 just by looking at oldname and newname, unfortunately). In these
4235 cases, renaming through a temporary name avoids the problem.
4237 A second problem on Windows 95 is that renaming through a temp name when
4238 newname is uppercase fails (the final long name ends up in
4239 lowercase, although the short alias might be uppercase) UNLESS the
4240 long temp name is not 8.3.
4242 So, on Windows 95 we always rename through a temp name, and we make sure
4243 the temp name has a long extension to ensure correct renaming. */
4245 strcpy (temp
, map_w32_filename (oldname
, NULL
));
4247 /* volume_info is set indirectly by map_w32_filename. */
4248 oldname_dev
= volume_info
.serialnum
;
4250 if (os_subtype
== OS_9X
)
4255 char oldname_a
[MAX_PATH
];
4257 oldname
= map_w32_filename (oldname
, NULL
);
4258 filename_to_ansi (oldname
, oldname_a
);
4259 filename_to_ansi (temp
, temp_a
);
4260 if ((o
= strrchr (oldname_a
, '\\')))
4263 o
= (char *) oldname_a
;
4265 if ((p
= strrchr (temp_a
, '\\')))
4272 /* Force temp name to require a manufactured 8.3 alias - this
4273 seems to make the second rename work properly. */
4274 sprintf (p
, "_.%s.%u", o
, i
);
4276 result
= rename (oldname_a
, temp_a
);
4278 /* This loop must surely terminate! */
4279 while (result
< 0 && errno
== EEXIST
);
4285 /* If FORCE, emulate Unix behavior - newname is deleted if it already exists
4286 (at least if it is a file; don't do this for directories).
4288 Since we mustn't do this if we are just changing the case of the
4289 file name (we would end up deleting the file we are trying to
4290 rename!), we let rename detect if the destination file already
4291 exists - that way we avoid the possible pitfalls of trying to
4292 determine ourselves whether two names really refer to the same
4293 file, which is not always possible in the general case. (Consider
4294 all the permutations of shared or subst'd drives, etc.) */
4296 newname
= map_w32_filename (newname
, NULL
);
4298 /* volume_info is set indirectly by map_w32_filename. */
4299 newname_dev
= volume_info
.serialnum
;
4301 if (w32_unicode_filenames
)
4303 wchar_t temp_w
[MAX_PATH
], newname_w
[MAX_PATH
];
4305 filename_to_utf16 (temp
, temp_w
);
4306 filename_to_utf16 (newname
, newname_w
);
4307 result
= _wrename (temp_w
, newname_w
);
4308 if (result
< 0 && force
)
4310 DWORD w32err
= GetLastError ();
4313 && newname_dev
!= oldname_dev
)
4315 /* The implementation of `rename' on Windows does not return
4316 errno = EXDEV when you are moving a directory to a
4317 different storage device (ex. logical disk). It returns
4318 EACCES instead. So here we handle such situations and
4322 if ((attributes
= GetFileAttributesW (temp_w
)) != -1
4323 && (attributes
& FILE_ATTRIBUTE_DIRECTORY
))
4326 else if (errno
== EEXIST
)
4328 if (_wchmod (newname_w
, 0666) != 0)
4330 if (_wunlink (newname_w
) != 0)
4332 result
= _wrename (temp_w
, newname_w
);
4334 else if (w32err
== ERROR_PRIVILEGE_NOT_HELD
4335 && is_symlink (temp
))
4337 /* This is Windows prohibiting the user from creating a
4338 symlink in another place, since that requires
4346 char newname_a
[MAX_PATH
];
4349 filename_to_ansi (temp
, temp_a
);
4350 filename_to_ansi (newname
, newname_a
);
4351 result
= rename (temp_a
, newname_a
);
4352 if (result
< 0 && force
)
4354 DWORD w32err
= GetLastError ();
4357 && newname_dev
!= oldname_dev
)
4361 if ((attributes
= GetFileAttributesA (temp_a
)) != -1
4362 && (attributes
& FILE_ATTRIBUTE_DIRECTORY
))
4365 else if (errno
== EEXIST
)
4367 if (_chmod (newname_a
, 0666) != 0)
4369 if (_unlink (newname_a
) != 0)
4371 result
= rename (temp_a
, newname_a
);
4373 else if (w32err
== ERROR_PRIVILEGE_NOT_HELD
4374 && is_symlink (temp
))
4383 sys_rename (char const *old
, char const *new)
4385 return sys_rename_replace (old
, new, TRUE
);
4389 sys_rmdir (const char * path
)
4391 path
= map_w32_filename (path
, NULL
);
4393 if (w32_unicode_filenames
)
4395 wchar_t path_w
[MAX_PATH
];
4397 filename_to_utf16 (path
, path_w
);
4398 return _wrmdir (path_w
);
4402 char path_a
[MAX_PATH
];
4404 filename_to_ansi (path
, path_a
);
4405 return _rmdir (path_a
);
4410 sys_unlink (const char * path
)
4412 path
= map_w32_filename (path
, NULL
);
4414 if (w32_unicode_filenames
)
4416 wchar_t path_w
[MAX_PATH
];
4418 filename_to_utf16 (path
, path_w
);
4419 /* On Unix, unlink works without write permission. */
4420 _wchmod (path_w
, 0666);
4421 return _wunlink (path_w
);
4425 char path_a
[MAX_PATH
];
4427 filename_to_ansi (path
, path_a
);
4428 _chmod (path_a
, 0666);
4429 return _unlink (path_a
);
4433 static FILETIME utc_base_ft
;
4434 static ULONGLONG utc_base
; /* In 100ns units */
4435 static int init
= 0;
4437 #define FILETIME_TO_U64(result, ft) \
4439 ULARGE_INTEGER uiTemp; \
4440 uiTemp.LowPart = (ft).dwLowDateTime; \
4441 uiTemp.HighPart = (ft).dwHighDateTime; \
4442 result = uiTemp.QuadPart; \
4446 initialize_utc_base (void)
4448 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
4457 st
.wMilliseconds
= 0;
4459 SystemTimeToFileTime (&st
, &utc_base_ft
);
4460 FILETIME_TO_U64 (utc_base
, utc_base_ft
);
4464 convert_time (FILETIME ft
)
4470 initialize_utc_base ();
4474 if (CompareFileTime (&ft
, &utc_base_ft
) < 0)
4477 FILETIME_TO_U64 (tmp
, ft
);
4478 return (time_t) ((tmp
- utc_base
) / 10000000L);
4482 convert_from_time_t (time_t time
, FILETIME
* pft
)
4488 initialize_utc_base ();
4492 /* time in 100ns units since 1-Jan-1601 */
4493 tmp
.QuadPart
= (ULONGLONG
) time
* 10000000L + utc_base
;
4494 pft
->dwHighDateTime
= tmp
.HighPart
;
4495 pft
->dwLowDateTime
= tmp
.LowPart
;
4498 static PSECURITY_DESCRIPTOR
4499 get_file_security_desc_by_handle (HANDLE h
)
4501 PSECURITY_DESCRIPTOR psd
= NULL
;
4503 SECURITY_INFORMATION si
= OWNER_SECURITY_INFORMATION
4504 | GROUP_SECURITY_INFORMATION
/* | DACL_SECURITY_INFORMATION */ ;
4506 err
= get_security_info (h
, SE_FILE_OBJECT
, si
,
4507 NULL
, NULL
, NULL
, NULL
, &psd
);
4508 if (err
!= ERROR_SUCCESS
)
4514 static PSECURITY_DESCRIPTOR
4515 get_file_security_desc_by_name (const char *fname
)
4517 PSECURITY_DESCRIPTOR psd
= NULL
;
4519 SECURITY_INFORMATION si
= OWNER_SECURITY_INFORMATION
4520 | GROUP_SECURITY_INFORMATION
/* | DACL_SECURITY_INFORMATION */ ;
4522 if (!get_file_security (fname
, si
, psd
, 0, &sd_len
))
4524 err
= GetLastError ();
4525 if (err
!= ERROR_INSUFFICIENT_BUFFER
)
4529 psd
= xmalloc (sd_len
);
4530 if (!get_file_security (fname
, si
, psd
, sd_len
, &sd_len
))
4542 unsigned n_subauthorities
;
4544 /* Use the last sub-authority value of the RID, the relative
4545 portion of the SID, as user/group ID. */
4546 n_subauthorities
= *get_sid_sub_authority_count (sid
);
4547 if (n_subauthorities
< 1)
4548 return 0; /* the "World" RID */
4549 return *get_sid_sub_authority (sid
, n_subauthorities
- 1);
4552 /* Caching SID and account values for faster lokup. */
4556 struct w32_id
*next
;
4558 unsigned char sid
[FLEXIBLE_ARRAY_MEMBER
];
4561 static struct w32_id
*w32_idlist
;
4564 w32_cached_id (PSID sid
, unsigned *id
, char *name
)
4566 struct w32_id
*tail
, *found
;
4568 for (found
= NULL
, tail
= w32_idlist
; tail
; tail
= tail
->next
)
4570 if (equal_sid ((PSID
)tail
->sid
, sid
))
4579 strcpy (name
, found
->name
);
4587 w32_add_to_cache (PSID sid
, unsigned id
, char *name
)
4590 struct w32_id
*new_entry
;
4592 /* We don't want to leave behind stale cache from when Emacs was
4596 sid_len
= get_length_sid (sid
);
4597 new_entry
= xmalloc (offsetof (struct w32_id
, sid
) + sid_len
);
4600 new_entry
->rid
= id
;
4601 strcpy (new_entry
->name
, name
);
4602 copy_sid (sid_len
, (PSID
)new_entry
->sid
, sid
);
4603 new_entry
->next
= w32_idlist
;
4604 w32_idlist
= new_entry
;
4613 get_name_and_id (PSECURITY_DESCRIPTOR psd
, unsigned *id
, char *nm
, int what
)
4617 SID_NAME_USE ignore
;
4619 DWORD name_len
= sizeof (name
);
4621 DWORD domain_len
= sizeof (domain
);
4626 result
= get_security_descriptor_owner (psd
, &sid
, &dflt
);
4627 else if (what
== GID
)
4628 result
= get_security_descriptor_group (psd
, &sid
, &dflt
);
4632 if (!result
|| !is_valid_sid (sid
))
4634 else if (!w32_cached_id (sid
, id
, nm
))
4636 if (!lookup_account_sid (NULL
, sid
, name
, &name_len
,
4637 domain
, &domain_len
, &ignore
)
4638 || name_len
> UNLEN
+1)
4642 *id
= get_rid (sid
);
4644 w32_add_to_cache (sid
, *id
, name
);
4651 get_file_owner_and_group (PSECURITY_DESCRIPTOR psd
, struct stat
*st
)
4653 int dflt_usr
= 0, dflt_grp
= 0;
4662 if (get_name_and_id (psd
, &st
->st_uid
, st
->st_uname
, UID
))
4664 if (get_name_and_id (psd
, &st
->st_gid
, st
->st_gname
, GID
))
4667 /* Consider files to belong to current user/group, if we cannot get
4668 more accurate information. */
4671 st
->st_uid
= dflt_passwd
.pw_uid
;
4672 strcpy (st
->st_uname
, dflt_passwd
.pw_name
);
4676 st
->st_gid
= dflt_passwd
.pw_gid
;
4677 strcpy (st
->st_gname
, dflt_group
.gr_name
);
4681 /* Return non-zero if NAME is a potentially slow filesystem. */
4683 is_slow_fs (const char *name
)
4688 if (IS_DIRECTORY_SEP (name
[0]) && IS_DIRECTORY_SEP (name
[1]))
4689 devtype
= DRIVE_REMOTE
; /* assume UNC name is remote */
4690 else if (!(strlen (name
) >= 2 && IS_DEVICE_SEP (name
[1])))
4691 devtype
= GetDriveType (NULL
); /* use root of current drive */
4694 /* GetDriveType needs the root directory of the drive. */
4695 strncpy (drive_root
, name
, 2);
4696 drive_root
[2] = '\\';
4697 drive_root
[3] = '\0';
4698 devtype
= GetDriveType (drive_root
);
4700 return !(devtype
== DRIVE_FIXED
|| devtype
== DRIVE_RAMDISK
);
4703 /* If this is non-zero, the caller wants accurate information about
4704 file's owner and group, which could be expensive to get. dired.c
4705 uses this flag when needed for the job at hand. */
4706 int w32_stat_get_owner_group
;
4708 /* MSVC stat function can't cope with UNC names and has other bugs, so
4709 replace it with our own. This also allows us to calculate consistent
4710 inode values and owner/group without hacks in the main Emacs code,
4711 and support file names encoded in UTF-8. */
4714 stat_worker (const char * path
, struct stat
* buf
, int follow_symlinks
)
4716 char *name
, *save_name
, *r
;
4717 WIN32_FIND_DATAW wfd_w
;
4718 WIN32_FIND_DATAA wfd_a
;
4720 unsigned __int64 fake_inode
= 0;
4723 int rootdir
= FALSE
;
4724 PSECURITY_DESCRIPTOR psd
= NULL
;
4725 int is_a_symlink
= 0;
4726 DWORD file_flags
= FILE_FLAG_BACKUP_SEMANTICS
;
4727 DWORD access_rights
= 0;
4728 DWORD fattrs
= 0, serialnum
= 0, fs_high
= 0, fs_low
= 0, nlinks
= 1;
4729 FILETIME ctime
, atime
, wtime
;
4730 wchar_t name_w
[MAX_PATH
];
4731 char name_a
[MAX_PATH
];
4733 if (path
== NULL
|| buf
== NULL
)
4739 save_name
= name
= (char *) map_w32_filename (path
, &path
);
4740 /* Must be valid filename, no wild cards or other invalid
4742 if (strpbrk (name
, "*?|<>\""))
4748 len
= strlen (name
);
4749 /* Allocate 1 extra byte so that we could append a slash to a root
4750 directory, down below. */
4751 name
= strcpy (alloca (len
+ 2), name
);
4753 /* Avoid a somewhat costly call to is_symlink if the filesystem
4754 doesn't support symlinks. */
4755 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) != 0)
4756 is_a_symlink
= is_symlink (name
);
4758 /* Plan A: Open the file and get all the necessary information via
4759 the resulting handle. This solves several issues in one blow:
4761 . retrieves attributes for the target of a symlink, if needed
4762 . gets attributes of root directories and symlinks pointing to
4763 root directories, thus avoiding the need for special-casing
4764 these and detecting them by examining the file-name format
4765 . retrieves more accurate attributes (e.g., non-zero size for
4766 some directories, esp. directories that are junction points)
4767 . correctly resolves "c:/..", "/.." and similar file names
4768 . avoids run-time penalties for 99% of use cases
4770 Plan A is always tried first, unless the user asked not to (but
4771 if the file is a symlink and we need to follow links, we try Plan
4772 A even if the user asked not to).
4774 If Plan A fails, we go to Plan B (below), where various
4775 potentially expensive techniques must be used to handle "special"
4776 files such as UNC volumes etc. */
4777 if (!(NILP (Vw32_get_true_file_attributes
)
4778 || (EQ (Vw32_get_true_file_attributes
, Qlocal
) && is_slow_fs (name
)))
4779 /* Following symlinks requires getting the info by handle. */
4780 || (is_a_symlink
&& follow_symlinks
))
4782 BY_HANDLE_FILE_INFORMATION info
;
4784 if (is_a_symlink
&& !follow_symlinks
)
4785 file_flags
|= FILE_FLAG_OPEN_REPARSE_POINT
;
4786 /* READ_CONTROL access rights are required to get security info
4787 by handle. But if the OS doesn't support security in the
4788 first place, we don't need to try. */
4789 if (is_windows_9x () != TRUE
)
4790 access_rights
|= READ_CONTROL
;
4792 if (w32_unicode_filenames
)
4794 filename_to_utf16 (name
, name_w
);
4795 fh
= CreateFileW (name_w
, access_rights
, 0, NULL
, OPEN_EXISTING
,
4797 /* If CreateFile fails with READ_CONTROL, try again with
4798 zero as access rights. */
4799 if (fh
== INVALID_HANDLE_VALUE
&& access_rights
)
4800 fh
= CreateFileW (name_w
, 0, 0, NULL
, OPEN_EXISTING
,
4805 filename_to_ansi (name
, name_a
);
4806 fh
= CreateFileA (name_a
, access_rights
, 0, NULL
, OPEN_EXISTING
,
4808 if (fh
== INVALID_HANDLE_VALUE
&& access_rights
)
4809 fh
= CreateFileA (name_a
, 0, 0, NULL
, OPEN_EXISTING
,
4812 if (fh
== INVALID_HANDLE_VALUE
)
4813 goto no_true_file_attributes
;
4815 /* This is more accurate in terms of getting the correct number
4816 of links, but is quite slow (it is noticeable when Emacs is
4817 making a list of file name completions). */
4818 if (GetFileInformationByHandle (fh
, &info
))
4820 nlinks
= info
.nNumberOfLinks
;
4821 /* Might as well use file index to fake inode values, but this
4822 is not guaranteed to be unique unless we keep a handle open
4823 all the time (even then there are situations where it is
4824 not unique). Reputedly, there are at most 48 bits of info
4825 (on NTFS, presumably less on FAT). */
4826 fake_inode
= info
.nFileIndexHigh
;
4828 fake_inode
+= info
.nFileIndexLow
;
4829 serialnum
= info
.dwVolumeSerialNumber
;
4830 fs_high
= info
.nFileSizeHigh
;
4831 fs_low
= info
.nFileSizeLow
;
4832 ctime
= info
.ftCreationTime
;
4833 atime
= info
.ftLastAccessTime
;
4834 wtime
= info
.ftLastWriteTime
;
4835 fattrs
= info
.dwFileAttributes
;
4839 /* We don't go to Plan B here, because it's not clear that
4840 it's a good idea. The only known use case where
4841 CreateFile succeeds, but GetFileInformationByHandle fails
4842 (with ERROR_INVALID_FUNCTION) is for character devices
4843 such as NUL, PRN, etc. For these, switching to Plan B is
4844 a net loss, because we lose the character device
4845 attribute returned by GetFileType below (FindFirstFile
4846 doesn't set that bit in the attributes), and the other
4847 fields don't make sense for character devices anyway.
4848 Emacs doesn't really care for non-file entities in the
4849 context of l?stat, so neither do we. */
4851 /* w32err is assigned so one could put a breakpoint here and
4852 examine its value, when GetFileInformationByHandle
4854 DWORD w32err
= GetLastError ();
4858 case ERROR_FILE_NOT_FOUND
: /* can this ever happen? */
4864 /* Test for a symlink before testing for a directory, since
4865 symlinks to directories have the directory bit set, but we
4866 don't want them to appear as directories. */
4867 if (is_a_symlink
&& !follow_symlinks
)
4868 buf
->st_mode
= S_IFLNK
;
4869 else if (fattrs
& FILE_ATTRIBUTE_DIRECTORY
)
4870 buf
->st_mode
= S_IFDIR
;
4873 DWORD ftype
= GetFileType (fh
);
4877 case FILE_TYPE_DISK
:
4878 buf
->st_mode
= S_IFREG
;
4880 case FILE_TYPE_PIPE
:
4881 buf
->st_mode
= S_IFIFO
;
4883 case FILE_TYPE_CHAR
:
4884 case FILE_TYPE_UNKNOWN
:
4886 buf
->st_mode
= S_IFCHR
;
4889 /* We produce the fallback owner and group data, based on the
4890 current user that runs Emacs, in the following cases:
4892 . caller didn't request owner and group info
4893 . this is Windows 9X
4894 . getting security by handle failed, and we need to produce
4895 information for the target of a symlink (this is better
4896 than producing a potentially misleading info about the
4899 If getting security by handle fails, and we don't need to
4900 resolve symlinks, we try getting security by name. */
4901 if (!w32_stat_get_owner_group
|| is_windows_9x () == TRUE
)
4902 get_file_owner_and_group (NULL
, buf
);
4905 psd
= get_file_security_desc_by_handle (fh
);
4908 get_file_owner_and_group (psd
, buf
);
4911 else if (!(is_a_symlink
&& follow_symlinks
))
4913 psd
= get_file_security_desc_by_name (name
);
4914 get_file_owner_and_group (psd
, buf
);
4918 get_file_owner_and_group (NULL
, buf
);
4924 no_true_file_attributes
:
4925 /* Plan B: Either getting a handle on the file failed, or the
4926 caller explicitly asked us to not bother making this
4927 information more accurate.
4929 Implementation note: In Plan B, we never bother to resolve
4930 symlinks, even if we got here because we tried Plan A and
4931 failed. That's because, even if the caller asked for extra
4932 precision by setting Vw32_get_true_file_attributes to t,
4933 resolving symlinks requires acquiring a file handle to the
4934 symlink, which we already know will fail. And if the user
4935 did not ask for extra precision, resolving symlinks will fly
4936 in the face of that request, since the user then wants the
4937 lightweight version of the code. */
4938 rootdir
= (path
>= save_name
+ len
- 1
4939 && (IS_DIRECTORY_SEP (*path
) || *path
== 0));
4941 /* If name is "c:/.." or "/.." then stat "c:/" or "/". */
4942 r
= IS_DEVICE_SEP (name
[1]) ? &name
[2] : name
;
4943 if (IS_DIRECTORY_SEP (r
[0])
4944 && r
[1] == '.' && r
[2] == '.' && r
[3] == '\0')
4947 /* Note: If NAME is a symlink to the root of a UNC volume
4948 (i.e. "\\SERVER"), we will not detect that here, and we will
4949 return data about the symlink as result of FindFirst below.
4950 This is unfortunate, but that marginal use case does not
4951 justify a call to chase_symlinks which would impose a penalty
4952 on all the other use cases. (We get here for symlinks to
4953 roots of UNC volumes because CreateFile above fails for them,
4954 unlike with symlinks to root directories X:\ of drives.) */
4955 if (is_unc_volume (name
))
4957 fattrs
= unc_volume_file_attributes (name
);
4961 ctime
= atime
= wtime
= utc_base_ft
;
4965 /* Make sure root directories end in a slash. */
4966 if (!IS_DIRECTORY_SEP (name
[len
-1]))
4967 strcat (name
, "\\");
4968 if (GetDriveType (name
) < 2)
4974 fattrs
= FILE_ATTRIBUTE_DIRECTORY
;
4975 ctime
= atime
= wtime
= utc_base_ft
;
4981 /* Make sure non-root directories do NOT end in a slash,
4982 otherwise FindFirstFile might fail. */
4983 if (IS_DIRECTORY_SEP (name
[len
-1]))
4986 /* (This is hacky, but helps when doing file completions on
4987 network drives.) Optimize by using information available from
4988 active readdir if possible. */
4989 len
= strlen (dir_pathname
);
4990 if (IS_DIRECTORY_SEP (dir_pathname
[len
-1]))
4992 if (dir_find_handle
!= INVALID_HANDLE_VALUE
4993 && last_dir_find_data
!= -1
4994 && !(is_a_symlink
&& follow_symlinks
)
4995 /* The 2 file-name comparisons below support only ASCII
4996 characters, and will lose (compare not equal) when
4997 the file names include non-ASCII characters that are
4998 the same but for the case. However, doing this
4999 properly involves: (a) converting both file names to
5000 UTF-16, (b) lower-casing both names using CharLowerW,
5001 and (c) comparing the results; this would be quite a
5002 bit slower, whereas Plan B is for users who want
5003 lightweight albeit inaccurate version of 'stat'. */
5004 && c_strncasecmp (save_name
, dir_pathname
, len
) == 0
5005 && IS_DIRECTORY_SEP (name
[len
])
5006 && xstrcasecmp (name
+ len
+ 1, dir_static
.d_name
) == 0)
5008 have_wfd
= last_dir_find_data
;
5009 /* This was the last entry returned by readdir. */
5010 if (last_dir_find_data
== DIR_FIND_DATA_W
)
5011 wfd_w
= dir_find_data_w
;
5013 wfd_a
= dir_find_data_a
;
5017 logon_network_drive (name
);
5019 if (w32_unicode_filenames
)
5021 filename_to_utf16 (name
, name_w
);
5022 fh
= FindFirstFileW (name_w
, &wfd_w
);
5023 have_wfd
= DIR_FIND_DATA_W
;
5027 filename_to_ansi (name
, name_a
);
5028 /* If NAME includes characters not representable by
5029 the current ANSI codepage, filename_to_ansi
5030 usually replaces them with a '?'. We don't want
5031 to let FindFirstFileA interpret those as wildcards,
5032 and "succeed", returning us data from some random
5033 file in the same directory. */
5034 if (_mbspbrk (name_a
, "?"))
5035 fh
= INVALID_HANDLE_VALUE
;
5037 fh
= FindFirstFileA (name_a
, &wfd_a
);
5038 have_wfd
= DIR_FIND_DATA_A
;
5040 if (fh
== INVALID_HANDLE_VALUE
)
5047 /* Note: if NAME is a symlink, the information we get from
5048 FindFirstFile is for the symlink, not its target. */
5049 if (have_wfd
== DIR_FIND_DATA_W
)
5051 fattrs
= wfd_w
.dwFileAttributes
;
5052 ctime
= wfd_w
.ftCreationTime
;
5053 atime
= wfd_w
.ftLastAccessTime
;
5054 wtime
= wfd_w
.ftLastWriteTime
;
5055 fs_high
= wfd_w
.nFileSizeHigh
;
5056 fs_low
= wfd_w
.nFileSizeLow
;
5060 fattrs
= wfd_a
.dwFileAttributes
;
5061 ctime
= wfd_a
.ftCreationTime
;
5062 atime
= wfd_a
.ftLastAccessTime
;
5063 wtime
= wfd_a
.ftLastWriteTime
;
5064 fs_high
= wfd_a
.nFileSizeHigh
;
5065 fs_low
= wfd_a
.nFileSizeLow
;
5069 serialnum
= volume_info
.serialnum
;
5071 if (is_a_symlink
&& !follow_symlinks
)
5072 buf
->st_mode
= S_IFLNK
;
5073 else if (fattrs
& FILE_ATTRIBUTE_DIRECTORY
)
5074 buf
->st_mode
= S_IFDIR
;
5076 buf
->st_mode
= S_IFREG
;
5078 get_file_owner_and_group (NULL
, buf
);
5081 buf
->st_ino
= fake_inode
;
5083 buf
->st_dev
= serialnum
;
5084 buf
->st_rdev
= serialnum
;
5086 buf
->st_size
= fs_high
;
5087 buf
->st_size
<<= 32;
5088 buf
->st_size
+= fs_low
;
5089 buf
->st_nlink
= nlinks
;
5091 /* Convert timestamps to Unix format. */
5092 buf
->st_mtime
= convert_time (wtime
);
5093 buf
->st_atime
= convert_time (atime
);
5094 if (buf
->st_atime
== 0) buf
->st_atime
= buf
->st_mtime
;
5095 buf
->st_ctime
= convert_time (ctime
);
5096 if (buf
->st_ctime
== 0) buf
->st_ctime
= buf
->st_mtime
;
5098 /* determine rwx permissions */
5099 if (is_a_symlink
&& !follow_symlinks
)
5100 permission
= S_IREAD
| S_IWRITE
| S_IEXEC
; /* Posix expectations */
5103 if (fattrs
& FILE_ATTRIBUTE_READONLY
)
5104 permission
= S_IREAD
;
5106 permission
= S_IREAD
| S_IWRITE
;
5108 if (fattrs
& FILE_ATTRIBUTE_DIRECTORY
)
5109 permission
|= S_IEXEC
;
5110 else if (is_exec (name
))
5111 permission
|= S_IEXEC
;
5114 buf
->st_mode
|= permission
| (permission
>> 3) | (permission
>> 6);
5120 stat (const char * path
, struct stat
* buf
)
5122 return stat_worker (path
, buf
, 1);
5126 lstat (const char * path
, struct stat
* buf
)
5128 return stat_worker (path
, buf
, 0);
5132 fstatat (int fd
, char const *name
, struct stat
*st
, int flags
)
5134 /* Rely on a hack: an open directory is modeled as file descriptor 0.
5135 This is good enough for the current usage in Emacs, but is fragile.
5137 FIXME: Add proper support for fdopendir, fstatat, readlinkat.
5138 Gnulib does this and can serve as a model. */
5139 char fullname
[MAX_UTF8_PATH
];
5143 char lastc
= dir_pathname
[strlen (dir_pathname
) - 1];
5145 if (_snprintf (fullname
, sizeof fullname
, "%s%s%s",
5146 dir_pathname
, IS_DIRECTORY_SEP (lastc
) ? "" : "/", name
)
5149 errno
= ENAMETOOLONG
;
5155 return stat_worker (name
, st
, ! (flags
& AT_SYMLINK_NOFOLLOW
));
5158 /* Provide fstat and utime as well as stat for consistent handling of
5161 fstat (int desc
, struct stat
* buf
)
5163 HANDLE fh
= (HANDLE
) _get_osfhandle (desc
);
5164 BY_HANDLE_FILE_INFORMATION info
;
5165 unsigned __int64 fake_inode
;
5168 switch (GetFileType (fh
) & ~FILE_TYPE_REMOTE
)
5170 case FILE_TYPE_DISK
:
5171 buf
->st_mode
= S_IFREG
;
5172 if (!GetFileInformationByHandle (fh
, &info
))
5178 case FILE_TYPE_PIPE
:
5179 buf
->st_mode
= S_IFIFO
;
5181 case FILE_TYPE_CHAR
:
5182 case FILE_TYPE_UNKNOWN
:
5184 buf
->st_mode
= S_IFCHR
;
5186 memset (&info
, 0, sizeof (info
));
5187 info
.dwFileAttributes
= 0;
5188 info
.ftCreationTime
= utc_base_ft
;
5189 info
.ftLastAccessTime
= utc_base_ft
;
5190 info
.ftLastWriteTime
= utc_base_ft
;
5193 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
5194 buf
->st_mode
= S_IFDIR
;
5196 buf
->st_nlink
= info
.nNumberOfLinks
;
5197 /* Might as well use file index to fake inode values, but this
5198 is not guaranteed to be unique unless we keep a handle open
5199 all the time (even then there are situations where it is
5200 not unique). Reputedly, there are at most 48 bits of info
5201 (on NTFS, presumably less on FAT). */
5202 fake_inode
= info
.nFileIndexHigh
;
5204 fake_inode
+= info
.nFileIndexLow
;
5206 /* MSVC defines _ino_t to be short; other libc's might not. */
5207 if (sizeof (buf
->st_ino
) == 2)
5208 buf
->st_ino
= fake_inode
^ (fake_inode
>> 16);
5210 buf
->st_ino
= fake_inode
;
5212 /* If the caller so requested, get the true file owner and group.
5213 Otherwise, consider the file to belong to the current user. */
5214 if (!w32_stat_get_owner_group
|| is_windows_9x () == TRUE
)
5215 get_file_owner_and_group (NULL
, buf
);
5218 PSECURITY_DESCRIPTOR psd
= NULL
;
5220 psd
= get_file_security_desc_by_handle (fh
);
5223 get_file_owner_and_group (psd
, buf
);
5227 get_file_owner_and_group (NULL
, buf
);
5230 buf
->st_dev
= info
.dwVolumeSerialNumber
;
5231 buf
->st_rdev
= info
.dwVolumeSerialNumber
;
5233 buf
->st_size
= info
.nFileSizeHigh
;
5234 buf
->st_size
<<= 32;
5235 buf
->st_size
+= info
.nFileSizeLow
;
5237 /* Convert timestamps to Unix format. */
5238 buf
->st_mtime
= convert_time (info
.ftLastWriteTime
);
5239 buf
->st_atime
= convert_time (info
.ftLastAccessTime
);
5240 if (buf
->st_atime
== 0) buf
->st_atime
= buf
->st_mtime
;
5241 buf
->st_ctime
= convert_time (info
.ftCreationTime
);
5242 if (buf
->st_ctime
== 0) buf
->st_ctime
= buf
->st_mtime
;
5244 /* determine rwx permissions */
5245 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
)
5246 permission
= S_IREAD
;
5248 permission
= S_IREAD
| S_IWRITE
;
5250 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
5251 permission
|= S_IEXEC
;
5254 #if 0 /* no way of knowing the filename */
5255 char * p
= strrchr (name
, '.');
5257 (xstrcasecmp (p
, ".exe") == 0 ||
5258 xstrcasecmp (p
, ".com") == 0 ||
5259 xstrcasecmp (p
, ".bat") == 0 ||
5260 xstrcasecmp (p
, ".cmd") == 0))
5261 permission
|= S_IEXEC
;
5265 buf
->st_mode
|= permission
| (permission
>> 3) | (permission
>> 6);
5270 /* A version of 'utime' which handles directories as well as
5274 utime (const char *name
, struct utimbuf
*times
)
5276 struct utimbuf deftime
;
5283 deftime
.modtime
= deftime
.actime
= time (NULL
);
5287 if (w32_unicode_filenames
)
5289 wchar_t name_utf16
[MAX_PATH
];
5291 if (filename_to_utf16 (name
, name_utf16
) != 0)
5292 return -1; /* errno set by filename_to_utf16 */
5294 /* Need write access to set times. */
5295 fh
= CreateFileW (name_utf16
, FILE_WRITE_ATTRIBUTES
,
5296 /* If NAME specifies a directory, FILE_SHARE_DELETE
5297 allows other processes to delete files inside it,
5298 while we have the directory open. */
5299 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
5300 0, OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
5304 char name_ansi
[MAX_PATH
];
5306 if (filename_to_ansi (name
, name_ansi
) != 0)
5307 return -1; /* errno set by filename_to_ansi */
5309 fh
= CreateFileA (name_ansi
, FILE_WRITE_ATTRIBUTES
,
5310 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
5311 0, OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
5313 if (fh
!= INVALID_HANDLE_VALUE
)
5315 convert_from_time_t (times
->actime
, &atime
);
5316 convert_from_time_t (times
->modtime
, &mtime
);
5317 if (!SetFileTime (fh
, NULL
, &atime
, &mtime
))
5327 DWORD err
= GetLastError ();
5331 case ERROR_FILE_NOT_FOUND
:
5332 case ERROR_PATH_NOT_FOUND
:
5333 case ERROR_INVALID_DRIVE
:
5334 case ERROR_BAD_NETPATH
:
5335 case ERROR_DEV_NOT_EXIST
:
5336 /* ERROR_INVALID_NAME is the error CreateFile sets when the
5337 file name includes ?s, i.e. translation to ANSI failed. */
5338 case ERROR_INVALID_NAME
:
5341 case ERROR_TOO_MANY_OPEN_FILES
:
5344 case ERROR_ACCESS_DENIED
:
5345 case ERROR_SHARING_VIOLATION
:
5357 /* Emacs expects us to support the traditional octal form of the mode
5358 bits, which is not what msvcrt.dll wants. */
5360 #define WRITE_USER 00200
5363 sys_umask (int mode
)
5365 static int current_mask
;
5366 int retval
, arg
= 0;
5368 /* The only bit we really support is the write bit. Files are
5369 always readable on MS-Windows, and the execute bit does not exist
5371 /* FIXME: if the GROUP and OTHER bits are reset, we should use ACLs
5372 to prevent access by other users on NTFS. */
5373 if ((mode
& WRITE_USER
) != 0)
5376 retval
= _umask (arg
);
5377 /* Merge into the return value the bits they've set the last time,
5378 which msvcrt.dll ignores and never returns. Emacs insists on its
5379 notion of mask being identical to what we return. */
5380 retval
|= (current_mask
& ~WRITE_USER
);
5381 current_mask
= mode
;
5387 /* Symlink-related functions. */
5388 #ifndef SYMBOLIC_LINK_FLAG_DIRECTORY
5389 #define SYMBOLIC_LINK_FLAG_DIRECTORY 0x1
5393 symlink (char const *filename
, char const *linkname
)
5395 char linkfn
[MAX_UTF8_PATH
], *tgtfn
;
5397 int dir_access
, filename_ends_in_slash
;
5399 /* Diagnostics follows Posix as much as possible. */
5400 if (filename
== NULL
|| linkname
== NULL
)
5410 if (strlen (filename
) > MAX_UTF8_PATH
|| strlen (linkname
) > MAX_UTF8_PATH
)
5412 errno
= ENAMETOOLONG
;
5416 strcpy (linkfn
, map_w32_filename (linkname
, NULL
));
5417 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) == 0)
5423 /* Note: since empty FILENAME was already rejected, we can safely
5424 refer to FILENAME[1]. */
5425 if (!(IS_DIRECTORY_SEP (filename
[0]) || IS_DEVICE_SEP (filename
[1])))
5427 /* Non-absolute FILENAME is understood as being relative to
5428 LINKNAME's directory. We need to prepend that directory to
5429 FILENAME to get correct results from faccessat below, since
5430 otherwise it will interpret FILENAME relative to the
5431 directory where the Emacs process runs. Note that
5432 make-symbolic-link always makes sure LINKNAME is a fully
5433 expanded file name. */
5434 char tem
[MAX_UTF8_PATH
];
5435 char *p
= linkfn
+ strlen (linkfn
);
5437 while (p
> linkfn
&& !IS_ANY_SEP (p
[-1]))
5440 strncpy (tem
, linkfn
, p
- linkfn
);
5441 tem
[p
- linkfn
] = '\0';
5442 strcat (tem
, filename
);
5443 dir_access
= faccessat (AT_FDCWD
, tem
, D_OK
, AT_EACCESS
);
5446 dir_access
= faccessat (AT_FDCWD
, filename
, D_OK
, AT_EACCESS
);
5448 /* Since Windows distinguishes between symlinks to directories and
5449 to files, we provide a kludgy feature: if FILENAME doesn't
5450 exist, but ends in a slash, we create a symlink to directory. If
5451 FILENAME exists and is a directory, we always create a symlink to
5453 filename_ends_in_slash
= IS_DIRECTORY_SEP (filename
[strlen (filename
) - 1]);
5454 if (dir_access
== 0 || filename_ends_in_slash
)
5455 flags
= SYMBOLIC_LINK_FLAG_DIRECTORY
;
5457 tgtfn
= (char *)map_w32_filename (filename
, NULL
);
5458 if (filename_ends_in_slash
)
5459 tgtfn
[strlen (tgtfn
) - 1] = '\0';
5462 if (!create_symbolic_link (linkfn
, tgtfn
, flags
))
5464 /* ENOSYS is set by create_symbolic_link, when it detects that
5465 the OS doesn't support the CreateSymbolicLink API. */
5466 if (errno
!= ENOSYS
)
5468 DWORD w32err
= GetLastError ();
5472 /* ERROR_SUCCESS is sometimes returned when LINKFN and
5473 TGTFN point to the same file name, go figure. */
5475 case ERROR_FILE_EXISTS
:
5478 case ERROR_ACCESS_DENIED
:
5481 case ERROR_FILE_NOT_FOUND
:
5482 case ERROR_PATH_NOT_FOUND
:
5483 case ERROR_BAD_NETPATH
:
5484 case ERROR_INVALID_REPARSE_DATA
:
5487 case ERROR_DIRECTORY
:
5490 case ERROR_PRIVILEGE_NOT_HELD
:
5491 case ERROR_NOT_ALL_ASSIGNED
:
5494 case ERROR_DISK_FULL
:
5507 /* A quick inexpensive test of whether FILENAME identifies a file that
5508 is a symlink. Returns non-zero if it is, zero otherwise. FILENAME
5509 must already be in the normalized form returned by
5512 Note: for repeated operations on many files, it is best to test
5513 whether the underlying volume actually supports symlinks, by
5514 testing the FILE_SUPPORTS_REPARSE_POINTS bit in volume's flags, and
5515 avoid the call to this function if it doesn't. That's because the
5516 call to GetFileAttributes takes a non-negligible time, especially
5517 on non-local or removable filesystems. See stat_worker for an
5518 example of how to do that. */
5520 is_symlink (const char *filename
)
5523 wchar_t filename_w
[MAX_PATH
];
5524 char filename_a
[MAX_PATH
];
5525 WIN32_FIND_DATAW wfdw
;
5526 WIN32_FIND_DATAA wfda
;
5528 int attrs_mean_symlink
;
5530 if (w32_unicode_filenames
)
5532 filename_to_utf16 (filename
, filename_w
);
5533 attrs
= GetFileAttributesW (filename_w
);
5537 filename_to_ansi (filename
, filename_a
);
5538 attrs
= GetFileAttributesA (filename_a
);
5542 DWORD w32err
= GetLastError ();
5546 case ERROR_BAD_NETPATH
: /* network share, can't be a symlink */
5548 case ERROR_ACCESS_DENIED
:
5551 case ERROR_FILE_NOT_FOUND
:
5552 case ERROR_PATH_NOT_FOUND
:
5559 if ((attrs
& FILE_ATTRIBUTE_REPARSE_POINT
) == 0)
5561 logon_network_drive (filename
);
5562 if (w32_unicode_filenames
)
5564 fh
= FindFirstFileW (filename_w
, &wfdw
);
5565 attrs_mean_symlink
=
5566 (wfdw
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) != 0
5567 && (wfdw
.dwReserved0
& IO_REPARSE_TAG_SYMLINK
) == IO_REPARSE_TAG_SYMLINK
;
5569 else if (_mbspbrk (filename_a
, "?"))
5571 /* filename_to_ansi failed to convert the file name. */
5577 fh
= FindFirstFileA (filename_a
, &wfda
);
5578 attrs_mean_symlink
=
5579 (wfda
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) != 0
5580 && (wfda
.dwReserved0
& IO_REPARSE_TAG_SYMLINK
) == IO_REPARSE_TAG_SYMLINK
;
5582 if (fh
== INVALID_HANDLE_VALUE
)
5585 return attrs_mean_symlink
;
5588 /* If NAME identifies a symbolic link, copy into BUF the file name of
5589 the symlink's target. Copy at most BUF_SIZE bytes, and do NOT
5590 null-terminate the target name, even if it fits. Return the number
5591 of bytes copied, or -1 if NAME is not a symlink or any error was
5592 encountered while resolving it. The file name copied into BUF is
5593 encoded in the current ANSI codepage. */
5595 readlink (const char *name
, char *buf
, size_t buf_size
)
5598 TOKEN_PRIVILEGES privs
;
5599 int restore_privs
= 0;
5602 char resolved
[MAX_UTF8_PATH
];
5615 path
= map_w32_filename (name
, NULL
);
5617 if (strlen (path
) > MAX_UTF8_PATH
)
5619 errno
= ENAMETOOLONG
;
5624 if (is_windows_9x () == TRUE
5625 || (volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) == 0
5626 || !is_symlink (path
))
5629 errno
= EINVAL
; /* not a symlink */
5633 /* Done with simple tests, now we're in for some _real_ work. */
5634 if (enable_privilege (SE_BACKUP_NAME
, TRUE
, &privs
))
5636 /* Implementation note: From here and onward, don't return early,
5637 since that will fail to restore the original set of privileges of
5638 the calling thread. */
5640 retval
= -1; /* not too optimistic, are we? */
5642 /* Note: In the next call to CreateFile, we use zero as the 2nd
5643 argument because, when the symlink is a hidden/system file,
5644 e.g. 'C:\Users\All Users', GENERIC_READ fails with
5645 ERROR_ACCESS_DENIED. Zero seems to work just fine, both for file
5646 and directory symlinks. */
5647 if (w32_unicode_filenames
)
5649 wchar_t path_w
[MAX_PATH
];
5651 filename_to_utf16 (path
, path_w
);
5652 sh
= CreateFileW (path_w
, 0, 0, NULL
, OPEN_EXISTING
,
5653 FILE_FLAG_OPEN_REPARSE_POINT
5654 | FILE_FLAG_BACKUP_SEMANTICS
,
5659 char path_a
[MAX_PATH
];
5661 filename_to_ansi (path
, path_a
);
5662 sh
= CreateFileA (path_a
, 0, 0, NULL
, OPEN_EXISTING
,
5663 FILE_FLAG_OPEN_REPARSE_POINT
5664 | FILE_FLAG_BACKUP_SEMANTICS
,
5667 if (sh
!= INVALID_HANDLE_VALUE
)
5669 BYTE reparse_buf
[MAXIMUM_REPARSE_DATA_BUFFER_SIZE
];
5670 REPARSE_DATA_BUFFER
*reparse_data
= (REPARSE_DATA_BUFFER
*)&reparse_buf
[0];
5673 if (!DeviceIoControl (sh
, FSCTL_GET_REPARSE_POINT
, NULL
, 0,
5674 reparse_buf
, MAXIMUM_REPARSE_DATA_BUFFER_SIZE
,
5677 else if (reparse_data
->ReparseTag
!= IO_REPARSE_TAG_SYMLINK
)
5681 /* Copy the link target name, in wide characters, from
5682 reparse_data, then convert it to multibyte encoding in
5683 the current locale's codepage. */
5687 reparse_data
->SymbolicLinkReparseBuffer
.PrintNameLength
;
5689 reparse_data
->SymbolicLinkReparseBuffer
.PathBuffer
5690 + reparse_data
->SymbolicLinkReparseBuffer
.PrintNameOffset
/sizeof(WCHAR
);
5691 size_t size_to_copy
= buf_size
;
5693 /* According to MSDN, PrintNameLength does not include the
5694 terminating null character. */
5695 lwname
= alloca ((lwname_len
+ 1) * sizeof(WCHAR
));
5696 memcpy (lwname
, lwname_src
, lwname_len
);
5697 lwname
[lwname_len
/sizeof(WCHAR
)] = 0; /* null-terminate */
5698 filename_from_utf16 (lwname
, resolved
);
5699 dostounix_filename (resolved
);
5700 lname_size
= strlen (resolved
) + 1;
5701 if (lname_size
<= buf_size
)
5702 size_to_copy
= lname_size
;
5703 strncpy (buf
, resolved
, size_to_copy
);
5705 retval
= size_to_copy
;
5711 /* CreateFile failed. */
5712 DWORD w32err2
= GetLastError ();
5716 case ERROR_FILE_NOT_FOUND
:
5717 case ERROR_PATH_NOT_FOUND
:
5720 case ERROR_ACCESS_DENIED
:
5721 case ERROR_TOO_MANY_OPEN_FILES
:
5731 restore_privilege (&privs
);
5739 readlinkat (int fd
, char const *name
, char *buffer
,
5742 /* Rely on a hack: an open directory is modeled as file descriptor 0,
5743 as in fstatat. FIXME: Add proper support for readlinkat. */
5744 char fullname
[MAX_UTF8_PATH
];
5748 if (_snprintf (fullname
, sizeof fullname
, "%s/%s", dir_pathname
, name
)
5751 errno
= ENAMETOOLONG
;
5757 return readlink (name
, buffer
, buffer_size
);
5760 /* If FILE is a symlink, return its target (stored in a static
5761 buffer); otherwise return FILE.
5763 This function repeatedly resolves symlinks in the last component of
5764 a chain of symlink file names, as in foo -> bar -> baz -> ...,
5765 until it arrives at a file whose last component is not a symlink,
5766 or some error occurs. It returns the target of the last
5767 successfully resolved symlink in the chain. If it succeeds to
5768 resolve even a single symlink, the value returned is an absolute
5769 file name with backslashes (result of GetFullPathName). By
5770 contrast, if the original FILE is returned, it is unaltered.
5772 Note: This function can set errno even if it succeeds.
5774 Implementation note: we only resolve the last portion ("basename")
5775 of the argument FILE and of each following file in the chain,
5776 disregarding any possible symlinks in its leading directories.
5777 This is because Windows system calls and library functions
5778 transparently resolve symlinks in leading directories and return
5779 correct information, as long as the basename is not a symlink. */
5781 chase_symlinks (const char *file
)
5783 static char target
[MAX_UTF8_PATH
];
5784 char link
[MAX_UTF8_PATH
];
5785 wchar_t target_w
[MAX_PATH
], link_w
[MAX_PATH
];
5786 char target_a
[MAX_PATH
], link_a
[MAX_PATH
];
5787 ssize_t res
, link_len
;
5790 if (is_windows_9x () == TRUE
|| !is_symlink (file
))
5791 return (char *)file
;
5793 if (w32_unicode_filenames
)
5795 wchar_t file_w
[MAX_PATH
];
5797 filename_to_utf16 (file
, file_w
);
5798 if (GetFullPathNameW (file_w
, MAX_PATH
, link_w
, NULL
) == 0)
5799 return (char *)file
;
5800 filename_from_utf16 (link_w
, link
);
5804 char file_a
[MAX_PATH
];
5806 filename_to_ansi (file
, file_a
);
5807 if (GetFullPathNameA (file_a
, MAX_PATH
, link_a
, NULL
) == 0)
5808 return (char *)file
;
5809 filename_from_ansi (link_a
, link
);
5811 link_len
= strlen (link
);
5816 /* Remove trailing slashes, as we want to resolve the last
5817 non-trivial part of the link name. */
5818 while (link_len
> 3 && IS_DIRECTORY_SEP (link
[link_len
-1]))
5819 link
[link_len
--] = '\0';
5821 res
= readlink (link
, target
, MAX_UTF8_PATH
);
5825 if (!(IS_DEVICE_SEP (target
[1])
5826 || (IS_DIRECTORY_SEP (target
[0]) && IS_DIRECTORY_SEP (target
[1]))))
5828 /* Target is relative. Append it to the directory part of
5829 the symlink, then copy the result back to target. */
5830 char *p
= link
+ link_len
;
5832 while (p
> link
&& !IS_ANY_SEP (p
[-1]))
5835 strcpy (target
, link
);
5837 /* Resolve any "." and ".." to get a fully-qualified file name
5839 if (w32_unicode_filenames
)
5841 filename_to_utf16 (target
, target_w
);
5842 link_len
= GetFullPathNameW (target_w
, MAX_PATH
, link_w
, NULL
);
5844 filename_from_utf16 (link_w
, link
);
5848 filename_to_ansi (target
, target_a
);
5849 link_len
= GetFullPathNameA (target_a
, MAX_PATH
, link_a
, NULL
);
5851 filename_from_ansi (link_a
, link
);
5853 link_len
= strlen (link
);
5855 } while (res
> 0 && link_len
> 0 && ++loop_count
<= 100);
5857 if (loop_count
> 100)
5860 if (target
[0] == '\0') /* not a single call to readlink succeeded */
5861 return (char *)file
;
5866 /* Posix ACL emulation. */
5869 acl_valid (acl_t acl
)
5871 return is_valid_security_descriptor ((PSECURITY_DESCRIPTOR
)acl
) ? 0 : -1;
5875 acl_to_text (acl_t acl
, ssize_t
*size
)
5878 SECURITY_INFORMATION flags
=
5879 OWNER_SECURITY_INFORMATION
|
5880 GROUP_SECURITY_INFORMATION
|
5881 DACL_SECURITY_INFORMATION
;
5882 char *retval
= NULL
;
5888 if (convert_sd_to_sddl ((PSECURITY_DESCRIPTOR
)acl
, SDDL_REVISION_1
, flags
, &str_acl
, &local_size
))
5891 /* We don't want to mix heaps, so we duplicate the string in our
5892 heap and free the one allocated by the API. */
5893 retval
= xstrdup (str_acl
);
5896 LocalFree (str_acl
);
5898 else if (errno
!= ENOTSUP
)
5905 acl_from_text (const char *acl_str
)
5907 PSECURITY_DESCRIPTOR psd
, retval
= NULL
;
5913 if (convert_sddl_to_sd (acl_str
, SDDL_REVISION_1
, &psd
, &sd_size
))
5916 retval
= xmalloc (sd_size
);
5917 memcpy (retval
, psd
, sd_size
);
5920 else if (errno
!= ENOTSUP
)
5927 acl_free (void *ptr
)
5934 acl_get_file (const char *fname
, acl_type_t type
)
5936 PSECURITY_DESCRIPTOR psd
= NULL
;
5937 const char *filename
;
5939 if (type
== ACL_TYPE_ACCESS
)
5942 SECURITY_INFORMATION si
=
5943 OWNER_SECURITY_INFORMATION
|
5944 GROUP_SECURITY_INFORMATION
|
5945 DACL_SECURITY_INFORMATION
;
5948 filename
= map_w32_filename (fname
, NULL
);
5949 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) != 0)
5950 fname
= chase_symlinks (filename
);
5955 if (!get_file_security (fname
, si
, psd
, 0, &sd_len
)
5956 && errno
!= ENOTSUP
)
5958 err
= GetLastError ();
5959 if (err
== ERROR_INSUFFICIENT_BUFFER
)
5961 psd
= xmalloc (sd_len
);
5962 if (!get_file_security (fname
, si
, psd
, sd_len
, &sd_len
))
5969 else if (err
== ERROR_FILE_NOT_FOUND
5970 || err
== ERROR_PATH_NOT_FOUND
5971 /* ERROR_INVALID_NAME is what we get if
5972 w32-unicode-filenames is nil and the file cannot
5973 be encoded in the current ANSI codepage. */
5974 || err
== ERROR_INVALID_NAME
)
5982 else if (type
!= ACL_TYPE_DEFAULT
)
5989 acl_set_file (const char *fname
, acl_type_t type
, acl_t acl
)
5991 TOKEN_PRIVILEGES old1
, old2
;
5993 int st
= 0, retval
= -1;
5994 SECURITY_INFORMATION flags
= 0;
5995 PSID psidOwner
, psidGroup
;
6000 const char *filename
;
6002 if (acl_valid (acl
) != 0
6003 || (type
!= ACL_TYPE_DEFAULT
&& type
!= ACL_TYPE_ACCESS
))
6009 if (type
== ACL_TYPE_DEFAULT
)
6015 filename
= map_w32_filename (fname
, NULL
);
6016 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) != 0)
6017 fname
= chase_symlinks (filename
);
6021 if (get_security_descriptor_owner ((PSECURITY_DESCRIPTOR
)acl
, &psidOwner
,
6024 flags
|= OWNER_SECURITY_INFORMATION
;
6025 if (get_security_descriptor_group ((PSECURITY_DESCRIPTOR
)acl
, &psidGroup
,
6028 flags
|= GROUP_SECURITY_INFORMATION
;
6029 if (get_security_descriptor_dacl ((PSECURITY_DESCRIPTOR
)acl
, &dacl_present
,
6032 flags
|= DACL_SECURITY_INFORMATION
;
6036 /* According to KB-245153, setting the owner will succeed if either:
6037 (1) the caller is the user who will be the new owner, and has the
6038 SE_TAKE_OWNERSHIP privilege, or
6039 (2) the caller has the SE_RESTORE privilege, in which case she can
6040 set any valid user or group as the owner
6042 We request below both SE_TAKE_OWNERSHIP and SE_RESTORE
6043 privileges, and disregard any failures in obtaining them. If
6044 these privileges cannot be obtained, and do not already exist in
6045 the calling thread's security token, this function could fail
6047 if (enable_privilege (SE_TAKE_OWNERSHIP_NAME
, TRUE
, &old1
))
6049 if (enable_privilege (SE_RESTORE_NAME
, TRUE
, &old2
))
6054 /* SetFileSecurity is deprecated by MS, and sometimes fails when
6055 DACL inheritance is involved, but it seems to preserve ownership
6056 better than SetNamedSecurityInfo, which is important e.g., in
6058 if (!set_file_security (fname
, flags
, (PSECURITY_DESCRIPTOR
)acl
))
6060 err
= GetLastError ();
6062 if (errno
!= ENOTSUP
)
6063 err
= set_named_security_info (fname
, SE_FILE_OBJECT
, flags
,
6064 psidOwner
, psidGroup
, pacl
, NULL
);
6067 err
= ERROR_SUCCESS
;
6068 if (err
!= ERROR_SUCCESS
)
6070 if (errno
== ENOTSUP
)
6072 else if (err
== ERROR_INVALID_OWNER
6073 || err
== ERROR_NOT_ALL_ASSIGNED
6074 || err
== ERROR_ACCESS_DENIED
)
6076 /* Maybe the requested ACL and the one the file already has
6077 are identical, in which case we can silently ignore the
6078 failure. (And no, Windows doesn't.) */
6079 acl_t current_acl
= acl_get_file (fname
, ACL_TYPE_ACCESS
);
6084 char *acl_from
= acl_to_text (current_acl
, NULL
);
6085 char *acl_to
= acl_to_text (acl
, NULL
);
6087 if (acl_from
&& acl_to
&& xstrcasecmp (acl_from
, acl_to
) == 0)
6093 acl_free (acl_from
);
6096 acl_free (current_acl
);
6099 else if (err
== ERROR_FILE_NOT_FOUND
6100 || err
== ERROR_PATH_NOT_FOUND
6101 /* ERROR_INVALID_NAME is what we get if
6102 w32-unicode-filenames is nil and the file cannot be
6103 encoded in the current ANSI codepage. */
6104 || err
== ERROR_INVALID_NAME
)
6118 restore_privilege (&old2
);
6119 restore_privilege (&old1
);
6127 /* MS-Windows version of careadlinkat (cf. ../lib/careadlinkat.c). We
6128 have a fixed max size for file names, so we don't need the kind of
6129 alloc/malloc/realloc dance the gnulib version does. We also don't
6130 support FD-relative symlinks. */
6132 careadlinkat (int fd
, char const *filename
,
6133 char *buffer
, size_t buffer_size
,
6134 struct allocator
const *alloc
,
6135 ssize_t (*preadlinkat
) (int, char const *, char *, size_t))
6137 char linkname
[MAX_UTF8_PATH
];
6140 link_size
= preadlinkat (fd
, filename
, linkname
, sizeof(linkname
));
6144 char *retval
= buffer
;
6146 linkname
[link_size
++] = '\0';
6147 if (link_size
> buffer_size
)
6148 retval
= (char *)(alloc
? alloc
->allocate
: xmalloc
) (link_size
);
6150 memcpy (retval
, linkname
, link_size
);
6158 w32_copy_file (const char *from
, const char *to
,
6159 int keep_time
, int preserve_ownership
, int copy_acls
)
6163 wchar_t from_w
[MAX_PATH
], to_w
[MAX_PATH
];
6164 char from_a
[MAX_PATH
], to_a
[MAX_PATH
];
6166 /* We ignore preserve_ownership for now. */
6167 preserve_ownership
= preserve_ownership
;
6171 acl
= acl_get_file (from
, ACL_TYPE_ACCESS
);
6172 if (acl
== NULL
&& acl_errno_valid (errno
))
6175 if (w32_unicode_filenames
)
6177 filename_to_utf16 (from
, from_w
);
6178 filename_to_utf16 (to
, to_w
);
6179 copy_result
= CopyFileW (from_w
, to_w
, FALSE
);
6183 filename_to_ansi (from
, from_a
);
6184 filename_to_ansi (to
, to_a
);
6185 copy_result
= CopyFileA (from_a
, to_a
, FALSE
);
6189 /* CopyFile doesn't set errno when it fails. By far the most
6190 "popular" reason is that the target is read-only. */
6191 DWORD err
= GetLastError ();
6195 case ERROR_FILE_NOT_FOUND
:
6198 case ERROR_ACCESS_DENIED
:
6201 case ERROR_ENCRYPTION_FAILED
:
6213 /* CopyFile retains the timestamp by default. However, see
6214 "Community Additions" for CopyFile: it sounds like that is not
6215 entirely true. Testing on Windows XP confirms that modified time
6216 is copied, but creation and last-access times are not.
6218 else if (!keep_time
)
6220 struct timespec now
;
6223 if (w32_unicode_filenames
)
6225 /* Ensure file is writable while its times are set. */
6226 attributes
= GetFileAttributesW (to_w
);
6227 SetFileAttributesW (to_w
, attributes
& ~FILE_ATTRIBUTE_READONLY
);
6228 now
= current_timespec ();
6229 if (set_file_times (-1, to
, now
, now
))
6231 /* Restore original attributes. */
6232 SetFileAttributesW (to_w
, attributes
);
6237 /* Restore original attributes. */
6238 SetFileAttributesW (to_w
, attributes
);
6242 attributes
= GetFileAttributesA (to_a
);
6243 SetFileAttributesA (to_a
, attributes
& ~FILE_ATTRIBUTE_READONLY
);
6244 now
= current_timespec ();
6245 if (set_file_times (-1, to
, now
, now
))
6247 SetFileAttributesA (to_a
, attributes
);
6252 SetFileAttributesA (to_a
, attributes
);
6258 acl_set_file (to
, ACL_TYPE_ACCESS
, acl
) != 0;
6260 if (fail
&& acl_errno_valid (errno
))
6268 /* Support for browsing other processes and their attributes. See
6269 process.c for the Lisp bindings. */
6271 /* Helper wrapper functions. */
6273 static HANDLE WINAPI
6274 create_toolhelp32_snapshot (DWORD Flags
, DWORD Ignored
)
6276 static CreateToolhelp32Snapshot_Proc s_pfn_Create_Toolhelp32_Snapshot
= NULL
;
6278 if (g_b_init_create_toolhelp32_snapshot
== 0)
6280 g_b_init_create_toolhelp32_snapshot
= 1;
6281 s_pfn_Create_Toolhelp32_Snapshot
= (CreateToolhelp32Snapshot_Proc
)
6282 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6283 "CreateToolhelp32Snapshot");
6285 if (s_pfn_Create_Toolhelp32_Snapshot
== NULL
)
6287 return INVALID_HANDLE_VALUE
;
6289 return (s_pfn_Create_Toolhelp32_Snapshot (Flags
, Ignored
));
6293 process32_first (HANDLE hSnapshot
, LPPROCESSENTRY32 lppe
)
6295 static Process32First_Proc s_pfn_Process32_First
= NULL
;
6297 if (g_b_init_process32_first
== 0)
6299 g_b_init_process32_first
= 1;
6300 s_pfn_Process32_First
= (Process32First_Proc
)
6301 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6304 if (s_pfn_Process32_First
== NULL
)
6308 return (s_pfn_Process32_First (hSnapshot
, lppe
));
6312 process32_next (HANDLE hSnapshot
, LPPROCESSENTRY32 lppe
)
6314 static Process32Next_Proc s_pfn_Process32_Next
= NULL
;
6316 if (g_b_init_process32_next
== 0)
6318 g_b_init_process32_next
= 1;
6319 s_pfn_Process32_Next
= (Process32Next_Proc
)
6320 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6323 if (s_pfn_Process32_Next
== NULL
)
6327 return (s_pfn_Process32_Next (hSnapshot
, lppe
));
6331 open_thread_token (HANDLE ThreadHandle
,
6332 DWORD DesiredAccess
,
6334 PHANDLE TokenHandle
)
6336 static OpenThreadToken_Proc s_pfn_Open_Thread_Token
= NULL
;
6337 HMODULE hm_advapi32
= NULL
;
6338 if (is_windows_9x () == TRUE
)
6340 SetLastError (ERROR_NOT_SUPPORTED
);
6343 if (g_b_init_open_thread_token
== 0)
6345 g_b_init_open_thread_token
= 1;
6346 hm_advapi32
= LoadLibrary ("Advapi32.dll");
6347 s_pfn_Open_Thread_Token
=
6348 (OpenThreadToken_Proc
) GetProcAddress (hm_advapi32
, "OpenThreadToken");
6350 if (s_pfn_Open_Thread_Token
== NULL
)
6352 SetLastError (ERROR_NOT_SUPPORTED
);
6356 s_pfn_Open_Thread_Token (
6365 impersonate_self (SECURITY_IMPERSONATION_LEVEL ImpersonationLevel
)
6367 static ImpersonateSelf_Proc s_pfn_Impersonate_Self
= NULL
;
6368 HMODULE hm_advapi32
= NULL
;
6369 if (is_windows_9x () == TRUE
)
6373 if (g_b_init_impersonate_self
== 0)
6375 g_b_init_impersonate_self
= 1;
6376 hm_advapi32
= LoadLibrary ("Advapi32.dll");
6377 s_pfn_Impersonate_Self
=
6378 (ImpersonateSelf_Proc
) GetProcAddress (hm_advapi32
, "ImpersonateSelf");
6380 if (s_pfn_Impersonate_Self
== NULL
)
6384 return s_pfn_Impersonate_Self (ImpersonationLevel
);
6388 revert_to_self (void)
6390 static RevertToSelf_Proc s_pfn_Revert_To_Self
= NULL
;
6391 HMODULE hm_advapi32
= NULL
;
6392 if (is_windows_9x () == TRUE
)
6396 if (g_b_init_revert_to_self
== 0)
6398 g_b_init_revert_to_self
= 1;
6399 hm_advapi32
= LoadLibrary ("Advapi32.dll");
6400 s_pfn_Revert_To_Self
=
6401 (RevertToSelf_Proc
) GetProcAddress (hm_advapi32
, "RevertToSelf");
6403 if (s_pfn_Revert_To_Self
== NULL
)
6407 return s_pfn_Revert_To_Self ();
6411 get_process_memory_info (HANDLE h_proc
,
6412 PPROCESS_MEMORY_COUNTERS mem_counters
,
6415 static GetProcessMemoryInfo_Proc s_pfn_Get_Process_Memory_Info
= NULL
;
6416 HMODULE hm_psapi
= NULL
;
6417 if (is_windows_9x () == TRUE
)
6421 if (g_b_init_get_process_memory_info
== 0)
6423 g_b_init_get_process_memory_info
= 1;
6424 hm_psapi
= LoadLibrary ("Psapi.dll");
6426 s_pfn_Get_Process_Memory_Info
= (GetProcessMemoryInfo_Proc
)
6427 GetProcAddress (hm_psapi
, "GetProcessMemoryInfo");
6429 if (s_pfn_Get_Process_Memory_Info
== NULL
)
6433 return s_pfn_Get_Process_Memory_Info (h_proc
, mem_counters
, bufsize
);
6437 get_process_working_set_size (HANDLE h_proc
,
6441 static GetProcessWorkingSetSize_Proc
6442 s_pfn_Get_Process_Working_Set_Size
= NULL
;
6444 if (is_windows_9x () == TRUE
)
6448 if (g_b_init_get_process_working_set_size
== 0)
6450 g_b_init_get_process_working_set_size
= 1;
6451 s_pfn_Get_Process_Working_Set_Size
= (GetProcessWorkingSetSize_Proc
)
6452 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6453 "GetProcessWorkingSetSize");
6455 if (s_pfn_Get_Process_Working_Set_Size
== NULL
)
6459 return s_pfn_Get_Process_Working_Set_Size (h_proc
, minrss
, maxrss
);
6463 global_memory_status (MEMORYSTATUS
*buf
)
6465 static GlobalMemoryStatus_Proc s_pfn_Global_Memory_Status
= NULL
;
6467 if (is_windows_9x () == TRUE
)
6471 if (g_b_init_global_memory_status
== 0)
6473 g_b_init_global_memory_status
= 1;
6474 s_pfn_Global_Memory_Status
= (GlobalMemoryStatus_Proc
)
6475 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6476 "GlobalMemoryStatus");
6478 if (s_pfn_Global_Memory_Status
== NULL
)
6482 return s_pfn_Global_Memory_Status (buf
);
6486 global_memory_status_ex (MEMORY_STATUS_EX
*buf
)
6488 static GlobalMemoryStatusEx_Proc s_pfn_Global_Memory_Status_Ex
= NULL
;
6490 if (is_windows_9x () == TRUE
)
6494 if (g_b_init_global_memory_status_ex
== 0)
6496 g_b_init_global_memory_status_ex
= 1;
6497 s_pfn_Global_Memory_Status_Ex
= (GlobalMemoryStatusEx_Proc
)
6498 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6499 "GlobalMemoryStatusEx");
6501 if (s_pfn_Global_Memory_Status_Ex
== NULL
)
6505 return s_pfn_Global_Memory_Status_Ex (buf
);
6509 list_system_processes (void)
6511 struct gcpro gcpro1
;
6512 Lisp_Object proclist
= Qnil
;
6515 h_snapshot
= create_toolhelp32_snapshot (TH32CS_SNAPPROCESS
, 0);
6517 if (h_snapshot
!= INVALID_HANDLE_VALUE
)
6519 PROCESSENTRY32 proc_entry
;
6525 proc_entry
.dwSize
= sizeof (PROCESSENTRY32
);
6526 for (res
= process32_first (h_snapshot
, &proc_entry
); res
;
6527 res
= process32_next (h_snapshot
, &proc_entry
))
6529 proc_id
= proc_entry
.th32ProcessID
;
6530 proclist
= Fcons (make_fixnum_or_float (proc_id
), proclist
);
6533 CloseHandle (h_snapshot
);
6535 proclist
= Fnreverse (proclist
);
6542 enable_privilege (LPCTSTR priv_name
, BOOL enable_p
, TOKEN_PRIVILEGES
*old_priv
)
6544 TOKEN_PRIVILEGES priv
;
6545 DWORD priv_size
= sizeof (priv
);
6546 DWORD opriv_size
= sizeof (*old_priv
);
6547 HANDLE h_token
= NULL
;
6548 HANDLE h_thread
= GetCurrentThread ();
6552 res
= open_thread_token (h_thread
,
6553 TOKEN_QUERY
| TOKEN_ADJUST_PRIVILEGES
,
6555 if (!res
&& GetLastError () == ERROR_NO_TOKEN
)
6557 if (impersonate_self (SecurityImpersonation
))
6558 res
= open_thread_token (h_thread
,
6559 TOKEN_QUERY
| TOKEN_ADJUST_PRIVILEGES
,
6564 priv
.PrivilegeCount
= 1;
6565 priv
.Privileges
[0].Attributes
= enable_p
? SE_PRIVILEGE_ENABLED
: 0;
6566 LookupPrivilegeValue (NULL
, priv_name
, &priv
.Privileges
[0].Luid
);
6567 if (AdjustTokenPrivileges (h_token
, FALSE
, &priv
, priv_size
,
6568 old_priv
, &opriv_size
)
6569 && GetLastError () != ERROR_NOT_ALL_ASSIGNED
)
6573 CloseHandle (h_token
);
6579 restore_privilege (TOKEN_PRIVILEGES
*priv
)
6581 DWORD priv_size
= sizeof (*priv
);
6582 HANDLE h_token
= NULL
;
6585 if (open_thread_token (GetCurrentThread (),
6586 TOKEN_QUERY
| TOKEN_ADJUST_PRIVILEGES
,
6589 if (AdjustTokenPrivileges (h_token
, FALSE
, priv
, priv_size
, NULL
, NULL
)
6590 && GetLastError () != ERROR_NOT_ALL_ASSIGNED
)
6594 CloseHandle (h_token
);
6600 ltime (ULONGLONG time_100ns
)
6602 ULONGLONG time_sec
= time_100ns
/ 10000000;
6603 int subsec
= time_100ns
% 10000000;
6604 return list4i (time_sec
>> 16, time_sec
& 0xffff,
6605 subsec
/ 10, subsec
% 10 * 100000);
6608 #define U64_TO_LISP_TIME(time) ltime (time)
6611 process_times (HANDLE h_proc
, Lisp_Object
*ctime
, Lisp_Object
*etime
,
6612 Lisp_Object
*stime
, Lisp_Object
*utime
, Lisp_Object
*ttime
,
6615 FILETIME ft_creation
, ft_exit
, ft_kernel
, ft_user
, ft_current
;
6616 ULONGLONG tem1
, tem2
, tem3
, tem
;
6619 || !get_process_times_fn
6620 || !(*get_process_times_fn
) (h_proc
, &ft_creation
, &ft_exit
,
6621 &ft_kernel
, &ft_user
))
6624 GetSystemTimeAsFileTime (&ft_current
);
6626 FILETIME_TO_U64 (tem1
, ft_kernel
);
6627 *stime
= U64_TO_LISP_TIME (tem1
);
6629 FILETIME_TO_U64 (tem2
, ft_user
);
6630 *utime
= U64_TO_LISP_TIME (tem2
);
6633 *ttime
= U64_TO_LISP_TIME (tem3
);
6635 FILETIME_TO_U64 (tem
, ft_creation
);
6636 /* Process no 4 (System) returns zero creation time. */
6639 *ctime
= U64_TO_LISP_TIME (tem
);
6643 FILETIME_TO_U64 (tem3
, ft_current
);
6644 tem
= (tem3
- utc_base
) - tem
;
6646 *etime
= U64_TO_LISP_TIME (tem
);
6650 *pcpu
= 100.0 * (tem1
+ tem2
) / tem
;
6661 system_process_attributes (Lisp_Object pid
)
6663 struct gcpro gcpro1
, gcpro2
, gcpro3
;
6664 Lisp_Object attrs
= Qnil
;
6665 Lisp_Object cmd_str
, decoded_cmd
, tem
;
6666 HANDLE h_snapshot
, h_proc
;
6669 char uname
[UNLEN
+1], gname
[GNLEN
+1], domain
[1025];
6670 DWORD ulength
= sizeof (uname
), dlength
= sizeof (domain
), needed
;
6671 DWORD glength
= sizeof (gname
);
6672 HANDLE token
= NULL
;
6673 SID_NAME_USE user_type
;
6674 unsigned char *buf
= NULL
;
6676 TOKEN_USER user_token
;
6677 TOKEN_PRIMARY_GROUP group_token
;
6680 PROCESS_MEMORY_COUNTERS mem
;
6681 PROCESS_MEMORY_COUNTERS_EX mem_ex
;
6682 SIZE_T minrss
, maxrss
;
6684 MEMORY_STATUS_EX memstex
;
6685 double totphys
= 0.0;
6686 Lisp_Object ctime
, stime
, utime
, etime
, ttime
;
6688 BOOL result
= FALSE
;
6690 CHECK_NUMBER_OR_FLOAT (pid
);
6691 proc_id
= FLOATP (pid
) ? XFLOAT_DATA (pid
) : XINT (pid
);
6693 h_snapshot
= create_toolhelp32_snapshot (TH32CS_SNAPPROCESS
, 0);
6695 GCPRO3 (attrs
, decoded_cmd
, tem
);
6697 if (h_snapshot
!= INVALID_HANDLE_VALUE
)
6702 pe
.dwSize
= sizeof (PROCESSENTRY32
);
6703 for (res
= process32_first (h_snapshot
, &pe
); res
;
6704 res
= process32_next (h_snapshot
, &pe
))
6706 if (proc_id
== pe
.th32ProcessID
)
6709 decoded_cmd
= build_string ("Idle");
6712 /* Decode the command name from locale-specific
6714 cmd_str
= build_unibyte_string (pe
.szExeFile
);
6717 code_convert_string_norecord (cmd_str
,
6718 Vlocale_coding_system
, 0);
6720 attrs
= Fcons (Fcons (Qcomm
, decoded_cmd
), attrs
);
6721 attrs
= Fcons (Fcons (Qppid
,
6722 make_fixnum_or_float (pe
.th32ParentProcessID
)),
6724 attrs
= Fcons (Fcons (Qpri
, make_number (pe
.pcPriClassBase
)),
6726 attrs
= Fcons (Fcons (Qthcount
,
6727 make_fixnum_or_float (pe
.cntThreads
)),
6734 CloseHandle (h_snapshot
);
6743 h_proc
= OpenProcess (PROCESS_QUERY_INFORMATION
| PROCESS_VM_READ
,
6745 /* If we were denied a handle to the process, try again after
6746 enabling the SeDebugPrivilege in our process. */
6749 TOKEN_PRIVILEGES priv_current
;
6751 if (enable_privilege (SE_DEBUG_NAME
, TRUE
, &priv_current
))
6753 h_proc
= OpenProcess (PROCESS_QUERY_INFORMATION
| PROCESS_VM_READ
,
6755 restore_privilege (&priv_current
);
6761 result
= open_process_token (h_proc
, TOKEN_QUERY
, &token
);
6764 result
= get_token_information (token
, TokenUser
, NULL
, 0, &blen
);
6765 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
6767 buf
= xmalloc (blen
);
6768 result
= get_token_information (token
, TokenUser
,
6769 (LPVOID
)buf
, blen
, &needed
);
6772 memcpy (&user_token
, buf
, sizeof (user_token
));
6773 if (!w32_cached_id (user_token
.User
.Sid
, &euid
, uname
))
6775 euid
= get_rid (user_token
.User
.Sid
);
6776 result
= lookup_account_sid (NULL
, user_token
.User
.Sid
,
6781 w32_add_to_cache (user_token
.User
.Sid
, euid
, uname
);
6784 strcpy (uname
, "unknown");
6788 ulength
= strlen (uname
);
6794 /* Determine a reasonable euid and gid values. */
6795 if (xstrcasecmp ("administrator", uname
) == 0)
6797 euid
= 500; /* well-known Administrator uid */
6798 egid
= 513; /* well-known None gid */
6802 /* Get group id and name. */
6803 result
= get_token_information (token
, TokenPrimaryGroup
,
6804 (LPVOID
)buf
, blen
, &needed
);
6805 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
6807 buf
= xrealloc (buf
, blen
= needed
);
6808 result
= get_token_information (token
, TokenPrimaryGroup
,
6809 (LPVOID
)buf
, blen
, &needed
);
6813 memcpy (&group_token
, buf
, sizeof (group_token
));
6814 if (!w32_cached_id (group_token
.PrimaryGroup
, &egid
, gname
))
6816 egid
= get_rid (group_token
.PrimaryGroup
);
6817 dlength
= sizeof (domain
);
6819 lookup_account_sid (NULL
, group_token
.PrimaryGroup
,
6820 gname
, &glength
, NULL
, &dlength
,
6823 w32_add_to_cache (group_token
.PrimaryGroup
,
6827 strcpy (gname
, "None");
6831 glength
= strlen (gname
);
6839 if (!is_windows_9x ())
6841 /* We couldn't open the process token, presumably because of
6842 insufficient access rights. Assume this process is run
6844 strcpy (uname
, "SYSTEM");
6845 strcpy (gname
, "None");
6846 euid
= 18; /* SYSTEM */
6847 egid
= 513; /* None */
6848 glength
= strlen (gname
);
6849 ulength
= strlen (uname
);
6851 /* If we are running under Windows 9X, where security calls are
6852 not supported, we assume all processes are run by the current
6854 else if (GetUserName (uname
, &ulength
))
6856 if (xstrcasecmp ("administrator", uname
) == 0)
6861 strcpy (gname
, "None");
6862 glength
= strlen (gname
);
6863 ulength
= strlen (uname
);
6869 strcpy (uname
, "administrator");
6870 ulength
= strlen (uname
);
6871 strcpy (gname
, "None");
6872 glength
= strlen (gname
);
6875 CloseHandle (token
);
6878 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (euid
)), attrs
);
6879 tem
= make_unibyte_string (uname
, ulength
);
6880 attrs
= Fcons (Fcons (Quser
,
6881 code_convert_string_norecord (tem
, Vlocale_coding_system
, 0)),
6883 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (egid
)), attrs
);
6884 tem
= make_unibyte_string (gname
, glength
);
6885 attrs
= Fcons (Fcons (Qgroup
,
6886 code_convert_string_norecord (tem
, Vlocale_coding_system
, 0)),
6889 if (global_memory_status_ex (&memstex
))
6890 #if __GNUC__ || (defined (_MSC_VER) && _MSC_VER >= 1300)
6891 totphys
= memstex
.ullTotalPhys
/ 1024.0;
6893 /* Visual Studio 6 cannot convert an unsigned __int64 type to
6894 double, so we need to do this for it... */
6896 DWORD tot_hi
= memstex
.ullTotalPhys
>> 32;
6897 DWORD tot_md
= (memstex
.ullTotalPhys
& 0x00000000ffffffff) >> 10;
6898 DWORD tot_lo
= memstex
.ullTotalPhys
% 1024;
6900 totphys
= tot_hi
* 4194304.0 + tot_md
+ tot_lo
/ 1024.0;
6902 #endif /* __GNUC__ || _MSC_VER >= 1300 */
6903 else if (global_memory_status (&memst
))
6904 totphys
= memst
.dwTotalPhys
/ 1024.0;
6907 && get_process_memory_info (h_proc
, (PROCESS_MEMORY_COUNTERS
*)&mem_ex
,
6910 SIZE_T rss
= mem_ex
.WorkingSetSize
/ 1024;
6912 attrs
= Fcons (Fcons (Qmajflt
,
6913 make_fixnum_or_float (mem_ex
.PageFaultCount
)),
6915 attrs
= Fcons (Fcons (Qvsize
,
6916 make_fixnum_or_float (mem_ex
.PrivateUsage
/ 1024)),
6918 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (rss
)), attrs
);
6920 attrs
= Fcons (Fcons (Qpmem
, make_float (100. * rss
/ totphys
)), attrs
);
6923 && get_process_memory_info (h_proc
, &mem
, sizeof (mem
)))
6925 SIZE_T rss
= mem_ex
.WorkingSetSize
/ 1024;
6927 attrs
= Fcons (Fcons (Qmajflt
,
6928 make_fixnum_or_float (mem
.PageFaultCount
)),
6930 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (rss
)), attrs
);
6932 attrs
= Fcons (Fcons (Qpmem
, make_float (100. * rss
/ totphys
)), attrs
);
6935 && get_process_working_set_size (h_proc
, &minrss
, &maxrss
))
6937 DWORD rss
= maxrss
/ 1024;
6939 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (maxrss
/ 1024)), attrs
);
6941 attrs
= Fcons (Fcons (Qpmem
, make_float (100. * rss
/ totphys
)), attrs
);
6944 if (process_times (h_proc
, &ctime
, &etime
, &stime
, &utime
, &ttime
, &pcpu
))
6946 attrs
= Fcons (Fcons (Qutime
, utime
), attrs
);
6947 attrs
= Fcons (Fcons (Qstime
, stime
), attrs
);
6948 attrs
= Fcons (Fcons (Qtime
, ttime
), attrs
);
6949 attrs
= Fcons (Fcons (Qstart
, ctime
), attrs
);
6950 attrs
= Fcons (Fcons (Qetime
, etime
), attrs
);
6951 attrs
= Fcons (Fcons (Qpcpu
, make_float (pcpu
)), attrs
);
6954 /* FIXME: Retrieve command line by walking the PEB of the process. */
6957 CloseHandle (h_proc
);
6963 /* Wrappers for winsock functions to map between our file descriptors
6964 and winsock's handles; also set h_errno for convenience.
6966 To allow Emacs to run on systems which don't have winsock support
6967 installed, we dynamically link to winsock on startup if present, and
6968 otherwise provide the minimum necessary functionality
6969 (eg. gethostname). */
6971 /* function pointers for relevant socket functions */
6972 int (PASCAL
*pfn_WSAStartup
) (WORD wVersionRequired
, LPWSADATA lpWSAData
);
6973 void (PASCAL
*pfn_WSASetLastError
) (int iError
);
6974 int (PASCAL
*pfn_WSAGetLastError
) (void);
6975 int (PASCAL
*pfn_WSAEventSelect
) (SOCKET s
, HANDLE hEventObject
, long lNetworkEvents
);
6976 HANDLE (PASCAL
*pfn_WSACreateEvent
) (void);
6977 int (PASCAL
*pfn_WSACloseEvent
) (HANDLE hEvent
);
6978 int (PASCAL
*pfn_socket
) (int af
, int type
, int protocol
);
6979 int (PASCAL
*pfn_bind
) (SOCKET s
, const struct sockaddr
*addr
, int namelen
);
6980 int (PASCAL
*pfn_connect
) (SOCKET s
, const struct sockaddr
*addr
, int namelen
);
6981 int (PASCAL
*pfn_ioctlsocket
) (SOCKET s
, long cmd
, u_long
*argp
);
6982 int (PASCAL
*pfn_recv
) (SOCKET s
, char * buf
, int len
, int flags
);
6983 int (PASCAL
*pfn_send
) (SOCKET s
, const char * buf
, int len
, int flags
);
6984 int (PASCAL
*pfn_closesocket
) (SOCKET s
);
6985 int (PASCAL
*pfn_shutdown
) (SOCKET s
, int how
);
6986 int (PASCAL
*pfn_WSACleanup
) (void);
6988 u_short (PASCAL
*pfn_htons
) (u_short hostshort
);
6989 u_short (PASCAL
*pfn_ntohs
) (u_short netshort
);
6990 unsigned long (PASCAL
*pfn_inet_addr
) (const char * cp
);
6991 int (PASCAL
*pfn_gethostname
) (char * name
, int namelen
);
6992 struct hostent
* (PASCAL
*pfn_gethostbyname
) (const char * name
);
6993 struct servent
* (PASCAL
*pfn_getservbyname
) (const char * name
, const char * proto
);
6994 int (PASCAL
*pfn_getpeername
) (SOCKET s
, struct sockaddr
*addr
, int * namelen
);
6995 int (PASCAL
*pfn_setsockopt
) (SOCKET s
, int level
, int optname
,
6996 const char * optval
, int optlen
);
6997 int (PASCAL
*pfn_listen
) (SOCKET s
, int backlog
);
6998 int (PASCAL
*pfn_getsockname
) (SOCKET s
, struct sockaddr
* name
,
7000 SOCKET (PASCAL
*pfn_accept
) (SOCKET s
, struct sockaddr
* addr
, int * addrlen
);
7001 int (PASCAL
*pfn_recvfrom
) (SOCKET s
, char * buf
, int len
, int flags
,
7002 struct sockaddr
* from
, int * fromlen
);
7003 int (PASCAL
*pfn_sendto
) (SOCKET s
, const char * buf
, int len
, int flags
,
7004 const struct sockaddr
* to
, int tolen
);
7006 /* SetHandleInformation is only needed to make sockets non-inheritable. */
7007 BOOL (WINAPI
*pfn_SetHandleInformation
) (HANDLE object
, DWORD mask
, DWORD flags
);
7008 #ifndef HANDLE_FLAG_INHERIT
7009 #define HANDLE_FLAG_INHERIT 1
7013 static int winsock_inuse
;
7018 if (winsock_lib
!= NULL
&& winsock_inuse
== 0)
7020 release_listen_threads ();
7021 /* Not sure what would cause WSAENETDOWN, or even if it can happen
7022 after WSAStartup returns successfully, but it seems reasonable
7023 to allow unloading winsock anyway in that case. */
7024 if (pfn_WSACleanup () == 0 ||
7025 pfn_WSAGetLastError () == WSAENETDOWN
)
7027 if (FreeLibrary (winsock_lib
))
7036 init_winsock (int load_now
)
7038 WSADATA winsockData
;
7040 if (winsock_lib
!= NULL
)
7043 pfn_SetHandleInformation
7044 = (void *) GetProcAddress (GetModuleHandle ("kernel32.dll"),
7045 "SetHandleInformation");
7047 winsock_lib
= LoadLibrary ("Ws2_32.dll");
7049 if (winsock_lib
!= NULL
)
7051 /* dynamically link to socket functions */
7053 #define LOAD_PROC(fn) \
7054 if ((pfn_##fn = (void *) GetProcAddress (winsock_lib, #fn)) == NULL) \
7057 LOAD_PROC (WSAStartup
);
7058 LOAD_PROC (WSASetLastError
);
7059 LOAD_PROC (WSAGetLastError
);
7060 LOAD_PROC (WSAEventSelect
);
7061 LOAD_PROC (WSACreateEvent
);
7062 LOAD_PROC (WSACloseEvent
);
7065 LOAD_PROC (connect
);
7066 LOAD_PROC (ioctlsocket
);
7069 LOAD_PROC (closesocket
);
7070 LOAD_PROC (shutdown
);
7073 LOAD_PROC (inet_addr
);
7074 LOAD_PROC (gethostname
);
7075 LOAD_PROC (gethostbyname
);
7076 LOAD_PROC (getservbyname
);
7077 LOAD_PROC (getpeername
);
7078 LOAD_PROC (WSACleanup
);
7079 LOAD_PROC (setsockopt
);
7081 LOAD_PROC (getsockname
);
7083 LOAD_PROC (recvfrom
);
7087 /* specify version 1.1 of winsock */
7088 if (pfn_WSAStartup (0x101, &winsockData
) == 0)
7090 if (winsockData
.wVersion
!= 0x101)
7095 /* Report that winsock exists and is usable, but leave
7096 socket functions disabled. I am assuming that calling
7097 WSAStartup does not require any network interaction,
7098 and in particular does not cause or require a dial-up
7099 connection to be established. */
7102 FreeLibrary (winsock_lib
);
7110 FreeLibrary (winsock_lib
);
7120 /* Function to map winsock error codes to errno codes for those errno
7121 code defined in errno.h (errno values not defined by errno.h are
7122 already in nt/inc/sys/socket.h). */
7129 if (winsock_lib
== NULL
)
7132 wsa_err
= pfn_WSAGetLastError ();
7136 case WSAEACCES
: errno
= EACCES
; break;
7137 case WSAEBADF
: errno
= EBADF
; break;
7138 case WSAEFAULT
: errno
= EFAULT
; break;
7139 case WSAEINTR
: errno
= EINTR
; break;
7140 case WSAEINVAL
: errno
= EINVAL
; break;
7141 case WSAEMFILE
: errno
= EMFILE
; break;
7142 case WSAENAMETOOLONG
: errno
= ENAMETOOLONG
; break;
7143 case WSAENOTEMPTY
: errno
= ENOTEMPTY
; break;
7144 default: errno
= wsa_err
; break;
7152 if (winsock_lib
!= NULL
)
7153 pfn_WSASetLastError (0);
7156 /* Extend strerror to handle the winsock-specific error codes. */
7160 } _wsa_errlist
[] = {
7161 {WSAEINTR
, "Interrupted function call"},
7162 {WSAEBADF
, "Bad file descriptor"},
7163 {WSAEACCES
, "Permission denied"},
7164 {WSAEFAULT
, "Bad address"},
7165 {WSAEINVAL
, "Invalid argument"},
7166 {WSAEMFILE
, "Too many open files"},
7168 {WSAEWOULDBLOCK
, "Resource temporarily unavailable"},
7169 {WSAEINPROGRESS
, "Operation now in progress"},
7170 {WSAEALREADY
, "Operation already in progress"},
7171 {WSAENOTSOCK
, "Socket operation on non-socket"},
7172 {WSAEDESTADDRREQ
, "Destination address required"},
7173 {WSAEMSGSIZE
, "Message too long"},
7174 {WSAEPROTOTYPE
, "Protocol wrong type for socket"},
7175 {WSAENOPROTOOPT
, "Bad protocol option"},
7176 {WSAEPROTONOSUPPORT
, "Protocol not supported"},
7177 {WSAESOCKTNOSUPPORT
, "Socket type not supported"},
7178 {WSAEOPNOTSUPP
, "Operation not supported"},
7179 {WSAEPFNOSUPPORT
, "Protocol family not supported"},
7180 {WSAEAFNOSUPPORT
, "Address family not supported by protocol family"},
7181 {WSAEADDRINUSE
, "Address already in use"},
7182 {WSAEADDRNOTAVAIL
, "Cannot assign requested address"},
7183 {WSAENETDOWN
, "Network is down"},
7184 {WSAENETUNREACH
, "Network is unreachable"},
7185 {WSAENETRESET
, "Network dropped connection on reset"},
7186 {WSAECONNABORTED
, "Software caused connection abort"},
7187 {WSAECONNRESET
, "Connection reset by peer"},
7188 {WSAENOBUFS
, "No buffer space available"},
7189 {WSAEISCONN
, "Socket is already connected"},
7190 {WSAENOTCONN
, "Socket is not connected"},
7191 {WSAESHUTDOWN
, "Cannot send after socket shutdown"},
7192 {WSAETOOMANYREFS
, "Too many references"}, /* not sure */
7193 {WSAETIMEDOUT
, "Connection timed out"},
7194 {WSAECONNREFUSED
, "Connection refused"},
7195 {WSAELOOP
, "Network loop"}, /* not sure */
7196 {WSAENAMETOOLONG
, "Name is too long"},
7197 {WSAEHOSTDOWN
, "Host is down"},
7198 {WSAEHOSTUNREACH
, "No route to host"},
7199 {WSAENOTEMPTY
, "Buffer not empty"}, /* not sure */
7200 {WSAEPROCLIM
, "Too many processes"},
7201 {WSAEUSERS
, "Too many users"}, /* not sure */
7202 {WSAEDQUOT
, "Double quote in host name"}, /* really not sure */
7203 {WSAESTALE
, "Data is stale"}, /* not sure */
7204 {WSAEREMOTE
, "Remote error"}, /* not sure */
7206 {WSASYSNOTREADY
, "Network subsystem is unavailable"},
7207 {WSAVERNOTSUPPORTED
, "WINSOCK.DLL version out of range"},
7208 {WSANOTINITIALISED
, "Winsock not initialized successfully"},
7209 {WSAEDISCON
, "Graceful shutdown in progress"},
7211 {WSAENOMORE
, "No more operations allowed"}, /* not sure */
7212 {WSAECANCELLED
, "Operation cancelled"}, /* not sure */
7213 {WSAEINVALIDPROCTABLE
, "Invalid procedure table from service provider"},
7214 {WSAEINVALIDPROVIDER
, "Invalid service provider version number"},
7215 {WSAEPROVIDERFAILEDINIT
, "Unable to initialize a service provider"},
7216 {WSASYSCALLFAILURE
, "System call failure"},
7217 {WSASERVICE_NOT_FOUND
, "Service not found"}, /* not sure */
7218 {WSATYPE_NOT_FOUND
, "Class type not found"},
7219 {WSA_E_NO_MORE
, "No more resources available"}, /* really not sure */
7220 {WSA_E_CANCELLED
, "Operation already cancelled"}, /* really not sure */
7221 {WSAEREFUSED
, "Operation refused"}, /* not sure */
7224 {WSAHOST_NOT_FOUND
, "Host not found"},
7225 {WSATRY_AGAIN
, "Authoritative host not found during name lookup"},
7226 {WSANO_RECOVERY
, "Non-recoverable error during name lookup"},
7227 {WSANO_DATA
, "Valid name, no data record of requested type"},
7233 sys_strerror (int error_no
)
7236 static char unknown_msg
[40];
7238 if (error_no
>= 0 && error_no
< sys_nerr
)
7239 return sys_errlist
[error_no
];
7241 for (i
= 0; _wsa_errlist
[i
].errnum
>= 0; i
++)
7242 if (_wsa_errlist
[i
].errnum
== error_no
)
7243 return _wsa_errlist
[i
].msg
;
7245 sprintf (unknown_msg
, "Unidentified error: %d", error_no
);
7249 /* [andrewi 3-May-96] I've had conflicting results using both methods,
7250 but I believe the method of keeping the socket handle separate (and
7251 insuring it is not inheritable) is the correct one. */
7253 #define SOCK_HANDLE(fd) ((SOCKET) fd_info[fd].hnd)
7255 static int socket_to_fd (SOCKET s
);
7258 sys_socket (int af
, int type
, int protocol
)
7262 if (winsock_lib
== NULL
)
7265 return INVALID_SOCKET
;
7270 /* call the real socket function */
7271 s
= pfn_socket (af
, type
, protocol
);
7273 if (s
!= INVALID_SOCKET
)
7274 return socket_to_fd (s
);
7280 /* Convert a SOCKET to a file descriptor. */
7282 socket_to_fd (SOCKET s
)
7287 /* Although under NT 3.5 _open_osfhandle will accept a socket
7288 handle, if opened with SO_OPENTYPE == SO_SYNCHRONOUS_NONALERT,
7289 that does not work under NT 3.1. However, we can get the same
7290 effect by using a backdoor function to replace an existing
7291 descriptor handle with the one we want. */
7293 /* allocate a file descriptor (with appropriate flags) */
7294 fd
= _open ("NUL:", _O_RDWR
);
7297 /* Make a non-inheritable copy of the socket handle. Note
7298 that it is possible that sockets aren't actually kernel
7299 handles, which appears to be the case on Windows 9x when
7300 the MS Proxy winsock client is installed. */
7302 /* Apparently there is a bug in NT 3.51 with some service
7303 packs, which prevents using DuplicateHandle to make a
7304 socket handle non-inheritable (causes WSACleanup to
7305 hang). The work-around is to use SetHandleInformation
7306 instead if it is available and implemented. */
7307 if (pfn_SetHandleInformation
)
7309 pfn_SetHandleInformation ((HANDLE
) s
, HANDLE_FLAG_INHERIT
, 0);
7313 HANDLE parent
= GetCurrentProcess ();
7314 HANDLE new_s
= INVALID_HANDLE_VALUE
;
7316 if (DuplicateHandle (parent
,
7322 DUPLICATE_SAME_ACCESS
))
7324 /* It is possible that DuplicateHandle succeeds even
7325 though the socket wasn't really a kernel handle,
7326 because a real handle has the same value. So
7327 test whether the new handle really is a socket. */
7328 long nonblocking
= 0;
7329 if (pfn_ioctlsocket ((SOCKET
) new_s
, FIONBIO
, &nonblocking
) == 0)
7331 pfn_closesocket (s
);
7336 CloseHandle (new_s
);
7341 eassert (fd
< MAXDESC
);
7342 fd_info
[fd
].hnd
= (HANDLE
) s
;
7344 /* set our own internal flags */
7345 fd_info
[fd
].flags
= FILE_SOCKET
| FILE_BINARY
| FILE_READ
| FILE_WRITE
;
7351 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
7353 /* attach child_process to fd_info */
7354 if (fd_info
[ fd
].cp
!= NULL
)
7356 DebPrint (("sys_socket: fd_info[%d] apparently in use!\n", fd
));
7360 fd_info
[ fd
].cp
= cp
;
7363 winsock_inuse
++; /* count open sockets */
7371 pfn_closesocket (s
);
7377 sys_bind (int s
, const struct sockaddr
* addr
, int namelen
)
7379 if (winsock_lib
== NULL
)
7382 return SOCKET_ERROR
;
7386 if (fd_info
[s
].flags
& FILE_SOCKET
)
7388 int rc
= pfn_bind (SOCK_HANDLE (s
), addr
, namelen
);
7389 if (rc
== SOCKET_ERROR
)
7394 return SOCKET_ERROR
;
7398 sys_connect (int s
, const struct sockaddr
* name
, int namelen
)
7400 if (winsock_lib
== NULL
)
7403 return SOCKET_ERROR
;
7407 if (fd_info
[s
].flags
& FILE_SOCKET
)
7409 int rc
= pfn_connect (SOCK_HANDLE (s
), name
, namelen
);
7410 if (rc
== SOCKET_ERROR
)
7415 return SOCKET_ERROR
;
7419 sys_htons (u_short hostshort
)
7421 return (winsock_lib
!= NULL
) ?
7422 pfn_htons (hostshort
) : hostshort
;
7426 sys_ntohs (u_short netshort
)
7428 return (winsock_lib
!= NULL
) ?
7429 pfn_ntohs (netshort
) : netshort
;
7433 sys_inet_addr (const char * cp
)
7435 return (winsock_lib
!= NULL
) ?
7436 pfn_inet_addr (cp
) : INADDR_NONE
;
7440 sys_gethostname (char * name
, int namelen
)
7442 if (winsock_lib
!= NULL
)
7447 retval
= pfn_gethostname (name
, namelen
);
7448 if (retval
== SOCKET_ERROR
)
7453 if (namelen
> MAX_COMPUTERNAME_LENGTH
)
7454 return !GetComputerName (name
, (DWORD
*)&namelen
);
7457 return SOCKET_ERROR
;
7461 sys_gethostbyname (const char * name
)
7463 struct hostent
* host
;
7464 int h_err
= h_errno
;
7466 if (winsock_lib
== NULL
)
7468 h_errno
= NO_RECOVERY
;
7474 host
= pfn_gethostbyname (name
);
7486 sys_getservbyname (const char * name
, const char * proto
)
7488 struct servent
* serv
;
7490 if (winsock_lib
== NULL
)
7497 serv
= pfn_getservbyname (name
, proto
);
7504 sys_getpeername (int s
, struct sockaddr
*addr
, int * namelen
)
7506 if (winsock_lib
== NULL
)
7509 return SOCKET_ERROR
;
7513 if (fd_info
[s
].flags
& FILE_SOCKET
)
7515 int rc
= pfn_getpeername (SOCK_HANDLE (s
), addr
, namelen
);
7516 if (rc
== SOCKET_ERROR
)
7521 return SOCKET_ERROR
;
7525 sys_shutdown (int s
, int how
)
7527 if (winsock_lib
== NULL
)
7530 return SOCKET_ERROR
;
7534 if (fd_info
[s
].flags
& FILE_SOCKET
)
7536 int rc
= pfn_shutdown (SOCK_HANDLE (s
), how
);
7537 if (rc
== SOCKET_ERROR
)
7542 return SOCKET_ERROR
;
7546 sys_setsockopt (int s
, int level
, int optname
, const void * optval
, int optlen
)
7548 if (winsock_lib
== NULL
)
7551 return SOCKET_ERROR
;
7555 if (fd_info
[s
].flags
& FILE_SOCKET
)
7557 int rc
= pfn_setsockopt (SOCK_HANDLE (s
), level
, optname
,
7558 (const char *)optval
, optlen
);
7559 if (rc
== SOCKET_ERROR
)
7564 return SOCKET_ERROR
;
7568 sys_listen (int s
, int backlog
)
7570 if (winsock_lib
== NULL
)
7573 return SOCKET_ERROR
;
7577 if (fd_info
[s
].flags
& FILE_SOCKET
)
7579 int rc
= pfn_listen (SOCK_HANDLE (s
), backlog
);
7580 if (rc
== SOCKET_ERROR
)
7583 fd_info
[s
].flags
|= FILE_LISTEN
;
7587 return SOCKET_ERROR
;
7591 sys_getsockname (int s
, struct sockaddr
* name
, int * namelen
)
7593 if (winsock_lib
== NULL
)
7596 return SOCKET_ERROR
;
7600 if (fd_info
[s
].flags
& FILE_SOCKET
)
7602 int rc
= pfn_getsockname (SOCK_HANDLE (s
), name
, namelen
);
7603 if (rc
== SOCKET_ERROR
)
7608 return SOCKET_ERROR
;
7612 sys_accept (int s
, struct sockaddr
* addr
, int * addrlen
)
7614 if (winsock_lib
== NULL
)
7621 if (fd_info
[s
].flags
& FILE_LISTEN
)
7623 SOCKET t
= pfn_accept (SOCK_HANDLE (s
), addr
, addrlen
);
7625 if (t
== INVALID_SOCKET
)
7628 fd
= socket_to_fd (t
);
7632 fd_info
[s
].cp
->status
= STATUS_READ_ACKNOWLEDGED
;
7633 ResetEvent (fd_info
[s
].cp
->char_avail
);
7642 sys_recvfrom (int s
, char * buf
, int len
, int flags
,
7643 struct sockaddr
* from
, int * fromlen
)
7645 if (winsock_lib
== NULL
)
7648 return SOCKET_ERROR
;
7652 if (fd_info
[s
].flags
& FILE_SOCKET
)
7654 int rc
= pfn_recvfrom (SOCK_HANDLE (s
), buf
, len
, flags
, from
, fromlen
);
7655 if (rc
== SOCKET_ERROR
)
7660 return SOCKET_ERROR
;
7664 sys_sendto (int s
, const char * buf
, int len
, int flags
,
7665 const struct sockaddr
* to
, int tolen
)
7667 if (winsock_lib
== NULL
)
7670 return SOCKET_ERROR
;
7674 if (fd_info
[s
].flags
& FILE_SOCKET
)
7676 int rc
= pfn_sendto (SOCK_HANDLE (s
), buf
, len
, flags
, to
, tolen
);
7677 if (rc
== SOCKET_ERROR
)
7682 return SOCKET_ERROR
;
7685 /* Windows does not have an fcntl function. Provide an implementation
7686 good enough for Emacs. */
7688 fcntl (int s
, int cmd
, int options
)
7690 /* In the w32 Emacs port, fcntl (fd, F_DUPFD_CLOEXEC, fd1) is always
7691 invoked in a context where fd1 is closed and all descriptors less
7692 than fd1 are open, so sys_dup is an adequate implementation. */
7693 if (cmd
== F_DUPFD_CLOEXEC
)
7696 if (winsock_lib
== NULL
)
7703 if (fd_info
[s
].flags
& FILE_SOCKET
)
7705 if (cmd
== F_SETFL
&& options
== O_NONBLOCK
)
7707 unsigned long nblock
= 1;
7708 int rc
= pfn_ioctlsocket (SOCK_HANDLE (s
), FIONBIO
, &nblock
);
7709 if (rc
== SOCKET_ERROR
)
7711 /* Keep track of the fact that we set this to non-blocking. */
7712 fd_info
[s
].flags
|= FILE_NDELAY
;
7718 return SOCKET_ERROR
;
7722 return SOCKET_ERROR
;
7726 /* Shadow main io functions: we need to handle pipes and sockets more
7727 intelligently, and implement non-blocking mode as well. */
7740 if (fd
< MAXDESC
&& fd_info
[fd
].cp
)
7742 child_process
* cp
= fd_info
[fd
].cp
;
7744 fd_info
[fd
].cp
= NULL
;
7746 if (CHILD_ACTIVE (cp
))
7748 /* if last descriptor to active child_process then cleanup */
7750 for (i
= 0; i
< MAXDESC
; i
++)
7754 if (fd_info
[i
].cp
== cp
)
7759 if (fd_info
[fd
].flags
& FILE_SOCKET
)
7761 if (winsock_lib
== NULL
) emacs_abort ();
7763 pfn_shutdown (SOCK_HANDLE (fd
), 2);
7764 rc
= pfn_closesocket (SOCK_HANDLE (fd
));
7766 winsock_inuse
--; /* count open sockets */
7768 /* If the process handle is NULL, it's either a socket
7769 or serial connection, or a subprocess that was
7770 already reaped by reap_subprocess, but whose
7771 resources were not yet freed, because its output was
7772 not fully read yet by the time it was reaped. (This
7773 usually happens with async subprocesses whose output
7774 is being read by Emacs.) Otherwise, this process was
7775 not reaped yet, so we set its FD to a negative value
7776 to make sure sys_select will eventually get to
7777 calling the SIGCHLD handler for it, which will then
7778 invoke waitpid and reap_subprocess. */
7779 if (cp
->procinfo
.hProcess
== NULL
)
7787 if (fd
>= 0 && fd
< MAXDESC
)
7788 fd_info
[fd
].flags
= 0;
7790 /* Note that sockets do not need special treatment here (at least on
7791 NT and Windows 95 using the standard tcp/ip stacks) - it appears that
7792 closesocket is equivalent to CloseHandle, which is to be expected
7793 because socket handles are fully fledged kernel handles. */
7805 if (new_fd
>= 0 && new_fd
< MAXDESC
)
7807 /* duplicate our internal info as well */
7808 fd_info
[new_fd
] = fd_info
[fd
];
7814 sys_dup2 (int src
, int dst
)
7818 if (dst
< 0 || dst
>= MAXDESC
)
7824 /* make sure we close the destination first if it's a pipe or socket */
7825 if (src
!= dst
&& fd_info
[dst
].flags
!= 0)
7828 rc
= _dup2 (src
, dst
);
7831 /* duplicate our internal info as well */
7832 fd_info
[dst
] = fd_info
[src
];
7838 pipe2 (int * phandles
, int pipe2_flags
)
7843 eassert (pipe2_flags
== O_CLOEXEC
);
7845 /* make pipe handles non-inheritable; when we spawn a child, we
7846 replace the relevant handle with an inheritable one. Also put
7847 pipes into binary mode; we will do text mode translation ourselves
7849 rc
= _pipe (phandles
, 0, _O_NOINHERIT
| _O_BINARY
);
7853 /* Protect against overflow, since Windows can open more handles than
7854 our fd_info array has room for. */
7855 if (phandles
[0] >= MAXDESC
|| phandles
[1] >= MAXDESC
)
7857 _close (phandles
[0]);
7858 _close (phandles
[1]);
7864 flags
= FILE_PIPE
| FILE_READ
| FILE_BINARY
;
7865 fd_info
[phandles
[0]].flags
= flags
;
7867 flags
= FILE_PIPE
| FILE_WRITE
| FILE_BINARY
;
7868 fd_info
[phandles
[1]].flags
= flags
;
7875 /* Function to do blocking read of one byte, needed to implement
7876 select. It is only allowed on communication ports, sockets, or
7879 _sys_read_ahead (int fd
)
7884 if (fd
< 0 || fd
>= MAXDESC
)
7885 return STATUS_READ_ERROR
;
7887 cp
= fd_info
[fd
].cp
;
7889 if (cp
== NULL
|| cp
->fd
!= fd
|| cp
->status
!= STATUS_READ_READY
)
7890 return STATUS_READ_ERROR
;
7892 if ((fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SERIAL
| FILE_SOCKET
)) == 0
7893 || (fd_info
[fd
].flags
& FILE_READ
) == 0)
7895 DebPrint (("_sys_read_ahead: internal error: fd %d is not a pipe, serial port, or socket!\n", fd
));
7899 cp
->status
= STATUS_READ_IN_PROGRESS
;
7901 if (fd_info
[fd
].flags
& FILE_PIPE
)
7903 rc
= _read (fd
, &cp
->chr
, sizeof (char));
7905 /* Give subprocess time to buffer some more output for us before
7906 reporting that input is available; we need this because Windows 95
7907 connects DOS programs to pipes by making the pipe appear to be
7908 the normal console stdout - as a result most DOS programs will
7909 write to stdout without buffering, ie. one character at a
7910 time. Even some W32 programs do this - "dir" in a command
7911 shell on NT is very slow if we don't do this. */
7914 int wait
= w32_pipe_read_delay
;
7920 /* Yield remainder of our time slice, effectively giving a
7921 temporary priority boost to the child process. */
7925 else if (fd_info
[fd
].flags
& FILE_SERIAL
)
7927 HANDLE hnd
= fd_info
[fd
].hnd
;
7928 OVERLAPPED
*ovl
= &fd_info
[fd
].cp
->ovl_read
;
7931 /* Configure timeouts for blocking read. */
7932 if (!GetCommTimeouts (hnd
, &ct
))
7934 cp
->status
= STATUS_READ_ERROR
;
7935 return STATUS_READ_ERROR
;
7937 ct
.ReadIntervalTimeout
= 0;
7938 ct
.ReadTotalTimeoutMultiplier
= 0;
7939 ct
.ReadTotalTimeoutConstant
= 0;
7940 if (!SetCommTimeouts (hnd
, &ct
))
7942 cp
->status
= STATUS_READ_ERROR
;
7943 return STATUS_READ_ERROR
;
7946 if (!ReadFile (hnd
, &cp
->chr
, sizeof (char), (DWORD
*) &rc
, ovl
))
7948 if (GetLastError () != ERROR_IO_PENDING
)
7950 cp
->status
= STATUS_READ_ERROR
;
7951 return STATUS_READ_ERROR
;
7953 if (!GetOverlappedResult (hnd
, ovl
, (DWORD
*) &rc
, TRUE
))
7955 cp
->status
= STATUS_READ_ERROR
;
7956 return STATUS_READ_ERROR
;
7960 else if (fd_info
[fd
].flags
& FILE_SOCKET
)
7962 unsigned long nblock
= 0;
7963 /* We always want this to block, so temporarily disable NDELAY. */
7964 if (fd_info
[fd
].flags
& FILE_NDELAY
)
7965 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
7967 rc
= pfn_recv (SOCK_HANDLE (fd
), &cp
->chr
, sizeof (char), 0);
7969 if (fd_info
[fd
].flags
& FILE_NDELAY
)
7972 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
7976 if (rc
== sizeof (char))
7977 cp
->status
= STATUS_READ_SUCCEEDED
;
7979 cp
->status
= STATUS_READ_FAILED
;
7985 _sys_wait_accept (int fd
)
7991 if (fd
< 0 || fd
>= MAXDESC
)
7992 return STATUS_READ_ERROR
;
7994 cp
= fd_info
[fd
].cp
;
7996 if (cp
== NULL
|| cp
->fd
!= fd
|| cp
->status
!= STATUS_READ_READY
)
7997 return STATUS_READ_ERROR
;
7999 cp
->status
= STATUS_READ_FAILED
;
8001 hEv
= pfn_WSACreateEvent ();
8002 rc
= pfn_WSAEventSelect (SOCK_HANDLE (fd
), hEv
, FD_ACCEPT
);
8003 if (rc
!= SOCKET_ERROR
)
8006 rc
= WaitForSingleObject (hEv
, 500);
8008 } while (rc
== WAIT_TIMEOUT
8009 && cp
->status
!= STATUS_READ_ERROR
8011 pfn_WSAEventSelect (SOCK_HANDLE (fd
), NULL
, 0);
8012 if (rc
== WAIT_OBJECT_0
)
8013 cp
->status
= STATUS_READ_SUCCEEDED
;
8015 pfn_WSACloseEvent (hEv
);
8021 sys_read (int fd
, char * buffer
, unsigned int count
)
8026 char * orig_buffer
= buffer
;
8034 if (fd
< MAXDESC
&& fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
| FILE_SERIAL
))
8036 child_process
*cp
= fd_info
[fd
].cp
;
8038 if ((fd_info
[fd
].flags
& FILE_READ
) == 0)
8046 /* re-read CR carried over from last read */
8047 if (fd_info
[fd
].flags
& FILE_LAST_CR
)
8049 if (fd_info
[fd
].flags
& FILE_BINARY
) emacs_abort ();
8053 fd_info
[fd
].flags
&= ~FILE_LAST_CR
;
8056 /* presence of a child_process structure means we are operating in
8057 non-blocking mode - otherwise we just call _read directly.
8058 Note that the child_process structure might be missing because
8059 reap_subprocess has been called; in this case the pipe is
8060 already broken, so calling _read on it is okay. */
8063 int current_status
= cp
->status
;
8065 switch (current_status
)
8067 case STATUS_READ_FAILED
:
8068 case STATUS_READ_ERROR
:
8069 /* report normal EOF if nothing in buffer */
8071 fd_info
[fd
].flags
|= FILE_AT_EOF
;
8074 case STATUS_READ_READY
:
8075 case STATUS_READ_IN_PROGRESS
:
8076 DebPrint (("sys_read called when read is in progress\n"));
8077 errno
= EWOULDBLOCK
;
8080 case STATUS_READ_SUCCEEDED
:
8081 /* consume read-ahead char */
8082 *buffer
++ = cp
->chr
;
8085 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
8086 ResetEvent (cp
->char_avail
);
8088 case STATUS_READ_ACKNOWLEDGED
:
8092 DebPrint (("sys_read: bad status %d\n", current_status
));
8097 if (fd_info
[fd
].flags
& FILE_PIPE
)
8099 PeekNamedPipe ((HANDLE
) _get_osfhandle (fd
), NULL
, 0, NULL
, &waiting
, NULL
);
8100 to_read
= min (waiting
, (DWORD
) count
);
8103 nchars
+= _read (fd
, buffer
, to_read
);
8105 else if (fd_info
[fd
].flags
& FILE_SERIAL
)
8107 HANDLE hnd
= fd_info
[fd
].hnd
;
8108 OVERLAPPED
*ovl
= &fd_info
[fd
].cp
->ovl_read
;
8114 /* Configure timeouts for non-blocking read. */
8115 if (!GetCommTimeouts (hnd
, &ct
))
8120 ct
.ReadIntervalTimeout
= MAXDWORD
;
8121 ct
.ReadTotalTimeoutMultiplier
= 0;
8122 ct
.ReadTotalTimeoutConstant
= 0;
8123 if (!SetCommTimeouts (hnd
, &ct
))
8129 if (!ResetEvent (ovl
->hEvent
))
8134 if (!ReadFile (hnd
, buffer
, count
, (DWORD
*) &rc
, ovl
))
8136 if (GetLastError () != ERROR_IO_PENDING
)
8141 if (!GetOverlappedResult (hnd
, ovl
, (DWORD
*) &rc
, TRUE
))
8150 else /* FILE_SOCKET */
8152 if (winsock_lib
== NULL
) emacs_abort ();
8154 /* do the equivalent of a non-blocking read */
8155 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONREAD
, &waiting
);
8156 if (waiting
== 0 && nchars
== 0)
8158 errno
= EWOULDBLOCK
;
8164 /* always use binary mode for sockets */
8165 int res
= pfn_recv (SOCK_HANDLE (fd
), buffer
, count
, 0);
8166 if (res
== SOCKET_ERROR
)
8168 DebPrint (("sys_read.recv failed with error %d on socket %ld\n",
8169 pfn_WSAGetLastError (), SOCK_HANDLE (fd
)));
8179 int nread
= _read (fd
, buffer
, count
);
8182 else if (nchars
== 0)
8187 fd_info
[fd
].flags
|= FILE_AT_EOF
;
8188 /* Perform text mode translation if required. */
8189 else if ((fd_info
[fd
].flags
& FILE_BINARY
) == 0)
8191 nchars
= crlf_to_lf (nchars
, orig_buffer
);
8192 /* If buffer contains only CR, return that. To be absolutely
8193 sure we should attempt to read the next char, but in
8194 practice a CR to be followed by LF would not appear by
8195 itself in the buffer. */
8196 if (nchars
> 1 && orig_buffer
[nchars
- 1] == 0x0d)
8198 fd_info
[fd
].flags
|= FILE_LAST_CR
;
8204 nchars
= _read (fd
, buffer
, count
);
8209 /* From w32xfns.c */
8210 extern HANDLE interrupt_handle
;
8212 /* For now, don't bother with a non-blocking mode */
8214 sys_write (int fd
, const void * buffer
, unsigned int count
)
8224 if (fd
< MAXDESC
&& fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
| FILE_SERIAL
))
8226 if ((fd_info
[fd
].flags
& FILE_WRITE
) == 0)
8232 /* Perform text mode translation if required. */
8233 if ((fd_info
[fd
].flags
& FILE_BINARY
) == 0)
8235 char * tmpbuf
= alloca (count
* 2);
8236 unsigned char * src
= (void *)buffer
;
8237 unsigned char * dst
= tmpbuf
;
8242 unsigned char *next
;
8243 /* copy next line or remaining bytes */
8244 next
= _memccpy (dst
, src
, '\n', nbytes
);
8247 /* copied one line ending with '\n' */
8248 int copied
= next
- dst
;
8251 /* insert '\r' before '\n' */
8258 /* copied remaining partial line -> now finished */
8265 if (fd
< MAXDESC
&& fd_info
[fd
].flags
& FILE_SERIAL
)
8267 HANDLE hnd
= (HANDLE
) _get_osfhandle (fd
);
8268 OVERLAPPED
*ovl
= &fd_info
[fd
].cp
->ovl_write
;
8269 HANDLE wait_hnd
[2] = { interrupt_handle
, ovl
->hEvent
};
8272 if (!WriteFile (hnd
, buffer
, count
, (DWORD
*) &nchars
, ovl
))
8274 if (GetLastError () != ERROR_IO_PENDING
)
8279 if (detect_input_pending ())
8280 active
= MsgWaitForMultipleObjects (2, wait_hnd
, FALSE
, INFINITE
,
8283 active
= WaitForMultipleObjects (2, wait_hnd
, FALSE
, INFINITE
);
8284 if (active
== WAIT_OBJECT_0
)
8285 { /* User pressed C-g, cancel write, then leave. Don't bother
8286 cleaning up as we may only get stuck in buggy drivers. */
8287 PurgeComm (hnd
, PURGE_TXABORT
| PURGE_TXCLEAR
);
8292 if (active
== WAIT_OBJECT_0
+ 1
8293 && !GetOverlappedResult (hnd
, ovl
, (DWORD
*) &nchars
, TRUE
))
8300 else if (fd
< MAXDESC
&& fd_info
[fd
].flags
& FILE_SOCKET
)
8302 unsigned long nblock
= 0;
8303 if (winsock_lib
== NULL
) emacs_abort ();
8305 /* TODO: implement select() properly so non-blocking I/O works. */
8306 /* For now, make sure the write blocks. */
8307 if (fd_info
[fd
].flags
& FILE_NDELAY
)
8308 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
8310 nchars
= pfn_send (SOCK_HANDLE (fd
), buffer
, count
, 0);
8312 /* Set the socket back to non-blocking if it was before,
8313 for other operations that support it. */
8314 if (fd_info
[fd
].flags
& FILE_NDELAY
)
8317 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
8320 if (nchars
== SOCKET_ERROR
)
8322 DebPrint (("sys_write.send failed with error %d on socket %ld\n",
8323 pfn_WSAGetLastError (), SOCK_HANDLE (fd
)));
8329 /* Some networked filesystems don't like too large writes, so
8330 break them into smaller chunks. See the Comments section of
8331 the MSDN documentation of WriteFile for details behind the
8332 choice of the value of CHUNK below. See also the thread
8333 http://thread.gmane.org/gmane.comp.version-control.git/145294
8334 in the git mailing list. */
8335 const unsigned char *p
= buffer
;
8336 const unsigned chunk
= 30 * 1024 * 1024;
8341 unsigned this_chunk
= count
< chunk
? count
: chunk
;
8342 int n
= _write (fd
, p
, this_chunk
);
8350 else if (n
< this_chunk
)
8361 /* Emulation of SIOCGIFCONF and getifaddrs, see process.c. */
8363 extern Lisp_Object
conv_sockaddr_to_lisp (struct sockaddr
*, int);
8365 /* Return information about network interface IFNAME, or about all
8366 interfaces (if IFNAME is nil). */
8368 network_interface_get_info (Lisp_Object ifname
)
8370 ULONG ainfo_len
= sizeof (IP_ADAPTER_INFO
);
8371 IP_ADAPTER_INFO
*adapter
, *ainfo
= xmalloc (ainfo_len
);
8372 DWORD retval
= get_adapters_info (ainfo
, &ainfo_len
);
8373 Lisp_Object res
= Qnil
;
8375 if (retval
== ERROR_BUFFER_OVERFLOW
)
8377 ainfo
= xrealloc (ainfo
, ainfo_len
);
8378 retval
= get_adapters_info (ainfo
, &ainfo_len
);
8381 if (retval
== ERROR_SUCCESS
)
8383 int eth_count
= 0, tr_count
= 0, fddi_count
= 0, ppp_count
= 0;
8384 int sl_count
= 0, wlan_count
= 0, lo_count
= 0, ifx_count
= 0;
8386 struct sockaddr_in sa
;
8388 /* For the below, we need some winsock functions, so make sure
8389 the winsock DLL is loaded. If we cannot successfully load
8390 it, they will have no use of the information we provide,
8392 if (!winsock_lib
&& !init_winsock (1))
8395 for (adapter
= ainfo
; adapter
; adapter
= adapter
->Next
)
8397 char namebuf
[MAX_ADAPTER_NAME_LENGTH
+ 4];
8399 /* Present Unix-compatible interface names, instead of the
8400 Windows names, which are really GUIDs not readable by
8402 static const char *ifmt
[] = {
8403 "eth%d", "tr%d", "fddi%d", "ppp%d", "sl%d", "wlan%d",
8418 switch (adapter
->Type
)
8420 case MIB_IF_TYPE_ETHERNET
:
8421 /* Windows before Vista reports wireless adapters as
8422 Ethernet. Work around by looking at the Description
8424 if (strstr (adapter
->Description
, "Wireless "))
8427 if_num
= wlan_count
++;
8431 ifmt_idx
= ETHERNET
;
8432 if_num
= eth_count
++;
8435 case MIB_IF_TYPE_TOKENRING
:
8436 ifmt_idx
= TOKENRING
;
8437 if_num
= tr_count
++;
8439 case MIB_IF_TYPE_FDDI
:
8441 if_num
= fddi_count
++;
8443 case MIB_IF_TYPE_PPP
:
8445 if_num
= ppp_count
++;
8447 case MIB_IF_TYPE_SLIP
:
8449 if_num
= sl_count
++;
8451 case IF_TYPE_IEEE80211
:
8453 if_num
= wlan_count
++;
8455 case MIB_IF_TYPE_LOOPBACK
:
8458 ifmt_idx
= LOOPBACK
;
8459 if_num
= lo_count
++;
8465 ifmt_idx
= OTHER_IF
;
8466 if_num
= ifx_count
++;
8469 if (ifmt_idx
== NONE
)
8471 sprintf (namebuf
, ifmt
[ifmt_idx
], if_num
);
8473 sa
.sin_family
= AF_INET
;
8474 ip_addr
= sys_inet_addr (adapter
->IpAddressList
.IpAddress
.String
);
8475 if (ip_addr
== INADDR_NONE
)
8477 /* Bogus address, skip this interface. */
8480 sa
.sin_addr
.s_addr
= ip_addr
;
8483 res
= Fcons (Fcons (build_string (namebuf
),
8484 conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
8485 sizeof (struct sockaddr
))),
8487 else if (strcmp (namebuf
, SSDATA (ifname
)) == 0)
8489 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
8490 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
8491 Lisp_Object flags
= Qnil
;
8495 /* Flags. We guess most of them by type, since the
8496 Windows flags are different and hard to get by. */
8497 flags
= Fcons (intern ("up"), flags
);
8498 if (ifmt_idx
== ETHERNET
|| ifmt_idx
== WLAN
)
8500 flags
= Fcons (intern ("broadcast"), flags
);
8501 flags
= Fcons (intern ("multicast"), flags
);
8503 flags
= Fcons (intern ("running"), flags
);
8504 if (ifmt_idx
== PPP
)
8506 flags
= Fcons (intern ("pointopoint"), flags
);
8507 flags
= Fcons (intern ("noarp"), flags
);
8509 if (adapter
->HaveWins
)
8510 flags
= Fcons (intern ("WINS"), flags
);
8511 if (adapter
->DhcpEnabled
)
8512 flags
= Fcons (intern ("dynamic"), flags
);
8514 res
= Fcons (flags
, res
);
8516 /* Hardware address and its family. */
8517 for (n
= 0; n
< adapter
->AddressLength
; n
++)
8518 p
->contents
[n
] = make_number ((int) adapter
->Address
[n
]);
8519 /* Windows does not support AF_LINK or AF_PACKET family
8520 of addresses. Use an arbitrary family number that is
8521 identical to what GNU/Linux returns. */
8522 res
= Fcons (Fcons (make_number (1), hwaddr
), res
);
8525 sa
.sin_family
= AF_INET
;
8526 net_mask
= sys_inet_addr (adapter
->IpAddressList
.IpMask
.String
);
8527 if (net_mask
!= INADDR_NONE
)
8529 sa
.sin_addr
.s_addr
= net_mask
;
8531 res
= Fcons (conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
8532 sizeof (struct sockaddr
)),
8536 res
= Fcons (Qnil
, res
);
8538 sa
.sin_family
= AF_INET
;
8539 if (ip_addr
!= INADDR_NONE
)
8541 /* Broadcast address is only reported by
8542 GetAdaptersAddresses, which is of limited
8543 availability. Generate it on our own. */
8544 u_long bcast_addr
= (ip_addr
& net_mask
) | ~net_mask
;
8546 sa
.sin_addr
.s_addr
= bcast_addr
;
8548 res
= Fcons (conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
8549 sizeof (struct sockaddr
)),
8553 sa
.sin_addr
.s_addr
= ip_addr
;
8555 res
= Fcons (conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
8556 sizeof (struct sockaddr
)),
8560 res
= Fcons (Qnil
, Fcons (Qnil
, res
));
8563 /* GetAdaptersInfo is documented to not report loopback
8564 interfaces, so we generate one out of thin air. */
8567 sa
.sin_family
= AF_INET
;
8571 sa
.sin_addr
.s_addr
= sys_inet_addr ("127.0.0.1");
8572 res
= Fcons (Fcons (build_string ("lo"),
8573 conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
8574 sizeof (struct sockaddr
))),
8577 else if (strcmp (SSDATA (ifname
), "lo") == 0)
8579 res
= Fcons (Fcons (intern ("running"),
8580 Fcons (intern ("loopback"),
8581 Fcons (intern ("up"), Qnil
))), Qnil
);
8582 /* 772 is what 3 different GNU/Linux systems report for
8583 the loopback interface. */
8584 res
= Fcons (Fcons (make_number (772),
8585 Fmake_vector (make_number (6),
8588 sa
.sin_addr
.s_addr
= sys_inet_addr ("255.0.0.0");
8589 res
= Fcons (conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
8590 sizeof (struct sockaddr
)),
8592 sa
.sin_addr
.s_addr
= sys_inet_addr ("0.0.0.0");
8593 res
= Fcons (conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
8594 sizeof (struct sockaddr
)),
8596 sa
.sin_addr
.s_addr
= sys_inet_addr ("127.0.0.1");
8597 res
= Fcons (conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
8598 sizeof (struct sockaddr
)),
8611 network_interface_list (void)
8613 return network_interface_get_info (Qnil
);
8617 network_interface_info (Lisp_Object ifname
)
8619 return network_interface_get_info (ifname
);
8623 /* The Windows CRT functions are "optimized for speed", so they don't
8624 check for timezone and DST changes if they were last called less
8625 than 1 minute ago (see http://support.microsoft.com/kb/821231). So
8626 all Emacs features that repeatedly call time functions (e.g.,
8627 display-time) are in real danger of missing timezone and DST
8628 changes. Calling tzset before each localtime call fixes that. */
8630 sys_localtime (const time_t *t
)
8633 return localtime (t
);
8638 /* Try loading LIBRARY_ID from the file(s) specified in
8639 Vdynamic_library_alist. If the library is loaded successfully,
8640 return the handle of the DLL, and record the filename in the
8641 property :loaded-from of LIBRARY_ID. If the library could not be
8642 found, or when it was already loaded (because the handle is not
8643 recorded anywhere, and so is lost after use), return NULL.
8645 We could also save the handle in :loaded-from, but currently
8646 there's no use case for it. */
8648 w32_delayed_load (Lisp_Object library_id
)
8650 HMODULE dll_handle
= NULL
;
8652 CHECK_SYMBOL (library_id
);
8654 if (CONSP (Vdynamic_library_alist
)
8655 && NILP (Fassq (library_id
, Vlibrary_cache
)))
8657 Lisp_Object found
= Qnil
;
8658 Lisp_Object dlls
= Fassq (library_id
, Vdynamic_library_alist
);
8661 for (dlls
= XCDR (dlls
); CONSP (dlls
); dlls
= XCDR (dlls
))
8663 Lisp_Object dll
= XCAR (dlls
);
8664 char name
[MAX_UTF8_PATH
];
8668 dll
= ENCODE_FILE (dll
);
8669 if (w32_unicode_filenames
)
8671 wchar_t name_w
[MAX_PATH
];
8673 filename_to_utf16 (SSDATA (dll
), name_w
);
8674 dll_handle
= LoadLibraryW (name_w
);
8677 res
= GetModuleFileNameW (dll_handle
, name_w
,
8680 filename_from_utf16 (name_w
, name
);
8685 char name_a
[MAX_PATH
];
8687 filename_to_ansi (SSDATA (dll
), name_a
);
8688 dll_handle
= LoadLibraryA (name_a
);
8691 res
= GetModuleFileNameA (dll_handle
, name_a
,
8694 filename_from_ansi (name_a
, name
);
8699 ptrdiff_t len
= strlen (name
);
8702 /* Possibly truncated */
8703 ? make_specified_string (name
, -1, len
, 1)
8709 Fput (library_id
, QCloaded_from
, found
);
8717 check_windows_init_file (void)
8719 /* A common indication that Emacs is not installed properly is when
8720 it cannot find the Windows installation file. If this file does
8721 not exist in the expected place, tell the user. */
8723 if (!noninteractive
&& !inhibit_window_system
8724 /* Vload_path is not yet initialized when we are loading
8726 && NILP (Vpurify_flag
))
8728 Lisp_Object init_file
;
8731 /* Implementation note: this function runs early during Emacs
8732 startup, before startup.el is run. So Vload_path is still in
8733 its initial unibyte form, but it holds UTF-8 encoded file
8734 names, since init_callproc was already called. So we do not
8735 need to ENCODE_FILE here, but we do need to convert the file
8736 names from UTF-8 to ANSI. */
8737 init_file
= build_string ("term/w32-win");
8738 fd
= openp (Vload_path
, init_file
, Fget_load_suffixes (), NULL
, Qnil
, 0);
8741 Lisp_Object load_path_print
= Fprin1_to_string (Vload_path
, Qnil
);
8742 char *init_file_name
= SDATA (init_file
);
8743 char *load_path
= SDATA (load_path_print
);
8744 char *buffer
= alloca (1024
8745 + strlen (init_file_name
)
8746 + strlen (load_path
));
8751 "The Emacs Windows initialization file \"%s.el\" "
8752 "could not be found in your Emacs installation. "
8753 "Emacs checked the following directories for this file:\n"
8755 "When Emacs cannot find this file, it usually means that it "
8756 "was not installed properly, or its distribution file was "
8757 "not unpacked properly.\nSee the README.W32 file in the "
8758 "top-level Emacs directory for more information.",
8759 init_file_name
, load_path
);
8760 needed
= pMultiByteToWideChar (CP_UTF8
, MB_ERR_INVALID_CHARS
, buffer
,
8764 wchar_t *msg_w
= alloca ((needed
+ 1) * sizeof (wchar_t));
8766 pMultiByteToWideChar (CP_UTF8
, MB_ERR_INVALID_CHARS
, buffer
, -1,
8768 needed
= pWideCharToMultiByte (CP_ACP
, 0, msg_w
, -1,
8769 NULL
, 0, NULL
, NULL
);
8772 char *msg_a
= alloca (needed
+ 1);
8774 pWideCharToMultiByte (CP_ACP
, 0, msg_w
, -1, msg_a
, needed
,
8781 "Emacs Abort Dialog",
8782 MB_OK
| MB_ICONEXCLAMATION
| MB_TASKMODAL
);
8783 /* Use the low-level system abort. */
8794 term_ntproc (int ignored
)
8800 /* shutdown the socket interface if necessary */
8807 init_ntproc (int dumping
)
8809 sigset_t initial_mask
= 0;
8811 /* Initialize the socket interface now if available and requested by
8812 the user by defining PRELOAD_WINSOCK; otherwise loading will be
8813 delayed until open-network-stream is called (w32-has-winsock can
8814 also be used to dynamically load or reload winsock).
8816 Conveniently, init_environment is called before us, so
8817 PRELOAD_WINSOCK can be set in the registry. */
8819 /* Always initialize this correctly. */
8822 if (getenv ("PRELOAD_WINSOCK") != NULL
)
8823 init_winsock (TRUE
);
8825 /* Initial preparation for subprocess support: replace our standard
8826 handles with non-inheritable versions. */
8829 HANDLE stdin_save
= INVALID_HANDLE_VALUE
;
8830 HANDLE stdout_save
= INVALID_HANDLE_VALUE
;
8831 HANDLE stderr_save
= INVALID_HANDLE_VALUE
;
8833 parent
= GetCurrentProcess ();
8835 /* ignore errors when duplicating and closing; typically the
8836 handles will be invalid when running as a gui program. */
8837 DuplicateHandle (parent
,
8838 GetStdHandle (STD_INPUT_HANDLE
),
8843 DUPLICATE_SAME_ACCESS
);
8845 DuplicateHandle (parent
,
8846 GetStdHandle (STD_OUTPUT_HANDLE
),
8851 DUPLICATE_SAME_ACCESS
);
8853 DuplicateHandle (parent
,
8854 GetStdHandle (STD_ERROR_HANDLE
),
8859 DUPLICATE_SAME_ACCESS
);
8865 if (stdin_save
!= INVALID_HANDLE_VALUE
)
8866 _open_osfhandle ((intptr_t) stdin_save
, O_TEXT
);
8868 _open ("nul", O_TEXT
| O_NOINHERIT
| O_RDONLY
);
8871 if (stdout_save
!= INVALID_HANDLE_VALUE
)
8872 _open_osfhandle ((intptr_t) stdout_save
, O_TEXT
);
8874 _open ("nul", O_TEXT
| O_NOINHERIT
| O_WRONLY
);
8877 if (stderr_save
!= INVALID_HANDLE_VALUE
)
8878 _open_osfhandle ((intptr_t) stderr_save
, O_TEXT
);
8880 _open ("nul", O_TEXT
| O_NOINHERIT
| O_WRONLY
);
8884 /* unfortunately, atexit depends on implementation of malloc */
8885 /* atexit (term_ntproc); */
8888 /* Make sure we start with all signals unblocked. */
8889 sigprocmask (SIG_SETMASK
, &initial_mask
, NULL
);
8890 signal (SIGABRT
, term_ntproc
);
8894 /* determine which drives are fixed, for GetCachedVolumeInformation */
8896 /* GetDriveType must have trailing backslash. */
8897 char drive
[] = "A:\\";
8899 /* Loop over all possible drive letters */
8900 while (*drive
<= 'Z')
8902 /* Record if this drive letter refers to a fixed drive. */
8903 fixed_drives
[DRIVE_INDEX (*drive
)] =
8904 (GetDriveType (drive
) == DRIVE_FIXED
);
8909 /* Reset the volume info cache. */
8910 volume_cache
= NULL
;
8915 shutdown_handler ensures that buffers' autosave files are
8916 up to date when the user logs off, or the system shuts down.
8919 shutdown_handler (DWORD type
)
8921 /* Ctrl-C and Ctrl-Break are already suppressed, so don't handle them. */
8922 if (type
== CTRL_CLOSE_EVENT
/* User closes console window. */
8923 || type
== CTRL_LOGOFF_EVENT
/* User logs off. */
8924 || type
== CTRL_SHUTDOWN_EVENT
) /* User shutsdown. */
8926 /* Shut down cleanly, making sure autosave files are up to date. */
8927 shut_down_emacs (0, Qnil
);
8930 /* Allow other handlers to handle this signal. */
8934 /* On Windows 9X, load UNICOWS.DLL and return its handle, or die. On
8935 NT, return a handle to GDI32.DLL. */
8937 maybe_load_unicows_dll (void)
8939 if (os_subtype
== OS_9X
)
8941 HANDLE ret
= LoadLibrary ("Unicows.dll");
8944 /* These two functions are present on Windows 9X as stubs
8945 that always fail. We need the real implementations from
8946 UNICOWS.DLL, so we must call these functions through
8947 pointers, and assign the correct addresses to these
8948 pointers at program startup (see emacs.c, which calls
8949 this function early on). */
8950 pMultiByteToWideChar
= GetProcAddress (ret
, "MultiByteToWideChar");
8951 pWideCharToMultiByte
= GetProcAddress (ret
, "WideCharToMultiByte");
8958 button
= MessageBox (NULL
,
8959 "Emacs cannot load the UNICOWS.DLL library.\n"
8960 "This library is essential for using Emacs\n"
8961 "on this system. You need to install it.\n\n"
8962 "Emacs will exit when you click OK.",
8963 "Emacs cannot load UNICOWS.DLL",
8964 MB_ICONERROR
| MB_TASKMODAL
8965 | MB_SETFOREGROUND
| MB_OK
);
8976 /* On NT family of Windows, these two functions are always
8977 linked in, so we just assign their addresses to the 2
8978 pointers; no need for the LoadLibrary dance. */
8979 pMultiByteToWideChar
= MultiByteToWideChar
;
8980 pWideCharToMultiByte
= WideCharToMultiByte
;
8981 return LoadLibrary ("Gdi32.dll");
8986 globals_of_w32 is used to initialize those global variables that
8987 must always be initialized on startup even when the global variable
8988 initialized is non zero (see the function main in emacs.c).
8991 globals_of_w32 (void)
8993 HMODULE kernel32
= GetModuleHandle ("kernel32.dll");
8995 get_process_times_fn
= (GetProcessTimes_Proc
)
8996 GetProcAddress (kernel32
, "GetProcessTimes");
8998 DEFSYM (QCloaded_from
, ":loaded-from");
9000 g_b_init_is_windows_9x
= 0;
9001 g_b_init_open_process_token
= 0;
9002 g_b_init_get_token_information
= 0;
9003 g_b_init_lookup_account_sid
= 0;
9004 g_b_init_get_sid_sub_authority
= 0;
9005 g_b_init_get_sid_sub_authority_count
= 0;
9006 g_b_init_get_security_info
= 0;
9007 g_b_init_get_file_security_w
= 0;
9008 g_b_init_get_file_security_a
= 0;
9009 g_b_init_get_security_descriptor_owner
= 0;
9010 g_b_init_get_security_descriptor_group
= 0;
9011 g_b_init_is_valid_sid
= 0;
9012 g_b_init_create_toolhelp32_snapshot
= 0;
9013 g_b_init_process32_first
= 0;
9014 g_b_init_process32_next
= 0;
9015 g_b_init_open_thread_token
= 0;
9016 g_b_init_impersonate_self
= 0;
9017 g_b_init_revert_to_self
= 0;
9018 g_b_init_get_process_memory_info
= 0;
9019 g_b_init_get_process_working_set_size
= 0;
9020 g_b_init_global_memory_status
= 0;
9021 g_b_init_global_memory_status_ex
= 0;
9022 g_b_init_equal_sid
= 0;
9023 g_b_init_copy_sid
= 0;
9024 g_b_init_get_length_sid
= 0;
9025 g_b_init_get_native_system_info
= 0;
9026 g_b_init_get_system_times
= 0;
9027 g_b_init_create_symbolic_link_w
= 0;
9028 g_b_init_create_symbolic_link_a
= 0;
9029 g_b_init_get_security_descriptor_dacl
= 0;
9030 g_b_init_convert_sd_to_sddl
= 0;
9031 g_b_init_convert_sddl_to_sd
= 0;
9032 g_b_init_is_valid_security_descriptor
= 0;
9033 g_b_init_set_file_security_w
= 0;
9034 g_b_init_set_file_security_a
= 0;
9035 g_b_init_set_named_security_info_w
= 0;
9036 g_b_init_set_named_security_info_a
= 0;
9037 g_b_init_get_adapters_info
= 0;
9038 num_of_processors
= 0;
9039 /* The following sets a handler for shutdown notifications for
9040 console apps. This actually applies to Emacs in both console and
9041 GUI modes, since we had to fool windows into thinking emacs is a
9042 console application to get console mode to work. */
9043 SetConsoleCtrlHandler (shutdown_handler
, TRUE
);
9045 /* "None" is the default group name on standalone workstations. */
9046 strcpy (dflt_group_name
, "None");
9048 /* Reset, in case it has some value inherited from dump time. */
9049 w32_stat_get_owner_group
= 0;
9051 /* If w32_unicode_filenames is non-zero, we will be using Unicode
9052 (a.k.a. "wide") APIs to invoke functions that accept file
9054 if (is_windows_9x ())
9055 w32_unicode_filenames
= 0;
9057 w32_unicode_filenames
= 1;
9060 /* For make-serial-process */
9062 serial_open (Lisp_Object port_obj
)
9064 char *port
= SSDATA (port_obj
);
9069 hnd
= CreateFile (port
, GENERIC_READ
| GENERIC_WRITE
, 0, 0,
9070 OPEN_EXISTING
, FILE_FLAG_OVERLAPPED
, 0);
9071 if (hnd
== INVALID_HANDLE_VALUE
)
9072 error ("Could not open %s", port
);
9073 fd
= (int) _open_osfhandle ((intptr_t) hnd
, 0);
9075 error ("Could not open %s", port
);
9079 error ("Could not create child process");
9081 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
9082 fd_info
[ fd
].hnd
= hnd
;
9083 fd_info
[ fd
].flags
|=
9084 FILE_READ
| FILE_WRITE
| FILE_BINARY
| FILE_SERIAL
;
9085 if (fd_info
[ fd
].cp
!= NULL
)
9087 error ("fd_info[fd = %d] is already in use", fd
);
9089 fd_info
[ fd
].cp
= cp
;
9090 cp
->ovl_read
.hEvent
= CreateEvent (NULL
, TRUE
, FALSE
, NULL
);
9091 if (cp
->ovl_read
.hEvent
== NULL
)
9092 error ("Could not create read event");
9093 cp
->ovl_write
.hEvent
= CreateEvent (NULL
, TRUE
, FALSE
, NULL
);
9094 if (cp
->ovl_write
.hEvent
== NULL
)
9095 error ("Could not create write event");
9100 /* For serial-process-configure */
9102 serial_configure (struct Lisp_Process
*p
, Lisp_Object contact
)
9104 Lisp_Object childp2
= Qnil
;
9105 Lisp_Object tem
= Qnil
;
9109 char summary
[4] = "???"; /* This usually becomes "8N1". */
9111 if ((fd_info
[ p
->outfd
].flags
& FILE_SERIAL
) == 0)
9112 error ("Not a serial process");
9113 hnd
= fd_info
[ p
->outfd
].hnd
;
9115 childp2
= Fcopy_sequence (p
->childp
);
9117 /* Initialize timeouts for blocking read and blocking write. */
9118 if (!GetCommTimeouts (hnd
, &ct
))
9119 error ("GetCommTimeouts() failed");
9120 ct
.ReadIntervalTimeout
= 0;
9121 ct
.ReadTotalTimeoutMultiplier
= 0;
9122 ct
.ReadTotalTimeoutConstant
= 0;
9123 ct
.WriteTotalTimeoutMultiplier
= 0;
9124 ct
.WriteTotalTimeoutConstant
= 0;
9125 if (!SetCommTimeouts (hnd
, &ct
))
9126 error ("SetCommTimeouts() failed");
9127 /* Read port attributes and prepare default configuration. */
9128 memset (&dcb
, 0, sizeof (dcb
));
9129 dcb
.DCBlength
= sizeof (DCB
);
9130 if (!GetCommState (hnd
, &dcb
))
9131 error ("GetCommState() failed");
9134 dcb
.fAbortOnError
= FALSE
;
9135 /* dcb.XonLim and dcb.XoffLim are set by GetCommState() */
9140 /* Configure speed. */
9141 if (!NILP (Fplist_member (contact
, QCspeed
)))
9142 tem
= Fplist_get (contact
, QCspeed
);
9144 tem
= Fplist_get (p
->childp
, QCspeed
);
9146 dcb
.BaudRate
= XINT (tem
);
9147 childp2
= Fplist_put (childp2
, QCspeed
, tem
);
9149 /* Configure bytesize. */
9150 if (!NILP (Fplist_member (contact
, QCbytesize
)))
9151 tem
= Fplist_get (contact
, QCbytesize
);
9153 tem
= Fplist_get (p
->childp
, QCbytesize
);
9155 tem
= make_number (8);
9157 if (XINT (tem
) != 7 && XINT (tem
) != 8)
9158 error (":bytesize must be nil (8), 7, or 8");
9159 dcb
.ByteSize
= XINT (tem
);
9160 summary
[0] = XINT (tem
) + '0';
9161 childp2
= Fplist_put (childp2
, QCbytesize
, tem
);
9163 /* Configure parity. */
9164 if (!NILP (Fplist_member (contact
, QCparity
)))
9165 tem
= Fplist_get (contact
, QCparity
);
9167 tem
= Fplist_get (p
->childp
, QCparity
);
9168 if (!NILP (tem
) && !EQ (tem
, Qeven
) && !EQ (tem
, Qodd
))
9169 error (":parity must be nil (no parity), `even', or `odd'");
9170 dcb
.fParity
= FALSE
;
9171 dcb
.Parity
= NOPARITY
;
9172 dcb
.fErrorChar
= FALSE
;
9177 else if (EQ (tem
, Qeven
))
9181 dcb
.Parity
= EVENPARITY
;
9182 dcb
.fErrorChar
= TRUE
;
9184 else if (EQ (tem
, Qodd
))
9188 dcb
.Parity
= ODDPARITY
;
9189 dcb
.fErrorChar
= TRUE
;
9191 childp2
= Fplist_put (childp2
, QCparity
, tem
);
9193 /* Configure stopbits. */
9194 if (!NILP (Fplist_member (contact
, QCstopbits
)))
9195 tem
= Fplist_get (contact
, QCstopbits
);
9197 tem
= Fplist_get (p
->childp
, QCstopbits
);
9199 tem
= make_number (1);
9201 if (XINT (tem
) != 1 && XINT (tem
) != 2)
9202 error (":stopbits must be nil (1 stopbit), 1, or 2");
9203 summary
[2] = XINT (tem
) + '0';
9204 if (XINT (tem
) == 1)
9205 dcb
.StopBits
= ONESTOPBIT
;
9206 else if (XINT (tem
) == 2)
9207 dcb
.StopBits
= TWOSTOPBITS
;
9208 childp2
= Fplist_put (childp2
, QCstopbits
, tem
);
9210 /* Configure flowcontrol. */
9211 if (!NILP (Fplist_member (contact
, QCflowcontrol
)))
9212 tem
= Fplist_get (contact
, QCflowcontrol
);
9214 tem
= Fplist_get (p
->childp
, QCflowcontrol
);
9215 if (!NILP (tem
) && !EQ (tem
, Qhw
) && !EQ (tem
, Qsw
))
9216 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
9217 dcb
.fOutxCtsFlow
= FALSE
;
9218 dcb
.fOutxDsrFlow
= FALSE
;
9219 dcb
.fDtrControl
= DTR_CONTROL_DISABLE
;
9220 dcb
.fDsrSensitivity
= FALSE
;
9221 dcb
.fTXContinueOnXoff
= FALSE
;
9224 dcb
.fRtsControl
= RTS_CONTROL_DISABLE
;
9225 dcb
.XonChar
= 17; /* Control-Q */
9226 dcb
.XoffChar
= 19; /* Control-S */
9229 /* Already configured. */
9231 else if (EQ (tem
, Qhw
))
9233 dcb
.fRtsControl
= RTS_CONTROL_HANDSHAKE
;
9234 dcb
.fOutxCtsFlow
= TRUE
;
9236 else if (EQ (tem
, Qsw
))
9241 childp2
= Fplist_put (childp2
, QCflowcontrol
, tem
);
9243 /* Activate configuration. */
9244 if (!SetCommState (hnd
, &dcb
))
9245 error ("SetCommState() failed");
9247 childp2
= Fplist_put (childp2
, QCsummary
, build_string (summary
));
9248 pset_childp (p
, childp2
);
9254 emacs_gnutls_pull (gnutls_transport_ptr_t p
, void* buf
, size_t sz
)
9258 struct timespec timeout
;
9259 struct Lisp_Process
*process
= (struct Lisp_Process
*)p
;
9260 int fd
= process
->infd
;
9262 n
= sys_read (fd
, (char*)buf
, sz
);
9269 /* Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
9270 if (err
== EWOULDBLOCK
)
9273 emacs_gnutls_transport_set_errno (process
->gnutls_state
, err
);
9279 emacs_gnutls_push (gnutls_transport_ptr_t p
, const void* buf
, size_t sz
)
9281 struct Lisp_Process
*process
= (struct Lisp_Process
*)p
;
9282 int fd
= process
->outfd
;
9283 ssize_t n
= sys_write (fd
, buf
, sz
);
9285 /* 0 or more bytes written means everything went fine. */
9289 /* Negative bytes written means we got an error in errno.
9290 Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
9291 emacs_gnutls_transport_set_errno (process
->gnutls_state
,
9292 errno
== EWOULDBLOCK
? EAGAIN
: errno
);
9296 #endif /* HAVE_GNUTLS */