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 defines these in its _mingw.h. */
76 #ifndef _ANONYMOUS_UNION
77 # define _ANONYMOUS_UNION
79 #ifndef _ANONYMOUS_STRUCT
80 # define _ANONYMOUS_STRUCT
83 /* Some versions of compiler define MEMORYSTATUSEX, some don't, so we
84 use a different name to avoid compilation problems. */
85 typedef struct _MEMORY_STATUS_EX
{
88 DWORDLONG ullTotalPhys
;
89 DWORDLONG ullAvailPhys
;
90 DWORDLONG ullTotalPageFile
;
91 DWORDLONG ullAvailPageFile
;
92 DWORDLONG ullTotalVirtual
;
93 DWORDLONG ullAvailVirtual
;
94 DWORDLONG ullAvailExtendedVirtual
;
95 } MEMORY_STATUS_EX
,*LPMEMORY_STATUS_EX
;
97 /* These are here so that GDB would know about these data types. This
98 allows to attach GDB to Emacs when a fatal exception is triggered
99 and Windows pops up the "application needs to be closed" dialog.
100 At that point, _gnu_exception_handler, the top-level exception
101 handler installed by the MinGW startup code, is somewhere on the
102 call-stack of the main thread, so going to that call frame and
103 looking at the argument to _gnu_exception_handler, which is a
104 PEXCEPTION_POINTERS pointer, can reveal the exception code
105 (excptr->ExceptionRecord->ExceptionCode) and the address where the
106 exception happened (excptr->ExceptionRecord->ExceptionAddress), as
107 well as some additional information specific to the exception. */
108 PEXCEPTION_POINTERS excptr
;
109 PEXCEPTION_RECORD excprec
;
115 #include <tlhelp32.h>
120 #if _WIN32_WINNT < 0x0500
121 #if !defined (__MINGW32__) || __W32API_MAJOR_VERSION < 3 || (__W32API_MAJOR_VERSION == 3 && __W32API_MINOR_VERSION < 15)
122 /* This either is not in psapi.h or guarded by higher value of
123 _WIN32_WINNT than what we use. w32api supplied with MinGW 3.15
124 defines it in psapi.h */
125 typedef struct _PROCESS_MEMORY_COUNTERS_EX
{
127 DWORD PageFaultCount
;
128 SIZE_T PeakWorkingSetSize
;
129 SIZE_T WorkingSetSize
;
130 SIZE_T QuotaPeakPagedPoolUsage
;
131 SIZE_T QuotaPagedPoolUsage
;
132 SIZE_T QuotaPeakNonPagedPoolUsage
;
133 SIZE_T QuotaNonPagedPoolUsage
;
134 SIZE_T PagefileUsage
;
135 SIZE_T PeakPagefileUsage
;
137 } PROCESS_MEMORY_COUNTERS_EX
,*PPROCESS_MEMORY_COUNTERS_EX
;
141 #include <winioctl.h>
148 /* This is not in MinGW's sddl.h (but they are in MSVC headers), so we
149 define them by hand if not already defined. */
150 #ifndef SDDL_REVISION_1
151 #define SDDL_REVISION_1 1
152 #endif /* SDDL_REVISION_1 */
154 #if defined(_MSC_VER) || defined(MINGW_W64)
155 /* MSVC and MinGW64 don't provide the definition of
156 REPARSE_DATA_BUFFER and the associated macros, except on ntifs.h,
157 which cannot be included because it triggers conflicts with other
158 Windows API headers. So we define it here by hand. */
160 typedef struct _REPARSE_DATA_BUFFER
{
162 USHORT ReparseDataLength
;
166 USHORT SubstituteNameOffset
;
167 USHORT SubstituteNameLength
;
168 USHORT PrintNameOffset
;
169 USHORT PrintNameLength
;
172 } SymbolicLinkReparseBuffer
;
174 USHORT SubstituteNameOffset
;
175 USHORT SubstituteNameLength
;
176 USHORT PrintNameOffset
;
177 USHORT PrintNameLength
;
179 } MountPointReparseBuffer
;
182 } GenericReparseBuffer
;
184 } REPARSE_DATA_BUFFER
, *PREPARSE_DATA_BUFFER
;
186 #ifndef FILE_DEVICE_FILE_SYSTEM
187 #define FILE_DEVICE_FILE_SYSTEM 9
189 #ifndef METHOD_BUFFERED
190 #define METHOD_BUFFERED 0
192 #ifndef FILE_ANY_ACCESS
193 #define FILE_ANY_ACCESS 0x00000000
196 #define CTL_CODE(t,f,m,a) (((t)<<16)|((a)<<14)|((f)<<2)|(m))
198 /* MinGW64 defines FSCTL_GET_REPARSE_POINT on winioctl.h. */
199 #ifndef FSCTL_GET_REPARSE_POINT
200 #define FSCTL_GET_REPARSE_POINT \
201 CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 42, METHOD_BUFFERED, FILE_ANY_ACCESS)
205 /* TCP connection support. */
206 #include <sys/socket.h>
225 #include <iphlpapi.h> /* should be after winsock2.h */
229 #include "w32common.h"
231 #include "w32select.h"
233 #include "dispextern.h" /* for xstrcasecmp */
234 #include "coding.h" /* for Vlocale_coding_system */
236 #include "careadlinkat.h"
237 #include "allocator.h"
239 /* For serial_configure and serial_open. */
242 typedef HRESULT (WINAPI
* ShGetFolderPath_fn
)
243 (IN HWND
, IN
int, IN HANDLE
, IN DWORD
, OUT
char *);
245 Lisp_Object QCloaded_from
;
247 void globals_of_w32 (void);
248 static DWORD
get_rid (PSID
);
249 static int is_symlink (const char *);
250 static char * chase_symlinks (const char *);
251 static int enable_privilege (LPCTSTR
, BOOL
, TOKEN_PRIVILEGES
*);
252 static int restore_privilege (TOKEN_PRIVILEGES
*);
253 static BOOL WINAPI
revert_to_self (void);
255 static int sys_access (const char *, int);
256 extern void *e_malloc (size_t);
257 extern int sys_select (int, SELECT_TYPE
*, SELECT_TYPE
*, SELECT_TYPE
*,
258 struct timespec
*, void *);
259 extern int sys_dup (int);
264 /* Initialization states.
266 WARNING: If you add any more such variables for additional APIs,
267 you MUST add initialization for them to globals_of_w32
268 below. This is because these variables might get set
269 to non-NULL values during dumping, but the dumped Emacs
270 cannot reuse those values, because it could be run on a
271 different version of the OS, where API addresses are
273 static BOOL g_b_init_is_windows_9x
;
274 static BOOL g_b_init_open_process_token
;
275 static BOOL g_b_init_get_token_information
;
276 static BOOL g_b_init_lookup_account_sid
;
277 static BOOL g_b_init_get_sid_sub_authority
;
278 static BOOL g_b_init_get_sid_sub_authority_count
;
279 static BOOL g_b_init_get_security_info
;
280 static BOOL g_b_init_get_file_security_w
;
281 static BOOL g_b_init_get_file_security_a
;
282 static BOOL g_b_init_get_security_descriptor_owner
;
283 static BOOL g_b_init_get_security_descriptor_group
;
284 static BOOL g_b_init_is_valid_sid
;
285 static BOOL g_b_init_create_toolhelp32_snapshot
;
286 static BOOL g_b_init_process32_first
;
287 static BOOL g_b_init_process32_next
;
288 static BOOL g_b_init_open_thread_token
;
289 static BOOL g_b_init_impersonate_self
;
290 static BOOL g_b_init_revert_to_self
;
291 static BOOL g_b_init_get_process_memory_info
;
292 static BOOL g_b_init_get_process_working_set_size
;
293 static BOOL g_b_init_global_memory_status
;
294 static BOOL g_b_init_global_memory_status_ex
;
295 static BOOL g_b_init_get_length_sid
;
296 static BOOL g_b_init_equal_sid
;
297 static BOOL g_b_init_copy_sid
;
298 static BOOL g_b_init_get_native_system_info
;
299 static BOOL g_b_init_get_system_times
;
300 static BOOL g_b_init_create_symbolic_link_w
;
301 static BOOL g_b_init_create_symbolic_link_a
;
302 static BOOL g_b_init_get_security_descriptor_dacl
;
303 static BOOL g_b_init_convert_sd_to_sddl
;
304 static BOOL g_b_init_convert_sddl_to_sd
;
305 static BOOL g_b_init_is_valid_security_descriptor
;
306 static BOOL g_b_init_set_file_security_w
;
307 static BOOL g_b_init_set_file_security_a
;
308 static BOOL g_b_init_set_named_security_info_w
;
309 static BOOL g_b_init_set_named_security_info_a
;
310 static BOOL g_b_init_get_adapters_info
;
312 BOOL g_b_init_compare_string_w
;
315 BEGIN: Wrapper functions around OpenProcessToken
316 and other functions in advapi32.dll that are only
317 supported in Windows NT / 2k / XP
319 /* ** Function pointer typedefs ** */
320 typedef BOOL (WINAPI
* OpenProcessToken_Proc
) (
321 HANDLE ProcessHandle
,
323 PHANDLE TokenHandle
);
324 typedef BOOL (WINAPI
* GetTokenInformation_Proc
) (
326 TOKEN_INFORMATION_CLASS TokenInformationClass
,
327 LPVOID TokenInformation
,
328 DWORD TokenInformationLength
,
329 PDWORD ReturnLength
);
330 typedef BOOL (WINAPI
* GetProcessTimes_Proc
) (
331 HANDLE process_handle
,
332 LPFILETIME creation_time
,
333 LPFILETIME exit_time
,
334 LPFILETIME kernel_time
,
335 LPFILETIME user_time
);
337 GetProcessTimes_Proc get_process_times_fn
= NULL
;
340 const char * const LookupAccountSid_Name
= "LookupAccountSidW";
342 const char * const LookupAccountSid_Name
= "LookupAccountSidA";
344 typedef BOOL (WINAPI
* LookupAccountSid_Proc
) (
345 LPCTSTR lpSystemName
,
350 LPDWORD cbDomainName
,
351 PSID_NAME_USE peUse
);
352 typedef PDWORD (WINAPI
* GetSidSubAuthority_Proc
) (
355 typedef PUCHAR (WINAPI
* GetSidSubAuthorityCount_Proc
) (
357 typedef DWORD (WINAPI
* GetSecurityInfo_Proc
) (
359 SE_OBJECT_TYPE ObjectType
,
360 SECURITY_INFORMATION SecurityInfo
,
365 PSECURITY_DESCRIPTOR
*ppSecurityDescriptor
);
366 typedef BOOL (WINAPI
* GetFileSecurityW_Proc
) (
368 SECURITY_INFORMATION RequestedInformation
,
369 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
371 LPDWORD lpnLengthNeeded
);
372 typedef BOOL (WINAPI
* GetFileSecurityA_Proc
) (
374 SECURITY_INFORMATION RequestedInformation
,
375 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
377 LPDWORD lpnLengthNeeded
);
378 typedef BOOL (WINAPI
*SetFileSecurityW_Proc
) (
380 SECURITY_INFORMATION SecurityInformation
,
381 PSECURITY_DESCRIPTOR pSecurityDescriptor
);
382 typedef BOOL (WINAPI
*SetFileSecurityA_Proc
) (
384 SECURITY_INFORMATION SecurityInformation
,
385 PSECURITY_DESCRIPTOR pSecurityDescriptor
);
386 typedef DWORD (WINAPI
*SetNamedSecurityInfoW_Proc
) (
387 LPCWSTR lpObjectName
,
388 SE_OBJECT_TYPE ObjectType
,
389 SECURITY_INFORMATION SecurityInformation
,
394 typedef DWORD (WINAPI
*SetNamedSecurityInfoA_Proc
) (
396 SE_OBJECT_TYPE ObjectType
,
397 SECURITY_INFORMATION SecurityInformation
,
402 typedef BOOL (WINAPI
* GetSecurityDescriptorOwner_Proc
) (
403 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
405 LPBOOL lpbOwnerDefaulted
);
406 typedef BOOL (WINAPI
* GetSecurityDescriptorGroup_Proc
) (
407 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
409 LPBOOL lpbGroupDefaulted
);
410 typedef BOOL (WINAPI
*GetSecurityDescriptorDacl_Proc
) (
411 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
412 LPBOOL lpbDaclPresent
,
414 LPBOOL lpbDaclDefaulted
);
415 typedef BOOL (WINAPI
* IsValidSid_Proc
) (
417 typedef HANDLE (WINAPI
* CreateToolhelp32Snapshot_Proc
) (
419 DWORD th32ProcessID
);
420 typedef BOOL (WINAPI
* Process32First_Proc
) (
422 LPPROCESSENTRY32 lppe
);
423 typedef BOOL (WINAPI
* Process32Next_Proc
) (
425 LPPROCESSENTRY32 lppe
);
426 typedef BOOL (WINAPI
* OpenThreadToken_Proc
) (
430 PHANDLE TokenHandle
);
431 typedef BOOL (WINAPI
* ImpersonateSelf_Proc
) (
432 SECURITY_IMPERSONATION_LEVEL ImpersonationLevel
);
433 typedef BOOL (WINAPI
* RevertToSelf_Proc
) (void);
434 typedef BOOL (WINAPI
* GetProcessMemoryInfo_Proc
) (
436 PPROCESS_MEMORY_COUNTERS ppsmemCounters
,
438 typedef BOOL (WINAPI
* GetProcessWorkingSetSize_Proc
) (
440 PSIZE_T lpMinimumWorkingSetSize
,
441 PSIZE_T lpMaximumWorkingSetSize
);
442 typedef BOOL (WINAPI
* GlobalMemoryStatus_Proc
) (
443 LPMEMORYSTATUS lpBuffer
);
444 typedef BOOL (WINAPI
* GlobalMemoryStatusEx_Proc
) (
445 LPMEMORY_STATUS_EX lpBuffer
);
446 typedef BOOL (WINAPI
* CopySid_Proc
) (
447 DWORD nDestinationSidLength
,
448 PSID pDestinationSid
,
450 typedef BOOL (WINAPI
* EqualSid_Proc
) (
453 typedef DWORD (WINAPI
* GetLengthSid_Proc
) (
455 typedef void (WINAPI
* GetNativeSystemInfo_Proc
) (
456 LPSYSTEM_INFO lpSystemInfo
);
457 typedef BOOL (WINAPI
* GetSystemTimes_Proc
) (
458 LPFILETIME lpIdleTime
,
459 LPFILETIME lpKernelTime
,
460 LPFILETIME lpUserTime
);
461 typedef BOOLEAN (WINAPI
*CreateSymbolicLinkW_Proc
) (
462 LPCWSTR lpSymlinkFileName
,
463 LPCWSTR lpTargetFileName
,
465 typedef BOOLEAN (WINAPI
*CreateSymbolicLinkA_Proc
) (
466 LPCSTR lpSymlinkFileName
,
467 LPCSTR lpTargetFileName
,
469 typedef BOOL (WINAPI
*ConvertStringSecurityDescriptorToSecurityDescriptor_Proc
) (
470 LPCTSTR StringSecurityDescriptor
,
471 DWORD StringSDRevision
,
472 PSECURITY_DESCRIPTOR
*SecurityDescriptor
,
473 PULONG SecurityDescriptorSize
);
474 typedef BOOL (WINAPI
*ConvertSecurityDescriptorToStringSecurityDescriptor_Proc
) (
475 PSECURITY_DESCRIPTOR SecurityDescriptor
,
476 DWORD RequestedStringSDRevision
,
477 SECURITY_INFORMATION SecurityInformation
,
478 LPTSTR
*StringSecurityDescriptor
,
479 PULONG StringSecurityDescriptorLen
);
480 typedef BOOL (WINAPI
*IsValidSecurityDescriptor_Proc
) (PSECURITY_DESCRIPTOR
);
481 typedef DWORD (WINAPI
*GetAdaptersInfo_Proc
) (
482 PIP_ADAPTER_INFO pAdapterInfo
,
485 int (WINAPI
*pMultiByteToWideChar
)(UINT
,DWORD
,LPCSTR
,int,LPWSTR
,int);
486 int (WINAPI
*pWideCharToMultiByte
)(UINT
,DWORD
,LPCWSTR
,int,LPSTR
,int,LPCSTR
,LPBOOL
);
488 /* ** A utility function ** */
492 static BOOL s_b_ret
= 0;
493 OSVERSIONINFO os_ver
;
494 if (g_b_init_is_windows_9x
== 0)
496 g_b_init_is_windows_9x
= 1;
497 ZeroMemory (&os_ver
, sizeof (OSVERSIONINFO
));
498 os_ver
.dwOSVersionInfoSize
= sizeof (OSVERSIONINFO
);
499 if (GetVersionEx (&os_ver
))
501 s_b_ret
= (os_ver
.dwPlatformId
== VER_PLATFORM_WIN32_WINDOWS
);
507 static Lisp_Object
ltime (ULONGLONG
);
509 /* Get total user and system times for get-internal-run-time.
510 Returns a list of integers if the times are provided by the OS
511 (NT derivatives), otherwise it returns the result of current-time. */
513 w32_get_internal_run_time (void)
515 if (get_process_times_fn
)
517 FILETIME create
, exit
, kernel
, user
;
518 HANDLE proc
= GetCurrentProcess ();
519 if ((*get_process_times_fn
) (proc
, &create
, &exit
, &kernel
, &user
))
521 LARGE_INTEGER user_int
, kernel_int
, total
;
522 user_int
.LowPart
= user
.dwLowDateTime
;
523 user_int
.HighPart
= user
.dwHighDateTime
;
524 kernel_int
.LowPart
= kernel
.dwLowDateTime
;
525 kernel_int
.HighPart
= kernel
.dwHighDateTime
;
526 total
.QuadPart
= user_int
.QuadPart
+ kernel_int
.QuadPart
;
527 return ltime (total
.QuadPart
);
531 return Fcurrent_time ();
534 /* ** The wrapper functions ** */
537 open_process_token (HANDLE ProcessHandle
,
541 static OpenProcessToken_Proc s_pfn_Open_Process_Token
= NULL
;
542 HMODULE hm_advapi32
= NULL
;
543 if (is_windows_9x () == TRUE
)
547 if (g_b_init_open_process_token
== 0)
549 g_b_init_open_process_token
= 1;
550 hm_advapi32
= LoadLibrary ("Advapi32.dll");
551 s_pfn_Open_Process_Token
=
552 (OpenProcessToken_Proc
) GetProcAddress (hm_advapi32
, "OpenProcessToken");
554 if (s_pfn_Open_Process_Token
== NULL
)
559 s_pfn_Open_Process_Token (
567 get_token_information (HANDLE TokenHandle
,
568 TOKEN_INFORMATION_CLASS TokenInformationClass
,
569 LPVOID TokenInformation
,
570 DWORD TokenInformationLength
,
573 static GetTokenInformation_Proc s_pfn_Get_Token_Information
= NULL
;
574 HMODULE hm_advapi32
= NULL
;
575 if (is_windows_9x () == TRUE
)
579 if (g_b_init_get_token_information
== 0)
581 g_b_init_get_token_information
= 1;
582 hm_advapi32
= LoadLibrary ("Advapi32.dll");
583 s_pfn_Get_Token_Information
=
584 (GetTokenInformation_Proc
) GetProcAddress (hm_advapi32
, "GetTokenInformation");
586 if (s_pfn_Get_Token_Information
== NULL
)
591 s_pfn_Get_Token_Information (
593 TokenInformationClass
,
595 TokenInformationLength
,
601 lookup_account_sid (LPCTSTR lpSystemName
,
606 LPDWORD cbDomainName
,
609 static LookupAccountSid_Proc s_pfn_Lookup_Account_Sid
= NULL
;
610 HMODULE hm_advapi32
= NULL
;
611 if (is_windows_9x () == TRUE
)
615 if (g_b_init_lookup_account_sid
== 0)
617 g_b_init_lookup_account_sid
= 1;
618 hm_advapi32
= LoadLibrary ("Advapi32.dll");
619 s_pfn_Lookup_Account_Sid
=
620 (LookupAccountSid_Proc
) GetProcAddress (hm_advapi32
, LookupAccountSid_Name
);
622 if (s_pfn_Lookup_Account_Sid
== NULL
)
627 s_pfn_Lookup_Account_Sid (
639 get_sid_sub_authority (PSID pSid
, DWORD n
)
641 static GetSidSubAuthority_Proc s_pfn_Get_Sid_Sub_Authority
= NULL
;
642 static DWORD zero
= 0U;
643 HMODULE hm_advapi32
= NULL
;
644 if (is_windows_9x () == TRUE
)
648 if (g_b_init_get_sid_sub_authority
== 0)
650 g_b_init_get_sid_sub_authority
= 1;
651 hm_advapi32
= LoadLibrary ("Advapi32.dll");
652 s_pfn_Get_Sid_Sub_Authority
=
653 (GetSidSubAuthority_Proc
) GetProcAddress (
654 hm_advapi32
, "GetSidSubAuthority");
656 if (s_pfn_Get_Sid_Sub_Authority
== NULL
)
660 return (s_pfn_Get_Sid_Sub_Authority (pSid
, n
));
664 get_sid_sub_authority_count (PSID pSid
)
666 static GetSidSubAuthorityCount_Proc s_pfn_Get_Sid_Sub_Authority_Count
= NULL
;
667 static UCHAR zero
= 0U;
668 HMODULE hm_advapi32
= NULL
;
669 if (is_windows_9x () == TRUE
)
673 if (g_b_init_get_sid_sub_authority_count
== 0)
675 g_b_init_get_sid_sub_authority_count
= 1;
676 hm_advapi32
= LoadLibrary ("Advapi32.dll");
677 s_pfn_Get_Sid_Sub_Authority_Count
=
678 (GetSidSubAuthorityCount_Proc
) GetProcAddress (
679 hm_advapi32
, "GetSidSubAuthorityCount");
681 if (s_pfn_Get_Sid_Sub_Authority_Count
== NULL
)
685 return (s_pfn_Get_Sid_Sub_Authority_Count (pSid
));
689 get_security_info (HANDLE handle
,
690 SE_OBJECT_TYPE ObjectType
,
691 SECURITY_INFORMATION SecurityInfo
,
696 PSECURITY_DESCRIPTOR
*ppSecurityDescriptor
)
698 static GetSecurityInfo_Proc s_pfn_Get_Security_Info
= NULL
;
699 HMODULE hm_advapi32
= NULL
;
700 if (is_windows_9x () == TRUE
)
704 if (g_b_init_get_security_info
== 0)
706 g_b_init_get_security_info
= 1;
707 hm_advapi32
= LoadLibrary ("Advapi32.dll");
708 s_pfn_Get_Security_Info
=
709 (GetSecurityInfo_Proc
) GetProcAddress (
710 hm_advapi32
, "GetSecurityInfo");
712 if (s_pfn_Get_Security_Info
== NULL
)
716 return (s_pfn_Get_Security_Info (handle
, ObjectType
, SecurityInfo
,
717 ppsidOwner
, ppsidGroup
, ppDacl
, ppSacl
,
718 ppSecurityDescriptor
));
722 get_file_security (const char *lpFileName
,
723 SECURITY_INFORMATION RequestedInformation
,
724 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
726 LPDWORD lpnLengthNeeded
)
728 static GetFileSecurityA_Proc s_pfn_Get_File_SecurityA
= NULL
;
729 static GetFileSecurityW_Proc s_pfn_Get_File_SecurityW
= NULL
;
730 HMODULE hm_advapi32
= NULL
;
731 if (is_windows_9x () == TRUE
)
736 if (w32_unicode_filenames
)
738 wchar_t filename_w
[MAX_PATH
];
740 if (g_b_init_get_file_security_w
== 0)
742 g_b_init_get_file_security_w
= 1;
743 hm_advapi32
= LoadLibrary ("Advapi32.dll");
744 s_pfn_Get_File_SecurityW
=
745 (GetFileSecurityW_Proc
) GetProcAddress (hm_advapi32
,
748 if (s_pfn_Get_File_SecurityW
== NULL
)
753 filename_to_utf16 (lpFileName
, filename_w
);
754 return (s_pfn_Get_File_SecurityW (filename_w
, RequestedInformation
,
755 pSecurityDescriptor
, nLength
,
760 char filename_a
[MAX_PATH
];
762 if (g_b_init_get_file_security_a
== 0)
764 g_b_init_get_file_security_a
= 1;
765 hm_advapi32
= LoadLibrary ("Advapi32.dll");
766 s_pfn_Get_File_SecurityA
=
767 (GetFileSecurityA_Proc
) GetProcAddress (hm_advapi32
,
770 if (s_pfn_Get_File_SecurityA
== NULL
)
775 filename_to_ansi (lpFileName
, filename_a
);
776 return (s_pfn_Get_File_SecurityA (filename_a
, RequestedInformation
,
777 pSecurityDescriptor
, nLength
,
783 set_file_security (const char *lpFileName
,
784 SECURITY_INFORMATION SecurityInformation
,
785 PSECURITY_DESCRIPTOR pSecurityDescriptor
)
787 static SetFileSecurityW_Proc s_pfn_Set_File_SecurityW
= NULL
;
788 static SetFileSecurityA_Proc s_pfn_Set_File_SecurityA
= NULL
;
789 HMODULE hm_advapi32
= NULL
;
790 if (is_windows_9x () == TRUE
)
795 if (w32_unicode_filenames
)
797 wchar_t filename_w
[MAX_PATH
];
799 if (g_b_init_set_file_security_w
== 0)
801 g_b_init_set_file_security_w
= 1;
802 hm_advapi32
= LoadLibrary ("Advapi32.dll");
803 s_pfn_Set_File_SecurityW
=
804 (SetFileSecurityW_Proc
) GetProcAddress (hm_advapi32
,
807 if (s_pfn_Set_File_SecurityW
== NULL
)
812 filename_to_utf16 (lpFileName
, filename_w
);
813 return (s_pfn_Set_File_SecurityW (filename_w
, SecurityInformation
,
814 pSecurityDescriptor
));
818 char filename_a
[MAX_PATH
];
820 if (g_b_init_set_file_security_a
== 0)
822 g_b_init_set_file_security_a
= 1;
823 hm_advapi32
= LoadLibrary ("Advapi32.dll");
824 s_pfn_Set_File_SecurityA
=
825 (SetFileSecurityA_Proc
) GetProcAddress (hm_advapi32
,
828 if (s_pfn_Set_File_SecurityA
== NULL
)
833 filename_to_ansi (lpFileName
, filename_a
);
834 return (s_pfn_Set_File_SecurityA (filename_a
, SecurityInformation
,
835 pSecurityDescriptor
));
840 set_named_security_info (LPCTSTR lpObjectName
,
841 SE_OBJECT_TYPE ObjectType
,
842 SECURITY_INFORMATION SecurityInformation
,
848 static SetNamedSecurityInfoW_Proc s_pfn_Set_Named_Security_InfoW
= NULL
;
849 static SetNamedSecurityInfoA_Proc s_pfn_Set_Named_Security_InfoA
= NULL
;
850 HMODULE hm_advapi32
= NULL
;
851 if (is_windows_9x () == TRUE
)
856 if (w32_unicode_filenames
)
858 wchar_t filename_w
[MAX_PATH
];
860 if (g_b_init_set_named_security_info_w
== 0)
862 g_b_init_set_named_security_info_w
= 1;
863 hm_advapi32
= LoadLibrary ("Advapi32.dll");
864 s_pfn_Set_Named_Security_InfoW
=
865 (SetNamedSecurityInfoW_Proc
) GetProcAddress (hm_advapi32
,
866 "SetNamedSecurityInfoW");
868 if (s_pfn_Set_Named_Security_InfoW
== NULL
)
873 filename_to_utf16 (lpObjectName
, filename_w
);
874 return (s_pfn_Set_Named_Security_InfoW (filename_w
, ObjectType
,
875 SecurityInformation
, psidOwner
,
876 psidGroup
, pDacl
, pSacl
));
880 char filename_a
[MAX_PATH
];
882 if (g_b_init_set_named_security_info_a
== 0)
884 g_b_init_set_named_security_info_a
= 1;
885 hm_advapi32
= LoadLibrary ("Advapi32.dll");
886 s_pfn_Set_Named_Security_InfoA
=
887 (SetNamedSecurityInfoA_Proc
) GetProcAddress (hm_advapi32
,
888 "SetNamedSecurityInfoA");
890 if (s_pfn_Set_Named_Security_InfoA
== NULL
)
895 filename_to_ansi (lpObjectName
, filename_a
);
896 return (s_pfn_Set_Named_Security_InfoA (filename_a
, ObjectType
,
897 SecurityInformation
, psidOwner
,
898 psidGroup
, pDacl
, pSacl
));
903 get_security_descriptor_owner (PSECURITY_DESCRIPTOR pSecurityDescriptor
,
905 LPBOOL lpbOwnerDefaulted
)
907 static GetSecurityDescriptorOwner_Proc s_pfn_Get_Security_Descriptor_Owner
= NULL
;
908 HMODULE hm_advapi32
= NULL
;
909 if (is_windows_9x () == TRUE
)
914 if (g_b_init_get_security_descriptor_owner
== 0)
916 g_b_init_get_security_descriptor_owner
= 1;
917 hm_advapi32
= LoadLibrary ("Advapi32.dll");
918 s_pfn_Get_Security_Descriptor_Owner
=
919 (GetSecurityDescriptorOwner_Proc
) GetProcAddress (
920 hm_advapi32
, "GetSecurityDescriptorOwner");
922 if (s_pfn_Get_Security_Descriptor_Owner
== NULL
)
927 return (s_pfn_Get_Security_Descriptor_Owner (pSecurityDescriptor
, pOwner
,
932 get_security_descriptor_group (PSECURITY_DESCRIPTOR pSecurityDescriptor
,
934 LPBOOL lpbGroupDefaulted
)
936 static GetSecurityDescriptorGroup_Proc s_pfn_Get_Security_Descriptor_Group
= NULL
;
937 HMODULE hm_advapi32
= NULL
;
938 if (is_windows_9x () == TRUE
)
943 if (g_b_init_get_security_descriptor_group
== 0)
945 g_b_init_get_security_descriptor_group
= 1;
946 hm_advapi32
= LoadLibrary ("Advapi32.dll");
947 s_pfn_Get_Security_Descriptor_Group
=
948 (GetSecurityDescriptorGroup_Proc
) GetProcAddress (
949 hm_advapi32
, "GetSecurityDescriptorGroup");
951 if (s_pfn_Get_Security_Descriptor_Group
== NULL
)
956 return (s_pfn_Get_Security_Descriptor_Group (pSecurityDescriptor
, pGroup
,
961 get_security_descriptor_dacl (PSECURITY_DESCRIPTOR pSecurityDescriptor
,
962 LPBOOL lpbDaclPresent
,
964 LPBOOL lpbDaclDefaulted
)
966 static GetSecurityDescriptorDacl_Proc s_pfn_Get_Security_Descriptor_Dacl
= NULL
;
967 HMODULE hm_advapi32
= NULL
;
968 if (is_windows_9x () == TRUE
)
973 if (g_b_init_get_security_descriptor_dacl
== 0)
975 g_b_init_get_security_descriptor_dacl
= 1;
976 hm_advapi32
= LoadLibrary ("Advapi32.dll");
977 s_pfn_Get_Security_Descriptor_Dacl
=
978 (GetSecurityDescriptorDacl_Proc
) GetProcAddress (
979 hm_advapi32
, "GetSecurityDescriptorDacl");
981 if (s_pfn_Get_Security_Descriptor_Dacl
== NULL
)
986 return (s_pfn_Get_Security_Descriptor_Dacl (pSecurityDescriptor
,
987 lpbDaclPresent
, pDacl
,
992 is_valid_sid (PSID sid
)
994 static IsValidSid_Proc s_pfn_Is_Valid_Sid
= NULL
;
995 HMODULE hm_advapi32
= NULL
;
996 if (is_windows_9x () == TRUE
)
1000 if (g_b_init_is_valid_sid
== 0)
1002 g_b_init_is_valid_sid
= 1;
1003 hm_advapi32
= LoadLibrary ("Advapi32.dll");
1004 s_pfn_Is_Valid_Sid
=
1005 (IsValidSid_Proc
) GetProcAddress (
1006 hm_advapi32
, "IsValidSid");
1008 if (s_pfn_Is_Valid_Sid
== NULL
)
1012 return (s_pfn_Is_Valid_Sid (sid
));
1016 equal_sid (PSID sid1
, PSID sid2
)
1018 static EqualSid_Proc s_pfn_Equal_Sid
= NULL
;
1019 HMODULE hm_advapi32
= NULL
;
1020 if (is_windows_9x () == TRUE
)
1024 if (g_b_init_equal_sid
== 0)
1026 g_b_init_equal_sid
= 1;
1027 hm_advapi32
= LoadLibrary ("Advapi32.dll");
1029 (EqualSid_Proc
) GetProcAddress (
1030 hm_advapi32
, "EqualSid");
1032 if (s_pfn_Equal_Sid
== NULL
)
1036 return (s_pfn_Equal_Sid (sid1
, sid2
));
1040 get_length_sid (PSID sid
)
1042 static GetLengthSid_Proc s_pfn_Get_Length_Sid
= NULL
;
1043 HMODULE hm_advapi32
= NULL
;
1044 if (is_windows_9x () == TRUE
)
1048 if (g_b_init_get_length_sid
== 0)
1050 g_b_init_get_length_sid
= 1;
1051 hm_advapi32
= LoadLibrary ("Advapi32.dll");
1052 s_pfn_Get_Length_Sid
=
1053 (GetLengthSid_Proc
) GetProcAddress (
1054 hm_advapi32
, "GetLengthSid");
1056 if (s_pfn_Get_Length_Sid
== NULL
)
1060 return (s_pfn_Get_Length_Sid (sid
));
1064 copy_sid (DWORD destlen
, PSID dest
, PSID src
)
1066 static CopySid_Proc s_pfn_Copy_Sid
= NULL
;
1067 HMODULE hm_advapi32
= NULL
;
1068 if (is_windows_9x () == TRUE
)
1072 if (g_b_init_copy_sid
== 0)
1074 g_b_init_copy_sid
= 1;
1075 hm_advapi32
= LoadLibrary ("Advapi32.dll");
1077 (CopySid_Proc
) GetProcAddress (
1078 hm_advapi32
, "CopySid");
1080 if (s_pfn_Copy_Sid
== NULL
)
1084 return (s_pfn_Copy_Sid (destlen
, dest
, src
));
1088 END: Wrapper functions around OpenProcessToken
1089 and other functions in advapi32.dll that are only
1090 supported in Windows NT / 2k / XP
1094 get_native_system_info (LPSYSTEM_INFO lpSystemInfo
)
1096 static GetNativeSystemInfo_Proc s_pfn_Get_Native_System_Info
= NULL
;
1097 if (is_windows_9x () != TRUE
)
1099 if (g_b_init_get_native_system_info
== 0)
1101 g_b_init_get_native_system_info
= 1;
1102 s_pfn_Get_Native_System_Info
=
1103 (GetNativeSystemInfo_Proc
)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1104 "GetNativeSystemInfo");
1106 if (s_pfn_Get_Native_System_Info
!= NULL
)
1107 s_pfn_Get_Native_System_Info (lpSystemInfo
);
1110 lpSystemInfo
->dwNumberOfProcessors
= -1;
1114 get_system_times (LPFILETIME lpIdleTime
,
1115 LPFILETIME lpKernelTime
,
1116 LPFILETIME lpUserTime
)
1118 static GetSystemTimes_Proc s_pfn_Get_System_times
= NULL
;
1119 if (is_windows_9x () == TRUE
)
1123 if (g_b_init_get_system_times
== 0)
1125 g_b_init_get_system_times
= 1;
1126 s_pfn_Get_System_times
=
1127 (GetSystemTimes_Proc
)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1130 if (s_pfn_Get_System_times
== NULL
)
1132 return (s_pfn_Get_System_times (lpIdleTime
, lpKernelTime
, lpUserTime
));
1135 static BOOLEAN WINAPI
1136 create_symbolic_link (LPCSTR lpSymlinkFilename
,
1137 LPCSTR lpTargetFileName
,
1140 static CreateSymbolicLinkW_Proc s_pfn_Create_Symbolic_LinkW
= NULL
;
1141 static CreateSymbolicLinkA_Proc s_pfn_Create_Symbolic_LinkA
= NULL
;
1144 if (is_windows_9x () == TRUE
)
1149 if (w32_unicode_filenames
)
1151 wchar_t symfn_w
[MAX_PATH
], tgtfn_w
[MAX_PATH
];
1153 if (g_b_init_create_symbolic_link_w
== 0)
1155 g_b_init_create_symbolic_link_w
= 1;
1156 s_pfn_Create_Symbolic_LinkW
=
1157 (CreateSymbolicLinkW_Proc
)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1158 "CreateSymbolicLinkW");
1160 if (s_pfn_Create_Symbolic_LinkW
== NULL
)
1166 filename_to_utf16 (lpSymlinkFilename
, symfn_w
);
1167 filename_to_utf16 (lpTargetFileName
, tgtfn_w
);
1168 retval
= s_pfn_Create_Symbolic_LinkW (symfn_w
, tgtfn_w
, dwFlags
);
1169 /* If we were denied creation of the symlink, try again after
1170 enabling the SeCreateSymbolicLinkPrivilege for our process. */
1173 TOKEN_PRIVILEGES priv_current
;
1175 if (enable_privilege (SE_CREATE_SYMBOLIC_LINK_NAME
, TRUE
,
1178 retval
= s_pfn_Create_Symbolic_LinkW (symfn_w
, tgtfn_w
, dwFlags
);
1179 restore_privilege (&priv_current
);
1186 char symfn_a
[MAX_PATH
], tgtfn_a
[MAX_PATH
];
1188 if (g_b_init_create_symbolic_link_a
== 0)
1190 g_b_init_create_symbolic_link_a
= 1;
1191 s_pfn_Create_Symbolic_LinkA
=
1192 (CreateSymbolicLinkA_Proc
)GetProcAddress (GetModuleHandle ("kernel32.dll"),
1193 "CreateSymbolicLinkA");
1195 if (s_pfn_Create_Symbolic_LinkA
== NULL
)
1201 filename_to_ansi (lpSymlinkFilename
, symfn_a
);
1202 filename_to_ansi (lpTargetFileName
, tgtfn_a
);
1203 retval
= s_pfn_Create_Symbolic_LinkA (symfn_a
, tgtfn_a
, dwFlags
);
1204 /* If we were denied creation of the symlink, try again after
1205 enabling the SeCreateSymbolicLinkPrivilege for our process. */
1208 TOKEN_PRIVILEGES priv_current
;
1210 if (enable_privilege (SE_CREATE_SYMBOLIC_LINK_NAME
, TRUE
,
1213 retval
= s_pfn_Create_Symbolic_LinkA (symfn_a
, tgtfn_a
, dwFlags
);
1214 restore_privilege (&priv_current
);
1223 is_valid_security_descriptor (PSECURITY_DESCRIPTOR pSecurityDescriptor
)
1225 static IsValidSecurityDescriptor_Proc s_pfn_Is_Valid_Security_Descriptor_Proc
= NULL
;
1227 if (is_windows_9x () == TRUE
)
1233 if (g_b_init_is_valid_security_descriptor
== 0)
1235 g_b_init_is_valid_security_descriptor
= 1;
1236 s_pfn_Is_Valid_Security_Descriptor_Proc
=
1237 (IsValidSecurityDescriptor_Proc
)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1238 "IsValidSecurityDescriptor");
1240 if (s_pfn_Is_Valid_Security_Descriptor_Proc
== NULL
)
1246 return s_pfn_Is_Valid_Security_Descriptor_Proc (pSecurityDescriptor
);
1250 convert_sd_to_sddl (PSECURITY_DESCRIPTOR SecurityDescriptor
,
1251 DWORD RequestedStringSDRevision
,
1252 SECURITY_INFORMATION SecurityInformation
,
1253 LPTSTR
*StringSecurityDescriptor
,
1254 PULONG StringSecurityDescriptorLen
)
1256 static ConvertSecurityDescriptorToStringSecurityDescriptor_Proc s_pfn_Convert_SD_To_SDDL
= NULL
;
1259 if (is_windows_9x () == TRUE
)
1265 if (g_b_init_convert_sd_to_sddl
== 0)
1267 g_b_init_convert_sd_to_sddl
= 1;
1269 s_pfn_Convert_SD_To_SDDL
=
1270 (ConvertSecurityDescriptorToStringSecurityDescriptor_Proc
)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1271 "ConvertSecurityDescriptorToStringSecurityDescriptorW");
1273 s_pfn_Convert_SD_To_SDDL
=
1274 (ConvertSecurityDescriptorToStringSecurityDescriptor_Proc
)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1275 "ConvertSecurityDescriptorToStringSecurityDescriptorA");
1278 if (s_pfn_Convert_SD_To_SDDL
== NULL
)
1284 retval
= s_pfn_Convert_SD_To_SDDL (SecurityDescriptor
,
1285 RequestedStringSDRevision
,
1286 SecurityInformation
,
1287 StringSecurityDescriptor
,
1288 StringSecurityDescriptorLen
);
1294 convert_sddl_to_sd (LPCTSTR StringSecurityDescriptor
,
1295 DWORD StringSDRevision
,
1296 PSECURITY_DESCRIPTOR
*SecurityDescriptor
,
1297 PULONG SecurityDescriptorSize
)
1299 static ConvertStringSecurityDescriptorToSecurityDescriptor_Proc s_pfn_Convert_SDDL_To_SD
= NULL
;
1302 if (is_windows_9x () == TRUE
)
1308 if (g_b_init_convert_sddl_to_sd
== 0)
1310 g_b_init_convert_sddl_to_sd
= 1;
1312 s_pfn_Convert_SDDL_To_SD
=
1313 (ConvertStringSecurityDescriptorToSecurityDescriptor_Proc
)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1314 "ConvertStringSecurityDescriptorToSecurityDescriptorW");
1316 s_pfn_Convert_SDDL_To_SD
=
1317 (ConvertStringSecurityDescriptorToSecurityDescriptor_Proc
)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1318 "ConvertStringSecurityDescriptorToSecurityDescriptorA");
1321 if (s_pfn_Convert_SDDL_To_SD
== NULL
)
1327 retval
= s_pfn_Convert_SDDL_To_SD (StringSecurityDescriptor
,
1330 SecurityDescriptorSize
);
1336 get_adapters_info (PIP_ADAPTER_INFO pAdapterInfo
, PULONG pOutBufLen
)
1338 static GetAdaptersInfo_Proc s_pfn_Get_Adapters_Info
= NULL
;
1339 HMODULE hm_iphlpapi
= NULL
;
1341 if (is_windows_9x () == TRUE
)
1342 return ERROR_NOT_SUPPORTED
;
1344 if (g_b_init_get_adapters_info
== 0)
1346 g_b_init_get_adapters_info
= 1;
1347 hm_iphlpapi
= LoadLibrary ("Iphlpapi.dll");
1349 s_pfn_Get_Adapters_Info
= (GetAdaptersInfo_Proc
)
1350 GetProcAddress (hm_iphlpapi
, "GetAdaptersInfo");
1352 if (s_pfn_Get_Adapters_Info
== NULL
)
1353 return ERROR_NOT_SUPPORTED
;
1354 return s_pfn_Get_Adapters_Info (pAdapterInfo
, pOutBufLen
);
1359 /* Return 1 if P is a valid pointer to an object of size SIZE. Return
1360 0 if P is NOT a valid pointer. Return -1 if we cannot validate P.
1362 This is called from alloc.c:valid_pointer_p. */
1364 w32_valid_pointer_p (void *p
, int size
)
1367 HANDLE h
= OpenProcess (PROCESS_VM_READ
, FALSE
, GetCurrentProcessId ());
1371 unsigned char *buf
= alloca (size
);
1372 int retval
= ReadProcessMemory (h
, p
, buf
, size
, &done
);
1383 /* Here's an overview of how the Windows build supports file names
1384 that cannot be encoded by the current system codepage.
1386 From the POV of Lisp and layers of C code above the functions here,
1387 Emacs on Windows pretends that its file names are encoded in UTF-8;
1388 see encode_file and decode_file on coding.c. Any file name that is
1389 passed as a unibyte string to C functions defined here is assumed
1390 to be in UTF-8 encoding. Any file name returned by functions
1391 defined here must be in UTF-8 encoding, with only a few exceptions
1392 reserved for a couple of special cases. (Be sure to use
1393 MAX_UTF8_PATH for char arrays that store UTF-8 encoded file names,
1394 as they can be much longer than MAX_PATH!)
1396 The UTF-8 encoded file names cannot be passed to system APIs, as
1397 Windows does not support that. Therefore, they are converted
1398 either to UTF-16 or to the ANSI codepage, depending on the value of
1399 w32-unicode-filenames, before calling any system APIs or CRT library
1400 functions. The default value of that variable is determined by the
1401 OS on which Emacs runs: nil on Windows 9X and t otherwise, but the
1402 user can change that default (although I don't see why would she
1405 The 4 functions defined below, filename_to_utf16, filename_to_ansi,
1406 filename_from_utf16, and filename_from_ansi, are the workhorses of
1407 these conversions. They rely on Windows native APIs
1408 MultiByteToWideChar and WideCharToMultiByte; we cannot use
1409 functions from coding.c here, because they allocate memory, which
1410 is a bad idea on the level of libc, which is what the functions
1411 here emulate. (If you worry about performance due to constant
1412 conversion back and forth from UTF-8 to UTF-16, then don't: first,
1413 it was measured to take only a few microseconds on a not-so-fast
1414 machine, and second, that's exactly what the ANSI APIs we used
1415 before did anyway, because they are just thin wrappers around the
1418 The variables file-name-coding-system and default-file-name-coding-system
1419 still exist, but are actually used only when a file name needs to
1420 be converted to the ANSI codepage. This happens all the time when
1421 w32-unicode-filenames is nil, but can also happen from time to time
1422 when it is t. Otherwise, these variables have no effect on file-name
1423 encoding when w32-unicode-filenames is t; this is similar to
1424 selection-coding-system.
1426 This arrangement works very well, but it has a few gotchas and
1429 . Lisp code that encodes or decodes file names manually should
1430 normally use 'utf-8' as the coding-system on Windows,
1431 disregarding file-name-coding-system. This is a somewhat
1432 unpleasant consequence, but it cannot be avoided. Fortunately,
1433 very few Lisp packages need to do that.
1435 More generally, passing to library functions (e.g., fopen or
1436 opendir) file names already encoded in the ANSI codepage is
1437 explicitly *verboten*, as all those functions, as shadowed and
1438 emulated here, assume they will receive UTF-8 encoded file names.
1440 For the same reasons, no CRT function or Win32 API can be called
1441 directly in Emacs sources, without either converting the file
1442 names from UTF-8 to UTF-16 or ANSI codepage, or going through
1443 some shadowing function defined here.
1445 . Environment variables stored in Vprocess_environment are encoded
1446 in the ANSI codepage, so if getenv/egetenv is used for a variable
1447 whose value is a file name or a list of directories, it needs to
1448 be converted to UTF-8, before it is used as argument to functions
1449 or decoded into a Lisp string.
1451 . File names passed to external libraries, like the image libraries
1452 and GnuTLS, need special handling. These libraries generally
1453 don't support UTF-16 or UTF-8 file names, so they must get file
1454 names encoded in the ANSI codepage. To facilitate using these
1455 libraries with file names that are not encodable in the ANSI
1456 codepage, use the function ansi_encode_filename, which will try
1457 to use the short 8+3 alias of a file name if that file name is
1458 not encodable in the ANSI codepage. See image.c and gnutls.c for
1459 examples of how this should be done.
1461 . Running subprocesses in non-ASCII directories and with non-ASCII
1462 file arguments is limited to the current codepage (even though
1463 Emacs is perfectly capable of finding an executable program file
1464 in a directory whose name cannot be encoded in the current
1465 codepage). This is because the command-line arguments are
1466 encoded _before_ they get to the w32-specific level, and the
1467 encoding is not known in advance (it doesn't have to be the
1468 current ANSI codepage), so w32proc.c functions cannot re-encode
1469 them in UTF-16. This should be fixed, but will also require
1470 changes in cmdproxy. The current limitation is not terribly bad
1471 anyway, since very few, if any, Windows console programs that are
1472 likely to be invoked by Emacs support UTF-16 encoded command
1475 . For similar reasons, server.el and emacsclient are also limited
1476 to the current ANSI codepage for now.
1478 . Emacs itself can only handle command-line arguments encoded in
1479 the current codepage.
1481 . Turning on w32-unicode-filename on Windows 9X (if it at all
1482 works) requires UNICOWS.DLL, which is thus a requirement even in
1483 non-GUI sessions, something the we previously avoided. */
1487 /* Converting file names from UTF-8 to either UTF-16 or the ANSI
1488 codepage defined by file-name-coding-system. */
1490 /* Current codepage for encoding file names. */
1491 static int file_name_codepage
;
1493 /* Produce a Windows ANSI codepage suitable for encoding file names.
1494 Return the information about that codepage in CP_INFO. */
1496 codepage_for_filenames (CPINFO
*cp_info
)
1498 /* A simple cache to avoid calling GetCPInfo every time we need to
1499 encode/decode a file name. The file-name encoding is not
1500 supposed to be changed too frequently, if ever. */
1501 static Lisp_Object last_file_name_encoding
;
1503 Lisp_Object current_encoding
;
1505 current_encoding
= Vfile_name_coding_system
;
1506 if (NILP (current_encoding
))
1507 current_encoding
= Vdefault_file_name_coding_system
;
1509 if (!EQ (last_file_name_encoding
, current_encoding
))
1511 /* Default to the current ANSI codepage. */
1512 file_name_codepage
= w32_ansi_code_page
;
1514 if (NILP (current_encoding
))
1516 char *cpname
= SDATA (SYMBOL_NAME (current_encoding
));
1517 char *cp
= NULL
, *end
;
1520 if (strncmp (cpname
, "cp", 2) == 0)
1522 else if (strncmp (cpname
, "windows-", 8) == 0)
1528 cpnum
= strtol (cp
, &end
, 10);
1529 if (cpnum
&& *end
== '\0' && end
- cp
>= 2)
1530 file_name_codepage
= cpnum
;
1534 if (!file_name_codepage
)
1535 file_name_codepage
= CP_ACP
; /* CP_ACP = 0, but let's not assume that */
1537 if (!GetCPInfo (file_name_codepage
, &cp
))
1539 file_name_codepage
= CP_ACP
;
1540 if (!GetCPInfo (file_name_codepage
, &cp
))
1547 return file_name_codepage
;
1551 filename_to_utf16 (const char *fn_in
, wchar_t *fn_out
)
1553 int result
= pMultiByteToWideChar (CP_UTF8
, MB_ERR_INVALID_CHARS
, fn_in
, -1,
1558 DWORD err
= GetLastError ();
1562 case ERROR_INVALID_FLAGS
:
1563 case ERROR_INVALID_PARAMETER
:
1566 case ERROR_INSUFFICIENT_BUFFER
:
1567 case ERROR_NO_UNICODE_TRANSLATION
:
1578 filename_from_utf16 (const wchar_t *fn_in
, char *fn_out
)
1580 int result
= pWideCharToMultiByte (CP_UTF8
, 0, fn_in
, -1,
1581 fn_out
, MAX_UTF8_PATH
, NULL
, NULL
);
1585 DWORD err
= GetLastError ();
1589 case ERROR_INVALID_FLAGS
:
1590 case ERROR_INVALID_PARAMETER
:
1593 case ERROR_INSUFFICIENT_BUFFER
:
1594 case ERROR_NO_UNICODE_TRANSLATION
:
1605 filename_to_ansi (const char *fn_in
, char *fn_out
)
1607 wchar_t fn_utf16
[MAX_PATH
];
1609 if (filename_to_utf16 (fn_in
, fn_utf16
) == 0)
1612 int codepage
= codepage_for_filenames (NULL
);
1614 result
= pWideCharToMultiByte (codepage
, 0, fn_utf16
, -1,
1615 fn_out
, MAX_PATH
, NULL
, NULL
);
1618 DWORD err
= GetLastError ();
1622 case ERROR_INVALID_FLAGS
:
1623 case ERROR_INVALID_PARAMETER
:
1626 case ERROR_INSUFFICIENT_BUFFER
:
1627 case ERROR_NO_UNICODE_TRANSLATION
:
1640 filename_from_ansi (const char *fn_in
, char *fn_out
)
1642 wchar_t fn_utf16
[MAX_PATH
];
1643 int codepage
= codepage_for_filenames (NULL
);
1644 int result
= pMultiByteToWideChar (codepage
, MB_ERR_INVALID_CHARS
, fn_in
, -1,
1645 fn_utf16
, MAX_PATH
);
1649 DWORD err
= GetLastError ();
1653 case ERROR_INVALID_FLAGS
:
1654 case ERROR_INVALID_PARAMETER
:
1657 case ERROR_INSUFFICIENT_BUFFER
:
1658 case ERROR_NO_UNICODE_TRANSLATION
:
1665 return filename_from_utf16 (fn_utf16
, fn_out
);
1670 /* The directory where we started, in UTF-8. */
1671 static char startup_dir
[MAX_UTF8_PATH
];
1673 /* Get the current working directory. */
1675 getcwd (char *dir
, int dirsize
)
1682 if (dirsize
<= strlen (startup_dir
))
1688 if (GetCurrentDirectory (MAXPATHLEN
, dir
) > 0)
1692 /* Emacs doesn't actually change directory itself, it stays in the
1693 same directory where it was started. */
1694 strcpy (dir
, startup_dir
);
1699 /* Emulate getloadavg. */
1701 struct load_sample
{
1708 /* Number of processors on this machine. */
1709 static unsigned num_of_processors
;
1711 /* We maintain 1-sec samples for the last 16 minutes in a circular buffer. */
1712 static struct load_sample samples
[16*60];
1713 static int first_idx
= -1, last_idx
= -1;
1714 static int max_idx
= ARRAYELTS (samples
);
1719 int next_idx
= from
+ 1;
1721 if (next_idx
>= max_idx
)
1730 int prev_idx
= from
- 1;
1733 prev_idx
= max_idx
- 1;
1739 sample_system_load (ULONGLONG
*idle
, ULONGLONG
*kernel
, ULONGLONG
*user
)
1741 SYSTEM_INFO sysinfo
;
1742 FILETIME ft_idle
, ft_user
, ft_kernel
;
1744 /* Initialize the number of processors on this machine. */
1745 if (num_of_processors
<= 0)
1747 get_native_system_info (&sysinfo
);
1748 num_of_processors
= sysinfo
.dwNumberOfProcessors
;
1749 if (num_of_processors
<= 0)
1751 GetSystemInfo (&sysinfo
);
1752 num_of_processors
= sysinfo
.dwNumberOfProcessors
;
1754 if (num_of_processors
<= 0)
1755 num_of_processors
= 1;
1758 /* TODO: Take into account threads that are ready to run, by
1759 sampling the "\System\Processor Queue Length" performance
1760 counter. The code below accounts only for threads that are
1761 actually running. */
1763 if (get_system_times (&ft_idle
, &ft_kernel
, &ft_user
))
1765 ULARGE_INTEGER uidle
, ukernel
, uuser
;
1767 memcpy (&uidle
, &ft_idle
, sizeof (ft_idle
));
1768 memcpy (&ukernel
, &ft_kernel
, sizeof (ft_kernel
));
1769 memcpy (&uuser
, &ft_user
, sizeof (ft_user
));
1770 *idle
= uidle
.QuadPart
;
1771 *kernel
= ukernel
.QuadPart
;
1772 *user
= uuser
.QuadPart
;
1782 /* Produce the load average for a given time interval, using the
1783 samples in the samples[] array. WHICH can be 0, 1, or 2, meaning
1784 1-minute, 5-minute, or 15-minute average, respectively. */
1788 double retval
= -1.0;
1791 double span
= (which
== 0 ? 1.0 : (which
== 1 ? 5.0 : 15.0)) * 60;
1792 time_t now
= samples
[last_idx
].sample_time
;
1794 if (first_idx
!= last_idx
)
1796 for (idx
= buf_prev (last_idx
); ; idx
= buf_prev (idx
))
1798 tdiff
= difftime (now
, samples
[idx
].sample_time
);
1799 if (tdiff
>= span
- 2*DBL_EPSILON
*now
)
1802 samples
[last_idx
].kernel
+ samples
[last_idx
].user
1803 - (samples
[idx
].kernel
+ samples
[idx
].user
);
1804 long double idl
= samples
[last_idx
].idle
- samples
[idx
].idle
;
1806 retval
= (1.0 - idl
/ sys
) * num_of_processors
;
1809 if (idx
== first_idx
)
1818 getloadavg (double loadavg
[], int nelem
)
1821 ULONGLONG idle
, kernel
, user
;
1822 time_t now
= time (NULL
);
1824 /* If system time jumped back for some reason, delete all samples
1825 whose time is later than the current wall-clock time. This
1826 prevents load average figures from becoming frozen for prolonged
1827 periods of time, when system time is reset backwards. */
1830 while (difftime (now
, samples
[last_idx
].sample_time
) < -1.0)
1832 if (last_idx
== first_idx
)
1834 first_idx
= last_idx
= -1;
1837 last_idx
= buf_prev (last_idx
);
1841 /* Store another sample. We ignore samples that are less than 1 sec
1844 || (difftime (now
, samples
[last_idx
].sample_time
)
1845 >= 1.0 - 2*DBL_EPSILON
*now
))
1847 sample_system_load (&idle
, &kernel
, &user
);
1848 last_idx
= buf_next (last_idx
);
1849 samples
[last_idx
].sample_time
= now
;
1850 samples
[last_idx
].idle
= idle
;
1851 samples
[last_idx
].kernel
= kernel
;
1852 samples
[last_idx
].user
= user
;
1853 /* If the buffer has more that 15 min worth of samples, discard
1855 if (first_idx
== -1)
1856 first_idx
= last_idx
;
1857 while (first_idx
!= last_idx
1858 && (difftime (now
, samples
[first_idx
].sample_time
)
1859 >= 15.0*60 + 2*DBL_EPSILON
*now
))
1860 first_idx
= buf_next (first_idx
);
1863 for (elem
= 0; elem
< nelem
; elem
++)
1865 double avg
= getavg (elem
);
1869 loadavg
[elem
] = avg
;
1875 /* Emulate getpwuid, getpwnam and others. */
1877 #define PASSWD_FIELD_SIZE 256
1879 static char dflt_passwd_name
[PASSWD_FIELD_SIZE
];
1880 static char dflt_passwd_passwd
[PASSWD_FIELD_SIZE
];
1881 static char dflt_passwd_gecos
[PASSWD_FIELD_SIZE
];
1882 static char dflt_passwd_dir
[MAX_UTF8_PATH
];
1883 static char dflt_passwd_shell
[MAX_UTF8_PATH
];
1885 static struct passwd dflt_passwd
=
1897 static char dflt_group_name
[GNLEN
+1];
1899 static struct group dflt_group
=
1901 /* When group information is not available, we return this as the
1902 group for all files. */
1910 return dflt_passwd
.pw_uid
;
1916 /* I could imagine arguing for checking to see whether the user is
1917 in the Administrators group and returning a UID of 0 for that
1918 case, but I don't know how wise that would be in the long run. */
1925 return dflt_passwd
.pw_gid
;
1935 getpwuid (unsigned uid
)
1937 if (uid
== dflt_passwd
.pw_uid
)
1938 return &dflt_passwd
;
1943 getgrgid (gid_t gid
)
1949 getpwnam (char *name
)
1953 pw
= getpwuid (getuid ());
1957 if (xstrcasecmp (name
, pw
->pw_name
))
1964 init_user_info (void)
1966 /* Find the user's real name by opening the process token and
1967 looking up the name associated with the user-sid in that token.
1969 Use the relative portion of the identifier authority value from
1970 the user-sid as the user id value (same for group id using the
1971 primary group sid from the process token). */
1973 char uname
[UNLEN
+1], gname
[GNLEN
+1], domain
[1025];
1974 DWORD ulength
= sizeof (uname
), dlength
= sizeof (domain
), needed
;
1975 DWORD glength
= sizeof (gname
);
1976 HANDLE token
= NULL
;
1977 SID_NAME_USE user_type
;
1978 unsigned char *buf
= NULL
;
1980 TOKEN_USER user_token
;
1981 TOKEN_PRIMARY_GROUP group_token
;
1984 result
= open_process_token (GetCurrentProcess (), TOKEN_QUERY
, &token
);
1987 result
= get_token_information (token
, TokenUser
, NULL
, 0, &blen
);
1988 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
1990 buf
= xmalloc (blen
);
1991 result
= get_token_information (token
, TokenUser
,
1992 (LPVOID
)buf
, blen
, &needed
);
1995 memcpy (&user_token
, buf
, sizeof (user_token
));
1996 result
= lookup_account_sid (NULL
, user_token
.User
.Sid
,
1998 domain
, &dlength
, &user_type
);
2006 strcpy (dflt_passwd
.pw_name
, uname
);
2007 /* Determine a reasonable uid value. */
2008 if (xstrcasecmp ("administrator", uname
) == 0)
2010 dflt_passwd
.pw_uid
= 500; /* well-known Administrator uid */
2011 dflt_passwd
.pw_gid
= 513; /* well-known None gid */
2015 /* Use the last sub-authority value of the RID, the relative
2016 portion of the SID, as user/group ID. */
2017 dflt_passwd
.pw_uid
= get_rid (user_token
.User
.Sid
);
2019 /* Get group id and name. */
2020 result
= get_token_information (token
, TokenPrimaryGroup
,
2021 (LPVOID
)buf
, blen
, &needed
);
2022 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
2024 buf
= xrealloc (buf
, blen
= needed
);
2025 result
= get_token_information (token
, TokenPrimaryGroup
,
2026 (LPVOID
)buf
, blen
, &needed
);
2030 memcpy (&group_token
, buf
, sizeof (group_token
));
2031 dflt_passwd
.pw_gid
= get_rid (group_token
.PrimaryGroup
);
2032 dlength
= sizeof (domain
);
2033 /* If we can get at the real Primary Group name, use that.
2034 Otherwise, the default group name was already set to
2035 "None" in globals_of_w32. */
2036 if (lookup_account_sid (NULL
, group_token
.PrimaryGroup
,
2037 gname
, &glength
, NULL
, &dlength
,
2039 strcpy (dflt_group_name
, gname
);
2042 dflt_passwd
.pw_gid
= dflt_passwd
.pw_uid
;
2045 /* If security calls are not supported (presumably because we
2046 are running under Windows 9X), fallback to this: */
2047 else if (GetUserName (uname
, &ulength
))
2049 strcpy (dflt_passwd
.pw_name
, uname
);
2050 if (xstrcasecmp ("administrator", uname
) == 0)
2051 dflt_passwd
.pw_uid
= 0;
2053 dflt_passwd
.pw_uid
= 123;
2054 dflt_passwd
.pw_gid
= dflt_passwd
.pw_uid
;
2058 strcpy (dflt_passwd
.pw_name
, "unknown");
2059 dflt_passwd
.pw_uid
= 123;
2060 dflt_passwd
.pw_gid
= 123;
2062 dflt_group
.gr_gid
= dflt_passwd
.pw_gid
;
2064 /* Set dir and shell from environment variables. */
2065 if (w32_unicode_filenames
)
2067 wchar_t *home
= _wgetenv (L
"HOME");
2068 wchar_t *shell
= _wgetenv (L
"SHELL");
2070 /* Ensure HOME and SHELL are defined. */
2075 filename_from_utf16 (home
, dflt_passwd
.pw_dir
);
2076 filename_from_utf16 (shell
, dflt_passwd
.pw_shell
);
2080 char *home
= getenv ("HOME");
2081 char *shell
= getenv ("SHELL");
2087 filename_from_ansi (home
, dflt_passwd
.pw_dir
);
2088 filename_from_ansi (shell
, dflt_passwd
.pw_shell
);
2093 CloseHandle (token
);
2099 /* rand () on NT gives us 15 random bits...hack together 30 bits. */
2100 return ((rand () << 15) | rand ());
2109 /* Return the maximum length in bytes of a multibyte character
2110 sequence encoded in the current ANSI codepage. This is required to
2111 correctly walk the encoded file names one character at a time. */
2113 max_filename_mbslen (void)
2117 codepage_for_filenames (&cp_info
);
2118 return cp_info
.MaxCharSize
;
2121 /* Normalize filename by converting in-place all of its path
2122 separators to the separator specified by PATH_SEP. */
2125 normalize_filename (register char *fp
, char path_sep
)
2129 /* Always lower-case drive letters a-z, even if the filesystem
2130 preserves case in filenames.
2131 This is so filenames can be compared by string comparison
2132 functions that are case-sensitive. Even case-preserving filesystems
2133 do not distinguish case in drive letters. */
2136 if (*p2
== ':' && *fp
>= 'A' && *fp
<= 'Z')
2144 if ((*fp
== '/' || *fp
== '\\') && *fp
!= path_sep
)
2150 /* Destructively turn backslashes into slashes. */
2152 dostounix_filename (register char *p
)
2154 normalize_filename (p
, '/');
2157 /* Destructively turn slashes into backslashes. */
2159 unixtodos_filename (register char *p
)
2161 normalize_filename (p
, '\\');
2164 /* Remove all CR's that are followed by a LF.
2165 (From msdos.c...probably should figure out a way to share it,
2166 although this code isn't going to ever change.) */
2168 crlf_to_lf (register int n
, register unsigned char *buf
)
2170 unsigned char *np
= buf
;
2171 unsigned char *startp
= buf
;
2172 unsigned char *endp
= buf
+ n
;
2176 while (buf
< endp
- 1)
2180 if (*(++buf
) != 0x0a)
2191 /* Parse the root part of file name, if present. Return length and
2192 optionally store pointer to char after root. */
2194 parse_root (const char * name
, const char ** pPath
)
2196 const char * start
= name
;
2201 /* find the root name of the volume if given */
2202 if (isalpha (name
[0]) && name
[1] == ':')
2204 /* skip past drive specifier */
2206 if (IS_DIRECTORY_SEP (name
[0]))
2209 else if (IS_DIRECTORY_SEP (name
[0]) && IS_DIRECTORY_SEP (name
[1]))
2216 if (IS_DIRECTORY_SEP (*name
) && --slashes
== 0)
2221 if (IS_DIRECTORY_SEP (name
[0]))
2228 return name
- start
;
2231 /* Get long base name for name; name is assumed to be absolute. */
2233 get_long_basename (char * name
, char * buf
, int size
)
2235 HANDLE dir_handle
= INVALID_HANDLE_VALUE
;
2236 char fname_utf8
[MAX_UTF8_PATH
];
2240 /* Must be valid filename, no wild cards or other invalid characters. */
2241 if (strpbrk (name
, "*?|<>\""))
2244 if (w32_unicode_filenames
)
2246 wchar_t fname_utf16
[MAX_PATH
];
2247 WIN32_FIND_DATAW find_data_wide
;
2249 filename_to_utf16 (name
, fname_utf16
);
2250 dir_handle
= FindFirstFileW (fname_utf16
, &find_data_wide
);
2251 if (dir_handle
!= INVALID_HANDLE_VALUE
)
2252 cstatus
= filename_from_utf16 (find_data_wide
.cFileName
, fname_utf8
);
2256 char fname_ansi
[MAX_PATH
];
2257 WIN32_FIND_DATAA find_data_ansi
;
2259 filename_to_ansi (name
, fname_ansi
);
2260 /* If the ANSI name includes ? characters, it is not encodable
2261 in the ANSI codepage. In that case, we deliver the question
2262 marks to the caller; calling FindFirstFileA in this case
2263 could return some unrelated file name in the same
2265 if (_mbspbrk (fname_ansi
, "?"))
2267 /* Find the basename of fname_ansi. */
2268 char *p
= strrchr (fname_ansi
, '\\');
2274 cstatus
= filename_from_ansi (p
, fname_utf8
);
2278 dir_handle
= FindFirstFileA (fname_ansi
, &find_data_ansi
);
2279 if (dir_handle
!= INVALID_HANDLE_VALUE
)
2280 cstatus
= filename_from_ansi (find_data_ansi
.cFileName
, fname_utf8
);
2284 if (cstatus
== 0 && (len
= strlen (fname_utf8
)) < size
)
2285 memcpy (buf
, fname_utf8
, len
+ 1);
2289 if (dir_handle
!= INVALID_HANDLE_VALUE
)
2290 FindClose (dir_handle
);
2295 /* Get long name for file, if possible (assumed to be absolute). */
2297 w32_get_long_filename (const char * name
, char * buf
, int size
)
2302 char full
[ MAX_UTF8_PATH
];
2305 len
= strlen (name
);
2306 if (len
>= MAX_UTF8_PATH
)
2309 /* Use local copy for destructive modification. */
2310 memcpy (full
, name
, len
+1);
2311 unixtodos_filename (full
);
2313 /* Copy root part verbatim. */
2314 len
= parse_root (full
, (const char **)&p
);
2315 memcpy (o
, full
, len
);
2320 while (p
!= NULL
&& *p
)
2323 p
= strchr (q
, '\\');
2325 len
= get_long_basename (full
, o
, size
);
2348 w32_get_short_filename (const char * name
, char * buf
, int size
)
2350 if (w32_unicode_filenames
)
2352 wchar_t name_utf16
[MAX_PATH
], short_name
[MAX_PATH
];
2353 unsigned int retval
;
2355 filename_to_utf16 (name
, name_utf16
);
2356 retval
= GetShortPathNameW (name_utf16
, short_name
, size
);
2357 if (retval
&& retval
< size
)
2358 filename_from_utf16 (short_name
, buf
);
2363 char name_ansi
[MAX_PATH
];
2365 filename_to_ansi (name
, name_ansi
);
2366 return GetShortPathNameA (name_ansi
, buf
, size
);
2370 /* Re-encode FILENAME, a UTF-8 encoded unibyte string, using the
2371 MS-Windows ANSI codepage. If FILENAME includes characters not
2372 supported by the ANSI codepage, return the 8+3 alias of FILENAME,
2373 if it exists. This is needed because the w32 build wants to
2374 support file names outside of the system locale, but image
2375 libraries typically don't support wide (a.k.a. "Unicode") APIs
2376 required for that. */
2379 ansi_encode_filename (Lisp_Object filename
)
2381 Lisp_Object encoded_filename
;
2382 char fname
[MAX_PATH
];
2384 filename_to_ansi (SSDATA (filename
), fname
);
2385 if (_mbspbrk (fname
, "?"))
2387 char shortname
[MAX_PATH
];
2389 if (w32_get_short_filename (SDATA (filename
), shortname
, MAX_PATH
))
2391 dostounix_filename (shortname
);
2392 encoded_filename
= build_string (shortname
);
2395 encoded_filename
= build_unibyte_string (fname
);
2398 encoded_filename
= build_unibyte_string (fname
);
2399 return encoded_filename
;
2403 is_unc_volume (const char *filename
)
2405 const char *ptr
= filename
;
2407 if (!IS_DIRECTORY_SEP (ptr
[0]) || !IS_DIRECTORY_SEP (ptr
[1]) || !ptr
[2])
2410 if (strpbrk (ptr
+ 2, "*?|<>\"\\/"))
2416 /* Emulate the Posix unsetenv. */
2418 unsetenv (const char *name
)
2423 if (name
== NULL
|| *name
== '\0' || strchr (name
, '=') != NULL
)
2428 name_len
= strlen (name
);
2429 /* MS docs says an environment variable cannot be longer than 32K. */
2430 if (name_len
> 32767)
2435 /* It is safe to use 'alloca' with 32K size, since the stack is at
2436 least 2MB, and we set it to 8MB in the link command line. */
2437 var
= alloca (name_len
+ 2);
2438 strncpy (var
, name
, name_len
);
2439 var
[name_len
++] = '=';
2440 var
[name_len
] = '\0';
2441 return _putenv (var
);
2444 /* MS _putenv doesn't support removing a variable when the argument
2445 does not include the '=' character, so we fix that here. */
2447 sys_putenv (char *str
)
2449 const char *const name_end
= strchr (str
, '=');
2451 if (name_end
== NULL
)
2453 /* Remove the variable from the environment. */
2454 return unsetenv (str
);
2457 return _putenv (str
);
2460 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
2463 w32_get_resource (char *key
, LPDWORD lpdwtype
)
2466 HKEY hrootkey
= NULL
;
2469 /* Check both the current user and the local machine to see if
2470 we have any resources. */
2472 if (RegOpenKeyEx (HKEY_CURRENT_USER
, REG_ROOT
, 0, KEY_READ
, &hrootkey
) == ERROR_SUCCESS
)
2476 if (RegQueryValueEx (hrootkey
, key
, NULL
, NULL
, NULL
, &cbData
) == ERROR_SUCCESS
2477 && (lpvalue
= xmalloc (cbData
)) != NULL
2478 && RegQueryValueEx (hrootkey
, key
, NULL
, lpdwtype
, lpvalue
, &cbData
) == ERROR_SUCCESS
)
2480 RegCloseKey (hrootkey
);
2486 RegCloseKey (hrootkey
);
2489 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE
, REG_ROOT
, 0, KEY_READ
, &hrootkey
) == ERROR_SUCCESS
)
2493 if (RegQueryValueEx (hrootkey
, key
, NULL
, NULL
, NULL
, &cbData
) == ERROR_SUCCESS
2494 && (lpvalue
= xmalloc (cbData
)) != NULL
2495 && RegQueryValueEx (hrootkey
, key
, NULL
, lpdwtype
, lpvalue
, &cbData
) == ERROR_SUCCESS
)
2497 RegCloseKey (hrootkey
);
2503 RegCloseKey (hrootkey
);
2509 /* The argv[] array holds ANSI-encoded strings, and so this function
2510 works with ANS_encoded strings. */
2512 init_environment (char ** argv
)
2514 static const char * const tempdirs
[] = {
2515 "$TMPDIR", "$TEMP", "$TMP", "c:/"
2520 const int imax
= ARRAYELTS (tempdirs
);
2522 /* Implementation note: This function explicitly works with ANSI
2523 file names, not with UTF-8 encoded file names. This is because
2524 this function pushes variables into the Emacs's environment, and
2525 the environment variables are always assumed to be in the
2526 locale-specific encoding. Do NOT call any functions that accept
2527 UTF-8 file names from this function! */
2529 /* Make sure they have a usable $TMPDIR. Many Emacs functions use
2530 temporary files and assume "/tmp" if $TMPDIR is unset, which
2531 will break on DOS/Windows. Refuse to work if we cannot find
2532 a directory, not even "c:/", usable for that purpose. */
2533 for (i
= 0; i
< imax
; i
++)
2535 const char *tmp
= tempdirs
[i
];
2538 tmp
= getenv (tmp
+ 1);
2539 /* Note that `access' can lie to us if the directory resides on a
2540 read-only filesystem, like CD-ROM or a write-protected floppy.
2541 The only way to be really sure is to actually create a file and
2542 see if it succeeds. But I think that's too much to ask. */
2544 /* MSVCRT's _access crashes with D_OK, so we use our replacement. */
2545 if (tmp
&& sys_access (tmp
, D_OK
) == 0)
2547 char * var
= alloca (strlen (tmp
) + 8);
2548 sprintf (var
, "TMPDIR=%s", tmp
);
2549 _putenv (strdup (var
));
2556 Fcons (build_string ("no usable temporary directories found!!"),
2558 "While setting TMPDIR: ");
2560 /* Check for environment variables and use registry settings if they
2561 don't exist. Fallback on default values where applicable. */
2566 char locale_name
[32];
2567 char default_home
[MAX_PATH
];
2570 static const struct env_entry
2576 /* If the default value is NULL, we will use the value from the
2577 outside environment or the Registry, but will not push the
2578 variable into the Emacs environment if it is defined neither
2579 in the Registry nor in the outside environment. */
2581 {"PRELOAD_WINSOCK", NULL
},
2582 {"emacs_dir", "C:/emacs"},
2583 {"EMACSLOADPATH", NULL
},
2584 {"SHELL", "cmdproxy.exe"}, /* perhaps it is somewhere on PATH */
2585 {"EMACSDATA", NULL
},
2586 {"EMACSPATH", NULL
},
2593 #define N_ENV_VARS ARRAYELTS (dflt_envvars)
2595 /* We need to copy dflt_envvars[] and work on the copy because we
2596 don't want the dumped Emacs to inherit the values of
2597 environment variables we saw during dumping (which could be on
2598 a different system). The defaults above must be left intact. */
2599 struct env_entry env_vars
[N_ENV_VARS
];
2601 for (i
= 0; i
< N_ENV_VARS
; i
++)
2602 env_vars
[i
] = dflt_envvars
[i
];
2604 /* For backwards compatibility, check if a .emacs file exists in C:/
2605 If not, then we can try to default to the appdata directory under the
2606 user's profile, which is more likely to be writable. */
2607 if (sys_access ("C:/.emacs", F_OK
) != 0)
2609 HRESULT profile_result
;
2610 /* Dynamically load ShGetFolderPath, as it won't exist on versions
2611 of Windows 95 and NT4 that have not been updated to include
2613 ShGetFolderPath_fn get_folder_path
;
2614 get_folder_path
= (ShGetFolderPath_fn
)
2615 GetProcAddress (GetModuleHandle ("shell32.dll"), "SHGetFolderPathA");
2617 if (get_folder_path
!= NULL
)
2619 profile_result
= get_folder_path (NULL
, CSIDL_APPDATA
, NULL
,
2622 /* If we can't get the appdata dir, revert to old behavior. */
2623 if (profile_result
== S_OK
)
2625 env_vars
[0].def_value
= default_home
;
2631 /* Get default locale info and use it for LANG. */
2632 if (GetLocaleInfo (LOCALE_USER_DEFAULT
,
2633 LOCALE_SABBREVLANGNAME
| LOCALE_USE_CP_ACP
,
2634 locale_name
, sizeof (locale_name
)))
2636 for (i
= 0; i
< N_ENV_VARS
; i
++)
2638 if (strcmp (env_vars
[i
].name
, "LANG") == 0)
2640 env_vars
[i
].def_value
= locale_name
;
2646 #define SET_ENV_BUF_SIZE (4 * MAX_PATH) /* to cover EMACSLOADPATH */
2648 /* Treat emacs_dir specially: set it unconditionally based on our
2652 char modname
[MAX_PATH
];
2654 if (!GetModuleFileNameA (NULL
, modname
, MAX_PATH
))
2656 if ((p
= _mbsrchr (modname
, '\\')) == NULL
)
2660 if ((p
= _mbsrchr (modname
, '\\'))
2661 /* From bin means installed Emacs, from src means uninstalled. */
2662 && (xstrcasecmp (p
, "\\bin") == 0 || xstrcasecmp (p
, "\\src") == 0))
2664 char buf
[SET_ENV_BUF_SIZE
];
2665 int within_build_tree
= xstrcasecmp (p
, "\\src") == 0;
2668 for (p
= modname
; *p
; p
= CharNext (p
))
2669 if (*p
== '\\') *p
= '/';
2671 _snprintf (buf
, sizeof (buf
)-1, "emacs_dir=%s", modname
);
2672 _putenv (strdup (buf
));
2673 /* If we are running from the Posix-like build tree, define
2674 SHELL to point to our own cmdproxy. The loop below will
2675 then disregard PATH_EXEC and the default value. */
2676 if (within_build_tree
)
2678 _snprintf (buf
, sizeof (buf
) - 1,
2679 "SHELL=%s/nt/cmdproxy.exe", modname
);
2680 _putenv (strdup (buf
));
2685 for (i
= 0; i
< N_ENV_VARS
; i
++)
2687 if (!getenv (env_vars
[i
].name
))
2690 char bufc
[SET_ENV_BUF_SIZE
];
2692 if ((lpval
= w32_get_resource (env_vars
[i
].name
, &dwType
)) == NULL
2693 /* Also ignore empty environment variables. */
2698 if (strcmp (env_vars
[i
].name
, "SHELL") == 0)
2700 /* Look for cmdproxy.exe in every directory in
2701 PATH_EXEC. FIXME: This does not find cmdproxy
2702 in nt/ when we run uninstalled. */
2703 char fname
[MAX_PATH
];
2704 const char *pstart
= PATH_EXEC
, *pend
;
2707 pend
= _mbschr (pstart
, ';');
2709 pend
= pstart
+ strlen (pstart
);
2710 /* Be defensive against series of ;;; characters. */
2713 strncpy (fname
, pstart
, pend
- pstart
);
2714 fname
[pend
- pstart
] = '/';
2715 strcpy (&fname
[pend
- pstart
+ 1], "cmdproxy.exe");
2716 ExpandEnvironmentStrings ((LPSTR
) fname
, bufc
,
2718 if (sys_access (bufc
, F_OK
) == 0)
2731 /* If not found in any directory, use the
2732 default as the last resort. */
2733 lpval
= env_vars
[i
].def_value
;
2734 dwType
= REG_EXPAND_SZ
;
2740 lpval
= env_vars
[i
].def_value
;
2741 dwType
= REG_EXPAND_SZ
;
2743 if (strcmp (env_vars
[i
].name
, "HOME") == 0 && !appdata
)
2744 Vdelayed_warnings_list
2745 = Fcons (listn (CONSTYPE_HEAP
, 2,
2746 intern ("initialization"),
2747 build_string ("Setting HOME to C:\\ by default is deprecated")),
2748 Vdelayed_warnings_list
);
2753 char buf1
[SET_ENV_BUF_SIZE
], buf2
[SET_ENV_BUF_SIZE
];
2755 if (dwType
== REG_EXPAND_SZ
)
2756 ExpandEnvironmentStrings ((LPSTR
) lpval
, buf1
, sizeof (buf1
));
2757 else if (dwType
== REG_SZ
)
2758 strcpy (buf1
, lpval
);
2759 if (dwType
== REG_EXPAND_SZ
|| dwType
== REG_SZ
)
2761 _snprintf (buf2
, sizeof (buf2
)-1, "%s=%s", env_vars
[i
].name
,
2763 _putenv (strdup (buf2
));
2773 /* Rebuild system configuration to reflect invoking system. */
2774 Vsystem_configuration
= build_string (EMACS_CONFIGURATION
);
2776 /* Another special case: on NT, the PATH variable is actually named
2777 "Path" although cmd.exe (perhaps NT itself) arranges for
2778 environment variable lookup and setting to be case insensitive.
2779 However, Emacs assumes a fully case sensitive environment, so we
2780 need to change "Path" to "PATH" to match the expectations of
2781 various elisp packages. We do this by the sneaky method of
2782 modifying the string in the C runtime environ entry.
2784 The same applies to COMSPEC. */
2788 for (envp
= environ
; *envp
; envp
++)
2789 if (_strnicmp (*envp
, "PATH=", 5) == 0)
2790 memcpy (*envp
, "PATH=", 5);
2791 else if (_strnicmp (*envp
, "COMSPEC=", 8) == 0)
2792 memcpy (*envp
, "COMSPEC=", 8);
2795 /* Remember the initial working directory for getcwd. */
2796 /* FIXME: Do we need to resolve possible symlinks in startup_dir?
2797 Does it matter anywhere in Emacs? */
2798 if (w32_unicode_filenames
)
2800 wchar_t wstartup_dir
[MAX_PATH
];
2802 if (!GetCurrentDirectoryW (MAX_PATH
, wstartup_dir
))
2804 filename_from_utf16 (wstartup_dir
, startup_dir
);
2808 char astartup_dir
[MAX_PATH
];
2810 if (!GetCurrentDirectoryA (MAX_PATH
, astartup_dir
))
2812 filename_from_ansi (astartup_dir
, startup_dir
);
2816 static char modname
[MAX_PATH
];
2818 if (!GetModuleFileNameA (NULL
, modname
, MAX_PATH
))
2823 /* Determine if there is a middle mouse button, to allow parse_button
2824 to decide whether right mouse events should be mouse-2 or
2826 w32_num_mouse_buttons
= GetSystemMetrics (SM_CMOUSEBUTTONS
);
2831 /* Called from expand-file-name when default-directory is not a string. */
2834 emacs_root_dir (void)
2836 static char root_dir
[MAX_UTF8_PATH
];
2839 p
= getenv ("emacs_dir");
2842 filename_from_ansi (p
, root_dir
);
2843 root_dir
[parse_root (root_dir
, NULL
)] = '\0';
2844 dostounix_filename (root_dir
);
2848 #include <sys/timeb.h>
2850 /* Emulate gettimeofday (Ulrich Leodolter, 1/11/95). */
2852 gettimeofday (struct timeval
*__restrict tv
, struct timezone
*__restrict tz
)
2857 tv
->tv_sec
= tb
.time
;
2858 tv
->tv_usec
= tb
.millitm
* 1000L;
2859 /* Implementation note: _ftime sometimes doesn't update the dstflag
2860 according to the new timezone when the system timezone is
2861 changed. We could fix that by using GetSystemTime and
2862 GetTimeZoneInformation, but that doesn't seem necessary, since
2863 Emacs always calls gettimeofday with the 2nd argument NULL (see
2864 current_emacs_time). */
2867 tz
->tz_minuteswest
= tb
.timezone
; /* minutes west of Greenwich */
2868 tz
->tz_dsttime
= tb
.dstflag
; /* type of dst correction */
2873 /* Emulate fdutimens. */
2875 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2876 TIMESPEC[0] and TIMESPEC[1], respectively.
2877 FD must be either negative -- in which case it is ignored --
2878 or a file descriptor that is open on FILE.
2879 If FD is nonnegative, then FILE can be NULL, which means
2880 use just futimes instead of utimes.
2881 If TIMESPEC is null, FAIL.
2882 Return 0 on success, -1 (setting errno) on failure. */
2885 fdutimens (int fd
, char const *file
, struct timespec
const timespec
[2])
2892 if (fd
< 0 && !file
)
2897 /* _futime's prototype defines 2nd arg as having the type 'struct
2898 _utimbuf', while utime needs to accept 'struct utimbuf' for
2899 compatibility with Posix. So we need to use 2 different (but
2900 equivalent) types to avoid compiler warnings, sigh. */
2903 struct _utimbuf _ut
;
2905 _ut
.actime
= timespec
[0].tv_sec
;
2906 _ut
.modtime
= timespec
[1].tv_sec
;
2907 return _futime (fd
, &_ut
);
2913 ut
.actime
= timespec
[0].tv_sec
;
2914 ut
.modtime
= timespec
[1].tv_sec
;
2915 /* Call 'utime', which is implemented below, not the MS library
2916 function, which fails on directories. */
2917 return utime (file
, &ut
);
2922 /* ------------------------------------------------------------------------- */
2923 /* IO support and wrapper functions for the Windows API. */
2924 /* ------------------------------------------------------------------------- */
2926 /* Place a wrapper around the MSVC version of ctime. It returns NULL
2927 on network directories, so we handle that case here.
2928 (Ulrich Leodolter, 1/11/95). */
2930 sys_ctime (const time_t *t
)
2932 char *str
= (char *) ctime (t
);
2933 return (str
? str
: "Sun Jan 01 00:00:00 1970");
2936 /* Emulate sleep...we could have done this with a define, but that
2937 would necessitate including windows.h in the files that used it.
2938 This is much easier. */
2940 sys_sleep (int seconds
)
2942 Sleep (seconds
* 1000);
2945 /* Internal MSVC functions for low-level descriptor munging */
2946 extern int __cdecl
_set_osfhnd (int fd
, long h
);
2947 extern int __cdecl
_free_osfhnd (int fd
);
2949 /* parallel array of private info on file handles */
2950 filedesc fd_info
[ MAXDESC
];
2952 typedef struct volume_info_data
{
2953 struct volume_info_data
* next
;
2955 /* time when info was obtained */
2958 /* actual volume info */
2967 /* Global referenced by various functions. */
2968 static volume_info_data volume_info
;
2970 /* Vector to indicate which drives are local and fixed (for which cached
2971 data never expires). */
2972 static BOOL fixed_drives
[26];
2974 /* Consider cached volume information to be stale if older than 10s,
2975 at least for non-local drives. Info for fixed drives is never stale. */
2976 #define DRIVE_INDEX( c ) ( (c) <= 'Z' ? (c) - 'A' : (c) - 'a' )
2977 #define VOLINFO_STILL_VALID( root_dir, info ) \
2978 ( ( isalpha (root_dir[0]) && \
2979 fixed_drives[ DRIVE_INDEX (root_dir[0]) ] ) \
2980 || GetTickCount () - info->timestamp < 10000 )
2982 /* Cache support functions. */
2984 /* Simple linked list with linear search is sufficient. */
2985 static volume_info_data
*volume_cache
= NULL
;
2987 static volume_info_data
*
2988 lookup_volume_info (char * root_dir
)
2990 volume_info_data
* info
;
2992 for (info
= volume_cache
; info
; info
= info
->next
)
2993 if (xstrcasecmp (info
->root_dir
, root_dir
) == 0)
2999 add_volume_info (char * root_dir
, volume_info_data
* info
)
3001 info
->root_dir
= xstrdup (root_dir
);
3002 unixtodos_filename (info
->root_dir
);
3003 info
->next
= volume_cache
;
3004 volume_cache
= info
;
3008 /* Wrapper for GetVolumeInformation, which uses caching to avoid
3009 performance penalty (~2ms on 486 for local drives, 7.5ms for local
3010 cdrom drive, ~5-10ms or more for remote drives on LAN). */
3011 static volume_info_data
*
3012 GetCachedVolumeInformation (char * root_dir
)
3014 volume_info_data
* info
;
3015 char default_root
[ MAX_UTF8_PATH
];
3016 char name
[MAX_PATH
+1];
3017 char type
[MAX_PATH
+1];
3019 /* NULL for root_dir means use root from current directory. */
3020 if (root_dir
== NULL
)
3022 if (w32_unicode_filenames
)
3024 wchar_t curdirw
[MAX_PATH
];
3026 if (GetCurrentDirectoryW (MAX_PATH
, curdirw
) == 0)
3028 filename_from_utf16 (curdirw
, default_root
);
3032 char curdira
[MAX_PATH
];
3034 if (GetCurrentDirectoryA (MAX_PATH
, curdira
) == 0)
3036 filename_from_ansi (curdira
, default_root
);
3038 parse_root (default_root
, (const char **)&root_dir
);
3040 root_dir
= default_root
;
3043 /* Local fixed drives can be cached permanently. Removable drives
3044 cannot be cached permanently, since the volume name and serial
3045 number (if nothing else) can change. Remote drives should be
3046 treated as if they are removable, since there is no sure way to
3047 tell whether they are or not. Also, the UNC association of drive
3048 letters mapped to remote volumes can be changed at any time (even
3049 by other processes) without notice.
3051 As a compromise, so we can benefit from caching info for remote
3052 volumes, we use a simple expiry mechanism to invalidate cache
3053 entries that are more than ten seconds old. */
3056 /* No point doing this, because WNetGetConnection is even slower than
3057 GetVolumeInformation, consistently taking ~50ms on a 486 (FWIW,
3058 GetDriveType is about the only call of this type which does not
3059 involve network access, and so is extremely quick). */
3061 /* Map drive letter to UNC if remote. */
3062 if (isalpha (root_dir
[0]) && !fixed
[DRIVE_INDEX (root_dir
[0])])
3064 char remote_name
[ 256 ];
3065 char drive
[3] = { root_dir
[0], ':' };
3067 if (WNetGetConnection (drive
, remote_name
, sizeof (remote_name
))
3069 /* do something */ ;
3073 info
= lookup_volume_info (root_dir
);
3075 if (info
== NULL
|| ! VOLINFO_STILL_VALID (root_dir
, info
))
3081 /* Info is not cached, or is stale. */
3082 if (w32_unicode_filenames
)
3084 wchar_t root_w
[MAX_PATH
];
3085 wchar_t name_w
[MAX_PATH
+1];
3086 wchar_t type_w
[MAX_PATH
+1];
3088 filename_to_utf16 (root_dir
, root_w
);
3089 if (!GetVolumeInformationW (root_w
,
3090 name_w
, sizeof (name_w
),
3094 type_w
, sizeof (type_w
)))
3096 /* Hmm... not really 100% correct, as these 2 are not file
3098 filename_from_utf16 (name_w
, name
);
3099 filename_from_utf16 (type_w
, type
);
3103 char root_a
[MAX_PATH
];
3104 char name_a
[MAX_PATH
+1];
3105 char type_a
[MAX_PATH
+1];
3107 filename_to_ansi (root_dir
, root_a
);
3108 if (!GetVolumeInformationA (root_a
,
3109 name_a
, sizeof (name_a
),
3113 type_a
, sizeof (type_a
)))
3115 filename_from_ansi (name_a
, name
);
3116 filename_from_ansi (type_a
, type
);
3119 /* Cache the volume information for future use, overwriting existing
3120 entry if present. */
3123 info
= xmalloc (sizeof (volume_info_data
));
3124 add_volume_info (root_dir
, info
);
3132 info
->name
= xstrdup (name
);
3133 unixtodos_filename (info
->name
);
3134 info
->serialnum
= serialnum
;
3135 info
->maxcomp
= maxcomp
;
3136 info
->flags
= flags
;
3137 info
->type
= xstrdup (type
);
3138 info
->timestamp
= GetTickCount ();
3144 /* Get information on the volume where NAME is held; set path pointer to
3145 start of pathname in NAME (past UNC header\volume header if present),
3146 if pPath is non-NULL.
3148 Note: if NAME includes symlinks, the information is for the volume
3149 of the symlink, not of its target. That's because, even though
3150 GetVolumeInformation returns information about the symlink target
3151 of its argument, we only pass the root directory to
3152 GetVolumeInformation, not the full NAME. */
3154 get_volume_info (const char * name
, const char ** pPath
)
3156 char temp
[MAX_UTF8_PATH
];
3157 char *rootname
= NULL
; /* default to current volume */
3158 volume_info_data
* info
;
3159 int root_len
= parse_root (name
, pPath
);
3164 /* Copy the root name of the volume, if given. */
3167 strncpy (temp
, name
, root_len
);
3168 temp
[root_len
] = '\0';
3169 unixtodos_filename (temp
);
3173 info
= GetCachedVolumeInformation (rootname
);
3176 /* Set global referenced by other functions. */
3177 volume_info
= *info
;
3183 /* Determine if volume is FAT format (ie. only supports short 8.3
3184 names); also set path pointer to start of pathname in name, if
3185 pPath is non-NULL. */
3187 is_fat_volume (const char * name
, const char ** pPath
)
3189 if (get_volume_info (name
, pPath
))
3190 return (volume_info
.maxcomp
== 12);
3194 /* Convert all slashes in a filename to backslashes, and map filename
3195 to a valid 8.3 name if necessary. The result is a pointer to a
3196 static buffer, so CAVEAT EMPTOR! */
3198 map_w32_filename (const char * name
, const char ** pPath
)
3200 static char shortname
[MAX_UTF8_PATH
];
3201 char * str
= shortname
;
3204 const char * save_name
= name
;
3206 if (strlen (name
) >= sizeof (shortname
))
3208 /* Return a filename which will cause callers to fail. */
3209 strcpy (shortname
, "?");
3213 if (is_fat_volume (name
, (const char **)&path
)) /* truncate to 8.3 */
3215 register int left
= 8; /* maximum number of chars in part */
3216 register int extn
= 0; /* extension added? */
3217 register int dots
= 2; /* maximum number of dots allowed */
3220 *str
++ = *name
++; /* skip past UNC header */
3222 while ((c
= *name
++))
3229 *str
++ = (c
== ':' ? ':' : '\\');
3230 extn
= 0; /* reset extension flags */
3231 dots
= 2; /* max 2 dots */
3232 left
= 8; /* max length 8 for main part */
3237 /* Convert path components of the form .xxx to _xxx,
3238 but leave . and .. as they are. This allows .emacs
3239 to be read as _emacs, for example. */
3243 IS_DIRECTORY_SEP (*name
))
3258 extn
= 1; /* we've got an extension */
3259 left
= 3; /* 3 chars in extension */
3263 /* any embedded dots after the first are converted to _ */
3268 case '#': /* don't lose these, they're important */
3270 str
[-1] = c
; /* replace last character of part */
3273 if ( left
&& 'A' <= c
&& c
<= 'Z' )
3275 *str
++ = tolower (c
); /* map to lower case (looks nicer) */
3277 dots
= 0; /* started a path component */
3286 strcpy (shortname
, name
);
3287 unixtodos_filename (shortname
);
3291 *pPath
= shortname
+ (path
- save_name
);
3297 is_exec (const char * name
)
3299 char * p
= strrchr (name
, '.');
3302 && (xstrcasecmp (p
, ".exe") == 0 ||
3303 xstrcasecmp (p
, ".com") == 0 ||
3304 xstrcasecmp (p
, ".bat") == 0 ||
3305 xstrcasecmp (p
, ".cmd") == 0));
3308 /* Emulate the Unix directory procedures opendir, closedir, and
3309 readdir. We rename them to sys_* names because some versions of
3310 MinGW startup code call opendir and readdir to glob wildcards, and
3311 the code that calls them doesn't grok UTF-8 encoded file names we
3312 produce in dirent->d_name[]. */
3314 struct dirent dir_static
; /* simulated directory contents */
3315 static HANDLE dir_find_handle
= INVALID_HANDLE_VALUE
;
3316 static int dir_is_fat
;
3317 static char dir_pathname
[MAX_UTF8_PATH
];
3318 static WIN32_FIND_DATAW dir_find_data_w
;
3319 static WIN32_FIND_DATAA dir_find_data_a
;
3320 #define DIR_FIND_DATA_W 1
3321 #define DIR_FIND_DATA_A 2
3322 static int last_dir_find_data
= -1;
3324 /* Support shares on a network resource as subdirectories of a read-only
3326 static HANDLE wnet_enum_handle
= INVALID_HANDLE_VALUE
;
3327 static HANDLE
open_unc_volume (const char *);
3328 static void *read_unc_volume (HANDLE
, wchar_t *, char *, int);
3329 static void close_unc_volume (HANDLE
);
3332 sys_opendir (const char *filename
)
3336 /* Opening is done by FindFirstFile. However, a read is inherent to
3337 this operation, so we defer the open until read time. */
3339 if (dir_find_handle
!= INVALID_HANDLE_VALUE
)
3341 if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
3344 /* Note: We don't support traversal of UNC volumes via symlinks.
3345 Doing so would mean punishing 99.99% of use cases by resolving
3346 all the possible symlinks in FILENAME, recursively. */
3347 if (is_unc_volume (filename
))
3349 wnet_enum_handle
= open_unc_volume (filename
);
3350 if (wnet_enum_handle
== INVALID_HANDLE_VALUE
)
3354 if (!(dirp
= (DIR *) malloc (sizeof (DIR))))
3361 strncpy (dir_pathname
, map_w32_filename (filename
, NULL
), MAX_UTF8_PATH
- 1);
3362 dir_pathname
[MAX_UTF8_PATH
- 1] = '\0';
3363 /* Note: We don't support symlinks to file names on FAT volumes.
3364 Doing so would mean punishing 99.99% of use cases by resolving
3365 all the possible symlinks in FILENAME, recursively. */
3366 dir_is_fat
= is_fat_volume (filename
, NULL
);
3372 sys_closedir (DIR *dirp
)
3374 /* If we have a find-handle open, close it. */
3375 if (dir_find_handle
!= INVALID_HANDLE_VALUE
)
3377 FindClose (dir_find_handle
);
3378 dir_find_handle
= INVALID_HANDLE_VALUE
;
3380 else if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
3382 close_unc_volume (wnet_enum_handle
);
3383 wnet_enum_handle
= INVALID_HANDLE_VALUE
;
3385 xfree ((char *) dirp
);
3389 sys_readdir (DIR *dirp
)
3391 int downcase
= !NILP (Vw32_downcase_file_names
);
3393 if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
3395 if (!read_unc_volume (wnet_enum_handle
,
3396 dir_find_data_w
.cFileName
,
3397 dir_find_data_a
.cFileName
,
3401 /* If we aren't dir_finding, do a find-first, otherwise do a find-next. */
3402 else if (dir_find_handle
== INVALID_HANDLE_VALUE
)
3404 char filename
[MAX_UTF8_PATH
+ 2];
3407 strcpy (filename
, dir_pathname
);
3408 ln
= strlen (filename
);
3409 if (!IS_DIRECTORY_SEP (filename
[ln
- 1]))
3410 filename
[ln
++] = '\\';
3411 strcpy (filename
+ ln
, "*");
3413 /* Note: No need to resolve symlinks in FILENAME, because
3414 FindFirst opens the directory that is the target of a
3416 if (w32_unicode_filenames
)
3418 wchar_t fnw
[MAX_PATH
];
3420 filename_to_utf16 (filename
, fnw
);
3421 dir_find_handle
= FindFirstFileW (fnw
, &dir_find_data_w
);
3427 filename_to_ansi (filename
, fna
);
3428 /* If FILENAME is not representable by the current ANSI
3429 codepage, we don't want FindFirstFileA to interpret the
3430 '?' characters as a wildcard. */
3431 if (_mbspbrk (fna
, "?"))
3432 dir_find_handle
= INVALID_HANDLE_VALUE
;
3434 dir_find_handle
= FindFirstFileA (fna
, &dir_find_data_a
);
3437 if (dir_find_handle
== INVALID_HANDLE_VALUE
)
3440 else if (w32_unicode_filenames
)
3442 if (!FindNextFileW (dir_find_handle
, &dir_find_data_w
))
3447 if (!FindNextFileA (dir_find_handle
, &dir_find_data_a
))
3451 /* Emacs never uses this value, so don't bother making it match
3452 value returned by stat(). */
3453 dir_static
.d_ino
= 1;
3455 if (w32_unicode_filenames
)
3457 if (downcase
|| dir_is_fat
)
3459 wchar_t tem
[MAX_PATH
];
3461 wcscpy (tem
, dir_find_data_w
.cFileName
);
3463 filename_from_utf16 (tem
, dir_static
.d_name
);
3466 filename_from_utf16 (dir_find_data_w
.cFileName
, dir_static
.d_name
);
3467 last_dir_find_data
= DIR_FIND_DATA_W
;
3473 /* If the file name in cFileName[] includes `?' characters, it
3474 means the original file name used characters that cannot be
3475 represented by the current ANSI codepage. To avoid total
3476 lossage, retrieve the short 8+3 alias of the long file
3478 if (_mbspbrk (dir_find_data_a
.cFileName
, "?"))
3480 strcpy (tem
, dir_find_data_a
.cAlternateFileName
);
3481 /* 8+3 aliases are returned in all caps, which could break
3482 various alists that look at filenames' extensions. */
3485 else if (downcase
|| dir_is_fat
)
3486 strcpy (tem
, dir_find_data_a
.cFileName
);
3488 filename_from_ansi (dir_find_data_a
.cFileName
, dir_static
.d_name
);
3489 if (downcase
|| dir_is_fat
)
3492 filename_from_ansi (tem
, dir_static
.d_name
);
3494 last_dir_find_data
= DIR_FIND_DATA_A
;
3497 dir_static
.d_namlen
= strlen (dir_static
.d_name
);
3498 dir_static
.d_reclen
= sizeof (struct dirent
) - MAX_UTF8_PATH
+ 3 +
3499 dir_static
.d_namlen
- dir_static
.d_namlen
% 4;
3505 open_unc_volume (const char *path
)
3507 const char *fn
= map_w32_filename (path
, NULL
);
3511 if (w32_unicode_filenames
)
3514 wchar_t fnw
[MAX_PATH
];
3516 nrw
.dwScope
= RESOURCE_GLOBALNET
;
3517 nrw
.dwType
= RESOURCETYPE_DISK
;
3518 nrw
.dwDisplayType
= RESOURCEDISPLAYTYPE_SERVER
;
3519 nrw
.dwUsage
= RESOURCEUSAGE_CONTAINER
;
3520 nrw
.lpLocalName
= NULL
;
3521 filename_to_utf16 (fn
, fnw
);
3522 nrw
.lpRemoteName
= fnw
;
3523 nrw
.lpComment
= NULL
;
3524 nrw
.lpProvider
= NULL
;
3526 result
= WNetOpenEnumW (RESOURCE_GLOBALNET
, RESOURCETYPE_DISK
,
3527 RESOURCEUSAGE_CONNECTABLE
, &nrw
, &henum
);
3534 nra
.dwScope
= RESOURCE_GLOBALNET
;
3535 nra
.dwType
= RESOURCETYPE_DISK
;
3536 nra
.dwDisplayType
= RESOURCEDISPLAYTYPE_SERVER
;
3537 nra
.dwUsage
= RESOURCEUSAGE_CONTAINER
;
3538 nra
.lpLocalName
= NULL
;
3539 filename_to_ansi (fn
, fna
);
3540 nra
.lpRemoteName
= fna
;
3541 nra
.lpComment
= NULL
;
3542 nra
.lpProvider
= NULL
;
3544 result
= WNetOpenEnumA (RESOURCE_GLOBALNET
, RESOURCETYPE_DISK
,
3545 RESOURCEUSAGE_CONNECTABLE
, &nra
, &henum
);
3547 if (result
== NO_ERROR
)
3550 return INVALID_HANDLE_VALUE
;
3554 read_unc_volume (HANDLE henum
, wchar_t *fname_w
, char *fname_a
, int size
)
3559 DWORD bufsize
= 512;
3563 if (w32_unicode_filenames
)
3568 buffer
= alloca (bufsize
);
3569 result
= WNetEnumResourceW (henum
, &count
, buffer
, &bufsize
);
3570 if (result
!= NO_ERROR
)
3572 /* WNetEnumResource returns \\resource\share...skip forward to "share". */
3573 ptrw
= ((LPNETRESOURCEW
) buffer
)->lpRemoteName
;
3575 while (*ptrw
&& *ptrw
!= L
'/' && *ptrw
!= L
'\\') ptrw
++;
3577 wcsncpy (fname_w
, ptrw
, size
);
3582 int dbcs_p
= max_filename_mbslen () > 1;
3585 buffer
= alloca (bufsize
);
3586 result
= WNetEnumResourceA (henum
, &count
, buffer
, &bufsize
);
3587 if (result
!= NO_ERROR
)
3589 ptra
= ((LPNETRESOURCEA
) buffer
)->lpRemoteName
;
3592 while (*ptra
&& !IS_DIRECTORY_SEP (*ptra
)) ptra
++;
3595 while (*ptra
&& !IS_DIRECTORY_SEP (*ptra
))
3596 ptra
= CharNextExA (file_name_codepage
, ptra
, 0);
3599 strncpy (fname_a
, ptra
, size
);
3607 close_unc_volume (HANDLE henum
)
3609 if (henum
!= INVALID_HANDLE_VALUE
)
3610 WNetCloseEnum (henum
);
3614 unc_volume_file_attributes (const char *path
)
3619 henum
= open_unc_volume (path
);
3620 if (henum
== INVALID_HANDLE_VALUE
)
3623 attrs
= FILE_ATTRIBUTE_READONLY
| FILE_ATTRIBUTE_DIRECTORY
;
3625 close_unc_volume (henum
);
3630 /* Ensure a network connection is authenticated. */
3632 logon_network_drive (const char *path
)
3634 char share
[MAX_UTF8_PATH
];
3641 if (IS_DIRECTORY_SEP (path
[0]) && IS_DIRECTORY_SEP (path
[1]))
3642 drvtype
= DRIVE_REMOTE
;
3643 else if (path
[0] == '\0' || path
[1] != ':')
3644 drvtype
= GetDriveType (NULL
);
3651 drvtype
= GetDriveType (drive
);
3654 /* Only logon to networked drives. */
3655 if (drvtype
!= DRIVE_REMOTE
)
3659 strncpy (share
, path
, MAX_UTF8_PATH
);
3660 /* Truncate to just server and share name. */
3661 for (p
= share
+ 2; *p
&& p
< share
+ MAX_UTF8_PATH
; p
++)
3663 if (IS_DIRECTORY_SEP (*p
) && ++n_slashes
> 3)
3670 if (w32_unicode_filenames
)
3672 NETRESOURCEW resourcew
;
3673 wchar_t share_w
[MAX_PATH
];
3675 resourcew
.dwScope
= RESOURCE_GLOBALNET
;
3676 resourcew
.dwType
= RESOURCETYPE_DISK
;
3677 resourcew
.dwDisplayType
= RESOURCEDISPLAYTYPE_SHARE
;
3678 resourcew
.dwUsage
= RESOURCEUSAGE_CONTAINER
;
3679 resourcew
.lpLocalName
= NULL
;
3680 filename_to_utf16 (share
, share_w
);
3681 resourcew
.lpRemoteName
= share_w
;
3682 resourcew
.lpProvider
= NULL
;
3684 val
= WNetAddConnection2W (&resourcew
, NULL
, NULL
, CONNECT_INTERACTIVE
);
3688 NETRESOURCEA resourcea
;
3689 char share_a
[MAX_PATH
];
3691 resourcea
.dwScope
= RESOURCE_GLOBALNET
;
3692 resourcea
.dwType
= RESOURCETYPE_DISK
;
3693 resourcea
.dwDisplayType
= RESOURCEDISPLAYTYPE_SHARE
;
3694 resourcea
.dwUsage
= RESOURCEUSAGE_CONTAINER
;
3695 resourcea
.lpLocalName
= NULL
;
3696 filename_to_ansi (share
, share_a
);
3697 resourcea
.lpRemoteName
= share_a
;
3698 resourcea
.lpProvider
= NULL
;
3700 val
= WNetAddConnection2A (&resourcea
, NULL
, NULL
, CONNECT_INTERACTIVE
);
3706 case ERROR_ALREADY_ASSIGNED
:
3708 case ERROR_ACCESS_DENIED
:
3709 case ERROR_LOGON_FAILURE
:
3715 case ERROR_BAD_NET_NAME
:
3716 case ERROR_NO_NET_OR_BAD_PATH
:
3717 case ERROR_NO_NETWORK
:
3718 case ERROR_CANCELLED
:
3725 /* Emulate faccessat(2). */
3727 faccessat (int dirfd
, const char * path
, int mode
, int flags
)
3731 if (dirfd
!= AT_FDCWD
3732 && !(IS_DIRECTORY_SEP (path
[0])
3733 || IS_DEVICE_SEP (path
[1])))
3739 /* MSVCRT implementation of 'access' doesn't recognize D_OK, and its
3740 newer versions blow up when passed D_OK. */
3741 path
= map_w32_filename (path
, NULL
);
3742 /* If the last element of PATH is a symlink, we need to resolve it
3743 to get the attributes of its target file. Note: any symlinks in
3744 PATH elements other than the last one are transparently resolved
3745 by GetFileAttributes below. */
3746 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) != 0
3747 && (flags
& AT_SYMLINK_NOFOLLOW
) == 0)
3748 path
= chase_symlinks (path
);
3750 if (w32_unicode_filenames
)
3752 wchar_t path_w
[MAX_PATH
];
3754 filename_to_utf16 (path
, path_w
);
3755 attributes
= GetFileAttributesW (path_w
);
3759 char path_a
[MAX_PATH
];
3761 filename_to_ansi (path
, path_a
);
3762 attributes
= GetFileAttributesA (path_a
);
3765 if (attributes
== -1)
3767 DWORD w32err
= GetLastError ();
3771 case ERROR_INVALID_NAME
:
3772 case ERROR_BAD_PATHNAME
:
3773 if (is_unc_volume (path
))
3775 attributes
= unc_volume_file_attributes (path
);
3776 if (attributes
== -1)
3784 case ERROR_FILE_NOT_FOUND
:
3785 case ERROR_BAD_NETPATH
:
3794 if ((mode
& X_OK
) != 0
3795 && !(is_exec (path
) || (attributes
& FILE_ATTRIBUTE_DIRECTORY
) != 0))
3800 if ((mode
& W_OK
) != 0 && (attributes
& FILE_ATTRIBUTE_READONLY
) != 0)
3805 if ((mode
& D_OK
) != 0 && (attributes
& FILE_ATTRIBUTE_DIRECTORY
) == 0)
3813 /* A version of 'access' to be used locally with file names in
3814 locale-specific encoding. Does not resolve symlinks and does not
3815 support file names on FAT12 and FAT16 volumes, but that's OK, since
3816 we only invoke this function for files inside the Emacs source or
3817 installation tree, on directories (so any symlinks should have the
3818 directory bit set), and on short file names such as "C:/.emacs". */
3820 sys_access (const char *fname
, int mode
)
3822 char fname_copy
[MAX_PATH
], *p
;
3825 strcpy (fname_copy
, fname
);
3826 /* Do the equivalent of unixtodos_filename. */
3827 for (p
= fname_copy
; *p
; p
= CharNext (p
))
3831 if ((attributes
= GetFileAttributesA (fname_copy
)) == -1)
3833 DWORD w32err
= GetLastError ();
3837 case ERROR_INVALID_NAME
:
3838 case ERROR_BAD_PATHNAME
:
3839 case ERROR_FILE_NOT_FOUND
:
3840 case ERROR_BAD_NETPATH
:
3849 if ((mode
& X_OK
) != 0
3850 && !(is_exec (fname_copy
)
3851 || (attributes
& FILE_ATTRIBUTE_DIRECTORY
) != 0))
3856 if ((mode
& W_OK
) != 0 && (attributes
& FILE_ATTRIBUTE_READONLY
) != 0)
3861 if ((mode
& D_OK
) != 0 && (attributes
& FILE_ATTRIBUTE_DIRECTORY
) == 0)
3869 /* Shadow some MSVC runtime functions to map requests for long filenames
3870 to reasonable short names if necessary. This was originally added to
3871 permit running Emacs on NT 3.1 on a FAT partition, which doesn't support
3875 sys_chdir (const char * path
)
3877 path
= map_w32_filename (path
, NULL
);
3878 if (w32_unicode_filenames
)
3880 wchar_t newdir_w
[MAX_PATH
];
3882 if (filename_to_utf16 (path
, newdir_w
) == 0)
3883 return _wchdir (newdir_w
);
3888 char newdir_a
[MAX_PATH
];
3890 if (filename_to_ansi (path
, newdir_a
) == 0)
3891 return _chdir (newdir_a
);
3897 sys_chmod (const char * path
, int mode
)
3899 path
= chase_symlinks (map_w32_filename (path
, NULL
));
3900 if (w32_unicode_filenames
)
3902 wchar_t path_w
[MAX_PATH
];
3904 filename_to_utf16 (path
, path_w
);
3905 return _wchmod (path_w
, mode
);
3909 char path_a
[MAX_PATH
];
3911 filename_to_ansi (path
, path_a
);
3912 return _chmod (path_a
, mode
);
3917 sys_creat (const char * path
, int mode
)
3919 path
= map_w32_filename (path
, NULL
);
3920 if (w32_unicode_filenames
)
3922 wchar_t path_w
[MAX_PATH
];
3924 filename_to_utf16 (path
, path_w
);
3925 return _wcreat (path_w
, mode
);
3929 char path_a
[MAX_PATH
];
3931 filename_to_ansi (path
, path_a
);
3932 return _creat (path_a
, mode
);
3937 sys_fopen (const char * path
, const char * mode
)
3941 const char * mode_save
= mode
;
3943 /* Force all file handles to be non-inheritable. This is necessary to
3944 ensure child processes don't unwittingly inherit handles that might
3945 prevent future file access. */
3949 else if (mode
[0] == 'w' || mode
[0] == 'a')
3950 oflag
= O_WRONLY
| O_CREAT
| O_TRUNC
;
3954 /* Only do simplistic option parsing. */
3958 oflag
&= ~(O_RDONLY
| O_WRONLY
);
3961 else if (mode
[0] == 'b')
3966 else if (mode
[0] == 't')
3973 path
= map_w32_filename (path
, NULL
);
3974 if (w32_unicode_filenames
)
3976 wchar_t path_w
[MAX_PATH
];
3978 filename_to_utf16 (path
, path_w
);
3979 fd
= _wopen (path_w
, oflag
| _O_NOINHERIT
, 0644);
3983 char path_a
[MAX_PATH
];
3985 filename_to_ansi (path
, path_a
);
3986 fd
= _open (path_a
, oflag
| _O_NOINHERIT
, 0644);
3991 return _fdopen (fd
, mode_save
);
3994 /* This only works on NTFS volumes, but is useful to have. */
3996 sys_link (const char * old
, const char * new)
4000 char oldname
[MAX_UTF8_PATH
], newname
[MAX_UTF8_PATH
];
4001 wchar_t oldname_w
[MAX_PATH
];
4002 char oldname_a
[MAX_PATH
];
4004 if (old
== NULL
|| new == NULL
)
4010 strcpy (oldname
, map_w32_filename (old
, NULL
));
4011 strcpy (newname
, map_w32_filename (new, NULL
));
4013 if (w32_unicode_filenames
)
4015 filename_to_utf16 (oldname
, oldname_w
);
4016 fileh
= CreateFileW (oldname_w
, 0, 0, NULL
, OPEN_EXISTING
,
4017 FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
4021 filename_to_ansi (oldname
, oldname_a
);
4022 fileh
= CreateFileA (oldname_a
, 0, 0, NULL
, OPEN_EXISTING
,
4023 FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
4025 if (fileh
!= INVALID_HANDLE_VALUE
)
4029 /* Confusingly, the "alternate" stream name field does not apply
4030 when restoring a hard link, and instead contains the actual
4031 stream data for the link (ie. the name of the link to create).
4032 The WIN32_STREAM_ID structure before the cStreamName field is
4033 the stream header, which is then immediately followed by the
4037 WIN32_STREAM_ID wid
;
4038 WCHAR wbuffer
[MAX_PATH
]; /* extra space for link name */
4041 /* We used to pass MB_PRECOMPOSED as the 2nd arg here, but MSDN
4042 indicates that flag is unsupported for CP_UTF8, and OTOH says
4043 it is the default anyway. */
4044 wlen
= pMultiByteToWideChar (CP_UTF8
, 0, newname
, -1,
4045 data
.wid
.cStreamName
, MAX_PATH
);
4048 LPVOID context
= NULL
;
4051 data
.wid
.dwStreamId
= BACKUP_LINK
;
4052 data
.wid
.dwStreamAttributes
= 0;
4053 data
.wid
.Size
.LowPart
= wlen
* sizeof (WCHAR
);
4054 data
.wid
.Size
.HighPart
= 0;
4055 data
.wid
.dwStreamNameSize
= 0;
4057 if (BackupWrite (fileh
, (LPBYTE
)&data
,
4058 offsetof (WIN32_STREAM_ID
, cStreamName
)
4059 + data
.wid
.Size
.LowPart
,
4060 &wbytes
, FALSE
, FALSE
, &context
)
4061 && BackupWrite (fileh
, NULL
, 0, &wbytes
, TRUE
, FALSE
, &context
))
4068 DWORD err
= GetLastError ();
4073 case ERROR_ACCESS_DENIED
:
4074 /* This is what happens when OLDNAME is a directory,
4075 since Windows doesn't support hard links to
4076 directories. Posix says to set errno to EPERM in
4078 if (w32_unicode_filenames
)
4079 attributes
= GetFileAttributesW (oldname_w
);
4081 attributes
= GetFileAttributesA (oldname_a
);
4082 if (attributes
!= -1
4083 && (attributes
& FILE_ATTRIBUTE_DIRECTORY
) != 0)
4085 else if (attributes
== -1
4086 && is_unc_volume (oldname
)
4087 && unc_volume_file_attributes (oldname
) != -1)
4092 case ERROR_TOO_MANY_LINKS
:
4095 case ERROR_NOT_SAME_DEVICE
:
4105 CloseHandle (fileh
);
4114 sys_mkdir (const char * path
)
4116 path
= map_w32_filename (path
, NULL
);
4118 if (w32_unicode_filenames
)
4120 wchar_t path_w
[MAX_PATH
];
4122 filename_to_utf16 (path
, path_w
);
4123 return _wmkdir (path_w
);
4127 char path_a
[MAX_PATH
];
4129 filename_to_ansi (path
, path_a
);
4130 return _mkdir (path_a
);
4135 sys_open (const char * path
, int oflag
, int mode
)
4137 const char* mpath
= map_w32_filename (path
, NULL
);
4140 if (w32_unicode_filenames
)
4142 wchar_t mpath_w
[MAX_PATH
];
4144 filename_to_utf16 (mpath
, mpath_w
);
4145 /* If possible, try to open file without _O_CREAT, to be able to
4146 write to existing hidden and system files. Force all file
4147 handles to be non-inheritable. */
4148 if ((oflag
& (_O_CREAT
| _O_EXCL
)) != (_O_CREAT
| _O_EXCL
))
4149 res
= _wopen (mpath_w
, (oflag
& ~_O_CREAT
) | _O_NOINHERIT
, mode
);
4151 res
= _wopen (mpath_w
, oflag
| _O_NOINHERIT
, mode
);
4155 char mpath_a
[MAX_PATH
];
4157 filename_to_ansi (mpath
, mpath_a
);
4158 if ((oflag
& (_O_CREAT
| _O_EXCL
)) != (_O_CREAT
| _O_EXCL
))
4159 res
= _open (mpath_a
, (oflag
& ~_O_CREAT
) | _O_NOINHERIT
, mode
);
4161 res
= _open (mpath_a
, oflag
| _O_NOINHERIT
, mode
);
4167 /* Implementation of mkostemp for MS-Windows, to avoid race conditions
4170 Standard algorithm for generating a temporary file name seems to be
4171 use pid or tid with a letter on the front (in place of the 6 X's)
4172 and cycle through the letters to find a unique name. We extend
4173 that to allow any reasonable character as the first of the 6 X's,
4174 so that the number of simultaneously used temporary files will be
4178 mkostemp (char * template, int flags
)
4182 unsigned uid
= GetCurrentThreadId ();
4183 int save_errno
= errno
;
4184 static char first_char
[] = "abcdefghijklmnopqrstuvwyz0123456789!%-_@#";
4187 if (template == NULL
)
4190 p
= template + strlen (template);
4192 /* replace up to the last 5 X's with uid in decimal */
4193 while (--p
>= template && p
[0] == 'X' && --i
>= 0)
4195 p
[0] = '0' + uid
% 10;
4199 if (i
< 0 && p
[0] == 'X')
4204 p
[0] = first_char
[i
];
4205 if ((fd
= sys_open (template,
4206 flags
| _O_CREAT
| _O_EXCL
| _O_RDWR
,
4207 S_IRUSR
| S_IWUSR
)) >= 0
4215 while (++i
< sizeof (first_char
));
4218 /* Template is badly formed or else we can't generate a unique name. */
4223 fchmod (int fd
, mode_t mode
)
4229 sys_rename_replace (const char *oldname
, const char *newname
, BOOL force
)
4232 char temp
[MAX_UTF8_PATH
], temp_a
[MAX_PATH
];;
4235 bool have_temp_a
= false;
4237 /* MoveFile on Windows 95 doesn't correctly change the short file name
4238 alias in a number of circumstances (it is not easy to predict when
4239 just by looking at oldname and newname, unfortunately). In these
4240 cases, renaming through a temporary name avoids the problem.
4242 A second problem on Windows 95 is that renaming through a temp name when
4243 newname is uppercase fails (the final long name ends up in
4244 lowercase, although the short alias might be uppercase) UNLESS the
4245 long temp name is not 8.3.
4247 So, on Windows 95 we always rename through a temp name, and we make sure
4248 the temp name has a long extension to ensure correct renaming. */
4250 strcpy (temp
, map_w32_filename (oldname
, NULL
));
4252 /* volume_info is set indirectly by map_w32_filename. */
4253 oldname_dev
= volume_info
.serialnum
;
4255 if (os_subtype
== OS_9X
)
4260 char oldname_a
[MAX_PATH
];
4262 oldname
= map_w32_filename (oldname
, NULL
);
4263 filename_to_ansi (oldname
, oldname_a
);
4264 filename_to_ansi (temp
, temp_a
);
4265 if ((o
= strrchr (oldname_a
, '\\')))
4268 o
= (char *) oldname_a
;
4270 if ((p
= strrchr (temp_a
, '\\')))
4277 /* Force temp name to require a manufactured 8.3 alias - this
4278 seems to make the second rename work properly. */
4279 sprintf (p
, "_.%s.%u", o
, i
);
4281 result
= rename (oldname_a
, temp_a
);
4283 /* This loop must surely terminate! */
4284 while (result
< 0 && errno
== EEXIST
);
4290 /* If FORCE, emulate Unix behavior - newname is deleted if it already exists
4291 (at least if it is a file; don't do this for directories).
4293 Since we mustn't do this if we are just changing the case of the
4294 file name (we would end up deleting the file we are trying to
4295 rename!), we let rename detect if the destination file already
4296 exists - that way we avoid the possible pitfalls of trying to
4297 determine ourselves whether two names really refer to the same
4298 file, which is not always possible in the general case. (Consider
4299 all the permutations of shared or subst'd drives, etc.) */
4301 newname
= map_w32_filename (newname
, NULL
);
4303 /* volume_info is set indirectly by map_w32_filename. */
4304 newname_dev
= volume_info
.serialnum
;
4306 if (w32_unicode_filenames
)
4308 wchar_t temp_w
[MAX_PATH
], newname_w
[MAX_PATH
];
4310 filename_to_utf16 (temp
, temp_w
);
4311 filename_to_utf16 (newname
, newname_w
);
4312 result
= _wrename (temp_w
, newname_w
);
4313 if (result
< 0 && force
)
4315 DWORD w32err
= GetLastError ();
4318 && newname_dev
!= oldname_dev
)
4320 /* The implementation of `rename' on Windows does not return
4321 errno = EXDEV when you are moving a directory to a
4322 different storage device (ex. logical disk). It returns
4323 EACCES instead. So here we handle such situations and
4327 if ((attributes
= GetFileAttributesW (temp_w
)) != -1
4328 && (attributes
& FILE_ATTRIBUTE_DIRECTORY
))
4331 else if (errno
== EEXIST
)
4333 if (_wchmod (newname_w
, 0666) != 0)
4335 if (_wunlink (newname_w
) != 0)
4337 result
= _wrename (temp_w
, newname_w
);
4339 else if (w32err
== ERROR_PRIVILEGE_NOT_HELD
4340 && is_symlink (temp
))
4342 /* This is Windows prohibiting the user from creating a
4343 symlink in another place, since that requires
4351 char newname_a
[MAX_PATH
];
4354 filename_to_ansi (temp
, temp_a
);
4355 filename_to_ansi (newname
, newname_a
);
4356 result
= rename (temp_a
, newname_a
);
4357 if (result
< 0 && force
)
4359 DWORD w32err
= GetLastError ();
4362 && newname_dev
!= oldname_dev
)
4366 if ((attributes
= GetFileAttributesA (temp_a
)) != -1
4367 && (attributes
& FILE_ATTRIBUTE_DIRECTORY
))
4370 else if (errno
== EEXIST
)
4372 if (_chmod (newname_a
, 0666) != 0)
4374 if (_unlink (newname_a
) != 0)
4376 result
= rename (temp_a
, newname_a
);
4378 else if (w32err
== ERROR_PRIVILEGE_NOT_HELD
4379 && is_symlink (temp
))
4388 sys_rename (char const *old
, char const *new)
4390 return sys_rename_replace (old
, new, TRUE
);
4394 sys_rmdir (const char * path
)
4396 path
= map_w32_filename (path
, NULL
);
4398 if (w32_unicode_filenames
)
4400 wchar_t path_w
[MAX_PATH
];
4402 filename_to_utf16 (path
, path_w
);
4403 return _wrmdir (path_w
);
4407 char path_a
[MAX_PATH
];
4409 filename_to_ansi (path
, path_a
);
4410 return _rmdir (path_a
);
4415 sys_unlink (const char * path
)
4417 path
= map_w32_filename (path
, NULL
);
4419 if (w32_unicode_filenames
)
4421 wchar_t path_w
[MAX_PATH
];
4423 filename_to_utf16 (path
, path_w
);
4424 /* On Unix, unlink works without write permission. */
4425 _wchmod (path_w
, 0666);
4426 return _wunlink (path_w
);
4430 char path_a
[MAX_PATH
];
4432 filename_to_ansi (path
, path_a
);
4433 _chmod (path_a
, 0666);
4434 return _unlink (path_a
);
4438 static FILETIME utc_base_ft
;
4439 static ULONGLONG utc_base
; /* In 100ns units */
4440 static int init
= 0;
4442 #define FILETIME_TO_U64(result, ft) \
4444 ULARGE_INTEGER uiTemp; \
4445 uiTemp.LowPart = (ft).dwLowDateTime; \
4446 uiTemp.HighPart = (ft).dwHighDateTime; \
4447 result = uiTemp.QuadPart; \
4451 initialize_utc_base (void)
4453 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
4462 st
.wMilliseconds
= 0;
4464 SystemTimeToFileTime (&st
, &utc_base_ft
);
4465 FILETIME_TO_U64 (utc_base
, utc_base_ft
);
4469 convert_time (FILETIME ft
)
4475 initialize_utc_base ();
4479 if (CompareFileTime (&ft
, &utc_base_ft
) < 0)
4482 FILETIME_TO_U64 (tmp
, ft
);
4483 return (time_t) ((tmp
- utc_base
) / 10000000L);
4487 convert_from_time_t (time_t time
, FILETIME
* pft
)
4493 initialize_utc_base ();
4497 /* time in 100ns units since 1-Jan-1601 */
4498 tmp
.QuadPart
= (ULONGLONG
) time
* 10000000L + utc_base
;
4499 pft
->dwHighDateTime
= tmp
.HighPart
;
4500 pft
->dwLowDateTime
= tmp
.LowPart
;
4503 static PSECURITY_DESCRIPTOR
4504 get_file_security_desc_by_handle (HANDLE h
)
4506 PSECURITY_DESCRIPTOR psd
= NULL
;
4508 SECURITY_INFORMATION si
= OWNER_SECURITY_INFORMATION
4509 | GROUP_SECURITY_INFORMATION
/* | DACL_SECURITY_INFORMATION */ ;
4511 err
= get_security_info (h
, SE_FILE_OBJECT
, si
,
4512 NULL
, NULL
, NULL
, NULL
, &psd
);
4513 if (err
!= ERROR_SUCCESS
)
4519 static PSECURITY_DESCRIPTOR
4520 get_file_security_desc_by_name (const char *fname
)
4522 PSECURITY_DESCRIPTOR psd
= NULL
;
4524 SECURITY_INFORMATION si
= OWNER_SECURITY_INFORMATION
4525 | GROUP_SECURITY_INFORMATION
/* | DACL_SECURITY_INFORMATION */ ;
4527 if (!get_file_security (fname
, si
, psd
, 0, &sd_len
))
4529 err
= GetLastError ();
4530 if (err
!= ERROR_INSUFFICIENT_BUFFER
)
4534 psd
= xmalloc (sd_len
);
4535 if (!get_file_security (fname
, si
, psd
, sd_len
, &sd_len
))
4547 unsigned n_subauthorities
;
4549 /* Use the last sub-authority value of the RID, the relative
4550 portion of the SID, as user/group ID. */
4551 n_subauthorities
= *get_sid_sub_authority_count (sid
);
4552 if (n_subauthorities
< 1)
4553 return 0; /* the "World" RID */
4554 return *get_sid_sub_authority (sid
, n_subauthorities
- 1);
4557 /* Caching SID and account values for faster lokup. */
4561 struct w32_id
*next
;
4563 unsigned char sid
[FLEXIBLE_ARRAY_MEMBER
];
4566 static struct w32_id
*w32_idlist
;
4569 w32_cached_id (PSID sid
, unsigned *id
, char *name
)
4571 struct w32_id
*tail
, *found
;
4573 for (found
= NULL
, tail
= w32_idlist
; tail
; tail
= tail
->next
)
4575 if (equal_sid ((PSID
)tail
->sid
, sid
))
4584 strcpy (name
, found
->name
);
4592 w32_add_to_cache (PSID sid
, unsigned id
, char *name
)
4595 struct w32_id
*new_entry
;
4597 /* We don't want to leave behind stale cache from when Emacs was
4601 sid_len
= get_length_sid (sid
);
4602 new_entry
= xmalloc (offsetof (struct w32_id
, sid
) + sid_len
);
4605 new_entry
->rid
= id
;
4606 strcpy (new_entry
->name
, name
);
4607 copy_sid (sid_len
, (PSID
)new_entry
->sid
, sid
);
4608 new_entry
->next
= w32_idlist
;
4609 w32_idlist
= new_entry
;
4618 get_name_and_id (PSECURITY_DESCRIPTOR psd
, unsigned *id
, char *nm
, int what
)
4622 SID_NAME_USE ignore
;
4624 DWORD name_len
= sizeof (name
);
4626 DWORD domain_len
= sizeof (domain
);
4631 result
= get_security_descriptor_owner (psd
, &sid
, &dflt
);
4632 else if (what
== GID
)
4633 result
= get_security_descriptor_group (psd
, &sid
, &dflt
);
4637 if (!result
|| !is_valid_sid (sid
))
4639 else if (!w32_cached_id (sid
, id
, nm
))
4641 if (!lookup_account_sid (NULL
, sid
, name
, &name_len
,
4642 domain
, &domain_len
, &ignore
)
4643 || name_len
> UNLEN
+1)
4647 *id
= get_rid (sid
);
4649 w32_add_to_cache (sid
, *id
, name
);
4656 get_file_owner_and_group (PSECURITY_DESCRIPTOR psd
, struct stat
*st
)
4658 int dflt_usr
= 0, dflt_grp
= 0;
4667 if (get_name_and_id (psd
, &st
->st_uid
, st
->st_uname
, UID
))
4669 if (get_name_and_id (psd
, &st
->st_gid
, st
->st_gname
, GID
))
4672 /* Consider files to belong to current user/group, if we cannot get
4673 more accurate information. */
4676 st
->st_uid
= dflt_passwd
.pw_uid
;
4677 strcpy (st
->st_uname
, dflt_passwd
.pw_name
);
4681 st
->st_gid
= dflt_passwd
.pw_gid
;
4682 strcpy (st
->st_gname
, dflt_group
.gr_name
);
4686 /* Return non-zero if NAME is a potentially slow filesystem. */
4688 is_slow_fs (const char *name
)
4693 if (IS_DIRECTORY_SEP (name
[0]) && IS_DIRECTORY_SEP (name
[1]))
4694 devtype
= DRIVE_REMOTE
; /* assume UNC name is remote */
4695 else if (!(strlen (name
) >= 2 && IS_DEVICE_SEP (name
[1])))
4696 devtype
= GetDriveType (NULL
); /* use root of current drive */
4699 /* GetDriveType needs the root directory of the drive. */
4700 strncpy (drive_root
, name
, 2);
4701 drive_root
[2] = '\\';
4702 drive_root
[3] = '\0';
4703 devtype
= GetDriveType (drive_root
);
4705 return !(devtype
== DRIVE_FIXED
|| devtype
== DRIVE_RAMDISK
);
4708 /* If this is non-zero, the caller wants accurate information about
4709 file's owner and group, which could be expensive to get. dired.c
4710 uses this flag when needed for the job at hand. */
4711 int w32_stat_get_owner_group
;
4713 /* MSVC stat function can't cope with UNC names and has other bugs, so
4714 replace it with our own. This also allows us to calculate consistent
4715 inode values and owner/group without hacks in the main Emacs code,
4716 and support file names encoded in UTF-8. */
4719 stat_worker (const char * path
, struct stat
* buf
, int follow_symlinks
)
4721 char *name
, *save_name
, *r
;
4722 WIN32_FIND_DATAW wfd_w
;
4723 WIN32_FIND_DATAA wfd_a
;
4725 unsigned __int64 fake_inode
= 0;
4728 int rootdir
= FALSE
;
4729 PSECURITY_DESCRIPTOR psd
= NULL
;
4730 int is_a_symlink
= 0;
4731 DWORD file_flags
= FILE_FLAG_BACKUP_SEMANTICS
;
4732 DWORD access_rights
= 0;
4733 DWORD fattrs
= 0, serialnum
= 0, fs_high
= 0, fs_low
= 0, nlinks
= 1;
4734 FILETIME ctime
, atime
, wtime
;
4735 wchar_t name_w
[MAX_PATH
];
4736 char name_a
[MAX_PATH
];
4738 if (path
== NULL
|| buf
== NULL
)
4744 save_name
= name
= (char *) map_w32_filename (path
, &path
);
4745 /* Must be valid filename, no wild cards or other invalid
4747 if (strpbrk (name
, "*?|<>\""))
4753 len
= strlen (name
);
4754 /* Allocate 1 extra byte so that we could append a slash to a root
4755 directory, down below. */
4756 name
= strcpy (alloca (len
+ 2), name
);
4758 /* Avoid a somewhat costly call to is_symlink if the filesystem
4759 doesn't support symlinks. */
4760 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) != 0)
4761 is_a_symlink
= is_symlink (name
);
4763 /* Plan A: Open the file and get all the necessary information via
4764 the resulting handle. This solves several issues in one blow:
4766 . retrieves attributes for the target of a symlink, if needed
4767 . gets attributes of root directories and symlinks pointing to
4768 root directories, thus avoiding the need for special-casing
4769 these and detecting them by examining the file-name format
4770 . retrieves more accurate attributes (e.g., non-zero size for
4771 some directories, esp. directories that are junction points)
4772 . correctly resolves "c:/..", "/.." and similar file names
4773 . avoids run-time penalties for 99% of use cases
4775 Plan A is always tried first, unless the user asked not to (but
4776 if the file is a symlink and we need to follow links, we try Plan
4777 A even if the user asked not to).
4779 If Plan A fails, we go to Plan B (below), where various
4780 potentially expensive techniques must be used to handle "special"
4781 files such as UNC volumes etc. */
4782 if (!(NILP (Vw32_get_true_file_attributes
)
4783 || (EQ (Vw32_get_true_file_attributes
, Qlocal
) && is_slow_fs (name
)))
4784 /* Following symlinks requires getting the info by handle. */
4785 || (is_a_symlink
&& follow_symlinks
))
4787 BY_HANDLE_FILE_INFORMATION info
;
4789 if (is_a_symlink
&& !follow_symlinks
)
4790 file_flags
|= FILE_FLAG_OPEN_REPARSE_POINT
;
4791 /* READ_CONTROL access rights are required to get security info
4792 by handle. But if the OS doesn't support security in the
4793 first place, we don't need to try. */
4794 if (is_windows_9x () != TRUE
)
4795 access_rights
|= READ_CONTROL
;
4797 if (w32_unicode_filenames
)
4799 filename_to_utf16 (name
, name_w
);
4800 fh
= CreateFileW (name_w
, access_rights
, 0, NULL
, OPEN_EXISTING
,
4802 /* If CreateFile fails with READ_CONTROL, try again with
4803 zero as access rights. */
4804 if (fh
== INVALID_HANDLE_VALUE
&& access_rights
)
4805 fh
= CreateFileW (name_w
, 0, 0, NULL
, OPEN_EXISTING
,
4810 filename_to_ansi (name
, name_a
);
4811 fh
= CreateFileA (name_a
, access_rights
, 0, NULL
, OPEN_EXISTING
,
4813 if (fh
== INVALID_HANDLE_VALUE
&& access_rights
)
4814 fh
= CreateFileA (name_a
, 0, 0, NULL
, OPEN_EXISTING
,
4817 if (fh
== INVALID_HANDLE_VALUE
)
4818 goto no_true_file_attributes
;
4820 /* This is more accurate in terms of getting the correct number
4821 of links, but is quite slow (it is noticeable when Emacs is
4822 making a list of file name completions). */
4823 if (GetFileInformationByHandle (fh
, &info
))
4825 nlinks
= info
.nNumberOfLinks
;
4826 /* Might as well use file index to fake inode values, but this
4827 is not guaranteed to be unique unless we keep a handle open
4828 all the time (even then there are situations where it is
4829 not unique). Reputedly, there are at most 48 bits of info
4830 (on NTFS, presumably less on FAT). */
4831 fake_inode
= info
.nFileIndexHigh
;
4833 fake_inode
+= info
.nFileIndexLow
;
4834 serialnum
= info
.dwVolumeSerialNumber
;
4835 fs_high
= info
.nFileSizeHigh
;
4836 fs_low
= info
.nFileSizeLow
;
4837 ctime
= info
.ftCreationTime
;
4838 atime
= info
.ftLastAccessTime
;
4839 wtime
= info
.ftLastWriteTime
;
4840 fattrs
= info
.dwFileAttributes
;
4844 /* We don't go to Plan B here, because it's not clear that
4845 it's a good idea. The only known use case where
4846 CreateFile succeeds, but GetFileInformationByHandle fails
4847 (with ERROR_INVALID_FUNCTION) is for character devices
4848 such as NUL, PRN, etc. For these, switching to Plan B is
4849 a net loss, because we lose the character device
4850 attribute returned by GetFileType below (FindFirstFile
4851 doesn't set that bit in the attributes), and the other
4852 fields don't make sense for character devices anyway.
4853 Emacs doesn't really care for non-file entities in the
4854 context of l?stat, so neither do we. */
4856 /* w32err is assigned so one could put a breakpoint here and
4857 examine its value, when GetFileInformationByHandle
4859 DWORD w32err
= GetLastError ();
4863 case ERROR_FILE_NOT_FOUND
: /* can this ever happen? */
4869 /* Test for a symlink before testing for a directory, since
4870 symlinks to directories have the directory bit set, but we
4871 don't want them to appear as directories. */
4872 if (is_a_symlink
&& !follow_symlinks
)
4873 buf
->st_mode
= S_IFLNK
;
4874 else if (fattrs
& FILE_ATTRIBUTE_DIRECTORY
)
4875 buf
->st_mode
= S_IFDIR
;
4878 DWORD ftype
= GetFileType (fh
);
4882 case FILE_TYPE_DISK
:
4883 buf
->st_mode
= S_IFREG
;
4885 case FILE_TYPE_PIPE
:
4886 buf
->st_mode
= S_IFIFO
;
4888 case FILE_TYPE_CHAR
:
4889 case FILE_TYPE_UNKNOWN
:
4891 buf
->st_mode
= S_IFCHR
;
4894 /* We produce the fallback owner and group data, based on the
4895 current user that runs Emacs, in the following cases:
4897 . caller didn't request owner and group info
4898 . this is Windows 9X
4899 . getting security by handle failed, and we need to produce
4900 information for the target of a symlink (this is better
4901 than producing a potentially misleading info about the
4904 If getting security by handle fails, and we don't need to
4905 resolve symlinks, we try getting security by name. */
4906 if (!w32_stat_get_owner_group
|| is_windows_9x () == TRUE
)
4907 get_file_owner_and_group (NULL
, buf
);
4910 psd
= get_file_security_desc_by_handle (fh
);
4913 get_file_owner_and_group (psd
, buf
);
4916 else if (!(is_a_symlink
&& follow_symlinks
))
4918 psd
= get_file_security_desc_by_name (name
);
4919 get_file_owner_and_group (psd
, buf
);
4923 get_file_owner_and_group (NULL
, buf
);
4929 no_true_file_attributes
:
4930 /* Plan B: Either getting a handle on the file failed, or the
4931 caller explicitly asked us to not bother making this
4932 information more accurate.
4934 Implementation note: In Plan B, we never bother to resolve
4935 symlinks, even if we got here because we tried Plan A and
4936 failed. That's because, even if the caller asked for extra
4937 precision by setting Vw32_get_true_file_attributes to t,
4938 resolving symlinks requires acquiring a file handle to the
4939 symlink, which we already know will fail. And if the user
4940 did not ask for extra precision, resolving symlinks will fly
4941 in the face of that request, since the user then wants the
4942 lightweight version of the code. */
4943 rootdir
= (path
>= save_name
+ len
- 1
4944 && (IS_DIRECTORY_SEP (*path
) || *path
== 0));
4946 /* If name is "c:/.." or "/.." then stat "c:/" or "/". */
4947 r
= IS_DEVICE_SEP (name
[1]) ? &name
[2] : name
;
4948 if (IS_DIRECTORY_SEP (r
[0])
4949 && r
[1] == '.' && r
[2] == '.' && r
[3] == '\0')
4952 /* Note: If NAME is a symlink to the root of a UNC volume
4953 (i.e. "\\SERVER"), we will not detect that here, and we will
4954 return data about the symlink as result of FindFirst below.
4955 This is unfortunate, but that marginal use case does not
4956 justify a call to chase_symlinks which would impose a penalty
4957 on all the other use cases. (We get here for symlinks to
4958 roots of UNC volumes because CreateFile above fails for them,
4959 unlike with symlinks to root directories X:\ of drives.) */
4960 if (is_unc_volume (name
))
4962 fattrs
= unc_volume_file_attributes (name
);
4966 ctime
= atime
= wtime
= utc_base_ft
;
4970 /* Make sure root directories end in a slash. */
4971 if (!IS_DIRECTORY_SEP (name
[len
-1]))
4972 strcpy (name
+ len
, "\\");
4973 if (GetDriveType (name
) < 2)
4979 fattrs
= FILE_ATTRIBUTE_DIRECTORY
;
4980 ctime
= atime
= wtime
= utc_base_ft
;
4986 /* Make sure non-root directories do NOT end in a slash,
4987 otherwise FindFirstFile might fail. */
4988 if (IS_DIRECTORY_SEP (name
[len
-1]))
4991 /* (This is hacky, but helps when doing file completions on
4992 network drives.) Optimize by using information available from
4993 active readdir if possible. */
4994 len
= strlen (dir_pathname
);
4995 if (IS_DIRECTORY_SEP (dir_pathname
[len
-1]))
4997 if (dir_find_handle
!= INVALID_HANDLE_VALUE
4998 && last_dir_find_data
!= -1
4999 && !(is_a_symlink
&& follow_symlinks
)
5000 /* The 2 file-name comparisons below support only ASCII
5001 characters, and will lose (compare not equal) when
5002 the file names include non-ASCII characters that are
5003 the same but for the case. However, doing this
5004 properly involves: (a) converting both file names to
5005 UTF-16, (b) lower-casing both names using CharLowerW,
5006 and (c) comparing the results; this would be quite a
5007 bit slower, whereas Plan B is for users who want
5008 lightweight albeit inaccurate version of 'stat'. */
5009 && c_strncasecmp (save_name
, dir_pathname
, len
) == 0
5010 && IS_DIRECTORY_SEP (name
[len
])
5011 && xstrcasecmp (name
+ len
+ 1, dir_static
.d_name
) == 0)
5013 have_wfd
= last_dir_find_data
;
5014 /* This was the last entry returned by readdir. */
5015 if (last_dir_find_data
== DIR_FIND_DATA_W
)
5016 wfd_w
= dir_find_data_w
;
5018 wfd_a
= dir_find_data_a
;
5022 logon_network_drive (name
);
5024 if (w32_unicode_filenames
)
5026 filename_to_utf16 (name
, name_w
);
5027 fh
= FindFirstFileW (name_w
, &wfd_w
);
5028 have_wfd
= DIR_FIND_DATA_W
;
5032 filename_to_ansi (name
, name_a
);
5033 /* If NAME includes characters not representable by
5034 the current ANSI codepage, filename_to_ansi
5035 usually replaces them with a '?'. We don't want
5036 to let FindFirstFileA interpret those as wildcards,
5037 and "succeed", returning us data from some random
5038 file in the same directory. */
5039 if (_mbspbrk (name_a
, "?"))
5040 fh
= INVALID_HANDLE_VALUE
;
5042 fh
= FindFirstFileA (name_a
, &wfd_a
);
5043 have_wfd
= DIR_FIND_DATA_A
;
5045 if (fh
== INVALID_HANDLE_VALUE
)
5052 /* Note: if NAME is a symlink, the information we get from
5053 FindFirstFile is for the symlink, not its target. */
5054 if (have_wfd
== DIR_FIND_DATA_W
)
5056 fattrs
= wfd_w
.dwFileAttributes
;
5057 ctime
= wfd_w
.ftCreationTime
;
5058 atime
= wfd_w
.ftLastAccessTime
;
5059 wtime
= wfd_w
.ftLastWriteTime
;
5060 fs_high
= wfd_w
.nFileSizeHigh
;
5061 fs_low
= wfd_w
.nFileSizeLow
;
5065 fattrs
= wfd_a
.dwFileAttributes
;
5066 ctime
= wfd_a
.ftCreationTime
;
5067 atime
= wfd_a
.ftLastAccessTime
;
5068 wtime
= wfd_a
.ftLastWriteTime
;
5069 fs_high
= wfd_a
.nFileSizeHigh
;
5070 fs_low
= wfd_a
.nFileSizeLow
;
5074 serialnum
= volume_info
.serialnum
;
5076 if (is_a_symlink
&& !follow_symlinks
)
5077 buf
->st_mode
= S_IFLNK
;
5078 else if (fattrs
& FILE_ATTRIBUTE_DIRECTORY
)
5079 buf
->st_mode
= S_IFDIR
;
5081 buf
->st_mode
= S_IFREG
;
5083 get_file_owner_and_group (NULL
, buf
);
5086 buf
->st_ino
= fake_inode
;
5088 buf
->st_dev
= serialnum
;
5089 buf
->st_rdev
= serialnum
;
5091 buf
->st_size
= fs_high
;
5092 buf
->st_size
<<= 32;
5093 buf
->st_size
+= fs_low
;
5094 buf
->st_nlink
= nlinks
;
5096 /* Convert timestamps to Unix format. */
5097 buf
->st_mtime
= convert_time (wtime
);
5098 buf
->st_atime
= convert_time (atime
);
5099 if (buf
->st_atime
== 0) buf
->st_atime
= buf
->st_mtime
;
5100 buf
->st_ctime
= convert_time (ctime
);
5101 if (buf
->st_ctime
== 0) buf
->st_ctime
= buf
->st_mtime
;
5103 /* determine rwx permissions */
5104 if (is_a_symlink
&& !follow_symlinks
)
5105 permission
= S_IREAD
| S_IWRITE
| S_IEXEC
; /* Posix expectations */
5108 if (fattrs
& FILE_ATTRIBUTE_READONLY
)
5109 permission
= S_IREAD
;
5111 permission
= S_IREAD
| S_IWRITE
;
5113 if (fattrs
& FILE_ATTRIBUTE_DIRECTORY
)
5114 permission
|= S_IEXEC
;
5115 else if (is_exec (name
))
5116 permission
|= S_IEXEC
;
5119 buf
->st_mode
|= permission
| (permission
>> 3) | (permission
>> 6);
5125 stat (const char * path
, struct stat
* buf
)
5127 return stat_worker (path
, buf
, 1);
5131 lstat (const char * path
, struct stat
* buf
)
5133 return stat_worker (path
, buf
, 0);
5137 fstatat (int fd
, char const *name
, struct stat
*st
, int flags
)
5139 /* Rely on a hack: an open directory is modeled as file descriptor 0.
5140 This is good enough for the current usage in Emacs, but is fragile.
5142 FIXME: Add proper support for fdopendir, fstatat, readlinkat.
5143 Gnulib does this and can serve as a model. */
5144 char fullname
[MAX_UTF8_PATH
];
5148 char lastc
= dir_pathname
[strlen (dir_pathname
) - 1];
5150 if (_snprintf (fullname
, sizeof fullname
, "%s%s%s",
5151 dir_pathname
, IS_DIRECTORY_SEP (lastc
) ? "" : "/", name
)
5154 errno
= ENAMETOOLONG
;
5160 return stat_worker (name
, st
, ! (flags
& AT_SYMLINK_NOFOLLOW
));
5163 /* Provide fstat and utime as well as stat for consistent handling of
5166 fstat (int desc
, struct stat
* buf
)
5168 HANDLE fh
= (HANDLE
) _get_osfhandle (desc
);
5169 BY_HANDLE_FILE_INFORMATION info
;
5170 unsigned __int64 fake_inode
;
5173 switch (GetFileType (fh
) & ~FILE_TYPE_REMOTE
)
5175 case FILE_TYPE_DISK
:
5176 buf
->st_mode
= S_IFREG
;
5177 if (!GetFileInformationByHandle (fh
, &info
))
5183 case FILE_TYPE_PIPE
:
5184 buf
->st_mode
= S_IFIFO
;
5186 case FILE_TYPE_CHAR
:
5187 case FILE_TYPE_UNKNOWN
:
5189 buf
->st_mode
= S_IFCHR
;
5191 memset (&info
, 0, sizeof (info
));
5192 info
.dwFileAttributes
= 0;
5193 info
.ftCreationTime
= utc_base_ft
;
5194 info
.ftLastAccessTime
= utc_base_ft
;
5195 info
.ftLastWriteTime
= utc_base_ft
;
5198 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
5199 buf
->st_mode
= S_IFDIR
;
5201 buf
->st_nlink
= info
.nNumberOfLinks
;
5202 /* Might as well use file index to fake inode values, but this
5203 is not guaranteed to be unique unless we keep a handle open
5204 all the time (even then there are situations where it is
5205 not unique). Reputedly, there are at most 48 bits of info
5206 (on NTFS, presumably less on FAT). */
5207 fake_inode
= info
.nFileIndexHigh
;
5209 fake_inode
+= info
.nFileIndexLow
;
5211 /* MSVC defines _ino_t to be short; other libc's might not. */
5212 if (sizeof (buf
->st_ino
) == 2)
5213 buf
->st_ino
= fake_inode
^ (fake_inode
>> 16);
5215 buf
->st_ino
= fake_inode
;
5217 /* If the caller so requested, get the true file owner and group.
5218 Otherwise, consider the file to belong to the current user. */
5219 if (!w32_stat_get_owner_group
|| is_windows_9x () == TRUE
)
5220 get_file_owner_and_group (NULL
, buf
);
5223 PSECURITY_DESCRIPTOR psd
= NULL
;
5225 psd
= get_file_security_desc_by_handle (fh
);
5228 get_file_owner_and_group (psd
, buf
);
5232 get_file_owner_and_group (NULL
, buf
);
5235 buf
->st_dev
= info
.dwVolumeSerialNumber
;
5236 buf
->st_rdev
= info
.dwVolumeSerialNumber
;
5238 buf
->st_size
= info
.nFileSizeHigh
;
5239 buf
->st_size
<<= 32;
5240 buf
->st_size
+= info
.nFileSizeLow
;
5242 /* Convert timestamps to Unix format. */
5243 buf
->st_mtime
= convert_time (info
.ftLastWriteTime
);
5244 buf
->st_atime
= convert_time (info
.ftLastAccessTime
);
5245 if (buf
->st_atime
== 0) buf
->st_atime
= buf
->st_mtime
;
5246 buf
->st_ctime
= convert_time (info
.ftCreationTime
);
5247 if (buf
->st_ctime
== 0) buf
->st_ctime
= buf
->st_mtime
;
5249 /* determine rwx permissions */
5250 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
)
5251 permission
= S_IREAD
;
5253 permission
= S_IREAD
| S_IWRITE
;
5255 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
5256 permission
|= S_IEXEC
;
5259 #if 0 /* no way of knowing the filename */
5260 char * p
= strrchr (name
, '.');
5262 (xstrcasecmp (p
, ".exe") == 0 ||
5263 xstrcasecmp (p
, ".com") == 0 ||
5264 xstrcasecmp (p
, ".bat") == 0 ||
5265 xstrcasecmp (p
, ".cmd") == 0))
5266 permission
|= S_IEXEC
;
5270 buf
->st_mode
|= permission
| (permission
>> 3) | (permission
>> 6);
5275 /* A version of 'utime' which handles directories as well as
5279 utime (const char *name
, struct utimbuf
*times
)
5281 struct utimbuf deftime
;
5288 deftime
.modtime
= deftime
.actime
= time (NULL
);
5292 if (w32_unicode_filenames
)
5294 wchar_t name_utf16
[MAX_PATH
];
5296 if (filename_to_utf16 (name
, name_utf16
) != 0)
5297 return -1; /* errno set by filename_to_utf16 */
5299 /* Need write access to set times. */
5300 fh
= CreateFileW (name_utf16
, FILE_WRITE_ATTRIBUTES
,
5301 /* If NAME specifies a directory, FILE_SHARE_DELETE
5302 allows other processes to delete files inside it,
5303 while we have the directory open. */
5304 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
5305 0, OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
5309 char name_ansi
[MAX_PATH
];
5311 if (filename_to_ansi (name
, name_ansi
) != 0)
5312 return -1; /* errno set by filename_to_ansi */
5314 fh
= CreateFileA (name_ansi
, FILE_WRITE_ATTRIBUTES
,
5315 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
5316 0, OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
5318 if (fh
!= INVALID_HANDLE_VALUE
)
5320 convert_from_time_t (times
->actime
, &atime
);
5321 convert_from_time_t (times
->modtime
, &mtime
);
5322 if (!SetFileTime (fh
, NULL
, &atime
, &mtime
))
5332 DWORD err
= GetLastError ();
5336 case ERROR_FILE_NOT_FOUND
:
5337 case ERROR_PATH_NOT_FOUND
:
5338 case ERROR_INVALID_DRIVE
:
5339 case ERROR_BAD_NETPATH
:
5340 case ERROR_DEV_NOT_EXIST
:
5341 /* ERROR_INVALID_NAME is the error CreateFile sets when the
5342 file name includes ?s, i.e. translation to ANSI failed. */
5343 case ERROR_INVALID_NAME
:
5346 case ERROR_TOO_MANY_OPEN_FILES
:
5349 case ERROR_ACCESS_DENIED
:
5350 case ERROR_SHARING_VIOLATION
:
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
& S_IWRITE
) != 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
& ~S_IWRITE
);
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 strcpy (tem
+ (p
- linkfn
), filename
);
5442 dir_access
= faccessat (AT_FDCWD
, tem
, D_OK
, AT_EACCESS
);
5445 dir_access
= faccessat (AT_FDCWD
, filename
, D_OK
, AT_EACCESS
);
5447 /* Since Windows distinguishes between symlinks to directories and
5448 to files, we provide a kludgy feature: if FILENAME doesn't
5449 exist, but ends in a slash, we create a symlink to directory. If
5450 FILENAME exists and is a directory, we always create a symlink to
5452 filename_ends_in_slash
= IS_DIRECTORY_SEP (filename
[strlen (filename
) - 1]);
5453 if (dir_access
== 0 || filename_ends_in_slash
)
5454 flags
= SYMBOLIC_LINK_FLAG_DIRECTORY
;
5456 tgtfn
= (char *)map_w32_filename (filename
, NULL
);
5457 if (filename_ends_in_slash
)
5458 tgtfn
[strlen (tgtfn
) - 1] = '\0';
5461 if (!create_symbolic_link (linkfn
, tgtfn
, flags
))
5463 /* ENOSYS is set by create_symbolic_link, when it detects that
5464 the OS doesn't support the CreateSymbolicLink API. */
5465 if (errno
!= ENOSYS
)
5467 DWORD w32err
= GetLastError ();
5471 /* ERROR_SUCCESS is sometimes returned when LINKFN and
5472 TGTFN point to the same file name, go figure. */
5474 case ERROR_FILE_EXISTS
:
5477 case ERROR_ACCESS_DENIED
:
5480 case ERROR_FILE_NOT_FOUND
:
5481 case ERROR_PATH_NOT_FOUND
:
5482 case ERROR_BAD_NETPATH
:
5483 case ERROR_INVALID_REPARSE_DATA
:
5486 case ERROR_DIRECTORY
:
5489 case ERROR_PRIVILEGE_NOT_HELD
:
5490 case ERROR_NOT_ALL_ASSIGNED
:
5493 case ERROR_DISK_FULL
:
5506 /* A quick inexpensive test of whether FILENAME identifies a file that
5507 is a symlink. Returns non-zero if it is, zero otherwise. FILENAME
5508 must already be in the normalized form returned by
5511 Note: for repeated operations on many files, it is best to test
5512 whether the underlying volume actually supports symlinks, by
5513 testing the FILE_SUPPORTS_REPARSE_POINTS bit in volume's flags, and
5514 avoid the call to this function if it doesn't. That's because the
5515 call to GetFileAttributes takes a non-negligible time, especially
5516 on non-local or removable filesystems. See stat_worker for an
5517 example of how to do that. */
5519 is_symlink (const char *filename
)
5522 wchar_t filename_w
[MAX_PATH
];
5523 char filename_a
[MAX_PATH
];
5524 WIN32_FIND_DATAW wfdw
;
5525 WIN32_FIND_DATAA wfda
;
5527 int attrs_mean_symlink
;
5529 if (w32_unicode_filenames
)
5531 filename_to_utf16 (filename
, filename_w
);
5532 attrs
= GetFileAttributesW (filename_w
);
5536 filename_to_ansi (filename
, filename_a
);
5537 attrs
= GetFileAttributesA (filename_a
);
5541 DWORD w32err
= GetLastError ();
5545 case ERROR_BAD_NETPATH
: /* network share, can't be a symlink */
5547 case ERROR_ACCESS_DENIED
:
5550 case ERROR_FILE_NOT_FOUND
:
5551 case ERROR_PATH_NOT_FOUND
:
5558 if ((attrs
& FILE_ATTRIBUTE_REPARSE_POINT
) == 0)
5560 logon_network_drive (filename
);
5561 if (w32_unicode_filenames
)
5563 fh
= FindFirstFileW (filename_w
, &wfdw
);
5564 attrs_mean_symlink
=
5565 (wfdw
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) != 0
5566 && (wfdw
.dwReserved0
& IO_REPARSE_TAG_SYMLINK
) == IO_REPARSE_TAG_SYMLINK
;
5568 else if (_mbspbrk (filename_a
, "?"))
5570 /* filename_to_ansi failed to convert the file name. */
5576 fh
= FindFirstFileA (filename_a
, &wfda
);
5577 attrs_mean_symlink
=
5578 (wfda
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) != 0
5579 && (wfda
.dwReserved0
& IO_REPARSE_TAG_SYMLINK
) == IO_REPARSE_TAG_SYMLINK
;
5581 if (fh
== INVALID_HANDLE_VALUE
)
5584 return attrs_mean_symlink
;
5587 /* If NAME identifies a symbolic link, copy into BUF the file name of
5588 the symlink's target. Copy at most BUF_SIZE bytes, and do NOT
5589 null-terminate the target name, even if it fits. Return the number
5590 of bytes copied, or -1 if NAME is not a symlink or any error was
5591 encountered while resolving it. The file name copied into BUF is
5592 encoded in the current ANSI codepage. */
5594 readlink (const char *name
, char *buf
, size_t buf_size
)
5597 TOKEN_PRIVILEGES privs
;
5598 int restore_privs
= 0;
5601 char resolved
[MAX_UTF8_PATH
];
5614 path
= map_w32_filename (name
, NULL
);
5616 if (strlen (path
) > MAX_UTF8_PATH
)
5618 errno
= ENAMETOOLONG
;
5623 if (is_windows_9x () == TRUE
5624 || (volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) == 0
5625 || !is_symlink (path
))
5628 errno
= EINVAL
; /* not a symlink */
5632 /* Done with simple tests, now we're in for some _real_ work. */
5633 if (enable_privilege (SE_BACKUP_NAME
, TRUE
, &privs
))
5635 /* Implementation note: From here and onward, don't return early,
5636 since that will fail to restore the original set of privileges of
5637 the calling thread. */
5639 retval
= -1; /* not too optimistic, are we? */
5641 /* Note: In the next call to CreateFile, we use zero as the 2nd
5642 argument because, when the symlink is a hidden/system file,
5643 e.g. 'C:\Users\All Users', GENERIC_READ fails with
5644 ERROR_ACCESS_DENIED. Zero seems to work just fine, both for file
5645 and directory symlinks. */
5646 if (w32_unicode_filenames
)
5648 wchar_t path_w
[MAX_PATH
];
5650 filename_to_utf16 (path
, path_w
);
5651 sh
= CreateFileW (path_w
, 0, 0, NULL
, OPEN_EXISTING
,
5652 FILE_FLAG_OPEN_REPARSE_POINT
5653 | FILE_FLAG_BACKUP_SEMANTICS
,
5658 char path_a
[MAX_PATH
];
5660 filename_to_ansi (path
, path_a
);
5661 sh
= CreateFileA (path_a
, 0, 0, NULL
, OPEN_EXISTING
,
5662 FILE_FLAG_OPEN_REPARSE_POINT
5663 | FILE_FLAG_BACKUP_SEMANTICS
,
5666 if (sh
!= INVALID_HANDLE_VALUE
)
5668 BYTE reparse_buf
[MAXIMUM_REPARSE_DATA_BUFFER_SIZE
];
5669 REPARSE_DATA_BUFFER
*reparse_data
= (REPARSE_DATA_BUFFER
*)&reparse_buf
[0];
5672 if (!DeviceIoControl (sh
, FSCTL_GET_REPARSE_POINT
, NULL
, 0,
5673 reparse_buf
, MAXIMUM_REPARSE_DATA_BUFFER_SIZE
,
5676 else if (reparse_data
->ReparseTag
!= IO_REPARSE_TAG_SYMLINK
)
5680 /* Copy the link target name, in wide characters, from
5681 reparse_data, then convert it to multibyte encoding in
5682 the current locale's codepage. */
5686 reparse_data
->SymbolicLinkReparseBuffer
.PrintNameLength
;
5688 reparse_data
->SymbolicLinkReparseBuffer
.PathBuffer
5689 + reparse_data
->SymbolicLinkReparseBuffer
.PrintNameOffset
/sizeof(WCHAR
);
5690 size_t size_to_copy
= buf_size
;
5692 /* According to MSDN, PrintNameLength does not include the
5693 terminating null character. */
5694 lwname
= alloca ((lwname_len
+ 1) * sizeof(WCHAR
));
5695 memcpy (lwname
, lwname_src
, lwname_len
);
5696 lwname
[lwname_len
/sizeof(WCHAR
)] = 0; /* null-terminate */
5697 filename_from_utf16 (lwname
, resolved
);
5698 dostounix_filename (resolved
);
5699 lname_size
= strlen (resolved
) + 1;
5700 if (lname_size
<= buf_size
)
5701 size_to_copy
= lname_size
;
5702 strncpy (buf
, resolved
, size_to_copy
);
5704 retval
= size_to_copy
;
5710 /* CreateFile failed. */
5711 DWORD w32err2
= GetLastError ();
5715 case ERROR_FILE_NOT_FOUND
:
5716 case ERROR_PATH_NOT_FOUND
:
5719 case ERROR_ACCESS_DENIED
:
5720 case ERROR_TOO_MANY_OPEN_FILES
:
5730 restore_privilege (&privs
);
5738 readlinkat (int fd
, char const *name
, char *buffer
,
5741 /* Rely on a hack: an open directory is modeled as file descriptor 0,
5742 as in fstatat. FIXME: Add proper support for readlinkat. */
5743 char fullname
[MAX_UTF8_PATH
];
5747 if (_snprintf (fullname
, sizeof fullname
, "%s/%s", dir_pathname
, name
)
5750 errno
= ENAMETOOLONG
;
5756 return readlink (name
, buffer
, buffer_size
);
5759 /* If FILE is a symlink, return its target (stored in a static
5760 buffer); otherwise return FILE.
5762 This function repeatedly resolves symlinks in the last component of
5763 a chain of symlink file names, as in foo -> bar -> baz -> ...,
5764 until it arrives at a file whose last component is not a symlink,
5765 or some error occurs. It returns the target of the last
5766 successfully resolved symlink in the chain. If it succeeds to
5767 resolve even a single symlink, the value returned is an absolute
5768 file name with backslashes (result of GetFullPathName). By
5769 contrast, if the original FILE is returned, it is unaltered.
5771 Note: This function can set errno even if it succeeds.
5773 Implementation note: we only resolve the last portion ("basename")
5774 of the argument FILE and of each following file in the chain,
5775 disregarding any possible symlinks in its leading directories.
5776 This is because Windows system calls and library functions
5777 transparently resolve symlinks in leading directories and return
5778 correct information, as long as the basename is not a symlink. */
5780 chase_symlinks (const char *file
)
5782 static char target
[MAX_UTF8_PATH
];
5783 char link
[MAX_UTF8_PATH
];
5784 wchar_t target_w
[MAX_PATH
], link_w
[MAX_PATH
];
5785 char target_a
[MAX_PATH
], link_a
[MAX_PATH
];
5786 ssize_t res
, link_len
;
5789 if (is_windows_9x () == TRUE
|| !is_symlink (file
))
5790 return (char *)file
;
5792 if (w32_unicode_filenames
)
5794 wchar_t file_w
[MAX_PATH
];
5796 filename_to_utf16 (file
, file_w
);
5797 if (GetFullPathNameW (file_w
, MAX_PATH
, link_w
, NULL
) == 0)
5798 return (char *)file
;
5799 filename_from_utf16 (link_w
, link
);
5803 char file_a
[MAX_PATH
];
5805 filename_to_ansi (file
, file_a
);
5806 if (GetFullPathNameA (file_a
, MAX_PATH
, link_a
, NULL
) == 0)
5807 return (char *)file
;
5808 filename_from_ansi (link_a
, link
);
5810 link_len
= strlen (link
);
5815 /* Remove trailing slashes, as we want to resolve the last
5816 non-trivial part of the link name. */
5817 while (link_len
> 3 && IS_DIRECTORY_SEP (link
[link_len
-1]))
5818 link
[link_len
--] = '\0';
5820 res
= readlink (link
, target
, MAX_UTF8_PATH
);
5824 if (!(IS_DEVICE_SEP (target
[1])
5825 || (IS_DIRECTORY_SEP (target
[0]) && IS_DIRECTORY_SEP (target
[1]))))
5827 /* Target is relative. Append it to the directory part of
5828 the symlink, then copy the result back to target. */
5829 char *p
= link
+ link_len
;
5831 while (p
> link
&& !IS_ANY_SEP (p
[-1]))
5834 strcpy (target
, link
);
5836 /* Resolve any "." and ".." to get a fully-qualified file name
5838 if (w32_unicode_filenames
)
5840 filename_to_utf16 (target
, target_w
);
5841 link_len
= GetFullPathNameW (target_w
, MAX_PATH
, link_w
, NULL
);
5843 filename_from_utf16 (link_w
, link
);
5847 filename_to_ansi (target
, target_a
);
5848 link_len
= GetFullPathNameA (target_a
, MAX_PATH
, link_a
, NULL
);
5850 filename_from_ansi (link_a
, link
);
5852 link_len
= strlen (link
);
5854 } while (res
> 0 && link_len
> 0 && ++loop_count
<= 100);
5856 if (loop_count
> 100)
5859 if (target
[0] == '\0') /* not a single call to readlink succeeded */
5860 return (char *)file
;
5865 /* Posix ACL emulation. */
5868 acl_valid (acl_t acl
)
5870 return is_valid_security_descriptor ((PSECURITY_DESCRIPTOR
)acl
) ? 0 : -1;
5874 acl_to_text (acl_t acl
, ssize_t
*size
)
5877 SECURITY_INFORMATION flags
=
5878 OWNER_SECURITY_INFORMATION
|
5879 GROUP_SECURITY_INFORMATION
|
5880 DACL_SECURITY_INFORMATION
;
5881 char *retval
= NULL
;
5887 if (convert_sd_to_sddl ((PSECURITY_DESCRIPTOR
)acl
, SDDL_REVISION_1
, flags
, &str_acl
, &local_size
))
5890 /* We don't want to mix heaps, so we duplicate the string in our
5891 heap and free the one allocated by the API. */
5892 retval
= xstrdup (str_acl
);
5895 LocalFree (str_acl
);
5897 else if (errno
!= ENOTSUP
)
5904 acl_from_text (const char *acl_str
)
5906 PSECURITY_DESCRIPTOR psd
, retval
= NULL
;
5912 if (convert_sddl_to_sd (acl_str
, SDDL_REVISION_1
, &psd
, &sd_size
))
5915 retval
= xmalloc (sd_size
);
5916 memcpy (retval
, psd
, sd_size
);
5919 else if (errno
!= ENOTSUP
)
5926 acl_free (void *ptr
)
5933 acl_get_file (const char *fname
, acl_type_t type
)
5935 PSECURITY_DESCRIPTOR psd
= NULL
;
5936 const char *filename
;
5938 if (type
== ACL_TYPE_ACCESS
)
5941 SECURITY_INFORMATION si
=
5942 OWNER_SECURITY_INFORMATION
|
5943 GROUP_SECURITY_INFORMATION
|
5944 DACL_SECURITY_INFORMATION
;
5947 filename
= map_w32_filename (fname
, NULL
);
5948 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) != 0)
5949 fname
= chase_symlinks (filename
);
5954 if (!get_file_security (fname
, si
, psd
, 0, &sd_len
)
5955 && errno
!= ENOTSUP
)
5957 err
= GetLastError ();
5958 if (err
== ERROR_INSUFFICIENT_BUFFER
)
5960 psd
= xmalloc (sd_len
);
5961 if (!get_file_security (fname
, si
, psd
, sd_len
, &sd_len
))
5968 else if (err
== ERROR_FILE_NOT_FOUND
5969 || err
== ERROR_PATH_NOT_FOUND
5970 /* ERROR_INVALID_NAME is what we get if
5971 w32-unicode-filenames is nil and the file cannot
5972 be encoded in the current ANSI codepage. */
5973 || err
== ERROR_INVALID_NAME
)
5981 else if (type
!= ACL_TYPE_DEFAULT
)
5988 acl_set_file (const char *fname
, acl_type_t type
, acl_t acl
)
5990 TOKEN_PRIVILEGES old1
, old2
;
5992 int st
= 0, retval
= -1;
5993 SECURITY_INFORMATION flags
= 0;
5994 PSID psidOwner
, psidGroup
;
5999 const char *filename
;
6001 if (acl_valid (acl
) != 0
6002 || (type
!= ACL_TYPE_DEFAULT
&& type
!= ACL_TYPE_ACCESS
))
6008 if (type
== ACL_TYPE_DEFAULT
)
6014 filename
= map_w32_filename (fname
, NULL
);
6015 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) != 0)
6016 fname
= chase_symlinks (filename
);
6020 if (get_security_descriptor_owner ((PSECURITY_DESCRIPTOR
)acl
, &psidOwner
,
6023 flags
|= OWNER_SECURITY_INFORMATION
;
6024 if (get_security_descriptor_group ((PSECURITY_DESCRIPTOR
)acl
, &psidGroup
,
6027 flags
|= GROUP_SECURITY_INFORMATION
;
6028 if (get_security_descriptor_dacl ((PSECURITY_DESCRIPTOR
)acl
, &dacl_present
,
6031 flags
|= DACL_SECURITY_INFORMATION
;
6035 /* According to KB-245153, setting the owner will succeed if either:
6036 (1) the caller is the user who will be the new owner, and has the
6037 SE_TAKE_OWNERSHIP privilege, or
6038 (2) the caller has the SE_RESTORE privilege, in which case she can
6039 set any valid user or group as the owner
6041 We request below both SE_TAKE_OWNERSHIP and SE_RESTORE
6042 privileges, and disregard any failures in obtaining them. If
6043 these privileges cannot be obtained, and do not already exist in
6044 the calling thread's security token, this function could fail
6046 if (enable_privilege (SE_TAKE_OWNERSHIP_NAME
, TRUE
, &old1
))
6048 if (enable_privilege (SE_RESTORE_NAME
, TRUE
, &old2
))
6053 /* SetFileSecurity is deprecated by MS, and sometimes fails when
6054 DACL inheritance is involved, but it seems to preserve ownership
6055 better than SetNamedSecurityInfo, which is important e.g., in
6057 if (!set_file_security (fname
, flags
, (PSECURITY_DESCRIPTOR
)acl
))
6059 err
= GetLastError ();
6061 if (errno
!= ENOTSUP
)
6062 err
= set_named_security_info (fname
, SE_FILE_OBJECT
, flags
,
6063 psidOwner
, psidGroup
, pacl
, NULL
);
6066 err
= ERROR_SUCCESS
;
6067 if (err
!= ERROR_SUCCESS
)
6069 if (errno
== ENOTSUP
)
6071 else if (err
== ERROR_INVALID_OWNER
6072 || err
== ERROR_NOT_ALL_ASSIGNED
6073 || err
== ERROR_ACCESS_DENIED
)
6075 /* Maybe the requested ACL and the one the file already has
6076 are identical, in which case we can silently ignore the
6077 failure. (And no, Windows doesn't.) */
6078 acl_t current_acl
= acl_get_file (fname
, ACL_TYPE_ACCESS
);
6083 char *acl_from
= acl_to_text (current_acl
, NULL
);
6084 char *acl_to
= acl_to_text (acl
, NULL
);
6086 if (acl_from
&& acl_to
&& xstrcasecmp (acl_from
, acl_to
) == 0)
6092 acl_free (acl_from
);
6095 acl_free (current_acl
);
6098 else if (err
== ERROR_FILE_NOT_FOUND
6099 || err
== ERROR_PATH_NOT_FOUND
6100 /* ERROR_INVALID_NAME is what we get if
6101 w32-unicode-filenames is nil and the file cannot be
6102 encoded in the current ANSI codepage. */
6103 || err
== ERROR_INVALID_NAME
)
6117 restore_privilege (&old2
);
6118 restore_privilege (&old1
);
6126 /* MS-Windows version of careadlinkat (cf. ../lib/careadlinkat.c). We
6127 have a fixed max size for file names, so we don't need the kind of
6128 alloc/malloc/realloc dance the gnulib version does. We also don't
6129 support FD-relative symlinks. */
6131 careadlinkat (int fd
, char const *filename
,
6132 char *buffer
, size_t buffer_size
,
6133 struct allocator
const *alloc
,
6134 ssize_t (*preadlinkat
) (int, char const *, char *, size_t))
6136 char linkname
[MAX_UTF8_PATH
];
6139 link_size
= preadlinkat (fd
, filename
, linkname
, sizeof(linkname
));
6143 char *retval
= buffer
;
6145 linkname
[link_size
++] = '\0';
6146 if (link_size
> buffer_size
)
6147 retval
= (char *)(alloc
? alloc
->allocate
: xmalloc
) (link_size
);
6149 memcpy (retval
, linkname
, link_size
);
6157 w32_copy_file (const char *from
, const char *to
,
6158 int keep_time
, int preserve_ownership
, int copy_acls
)
6162 wchar_t from_w
[MAX_PATH
], to_w
[MAX_PATH
];
6163 char from_a
[MAX_PATH
], to_a
[MAX_PATH
];
6165 /* We ignore preserve_ownership for now. */
6166 preserve_ownership
= preserve_ownership
;
6170 acl
= acl_get_file (from
, ACL_TYPE_ACCESS
);
6171 if (acl
== NULL
&& acl_errno_valid (errno
))
6174 if (w32_unicode_filenames
)
6176 filename_to_utf16 (from
, from_w
);
6177 filename_to_utf16 (to
, to_w
);
6178 copy_result
= CopyFileW (from_w
, to_w
, FALSE
);
6182 filename_to_ansi (from
, from_a
);
6183 filename_to_ansi (to
, to_a
);
6184 copy_result
= CopyFileA (from_a
, to_a
, FALSE
);
6188 /* CopyFile doesn't set errno when it fails. By far the most
6189 "popular" reason is that the target is read-only. */
6190 DWORD err
= GetLastError ();
6194 case ERROR_FILE_NOT_FOUND
:
6197 case ERROR_ACCESS_DENIED
:
6200 case ERROR_ENCRYPTION_FAILED
:
6212 /* CopyFile retains the timestamp by default. However, see
6213 "Community Additions" for CopyFile: it sounds like that is not
6214 entirely true. Testing on Windows XP confirms that modified time
6215 is copied, but creation and last-access times are not.
6217 else if (!keep_time
)
6219 struct timespec now
;
6222 if (w32_unicode_filenames
)
6224 /* Ensure file is writable while its times are set. */
6225 attributes
= GetFileAttributesW (to_w
);
6226 SetFileAttributesW (to_w
, attributes
& ~FILE_ATTRIBUTE_READONLY
);
6227 now
= current_timespec ();
6228 if (set_file_times (-1, to
, now
, now
))
6230 /* Restore original attributes. */
6231 SetFileAttributesW (to_w
, attributes
);
6236 /* Restore original attributes. */
6237 SetFileAttributesW (to_w
, attributes
);
6241 attributes
= GetFileAttributesA (to_a
);
6242 SetFileAttributesA (to_a
, attributes
& ~FILE_ATTRIBUTE_READONLY
);
6243 now
= current_timespec ();
6244 if (set_file_times (-1, to
, now
, now
))
6246 SetFileAttributesA (to_a
, attributes
);
6251 SetFileAttributesA (to_a
, attributes
);
6257 acl_set_file (to
, ACL_TYPE_ACCESS
, acl
) != 0;
6259 if (fail
&& acl_errno_valid (errno
))
6267 /* Support for browsing other processes and their attributes. See
6268 process.c for the Lisp bindings. */
6270 /* Helper wrapper functions. */
6272 static HANDLE WINAPI
6273 create_toolhelp32_snapshot (DWORD Flags
, DWORD Ignored
)
6275 static CreateToolhelp32Snapshot_Proc s_pfn_Create_Toolhelp32_Snapshot
= NULL
;
6277 if (g_b_init_create_toolhelp32_snapshot
== 0)
6279 g_b_init_create_toolhelp32_snapshot
= 1;
6280 s_pfn_Create_Toolhelp32_Snapshot
= (CreateToolhelp32Snapshot_Proc
)
6281 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6282 "CreateToolhelp32Snapshot");
6284 if (s_pfn_Create_Toolhelp32_Snapshot
== NULL
)
6286 return INVALID_HANDLE_VALUE
;
6288 return (s_pfn_Create_Toolhelp32_Snapshot (Flags
, Ignored
));
6292 process32_first (HANDLE hSnapshot
, LPPROCESSENTRY32 lppe
)
6294 static Process32First_Proc s_pfn_Process32_First
= NULL
;
6296 if (g_b_init_process32_first
== 0)
6298 g_b_init_process32_first
= 1;
6299 s_pfn_Process32_First
= (Process32First_Proc
)
6300 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6303 if (s_pfn_Process32_First
== NULL
)
6307 return (s_pfn_Process32_First (hSnapshot
, lppe
));
6311 process32_next (HANDLE hSnapshot
, LPPROCESSENTRY32 lppe
)
6313 static Process32Next_Proc s_pfn_Process32_Next
= NULL
;
6315 if (g_b_init_process32_next
== 0)
6317 g_b_init_process32_next
= 1;
6318 s_pfn_Process32_Next
= (Process32Next_Proc
)
6319 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6322 if (s_pfn_Process32_Next
== NULL
)
6326 return (s_pfn_Process32_Next (hSnapshot
, lppe
));
6330 open_thread_token (HANDLE ThreadHandle
,
6331 DWORD DesiredAccess
,
6333 PHANDLE TokenHandle
)
6335 static OpenThreadToken_Proc s_pfn_Open_Thread_Token
= NULL
;
6336 HMODULE hm_advapi32
= NULL
;
6337 if (is_windows_9x () == TRUE
)
6339 SetLastError (ERROR_NOT_SUPPORTED
);
6342 if (g_b_init_open_thread_token
== 0)
6344 g_b_init_open_thread_token
= 1;
6345 hm_advapi32
= LoadLibrary ("Advapi32.dll");
6346 s_pfn_Open_Thread_Token
=
6347 (OpenThreadToken_Proc
) GetProcAddress (hm_advapi32
, "OpenThreadToken");
6349 if (s_pfn_Open_Thread_Token
== NULL
)
6351 SetLastError (ERROR_NOT_SUPPORTED
);
6355 s_pfn_Open_Thread_Token (
6364 impersonate_self (SECURITY_IMPERSONATION_LEVEL ImpersonationLevel
)
6366 static ImpersonateSelf_Proc s_pfn_Impersonate_Self
= NULL
;
6367 HMODULE hm_advapi32
= NULL
;
6368 if (is_windows_9x () == TRUE
)
6372 if (g_b_init_impersonate_self
== 0)
6374 g_b_init_impersonate_self
= 1;
6375 hm_advapi32
= LoadLibrary ("Advapi32.dll");
6376 s_pfn_Impersonate_Self
=
6377 (ImpersonateSelf_Proc
) GetProcAddress (hm_advapi32
, "ImpersonateSelf");
6379 if (s_pfn_Impersonate_Self
== NULL
)
6383 return s_pfn_Impersonate_Self (ImpersonationLevel
);
6387 revert_to_self (void)
6389 static RevertToSelf_Proc s_pfn_Revert_To_Self
= NULL
;
6390 HMODULE hm_advapi32
= NULL
;
6391 if (is_windows_9x () == TRUE
)
6395 if (g_b_init_revert_to_self
== 0)
6397 g_b_init_revert_to_self
= 1;
6398 hm_advapi32
= LoadLibrary ("Advapi32.dll");
6399 s_pfn_Revert_To_Self
=
6400 (RevertToSelf_Proc
) GetProcAddress (hm_advapi32
, "RevertToSelf");
6402 if (s_pfn_Revert_To_Self
== NULL
)
6406 return s_pfn_Revert_To_Self ();
6410 get_process_memory_info (HANDLE h_proc
,
6411 PPROCESS_MEMORY_COUNTERS mem_counters
,
6414 static GetProcessMemoryInfo_Proc s_pfn_Get_Process_Memory_Info
= NULL
;
6415 HMODULE hm_psapi
= NULL
;
6416 if (is_windows_9x () == TRUE
)
6420 if (g_b_init_get_process_memory_info
== 0)
6422 g_b_init_get_process_memory_info
= 1;
6423 hm_psapi
= LoadLibrary ("Psapi.dll");
6425 s_pfn_Get_Process_Memory_Info
= (GetProcessMemoryInfo_Proc
)
6426 GetProcAddress (hm_psapi
, "GetProcessMemoryInfo");
6428 if (s_pfn_Get_Process_Memory_Info
== NULL
)
6432 return s_pfn_Get_Process_Memory_Info (h_proc
, mem_counters
, bufsize
);
6436 get_process_working_set_size (HANDLE h_proc
,
6440 static GetProcessWorkingSetSize_Proc
6441 s_pfn_Get_Process_Working_Set_Size
= NULL
;
6443 if (is_windows_9x () == TRUE
)
6447 if (g_b_init_get_process_working_set_size
== 0)
6449 g_b_init_get_process_working_set_size
= 1;
6450 s_pfn_Get_Process_Working_Set_Size
= (GetProcessWorkingSetSize_Proc
)
6451 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6452 "GetProcessWorkingSetSize");
6454 if (s_pfn_Get_Process_Working_Set_Size
== NULL
)
6458 return s_pfn_Get_Process_Working_Set_Size (h_proc
, minrss
, maxrss
);
6462 global_memory_status (MEMORYSTATUS
*buf
)
6464 static GlobalMemoryStatus_Proc s_pfn_Global_Memory_Status
= NULL
;
6466 if (is_windows_9x () == TRUE
)
6470 if (g_b_init_global_memory_status
== 0)
6472 g_b_init_global_memory_status
= 1;
6473 s_pfn_Global_Memory_Status
= (GlobalMemoryStatus_Proc
)
6474 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6475 "GlobalMemoryStatus");
6477 if (s_pfn_Global_Memory_Status
== NULL
)
6481 return s_pfn_Global_Memory_Status (buf
);
6485 global_memory_status_ex (MEMORY_STATUS_EX
*buf
)
6487 static GlobalMemoryStatusEx_Proc s_pfn_Global_Memory_Status_Ex
= NULL
;
6489 if (is_windows_9x () == TRUE
)
6493 if (g_b_init_global_memory_status_ex
== 0)
6495 g_b_init_global_memory_status_ex
= 1;
6496 s_pfn_Global_Memory_Status_Ex
= (GlobalMemoryStatusEx_Proc
)
6497 GetProcAddress (GetModuleHandle ("kernel32.dll"),
6498 "GlobalMemoryStatusEx");
6500 if (s_pfn_Global_Memory_Status_Ex
== NULL
)
6504 return s_pfn_Global_Memory_Status_Ex (buf
);
6508 list_system_processes (void)
6510 struct gcpro gcpro1
;
6511 Lisp_Object proclist
= Qnil
;
6514 h_snapshot
= create_toolhelp32_snapshot (TH32CS_SNAPPROCESS
, 0);
6516 if (h_snapshot
!= INVALID_HANDLE_VALUE
)
6518 PROCESSENTRY32 proc_entry
;
6524 proc_entry
.dwSize
= sizeof (PROCESSENTRY32
);
6525 for (res
= process32_first (h_snapshot
, &proc_entry
); res
;
6526 res
= process32_next (h_snapshot
, &proc_entry
))
6528 proc_id
= proc_entry
.th32ProcessID
;
6529 proclist
= Fcons (make_fixnum_or_float (proc_id
), proclist
);
6532 CloseHandle (h_snapshot
);
6534 proclist
= Fnreverse (proclist
);
6541 enable_privilege (LPCTSTR priv_name
, BOOL enable_p
, TOKEN_PRIVILEGES
*old_priv
)
6543 TOKEN_PRIVILEGES priv
;
6544 DWORD priv_size
= sizeof (priv
);
6545 DWORD opriv_size
= sizeof (*old_priv
);
6546 HANDLE h_token
= NULL
;
6547 HANDLE h_thread
= GetCurrentThread ();
6551 res
= open_thread_token (h_thread
,
6552 TOKEN_QUERY
| TOKEN_ADJUST_PRIVILEGES
,
6554 if (!res
&& GetLastError () == ERROR_NO_TOKEN
)
6556 if (impersonate_self (SecurityImpersonation
))
6557 res
= open_thread_token (h_thread
,
6558 TOKEN_QUERY
| TOKEN_ADJUST_PRIVILEGES
,
6563 priv
.PrivilegeCount
= 1;
6564 priv
.Privileges
[0].Attributes
= enable_p
? SE_PRIVILEGE_ENABLED
: 0;
6565 LookupPrivilegeValue (NULL
, priv_name
, &priv
.Privileges
[0].Luid
);
6566 if (AdjustTokenPrivileges (h_token
, FALSE
, &priv
, priv_size
,
6567 old_priv
, &opriv_size
)
6568 && GetLastError () != ERROR_NOT_ALL_ASSIGNED
)
6572 CloseHandle (h_token
);
6578 restore_privilege (TOKEN_PRIVILEGES
*priv
)
6580 DWORD priv_size
= sizeof (*priv
);
6581 HANDLE h_token
= NULL
;
6584 if (open_thread_token (GetCurrentThread (),
6585 TOKEN_QUERY
| TOKEN_ADJUST_PRIVILEGES
,
6588 if (AdjustTokenPrivileges (h_token
, FALSE
, priv
, priv_size
, NULL
, NULL
)
6589 && GetLastError () != ERROR_NOT_ALL_ASSIGNED
)
6593 CloseHandle (h_token
);
6599 ltime (ULONGLONG time_100ns
)
6601 ULONGLONG time_sec
= time_100ns
/ 10000000;
6602 int subsec
= time_100ns
% 10000000;
6603 return list4i (time_sec
>> 16, time_sec
& 0xffff,
6604 subsec
/ 10, subsec
% 10 * 100000);
6607 #define U64_TO_LISP_TIME(time) ltime (time)
6610 process_times (HANDLE h_proc
, Lisp_Object
*ctime
, Lisp_Object
*etime
,
6611 Lisp_Object
*stime
, Lisp_Object
*utime
, Lisp_Object
*ttime
,
6614 FILETIME ft_creation
, ft_exit
, ft_kernel
, ft_user
, ft_current
;
6615 ULONGLONG tem1
, tem2
, tem3
, tem
;
6618 || !get_process_times_fn
6619 || !(*get_process_times_fn
) (h_proc
, &ft_creation
, &ft_exit
,
6620 &ft_kernel
, &ft_user
))
6623 GetSystemTimeAsFileTime (&ft_current
);
6625 FILETIME_TO_U64 (tem1
, ft_kernel
);
6626 *stime
= U64_TO_LISP_TIME (tem1
);
6628 FILETIME_TO_U64 (tem2
, ft_user
);
6629 *utime
= U64_TO_LISP_TIME (tem2
);
6632 *ttime
= U64_TO_LISP_TIME (tem3
);
6634 FILETIME_TO_U64 (tem
, ft_creation
);
6635 /* Process no 4 (System) returns zero creation time. */
6638 *ctime
= U64_TO_LISP_TIME (tem
);
6642 FILETIME_TO_U64 (tem3
, ft_current
);
6643 tem
= (tem3
- utc_base
) - tem
;
6645 *etime
= U64_TO_LISP_TIME (tem
);
6649 *pcpu
= 100.0 * (tem1
+ tem2
) / tem
;
6660 system_process_attributes (Lisp_Object pid
)
6662 struct gcpro gcpro1
, gcpro2
, gcpro3
;
6663 Lisp_Object attrs
= Qnil
;
6664 Lisp_Object cmd_str
, decoded_cmd
, tem
;
6665 HANDLE h_snapshot
, h_proc
;
6668 char uname
[UNLEN
+1], gname
[GNLEN
+1], domain
[1025];
6669 DWORD ulength
= sizeof (uname
), dlength
= sizeof (domain
), needed
;
6670 DWORD glength
= sizeof (gname
);
6671 HANDLE token
= NULL
;
6672 SID_NAME_USE user_type
;
6673 unsigned char *buf
= NULL
;
6675 TOKEN_USER user_token
;
6676 TOKEN_PRIMARY_GROUP group_token
;
6679 PROCESS_MEMORY_COUNTERS mem
;
6680 PROCESS_MEMORY_COUNTERS_EX mem_ex
;
6681 SIZE_T minrss
, maxrss
;
6683 MEMORY_STATUS_EX memstex
;
6684 double totphys
= 0.0;
6685 Lisp_Object ctime
, stime
, utime
, etime
, ttime
;
6687 BOOL result
= FALSE
;
6689 CHECK_NUMBER_OR_FLOAT (pid
);
6690 proc_id
= FLOATP (pid
) ? XFLOAT_DATA (pid
) : XINT (pid
);
6692 h_snapshot
= create_toolhelp32_snapshot (TH32CS_SNAPPROCESS
, 0);
6694 GCPRO3 (attrs
, decoded_cmd
, tem
);
6696 if (h_snapshot
!= INVALID_HANDLE_VALUE
)
6701 pe
.dwSize
= sizeof (PROCESSENTRY32
);
6702 for (res
= process32_first (h_snapshot
, &pe
); res
;
6703 res
= process32_next (h_snapshot
, &pe
))
6705 if (proc_id
== pe
.th32ProcessID
)
6708 decoded_cmd
= build_string ("Idle");
6711 /* Decode the command name from locale-specific
6713 cmd_str
= build_unibyte_string (pe
.szExeFile
);
6716 code_convert_string_norecord (cmd_str
,
6717 Vlocale_coding_system
, 0);
6719 attrs
= Fcons (Fcons (Qcomm
, decoded_cmd
), attrs
);
6720 attrs
= Fcons (Fcons (Qppid
,
6721 make_fixnum_or_float (pe
.th32ParentProcessID
)),
6723 attrs
= Fcons (Fcons (Qpri
, make_number (pe
.pcPriClassBase
)),
6725 attrs
= Fcons (Fcons (Qthcount
,
6726 make_fixnum_or_float (pe
.cntThreads
)),
6733 CloseHandle (h_snapshot
);
6742 h_proc
= OpenProcess (PROCESS_QUERY_INFORMATION
| PROCESS_VM_READ
,
6744 /* If we were denied a handle to the process, try again after
6745 enabling the SeDebugPrivilege in our process. */
6748 TOKEN_PRIVILEGES priv_current
;
6750 if (enable_privilege (SE_DEBUG_NAME
, TRUE
, &priv_current
))
6752 h_proc
= OpenProcess (PROCESS_QUERY_INFORMATION
| PROCESS_VM_READ
,
6754 restore_privilege (&priv_current
);
6760 result
= open_process_token (h_proc
, TOKEN_QUERY
, &token
);
6763 result
= get_token_information (token
, TokenUser
, NULL
, 0, &blen
);
6764 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
6766 buf
= xmalloc (blen
);
6767 result
= get_token_information (token
, TokenUser
,
6768 (LPVOID
)buf
, blen
, &needed
);
6771 memcpy (&user_token
, buf
, sizeof (user_token
));
6772 if (!w32_cached_id (user_token
.User
.Sid
, &euid
, uname
))
6774 euid
= get_rid (user_token
.User
.Sid
);
6775 result
= lookup_account_sid (NULL
, user_token
.User
.Sid
,
6780 w32_add_to_cache (user_token
.User
.Sid
, euid
, uname
);
6783 strcpy (uname
, "unknown");
6787 ulength
= strlen (uname
);
6793 /* Determine a reasonable euid and gid values. */
6794 if (xstrcasecmp ("administrator", uname
) == 0)
6796 euid
= 500; /* well-known Administrator uid */
6797 egid
= 513; /* well-known None gid */
6801 /* Get group id and name. */
6802 result
= get_token_information (token
, TokenPrimaryGroup
,
6803 (LPVOID
)buf
, blen
, &needed
);
6804 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
6806 buf
= xrealloc (buf
, blen
= needed
);
6807 result
= get_token_information (token
, TokenPrimaryGroup
,
6808 (LPVOID
)buf
, blen
, &needed
);
6812 memcpy (&group_token
, buf
, sizeof (group_token
));
6813 if (!w32_cached_id (group_token
.PrimaryGroup
, &egid
, gname
))
6815 egid
= get_rid (group_token
.PrimaryGroup
);
6816 dlength
= sizeof (domain
);
6818 lookup_account_sid (NULL
, group_token
.PrimaryGroup
,
6819 gname
, &glength
, NULL
, &dlength
,
6822 w32_add_to_cache (group_token
.PrimaryGroup
,
6826 strcpy (gname
, "None");
6830 glength
= strlen (gname
);
6838 if (!is_windows_9x ())
6840 /* We couldn't open the process token, presumably because of
6841 insufficient access rights. Assume this process is run
6843 strcpy (uname
, "SYSTEM");
6844 strcpy (gname
, "None");
6845 euid
= 18; /* SYSTEM */
6846 egid
= 513; /* None */
6847 glength
= strlen (gname
);
6848 ulength
= strlen (uname
);
6850 /* If we are running under Windows 9X, where security calls are
6851 not supported, we assume all processes are run by the current
6853 else if (GetUserName (uname
, &ulength
))
6855 if (xstrcasecmp ("administrator", uname
) == 0)
6860 strcpy (gname
, "None");
6861 glength
= strlen (gname
);
6862 ulength
= strlen (uname
);
6868 strcpy (uname
, "administrator");
6869 ulength
= strlen (uname
);
6870 strcpy (gname
, "None");
6871 glength
= strlen (gname
);
6874 CloseHandle (token
);
6877 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (euid
)), attrs
);
6878 tem
= make_unibyte_string (uname
, ulength
);
6879 attrs
= Fcons (Fcons (Quser
,
6880 code_convert_string_norecord (tem
, Vlocale_coding_system
, 0)),
6882 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (egid
)), attrs
);
6883 tem
= make_unibyte_string (gname
, glength
);
6884 attrs
= Fcons (Fcons (Qgroup
,
6885 code_convert_string_norecord (tem
, Vlocale_coding_system
, 0)),
6888 if (global_memory_status_ex (&memstex
))
6889 #if __GNUC__ || (defined (_MSC_VER) && _MSC_VER >= 1300)
6890 totphys
= memstex
.ullTotalPhys
/ 1024.0;
6892 /* Visual Studio 6 cannot convert an unsigned __int64 type to
6893 double, so we need to do this for it... */
6895 DWORD tot_hi
= memstex
.ullTotalPhys
>> 32;
6896 DWORD tot_md
= (memstex
.ullTotalPhys
& 0x00000000ffffffff) >> 10;
6897 DWORD tot_lo
= memstex
.ullTotalPhys
% 1024;
6899 totphys
= tot_hi
* 4194304.0 + tot_md
+ tot_lo
/ 1024.0;
6901 #endif /* __GNUC__ || _MSC_VER >= 1300 */
6902 else if (global_memory_status (&memst
))
6903 totphys
= memst
.dwTotalPhys
/ 1024.0;
6906 && get_process_memory_info (h_proc
, (PROCESS_MEMORY_COUNTERS
*)&mem_ex
,
6909 SIZE_T rss
= mem_ex
.WorkingSetSize
/ 1024;
6911 attrs
= Fcons (Fcons (Qmajflt
,
6912 make_fixnum_or_float (mem_ex
.PageFaultCount
)),
6914 attrs
= Fcons (Fcons (Qvsize
,
6915 make_fixnum_or_float (mem_ex
.PrivateUsage
/ 1024)),
6917 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (rss
)), attrs
);
6919 attrs
= Fcons (Fcons (Qpmem
, make_float (100. * rss
/ totphys
)), attrs
);
6922 && get_process_memory_info (h_proc
, &mem
, sizeof (mem
)))
6924 SIZE_T rss
= mem_ex
.WorkingSetSize
/ 1024;
6926 attrs
= Fcons (Fcons (Qmajflt
,
6927 make_fixnum_or_float (mem
.PageFaultCount
)),
6929 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (rss
)), attrs
);
6931 attrs
= Fcons (Fcons (Qpmem
, make_float (100. * rss
/ totphys
)), attrs
);
6934 && get_process_working_set_size (h_proc
, &minrss
, &maxrss
))
6936 DWORD rss
= maxrss
/ 1024;
6938 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (maxrss
/ 1024)), attrs
);
6940 attrs
= Fcons (Fcons (Qpmem
, make_float (100. * rss
/ totphys
)), attrs
);
6943 if (process_times (h_proc
, &ctime
, &etime
, &stime
, &utime
, &ttime
, &pcpu
))
6945 attrs
= Fcons (Fcons (Qutime
, utime
), attrs
);
6946 attrs
= Fcons (Fcons (Qstime
, stime
), attrs
);
6947 attrs
= Fcons (Fcons (Qtime
, ttime
), attrs
);
6948 attrs
= Fcons (Fcons (Qstart
, ctime
), attrs
);
6949 attrs
= Fcons (Fcons (Qetime
, etime
), attrs
);
6950 attrs
= Fcons (Fcons (Qpcpu
, make_float (pcpu
)), attrs
);
6953 /* FIXME: Retrieve command line by walking the PEB of the process. */
6956 CloseHandle (h_proc
);
6962 w32_memory_info (unsigned long long *totalram
, unsigned long long *freeram
,
6963 unsigned long long *totalswap
, unsigned long long *freeswap
)
6966 MEMORY_STATUS_EX memstex
;
6968 /* Use GlobalMemoryStatusEx if available, as it can report more than
6970 if (global_memory_status_ex (&memstex
))
6972 *totalram
= memstex
.ullTotalPhys
;
6973 *freeram
= memstex
.ullAvailPhys
;
6974 *totalswap
= memstex
.ullTotalPageFile
;
6975 *freeswap
= memstex
.ullAvailPageFile
;
6978 else if (global_memory_status (&memst
))
6980 *totalram
= memst
.dwTotalPhys
;
6981 *freeram
= memst
.dwAvailPhys
;
6982 *totalswap
= memst
.dwTotalPageFile
;
6983 *freeswap
= memst
.dwAvailPageFile
;
6991 /* Wrappers for winsock functions to map between our file descriptors
6992 and winsock's handles; also set h_errno for convenience.
6994 To allow Emacs to run on systems which don't have winsock support
6995 installed, we dynamically link to winsock on startup if present, and
6996 otherwise provide the minimum necessary functionality
6997 (eg. gethostname). */
6999 /* function pointers for relevant socket functions */
7000 int (PASCAL
*pfn_WSAStartup
) (WORD wVersionRequired
, LPWSADATA lpWSAData
);
7001 void (PASCAL
*pfn_WSASetLastError
) (int iError
);
7002 int (PASCAL
*pfn_WSAGetLastError
) (void);
7003 int (PASCAL
*pfn_WSAEventSelect
) (SOCKET s
, HANDLE hEventObject
, long lNetworkEvents
);
7004 HANDLE (PASCAL
*pfn_WSACreateEvent
) (void);
7005 int (PASCAL
*pfn_WSACloseEvent
) (HANDLE hEvent
);
7006 int (PASCAL
*pfn_socket
) (int af
, int type
, int protocol
);
7007 int (PASCAL
*pfn_bind
) (SOCKET s
, const struct sockaddr
*addr
, int namelen
);
7008 int (PASCAL
*pfn_connect
) (SOCKET s
, const struct sockaddr
*addr
, int namelen
);
7009 int (PASCAL
*pfn_ioctlsocket
) (SOCKET s
, long cmd
, u_long
*argp
);
7010 int (PASCAL
*pfn_recv
) (SOCKET s
, char * buf
, int len
, int flags
);
7011 int (PASCAL
*pfn_send
) (SOCKET s
, const char * buf
, int len
, int flags
);
7012 int (PASCAL
*pfn_closesocket
) (SOCKET s
);
7013 int (PASCAL
*pfn_shutdown
) (SOCKET s
, int how
);
7014 int (PASCAL
*pfn_WSACleanup
) (void);
7016 u_short (PASCAL
*pfn_htons
) (u_short hostshort
);
7017 u_short (PASCAL
*pfn_ntohs
) (u_short netshort
);
7018 unsigned long (PASCAL
*pfn_inet_addr
) (const char * cp
);
7019 int (PASCAL
*pfn_gethostname
) (char * name
, int namelen
);
7020 struct hostent
* (PASCAL
*pfn_gethostbyname
) (const char * name
);
7021 struct servent
* (PASCAL
*pfn_getservbyname
) (const char * name
, const char * proto
);
7022 int (PASCAL
*pfn_getpeername
) (SOCKET s
, struct sockaddr
*addr
, int * namelen
);
7023 int (PASCAL
*pfn_setsockopt
) (SOCKET s
, int level
, int optname
,
7024 const char * optval
, int optlen
);
7025 int (PASCAL
*pfn_listen
) (SOCKET s
, int backlog
);
7026 int (PASCAL
*pfn_getsockname
) (SOCKET s
, struct sockaddr
* name
,
7028 SOCKET (PASCAL
*pfn_accept
) (SOCKET s
, struct sockaddr
* addr
, int * addrlen
);
7029 int (PASCAL
*pfn_recvfrom
) (SOCKET s
, char * buf
, int len
, int flags
,
7030 struct sockaddr
* from
, int * fromlen
);
7031 int (PASCAL
*pfn_sendto
) (SOCKET s
, const char * buf
, int len
, int flags
,
7032 const struct sockaddr
* to
, int tolen
);
7034 /* SetHandleInformation is only needed to make sockets non-inheritable. */
7035 BOOL (WINAPI
*pfn_SetHandleInformation
) (HANDLE object
, DWORD mask
, DWORD flags
);
7036 #ifndef HANDLE_FLAG_INHERIT
7037 #define HANDLE_FLAG_INHERIT 1
7041 static int winsock_inuse
;
7046 if (winsock_lib
!= NULL
&& winsock_inuse
== 0)
7048 release_listen_threads ();
7049 /* Not sure what would cause WSAENETDOWN, or even if it can happen
7050 after WSAStartup returns successfully, but it seems reasonable
7051 to allow unloading winsock anyway in that case. */
7052 if (pfn_WSACleanup () == 0 ||
7053 pfn_WSAGetLastError () == WSAENETDOWN
)
7055 if (FreeLibrary (winsock_lib
))
7064 init_winsock (int load_now
)
7066 WSADATA winsockData
;
7068 if (winsock_lib
!= NULL
)
7071 pfn_SetHandleInformation
7072 = (void *) GetProcAddress (GetModuleHandle ("kernel32.dll"),
7073 "SetHandleInformation");
7075 winsock_lib
= LoadLibrary ("Ws2_32.dll");
7077 if (winsock_lib
!= NULL
)
7079 /* dynamically link to socket functions */
7081 #define LOAD_PROC(fn) \
7082 if ((pfn_##fn = (void *) GetProcAddress (winsock_lib, #fn)) == NULL) \
7085 LOAD_PROC (WSAStartup
);
7086 LOAD_PROC (WSASetLastError
);
7087 LOAD_PROC (WSAGetLastError
);
7088 LOAD_PROC (WSAEventSelect
);
7089 LOAD_PROC (WSACreateEvent
);
7090 LOAD_PROC (WSACloseEvent
);
7093 LOAD_PROC (connect
);
7094 LOAD_PROC (ioctlsocket
);
7097 LOAD_PROC (closesocket
);
7098 LOAD_PROC (shutdown
);
7101 LOAD_PROC (inet_addr
);
7102 LOAD_PROC (gethostname
);
7103 LOAD_PROC (gethostbyname
);
7104 LOAD_PROC (getservbyname
);
7105 LOAD_PROC (getpeername
);
7106 LOAD_PROC (WSACleanup
);
7107 LOAD_PROC (setsockopt
);
7109 LOAD_PROC (getsockname
);
7111 LOAD_PROC (recvfrom
);
7115 /* specify version 1.1 of winsock */
7116 if (pfn_WSAStartup (0x101, &winsockData
) == 0)
7118 if (winsockData
.wVersion
!= 0x101)
7123 /* Report that winsock exists and is usable, but leave
7124 socket functions disabled. I am assuming that calling
7125 WSAStartup does not require any network interaction,
7126 and in particular does not cause or require a dial-up
7127 connection to be established. */
7130 FreeLibrary (winsock_lib
);
7138 FreeLibrary (winsock_lib
);
7148 /* Function to map winsock error codes to errno codes for those errno
7149 code defined in errno.h (errno values not defined by errno.h are
7150 already in nt/inc/sys/socket.h). */
7157 if (winsock_lib
== NULL
)
7160 wsa_err
= pfn_WSAGetLastError ();
7164 case WSAEACCES
: errno
= EACCES
; break;
7165 case WSAEBADF
: errno
= EBADF
; break;
7166 case WSAEFAULT
: errno
= EFAULT
; break;
7167 case WSAEINTR
: errno
= EINTR
; break;
7168 case WSAEINVAL
: errno
= EINVAL
; break;
7169 case WSAEMFILE
: errno
= EMFILE
; break;
7170 case WSAENAMETOOLONG
: errno
= ENAMETOOLONG
; break;
7171 case WSAENOTEMPTY
: errno
= ENOTEMPTY
; break;
7172 default: errno
= wsa_err
; break;
7180 if (winsock_lib
!= NULL
)
7181 pfn_WSASetLastError (0);
7184 /* Extend strerror to handle the winsock-specific error codes. */
7188 } _wsa_errlist
[] = {
7189 {WSAEINTR
, "Interrupted function call"},
7190 {WSAEBADF
, "Bad file descriptor"},
7191 {WSAEACCES
, "Permission denied"},
7192 {WSAEFAULT
, "Bad address"},
7193 {WSAEINVAL
, "Invalid argument"},
7194 {WSAEMFILE
, "Too many open files"},
7196 {WSAEWOULDBLOCK
, "Resource temporarily unavailable"},
7197 {WSAEINPROGRESS
, "Operation now in progress"},
7198 {WSAEALREADY
, "Operation already in progress"},
7199 {WSAENOTSOCK
, "Socket operation on non-socket"},
7200 {WSAEDESTADDRREQ
, "Destination address required"},
7201 {WSAEMSGSIZE
, "Message too long"},
7202 {WSAEPROTOTYPE
, "Protocol wrong type for socket"},
7203 {WSAENOPROTOOPT
, "Bad protocol option"},
7204 {WSAEPROTONOSUPPORT
, "Protocol not supported"},
7205 {WSAESOCKTNOSUPPORT
, "Socket type not supported"},
7206 {WSAEOPNOTSUPP
, "Operation not supported"},
7207 {WSAEPFNOSUPPORT
, "Protocol family not supported"},
7208 {WSAEAFNOSUPPORT
, "Address family not supported by protocol family"},
7209 {WSAEADDRINUSE
, "Address already in use"},
7210 {WSAEADDRNOTAVAIL
, "Cannot assign requested address"},
7211 {WSAENETDOWN
, "Network is down"},
7212 {WSAENETUNREACH
, "Network is unreachable"},
7213 {WSAENETRESET
, "Network dropped connection on reset"},
7214 {WSAECONNABORTED
, "Software caused connection abort"},
7215 {WSAECONNRESET
, "Connection reset by peer"},
7216 {WSAENOBUFS
, "No buffer space available"},
7217 {WSAEISCONN
, "Socket is already connected"},
7218 {WSAENOTCONN
, "Socket is not connected"},
7219 {WSAESHUTDOWN
, "Cannot send after socket shutdown"},
7220 {WSAETOOMANYREFS
, "Too many references"}, /* not sure */
7221 {WSAETIMEDOUT
, "Connection timed out"},
7222 {WSAECONNREFUSED
, "Connection refused"},
7223 {WSAELOOP
, "Network loop"}, /* not sure */
7224 {WSAENAMETOOLONG
, "Name is too long"},
7225 {WSAEHOSTDOWN
, "Host is down"},
7226 {WSAEHOSTUNREACH
, "No route to host"},
7227 {WSAENOTEMPTY
, "Buffer not empty"}, /* not sure */
7228 {WSAEPROCLIM
, "Too many processes"},
7229 {WSAEUSERS
, "Too many users"}, /* not sure */
7230 {WSAEDQUOT
, "Double quote in host name"}, /* really not sure */
7231 {WSAESTALE
, "Data is stale"}, /* not sure */
7232 {WSAEREMOTE
, "Remote error"}, /* not sure */
7234 {WSASYSNOTREADY
, "Network subsystem is unavailable"},
7235 {WSAVERNOTSUPPORTED
, "WINSOCK.DLL version out of range"},
7236 {WSANOTINITIALISED
, "Winsock not initialized successfully"},
7237 {WSAEDISCON
, "Graceful shutdown in progress"},
7239 {WSAENOMORE
, "No more operations allowed"}, /* not sure */
7240 {WSAECANCELLED
, "Operation cancelled"}, /* not sure */
7241 {WSAEINVALIDPROCTABLE
, "Invalid procedure table from service provider"},
7242 {WSAEINVALIDPROVIDER
, "Invalid service provider version number"},
7243 {WSAEPROVIDERFAILEDINIT
, "Unable to initialize a service provider"},
7244 {WSASYSCALLFAILURE
, "System call failure"},
7245 {WSASERVICE_NOT_FOUND
, "Service not found"}, /* not sure */
7246 {WSATYPE_NOT_FOUND
, "Class type not found"},
7247 {WSA_E_NO_MORE
, "No more resources available"}, /* really not sure */
7248 {WSA_E_CANCELLED
, "Operation already cancelled"}, /* really not sure */
7249 {WSAEREFUSED
, "Operation refused"}, /* not sure */
7252 {WSAHOST_NOT_FOUND
, "Host not found"},
7253 {WSATRY_AGAIN
, "Authoritative host not found during name lookup"},
7254 {WSANO_RECOVERY
, "Non-recoverable error during name lookup"},
7255 {WSANO_DATA
, "Valid name, no data record of requested type"},
7261 sys_strerror (int error_no
)
7264 static char unknown_msg
[40];
7266 if (error_no
>= 0 && error_no
< sys_nerr
)
7267 return sys_errlist
[error_no
];
7269 for (i
= 0; _wsa_errlist
[i
].errnum
>= 0; i
++)
7270 if (_wsa_errlist
[i
].errnum
== error_no
)
7271 return _wsa_errlist
[i
].msg
;
7273 sprintf (unknown_msg
, "Unidentified error: %d", error_no
);
7277 /* [andrewi 3-May-96] I've had conflicting results using both methods,
7278 but I believe the method of keeping the socket handle separate (and
7279 insuring it is not inheritable) is the correct one. */
7281 #define SOCK_HANDLE(fd) ((SOCKET) fd_info[fd].hnd)
7283 static int socket_to_fd (SOCKET s
);
7286 sys_socket (int af
, int type
, int protocol
)
7290 if (winsock_lib
== NULL
)
7293 return INVALID_SOCKET
;
7298 /* call the real socket function */
7299 s
= pfn_socket (af
, type
, protocol
);
7301 if (s
!= INVALID_SOCKET
)
7302 return socket_to_fd (s
);
7308 /* Convert a SOCKET to a file descriptor. */
7310 socket_to_fd (SOCKET s
)
7315 /* Although under NT 3.5 _open_osfhandle will accept a socket
7316 handle, if opened with SO_OPENTYPE == SO_SYNCHRONOUS_NONALERT,
7317 that does not work under NT 3.1. However, we can get the same
7318 effect by using a backdoor function to replace an existing
7319 descriptor handle with the one we want. */
7321 /* allocate a file descriptor (with appropriate flags) */
7322 fd
= _open ("NUL:", _O_RDWR
);
7325 /* Make a non-inheritable copy of the socket handle. Note
7326 that it is possible that sockets aren't actually kernel
7327 handles, which appears to be the case on Windows 9x when
7328 the MS Proxy winsock client is installed. */
7330 /* Apparently there is a bug in NT 3.51 with some service
7331 packs, which prevents using DuplicateHandle to make a
7332 socket handle non-inheritable (causes WSACleanup to
7333 hang). The work-around is to use SetHandleInformation
7334 instead if it is available and implemented. */
7335 if (pfn_SetHandleInformation
)
7337 pfn_SetHandleInformation ((HANDLE
) s
, HANDLE_FLAG_INHERIT
, 0);
7341 HANDLE parent
= GetCurrentProcess ();
7342 HANDLE new_s
= INVALID_HANDLE_VALUE
;
7344 if (DuplicateHandle (parent
,
7350 DUPLICATE_SAME_ACCESS
))
7352 /* It is possible that DuplicateHandle succeeds even
7353 though the socket wasn't really a kernel handle,
7354 because a real handle has the same value. So
7355 test whether the new handle really is a socket. */
7356 long nonblocking
= 0;
7357 if (pfn_ioctlsocket ((SOCKET
) new_s
, FIONBIO
, &nonblocking
) == 0)
7359 pfn_closesocket (s
);
7364 CloseHandle (new_s
);
7369 eassert (fd
< MAXDESC
);
7370 fd_info
[fd
].hnd
= (HANDLE
) s
;
7372 /* set our own internal flags */
7373 fd_info
[fd
].flags
= FILE_SOCKET
| FILE_BINARY
| FILE_READ
| FILE_WRITE
;
7379 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
7381 /* attach child_process to fd_info */
7382 if (fd_info
[ fd
].cp
!= NULL
)
7384 DebPrint (("sys_socket: fd_info[%d] apparently in use!\n", fd
));
7388 fd_info
[ fd
].cp
= cp
;
7391 winsock_inuse
++; /* count open sockets */
7399 pfn_closesocket (s
);
7405 sys_bind (int s
, const struct sockaddr
* addr
, int namelen
)
7407 if (winsock_lib
== NULL
)
7410 return SOCKET_ERROR
;
7414 if (fd_info
[s
].flags
& FILE_SOCKET
)
7416 int rc
= pfn_bind (SOCK_HANDLE (s
), addr
, namelen
);
7417 if (rc
== SOCKET_ERROR
)
7422 return SOCKET_ERROR
;
7426 sys_connect (int s
, const struct sockaddr
* name
, int namelen
)
7428 if (winsock_lib
== NULL
)
7431 return SOCKET_ERROR
;
7435 if (fd_info
[s
].flags
& FILE_SOCKET
)
7437 int rc
= pfn_connect (SOCK_HANDLE (s
), name
, namelen
);
7438 if (rc
== SOCKET_ERROR
)
7443 return SOCKET_ERROR
;
7447 sys_htons (u_short hostshort
)
7449 return (winsock_lib
!= NULL
) ?
7450 pfn_htons (hostshort
) : hostshort
;
7454 sys_ntohs (u_short netshort
)
7456 return (winsock_lib
!= NULL
) ?
7457 pfn_ntohs (netshort
) : netshort
;
7461 sys_inet_addr (const char * cp
)
7463 return (winsock_lib
!= NULL
) ?
7464 pfn_inet_addr (cp
) : INADDR_NONE
;
7468 sys_gethostname (char * name
, int namelen
)
7470 if (winsock_lib
!= NULL
)
7475 retval
= pfn_gethostname (name
, namelen
);
7476 if (retval
== SOCKET_ERROR
)
7481 if (namelen
> MAX_COMPUTERNAME_LENGTH
)
7482 return !GetComputerName (name
, (DWORD
*)&namelen
);
7485 return SOCKET_ERROR
;
7489 sys_gethostbyname (const char * name
)
7491 struct hostent
* host
;
7492 int h_err
= h_errno
;
7494 if (winsock_lib
== NULL
)
7496 h_errno
= NO_RECOVERY
;
7502 host
= pfn_gethostbyname (name
);
7514 sys_getservbyname (const char * name
, const char * proto
)
7516 struct servent
* serv
;
7518 if (winsock_lib
== NULL
)
7525 serv
= pfn_getservbyname (name
, proto
);
7532 sys_getpeername (int s
, struct sockaddr
*addr
, int * namelen
)
7534 if (winsock_lib
== NULL
)
7537 return SOCKET_ERROR
;
7541 if (fd_info
[s
].flags
& FILE_SOCKET
)
7543 int rc
= pfn_getpeername (SOCK_HANDLE (s
), addr
, namelen
);
7544 if (rc
== SOCKET_ERROR
)
7549 return SOCKET_ERROR
;
7553 sys_shutdown (int s
, int how
)
7555 if (winsock_lib
== NULL
)
7558 return SOCKET_ERROR
;
7562 if (fd_info
[s
].flags
& FILE_SOCKET
)
7564 int rc
= pfn_shutdown (SOCK_HANDLE (s
), how
);
7565 if (rc
== SOCKET_ERROR
)
7570 return SOCKET_ERROR
;
7574 sys_setsockopt (int s
, int level
, int optname
, const void * optval
, int optlen
)
7576 if (winsock_lib
== NULL
)
7579 return SOCKET_ERROR
;
7583 if (fd_info
[s
].flags
& FILE_SOCKET
)
7585 int rc
= pfn_setsockopt (SOCK_HANDLE (s
), level
, optname
,
7586 (const char *)optval
, optlen
);
7587 if (rc
== SOCKET_ERROR
)
7592 return SOCKET_ERROR
;
7596 sys_listen (int s
, int backlog
)
7598 if (winsock_lib
== NULL
)
7601 return SOCKET_ERROR
;
7605 if (fd_info
[s
].flags
& FILE_SOCKET
)
7607 int rc
= pfn_listen (SOCK_HANDLE (s
), backlog
);
7608 if (rc
== SOCKET_ERROR
)
7611 fd_info
[s
].flags
|= FILE_LISTEN
;
7615 return SOCKET_ERROR
;
7619 sys_getsockname (int s
, struct sockaddr
* name
, int * namelen
)
7621 if (winsock_lib
== NULL
)
7624 return SOCKET_ERROR
;
7628 if (fd_info
[s
].flags
& FILE_SOCKET
)
7630 int rc
= pfn_getsockname (SOCK_HANDLE (s
), name
, namelen
);
7631 if (rc
== SOCKET_ERROR
)
7636 return SOCKET_ERROR
;
7640 sys_accept (int s
, struct sockaddr
* addr
, int * addrlen
)
7642 if (winsock_lib
== NULL
)
7649 if (fd_info
[s
].flags
& FILE_LISTEN
)
7651 SOCKET t
= pfn_accept (SOCK_HANDLE (s
), addr
, addrlen
);
7653 if (t
== INVALID_SOCKET
)
7656 fd
= socket_to_fd (t
);
7660 fd_info
[s
].cp
->status
= STATUS_READ_ACKNOWLEDGED
;
7661 ResetEvent (fd_info
[s
].cp
->char_avail
);
7670 sys_recvfrom (int s
, char * buf
, int len
, int flags
,
7671 struct sockaddr
* from
, int * fromlen
)
7673 if (winsock_lib
== NULL
)
7676 return SOCKET_ERROR
;
7680 if (fd_info
[s
].flags
& FILE_SOCKET
)
7682 int rc
= pfn_recvfrom (SOCK_HANDLE (s
), buf
, len
, flags
, from
, fromlen
);
7683 if (rc
== SOCKET_ERROR
)
7688 return SOCKET_ERROR
;
7692 sys_sendto (int s
, const char * buf
, int len
, int flags
,
7693 const struct sockaddr
* to
, int tolen
)
7695 if (winsock_lib
== NULL
)
7698 return SOCKET_ERROR
;
7702 if (fd_info
[s
].flags
& FILE_SOCKET
)
7704 int rc
= pfn_sendto (SOCK_HANDLE (s
), buf
, len
, flags
, to
, tolen
);
7705 if (rc
== SOCKET_ERROR
)
7710 return SOCKET_ERROR
;
7713 /* Windows does not have an fcntl function. Provide an implementation
7714 good enough for Emacs. */
7716 fcntl (int s
, int cmd
, int options
)
7718 /* In the w32 Emacs port, fcntl (fd, F_DUPFD_CLOEXEC, fd1) is always
7719 invoked in a context where fd1 is closed and all descriptors less
7720 than fd1 are open, so sys_dup is an adequate implementation. */
7721 if (cmd
== F_DUPFD_CLOEXEC
)
7725 if (fd_info
[s
].flags
& FILE_SOCKET
)
7727 if (winsock_lib
== NULL
)
7733 if (cmd
== F_SETFL
&& options
== O_NONBLOCK
)
7735 unsigned long nblock
= 1;
7736 int rc
= pfn_ioctlsocket (SOCK_HANDLE (s
), FIONBIO
, &nblock
);
7737 if (rc
== SOCKET_ERROR
)
7739 /* Keep track of the fact that we set this to non-blocking. */
7740 fd_info
[s
].flags
|= FILE_NDELAY
;
7746 return SOCKET_ERROR
;
7749 else if ((fd_info
[s
].flags
& (FILE_PIPE
| FILE_WRITE
))
7750 == (FILE_PIPE
| FILE_WRITE
))
7752 /* Force our writes to pipes be non-blocking. */
7753 if (cmd
== F_SETFL
&& options
== O_NONBLOCK
)
7755 HANDLE h
= (HANDLE
)_get_osfhandle (s
);
7756 DWORD pipe_mode
= PIPE_NOWAIT
;
7758 if (!SetNamedPipeHandleState (h
, &pipe_mode
, NULL
, NULL
))
7760 DebPrint (("SetNamedPipeHandleState: %lu\n", GetLastError ()));
7761 return SOCKET_ERROR
;
7763 fd_info
[s
].flags
|= FILE_NDELAY
;
7769 return SOCKET_ERROR
;
7773 return SOCKET_ERROR
;
7777 /* Shadow main io functions: we need to handle pipes and sockets more
7791 if (fd
< MAXDESC
&& fd_info
[fd
].cp
)
7793 child_process
* cp
= fd_info
[fd
].cp
;
7795 fd_info
[fd
].cp
= NULL
;
7797 if (CHILD_ACTIVE (cp
))
7799 /* if last descriptor to active child_process then cleanup */
7801 for (i
= 0; i
< MAXDESC
; i
++)
7805 if (fd_info
[i
].cp
== cp
)
7810 if (fd_info
[fd
].flags
& FILE_SOCKET
)
7812 if (winsock_lib
== NULL
) emacs_abort ();
7814 pfn_shutdown (SOCK_HANDLE (fd
), 2);
7815 rc
= pfn_closesocket (SOCK_HANDLE (fd
));
7817 winsock_inuse
--; /* count open sockets */
7819 /* If the process handle is NULL, it's either a socket
7820 or serial connection, or a subprocess that was
7821 already reaped by reap_subprocess, but whose
7822 resources were not yet freed, because its output was
7823 not fully read yet by the time it was reaped. (This
7824 usually happens with async subprocesses whose output
7825 is being read by Emacs.) Otherwise, this process was
7826 not reaped yet, so we set its FD to a negative value
7827 to make sure sys_select will eventually get to
7828 calling the SIGCHLD handler for it, which will then
7829 invoke waitpid and reap_subprocess. */
7830 if (cp
->procinfo
.hProcess
== NULL
)
7838 if (fd
>= 0 && fd
< MAXDESC
)
7839 fd_info
[fd
].flags
= 0;
7841 /* Note that sockets do not need special treatment here (at least on
7842 NT and Windows 95 using the standard tcp/ip stacks) - it appears that
7843 closesocket is equivalent to CloseHandle, which is to be expected
7844 because socket handles are fully fledged kernel handles. */
7856 if (new_fd
>= 0 && new_fd
< MAXDESC
)
7858 /* duplicate our internal info as well */
7859 fd_info
[new_fd
] = fd_info
[fd
];
7865 sys_dup2 (int src
, int dst
)
7869 if (dst
< 0 || dst
>= MAXDESC
)
7875 /* make sure we close the destination first if it's a pipe or socket */
7876 if (src
!= dst
&& fd_info
[dst
].flags
!= 0)
7879 rc
= _dup2 (src
, dst
);
7882 /* duplicate our internal info as well */
7883 fd_info
[dst
] = fd_info
[src
];
7889 pipe2 (int * phandles
, int pipe2_flags
)
7894 eassert (pipe2_flags
== (O_BINARY
| O_CLOEXEC
));
7896 /* make pipe handles non-inheritable; when we spawn a child, we
7897 replace the relevant handle with an inheritable one. Also put
7898 pipes into binary mode; we will do text mode translation ourselves
7900 rc
= _pipe (phandles
, 0, _O_NOINHERIT
| _O_BINARY
);
7904 /* Protect against overflow, since Windows can open more handles than
7905 our fd_info array has room for. */
7906 if (phandles
[0] >= MAXDESC
|| phandles
[1] >= MAXDESC
)
7908 _close (phandles
[0]);
7909 _close (phandles
[1]);
7915 flags
= FILE_PIPE
| FILE_READ
| FILE_BINARY
;
7916 fd_info
[phandles
[0]].flags
= flags
;
7918 flags
= FILE_PIPE
| FILE_WRITE
| FILE_BINARY
;
7919 fd_info
[phandles
[1]].flags
= flags
;
7926 /* Function to do blocking read of one byte, needed to implement
7927 select. It is only allowed on communication ports, sockets, or
7930 _sys_read_ahead (int fd
)
7935 if (fd
< 0 || fd
>= MAXDESC
)
7936 return STATUS_READ_ERROR
;
7938 cp
= fd_info
[fd
].cp
;
7940 if (cp
== NULL
|| cp
->fd
!= fd
|| cp
->status
!= STATUS_READ_READY
)
7941 return STATUS_READ_ERROR
;
7943 if ((fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SERIAL
| FILE_SOCKET
)) == 0
7944 || (fd_info
[fd
].flags
& FILE_READ
) == 0)
7946 DebPrint (("_sys_read_ahead: internal error: fd %d is not a pipe, serial port, or socket!\n", fd
));
7950 cp
->status
= STATUS_READ_IN_PROGRESS
;
7952 if (fd_info
[fd
].flags
& FILE_PIPE
)
7954 rc
= _read (fd
, &cp
->chr
, sizeof (char));
7956 /* Give subprocess time to buffer some more output for us before
7957 reporting that input is available; we need this because Windows 95
7958 connects DOS programs to pipes by making the pipe appear to be
7959 the normal console stdout - as a result most DOS programs will
7960 write to stdout without buffering, ie. one character at a
7961 time. Even some W32 programs do this - "dir" in a command
7962 shell on NT is very slow if we don't do this. */
7965 int wait
= w32_pipe_read_delay
;
7971 /* Yield remainder of our time slice, effectively giving a
7972 temporary priority boost to the child process. */
7976 else if (fd_info
[fd
].flags
& FILE_SERIAL
)
7978 HANDLE hnd
= fd_info
[fd
].hnd
;
7979 OVERLAPPED
*ovl
= &fd_info
[fd
].cp
->ovl_read
;
7982 /* Configure timeouts for blocking read. */
7983 if (!GetCommTimeouts (hnd
, &ct
))
7985 cp
->status
= STATUS_READ_ERROR
;
7986 return STATUS_READ_ERROR
;
7988 ct
.ReadIntervalTimeout
= 0;
7989 ct
.ReadTotalTimeoutMultiplier
= 0;
7990 ct
.ReadTotalTimeoutConstant
= 0;
7991 if (!SetCommTimeouts (hnd
, &ct
))
7993 cp
->status
= STATUS_READ_ERROR
;
7994 return STATUS_READ_ERROR
;
7997 if (!ReadFile (hnd
, &cp
->chr
, sizeof (char), (DWORD
*) &rc
, ovl
))
7999 if (GetLastError () != ERROR_IO_PENDING
)
8001 cp
->status
= STATUS_READ_ERROR
;
8002 return STATUS_READ_ERROR
;
8004 if (!GetOverlappedResult (hnd
, ovl
, (DWORD
*) &rc
, TRUE
))
8006 cp
->status
= STATUS_READ_ERROR
;
8007 return STATUS_READ_ERROR
;
8011 else if (fd_info
[fd
].flags
& FILE_SOCKET
)
8013 unsigned long nblock
= 0;
8014 /* We always want this to block, so temporarily disable NDELAY. */
8015 if (fd_info
[fd
].flags
& FILE_NDELAY
)
8016 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
8018 rc
= pfn_recv (SOCK_HANDLE (fd
), &cp
->chr
, sizeof (char), 0);
8020 if (fd_info
[fd
].flags
& FILE_NDELAY
)
8023 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
8027 if (rc
== sizeof (char))
8028 cp
->status
= STATUS_READ_SUCCEEDED
;
8030 cp
->status
= STATUS_READ_FAILED
;
8036 _sys_wait_accept (int fd
)
8042 if (fd
< 0 || fd
>= MAXDESC
)
8043 return STATUS_READ_ERROR
;
8045 cp
= fd_info
[fd
].cp
;
8047 if (cp
== NULL
|| cp
->fd
!= fd
|| cp
->status
!= STATUS_READ_READY
)
8048 return STATUS_READ_ERROR
;
8050 cp
->status
= STATUS_READ_FAILED
;
8052 hEv
= pfn_WSACreateEvent ();
8053 rc
= pfn_WSAEventSelect (SOCK_HANDLE (fd
), hEv
, FD_ACCEPT
);
8054 if (rc
!= SOCKET_ERROR
)
8057 rc
= WaitForSingleObject (hEv
, 500);
8059 } while (rc
== WAIT_TIMEOUT
8060 && cp
->status
!= STATUS_READ_ERROR
8062 pfn_WSAEventSelect (SOCK_HANDLE (fd
), NULL
, 0);
8063 if (rc
== WAIT_OBJECT_0
)
8064 cp
->status
= STATUS_READ_SUCCEEDED
;
8066 pfn_WSACloseEvent (hEv
);
8072 sys_read (int fd
, char * buffer
, unsigned int count
)
8077 char * orig_buffer
= buffer
;
8085 if (fd
< MAXDESC
&& fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
| FILE_SERIAL
))
8087 child_process
*cp
= fd_info
[fd
].cp
;
8089 if ((fd_info
[fd
].flags
& FILE_READ
) == 0)
8097 /* re-read CR carried over from last read */
8098 if (fd_info
[fd
].flags
& FILE_LAST_CR
)
8100 if (fd_info
[fd
].flags
& FILE_BINARY
) emacs_abort ();
8104 fd_info
[fd
].flags
&= ~FILE_LAST_CR
;
8107 /* presence of a child_process structure means we are operating in
8108 non-blocking mode - otherwise we just call _read directly.
8109 Note that the child_process structure might be missing because
8110 reap_subprocess has been called; in this case the pipe is
8111 already broken, so calling _read on it is okay. */
8114 int current_status
= cp
->status
;
8116 switch (current_status
)
8118 case STATUS_READ_FAILED
:
8119 case STATUS_READ_ERROR
:
8120 /* report normal EOF if nothing in buffer */
8122 fd_info
[fd
].flags
|= FILE_AT_EOF
;
8125 case STATUS_READ_READY
:
8126 case STATUS_READ_IN_PROGRESS
:
8127 DebPrint (("sys_read called when read is in progress\n"));
8128 errno
= EWOULDBLOCK
;
8131 case STATUS_READ_SUCCEEDED
:
8132 /* consume read-ahead char */
8133 *buffer
++ = cp
->chr
;
8136 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
8137 ResetEvent (cp
->char_avail
);
8139 case STATUS_READ_ACKNOWLEDGED
:
8143 DebPrint (("sys_read: bad status %d\n", current_status
));
8148 if (fd_info
[fd
].flags
& FILE_PIPE
)
8150 PeekNamedPipe ((HANDLE
) _get_osfhandle (fd
), NULL
, 0, NULL
, &waiting
, NULL
);
8151 to_read
= min (waiting
, (DWORD
) count
);
8154 nchars
+= _read (fd
, buffer
, to_read
);
8156 else if (fd_info
[fd
].flags
& FILE_SERIAL
)
8158 HANDLE hnd
= fd_info
[fd
].hnd
;
8159 OVERLAPPED
*ovl
= &fd_info
[fd
].cp
->ovl_read
;
8165 /* Configure timeouts for non-blocking read. */
8166 if (!GetCommTimeouts (hnd
, &ct
))
8171 ct
.ReadIntervalTimeout
= MAXDWORD
;
8172 ct
.ReadTotalTimeoutMultiplier
= 0;
8173 ct
.ReadTotalTimeoutConstant
= 0;
8174 if (!SetCommTimeouts (hnd
, &ct
))
8180 if (!ResetEvent (ovl
->hEvent
))
8185 if (!ReadFile (hnd
, buffer
, count
, (DWORD
*) &rc
, ovl
))
8187 if (GetLastError () != ERROR_IO_PENDING
)
8192 if (!GetOverlappedResult (hnd
, ovl
, (DWORD
*) &rc
, TRUE
))
8201 else /* FILE_SOCKET */
8203 if (winsock_lib
== NULL
) emacs_abort ();
8205 /* do the equivalent of a non-blocking read */
8206 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONREAD
, &waiting
);
8207 if (waiting
== 0 && nchars
== 0)
8209 errno
= EWOULDBLOCK
;
8215 /* always use binary mode for sockets */
8216 int res
= pfn_recv (SOCK_HANDLE (fd
), buffer
, count
, 0);
8217 if (res
== SOCKET_ERROR
)
8219 DebPrint (("sys_read.recv failed with error %d on socket %ld\n",
8220 pfn_WSAGetLastError (), SOCK_HANDLE (fd
)));
8230 int nread
= _read (fd
, buffer
, count
);
8233 else if (nchars
== 0)
8238 fd_info
[fd
].flags
|= FILE_AT_EOF
;
8239 /* Perform text mode translation if required. */
8240 else if ((fd_info
[fd
].flags
& FILE_BINARY
) == 0)
8242 nchars
= crlf_to_lf (nchars
, orig_buffer
);
8243 /* If buffer contains only CR, return that. To be absolutely
8244 sure we should attempt to read the next char, but in
8245 practice a CR to be followed by LF would not appear by
8246 itself in the buffer. */
8247 if (nchars
> 1 && orig_buffer
[nchars
- 1] == 0x0d)
8249 fd_info
[fd
].flags
|= FILE_LAST_CR
;
8255 nchars
= _read (fd
, buffer
, count
);
8260 /* From w32xfns.c */
8261 extern HANDLE interrupt_handle
;
8264 sys_write (int fd
, const void * buffer
, unsigned int count
)
8275 if (fd
< MAXDESC
&& fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
| FILE_SERIAL
))
8277 if ((fd_info
[fd
].flags
& FILE_WRITE
) == 0)
8283 /* Perform text mode translation if required. */
8284 if ((fd_info
[fd
].flags
& FILE_BINARY
) == 0)
8287 const unsigned char * src
= buffer
;
8288 unsigned char * dst
;
8291 SAFE_NALLOCA (tmpbuf
, 2, count
);
8296 unsigned char *next
;
8297 /* Copy next line or remaining bytes. */
8298 next
= _memccpy (dst
, src
, '\n', nbytes
);
8301 /* Copied one line ending with '\n'. */
8302 int copied
= next
- dst
;
8305 /* Insert '\r' before '\n'. */
8312 /* Copied remaining partial line -> now finished. */
8319 if (fd
< MAXDESC
&& fd_info
[fd
].flags
& FILE_SERIAL
)
8321 HANDLE hnd
= (HANDLE
) _get_osfhandle (fd
);
8322 OVERLAPPED
*ovl
= &fd_info
[fd
].cp
->ovl_write
;
8323 HANDLE wait_hnd
[2] = { interrupt_handle
, ovl
->hEvent
};
8326 /* This is async (a.k.a. "overlapped") I/O, so the return value
8327 of FALSE from WriteFile means either an error or the output
8328 will be completed asynchronously (ERROR_IO_PENDING). */
8329 if (!WriteFile (hnd
, buffer
, count
, (DWORD
*) &nchars
, ovl
))
8331 if (GetLastError () != ERROR_IO_PENDING
)
8338 /* Wait for the write to complete, and watch C-g while
8340 if (detect_input_pending ())
8341 active
= MsgWaitForMultipleObjects (2, wait_hnd
, FALSE
,
8342 INFINITE
, QS_ALLINPUT
);
8344 active
= WaitForMultipleObjects (2, wait_hnd
, FALSE
, INFINITE
);
8348 /* User pressed C-g, cancel write, then leave.
8349 Don't bother cleaning up as we may only get stuck
8350 in buggy drivers. */
8351 PurgeComm (hnd
, PURGE_TXABORT
| PURGE_TXCLEAR
);
8353 errno
= EIO
; /* Why not EINTR? */
8356 case WAIT_OBJECT_0
+ 1:
8357 if (!GetOverlappedResult (hnd
, ovl
, (DWORD
*) &nchars
, TRUE
))
8367 else if (fd
< MAXDESC
&& fd_info
[fd
].flags
& FILE_SOCKET
)
8369 unsigned long nblock
= 0;
8370 if (winsock_lib
== NULL
) emacs_abort ();
8372 /* TODO: implement select() properly so non-blocking I/O works. */
8373 /* For now, make sure the write blocks. */
8374 if (fd_info
[fd
].flags
& FILE_NDELAY
)
8375 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
8377 nchars
= pfn_send (SOCK_HANDLE (fd
), buffer
, count
, 0);
8379 /* Set the socket back to non-blocking if it was before,
8380 for other operations that support it. */
8381 if (fd_info
[fd
].flags
& FILE_NDELAY
)
8384 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
8387 if (nchars
== SOCKET_ERROR
)
8389 DebPrint (("sys_write.send failed with error %d on socket %ld\n",
8390 pfn_WSAGetLastError (), SOCK_HANDLE (fd
)));
8396 /* Some networked filesystems don't like too large writes, so
8397 break them into smaller chunks. See the Comments section of
8398 the MSDN documentation of WriteFile for details behind the
8399 choice of the value of CHUNK below. See also the thread
8400 http://thread.gmane.org/gmane.comp.version-control.git/145294
8401 in the git mailing list. */
8402 const unsigned char *p
= buffer
;
8403 const unsigned chunk
= 30 * 1024 * 1024;
8408 unsigned this_chunk
= count
< chunk
? count
: chunk
;
8409 int n
= _write (fd
, p
, this_chunk
);
8414 /* When there's no buffer space in a pipe that is in the
8415 non-blocking mode, _write returns ENOSPC. We return
8416 EAGAIN instead, which should trigger the logic in
8417 send_process that enters waiting loop and calls
8418 wait_reading_process_output to allow process input to
8419 be accepted during the wait. Those calls to
8420 wait_reading_process_output allow sys_select to
8421 notice when process input becomes available, thus
8422 avoiding deadlock whereby each side of the pipe is
8423 blocked on write, waiting for the other party to read
8424 its end of the pipe. */
8427 && ((fd_info
[fd
].flags
& (FILE_PIPE
| FILE_NDELAY
))
8428 == (FILE_PIPE
| FILE_NDELAY
)))
8433 else if (n
< this_chunk
)
8445 /* Emulation of SIOCGIFCONF and getifaddrs, see process.c. */
8447 extern Lisp_Object
conv_sockaddr_to_lisp (struct sockaddr
*, int);
8449 /* Return information about network interface IFNAME, or about all
8450 interfaces (if IFNAME is nil). */
8452 network_interface_get_info (Lisp_Object ifname
)
8454 ULONG ainfo_len
= sizeof (IP_ADAPTER_INFO
);
8455 IP_ADAPTER_INFO
*adapter
, *ainfo
= xmalloc (ainfo_len
);
8456 DWORD retval
= get_adapters_info (ainfo
, &ainfo_len
);
8457 Lisp_Object res
= Qnil
;
8459 if (retval
== ERROR_BUFFER_OVERFLOW
)
8461 ainfo
= xrealloc (ainfo
, ainfo_len
);
8462 retval
= get_adapters_info (ainfo
, &ainfo_len
);
8465 if (retval
== ERROR_SUCCESS
)
8467 int eth_count
= 0, tr_count
= 0, fddi_count
= 0, ppp_count
= 0;
8468 int sl_count
= 0, wlan_count
= 0, lo_count
= 0, ifx_count
= 0;
8470 struct sockaddr_in sa
;
8472 /* For the below, we need some winsock functions, so make sure
8473 the winsock DLL is loaded. If we cannot successfully load
8474 it, they will have no use of the information we provide,
8476 if (!winsock_lib
&& !init_winsock (1))
8479 for (adapter
= ainfo
; adapter
; adapter
= adapter
->Next
)
8481 char namebuf
[MAX_ADAPTER_NAME_LENGTH
+ 4];
8483 /* Present Unix-compatible interface names, instead of the
8484 Windows names, which are really GUIDs not readable by
8486 static const char *ifmt
[] = {
8487 "eth%d", "tr%d", "fddi%d", "ppp%d", "sl%d", "wlan%d",
8502 switch (adapter
->Type
)
8504 case MIB_IF_TYPE_ETHERNET
:
8505 /* Windows before Vista reports wireless adapters as
8506 Ethernet. Work around by looking at the Description
8508 if (strstr (adapter
->Description
, "Wireless "))
8511 if_num
= wlan_count
++;
8515 ifmt_idx
= ETHERNET
;
8516 if_num
= eth_count
++;
8519 case MIB_IF_TYPE_TOKENRING
:
8520 ifmt_idx
= TOKENRING
;
8521 if_num
= tr_count
++;
8523 case MIB_IF_TYPE_FDDI
:
8525 if_num
= fddi_count
++;
8527 case MIB_IF_TYPE_PPP
:
8529 if_num
= ppp_count
++;
8531 case MIB_IF_TYPE_SLIP
:
8533 if_num
= sl_count
++;
8535 case IF_TYPE_IEEE80211
:
8537 if_num
= wlan_count
++;
8539 case MIB_IF_TYPE_LOOPBACK
:
8542 ifmt_idx
= LOOPBACK
;
8543 if_num
= lo_count
++;
8549 ifmt_idx
= OTHER_IF
;
8550 if_num
= ifx_count
++;
8553 if (ifmt_idx
== NONE
)
8555 sprintf (namebuf
, ifmt
[ifmt_idx
], if_num
);
8557 sa
.sin_family
= AF_INET
;
8558 ip_addr
= sys_inet_addr (adapter
->IpAddressList
.IpAddress
.String
);
8559 if (ip_addr
== INADDR_NONE
)
8561 /* Bogus address, skip this interface. */
8564 sa
.sin_addr
.s_addr
= ip_addr
;
8567 res
= Fcons (Fcons (build_string (namebuf
),
8568 conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
8569 sizeof (struct sockaddr
))),
8571 else if (strcmp (namebuf
, SSDATA (ifname
)) == 0)
8573 Lisp_Object hwaddr
= Fmake_vector (make_number (6), Qnil
);
8574 register struct Lisp_Vector
*p
= XVECTOR (hwaddr
);
8575 Lisp_Object flags
= Qnil
;
8579 /* Flags. We guess most of them by type, since the
8580 Windows flags are different and hard to get by. */
8581 flags
= Fcons (intern ("up"), flags
);
8582 if (ifmt_idx
== ETHERNET
|| ifmt_idx
== WLAN
)
8584 flags
= Fcons (intern ("broadcast"), flags
);
8585 flags
= Fcons (intern ("multicast"), flags
);
8587 flags
= Fcons (intern ("running"), flags
);
8588 if (ifmt_idx
== PPP
)
8590 flags
= Fcons (intern ("pointopoint"), flags
);
8591 flags
= Fcons (intern ("noarp"), flags
);
8593 if (adapter
->HaveWins
)
8594 flags
= Fcons (intern ("WINS"), flags
);
8595 if (adapter
->DhcpEnabled
)
8596 flags
= Fcons (intern ("dynamic"), flags
);
8598 res
= Fcons (flags
, res
);
8600 /* Hardware address and its family. */
8601 for (n
= 0; n
< adapter
->AddressLength
; n
++)
8602 p
->contents
[n
] = make_number ((int) adapter
->Address
[n
]);
8603 /* Windows does not support AF_LINK or AF_PACKET family
8604 of addresses. Use an arbitrary family number that is
8605 identical to what GNU/Linux returns. */
8606 res
= Fcons (Fcons (make_number (1), hwaddr
), res
);
8609 sa
.sin_family
= AF_INET
;
8610 net_mask
= sys_inet_addr (adapter
->IpAddressList
.IpMask
.String
);
8611 if (net_mask
!= INADDR_NONE
)
8613 sa
.sin_addr
.s_addr
= net_mask
;
8615 res
= Fcons (conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
8616 sizeof (struct sockaddr
)),
8620 res
= Fcons (Qnil
, res
);
8622 sa
.sin_family
= AF_INET
;
8623 if (ip_addr
!= INADDR_NONE
)
8625 /* Broadcast address is only reported by
8626 GetAdaptersAddresses, which is of limited
8627 availability. Generate it on our own. */
8628 u_long bcast_addr
= (ip_addr
& net_mask
) | ~net_mask
;
8630 sa
.sin_addr
.s_addr
= bcast_addr
;
8632 res
= Fcons (conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
8633 sizeof (struct sockaddr
)),
8637 sa
.sin_addr
.s_addr
= ip_addr
;
8639 res
= Fcons (conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
8640 sizeof (struct sockaddr
)),
8644 res
= Fcons (Qnil
, Fcons (Qnil
, res
));
8647 /* GetAdaptersInfo is documented to not report loopback
8648 interfaces, so we generate one out of thin air. */
8651 sa
.sin_family
= AF_INET
;
8655 sa
.sin_addr
.s_addr
= sys_inet_addr ("127.0.0.1");
8656 res
= Fcons (Fcons (build_string ("lo"),
8657 conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
8658 sizeof (struct sockaddr
))),
8661 else if (strcmp (SSDATA (ifname
), "lo") == 0)
8663 res
= Fcons (Fcons (intern ("running"),
8664 Fcons (intern ("loopback"),
8665 Fcons (intern ("up"), Qnil
))), Qnil
);
8666 /* 772 is what 3 different GNU/Linux systems report for
8667 the loopback interface. */
8668 res
= Fcons (Fcons (make_number (772),
8669 Fmake_vector (make_number (6),
8672 sa
.sin_addr
.s_addr
= sys_inet_addr ("255.0.0.0");
8673 res
= Fcons (conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
8674 sizeof (struct sockaddr
)),
8676 sa
.sin_addr
.s_addr
= sys_inet_addr ("0.0.0.0");
8677 res
= Fcons (conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
8678 sizeof (struct sockaddr
)),
8680 sa
.sin_addr
.s_addr
= sys_inet_addr ("127.0.0.1");
8681 res
= Fcons (conv_sockaddr_to_lisp ((struct sockaddr
*) &sa
,
8682 sizeof (struct sockaddr
)),
8695 network_interface_list (void)
8697 return network_interface_get_info (Qnil
);
8701 network_interface_info (Lisp_Object ifname
)
8703 CHECK_STRING (ifname
);
8704 return network_interface_get_info (ifname
);
8708 /* The Windows CRT functions are "optimized for speed", so they don't
8709 check for timezone and DST changes if they were last called less
8710 than 1 minute ago (see http://support.microsoft.com/kb/821231). So
8711 all Emacs features that repeatedly call time functions (e.g.,
8712 display-time) are in real danger of missing timezone and DST
8713 changes. Calling tzset before each localtime call fixes that. */
8715 sys_localtime (const time_t *t
)
8718 return localtime (t
);
8723 /* Try loading LIBRARY_ID from the file(s) specified in
8724 Vdynamic_library_alist. If the library is loaded successfully,
8725 return the handle of the DLL, and record the filename in the
8726 property :loaded-from of LIBRARY_ID. If the library could not be
8727 found, or when it was already loaded (because the handle is not
8728 recorded anywhere, and so is lost after use), return NULL.
8730 We could also save the handle in :loaded-from, but currently
8731 there's no use case for it. */
8733 w32_delayed_load (Lisp_Object library_id
)
8735 HMODULE dll_handle
= NULL
;
8737 CHECK_SYMBOL (library_id
);
8739 if (CONSP (Vdynamic_library_alist
)
8740 && NILP (Fassq (library_id
, Vlibrary_cache
)))
8742 Lisp_Object found
= Qnil
;
8743 Lisp_Object dlls
= Fassq (library_id
, Vdynamic_library_alist
);
8746 for (dlls
= XCDR (dlls
); CONSP (dlls
); dlls
= XCDR (dlls
))
8748 Lisp_Object dll
= XCAR (dlls
);
8749 char name
[MAX_UTF8_PATH
];
8753 dll
= ENCODE_FILE (dll
);
8754 if (w32_unicode_filenames
)
8756 wchar_t name_w
[MAX_PATH
];
8758 filename_to_utf16 (SSDATA (dll
), name_w
);
8759 dll_handle
= LoadLibraryW (name_w
);
8762 res
= GetModuleFileNameW (dll_handle
, name_w
,
8765 filename_from_utf16 (name_w
, name
);
8770 char name_a
[MAX_PATH
];
8772 filename_to_ansi (SSDATA (dll
), name_a
);
8773 dll_handle
= LoadLibraryA (name_a
);
8776 res
= GetModuleFileNameA (dll_handle
, name_a
,
8779 filename_from_ansi (name_a
, name
);
8784 ptrdiff_t len
= strlen (name
);
8787 /* Possibly truncated */
8788 ? make_specified_string (name
, -1, len
, 1)
8790 /* This prevents thread start and end notifications
8791 from being sent to the DLL, for every thread we
8792 start. We don't need those notifications because
8793 threads we create never use any of these DLLs, only
8794 the main thread uses them. This is supposed to
8795 speed up thread creation. */
8796 DisableThreadLibraryCalls (dll_handle
);
8801 Fput (library_id
, QCloaded_from
, found
);
8809 check_windows_init_file (void)
8811 /* A common indication that Emacs is not installed properly is when
8812 it cannot find the Windows installation file. If this file does
8813 not exist in the expected place, tell the user. */
8815 if (!noninteractive
&& !inhibit_window_system
8816 /* Vload_path is not yet initialized when we are loading
8818 && NILP (Vpurify_flag
))
8820 Lisp_Object init_file
;
8823 /* Implementation note: this function runs early during Emacs
8824 startup, before startup.el is run. So Vload_path is still in
8825 its initial unibyte form, but it holds UTF-8 encoded file
8826 names, since init_callproc was already called. So we do not
8827 need to ENCODE_FILE here, but we do need to convert the file
8828 names from UTF-8 to ANSI. */
8829 init_file
= build_string ("term/w32-win");
8830 fd
= openp (Vload_path
, init_file
, Fget_load_suffixes (), NULL
, Qnil
, 0);
8833 Lisp_Object load_path_print
= Fprin1_to_string (Vload_path
, Qnil
);
8834 char *init_file_name
= SDATA (init_file
);
8835 char *load_path
= SDATA (load_path_print
);
8836 char *buffer
= alloca (1024
8837 + strlen (init_file_name
)
8838 + strlen (load_path
));
8843 "The Emacs Windows initialization file \"%s.el\" "
8844 "could not be found in your Emacs installation. "
8845 "Emacs checked the following directories for this file:\n"
8847 "When Emacs cannot find this file, it usually means that it "
8848 "was not installed properly, or its distribution file was "
8849 "not unpacked properly.\nSee the README.W32 file in the "
8850 "top-level Emacs directory for more information.",
8851 init_file_name
, load_path
);
8852 needed
= pMultiByteToWideChar (CP_UTF8
, MB_ERR_INVALID_CHARS
, buffer
,
8856 wchar_t *msg_w
= alloca ((needed
+ 1) * sizeof (wchar_t));
8858 pMultiByteToWideChar (CP_UTF8
, MB_ERR_INVALID_CHARS
, buffer
, -1,
8860 needed
= pWideCharToMultiByte (CP_ACP
, 0, msg_w
, -1,
8861 NULL
, 0, NULL
, NULL
);
8864 char *msg_a
= alloca (needed
+ 1);
8866 pWideCharToMultiByte (CP_ACP
, 0, msg_w
, -1, msg_a
, needed
,
8873 "Emacs Abort Dialog",
8874 MB_OK
| MB_ICONEXCLAMATION
| MB_TASKMODAL
);
8875 /* Use the low-level system abort. */
8886 term_ntproc (int ignored
)
8892 /* shutdown the socket interface if necessary */
8899 init_ntproc (int dumping
)
8901 sigset_t initial_mask
= 0;
8903 /* Initialize the socket interface now if available and requested by
8904 the user by defining PRELOAD_WINSOCK; otherwise loading will be
8905 delayed until open-network-stream is called (w32-has-winsock can
8906 also be used to dynamically load or reload winsock).
8908 Conveniently, init_environment is called before us, so
8909 PRELOAD_WINSOCK can be set in the registry. */
8911 /* Always initialize this correctly. */
8914 if (getenv ("PRELOAD_WINSOCK") != NULL
)
8915 init_winsock (TRUE
);
8917 /* Initial preparation for subprocess support: replace our standard
8918 handles with non-inheritable versions. */
8921 HANDLE stdin_save
= INVALID_HANDLE_VALUE
;
8922 HANDLE stdout_save
= INVALID_HANDLE_VALUE
;
8923 HANDLE stderr_save
= INVALID_HANDLE_VALUE
;
8925 parent
= GetCurrentProcess ();
8927 /* ignore errors when duplicating and closing; typically the
8928 handles will be invalid when running as a gui program. */
8929 DuplicateHandle (parent
,
8930 GetStdHandle (STD_INPUT_HANDLE
),
8935 DUPLICATE_SAME_ACCESS
);
8937 DuplicateHandle (parent
,
8938 GetStdHandle (STD_OUTPUT_HANDLE
),
8943 DUPLICATE_SAME_ACCESS
);
8945 DuplicateHandle (parent
,
8946 GetStdHandle (STD_ERROR_HANDLE
),
8951 DUPLICATE_SAME_ACCESS
);
8957 if (stdin_save
!= INVALID_HANDLE_VALUE
)
8958 _open_osfhandle ((intptr_t) stdin_save
, O_TEXT
);
8960 _open ("nul", O_TEXT
| O_NOINHERIT
| O_RDONLY
);
8963 if (stdout_save
!= INVALID_HANDLE_VALUE
)
8964 _open_osfhandle ((intptr_t) stdout_save
, O_TEXT
);
8966 _open ("nul", O_TEXT
| O_NOINHERIT
| O_WRONLY
);
8969 if (stderr_save
!= INVALID_HANDLE_VALUE
)
8970 _open_osfhandle ((intptr_t) stderr_save
, O_TEXT
);
8972 _open ("nul", O_TEXT
| O_NOINHERIT
| O_WRONLY
);
8976 /* unfortunately, atexit depends on implementation of malloc */
8977 /* atexit (term_ntproc); */
8980 /* Make sure we start with all signals unblocked. */
8981 sigprocmask (SIG_SETMASK
, &initial_mask
, NULL
);
8982 signal (SIGABRT
, term_ntproc
);
8986 /* determine which drives are fixed, for GetCachedVolumeInformation */
8988 /* GetDriveType must have trailing backslash. */
8989 char drive
[] = "A:\\";
8991 /* Loop over all possible drive letters */
8992 while (*drive
<= 'Z')
8994 /* Record if this drive letter refers to a fixed drive. */
8995 fixed_drives
[DRIVE_INDEX (*drive
)] =
8996 (GetDriveType (drive
) == DRIVE_FIXED
);
9001 /* Reset the volume info cache. */
9002 volume_cache
= NULL
;
9007 shutdown_handler ensures that buffers' autosave files are
9008 up to date when the user logs off, or the system shuts down.
9011 shutdown_handler (DWORD type
)
9013 /* Ctrl-C and Ctrl-Break are already suppressed, so don't handle them. */
9014 if (type
== CTRL_CLOSE_EVENT
/* User closes console window. */
9015 || type
== CTRL_LOGOFF_EVENT
/* User logs off. */
9016 || type
== CTRL_SHUTDOWN_EVENT
) /* User shutsdown. */
9018 /* Shut down cleanly, making sure autosave files are up to date. */
9019 shut_down_emacs (0, Qnil
);
9022 /* Allow other handlers to handle this signal. */
9026 /* On Windows 9X, load UNICOWS.DLL and return its handle, or die. On
9027 NT, return a handle to GDI32.DLL. */
9029 maybe_load_unicows_dll (void)
9031 if (os_subtype
== OS_9X
)
9033 HANDLE ret
= LoadLibrary ("Unicows.dll");
9036 /* These two functions are present on Windows 9X as stubs
9037 that always fail. We need the real implementations from
9038 UNICOWS.DLL, so we must call these functions through
9039 pointers, and assign the correct addresses to these
9040 pointers at program startup (see emacs.c, which calls
9041 this function early on). */
9042 pMultiByteToWideChar
= GetProcAddress (ret
, "MultiByteToWideChar");
9043 pWideCharToMultiByte
= GetProcAddress (ret
, "WideCharToMultiByte");
9050 button
= MessageBox (NULL
,
9051 "Emacs cannot load the UNICOWS.DLL library.\n"
9052 "This library is essential for using Emacs\n"
9053 "on this system. You need to install it.\n\n"
9054 "Emacs will exit when you click OK.",
9055 "Emacs cannot load UNICOWS.DLL",
9056 MB_ICONERROR
| MB_TASKMODAL
9057 | MB_SETFOREGROUND
| MB_OK
);
9068 /* On NT family of Windows, these two functions are always
9069 linked in, so we just assign their addresses to the 2
9070 pointers; no need for the LoadLibrary dance. */
9071 pMultiByteToWideChar
= MultiByteToWideChar
;
9072 pWideCharToMultiByte
= WideCharToMultiByte
;
9073 return LoadLibrary ("Gdi32.dll");
9078 globals_of_w32 is used to initialize those global variables that
9079 must always be initialized on startup even when the global variable
9080 initialized is non zero (see the function main in emacs.c).
9083 globals_of_w32 (void)
9085 HMODULE kernel32
= GetModuleHandle ("kernel32.dll");
9087 get_process_times_fn
= (GetProcessTimes_Proc
)
9088 GetProcAddress (kernel32
, "GetProcessTimes");
9090 DEFSYM (QCloaded_from
, ":loaded-from");
9092 g_b_init_is_windows_9x
= 0;
9093 g_b_init_open_process_token
= 0;
9094 g_b_init_get_token_information
= 0;
9095 g_b_init_lookup_account_sid
= 0;
9096 g_b_init_get_sid_sub_authority
= 0;
9097 g_b_init_get_sid_sub_authority_count
= 0;
9098 g_b_init_get_security_info
= 0;
9099 g_b_init_get_file_security_w
= 0;
9100 g_b_init_get_file_security_a
= 0;
9101 g_b_init_get_security_descriptor_owner
= 0;
9102 g_b_init_get_security_descriptor_group
= 0;
9103 g_b_init_is_valid_sid
= 0;
9104 g_b_init_create_toolhelp32_snapshot
= 0;
9105 g_b_init_process32_first
= 0;
9106 g_b_init_process32_next
= 0;
9107 g_b_init_open_thread_token
= 0;
9108 g_b_init_impersonate_self
= 0;
9109 g_b_init_revert_to_self
= 0;
9110 g_b_init_get_process_memory_info
= 0;
9111 g_b_init_get_process_working_set_size
= 0;
9112 g_b_init_global_memory_status
= 0;
9113 g_b_init_global_memory_status_ex
= 0;
9114 g_b_init_equal_sid
= 0;
9115 g_b_init_copy_sid
= 0;
9116 g_b_init_get_length_sid
= 0;
9117 g_b_init_get_native_system_info
= 0;
9118 g_b_init_get_system_times
= 0;
9119 g_b_init_create_symbolic_link_w
= 0;
9120 g_b_init_create_symbolic_link_a
= 0;
9121 g_b_init_get_security_descriptor_dacl
= 0;
9122 g_b_init_convert_sd_to_sddl
= 0;
9123 g_b_init_convert_sddl_to_sd
= 0;
9124 g_b_init_is_valid_security_descriptor
= 0;
9125 g_b_init_set_file_security_w
= 0;
9126 g_b_init_set_file_security_a
= 0;
9127 g_b_init_set_named_security_info_w
= 0;
9128 g_b_init_set_named_security_info_a
= 0;
9129 g_b_init_get_adapters_info
= 0;
9130 g_b_init_compare_string_w
= 0;
9131 num_of_processors
= 0;
9132 /* The following sets a handler for shutdown notifications for
9133 console apps. This actually applies to Emacs in both console and
9134 GUI modes, since we had to fool windows into thinking emacs is a
9135 console application to get console mode to work. */
9136 SetConsoleCtrlHandler (shutdown_handler
, TRUE
);
9138 /* "None" is the default group name on standalone workstations. */
9139 strcpy (dflt_group_name
, "None");
9141 /* Reset, in case it has some value inherited from dump time. */
9142 w32_stat_get_owner_group
= 0;
9144 /* If w32_unicode_filenames is non-zero, we will be using Unicode
9145 (a.k.a. "wide") APIs to invoke functions that accept file
9147 if (is_windows_9x ())
9148 w32_unicode_filenames
= 0;
9150 w32_unicode_filenames
= 1;
9153 /* For make-serial-process */
9155 serial_open (Lisp_Object port_obj
)
9157 char *port
= SSDATA (port_obj
);
9162 hnd
= CreateFile (port
, GENERIC_READ
| GENERIC_WRITE
, 0, 0,
9163 OPEN_EXISTING
, FILE_FLAG_OVERLAPPED
, 0);
9164 if (hnd
== INVALID_HANDLE_VALUE
)
9165 error ("Could not open %s", port
);
9166 fd
= (int) _open_osfhandle ((intptr_t) hnd
, 0);
9168 error ("Could not open %s", port
);
9172 error ("Could not create child process");
9174 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
9175 fd_info
[ fd
].hnd
= hnd
;
9176 fd_info
[ fd
].flags
|=
9177 FILE_READ
| FILE_WRITE
| FILE_BINARY
| FILE_SERIAL
;
9178 if (fd_info
[ fd
].cp
!= NULL
)
9180 error ("fd_info[fd = %d] is already in use", fd
);
9182 fd_info
[ fd
].cp
= cp
;
9183 cp
->ovl_read
.hEvent
= CreateEvent (NULL
, TRUE
, FALSE
, NULL
);
9184 if (cp
->ovl_read
.hEvent
== NULL
)
9185 error ("Could not create read event");
9186 cp
->ovl_write
.hEvent
= CreateEvent (NULL
, TRUE
, FALSE
, NULL
);
9187 if (cp
->ovl_write
.hEvent
== NULL
)
9188 error ("Could not create write event");
9193 /* For serial-process-configure */
9195 serial_configure (struct Lisp_Process
*p
, Lisp_Object contact
)
9197 Lisp_Object childp2
= Qnil
;
9198 Lisp_Object tem
= Qnil
;
9202 char summary
[4] = "???"; /* This usually becomes "8N1". */
9204 if ((fd_info
[ p
->outfd
].flags
& FILE_SERIAL
) == 0)
9205 error ("Not a serial process");
9206 hnd
= fd_info
[ p
->outfd
].hnd
;
9208 childp2
= Fcopy_sequence (p
->childp
);
9210 /* Initialize timeouts for blocking read and blocking write. */
9211 if (!GetCommTimeouts (hnd
, &ct
))
9212 error ("GetCommTimeouts() failed");
9213 ct
.ReadIntervalTimeout
= 0;
9214 ct
.ReadTotalTimeoutMultiplier
= 0;
9215 ct
.ReadTotalTimeoutConstant
= 0;
9216 ct
.WriteTotalTimeoutMultiplier
= 0;
9217 ct
.WriteTotalTimeoutConstant
= 0;
9218 if (!SetCommTimeouts (hnd
, &ct
))
9219 error ("SetCommTimeouts() failed");
9220 /* Read port attributes and prepare default configuration. */
9221 memset (&dcb
, 0, sizeof (dcb
));
9222 dcb
.DCBlength
= sizeof (DCB
);
9223 if (!GetCommState (hnd
, &dcb
))
9224 error ("GetCommState() failed");
9227 dcb
.fAbortOnError
= FALSE
;
9228 /* dcb.XonLim and dcb.XoffLim are set by GetCommState() */
9233 /* Configure speed. */
9234 if (!NILP (Fplist_member (contact
, QCspeed
)))
9235 tem
= Fplist_get (contact
, QCspeed
);
9237 tem
= Fplist_get (p
->childp
, QCspeed
);
9239 dcb
.BaudRate
= XINT (tem
);
9240 childp2
= Fplist_put (childp2
, QCspeed
, tem
);
9242 /* Configure bytesize. */
9243 if (!NILP (Fplist_member (contact
, QCbytesize
)))
9244 tem
= Fplist_get (contact
, QCbytesize
);
9246 tem
= Fplist_get (p
->childp
, QCbytesize
);
9248 tem
= make_number (8);
9250 if (XINT (tem
) != 7 && XINT (tem
) != 8)
9251 error (":bytesize must be nil (8), 7, or 8");
9252 dcb
.ByteSize
= XINT (tem
);
9253 summary
[0] = XINT (tem
) + '0';
9254 childp2
= Fplist_put (childp2
, QCbytesize
, tem
);
9256 /* Configure parity. */
9257 if (!NILP (Fplist_member (contact
, QCparity
)))
9258 tem
= Fplist_get (contact
, QCparity
);
9260 tem
= Fplist_get (p
->childp
, QCparity
);
9261 if (!NILP (tem
) && !EQ (tem
, Qeven
) && !EQ (tem
, Qodd
))
9262 error (":parity must be nil (no parity), `even', or `odd'");
9263 dcb
.fParity
= FALSE
;
9264 dcb
.Parity
= NOPARITY
;
9265 dcb
.fErrorChar
= FALSE
;
9270 else if (EQ (tem
, Qeven
))
9274 dcb
.Parity
= EVENPARITY
;
9275 dcb
.fErrorChar
= TRUE
;
9277 else if (EQ (tem
, Qodd
))
9281 dcb
.Parity
= ODDPARITY
;
9282 dcb
.fErrorChar
= TRUE
;
9284 childp2
= Fplist_put (childp2
, QCparity
, tem
);
9286 /* Configure stopbits. */
9287 if (!NILP (Fplist_member (contact
, QCstopbits
)))
9288 tem
= Fplist_get (contact
, QCstopbits
);
9290 tem
= Fplist_get (p
->childp
, QCstopbits
);
9292 tem
= make_number (1);
9294 if (XINT (tem
) != 1 && XINT (tem
) != 2)
9295 error (":stopbits must be nil (1 stopbit), 1, or 2");
9296 summary
[2] = XINT (tem
) + '0';
9297 if (XINT (tem
) == 1)
9298 dcb
.StopBits
= ONESTOPBIT
;
9299 else if (XINT (tem
) == 2)
9300 dcb
.StopBits
= TWOSTOPBITS
;
9301 childp2
= Fplist_put (childp2
, QCstopbits
, tem
);
9303 /* Configure flowcontrol. */
9304 if (!NILP (Fplist_member (contact
, QCflowcontrol
)))
9305 tem
= Fplist_get (contact
, QCflowcontrol
);
9307 tem
= Fplist_get (p
->childp
, QCflowcontrol
);
9308 if (!NILP (tem
) && !EQ (tem
, Qhw
) && !EQ (tem
, Qsw
))
9309 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
9310 dcb
.fOutxCtsFlow
= FALSE
;
9311 dcb
.fOutxDsrFlow
= FALSE
;
9312 dcb
.fDtrControl
= DTR_CONTROL_DISABLE
;
9313 dcb
.fDsrSensitivity
= FALSE
;
9314 dcb
.fTXContinueOnXoff
= FALSE
;
9317 dcb
.fRtsControl
= RTS_CONTROL_DISABLE
;
9318 dcb
.XonChar
= 17; /* Control-Q */
9319 dcb
.XoffChar
= 19; /* Control-S */
9322 /* Already configured. */
9324 else if (EQ (tem
, Qhw
))
9326 dcb
.fRtsControl
= RTS_CONTROL_HANDSHAKE
;
9327 dcb
.fOutxCtsFlow
= TRUE
;
9329 else if (EQ (tem
, Qsw
))
9334 childp2
= Fplist_put (childp2
, QCflowcontrol
, tem
);
9336 /* Activate configuration. */
9337 if (!SetCommState (hnd
, &dcb
))
9338 error ("SetCommState() failed");
9340 childp2
= Fplist_put (childp2
, QCsummary
, build_string (summary
));
9341 pset_childp (p
, childp2
);
9347 emacs_gnutls_pull (gnutls_transport_ptr_t p
, void* buf
, size_t sz
)
9350 struct Lisp_Process
*process
= (struct Lisp_Process
*)p
;
9351 int fd
= process
->infd
;
9353 n
= sys_read (fd
, (char*)buf
, sz
);
9360 /* Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
9361 if (err
== EWOULDBLOCK
)
9364 emacs_gnutls_transport_set_errno (process
->gnutls_state
, err
);
9370 emacs_gnutls_push (gnutls_transport_ptr_t p
, const void* buf
, size_t sz
)
9372 struct Lisp_Process
*process
= (struct Lisp_Process
*)p
;
9373 int fd
= process
->outfd
;
9374 ssize_t n
= sys_write (fd
, buf
, sz
);
9376 /* 0 or more bytes written means everything went fine. */
9380 /* Negative bytes written means we got an error in errno.
9381 Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
9382 emacs_gnutls_transport_set_errno (process
->gnutls_state
,
9383 errno
== EWOULDBLOCK
? EAGAIN
: errno
);
9387 #endif /* HAVE_GNUTLS */