* src/editfns.c (region_limit): Clip to narrowing.
[emacs/old-mirror.git] / src / w32.c
blobb0272c6487164304a99b9b355b6d84b118d3c459
1 /* Utility and Unix shadow routines for GNU Emacs on the Microsoft W32 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, and we want to
782 force our real wd to be where emacs.exe is to avoid unnecessary
783 conflicts when trying to rename or delete directories. */
784 strcpy (dir, startup_dir);
785 return dir;
786 #endif
789 /* Emulate getloadavg. */
791 struct load_sample {
792 time_t sample_time;
793 ULONGLONG idle;
794 ULONGLONG kernel;
795 ULONGLONG user;
798 /* Number of processors on this machine. */
799 static unsigned num_of_processors;
801 /* We maintain 1-sec samples for the last 16 minutes in a circular buffer. */
802 static struct load_sample samples[16*60];
803 static int first_idx = -1, last_idx = -1;
804 static int max_idx = sizeof (samples) / sizeof (samples[0]);
806 static int
807 buf_next (int from)
809 int next_idx = from + 1;
811 if (next_idx >= max_idx)
812 next_idx = 0;
814 return next_idx;
817 static int
818 buf_prev (int from)
820 int prev_idx = from - 1;
822 if (prev_idx < 0)
823 prev_idx = max_idx - 1;
825 return prev_idx;
828 static void
829 sample_system_load (ULONGLONG *idle, ULONGLONG *kernel, ULONGLONG *user)
831 SYSTEM_INFO sysinfo;
832 FILETIME ft_idle, ft_user, ft_kernel;
834 /* Initialize the number of processors on this machine. */
835 if (num_of_processors <= 0)
837 get_native_system_info (&sysinfo);
838 num_of_processors = sysinfo.dwNumberOfProcessors;
839 if (num_of_processors <= 0)
841 GetSystemInfo (&sysinfo);
842 num_of_processors = sysinfo.dwNumberOfProcessors;
844 if (num_of_processors <= 0)
845 num_of_processors = 1;
848 /* TODO: Take into account threads that are ready to run, by
849 sampling the "\System\Processor Queue Length" performance
850 counter. The code below accounts only for threads that are
851 actually running. */
853 if (get_system_times (&ft_idle, &ft_kernel, &ft_user))
855 ULARGE_INTEGER uidle, ukernel, uuser;
857 memcpy (&uidle, &ft_idle, sizeof (ft_idle));
858 memcpy (&ukernel, &ft_kernel, sizeof (ft_kernel));
859 memcpy (&uuser, &ft_user, sizeof (ft_user));
860 *idle = uidle.QuadPart;
861 *kernel = ukernel.QuadPart;
862 *user = uuser.QuadPart;
864 else
866 *idle = 0;
867 *kernel = 0;
868 *user = 0;
872 /* Produce the load average for a given time interval, using the
873 samples in the samples[] array. WHICH can be 0, 1, or 2, meaning
874 1-minute, 5-minute, or 15-minute average, respectively. */
875 static double
876 getavg (int which)
878 double retval = -1.0;
879 double tdiff;
880 int idx;
881 double span = (which == 0 ? 1.0 : (which == 1 ? 5.0 : 15.0)) * 60;
882 time_t now = samples[last_idx].sample_time;
884 if (first_idx != last_idx)
886 for (idx = buf_prev (last_idx); ; idx = buf_prev (idx))
888 tdiff = difftime (now, samples[idx].sample_time);
889 if (tdiff >= span - 2*DBL_EPSILON*now)
891 long double sys =
892 samples[last_idx].kernel + samples[last_idx].user
893 - (samples[idx].kernel + samples[idx].user);
894 long double idl = samples[last_idx].idle - samples[idx].idle;
896 retval = (1.0 - idl / sys) * num_of_processors;
897 break;
899 if (idx == first_idx)
900 break;
904 return retval;
908 getloadavg (double loadavg[], int nelem)
910 int elem;
911 ULONGLONG idle, kernel, user;
912 time_t now = time (NULL);
914 /* Store another sample. We ignore samples that are less than 1 sec
915 apart. */
916 if (difftime (now, samples[last_idx].sample_time) >= 1.0 - 2*DBL_EPSILON*now)
918 sample_system_load (&idle, &kernel, &user);
919 last_idx = buf_next (last_idx);
920 samples[last_idx].sample_time = now;
921 samples[last_idx].idle = idle;
922 samples[last_idx].kernel = kernel;
923 samples[last_idx].user = user;
924 /* If the buffer has more that 15 min worth of samples, discard
925 the old ones. */
926 if (first_idx == -1)
927 first_idx = last_idx;
928 while (first_idx != last_idx
929 && (difftime (now, samples[first_idx].sample_time)
930 >= 15.0*60 + 2*DBL_EPSILON*now))
931 first_idx = buf_next (first_idx);
934 for (elem = 0; elem < nelem; elem++)
936 double avg = getavg (elem);
938 if (avg < 0)
939 break;
940 loadavg[elem] = avg;
943 return elem;
946 /* Emulate getpwuid, getpwnam and others. */
948 #define PASSWD_FIELD_SIZE 256
950 static char dflt_passwd_name[PASSWD_FIELD_SIZE];
951 static char dflt_passwd_passwd[PASSWD_FIELD_SIZE];
952 static char dflt_passwd_gecos[PASSWD_FIELD_SIZE];
953 static char dflt_passwd_dir[PASSWD_FIELD_SIZE];
954 static char dflt_passwd_shell[PASSWD_FIELD_SIZE];
956 static struct passwd dflt_passwd =
958 dflt_passwd_name,
959 dflt_passwd_passwd,
963 dflt_passwd_gecos,
964 dflt_passwd_dir,
965 dflt_passwd_shell,
968 static char dflt_group_name[GNLEN+1];
970 static struct group dflt_group =
972 /* When group information is not available, we return this as the
973 group for all files. */
974 dflt_group_name,
978 unsigned
979 getuid (void)
981 return dflt_passwd.pw_uid;
984 unsigned
985 geteuid (void)
987 /* I could imagine arguing for checking to see whether the user is
988 in the Administrators group and returning a UID of 0 for that
989 case, but I don't know how wise that would be in the long run. */
990 return getuid ();
993 unsigned
994 getgid (void)
996 return dflt_passwd.pw_gid;
999 unsigned
1000 getegid (void)
1002 return getgid ();
1005 struct passwd *
1006 getpwuid (unsigned uid)
1008 if (uid == dflt_passwd.pw_uid)
1009 return &dflt_passwd;
1010 return NULL;
1013 struct group *
1014 getgrgid (gid_t gid)
1016 return &dflt_group;
1019 struct passwd *
1020 getpwnam (char *name)
1022 struct passwd *pw;
1024 pw = getpwuid (getuid ());
1025 if (!pw)
1026 return pw;
1028 if (xstrcasecmp (name, pw->pw_name))
1029 return NULL;
1031 return pw;
1034 static void
1035 init_user_info (void)
1037 /* Find the user's real name by opening the process token and
1038 looking up the name associated with the user-sid in that token.
1040 Use the relative portion of the identifier authority value from
1041 the user-sid as the user id value (same for group id using the
1042 primary group sid from the process token). */
1044 char uname[UNLEN+1], gname[GNLEN+1], domain[1025];
1045 DWORD ulength = sizeof (uname), dlength = sizeof (domain), needed;
1046 DWORD glength = sizeof (gname);
1047 HANDLE token = NULL;
1048 SID_NAME_USE user_type;
1049 unsigned char *buf = NULL;
1050 DWORD blen = 0;
1051 TOKEN_USER user_token;
1052 TOKEN_PRIMARY_GROUP group_token;
1053 BOOL result;
1055 result = open_process_token (GetCurrentProcess (), TOKEN_QUERY, &token);
1056 if (result)
1058 result = get_token_information (token, TokenUser, NULL, 0, &blen);
1059 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
1061 buf = xmalloc (blen);
1062 result = get_token_information (token, TokenUser,
1063 (LPVOID)buf, blen, &needed);
1064 if (result)
1066 memcpy (&user_token, buf, sizeof (user_token));
1067 result = lookup_account_sid (NULL, user_token.User.Sid,
1068 uname, &ulength,
1069 domain, &dlength, &user_type);
1072 else
1073 result = FALSE;
1075 if (result)
1077 strcpy (dflt_passwd.pw_name, uname);
1078 /* Determine a reasonable uid value. */
1079 if (xstrcasecmp ("administrator", uname) == 0)
1081 dflt_passwd.pw_uid = 500; /* well-known Administrator uid */
1082 dflt_passwd.pw_gid = 513; /* well-known None gid */
1084 else
1086 /* Use the last sub-authority value of the RID, the relative
1087 portion of the SID, as user/group ID. */
1088 dflt_passwd.pw_uid = get_rid (user_token.User.Sid);
1090 /* Get group id and name. */
1091 result = get_token_information (token, TokenPrimaryGroup,
1092 (LPVOID)buf, blen, &needed);
1093 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
1095 buf = xrealloc (buf, blen = needed);
1096 result = get_token_information (token, TokenPrimaryGroup,
1097 (LPVOID)buf, blen, &needed);
1099 if (result)
1101 memcpy (&group_token, buf, sizeof (group_token));
1102 dflt_passwd.pw_gid = get_rid (group_token.PrimaryGroup);
1103 dlength = sizeof (domain);
1104 /* If we can get at the real Primary Group name, use that.
1105 Otherwise, the default group name was already set to
1106 "None" in globals_of_w32. */
1107 if (lookup_account_sid (NULL, group_token.PrimaryGroup,
1108 gname, &glength, NULL, &dlength,
1109 &user_type))
1110 strcpy (dflt_group_name, gname);
1112 else
1113 dflt_passwd.pw_gid = dflt_passwd.pw_uid;
1116 /* If security calls are not supported (presumably because we
1117 are running under Windows 9X), fallback to this: */
1118 else if (GetUserName (uname, &ulength))
1120 strcpy (dflt_passwd.pw_name, uname);
1121 if (xstrcasecmp ("administrator", uname) == 0)
1122 dflt_passwd.pw_uid = 0;
1123 else
1124 dflt_passwd.pw_uid = 123;
1125 dflt_passwd.pw_gid = dflt_passwd.pw_uid;
1127 else
1129 strcpy (dflt_passwd.pw_name, "unknown");
1130 dflt_passwd.pw_uid = 123;
1131 dflt_passwd.pw_gid = 123;
1133 dflt_group.gr_gid = dflt_passwd.pw_gid;
1135 /* Ensure HOME and SHELL are defined. */
1136 if (getenv ("HOME") == NULL)
1137 abort ();
1138 if (getenv ("SHELL") == NULL)
1139 abort ();
1141 /* Set dir and shell from environment variables. */
1142 strcpy (dflt_passwd.pw_dir, getenv ("HOME"));
1143 strcpy (dflt_passwd.pw_shell, getenv ("SHELL"));
1145 xfree (buf);
1146 if (token)
1147 CloseHandle (token);
1151 random (void)
1153 /* rand () on NT gives us 15 random bits...hack together 30 bits. */
1154 return ((rand () << 15) | rand ());
1157 void
1158 srandom (int seed)
1160 srand (seed);
1164 /* Normalize filename by converting all path separators to
1165 the specified separator. Also conditionally convert upper
1166 case path name components to lower case. */
1168 static void
1169 normalize_filename (register char *fp, char path_sep)
1171 char sep;
1172 char *elem;
1174 /* Always lower-case drive letters a-z, even if the filesystem
1175 preserves case in filenames.
1176 This is so filenames can be compared by string comparison
1177 functions that are case-sensitive. Even case-preserving filesystems
1178 do not distinguish case in drive letters. */
1179 if (fp[1] == ':' && *fp >= 'A' && *fp <= 'Z')
1181 *fp += 'a' - 'A';
1182 fp += 2;
1185 if (NILP (Vw32_downcase_file_names))
1187 while (*fp)
1189 if (*fp == '/' || *fp == '\\')
1190 *fp = path_sep;
1191 fp++;
1193 return;
1196 sep = path_sep; /* convert to this path separator */
1197 elem = fp; /* start of current path element */
1199 do {
1200 if (*fp >= 'a' && *fp <= 'z')
1201 elem = 0; /* don't convert this element */
1203 if (*fp == 0 || *fp == ':')
1205 sep = *fp; /* restore current separator (or 0) */
1206 *fp = '/'; /* after conversion of this element */
1209 if (*fp == '/' || *fp == '\\')
1211 if (elem && elem != fp)
1213 *fp = 0; /* temporary end of string */
1214 _strlwr (elem); /* while we convert to lower case */
1216 *fp = sep; /* convert (or restore) path separator */
1217 elem = fp + 1; /* next element starts after separator */
1218 sep = path_sep;
1220 } while (*fp++);
1223 /* Destructively turn backslashes into slashes. */
1224 void
1225 dostounix_filename (register char *p)
1227 normalize_filename (p, '/');
1230 /* Destructively turn slashes into backslashes. */
1231 void
1232 unixtodos_filename (register char *p)
1234 normalize_filename (p, '\\');
1237 /* Remove all CR's that are followed by a LF.
1238 (From msdos.c...probably should figure out a way to share it,
1239 although this code isn't going to ever change.) */
1240 static int
1241 crlf_to_lf (register int n, register unsigned char *buf)
1243 unsigned char *np = buf;
1244 unsigned char *startp = buf;
1245 unsigned char *endp = buf + n;
1247 if (n == 0)
1248 return n;
1249 while (buf < endp - 1)
1251 if (*buf == 0x0d)
1253 if (*(++buf) != 0x0a)
1254 *np++ = 0x0d;
1256 else
1257 *np++ = *buf++;
1259 if (buf < endp)
1260 *np++ = *buf++;
1261 return np - startp;
1264 /* Parse the root part of file name, if present. Return length and
1265 optionally store pointer to char after root. */
1266 static int
1267 parse_root (char * name, char ** pPath)
1269 char * start = name;
1271 if (name == NULL)
1272 return 0;
1274 /* find the root name of the volume if given */
1275 if (isalpha (name[0]) && name[1] == ':')
1277 /* skip past drive specifier */
1278 name += 2;
1279 if (IS_DIRECTORY_SEP (name[0]))
1280 name++;
1282 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
1284 int slashes = 2;
1285 name += 2;
1288 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
1289 break;
1290 name++;
1292 while ( *name );
1293 if (IS_DIRECTORY_SEP (name[0]))
1294 name++;
1297 if (pPath)
1298 *pPath = name;
1300 return name - start;
1303 /* Get long base name for name; name is assumed to be absolute. */
1304 static int
1305 get_long_basename (char * name, char * buf, int size)
1307 WIN32_FIND_DATA find_data;
1308 HANDLE dir_handle;
1309 int len = 0;
1311 /* must be valid filename, no wild cards or other invalid characters */
1312 if (_mbspbrk (name, "*?|<>\""))
1313 return 0;
1315 dir_handle = FindFirstFile (name, &find_data);
1316 if (dir_handle != INVALID_HANDLE_VALUE)
1318 if ((len = strlen (find_data.cFileName)) < size)
1319 memcpy (buf, find_data.cFileName, len + 1);
1320 else
1321 len = 0;
1322 FindClose (dir_handle);
1324 return len;
1327 /* Get long name for file, if possible (assumed to be absolute). */
1328 BOOL
1329 w32_get_long_filename (char * name, char * buf, int size)
1331 char * o = buf;
1332 char * p;
1333 char * q;
1334 char full[ MAX_PATH ];
1335 int len;
1337 len = strlen (name);
1338 if (len >= MAX_PATH)
1339 return FALSE;
1341 /* Use local copy for destructive modification. */
1342 memcpy (full, name, len+1);
1343 unixtodos_filename (full);
1345 /* Copy root part verbatim. */
1346 len = parse_root (full, &p);
1347 memcpy (o, full, len);
1348 o += len;
1349 *o = '\0';
1350 size -= len;
1352 while (p != NULL && *p)
1354 q = p;
1355 p = strchr (q, '\\');
1356 if (p) *p = '\0';
1357 len = get_long_basename (full, o, size);
1358 if (len > 0)
1360 o += len;
1361 size -= len;
1362 if (p != NULL)
1364 *p++ = '\\';
1365 if (size < 2)
1366 return FALSE;
1367 *o++ = '\\';
1368 size--;
1369 *o = '\0';
1372 else
1373 return FALSE;
1376 return TRUE;
1379 static int
1380 is_unc_volume (const char *filename)
1382 const char *ptr = filename;
1384 if (!IS_DIRECTORY_SEP (ptr[0]) || !IS_DIRECTORY_SEP (ptr[1]) || !ptr[2])
1385 return 0;
1387 if (_mbspbrk (ptr + 2, "*?|<>\"\\/"))
1388 return 0;
1390 return 1;
1393 /* Routines that are no-ops on NT but are defined to get Emacs to compile. */
1396 sigsetmask (int signal_mask)
1398 return 0;
1402 sigmask (int sig)
1404 return 0;
1408 sigblock (int sig)
1410 return 0;
1414 sigunblock (int sig)
1416 return 0;
1420 sigemptyset (sigset_t *set)
1422 return 0;
1426 sigaddset (sigset_t *set, int signo)
1428 return 0;
1432 sigfillset (sigset_t *set)
1434 return 0;
1438 sigprocmask (int how, const sigset_t *set, sigset_t *oset)
1440 return 0;
1444 pthread_sigmask (int how, const sigset_t *set, sigset_t *oset)
1446 if (sigprocmask (how, set, oset) == -1)
1447 return EINVAL;
1448 return 0;
1452 setpgrp (int pid, int gid)
1454 return 0;
1458 alarm (int seconds)
1460 return 0;
1463 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
1465 LPBYTE
1466 w32_get_resource (char *key, LPDWORD lpdwtype)
1468 LPBYTE lpvalue;
1469 HKEY hrootkey = NULL;
1470 DWORD cbData;
1472 /* Check both the current user and the local machine to see if
1473 we have any resources. */
1475 if (RegOpenKeyEx (HKEY_CURRENT_USER, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
1477 lpvalue = NULL;
1479 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
1480 && (lpvalue = (LPBYTE) xmalloc (cbData)) != NULL
1481 && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
1483 RegCloseKey (hrootkey);
1484 return (lpvalue);
1487 xfree (lpvalue);
1489 RegCloseKey (hrootkey);
1492 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
1494 lpvalue = NULL;
1496 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
1497 && (lpvalue = (LPBYTE) xmalloc (cbData)) != NULL
1498 && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
1500 RegCloseKey (hrootkey);
1501 return (lpvalue);
1504 xfree (lpvalue);
1506 RegCloseKey (hrootkey);
1509 return (NULL);
1512 char *get_emacs_configuration (void);
1514 void
1515 init_environment (char ** argv)
1517 static const char * const tempdirs[] = {
1518 "$TMPDIR", "$TEMP", "$TMP", "c:/"
1521 int i;
1523 const int imax = sizeof (tempdirs) / sizeof (tempdirs[0]);
1525 /* Make sure they have a usable $TMPDIR. Many Emacs functions use
1526 temporary files and assume "/tmp" if $TMPDIR is unset, which
1527 will break on DOS/Windows. Refuse to work if we cannot find
1528 a directory, not even "c:/", usable for that purpose. */
1529 for (i = 0; i < imax ; i++)
1531 const char *tmp = tempdirs[i];
1533 if (*tmp == '$')
1534 tmp = getenv (tmp + 1);
1535 /* Note that `access' can lie to us if the directory resides on a
1536 read-only filesystem, like CD-ROM or a write-protected floppy.
1537 The only way to be really sure is to actually create a file and
1538 see if it succeeds. But I think that's too much to ask. */
1539 #ifdef _MSC_VER
1540 /* MSVC's _access crashes with D_OK. */
1541 if (tmp && sys_access (tmp, D_OK) == 0)
1542 #else
1543 if (tmp && _access (tmp, D_OK) == 0)
1544 #endif
1546 char * var = alloca (strlen (tmp) + 8);
1547 sprintf (var, "TMPDIR=%s", tmp);
1548 _putenv (strdup (var));
1549 break;
1552 if (i >= imax)
1553 cmd_error_internal
1554 (Fcons (Qerror,
1555 Fcons (build_string ("no usable temporary directories found!!"),
1556 Qnil)),
1557 "While setting TMPDIR: ");
1559 /* Check for environment variables and use registry settings if they
1560 don't exist. Fallback on default values where applicable. */
1562 int i;
1563 LPBYTE lpval;
1564 DWORD dwType;
1565 char locale_name[32];
1566 struct stat ignored;
1567 char default_home[MAX_PATH];
1568 int appdata = 0;
1570 static const struct env_entry
1572 char * name;
1573 char * def_value;
1574 } dflt_envvars[] =
1576 {"HOME", "C:/"},
1577 {"PRELOAD_WINSOCK", NULL},
1578 {"emacs_dir", "C:/emacs"},
1579 {"EMACSLOADPATH", "%emacs_dir%/site-lisp;%emacs_dir%/../site-lisp;%emacs_dir%/lisp;%emacs_dir%/leim"},
1580 {"SHELL", "%emacs_dir%/bin/cmdproxy.exe"},
1581 {"EMACSDATA", "%emacs_dir%/etc"},
1582 {"EMACSPATH", "%emacs_dir%/bin"},
1583 /* We no longer set INFOPATH because Info-default-directory-list
1584 is then ignored. */
1585 /* {"INFOPATH", "%emacs_dir%/info"}, */
1586 {"EMACSDOC", "%emacs_dir%/etc"},
1587 {"TERM", "cmd"},
1588 {"LANG", NULL},
1591 #define N_ENV_VARS sizeof (dflt_envvars)/sizeof (dflt_envvars[0])
1593 /* We need to copy dflt_envvars[] and work on the copy because we
1594 don't want the dumped Emacs to inherit the values of
1595 environment variables we saw during dumping (which could be on
1596 a different system). The defaults above must be left intact. */
1597 struct env_entry env_vars[N_ENV_VARS];
1599 for (i = 0; i < N_ENV_VARS; i++)
1600 env_vars[i] = dflt_envvars[i];
1602 /* For backwards compatibility, check if a .emacs file exists in C:/
1603 If not, then we can try to default to the appdata directory under the
1604 user's profile, which is more likely to be writable. */
1605 if (stat ("C:/.emacs", &ignored) < 0)
1607 HRESULT profile_result;
1608 /* Dynamically load ShGetFolderPath, as it won't exist on versions
1609 of Windows 95 and NT4 that have not been updated to include
1610 MSIE 5. */
1611 ShGetFolderPath_fn get_folder_path;
1612 get_folder_path = (ShGetFolderPath_fn)
1613 GetProcAddress (GetModuleHandle ("shell32.dll"), "SHGetFolderPathA");
1615 if (get_folder_path != NULL)
1617 profile_result = get_folder_path (NULL, CSIDL_APPDATA, NULL,
1618 0, default_home);
1620 /* If we can't get the appdata dir, revert to old behavior. */
1621 if (profile_result == S_OK)
1623 env_vars[0].def_value = default_home;
1624 appdata = 1;
1629 /* Get default locale info and use it for LANG. */
1630 if (GetLocaleInfo (LOCALE_USER_DEFAULT,
1631 LOCALE_SABBREVLANGNAME | LOCALE_USE_CP_ACP,
1632 locale_name, sizeof (locale_name)))
1634 for (i = 0; i < N_ENV_VARS; i++)
1636 if (strcmp (env_vars[i].name, "LANG") == 0)
1638 env_vars[i].def_value = locale_name;
1639 break;
1644 /* When Emacs is invoked with --no-site-lisp, we must remove the
1645 site-lisp directories from the default value of EMACSLOADPATH.
1646 This assumes that the site-lisp entries are at the front, and
1647 that additional entries do exist. */
1648 if (no_site_lisp)
1650 for (i = 0; i < N_ENV_VARS; i++)
1652 if (strcmp (env_vars[i].name, "EMACSLOADPATH") == 0)
1654 char *site;
1655 while ((site = strstr (env_vars[i].def_value, "site-lisp")))
1656 env_vars[i].def_value = strchr (site, ';') + 1;
1657 break;
1662 #define SET_ENV_BUF_SIZE (4 * MAX_PATH) /* to cover EMACSLOADPATH */
1664 /* Treat emacs_dir specially: set it unconditionally based on our
1665 location, if it appears that we are running from the bin subdir
1666 of a standard installation. */
1668 char *p;
1669 char modname[MAX_PATH];
1671 if (!GetModuleFileName (NULL, modname, MAX_PATH))
1672 abort ();
1673 if ((p = strrchr (modname, '\\')) == NULL)
1674 abort ();
1675 *p = 0;
1677 if ((p = strrchr (modname, '\\')) && xstrcasecmp (p, "\\bin") == 0)
1679 char buf[SET_ENV_BUF_SIZE];
1681 *p = 0;
1682 for (p = modname; *p; p++)
1683 if (*p == '\\') *p = '/';
1685 _snprintf (buf, sizeof (buf)-1, "emacs_dir=%s", modname);
1686 _putenv (strdup (buf));
1688 /* Handle running emacs from the build directory: src/oo-spd/i386/ */
1690 /* FIXME: should use substring of get_emacs_configuration ().
1691 But I don't think the Windows build supports alpha, mips etc
1692 anymore, so have taken the easy option for now. */
1693 else if (p && xstrcasecmp (p, "\\i386") == 0)
1695 *p = 0;
1696 p = strrchr (modname, '\\');
1697 if (p != NULL)
1699 *p = 0;
1700 p = strrchr (modname, '\\');
1701 if (p && xstrcasecmp (p, "\\src") == 0)
1703 char buf[SET_ENV_BUF_SIZE];
1705 *p = 0;
1706 for (p = modname; *p; p++)
1707 if (*p == '\\') *p = '/';
1709 _snprintf (buf, sizeof (buf)-1, "emacs_dir=%s", modname);
1710 _putenv (strdup (buf));
1716 for (i = 0; i < N_ENV_VARS; i++)
1718 if (!getenv (env_vars[i].name))
1720 int dont_free = 0;
1722 if ((lpval = w32_get_resource (env_vars[i].name, &dwType)) == NULL
1723 /* Also ignore empty environment variables. */
1724 || *lpval == 0)
1726 xfree (lpval);
1727 lpval = env_vars[i].def_value;
1728 dwType = REG_EXPAND_SZ;
1729 dont_free = 1;
1730 if (!strcmp (env_vars[i].name, "HOME") && !appdata)
1732 Lisp_Object warning[2];
1733 warning[0] = intern ("initialization");
1734 warning[1] = build_string ("Setting HOME to C:\\ by default is deprecated");
1735 Vdelayed_warnings_list = Fcons (Flist (2, warning),
1736 Vdelayed_warnings_list);
1740 if (lpval)
1742 char buf1[SET_ENV_BUF_SIZE], buf2[SET_ENV_BUF_SIZE];
1744 if (dwType == REG_EXPAND_SZ)
1745 ExpandEnvironmentStrings ((LPSTR) lpval, buf1, sizeof (buf1));
1746 else if (dwType == REG_SZ)
1747 strcpy (buf1, lpval);
1748 if (dwType == REG_EXPAND_SZ || dwType == REG_SZ)
1750 _snprintf (buf2, sizeof (buf2)-1, "%s=%s", env_vars[i].name,
1751 buf1);
1752 _putenv (strdup (buf2));
1755 if (!dont_free)
1756 xfree (lpval);
1762 /* Rebuild system configuration to reflect invoking system. */
1763 Vsystem_configuration = build_string (EMACS_CONFIGURATION);
1765 /* Another special case: on NT, the PATH variable is actually named
1766 "Path" although cmd.exe (perhaps NT itself) arranges for
1767 environment variable lookup and setting to be case insensitive.
1768 However, Emacs assumes a fully case sensitive environment, so we
1769 need to change "Path" to "PATH" to match the expectations of
1770 various elisp packages. We do this by the sneaky method of
1771 modifying the string in the C runtime environ entry.
1773 The same applies to COMSPEC. */
1775 char ** envp;
1777 for (envp = environ; *envp; envp++)
1778 if (_strnicmp (*envp, "PATH=", 5) == 0)
1779 memcpy (*envp, "PATH=", 5);
1780 else if (_strnicmp (*envp, "COMSPEC=", 8) == 0)
1781 memcpy (*envp, "COMSPEC=", 8);
1784 /* Remember the initial working directory for getwd, then make the
1785 real wd be the location of emacs.exe to avoid conflicts when
1786 renaming or deleting directories. (We also don't call chdir when
1787 running subprocesses for the same reason.) */
1788 if (!GetCurrentDirectory (MAXPATHLEN, startup_dir))
1789 abort ();
1792 char *p;
1793 static char modname[MAX_PATH];
1795 if (!GetModuleFileName (NULL, modname, MAX_PATH))
1796 abort ();
1797 if ((p = strrchr (modname, '\\')) == NULL)
1798 abort ();
1799 *p = 0;
1801 SetCurrentDirectory (modname);
1803 /* Ensure argv[0] has the full path to Emacs. */
1804 *p = '\\';
1805 argv[0] = modname;
1808 /* Determine if there is a middle mouse button, to allow parse_button
1809 to decide whether right mouse events should be mouse-2 or
1810 mouse-3. */
1811 w32_num_mouse_buttons = GetSystemMetrics (SM_CMOUSEBUTTONS);
1813 init_user_info ();
1816 char *
1817 emacs_root_dir (void)
1819 static char root_dir[FILENAME_MAX];
1820 const char *p;
1822 p = getenv ("emacs_dir");
1823 if (p == NULL)
1824 abort ();
1825 strcpy (root_dir, p);
1826 root_dir[parse_root (root_dir, NULL)] = '\0';
1827 dostounix_filename (root_dir);
1828 return root_dir;
1831 /* We don't have scripts to automatically determine the system configuration
1832 for Emacs before it's compiled, and we don't want to have to make the
1833 user enter it, so we define EMACS_CONFIGURATION to invoke this runtime
1834 routine. */
1836 char *
1837 get_emacs_configuration (void)
1839 char *arch, *oem, *os;
1840 int build_num;
1841 static char configuration_buffer[32];
1843 /* Determine the processor type. */
1844 switch (get_processor_type ())
1847 #ifdef PROCESSOR_INTEL_386
1848 case PROCESSOR_INTEL_386:
1849 case PROCESSOR_INTEL_486:
1850 case PROCESSOR_INTEL_PENTIUM:
1851 arch = "i386";
1852 break;
1853 #endif
1855 #ifdef PROCESSOR_MIPS_R2000
1856 case PROCESSOR_MIPS_R2000:
1857 case PROCESSOR_MIPS_R3000:
1858 case PROCESSOR_MIPS_R4000:
1859 arch = "mips";
1860 break;
1861 #endif
1863 #ifdef PROCESSOR_ALPHA_21064
1864 case PROCESSOR_ALPHA_21064:
1865 arch = "alpha";
1866 break;
1867 #endif
1869 default:
1870 arch = "unknown";
1871 break;
1874 /* Use the OEM field to reflect the compiler/library combination. */
1875 #ifdef _MSC_VER
1876 #define COMPILER_NAME "msvc"
1877 #else
1878 #ifdef __GNUC__
1879 #define COMPILER_NAME "mingw"
1880 #else
1881 #define COMPILER_NAME "unknown"
1882 #endif
1883 #endif
1884 oem = COMPILER_NAME;
1886 switch (osinfo_cache.dwPlatformId) {
1887 case VER_PLATFORM_WIN32_NT:
1888 os = "nt";
1889 build_num = osinfo_cache.dwBuildNumber;
1890 break;
1891 case VER_PLATFORM_WIN32_WINDOWS:
1892 if (osinfo_cache.dwMinorVersion == 0) {
1893 os = "windows95";
1894 } else {
1895 os = "windows98";
1897 build_num = LOWORD (osinfo_cache.dwBuildNumber);
1898 break;
1899 case VER_PLATFORM_WIN32s:
1900 /* Not supported, should not happen. */
1901 os = "windows32s";
1902 build_num = LOWORD (osinfo_cache.dwBuildNumber);
1903 break;
1904 default:
1905 os = "unknown";
1906 build_num = 0;
1907 break;
1910 if (osinfo_cache.dwPlatformId == VER_PLATFORM_WIN32_NT) {
1911 sprintf (configuration_buffer, "%s-%s-%s%d.%d.%d", arch, oem, os,
1912 get_w32_major_version (), get_w32_minor_version (), build_num);
1913 } else {
1914 sprintf (configuration_buffer, "%s-%s-%s.%d", arch, oem, os, build_num);
1917 return configuration_buffer;
1920 char *
1921 get_emacs_configuration_options (void)
1923 static char *options_buffer;
1924 char cv[32]; /* Enough for COMPILER_VERSION. */
1925 char *options[] = {
1926 cv, /* To be filled later. */
1927 #ifdef EMACSDEBUG
1928 " --no-opt",
1929 #endif
1930 #ifdef ENABLE_CHECKING
1931 " --enable-checking",
1932 #endif
1933 /* configure.bat already sets USER_CFLAGS and USER_LDFLAGS
1934 with a starting space to save work here. */
1935 #ifdef USER_CFLAGS
1936 " --cflags", USER_CFLAGS,
1937 #endif
1938 #ifdef USER_LDFLAGS
1939 " --ldflags", USER_LDFLAGS,
1940 #endif
1941 NULL
1943 size_t size = 0;
1944 int i;
1946 /* Work out the effective configure options for this build. */
1947 #ifdef _MSC_VER
1948 #define COMPILER_VERSION "--with-msvc (%d.%02d)", _MSC_VER / 100, _MSC_VER % 100
1949 #else
1950 #ifdef __GNUC__
1951 #define COMPILER_VERSION "--with-gcc (%d.%d)", __GNUC__, __GNUC_MINOR__
1952 #else
1953 #define COMPILER_VERSION ""
1954 #endif
1955 #endif
1957 if (_snprintf (cv, sizeof (cv) - 1, COMPILER_VERSION) < 0)
1958 return "Error: not enough space for compiler version";
1959 cv[sizeof (cv) - 1] = '\0';
1961 for (i = 0; options[i]; i++)
1962 size += strlen (options[i]);
1964 options_buffer = xmalloc (size + 1);
1965 options_buffer[0] = '\0';
1967 for (i = 0; options[i]; i++)
1968 strcat (options_buffer, options[i]);
1970 return options_buffer;
1974 #include <sys/timeb.h>
1976 /* Emulate gettimeofday (Ulrich Leodolter, 1/11/95). */
1977 void
1978 gettimeofday (struct timeval *tv, struct timezone *tz)
1980 struct _timeb tb;
1981 _ftime (&tb);
1983 tv->tv_sec = tb.time;
1984 tv->tv_usec = tb.millitm * 1000L;
1985 /* Implementation note: _ftime sometimes doesn't update the dstflag
1986 according to the new timezone when the system timezone is
1987 changed. We could fix that by using GetSystemTime and
1988 GetTimeZoneInformation, but that doesn't seem necessary, since
1989 Emacs always calls gettimeofday with the 2nd argument NULL (see
1990 EMACS_GET_TIME). */
1991 if (tz)
1993 tz->tz_minuteswest = tb.timezone; /* minutes west of Greenwich */
1994 tz->tz_dsttime = tb.dstflag; /* type of dst correction */
1998 /* Emulate fdutimens. */
2000 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2001 TIMESPEC[0] and TIMESPEC[1], respectively.
2002 FD must be either negative -- in which case it is ignored --
2003 or a file descriptor that is open on FILE.
2004 If FD is nonnegative, then FILE can be NULL, which means
2005 use just futimes instead of utimes.
2006 If TIMESPEC is null, FAIL.
2007 Return 0 on success, -1 (setting errno) on failure. */
2010 fdutimens (int fd, char const *file, struct timespec const timespec[2])
2012 struct _utimbuf ut;
2014 if (!timespec)
2016 errno = ENOSYS;
2017 return -1;
2019 if (fd < 0 && !file)
2021 errno = EBADF;
2022 return -1;
2024 ut.actime = timespec[0].tv_sec;
2025 ut.modtime = timespec[1].tv_sec;
2026 if (fd >= 0)
2027 return _futime (fd, &ut);
2028 else
2029 return _utime (file, &ut);
2033 /* ------------------------------------------------------------------------- */
2034 /* IO support and wrapper functions for W32 API. */
2035 /* ------------------------------------------------------------------------- */
2037 /* Place a wrapper around the MSVC version of ctime. It returns NULL
2038 on network directories, so we handle that case here.
2039 (Ulrich Leodolter, 1/11/95). */
2040 char *
2041 sys_ctime (const time_t *t)
2043 char *str = (char *) ctime (t);
2044 return (str ? str : "Sun Jan 01 00:00:00 1970");
2047 /* Emulate sleep...we could have done this with a define, but that
2048 would necessitate including windows.h in the files that used it.
2049 This is much easier. */
2050 void
2051 sys_sleep (int seconds)
2053 Sleep (seconds * 1000);
2056 /* Internal MSVC functions for low-level descriptor munging */
2057 extern int __cdecl _set_osfhnd (int fd, long h);
2058 extern int __cdecl _free_osfhnd (int fd);
2060 /* parallel array of private info on file handles */
2061 filedesc fd_info [ MAXDESC ];
2063 typedef struct volume_info_data {
2064 struct volume_info_data * next;
2066 /* time when info was obtained */
2067 DWORD timestamp;
2069 /* actual volume info */
2070 char * root_dir;
2071 DWORD serialnum;
2072 DWORD maxcomp;
2073 DWORD flags;
2074 char * name;
2075 char * type;
2076 } volume_info_data;
2078 /* Global referenced by various functions. */
2079 static volume_info_data volume_info;
2081 /* Vector to indicate which drives are local and fixed (for which cached
2082 data never expires). */
2083 static BOOL fixed_drives[26];
2085 /* Consider cached volume information to be stale if older than 10s,
2086 at least for non-local drives. Info for fixed drives is never stale. */
2087 #define DRIVE_INDEX( c ) ( (c) <= 'Z' ? (c) - 'A' : (c) - 'a' )
2088 #define VOLINFO_STILL_VALID( root_dir, info ) \
2089 ( ( isalpha (root_dir[0]) && \
2090 fixed_drives[ DRIVE_INDEX (root_dir[0]) ] ) \
2091 || GetTickCount () - info->timestamp < 10000 )
2093 /* Cache support functions. */
2095 /* Simple linked list with linear search is sufficient. */
2096 static volume_info_data *volume_cache = NULL;
2098 static volume_info_data *
2099 lookup_volume_info (char * root_dir)
2101 volume_info_data * info;
2103 for (info = volume_cache; info; info = info->next)
2104 if (xstrcasecmp (info->root_dir, root_dir) == 0)
2105 break;
2106 return info;
2109 static void
2110 add_volume_info (char * root_dir, volume_info_data * info)
2112 info->root_dir = xstrdup (root_dir);
2113 info->next = volume_cache;
2114 volume_cache = info;
2118 /* Wrapper for GetVolumeInformation, which uses caching to avoid
2119 performance penalty (~2ms on 486 for local drives, 7.5ms for local
2120 cdrom drive, ~5-10ms or more for remote drives on LAN). */
2121 static volume_info_data *
2122 GetCachedVolumeInformation (char * root_dir)
2124 volume_info_data * info;
2125 char default_root[ MAX_PATH ];
2127 /* NULL for root_dir means use root from current directory. */
2128 if (root_dir == NULL)
2130 if (GetCurrentDirectory (MAX_PATH, default_root) == 0)
2131 return NULL;
2132 parse_root (default_root, &root_dir);
2133 *root_dir = 0;
2134 root_dir = default_root;
2137 /* Local fixed drives can be cached permanently. Removable drives
2138 cannot be cached permanently, since the volume name and serial
2139 number (if nothing else) can change. Remote drives should be
2140 treated as if they are removable, since there is no sure way to
2141 tell whether they are or not. Also, the UNC association of drive
2142 letters mapped to remote volumes can be changed at any time (even
2143 by other processes) without notice.
2145 As a compromise, so we can benefit from caching info for remote
2146 volumes, we use a simple expiry mechanism to invalidate cache
2147 entries that are more than ten seconds old. */
2149 #if 0
2150 /* No point doing this, because WNetGetConnection is even slower than
2151 GetVolumeInformation, consistently taking ~50ms on a 486 (FWIW,
2152 GetDriveType is about the only call of this type which does not
2153 involve network access, and so is extremely quick). */
2155 /* Map drive letter to UNC if remote. */
2156 if (isalpha (root_dir[0]) && !fixed[DRIVE_INDEX (root_dir[0])])
2158 char remote_name[ 256 ];
2159 char drive[3] = { root_dir[0], ':' };
2161 if (WNetGetConnection (drive, remote_name, sizeof (remote_name))
2162 == NO_ERROR)
2163 /* do something */ ;
2165 #endif
2167 info = lookup_volume_info (root_dir);
2169 if (info == NULL || ! VOLINFO_STILL_VALID (root_dir, info))
2171 char name[ 256 ];
2172 DWORD serialnum;
2173 DWORD maxcomp;
2174 DWORD flags;
2175 char type[ 256 ];
2177 /* Info is not cached, or is stale. */
2178 if (!GetVolumeInformation (root_dir,
2179 name, sizeof (name),
2180 &serialnum,
2181 &maxcomp,
2182 &flags,
2183 type, sizeof (type)))
2184 return NULL;
2186 /* Cache the volume information for future use, overwriting existing
2187 entry if present. */
2188 if (info == NULL)
2190 info = (volume_info_data *) xmalloc (sizeof (volume_info_data));
2191 add_volume_info (root_dir, info);
2193 else
2195 xfree (info->name);
2196 xfree (info->type);
2199 info->name = xstrdup (name);
2200 info->serialnum = serialnum;
2201 info->maxcomp = maxcomp;
2202 info->flags = flags;
2203 info->type = xstrdup (type);
2204 info->timestamp = GetTickCount ();
2207 return info;
2210 /* Get information on the volume where name is held; set path pointer to
2211 start of pathname in name (past UNC header\volume header if present). */
2212 static int
2213 get_volume_info (const char * name, const char ** pPath)
2215 char temp[MAX_PATH];
2216 char *rootname = NULL; /* default to current volume */
2217 volume_info_data * info;
2219 if (name == NULL)
2220 return FALSE;
2222 /* find the root name of the volume if given */
2223 if (isalpha (name[0]) && name[1] == ':')
2225 rootname = temp;
2226 temp[0] = *name++;
2227 temp[1] = *name++;
2228 temp[2] = '\\';
2229 temp[3] = 0;
2231 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
2233 char *str = temp;
2234 int slashes = 4;
2235 rootname = temp;
2238 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
2239 break;
2240 *str++ = *name++;
2242 while ( *name );
2244 *str++ = '\\';
2245 *str = 0;
2248 if (pPath)
2249 *pPath = name;
2251 info = GetCachedVolumeInformation (rootname);
2252 if (info != NULL)
2254 /* Set global referenced by other functions. */
2255 volume_info = *info;
2256 return TRUE;
2258 return FALSE;
2261 /* Determine if volume is FAT format (ie. only supports short 8.3
2262 names); also set path pointer to start of pathname in name. */
2263 static int
2264 is_fat_volume (const char * name, const char ** pPath)
2266 if (get_volume_info (name, pPath))
2267 return (volume_info.maxcomp == 12);
2268 return FALSE;
2271 /* Map filename to a valid 8.3 name if necessary. */
2272 const char *
2273 map_w32_filename (const char * name, const char ** pPath)
2275 static char shortname[MAX_PATH];
2276 char * str = shortname;
2277 char c;
2278 char * path;
2279 const char * save_name = name;
2281 if (strlen (name) >= MAX_PATH)
2283 /* Return a filename which will cause callers to fail. */
2284 strcpy (shortname, "?");
2285 return shortname;
2288 if (is_fat_volume (name, (const char **)&path)) /* truncate to 8.3 */
2290 register int left = 8; /* maximum number of chars in part */
2291 register int extn = 0; /* extension added? */
2292 register int dots = 2; /* maximum number of dots allowed */
2294 while (name < path)
2295 *str++ = *name++; /* skip past UNC header */
2297 while ((c = *name++))
2299 switch ( c )
2301 case '\\':
2302 case '/':
2303 *str++ = '\\';
2304 extn = 0; /* reset extension flags */
2305 dots = 2; /* max 2 dots */
2306 left = 8; /* max length 8 for main part */
2307 break;
2308 case ':':
2309 *str++ = ':';
2310 extn = 0; /* reset extension flags */
2311 dots = 2; /* max 2 dots */
2312 left = 8; /* max length 8 for main part */
2313 break;
2314 case '.':
2315 if ( dots )
2317 /* Convert path components of the form .xxx to _xxx,
2318 but leave . and .. as they are. This allows .emacs
2319 to be read as _emacs, for example. */
2321 if (! *name ||
2322 *name == '.' ||
2323 IS_DIRECTORY_SEP (*name))
2325 *str++ = '.';
2326 dots--;
2328 else
2330 *str++ = '_';
2331 left--;
2332 dots = 0;
2335 else if ( !extn )
2337 *str++ = '.';
2338 extn = 1; /* we've got an extension */
2339 left = 3; /* 3 chars in extension */
2341 else
2343 /* any embedded dots after the first are converted to _ */
2344 *str++ = '_';
2346 break;
2347 case '~':
2348 case '#': /* don't lose these, they're important */
2349 if ( ! left )
2350 str[-1] = c; /* replace last character of part */
2351 /* FALLTHRU */
2352 default:
2353 if ( left )
2355 *str++ = tolower (c); /* map to lower case (looks nicer) */
2356 left--;
2357 dots = 0; /* started a path component */
2359 break;
2362 *str = '\0';
2364 else
2366 strcpy (shortname, name);
2367 unixtodos_filename (shortname);
2370 if (pPath)
2371 *pPath = shortname + (path - save_name);
2373 return shortname;
2376 static int
2377 is_exec (const char * name)
2379 char * p = strrchr (name, '.');
2380 return
2381 (p != NULL
2382 && (xstrcasecmp (p, ".exe") == 0 ||
2383 xstrcasecmp (p, ".com") == 0 ||
2384 xstrcasecmp (p, ".bat") == 0 ||
2385 xstrcasecmp (p, ".cmd") == 0));
2388 /* Emulate the Unix directory procedures opendir, closedir,
2389 and readdir. We can't use the procedures supplied in sysdep.c,
2390 so we provide them here. */
2392 struct direct dir_static; /* simulated directory contents */
2393 static HANDLE dir_find_handle = INVALID_HANDLE_VALUE;
2394 static int dir_is_fat;
2395 static char dir_pathname[MAXPATHLEN+1];
2396 static WIN32_FIND_DATA dir_find_data;
2398 /* Support shares on a network resource as subdirectories of a read-only
2399 root directory. */
2400 static HANDLE wnet_enum_handle = INVALID_HANDLE_VALUE;
2401 static HANDLE open_unc_volume (const char *);
2402 static char *read_unc_volume (HANDLE, char *, int);
2403 static void close_unc_volume (HANDLE);
2405 DIR *
2406 opendir (char *filename)
2408 DIR *dirp;
2410 /* Opening is done by FindFirstFile. However, a read is inherent to
2411 this operation, so we defer the open until read time. */
2413 if (dir_find_handle != INVALID_HANDLE_VALUE)
2414 return NULL;
2415 if (wnet_enum_handle != INVALID_HANDLE_VALUE)
2416 return NULL;
2418 if (is_unc_volume (filename))
2420 wnet_enum_handle = open_unc_volume (filename);
2421 if (wnet_enum_handle == INVALID_HANDLE_VALUE)
2422 return NULL;
2425 if (!(dirp = (DIR *) malloc (sizeof (DIR))))
2426 return NULL;
2428 dirp->dd_fd = 0;
2429 dirp->dd_loc = 0;
2430 dirp->dd_size = 0;
2432 strncpy (dir_pathname, map_w32_filename (filename, NULL), MAXPATHLEN);
2433 dir_pathname[MAXPATHLEN] = '\0';
2434 dir_is_fat = is_fat_volume (filename, NULL);
2436 return dirp;
2439 void
2440 closedir (DIR *dirp)
2442 /* If we have a find-handle open, close it. */
2443 if (dir_find_handle != INVALID_HANDLE_VALUE)
2445 FindClose (dir_find_handle);
2446 dir_find_handle = INVALID_HANDLE_VALUE;
2448 else if (wnet_enum_handle != INVALID_HANDLE_VALUE)
2450 close_unc_volume (wnet_enum_handle);
2451 wnet_enum_handle = INVALID_HANDLE_VALUE;
2453 xfree ((char *) dirp);
2456 struct direct *
2457 readdir (DIR *dirp)
2459 int downcase = !NILP (Vw32_downcase_file_names);
2461 if (wnet_enum_handle != INVALID_HANDLE_VALUE)
2463 if (!read_unc_volume (wnet_enum_handle,
2464 dir_find_data.cFileName,
2465 MAX_PATH))
2466 return NULL;
2468 /* If we aren't dir_finding, do a find-first, otherwise do a find-next. */
2469 else if (dir_find_handle == INVALID_HANDLE_VALUE)
2471 char filename[MAXNAMLEN + 3];
2472 int ln;
2474 strcpy (filename, dir_pathname);
2475 ln = strlen (filename) - 1;
2476 if (!IS_DIRECTORY_SEP (filename[ln]))
2477 strcat (filename, "\\");
2478 strcat (filename, "*");
2480 dir_find_handle = FindFirstFile (filename, &dir_find_data);
2482 if (dir_find_handle == INVALID_HANDLE_VALUE)
2483 return NULL;
2485 else
2487 if (!FindNextFile (dir_find_handle, &dir_find_data))
2488 return NULL;
2491 /* Emacs never uses this value, so don't bother making it match
2492 value returned by stat(). */
2493 dir_static.d_ino = 1;
2495 strcpy (dir_static.d_name, dir_find_data.cFileName);
2497 /* If the file name in cFileName[] includes `?' characters, it means
2498 the original file name used characters that cannot be represented
2499 by the current ANSI codepage. To avoid total lossage, retrieve
2500 the short 8+3 alias of the long file name. */
2501 if (_mbspbrk (dir_static.d_name, "?"))
2503 strcpy (dir_static.d_name, dir_find_data.cAlternateFileName);
2504 downcase = 1; /* 8+3 aliases are returned in all caps */
2506 dir_static.d_namlen = strlen (dir_static.d_name);
2507 dir_static.d_reclen = sizeof (struct direct) - MAXNAMLEN + 3 +
2508 dir_static.d_namlen - dir_static.d_namlen % 4;
2510 /* If the file name in cFileName[] includes `?' characters, it means
2511 the original file name used characters that cannot be represented
2512 by the current ANSI codepage. To avoid total lossage, retrieve
2513 the short 8+3 alias of the long file name. */
2514 if (_mbspbrk (dir_find_data.cFileName, "?"))
2516 strcpy (dir_static.d_name, dir_find_data.cAlternateFileName);
2517 /* 8+3 aliases are returned in all caps, which could break
2518 various alists that look at filenames' extensions. */
2519 downcase = 1;
2521 else
2522 strcpy (dir_static.d_name, dir_find_data.cFileName);
2523 dir_static.d_namlen = strlen (dir_static.d_name);
2524 if (dir_is_fat)
2525 _strlwr (dir_static.d_name);
2526 else if (downcase)
2528 register char *p;
2529 for (p = dir_static.d_name; *p; p++)
2530 if (*p >= 'a' && *p <= 'z')
2531 break;
2532 if (!*p)
2533 _strlwr (dir_static.d_name);
2536 return &dir_static;
2539 static HANDLE
2540 open_unc_volume (const char *path)
2542 NETRESOURCE nr;
2543 HANDLE henum;
2544 int result;
2546 nr.dwScope = RESOURCE_GLOBALNET;
2547 nr.dwType = RESOURCETYPE_DISK;
2548 nr.dwDisplayType = RESOURCEDISPLAYTYPE_SERVER;
2549 nr.dwUsage = RESOURCEUSAGE_CONTAINER;
2550 nr.lpLocalName = NULL;
2551 nr.lpRemoteName = (LPSTR)map_w32_filename (path, NULL);
2552 nr.lpComment = NULL;
2553 nr.lpProvider = NULL;
2555 result = WNetOpenEnum (RESOURCE_GLOBALNET, RESOURCETYPE_DISK,
2556 RESOURCEUSAGE_CONNECTABLE, &nr, &henum);
2558 if (result == NO_ERROR)
2559 return henum;
2560 else
2561 return INVALID_HANDLE_VALUE;
2564 static char *
2565 read_unc_volume (HANDLE henum, char *readbuf, int size)
2567 DWORD count;
2568 int result;
2569 DWORD bufsize = 512;
2570 char *buffer;
2571 char *ptr;
2573 count = 1;
2574 buffer = alloca (bufsize);
2575 result = WNetEnumResource (henum, &count, buffer, &bufsize);
2576 if (result != NO_ERROR)
2577 return NULL;
2579 /* WNetEnumResource returns \\resource\share...skip forward to "share". */
2580 ptr = ((LPNETRESOURCE) buffer)->lpRemoteName;
2581 ptr += 2;
2582 while (*ptr && !IS_DIRECTORY_SEP (*ptr)) ptr++;
2583 ptr++;
2585 strncpy (readbuf, ptr, size);
2586 return readbuf;
2589 static void
2590 close_unc_volume (HANDLE henum)
2592 if (henum != INVALID_HANDLE_VALUE)
2593 WNetCloseEnum (henum);
2596 static DWORD
2597 unc_volume_file_attributes (const char *path)
2599 HANDLE henum;
2600 DWORD attrs;
2602 henum = open_unc_volume (path);
2603 if (henum == INVALID_HANDLE_VALUE)
2604 return -1;
2606 attrs = FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_DIRECTORY;
2608 close_unc_volume (henum);
2610 return attrs;
2613 /* Ensure a network connection is authenticated. */
2614 static void
2615 logon_network_drive (const char *path)
2617 NETRESOURCE resource;
2618 char share[MAX_PATH];
2619 int i, n_slashes;
2620 char drive[4];
2621 UINT drvtype;
2623 if (IS_DIRECTORY_SEP (path[0]) && IS_DIRECTORY_SEP (path[1]))
2624 drvtype = DRIVE_REMOTE;
2625 else if (path[0] == '\0' || path[1] != ':')
2626 drvtype = GetDriveType (NULL);
2627 else
2629 drive[0] = path[0];
2630 drive[1] = ':';
2631 drive[2] = '\\';
2632 drive[3] = '\0';
2633 drvtype = GetDriveType (drive);
2636 /* Only logon to networked drives. */
2637 if (drvtype != DRIVE_REMOTE)
2638 return;
2640 n_slashes = 2;
2641 strncpy (share, path, MAX_PATH);
2642 /* Truncate to just server and share name. */
2643 for (i = 2; i < MAX_PATH; i++)
2645 if (IS_DIRECTORY_SEP (share[i]) && ++n_slashes > 3)
2647 share[i] = '\0';
2648 break;
2652 resource.dwType = RESOURCETYPE_DISK;
2653 resource.lpLocalName = NULL;
2654 resource.lpRemoteName = share;
2655 resource.lpProvider = NULL;
2657 WNetAddConnection2 (&resource, NULL, NULL, CONNECT_INTERACTIVE);
2660 /* Shadow some MSVC runtime functions to map requests for long filenames
2661 to reasonable short names if necessary. This was originally added to
2662 permit running Emacs on NT 3.1 on a FAT partition, which doesn't support
2663 long file names. */
2666 sys_access (const char * path, int mode)
2668 DWORD attributes;
2670 /* MSVC implementation doesn't recognize D_OK. */
2671 path = map_w32_filename (path, NULL);
2672 if (is_unc_volume (path))
2674 attributes = unc_volume_file_attributes (path);
2675 if (attributes == -1) {
2676 errno = EACCES;
2677 return -1;
2680 else if ((attributes = GetFileAttributes (path)) == -1)
2682 /* Should try mapping GetLastError to errno; for now just indicate
2683 that path doesn't exist. */
2684 errno = EACCES;
2685 return -1;
2687 if ((mode & X_OK) != 0 && !is_exec (path))
2689 errno = EACCES;
2690 return -1;
2692 if ((mode & W_OK) != 0 && (attributes & FILE_ATTRIBUTE_READONLY) != 0)
2694 errno = EACCES;
2695 return -1;
2697 if ((mode & D_OK) != 0 && (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
2699 errno = EACCES;
2700 return -1;
2702 return 0;
2706 sys_chdir (const char * path)
2708 return _chdir (map_w32_filename (path, NULL));
2712 sys_chmod (const char * path, int mode)
2714 return _chmod (map_w32_filename (path, NULL), mode);
2718 sys_chown (const char *path, uid_t owner, gid_t group)
2720 if (sys_chmod (path, S_IREAD) == -1) /* check if file exists */
2721 return -1;
2722 return 0;
2726 sys_creat (const char * path, int mode)
2728 return _creat (map_w32_filename (path, NULL), mode);
2731 FILE *
2732 sys_fopen (const char * path, const char * mode)
2734 int fd;
2735 int oflag;
2736 const char * mode_save = mode;
2738 /* Force all file handles to be non-inheritable. This is necessary to
2739 ensure child processes don't unwittingly inherit handles that might
2740 prevent future file access. */
2742 if (mode[0] == 'r')
2743 oflag = O_RDONLY;
2744 else if (mode[0] == 'w' || mode[0] == 'a')
2745 oflag = O_WRONLY | O_CREAT | O_TRUNC;
2746 else
2747 return NULL;
2749 /* Only do simplistic option parsing. */
2750 while (*++mode)
2751 if (mode[0] == '+')
2753 oflag &= ~(O_RDONLY | O_WRONLY);
2754 oflag |= O_RDWR;
2756 else if (mode[0] == 'b')
2758 oflag &= ~O_TEXT;
2759 oflag |= O_BINARY;
2761 else if (mode[0] == 't')
2763 oflag &= ~O_BINARY;
2764 oflag |= O_TEXT;
2766 else break;
2768 fd = _open (map_w32_filename (path, NULL), oflag | _O_NOINHERIT, 0644);
2769 if (fd < 0)
2770 return NULL;
2772 return _fdopen (fd, mode_save);
2775 /* This only works on NTFS volumes, but is useful to have. */
2777 sys_link (const char * old, const char * new)
2779 HANDLE fileh;
2780 int result = -1;
2781 char oldname[MAX_PATH], newname[MAX_PATH];
2783 if (old == NULL || new == NULL)
2785 errno = ENOENT;
2786 return -1;
2789 strcpy (oldname, map_w32_filename (old, NULL));
2790 strcpy (newname, map_w32_filename (new, NULL));
2792 fileh = CreateFile (oldname, 0, 0, NULL, OPEN_EXISTING,
2793 FILE_FLAG_BACKUP_SEMANTICS, NULL);
2794 if (fileh != INVALID_HANDLE_VALUE)
2796 int wlen;
2798 /* Confusingly, the "alternate" stream name field does not apply
2799 when restoring a hard link, and instead contains the actual
2800 stream data for the link (ie. the name of the link to create).
2801 The WIN32_STREAM_ID structure before the cStreamName field is
2802 the stream header, which is then immediately followed by the
2803 stream data. */
2805 struct {
2806 WIN32_STREAM_ID wid;
2807 WCHAR wbuffer[MAX_PATH]; /* extra space for link name */
2808 } data;
2810 wlen = MultiByteToWideChar (CP_ACP, MB_PRECOMPOSED, newname, -1,
2811 data.wid.cStreamName, MAX_PATH);
2812 if (wlen > 0)
2814 LPVOID context = NULL;
2815 DWORD wbytes = 0;
2817 data.wid.dwStreamId = BACKUP_LINK;
2818 data.wid.dwStreamAttributes = 0;
2819 data.wid.Size.LowPart = wlen * sizeof (WCHAR);
2820 data.wid.Size.HighPart = 0;
2821 data.wid.dwStreamNameSize = 0;
2823 if (BackupWrite (fileh, (LPBYTE)&data,
2824 offsetof (WIN32_STREAM_ID, cStreamName)
2825 + data.wid.Size.LowPart,
2826 &wbytes, FALSE, FALSE, &context)
2827 && BackupWrite (fileh, NULL, 0, &wbytes, TRUE, FALSE, &context))
2829 /* succeeded */
2830 result = 0;
2832 else
2834 /* Should try mapping GetLastError to errno; for now just
2835 indicate a general error (eg. links not supported). */
2836 errno = EINVAL; // perhaps EMLINK?
2840 CloseHandle (fileh);
2842 else
2843 errno = ENOENT;
2845 return result;
2849 sys_mkdir (const char * path)
2851 return _mkdir (map_w32_filename (path, NULL));
2854 /* Because of long name mapping issues, we need to implement this
2855 ourselves. Also, MSVC's _mktemp returns NULL when it can't generate
2856 a unique name, instead of setting the input template to an empty
2857 string.
2859 Standard algorithm seems to be use pid or tid with a letter on the
2860 front (in place of the 6 X's) and cycle through the letters to find a
2861 unique name. We extend that to allow any reasonable character as the
2862 first of the 6 X's. */
2863 char *
2864 sys_mktemp (char * template)
2866 char * p;
2867 int i;
2868 unsigned uid = GetCurrentThreadId ();
2869 static char first_char[] = "abcdefghijklmnopqrstuvwyz0123456789!%-_@#";
2871 if (template == NULL)
2872 return NULL;
2873 p = template + strlen (template);
2874 i = 5;
2875 /* replace up to the last 5 X's with uid in decimal */
2876 while (--p >= template && p[0] == 'X' && --i >= 0)
2878 p[0] = '0' + uid % 10;
2879 uid /= 10;
2882 if (i < 0 && p[0] == 'X')
2884 i = 0;
2887 int save_errno = errno;
2888 p[0] = first_char[i];
2889 if (sys_access (template, 0) < 0)
2891 errno = save_errno;
2892 return template;
2895 while (++i < sizeof (first_char));
2898 /* Template is badly formed or else we can't generate a unique name,
2899 so return empty string */
2900 template[0] = 0;
2901 return template;
2905 sys_open (const char * path, int oflag, int mode)
2907 const char* mpath = map_w32_filename (path, NULL);
2908 /* Try to open file without _O_CREAT, to be able to write to hidden
2909 and system files. Force all file handles to be
2910 non-inheritable. */
2911 int res = _open (mpath, (oflag & ~_O_CREAT) | _O_NOINHERIT, mode);
2912 if (res >= 0)
2913 return res;
2914 return _open (mpath, oflag | _O_NOINHERIT, mode);
2918 sys_rename (const char * oldname, const char * newname)
2920 BOOL result;
2921 char temp[MAX_PATH];
2922 int newname_dev;
2923 int oldname_dev;
2925 /* MoveFile on Windows 95 doesn't correctly change the short file name
2926 alias in a number of circumstances (it is not easy to predict when
2927 just by looking at oldname and newname, unfortunately). In these
2928 cases, renaming through a temporary name avoids the problem.
2930 A second problem on Windows 95 is that renaming through a temp name when
2931 newname is uppercase fails (the final long name ends up in
2932 lowercase, although the short alias might be uppercase) UNLESS the
2933 long temp name is not 8.3.
2935 So, on Windows 95 we always rename through a temp name, and we make sure
2936 the temp name has a long extension to ensure correct renaming. */
2938 strcpy (temp, map_w32_filename (oldname, NULL));
2940 /* volume_info is set indirectly by map_w32_filename. */
2941 oldname_dev = volume_info.serialnum;
2943 if (os_subtype == OS_WIN95)
2945 char * o;
2946 char * p;
2947 int i = 0;
2949 oldname = map_w32_filename (oldname, NULL);
2950 if ((o = strrchr (oldname, '\\')))
2951 o++;
2952 else
2953 o = (char *) oldname;
2955 if ((p = strrchr (temp, '\\')))
2956 p++;
2957 else
2958 p = temp;
2962 /* Force temp name to require a manufactured 8.3 alias - this
2963 seems to make the second rename work properly. */
2964 sprintf (p, "_.%s.%u", o, i);
2965 i++;
2966 result = rename (oldname, temp);
2968 /* This loop must surely terminate! */
2969 while (result < 0 && errno == EEXIST);
2970 if (result < 0)
2971 return -1;
2974 /* Emulate Unix behavior - newname is deleted if it already exists
2975 (at least if it is a file; don't do this for directories).
2977 Since we mustn't do this if we are just changing the case of the
2978 file name (we would end up deleting the file we are trying to
2979 rename!), we let rename detect if the destination file already
2980 exists - that way we avoid the possible pitfalls of trying to
2981 determine ourselves whether two names really refer to the same
2982 file, which is not always possible in the general case. (Consider
2983 all the permutations of shared or subst'd drives, etc.) */
2985 newname = map_w32_filename (newname, NULL);
2987 /* volume_info is set indirectly by map_w32_filename. */
2988 newname_dev = volume_info.serialnum;
2990 result = rename (temp, newname);
2992 if (result < 0)
2995 if (errno == EACCES
2996 && newname_dev != oldname_dev)
2998 /* The implementation of `rename' on Windows does not return
2999 errno = EXDEV when you are moving a directory to a
3000 different storage device (ex. logical disk). It returns
3001 EACCES instead. So here we handle such situations and
3002 return EXDEV. */
3003 DWORD attributes;
3005 if ((attributes = GetFileAttributes (temp)) != -1
3006 && attributes & FILE_ATTRIBUTE_DIRECTORY)
3007 errno = EXDEV;
3009 else if (errno == EEXIST)
3011 if (_chmod (newname, 0666) != 0)
3012 return result;
3013 if (_unlink (newname) != 0)
3014 return result;
3015 result = rename (temp, newname);
3019 return result;
3023 sys_rmdir (const char * path)
3025 return _rmdir (map_w32_filename (path, NULL));
3029 sys_unlink (const char * path)
3031 path = map_w32_filename (path, NULL);
3033 /* On Unix, unlink works without write permission. */
3034 _chmod (path, 0666);
3035 return _unlink (path);
3038 static FILETIME utc_base_ft;
3039 static ULONGLONG utc_base; /* In 100ns units */
3040 static int init = 0;
3042 #define FILETIME_TO_U64(result, ft) \
3043 do { \
3044 ULARGE_INTEGER uiTemp; \
3045 uiTemp.LowPart = (ft).dwLowDateTime; \
3046 uiTemp.HighPart = (ft).dwHighDateTime; \
3047 result = uiTemp.QuadPart; \
3048 } while (0)
3050 static void
3051 initialize_utc_base (void)
3053 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
3054 SYSTEMTIME st;
3056 st.wYear = 1970;
3057 st.wMonth = 1;
3058 st.wDay = 1;
3059 st.wHour = 0;
3060 st.wMinute = 0;
3061 st.wSecond = 0;
3062 st.wMilliseconds = 0;
3064 SystemTimeToFileTime (&st, &utc_base_ft);
3065 FILETIME_TO_U64 (utc_base, utc_base_ft);
3068 static time_t
3069 convert_time (FILETIME ft)
3071 ULONGLONG tmp;
3073 if (!init)
3075 initialize_utc_base ();
3076 init = 1;
3079 if (CompareFileTime (&ft, &utc_base_ft) < 0)
3080 return 0;
3082 FILETIME_TO_U64 (tmp, ft);
3083 return (time_t) ((tmp - utc_base) / 10000000L);
3086 static void
3087 convert_from_time_t (time_t time, FILETIME * pft)
3089 ULARGE_INTEGER tmp;
3091 if (!init)
3093 initialize_utc_base ();
3094 init = 1;
3097 /* time in 100ns units since 1-Jan-1601 */
3098 tmp.QuadPart = (ULONGLONG) time * 10000000L + utc_base;
3099 pft->dwHighDateTime = tmp.HighPart;
3100 pft->dwLowDateTime = tmp.LowPart;
3103 #if 0
3104 /* No reason to keep this; faking inode values either by hashing or even
3105 using the file index from GetInformationByHandle, is not perfect and
3106 so by default Emacs doesn't use the inode values on Windows.
3107 Instead, we now determine file-truename correctly (except for
3108 possible drive aliasing etc). */
3110 /* Modified version of "PJW" algorithm (see the "Dragon" compiler book). */
3111 static unsigned
3112 hashval (const unsigned char * str)
3114 unsigned h = 0;
3115 while (*str)
3117 h = (h << 4) + *str++;
3118 h ^= (h >> 28);
3120 return h;
3123 /* Return the hash value of the canonical pathname, excluding the
3124 drive/UNC header, to get a hopefully unique inode number. */
3125 static DWORD
3126 generate_inode_val (const char * name)
3128 char fullname[ MAX_PATH ];
3129 char * p;
3130 unsigned hash;
3132 /* Get the truly canonical filename, if it exists. (Note: this
3133 doesn't resolve aliasing due to subst commands, or recognize hard
3134 links. */
3135 if (!w32_get_long_filename ((char *)name, fullname, MAX_PATH))
3136 abort ();
3138 parse_root (fullname, &p);
3139 /* Normal W32 filesystems are still case insensitive. */
3140 _strlwr (p);
3141 return hashval (p);
3144 #endif
3146 static PSECURITY_DESCRIPTOR
3147 get_file_security_desc (const char *fname)
3149 PSECURITY_DESCRIPTOR psd = NULL;
3150 DWORD sd_len, err;
3151 SECURITY_INFORMATION si = OWNER_SECURITY_INFORMATION
3152 | GROUP_SECURITY_INFORMATION /* | DACL_SECURITY_INFORMATION */ ;
3154 if (!get_file_security (fname, si, psd, 0, &sd_len))
3156 err = GetLastError ();
3157 if (err != ERROR_INSUFFICIENT_BUFFER)
3158 return NULL;
3161 psd = xmalloc (sd_len);
3162 if (!get_file_security (fname, si, psd, sd_len, &sd_len))
3164 xfree (psd);
3165 return NULL;
3168 return psd;
3171 static DWORD
3172 get_rid (PSID sid)
3174 unsigned n_subauthorities;
3176 /* Use the last sub-authority value of the RID, the relative
3177 portion of the SID, as user/group ID. */
3178 n_subauthorities = *get_sid_sub_authority_count (sid);
3179 if (n_subauthorities < 1)
3180 return 0; /* the "World" RID */
3181 return *get_sid_sub_authority (sid, n_subauthorities - 1);
3184 /* Caching SID and account values for faster lokup. */
3186 #ifdef __GNUC__
3187 # define FLEXIBLE_ARRAY_MEMBER
3188 #else
3189 # define FLEXIBLE_ARRAY_MEMBER 1
3190 #endif
3192 struct w32_id {
3193 unsigned rid;
3194 struct w32_id *next;
3195 char name[GNLEN+1];
3196 unsigned char sid[FLEXIBLE_ARRAY_MEMBER];
3199 static struct w32_id *w32_idlist;
3201 static int
3202 w32_cached_id (PSID sid, unsigned *id, char *name)
3204 struct w32_id *tail, *found;
3206 for (found = NULL, tail = w32_idlist; tail; tail = tail->next)
3208 if (equal_sid ((PSID)tail->sid, sid))
3210 found = tail;
3211 break;
3214 if (found)
3216 *id = found->rid;
3217 strcpy (name, found->name);
3218 return 1;
3220 else
3221 return 0;
3224 static void
3225 w32_add_to_cache (PSID sid, unsigned id, char *name)
3227 DWORD sid_len;
3228 struct w32_id *new_entry;
3230 /* We don't want to leave behind stale cache from when Emacs was
3231 dumped. */
3232 if (initialized)
3234 sid_len = get_length_sid (sid);
3235 new_entry = xmalloc (offsetof (struct w32_id, sid) + sid_len);
3236 if (new_entry)
3238 new_entry->rid = id;
3239 strcpy (new_entry->name, name);
3240 copy_sid (sid_len, (PSID)new_entry->sid, sid);
3241 new_entry->next = w32_idlist;
3242 w32_idlist = new_entry;
3247 #define UID 1
3248 #define GID 2
3250 static int
3251 get_name_and_id (PSECURITY_DESCRIPTOR psd, const char *fname,
3252 unsigned *id, char *nm, int what)
3254 PSID sid = NULL;
3255 char machine[MAX_COMPUTERNAME_LENGTH+1];
3256 BOOL dflt;
3257 SID_NAME_USE ignore;
3258 char name[UNLEN+1];
3259 DWORD name_len = sizeof (name);
3260 char domain[1024];
3261 DWORD domain_len = sizeof (domain);
3262 char *mp = NULL;
3263 int use_dflt = 0;
3264 int result;
3266 if (what == UID)
3267 result = get_security_descriptor_owner (psd, &sid, &dflt);
3268 else if (what == GID)
3269 result = get_security_descriptor_group (psd, &sid, &dflt);
3270 else
3271 result = 0;
3273 if (!result || !is_valid_sid (sid))
3274 use_dflt = 1;
3275 else if (!w32_cached_id (sid, id, nm))
3277 /* If FNAME is a UNC, we need to lookup account on the
3278 specified machine. */
3279 if (IS_DIRECTORY_SEP (fname[0]) && IS_DIRECTORY_SEP (fname[1])
3280 && fname[2] != '\0')
3282 const char *s;
3283 char *p;
3285 for (s = fname + 2, p = machine;
3286 *s && !IS_DIRECTORY_SEP (*s); s++, p++)
3287 *p = *s;
3288 *p = '\0';
3289 mp = machine;
3292 if (!lookup_account_sid (mp, sid, name, &name_len,
3293 domain, &domain_len, &ignore)
3294 || name_len > UNLEN+1)
3295 use_dflt = 1;
3296 else
3298 *id = get_rid (sid);
3299 strcpy (nm, name);
3300 w32_add_to_cache (sid, *id, name);
3303 return use_dflt;
3306 static void
3307 get_file_owner_and_group (PSECURITY_DESCRIPTOR psd,
3308 const char *fname,
3309 struct stat *st)
3311 int dflt_usr = 0, dflt_grp = 0;
3313 if (!psd)
3315 dflt_usr = 1;
3316 dflt_grp = 1;
3318 else
3320 if (get_name_and_id (psd, fname, &st->st_uid, st->st_uname, UID))
3321 dflt_usr = 1;
3322 if (get_name_and_id (psd, fname, &st->st_gid, st->st_gname, GID))
3323 dflt_grp = 1;
3325 /* Consider files to belong to current user/group, if we cannot get
3326 more accurate information. */
3327 if (dflt_usr)
3329 st->st_uid = dflt_passwd.pw_uid;
3330 strcpy (st->st_uname, dflt_passwd.pw_name);
3332 if (dflt_grp)
3334 st->st_gid = dflt_passwd.pw_gid;
3335 strcpy (st->st_gname, dflt_group.gr_name);
3339 /* Return non-zero if NAME is a potentially slow filesystem. */
3341 is_slow_fs (const char *name)
3343 char drive_root[4];
3344 UINT devtype;
3346 if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
3347 devtype = DRIVE_REMOTE; /* assume UNC name is remote */
3348 else if (!(strlen (name) >= 2 && IS_DEVICE_SEP (name[1])))
3349 devtype = GetDriveType (NULL); /* use root of current drive */
3350 else
3352 /* GetDriveType needs the root directory of the drive. */
3353 strncpy (drive_root, name, 2);
3354 drive_root[2] = '\\';
3355 drive_root[3] = '\0';
3356 devtype = GetDriveType (drive_root);
3358 return !(devtype == DRIVE_FIXED || devtype == DRIVE_RAMDISK);
3361 /* MSVC stat function can't cope with UNC names and has other bugs, so
3362 replace it with our own. This also allows us to calculate consistent
3363 inode values without hacks in the main Emacs code. */
3365 stat (const char * path, struct stat * buf)
3367 char *name, *r;
3368 WIN32_FIND_DATA wfd;
3369 HANDLE fh;
3370 unsigned __int64 fake_inode;
3371 int permission;
3372 int len;
3373 int rootdir = FALSE;
3374 PSECURITY_DESCRIPTOR psd = NULL;
3376 if (path == NULL || buf == NULL)
3378 errno = EFAULT;
3379 return -1;
3382 name = (char *) map_w32_filename (path, &path);
3383 /* Must be valid filename, no wild cards or other invalid
3384 characters. We use _mbspbrk to support multibyte strings that
3385 might look to strpbrk as if they included literal *, ?, and other
3386 characters mentioned below that are disallowed by Windows
3387 filesystems. */
3388 if (_mbspbrk (name, "*?|<>\""))
3390 errno = ENOENT;
3391 return -1;
3394 /* If name is "c:/.." or "/.." then stat "c:/" or "/". */
3395 r = IS_DEVICE_SEP (name[1]) ? &name[2] : name;
3396 if (IS_DIRECTORY_SEP (r[0]) && r[1] == '.' && r[2] == '.' && r[3] == '\0')
3398 r[1] = r[2] = '\0';
3401 /* Remove trailing directory separator, unless name is the root
3402 directory of a drive or UNC volume in which case ensure there
3403 is a trailing separator. */
3404 len = strlen (name);
3405 rootdir = (path >= name + len - 1
3406 && (IS_DIRECTORY_SEP (*path) || *path == 0));
3407 name = strcpy (alloca (len + 2), name);
3409 if (is_unc_volume (name))
3411 DWORD attrs = unc_volume_file_attributes (name);
3413 if (attrs == -1)
3414 return -1;
3416 memset (&wfd, 0, sizeof (wfd));
3417 wfd.dwFileAttributes = attrs;
3418 wfd.ftCreationTime = utc_base_ft;
3419 wfd.ftLastAccessTime = utc_base_ft;
3420 wfd.ftLastWriteTime = utc_base_ft;
3421 strcpy (wfd.cFileName, name);
3423 else if (rootdir)
3425 if (!IS_DIRECTORY_SEP (name[len-1]))
3426 strcat (name, "\\");
3427 if (GetDriveType (name) < 2)
3429 errno = ENOENT;
3430 return -1;
3432 memset (&wfd, 0, sizeof (wfd));
3433 wfd.dwFileAttributes = FILE_ATTRIBUTE_DIRECTORY;
3434 wfd.ftCreationTime = utc_base_ft;
3435 wfd.ftLastAccessTime = utc_base_ft;
3436 wfd.ftLastWriteTime = utc_base_ft;
3437 strcpy (wfd.cFileName, name);
3439 else
3441 if (IS_DIRECTORY_SEP (name[len-1]))
3442 name[len - 1] = 0;
3444 /* (This is hacky, but helps when doing file completions on
3445 network drives.) Optimize by using information available from
3446 active readdir if possible. */
3447 len = strlen (dir_pathname);
3448 if (IS_DIRECTORY_SEP (dir_pathname[len-1]))
3449 len--;
3450 if (dir_find_handle != INVALID_HANDLE_VALUE
3451 && strnicmp (name, dir_pathname, len) == 0
3452 && IS_DIRECTORY_SEP (name[len])
3453 && xstrcasecmp (name + len + 1, dir_static.d_name) == 0)
3455 /* This was the last entry returned by readdir. */
3456 wfd = dir_find_data;
3458 else
3460 logon_network_drive (name);
3462 fh = FindFirstFile (name, &wfd);
3463 if (fh == INVALID_HANDLE_VALUE)
3465 errno = ENOENT;
3466 return -1;
3468 FindClose (fh);
3472 if (!(NILP (Vw32_get_true_file_attributes)
3473 || (EQ (Vw32_get_true_file_attributes, Qlocal) && is_slow_fs (name)))
3474 /* No access rights required to get info. */
3475 && (fh = CreateFile (name, 0, 0, NULL, OPEN_EXISTING,
3476 FILE_FLAG_BACKUP_SEMANTICS, NULL))
3477 != INVALID_HANDLE_VALUE)
3479 /* This is more accurate in terms of getting the correct number
3480 of links, but is quite slow (it is noticeable when Emacs is
3481 making a list of file name completions). */
3482 BY_HANDLE_FILE_INFORMATION info;
3484 if (GetFileInformationByHandle (fh, &info))
3486 buf->st_nlink = info.nNumberOfLinks;
3487 /* Might as well use file index to fake inode values, but this
3488 is not guaranteed to be unique unless we keep a handle open
3489 all the time (even then there are situations where it is
3490 not unique). Reputedly, there are at most 48 bits of info
3491 (on NTFS, presumably less on FAT). */
3492 fake_inode = info.nFileIndexHigh;
3493 fake_inode <<= 32;
3494 fake_inode += info.nFileIndexLow;
3496 else
3498 buf->st_nlink = 1;
3499 fake_inode = 0;
3502 if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
3504 buf->st_mode = S_IFDIR;
3506 else
3508 switch (GetFileType (fh))
3510 case FILE_TYPE_DISK:
3511 buf->st_mode = S_IFREG;
3512 break;
3513 case FILE_TYPE_PIPE:
3514 buf->st_mode = S_IFIFO;
3515 break;
3516 case FILE_TYPE_CHAR:
3517 case FILE_TYPE_UNKNOWN:
3518 default:
3519 buf->st_mode = S_IFCHR;
3522 CloseHandle (fh);
3523 psd = get_file_security_desc (name);
3524 get_file_owner_and_group (psd, name, buf);
3526 else
3528 /* Don't bother to make this information more accurate. */
3529 buf->st_mode = (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ?
3530 S_IFDIR : S_IFREG;
3531 buf->st_nlink = 1;
3532 fake_inode = 0;
3534 get_file_owner_and_group (NULL, name, buf);
3536 xfree (psd);
3538 #if 0
3539 /* Not sure if there is any point in this. */
3540 if (!NILP (Vw32_generate_fake_inodes))
3541 fake_inode = generate_inode_val (name);
3542 else if (fake_inode == 0)
3544 /* For want of something better, try to make everything unique. */
3545 static DWORD gen_num = 0;
3546 fake_inode = ++gen_num;
3548 #endif
3550 /* MSVC defines _ino_t to be short; other libc's might not. */
3551 if (sizeof (buf->st_ino) == 2)
3552 buf->st_ino = fake_inode ^ (fake_inode >> 16);
3553 else
3554 buf->st_ino = fake_inode;
3556 /* volume_info is set indirectly by map_w32_filename */
3557 buf->st_dev = volume_info.serialnum;
3558 buf->st_rdev = volume_info.serialnum;
3560 buf->st_size = wfd.nFileSizeHigh;
3561 buf->st_size <<= 32;
3562 buf->st_size += wfd.nFileSizeLow;
3564 /* Convert timestamps to Unix format. */
3565 buf->st_mtime = convert_time (wfd.ftLastWriteTime);
3566 buf->st_atime = convert_time (wfd.ftLastAccessTime);
3567 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
3568 buf->st_ctime = convert_time (wfd.ftCreationTime);
3569 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
3571 /* determine rwx permissions */
3572 if (wfd.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
3573 permission = S_IREAD;
3574 else
3575 permission = S_IREAD | S_IWRITE;
3577 if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
3578 permission |= S_IEXEC;
3579 else if (is_exec (name))
3580 permission |= S_IEXEC;
3582 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
3584 return 0;
3587 /* Provide fstat and utime as well as stat for consistent handling of
3588 file timestamps. */
3590 fstat (int desc, struct stat * buf)
3592 HANDLE fh = (HANDLE) _get_osfhandle (desc);
3593 BY_HANDLE_FILE_INFORMATION info;
3594 unsigned __int64 fake_inode;
3595 int permission;
3597 switch (GetFileType (fh) & ~FILE_TYPE_REMOTE)
3599 case FILE_TYPE_DISK:
3600 buf->st_mode = S_IFREG;
3601 if (!GetFileInformationByHandle (fh, &info))
3603 errno = EACCES;
3604 return -1;
3606 break;
3607 case FILE_TYPE_PIPE:
3608 buf->st_mode = S_IFIFO;
3609 goto non_disk;
3610 case FILE_TYPE_CHAR:
3611 case FILE_TYPE_UNKNOWN:
3612 default:
3613 buf->st_mode = S_IFCHR;
3614 non_disk:
3615 memset (&info, 0, sizeof (info));
3616 info.dwFileAttributes = 0;
3617 info.ftCreationTime = utc_base_ft;
3618 info.ftLastAccessTime = utc_base_ft;
3619 info.ftLastWriteTime = utc_base_ft;
3622 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
3623 buf->st_mode = S_IFDIR;
3625 buf->st_nlink = info.nNumberOfLinks;
3626 /* Might as well use file index to fake inode values, but this
3627 is not guaranteed to be unique unless we keep a handle open
3628 all the time (even then there are situations where it is
3629 not unique). Reputedly, there are at most 48 bits of info
3630 (on NTFS, presumably less on FAT). */
3631 fake_inode = info.nFileIndexHigh;
3632 fake_inode <<= 32;
3633 fake_inode += info.nFileIndexLow;
3635 /* MSVC defines _ino_t to be short; other libc's might not. */
3636 if (sizeof (buf->st_ino) == 2)
3637 buf->st_ino = fake_inode ^ (fake_inode >> 16);
3638 else
3639 buf->st_ino = fake_inode;
3641 /* Consider files to belong to current user.
3642 FIXME: this should use GetSecurityInfo API, but it is only
3643 available for _WIN32_WINNT >= 0x501. */
3644 buf->st_uid = dflt_passwd.pw_uid;
3645 buf->st_gid = dflt_passwd.pw_gid;
3646 strcpy (buf->st_uname, dflt_passwd.pw_name);
3647 strcpy (buf->st_gname, dflt_group.gr_name);
3649 buf->st_dev = info.dwVolumeSerialNumber;
3650 buf->st_rdev = info.dwVolumeSerialNumber;
3652 buf->st_size = info.nFileSizeHigh;
3653 buf->st_size <<= 32;
3654 buf->st_size += info.nFileSizeLow;
3656 /* Convert timestamps to Unix format. */
3657 buf->st_mtime = convert_time (info.ftLastWriteTime);
3658 buf->st_atime = convert_time (info.ftLastAccessTime);
3659 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
3660 buf->st_ctime = convert_time (info.ftCreationTime);
3661 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
3663 /* determine rwx permissions */
3664 if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
3665 permission = S_IREAD;
3666 else
3667 permission = S_IREAD | S_IWRITE;
3669 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
3670 permission |= S_IEXEC;
3671 else
3673 #if 0 /* no way of knowing the filename */
3674 char * p = strrchr (name, '.');
3675 if (p != NULL &&
3676 (xstrcasecmp (p, ".exe") == 0 ||
3677 xstrcasecmp (p, ".com") == 0 ||
3678 xstrcasecmp (p, ".bat") == 0 ||
3679 xstrcasecmp (p, ".cmd") == 0))
3680 permission |= S_IEXEC;
3681 #endif
3684 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
3686 return 0;
3690 utime (const char *name, struct utimbuf *times)
3692 struct utimbuf deftime;
3693 HANDLE fh;
3694 FILETIME mtime;
3695 FILETIME atime;
3697 if (times == NULL)
3699 deftime.modtime = deftime.actime = time (NULL);
3700 times = &deftime;
3703 /* Need write access to set times. */
3704 fh = CreateFile (name, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
3705 0, OPEN_EXISTING, 0, NULL);
3706 if (fh)
3708 convert_from_time_t (times->actime, &atime);
3709 convert_from_time_t (times->modtime, &mtime);
3710 if (!SetFileTime (fh, NULL, &atime, &mtime))
3712 CloseHandle (fh);
3713 errno = EACCES;
3714 return -1;
3716 CloseHandle (fh);
3718 else
3720 errno = EINVAL;
3721 return -1;
3723 return 0;
3727 /* Symlink-related functions that always fail. Used in fileio.c and in
3728 sysdep.c to avoid #ifdef's. */
3730 symlink (char const *dummy1, char const *dummy2)
3732 errno = ENOSYS;
3733 return -1;
3736 ssize_t
3737 readlink (const char *name, char *dummy1, size_t dummy2)
3739 /* `access' is much faster than `stat' on MS-Windows. */
3740 if (sys_access (name, 0) == 0)
3741 errno = EINVAL;
3742 return -1;
3745 char *
3746 careadlinkat (int fd, char const *filename,
3747 char *buffer, size_t buffer_size,
3748 struct allocator const *alloc,
3749 ssize_t (*preadlinkat) (int, char const *, char *, size_t))
3751 errno = ENOSYS;
3752 return NULL;
3755 ssize_t
3756 careadlinkatcwd (int fd, char const *filename, char *buffer,
3757 size_t buffer_size)
3759 (void) fd;
3760 return readlink (filename, buffer, buffer_size);
3764 /* Support for browsing other processes and their attributes. See
3765 process.c for the Lisp bindings. */
3767 /* Helper wrapper functions. */
3769 static HANDLE WINAPI
3770 create_toolhelp32_snapshot (DWORD Flags, DWORD Ignored)
3772 static CreateToolhelp32Snapshot_Proc s_pfn_Create_Toolhelp32_Snapshot = NULL;
3774 if (g_b_init_create_toolhelp32_snapshot == 0)
3776 g_b_init_create_toolhelp32_snapshot = 1;
3777 s_pfn_Create_Toolhelp32_Snapshot = (CreateToolhelp32Snapshot_Proc)
3778 GetProcAddress (GetModuleHandle ("kernel32.dll"),
3779 "CreateToolhelp32Snapshot");
3781 if (s_pfn_Create_Toolhelp32_Snapshot == NULL)
3783 return INVALID_HANDLE_VALUE;
3785 return (s_pfn_Create_Toolhelp32_Snapshot (Flags, Ignored));
3788 static BOOL WINAPI
3789 process32_first (HANDLE hSnapshot, LPPROCESSENTRY32 lppe)
3791 static Process32First_Proc s_pfn_Process32_First = NULL;
3793 if (g_b_init_process32_first == 0)
3795 g_b_init_process32_first = 1;
3796 s_pfn_Process32_First = (Process32First_Proc)
3797 GetProcAddress (GetModuleHandle ("kernel32.dll"),
3798 "Process32First");
3800 if (s_pfn_Process32_First == NULL)
3802 return FALSE;
3804 return (s_pfn_Process32_First (hSnapshot, lppe));
3807 static BOOL WINAPI
3808 process32_next (HANDLE hSnapshot, LPPROCESSENTRY32 lppe)
3810 static Process32Next_Proc s_pfn_Process32_Next = NULL;
3812 if (g_b_init_process32_next == 0)
3814 g_b_init_process32_next = 1;
3815 s_pfn_Process32_Next = (Process32Next_Proc)
3816 GetProcAddress (GetModuleHandle ("kernel32.dll"),
3817 "Process32Next");
3819 if (s_pfn_Process32_Next == NULL)
3821 return FALSE;
3823 return (s_pfn_Process32_Next (hSnapshot, lppe));
3826 static BOOL WINAPI
3827 open_thread_token (HANDLE ThreadHandle,
3828 DWORD DesiredAccess,
3829 BOOL OpenAsSelf,
3830 PHANDLE TokenHandle)
3832 static OpenThreadToken_Proc s_pfn_Open_Thread_Token = NULL;
3833 HMODULE hm_advapi32 = NULL;
3834 if (is_windows_9x () == TRUE)
3836 SetLastError (ERROR_NOT_SUPPORTED);
3837 return FALSE;
3839 if (g_b_init_open_thread_token == 0)
3841 g_b_init_open_thread_token = 1;
3842 hm_advapi32 = LoadLibrary ("Advapi32.dll");
3843 s_pfn_Open_Thread_Token =
3844 (OpenThreadToken_Proc) GetProcAddress (hm_advapi32, "OpenThreadToken");
3846 if (s_pfn_Open_Thread_Token == NULL)
3848 SetLastError (ERROR_NOT_SUPPORTED);
3849 return FALSE;
3851 return (
3852 s_pfn_Open_Thread_Token (
3853 ThreadHandle,
3854 DesiredAccess,
3855 OpenAsSelf,
3856 TokenHandle)
3860 static BOOL WINAPI
3861 impersonate_self (SECURITY_IMPERSONATION_LEVEL ImpersonationLevel)
3863 static ImpersonateSelf_Proc s_pfn_Impersonate_Self = NULL;
3864 HMODULE hm_advapi32 = NULL;
3865 if (is_windows_9x () == TRUE)
3867 return FALSE;
3869 if (g_b_init_impersonate_self == 0)
3871 g_b_init_impersonate_self = 1;
3872 hm_advapi32 = LoadLibrary ("Advapi32.dll");
3873 s_pfn_Impersonate_Self =
3874 (ImpersonateSelf_Proc) GetProcAddress (hm_advapi32, "ImpersonateSelf");
3876 if (s_pfn_Impersonate_Self == NULL)
3878 return FALSE;
3880 return s_pfn_Impersonate_Self (ImpersonationLevel);
3883 static BOOL WINAPI
3884 revert_to_self (void)
3886 static RevertToSelf_Proc s_pfn_Revert_To_Self = NULL;
3887 HMODULE hm_advapi32 = NULL;
3888 if (is_windows_9x () == TRUE)
3890 return FALSE;
3892 if (g_b_init_revert_to_self == 0)
3894 g_b_init_revert_to_self = 1;
3895 hm_advapi32 = LoadLibrary ("Advapi32.dll");
3896 s_pfn_Revert_To_Self =
3897 (RevertToSelf_Proc) GetProcAddress (hm_advapi32, "RevertToSelf");
3899 if (s_pfn_Revert_To_Self == NULL)
3901 return FALSE;
3903 return s_pfn_Revert_To_Self ();
3906 static BOOL WINAPI
3907 get_process_memory_info (HANDLE h_proc,
3908 PPROCESS_MEMORY_COUNTERS mem_counters,
3909 DWORD bufsize)
3911 static GetProcessMemoryInfo_Proc s_pfn_Get_Process_Memory_Info = NULL;
3912 HMODULE hm_psapi = NULL;
3913 if (is_windows_9x () == TRUE)
3915 return FALSE;
3917 if (g_b_init_get_process_memory_info == 0)
3919 g_b_init_get_process_memory_info = 1;
3920 hm_psapi = LoadLibrary ("Psapi.dll");
3921 if (hm_psapi)
3922 s_pfn_Get_Process_Memory_Info = (GetProcessMemoryInfo_Proc)
3923 GetProcAddress (hm_psapi, "GetProcessMemoryInfo");
3925 if (s_pfn_Get_Process_Memory_Info == NULL)
3927 return FALSE;
3929 return s_pfn_Get_Process_Memory_Info (h_proc, mem_counters, bufsize);
3932 static BOOL WINAPI
3933 get_process_working_set_size (HANDLE h_proc,
3934 DWORD *minrss,
3935 DWORD *maxrss)
3937 static GetProcessWorkingSetSize_Proc
3938 s_pfn_Get_Process_Working_Set_Size = NULL;
3940 if (is_windows_9x () == TRUE)
3942 return FALSE;
3944 if (g_b_init_get_process_working_set_size == 0)
3946 g_b_init_get_process_working_set_size = 1;
3947 s_pfn_Get_Process_Working_Set_Size = (GetProcessWorkingSetSize_Proc)
3948 GetProcAddress (GetModuleHandle ("kernel32.dll"),
3949 "GetProcessWorkingSetSize");
3951 if (s_pfn_Get_Process_Working_Set_Size == NULL)
3953 return FALSE;
3955 return s_pfn_Get_Process_Working_Set_Size (h_proc, minrss, maxrss);
3958 static BOOL WINAPI
3959 global_memory_status (MEMORYSTATUS *buf)
3961 static GlobalMemoryStatus_Proc s_pfn_Global_Memory_Status = NULL;
3963 if (is_windows_9x () == TRUE)
3965 return FALSE;
3967 if (g_b_init_global_memory_status == 0)
3969 g_b_init_global_memory_status = 1;
3970 s_pfn_Global_Memory_Status = (GlobalMemoryStatus_Proc)
3971 GetProcAddress (GetModuleHandle ("kernel32.dll"),
3972 "GlobalMemoryStatus");
3974 if (s_pfn_Global_Memory_Status == NULL)
3976 return FALSE;
3978 return s_pfn_Global_Memory_Status (buf);
3981 static BOOL WINAPI
3982 global_memory_status_ex (MEMORY_STATUS_EX *buf)
3984 static GlobalMemoryStatusEx_Proc s_pfn_Global_Memory_Status_Ex = NULL;
3986 if (is_windows_9x () == TRUE)
3988 return FALSE;
3990 if (g_b_init_global_memory_status_ex == 0)
3992 g_b_init_global_memory_status_ex = 1;
3993 s_pfn_Global_Memory_Status_Ex = (GlobalMemoryStatusEx_Proc)
3994 GetProcAddress (GetModuleHandle ("kernel32.dll"),
3995 "GlobalMemoryStatusEx");
3997 if (s_pfn_Global_Memory_Status_Ex == NULL)
3999 return FALSE;
4001 return s_pfn_Global_Memory_Status_Ex (buf);
4004 Lisp_Object
4005 list_system_processes (void)
4007 struct gcpro gcpro1;
4008 Lisp_Object proclist = Qnil;
4009 HANDLE h_snapshot;
4011 h_snapshot = create_toolhelp32_snapshot (TH32CS_SNAPPROCESS, 0);
4013 if (h_snapshot != INVALID_HANDLE_VALUE)
4015 PROCESSENTRY32 proc_entry;
4016 DWORD proc_id;
4017 BOOL res;
4019 GCPRO1 (proclist);
4021 proc_entry.dwSize = sizeof (PROCESSENTRY32);
4022 for (res = process32_first (h_snapshot, &proc_entry); res;
4023 res = process32_next (h_snapshot, &proc_entry))
4025 proc_id = proc_entry.th32ProcessID;
4026 proclist = Fcons (make_fixnum_or_float (proc_id), proclist);
4029 CloseHandle (h_snapshot);
4030 UNGCPRO;
4031 proclist = Fnreverse (proclist);
4034 return proclist;
4037 static int
4038 enable_privilege (LPCTSTR priv_name, BOOL enable_p, TOKEN_PRIVILEGES *old_priv)
4040 TOKEN_PRIVILEGES priv;
4041 DWORD priv_size = sizeof (priv);
4042 DWORD opriv_size = sizeof (*old_priv);
4043 HANDLE h_token = NULL;
4044 HANDLE h_thread = GetCurrentThread ();
4045 int ret_val = 0;
4046 BOOL res;
4048 res = open_thread_token (h_thread,
4049 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
4050 FALSE, &h_token);
4051 if (!res && GetLastError () == ERROR_NO_TOKEN)
4053 if (impersonate_self (SecurityImpersonation))
4054 res = open_thread_token (h_thread,
4055 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
4056 FALSE, &h_token);
4058 if (res)
4060 priv.PrivilegeCount = 1;
4061 priv.Privileges[0].Attributes = enable_p ? SE_PRIVILEGE_ENABLED : 0;
4062 LookupPrivilegeValue (NULL, priv_name, &priv.Privileges[0].Luid);
4063 if (AdjustTokenPrivileges (h_token, FALSE, &priv, priv_size,
4064 old_priv, &opriv_size)
4065 && GetLastError () != ERROR_NOT_ALL_ASSIGNED)
4066 ret_val = 1;
4068 if (h_token)
4069 CloseHandle (h_token);
4071 return ret_val;
4074 static int
4075 restore_privilege (TOKEN_PRIVILEGES *priv)
4077 DWORD priv_size = sizeof (*priv);
4078 HANDLE h_token = NULL;
4079 int ret_val = 0;
4081 if (open_thread_token (GetCurrentThread (),
4082 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
4083 FALSE, &h_token))
4085 if (AdjustTokenPrivileges (h_token, FALSE, priv, priv_size, NULL, NULL)
4086 && GetLastError () != ERROR_NOT_ALL_ASSIGNED)
4087 ret_val = 1;
4089 if (h_token)
4090 CloseHandle (h_token);
4092 return ret_val;
4095 static Lisp_Object
4096 ltime (ULONGLONG time_100ns)
4098 ULONGLONG time_sec = time_100ns / 10000000;
4099 int subsec = time_100ns % 10000000;
4100 return list4 (make_number (time_sec >> 16),
4101 make_number (time_sec & 0xffff),
4102 make_number (subsec / 10),
4103 make_number (subsec % 10 * 100000));
4106 #define U64_TO_LISP_TIME(time) ltime (time)
4108 static int
4109 process_times (HANDLE h_proc, Lisp_Object *ctime, Lisp_Object *etime,
4110 Lisp_Object *stime, Lisp_Object *utime, Lisp_Object *ttime,
4111 double *pcpu)
4113 FILETIME ft_creation, ft_exit, ft_kernel, ft_user, ft_current;
4114 ULONGLONG tem1, tem2, tem3, tem;
4116 if (!h_proc
4117 || !get_process_times_fn
4118 || !(*get_process_times_fn) (h_proc, &ft_creation, &ft_exit,
4119 &ft_kernel, &ft_user))
4120 return 0;
4122 GetSystemTimeAsFileTime (&ft_current);
4124 FILETIME_TO_U64 (tem1, ft_kernel);
4125 *stime = U64_TO_LISP_TIME (tem1);
4127 FILETIME_TO_U64 (tem2, ft_user);
4128 *utime = U64_TO_LISP_TIME (tem2);
4130 tem3 = tem1 + tem2;
4131 *ttime = U64_TO_LISP_TIME (tem3);
4133 FILETIME_TO_U64 (tem, ft_creation);
4134 /* Process no 4 (System) returns zero creation time. */
4135 if (tem)
4136 tem -= utc_base;
4137 *ctime = U64_TO_LISP_TIME (tem);
4139 if (tem)
4141 FILETIME_TO_U64 (tem3, ft_current);
4142 tem = (tem3 - utc_base) - tem;
4144 *etime = U64_TO_LISP_TIME (tem);
4146 if (tem)
4148 *pcpu = 100.0 * (tem1 + tem2) / tem;
4149 if (*pcpu > 100)
4150 *pcpu = 100.0;
4152 else
4153 *pcpu = 0;
4155 return 1;
4158 Lisp_Object
4159 system_process_attributes (Lisp_Object pid)
4161 struct gcpro gcpro1, gcpro2, gcpro3;
4162 Lisp_Object attrs = Qnil;
4163 Lisp_Object cmd_str, decoded_cmd, tem;
4164 HANDLE h_snapshot, h_proc;
4165 DWORD proc_id;
4166 int found_proc = 0;
4167 char uname[UNLEN+1], gname[GNLEN+1], domain[1025];
4168 DWORD ulength = sizeof (uname), dlength = sizeof (domain), needed;
4169 DWORD glength = sizeof (gname);
4170 HANDLE token = NULL;
4171 SID_NAME_USE user_type;
4172 unsigned char *buf = NULL;
4173 DWORD blen = 0;
4174 TOKEN_USER user_token;
4175 TOKEN_PRIMARY_GROUP group_token;
4176 unsigned euid;
4177 unsigned egid;
4178 PROCESS_MEMORY_COUNTERS mem;
4179 PROCESS_MEMORY_COUNTERS_EX mem_ex;
4180 DWORD minrss, maxrss;
4181 MEMORYSTATUS memst;
4182 MEMORY_STATUS_EX memstex;
4183 double totphys = 0.0;
4184 Lisp_Object ctime, stime, utime, etime, ttime;
4185 double pcpu;
4186 BOOL result = FALSE;
4188 CHECK_NUMBER_OR_FLOAT (pid);
4189 proc_id = FLOATP (pid) ? XFLOAT_DATA (pid) : XINT (pid);
4191 h_snapshot = create_toolhelp32_snapshot (TH32CS_SNAPPROCESS, 0);
4193 GCPRO3 (attrs, decoded_cmd, tem);
4195 if (h_snapshot != INVALID_HANDLE_VALUE)
4197 PROCESSENTRY32 pe;
4198 BOOL res;
4200 pe.dwSize = sizeof (PROCESSENTRY32);
4201 for (res = process32_first (h_snapshot, &pe); res;
4202 res = process32_next (h_snapshot, &pe))
4204 if (proc_id == pe.th32ProcessID)
4206 if (proc_id == 0)
4207 decoded_cmd = build_string ("Idle");
4208 else
4210 /* Decode the command name from locale-specific
4211 encoding. */
4212 cmd_str = make_unibyte_string (pe.szExeFile,
4213 strlen (pe.szExeFile));
4214 decoded_cmd =
4215 code_convert_string_norecord (cmd_str,
4216 Vlocale_coding_system, 0);
4218 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
4219 attrs = Fcons (Fcons (Qppid,
4220 make_fixnum_or_float (pe.th32ParentProcessID)),
4221 attrs);
4222 attrs = Fcons (Fcons (Qpri, make_number (pe.pcPriClassBase)),
4223 attrs);
4224 attrs = Fcons (Fcons (Qthcount,
4225 make_fixnum_or_float (pe.cntThreads)),
4226 attrs);
4227 found_proc = 1;
4228 break;
4232 CloseHandle (h_snapshot);
4235 if (!found_proc)
4237 UNGCPRO;
4238 return Qnil;
4241 h_proc = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
4242 FALSE, proc_id);
4243 /* If we were denied a handle to the process, try again after
4244 enabling the SeDebugPrivilege in our process. */
4245 if (!h_proc)
4247 TOKEN_PRIVILEGES priv_current;
4249 if (enable_privilege (SE_DEBUG_NAME, TRUE, &priv_current))
4251 h_proc = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
4252 FALSE, proc_id);
4253 restore_privilege (&priv_current);
4254 revert_to_self ();
4257 if (h_proc)
4259 result = open_process_token (h_proc, TOKEN_QUERY, &token);
4260 if (result)
4262 result = get_token_information (token, TokenUser, NULL, 0, &blen);
4263 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
4265 buf = xmalloc (blen);
4266 result = get_token_information (token, TokenUser,
4267 (LPVOID)buf, blen, &needed);
4268 if (result)
4270 memcpy (&user_token, buf, sizeof (user_token));
4271 if (!w32_cached_id (user_token.User.Sid, &euid, uname))
4273 euid = get_rid (user_token.User.Sid);
4274 result = lookup_account_sid (NULL, user_token.User.Sid,
4275 uname, &ulength,
4276 domain, &dlength,
4277 &user_type);
4278 if (result)
4279 w32_add_to_cache (user_token.User.Sid, euid, uname);
4280 else
4282 strcpy (uname, "unknown");
4283 result = TRUE;
4286 ulength = strlen (uname);
4290 if (result)
4292 /* Determine a reasonable euid and gid values. */
4293 if (xstrcasecmp ("administrator", uname) == 0)
4295 euid = 500; /* well-known Administrator uid */
4296 egid = 513; /* well-known None gid */
4298 else
4300 /* Get group id and name. */
4301 result = get_token_information (token, TokenPrimaryGroup,
4302 (LPVOID)buf, blen, &needed);
4303 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
4305 buf = xrealloc (buf, blen = needed);
4306 result = get_token_information (token, TokenPrimaryGroup,
4307 (LPVOID)buf, blen, &needed);
4309 if (result)
4311 memcpy (&group_token, buf, sizeof (group_token));
4312 if (!w32_cached_id (group_token.PrimaryGroup, &egid, gname))
4314 egid = get_rid (group_token.PrimaryGroup);
4315 dlength = sizeof (domain);
4316 result =
4317 lookup_account_sid (NULL, group_token.PrimaryGroup,
4318 gname, &glength, NULL, &dlength,
4319 &user_type);
4320 if (result)
4321 w32_add_to_cache (group_token.PrimaryGroup,
4322 egid, gname);
4323 else
4325 strcpy (gname, "None");
4326 result = TRUE;
4329 glength = strlen (gname);
4333 xfree (buf);
4335 if (!result)
4337 if (!is_windows_9x ())
4339 /* We couldn't open the process token, presumably because of
4340 insufficient access rights. Assume this process is run
4341 by the system. */
4342 strcpy (uname, "SYSTEM");
4343 strcpy (gname, "None");
4344 euid = 18; /* SYSTEM */
4345 egid = 513; /* None */
4346 glength = strlen (gname);
4347 ulength = strlen (uname);
4349 /* If we are running under Windows 9X, where security calls are
4350 not supported, we assume all processes are run by the current
4351 user. */
4352 else if (GetUserName (uname, &ulength))
4354 if (xstrcasecmp ("administrator", uname) == 0)
4355 euid = 0;
4356 else
4357 euid = 123;
4358 egid = euid;
4359 strcpy (gname, "None");
4360 glength = strlen (gname);
4361 ulength = strlen (uname);
4363 else
4365 euid = 123;
4366 egid = 123;
4367 strcpy (uname, "administrator");
4368 ulength = strlen (uname);
4369 strcpy (gname, "None");
4370 glength = strlen (gname);
4372 if (token)
4373 CloseHandle (token);
4376 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (euid)), attrs);
4377 tem = make_unibyte_string (uname, ulength);
4378 attrs = Fcons (Fcons (Quser,
4379 code_convert_string_norecord (tem, Vlocale_coding_system, 0)),
4380 attrs);
4381 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (egid)), attrs);
4382 tem = make_unibyte_string (gname, glength);
4383 attrs = Fcons (Fcons (Qgroup,
4384 code_convert_string_norecord (tem, Vlocale_coding_system, 0)),
4385 attrs);
4387 if (global_memory_status_ex (&memstex))
4388 #if __GNUC__ || (defined (_MSC_VER) && _MSC_VER >= 1300)
4389 totphys = memstex.ullTotalPhys / 1024.0;
4390 #else
4391 /* Visual Studio 6 cannot convert an unsigned __int64 type to
4392 double, so we need to do this for it... */
4394 DWORD tot_hi = memstex.ullTotalPhys >> 32;
4395 DWORD tot_md = (memstex.ullTotalPhys & 0x00000000ffffffff) >> 10;
4396 DWORD tot_lo = memstex.ullTotalPhys % 1024;
4398 totphys = tot_hi * 4194304.0 + tot_md + tot_lo / 1024.0;
4400 #endif /* __GNUC__ || _MSC_VER >= 1300 */
4401 else if (global_memory_status (&memst))
4402 totphys = memst.dwTotalPhys / 1024.0;
4404 if (h_proc
4405 && get_process_memory_info (h_proc, (PROCESS_MEMORY_COUNTERS *)&mem_ex,
4406 sizeof (mem_ex)))
4408 DWORD rss = mem_ex.WorkingSetSize / 1024;
4410 attrs = Fcons (Fcons (Qmajflt,
4411 make_fixnum_or_float (mem_ex.PageFaultCount)),
4412 attrs);
4413 attrs = Fcons (Fcons (Qvsize,
4414 make_fixnum_or_float (mem_ex.PrivateUsage / 1024)),
4415 attrs);
4416 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (rss)), attrs);
4417 if (totphys)
4418 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
4420 else if (h_proc
4421 && get_process_memory_info (h_proc, &mem, sizeof (mem)))
4423 DWORD rss = mem_ex.WorkingSetSize / 1024;
4425 attrs = Fcons (Fcons (Qmajflt,
4426 make_fixnum_or_float (mem.PageFaultCount)),
4427 attrs);
4428 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (rss)), attrs);
4429 if (totphys)
4430 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
4432 else if (h_proc
4433 && get_process_working_set_size (h_proc, &minrss, &maxrss))
4435 DWORD rss = maxrss / 1024;
4437 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (maxrss / 1024)), attrs);
4438 if (totphys)
4439 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
4442 if (process_times (h_proc, &ctime, &etime, &stime, &utime, &ttime, &pcpu))
4444 attrs = Fcons (Fcons (Qutime, utime), attrs);
4445 attrs = Fcons (Fcons (Qstime, stime), attrs);
4446 attrs = Fcons (Fcons (Qtime, ttime), attrs);
4447 attrs = Fcons (Fcons (Qstart, ctime), attrs);
4448 attrs = Fcons (Fcons (Qetime, etime), attrs);
4449 attrs = Fcons (Fcons (Qpcpu, make_float (pcpu)), attrs);
4452 /* FIXME: Retrieve command line by walking the PEB of the process. */
4454 if (h_proc)
4455 CloseHandle (h_proc);
4456 UNGCPRO;
4457 return attrs;
4461 /* Wrappers for winsock functions to map between our file descriptors
4462 and winsock's handles; also set h_errno for convenience.
4464 To allow Emacs to run on systems which don't have winsock support
4465 installed, we dynamically link to winsock on startup if present, and
4466 otherwise provide the minimum necessary functionality
4467 (eg. gethostname). */
4469 /* function pointers for relevant socket functions */
4470 int (PASCAL *pfn_WSAStartup) (WORD wVersionRequired, LPWSADATA lpWSAData);
4471 void (PASCAL *pfn_WSASetLastError) (int iError);
4472 int (PASCAL *pfn_WSAGetLastError) (void);
4473 int (PASCAL *pfn_WSAEventSelect) (SOCKET s, HANDLE hEventObject, long lNetworkEvents);
4474 HANDLE (PASCAL *pfn_WSACreateEvent) (void);
4475 int (PASCAL *pfn_WSACloseEvent) (HANDLE hEvent);
4476 int (PASCAL *pfn_socket) (int af, int type, int protocol);
4477 int (PASCAL *pfn_bind) (SOCKET s, const struct sockaddr *addr, int namelen);
4478 int (PASCAL *pfn_connect) (SOCKET s, const struct sockaddr *addr, int namelen);
4479 int (PASCAL *pfn_ioctlsocket) (SOCKET s, long cmd, u_long *argp);
4480 int (PASCAL *pfn_recv) (SOCKET s, char * buf, int len, int flags);
4481 int (PASCAL *pfn_send) (SOCKET s, const char * buf, int len, int flags);
4482 int (PASCAL *pfn_closesocket) (SOCKET s);
4483 int (PASCAL *pfn_shutdown) (SOCKET s, int how);
4484 int (PASCAL *pfn_WSACleanup) (void);
4486 u_short (PASCAL *pfn_htons) (u_short hostshort);
4487 u_short (PASCAL *pfn_ntohs) (u_short netshort);
4488 unsigned long (PASCAL *pfn_inet_addr) (const char * cp);
4489 int (PASCAL *pfn_gethostname) (char * name, int namelen);
4490 struct hostent * (PASCAL *pfn_gethostbyname) (const char * name);
4491 struct servent * (PASCAL *pfn_getservbyname) (const char * name, const char * proto);
4492 int (PASCAL *pfn_getpeername) (SOCKET s, struct sockaddr *addr, int * namelen);
4493 int (PASCAL *pfn_setsockopt) (SOCKET s, int level, int optname,
4494 const char * optval, int optlen);
4495 int (PASCAL *pfn_listen) (SOCKET s, int backlog);
4496 int (PASCAL *pfn_getsockname) (SOCKET s, struct sockaddr * name,
4497 int * namelen);
4498 SOCKET (PASCAL *pfn_accept) (SOCKET s, struct sockaddr * addr, int * addrlen);
4499 int (PASCAL *pfn_recvfrom) (SOCKET s, char * buf, int len, int flags,
4500 struct sockaddr * from, int * fromlen);
4501 int (PASCAL *pfn_sendto) (SOCKET s, const char * buf, int len, int flags,
4502 const struct sockaddr * to, int tolen);
4504 /* SetHandleInformation is only needed to make sockets non-inheritable. */
4505 BOOL (WINAPI *pfn_SetHandleInformation) (HANDLE object, DWORD mask, DWORD flags);
4506 #ifndef HANDLE_FLAG_INHERIT
4507 #define HANDLE_FLAG_INHERIT 1
4508 #endif
4510 HANDLE winsock_lib;
4511 static int winsock_inuse;
4513 BOOL
4514 term_winsock (void)
4516 if (winsock_lib != NULL && winsock_inuse == 0)
4518 /* Not sure what would cause WSAENETDOWN, or even if it can happen
4519 after WSAStartup returns successfully, but it seems reasonable
4520 to allow unloading winsock anyway in that case. */
4521 if (pfn_WSACleanup () == 0 ||
4522 pfn_WSAGetLastError () == WSAENETDOWN)
4524 if (FreeLibrary (winsock_lib))
4525 winsock_lib = NULL;
4526 return TRUE;
4529 return FALSE;
4532 BOOL
4533 init_winsock (int load_now)
4535 WSADATA winsockData;
4537 if (winsock_lib != NULL)
4538 return TRUE;
4540 pfn_SetHandleInformation
4541 = (void *) GetProcAddress (GetModuleHandle ("kernel32.dll"),
4542 "SetHandleInformation");
4544 winsock_lib = LoadLibrary ("Ws2_32.dll");
4546 if (winsock_lib != NULL)
4548 /* dynamically link to socket functions */
4550 #define LOAD_PROC(fn) \
4551 if ((pfn_##fn = (void *) GetProcAddress (winsock_lib, #fn)) == NULL) \
4552 goto fail;
4554 LOAD_PROC (WSAStartup);
4555 LOAD_PROC (WSASetLastError);
4556 LOAD_PROC (WSAGetLastError);
4557 LOAD_PROC (WSAEventSelect);
4558 LOAD_PROC (WSACreateEvent);
4559 LOAD_PROC (WSACloseEvent);
4560 LOAD_PROC (socket);
4561 LOAD_PROC (bind);
4562 LOAD_PROC (connect);
4563 LOAD_PROC (ioctlsocket);
4564 LOAD_PROC (recv);
4565 LOAD_PROC (send);
4566 LOAD_PROC (closesocket);
4567 LOAD_PROC (shutdown);
4568 LOAD_PROC (htons);
4569 LOAD_PROC (ntohs);
4570 LOAD_PROC (inet_addr);
4571 LOAD_PROC (gethostname);
4572 LOAD_PROC (gethostbyname);
4573 LOAD_PROC (getservbyname);
4574 LOAD_PROC (getpeername);
4575 LOAD_PROC (WSACleanup);
4576 LOAD_PROC (setsockopt);
4577 LOAD_PROC (listen);
4578 LOAD_PROC (getsockname);
4579 LOAD_PROC (accept);
4580 LOAD_PROC (recvfrom);
4581 LOAD_PROC (sendto);
4582 #undef LOAD_PROC
4584 /* specify version 1.1 of winsock */
4585 if (pfn_WSAStartup (0x101, &winsockData) == 0)
4587 if (winsockData.wVersion != 0x101)
4588 goto fail;
4590 if (!load_now)
4592 /* Report that winsock exists and is usable, but leave
4593 socket functions disabled. I am assuming that calling
4594 WSAStartup does not require any network interaction,
4595 and in particular does not cause or require a dial-up
4596 connection to be established. */
4598 pfn_WSACleanup ();
4599 FreeLibrary (winsock_lib);
4600 winsock_lib = NULL;
4602 winsock_inuse = 0;
4603 return TRUE;
4606 fail:
4607 FreeLibrary (winsock_lib);
4608 winsock_lib = NULL;
4611 return FALSE;
4615 int h_errno = 0;
4617 /* function to set h_errno for compatibility; map winsock error codes to
4618 normal system codes where they overlap (non-overlapping definitions
4619 are already in <sys/socket.h> */
4620 static void
4621 set_errno (void)
4623 if (winsock_lib == NULL)
4624 h_errno = EINVAL;
4625 else
4626 h_errno = pfn_WSAGetLastError ();
4628 switch (h_errno)
4630 case WSAEACCES: h_errno = EACCES; break;
4631 case WSAEBADF: h_errno = EBADF; break;
4632 case WSAEFAULT: h_errno = EFAULT; break;
4633 case WSAEINTR: h_errno = EINTR; break;
4634 case WSAEINVAL: h_errno = EINVAL; break;
4635 case WSAEMFILE: h_errno = EMFILE; break;
4636 case WSAENAMETOOLONG: h_errno = ENAMETOOLONG; break;
4637 case WSAENOTEMPTY: h_errno = ENOTEMPTY; break;
4639 errno = h_errno;
4642 static void
4643 check_errno (void)
4645 if (h_errno == 0 && winsock_lib != NULL)
4646 pfn_WSASetLastError (0);
4649 /* Extend strerror to handle the winsock-specific error codes. */
4650 struct {
4651 int errnum;
4652 char * msg;
4653 } _wsa_errlist[] = {
4654 {WSAEINTR , "Interrupted function call"},
4655 {WSAEBADF , "Bad file descriptor"},
4656 {WSAEACCES , "Permission denied"},
4657 {WSAEFAULT , "Bad address"},
4658 {WSAEINVAL , "Invalid argument"},
4659 {WSAEMFILE , "Too many open files"},
4661 {WSAEWOULDBLOCK , "Resource temporarily unavailable"},
4662 {WSAEINPROGRESS , "Operation now in progress"},
4663 {WSAEALREADY , "Operation already in progress"},
4664 {WSAENOTSOCK , "Socket operation on non-socket"},
4665 {WSAEDESTADDRREQ , "Destination address required"},
4666 {WSAEMSGSIZE , "Message too long"},
4667 {WSAEPROTOTYPE , "Protocol wrong type for socket"},
4668 {WSAENOPROTOOPT , "Bad protocol option"},
4669 {WSAEPROTONOSUPPORT , "Protocol not supported"},
4670 {WSAESOCKTNOSUPPORT , "Socket type not supported"},
4671 {WSAEOPNOTSUPP , "Operation not supported"},
4672 {WSAEPFNOSUPPORT , "Protocol family not supported"},
4673 {WSAEAFNOSUPPORT , "Address family not supported by protocol family"},
4674 {WSAEADDRINUSE , "Address already in use"},
4675 {WSAEADDRNOTAVAIL , "Cannot assign requested address"},
4676 {WSAENETDOWN , "Network is down"},
4677 {WSAENETUNREACH , "Network is unreachable"},
4678 {WSAENETRESET , "Network dropped connection on reset"},
4679 {WSAECONNABORTED , "Software caused connection abort"},
4680 {WSAECONNRESET , "Connection reset by peer"},
4681 {WSAENOBUFS , "No buffer space available"},
4682 {WSAEISCONN , "Socket is already connected"},
4683 {WSAENOTCONN , "Socket is not connected"},
4684 {WSAESHUTDOWN , "Cannot send after socket shutdown"},
4685 {WSAETOOMANYREFS , "Too many references"}, /* not sure */
4686 {WSAETIMEDOUT , "Connection timed out"},
4687 {WSAECONNREFUSED , "Connection refused"},
4688 {WSAELOOP , "Network loop"}, /* not sure */
4689 {WSAENAMETOOLONG , "Name is too long"},
4690 {WSAEHOSTDOWN , "Host is down"},
4691 {WSAEHOSTUNREACH , "No route to host"},
4692 {WSAENOTEMPTY , "Buffer not empty"}, /* not sure */
4693 {WSAEPROCLIM , "Too many processes"},
4694 {WSAEUSERS , "Too many users"}, /* not sure */
4695 {WSAEDQUOT , "Double quote in host name"}, /* really not sure */
4696 {WSAESTALE , "Data is stale"}, /* not sure */
4697 {WSAEREMOTE , "Remote error"}, /* not sure */
4699 {WSASYSNOTREADY , "Network subsystem is unavailable"},
4700 {WSAVERNOTSUPPORTED , "WINSOCK.DLL version out of range"},
4701 {WSANOTINITIALISED , "Winsock not initialized successfully"},
4702 {WSAEDISCON , "Graceful shutdown in progress"},
4703 #ifdef WSAENOMORE
4704 {WSAENOMORE , "No more operations allowed"}, /* not sure */
4705 {WSAECANCELLED , "Operation cancelled"}, /* not sure */
4706 {WSAEINVALIDPROCTABLE , "Invalid procedure table from service provider"},
4707 {WSAEINVALIDPROVIDER , "Invalid service provider version number"},
4708 {WSAEPROVIDERFAILEDINIT , "Unable to initialize a service provider"},
4709 {WSASYSCALLFAILURE , "System call failure"},
4710 {WSASERVICE_NOT_FOUND , "Service not found"}, /* not sure */
4711 {WSATYPE_NOT_FOUND , "Class type not found"},
4712 {WSA_E_NO_MORE , "No more resources available"}, /* really not sure */
4713 {WSA_E_CANCELLED , "Operation already cancelled"}, /* really not sure */
4714 {WSAEREFUSED , "Operation refused"}, /* not sure */
4715 #endif
4717 {WSAHOST_NOT_FOUND , "Host not found"},
4718 {WSATRY_AGAIN , "Authoritative host not found during name lookup"},
4719 {WSANO_RECOVERY , "Non-recoverable error during name lookup"},
4720 {WSANO_DATA , "Valid name, no data record of requested type"},
4722 {-1, NULL}
4725 char *
4726 sys_strerror (int error_no)
4728 int i;
4729 static char unknown_msg[40];
4731 if (error_no >= 0 && error_no < sys_nerr)
4732 return sys_errlist[error_no];
4734 for (i = 0; _wsa_errlist[i].errnum >= 0; i++)
4735 if (_wsa_errlist[i].errnum == error_no)
4736 return _wsa_errlist[i].msg;
4738 sprintf (unknown_msg, "Unidentified error: %d", error_no);
4739 return unknown_msg;
4742 /* [andrewi 3-May-96] I've had conflicting results using both methods,
4743 but I believe the method of keeping the socket handle separate (and
4744 insuring it is not inheritable) is the correct one. */
4746 #define SOCK_HANDLE(fd) ((SOCKET) fd_info[fd].hnd)
4748 static int socket_to_fd (SOCKET s);
4751 sys_socket (int af, int type, int protocol)
4753 SOCKET s;
4755 if (winsock_lib == NULL)
4757 h_errno = ENETDOWN;
4758 return INVALID_SOCKET;
4761 check_errno ();
4763 /* call the real socket function */
4764 s = pfn_socket (af, type, protocol);
4766 if (s != INVALID_SOCKET)
4767 return socket_to_fd (s);
4769 set_errno ();
4770 return -1;
4773 /* Convert a SOCKET to a file descriptor. */
4774 static int
4775 socket_to_fd (SOCKET s)
4777 int fd;
4778 child_process * cp;
4780 /* Although under NT 3.5 _open_osfhandle will accept a socket
4781 handle, if opened with SO_OPENTYPE == SO_SYNCHRONOUS_NONALERT,
4782 that does not work under NT 3.1. However, we can get the same
4783 effect by using a backdoor function to replace an existing
4784 descriptor handle with the one we want. */
4786 /* allocate a file descriptor (with appropriate flags) */
4787 fd = _open ("NUL:", _O_RDWR);
4788 if (fd >= 0)
4790 /* Make a non-inheritable copy of the socket handle. Note
4791 that it is possible that sockets aren't actually kernel
4792 handles, which appears to be the case on Windows 9x when
4793 the MS Proxy winsock client is installed. */
4795 /* Apparently there is a bug in NT 3.51 with some service
4796 packs, which prevents using DuplicateHandle to make a
4797 socket handle non-inheritable (causes WSACleanup to
4798 hang). The work-around is to use SetHandleInformation
4799 instead if it is available and implemented. */
4800 if (pfn_SetHandleInformation)
4802 pfn_SetHandleInformation ((HANDLE) s, HANDLE_FLAG_INHERIT, 0);
4804 else
4806 HANDLE parent = GetCurrentProcess ();
4807 HANDLE new_s = INVALID_HANDLE_VALUE;
4809 if (DuplicateHandle (parent,
4810 (HANDLE) s,
4811 parent,
4812 &new_s,
4814 FALSE,
4815 DUPLICATE_SAME_ACCESS))
4817 /* It is possible that DuplicateHandle succeeds even
4818 though the socket wasn't really a kernel handle,
4819 because a real handle has the same value. So
4820 test whether the new handle really is a socket. */
4821 long nonblocking = 0;
4822 if (pfn_ioctlsocket ((SOCKET) new_s, FIONBIO, &nonblocking) == 0)
4824 pfn_closesocket (s);
4825 s = (SOCKET) new_s;
4827 else
4829 CloseHandle (new_s);
4834 fd_info[fd].hnd = (HANDLE) s;
4836 /* set our own internal flags */
4837 fd_info[fd].flags = FILE_SOCKET | FILE_BINARY | FILE_READ | FILE_WRITE;
4839 cp = new_child ();
4840 if (cp)
4842 cp->fd = fd;
4843 cp->status = STATUS_READ_ACKNOWLEDGED;
4845 /* attach child_process to fd_info */
4846 if (fd_info[ fd ].cp != NULL)
4848 DebPrint (("sys_socket: fd_info[%d] apparently in use!\n", fd));
4849 abort ();
4852 fd_info[ fd ].cp = cp;
4854 /* success! */
4855 winsock_inuse++; /* count open sockets */
4856 return fd;
4859 /* clean up */
4860 _close (fd);
4862 pfn_closesocket (s);
4863 h_errno = EMFILE;
4864 return -1;
4868 sys_bind (int s, const struct sockaddr * addr, int namelen)
4870 if (winsock_lib == NULL)
4872 h_errno = ENOTSOCK;
4873 return SOCKET_ERROR;
4876 check_errno ();
4877 if (fd_info[s].flags & FILE_SOCKET)
4879 int rc = pfn_bind (SOCK_HANDLE (s), addr, namelen);
4880 if (rc == SOCKET_ERROR)
4881 set_errno ();
4882 return rc;
4884 h_errno = ENOTSOCK;
4885 return SOCKET_ERROR;
4889 sys_connect (int s, const struct sockaddr * name, int namelen)
4891 if (winsock_lib == NULL)
4893 h_errno = ENOTSOCK;
4894 return SOCKET_ERROR;
4897 check_errno ();
4898 if (fd_info[s].flags & FILE_SOCKET)
4900 int rc = pfn_connect (SOCK_HANDLE (s), name, namelen);
4901 if (rc == SOCKET_ERROR)
4902 set_errno ();
4903 return rc;
4905 h_errno = ENOTSOCK;
4906 return SOCKET_ERROR;
4909 u_short
4910 sys_htons (u_short hostshort)
4912 return (winsock_lib != NULL) ?
4913 pfn_htons (hostshort) : hostshort;
4916 u_short
4917 sys_ntohs (u_short netshort)
4919 return (winsock_lib != NULL) ?
4920 pfn_ntohs (netshort) : netshort;
4923 unsigned long
4924 sys_inet_addr (const char * cp)
4926 return (winsock_lib != NULL) ?
4927 pfn_inet_addr (cp) : INADDR_NONE;
4931 sys_gethostname (char * name, int namelen)
4933 if (winsock_lib != NULL)
4934 return pfn_gethostname (name, namelen);
4936 if (namelen > MAX_COMPUTERNAME_LENGTH)
4937 return !GetComputerName (name, (DWORD *)&namelen);
4939 h_errno = EFAULT;
4940 return SOCKET_ERROR;
4943 struct hostent *
4944 sys_gethostbyname (const char * name)
4946 struct hostent * host;
4948 if (winsock_lib == NULL)
4950 h_errno = ENETDOWN;
4951 return NULL;
4954 check_errno ();
4955 host = pfn_gethostbyname (name);
4956 if (!host)
4957 set_errno ();
4958 return host;
4961 struct servent *
4962 sys_getservbyname (const char * name, const char * proto)
4964 struct servent * serv;
4966 if (winsock_lib == NULL)
4968 h_errno = ENETDOWN;
4969 return NULL;
4972 check_errno ();
4973 serv = pfn_getservbyname (name, proto);
4974 if (!serv)
4975 set_errno ();
4976 return serv;
4980 sys_getpeername (int s, struct sockaddr *addr, int * namelen)
4982 if (winsock_lib == NULL)
4984 h_errno = ENETDOWN;
4985 return SOCKET_ERROR;
4988 check_errno ();
4989 if (fd_info[s].flags & FILE_SOCKET)
4991 int rc = pfn_getpeername (SOCK_HANDLE (s), addr, namelen);
4992 if (rc == SOCKET_ERROR)
4993 set_errno ();
4994 return rc;
4996 h_errno = ENOTSOCK;
4997 return SOCKET_ERROR;
5001 sys_shutdown (int s, int how)
5003 if (winsock_lib == NULL)
5005 h_errno = ENETDOWN;
5006 return SOCKET_ERROR;
5009 check_errno ();
5010 if (fd_info[s].flags & FILE_SOCKET)
5012 int rc = pfn_shutdown (SOCK_HANDLE (s), how);
5013 if (rc == SOCKET_ERROR)
5014 set_errno ();
5015 return rc;
5017 h_errno = ENOTSOCK;
5018 return SOCKET_ERROR;
5022 sys_setsockopt (int s, int level, int optname, const void * optval, int optlen)
5024 if (winsock_lib == NULL)
5026 h_errno = ENETDOWN;
5027 return SOCKET_ERROR;
5030 check_errno ();
5031 if (fd_info[s].flags & FILE_SOCKET)
5033 int rc = pfn_setsockopt (SOCK_HANDLE (s), level, optname,
5034 (const char *)optval, optlen);
5035 if (rc == SOCKET_ERROR)
5036 set_errno ();
5037 return rc;
5039 h_errno = ENOTSOCK;
5040 return SOCKET_ERROR;
5044 sys_listen (int s, int backlog)
5046 if (winsock_lib == NULL)
5048 h_errno = ENETDOWN;
5049 return SOCKET_ERROR;
5052 check_errno ();
5053 if (fd_info[s].flags & FILE_SOCKET)
5055 int rc = pfn_listen (SOCK_HANDLE (s), backlog);
5056 if (rc == SOCKET_ERROR)
5057 set_errno ();
5058 else
5059 fd_info[s].flags |= FILE_LISTEN;
5060 return rc;
5062 h_errno = ENOTSOCK;
5063 return SOCKET_ERROR;
5067 sys_getsockname (int s, struct sockaddr * name, int * namelen)
5069 if (winsock_lib == NULL)
5071 h_errno = ENETDOWN;
5072 return SOCKET_ERROR;
5075 check_errno ();
5076 if (fd_info[s].flags & FILE_SOCKET)
5078 int rc = pfn_getsockname (SOCK_HANDLE (s), name, namelen);
5079 if (rc == SOCKET_ERROR)
5080 set_errno ();
5081 return rc;
5083 h_errno = ENOTSOCK;
5084 return SOCKET_ERROR;
5088 sys_accept (int s, struct sockaddr * addr, int * addrlen)
5090 if (winsock_lib == NULL)
5092 h_errno = ENETDOWN;
5093 return -1;
5096 check_errno ();
5097 if (fd_info[s].flags & FILE_LISTEN)
5099 SOCKET t = pfn_accept (SOCK_HANDLE (s), addr, addrlen);
5100 int fd = -1;
5101 if (t == INVALID_SOCKET)
5102 set_errno ();
5103 else
5104 fd = socket_to_fd (t);
5106 fd_info[s].cp->status = STATUS_READ_ACKNOWLEDGED;
5107 ResetEvent (fd_info[s].cp->char_avail);
5108 return fd;
5110 h_errno = ENOTSOCK;
5111 return -1;
5115 sys_recvfrom (int s, char * buf, int len, int flags,
5116 struct sockaddr * from, int * fromlen)
5118 if (winsock_lib == NULL)
5120 h_errno = ENETDOWN;
5121 return SOCKET_ERROR;
5124 check_errno ();
5125 if (fd_info[s].flags & FILE_SOCKET)
5127 int rc = pfn_recvfrom (SOCK_HANDLE (s), buf, len, flags, from, fromlen);
5128 if (rc == SOCKET_ERROR)
5129 set_errno ();
5130 return rc;
5132 h_errno = ENOTSOCK;
5133 return SOCKET_ERROR;
5137 sys_sendto (int s, const char * buf, int len, int flags,
5138 const struct sockaddr * to, int tolen)
5140 if (winsock_lib == NULL)
5142 h_errno = ENETDOWN;
5143 return SOCKET_ERROR;
5146 check_errno ();
5147 if (fd_info[s].flags & FILE_SOCKET)
5149 int rc = pfn_sendto (SOCK_HANDLE (s), buf, len, flags, to, tolen);
5150 if (rc == SOCKET_ERROR)
5151 set_errno ();
5152 return rc;
5154 h_errno = ENOTSOCK;
5155 return SOCKET_ERROR;
5158 /* Windows does not have an fcntl function. Provide an implementation
5159 solely for making sockets non-blocking. */
5161 fcntl (int s, int cmd, int options)
5163 if (winsock_lib == NULL)
5165 h_errno = ENETDOWN;
5166 return -1;
5169 check_errno ();
5170 if (fd_info[s].flags & FILE_SOCKET)
5172 if (cmd == F_SETFL && options == O_NDELAY)
5174 unsigned long nblock = 1;
5175 int rc = pfn_ioctlsocket (SOCK_HANDLE (s), FIONBIO, &nblock);
5176 if (rc == SOCKET_ERROR)
5177 set_errno ();
5178 /* Keep track of the fact that we set this to non-blocking. */
5179 fd_info[s].flags |= FILE_NDELAY;
5180 return rc;
5182 else
5184 h_errno = EINVAL;
5185 return SOCKET_ERROR;
5188 h_errno = ENOTSOCK;
5189 return SOCKET_ERROR;
5193 /* Shadow main io functions: we need to handle pipes and sockets more
5194 intelligently, and implement non-blocking mode as well. */
5197 sys_close (int fd)
5199 int rc;
5201 if (fd < 0)
5203 errno = EBADF;
5204 return -1;
5207 if (fd < MAXDESC && fd_info[fd].cp)
5209 child_process * cp = fd_info[fd].cp;
5211 fd_info[fd].cp = NULL;
5213 if (CHILD_ACTIVE (cp))
5215 /* if last descriptor to active child_process then cleanup */
5216 int i;
5217 for (i = 0; i < MAXDESC; i++)
5219 if (i == fd)
5220 continue;
5221 if (fd_info[i].cp == cp)
5222 break;
5224 if (i == MAXDESC)
5226 if (fd_info[fd].flags & FILE_SOCKET)
5228 if (winsock_lib == NULL) abort ();
5230 pfn_shutdown (SOCK_HANDLE (fd), 2);
5231 rc = pfn_closesocket (SOCK_HANDLE (fd));
5233 winsock_inuse--; /* count open sockets */
5235 delete_child (cp);
5240 /* Note that sockets do not need special treatment here (at least on
5241 NT and Windows 95 using the standard tcp/ip stacks) - it appears that
5242 closesocket is equivalent to CloseHandle, which is to be expected
5243 because socket handles are fully fledged kernel handles. */
5244 rc = _close (fd);
5246 if (rc == 0 && fd < MAXDESC)
5247 fd_info[fd].flags = 0;
5249 return rc;
5253 sys_dup (int fd)
5255 int new_fd;
5257 new_fd = _dup (fd);
5258 if (new_fd >= 0 && new_fd < MAXDESC)
5260 /* duplicate our internal info as well */
5261 fd_info[new_fd] = fd_info[fd];
5263 return new_fd;
5267 sys_dup2 (int src, int dst)
5269 int rc;
5271 if (dst < 0 || dst >= MAXDESC)
5273 errno = EBADF;
5274 return -1;
5277 /* make sure we close the destination first if it's a pipe or socket */
5278 if (src != dst && fd_info[dst].flags != 0)
5279 sys_close (dst);
5281 rc = _dup2 (src, dst);
5282 if (rc == 0)
5284 /* duplicate our internal info as well */
5285 fd_info[dst] = fd_info[src];
5287 return rc;
5290 /* Unix pipe() has only one arg */
5292 sys_pipe (int * phandles)
5294 int rc;
5295 unsigned flags;
5297 /* make pipe handles non-inheritable; when we spawn a child, we
5298 replace the relevant handle with an inheritable one. Also put
5299 pipes into binary mode; we will do text mode translation ourselves
5300 if required. */
5301 rc = _pipe (phandles, 0, _O_NOINHERIT | _O_BINARY);
5303 if (rc == 0)
5305 /* Protect against overflow, since Windows can open more handles than
5306 our fd_info array has room for. */
5307 if (phandles[0] >= MAXDESC || phandles[1] >= MAXDESC)
5309 _close (phandles[0]);
5310 _close (phandles[1]);
5311 rc = -1;
5313 else
5315 flags = FILE_PIPE | FILE_READ | FILE_BINARY;
5316 fd_info[phandles[0]].flags = flags;
5318 flags = FILE_PIPE | FILE_WRITE | FILE_BINARY;
5319 fd_info[phandles[1]].flags = flags;
5323 return rc;
5326 /* Function to do blocking read of one byte, needed to implement
5327 select. It is only allowed on sockets and pipes. */
5329 _sys_read_ahead (int fd)
5331 child_process * cp;
5332 int rc;
5334 if (fd < 0 || fd >= MAXDESC)
5335 return STATUS_READ_ERROR;
5337 cp = fd_info[fd].cp;
5339 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
5340 return STATUS_READ_ERROR;
5342 if ((fd_info[fd].flags & (FILE_PIPE | FILE_SERIAL | FILE_SOCKET)) == 0
5343 || (fd_info[fd].flags & FILE_READ) == 0)
5345 DebPrint (("_sys_read_ahead: internal error: fd %d is not a pipe, serial port, or socket!\n", fd));
5346 abort ();
5349 cp->status = STATUS_READ_IN_PROGRESS;
5351 if (fd_info[fd].flags & FILE_PIPE)
5353 rc = _read (fd, &cp->chr, sizeof (char));
5355 /* Give subprocess time to buffer some more output for us before
5356 reporting that input is available; we need this because Windows 95
5357 connects DOS programs to pipes by making the pipe appear to be
5358 the normal console stdout - as a result most DOS programs will
5359 write to stdout without buffering, ie. one character at a
5360 time. Even some W32 programs do this - "dir" in a command
5361 shell on NT is very slow if we don't do this. */
5362 if (rc > 0)
5364 int wait = w32_pipe_read_delay;
5366 if (wait > 0)
5367 Sleep (wait);
5368 else if (wait < 0)
5369 while (++wait <= 0)
5370 /* Yield remainder of our time slice, effectively giving a
5371 temporary priority boost to the child process. */
5372 Sleep (0);
5375 else if (fd_info[fd].flags & FILE_SERIAL)
5377 HANDLE hnd = fd_info[fd].hnd;
5378 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_read;
5379 COMMTIMEOUTS ct;
5381 /* Configure timeouts for blocking read. */
5382 if (!GetCommTimeouts (hnd, &ct))
5383 return STATUS_READ_ERROR;
5384 ct.ReadIntervalTimeout = 0;
5385 ct.ReadTotalTimeoutMultiplier = 0;
5386 ct.ReadTotalTimeoutConstant = 0;
5387 if (!SetCommTimeouts (hnd, &ct))
5388 return STATUS_READ_ERROR;
5390 if (!ReadFile (hnd, &cp->chr, sizeof (char), (DWORD*) &rc, ovl))
5392 if (GetLastError () != ERROR_IO_PENDING)
5393 return STATUS_READ_ERROR;
5394 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &rc, TRUE))
5395 return STATUS_READ_ERROR;
5398 else if (fd_info[fd].flags & FILE_SOCKET)
5400 unsigned long nblock = 0;
5401 /* We always want this to block, so temporarily disable NDELAY. */
5402 if (fd_info[fd].flags & FILE_NDELAY)
5403 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
5405 rc = pfn_recv (SOCK_HANDLE (fd), &cp->chr, sizeof (char), 0);
5407 if (fd_info[fd].flags & FILE_NDELAY)
5409 nblock = 1;
5410 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
5414 if (rc == sizeof (char))
5415 cp->status = STATUS_READ_SUCCEEDED;
5416 else
5417 cp->status = STATUS_READ_FAILED;
5419 return cp->status;
5423 _sys_wait_accept (int fd)
5425 HANDLE hEv;
5426 child_process * cp;
5427 int rc;
5429 if (fd < 0 || fd >= MAXDESC)
5430 return STATUS_READ_ERROR;
5432 cp = fd_info[fd].cp;
5434 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
5435 return STATUS_READ_ERROR;
5437 cp->status = STATUS_READ_FAILED;
5439 hEv = pfn_WSACreateEvent ();
5440 rc = pfn_WSAEventSelect (SOCK_HANDLE (fd), hEv, FD_ACCEPT);
5441 if (rc != SOCKET_ERROR)
5443 rc = WaitForSingleObject (hEv, INFINITE);
5444 pfn_WSAEventSelect (SOCK_HANDLE (fd), NULL, 0);
5445 if (rc == WAIT_OBJECT_0)
5446 cp->status = STATUS_READ_SUCCEEDED;
5448 pfn_WSACloseEvent (hEv);
5450 return cp->status;
5454 sys_read (int fd, char * buffer, unsigned int count)
5456 int nchars;
5457 int to_read;
5458 DWORD waiting;
5459 char * orig_buffer = buffer;
5461 if (fd < 0)
5463 errno = EBADF;
5464 return -1;
5467 if (fd < MAXDESC && fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET | FILE_SERIAL))
5469 child_process *cp = fd_info[fd].cp;
5471 if ((fd_info[fd].flags & FILE_READ) == 0)
5473 errno = EBADF;
5474 return -1;
5477 nchars = 0;
5479 /* re-read CR carried over from last read */
5480 if (fd_info[fd].flags & FILE_LAST_CR)
5482 if (fd_info[fd].flags & FILE_BINARY) abort ();
5483 *buffer++ = 0x0d;
5484 count--;
5485 nchars++;
5486 fd_info[fd].flags &= ~FILE_LAST_CR;
5489 /* presence of a child_process structure means we are operating in
5490 non-blocking mode - otherwise we just call _read directly.
5491 Note that the child_process structure might be missing because
5492 reap_subprocess has been called; in this case the pipe is
5493 already broken, so calling _read on it is okay. */
5494 if (cp)
5496 int current_status = cp->status;
5498 switch (current_status)
5500 case STATUS_READ_FAILED:
5501 case STATUS_READ_ERROR:
5502 /* report normal EOF if nothing in buffer */
5503 if (nchars <= 0)
5504 fd_info[fd].flags |= FILE_AT_EOF;
5505 return nchars;
5507 case STATUS_READ_READY:
5508 case STATUS_READ_IN_PROGRESS:
5509 DebPrint (("sys_read called when read is in progress\n"));
5510 errno = EWOULDBLOCK;
5511 return -1;
5513 case STATUS_READ_SUCCEEDED:
5514 /* consume read-ahead char */
5515 *buffer++ = cp->chr;
5516 count--;
5517 nchars++;
5518 cp->status = STATUS_READ_ACKNOWLEDGED;
5519 ResetEvent (cp->char_avail);
5521 case STATUS_READ_ACKNOWLEDGED:
5522 break;
5524 default:
5525 DebPrint (("sys_read: bad status %d\n", current_status));
5526 errno = EBADF;
5527 return -1;
5530 if (fd_info[fd].flags & FILE_PIPE)
5532 PeekNamedPipe ((HANDLE) _get_osfhandle (fd), NULL, 0, NULL, &waiting, NULL);
5533 to_read = min (waiting, (DWORD) count);
5535 if (to_read > 0)
5536 nchars += _read (fd, buffer, to_read);
5538 else if (fd_info[fd].flags & FILE_SERIAL)
5540 HANDLE hnd = fd_info[fd].hnd;
5541 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_read;
5542 int rc = 0;
5543 COMMTIMEOUTS ct;
5545 if (count > 0)
5547 /* Configure timeouts for non-blocking read. */
5548 if (!GetCommTimeouts (hnd, &ct))
5550 errno = EIO;
5551 return -1;
5553 ct.ReadIntervalTimeout = MAXDWORD;
5554 ct.ReadTotalTimeoutMultiplier = 0;
5555 ct.ReadTotalTimeoutConstant = 0;
5556 if (!SetCommTimeouts (hnd, &ct))
5558 errno = EIO;
5559 return -1;
5562 if (!ResetEvent (ovl->hEvent))
5564 errno = EIO;
5565 return -1;
5567 if (!ReadFile (hnd, buffer, count, (DWORD*) &rc, ovl))
5569 if (GetLastError () != ERROR_IO_PENDING)
5571 errno = EIO;
5572 return -1;
5574 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &rc, TRUE))
5576 errno = EIO;
5577 return -1;
5580 nchars += rc;
5583 else /* FILE_SOCKET */
5585 if (winsock_lib == NULL) abort ();
5587 /* do the equivalent of a non-blocking read */
5588 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONREAD, &waiting);
5589 if (waiting == 0 && nchars == 0)
5591 h_errno = errno = EWOULDBLOCK;
5592 return -1;
5595 if (waiting)
5597 /* always use binary mode for sockets */
5598 int res = pfn_recv (SOCK_HANDLE (fd), buffer, count, 0);
5599 if (res == SOCKET_ERROR)
5601 DebPrint (("sys_read.recv failed with error %d on socket %ld\n",
5602 pfn_WSAGetLastError (), SOCK_HANDLE (fd)));
5603 set_errno ();
5604 return -1;
5606 nchars += res;
5610 else
5612 int nread = _read (fd, buffer, count);
5613 if (nread >= 0)
5614 nchars += nread;
5615 else if (nchars == 0)
5616 nchars = nread;
5619 if (nchars <= 0)
5620 fd_info[fd].flags |= FILE_AT_EOF;
5621 /* Perform text mode translation if required. */
5622 else if ((fd_info[fd].flags & FILE_BINARY) == 0)
5624 nchars = crlf_to_lf (nchars, orig_buffer);
5625 /* If buffer contains only CR, return that. To be absolutely
5626 sure we should attempt to read the next char, but in
5627 practice a CR to be followed by LF would not appear by
5628 itself in the buffer. */
5629 if (nchars > 1 && orig_buffer[nchars - 1] == 0x0d)
5631 fd_info[fd].flags |= FILE_LAST_CR;
5632 nchars--;
5636 else
5637 nchars = _read (fd, buffer, count);
5639 return nchars;
5642 /* From w32xfns.c */
5643 extern HANDLE interrupt_handle;
5645 /* For now, don't bother with a non-blocking mode */
5647 sys_write (int fd, const void * buffer, unsigned int count)
5649 int nchars;
5651 if (fd < 0)
5653 errno = EBADF;
5654 return -1;
5657 if (fd < MAXDESC && fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET | FILE_SERIAL))
5659 if ((fd_info[fd].flags & FILE_WRITE) == 0)
5661 errno = EBADF;
5662 return -1;
5665 /* Perform text mode translation if required. */
5666 if ((fd_info[fd].flags & FILE_BINARY) == 0)
5668 char * tmpbuf = alloca (count * 2);
5669 unsigned char * src = (void *)buffer;
5670 unsigned char * dst = tmpbuf;
5671 int nbytes = count;
5673 while (1)
5675 unsigned char *next;
5676 /* copy next line or remaining bytes */
5677 next = _memccpy (dst, src, '\n', nbytes);
5678 if (next)
5680 /* copied one line ending with '\n' */
5681 int copied = next - dst;
5682 nbytes -= copied;
5683 src += copied;
5684 /* insert '\r' before '\n' */
5685 next[-1] = '\r';
5686 next[0] = '\n';
5687 dst = next + 1;
5688 count++;
5690 else
5691 /* copied remaining partial line -> now finished */
5692 break;
5694 buffer = tmpbuf;
5698 if (fd < MAXDESC && fd_info[fd].flags & FILE_SERIAL)
5700 HANDLE hnd = (HANDLE) _get_osfhandle (fd);
5701 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_write;
5702 HANDLE wait_hnd[2] = { interrupt_handle, ovl->hEvent };
5703 DWORD active = 0;
5705 if (!WriteFile (hnd, buffer, count, (DWORD*) &nchars, ovl))
5707 if (GetLastError () != ERROR_IO_PENDING)
5709 errno = EIO;
5710 return -1;
5712 if (detect_input_pending ())
5713 active = MsgWaitForMultipleObjects (2, wait_hnd, FALSE, INFINITE,
5714 QS_ALLINPUT);
5715 else
5716 active = WaitForMultipleObjects (2, wait_hnd, FALSE, INFINITE);
5717 if (active == WAIT_OBJECT_0)
5718 { /* User pressed C-g, cancel write, then leave. Don't bother
5719 cleaning up as we may only get stuck in buggy drivers. */
5720 PurgeComm (hnd, PURGE_TXABORT | PURGE_TXCLEAR);
5721 CancelIo (hnd);
5722 errno = EIO;
5723 return -1;
5725 if (active == WAIT_OBJECT_0 + 1
5726 && !GetOverlappedResult (hnd, ovl, (DWORD*) &nchars, TRUE))
5728 errno = EIO;
5729 return -1;
5733 else if (fd < MAXDESC && fd_info[fd].flags & FILE_SOCKET)
5735 unsigned long nblock = 0;
5736 if (winsock_lib == NULL) abort ();
5738 /* TODO: implement select() properly so non-blocking I/O works. */
5739 /* For now, make sure the write blocks. */
5740 if (fd_info[fd].flags & FILE_NDELAY)
5741 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
5743 nchars = pfn_send (SOCK_HANDLE (fd), buffer, count, 0);
5745 /* Set the socket back to non-blocking if it was before,
5746 for other operations that support it. */
5747 if (fd_info[fd].flags & FILE_NDELAY)
5749 nblock = 1;
5750 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
5753 if (nchars == SOCKET_ERROR)
5755 DebPrint (("sys_write.send failed with error %d on socket %ld\n",
5756 pfn_WSAGetLastError (), SOCK_HANDLE (fd)));
5757 set_errno ();
5760 else
5762 /* Some networked filesystems don't like too large writes, so
5763 break them into smaller chunks. See the Comments section of
5764 the MSDN documentation of WriteFile for details behind the
5765 choice of the value of CHUNK below. See also the thread
5766 http://thread.gmane.org/gmane.comp.version-control.git/145294
5767 in the git mailing list. */
5768 const unsigned char *p = buffer;
5769 const unsigned chunk = 30 * 1024 * 1024;
5771 nchars = 0;
5772 while (count > 0)
5774 unsigned this_chunk = count < chunk ? count : chunk;
5775 int n = _write (fd, p, this_chunk);
5777 nchars += n;
5778 if (n < 0)
5780 nchars = n;
5781 break;
5783 else if (n < this_chunk)
5784 break;
5785 count -= n;
5786 p += n;
5790 return nchars;
5793 /* The Windows CRT functions are "optimized for speed", so they don't
5794 check for timezone and DST changes if they were last called less
5795 than 1 minute ago (see http://support.microsoft.com/kb/821231). So
5796 all Emacs features that repeatedly call time functions (e.g.,
5797 display-time) are in real danger of missing timezone and DST
5798 changes. Calling tzset before each localtime call fixes that. */
5799 struct tm *
5800 sys_localtime (const time_t *t)
5802 tzset ();
5803 return localtime (t);
5808 /* Delayed loading of libraries. */
5810 Lisp_Object Vlibrary_cache;
5812 /* The argument LIBRARIES is an alist that associates a symbol
5813 LIBRARY_ID, identifying an external DLL library known to Emacs, to
5814 a list of filenames under which the library is usually found. In
5815 most cases, the argument passed as LIBRARIES is the variable
5816 `dynamic-library-alist', which is initialized to a list of common
5817 library names. If the function loads the library successfully, it
5818 returns the handle of the DLL, and records the filename in the
5819 property :loaded-from of LIBRARY_ID; it returns NULL if the library
5820 could not be found, or when it was already loaded (because the
5821 handle is not recorded anywhere, and so is lost after use). It
5822 would be trivial to save the handle too in :loaded-from, but
5823 currently there's no use case for it. */
5824 HMODULE
5825 w32_delayed_load (Lisp_Object libraries, Lisp_Object library_id)
5827 HMODULE library_dll = NULL;
5829 CHECK_SYMBOL (library_id);
5831 if (CONSP (libraries) && NILP (Fassq (library_id, Vlibrary_cache)))
5833 Lisp_Object found = Qnil;
5834 Lisp_Object dlls = Fassq (library_id, libraries);
5836 if (CONSP (dlls))
5837 for (dlls = XCDR (dlls); CONSP (dlls); dlls = XCDR (dlls))
5839 CHECK_STRING_CAR (dlls);
5840 if ((library_dll = LoadLibrary (SDATA (XCAR (dlls)))))
5842 char name[MAX_PATH];
5843 DWORD len;
5845 len = GetModuleFileNameA (library_dll, name, sizeof (name));
5846 found = Fcons (XCAR (dlls),
5847 (len > 0)
5848 /* Possibly truncated */
5849 ? make_specified_string (name, -1, len, 1)
5850 : Qnil);
5851 break;
5855 Fput (library_id, QCloaded_from, found);
5858 return library_dll;
5862 static void
5863 check_windows_init_file (void)
5865 /* A common indication that Emacs is not installed properly is when
5866 it cannot find the Windows installation file. If this file does
5867 not exist in the expected place, tell the user. */
5869 if (!noninteractive && !inhibit_window_system
5870 /* Vload_path is not yet initialized when we are loading
5871 loadup.el. */
5872 && NILP (Vpurify_flag))
5874 Lisp_Object objs[2];
5875 Lisp_Object full_load_path;
5876 Lisp_Object init_file;
5877 int fd;
5879 objs[0] = Vload_path;
5880 objs[1] = decode_env_path (0, (getenv ("EMACSLOADPATH")));
5881 full_load_path = Fappend (2, objs);
5882 init_file = build_string ("term/w32-win");
5883 fd = openp (full_load_path, init_file, Fget_load_suffixes (), NULL, Qnil);
5884 if (fd < 0)
5886 Lisp_Object load_path_print = Fprin1_to_string (full_load_path, Qnil);
5887 char *init_file_name = SDATA (init_file);
5888 char *load_path = SDATA (load_path_print);
5889 char *buffer = alloca (1024
5890 + strlen (init_file_name)
5891 + strlen (load_path));
5893 sprintf (buffer,
5894 "The Emacs Windows initialization file \"%s.el\" "
5895 "could not be found in your Emacs installation. "
5896 "Emacs checked the following directories for this file:\n"
5897 "\n%s\n\n"
5898 "When Emacs cannot find this file, it usually means that it "
5899 "was not installed properly, or its distribution file was "
5900 "not unpacked properly.\nSee the README.W32 file in the "
5901 "top-level Emacs directory for more information.",
5902 init_file_name, load_path);
5903 MessageBox (NULL,
5904 buffer,
5905 "Emacs Abort Dialog",
5906 MB_OK | MB_ICONEXCLAMATION | MB_TASKMODAL);
5907 /* Use the low-level Emacs abort. */
5908 #undef abort
5909 abort ();
5911 else
5913 _close (fd);
5918 void
5919 term_ntproc (void)
5921 /* shutdown the socket interface if necessary */
5922 term_winsock ();
5924 term_w32select ();
5927 void
5928 init_ntproc (void)
5930 /* Initialize the socket interface now if available and requested by
5931 the user by defining PRELOAD_WINSOCK; otherwise loading will be
5932 delayed until open-network-stream is called (w32-has-winsock can
5933 also be used to dynamically load or reload winsock).
5935 Conveniently, init_environment is called before us, so
5936 PRELOAD_WINSOCK can be set in the registry. */
5938 /* Always initialize this correctly. */
5939 winsock_lib = NULL;
5941 if (getenv ("PRELOAD_WINSOCK") != NULL)
5942 init_winsock (TRUE);
5944 /* Initial preparation for subprocess support: replace our standard
5945 handles with non-inheritable versions. */
5947 HANDLE parent;
5948 HANDLE stdin_save = INVALID_HANDLE_VALUE;
5949 HANDLE stdout_save = INVALID_HANDLE_VALUE;
5950 HANDLE stderr_save = INVALID_HANDLE_VALUE;
5952 parent = GetCurrentProcess ();
5954 /* ignore errors when duplicating and closing; typically the
5955 handles will be invalid when running as a gui program. */
5956 DuplicateHandle (parent,
5957 GetStdHandle (STD_INPUT_HANDLE),
5958 parent,
5959 &stdin_save,
5961 FALSE,
5962 DUPLICATE_SAME_ACCESS);
5964 DuplicateHandle (parent,
5965 GetStdHandle (STD_OUTPUT_HANDLE),
5966 parent,
5967 &stdout_save,
5969 FALSE,
5970 DUPLICATE_SAME_ACCESS);
5972 DuplicateHandle (parent,
5973 GetStdHandle (STD_ERROR_HANDLE),
5974 parent,
5975 &stderr_save,
5977 FALSE,
5978 DUPLICATE_SAME_ACCESS);
5980 fclose (stdin);
5981 fclose (stdout);
5982 fclose (stderr);
5984 if (stdin_save != INVALID_HANDLE_VALUE)
5985 _open_osfhandle ((long) stdin_save, O_TEXT);
5986 else
5987 _open ("nul", O_TEXT | O_NOINHERIT | O_RDONLY);
5988 _fdopen (0, "r");
5990 if (stdout_save != INVALID_HANDLE_VALUE)
5991 _open_osfhandle ((long) stdout_save, O_TEXT);
5992 else
5993 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
5994 _fdopen (1, "w");
5996 if (stderr_save != INVALID_HANDLE_VALUE)
5997 _open_osfhandle ((long) stderr_save, O_TEXT);
5998 else
5999 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
6000 _fdopen (2, "w");
6003 /* unfortunately, atexit depends on implementation of malloc */
6004 /* atexit (term_ntproc); */
6005 signal (SIGABRT, term_ntproc);
6007 /* determine which drives are fixed, for GetCachedVolumeInformation */
6009 /* GetDriveType must have trailing backslash. */
6010 char drive[] = "A:\\";
6012 /* Loop over all possible drive letters */
6013 while (*drive <= 'Z')
6015 /* Record if this drive letter refers to a fixed drive. */
6016 fixed_drives[DRIVE_INDEX (*drive)] =
6017 (GetDriveType (drive) == DRIVE_FIXED);
6019 (*drive)++;
6022 /* Reset the volume info cache. */
6023 volume_cache = NULL;
6026 /* Check to see if Emacs has been installed correctly. */
6027 check_windows_init_file ();
6031 shutdown_handler ensures that buffers' autosave files are
6032 up to date when the user logs off, or the system shuts down.
6034 static BOOL WINAPI
6035 shutdown_handler (DWORD type)
6037 /* Ctrl-C and Ctrl-Break are already suppressed, so don't handle them. */
6038 if (type == CTRL_CLOSE_EVENT /* User closes console window. */
6039 || type == CTRL_LOGOFF_EVENT /* User logs off. */
6040 || type == CTRL_SHUTDOWN_EVENT) /* User shutsdown. */
6042 /* Shut down cleanly, making sure autosave files are up to date. */
6043 shut_down_emacs (0, 0, Qnil);
6046 /* Allow other handlers to handle this signal. */
6047 return FALSE;
6051 globals_of_w32 is used to initialize those global variables that
6052 must always be initialized on startup even when the global variable
6053 initialized is non zero (see the function main in emacs.c).
6055 void
6056 globals_of_w32 (void)
6058 HMODULE kernel32 = GetModuleHandle ("kernel32.dll");
6060 get_process_times_fn = (GetProcessTimes_Proc)
6061 GetProcAddress (kernel32, "GetProcessTimes");
6063 DEFSYM (QCloaded_from, ":loaded-from");
6065 Vlibrary_cache = Qnil;
6066 staticpro (&Vlibrary_cache);
6068 g_b_init_is_windows_9x = 0;
6069 g_b_init_open_process_token = 0;
6070 g_b_init_get_token_information = 0;
6071 g_b_init_lookup_account_sid = 0;
6072 g_b_init_get_sid_sub_authority = 0;
6073 g_b_init_get_sid_sub_authority_count = 0;
6074 g_b_init_get_file_security = 0;
6075 g_b_init_get_security_descriptor_owner = 0;
6076 g_b_init_get_security_descriptor_group = 0;
6077 g_b_init_is_valid_sid = 0;
6078 g_b_init_create_toolhelp32_snapshot = 0;
6079 g_b_init_process32_first = 0;
6080 g_b_init_process32_next = 0;
6081 g_b_init_open_thread_token = 0;
6082 g_b_init_impersonate_self = 0;
6083 g_b_init_revert_to_self = 0;
6084 g_b_init_get_process_memory_info = 0;
6085 g_b_init_get_process_working_set_size = 0;
6086 g_b_init_global_memory_status = 0;
6087 g_b_init_global_memory_status_ex = 0;
6088 g_b_init_equal_sid = 0;
6089 g_b_init_copy_sid = 0;
6090 g_b_init_get_length_sid = 0;
6091 g_b_init_get_native_system_info = 0;
6092 g_b_init_get_system_times = 0;
6093 num_of_processors = 0;
6094 /* The following sets a handler for shutdown notifications for
6095 console apps. This actually applies to Emacs in both console and
6096 GUI modes, since we had to fool windows into thinking emacs is a
6097 console application to get console mode to work. */
6098 SetConsoleCtrlHandler (shutdown_handler, TRUE);
6100 /* "None" is the default group name on standalone workstations. */
6101 strcpy (dflt_group_name, "None");
6104 /* For make-serial-process */
6106 serial_open (char *port)
6108 HANDLE hnd;
6109 child_process *cp;
6110 int fd = -1;
6112 hnd = CreateFile (port, GENERIC_READ | GENERIC_WRITE, 0, 0,
6113 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
6114 if (hnd == INVALID_HANDLE_VALUE)
6115 error ("Could not open %s", port);
6116 fd = (int) _open_osfhandle ((int) hnd, 0);
6117 if (fd == -1)
6118 error ("Could not open %s", port);
6120 cp = new_child ();
6121 if (!cp)
6122 error ("Could not create child process");
6123 cp->fd = fd;
6124 cp->status = STATUS_READ_ACKNOWLEDGED;
6125 fd_info[ fd ].hnd = hnd;
6126 fd_info[ fd ].flags |=
6127 FILE_READ | FILE_WRITE | FILE_BINARY | FILE_SERIAL;
6128 if (fd_info[ fd ].cp != NULL)
6130 error ("fd_info[fd = %d] is already in use", fd);
6132 fd_info[ fd ].cp = cp;
6133 cp->ovl_read.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
6134 if (cp->ovl_read.hEvent == NULL)
6135 error ("Could not create read event");
6136 cp->ovl_write.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
6137 if (cp->ovl_write.hEvent == NULL)
6138 error ("Could not create write event");
6140 return fd;
6143 /* For serial-process-configure */
6144 void
6145 serial_configure (struct Lisp_Process *p, Lisp_Object contact)
6147 Lisp_Object childp2 = Qnil;
6148 Lisp_Object tem = Qnil;
6149 HANDLE hnd;
6150 DCB dcb;
6151 COMMTIMEOUTS ct;
6152 char summary[4] = "???"; /* This usually becomes "8N1". */
6154 if ((fd_info[ p->outfd ].flags & FILE_SERIAL) == 0)
6155 error ("Not a serial process");
6156 hnd = fd_info[ p->outfd ].hnd;
6158 childp2 = Fcopy_sequence (p->childp);
6160 /* Initialize timeouts for blocking read and blocking write. */
6161 if (!GetCommTimeouts (hnd, &ct))
6162 error ("GetCommTimeouts() failed");
6163 ct.ReadIntervalTimeout = 0;
6164 ct.ReadTotalTimeoutMultiplier = 0;
6165 ct.ReadTotalTimeoutConstant = 0;
6166 ct.WriteTotalTimeoutMultiplier = 0;
6167 ct.WriteTotalTimeoutConstant = 0;
6168 if (!SetCommTimeouts (hnd, &ct))
6169 error ("SetCommTimeouts() failed");
6170 /* Read port attributes and prepare default configuration. */
6171 memset (&dcb, 0, sizeof (dcb));
6172 dcb.DCBlength = sizeof (DCB);
6173 if (!GetCommState (hnd, &dcb))
6174 error ("GetCommState() failed");
6175 dcb.fBinary = TRUE;
6176 dcb.fNull = FALSE;
6177 dcb.fAbortOnError = FALSE;
6178 /* dcb.XonLim and dcb.XoffLim are set by GetCommState() */
6179 dcb.ErrorChar = 0;
6180 dcb.EofChar = 0;
6181 dcb.EvtChar = 0;
6183 /* Configure speed. */
6184 if (!NILP (Fplist_member (contact, QCspeed)))
6185 tem = Fplist_get (contact, QCspeed);
6186 else
6187 tem = Fplist_get (p->childp, QCspeed);
6188 CHECK_NUMBER (tem);
6189 dcb.BaudRate = XINT (tem);
6190 childp2 = Fplist_put (childp2, QCspeed, tem);
6192 /* Configure bytesize. */
6193 if (!NILP (Fplist_member (contact, QCbytesize)))
6194 tem = Fplist_get (contact, QCbytesize);
6195 else
6196 tem = Fplist_get (p->childp, QCbytesize);
6197 if (NILP (tem))
6198 tem = make_number (8);
6199 CHECK_NUMBER (tem);
6200 if (XINT (tem) != 7 && XINT (tem) != 8)
6201 error (":bytesize must be nil (8), 7, or 8");
6202 dcb.ByteSize = XINT (tem);
6203 summary[0] = XINT (tem) + '0';
6204 childp2 = Fplist_put (childp2, QCbytesize, tem);
6206 /* Configure parity. */
6207 if (!NILP (Fplist_member (contact, QCparity)))
6208 tem = Fplist_get (contact, QCparity);
6209 else
6210 tem = Fplist_get (p->childp, QCparity);
6211 if (!NILP (tem) && !EQ (tem, Qeven) && !EQ (tem, Qodd))
6212 error (":parity must be nil (no parity), `even', or `odd'");
6213 dcb.fParity = FALSE;
6214 dcb.Parity = NOPARITY;
6215 dcb.fErrorChar = FALSE;
6216 if (NILP (tem))
6218 summary[1] = 'N';
6220 else if (EQ (tem, Qeven))
6222 summary[1] = 'E';
6223 dcb.fParity = TRUE;
6224 dcb.Parity = EVENPARITY;
6225 dcb.fErrorChar = TRUE;
6227 else if (EQ (tem, Qodd))
6229 summary[1] = 'O';
6230 dcb.fParity = TRUE;
6231 dcb.Parity = ODDPARITY;
6232 dcb.fErrorChar = TRUE;
6234 childp2 = Fplist_put (childp2, QCparity, tem);
6236 /* Configure stopbits. */
6237 if (!NILP (Fplist_member (contact, QCstopbits)))
6238 tem = Fplist_get (contact, QCstopbits);
6239 else
6240 tem = Fplist_get (p->childp, QCstopbits);
6241 if (NILP (tem))
6242 tem = make_number (1);
6243 CHECK_NUMBER (tem);
6244 if (XINT (tem) != 1 && XINT (tem) != 2)
6245 error (":stopbits must be nil (1 stopbit), 1, or 2");
6246 summary[2] = XINT (tem) + '0';
6247 if (XINT (tem) == 1)
6248 dcb.StopBits = ONESTOPBIT;
6249 else if (XINT (tem) == 2)
6250 dcb.StopBits = TWOSTOPBITS;
6251 childp2 = Fplist_put (childp2, QCstopbits, tem);
6253 /* Configure flowcontrol. */
6254 if (!NILP (Fplist_member (contact, QCflowcontrol)))
6255 tem = Fplist_get (contact, QCflowcontrol);
6256 else
6257 tem = Fplist_get (p->childp, QCflowcontrol);
6258 if (!NILP (tem) && !EQ (tem, Qhw) && !EQ (tem, Qsw))
6259 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
6260 dcb.fOutxCtsFlow = FALSE;
6261 dcb.fOutxDsrFlow = FALSE;
6262 dcb.fDtrControl = DTR_CONTROL_DISABLE;
6263 dcb.fDsrSensitivity = FALSE;
6264 dcb.fTXContinueOnXoff = FALSE;
6265 dcb.fOutX = FALSE;
6266 dcb.fInX = FALSE;
6267 dcb.fRtsControl = RTS_CONTROL_DISABLE;
6268 dcb.XonChar = 17; /* Control-Q */
6269 dcb.XoffChar = 19; /* Control-S */
6270 if (NILP (tem))
6272 /* Already configured. */
6274 else if (EQ (tem, Qhw))
6276 dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
6277 dcb.fOutxCtsFlow = TRUE;
6279 else if (EQ (tem, Qsw))
6281 dcb.fOutX = TRUE;
6282 dcb.fInX = TRUE;
6284 childp2 = Fplist_put (childp2, QCflowcontrol, tem);
6286 /* Activate configuration. */
6287 if (!SetCommState (hnd, &dcb))
6288 error ("SetCommState() failed");
6290 childp2 = Fplist_put (childp2, QCsummary, build_string (summary));
6291 p->childp = childp2;
6294 #ifdef HAVE_GNUTLS
6296 ssize_t
6297 emacs_gnutls_pull (gnutls_transport_ptr_t p, void* buf, size_t sz)
6299 int n, sc, err;
6300 SELECT_TYPE fdset;
6301 struct timeval timeout;
6302 struct Lisp_Process *process = (struct Lisp_Process *)p;
6303 int fd = process->infd;
6305 for (;;)
6307 n = sys_read (fd, (char*)buf, sz);
6309 if (n >= 0)
6310 return n;
6312 err = errno;
6314 if (err == EWOULDBLOCK)
6316 /* Set a small timeout. */
6317 timeout.tv_sec = 1;
6318 timeout.tv_usec = 0;
6319 FD_ZERO (&fdset);
6320 FD_SET ((int)fd, &fdset);
6322 /* Use select with the timeout to poll the selector. */
6323 sc = select (fd + 1, &fdset, (SELECT_TYPE *)0, (SELECT_TYPE *)0,
6324 &timeout);
6326 if (sc > 0)
6327 continue; /* Try again. */
6329 /* Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN.
6330 Also accept select return 0 as an indicator to EAGAIN. */
6331 if (sc == 0 || errno == EWOULDBLOCK)
6332 err = EAGAIN;
6333 else
6334 err = errno; /* Other errors are just passed on. */
6337 emacs_gnutls_transport_set_errno (process->gnutls_state, err);
6339 return -1;
6343 ssize_t
6344 emacs_gnutls_push (gnutls_transport_ptr_t p, const void* buf, size_t sz)
6346 struct Lisp_Process *process = (struct Lisp_Process *)p;
6347 int fd = process->outfd;
6348 ssize_t n = sys_write (fd, buf, sz);
6350 /* 0 or more bytes written means everything went fine. */
6351 if (n >= 0)
6352 return n;
6354 /* Negative bytes written means we got an error in errno.
6355 Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
6356 emacs_gnutls_transport_set_errno (process->gnutls_state,
6357 errno == EWOULDBLOCK ? EAGAIN : errno);
6359 return -1;
6361 #endif /* HAVE_GNUTLS */
6363 /* end of w32.c */