1 /* Utility and Unix shadow routines for GNU Emacs on the Microsoft Windows API.
2 Copyright (C) 1994-1995, 2000-2012 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 */
33 #include <sys/utime.h>
37 /* must include CRT headers *before* config.h */
40 #include <mbstring.h> /* for _mbspbrk */
73 #define _ANONYMOUS_UNION
74 #define _ANONYMOUS_STRUCT
77 /* Some versions of compiler define MEMORYSTATUSEX, some don't, so we
78 use a different name to avoid compilation problems. */
79 typedef struct _MEMORY_STATUS_EX
{
82 DWORDLONG ullTotalPhys
;
83 DWORDLONG ullAvailPhys
;
84 DWORDLONG ullTotalPageFile
;
85 DWORDLONG ullAvailPageFile
;
86 DWORDLONG ullTotalVirtual
;
87 DWORDLONG ullAvailVirtual
;
88 DWORDLONG ullAvailExtendedVirtual
;
89 } MEMORY_STATUS_EX
,*LPMEMORY_STATUS_EX
;
99 #if !defined (__MINGW32__) || __W32API_MAJOR_VERSION < 3 || (__W32API_MAJOR_VERSION == 3 && __W32API_MINOR_VERSION < 15)
100 /* This either is not in psapi.h or guarded by higher value of
101 _WIN32_WINNT than what we use. w32api supplied with MinGW 3.15
102 defines it in psapi.h */
103 typedef struct _PROCESS_MEMORY_COUNTERS_EX
{
105 DWORD PageFaultCount
;
106 DWORD PeakWorkingSetSize
;
107 DWORD WorkingSetSize
;
108 DWORD QuotaPeakPagedPoolUsage
;
109 DWORD QuotaPagedPoolUsage
;
110 DWORD QuotaPeakNonPagedPoolUsage
;
111 DWORD QuotaNonPagedPoolUsage
;
113 DWORD PeakPagefileUsage
;
115 } PROCESS_MEMORY_COUNTERS_EX
,*PPROCESS_MEMORY_COUNTERS_EX
;
118 #include <winioctl.h>
122 /* MSVC doesn't provide the definition of REPARSE_DATA_BUFFER and the
123 associated macros, except on ntifs.h, which cannot be included
124 because it triggers conflicts with other Windows API headers. So
125 we define it here by hand. */
127 typedef struct _REPARSE_DATA_BUFFER
{
129 USHORT ReparseDataLength
;
133 USHORT SubstituteNameOffset
;
134 USHORT SubstituteNameLength
;
135 USHORT PrintNameOffset
;
136 USHORT PrintNameLength
;
139 } SymbolicLinkReparseBuffer
;
141 USHORT SubstituteNameOffset
;
142 USHORT SubstituteNameLength
;
143 USHORT PrintNameOffset
;
144 USHORT PrintNameLength
;
146 } MountPointReparseBuffer
;
149 } GenericReparseBuffer
;
151 } REPARSE_DATA_BUFFER
, *PREPARSE_DATA_BUFFER
;
153 #define FILE_DEVICE_FILE_SYSTEM 9
154 #define METHOD_BUFFERED 0
155 #define FILE_ANY_ACCESS 0x00000000
156 #define CTL_CODE(t,f,m,a) (((t)<<16)|((a)<<14)|((f)<<2)|(m))
157 #define FSCTL_GET_REPARSE_POINT \
158 CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 42, METHOD_BUFFERED, FILE_ANY_ACCESS)
161 /* TCP connection support. */
162 #include <sys/socket.h>
183 #include "w32common.h"
185 #include "w32select.h"
187 #include "dispextern.h" /* for xstrcasecmp */
188 #include "coding.h" /* for Vlocale_coding_system */
190 #include "careadlinkat.h"
191 #include "allocator.h"
193 /* For serial_configure and serial_open. */
196 typedef HRESULT (WINAPI
* ShGetFolderPath_fn
)
197 (IN HWND
, IN
int, IN HANDLE
, IN DWORD
, OUT
char *);
199 Lisp_Object QCloaded_from
;
201 void globals_of_w32 (void);
202 static DWORD
get_rid (PSID
);
203 static int is_symlink (const char *);
204 static char * chase_symlinks (const char *);
205 static int enable_privilege (LPCTSTR
, BOOL
, TOKEN_PRIVILEGES
*);
206 static int restore_privilege (TOKEN_PRIVILEGES
*);
207 static BOOL WINAPI
revert_to_self (void);
209 extern int sys_access (const char *, int);
210 extern void *e_malloc (size_t);
211 extern int sys_select (int, SELECT_TYPE
*, SELECT_TYPE
*, SELECT_TYPE
*,
212 EMACS_TIME
*, void *);
216 /* Initialization states.
218 WARNING: If you add any more such variables for additional APIs,
219 you MUST add initialization for them to globals_of_w32
220 below. This is because these variables might get set
221 to non-NULL values during dumping, but the dumped Emacs
222 cannot reuse those values, because it could be run on a
223 different version of the OS, where API addresses are
225 static BOOL g_b_init_is_windows_9x
;
226 static BOOL g_b_init_open_process_token
;
227 static BOOL g_b_init_get_token_information
;
228 static BOOL g_b_init_lookup_account_sid
;
229 static BOOL g_b_init_get_sid_sub_authority
;
230 static BOOL g_b_init_get_sid_sub_authority_count
;
231 static BOOL g_b_init_get_security_info
;
232 static BOOL g_b_init_get_file_security
;
233 static BOOL g_b_init_get_security_descriptor_owner
;
234 static BOOL g_b_init_get_security_descriptor_group
;
235 static BOOL g_b_init_is_valid_sid
;
236 static BOOL g_b_init_create_toolhelp32_snapshot
;
237 static BOOL g_b_init_process32_first
;
238 static BOOL g_b_init_process32_next
;
239 static BOOL g_b_init_open_thread_token
;
240 static BOOL g_b_init_impersonate_self
;
241 static BOOL g_b_init_revert_to_self
;
242 static BOOL g_b_init_get_process_memory_info
;
243 static BOOL g_b_init_get_process_working_set_size
;
244 static BOOL g_b_init_global_memory_status
;
245 static BOOL g_b_init_global_memory_status_ex
;
246 static BOOL g_b_init_get_length_sid
;
247 static BOOL g_b_init_equal_sid
;
248 static BOOL g_b_init_copy_sid
;
249 static BOOL g_b_init_get_native_system_info
;
250 static BOOL g_b_init_get_system_times
;
251 static BOOL g_b_init_create_symbolic_link
;
254 BEGIN: Wrapper functions around OpenProcessToken
255 and other functions in advapi32.dll that are only
256 supported in Windows NT / 2k / XP
258 /* ** Function pointer typedefs ** */
259 typedef BOOL (WINAPI
* OpenProcessToken_Proc
) (
260 HANDLE ProcessHandle
,
262 PHANDLE TokenHandle
);
263 typedef BOOL (WINAPI
* GetTokenInformation_Proc
) (
265 TOKEN_INFORMATION_CLASS TokenInformationClass
,
266 LPVOID TokenInformation
,
267 DWORD TokenInformationLength
,
268 PDWORD ReturnLength
);
269 typedef BOOL (WINAPI
* GetProcessTimes_Proc
) (
270 HANDLE process_handle
,
271 LPFILETIME creation_time
,
272 LPFILETIME exit_time
,
273 LPFILETIME kernel_time
,
274 LPFILETIME user_time
);
276 GetProcessTimes_Proc get_process_times_fn
= NULL
;
279 const char * const LookupAccountSid_Name
= "LookupAccountSidW";
280 const char * const GetFileSecurity_Name
= "GetFileSecurityW";
282 const char * const LookupAccountSid_Name
= "LookupAccountSidA";
283 const char * const GetFileSecurity_Name
= "GetFileSecurityA";
285 typedef BOOL (WINAPI
* LookupAccountSid_Proc
) (
286 LPCTSTR lpSystemName
,
291 LPDWORD cbDomainName
,
292 PSID_NAME_USE peUse
);
293 typedef PDWORD (WINAPI
* GetSidSubAuthority_Proc
) (
296 typedef PUCHAR (WINAPI
* GetSidSubAuthorityCount_Proc
) (
298 typedef DWORD (WINAPI
* GetSecurityInfo_Proc
) (
300 SE_OBJECT_TYPE ObjectType
,
301 SECURITY_INFORMATION SecurityInfo
,
306 PSECURITY_DESCRIPTOR
*ppSecurityDescriptor
);
307 typedef BOOL (WINAPI
* GetFileSecurity_Proc
) (
309 SECURITY_INFORMATION RequestedInformation
,
310 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
312 LPDWORD lpnLengthNeeded
);
313 typedef BOOL (WINAPI
* GetSecurityDescriptorOwner_Proc
) (
314 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
316 LPBOOL lpbOwnerDefaulted
);
317 typedef BOOL (WINAPI
* GetSecurityDescriptorGroup_Proc
) (
318 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
320 LPBOOL lpbGroupDefaulted
);
321 typedef BOOL (WINAPI
* IsValidSid_Proc
) (
323 typedef HANDLE (WINAPI
* CreateToolhelp32Snapshot_Proc
) (
325 DWORD th32ProcessID
);
326 typedef BOOL (WINAPI
* Process32First_Proc
) (
328 LPPROCESSENTRY32 lppe
);
329 typedef BOOL (WINAPI
* Process32Next_Proc
) (
331 LPPROCESSENTRY32 lppe
);
332 typedef BOOL (WINAPI
* OpenThreadToken_Proc
) (
336 PHANDLE TokenHandle
);
337 typedef BOOL (WINAPI
* ImpersonateSelf_Proc
) (
338 SECURITY_IMPERSONATION_LEVEL ImpersonationLevel
);
339 typedef BOOL (WINAPI
* RevertToSelf_Proc
) (void);
340 typedef BOOL (WINAPI
* GetProcessMemoryInfo_Proc
) (
342 PPROCESS_MEMORY_COUNTERS ppsmemCounters
,
344 typedef BOOL (WINAPI
* GetProcessWorkingSetSize_Proc
) (
346 DWORD
* lpMinimumWorkingSetSize
,
347 DWORD
* lpMaximumWorkingSetSize
);
348 typedef BOOL (WINAPI
* GlobalMemoryStatus_Proc
) (
349 LPMEMORYSTATUS lpBuffer
);
350 typedef BOOL (WINAPI
* GlobalMemoryStatusEx_Proc
) (
351 LPMEMORY_STATUS_EX lpBuffer
);
352 typedef BOOL (WINAPI
* CopySid_Proc
) (
353 DWORD nDestinationSidLength
,
354 PSID pDestinationSid
,
356 typedef BOOL (WINAPI
* EqualSid_Proc
) (
359 typedef DWORD (WINAPI
* GetLengthSid_Proc
) (
361 typedef void (WINAPI
* GetNativeSystemInfo_Proc
) (
362 LPSYSTEM_INFO lpSystemInfo
);
363 typedef BOOL (WINAPI
* GetSystemTimes_Proc
) (
364 LPFILETIME lpIdleTime
,
365 LPFILETIME lpKernelTime
,
366 LPFILETIME lpUserTime
);
367 typedef BOOLEAN (WINAPI
*CreateSymbolicLink_Proc
) (
368 LPTSTR lpSymlinkFileName
,
369 LPTSTR lpTargetFileName
,
372 /* ** A utility function ** */
376 static BOOL s_b_ret
= 0;
377 OSVERSIONINFO os_ver
;
378 if (g_b_init_is_windows_9x
== 0)
380 g_b_init_is_windows_9x
= 1;
381 ZeroMemory (&os_ver
, sizeof (OSVERSIONINFO
));
382 os_ver
.dwOSVersionInfoSize
= sizeof (OSVERSIONINFO
);
383 if (GetVersionEx (&os_ver
))
385 s_b_ret
= (os_ver
.dwPlatformId
== VER_PLATFORM_WIN32_WINDOWS
);
391 static Lisp_Object
ltime (ULONGLONG
);
393 /* Get total user and system times for get-internal-run-time.
394 Returns a list of integers if the times are provided by the OS
395 (NT derivatives), otherwise it returns the result of current-time. */
397 w32_get_internal_run_time (void)
399 if (get_process_times_fn
)
401 FILETIME create
, exit
, kernel
, user
;
402 HANDLE proc
= GetCurrentProcess ();
403 if ((*get_process_times_fn
) (proc
, &create
, &exit
, &kernel
, &user
))
405 LARGE_INTEGER user_int
, kernel_int
, total
;
406 user_int
.LowPart
= user
.dwLowDateTime
;
407 user_int
.HighPart
= user
.dwHighDateTime
;
408 kernel_int
.LowPart
= kernel
.dwLowDateTime
;
409 kernel_int
.HighPart
= kernel
.dwHighDateTime
;
410 total
.QuadPart
= user_int
.QuadPart
+ kernel_int
.QuadPart
;
411 return ltime (total
.QuadPart
);
415 return Fcurrent_time ();
418 /* ** The wrapper functions ** */
421 open_process_token (HANDLE ProcessHandle
,
425 static OpenProcessToken_Proc s_pfn_Open_Process_Token
= NULL
;
426 HMODULE hm_advapi32
= NULL
;
427 if (is_windows_9x () == TRUE
)
431 if (g_b_init_open_process_token
== 0)
433 g_b_init_open_process_token
= 1;
434 hm_advapi32
= LoadLibrary ("Advapi32.dll");
435 s_pfn_Open_Process_Token
=
436 (OpenProcessToken_Proc
) GetProcAddress (hm_advapi32
, "OpenProcessToken");
438 if (s_pfn_Open_Process_Token
== NULL
)
443 s_pfn_Open_Process_Token (
451 get_token_information (HANDLE TokenHandle
,
452 TOKEN_INFORMATION_CLASS TokenInformationClass
,
453 LPVOID TokenInformation
,
454 DWORD TokenInformationLength
,
457 static GetTokenInformation_Proc s_pfn_Get_Token_Information
= NULL
;
458 HMODULE hm_advapi32
= NULL
;
459 if (is_windows_9x () == TRUE
)
463 if (g_b_init_get_token_information
== 0)
465 g_b_init_get_token_information
= 1;
466 hm_advapi32
= LoadLibrary ("Advapi32.dll");
467 s_pfn_Get_Token_Information
=
468 (GetTokenInformation_Proc
) GetProcAddress (hm_advapi32
, "GetTokenInformation");
470 if (s_pfn_Get_Token_Information
== NULL
)
475 s_pfn_Get_Token_Information (
477 TokenInformationClass
,
479 TokenInformationLength
,
485 lookup_account_sid (LPCTSTR lpSystemName
,
490 LPDWORD cbDomainName
,
493 static LookupAccountSid_Proc s_pfn_Lookup_Account_Sid
= NULL
;
494 HMODULE hm_advapi32
= NULL
;
495 if (is_windows_9x () == TRUE
)
499 if (g_b_init_lookup_account_sid
== 0)
501 g_b_init_lookup_account_sid
= 1;
502 hm_advapi32
= LoadLibrary ("Advapi32.dll");
503 s_pfn_Lookup_Account_Sid
=
504 (LookupAccountSid_Proc
) GetProcAddress (hm_advapi32
, LookupAccountSid_Name
);
506 if (s_pfn_Lookup_Account_Sid
== NULL
)
511 s_pfn_Lookup_Account_Sid (
523 get_sid_sub_authority (PSID pSid
, DWORD n
)
525 static GetSidSubAuthority_Proc s_pfn_Get_Sid_Sub_Authority
= NULL
;
526 static DWORD zero
= 0U;
527 HMODULE hm_advapi32
= NULL
;
528 if (is_windows_9x () == TRUE
)
532 if (g_b_init_get_sid_sub_authority
== 0)
534 g_b_init_get_sid_sub_authority
= 1;
535 hm_advapi32
= LoadLibrary ("Advapi32.dll");
536 s_pfn_Get_Sid_Sub_Authority
=
537 (GetSidSubAuthority_Proc
) GetProcAddress (
538 hm_advapi32
, "GetSidSubAuthority");
540 if (s_pfn_Get_Sid_Sub_Authority
== NULL
)
544 return (s_pfn_Get_Sid_Sub_Authority (pSid
, n
));
548 get_sid_sub_authority_count (PSID pSid
)
550 static GetSidSubAuthorityCount_Proc s_pfn_Get_Sid_Sub_Authority_Count
= NULL
;
551 static UCHAR zero
= 0U;
552 HMODULE hm_advapi32
= NULL
;
553 if (is_windows_9x () == TRUE
)
557 if (g_b_init_get_sid_sub_authority_count
== 0)
559 g_b_init_get_sid_sub_authority_count
= 1;
560 hm_advapi32
= LoadLibrary ("Advapi32.dll");
561 s_pfn_Get_Sid_Sub_Authority_Count
=
562 (GetSidSubAuthorityCount_Proc
) GetProcAddress (
563 hm_advapi32
, "GetSidSubAuthorityCount");
565 if (s_pfn_Get_Sid_Sub_Authority_Count
== NULL
)
569 return (s_pfn_Get_Sid_Sub_Authority_Count (pSid
));
573 get_security_info (HANDLE handle
,
574 SE_OBJECT_TYPE ObjectType
,
575 SECURITY_INFORMATION SecurityInfo
,
580 PSECURITY_DESCRIPTOR
*ppSecurityDescriptor
)
582 static GetSecurityInfo_Proc s_pfn_Get_Security_Info
= NULL
;
583 HMODULE hm_advapi32
= NULL
;
584 if (is_windows_9x () == TRUE
)
588 if (g_b_init_get_security_info
== 0)
590 g_b_init_get_security_info
= 1;
591 hm_advapi32
= LoadLibrary ("Advapi32.dll");
592 s_pfn_Get_Security_Info
=
593 (GetSecurityInfo_Proc
) GetProcAddress (
594 hm_advapi32
, "GetSecurityInfo");
596 if (s_pfn_Get_Security_Info
== NULL
)
600 return (s_pfn_Get_Security_Info (handle
, ObjectType
, SecurityInfo
,
601 ppsidOwner
, ppsidGroup
, ppDacl
, ppSacl
,
602 ppSecurityDescriptor
));
606 get_file_security (LPCTSTR lpFileName
,
607 SECURITY_INFORMATION RequestedInformation
,
608 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
610 LPDWORD lpnLengthNeeded
)
612 static GetFileSecurity_Proc s_pfn_Get_File_Security
= NULL
;
613 HMODULE hm_advapi32
= NULL
;
614 if (is_windows_9x () == TRUE
)
618 if (g_b_init_get_file_security
== 0)
620 g_b_init_get_file_security
= 1;
621 hm_advapi32
= LoadLibrary ("Advapi32.dll");
622 s_pfn_Get_File_Security
=
623 (GetFileSecurity_Proc
) GetProcAddress (
624 hm_advapi32
, GetFileSecurity_Name
);
626 if (s_pfn_Get_File_Security
== NULL
)
630 return (s_pfn_Get_File_Security (lpFileName
, RequestedInformation
,
631 pSecurityDescriptor
, nLength
,
636 get_security_descriptor_owner (PSECURITY_DESCRIPTOR pSecurityDescriptor
,
638 LPBOOL lpbOwnerDefaulted
)
640 static GetSecurityDescriptorOwner_Proc s_pfn_Get_Security_Descriptor_Owner
= NULL
;
641 HMODULE hm_advapi32
= NULL
;
642 if (is_windows_9x () == TRUE
)
646 if (g_b_init_get_security_descriptor_owner
== 0)
648 g_b_init_get_security_descriptor_owner
= 1;
649 hm_advapi32
= LoadLibrary ("Advapi32.dll");
650 s_pfn_Get_Security_Descriptor_Owner
=
651 (GetSecurityDescriptorOwner_Proc
) GetProcAddress (
652 hm_advapi32
, "GetSecurityDescriptorOwner");
654 if (s_pfn_Get_Security_Descriptor_Owner
== NULL
)
658 return (s_pfn_Get_Security_Descriptor_Owner (pSecurityDescriptor
, pOwner
,
663 get_security_descriptor_group (PSECURITY_DESCRIPTOR pSecurityDescriptor
,
665 LPBOOL lpbGroupDefaulted
)
667 static GetSecurityDescriptorGroup_Proc s_pfn_Get_Security_Descriptor_Group
= NULL
;
668 HMODULE hm_advapi32
= NULL
;
669 if (is_windows_9x () == TRUE
)
673 if (g_b_init_get_security_descriptor_group
== 0)
675 g_b_init_get_security_descriptor_group
= 1;
676 hm_advapi32
= LoadLibrary ("Advapi32.dll");
677 s_pfn_Get_Security_Descriptor_Group
=
678 (GetSecurityDescriptorGroup_Proc
) GetProcAddress (
679 hm_advapi32
, "GetSecurityDescriptorGroup");
681 if (s_pfn_Get_Security_Descriptor_Group
== NULL
)
685 return (s_pfn_Get_Security_Descriptor_Group (pSecurityDescriptor
, pGroup
,
690 is_valid_sid (PSID sid
)
692 static IsValidSid_Proc s_pfn_Is_Valid_Sid
= NULL
;
693 HMODULE hm_advapi32
= NULL
;
694 if (is_windows_9x () == TRUE
)
698 if (g_b_init_is_valid_sid
== 0)
700 g_b_init_is_valid_sid
= 1;
701 hm_advapi32
= LoadLibrary ("Advapi32.dll");
703 (IsValidSid_Proc
) GetProcAddress (
704 hm_advapi32
, "IsValidSid");
706 if (s_pfn_Is_Valid_Sid
== NULL
)
710 return (s_pfn_Is_Valid_Sid (sid
));
714 equal_sid (PSID sid1
, PSID sid2
)
716 static EqualSid_Proc s_pfn_Equal_Sid
= NULL
;
717 HMODULE hm_advapi32
= NULL
;
718 if (is_windows_9x () == TRUE
)
722 if (g_b_init_equal_sid
== 0)
724 g_b_init_equal_sid
= 1;
725 hm_advapi32
= LoadLibrary ("Advapi32.dll");
727 (EqualSid_Proc
) GetProcAddress (
728 hm_advapi32
, "EqualSid");
730 if (s_pfn_Equal_Sid
== NULL
)
734 return (s_pfn_Equal_Sid (sid1
, sid2
));
738 get_length_sid (PSID sid
)
740 static GetLengthSid_Proc s_pfn_Get_Length_Sid
= NULL
;
741 HMODULE hm_advapi32
= NULL
;
742 if (is_windows_9x () == TRUE
)
746 if (g_b_init_get_length_sid
== 0)
748 g_b_init_get_length_sid
= 1;
749 hm_advapi32
= LoadLibrary ("Advapi32.dll");
750 s_pfn_Get_Length_Sid
=
751 (GetLengthSid_Proc
) GetProcAddress (
752 hm_advapi32
, "GetLengthSid");
754 if (s_pfn_Get_Length_Sid
== NULL
)
758 return (s_pfn_Get_Length_Sid (sid
));
762 copy_sid (DWORD destlen
, PSID dest
, PSID src
)
764 static CopySid_Proc s_pfn_Copy_Sid
= NULL
;
765 HMODULE hm_advapi32
= NULL
;
766 if (is_windows_9x () == TRUE
)
770 if (g_b_init_copy_sid
== 0)
772 g_b_init_copy_sid
= 1;
773 hm_advapi32
= LoadLibrary ("Advapi32.dll");
775 (CopySid_Proc
) GetProcAddress (
776 hm_advapi32
, "CopySid");
778 if (s_pfn_Copy_Sid
== NULL
)
782 return (s_pfn_Copy_Sid (destlen
, dest
, src
));
786 END: Wrapper functions around OpenProcessToken
787 and other functions in advapi32.dll that are only
788 supported in Windows NT / 2k / XP
792 get_native_system_info (LPSYSTEM_INFO lpSystemInfo
)
794 static GetNativeSystemInfo_Proc s_pfn_Get_Native_System_Info
= NULL
;
795 if (is_windows_9x () != TRUE
)
797 if (g_b_init_get_native_system_info
== 0)
799 g_b_init_get_native_system_info
= 1;
800 s_pfn_Get_Native_System_Info
=
801 (GetNativeSystemInfo_Proc
)GetProcAddress (GetModuleHandle ("kernel32.dll"),
802 "GetNativeSystemInfo");
804 if (s_pfn_Get_Native_System_Info
!= NULL
)
805 s_pfn_Get_Native_System_Info (lpSystemInfo
);
808 lpSystemInfo
->dwNumberOfProcessors
= -1;
812 get_system_times (LPFILETIME lpIdleTime
,
813 LPFILETIME lpKernelTime
,
814 LPFILETIME lpUserTime
)
816 static GetSystemTimes_Proc s_pfn_Get_System_times
= NULL
;
817 if (is_windows_9x () == TRUE
)
821 if (g_b_init_get_system_times
== 0)
823 g_b_init_get_system_times
= 1;
824 s_pfn_Get_System_times
=
825 (GetSystemTimes_Proc
)GetProcAddress (GetModuleHandle ("kernel32.dll"),
828 if (s_pfn_Get_System_times
== NULL
)
830 return (s_pfn_Get_System_times (lpIdleTime
, lpKernelTime
, lpUserTime
));
833 static BOOLEAN WINAPI
834 create_symbolic_link (LPTSTR lpSymlinkFilename
,
835 LPTSTR lpTargetFileName
,
838 static CreateSymbolicLink_Proc s_pfn_Create_Symbolic_Link
= NULL
;
841 if (is_windows_9x () == TRUE
)
846 if (g_b_init_create_symbolic_link
== 0)
848 g_b_init_create_symbolic_link
= 1;
850 s_pfn_Create_Symbolic_Link
=
851 (CreateSymbolicLink_Proc
)GetProcAddress (GetModuleHandle ("kernel32.dll"),
852 "CreateSymbolicLinkW");
854 s_pfn_Create_Symbolic_Link
=
855 (CreateSymbolicLink_Proc
)GetProcAddress (GetModuleHandle ("kernel32.dll"),
856 "CreateSymbolicLinkA");
859 if (s_pfn_Create_Symbolic_Link
== NULL
)
865 retval
= s_pfn_Create_Symbolic_Link (lpSymlinkFilename
, lpTargetFileName
,
867 /* If we were denied creation of the symlink, try again after
868 enabling the SeCreateSymbolicLinkPrivilege for our process. */
871 TOKEN_PRIVILEGES priv_current
;
873 if (enable_privilege (SE_CREATE_SYMBOLIC_LINK_NAME
, TRUE
, &priv_current
))
875 retval
= s_pfn_Create_Symbolic_Link (lpSymlinkFilename
, lpTargetFileName
,
877 restore_privilege (&priv_current
);
885 /* Return 1 if P is a valid pointer to an object of size SIZE. Return
886 0 if P is NOT a valid pointer. Return -1 if we cannot validate P.
888 This is called from alloc.c:valid_pointer_p. */
890 w32_valid_pointer_p (void *p
, int size
)
893 HANDLE h
= OpenProcess (PROCESS_VM_READ
, FALSE
, GetCurrentProcessId ());
897 unsigned char *buf
= alloca (size
);
898 int retval
= ReadProcessMemory (h
, p
, buf
, size
, &done
);
907 static char startup_dir
[MAXPATHLEN
];
909 /* Get the current working directory. */
914 if (GetCurrentDirectory (MAXPATHLEN
, dir
) > 0)
918 /* Emacs doesn't actually change directory itself, it stays in the
919 same directory where it was started. */
920 strcpy (dir
, startup_dir
);
925 /* Emulate getloadavg. */
934 /* Number of processors on this machine. */
935 static unsigned num_of_processors
;
937 /* We maintain 1-sec samples for the last 16 minutes in a circular buffer. */
938 static struct load_sample samples
[16*60];
939 static int first_idx
= -1, last_idx
= -1;
940 static int max_idx
= sizeof (samples
) / sizeof (samples
[0]);
945 int next_idx
= from
+ 1;
947 if (next_idx
>= max_idx
)
956 int prev_idx
= from
- 1;
959 prev_idx
= max_idx
- 1;
965 sample_system_load (ULONGLONG
*idle
, ULONGLONG
*kernel
, ULONGLONG
*user
)
968 FILETIME ft_idle
, ft_user
, ft_kernel
;
970 /* Initialize the number of processors on this machine. */
971 if (num_of_processors
<= 0)
973 get_native_system_info (&sysinfo
);
974 num_of_processors
= sysinfo
.dwNumberOfProcessors
;
975 if (num_of_processors
<= 0)
977 GetSystemInfo (&sysinfo
);
978 num_of_processors
= sysinfo
.dwNumberOfProcessors
;
980 if (num_of_processors
<= 0)
981 num_of_processors
= 1;
984 /* TODO: Take into account threads that are ready to run, by
985 sampling the "\System\Processor Queue Length" performance
986 counter. The code below accounts only for threads that are
989 if (get_system_times (&ft_idle
, &ft_kernel
, &ft_user
))
991 ULARGE_INTEGER uidle
, ukernel
, uuser
;
993 memcpy (&uidle
, &ft_idle
, sizeof (ft_idle
));
994 memcpy (&ukernel
, &ft_kernel
, sizeof (ft_kernel
));
995 memcpy (&uuser
, &ft_user
, sizeof (ft_user
));
996 *idle
= uidle
.QuadPart
;
997 *kernel
= ukernel
.QuadPart
;
998 *user
= uuser
.QuadPart
;
1008 /* Produce the load average for a given time interval, using the
1009 samples in the samples[] array. WHICH can be 0, 1, or 2, meaning
1010 1-minute, 5-minute, or 15-minute average, respectively. */
1014 double retval
= -1.0;
1017 double span
= (which
== 0 ? 1.0 : (which
== 1 ? 5.0 : 15.0)) * 60;
1018 time_t now
= samples
[last_idx
].sample_time
;
1020 if (first_idx
!= last_idx
)
1022 for (idx
= buf_prev (last_idx
); ; idx
= buf_prev (idx
))
1024 tdiff
= difftime (now
, samples
[idx
].sample_time
);
1025 if (tdiff
>= span
- 2*DBL_EPSILON
*now
)
1028 samples
[last_idx
].kernel
+ samples
[last_idx
].user
1029 - (samples
[idx
].kernel
+ samples
[idx
].user
);
1030 long double idl
= samples
[last_idx
].idle
- samples
[idx
].idle
;
1032 retval
= (1.0 - idl
/ sys
) * num_of_processors
;
1035 if (idx
== first_idx
)
1044 getloadavg (double loadavg
[], int nelem
)
1047 ULONGLONG idle
, kernel
, user
;
1048 time_t now
= time (NULL
);
1050 /* Store another sample. We ignore samples that are less than 1 sec
1052 if (difftime (now
, samples
[last_idx
].sample_time
) >= 1.0 - 2*DBL_EPSILON
*now
)
1054 sample_system_load (&idle
, &kernel
, &user
);
1055 last_idx
= buf_next (last_idx
);
1056 samples
[last_idx
].sample_time
= now
;
1057 samples
[last_idx
].idle
= idle
;
1058 samples
[last_idx
].kernel
= kernel
;
1059 samples
[last_idx
].user
= user
;
1060 /* If the buffer has more that 15 min worth of samples, discard
1062 if (first_idx
== -1)
1063 first_idx
= last_idx
;
1064 while (first_idx
!= last_idx
1065 && (difftime (now
, samples
[first_idx
].sample_time
)
1066 >= 15.0*60 + 2*DBL_EPSILON
*now
))
1067 first_idx
= buf_next (first_idx
);
1070 for (elem
= 0; elem
< nelem
; elem
++)
1072 double avg
= getavg (elem
);
1076 loadavg
[elem
] = avg
;
1082 /* Emulate getpwuid, getpwnam and others. */
1084 #define PASSWD_FIELD_SIZE 256
1086 static char dflt_passwd_name
[PASSWD_FIELD_SIZE
];
1087 static char dflt_passwd_passwd
[PASSWD_FIELD_SIZE
];
1088 static char dflt_passwd_gecos
[PASSWD_FIELD_SIZE
];
1089 static char dflt_passwd_dir
[PASSWD_FIELD_SIZE
];
1090 static char dflt_passwd_shell
[PASSWD_FIELD_SIZE
];
1092 static struct passwd dflt_passwd
=
1104 static char dflt_group_name
[GNLEN
+1];
1106 static struct group dflt_group
=
1108 /* When group information is not available, we return this as the
1109 group for all files. */
1117 return dflt_passwd
.pw_uid
;
1123 /* I could imagine arguing for checking to see whether the user is
1124 in the Administrators group and returning a UID of 0 for that
1125 case, but I don't know how wise that would be in the long run. */
1132 return dflt_passwd
.pw_gid
;
1142 getpwuid (unsigned uid
)
1144 if (uid
== dflt_passwd
.pw_uid
)
1145 return &dflt_passwd
;
1150 getgrgid (gid_t gid
)
1156 getpwnam (char *name
)
1160 pw
= getpwuid (getuid ());
1164 if (xstrcasecmp (name
, pw
->pw_name
))
1171 init_user_info (void)
1173 /* Find the user's real name by opening the process token and
1174 looking up the name associated with the user-sid in that token.
1176 Use the relative portion of the identifier authority value from
1177 the user-sid as the user id value (same for group id using the
1178 primary group sid from the process token). */
1180 char uname
[UNLEN
+1], gname
[GNLEN
+1], domain
[1025];
1181 DWORD ulength
= sizeof (uname
), dlength
= sizeof (domain
), needed
;
1182 DWORD glength
= sizeof (gname
);
1183 HANDLE token
= NULL
;
1184 SID_NAME_USE user_type
;
1185 unsigned char *buf
= NULL
;
1187 TOKEN_USER user_token
;
1188 TOKEN_PRIMARY_GROUP group_token
;
1191 result
= open_process_token (GetCurrentProcess (), TOKEN_QUERY
, &token
);
1194 result
= get_token_information (token
, TokenUser
, NULL
, 0, &blen
);
1195 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
1197 buf
= xmalloc (blen
);
1198 result
= get_token_information (token
, TokenUser
,
1199 (LPVOID
)buf
, blen
, &needed
);
1202 memcpy (&user_token
, buf
, sizeof (user_token
));
1203 result
= lookup_account_sid (NULL
, user_token
.User
.Sid
,
1205 domain
, &dlength
, &user_type
);
1213 strcpy (dflt_passwd
.pw_name
, uname
);
1214 /* Determine a reasonable uid value. */
1215 if (xstrcasecmp ("administrator", uname
) == 0)
1217 dflt_passwd
.pw_uid
= 500; /* well-known Administrator uid */
1218 dflt_passwd
.pw_gid
= 513; /* well-known None gid */
1222 /* Use the last sub-authority value of the RID, the relative
1223 portion of the SID, as user/group ID. */
1224 dflt_passwd
.pw_uid
= get_rid (user_token
.User
.Sid
);
1226 /* Get group id and name. */
1227 result
= get_token_information (token
, TokenPrimaryGroup
,
1228 (LPVOID
)buf
, blen
, &needed
);
1229 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
1231 buf
= xrealloc (buf
, blen
= needed
);
1232 result
= get_token_information (token
, TokenPrimaryGroup
,
1233 (LPVOID
)buf
, blen
, &needed
);
1237 memcpy (&group_token
, buf
, sizeof (group_token
));
1238 dflt_passwd
.pw_gid
= get_rid (group_token
.PrimaryGroup
);
1239 dlength
= sizeof (domain
);
1240 /* If we can get at the real Primary Group name, use that.
1241 Otherwise, the default group name was already set to
1242 "None" in globals_of_w32. */
1243 if (lookup_account_sid (NULL
, group_token
.PrimaryGroup
,
1244 gname
, &glength
, NULL
, &dlength
,
1246 strcpy (dflt_group_name
, gname
);
1249 dflt_passwd
.pw_gid
= dflt_passwd
.pw_uid
;
1252 /* If security calls are not supported (presumably because we
1253 are running under Windows 9X), fallback to this: */
1254 else if (GetUserName (uname
, &ulength
))
1256 strcpy (dflt_passwd
.pw_name
, uname
);
1257 if (xstrcasecmp ("administrator", uname
) == 0)
1258 dflt_passwd
.pw_uid
= 0;
1260 dflt_passwd
.pw_uid
= 123;
1261 dflt_passwd
.pw_gid
= dflt_passwd
.pw_uid
;
1265 strcpy (dflt_passwd
.pw_name
, "unknown");
1266 dflt_passwd
.pw_uid
= 123;
1267 dflt_passwd
.pw_gid
= 123;
1269 dflt_group
.gr_gid
= dflt_passwd
.pw_gid
;
1271 /* Ensure HOME and SHELL are defined. */
1272 if (getenv ("HOME") == NULL
)
1274 if (getenv ("SHELL") == NULL
)
1277 /* Set dir and shell from environment variables. */
1278 strcpy (dflt_passwd
.pw_dir
, getenv ("HOME"));
1279 strcpy (dflt_passwd
.pw_shell
, getenv ("SHELL"));
1283 CloseHandle (token
);
1289 /* rand () on NT gives us 15 random bits...hack together 30 bits. */
1290 return ((rand () << 15) | rand ());
1300 /* Normalize filename by converting all path separators to
1301 the specified separator. Also conditionally convert upper
1302 case path name components to lower case. */
1305 normalize_filename (register char *fp
, char path_sep
)
1310 /* Always lower-case drive letters a-z, even if the filesystem
1311 preserves case in filenames.
1312 This is so filenames can be compared by string comparison
1313 functions that are case-sensitive. Even case-preserving filesystems
1314 do not distinguish case in drive letters. */
1315 if (fp
[1] == ':' && *fp
>= 'A' && *fp
<= 'Z')
1321 if (NILP (Vw32_downcase_file_names
))
1325 if (*fp
== '/' || *fp
== '\\')
1332 sep
= path_sep
; /* convert to this path separator */
1333 elem
= fp
; /* start of current path element */
1336 if (*fp
>= 'a' && *fp
<= 'z')
1337 elem
= 0; /* don't convert this element */
1339 if (*fp
== 0 || *fp
== ':')
1341 sep
= *fp
; /* restore current separator (or 0) */
1342 *fp
= '/'; /* after conversion of this element */
1345 if (*fp
== '/' || *fp
== '\\')
1347 if (elem
&& elem
!= fp
)
1349 *fp
= 0; /* temporary end of string */
1350 _strlwr (elem
); /* while we convert to lower case */
1352 *fp
= sep
; /* convert (or restore) path separator */
1353 elem
= fp
+ 1; /* next element starts after separator */
1359 /* Destructively turn backslashes into slashes. */
1361 dostounix_filename (register char *p
)
1363 normalize_filename (p
, '/');
1366 /* Destructively turn slashes into backslashes. */
1368 unixtodos_filename (register char *p
)
1370 normalize_filename (p
, '\\');
1373 /* Remove all CR's that are followed by a LF.
1374 (From msdos.c...probably should figure out a way to share it,
1375 although this code isn't going to ever change.) */
1377 crlf_to_lf (register int n
, register unsigned char *buf
)
1379 unsigned char *np
= buf
;
1380 unsigned char *startp
= buf
;
1381 unsigned char *endp
= buf
+ n
;
1385 while (buf
< endp
- 1)
1389 if (*(++buf
) != 0x0a)
1400 /* Parse the root part of file name, if present. Return length and
1401 optionally store pointer to char after root. */
1403 parse_root (char * name
, char ** pPath
)
1405 char * start
= name
;
1410 /* find the root name of the volume if given */
1411 if (isalpha (name
[0]) && name
[1] == ':')
1413 /* skip past drive specifier */
1415 if (IS_DIRECTORY_SEP (name
[0]))
1418 else if (IS_DIRECTORY_SEP (name
[0]) && IS_DIRECTORY_SEP (name
[1]))
1424 if (IS_DIRECTORY_SEP (*name
) && --slashes
== 0)
1429 if (IS_DIRECTORY_SEP (name
[0]))
1436 return name
- start
;
1439 /* Get long base name for name; name is assumed to be absolute. */
1441 get_long_basename (char * name
, char * buf
, int size
)
1443 WIN32_FIND_DATA find_data
;
1447 /* must be valid filename, no wild cards or other invalid characters */
1448 if (_mbspbrk (name
, "*?|<>\""))
1451 dir_handle
= FindFirstFile (name
, &find_data
);
1452 if (dir_handle
!= INVALID_HANDLE_VALUE
)
1454 if ((len
= strlen (find_data
.cFileName
)) < size
)
1455 memcpy (buf
, find_data
.cFileName
, len
+ 1);
1458 FindClose (dir_handle
);
1463 /* Get long name for file, if possible (assumed to be absolute). */
1465 w32_get_long_filename (char * name
, char * buf
, int size
)
1470 char full
[ MAX_PATH
];
1473 len
= strlen (name
);
1474 if (len
>= MAX_PATH
)
1477 /* Use local copy for destructive modification. */
1478 memcpy (full
, name
, len
+1);
1479 unixtodos_filename (full
);
1481 /* Copy root part verbatim. */
1482 len
= parse_root (full
, &p
);
1483 memcpy (o
, full
, len
);
1488 while (p
!= NULL
&& *p
)
1491 p
= strchr (q
, '\\');
1493 len
= get_long_basename (full
, o
, size
);
1516 is_unc_volume (const char *filename
)
1518 const char *ptr
= filename
;
1520 if (!IS_DIRECTORY_SEP (ptr
[0]) || !IS_DIRECTORY_SEP (ptr
[1]) || !ptr
[2])
1523 if (_mbspbrk (ptr
+ 2, "*?|<>\"\\/"))
1529 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
1532 w32_get_resource (char *key
, LPDWORD lpdwtype
)
1535 HKEY hrootkey
= NULL
;
1538 /* Check both the current user and the local machine to see if
1539 we have any resources. */
1541 if (RegOpenKeyEx (HKEY_CURRENT_USER
, REG_ROOT
, 0, KEY_READ
, &hrootkey
) == ERROR_SUCCESS
)
1545 if (RegQueryValueEx (hrootkey
, key
, NULL
, NULL
, NULL
, &cbData
) == ERROR_SUCCESS
1546 && (lpvalue
= xmalloc (cbData
)) != NULL
1547 && RegQueryValueEx (hrootkey
, key
, NULL
, lpdwtype
, lpvalue
, &cbData
) == ERROR_SUCCESS
)
1549 RegCloseKey (hrootkey
);
1555 RegCloseKey (hrootkey
);
1558 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE
, REG_ROOT
, 0, KEY_READ
, &hrootkey
) == ERROR_SUCCESS
)
1562 if (RegQueryValueEx (hrootkey
, key
, NULL
, NULL
, NULL
, &cbData
) == ERROR_SUCCESS
1563 && (lpvalue
= xmalloc (cbData
)) != NULL
1564 && RegQueryValueEx (hrootkey
, key
, NULL
, lpdwtype
, lpvalue
, &cbData
) == ERROR_SUCCESS
)
1566 RegCloseKey (hrootkey
);
1572 RegCloseKey (hrootkey
);
1578 char *get_emacs_configuration (void);
1581 init_environment (char ** argv
)
1583 static const char * const tempdirs
[] = {
1584 "$TMPDIR", "$TEMP", "$TMP", "c:/"
1589 const int imax
= sizeof (tempdirs
) / sizeof (tempdirs
[0]);
1591 /* Make sure they have a usable $TMPDIR. Many Emacs functions use
1592 temporary files and assume "/tmp" if $TMPDIR is unset, which
1593 will break on DOS/Windows. Refuse to work if we cannot find
1594 a directory, not even "c:/", usable for that purpose. */
1595 for (i
= 0; i
< imax
; i
++)
1597 const char *tmp
= tempdirs
[i
];
1600 tmp
= getenv (tmp
+ 1);
1601 /* Note that `access' can lie to us if the directory resides on a
1602 read-only filesystem, like CD-ROM or a write-protected floppy.
1603 The only way to be really sure is to actually create a file and
1604 see if it succeeds. But I think that's too much to ask. */
1606 /* MSVCRT's _access crashes with D_OK. */
1607 if (tmp
&& faccessat (AT_FDCWD
, tmp
, D_OK
, AT_EACCESS
) == 0)
1609 char * var
= alloca (strlen (tmp
) + 8);
1610 sprintf (var
, "TMPDIR=%s", tmp
);
1611 _putenv (strdup (var
));
1618 Fcons (build_string ("no usable temporary directories found!!"),
1620 "While setting TMPDIR: ");
1622 /* Check for environment variables and use registry settings if they
1623 don't exist. Fallback on default values where applicable. */
1628 char locale_name
[32];
1629 char default_home
[MAX_PATH
];
1632 static const struct env_entry
1638 /* If the default value is NULL, we will use the value from the
1639 outside environment or the Registry, but will not push the
1640 variable into the Emacs environment if it is defined neither
1641 in the Registry nor in the outside environment. */
1643 {"PRELOAD_WINSOCK", NULL
},
1644 {"emacs_dir", "C:/emacs"},
1645 {"EMACSLOADPATH", NULL
},
1646 {"SHELL", "%emacs_dir%/bin/cmdproxy.exe"},
1647 {"EMACSDATA", NULL
},
1648 {"EMACSPATH", NULL
},
1655 #define N_ENV_VARS sizeof (dflt_envvars)/sizeof (dflt_envvars[0])
1657 /* We need to copy dflt_envvars[] and work on the copy because we
1658 don't want the dumped Emacs to inherit the values of
1659 environment variables we saw during dumping (which could be on
1660 a different system). The defaults above must be left intact. */
1661 struct env_entry env_vars
[N_ENV_VARS
];
1663 for (i
= 0; i
< N_ENV_VARS
; i
++)
1664 env_vars
[i
] = dflt_envvars
[i
];
1666 /* For backwards compatibility, check if a .emacs file exists in C:/
1667 If not, then we can try to default to the appdata directory under the
1668 user's profile, which is more likely to be writable. */
1669 if (!check_existing ("C:/.emacs"))
1671 HRESULT profile_result
;
1672 /* Dynamically load ShGetFolderPath, as it won't exist on versions
1673 of Windows 95 and NT4 that have not been updated to include
1675 ShGetFolderPath_fn get_folder_path
;
1676 get_folder_path
= (ShGetFolderPath_fn
)
1677 GetProcAddress (GetModuleHandle ("shell32.dll"), "SHGetFolderPathA");
1679 if (get_folder_path
!= NULL
)
1681 profile_result
= get_folder_path (NULL
, CSIDL_APPDATA
, NULL
,
1684 /* If we can't get the appdata dir, revert to old behavior. */
1685 if (profile_result
== S_OK
)
1687 env_vars
[0].def_value
= default_home
;
1693 /* Get default locale info and use it for LANG. */
1694 if (GetLocaleInfo (LOCALE_USER_DEFAULT
,
1695 LOCALE_SABBREVLANGNAME
| LOCALE_USE_CP_ACP
,
1696 locale_name
, sizeof (locale_name
)))
1698 for (i
= 0; i
< N_ENV_VARS
; i
++)
1700 if (strcmp (env_vars
[i
].name
, "LANG") == 0)
1702 env_vars
[i
].def_value
= locale_name
;
1708 #define SET_ENV_BUF_SIZE (4 * MAX_PATH) /* to cover EMACSLOADPATH */
1710 /* Treat emacs_dir specially: set it unconditionally based on our
1714 char modname
[MAX_PATH
];
1716 if (!GetModuleFileName (NULL
, modname
, MAX_PATH
))
1718 if ((p
= strrchr (modname
, '\\')) == NULL
)
1722 if ((p
= strrchr (modname
, '\\')) && xstrcasecmp (p
, "\\bin") == 0)
1724 char buf
[SET_ENV_BUF_SIZE
];
1727 for (p
= modname
; *p
; p
++)
1728 if (*p
== '\\') *p
= '/';
1730 _snprintf (buf
, sizeof (buf
)-1, "emacs_dir=%s", modname
);
1731 _putenv (strdup (buf
));
1733 /* Handle running emacs from the build directory: src/oo-spd/i386/ */
1735 /* FIXME: should use substring of get_emacs_configuration ().
1736 But I don't think the Windows build supports alpha, mips etc
1737 anymore, so have taken the easy option for now. */
1738 else if (p
&& (xstrcasecmp (p
, "\\i386") == 0
1739 || xstrcasecmp (p
, "\\AMD64") == 0))
1742 p
= strrchr (modname
, '\\');
1746 p
= strrchr (modname
, '\\');
1747 if (p
&& xstrcasecmp (p
, "\\src") == 0)
1749 char buf
[SET_ENV_BUF_SIZE
];
1752 for (p
= modname
; *p
; p
++)
1753 if (*p
== '\\') *p
= '/';
1755 _snprintf (buf
, sizeof (buf
)-1, "emacs_dir=%s", modname
);
1756 _putenv (strdup (buf
));
1762 for (i
= 0; i
< N_ENV_VARS
; i
++)
1764 if (!getenv (env_vars
[i
].name
))
1768 if ((lpval
= w32_get_resource (env_vars
[i
].name
, &dwType
)) == NULL
1769 /* Also ignore empty environment variables. */
1773 lpval
= env_vars
[i
].def_value
;
1774 dwType
= REG_EXPAND_SZ
;
1776 if (!strcmp (env_vars
[i
].name
, "HOME") && !appdata
)
1777 Vdelayed_warnings_list
1778 = Fcons (listn (CONSTYPE_HEAP
, 2,
1779 intern ("initialization"),
1780 build_string ("Setting HOME to C:\\ by default is deprecated")),
1781 Vdelayed_warnings_list
);
1786 char buf1
[SET_ENV_BUF_SIZE
], buf2
[SET_ENV_BUF_SIZE
];
1788 if (dwType
== REG_EXPAND_SZ
)
1789 ExpandEnvironmentStrings ((LPSTR
) lpval
, buf1
, sizeof (buf1
));
1790 else if (dwType
== REG_SZ
)
1791 strcpy (buf1
, lpval
);
1792 if (dwType
== REG_EXPAND_SZ
|| dwType
== REG_SZ
)
1794 _snprintf (buf2
, sizeof (buf2
)-1, "%s=%s", env_vars
[i
].name
,
1796 _putenv (strdup (buf2
));
1806 /* Rebuild system configuration to reflect invoking system. */
1807 Vsystem_configuration
= build_string (EMACS_CONFIGURATION
);
1809 /* Another special case: on NT, the PATH variable is actually named
1810 "Path" although cmd.exe (perhaps NT itself) arranges for
1811 environment variable lookup and setting to be case insensitive.
1812 However, Emacs assumes a fully case sensitive environment, so we
1813 need to change "Path" to "PATH" to match the expectations of
1814 various elisp packages. We do this by the sneaky method of
1815 modifying the string in the C runtime environ entry.
1817 The same applies to COMSPEC. */
1821 for (envp
= environ
; *envp
; envp
++)
1822 if (_strnicmp (*envp
, "PATH=", 5) == 0)
1823 memcpy (*envp
, "PATH=", 5);
1824 else if (_strnicmp (*envp
, "COMSPEC=", 8) == 0)
1825 memcpy (*envp
, "COMSPEC=", 8);
1828 /* Remember the initial working directory for getwd. */
1829 /* FIXME: Do we need to resolve possible symlinks in startup_dir?
1830 Does it matter anywhere in Emacs? */
1831 if (!GetCurrentDirectory (MAXPATHLEN
, startup_dir
))
1835 static char modname
[MAX_PATH
];
1837 if (!GetModuleFileName (NULL
, modname
, MAX_PATH
))
1842 /* Determine if there is a middle mouse button, to allow parse_button
1843 to decide whether right mouse events should be mouse-2 or
1845 w32_num_mouse_buttons
= GetSystemMetrics (SM_CMOUSEBUTTONS
);
1850 /* Called from expand-file-name when default-directory is not a string. */
1853 emacs_root_dir (void)
1855 static char root_dir
[FILENAME_MAX
];
1858 p
= getenv ("emacs_dir");
1861 strcpy (root_dir
, p
);
1862 root_dir
[parse_root (root_dir
, NULL
)] = '\0';
1863 dostounix_filename (root_dir
);
1867 /* We don't have scripts to automatically determine the system configuration
1868 for Emacs before it's compiled, and we don't want to have to make the
1869 user enter it, so we define EMACS_CONFIGURATION to invoke this runtime
1873 get_emacs_configuration (void)
1875 char *arch
, *oem
, *os
;
1877 static char configuration_buffer
[32];
1879 /* Determine the processor type. */
1880 switch (get_processor_type ())
1883 #ifdef PROCESSOR_INTEL_386
1884 case PROCESSOR_INTEL_386
:
1885 case PROCESSOR_INTEL_486
:
1886 case PROCESSOR_INTEL_PENTIUM
:
1894 #ifdef PROCESSOR_AMD_X8664
1895 case PROCESSOR_AMD_X8664
:
1900 #ifdef PROCESSOR_MIPS_R2000
1901 case PROCESSOR_MIPS_R2000
:
1902 case PROCESSOR_MIPS_R3000
:
1903 case PROCESSOR_MIPS_R4000
:
1908 #ifdef PROCESSOR_ALPHA_21064
1909 case PROCESSOR_ALPHA_21064
:
1919 /* Use the OEM field to reflect the compiler/library combination. */
1921 #define COMPILER_NAME "msvc"
1924 #define COMPILER_NAME "mingw"
1926 #define COMPILER_NAME "unknown"
1929 oem
= COMPILER_NAME
;
1931 switch (osinfo_cache
.dwPlatformId
) {
1932 case VER_PLATFORM_WIN32_NT
:
1934 build_num
= osinfo_cache
.dwBuildNumber
;
1936 case VER_PLATFORM_WIN32_WINDOWS
:
1937 if (osinfo_cache
.dwMinorVersion
== 0) {
1942 build_num
= LOWORD (osinfo_cache
.dwBuildNumber
);
1944 case VER_PLATFORM_WIN32s
:
1945 /* Not supported, should not happen. */
1947 build_num
= LOWORD (osinfo_cache
.dwBuildNumber
);
1955 if (osinfo_cache
.dwPlatformId
== VER_PLATFORM_WIN32_NT
) {
1956 sprintf (configuration_buffer
, "%s-%s-%s%d.%d.%d", arch
, oem
, os
,
1957 get_w32_major_version (), get_w32_minor_version (), build_num
);
1959 sprintf (configuration_buffer
, "%s-%s-%s.%d", arch
, oem
, os
, build_num
);
1962 return configuration_buffer
;
1966 get_emacs_configuration_options (void)
1968 static char *options_buffer
;
1969 char cv
[32]; /* Enough for COMPILER_VERSION. */
1971 cv
, /* To be filled later. */
1975 #ifdef ENABLE_CHECKING
1976 " --enable-checking",
1978 /* configure.bat already sets USER_CFLAGS and USER_LDFLAGS
1979 with a starting space to save work here. */
1981 " --cflags", USER_CFLAGS
,
1984 " --ldflags", USER_LDFLAGS
,
1991 /* Work out the effective configure options for this build. */
1993 #define COMPILER_VERSION "--with-msvc (%d.%02d)", _MSC_VER / 100, _MSC_VER % 100
1996 #define COMPILER_VERSION "--with-gcc (%d.%d)", __GNUC__, __GNUC_MINOR__
1998 #define COMPILER_VERSION ""
2002 if (_snprintf (cv
, sizeof (cv
) - 1, COMPILER_VERSION
) < 0)
2003 return "Error: not enough space for compiler version";
2004 cv
[sizeof (cv
) - 1] = '\0';
2006 for (i
= 0; options
[i
]; i
++)
2007 size
+= strlen (options
[i
]);
2009 options_buffer
= xmalloc (size
+ 1);
2010 options_buffer
[0] = '\0';
2012 for (i
= 0; options
[i
]; i
++)
2013 strcat (options_buffer
, options
[i
]);
2015 return options_buffer
;
2019 #include <sys/timeb.h>
2021 /* Emulate gettimeofday (Ulrich Leodolter, 1/11/95). */
2023 gettimeofday (struct timeval
*tv
, struct timezone
*tz
)
2028 tv
->tv_sec
= tb
.time
;
2029 tv
->tv_usec
= tb
.millitm
* 1000L;
2030 /* Implementation note: _ftime sometimes doesn't update the dstflag
2031 according to the new timezone when the system timezone is
2032 changed. We could fix that by using GetSystemTime and
2033 GetTimeZoneInformation, but that doesn't seem necessary, since
2034 Emacs always calls gettimeofday with the 2nd argument NULL (see
2035 current_emacs_time). */
2038 tz
->tz_minuteswest
= tb
.timezone
; /* minutes west of Greenwich */
2039 tz
->tz_dsttime
= tb
.dstflag
; /* type of dst correction */
2043 /* Emulate fdutimens. */
2045 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2046 TIMESPEC[0] and TIMESPEC[1], respectively.
2047 FD must be either negative -- in which case it is ignored --
2048 or a file descriptor that is open on FILE.
2049 If FD is nonnegative, then FILE can be NULL, which means
2050 use just futimes instead of utimes.
2051 If TIMESPEC is null, FAIL.
2052 Return 0 on success, -1 (setting errno) on failure. */
2055 fdutimens (int fd
, char const *file
, struct timespec
const timespec
[2])
2064 if (fd
< 0 && !file
)
2069 ut
.actime
= timespec
[0].tv_sec
;
2070 ut
.modtime
= timespec
[1].tv_sec
;
2072 return _futime (fd
, &ut
);
2074 return _utime (file
, &ut
);
2078 /* ------------------------------------------------------------------------- */
2079 /* IO support and wrapper functions for the Windows API. */
2080 /* ------------------------------------------------------------------------- */
2082 /* Place a wrapper around the MSVC version of ctime. It returns NULL
2083 on network directories, so we handle that case here.
2084 (Ulrich Leodolter, 1/11/95). */
2086 sys_ctime (const time_t *t
)
2088 char *str
= (char *) ctime (t
);
2089 return (str
? str
: "Sun Jan 01 00:00:00 1970");
2092 /* Emulate sleep...we could have done this with a define, but that
2093 would necessitate including windows.h in the files that used it.
2094 This is much easier. */
2096 sys_sleep (int seconds
)
2098 Sleep (seconds
* 1000);
2101 /* Internal MSVC functions for low-level descriptor munging */
2102 extern int __cdecl
_set_osfhnd (int fd
, long h
);
2103 extern int __cdecl
_free_osfhnd (int fd
);
2105 /* parallel array of private info on file handles */
2106 filedesc fd_info
[ MAXDESC
];
2108 typedef struct volume_info_data
{
2109 struct volume_info_data
* next
;
2111 /* time when info was obtained */
2114 /* actual volume info */
2123 /* Global referenced by various functions. */
2124 static volume_info_data volume_info
;
2126 /* Vector to indicate which drives are local and fixed (for which cached
2127 data never expires). */
2128 static BOOL fixed_drives
[26];
2130 /* Consider cached volume information to be stale if older than 10s,
2131 at least for non-local drives. Info for fixed drives is never stale. */
2132 #define DRIVE_INDEX( c ) ( (c) <= 'Z' ? (c) - 'A' : (c) - 'a' )
2133 #define VOLINFO_STILL_VALID( root_dir, info ) \
2134 ( ( isalpha (root_dir[0]) && \
2135 fixed_drives[ DRIVE_INDEX (root_dir[0]) ] ) \
2136 || GetTickCount () - info->timestamp < 10000 )
2138 /* Cache support functions. */
2140 /* Simple linked list with linear search is sufficient. */
2141 static volume_info_data
*volume_cache
= NULL
;
2143 static volume_info_data
*
2144 lookup_volume_info (char * root_dir
)
2146 volume_info_data
* info
;
2148 for (info
= volume_cache
; info
; info
= info
->next
)
2149 if (xstrcasecmp (info
->root_dir
, root_dir
) == 0)
2155 add_volume_info (char * root_dir
, volume_info_data
* info
)
2157 info
->root_dir
= xstrdup (root_dir
);
2158 info
->next
= volume_cache
;
2159 volume_cache
= info
;
2163 /* Wrapper for GetVolumeInformation, which uses caching to avoid
2164 performance penalty (~2ms on 486 for local drives, 7.5ms for local
2165 cdrom drive, ~5-10ms or more for remote drives on LAN). */
2166 static volume_info_data
*
2167 GetCachedVolumeInformation (char * root_dir
)
2169 volume_info_data
* info
;
2170 char default_root
[ MAX_PATH
];
2172 /* NULL for root_dir means use root from current directory. */
2173 if (root_dir
== NULL
)
2175 if (GetCurrentDirectory (MAX_PATH
, default_root
) == 0)
2177 parse_root (default_root
, &root_dir
);
2179 root_dir
= default_root
;
2182 /* Local fixed drives can be cached permanently. Removable drives
2183 cannot be cached permanently, since the volume name and serial
2184 number (if nothing else) can change. Remote drives should be
2185 treated as if they are removable, since there is no sure way to
2186 tell whether they are or not. Also, the UNC association of drive
2187 letters mapped to remote volumes can be changed at any time (even
2188 by other processes) without notice.
2190 As a compromise, so we can benefit from caching info for remote
2191 volumes, we use a simple expiry mechanism to invalidate cache
2192 entries that are more than ten seconds old. */
2195 /* No point doing this, because WNetGetConnection is even slower than
2196 GetVolumeInformation, consistently taking ~50ms on a 486 (FWIW,
2197 GetDriveType is about the only call of this type which does not
2198 involve network access, and so is extremely quick). */
2200 /* Map drive letter to UNC if remote. */
2201 if (isalpha (root_dir
[0]) && !fixed
[DRIVE_INDEX (root_dir
[0])])
2203 char remote_name
[ 256 ];
2204 char drive
[3] = { root_dir
[0], ':' };
2206 if (WNetGetConnection (drive
, remote_name
, sizeof (remote_name
))
2208 /* do something */ ;
2212 info
= lookup_volume_info (root_dir
);
2214 if (info
== NULL
|| ! VOLINFO_STILL_VALID (root_dir
, info
))
2222 /* Info is not cached, or is stale. */
2223 if (!GetVolumeInformation (root_dir
,
2224 name
, sizeof (name
),
2228 type
, sizeof (type
)))
2231 /* Cache the volume information for future use, overwriting existing
2232 entry if present. */
2235 info
= xmalloc (sizeof (volume_info_data
));
2236 add_volume_info (root_dir
, info
);
2244 info
->name
= xstrdup (name
);
2245 info
->serialnum
= serialnum
;
2246 info
->maxcomp
= maxcomp
;
2247 info
->flags
= flags
;
2248 info
->type
= xstrdup (type
);
2249 info
->timestamp
= GetTickCount ();
2255 /* Get information on the volume where NAME is held; set path pointer to
2256 start of pathname in NAME (past UNC header\volume header if present),
2257 if pPath is non-NULL.
2259 Note: if NAME includes symlinks, the information is for the volume
2260 of the symlink, not of its target. That's because, even though
2261 GetVolumeInformation returns information about the symlink target
2262 of its argument, we only pass the root directory to
2263 GetVolumeInformation, not the full NAME. */
2265 get_volume_info (const char * name
, const char ** pPath
)
2267 char temp
[MAX_PATH
];
2268 char *rootname
= NULL
; /* default to current volume */
2269 volume_info_data
* info
;
2274 /* Find the root name of the volume if given. */
2275 if (isalpha (name
[0]) && name
[1] == ':')
2283 else if (IS_DIRECTORY_SEP (name
[0]) && IS_DIRECTORY_SEP (name
[1]))
2290 if (IS_DIRECTORY_SEP (*name
) && --slashes
== 0)
2303 info
= GetCachedVolumeInformation (rootname
);
2306 /* Set global referenced by other functions. */
2307 volume_info
= *info
;
2313 /* Determine if volume is FAT format (ie. only supports short 8.3
2314 names); also set path pointer to start of pathname in name, if
2315 pPath is non-NULL. */
2317 is_fat_volume (const char * name
, const char ** pPath
)
2319 if (get_volume_info (name
, pPath
))
2320 return (volume_info
.maxcomp
== 12);
2324 /* Map filename to a valid 8.3 name if necessary.
2325 The result is a pointer to a static buffer, so CAVEAT EMPTOR! */
2327 map_w32_filename (const char * name
, const char ** pPath
)
2329 static char shortname
[MAX_PATH
];
2330 char * str
= shortname
;
2333 const char * save_name
= name
;
2335 if (strlen (name
) >= MAX_PATH
)
2337 /* Return a filename which will cause callers to fail. */
2338 strcpy (shortname
, "?");
2342 if (is_fat_volume (name
, (const char **)&path
)) /* truncate to 8.3 */
2344 register int left
= 8; /* maximum number of chars in part */
2345 register int extn
= 0; /* extension added? */
2346 register int dots
= 2; /* maximum number of dots allowed */
2349 *str
++ = *name
++; /* skip past UNC header */
2351 while ((c
= *name
++))
2358 *str
++ = (c
== ':' ? ':' : '\\');
2359 extn
= 0; /* reset extension flags */
2360 dots
= 2; /* max 2 dots */
2361 left
= 8; /* max length 8 for main part */
2366 /* Convert path components of the form .xxx to _xxx,
2367 but leave . and .. as they are. This allows .emacs
2368 to be read as _emacs, for example. */
2372 IS_DIRECTORY_SEP (*name
))
2387 extn
= 1; /* we've got an extension */
2388 left
= 3; /* 3 chars in extension */
2392 /* any embedded dots after the first are converted to _ */
2397 case '#': /* don't lose these, they're important */
2399 str
[-1] = c
; /* replace last character of part */
2404 *str
++ = tolower (c
); /* map to lower case (looks nicer) */
2406 dots
= 0; /* started a path component */
2415 strcpy (shortname
, name
);
2416 unixtodos_filename (shortname
);
2420 *pPath
= shortname
+ (path
- save_name
);
2426 is_exec (const char * name
)
2428 char * p
= strrchr (name
, '.');
2431 && (xstrcasecmp (p
, ".exe") == 0 ||
2432 xstrcasecmp (p
, ".com") == 0 ||
2433 xstrcasecmp (p
, ".bat") == 0 ||
2434 xstrcasecmp (p
, ".cmd") == 0));
2437 /* Emulate the Unix directory procedures opendir, closedir,
2438 and readdir. We can't use the procedures supplied in sysdep.c,
2439 so we provide them here. */
2441 struct direct dir_static
; /* simulated directory contents */
2442 static HANDLE dir_find_handle
= INVALID_HANDLE_VALUE
;
2443 static int dir_is_fat
;
2444 static char dir_pathname
[MAXPATHLEN
+1];
2445 static WIN32_FIND_DATA dir_find_data
;
2447 /* Support shares on a network resource as subdirectories of a read-only
2449 static HANDLE wnet_enum_handle
= INVALID_HANDLE_VALUE
;
2450 static HANDLE
open_unc_volume (const char *);
2451 static char *read_unc_volume (HANDLE
, char *, int);
2452 static void close_unc_volume (HANDLE
);
2455 opendir (char *filename
)
2459 /* Opening is done by FindFirstFile. However, a read is inherent to
2460 this operation, so we defer the open until read time. */
2462 if (dir_find_handle
!= INVALID_HANDLE_VALUE
)
2464 if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
2467 /* Note: We don't support traversal of UNC volumes via symlinks.
2468 Doing so would mean punishing 99.99% of use cases by resolving
2469 all the possible symlinks in FILENAME, recursively. */
2470 if (is_unc_volume (filename
))
2472 wnet_enum_handle
= open_unc_volume (filename
);
2473 if (wnet_enum_handle
== INVALID_HANDLE_VALUE
)
2477 if (!(dirp
= (DIR *) malloc (sizeof (DIR))))
2484 strncpy (dir_pathname
, map_w32_filename (filename
, NULL
), MAXPATHLEN
);
2485 dir_pathname
[MAXPATHLEN
] = '\0';
2486 /* Note: We don't support symlinks to file names on FAT volumes.
2487 Doing so would mean punishing 99.99% of use cases by resolving
2488 all the possible symlinks in FILENAME, recursively. */
2489 dir_is_fat
= is_fat_volume (filename
, NULL
);
2495 closedir (DIR *dirp
)
2497 /* If we have a find-handle open, close it. */
2498 if (dir_find_handle
!= INVALID_HANDLE_VALUE
)
2500 FindClose (dir_find_handle
);
2501 dir_find_handle
= INVALID_HANDLE_VALUE
;
2503 else if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
2505 close_unc_volume (wnet_enum_handle
);
2506 wnet_enum_handle
= INVALID_HANDLE_VALUE
;
2508 xfree ((char *) dirp
);
2514 int downcase
= !NILP (Vw32_downcase_file_names
);
2516 if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
2518 if (!read_unc_volume (wnet_enum_handle
,
2519 dir_find_data
.cFileName
,
2523 /* If we aren't dir_finding, do a find-first, otherwise do a find-next. */
2524 else if (dir_find_handle
== INVALID_HANDLE_VALUE
)
2526 char filename
[MAXNAMLEN
+ 3];
2529 strcpy (filename
, dir_pathname
);
2530 ln
= strlen (filename
) - 1;
2531 if (!IS_DIRECTORY_SEP (filename
[ln
]))
2532 strcat (filename
, "\\");
2533 strcat (filename
, "*");
2535 /* Note: No need to resolve symlinks in FILENAME, because
2536 FindFirst opens the directory that is the target of a
2538 dir_find_handle
= FindFirstFile (filename
, &dir_find_data
);
2540 if (dir_find_handle
== INVALID_HANDLE_VALUE
)
2545 if (!FindNextFile (dir_find_handle
, &dir_find_data
))
2549 /* Emacs never uses this value, so don't bother making it match
2550 value returned by stat(). */
2551 dir_static
.d_ino
= 1;
2553 strcpy (dir_static
.d_name
, dir_find_data
.cFileName
);
2555 /* If the file name in cFileName[] includes `?' characters, it means
2556 the original file name used characters that cannot be represented
2557 by the current ANSI codepage. To avoid total lossage, retrieve
2558 the short 8+3 alias of the long file name. */
2559 if (_mbspbrk (dir_static
.d_name
, "?"))
2561 strcpy (dir_static
.d_name
, dir_find_data
.cAlternateFileName
);
2562 downcase
= 1; /* 8+3 aliases are returned in all caps */
2564 dir_static
.d_namlen
= strlen (dir_static
.d_name
);
2565 dir_static
.d_reclen
= sizeof (struct direct
) - MAXNAMLEN
+ 3 +
2566 dir_static
.d_namlen
- dir_static
.d_namlen
% 4;
2568 /* If the file name in cFileName[] includes `?' characters, it means
2569 the original file name used characters that cannot be represented
2570 by the current ANSI codepage. To avoid total lossage, retrieve
2571 the short 8+3 alias of the long file name. */
2572 if (_mbspbrk (dir_find_data
.cFileName
, "?"))
2574 strcpy (dir_static
.d_name
, dir_find_data
.cAlternateFileName
);
2575 /* 8+3 aliases are returned in all caps, which could break
2576 various alists that look at filenames' extensions. */
2580 strcpy (dir_static
.d_name
, dir_find_data
.cFileName
);
2581 dir_static
.d_namlen
= strlen (dir_static
.d_name
);
2583 _strlwr (dir_static
.d_name
);
2587 for (p
= dir_static
.d_name
; *p
; p
++)
2588 if (*p
>= 'a' && *p
<= 'z')
2591 _strlwr (dir_static
.d_name
);
2598 open_unc_volume (const char *path
)
2604 nr
.dwScope
= RESOURCE_GLOBALNET
;
2605 nr
.dwType
= RESOURCETYPE_DISK
;
2606 nr
.dwDisplayType
= RESOURCEDISPLAYTYPE_SERVER
;
2607 nr
.dwUsage
= RESOURCEUSAGE_CONTAINER
;
2608 nr
.lpLocalName
= NULL
;
2609 nr
.lpRemoteName
= (LPSTR
)map_w32_filename (path
, NULL
);
2610 nr
.lpComment
= NULL
;
2611 nr
.lpProvider
= NULL
;
2613 result
= WNetOpenEnum (RESOURCE_GLOBALNET
, RESOURCETYPE_DISK
,
2614 RESOURCEUSAGE_CONNECTABLE
, &nr
, &henum
);
2616 if (result
== NO_ERROR
)
2619 return INVALID_HANDLE_VALUE
;
2623 read_unc_volume (HANDLE henum
, char *readbuf
, int size
)
2627 DWORD bufsize
= 512;
2632 buffer
= alloca (bufsize
);
2633 result
= WNetEnumResource (henum
, &count
, buffer
, &bufsize
);
2634 if (result
!= NO_ERROR
)
2637 /* WNetEnumResource returns \\resource\share...skip forward to "share". */
2638 ptr
= ((LPNETRESOURCE
) buffer
)->lpRemoteName
;
2640 while (*ptr
&& !IS_DIRECTORY_SEP (*ptr
)) ptr
++;
2643 strncpy (readbuf
, ptr
, size
);
2648 close_unc_volume (HANDLE henum
)
2650 if (henum
!= INVALID_HANDLE_VALUE
)
2651 WNetCloseEnum (henum
);
2655 unc_volume_file_attributes (const char *path
)
2660 henum
= open_unc_volume (path
);
2661 if (henum
== INVALID_HANDLE_VALUE
)
2664 attrs
= FILE_ATTRIBUTE_READONLY
| FILE_ATTRIBUTE_DIRECTORY
;
2666 close_unc_volume (henum
);
2671 /* Ensure a network connection is authenticated. */
2673 logon_network_drive (const char *path
)
2675 NETRESOURCE resource
;
2676 char share
[MAX_PATH
];
2681 if (IS_DIRECTORY_SEP (path
[0]) && IS_DIRECTORY_SEP (path
[1]))
2682 drvtype
= DRIVE_REMOTE
;
2683 else if (path
[0] == '\0' || path
[1] != ':')
2684 drvtype
= GetDriveType (NULL
);
2691 drvtype
= GetDriveType (drive
);
2694 /* Only logon to networked drives. */
2695 if (drvtype
!= DRIVE_REMOTE
)
2699 strncpy (share
, path
, MAX_PATH
);
2700 /* Truncate to just server and share name. */
2701 for (i
= 2; i
< MAX_PATH
; i
++)
2703 if (IS_DIRECTORY_SEP (share
[i
]) && ++n_slashes
> 3)
2710 resource
.dwType
= RESOURCETYPE_DISK
;
2711 resource
.lpLocalName
= NULL
;
2712 resource
.lpRemoteName
= share
;
2713 resource
.lpProvider
= NULL
;
2715 WNetAddConnection2 (&resource
, NULL
, NULL
, CONNECT_INTERACTIVE
);
2718 /* Emulate faccessat(2). */
2720 faccessat (int dirfd
, const char * path
, int mode
, int flags
)
2724 if (dirfd
!= AT_FDCWD
2725 && !(IS_DIRECTORY_SEP (path
[0])
2726 || IS_DEVICE_SEP (path
[1])))
2732 /* MSVCRT implementation of 'access' doesn't recognize D_OK, and its
2733 newer versions blow up when passed D_OK. */
2734 path
= map_w32_filename (path
, NULL
);
2735 /* If the last element of PATH is a symlink, we need to resolve it
2736 to get the attributes of its target file. Note: any symlinks in
2737 PATH elements other than the last one are transparently resolved
2738 by GetFileAttributes below. */
2739 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) != 0
2740 && (flags
& AT_SYMLINK_NOFOLLOW
) == 0)
2741 path
= chase_symlinks (path
);
2743 if ((attributes
= GetFileAttributes (path
)) == -1)
2745 DWORD w32err
= GetLastError ();
2749 case ERROR_INVALID_NAME
:
2750 case ERROR_BAD_PATHNAME
:
2751 if (is_unc_volume (path
))
2753 attributes
= unc_volume_file_attributes (path
);
2754 if (attributes
== -1)
2762 case ERROR_FILE_NOT_FOUND
:
2763 case ERROR_BAD_NETPATH
:
2772 if ((mode
& X_OK
) != 0
2773 && !(is_exec (path
) || (attributes
& FILE_ATTRIBUTE_DIRECTORY
) != 0))
2778 if ((mode
& W_OK
) != 0 && (attributes
& FILE_ATTRIBUTE_READONLY
) != 0)
2783 if ((mode
& D_OK
) != 0 && (attributes
& FILE_ATTRIBUTE_DIRECTORY
) == 0)
2791 /* Shadow some MSVC runtime functions to map requests for long filenames
2792 to reasonable short names if necessary. This was originally added to
2793 permit running Emacs on NT 3.1 on a FAT partition, which doesn't support
2797 sys_chdir (const char * path
)
2799 return _chdir (map_w32_filename (path
, NULL
));
2803 sys_chmod (const char * path
, int mode
)
2805 path
= chase_symlinks (map_w32_filename (path
, NULL
));
2806 return _chmod (path
, mode
);
2810 sys_chown (const char *path
, uid_t owner
, gid_t group
)
2812 if (sys_chmod (path
, S_IREAD
) == -1) /* check if file exists */
2818 sys_creat (const char * path
, int mode
)
2820 return _creat (map_w32_filename (path
, NULL
), mode
);
2824 sys_fopen (const char * path
, const char * mode
)
2828 const char * mode_save
= mode
;
2830 /* Force all file handles to be non-inheritable. This is necessary to
2831 ensure child processes don't unwittingly inherit handles that might
2832 prevent future file access. */
2836 else if (mode
[0] == 'w' || mode
[0] == 'a')
2837 oflag
= O_WRONLY
| O_CREAT
| O_TRUNC
;
2841 /* Only do simplistic option parsing. */
2845 oflag
&= ~(O_RDONLY
| O_WRONLY
);
2848 else if (mode
[0] == 'b')
2853 else if (mode
[0] == 't')
2860 fd
= _open (map_w32_filename (path
, NULL
), oflag
| _O_NOINHERIT
, 0644);
2864 return _fdopen (fd
, mode_save
);
2867 /* This only works on NTFS volumes, but is useful to have. */
2869 sys_link (const char * old
, const char * new)
2873 char oldname
[MAX_PATH
], newname
[MAX_PATH
];
2875 if (old
== NULL
|| new == NULL
)
2881 strcpy (oldname
, map_w32_filename (old
, NULL
));
2882 strcpy (newname
, map_w32_filename (new, NULL
));
2884 fileh
= CreateFile (oldname
, 0, 0, NULL
, OPEN_EXISTING
,
2885 FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
2886 if (fileh
!= INVALID_HANDLE_VALUE
)
2890 /* Confusingly, the "alternate" stream name field does not apply
2891 when restoring a hard link, and instead contains the actual
2892 stream data for the link (ie. the name of the link to create).
2893 The WIN32_STREAM_ID structure before the cStreamName field is
2894 the stream header, which is then immediately followed by the
2898 WIN32_STREAM_ID wid
;
2899 WCHAR wbuffer
[MAX_PATH
]; /* extra space for link name */
2902 wlen
= MultiByteToWideChar (CP_ACP
, MB_PRECOMPOSED
, newname
, -1,
2903 data
.wid
.cStreamName
, MAX_PATH
);
2906 LPVOID context
= NULL
;
2909 data
.wid
.dwStreamId
= BACKUP_LINK
;
2910 data
.wid
.dwStreamAttributes
= 0;
2911 data
.wid
.Size
.LowPart
= wlen
* sizeof (WCHAR
);
2912 data
.wid
.Size
.HighPart
= 0;
2913 data
.wid
.dwStreamNameSize
= 0;
2915 if (BackupWrite (fileh
, (LPBYTE
)&data
,
2916 offsetof (WIN32_STREAM_ID
, cStreamName
)
2917 + data
.wid
.Size
.LowPart
,
2918 &wbytes
, FALSE
, FALSE
, &context
)
2919 && BackupWrite (fileh
, NULL
, 0, &wbytes
, TRUE
, FALSE
, &context
))
2926 /* Should try mapping GetLastError to errno; for now just
2927 indicate a general error (eg. links not supported). */
2928 errno
= EINVAL
; // perhaps EMLINK?
2932 CloseHandle (fileh
);
2941 sys_mkdir (const char * path
)
2943 return _mkdir (map_w32_filename (path
, NULL
));
2946 /* Because of long name mapping issues, we need to implement this
2947 ourselves. Also, MSVC's _mktemp returns NULL when it can't generate
2948 a unique name, instead of setting the input template to an empty
2951 Standard algorithm seems to be use pid or tid with a letter on the
2952 front (in place of the 6 X's) and cycle through the letters to find a
2953 unique name. We extend that to allow any reasonable character as the
2954 first of the 6 X's. */
2956 sys_mktemp (char * template)
2960 unsigned uid
= GetCurrentThreadId ();
2961 static char first_char
[] = "abcdefghijklmnopqrstuvwyz0123456789!%-_@#";
2963 if (template == NULL
)
2965 p
= template + strlen (template);
2967 /* replace up to the last 5 X's with uid in decimal */
2968 while (--p
>= template && p
[0] == 'X' && --i
>= 0)
2970 p
[0] = '0' + uid
% 10;
2974 if (i
< 0 && p
[0] == 'X')
2979 int save_errno
= errno
;
2980 p
[0] = first_char
[i
];
2981 if (faccessat (AT_FDCWD
, template, F_OK
, AT_EACCESS
) < 0)
2987 while (++i
< sizeof (first_char
));
2990 /* Template is badly formed or else we can't generate a unique name,
2991 so return empty string */
2997 sys_open (const char * path
, int oflag
, int mode
)
2999 const char* mpath
= map_w32_filename (path
, NULL
);
3000 /* Try to open file without _O_CREAT, to be able to write to hidden
3001 and system files. Force all file handles to be
3003 int res
= _open (mpath
, (oflag
& ~_O_CREAT
) | _O_NOINHERIT
, mode
);
3006 return _open (mpath
, oflag
| _O_NOINHERIT
, mode
);
3010 sys_rename (const char * oldname
, const char * newname
)
3013 char temp
[MAX_PATH
];
3017 /* MoveFile on Windows 95 doesn't correctly change the short file name
3018 alias in a number of circumstances (it is not easy to predict when
3019 just by looking at oldname and newname, unfortunately). In these
3020 cases, renaming through a temporary name avoids the problem.
3022 A second problem on Windows 95 is that renaming through a temp name when
3023 newname is uppercase fails (the final long name ends up in
3024 lowercase, although the short alias might be uppercase) UNLESS the
3025 long temp name is not 8.3.
3027 So, on Windows 95 we always rename through a temp name, and we make sure
3028 the temp name has a long extension to ensure correct renaming. */
3030 strcpy (temp
, map_w32_filename (oldname
, NULL
));
3032 /* volume_info is set indirectly by map_w32_filename. */
3033 oldname_dev
= volume_info
.serialnum
;
3035 if (os_subtype
== OS_9X
)
3041 oldname
= map_w32_filename (oldname
, NULL
);
3042 if ((o
= strrchr (oldname
, '\\')))
3045 o
= (char *) oldname
;
3047 if ((p
= strrchr (temp
, '\\')))
3054 /* Force temp name to require a manufactured 8.3 alias - this
3055 seems to make the second rename work properly. */
3056 sprintf (p
, "_.%s.%u", o
, i
);
3058 result
= rename (oldname
, temp
);
3060 /* This loop must surely terminate! */
3061 while (result
< 0 && errno
== EEXIST
);
3066 /* Emulate Unix behavior - newname is deleted if it already exists
3067 (at least if it is a file; don't do this for directories).
3069 Since we mustn't do this if we are just changing the case of the
3070 file name (we would end up deleting the file we are trying to
3071 rename!), we let rename detect if the destination file already
3072 exists - that way we avoid the possible pitfalls of trying to
3073 determine ourselves whether two names really refer to the same
3074 file, which is not always possible in the general case. (Consider
3075 all the permutations of shared or subst'd drives, etc.) */
3077 newname
= map_w32_filename (newname
, NULL
);
3079 /* volume_info is set indirectly by map_w32_filename. */
3080 newname_dev
= volume_info
.serialnum
;
3082 result
= rename (temp
, newname
);
3086 DWORD w32err
= GetLastError ();
3089 && newname_dev
!= oldname_dev
)
3091 /* The implementation of `rename' on Windows does not return
3092 errno = EXDEV when you are moving a directory to a
3093 different storage device (ex. logical disk). It returns
3094 EACCES instead. So here we handle such situations and
3098 if ((attributes
= GetFileAttributes (temp
)) != -1
3099 && (attributes
& FILE_ATTRIBUTE_DIRECTORY
))
3102 else if (errno
== EEXIST
)
3104 if (_chmod (newname
, 0666) != 0)
3106 if (_unlink (newname
) != 0)
3108 result
= rename (temp
, newname
);
3110 else if (w32err
== ERROR_PRIVILEGE_NOT_HELD
3111 && is_symlink (temp
))
3113 /* This is Windows prohibiting the user from creating a
3114 symlink in another place, since that requires
3124 sys_rmdir (const char * path
)
3126 return _rmdir (map_w32_filename (path
, NULL
));
3130 sys_unlink (const char * path
)
3132 path
= map_w32_filename (path
, NULL
);
3134 /* On Unix, unlink works without write permission. */
3135 _chmod (path
, 0666);
3136 return _unlink (path
);
3139 static FILETIME utc_base_ft
;
3140 static ULONGLONG utc_base
; /* In 100ns units */
3141 static int init
= 0;
3143 #define FILETIME_TO_U64(result, ft) \
3145 ULARGE_INTEGER uiTemp; \
3146 uiTemp.LowPart = (ft).dwLowDateTime; \
3147 uiTemp.HighPart = (ft).dwHighDateTime; \
3148 result = uiTemp.QuadPart; \
3152 initialize_utc_base (void)
3154 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
3163 st
.wMilliseconds
= 0;
3165 SystemTimeToFileTime (&st
, &utc_base_ft
);
3166 FILETIME_TO_U64 (utc_base
, utc_base_ft
);
3170 convert_time (FILETIME ft
)
3176 initialize_utc_base ();
3180 if (CompareFileTime (&ft
, &utc_base_ft
) < 0)
3183 FILETIME_TO_U64 (tmp
, ft
);
3184 return (time_t) ((tmp
- utc_base
) / 10000000L);
3188 convert_from_time_t (time_t time
, FILETIME
* pft
)
3194 initialize_utc_base ();
3198 /* time in 100ns units since 1-Jan-1601 */
3199 tmp
.QuadPart
= (ULONGLONG
) time
* 10000000L + utc_base
;
3200 pft
->dwHighDateTime
= tmp
.HighPart
;
3201 pft
->dwLowDateTime
= tmp
.LowPart
;
3205 /* No reason to keep this; faking inode values either by hashing or even
3206 using the file index from GetInformationByHandle, is not perfect and
3207 so by default Emacs doesn't use the inode values on Windows.
3208 Instead, we now determine file-truename correctly (except for
3209 possible drive aliasing etc). */
3211 /* Modified version of "PJW" algorithm (see the "Dragon" compiler book). */
3213 hashval (const unsigned char * str
)
3218 h
= (h
<< 4) + *str
++;
3224 /* Return the hash value of the canonical pathname, excluding the
3225 drive/UNC header, to get a hopefully unique inode number. */
3227 generate_inode_val (const char * name
)
3229 char fullname
[ MAX_PATH
];
3233 /* Get the truly canonical filename, if it exists. (Note: this
3234 doesn't resolve aliasing due to subst commands, or recognize hard
3236 if (!w32_get_long_filename ((char *)name
, fullname
, MAX_PATH
))
3239 parse_root (fullname
, &p
);
3240 /* Normal W32 filesystems are still case insensitive. */
3247 static PSECURITY_DESCRIPTOR
3248 get_file_security_desc_by_handle (HANDLE h
)
3250 PSECURITY_DESCRIPTOR psd
= NULL
;
3252 SECURITY_INFORMATION si
= OWNER_SECURITY_INFORMATION
3253 | GROUP_SECURITY_INFORMATION
/* | DACL_SECURITY_INFORMATION */ ;
3255 err
= get_security_info (h
, SE_FILE_OBJECT
, si
,
3256 NULL
, NULL
, NULL
, NULL
, &psd
);
3257 if (err
!= ERROR_SUCCESS
)
3263 static PSECURITY_DESCRIPTOR
3264 get_file_security_desc_by_name (const char *fname
)
3266 PSECURITY_DESCRIPTOR psd
= NULL
;
3268 SECURITY_INFORMATION si
= OWNER_SECURITY_INFORMATION
3269 | GROUP_SECURITY_INFORMATION
/* | DACL_SECURITY_INFORMATION */ ;
3271 if (!get_file_security (fname
, si
, psd
, 0, &sd_len
))
3273 err
= GetLastError ();
3274 if (err
!= ERROR_INSUFFICIENT_BUFFER
)
3278 psd
= xmalloc (sd_len
);
3279 if (!get_file_security (fname
, si
, psd
, sd_len
, &sd_len
))
3291 unsigned n_subauthorities
;
3293 /* Use the last sub-authority value of the RID, the relative
3294 portion of the SID, as user/group ID. */
3295 n_subauthorities
= *get_sid_sub_authority_count (sid
);
3296 if (n_subauthorities
< 1)
3297 return 0; /* the "World" RID */
3298 return *get_sid_sub_authority (sid
, n_subauthorities
- 1);
3301 /* Caching SID and account values for faster lokup. */
3304 # define FLEXIBLE_ARRAY_MEMBER
3306 # define FLEXIBLE_ARRAY_MEMBER 1
3311 struct w32_id
*next
;
3313 unsigned char sid
[FLEXIBLE_ARRAY_MEMBER
];
3316 static struct w32_id
*w32_idlist
;
3319 w32_cached_id (PSID sid
, unsigned *id
, char *name
)
3321 struct w32_id
*tail
, *found
;
3323 for (found
= NULL
, tail
= w32_idlist
; tail
; tail
= tail
->next
)
3325 if (equal_sid ((PSID
)tail
->sid
, sid
))
3334 strcpy (name
, found
->name
);
3342 w32_add_to_cache (PSID sid
, unsigned id
, char *name
)
3345 struct w32_id
*new_entry
;
3347 /* We don't want to leave behind stale cache from when Emacs was
3351 sid_len
= get_length_sid (sid
);
3352 new_entry
= xmalloc (offsetof (struct w32_id
, sid
) + sid_len
);
3355 new_entry
->rid
= id
;
3356 strcpy (new_entry
->name
, name
);
3357 copy_sid (sid_len
, (PSID
)new_entry
->sid
, sid
);
3358 new_entry
->next
= w32_idlist
;
3359 w32_idlist
= new_entry
;
3368 get_name_and_id (PSECURITY_DESCRIPTOR psd
, const char *fname
,
3369 unsigned *id
, char *nm
, int what
)
3372 char machine
[MAX_COMPUTERNAME_LENGTH
+1];
3374 SID_NAME_USE ignore
;
3376 DWORD name_len
= sizeof (name
);
3378 DWORD domain_len
= sizeof (domain
);
3384 result
= get_security_descriptor_owner (psd
, &sid
, &dflt
);
3385 else if (what
== GID
)
3386 result
= get_security_descriptor_group (psd
, &sid
, &dflt
);
3390 if (!result
|| !is_valid_sid (sid
))
3392 else if (!w32_cached_id (sid
, id
, nm
))
3394 /* If FNAME is a UNC, we need to lookup account on the
3395 specified machine. */
3396 if (IS_DIRECTORY_SEP (fname
[0]) && IS_DIRECTORY_SEP (fname
[1])
3397 && fname
[2] != '\0')
3402 for (s
= fname
+ 2, p
= machine
;
3403 *s
&& !IS_DIRECTORY_SEP (*s
); s
++, p
++)
3409 if (!lookup_account_sid (mp
, sid
, name
, &name_len
,
3410 domain
, &domain_len
, &ignore
)
3411 || name_len
> UNLEN
+1)
3415 *id
= get_rid (sid
);
3417 w32_add_to_cache (sid
, *id
, name
);
3424 get_file_owner_and_group (PSECURITY_DESCRIPTOR psd
,
3428 int dflt_usr
= 0, dflt_grp
= 0;
3437 if (get_name_and_id (psd
, fname
, &st
->st_uid
, st
->st_uname
, UID
))
3439 if (get_name_and_id (psd
, fname
, &st
->st_gid
, st
->st_gname
, GID
))
3442 /* Consider files to belong to current user/group, if we cannot get
3443 more accurate information. */
3446 st
->st_uid
= dflt_passwd
.pw_uid
;
3447 strcpy (st
->st_uname
, dflt_passwd
.pw_name
);
3451 st
->st_gid
= dflt_passwd
.pw_gid
;
3452 strcpy (st
->st_gname
, dflt_group
.gr_name
);
3456 /* Return non-zero if NAME is a potentially slow filesystem. */
3458 is_slow_fs (const char *name
)
3463 if (IS_DIRECTORY_SEP (name
[0]) && IS_DIRECTORY_SEP (name
[1]))
3464 devtype
= DRIVE_REMOTE
; /* assume UNC name is remote */
3465 else if (!(strlen (name
) >= 2 && IS_DEVICE_SEP (name
[1])))
3466 devtype
= GetDriveType (NULL
); /* use root of current drive */
3469 /* GetDriveType needs the root directory of the drive. */
3470 strncpy (drive_root
, name
, 2);
3471 drive_root
[2] = '\\';
3472 drive_root
[3] = '\0';
3473 devtype
= GetDriveType (drive_root
);
3475 return !(devtype
== DRIVE_FIXED
|| devtype
== DRIVE_RAMDISK
);
3478 /* MSVC stat function can't cope with UNC names and has other bugs, so
3479 replace it with our own. This also allows us to calculate consistent
3480 inode values and owner/group without hacks in the main Emacs code. */
3483 stat_worker (const char * path
, struct stat
* buf
, int follow_symlinks
)
3485 char *name
, *save_name
, *r
;
3486 WIN32_FIND_DATA wfd
;
3488 unsigned __int64 fake_inode
= 0;
3491 int rootdir
= FALSE
;
3492 PSECURITY_DESCRIPTOR psd
= NULL
;
3493 int is_a_symlink
= 0;
3494 DWORD file_flags
= FILE_FLAG_BACKUP_SEMANTICS
;
3495 DWORD access_rights
= 0;
3496 DWORD fattrs
= 0, serialnum
= 0, fs_high
= 0, fs_low
= 0, nlinks
= 1;
3497 FILETIME ctime
, atime
, wtime
;
3499 if (path
== NULL
|| buf
== NULL
)
3505 save_name
= name
= (char *) map_w32_filename (path
, &path
);
3506 /* Must be valid filename, no wild cards or other invalid
3507 characters. We use _mbspbrk to support multibyte strings that
3508 might look to strpbrk as if they included literal *, ?, and other
3509 characters mentioned below that are disallowed by Windows
3511 if (_mbspbrk (name
, "*?|<>\""))
3517 /* Remove trailing directory separator, unless name is the root
3518 directory of a drive or UNC volume in which case ensure there
3519 is a trailing separator. */
3520 len
= strlen (name
);
3521 name
= strcpy (alloca (len
+ 2), name
);
3523 /* Avoid a somewhat costly call to is_symlink if the filesystem
3524 doesn't support symlinks. */
3525 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) != 0)
3526 is_a_symlink
= is_symlink (name
);
3528 /* Plan A: Open the file and get all the necessary information via
3529 the resulting handle. This solves several issues in one blow:
3531 . retrieves attributes for the target of a symlink, if needed
3532 . gets attributes of root directories and symlinks pointing to
3533 root directories, thus avoiding the need for special-casing
3534 these and detecting them by examining the file-name format
3535 . retrieves more accurate attributes (e.g., non-zero size for
3536 some directories, esp. directories that are junction points)
3537 . correctly resolves "c:/..", "/.." and similar file names
3538 . avoids run-time penalties for 99% of use cases
3540 Plan A is always tried first, unless the user asked not to (but
3541 if the file is a symlink and we need to follow links, we try Plan
3542 A even if the user asked not to).
3544 If Plan A fails, we go to Plan B (below), where various
3545 potentially expensive techniques must be used to handle "special"
3546 files such as UNC volumes etc. */
3547 if (!(NILP (Vw32_get_true_file_attributes
)
3548 || (EQ (Vw32_get_true_file_attributes
, Qlocal
) && is_slow_fs (name
)))
3549 /* Following symlinks requires getting the info by handle. */
3550 || (is_a_symlink
&& follow_symlinks
))
3552 BY_HANDLE_FILE_INFORMATION info
;
3554 if (is_a_symlink
&& !follow_symlinks
)
3555 file_flags
|= FILE_FLAG_OPEN_REPARSE_POINT
;
3556 /* READ_CONTROL access rights are required to get security info
3557 by handle. But if the OS doesn't support security in the
3558 first place, we don't need to try. */
3559 if (is_windows_9x () != TRUE
)
3560 access_rights
|= READ_CONTROL
;
3562 fh
= CreateFile (name
, access_rights
, 0, NULL
, OPEN_EXISTING
,
3564 /* If CreateFile fails with READ_CONTROL, try again with zero as
3566 if (fh
== INVALID_HANDLE_VALUE
&& access_rights
)
3567 fh
= CreateFile (name
, 0, 0, NULL
, OPEN_EXISTING
,
3569 if (fh
== INVALID_HANDLE_VALUE
)
3570 goto no_true_file_attributes
;
3572 /* This is more accurate in terms of getting the correct number
3573 of links, but is quite slow (it is noticeable when Emacs is
3574 making a list of file name completions). */
3575 if (GetFileInformationByHandle (fh
, &info
))
3577 nlinks
= info
.nNumberOfLinks
;
3578 /* Might as well use file index to fake inode values, but this
3579 is not guaranteed to be unique unless we keep a handle open
3580 all the time (even then there are situations where it is
3581 not unique). Reputedly, there are at most 48 bits of info
3582 (on NTFS, presumably less on FAT). */
3583 fake_inode
= info
.nFileIndexHigh
;
3585 fake_inode
+= info
.nFileIndexLow
;
3586 serialnum
= info
.dwVolumeSerialNumber
;
3587 fs_high
= info
.nFileSizeHigh
;
3588 fs_low
= info
.nFileSizeLow
;
3589 ctime
= info
.ftCreationTime
;
3590 atime
= info
.ftLastAccessTime
;
3591 wtime
= info
.ftLastWriteTime
;
3592 fattrs
= info
.dwFileAttributes
;
3596 /* We don't go to Plan B here, because it's not clear that
3597 it's a good idea. The only known use case where
3598 CreateFile succeeds, but GetFileInformationByHandle fails
3599 (with ERROR_INVALID_FUNCTION) is for character devices
3600 such as NUL, PRN, etc. For these, switching to Plan B is
3601 a net loss, because we lose the character device
3602 attribute returned by GetFileType below (FindFirstFile
3603 doesn't set that bit in the attributes), and the other
3604 fields don't make sense for character devices anyway.
3605 Emacs doesn't really care for non-file entities in the
3606 context of l?stat, so neither do we. */
3608 /* w32err is assigned so one could put a breakpoint here and
3609 examine its value, when GetFileInformationByHandle
3611 DWORD w32err
= GetLastError ();
3615 case ERROR_FILE_NOT_FOUND
: /* can this ever happen? */
3621 /* Test for a symlink before testing for a directory, since
3622 symlinks to directories have the directory bit set, but we
3623 don't want them to appear as directories. */
3624 if (is_a_symlink
&& !follow_symlinks
)
3625 buf
->st_mode
= S_IFLNK
;
3626 else if (fattrs
& FILE_ATTRIBUTE_DIRECTORY
)
3627 buf
->st_mode
= S_IFDIR
;
3630 DWORD ftype
= GetFileType (fh
);
3634 case FILE_TYPE_DISK
:
3635 buf
->st_mode
= S_IFREG
;
3637 case FILE_TYPE_PIPE
:
3638 buf
->st_mode
= S_IFIFO
;
3640 case FILE_TYPE_CHAR
:
3641 case FILE_TYPE_UNKNOWN
:
3643 buf
->st_mode
= S_IFCHR
;
3646 /* We produce the fallback owner and group data, based on the
3647 current user that runs Emacs, in the following cases:
3649 . this is Windows 9X
3650 . getting security by handle failed, and we need to produce
3651 information for the target of a symlink (this is better
3652 than producing a potentially misleading info about the
3655 If getting security by handle fails, and we don't need to
3656 resolve symlinks, we try getting security by name. */
3657 if (is_windows_9x () != TRUE
)
3658 psd
= get_file_security_desc_by_handle (fh
);
3661 get_file_owner_and_group (psd
, name
, buf
);
3664 else if (is_windows_9x () == TRUE
)
3665 get_file_owner_and_group (NULL
, name
, buf
);
3666 else if (!(is_a_symlink
&& follow_symlinks
))
3668 psd
= get_file_security_desc_by_name (name
);
3669 get_file_owner_and_group (psd
, name
, buf
);
3673 get_file_owner_and_group (NULL
, name
, buf
);
3678 no_true_file_attributes
:
3679 /* Plan B: Either getting a handle on the file failed, or the
3680 caller explicitly asked us to not bother making this
3681 information more accurate.
3683 Implementation note: In Plan B, we never bother to resolve
3684 symlinks, even if we got here because we tried Plan A and
3685 failed. That's because, even if the caller asked for extra
3686 precision by setting Vw32_get_true_file_attributes to t,
3687 resolving symlinks requires acquiring a file handle to the
3688 symlink, which we already know will fail. And if the user
3689 did not ask for extra precision, resolving symlinks will fly
3690 in the face of that request, since the user then wants the
3691 lightweight version of the code. */
3692 rootdir
= (path
>= save_name
+ len
- 1
3693 && (IS_DIRECTORY_SEP (*path
) || *path
== 0));
3695 /* If name is "c:/.." or "/.." then stat "c:/" or "/". */
3696 r
= IS_DEVICE_SEP (name
[1]) ? &name
[2] : name
;
3697 if (IS_DIRECTORY_SEP (r
[0])
3698 && r
[1] == '.' && r
[2] == '.' && r
[3] == '\0')
3701 /* Note: If NAME is a symlink to the root of a UNC volume
3702 (i.e. "\\SERVER"), we will not detect that here, and we will
3703 return data about the symlink as result of FindFirst below.
3704 This is unfortunate, but that marginal use case does not
3705 justify a call to chase_symlinks which would impose a penalty
3706 on all the other use cases. (We get here for symlinks to
3707 roots of UNC volumes because CreateFile above fails for them,
3708 unlike with symlinks to root directories X:\ of drives.) */
3709 if (is_unc_volume (name
))
3711 fattrs
= unc_volume_file_attributes (name
);
3715 ctime
= atime
= wtime
= utc_base_ft
;
3719 if (!IS_DIRECTORY_SEP (name
[len
-1]))
3720 strcat (name
, "\\");
3721 if (GetDriveType (name
) < 2)
3727 fattrs
= FILE_ATTRIBUTE_DIRECTORY
;
3728 ctime
= atime
= wtime
= utc_base_ft
;
3732 if (IS_DIRECTORY_SEP (name
[len
-1]))
3735 /* (This is hacky, but helps when doing file completions on
3736 network drives.) Optimize by using information available from
3737 active readdir if possible. */
3738 len
= strlen (dir_pathname
);
3739 if (IS_DIRECTORY_SEP (dir_pathname
[len
-1]))
3741 if (dir_find_handle
!= INVALID_HANDLE_VALUE
3742 && !(is_a_symlink
&& follow_symlinks
)
3743 && strnicmp (save_name
, dir_pathname
, len
) == 0
3744 && IS_DIRECTORY_SEP (name
[len
])
3745 && xstrcasecmp (name
+ len
+ 1, dir_static
.d_name
) == 0)
3747 /* This was the last entry returned by readdir. */
3748 wfd
= dir_find_data
;
3752 logon_network_drive (name
);
3754 fh
= FindFirstFile (name
, &wfd
);
3755 if (fh
== INVALID_HANDLE_VALUE
)
3762 /* Note: if NAME is a symlink, the information we get from
3763 FindFirstFile is for the symlink, not its target. */
3764 fattrs
= wfd
.dwFileAttributes
;
3765 ctime
= wfd
.ftCreationTime
;
3766 atime
= wfd
.ftLastAccessTime
;
3767 wtime
= wfd
.ftLastWriteTime
;
3768 fs_high
= wfd
.nFileSizeHigh
;
3769 fs_low
= wfd
.nFileSizeLow
;
3772 serialnum
= volume_info
.serialnum
;
3774 if (is_a_symlink
&& !follow_symlinks
)
3775 buf
->st_mode
= S_IFLNK
;
3776 else if (fattrs
& FILE_ATTRIBUTE_DIRECTORY
)
3777 buf
->st_mode
= S_IFDIR
;
3779 buf
->st_mode
= S_IFREG
;
3781 get_file_owner_and_group (NULL
, name
, buf
);
3785 /* Not sure if there is any point in this. */
3786 if (!NILP (Vw32_generate_fake_inodes
))
3787 fake_inode
= generate_inode_val (name
);
3788 else if (fake_inode
== 0)
3790 /* For want of something better, try to make everything unique. */
3791 static DWORD gen_num
= 0;
3792 fake_inode
= ++gen_num
;
3796 buf
->st_ino
= fake_inode
;
3798 buf
->st_dev
= serialnum
;
3799 buf
->st_rdev
= serialnum
;
3801 buf
->st_size
= fs_high
;
3802 buf
->st_size
<<= 32;
3803 buf
->st_size
+= fs_low
;
3804 buf
->st_nlink
= nlinks
;
3806 /* Convert timestamps to Unix format. */
3807 buf
->st_mtime
= convert_time (wtime
);
3808 buf
->st_atime
= convert_time (atime
);
3809 if (buf
->st_atime
== 0) buf
->st_atime
= buf
->st_mtime
;
3810 buf
->st_ctime
= convert_time (ctime
);
3811 if (buf
->st_ctime
== 0) buf
->st_ctime
= buf
->st_mtime
;
3813 /* determine rwx permissions */
3814 if (is_a_symlink
&& !follow_symlinks
)
3815 permission
= S_IREAD
| S_IWRITE
| S_IEXEC
; /* Posix expectations */
3818 if (fattrs
& FILE_ATTRIBUTE_READONLY
)
3819 permission
= S_IREAD
;
3821 permission
= S_IREAD
| S_IWRITE
;
3823 if (fattrs
& FILE_ATTRIBUTE_DIRECTORY
)
3824 permission
|= S_IEXEC
;
3825 else if (is_exec (name
))
3826 permission
|= S_IEXEC
;
3829 buf
->st_mode
|= permission
| (permission
>> 3) | (permission
>> 6);
3835 stat (const char * path
, struct stat
* buf
)
3837 return stat_worker (path
, buf
, 1);
3841 lstat (const char * path
, struct stat
* buf
)
3843 return stat_worker (path
, buf
, 0);
3846 /* Provide fstat and utime as well as stat for consistent handling of
3849 fstat (int desc
, struct stat
* buf
)
3851 HANDLE fh
= (HANDLE
) _get_osfhandle (desc
);
3852 BY_HANDLE_FILE_INFORMATION info
;
3853 unsigned __int64 fake_inode
;
3856 switch (GetFileType (fh
) & ~FILE_TYPE_REMOTE
)
3858 case FILE_TYPE_DISK
:
3859 buf
->st_mode
= S_IFREG
;
3860 if (!GetFileInformationByHandle (fh
, &info
))
3866 case FILE_TYPE_PIPE
:
3867 buf
->st_mode
= S_IFIFO
;
3869 case FILE_TYPE_CHAR
:
3870 case FILE_TYPE_UNKNOWN
:
3872 buf
->st_mode
= S_IFCHR
;
3874 memset (&info
, 0, sizeof (info
));
3875 info
.dwFileAttributes
= 0;
3876 info
.ftCreationTime
= utc_base_ft
;
3877 info
.ftLastAccessTime
= utc_base_ft
;
3878 info
.ftLastWriteTime
= utc_base_ft
;
3881 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
3882 buf
->st_mode
= S_IFDIR
;
3884 buf
->st_nlink
= info
.nNumberOfLinks
;
3885 /* Might as well use file index to fake inode values, but this
3886 is not guaranteed to be unique unless we keep a handle open
3887 all the time (even then there are situations where it is
3888 not unique). Reputedly, there are at most 48 bits of info
3889 (on NTFS, presumably less on FAT). */
3890 fake_inode
= info
.nFileIndexHigh
;
3892 fake_inode
+= info
.nFileIndexLow
;
3894 /* MSVC defines _ino_t to be short; other libc's might not. */
3895 if (sizeof (buf
->st_ino
) == 2)
3896 buf
->st_ino
= fake_inode
^ (fake_inode
>> 16);
3898 buf
->st_ino
= fake_inode
;
3900 /* Consider files to belong to current user.
3901 FIXME: this should use GetSecurityInfo API, but it is only
3902 available for _WIN32_WINNT >= 0x501. */
3903 buf
->st_uid
= dflt_passwd
.pw_uid
;
3904 buf
->st_gid
= dflt_passwd
.pw_gid
;
3905 strcpy (buf
->st_uname
, dflt_passwd
.pw_name
);
3906 strcpy (buf
->st_gname
, dflt_group
.gr_name
);
3908 buf
->st_dev
= info
.dwVolumeSerialNumber
;
3909 buf
->st_rdev
= info
.dwVolumeSerialNumber
;
3911 buf
->st_size
= info
.nFileSizeHigh
;
3912 buf
->st_size
<<= 32;
3913 buf
->st_size
+= info
.nFileSizeLow
;
3915 /* Convert timestamps to Unix format. */
3916 buf
->st_mtime
= convert_time (info
.ftLastWriteTime
);
3917 buf
->st_atime
= convert_time (info
.ftLastAccessTime
);
3918 if (buf
->st_atime
== 0) buf
->st_atime
= buf
->st_mtime
;
3919 buf
->st_ctime
= convert_time (info
.ftCreationTime
);
3920 if (buf
->st_ctime
== 0) buf
->st_ctime
= buf
->st_mtime
;
3922 /* determine rwx permissions */
3923 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
)
3924 permission
= S_IREAD
;
3926 permission
= S_IREAD
| S_IWRITE
;
3928 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
3929 permission
|= S_IEXEC
;
3932 #if 0 /* no way of knowing the filename */
3933 char * p
= strrchr (name
, '.');
3935 (xstrcasecmp (p
, ".exe") == 0 ||
3936 xstrcasecmp (p
, ".com") == 0 ||
3937 xstrcasecmp (p
, ".bat") == 0 ||
3938 xstrcasecmp (p
, ".cmd") == 0))
3939 permission
|= S_IEXEC
;
3943 buf
->st_mode
|= permission
| (permission
>> 3) | (permission
>> 6);
3949 utime (const char *name
, struct utimbuf
*times
)
3951 struct utimbuf deftime
;
3958 deftime
.modtime
= deftime
.actime
= time (NULL
);
3962 /* Need write access to set times. */
3963 fh
= CreateFile (name
, FILE_WRITE_ATTRIBUTES
,
3964 /* If NAME specifies a directory, FILE_SHARE_DELETE
3965 allows other processes to delete files inside it,
3966 while we have the directory open. */
3967 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
3968 0, OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
3969 if (fh
!= INVALID_HANDLE_VALUE
)
3971 convert_from_time_t (times
->actime
, &atime
);
3972 convert_from_time_t (times
->modtime
, &mtime
);
3973 if (!SetFileTime (fh
, NULL
, &atime
, &mtime
))
3990 /* Symlink-related functions. */
3991 #ifndef SYMBOLIC_LINK_FLAG_DIRECTORY
3992 #define SYMBOLIC_LINK_FLAG_DIRECTORY 0x1
3996 symlink (char const *filename
, char const *linkname
)
3998 char linkfn
[MAX_PATH
], *tgtfn
;
4000 int dir_access
, filename_ends_in_slash
;
4002 /* Diagnostics follows Posix as much as possible. */
4003 if (filename
== NULL
|| linkname
== NULL
)
4013 if (strlen (filename
) > MAX_PATH
|| strlen (linkname
) > MAX_PATH
)
4015 errno
= ENAMETOOLONG
;
4019 strcpy (linkfn
, map_w32_filename (linkname
, NULL
));
4020 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) == 0)
4026 /* Note: since empty FILENAME was already rejected, we can safely
4027 refer to FILENAME[1]. */
4028 if (!(IS_DIRECTORY_SEP (filename
[0]) || IS_DEVICE_SEP (filename
[1])))
4030 /* Non-absolute FILENAME is understood as being relative to
4031 LINKNAME's directory. We need to prepend that directory to
4032 FILENAME to get correct results from faccessat below, since
4033 otherwise it will interpret FILENAME relative to the
4034 directory where the Emacs process runs. Note that
4035 make-symbolic-link always makes sure LINKNAME is a fully
4036 expanded file name. */
4038 char *p
= linkfn
+ strlen (linkfn
);
4040 while (p
> linkfn
&& !IS_ANY_SEP (p
[-1]))
4043 strncpy (tem
, linkfn
, p
- linkfn
);
4044 tem
[p
- linkfn
] = '\0';
4045 strcat (tem
, filename
);
4046 dir_access
= faccessat (AT_FDCWD
, tem
, D_OK
, AT_EACCESS
);
4049 dir_access
= faccessat (AT_FDCWD
, filename
, D_OK
, AT_EACCESS
);
4051 /* Since Windows distinguishes between symlinks to directories and
4052 to files, we provide a kludgy feature: if FILENAME doesn't
4053 exist, but ends in a slash, we create a symlink to directory. If
4054 FILENAME exists and is a directory, we always create a symlink to
4056 filename_ends_in_slash
= IS_DIRECTORY_SEP (filename
[strlen (filename
) - 1]);
4057 if (dir_access
== 0 || filename_ends_in_slash
)
4058 flags
= SYMBOLIC_LINK_FLAG_DIRECTORY
;
4060 tgtfn
= (char *)map_w32_filename (filename
, NULL
);
4061 if (filename_ends_in_slash
)
4062 tgtfn
[strlen (tgtfn
) - 1] = '\0';
4065 if (!create_symbolic_link (linkfn
, tgtfn
, flags
))
4067 /* ENOSYS is set by create_symbolic_link, when it detects that
4068 the OS doesn't support the CreateSymbolicLink API. */
4069 if (errno
!= ENOSYS
)
4071 DWORD w32err
= GetLastError ();
4075 /* ERROR_SUCCESS is sometimes returned when LINKFN and
4076 TGTFN point to the same file name, go figure. */
4078 case ERROR_FILE_EXISTS
:
4081 case ERROR_ACCESS_DENIED
:
4084 case ERROR_FILE_NOT_FOUND
:
4085 case ERROR_PATH_NOT_FOUND
:
4086 case ERROR_BAD_NETPATH
:
4087 case ERROR_INVALID_REPARSE_DATA
:
4090 case ERROR_DIRECTORY
:
4093 case ERROR_PRIVILEGE_NOT_HELD
:
4094 case ERROR_NOT_ALL_ASSIGNED
:
4097 case ERROR_DISK_FULL
:
4110 /* A quick inexpensive test of whether FILENAME identifies a file that
4111 is a symlink. Returns non-zero if it is, zero otherwise. FILENAME
4112 must already be in the normalized form returned by
4115 Note: for repeated operations on many files, it is best to test
4116 whether the underlying volume actually supports symlinks, by
4117 testing the FILE_SUPPORTS_REPARSE_POINTS bit in volume's flags, and
4118 avoid the call to this function if it doesn't. That's because the
4119 call to GetFileAttributes takes a non-negligible time, especially
4120 on non-local or removable filesystems. See stat_worker for an
4121 example of how to do that. */
4123 is_symlink (const char *filename
)
4126 WIN32_FIND_DATA wfd
;
4129 attrs
= GetFileAttributes (filename
);
4132 DWORD w32err
= GetLastError ();
4136 case ERROR_BAD_NETPATH
: /* network share, can't be a symlink */
4138 case ERROR_ACCESS_DENIED
:
4141 case ERROR_FILE_NOT_FOUND
:
4142 case ERROR_PATH_NOT_FOUND
:
4149 if ((attrs
& FILE_ATTRIBUTE_REPARSE_POINT
) == 0)
4151 logon_network_drive (filename
);
4152 fh
= FindFirstFile (filename
, &wfd
);
4153 if (fh
== INVALID_HANDLE_VALUE
)
4156 return (wfd
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) != 0
4157 && (wfd
.dwReserved0
& IO_REPARSE_TAG_SYMLINK
) == IO_REPARSE_TAG_SYMLINK
;
4160 /* If NAME identifies a symbolic link, copy into BUF the file name of
4161 the symlink's target. Copy at most BUF_SIZE bytes, and do NOT
4162 null-terminate the target name, even if it fits. Return the number
4163 of bytes copied, or -1 if NAME is not a symlink or any error was
4164 encountered while resolving it. The file name copied into BUF is
4165 encoded in the current ANSI codepage. */
4167 readlink (const char *name
, char *buf
, size_t buf_size
)
4170 TOKEN_PRIVILEGES privs
;
4171 int restore_privs
= 0;
4186 path
= map_w32_filename (name
, NULL
);
4188 if (strlen (path
) > MAX_PATH
)
4190 errno
= ENAMETOOLONG
;
4195 if (is_windows_9x () == TRUE
4196 || (volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) == 0
4197 || !is_symlink (path
))
4200 errno
= EINVAL
; /* not a symlink */
4204 /* Done with simple tests, now we're in for some _real_ work. */
4205 if (enable_privilege (SE_BACKUP_NAME
, TRUE
, &privs
))
4207 /* Implementation note: From here and onward, don't return early,
4208 since that will fail to restore the original set of privileges of
4209 the calling thread. */
4211 retval
= -1; /* not too optimistic, are we? */
4213 /* Note: In the next call to CreateFile, we use zero as the 2nd
4214 argument because, when the symlink is a hidden/system file,
4215 e.g. 'C:\Users\All Users', GENERIC_READ fails with
4216 ERROR_ACCESS_DENIED. Zero seems to work just fine, both for file
4217 and directory symlinks. */
4218 sh
= CreateFile (path
, 0, 0, NULL
, OPEN_EXISTING
,
4219 FILE_FLAG_OPEN_REPARSE_POINT
| FILE_FLAG_BACKUP_SEMANTICS
,
4221 if (sh
!= INVALID_HANDLE_VALUE
)
4223 BYTE reparse_buf
[MAXIMUM_REPARSE_DATA_BUFFER_SIZE
];
4224 REPARSE_DATA_BUFFER
*reparse_data
= (REPARSE_DATA_BUFFER
*)&reparse_buf
[0];
4227 if (!DeviceIoControl (sh
, FSCTL_GET_REPARSE_POINT
, NULL
, 0,
4228 reparse_buf
, MAXIMUM_REPARSE_DATA_BUFFER_SIZE
,
4231 else if (reparse_data
->ReparseTag
!= IO_REPARSE_TAG_SYMLINK
)
4235 /* Copy the link target name, in wide characters, fro
4236 reparse_data, then convert it to multibyte encoding in
4237 the current locale's codepage. */
4239 BYTE lname
[MAX_PATH
];
4242 reparse_data
->SymbolicLinkReparseBuffer
.PrintNameLength
;
4244 reparse_data
->SymbolicLinkReparseBuffer
.PathBuffer
4245 + reparse_data
->SymbolicLinkReparseBuffer
.PrintNameOffset
/sizeof(WCHAR
);
4247 /* According to MSDN, PrintNameLength does not include the
4248 terminating null character. */
4249 lwname
= alloca ((lwname_len
+ 1) * sizeof(WCHAR
));
4250 memcpy (lwname
, lwname_src
, lwname_len
);
4251 lwname
[lwname_len
/sizeof(WCHAR
)] = 0; /* null-terminate */
4253 /* FIXME: Should we use the current file-name coding system
4254 instead of the fixed value of the ANSI codepage? */
4255 lname_len
= WideCharToMultiByte (w32_ansi_code_page
, 0, lwname
, -1,
4256 lname
, MAX_PATH
, NULL
, NULL
);
4259 /* WideCharToMultiByte failed. */
4260 DWORD w32err1
= GetLastError ();
4264 case ERROR_INSUFFICIENT_BUFFER
:
4265 errno
= ENAMETOOLONG
;
4267 case ERROR_INVALID_PARAMETER
:
4270 case ERROR_NO_UNICODE_TRANSLATION
:
4280 size_t size_to_copy
= buf_size
;
4282 BYTE
*pend
= p
+ lname_len
;
4284 /* Normalize like dostounix_filename does, but we don't
4285 want to assume that lname is null-terminated. */
4286 if (*p
&& p
[1] == ':' && *p
>= 'A' && *p
<= 'Z')
4294 /* Testing for null-terminated LNAME is paranoia:
4295 WideCharToMultiByte should always return a
4296 null-terminated string when its 4th argument is -1
4297 and its 3rd argument is null-terminated (which they
4299 if (lname
[lname_len
- 1] == '\0')
4301 if (lname_len
<= buf_size
)
4302 size_to_copy
= lname_len
;
4303 strncpy (buf
, lname
, size_to_copy
);
4305 retval
= size_to_copy
;
4312 /* CreateFile failed. */
4313 DWORD w32err2
= GetLastError ();
4317 case ERROR_FILE_NOT_FOUND
:
4318 case ERROR_PATH_NOT_FOUND
:
4321 case ERROR_ACCESS_DENIED
:
4322 case ERROR_TOO_MANY_OPEN_FILES
:
4332 restore_privilege (&privs
);
4339 /* If FILE is a symlink, return its target (stored in a static
4340 buffer); otherwise return FILE.
4342 This function repeatedly resolves symlinks in the last component of
4343 a chain of symlink file names, as in foo -> bar -> baz -> ...,
4344 until it arrives at a file whose last component is not a symlink,
4345 or some error occurs. It returns the target of the last
4346 successfully resolved symlink in the chain. If it succeeds to
4347 resolve even a single symlink, the value returned is an absolute
4348 file name with backslashes (result of GetFullPathName). By
4349 contrast, if the original FILE is returned, it is unaltered.
4351 Note: This function can set errno even if it succeeds.
4353 Implementation note: we only resolve the last portion ("basename")
4354 of the argument FILE and of each following file in the chain,
4355 disregarding any possible symlinks in its leading directories.
4356 This is because Windows system calls and library functions
4357 transparently resolve symlinks in leading directories and return
4358 correct information, as long as the basename is not a symlink. */
4360 chase_symlinks (const char *file
)
4362 static char target
[MAX_PATH
];
4363 char link
[MAX_PATH
];
4364 ssize_t res
, link_len
;
4367 if (is_windows_9x () == TRUE
|| !is_symlink (file
))
4368 return (char *)file
;
4370 if ((link_len
= GetFullPathName (file
, MAX_PATH
, link
, NULL
)) == 0)
4371 return (char *)file
;
4376 /* Remove trailing slashes, as we want to resolve the last
4377 non-trivial part of the link name. */
4378 while (link_len
> 3 && IS_DIRECTORY_SEP (link
[link_len
-1]))
4379 link
[link_len
--] = '\0';
4381 res
= readlink (link
, target
, MAX_PATH
);
4385 if (!(IS_DEVICE_SEP (target
[1])
4386 || (IS_DIRECTORY_SEP (target
[0]) && IS_DIRECTORY_SEP (target
[1]))))
4388 /* Target is relative. Append it to the directory part of
4389 the symlink, then copy the result back to target. */
4390 char *p
= link
+ link_len
;
4392 while (p
> link
&& !IS_ANY_SEP (p
[-1]))
4395 strcpy (target
, link
);
4397 /* Resolve any "." and ".." to get a fully-qualified file name
4399 link_len
= GetFullPathName (target
, MAX_PATH
, link
, NULL
);
4401 } while (res
> 0 && link_len
> 0 && ++loop_count
<= 100);
4403 if (loop_count
> 100)
4406 if (target
[0] == '\0') /* not a single call to readlink succeeded */
4407 return (char *)file
;
4411 /* MS-Windows version of careadlinkat (cf. ../lib/careadlinkat.c). We
4412 have a fixed max size for file names, so we don't need the kind of
4413 alloc/malloc/realloc dance the gnulib version does. We also don't
4414 support FD-relative symlinks. */
4416 careadlinkat (int fd
, char const *filename
,
4417 char *buffer
, size_t buffer_size
,
4418 struct allocator
const *alloc
,
4419 ssize_t (*preadlinkat
) (int, char const *, char *, size_t))
4421 char linkname
[MAX_PATH
];
4430 link_size
= preadlinkat (fd
, filename
, linkname
, sizeof(linkname
));
4434 char *retval
= buffer
;
4436 linkname
[link_size
++] = '\0';
4437 if (link_size
> buffer_size
)
4438 retval
= (char *)(alloc
? alloc
->allocate
: xmalloc
) (link_size
);
4440 memcpy (retval
, linkname
, link_size
);
4448 careadlinkatcwd (int fd
, char const *filename
, char *buffer
,
4452 return readlink (filename
, buffer
, buffer_size
);
4456 /* Support for browsing other processes and their attributes. See
4457 process.c for the Lisp bindings. */
4459 /* Helper wrapper functions. */
4461 static HANDLE WINAPI
4462 create_toolhelp32_snapshot (DWORD Flags
, DWORD Ignored
)
4464 static CreateToolhelp32Snapshot_Proc s_pfn_Create_Toolhelp32_Snapshot
= NULL
;
4466 if (g_b_init_create_toolhelp32_snapshot
== 0)
4468 g_b_init_create_toolhelp32_snapshot
= 1;
4469 s_pfn_Create_Toolhelp32_Snapshot
= (CreateToolhelp32Snapshot_Proc
)
4470 GetProcAddress (GetModuleHandle ("kernel32.dll"),
4471 "CreateToolhelp32Snapshot");
4473 if (s_pfn_Create_Toolhelp32_Snapshot
== NULL
)
4475 return INVALID_HANDLE_VALUE
;
4477 return (s_pfn_Create_Toolhelp32_Snapshot (Flags
, Ignored
));
4481 process32_first (HANDLE hSnapshot
, LPPROCESSENTRY32 lppe
)
4483 static Process32First_Proc s_pfn_Process32_First
= NULL
;
4485 if (g_b_init_process32_first
== 0)
4487 g_b_init_process32_first
= 1;
4488 s_pfn_Process32_First
= (Process32First_Proc
)
4489 GetProcAddress (GetModuleHandle ("kernel32.dll"),
4492 if (s_pfn_Process32_First
== NULL
)
4496 return (s_pfn_Process32_First (hSnapshot
, lppe
));
4500 process32_next (HANDLE hSnapshot
, LPPROCESSENTRY32 lppe
)
4502 static Process32Next_Proc s_pfn_Process32_Next
= NULL
;
4504 if (g_b_init_process32_next
== 0)
4506 g_b_init_process32_next
= 1;
4507 s_pfn_Process32_Next
= (Process32Next_Proc
)
4508 GetProcAddress (GetModuleHandle ("kernel32.dll"),
4511 if (s_pfn_Process32_Next
== NULL
)
4515 return (s_pfn_Process32_Next (hSnapshot
, lppe
));
4519 open_thread_token (HANDLE ThreadHandle
,
4520 DWORD DesiredAccess
,
4522 PHANDLE TokenHandle
)
4524 static OpenThreadToken_Proc s_pfn_Open_Thread_Token
= NULL
;
4525 HMODULE hm_advapi32
= NULL
;
4526 if (is_windows_9x () == TRUE
)
4528 SetLastError (ERROR_NOT_SUPPORTED
);
4531 if (g_b_init_open_thread_token
== 0)
4533 g_b_init_open_thread_token
= 1;
4534 hm_advapi32
= LoadLibrary ("Advapi32.dll");
4535 s_pfn_Open_Thread_Token
=
4536 (OpenThreadToken_Proc
) GetProcAddress (hm_advapi32
, "OpenThreadToken");
4538 if (s_pfn_Open_Thread_Token
== NULL
)
4540 SetLastError (ERROR_NOT_SUPPORTED
);
4544 s_pfn_Open_Thread_Token (
4553 impersonate_self (SECURITY_IMPERSONATION_LEVEL ImpersonationLevel
)
4555 static ImpersonateSelf_Proc s_pfn_Impersonate_Self
= NULL
;
4556 HMODULE hm_advapi32
= NULL
;
4557 if (is_windows_9x () == TRUE
)
4561 if (g_b_init_impersonate_self
== 0)
4563 g_b_init_impersonate_self
= 1;
4564 hm_advapi32
= LoadLibrary ("Advapi32.dll");
4565 s_pfn_Impersonate_Self
=
4566 (ImpersonateSelf_Proc
) GetProcAddress (hm_advapi32
, "ImpersonateSelf");
4568 if (s_pfn_Impersonate_Self
== NULL
)
4572 return s_pfn_Impersonate_Self (ImpersonationLevel
);
4576 revert_to_self (void)
4578 static RevertToSelf_Proc s_pfn_Revert_To_Self
= NULL
;
4579 HMODULE hm_advapi32
= NULL
;
4580 if (is_windows_9x () == TRUE
)
4584 if (g_b_init_revert_to_self
== 0)
4586 g_b_init_revert_to_self
= 1;
4587 hm_advapi32
= LoadLibrary ("Advapi32.dll");
4588 s_pfn_Revert_To_Self
=
4589 (RevertToSelf_Proc
) GetProcAddress (hm_advapi32
, "RevertToSelf");
4591 if (s_pfn_Revert_To_Self
== NULL
)
4595 return s_pfn_Revert_To_Self ();
4599 get_process_memory_info (HANDLE h_proc
,
4600 PPROCESS_MEMORY_COUNTERS mem_counters
,
4603 static GetProcessMemoryInfo_Proc s_pfn_Get_Process_Memory_Info
= NULL
;
4604 HMODULE hm_psapi
= NULL
;
4605 if (is_windows_9x () == TRUE
)
4609 if (g_b_init_get_process_memory_info
== 0)
4611 g_b_init_get_process_memory_info
= 1;
4612 hm_psapi
= LoadLibrary ("Psapi.dll");
4614 s_pfn_Get_Process_Memory_Info
= (GetProcessMemoryInfo_Proc
)
4615 GetProcAddress (hm_psapi
, "GetProcessMemoryInfo");
4617 if (s_pfn_Get_Process_Memory_Info
== NULL
)
4621 return s_pfn_Get_Process_Memory_Info (h_proc
, mem_counters
, bufsize
);
4625 get_process_working_set_size (HANDLE h_proc
,
4629 static GetProcessWorkingSetSize_Proc
4630 s_pfn_Get_Process_Working_Set_Size
= NULL
;
4632 if (is_windows_9x () == TRUE
)
4636 if (g_b_init_get_process_working_set_size
== 0)
4638 g_b_init_get_process_working_set_size
= 1;
4639 s_pfn_Get_Process_Working_Set_Size
= (GetProcessWorkingSetSize_Proc
)
4640 GetProcAddress (GetModuleHandle ("kernel32.dll"),
4641 "GetProcessWorkingSetSize");
4643 if (s_pfn_Get_Process_Working_Set_Size
== NULL
)
4647 return s_pfn_Get_Process_Working_Set_Size (h_proc
, minrss
, maxrss
);
4651 global_memory_status (MEMORYSTATUS
*buf
)
4653 static GlobalMemoryStatus_Proc s_pfn_Global_Memory_Status
= NULL
;
4655 if (is_windows_9x () == TRUE
)
4659 if (g_b_init_global_memory_status
== 0)
4661 g_b_init_global_memory_status
= 1;
4662 s_pfn_Global_Memory_Status
= (GlobalMemoryStatus_Proc
)
4663 GetProcAddress (GetModuleHandle ("kernel32.dll"),
4664 "GlobalMemoryStatus");
4666 if (s_pfn_Global_Memory_Status
== NULL
)
4670 return s_pfn_Global_Memory_Status (buf
);
4674 global_memory_status_ex (MEMORY_STATUS_EX
*buf
)
4676 static GlobalMemoryStatusEx_Proc s_pfn_Global_Memory_Status_Ex
= NULL
;
4678 if (is_windows_9x () == TRUE
)
4682 if (g_b_init_global_memory_status_ex
== 0)
4684 g_b_init_global_memory_status_ex
= 1;
4685 s_pfn_Global_Memory_Status_Ex
= (GlobalMemoryStatusEx_Proc
)
4686 GetProcAddress (GetModuleHandle ("kernel32.dll"),
4687 "GlobalMemoryStatusEx");
4689 if (s_pfn_Global_Memory_Status_Ex
== NULL
)
4693 return s_pfn_Global_Memory_Status_Ex (buf
);
4697 list_system_processes (void)
4699 struct gcpro gcpro1
;
4700 Lisp_Object proclist
= Qnil
;
4703 h_snapshot
= create_toolhelp32_snapshot (TH32CS_SNAPPROCESS
, 0);
4705 if (h_snapshot
!= INVALID_HANDLE_VALUE
)
4707 PROCESSENTRY32 proc_entry
;
4713 proc_entry
.dwSize
= sizeof (PROCESSENTRY32
);
4714 for (res
= process32_first (h_snapshot
, &proc_entry
); res
;
4715 res
= process32_next (h_snapshot
, &proc_entry
))
4717 proc_id
= proc_entry
.th32ProcessID
;
4718 proclist
= Fcons (make_fixnum_or_float (proc_id
), proclist
);
4721 CloseHandle (h_snapshot
);
4723 proclist
= Fnreverse (proclist
);
4730 enable_privilege (LPCTSTR priv_name
, BOOL enable_p
, TOKEN_PRIVILEGES
*old_priv
)
4732 TOKEN_PRIVILEGES priv
;
4733 DWORD priv_size
= sizeof (priv
);
4734 DWORD opriv_size
= sizeof (*old_priv
);
4735 HANDLE h_token
= NULL
;
4736 HANDLE h_thread
= GetCurrentThread ();
4740 res
= open_thread_token (h_thread
,
4741 TOKEN_QUERY
| TOKEN_ADJUST_PRIVILEGES
,
4743 if (!res
&& GetLastError () == ERROR_NO_TOKEN
)
4745 if (impersonate_self (SecurityImpersonation
))
4746 res
= open_thread_token (h_thread
,
4747 TOKEN_QUERY
| TOKEN_ADJUST_PRIVILEGES
,
4752 priv
.PrivilegeCount
= 1;
4753 priv
.Privileges
[0].Attributes
= enable_p
? SE_PRIVILEGE_ENABLED
: 0;
4754 LookupPrivilegeValue (NULL
, priv_name
, &priv
.Privileges
[0].Luid
);
4755 if (AdjustTokenPrivileges (h_token
, FALSE
, &priv
, priv_size
,
4756 old_priv
, &opriv_size
)
4757 && GetLastError () != ERROR_NOT_ALL_ASSIGNED
)
4761 CloseHandle (h_token
);
4767 restore_privilege (TOKEN_PRIVILEGES
*priv
)
4769 DWORD priv_size
= sizeof (*priv
);
4770 HANDLE h_token
= NULL
;
4773 if (open_thread_token (GetCurrentThread (),
4774 TOKEN_QUERY
| TOKEN_ADJUST_PRIVILEGES
,
4777 if (AdjustTokenPrivileges (h_token
, FALSE
, priv
, priv_size
, NULL
, NULL
)
4778 && GetLastError () != ERROR_NOT_ALL_ASSIGNED
)
4782 CloseHandle (h_token
);
4788 ltime (ULONGLONG time_100ns
)
4790 ULONGLONG time_sec
= time_100ns
/ 10000000;
4791 int subsec
= time_100ns
% 10000000;
4792 return list4 (make_number (time_sec
>> 16),
4793 make_number (time_sec
& 0xffff),
4794 make_number (subsec
/ 10),
4795 make_number (subsec
% 10 * 100000));
4798 #define U64_TO_LISP_TIME(time) ltime (time)
4801 process_times (HANDLE h_proc
, Lisp_Object
*ctime
, Lisp_Object
*etime
,
4802 Lisp_Object
*stime
, Lisp_Object
*utime
, Lisp_Object
*ttime
,
4805 FILETIME ft_creation
, ft_exit
, ft_kernel
, ft_user
, ft_current
;
4806 ULONGLONG tem1
, tem2
, tem3
, tem
;
4809 || !get_process_times_fn
4810 || !(*get_process_times_fn
) (h_proc
, &ft_creation
, &ft_exit
,
4811 &ft_kernel
, &ft_user
))
4814 GetSystemTimeAsFileTime (&ft_current
);
4816 FILETIME_TO_U64 (tem1
, ft_kernel
);
4817 *stime
= U64_TO_LISP_TIME (tem1
);
4819 FILETIME_TO_U64 (tem2
, ft_user
);
4820 *utime
= U64_TO_LISP_TIME (tem2
);
4823 *ttime
= U64_TO_LISP_TIME (tem3
);
4825 FILETIME_TO_U64 (tem
, ft_creation
);
4826 /* Process no 4 (System) returns zero creation time. */
4829 *ctime
= U64_TO_LISP_TIME (tem
);
4833 FILETIME_TO_U64 (tem3
, ft_current
);
4834 tem
= (tem3
- utc_base
) - tem
;
4836 *etime
= U64_TO_LISP_TIME (tem
);
4840 *pcpu
= 100.0 * (tem1
+ tem2
) / tem
;
4851 system_process_attributes (Lisp_Object pid
)
4853 struct gcpro gcpro1
, gcpro2
, gcpro3
;
4854 Lisp_Object attrs
= Qnil
;
4855 Lisp_Object cmd_str
, decoded_cmd
, tem
;
4856 HANDLE h_snapshot
, h_proc
;
4859 char uname
[UNLEN
+1], gname
[GNLEN
+1], domain
[1025];
4860 DWORD ulength
= sizeof (uname
), dlength
= sizeof (domain
), needed
;
4861 DWORD glength
= sizeof (gname
);
4862 HANDLE token
= NULL
;
4863 SID_NAME_USE user_type
;
4864 unsigned char *buf
= NULL
;
4866 TOKEN_USER user_token
;
4867 TOKEN_PRIMARY_GROUP group_token
;
4870 PROCESS_MEMORY_COUNTERS mem
;
4871 PROCESS_MEMORY_COUNTERS_EX mem_ex
;
4872 DWORD minrss
, maxrss
;
4874 MEMORY_STATUS_EX memstex
;
4875 double totphys
= 0.0;
4876 Lisp_Object ctime
, stime
, utime
, etime
, ttime
;
4878 BOOL result
= FALSE
;
4880 CHECK_NUMBER_OR_FLOAT (pid
);
4881 proc_id
= FLOATP (pid
) ? XFLOAT_DATA (pid
) : XINT (pid
);
4883 h_snapshot
= create_toolhelp32_snapshot (TH32CS_SNAPPROCESS
, 0);
4885 GCPRO3 (attrs
, decoded_cmd
, tem
);
4887 if (h_snapshot
!= INVALID_HANDLE_VALUE
)
4892 pe
.dwSize
= sizeof (PROCESSENTRY32
);
4893 for (res
= process32_first (h_snapshot
, &pe
); res
;
4894 res
= process32_next (h_snapshot
, &pe
))
4896 if (proc_id
== pe
.th32ProcessID
)
4899 decoded_cmd
= build_string ("Idle");
4902 /* Decode the command name from locale-specific
4904 cmd_str
= make_unibyte_string (pe
.szExeFile
,
4905 strlen (pe
.szExeFile
));
4907 code_convert_string_norecord (cmd_str
,
4908 Vlocale_coding_system
, 0);
4910 attrs
= Fcons (Fcons (Qcomm
, decoded_cmd
), attrs
);
4911 attrs
= Fcons (Fcons (Qppid
,
4912 make_fixnum_or_float (pe
.th32ParentProcessID
)),
4914 attrs
= Fcons (Fcons (Qpri
, make_number (pe
.pcPriClassBase
)),
4916 attrs
= Fcons (Fcons (Qthcount
,
4917 make_fixnum_or_float (pe
.cntThreads
)),
4924 CloseHandle (h_snapshot
);
4933 h_proc
= OpenProcess (PROCESS_QUERY_INFORMATION
| PROCESS_VM_READ
,
4935 /* If we were denied a handle to the process, try again after
4936 enabling the SeDebugPrivilege in our process. */
4939 TOKEN_PRIVILEGES priv_current
;
4941 if (enable_privilege (SE_DEBUG_NAME
, TRUE
, &priv_current
))
4943 h_proc
= OpenProcess (PROCESS_QUERY_INFORMATION
| PROCESS_VM_READ
,
4945 restore_privilege (&priv_current
);
4951 result
= open_process_token (h_proc
, TOKEN_QUERY
, &token
);
4954 result
= get_token_information (token
, TokenUser
, NULL
, 0, &blen
);
4955 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
4957 buf
= xmalloc (blen
);
4958 result
= get_token_information (token
, TokenUser
,
4959 (LPVOID
)buf
, blen
, &needed
);
4962 memcpy (&user_token
, buf
, sizeof (user_token
));
4963 if (!w32_cached_id (user_token
.User
.Sid
, &euid
, uname
))
4965 euid
= get_rid (user_token
.User
.Sid
);
4966 result
= lookup_account_sid (NULL
, user_token
.User
.Sid
,
4971 w32_add_to_cache (user_token
.User
.Sid
, euid
, uname
);
4974 strcpy (uname
, "unknown");
4978 ulength
= strlen (uname
);
4984 /* Determine a reasonable euid and gid values. */
4985 if (xstrcasecmp ("administrator", uname
) == 0)
4987 euid
= 500; /* well-known Administrator uid */
4988 egid
= 513; /* well-known None gid */
4992 /* Get group id and name. */
4993 result
= get_token_information (token
, TokenPrimaryGroup
,
4994 (LPVOID
)buf
, blen
, &needed
);
4995 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
4997 buf
= xrealloc (buf
, blen
= needed
);
4998 result
= get_token_information (token
, TokenPrimaryGroup
,
4999 (LPVOID
)buf
, blen
, &needed
);
5003 memcpy (&group_token
, buf
, sizeof (group_token
));
5004 if (!w32_cached_id (group_token
.PrimaryGroup
, &egid
, gname
))
5006 egid
= get_rid (group_token
.PrimaryGroup
);
5007 dlength
= sizeof (domain
);
5009 lookup_account_sid (NULL
, group_token
.PrimaryGroup
,
5010 gname
, &glength
, NULL
, &dlength
,
5013 w32_add_to_cache (group_token
.PrimaryGroup
,
5017 strcpy (gname
, "None");
5021 glength
= strlen (gname
);
5029 if (!is_windows_9x ())
5031 /* We couldn't open the process token, presumably because of
5032 insufficient access rights. Assume this process is run
5034 strcpy (uname
, "SYSTEM");
5035 strcpy (gname
, "None");
5036 euid
= 18; /* SYSTEM */
5037 egid
= 513; /* None */
5038 glength
= strlen (gname
);
5039 ulength
= strlen (uname
);
5041 /* If we are running under Windows 9X, where security calls are
5042 not supported, we assume all processes are run by the current
5044 else if (GetUserName (uname
, &ulength
))
5046 if (xstrcasecmp ("administrator", uname
) == 0)
5051 strcpy (gname
, "None");
5052 glength
= strlen (gname
);
5053 ulength
= strlen (uname
);
5059 strcpy (uname
, "administrator");
5060 ulength
= strlen (uname
);
5061 strcpy (gname
, "None");
5062 glength
= strlen (gname
);
5065 CloseHandle (token
);
5068 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (euid
)), attrs
);
5069 tem
= make_unibyte_string (uname
, ulength
);
5070 attrs
= Fcons (Fcons (Quser
,
5071 code_convert_string_norecord (tem
, Vlocale_coding_system
, 0)),
5073 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (egid
)), attrs
);
5074 tem
= make_unibyte_string (gname
, glength
);
5075 attrs
= Fcons (Fcons (Qgroup
,
5076 code_convert_string_norecord (tem
, Vlocale_coding_system
, 0)),
5079 if (global_memory_status_ex (&memstex
))
5080 #if __GNUC__ || (defined (_MSC_VER) && _MSC_VER >= 1300)
5081 totphys
= memstex
.ullTotalPhys
/ 1024.0;
5083 /* Visual Studio 6 cannot convert an unsigned __int64 type to
5084 double, so we need to do this for it... */
5086 DWORD tot_hi
= memstex
.ullTotalPhys
>> 32;
5087 DWORD tot_md
= (memstex
.ullTotalPhys
& 0x00000000ffffffff) >> 10;
5088 DWORD tot_lo
= memstex
.ullTotalPhys
% 1024;
5090 totphys
= tot_hi
* 4194304.0 + tot_md
+ tot_lo
/ 1024.0;
5092 #endif /* __GNUC__ || _MSC_VER >= 1300 */
5093 else if (global_memory_status (&memst
))
5094 totphys
= memst
.dwTotalPhys
/ 1024.0;
5097 && get_process_memory_info (h_proc
, (PROCESS_MEMORY_COUNTERS
*)&mem_ex
,
5100 DWORD rss
= mem_ex
.WorkingSetSize
/ 1024;
5102 attrs
= Fcons (Fcons (Qmajflt
,
5103 make_fixnum_or_float (mem_ex
.PageFaultCount
)),
5105 attrs
= Fcons (Fcons (Qvsize
,
5106 make_fixnum_or_float (mem_ex
.PrivateUsage
/ 1024)),
5108 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (rss
)), attrs
);
5110 attrs
= Fcons (Fcons (Qpmem
, make_float (100. * rss
/ totphys
)), attrs
);
5113 && get_process_memory_info (h_proc
, &mem
, sizeof (mem
)))
5115 DWORD rss
= mem_ex
.WorkingSetSize
/ 1024;
5117 attrs
= Fcons (Fcons (Qmajflt
,
5118 make_fixnum_or_float (mem
.PageFaultCount
)),
5120 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (rss
)), attrs
);
5122 attrs
= Fcons (Fcons (Qpmem
, make_float (100. * rss
/ totphys
)), attrs
);
5125 && get_process_working_set_size (h_proc
, &minrss
, &maxrss
))
5127 DWORD rss
= maxrss
/ 1024;
5129 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (maxrss
/ 1024)), attrs
);
5131 attrs
= Fcons (Fcons (Qpmem
, make_float (100. * rss
/ totphys
)), attrs
);
5134 if (process_times (h_proc
, &ctime
, &etime
, &stime
, &utime
, &ttime
, &pcpu
))
5136 attrs
= Fcons (Fcons (Qutime
, utime
), attrs
);
5137 attrs
= Fcons (Fcons (Qstime
, stime
), attrs
);
5138 attrs
= Fcons (Fcons (Qtime
, ttime
), attrs
);
5139 attrs
= Fcons (Fcons (Qstart
, ctime
), attrs
);
5140 attrs
= Fcons (Fcons (Qetime
, etime
), attrs
);
5141 attrs
= Fcons (Fcons (Qpcpu
, make_float (pcpu
)), attrs
);
5144 /* FIXME: Retrieve command line by walking the PEB of the process. */
5147 CloseHandle (h_proc
);
5153 /* Wrappers for winsock functions to map between our file descriptors
5154 and winsock's handles; also set h_errno for convenience.
5156 To allow Emacs to run on systems which don't have winsock support
5157 installed, we dynamically link to winsock on startup if present, and
5158 otherwise provide the minimum necessary functionality
5159 (eg. gethostname). */
5161 /* function pointers for relevant socket functions */
5162 int (PASCAL
*pfn_WSAStartup
) (WORD wVersionRequired
, LPWSADATA lpWSAData
);
5163 void (PASCAL
*pfn_WSASetLastError
) (int iError
);
5164 int (PASCAL
*pfn_WSAGetLastError
) (void);
5165 int (PASCAL
*pfn_WSAEventSelect
) (SOCKET s
, HANDLE hEventObject
, long lNetworkEvents
);
5166 HANDLE (PASCAL
*pfn_WSACreateEvent
) (void);
5167 int (PASCAL
*pfn_WSACloseEvent
) (HANDLE hEvent
);
5168 int (PASCAL
*pfn_socket
) (int af
, int type
, int protocol
);
5169 int (PASCAL
*pfn_bind
) (SOCKET s
, const struct sockaddr
*addr
, int namelen
);
5170 int (PASCAL
*pfn_connect
) (SOCKET s
, const struct sockaddr
*addr
, int namelen
);
5171 int (PASCAL
*pfn_ioctlsocket
) (SOCKET s
, long cmd
, u_long
*argp
);
5172 int (PASCAL
*pfn_recv
) (SOCKET s
, char * buf
, int len
, int flags
);
5173 int (PASCAL
*pfn_send
) (SOCKET s
, const char * buf
, int len
, int flags
);
5174 int (PASCAL
*pfn_closesocket
) (SOCKET s
);
5175 int (PASCAL
*pfn_shutdown
) (SOCKET s
, int how
);
5176 int (PASCAL
*pfn_WSACleanup
) (void);
5178 u_short (PASCAL
*pfn_htons
) (u_short hostshort
);
5179 u_short (PASCAL
*pfn_ntohs
) (u_short netshort
);
5180 unsigned long (PASCAL
*pfn_inet_addr
) (const char * cp
);
5181 int (PASCAL
*pfn_gethostname
) (char * name
, int namelen
);
5182 struct hostent
* (PASCAL
*pfn_gethostbyname
) (const char * name
);
5183 struct servent
* (PASCAL
*pfn_getservbyname
) (const char * name
, const char * proto
);
5184 int (PASCAL
*pfn_getpeername
) (SOCKET s
, struct sockaddr
*addr
, int * namelen
);
5185 int (PASCAL
*pfn_setsockopt
) (SOCKET s
, int level
, int optname
,
5186 const char * optval
, int optlen
);
5187 int (PASCAL
*pfn_listen
) (SOCKET s
, int backlog
);
5188 int (PASCAL
*pfn_getsockname
) (SOCKET s
, struct sockaddr
* name
,
5190 SOCKET (PASCAL
*pfn_accept
) (SOCKET s
, struct sockaddr
* addr
, int * addrlen
);
5191 int (PASCAL
*pfn_recvfrom
) (SOCKET s
, char * buf
, int len
, int flags
,
5192 struct sockaddr
* from
, int * fromlen
);
5193 int (PASCAL
*pfn_sendto
) (SOCKET s
, const char * buf
, int len
, int flags
,
5194 const struct sockaddr
* to
, int tolen
);
5196 /* SetHandleInformation is only needed to make sockets non-inheritable. */
5197 BOOL (WINAPI
*pfn_SetHandleInformation
) (HANDLE object
, DWORD mask
, DWORD flags
);
5198 #ifndef HANDLE_FLAG_INHERIT
5199 #define HANDLE_FLAG_INHERIT 1
5203 static int winsock_inuse
;
5208 if (winsock_lib
!= NULL
&& winsock_inuse
== 0)
5210 /* Not sure what would cause WSAENETDOWN, or even if it can happen
5211 after WSAStartup returns successfully, but it seems reasonable
5212 to allow unloading winsock anyway in that case. */
5213 if (pfn_WSACleanup () == 0 ||
5214 pfn_WSAGetLastError () == WSAENETDOWN
)
5216 if (FreeLibrary (winsock_lib
))
5225 init_winsock (int load_now
)
5227 WSADATA winsockData
;
5229 if (winsock_lib
!= NULL
)
5232 pfn_SetHandleInformation
5233 = (void *) GetProcAddress (GetModuleHandle ("kernel32.dll"),
5234 "SetHandleInformation");
5236 winsock_lib
= LoadLibrary ("Ws2_32.dll");
5238 if (winsock_lib
!= NULL
)
5240 /* dynamically link to socket functions */
5242 #define LOAD_PROC(fn) \
5243 if ((pfn_##fn = (void *) GetProcAddress (winsock_lib, #fn)) == NULL) \
5246 LOAD_PROC (WSAStartup
);
5247 LOAD_PROC (WSASetLastError
);
5248 LOAD_PROC (WSAGetLastError
);
5249 LOAD_PROC (WSAEventSelect
);
5250 LOAD_PROC (WSACreateEvent
);
5251 LOAD_PROC (WSACloseEvent
);
5254 LOAD_PROC (connect
);
5255 LOAD_PROC (ioctlsocket
);
5258 LOAD_PROC (closesocket
);
5259 LOAD_PROC (shutdown
);
5262 LOAD_PROC (inet_addr
);
5263 LOAD_PROC (gethostname
);
5264 LOAD_PROC (gethostbyname
);
5265 LOAD_PROC (getservbyname
);
5266 LOAD_PROC (getpeername
);
5267 LOAD_PROC (WSACleanup
);
5268 LOAD_PROC (setsockopt
);
5270 LOAD_PROC (getsockname
);
5272 LOAD_PROC (recvfrom
);
5276 /* specify version 1.1 of winsock */
5277 if (pfn_WSAStartup (0x101, &winsockData
) == 0)
5279 if (winsockData
.wVersion
!= 0x101)
5284 /* Report that winsock exists and is usable, but leave
5285 socket functions disabled. I am assuming that calling
5286 WSAStartup does not require any network interaction,
5287 and in particular does not cause or require a dial-up
5288 connection to be established. */
5291 FreeLibrary (winsock_lib
);
5299 FreeLibrary (winsock_lib
);
5309 /* function to set h_errno for compatibility; map winsock error codes to
5310 normal system codes where they overlap (non-overlapping definitions
5311 are already in <sys/socket.h> */
5315 if (winsock_lib
== NULL
)
5318 h_errno
= pfn_WSAGetLastError ();
5322 case WSAEACCES
: h_errno
= EACCES
; break;
5323 case WSAEBADF
: h_errno
= EBADF
; break;
5324 case WSAEFAULT
: h_errno
= EFAULT
; break;
5325 case WSAEINTR
: h_errno
= EINTR
; break;
5326 case WSAEINVAL
: h_errno
= EINVAL
; break;
5327 case WSAEMFILE
: h_errno
= EMFILE
; break;
5328 case WSAENAMETOOLONG
: h_errno
= ENAMETOOLONG
; break;
5329 case WSAENOTEMPTY
: h_errno
= ENOTEMPTY
; break;
5337 if (h_errno
== 0 && winsock_lib
!= NULL
)
5338 pfn_WSASetLastError (0);
5341 /* Extend strerror to handle the winsock-specific error codes. */
5345 } _wsa_errlist
[] = {
5346 {WSAEINTR
, "Interrupted function call"},
5347 {WSAEBADF
, "Bad file descriptor"},
5348 {WSAEACCES
, "Permission denied"},
5349 {WSAEFAULT
, "Bad address"},
5350 {WSAEINVAL
, "Invalid argument"},
5351 {WSAEMFILE
, "Too many open files"},
5353 {WSAEWOULDBLOCK
, "Resource temporarily unavailable"},
5354 {WSAEINPROGRESS
, "Operation now in progress"},
5355 {WSAEALREADY
, "Operation already in progress"},
5356 {WSAENOTSOCK
, "Socket operation on non-socket"},
5357 {WSAEDESTADDRREQ
, "Destination address required"},
5358 {WSAEMSGSIZE
, "Message too long"},
5359 {WSAEPROTOTYPE
, "Protocol wrong type for socket"},
5360 {WSAENOPROTOOPT
, "Bad protocol option"},
5361 {WSAEPROTONOSUPPORT
, "Protocol not supported"},
5362 {WSAESOCKTNOSUPPORT
, "Socket type not supported"},
5363 {WSAEOPNOTSUPP
, "Operation not supported"},
5364 {WSAEPFNOSUPPORT
, "Protocol family not supported"},
5365 {WSAEAFNOSUPPORT
, "Address family not supported by protocol family"},
5366 {WSAEADDRINUSE
, "Address already in use"},
5367 {WSAEADDRNOTAVAIL
, "Cannot assign requested address"},
5368 {WSAENETDOWN
, "Network is down"},
5369 {WSAENETUNREACH
, "Network is unreachable"},
5370 {WSAENETRESET
, "Network dropped connection on reset"},
5371 {WSAECONNABORTED
, "Software caused connection abort"},
5372 {WSAECONNRESET
, "Connection reset by peer"},
5373 {WSAENOBUFS
, "No buffer space available"},
5374 {WSAEISCONN
, "Socket is already connected"},
5375 {WSAENOTCONN
, "Socket is not connected"},
5376 {WSAESHUTDOWN
, "Cannot send after socket shutdown"},
5377 {WSAETOOMANYREFS
, "Too many references"}, /* not sure */
5378 {WSAETIMEDOUT
, "Connection timed out"},
5379 {WSAECONNREFUSED
, "Connection refused"},
5380 {WSAELOOP
, "Network loop"}, /* not sure */
5381 {WSAENAMETOOLONG
, "Name is too long"},
5382 {WSAEHOSTDOWN
, "Host is down"},
5383 {WSAEHOSTUNREACH
, "No route to host"},
5384 {WSAENOTEMPTY
, "Buffer not empty"}, /* not sure */
5385 {WSAEPROCLIM
, "Too many processes"},
5386 {WSAEUSERS
, "Too many users"}, /* not sure */
5387 {WSAEDQUOT
, "Double quote in host name"}, /* really not sure */
5388 {WSAESTALE
, "Data is stale"}, /* not sure */
5389 {WSAEREMOTE
, "Remote error"}, /* not sure */
5391 {WSASYSNOTREADY
, "Network subsystem is unavailable"},
5392 {WSAVERNOTSUPPORTED
, "WINSOCK.DLL version out of range"},
5393 {WSANOTINITIALISED
, "Winsock not initialized successfully"},
5394 {WSAEDISCON
, "Graceful shutdown in progress"},
5396 {WSAENOMORE
, "No more operations allowed"}, /* not sure */
5397 {WSAECANCELLED
, "Operation cancelled"}, /* not sure */
5398 {WSAEINVALIDPROCTABLE
, "Invalid procedure table from service provider"},
5399 {WSAEINVALIDPROVIDER
, "Invalid service provider version number"},
5400 {WSAEPROVIDERFAILEDINIT
, "Unable to initialize a service provider"},
5401 {WSASYSCALLFAILURE
, "System call failure"},
5402 {WSASERVICE_NOT_FOUND
, "Service not found"}, /* not sure */
5403 {WSATYPE_NOT_FOUND
, "Class type not found"},
5404 {WSA_E_NO_MORE
, "No more resources available"}, /* really not sure */
5405 {WSA_E_CANCELLED
, "Operation already cancelled"}, /* really not sure */
5406 {WSAEREFUSED
, "Operation refused"}, /* not sure */
5409 {WSAHOST_NOT_FOUND
, "Host not found"},
5410 {WSATRY_AGAIN
, "Authoritative host not found during name lookup"},
5411 {WSANO_RECOVERY
, "Non-recoverable error during name lookup"},
5412 {WSANO_DATA
, "Valid name, no data record of requested type"},
5418 sys_strerror (int error_no
)
5421 static char unknown_msg
[40];
5423 if (error_no
>= 0 && error_no
< sys_nerr
)
5424 return sys_errlist
[error_no
];
5426 for (i
= 0; _wsa_errlist
[i
].errnum
>= 0; i
++)
5427 if (_wsa_errlist
[i
].errnum
== error_no
)
5428 return _wsa_errlist
[i
].msg
;
5430 sprintf (unknown_msg
, "Unidentified error: %d", error_no
);
5434 /* [andrewi 3-May-96] I've had conflicting results using both methods,
5435 but I believe the method of keeping the socket handle separate (and
5436 insuring it is not inheritable) is the correct one. */
5438 #define SOCK_HANDLE(fd) ((SOCKET) fd_info[fd].hnd)
5440 static int socket_to_fd (SOCKET s
);
5443 sys_socket (int af
, int type
, int protocol
)
5447 if (winsock_lib
== NULL
)
5450 return INVALID_SOCKET
;
5455 /* call the real socket function */
5456 s
= pfn_socket (af
, type
, protocol
);
5458 if (s
!= INVALID_SOCKET
)
5459 return socket_to_fd (s
);
5465 /* Convert a SOCKET to a file descriptor. */
5467 socket_to_fd (SOCKET s
)
5472 /* Although under NT 3.5 _open_osfhandle will accept a socket
5473 handle, if opened with SO_OPENTYPE == SO_SYNCHRONOUS_NONALERT,
5474 that does not work under NT 3.1. However, we can get the same
5475 effect by using a backdoor function to replace an existing
5476 descriptor handle with the one we want. */
5478 /* allocate a file descriptor (with appropriate flags) */
5479 fd
= _open ("NUL:", _O_RDWR
);
5482 /* Make a non-inheritable copy of the socket handle. Note
5483 that it is possible that sockets aren't actually kernel
5484 handles, which appears to be the case on Windows 9x when
5485 the MS Proxy winsock client is installed. */
5487 /* Apparently there is a bug in NT 3.51 with some service
5488 packs, which prevents using DuplicateHandle to make a
5489 socket handle non-inheritable (causes WSACleanup to
5490 hang). The work-around is to use SetHandleInformation
5491 instead if it is available and implemented. */
5492 if (pfn_SetHandleInformation
)
5494 pfn_SetHandleInformation ((HANDLE
) s
, HANDLE_FLAG_INHERIT
, 0);
5498 HANDLE parent
= GetCurrentProcess ();
5499 HANDLE new_s
= INVALID_HANDLE_VALUE
;
5501 if (DuplicateHandle (parent
,
5507 DUPLICATE_SAME_ACCESS
))
5509 /* It is possible that DuplicateHandle succeeds even
5510 though the socket wasn't really a kernel handle,
5511 because a real handle has the same value. So
5512 test whether the new handle really is a socket. */
5513 long nonblocking
= 0;
5514 if (pfn_ioctlsocket ((SOCKET
) new_s
, FIONBIO
, &nonblocking
) == 0)
5516 pfn_closesocket (s
);
5521 CloseHandle (new_s
);
5526 fd_info
[fd
].hnd
= (HANDLE
) s
;
5528 /* set our own internal flags */
5529 fd_info
[fd
].flags
= FILE_SOCKET
| FILE_BINARY
| FILE_READ
| FILE_WRITE
;
5535 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
5537 /* attach child_process to fd_info */
5538 if (fd_info
[ fd
].cp
!= NULL
)
5540 DebPrint (("sys_socket: fd_info[%d] apparently in use!\n", fd
));
5544 fd_info
[ fd
].cp
= cp
;
5547 winsock_inuse
++; /* count open sockets */
5554 pfn_closesocket (s
);
5560 sys_bind (int s
, const struct sockaddr
* addr
, int namelen
)
5562 if (winsock_lib
== NULL
)
5565 return SOCKET_ERROR
;
5569 if (fd_info
[s
].flags
& FILE_SOCKET
)
5571 int rc
= pfn_bind (SOCK_HANDLE (s
), addr
, namelen
);
5572 if (rc
== SOCKET_ERROR
)
5577 return SOCKET_ERROR
;
5581 sys_connect (int s
, const struct sockaddr
* name
, int namelen
)
5583 if (winsock_lib
== NULL
)
5586 return SOCKET_ERROR
;
5590 if (fd_info
[s
].flags
& FILE_SOCKET
)
5592 int rc
= pfn_connect (SOCK_HANDLE (s
), name
, namelen
);
5593 if (rc
== SOCKET_ERROR
)
5598 return SOCKET_ERROR
;
5602 sys_htons (u_short hostshort
)
5604 return (winsock_lib
!= NULL
) ?
5605 pfn_htons (hostshort
) : hostshort
;
5609 sys_ntohs (u_short netshort
)
5611 return (winsock_lib
!= NULL
) ?
5612 pfn_ntohs (netshort
) : netshort
;
5616 sys_inet_addr (const char * cp
)
5618 return (winsock_lib
!= NULL
) ?
5619 pfn_inet_addr (cp
) : INADDR_NONE
;
5623 sys_gethostname (char * name
, int namelen
)
5625 if (winsock_lib
!= NULL
)
5626 return pfn_gethostname (name
, namelen
);
5628 if (namelen
> MAX_COMPUTERNAME_LENGTH
)
5629 return !GetComputerName (name
, (DWORD
*)&namelen
);
5632 return SOCKET_ERROR
;
5636 sys_gethostbyname (const char * name
)
5638 struct hostent
* host
;
5640 if (winsock_lib
== NULL
)
5647 host
= pfn_gethostbyname (name
);
5654 sys_getservbyname (const char * name
, const char * proto
)
5656 struct servent
* serv
;
5658 if (winsock_lib
== NULL
)
5665 serv
= pfn_getservbyname (name
, proto
);
5672 sys_getpeername (int s
, struct sockaddr
*addr
, int * namelen
)
5674 if (winsock_lib
== NULL
)
5677 return SOCKET_ERROR
;
5681 if (fd_info
[s
].flags
& FILE_SOCKET
)
5683 int rc
= pfn_getpeername (SOCK_HANDLE (s
), addr
, namelen
);
5684 if (rc
== SOCKET_ERROR
)
5689 return SOCKET_ERROR
;
5693 sys_shutdown (int s
, int how
)
5695 if (winsock_lib
== NULL
)
5698 return SOCKET_ERROR
;
5702 if (fd_info
[s
].flags
& FILE_SOCKET
)
5704 int rc
= pfn_shutdown (SOCK_HANDLE (s
), how
);
5705 if (rc
== SOCKET_ERROR
)
5710 return SOCKET_ERROR
;
5714 sys_setsockopt (int s
, int level
, int optname
, const void * optval
, int optlen
)
5716 if (winsock_lib
== NULL
)
5719 return SOCKET_ERROR
;
5723 if (fd_info
[s
].flags
& FILE_SOCKET
)
5725 int rc
= pfn_setsockopt (SOCK_HANDLE (s
), level
, optname
,
5726 (const char *)optval
, optlen
);
5727 if (rc
== SOCKET_ERROR
)
5732 return SOCKET_ERROR
;
5736 sys_listen (int s
, int backlog
)
5738 if (winsock_lib
== NULL
)
5741 return SOCKET_ERROR
;
5745 if (fd_info
[s
].flags
& FILE_SOCKET
)
5747 int rc
= pfn_listen (SOCK_HANDLE (s
), backlog
);
5748 if (rc
== SOCKET_ERROR
)
5751 fd_info
[s
].flags
|= FILE_LISTEN
;
5755 return SOCKET_ERROR
;
5759 sys_getsockname (int s
, struct sockaddr
* name
, int * namelen
)
5761 if (winsock_lib
== NULL
)
5764 return SOCKET_ERROR
;
5768 if (fd_info
[s
].flags
& FILE_SOCKET
)
5770 int rc
= pfn_getsockname (SOCK_HANDLE (s
), name
, namelen
);
5771 if (rc
== SOCKET_ERROR
)
5776 return SOCKET_ERROR
;
5780 sys_accept (int s
, struct sockaddr
* addr
, int * addrlen
)
5782 if (winsock_lib
== NULL
)
5789 if (fd_info
[s
].flags
& FILE_LISTEN
)
5791 SOCKET t
= pfn_accept (SOCK_HANDLE (s
), addr
, addrlen
);
5793 if (t
== INVALID_SOCKET
)
5796 fd
= socket_to_fd (t
);
5798 fd_info
[s
].cp
->status
= STATUS_READ_ACKNOWLEDGED
;
5799 ResetEvent (fd_info
[s
].cp
->char_avail
);
5807 sys_recvfrom (int s
, char * buf
, int len
, int flags
,
5808 struct sockaddr
* from
, int * fromlen
)
5810 if (winsock_lib
== NULL
)
5813 return SOCKET_ERROR
;
5817 if (fd_info
[s
].flags
& FILE_SOCKET
)
5819 int rc
= pfn_recvfrom (SOCK_HANDLE (s
), buf
, len
, flags
, from
, fromlen
);
5820 if (rc
== SOCKET_ERROR
)
5825 return SOCKET_ERROR
;
5829 sys_sendto (int s
, const char * buf
, int len
, int flags
,
5830 const struct sockaddr
* to
, int tolen
)
5832 if (winsock_lib
== NULL
)
5835 return SOCKET_ERROR
;
5839 if (fd_info
[s
].flags
& FILE_SOCKET
)
5841 int rc
= pfn_sendto (SOCK_HANDLE (s
), buf
, len
, flags
, to
, tolen
);
5842 if (rc
== SOCKET_ERROR
)
5847 return SOCKET_ERROR
;
5850 /* Windows does not have an fcntl function. Provide an implementation
5851 solely for making sockets non-blocking. */
5853 fcntl (int s
, int cmd
, int options
)
5855 if (winsock_lib
== NULL
)
5862 if (fd_info
[s
].flags
& FILE_SOCKET
)
5864 if (cmd
== F_SETFL
&& options
== O_NONBLOCK
)
5866 unsigned long nblock
= 1;
5867 int rc
= pfn_ioctlsocket (SOCK_HANDLE (s
), FIONBIO
, &nblock
);
5868 if (rc
== SOCKET_ERROR
)
5870 /* Keep track of the fact that we set this to non-blocking. */
5871 fd_info
[s
].flags
|= FILE_NDELAY
;
5877 return SOCKET_ERROR
;
5881 return SOCKET_ERROR
;
5885 /* Shadow main io functions: we need to handle pipes and sockets more
5886 intelligently, and implement non-blocking mode as well. */
5899 if (fd
< MAXDESC
&& fd_info
[fd
].cp
)
5901 child_process
* cp
= fd_info
[fd
].cp
;
5903 fd_info
[fd
].cp
= NULL
;
5905 if (CHILD_ACTIVE (cp
))
5907 /* if last descriptor to active child_process then cleanup */
5909 for (i
= 0; i
< MAXDESC
; i
++)
5913 if (fd_info
[i
].cp
== cp
)
5918 if (fd_info
[fd
].flags
& FILE_SOCKET
)
5920 if (winsock_lib
== NULL
) emacs_abort ();
5922 pfn_shutdown (SOCK_HANDLE (fd
), 2);
5923 rc
= pfn_closesocket (SOCK_HANDLE (fd
));
5925 winsock_inuse
--; /* count open sockets */
5932 /* Note that sockets do not need special treatment here (at least on
5933 NT and Windows 95 using the standard tcp/ip stacks) - it appears that
5934 closesocket is equivalent to CloseHandle, which is to be expected
5935 because socket handles are fully fledged kernel handles. */
5938 if (rc
== 0 && fd
< MAXDESC
)
5939 fd_info
[fd
].flags
= 0;
5950 if (new_fd
>= 0 && new_fd
< MAXDESC
)
5952 /* duplicate our internal info as well */
5953 fd_info
[new_fd
] = fd_info
[fd
];
5959 sys_dup2 (int src
, int dst
)
5963 if (dst
< 0 || dst
>= MAXDESC
)
5969 /* make sure we close the destination first if it's a pipe or socket */
5970 if (src
!= dst
&& fd_info
[dst
].flags
!= 0)
5973 rc
= _dup2 (src
, dst
);
5976 /* duplicate our internal info as well */
5977 fd_info
[dst
] = fd_info
[src
];
5982 /* Unix pipe() has only one arg */
5984 sys_pipe (int * phandles
)
5989 /* make pipe handles non-inheritable; when we spawn a child, we
5990 replace the relevant handle with an inheritable one. Also put
5991 pipes into binary mode; we will do text mode translation ourselves
5993 rc
= _pipe (phandles
, 0, _O_NOINHERIT
| _O_BINARY
);
5997 /* Protect against overflow, since Windows can open more handles than
5998 our fd_info array has room for. */
5999 if (phandles
[0] >= MAXDESC
|| phandles
[1] >= MAXDESC
)
6001 _close (phandles
[0]);
6002 _close (phandles
[1]);
6007 flags
= FILE_PIPE
| FILE_READ
| FILE_BINARY
;
6008 fd_info
[phandles
[0]].flags
= flags
;
6010 flags
= FILE_PIPE
| FILE_WRITE
| FILE_BINARY
;
6011 fd_info
[phandles
[1]].flags
= flags
;
6018 /* Function to do blocking read of one byte, needed to implement
6019 select. It is only allowed on sockets and pipes. */
6021 _sys_read_ahead (int fd
)
6026 if (fd
< 0 || fd
>= MAXDESC
)
6027 return STATUS_READ_ERROR
;
6029 cp
= fd_info
[fd
].cp
;
6031 if (cp
== NULL
|| cp
->fd
!= fd
|| cp
->status
!= STATUS_READ_READY
)
6032 return STATUS_READ_ERROR
;
6034 if ((fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SERIAL
| FILE_SOCKET
)) == 0
6035 || (fd_info
[fd
].flags
& FILE_READ
) == 0)
6037 DebPrint (("_sys_read_ahead: internal error: fd %d is not a pipe, serial port, or socket!\n", fd
));
6041 cp
->status
= STATUS_READ_IN_PROGRESS
;
6043 if (fd_info
[fd
].flags
& FILE_PIPE
)
6045 rc
= _read (fd
, &cp
->chr
, sizeof (char));
6047 /* Give subprocess time to buffer some more output for us before
6048 reporting that input is available; we need this because Windows 95
6049 connects DOS programs to pipes by making the pipe appear to be
6050 the normal console stdout - as a result most DOS programs will
6051 write to stdout without buffering, ie. one character at a
6052 time. Even some W32 programs do this - "dir" in a command
6053 shell on NT is very slow if we don't do this. */
6056 int wait
= w32_pipe_read_delay
;
6062 /* Yield remainder of our time slice, effectively giving a
6063 temporary priority boost to the child process. */
6067 else if (fd_info
[fd
].flags
& FILE_SERIAL
)
6069 HANDLE hnd
= fd_info
[fd
].hnd
;
6070 OVERLAPPED
*ovl
= &fd_info
[fd
].cp
->ovl_read
;
6073 /* Configure timeouts for blocking read. */
6074 if (!GetCommTimeouts (hnd
, &ct
))
6075 return STATUS_READ_ERROR
;
6076 ct
.ReadIntervalTimeout
= 0;
6077 ct
.ReadTotalTimeoutMultiplier
= 0;
6078 ct
.ReadTotalTimeoutConstant
= 0;
6079 if (!SetCommTimeouts (hnd
, &ct
))
6080 return STATUS_READ_ERROR
;
6082 if (!ReadFile (hnd
, &cp
->chr
, sizeof (char), (DWORD
*) &rc
, ovl
))
6084 if (GetLastError () != ERROR_IO_PENDING
)
6085 return STATUS_READ_ERROR
;
6086 if (!GetOverlappedResult (hnd
, ovl
, (DWORD
*) &rc
, TRUE
))
6087 return STATUS_READ_ERROR
;
6090 else if (fd_info
[fd
].flags
& FILE_SOCKET
)
6092 unsigned long nblock
= 0;
6093 /* We always want this to block, so temporarily disable NDELAY. */
6094 if (fd_info
[fd
].flags
& FILE_NDELAY
)
6095 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
6097 rc
= pfn_recv (SOCK_HANDLE (fd
), &cp
->chr
, sizeof (char), 0);
6099 if (fd_info
[fd
].flags
& FILE_NDELAY
)
6102 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
6106 if (rc
== sizeof (char))
6107 cp
->status
= STATUS_READ_SUCCEEDED
;
6109 cp
->status
= STATUS_READ_FAILED
;
6115 _sys_wait_accept (int fd
)
6121 if (fd
< 0 || fd
>= MAXDESC
)
6122 return STATUS_READ_ERROR
;
6124 cp
= fd_info
[fd
].cp
;
6126 if (cp
== NULL
|| cp
->fd
!= fd
|| cp
->status
!= STATUS_READ_READY
)
6127 return STATUS_READ_ERROR
;
6129 cp
->status
= STATUS_READ_FAILED
;
6131 hEv
= pfn_WSACreateEvent ();
6132 rc
= pfn_WSAEventSelect (SOCK_HANDLE (fd
), hEv
, FD_ACCEPT
);
6133 if (rc
!= SOCKET_ERROR
)
6135 rc
= WaitForSingleObject (hEv
, INFINITE
);
6136 pfn_WSAEventSelect (SOCK_HANDLE (fd
), NULL
, 0);
6137 if (rc
== WAIT_OBJECT_0
)
6138 cp
->status
= STATUS_READ_SUCCEEDED
;
6140 pfn_WSACloseEvent (hEv
);
6146 sys_read (int fd
, char * buffer
, unsigned int count
)
6151 char * orig_buffer
= buffer
;
6159 if (fd
< MAXDESC
&& fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
| FILE_SERIAL
))
6161 child_process
*cp
= fd_info
[fd
].cp
;
6163 if ((fd_info
[fd
].flags
& FILE_READ
) == 0)
6171 /* re-read CR carried over from last read */
6172 if (fd_info
[fd
].flags
& FILE_LAST_CR
)
6174 if (fd_info
[fd
].flags
& FILE_BINARY
) emacs_abort ();
6178 fd_info
[fd
].flags
&= ~FILE_LAST_CR
;
6181 /* presence of a child_process structure means we are operating in
6182 non-blocking mode - otherwise we just call _read directly.
6183 Note that the child_process structure might be missing because
6184 reap_subprocess has been called; in this case the pipe is
6185 already broken, so calling _read on it is okay. */
6188 int current_status
= cp
->status
;
6190 switch (current_status
)
6192 case STATUS_READ_FAILED
:
6193 case STATUS_READ_ERROR
:
6194 /* report normal EOF if nothing in buffer */
6196 fd_info
[fd
].flags
|= FILE_AT_EOF
;
6199 case STATUS_READ_READY
:
6200 case STATUS_READ_IN_PROGRESS
:
6201 DebPrint (("sys_read called when read is in progress\n"));
6202 errno
= EWOULDBLOCK
;
6205 case STATUS_READ_SUCCEEDED
:
6206 /* consume read-ahead char */
6207 *buffer
++ = cp
->chr
;
6210 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
6211 ResetEvent (cp
->char_avail
);
6213 case STATUS_READ_ACKNOWLEDGED
:
6217 DebPrint (("sys_read: bad status %d\n", current_status
));
6222 if (fd_info
[fd
].flags
& FILE_PIPE
)
6224 PeekNamedPipe ((HANDLE
) _get_osfhandle (fd
), NULL
, 0, NULL
, &waiting
, NULL
);
6225 to_read
= min (waiting
, (DWORD
) count
);
6228 nchars
+= _read (fd
, buffer
, to_read
);
6230 else if (fd_info
[fd
].flags
& FILE_SERIAL
)
6232 HANDLE hnd
= fd_info
[fd
].hnd
;
6233 OVERLAPPED
*ovl
= &fd_info
[fd
].cp
->ovl_read
;
6239 /* Configure timeouts for non-blocking read. */
6240 if (!GetCommTimeouts (hnd
, &ct
))
6245 ct
.ReadIntervalTimeout
= MAXDWORD
;
6246 ct
.ReadTotalTimeoutMultiplier
= 0;
6247 ct
.ReadTotalTimeoutConstant
= 0;
6248 if (!SetCommTimeouts (hnd
, &ct
))
6254 if (!ResetEvent (ovl
->hEvent
))
6259 if (!ReadFile (hnd
, buffer
, count
, (DWORD
*) &rc
, ovl
))
6261 if (GetLastError () != ERROR_IO_PENDING
)
6266 if (!GetOverlappedResult (hnd
, ovl
, (DWORD
*) &rc
, TRUE
))
6275 else /* FILE_SOCKET */
6277 if (winsock_lib
== NULL
) emacs_abort ();
6279 /* do the equivalent of a non-blocking read */
6280 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONREAD
, &waiting
);
6281 if (waiting
== 0 && nchars
== 0)
6283 h_errno
= errno
= EWOULDBLOCK
;
6289 /* always use binary mode for sockets */
6290 int res
= pfn_recv (SOCK_HANDLE (fd
), buffer
, count
, 0);
6291 if (res
== SOCKET_ERROR
)
6293 DebPrint (("sys_read.recv failed with error %d on socket %ld\n",
6294 pfn_WSAGetLastError (), SOCK_HANDLE (fd
)));
6304 int nread
= _read (fd
, buffer
, count
);
6307 else if (nchars
== 0)
6312 fd_info
[fd
].flags
|= FILE_AT_EOF
;
6313 /* Perform text mode translation if required. */
6314 else if ((fd_info
[fd
].flags
& FILE_BINARY
) == 0)
6316 nchars
= crlf_to_lf (nchars
, orig_buffer
);
6317 /* If buffer contains only CR, return that. To be absolutely
6318 sure we should attempt to read the next char, but in
6319 practice a CR to be followed by LF would not appear by
6320 itself in the buffer. */
6321 if (nchars
> 1 && orig_buffer
[nchars
- 1] == 0x0d)
6323 fd_info
[fd
].flags
|= FILE_LAST_CR
;
6329 nchars
= _read (fd
, buffer
, count
);
6334 /* From w32xfns.c */
6335 extern HANDLE interrupt_handle
;
6337 /* For now, don't bother with a non-blocking mode */
6339 sys_write (int fd
, const void * buffer
, unsigned int count
)
6349 if (fd
< MAXDESC
&& fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
| FILE_SERIAL
))
6351 if ((fd_info
[fd
].flags
& FILE_WRITE
) == 0)
6357 /* Perform text mode translation if required. */
6358 if ((fd_info
[fd
].flags
& FILE_BINARY
) == 0)
6360 char * tmpbuf
= alloca (count
* 2);
6361 unsigned char * src
= (void *)buffer
;
6362 unsigned char * dst
= tmpbuf
;
6367 unsigned char *next
;
6368 /* copy next line or remaining bytes */
6369 next
= _memccpy (dst
, src
, '\n', nbytes
);
6372 /* copied one line ending with '\n' */
6373 int copied
= next
- dst
;
6376 /* insert '\r' before '\n' */
6383 /* copied remaining partial line -> now finished */
6390 if (fd
< MAXDESC
&& fd_info
[fd
].flags
& FILE_SERIAL
)
6392 HANDLE hnd
= (HANDLE
) _get_osfhandle (fd
);
6393 OVERLAPPED
*ovl
= &fd_info
[fd
].cp
->ovl_write
;
6394 HANDLE wait_hnd
[2] = { interrupt_handle
, ovl
->hEvent
};
6397 if (!WriteFile (hnd
, buffer
, count
, (DWORD
*) &nchars
, ovl
))
6399 if (GetLastError () != ERROR_IO_PENDING
)
6404 if (detect_input_pending ())
6405 active
= MsgWaitForMultipleObjects (2, wait_hnd
, FALSE
, INFINITE
,
6408 active
= WaitForMultipleObjects (2, wait_hnd
, FALSE
, INFINITE
);
6409 if (active
== WAIT_OBJECT_0
)
6410 { /* User pressed C-g, cancel write, then leave. Don't bother
6411 cleaning up as we may only get stuck in buggy drivers. */
6412 PurgeComm (hnd
, PURGE_TXABORT
| PURGE_TXCLEAR
);
6417 if (active
== WAIT_OBJECT_0
+ 1
6418 && !GetOverlappedResult (hnd
, ovl
, (DWORD
*) &nchars
, TRUE
))
6425 else if (fd
< MAXDESC
&& fd_info
[fd
].flags
& FILE_SOCKET
)
6427 unsigned long nblock
= 0;
6428 if (winsock_lib
== NULL
) emacs_abort ();
6430 /* TODO: implement select() properly so non-blocking I/O works. */
6431 /* For now, make sure the write blocks. */
6432 if (fd_info
[fd
].flags
& FILE_NDELAY
)
6433 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
6435 nchars
= pfn_send (SOCK_HANDLE (fd
), buffer
, count
, 0);
6437 /* Set the socket back to non-blocking if it was before,
6438 for other operations that support it. */
6439 if (fd_info
[fd
].flags
& FILE_NDELAY
)
6442 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
6445 if (nchars
== SOCKET_ERROR
)
6447 DebPrint (("sys_write.send failed with error %d on socket %ld\n",
6448 pfn_WSAGetLastError (), SOCK_HANDLE (fd
)));
6454 /* Some networked filesystems don't like too large writes, so
6455 break them into smaller chunks. See the Comments section of
6456 the MSDN documentation of WriteFile for details behind the
6457 choice of the value of CHUNK below. See also the thread
6458 http://thread.gmane.org/gmane.comp.version-control.git/145294
6459 in the git mailing list. */
6460 const unsigned char *p
= buffer
;
6461 const unsigned chunk
= 30 * 1024 * 1024;
6466 unsigned this_chunk
= count
< chunk
? count
: chunk
;
6467 int n
= _write (fd
, p
, this_chunk
);
6475 else if (n
< this_chunk
)
6485 /* The Windows CRT functions are "optimized for speed", so they don't
6486 check for timezone and DST changes if they were last called less
6487 than 1 minute ago (see http://support.microsoft.com/kb/821231). So
6488 all Emacs features that repeatedly call time functions (e.g.,
6489 display-time) are in real danger of missing timezone and DST
6490 changes. Calling tzset before each localtime call fixes that. */
6492 sys_localtime (const time_t *t
)
6495 return localtime (t
);
6500 /* Try loading LIBRARY_ID from the file(s) specified in
6501 Vdynamic_library_alist. If the library is loaded successfully,
6502 return the handle of the DLL, and record the filename in the
6503 property :loaded-from of LIBRARY_ID. If the library could not be
6504 found, or when it was already loaded (because the handle is not
6505 recorded anywhere, and so is lost after use), return NULL.
6507 We could also save the handle in :loaded-from, but currently
6508 there's no use case for it. */
6510 w32_delayed_load (Lisp_Object library_id
)
6512 HMODULE library_dll
= NULL
;
6514 CHECK_SYMBOL (library_id
);
6516 if (CONSP (Vdynamic_library_alist
)
6517 && NILP (Fassq (library_id
, Vlibrary_cache
)))
6519 Lisp_Object found
= Qnil
;
6520 Lisp_Object dlls
= Fassq (library_id
, Vdynamic_library_alist
);
6523 for (dlls
= XCDR (dlls
); CONSP (dlls
); dlls
= XCDR (dlls
))
6525 CHECK_STRING_CAR (dlls
);
6526 if ((library_dll
= LoadLibrary (SDATA (XCAR (dlls
)))))
6528 char name
[MAX_PATH
];
6531 len
= GetModuleFileNameA (library_dll
, name
, sizeof (name
));
6532 found
= Fcons (XCAR (dlls
),
6534 /* Possibly truncated */
6535 ? make_specified_string (name
, -1, len
, 1)
6541 Fput (library_id
, QCloaded_from
, found
);
6549 check_windows_init_file (void)
6551 /* A common indication that Emacs is not installed properly is when
6552 it cannot find the Windows installation file. If this file does
6553 not exist in the expected place, tell the user. */
6555 if (!noninteractive
&& !inhibit_window_system
6556 /* Vload_path is not yet initialized when we are loading
6558 && NILP (Vpurify_flag
))
6560 Lisp_Object init_file
;
6563 init_file
= build_string ("term/w32-win");
6564 fd
= openp (Vload_path
, init_file
, Fget_load_suffixes (), NULL
, Qnil
);
6567 Lisp_Object load_path_print
= Fprin1_to_string (Vload_path
, Qnil
);
6568 char *init_file_name
= SDATA (init_file
);
6569 char *load_path
= SDATA (load_path_print
);
6570 char *buffer
= alloca (1024
6571 + strlen (init_file_name
)
6572 + strlen (load_path
));
6575 "The Emacs Windows initialization file \"%s.el\" "
6576 "could not be found in your Emacs installation. "
6577 "Emacs checked the following directories for this file:\n"
6579 "When Emacs cannot find this file, it usually means that it "
6580 "was not installed properly, or its distribution file was "
6581 "not unpacked properly.\nSee the README.W32 file in the "
6582 "top-level Emacs directory for more information.",
6583 init_file_name
, load_path
);
6586 "Emacs Abort Dialog",
6587 MB_OK
| MB_ICONEXCLAMATION
| MB_TASKMODAL
);
6588 /* Use the low-level system abort. */
6599 term_ntproc (int ignored
)
6605 /* shutdown the socket interface if necessary */
6612 init_ntproc (int dumping
)
6614 sigset_t initial_mask
= 0;
6616 /* Initialize the socket interface now if available and requested by
6617 the user by defining PRELOAD_WINSOCK; otherwise loading will be
6618 delayed until open-network-stream is called (w32-has-winsock can
6619 also be used to dynamically load or reload winsock).
6621 Conveniently, init_environment is called before us, so
6622 PRELOAD_WINSOCK can be set in the registry. */
6624 /* Always initialize this correctly. */
6627 if (getenv ("PRELOAD_WINSOCK") != NULL
)
6628 init_winsock (TRUE
);
6630 /* Initial preparation for subprocess support: replace our standard
6631 handles with non-inheritable versions. */
6634 HANDLE stdin_save
= INVALID_HANDLE_VALUE
;
6635 HANDLE stdout_save
= INVALID_HANDLE_VALUE
;
6636 HANDLE stderr_save
= INVALID_HANDLE_VALUE
;
6638 parent
= GetCurrentProcess ();
6640 /* ignore errors when duplicating and closing; typically the
6641 handles will be invalid when running as a gui program. */
6642 DuplicateHandle (parent
,
6643 GetStdHandle (STD_INPUT_HANDLE
),
6648 DUPLICATE_SAME_ACCESS
);
6650 DuplicateHandle (parent
,
6651 GetStdHandle (STD_OUTPUT_HANDLE
),
6656 DUPLICATE_SAME_ACCESS
);
6658 DuplicateHandle (parent
,
6659 GetStdHandle (STD_ERROR_HANDLE
),
6664 DUPLICATE_SAME_ACCESS
);
6670 if (stdin_save
!= INVALID_HANDLE_VALUE
)
6671 _open_osfhandle ((intptr_t) stdin_save
, O_TEXT
);
6673 _open ("nul", O_TEXT
| O_NOINHERIT
| O_RDONLY
);
6676 if (stdout_save
!= INVALID_HANDLE_VALUE
)
6677 _open_osfhandle ((intptr_t) stdout_save
, O_TEXT
);
6679 _open ("nul", O_TEXT
| O_NOINHERIT
| O_WRONLY
);
6682 if (stderr_save
!= INVALID_HANDLE_VALUE
)
6683 _open_osfhandle ((intptr_t) stderr_save
, O_TEXT
);
6685 _open ("nul", O_TEXT
| O_NOINHERIT
| O_WRONLY
);
6689 /* unfortunately, atexit depends on implementation of malloc */
6690 /* atexit (term_ntproc); */
6693 /* Make sure we start with all signals unblocked. */
6694 sigprocmask (SIG_SETMASK
, &initial_mask
, NULL
);
6695 signal (SIGABRT
, term_ntproc
);
6699 /* determine which drives are fixed, for GetCachedVolumeInformation */
6701 /* GetDriveType must have trailing backslash. */
6702 char drive
[] = "A:\\";
6704 /* Loop over all possible drive letters */
6705 while (*drive
<= 'Z')
6707 /* Record if this drive letter refers to a fixed drive. */
6708 fixed_drives
[DRIVE_INDEX (*drive
)] =
6709 (GetDriveType (drive
) == DRIVE_FIXED
);
6714 /* Reset the volume info cache. */
6715 volume_cache
= NULL
;
6720 shutdown_handler ensures that buffers' autosave files are
6721 up to date when the user logs off, or the system shuts down.
6724 shutdown_handler (DWORD type
)
6726 /* Ctrl-C and Ctrl-Break are already suppressed, so don't handle them. */
6727 if (type
== CTRL_CLOSE_EVENT
/* User closes console window. */
6728 || type
== CTRL_LOGOFF_EVENT
/* User logs off. */
6729 || type
== CTRL_SHUTDOWN_EVENT
) /* User shutsdown. */
6731 /* Shut down cleanly, making sure autosave files are up to date. */
6732 shut_down_emacs (0, Qnil
);
6735 /* Allow other handlers to handle this signal. */
6740 globals_of_w32 is used to initialize those global variables that
6741 must always be initialized on startup even when the global variable
6742 initialized is non zero (see the function main in emacs.c).
6745 globals_of_w32 (void)
6747 HMODULE kernel32
= GetModuleHandle ("kernel32.dll");
6749 get_process_times_fn
= (GetProcessTimes_Proc
)
6750 GetProcAddress (kernel32
, "GetProcessTimes");
6752 DEFSYM (QCloaded_from
, ":loaded-from");
6754 g_b_init_is_windows_9x
= 0;
6755 g_b_init_open_process_token
= 0;
6756 g_b_init_get_token_information
= 0;
6757 g_b_init_lookup_account_sid
= 0;
6758 g_b_init_get_sid_sub_authority
= 0;
6759 g_b_init_get_sid_sub_authority_count
= 0;
6760 g_b_init_get_security_info
= 0;
6761 g_b_init_get_file_security
= 0;
6762 g_b_init_get_security_descriptor_owner
= 0;
6763 g_b_init_get_security_descriptor_group
= 0;
6764 g_b_init_is_valid_sid
= 0;
6765 g_b_init_create_toolhelp32_snapshot
= 0;
6766 g_b_init_process32_first
= 0;
6767 g_b_init_process32_next
= 0;
6768 g_b_init_open_thread_token
= 0;
6769 g_b_init_impersonate_self
= 0;
6770 g_b_init_revert_to_self
= 0;
6771 g_b_init_get_process_memory_info
= 0;
6772 g_b_init_get_process_working_set_size
= 0;
6773 g_b_init_global_memory_status
= 0;
6774 g_b_init_global_memory_status_ex
= 0;
6775 g_b_init_equal_sid
= 0;
6776 g_b_init_copy_sid
= 0;
6777 g_b_init_get_length_sid
= 0;
6778 g_b_init_get_native_system_info
= 0;
6779 g_b_init_get_system_times
= 0;
6780 g_b_init_create_symbolic_link
= 0;
6781 num_of_processors
= 0;
6782 /* The following sets a handler for shutdown notifications for
6783 console apps. This actually applies to Emacs in both console and
6784 GUI modes, since we had to fool windows into thinking emacs is a
6785 console application to get console mode to work. */
6786 SetConsoleCtrlHandler (shutdown_handler
, TRUE
);
6788 /* "None" is the default group name on standalone workstations. */
6789 strcpy (dflt_group_name
, "None");
6792 /* For make-serial-process */
6794 serial_open (char *port
)
6800 hnd
= CreateFile (port
, GENERIC_READ
| GENERIC_WRITE
, 0, 0,
6801 OPEN_EXISTING
, FILE_FLAG_OVERLAPPED
, 0);
6802 if (hnd
== INVALID_HANDLE_VALUE
)
6803 error ("Could not open %s", port
);
6804 fd
= (int) _open_osfhandle ((intptr_t) hnd
, 0);
6806 error ("Could not open %s", port
);
6810 error ("Could not create child process");
6812 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
6813 fd_info
[ fd
].hnd
= hnd
;
6814 fd_info
[ fd
].flags
|=
6815 FILE_READ
| FILE_WRITE
| FILE_BINARY
| FILE_SERIAL
;
6816 if (fd_info
[ fd
].cp
!= NULL
)
6818 error ("fd_info[fd = %d] is already in use", fd
);
6820 fd_info
[ fd
].cp
= cp
;
6821 cp
->ovl_read
.hEvent
= CreateEvent (NULL
, TRUE
, FALSE
, NULL
);
6822 if (cp
->ovl_read
.hEvent
== NULL
)
6823 error ("Could not create read event");
6824 cp
->ovl_write
.hEvent
= CreateEvent (NULL
, TRUE
, FALSE
, NULL
);
6825 if (cp
->ovl_write
.hEvent
== NULL
)
6826 error ("Could not create write event");
6831 /* For serial-process-configure */
6833 serial_configure (struct Lisp_Process
*p
, Lisp_Object contact
)
6835 Lisp_Object childp2
= Qnil
;
6836 Lisp_Object tem
= Qnil
;
6840 char summary
[4] = "???"; /* This usually becomes "8N1". */
6842 if ((fd_info
[ p
->outfd
].flags
& FILE_SERIAL
) == 0)
6843 error ("Not a serial process");
6844 hnd
= fd_info
[ p
->outfd
].hnd
;
6846 childp2
= Fcopy_sequence (p
->childp
);
6848 /* Initialize timeouts for blocking read and blocking write. */
6849 if (!GetCommTimeouts (hnd
, &ct
))
6850 error ("GetCommTimeouts() failed");
6851 ct
.ReadIntervalTimeout
= 0;
6852 ct
.ReadTotalTimeoutMultiplier
= 0;
6853 ct
.ReadTotalTimeoutConstant
= 0;
6854 ct
.WriteTotalTimeoutMultiplier
= 0;
6855 ct
.WriteTotalTimeoutConstant
= 0;
6856 if (!SetCommTimeouts (hnd
, &ct
))
6857 error ("SetCommTimeouts() failed");
6858 /* Read port attributes and prepare default configuration. */
6859 memset (&dcb
, 0, sizeof (dcb
));
6860 dcb
.DCBlength
= sizeof (DCB
);
6861 if (!GetCommState (hnd
, &dcb
))
6862 error ("GetCommState() failed");
6865 dcb
.fAbortOnError
= FALSE
;
6866 /* dcb.XonLim and dcb.XoffLim are set by GetCommState() */
6871 /* Configure speed. */
6872 if (!NILP (Fplist_member (contact
, QCspeed
)))
6873 tem
= Fplist_get (contact
, QCspeed
);
6875 tem
= Fplist_get (p
->childp
, QCspeed
);
6877 dcb
.BaudRate
= XINT (tem
);
6878 childp2
= Fplist_put (childp2
, QCspeed
, tem
);
6880 /* Configure bytesize. */
6881 if (!NILP (Fplist_member (contact
, QCbytesize
)))
6882 tem
= Fplist_get (contact
, QCbytesize
);
6884 tem
= Fplist_get (p
->childp
, QCbytesize
);
6886 tem
= make_number (8);
6888 if (XINT (tem
) != 7 && XINT (tem
) != 8)
6889 error (":bytesize must be nil (8), 7, or 8");
6890 dcb
.ByteSize
= XINT (tem
);
6891 summary
[0] = XINT (tem
) + '0';
6892 childp2
= Fplist_put (childp2
, QCbytesize
, tem
);
6894 /* Configure parity. */
6895 if (!NILP (Fplist_member (contact
, QCparity
)))
6896 tem
= Fplist_get (contact
, QCparity
);
6898 tem
= Fplist_get (p
->childp
, QCparity
);
6899 if (!NILP (tem
) && !EQ (tem
, Qeven
) && !EQ (tem
, Qodd
))
6900 error (":parity must be nil (no parity), `even', or `odd'");
6901 dcb
.fParity
= FALSE
;
6902 dcb
.Parity
= NOPARITY
;
6903 dcb
.fErrorChar
= FALSE
;
6908 else if (EQ (tem
, Qeven
))
6912 dcb
.Parity
= EVENPARITY
;
6913 dcb
.fErrorChar
= TRUE
;
6915 else if (EQ (tem
, Qodd
))
6919 dcb
.Parity
= ODDPARITY
;
6920 dcb
.fErrorChar
= TRUE
;
6922 childp2
= Fplist_put (childp2
, QCparity
, tem
);
6924 /* Configure stopbits. */
6925 if (!NILP (Fplist_member (contact
, QCstopbits
)))
6926 tem
= Fplist_get (contact
, QCstopbits
);
6928 tem
= Fplist_get (p
->childp
, QCstopbits
);
6930 tem
= make_number (1);
6932 if (XINT (tem
) != 1 && XINT (tem
) != 2)
6933 error (":stopbits must be nil (1 stopbit), 1, or 2");
6934 summary
[2] = XINT (tem
) + '0';
6935 if (XINT (tem
) == 1)
6936 dcb
.StopBits
= ONESTOPBIT
;
6937 else if (XINT (tem
) == 2)
6938 dcb
.StopBits
= TWOSTOPBITS
;
6939 childp2
= Fplist_put (childp2
, QCstopbits
, tem
);
6941 /* Configure flowcontrol. */
6942 if (!NILP (Fplist_member (contact
, QCflowcontrol
)))
6943 tem
= Fplist_get (contact
, QCflowcontrol
);
6945 tem
= Fplist_get (p
->childp
, QCflowcontrol
);
6946 if (!NILP (tem
) && !EQ (tem
, Qhw
) && !EQ (tem
, Qsw
))
6947 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
6948 dcb
.fOutxCtsFlow
= FALSE
;
6949 dcb
.fOutxDsrFlow
= FALSE
;
6950 dcb
.fDtrControl
= DTR_CONTROL_DISABLE
;
6951 dcb
.fDsrSensitivity
= FALSE
;
6952 dcb
.fTXContinueOnXoff
= FALSE
;
6955 dcb
.fRtsControl
= RTS_CONTROL_DISABLE
;
6956 dcb
.XonChar
= 17; /* Control-Q */
6957 dcb
.XoffChar
= 19; /* Control-S */
6960 /* Already configured. */
6962 else if (EQ (tem
, Qhw
))
6964 dcb
.fRtsControl
= RTS_CONTROL_HANDSHAKE
;
6965 dcb
.fOutxCtsFlow
= TRUE
;
6967 else if (EQ (tem
, Qsw
))
6972 childp2
= Fplist_put (childp2
, QCflowcontrol
, tem
);
6974 /* Activate configuration. */
6975 if (!SetCommState (hnd
, &dcb
))
6976 error ("SetCommState() failed");
6978 childp2
= Fplist_put (childp2
, QCsummary
, build_string (summary
));
6979 pset_childp (p
, childp2
);
6985 emacs_gnutls_pull (gnutls_transport_ptr_t p
, void* buf
, size_t sz
)
6990 struct Lisp_Process
*process
= (struct Lisp_Process
*)p
;
6991 int fd
= process
->infd
;
6995 n
= sys_read (fd
, (char*)buf
, sz
);
7002 if (err
== EWOULDBLOCK
)
7004 /* Set a small timeout. */
7005 timeout
= make_emacs_time (1, 0);
7007 FD_SET ((int)fd
, &fdset
);
7009 /* Use select with the timeout to poll the selector. */
7010 sc
= select (fd
+ 1, &fdset
, (SELECT_TYPE
*)0, (SELECT_TYPE
*)0,
7014 continue; /* Try again. */
7016 /* Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN.
7017 Also accept select return 0 as an indicator to EAGAIN. */
7018 if (sc
== 0 || errno
== EWOULDBLOCK
)
7021 err
= errno
; /* Other errors are just passed on. */
7024 emacs_gnutls_transport_set_errno (process
->gnutls_state
, err
);
7031 emacs_gnutls_push (gnutls_transport_ptr_t p
, const void* buf
, size_t sz
)
7033 struct Lisp_Process
*process
= (struct Lisp_Process
*)p
;
7034 int fd
= process
->outfd
;
7035 ssize_t n
= sys_write (fd
, buf
, sz
);
7037 /* 0 or more bytes written means everything went fine. */
7041 /* Negative bytes written means we got an error in errno.
7042 Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
7043 emacs_gnutls_transport_set_errno (process
->gnutls_state
,
7044 errno
== EWOULDBLOCK
? EAGAIN
: errno
);
7048 #endif /* HAVE_GNUTLS */