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>
34 #include <mbstring.h> /* for _mbspbrk */
39 /* must include CRT headers *before* config.h */
74 #define _ANONYMOUS_UNION
75 #define _ANONYMOUS_STRUCT
78 /* Some versions of compiler define MEMORYSTATUSEX, some don't, so we
79 use a different name to avoid compilation problems. */
80 typedef struct _MEMORY_STATUS_EX
{
83 DWORDLONG ullTotalPhys
;
84 DWORDLONG ullAvailPhys
;
85 DWORDLONG ullTotalPageFile
;
86 DWORDLONG ullAvailPageFile
;
87 DWORDLONG ullTotalVirtual
;
88 DWORDLONG ullAvailVirtual
;
89 DWORDLONG ullAvailExtendedVirtual
;
90 } MEMORY_STATUS_EX
,*LPMEMORY_STATUS_EX
;
100 #if !defined (__MINGW32__) || __W32API_MAJOR_VERSION < 3 || (__W32API_MAJOR_VERSION == 3 && __W32API_MINOR_VERSION < 15)
101 /* This either is not in psapi.h or guarded by higher value of
102 _WIN32_WINNT than what we use. w32api supplied with MinGW 3.15
103 defines it in psapi.h */
104 typedef struct _PROCESS_MEMORY_COUNTERS_EX
{
106 DWORD PageFaultCount
;
107 DWORD PeakWorkingSetSize
;
108 DWORD WorkingSetSize
;
109 DWORD QuotaPeakPagedPoolUsage
;
110 DWORD QuotaPagedPoolUsage
;
111 DWORD QuotaPeakNonPagedPoolUsage
;
112 DWORD QuotaNonPagedPoolUsage
;
114 DWORD PeakPagefileUsage
;
116 } PROCESS_MEMORY_COUNTERS_EX
,*PPROCESS_MEMORY_COUNTERS_EX
;
119 /* TCP connection support. */
120 #include <sys/socket.h>
143 #include "dispextern.h" /* for xstrcasecmp */
144 #include "coding.h" /* for Vlocale_coding_system */
146 #include "careadlinkat.h"
147 #include "allocator.h"
149 /* For serial_configure and serial_open. */
152 typedef HRESULT (WINAPI
* ShGetFolderPath_fn
)
153 (IN HWND
, IN
int, IN HANDLE
, IN DWORD
, OUT
char *);
155 Lisp_Object QCloaded_from
;
157 void globals_of_w32 (void);
158 static DWORD
get_rid (PSID
);
161 /* Initialization states.
163 WARNING: If you add any more such variables for additional APIs,
164 you MUST add initialization for them to globals_of_w32
165 below. This is because these variables might get set
166 to non-NULL values during dumping, but the dumped Emacs
167 cannot reuse those values, because it could be run on a
168 different version of the OS, where API addresses are
170 static BOOL g_b_init_is_windows_9x
;
171 static BOOL g_b_init_open_process_token
;
172 static BOOL g_b_init_get_token_information
;
173 static BOOL g_b_init_lookup_account_sid
;
174 static BOOL g_b_init_get_sid_sub_authority
;
175 static BOOL g_b_init_get_sid_sub_authority_count
;
176 static BOOL g_b_init_get_file_security
;
177 static BOOL g_b_init_get_security_descriptor_owner
;
178 static BOOL g_b_init_get_security_descriptor_group
;
179 static BOOL g_b_init_is_valid_sid
;
180 static BOOL g_b_init_create_toolhelp32_snapshot
;
181 static BOOL g_b_init_process32_first
;
182 static BOOL g_b_init_process32_next
;
183 static BOOL g_b_init_open_thread_token
;
184 static BOOL g_b_init_impersonate_self
;
185 static BOOL g_b_init_revert_to_self
;
186 static BOOL g_b_init_get_process_memory_info
;
187 static BOOL g_b_init_get_process_working_set_size
;
188 static BOOL g_b_init_global_memory_status
;
189 static BOOL g_b_init_global_memory_status_ex
;
190 static BOOL g_b_init_get_length_sid
;
191 static BOOL g_b_init_equal_sid
;
192 static BOOL g_b_init_copy_sid
;
193 static BOOL g_b_init_get_native_system_info
;
194 static BOOL g_b_init_get_system_times
;
197 BEGIN: Wrapper functions around OpenProcessToken
198 and other functions in advapi32.dll that are only
199 supported in Windows NT / 2k / XP
201 /* ** Function pointer typedefs ** */
202 typedef BOOL (WINAPI
* OpenProcessToken_Proc
) (
203 HANDLE ProcessHandle
,
205 PHANDLE TokenHandle
);
206 typedef BOOL (WINAPI
* GetTokenInformation_Proc
) (
208 TOKEN_INFORMATION_CLASS TokenInformationClass
,
209 LPVOID TokenInformation
,
210 DWORD TokenInformationLength
,
211 PDWORD ReturnLength
);
212 typedef BOOL (WINAPI
* GetProcessTimes_Proc
) (
213 HANDLE process_handle
,
214 LPFILETIME creation_time
,
215 LPFILETIME exit_time
,
216 LPFILETIME kernel_time
,
217 LPFILETIME user_time
);
219 GetProcessTimes_Proc get_process_times_fn
= NULL
;
222 const char * const LookupAccountSid_Name
= "LookupAccountSidW";
223 const char * const GetFileSecurity_Name
= "GetFileSecurityW";
225 const char * const LookupAccountSid_Name
= "LookupAccountSidA";
226 const char * const GetFileSecurity_Name
= "GetFileSecurityA";
228 typedef BOOL (WINAPI
* LookupAccountSid_Proc
) (
229 LPCTSTR lpSystemName
,
234 LPDWORD cbDomainName
,
235 PSID_NAME_USE peUse
);
236 typedef PDWORD (WINAPI
* GetSidSubAuthority_Proc
) (
239 typedef PUCHAR (WINAPI
* GetSidSubAuthorityCount_Proc
) (
241 typedef BOOL (WINAPI
* GetFileSecurity_Proc
) (
243 SECURITY_INFORMATION RequestedInformation
,
244 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
246 LPDWORD lpnLengthNeeded
);
247 typedef BOOL (WINAPI
* GetSecurityDescriptorOwner_Proc
) (
248 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
250 LPBOOL lpbOwnerDefaulted
);
251 typedef BOOL (WINAPI
* GetSecurityDescriptorGroup_Proc
) (
252 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
254 LPBOOL lpbGroupDefaulted
);
255 typedef BOOL (WINAPI
* IsValidSid_Proc
) (
257 typedef HANDLE (WINAPI
* CreateToolhelp32Snapshot_Proc
) (
259 DWORD th32ProcessID
);
260 typedef BOOL (WINAPI
* Process32First_Proc
) (
262 LPPROCESSENTRY32 lppe
);
263 typedef BOOL (WINAPI
* Process32Next_Proc
) (
265 LPPROCESSENTRY32 lppe
);
266 typedef BOOL (WINAPI
* OpenThreadToken_Proc
) (
270 PHANDLE TokenHandle
);
271 typedef BOOL (WINAPI
* ImpersonateSelf_Proc
) (
272 SECURITY_IMPERSONATION_LEVEL ImpersonationLevel
);
273 typedef BOOL (WINAPI
* RevertToSelf_Proc
) (void);
274 typedef BOOL (WINAPI
* GetProcessMemoryInfo_Proc
) (
276 PPROCESS_MEMORY_COUNTERS ppsmemCounters
,
278 typedef BOOL (WINAPI
* GetProcessWorkingSetSize_Proc
) (
280 DWORD
* lpMinimumWorkingSetSize
,
281 DWORD
* lpMaximumWorkingSetSize
);
282 typedef BOOL (WINAPI
* GlobalMemoryStatus_Proc
) (
283 LPMEMORYSTATUS lpBuffer
);
284 typedef BOOL (WINAPI
* GlobalMemoryStatusEx_Proc
) (
285 LPMEMORY_STATUS_EX lpBuffer
);
286 typedef BOOL (WINAPI
* CopySid_Proc
) (
287 DWORD nDestinationSidLength
,
288 PSID pDestinationSid
,
290 typedef BOOL (WINAPI
* EqualSid_Proc
) (
293 typedef DWORD (WINAPI
* GetLengthSid_Proc
) (
295 typedef void (WINAPI
* GetNativeSystemInfo_Proc
) (
296 LPSYSTEM_INFO lpSystemInfo
);
297 typedef BOOL (WINAPI
* GetSystemTimes_Proc
) (
298 LPFILETIME lpIdleTime
,
299 LPFILETIME lpKernelTime
,
300 LPFILETIME lpUserTime
);
302 /* ** A utility function ** */
306 static BOOL s_b_ret
= 0;
307 OSVERSIONINFO os_ver
;
308 if (g_b_init_is_windows_9x
== 0)
310 g_b_init_is_windows_9x
= 1;
311 ZeroMemory (&os_ver
, sizeof (OSVERSIONINFO
));
312 os_ver
.dwOSVersionInfoSize
= sizeof (OSVERSIONINFO
);
313 if (GetVersionEx (&os_ver
))
315 s_b_ret
= (os_ver
.dwPlatformId
== VER_PLATFORM_WIN32_WINDOWS
);
321 static Lisp_Object
ltime (ULONGLONG
);
323 /* Get total user and system times for get-internal-run-time.
324 Returns a list of integers if the times are provided by the OS
325 (NT derivatives), otherwise it returns the result of current-time. */
327 w32_get_internal_run_time (void)
329 if (get_process_times_fn
)
331 FILETIME create
, exit
, kernel
, user
;
332 HANDLE proc
= GetCurrentProcess ();
333 if ((*get_process_times_fn
) (proc
, &create
, &exit
, &kernel
, &user
))
335 LARGE_INTEGER user_int
, kernel_int
, total
;
336 user_int
.LowPart
= user
.dwLowDateTime
;
337 user_int
.HighPart
= user
.dwHighDateTime
;
338 kernel_int
.LowPart
= kernel
.dwLowDateTime
;
339 kernel_int
.HighPart
= kernel
.dwHighDateTime
;
340 total
.QuadPart
= user_int
.QuadPart
+ kernel_int
.QuadPart
;
341 return ltime (total
.QuadPart
);
345 return Fcurrent_time ();
348 /* ** The wrapper functions ** */
351 open_process_token (HANDLE ProcessHandle
,
355 static OpenProcessToken_Proc s_pfn_Open_Process_Token
= NULL
;
356 HMODULE hm_advapi32
= NULL
;
357 if (is_windows_9x () == TRUE
)
361 if (g_b_init_open_process_token
== 0)
363 g_b_init_open_process_token
= 1;
364 hm_advapi32
= LoadLibrary ("Advapi32.dll");
365 s_pfn_Open_Process_Token
=
366 (OpenProcessToken_Proc
) GetProcAddress (hm_advapi32
, "OpenProcessToken");
368 if (s_pfn_Open_Process_Token
== NULL
)
373 s_pfn_Open_Process_Token (
381 get_token_information (HANDLE TokenHandle
,
382 TOKEN_INFORMATION_CLASS TokenInformationClass
,
383 LPVOID TokenInformation
,
384 DWORD TokenInformationLength
,
387 static GetTokenInformation_Proc s_pfn_Get_Token_Information
= NULL
;
388 HMODULE hm_advapi32
= NULL
;
389 if (is_windows_9x () == TRUE
)
393 if (g_b_init_get_token_information
== 0)
395 g_b_init_get_token_information
= 1;
396 hm_advapi32
= LoadLibrary ("Advapi32.dll");
397 s_pfn_Get_Token_Information
=
398 (GetTokenInformation_Proc
) GetProcAddress (hm_advapi32
, "GetTokenInformation");
400 if (s_pfn_Get_Token_Information
== NULL
)
405 s_pfn_Get_Token_Information (
407 TokenInformationClass
,
409 TokenInformationLength
,
415 lookup_account_sid (LPCTSTR lpSystemName
,
420 LPDWORD cbDomainName
,
423 static LookupAccountSid_Proc s_pfn_Lookup_Account_Sid
= NULL
;
424 HMODULE hm_advapi32
= NULL
;
425 if (is_windows_9x () == TRUE
)
429 if (g_b_init_lookup_account_sid
== 0)
431 g_b_init_lookup_account_sid
= 1;
432 hm_advapi32
= LoadLibrary ("Advapi32.dll");
433 s_pfn_Lookup_Account_Sid
=
434 (LookupAccountSid_Proc
) GetProcAddress (hm_advapi32
, LookupAccountSid_Name
);
436 if (s_pfn_Lookup_Account_Sid
== NULL
)
441 s_pfn_Lookup_Account_Sid (
453 get_sid_sub_authority (PSID pSid
, DWORD n
)
455 static GetSidSubAuthority_Proc s_pfn_Get_Sid_Sub_Authority
= NULL
;
456 static DWORD zero
= 0U;
457 HMODULE hm_advapi32
= NULL
;
458 if (is_windows_9x () == TRUE
)
462 if (g_b_init_get_sid_sub_authority
== 0)
464 g_b_init_get_sid_sub_authority
= 1;
465 hm_advapi32
= LoadLibrary ("Advapi32.dll");
466 s_pfn_Get_Sid_Sub_Authority
=
467 (GetSidSubAuthority_Proc
) GetProcAddress (
468 hm_advapi32
, "GetSidSubAuthority");
470 if (s_pfn_Get_Sid_Sub_Authority
== NULL
)
474 return (s_pfn_Get_Sid_Sub_Authority (pSid
, n
));
478 get_sid_sub_authority_count (PSID pSid
)
480 static GetSidSubAuthorityCount_Proc s_pfn_Get_Sid_Sub_Authority_Count
= NULL
;
481 static UCHAR zero
= 0U;
482 HMODULE hm_advapi32
= NULL
;
483 if (is_windows_9x () == TRUE
)
487 if (g_b_init_get_sid_sub_authority_count
== 0)
489 g_b_init_get_sid_sub_authority_count
= 1;
490 hm_advapi32
= LoadLibrary ("Advapi32.dll");
491 s_pfn_Get_Sid_Sub_Authority_Count
=
492 (GetSidSubAuthorityCount_Proc
) GetProcAddress (
493 hm_advapi32
, "GetSidSubAuthorityCount");
495 if (s_pfn_Get_Sid_Sub_Authority_Count
== NULL
)
499 return (s_pfn_Get_Sid_Sub_Authority_Count (pSid
));
503 get_file_security (LPCTSTR lpFileName
,
504 SECURITY_INFORMATION RequestedInformation
,
505 PSECURITY_DESCRIPTOR pSecurityDescriptor
,
507 LPDWORD lpnLengthNeeded
)
509 static GetFileSecurity_Proc s_pfn_Get_File_Security
= NULL
;
510 HMODULE hm_advapi32
= NULL
;
511 if (is_windows_9x () == TRUE
)
515 if (g_b_init_get_file_security
== 0)
517 g_b_init_get_file_security
= 1;
518 hm_advapi32
= LoadLibrary ("Advapi32.dll");
519 s_pfn_Get_File_Security
=
520 (GetFileSecurity_Proc
) GetProcAddress (
521 hm_advapi32
, GetFileSecurity_Name
);
523 if (s_pfn_Get_File_Security
== NULL
)
527 return (s_pfn_Get_File_Security (lpFileName
, RequestedInformation
,
528 pSecurityDescriptor
, nLength
,
533 get_security_descriptor_owner (PSECURITY_DESCRIPTOR pSecurityDescriptor
,
535 LPBOOL lpbOwnerDefaulted
)
537 static GetSecurityDescriptorOwner_Proc s_pfn_Get_Security_Descriptor_Owner
= NULL
;
538 HMODULE hm_advapi32
= NULL
;
539 if (is_windows_9x () == TRUE
)
543 if (g_b_init_get_security_descriptor_owner
== 0)
545 g_b_init_get_security_descriptor_owner
= 1;
546 hm_advapi32
= LoadLibrary ("Advapi32.dll");
547 s_pfn_Get_Security_Descriptor_Owner
=
548 (GetSecurityDescriptorOwner_Proc
) GetProcAddress (
549 hm_advapi32
, "GetSecurityDescriptorOwner");
551 if (s_pfn_Get_Security_Descriptor_Owner
== NULL
)
555 return (s_pfn_Get_Security_Descriptor_Owner (pSecurityDescriptor
, pOwner
,
560 get_security_descriptor_group (PSECURITY_DESCRIPTOR pSecurityDescriptor
,
562 LPBOOL lpbGroupDefaulted
)
564 static GetSecurityDescriptorGroup_Proc s_pfn_Get_Security_Descriptor_Group
= NULL
;
565 HMODULE hm_advapi32
= NULL
;
566 if (is_windows_9x () == TRUE
)
570 if (g_b_init_get_security_descriptor_group
== 0)
572 g_b_init_get_security_descriptor_group
= 1;
573 hm_advapi32
= LoadLibrary ("Advapi32.dll");
574 s_pfn_Get_Security_Descriptor_Group
=
575 (GetSecurityDescriptorGroup_Proc
) GetProcAddress (
576 hm_advapi32
, "GetSecurityDescriptorGroup");
578 if (s_pfn_Get_Security_Descriptor_Group
== NULL
)
582 return (s_pfn_Get_Security_Descriptor_Group (pSecurityDescriptor
, pGroup
,
587 is_valid_sid (PSID sid
)
589 static IsValidSid_Proc s_pfn_Is_Valid_Sid
= NULL
;
590 HMODULE hm_advapi32
= NULL
;
591 if (is_windows_9x () == TRUE
)
595 if (g_b_init_is_valid_sid
== 0)
597 g_b_init_is_valid_sid
= 1;
598 hm_advapi32
= LoadLibrary ("Advapi32.dll");
600 (IsValidSid_Proc
) GetProcAddress (
601 hm_advapi32
, "IsValidSid");
603 if (s_pfn_Is_Valid_Sid
== NULL
)
607 return (s_pfn_Is_Valid_Sid (sid
));
611 equal_sid (PSID sid1
, PSID sid2
)
613 static EqualSid_Proc s_pfn_Equal_Sid
= NULL
;
614 HMODULE hm_advapi32
= NULL
;
615 if (is_windows_9x () == TRUE
)
619 if (g_b_init_equal_sid
== 0)
621 g_b_init_equal_sid
= 1;
622 hm_advapi32
= LoadLibrary ("Advapi32.dll");
624 (EqualSid_Proc
) GetProcAddress (
625 hm_advapi32
, "EqualSid");
627 if (s_pfn_Equal_Sid
== NULL
)
631 return (s_pfn_Equal_Sid (sid1
, sid2
));
635 get_length_sid (PSID sid
)
637 static GetLengthSid_Proc s_pfn_Get_Length_Sid
= NULL
;
638 HMODULE hm_advapi32
= NULL
;
639 if (is_windows_9x () == TRUE
)
643 if (g_b_init_get_length_sid
== 0)
645 g_b_init_get_length_sid
= 1;
646 hm_advapi32
= LoadLibrary ("Advapi32.dll");
647 s_pfn_Get_Length_Sid
=
648 (GetLengthSid_Proc
) GetProcAddress (
649 hm_advapi32
, "GetLengthSid");
651 if (s_pfn_Get_Length_Sid
== NULL
)
655 return (s_pfn_Get_Length_Sid (sid
));
659 copy_sid (DWORD destlen
, PSID dest
, PSID src
)
661 static CopySid_Proc s_pfn_Copy_Sid
= NULL
;
662 HMODULE hm_advapi32
= NULL
;
663 if (is_windows_9x () == TRUE
)
667 if (g_b_init_copy_sid
== 0)
669 g_b_init_copy_sid
= 1;
670 hm_advapi32
= LoadLibrary ("Advapi32.dll");
672 (CopySid_Proc
) GetProcAddress (
673 hm_advapi32
, "CopySid");
675 if (s_pfn_Copy_Sid
== NULL
)
679 return (s_pfn_Copy_Sid (destlen
, dest
, src
));
683 END: Wrapper functions around OpenProcessToken
684 and other functions in advapi32.dll that are only
685 supported in Windows NT / 2k / XP
689 get_native_system_info (LPSYSTEM_INFO lpSystemInfo
)
691 static GetNativeSystemInfo_Proc s_pfn_Get_Native_System_Info
= NULL
;
692 if (is_windows_9x () != TRUE
)
694 if (g_b_init_get_native_system_info
== 0)
696 g_b_init_get_native_system_info
= 1;
697 s_pfn_Get_Native_System_Info
=
698 (GetNativeSystemInfo_Proc
)GetProcAddress (GetModuleHandle ("kernel32.dll"),
699 "GetNativeSystemInfo");
701 if (s_pfn_Get_Native_System_Info
!= NULL
)
702 s_pfn_Get_Native_System_Info (lpSystemInfo
);
705 lpSystemInfo
->dwNumberOfProcessors
= -1;
709 get_system_times (LPFILETIME lpIdleTime
,
710 LPFILETIME lpKernelTime
,
711 LPFILETIME lpUserTime
)
713 static GetSystemTimes_Proc s_pfn_Get_System_times
= NULL
;
714 if (is_windows_9x () == TRUE
)
718 if (g_b_init_get_system_times
== 0)
720 g_b_init_get_system_times
= 1;
721 s_pfn_Get_System_times
=
722 (GetSystemTimes_Proc
)GetProcAddress (GetModuleHandle ("kernel32.dll"),
725 if (s_pfn_Get_System_times
== NULL
)
727 return (s_pfn_Get_System_times (lpIdleTime
, lpKernelTime
, lpUserTime
));
730 /* Equivalent of strerror for W32 error codes. */
732 w32_strerror (int error_no
)
734 static char buf
[500];
737 error_no
= GetLastError ();
740 if (!FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM
, NULL
,
742 0, /* choose most suitable language */
743 buf
, sizeof (buf
), NULL
))
744 sprintf (buf
, "w32 error %u", error_no
);
748 /* Return 1 if P is a valid pointer to an object of size SIZE. Return
749 0 if P is NOT a valid pointer. Return -1 if we cannot validate P.
751 This is called from alloc.c:valid_pointer_p. */
753 w32_valid_pointer_p (void *p
, int size
)
756 HANDLE h
= OpenProcess (PROCESS_VM_READ
, FALSE
, GetCurrentProcessId ());
760 unsigned char *buf
= alloca (size
);
761 int retval
= ReadProcessMemory (h
, p
, buf
, size
, &done
);
770 static char startup_dir
[MAXPATHLEN
];
772 /* Get the current working directory. */
777 if (GetCurrentDirectory (MAXPATHLEN
, dir
) > 0)
781 /* Emacs doesn't actually change directory itself, it stays in the
782 same directory where it was started. */
783 strcpy (dir
, startup_dir
);
788 /* Emulate getloadavg. */
797 /* Number of processors on this machine. */
798 static unsigned num_of_processors
;
800 /* We maintain 1-sec samples for the last 16 minutes in a circular buffer. */
801 static struct load_sample samples
[16*60];
802 static int first_idx
= -1, last_idx
= -1;
803 static int max_idx
= sizeof (samples
) / sizeof (samples
[0]);
808 int next_idx
= from
+ 1;
810 if (next_idx
>= max_idx
)
819 int prev_idx
= from
- 1;
822 prev_idx
= max_idx
- 1;
828 sample_system_load (ULONGLONG
*idle
, ULONGLONG
*kernel
, ULONGLONG
*user
)
831 FILETIME ft_idle
, ft_user
, ft_kernel
;
833 /* Initialize the number of processors on this machine. */
834 if (num_of_processors
<= 0)
836 get_native_system_info (&sysinfo
);
837 num_of_processors
= sysinfo
.dwNumberOfProcessors
;
838 if (num_of_processors
<= 0)
840 GetSystemInfo (&sysinfo
);
841 num_of_processors
= sysinfo
.dwNumberOfProcessors
;
843 if (num_of_processors
<= 0)
844 num_of_processors
= 1;
847 /* TODO: Take into account threads that are ready to run, by
848 sampling the "\System\Processor Queue Length" performance
849 counter. The code below accounts only for threads that are
852 if (get_system_times (&ft_idle
, &ft_kernel
, &ft_user
))
854 ULARGE_INTEGER uidle
, ukernel
, uuser
;
856 memcpy (&uidle
, &ft_idle
, sizeof (ft_idle
));
857 memcpy (&ukernel
, &ft_kernel
, sizeof (ft_kernel
));
858 memcpy (&uuser
, &ft_user
, sizeof (ft_user
));
859 *idle
= uidle
.QuadPart
;
860 *kernel
= ukernel
.QuadPart
;
861 *user
= uuser
.QuadPart
;
871 /* Produce the load average for a given time interval, using the
872 samples in the samples[] array. WHICH can be 0, 1, or 2, meaning
873 1-minute, 5-minute, or 15-minute average, respectively. */
877 double retval
= -1.0;
880 double span
= (which
== 0 ? 1.0 : (which
== 1 ? 5.0 : 15.0)) * 60;
881 time_t now
= samples
[last_idx
].sample_time
;
883 if (first_idx
!= last_idx
)
885 for (idx
= buf_prev (last_idx
); ; idx
= buf_prev (idx
))
887 tdiff
= difftime (now
, samples
[idx
].sample_time
);
888 if (tdiff
>= span
- 2*DBL_EPSILON
*now
)
891 samples
[last_idx
].kernel
+ samples
[last_idx
].user
892 - (samples
[idx
].kernel
+ samples
[idx
].user
);
893 long double idl
= samples
[last_idx
].idle
- samples
[idx
].idle
;
895 retval
= (1.0 - idl
/ sys
) * num_of_processors
;
898 if (idx
== first_idx
)
907 getloadavg (double loadavg
[], int nelem
)
910 ULONGLONG idle
, kernel
, user
;
911 time_t now
= time (NULL
);
913 /* Store another sample. We ignore samples that are less than 1 sec
915 if (difftime (now
, samples
[last_idx
].sample_time
) >= 1.0 - 2*DBL_EPSILON
*now
)
917 sample_system_load (&idle
, &kernel
, &user
);
918 last_idx
= buf_next (last_idx
);
919 samples
[last_idx
].sample_time
= now
;
920 samples
[last_idx
].idle
= idle
;
921 samples
[last_idx
].kernel
= kernel
;
922 samples
[last_idx
].user
= user
;
923 /* If the buffer has more that 15 min worth of samples, discard
926 first_idx
= last_idx
;
927 while (first_idx
!= last_idx
928 && (difftime (now
, samples
[first_idx
].sample_time
)
929 >= 15.0*60 + 2*DBL_EPSILON
*now
))
930 first_idx
= buf_next (first_idx
);
933 for (elem
= 0; elem
< nelem
; elem
++)
935 double avg
= getavg (elem
);
945 /* Emulate getpwuid, getpwnam and others. */
947 #define PASSWD_FIELD_SIZE 256
949 static char dflt_passwd_name
[PASSWD_FIELD_SIZE
];
950 static char dflt_passwd_passwd
[PASSWD_FIELD_SIZE
];
951 static char dflt_passwd_gecos
[PASSWD_FIELD_SIZE
];
952 static char dflt_passwd_dir
[PASSWD_FIELD_SIZE
];
953 static char dflt_passwd_shell
[PASSWD_FIELD_SIZE
];
955 static struct passwd dflt_passwd
=
967 static char dflt_group_name
[GNLEN
+1];
969 static struct group dflt_group
=
971 /* When group information is not available, we return this as the
972 group for all files. */
980 return dflt_passwd
.pw_uid
;
986 /* I could imagine arguing for checking to see whether the user is
987 in the Administrators group and returning a UID of 0 for that
988 case, but I don't know how wise that would be in the long run. */
995 return dflt_passwd
.pw_gid
;
1005 getpwuid (unsigned uid
)
1007 if (uid
== dflt_passwd
.pw_uid
)
1008 return &dflt_passwd
;
1013 getgrgid (gid_t gid
)
1019 getpwnam (char *name
)
1023 pw
= getpwuid (getuid ());
1027 if (xstrcasecmp (name
, pw
->pw_name
))
1034 init_user_info (void)
1036 /* Find the user's real name by opening the process token and
1037 looking up the name associated with the user-sid in that token.
1039 Use the relative portion of the identifier authority value from
1040 the user-sid as the user id value (same for group id using the
1041 primary group sid from the process token). */
1043 char uname
[UNLEN
+1], gname
[GNLEN
+1], domain
[1025];
1044 DWORD ulength
= sizeof (uname
), dlength
= sizeof (domain
), needed
;
1045 DWORD glength
= sizeof (gname
);
1046 HANDLE token
= NULL
;
1047 SID_NAME_USE user_type
;
1048 unsigned char *buf
= NULL
;
1050 TOKEN_USER user_token
;
1051 TOKEN_PRIMARY_GROUP group_token
;
1054 result
= open_process_token (GetCurrentProcess (), TOKEN_QUERY
, &token
);
1057 result
= get_token_information (token
, TokenUser
, NULL
, 0, &blen
);
1058 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
1060 buf
= xmalloc (blen
);
1061 result
= get_token_information (token
, TokenUser
,
1062 (LPVOID
)buf
, blen
, &needed
);
1065 memcpy (&user_token
, buf
, sizeof (user_token
));
1066 result
= lookup_account_sid (NULL
, user_token
.User
.Sid
,
1068 domain
, &dlength
, &user_type
);
1076 strcpy (dflt_passwd
.pw_name
, uname
);
1077 /* Determine a reasonable uid value. */
1078 if (xstrcasecmp ("administrator", uname
) == 0)
1080 dflt_passwd
.pw_uid
= 500; /* well-known Administrator uid */
1081 dflt_passwd
.pw_gid
= 513; /* well-known None gid */
1085 /* Use the last sub-authority value of the RID, the relative
1086 portion of the SID, as user/group ID. */
1087 dflt_passwd
.pw_uid
= get_rid (user_token
.User
.Sid
);
1089 /* Get group id and name. */
1090 result
= get_token_information (token
, TokenPrimaryGroup
,
1091 (LPVOID
)buf
, blen
, &needed
);
1092 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
1094 buf
= xrealloc (buf
, blen
= needed
);
1095 result
= get_token_information (token
, TokenPrimaryGroup
,
1096 (LPVOID
)buf
, blen
, &needed
);
1100 memcpy (&group_token
, buf
, sizeof (group_token
));
1101 dflt_passwd
.pw_gid
= get_rid (group_token
.PrimaryGroup
);
1102 dlength
= sizeof (domain
);
1103 /* If we can get at the real Primary Group name, use that.
1104 Otherwise, the default group name was already set to
1105 "None" in globals_of_w32. */
1106 if (lookup_account_sid (NULL
, group_token
.PrimaryGroup
,
1107 gname
, &glength
, NULL
, &dlength
,
1109 strcpy (dflt_group_name
, gname
);
1112 dflt_passwd
.pw_gid
= dflt_passwd
.pw_uid
;
1115 /* If security calls are not supported (presumably because we
1116 are running under Windows 9X), fallback to this: */
1117 else if (GetUserName (uname
, &ulength
))
1119 strcpy (dflt_passwd
.pw_name
, uname
);
1120 if (xstrcasecmp ("administrator", uname
) == 0)
1121 dflt_passwd
.pw_uid
= 0;
1123 dflt_passwd
.pw_uid
= 123;
1124 dflt_passwd
.pw_gid
= dflt_passwd
.pw_uid
;
1128 strcpy (dflt_passwd
.pw_name
, "unknown");
1129 dflt_passwd
.pw_uid
= 123;
1130 dflt_passwd
.pw_gid
= 123;
1132 dflt_group
.gr_gid
= dflt_passwd
.pw_gid
;
1134 /* Ensure HOME and SHELL are defined. */
1135 if (getenv ("HOME") == NULL
)
1137 if (getenv ("SHELL") == NULL
)
1140 /* Set dir and shell from environment variables. */
1141 strcpy (dflt_passwd
.pw_dir
, getenv ("HOME"));
1142 strcpy (dflt_passwd
.pw_shell
, getenv ("SHELL"));
1146 CloseHandle (token
);
1152 /* rand () on NT gives us 15 random bits...hack together 30 bits. */
1153 return ((rand () << 15) | rand ());
1163 /* Normalize filename by converting all path separators to
1164 the specified separator. Also conditionally convert upper
1165 case path name components to lower case. */
1168 normalize_filename (register char *fp
, char path_sep
)
1173 /* Always lower-case drive letters a-z, even if the filesystem
1174 preserves case in filenames.
1175 This is so filenames can be compared by string comparison
1176 functions that are case-sensitive. Even case-preserving filesystems
1177 do not distinguish case in drive letters. */
1178 if (fp
[1] == ':' && *fp
>= 'A' && *fp
<= 'Z')
1184 if (NILP (Vw32_downcase_file_names
))
1188 if (*fp
== '/' || *fp
== '\\')
1195 sep
= path_sep
; /* convert to this path separator */
1196 elem
= fp
; /* start of current path element */
1199 if (*fp
>= 'a' && *fp
<= 'z')
1200 elem
= 0; /* don't convert this element */
1202 if (*fp
== 0 || *fp
== ':')
1204 sep
= *fp
; /* restore current separator (or 0) */
1205 *fp
= '/'; /* after conversion of this element */
1208 if (*fp
== '/' || *fp
== '\\')
1210 if (elem
&& elem
!= fp
)
1212 *fp
= 0; /* temporary end of string */
1213 _strlwr (elem
); /* while we convert to lower case */
1215 *fp
= sep
; /* convert (or restore) path separator */
1216 elem
= fp
+ 1; /* next element starts after separator */
1222 /* Destructively turn backslashes into slashes. */
1224 dostounix_filename (register char *p
)
1226 normalize_filename (p
, '/');
1229 /* Destructively turn slashes into backslashes. */
1231 unixtodos_filename (register char *p
)
1233 normalize_filename (p
, '\\');
1236 /* Remove all CR's that are followed by a LF.
1237 (From msdos.c...probably should figure out a way to share it,
1238 although this code isn't going to ever change.) */
1240 crlf_to_lf (register int n
, register unsigned char *buf
)
1242 unsigned char *np
= buf
;
1243 unsigned char *startp
= buf
;
1244 unsigned char *endp
= buf
+ n
;
1248 while (buf
< endp
- 1)
1252 if (*(++buf
) != 0x0a)
1263 /* Parse the root part of file name, if present. Return length and
1264 optionally store pointer to char after root. */
1266 parse_root (char * name
, char ** pPath
)
1268 char * start
= name
;
1273 /* find the root name of the volume if given */
1274 if (isalpha (name
[0]) && name
[1] == ':')
1276 /* skip past drive specifier */
1278 if (IS_DIRECTORY_SEP (name
[0]))
1281 else if (IS_DIRECTORY_SEP (name
[0]) && IS_DIRECTORY_SEP (name
[1]))
1287 if (IS_DIRECTORY_SEP (*name
) && --slashes
== 0)
1292 if (IS_DIRECTORY_SEP (name
[0]))
1299 return name
- start
;
1302 /* Get long base name for name; name is assumed to be absolute. */
1304 get_long_basename (char * name
, char * buf
, int size
)
1306 WIN32_FIND_DATA find_data
;
1310 /* must be valid filename, no wild cards or other invalid characters */
1311 if (_mbspbrk (name
, "*?|<>\""))
1314 dir_handle
= FindFirstFile (name
, &find_data
);
1315 if (dir_handle
!= INVALID_HANDLE_VALUE
)
1317 if ((len
= strlen (find_data
.cFileName
)) < size
)
1318 memcpy (buf
, find_data
.cFileName
, len
+ 1);
1321 FindClose (dir_handle
);
1326 /* Get long name for file, if possible (assumed to be absolute). */
1328 w32_get_long_filename (char * name
, char * buf
, int size
)
1333 char full
[ MAX_PATH
];
1336 len
= strlen (name
);
1337 if (len
>= MAX_PATH
)
1340 /* Use local copy for destructive modification. */
1341 memcpy (full
, name
, len
+1);
1342 unixtodos_filename (full
);
1344 /* Copy root part verbatim. */
1345 len
= parse_root (full
, &p
);
1346 memcpy (o
, full
, len
);
1351 while (p
!= NULL
&& *p
)
1354 p
= strchr (q
, '\\');
1356 len
= get_long_basename (full
, o
, size
);
1379 is_unc_volume (const char *filename
)
1381 const char *ptr
= filename
;
1383 if (!IS_DIRECTORY_SEP (ptr
[0]) || !IS_DIRECTORY_SEP (ptr
[1]) || !ptr
[2])
1386 if (_mbspbrk (ptr
+ 2, "*?|<>\"\\/"))
1392 /* Routines that are no-ops on NT but are defined to get Emacs to compile. */
1395 sigsetmask (int signal_mask
)
1413 sigunblock (int sig
)
1419 sigemptyset (sigset_t
*set
)
1425 sigaddset (sigset_t
*set
, int signo
)
1431 sigfillset (sigset_t
*set
)
1437 sigprocmask (int how
, const sigset_t
*set
, sigset_t
*oset
)
1443 pthread_sigmask (int how
, const sigset_t
*set
, sigset_t
*oset
)
1445 if (sigprocmask (how
, set
, oset
) == -1)
1451 setpgrp (int pid
, int gid
)
1462 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
1465 w32_get_resource (char *key
, LPDWORD lpdwtype
)
1468 HKEY hrootkey
= NULL
;
1471 /* Check both the current user and the local machine to see if
1472 we have any resources. */
1474 if (RegOpenKeyEx (HKEY_CURRENT_USER
, REG_ROOT
, 0, KEY_READ
, &hrootkey
) == ERROR_SUCCESS
)
1478 if (RegQueryValueEx (hrootkey
, key
, NULL
, NULL
, NULL
, &cbData
) == ERROR_SUCCESS
1479 && (lpvalue
= xmalloc (cbData
)) != NULL
1480 && RegQueryValueEx (hrootkey
, key
, NULL
, lpdwtype
, lpvalue
, &cbData
) == ERROR_SUCCESS
)
1482 RegCloseKey (hrootkey
);
1488 RegCloseKey (hrootkey
);
1491 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE
, REG_ROOT
, 0, KEY_READ
, &hrootkey
) == ERROR_SUCCESS
)
1495 if (RegQueryValueEx (hrootkey
, key
, NULL
, NULL
, NULL
, &cbData
) == ERROR_SUCCESS
1496 && (lpvalue
= xmalloc (cbData
)) != NULL
1497 && RegQueryValueEx (hrootkey
, key
, NULL
, lpdwtype
, lpvalue
, &cbData
) == ERROR_SUCCESS
)
1499 RegCloseKey (hrootkey
);
1505 RegCloseKey (hrootkey
);
1511 char *get_emacs_configuration (void);
1514 init_environment (char ** argv
)
1516 static const char * const tempdirs
[] = {
1517 "$TMPDIR", "$TEMP", "$TMP", "c:/"
1522 const int imax
= sizeof (tempdirs
) / sizeof (tempdirs
[0]);
1524 /* Make sure they have a usable $TMPDIR. Many Emacs functions use
1525 temporary files and assume "/tmp" if $TMPDIR is unset, which
1526 will break on DOS/Windows. Refuse to work if we cannot find
1527 a directory, not even "c:/", usable for that purpose. */
1528 for (i
= 0; i
< imax
; i
++)
1530 const char *tmp
= tempdirs
[i
];
1533 tmp
= getenv (tmp
+ 1);
1534 /* Note that `access' can lie to us if the directory resides on a
1535 read-only filesystem, like CD-ROM or a write-protected floppy.
1536 The only way to be really sure is to actually create a file and
1537 see if it succeeds. But I think that's too much to ask. */
1538 if (tmp
&& sys_access (tmp
, D_OK
) == 0)
1540 char * var
= alloca (strlen (tmp
) + 8);
1541 sprintf (var
, "TMPDIR=%s", tmp
);
1542 _putenv (strdup (var
));
1549 Fcons (build_string ("no usable temporary directories found!!"),
1551 "While setting TMPDIR: ");
1553 /* Check for environment variables and use registry settings if they
1554 don't exist. Fallback on default values where applicable. */
1559 char locale_name
[32];
1560 struct stat ignored
;
1561 char default_home
[MAX_PATH
];
1564 static const struct env_entry
1571 {"PRELOAD_WINSOCK", NULL
},
1572 {"emacs_dir", "C:/emacs"},
1573 {"EMACSLOADPATH", "%emacs_dir%/site-lisp;%emacs_dir%/../site-lisp;%emacs_dir%/lisp;%emacs_dir%/leim"},
1574 {"SHELL", "%emacs_dir%/bin/cmdproxy.exe"},
1575 {"EMACSDATA", "%emacs_dir%/etc"},
1576 {"EMACSPATH", "%emacs_dir%/bin"},
1577 /* We no longer set INFOPATH because Info-default-directory-list
1579 /* {"INFOPATH", "%emacs_dir%/info"}, */
1580 {"EMACSDOC", "%emacs_dir%/etc"},
1585 #define N_ENV_VARS sizeof (dflt_envvars)/sizeof (dflt_envvars[0])
1587 /* We need to copy dflt_envvars[] and work on the copy because we
1588 don't want the dumped Emacs to inherit the values of
1589 environment variables we saw during dumping (which could be on
1590 a different system). The defaults above must be left intact. */
1591 struct env_entry env_vars
[N_ENV_VARS
];
1593 for (i
= 0; i
< N_ENV_VARS
; i
++)
1594 env_vars
[i
] = dflt_envvars
[i
];
1596 /* For backwards compatibility, check if a .emacs file exists in C:/
1597 If not, then we can try to default to the appdata directory under the
1598 user's profile, which is more likely to be writable. */
1599 if (stat ("C:/.emacs", &ignored
) < 0)
1601 HRESULT profile_result
;
1602 /* Dynamically load ShGetFolderPath, as it won't exist on versions
1603 of Windows 95 and NT4 that have not been updated to include
1605 ShGetFolderPath_fn get_folder_path
;
1606 get_folder_path
= (ShGetFolderPath_fn
)
1607 GetProcAddress (GetModuleHandle ("shell32.dll"), "SHGetFolderPathA");
1609 if (get_folder_path
!= NULL
)
1611 profile_result
= get_folder_path (NULL
, CSIDL_APPDATA
, NULL
,
1614 /* If we can't get the appdata dir, revert to old behavior. */
1615 if (profile_result
== S_OK
)
1617 env_vars
[0].def_value
= default_home
;
1623 /* Get default locale info and use it for LANG. */
1624 if (GetLocaleInfo (LOCALE_USER_DEFAULT
,
1625 LOCALE_SABBREVLANGNAME
| LOCALE_USE_CP_ACP
,
1626 locale_name
, sizeof (locale_name
)))
1628 for (i
= 0; i
< N_ENV_VARS
; i
++)
1630 if (strcmp (env_vars
[i
].name
, "LANG") == 0)
1632 env_vars
[i
].def_value
= locale_name
;
1638 /* When Emacs is invoked with --no-site-lisp, we must remove the
1639 site-lisp directories from the default value of EMACSLOADPATH.
1640 This assumes that the site-lisp entries are at the front, and
1641 that additional entries do exist. */
1644 for (i
= 0; i
< N_ENV_VARS
; i
++)
1646 if (strcmp (env_vars
[i
].name
, "EMACSLOADPATH") == 0)
1649 while ((site
= strstr (env_vars
[i
].def_value
, "site-lisp")))
1650 env_vars
[i
].def_value
= strchr (site
, ';') + 1;
1656 #define SET_ENV_BUF_SIZE (4 * MAX_PATH) /* to cover EMACSLOADPATH */
1658 /* Treat emacs_dir specially: set it unconditionally based on our
1659 location, if it appears that we are running from the bin subdir
1660 of a standard installation. */
1663 char modname
[MAX_PATH
];
1665 if (!GetModuleFileName (NULL
, modname
, MAX_PATH
))
1667 if ((p
= strrchr (modname
, '\\')) == NULL
)
1671 if ((p
= strrchr (modname
, '\\')) && xstrcasecmp (p
, "\\bin") == 0)
1673 char buf
[SET_ENV_BUF_SIZE
];
1676 for (p
= modname
; *p
; p
++)
1677 if (*p
== '\\') *p
= '/';
1679 _snprintf (buf
, sizeof (buf
)-1, "emacs_dir=%s", modname
);
1680 _putenv (strdup (buf
));
1682 /* Handle running emacs from the build directory: src/oo-spd/i386/ */
1684 /* FIXME: should use substring of get_emacs_configuration ().
1685 But I don't think the Windows build supports alpha, mips etc
1686 anymore, so have taken the easy option for now. */
1687 else if (p
&& xstrcasecmp (p
, "\\i386") == 0)
1690 p
= strrchr (modname
, '\\');
1694 p
= strrchr (modname
, '\\');
1695 if (p
&& xstrcasecmp (p
, "\\src") == 0)
1697 char buf
[SET_ENV_BUF_SIZE
];
1700 for (p
= modname
; *p
; p
++)
1701 if (*p
== '\\') *p
= '/';
1703 _snprintf (buf
, sizeof (buf
)-1, "emacs_dir=%s", modname
);
1704 _putenv (strdup (buf
));
1710 for (i
= 0; i
< N_ENV_VARS
; i
++)
1712 if (!getenv (env_vars
[i
].name
))
1716 if ((lpval
= w32_get_resource (env_vars
[i
].name
, &dwType
)) == NULL
1717 /* Also ignore empty environment variables. */
1721 lpval
= env_vars
[i
].def_value
;
1722 dwType
= REG_EXPAND_SZ
;
1724 if (!strcmp (env_vars
[i
].name
, "HOME") && !appdata
)
1725 Vdelayed_warnings_list
1726 = Fcons (listn (CONSTYPE_HEAP
, 2,
1727 intern ("initialization"),
1728 build_string ("Setting HOME to C:\\ by default is deprecated")),
1729 Vdelayed_warnings_list
);
1734 char buf1
[SET_ENV_BUF_SIZE
], buf2
[SET_ENV_BUF_SIZE
];
1736 if (dwType
== REG_EXPAND_SZ
)
1737 ExpandEnvironmentStrings ((LPSTR
) lpval
, buf1
, sizeof (buf1
));
1738 else if (dwType
== REG_SZ
)
1739 strcpy (buf1
, lpval
);
1740 if (dwType
== REG_EXPAND_SZ
|| dwType
== REG_SZ
)
1742 _snprintf (buf2
, sizeof (buf2
)-1, "%s=%s", env_vars
[i
].name
,
1744 _putenv (strdup (buf2
));
1754 /* Rebuild system configuration to reflect invoking system. */
1755 Vsystem_configuration
= build_string (EMACS_CONFIGURATION
);
1757 /* Another special case: on NT, the PATH variable is actually named
1758 "Path" although cmd.exe (perhaps NT itself) arranges for
1759 environment variable lookup and setting to be case insensitive.
1760 However, Emacs assumes a fully case sensitive environment, so we
1761 need to change "Path" to "PATH" to match the expectations of
1762 various elisp packages. We do this by the sneaky method of
1763 modifying the string in the C runtime environ entry.
1765 The same applies to COMSPEC. */
1769 for (envp
= environ
; *envp
; envp
++)
1770 if (_strnicmp (*envp
, "PATH=", 5) == 0)
1771 memcpy (*envp
, "PATH=", 5);
1772 else if (_strnicmp (*envp
, "COMSPEC=", 8) == 0)
1773 memcpy (*envp
, "COMSPEC=", 8);
1776 /* Remember the initial working directory for getwd. */
1777 if (!GetCurrentDirectory (MAXPATHLEN
, startup_dir
))
1781 static char modname
[MAX_PATH
];
1783 if (!GetModuleFileName (NULL
, modname
, MAX_PATH
))
1788 /* Determine if there is a middle mouse button, to allow parse_button
1789 to decide whether right mouse events should be mouse-2 or
1791 w32_num_mouse_buttons
= GetSystemMetrics (SM_CMOUSEBUTTONS
);
1797 emacs_root_dir (void)
1799 static char root_dir
[FILENAME_MAX
];
1802 p
= getenv ("emacs_dir");
1805 strcpy (root_dir
, p
);
1806 root_dir
[parse_root (root_dir
, NULL
)] = '\0';
1807 dostounix_filename (root_dir
);
1811 /* We don't have scripts to automatically determine the system configuration
1812 for Emacs before it's compiled, and we don't want to have to make the
1813 user enter it, so we define EMACS_CONFIGURATION to invoke this runtime
1817 get_emacs_configuration (void)
1819 char *arch
, *oem
, *os
;
1821 static char configuration_buffer
[32];
1823 /* Determine the processor type. */
1824 switch (get_processor_type ())
1827 #ifdef PROCESSOR_INTEL_386
1828 case PROCESSOR_INTEL_386
:
1829 case PROCESSOR_INTEL_486
:
1830 case PROCESSOR_INTEL_PENTIUM
:
1835 #ifdef PROCESSOR_MIPS_R2000
1836 case PROCESSOR_MIPS_R2000
:
1837 case PROCESSOR_MIPS_R3000
:
1838 case PROCESSOR_MIPS_R4000
:
1843 #ifdef PROCESSOR_ALPHA_21064
1844 case PROCESSOR_ALPHA_21064
:
1854 /* Use the OEM field to reflect the compiler/library combination. */
1856 #define COMPILER_NAME "msvc"
1859 #define COMPILER_NAME "mingw"
1861 #define COMPILER_NAME "unknown"
1864 oem
= COMPILER_NAME
;
1866 switch (osinfo_cache
.dwPlatformId
) {
1867 case VER_PLATFORM_WIN32_NT
:
1869 build_num
= osinfo_cache
.dwBuildNumber
;
1871 case VER_PLATFORM_WIN32_WINDOWS
:
1872 if (osinfo_cache
.dwMinorVersion
== 0) {
1877 build_num
= LOWORD (osinfo_cache
.dwBuildNumber
);
1879 case VER_PLATFORM_WIN32s
:
1880 /* Not supported, should not happen. */
1882 build_num
= LOWORD (osinfo_cache
.dwBuildNumber
);
1890 if (osinfo_cache
.dwPlatformId
== VER_PLATFORM_WIN32_NT
) {
1891 sprintf (configuration_buffer
, "%s-%s-%s%d.%d.%d", arch
, oem
, os
,
1892 get_w32_major_version (), get_w32_minor_version (), build_num
);
1894 sprintf (configuration_buffer
, "%s-%s-%s.%d", arch
, oem
, os
, build_num
);
1897 return configuration_buffer
;
1901 get_emacs_configuration_options (void)
1903 static char *options_buffer
;
1904 char cv
[32]; /* Enough for COMPILER_VERSION. */
1906 cv
, /* To be filled later. */
1910 #ifdef ENABLE_CHECKING
1911 " --enable-checking",
1913 /* configure.bat already sets USER_CFLAGS and USER_LDFLAGS
1914 with a starting space to save work here. */
1916 " --cflags", USER_CFLAGS
,
1919 " --ldflags", USER_LDFLAGS
,
1926 /* Work out the effective configure options for this build. */
1928 #define COMPILER_VERSION "--with-msvc (%d.%02d)", _MSC_VER / 100, _MSC_VER % 100
1931 #define COMPILER_VERSION "--with-gcc (%d.%d)", __GNUC__, __GNUC_MINOR__
1933 #define COMPILER_VERSION ""
1937 if (_snprintf (cv
, sizeof (cv
) - 1, COMPILER_VERSION
) < 0)
1938 return "Error: not enough space for compiler version";
1939 cv
[sizeof (cv
) - 1] = '\0';
1941 for (i
= 0; options
[i
]; i
++)
1942 size
+= strlen (options
[i
]);
1944 options_buffer
= xmalloc (size
+ 1);
1945 options_buffer
[0] = '\0';
1947 for (i
= 0; options
[i
]; i
++)
1948 strcat (options_buffer
, options
[i
]);
1950 return options_buffer
;
1954 #include <sys/timeb.h>
1956 /* Emulate gettimeofday (Ulrich Leodolter, 1/11/95). */
1958 gettimeofday (struct timeval
*tv
, struct timezone
*tz
)
1963 tv
->tv_sec
= tb
.time
;
1964 tv
->tv_usec
= tb
.millitm
* 1000L;
1965 /* Implementation note: _ftime sometimes doesn't update the dstflag
1966 according to the new timezone when the system timezone is
1967 changed. We could fix that by using GetSystemTime and
1968 GetTimeZoneInformation, but that doesn't seem necessary, since
1969 Emacs always calls gettimeofday with the 2nd argument NULL (see
1970 current_emacs_time). */
1973 tz
->tz_minuteswest
= tb
.timezone
; /* minutes west of Greenwich */
1974 tz
->tz_dsttime
= tb
.dstflag
; /* type of dst correction */
1978 /* Emulate fdutimens. */
1980 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
1981 TIMESPEC[0] and TIMESPEC[1], respectively.
1982 FD must be either negative -- in which case it is ignored --
1983 or a file descriptor that is open on FILE.
1984 If FD is nonnegative, then FILE can be NULL, which means
1985 use just futimes instead of utimes.
1986 If TIMESPEC is null, FAIL.
1987 Return 0 on success, -1 (setting errno) on failure. */
1990 fdutimens (int fd
, char const *file
, struct timespec
const timespec
[2])
1999 if (fd
< 0 && !file
)
2004 ut
.actime
= timespec
[0].tv_sec
;
2005 ut
.modtime
= timespec
[1].tv_sec
;
2007 return _futime (fd
, &ut
);
2009 return _utime (file
, &ut
);
2013 /* ------------------------------------------------------------------------- */
2014 /* IO support and wrapper functions for the Windows API. */
2015 /* ------------------------------------------------------------------------- */
2017 /* Place a wrapper around the MSVC version of ctime. It returns NULL
2018 on network directories, so we handle that case here.
2019 (Ulrich Leodolter, 1/11/95). */
2021 sys_ctime (const time_t *t
)
2023 char *str
= (char *) ctime (t
);
2024 return (str
? str
: "Sun Jan 01 00:00:00 1970");
2027 /* Emulate sleep...we could have done this with a define, but that
2028 would necessitate including windows.h in the files that used it.
2029 This is much easier. */
2031 sys_sleep (int seconds
)
2033 Sleep (seconds
* 1000);
2036 /* Internal MSVC functions for low-level descriptor munging */
2037 extern int __cdecl
_set_osfhnd (int fd
, long h
);
2038 extern int __cdecl
_free_osfhnd (int fd
);
2040 /* parallel array of private info on file handles */
2041 filedesc fd_info
[ MAXDESC
];
2043 typedef struct volume_info_data
{
2044 struct volume_info_data
* next
;
2046 /* time when info was obtained */
2049 /* actual volume info */
2058 /* Global referenced by various functions. */
2059 static volume_info_data volume_info
;
2061 /* Vector to indicate which drives are local and fixed (for which cached
2062 data never expires). */
2063 static BOOL fixed_drives
[26];
2065 /* Consider cached volume information to be stale if older than 10s,
2066 at least for non-local drives. Info for fixed drives is never stale. */
2067 #define DRIVE_INDEX( c ) ( (c) <= 'Z' ? (c) - 'A' : (c) - 'a' )
2068 #define VOLINFO_STILL_VALID( root_dir, info ) \
2069 ( ( isalpha (root_dir[0]) && \
2070 fixed_drives[ DRIVE_INDEX (root_dir[0]) ] ) \
2071 || GetTickCount () - info->timestamp < 10000 )
2073 /* Cache support functions. */
2075 /* Simple linked list with linear search is sufficient. */
2076 static volume_info_data
*volume_cache
= NULL
;
2078 static volume_info_data
*
2079 lookup_volume_info (char * root_dir
)
2081 volume_info_data
* info
;
2083 for (info
= volume_cache
; info
; info
= info
->next
)
2084 if (xstrcasecmp (info
->root_dir
, root_dir
) == 0)
2090 add_volume_info (char * root_dir
, volume_info_data
* info
)
2092 info
->root_dir
= xstrdup (root_dir
);
2093 info
->next
= volume_cache
;
2094 volume_cache
= info
;
2098 /* Wrapper for GetVolumeInformation, which uses caching to avoid
2099 performance penalty (~2ms on 486 for local drives, 7.5ms for local
2100 cdrom drive, ~5-10ms or more for remote drives on LAN). */
2101 static volume_info_data
*
2102 GetCachedVolumeInformation (char * root_dir
)
2104 volume_info_data
* info
;
2105 char default_root
[ MAX_PATH
];
2107 /* NULL for root_dir means use root from current directory. */
2108 if (root_dir
== NULL
)
2110 if (GetCurrentDirectory (MAX_PATH
, default_root
) == 0)
2112 parse_root (default_root
, &root_dir
);
2114 root_dir
= default_root
;
2117 /* Local fixed drives can be cached permanently. Removable drives
2118 cannot be cached permanently, since the volume name and serial
2119 number (if nothing else) can change. Remote drives should be
2120 treated as if they are removable, since there is no sure way to
2121 tell whether they are or not. Also, the UNC association of drive
2122 letters mapped to remote volumes can be changed at any time (even
2123 by other processes) without notice.
2125 As a compromise, so we can benefit from caching info for remote
2126 volumes, we use a simple expiry mechanism to invalidate cache
2127 entries that are more than ten seconds old. */
2130 /* No point doing this, because WNetGetConnection is even slower than
2131 GetVolumeInformation, consistently taking ~50ms on a 486 (FWIW,
2132 GetDriveType is about the only call of this type which does not
2133 involve network access, and so is extremely quick). */
2135 /* Map drive letter to UNC if remote. */
2136 if (isalpha (root_dir
[0]) && !fixed
[DRIVE_INDEX (root_dir
[0])])
2138 char remote_name
[ 256 ];
2139 char drive
[3] = { root_dir
[0], ':' };
2141 if (WNetGetConnection (drive
, remote_name
, sizeof (remote_name
))
2143 /* do something */ ;
2147 info
= lookup_volume_info (root_dir
);
2149 if (info
== NULL
|| ! VOLINFO_STILL_VALID (root_dir
, info
))
2157 /* Info is not cached, or is stale. */
2158 if (!GetVolumeInformation (root_dir
,
2159 name
, sizeof (name
),
2163 type
, sizeof (type
)))
2166 /* Cache the volume information for future use, overwriting existing
2167 entry if present. */
2170 info
= xmalloc (sizeof (volume_info_data
));
2171 add_volume_info (root_dir
, info
);
2179 info
->name
= xstrdup (name
);
2180 info
->serialnum
= serialnum
;
2181 info
->maxcomp
= maxcomp
;
2182 info
->flags
= flags
;
2183 info
->type
= xstrdup (type
);
2184 info
->timestamp
= GetTickCount ();
2190 /* Get information on the volume where name is held; set path pointer to
2191 start of pathname in name (past UNC header\volume header if present). */
2193 get_volume_info (const char * name
, const char ** pPath
)
2195 char temp
[MAX_PATH
];
2196 char *rootname
= NULL
; /* default to current volume */
2197 volume_info_data
* info
;
2202 /* find the root name of the volume if given */
2203 if (isalpha (name
[0]) && name
[1] == ':')
2211 else if (IS_DIRECTORY_SEP (name
[0]) && IS_DIRECTORY_SEP (name
[1]))
2218 if (IS_DIRECTORY_SEP (*name
) && --slashes
== 0)
2231 info
= GetCachedVolumeInformation (rootname
);
2234 /* Set global referenced by other functions. */
2235 volume_info
= *info
;
2241 /* Determine if volume is FAT format (ie. only supports short 8.3
2242 names); also set path pointer to start of pathname in name. */
2244 is_fat_volume (const char * name
, const char ** pPath
)
2246 if (get_volume_info (name
, pPath
))
2247 return (volume_info
.maxcomp
== 12);
2251 /* Map filename to a valid 8.3 name if necessary. */
2253 map_w32_filename (const char * name
, const char ** pPath
)
2255 static char shortname
[MAX_PATH
];
2256 char * str
= shortname
;
2259 const char * save_name
= name
;
2261 if (strlen (name
) >= MAX_PATH
)
2263 /* Return a filename which will cause callers to fail. */
2264 strcpy (shortname
, "?");
2268 if (is_fat_volume (name
, (const char **)&path
)) /* truncate to 8.3 */
2270 register int left
= 8; /* maximum number of chars in part */
2271 register int extn
= 0; /* extension added? */
2272 register int dots
= 2; /* maximum number of dots allowed */
2275 *str
++ = *name
++; /* skip past UNC header */
2277 while ((c
= *name
++))
2284 extn
= 0; /* reset extension flags */
2285 dots
= 2; /* max 2 dots */
2286 left
= 8; /* max length 8 for main part */
2290 extn
= 0; /* reset extension flags */
2291 dots
= 2; /* max 2 dots */
2292 left
= 8; /* max length 8 for main part */
2297 /* Convert path components of the form .xxx to _xxx,
2298 but leave . and .. as they are. This allows .emacs
2299 to be read as _emacs, for example. */
2303 IS_DIRECTORY_SEP (*name
))
2318 extn
= 1; /* we've got an extension */
2319 left
= 3; /* 3 chars in extension */
2323 /* any embedded dots after the first are converted to _ */
2328 case '#': /* don't lose these, they're important */
2330 str
[-1] = c
; /* replace last character of part */
2335 *str
++ = tolower (c
); /* map to lower case (looks nicer) */
2337 dots
= 0; /* started a path component */
2346 strcpy (shortname
, name
);
2347 unixtodos_filename (shortname
);
2351 *pPath
= shortname
+ (path
- save_name
);
2357 is_exec (const char * name
)
2359 char * p
= strrchr (name
, '.');
2362 && (xstrcasecmp (p
, ".exe") == 0 ||
2363 xstrcasecmp (p
, ".com") == 0 ||
2364 xstrcasecmp (p
, ".bat") == 0 ||
2365 xstrcasecmp (p
, ".cmd") == 0));
2368 /* Emulate the Unix directory procedures opendir, closedir,
2369 and readdir. We can't use the procedures supplied in sysdep.c,
2370 so we provide them here. */
2372 struct direct dir_static
; /* simulated directory contents */
2373 static HANDLE dir_find_handle
= INVALID_HANDLE_VALUE
;
2374 static int dir_is_fat
;
2375 static char dir_pathname
[MAXPATHLEN
+1];
2376 static WIN32_FIND_DATA dir_find_data
;
2378 /* Support shares on a network resource as subdirectories of a read-only
2380 static HANDLE wnet_enum_handle
= INVALID_HANDLE_VALUE
;
2381 static HANDLE
open_unc_volume (const char *);
2382 static char *read_unc_volume (HANDLE
, char *, int);
2383 static void close_unc_volume (HANDLE
);
2386 opendir (char *filename
)
2390 /* Opening is done by FindFirstFile. However, a read is inherent to
2391 this operation, so we defer the open until read time. */
2393 if (dir_find_handle
!= INVALID_HANDLE_VALUE
)
2395 if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
2398 if (is_unc_volume (filename
))
2400 wnet_enum_handle
= open_unc_volume (filename
);
2401 if (wnet_enum_handle
== INVALID_HANDLE_VALUE
)
2405 if (!(dirp
= (DIR *) malloc (sizeof (DIR))))
2412 strncpy (dir_pathname
, map_w32_filename (filename
, NULL
), MAXPATHLEN
);
2413 dir_pathname
[MAXPATHLEN
] = '\0';
2414 dir_is_fat
= is_fat_volume (filename
, NULL
);
2420 closedir (DIR *dirp
)
2422 /* If we have a find-handle open, close it. */
2423 if (dir_find_handle
!= INVALID_HANDLE_VALUE
)
2425 FindClose (dir_find_handle
);
2426 dir_find_handle
= INVALID_HANDLE_VALUE
;
2428 else if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
2430 close_unc_volume (wnet_enum_handle
);
2431 wnet_enum_handle
= INVALID_HANDLE_VALUE
;
2433 xfree ((char *) dirp
);
2439 int downcase
= !NILP (Vw32_downcase_file_names
);
2441 if (wnet_enum_handle
!= INVALID_HANDLE_VALUE
)
2443 if (!read_unc_volume (wnet_enum_handle
,
2444 dir_find_data
.cFileName
,
2448 /* If we aren't dir_finding, do a find-first, otherwise do a find-next. */
2449 else if (dir_find_handle
== INVALID_HANDLE_VALUE
)
2451 char filename
[MAXNAMLEN
+ 3];
2454 strcpy (filename
, dir_pathname
);
2455 ln
= strlen (filename
) - 1;
2456 if (!IS_DIRECTORY_SEP (filename
[ln
]))
2457 strcat (filename
, "\\");
2458 strcat (filename
, "*");
2460 dir_find_handle
= FindFirstFile (filename
, &dir_find_data
);
2462 if (dir_find_handle
== INVALID_HANDLE_VALUE
)
2467 if (!FindNextFile (dir_find_handle
, &dir_find_data
))
2471 /* Emacs never uses this value, so don't bother making it match
2472 value returned by stat(). */
2473 dir_static
.d_ino
= 1;
2475 strcpy (dir_static
.d_name
, dir_find_data
.cFileName
);
2477 /* If the file name in cFileName[] includes `?' characters, it means
2478 the original file name used characters that cannot be represented
2479 by the current ANSI codepage. To avoid total lossage, retrieve
2480 the short 8+3 alias of the long file name. */
2481 if (_mbspbrk (dir_static
.d_name
, "?"))
2483 strcpy (dir_static
.d_name
, dir_find_data
.cAlternateFileName
);
2484 downcase
= 1; /* 8+3 aliases are returned in all caps */
2486 dir_static
.d_namlen
= strlen (dir_static
.d_name
);
2487 dir_static
.d_reclen
= sizeof (struct direct
) - MAXNAMLEN
+ 3 +
2488 dir_static
.d_namlen
- dir_static
.d_namlen
% 4;
2490 /* If the file name in cFileName[] includes `?' characters, it means
2491 the original file name used characters that cannot be represented
2492 by the current ANSI codepage. To avoid total lossage, retrieve
2493 the short 8+3 alias of the long file name. */
2494 if (_mbspbrk (dir_find_data
.cFileName
, "?"))
2496 strcpy (dir_static
.d_name
, dir_find_data
.cAlternateFileName
);
2497 /* 8+3 aliases are returned in all caps, which could break
2498 various alists that look at filenames' extensions. */
2502 strcpy (dir_static
.d_name
, dir_find_data
.cFileName
);
2503 dir_static
.d_namlen
= strlen (dir_static
.d_name
);
2505 _strlwr (dir_static
.d_name
);
2509 for (p
= dir_static
.d_name
; *p
; p
++)
2510 if (*p
>= 'a' && *p
<= 'z')
2513 _strlwr (dir_static
.d_name
);
2520 open_unc_volume (const char *path
)
2526 nr
.dwScope
= RESOURCE_GLOBALNET
;
2527 nr
.dwType
= RESOURCETYPE_DISK
;
2528 nr
.dwDisplayType
= RESOURCEDISPLAYTYPE_SERVER
;
2529 nr
.dwUsage
= RESOURCEUSAGE_CONTAINER
;
2530 nr
.lpLocalName
= NULL
;
2531 nr
.lpRemoteName
= (LPSTR
)map_w32_filename (path
, NULL
);
2532 nr
.lpComment
= NULL
;
2533 nr
.lpProvider
= NULL
;
2535 result
= WNetOpenEnum (RESOURCE_GLOBALNET
, RESOURCETYPE_DISK
,
2536 RESOURCEUSAGE_CONNECTABLE
, &nr
, &henum
);
2538 if (result
== NO_ERROR
)
2541 return INVALID_HANDLE_VALUE
;
2545 read_unc_volume (HANDLE henum
, char *readbuf
, int size
)
2549 DWORD bufsize
= 512;
2554 buffer
= alloca (bufsize
);
2555 result
= WNetEnumResource (henum
, &count
, buffer
, &bufsize
);
2556 if (result
!= NO_ERROR
)
2559 /* WNetEnumResource returns \\resource\share...skip forward to "share". */
2560 ptr
= ((LPNETRESOURCE
) buffer
)->lpRemoteName
;
2562 while (*ptr
&& !IS_DIRECTORY_SEP (*ptr
)) ptr
++;
2565 strncpy (readbuf
, ptr
, size
);
2570 close_unc_volume (HANDLE henum
)
2572 if (henum
!= INVALID_HANDLE_VALUE
)
2573 WNetCloseEnum (henum
);
2577 unc_volume_file_attributes (const char *path
)
2582 henum
= open_unc_volume (path
);
2583 if (henum
== INVALID_HANDLE_VALUE
)
2586 attrs
= FILE_ATTRIBUTE_READONLY
| FILE_ATTRIBUTE_DIRECTORY
;
2588 close_unc_volume (henum
);
2593 /* Ensure a network connection is authenticated. */
2595 logon_network_drive (const char *path
)
2597 NETRESOURCE resource
;
2598 char share
[MAX_PATH
];
2603 if (IS_DIRECTORY_SEP (path
[0]) && IS_DIRECTORY_SEP (path
[1]))
2604 drvtype
= DRIVE_REMOTE
;
2605 else if (path
[0] == '\0' || path
[1] != ':')
2606 drvtype
= GetDriveType (NULL
);
2613 drvtype
= GetDriveType (drive
);
2616 /* Only logon to networked drives. */
2617 if (drvtype
!= DRIVE_REMOTE
)
2621 strncpy (share
, path
, MAX_PATH
);
2622 /* Truncate to just server and share name. */
2623 for (i
= 2; i
< MAX_PATH
; i
++)
2625 if (IS_DIRECTORY_SEP (share
[i
]) && ++n_slashes
> 3)
2632 resource
.dwType
= RESOURCETYPE_DISK
;
2633 resource
.lpLocalName
= NULL
;
2634 resource
.lpRemoteName
= share
;
2635 resource
.lpProvider
= NULL
;
2637 WNetAddConnection2 (&resource
, NULL
, NULL
, CONNECT_INTERACTIVE
);
2640 /* Shadow some MSVC runtime functions to map requests for long filenames
2641 to reasonable short names if necessary. This was originally added to
2642 permit running Emacs on NT 3.1 on a FAT partition, which doesn't support
2646 sys_access (const char * path
, int mode
)
2650 /* MSVCRT implementation of 'access' doesn't recognize D_OK, and its
2651 newer versions blow up when passed D_OK. */
2652 path
= map_w32_filename (path
, NULL
);
2653 if (is_unc_volume (path
))
2655 attributes
= unc_volume_file_attributes (path
);
2656 if (attributes
== -1) {
2661 else if ((attributes
= GetFileAttributes (path
)) == -1)
2663 DWORD w32err
= GetLastError ();
2667 case ERROR_FILE_NOT_FOUND
:
2676 if ((mode
& X_OK
) != 0 && !is_exec (path
))
2681 if ((mode
& W_OK
) != 0 && (attributes
& FILE_ATTRIBUTE_READONLY
) != 0)
2686 if ((mode
& D_OK
) != 0 && (attributes
& FILE_ATTRIBUTE_DIRECTORY
) == 0)
2695 sys_chdir (const char * path
)
2697 return _chdir (map_w32_filename (path
, NULL
));
2701 sys_chmod (const char * path
, int mode
)
2703 return _chmod (map_w32_filename (path
, NULL
), mode
);
2707 sys_chown (const char *path
, uid_t owner
, gid_t group
)
2709 if (sys_chmod (path
, S_IREAD
) == -1) /* check if file exists */
2715 sys_creat (const char * path
, int mode
)
2717 return _creat (map_w32_filename (path
, NULL
), mode
);
2721 sys_fopen (const char * path
, const char * mode
)
2725 const char * mode_save
= mode
;
2727 /* Force all file handles to be non-inheritable. This is necessary to
2728 ensure child processes don't unwittingly inherit handles that might
2729 prevent future file access. */
2733 else if (mode
[0] == 'w' || mode
[0] == 'a')
2734 oflag
= O_WRONLY
| O_CREAT
| O_TRUNC
;
2738 /* Only do simplistic option parsing. */
2742 oflag
&= ~(O_RDONLY
| O_WRONLY
);
2745 else if (mode
[0] == 'b')
2750 else if (mode
[0] == 't')
2757 fd
= _open (map_w32_filename (path
, NULL
), oflag
| _O_NOINHERIT
, 0644);
2761 return _fdopen (fd
, mode_save
);
2764 /* This only works on NTFS volumes, but is useful to have. */
2766 sys_link (const char * old
, const char * new)
2770 char oldname
[MAX_PATH
], newname
[MAX_PATH
];
2772 if (old
== NULL
|| new == NULL
)
2778 strcpy (oldname
, map_w32_filename (old
, NULL
));
2779 strcpy (newname
, map_w32_filename (new, NULL
));
2781 fileh
= CreateFile (oldname
, 0, 0, NULL
, OPEN_EXISTING
,
2782 FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
2783 if (fileh
!= INVALID_HANDLE_VALUE
)
2787 /* Confusingly, the "alternate" stream name field does not apply
2788 when restoring a hard link, and instead contains the actual
2789 stream data for the link (ie. the name of the link to create).
2790 The WIN32_STREAM_ID structure before the cStreamName field is
2791 the stream header, which is then immediately followed by the
2795 WIN32_STREAM_ID wid
;
2796 WCHAR wbuffer
[MAX_PATH
]; /* extra space for link name */
2799 wlen
= MultiByteToWideChar (CP_ACP
, MB_PRECOMPOSED
, newname
, -1,
2800 data
.wid
.cStreamName
, MAX_PATH
);
2803 LPVOID context
= NULL
;
2806 data
.wid
.dwStreamId
= BACKUP_LINK
;
2807 data
.wid
.dwStreamAttributes
= 0;
2808 data
.wid
.Size
.LowPart
= wlen
* sizeof (WCHAR
);
2809 data
.wid
.Size
.HighPart
= 0;
2810 data
.wid
.dwStreamNameSize
= 0;
2812 if (BackupWrite (fileh
, (LPBYTE
)&data
,
2813 offsetof (WIN32_STREAM_ID
, cStreamName
)
2814 + data
.wid
.Size
.LowPart
,
2815 &wbytes
, FALSE
, FALSE
, &context
)
2816 && BackupWrite (fileh
, NULL
, 0, &wbytes
, TRUE
, FALSE
, &context
))
2823 /* Should try mapping GetLastError to errno; for now just
2824 indicate a general error (eg. links not supported). */
2825 errno
= EINVAL
; // perhaps EMLINK?
2829 CloseHandle (fileh
);
2838 sys_mkdir (const char * path
)
2840 return _mkdir (map_w32_filename (path
, NULL
));
2843 /* Because of long name mapping issues, we need to implement this
2844 ourselves. Also, MSVC's _mktemp returns NULL when it can't generate
2845 a unique name, instead of setting the input template to an empty
2848 Standard algorithm seems to be use pid or tid with a letter on the
2849 front (in place of the 6 X's) and cycle through the letters to find a
2850 unique name. We extend that to allow any reasonable character as the
2851 first of the 6 X's. */
2853 sys_mktemp (char * template)
2857 unsigned uid
= GetCurrentThreadId ();
2858 static char first_char
[] = "abcdefghijklmnopqrstuvwyz0123456789!%-_@#";
2860 if (template == NULL
)
2862 p
= template + strlen (template);
2864 /* replace up to the last 5 X's with uid in decimal */
2865 while (--p
>= template && p
[0] == 'X' && --i
>= 0)
2867 p
[0] = '0' + uid
% 10;
2871 if (i
< 0 && p
[0] == 'X')
2876 int save_errno
= errno
;
2877 p
[0] = first_char
[i
];
2878 if (sys_access (template, 0) < 0)
2884 while (++i
< sizeof (first_char
));
2887 /* Template is badly formed or else we can't generate a unique name,
2888 so return empty string */
2894 sys_open (const char * path
, int oflag
, int mode
)
2896 const char* mpath
= map_w32_filename (path
, NULL
);
2897 /* Try to open file without _O_CREAT, to be able to write to hidden
2898 and system files. Force all file handles to be
2900 int res
= _open (mpath
, (oflag
& ~_O_CREAT
) | _O_NOINHERIT
, mode
);
2903 return _open (mpath
, oflag
| _O_NOINHERIT
, mode
);
2907 sys_rename (const char * oldname
, const char * newname
)
2910 char temp
[MAX_PATH
];
2914 /* MoveFile on Windows 95 doesn't correctly change the short file name
2915 alias in a number of circumstances (it is not easy to predict when
2916 just by looking at oldname and newname, unfortunately). In these
2917 cases, renaming through a temporary name avoids the problem.
2919 A second problem on Windows 95 is that renaming through a temp name when
2920 newname is uppercase fails (the final long name ends up in
2921 lowercase, although the short alias might be uppercase) UNLESS the
2922 long temp name is not 8.3.
2924 So, on Windows 95 we always rename through a temp name, and we make sure
2925 the temp name has a long extension to ensure correct renaming. */
2927 strcpy (temp
, map_w32_filename (oldname
, NULL
));
2929 /* volume_info is set indirectly by map_w32_filename. */
2930 oldname_dev
= volume_info
.serialnum
;
2932 if (os_subtype
== OS_9X
)
2938 oldname
= map_w32_filename (oldname
, NULL
);
2939 if ((o
= strrchr (oldname
, '\\')))
2942 o
= (char *) oldname
;
2944 if ((p
= strrchr (temp
, '\\')))
2951 /* Force temp name to require a manufactured 8.3 alias - this
2952 seems to make the second rename work properly. */
2953 sprintf (p
, "_.%s.%u", o
, i
);
2955 result
= rename (oldname
, temp
);
2957 /* This loop must surely terminate! */
2958 while (result
< 0 && errno
== EEXIST
);
2963 /* Emulate Unix behavior - newname is deleted if it already exists
2964 (at least if it is a file; don't do this for directories).
2966 Since we mustn't do this if we are just changing the case of the
2967 file name (we would end up deleting the file we are trying to
2968 rename!), we let rename detect if the destination file already
2969 exists - that way we avoid the possible pitfalls of trying to
2970 determine ourselves whether two names really refer to the same
2971 file, which is not always possible in the general case. (Consider
2972 all the permutations of shared or subst'd drives, etc.) */
2974 newname
= map_w32_filename (newname
, NULL
);
2976 /* volume_info is set indirectly by map_w32_filename. */
2977 newname_dev
= volume_info
.serialnum
;
2979 result
= rename (temp
, newname
);
2985 && newname_dev
!= oldname_dev
)
2987 /* The implementation of `rename' on Windows does not return
2988 errno = EXDEV when you are moving a directory to a
2989 different storage device (ex. logical disk). It returns
2990 EACCES instead. So here we handle such situations and
2994 if ((attributes
= GetFileAttributes (temp
)) != -1
2995 && attributes
& FILE_ATTRIBUTE_DIRECTORY
)
2998 else if (errno
== EEXIST
)
3000 if (_chmod (newname
, 0666) != 0)
3002 if (_unlink (newname
) != 0)
3004 result
= rename (temp
, newname
);
3012 sys_rmdir (const char * path
)
3014 return _rmdir (map_w32_filename (path
, NULL
));
3018 sys_unlink (const char * path
)
3020 path
= map_w32_filename (path
, NULL
);
3022 /* On Unix, unlink works without write permission. */
3023 _chmod (path
, 0666);
3024 return _unlink (path
);
3027 static FILETIME utc_base_ft
;
3028 static ULONGLONG utc_base
; /* In 100ns units */
3029 static int init
= 0;
3031 #define FILETIME_TO_U64(result, ft) \
3033 ULARGE_INTEGER uiTemp; \
3034 uiTemp.LowPart = (ft).dwLowDateTime; \
3035 uiTemp.HighPart = (ft).dwHighDateTime; \
3036 result = uiTemp.QuadPart; \
3040 initialize_utc_base (void)
3042 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
3051 st
.wMilliseconds
= 0;
3053 SystemTimeToFileTime (&st
, &utc_base_ft
);
3054 FILETIME_TO_U64 (utc_base
, utc_base_ft
);
3058 convert_time (FILETIME ft
)
3064 initialize_utc_base ();
3068 if (CompareFileTime (&ft
, &utc_base_ft
) < 0)
3071 FILETIME_TO_U64 (tmp
, ft
);
3072 return (time_t) ((tmp
- utc_base
) / 10000000L);
3076 convert_from_time_t (time_t time
, FILETIME
* pft
)
3082 initialize_utc_base ();
3086 /* time in 100ns units since 1-Jan-1601 */
3087 tmp
.QuadPart
= (ULONGLONG
) time
* 10000000L + utc_base
;
3088 pft
->dwHighDateTime
= tmp
.HighPart
;
3089 pft
->dwLowDateTime
= tmp
.LowPart
;
3093 /* No reason to keep this; faking inode values either by hashing or even
3094 using the file index from GetInformationByHandle, is not perfect and
3095 so by default Emacs doesn't use the inode values on Windows.
3096 Instead, we now determine file-truename correctly (except for
3097 possible drive aliasing etc). */
3099 /* Modified version of "PJW" algorithm (see the "Dragon" compiler book). */
3101 hashval (const unsigned char * str
)
3106 h
= (h
<< 4) + *str
++;
3112 /* Return the hash value of the canonical pathname, excluding the
3113 drive/UNC header, to get a hopefully unique inode number. */
3115 generate_inode_val (const char * name
)
3117 char fullname
[ MAX_PATH
];
3121 /* Get the truly canonical filename, if it exists. (Note: this
3122 doesn't resolve aliasing due to subst commands, or recognize hard
3124 if (!w32_get_long_filename ((char *)name
, fullname
, MAX_PATH
))
3127 parse_root (fullname
, &p
);
3128 /* Normal W32 filesystems are still case insensitive. */
3135 static PSECURITY_DESCRIPTOR
3136 get_file_security_desc (const char *fname
)
3138 PSECURITY_DESCRIPTOR psd
= NULL
;
3140 SECURITY_INFORMATION si
= OWNER_SECURITY_INFORMATION
3141 | GROUP_SECURITY_INFORMATION
/* | DACL_SECURITY_INFORMATION */ ;
3143 if (!get_file_security (fname
, si
, psd
, 0, &sd_len
))
3145 err
= GetLastError ();
3146 if (err
!= ERROR_INSUFFICIENT_BUFFER
)
3150 psd
= xmalloc (sd_len
);
3151 if (!get_file_security (fname
, si
, psd
, sd_len
, &sd_len
))
3163 unsigned n_subauthorities
;
3165 /* Use the last sub-authority value of the RID, the relative
3166 portion of the SID, as user/group ID. */
3167 n_subauthorities
= *get_sid_sub_authority_count (sid
);
3168 if (n_subauthorities
< 1)
3169 return 0; /* the "World" RID */
3170 return *get_sid_sub_authority (sid
, n_subauthorities
- 1);
3173 /* Caching SID and account values for faster lokup. */
3176 # define FLEXIBLE_ARRAY_MEMBER
3178 # define FLEXIBLE_ARRAY_MEMBER 1
3183 struct w32_id
*next
;
3185 unsigned char sid
[FLEXIBLE_ARRAY_MEMBER
];
3188 static struct w32_id
*w32_idlist
;
3191 w32_cached_id (PSID sid
, unsigned *id
, char *name
)
3193 struct w32_id
*tail
, *found
;
3195 for (found
= NULL
, tail
= w32_idlist
; tail
; tail
= tail
->next
)
3197 if (equal_sid ((PSID
)tail
->sid
, sid
))
3206 strcpy (name
, found
->name
);
3214 w32_add_to_cache (PSID sid
, unsigned id
, char *name
)
3217 struct w32_id
*new_entry
;
3219 /* We don't want to leave behind stale cache from when Emacs was
3223 sid_len
= get_length_sid (sid
);
3224 new_entry
= xmalloc (offsetof (struct w32_id
, sid
) + sid_len
);
3227 new_entry
->rid
= id
;
3228 strcpy (new_entry
->name
, name
);
3229 copy_sid (sid_len
, (PSID
)new_entry
->sid
, sid
);
3230 new_entry
->next
= w32_idlist
;
3231 w32_idlist
= new_entry
;
3240 get_name_and_id (PSECURITY_DESCRIPTOR psd
, const char *fname
,
3241 unsigned *id
, char *nm
, int what
)
3244 char machine
[MAX_COMPUTERNAME_LENGTH
+1];
3246 SID_NAME_USE ignore
;
3248 DWORD name_len
= sizeof (name
);
3250 DWORD domain_len
= sizeof (domain
);
3256 result
= get_security_descriptor_owner (psd
, &sid
, &dflt
);
3257 else if (what
== GID
)
3258 result
= get_security_descriptor_group (psd
, &sid
, &dflt
);
3262 if (!result
|| !is_valid_sid (sid
))
3264 else if (!w32_cached_id (sid
, id
, nm
))
3266 /* If FNAME is a UNC, we need to lookup account on the
3267 specified machine. */
3268 if (IS_DIRECTORY_SEP (fname
[0]) && IS_DIRECTORY_SEP (fname
[1])
3269 && fname
[2] != '\0')
3274 for (s
= fname
+ 2, p
= machine
;
3275 *s
&& !IS_DIRECTORY_SEP (*s
); s
++, p
++)
3281 if (!lookup_account_sid (mp
, sid
, name
, &name_len
,
3282 domain
, &domain_len
, &ignore
)
3283 || name_len
> UNLEN
+1)
3287 *id
= get_rid (sid
);
3289 w32_add_to_cache (sid
, *id
, name
);
3296 get_file_owner_and_group (PSECURITY_DESCRIPTOR psd
,
3300 int dflt_usr
= 0, dflt_grp
= 0;
3309 if (get_name_and_id (psd
, fname
, &st
->st_uid
, st
->st_uname
, UID
))
3311 if (get_name_and_id (psd
, fname
, &st
->st_gid
, st
->st_gname
, GID
))
3314 /* Consider files to belong to current user/group, if we cannot get
3315 more accurate information. */
3318 st
->st_uid
= dflt_passwd
.pw_uid
;
3319 strcpy (st
->st_uname
, dflt_passwd
.pw_name
);
3323 st
->st_gid
= dflt_passwd
.pw_gid
;
3324 strcpy (st
->st_gname
, dflt_group
.gr_name
);
3328 /* Return non-zero if NAME is a potentially slow filesystem. */
3330 is_slow_fs (const char *name
)
3335 if (IS_DIRECTORY_SEP (name
[0]) && IS_DIRECTORY_SEP (name
[1]))
3336 devtype
= DRIVE_REMOTE
; /* assume UNC name is remote */
3337 else if (!(strlen (name
) >= 2 && IS_DEVICE_SEP (name
[1])))
3338 devtype
= GetDriveType (NULL
); /* use root of current drive */
3341 /* GetDriveType needs the root directory of the drive. */
3342 strncpy (drive_root
, name
, 2);
3343 drive_root
[2] = '\\';
3344 drive_root
[3] = '\0';
3345 devtype
= GetDriveType (drive_root
);
3347 return !(devtype
== DRIVE_FIXED
|| devtype
== DRIVE_RAMDISK
);
3350 /* MSVC stat function can't cope with UNC names and has other bugs, so
3351 replace it with our own. This also allows us to calculate consistent
3352 inode values without hacks in the main Emacs code. */
3354 stat (const char * path
, struct stat
* buf
)
3357 WIN32_FIND_DATA wfd
;
3359 unsigned __int64 fake_inode
;
3362 int rootdir
= FALSE
;
3363 PSECURITY_DESCRIPTOR psd
= NULL
;
3365 if (path
== NULL
|| buf
== NULL
)
3371 name
= (char *) map_w32_filename (path
, &path
);
3372 /* Must be valid filename, no wild cards or other invalid
3373 characters. We use _mbspbrk to support multibyte strings that
3374 might look to strpbrk as if they included literal *, ?, and other
3375 characters mentioned below that are disallowed by Windows
3377 if (_mbspbrk (name
, "*?|<>\""))
3383 /* If name is "c:/.." or "/.." then stat "c:/" or "/". */
3384 r
= IS_DEVICE_SEP (name
[1]) ? &name
[2] : name
;
3385 if (IS_DIRECTORY_SEP (r
[0]) && r
[1] == '.' && r
[2] == '.' && r
[3] == '\0')
3390 /* Remove trailing directory separator, unless name is the root
3391 directory of a drive or UNC volume in which case ensure there
3392 is a trailing separator. */
3393 len
= strlen (name
);
3394 rootdir
= (path
>= name
+ len
- 1
3395 && (IS_DIRECTORY_SEP (*path
) || *path
== 0));
3396 name
= strcpy (alloca (len
+ 2), name
);
3398 if (is_unc_volume (name
))
3400 DWORD attrs
= unc_volume_file_attributes (name
);
3405 memset (&wfd
, 0, sizeof (wfd
));
3406 wfd
.dwFileAttributes
= attrs
;
3407 wfd
.ftCreationTime
= utc_base_ft
;
3408 wfd
.ftLastAccessTime
= utc_base_ft
;
3409 wfd
.ftLastWriteTime
= utc_base_ft
;
3410 strcpy (wfd
.cFileName
, name
);
3414 if (!IS_DIRECTORY_SEP (name
[len
-1]))
3415 strcat (name
, "\\");
3416 if (GetDriveType (name
) < 2)
3421 memset (&wfd
, 0, sizeof (wfd
));
3422 wfd
.dwFileAttributes
= FILE_ATTRIBUTE_DIRECTORY
;
3423 wfd
.ftCreationTime
= utc_base_ft
;
3424 wfd
.ftLastAccessTime
= utc_base_ft
;
3425 wfd
.ftLastWriteTime
= utc_base_ft
;
3426 strcpy (wfd
.cFileName
, name
);
3430 if (IS_DIRECTORY_SEP (name
[len
-1]))
3433 /* (This is hacky, but helps when doing file completions on
3434 network drives.) Optimize by using information available from
3435 active readdir if possible. */
3436 len
= strlen (dir_pathname
);
3437 if (IS_DIRECTORY_SEP (dir_pathname
[len
-1]))
3439 if (dir_find_handle
!= INVALID_HANDLE_VALUE
3440 && strnicmp (name
, dir_pathname
, len
) == 0
3441 && IS_DIRECTORY_SEP (name
[len
])
3442 && xstrcasecmp (name
+ len
+ 1, dir_static
.d_name
) == 0)
3444 /* This was the last entry returned by readdir. */
3445 wfd
= dir_find_data
;
3449 logon_network_drive (name
);
3451 fh
= FindFirstFile (name
, &wfd
);
3452 if (fh
== INVALID_HANDLE_VALUE
)
3461 if (!(NILP (Vw32_get_true_file_attributes
)
3462 || (EQ (Vw32_get_true_file_attributes
, Qlocal
) && is_slow_fs (name
)))
3463 /* No access rights required to get info. */
3464 && (fh
= CreateFile (name
, 0, 0, NULL
, OPEN_EXISTING
,
3465 FILE_FLAG_BACKUP_SEMANTICS
, NULL
))
3466 != INVALID_HANDLE_VALUE
)
3468 /* This is more accurate in terms of getting the correct number
3469 of links, but is quite slow (it is noticeable when Emacs is
3470 making a list of file name completions). */
3471 BY_HANDLE_FILE_INFORMATION info
;
3473 if (GetFileInformationByHandle (fh
, &info
))
3475 buf
->st_nlink
= info
.nNumberOfLinks
;
3476 /* Might as well use file index to fake inode values, but this
3477 is not guaranteed to be unique unless we keep a handle open
3478 all the time (even then there are situations where it is
3479 not unique). Reputedly, there are at most 48 bits of info
3480 (on NTFS, presumably less on FAT). */
3481 fake_inode
= info
.nFileIndexHigh
;
3483 fake_inode
+= info
.nFileIndexLow
;
3491 if (wfd
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
3493 buf
->st_mode
= S_IFDIR
;
3497 switch (GetFileType (fh
))
3499 case FILE_TYPE_DISK
:
3500 buf
->st_mode
= S_IFREG
;
3502 case FILE_TYPE_PIPE
:
3503 buf
->st_mode
= S_IFIFO
;
3505 case FILE_TYPE_CHAR
:
3506 case FILE_TYPE_UNKNOWN
:
3508 buf
->st_mode
= S_IFCHR
;
3512 psd
= get_file_security_desc (name
);
3513 get_file_owner_and_group (psd
, name
, buf
);
3517 /* Don't bother to make this information more accurate. */
3518 buf
->st_mode
= (wfd
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
) ?
3523 get_file_owner_and_group (NULL
, name
, buf
);
3528 /* Not sure if there is any point in this. */
3529 if (!NILP (Vw32_generate_fake_inodes
))
3530 fake_inode
= generate_inode_val (name
);
3531 else if (fake_inode
== 0)
3533 /* For want of something better, try to make everything unique. */
3534 static DWORD gen_num
= 0;
3535 fake_inode
= ++gen_num
;
3539 /* MSVC defines _ino_t to be short; other libc's might not. */
3540 if (sizeof (buf
->st_ino
) == 2)
3541 buf
->st_ino
= fake_inode
^ (fake_inode
>> 16);
3543 buf
->st_ino
= fake_inode
;
3545 /* volume_info is set indirectly by map_w32_filename */
3546 buf
->st_dev
= volume_info
.serialnum
;
3547 buf
->st_rdev
= volume_info
.serialnum
;
3549 buf
->st_size
= wfd
.nFileSizeHigh
;
3550 buf
->st_size
<<= 32;
3551 buf
->st_size
+= wfd
.nFileSizeLow
;
3553 /* Convert timestamps to Unix format. */
3554 buf
->st_mtime
= convert_time (wfd
.ftLastWriteTime
);
3555 buf
->st_atime
= convert_time (wfd
.ftLastAccessTime
);
3556 if (buf
->st_atime
== 0) buf
->st_atime
= buf
->st_mtime
;
3557 buf
->st_ctime
= convert_time (wfd
.ftCreationTime
);
3558 if (buf
->st_ctime
== 0) buf
->st_ctime
= buf
->st_mtime
;
3560 /* determine rwx permissions */
3561 if (wfd
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
)
3562 permission
= S_IREAD
;
3564 permission
= S_IREAD
| S_IWRITE
;
3566 if (wfd
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
3567 permission
|= S_IEXEC
;
3568 else if (is_exec (name
))
3569 permission
|= S_IEXEC
;
3571 buf
->st_mode
|= permission
| (permission
>> 3) | (permission
>> 6);
3576 /* Provide fstat and utime as well as stat for consistent handling of
3579 fstat (int desc
, struct stat
* buf
)
3581 HANDLE fh
= (HANDLE
) _get_osfhandle (desc
);
3582 BY_HANDLE_FILE_INFORMATION info
;
3583 unsigned __int64 fake_inode
;
3586 switch (GetFileType (fh
) & ~FILE_TYPE_REMOTE
)
3588 case FILE_TYPE_DISK
:
3589 buf
->st_mode
= S_IFREG
;
3590 if (!GetFileInformationByHandle (fh
, &info
))
3596 case FILE_TYPE_PIPE
:
3597 buf
->st_mode
= S_IFIFO
;
3599 case FILE_TYPE_CHAR
:
3600 case FILE_TYPE_UNKNOWN
:
3602 buf
->st_mode
= S_IFCHR
;
3604 memset (&info
, 0, sizeof (info
));
3605 info
.dwFileAttributes
= 0;
3606 info
.ftCreationTime
= utc_base_ft
;
3607 info
.ftLastAccessTime
= utc_base_ft
;
3608 info
.ftLastWriteTime
= utc_base_ft
;
3611 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
3612 buf
->st_mode
= S_IFDIR
;
3614 buf
->st_nlink
= info
.nNumberOfLinks
;
3615 /* Might as well use file index to fake inode values, but this
3616 is not guaranteed to be unique unless we keep a handle open
3617 all the time (even then there are situations where it is
3618 not unique). Reputedly, there are at most 48 bits of info
3619 (on NTFS, presumably less on FAT). */
3620 fake_inode
= info
.nFileIndexHigh
;
3622 fake_inode
+= info
.nFileIndexLow
;
3624 /* MSVC defines _ino_t to be short; other libc's might not. */
3625 if (sizeof (buf
->st_ino
) == 2)
3626 buf
->st_ino
= fake_inode
^ (fake_inode
>> 16);
3628 buf
->st_ino
= fake_inode
;
3630 /* Consider files to belong to current user.
3631 FIXME: this should use GetSecurityInfo API, but it is only
3632 available for _WIN32_WINNT >= 0x501. */
3633 buf
->st_uid
= dflt_passwd
.pw_uid
;
3634 buf
->st_gid
= dflt_passwd
.pw_gid
;
3635 strcpy (buf
->st_uname
, dflt_passwd
.pw_name
);
3636 strcpy (buf
->st_gname
, dflt_group
.gr_name
);
3638 buf
->st_dev
= info
.dwVolumeSerialNumber
;
3639 buf
->st_rdev
= info
.dwVolumeSerialNumber
;
3641 buf
->st_size
= info
.nFileSizeHigh
;
3642 buf
->st_size
<<= 32;
3643 buf
->st_size
+= info
.nFileSizeLow
;
3645 /* Convert timestamps to Unix format. */
3646 buf
->st_mtime
= convert_time (info
.ftLastWriteTime
);
3647 buf
->st_atime
= convert_time (info
.ftLastAccessTime
);
3648 if (buf
->st_atime
== 0) buf
->st_atime
= buf
->st_mtime
;
3649 buf
->st_ctime
= convert_time (info
.ftCreationTime
);
3650 if (buf
->st_ctime
== 0) buf
->st_ctime
= buf
->st_mtime
;
3652 /* determine rwx permissions */
3653 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
)
3654 permission
= S_IREAD
;
3656 permission
= S_IREAD
| S_IWRITE
;
3658 if (info
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
3659 permission
|= S_IEXEC
;
3662 #if 0 /* no way of knowing the filename */
3663 char * p
= strrchr (name
, '.');
3665 (xstrcasecmp (p
, ".exe") == 0 ||
3666 xstrcasecmp (p
, ".com") == 0 ||
3667 xstrcasecmp (p
, ".bat") == 0 ||
3668 xstrcasecmp (p
, ".cmd") == 0))
3669 permission
|= S_IEXEC
;
3673 buf
->st_mode
|= permission
| (permission
>> 3) | (permission
>> 6);
3679 utime (const char *name
, struct utimbuf
*times
)
3681 struct utimbuf deftime
;
3688 deftime
.modtime
= deftime
.actime
= time (NULL
);
3692 /* Need write access to set times. */
3693 fh
= CreateFile (name
, GENERIC_WRITE
, FILE_SHARE_READ
| FILE_SHARE_WRITE
,
3694 0, OPEN_EXISTING
, 0, NULL
);
3697 convert_from_time_t (times
->actime
, &atime
);
3698 convert_from_time_t (times
->modtime
, &mtime
);
3699 if (!SetFileTime (fh
, NULL
, &atime
, &mtime
))
3716 /* Symlink-related functions that always fail. Used in fileio.c and in
3717 sysdep.c to avoid #ifdef's. */
3719 symlink (char const *dummy1
, char const *dummy2
)
3726 readlink (const char *name
, char *dummy1
, size_t dummy2
)
3728 /* `access' is much faster than `stat' on MS-Windows. */
3729 if (sys_access (name
, 0) == 0)
3735 careadlinkat (int fd
, char const *filename
,
3736 char *buffer
, size_t buffer_size
,
3737 struct allocator
const *alloc
,
3738 ssize_t (*preadlinkat
) (int, char const *, char *, size_t))
3745 careadlinkatcwd (int fd
, char const *filename
, char *buffer
,
3749 return readlink (filename
, buffer
, buffer_size
);
3753 /* Support for browsing other processes and their attributes. See
3754 process.c for the Lisp bindings. */
3756 /* Helper wrapper functions. */
3758 static HANDLE WINAPI
3759 create_toolhelp32_snapshot (DWORD Flags
, DWORD Ignored
)
3761 static CreateToolhelp32Snapshot_Proc s_pfn_Create_Toolhelp32_Snapshot
= NULL
;
3763 if (g_b_init_create_toolhelp32_snapshot
== 0)
3765 g_b_init_create_toolhelp32_snapshot
= 1;
3766 s_pfn_Create_Toolhelp32_Snapshot
= (CreateToolhelp32Snapshot_Proc
)
3767 GetProcAddress (GetModuleHandle ("kernel32.dll"),
3768 "CreateToolhelp32Snapshot");
3770 if (s_pfn_Create_Toolhelp32_Snapshot
== NULL
)
3772 return INVALID_HANDLE_VALUE
;
3774 return (s_pfn_Create_Toolhelp32_Snapshot (Flags
, Ignored
));
3778 process32_first (HANDLE hSnapshot
, LPPROCESSENTRY32 lppe
)
3780 static Process32First_Proc s_pfn_Process32_First
= NULL
;
3782 if (g_b_init_process32_first
== 0)
3784 g_b_init_process32_first
= 1;
3785 s_pfn_Process32_First
= (Process32First_Proc
)
3786 GetProcAddress (GetModuleHandle ("kernel32.dll"),
3789 if (s_pfn_Process32_First
== NULL
)
3793 return (s_pfn_Process32_First (hSnapshot
, lppe
));
3797 process32_next (HANDLE hSnapshot
, LPPROCESSENTRY32 lppe
)
3799 static Process32Next_Proc s_pfn_Process32_Next
= NULL
;
3801 if (g_b_init_process32_next
== 0)
3803 g_b_init_process32_next
= 1;
3804 s_pfn_Process32_Next
= (Process32Next_Proc
)
3805 GetProcAddress (GetModuleHandle ("kernel32.dll"),
3808 if (s_pfn_Process32_Next
== NULL
)
3812 return (s_pfn_Process32_Next (hSnapshot
, lppe
));
3816 open_thread_token (HANDLE ThreadHandle
,
3817 DWORD DesiredAccess
,
3819 PHANDLE TokenHandle
)
3821 static OpenThreadToken_Proc s_pfn_Open_Thread_Token
= NULL
;
3822 HMODULE hm_advapi32
= NULL
;
3823 if (is_windows_9x () == TRUE
)
3825 SetLastError (ERROR_NOT_SUPPORTED
);
3828 if (g_b_init_open_thread_token
== 0)
3830 g_b_init_open_thread_token
= 1;
3831 hm_advapi32
= LoadLibrary ("Advapi32.dll");
3832 s_pfn_Open_Thread_Token
=
3833 (OpenThreadToken_Proc
) GetProcAddress (hm_advapi32
, "OpenThreadToken");
3835 if (s_pfn_Open_Thread_Token
== NULL
)
3837 SetLastError (ERROR_NOT_SUPPORTED
);
3841 s_pfn_Open_Thread_Token (
3850 impersonate_self (SECURITY_IMPERSONATION_LEVEL ImpersonationLevel
)
3852 static ImpersonateSelf_Proc s_pfn_Impersonate_Self
= NULL
;
3853 HMODULE hm_advapi32
= NULL
;
3854 if (is_windows_9x () == TRUE
)
3858 if (g_b_init_impersonate_self
== 0)
3860 g_b_init_impersonate_self
= 1;
3861 hm_advapi32
= LoadLibrary ("Advapi32.dll");
3862 s_pfn_Impersonate_Self
=
3863 (ImpersonateSelf_Proc
) GetProcAddress (hm_advapi32
, "ImpersonateSelf");
3865 if (s_pfn_Impersonate_Self
== NULL
)
3869 return s_pfn_Impersonate_Self (ImpersonationLevel
);
3873 revert_to_self (void)
3875 static RevertToSelf_Proc s_pfn_Revert_To_Self
= NULL
;
3876 HMODULE hm_advapi32
= NULL
;
3877 if (is_windows_9x () == TRUE
)
3881 if (g_b_init_revert_to_self
== 0)
3883 g_b_init_revert_to_self
= 1;
3884 hm_advapi32
= LoadLibrary ("Advapi32.dll");
3885 s_pfn_Revert_To_Self
=
3886 (RevertToSelf_Proc
) GetProcAddress (hm_advapi32
, "RevertToSelf");
3888 if (s_pfn_Revert_To_Self
== NULL
)
3892 return s_pfn_Revert_To_Self ();
3896 get_process_memory_info (HANDLE h_proc
,
3897 PPROCESS_MEMORY_COUNTERS mem_counters
,
3900 static GetProcessMemoryInfo_Proc s_pfn_Get_Process_Memory_Info
= NULL
;
3901 HMODULE hm_psapi
= NULL
;
3902 if (is_windows_9x () == TRUE
)
3906 if (g_b_init_get_process_memory_info
== 0)
3908 g_b_init_get_process_memory_info
= 1;
3909 hm_psapi
= LoadLibrary ("Psapi.dll");
3911 s_pfn_Get_Process_Memory_Info
= (GetProcessMemoryInfo_Proc
)
3912 GetProcAddress (hm_psapi
, "GetProcessMemoryInfo");
3914 if (s_pfn_Get_Process_Memory_Info
== NULL
)
3918 return s_pfn_Get_Process_Memory_Info (h_proc
, mem_counters
, bufsize
);
3922 get_process_working_set_size (HANDLE h_proc
,
3926 static GetProcessWorkingSetSize_Proc
3927 s_pfn_Get_Process_Working_Set_Size
= NULL
;
3929 if (is_windows_9x () == TRUE
)
3933 if (g_b_init_get_process_working_set_size
== 0)
3935 g_b_init_get_process_working_set_size
= 1;
3936 s_pfn_Get_Process_Working_Set_Size
= (GetProcessWorkingSetSize_Proc
)
3937 GetProcAddress (GetModuleHandle ("kernel32.dll"),
3938 "GetProcessWorkingSetSize");
3940 if (s_pfn_Get_Process_Working_Set_Size
== NULL
)
3944 return s_pfn_Get_Process_Working_Set_Size (h_proc
, minrss
, maxrss
);
3948 global_memory_status (MEMORYSTATUS
*buf
)
3950 static GlobalMemoryStatus_Proc s_pfn_Global_Memory_Status
= NULL
;
3952 if (is_windows_9x () == TRUE
)
3956 if (g_b_init_global_memory_status
== 0)
3958 g_b_init_global_memory_status
= 1;
3959 s_pfn_Global_Memory_Status
= (GlobalMemoryStatus_Proc
)
3960 GetProcAddress (GetModuleHandle ("kernel32.dll"),
3961 "GlobalMemoryStatus");
3963 if (s_pfn_Global_Memory_Status
== NULL
)
3967 return s_pfn_Global_Memory_Status (buf
);
3971 global_memory_status_ex (MEMORY_STATUS_EX
*buf
)
3973 static GlobalMemoryStatusEx_Proc s_pfn_Global_Memory_Status_Ex
= NULL
;
3975 if (is_windows_9x () == TRUE
)
3979 if (g_b_init_global_memory_status_ex
== 0)
3981 g_b_init_global_memory_status_ex
= 1;
3982 s_pfn_Global_Memory_Status_Ex
= (GlobalMemoryStatusEx_Proc
)
3983 GetProcAddress (GetModuleHandle ("kernel32.dll"),
3984 "GlobalMemoryStatusEx");
3986 if (s_pfn_Global_Memory_Status_Ex
== NULL
)
3990 return s_pfn_Global_Memory_Status_Ex (buf
);
3994 list_system_processes (void)
3996 struct gcpro gcpro1
;
3997 Lisp_Object proclist
= Qnil
;
4000 h_snapshot
= create_toolhelp32_snapshot (TH32CS_SNAPPROCESS
, 0);
4002 if (h_snapshot
!= INVALID_HANDLE_VALUE
)
4004 PROCESSENTRY32 proc_entry
;
4010 proc_entry
.dwSize
= sizeof (PROCESSENTRY32
);
4011 for (res
= process32_first (h_snapshot
, &proc_entry
); res
;
4012 res
= process32_next (h_snapshot
, &proc_entry
))
4014 proc_id
= proc_entry
.th32ProcessID
;
4015 proclist
= Fcons (make_fixnum_or_float (proc_id
), proclist
);
4018 CloseHandle (h_snapshot
);
4020 proclist
= Fnreverse (proclist
);
4027 enable_privilege (LPCTSTR priv_name
, BOOL enable_p
, TOKEN_PRIVILEGES
*old_priv
)
4029 TOKEN_PRIVILEGES priv
;
4030 DWORD priv_size
= sizeof (priv
);
4031 DWORD opriv_size
= sizeof (*old_priv
);
4032 HANDLE h_token
= NULL
;
4033 HANDLE h_thread
= GetCurrentThread ();
4037 res
= open_thread_token (h_thread
,
4038 TOKEN_QUERY
| TOKEN_ADJUST_PRIVILEGES
,
4040 if (!res
&& GetLastError () == ERROR_NO_TOKEN
)
4042 if (impersonate_self (SecurityImpersonation
))
4043 res
= open_thread_token (h_thread
,
4044 TOKEN_QUERY
| TOKEN_ADJUST_PRIVILEGES
,
4049 priv
.PrivilegeCount
= 1;
4050 priv
.Privileges
[0].Attributes
= enable_p
? SE_PRIVILEGE_ENABLED
: 0;
4051 LookupPrivilegeValue (NULL
, priv_name
, &priv
.Privileges
[0].Luid
);
4052 if (AdjustTokenPrivileges (h_token
, FALSE
, &priv
, priv_size
,
4053 old_priv
, &opriv_size
)
4054 && GetLastError () != ERROR_NOT_ALL_ASSIGNED
)
4058 CloseHandle (h_token
);
4064 restore_privilege (TOKEN_PRIVILEGES
*priv
)
4066 DWORD priv_size
= sizeof (*priv
);
4067 HANDLE h_token
= NULL
;
4070 if (open_thread_token (GetCurrentThread (),
4071 TOKEN_QUERY
| TOKEN_ADJUST_PRIVILEGES
,
4074 if (AdjustTokenPrivileges (h_token
, FALSE
, priv
, priv_size
, NULL
, NULL
)
4075 && GetLastError () != ERROR_NOT_ALL_ASSIGNED
)
4079 CloseHandle (h_token
);
4085 ltime (ULONGLONG time_100ns
)
4087 ULONGLONG time_sec
= time_100ns
/ 10000000;
4088 int subsec
= time_100ns
% 10000000;
4089 return list4 (make_number (time_sec
>> 16),
4090 make_number (time_sec
& 0xffff),
4091 make_number (subsec
/ 10),
4092 make_number (subsec
% 10 * 100000));
4095 #define U64_TO_LISP_TIME(time) ltime (time)
4098 process_times (HANDLE h_proc
, Lisp_Object
*ctime
, Lisp_Object
*etime
,
4099 Lisp_Object
*stime
, Lisp_Object
*utime
, Lisp_Object
*ttime
,
4102 FILETIME ft_creation
, ft_exit
, ft_kernel
, ft_user
, ft_current
;
4103 ULONGLONG tem1
, tem2
, tem3
, tem
;
4106 || !get_process_times_fn
4107 || !(*get_process_times_fn
) (h_proc
, &ft_creation
, &ft_exit
,
4108 &ft_kernel
, &ft_user
))
4111 GetSystemTimeAsFileTime (&ft_current
);
4113 FILETIME_TO_U64 (tem1
, ft_kernel
);
4114 *stime
= U64_TO_LISP_TIME (tem1
);
4116 FILETIME_TO_U64 (tem2
, ft_user
);
4117 *utime
= U64_TO_LISP_TIME (tem2
);
4120 *ttime
= U64_TO_LISP_TIME (tem3
);
4122 FILETIME_TO_U64 (tem
, ft_creation
);
4123 /* Process no 4 (System) returns zero creation time. */
4126 *ctime
= U64_TO_LISP_TIME (tem
);
4130 FILETIME_TO_U64 (tem3
, ft_current
);
4131 tem
= (tem3
- utc_base
) - tem
;
4133 *etime
= U64_TO_LISP_TIME (tem
);
4137 *pcpu
= 100.0 * (tem1
+ tem2
) / tem
;
4148 system_process_attributes (Lisp_Object pid
)
4150 struct gcpro gcpro1
, gcpro2
, gcpro3
;
4151 Lisp_Object attrs
= Qnil
;
4152 Lisp_Object cmd_str
, decoded_cmd
, tem
;
4153 HANDLE h_snapshot
, h_proc
;
4156 char uname
[UNLEN
+1], gname
[GNLEN
+1], domain
[1025];
4157 DWORD ulength
= sizeof (uname
), dlength
= sizeof (domain
), needed
;
4158 DWORD glength
= sizeof (gname
);
4159 HANDLE token
= NULL
;
4160 SID_NAME_USE user_type
;
4161 unsigned char *buf
= NULL
;
4163 TOKEN_USER user_token
;
4164 TOKEN_PRIMARY_GROUP group_token
;
4167 PROCESS_MEMORY_COUNTERS mem
;
4168 PROCESS_MEMORY_COUNTERS_EX mem_ex
;
4169 DWORD minrss
, maxrss
;
4171 MEMORY_STATUS_EX memstex
;
4172 double totphys
= 0.0;
4173 Lisp_Object ctime
, stime
, utime
, etime
, ttime
;
4175 BOOL result
= FALSE
;
4177 CHECK_NUMBER_OR_FLOAT (pid
);
4178 proc_id
= FLOATP (pid
) ? XFLOAT_DATA (pid
) : XINT (pid
);
4180 h_snapshot
= create_toolhelp32_snapshot (TH32CS_SNAPPROCESS
, 0);
4182 GCPRO3 (attrs
, decoded_cmd
, tem
);
4184 if (h_snapshot
!= INVALID_HANDLE_VALUE
)
4189 pe
.dwSize
= sizeof (PROCESSENTRY32
);
4190 for (res
= process32_first (h_snapshot
, &pe
); res
;
4191 res
= process32_next (h_snapshot
, &pe
))
4193 if (proc_id
== pe
.th32ProcessID
)
4196 decoded_cmd
= build_string ("Idle");
4199 /* Decode the command name from locale-specific
4201 cmd_str
= make_unibyte_string (pe
.szExeFile
,
4202 strlen (pe
.szExeFile
));
4204 code_convert_string_norecord (cmd_str
,
4205 Vlocale_coding_system
, 0);
4207 attrs
= Fcons (Fcons (Qcomm
, decoded_cmd
), attrs
);
4208 attrs
= Fcons (Fcons (Qppid
,
4209 make_fixnum_or_float (pe
.th32ParentProcessID
)),
4211 attrs
= Fcons (Fcons (Qpri
, make_number (pe
.pcPriClassBase
)),
4213 attrs
= Fcons (Fcons (Qthcount
,
4214 make_fixnum_or_float (pe
.cntThreads
)),
4221 CloseHandle (h_snapshot
);
4230 h_proc
= OpenProcess (PROCESS_QUERY_INFORMATION
| PROCESS_VM_READ
,
4232 /* If we were denied a handle to the process, try again after
4233 enabling the SeDebugPrivilege in our process. */
4236 TOKEN_PRIVILEGES priv_current
;
4238 if (enable_privilege (SE_DEBUG_NAME
, TRUE
, &priv_current
))
4240 h_proc
= OpenProcess (PROCESS_QUERY_INFORMATION
| PROCESS_VM_READ
,
4242 restore_privilege (&priv_current
);
4248 result
= open_process_token (h_proc
, TOKEN_QUERY
, &token
);
4251 result
= get_token_information (token
, TokenUser
, NULL
, 0, &blen
);
4252 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
4254 buf
= xmalloc (blen
);
4255 result
= get_token_information (token
, TokenUser
,
4256 (LPVOID
)buf
, blen
, &needed
);
4259 memcpy (&user_token
, buf
, sizeof (user_token
));
4260 if (!w32_cached_id (user_token
.User
.Sid
, &euid
, uname
))
4262 euid
= get_rid (user_token
.User
.Sid
);
4263 result
= lookup_account_sid (NULL
, user_token
.User
.Sid
,
4268 w32_add_to_cache (user_token
.User
.Sid
, euid
, uname
);
4271 strcpy (uname
, "unknown");
4275 ulength
= strlen (uname
);
4281 /* Determine a reasonable euid and gid values. */
4282 if (xstrcasecmp ("administrator", uname
) == 0)
4284 euid
= 500; /* well-known Administrator uid */
4285 egid
= 513; /* well-known None gid */
4289 /* Get group id and name. */
4290 result
= get_token_information (token
, TokenPrimaryGroup
,
4291 (LPVOID
)buf
, blen
, &needed
);
4292 if (!result
&& GetLastError () == ERROR_INSUFFICIENT_BUFFER
)
4294 buf
= xrealloc (buf
, blen
= needed
);
4295 result
= get_token_information (token
, TokenPrimaryGroup
,
4296 (LPVOID
)buf
, blen
, &needed
);
4300 memcpy (&group_token
, buf
, sizeof (group_token
));
4301 if (!w32_cached_id (group_token
.PrimaryGroup
, &egid
, gname
))
4303 egid
= get_rid (group_token
.PrimaryGroup
);
4304 dlength
= sizeof (domain
);
4306 lookup_account_sid (NULL
, group_token
.PrimaryGroup
,
4307 gname
, &glength
, NULL
, &dlength
,
4310 w32_add_to_cache (group_token
.PrimaryGroup
,
4314 strcpy (gname
, "None");
4318 glength
= strlen (gname
);
4326 if (!is_windows_9x ())
4328 /* We couldn't open the process token, presumably because of
4329 insufficient access rights. Assume this process is run
4331 strcpy (uname
, "SYSTEM");
4332 strcpy (gname
, "None");
4333 euid
= 18; /* SYSTEM */
4334 egid
= 513; /* None */
4335 glength
= strlen (gname
);
4336 ulength
= strlen (uname
);
4338 /* If we are running under Windows 9X, where security calls are
4339 not supported, we assume all processes are run by the current
4341 else if (GetUserName (uname
, &ulength
))
4343 if (xstrcasecmp ("administrator", uname
) == 0)
4348 strcpy (gname
, "None");
4349 glength
= strlen (gname
);
4350 ulength
= strlen (uname
);
4356 strcpy (uname
, "administrator");
4357 ulength
= strlen (uname
);
4358 strcpy (gname
, "None");
4359 glength
= strlen (gname
);
4362 CloseHandle (token
);
4365 attrs
= Fcons (Fcons (Qeuid
, make_fixnum_or_float (euid
)), attrs
);
4366 tem
= make_unibyte_string (uname
, ulength
);
4367 attrs
= Fcons (Fcons (Quser
,
4368 code_convert_string_norecord (tem
, Vlocale_coding_system
, 0)),
4370 attrs
= Fcons (Fcons (Qegid
, make_fixnum_or_float (egid
)), attrs
);
4371 tem
= make_unibyte_string (gname
, glength
);
4372 attrs
= Fcons (Fcons (Qgroup
,
4373 code_convert_string_norecord (tem
, Vlocale_coding_system
, 0)),
4376 if (global_memory_status_ex (&memstex
))
4377 #if __GNUC__ || (defined (_MSC_VER) && _MSC_VER >= 1300)
4378 totphys
= memstex
.ullTotalPhys
/ 1024.0;
4380 /* Visual Studio 6 cannot convert an unsigned __int64 type to
4381 double, so we need to do this for it... */
4383 DWORD tot_hi
= memstex
.ullTotalPhys
>> 32;
4384 DWORD tot_md
= (memstex
.ullTotalPhys
& 0x00000000ffffffff) >> 10;
4385 DWORD tot_lo
= memstex
.ullTotalPhys
% 1024;
4387 totphys
= tot_hi
* 4194304.0 + tot_md
+ tot_lo
/ 1024.0;
4389 #endif /* __GNUC__ || _MSC_VER >= 1300 */
4390 else if (global_memory_status (&memst
))
4391 totphys
= memst
.dwTotalPhys
/ 1024.0;
4394 && get_process_memory_info (h_proc
, (PROCESS_MEMORY_COUNTERS
*)&mem_ex
,
4397 DWORD rss
= mem_ex
.WorkingSetSize
/ 1024;
4399 attrs
= Fcons (Fcons (Qmajflt
,
4400 make_fixnum_or_float (mem_ex
.PageFaultCount
)),
4402 attrs
= Fcons (Fcons (Qvsize
,
4403 make_fixnum_or_float (mem_ex
.PrivateUsage
/ 1024)),
4405 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (rss
)), attrs
);
4407 attrs
= Fcons (Fcons (Qpmem
, make_float (100. * rss
/ totphys
)), attrs
);
4410 && get_process_memory_info (h_proc
, &mem
, sizeof (mem
)))
4412 DWORD rss
= mem_ex
.WorkingSetSize
/ 1024;
4414 attrs
= Fcons (Fcons (Qmajflt
,
4415 make_fixnum_or_float (mem
.PageFaultCount
)),
4417 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (rss
)), attrs
);
4419 attrs
= Fcons (Fcons (Qpmem
, make_float (100. * rss
/ totphys
)), attrs
);
4422 && get_process_working_set_size (h_proc
, &minrss
, &maxrss
))
4424 DWORD rss
= maxrss
/ 1024;
4426 attrs
= Fcons (Fcons (Qrss
, make_fixnum_or_float (maxrss
/ 1024)), attrs
);
4428 attrs
= Fcons (Fcons (Qpmem
, make_float (100. * rss
/ totphys
)), attrs
);
4431 if (process_times (h_proc
, &ctime
, &etime
, &stime
, &utime
, &ttime
, &pcpu
))
4433 attrs
= Fcons (Fcons (Qutime
, utime
), attrs
);
4434 attrs
= Fcons (Fcons (Qstime
, stime
), attrs
);
4435 attrs
= Fcons (Fcons (Qtime
, ttime
), attrs
);
4436 attrs
= Fcons (Fcons (Qstart
, ctime
), attrs
);
4437 attrs
= Fcons (Fcons (Qetime
, etime
), attrs
);
4438 attrs
= Fcons (Fcons (Qpcpu
, make_float (pcpu
)), attrs
);
4441 /* FIXME: Retrieve command line by walking the PEB of the process. */
4444 CloseHandle (h_proc
);
4450 /* Wrappers for winsock functions to map between our file descriptors
4451 and winsock's handles; also set h_errno for convenience.
4453 To allow Emacs to run on systems which don't have winsock support
4454 installed, we dynamically link to winsock on startup if present, and
4455 otherwise provide the minimum necessary functionality
4456 (eg. gethostname). */
4458 /* function pointers for relevant socket functions */
4459 int (PASCAL
*pfn_WSAStartup
) (WORD wVersionRequired
, LPWSADATA lpWSAData
);
4460 void (PASCAL
*pfn_WSASetLastError
) (int iError
);
4461 int (PASCAL
*pfn_WSAGetLastError
) (void);
4462 int (PASCAL
*pfn_WSAEventSelect
) (SOCKET s
, HANDLE hEventObject
, long lNetworkEvents
);
4463 HANDLE (PASCAL
*pfn_WSACreateEvent
) (void);
4464 int (PASCAL
*pfn_WSACloseEvent
) (HANDLE hEvent
);
4465 int (PASCAL
*pfn_socket
) (int af
, int type
, int protocol
);
4466 int (PASCAL
*pfn_bind
) (SOCKET s
, const struct sockaddr
*addr
, int namelen
);
4467 int (PASCAL
*pfn_connect
) (SOCKET s
, const struct sockaddr
*addr
, int namelen
);
4468 int (PASCAL
*pfn_ioctlsocket
) (SOCKET s
, long cmd
, u_long
*argp
);
4469 int (PASCAL
*pfn_recv
) (SOCKET s
, char * buf
, int len
, int flags
);
4470 int (PASCAL
*pfn_send
) (SOCKET s
, const char * buf
, int len
, int flags
);
4471 int (PASCAL
*pfn_closesocket
) (SOCKET s
);
4472 int (PASCAL
*pfn_shutdown
) (SOCKET s
, int how
);
4473 int (PASCAL
*pfn_WSACleanup
) (void);
4475 u_short (PASCAL
*pfn_htons
) (u_short hostshort
);
4476 u_short (PASCAL
*pfn_ntohs
) (u_short netshort
);
4477 unsigned long (PASCAL
*pfn_inet_addr
) (const char * cp
);
4478 int (PASCAL
*pfn_gethostname
) (char * name
, int namelen
);
4479 struct hostent
* (PASCAL
*pfn_gethostbyname
) (const char * name
);
4480 struct servent
* (PASCAL
*pfn_getservbyname
) (const char * name
, const char * proto
);
4481 int (PASCAL
*pfn_getpeername
) (SOCKET s
, struct sockaddr
*addr
, int * namelen
);
4482 int (PASCAL
*pfn_setsockopt
) (SOCKET s
, int level
, int optname
,
4483 const char * optval
, int optlen
);
4484 int (PASCAL
*pfn_listen
) (SOCKET s
, int backlog
);
4485 int (PASCAL
*pfn_getsockname
) (SOCKET s
, struct sockaddr
* name
,
4487 SOCKET (PASCAL
*pfn_accept
) (SOCKET s
, struct sockaddr
* addr
, int * addrlen
);
4488 int (PASCAL
*pfn_recvfrom
) (SOCKET s
, char * buf
, int len
, int flags
,
4489 struct sockaddr
* from
, int * fromlen
);
4490 int (PASCAL
*pfn_sendto
) (SOCKET s
, const char * buf
, int len
, int flags
,
4491 const struct sockaddr
* to
, int tolen
);
4493 /* SetHandleInformation is only needed to make sockets non-inheritable. */
4494 BOOL (WINAPI
*pfn_SetHandleInformation
) (HANDLE object
, DWORD mask
, DWORD flags
);
4495 #ifndef HANDLE_FLAG_INHERIT
4496 #define HANDLE_FLAG_INHERIT 1
4500 static int winsock_inuse
;
4505 if (winsock_lib
!= NULL
&& winsock_inuse
== 0)
4507 /* Not sure what would cause WSAENETDOWN, or even if it can happen
4508 after WSAStartup returns successfully, but it seems reasonable
4509 to allow unloading winsock anyway in that case. */
4510 if (pfn_WSACleanup () == 0 ||
4511 pfn_WSAGetLastError () == WSAENETDOWN
)
4513 if (FreeLibrary (winsock_lib
))
4522 init_winsock (int load_now
)
4524 WSADATA winsockData
;
4526 if (winsock_lib
!= NULL
)
4529 pfn_SetHandleInformation
4530 = (void *) GetProcAddress (GetModuleHandle ("kernel32.dll"),
4531 "SetHandleInformation");
4533 winsock_lib
= LoadLibrary ("Ws2_32.dll");
4535 if (winsock_lib
!= NULL
)
4537 /* dynamically link to socket functions */
4539 #define LOAD_PROC(fn) \
4540 if ((pfn_##fn = (void *) GetProcAddress (winsock_lib, #fn)) == NULL) \
4543 LOAD_PROC (WSAStartup
);
4544 LOAD_PROC (WSASetLastError
);
4545 LOAD_PROC (WSAGetLastError
);
4546 LOAD_PROC (WSAEventSelect
);
4547 LOAD_PROC (WSACreateEvent
);
4548 LOAD_PROC (WSACloseEvent
);
4551 LOAD_PROC (connect
);
4552 LOAD_PROC (ioctlsocket
);
4555 LOAD_PROC (closesocket
);
4556 LOAD_PROC (shutdown
);
4559 LOAD_PROC (inet_addr
);
4560 LOAD_PROC (gethostname
);
4561 LOAD_PROC (gethostbyname
);
4562 LOAD_PROC (getservbyname
);
4563 LOAD_PROC (getpeername
);
4564 LOAD_PROC (WSACleanup
);
4565 LOAD_PROC (setsockopt
);
4567 LOAD_PROC (getsockname
);
4569 LOAD_PROC (recvfrom
);
4573 /* specify version 1.1 of winsock */
4574 if (pfn_WSAStartup (0x101, &winsockData
) == 0)
4576 if (winsockData
.wVersion
!= 0x101)
4581 /* Report that winsock exists and is usable, but leave
4582 socket functions disabled. I am assuming that calling
4583 WSAStartup does not require any network interaction,
4584 and in particular does not cause or require a dial-up
4585 connection to be established. */
4588 FreeLibrary (winsock_lib
);
4596 FreeLibrary (winsock_lib
);
4606 /* function to set h_errno for compatibility; map winsock error codes to
4607 normal system codes where they overlap (non-overlapping definitions
4608 are already in <sys/socket.h> */
4612 if (winsock_lib
== NULL
)
4615 h_errno
= pfn_WSAGetLastError ();
4619 case WSAEACCES
: h_errno
= EACCES
; break;
4620 case WSAEBADF
: h_errno
= EBADF
; break;
4621 case WSAEFAULT
: h_errno
= EFAULT
; break;
4622 case WSAEINTR
: h_errno
= EINTR
; break;
4623 case WSAEINVAL
: h_errno
= EINVAL
; break;
4624 case WSAEMFILE
: h_errno
= EMFILE
; break;
4625 case WSAENAMETOOLONG
: h_errno
= ENAMETOOLONG
; break;
4626 case WSAENOTEMPTY
: h_errno
= ENOTEMPTY
; break;
4634 if (h_errno
== 0 && winsock_lib
!= NULL
)
4635 pfn_WSASetLastError (0);
4638 /* Extend strerror to handle the winsock-specific error codes. */
4642 } _wsa_errlist
[] = {
4643 {WSAEINTR
, "Interrupted function call"},
4644 {WSAEBADF
, "Bad file descriptor"},
4645 {WSAEACCES
, "Permission denied"},
4646 {WSAEFAULT
, "Bad address"},
4647 {WSAEINVAL
, "Invalid argument"},
4648 {WSAEMFILE
, "Too many open files"},
4650 {WSAEWOULDBLOCK
, "Resource temporarily unavailable"},
4651 {WSAEINPROGRESS
, "Operation now in progress"},
4652 {WSAEALREADY
, "Operation already in progress"},
4653 {WSAENOTSOCK
, "Socket operation on non-socket"},
4654 {WSAEDESTADDRREQ
, "Destination address required"},
4655 {WSAEMSGSIZE
, "Message too long"},
4656 {WSAEPROTOTYPE
, "Protocol wrong type for socket"},
4657 {WSAENOPROTOOPT
, "Bad protocol option"},
4658 {WSAEPROTONOSUPPORT
, "Protocol not supported"},
4659 {WSAESOCKTNOSUPPORT
, "Socket type not supported"},
4660 {WSAEOPNOTSUPP
, "Operation not supported"},
4661 {WSAEPFNOSUPPORT
, "Protocol family not supported"},
4662 {WSAEAFNOSUPPORT
, "Address family not supported by protocol family"},
4663 {WSAEADDRINUSE
, "Address already in use"},
4664 {WSAEADDRNOTAVAIL
, "Cannot assign requested address"},
4665 {WSAENETDOWN
, "Network is down"},
4666 {WSAENETUNREACH
, "Network is unreachable"},
4667 {WSAENETRESET
, "Network dropped connection on reset"},
4668 {WSAECONNABORTED
, "Software caused connection abort"},
4669 {WSAECONNRESET
, "Connection reset by peer"},
4670 {WSAENOBUFS
, "No buffer space available"},
4671 {WSAEISCONN
, "Socket is already connected"},
4672 {WSAENOTCONN
, "Socket is not connected"},
4673 {WSAESHUTDOWN
, "Cannot send after socket shutdown"},
4674 {WSAETOOMANYREFS
, "Too many references"}, /* not sure */
4675 {WSAETIMEDOUT
, "Connection timed out"},
4676 {WSAECONNREFUSED
, "Connection refused"},
4677 {WSAELOOP
, "Network loop"}, /* not sure */
4678 {WSAENAMETOOLONG
, "Name is too long"},
4679 {WSAEHOSTDOWN
, "Host is down"},
4680 {WSAEHOSTUNREACH
, "No route to host"},
4681 {WSAENOTEMPTY
, "Buffer not empty"}, /* not sure */
4682 {WSAEPROCLIM
, "Too many processes"},
4683 {WSAEUSERS
, "Too many users"}, /* not sure */
4684 {WSAEDQUOT
, "Double quote in host name"}, /* really not sure */
4685 {WSAESTALE
, "Data is stale"}, /* not sure */
4686 {WSAEREMOTE
, "Remote error"}, /* not sure */
4688 {WSASYSNOTREADY
, "Network subsystem is unavailable"},
4689 {WSAVERNOTSUPPORTED
, "WINSOCK.DLL version out of range"},
4690 {WSANOTINITIALISED
, "Winsock not initialized successfully"},
4691 {WSAEDISCON
, "Graceful shutdown in progress"},
4693 {WSAENOMORE
, "No more operations allowed"}, /* not sure */
4694 {WSAECANCELLED
, "Operation cancelled"}, /* not sure */
4695 {WSAEINVALIDPROCTABLE
, "Invalid procedure table from service provider"},
4696 {WSAEINVALIDPROVIDER
, "Invalid service provider version number"},
4697 {WSAEPROVIDERFAILEDINIT
, "Unable to initialize a service provider"},
4698 {WSASYSCALLFAILURE
, "System call failure"},
4699 {WSASERVICE_NOT_FOUND
, "Service not found"}, /* not sure */
4700 {WSATYPE_NOT_FOUND
, "Class type not found"},
4701 {WSA_E_NO_MORE
, "No more resources available"}, /* really not sure */
4702 {WSA_E_CANCELLED
, "Operation already cancelled"}, /* really not sure */
4703 {WSAEREFUSED
, "Operation refused"}, /* not sure */
4706 {WSAHOST_NOT_FOUND
, "Host not found"},
4707 {WSATRY_AGAIN
, "Authoritative host not found during name lookup"},
4708 {WSANO_RECOVERY
, "Non-recoverable error during name lookup"},
4709 {WSANO_DATA
, "Valid name, no data record of requested type"},
4715 sys_strerror (int error_no
)
4718 static char unknown_msg
[40];
4720 if (error_no
>= 0 && error_no
< sys_nerr
)
4721 return sys_errlist
[error_no
];
4723 for (i
= 0; _wsa_errlist
[i
].errnum
>= 0; i
++)
4724 if (_wsa_errlist
[i
].errnum
== error_no
)
4725 return _wsa_errlist
[i
].msg
;
4727 sprintf (unknown_msg
, "Unidentified error: %d", error_no
);
4731 /* [andrewi 3-May-96] I've had conflicting results using both methods,
4732 but I believe the method of keeping the socket handle separate (and
4733 insuring it is not inheritable) is the correct one. */
4735 #define SOCK_HANDLE(fd) ((SOCKET) fd_info[fd].hnd)
4737 static int socket_to_fd (SOCKET s
);
4740 sys_socket (int af
, int type
, int protocol
)
4744 if (winsock_lib
== NULL
)
4747 return INVALID_SOCKET
;
4752 /* call the real socket function */
4753 s
= pfn_socket (af
, type
, protocol
);
4755 if (s
!= INVALID_SOCKET
)
4756 return socket_to_fd (s
);
4762 /* Convert a SOCKET to a file descriptor. */
4764 socket_to_fd (SOCKET s
)
4769 /* Although under NT 3.5 _open_osfhandle will accept a socket
4770 handle, if opened with SO_OPENTYPE == SO_SYNCHRONOUS_NONALERT,
4771 that does not work under NT 3.1. However, we can get the same
4772 effect by using a backdoor function to replace an existing
4773 descriptor handle with the one we want. */
4775 /* allocate a file descriptor (with appropriate flags) */
4776 fd
= _open ("NUL:", _O_RDWR
);
4779 /* Make a non-inheritable copy of the socket handle. Note
4780 that it is possible that sockets aren't actually kernel
4781 handles, which appears to be the case on Windows 9x when
4782 the MS Proxy winsock client is installed. */
4784 /* Apparently there is a bug in NT 3.51 with some service
4785 packs, which prevents using DuplicateHandle to make a
4786 socket handle non-inheritable (causes WSACleanup to
4787 hang). The work-around is to use SetHandleInformation
4788 instead if it is available and implemented. */
4789 if (pfn_SetHandleInformation
)
4791 pfn_SetHandleInformation ((HANDLE
) s
, HANDLE_FLAG_INHERIT
, 0);
4795 HANDLE parent
= GetCurrentProcess ();
4796 HANDLE new_s
= INVALID_HANDLE_VALUE
;
4798 if (DuplicateHandle (parent
,
4804 DUPLICATE_SAME_ACCESS
))
4806 /* It is possible that DuplicateHandle succeeds even
4807 though the socket wasn't really a kernel handle,
4808 because a real handle has the same value. So
4809 test whether the new handle really is a socket. */
4810 long nonblocking
= 0;
4811 if (pfn_ioctlsocket ((SOCKET
) new_s
, FIONBIO
, &nonblocking
) == 0)
4813 pfn_closesocket (s
);
4818 CloseHandle (new_s
);
4823 fd_info
[fd
].hnd
= (HANDLE
) s
;
4825 /* set our own internal flags */
4826 fd_info
[fd
].flags
= FILE_SOCKET
| FILE_BINARY
| FILE_READ
| FILE_WRITE
;
4832 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
4834 /* attach child_process to fd_info */
4835 if (fd_info
[ fd
].cp
!= NULL
)
4837 DebPrint (("sys_socket: fd_info[%d] apparently in use!\n", fd
));
4841 fd_info
[ fd
].cp
= cp
;
4844 winsock_inuse
++; /* count open sockets */
4851 pfn_closesocket (s
);
4857 sys_bind (int s
, const struct sockaddr
* addr
, int namelen
)
4859 if (winsock_lib
== NULL
)
4862 return SOCKET_ERROR
;
4866 if (fd_info
[s
].flags
& FILE_SOCKET
)
4868 int rc
= pfn_bind (SOCK_HANDLE (s
), addr
, namelen
);
4869 if (rc
== SOCKET_ERROR
)
4874 return SOCKET_ERROR
;
4878 sys_connect (int s
, const struct sockaddr
* name
, int namelen
)
4880 if (winsock_lib
== NULL
)
4883 return SOCKET_ERROR
;
4887 if (fd_info
[s
].flags
& FILE_SOCKET
)
4889 int rc
= pfn_connect (SOCK_HANDLE (s
), name
, namelen
);
4890 if (rc
== SOCKET_ERROR
)
4895 return SOCKET_ERROR
;
4899 sys_htons (u_short hostshort
)
4901 return (winsock_lib
!= NULL
) ?
4902 pfn_htons (hostshort
) : hostshort
;
4906 sys_ntohs (u_short netshort
)
4908 return (winsock_lib
!= NULL
) ?
4909 pfn_ntohs (netshort
) : netshort
;
4913 sys_inet_addr (const char * cp
)
4915 return (winsock_lib
!= NULL
) ?
4916 pfn_inet_addr (cp
) : INADDR_NONE
;
4920 sys_gethostname (char * name
, int namelen
)
4922 if (winsock_lib
!= NULL
)
4923 return pfn_gethostname (name
, namelen
);
4925 if (namelen
> MAX_COMPUTERNAME_LENGTH
)
4926 return !GetComputerName (name
, (DWORD
*)&namelen
);
4929 return SOCKET_ERROR
;
4933 sys_gethostbyname (const char * name
)
4935 struct hostent
* host
;
4937 if (winsock_lib
== NULL
)
4944 host
= pfn_gethostbyname (name
);
4951 sys_getservbyname (const char * name
, const char * proto
)
4953 struct servent
* serv
;
4955 if (winsock_lib
== NULL
)
4962 serv
= pfn_getservbyname (name
, proto
);
4969 sys_getpeername (int s
, struct sockaddr
*addr
, int * namelen
)
4971 if (winsock_lib
== NULL
)
4974 return SOCKET_ERROR
;
4978 if (fd_info
[s
].flags
& FILE_SOCKET
)
4980 int rc
= pfn_getpeername (SOCK_HANDLE (s
), addr
, namelen
);
4981 if (rc
== SOCKET_ERROR
)
4986 return SOCKET_ERROR
;
4990 sys_shutdown (int s
, int how
)
4992 if (winsock_lib
== NULL
)
4995 return SOCKET_ERROR
;
4999 if (fd_info
[s
].flags
& FILE_SOCKET
)
5001 int rc
= pfn_shutdown (SOCK_HANDLE (s
), how
);
5002 if (rc
== SOCKET_ERROR
)
5007 return SOCKET_ERROR
;
5011 sys_setsockopt (int s
, int level
, int optname
, const void * optval
, int optlen
)
5013 if (winsock_lib
== NULL
)
5016 return SOCKET_ERROR
;
5020 if (fd_info
[s
].flags
& FILE_SOCKET
)
5022 int rc
= pfn_setsockopt (SOCK_HANDLE (s
), level
, optname
,
5023 (const char *)optval
, optlen
);
5024 if (rc
== SOCKET_ERROR
)
5029 return SOCKET_ERROR
;
5033 sys_listen (int s
, int backlog
)
5035 if (winsock_lib
== NULL
)
5038 return SOCKET_ERROR
;
5042 if (fd_info
[s
].flags
& FILE_SOCKET
)
5044 int rc
= pfn_listen (SOCK_HANDLE (s
), backlog
);
5045 if (rc
== SOCKET_ERROR
)
5048 fd_info
[s
].flags
|= FILE_LISTEN
;
5052 return SOCKET_ERROR
;
5056 sys_getsockname (int s
, struct sockaddr
* name
, int * namelen
)
5058 if (winsock_lib
== NULL
)
5061 return SOCKET_ERROR
;
5065 if (fd_info
[s
].flags
& FILE_SOCKET
)
5067 int rc
= pfn_getsockname (SOCK_HANDLE (s
), name
, namelen
);
5068 if (rc
== SOCKET_ERROR
)
5073 return SOCKET_ERROR
;
5077 sys_accept (int s
, struct sockaddr
* addr
, int * addrlen
)
5079 if (winsock_lib
== NULL
)
5086 if (fd_info
[s
].flags
& FILE_LISTEN
)
5088 SOCKET t
= pfn_accept (SOCK_HANDLE (s
), addr
, addrlen
);
5090 if (t
== INVALID_SOCKET
)
5093 fd
= socket_to_fd (t
);
5095 fd_info
[s
].cp
->status
= STATUS_READ_ACKNOWLEDGED
;
5096 ResetEvent (fd_info
[s
].cp
->char_avail
);
5104 sys_recvfrom (int s
, char * buf
, int len
, int flags
,
5105 struct sockaddr
* from
, int * fromlen
)
5107 if (winsock_lib
== NULL
)
5110 return SOCKET_ERROR
;
5114 if (fd_info
[s
].flags
& FILE_SOCKET
)
5116 int rc
= pfn_recvfrom (SOCK_HANDLE (s
), buf
, len
, flags
, from
, fromlen
);
5117 if (rc
== SOCKET_ERROR
)
5122 return SOCKET_ERROR
;
5126 sys_sendto (int s
, const char * buf
, int len
, int flags
,
5127 const struct sockaddr
* to
, int tolen
)
5129 if (winsock_lib
== NULL
)
5132 return SOCKET_ERROR
;
5136 if (fd_info
[s
].flags
& FILE_SOCKET
)
5138 int rc
= pfn_sendto (SOCK_HANDLE (s
), buf
, len
, flags
, to
, tolen
);
5139 if (rc
== SOCKET_ERROR
)
5144 return SOCKET_ERROR
;
5147 /* Windows does not have an fcntl function. Provide an implementation
5148 solely for making sockets non-blocking. */
5150 fcntl (int s
, int cmd
, int options
)
5152 if (winsock_lib
== NULL
)
5159 if (fd_info
[s
].flags
& FILE_SOCKET
)
5161 if (cmd
== F_SETFL
&& options
== O_NDELAY
)
5163 unsigned long nblock
= 1;
5164 int rc
= pfn_ioctlsocket (SOCK_HANDLE (s
), FIONBIO
, &nblock
);
5165 if (rc
== SOCKET_ERROR
)
5167 /* Keep track of the fact that we set this to non-blocking. */
5168 fd_info
[s
].flags
|= FILE_NDELAY
;
5174 return SOCKET_ERROR
;
5178 return SOCKET_ERROR
;
5182 /* Shadow main io functions: we need to handle pipes and sockets more
5183 intelligently, and implement non-blocking mode as well. */
5196 if (fd
< MAXDESC
&& fd_info
[fd
].cp
)
5198 child_process
* cp
= fd_info
[fd
].cp
;
5200 fd_info
[fd
].cp
= NULL
;
5202 if (CHILD_ACTIVE (cp
))
5204 /* if last descriptor to active child_process then cleanup */
5206 for (i
= 0; i
< MAXDESC
; i
++)
5210 if (fd_info
[i
].cp
== cp
)
5215 if (fd_info
[fd
].flags
& FILE_SOCKET
)
5217 if (winsock_lib
== NULL
) abort ();
5219 pfn_shutdown (SOCK_HANDLE (fd
), 2);
5220 rc
= pfn_closesocket (SOCK_HANDLE (fd
));
5222 winsock_inuse
--; /* count open sockets */
5229 /* Note that sockets do not need special treatment here (at least on
5230 NT and Windows 95 using the standard tcp/ip stacks) - it appears that
5231 closesocket is equivalent to CloseHandle, which is to be expected
5232 because socket handles are fully fledged kernel handles. */
5235 if (rc
== 0 && fd
< MAXDESC
)
5236 fd_info
[fd
].flags
= 0;
5247 if (new_fd
>= 0 && new_fd
< MAXDESC
)
5249 /* duplicate our internal info as well */
5250 fd_info
[new_fd
] = fd_info
[fd
];
5256 sys_dup2 (int src
, int dst
)
5260 if (dst
< 0 || dst
>= MAXDESC
)
5266 /* make sure we close the destination first if it's a pipe or socket */
5267 if (src
!= dst
&& fd_info
[dst
].flags
!= 0)
5270 rc
= _dup2 (src
, dst
);
5273 /* duplicate our internal info as well */
5274 fd_info
[dst
] = fd_info
[src
];
5279 /* Unix pipe() has only one arg */
5281 sys_pipe (int * phandles
)
5286 /* make pipe handles non-inheritable; when we spawn a child, we
5287 replace the relevant handle with an inheritable one. Also put
5288 pipes into binary mode; we will do text mode translation ourselves
5290 rc
= _pipe (phandles
, 0, _O_NOINHERIT
| _O_BINARY
);
5294 /* Protect against overflow, since Windows can open more handles than
5295 our fd_info array has room for. */
5296 if (phandles
[0] >= MAXDESC
|| phandles
[1] >= MAXDESC
)
5298 _close (phandles
[0]);
5299 _close (phandles
[1]);
5304 flags
= FILE_PIPE
| FILE_READ
| FILE_BINARY
;
5305 fd_info
[phandles
[0]].flags
= flags
;
5307 flags
= FILE_PIPE
| FILE_WRITE
| FILE_BINARY
;
5308 fd_info
[phandles
[1]].flags
= flags
;
5315 /* Function to do blocking read of one byte, needed to implement
5316 select. It is only allowed on sockets and pipes. */
5318 _sys_read_ahead (int fd
)
5323 if (fd
< 0 || fd
>= MAXDESC
)
5324 return STATUS_READ_ERROR
;
5326 cp
= fd_info
[fd
].cp
;
5328 if (cp
== NULL
|| cp
->fd
!= fd
|| cp
->status
!= STATUS_READ_READY
)
5329 return STATUS_READ_ERROR
;
5331 if ((fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SERIAL
| FILE_SOCKET
)) == 0
5332 || (fd_info
[fd
].flags
& FILE_READ
) == 0)
5334 DebPrint (("_sys_read_ahead: internal error: fd %d is not a pipe, serial port, or socket!\n", fd
));
5338 cp
->status
= STATUS_READ_IN_PROGRESS
;
5340 if (fd_info
[fd
].flags
& FILE_PIPE
)
5342 rc
= _read (fd
, &cp
->chr
, sizeof (char));
5344 /* Give subprocess time to buffer some more output for us before
5345 reporting that input is available; we need this because Windows 95
5346 connects DOS programs to pipes by making the pipe appear to be
5347 the normal console stdout - as a result most DOS programs will
5348 write to stdout without buffering, ie. one character at a
5349 time. Even some W32 programs do this - "dir" in a command
5350 shell on NT is very slow if we don't do this. */
5353 int wait
= w32_pipe_read_delay
;
5359 /* Yield remainder of our time slice, effectively giving a
5360 temporary priority boost to the child process. */
5364 else if (fd_info
[fd
].flags
& FILE_SERIAL
)
5366 HANDLE hnd
= fd_info
[fd
].hnd
;
5367 OVERLAPPED
*ovl
= &fd_info
[fd
].cp
->ovl_read
;
5370 /* Configure timeouts for blocking read. */
5371 if (!GetCommTimeouts (hnd
, &ct
))
5372 return STATUS_READ_ERROR
;
5373 ct
.ReadIntervalTimeout
= 0;
5374 ct
.ReadTotalTimeoutMultiplier
= 0;
5375 ct
.ReadTotalTimeoutConstant
= 0;
5376 if (!SetCommTimeouts (hnd
, &ct
))
5377 return STATUS_READ_ERROR
;
5379 if (!ReadFile (hnd
, &cp
->chr
, sizeof (char), (DWORD
*) &rc
, ovl
))
5381 if (GetLastError () != ERROR_IO_PENDING
)
5382 return STATUS_READ_ERROR
;
5383 if (!GetOverlappedResult (hnd
, ovl
, (DWORD
*) &rc
, TRUE
))
5384 return STATUS_READ_ERROR
;
5387 else if (fd_info
[fd
].flags
& FILE_SOCKET
)
5389 unsigned long nblock
= 0;
5390 /* We always want this to block, so temporarily disable NDELAY. */
5391 if (fd_info
[fd
].flags
& FILE_NDELAY
)
5392 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
5394 rc
= pfn_recv (SOCK_HANDLE (fd
), &cp
->chr
, sizeof (char), 0);
5396 if (fd_info
[fd
].flags
& FILE_NDELAY
)
5399 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
5403 if (rc
== sizeof (char))
5404 cp
->status
= STATUS_READ_SUCCEEDED
;
5406 cp
->status
= STATUS_READ_FAILED
;
5412 _sys_wait_accept (int fd
)
5418 if (fd
< 0 || fd
>= MAXDESC
)
5419 return STATUS_READ_ERROR
;
5421 cp
= fd_info
[fd
].cp
;
5423 if (cp
== NULL
|| cp
->fd
!= fd
|| cp
->status
!= STATUS_READ_READY
)
5424 return STATUS_READ_ERROR
;
5426 cp
->status
= STATUS_READ_FAILED
;
5428 hEv
= pfn_WSACreateEvent ();
5429 rc
= pfn_WSAEventSelect (SOCK_HANDLE (fd
), hEv
, FD_ACCEPT
);
5430 if (rc
!= SOCKET_ERROR
)
5432 rc
= WaitForSingleObject (hEv
, INFINITE
);
5433 pfn_WSAEventSelect (SOCK_HANDLE (fd
), NULL
, 0);
5434 if (rc
== WAIT_OBJECT_0
)
5435 cp
->status
= STATUS_READ_SUCCEEDED
;
5437 pfn_WSACloseEvent (hEv
);
5443 sys_read (int fd
, char * buffer
, unsigned int count
)
5448 char * orig_buffer
= buffer
;
5456 if (fd
< MAXDESC
&& fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
| FILE_SERIAL
))
5458 child_process
*cp
= fd_info
[fd
].cp
;
5460 if ((fd_info
[fd
].flags
& FILE_READ
) == 0)
5468 /* re-read CR carried over from last read */
5469 if (fd_info
[fd
].flags
& FILE_LAST_CR
)
5471 if (fd_info
[fd
].flags
& FILE_BINARY
) abort ();
5475 fd_info
[fd
].flags
&= ~FILE_LAST_CR
;
5478 /* presence of a child_process structure means we are operating in
5479 non-blocking mode - otherwise we just call _read directly.
5480 Note that the child_process structure might be missing because
5481 reap_subprocess has been called; in this case the pipe is
5482 already broken, so calling _read on it is okay. */
5485 int current_status
= cp
->status
;
5487 switch (current_status
)
5489 case STATUS_READ_FAILED
:
5490 case STATUS_READ_ERROR
:
5491 /* report normal EOF if nothing in buffer */
5493 fd_info
[fd
].flags
|= FILE_AT_EOF
;
5496 case STATUS_READ_READY
:
5497 case STATUS_READ_IN_PROGRESS
:
5498 DebPrint (("sys_read called when read is in progress\n"));
5499 errno
= EWOULDBLOCK
;
5502 case STATUS_READ_SUCCEEDED
:
5503 /* consume read-ahead char */
5504 *buffer
++ = cp
->chr
;
5507 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
5508 ResetEvent (cp
->char_avail
);
5510 case STATUS_READ_ACKNOWLEDGED
:
5514 DebPrint (("sys_read: bad status %d\n", current_status
));
5519 if (fd_info
[fd
].flags
& FILE_PIPE
)
5521 PeekNamedPipe ((HANDLE
) _get_osfhandle (fd
), NULL
, 0, NULL
, &waiting
, NULL
);
5522 to_read
= min (waiting
, (DWORD
) count
);
5525 nchars
+= _read (fd
, buffer
, to_read
);
5527 else if (fd_info
[fd
].flags
& FILE_SERIAL
)
5529 HANDLE hnd
= fd_info
[fd
].hnd
;
5530 OVERLAPPED
*ovl
= &fd_info
[fd
].cp
->ovl_read
;
5536 /* Configure timeouts for non-blocking read. */
5537 if (!GetCommTimeouts (hnd
, &ct
))
5542 ct
.ReadIntervalTimeout
= MAXDWORD
;
5543 ct
.ReadTotalTimeoutMultiplier
= 0;
5544 ct
.ReadTotalTimeoutConstant
= 0;
5545 if (!SetCommTimeouts (hnd
, &ct
))
5551 if (!ResetEvent (ovl
->hEvent
))
5556 if (!ReadFile (hnd
, buffer
, count
, (DWORD
*) &rc
, ovl
))
5558 if (GetLastError () != ERROR_IO_PENDING
)
5563 if (!GetOverlappedResult (hnd
, ovl
, (DWORD
*) &rc
, TRUE
))
5572 else /* FILE_SOCKET */
5574 if (winsock_lib
== NULL
) abort ();
5576 /* do the equivalent of a non-blocking read */
5577 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONREAD
, &waiting
);
5578 if (waiting
== 0 && nchars
== 0)
5580 h_errno
= errno
= EWOULDBLOCK
;
5586 /* always use binary mode for sockets */
5587 int res
= pfn_recv (SOCK_HANDLE (fd
), buffer
, count
, 0);
5588 if (res
== SOCKET_ERROR
)
5590 DebPrint (("sys_read.recv failed with error %d on socket %ld\n",
5591 pfn_WSAGetLastError (), SOCK_HANDLE (fd
)));
5601 int nread
= _read (fd
, buffer
, count
);
5604 else if (nchars
== 0)
5609 fd_info
[fd
].flags
|= FILE_AT_EOF
;
5610 /* Perform text mode translation if required. */
5611 else if ((fd_info
[fd
].flags
& FILE_BINARY
) == 0)
5613 nchars
= crlf_to_lf (nchars
, orig_buffer
);
5614 /* If buffer contains only CR, return that. To be absolutely
5615 sure we should attempt to read the next char, but in
5616 practice a CR to be followed by LF would not appear by
5617 itself in the buffer. */
5618 if (nchars
> 1 && orig_buffer
[nchars
- 1] == 0x0d)
5620 fd_info
[fd
].flags
|= FILE_LAST_CR
;
5626 nchars
= _read (fd
, buffer
, count
);
5631 /* From w32xfns.c */
5632 extern HANDLE interrupt_handle
;
5634 /* For now, don't bother with a non-blocking mode */
5636 sys_write (int fd
, const void * buffer
, unsigned int count
)
5646 if (fd
< MAXDESC
&& fd_info
[fd
].flags
& (FILE_PIPE
| FILE_SOCKET
| FILE_SERIAL
))
5648 if ((fd_info
[fd
].flags
& FILE_WRITE
) == 0)
5654 /* Perform text mode translation if required. */
5655 if ((fd_info
[fd
].flags
& FILE_BINARY
) == 0)
5657 char * tmpbuf
= alloca (count
* 2);
5658 unsigned char * src
= (void *)buffer
;
5659 unsigned char * dst
= tmpbuf
;
5664 unsigned char *next
;
5665 /* copy next line or remaining bytes */
5666 next
= _memccpy (dst
, src
, '\n', nbytes
);
5669 /* copied one line ending with '\n' */
5670 int copied
= next
- dst
;
5673 /* insert '\r' before '\n' */
5680 /* copied remaining partial line -> now finished */
5687 if (fd
< MAXDESC
&& fd_info
[fd
].flags
& FILE_SERIAL
)
5689 HANDLE hnd
= (HANDLE
) _get_osfhandle (fd
);
5690 OVERLAPPED
*ovl
= &fd_info
[fd
].cp
->ovl_write
;
5691 HANDLE wait_hnd
[2] = { interrupt_handle
, ovl
->hEvent
};
5694 if (!WriteFile (hnd
, buffer
, count
, (DWORD
*) &nchars
, ovl
))
5696 if (GetLastError () != ERROR_IO_PENDING
)
5701 if (detect_input_pending ())
5702 active
= MsgWaitForMultipleObjects (2, wait_hnd
, FALSE
, INFINITE
,
5705 active
= WaitForMultipleObjects (2, wait_hnd
, FALSE
, INFINITE
);
5706 if (active
== WAIT_OBJECT_0
)
5707 { /* User pressed C-g, cancel write, then leave. Don't bother
5708 cleaning up as we may only get stuck in buggy drivers. */
5709 PurgeComm (hnd
, PURGE_TXABORT
| PURGE_TXCLEAR
);
5714 if (active
== WAIT_OBJECT_0
+ 1
5715 && !GetOverlappedResult (hnd
, ovl
, (DWORD
*) &nchars
, TRUE
))
5722 else if (fd
< MAXDESC
&& fd_info
[fd
].flags
& FILE_SOCKET
)
5724 unsigned long nblock
= 0;
5725 if (winsock_lib
== NULL
) abort ();
5727 /* TODO: implement select() properly so non-blocking I/O works. */
5728 /* For now, make sure the write blocks. */
5729 if (fd_info
[fd
].flags
& FILE_NDELAY
)
5730 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
5732 nchars
= pfn_send (SOCK_HANDLE (fd
), buffer
, count
, 0);
5734 /* Set the socket back to non-blocking if it was before,
5735 for other operations that support it. */
5736 if (fd_info
[fd
].flags
& FILE_NDELAY
)
5739 pfn_ioctlsocket (SOCK_HANDLE (fd
), FIONBIO
, &nblock
);
5742 if (nchars
== SOCKET_ERROR
)
5744 DebPrint (("sys_write.send failed with error %d on socket %ld\n",
5745 pfn_WSAGetLastError (), SOCK_HANDLE (fd
)));
5751 /* Some networked filesystems don't like too large writes, so
5752 break them into smaller chunks. See the Comments section of
5753 the MSDN documentation of WriteFile for details behind the
5754 choice of the value of CHUNK below. See also the thread
5755 http://thread.gmane.org/gmane.comp.version-control.git/145294
5756 in the git mailing list. */
5757 const unsigned char *p
= buffer
;
5758 const unsigned chunk
= 30 * 1024 * 1024;
5763 unsigned this_chunk
= count
< chunk
? count
: chunk
;
5764 int n
= _write (fd
, p
, this_chunk
);
5772 else if (n
< this_chunk
)
5782 /* The Windows CRT functions are "optimized for speed", so they don't
5783 check for timezone and DST changes if they were last called less
5784 than 1 minute ago (see http://support.microsoft.com/kb/821231). So
5785 all Emacs features that repeatedly call time functions (e.g.,
5786 display-time) are in real danger of missing timezone and DST
5787 changes. Calling tzset before each localtime call fixes that. */
5789 sys_localtime (const time_t *t
)
5792 return localtime (t
);
5797 /* Delayed loading of libraries. */
5799 Lisp_Object Vlibrary_cache
;
5801 /* The argument LIBRARIES is an alist that associates a symbol
5802 LIBRARY_ID, identifying an external DLL library known to Emacs, to
5803 a list of filenames under which the library is usually found. In
5804 most cases, the argument passed as LIBRARIES is the variable
5805 `dynamic-library-alist', which is initialized to a list of common
5806 library names. If the function loads the library successfully, it
5807 returns the handle of the DLL, and records the filename in the
5808 property :loaded-from of LIBRARY_ID; it returns NULL if the library
5809 could not be found, or when it was already loaded (because the
5810 handle is not recorded anywhere, and so is lost after use). It
5811 would be trivial to save the handle too in :loaded-from, but
5812 currently there's no use case for it. */
5814 w32_delayed_load (Lisp_Object libraries
, Lisp_Object library_id
)
5816 HMODULE library_dll
= NULL
;
5818 CHECK_SYMBOL (library_id
);
5820 if (CONSP (libraries
) && NILP (Fassq (library_id
, Vlibrary_cache
)))
5822 Lisp_Object found
= Qnil
;
5823 Lisp_Object dlls
= Fassq (library_id
, libraries
);
5826 for (dlls
= XCDR (dlls
); CONSP (dlls
); dlls
= XCDR (dlls
))
5828 CHECK_STRING_CAR (dlls
);
5829 if ((library_dll
= LoadLibrary (SDATA (XCAR (dlls
)))))
5831 char name
[MAX_PATH
];
5834 len
= GetModuleFileNameA (library_dll
, name
, sizeof (name
));
5835 found
= Fcons (XCAR (dlls
),
5837 /* Possibly truncated */
5838 ? make_specified_string (name
, -1, len
, 1)
5844 Fput (library_id
, QCloaded_from
, found
);
5852 check_windows_init_file (void)
5854 /* A common indication that Emacs is not installed properly is when
5855 it cannot find the Windows installation file. If this file does
5856 not exist in the expected place, tell the user. */
5858 if (!noninteractive
&& !inhibit_window_system
5859 /* Vload_path is not yet initialized when we are loading
5861 && NILP (Vpurify_flag
))
5863 Lisp_Object objs
[2];
5864 Lisp_Object full_load_path
;
5865 Lisp_Object init_file
;
5868 objs
[0] = Vload_path
;
5869 objs
[1] = decode_env_path (0, (getenv ("EMACSLOADPATH")));
5870 full_load_path
= Fappend (2, objs
);
5871 init_file
= build_string ("term/w32-win");
5872 fd
= openp (full_load_path
, init_file
, Fget_load_suffixes (), NULL
, Qnil
);
5875 Lisp_Object load_path_print
= Fprin1_to_string (full_load_path
, Qnil
);
5876 char *init_file_name
= SDATA (init_file
);
5877 char *load_path
= SDATA (load_path_print
);
5878 char *buffer
= alloca (1024
5879 + strlen (init_file_name
)
5880 + strlen (load_path
));
5883 "The Emacs Windows initialization file \"%s.el\" "
5884 "could not be found in your Emacs installation. "
5885 "Emacs checked the following directories for this file:\n"
5887 "When Emacs cannot find this file, it usually means that it "
5888 "was not installed properly, or its distribution file was "
5889 "not unpacked properly.\nSee the README.W32 file in the "
5890 "top-level Emacs directory for more information.",
5891 init_file_name
, load_path
);
5894 "Emacs Abort Dialog",
5895 MB_OK
| MB_ICONEXCLAMATION
| MB_TASKMODAL
);
5896 /* Use the low-level Emacs abort. */
5910 /* shutdown the socket interface if necessary */
5919 /* Initialize the socket interface now if available and requested by
5920 the user by defining PRELOAD_WINSOCK; otherwise loading will be
5921 delayed until open-network-stream is called (w32-has-winsock can
5922 also be used to dynamically load or reload winsock).
5924 Conveniently, init_environment is called before us, so
5925 PRELOAD_WINSOCK can be set in the registry. */
5927 /* Always initialize this correctly. */
5930 if (getenv ("PRELOAD_WINSOCK") != NULL
)
5931 init_winsock (TRUE
);
5933 /* Initial preparation for subprocess support: replace our standard
5934 handles with non-inheritable versions. */
5937 HANDLE stdin_save
= INVALID_HANDLE_VALUE
;
5938 HANDLE stdout_save
= INVALID_HANDLE_VALUE
;
5939 HANDLE stderr_save
= INVALID_HANDLE_VALUE
;
5941 parent
= GetCurrentProcess ();
5943 /* ignore errors when duplicating and closing; typically the
5944 handles will be invalid when running as a gui program. */
5945 DuplicateHandle (parent
,
5946 GetStdHandle (STD_INPUT_HANDLE
),
5951 DUPLICATE_SAME_ACCESS
);
5953 DuplicateHandle (parent
,
5954 GetStdHandle (STD_OUTPUT_HANDLE
),
5959 DUPLICATE_SAME_ACCESS
);
5961 DuplicateHandle (parent
,
5962 GetStdHandle (STD_ERROR_HANDLE
),
5967 DUPLICATE_SAME_ACCESS
);
5973 if (stdin_save
!= INVALID_HANDLE_VALUE
)
5974 _open_osfhandle ((long) stdin_save
, O_TEXT
);
5976 _open ("nul", O_TEXT
| O_NOINHERIT
| O_RDONLY
);
5979 if (stdout_save
!= INVALID_HANDLE_VALUE
)
5980 _open_osfhandle ((long) stdout_save
, O_TEXT
);
5982 _open ("nul", O_TEXT
| O_NOINHERIT
| O_WRONLY
);
5985 if (stderr_save
!= INVALID_HANDLE_VALUE
)
5986 _open_osfhandle ((long) stderr_save
, O_TEXT
);
5988 _open ("nul", O_TEXT
| O_NOINHERIT
| O_WRONLY
);
5992 /* unfortunately, atexit depends on implementation of malloc */
5993 /* atexit (term_ntproc); */
5994 signal (SIGABRT
, term_ntproc
);
5996 /* determine which drives are fixed, for GetCachedVolumeInformation */
5998 /* GetDriveType must have trailing backslash. */
5999 char drive
[] = "A:\\";
6001 /* Loop over all possible drive letters */
6002 while (*drive
<= 'Z')
6004 /* Record if this drive letter refers to a fixed drive. */
6005 fixed_drives
[DRIVE_INDEX (*drive
)] =
6006 (GetDriveType (drive
) == DRIVE_FIXED
);
6011 /* Reset the volume info cache. */
6012 volume_cache
= NULL
;
6015 /* Check to see if Emacs has been installed correctly. */
6016 check_windows_init_file ();
6020 shutdown_handler ensures that buffers' autosave files are
6021 up to date when the user logs off, or the system shuts down.
6024 shutdown_handler (DWORD type
)
6026 /* Ctrl-C and Ctrl-Break are already suppressed, so don't handle them. */
6027 if (type
== CTRL_CLOSE_EVENT
/* User closes console window. */
6028 || type
== CTRL_LOGOFF_EVENT
/* User logs off. */
6029 || type
== CTRL_SHUTDOWN_EVENT
) /* User shutsdown. */
6031 /* Shut down cleanly, making sure autosave files are up to date. */
6032 shut_down_emacs (0, 0, Qnil
);
6035 /* Allow other handlers to handle this signal. */
6040 globals_of_w32 is used to initialize those global variables that
6041 must always be initialized on startup even when the global variable
6042 initialized is non zero (see the function main in emacs.c).
6045 globals_of_w32 (void)
6047 HMODULE kernel32
= GetModuleHandle ("kernel32.dll");
6049 get_process_times_fn
= (GetProcessTimes_Proc
)
6050 GetProcAddress (kernel32
, "GetProcessTimes");
6052 DEFSYM (QCloaded_from
, ":loaded-from");
6054 Vlibrary_cache
= Qnil
;
6055 staticpro (&Vlibrary_cache
);
6057 g_b_init_is_windows_9x
= 0;
6058 g_b_init_open_process_token
= 0;
6059 g_b_init_get_token_information
= 0;
6060 g_b_init_lookup_account_sid
= 0;
6061 g_b_init_get_sid_sub_authority
= 0;
6062 g_b_init_get_sid_sub_authority_count
= 0;
6063 g_b_init_get_file_security
= 0;
6064 g_b_init_get_security_descriptor_owner
= 0;
6065 g_b_init_get_security_descriptor_group
= 0;
6066 g_b_init_is_valid_sid
= 0;
6067 g_b_init_create_toolhelp32_snapshot
= 0;
6068 g_b_init_process32_first
= 0;
6069 g_b_init_process32_next
= 0;
6070 g_b_init_open_thread_token
= 0;
6071 g_b_init_impersonate_self
= 0;
6072 g_b_init_revert_to_self
= 0;
6073 g_b_init_get_process_memory_info
= 0;
6074 g_b_init_get_process_working_set_size
= 0;
6075 g_b_init_global_memory_status
= 0;
6076 g_b_init_global_memory_status_ex
= 0;
6077 g_b_init_equal_sid
= 0;
6078 g_b_init_copy_sid
= 0;
6079 g_b_init_get_length_sid
= 0;
6080 g_b_init_get_native_system_info
= 0;
6081 g_b_init_get_system_times
= 0;
6082 num_of_processors
= 0;
6083 /* The following sets a handler for shutdown notifications for
6084 console apps. This actually applies to Emacs in both console and
6085 GUI modes, since we had to fool windows into thinking emacs is a
6086 console application to get console mode to work. */
6087 SetConsoleCtrlHandler (shutdown_handler
, TRUE
);
6089 /* "None" is the default group name on standalone workstations. */
6090 strcpy (dflt_group_name
, "None");
6093 /* For make-serial-process */
6095 serial_open (char *port
)
6101 hnd
= CreateFile (port
, GENERIC_READ
| GENERIC_WRITE
, 0, 0,
6102 OPEN_EXISTING
, FILE_FLAG_OVERLAPPED
, 0);
6103 if (hnd
== INVALID_HANDLE_VALUE
)
6104 error ("Could not open %s", port
);
6105 fd
= (int) _open_osfhandle ((int) hnd
, 0);
6107 error ("Could not open %s", port
);
6111 error ("Could not create child process");
6113 cp
->status
= STATUS_READ_ACKNOWLEDGED
;
6114 fd_info
[ fd
].hnd
= hnd
;
6115 fd_info
[ fd
].flags
|=
6116 FILE_READ
| FILE_WRITE
| FILE_BINARY
| FILE_SERIAL
;
6117 if (fd_info
[ fd
].cp
!= NULL
)
6119 error ("fd_info[fd = %d] is already in use", fd
);
6121 fd_info
[ fd
].cp
= cp
;
6122 cp
->ovl_read
.hEvent
= CreateEvent (NULL
, TRUE
, FALSE
, NULL
);
6123 if (cp
->ovl_read
.hEvent
== NULL
)
6124 error ("Could not create read event");
6125 cp
->ovl_write
.hEvent
= CreateEvent (NULL
, TRUE
, FALSE
, NULL
);
6126 if (cp
->ovl_write
.hEvent
== NULL
)
6127 error ("Could not create write event");
6132 /* For serial-process-configure */
6134 serial_configure (struct Lisp_Process
*p
, Lisp_Object contact
)
6136 Lisp_Object childp2
= Qnil
;
6137 Lisp_Object tem
= Qnil
;
6141 char summary
[4] = "???"; /* This usually becomes "8N1". */
6143 if ((fd_info
[ p
->outfd
].flags
& FILE_SERIAL
) == 0)
6144 error ("Not a serial process");
6145 hnd
= fd_info
[ p
->outfd
].hnd
;
6147 childp2
= Fcopy_sequence (p
->childp
);
6149 /* Initialize timeouts for blocking read and blocking write. */
6150 if (!GetCommTimeouts (hnd
, &ct
))
6151 error ("GetCommTimeouts() failed");
6152 ct
.ReadIntervalTimeout
= 0;
6153 ct
.ReadTotalTimeoutMultiplier
= 0;
6154 ct
.ReadTotalTimeoutConstant
= 0;
6155 ct
.WriteTotalTimeoutMultiplier
= 0;
6156 ct
.WriteTotalTimeoutConstant
= 0;
6157 if (!SetCommTimeouts (hnd
, &ct
))
6158 error ("SetCommTimeouts() failed");
6159 /* Read port attributes and prepare default configuration. */
6160 memset (&dcb
, 0, sizeof (dcb
));
6161 dcb
.DCBlength
= sizeof (DCB
);
6162 if (!GetCommState (hnd
, &dcb
))
6163 error ("GetCommState() failed");
6166 dcb
.fAbortOnError
= FALSE
;
6167 /* dcb.XonLim and dcb.XoffLim are set by GetCommState() */
6172 /* Configure speed. */
6173 if (!NILP (Fplist_member (contact
, QCspeed
)))
6174 tem
= Fplist_get (contact
, QCspeed
);
6176 tem
= Fplist_get (p
->childp
, QCspeed
);
6178 dcb
.BaudRate
= XINT (tem
);
6179 childp2
= Fplist_put (childp2
, QCspeed
, tem
);
6181 /* Configure bytesize. */
6182 if (!NILP (Fplist_member (contact
, QCbytesize
)))
6183 tem
= Fplist_get (contact
, QCbytesize
);
6185 tem
= Fplist_get (p
->childp
, QCbytesize
);
6187 tem
= make_number (8);
6189 if (XINT (tem
) != 7 && XINT (tem
) != 8)
6190 error (":bytesize must be nil (8), 7, or 8");
6191 dcb
.ByteSize
= XINT (tem
);
6192 summary
[0] = XINT (tem
) + '0';
6193 childp2
= Fplist_put (childp2
, QCbytesize
, tem
);
6195 /* Configure parity. */
6196 if (!NILP (Fplist_member (contact
, QCparity
)))
6197 tem
= Fplist_get (contact
, QCparity
);
6199 tem
= Fplist_get (p
->childp
, QCparity
);
6200 if (!NILP (tem
) && !EQ (tem
, Qeven
) && !EQ (tem
, Qodd
))
6201 error (":parity must be nil (no parity), `even', or `odd'");
6202 dcb
.fParity
= FALSE
;
6203 dcb
.Parity
= NOPARITY
;
6204 dcb
.fErrorChar
= FALSE
;
6209 else if (EQ (tem
, Qeven
))
6213 dcb
.Parity
= EVENPARITY
;
6214 dcb
.fErrorChar
= TRUE
;
6216 else if (EQ (tem
, Qodd
))
6220 dcb
.Parity
= ODDPARITY
;
6221 dcb
.fErrorChar
= TRUE
;
6223 childp2
= Fplist_put (childp2
, QCparity
, tem
);
6225 /* Configure stopbits. */
6226 if (!NILP (Fplist_member (contact
, QCstopbits
)))
6227 tem
= Fplist_get (contact
, QCstopbits
);
6229 tem
= Fplist_get (p
->childp
, QCstopbits
);
6231 tem
= make_number (1);
6233 if (XINT (tem
) != 1 && XINT (tem
) != 2)
6234 error (":stopbits must be nil (1 stopbit), 1, or 2");
6235 summary
[2] = XINT (tem
) + '0';
6236 if (XINT (tem
) == 1)
6237 dcb
.StopBits
= ONESTOPBIT
;
6238 else if (XINT (tem
) == 2)
6239 dcb
.StopBits
= TWOSTOPBITS
;
6240 childp2
= Fplist_put (childp2
, QCstopbits
, tem
);
6242 /* Configure flowcontrol. */
6243 if (!NILP (Fplist_member (contact
, QCflowcontrol
)))
6244 tem
= Fplist_get (contact
, QCflowcontrol
);
6246 tem
= Fplist_get (p
->childp
, QCflowcontrol
);
6247 if (!NILP (tem
) && !EQ (tem
, Qhw
) && !EQ (tem
, Qsw
))
6248 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
6249 dcb
.fOutxCtsFlow
= FALSE
;
6250 dcb
.fOutxDsrFlow
= FALSE
;
6251 dcb
.fDtrControl
= DTR_CONTROL_DISABLE
;
6252 dcb
.fDsrSensitivity
= FALSE
;
6253 dcb
.fTXContinueOnXoff
= FALSE
;
6256 dcb
.fRtsControl
= RTS_CONTROL_DISABLE
;
6257 dcb
.XonChar
= 17; /* Control-Q */
6258 dcb
.XoffChar
= 19; /* Control-S */
6261 /* Already configured. */
6263 else if (EQ (tem
, Qhw
))
6265 dcb
.fRtsControl
= RTS_CONTROL_HANDSHAKE
;
6266 dcb
.fOutxCtsFlow
= TRUE
;
6268 else if (EQ (tem
, Qsw
))
6273 childp2
= Fplist_put (childp2
, QCflowcontrol
, tem
);
6275 /* Activate configuration. */
6276 if (!SetCommState (hnd
, &dcb
))
6277 error ("SetCommState() failed");
6279 childp2
= Fplist_put (childp2
, QCsummary
, build_string (summary
));
6280 p
->childp
= childp2
;
6286 emacs_gnutls_pull (gnutls_transport_ptr_t p
, void* buf
, size_t sz
)
6290 struct timeval timeout
;
6291 struct Lisp_Process
*process
= (struct Lisp_Process
*)p
;
6292 int fd
= process
->infd
;
6296 n
= sys_read (fd
, (char*)buf
, sz
);
6303 if (err
== EWOULDBLOCK
)
6305 /* Set a small timeout. */
6307 timeout
.tv_usec
= 0;
6309 FD_SET ((int)fd
, &fdset
);
6311 /* Use select with the timeout to poll the selector. */
6312 sc
= select (fd
+ 1, &fdset
, (SELECT_TYPE
*)0, (SELECT_TYPE
*)0,
6316 continue; /* Try again. */
6318 /* Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN.
6319 Also accept select return 0 as an indicator to EAGAIN. */
6320 if (sc
== 0 || errno
== EWOULDBLOCK
)
6323 err
= errno
; /* Other errors are just passed on. */
6326 emacs_gnutls_transport_set_errno (process
->gnutls_state
, err
);
6333 emacs_gnutls_push (gnutls_transport_ptr_t p
, const void* buf
, size_t sz
)
6335 struct Lisp_Process
*process
= (struct Lisp_Process
*)p
;
6336 int fd
= process
->outfd
;
6337 ssize_t n
= sys_write (fd
, buf
, sz
);
6339 /* 0 or more bytes written means everything went fine. */
6343 /* Negative bytes written means we got an error in errno.
6344 Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
6345 emacs_gnutls_transport_set_errno (process
->gnutls_state
,
6346 errno
== EWOULDBLOCK
? EAGAIN
: errno
);
6350 #endif /* HAVE_GNUTLS */