1 /* Utility and Unix shadow routines for GNU Emacs on the Microsoft Windows API.
2 Copyright (C) 1994-1995, 2000-2013 Free Software Foundation, Inc.
4 This file is part of GNU Emacs.
6 GNU Emacs is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 GNU Emacs is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 Geoff Voelker (voelker@cs.washington.edu) 7-29-94
22 #include <stddef.h> /* for offsetof */
25 #include <float.h> /* for DBL_EPSILON */
32 #include <time.h> /* must be before nt/inc/sys/time.h, for MinGW64 */
34 #include <sys/utime.h>
37 /* must include CRT headers *before* config.h */
40 #include <mbstring.h> /* for _mbspbrk, _mbslwr, _mbsrchr, ... */
42 #include <sys/socket.h>
69 #include "epaths.h" /* for SHELL */
74 /* MinGW64 (_W64) defines these in its _mingw.h. */
75 #if !defined(_ANONYMOUS_UNION) && !defined(_ANONYMOUS_STRUCT)
76 #define _ANONYMOUS_UNION
77 #define _ANONYMOUS_STRUCT
80 /* Some versions of compiler define MEMORYSTATUSEX, some don't, so we
81 use a different name to avoid compilation problems. */
82 typedef struct _MEMORY_STATUS_EX
{
85 DWORDLONG ullTotalPhys
;
86 DWORDLONG ullAvailPhys
;
87 DWORDLONG ullTotalPageFile
;
88 DWORDLONG ullAvailPageFile
;
89 DWORDLONG ullTotalVirtual
;
90 DWORDLONG ullAvailVirtual
;
91 DWORDLONG ullAvailExtendedVirtual
;
92 } MEMORY_STATUS_EX
,*LPMEMORY_STATUS_EX
;
94 /* These are here so that GDB would know about these data types. This
95 allows to attach GDB to Emacs when a fatal exception is triggered
96 and Windows pops up the "application needs to be closed" dialog.
97 At that point, _gnu_exception_handler, the top-level exception
98 handler installed by the MinGW startup code, is somewhere on the
99 call-stack of the main thread, so going to that call frame and
100 looking at the argument to _gnu_exception_handler, which is a
101 PEXCEPTION_POINTERS pointer, can reveal the exception code
102 (excptr->ExceptionRecord->ExceptionCode) and the address where the
103 exception happened (excptr->ExceptionRecord->ExceptionAddress), as
104 well as some additional information specific to the exception. */
105 PEXCEPTION_POINTERS excptr
;
106 PEXCEPTION_RECORD excprec
;
112 #include <tlhelp32.h>
117 #if _WIN32_WINNT < 0x0500
118 #if !defined (__MINGW32__) || __W32API_MAJOR_VERSION < 3 || (__W32API_MAJOR_VERSION == 3 && __W32API_MINOR_VERSION < 15)
119 /* This either is not in psapi.h or guarded by higher value of
120 _WIN32_WINNT than what we use. w32api supplied with MinGW 3.15
121 defines it in psapi.h */
122 typedef struct _PROCESS_MEMORY_COUNTERS_EX
{
124 DWORD PageFaultCount
;
125 SIZE_T PeakWorkingSetSize
;
126 SIZE_T WorkingSetSize
;
127 SIZE_T QuotaPeakPagedPoolUsage
;
128 SIZE_T QuotaPagedPoolUsage
;
129 SIZE_T QuotaPeakNonPagedPoolUsage
;
130 SIZE_T QuotaNonPagedPoolUsage
;
131 SIZE_T PagefileUsage
;
132 SIZE_T PeakPagefileUsage
;
134 } PROCESS_MEMORY_COUNTERS_EX
,*PPROCESS_MEMORY_COUNTERS_EX
;
138 #include <winioctl.h>
144 /* This is not in MinGW's sddl.h (but they are in MSVC headers), so we
145 define them by hand if not already defined. */
146 #ifndef SDDL_REVISION_1
147 #define SDDL_REVISION_1 1
148 #endif /* SDDL_REVISION_1 */
150 #if defined(_MSC_VER) || defined(_W64)
151 /* MSVC and MinGW64 don't provide the definition of
152 REPARSE_DATA_BUFFER and the associated macros, except on ntifs.h,
153 which cannot be included because it triggers conflicts with other
154 Windows API headers. So we define it here by hand. */
156 typedef struct _REPARSE_DATA_BUFFER
{
158 USHORT ReparseDataLength
;
162 USHORT SubstituteNameOffset
;
163 USHORT SubstituteNameLength
;
164 USHORT PrintNameOffset
;
165 USHORT PrintNameLength
;
168 } SymbolicLinkReparseBuffer
;
170 USHORT SubstituteNameOffset
;
171 USHORT SubstituteNameLength
;
172 USHORT PrintNameOffset
;
173 USHORT PrintNameLength
;
175 } MountPointReparseBuffer
;
178 } GenericReparseBuffer
;
180 } REPARSE_DATA_BUFFER
, *PREPARSE_DATA_BUFFER
;
182 #ifndef FILE_DEVICE_FILE_SYSTEM
183 #define FILE_DEVICE_FILE_SYSTEM 9
185 #ifndef METHOD_BUFFERED
186 #define METHOD_BUFFERED 0
188 #ifndef FILE_ANY_ACCESS
189 #define FILE_ANY_ACCESS 0x00000000
192 #define CTL_CODE(t,f,m,a) (((t)<<16)|((a)<<14)|((f)<<2)|(m))
194 /* MinGW64 defines FSCTL_GET_REPARSE_POINT on winioctl.h. */
195 #ifndef FSCTL_GET_REPARSE_POINT
196 #define FSCTL_GET_REPARSE_POINT \
197 CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 42, METHOD_BUFFERED, FILE_ANY_ACCESS)
201 /* TCP connection support. */
222 #include "w32common.h"
224 #include "w32select.h"
226 #include "dispextern.h" /* for xstrcasecmp */
227 #include "coding.h" /* for Vlocale_coding_system */
229 #include "careadlinkat.h"
230 #include "allocator.h"
232 /* For serial_configure and serial_open. */
235 typedef HRESULT (WINAPI
* ShGetFolderPath_fn
)
236 (IN HWND
, IN
int, IN HANDLE
, IN DWORD
, OUT
char *);
238 Lisp_Object QCloaded_from
;
240 void globals_of_w32 (void);
241 static DWORD
get_rid (PSID
);
242 static int is_symlink (const char *);
243 static char * chase_symlinks (const char *);
244 static int enable_privilege (LPCTSTR
, BOOL
, TOKEN_PRIVILEGES
*);
245 static int restore_privilege (TOKEN_PRIVILEGES
*);
246 static BOOL WINAPI
revert_to_self (void);
248 extern int sys_access (const char *, int);
249 extern void *e_malloc (size_t);
250 extern int sys_select (int, SELECT_TYPE
*, SELECT_TYPE
*, SELECT_TYPE
*,
251 EMACS_TIME
*, sigset_t
*);
252 extern int sys_dup (int);
257 /* Initialization states.
259 WARNING: If you add any more such variables for additional APIs,
260 you MUST add initialization for them to globals_of_w32
261 below. This is because these variables might get set
262 to non-NULL values during dumping, but the dumped Emacs
263 cannot reuse those values, because it could be run on a
264 different version of the OS, where API addresses are
266 static BOOL g_b_init_is_windows_9x
;
267 static BOOL g_b_init_open_process_token
;
268 static BOOL g_b_init_get_token_information
;
269 static BOOL g_b_init_lookup_account_sid
;
270 static BOOL g_b_init_get_sid_sub_authority
;
271 static BOOL g_b_init_get_sid_sub_authority_count
;
272 static BOOL g_b_init_get_security_info
;
273 static BOOL g_b_init_get_file_security
;
274 static BOOL g_b_init_get_security_descriptor_owner
;
275 static BOOL g_b_init_get_security_descriptor_group
;
276 static BOOL g_b_init_is_valid_sid
;
277 static BOOL g_b_init_create_toolhelp32_snapshot
;
278 static BOOL g_b_init_process32_first
;
279 static BOOL g_b_init_process32_next
;
280 static BOOL g_b_init_open_thread_token
;
281 static BOOL g_b_init_impersonate_self
;
282 static BOOL g_b_init_revert_to_self
;
283 static BOOL g_b_init_get_process_memory_info
;
284 static BOOL g_b_init_get_process_working_set_size
;
285 static BOOL g_b_init_global_memory_status
;
286 static BOOL g_b_init_global_memory_status_ex
;
287 static BOOL g_b_init_get_length_sid
;
288 static BOOL g_b_init_equal_sid
;
289 static BOOL g_b_init_copy_sid
;
290 static BOOL g_b_init_get_native_system_info
;
291 static BOOL g_b_init_get_system_times
;
292 static BOOL g_b_init_create_symbolic_link
;
293 static BOOL g_b_init_get_security_descriptor_dacl
;
294 static BOOL g_b_init_convert_sd_to_sddl
;
295 static BOOL g_b_init_convert_sddl_to_sd
;
296 static BOOL g_b_init_is_valid_security_descriptor
;
297 static BOOL g_b_init_set_file_security
;
300 BEGIN: Wrapper functions around OpenProcessToken
301 and other functions in advapi32.dll that are only
302 supported in Windows NT / 2k / XP
304 /* ** Function pointer typedefs ** */
305 typedef BOOL (WINAPI
* OpenProcessToken_Proc
) (
306 HANDLE ProcessHandle
,
308 PHANDLE TokenHandle
);
309 typedef BOOL (WINAPI
* GetTokenInformation_Proc
) (
311 TOKEN_INFORMATION_CLASS TokenInformationClass
,
312 LPVOID TokenInformation
,
313 DWORD TokenInformationLength
,
314 PDWORD ReturnLength
);
315 typedef BOOL (WINAPI
* GetProcessTimes_Proc
) (
316 HANDLE process_handle
,
317 LPFILETIME creation_time
,
318 LPFILETIME exit_time
,
319 LPFILETIME kernel_time
,
320 LPFILETIME user_time
);
322 GetProcessTimes_Proc get_process_times_fn
= NULL
;
325 const char * const LookupAccountSid_Name
= "LookupAccountSidW";
326 const char * const GetFileSecurity_Name
= "GetFileSecurityW";
327 const char * const SetFileSecurity_Name
= "SetFileSecurityW";
329 const char * const LookupAccountSid_Name
= "LookupAccountSidA";
330 const char * const GetFileSecurity_Name
= "GetFileSecurityA";
331 const char * const SetFileSecurity_Name
= "SetFileSecurityA";
333 typedef BOOL (WINAPI
* LookupAccountSid_Proc
) (
334 LPCTSTR lpSystemName
,
339 LPDWORD cbDomainName
,
340 PSID_NAME_USE peUse
);
341 typedef PDWORD (WINAPI
* GetSidSubAuthority_Proc
) (
344 typedef PUCHAR (WINAPI
* GetSidSubAuthorityCount_Proc
) (
346 typedef DWORD (WINAPI
* GetSecurityInfo_Proc
) (
348 SE_OBJECT_TYPE ObjectType
,
349 SECURITY_INFORMATION SecurityInfo
,
354 PSECURITY_DESCRIPTOR
*ppSecurityDescriptor
);
355 typedef BOOL (WINAPI
* GetFileSecurity_Proc
) (
357 SECURITY_INFORMATION RequestedInformation
,
358 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
360 LPDWORD lpnLengthNeeded
);
361 typedef BOOL (WINAPI
*SetFileSecurity_Proc
) (
363 SECURITY_INFORMATION SecurityInformation
,
364 PSECURITY_DESCRIPTOR pSecurityDescriptor
);
365 typedef BOOL (WINAPI
* GetSecurityDescriptorOwner_Proc
) (
366 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
368 LPBOOL lpbOwnerDefaulted
);
369 typedef BOOL (WINAPI
* GetSecurityDescriptorGroup_Proc
) (
370 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
372 LPBOOL lpbGroupDefaulted
);
373 typedef BOOL (WINAPI
*GetSecurityDescriptorDacl_Proc
) (
374 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
375 LPBOOL lpbDaclPresent
,
377 LPBOOL lpbDaclDefaulted
);
378 typedef BOOL (WINAPI
* IsValidSid_Proc
) (
380 typedef HANDLE (WINAPI
* CreateToolhelp32Snapshot_Proc
) (
382 DWORD th32ProcessID
);
383 typedef BOOL (WINAPI
* Process32First_Proc
) (
385 LPPROCESSENTRY32 lppe
);
386 typedef BOOL (WINAPI
* Process32Next_Proc
) (
388 LPPROCESSENTRY32 lppe
);
389 typedef BOOL (WINAPI
* OpenThreadToken_Proc
) (
393 PHANDLE TokenHandle
);
394 typedef BOOL (WINAPI
* ImpersonateSelf_Proc
) (
395 SECURITY_IMPERSONATION_LEVEL ImpersonationLevel
);
396 typedef BOOL (WINAPI
* RevertToSelf_Proc
) (void);
397 typedef BOOL (WINAPI
* GetProcessMemoryInfo_Proc
) (
399 PPROCESS_MEMORY_COUNTERS ppsmemCounters
,
401 typedef BOOL (WINAPI
* GetProcessWorkingSetSize_Proc
) (
403 PSIZE_T lpMinimumWorkingSetSize
,
404 PSIZE_T lpMaximumWorkingSetSize
);
405 typedef BOOL (WINAPI
* GlobalMemoryStatus_Proc
) (
406 LPMEMORYSTATUS lpBuffer
);
407 typedef BOOL (WINAPI
* GlobalMemoryStatusEx_Proc
) (
408 LPMEMORY_STATUS_EX lpBuffer
);
409 typedef BOOL (WINAPI
* CopySid_Proc
) (
410 DWORD nDestinationSidLength
,
411 PSID pDestinationSid
,
413 typedef BOOL (WINAPI
* EqualSid_Proc
) (
416 typedef DWORD (WINAPI
* GetLengthSid_Proc
) (
418 typedef void (WINAPI
* GetNativeSystemInfo_Proc
) (
419 LPSYSTEM_INFO lpSystemInfo
);
420 typedef BOOL (WINAPI
* GetSystemTimes_Proc
) (
421 LPFILETIME lpIdleTime
,
422 LPFILETIME lpKernelTime
,
423 LPFILETIME lpUserTime
);
424 typedef BOOLEAN (WINAPI
*CreateSymbolicLink_Proc
) (
425 LPTSTR lpSymlinkFileName
,
426 LPTSTR lpTargetFileName
,
428 typedef BOOL (WINAPI
*ConvertStringSecurityDescriptorToSecurityDescriptor_Proc
) (
429 LPCTSTR StringSecurityDescriptor
,
430 DWORD StringSDRevision
,
431 PSECURITY_DESCRIPTOR
*SecurityDescriptor
,
432 PULONG SecurityDescriptorSize
);
433 typedef BOOL (WINAPI
*ConvertSecurityDescriptorToStringSecurityDescriptor_Proc
) (
434 PSECURITY_DESCRIPTOR SecurityDescriptor
,
435 DWORD RequestedStringSDRevision
,
436 SECURITY_INFORMATION SecurityInformation
,
437 LPTSTR
*StringSecurityDescriptor
,
438 PULONG StringSecurityDescriptorLen
);
439 typedef BOOL (WINAPI
*IsValidSecurityDescriptor_Proc
) (PSECURITY_DESCRIPTOR
);
441 /* ** A utility function ** */
445 static BOOL s_b_ret
= 0;
446 OSVERSIONINFO os_ver
;
447 if (g_b_init_is_windows_9x
== 0)
449 g_b_init_is_windows_9x
= 1;
450 ZeroMemory (&os_ver
, sizeof (OSVERSIONINFO
));
451 os_ver
.dwOSVersionInfoSize
= sizeof (OSVERSIONINFO
);
452 if (GetVersionEx (&os_ver
))
454 s_b_ret
= (os_ver
.dwPlatformId
== VER_PLATFORM_WIN32_WINDOWS
);
460 static Lisp_Object
ltime (ULONGLONG
);
462 /* Get total user and system times for get-internal-run-time.
463 Returns a list of integers if the times are provided by the OS
464 (NT derivatives), otherwise it returns the result of current-time. */
466 w32_get_internal_run_time (void)
468 if (get_process_times_fn
)
470 FILETIME create
, exit
, kernel
, user
;
471 HANDLE proc
= GetCurrentProcess ();
472 if ((*get_process_times_fn
) (proc
, &create
, &exit
, &kernel
, &user
))
474 LARGE_INTEGER user_int
, kernel_int
, total
;
475 user_int
.LowPart
= user
.dwLowDateTime
;
476 user_int
.HighPart
= user
.dwHighDateTime
;
477 kernel_int
.LowPart
= kernel
.dwLowDateTime
;
478 kernel_int
.HighPart
= kernel
.dwHighDateTime
;
479 total
.QuadPart
= user_int
.QuadPart
+ kernel_int
.QuadPart
;
480 return ltime (total
.QuadPart
);
484 return Fcurrent_time ();
487 /* ** The wrapper functions ** */
490 open_process_token (HANDLE ProcessHandle
,
494 static OpenProcessToken_Proc s_pfn_Open_Process_Token
= NULL
;
495 HMODULE hm_advapi32
= NULL
;
496 if (is_windows_9x () == TRUE
)
500 if (g_b_init_open_process_token
== 0)
502 g_b_init_open_process_token
= 1;
503 hm_advapi32
= LoadLibrary ("Advapi32.dll");
504 s_pfn_Open_Process_Token
=
505 (OpenProcessToken_Proc
) GetProcAddress (hm_advapi32
, "OpenProcessToken");
507 if (s_pfn_Open_Process_Token
== NULL
)
512 s_pfn_Open_Process_Token (
520 get_token_information (HANDLE TokenHandle
,
521 TOKEN_INFORMATION_CLASS TokenInformationClass
,
522 LPVOID TokenInformation
,
523 DWORD TokenInformationLength
,
526 static GetTokenInformation_Proc s_pfn_Get_Token_Information
= NULL
;
527 HMODULE hm_advapi32
= NULL
;
528 if (is_windows_9x () == TRUE
)
532 if (g_b_init_get_token_information
== 0)
534 g_b_init_get_token_information
= 1;
535 hm_advapi32
= LoadLibrary ("Advapi32.dll");
536 s_pfn_Get_Token_Information
=
537 (GetTokenInformation_Proc
) GetProcAddress (hm_advapi32
, "GetTokenInformation");
539 if (s_pfn_Get_Token_Information
== NULL
)
544 s_pfn_Get_Token_Information (
546 TokenInformationClass
,
548 TokenInformationLength
,
554 lookup_account_sid (LPCTSTR lpSystemName
,
559 LPDWORD cbDomainName
,
562 static LookupAccountSid_Proc s_pfn_Lookup_Account_Sid
= NULL
;
563 HMODULE hm_advapi32
= NULL
;
564 if (is_windows_9x () == TRUE
)
568 if (g_b_init_lookup_account_sid
== 0)
570 g_b_init_lookup_account_sid
= 1;
571 hm_advapi32
= LoadLibrary ("Advapi32.dll");
572 s_pfn_Lookup_Account_Sid
=
573 (LookupAccountSid_Proc
) GetProcAddress (hm_advapi32
, LookupAccountSid_Name
);
575 if (s_pfn_Lookup_Account_Sid
== NULL
)
580 s_pfn_Lookup_Account_Sid (
592 get_sid_sub_authority (PSID pSid
, DWORD n
)
594 static GetSidSubAuthority_Proc s_pfn_Get_Sid_Sub_Authority
= NULL
;
595 static DWORD zero
= 0U;
596 HMODULE hm_advapi32
= NULL
;
597 if (is_windows_9x () == TRUE
)
601 if (g_b_init_get_sid_sub_authority
== 0)
603 g_b_init_get_sid_sub_authority
= 1;
604 hm_advapi32
= LoadLibrary ("Advapi32.dll");
605 s_pfn_Get_Sid_Sub_Authority
=
606 (GetSidSubAuthority_Proc
) GetProcAddress (
607 hm_advapi32
, "GetSidSubAuthority");
609 if (s_pfn_Get_Sid_Sub_Authority
== NULL
)
613 return (s_pfn_Get_Sid_Sub_Authority (pSid
, n
));
617 get_sid_sub_authority_count (PSID pSid
)
619 static GetSidSubAuthorityCount_Proc s_pfn_Get_Sid_Sub_Authority_Count
= NULL
;
620 static UCHAR zero
= 0U;
621 HMODULE hm_advapi32
= NULL
;
622 if (is_windows_9x () == TRUE
)
626 if (g_b_init_get_sid_sub_authority_count
== 0)
628 g_b_init_get_sid_sub_authority_count
= 1;
629 hm_advapi32
= LoadLibrary ("Advapi32.dll");
630 s_pfn_Get_Sid_Sub_Authority_Count
=
631 (GetSidSubAuthorityCount_Proc
) GetProcAddress (
632 hm_advapi32
, "GetSidSubAuthorityCount");
634 if (s_pfn_Get_Sid_Sub_Authority_Count
== NULL
)
638 return (s_pfn_Get_Sid_Sub_Authority_Count (pSid
));
642 get_security_info (HANDLE handle
,
643 SE_OBJECT_TYPE ObjectType
,
644 SECURITY_INFORMATION SecurityInfo
,
649 PSECURITY_DESCRIPTOR
*ppSecurityDescriptor
)
651 static GetSecurityInfo_Proc s_pfn_Get_Security_Info
= NULL
;
652 HMODULE hm_advapi32
= NULL
;
653 if (is_windows_9x () == TRUE
)
657 if (g_b_init_get_security_info
== 0)
659 g_b_init_get_security_info
= 1;
660 hm_advapi32
= LoadLibrary ("Advapi32.dll");
661 s_pfn_Get_Security_Info
=
662 (GetSecurityInfo_Proc
) GetProcAddress (
663 hm_advapi32
, "GetSecurityInfo");
665 if (s_pfn_Get_Security_Info
== NULL
)
669 return (s_pfn_Get_Security_Info (handle
, ObjectType
, SecurityInfo
,
670 ppsidOwner
, ppsidGroup
, ppDacl
, ppSacl
,
671 ppSecurityDescriptor
));
675 get_file_security (LPCTSTR lpFileName
,
676 SECURITY_INFORMATION RequestedInformation
,
677 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
679 LPDWORD lpnLengthNeeded
)
681 static GetFileSecurity_Proc s_pfn_Get_File_Security
= NULL
;
682 HMODULE hm_advapi32
= NULL
;
683 if (is_windows_9x () == TRUE
)
688 if (g_b_init_get_file_security
== 0)
690 g_b_init_get_file_security
= 1;
691 hm_advapi32
= LoadLibrary ("Advapi32.dll");
692 s_pfn_Get_File_Security
=
693 (GetFileSecurity_Proc
) GetProcAddress (
694 hm_advapi32
, GetFileSecurity_Name
);
696 if (s_pfn_Get_File_Security
== NULL
)
701 return (s_pfn_Get_File_Security (lpFileName
, RequestedInformation
,
702 pSecurityDescriptor
, nLength
,
707 set_file_security (LPCTSTR lpFileName
,
708 SECURITY_INFORMATION SecurityInformation
,
709 PSECURITY_DESCRIPTOR pSecurityDescriptor
)
711 static SetFileSecurity_Proc s_pfn_Set_File_Security
= NULL
;
712 HMODULE hm_advapi32
= NULL
;
713 if (is_windows_9x () == TRUE
)
718 if (g_b_init_set_file_security
== 0)
720 g_b_init_set_file_security
= 1;
721 hm_advapi32
= LoadLibrary ("Advapi32.dll");
722 s_pfn_Set_File_Security
=
723 (SetFileSecurity_Proc
) GetProcAddress (
724 hm_advapi32
, SetFileSecurity_Name
);
726 if (s_pfn_Set_File_Security
== NULL
)
731 return (s_pfn_Set_File_Security (lpFileName
, SecurityInformation
,
732 pSecurityDescriptor
));
736 get_security_descriptor_owner (PSECURITY_DESCRIPTOR pSecurityDescriptor
,
738 LPBOOL lpbOwnerDefaulted
)
740 static GetSecurityDescriptorOwner_Proc s_pfn_Get_Security_Descriptor_Owner
= NULL
;
741 HMODULE hm_advapi32
= NULL
;
742 if (is_windows_9x () == TRUE
)
747 if (g_b_init_get_security_descriptor_owner
== 0)
749 g_b_init_get_security_descriptor_owner
= 1;
750 hm_advapi32
= LoadLibrary ("Advapi32.dll");
751 s_pfn_Get_Security_Descriptor_Owner
=
752 (GetSecurityDescriptorOwner_Proc
) GetProcAddress (
753 hm_advapi32
, "GetSecurityDescriptorOwner");
755 if (s_pfn_Get_Security_Descriptor_Owner
== NULL
)
760 return (s_pfn_Get_Security_Descriptor_Owner (pSecurityDescriptor
, pOwner
,
765 get_security_descriptor_group (PSECURITY_DESCRIPTOR pSecurityDescriptor
,
767 LPBOOL lpbGroupDefaulted
)
769 static GetSecurityDescriptorGroup_Proc s_pfn_Get_Security_Descriptor_Group
= NULL
;
770 HMODULE hm_advapi32
= NULL
;
771 if (is_windows_9x () == TRUE
)
776 if (g_b_init_get_security_descriptor_group
== 0)
778 g_b_init_get_security_descriptor_group
= 1;
779 hm_advapi32
= LoadLibrary ("Advapi32.dll");
780 s_pfn_Get_Security_Descriptor_Group
=
781 (GetSecurityDescriptorGroup_Proc
) GetProcAddress (
782 hm_advapi32
, "GetSecurityDescriptorGroup");
784 if (s_pfn_Get_Security_Descriptor_Group
== NULL
)
789 return (s_pfn_Get_Security_Descriptor_Group (pSecurityDescriptor
, pGroup
,
794 get_security_descriptor_dacl (PSECURITY_DESCRIPTOR pSecurityDescriptor
,
795 LPBOOL lpbDaclPresent
,
797 LPBOOL lpbDaclDefaulted
)
799 static GetSecurityDescriptorDacl_Proc s_pfn_Get_Security_Descriptor_Dacl
= NULL
;
800 HMODULE hm_advapi32
= NULL
;
801 if (is_windows_9x () == TRUE
)
806 if (g_b_init_get_security_descriptor_dacl
== 0)
808 g_b_init_get_security_descriptor_dacl
= 1;
809 hm_advapi32
= LoadLibrary ("Advapi32.dll");
810 s_pfn_Get_Security_Descriptor_Dacl
=
811 (GetSecurityDescriptorDacl_Proc
) GetProcAddress (
812 hm_advapi32
, "GetSecurityDescriptorDacl");
814 if (s_pfn_Get_Security_Descriptor_Dacl
== NULL
)
819 return (s_pfn_Get_Security_Descriptor_Dacl (pSecurityDescriptor
,
820 lpbDaclPresent
, pDacl
,
825 is_valid_sid (PSID sid
)
827 static IsValidSid_Proc s_pfn_Is_Valid_Sid
= NULL
;
828 HMODULE hm_advapi32
= NULL
;
829 if (is_windows_9x () == TRUE
)
833 if (g_b_init_is_valid_sid
== 0)
835 g_b_init_is_valid_sid
= 1;
836 hm_advapi32
= LoadLibrary ("Advapi32.dll");
838 (IsValidSid_Proc
) GetProcAddress (
839 hm_advapi32
, "IsValidSid");
841 if (s_pfn_Is_Valid_Sid
== NULL
)
845 return (s_pfn_Is_Valid_Sid (sid
));
849 equal_sid (PSID sid1
, PSID sid2
)
851 static EqualSid_Proc s_pfn_Equal_Sid
= NULL
;
852 HMODULE hm_advapi32
= NULL
;
853 if (is_windows_9x () == TRUE
)
857 if (g_b_init_equal_sid
== 0)
859 g_b_init_equal_sid
= 1;
860 hm_advapi32
= LoadLibrary ("Advapi32.dll");
862 (EqualSid_Proc
) GetProcAddress (
863 hm_advapi32
, "EqualSid");
865 if (s_pfn_Equal_Sid
== NULL
)
869 return (s_pfn_Equal_Sid (sid1
, sid2
));
873 get_length_sid (PSID sid
)
875 static GetLengthSid_Proc s_pfn_Get_Length_Sid
= NULL
;
876 HMODULE hm_advapi32
= NULL
;
877 if (is_windows_9x () == TRUE
)
881 if (g_b_init_get_length_sid
== 0)
883 g_b_init_get_length_sid
= 1;
884 hm_advapi32
= LoadLibrary ("Advapi32.dll");
885 s_pfn_Get_Length_Sid
=
886 (GetLengthSid_Proc
) GetProcAddress (
887 hm_advapi32
, "GetLengthSid");
889 if (s_pfn_Get_Length_Sid
== NULL
)
893 return (s_pfn_Get_Length_Sid (sid
));
897 copy_sid (DWORD destlen
, PSID dest
, PSID src
)
899 static CopySid_Proc s_pfn_Copy_Sid
= NULL
;
900 HMODULE hm_advapi32
= NULL
;
901 if (is_windows_9x () == TRUE
)
905 if (g_b_init_copy_sid
== 0)
907 g_b_init_copy_sid
= 1;
908 hm_advapi32
= LoadLibrary ("Advapi32.dll");
910 (CopySid_Proc
) GetProcAddress (
911 hm_advapi32
, "CopySid");
913 if (s_pfn_Copy_Sid
== NULL
)
917 return (s_pfn_Copy_Sid (destlen
, dest
, src
));
921 END: Wrapper functions around OpenProcessToken
922 and other functions in advapi32.dll that are only
923 supported in Windows NT / 2k / XP
927 get_native_system_info (LPSYSTEM_INFO lpSystemInfo
)
929 static GetNativeSystemInfo_Proc s_pfn_Get_Native_System_Info
= NULL
;
930 if (is_windows_9x () != TRUE
)
932 if (g_b_init_get_native_system_info
== 0)
934 g_b_init_get_native_system_info
= 1;
935 s_pfn_Get_Native_System_Info
=
936 (GetNativeSystemInfo_Proc
)GetProcAddress (GetModuleHandle ("kernel32.dll"),
937 "GetNativeSystemInfo");
939 if (s_pfn_Get_Native_System_Info
!= NULL
)
940 s_pfn_Get_Native_System_Info (lpSystemInfo
);
943 lpSystemInfo
->dwNumberOfProcessors
= -1;
947 get_system_times (LPFILETIME lpIdleTime
,
948 LPFILETIME lpKernelTime
,
949 LPFILETIME lpUserTime
)
951 static GetSystemTimes_Proc s_pfn_Get_System_times
= NULL
;
952 if (is_windows_9x () == TRUE
)
956 if (g_b_init_get_system_times
== 0)
958 g_b_init_get_system_times
= 1;
959 s_pfn_Get_System_times
=
960 (GetSystemTimes_Proc
)GetProcAddress (GetModuleHandle ("kernel32.dll"),
963 if (s_pfn_Get_System_times
== NULL
)
965 return (s_pfn_Get_System_times (lpIdleTime
, lpKernelTime
, lpUserTime
));
968 static BOOLEAN WINAPI
969 create_symbolic_link (LPTSTR lpSymlinkFilename
,
970 LPTSTR lpTargetFileName
,
973 static CreateSymbolicLink_Proc s_pfn_Create_Symbolic_Link
= NULL
;
976 if (is_windows_9x () == TRUE
)
981 if (g_b_init_create_symbolic_link
== 0)
983 g_b_init_create_symbolic_link
= 1;
985 s_pfn_Create_Symbolic_Link
=
986 (CreateSymbolicLink_Proc
)GetProcAddress (GetModuleHandle ("kernel32.dll"),
987 "CreateSymbolicLinkW");
989 s_pfn_Create_Symbolic_Link
=
990 (CreateSymbolicLink_Proc
)GetProcAddress (GetModuleHandle ("kernel32.dll"),
991 "CreateSymbolicLinkA");
994 if (s_pfn_Create_Symbolic_Link
== NULL
)
1000 retval
= s_pfn_Create_Symbolic_Link (lpSymlinkFilename
, lpTargetFileName
,
1002 /* If we were denied creation of the symlink, try again after
1003 enabling the SeCreateSymbolicLinkPrivilege for our process. */
1006 TOKEN_PRIVILEGES priv_current
;
1008 if (enable_privilege (SE_CREATE_SYMBOLIC_LINK_NAME
, TRUE
, &priv_current
))
1010 retval
= s_pfn_Create_Symbolic_Link (lpSymlinkFilename
, lpTargetFileName
,
1012 restore_privilege (&priv_current
);
1020 is_valid_security_descriptor (PSECURITY_DESCRIPTOR pSecurityDescriptor
)
1022 static IsValidSecurityDescriptor_Proc s_pfn_Is_Valid_Security_Descriptor_Proc
= NULL
;
1024 if (is_windows_9x () == TRUE
)
1030 if (g_b_init_is_valid_security_descriptor
== 0)
1032 g_b_init_is_valid_security_descriptor
= 1;
1033 s_pfn_Is_Valid_Security_Descriptor_Proc
=
1034 (IsValidSecurityDescriptor_Proc
)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1035 "IsValidSecurityDescriptor");
1037 if (s_pfn_Is_Valid_Security_Descriptor_Proc
== NULL
)
1043 return s_pfn_Is_Valid_Security_Descriptor_Proc (pSecurityDescriptor
);
1047 convert_sd_to_sddl (PSECURITY_DESCRIPTOR SecurityDescriptor
,
1048 DWORD RequestedStringSDRevision
,
1049 SECURITY_INFORMATION SecurityInformation
,
1050 LPTSTR
*StringSecurityDescriptor
,
1051 PULONG StringSecurityDescriptorLen
)
1053 static ConvertSecurityDescriptorToStringSecurityDescriptor_Proc s_pfn_Convert_SD_To_SDDL
= NULL
;
1056 if (is_windows_9x () == TRUE
)
1062 if (g_b_init_convert_sd_to_sddl
== 0)
1064 g_b_init_convert_sd_to_sddl
= 1;
1066 s_pfn_Convert_SD_To_SDDL
=
1067 (ConvertSecurityDescriptorToStringSecurityDescriptor_Proc
)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1068 "ConvertSecurityDescriptorToStringSecurityDescriptorW");
1070 s_pfn_Convert_SD_To_SDDL
=
1071 (ConvertSecurityDescriptorToStringSecurityDescriptor_Proc
)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1072 "ConvertSecurityDescriptorToStringSecurityDescriptorA");
1075 if (s_pfn_Convert_SD_To_SDDL
== NULL
)
1081 retval
= s_pfn_Convert_SD_To_SDDL (SecurityDescriptor
,
1082 RequestedStringSDRevision
,
1083 SecurityInformation
,
1084 StringSecurityDescriptor
,
1085 StringSecurityDescriptorLen
);
1091 convert_sddl_to_sd (LPCTSTR StringSecurityDescriptor
,
1092 DWORD StringSDRevision
,
1093 PSECURITY_DESCRIPTOR
*SecurityDescriptor
,
1094 PULONG SecurityDescriptorSize
)
1096 static ConvertStringSecurityDescriptorToSecurityDescriptor_Proc s_pfn_Convert_SDDL_To_SD
= NULL
;
1099 if (is_windows_9x () == TRUE
)
1105 if (g_b_init_convert_sddl_to_sd
== 0)
1107 g_b_init_convert_sddl_to_sd
= 1;
1109 s_pfn_Convert_SDDL_To_SD
=
1110 (ConvertStringSecurityDescriptorToSecurityDescriptor_Proc
)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1111 "ConvertStringSecurityDescriptorToSecurityDescriptorW");
1113 s_pfn_Convert_SDDL_To_SD
=
1114 (ConvertStringSecurityDescriptorToSecurityDescriptor_Proc
)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1115 "ConvertStringSecurityDescriptorToSecurityDescriptorA");
1118 if (s_pfn_Convert_SDDL_To_SD
== NULL
)
1124 retval
= s_pfn_Convert_SDDL_To_SD (StringSecurityDescriptor
,
1127 SecurityDescriptorSize
);
1134 /* Return 1 if P is a valid pointer to an object of size SIZE. Return
1135 0 if P is NOT a valid pointer. Return -1 if we cannot validate P.
1137 This is called from alloc.c:valid_pointer_p. */
1139 w32_valid_pointer_p (void *p
, int size
)
1142 HANDLE h
= OpenProcess (PROCESS_VM_READ
, FALSE
, GetCurrentProcessId ());
1146 unsigned char *buf
= alloca (size
);
1147 int retval
= ReadProcessMemory (h
, p
, buf
, size
, &done
);
1156 static char startup_dir
[MAXPATHLEN
];
1158 /* Get the current working directory. */
1160 getcwd (char *dir
, int dirsize
)
1167 if (dirsize
<= strlen (startup_dir
))
1173 if (GetCurrentDirectory (MAXPATHLEN
, dir
) > 0)
1177 /* Emacs doesn't actually change directory itself, it stays in the
1178 same directory where it was started. */
1179 strcpy (dir
, startup_dir
);
1184 /* Emulate getloadavg. */
1186 struct load_sample
{
1193 /* Number of processors on this machine. */
1194 static unsigned num_of_processors
;
1196 /* We maintain 1-sec samples for the last 16 minutes in a circular buffer. */
1197 static struct load_sample samples
[16*60];
1198 static int first_idx
= -1, last_idx
= -1;
1199 static int max_idx
= sizeof (samples
) / sizeof (samples
[0]);
1204 int next_idx
= from
+ 1;
1206 if (next_idx
>= max_idx
)
1215 int prev_idx
= from
- 1;
1218 prev_idx
= max_idx
- 1;
1224 sample_system_load (ULONGLONG
*idle
, ULONGLONG
*kernel
, ULONGLONG
*user
)
1226 SYSTEM_INFO sysinfo
;
1227 FILETIME ft_idle
, ft_user
, ft_kernel
;
1229 /* Initialize the number of processors on this machine. */
1230 if (num_of_processors
<= 0)
1232 get_native_system_info (&sysinfo
);
1233 num_of_processors
= sysinfo
.dwNumberOfProcessors
;
1234 if (num_of_processors
<= 0)
1236 GetSystemInfo (&sysinfo
);
1237 num_of_processors
= sysinfo
.dwNumberOfProcessors
;
1239 if (num_of_processors
<= 0)
1240 num_of_processors
= 1;
1243 /* TODO: Take into account threads that are ready to run, by
1244 sampling the "\System\Processor Queue Length" performance
1245 counter. The code below accounts only for threads that are
1246 actually running. */
1248 if (get_system_times (&ft_idle
, &ft_kernel
, &ft_user
))
1250 ULARGE_INTEGER uidle
, ukernel
, uuser
;
1252 memcpy (&uidle
, &ft_idle
, sizeof (ft_idle
));
1253 memcpy (&ukernel
, &ft_kernel
, sizeof (ft_kernel
));
1254 memcpy (&uuser
, &ft_user
, sizeof (ft_user
));
1255 *idle
= uidle
.QuadPart
;
1256 *kernel
= ukernel
.QuadPart
;
1257 *user
= uuser
.QuadPart
;
1267 /* Produce the load average for a given time interval, using the
1268 samples in the samples[] array. WHICH can be 0, 1, or 2, meaning
1269 1-minute, 5-minute, or 15-minute average, respectively. */
1273 double retval
= -1.0;
1276 double span
= (which
== 0 ? 1.0 : (which
== 1 ? 5.0 : 15.0)) * 60;
1277 time_t now
= samples
[last_idx
].sample_time
;
1279 if (first_idx
!= last_idx
)
1281 for (idx
= buf_prev (last_idx
); ; idx
= buf_prev (idx
))
1283 tdiff
= difftime (now
, samples
[idx
].sample_time
);
1284 if (tdiff
>= span
- 2*DBL_EPSILON
*now
)
1287 samples
[last_idx
].kernel
+ samples
[last_idx
].user
1288 - (samples
[idx
].kernel
+ samples
[idx
].user
);
1289 long double idl
= samples
[last_idx
].idle
- samples
[idx
].idle
;
1291 retval
= (1.0 - idl
/ sys
) * num_of_processors
;
1294 if (idx
== first_idx
)
1303 getloadavg (double loadavg
[], int nelem
)
1306 ULONGLONG idle
, kernel
, user
;
1307 time_t now
= time (NULL
);
1309 /* Store another sample. We ignore samples that are less than 1 sec
1311 if (difftime (now
, samples
[last_idx
].sample_time
) >= 1.0 - 2*DBL_EPSILON
*now
)
1313 sample_system_load (&idle
, &kernel
, &user
);
1314 last_idx
= buf_next (last_idx
);
1315 samples
[last_idx
].sample_time
= now
;
1316 samples
[last_idx
].idle
= idle
;
1317 samples
[last_idx
].kernel
= kernel
;
1318 samples
[last_idx
].user
= user
;
1319 /* If the buffer has more that 15 min worth of samples, discard
1321 if (first_idx
== -1)
1322 first_idx
= last_idx
;
1323 while (first_idx
!= last_idx
1324 && (difftime (now
, samples
[first_idx
].sample_time
)
1325 >= 15.0*60 + 2*DBL_EPSILON
*now
))
1326 first_idx
= buf_next (first_idx
);
1329 for (elem
= 0; elem
< nelem
; elem
++)
1331 double avg
= getavg (elem
);
1335 loadavg
[elem
] = avg
;
1341 /* Emulate getpwuid, getpwnam and others. */
1343 #define PASSWD_FIELD_SIZE 256
1345 static char dflt_passwd_name
[PASSWD_FIELD_SIZE
];
1346 static char dflt_passwd_passwd
[PASSWD_FIELD_SIZE
];
1347 static char dflt_passwd_gecos
[PASSWD_FIELD_SIZE
];
1348 static char dflt_passwd_dir
[PASSWD_FIELD_SIZE
];
1349 static char dflt_passwd_shell
[PASSWD_FIELD_SIZE
];
1351 static struct passwd dflt_passwd
=
1363 static char dflt_group_name
[GNLEN
+1];
1365 static struct group dflt_group
=
1367 /* When group information is not available, we return this as the
1368 group for all files. */
1376 return dflt_passwd
.pw_uid
;
1382 /* I could imagine arguing for checking to see whether the user is
1383 in the Administrators group and returning a UID of 0 for that
1384 case, but I don't know how wise that would be in the long run. */
1391 return dflt_passwd
.pw_gid
;
1401 getpwuid (unsigned uid
)
1403 if (uid
== dflt_passwd
.pw_uid
)
1404 return &dflt_passwd
;
1409 getgrgid (gid_t gid
)
1415 getpwnam (char *name
)
1419 pw
= getpwuid (getuid ());
1423 if (xstrcasecmp (name
, pw
->pw_name
))
1430 init_user_info (void)
1432 /* Find the user's real name by opening the process token and
1433 looking up the name associated with the user-sid in that token.
1435 Use the relative portion of the identifier authority value from
1436 the user-sid as the user id value (same for group id using the
1437 primary group sid from the process token). */
1439 char uname
[UNLEN
+1], gname
[GNLEN
+1], domain
[1025];
1440 DWORD ulength
= sizeof (uname
), dlength
= sizeof (domain
), needed
;
1441 DWORD glength
= sizeof (gname
);
1442 HANDLE token
= NULL
;
1443 SID_NAME_USE user_type
;
1444 unsigned char *buf
= NULL
;
1446 TOKEN_USER user_token
;
1447 TOKEN_PRIMARY_GROUP group_token
;
1450 result
= open_process_token (GetCurrentProcess (), TOKEN_QUERY
, &token
);
1453 result
= get_token_information (token
, TokenUser
, NULL
, 0, &blen
);
1454 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
1456 buf
= xmalloc (blen
);
1457 result
= get_token_information (token
, TokenUser
,
1458 (LPVOID
)buf
, blen
, &needed
);
1461 memcpy (&user_token
, buf
, sizeof (user_token
));
1462 result
= lookup_account_sid (NULL
, user_token
.User
.Sid
,
1464 domain
, &dlength
, &user_type
);
1472 strcpy (dflt_passwd
.pw_name
, uname
);
1473 /* Determine a reasonable uid value. */
1474 if (xstrcasecmp ("administrator", uname
) == 0)
1476 dflt_passwd
.pw_uid
= 500; /* well-known Administrator uid */
1477 dflt_passwd
.pw_gid
= 513; /* well-known None gid */
1481 /* Use the last sub-authority value of the RID, the relative
1482 portion of the SID, as user/group ID. */
1483 dflt_passwd
.pw_uid
= get_rid (user_token
.User
.Sid
);
1485 /* Get group id and name. */
1486 result
= get_token_information (token
, TokenPrimaryGroup
,
1487 (LPVOID
)buf
, blen
, &needed
);
1488 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
1490 buf
= xrealloc (buf
, blen
= needed
);
1491 result
= get_token_information (token
, TokenPrimaryGroup
,
1492 (LPVOID
)buf
, blen
, &needed
);
1496 memcpy (&group_token
, buf
, sizeof (group_token
));
1497 dflt_passwd
.pw_gid
= get_rid (group_token
.PrimaryGroup
);
1498 dlength
= sizeof (domain
);
1499 /* If we can get at the real Primary Group name, use that.
1500 Otherwise, the default group name was already set to
1501 "None" in globals_of_w32. */
1502 if (lookup_account_sid (NULL
, group_token
.PrimaryGroup
,
1503 gname
, &glength
, NULL
, &dlength
,
1505 strcpy (dflt_group_name
, gname
);
1508 dflt_passwd
.pw_gid
= dflt_passwd
.pw_uid
;
1511 /* If security calls are not supported (presumably because we
1512 are running under Windows 9X), fallback to this: */
1513 else if (GetUserName (uname
, &ulength
))
1515 strcpy (dflt_passwd
.pw_name
, uname
);
1516 if (xstrcasecmp ("administrator", uname
) == 0)
1517 dflt_passwd
.pw_uid
= 0;
1519 dflt_passwd
.pw_uid
= 123;
1520 dflt_passwd
.pw_gid
= dflt_passwd
.pw_uid
;
1524 strcpy (dflt_passwd
.pw_name
, "unknown");
1525 dflt_passwd
.pw_uid
= 123;
1526 dflt_passwd
.pw_gid
= 123;
1528 dflt_group
.gr_gid
= dflt_passwd
.pw_gid
;
1530 /* Ensure HOME and SHELL are defined. */
1531 if (getenv ("HOME") == NULL
)
1533 if (getenv ("SHELL") == NULL
)
1536 /* Set dir and shell from environment variables. */
1537 strcpy (dflt_passwd
.pw_dir
, getenv ("HOME"));
1538 strcpy (dflt_passwd
.pw_shell
, getenv ("SHELL"));
1542 CloseHandle (token
);
1548 /* rand () on NT gives us 15 random bits...hack together 30 bits. */
1549 return ((rand () << 15) | rand ());
1558 /* Current codepage for encoding file names. */
1559 static int file_name_codepage
;
1561 /* Return the maximum length in bytes of a multibyte character
1562 sequence encoded in the current ANSI codepage. This is required to
1563 correctly walk the encoded file names one character at a time. */
1565 max_filename_mbslen (void)
1567 /* A simple cache to avoid calling GetCPInfo every time we need to
1568 normalize a file name. The file-name encoding is not supposed to
1569 be changed too frequently, if ever. */
1570 static Lisp_Object last_file_name_encoding
;
1571 static int last_max_mbslen
;
1572 Lisp_Object current_encoding
;
1574 current_encoding
= Vfile_name_coding_system
;
1575 if (NILP (current_encoding
))
1576 current_encoding
= Vdefault_file_name_coding_system
;
1578 if (!EQ (last_file_name_encoding
, current_encoding
))
1582 last_file_name_encoding
= current_encoding
;
1583 /* Default to the current ANSI codepage. */
1584 file_name_codepage
= w32_ansi_code_page
;
1585 if (!NILP (current_encoding
))
1587 char *cpname
= SDATA (SYMBOL_NAME (current_encoding
));
1588 char *cp
= NULL
, *end
;
1591 if (strncmp (cpname
, "cp", 2) == 0)
1593 else if (strncmp (cpname
, "windows-", 8) == 0)
1599 cpnum
= strtol (cp
, &end
, 10);
1600 if (cpnum
&& *end
== '\0' && end
- cp
>= 2)
1601 file_name_codepage
= cpnum
;
1605 if (!file_name_codepage
)
1606 file_name_codepage
= CP_ACP
; /* CP_ACP = 0, but let's not assume that */
1608 if (!GetCPInfo (file_name_codepage
, &cp_info
))
1610 file_name_codepage
= CP_ACP
;
1611 if (!GetCPInfo (file_name_codepage
, &cp_info
))
1614 last_max_mbslen
= cp_info
.MaxCharSize
;
1617 return last_max_mbslen
;
1620 /* Normalize filename by converting all path separators to
1621 the specified separator. Also conditionally convert upper
1622 case path name components to lower case. */
1625 normalize_filename (register char *fp
, char path_sep
, int multibyte
)
1629 int dbcs_p
= max_filename_mbslen () > 1;
1631 /* Multibyte file names are in the Emacs internal representation, so
1632 we can traverse them by bytes with no problems. */
1636 /* Always lower-case drive letters a-z, even if the filesystem
1637 preserves case in filenames.
1638 This is so filenames can be compared by string comparison
1639 functions that are case-sensitive. Even case-preserving filesystems
1640 do not distinguish case in drive letters. */
1642 p2
= CharNextExA (file_name_codepage
, fp
, 0);
1646 if (*p2
== ':' && *fp
>= 'A' && *fp
<= 'Z')
1652 if (multibyte
|| NILP (Vw32_downcase_file_names
))
1656 if (*fp
== '/' || *fp
== '\\')
1661 fp
= CharNextExA (file_name_codepage
, fp
, 0);
1666 sep
= path_sep
; /* convert to this path separator */
1667 elem
= fp
; /* start of current path element */
1670 if (*fp
>= 'a' && *fp
<= 'z')
1671 elem
= 0; /* don't convert this element */
1673 if (*fp
== 0 || *fp
== ':')
1675 sep
= *fp
; /* restore current separator (or 0) */
1676 *fp
= '/'; /* after conversion of this element */
1679 if (*fp
== '/' || *fp
== '\\')
1681 if (elem
&& elem
!= fp
)
1683 *fp
= 0; /* temporary end of string */
1684 _mbslwr (elem
); /* while we convert to lower case */
1686 *fp
= sep
; /* convert (or restore) path separator */
1687 elem
= fp
+ 1; /* next element starts after separator */
1695 fp
= CharNextExA (file_name_codepage
, fp
, 0);
1700 /* Destructively turn backslashes into slashes. MULTIBYTE non-zero
1701 means the file name is a multibyte string in Emacs's internal
1704 dostounix_filename (register char *p
, int multibyte
)
1706 normalize_filename (p
, '/', multibyte
);
1709 /* Destructively turn slashes into backslashes. */
1711 unixtodos_filename (register char *p
)
1713 normalize_filename (p
, '\\', 0);
1716 /* Remove all CR's that are followed by a LF.
1717 (From msdos.c...probably should figure out a way to share it,
1718 although this code isn't going to ever change.) */
1720 crlf_to_lf (register int n
, register unsigned char *buf
)
1722 unsigned char *np
= buf
;
1723 unsigned char *startp
= buf
;
1724 unsigned char *endp
= buf
+ n
;
1728 while (buf
< endp
- 1)
1732 if (*(++buf
) != 0x0a)
1743 /* Parse the root part of file name, if present. Return length and
1744 optionally store pointer to char after root. */
1746 parse_root (char * name
, char ** pPath
)
1748 char * start
= name
;
1753 /* find the root name of the volume if given */
1754 if (isalpha (name
[0]) && name
[1] == ':')
1756 /* skip past drive specifier */
1758 if (IS_DIRECTORY_SEP (name
[0]))
1761 else if (IS_DIRECTORY_SEP (name
[0]) && IS_DIRECTORY_SEP (name
[1]))
1764 int dbcs_p
= max_filename_mbslen () > 1;
1769 if (IS_DIRECTORY_SEP (*name
) && --slashes
== 0)
1772 name
= CharNextExA (file_name_codepage
, name
, 0);
1777 if (IS_DIRECTORY_SEP (name
[0]))
1784 return name
- start
;
1787 /* Get long base name for name; name is assumed to be absolute. */
1789 get_long_basename (char * name
, char * buf
, int size
)
1791 WIN32_FIND_DATA find_data
;
1795 /* must be valid filename, no wild cards or other invalid characters */
1796 if (_mbspbrk (name
, "*?|<>\""))
1799 dir_handle
= FindFirstFile (name
, &find_data
);
1800 if (dir_handle
!= INVALID_HANDLE_VALUE
)
1802 if ((len
= strlen (find_data
.cFileName
)) < size
)
1803 memcpy (buf
, find_data
.cFileName
, len
+ 1);
1806 FindClose (dir_handle
);
1811 /* Get long name for file, if possible (assumed to be absolute). */
1813 w32_get_long_filename (char * name
, char * buf
, int size
)
1818 char full
[ MAX_PATH
];
1821 len
= strlen (name
);
1822 if (len
>= MAX_PATH
)
1825 /* Use local copy for destructive modification. */
1826 memcpy (full
, name
, len
+1);
1827 unixtodos_filename (full
);
1829 /* Copy root part verbatim. */
1830 len
= parse_root (full
, &p
);
1831 memcpy (o
, full
, len
);
1836 while (p
!= NULL
&& *p
)
1839 p
= _mbschr (q
, '\\');
1841 len
= get_long_basename (full
, o
, size
);
1864 is_unc_volume (const char *filename
)
1866 const char *ptr
= filename
;
1868 if (!IS_DIRECTORY_SEP (ptr
[0]) || !IS_DIRECTORY_SEP (ptr
[1]) || !ptr
[2])
1871 if (_mbspbrk (ptr
+ 2, "*?|<>\"\\/"))
1877 /* Emulate the Posix unsetenv. */
1879 unsetenv (const char *name
)
1885 if (name
== NULL
|| *name
== '\0' || strchr (name
, '=') != NULL
)
1890 name_len
= strlen (name
);
1891 /* MS docs says an environment variable cannot be longer than 32K. */
1892 if (name_len
> 32767)
1897 /* It is safe to use 'alloca' with 32K size, since the stack is at
1898 least 2MB, and we set it to 8MB in the link command line. */
1899 var
= alloca (name_len
+ 2);
1900 strncpy (var
, name
, name_len
);
1901 var
[name_len
++] = '=';
1902 var
[name_len
] = '\0';
1903 return _putenv (var
);
1906 /* MS _putenv doesn't support removing a variable when the argument
1907 does not include the '=' character, so we fix that here. */
1909 sys_putenv (char *str
)
1911 const char *const name_end
= strchr (str
, '=');
1913 if (name_end
== NULL
)
1915 /* Remove the variable from the environment. */
1916 return unsetenv (str
);
1919 return _putenv (str
);
1922 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
1925 w32_get_resource (char *key
, LPDWORD lpdwtype
)
1928 HKEY hrootkey
= NULL
;
1931 /* Check both the current user and the local machine to see if
1932 we have any resources. */
1934 if (RegOpenKeyEx (HKEY_CURRENT_USER
, REG_ROOT
, 0, KEY_READ
, &hrootkey
) == ERROR_SUCCESS
)
1938 if (RegQueryValueEx (hrootkey
, key
, NULL
, NULL
, NULL
, &cbData
) == ERROR_SUCCESS
1939 && (lpvalue
= xmalloc (cbData
)) != NULL
1940 && RegQueryValueEx (hrootkey
, key
, NULL
, lpdwtype
, lpvalue
, &cbData
) == ERROR_SUCCESS
)
1942 RegCloseKey (hrootkey
);
1948 RegCloseKey (hrootkey
);
1951 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE
, REG_ROOT
, 0, KEY_READ
, &hrootkey
) == ERROR_SUCCESS
)
1955 if (RegQueryValueEx (hrootkey
, key
, NULL
, NULL
, NULL
, &cbData
) == ERROR_SUCCESS
1956 && (lpvalue
= xmalloc (cbData
)) != NULL
1957 && RegQueryValueEx (hrootkey
, key
, NULL
, lpdwtype
, lpvalue
, &cbData
) == ERROR_SUCCESS
)
1959 RegCloseKey (hrootkey
);
1965 RegCloseKey (hrootkey
);
1971 char *get_emacs_configuration (void);
1974 init_environment (char ** argv
)
1976 static const char * const tempdirs
[] = {
1977 "$TMPDIR", "$TEMP", "$TMP", "c:/"
1982 const int imax
= sizeof (tempdirs
) / sizeof (tempdirs
[0]);
1984 /* Make sure they have a usable $TMPDIR. Many Emacs functions use
1985 temporary files and assume "/tmp" if $TMPDIR is unset, which
1986 will break on DOS/Windows. Refuse to work if we cannot find
1987 a directory, not even "c:/", usable for that purpose. */
1988 for (i
= 0; i
< imax
; i
++)
1990 const char *tmp
= tempdirs
[i
];
1993 tmp
= getenv (tmp
+ 1);
1994 /* Note that `access' can lie to us if the directory resides on a
1995 read-only filesystem, like CD-ROM or a write-protected floppy.
1996 The only way to be really sure is to actually create a file and
1997 see if it succeeds. But I think that's too much to ask. */
1999 /* MSVCRT's _access crashes with D_OK. */
2000 if (tmp
&& faccessat (AT_FDCWD
, tmp
, D_OK
, AT_EACCESS
) == 0)
2002 char * var
= alloca (strlen (tmp
) + 8);
2003 sprintf (var
, "TMPDIR=%s", tmp
);
2004 _putenv (strdup (var
));
2011 Fcons (build_string ("no usable temporary directories found!!"),
2013 "While setting TMPDIR: ");
2015 /* Check for environment variables and use registry settings if they
2016 don't exist. Fallback on default values where applicable. */
2021 char locale_name
[32];
2022 char default_home
[MAX_PATH
];
2025 static const struct env_entry
2031 /* If the default value is NULL, we will use the value from the
2032 outside environment or the Registry, but will not push the
2033 variable into the Emacs environment if it is defined neither
2034 in the Registry nor in the outside environment. */
2036 {"PRELOAD_WINSOCK", NULL
},
2037 {"emacs_dir", "C:/emacs"},
2038 {"EMACSLOADPATH", NULL
},
2039 {"SHELL", "cmdproxy.exe"}, /* perhaps it is somewhere on PATH */
2040 {"EMACSDATA", NULL
},
2041 {"EMACSPATH", NULL
},
2048 #define N_ENV_VARS sizeof (dflt_envvars)/sizeof (dflt_envvars[0])
2050 /* We need to copy dflt_envvars[] and work on the copy because we
2051 don't want the dumped Emacs to inherit the values of
2052 environment variables we saw during dumping (which could be on
2053 a different system). The defaults above must be left intact. */
2054 struct env_entry env_vars
[N_ENV_VARS
];
2056 for (i
= 0; i
< N_ENV_VARS
; i
++)
2057 env_vars
[i
] = dflt_envvars
[i
];
2059 /* For backwards compatibility, check if a .emacs file exists in C:/
2060 If not, then we can try to default to the appdata directory under the
2061 user's profile, which is more likely to be writable. */
2062 if (!check_existing ("C:/.emacs"))
2064 HRESULT profile_result
;
2065 /* Dynamically load ShGetFolderPath, as it won't exist on versions
2066 of Windows 95 and NT4 that have not been updated to include
2068 ShGetFolderPath_fn get_folder_path
;
2069 get_folder_path
= (ShGetFolderPath_fn
)
2070 GetProcAddress (GetModuleHandle ("shell32.dll"), "SHGetFolderPathA");
2072 if (get_folder_path
!= NULL
)
2074 profile_result
= get_folder_path (NULL
, CSIDL_APPDATA
, NULL
,
2077 /* If we can't get the appdata dir, revert to old behavior. */
2078 if (profile_result
== S_OK
)
2080 env_vars
[0].def_value
= default_home
;
2086 /* Get default locale info and use it for LANG. */
2087 if (GetLocaleInfo (LOCALE_USER_DEFAULT
,
2088 LOCALE_SABBREVLANGNAME
| LOCALE_USE_CP_ACP
,
2089 locale_name
, sizeof (locale_name
)))
2091 for (i
= 0; i
< N_ENV_VARS
; i
++)
2093 if (strcmp (env_vars
[i
].name
, "LANG") == 0)
2095 env_vars
[i
].def_value
= locale_name
;
2101 #define SET_ENV_BUF_SIZE (4 * MAX_PATH) /* to cover EMACSLOADPATH */
2103 /* Treat emacs_dir specially: set it unconditionally based on our
2107 char modname
[MAX_PATH
];
2109 if (!GetModuleFileName (NULL
, modname
, MAX_PATH
))
2111 if ((p
= _mbsrchr (modname
, '\\')) == NULL
)
2115 if ((p
= _mbsrchr (modname
, '\\'))
2116 /* From bin means installed Emacs, from src means uninstalled. */
2117 && (xstrcasecmp (p
, "\\bin") == 0 || xstrcasecmp (p
, "\\src") == 0))
2119 char buf
[SET_ENV_BUF_SIZE
];
2120 int within_build_tree
= xstrcasecmp (p
, "\\src") == 0;
2123 for (p
= modname
; *p
; p
= CharNext (p
))
2124 if (*p
== '\\') *p
= '/';
2126 _snprintf (buf
, sizeof (buf
)-1, "emacs_dir=%s", modname
);
2127 _putenv (strdup (buf
));
2128 /* If we are running from the Posix-like build tree, define
2129 SHELL to point to our own cmdproxy. The loop below will
2130 then disregard PATH_EXEC and the default value. */
2131 if (within_build_tree
)
2133 _snprintf (buf
, sizeof (buf
) - 1,
2134 "SHELL=%s/nt/cmdproxy.exe", modname
);
2135 _putenv (strdup (buf
));
2138 /* Handle running emacs from the build directory: src/oo-spd/i386/ */
2140 /* FIXME: should use substring of get_emacs_configuration ().
2141 But I don't think the Windows build supports alpha, mips etc
2142 anymore, so have taken the easy option for now. */
2143 else if (p
&& (xstrcasecmp (p
, "\\i386") == 0
2144 || xstrcasecmp (p
, "\\AMD64") == 0))
2147 p
= _mbsrchr (modname
, '\\');
2151 p
= _mbsrchr (modname
, '\\');
2152 if (p
&& xstrcasecmp (p
, "\\src") == 0)
2154 char buf
[SET_ENV_BUF_SIZE
];
2157 for (p
= modname
; *p
; p
= CharNext (p
))
2158 if (*p
== '\\') *p
= '/';
2160 _snprintf (buf
, sizeof (buf
)-1, "emacs_dir=%s", modname
);
2161 _putenv (strdup (buf
));
2167 for (i
= 0; i
< N_ENV_VARS
; i
++)
2169 if (!getenv (env_vars
[i
].name
))
2172 char bufc
[SET_ENV_BUF_SIZE
];
2174 if ((lpval
= w32_get_resource (env_vars
[i
].name
, &dwType
)) == NULL
2175 /* Also ignore empty environment variables. */
2180 if (strcmp (env_vars
[i
].name
, "SHELL") == 0)
2182 /* Look for cmdproxy.exe in every directory in
2183 PATH_EXEC. FIXME: This does not find cmdproxy
2184 in nt/ when we run uninstalled. */
2185 char fname
[MAX_PATH
];
2186 const char *pstart
= PATH_EXEC
, *pend
;
2189 pend
= _mbschr (pstart
, ';');
2191 pend
= pstart
+ strlen (pstart
);
2192 /* Be defensive against series of ;;; characters. */
2195 strncpy (fname
, pstart
, pend
- pstart
);
2196 fname
[pend
- pstart
] = '/';
2197 strcpy (&fname
[pend
- pstart
+ 1], "cmdproxy.exe");
2198 ExpandEnvironmentStrings ((LPSTR
) fname
, bufc
,
2200 if (check_existing (bufc
))
2213 /* If not found in any directory, use the
2214 default as the last resort. */
2215 lpval
= env_vars
[i
].def_value
;
2216 dwType
= REG_EXPAND_SZ
;
2222 lpval
= env_vars
[i
].def_value
;
2223 dwType
= REG_EXPAND_SZ
;
2225 if (strcmp (env_vars
[i
].name
, "HOME") == 0 && !appdata
)
2226 Vdelayed_warnings_list
2227 = Fcons (listn (CONSTYPE_HEAP
, 2,
2228 intern ("initialization"),
2229 build_string ("Setting HOME to C:\\ by default is deprecated")),
2230 Vdelayed_warnings_list
);
2235 char buf1
[SET_ENV_BUF_SIZE
], buf2
[SET_ENV_BUF_SIZE
];
2237 if (dwType
== REG_EXPAND_SZ
)
2238 ExpandEnvironmentStrings ((LPSTR
) lpval
, buf1
, sizeof (buf1
));
2239 else if (dwType
== REG_SZ
)
2240 strcpy (buf1
, lpval
);
2241 if (dwType
== REG_EXPAND_SZ
|| dwType
== REG_SZ
)
2243 _snprintf (buf2
, sizeof (buf2
)-1, "%s=%s", env_vars
[i
].name
,
2245 _putenv (strdup (buf2
));
2255 /* Rebuild system configuration to reflect invoking system. */
2256 Vsystem_configuration
= build_string (EMACS_CONFIGURATION
);
2258 /* Another special case: on NT, the PATH variable is actually named
2259 "Path" although cmd.exe (perhaps NT itself) arranges for
2260 environment variable lookup and setting to be case insensitive.
2261 However, Emacs assumes a fully case sensitive environment, so we
2262 need to change "Path" to "PATH" to match the expectations of
2263 various elisp packages. We do this by the sneaky method of
2264 modifying the string in the C runtime environ entry.
2266 The same applies to COMSPEC. */
2270 for (envp
= environ
; *envp
; envp
++)
2271 if (_strnicmp (*envp
, "PATH=", 5) == 0)
2272 memcpy (*envp
, "PATH=", 5);
2273 else if (_strnicmp (*envp
, "COMSPEC=", 8) == 0)
2274 memcpy (*envp
, "COMSPEC=", 8);
2277 /* Remember the initial working directory for getcwd. */
2278 /* FIXME: Do we need to resolve possible symlinks in startup_dir?
2279 Does it matter anywhere in Emacs? */
2280 if (!GetCurrentDirectory (MAXPATHLEN
, startup_dir
))
2284 static char modname
[MAX_PATH
];
2286 if (!GetModuleFileName (NULL
, modname
, MAX_PATH
))
2291 /* Determine if there is a middle mouse button, to allow parse_button
2292 to decide whether right mouse events should be mouse-2 or
2294 w32_num_mouse_buttons
= GetSystemMetrics (SM_CMOUSEBUTTONS
);
2299 /* Called from expand-file-name when default-directory is not a string. */
2302 emacs_root_dir (void)
2304 static char root_dir
[FILENAME_MAX
];
2307 p
= getenv ("emacs_dir");
2310 strcpy (root_dir
, p
);
2311 root_dir
[parse_root (root_dir
, NULL
)] = '\0';
2312 dostounix_filename (root_dir
, 0);
2316 /* We don't have scripts to automatically determine the system configuration
2317 for Emacs before it's compiled, and we don't want to have to make the
2318 user enter it, so we define EMACS_CONFIGURATION to invoke this runtime
2322 get_emacs_configuration (void)
2324 char *arch
, *oem
, *os
;
2326 static char configuration_buffer
[32];
2328 /* Determine the processor type. */
2329 switch (get_processor_type ())
2332 #ifdef PROCESSOR_INTEL_386
2333 case PROCESSOR_INTEL_386
:
2334 case PROCESSOR_INTEL_486
:
2335 case PROCESSOR_INTEL_PENTIUM
:
2343 #ifdef PROCESSOR_AMD_X8664
2344 case PROCESSOR_AMD_X8664
:
2349 #ifdef PROCESSOR_MIPS_R2000
2350 case PROCESSOR_MIPS_R2000
:
2351 case PROCESSOR_MIPS_R3000
:
2352 case PROCESSOR_MIPS_R4000
:
2357 #ifdef PROCESSOR_ALPHA_21064
2358 case PROCESSOR_ALPHA_21064
:
2368 /* Use the OEM field to reflect the compiler/library combination. */
2370 #define COMPILER_NAME "msvc"
2373 #define COMPILER_NAME "mingw"
2375 #define COMPILER_NAME "unknown"
2378 oem
= COMPILER_NAME
;
2380 switch (osinfo_cache
.dwPlatformId
) {
2381 case VER_PLATFORM_WIN32_NT
:
2383 build_num
= osinfo_cache
.dwBuildNumber
;
2385 case VER_PLATFORM_WIN32_WINDOWS
:
2386 if (osinfo_cache
.dwMinorVersion
== 0) {
2391 build_num
= LOWORD (osinfo_cache
.dwBuildNumber
);
2393 case VER_PLATFORM_WIN32s
:
2394 /* Not supported, should not happen. */
2396 build_num
= LOWORD (osinfo_cache
.dwBuildNumber
);
2404 if (osinfo_cache
.dwPlatformId
== VER_PLATFORM_WIN32_NT
) {
2405 sprintf (configuration_buffer
, "%s-%s-%s%d.%d.%d", arch
, oem
, os
,
2406 get_w32_major_version (), get_w32_minor_version (), build_num
);
2408 sprintf (configuration_buffer
, "%s-%s-%s.%d", arch
, oem
, os
, build_num
);
2411 return configuration_buffer
;
2415 get_emacs_configuration_options (void)
2417 static char *options_buffer
;
2418 char cv
[32]; /* Enough for COMPILER_VERSION. */
2420 cv
, /* To be filled later. */
2424 #ifdef ENABLE_CHECKING
2425 " --enable-checking",
2427 /* configure.bat already sets USER_CFLAGS and USER_LDFLAGS
2428 with a starting space to save work here. */
2430 " --cflags", USER_CFLAGS
,
2433 " --ldflags", USER_LDFLAGS
,
2440 /* Work out the effective configure options for this build. */
2442 #define COMPILER_VERSION "--with-msvc (%d.%02d)", _MSC_VER / 100, _MSC_VER % 100
2445 #define COMPILER_VERSION "--with-gcc (%d.%d)", __GNUC__, __GNUC_MINOR__
2447 #define COMPILER_VERSION ""
2451 if (_snprintf (cv
, sizeof (cv
) - 1, COMPILER_VERSION
) < 0)
2452 return "Error: not enough space for compiler version";
2453 cv
[sizeof (cv
) - 1] = '\0';
2455 for (i
= 0; options
[i
]; i
++)
2456 size
+= strlen (options
[i
]);
2458 options_buffer
= xmalloc (size
+ 1);
2459 options_buffer
[0] = '\0';
2461 for (i
= 0; options
[i
]; i
++)
2462 strcat (options_buffer
, options
[i
]);
2464 return options_buffer
;
2468 #include <sys/timeb.h>
2470 /* Emulate gettimeofday (Ulrich Leodolter, 1/11/95). */
2472 gettimeofday (struct timeval
*__restrict tv
, struct timezone
*__restrict tz
)
2477 tv
->tv_sec
= tb
.time
;
2478 tv
->tv_usec
= tb
.millitm
* 1000L;
2479 /* Implementation note: _ftime sometimes doesn't update the dstflag
2480 according to the new timezone when the system timezone is
2481 changed. We could fix that by using GetSystemTime and
2482 GetTimeZoneInformation, but that doesn't seem necessary, since
2483 Emacs always calls gettimeofday with the 2nd argument NULL (see
2484 current_emacs_time). */
2487 tz
->tz_minuteswest
= tb
.timezone
; /* minutes west of Greenwich */
2488 tz
->tz_dsttime
= tb
.dstflag
; /* type of dst correction */
2493 /* Emulate fdutimens. */
2495 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2496 TIMESPEC[0] and TIMESPEC[1], respectively.
2497 FD must be either negative -- in which case it is ignored --
2498 or a file descriptor that is open on FILE.
2499 If FD is nonnegative, then FILE can be NULL, which means
2500 use just futimes instead of utimes.
2501 If TIMESPEC is null, FAIL.
2502 Return 0 on success, -1 (setting errno) on failure. */
2505 fdutimens (int fd
, char const *file
, struct timespec
const timespec
[2])
2512 if (fd
< 0 && !file
)
2517 /* _futime's prototype defines 2nd arg as having the type 'struct
2518 _utimbuf', while utime needs to accept 'struct utimbuf' for
2519 compatibility with Posix. So we need to use 2 different (but
2520 equivalent) types to avoid compiler warnings, sigh. */
2523 struct _utimbuf _ut
;
2525 _ut
.actime
= timespec
[0].tv_sec
;
2526 _ut
.modtime
= timespec
[1].tv_sec
;
2527 return _futime (fd
, &_ut
);
2533 ut
.actime
= timespec
[0].tv_sec
;
2534 ut
.modtime
= timespec
[1].tv_sec
;
2535 /* Call 'utime', which is implemented below, not the MS library
2536 function, which fails on directories. */
2537 return utime (file
, &ut
);
2542 /* ------------------------------------------------------------------------- */
2543 /* IO support and wrapper functions for the Windows API. */
2544 /* ------------------------------------------------------------------------- */
2546 /* Place a wrapper around the MSVC version of ctime. It returns NULL
2547 on network directories, so we handle that case here.
2548 (Ulrich Leodolter, 1/11/95). */
2550 sys_ctime (const time_t *t
)
2552 char *str
= (char *) ctime (t
);
2553 return (str
? str
: "Sun Jan 01 00:00:00 1970");
2556 /* Emulate sleep...we could have done this with a define, but that
2557 would necessitate including windows.h in the files that used it.
2558 This is much easier. */
2560 sys_sleep (int seconds
)
2562 Sleep (seconds
* 1000);
2565 /* Internal MSVC functions for low-level descriptor munging */
2566 extern int __cdecl
_set_osfhnd (int fd
, long h
);
2567 extern int __cdecl
_free_osfhnd (int fd
);
2569 /* parallel array of private info on file handles */
2570 filedesc fd_info
[ MAXDESC
];
2572 typedef struct volume_info_data
{
2573 struct volume_info_data
* next
;
2575 /* time when info was obtained */
2578 /* actual volume info */
2587 /* Global referenced by various functions. */
2588 static volume_info_data volume_info
;
2590 /* Vector to indicate which drives are local and fixed (for which cached
2591 data never expires). */
2592 static BOOL fixed_drives
[26];
2594 /* Consider cached volume information to be stale if older than 10s,
2595 at least for non-local drives. Info for fixed drives is never stale. */
2596 #define DRIVE_INDEX( c ) ( (c) <= 'Z' ? (c) - 'A' : (c) - 'a' )
2597 #define VOLINFO_STILL_VALID( root_dir, info ) \
2598 ( ( isalpha (root_dir[0]) && \
2599 fixed_drives[ DRIVE_INDEX (root_dir[0]) ] ) \
2600 || GetTickCount () - info->timestamp < 10000 )
2602 /* Cache support functions. */
2604 /* Simple linked list with linear search is sufficient. */
2605 static volume_info_data
*volume_cache
= NULL
;
2607 static volume_info_data
*
2608 lookup_volume_info (char * root_dir
)
2610 volume_info_data
* info
;
2612 for (info
= volume_cache
; info
; info
= info
->next
)
2613 if (xstrcasecmp (info
->root_dir
, root_dir
) == 0)
2619 add_volume_info (char * root_dir
, volume_info_data
* info
)
2621 info
->root_dir
= xstrdup (root_dir
);
2622 info
->next
= volume_cache
;
2623 volume_cache
= info
;
2627 /* Wrapper for GetVolumeInformation, which uses caching to avoid
2628 performance penalty (~2ms on 486 for local drives, 7.5ms for local
2629 cdrom drive, ~5-10ms or more for remote drives on LAN). */
2630 static volume_info_data
*
2631 GetCachedVolumeInformation (char * root_dir
)
2633 volume_info_data
* info
;
2634 char default_root
[ MAX_PATH
];
2636 /* NULL for root_dir means use root from current directory. */
2637 if (root_dir
== NULL
)
2639 if (GetCurrentDirectory (MAX_PATH
, default_root
) == 0)
2641 parse_root (default_root
, &root_dir
);
2643 root_dir
= default_root
;
2646 /* Local fixed drives can be cached permanently. Removable drives
2647 cannot be cached permanently, since the volume name and serial
2648 number (if nothing else) can change. Remote drives should be
2649 treated as if they are removable, since there is no sure way to
2650 tell whether they are or not. Also, the UNC association of drive
2651 letters mapped to remote volumes can be changed at any time (even
2652 by other processes) without notice.
2654 As a compromise, so we can benefit from caching info for remote
2655 volumes, we use a simple expiry mechanism to invalidate cache
2656 entries that are more than ten seconds old. */
2659 /* No point doing this, because WNetGetConnection is even slower than
2660 GetVolumeInformation, consistently taking ~50ms on a 486 (FWIW,
2661 GetDriveType is about the only call of this type which does not
2662 involve network access, and so is extremely quick). */
2664 /* Map drive letter to UNC if remote. */
2665 if (isalpha (root_dir
[0]) && !fixed
[DRIVE_INDEX (root_dir
[0])])
2667 char remote_name
[ 256 ];
2668 char drive
[3] = { root_dir
[0], ':' };
2670 if (WNetGetConnection (drive
, remote_name
, sizeof (remote_name
))
2672 /* do something */ ;
2676 info
= lookup_volume_info (root_dir
);
2678 if (info
== NULL
|| ! VOLINFO_STILL_VALID (root_dir
, info
))
2686 /* Info is not cached, or is stale. */
2687 if (!GetVolumeInformation (root_dir
,
2688 name
, sizeof (name
),
2692 type
, sizeof (type
)))
2695 /* Cache the volume information for future use, overwriting existing
2696 entry if present. */
2699 info
= xmalloc (sizeof (volume_info_data
));
2700 add_volume_info (root_dir
, info
);
2708 info
->name
= xstrdup (name
);
2709 info
->serialnum
= serialnum
;
2710 info
->maxcomp
= maxcomp
;
2711 info
->flags
= flags
;
2712 info
->type
= xstrdup (type
);
2713 info
->timestamp
= GetTickCount ();
2719 /* Get information on the volume where NAME is held; set path pointer to
2720 start of pathname in NAME (past UNC header\volume header if present),
2721 if pPath is non-NULL.
2723 Note: if NAME includes symlinks, the information is for the volume
2724 of the symlink, not of its target. That's because, even though
2725 GetVolumeInformation returns information about the symlink target
2726 of its argument, we only pass the root directory to
2727 GetVolumeInformation, not the full NAME. */
2729 get_volume_info (const char * name
, const char ** pPath
)
2731 char temp
[MAX_PATH
];
2732 char *rootname
= NULL
; /* default to current volume */
2733 volume_info_data
* info
;
2738 /* Find the root name of the volume if given. */
2739 if (isalpha (name
[0]) && name
[1] == ':')
2747 else if (IS_DIRECTORY_SEP (name
[0]) && IS_DIRECTORY_SEP (name
[1]))
2751 int dbcs_p
= max_filename_mbslen () > 1;
2756 if (IS_DIRECTORY_SEP (*name
) && --slashes
== 0)
2762 const char *p
= name
;
2764 name
= CharNextExA (file_name_codepage
, name
, 0);
2765 memcpy (str
, p
, name
- p
);
2778 info
= GetCachedVolumeInformation (rootname
);
2781 /* Set global referenced by other functions. */
2782 volume_info
= *info
;
2788 /* Determine if volume is FAT format (ie. only supports short 8.3
2789 names); also set path pointer to start of pathname in name, if
2790 pPath is non-NULL. */
2792 is_fat_volume (const char * name
, const char ** pPath
)
2794 if (get_volume_info (name
, pPath
))
2795 return (volume_info
.maxcomp
== 12);
2799 /* Map filename to a valid 8.3 name if necessary.
2800 The result is a pointer to a static buffer, so CAVEAT EMPTOR! */
2802 map_w32_filename (const char * name
, const char ** pPath
)
2804 static char shortname
[MAX_PATH
];
2805 char * str
= shortname
;
2808 const char * save_name
= name
;
2810 if (strlen (name
) >= MAX_PATH
)
2812 /* Return a filename which will cause callers to fail. */
2813 strcpy (shortname
, "?");
2817 if (is_fat_volume (name
, (const char **)&path
)) /* truncate to 8.3 */
2819 register int left
= 8; /* maximum number of chars in part */
2820 register int extn
= 0; /* extension added? */
2821 register int dots
= 2; /* maximum number of dots allowed */
2824 *str
++ = *name
++; /* skip past UNC header */
2826 while ((c
= *name
++))
2833 *str
++ = (c
== ':' ? ':' : '\\');
2834 extn
= 0; /* reset extension flags */
2835 dots
= 2; /* max 2 dots */
2836 left
= 8; /* max length 8 for main part */
2841 /* Convert path components of the form .xxx to _xxx,
2842 but leave . and .. as they are. This allows .emacs
2843 to be read as _emacs, for example. */
2847 IS_DIRECTORY_SEP (*name
))
2862 extn
= 1; /* we've got an extension */
2863 left
= 3; /* 3 chars in extension */
2867 /* any embedded dots after the first are converted to _ */
2872 case '#': /* don't lose these, they're important */
2874 str
[-1] = c
; /* replace last character of part */
2879 *str
++ = tolower (c
); /* map to lower case (looks nicer) */
2881 dots
= 0; /* started a path component */
2890 strcpy (shortname
, name
);
2891 unixtodos_filename (shortname
);
2895 *pPath
= shortname
+ (path
- save_name
);
2901 is_exec (const char * name
)
2903 char * p
= strrchr (name
, '.');
2906 && (xstrcasecmp (p
, ".exe") == 0 ||
2907 xstrcasecmp (p
, ".com") == 0 ||
2908 xstrcasecmp (p
, ".bat") == 0 ||
2909 xstrcasecmp (p
, ".cmd") == 0));
2912 /* Emulate the Unix directory procedures opendir, closedir,
2913 and readdir. We can't use the procedures supplied in sysdep.c,
2914 so we provide them here. */
2916 struct dirent dir_static
; /* simulated directory contents */
2917 static HANDLE dir_find_handle
= INVALID_HANDLE_VALUE
;
2918 static int dir_is_fat
;
2919 static char dir_pathname
[MAXPATHLEN
+1];
2920 static WIN32_FIND_DATA dir_find_data
;
2922 /* Support shares on a network resource as subdirectories of a read-only
2924 static HANDLE wnet_enum_handle
= INVALID_HANDLE_VALUE
;
2925 static HANDLE
open_unc_volume (const char *);
2926 static char *read_unc_volume (HANDLE
, char *, int);
2927 static void close_unc_volume (HANDLE
);
2930 opendir (const char *filename
)
2934 /* Opening is done by FindFirstFile. However, a read is inherent to
2935 this operation, so we defer the open until read time. */
2937 if (dir_find_handle
!= INVALID_HANDLE_VALUE
)
2939 if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
2942 /* Note: We don't support traversal of UNC volumes via symlinks.
2943 Doing so would mean punishing 99.99% of use cases by resolving
2944 all the possible symlinks in FILENAME, recursively. */
2945 if (is_unc_volume (filename
))
2947 wnet_enum_handle
= open_unc_volume (filename
);
2948 if (wnet_enum_handle
== INVALID_HANDLE_VALUE
)
2952 if (!(dirp
= (DIR *) malloc (sizeof (DIR))))
2959 strncpy (dir_pathname
, map_w32_filename (filename
, NULL
), MAXPATHLEN
);
2960 dir_pathname
[MAXPATHLEN
] = '\0';
2961 /* Note: We don't support symlinks to file names on FAT volumes.
2962 Doing so would mean punishing 99.99% of use cases by resolving
2963 all the possible symlinks in FILENAME, recursively. */
2964 dir_is_fat
= is_fat_volume (filename
, NULL
);
2970 closedir (DIR *dirp
)
2972 /* If we have a find-handle open, close it. */
2973 if (dir_find_handle
!= INVALID_HANDLE_VALUE
)
2975 FindClose (dir_find_handle
);
2976 dir_find_handle
= INVALID_HANDLE_VALUE
;
2978 else if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
2980 close_unc_volume (wnet_enum_handle
);
2981 wnet_enum_handle
= INVALID_HANDLE_VALUE
;
2983 xfree ((char *) dirp
);
2989 int downcase
= !NILP (Vw32_downcase_file_names
);
2991 if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
2993 if (!read_unc_volume (wnet_enum_handle
,
2994 dir_find_data
.cFileName
,
2998 /* If we aren't dir_finding, do a find-first, otherwise do a find-next. */
2999 else if (dir_find_handle
== INVALID_HANDLE_VALUE
)
3001 char filename
[MAXNAMLEN
+ 3];
3003 int dbcs_p
= max_filename_mbslen () > 1;
3005 strcpy (filename
, dir_pathname
);
3006 ln
= strlen (filename
) - 1;
3009 if (!IS_DIRECTORY_SEP (filename
[ln
]))
3010 strcat (filename
, "\\");
3014 char *end
= filename
+ ln
+ 1;
3015 char *last_char
= CharPrevExA (file_name_codepage
, filename
, end
, 0);
3017 if (!IS_DIRECTORY_SEP (*last_char
))
3018 strcat (filename
, "\\");
3020 strcat (filename
, "*");
3022 /* Note: No need to resolve symlinks in FILENAME, because
3023 FindFirst opens the directory that is the target of a
3025 dir_find_handle
= FindFirstFile (filename
, &dir_find_data
);
3027 if (dir_find_handle
== INVALID_HANDLE_VALUE
)
3032 if (!FindNextFile (dir_find_handle
, &dir_find_data
))
3036 /* Emacs never uses this value, so don't bother making it match
3037 value returned by stat(). */
3038 dir_static
.d_ino
= 1;
3040 strcpy (dir_static
.d_name
, dir_find_data
.cFileName
);
3042 /* If the file name in cFileName[] includes `?' characters, it means
3043 the original file name used characters that cannot be represented
3044 by the current ANSI codepage. To avoid total lossage, retrieve
3045 the short 8+3 alias of the long file name. */
3046 if (_mbspbrk (dir_static
.d_name
, "?"))
3048 strcpy (dir_static
.d_name
, dir_find_data
.cAlternateFileName
);
3049 downcase
= 1; /* 8+3 aliases are returned in all caps */
3051 dir_static
.d_namlen
= strlen (dir_static
.d_name
);
3052 dir_static
.d_reclen
= sizeof (struct dirent
) - MAXNAMLEN
+ 3 +
3053 dir_static
.d_namlen
- dir_static
.d_namlen
% 4;
3055 /* If the file name in cFileName[] includes `?' characters, it means
3056 the original file name used characters that cannot be represented
3057 by the current ANSI codepage. To avoid total lossage, retrieve
3058 the short 8+3 alias of the long file name. */
3059 if (_mbspbrk (dir_find_data
.cFileName
, "?"))
3061 strcpy (dir_static
.d_name
, dir_find_data
.cAlternateFileName
);
3062 /* 8+3 aliases are returned in all caps, which could break
3063 various alists that look at filenames' extensions. */
3067 strcpy (dir_static
.d_name
, dir_find_data
.cFileName
);
3068 dir_static
.d_namlen
= strlen (dir_static
.d_name
);
3070 _mbslwr (dir_static
.d_name
);
3074 int dbcs_p
= max_filename_mbslen () > 1;
3075 for (p
= dir_static
.d_name
; *p
; )
3077 if (*p
>= 'a' && *p
<= 'z')
3080 p
= CharNextExA (file_name_codepage
, p
, 0);
3085 _mbslwr (dir_static
.d_name
);
3092 open_unc_volume (const char *path
)
3098 nr
.dwScope
= RESOURCE_GLOBALNET
;
3099 nr
.dwType
= RESOURCETYPE_DISK
;
3100 nr
.dwDisplayType
= RESOURCEDISPLAYTYPE_SERVER
;
3101 nr
.dwUsage
= RESOURCEUSAGE_CONTAINER
;
3102 nr
.lpLocalName
= NULL
;
3103 nr
.lpRemoteName
= (LPSTR
)map_w32_filename (path
, NULL
);
3104 nr
.lpComment
= NULL
;
3105 nr
.lpProvider
= NULL
;
3107 result
= WNetOpenEnum (RESOURCE_GLOBALNET
, RESOURCETYPE_DISK
,
3108 RESOURCEUSAGE_CONNECTABLE
, &nr
, &henum
);
3110 if (result
== NO_ERROR
)
3113 return INVALID_HANDLE_VALUE
;
3117 read_unc_volume (HANDLE henum
, char *readbuf
, int size
)
3121 DWORD bufsize
= 512;
3124 int dbcs_p
= max_filename_mbslen () > 1;
3127 buffer
= alloca (bufsize
);
3128 result
= WNetEnumResource (henum
, &count
, buffer
, &bufsize
);
3129 if (result
!= NO_ERROR
)
3132 /* WNetEnumResource returns \\resource\share...skip forward to "share". */
3133 ptr
= ((LPNETRESOURCE
) buffer
)->lpRemoteName
;
3136 while (*ptr
&& !IS_DIRECTORY_SEP (*ptr
)) ptr
++;
3139 while (*ptr
&& !IS_DIRECTORY_SEP (*ptr
))
3140 ptr
= CharNextExA (file_name_codepage
, ptr
, 0);
3144 strncpy (readbuf
, ptr
, size
);
3149 close_unc_volume (HANDLE henum
)
3151 if (henum
!= INVALID_HANDLE_VALUE
)
3152 WNetCloseEnum (henum
);
3156 unc_volume_file_attributes (const char *path
)
3161 henum
= open_unc_volume (path
);
3162 if (henum
== INVALID_HANDLE_VALUE
)
3165 attrs
= FILE_ATTRIBUTE_READONLY
| FILE_ATTRIBUTE_DIRECTORY
;
3167 close_unc_volume (henum
);
3172 /* Ensure a network connection is authenticated. */
3174 logon_network_drive (const char *path
)
3176 NETRESOURCE resource
;
3177 char share
[MAX_PATH
];
3184 if (IS_DIRECTORY_SEP (path
[0]) && IS_DIRECTORY_SEP (path
[1]))
3185 drvtype
= DRIVE_REMOTE
;
3186 else if (path
[0] == '\0' || path
[1] != ':')
3187 drvtype
= GetDriveType (NULL
);
3194 drvtype
= GetDriveType (drive
);
3197 /* Only logon to networked drives. */
3198 if (drvtype
!= DRIVE_REMOTE
)
3202 strncpy (share
, path
, MAX_PATH
);
3203 /* Truncate to just server and share name. */
3204 dbcs_p
= max_filename_mbslen () > 1;
3205 for (p
= share
+ 2; *p
&& p
< share
+ MAX_PATH
; )
3207 if (IS_DIRECTORY_SEP (*p
) && ++n_slashes
> 3)
3213 p
= CharNextExA (file_name_codepage
, p
, 0);
3218 resource
.dwType
= RESOURCETYPE_DISK
;
3219 resource
.lpLocalName
= NULL
;
3220 resource
.lpRemoteName
= share
;
3221 resource
.lpProvider
= NULL
;
3223 WNetAddConnection2 (&resource
, NULL
, NULL
, CONNECT_INTERACTIVE
);
3226 /* Emulate faccessat(2). */
3228 faccessat (int dirfd
, const char * path
, int mode
, int flags
)
3232 if (dirfd
!= AT_FDCWD
3233 && !(IS_DIRECTORY_SEP (path
[0])
3234 || IS_DEVICE_SEP (path
[1])))
3240 /* MSVCRT implementation of 'access' doesn't recognize D_OK, and its
3241 newer versions blow up when passed D_OK. */
3242 path
= map_w32_filename (path
, NULL
);
3243 /* If the last element of PATH is a symlink, we need to resolve it
3244 to get the attributes of its target file. Note: any symlinks in
3245 PATH elements other than the last one are transparently resolved
3246 by GetFileAttributes below. */
3247 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) != 0
3248 && (flags
& AT_SYMLINK_NOFOLLOW
) == 0)
3249 path
= chase_symlinks (path
);
3251 if ((attributes
= GetFileAttributes (path
)) == -1)
3253 DWORD w32err
= GetLastError ();
3257 case ERROR_INVALID_NAME
:
3258 case ERROR_BAD_PATHNAME
:
3259 if (is_unc_volume (path
))
3261 attributes
= unc_volume_file_attributes (path
);
3262 if (attributes
== -1)
3270 case ERROR_FILE_NOT_FOUND
:
3271 case ERROR_BAD_NETPATH
:
3280 if ((mode
& X_OK
) != 0
3281 && !(is_exec (path
) || (attributes
& FILE_ATTRIBUTE_DIRECTORY
) != 0))
3286 if ((mode
& W_OK
) != 0 && (attributes
& FILE_ATTRIBUTE_READONLY
) != 0)
3291 if ((mode
& D_OK
) != 0 && (attributes
& FILE_ATTRIBUTE_DIRECTORY
) == 0)
3299 /* Shadow some MSVC runtime functions to map requests for long filenames
3300 to reasonable short names if necessary. This was originally added to
3301 permit running Emacs on NT 3.1 on a FAT partition, which doesn't support
3305 sys_chdir (const char * path
)
3307 return _chdir (map_w32_filename (path
, NULL
));
3311 sys_chmod (const char * path
, int mode
)
3313 path
= chase_symlinks (map_w32_filename (path
, NULL
));
3314 return _chmod (path
, mode
);
3318 sys_creat (const char * path
, int mode
)
3320 return _creat (map_w32_filename (path
, NULL
), mode
);
3324 sys_fopen (const char * path
, const char * mode
)
3328 const char * mode_save
= mode
;
3330 /* Force all file handles to be non-inheritable. This is necessary to
3331 ensure child processes don't unwittingly inherit handles that might
3332 prevent future file access. */
3336 else if (mode
[0] == 'w' || mode
[0] == 'a')
3337 oflag
= O_WRONLY
| O_CREAT
| O_TRUNC
;
3341 /* Only do simplistic option parsing. */
3345 oflag
&= ~(O_RDONLY
| O_WRONLY
);
3348 else if (mode
[0] == 'b')
3353 else if (mode
[0] == 't')
3360 fd
= _open (map_w32_filename (path
, NULL
), oflag
| _O_NOINHERIT
, 0644);
3364 return _fdopen (fd
, mode_save
);
3367 /* This only works on NTFS volumes, but is useful to have. */
3369 sys_link (const char * old
, const char * new)
3373 char oldname
[MAX_PATH
], newname
[MAX_PATH
];
3375 if (old
== NULL
|| new == NULL
)
3381 strcpy (oldname
, map_w32_filename (old
, NULL
));
3382 strcpy (newname
, map_w32_filename (new, NULL
));
3384 fileh
= CreateFile (oldname
, 0, 0, NULL
, OPEN_EXISTING
,
3385 FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
3386 if (fileh
!= INVALID_HANDLE_VALUE
)
3390 /* Confusingly, the "alternate" stream name field does not apply
3391 when restoring a hard link, and instead contains the actual
3392 stream data for the link (ie. the name of the link to create).
3393 The WIN32_STREAM_ID structure before the cStreamName field is
3394 the stream header, which is then immediately followed by the
3398 WIN32_STREAM_ID wid
;
3399 WCHAR wbuffer
[MAX_PATH
]; /* extra space for link name */
3402 wlen
= MultiByteToWideChar (CP_ACP
, MB_PRECOMPOSED
, newname
, -1,
3403 data
.wid
.cStreamName
, MAX_PATH
);
3406 LPVOID context
= NULL
;
3409 data
.wid
.dwStreamId
= BACKUP_LINK
;
3410 data
.wid
.dwStreamAttributes
= 0;
3411 data
.wid
.Size
.LowPart
= wlen
* sizeof (WCHAR
);
3412 data
.wid
.Size
.HighPart
= 0;
3413 data
.wid
.dwStreamNameSize
= 0;
3415 if (BackupWrite (fileh
, (LPBYTE
)&data
,
3416 offsetof (WIN32_STREAM_ID
, cStreamName
)
3417 + data
.wid
.Size
.LowPart
,
3418 &wbytes
, FALSE
, FALSE
, &context
)
3419 && BackupWrite (fileh
, NULL
, 0, &wbytes
, TRUE
, FALSE
, &context
))
3426 /* Should try mapping GetLastError to errno; for now just
3427 indicate a general error (eg. links not supported). */
3428 errno
= EINVAL
; // perhaps EMLINK?
3432 CloseHandle (fileh
);
3441 sys_mkdir (const char * path
)
3443 return _mkdir (map_w32_filename (path
, NULL
));
3447 sys_open (const char * path
, int oflag
, int mode
)
3449 const char* mpath
= map_w32_filename (path
, NULL
);
3452 /* If possible, try to open file without _O_CREAT, to be able to
3453 write to existing hidden and system files. Force all file
3454 handles to be non-inheritable. */
3455 if ((oflag
& (_O_CREAT
| _O_EXCL
)) != (_O_CREAT
| _O_EXCL
))
3456 res
= _open (mpath
, (oflag
& ~_O_CREAT
) | _O_NOINHERIT
, mode
);
3458 res
= _open (mpath
, oflag
| _O_NOINHERIT
, mode
);
3463 /* Implementation of mkostemp for MS-Windows, to avoid race conditions
3466 Standard algorithm for generating a temporary file name seems to be
3467 use pid or tid with a letter on the front (in place of the 6 X's)
3468 and cycle through the letters to find a unique name. We extend
3469 that to allow any reasonable character as the first of the 6 X's,
3470 so that the number of simultaneously used temporary files will be
3474 mkostemp (char * template, int flags
)
3478 unsigned uid
= GetCurrentThreadId ();
3479 int save_errno
= errno
;
3480 static char first_char
[] = "abcdefghijklmnopqrstuvwyz0123456789!%-_@#";
3483 if (template == NULL
)
3486 p
= template + strlen (template);
3488 /* replace up to the last 5 X's with uid in decimal */
3489 while (--p
>= template && p
[0] == 'X' && --i
>= 0)
3491 p
[0] = '0' + uid
% 10;
3495 if (i
< 0 && p
[0] == 'X')
3500 p
[0] = first_char
[i
];
3501 if ((fd
= sys_open (template,
3502 flags
| _O_CREAT
| _O_EXCL
| _O_RDWR
,
3503 S_IRUSR
| S_IWUSR
)) >= 0
3511 while (++i
< sizeof (first_char
));
3514 /* Template is badly formed or else we can't generate a unique name. */
3519 fchmod (int fd
, mode_t mode
)
3525 sys_rename_replace (const char *oldname
, const char *newname
, BOOL force
)
3528 char temp
[MAX_PATH
];
3532 /* MoveFile on Windows 95 doesn't correctly change the short file name
3533 alias in a number of circumstances (it is not easy to predict when
3534 just by looking at oldname and newname, unfortunately). In these
3535 cases, renaming through a temporary name avoids the problem.
3537 A second problem on Windows 95 is that renaming through a temp name when
3538 newname is uppercase fails (the final long name ends up in
3539 lowercase, although the short alias might be uppercase) UNLESS the
3540 long temp name is not 8.3.
3542 So, on Windows 95 we always rename through a temp name, and we make sure
3543 the temp name has a long extension to ensure correct renaming. */
3545 strcpy (temp
, map_w32_filename (oldname
, NULL
));
3547 /* volume_info is set indirectly by map_w32_filename. */
3548 oldname_dev
= volume_info
.serialnum
;
3550 if (os_subtype
== OS_9X
)
3556 oldname
= map_w32_filename (oldname
, NULL
);
3557 if ((o
= strrchr (oldname
, '\\')))
3560 o
= (char *) oldname
;
3562 if ((p
= strrchr (temp
, '\\')))
3569 /* Force temp name to require a manufactured 8.3 alias - this
3570 seems to make the second rename work properly. */
3571 sprintf (p
, "_.%s.%u", o
, i
);
3573 result
= rename (oldname
, temp
);
3575 /* This loop must surely terminate! */
3576 while (result
< 0 && errno
== EEXIST
);
3581 /* If FORCE, emulate Unix behavior - newname is deleted if it already exists
3582 (at least if it is a file; don't do this for directories).
3584 Since we mustn't do this if we are just changing the case of the
3585 file name (we would end up deleting the file we are trying to
3586 rename!), we let rename detect if the destination file already
3587 exists - that way we avoid the possible pitfalls of trying to
3588 determine ourselves whether two names really refer to the same
3589 file, which is not always possible in the general case. (Consider
3590 all the permutations of shared or subst'd drives, etc.) */
3592 newname
= map_w32_filename (newname
, NULL
);
3594 /* volume_info is set indirectly by map_w32_filename. */
3595 newname_dev
= volume_info
.serialnum
;
3597 result
= rename (temp
, newname
);
3599 if (result
< 0 && force
)
3601 DWORD w32err
= GetLastError ();
3604 && newname_dev
!= oldname_dev
)
3606 /* The implementation of `rename' on Windows does not return
3607 errno = EXDEV when you are moving a directory to a
3608 different storage device (ex. logical disk). It returns
3609 EACCES instead. So here we handle such situations and
3613 if ((attributes
= GetFileAttributes (temp
)) != -1
3614 && (attributes
& FILE_ATTRIBUTE_DIRECTORY
))
3617 else if (errno
== EEXIST
)
3619 if (_chmod (newname
, 0666) != 0)
3621 if (_unlink (newname
) != 0)
3623 result
= rename (temp
, newname
);
3625 else if (w32err
== ERROR_PRIVILEGE_NOT_HELD
3626 && is_symlink (temp
))
3628 /* This is Windows prohibiting the user from creating a
3629 symlink in another place, since that requires
3639 sys_rename (char const *old
, char const *new)
3641 return sys_rename_replace (old
, new, TRUE
);
3645 sys_rmdir (const char * path
)
3647 return _rmdir (map_w32_filename (path
, NULL
));
3651 sys_unlink (const char * path
)
3653 path
= map_w32_filename (path
, NULL
);
3655 /* On Unix, unlink works without write permission. */
3656 _chmod (path
, 0666);
3657 return _unlink (path
);
3660 static FILETIME utc_base_ft
;
3661 static ULONGLONG utc_base
; /* In 100ns units */
3662 static int init
= 0;
3664 #define FILETIME_TO_U64(result, ft) \
3666 ULARGE_INTEGER uiTemp; \
3667 uiTemp.LowPart = (ft).dwLowDateTime; \
3668 uiTemp.HighPart = (ft).dwHighDateTime; \
3669 result = uiTemp.QuadPart; \
3673 initialize_utc_base (void)
3675 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
3684 st
.wMilliseconds
= 0;
3686 SystemTimeToFileTime (&st
, &utc_base_ft
);
3687 FILETIME_TO_U64 (utc_base
, utc_base_ft
);
3691 convert_time (FILETIME ft
)
3697 initialize_utc_base ();
3701 if (CompareFileTime (&ft
, &utc_base_ft
) < 0)
3704 FILETIME_TO_U64 (tmp
, ft
);
3705 return (time_t) ((tmp
- utc_base
) / 10000000L);
3709 convert_from_time_t (time_t time
, FILETIME
* pft
)
3715 initialize_utc_base ();
3719 /* time in 100ns units since 1-Jan-1601 */
3720 tmp
.QuadPart
= (ULONGLONG
) time
* 10000000L + utc_base
;
3721 pft
->dwHighDateTime
= tmp
.HighPart
;
3722 pft
->dwLowDateTime
= tmp
.LowPart
;
3726 /* No reason to keep this; faking inode values either by hashing or even
3727 using the file index from GetInformationByHandle, is not perfect and
3728 so by default Emacs doesn't use the inode values on Windows.
3729 Instead, we now determine file-truename correctly (except for
3730 possible drive aliasing etc). */
3732 /* Modified version of "PJW" algorithm (see the "Dragon" compiler book). */
3734 hashval (const unsigned char * str
)
3739 h
= (h
<< 4) + *str
++;
3745 /* Return the hash value of the canonical pathname, excluding the
3746 drive/UNC header, to get a hopefully unique inode number. */
3748 generate_inode_val (const char * name
)
3750 char fullname
[ MAX_PATH
];
3754 /* Get the truly canonical filename, if it exists. (Note: this
3755 doesn't resolve aliasing due to subst commands, or recognize hard
3757 if (!w32_get_long_filename ((char *)name
, fullname
, MAX_PATH
))
3760 parse_root (fullname
, &p
);
3761 /* Normal W32 filesystems are still case insensitive. */
3768 static PSECURITY_DESCRIPTOR
3769 get_file_security_desc_by_handle (HANDLE h
)
3771 PSECURITY_DESCRIPTOR psd
= NULL
;
3773 SECURITY_INFORMATION si
= OWNER_SECURITY_INFORMATION
3774 | GROUP_SECURITY_INFORMATION
/* | DACL_SECURITY_INFORMATION */ ;
3776 err
= get_security_info (h
, SE_FILE_OBJECT
, si
,
3777 NULL
, NULL
, NULL
, NULL
, &psd
);
3778 if (err
!= ERROR_SUCCESS
)
3784 static PSECURITY_DESCRIPTOR
3785 get_file_security_desc_by_name (const char *fname
)
3787 PSECURITY_DESCRIPTOR psd
= NULL
;
3789 SECURITY_INFORMATION si
= OWNER_SECURITY_INFORMATION
3790 | GROUP_SECURITY_INFORMATION
/* | DACL_SECURITY_INFORMATION */ ;
3792 if (!get_file_security (fname
, si
, psd
, 0, &sd_len
))
3794 err
= GetLastError ();
3795 if (err
!= ERROR_INSUFFICIENT_BUFFER
)
3799 psd
= xmalloc (sd_len
);
3800 if (!get_file_security (fname
, si
, psd
, sd_len
, &sd_len
))
3812 unsigned n_subauthorities
;
3814 /* Use the last sub-authority value of the RID, the relative
3815 portion of the SID, as user/group ID. */
3816 n_subauthorities
= *get_sid_sub_authority_count (sid
);
3817 if (n_subauthorities
< 1)
3818 return 0; /* the "World" RID */
3819 return *get_sid_sub_authority (sid
, n_subauthorities
- 1);
3822 /* Caching SID and account values for faster lokup. */
3826 struct w32_id
*next
;
3828 unsigned char sid
[FLEXIBLE_ARRAY_MEMBER
];
3831 static struct w32_id
*w32_idlist
;
3834 w32_cached_id (PSID sid
, unsigned *id
, char *name
)
3836 struct w32_id
*tail
, *found
;
3838 for (found
= NULL
, tail
= w32_idlist
; tail
; tail
= tail
->next
)
3840 if (equal_sid ((PSID
)tail
->sid
, sid
))
3849 strcpy (name
, found
->name
);
3857 w32_add_to_cache (PSID sid
, unsigned id
, char *name
)
3860 struct w32_id
*new_entry
;
3862 /* We don't want to leave behind stale cache from when Emacs was
3866 sid_len
= get_length_sid (sid
);
3867 new_entry
= xmalloc (offsetof (struct w32_id
, sid
) + sid_len
);
3870 new_entry
->rid
= id
;
3871 strcpy (new_entry
->name
, name
);
3872 copy_sid (sid_len
, (PSID
)new_entry
->sid
, sid
);
3873 new_entry
->next
= w32_idlist
;
3874 w32_idlist
= new_entry
;
3883 get_name_and_id (PSECURITY_DESCRIPTOR psd
, unsigned *id
, char *nm
, int what
)
3887 SID_NAME_USE ignore
;
3889 DWORD name_len
= sizeof (name
);
3891 DWORD domain_len
= sizeof (domain
);
3896 result
= get_security_descriptor_owner (psd
, &sid
, &dflt
);
3897 else if (what
== GID
)
3898 result
= get_security_descriptor_group (psd
, &sid
, &dflt
);
3902 if (!result
|| !is_valid_sid (sid
))
3904 else if (!w32_cached_id (sid
, id
, nm
))
3906 if (!lookup_account_sid (NULL
, sid
, name
, &name_len
,
3907 domain
, &domain_len
, &ignore
)
3908 || name_len
> UNLEN
+1)
3912 *id
= get_rid (sid
);
3914 w32_add_to_cache (sid
, *id
, name
);
3921 get_file_owner_and_group (PSECURITY_DESCRIPTOR psd
, struct stat
*st
)
3923 int dflt_usr
= 0, dflt_grp
= 0;
3932 if (get_name_and_id (psd
, &st
->st_uid
, st
->st_uname
, UID
))
3934 if (get_name_and_id (psd
, &st
->st_gid
, st
->st_gname
, GID
))
3937 /* Consider files to belong to current user/group, if we cannot get
3938 more accurate information. */
3941 st
->st_uid
= dflt_passwd
.pw_uid
;
3942 strcpy (st
->st_uname
, dflt_passwd
.pw_name
);
3946 st
->st_gid
= dflt_passwd
.pw_gid
;
3947 strcpy (st
->st_gname
, dflt_group
.gr_name
);
3951 /* Return non-zero if NAME is a potentially slow filesystem. */
3953 is_slow_fs (const char *name
)
3958 if (IS_DIRECTORY_SEP (name
[0]) && IS_DIRECTORY_SEP (name
[1]))
3959 devtype
= DRIVE_REMOTE
; /* assume UNC name is remote */
3960 else if (!(strlen (name
) >= 2 && IS_DEVICE_SEP (name
[1])))
3961 devtype
= GetDriveType (NULL
); /* use root of current drive */
3964 /* GetDriveType needs the root directory of the drive. */
3965 strncpy (drive_root
, name
, 2);
3966 drive_root
[2] = '\\';
3967 drive_root
[3] = '\0';
3968 devtype
= GetDriveType (drive_root
);
3970 return !(devtype
== DRIVE_FIXED
|| devtype
== DRIVE_RAMDISK
);
3973 /* If this is non-zero, the caller wants accurate information about
3974 file's owner and group, which could be expensive to get. */
3975 int w32_stat_get_owner_group
;
3977 /* MSVC stat function can't cope with UNC names and has other bugs, so
3978 replace it with our own. This also allows us to calculate consistent
3979 inode values and owner/group without hacks in the main Emacs code. */
3982 stat_worker (const char * path
, struct stat
* buf
, int follow_symlinks
)
3984 char *name
, *save_name
, *r
;
3985 WIN32_FIND_DATA wfd
;
3987 unsigned __int64 fake_inode
= 0;
3990 int rootdir
= FALSE
;
3991 PSECURITY_DESCRIPTOR psd
= NULL
;
3992 int is_a_symlink
= 0;
3993 DWORD file_flags
= FILE_FLAG_BACKUP_SEMANTICS
;
3994 DWORD access_rights
= 0;
3995 DWORD fattrs
= 0, serialnum
= 0, fs_high
= 0, fs_low
= 0, nlinks
= 1;
3996 FILETIME ctime
, atime
, wtime
;
3999 if (path
== NULL
|| buf
== NULL
)
4005 save_name
= name
= (char *) map_w32_filename (path
, &path
);
4006 /* Must be valid filename, no wild cards or other invalid
4007 characters. We use _mbspbrk to support multibyte strings that
4008 might look to strpbrk as if they included literal *, ?, and other
4009 characters mentioned below that are disallowed by Windows
4011 if (_mbspbrk (name
, "*?|<>\""))
4017 /* Remove trailing directory separator, unless name is the root
4018 directory of a drive or UNC volume in which case ensure there
4019 is a trailing separator. */
4020 len
= strlen (name
);
4021 name
= strcpy (alloca (len
+ 2), name
);
4023 /* Avoid a somewhat costly call to is_symlink if the filesystem
4024 doesn't support symlinks. */
4025 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) != 0)
4026 is_a_symlink
= is_symlink (name
);
4028 /* Plan A: Open the file and get all the necessary information via
4029 the resulting handle. This solves several issues in one blow:
4031 . retrieves attributes for the target of a symlink, if needed
4032 . gets attributes of root directories and symlinks pointing to
4033 root directories, thus avoiding the need for special-casing
4034 these and detecting them by examining the file-name format
4035 . retrieves more accurate attributes (e.g., non-zero size for
4036 some directories, esp. directories that are junction points)
4037 . correctly resolves "c:/..", "/.." and similar file names
4038 . avoids run-time penalties for 99% of use cases
4040 Plan A is always tried first, unless the user asked not to (but
4041 if the file is a symlink and we need to follow links, we try Plan
4042 A even if the user asked not to).
4044 If Plan A fails, we go to Plan B (below), where various
4045 potentially expensive techniques must be used to handle "special"
4046 files such as UNC volumes etc. */
4047 if (!(NILP (Vw32_get_true_file_attributes
)
4048 || (EQ (Vw32_get_true_file_attributes
, Qlocal
) && is_slow_fs (name
)))
4049 /* Following symlinks requires getting the info by handle. */
4050 || (is_a_symlink
&& follow_symlinks
))
4052 BY_HANDLE_FILE_INFORMATION info
;
4054 if (is_a_symlink
&& !follow_symlinks
)
4055 file_flags
|= FILE_FLAG_OPEN_REPARSE_POINT
;
4056 /* READ_CONTROL access rights are required to get security info
4057 by handle. But if the OS doesn't support security in the
4058 first place, we don't need to try. */
4059 if (is_windows_9x () != TRUE
)
4060 access_rights
|= READ_CONTROL
;
4062 fh
= CreateFile (name
, access_rights
, 0, NULL
, OPEN_EXISTING
,
4064 /* If CreateFile fails with READ_CONTROL, try again with zero as
4066 if (fh
== INVALID_HANDLE_VALUE
&& access_rights
)
4067 fh
= CreateFile (name
, 0, 0, NULL
, OPEN_EXISTING
,
4069 if (fh
== INVALID_HANDLE_VALUE
)
4070 goto no_true_file_attributes
;
4072 /* This is more accurate in terms of getting the correct number
4073 of links, but is quite slow (it is noticeable when Emacs is
4074 making a list of file name completions). */
4075 if (GetFileInformationByHandle (fh
, &info
))
4077 nlinks
= info
.nNumberOfLinks
;
4078 /* Might as well use file index to fake inode values, but this
4079 is not guaranteed to be unique unless we keep a handle open
4080 all the time (even then there are situations where it is
4081 not unique). Reputedly, there are at most 48 bits of info
4082 (on NTFS, presumably less on FAT). */
4083 fake_inode
= info
.nFileIndexHigh
;
4085 fake_inode
+= info
.nFileIndexLow
;
4086 serialnum
= info
.dwVolumeSerialNumber
;
4087 fs_high
= info
.nFileSizeHigh
;
4088 fs_low
= info
.nFileSizeLow
;
4089 ctime
= info
.ftCreationTime
;
4090 atime
= info
.ftLastAccessTime
;
4091 wtime
= info
.ftLastWriteTime
;
4092 fattrs
= info
.dwFileAttributes
;
4096 /* We don't go to Plan B here, because it's not clear that
4097 it's a good idea. The only known use case where
4098 CreateFile succeeds, but GetFileInformationByHandle fails
4099 (with ERROR_INVALID_FUNCTION) is for character devices
4100 such as NUL, PRN, etc. For these, switching to Plan B is
4101 a net loss, because we lose the character device
4102 attribute returned by GetFileType below (FindFirstFile
4103 doesn't set that bit in the attributes), and the other
4104 fields don't make sense for character devices anyway.
4105 Emacs doesn't really care for non-file entities in the
4106 context of l?stat, so neither do we. */
4108 /* w32err is assigned so one could put a breakpoint here and
4109 examine its value, when GetFileInformationByHandle
4111 DWORD w32err
= GetLastError ();
4115 case ERROR_FILE_NOT_FOUND
: /* can this ever happen? */
4121 /* Test for a symlink before testing for a directory, since
4122 symlinks to directories have the directory bit set, but we
4123 don't want them to appear as directories. */
4124 if (is_a_symlink
&& !follow_symlinks
)
4125 buf
->st_mode
= S_IFLNK
;
4126 else if (fattrs
& FILE_ATTRIBUTE_DIRECTORY
)
4127 buf
->st_mode
= S_IFDIR
;
4130 DWORD ftype
= GetFileType (fh
);
4134 case FILE_TYPE_DISK
:
4135 buf
->st_mode
= S_IFREG
;
4137 case FILE_TYPE_PIPE
:
4138 buf
->st_mode
= S_IFIFO
;
4140 case FILE_TYPE_CHAR
:
4141 case FILE_TYPE_UNKNOWN
:
4143 buf
->st_mode
= S_IFCHR
;
4146 /* We produce the fallback owner and group data, based on the
4147 current user that runs Emacs, in the following cases:
4149 . caller didn't request owner and group info
4150 . this is Windows 9X
4151 . getting security by handle failed, and we need to produce
4152 information for the target of a symlink (this is better
4153 than producing a potentially misleading info about the
4156 If getting security by handle fails, and we don't need to
4157 resolve symlinks, we try getting security by name. */
4158 if (!w32_stat_get_owner_group
|| is_windows_9x () == TRUE
)
4159 get_file_owner_and_group (NULL
, buf
);
4162 psd
= get_file_security_desc_by_handle (fh
);
4165 get_file_owner_and_group (psd
, buf
);
4168 else if (!(is_a_symlink
&& follow_symlinks
))
4170 psd
= get_file_security_desc_by_name (name
);
4171 get_file_owner_and_group (psd
, buf
);
4175 get_file_owner_and_group (NULL
, buf
);
4181 no_true_file_attributes
:
4182 /* Plan B: Either getting a handle on the file failed, or the
4183 caller explicitly asked us to not bother making this
4184 information more accurate.
4186 Implementation note: In Plan B, we never bother to resolve
4187 symlinks, even if we got here because we tried Plan A and
4188 failed. That's because, even if the caller asked for extra
4189 precision by setting Vw32_get_true_file_attributes to t,
4190 resolving symlinks requires acquiring a file handle to the
4191 symlink, which we already know will fail. And if the user
4192 did not ask for extra precision, resolving symlinks will fly
4193 in the face of that request, since the user then wants the
4194 lightweight version of the code. */
4195 dbcs_p
= max_filename_mbslen () > 1;
4196 rootdir
= (path
>= save_name
+ len
- 1
4197 && (IS_DIRECTORY_SEP (*path
) || *path
== 0));
4199 /* If name is "c:/.." or "/.." then stat "c:/" or "/". */
4200 r
= IS_DEVICE_SEP (name
[1]) ? &name
[2] : name
;
4201 if (IS_DIRECTORY_SEP (r
[0])
4202 && r
[1] == '.' && r
[2] == '.' && r
[3] == '\0')
4205 /* Note: If NAME is a symlink to the root of a UNC volume
4206 (i.e. "\\SERVER"), we will not detect that here, and we will
4207 return data about the symlink as result of FindFirst below.
4208 This is unfortunate, but that marginal use case does not
4209 justify a call to chase_symlinks which would impose a penalty
4210 on all the other use cases. (We get here for symlinks to
4211 roots of UNC volumes because CreateFile above fails for them,
4212 unlike with symlinks to root directories X:\ of drives.) */
4213 if (is_unc_volume (name
))
4215 fattrs
= unc_volume_file_attributes (name
);
4219 ctime
= atime
= wtime
= utc_base_ft
;
4225 if (!IS_DIRECTORY_SEP (name
[len
-1]))
4226 strcat (name
, "\\");
4230 char *end
= name
+ len
;
4231 char *n
= CharPrevExA (file_name_codepage
, name
, end
, 0);
4233 if (!IS_DIRECTORY_SEP (*n
))
4234 strcat (name
, "\\");
4236 if (GetDriveType (name
) < 2)
4242 fattrs
= FILE_ATTRIBUTE_DIRECTORY
;
4243 ctime
= atime
= wtime
= utc_base_ft
;
4249 if (IS_DIRECTORY_SEP (name
[len
-1]))
4254 char *end
= name
+ len
;
4255 char *n
= CharPrevExA (file_name_codepage
, name
, end
, 0);
4257 if (IS_DIRECTORY_SEP (*n
))
4261 /* (This is hacky, but helps when doing file completions on
4262 network drives.) Optimize by using information available from
4263 active readdir if possible. */
4264 len
= strlen (dir_pathname
);
4267 if (IS_DIRECTORY_SEP (dir_pathname
[len
-1]))
4272 char *end
= dir_pathname
+ len
;
4273 char *n
= CharPrevExA (file_name_codepage
, dir_pathname
, end
, 0);
4275 if (IS_DIRECTORY_SEP (*n
))
4278 if (dir_find_handle
!= INVALID_HANDLE_VALUE
4279 && !(is_a_symlink
&& follow_symlinks
)
4280 && strnicmp (save_name
, dir_pathname
, len
) == 0
4281 && IS_DIRECTORY_SEP (name
[len
])
4282 && xstrcasecmp (name
+ len
+ 1, dir_static
.d_name
) == 0)
4284 /* This was the last entry returned by readdir. */
4285 wfd
= dir_find_data
;
4289 logon_network_drive (name
);
4291 fh
= FindFirstFile (name
, &wfd
);
4292 if (fh
== INVALID_HANDLE_VALUE
)
4299 /* Note: if NAME is a symlink, the information we get from
4300 FindFirstFile is for the symlink, not its target. */
4301 fattrs
= wfd
.dwFileAttributes
;
4302 ctime
= wfd
.ftCreationTime
;
4303 atime
= wfd
.ftLastAccessTime
;
4304 wtime
= wfd
.ftLastWriteTime
;
4305 fs_high
= wfd
.nFileSizeHigh
;
4306 fs_low
= wfd
.nFileSizeLow
;
4309 serialnum
= volume_info
.serialnum
;
4311 if (is_a_symlink
&& !follow_symlinks
)
4312 buf
->st_mode
= S_IFLNK
;
4313 else if (fattrs
& FILE_ATTRIBUTE_DIRECTORY
)
4314 buf
->st_mode
= S_IFDIR
;
4316 buf
->st_mode
= S_IFREG
;
4318 get_file_owner_and_group (NULL
, buf
);
4322 /* Not sure if there is any point in this. */
4323 if (!NILP (Vw32_generate_fake_inodes
))
4324 fake_inode
= generate_inode_val (name
);
4325 else if (fake_inode
== 0)
4327 /* For want of something better, try to make everything unique. */
4328 static DWORD gen_num
= 0;
4329 fake_inode
= ++gen_num
;
4333 buf
->st_ino
= fake_inode
;
4335 buf
->st_dev
= serialnum
;
4336 buf
->st_rdev
= serialnum
;
4338 buf
->st_size
= fs_high
;
4339 buf
->st_size
<<= 32;
4340 buf
->st_size
+= fs_low
;
4341 buf
->st_nlink
= nlinks
;
4343 /* Convert timestamps to Unix format. */
4344 buf
->st_mtime
= convert_time (wtime
);
4345 buf
->st_atime
= convert_time (atime
);
4346 if (buf
->st_atime
== 0) buf
->st_atime
= buf
->st_mtime
;
4347 buf
->st_ctime
= convert_time (ctime
);
4348 if (buf
->st_ctime
== 0) buf
->st_ctime
= buf
->st_mtime
;
4350 /* determine rwx permissions */
4351 if (is_a_symlink
&& !follow_symlinks
)
4352 permission
= S_IREAD
| S_IWRITE
| S_IEXEC
; /* Posix expectations */
4355 if (fattrs
& FILE_ATTRIBUTE_READONLY
)
4356 permission
= S_IREAD
;
4358 permission
= S_IREAD
| S_IWRITE
;
4360 if (fattrs
& FILE_ATTRIBUTE_DIRECTORY
)
4361 permission
|= S_IEXEC
;
4362 else if (is_exec (name
))
4363 permission
|= S_IEXEC
;
4366 buf
->st_mode
|= permission
| (permission
>> 3) | (permission
>> 6);
4372 stat (const char * path
, struct stat
* buf
)
4374 return stat_worker (path
, buf
, 1);
4378 lstat (const char * path
, struct stat
* buf
)
4380 return stat_worker (path
, buf
, 0);
4384 fstatat (int fd
, char const *name
, struct stat
*st
, int flags
)
4386 /* Rely on a hack: an open directory is modeled as file descriptor 0.
4387 This is good enough for the current usage in Emacs, but is fragile.
4389 FIXME: Add proper support for fdopendir, fstatat, readlinkat.
4390 Gnulib does this and can serve as a model. */
4391 char fullname
[MAX_PATH
];
4395 if (_snprintf (fullname
, sizeof fullname
, "%s/%s", dir_pathname
, name
)
4398 errno
= ENAMETOOLONG
;
4404 return stat_worker (name
, st
, ! (flags
& AT_SYMLINK_NOFOLLOW
));
4407 /* Provide fstat and utime as well as stat for consistent handling of
4410 fstat (int desc
, struct stat
* buf
)
4412 HANDLE fh
= (HANDLE
) _get_osfhandle (desc
);
4413 BY_HANDLE_FILE_INFORMATION info
;
4414 unsigned __int64 fake_inode
;
4417 switch (GetFileType (fh
) & ~FILE_TYPE_REMOTE
)
4419 case FILE_TYPE_DISK
:
4420 buf
->st_mode
= S_IFREG
;
4421 if (!GetFileInformationByHandle (fh
, &info
))
4427 case FILE_TYPE_PIPE
:
4428 buf
->st_mode
= S_IFIFO
;
4430 case FILE_TYPE_CHAR
:
4431 case FILE_TYPE_UNKNOWN
:
4433 buf
->st_mode
= S_IFCHR
;
4435 memset (&info
, 0, sizeof (info
));
4436 info
.dwFileAttributes
= 0;
4437 info
.ftCreationTime
= utc_base_ft
;
4438 info
.ftLastAccessTime
= utc_base_ft
;
4439 info
.ftLastWriteTime
= utc_base_ft
;
4442 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
4443 buf
->st_mode
= S_IFDIR
;
4445 buf
->st_nlink
= info
.nNumberOfLinks
;
4446 /* Might as well use file index to fake inode values, but this
4447 is not guaranteed to be unique unless we keep a handle open
4448 all the time (even then there are situations where it is
4449 not unique). Reputedly, there are at most 48 bits of info
4450 (on NTFS, presumably less on FAT). */
4451 fake_inode
= info
.nFileIndexHigh
;
4453 fake_inode
+= info
.nFileIndexLow
;
4455 /* MSVC defines _ino_t to be short; other libc's might not. */
4456 if (sizeof (buf
->st_ino
) == 2)
4457 buf
->st_ino
= fake_inode
^ (fake_inode
>> 16);
4459 buf
->st_ino
= fake_inode
;
4461 /* If the caller so requested, get the true file owner and group.
4462 Otherwise, consider the file to belong to the current user. */
4463 if (!w32_stat_get_owner_group
|| is_windows_9x () == TRUE
)
4464 get_file_owner_and_group (NULL
, buf
);
4467 PSECURITY_DESCRIPTOR psd
= NULL
;
4469 psd
= get_file_security_desc_by_handle (fh
);
4472 get_file_owner_and_group (psd
, buf
);
4476 get_file_owner_and_group (NULL
, buf
);
4479 buf
->st_dev
= info
.dwVolumeSerialNumber
;
4480 buf
->st_rdev
= info
.dwVolumeSerialNumber
;
4482 buf
->st_size
= info
.nFileSizeHigh
;
4483 buf
->st_size
<<= 32;
4484 buf
->st_size
+= info
.nFileSizeLow
;
4486 /* Convert timestamps to Unix format. */
4487 buf
->st_mtime
= convert_time (info
.ftLastWriteTime
);
4488 buf
->st_atime
= convert_time (info
.ftLastAccessTime
);
4489 if (buf
->st_atime
== 0) buf
->st_atime
= buf
->st_mtime
;
4490 buf
->st_ctime
= convert_time (info
.ftCreationTime
);
4491 if (buf
->st_ctime
== 0) buf
->st_ctime
= buf
->st_mtime
;
4493 /* determine rwx permissions */
4494 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
)
4495 permission
= S_IREAD
;
4497 permission
= S_IREAD
| S_IWRITE
;
4499 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
4500 permission
|= S_IEXEC
;
4503 #if 0 /* no way of knowing the filename */
4504 char * p
= strrchr (name
, '.');
4506 (xstrcasecmp (p
, ".exe") == 0 ||
4507 xstrcasecmp (p
, ".com") == 0 ||
4508 xstrcasecmp (p
, ".bat") == 0 ||
4509 xstrcasecmp (p
, ".cmd") == 0))
4510 permission
|= S_IEXEC
;
4514 buf
->st_mode
|= permission
| (permission
>> 3) | (permission
>> 6);
4519 /* A version of 'utime' which handles directories as well as
4523 utime (const char *name
, struct utimbuf
*times
)
4525 struct utimbuf deftime
;
4532 deftime
.modtime
= deftime
.actime
= time (NULL
);
4536 /* Need write access to set times. */
4537 fh
= CreateFile (name
, FILE_WRITE_ATTRIBUTES
,
4538 /* If NAME specifies a directory, FILE_SHARE_DELETE
4539 allows other processes to delete files inside it,
4540 while we have the directory open. */
4541 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
4542 0, OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
4543 if (fh
!= INVALID_HANDLE_VALUE
)
4545 convert_from_time_t (times
->actime
, &atime
);
4546 convert_from_time_t (times
->modtime
, &mtime
);
4547 if (!SetFileTime (fh
, NULL
, &atime
, &mtime
))
4564 /* Symlink-related functions. */
4565 #ifndef SYMBOLIC_LINK_FLAG_DIRECTORY
4566 #define SYMBOLIC_LINK_FLAG_DIRECTORY 0x1
4570 symlink (char const *filename
, char const *linkname
)
4572 char linkfn
[MAX_PATH
], *tgtfn
;
4574 int dir_access
, filename_ends_in_slash
;
4577 /* Diagnostics follows Posix as much as possible. */
4578 if (filename
== NULL
|| linkname
== NULL
)
4588 if (strlen (filename
) > MAX_PATH
|| strlen (linkname
) > MAX_PATH
)
4590 errno
= ENAMETOOLONG
;
4594 strcpy (linkfn
, map_w32_filename (linkname
, NULL
));
4595 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) == 0)
4601 dbcs_p
= max_filename_mbslen () > 1;
4603 /* Note: since empty FILENAME was already rejected, we can safely
4604 refer to FILENAME[1]. */
4605 if (!(IS_DIRECTORY_SEP (filename
[0]) || IS_DEVICE_SEP (filename
[1])))
4607 /* Non-absolute FILENAME is understood as being relative to
4608 LINKNAME's directory. We need to prepend that directory to
4609 FILENAME to get correct results from faccessat below, since
4610 otherwise it will interpret FILENAME relative to the
4611 directory where the Emacs process runs. Note that
4612 make-symbolic-link always makes sure LINKNAME is a fully
4613 expanded file name. */
4615 char *p
= linkfn
+ strlen (linkfn
);
4619 while (p
> linkfn
&& !IS_ANY_SEP (p
[-1]))
4624 char *p1
= CharPrevExA (file_name_codepage
, linkfn
, p
, 0);
4626 while (p
> linkfn
&& !IS_ANY_SEP (*p1
))
4629 p1
= CharPrevExA (file_name_codepage
, linkfn
, p1
, 0);
4633 strncpy (tem
, linkfn
, p
- linkfn
);
4634 tem
[p
- linkfn
] = '\0';
4635 strcat (tem
, filename
);
4636 dir_access
= faccessat (AT_FDCWD
, tem
, D_OK
, AT_EACCESS
);
4639 dir_access
= faccessat (AT_FDCWD
, filename
, D_OK
, AT_EACCESS
);
4641 /* Since Windows distinguishes between symlinks to directories and
4642 to files, we provide a kludgy feature: if FILENAME doesn't
4643 exist, but ends in a slash, we create a symlink to directory. If
4644 FILENAME exists and is a directory, we always create a symlink to
4647 filename_ends_in_slash
= IS_DIRECTORY_SEP (filename
[strlen (filename
) - 1]);
4650 const char *end
= filename
+ strlen (filename
);
4651 const char *n
= CharPrevExA (file_name_codepage
, filename
, end
, 0);
4653 filename_ends_in_slash
= IS_DIRECTORY_SEP (*n
);
4655 if (dir_access
== 0 || filename_ends_in_slash
)
4656 flags
= SYMBOLIC_LINK_FLAG_DIRECTORY
;
4658 tgtfn
= (char *)map_w32_filename (filename
, NULL
);
4659 if (filename_ends_in_slash
)
4660 tgtfn
[strlen (tgtfn
) - 1] = '\0';
4663 if (!create_symbolic_link (linkfn
, tgtfn
, flags
))
4665 /* ENOSYS is set by create_symbolic_link, when it detects that
4666 the OS doesn't support the CreateSymbolicLink API. */
4667 if (errno
!= ENOSYS
)
4669 DWORD w32err
= GetLastError ();
4673 /* ERROR_SUCCESS is sometimes returned when LINKFN and
4674 TGTFN point to the same file name, go figure. */
4676 case ERROR_FILE_EXISTS
:
4679 case ERROR_ACCESS_DENIED
:
4682 case ERROR_FILE_NOT_FOUND
:
4683 case ERROR_PATH_NOT_FOUND
:
4684 case ERROR_BAD_NETPATH
:
4685 case ERROR_INVALID_REPARSE_DATA
:
4688 case ERROR_DIRECTORY
:
4691 case ERROR_PRIVILEGE_NOT_HELD
:
4692 case ERROR_NOT_ALL_ASSIGNED
:
4695 case ERROR_DISK_FULL
:
4708 /* A quick inexpensive test of whether FILENAME identifies a file that
4709 is a symlink. Returns non-zero if it is, zero otherwise. FILENAME
4710 must already be in the normalized form returned by
4713 Note: for repeated operations on many files, it is best to test
4714 whether the underlying volume actually supports symlinks, by
4715 testing the FILE_SUPPORTS_REPARSE_POINTS bit in volume's flags, and
4716 avoid the call to this function if it doesn't. That's because the
4717 call to GetFileAttributes takes a non-negligible time, especially
4718 on non-local or removable filesystems. See stat_worker for an
4719 example of how to do that. */
4721 is_symlink (const char *filename
)
4724 WIN32_FIND_DATA wfd
;
4727 attrs
= GetFileAttributes (filename
);
4730 DWORD w32err
= GetLastError ();
4734 case ERROR_BAD_NETPATH
: /* network share, can't be a symlink */
4736 case ERROR_ACCESS_DENIED
:
4739 case ERROR_FILE_NOT_FOUND
:
4740 case ERROR_PATH_NOT_FOUND
:
4747 if ((attrs
& FILE_ATTRIBUTE_REPARSE_POINT
) == 0)
4749 logon_network_drive (filename
);
4750 fh
= FindFirstFile (filename
, &wfd
);
4751 if (fh
== INVALID_HANDLE_VALUE
)
4754 return (wfd
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) != 0
4755 && (wfd
.dwReserved0
& IO_REPARSE_TAG_SYMLINK
) == IO_REPARSE_TAG_SYMLINK
;
4758 /* If NAME identifies a symbolic link, copy into BUF the file name of
4759 the symlink's target. Copy at most BUF_SIZE bytes, and do NOT
4760 null-terminate the target name, even if it fits. Return the number
4761 of bytes copied, or -1 if NAME is not a symlink or any error was
4762 encountered while resolving it. The file name copied into BUF is
4763 encoded in the current ANSI codepage. */
4765 readlink (const char *name
, char *buf
, size_t buf_size
)
4768 TOKEN_PRIVILEGES privs
;
4769 int restore_privs
= 0;
4784 path
= map_w32_filename (name
, NULL
);
4786 if (strlen (path
) > MAX_PATH
)
4788 errno
= ENAMETOOLONG
;
4793 if (is_windows_9x () == TRUE
4794 || (volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) == 0
4795 || !is_symlink (path
))
4798 errno
= EINVAL
; /* not a symlink */
4802 /* Done with simple tests, now we're in for some _real_ work. */
4803 if (enable_privilege (SE_BACKUP_NAME
, TRUE
, &privs
))
4805 /* Implementation note: From here and onward, don't return early,
4806 since that will fail to restore the original set of privileges of
4807 the calling thread. */
4809 retval
= -1; /* not too optimistic, are we? */
4811 /* Note: In the next call to CreateFile, we use zero as the 2nd
4812 argument because, when the symlink is a hidden/system file,
4813 e.g. 'C:\Users\All Users', GENERIC_READ fails with
4814 ERROR_ACCESS_DENIED. Zero seems to work just fine, both for file
4815 and directory symlinks. */
4816 sh
= CreateFile (path
, 0, 0, NULL
, OPEN_EXISTING
,
4817 FILE_FLAG_OPEN_REPARSE_POINT
| FILE_FLAG_BACKUP_SEMANTICS
,
4819 if (sh
!= INVALID_HANDLE_VALUE
)
4821 BYTE reparse_buf
[MAXIMUM_REPARSE_DATA_BUFFER_SIZE
];
4822 REPARSE_DATA_BUFFER
*reparse_data
= (REPARSE_DATA_BUFFER
*)&reparse_buf
[0];
4825 if (!DeviceIoControl (sh
, FSCTL_GET_REPARSE_POINT
, NULL
, 0,
4826 reparse_buf
, MAXIMUM_REPARSE_DATA_BUFFER_SIZE
,
4829 else if (reparse_data
->ReparseTag
!= IO_REPARSE_TAG_SYMLINK
)
4833 /* Copy the link target name, in wide characters, from
4834 reparse_data, then convert it to multibyte encoding in
4835 the current locale's codepage. */
4837 BYTE lname
[MAX_PATH
];
4840 reparse_data
->SymbolicLinkReparseBuffer
.PrintNameLength
;
4842 reparse_data
->SymbolicLinkReparseBuffer
.PathBuffer
4843 + reparse_data
->SymbolicLinkReparseBuffer
.PrintNameOffset
/sizeof(WCHAR
);
4844 /* This updates file_name_codepage which we need below. */
4845 int dbcs_p
= max_filename_mbslen () > 1;
4847 /* According to MSDN, PrintNameLength does not include the
4848 terminating null character. */
4849 lwname
= alloca ((lwname_len
+ 1) * sizeof(WCHAR
));
4850 memcpy (lwname
, lwname_src
, lwname_len
);
4851 lwname
[lwname_len
/sizeof(WCHAR
)] = 0; /* null-terminate */
4853 lname_len
= WideCharToMultiByte (file_name_codepage
, 0, lwname
, -1,
4854 lname
, MAX_PATH
, NULL
, NULL
);
4857 /* WideCharToMultiByte failed. */
4858 DWORD w32err1
= GetLastError ();
4862 case ERROR_INSUFFICIENT_BUFFER
:
4863 errno
= ENAMETOOLONG
;
4865 case ERROR_INVALID_PARAMETER
:
4868 case ERROR_NO_UNICODE_TRANSLATION
:
4878 size_t size_to_copy
= buf_size
;
4879 BYTE
*p
= lname
, *p2
;
4880 BYTE
*pend
= p
+ lname_len
;
4882 /* Normalize like dostounix_filename does, but we don't
4883 want to assume that lname is null-terminated. */
4885 p2
= CharNextExA (file_name_codepage
, p
, 0);
4888 if (*p
&& *p2
== ':' && *p
>= 'A' && *p
<= 'Z')
4899 p
= CharNextExA (file_name_codepage
, p
, 0);
4900 /* CharNextExA doesn't advance at null character. */
4907 /* Testing for null-terminated LNAME is paranoia:
4908 WideCharToMultiByte should always return a
4909 null-terminated string when its 4th argument is -1
4910 and its 3rd argument is null-terminated (which they
4912 if (lname
[lname_len
- 1] == '\0')
4914 if (lname_len
<= buf_size
)
4915 size_to_copy
= lname_len
;
4916 strncpy (buf
, lname
, size_to_copy
);
4918 retval
= size_to_copy
;
4925 /* CreateFile failed. */
4926 DWORD w32err2
= GetLastError ();
4930 case ERROR_FILE_NOT_FOUND
:
4931 case ERROR_PATH_NOT_FOUND
:
4934 case ERROR_ACCESS_DENIED
:
4935 case ERROR_TOO_MANY_OPEN_FILES
:
4945 restore_privilege (&privs
);
4953 readlinkat (int fd
, char const *name
, char *buffer
,
4956 /* Rely on a hack: an open directory is modeled as file descriptor 0,
4957 as in fstatat. FIXME: Add proper support for readlinkat. */
4958 char fullname
[MAX_PATH
];
4962 if (_snprintf (fullname
, sizeof fullname
, "%s/%s", dir_pathname
, name
)
4965 errno
= ENAMETOOLONG
;
4971 return readlink (name
, buffer
, buffer_size
);
4974 /* If FILE is a symlink, return its target (stored in a static
4975 buffer); otherwise return FILE.
4977 This function repeatedly resolves symlinks in the last component of
4978 a chain of symlink file names, as in foo -> bar -> baz -> ...,
4979 until it arrives at a file whose last component is not a symlink,
4980 or some error occurs. It returns the target of the last
4981 successfully resolved symlink in the chain. If it succeeds to
4982 resolve even a single symlink, the value returned is an absolute
4983 file name with backslashes (result of GetFullPathName). By
4984 contrast, if the original FILE is returned, it is unaltered.
4986 Note: This function can set errno even if it succeeds.
4988 Implementation note: we only resolve the last portion ("basename")
4989 of the argument FILE and of each following file in the chain,
4990 disregarding any possible symlinks in its leading directories.
4991 This is because Windows system calls and library functions
4992 transparently resolve symlinks in leading directories and return
4993 correct information, as long as the basename is not a symlink. */
4995 chase_symlinks (const char *file
)
4997 static char target
[MAX_PATH
];
4998 char link
[MAX_PATH
];
4999 ssize_t res
, link_len
;
5003 if (is_windows_9x () == TRUE
|| !is_symlink (file
))
5004 return (char *)file
;
5006 if ((link_len
= GetFullPathName (file
, MAX_PATH
, link
, NULL
)) == 0)
5007 return (char *)file
;
5009 dbcs_p
= max_filename_mbslen () > 1;
5013 /* Remove trailing slashes, as we want to resolve the last
5014 non-trivial part of the link name. */
5017 while (link_len
> 3 && IS_DIRECTORY_SEP (link
[link_len
-1]))
5018 link
[link_len
--] = '\0';
5020 else if (link_len
> 3)
5022 char *n
= CharPrevExA (file_name_codepage
, link
, link
+ link_len
, 0);
5024 while (n
>= link
+ 2 && IS_DIRECTORY_SEP (*n
))
5027 n
= CharPrevExA (file_name_codepage
, link
, n
, 0);
5031 res
= readlink (link
, target
, MAX_PATH
);
5035 if (!(IS_DEVICE_SEP (target
[1])
5036 || (IS_DIRECTORY_SEP (target
[0]) && IS_DIRECTORY_SEP (target
[1]))))
5038 /* Target is relative. Append it to the directory part of
5039 the symlink, then copy the result back to target. */
5040 char *p
= link
+ link_len
;
5044 while (p
> link
&& !IS_ANY_SEP (p
[-1]))
5049 char *p1
= CharPrevExA (file_name_codepage
, link
, p
, 0);
5051 while (p
> link
&& !IS_ANY_SEP (*p1
))
5054 p1
= CharPrevExA (file_name_codepage
, link
, p1
, 0);
5058 strcpy (target
, link
);
5060 /* Resolve any "." and ".." to get a fully-qualified file name
5062 link_len
= GetFullPathName (target
, MAX_PATH
, link
, NULL
);
5064 } while (res
> 0 && link_len
> 0 && ++loop_count
<= 100);
5066 if (loop_count
> 100)
5069 if (target
[0] == '\0') /* not a single call to readlink succeeded */
5070 return (char *)file
;
5075 /* Posix ACL emulation. */
5078 acl_valid (acl_t acl
)
5080 return is_valid_security_descriptor ((PSECURITY_DESCRIPTOR
)acl
) ? 0 : -1;
5084 acl_to_text (acl_t acl
, ssize_t
*size
)
5087 SECURITY_INFORMATION flags
=
5088 OWNER_SECURITY_INFORMATION
|
5089 GROUP_SECURITY_INFORMATION
|
5090 DACL_SECURITY_INFORMATION
;
5091 char *retval
= NULL
;
5097 if (convert_sd_to_sddl ((PSECURITY_DESCRIPTOR
)acl
, SDDL_REVISION_1
, flags
, &str_acl
, &local_size
))
5100 /* We don't want to mix heaps, so we duplicate the string in our
5101 heap and free the one allocated by the API. */
5102 retval
= xstrdup (str_acl
);
5105 LocalFree (str_acl
);
5107 else if (errno
!= ENOTSUP
)
5114 acl_from_text (const char *acl_str
)
5116 PSECURITY_DESCRIPTOR psd
, retval
= NULL
;
5122 if (convert_sddl_to_sd (acl_str
, SDDL_REVISION_1
, &psd
, &sd_size
))
5125 retval
= xmalloc (sd_size
);
5126 memcpy (retval
, psd
, sd_size
);
5129 else if (errno
!= ENOTSUP
)
5136 acl_free (void *ptr
)
5143 acl_get_file (const char *fname
, acl_type_t type
)
5145 PSECURITY_DESCRIPTOR psd
= NULL
;
5146 const char *filename
;
5148 if (type
== ACL_TYPE_ACCESS
)
5151 SECURITY_INFORMATION si
=
5152 OWNER_SECURITY_INFORMATION
|
5153 GROUP_SECURITY_INFORMATION
|
5154 DACL_SECURITY_INFORMATION
;
5157 filename
= map_w32_filename (fname
, NULL
);
5158 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) != 0)
5159 fname
= chase_symlinks (filename
);
5164 if (!get_file_security (fname
, si
, psd
, 0, &sd_len
)
5165 && errno
!= ENOTSUP
)
5167 err
= GetLastError ();
5168 if (err
== ERROR_INSUFFICIENT_BUFFER
)
5170 psd
= xmalloc (sd_len
);
5171 if (!get_file_security (fname
, si
, psd
, sd_len
, &sd_len
))
5178 else if (err
== ERROR_FILE_NOT_FOUND
5179 || err
== ERROR_PATH_NOT_FOUND
)
5187 else if (type
!= ACL_TYPE_DEFAULT
)
5194 acl_set_file (const char *fname
, acl_type_t type
, acl_t acl
)
5196 TOKEN_PRIVILEGES old1
, old2
;
5198 int st
= 0, retval
= -1;
5199 SECURITY_INFORMATION flags
= 0;
5205 const char *filename
;
5207 if (acl_valid (acl
) != 0
5208 || (type
!= ACL_TYPE_DEFAULT
&& type
!= ACL_TYPE_ACCESS
))
5214 if (type
== ACL_TYPE_DEFAULT
)
5220 filename
= map_w32_filename (fname
, NULL
);
5221 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) != 0)
5222 fname
= chase_symlinks (filename
);
5226 if (get_security_descriptor_owner ((PSECURITY_DESCRIPTOR
)acl
, &psid
, &dflt
)
5228 flags
|= OWNER_SECURITY_INFORMATION
;
5229 if (get_security_descriptor_group ((PSECURITY_DESCRIPTOR
)acl
, &psid
, &dflt
)
5231 flags
|= GROUP_SECURITY_INFORMATION
;
5232 if (get_security_descriptor_dacl ((PSECURITY_DESCRIPTOR
)acl
, &dacl_present
,
5235 flags
|= DACL_SECURITY_INFORMATION
;
5239 /* According to KB-245153, setting the owner will succeed if either:
5240 (1) the caller is the user who will be the new owner, and has the
5241 SE_TAKE_OWNERSHIP privilege, or
5242 (2) the caller has the SE_RESTORE privilege, in which case she can
5243 set any valid user or group as the owner
5245 We request below both SE_TAKE_OWNERSHIP and SE_RESTORE
5246 privileges, and disregard any failures in obtaining them. If
5247 these privileges cannot be obtained, and do not already exist in
5248 the calling thread's security token, this function could fail
5250 if (enable_privilege (SE_TAKE_OWNERSHIP_NAME
, TRUE
, &old1
))
5252 if (enable_privilege (SE_RESTORE_NAME
, TRUE
, &old2
))
5257 if (!set_file_security ((char *)fname
, flags
, (PSECURITY_DESCRIPTOR
)acl
))
5259 err
= GetLastError ();
5261 if (errno
== ENOTSUP
)
5263 else if (err
== ERROR_INVALID_OWNER
5264 || err
== ERROR_NOT_ALL_ASSIGNED
5265 || err
== ERROR_ACCESS_DENIED
)
5267 /* Maybe the requested ACL and the one the file already has
5268 are identical, in which case we can silently ignore the
5269 failure. (And no, Windows doesn't.) */
5270 acl_t current_acl
= acl_get_file (fname
, ACL_TYPE_ACCESS
);
5275 char *acl_from
= acl_to_text (current_acl
, NULL
);
5276 char *acl_to
= acl_to_text (acl
, NULL
);
5278 if (acl_from
&& acl_to
&& xstrcasecmp (acl_from
, acl_to
) == 0)
5284 acl_free (acl_from
);
5287 acl_free (current_acl
);
5290 else if (err
== ERROR_FILE_NOT_FOUND
|| err
== ERROR_PATH_NOT_FOUND
)
5304 restore_privilege (&old2
);
5305 restore_privilege (&old1
);
5313 /* MS-Windows version of careadlinkat (cf. ../lib/careadlinkat.c). We
5314 have a fixed max size for file names, so we don't need the kind of
5315 alloc/malloc/realloc dance the gnulib version does. We also don't
5316 support FD-relative symlinks. */
5318 careadlinkat (int fd
, char const *filename
,
5319 char *buffer
, size_t buffer_size
,
5320 struct allocator
const *alloc
,
5321 ssize_t (*preadlinkat
) (int, char const *, char *, size_t))
5323 char linkname
[MAX_PATH
];
5326 link_size
= preadlinkat (fd
, filename
, linkname
, sizeof(linkname
));
5330 char *retval
= buffer
;
5332 linkname
[link_size
++] = '\0';
5333 if (link_size
> buffer_size
)
5334 retval
= (char *)(alloc
? alloc
->allocate
: xmalloc
) (link_size
);
5336 memcpy (retval
, linkname
, link_size
);
5344 /* Support for browsing other processes and their attributes. See
5345 process.c for the Lisp bindings. */
5347 /* Helper wrapper functions. */
5349 static HANDLE WINAPI
5350 create_toolhelp32_snapshot (DWORD Flags
, DWORD Ignored
)
5352 static CreateToolhelp32Snapshot_Proc s_pfn_Create_Toolhelp32_Snapshot
= NULL
;
5354 if (g_b_init_create_toolhelp32_snapshot
== 0)
5356 g_b_init_create_toolhelp32_snapshot
= 1;
5357 s_pfn_Create_Toolhelp32_Snapshot
= (CreateToolhelp32Snapshot_Proc
)
5358 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5359 "CreateToolhelp32Snapshot");
5361 if (s_pfn_Create_Toolhelp32_Snapshot
== NULL
)
5363 return INVALID_HANDLE_VALUE
;
5365 return (s_pfn_Create_Toolhelp32_Snapshot (Flags
, Ignored
));
5369 process32_first (HANDLE hSnapshot
, LPPROCESSENTRY32 lppe
)
5371 static Process32First_Proc s_pfn_Process32_First
= NULL
;
5373 if (g_b_init_process32_first
== 0)
5375 g_b_init_process32_first
= 1;
5376 s_pfn_Process32_First
= (Process32First_Proc
)
5377 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5380 if (s_pfn_Process32_First
== NULL
)
5384 return (s_pfn_Process32_First (hSnapshot
, lppe
));
5388 process32_next (HANDLE hSnapshot
, LPPROCESSENTRY32 lppe
)
5390 static Process32Next_Proc s_pfn_Process32_Next
= NULL
;
5392 if (g_b_init_process32_next
== 0)
5394 g_b_init_process32_next
= 1;
5395 s_pfn_Process32_Next
= (Process32Next_Proc
)
5396 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5399 if (s_pfn_Process32_Next
== NULL
)
5403 return (s_pfn_Process32_Next (hSnapshot
, lppe
));
5407 open_thread_token (HANDLE ThreadHandle
,
5408 DWORD DesiredAccess
,
5410 PHANDLE TokenHandle
)
5412 static OpenThreadToken_Proc s_pfn_Open_Thread_Token
= NULL
;
5413 HMODULE hm_advapi32
= NULL
;
5414 if (is_windows_9x () == TRUE
)
5416 SetLastError (ERROR_NOT_SUPPORTED
);
5419 if (g_b_init_open_thread_token
== 0)
5421 g_b_init_open_thread_token
= 1;
5422 hm_advapi32
= LoadLibrary ("Advapi32.dll");
5423 s_pfn_Open_Thread_Token
=
5424 (OpenThreadToken_Proc
) GetProcAddress (hm_advapi32
, "OpenThreadToken");
5426 if (s_pfn_Open_Thread_Token
== NULL
)
5428 SetLastError (ERROR_NOT_SUPPORTED
);
5432 s_pfn_Open_Thread_Token (
5441 impersonate_self (SECURITY_IMPERSONATION_LEVEL ImpersonationLevel
)
5443 static ImpersonateSelf_Proc s_pfn_Impersonate_Self
= NULL
;
5444 HMODULE hm_advapi32
= NULL
;
5445 if (is_windows_9x () == TRUE
)
5449 if (g_b_init_impersonate_self
== 0)
5451 g_b_init_impersonate_self
= 1;
5452 hm_advapi32
= LoadLibrary ("Advapi32.dll");
5453 s_pfn_Impersonate_Self
=
5454 (ImpersonateSelf_Proc
) GetProcAddress (hm_advapi32
, "ImpersonateSelf");
5456 if (s_pfn_Impersonate_Self
== NULL
)
5460 return s_pfn_Impersonate_Self (ImpersonationLevel
);
5464 revert_to_self (void)
5466 static RevertToSelf_Proc s_pfn_Revert_To_Self
= NULL
;
5467 HMODULE hm_advapi32
= NULL
;
5468 if (is_windows_9x () == TRUE
)
5472 if (g_b_init_revert_to_self
== 0)
5474 g_b_init_revert_to_self
= 1;
5475 hm_advapi32
= LoadLibrary ("Advapi32.dll");
5476 s_pfn_Revert_To_Self
=
5477 (RevertToSelf_Proc
) GetProcAddress (hm_advapi32
, "RevertToSelf");
5479 if (s_pfn_Revert_To_Self
== NULL
)
5483 return s_pfn_Revert_To_Self ();
5487 get_process_memory_info (HANDLE h_proc
,
5488 PPROCESS_MEMORY_COUNTERS mem_counters
,
5491 static GetProcessMemoryInfo_Proc s_pfn_Get_Process_Memory_Info
= NULL
;
5492 HMODULE hm_psapi
= NULL
;
5493 if (is_windows_9x () == TRUE
)
5497 if (g_b_init_get_process_memory_info
== 0)
5499 g_b_init_get_process_memory_info
= 1;
5500 hm_psapi
= LoadLibrary ("Psapi.dll");
5502 s_pfn_Get_Process_Memory_Info
= (GetProcessMemoryInfo_Proc
)
5503 GetProcAddress (hm_psapi
, "GetProcessMemoryInfo");
5505 if (s_pfn_Get_Process_Memory_Info
== NULL
)
5509 return s_pfn_Get_Process_Memory_Info (h_proc
, mem_counters
, bufsize
);
5513 get_process_working_set_size (HANDLE h_proc
,
5517 static GetProcessWorkingSetSize_Proc
5518 s_pfn_Get_Process_Working_Set_Size
= NULL
;
5520 if (is_windows_9x () == TRUE
)
5524 if (g_b_init_get_process_working_set_size
== 0)
5526 g_b_init_get_process_working_set_size
= 1;
5527 s_pfn_Get_Process_Working_Set_Size
= (GetProcessWorkingSetSize_Proc
)
5528 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5529 "GetProcessWorkingSetSize");
5531 if (s_pfn_Get_Process_Working_Set_Size
== NULL
)
5535 return s_pfn_Get_Process_Working_Set_Size (h_proc
, minrss
, maxrss
);
5539 global_memory_status (MEMORYSTATUS
*buf
)
5541 static GlobalMemoryStatus_Proc s_pfn_Global_Memory_Status
= NULL
;
5543 if (is_windows_9x () == TRUE
)
5547 if (g_b_init_global_memory_status
== 0)
5549 g_b_init_global_memory_status
= 1;
5550 s_pfn_Global_Memory_Status
= (GlobalMemoryStatus_Proc
)
5551 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5552 "GlobalMemoryStatus");
5554 if (s_pfn_Global_Memory_Status
== NULL
)
5558 return s_pfn_Global_Memory_Status (buf
);
5562 global_memory_status_ex (MEMORY_STATUS_EX
*buf
)
5564 static GlobalMemoryStatusEx_Proc s_pfn_Global_Memory_Status_Ex
= NULL
;
5566 if (is_windows_9x () == TRUE
)
5570 if (g_b_init_global_memory_status_ex
== 0)
5572 g_b_init_global_memory_status_ex
= 1;
5573 s_pfn_Global_Memory_Status_Ex
= (GlobalMemoryStatusEx_Proc
)
5574 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5575 "GlobalMemoryStatusEx");
5577 if (s_pfn_Global_Memory_Status_Ex
== NULL
)
5581 return s_pfn_Global_Memory_Status_Ex (buf
);
5585 list_system_processes (void)
5587 struct gcpro gcpro1
;
5588 Lisp_Object proclist
= Qnil
;
5591 h_snapshot
= create_toolhelp32_snapshot (TH32CS_SNAPPROCESS
, 0);
5593 if (h_snapshot
!= INVALID_HANDLE_VALUE
)
5595 PROCESSENTRY32 proc_entry
;
5601 proc_entry
.dwSize
= sizeof (PROCESSENTRY32
);
5602 for (res
= process32_first (h_snapshot
, &proc_entry
); res
;
5603 res
= process32_next (h_snapshot
, &proc_entry
))
5605 proc_id
= proc_entry
.th32ProcessID
;
5606 proclist
= Fcons (make_fixnum_or_float (proc_id
), proclist
);
5609 CloseHandle (h_snapshot
);
5611 proclist
= Fnreverse (proclist
);
5618 enable_privilege (LPCTSTR priv_name
, BOOL enable_p
, TOKEN_PRIVILEGES
*old_priv
)
5620 TOKEN_PRIVILEGES priv
;
5621 DWORD priv_size
= sizeof (priv
);
5622 DWORD opriv_size
= sizeof (*old_priv
);
5623 HANDLE h_token
= NULL
;
5624 HANDLE h_thread
= GetCurrentThread ();
5628 res
= open_thread_token (h_thread
,
5629 TOKEN_QUERY
| TOKEN_ADJUST_PRIVILEGES
,
5631 if (!res
&& GetLastError () == ERROR_NO_TOKEN
)
5633 if (impersonate_self (SecurityImpersonation
))
5634 res
= open_thread_token (h_thread
,
5635 TOKEN_QUERY
| TOKEN_ADJUST_PRIVILEGES
,
5640 priv
.PrivilegeCount
= 1;
5641 priv
.Privileges
[0].Attributes
= enable_p
? SE_PRIVILEGE_ENABLED
: 0;
5642 LookupPrivilegeValue (NULL
, priv_name
, &priv
.Privileges
[0].Luid
);
5643 if (AdjustTokenPrivileges (h_token
, FALSE
, &priv
, priv_size
,
5644 old_priv
, &opriv_size
)
5645 && GetLastError () != ERROR_NOT_ALL_ASSIGNED
)
5649 CloseHandle (h_token
);
5655 restore_privilege (TOKEN_PRIVILEGES
*priv
)
5657 DWORD priv_size
= sizeof (*priv
);
5658 HANDLE h_token
= NULL
;
5661 if (open_thread_token (GetCurrentThread (),
5662 TOKEN_QUERY
| TOKEN_ADJUST_PRIVILEGES
,
5665 if (AdjustTokenPrivileges (h_token
, FALSE
, priv
, priv_size
, NULL
, NULL
)
5666 && GetLastError () != ERROR_NOT_ALL_ASSIGNED
)
5670 CloseHandle (h_token
);
5676 ltime (ULONGLONG time_100ns
)
5678 ULONGLONG time_sec
= time_100ns
/ 10000000;
5679 int subsec
= time_100ns
% 10000000;
5680 return list4i (time_sec
>> 16, time_sec
& 0xffff,
5681 subsec
/ 10, subsec
% 10 * 100000);
5684 #define U64_TO_LISP_TIME(time) ltime (time)
5687 process_times (HANDLE h_proc
, Lisp_Object
*ctime
, Lisp_Object
*etime
,
5688 Lisp_Object
*stime
, Lisp_Object
*utime
, Lisp_Object
*ttime
,
5691 FILETIME ft_creation
, ft_exit
, ft_kernel
, ft_user
, ft_current
;
5692 ULONGLONG tem1
, tem2
, tem3
, tem
;
5695 || !get_process_times_fn
5696 || !(*get_process_times_fn
) (h_proc
, &ft_creation
, &ft_exit
,
5697 &ft_kernel
, &ft_user
))
5700 GetSystemTimeAsFileTime (&ft_current
);
5702 FILETIME_TO_U64 (tem1
, ft_kernel
);
5703 *stime
= U64_TO_LISP_TIME (tem1
);
5705 FILETIME_TO_U64 (tem2
, ft_user
);
5706 *utime
= U64_TO_LISP_TIME (tem2
);
5709 *ttime
= U64_TO_LISP_TIME (tem3
);
5711 FILETIME_TO_U64 (tem
, ft_creation
);
5712 /* Process no 4 (System) returns zero creation time. */
5715 *ctime
= U64_TO_LISP_TIME (tem
);
5719 FILETIME_TO_U64 (tem3
, ft_current
);
5720 tem
= (tem3
- utc_base
) - tem
;
5722 *etime
= U64_TO_LISP_TIME (tem
);
5726 *pcpu
= 100.0 * (tem1
+ tem2
) / tem
;
5737 system_process_attributes (Lisp_Object pid
)
5739 struct gcpro gcpro1
, gcpro2
, gcpro3
;
5740 Lisp_Object attrs
= Qnil
;
5741 Lisp_Object cmd_str
, decoded_cmd
, tem
;
5742 HANDLE h_snapshot
, h_proc
;
5745 char uname
[UNLEN
+1], gname
[GNLEN
+1], domain
[1025];
5746 DWORD ulength
= sizeof (uname
), dlength
= sizeof (domain
), needed
;
5747 DWORD glength
= sizeof (gname
);
5748 HANDLE token
= NULL
;
5749 SID_NAME_USE user_type
;
5750 unsigned char *buf
= NULL
;
5752 TOKEN_USER user_token
;
5753 TOKEN_PRIMARY_GROUP group_token
;
5756 PROCESS_MEMORY_COUNTERS mem
;
5757 PROCESS_MEMORY_COUNTERS_EX mem_ex
;
5758 SIZE_T minrss
, maxrss
;
5760 MEMORY_STATUS_EX memstex
;
5761 double totphys
= 0.0;
5762 Lisp_Object ctime
, stime
, utime
, etime
, ttime
;
5764 BOOL result
= FALSE
;
5766 CHECK_NUMBER_OR_FLOAT (pid
);
5767 proc_id
= FLOATP (pid
) ? XFLOAT_DATA (pid
) : XINT (pid
);
5769 h_snapshot
= create_toolhelp32_snapshot (TH32CS_SNAPPROCESS
, 0);
5771 GCPRO3 (attrs
, decoded_cmd
, tem
);
5773 if (h_snapshot
!= INVALID_HANDLE_VALUE
)
5778 pe
.dwSize
= sizeof (PROCESSENTRY32
);
5779 for (res
= process32_first (h_snapshot
, &pe
); res
;
5780 res
= process32_next (h_snapshot
, &pe
))
5782 if (proc_id
== pe
.th32ProcessID
)
5785 decoded_cmd
= build_string ("Idle");
5788 /* Decode the command name from locale-specific
5790 cmd_str
= build_unibyte_string (pe
.szExeFile
);
5793 code_convert_string_norecord (cmd_str
,
5794 Vlocale_coding_system
, 0);
5796 attrs
= Fcons (Fcons (Qcomm
, decoded_cmd
), attrs
);
5797 attrs
= Fcons (Fcons (Qppid
,
5798 make_fixnum_or_float (pe
.th32ParentProcessID
)),
5800 attrs
= Fcons (Fcons (Qpri
, make_number (pe
.pcPriClassBase
)),
5802 attrs
= Fcons (Fcons (Qthcount
,
5803 make_fixnum_or_float (pe
.cntThreads
)),
5810 CloseHandle (h_snapshot
);
5819 h_proc
= OpenProcess (PROCESS_QUERY_INFORMATION
| PROCESS_VM_READ
,
5821 /* If we were denied a handle to the process, try again after
5822 enabling the SeDebugPrivilege in our process. */
5825 TOKEN_PRIVILEGES priv_current
;
5827 if (enable_privilege (SE_DEBUG_NAME
, TRUE
, &priv_current
))
5829 h_proc
= OpenProcess (PROCESS_QUERY_INFORMATION
| PROCESS_VM_READ
,
5831 restore_privilege (&priv_current
);
5837 result
= open_process_token (h_proc
, TOKEN_QUERY
, &token
);
5840 result
= get_token_information (token
, TokenUser
, NULL
, 0, &blen
);
5841 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
5843 buf
= xmalloc (blen
);
5844 result
= get_token_information (token
, TokenUser
,
5845 (LPVOID
)buf
, blen
, &needed
);
5848 memcpy (&user_token
, buf
, sizeof (user_token
));
5849 if (!w32_cached_id (user_token
.User
.Sid
, &euid
, uname
))
5851 euid
= get_rid (user_token
.User
.Sid
);
5852 result
= lookup_account_sid (NULL
, user_token
.User
.Sid
,
5857 w32_add_to_cache (user_token
.User
.Sid
, euid
, uname
);
5860 strcpy (uname
, "unknown");
5864 ulength
= strlen (uname
);
5870 /* Determine a reasonable euid and gid values. */
5871 if (xstrcasecmp ("administrator", uname
) == 0)
5873 euid
= 500; /* well-known Administrator uid */
5874 egid
= 513; /* well-known None gid */
5878 /* Get group id and name. */
5879 result
= get_token_information (token
, TokenPrimaryGroup
,
5880 (LPVOID
)buf
, blen
, &needed
);
5881 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
5883 buf
= xrealloc (buf
, blen
= needed
);
5884 result
= get_token_information (token
, TokenPrimaryGroup
,
5885 (LPVOID
)buf
, blen
, &needed
);
5889 memcpy (&group_token
, buf
, sizeof (group_token
));
5890 if (!w32_cached_id (group_token
.PrimaryGroup
, &egid
, gname
))
5892 egid
= get_rid (group_token
.PrimaryGroup
);
5893 dlength
= sizeof (domain
);
5895 lookup_account_sid (NULL
, group_token
.PrimaryGroup
,
5896 gname
, &glength
, NULL
, &dlength
,
5899 w32_add_to_cache (group_token
.PrimaryGroup
,
5903 strcpy (gname
, "None");
5907 glength
= strlen (gname
);
5915 if (!is_windows_9x ())
5917 /* We couldn't open the process token, presumably because of
5918 insufficient access rights. Assume this process is run
5920 strcpy (uname
, "SYSTEM");
5921 strcpy (gname
, "None");
5922 euid
= 18; /* SYSTEM */
5923 egid
= 513; /* None */
5924 glength
= strlen (gname
);
5925 ulength
= strlen (uname
);
5927 /* If we are running under Windows 9X, where security calls are
5928 not supported, we assume all processes are run by the current
5930 else if (GetUserName (uname
, &ulength
))
5932 if (xstrcasecmp ("administrator", uname
) == 0)
5937 strcpy (gname
, "None");
5938 glength
= strlen (gname
);
5939 ulength
= strlen (uname
);
5945 strcpy (uname
, "administrator");
5946 ulength
= strlen (uname
);
5947 strcpy (gname
, "None");
5948 glength
= strlen (gname
);
5951 CloseHandle (token
);
5954 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (euid
)), attrs
);
5955 tem
= make_unibyte_string (uname
, ulength
);
5956 attrs
= Fcons (Fcons (Quser
,
5957 code_convert_string_norecord (tem
, Vlocale_coding_system
, 0)),
5959 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (egid
)), attrs
);
5960 tem
= make_unibyte_string (gname
, glength
);
5961 attrs
= Fcons (Fcons (Qgroup
,
5962 code_convert_string_norecord (tem
, Vlocale_coding_system
, 0)),
5965 if (global_memory_status_ex (&memstex
))
5966 #if __GNUC__ || (defined (_MSC_VER) && _MSC_VER >= 1300)
5967 totphys
= memstex
.ullTotalPhys
/ 1024.0;
5969 /* Visual Studio 6 cannot convert an unsigned __int64 type to
5970 double, so we need to do this for it... */
5972 DWORD tot_hi
= memstex
.ullTotalPhys
>> 32;
5973 DWORD tot_md
= (memstex
.ullTotalPhys
& 0x00000000ffffffff) >> 10;
5974 DWORD tot_lo
= memstex
.ullTotalPhys
% 1024;
5976 totphys
= tot_hi
* 4194304.0 + tot_md
+ tot_lo
/ 1024.0;
5978 #endif /* __GNUC__ || _MSC_VER >= 1300 */
5979 else if (global_memory_status (&memst
))
5980 totphys
= memst
.dwTotalPhys
/ 1024.0;
5983 && get_process_memory_info (h_proc
, (PROCESS_MEMORY_COUNTERS
*)&mem_ex
,
5986 SIZE_T rss
= mem_ex
.WorkingSetSize
/ 1024;
5988 attrs
= Fcons (Fcons (Qmajflt
,
5989 make_fixnum_or_float (mem_ex
.PageFaultCount
)),
5991 attrs
= Fcons (Fcons (Qvsize
,
5992 make_fixnum_or_float (mem_ex
.PrivateUsage
/ 1024)),
5994 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (rss
)), attrs
);
5996 attrs
= Fcons (Fcons (Qpmem
, make_float (100. * rss
/ totphys
)), attrs
);
5999 && get_process_memory_info (h_proc
, &mem
, sizeof (mem
)))
6001 SIZE_T rss
= mem_ex
.WorkingSetSize
/ 1024;
6003 attrs
= Fcons (Fcons (Qmajflt
,
6004 make_fixnum_or_float (mem
.PageFaultCount
)),
6006 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (rss
)), attrs
);
6008 attrs
= Fcons (Fcons (Qpmem
, make_float (100. * rss
/ totphys
)), attrs
);
6011 && get_process_working_set_size (h_proc
, &minrss
, &maxrss
))
6013 DWORD rss
= maxrss
/ 1024;
6015 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (maxrss
/ 1024)), attrs
);
6017 attrs
= Fcons (Fcons (Qpmem
, make_float (100. * rss
/ totphys
)), attrs
);
6020 if (process_times (h_proc
, &ctime
, &etime
, &stime
, &utime
, &ttime
, &pcpu
))
6022 attrs
= Fcons (Fcons (Qutime
, utime
), attrs
);
6023 attrs
= Fcons (Fcons (Qstime
, stime
), attrs
);
6024 attrs
= Fcons (Fcons (Qtime
, ttime
), attrs
);
6025 attrs
= Fcons (Fcons (Qstart
, ctime
), attrs
);
6026 attrs
= Fcons (Fcons (Qetime
, etime
), attrs
);
6027 attrs
= Fcons (Fcons (Qpcpu
, make_float (pcpu
)), attrs
);
6030 /* FIXME: Retrieve command line by walking the PEB of the process. */
6033 CloseHandle (h_proc
);
6039 /* Wrappers for winsock functions to map between our file descriptors
6040 and winsock's handles; also set h_errno for convenience.
6042 To allow Emacs to run on systems which don't have winsock support
6043 installed, we dynamically link to winsock on startup if present, and
6044 otherwise provide the minimum necessary functionality
6045 (eg. gethostname). */
6047 /* function pointers for relevant socket functions */
6048 int (PASCAL
*pfn_WSAStartup
) (WORD wVersionRequired
, LPWSADATA lpWSAData
);
6049 void (PASCAL
*pfn_WSASetLastError
) (int iError
);
6050 int (PASCAL
*pfn_WSAGetLastError
) (void);
6051 int (PASCAL
*pfn_WSAEventSelect
) (SOCKET s
, HANDLE hEventObject
, long lNetworkEvents
);
6052 HANDLE (PASCAL
*pfn_WSACreateEvent
) (void);
6053 int (PASCAL
*pfn_WSACloseEvent
) (HANDLE hEvent
);
6054 int (PASCAL
*pfn_socket
) (int af
, int type
, int protocol
);
6055 int (PASCAL
*pfn_bind
) (SOCKET s
, const struct sockaddr
*addr
, int namelen
);
6056 int (PASCAL
*pfn_connect
) (SOCKET s
, const struct sockaddr
*addr
, int namelen
);
6057 int (PASCAL
*pfn_ioctlsocket
) (SOCKET s
, long cmd
, u_long
*argp
);
6058 int (PASCAL
*pfn_recv
) (SOCKET s
, char * buf
, int len
, int flags
);
6059 int (PASCAL
*pfn_send
) (SOCKET s
, const char * buf
, int len
, int flags
);
6060 int (PASCAL
*pfn_closesocket
) (SOCKET s
);
6061 int (PASCAL
*pfn_shutdown
) (SOCKET s
, int how
);
6062 int (PASCAL
*pfn_WSACleanup
) (void);
6064 u_short (PASCAL
*pfn_htons
) (u_short hostshort
);
6065 u_short (PASCAL
*pfn_ntohs
) (u_short netshort
);
6066 unsigned long (PASCAL
*pfn_inet_addr
) (const char * cp
);
6067 int (PASCAL
*pfn_gethostname
) (char * name
, int namelen
);
6068 struct hostent
* (PASCAL
*pfn_gethostbyname
) (const char * name
);
6069 struct servent
* (PASCAL
*pfn_getservbyname
) (const char * name
, const char * proto
);
6070 int (PASCAL
*pfn_getpeername
) (SOCKET s
, struct sockaddr
*addr
, int * namelen
);
6071 int (PASCAL
*pfn_setsockopt
) (SOCKET s
, int level
, int optname
,
6072 const char * optval
, int optlen
);
6073 int (PASCAL
*pfn_listen
) (SOCKET s
, int backlog
);
6074 int (PASCAL
*pfn_getsockname
) (SOCKET s
, struct sockaddr
* name
,
6076 SOCKET (PASCAL
*pfn_accept
) (SOCKET s
, struct sockaddr
* addr
, int * addrlen
);
6077 int (PASCAL
*pfn_recvfrom
) (SOCKET s
, char * buf
, int len
, int flags
,
6078 struct sockaddr
* from
, int * fromlen
);
6079 int (PASCAL
*pfn_sendto
) (SOCKET s
, const char * buf
, int len
, int flags
,
6080 const struct sockaddr
* to
, int tolen
);
6082 /* SetHandleInformation is only needed to make sockets non-inheritable. */
6083 BOOL (WINAPI
*pfn_SetHandleInformation
) (HANDLE object
, DWORD mask
, DWORD flags
);
6084 #ifndef HANDLE_FLAG_INHERIT
6085 #define HANDLE_FLAG_INHERIT 1
6089 static int winsock_inuse
;
6094 if (winsock_lib
!= NULL
&& winsock_inuse
== 0)
6096 /* Not sure what would cause WSAENETDOWN, or even if it can happen
6097 after WSAStartup returns successfully, but it seems reasonable
6098 to allow unloading winsock anyway in that case. */
6099 if (pfn_WSACleanup () == 0 ||
6100 pfn_WSAGetLastError () == WSAENETDOWN
)
6102 if (FreeLibrary (winsock_lib
))
6111 init_winsock (int load_now
)
6113 WSADATA winsockData
;
6115 if (winsock_lib
!= NULL
)
6118 pfn_SetHandleInformation
6119 = (void *) GetProcAddress (GetModuleHandle ("kernel32.dll"),
6120 "SetHandleInformation");
6122 winsock_lib
= LoadLibrary ("Ws2_32.dll");
6124 if (winsock_lib
!= NULL
)
6126 /* dynamically link to socket functions */
6128 #define LOAD_PROC(fn) \
6129 if ((pfn_##fn = (void *) GetProcAddress (winsock_lib, #fn)) == NULL) \
6132 LOAD_PROC (WSAStartup
);
6133 LOAD_PROC (WSASetLastError
);
6134 LOAD_PROC (WSAGetLastError
);
6135 LOAD_PROC (WSAEventSelect
);
6136 LOAD_PROC (WSACreateEvent
);
6137 LOAD_PROC (WSACloseEvent
);
6140 LOAD_PROC (connect
);
6141 LOAD_PROC (ioctlsocket
);
6144 LOAD_PROC (closesocket
);
6145 LOAD_PROC (shutdown
);
6148 LOAD_PROC (inet_addr
);
6149 LOAD_PROC (gethostname
);
6150 LOAD_PROC (gethostbyname
);
6151 LOAD_PROC (getservbyname
);
6152 LOAD_PROC (getpeername
);
6153 LOAD_PROC (WSACleanup
);
6154 LOAD_PROC (setsockopt
);
6156 LOAD_PROC (getsockname
);
6158 LOAD_PROC (recvfrom
);
6162 /* specify version 1.1 of winsock */
6163 if (pfn_WSAStartup (0x101, &winsockData
) == 0)
6165 if (winsockData
.wVersion
!= 0x101)
6170 /* Report that winsock exists and is usable, but leave
6171 socket functions disabled. I am assuming that calling
6172 WSAStartup does not require any network interaction,
6173 and in particular does not cause or require a dial-up
6174 connection to be established. */
6177 FreeLibrary (winsock_lib
);
6185 FreeLibrary (winsock_lib
);
6195 /* Function to map winsock error codes to errno codes for those errno
6196 code defined in errno.h (errno values not defined by errno.h are
6197 already in nt/inc/sys/socket.h). */
6204 if (winsock_lib
== NULL
)
6207 wsa_err
= pfn_WSAGetLastError ();
6211 case WSAEACCES
: errno
= EACCES
; break;
6212 case WSAEBADF
: errno
= EBADF
; break;
6213 case WSAEFAULT
: errno
= EFAULT
; break;
6214 case WSAEINTR
: errno
= EINTR
; break;
6215 case WSAEINVAL
: errno
= EINVAL
; break;
6216 case WSAEMFILE
: errno
= EMFILE
; break;
6217 case WSAENAMETOOLONG
: errno
= ENAMETOOLONG
; break;
6218 case WSAENOTEMPTY
: errno
= ENOTEMPTY
; break;
6219 default: errno
= wsa_err
; break;
6227 if (winsock_lib
!= NULL
)
6228 pfn_WSASetLastError (0);
6231 /* Extend strerror to handle the winsock-specific error codes. */
6235 } _wsa_errlist
[] = {
6236 {WSAEINTR
, "Interrupted function call"},
6237 {WSAEBADF
, "Bad file descriptor"},
6238 {WSAEACCES
, "Permission denied"},
6239 {WSAEFAULT
, "Bad address"},
6240 {WSAEINVAL
, "Invalid argument"},
6241 {WSAEMFILE
, "Too many open files"},
6243 {WSAEWOULDBLOCK
, "Resource temporarily unavailable"},
6244 {WSAEINPROGRESS
, "Operation now in progress"},
6245 {WSAEALREADY
, "Operation already in progress"},
6246 {WSAENOTSOCK
, "Socket operation on non-socket"},
6247 {WSAEDESTADDRREQ
, "Destination address required"},
6248 {WSAEMSGSIZE
, "Message too long"},
6249 {WSAEPROTOTYPE
, "Protocol wrong type for socket"},
6250 {WSAENOPROTOOPT
, "Bad protocol option"},
6251 {WSAEPROTONOSUPPORT
, "Protocol not supported"},
6252 {WSAESOCKTNOSUPPORT
, "Socket type not supported"},
6253 {WSAEOPNOTSUPP
, "Operation not supported"},
6254 {WSAEPFNOSUPPORT
, "Protocol family not supported"},
6255 {WSAEAFNOSUPPORT
, "Address family not supported by protocol family"},
6256 {WSAEADDRINUSE
, "Address already in use"},
6257 {WSAEADDRNOTAVAIL
, "Cannot assign requested address"},
6258 {WSAENETDOWN
, "Network is down"},
6259 {WSAENETUNREACH
, "Network is unreachable"},
6260 {WSAENETRESET
, "Network dropped connection on reset"},
6261 {WSAECONNABORTED
, "Software caused connection abort"},
6262 {WSAECONNRESET
, "Connection reset by peer"},
6263 {WSAENOBUFS
, "No buffer space available"},
6264 {WSAEISCONN
, "Socket is already connected"},
6265 {WSAENOTCONN
, "Socket is not connected"},
6266 {WSAESHUTDOWN
, "Cannot send after socket shutdown"},
6267 {WSAETOOMANYREFS
, "Too many references"}, /* not sure */
6268 {WSAETIMEDOUT
, "Connection timed out"},
6269 {WSAECONNREFUSED
, "Connection refused"},
6270 {WSAELOOP
, "Network loop"}, /* not sure */
6271 {WSAENAMETOOLONG
, "Name is too long"},
6272 {WSAEHOSTDOWN
, "Host is down"},
6273 {WSAEHOSTUNREACH
, "No route to host"},
6274 {WSAENOTEMPTY
, "Buffer not empty"}, /* not sure */
6275 {WSAEPROCLIM
, "Too many processes"},
6276 {WSAEUSERS
, "Too many users"}, /* not sure */
6277 {WSAEDQUOT
, "Double quote in host name"}, /* really not sure */
6278 {WSAESTALE
, "Data is stale"}, /* not sure */
6279 {WSAEREMOTE
, "Remote error"}, /* not sure */
6281 {WSASYSNOTREADY
, "Network subsystem is unavailable"},
6282 {WSAVERNOTSUPPORTED
, "WINSOCK.DLL version out of range"},
6283 {WSANOTINITIALISED
, "Winsock not initialized successfully"},
6284 {WSAEDISCON
, "Graceful shutdown in progress"},
6286 {WSAENOMORE
, "No more operations allowed"}, /* not sure */
6287 {WSAECANCELLED
, "Operation cancelled"}, /* not sure */
6288 {WSAEINVALIDPROCTABLE
, "Invalid procedure table from service provider"},
6289 {WSAEINVALIDPROVIDER
, "Invalid service provider version number"},
6290 {WSAEPROVIDERFAILEDINIT
, "Unable to initialize a service provider"},
6291 {WSASYSCALLFAILURE
, "System call failure"},
6292 {WSASERVICE_NOT_FOUND
, "Service not found"}, /* not sure */
6293 {WSATYPE_NOT_FOUND
, "Class type not found"},
6294 {WSA_E_NO_MORE
, "No more resources available"}, /* really not sure */
6295 {WSA_E_CANCELLED
, "Operation already cancelled"}, /* really not sure */
6296 {WSAEREFUSED
, "Operation refused"}, /* not sure */
6299 {WSAHOST_NOT_FOUND
, "Host not found"},
6300 {WSATRY_AGAIN
, "Authoritative host not found during name lookup"},
6301 {WSANO_RECOVERY
, "Non-recoverable error during name lookup"},
6302 {WSANO_DATA
, "Valid name, no data record of requested type"},
6308 sys_strerror (int error_no
)
6311 static char unknown_msg
[40];
6313 if (error_no
>= 0 && error_no
< sys_nerr
)
6314 return sys_errlist
[error_no
];
6316 for (i
= 0; _wsa_errlist
[i
].errnum
>= 0; i
++)
6317 if (_wsa_errlist
[i
].errnum
== error_no
)
6318 return _wsa_errlist
[i
].msg
;
6320 sprintf (unknown_msg
, "Unidentified error: %d", error_no
);
6324 /* [andrewi 3-May-96] I've had conflicting results using both methods,
6325 but I believe the method of keeping the socket handle separate (and
6326 insuring it is not inheritable) is the correct one. */
6328 #define SOCK_HANDLE(fd) ((SOCKET) fd_info[fd].hnd)
6330 static int socket_to_fd (SOCKET s
);
6333 sys_socket (int af
, int type
, int protocol
)
6337 if (winsock_lib
== NULL
)
6340 return INVALID_SOCKET
;
6345 /* call the real socket function */
6346 s
= pfn_socket (af
, type
, protocol
);
6348 if (s
!= INVALID_SOCKET
)
6349 return socket_to_fd (s
);
6355 /* Convert a SOCKET to a file descriptor. */
6357 socket_to_fd (SOCKET s
)
6362 /* Although under NT 3.5 _open_osfhandle will accept a socket
6363 handle, if opened with SO_OPENTYPE == SO_SYNCHRONOUS_NONALERT,
6364 that does not work under NT 3.1. However, we can get the same
6365 effect by using a backdoor function to replace an existing
6366 descriptor handle with the one we want. */
6368 /* allocate a file descriptor (with appropriate flags) */
6369 fd
= _open ("NUL:", _O_RDWR
);
6372 /* Make a non-inheritable copy of the socket handle. Note
6373 that it is possible that sockets aren't actually kernel
6374 handles, which appears to be the case on Windows 9x when
6375 the MS Proxy winsock client is installed. */
6377 /* Apparently there is a bug in NT 3.51 with some service
6378 packs, which prevents using DuplicateHandle to make a
6379 socket handle non-inheritable (causes WSACleanup to
6380 hang). The work-around is to use SetHandleInformation
6381 instead if it is available and implemented. */
6382 if (pfn_SetHandleInformation
)
6384 pfn_SetHandleInformation ((HANDLE
) s
, HANDLE_FLAG_INHERIT
, 0);
6388 HANDLE parent
= GetCurrentProcess ();
6389 HANDLE new_s
= INVALID_HANDLE_VALUE
;
6391 if (DuplicateHandle (parent
,
6397 DUPLICATE_SAME_ACCESS
))
6399 /* It is possible that DuplicateHandle succeeds even
6400 though the socket wasn't really a kernel handle,
6401 because a real handle has the same value. So
6402 test whether the new handle really is a socket. */
6403 long nonblocking
= 0;
6404 if (pfn_ioctlsocket ((SOCKET
) new_s
, FIONBIO
, &nonblocking
) == 0)
6406 pfn_closesocket (s
);
6411 CloseHandle (new_s
);
6416 eassert (fd
< MAXDESC
);
6417 fd_info
[fd
].hnd
= (HANDLE
) s
;
6419 /* set our own internal flags */
6420 fd_info
[fd
].flags
= FILE_SOCKET
| FILE_BINARY
| FILE_READ
| FILE_WRITE
;
6426 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
6428 /* attach child_process to fd_info */
6429 if (fd_info
[ fd
].cp
!= NULL
)
6431 DebPrint (("sys_socket: fd_info[%d] apparently in use!\n", fd
));
6435 fd_info
[ fd
].cp
= cp
;
6438 winsock_inuse
++; /* count open sockets */
6446 pfn_closesocket (s
);
6452 sys_bind (int s
, const struct sockaddr
* addr
, int namelen
)
6454 if (winsock_lib
== NULL
)
6457 return SOCKET_ERROR
;
6461 if (fd_info
[s
].flags
& FILE_SOCKET
)
6463 int rc
= pfn_bind (SOCK_HANDLE (s
), addr
, namelen
);
6464 if (rc
== SOCKET_ERROR
)
6469 return SOCKET_ERROR
;
6473 sys_connect (int s
, const struct sockaddr
* name
, int namelen
)
6475 if (winsock_lib
== NULL
)
6478 return SOCKET_ERROR
;
6482 if (fd_info
[s
].flags
& FILE_SOCKET
)
6484 int rc
= pfn_connect (SOCK_HANDLE (s
), name
, namelen
);
6485 if (rc
== SOCKET_ERROR
)
6490 return SOCKET_ERROR
;
6494 sys_htons (u_short hostshort
)
6496 return (winsock_lib
!= NULL
) ?
6497 pfn_htons (hostshort
) : hostshort
;
6501 sys_ntohs (u_short netshort
)
6503 return (winsock_lib
!= NULL
) ?
6504 pfn_ntohs (netshort
) : netshort
;
6508 sys_inet_addr (const char * cp
)
6510 return (winsock_lib
!= NULL
) ?
6511 pfn_inet_addr (cp
) : INADDR_NONE
;
6515 sys_gethostname (char * name
, int namelen
)
6517 if (winsock_lib
!= NULL
)
6522 retval
= pfn_gethostname (name
, namelen
);
6523 if (retval
== SOCKET_ERROR
)
6528 if (namelen
> MAX_COMPUTERNAME_LENGTH
)
6529 return !GetComputerName (name
, (DWORD
*)&namelen
);
6532 return SOCKET_ERROR
;
6536 sys_gethostbyname (const char * name
)
6538 struct hostent
* host
;
6539 int h_err
= h_errno
;
6541 if (winsock_lib
== NULL
)
6543 h_errno
= NO_RECOVERY
;
6549 host
= pfn_gethostbyname (name
);
6561 sys_getservbyname (const char * name
, const char * proto
)
6563 struct servent
* serv
;
6565 if (winsock_lib
== NULL
)
6572 serv
= pfn_getservbyname (name
, proto
);
6579 sys_getpeername (int s
, struct sockaddr
*addr
, int * namelen
)
6581 if (winsock_lib
== NULL
)
6584 return SOCKET_ERROR
;
6588 if (fd_info
[s
].flags
& FILE_SOCKET
)
6590 int rc
= pfn_getpeername (SOCK_HANDLE (s
), addr
, namelen
);
6591 if (rc
== SOCKET_ERROR
)
6596 return SOCKET_ERROR
;
6600 sys_shutdown (int s
, int how
)
6602 if (winsock_lib
== NULL
)
6605 return SOCKET_ERROR
;
6609 if (fd_info
[s
].flags
& FILE_SOCKET
)
6611 int rc
= pfn_shutdown (SOCK_HANDLE (s
), how
);
6612 if (rc
== SOCKET_ERROR
)
6617 return SOCKET_ERROR
;
6621 sys_setsockopt (int s
, int level
, int optname
, const void * optval
, int optlen
)
6623 if (winsock_lib
== NULL
)
6626 return SOCKET_ERROR
;
6630 if (fd_info
[s
].flags
& FILE_SOCKET
)
6632 int rc
= pfn_setsockopt (SOCK_HANDLE (s
), level
, optname
,
6633 (const char *)optval
, optlen
);
6634 if (rc
== SOCKET_ERROR
)
6639 return SOCKET_ERROR
;
6643 sys_listen (int s
, int backlog
)
6645 if (winsock_lib
== NULL
)
6648 return SOCKET_ERROR
;
6652 if (fd_info
[s
].flags
& FILE_SOCKET
)
6654 int rc
= pfn_listen (SOCK_HANDLE (s
), backlog
);
6655 if (rc
== SOCKET_ERROR
)
6658 fd_info
[s
].flags
|= FILE_LISTEN
;
6662 return SOCKET_ERROR
;
6666 sys_getsockname (int s
, struct sockaddr
* name
, int * namelen
)
6668 if (winsock_lib
== NULL
)
6671 return SOCKET_ERROR
;
6675 if (fd_info
[s
].flags
& FILE_SOCKET
)
6677 int rc
= pfn_getsockname (SOCK_HANDLE (s
), name
, namelen
);
6678 if (rc
== SOCKET_ERROR
)
6683 return SOCKET_ERROR
;
6687 sys_accept (int s
, struct sockaddr
* addr
, int * addrlen
)
6689 if (winsock_lib
== NULL
)
6696 if (fd_info
[s
].flags
& FILE_LISTEN
)
6698 SOCKET t
= pfn_accept (SOCK_HANDLE (s
), addr
, addrlen
);
6700 if (t
== INVALID_SOCKET
)
6703 fd
= socket_to_fd (t
);
6707 fd_info
[s
].cp
->status
= STATUS_READ_ACKNOWLEDGED
;
6708 ResetEvent (fd_info
[s
].cp
->char_avail
);
6717 sys_recvfrom (int s
, char * buf
, int len
, int flags
,
6718 struct sockaddr
* from
, int * fromlen
)
6720 if (winsock_lib
== NULL
)
6723 return SOCKET_ERROR
;
6727 if (fd_info
[s
].flags
& FILE_SOCKET
)
6729 int rc
= pfn_recvfrom (SOCK_HANDLE (s
), buf
, len
, flags
, from
, fromlen
);
6730 if (rc
== SOCKET_ERROR
)
6735 return SOCKET_ERROR
;
6739 sys_sendto (int s
, const char * buf
, int len
, int flags
,
6740 const struct sockaddr
* to
, int tolen
)
6742 if (winsock_lib
== NULL
)
6745 return SOCKET_ERROR
;
6749 if (fd_info
[s
].flags
& FILE_SOCKET
)
6751 int rc
= pfn_sendto (SOCK_HANDLE (s
), buf
, len
, flags
, to
, tolen
);
6752 if (rc
== SOCKET_ERROR
)
6757 return SOCKET_ERROR
;
6760 /* Windows does not have an fcntl function. Provide an implementation
6761 good enough for Emacs. */
6763 fcntl (int s
, int cmd
, int options
)
6765 /* In the w32 Emacs port, fcntl (fd, F_DUPFD_CLOEXEC, fd1) is always
6766 invoked in a context where fd1 is closed and all descriptors less
6767 than fd1 are open, so sys_dup is an adequate implementation. */
6768 if (cmd
== F_DUPFD_CLOEXEC
)
6771 if (winsock_lib
== NULL
)
6778 if (fd_info
[s
].flags
& FILE_SOCKET
)
6780 if (cmd
== F_SETFL
&& options
== O_NONBLOCK
)
6782 unsigned long nblock
= 1;
6783 int rc
= pfn_ioctlsocket (SOCK_HANDLE (s
), FIONBIO
, &nblock
);
6784 if (rc
== SOCKET_ERROR
)
6786 /* Keep track of the fact that we set this to non-blocking. */
6787 fd_info
[s
].flags
|= FILE_NDELAY
;
6793 return SOCKET_ERROR
;
6797 return SOCKET_ERROR
;
6801 /* Shadow main io functions: we need to handle pipes and sockets more
6802 intelligently, and implement non-blocking mode as well. */
6815 if (fd
< MAXDESC
&& fd_info
[fd
].cp
)
6817 child_process
* cp
= fd_info
[fd
].cp
;
6819 fd_info
[fd
].cp
= NULL
;
6821 if (CHILD_ACTIVE (cp
))
6823 /* if last descriptor to active child_process then cleanup */
6825 for (i
= 0; i
< MAXDESC
; i
++)
6829 if (fd_info
[i
].cp
== cp
)
6834 if (fd_info
[fd
].flags
& FILE_SOCKET
)
6836 if (winsock_lib
== NULL
) emacs_abort ();
6838 pfn_shutdown (SOCK_HANDLE (fd
), 2);
6839 rc
= pfn_closesocket (SOCK_HANDLE (fd
));
6841 winsock_inuse
--; /* count open sockets */
6843 /* If the process handle is NULL, it's either a socket
6844 or serial connection, or a subprocess that was
6845 already reaped by reap_subprocess, but whose
6846 resources were not yet freed, because its output was
6847 not fully read yet by the time it was reaped. (This
6848 usually happens with async subprocesses whose output
6849 is being read by Emacs.) Otherwise, this process was
6850 not reaped yet, so we set its FD to a negative value
6851 to make sure sys_select will eventually get to
6852 calling the SIGCHLD handler for it, which will then
6853 invoke waitpid and reap_subprocess. */
6854 if (cp
->procinfo
.hProcess
== NULL
)
6862 if (fd
>= 0 && fd
< MAXDESC
)
6863 fd_info
[fd
].flags
= 0;
6865 /* Note that sockets do not need special treatment here (at least on
6866 NT and Windows 95 using the standard tcp/ip stacks) - it appears that
6867 closesocket is equivalent to CloseHandle, which is to be expected
6868 because socket handles are fully fledged kernel handles. */
6880 if (new_fd
>= 0 && new_fd
< MAXDESC
)
6882 /* duplicate our internal info as well */
6883 fd_info
[new_fd
] = fd_info
[fd
];
6889 sys_dup2 (int src
, int dst
)
6893 if (dst
< 0 || dst
>= MAXDESC
)
6899 /* make sure we close the destination first if it's a pipe or socket */
6900 if (src
!= dst
&& fd_info
[dst
].flags
!= 0)
6903 rc
= _dup2 (src
, dst
);
6906 /* duplicate our internal info as well */
6907 fd_info
[dst
] = fd_info
[src
];
6913 pipe2 (int * phandles
, int pipe2_flags
)
6918 eassert (pipe2_flags
== O_CLOEXEC
);
6920 /* make pipe handles non-inheritable; when we spawn a child, we
6921 replace the relevant handle with an inheritable one. Also put
6922 pipes into binary mode; we will do text mode translation ourselves
6924 rc
= _pipe (phandles
, 0, _O_NOINHERIT
| _O_BINARY
);
6928 /* Protect against overflow, since Windows can open more handles than
6929 our fd_info array has room for. */
6930 if (phandles
[0] >= MAXDESC
|| phandles
[1] >= MAXDESC
)
6932 _close (phandles
[0]);
6933 _close (phandles
[1]);
6939 flags
= FILE_PIPE
| FILE_READ
| FILE_BINARY
;
6940 fd_info
[phandles
[0]].flags
= flags
;
6942 flags
= FILE_PIPE
| FILE_WRITE
| FILE_BINARY
;
6943 fd_info
[phandles
[1]].flags
= flags
;
6950 /* Function to do blocking read of one byte, needed to implement
6951 select. It is only allowed on communication ports, sockets, or
6954 _sys_read_ahead (int fd
)
6959 if (fd
< 0 || fd
>= MAXDESC
)
6960 return STATUS_READ_ERROR
;
6962 cp
= fd_info
[fd
].cp
;
6964 if (cp
== NULL
|| cp
->fd
!= fd
|| cp
->status
!= STATUS_READ_READY
)
6965 return STATUS_READ_ERROR
;
6967 if ((fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SERIAL
| FILE_SOCKET
)) == 0
6968 || (fd_info
[fd
].flags
& FILE_READ
) == 0)
6970 DebPrint (("_sys_read_ahead: internal error: fd %d is not a pipe, serial port, or socket!\n", fd
));
6974 cp
->status
= STATUS_READ_IN_PROGRESS
;
6976 if (fd_info
[fd
].flags
& FILE_PIPE
)
6978 rc
= _read (fd
, &cp
->chr
, sizeof (char));
6980 /* Give subprocess time to buffer some more output for us before
6981 reporting that input is available; we need this because Windows 95
6982 connects DOS programs to pipes by making the pipe appear to be
6983 the normal console stdout - as a result most DOS programs will
6984 write to stdout without buffering, ie. one character at a
6985 time. Even some W32 programs do this - "dir" in a command
6986 shell on NT is very slow if we don't do this. */
6989 int wait
= w32_pipe_read_delay
;
6995 /* Yield remainder of our time slice, effectively giving a
6996 temporary priority boost to the child process. */
7000 else if (fd_info
[fd
].flags
& FILE_SERIAL
)
7002 HANDLE hnd
= fd_info
[fd
].hnd
;
7003 OVERLAPPED
*ovl
= &fd_info
[fd
].cp
->ovl_read
;
7006 /* Configure timeouts for blocking read. */
7007 if (!GetCommTimeouts (hnd
, &ct
))
7009 cp
->status
= STATUS_READ_ERROR
;
7010 return STATUS_READ_ERROR
;
7012 ct
.ReadIntervalTimeout
= 0;
7013 ct
.ReadTotalTimeoutMultiplier
= 0;
7014 ct
.ReadTotalTimeoutConstant
= 0;
7015 if (!SetCommTimeouts (hnd
, &ct
))
7017 cp
->status
= STATUS_READ_ERROR
;
7018 return STATUS_READ_ERROR
;
7021 if (!ReadFile (hnd
, &cp
->chr
, sizeof (char), (DWORD
*) &rc
, ovl
))
7023 if (GetLastError () != ERROR_IO_PENDING
)
7025 cp
->status
= STATUS_READ_ERROR
;
7026 return STATUS_READ_ERROR
;
7028 if (!GetOverlappedResult (hnd
, ovl
, (DWORD
*) &rc
, TRUE
))
7030 cp
->status
= STATUS_READ_ERROR
;
7031 return STATUS_READ_ERROR
;
7035 else if (fd_info
[fd
].flags
& FILE_SOCKET
)
7037 unsigned long nblock
= 0;
7038 /* We always want this to block, so temporarily disable NDELAY. */
7039 if (fd_info
[fd
].flags
& FILE_NDELAY
)
7040 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
7042 rc
= pfn_recv (SOCK_HANDLE (fd
), &cp
->chr
, sizeof (char), 0);
7044 if (fd_info
[fd
].flags
& FILE_NDELAY
)
7047 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
7051 if (rc
== sizeof (char))
7052 cp
->status
= STATUS_READ_SUCCEEDED
;
7054 cp
->status
= STATUS_READ_FAILED
;
7060 _sys_wait_accept (int fd
)
7066 if (fd
< 0 || fd
>= MAXDESC
)
7067 return STATUS_READ_ERROR
;
7069 cp
= fd_info
[fd
].cp
;
7071 if (cp
== NULL
|| cp
->fd
!= fd
|| cp
->status
!= STATUS_READ_READY
)
7072 return STATUS_READ_ERROR
;
7074 cp
->status
= STATUS_READ_FAILED
;
7076 hEv
= pfn_WSACreateEvent ();
7077 rc
= pfn_WSAEventSelect (SOCK_HANDLE (fd
), hEv
, FD_ACCEPT
);
7078 if (rc
!= SOCKET_ERROR
)
7080 rc
= WaitForSingleObject (hEv
, INFINITE
);
7081 pfn_WSAEventSelect (SOCK_HANDLE (fd
), NULL
, 0);
7082 if (rc
== WAIT_OBJECT_0
)
7083 cp
->status
= STATUS_READ_SUCCEEDED
;
7085 pfn_WSACloseEvent (hEv
);
7091 sys_read (int fd
, char * buffer
, unsigned int count
)
7096 char * orig_buffer
= buffer
;
7104 if (fd
< MAXDESC
&& fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
| FILE_SERIAL
))
7106 child_process
*cp
= fd_info
[fd
].cp
;
7108 if ((fd_info
[fd
].flags
& FILE_READ
) == 0)
7116 /* re-read CR carried over from last read */
7117 if (fd_info
[fd
].flags
& FILE_LAST_CR
)
7119 if (fd_info
[fd
].flags
& FILE_BINARY
) emacs_abort ();
7123 fd_info
[fd
].flags
&= ~FILE_LAST_CR
;
7126 /* presence of a child_process structure means we are operating in
7127 non-blocking mode - otherwise we just call _read directly.
7128 Note that the child_process structure might be missing because
7129 reap_subprocess has been called; in this case the pipe is
7130 already broken, so calling _read on it is okay. */
7133 int current_status
= cp
->status
;
7135 switch (current_status
)
7137 case STATUS_READ_FAILED
:
7138 case STATUS_READ_ERROR
:
7139 /* report normal EOF if nothing in buffer */
7141 fd_info
[fd
].flags
|= FILE_AT_EOF
;
7144 case STATUS_READ_READY
:
7145 case STATUS_READ_IN_PROGRESS
:
7146 DebPrint (("sys_read called when read is in progress\n"));
7147 errno
= EWOULDBLOCK
;
7150 case STATUS_READ_SUCCEEDED
:
7151 /* consume read-ahead char */
7152 *buffer
++ = cp
->chr
;
7155 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
7156 ResetEvent (cp
->char_avail
);
7158 case STATUS_READ_ACKNOWLEDGED
:
7162 DebPrint (("sys_read: bad status %d\n", current_status
));
7167 if (fd_info
[fd
].flags
& FILE_PIPE
)
7169 PeekNamedPipe ((HANDLE
) _get_osfhandle (fd
), NULL
, 0, NULL
, &waiting
, NULL
);
7170 to_read
= min (waiting
, (DWORD
) count
);
7173 nchars
+= _read (fd
, buffer
, to_read
);
7175 else if (fd_info
[fd
].flags
& FILE_SERIAL
)
7177 HANDLE hnd
= fd_info
[fd
].hnd
;
7178 OVERLAPPED
*ovl
= &fd_info
[fd
].cp
->ovl_read
;
7184 /* Configure timeouts for non-blocking read. */
7185 if (!GetCommTimeouts (hnd
, &ct
))
7190 ct
.ReadIntervalTimeout
= MAXDWORD
;
7191 ct
.ReadTotalTimeoutMultiplier
= 0;
7192 ct
.ReadTotalTimeoutConstant
= 0;
7193 if (!SetCommTimeouts (hnd
, &ct
))
7199 if (!ResetEvent (ovl
->hEvent
))
7204 if (!ReadFile (hnd
, buffer
, count
, (DWORD
*) &rc
, ovl
))
7206 if (GetLastError () != ERROR_IO_PENDING
)
7211 if (!GetOverlappedResult (hnd
, ovl
, (DWORD
*) &rc
, TRUE
))
7220 else /* FILE_SOCKET */
7222 if (winsock_lib
== NULL
) emacs_abort ();
7224 /* do the equivalent of a non-blocking read */
7225 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONREAD
, &waiting
);
7226 if (waiting
== 0 && nchars
== 0)
7228 errno
= EWOULDBLOCK
;
7234 /* always use binary mode for sockets */
7235 int res
= pfn_recv (SOCK_HANDLE (fd
), buffer
, count
, 0);
7236 if (res
== SOCKET_ERROR
)
7238 DebPrint (("sys_read.recv failed with error %d on socket %ld\n",
7239 pfn_WSAGetLastError (), SOCK_HANDLE (fd
)));
7249 int nread
= _read (fd
, buffer
, count
);
7252 else if (nchars
== 0)
7257 fd_info
[fd
].flags
|= FILE_AT_EOF
;
7258 /* Perform text mode translation if required. */
7259 else if ((fd_info
[fd
].flags
& FILE_BINARY
) == 0)
7261 nchars
= crlf_to_lf (nchars
, orig_buffer
);
7262 /* If buffer contains only CR, return that. To be absolutely
7263 sure we should attempt to read the next char, but in
7264 practice a CR to be followed by LF would not appear by
7265 itself in the buffer. */
7266 if (nchars
> 1 && orig_buffer
[nchars
- 1] == 0x0d)
7268 fd_info
[fd
].flags
|= FILE_LAST_CR
;
7274 nchars
= _read (fd
, buffer
, count
);
7279 /* From w32xfns.c */
7280 extern HANDLE interrupt_handle
;
7282 /* For now, don't bother with a non-blocking mode */
7284 sys_write (int fd
, const void * buffer
, unsigned int count
)
7294 if (fd
< MAXDESC
&& fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
| FILE_SERIAL
))
7296 if ((fd_info
[fd
].flags
& FILE_WRITE
) == 0)
7302 /* Perform text mode translation if required. */
7303 if ((fd_info
[fd
].flags
& FILE_BINARY
) == 0)
7305 char * tmpbuf
= alloca (count
* 2);
7306 unsigned char * src
= (void *)buffer
;
7307 unsigned char * dst
= tmpbuf
;
7312 unsigned char *next
;
7313 /* copy next line or remaining bytes */
7314 next
= _memccpy (dst
, src
, '\n', nbytes
);
7317 /* copied one line ending with '\n' */
7318 int copied
= next
- dst
;
7321 /* insert '\r' before '\n' */
7328 /* copied remaining partial line -> now finished */
7335 if (fd
< MAXDESC
&& fd_info
[fd
].flags
& FILE_SERIAL
)
7337 HANDLE hnd
= (HANDLE
) _get_osfhandle (fd
);
7338 OVERLAPPED
*ovl
= &fd_info
[fd
].cp
->ovl_write
;
7339 HANDLE wait_hnd
[2] = { interrupt_handle
, ovl
->hEvent
};
7342 if (!WriteFile (hnd
, buffer
, count
, (DWORD
*) &nchars
, ovl
))
7344 if (GetLastError () != ERROR_IO_PENDING
)
7349 if (detect_input_pending ())
7350 active
= MsgWaitForMultipleObjects (2, wait_hnd
, FALSE
, INFINITE
,
7353 active
= WaitForMultipleObjects (2, wait_hnd
, FALSE
, INFINITE
);
7354 if (active
== WAIT_OBJECT_0
)
7355 { /* User pressed C-g, cancel write, then leave. Don't bother
7356 cleaning up as we may only get stuck in buggy drivers. */
7357 PurgeComm (hnd
, PURGE_TXABORT
| PURGE_TXCLEAR
);
7362 if (active
== WAIT_OBJECT_0
+ 1
7363 && !GetOverlappedResult (hnd
, ovl
, (DWORD
*) &nchars
, TRUE
))
7370 else if (fd
< MAXDESC
&& fd_info
[fd
].flags
& FILE_SOCKET
)
7372 unsigned long nblock
= 0;
7373 if (winsock_lib
== NULL
) emacs_abort ();
7375 /* TODO: implement select() properly so non-blocking I/O works. */
7376 /* For now, make sure the write blocks. */
7377 if (fd_info
[fd
].flags
& FILE_NDELAY
)
7378 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
7380 nchars
= pfn_send (SOCK_HANDLE (fd
), buffer
, count
, 0);
7382 /* Set the socket back to non-blocking if it was before,
7383 for other operations that support it. */
7384 if (fd_info
[fd
].flags
& FILE_NDELAY
)
7387 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
7390 if (nchars
== SOCKET_ERROR
)
7392 DebPrint (("sys_write.send failed with error %d on socket %ld\n",
7393 pfn_WSAGetLastError (), SOCK_HANDLE (fd
)));
7399 /* Some networked filesystems don't like too large writes, so
7400 break them into smaller chunks. See the Comments section of
7401 the MSDN documentation of WriteFile for details behind the
7402 choice of the value of CHUNK below. See also the thread
7403 http://thread.gmane.org/gmane.comp.version-control.git/145294
7404 in the git mailing list. */
7405 const unsigned char *p
= buffer
;
7406 const unsigned chunk
= 30 * 1024 * 1024;
7411 unsigned this_chunk
= count
< chunk
? count
: chunk
;
7412 int n
= _write (fd
, p
, this_chunk
);
7420 else if (n
< this_chunk
)
7430 /* The Windows CRT functions are "optimized for speed", so they don't
7431 check for timezone and DST changes if they were last called less
7432 than 1 minute ago (see http://support.microsoft.com/kb/821231). So
7433 all Emacs features that repeatedly call time functions (e.g.,
7434 display-time) are in real danger of missing timezone and DST
7435 changes. Calling tzset before each localtime call fixes that. */
7437 sys_localtime (const time_t *t
)
7440 return localtime (t
);
7445 /* Try loading LIBRARY_ID from the file(s) specified in
7446 Vdynamic_library_alist. If the library is loaded successfully,
7447 return the handle of the DLL, and record the filename in the
7448 property :loaded-from of LIBRARY_ID. If the library could not be
7449 found, or when it was already loaded (because the handle is not
7450 recorded anywhere, and so is lost after use), return NULL.
7452 We could also save the handle in :loaded-from, but currently
7453 there's no use case for it. */
7455 w32_delayed_load (Lisp_Object library_id
)
7457 HMODULE library_dll
= NULL
;
7459 CHECK_SYMBOL (library_id
);
7461 if (CONSP (Vdynamic_library_alist
)
7462 && NILP (Fassq (library_id
, Vlibrary_cache
)))
7464 Lisp_Object found
= Qnil
;
7465 Lisp_Object dlls
= Fassq (library_id
, Vdynamic_library_alist
);
7468 for (dlls
= XCDR (dlls
); CONSP (dlls
); dlls
= XCDR (dlls
))
7470 CHECK_STRING_CAR (dlls
);
7471 if ((library_dll
= LoadLibrary (SDATA (XCAR (dlls
)))))
7473 char name
[MAX_PATH
];
7476 len
= GetModuleFileNameA (library_dll
, name
, sizeof (name
));
7477 found
= Fcons (XCAR (dlls
),
7479 /* Possibly truncated */
7480 ? make_specified_string (name
, -1, len
, 1)
7486 Fput (library_id
, QCloaded_from
, found
);
7494 check_windows_init_file (void)
7496 /* A common indication that Emacs is not installed properly is when
7497 it cannot find the Windows installation file. If this file does
7498 not exist in the expected place, tell the user. */
7500 if (!noninteractive
&& !inhibit_window_system
7501 /* Vload_path is not yet initialized when we are loading
7503 && NILP (Vpurify_flag
))
7505 Lisp_Object init_file
;
7508 init_file
= build_string ("term/w32-win");
7509 fd
= openp (Vload_path
, init_file
, Fget_load_suffixes (), NULL
, Qnil
);
7512 Lisp_Object load_path_print
= Fprin1_to_string (Vload_path
, Qnil
);
7513 char *init_file_name
= SDATA (init_file
);
7514 char *load_path
= SDATA (load_path_print
);
7515 char *buffer
= alloca (1024
7516 + strlen (init_file_name
)
7517 + strlen (load_path
));
7520 "The Emacs Windows initialization file \"%s.el\" "
7521 "could not be found in your Emacs installation. "
7522 "Emacs checked the following directories for this file:\n"
7524 "When Emacs cannot find this file, it usually means that it "
7525 "was not installed properly, or its distribution file was "
7526 "not unpacked properly.\nSee the README.W32 file in the "
7527 "top-level Emacs directory for more information.",
7528 init_file_name
, load_path
);
7531 "Emacs Abort Dialog",
7532 MB_OK
| MB_ICONEXCLAMATION
| MB_TASKMODAL
);
7533 /* Use the low-level system abort. */
7544 term_ntproc (int ignored
)
7550 /* shutdown the socket interface if necessary */
7557 init_ntproc (int dumping
)
7559 sigset_t initial_mask
= 0;
7561 /* Initialize the socket interface now if available and requested by
7562 the user by defining PRELOAD_WINSOCK; otherwise loading will be
7563 delayed until open-network-stream is called (w32-has-winsock can
7564 also be used to dynamically load or reload winsock).
7566 Conveniently, init_environment is called before us, so
7567 PRELOAD_WINSOCK can be set in the registry. */
7569 /* Always initialize this correctly. */
7572 if (getenv ("PRELOAD_WINSOCK") != NULL
)
7573 init_winsock (TRUE
);
7575 /* Initial preparation for subprocess support: replace our standard
7576 handles with non-inheritable versions. */
7579 HANDLE stdin_save
= INVALID_HANDLE_VALUE
;
7580 HANDLE stdout_save
= INVALID_HANDLE_VALUE
;
7581 HANDLE stderr_save
= INVALID_HANDLE_VALUE
;
7583 parent
= GetCurrentProcess ();
7585 /* ignore errors when duplicating and closing; typically the
7586 handles will be invalid when running as a gui program. */
7587 DuplicateHandle (parent
,
7588 GetStdHandle (STD_INPUT_HANDLE
),
7593 DUPLICATE_SAME_ACCESS
);
7595 DuplicateHandle (parent
,
7596 GetStdHandle (STD_OUTPUT_HANDLE
),
7601 DUPLICATE_SAME_ACCESS
);
7603 DuplicateHandle (parent
,
7604 GetStdHandle (STD_ERROR_HANDLE
),
7609 DUPLICATE_SAME_ACCESS
);
7615 if (stdin_save
!= INVALID_HANDLE_VALUE
)
7616 _open_osfhandle ((intptr_t) stdin_save
, O_TEXT
);
7618 _open ("nul", O_TEXT
| O_NOINHERIT
| O_RDONLY
);
7621 if (stdout_save
!= INVALID_HANDLE_VALUE
)
7622 _open_osfhandle ((intptr_t) stdout_save
, O_TEXT
);
7624 _open ("nul", O_TEXT
| O_NOINHERIT
| O_WRONLY
);
7627 if (stderr_save
!= INVALID_HANDLE_VALUE
)
7628 _open_osfhandle ((intptr_t) stderr_save
, O_TEXT
);
7630 _open ("nul", O_TEXT
| O_NOINHERIT
| O_WRONLY
);
7634 /* unfortunately, atexit depends on implementation of malloc */
7635 /* atexit (term_ntproc); */
7638 /* Make sure we start with all signals unblocked. */
7639 sigprocmask (SIG_SETMASK
, &initial_mask
, NULL
);
7640 signal (SIGABRT
, term_ntproc
);
7644 /* determine which drives are fixed, for GetCachedVolumeInformation */
7646 /* GetDriveType must have trailing backslash. */
7647 char drive
[] = "A:\\";
7649 /* Loop over all possible drive letters */
7650 while (*drive
<= 'Z')
7652 /* Record if this drive letter refers to a fixed drive. */
7653 fixed_drives
[DRIVE_INDEX (*drive
)] =
7654 (GetDriveType (drive
) == DRIVE_FIXED
);
7659 /* Reset the volume info cache. */
7660 volume_cache
= NULL
;
7665 shutdown_handler ensures that buffers' autosave files are
7666 up to date when the user logs off, or the system shuts down.
7669 shutdown_handler (DWORD type
)
7671 /* Ctrl-C and Ctrl-Break are already suppressed, so don't handle them. */
7672 if (type
== CTRL_CLOSE_EVENT
/* User closes console window. */
7673 || type
== CTRL_LOGOFF_EVENT
/* User logs off. */
7674 || type
== CTRL_SHUTDOWN_EVENT
) /* User shutsdown. */
7676 /* Shut down cleanly, making sure autosave files are up to date. */
7677 shut_down_emacs (0, Qnil
);
7680 /* Allow other handlers to handle this signal. */
7685 globals_of_w32 is used to initialize those global variables that
7686 must always be initialized on startup even when the global variable
7687 initialized is non zero (see the function main in emacs.c).
7690 globals_of_w32 (void)
7692 HMODULE kernel32
= GetModuleHandle ("kernel32.dll");
7694 get_process_times_fn
= (GetProcessTimes_Proc
)
7695 GetProcAddress (kernel32
, "GetProcessTimes");
7697 DEFSYM (QCloaded_from
, ":loaded-from");
7699 g_b_init_is_windows_9x
= 0;
7700 g_b_init_open_process_token
= 0;
7701 g_b_init_get_token_information
= 0;
7702 g_b_init_lookup_account_sid
= 0;
7703 g_b_init_get_sid_sub_authority
= 0;
7704 g_b_init_get_sid_sub_authority_count
= 0;
7705 g_b_init_get_security_info
= 0;
7706 g_b_init_get_file_security
= 0;
7707 g_b_init_get_security_descriptor_owner
= 0;
7708 g_b_init_get_security_descriptor_group
= 0;
7709 g_b_init_is_valid_sid
= 0;
7710 g_b_init_create_toolhelp32_snapshot
= 0;
7711 g_b_init_process32_first
= 0;
7712 g_b_init_process32_next
= 0;
7713 g_b_init_open_thread_token
= 0;
7714 g_b_init_impersonate_self
= 0;
7715 g_b_init_revert_to_self
= 0;
7716 g_b_init_get_process_memory_info
= 0;
7717 g_b_init_get_process_working_set_size
= 0;
7718 g_b_init_global_memory_status
= 0;
7719 g_b_init_global_memory_status_ex
= 0;
7720 g_b_init_equal_sid
= 0;
7721 g_b_init_copy_sid
= 0;
7722 g_b_init_get_length_sid
= 0;
7723 g_b_init_get_native_system_info
= 0;
7724 g_b_init_get_system_times
= 0;
7725 g_b_init_create_symbolic_link
= 0;
7726 g_b_init_get_security_descriptor_dacl
= 0;
7727 g_b_init_convert_sd_to_sddl
= 0;
7728 g_b_init_convert_sddl_to_sd
= 0;
7729 g_b_init_is_valid_security_descriptor
= 0;
7730 g_b_init_set_file_security
= 0;
7731 num_of_processors
= 0;
7732 /* The following sets a handler for shutdown notifications for
7733 console apps. This actually applies to Emacs in both console and
7734 GUI modes, since we had to fool windows into thinking emacs is a
7735 console application to get console mode to work. */
7736 SetConsoleCtrlHandler (shutdown_handler
, TRUE
);
7738 /* "None" is the default group name on standalone workstations. */
7739 strcpy (dflt_group_name
, "None");
7741 /* Reset, in case it has some value inherited from dump time. */
7742 w32_stat_get_owner_group
= 0;
7745 /* For make-serial-process */
7747 serial_open (Lisp_Object port_obj
)
7749 char *port
= SSDATA (port_obj
);
7754 hnd
= CreateFile (port
, GENERIC_READ
| GENERIC_WRITE
, 0, 0,
7755 OPEN_EXISTING
, FILE_FLAG_OVERLAPPED
, 0);
7756 if (hnd
== INVALID_HANDLE_VALUE
)
7757 error ("Could not open %s", port
);
7758 fd
= (int) _open_osfhandle ((intptr_t) hnd
, 0);
7760 error ("Could not open %s", port
);
7764 error ("Could not create child process");
7766 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
7767 fd_info
[ fd
].hnd
= hnd
;
7768 fd_info
[ fd
].flags
|=
7769 FILE_READ
| FILE_WRITE
| FILE_BINARY
| FILE_SERIAL
;
7770 if (fd_info
[ fd
].cp
!= NULL
)
7772 error ("fd_info[fd = %d] is already in use", fd
);
7774 fd_info
[ fd
].cp
= cp
;
7775 cp
->ovl_read
.hEvent
= CreateEvent (NULL
, TRUE
, FALSE
, NULL
);
7776 if (cp
->ovl_read
.hEvent
== NULL
)
7777 error ("Could not create read event");
7778 cp
->ovl_write
.hEvent
= CreateEvent (NULL
, TRUE
, FALSE
, NULL
);
7779 if (cp
->ovl_write
.hEvent
== NULL
)
7780 error ("Could not create write event");
7785 /* For serial-process-configure */
7787 serial_configure (struct Lisp_Process
*p
, Lisp_Object contact
)
7789 Lisp_Object childp2
= Qnil
;
7790 Lisp_Object tem
= Qnil
;
7794 char summary
[4] = "???"; /* This usually becomes "8N1". */
7796 if ((fd_info
[ p
->outfd
].flags
& FILE_SERIAL
) == 0)
7797 error ("Not a serial process");
7798 hnd
= fd_info
[ p
->outfd
].hnd
;
7800 childp2
= Fcopy_sequence (p
->childp
);
7802 /* Initialize timeouts for blocking read and blocking write. */
7803 if (!GetCommTimeouts (hnd
, &ct
))
7804 error ("GetCommTimeouts() failed");
7805 ct
.ReadIntervalTimeout
= 0;
7806 ct
.ReadTotalTimeoutMultiplier
= 0;
7807 ct
.ReadTotalTimeoutConstant
= 0;
7808 ct
.WriteTotalTimeoutMultiplier
= 0;
7809 ct
.WriteTotalTimeoutConstant
= 0;
7810 if (!SetCommTimeouts (hnd
, &ct
))
7811 error ("SetCommTimeouts() failed");
7812 /* Read port attributes and prepare default configuration. */
7813 memset (&dcb
, 0, sizeof (dcb
));
7814 dcb
.DCBlength
= sizeof (DCB
);
7815 if (!GetCommState (hnd
, &dcb
))
7816 error ("GetCommState() failed");
7819 dcb
.fAbortOnError
= FALSE
;
7820 /* dcb.XonLim and dcb.XoffLim are set by GetCommState() */
7825 /* Configure speed. */
7826 if (!NILP (Fplist_member (contact
, QCspeed
)))
7827 tem
= Fplist_get (contact
, QCspeed
);
7829 tem
= Fplist_get (p
->childp
, QCspeed
);
7831 dcb
.BaudRate
= XINT (tem
);
7832 childp2
= Fplist_put (childp2
, QCspeed
, tem
);
7834 /* Configure bytesize. */
7835 if (!NILP (Fplist_member (contact
, QCbytesize
)))
7836 tem
= Fplist_get (contact
, QCbytesize
);
7838 tem
= Fplist_get (p
->childp
, QCbytesize
);
7840 tem
= make_number (8);
7842 if (XINT (tem
) != 7 && XINT (tem
) != 8)
7843 error (":bytesize must be nil (8), 7, or 8");
7844 dcb
.ByteSize
= XINT (tem
);
7845 summary
[0] = XINT (tem
) + '0';
7846 childp2
= Fplist_put (childp2
, QCbytesize
, tem
);
7848 /* Configure parity. */
7849 if (!NILP (Fplist_member (contact
, QCparity
)))
7850 tem
= Fplist_get (contact
, QCparity
);
7852 tem
= Fplist_get (p
->childp
, QCparity
);
7853 if (!NILP (tem
) && !EQ (tem
, Qeven
) && !EQ (tem
, Qodd
))
7854 error (":parity must be nil (no parity), `even', or `odd'");
7855 dcb
.fParity
= FALSE
;
7856 dcb
.Parity
= NOPARITY
;
7857 dcb
.fErrorChar
= FALSE
;
7862 else if (EQ (tem
, Qeven
))
7866 dcb
.Parity
= EVENPARITY
;
7867 dcb
.fErrorChar
= TRUE
;
7869 else if (EQ (tem
, Qodd
))
7873 dcb
.Parity
= ODDPARITY
;
7874 dcb
.fErrorChar
= TRUE
;
7876 childp2
= Fplist_put (childp2
, QCparity
, tem
);
7878 /* Configure stopbits. */
7879 if (!NILP (Fplist_member (contact
, QCstopbits
)))
7880 tem
= Fplist_get (contact
, QCstopbits
);
7882 tem
= Fplist_get (p
->childp
, QCstopbits
);
7884 tem
= make_number (1);
7886 if (XINT (tem
) != 1 && XINT (tem
) != 2)
7887 error (":stopbits must be nil (1 stopbit), 1, or 2");
7888 summary
[2] = XINT (tem
) + '0';
7889 if (XINT (tem
) == 1)
7890 dcb
.StopBits
= ONESTOPBIT
;
7891 else if (XINT (tem
) == 2)
7892 dcb
.StopBits
= TWOSTOPBITS
;
7893 childp2
= Fplist_put (childp2
, QCstopbits
, tem
);
7895 /* Configure flowcontrol. */
7896 if (!NILP (Fplist_member (contact
, QCflowcontrol
)))
7897 tem
= Fplist_get (contact
, QCflowcontrol
);
7899 tem
= Fplist_get (p
->childp
, QCflowcontrol
);
7900 if (!NILP (tem
) && !EQ (tem
, Qhw
) && !EQ (tem
, Qsw
))
7901 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
7902 dcb
.fOutxCtsFlow
= FALSE
;
7903 dcb
.fOutxDsrFlow
= FALSE
;
7904 dcb
.fDtrControl
= DTR_CONTROL_DISABLE
;
7905 dcb
.fDsrSensitivity
= FALSE
;
7906 dcb
.fTXContinueOnXoff
= FALSE
;
7909 dcb
.fRtsControl
= RTS_CONTROL_DISABLE
;
7910 dcb
.XonChar
= 17; /* Control-Q */
7911 dcb
.XoffChar
= 19; /* Control-S */
7914 /* Already configured. */
7916 else if (EQ (tem
, Qhw
))
7918 dcb
.fRtsControl
= RTS_CONTROL_HANDSHAKE
;
7919 dcb
.fOutxCtsFlow
= TRUE
;
7921 else if (EQ (tem
, Qsw
))
7926 childp2
= Fplist_put (childp2
, QCflowcontrol
, tem
);
7928 /* Activate configuration. */
7929 if (!SetCommState (hnd
, &dcb
))
7930 error ("SetCommState() failed");
7932 childp2
= Fplist_put (childp2
, QCsummary
, build_string (summary
));
7933 pset_childp (p
, childp2
);
7939 emacs_gnutls_pull (gnutls_transport_ptr_t p
, void* buf
, size_t sz
)
7944 struct Lisp_Process
*process
= (struct Lisp_Process
*)p
;
7945 int fd
= process
->infd
;
7947 n
= sys_read (fd
, (char*)buf
, sz
);
7954 /* Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
7955 if (err
== EWOULDBLOCK
)
7958 emacs_gnutls_transport_set_errno (process
->gnutls_state
, err
);
7964 emacs_gnutls_push (gnutls_transport_ptr_t p
, const void* buf
, size_t sz
)
7966 struct Lisp_Process
*process
= (struct Lisp_Process
*)p
;
7967 int fd
= process
->outfd
;
7968 ssize_t n
= sys_write (fd
, buf
, sz
);
7970 /* 0 or more bytes written means everything went fine. */
7974 /* Negative bytes written means we got an error in errno.
7975 Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
7976 emacs_gnutls_transport_set_errno (process
->gnutls_state
,
7977 errno
== EWOULDBLOCK
? EAGAIN
: errno
);
7981 #endif /* HAVE_GNUTLS */