Rename OS_WINDOWS_95 to OS_9X.
[emacs.git] / src / w32.c
bloba9f4f6fb50e1808790a3acaf2add970a71c59843
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 */
23 #include <stdlib.h>
24 #include <stdio.h>
25 #include <float.h> /* for DBL_EPSILON */
26 #include <io.h>
27 #include <errno.h>
28 #include <fcntl.h>
29 #include <ctype.h>
30 #include <signal.h>
31 #include <sys/file.h>
32 #include <sys/time.h>
33 #include <sys/utime.h>
34 #include <mbstring.h> /* for _mbspbrk */
35 #include <math.h>
36 #include <setjmp.h>
37 #include <time.h>
39 /* must include CRT headers *before* config.h */
41 #include <config.h>
43 #undef access
44 #undef chdir
45 #undef chmod
46 #undef creat
47 #undef ctime
48 #undef fopen
49 #undef link
50 #undef mkdir
51 #undef mktemp
52 #undef open
53 #undef rename
54 #undef rmdir
55 #undef unlink
57 #undef close
58 #undef dup
59 #undef dup2
60 #undef pipe
61 #undef read
62 #undef write
64 #undef strerror
66 #undef localtime
68 #include "lisp.h"
70 #include <pwd.h>
71 #include <grp.h>
73 #ifdef __GNUC__
74 #define _ANONYMOUS_UNION
75 #define _ANONYMOUS_STRUCT
76 #endif
77 #include <windows.h>
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 {
81 DWORD dwLength;
82 DWORD dwMemoryLoad;
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;
92 #include <lmcons.h>
93 #include <shlobj.h>
95 #include <tlhelp32.h>
96 #include <psapi.h>
97 #ifndef _MSC_VER
98 #include <w32api.h>
99 #endif
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 {
105 DWORD cb;
106 DWORD PageFaultCount;
107 DWORD PeakWorkingSetSize;
108 DWORD WorkingSetSize;
109 DWORD QuotaPeakPagedPoolUsage;
110 DWORD QuotaPagedPoolUsage;
111 DWORD QuotaPeakNonPagedPoolUsage;
112 DWORD QuotaNonPagedPoolUsage;
113 DWORD PagefileUsage;
114 DWORD PeakPagefileUsage;
115 DWORD PrivateUsage;
116 } PROCESS_MEMORY_COUNTERS_EX,*PPROCESS_MEMORY_COUNTERS_EX;
117 #endif
119 /* TCP connection support. */
120 #include <sys/socket.h>
121 #undef socket
122 #undef bind
123 #undef connect
124 #undef htons
125 #undef ntohs
126 #undef inet_addr
127 #undef gethostname
128 #undef gethostbyname
129 #undef getservbyname
130 #undef getpeername
131 #undef shutdown
132 #undef setsockopt
133 #undef listen
134 #undef getsockname
135 #undef accept
136 #undef recvfrom
137 #undef sendto
139 #include "w32.h"
140 #include "ndir.h"
141 #include "w32heap.h"
142 #include "systime.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. */
150 #include "process.h"
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
169 different. */
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,
204 DWORD DesiredAccess,
205 PHANDLE TokenHandle);
206 typedef BOOL (WINAPI * GetTokenInformation_Proc) (
207 HANDLE TokenHandle,
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;
221 #ifdef _UNICODE
222 const char * const LookupAccountSid_Name = "LookupAccountSidW";
223 const char * const GetFileSecurity_Name = "GetFileSecurityW";
224 #else
225 const char * const LookupAccountSid_Name = "LookupAccountSidA";
226 const char * const GetFileSecurity_Name = "GetFileSecurityA";
227 #endif
228 typedef BOOL (WINAPI * LookupAccountSid_Proc) (
229 LPCTSTR lpSystemName,
230 PSID Sid,
231 LPTSTR Name,
232 LPDWORD cbName,
233 LPTSTR DomainName,
234 LPDWORD cbDomainName,
235 PSID_NAME_USE peUse);
236 typedef PDWORD (WINAPI * GetSidSubAuthority_Proc) (
237 PSID pSid,
238 DWORD n);
239 typedef PUCHAR (WINAPI * GetSidSubAuthorityCount_Proc) (
240 PSID pSid);
241 typedef BOOL (WINAPI * GetFileSecurity_Proc) (
242 LPCTSTR lpFileName,
243 SECURITY_INFORMATION RequestedInformation,
244 PSECURITY_DESCRIPTOR pSecurityDescriptor,
245 DWORD nLength,
246 LPDWORD lpnLengthNeeded);
247 typedef BOOL (WINAPI * GetSecurityDescriptorOwner_Proc) (
248 PSECURITY_DESCRIPTOR pSecurityDescriptor,
249 PSID *pOwner,
250 LPBOOL lpbOwnerDefaulted);
251 typedef BOOL (WINAPI * GetSecurityDescriptorGroup_Proc) (
252 PSECURITY_DESCRIPTOR pSecurityDescriptor,
253 PSID *pGroup,
254 LPBOOL lpbGroupDefaulted);
255 typedef BOOL (WINAPI * IsValidSid_Proc) (
256 PSID sid);
257 typedef HANDLE (WINAPI * CreateToolhelp32Snapshot_Proc) (
258 DWORD dwFlags,
259 DWORD th32ProcessID);
260 typedef BOOL (WINAPI * Process32First_Proc) (
261 HANDLE hSnapshot,
262 LPPROCESSENTRY32 lppe);
263 typedef BOOL (WINAPI * Process32Next_Proc) (
264 HANDLE hSnapshot,
265 LPPROCESSENTRY32 lppe);
266 typedef BOOL (WINAPI * OpenThreadToken_Proc) (
267 HANDLE ThreadHandle,
268 DWORD DesiredAccess,
269 BOOL OpenAsSelf,
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) (
275 HANDLE Process,
276 PPROCESS_MEMORY_COUNTERS ppsmemCounters,
277 DWORD cb);
278 typedef BOOL (WINAPI * GetProcessWorkingSetSize_Proc) (
279 HANDLE hProcess,
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,
289 PSID pSourceSid);
290 typedef BOOL (WINAPI * EqualSid_Proc) (
291 PSID pSid1,
292 PSID pSid2);
293 typedef DWORD (WINAPI * GetLengthSid_Proc) (
294 PSID pSid);
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 ** */
303 static BOOL
304 is_windows_9x (void)
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);
318 return s_b_ret;
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. */
326 Lisp_Object
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 ** */
350 static BOOL WINAPI
351 open_process_token (HANDLE ProcessHandle,
352 DWORD DesiredAccess,
353 PHANDLE TokenHandle)
355 static OpenProcessToken_Proc s_pfn_Open_Process_Token = NULL;
356 HMODULE hm_advapi32 = NULL;
357 if (is_windows_9x () == TRUE)
359 return FALSE;
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)
370 return FALSE;
372 return (
373 s_pfn_Open_Process_Token (
374 ProcessHandle,
375 DesiredAccess,
376 TokenHandle)
380 static BOOL WINAPI
381 get_token_information (HANDLE TokenHandle,
382 TOKEN_INFORMATION_CLASS TokenInformationClass,
383 LPVOID TokenInformation,
384 DWORD TokenInformationLength,
385 PDWORD ReturnLength)
387 static GetTokenInformation_Proc s_pfn_Get_Token_Information = NULL;
388 HMODULE hm_advapi32 = NULL;
389 if (is_windows_9x () == TRUE)
391 return FALSE;
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)
402 return FALSE;
404 return (
405 s_pfn_Get_Token_Information (
406 TokenHandle,
407 TokenInformationClass,
408 TokenInformation,
409 TokenInformationLength,
410 ReturnLength)
414 static BOOL WINAPI
415 lookup_account_sid (LPCTSTR lpSystemName,
416 PSID Sid,
417 LPTSTR Name,
418 LPDWORD cbName,
419 LPTSTR DomainName,
420 LPDWORD cbDomainName,
421 PSID_NAME_USE peUse)
423 static LookupAccountSid_Proc s_pfn_Lookup_Account_Sid = NULL;
424 HMODULE hm_advapi32 = NULL;
425 if (is_windows_9x () == TRUE)
427 return FALSE;
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)
438 return FALSE;
440 return (
441 s_pfn_Lookup_Account_Sid (
442 lpSystemName,
443 Sid,
444 Name,
445 cbName,
446 DomainName,
447 cbDomainName,
448 peUse)
452 static PDWORD WINAPI
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)
460 return &zero;
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)
472 return &zero;
474 return (s_pfn_Get_Sid_Sub_Authority (pSid, n));
477 static PUCHAR WINAPI
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)
485 return &zero;
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)
497 return &zero;
499 return (s_pfn_Get_Sid_Sub_Authority_Count (pSid));
502 static BOOL WINAPI
503 get_file_security (LPCTSTR lpFileName,
504 SECURITY_INFORMATION RequestedInformation,
505 PSECURITY_DESCRIPTOR pSecurityDescriptor,
506 DWORD nLength,
507 LPDWORD lpnLengthNeeded)
509 static GetFileSecurity_Proc s_pfn_Get_File_Security = NULL;
510 HMODULE hm_advapi32 = NULL;
511 if (is_windows_9x () == TRUE)
513 return FALSE;
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)
525 return FALSE;
527 return (s_pfn_Get_File_Security (lpFileName, RequestedInformation,
528 pSecurityDescriptor, nLength,
529 lpnLengthNeeded));
532 static BOOL WINAPI
533 get_security_descriptor_owner (PSECURITY_DESCRIPTOR pSecurityDescriptor,
534 PSID *pOwner,
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)
541 return FALSE;
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)
553 return FALSE;
555 return (s_pfn_Get_Security_Descriptor_Owner (pSecurityDescriptor, pOwner,
556 lpbOwnerDefaulted));
559 static BOOL WINAPI
560 get_security_descriptor_group (PSECURITY_DESCRIPTOR pSecurityDescriptor,
561 PSID *pGroup,
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)
568 return FALSE;
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)
580 return FALSE;
582 return (s_pfn_Get_Security_Descriptor_Group (pSecurityDescriptor, pGroup,
583 lpbGroupDefaulted));
586 static BOOL WINAPI
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)
593 return FALSE;
595 if (g_b_init_is_valid_sid == 0)
597 g_b_init_is_valid_sid = 1;
598 hm_advapi32 = LoadLibrary ("Advapi32.dll");
599 s_pfn_Is_Valid_Sid =
600 (IsValidSid_Proc) GetProcAddress (
601 hm_advapi32, "IsValidSid");
603 if (s_pfn_Is_Valid_Sid == NULL)
605 return FALSE;
607 return (s_pfn_Is_Valid_Sid (sid));
610 static BOOL WINAPI
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)
617 return FALSE;
619 if (g_b_init_equal_sid == 0)
621 g_b_init_equal_sid = 1;
622 hm_advapi32 = LoadLibrary ("Advapi32.dll");
623 s_pfn_Equal_Sid =
624 (EqualSid_Proc) GetProcAddress (
625 hm_advapi32, "EqualSid");
627 if (s_pfn_Equal_Sid == NULL)
629 return FALSE;
631 return (s_pfn_Equal_Sid (sid1, sid2));
634 static DWORD WINAPI
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)
641 return 0;
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)
653 return 0;
655 return (s_pfn_Get_Length_Sid (sid));
658 static BOOL WINAPI
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)
665 return FALSE;
667 if (g_b_init_copy_sid == 0)
669 g_b_init_copy_sid = 1;
670 hm_advapi32 = LoadLibrary ("Advapi32.dll");
671 s_pfn_Copy_Sid =
672 (CopySid_Proc) GetProcAddress (
673 hm_advapi32, "CopySid");
675 if (s_pfn_Copy_Sid == NULL)
677 return FALSE;
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
688 static void WINAPI
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);
704 else
705 lpSystemInfo->dwNumberOfProcessors = -1;
708 static BOOL WINAPI
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)
716 return FALSE;
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"),
723 "GetSystemTimes");
725 if (s_pfn_Get_System_times == NULL)
726 return FALSE;
727 return (s_pfn_Get_System_times (lpIdleTime, lpKernelTime, lpUserTime));
730 /* Equivalent of strerror for W32 error codes. */
731 char *
732 w32_strerror (int error_no)
734 static char buf[500];
736 if (error_no == 0)
737 error_no = GetLastError ();
739 buf[0] = '\0';
740 if (!FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM, NULL,
741 error_no,
742 0, /* choose most suitable language */
743 buf, sizeof (buf), NULL))
744 sprintf (buf, "w32 error %u", error_no);
745 return buf;
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)
755 SIZE_T done;
756 HANDLE h = OpenProcess (PROCESS_VM_READ, FALSE, GetCurrentProcessId ());
758 if (h)
760 unsigned char *buf = alloca (size);
761 int retval = ReadProcessMemory (h, p, buf, size, &done);
763 CloseHandle (h);
764 return retval;
766 else
767 return -1;
770 static char startup_dir[MAXPATHLEN];
772 /* Get the current working directory. */
773 char *
774 getwd (char *dir)
776 #if 0
777 if (GetCurrentDirectory (MAXPATHLEN, dir) > 0)
778 return dir;
779 return NULL;
780 #else
781 /* Emacs doesn't actually change directory itself, it stays in the
782 same directory where it was started. */
783 strcpy (dir, startup_dir);
784 return dir;
785 #endif
788 /* Emulate getloadavg. */
790 struct load_sample {
791 time_t sample_time;
792 ULONGLONG idle;
793 ULONGLONG kernel;
794 ULONGLONG user;
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]);
805 static int
806 buf_next (int from)
808 int next_idx = from + 1;
810 if (next_idx >= max_idx)
811 next_idx = 0;
813 return next_idx;
816 static int
817 buf_prev (int from)
819 int prev_idx = from - 1;
821 if (prev_idx < 0)
822 prev_idx = max_idx - 1;
824 return prev_idx;
827 static void
828 sample_system_load (ULONGLONG *idle, ULONGLONG *kernel, ULONGLONG *user)
830 SYSTEM_INFO sysinfo;
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
850 actually running. */
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;
863 else
865 *idle = 0;
866 *kernel = 0;
867 *user = 0;
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. */
874 static double
875 getavg (int which)
877 double retval = -1.0;
878 double tdiff;
879 int idx;
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)
890 long double sys =
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;
896 break;
898 if (idx == first_idx)
899 break;
903 return retval;
907 getloadavg (double loadavg[], int nelem)
909 int elem;
910 ULONGLONG idle, kernel, user;
911 time_t now = time (NULL);
913 /* Store another sample. We ignore samples that are less than 1 sec
914 apart. */
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
924 the old ones. */
925 if (first_idx == -1)
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);
937 if (avg < 0)
938 break;
939 loadavg[elem] = avg;
942 return 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 =
957 dflt_passwd_name,
958 dflt_passwd_passwd,
962 dflt_passwd_gecos,
963 dflt_passwd_dir,
964 dflt_passwd_shell,
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. */
973 dflt_group_name,
977 unsigned
978 getuid (void)
980 return dflt_passwd.pw_uid;
983 unsigned
984 geteuid (void)
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. */
989 return getuid ();
992 unsigned
993 getgid (void)
995 return dflt_passwd.pw_gid;
998 unsigned
999 getegid (void)
1001 return getgid ();
1004 struct passwd *
1005 getpwuid (unsigned uid)
1007 if (uid == dflt_passwd.pw_uid)
1008 return &dflt_passwd;
1009 return NULL;
1012 struct group *
1013 getgrgid (gid_t gid)
1015 return &dflt_group;
1018 struct passwd *
1019 getpwnam (char *name)
1021 struct passwd *pw;
1023 pw = getpwuid (getuid ());
1024 if (!pw)
1025 return pw;
1027 if (xstrcasecmp (name, pw->pw_name))
1028 return NULL;
1030 return pw;
1033 static void
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;
1049 DWORD blen = 0;
1050 TOKEN_USER user_token;
1051 TOKEN_PRIMARY_GROUP group_token;
1052 BOOL result;
1054 result = open_process_token (GetCurrentProcess (), TOKEN_QUERY, &token);
1055 if (result)
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);
1063 if (result)
1065 memcpy (&user_token, buf, sizeof (user_token));
1066 result = lookup_account_sid (NULL, user_token.User.Sid,
1067 uname, &ulength,
1068 domain, &dlength, &user_type);
1071 else
1072 result = FALSE;
1074 if (result)
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 */
1083 else
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);
1098 if (result)
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,
1108 &user_type))
1109 strcpy (dflt_group_name, gname);
1111 else
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;
1122 else
1123 dflt_passwd.pw_uid = 123;
1124 dflt_passwd.pw_gid = dflt_passwd.pw_uid;
1126 else
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)
1136 abort ();
1137 if (getenv ("SHELL") == NULL)
1138 abort ();
1140 /* Set dir and shell from environment variables. */
1141 strcpy (dflt_passwd.pw_dir, getenv ("HOME"));
1142 strcpy (dflt_passwd.pw_shell, getenv ("SHELL"));
1144 xfree (buf);
1145 if (token)
1146 CloseHandle (token);
1150 random (void)
1152 /* rand () on NT gives us 15 random bits...hack together 30 bits. */
1153 return ((rand () << 15) | rand ());
1156 void
1157 srandom (int seed)
1159 srand (seed);
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. */
1167 static void
1168 normalize_filename (register char *fp, char path_sep)
1170 char sep;
1171 char *elem;
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')
1180 *fp += 'a' - 'A';
1181 fp += 2;
1184 if (NILP (Vw32_downcase_file_names))
1186 while (*fp)
1188 if (*fp == '/' || *fp == '\\')
1189 *fp = path_sep;
1190 fp++;
1192 return;
1195 sep = path_sep; /* convert to this path separator */
1196 elem = fp; /* start of current path element */
1198 do {
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 */
1217 sep = path_sep;
1219 } while (*fp++);
1222 /* Destructively turn backslashes into slashes. */
1223 void
1224 dostounix_filename (register char *p)
1226 normalize_filename (p, '/');
1229 /* Destructively turn slashes into backslashes. */
1230 void
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.) */
1239 static int
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;
1246 if (n == 0)
1247 return n;
1248 while (buf < endp - 1)
1250 if (*buf == 0x0d)
1252 if (*(++buf) != 0x0a)
1253 *np++ = 0x0d;
1255 else
1256 *np++ = *buf++;
1258 if (buf < endp)
1259 *np++ = *buf++;
1260 return np - startp;
1263 /* Parse the root part of file name, if present. Return length and
1264 optionally store pointer to char after root. */
1265 static int
1266 parse_root (char * name, char ** pPath)
1268 char * start = name;
1270 if (name == NULL)
1271 return 0;
1273 /* find the root name of the volume if given */
1274 if (isalpha (name[0]) && name[1] == ':')
1276 /* skip past drive specifier */
1277 name += 2;
1278 if (IS_DIRECTORY_SEP (name[0]))
1279 name++;
1281 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
1283 int slashes = 2;
1284 name += 2;
1287 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
1288 break;
1289 name++;
1291 while ( *name );
1292 if (IS_DIRECTORY_SEP (name[0]))
1293 name++;
1296 if (pPath)
1297 *pPath = name;
1299 return name - start;
1302 /* Get long base name for name; name is assumed to be absolute. */
1303 static int
1304 get_long_basename (char * name, char * buf, int size)
1306 WIN32_FIND_DATA find_data;
1307 HANDLE dir_handle;
1308 int len = 0;
1310 /* must be valid filename, no wild cards or other invalid characters */
1311 if (_mbspbrk (name, "*?|<>\""))
1312 return 0;
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);
1319 else
1320 len = 0;
1321 FindClose (dir_handle);
1323 return len;
1326 /* Get long name for file, if possible (assumed to be absolute). */
1327 BOOL
1328 w32_get_long_filename (char * name, char * buf, int size)
1330 char * o = buf;
1331 char * p;
1332 char * q;
1333 char full[ MAX_PATH ];
1334 int len;
1336 len = strlen (name);
1337 if (len >= MAX_PATH)
1338 return FALSE;
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);
1347 o += len;
1348 *o = '\0';
1349 size -= len;
1351 while (p != NULL && *p)
1353 q = p;
1354 p = strchr (q, '\\');
1355 if (p) *p = '\0';
1356 len = get_long_basename (full, o, size);
1357 if (len > 0)
1359 o += len;
1360 size -= len;
1361 if (p != NULL)
1363 *p++ = '\\';
1364 if (size < 2)
1365 return FALSE;
1366 *o++ = '\\';
1367 size--;
1368 *o = '\0';
1371 else
1372 return FALSE;
1375 return TRUE;
1378 static int
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])
1384 return 0;
1386 if (_mbspbrk (ptr + 2, "*?|<>\"\\/"))
1387 return 0;
1389 return 1;
1392 /* Routines that are no-ops on NT but are defined to get Emacs to compile. */
1395 sigsetmask (int signal_mask)
1397 return 0;
1401 sigmask (int sig)
1403 return 0;
1407 sigblock (int sig)
1409 return 0;
1413 sigunblock (int sig)
1415 return 0;
1419 sigemptyset (sigset_t *set)
1421 return 0;
1425 sigaddset (sigset_t *set, int signo)
1427 return 0;
1431 sigfillset (sigset_t *set)
1433 return 0;
1437 sigprocmask (int how, const sigset_t *set, sigset_t *oset)
1439 return 0;
1443 pthread_sigmask (int how, const sigset_t *set, sigset_t *oset)
1445 if (sigprocmask (how, set, oset) == -1)
1446 return EINVAL;
1447 return 0;
1451 setpgrp (int pid, int gid)
1453 return 0;
1457 alarm (int seconds)
1459 return 0;
1462 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
1464 LPBYTE
1465 w32_get_resource (char *key, LPDWORD lpdwtype)
1467 LPBYTE lpvalue;
1468 HKEY hrootkey = NULL;
1469 DWORD cbData;
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)
1476 lpvalue = NULL;
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);
1483 return (lpvalue);
1486 xfree (lpvalue);
1488 RegCloseKey (hrootkey);
1491 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
1493 lpvalue = NULL;
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);
1500 return (lpvalue);
1503 xfree (lpvalue);
1505 RegCloseKey (hrootkey);
1508 return (NULL);
1511 char *get_emacs_configuration (void);
1513 void
1514 init_environment (char ** argv)
1516 static const char * const tempdirs[] = {
1517 "$TMPDIR", "$TEMP", "$TMP", "c:/"
1520 int i;
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];
1532 if (*tmp == '$')
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));
1543 break;
1546 if (i >= imax)
1547 cmd_error_internal
1548 (Fcons (Qerror,
1549 Fcons (build_string ("no usable temporary directories found!!"),
1550 Qnil)),
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. */
1556 int i;
1557 LPBYTE lpval;
1558 DWORD dwType;
1559 char locale_name[32];
1560 struct stat ignored;
1561 char default_home[MAX_PATH];
1562 int appdata = 0;
1564 static const struct env_entry
1566 char * name;
1567 char * def_value;
1568 } dflt_envvars[] =
1570 {"HOME", "C:/"},
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
1578 is then ignored. */
1579 /* {"INFOPATH", "%emacs_dir%/info"}, */
1580 {"EMACSDOC", "%emacs_dir%/etc"},
1581 {"TERM", "cmd"},
1582 {"LANG", NULL},
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
1604 MSIE 5. */
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,
1612 0, default_home);
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;
1618 appdata = 1;
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;
1633 break;
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. */
1642 if (no_site_lisp)
1644 for (i = 0; i < N_ENV_VARS; i++)
1646 if (strcmp (env_vars[i].name, "EMACSLOADPATH") == 0)
1648 char *site;
1649 while ((site = strstr (env_vars[i].def_value, "site-lisp")))
1650 env_vars[i].def_value = strchr (site, ';') + 1;
1651 break;
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. */
1662 char *p;
1663 char modname[MAX_PATH];
1665 if (!GetModuleFileName (NULL, modname, MAX_PATH))
1666 abort ();
1667 if ((p = strrchr (modname, '\\')) == NULL)
1668 abort ();
1669 *p = 0;
1671 if ((p = strrchr (modname, '\\')) && xstrcasecmp (p, "\\bin") == 0)
1673 char buf[SET_ENV_BUF_SIZE];
1675 *p = 0;
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)
1689 *p = 0;
1690 p = strrchr (modname, '\\');
1691 if (p != NULL)
1693 *p = 0;
1694 p = strrchr (modname, '\\');
1695 if (p && xstrcasecmp (p, "\\src") == 0)
1697 char buf[SET_ENV_BUF_SIZE];
1699 *p = 0;
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))
1714 int dont_free = 0;
1716 if ((lpval = w32_get_resource (env_vars[i].name, &dwType)) == NULL
1717 /* Also ignore empty environment variables. */
1718 || *lpval == 0)
1720 xfree (lpval);
1721 lpval = env_vars[i].def_value;
1722 dwType = REG_EXPAND_SZ;
1723 dont_free = 1;
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);
1732 if (lpval)
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,
1743 buf1);
1744 _putenv (strdup (buf2));
1747 if (!dont_free)
1748 xfree (lpval);
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. */
1767 char ** envp;
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))
1778 abort ();
1781 static char modname[MAX_PATH];
1783 if (!GetModuleFileName (NULL, modname, MAX_PATH))
1784 abort ();
1785 argv[0] = modname;
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
1790 mouse-3. */
1791 w32_num_mouse_buttons = GetSystemMetrics (SM_CMOUSEBUTTONS);
1793 init_user_info ();
1796 char *
1797 emacs_root_dir (void)
1799 static char root_dir[FILENAME_MAX];
1800 const char *p;
1802 p = getenv ("emacs_dir");
1803 if (p == NULL)
1804 abort ();
1805 strcpy (root_dir, p);
1806 root_dir[parse_root (root_dir, NULL)] = '\0';
1807 dostounix_filename (root_dir);
1808 return 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
1814 routine. */
1816 char *
1817 get_emacs_configuration (void)
1819 char *arch, *oem, *os;
1820 int build_num;
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:
1831 arch = "i386";
1832 break;
1833 #endif
1835 #ifdef PROCESSOR_MIPS_R2000
1836 case PROCESSOR_MIPS_R2000:
1837 case PROCESSOR_MIPS_R3000:
1838 case PROCESSOR_MIPS_R4000:
1839 arch = "mips";
1840 break;
1841 #endif
1843 #ifdef PROCESSOR_ALPHA_21064
1844 case PROCESSOR_ALPHA_21064:
1845 arch = "alpha";
1846 break;
1847 #endif
1849 default:
1850 arch = "unknown";
1851 break;
1854 /* Use the OEM field to reflect the compiler/library combination. */
1855 #ifdef _MSC_VER
1856 #define COMPILER_NAME "msvc"
1857 #else
1858 #ifdef __GNUC__
1859 #define COMPILER_NAME "mingw"
1860 #else
1861 #define COMPILER_NAME "unknown"
1862 #endif
1863 #endif
1864 oem = COMPILER_NAME;
1866 switch (osinfo_cache.dwPlatformId) {
1867 case VER_PLATFORM_WIN32_NT:
1868 os = "nt";
1869 build_num = osinfo_cache.dwBuildNumber;
1870 break;
1871 case VER_PLATFORM_WIN32_WINDOWS:
1872 if (osinfo_cache.dwMinorVersion == 0) {
1873 os = "windows95";
1874 } else {
1875 os = "windows98";
1877 build_num = LOWORD (osinfo_cache.dwBuildNumber);
1878 break;
1879 case VER_PLATFORM_WIN32s:
1880 /* Not supported, should not happen. */
1881 os = "windows32s";
1882 build_num = LOWORD (osinfo_cache.dwBuildNumber);
1883 break;
1884 default:
1885 os = "unknown";
1886 build_num = 0;
1887 break;
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);
1893 } else {
1894 sprintf (configuration_buffer, "%s-%s-%s.%d", arch, oem, os, build_num);
1897 return configuration_buffer;
1900 char *
1901 get_emacs_configuration_options (void)
1903 static char *options_buffer;
1904 char cv[32]; /* Enough for COMPILER_VERSION. */
1905 char *options[] = {
1906 cv, /* To be filled later. */
1907 #ifdef EMACSDEBUG
1908 " --no-opt",
1909 #endif
1910 #ifdef ENABLE_CHECKING
1911 " --enable-checking",
1912 #endif
1913 /* configure.bat already sets USER_CFLAGS and USER_LDFLAGS
1914 with a starting space to save work here. */
1915 #ifdef USER_CFLAGS
1916 " --cflags", USER_CFLAGS,
1917 #endif
1918 #ifdef USER_LDFLAGS
1919 " --ldflags", USER_LDFLAGS,
1920 #endif
1921 NULL
1923 size_t size = 0;
1924 int i;
1926 /* Work out the effective configure options for this build. */
1927 #ifdef _MSC_VER
1928 #define COMPILER_VERSION "--with-msvc (%d.%02d)", _MSC_VER / 100, _MSC_VER % 100
1929 #else
1930 #ifdef __GNUC__
1931 #define COMPILER_VERSION "--with-gcc (%d.%d)", __GNUC__, __GNUC_MINOR__
1932 #else
1933 #define COMPILER_VERSION ""
1934 #endif
1935 #endif
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). */
1957 void
1958 gettimeofday (struct timeval *tv, struct timezone *tz)
1960 struct _timeb tb;
1961 _ftime (&tb);
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). */
1971 if (tz)
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])
1992 struct _utimbuf ut;
1994 if (!timespec)
1996 errno = ENOSYS;
1997 return -1;
1999 if (fd < 0 && !file)
2001 errno = EBADF;
2002 return -1;
2004 ut.actime = timespec[0].tv_sec;
2005 ut.modtime = timespec[1].tv_sec;
2006 if (fd >= 0)
2007 return _futime (fd, &ut);
2008 else
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). */
2020 char *
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. */
2030 void
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 */
2047 DWORD timestamp;
2049 /* actual volume info */
2050 char * root_dir;
2051 DWORD serialnum;
2052 DWORD maxcomp;
2053 DWORD flags;
2054 char * name;
2055 char * type;
2056 } volume_info_data;
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)
2085 break;
2086 return info;
2089 static void
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)
2111 return NULL;
2112 parse_root (default_root, &root_dir);
2113 *root_dir = 0;
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. */
2129 #if 0
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))
2142 == NO_ERROR)
2143 /* do something */ ;
2145 #endif
2147 info = lookup_volume_info (root_dir);
2149 if (info == NULL || ! VOLINFO_STILL_VALID (root_dir, info))
2151 char name[ 256 ];
2152 DWORD serialnum;
2153 DWORD maxcomp;
2154 DWORD flags;
2155 char type[ 256 ];
2157 /* Info is not cached, or is stale. */
2158 if (!GetVolumeInformation (root_dir,
2159 name, sizeof (name),
2160 &serialnum,
2161 &maxcomp,
2162 &flags,
2163 type, sizeof (type)))
2164 return NULL;
2166 /* Cache the volume information for future use, overwriting existing
2167 entry if present. */
2168 if (info == NULL)
2170 info = xmalloc (sizeof (volume_info_data));
2171 add_volume_info (root_dir, info);
2173 else
2175 xfree (info->name);
2176 xfree (info->type);
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 ();
2187 return info;
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). */
2192 static int
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;
2199 if (name == NULL)
2200 return FALSE;
2202 /* find the root name of the volume if given */
2203 if (isalpha (name[0]) && name[1] == ':')
2205 rootname = temp;
2206 temp[0] = *name++;
2207 temp[1] = *name++;
2208 temp[2] = '\\';
2209 temp[3] = 0;
2211 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
2213 char *str = temp;
2214 int slashes = 4;
2215 rootname = temp;
2218 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
2219 break;
2220 *str++ = *name++;
2222 while ( *name );
2224 *str++ = '\\';
2225 *str = 0;
2228 if (pPath)
2229 *pPath = name;
2231 info = GetCachedVolumeInformation (rootname);
2232 if (info != NULL)
2234 /* Set global referenced by other functions. */
2235 volume_info = *info;
2236 return TRUE;
2238 return FALSE;
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. */
2243 static int
2244 is_fat_volume (const char * name, const char ** pPath)
2246 if (get_volume_info (name, pPath))
2247 return (volume_info.maxcomp == 12);
2248 return FALSE;
2251 /* Map filename to a valid 8.3 name if necessary. */
2252 const char *
2253 map_w32_filename (const char * name, const char ** pPath)
2255 static char shortname[MAX_PATH];
2256 char * str = shortname;
2257 char c;
2258 char * path;
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, "?");
2265 return 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 */
2274 while (name < path)
2275 *str++ = *name++; /* skip past UNC header */
2277 while ((c = *name++))
2279 switch ( c )
2281 case '\\':
2282 case '/':
2283 *str++ = '\\';
2284 extn = 0; /* reset extension flags */
2285 dots = 2; /* max 2 dots */
2286 left = 8; /* max length 8 for main part */
2287 break;
2288 case ':':
2289 *str++ = ':';
2290 extn = 0; /* reset extension flags */
2291 dots = 2; /* max 2 dots */
2292 left = 8; /* max length 8 for main part */
2293 break;
2294 case '.':
2295 if ( dots )
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. */
2301 if (! *name ||
2302 *name == '.' ||
2303 IS_DIRECTORY_SEP (*name))
2305 *str++ = '.';
2306 dots--;
2308 else
2310 *str++ = '_';
2311 left--;
2312 dots = 0;
2315 else if ( !extn )
2317 *str++ = '.';
2318 extn = 1; /* we've got an extension */
2319 left = 3; /* 3 chars in extension */
2321 else
2323 /* any embedded dots after the first are converted to _ */
2324 *str++ = '_';
2326 break;
2327 case '~':
2328 case '#': /* don't lose these, they're important */
2329 if ( ! left )
2330 str[-1] = c; /* replace last character of part */
2331 /* FALLTHRU */
2332 default:
2333 if ( left )
2335 *str++ = tolower (c); /* map to lower case (looks nicer) */
2336 left--;
2337 dots = 0; /* started a path component */
2339 break;
2342 *str = '\0';
2344 else
2346 strcpy (shortname, name);
2347 unixtodos_filename (shortname);
2350 if (pPath)
2351 *pPath = shortname + (path - save_name);
2353 return shortname;
2356 static int
2357 is_exec (const char * name)
2359 char * p = strrchr (name, '.');
2360 return
2361 (p != NULL
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
2379 root directory. */
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);
2385 DIR *
2386 opendir (char *filename)
2388 DIR *dirp;
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)
2394 return NULL;
2395 if (wnet_enum_handle != INVALID_HANDLE_VALUE)
2396 return NULL;
2398 if (is_unc_volume (filename))
2400 wnet_enum_handle = open_unc_volume (filename);
2401 if (wnet_enum_handle == INVALID_HANDLE_VALUE)
2402 return NULL;
2405 if (!(dirp = (DIR *) malloc (sizeof (DIR))))
2406 return NULL;
2408 dirp->dd_fd = 0;
2409 dirp->dd_loc = 0;
2410 dirp->dd_size = 0;
2412 strncpy (dir_pathname, map_w32_filename (filename, NULL), MAXPATHLEN);
2413 dir_pathname[MAXPATHLEN] = '\0';
2414 dir_is_fat = is_fat_volume (filename, NULL);
2416 return dirp;
2419 void
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);
2436 struct direct *
2437 readdir (DIR *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,
2445 MAX_PATH))
2446 return NULL;
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];
2452 int ln;
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)
2463 return NULL;
2465 else
2467 if (!FindNextFile (dir_find_handle, &dir_find_data))
2468 return NULL;
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. */
2499 downcase = 1;
2501 else
2502 strcpy (dir_static.d_name, dir_find_data.cFileName);
2503 dir_static.d_namlen = strlen (dir_static.d_name);
2504 if (dir_is_fat)
2505 _strlwr (dir_static.d_name);
2506 else if (downcase)
2508 register char *p;
2509 for (p = dir_static.d_name; *p; p++)
2510 if (*p >= 'a' && *p <= 'z')
2511 break;
2512 if (!*p)
2513 _strlwr (dir_static.d_name);
2516 return &dir_static;
2519 static HANDLE
2520 open_unc_volume (const char *path)
2522 NETRESOURCE nr;
2523 HANDLE henum;
2524 int result;
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)
2539 return henum;
2540 else
2541 return INVALID_HANDLE_VALUE;
2544 static char *
2545 read_unc_volume (HANDLE henum, char *readbuf, int size)
2547 DWORD count;
2548 int result;
2549 DWORD bufsize = 512;
2550 char *buffer;
2551 char *ptr;
2553 count = 1;
2554 buffer = alloca (bufsize);
2555 result = WNetEnumResource (henum, &count, buffer, &bufsize);
2556 if (result != NO_ERROR)
2557 return NULL;
2559 /* WNetEnumResource returns \\resource\share...skip forward to "share". */
2560 ptr = ((LPNETRESOURCE) buffer)->lpRemoteName;
2561 ptr += 2;
2562 while (*ptr && !IS_DIRECTORY_SEP (*ptr)) ptr++;
2563 ptr++;
2565 strncpy (readbuf, ptr, size);
2566 return readbuf;
2569 static void
2570 close_unc_volume (HANDLE henum)
2572 if (henum != INVALID_HANDLE_VALUE)
2573 WNetCloseEnum (henum);
2576 static DWORD
2577 unc_volume_file_attributes (const char *path)
2579 HANDLE henum;
2580 DWORD attrs;
2582 henum = open_unc_volume (path);
2583 if (henum == INVALID_HANDLE_VALUE)
2584 return -1;
2586 attrs = FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_DIRECTORY;
2588 close_unc_volume (henum);
2590 return attrs;
2593 /* Ensure a network connection is authenticated. */
2594 static void
2595 logon_network_drive (const char *path)
2597 NETRESOURCE resource;
2598 char share[MAX_PATH];
2599 int i, n_slashes;
2600 char drive[4];
2601 UINT drvtype;
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);
2607 else
2609 drive[0] = path[0];
2610 drive[1] = ':';
2611 drive[2] = '\\';
2612 drive[3] = '\0';
2613 drvtype = GetDriveType (drive);
2616 /* Only logon to networked drives. */
2617 if (drvtype != DRIVE_REMOTE)
2618 return;
2620 n_slashes = 2;
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)
2627 share[i] = '\0';
2628 break;
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
2643 long file names. */
2646 sys_access (const char * path, int mode)
2648 DWORD attributes;
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) {
2657 errno = EACCES;
2658 return -1;
2661 else if ((attributes = GetFileAttributes (path)) == -1)
2663 DWORD w32err = GetLastError ();
2665 switch (w32err)
2667 case ERROR_FILE_NOT_FOUND:
2668 errno = ENOENT;
2669 break;
2670 default:
2671 errno = EACCES;
2672 break;
2674 return -1;
2676 if ((mode & X_OK) != 0 && !is_exec (path))
2678 errno = EACCES;
2679 return -1;
2681 if ((mode & W_OK) != 0 && (attributes & FILE_ATTRIBUTE_READONLY) != 0)
2683 errno = EACCES;
2684 return -1;
2686 if ((mode & D_OK) != 0 && (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
2688 errno = EACCES;
2689 return -1;
2691 return 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 */
2710 return -1;
2711 return 0;
2715 sys_creat (const char * path, int mode)
2717 return _creat (map_w32_filename (path, NULL), mode);
2720 FILE *
2721 sys_fopen (const char * path, const char * mode)
2723 int fd;
2724 int oflag;
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. */
2731 if (mode[0] == 'r')
2732 oflag = O_RDONLY;
2733 else if (mode[0] == 'w' || mode[0] == 'a')
2734 oflag = O_WRONLY | O_CREAT | O_TRUNC;
2735 else
2736 return NULL;
2738 /* Only do simplistic option parsing. */
2739 while (*++mode)
2740 if (mode[0] == '+')
2742 oflag &= ~(O_RDONLY | O_WRONLY);
2743 oflag |= O_RDWR;
2745 else if (mode[0] == 'b')
2747 oflag &= ~O_TEXT;
2748 oflag |= O_BINARY;
2750 else if (mode[0] == 't')
2752 oflag &= ~O_BINARY;
2753 oflag |= O_TEXT;
2755 else break;
2757 fd = _open (map_w32_filename (path, NULL), oflag | _O_NOINHERIT, 0644);
2758 if (fd < 0)
2759 return NULL;
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)
2768 HANDLE fileh;
2769 int result = -1;
2770 char oldname[MAX_PATH], newname[MAX_PATH];
2772 if (old == NULL || new == NULL)
2774 errno = ENOENT;
2775 return -1;
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)
2785 int wlen;
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
2792 stream data. */
2794 struct {
2795 WIN32_STREAM_ID wid;
2796 WCHAR wbuffer[MAX_PATH]; /* extra space for link name */
2797 } data;
2799 wlen = MultiByteToWideChar (CP_ACP, MB_PRECOMPOSED, newname, -1,
2800 data.wid.cStreamName, MAX_PATH);
2801 if (wlen > 0)
2803 LPVOID context = NULL;
2804 DWORD wbytes = 0;
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))
2818 /* succeeded */
2819 result = 0;
2821 else
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);
2831 else
2832 errno = ENOENT;
2834 return result;
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
2846 string.
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. */
2852 char *
2853 sys_mktemp (char * template)
2855 char * p;
2856 int i;
2857 unsigned uid = GetCurrentThreadId ();
2858 static char first_char[] = "abcdefghijklmnopqrstuvwyz0123456789!%-_@#";
2860 if (template == NULL)
2861 return NULL;
2862 p = template + strlen (template);
2863 i = 5;
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;
2868 uid /= 10;
2871 if (i < 0 && p[0] == 'X')
2873 i = 0;
2876 int save_errno = errno;
2877 p[0] = first_char[i];
2878 if (sys_access (template, 0) < 0)
2880 errno = save_errno;
2881 return template;
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 */
2889 template[0] = 0;
2890 return template;
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
2899 non-inheritable. */
2900 int res = _open (mpath, (oflag & ~_O_CREAT) | _O_NOINHERIT, mode);
2901 if (res >= 0)
2902 return res;
2903 return _open (mpath, oflag | _O_NOINHERIT, mode);
2907 sys_rename (const char * oldname, const char * newname)
2909 BOOL result;
2910 char temp[MAX_PATH];
2911 int newname_dev;
2912 int oldname_dev;
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)
2934 char * o;
2935 char * p;
2936 int i = 0;
2938 oldname = map_w32_filename (oldname, NULL);
2939 if ((o = strrchr (oldname, '\\')))
2940 o++;
2941 else
2942 o = (char *) oldname;
2944 if ((p = strrchr (temp, '\\')))
2945 p++;
2946 else
2947 p = 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);
2954 i++;
2955 result = rename (oldname, temp);
2957 /* This loop must surely terminate! */
2958 while (result < 0 && errno == EEXIST);
2959 if (result < 0)
2960 return -1;
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);
2981 if (result < 0)
2984 if (errno == EACCES
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
2991 return EXDEV. */
2992 DWORD attributes;
2994 if ((attributes = GetFileAttributes (temp)) != -1
2995 && attributes & FILE_ATTRIBUTE_DIRECTORY)
2996 errno = EXDEV;
2998 else if (errno == EEXIST)
3000 if (_chmod (newname, 0666) != 0)
3001 return result;
3002 if (_unlink (newname) != 0)
3003 return result;
3004 result = rename (temp, newname);
3008 return result;
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) \
3032 do { \
3033 ULARGE_INTEGER uiTemp; \
3034 uiTemp.LowPart = (ft).dwLowDateTime; \
3035 uiTemp.HighPart = (ft).dwHighDateTime; \
3036 result = uiTemp.QuadPart; \
3037 } while (0)
3039 static void
3040 initialize_utc_base (void)
3042 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
3043 SYSTEMTIME st;
3045 st.wYear = 1970;
3046 st.wMonth = 1;
3047 st.wDay = 1;
3048 st.wHour = 0;
3049 st.wMinute = 0;
3050 st.wSecond = 0;
3051 st.wMilliseconds = 0;
3053 SystemTimeToFileTime (&st, &utc_base_ft);
3054 FILETIME_TO_U64 (utc_base, utc_base_ft);
3057 static time_t
3058 convert_time (FILETIME ft)
3060 ULONGLONG tmp;
3062 if (!init)
3064 initialize_utc_base ();
3065 init = 1;
3068 if (CompareFileTime (&ft, &utc_base_ft) < 0)
3069 return 0;
3071 FILETIME_TO_U64 (tmp, ft);
3072 return (time_t) ((tmp - utc_base) / 10000000L);
3075 static void
3076 convert_from_time_t (time_t time, FILETIME * pft)
3078 ULARGE_INTEGER tmp;
3080 if (!init)
3082 initialize_utc_base ();
3083 init = 1;
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;
3092 #if 0
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). */
3100 static unsigned
3101 hashval (const unsigned char * str)
3103 unsigned h = 0;
3104 while (*str)
3106 h = (h << 4) + *str++;
3107 h ^= (h >> 28);
3109 return h;
3112 /* Return the hash value of the canonical pathname, excluding the
3113 drive/UNC header, to get a hopefully unique inode number. */
3114 static DWORD
3115 generate_inode_val (const char * name)
3117 char fullname[ MAX_PATH ];
3118 char * p;
3119 unsigned hash;
3121 /* Get the truly canonical filename, if it exists. (Note: this
3122 doesn't resolve aliasing due to subst commands, or recognize hard
3123 links. */
3124 if (!w32_get_long_filename ((char *)name, fullname, MAX_PATH))
3125 abort ();
3127 parse_root (fullname, &p);
3128 /* Normal W32 filesystems are still case insensitive. */
3129 _strlwr (p);
3130 return hashval (p);
3133 #endif
3135 static PSECURITY_DESCRIPTOR
3136 get_file_security_desc (const char *fname)
3138 PSECURITY_DESCRIPTOR psd = NULL;
3139 DWORD sd_len, err;
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)
3147 return NULL;
3150 psd = xmalloc (sd_len);
3151 if (!get_file_security (fname, si, psd, sd_len, &sd_len))
3153 xfree (psd);
3154 return NULL;
3157 return psd;
3160 static DWORD
3161 get_rid (PSID sid)
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. */
3175 #ifdef __GNUC__
3176 # define FLEXIBLE_ARRAY_MEMBER
3177 #else
3178 # define FLEXIBLE_ARRAY_MEMBER 1
3179 #endif
3181 struct w32_id {
3182 unsigned rid;
3183 struct w32_id *next;
3184 char name[GNLEN+1];
3185 unsigned char sid[FLEXIBLE_ARRAY_MEMBER];
3188 static struct w32_id *w32_idlist;
3190 static int
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))
3199 found = tail;
3200 break;
3203 if (found)
3205 *id = found->rid;
3206 strcpy (name, found->name);
3207 return 1;
3209 else
3210 return 0;
3213 static void
3214 w32_add_to_cache (PSID sid, unsigned id, char *name)
3216 DWORD sid_len;
3217 struct w32_id *new_entry;
3219 /* We don't want to leave behind stale cache from when Emacs was
3220 dumped. */
3221 if (initialized)
3223 sid_len = get_length_sid (sid);
3224 new_entry = xmalloc (offsetof (struct w32_id, sid) + sid_len);
3225 if (new_entry)
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;
3236 #define UID 1
3237 #define GID 2
3239 static int
3240 get_name_and_id (PSECURITY_DESCRIPTOR psd, const char *fname,
3241 unsigned *id, char *nm, int what)
3243 PSID sid = NULL;
3244 char machine[MAX_COMPUTERNAME_LENGTH+1];
3245 BOOL dflt;
3246 SID_NAME_USE ignore;
3247 char name[UNLEN+1];
3248 DWORD name_len = sizeof (name);
3249 char domain[1024];
3250 DWORD domain_len = sizeof (domain);
3251 char *mp = NULL;
3252 int use_dflt = 0;
3253 int result;
3255 if (what == UID)
3256 result = get_security_descriptor_owner (psd, &sid, &dflt);
3257 else if (what == GID)
3258 result = get_security_descriptor_group (psd, &sid, &dflt);
3259 else
3260 result = 0;
3262 if (!result || !is_valid_sid (sid))
3263 use_dflt = 1;
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')
3271 const char *s;
3272 char *p;
3274 for (s = fname + 2, p = machine;
3275 *s && !IS_DIRECTORY_SEP (*s); s++, p++)
3276 *p = *s;
3277 *p = '\0';
3278 mp = machine;
3281 if (!lookup_account_sid (mp, sid, name, &name_len,
3282 domain, &domain_len, &ignore)
3283 || name_len > UNLEN+1)
3284 use_dflt = 1;
3285 else
3287 *id = get_rid (sid);
3288 strcpy (nm, name);
3289 w32_add_to_cache (sid, *id, name);
3292 return use_dflt;
3295 static void
3296 get_file_owner_and_group (PSECURITY_DESCRIPTOR psd,
3297 const char *fname,
3298 struct stat *st)
3300 int dflt_usr = 0, dflt_grp = 0;
3302 if (!psd)
3304 dflt_usr = 1;
3305 dflt_grp = 1;
3307 else
3309 if (get_name_and_id (psd, fname, &st->st_uid, st->st_uname, UID))
3310 dflt_usr = 1;
3311 if (get_name_and_id (psd, fname, &st->st_gid, st->st_gname, GID))
3312 dflt_grp = 1;
3314 /* Consider files to belong to current user/group, if we cannot get
3315 more accurate information. */
3316 if (dflt_usr)
3318 st->st_uid = dflt_passwd.pw_uid;
3319 strcpy (st->st_uname, dflt_passwd.pw_name);
3321 if (dflt_grp)
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)
3332 char drive_root[4];
3333 UINT devtype;
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 */
3339 else
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)
3356 char *name, *r;
3357 WIN32_FIND_DATA wfd;
3358 HANDLE fh;
3359 unsigned __int64 fake_inode;
3360 int permission;
3361 int len;
3362 int rootdir = FALSE;
3363 PSECURITY_DESCRIPTOR psd = NULL;
3365 if (path == NULL || buf == NULL)
3367 errno = EFAULT;
3368 return -1;
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
3376 filesystems. */
3377 if (_mbspbrk (name, "*?|<>\""))
3379 errno = ENOENT;
3380 return -1;
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')
3387 r[1] = r[2] = '\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);
3402 if (attrs == -1)
3403 return -1;
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);
3412 else if (rootdir)
3414 if (!IS_DIRECTORY_SEP (name[len-1]))
3415 strcat (name, "\\");
3416 if (GetDriveType (name) < 2)
3418 errno = ENOENT;
3419 return -1;
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);
3428 else
3430 if (IS_DIRECTORY_SEP (name[len-1]))
3431 name[len - 1] = 0;
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]))
3438 len--;
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;
3447 else
3449 logon_network_drive (name);
3451 fh = FindFirstFile (name, &wfd);
3452 if (fh == INVALID_HANDLE_VALUE)
3454 errno = ENOENT;
3455 return -1;
3457 FindClose (fh);
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;
3482 fake_inode <<= 32;
3483 fake_inode += info.nFileIndexLow;
3485 else
3487 buf->st_nlink = 1;
3488 fake_inode = 0;
3491 if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
3493 buf->st_mode = S_IFDIR;
3495 else
3497 switch (GetFileType (fh))
3499 case FILE_TYPE_DISK:
3500 buf->st_mode = S_IFREG;
3501 break;
3502 case FILE_TYPE_PIPE:
3503 buf->st_mode = S_IFIFO;
3504 break;
3505 case FILE_TYPE_CHAR:
3506 case FILE_TYPE_UNKNOWN:
3507 default:
3508 buf->st_mode = S_IFCHR;
3511 CloseHandle (fh);
3512 psd = get_file_security_desc (name);
3513 get_file_owner_and_group (psd, name, buf);
3515 else
3517 /* Don't bother to make this information more accurate. */
3518 buf->st_mode = (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ?
3519 S_IFDIR : S_IFREG;
3520 buf->st_nlink = 1;
3521 fake_inode = 0;
3523 get_file_owner_and_group (NULL, name, buf);
3525 xfree (psd);
3527 #if 0
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;
3537 #endif
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);
3542 else
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;
3563 else
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);
3573 return 0;
3576 /* Provide fstat and utime as well as stat for consistent handling of
3577 file timestamps. */
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;
3584 int permission;
3586 switch (GetFileType (fh) & ~FILE_TYPE_REMOTE)
3588 case FILE_TYPE_DISK:
3589 buf->st_mode = S_IFREG;
3590 if (!GetFileInformationByHandle (fh, &info))
3592 errno = EACCES;
3593 return -1;
3595 break;
3596 case FILE_TYPE_PIPE:
3597 buf->st_mode = S_IFIFO;
3598 goto non_disk;
3599 case FILE_TYPE_CHAR:
3600 case FILE_TYPE_UNKNOWN:
3601 default:
3602 buf->st_mode = S_IFCHR;
3603 non_disk:
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;
3621 fake_inode <<= 32;
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);
3627 else
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;
3655 else
3656 permission = S_IREAD | S_IWRITE;
3658 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
3659 permission |= S_IEXEC;
3660 else
3662 #if 0 /* no way of knowing the filename */
3663 char * p = strrchr (name, '.');
3664 if (p != NULL &&
3665 (xstrcasecmp (p, ".exe") == 0 ||
3666 xstrcasecmp (p, ".com") == 0 ||
3667 xstrcasecmp (p, ".bat") == 0 ||
3668 xstrcasecmp (p, ".cmd") == 0))
3669 permission |= S_IEXEC;
3670 #endif
3673 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
3675 return 0;
3679 utime (const char *name, struct utimbuf *times)
3681 struct utimbuf deftime;
3682 HANDLE fh;
3683 FILETIME mtime;
3684 FILETIME atime;
3686 if (times == NULL)
3688 deftime.modtime = deftime.actime = time (NULL);
3689 times = &deftime;
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);
3695 if (fh)
3697 convert_from_time_t (times->actime, &atime);
3698 convert_from_time_t (times->modtime, &mtime);
3699 if (!SetFileTime (fh, NULL, &atime, &mtime))
3701 CloseHandle (fh);
3702 errno = EACCES;
3703 return -1;
3705 CloseHandle (fh);
3707 else
3709 errno = EINVAL;
3710 return -1;
3712 return 0;
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)
3721 errno = ENOSYS;
3722 return -1;
3725 ssize_t
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)
3730 errno = EINVAL;
3731 return -1;
3734 char *
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))
3740 errno = ENOSYS;
3741 return NULL;
3744 ssize_t
3745 careadlinkatcwd (int fd, char const *filename, char *buffer,
3746 size_t buffer_size)
3748 (void) fd;
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));
3777 static BOOL WINAPI
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"),
3787 "Process32First");
3789 if (s_pfn_Process32_First == NULL)
3791 return FALSE;
3793 return (s_pfn_Process32_First (hSnapshot, lppe));
3796 static BOOL WINAPI
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"),
3806 "Process32Next");
3808 if (s_pfn_Process32_Next == NULL)
3810 return FALSE;
3812 return (s_pfn_Process32_Next (hSnapshot, lppe));
3815 static BOOL WINAPI
3816 open_thread_token (HANDLE ThreadHandle,
3817 DWORD DesiredAccess,
3818 BOOL OpenAsSelf,
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);
3826 return FALSE;
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);
3838 return FALSE;
3840 return (
3841 s_pfn_Open_Thread_Token (
3842 ThreadHandle,
3843 DesiredAccess,
3844 OpenAsSelf,
3845 TokenHandle)
3849 static BOOL WINAPI
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)
3856 return FALSE;
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)
3867 return FALSE;
3869 return s_pfn_Impersonate_Self (ImpersonationLevel);
3872 static BOOL WINAPI
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)
3879 return FALSE;
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)
3890 return FALSE;
3892 return s_pfn_Revert_To_Self ();
3895 static BOOL WINAPI
3896 get_process_memory_info (HANDLE h_proc,
3897 PPROCESS_MEMORY_COUNTERS mem_counters,
3898 DWORD bufsize)
3900 static GetProcessMemoryInfo_Proc s_pfn_Get_Process_Memory_Info = NULL;
3901 HMODULE hm_psapi = NULL;
3902 if (is_windows_9x () == TRUE)
3904 return FALSE;
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");
3910 if (hm_psapi)
3911 s_pfn_Get_Process_Memory_Info = (GetProcessMemoryInfo_Proc)
3912 GetProcAddress (hm_psapi, "GetProcessMemoryInfo");
3914 if (s_pfn_Get_Process_Memory_Info == NULL)
3916 return FALSE;
3918 return s_pfn_Get_Process_Memory_Info (h_proc, mem_counters, bufsize);
3921 static BOOL WINAPI
3922 get_process_working_set_size (HANDLE h_proc,
3923 DWORD *minrss,
3924 DWORD *maxrss)
3926 static GetProcessWorkingSetSize_Proc
3927 s_pfn_Get_Process_Working_Set_Size = NULL;
3929 if (is_windows_9x () == TRUE)
3931 return FALSE;
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)
3942 return FALSE;
3944 return s_pfn_Get_Process_Working_Set_Size (h_proc, minrss, maxrss);
3947 static BOOL WINAPI
3948 global_memory_status (MEMORYSTATUS *buf)
3950 static GlobalMemoryStatus_Proc s_pfn_Global_Memory_Status = NULL;
3952 if (is_windows_9x () == TRUE)
3954 return FALSE;
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)
3965 return FALSE;
3967 return s_pfn_Global_Memory_Status (buf);
3970 static BOOL WINAPI
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)
3977 return FALSE;
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)
3988 return FALSE;
3990 return s_pfn_Global_Memory_Status_Ex (buf);
3993 Lisp_Object
3994 list_system_processes (void)
3996 struct gcpro gcpro1;
3997 Lisp_Object proclist = Qnil;
3998 HANDLE h_snapshot;
4000 h_snapshot = create_toolhelp32_snapshot (TH32CS_SNAPPROCESS, 0);
4002 if (h_snapshot != INVALID_HANDLE_VALUE)
4004 PROCESSENTRY32 proc_entry;
4005 DWORD proc_id;
4006 BOOL res;
4008 GCPRO1 (proclist);
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);
4019 UNGCPRO;
4020 proclist = Fnreverse (proclist);
4023 return proclist;
4026 static int
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 ();
4034 int ret_val = 0;
4035 BOOL res;
4037 res = open_thread_token (h_thread,
4038 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
4039 FALSE, &h_token);
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,
4045 FALSE, &h_token);
4047 if (res)
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)
4055 ret_val = 1;
4057 if (h_token)
4058 CloseHandle (h_token);
4060 return ret_val;
4063 static int
4064 restore_privilege (TOKEN_PRIVILEGES *priv)
4066 DWORD priv_size = sizeof (*priv);
4067 HANDLE h_token = NULL;
4068 int ret_val = 0;
4070 if (open_thread_token (GetCurrentThread (),
4071 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
4072 FALSE, &h_token))
4074 if (AdjustTokenPrivileges (h_token, FALSE, priv, priv_size, NULL, NULL)
4075 && GetLastError () != ERROR_NOT_ALL_ASSIGNED)
4076 ret_val = 1;
4078 if (h_token)
4079 CloseHandle (h_token);
4081 return ret_val;
4084 static Lisp_Object
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)
4097 static int
4098 process_times (HANDLE h_proc, Lisp_Object *ctime, Lisp_Object *etime,
4099 Lisp_Object *stime, Lisp_Object *utime, Lisp_Object *ttime,
4100 double *pcpu)
4102 FILETIME ft_creation, ft_exit, ft_kernel, ft_user, ft_current;
4103 ULONGLONG tem1, tem2, tem3, tem;
4105 if (!h_proc
4106 || !get_process_times_fn
4107 || !(*get_process_times_fn) (h_proc, &ft_creation, &ft_exit,
4108 &ft_kernel, &ft_user))
4109 return 0;
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);
4119 tem3 = tem1 + tem2;
4120 *ttime = U64_TO_LISP_TIME (tem3);
4122 FILETIME_TO_U64 (tem, ft_creation);
4123 /* Process no 4 (System) returns zero creation time. */
4124 if (tem)
4125 tem -= utc_base;
4126 *ctime = U64_TO_LISP_TIME (tem);
4128 if (tem)
4130 FILETIME_TO_U64 (tem3, ft_current);
4131 tem = (tem3 - utc_base) - tem;
4133 *etime = U64_TO_LISP_TIME (tem);
4135 if (tem)
4137 *pcpu = 100.0 * (tem1 + tem2) / tem;
4138 if (*pcpu > 100)
4139 *pcpu = 100.0;
4141 else
4142 *pcpu = 0;
4144 return 1;
4147 Lisp_Object
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;
4154 DWORD proc_id;
4155 int found_proc = 0;
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;
4162 DWORD blen = 0;
4163 TOKEN_USER user_token;
4164 TOKEN_PRIMARY_GROUP group_token;
4165 unsigned euid;
4166 unsigned egid;
4167 PROCESS_MEMORY_COUNTERS mem;
4168 PROCESS_MEMORY_COUNTERS_EX mem_ex;
4169 DWORD minrss, maxrss;
4170 MEMORYSTATUS memst;
4171 MEMORY_STATUS_EX memstex;
4172 double totphys = 0.0;
4173 Lisp_Object ctime, stime, utime, etime, ttime;
4174 double pcpu;
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)
4186 PROCESSENTRY32 pe;
4187 BOOL res;
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)
4195 if (proc_id == 0)
4196 decoded_cmd = build_string ("Idle");
4197 else
4199 /* Decode the command name from locale-specific
4200 encoding. */
4201 cmd_str = make_unibyte_string (pe.szExeFile,
4202 strlen (pe.szExeFile));
4203 decoded_cmd =
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)),
4210 attrs);
4211 attrs = Fcons (Fcons (Qpri, make_number (pe.pcPriClassBase)),
4212 attrs);
4213 attrs = Fcons (Fcons (Qthcount,
4214 make_fixnum_or_float (pe.cntThreads)),
4215 attrs);
4216 found_proc = 1;
4217 break;
4221 CloseHandle (h_snapshot);
4224 if (!found_proc)
4226 UNGCPRO;
4227 return Qnil;
4230 h_proc = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
4231 FALSE, proc_id);
4232 /* If we were denied a handle to the process, try again after
4233 enabling the SeDebugPrivilege in our process. */
4234 if (!h_proc)
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,
4241 FALSE, proc_id);
4242 restore_privilege (&priv_current);
4243 revert_to_self ();
4246 if (h_proc)
4248 result = open_process_token (h_proc, TOKEN_QUERY, &token);
4249 if (result)
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);
4257 if (result)
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,
4264 uname, &ulength,
4265 domain, &dlength,
4266 &user_type);
4267 if (result)
4268 w32_add_to_cache (user_token.User.Sid, euid, uname);
4269 else
4271 strcpy (uname, "unknown");
4272 result = TRUE;
4275 ulength = strlen (uname);
4279 if (result)
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 */
4287 else
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);
4298 if (result)
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);
4305 result =
4306 lookup_account_sid (NULL, group_token.PrimaryGroup,
4307 gname, &glength, NULL, &dlength,
4308 &user_type);
4309 if (result)
4310 w32_add_to_cache (group_token.PrimaryGroup,
4311 egid, gname);
4312 else
4314 strcpy (gname, "None");
4315 result = TRUE;
4318 glength = strlen (gname);
4322 xfree (buf);
4324 if (!result)
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
4330 by the system. */
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
4340 user. */
4341 else if (GetUserName (uname, &ulength))
4343 if (xstrcasecmp ("administrator", uname) == 0)
4344 euid = 0;
4345 else
4346 euid = 123;
4347 egid = euid;
4348 strcpy (gname, "None");
4349 glength = strlen (gname);
4350 ulength = strlen (uname);
4352 else
4354 euid = 123;
4355 egid = 123;
4356 strcpy (uname, "administrator");
4357 ulength = strlen (uname);
4358 strcpy (gname, "None");
4359 glength = strlen (gname);
4361 if (token)
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)),
4369 attrs);
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)),
4374 attrs);
4376 if (global_memory_status_ex (&memstex))
4377 #if __GNUC__ || (defined (_MSC_VER) && _MSC_VER >= 1300)
4378 totphys = memstex.ullTotalPhys / 1024.0;
4379 #else
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;
4393 if (h_proc
4394 && get_process_memory_info (h_proc, (PROCESS_MEMORY_COUNTERS *)&mem_ex,
4395 sizeof (mem_ex)))
4397 DWORD rss = mem_ex.WorkingSetSize / 1024;
4399 attrs = Fcons (Fcons (Qmajflt,
4400 make_fixnum_or_float (mem_ex.PageFaultCount)),
4401 attrs);
4402 attrs = Fcons (Fcons (Qvsize,
4403 make_fixnum_or_float (mem_ex.PrivateUsage / 1024)),
4404 attrs);
4405 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (rss)), attrs);
4406 if (totphys)
4407 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
4409 else if (h_proc
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)),
4416 attrs);
4417 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (rss)), attrs);
4418 if (totphys)
4419 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
4421 else if (h_proc
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);
4427 if (totphys)
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. */
4443 if (h_proc)
4444 CloseHandle (h_proc);
4445 UNGCPRO;
4446 return attrs;
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,
4486 int * namelen);
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
4497 #endif
4499 HANDLE winsock_lib;
4500 static int winsock_inuse;
4502 BOOL
4503 term_winsock (void)
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))
4514 winsock_lib = NULL;
4515 return TRUE;
4518 return FALSE;
4521 BOOL
4522 init_winsock (int load_now)
4524 WSADATA winsockData;
4526 if (winsock_lib != NULL)
4527 return TRUE;
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) \
4541 goto fail;
4543 LOAD_PROC (WSAStartup);
4544 LOAD_PROC (WSASetLastError);
4545 LOAD_PROC (WSAGetLastError);
4546 LOAD_PROC (WSAEventSelect);
4547 LOAD_PROC (WSACreateEvent);
4548 LOAD_PROC (WSACloseEvent);
4549 LOAD_PROC (socket);
4550 LOAD_PROC (bind);
4551 LOAD_PROC (connect);
4552 LOAD_PROC (ioctlsocket);
4553 LOAD_PROC (recv);
4554 LOAD_PROC (send);
4555 LOAD_PROC (closesocket);
4556 LOAD_PROC (shutdown);
4557 LOAD_PROC (htons);
4558 LOAD_PROC (ntohs);
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);
4566 LOAD_PROC (listen);
4567 LOAD_PROC (getsockname);
4568 LOAD_PROC (accept);
4569 LOAD_PROC (recvfrom);
4570 LOAD_PROC (sendto);
4571 #undef LOAD_PROC
4573 /* specify version 1.1 of winsock */
4574 if (pfn_WSAStartup (0x101, &winsockData) == 0)
4576 if (winsockData.wVersion != 0x101)
4577 goto fail;
4579 if (!load_now)
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. */
4587 pfn_WSACleanup ();
4588 FreeLibrary (winsock_lib);
4589 winsock_lib = NULL;
4591 winsock_inuse = 0;
4592 return TRUE;
4595 fail:
4596 FreeLibrary (winsock_lib);
4597 winsock_lib = NULL;
4600 return FALSE;
4604 int h_errno = 0;
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> */
4609 static void
4610 set_errno (void)
4612 if (winsock_lib == NULL)
4613 h_errno = EINVAL;
4614 else
4615 h_errno = pfn_WSAGetLastError ();
4617 switch (h_errno)
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;
4628 errno = h_errno;
4631 static void
4632 check_errno (void)
4634 if (h_errno == 0 && winsock_lib != NULL)
4635 pfn_WSASetLastError (0);
4638 /* Extend strerror to handle the winsock-specific error codes. */
4639 struct {
4640 int errnum;
4641 char * msg;
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"},
4692 #ifdef WSAENOMORE
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 */
4704 #endif
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"},
4711 {-1, NULL}
4714 char *
4715 sys_strerror (int error_no)
4717 int i;
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);
4728 return unknown_msg;
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)
4742 SOCKET s;
4744 if (winsock_lib == NULL)
4746 h_errno = ENETDOWN;
4747 return INVALID_SOCKET;
4750 check_errno ();
4752 /* call the real socket function */
4753 s = pfn_socket (af, type, protocol);
4755 if (s != INVALID_SOCKET)
4756 return socket_to_fd (s);
4758 set_errno ();
4759 return -1;
4762 /* Convert a SOCKET to a file descriptor. */
4763 static int
4764 socket_to_fd (SOCKET s)
4766 int fd;
4767 child_process * cp;
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);
4777 if (fd >= 0)
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);
4793 else
4795 HANDLE parent = GetCurrentProcess ();
4796 HANDLE new_s = INVALID_HANDLE_VALUE;
4798 if (DuplicateHandle (parent,
4799 (HANDLE) s,
4800 parent,
4801 &new_s,
4803 FALSE,
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);
4814 s = (SOCKET) new_s;
4816 else
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;
4828 cp = new_child ();
4829 if (cp)
4831 cp->fd = fd;
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));
4838 abort ();
4841 fd_info[ fd ].cp = cp;
4843 /* success! */
4844 winsock_inuse++; /* count open sockets */
4845 return fd;
4848 /* clean up */
4849 _close (fd);
4851 pfn_closesocket (s);
4852 h_errno = EMFILE;
4853 return -1;
4857 sys_bind (int s, const struct sockaddr * addr, int namelen)
4859 if (winsock_lib == NULL)
4861 h_errno = ENOTSOCK;
4862 return SOCKET_ERROR;
4865 check_errno ();
4866 if (fd_info[s].flags & FILE_SOCKET)
4868 int rc = pfn_bind (SOCK_HANDLE (s), addr, namelen);
4869 if (rc == SOCKET_ERROR)
4870 set_errno ();
4871 return rc;
4873 h_errno = ENOTSOCK;
4874 return SOCKET_ERROR;
4878 sys_connect (int s, const struct sockaddr * name, int namelen)
4880 if (winsock_lib == NULL)
4882 h_errno = ENOTSOCK;
4883 return SOCKET_ERROR;
4886 check_errno ();
4887 if (fd_info[s].flags & FILE_SOCKET)
4889 int rc = pfn_connect (SOCK_HANDLE (s), name, namelen);
4890 if (rc == SOCKET_ERROR)
4891 set_errno ();
4892 return rc;
4894 h_errno = ENOTSOCK;
4895 return SOCKET_ERROR;
4898 u_short
4899 sys_htons (u_short hostshort)
4901 return (winsock_lib != NULL) ?
4902 pfn_htons (hostshort) : hostshort;
4905 u_short
4906 sys_ntohs (u_short netshort)
4908 return (winsock_lib != NULL) ?
4909 pfn_ntohs (netshort) : netshort;
4912 unsigned long
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);
4928 h_errno = EFAULT;
4929 return SOCKET_ERROR;
4932 struct hostent *
4933 sys_gethostbyname (const char * name)
4935 struct hostent * host;
4937 if (winsock_lib == NULL)
4939 h_errno = ENETDOWN;
4940 return NULL;
4943 check_errno ();
4944 host = pfn_gethostbyname (name);
4945 if (!host)
4946 set_errno ();
4947 return host;
4950 struct servent *
4951 sys_getservbyname (const char * name, const char * proto)
4953 struct servent * serv;
4955 if (winsock_lib == NULL)
4957 h_errno = ENETDOWN;
4958 return NULL;
4961 check_errno ();
4962 serv = pfn_getservbyname (name, proto);
4963 if (!serv)
4964 set_errno ();
4965 return serv;
4969 sys_getpeername (int s, struct sockaddr *addr, int * namelen)
4971 if (winsock_lib == NULL)
4973 h_errno = ENETDOWN;
4974 return SOCKET_ERROR;
4977 check_errno ();
4978 if (fd_info[s].flags & FILE_SOCKET)
4980 int rc = pfn_getpeername (SOCK_HANDLE (s), addr, namelen);
4981 if (rc == SOCKET_ERROR)
4982 set_errno ();
4983 return rc;
4985 h_errno = ENOTSOCK;
4986 return SOCKET_ERROR;
4990 sys_shutdown (int s, int how)
4992 if (winsock_lib == NULL)
4994 h_errno = ENETDOWN;
4995 return SOCKET_ERROR;
4998 check_errno ();
4999 if (fd_info[s].flags & FILE_SOCKET)
5001 int rc = pfn_shutdown (SOCK_HANDLE (s), how);
5002 if (rc == SOCKET_ERROR)
5003 set_errno ();
5004 return rc;
5006 h_errno = ENOTSOCK;
5007 return SOCKET_ERROR;
5011 sys_setsockopt (int s, int level, int optname, const void * optval, int optlen)
5013 if (winsock_lib == NULL)
5015 h_errno = ENETDOWN;
5016 return SOCKET_ERROR;
5019 check_errno ();
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)
5025 set_errno ();
5026 return rc;
5028 h_errno = ENOTSOCK;
5029 return SOCKET_ERROR;
5033 sys_listen (int s, int backlog)
5035 if (winsock_lib == NULL)
5037 h_errno = ENETDOWN;
5038 return SOCKET_ERROR;
5041 check_errno ();
5042 if (fd_info[s].flags & FILE_SOCKET)
5044 int rc = pfn_listen (SOCK_HANDLE (s), backlog);
5045 if (rc == SOCKET_ERROR)
5046 set_errno ();
5047 else
5048 fd_info[s].flags |= FILE_LISTEN;
5049 return rc;
5051 h_errno = ENOTSOCK;
5052 return SOCKET_ERROR;
5056 sys_getsockname (int s, struct sockaddr * name, int * namelen)
5058 if (winsock_lib == NULL)
5060 h_errno = ENETDOWN;
5061 return SOCKET_ERROR;
5064 check_errno ();
5065 if (fd_info[s].flags & FILE_SOCKET)
5067 int rc = pfn_getsockname (SOCK_HANDLE (s), name, namelen);
5068 if (rc == SOCKET_ERROR)
5069 set_errno ();
5070 return rc;
5072 h_errno = ENOTSOCK;
5073 return SOCKET_ERROR;
5077 sys_accept (int s, struct sockaddr * addr, int * addrlen)
5079 if (winsock_lib == NULL)
5081 h_errno = ENETDOWN;
5082 return -1;
5085 check_errno ();
5086 if (fd_info[s].flags & FILE_LISTEN)
5088 SOCKET t = pfn_accept (SOCK_HANDLE (s), addr, addrlen);
5089 int fd = -1;
5090 if (t == INVALID_SOCKET)
5091 set_errno ();
5092 else
5093 fd = socket_to_fd (t);
5095 fd_info[s].cp->status = STATUS_READ_ACKNOWLEDGED;
5096 ResetEvent (fd_info[s].cp->char_avail);
5097 return fd;
5099 h_errno = ENOTSOCK;
5100 return -1;
5104 sys_recvfrom (int s, char * buf, int len, int flags,
5105 struct sockaddr * from, int * fromlen)
5107 if (winsock_lib == NULL)
5109 h_errno = ENETDOWN;
5110 return SOCKET_ERROR;
5113 check_errno ();
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)
5118 set_errno ();
5119 return rc;
5121 h_errno = ENOTSOCK;
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)
5131 h_errno = ENETDOWN;
5132 return SOCKET_ERROR;
5135 check_errno ();
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)
5140 set_errno ();
5141 return rc;
5143 h_errno = ENOTSOCK;
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)
5154 h_errno = ENETDOWN;
5155 return -1;
5158 check_errno ();
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)
5166 set_errno ();
5167 /* Keep track of the fact that we set this to non-blocking. */
5168 fd_info[s].flags |= FILE_NDELAY;
5169 return rc;
5171 else
5173 h_errno = EINVAL;
5174 return SOCKET_ERROR;
5177 h_errno = ENOTSOCK;
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. */
5186 sys_close (int fd)
5188 int rc;
5190 if (fd < 0)
5192 errno = EBADF;
5193 return -1;
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 */
5205 int i;
5206 for (i = 0; i < MAXDESC; i++)
5208 if (i == fd)
5209 continue;
5210 if (fd_info[i].cp == cp)
5211 break;
5213 if (i == MAXDESC)
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 */
5224 delete_child (cp);
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. */
5233 rc = _close (fd);
5235 if (rc == 0 && fd < MAXDESC)
5236 fd_info[fd].flags = 0;
5238 return rc;
5242 sys_dup (int fd)
5244 int new_fd;
5246 new_fd = _dup (fd);
5247 if (new_fd >= 0 && new_fd < MAXDESC)
5249 /* duplicate our internal info as well */
5250 fd_info[new_fd] = fd_info[fd];
5252 return new_fd;
5256 sys_dup2 (int src, int dst)
5258 int rc;
5260 if (dst < 0 || dst >= MAXDESC)
5262 errno = EBADF;
5263 return -1;
5266 /* make sure we close the destination first if it's a pipe or socket */
5267 if (src != dst && fd_info[dst].flags != 0)
5268 sys_close (dst);
5270 rc = _dup2 (src, dst);
5271 if (rc == 0)
5273 /* duplicate our internal info as well */
5274 fd_info[dst] = fd_info[src];
5276 return rc;
5279 /* Unix pipe() has only one arg */
5281 sys_pipe (int * phandles)
5283 int rc;
5284 unsigned flags;
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
5289 if required. */
5290 rc = _pipe (phandles, 0, _O_NOINHERIT | _O_BINARY);
5292 if (rc == 0)
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]);
5300 rc = -1;
5302 else
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;
5312 return rc;
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)
5320 child_process * cp;
5321 int rc;
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));
5335 abort ();
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. */
5351 if (rc > 0)
5353 int wait = w32_pipe_read_delay;
5355 if (wait > 0)
5356 Sleep (wait);
5357 else if (wait < 0)
5358 while (++wait <= 0)
5359 /* Yield remainder of our time slice, effectively giving a
5360 temporary priority boost to the child process. */
5361 Sleep (0);
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;
5368 COMMTIMEOUTS ct;
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)
5398 nblock = 1;
5399 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
5403 if (rc == sizeof (char))
5404 cp->status = STATUS_READ_SUCCEEDED;
5405 else
5406 cp->status = STATUS_READ_FAILED;
5408 return cp->status;
5412 _sys_wait_accept (int fd)
5414 HANDLE hEv;
5415 child_process * cp;
5416 int rc;
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);
5439 return cp->status;
5443 sys_read (int fd, char * buffer, unsigned int count)
5445 int nchars;
5446 int to_read;
5447 DWORD waiting;
5448 char * orig_buffer = buffer;
5450 if (fd < 0)
5452 errno = EBADF;
5453 return -1;
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)
5462 errno = EBADF;
5463 return -1;
5466 nchars = 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 ();
5472 *buffer++ = 0x0d;
5473 count--;
5474 nchars++;
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. */
5483 if (cp)
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 */
5492 if (nchars <= 0)
5493 fd_info[fd].flags |= FILE_AT_EOF;
5494 return nchars;
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;
5500 return -1;
5502 case STATUS_READ_SUCCEEDED:
5503 /* consume read-ahead char */
5504 *buffer++ = cp->chr;
5505 count--;
5506 nchars++;
5507 cp->status = STATUS_READ_ACKNOWLEDGED;
5508 ResetEvent (cp->char_avail);
5510 case STATUS_READ_ACKNOWLEDGED:
5511 break;
5513 default:
5514 DebPrint (("sys_read: bad status %d\n", current_status));
5515 errno = EBADF;
5516 return -1;
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);
5524 if (to_read > 0)
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;
5531 int rc = 0;
5532 COMMTIMEOUTS ct;
5534 if (count > 0)
5536 /* Configure timeouts for non-blocking read. */
5537 if (!GetCommTimeouts (hnd, &ct))
5539 errno = EIO;
5540 return -1;
5542 ct.ReadIntervalTimeout = MAXDWORD;
5543 ct.ReadTotalTimeoutMultiplier = 0;
5544 ct.ReadTotalTimeoutConstant = 0;
5545 if (!SetCommTimeouts (hnd, &ct))
5547 errno = EIO;
5548 return -1;
5551 if (!ResetEvent (ovl->hEvent))
5553 errno = EIO;
5554 return -1;
5556 if (!ReadFile (hnd, buffer, count, (DWORD*) &rc, ovl))
5558 if (GetLastError () != ERROR_IO_PENDING)
5560 errno = EIO;
5561 return -1;
5563 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &rc, TRUE))
5565 errno = EIO;
5566 return -1;
5569 nchars += rc;
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;
5581 return -1;
5584 if (waiting)
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)));
5592 set_errno ();
5593 return -1;
5595 nchars += res;
5599 else
5601 int nread = _read (fd, buffer, count);
5602 if (nread >= 0)
5603 nchars += nread;
5604 else if (nchars == 0)
5605 nchars = nread;
5608 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;
5621 nchars--;
5625 else
5626 nchars = _read (fd, buffer, count);
5628 return nchars;
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)
5638 int nchars;
5640 if (fd < 0)
5642 errno = EBADF;
5643 return -1;
5646 if (fd < MAXDESC && fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET | FILE_SERIAL))
5648 if ((fd_info[fd].flags & FILE_WRITE) == 0)
5650 errno = EBADF;
5651 return -1;
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;
5660 int nbytes = count;
5662 while (1)
5664 unsigned char *next;
5665 /* copy next line or remaining bytes */
5666 next = _memccpy (dst, src, '\n', nbytes);
5667 if (next)
5669 /* copied one line ending with '\n' */
5670 int copied = next - dst;
5671 nbytes -= copied;
5672 src += copied;
5673 /* insert '\r' before '\n' */
5674 next[-1] = '\r';
5675 next[0] = '\n';
5676 dst = next + 1;
5677 count++;
5679 else
5680 /* copied remaining partial line -> now finished */
5681 break;
5683 buffer = tmpbuf;
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 };
5692 DWORD active = 0;
5694 if (!WriteFile (hnd, buffer, count, (DWORD*) &nchars, ovl))
5696 if (GetLastError () != ERROR_IO_PENDING)
5698 errno = EIO;
5699 return -1;
5701 if (detect_input_pending ())
5702 active = MsgWaitForMultipleObjects (2, wait_hnd, FALSE, INFINITE,
5703 QS_ALLINPUT);
5704 else
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);
5710 CancelIo (hnd);
5711 errno = EIO;
5712 return -1;
5714 if (active == WAIT_OBJECT_0 + 1
5715 && !GetOverlappedResult (hnd, ovl, (DWORD*) &nchars, TRUE))
5717 errno = EIO;
5718 return -1;
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)
5738 nblock = 1;
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)));
5746 set_errno ();
5749 else
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;
5760 nchars = 0;
5761 while (count > 0)
5763 unsigned this_chunk = count < chunk ? count : chunk;
5764 int n = _write (fd, p, this_chunk);
5766 nchars += n;
5767 if (n < 0)
5769 nchars = n;
5770 break;
5772 else if (n < this_chunk)
5773 break;
5774 count -= n;
5775 p += n;
5779 return nchars;
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. */
5788 struct tm *
5789 sys_localtime (const time_t *t)
5791 tzset ();
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. */
5813 HMODULE
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);
5825 if (CONSP (dlls))
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];
5832 DWORD len;
5834 len = GetModuleFileNameA (library_dll, name, sizeof (name));
5835 found = Fcons (XCAR (dlls),
5836 (len > 0)
5837 /* Possibly truncated */
5838 ? make_specified_string (name, -1, len, 1)
5839 : Qnil);
5840 break;
5844 Fput (library_id, QCloaded_from, found);
5847 return library_dll;
5851 static void
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
5860 loadup.el. */
5861 && NILP (Vpurify_flag))
5863 Lisp_Object objs[2];
5864 Lisp_Object full_load_path;
5865 Lisp_Object init_file;
5866 int fd;
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);
5873 if (fd < 0)
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));
5882 sprintf (buffer,
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"
5886 "\n%s\n\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);
5892 MessageBox (NULL,
5893 buffer,
5894 "Emacs Abort Dialog",
5895 MB_OK | MB_ICONEXCLAMATION | MB_TASKMODAL);
5896 /* Use the low-level Emacs abort. */
5897 #undef abort
5898 abort ();
5900 else
5902 _close (fd);
5907 void
5908 term_ntproc (void)
5910 /* shutdown the socket interface if necessary */
5911 term_winsock ();
5913 term_w32select ();
5916 void
5917 init_ntproc (void)
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. */
5928 winsock_lib = NULL;
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. */
5936 HANDLE parent;
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),
5947 parent,
5948 &stdin_save,
5950 FALSE,
5951 DUPLICATE_SAME_ACCESS);
5953 DuplicateHandle (parent,
5954 GetStdHandle (STD_OUTPUT_HANDLE),
5955 parent,
5956 &stdout_save,
5958 FALSE,
5959 DUPLICATE_SAME_ACCESS);
5961 DuplicateHandle (parent,
5962 GetStdHandle (STD_ERROR_HANDLE),
5963 parent,
5964 &stderr_save,
5966 FALSE,
5967 DUPLICATE_SAME_ACCESS);
5969 fclose (stdin);
5970 fclose (stdout);
5971 fclose (stderr);
5973 if (stdin_save != INVALID_HANDLE_VALUE)
5974 _open_osfhandle ((long) stdin_save, O_TEXT);
5975 else
5976 _open ("nul", O_TEXT | O_NOINHERIT | O_RDONLY);
5977 _fdopen (0, "r");
5979 if (stdout_save != INVALID_HANDLE_VALUE)
5980 _open_osfhandle ((long) stdout_save, O_TEXT);
5981 else
5982 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
5983 _fdopen (1, "w");
5985 if (stderr_save != INVALID_HANDLE_VALUE)
5986 _open_osfhandle ((long) stderr_save, O_TEXT);
5987 else
5988 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
5989 _fdopen (2, "w");
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);
6008 (*drive)++;
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.
6023 static BOOL WINAPI
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. */
6036 return FALSE;
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).
6044 void
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)
6097 HANDLE hnd;
6098 child_process *cp;
6099 int fd = -1;
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);
6106 if (fd == -1)
6107 error ("Could not open %s", port);
6109 cp = new_child ();
6110 if (!cp)
6111 error ("Could not create child process");
6112 cp->fd = fd;
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");
6129 return fd;
6132 /* For serial-process-configure */
6133 void
6134 serial_configure (struct Lisp_Process *p, Lisp_Object contact)
6136 Lisp_Object childp2 = Qnil;
6137 Lisp_Object tem = Qnil;
6138 HANDLE hnd;
6139 DCB dcb;
6140 COMMTIMEOUTS ct;
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");
6164 dcb.fBinary = TRUE;
6165 dcb.fNull = FALSE;
6166 dcb.fAbortOnError = FALSE;
6167 /* dcb.XonLim and dcb.XoffLim are set by GetCommState() */
6168 dcb.ErrorChar = 0;
6169 dcb.EofChar = 0;
6170 dcb.EvtChar = 0;
6172 /* Configure speed. */
6173 if (!NILP (Fplist_member (contact, QCspeed)))
6174 tem = Fplist_get (contact, QCspeed);
6175 else
6176 tem = Fplist_get (p->childp, QCspeed);
6177 CHECK_NUMBER (tem);
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);
6184 else
6185 tem = Fplist_get (p->childp, QCbytesize);
6186 if (NILP (tem))
6187 tem = make_number (8);
6188 CHECK_NUMBER (tem);
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);
6198 else
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;
6205 if (NILP (tem))
6207 summary[1] = 'N';
6209 else if (EQ (tem, Qeven))
6211 summary[1] = 'E';
6212 dcb.fParity = TRUE;
6213 dcb.Parity = EVENPARITY;
6214 dcb.fErrorChar = TRUE;
6216 else if (EQ (tem, Qodd))
6218 summary[1] = 'O';
6219 dcb.fParity = TRUE;
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);
6228 else
6229 tem = Fplist_get (p->childp, QCstopbits);
6230 if (NILP (tem))
6231 tem = make_number (1);
6232 CHECK_NUMBER (tem);
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);
6245 else
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;
6254 dcb.fOutX = FALSE;
6255 dcb.fInX = FALSE;
6256 dcb.fRtsControl = RTS_CONTROL_DISABLE;
6257 dcb.XonChar = 17; /* Control-Q */
6258 dcb.XoffChar = 19; /* Control-S */
6259 if (NILP (tem))
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))
6270 dcb.fOutX = TRUE;
6271 dcb.fInX = TRUE;
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;
6283 #ifdef HAVE_GNUTLS
6285 ssize_t
6286 emacs_gnutls_pull (gnutls_transport_ptr_t p, void* buf, size_t sz)
6288 int n, sc, err;
6289 SELECT_TYPE fdset;
6290 struct timeval timeout;
6291 struct Lisp_Process *process = (struct Lisp_Process *)p;
6292 int fd = process->infd;
6294 for (;;)
6296 n = sys_read (fd, (char*)buf, sz);
6298 if (n >= 0)
6299 return n;
6301 err = errno;
6303 if (err == EWOULDBLOCK)
6305 /* Set a small timeout. */
6306 timeout.tv_sec = 1;
6307 timeout.tv_usec = 0;
6308 FD_ZERO (&fdset);
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,
6313 &timeout, NULL);
6315 if (sc > 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)
6321 err = EAGAIN;
6322 else
6323 err = errno; /* Other errors are just passed on. */
6326 emacs_gnutls_transport_set_errno (process->gnutls_state, err);
6328 return -1;
6332 ssize_t
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. */
6340 if (n >= 0)
6341 return n;
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);
6348 return -1;
6350 #endif /* HAVE_GNUTLS */
6352 /* end of w32.c */