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
&& sys_access (tmp
, D_OK
) == 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 /* Shadow some MSVC runtime functions to map requests for long filenames
2719 to reasonable short names if necessary. This was originally added to
2720 permit running Emacs on NT 3.1 on a FAT partition, which doesn't support
2724 sys_access (const char * path
, int mode
)
2728 /* MSVCRT implementation of 'access' doesn't recognize D_OK, and its
2729 newer versions blow up when passed D_OK. */
2730 path
= map_w32_filename (path
, NULL
);
2731 /* If the last element of PATH is a symlink, we need to resolve it
2732 to get the attributes of its target file. Note: any symlinks in
2733 PATH elements other than the last one are transparently resolved
2734 by GetFileAttributes below. */
2735 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) != 0)
2736 path
= chase_symlinks (path
);
2738 if ((attributes
= GetFileAttributes (path
)) == -1)
2740 DWORD w32err
= GetLastError ();
2744 case ERROR_INVALID_NAME
:
2745 case ERROR_BAD_PATHNAME
:
2746 if (is_unc_volume (path
))
2748 attributes
= unc_volume_file_attributes (path
);
2749 if (attributes
== -1)
2757 case ERROR_FILE_NOT_FOUND
:
2758 case ERROR_BAD_NETPATH
:
2767 if ((mode
& X_OK
) != 0 && !is_exec (path
))
2772 if ((mode
& W_OK
) != 0 && (attributes
& FILE_ATTRIBUTE_READONLY
) != 0)
2777 if ((mode
& D_OK
) != 0 && (attributes
& FILE_ATTRIBUTE_DIRECTORY
) == 0)
2786 sys_chdir (const char * path
)
2788 return _chdir (map_w32_filename (path
, NULL
));
2792 sys_chmod (const char * path
, int mode
)
2794 path
= chase_symlinks (map_w32_filename (path
, NULL
));
2795 return _chmod (path
, mode
);
2799 sys_chown (const char *path
, uid_t owner
, gid_t group
)
2801 if (sys_chmod (path
, S_IREAD
) == -1) /* check if file exists */
2807 sys_creat (const char * path
, int mode
)
2809 return _creat (map_w32_filename (path
, NULL
), mode
);
2813 sys_fopen (const char * path
, const char * mode
)
2817 const char * mode_save
= mode
;
2819 /* Force all file handles to be non-inheritable. This is necessary to
2820 ensure child processes don't unwittingly inherit handles that might
2821 prevent future file access. */
2825 else if (mode
[0] == 'w' || mode
[0] == 'a')
2826 oflag
= O_WRONLY
| O_CREAT
| O_TRUNC
;
2830 /* Only do simplistic option parsing. */
2834 oflag
&= ~(O_RDONLY
| O_WRONLY
);
2837 else if (mode
[0] == 'b')
2842 else if (mode
[0] == 't')
2849 fd
= _open (map_w32_filename (path
, NULL
), oflag
| _O_NOINHERIT
, 0644);
2853 return _fdopen (fd
, mode_save
);
2856 /* This only works on NTFS volumes, but is useful to have. */
2858 sys_link (const char * old
, const char * new)
2862 char oldname
[MAX_PATH
], newname
[MAX_PATH
];
2864 if (old
== NULL
|| new == NULL
)
2870 strcpy (oldname
, map_w32_filename (old
, NULL
));
2871 strcpy (newname
, map_w32_filename (new, NULL
));
2873 fileh
= CreateFile (oldname
, 0, 0, NULL
, OPEN_EXISTING
,
2874 FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
2875 if (fileh
!= INVALID_HANDLE_VALUE
)
2879 /* Confusingly, the "alternate" stream name field does not apply
2880 when restoring a hard link, and instead contains the actual
2881 stream data for the link (ie. the name of the link to create).
2882 The WIN32_STREAM_ID structure before the cStreamName field is
2883 the stream header, which is then immediately followed by the
2887 WIN32_STREAM_ID wid
;
2888 WCHAR wbuffer
[MAX_PATH
]; /* extra space for link name */
2891 wlen
= MultiByteToWideChar (CP_ACP
, MB_PRECOMPOSED
, newname
, -1,
2892 data
.wid
.cStreamName
, MAX_PATH
);
2895 LPVOID context
= NULL
;
2898 data
.wid
.dwStreamId
= BACKUP_LINK
;
2899 data
.wid
.dwStreamAttributes
= 0;
2900 data
.wid
.Size
.LowPart
= wlen
* sizeof (WCHAR
);
2901 data
.wid
.Size
.HighPart
= 0;
2902 data
.wid
.dwStreamNameSize
= 0;
2904 if (BackupWrite (fileh
, (LPBYTE
)&data
,
2905 offsetof (WIN32_STREAM_ID
, cStreamName
)
2906 + data
.wid
.Size
.LowPart
,
2907 &wbytes
, FALSE
, FALSE
, &context
)
2908 && BackupWrite (fileh
, NULL
, 0, &wbytes
, TRUE
, FALSE
, &context
))
2915 /* Should try mapping GetLastError to errno; for now just
2916 indicate a general error (eg. links not supported). */
2917 errno
= EINVAL
; // perhaps EMLINK?
2921 CloseHandle (fileh
);
2930 sys_mkdir (const char * path
)
2932 return _mkdir (map_w32_filename (path
, NULL
));
2935 /* Because of long name mapping issues, we need to implement this
2936 ourselves. Also, MSVC's _mktemp returns NULL when it can't generate
2937 a unique name, instead of setting the input template to an empty
2940 Standard algorithm seems to be use pid or tid with a letter on the
2941 front (in place of the 6 X's) and cycle through the letters to find a
2942 unique name. We extend that to allow any reasonable character as the
2943 first of the 6 X's. */
2945 sys_mktemp (char * template)
2949 unsigned uid
= GetCurrentThreadId ();
2950 static char first_char
[] = "abcdefghijklmnopqrstuvwyz0123456789!%-_@#";
2952 if (template == NULL
)
2954 p
= template + strlen (template);
2956 /* replace up to the last 5 X's with uid in decimal */
2957 while (--p
>= template && p
[0] == 'X' && --i
>= 0)
2959 p
[0] = '0' + uid
% 10;
2963 if (i
< 0 && p
[0] == 'X')
2968 int save_errno
= errno
;
2969 p
[0] = first_char
[i
];
2970 if (sys_access (template, 0) < 0)
2976 while (++i
< sizeof (first_char
));
2979 /* Template is badly formed or else we can't generate a unique name,
2980 so return empty string */
2986 sys_open (const char * path
, int oflag
, int mode
)
2988 const char* mpath
= map_w32_filename (path
, NULL
);
2989 /* Try to open file without _O_CREAT, to be able to write to hidden
2990 and system files. Force all file handles to be
2992 int res
= _open (mpath
, (oflag
& ~_O_CREAT
) | _O_NOINHERIT
, mode
);
2995 return _open (mpath
, oflag
| _O_NOINHERIT
, mode
);
2999 sys_rename (const char * oldname
, const char * newname
)
3002 char temp
[MAX_PATH
];
3006 /* MoveFile on Windows 95 doesn't correctly change the short file name
3007 alias in a number of circumstances (it is not easy to predict when
3008 just by looking at oldname and newname, unfortunately). In these
3009 cases, renaming through a temporary name avoids the problem.
3011 A second problem on Windows 95 is that renaming through a temp name when
3012 newname is uppercase fails (the final long name ends up in
3013 lowercase, although the short alias might be uppercase) UNLESS the
3014 long temp name is not 8.3.
3016 So, on Windows 95 we always rename through a temp name, and we make sure
3017 the temp name has a long extension to ensure correct renaming. */
3019 strcpy (temp
, map_w32_filename (oldname
, NULL
));
3021 /* volume_info is set indirectly by map_w32_filename. */
3022 oldname_dev
= volume_info
.serialnum
;
3024 if (os_subtype
== OS_9X
)
3030 oldname
= map_w32_filename (oldname
, NULL
);
3031 if ((o
= strrchr (oldname
, '\\')))
3034 o
= (char *) oldname
;
3036 if ((p
= strrchr (temp
, '\\')))
3043 /* Force temp name to require a manufactured 8.3 alias - this
3044 seems to make the second rename work properly. */
3045 sprintf (p
, "_.%s.%u", o
, i
);
3047 result
= rename (oldname
, temp
);
3049 /* This loop must surely terminate! */
3050 while (result
< 0 && errno
== EEXIST
);
3055 /* Emulate Unix behavior - newname is deleted if it already exists
3056 (at least if it is a file; don't do this for directories).
3058 Since we mustn't do this if we are just changing the case of the
3059 file name (we would end up deleting the file we are trying to
3060 rename!), we let rename detect if the destination file already
3061 exists - that way we avoid the possible pitfalls of trying to
3062 determine ourselves whether two names really refer to the same
3063 file, which is not always possible in the general case. (Consider
3064 all the permutations of shared or subst'd drives, etc.) */
3066 newname
= map_w32_filename (newname
, NULL
);
3068 /* volume_info is set indirectly by map_w32_filename. */
3069 newname_dev
= volume_info
.serialnum
;
3071 result
= rename (temp
, newname
);
3075 DWORD w32err
= GetLastError ();
3078 && newname_dev
!= oldname_dev
)
3080 /* The implementation of `rename' on Windows does not return
3081 errno = EXDEV when you are moving a directory to a
3082 different storage device (ex. logical disk). It returns
3083 EACCES instead. So here we handle such situations and
3087 if ((attributes
= GetFileAttributes (temp
)) != -1
3088 && (attributes
& FILE_ATTRIBUTE_DIRECTORY
))
3091 else if (errno
== EEXIST
)
3093 if (_chmod (newname
, 0666) != 0)
3095 if (_unlink (newname
) != 0)
3097 result
= rename (temp
, newname
);
3099 else if (w32err
== ERROR_PRIVILEGE_NOT_HELD
3100 && is_symlink (temp
))
3102 /* This is Windows prohibiting the user from creating a
3103 symlink in another place, since that requires
3113 sys_rmdir (const char * path
)
3115 return _rmdir (map_w32_filename (path
, NULL
));
3119 sys_unlink (const char * path
)
3121 path
= map_w32_filename (path
, NULL
);
3123 /* On Unix, unlink works without write permission. */
3124 _chmod (path
, 0666);
3125 return _unlink (path
);
3128 static FILETIME utc_base_ft
;
3129 static ULONGLONG utc_base
; /* In 100ns units */
3130 static int init
= 0;
3132 #define FILETIME_TO_U64(result, ft) \
3134 ULARGE_INTEGER uiTemp; \
3135 uiTemp.LowPart = (ft).dwLowDateTime; \
3136 uiTemp.HighPart = (ft).dwHighDateTime; \
3137 result = uiTemp.QuadPart; \
3141 initialize_utc_base (void)
3143 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
3152 st
.wMilliseconds
= 0;
3154 SystemTimeToFileTime (&st
, &utc_base_ft
);
3155 FILETIME_TO_U64 (utc_base
, utc_base_ft
);
3159 convert_time (FILETIME ft
)
3165 initialize_utc_base ();
3169 if (CompareFileTime (&ft
, &utc_base_ft
) < 0)
3172 FILETIME_TO_U64 (tmp
, ft
);
3173 return (time_t) ((tmp
- utc_base
) / 10000000L);
3177 convert_from_time_t (time_t time
, FILETIME
* pft
)
3183 initialize_utc_base ();
3187 /* time in 100ns units since 1-Jan-1601 */
3188 tmp
.QuadPart
= (ULONGLONG
) time
* 10000000L + utc_base
;
3189 pft
->dwHighDateTime
= tmp
.HighPart
;
3190 pft
->dwLowDateTime
= tmp
.LowPart
;
3194 /* No reason to keep this; faking inode values either by hashing or even
3195 using the file index from GetInformationByHandle, is not perfect and
3196 so by default Emacs doesn't use the inode values on Windows.
3197 Instead, we now determine file-truename correctly (except for
3198 possible drive aliasing etc). */
3200 /* Modified version of "PJW" algorithm (see the "Dragon" compiler book). */
3202 hashval (const unsigned char * str
)
3207 h
= (h
<< 4) + *str
++;
3213 /* Return the hash value of the canonical pathname, excluding the
3214 drive/UNC header, to get a hopefully unique inode number. */
3216 generate_inode_val (const char * name
)
3218 char fullname
[ MAX_PATH
];
3222 /* Get the truly canonical filename, if it exists. (Note: this
3223 doesn't resolve aliasing due to subst commands, or recognize hard
3225 if (!w32_get_long_filename ((char *)name
, fullname
, MAX_PATH
))
3228 parse_root (fullname
, &p
);
3229 /* Normal W32 filesystems are still case insensitive. */
3236 static PSECURITY_DESCRIPTOR
3237 get_file_security_desc_by_handle (HANDLE h
)
3239 PSECURITY_DESCRIPTOR psd
= NULL
;
3241 SECURITY_INFORMATION si
= OWNER_SECURITY_INFORMATION
3242 | GROUP_SECURITY_INFORMATION
/* | DACL_SECURITY_INFORMATION */ ;
3244 err
= get_security_info (h
, SE_FILE_OBJECT
, si
,
3245 NULL
, NULL
, NULL
, NULL
, &psd
);
3246 if (err
!= ERROR_SUCCESS
)
3252 static PSECURITY_DESCRIPTOR
3253 get_file_security_desc_by_name (const char *fname
)
3255 PSECURITY_DESCRIPTOR psd
= NULL
;
3257 SECURITY_INFORMATION si
= OWNER_SECURITY_INFORMATION
3258 | GROUP_SECURITY_INFORMATION
/* | DACL_SECURITY_INFORMATION */ ;
3260 if (!get_file_security (fname
, si
, psd
, 0, &sd_len
))
3262 err
= GetLastError ();
3263 if (err
!= ERROR_INSUFFICIENT_BUFFER
)
3267 psd
= xmalloc (sd_len
);
3268 if (!get_file_security (fname
, si
, psd
, sd_len
, &sd_len
))
3280 unsigned n_subauthorities
;
3282 /* Use the last sub-authority value of the RID, the relative
3283 portion of the SID, as user/group ID. */
3284 n_subauthorities
= *get_sid_sub_authority_count (sid
);
3285 if (n_subauthorities
< 1)
3286 return 0; /* the "World" RID */
3287 return *get_sid_sub_authority (sid
, n_subauthorities
- 1);
3290 /* Caching SID and account values for faster lokup. */
3293 # define FLEXIBLE_ARRAY_MEMBER
3295 # define FLEXIBLE_ARRAY_MEMBER 1
3300 struct w32_id
*next
;
3302 unsigned char sid
[FLEXIBLE_ARRAY_MEMBER
];
3305 static struct w32_id
*w32_idlist
;
3308 w32_cached_id (PSID sid
, unsigned *id
, char *name
)
3310 struct w32_id
*tail
, *found
;
3312 for (found
= NULL
, tail
= w32_idlist
; tail
; tail
= tail
->next
)
3314 if (equal_sid ((PSID
)tail
->sid
, sid
))
3323 strcpy (name
, found
->name
);
3331 w32_add_to_cache (PSID sid
, unsigned id
, char *name
)
3334 struct w32_id
*new_entry
;
3336 /* We don't want to leave behind stale cache from when Emacs was
3340 sid_len
= get_length_sid (sid
);
3341 new_entry
= xmalloc (offsetof (struct w32_id
, sid
) + sid_len
);
3344 new_entry
->rid
= id
;
3345 strcpy (new_entry
->name
, name
);
3346 copy_sid (sid_len
, (PSID
)new_entry
->sid
, sid
);
3347 new_entry
->next
= w32_idlist
;
3348 w32_idlist
= new_entry
;
3357 get_name_and_id (PSECURITY_DESCRIPTOR psd
, const char *fname
,
3358 unsigned *id
, char *nm
, int what
)
3361 char machine
[MAX_COMPUTERNAME_LENGTH
+1];
3363 SID_NAME_USE ignore
;
3365 DWORD name_len
= sizeof (name
);
3367 DWORD domain_len
= sizeof (domain
);
3373 result
= get_security_descriptor_owner (psd
, &sid
, &dflt
);
3374 else if (what
== GID
)
3375 result
= get_security_descriptor_group (psd
, &sid
, &dflt
);
3379 if (!result
|| !is_valid_sid (sid
))
3381 else if (!w32_cached_id (sid
, id
, nm
))
3383 /* If FNAME is a UNC, we need to lookup account on the
3384 specified machine. */
3385 if (IS_DIRECTORY_SEP (fname
[0]) && IS_DIRECTORY_SEP (fname
[1])
3386 && fname
[2] != '\0')
3391 for (s
= fname
+ 2, p
= machine
;
3392 *s
&& !IS_DIRECTORY_SEP (*s
); s
++, p
++)
3398 if (!lookup_account_sid (mp
, sid
, name
, &name_len
,
3399 domain
, &domain_len
, &ignore
)
3400 || name_len
> UNLEN
+1)
3404 *id
= get_rid (sid
);
3406 w32_add_to_cache (sid
, *id
, name
);
3413 get_file_owner_and_group (PSECURITY_DESCRIPTOR psd
,
3417 int dflt_usr
= 0, dflt_grp
= 0;
3426 if (get_name_and_id (psd
, fname
, &st
->st_uid
, st
->st_uname
, UID
))
3428 if (get_name_and_id (psd
, fname
, &st
->st_gid
, st
->st_gname
, GID
))
3431 /* Consider files to belong to current user/group, if we cannot get
3432 more accurate information. */
3435 st
->st_uid
= dflt_passwd
.pw_uid
;
3436 strcpy (st
->st_uname
, dflt_passwd
.pw_name
);
3440 st
->st_gid
= dflt_passwd
.pw_gid
;
3441 strcpy (st
->st_gname
, dflt_group
.gr_name
);
3445 /* Return non-zero if NAME is a potentially slow filesystem. */
3447 is_slow_fs (const char *name
)
3452 if (IS_DIRECTORY_SEP (name
[0]) && IS_DIRECTORY_SEP (name
[1]))
3453 devtype
= DRIVE_REMOTE
; /* assume UNC name is remote */
3454 else if (!(strlen (name
) >= 2 && IS_DEVICE_SEP (name
[1])))
3455 devtype
= GetDriveType (NULL
); /* use root of current drive */
3458 /* GetDriveType needs the root directory of the drive. */
3459 strncpy (drive_root
, name
, 2);
3460 drive_root
[2] = '\\';
3461 drive_root
[3] = '\0';
3462 devtype
= GetDriveType (drive_root
);
3464 return !(devtype
== DRIVE_FIXED
|| devtype
== DRIVE_RAMDISK
);
3467 /* MSVC stat function can't cope with UNC names and has other bugs, so
3468 replace it with our own. This also allows us to calculate consistent
3469 inode values and owner/group without hacks in the main Emacs code. */
3472 stat_worker (const char * path
, struct stat
* buf
, int follow_symlinks
)
3474 char *name
, *save_name
, *r
;
3475 WIN32_FIND_DATA wfd
;
3477 unsigned __int64 fake_inode
= 0;
3480 int rootdir
= FALSE
;
3481 PSECURITY_DESCRIPTOR psd
= NULL
;
3482 int is_a_symlink
= 0;
3483 DWORD file_flags
= FILE_FLAG_BACKUP_SEMANTICS
;
3484 DWORD access_rights
= 0;
3485 DWORD fattrs
= 0, serialnum
= 0, fs_high
= 0, fs_low
= 0, nlinks
= 1;
3486 FILETIME ctime
, atime
, wtime
;
3488 if (path
== NULL
|| buf
== NULL
)
3494 save_name
= name
= (char *) map_w32_filename (path
, &path
);
3495 /* Must be valid filename, no wild cards or other invalid
3496 characters. We use _mbspbrk to support multibyte strings that
3497 might look to strpbrk as if they included literal *, ?, and other
3498 characters mentioned below that are disallowed by Windows
3500 if (_mbspbrk (name
, "*?|<>\""))
3506 /* Remove trailing directory separator, unless name is the root
3507 directory of a drive or UNC volume in which case ensure there
3508 is a trailing separator. */
3509 len
= strlen (name
);
3510 name
= strcpy (alloca (len
+ 2), name
);
3512 /* Avoid a somewhat costly call to is_symlink if the filesystem
3513 doesn't support symlinks. */
3514 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) != 0)
3515 is_a_symlink
= is_symlink (name
);
3517 /* Plan A: Open the file and get all the necessary information via
3518 the resulting handle. This solves several issues in one blow:
3520 . retrieves attributes for the target of a symlink, if needed
3521 . gets attributes of root directories and symlinks pointing to
3522 root directories, thus avoiding the need for special-casing
3523 these and detecting them by examining the file-name format
3524 . retrieves more accurate attributes (e.g., non-zero size for
3525 some directories, esp. directories that are junction points)
3526 . correctly resolves "c:/..", "/.." and similar file names
3527 . avoids run-time penalties for 99% of use cases
3529 Plan A is always tried first, unless the user asked not to (but
3530 if the file is a symlink and we need to follow links, we try Plan
3531 A even if the user asked not to).
3533 If Plan A fails, we go to Plan B (below), where various
3534 potentially expensive techniques must be used to handle "special"
3535 files such as UNC volumes etc. */
3536 if (!(NILP (Vw32_get_true_file_attributes
)
3537 || (EQ (Vw32_get_true_file_attributes
, Qlocal
) && is_slow_fs (name
)))
3538 /* Following symlinks requires getting the info by handle. */
3539 || (is_a_symlink
&& follow_symlinks
))
3541 BY_HANDLE_FILE_INFORMATION info
;
3543 if (is_a_symlink
&& !follow_symlinks
)
3544 file_flags
|= FILE_FLAG_OPEN_REPARSE_POINT
;
3545 /* READ_CONTROL access rights are required to get security info
3546 by handle. But if the OS doesn't support security in the
3547 first place, we don't need to try. */
3548 if (is_windows_9x () != TRUE
)
3549 access_rights
|= READ_CONTROL
;
3551 fh
= CreateFile (name
, access_rights
, 0, NULL
, OPEN_EXISTING
,
3553 /* If CreateFile fails with READ_CONTROL, try again with zero as
3555 if (fh
== INVALID_HANDLE_VALUE
&& access_rights
)
3556 fh
= CreateFile (name
, 0, 0, NULL
, OPEN_EXISTING
,
3558 if (fh
== INVALID_HANDLE_VALUE
)
3559 goto no_true_file_attributes
;
3561 /* This is more accurate in terms of getting the correct number
3562 of links, but is quite slow (it is noticeable when Emacs is
3563 making a list of file name completions). */
3564 if (GetFileInformationByHandle (fh
, &info
))
3566 nlinks
= info
.nNumberOfLinks
;
3567 /* Might as well use file index to fake inode values, but this
3568 is not guaranteed to be unique unless we keep a handle open
3569 all the time (even then there are situations where it is
3570 not unique). Reputedly, there are at most 48 bits of info
3571 (on NTFS, presumably less on FAT). */
3572 fake_inode
= info
.nFileIndexHigh
;
3574 fake_inode
+= info
.nFileIndexLow
;
3575 serialnum
= info
.dwVolumeSerialNumber
;
3576 fs_high
= info
.nFileSizeHigh
;
3577 fs_low
= info
.nFileSizeLow
;
3578 ctime
= info
.ftCreationTime
;
3579 atime
= info
.ftLastAccessTime
;
3580 wtime
= info
.ftLastWriteTime
;
3581 fattrs
= info
.dwFileAttributes
;
3585 /* We don't go to Plan B here, because it's not clear that
3586 it's a good idea. The only known use case where
3587 CreateFile succeeds, but GetFileInformationByHandle fails
3588 (with ERROR_INVALID_FUNCTION) is for character devices
3589 such as NUL, PRN, etc. For these, switching to Plan B is
3590 a net loss, because we lose the character device
3591 attribute returned by GetFileType below (FindFirstFile
3592 doesn't set that bit in the attributes), and the other
3593 fields don't make sense for character devices anyway.
3594 Emacs doesn't really care for non-file entities in the
3595 context of l?stat, so neither do we. */
3597 /* w32err is assigned so one could put a breakpoint here and
3598 examine its value, when GetFileInformationByHandle
3600 DWORD w32err
= GetLastError ();
3604 case ERROR_FILE_NOT_FOUND
: /* can this ever happen? */
3610 /* Test for a symlink before testing for a directory, since
3611 symlinks to directories have the directory bit set, but we
3612 don't want them to appear as directories. */
3613 if (is_a_symlink
&& !follow_symlinks
)
3614 buf
->st_mode
= S_IFLNK
;
3615 else if (fattrs
& FILE_ATTRIBUTE_DIRECTORY
)
3616 buf
->st_mode
= S_IFDIR
;
3619 DWORD ftype
= GetFileType (fh
);
3623 case FILE_TYPE_DISK
:
3624 buf
->st_mode
= S_IFREG
;
3626 case FILE_TYPE_PIPE
:
3627 buf
->st_mode
= S_IFIFO
;
3629 case FILE_TYPE_CHAR
:
3630 case FILE_TYPE_UNKNOWN
:
3632 buf
->st_mode
= S_IFCHR
;
3635 /* We produce the fallback owner and group data, based on the
3636 current user that runs Emacs, in the following cases:
3638 . this is Windows 9X
3639 . getting security by handle failed, and we need to produce
3640 information for the target of a symlink (this is better
3641 than producing a potentially misleading info about the
3644 If getting security by handle fails, and we don't need to
3645 resolve symlinks, we try getting security by name. */
3646 if (is_windows_9x () != TRUE
)
3647 psd
= get_file_security_desc_by_handle (fh
);
3650 get_file_owner_and_group (psd
, name
, buf
);
3653 else if (is_windows_9x () == TRUE
)
3654 get_file_owner_and_group (NULL
, name
, buf
);
3655 else if (!(is_a_symlink
&& follow_symlinks
))
3657 psd
= get_file_security_desc_by_name (name
);
3658 get_file_owner_and_group (psd
, name
, buf
);
3662 get_file_owner_and_group (NULL
, name
, buf
);
3667 no_true_file_attributes
:
3668 /* Plan B: Either getting a handle on the file failed, or the
3669 caller explicitly asked us to not bother making this
3670 information more accurate.
3672 Implementation note: In Plan B, we never bother to resolve
3673 symlinks, even if we got here because we tried Plan A and
3674 failed. That's because, even if the caller asked for extra
3675 precision by setting Vw32_get_true_file_attributes to t,
3676 resolving symlinks requires acquiring a file handle to the
3677 symlink, which we already know will fail. And if the user
3678 did not ask for extra precision, resolving symlinks will fly
3679 in the face of that request, since the user then wants the
3680 lightweight version of the code. */
3681 rootdir
= (path
>= save_name
+ len
- 1
3682 && (IS_DIRECTORY_SEP (*path
) || *path
== 0));
3684 /* If name is "c:/.." or "/.." then stat "c:/" or "/". */
3685 r
= IS_DEVICE_SEP (name
[1]) ? &name
[2] : name
;
3686 if (IS_DIRECTORY_SEP (r
[0])
3687 && r
[1] == '.' && r
[2] == '.' && r
[3] == '\0')
3690 /* Note: If NAME is a symlink to the root of a UNC volume
3691 (i.e. "\\SERVER"), we will not detect that here, and we will
3692 return data about the symlink as result of FindFirst below.
3693 This is unfortunate, but that marginal use case does not
3694 justify a call to chase_symlinks which would impose a penalty
3695 on all the other use cases. (We get here for symlinks to
3696 roots of UNC volumes because CreateFile above fails for them,
3697 unlike with symlinks to root directories X:\ of drives.) */
3698 if (is_unc_volume (name
))
3700 fattrs
= unc_volume_file_attributes (name
);
3704 ctime
= atime
= wtime
= utc_base_ft
;
3708 if (!IS_DIRECTORY_SEP (name
[len
-1]))
3709 strcat (name
, "\\");
3710 if (GetDriveType (name
) < 2)
3716 fattrs
= FILE_ATTRIBUTE_DIRECTORY
;
3717 ctime
= atime
= wtime
= utc_base_ft
;
3721 if (IS_DIRECTORY_SEP (name
[len
-1]))
3724 /* (This is hacky, but helps when doing file completions on
3725 network drives.) Optimize by using information available from
3726 active readdir if possible. */
3727 len
= strlen (dir_pathname
);
3728 if (IS_DIRECTORY_SEP (dir_pathname
[len
-1]))
3730 if (dir_find_handle
!= INVALID_HANDLE_VALUE
3731 && !(is_a_symlink
&& follow_symlinks
)
3732 && strnicmp (save_name
, dir_pathname
, len
) == 0
3733 && IS_DIRECTORY_SEP (name
[len
])
3734 && xstrcasecmp (name
+ len
+ 1, dir_static
.d_name
) == 0)
3736 /* This was the last entry returned by readdir. */
3737 wfd
= dir_find_data
;
3741 logon_network_drive (name
);
3743 fh
= FindFirstFile (name
, &wfd
);
3744 if (fh
== INVALID_HANDLE_VALUE
)
3751 /* Note: if NAME is a symlink, the information we get from
3752 FindFirstFile is for the symlink, not its target. */
3753 fattrs
= wfd
.dwFileAttributes
;
3754 ctime
= wfd
.ftCreationTime
;
3755 atime
= wfd
.ftLastAccessTime
;
3756 wtime
= wfd
.ftLastWriteTime
;
3757 fs_high
= wfd
.nFileSizeHigh
;
3758 fs_low
= wfd
.nFileSizeLow
;
3761 serialnum
= volume_info
.serialnum
;
3763 if (is_a_symlink
&& !follow_symlinks
)
3764 buf
->st_mode
= S_IFLNK
;
3765 else if (fattrs
& FILE_ATTRIBUTE_DIRECTORY
)
3766 buf
->st_mode
= S_IFDIR
;
3768 buf
->st_mode
= S_IFREG
;
3770 get_file_owner_and_group (NULL
, name
, buf
);
3774 /* Not sure if there is any point in this. */
3775 if (!NILP (Vw32_generate_fake_inodes
))
3776 fake_inode
= generate_inode_val (name
);
3777 else if (fake_inode
== 0)
3779 /* For want of something better, try to make everything unique. */
3780 static DWORD gen_num
= 0;
3781 fake_inode
= ++gen_num
;
3785 buf
->st_ino
= fake_inode
;
3787 buf
->st_dev
= serialnum
;
3788 buf
->st_rdev
= serialnum
;
3790 buf
->st_size
= fs_high
;
3791 buf
->st_size
<<= 32;
3792 buf
->st_size
+= fs_low
;
3793 buf
->st_nlink
= nlinks
;
3795 /* Convert timestamps to Unix format. */
3796 buf
->st_mtime
= convert_time (wtime
);
3797 buf
->st_atime
= convert_time (atime
);
3798 if (buf
->st_atime
== 0) buf
->st_atime
= buf
->st_mtime
;
3799 buf
->st_ctime
= convert_time (ctime
);
3800 if (buf
->st_ctime
== 0) buf
->st_ctime
= buf
->st_mtime
;
3802 /* determine rwx permissions */
3803 if (is_a_symlink
&& !follow_symlinks
)
3804 permission
= S_IREAD
| S_IWRITE
| S_IEXEC
; /* Posix expectations */
3807 if (fattrs
& FILE_ATTRIBUTE_READONLY
)
3808 permission
= S_IREAD
;
3810 permission
= S_IREAD
| S_IWRITE
;
3812 if (fattrs
& FILE_ATTRIBUTE_DIRECTORY
)
3813 permission
|= S_IEXEC
;
3814 else if (is_exec (name
))
3815 permission
|= S_IEXEC
;
3818 buf
->st_mode
|= permission
| (permission
>> 3) | (permission
>> 6);
3824 stat (const char * path
, struct stat
* buf
)
3826 return stat_worker (path
, buf
, 1);
3830 lstat (const char * path
, struct stat
* buf
)
3832 return stat_worker (path
, buf
, 0);
3835 /* Provide fstat and utime as well as stat for consistent handling of
3838 fstat (int desc
, struct stat
* buf
)
3840 HANDLE fh
= (HANDLE
) _get_osfhandle (desc
);
3841 BY_HANDLE_FILE_INFORMATION info
;
3842 unsigned __int64 fake_inode
;
3845 switch (GetFileType (fh
) & ~FILE_TYPE_REMOTE
)
3847 case FILE_TYPE_DISK
:
3848 buf
->st_mode
= S_IFREG
;
3849 if (!GetFileInformationByHandle (fh
, &info
))
3855 case FILE_TYPE_PIPE
:
3856 buf
->st_mode
= S_IFIFO
;
3858 case FILE_TYPE_CHAR
:
3859 case FILE_TYPE_UNKNOWN
:
3861 buf
->st_mode
= S_IFCHR
;
3863 memset (&info
, 0, sizeof (info
));
3864 info
.dwFileAttributes
= 0;
3865 info
.ftCreationTime
= utc_base_ft
;
3866 info
.ftLastAccessTime
= utc_base_ft
;
3867 info
.ftLastWriteTime
= utc_base_ft
;
3870 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
3871 buf
->st_mode
= S_IFDIR
;
3873 buf
->st_nlink
= info
.nNumberOfLinks
;
3874 /* Might as well use file index to fake inode values, but this
3875 is not guaranteed to be unique unless we keep a handle open
3876 all the time (even then there are situations where it is
3877 not unique). Reputedly, there are at most 48 bits of info
3878 (on NTFS, presumably less on FAT). */
3879 fake_inode
= info
.nFileIndexHigh
;
3881 fake_inode
+= info
.nFileIndexLow
;
3883 /* MSVC defines _ino_t to be short; other libc's might not. */
3884 if (sizeof (buf
->st_ino
) == 2)
3885 buf
->st_ino
= fake_inode
^ (fake_inode
>> 16);
3887 buf
->st_ino
= fake_inode
;
3889 /* Consider files to belong to current user.
3890 FIXME: this should use GetSecurityInfo API, but it is only
3891 available for _WIN32_WINNT >= 0x501. */
3892 buf
->st_uid
= dflt_passwd
.pw_uid
;
3893 buf
->st_gid
= dflt_passwd
.pw_gid
;
3894 strcpy (buf
->st_uname
, dflt_passwd
.pw_name
);
3895 strcpy (buf
->st_gname
, dflt_group
.gr_name
);
3897 buf
->st_dev
= info
.dwVolumeSerialNumber
;
3898 buf
->st_rdev
= info
.dwVolumeSerialNumber
;
3900 buf
->st_size
= info
.nFileSizeHigh
;
3901 buf
->st_size
<<= 32;
3902 buf
->st_size
+= info
.nFileSizeLow
;
3904 /* Convert timestamps to Unix format. */
3905 buf
->st_mtime
= convert_time (info
.ftLastWriteTime
);
3906 buf
->st_atime
= convert_time (info
.ftLastAccessTime
);
3907 if (buf
->st_atime
== 0) buf
->st_atime
= buf
->st_mtime
;
3908 buf
->st_ctime
= convert_time (info
.ftCreationTime
);
3909 if (buf
->st_ctime
== 0) buf
->st_ctime
= buf
->st_mtime
;
3911 /* determine rwx permissions */
3912 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
)
3913 permission
= S_IREAD
;
3915 permission
= S_IREAD
| S_IWRITE
;
3917 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
3918 permission
|= S_IEXEC
;
3921 #if 0 /* no way of knowing the filename */
3922 char * p
= strrchr (name
, '.');
3924 (xstrcasecmp (p
, ".exe") == 0 ||
3925 xstrcasecmp (p
, ".com") == 0 ||
3926 xstrcasecmp (p
, ".bat") == 0 ||
3927 xstrcasecmp (p
, ".cmd") == 0))
3928 permission
|= S_IEXEC
;
3932 buf
->st_mode
|= permission
| (permission
>> 3) | (permission
>> 6);
3938 utime (const char *name
, struct utimbuf
*times
)
3940 struct utimbuf deftime
;
3947 deftime
.modtime
= deftime
.actime
= time (NULL
);
3951 /* Need write access to set times. */
3952 fh
= CreateFile (name
, FILE_WRITE_ATTRIBUTES
,
3953 /* If NAME specifies a directory, FILE_SHARE_DELETE
3954 allows other processes to delete files inside it,
3955 while we have the directory open. */
3956 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
3957 0, OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
3958 if (fh
!= INVALID_HANDLE_VALUE
)
3960 convert_from_time_t (times
->actime
, &atime
);
3961 convert_from_time_t (times
->modtime
, &mtime
);
3962 if (!SetFileTime (fh
, NULL
, &atime
, &mtime
))
3979 /* Symlink-related functions. */
3980 #ifndef SYMBOLIC_LINK_FLAG_DIRECTORY
3981 #define SYMBOLIC_LINK_FLAG_DIRECTORY 0x1
3985 symlink (char const *filename
, char const *linkname
)
3987 char linkfn
[MAX_PATH
], *tgtfn
;
3989 int dir_access
, filename_ends_in_slash
;
3991 /* Diagnostics follows Posix as much as possible. */
3992 if (filename
== NULL
|| linkname
== NULL
)
4002 if (strlen (filename
) > MAX_PATH
|| strlen (linkname
) > MAX_PATH
)
4004 errno
= ENAMETOOLONG
;
4008 strcpy (linkfn
, map_w32_filename (linkname
, NULL
));
4009 if ((volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) == 0)
4015 /* Note: since empty FILENAME was already rejected, we can safely
4016 refer to FILENAME[1]. */
4017 if (!(IS_DIRECTORY_SEP (filename
[0]) || IS_DEVICE_SEP (filename
[1])))
4019 /* Non-absolute FILENAME is understood as being relative to
4020 LINKNAME's directory. We need to prepend that directory to
4021 FILENAME to get correct results from sys_access below, since
4022 otherwise it will interpret FILENAME relative to the
4023 directory where the Emacs process runs. Note that
4024 make-symbolic-link always makes sure LINKNAME is a fully
4025 expanded file name. */
4027 char *p
= linkfn
+ strlen (linkfn
);
4029 while (p
> linkfn
&& !IS_ANY_SEP (p
[-1]))
4032 strncpy (tem
, linkfn
, p
- linkfn
);
4033 tem
[p
- linkfn
] = '\0';
4034 strcat (tem
, filename
);
4035 dir_access
= sys_access (tem
, D_OK
);
4038 dir_access
= sys_access (filename
, D_OK
);
4040 /* Since Windows distinguishes between symlinks to directories and
4041 to files, we provide a kludgy feature: if FILENAME doesn't
4042 exist, but ends in a slash, we create a symlink to directory. If
4043 FILENAME exists and is a directory, we always create a symlink to
4045 filename_ends_in_slash
= IS_DIRECTORY_SEP (filename
[strlen (filename
) - 1]);
4046 if (dir_access
== 0 || filename_ends_in_slash
)
4047 flags
= SYMBOLIC_LINK_FLAG_DIRECTORY
;
4049 tgtfn
= (char *)map_w32_filename (filename
, NULL
);
4050 if (filename_ends_in_slash
)
4051 tgtfn
[strlen (tgtfn
) - 1] = '\0';
4054 if (!create_symbolic_link (linkfn
, tgtfn
, flags
))
4056 /* ENOSYS is set by create_symbolic_link, when it detects that
4057 the OS doesn't support the CreateSymbolicLink API. */
4058 if (errno
!= ENOSYS
)
4060 DWORD w32err
= GetLastError ();
4064 /* ERROR_SUCCESS is sometimes returned when LINKFN and
4065 TGTFN point to the same file name, go figure. */
4067 case ERROR_FILE_EXISTS
:
4070 case ERROR_ACCESS_DENIED
:
4073 case ERROR_FILE_NOT_FOUND
:
4074 case ERROR_PATH_NOT_FOUND
:
4075 case ERROR_BAD_NETPATH
:
4076 case ERROR_INVALID_REPARSE_DATA
:
4079 case ERROR_DIRECTORY
:
4082 case ERROR_PRIVILEGE_NOT_HELD
:
4083 case ERROR_NOT_ALL_ASSIGNED
:
4086 case ERROR_DISK_FULL
:
4099 /* A quick inexpensive test of whether FILENAME identifies a file that
4100 is a symlink. Returns non-zero if it is, zero otherwise. FILENAME
4101 must already be in the normalized form returned by
4104 Note: for repeated operations on many files, it is best to test
4105 whether the underlying volume actually supports symlinks, by
4106 testing the FILE_SUPPORTS_REPARSE_POINTS bit in volume's flags, and
4107 avoid the call to this function if it doesn't. That's because the
4108 call to GetFileAttributes takes a non-negligible time, especially
4109 on non-local or removable filesystems. See stat_worker for an
4110 example of how to do that. */
4112 is_symlink (const char *filename
)
4115 WIN32_FIND_DATA wfd
;
4118 attrs
= GetFileAttributes (filename
);
4121 DWORD w32err
= GetLastError ();
4125 case ERROR_BAD_NETPATH
: /* network share, can't be a symlink */
4127 case ERROR_ACCESS_DENIED
:
4130 case ERROR_FILE_NOT_FOUND
:
4131 case ERROR_PATH_NOT_FOUND
:
4138 if ((attrs
& FILE_ATTRIBUTE_REPARSE_POINT
) == 0)
4140 logon_network_drive (filename
);
4141 fh
= FindFirstFile (filename
, &wfd
);
4142 if (fh
== INVALID_HANDLE_VALUE
)
4145 return (wfd
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
) != 0
4146 && (wfd
.dwReserved0
& IO_REPARSE_TAG_SYMLINK
) == IO_REPARSE_TAG_SYMLINK
;
4149 /* If NAME identifies a symbolic link, copy into BUF the file name of
4150 the symlink's target. Copy at most BUF_SIZE bytes, and do NOT
4151 null-terminate the target name, even if it fits. Return the number
4152 of bytes copied, or -1 if NAME is not a symlink or any error was
4153 encountered while resolving it. The file name copied into BUF is
4154 encoded in the current ANSI codepage. */
4156 readlink (const char *name
, char *buf
, size_t buf_size
)
4159 TOKEN_PRIVILEGES privs
;
4160 int restore_privs
= 0;
4175 path
= map_w32_filename (name
, NULL
);
4177 if (strlen (path
) > MAX_PATH
)
4179 errno
= ENAMETOOLONG
;
4184 if (is_windows_9x () == TRUE
4185 || (volume_info
.flags
& FILE_SUPPORTS_REPARSE_POINTS
) == 0
4186 || !is_symlink (path
))
4189 errno
= EINVAL
; /* not a symlink */
4193 /* Done with simple tests, now we're in for some _real_ work. */
4194 if (enable_privilege (SE_BACKUP_NAME
, TRUE
, &privs
))
4196 /* Implementation note: From here and onward, don't return early,
4197 since that will fail to restore the original set of privileges of
4198 the calling thread. */
4200 retval
= -1; /* not too optimistic, are we? */
4202 /* Note: In the next call to CreateFile, we use zero as the 2nd
4203 argument because, when the symlink is a hidden/system file,
4204 e.g. 'C:\Users\All Users', GENERIC_READ fails with
4205 ERROR_ACCESS_DENIED. Zero seems to work just fine, both for file
4206 and directory symlinks. */
4207 sh
= CreateFile (path
, 0, 0, NULL
, OPEN_EXISTING
,
4208 FILE_FLAG_OPEN_REPARSE_POINT
| FILE_FLAG_BACKUP_SEMANTICS
,
4210 if (sh
!= INVALID_HANDLE_VALUE
)
4212 BYTE reparse_buf
[MAXIMUM_REPARSE_DATA_BUFFER_SIZE
];
4213 REPARSE_DATA_BUFFER
*reparse_data
= (REPARSE_DATA_BUFFER
*)&reparse_buf
[0];
4216 if (!DeviceIoControl (sh
, FSCTL_GET_REPARSE_POINT
, NULL
, 0,
4217 reparse_buf
, MAXIMUM_REPARSE_DATA_BUFFER_SIZE
,
4220 else if (reparse_data
->ReparseTag
!= IO_REPARSE_TAG_SYMLINK
)
4224 /* Copy the link target name, in wide characters, fro
4225 reparse_data, then convert it to multibyte encoding in
4226 the current locale's codepage. */
4228 BYTE lname
[MAX_PATH
];
4231 reparse_data
->SymbolicLinkReparseBuffer
.PrintNameLength
;
4233 reparse_data
->SymbolicLinkReparseBuffer
.PathBuffer
4234 + reparse_data
->SymbolicLinkReparseBuffer
.PrintNameOffset
/sizeof(WCHAR
);
4236 /* According to MSDN, PrintNameLength does not include the
4237 terminating null character. */
4238 lwname
= alloca ((lwname_len
+ 1) * sizeof(WCHAR
));
4239 memcpy (lwname
, lwname_src
, lwname_len
);
4240 lwname
[lwname_len
/sizeof(WCHAR
)] = 0; /* null-terminate */
4242 /* FIXME: Should we use the current file-name coding system
4243 instead of the fixed value of the ANSI codepage? */
4244 lname_len
= WideCharToMultiByte (w32_ansi_code_page
, 0, lwname
, -1,
4245 lname
, MAX_PATH
, NULL
, NULL
);
4248 /* WideCharToMultiByte failed. */
4249 DWORD w32err1
= GetLastError ();
4253 case ERROR_INSUFFICIENT_BUFFER
:
4254 errno
= ENAMETOOLONG
;
4256 case ERROR_INVALID_PARAMETER
:
4259 case ERROR_NO_UNICODE_TRANSLATION
:
4269 size_t size_to_copy
= buf_size
;
4271 BYTE
*pend
= p
+ lname_len
;
4273 /* Normalize like dostounix_filename does, but we don't
4274 want to assume that lname is null-terminated. */
4275 if (*p
&& p
[1] == ':' && *p
>= 'A' && *p
<= 'Z')
4283 /* Testing for null-terminated LNAME is paranoia:
4284 WideCharToMultiByte should always return a
4285 null-terminated string when its 4th argument is -1
4286 and its 3rd argument is null-terminated (which they
4288 if (lname
[lname_len
- 1] == '\0')
4290 if (lname_len
<= buf_size
)
4291 size_to_copy
= lname_len
;
4292 strncpy (buf
, lname
, size_to_copy
);
4294 retval
= size_to_copy
;
4301 /* CreateFile failed. */
4302 DWORD w32err2
= GetLastError ();
4306 case ERROR_FILE_NOT_FOUND
:
4307 case ERROR_PATH_NOT_FOUND
:
4310 case ERROR_ACCESS_DENIED
:
4311 case ERROR_TOO_MANY_OPEN_FILES
:
4321 restore_privilege (&privs
);
4328 /* If FILE is a symlink, return its target (stored in a static
4329 buffer); otherwise return FILE.
4331 This function repeatedly resolves symlinks in the last component of
4332 a chain of symlink file names, as in foo -> bar -> baz -> ...,
4333 until it arrives at a file whose last component is not a symlink,
4334 or some error occurs. It returns the target of the last
4335 successfully resolved symlink in the chain. If it succeeds to
4336 resolve even a single symlink, the value returned is an absolute
4337 file name with backslashes (result of GetFullPathName). By
4338 contrast, if the original FILE is returned, it is unaltered.
4340 Note: This function can set errno even if it succeeds.
4342 Implementation note: we only resolve the last portion ("basename")
4343 of the argument FILE and of each following file in the chain,
4344 disregarding any possible symlinks in its leading directories.
4345 This is because Windows system calls and library functions
4346 transparently resolve symlinks in leading directories and return
4347 correct information, as long as the basename is not a symlink. */
4349 chase_symlinks (const char *file
)
4351 static char target
[MAX_PATH
];
4352 char link
[MAX_PATH
];
4353 ssize_t res
, link_len
;
4356 if (is_windows_9x () == TRUE
|| !is_symlink (file
))
4357 return (char *)file
;
4359 if ((link_len
= GetFullPathName (file
, MAX_PATH
, link
, NULL
)) == 0)
4360 return (char *)file
;
4365 /* Remove trailing slashes, as we want to resolve the last
4366 non-trivial part of the link name. */
4367 while (link_len
> 3 && IS_DIRECTORY_SEP (link
[link_len
-1]))
4368 link
[link_len
--] = '\0';
4370 res
= readlink (link
, target
, MAX_PATH
);
4374 if (!(IS_DEVICE_SEP (target
[1])
4375 || (IS_DIRECTORY_SEP (target
[0]) && IS_DIRECTORY_SEP (target
[1]))))
4377 /* Target is relative. Append it to the directory part of
4378 the symlink, then copy the result back to target. */
4379 char *p
= link
+ link_len
;
4381 while (p
> link
&& !IS_ANY_SEP (p
[-1]))
4384 strcpy (target
, link
);
4386 /* Resolve any "." and ".." to get a fully-qualified file name
4388 link_len
= GetFullPathName (target
, MAX_PATH
, link
, NULL
);
4390 } while (res
> 0 && link_len
> 0 && ++loop_count
<= 100);
4392 if (loop_count
> 100)
4395 if (target
[0] == '\0') /* not a single call to readlink succeeded */
4396 return (char *)file
;
4400 /* MS-Windows version of careadlinkat (cf. ../lib/careadlinkat.c). We
4401 have a fixed max size for file names, so we don't need the kind of
4402 alloc/malloc/realloc dance the gnulib version does. We also don't
4403 support FD-relative symlinks. */
4405 careadlinkat (int fd
, char const *filename
,
4406 char *buffer
, size_t buffer_size
,
4407 struct allocator
const *alloc
,
4408 ssize_t (*preadlinkat
) (int, char const *, char *, size_t))
4410 char linkname
[MAX_PATH
];
4419 link_size
= preadlinkat (fd
, filename
, linkname
, sizeof(linkname
));
4423 char *retval
= buffer
;
4425 linkname
[link_size
++] = '\0';
4426 if (link_size
> buffer_size
)
4427 retval
= (char *)(alloc
? alloc
->allocate
: xmalloc
) (link_size
);
4429 memcpy (retval
, linkname
, link_size
);
4437 careadlinkatcwd (int fd
, char const *filename
, char *buffer
,
4441 return readlink (filename
, buffer
, buffer_size
);
4445 /* Support for browsing other processes and their attributes. See
4446 process.c for the Lisp bindings. */
4448 /* Helper wrapper functions. */
4450 static HANDLE WINAPI
4451 create_toolhelp32_snapshot (DWORD Flags
, DWORD Ignored
)
4453 static CreateToolhelp32Snapshot_Proc s_pfn_Create_Toolhelp32_Snapshot
= NULL
;
4455 if (g_b_init_create_toolhelp32_snapshot
== 0)
4457 g_b_init_create_toolhelp32_snapshot
= 1;
4458 s_pfn_Create_Toolhelp32_Snapshot
= (CreateToolhelp32Snapshot_Proc
)
4459 GetProcAddress (GetModuleHandle ("kernel32.dll"),
4460 "CreateToolhelp32Snapshot");
4462 if (s_pfn_Create_Toolhelp32_Snapshot
== NULL
)
4464 return INVALID_HANDLE_VALUE
;
4466 return (s_pfn_Create_Toolhelp32_Snapshot (Flags
, Ignored
));
4470 process32_first (HANDLE hSnapshot
, LPPROCESSENTRY32 lppe
)
4472 static Process32First_Proc s_pfn_Process32_First
= NULL
;
4474 if (g_b_init_process32_first
== 0)
4476 g_b_init_process32_first
= 1;
4477 s_pfn_Process32_First
= (Process32First_Proc
)
4478 GetProcAddress (GetModuleHandle ("kernel32.dll"),
4481 if (s_pfn_Process32_First
== NULL
)
4485 return (s_pfn_Process32_First (hSnapshot
, lppe
));
4489 process32_next (HANDLE hSnapshot
, LPPROCESSENTRY32 lppe
)
4491 static Process32Next_Proc s_pfn_Process32_Next
= NULL
;
4493 if (g_b_init_process32_next
== 0)
4495 g_b_init_process32_next
= 1;
4496 s_pfn_Process32_Next
= (Process32Next_Proc
)
4497 GetProcAddress (GetModuleHandle ("kernel32.dll"),
4500 if (s_pfn_Process32_Next
== NULL
)
4504 return (s_pfn_Process32_Next (hSnapshot
, lppe
));
4508 open_thread_token (HANDLE ThreadHandle
,
4509 DWORD DesiredAccess
,
4511 PHANDLE TokenHandle
)
4513 static OpenThreadToken_Proc s_pfn_Open_Thread_Token
= NULL
;
4514 HMODULE hm_advapi32
= NULL
;
4515 if (is_windows_9x () == TRUE
)
4517 SetLastError (ERROR_NOT_SUPPORTED
);
4520 if (g_b_init_open_thread_token
== 0)
4522 g_b_init_open_thread_token
= 1;
4523 hm_advapi32
= LoadLibrary ("Advapi32.dll");
4524 s_pfn_Open_Thread_Token
=
4525 (OpenThreadToken_Proc
) GetProcAddress (hm_advapi32
, "OpenThreadToken");
4527 if (s_pfn_Open_Thread_Token
== NULL
)
4529 SetLastError (ERROR_NOT_SUPPORTED
);
4533 s_pfn_Open_Thread_Token (
4542 impersonate_self (SECURITY_IMPERSONATION_LEVEL ImpersonationLevel
)
4544 static ImpersonateSelf_Proc s_pfn_Impersonate_Self
= NULL
;
4545 HMODULE hm_advapi32
= NULL
;
4546 if (is_windows_9x () == TRUE
)
4550 if (g_b_init_impersonate_self
== 0)
4552 g_b_init_impersonate_self
= 1;
4553 hm_advapi32
= LoadLibrary ("Advapi32.dll");
4554 s_pfn_Impersonate_Self
=
4555 (ImpersonateSelf_Proc
) GetProcAddress (hm_advapi32
, "ImpersonateSelf");
4557 if (s_pfn_Impersonate_Self
== NULL
)
4561 return s_pfn_Impersonate_Self (ImpersonationLevel
);
4565 revert_to_self (void)
4567 static RevertToSelf_Proc s_pfn_Revert_To_Self
= NULL
;
4568 HMODULE hm_advapi32
= NULL
;
4569 if (is_windows_9x () == TRUE
)
4573 if (g_b_init_revert_to_self
== 0)
4575 g_b_init_revert_to_self
= 1;
4576 hm_advapi32
= LoadLibrary ("Advapi32.dll");
4577 s_pfn_Revert_To_Self
=
4578 (RevertToSelf_Proc
) GetProcAddress (hm_advapi32
, "RevertToSelf");
4580 if (s_pfn_Revert_To_Self
== NULL
)
4584 return s_pfn_Revert_To_Self ();
4588 get_process_memory_info (HANDLE h_proc
,
4589 PPROCESS_MEMORY_COUNTERS mem_counters
,
4592 static GetProcessMemoryInfo_Proc s_pfn_Get_Process_Memory_Info
= NULL
;
4593 HMODULE hm_psapi
= NULL
;
4594 if (is_windows_9x () == TRUE
)
4598 if (g_b_init_get_process_memory_info
== 0)
4600 g_b_init_get_process_memory_info
= 1;
4601 hm_psapi
= LoadLibrary ("Psapi.dll");
4603 s_pfn_Get_Process_Memory_Info
= (GetProcessMemoryInfo_Proc
)
4604 GetProcAddress (hm_psapi
, "GetProcessMemoryInfo");
4606 if (s_pfn_Get_Process_Memory_Info
== NULL
)
4610 return s_pfn_Get_Process_Memory_Info (h_proc
, mem_counters
, bufsize
);
4614 get_process_working_set_size (HANDLE h_proc
,
4618 static GetProcessWorkingSetSize_Proc
4619 s_pfn_Get_Process_Working_Set_Size
= NULL
;
4621 if (is_windows_9x () == TRUE
)
4625 if (g_b_init_get_process_working_set_size
== 0)
4627 g_b_init_get_process_working_set_size
= 1;
4628 s_pfn_Get_Process_Working_Set_Size
= (GetProcessWorkingSetSize_Proc
)
4629 GetProcAddress (GetModuleHandle ("kernel32.dll"),
4630 "GetProcessWorkingSetSize");
4632 if (s_pfn_Get_Process_Working_Set_Size
== NULL
)
4636 return s_pfn_Get_Process_Working_Set_Size (h_proc
, minrss
, maxrss
);
4640 global_memory_status (MEMORYSTATUS
*buf
)
4642 static GlobalMemoryStatus_Proc s_pfn_Global_Memory_Status
= NULL
;
4644 if (is_windows_9x () == TRUE
)
4648 if (g_b_init_global_memory_status
== 0)
4650 g_b_init_global_memory_status
= 1;
4651 s_pfn_Global_Memory_Status
= (GlobalMemoryStatus_Proc
)
4652 GetProcAddress (GetModuleHandle ("kernel32.dll"),
4653 "GlobalMemoryStatus");
4655 if (s_pfn_Global_Memory_Status
== NULL
)
4659 return s_pfn_Global_Memory_Status (buf
);
4663 global_memory_status_ex (MEMORY_STATUS_EX
*buf
)
4665 static GlobalMemoryStatusEx_Proc s_pfn_Global_Memory_Status_Ex
= NULL
;
4667 if (is_windows_9x () == TRUE
)
4671 if (g_b_init_global_memory_status_ex
== 0)
4673 g_b_init_global_memory_status_ex
= 1;
4674 s_pfn_Global_Memory_Status_Ex
= (GlobalMemoryStatusEx_Proc
)
4675 GetProcAddress (GetModuleHandle ("kernel32.dll"),
4676 "GlobalMemoryStatusEx");
4678 if (s_pfn_Global_Memory_Status_Ex
== NULL
)
4682 return s_pfn_Global_Memory_Status_Ex (buf
);
4686 list_system_processes (void)
4688 struct gcpro gcpro1
;
4689 Lisp_Object proclist
= Qnil
;
4692 h_snapshot
= create_toolhelp32_snapshot (TH32CS_SNAPPROCESS
, 0);
4694 if (h_snapshot
!= INVALID_HANDLE_VALUE
)
4696 PROCESSENTRY32 proc_entry
;
4702 proc_entry
.dwSize
= sizeof (PROCESSENTRY32
);
4703 for (res
= process32_first (h_snapshot
, &proc_entry
); res
;
4704 res
= process32_next (h_snapshot
, &proc_entry
))
4706 proc_id
= proc_entry
.th32ProcessID
;
4707 proclist
= Fcons (make_fixnum_or_float (proc_id
), proclist
);
4710 CloseHandle (h_snapshot
);
4712 proclist
= Fnreverse (proclist
);
4719 enable_privilege (LPCTSTR priv_name
, BOOL enable_p
, TOKEN_PRIVILEGES
*old_priv
)
4721 TOKEN_PRIVILEGES priv
;
4722 DWORD priv_size
= sizeof (priv
);
4723 DWORD opriv_size
= sizeof (*old_priv
);
4724 HANDLE h_token
= NULL
;
4725 HANDLE h_thread
= GetCurrentThread ();
4729 res
= open_thread_token (h_thread
,
4730 TOKEN_QUERY
| TOKEN_ADJUST_PRIVILEGES
,
4732 if (!res
&& GetLastError () == ERROR_NO_TOKEN
)
4734 if (impersonate_self (SecurityImpersonation
))
4735 res
= open_thread_token (h_thread
,
4736 TOKEN_QUERY
| TOKEN_ADJUST_PRIVILEGES
,
4741 priv
.PrivilegeCount
= 1;
4742 priv
.Privileges
[0].Attributes
= enable_p
? SE_PRIVILEGE_ENABLED
: 0;
4743 LookupPrivilegeValue (NULL
, priv_name
, &priv
.Privileges
[0].Luid
);
4744 if (AdjustTokenPrivileges (h_token
, FALSE
, &priv
, priv_size
,
4745 old_priv
, &opriv_size
)
4746 && GetLastError () != ERROR_NOT_ALL_ASSIGNED
)
4750 CloseHandle (h_token
);
4756 restore_privilege (TOKEN_PRIVILEGES
*priv
)
4758 DWORD priv_size
= sizeof (*priv
);
4759 HANDLE h_token
= NULL
;
4762 if (open_thread_token (GetCurrentThread (),
4763 TOKEN_QUERY
| TOKEN_ADJUST_PRIVILEGES
,
4766 if (AdjustTokenPrivileges (h_token
, FALSE
, priv
, priv_size
, NULL
, NULL
)
4767 && GetLastError () != ERROR_NOT_ALL_ASSIGNED
)
4771 CloseHandle (h_token
);
4777 ltime (ULONGLONG time_100ns
)
4779 ULONGLONG time_sec
= time_100ns
/ 10000000;
4780 int subsec
= time_100ns
% 10000000;
4781 return list4 (make_number (time_sec
>> 16),
4782 make_number (time_sec
& 0xffff),
4783 make_number (subsec
/ 10),
4784 make_number (subsec
% 10 * 100000));
4787 #define U64_TO_LISP_TIME(time) ltime (time)
4790 process_times (HANDLE h_proc
, Lisp_Object
*ctime
, Lisp_Object
*etime
,
4791 Lisp_Object
*stime
, Lisp_Object
*utime
, Lisp_Object
*ttime
,
4794 FILETIME ft_creation
, ft_exit
, ft_kernel
, ft_user
, ft_current
;
4795 ULONGLONG tem1
, tem2
, tem3
, tem
;
4798 || !get_process_times_fn
4799 || !(*get_process_times_fn
) (h_proc
, &ft_creation
, &ft_exit
,
4800 &ft_kernel
, &ft_user
))
4803 GetSystemTimeAsFileTime (&ft_current
);
4805 FILETIME_TO_U64 (tem1
, ft_kernel
);
4806 *stime
= U64_TO_LISP_TIME (tem1
);
4808 FILETIME_TO_U64 (tem2
, ft_user
);
4809 *utime
= U64_TO_LISP_TIME (tem2
);
4812 *ttime
= U64_TO_LISP_TIME (tem3
);
4814 FILETIME_TO_U64 (tem
, ft_creation
);
4815 /* Process no 4 (System) returns zero creation time. */
4818 *ctime
= U64_TO_LISP_TIME (tem
);
4822 FILETIME_TO_U64 (tem3
, ft_current
);
4823 tem
= (tem3
- utc_base
) - tem
;
4825 *etime
= U64_TO_LISP_TIME (tem
);
4829 *pcpu
= 100.0 * (tem1
+ tem2
) / tem
;
4840 system_process_attributes (Lisp_Object pid
)
4842 struct gcpro gcpro1
, gcpro2
, gcpro3
;
4843 Lisp_Object attrs
= Qnil
;
4844 Lisp_Object cmd_str
, decoded_cmd
, tem
;
4845 HANDLE h_snapshot
, h_proc
;
4848 char uname
[UNLEN
+1], gname
[GNLEN
+1], domain
[1025];
4849 DWORD ulength
= sizeof (uname
), dlength
= sizeof (domain
), needed
;
4850 DWORD glength
= sizeof (gname
);
4851 HANDLE token
= NULL
;
4852 SID_NAME_USE user_type
;
4853 unsigned char *buf
= NULL
;
4855 TOKEN_USER user_token
;
4856 TOKEN_PRIMARY_GROUP group_token
;
4859 PROCESS_MEMORY_COUNTERS mem
;
4860 PROCESS_MEMORY_COUNTERS_EX mem_ex
;
4861 DWORD minrss
, maxrss
;
4863 MEMORY_STATUS_EX memstex
;
4864 double totphys
= 0.0;
4865 Lisp_Object ctime
, stime
, utime
, etime
, ttime
;
4867 BOOL result
= FALSE
;
4869 CHECK_NUMBER_OR_FLOAT (pid
);
4870 proc_id
= FLOATP (pid
) ? XFLOAT_DATA (pid
) : XINT (pid
);
4872 h_snapshot
= create_toolhelp32_snapshot (TH32CS_SNAPPROCESS
, 0);
4874 GCPRO3 (attrs
, decoded_cmd
, tem
);
4876 if (h_snapshot
!= INVALID_HANDLE_VALUE
)
4881 pe
.dwSize
= sizeof (PROCESSENTRY32
);
4882 for (res
= process32_first (h_snapshot
, &pe
); res
;
4883 res
= process32_next (h_snapshot
, &pe
))
4885 if (proc_id
== pe
.th32ProcessID
)
4888 decoded_cmd
= build_string ("Idle");
4891 /* Decode the command name from locale-specific
4893 cmd_str
= make_unibyte_string (pe
.szExeFile
,
4894 strlen (pe
.szExeFile
));
4896 code_convert_string_norecord (cmd_str
,
4897 Vlocale_coding_system
, 0);
4899 attrs
= Fcons (Fcons (Qcomm
, decoded_cmd
), attrs
);
4900 attrs
= Fcons (Fcons (Qppid
,
4901 make_fixnum_or_float (pe
.th32ParentProcessID
)),
4903 attrs
= Fcons (Fcons (Qpri
, make_number (pe
.pcPriClassBase
)),
4905 attrs
= Fcons (Fcons (Qthcount
,
4906 make_fixnum_or_float (pe
.cntThreads
)),
4913 CloseHandle (h_snapshot
);
4922 h_proc
= OpenProcess (PROCESS_QUERY_INFORMATION
| PROCESS_VM_READ
,
4924 /* If we were denied a handle to the process, try again after
4925 enabling the SeDebugPrivilege in our process. */
4928 TOKEN_PRIVILEGES priv_current
;
4930 if (enable_privilege (SE_DEBUG_NAME
, TRUE
, &priv_current
))
4932 h_proc
= OpenProcess (PROCESS_QUERY_INFORMATION
| PROCESS_VM_READ
,
4934 restore_privilege (&priv_current
);
4940 result
= open_process_token (h_proc
, TOKEN_QUERY
, &token
);
4943 result
= get_token_information (token
, TokenUser
, NULL
, 0, &blen
);
4944 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
4946 buf
= xmalloc (blen
);
4947 result
= get_token_information (token
, TokenUser
,
4948 (LPVOID
)buf
, blen
, &needed
);
4951 memcpy (&user_token
, buf
, sizeof (user_token
));
4952 if (!w32_cached_id (user_token
.User
.Sid
, &euid
, uname
))
4954 euid
= get_rid (user_token
.User
.Sid
);
4955 result
= lookup_account_sid (NULL
, user_token
.User
.Sid
,
4960 w32_add_to_cache (user_token
.User
.Sid
, euid
, uname
);
4963 strcpy (uname
, "unknown");
4967 ulength
= strlen (uname
);
4973 /* Determine a reasonable euid and gid values. */
4974 if (xstrcasecmp ("administrator", uname
) == 0)
4976 euid
= 500; /* well-known Administrator uid */
4977 egid
= 513; /* well-known None gid */
4981 /* Get group id and name. */
4982 result
= get_token_information (token
, TokenPrimaryGroup
,
4983 (LPVOID
)buf
, blen
, &needed
);
4984 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
4986 buf
= xrealloc (buf
, blen
= needed
);
4987 result
= get_token_information (token
, TokenPrimaryGroup
,
4988 (LPVOID
)buf
, blen
, &needed
);
4992 memcpy (&group_token
, buf
, sizeof (group_token
));
4993 if (!w32_cached_id (group_token
.PrimaryGroup
, &egid
, gname
))
4995 egid
= get_rid (group_token
.PrimaryGroup
);
4996 dlength
= sizeof (domain
);
4998 lookup_account_sid (NULL
, group_token
.PrimaryGroup
,
4999 gname
, &glength
, NULL
, &dlength
,
5002 w32_add_to_cache (group_token
.PrimaryGroup
,
5006 strcpy (gname
, "None");
5010 glength
= strlen (gname
);
5018 if (!is_windows_9x ())
5020 /* We couldn't open the process token, presumably because of
5021 insufficient access rights. Assume this process is run
5023 strcpy (uname
, "SYSTEM");
5024 strcpy (gname
, "None");
5025 euid
= 18; /* SYSTEM */
5026 egid
= 513; /* None */
5027 glength
= strlen (gname
);
5028 ulength
= strlen (uname
);
5030 /* If we are running under Windows 9X, where security calls are
5031 not supported, we assume all processes are run by the current
5033 else if (GetUserName (uname
, &ulength
))
5035 if (xstrcasecmp ("administrator", uname
) == 0)
5040 strcpy (gname
, "None");
5041 glength
= strlen (gname
);
5042 ulength
= strlen (uname
);
5048 strcpy (uname
, "administrator");
5049 ulength
= strlen (uname
);
5050 strcpy (gname
, "None");
5051 glength
= strlen (gname
);
5054 CloseHandle (token
);
5057 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (euid
)), attrs
);
5058 tem
= make_unibyte_string (uname
, ulength
);
5059 attrs
= Fcons (Fcons (Quser
,
5060 code_convert_string_norecord (tem
, Vlocale_coding_system
, 0)),
5062 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (egid
)), attrs
);
5063 tem
= make_unibyte_string (gname
, glength
);
5064 attrs
= Fcons (Fcons (Qgroup
,
5065 code_convert_string_norecord (tem
, Vlocale_coding_system
, 0)),
5068 if (global_memory_status_ex (&memstex
))
5069 #if __GNUC__ || (defined (_MSC_VER) && _MSC_VER >= 1300)
5070 totphys
= memstex
.ullTotalPhys
/ 1024.0;
5072 /* Visual Studio 6 cannot convert an unsigned __int64 type to
5073 double, so we need to do this for it... */
5075 DWORD tot_hi
= memstex
.ullTotalPhys
>> 32;
5076 DWORD tot_md
= (memstex
.ullTotalPhys
& 0x00000000ffffffff) >> 10;
5077 DWORD tot_lo
= memstex
.ullTotalPhys
% 1024;
5079 totphys
= tot_hi
* 4194304.0 + tot_md
+ tot_lo
/ 1024.0;
5081 #endif /* __GNUC__ || _MSC_VER >= 1300 */
5082 else if (global_memory_status (&memst
))
5083 totphys
= memst
.dwTotalPhys
/ 1024.0;
5086 && get_process_memory_info (h_proc
, (PROCESS_MEMORY_COUNTERS
*)&mem_ex
,
5089 DWORD rss
= mem_ex
.WorkingSetSize
/ 1024;
5091 attrs
= Fcons (Fcons (Qmajflt
,
5092 make_fixnum_or_float (mem_ex
.PageFaultCount
)),
5094 attrs
= Fcons (Fcons (Qvsize
,
5095 make_fixnum_or_float (mem_ex
.PrivateUsage
/ 1024)),
5097 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (rss
)), attrs
);
5099 attrs
= Fcons (Fcons (Qpmem
, make_float (100. * rss
/ totphys
)), attrs
);
5102 && get_process_memory_info (h_proc
, &mem
, sizeof (mem
)))
5104 DWORD rss
= mem_ex
.WorkingSetSize
/ 1024;
5106 attrs
= Fcons (Fcons (Qmajflt
,
5107 make_fixnum_or_float (mem
.PageFaultCount
)),
5109 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (rss
)), attrs
);
5111 attrs
= Fcons (Fcons (Qpmem
, make_float (100. * rss
/ totphys
)), attrs
);
5114 && get_process_working_set_size (h_proc
, &minrss
, &maxrss
))
5116 DWORD rss
= maxrss
/ 1024;
5118 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (maxrss
/ 1024)), attrs
);
5120 attrs
= Fcons (Fcons (Qpmem
, make_float (100. * rss
/ totphys
)), attrs
);
5123 if (process_times (h_proc
, &ctime
, &etime
, &stime
, &utime
, &ttime
, &pcpu
))
5125 attrs
= Fcons (Fcons (Qutime
, utime
), attrs
);
5126 attrs
= Fcons (Fcons (Qstime
, stime
), attrs
);
5127 attrs
= Fcons (Fcons (Qtime
, ttime
), attrs
);
5128 attrs
= Fcons (Fcons (Qstart
, ctime
), attrs
);
5129 attrs
= Fcons (Fcons (Qetime
, etime
), attrs
);
5130 attrs
= Fcons (Fcons (Qpcpu
, make_float (pcpu
)), attrs
);
5133 /* FIXME: Retrieve command line by walking the PEB of the process. */
5136 CloseHandle (h_proc
);
5142 /* Wrappers for winsock functions to map between our file descriptors
5143 and winsock's handles; also set h_errno for convenience.
5145 To allow Emacs to run on systems which don't have winsock support
5146 installed, we dynamically link to winsock on startup if present, and
5147 otherwise provide the minimum necessary functionality
5148 (eg. gethostname). */
5150 /* function pointers for relevant socket functions */
5151 int (PASCAL
*pfn_WSAStartup
) (WORD wVersionRequired
, LPWSADATA lpWSAData
);
5152 void (PASCAL
*pfn_WSASetLastError
) (int iError
);
5153 int (PASCAL
*pfn_WSAGetLastError
) (void);
5154 int (PASCAL
*pfn_WSAEventSelect
) (SOCKET s
, HANDLE hEventObject
, long lNetworkEvents
);
5155 HANDLE (PASCAL
*pfn_WSACreateEvent
) (void);
5156 int (PASCAL
*pfn_WSACloseEvent
) (HANDLE hEvent
);
5157 int (PASCAL
*pfn_socket
) (int af
, int type
, int protocol
);
5158 int (PASCAL
*pfn_bind
) (SOCKET s
, const struct sockaddr
*addr
, int namelen
);
5159 int (PASCAL
*pfn_connect
) (SOCKET s
, const struct sockaddr
*addr
, int namelen
);
5160 int (PASCAL
*pfn_ioctlsocket
) (SOCKET s
, long cmd
, u_long
*argp
);
5161 int (PASCAL
*pfn_recv
) (SOCKET s
, char * buf
, int len
, int flags
);
5162 int (PASCAL
*pfn_send
) (SOCKET s
, const char * buf
, int len
, int flags
);
5163 int (PASCAL
*pfn_closesocket
) (SOCKET s
);
5164 int (PASCAL
*pfn_shutdown
) (SOCKET s
, int how
);
5165 int (PASCAL
*pfn_WSACleanup
) (void);
5167 u_short (PASCAL
*pfn_htons
) (u_short hostshort
);
5168 u_short (PASCAL
*pfn_ntohs
) (u_short netshort
);
5169 unsigned long (PASCAL
*pfn_inet_addr
) (const char * cp
);
5170 int (PASCAL
*pfn_gethostname
) (char * name
, int namelen
);
5171 struct hostent
* (PASCAL
*pfn_gethostbyname
) (const char * name
);
5172 struct servent
* (PASCAL
*pfn_getservbyname
) (const char * name
, const char * proto
);
5173 int (PASCAL
*pfn_getpeername
) (SOCKET s
, struct sockaddr
*addr
, int * namelen
);
5174 int (PASCAL
*pfn_setsockopt
) (SOCKET s
, int level
, int optname
,
5175 const char * optval
, int optlen
);
5176 int (PASCAL
*pfn_listen
) (SOCKET s
, int backlog
);
5177 int (PASCAL
*pfn_getsockname
) (SOCKET s
, struct sockaddr
* name
,
5179 SOCKET (PASCAL
*pfn_accept
) (SOCKET s
, struct sockaddr
* addr
, int * addrlen
);
5180 int (PASCAL
*pfn_recvfrom
) (SOCKET s
, char * buf
, int len
, int flags
,
5181 struct sockaddr
* from
, int * fromlen
);
5182 int (PASCAL
*pfn_sendto
) (SOCKET s
, const char * buf
, int len
, int flags
,
5183 const struct sockaddr
* to
, int tolen
);
5185 /* SetHandleInformation is only needed to make sockets non-inheritable. */
5186 BOOL (WINAPI
*pfn_SetHandleInformation
) (HANDLE object
, DWORD mask
, DWORD flags
);
5187 #ifndef HANDLE_FLAG_INHERIT
5188 #define HANDLE_FLAG_INHERIT 1
5192 static int winsock_inuse
;
5197 if (winsock_lib
!= NULL
&& winsock_inuse
== 0)
5199 /* Not sure what would cause WSAENETDOWN, or even if it can happen
5200 after WSAStartup returns successfully, but it seems reasonable
5201 to allow unloading winsock anyway in that case. */
5202 if (pfn_WSACleanup () == 0 ||
5203 pfn_WSAGetLastError () == WSAENETDOWN
)
5205 if (FreeLibrary (winsock_lib
))
5214 init_winsock (int load_now
)
5216 WSADATA winsockData
;
5218 if (winsock_lib
!= NULL
)
5221 pfn_SetHandleInformation
5222 = (void *) GetProcAddress (GetModuleHandle ("kernel32.dll"),
5223 "SetHandleInformation");
5225 winsock_lib
= LoadLibrary ("Ws2_32.dll");
5227 if (winsock_lib
!= NULL
)
5229 /* dynamically link to socket functions */
5231 #define LOAD_PROC(fn) \
5232 if ((pfn_##fn = (void *) GetProcAddress (winsock_lib, #fn)) == NULL) \
5235 LOAD_PROC (WSAStartup
);
5236 LOAD_PROC (WSASetLastError
);
5237 LOAD_PROC (WSAGetLastError
);
5238 LOAD_PROC (WSAEventSelect
);
5239 LOAD_PROC (WSACreateEvent
);
5240 LOAD_PROC (WSACloseEvent
);
5243 LOAD_PROC (connect
);
5244 LOAD_PROC (ioctlsocket
);
5247 LOAD_PROC (closesocket
);
5248 LOAD_PROC (shutdown
);
5251 LOAD_PROC (inet_addr
);
5252 LOAD_PROC (gethostname
);
5253 LOAD_PROC (gethostbyname
);
5254 LOAD_PROC (getservbyname
);
5255 LOAD_PROC (getpeername
);
5256 LOAD_PROC (WSACleanup
);
5257 LOAD_PROC (setsockopt
);
5259 LOAD_PROC (getsockname
);
5261 LOAD_PROC (recvfrom
);
5265 /* specify version 1.1 of winsock */
5266 if (pfn_WSAStartup (0x101, &winsockData
) == 0)
5268 if (winsockData
.wVersion
!= 0x101)
5273 /* Report that winsock exists and is usable, but leave
5274 socket functions disabled. I am assuming that calling
5275 WSAStartup does not require any network interaction,
5276 and in particular does not cause or require a dial-up
5277 connection to be established. */
5280 FreeLibrary (winsock_lib
);
5288 FreeLibrary (winsock_lib
);
5298 /* function to set h_errno for compatibility; map winsock error codes to
5299 normal system codes where they overlap (non-overlapping definitions
5300 are already in <sys/socket.h> */
5304 if (winsock_lib
== NULL
)
5307 h_errno
= pfn_WSAGetLastError ();
5311 case WSAEACCES
: h_errno
= EACCES
; break;
5312 case WSAEBADF
: h_errno
= EBADF
; break;
5313 case WSAEFAULT
: h_errno
= EFAULT
; break;
5314 case WSAEINTR
: h_errno
= EINTR
; break;
5315 case WSAEINVAL
: h_errno
= EINVAL
; break;
5316 case WSAEMFILE
: h_errno
= EMFILE
; break;
5317 case WSAENAMETOOLONG
: h_errno
= ENAMETOOLONG
; break;
5318 case WSAENOTEMPTY
: h_errno
= ENOTEMPTY
; break;
5326 if (h_errno
== 0 && winsock_lib
!= NULL
)
5327 pfn_WSASetLastError (0);
5330 /* Extend strerror to handle the winsock-specific error codes. */
5334 } _wsa_errlist
[] = {
5335 {WSAEINTR
, "Interrupted function call"},
5336 {WSAEBADF
, "Bad file descriptor"},
5337 {WSAEACCES
, "Permission denied"},
5338 {WSAEFAULT
, "Bad address"},
5339 {WSAEINVAL
, "Invalid argument"},
5340 {WSAEMFILE
, "Too many open files"},
5342 {WSAEWOULDBLOCK
, "Resource temporarily unavailable"},
5343 {WSAEINPROGRESS
, "Operation now in progress"},
5344 {WSAEALREADY
, "Operation already in progress"},
5345 {WSAENOTSOCK
, "Socket operation on non-socket"},
5346 {WSAEDESTADDRREQ
, "Destination address required"},
5347 {WSAEMSGSIZE
, "Message too long"},
5348 {WSAEPROTOTYPE
, "Protocol wrong type for socket"},
5349 {WSAENOPROTOOPT
, "Bad protocol option"},
5350 {WSAEPROTONOSUPPORT
, "Protocol not supported"},
5351 {WSAESOCKTNOSUPPORT
, "Socket type not supported"},
5352 {WSAEOPNOTSUPP
, "Operation not supported"},
5353 {WSAEPFNOSUPPORT
, "Protocol family not supported"},
5354 {WSAEAFNOSUPPORT
, "Address family not supported by protocol family"},
5355 {WSAEADDRINUSE
, "Address already in use"},
5356 {WSAEADDRNOTAVAIL
, "Cannot assign requested address"},
5357 {WSAENETDOWN
, "Network is down"},
5358 {WSAENETUNREACH
, "Network is unreachable"},
5359 {WSAENETRESET
, "Network dropped connection on reset"},
5360 {WSAECONNABORTED
, "Software caused connection abort"},
5361 {WSAECONNRESET
, "Connection reset by peer"},
5362 {WSAENOBUFS
, "No buffer space available"},
5363 {WSAEISCONN
, "Socket is already connected"},
5364 {WSAENOTCONN
, "Socket is not connected"},
5365 {WSAESHUTDOWN
, "Cannot send after socket shutdown"},
5366 {WSAETOOMANYREFS
, "Too many references"}, /* not sure */
5367 {WSAETIMEDOUT
, "Connection timed out"},
5368 {WSAECONNREFUSED
, "Connection refused"},
5369 {WSAELOOP
, "Network loop"}, /* not sure */
5370 {WSAENAMETOOLONG
, "Name is too long"},
5371 {WSAEHOSTDOWN
, "Host is down"},
5372 {WSAEHOSTUNREACH
, "No route to host"},
5373 {WSAENOTEMPTY
, "Buffer not empty"}, /* not sure */
5374 {WSAEPROCLIM
, "Too many processes"},
5375 {WSAEUSERS
, "Too many users"}, /* not sure */
5376 {WSAEDQUOT
, "Double quote in host name"}, /* really not sure */
5377 {WSAESTALE
, "Data is stale"}, /* not sure */
5378 {WSAEREMOTE
, "Remote error"}, /* not sure */
5380 {WSASYSNOTREADY
, "Network subsystem is unavailable"},
5381 {WSAVERNOTSUPPORTED
, "WINSOCK.DLL version out of range"},
5382 {WSANOTINITIALISED
, "Winsock not initialized successfully"},
5383 {WSAEDISCON
, "Graceful shutdown in progress"},
5385 {WSAENOMORE
, "No more operations allowed"}, /* not sure */
5386 {WSAECANCELLED
, "Operation cancelled"}, /* not sure */
5387 {WSAEINVALIDPROCTABLE
, "Invalid procedure table from service provider"},
5388 {WSAEINVALIDPROVIDER
, "Invalid service provider version number"},
5389 {WSAEPROVIDERFAILEDINIT
, "Unable to initialize a service provider"},
5390 {WSASYSCALLFAILURE
, "System call failure"},
5391 {WSASERVICE_NOT_FOUND
, "Service not found"}, /* not sure */
5392 {WSATYPE_NOT_FOUND
, "Class type not found"},
5393 {WSA_E_NO_MORE
, "No more resources available"}, /* really not sure */
5394 {WSA_E_CANCELLED
, "Operation already cancelled"}, /* really not sure */
5395 {WSAEREFUSED
, "Operation refused"}, /* not sure */
5398 {WSAHOST_NOT_FOUND
, "Host not found"},
5399 {WSATRY_AGAIN
, "Authoritative host not found during name lookup"},
5400 {WSANO_RECOVERY
, "Non-recoverable error during name lookup"},
5401 {WSANO_DATA
, "Valid name, no data record of requested type"},
5407 sys_strerror (int error_no
)
5410 static char unknown_msg
[40];
5412 if (error_no
>= 0 && error_no
< sys_nerr
)
5413 return sys_errlist
[error_no
];
5415 for (i
= 0; _wsa_errlist
[i
].errnum
>= 0; i
++)
5416 if (_wsa_errlist
[i
].errnum
== error_no
)
5417 return _wsa_errlist
[i
].msg
;
5419 sprintf (unknown_msg
, "Unidentified error: %d", error_no
);
5423 /* [andrewi 3-May-96] I've had conflicting results using both methods,
5424 but I believe the method of keeping the socket handle separate (and
5425 insuring it is not inheritable) is the correct one. */
5427 #define SOCK_HANDLE(fd) ((SOCKET) fd_info[fd].hnd)
5429 static int socket_to_fd (SOCKET s
);
5432 sys_socket (int af
, int type
, int protocol
)
5436 if (winsock_lib
== NULL
)
5439 return INVALID_SOCKET
;
5444 /* call the real socket function */
5445 s
= pfn_socket (af
, type
, protocol
);
5447 if (s
!= INVALID_SOCKET
)
5448 return socket_to_fd (s
);
5454 /* Convert a SOCKET to a file descriptor. */
5456 socket_to_fd (SOCKET s
)
5461 /* Although under NT 3.5 _open_osfhandle will accept a socket
5462 handle, if opened with SO_OPENTYPE == SO_SYNCHRONOUS_NONALERT,
5463 that does not work under NT 3.1. However, we can get the same
5464 effect by using a backdoor function to replace an existing
5465 descriptor handle with the one we want. */
5467 /* allocate a file descriptor (with appropriate flags) */
5468 fd
= _open ("NUL:", _O_RDWR
);
5471 /* Make a non-inheritable copy of the socket handle. Note
5472 that it is possible that sockets aren't actually kernel
5473 handles, which appears to be the case on Windows 9x when
5474 the MS Proxy winsock client is installed. */
5476 /* Apparently there is a bug in NT 3.51 with some service
5477 packs, which prevents using DuplicateHandle to make a
5478 socket handle non-inheritable (causes WSACleanup to
5479 hang). The work-around is to use SetHandleInformation
5480 instead if it is available and implemented. */
5481 if (pfn_SetHandleInformation
)
5483 pfn_SetHandleInformation ((HANDLE
) s
, HANDLE_FLAG_INHERIT
, 0);
5487 HANDLE parent
= GetCurrentProcess ();
5488 HANDLE new_s
= INVALID_HANDLE_VALUE
;
5490 if (DuplicateHandle (parent
,
5496 DUPLICATE_SAME_ACCESS
))
5498 /* It is possible that DuplicateHandle succeeds even
5499 though the socket wasn't really a kernel handle,
5500 because a real handle has the same value. So
5501 test whether the new handle really is a socket. */
5502 long nonblocking
= 0;
5503 if (pfn_ioctlsocket ((SOCKET
) new_s
, FIONBIO
, &nonblocking
) == 0)
5505 pfn_closesocket (s
);
5510 CloseHandle (new_s
);
5515 fd_info
[fd
].hnd
= (HANDLE
) s
;
5517 /* set our own internal flags */
5518 fd_info
[fd
].flags
= FILE_SOCKET
| FILE_BINARY
| FILE_READ
| FILE_WRITE
;
5524 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
5526 /* attach child_process to fd_info */
5527 if (fd_info
[ fd
].cp
!= NULL
)
5529 DebPrint (("sys_socket: fd_info[%d] apparently in use!\n", fd
));
5533 fd_info
[ fd
].cp
= cp
;
5536 winsock_inuse
++; /* count open sockets */
5543 pfn_closesocket (s
);
5549 sys_bind (int s
, const struct sockaddr
* addr
, int namelen
)
5551 if (winsock_lib
== NULL
)
5554 return SOCKET_ERROR
;
5558 if (fd_info
[s
].flags
& FILE_SOCKET
)
5560 int rc
= pfn_bind (SOCK_HANDLE (s
), addr
, namelen
);
5561 if (rc
== SOCKET_ERROR
)
5566 return SOCKET_ERROR
;
5570 sys_connect (int s
, const struct sockaddr
* name
, int namelen
)
5572 if (winsock_lib
== NULL
)
5575 return SOCKET_ERROR
;
5579 if (fd_info
[s
].flags
& FILE_SOCKET
)
5581 int rc
= pfn_connect (SOCK_HANDLE (s
), name
, namelen
);
5582 if (rc
== SOCKET_ERROR
)
5587 return SOCKET_ERROR
;
5591 sys_htons (u_short hostshort
)
5593 return (winsock_lib
!= NULL
) ?
5594 pfn_htons (hostshort
) : hostshort
;
5598 sys_ntohs (u_short netshort
)
5600 return (winsock_lib
!= NULL
) ?
5601 pfn_ntohs (netshort
) : netshort
;
5605 sys_inet_addr (const char * cp
)
5607 return (winsock_lib
!= NULL
) ?
5608 pfn_inet_addr (cp
) : INADDR_NONE
;
5612 sys_gethostname (char * name
, int namelen
)
5614 if (winsock_lib
!= NULL
)
5615 return pfn_gethostname (name
, namelen
);
5617 if (namelen
> MAX_COMPUTERNAME_LENGTH
)
5618 return !GetComputerName (name
, (DWORD
*)&namelen
);
5621 return SOCKET_ERROR
;
5625 sys_gethostbyname (const char * name
)
5627 struct hostent
* host
;
5629 if (winsock_lib
== NULL
)
5636 host
= pfn_gethostbyname (name
);
5643 sys_getservbyname (const char * name
, const char * proto
)
5645 struct servent
* serv
;
5647 if (winsock_lib
== NULL
)
5654 serv
= pfn_getservbyname (name
, proto
);
5661 sys_getpeername (int s
, struct sockaddr
*addr
, int * namelen
)
5663 if (winsock_lib
== NULL
)
5666 return SOCKET_ERROR
;
5670 if (fd_info
[s
].flags
& FILE_SOCKET
)
5672 int rc
= pfn_getpeername (SOCK_HANDLE (s
), addr
, namelen
);
5673 if (rc
== SOCKET_ERROR
)
5678 return SOCKET_ERROR
;
5682 sys_shutdown (int s
, int how
)
5684 if (winsock_lib
== NULL
)
5687 return SOCKET_ERROR
;
5691 if (fd_info
[s
].flags
& FILE_SOCKET
)
5693 int rc
= pfn_shutdown (SOCK_HANDLE (s
), how
);
5694 if (rc
== SOCKET_ERROR
)
5699 return SOCKET_ERROR
;
5703 sys_setsockopt (int s
, int level
, int optname
, const void * optval
, int optlen
)
5705 if (winsock_lib
== NULL
)
5708 return SOCKET_ERROR
;
5712 if (fd_info
[s
].flags
& FILE_SOCKET
)
5714 int rc
= pfn_setsockopt (SOCK_HANDLE (s
), level
, optname
,
5715 (const char *)optval
, optlen
);
5716 if (rc
== SOCKET_ERROR
)
5721 return SOCKET_ERROR
;
5725 sys_listen (int s
, int backlog
)
5727 if (winsock_lib
== NULL
)
5730 return SOCKET_ERROR
;
5734 if (fd_info
[s
].flags
& FILE_SOCKET
)
5736 int rc
= pfn_listen (SOCK_HANDLE (s
), backlog
);
5737 if (rc
== SOCKET_ERROR
)
5740 fd_info
[s
].flags
|= FILE_LISTEN
;
5744 return SOCKET_ERROR
;
5748 sys_getsockname (int s
, struct sockaddr
* name
, int * namelen
)
5750 if (winsock_lib
== NULL
)
5753 return SOCKET_ERROR
;
5757 if (fd_info
[s
].flags
& FILE_SOCKET
)
5759 int rc
= pfn_getsockname (SOCK_HANDLE (s
), name
, namelen
);
5760 if (rc
== SOCKET_ERROR
)
5765 return SOCKET_ERROR
;
5769 sys_accept (int s
, struct sockaddr
* addr
, int * addrlen
)
5771 if (winsock_lib
== NULL
)
5778 if (fd_info
[s
].flags
& FILE_LISTEN
)
5780 SOCKET t
= pfn_accept (SOCK_HANDLE (s
), addr
, addrlen
);
5782 if (t
== INVALID_SOCKET
)
5785 fd
= socket_to_fd (t
);
5787 fd_info
[s
].cp
->status
= STATUS_READ_ACKNOWLEDGED
;
5788 ResetEvent (fd_info
[s
].cp
->char_avail
);
5796 sys_recvfrom (int s
, char * buf
, int len
, int flags
,
5797 struct sockaddr
* from
, int * fromlen
)
5799 if (winsock_lib
== NULL
)
5802 return SOCKET_ERROR
;
5806 if (fd_info
[s
].flags
& FILE_SOCKET
)
5808 int rc
= pfn_recvfrom (SOCK_HANDLE (s
), buf
, len
, flags
, from
, fromlen
);
5809 if (rc
== SOCKET_ERROR
)
5814 return SOCKET_ERROR
;
5818 sys_sendto (int s
, const char * buf
, int len
, int flags
,
5819 const struct sockaddr
* to
, int tolen
)
5821 if (winsock_lib
== NULL
)
5824 return SOCKET_ERROR
;
5828 if (fd_info
[s
].flags
& FILE_SOCKET
)
5830 int rc
= pfn_sendto (SOCK_HANDLE (s
), buf
, len
, flags
, to
, tolen
);
5831 if (rc
== SOCKET_ERROR
)
5836 return SOCKET_ERROR
;
5839 /* Windows does not have an fcntl function. Provide an implementation
5840 solely for making sockets non-blocking. */
5842 fcntl (int s
, int cmd
, int options
)
5844 if (winsock_lib
== NULL
)
5851 if (fd_info
[s
].flags
& FILE_SOCKET
)
5853 if (cmd
== F_SETFL
&& options
== O_NDELAY
)
5855 unsigned long nblock
= 1;
5856 int rc
= pfn_ioctlsocket (SOCK_HANDLE (s
), FIONBIO
, &nblock
);
5857 if (rc
== SOCKET_ERROR
)
5859 /* Keep track of the fact that we set this to non-blocking. */
5860 fd_info
[s
].flags
|= FILE_NDELAY
;
5866 return SOCKET_ERROR
;
5870 return SOCKET_ERROR
;
5874 /* Shadow main io functions: we need to handle pipes and sockets more
5875 intelligently, and implement non-blocking mode as well. */
5888 if (fd
< MAXDESC
&& fd_info
[fd
].cp
)
5890 child_process
* cp
= fd_info
[fd
].cp
;
5892 fd_info
[fd
].cp
= NULL
;
5894 if (CHILD_ACTIVE (cp
))
5896 /* if last descriptor to active child_process then cleanup */
5898 for (i
= 0; i
< MAXDESC
; i
++)
5902 if (fd_info
[i
].cp
== cp
)
5907 if (fd_info
[fd
].flags
& FILE_SOCKET
)
5909 if (winsock_lib
== NULL
) emacs_abort ();
5911 pfn_shutdown (SOCK_HANDLE (fd
), 2);
5912 rc
= pfn_closesocket (SOCK_HANDLE (fd
));
5914 winsock_inuse
--; /* count open sockets */
5921 /* Note that sockets do not need special treatment here (at least on
5922 NT and Windows 95 using the standard tcp/ip stacks) - it appears that
5923 closesocket is equivalent to CloseHandle, which is to be expected
5924 because socket handles are fully fledged kernel handles. */
5927 if (rc
== 0 && fd
< MAXDESC
)
5928 fd_info
[fd
].flags
= 0;
5939 if (new_fd
>= 0 && new_fd
< MAXDESC
)
5941 /* duplicate our internal info as well */
5942 fd_info
[new_fd
] = fd_info
[fd
];
5948 sys_dup2 (int src
, int dst
)
5952 if (dst
< 0 || dst
>= MAXDESC
)
5958 /* make sure we close the destination first if it's a pipe or socket */
5959 if (src
!= dst
&& fd_info
[dst
].flags
!= 0)
5962 rc
= _dup2 (src
, dst
);
5965 /* duplicate our internal info as well */
5966 fd_info
[dst
] = fd_info
[src
];
5971 /* Unix pipe() has only one arg */
5973 sys_pipe (int * phandles
)
5978 /* make pipe handles non-inheritable; when we spawn a child, we
5979 replace the relevant handle with an inheritable one. Also put
5980 pipes into binary mode; we will do text mode translation ourselves
5982 rc
= _pipe (phandles
, 0, _O_NOINHERIT
| _O_BINARY
);
5986 /* Protect against overflow, since Windows can open more handles than
5987 our fd_info array has room for. */
5988 if (phandles
[0] >= MAXDESC
|| phandles
[1] >= MAXDESC
)
5990 _close (phandles
[0]);
5991 _close (phandles
[1]);
5996 flags
= FILE_PIPE
| FILE_READ
| FILE_BINARY
;
5997 fd_info
[phandles
[0]].flags
= flags
;
5999 flags
= FILE_PIPE
| FILE_WRITE
| FILE_BINARY
;
6000 fd_info
[phandles
[1]].flags
= flags
;
6007 /* Function to do blocking read of one byte, needed to implement
6008 select. It is only allowed on sockets and pipes. */
6010 _sys_read_ahead (int fd
)
6015 if (fd
< 0 || fd
>= MAXDESC
)
6016 return STATUS_READ_ERROR
;
6018 cp
= fd_info
[fd
].cp
;
6020 if (cp
== NULL
|| cp
->fd
!= fd
|| cp
->status
!= STATUS_READ_READY
)
6021 return STATUS_READ_ERROR
;
6023 if ((fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SERIAL
| FILE_SOCKET
)) == 0
6024 || (fd_info
[fd
].flags
& FILE_READ
) == 0)
6026 DebPrint (("_sys_read_ahead: internal error: fd %d is not a pipe, serial port, or socket!\n", fd
));
6030 cp
->status
= STATUS_READ_IN_PROGRESS
;
6032 if (fd_info
[fd
].flags
& FILE_PIPE
)
6034 rc
= _read (fd
, &cp
->chr
, sizeof (char));
6036 /* Give subprocess time to buffer some more output for us before
6037 reporting that input is available; we need this because Windows 95
6038 connects DOS programs to pipes by making the pipe appear to be
6039 the normal console stdout - as a result most DOS programs will
6040 write to stdout without buffering, ie. one character at a
6041 time. Even some W32 programs do this - "dir" in a command
6042 shell on NT is very slow if we don't do this. */
6045 int wait
= w32_pipe_read_delay
;
6051 /* Yield remainder of our time slice, effectively giving a
6052 temporary priority boost to the child process. */
6056 else if (fd_info
[fd
].flags
& FILE_SERIAL
)
6058 HANDLE hnd
= fd_info
[fd
].hnd
;
6059 OVERLAPPED
*ovl
= &fd_info
[fd
].cp
->ovl_read
;
6062 /* Configure timeouts for blocking read. */
6063 if (!GetCommTimeouts (hnd
, &ct
))
6064 return STATUS_READ_ERROR
;
6065 ct
.ReadIntervalTimeout
= 0;
6066 ct
.ReadTotalTimeoutMultiplier
= 0;
6067 ct
.ReadTotalTimeoutConstant
= 0;
6068 if (!SetCommTimeouts (hnd
, &ct
))
6069 return STATUS_READ_ERROR
;
6071 if (!ReadFile (hnd
, &cp
->chr
, sizeof (char), (DWORD
*) &rc
, ovl
))
6073 if (GetLastError () != ERROR_IO_PENDING
)
6074 return STATUS_READ_ERROR
;
6075 if (!GetOverlappedResult (hnd
, ovl
, (DWORD
*) &rc
, TRUE
))
6076 return STATUS_READ_ERROR
;
6079 else if (fd_info
[fd
].flags
& FILE_SOCKET
)
6081 unsigned long nblock
= 0;
6082 /* We always want this to block, so temporarily disable NDELAY. */
6083 if (fd_info
[fd
].flags
& FILE_NDELAY
)
6084 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
6086 rc
= pfn_recv (SOCK_HANDLE (fd
), &cp
->chr
, sizeof (char), 0);
6088 if (fd_info
[fd
].flags
& FILE_NDELAY
)
6091 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
6095 if (rc
== sizeof (char))
6096 cp
->status
= STATUS_READ_SUCCEEDED
;
6098 cp
->status
= STATUS_READ_FAILED
;
6104 _sys_wait_accept (int fd
)
6110 if (fd
< 0 || fd
>= MAXDESC
)
6111 return STATUS_READ_ERROR
;
6113 cp
= fd_info
[fd
].cp
;
6115 if (cp
== NULL
|| cp
->fd
!= fd
|| cp
->status
!= STATUS_READ_READY
)
6116 return STATUS_READ_ERROR
;
6118 cp
->status
= STATUS_READ_FAILED
;
6120 hEv
= pfn_WSACreateEvent ();
6121 rc
= pfn_WSAEventSelect (SOCK_HANDLE (fd
), hEv
, FD_ACCEPT
);
6122 if (rc
!= SOCKET_ERROR
)
6124 rc
= WaitForSingleObject (hEv
, INFINITE
);
6125 pfn_WSAEventSelect (SOCK_HANDLE (fd
), NULL
, 0);
6126 if (rc
== WAIT_OBJECT_0
)
6127 cp
->status
= STATUS_READ_SUCCEEDED
;
6129 pfn_WSACloseEvent (hEv
);
6135 sys_read (int fd
, char * buffer
, unsigned int count
)
6140 char * orig_buffer
= buffer
;
6148 if (fd
< MAXDESC
&& fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
| FILE_SERIAL
))
6150 child_process
*cp
= fd_info
[fd
].cp
;
6152 if ((fd_info
[fd
].flags
& FILE_READ
) == 0)
6160 /* re-read CR carried over from last read */
6161 if (fd_info
[fd
].flags
& FILE_LAST_CR
)
6163 if (fd_info
[fd
].flags
& FILE_BINARY
) emacs_abort ();
6167 fd_info
[fd
].flags
&= ~FILE_LAST_CR
;
6170 /* presence of a child_process structure means we are operating in
6171 non-blocking mode - otherwise we just call _read directly.
6172 Note that the child_process structure might be missing because
6173 reap_subprocess has been called; in this case the pipe is
6174 already broken, so calling _read on it is okay. */
6177 int current_status
= cp
->status
;
6179 switch (current_status
)
6181 case STATUS_READ_FAILED
:
6182 case STATUS_READ_ERROR
:
6183 /* report normal EOF if nothing in buffer */
6185 fd_info
[fd
].flags
|= FILE_AT_EOF
;
6188 case STATUS_READ_READY
:
6189 case STATUS_READ_IN_PROGRESS
:
6190 DebPrint (("sys_read called when read is in progress\n"));
6191 errno
= EWOULDBLOCK
;
6194 case STATUS_READ_SUCCEEDED
:
6195 /* consume read-ahead char */
6196 *buffer
++ = cp
->chr
;
6199 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
6200 ResetEvent (cp
->char_avail
);
6202 case STATUS_READ_ACKNOWLEDGED
:
6206 DebPrint (("sys_read: bad status %d\n", current_status
));
6211 if (fd_info
[fd
].flags
& FILE_PIPE
)
6213 PeekNamedPipe ((HANDLE
) _get_osfhandle (fd
), NULL
, 0, NULL
, &waiting
, NULL
);
6214 to_read
= min (waiting
, (DWORD
) count
);
6217 nchars
+= _read (fd
, buffer
, to_read
);
6219 else if (fd_info
[fd
].flags
& FILE_SERIAL
)
6221 HANDLE hnd
= fd_info
[fd
].hnd
;
6222 OVERLAPPED
*ovl
= &fd_info
[fd
].cp
->ovl_read
;
6228 /* Configure timeouts for non-blocking read. */
6229 if (!GetCommTimeouts (hnd
, &ct
))
6234 ct
.ReadIntervalTimeout
= MAXDWORD
;
6235 ct
.ReadTotalTimeoutMultiplier
= 0;
6236 ct
.ReadTotalTimeoutConstant
= 0;
6237 if (!SetCommTimeouts (hnd
, &ct
))
6243 if (!ResetEvent (ovl
->hEvent
))
6248 if (!ReadFile (hnd
, buffer
, count
, (DWORD
*) &rc
, ovl
))
6250 if (GetLastError () != ERROR_IO_PENDING
)
6255 if (!GetOverlappedResult (hnd
, ovl
, (DWORD
*) &rc
, TRUE
))
6264 else /* FILE_SOCKET */
6266 if (winsock_lib
== NULL
) emacs_abort ();
6268 /* do the equivalent of a non-blocking read */
6269 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONREAD
, &waiting
);
6270 if (waiting
== 0 && nchars
== 0)
6272 h_errno
= errno
= EWOULDBLOCK
;
6278 /* always use binary mode for sockets */
6279 int res
= pfn_recv (SOCK_HANDLE (fd
), buffer
, count
, 0);
6280 if (res
== SOCKET_ERROR
)
6282 DebPrint (("sys_read.recv failed with error %d on socket %ld\n",
6283 pfn_WSAGetLastError (), SOCK_HANDLE (fd
)));
6293 int nread
= _read (fd
, buffer
, count
);
6296 else if (nchars
== 0)
6301 fd_info
[fd
].flags
|= FILE_AT_EOF
;
6302 /* Perform text mode translation if required. */
6303 else if ((fd_info
[fd
].flags
& FILE_BINARY
) == 0)
6305 nchars
= crlf_to_lf (nchars
, orig_buffer
);
6306 /* If buffer contains only CR, return that. To be absolutely
6307 sure we should attempt to read the next char, but in
6308 practice a CR to be followed by LF would not appear by
6309 itself in the buffer. */
6310 if (nchars
> 1 && orig_buffer
[nchars
- 1] == 0x0d)
6312 fd_info
[fd
].flags
|= FILE_LAST_CR
;
6318 nchars
= _read (fd
, buffer
, count
);
6323 /* From w32xfns.c */
6324 extern HANDLE interrupt_handle
;
6326 /* For now, don't bother with a non-blocking mode */
6328 sys_write (int fd
, const void * buffer
, unsigned int count
)
6338 if (fd
< MAXDESC
&& fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
| FILE_SERIAL
))
6340 if ((fd_info
[fd
].flags
& FILE_WRITE
) == 0)
6346 /* Perform text mode translation if required. */
6347 if ((fd_info
[fd
].flags
& FILE_BINARY
) == 0)
6349 char * tmpbuf
= alloca (count
* 2);
6350 unsigned char * src
= (void *)buffer
;
6351 unsigned char * dst
= tmpbuf
;
6356 unsigned char *next
;
6357 /* copy next line or remaining bytes */
6358 next
= _memccpy (dst
, src
, '\n', nbytes
);
6361 /* copied one line ending with '\n' */
6362 int copied
= next
- dst
;
6365 /* insert '\r' before '\n' */
6372 /* copied remaining partial line -> now finished */
6379 if (fd
< MAXDESC
&& fd_info
[fd
].flags
& FILE_SERIAL
)
6381 HANDLE hnd
= (HANDLE
) _get_osfhandle (fd
);
6382 OVERLAPPED
*ovl
= &fd_info
[fd
].cp
->ovl_write
;
6383 HANDLE wait_hnd
[2] = { interrupt_handle
, ovl
->hEvent
};
6386 if (!WriteFile (hnd
, buffer
, count
, (DWORD
*) &nchars
, ovl
))
6388 if (GetLastError () != ERROR_IO_PENDING
)
6393 if (detect_input_pending ())
6394 active
= MsgWaitForMultipleObjects (2, wait_hnd
, FALSE
, INFINITE
,
6397 active
= WaitForMultipleObjects (2, wait_hnd
, FALSE
, INFINITE
);
6398 if (active
== WAIT_OBJECT_0
)
6399 { /* User pressed C-g, cancel write, then leave. Don't bother
6400 cleaning up as we may only get stuck in buggy drivers. */
6401 PurgeComm (hnd
, PURGE_TXABORT
| PURGE_TXCLEAR
);
6406 if (active
== WAIT_OBJECT_0
+ 1
6407 && !GetOverlappedResult (hnd
, ovl
, (DWORD
*) &nchars
, TRUE
))
6414 else if (fd
< MAXDESC
&& fd_info
[fd
].flags
& FILE_SOCKET
)
6416 unsigned long nblock
= 0;
6417 if (winsock_lib
== NULL
) emacs_abort ();
6419 /* TODO: implement select() properly so non-blocking I/O works. */
6420 /* For now, make sure the write blocks. */
6421 if (fd_info
[fd
].flags
& FILE_NDELAY
)
6422 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
6424 nchars
= pfn_send (SOCK_HANDLE (fd
), buffer
, count
, 0);
6426 /* Set the socket back to non-blocking if it was before,
6427 for other operations that support it. */
6428 if (fd_info
[fd
].flags
& FILE_NDELAY
)
6431 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
6434 if (nchars
== SOCKET_ERROR
)
6436 DebPrint (("sys_write.send failed with error %d on socket %ld\n",
6437 pfn_WSAGetLastError (), SOCK_HANDLE (fd
)));
6443 /* Some networked filesystems don't like too large writes, so
6444 break them into smaller chunks. See the Comments section of
6445 the MSDN documentation of WriteFile for details behind the
6446 choice of the value of CHUNK below. See also the thread
6447 http://thread.gmane.org/gmane.comp.version-control.git/145294
6448 in the git mailing list. */
6449 const unsigned char *p
= buffer
;
6450 const unsigned chunk
= 30 * 1024 * 1024;
6455 unsigned this_chunk
= count
< chunk
? count
: chunk
;
6456 int n
= _write (fd
, p
, this_chunk
);
6464 else if (n
< this_chunk
)
6474 /* The Windows CRT functions are "optimized for speed", so they don't
6475 check for timezone and DST changes if they were last called less
6476 than 1 minute ago (see http://support.microsoft.com/kb/821231). So
6477 all Emacs features that repeatedly call time functions (e.g.,
6478 display-time) are in real danger of missing timezone and DST
6479 changes. Calling tzset before each localtime call fixes that. */
6481 sys_localtime (const time_t *t
)
6484 return localtime (t
);
6489 /* Try loading LIBRARY_ID from the file(s) specified in
6490 Vdynamic_library_alist. If the library is loaded successfully,
6491 return the handle of the DLL, and record the filename in the
6492 property :loaded-from of LIBRARY_ID. If the library could not be
6493 found, or when it was already loaded (because the handle is not
6494 recorded anywhere, and so is lost after use), return NULL.
6496 We could also save the handle in :loaded-from, but currently
6497 there's no use case for it. */
6499 w32_delayed_load (Lisp_Object library_id
)
6501 HMODULE library_dll
= NULL
;
6503 CHECK_SYMBOL (library_id
);
6505 if (CONSP (Vdynamic_library_alist
)
6506 && NILP (Fassq (library_id
, Vlibrary_cache
)))
6508 Lisp_Object found
= Qnil
;
6509 Lisp_Object dlls
= Fassq (library_id
, Vdynamic_library_alist
);
6512 for (dlls
= XCDR (dlls
); CONSP (dlls
); dlls
= XCDR (dlls
))
6514 CHECK_STRING_CAR (dlls
);
6515 if ((library_dll
= LoadLibrary (SDATA (XCAR (dlls
)))))
6517 char name
[MAX_PATH
];
6520 len
= GetModuleFileNameA (library_dll
, name
, sizeof (name
));
6521 found
= Fcons (XCAR (dlls
),
6523 /* Possibly truncated */
6524 ? make_specified_string (name
, -1, len
, 1)
6530 Fput (library_id
, QCloaded_from
, found
);
6538 check_windows_init_file (void)
6540 /* A common indication that Emacs is not installed properly is when
6541 it cannot find the Windows installation file. If this file does
6542 not exist in the expected place, tell the user. */
6544 if (!noninteractive
&& !inhibit_window_system
6545 /* Vload_path is not yet initialized when we are loading
6547 && NILP (Vpurify_flag
))
6549 Lisp_Object init_file
;
6552 init_file
= build_string ("term/w32-win");
6553 fd
= openp (Vload_path
, init_file
, Fget_load_suffixes (), NULL
, Qnil
);
6556 Lisp_Object load_path_print
= Fprin1_to_string (Vload_path
, Qnil
);
6557 char *init_file_name
= SDATA (init_file
);
6558 char *load_path
= SDATA (load_path_print
);
6559 char *buffer
= alloca (1024
6560 + strlen (init_file_name
)
6561 + strlen (load_path
));
6564 "The Emacs Windows initialization file \"%s.el\" "
6565 "could not be found in your Emacs installation. "
6566 "Emacs checked the following directories for this file:\n"
6568 "When Emacs cannot find this file, it usually means that it "
6569 "was not installed properly, or its distribution file was "
6570 "not unpacked properly.\nSee the README.W32 file in the "
6571 "top-level Emacs directory for more information.",
6572 init_file_name
, load_path
);
6575 "Emacs Abort Dialog",
6576 MB_OK
| MB_ICONEXCLAMATION
| MB_TASKMODAL
);
6577 /* Use the low-level system abort. */
6588 term_ntproc (int ignored
)
6594 /* shutdown the socket interface if necessary */
6601 init_ntproc (int dumping
)
6603 sigset_t initial_mask
= 0;
6605 /* Initialize the socket interface now if available and requested by
6606 the user by defining PRELOAD_WINSOCK; otherwise loading will be
6607 delayed until open-network-stream is called (w32-has-winsock can
6608 also be used to dynamically load or reload winsock).
6610 Conveniently, init_environment is called before us, so
6611 PRELOAD_WINSOCK can be set in the registry. */
6613 /* Always initialize this correctly. */
6616 if (getenv ("PRELOAD_WINSOCK") != NULL
)
6617 init_winsock (TRUE
);
6619 /* Initial preparation for subprocess support: replace our standard
6620 handles with non-inheritable versions. */
6623 HANDLE stdin_save
= INVALID_HANDLE_VALUE
;
6624 HANDLE stdout_save
= INVALID_HANDLE_VALUE
;
6625 HANDLE stderr_save
= INVALID_HANDLE_VALUE
;
6627 parent
= GetCurrentProcess ();
6629 /* ignore errors when duplicating and closing; typically the
6630 handles will be invalid when running as a gui program. */
6631 DuplicateHandle (parent
,
6632 GetStdHandle (STD_INPUT_HANDLE
),
6637 DUPLICATE_SAME_ACCESS
);
6639 DuplicateHandle (parent
,
6640 GetStdHandle (STD_OUTPUT_HANDLE
),
6645 DUPLICATE_SAME_ACCESS
);
6647 DuplicateHandle (parent
,
6648 GetStdHandle (STD_ERROR_HANDLE
),
6653 DUPLICATE_SAME_ACCESS
);
6659 if (stdin_save
!= INVALID_HANDLE_VALUE
)
6660 _open_osfhandle ((intptr_t) stdin_save
, O_TEXT
);
6662 _open ("nul", O_TEXT
| O_NOINHERIT
| O_RDONLY
);
6665 if (stdout_save
!= INVALID_HANDLE_VALUE
)
6666 _open_osfhandle ((intptr_t) stdout_save
, O_TEXT
);
6668 _open ("nul", O_TEXT
| O_NOINHERIT
| O_WRONLY
);
6671 if (stderr_save
!= INVALID_HANDLE_VALUE
)
6672 _open_osfhandle ((intptr_t) stderr_save
, O_TEXT
);
6674 _open ("nul", O_TEXT
| O_NOINHERIT
| O_WRONLY
);
6678 /* unfortunately, atexit depends on implementation of malloc */
6679 /* atexit (term_ntproc); */
6682 /* Make sure we start with all signals unblocked. */
6683 sigprocmask (SIG_SETMASK
, &initial_mask
, NULL
);
6684 signal (SIGABRT
, term_ntproc
);
6688 /* determine which drives are fixed, for GetCachedVolumeInformation */
6690 /* GetDriveType must have trailing backslash. */
6691 char drive
[] = "A:\\";
6693 /* Loop over all possible drive letters */
6694 while (*drive
<= 'Z')
6696 /* Record if this drive letter refers to a fixed drive. */
6697 fixed_drives
[DRIVE_INDEX (*drive
)] =
6698 (GetDriveType (drive
) == DRIVE_FIXED
);
6703 /* Reset the volume info cache. */
6704 volume_cache
= NULL
;
6709 shutdown_handler ensures that buffers' autosave files are
6710 up to date when the user logs off, or the system shuts down.
6713 shutdown_handler (DWORD type
)
6715 /* Ctrl-C and Ctrl-Break are already suppressed, so don't handle them. */
6716 if (type
== CTRL_CLOSE_EVENT
/* User closes console window. */
6717 || type
== CTRL_LOGOFF_EVENT
/* User logs off. */
6718 || type
== CTRL_SHUTDOWN_EVENT
) /* User shutsdown. */
6720 /* Shut down cleanly, making sure autosave files are up to date. */
6721 shut_down_emacs (0, Qnil
);
6724 /* Allow other handlers to handle this signal. */
6729 globals_of_w32 is used to initialize those global variables that
6730 must always be initialized on startup even when the global variable
6731 initialized is non zero (see the function main in emacs.c).
6734 globals_of_w32 (void)
6736 HMODULE kernel32
= GetModuleHandle ("kernel32.dll");
6738 get_process_times_fn
= (GetProcessTimes_Proc
)
6739 GetProcAddress (kernel32
, "GetProcessTimes");
6741 DEFSYM (QCloaded_from
, ":loaded-from");
6743 g_b_init_is_windows_9x
= 0;
6744 g_b_init_open_process_token
= 0;
6745 g_b_init_get_token_information
= 0;
6746 g_b_init_lookup_account_sid
= 0;
6747 g_b_init_get_sid_sub_authority
= 0;
6748 g_b_init_get_sid_sub_authority_count
= 0;
6749 g_b_init_get_security_info
= 0;
6750 g_b_init_get_file_security
= 0;
6751 g_b_init_get_security_descriptor_owner
= 0;
6752 g_b_init_get_security_descriptor_group
= 0;
6753 g_b_init_is_valid_sid
= 0;
6754 g_b_init_create_toolhelp32_snapshot
= 0;
6755 g_b_init_process32_first
= 0;
6756 g_b_init_process32_next
= 0;
6757 g_b_init_open_thread_token
= 0;
6758 g_b_init_impersonate_self
= 0;
6759 g_b_init_revert_to_self
= 0;
6760 g_b_init_get_process_memory_info
= 0;
6761 g_b_init_get_process_working_set_size
= 0;
6762 g_b_init_global_memory_status
= 0;
6763 g_b_init_global_memory_status_ex
= 0;
6764 g_b_init_equal_sid
= 0;
6765 g_b_init_copy_sid
= 0;
6766 g_b_init_get_length_sid
= 0;
6767 g_b_init_get_native_system_info
= 0;
6768 g_b_init_get_system_times
= 0;
6769 g_b_init_create_symbolic_link
= 0;
6770 num_of_processors
= 0;
6771 /* The following sets a handler for shutdown notifications for
6772 console apps. This actually applies to Emacs in both console and
6773 GUI modes, since we had to fool windows into thinking emacs is a
6774 console application to get console mode to work. */
6775 SetConsoleCtrlHandler (shutdown_handler
, TRUE
);
6777 /* "None" is the default group name on standalone workstations. */
6778 strcpy (dflt_group_name
, "None");
6781 /* For make-serial-process */
6783 serial_open (char *port
)
6789 hnd
= CreateFile (port
, GENERIC_READ
| GENERIC_WRITE
, 0, 0,
6790 OPEN_EXISTING
, FILE_FLAG_OVERLAPPED
, 0);
6791 if (hnd
== INVALID_HANDLE_VALUE
)
6792 error ("Could not open %s", port
);
6793 fd
= (int) _open_osfhandle ((intptr_t) hnd
, 0);
6795 error ("Could not open %s", port
);
6799 error ("Could not create child process");
6801 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
6802 fd_info
[ fd
].hnd
= hnd
;
6803 fd_info
[ fd
].flags
|=
6804 FILE_READ
| FILE_WRITE
| FILE_BINARY
| FILE_SERIAL
;
6805 if (fd_info
[ fd
].cp
!= NULL
)
6807 error ("fd_info[fd = %d] is already in use", fd
);
6809 fd_info
[ fd
].cp
= cp
;
6810 cp
->ovl_read
.hEvent
= CreateEvent (NULL
, TRUE
, FALSE
, NULL
);
6811 if (cp
->ovl_read
.hEvent
== NULL
)
6812 error ("Could not create read event");
6813 cp
->ovl_write
.hEvent
= CreateEvent (NULL
, TRUE
, FALSE
, NULL
);
6814 if (cp
->ovl_write
.hEvent
== NULL
)
6815 error ("Could not create write event");
6820 /* For serial-process-configure */
6822 serial_configure (struct Lisp_Process
*p
, Lisp_Object contact
)
6824 Lisp_Object childp2
= Qnil
;
6825 Lisp_Object tem
= Qnil
;
6829 char summary
[4] = "???"; /* This usually becomes "8N1". */
6831 if ((fd_info
[ p
->outfd
].flags
& FILE_SERIAL
) == 0)
6832 error ("Not a serial process");
6833 hnd
= fd_info
[ p
->outfd
].hnd
;
6835 childp2
= Fcopy_sequence (p
->childp
);
6837 /* Initialize timeouts for blocking read and blocking write. */
6838 if (!GetCommTimeouts (hnd
, &ct
))
6839 error ("GetCommTimeouts() failed");
6840 ct
.ReadIntervalTimeout
= 0;
6841 ct
.ReadTotalTimeoutMultiplier
= 0;
6842 ct
.ReadTotalTimeoutConstant
= 0;
6843 ct
.WriteTotalTimeoutMultiplier
= 0;
6844 ct
.WriteTotalTimeoutConstant
= 0;
6845 if (!SetCommTimeouts (hnd
, &ct
))
6846 error ("SetCommTimeouts() failed");
6847 /* Read port attributes and prepare default configuration. */
6848 memset (&dcb
, 0, sizeof (dcb
));
6849 dcb
.DCBlength
= sizeof (DCB
);
6850 if (!GetCommState (hnd
, &dcb
))
6851 error ("GetCommState() failed");
6854 dcb
.fAbortOnError
= FALSE
;
6855 /* dcb.XonLim and dcb.XoffLim are set by GetCommState() */
6860 /* Configure speed. */
6861 if (!NILP (Fplist_member (contact
, QCspeed
)))
6862 tem
= Fplist_get (contact
, QCspeed
);
6864 tem
= Fplist_get (p
->childp
, QCspeed
);
6866 dcb
.BaudRate
= XINT (tem
);
6867 childp2
= Fplist_put (childp2
, QCspeed
, tem
);
6869 /* Configure bytesize. */
6870 if (!NILP (Fplist_member (contact
, QCbytesize
)))
6871 tem
= Fplist_get (contact
, QCbytesize
);
6873 tem
= Fplist_get (p
->childp
, QCbytesize
);
6875 tem
= make_number (8);
6877 if (XINT (tem
) != 7 && XINT (tem
) != 8)
6878 error (":bytesize must be nil (8), 7, or 8");
6879 dcb
.ByteSize
= XINT (tem
);
6880 summary
[0] = XINT (tem
) + '0';
6881 childp2
= Fplist_put (childp2
, QCbytesize
, tem
);
6883 /* Configure parity. */
6884 if (!NILP (Fplist_member (contact
, QCparity
)))
6885 tem
= Fplist_get (contact
, QCparity
);
6887 tem
= Fplist_get (p
->childp
, QCparity
);
6888 if (!NILP (tem
) && !EQ (tem
, Qeven
) && !EQ (tem
, Qodd
))
6889 error (":parity must be nil (no parity), `even', or `odd'");
6890 dcb
.fParity
= FALSE
;
6891 dcb
.Parity
= NOPARITY
;
6892 dcb
.fErrorChar
= FALSE
;
6897 else if (EQ (tem
, Qeven
))
6901 dcb
.Parity
= EVENPARITY
;
6902 dcb
.fErrorChar
= TRUE
;
6904 else if (EQ (tem
, Qodd
))
6908 dcb
.Parity
= ODDPARITY
;
6909 dcb
.fErrorChar
= TRUE
;
6911 childp2
= Fplist_put (childp2
, QCparity
, tem
);
6913 /* Configure stopbits. */
6914 if (!NILP (Fplist_member (contact
, QCstopbits
)))
6915 tem
= Fplist_get (contact
, QCstopbits
);
6917 tem
= Fplist_get (p
->childp
, QCstopbits
);
6919 tem
= make_number (1);
6921 if (XINT (tem
) != 1 && XINT (tem
) != 2)
6922 error (":stopbits must be nil (1 stopbit), 1, or 2");
6923 summary
[2] = XINT (tem
) + '0';
6924 if (XINT (tem
) == 1)
6925 dcb
.StopBits
= ONESTOPBIT
;
6926 else if (XINT (tem
) == 2)
6927 dcb
.StopBits
= TWOSTOPBITS
;
6928 childp2
= Fplist_put (childp2
, QCstopbits
, tem
);
6930 /* Configure flowcontrol. */
6931 if (!NILP (Fplist_member (contact
, QCflowcontrol
)))
6932 tem
= Fplist_get (contact
, QCflowcontrol
);
6934 tem
= Fplist_get (p
->childp
, QCflowcontrol
);
6935 if (!NILP (tem
) && !EQ (tem
, Qhw
) && !EQ (tem
, Qsw
))
6936 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
6937 dcb
.fOutxCtsFlow
= FALSE
;
6938 dcb
.fOutxDsrFlow
= FALSE
;
6939 dcb
.fDtrControl
= DTR_CONTROL_DISABLE
;
6940 dcb
.fDsrSensitivity
= FALSE
;
6941 dcb
.fTXContinueOnXoff
= FALSE
;
6944 dcb
.fRtsControl
= RTS_CONTROL_DISABLE
;
6945 dcb
.XonChar
= 17; /* Control-Q */
6946 dcb
.XoffChar
= 19; /* Control-S */
6949 /* Already configured. */
6951 else if (EQ (tem
, Qhw
))
6953 dcb
.fRtsControl
= RTS_CONTROL_HANDSHAKE
;
6954 dcb
.fOutxCtsFlow
= TRUE
;
6956 else if (EQ (tem
, Qsw
))
6961 childp2
= Fplist_put (childp2
, QCflowcontrol
, tem
);
6963 /* Activate configuration. */
6964 if (!SetCommState (hnd
, &dcb
))
6965 error ("SetCommState() failed");
6967 childp2
= Fplist_put (childp2
, QCsummary
, build_string (summary
));
6968 pset_childp (p
, childp2
);
6974 emacs_gnutls_pull (gnutls_transport_ptr_t p
, void* buf
, size_t sz
)
6979 struct Lisp_Process
*process
= (struct Lisp_Process
*)p
;
6980 int fd
= process
->infd
;
6984 n
= sys_read (fd
, (char*)buf
, sz
);
6991 if (err
== EWOULDBLOCK
)
6993 /* Set a small timeout. */
6994 timeout
= make_emacs_time (1, 0);
6996 FD_SET ((int)fd
, &fdset
);
6998 /* Use select with the timeout to poll the selector. */
6999 sc
= select (fd
+ 1, &fdset
, (SELECT_TYPE
*)0, (SELECT_TYPE
*)0,
7003 continue; /* Try again. */
7005 /* Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN.
7006 Also accept select return 0 as an indicator to EAGAIN. */
7007 if (sc
== 0 || errno
== EWOULDBLOCK
)
7010 err
= errno
; /* Other errors are just passed on. */
7013 emacs_gnutls_transport_set_errno (process
->gnutls_state
, err
);
7020 emacs_gnutls_push (gnutls_transport_ptr_t p
, const void* buf
, size_t sz
)
7022 struct Lisp_Process
*process
= (struct Lisp_Process
*)p
;
7023 int fd
= process
->outfd
;
7024 ssize_t n
= sys_write (fd
, buf
, sz
);
7026 /* 0 or more bytes written means everything went fine. */
7030 /* Negative bytes written means we got an error in errno.
7031 Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
7032 emacs_gnutls_transport_set_errno (process
->gnutls_state
,
7033 errno
== EWOULDBLOCK
? EAGAIN
: errno
);
7037 #endif /* HAVE_GNUTLS */