Minor changes, detected by test suite.
[emacs.git] / src / w32.c
blobe48078aec99cf6702741261496aacd924634c7e1
1 /* Utility and Unix shadow routines for GNU Emacs on the Microsoft Windows API.
2 Copyright (C) 1994-1995, 2000-2013 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
23 #include <mingw_time.h>
24 #include <stddef.h> /* for offsetof */
25 #include <stdlib.h>
26 #include <stdio.h>
27 #include <float.h> /* for DBL_EPSILON */
28 #include <io.h>
29 #include <errno.h>
30 #include <fcntl.h>
31 #include <ctype.h>
32 #include <signal.h>
33 #include <sys/file.h>
34 #include <time.h> /* must be before nt/inc/sys/time.h, for MinGW64 */
35 #include <sys/time.h>
36 #include <sys/utime.h>
37 #include <math.h>
39 /* must include CRT headers *before* config.h */
41 #include <config.h>
42 #include <mbstring.h> /* for _mbspbrk, _mbslwr, _mbsrchr, ... */
44 #undef access
45 #undef chdir
46 #undef chmod
47 #undef creat
48 #undef ctime
49 #undef fopen
50 #undef link
51 #undef mkdir
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"
69 #include "epaths.h" /* for SHELL */
71 #include <pwd.h>
72 #include <grp.h>
74 /* MinGW64 (_W64) defines these in its _mingw.h. */
75 #if defined(__GNUC__) && !defined(_W64)
76 #define _ANONYMOUS_UNION
77 #define _ANONYMOUS_STRUCT
78 #endif
79 #include <windows.h>
80 /* Some versions of compiler define MEMORYSTATUSEX, some don't, so we
81 use a different name to avoid compilation problems. */
82 typedef struct _MEMORY_STATUS_EX {
83 DWORD dwLength;
84 DWORD dwMemoryLoad;
85 DWORDLONG ullTotalPhys;
86 DWORDLONG ullAvailPhys;
87 DWORDLONG ullTotalPageFile;
88 DWORDLONG ullAvailPageFile;
89 DWORDLONG ullTotalVirtual;
90 DWORDLONG ullAvailVirtual;
91 DWORDLONG ullAvailExtendedVirtual;
92 } MEMORY_STATUS_EX,*LPMEMORY_STATUS_EX;
94 /* These are here so that GDB would know about these data types. This
95 allows to attach GDB to Emacs when a fatal exception is triggered
96 and Windows pops up the "application needs to be closed" dialog.
97 At that point, _gnu_exception_handler, the top-level exception
98 handler installed by the MinGW startup code, is somewhere on the
99 call-stack of the main thread, so going to that call frame and
100 looking at the argument to _gnu_exception_handler, which is a
101 PEXCEPTION_POINTERS pointer, can reveal the exception code
102 (excptr->ExceptionRecord->ExceptionCode) and the address where the
103 exception happened (excptr->ExceptionRecord->ExceptionAddress), as
104 well as some additional information specific to the exception. */
105 PEXCEPTION_POINTERS excptr;
106 PEXCEPTION_RECORD excprec;
107 PCONTEXT ctxrec;
109 #include <lmcons.h>
110 #include <shlobj.h>
112 #include <tlhelp32.h>
113 #include <psapi.h>
114 #ifndef _MSC_VER
115 #include <w32api.h>
116 #endif
117 #if _WIN32_WINNT < 0x0500
118 #if !defined (__MINGW32__) || __W32API_MAJOR_VERSION < 3 || (__W32API_MAJOR_VERSION == 3 && __W32API_MINOR_VERSION < 15)
119 /* This either is not in psapi.h or guarded by higher value of
120 _WIN32_WINNT than what we use. w32api supplied with MinGW 3.15
121 defines it in psapi.h */
122 typedef struct _PROCESS_MEMORY_COUNTERS_EX {
123 DWORD cb;
124 DWORD PageFaultCount;
125 SIZE_T PeakWorkingSetSize;
126 SIZE_T WorkingSetSize;
127 SIZE_T QuotaPeakPagedPoolUsage;
128 SIZE_T QuotaPagedPoolUsage;
129 SIZE_T QuotaPeakNonPagedPoolUsage;
130 SIZE_T QuotaNonPagedPoolUsage;
131 SIZE_T PagefileUsage;
132 SIZE_T PeakPagefileUsage;
133 SIZE_T PrivateUsage;
134 } PROCESS_MEMORY_COUNTERS_EX,*PPROCESS_MEMORY_COUNTERS_EX;
135 #endif
136 #endif
138 #include <winioctl.h>
139 #include <aclapi.h>
140 #include <sddl.h>
142 #include <sys/acl.h>
144 /* This is not in MinGW's sddl.h (but they are in MSVC headers), so we
145 define them by hand if not already defined. */
146 #ifndef SDDL_REVISION_1
147 #define SDDL_REVISION_1 1
148 #endif /* SDDL_REVISION_1 */
150 #if defined(_MSC_VER) || defined(_W64)
151 /* MSVC and MinGW64 don't provide the definition of
152 REPARSE_DATA_BUFFER and the associated macros, except on ntifs.h,
153 which cannot be included because it triggers conflicts with other
154 Windows API headers. So we define it here by hand. */
156 typedef struct _REPARSE_DATA_BUFFER {
157 ULONG ReparseTag;
158 USHORT ReparseDataLength;
159 USHORT Reserved;
160 union {
161 struct {
162 USHORT SubstituteNameOffset;
163 USHORT SubstituteNameLength;
164 USHORT PrintNameOffset;
165 USHORT PrintNameLength;
166 ULONG Flags;
167 WCHAR PathBuffer[1];
168 } SymbolicLinkReparseBuffer;
169 struct {
170 USHORT SubstituteNameOffset;
171 USHORT SubstituteNameLength;
172 USHORT PrintNameOffset;
173 USHORT PrintNameLength;
174 WCHAR PathBuffer[1];
175 } MountPointReparseBuffer;
176 struct {
177 UCHAR DataBuffer[1];
178 } GenericReparseBuffer;
179 } DUMMYUNIONNAME;
180 } REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;
182 #ifndef FILE_DEVICE_FILE_SYSTEM
183 #define FILE_DEVICE_FILE_SYSTEM 9
184 #endif
185 #ifndef METHOD_BUFFERED
186 #define METHOD_BUFFERED 0
187 #endif
188 #ifndef FILE_ANY_ACCESS
189 #define FILE_ANY_ACCESS 0x00000000
190 #endif
191 #ifndef CTL_CODE
192 #define CTL_CODE(t,f,m,a) (((t)<<16)|((a)<<14)|((f)<<2)|(m))
193 #endif
194 /* MinGW64 defines FSCTL_GET_REPARSE_POINT on winioctl.h. */
195 #ifndef FSCTL_GET_REPARSE_POINT
196 #define FSCTL_GET_REPARSE_POINT \
197 CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 42, METHOD_BUFFERED, FILE_ANY_ACCESS)
198 #endif
199 #endif
201 /* TCP connection support. */
202 #include <sys/socket.h>
203 #undef socket
204 #undef bind
205 #undef connect
206 #undef htons
207 #undef ntohs
208 #undef inet_addr
209 #undef gethostname
210 #undef gethostbyname
211 #undef getservbyname
212 #undef getpeername
213 #undef shutdown
214 #undef setsockopt
215 #undef listen
216 #undef getsockname
217 #undef accept
218 #undef recvfrom
219 #undef sendto
221 #include <iphlpapi.h> /* should be after winsock2.h */
223 #include "w32.h"
224 #include <dirent.h>
225 #include "w32common.h"
226 #include "w32heap.h"
227 #include "w32select.h"
228 #include "systime.h"
229 #include "dispextern.h" /* for xstrcasecmp */
230 #include "coding.h" /* for Vlocale_coding_system */
232 #include "careadlinkat.h"
233 #include "allocator.h"
235 /* For serial_configure and serial_open. */
236 #include "process.h"
238 typedef HRESULT (WINAPI * ShGetFolderPath_fn)
239 (IN HWND, IN int, IN HANDLE, IN DWORD, OUT char *);
241 Lisp_Object QCloaded_from;
243 void globals_of_w32 (void);
244 static DWORD get_rid (PSID);
245 static int is_symlink (const char *);
246 static char * chase_symlinks (const char *);
247 static int enable_privilege (LPCTSTR, BOOL, TOKEN_PRIVILEGES *);
248 static int restore_privilege (TOKEN_PRIVILEGES *);
249 static BOOL WINAPI revert_to_self (void);
251 extern int sys_access (const char *, int);
252 extern void *e_malloc (size_t);
253 extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
254 struct timespec *, void *);
255 extern int sys_dup (int);
260 /* Initialization states.
262 WARNING: If you add any more such variables for additional APIs,
263 you MUST add initialization for them to globals_of_w32
264 below. This is because these variables might get set
265 to non-NULL values during dumping, but the dumped Emacs
266 cannot reuse those values, because it could be run on a
267 different version of the OS, where API addresses are
268 different. */
269 static BOOL g_b_init_is_windows_9x;
270 static BOOL g_b_init_open_process_token;
271 static BOOL g_b_init_get_token_information;
272 static BOOL g_b_init_lookup_account_sid;
273 static BOOL g_b_init_get_sid_sub_authority;
274 static BOOL g_b_init_get_sid_sub_authority_count;
275 static BOOL g_b_init_get_security_info;
276 static BOOL g_b_init_get_file_security;
277 static BOOL g_b_init_get_security_descriptor_owner;
278 static BOOL g_b_init_get_security_descriptor_group;
279 static BOOL g_b_init_is_valid_sid;
280 static BOOL g_b_init_create_toolhelp32_snapshot;
281 static BOOL g_b_init_process32_first;
282 static BOOL g_b_init_process32_next;
283 static BOOL g_b_init_open_thread_token;
284 static BOOL g_b_init_impersonate_self;
285 static BOOL g_b_init_revert_to_self;
286 static BOOL g_b_init_get_process_memory_info;
287 static BOOL g_b_init_get_process_working_set_size;
288 static BOOL g_b_init_global_memory_status;
289 static BOOL g_b_init_global_memory_status_ex;
290 static BOOL g_b_init_get_length_sid;
291 static BOOL g_b_init_equal_sid;
292 static BOOL g_b_init_copy_sid;
293 static BOOL g_b_init_get_native_system_info;
294 static BOOL g_b_init_get_system_times;
295 static BOOL g_b_init_create_symbolic_link;
296 static BOOL g_b_init_get_security_descriptor_dacl;
297 static BOOL g_b_init_convert_sd_to_sddl;
298 static BOOL g_b_init_convert_sddl_to_sd;
299 static BOOL g_b_init_is_valid_security_descriptor;
300 static BOOL g_b_init_set_file_security;
301 static BOOL g_b_init_get_adapters_info;
304 BEGIN: Wrapper functions around OpenProcessToken
305 and other functions in advapi32.dll that are only
306 supported in Windows NT / 2k / XP
308 /* ** Function pointer typedefs ** */
309 typedef BOOL (WINAPI * OpenProcessToken_Proc) (
310 HANDLE ProcessHandle,
311 DWORD DesiredAccess,
312 PHANDLE TokenHandle);
313 typedef BOOL (WINAPI * GetTokenInformation_Proc) (
314 HANDLE TokenHandle,
315 TOKEN_INFORMATION_CLASS TokenInformationClass,
316 LPVOID TokenInformation,
317 DWORD TokenInformationLength,
318 PDWORD ReturnLength);
319 typedef BOOL (WINAPI * GetProcessTimes_Proc) (
320 HANDLE process_handle,
321 LPFILETIME creation_time,
322 LPFILETIME exit_time,
323 LPFILETIME kernel_time,
324 LPFILETIME user_time);
326 GetProcessTimes_Proc get_process_times_fn = NULL;
328 #ifdef _UNICODE
329 const char * const LookupAccountSid_Name = "LookupAccountSidW";
330 const char * const GetFileSecurity_Name = "GetFileSecurityW";
331 const char * const SetFileSecurity_Name = "SetFileSecurityW";
332 #else
333 const char * const LookupAccountSid_Name = "LookupAccountSidA";
334 const char * const GetFileSecurity_Name = "GetFileSecurityA";
335 const char * const SetFileSecurity_Name = "SetFileSecurityA";
336 #endif
337 typedef BOOL (WINAPI * LookupAccountSid_Proc) (
338 LPCTSTR lpSystemName,
339 PSID Sid,
340 LPTSTR Name,
341 LPDWORD cbName,
342 LPTSTR DomainName,
343 LPDWORD cbDomainName,
344 PSID_NAME_USE peUse);
345 typedef PDWORD (WINAPI * GetSidSubAuthority_Proc) (
346 PSID pSid,
347 DWORD n);
348 typedef PUCHAR (WINAPI * GetSidSubAuthorityCount_Proc) (
349 PSID pSid);
350 typedef DWORD (WINAPI * GetSecurityInfo_Proc) (
351 HANDLE handle,
352 SE_OBJECT_TYPE ObjectType,
353 SECURITY_INFORMATION SecurityInfo,
354 PSID *ppsidOwner,
355 PSID *ppsidGroup,
356 PACL *ppDacl,
357 PACL *ppSacl,
358 PSECURITY_DESCRIPTOR *ppSecurityDescriptor);
359 typedef BOOL (WINAPI * GetFileSecurity_Proc) (
360 LPCTSTR lpFileName,
361 SECURITY_INFORMATION RequestedInformation,
362 PSECURITY_DESCRIPTOR pSecurityDescriptor,
363 DWORD nLength,
364 LPDWORD lpnLengthNeeded);
365 typedef BOOL (WINAPI *SetFileSecurity_Proc) (
366 LPCTSTR lpFileName,
367 SECURITY_INFORMATION SecurityInformation,
368 PSECURITY_DESCRIPTOR pSecurityDescriptor);
369 typedef BOOL (WINAPI * GetSecurityDescriptorOwner_Proc) (
370 PSECURITY_DESCRIPTOR pSecurityDescriptor,
371 PSID *pOwner,
372 LPBOOL lpbOwnerDefaulted);
373 typedef BOOL (WINAPI * GetSecurityDescriptorGroup_Proc) (
374 PSECURITY_DESCRIPTOR pSecurityDescriptor,
375 PSID *pGroup,
376 LPBOOL lpbGroupDefaulted);
377 typedef BOOL (WINAPI *GetSecurityDescriptorDacl_Proc) (
378 PSECURITY_DESCRIPTOR pSecurityDescriptor,
379 LPBOOL lpbDaclPresent,
380 PACL *pDacl,
381 LPBOOL lpbDaclDefaulted);
382 typedef BOOL (WINAPI * IsValidSid_Proc) (
383 PSID sid);
384 typedef HANDLE (WINAPI * CreateToolhelp32Snapshot_Proc) (
385 DWORD dwFlags,
386 DWORD th32ProcessID);
387 typedef BOOL (WINAPI * Process32First_Proc) (
388 HANDLE hSnapshot,
389 LPPROCESSENTRY32 lppe);
390 typedef BOOL (WINAPI * Process32Next_Proc) (
391 HANDLE hSnapshot,
392 LPPROCESSENTRY32 lppe);
393 typedef BOOL (WINAPI * OpenThreadToken_Proc) (
394 HANDLE ThreadHandle,
395 DWORD DesiredAccess,
396 BOOL OpenAsSelf,
397 PHANDLE TokenHandle);
398 typedef BOOL (WINAPI * ImpersonateSelf_Proc) (
399 SECURITY_IMPERSONATION_LEVEL ImpersonationLevel);
400 typedef BOOL (WINAPI * RevertToSelf_Proc) (void);
401 typedef BOOL (WINAPI * GetProcessMemoryInfo_Proc) (
402 HANDLE Process,
403 PPROCESS_MEMORY_COUNTERS ppsmemCounters,
404 DWORD cb);
405 typedef BOOL (WINAPI * GetProcessWorkingSetSize_Proc) (
406 HANDLE hProcess,
407 PSIZE_T lpMinimumWorkingSetSize,
408 PSIZE_T lpMaximumWorkingSetSize);
409 typedef BOOL (WINAPI * GlobalMemoryStatus_Proc) (
410 LPMEMORYSTATUS lpBuffer);
411 typedef BOOL (WINAPI * GlobalMemoryStatusEx_Proc) (
412 LPMEMORY_STATUS_EX lpBuffer);
413 typedef BOOL (WINAPI * CopySid_Proc) (
414 DWORD nDestinationSidLength,
415 PSID pDestinationSid,
416 PSID pSourceSid);
417 typedef BOOL (WINAPI * EqualSid_Proc) (
418 PSID pSid1,
419 PSID pSid2);
420 typedef DWORD (WINAPI * GetLengthSid_Proc) (
421 PSID pSid);
422 typedef void (WINAPI * GetNativeSystemInfo_Proc) (
423 LPSYSTEM_INFO lpSystemInfo);
424 typedef BOOL (WINAPI * GetSystemTimes_Proc) (
425 LPFILETIME lpIdleTime,
426 LPFILETIME lpKernelTime,
427 LPFILETIME lpUserTime);
428 typedef BOOLEAN (WINAPI *CreateSymbolicLink_Proc) (
429 LPTSTR lpSymlinkFileName,
430 LPTSTR lpTargetFileName,
431 DWORD dwFlags);
432 typedef BOOL (WINAPI *ConvertStringSecurityDescriptorToSecurityDescriptor_Proc) (
433 LPCTSTR StringSecurityDescriptor,
434 DWORD StringSDRevision,
435 PSECURITY_DESCRIPTOR *SecurityDescriptor,
436 PULONG SecurityDescriptorSize);
437 typedef BOOL (WINAPI *ConvertSecurityDescriptorToStringSecurityDescriptor_Proc) (
438 PSECURITY_DESCRIPTOR SecurityDescriptor,
439 DWORD RequestedStringSDRevision,
440 SECURITY_INFORMATION SecurityInformation,
441 LPTSTR *StringSecurityDescriptor,
442 PULONG StringSecurityDescriptorLen);
443 typedef BOOL (WINAPI *IsValidSecurityDescriptor_Proc) (PSECURITY_DESCRIPTOR);
444 typedef DWORD (WINAPI *GetAdaptersInfo_Proc) (
445 PIP_ADAPTER_INFO pAdapterInfo,
446 PULONG pOutBufLen);
448 /* ** A utility function ** */
449 static BOOL
450 is_windows_9x (void)
452 static BOOL s_b_ret = 0;
453 OSVERSIONINFO os_ver;
454 if (g_b_init_is_windows_9x == 0)
456 g_b_init_is_windows_9x = 1;
457 ZeroMemory (&os_ver, sizeof (OSVERSIONINFO));
458 os_ver.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
459 if (GetVersionEx (&os_ver))
461 s_b_ret = (os_ver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS);
464 return s_b_ret;
467 static Lisp_Object ltime (ULONGLONG);
469 /* Get total user and system times for get-internal-run-time.
470 Returns a list of integers if the times are provided by the OS
471 (NT derivatives), otherwise it returns the result of current-time. */
472 Lisp_Object
473 w32_get_internal_run_time (void)
475 if (get_process_times_fn)
477 FILETIME create, exit, kernel, user;
478 HANDLE proc = GetCurrentProcess ();
479 if ((*get_process_times_fn) (proc, &create, &exit, &kernel, &user))
481 LARGE_INTEGER user_int, kernel_int, total;
482 user_int.LowPart = user.dwLowDateTime;
483 user_int.HighPart = user.dwHighDateTime;
484 kernel_int.LowPart = kernel.dwLowDateTime;
485 kernel_int.HighPart = kernel.dwHighDateTime;
486 total.QuadPart = user_int.QuadPart + kernel_int.QuadPart;
487 return ltime (total.QuadPart);
491 return Fcurrent_time ();
494 /* ** The wrapper functions ** */
496 static BOOL WINAPI
497 open_process_token (HANDLE ProcessHandle,
498 DWORD DesiredAccess,
499 PHANDLE TokenHandle)
501 static OpenProcessToken_Proc s_pfn_Open_Process_Token = NULL;
502 HMODULE hm_advapi32 = NULL;
503 if (is_windows_9x () == TRUE)
505 return FALSE;
507 if (g_b_init_open_process_token == 0)
509 g_b_init_open_process_token = 1;
510 hm_advapi32 = LoadLibrary ("Advapi32.dll");
511 s_pfn_Open_Process_Token =
512 (OpenProcessToken_Proc) GetProcAddress (hm_advapi32, "OpenProcessToken");
514 if (s_pfn_Open_Process_Token == NULL)
516 return FALSE;
518 return (
519 s_pfn_Open_Process_Token (
520 ProcessHandle,
521 DesiredAccess,
522 TokenHandle)
526 static BOOL WINAPI
527 get_token_information (HANDLE TokenHandle,
528 TOKEN_INFORMATION_CLASS TokenInformationClass,
529 LPVOID TokenInformation,
530 DWORD TokenInformationLength,
531 PDWORD ReturnLength)
533 static GetTokenInformation_Proc s_pfn_Get_Token_Information = NULL;
534 HMODULE hm_advapi32 = NULL;
535 if (is_windows_9x () == TRUE)
537 return FALSE;
539 if (g_b_init_get_token_information == 0)
541 g_b_init_get_token_information = 1;
542 hm_advapi32 = LoadLibrary ("Advapi32.dll");
543 s_pfn_Get_Token_Information =
544 (GetTokenInformation_Proc) GetProcAddress (hm_advapi32, "GetTokenInformation");
546 if (s_pfn_Get_Token_Information == NULL)
548 return FALSE;
550 return (
551 s_pfn_Get_Token_Information (
552 TokenHandle,
553 TokenInformationClass,
554 TokenInformation,
555 TokenInformationLength,
556 ReturnLength)
560 static BOOL WINAPI
561 lookup_account_sid (LPCTSTR lpSystemName,
562 PSID Sid,
563 LPTSTR Name,
564 LPDWORD cbName,
565 LPTSTR DomainName,
566 LPDWORD cbDomainName,
567 PSID_NAME_USE peUse)
569 static LookupAccountSid_Proc s_pfn_Lookup_Account_Sid = NULL;
570 HMODULE hm_advapi32 = NULL;
571 if (is_windows_9x () == TRUE)
573 return FALSE;
575 if (g_b_init_lookup_account_sid == 0)
577 g_b_init_lookup_account_sid = 1;
578 hm_advapi32 = LoadLibrary ("Advapi32.dll");
579 s_pfn_Lookup_Account_Sid =
580 (LookupAccountSid_Proc) GetProcAddress (hm_advapi32, LookupAccountSid_Name);
582 if (s_pfn_Lookup_Account_Sid == NULL)
584 return FALSE;
586 return (
587 s_pfn_Lookup_Account_Sid (
588 lpSystemName,
589 Sid,
590 Name,
591 cbName,
592 DomainName,
593 cbDomainName,
594 peUse)
598 static PDWORD WINAPI
599 get_sid_sub_authority (PSID pSid, DWORD n)
601 static GetSidSubAuthority_Proc s_pfn_Get_Sid_Sub_Authority = NULL;
602 static DWORD zero = 0U;
603 HMODULE hm_advapi32 = NULL;
604 if (is_windows_9x () == TRUE)
606 return &zero;
608 if (g_b_init_get_sid_sub_authority == 0)
610 g_b_init_get_sid_sub_authority = 1;
611 hm_advapi32 = LoadLibrary ("Advapi32.dll");
612 s_pfn_Get_Sid_Sub_Authority =
613 (GetSidSubAuthority_Proc) GetProcAddress (
614 hm_advapi32, "GetSidSubAuthority");
616 if (s_pfn_Get_Sid_Sub_Authority == NULL)
618 return &zero;
620 return (s_pfn_Get_Sid_Sub_Authority (pSid, n));
623 static PUCHAR WINAPI
624 get_sid_sub_authority_count (PSID pSid)
626 static GetSidSubAuthorityCount_Proc s_pfn_Get_Sid_Sub_Authority_Count = NULL;
627 static UCHAR zero = 0U;
628 HMODULE hm_advapi32 = NULL;
629 if (is_windows_9x () == TRUE)
631 return &zero;
633 if (g_b_init_get_sid_sub_authority_count == 0)
635 g_b_init_get_sid_sub_authority_count = 1;
636 hm_advapi32 = LoadLibrary ("Advapi32.dll");
637 s_pfn_Get_Sid_Sub_Authority_Count =
638 (GetSidSubAuthorityCount_Proc) GetProcAddress (
639 hm_advapi32, "GetSidSubAuthorityCount");
641 if (s_pfn_Get_Sid_Sub_Authority_Count == NULL)
643 return &zero;
645 return (s_pfn_Get_Sid_Sub_Authority_Count (pSid));
648 static DWORD WINAPI
649 get_security_info (HANDLE handle,
650 SE_OBJECT_TYPE ObjectType,
651 SECURITY_INFORMATION SecurityInfo,
652 PSID *ppsidOwner,
653 PSID *ppsidGroup,
654 PACL *ppDacl,
655 PACL *ppSacl,
656 PSECURITY_DESCRIPTOR *ppSecurityDescriptor)
658 static GetSecurityInfo_Proc s_pfn_Get_Security_Info = NULL;
659 HMODULE hm_advapi32 = NULL;
660 if (is_windows_9x () == TRUE)
662 return FALSE;
664 if (g_b_init_get_security_info == 0)
666 g_b_init_get_security_info = 1;
667 hm_advapi32 = LoadLibrary ("Advapi32.dll");
668 s_pfn_Get_Security_Info =
669 (GetSecurityInfo_Proc) GetProcAddress (
670 hm_advapi32, "GetSecurityInfo");
672 if (s_pfn_Get_Security_Info == NULL)
674 return FALSE;
676 return (s_pfn_Get_Security_Info (handle, ObjectType, SecurityInfo,
677 ppsidOwner, ppsidGroup, ppDacl, ppSacl,
678 ppSecurityDescriptor));
681 static BOOL WINAPI
682 get_file_security (LPCTSTR lpFileName,
683 SECURITY_INFORMATION RequestedInformation,
684 PSECURITY_DESCRIPTOR pSecurityDescriptor,
685 DWORD nLength,
686 LPDWORD lpnLengthNeeded)
688 static GetFileSecurity_Proc s_pfn_Get_File_Security = NULL;
689 HMODULE hm_advapi32 = NULL;
690 if (is_windows_9x () == TRUE)
692 errno = ENOTSUP;
693 return FALSE;
695 if (g_b_init_get_file_security == 0)
697 g_b_init_get_file_security = 1;
698 hm_advapi32 = LoadLibrary ("Advapi32.dll");
699 s_pfn_Get_File_Security =
700 (GetFileSecurity_Proc) GetProcAddress (
701 hm_advapi32, GetFileSecurity_Name);
703 if (s_pfn_Get_File_Security == NULL)
705 errno = ENOTSUP;
706 return FALSE;
708 return (s_pfn_Get_File_Security (lpFileName, RequestedInformation,
709 pSecurityDescriptor, nLength,
710 lpnLengthNeeded));
713 static BOOL WINAPI
714 set_file_security (LPCTSTR lpFileName,
715 SECURITY_INFORMATION SecurityInformation,
716 PSECURITY_DESCRIPTOR pSecurityDescriptor)
718 static SetFileSecurity_Proc s_pfn_Set_File_Security = NULL;
719 HMODULE hm_advapi32 = NULL;
720 if (is_windows_9x () == TRUE)
722 errno = ENOTSUP;
723 return FALSE;
725 if (g_b_init_set_file_security == 0)
727 g_b_init_set_file_security = 1;
728 hm_advapi32 = LoadLibrary ("Advapi32.dll");
729 s_pfn_Set_File_Security =
730 (SetFileSecurity_Proc) GetProcAddress (
731 hm_advapi32, SetFileSecurity_Name);
733 if (s_pfn_Set_File_Security == NULL)
735 errno = ENOTSUP;
736 return FALSE;
738 return (s_pfn_Set_File_Security (lpFileName, SecurityInformation,
739 pSecurityDescriptor));
742 static BOOL WINAPI
743 get_security_descriptor_owner (PSECURITY_DESCRIPTOR pSecurityDescriptor,
744 PSID *pOwner,
745 LPBOOL lpbOwnerDefaulted)
747 static GetSecurityDescriptorOwner_Proc s_pfn_Get_Security_Descriptor_Owner = NULL;
748 HMODULE hm_advapi32 = NULL;
749 if (is_windows_9x () == TRUE)
751 errno = ENOTSUP;
752 return FALSE;
754 if (g_b_init_get_security_descriptor_owner == 0)
756 g_b_init_get_security_descriptor_owner = 1;
757 hm_advapi32 = LoadLibrary ("Advapi32.dll");
758 s_pfn_Get_Security_Descriptor_Owner =
759 (GetSecurityDescriptorOwner_Proc) GetProcAddress (
760 hm_advapi32, "GetSecurityDescriptorOwner");
762 if (s_pfn_Get_Security_Descriptor_Owner == NULL)
764 errno = ENOTSUP;
765 return FALSE;
767 return (s_pfn_Get_Security_Descriptor_Owner (pSecurityDescriptor, pOwner,
768 lpbOwnerDefaulted));
771 static BOOL WINAPI
772 get_security_descriptor_group (PSECURITY_DESCRIPTOR pSecurityDescriptor,
773 PSID *pGroup,
774 LPBOOL lpbGroupDefaulted)
776 static GetSecurityDescriptorGroup_Proc s_pfn_Get_Security_Descriptor_Group = NULL;
777 HMODULE hm_advapi32 = NULL;
778 if (is_windows_9x () == TRUE)
780 errno = ENOTSUP;
781 return FALSE;
783 if (g_b_init_get_security_descriptor_group == 0)
785 g_b_init_get_security_descriptor_group = 1;
786 hm_advapi32 = LoadLibrary ("Advapi32.dll");
787 s_pfn_Get_Security_Descriptor_Group =
788 (GetSecurityDescriptorGroup_Proc) GetProcAddress (
789 hm_advapi32, "GetSecurityDescriptorGroup");
791 if (s_pfn_Get_Security_Descriptor_Group == NULL)
793 errno = ENOTSUP;
794 return FALSE;
796 return (s_pfn_Get_Security_Descriptor_Group (pSecurityDescriptor, pGroup,
797 lpbGroupDefaulted));
800 static BOOL WINAPI
801 get_security_descriptor_dacl (PSECURITY_DESCRIPTOR pSecurityDescriptor,
802 LPBOOL lpbDaclPresent,
803 PACL *pDacl,
804 LPBOOL lpbDaclDefaulted)
806 static GetSecurityDescriptorDacl_Proc s_pfn_Get_Security_Descriptor_Dacl = NULL;
807 HMODULE hm_advapi32 = NULL;
808 if (is_windows_9x () == TRUE)
810 errno = ENOTSUP;
811 return FALSE;
813 if (g_b_init_get_security_descriptor_dacl == 0)
815 g_b_init_get_security_descriptor_dacl = 1;
816 hm_advapi32 = LoadLibrary ("Advapi32.dll");
817 s_pfn_Get_Security_Descriptor_Dacl =
818 (GetSecurityDescriptorDacl_Proc) GetProcAddress (
819 hm_advapi32, "GetSecurityDescriptorDacl");
821 if (s_pfn_Get_Security_Descriptor_Dacl == NULL)
823 errno = ENOTSUP;
824 return FALSE;
826 return (s_pfn_Get_Security_Descriptor_Dacl (pSecurityDescriptor,
827 lpbDaclPresent, pDacl,
828 lpbDaclDefaulted));
831 static BOOL WINAPI
832 is_valid_sid (PSID sid)
834 static IsValidSid_Proc s_pfn_Is_Valid_Sid = NULL;
835 HMODULE hm_advapi32 = NULL;
836 if (is_windows_9x () == TRUE)
838 return FALSE;
840 if (g_b_init_is_valid_sid == 0)
842 g_b_init_is_valid_sid = 1;
843 hm_advapi32 = LoadLibrary ("Advapi32.dll");
844 s_pfn_Is_Valid_Sid =
845 (IsValidSid_Proc) GetProcAddress (
846 hm_advapi32, "IsValidSid");
848 if (s_pfn_Is_Valid_Sid == NULL)
850 return FALSE;
852 return (s_pfn_Is_Valid_Sid (sid));
855 static BOOL WINAPI
856 equal_sid (PSID sid1, PSID sid2)
858 static EqualSid_Proc s_pfn_Equal_Sid = NULL;
859 HMODULE hm_advapi32 = NULL;
860 if (is_windows_9x () == TRUE)
862 return FALSE;
864 if (g_b_init_equal_sid == 0)
866 g_b_init_equal_sid = 1;
867 hm_advapi32 = LoadLibrary ("Advapi32.dll");
868 s_pfn_Equal_Sid =
869 (EqualSid_Proc) GetProcAddress (
870 hm_advapi32, "EqualSid");
872 if (s_pfn_Equal_Sid == NULL)
874 return FALSE;
876 return (s_pfn_Equal_Sid (sid1, sid2));
879 static DWORD WINAPI
880 get_length_sid (PSID sid)
882 static GetLengthSid_Proc s_pfn_Get_Length_Sid = NULL;
883 HMODULE hm_advapi32 = NULL;
884 if (is_windows_9x () == TRUE)
886 return 0;
888 if (g_b_init_get_length_sid == 0)
890 g_b_init_get_length_sid = 1;
891 hm_advapi32 = LoadLibrary ("Advapi32.dll");
892 s_pfn_Get_Length_Sid =
893 (GetLengthSid_Proc) GetProcAddress (
894 hm_advapi32, "GetLengthSid");
896 if (s_pfn_Get_Length_Sid == NULL)
898 return 0;
900 return (s_pfn_Get_Length_Sid (sid));
903 static BOOL WINAPI
904 copy_sid (DWORD destlen, PSID dest, PSID src)
906 static CopySid_Proc s_pfn_Copy_Sid = NULL;
907 HMODULE hm_advapi32 = NULL;
908 if (is_windows_9x () == TRUE)
910 return FALSE;
912 if (g_b_init_copy_sid == 0)
914 g_b_init_copy_sid = 1;
915 hm_advapi32 = LoadLibrary ("Advapi32.dll");
916 s_pfn_Copy_Sid =
917 (CopySid_Proc) GetProcAddress (
918 hm_advapi32, "CopySid");
920 if (s_pfn_Copy_Sid == NULL)
922 return FALSE;
924 return (s_pfn_Copy_Sid (destlen, dest, src));
928 END: Wrapper functions around OpenProcessToken
929 and other functions in advapi32.dll that are only
930 supported in Windows NT / 2k / XP
933 static void WINAPI
934 get_native_system_info (LPSYSTEM_INFO lpSystemInfo)
936 static GetNativeSystemInfo_Proc s_pfn_Get_Native_System_Info = NULL;
937 if (is_windows_9x () != TRUE)
939 if (g_b_init_get_native_system_info == 0)
941 g_b_init_get_native_system_info = 1;
942 s_pfn_Get_Native_System_Info =
943 (GetNativeSystemInfo_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
944 "GetNativeSystemInfo");
946 if (s_pfn_Get_Native_System_Info != NULL)
947 s_pfn_Get_Native_System_Info (lpSystemInfo);
949 else
950 lpSystemInfo->dwNumberOfProcessors = -1;
953 static BOOL WINAPI
954 get_system_times (LPFILETIME lpIdleTime,
955 LPFILETIME lpKernelTime,
956 LPFILETIME lpUserTime)
958 static GetSystemTimes_Proc s_pfn_Get_System_times = NULL;
959 if (is_windows_9x () == TRUE)
961 return FALSE;
963 if (g_b_init_get_system_times == 0)
965 g_b_init_get_system_times = 1;
966 s_pfn_Get_System_times =
967 (GetSystemTimes_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
968 "GetSystemTimes");
970 if (s_pfn_Get_System_times == NULL)
971 return FALSE;
972 return (s_pfn_Get_System_times (lpIdleTime, lpKernelTime, lpUserTime));
975 static BOOLEAN WINAPI
976 create_symbolic_link (LPTSTR lpSymlinkFilename,
977 LPTSTR lpTargetFileName,
978 DWORD dwFlags)
980 static CreateSymbolicLink_Proc s_pfn_Create_Symbolic_Link = NULL;
981 BOOLEAN retval;
983 if (is_windows_9x () == TRUE)
985 errno = ENOSYS;
986 return 0;
988 if (g_b_init_create_symbolic_link == 0)
990 g_b_init_create_symbolic_link = 1;
991 #ifdef _UNICODE
992 s_pfn_Create_Symbolic_Link =
993 (CreateSymbolicLink_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
994 "CreateSymbolicLinkW");
995 #else
996 s_pfn_Create_Symbolic_Link =
997 (CreateSymbolicLink_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
998 "CreateSymbolicLinkA");
999 #endif
1001 if (s_pfn_Create_Symbolic_Link == NULL)
1003 errno = ENOSYS;
1004 return 0;
1007 retval = s_pfn_Create_Symbolic_Link (lpSymlinkFilename, lpTargetFileName,
1008 dwFlags);
1009 /* If we were denied creation of the symlink, try again after
1010 enabling the SeCreateSymbolicLinkPrivilege for our process. */
1011 if (!retval)
1013 TOKEN_PRIVILEGES priv_current;
1015 if (enable_privilege (SE_CREATE_SYMBOLIC_LINK_NAME, TRUE, &priv_current))
1017 retval = s_pfn_Create_Symbolic_Link (lpSymlinkFilename, lpTargetFileName,
1018 dwFlags);
1019 restore_privilege (&priv_current);
1020 revert_to_self ();
1023 return retval;
1026 static BOOL WINAPI
1027 is_valid_security_descriptor (PSECURITY_DESCRIPTOR pSecurityDescriptor)
1029 static IsValidSecurityDescriptor_Proc s_pfn_Is_Valid_Security_Descriptor_Proc = NULL;
1031 if (is_windows_9x () == TRUE)
1033 errno = ENOTSUP;
1034 return FALSE;
1037 if (g_b_init_is_valid_security_descriptor == 0)
1039 g_b_init_is_valid_security_descriptor = 1;
1040 s_pfn_Is_Valid_Security_Descriptor_Proc =
1041 (IsValidSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1042 "IsValidSecurityDescriptor");
1044 if (s_pfn_Is_Valid_Security_Descriptor_Proc == NULL)
1046 errno = ENOTSUP;
1047 return FALSE;
1050 return s_pfn_Is_Valid_Security_Descriptor_Proc (pSecurityDescriptor);
1053 static BOOL WINAPI
1054 convert_sd_to_sddl (PSECURITY_DESCRIPTOR SecurityDescriptor,
1055 DWORD RequestedStringSDRevision,
1056 SECURITY_INFORMATION SecurityInformation,
1057 LPTSTR *StringSecurityDescriptor,
1058 PULONG StringSecurityDescriptorLen)
1060 static ConvertSecurityDescriptorToStringSecurityDescriptor_Proc s_pfn_Convert_SD_To_SDDL = NULL;
1061 BOOL retval;
1063 if (is_windows_9x () == TRUE)
1065 errno = ENOTSUP;
1066 return FALSE;
1069 if (g_b_init_convert_sd_to_sddl == 0)
1071 g_b_init_convert_sd_to_sddl = 1;
1072 #ifdef _UNICODE
1073 s_pfn_Convert_SD_To_SDDL =
1074 (ConvertSecurityDescriptorToStringSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1075 "ConvertSecurityDescriptorToStringSecurityDescriptorW");
1076 #else
1077 s_pfn_Convert_SD_To_SDDL =
1078 (ConvertSecurityDescriptorToStringSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1079 "ConvertSecurityDescriptorToStringSecurityDescriptorA");
1080 #endif
1082 if (s_pfn_Convert_SD_To_SDDL == NULL)
1084 errno = ENOTSUP;
1085 return FALSE;
1088 retval = s_pfn_Convert_SD_To_SDDL (SecurityDescriptor,
1089 RequestedStringSDRevision,
1090 SecurityInformation,
1091 StringSecurityDescriptor,
1092 StringSecurityDescriptorLen);
1094 return retval;
1097 static BOOL WINAPI
1098 convert_sddl_to_sd (LPCTSTR StringSecurityDescriptor,
1099 DWORD StringSDRevision,
1100 PSECURITY_DESCRIPTOR *SecurityDescriptor,
1101 PULONG SecurityDescriptorSize)
1103 static ConvertStringSecurityDescriptorToSecurityDescriptor_Proc s_pfn_Convert_SDDL_To_SD = NULL;
1104 BOOL retval;
1106 if (is_windows_9x () == TRUE)
1108 errno = ENOTSUP;
1109 return FALSE;
1112 if (g_b_init_convert_sddl_to_sd == 0)
1114 g_b_init_convert_sddl_to_sd = 1;
1115 #ifdef _UNICODE
1116 s_pfn_Convert_SDDL_To_SD =
1117 (ConvertStringSecurityDescriptorToSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1118 "ConvertStringSecurityDescriptorToSecurityDescriptorW");
1119 #else
1120 s_pfn_Convert_SDDL_To_SD =
1121 (ConvertStringSecurityDescriptorToSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1122 "ConvertStringSecurityDescriptorToSecurityDescriptorA");
1123 #endif
1125 if (s_pfn_Convert_SDDL_To_SD == NULL)
1127 errno = ENOTSUP;
1128 return FALSE;
1131 retval = s_pfn_Convert_SDDL_To_SD (StringSecurityDescriptor,
1132 StringSDRevision,
1133 SecurityDescriptor,
1134 SecurityDescriptorSize);
1136 return retval;
1139 static DWORD WINAPI
1140 get_adapters_info (PIP_ADAPTER_INFO pAdapterInfo, PULONG pOutBufLen)
1142 static GetAdaptersInfo_Proc s_pfn_Get_Adapters_Info = NULL;
1143 HMODULE hm_iphlpapi = NULL;
1145 if (is_windows_9x () == TRUE)
1146 return ERROR_NOT_SUPPORTED;
1148 if (g_b_init_get_adapters_info == 0)
1150 g_b_init_get_adapters_info = 1;
1151 hm_iphlpapi = LoadLibrary ("Iphlpapi.dll");
1152 if (hm_iphlpapi)
1153 s_pfn_Get_Adapters_Info = (GetAdaptersInfo_Proc)
1154 GetProcAddress (hm_iphlpapi, "GetAdaptersInfo");
1156 if (s_pfn_Get_Adapters_Info == NULL)
1157 return ERROR_NOT_SUPPORTED;
1158 return s_pfn_Get_Adapters_Info (pAdapterInfo, pOutBufLen);
1163 /* Return 1 if P is a valid pointer to an object of size SIZE. Return
1164 0 if P is NOT a valid pointer. Return -1 if we cannot validate P.
1166 This is called from alloc.c:valid_pointer_p. */
1168 w32_valid_pointer_p (void *p, int size)
1170 SIZE_T done;
1171 HANDLE h = OpenProcess (PROCESS_VM_READ, FALSE, GetCurrentProcessId ());
1173 if (h)
1175 unsigned char *buf = alloca (size);
1176 int retval = ReadProcessMemory (h, p, buf, size, &done);
1178 CloseHandle (h);
1179 return retval;
1181 else
1182 return -1;
1185 static char startup_dir[MAXPATHLEN];
1187 /* Get the current working directory. */
1188 char *
1189 getcwd (char *dir, int dirsize)
1191 if (!dirsize)
1193 errno = EINVAL;
1194 return NULL;
1196 if (dirsize <= strlen (startup_dir))
1198 errno = ERANGE;
1199 return NULL;
1201 #if 0
1202 if (GetCurrentDirectory (MAXPATHLEN, dir) > 0)
1203 return dir;
1204 return NULL;
1205 #else
1206 /* Emacs doesn't actually change directory itself, it stays in the
1207 same directory where it was started. */
1208 strcpy (dir, startup_dir);
1209 return dir;
1210 #endif
1213 /* Emulate getloadavg. */
1215 struct load_sample {
1216 time_t sample_time;
1217 ULONGLONG idle;
1218 ULONGLONG kernel;
1219 ULONGLONG user;
1222 /* Number of processors on this machine. */
1223 static unsigned num_of_processors;
1225 /* We maintain 1-sec samples for the last 16 minutes in a circular buffer. */
1226 static struct load_sample samples[16*60];
1227 static int first_idx = -1, last_idx = -1;
1228 static int max_idx = sizeof (samples) / sizeof (samples[0]);
1230 static int
1231 buf_next (int from)
1233 int next_idx = from + 1;
1235 if (next_idx >= max_idx)
1236 next_idx = 0;
1238 return next_idx;
1241 static int
1242 buf_prev (int from)
1244 int prev_idx = from - 1;
1246 if (prev_idx < 0)
1247 prev_idx = max_idx - 1;
1249 return prev_idx;
1252 static void
1253 sample_system_load (ULONGLONG *idle, ULONGLONG *kernel, ULONGLONG *user)
1255 SYSTEM_INFO sysinfo;
1256 FILETIME ft_idle, ft_user, ft_kernel;
1258 /* Initialize the number of processors on this machine. */
1259 if (num_of_processors <= 0)
1261 get_native_system_info (&sysinfo);
1262 num_of_processors = sysinfo.dwNumberOfProcessors;
1263 if (num_of_processors <= 0)
1265 GetSystemInfo (&sysinfo);
1266 num_of_processors = sysinfo.dwNumberOfProcessors;
1268 if (num_of_processors <= 0)
1269 num_of_processors = 1;
1272 /* TODO: Take into account threads that are ready to run, by
1273 sampling the "\System\Processor Queue Length" performance
1274 counter. The code below accounts only for threads that are
1275 actually running. */
1277 if (get_system_times (&ft_idle, &ft_kernel, &ft_user))
1279 ULARGE_INTEGER uidle, ukernel, uuser;
1281 memcpy (&uidle, &ft_idle, sizeof (ft_idle));
1282 memcpy (&ukernel, &ft_kernel, sizeof (ft_kernel));
1283 memcpy (&uuser, &ft_user, sizeof (ft_user));
1284 *idle = uidle.QuadPart;
1285 *kernel = ukernel.QuadPart;
1286 *user = uuser.QuadPart;
1288 else
1290 *idle = 0;
1291 *kernel = 0;
1292 *user = 0;
1296 /* Produce the load average for a given time interval, using the
1297 samples in the samples[] array. WHICH can be 0, 1, or 2, meaning
1298 1-minute, 5-minute, or 15-minute average, respectively. */
1299 static double
1300 getavg (int which)
1302 double retval = -1.0;
1303 double tdiff;
1304 int idx;
1305 double span = (which == 0 ? 1.0 : (which == 1 ? 5.0 : 15.0)) * 60;
1306 time_t now = samples[last_idx].sample_time;
1308 if (first_idx != last_idx)
1310 for (idx = buf_prev (last_idx); ; idx = buf_prev (idx))
1312 tdiff = difftime (now, samples[idx].sample_time);
1313 if (tdiff >= span - 2*DBL_EPSILON*now)
1315 long double sys =
1316 samples[last_idx].kernel + samples[last_idx].user
1317 - (samples[idx].kernel + samples[idx].user);
1318 long double idl = samples[last_idx].idle - samples[idx].idle;
1320 retval = (1.0 - idl / sys) * num_of_processors;
1321 break;
1323 if (idx == first_idx)
1324 break;
1328 return retval;
1332 getloadavg (double loadavg[], int nelem)
1334 int elem;
1335 ULONGLONG idle, kernel, user;
1336 time_t now = time (NULL);
1338 /* Store another sample. We ignore samples that are less than 1 sec
1339 apart. */
1340 if (difftime (now, samples[last_idx].sample_time) >= 1.0 - 2*DBL_EPSILON*now)
1342 sample_system_load (&idle, &kernel, &user);
1343 last_idx = buf_next (last_idx);
1344 samples[last_idx].sample_time = now;
1345 samples[last_idx].idle = idle;
1346 samples[last_idx].kernel = kernel;
1347 samples[last_idx].user = user;
1348 /* If the buffer has more that 15 min worth of samples, discard
1349 the old ones. */
1350 if (first_idx == -1)
1351 first_idx = last_idx;
1352 while (first_idx != last_idx
1353 && (difftime (now, samples[first_idx].sample_time)
1354 >= 15.0*60 + 2*DBL_EPSILON*now))
1355 first_idx = buf_next (first_idx);
1358 for (elem = 0; elem < nelem; elem++)
1360 double avg = getavg (elem);
1362 if (avg < 0)
1363 break;
1364 loadavg[elem] = avg;
1367 return elem;
1370 /* Emulate getpwuid, getpwnam and others. */
1372 #define PASSWD_FIELD_SIZE 256
1374 static char dflt_passwd_name[PASSWD_FIELD_SIZE];
1375 static char dflt_passwd_passwd[PASSWD_FIELD_SIZE];
1376 static char dflt_passwd_gecos[PASSWD_FIELD_SIZE];
1377 static char dflt_passwd_dir[PASSWD_FIELD_SIZE];
1378 static char dflt_passwd_shell[PASSWD_FIELD_SIZE];
1380 static struct passwd dflt_passwd =
1382 dflt_passwd_name,
1383 dflt_passwd_passwd,
1387 dflt_passwd_gecos,
1388 dflt_passwd_dir,
1389 dflt_passwd_shell,
1392 static char dflt_group_name[GNLEN+1];
1394 static struct group dflt_group =
1396 /* When group information is not available, we return this as the
1397 group for all files. */
1398 dflt_group_name,
1402 unsigned
1403 getuid (void)
1405 return dflt_passwd.pw_uid;
1408 unsigned
1409 geteuid (void)
1411 /* I could imagine arguing for checking to see whether the user is
1412 in the Administrators group and returning a UID of 0 for that
1413 case, but I don't know how wise that would be in the long run. */
1414 return getuid ();
1417 unsigned
1418 getgid (void)
1420 return dflt_passwd.pw_gid;
1423 unsigned
1424 getegid (void)
1426 return getgid ();
1429 struct passwd *
1430 getpwuid (unsigned uid)
1432 if (uid == dflt_passwd.pw_uid)
1433 return &dflt_passwd;
1434 return NULL;
1437 struct group *
1438 getgrgid (gid_t gid)
1440 return &dflt_group;
1443 struct passwd *
1444 getpwnam (char *name)
1446 struct passwd *pw;
1448 pw = getpwuid (getuid ());
1449 if (!pw)
1450 return pw;
1452 if (xstrcasecmp (name, pw->pw_name))
1453 return NULL;
1455 return pw;
1458 static void
1459 init_user_info (void)
1461 /* Find the user's real name by opening the process token and
1462 looking up the name associated with the user-sid in that token.
1464 Use the relative portion of the identifier authority value from
1465 the user-sid as the user id value (same for group id using the
1466 primary group sid from the process token). */
1468 char uname[UNLEN+1], gname[GNLEN+1], domain[1025];
1469 DWORD ulength = sizeof (uname), dlength = sizeof (domain), needed;
1470 DWORD glength = sizeof (gname);
1471 HANDLE token = NULL;
1472 SID_NAME_USE user_type;
1473 unsigned char *buf = NULL;
1474 DWORD blen = 0;
1475 TOKEN_USER user_token;
1476 TOKEN_PRIMARY_GROUP group_token;
1477 BOOL result;
1479 result = open_process_token (GetCurrentProcess (), TOKEN_QUERY, &token);
1480 if (result)
1482 result = get_token_information (token, TokenUser, NULL, 0, &blen);
1483 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
1485 buf = xmalloc (blen);
1486 result = get_token_information (token, TokenUser,
1487 (LPVOID)buf, blen, &needed);
1488 if (result)
1490 memcpy (&user_token, buf, sizeof (user_token));
1491 result = lookup_account_sid (NULL, user_token.User.Sid,
1492 uname, &ulength,
1493 domain, &dlength, &user_type);
1496 else
1497 result = FALSE;
1499 if (result)
1501 strcpy (dflt_passwd.pw_name, uname);
1502 /* Determine a reasonable uid value. */
1503 if (xstrcasecmp ("administrator", uname) == 0)
1505 dflt_passwd.pw_uid = 500; /* well-known Administrator uid */
1506 dflt_passwd.pw_gid = 513; /* well-known None gid */
1508 else
1510 /* Use the last sub-authority value of the RID, the relative
1511 portion of the SID, as user/group ID. */
1512 dflt_passwd.pw_uid = get_rid (user_token.User.Sid);
1514 /* Get group id and name. */
1515 result = get_token_information (token, TokenPrimaryGroup,
1516 (LPVOID)buf, blen, &needed);
1517 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
1519 buf = xrealloc (buf, blen = needed);
1520 result = get_token_information (token, TokenPrimaryGroup,
1521 (LPVOID)buf, blen, &needed);
1523 if (result)
1525 memcpy (&group_token, buf, sizeof (group_token));
1526 dflt_passwd.pw_gid = get_rid (group_token.PrimaryGroup);
1527 dlength = sizeof (domain);
1528 /* If we can get at the real Primary Group name, use that.
1529 Otherwise, the default group name was already set to
1530 "None" in globals_of_w32. */
1531 if (lookup_account_sid (NULL, group_token.PrimaryGroup,
1532 gname, &glength, NULL, &dlength,
1533 &user_type))
1534 strcpy (dflt_group_name, gname);
1536 else
1537 dflt_passwd.pw_gid = dflt_passwd.pw_uid;
1540 /* If security calls are not supported (presumably because we
1541 are running under Windows 9X), fallback to this: */
1542 else if (GetUserName (uname, &ulength))
1544 strcpy (dflt_passwd.pw_name, uname);
1545 if (xstrcasecmp ("administrator", uname) == 0)
1546 dflt_passwd.pw_uid = 0;
1547 else
1548 dflt_passwd.pw_uid = 123;
1549 dflt_passwd.pw_gid = dflt_passwd.pw_uid;
1551 else
1553 strcpy (dflt_passwd.pw_name, "unknown");
1554 dflt_passwd.pw_uid = 123;
1555 dflt_passwd.pw_gid = 123;
1557 dflt_group.gr_gid = dflt_passwd.pw_gid;
1559 /* Ensure HOME and SHELL are defined. */
1560 if (getenv ("HOME") == NULL)
1561 emacs_abort ();
1562 if (getenv ("SHELL") == NULL)
1563 emacs_abort ();
1565 /* Set dir and shell from environment variables. */
1566 strcpy (dflt_passwd.pw_dir, getenv ("HOME"));
1567 strcpy (dflt_passwd.pw_shell, getenv ("SHELL"));
1569 xfree (buf);
1570 if (token)
1571 CloseHandle (token);
1575 random (void)
1577 /* rand () on NT gives us 15 random bits...hack together 30 bits. */
1578 return ((rand () << 15) | rand ());
1581 void
1582 srandom (int seed)
1584 srand (seed);
1587 /* Current codepage for encoding file names. */
1588 static int file_name_codepage;
1590 /* Return the maximum length in bytes of a multibyte character
1591 sequence encoded in the current ANSI codepage. This is required to
1592 correctly walk the encoded file names one character at a time. */
1593 static int
1594 max_filename_mbslen (void)
1596 /* A simple cache to avoid calling GetCPInfo every time we need to
1597 normalize a file name. The file-name encoding is not supposed to
1598 be changed too frequently, if ever. */
1599 static Lisp_Object last_file_name_encoding;
1600 static int last_max_mbslen;
1601 Lisp_Object current_encoding;
1603 current_encoding = Vfile_name_coding_system;
1604 if (NILP (current_encoding))
1605 current_encoding = Vdefault_file_name_coding_system;
1607 if (!EQ (last_file_name_encoding, current_encoding))
1609 CPINFO cp_info;
1611 last_file_name_encoding = current_encoding;
1612 /* Default to the current ANSI codepage. */
1613 file_name_codepage = w32_ansi_code_page;
1614 if (!NILP (current_encoding))
1616 char *cpname = SDATA (SYMBOL_NAME (current_encoding));
1617 char *cp = NULL, *end;
1618 int cpnum;
1620 if (strncmp (cpname, "cp", 2) == 0)
1621 cp = cpname + 2;
1622 else if (strncmp (cpname, "windows-", 8) == 0)
1623 cp = cpname + 8;
1625 if (cp)
1627 end = cp;
1628 cpnum = strtol (cp, &end, 10);
1629 if (cpnum && *end == '\0' && end - cp >= 2)
1630 file_name_codepage = cpnum;
1634 if (!file_name_codepage)
1635 file_name_codepage = CP_ACP; /* CP_ACP = 0, but let's not assume that */
1637 if (!GetCPInfo (file_name_codepage, &cp_info))
1639 file_name_codepage = CP_ACP;
1640 if (!GetCPInfo (file_name_codepage, &cp_info))
1641 emacs_abort ();
1643 last_max_mbslen = cp_info.MaxCharSize;
1646 return last_max_mbslen;
1649 /* Normalize filename by converting all path separators to
1650 the specified separator. Also conditionally convert upper
1651 case path name components to lower case. */
1653 static void
1654 normalize_filename (register char *fp, char path_sep, int multibyte)
1656 char sep;
1657 char *elem, *p2;
1658 int dbcs_p = max_filename_mbslen () > 1;
1660 /* Multibyte file names are in the Emacs internal representation, so
1661 we can traverse them by bytes with no problems. */
1662 if (multibyte)
1663 dbcs_p = 0;
1665 /* Always lower-case drive letters a-z, even if the filesystem
1666 preserves case in filenames.
1667 This is so filenames can be compared by string comparison
1668 functions that are case-sensitive. Even case-preserving filesystems
1669 do not distinguish case in drive letters. */
1670 if (dbcs_p)
1671 p2 = CharNextExA (file_name_codepage, fp, 0);
1672 else
1673 p2 = fp + 1;
1675 if (*p2 == ':' && *fp >= 'A' && *fp <= 'Z')
1677 *fp += 'a' - 'A';
1678 fp += 2;
1681 if (multibyte || NILP (Vw32_downcase_file_names))
1683 while (*fp)
1685 if (*fp == '/' || *fp == '\\')
1686 *fp = path_sep;
1687 if (!dbcs_p)
1688 fp++;
1689 else
1690 fp = CharNextExA (file_name_codepage, fp, 0);
1692 return;
1695 sep = path_sep; /* convert to this path separator */
1696 elem = fp; /* start of current path element */
1698 do {
1699 if (*fp >= 'a' && *fp <= 'z')
1700 elem = 0; /* don't convert this element */
1702 if (*fp == 0 || *fp == ':')
1704 sep = *fp; /* restore current separator (or 0) */
1705 *fp = '/'; /* after conversion of this element */
1708 if (*fp == '/' || *fp == '\\')
1710 if (elem && elem != fp)
1712 *fp = 0; /* temporary end of string */
1713 _mbslwr (elem); /* while we convert to lower case */
1715 *fp = sep; /* convert (or restore) path separator */
1716 elem = fp + 1; /* next element starts after separator */
1717 sep = path_sep;
1719 if (*fp)
1721 if (!dbcs_p)
1722 fp++;
1723 else
1724 fp = CharNextExA (file_name_codepage, fp, 0);
1726 } while (*fp);
1729 /* Destructively turn backslashes into slashes. MULTIBYTE non-zero
1730 means the file name is a multibyte string in Emacs's internal
1731 representation. */
1732 void
1733 dostounix_filename (register char *p, int multibyte)
1735 normalize_filename (p, '/', multibyte);
1738 /* Destructively turn slashes into backslashes. */
1739 void
1740 unixtodos_filename (register char *p)
1742 normalize_filename (p, '\\', 0);
1745 /* Remove all CR's that are followed by a LF.
1746 (From msdos.c...probably should figure out a way to share it,
1747 although this code isn't going to ever change.) */
1748 static int
1749 crlf_to_lf (register int n, register unsigned char *buf)
1751 unsigned char *np = buf;
1752 unsigned char *startp = buf;
1753 unsigned char *endp = buf + n;
1755 if (n == 0)
1756 return n;
1757 while (buf < endp - 1)
1759 if (*buf == 0x0d)
1761 if (*(++buf) != 0x0a)
1762 *np++ = 0x0d;
1764 else
1765 *np++ = *buf++;
1767 if (buf < endp)
1768 *np++ = *buf++;
1769 return np - startp;
1772 /* Parse the root part of file name, if present. Return length and
1773 optionally store pointer to char after root. */
1774 static int
1775 parse_root (char * name, char ** pPath)
1777 char * start = name;
1779 if (name == NULL)
1780 return 0;
1782 /* find the root name of the volume if given */
1783 if (isalpha (name[0]) && name[1] == ':')
1785 /* skip past drive specifier */
1786 name += 2;
1787 if (IS_DIRECTORY_SEP (name[0]))
1788 name++;
1790 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
1792 int slashes = 2;
1793 int dbcs_p = max_filename_mbslen () > 1;
1795 name += 2;
1798 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
1799 break;
1800 if (dbcs_p)
1801 name = CharNextExA (file_name_codepage, name, 0);
1802 else
1803 name++;
1805 while ( *name );
1806 if (IS_DIRECTORY_SEP (name[0]))
1807 name++;
1810 if (pPath)
1811 *pPath = name;
1813 return name - start;
1816 /* Get long base name for name; name is assumed to be absolute. */
1817 static int
1818 get_long_basename (char * name, char * buf, int size)
1820 WIN32_FIND_DATA find_data;
1821 HANDLE dir_handle;
1822 int len = 0;
1824 /* must be valid filename, no wild cards or other invalid characters */
1825 if (_mbspbrk (name, "*?|<>\""))
1826 return 0;
1828 dir_handle = FindFirstFile (name, &find_data);
1829 if (dir_handle != INVALID_HANDLE_VALUE)
1831 if ((len = strlen (find_data.cFileName)) < size)
1832 memcpy (buf, find_data.cFileName, len + 1);
1833 else
1834 len = 0;
1835 FindClose (dir_handle);
1837 return len;
1840 /* Get long name for file, if possible (assumed to be absolute). */
1841 BOOL
1842 w32_get_long_filename (char * name, char * buf, int size)
1844 char * o = buf;
1845 char * p;
1846 char * q;
1847 char full[ MAX_PATH ];
1848 int len;
1850 len = strlen (name);
1851 if (len >= MAX_PATH)
1852 return FALSE;
1854 /* Use local copy for destructive modification. */
1855 memcpy (full, name, len+1);
1856 unixtodos_filename (full);
1858 /* Copy root part verbatim. */
1859 len = parse_root (full, &p);
1860 memcpy (o, full, len);
1861 o += len;
1862 *o = '\0';
1863 size -= len;
1865 while (p != NULL && *p)
1867 q = p;
1868 p = _mbschr (q, '\\');
1869 if (p) *p = '\0';
1870 len = get_long_basename (full, o, size);
1871 if (len > 0)
1873 o += len;
1874 size -= len;
1875 if (p != NULL)
1877 *p++ = '\\';
1878 if (size < 2)
1879 return FALSE;
1880 *o++ = '\\';
1881 size--;
1882 *o = '\0';
1885 else
1886 return FALSE;
1889 return TRUE;
1892 static int
1893 is_unc_volume (const char *filename)
1895 const char *ptr = filename;
1897 if (!IS_DIRECTORY_SEP (ptr[0]) || !IS_DIRECTORY_SEP (ptr[1]) || !ptr[2])
1898 return 0;
1900 if (_mbspbrk (ptr + 2, "*?|<>\"\\/"))
1901 return 0;
1903 return 1;
1906 /* Emulate the Posix unsetenv. */
1908 unsetenv (const char *name)
1910 char *var;
1911 size_t name_len;
1912 int retval;
1914 if (name == NULL || *name == '\0' || strchr (name, '=') != NULL)
1916 errno = EINVAL;
1917 return -1;
1919 name_len = strlen (name);
1920 /* MS docs says an environment variable cannot be longer than 32K. */
1921 if (name_len > 32767)
1923 errno = ENOMEM;
1924 return 0;
1926 /* It is safe to use 'alloca' with 32K size, since the stack is at
1927 least 2MB, and we set it to 8MB in the link command line. */
1928 var = alloca (name_len + 2);
1929 strncpy (var, name, name_len);
1930 var[name_len++] = '=';
1931 var[name_len] = '\0';
1932 return _putenv (var);
1935 /* MS _putenv doesn't support removing a variable when the argument
1936 does not include the '=' character, so we fix that here. */
1938 sys_putenv (char *str)
1940 const char *const name_end = strchr (str, '=');
1942 if (name_end == NULL)
1944 /* Remove the variable from the environment. */
1945 return unsetenv (str);
1948 return _putenv (str);
1951 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
1953 LPBYTE
1954 w32_get_resource (char *key, LPDWORD lpdwtype)
1956 LPBYTE lpvalue;
1957 HKEY hrootkey = NULL;
1958 DWORD cbData;
1960 /* Check both the current user and the local machine to see if
1961 we have any resources. */
1963 if (RegOpenKeyEx (HKEY_CURRENT_USER, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
1965 lpvalue = NULL;
1967 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
1968 && (lpvalue = xmalloc (cbData)) != NULL
1969 && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
1971 RegCloseKey (hrootkey);
1972 return (lpvalue);
1975 xfree (lpvalue);
1977 RegCloseKey (hrootkey);
1980 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
1982 lpvalue = NULL;
1984 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
1985 && (lpvalue = xmalloc (cbData)) != NULL
1986 && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
1988 RegCloseKey (hrootkey);
1989 return (lpvalue);
1992 xfree (lpvalue);
1994 RegCloseKey (hrootkey);
1997 return (NULL);
2000 char *get_emacs_configuration (void);
2002 void
2003 init_environment (char ** argv)
2005 static const char * const tempdirs[] = {
2006 "$TMPDIR", "$TEMP", "$TMP", "c:/"
2009 int i;
2011 const int imax = sizeof (tempdirs) / sizeof (tempdirs[0]);
2013 /* Make sure they have a usable $TMPDIR. Many Emacs functions use
2014 temporary files and assume "/tmp" if $TMPDIR is unset, which
2015 will break on DOS/Windows. Refuse to work if we cannot find
2016 a directory, not even "c:/", usable for that purpose. */
2017 for (i = 0; i < imax ; i++)
2019 const char *tmp = tempdirs[i];
2021 if (*tmp == '$')
2022 tmp = getenv (tmp + 1);
2023 /* Note that `access' can lie to us if the directory resides on a
2024 read-only filesystem, like CD-ROM or a write-protected floppy.
2025 The only way to be really sure is to actually create a file and
2026 see if it succeeds. But I think that's too much to ask. */
2028 /* MSVCRT's _access crashes with D_OK. */
2029 if (tmp && faccessat (AT_FDCWD, tmp, D_OK, AT_EACCESS) == 0)
2031 char * var = alloca (strlen (tmp) + 8);
2032 sprintf (var, "TMPDIR=%s", tmp);
2033 _putenv (strdup (var));
2034 break;
2037 if (i >= imax)
2038 cmd_error_internal
2039 (Fcons (Qerror,
2040 Fcons (build_string ("no usable temporary directories found!!"),
2041 Qnil)),
2042 "While setting TMPDIR: ");
2044 /* Check for environment variables and use registry settings if they
2045 don't exist. Fallback on default values where applicable. */
2047 int i;
2048 LPBYTE lpval;
2049 DWORD dwType;
2050 char locale_name[32];
2051 char default_home[MAX_PATH];
2052 int appdata = 0;
2054 static const struct env_entry
2056 char * name;
2057 char * def_value;
2058 } dflt_envvars[] =
2060 /* If the default value is NULL, we will use the value from the
2061 outside environment or the Registry, but will not push the
2062 variable into the Emacs environment if it is defined neither
2063 in the Registry nor in the outside environment. */
2064 {"HOME", "C:/"},
2065 {"PRELOAD_WINSOCK", NULL},
2066 {"emacs_dir", "C:/emacs"},
2067 {"EMACSLOADPATH", NULL},
2068 {"SHELL", "cmdproxy.exe"}, /* perhaps it is somewhere on PATH */
2069 {"EMACSDATA", NULL},
2070 {"EMACSPATH", NULL},
2071 {"INFOPATH", NULL},
2072 {"EMACSDOC", NULL},
2073 {"TERM", "cmd"},
2074 {"LANG", NULL},
2077 #define N_ENV_VARS sizeof (dflt_envvars)/sizeof (dflt_envvars[0])
2079 /* We need to copy dflt_envvars[] and work on the copy because we
2080 don't want the dumped Emacs to inherit the values of
2081 environment variables we saw during dumping (which could be on
2082 a different system). The defaults above must be left intact. */
2083 struct env_entry env_vars[N_ENV_VARS];
2085 for (i = 0; i < N_ENV_VARS; i++)
2086 env_vars[i] = dflt_envvars[i];
2088 /* For backwards compatibility, check if a .emacs file exists in C:/
2089 If not, then we can try to default to the appdata directory under the
2090 user's profile, which is more likely to be writable. */
2091 if (faccessat (AT_FDCWD, "C:/.emacs", F_OK, AT_EACCESS) != 0)
2093 HRESULT profile_result;
2094 /* Dynamically load ShGetFolderPath, as it won't exist on versions
2095 of Windows 95 and NT4 that have not been updated to include
2096 MSIE 5. */
2097 ShGetFolderPath_fn get_folder_path;
2098 get_folder_path = (ShGetFolderPath_fn)
2099 GetProcAddress (GetModuleHandle ("shell32.dll"), "SHGetFolderPathA");
2101 if (get_folder_path != NULL)
2103 profile_result = get_folder_path (NULL, CSIDL_APPDATA, NULL,
2104 0, default_home);
2106 /* If we can't get the appdata dir, revert to old behavior. */
2107 if (profile_result == S_OK)
2109 env_vars[0].def_value = default_home;
2110 appdata = 1;
2115 /* Get default locale info and use it for LANG. */
2116 if (GetLocaleInfo (LOCALE_USER_DEFAULT,
2117 LOCALE_SABBREVLANGNAME | LOCALE_USE_CP_ACP,
2118 locale_name, sizeof (locale_name)))
2120 for (i = 0; i < N_ENV_VARS; i++)
2122 if (strcmp (env_vars[i].name, "LANG") == 0)
2124 env_vars[i].def_value = locale_name;
2125 break;
2130 #define SET_ENV_BUF_SIZE (4 * MAX_PATH) /* to cover EMACSLOADPATH */
2132 /* Treat emacs_dir specially: set it unconditionally based on our
2133 location. */
2135 char *p;
2136 char modname[MAX_PATH];
2138 if (!GetModuleFileName (NULL, modname, MAX_PATH))
2139 emacs_abort ();
2140 if ((p = _mbsrchr (modname, '\\')) == NULL)
2141 emacs_abort ();
2142 *p = 0;
2144 if ((p = _mbsrchr (modname, '\\'))
2145 /* From bin means installed Emacs, from src means uninstalled. */
2146 && (xstrcasecmp (p, "\\bin") == 0 || xstrcasecmp (p, "\\src") == 0))
2148 char buf[SET_ENV_BUF_SIZE];
2149 int within_build_tree = xstrcasecmp (p, "\\src") == 0;
2151 *p = 0;
2152 for (p = modname; *p; p = CharNext (p))
2153 if (*p == '\\') *p = '/';
2155 _snprintf (buf, sizeof (buf)-1, "emacs_dir=%s", modname);
2156 _putenv (strdup (buf));
2157 /* If we are running from the Posix-like build tree, define
2158 SHELL to point to our own cmdproxy. The loop below will
2159 then disregard PATH_EXEC and the default value. */
2160 if (within_build_tree)
2162 _snprintf (buf, sizeof (buf) - 1,
2163 "SHELL=%s/nt/cmdproxy.exe", modname);
2164 _putenv (strdup (buf));
2167 /* Handle running emacs from the build directory: src/oo-spd/i386/ */
2169 /* FIXME: should use substring of get_emacs_configuration ().
2170 But I don't think the Windows build supports alpha, mips etc
2171 anymore, so have taken the easy option for now. */
2172 else if (p && (xstrcasecmp (p, "\\i386") == 0
2173 || xstrcasecmp (p, "\\AMD64") == 0))
2175 *p = 0;
2176 p = _mbsrchr (modname, '\\');
2177 if (p != NULL)
2179 *p = 0;
2180 p = _mbsrchr (modname, '\\');
2181 if (p && xstrcasecmp (p, "\\src") == 0)
2183 char buf[SET_ENV_BUF_SIZE];
2185 *p = 0;
2186 for (p = modname; *p; p = CharNext (p))
2187 if (*p == '\\') *p = '/';
2189 _snprintf (buf, sizeof (buf)-1, "emacs_dir=%s", modname);
2190 _putenv (strdup (buf));
2196 for (i = 0; i < N_ENV_VARS; i++)
2198 if (!getenv (env_vars[i].name))
2200 int dont_free = 0;
2201 char bufc[SET_ENV_BUF_SIZE];
2203 if ((lpval = w32_get_resource (env_vars[i].name, &dwType)) == NULL
2204 /* Also ignore empty environment variables. */
2205 || *lpval == 0)
2207 xfree (lpval);
2208 dont_free = 1;
2209 if (strcmp (env_vars[i].name, "SHELL") == 0)
2211 /* Look for cmdproxy.exe in every directory in
2212 PATH_EXEC. FIXME: This does not find cmdproxy
2213 in nt/ when we run uninstalled. */
2214 char fname[MAX_PATH];
2215 const char *pstart = PATH_EXEC, *pend;
2217 do {
2218 pend = _mbschr (pstart, ';');
2219 if (!pend)
2220 pend = pstart + strlen (pstart);
2221 /* Be defensive against series of ;;; characters. */
2222 if (pend > pstart)
2224 strncpy (fname, pstart, pend - pstart);
2225 fname[pend - pstart] = '/';
2226 strcpy (&fname[pend - pstart + 1], "cmdproxy.exe");
2227 ExpandEnvironmentStrings ((LPSTR) fname, bufc,
2228 sizeof (bufc));
2229 if (faccessat (AT_FDCWD, bufc, F_OK, AT_EACCESS)
2230 == 0)
2232 lpval = bufc;
2233 dwType = REG_SZ;
2234 break;
2237 if (*pend)
2238 pstart = pend + 1;
2239 else
2240 pstart = pend;
2241 if (!*pstart)
2243 /* If not found in any directory, use the
2244 default as the last resort. */
2245 lpval = env_vars[i].def_value;
2246 dwType = REG_EXPAND_SZ;
2248 } while (*pstart);
2250 else
2252 lpval = env_vars[i].def_value;
2253 dwType = REG_EXPAND_SZ;
2255 if (strcmp (env_vars[i].name, "HOME") == 0 && !appdata)
2256 Vdelayed_warnings_list
2257 = Fcons (listn (CONSTYPE_HEAP, 2,
2258 intern ("initialization"),
2259 build_string ("Setting HOME to C:\\ by default is deprecated")),
2260 Vdelayed_warnings_list);
2263 if (lpval)
2265 char buf1[SET_ENV_BUF_SIZE], buf2[SET_ENV_BUF_SIZE];
2267 if (dwType == REG_EXPAND_SZ)
2268 ExpandEnvironmentStrings ((LPSTR) lpval, buf1, sizeof (buf1));
2269 else if (dwType == REG_SZ)
2270 strcpy (buf1, lpval);
2271 if (dwType == REG_EXPAND_SZ || dwType == REG_SZ)
2273 _snprintf (buf2, sizeof (buf2)-1, "%s=%s", env_vars[i].name,
2274 buf1);
2275 _putenv (strdup (buf2));
2278 if (!dont_free)
2279 xfree (lpval);
2285 /* Rebuild system configuration to reflect invoking system. */
2286 Vsystem_configuration = build_string (EMACS_CONFIGURATION);
2288 /* Another special case: on NT, the PATH variable is actually named
2289 "Path" although cmd.exe (perhaps NT itself) arranges for
2290 environment variable lookup and setting to be case insensitive.
2291 However, Emacs assumes a fully case sensitive environment, so we
2292 need to change "Path" to "PATH" to match the expectations of
2293 various elisp packages. We do this by the sneaky method of
2294 modifying the string in the C runtime environ entry.
2296 The same applies to COMSPEC. */
2298 char ** envp;
2300 for (envp = environ; *envp; envp++)
2301 if (_strnicmp (*envp, "PATH=", 5) == 0)
2302 memcpy (*envp, "PATH=", 5);
2303 else if (_strnicmp (*envp, "COMSPEC=", 8) == 0)
2304 memcpy (*envp, "COMSPEC=", 8);
2307 /* Remember the initial working directory for getcwd. */
2308 /* FIXME: Do we need to resolve possible symlinks in startup_dir?
2309 Does it matter anywhere in Emacs? */
2310 if (!GetCurrentDirectory (MAXPATHLEN, startup_dir))
2311 emacs_abort ();
2314 static char modname[MAX_PATH];
2316 if (!GetModuleFileName (NULL, modname, MAX_PATH))
2317 emacs_abort ();
2318 argv[0] = modname;
2321 /* Determine if there is a middle mouse button, to allow parse_button
2322 to decide whether right mouse events should be mouse-2 or
2323 mouse-3. */
2324 w32_num_mouse_buttons = GetSystemMetrics (SM_CMOUSEBUTTONS);
2326 init_user_info ();
2329 /* Called from expand-file-name when default-directory is not a string. */
2331 char *
2332 emacs_root_dir (void)
2334 static char root_dir[FILENAME_MAX];
2335 const char *p;
2337 p = getenv ("emacs_dir");
2338 if (p == NULL)
2339 emacs_abort ();
2340 strcpy (root_dir, p);
2341 root_dir[parse_root (root_dir, NULL)] = '\0';
2342 dostounix_filename (root_dir, 0);
2343 return root_dir;
2346 /* We don't have scripts to automatically determine the system configuration
2347 for Emacs before it's compiled, and we don't want to have to make the
2348 user enter it, so we define EMACS_CONFIGURATION to invoke this runtime
2349 routine. */
2351 char *
2352 get_emacs_configuration (void)
2354 char *arch, *oem, *os;
2355 int build_num;
2356 static char configuration_buffer[32];
2358 /* Determine the processor type. */
2359 switch (get_processor_type ())
2362 #ifdef PROCESSOR_INTEL_386
2363 case PROCESSOR_INTEL_386:
2364 case PROCESSOR_INTEL_486:
2365 case PROCESSOR_INTEL_PENTIUM:
2366 #ifdef _WIN64
2367 arch = "amd64";
2368 #else
2369 arch = "i386";
2370 #endif
2371 break;
2372 #endif
2373 #ifdef PROCESSOR_AMD_X8664
2374 case PROCESSOR_AMD_X8664:
2375 arch = "amd64";
2376 break;
2377 #endif
2379 #ifdef PROCESSOR_MIPS_R2000
2380 case PROCESSOR_MIPS_R2000:
2381 case PROCESSOR_MIPS_R3000:
2382 case PROCESSOR_MIPS_R4000:
2383 arch = "mips";
2384 break;
2385 #endif
2387 #ifdef PROCESSOR_ALPHA_21064
2388 case PROCESSOR_ALPHA_21064:
2389 arch = "alpha";
2390 break;
2391 #endif
2393 default:
2394 arch = "unknown";
2395 break;
2398 /* Use the OEM field to reflect the compiler/library combination. */
2399 #ifdef _MSC_VER
2400 #define COMPILER_NAME "msvc"
2401 #else
2402 #ifdef __GNUC__
2403 #define COMPILER_NAME "mingw"
2404 #else
2405 #define COMPILER_NAME "unknown"
2406 #endif
2407 #endif
2408 oem = COMPILER_NAME;
2410 switch (osinfo_cache.dwPlatformId) {
2411 case VER_PLATFORM_WIN32_NT:
2412 os = "nt";
2413 build_num = osinfo_cache.dwBuildNumber;
2414 break;
2415 case VER_PLATFORM_WIN32_WINDOWS:
2416 if (osinfo_cache.dwMinorVersion == 0) {
2417 os = "windows95";
2418 } else {
2419 os = "windows98";
2421 build_num = LOWORD (osinfo_cache.dwBuildNumber);
2422 break;
2423 case VER_PLATFORM_WIN32s:
2424 /* Not supported, should not happen. */
2425 os = "windows32s";
2426 build_num = LOWORD (osinfo_cache.dwBuildNumber);
2427 break;
2428 default:
2429 os = "unknown";
2430 build_num = 0;
2431 break;
2434 if (osinfo_cache.dwPlatformId == VER_PLATFORM_WIN32_NT) {
2435 sprintf (configuration_buffer, "%s-%s-%s%d.%d.%d", arch, oem, os,
2436 get_w32_major_version (), get_w32_minor_version (), build_num);
2437 } else {
2438 sprintf (configuration_buffer, "%s-%s-%s.%d", arch, oem, os, build_num);
2441 return configuration_buffer;
2444 char *
2445 get_emacs_configuration_options (void)
2447 static char *options_buffer;
2448 char cv[32]; /* Enough for COMPILER_VERSION. */
2449 char *options[] = {
2450 cv, /* To be filled later. */
2451 #ifdef EMACSDEBUG
2452 " --no-opt",
2453 #endif
2454 #ifdef ENABLE_CHECKING
2455 " --enable-checking",
2456 #endif
2457 /* configure.bat already sets USER_CFLAGS and USER_LDFLAGS
2458 with a starting space to save work here. */
2459 #ifdef USER_CFLAGS
2460 " --cflags", USER_CFLAGS,
2461 #endif
2462 #ifdef USER_LDFLAGS
2463 " --ldflags", USER_LDFLAGS,
2464 #endif
2465 NULL
2467 size_t size = 0;
2468 int i;
2470 /* Work out the effective configure options for this build. */
2471 #ifdef _MSC_VER
2472 #define COMPILER_VERSION "--with-msvc (%d.%02d)", _MSC_VER / 100, _MSC_VER % 100
2473 #else
2474 #ifdef __GNUC__
2475 #define COMPILER_VERSION "--with-gcc (%d.%d)", __GNUC__, __GNUC_MINOR__
2476 #else
2477 #define COMPILER_VERSION ""
2478 #endif
2479 #endif
2481 if (_snprintf (cv, sizeof (cv) - 1, COMPILER_VERSION) < 0)
2482 return "Error: not enough space for compiler version";
2483 cv[sizeof (cv) - 1] = '\0';
2485 for (i = 0; options[i]; i++)
2486 size += strlen (options[i]);
2488 options_buffer = xmalloc (size + 1);
2489 options_buffer[0] = '\0';
2491 for (i = 0; options[i]; i++)
2492 strcat (options_buffer, options[i]);
2494 return options_buffer;
2498 #include <sys/timeb.h>
2500 /* Emulate gettimeofday (Ulrich Leodolter, 1/11/95). */
2502 gettimeofday (struct timeval *__restrict tv, struct timezone *__restrict tz)
2504 struct _timeb tb;
2505 _ftime (&tb);
2507 tv->tv_sec = tb.time;
2508 tv->tv_usec = tb.millitm * 1000L;
2509 /* Implementation note: _ftime sometimes doesn't update the dstflag
2510 according to the new timezone when the system timezone is
2511 changed. We could fix that by using GetSystemTime and
2512 GetTimeZoneInformation, but that doesn't seem necessary, since
2513 Emacs always calls gettimeofday with the 2nd argument NULL (see
2514 current_emacs_time). */
2515 if (tz)
2517 tz->tz_minuteswest = tb.timezone; /* minutes west of Greenwich */
2518 tz->tz_dsttime = tb.dstflag; /* type of dst correction */
2520 return 0;
2523 /* Emulate fdutimens. */
2525 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2526 TIMESPEC[0] and TIMESPEC[1], respectively.
2527 FD must be either negative -- in which case it is ignored --
2528 or a file descriptor that is open on FILE.
2529 If FD is nonnegative, then FILE can be NULL, which means
2530 use just futimes instead of utimes.
2531 If TIMESPEC is null, FAIL.
2532 Return 0 on success, -1 (setting errno) on failure. */
2535 fdutimens (int fd, char const *file, struct timespec const timespec[2])
2537 if (!timespec)
2539 errno = ENOSYS;
2540 return -1;
2542 if (fd < 0 && !file)
2544 errno = EBADF;
2545 return -1;
2547 /* _futime's prototype defines 2nd arg as having the type 'struct
2548 _utimbuf', while utime needs to accept 'struct utimbuf' for
2549 compatibility with Posix. So we need to use 2 different (but
2550 equivalent) types to avoid compiler warnings, sigh. */
2551 if (fd >= 0)
2553 struct _utimbuf _ut;
2555 _ut.actime = timespec[0].tv_sec;
2556 _ut.modtime = timespec[1].tv_sec;
2557 return _futime (fd, &_ut);
2559 else
2561 struct utimbuf ut;
2563 ut.actime = timespec[0].tv_sec;
2564 ut.modtime = timespec[1].tv_sec;
2565 /* Call 'utime', which is implemented below, not the MS library
2566 function, which fails on directories. */
2567 return utime (file, &ut);
2572 /* ------------------------------------------------------------------------- */
2573 /* IO support and wrapper functions for the Windows API. */
2574 /* ------------------------------------------------------------------------- */
2576 /* Place a wrapper around the MSVC version of ctime. It returns NULL
2577 on network directories, so we handle that case here.
2578 (Ulrich Leodolter, 1/11/95). */
2579 char *
2580 sys_ctime (const time_t *t)
2582 char *str = (char *) ctime (t);
2583 return (str ? str : "Sun Jan 01 00:00:00 1970");
2586 /* Emulate sleep...we could have done this with a define, but that
2587 would necessitate including windows.h in the files that used it.
2588 This is much easier. */
2589 void
2590 sys_sleep (int seconds)
2592 Sleep (seconds * 1000);
2595 /* Internal MSVC functions for low-level descriptor munging */
2596 extern int __cdecl _set_osfhnd (int fd, long h);
2597 extern int __cdecl _free_osfhnd (int fd);
2599 /* parallel array of private info on file handles */
2600 filedesc fd_info [ MAXDESC ];
2602 typedef struct volume_info_data {
2603 struct volume_info_data * next;
2605 /* time when info was obtained */
2606 DWORD timestamp;
2608 /* actual volume info */
2609 char * root_dir;
2610 DWORD serialnum;
2611 DWORD maxcomp;
2612 DWORD flags;
2613 char * name;
2614 char * type;
2615 } volume_info_data;
2617 /* Global referenced by various functions. */
2618 static volume_info_data volume_info;
2620 /* Vector to indicate which drives are local and fixed (for which cached
2621 data never expires). */
2622 static BOOL fixed_drives[26];
2624 /* Consider cached volume information to be stale if older than 10s,
2625 at least for non-local drives. Info for fixed drives is never stale. */
2626 #define DRIVE_INDEX( c ) ( (c) <= 'Z' ? (c) - 'A' : (c) - 'a' )
2627 #define VOLINFO_STILL_VALID( root_dir, info ) \
2628 ( ( isalpha (root_dir[0]) && \
2629 fixed_drives[ DRIVE_INDEX (root_dir[0]) ] ) \
2630 || GetTickCount () - info->timestamp < 10000 )
2632 /* Cache support functions. */
2634 /* Simple linked list with linear search is sufficient. */
2635 static volume_info_data *volume_cache = NULL;
2637 static volume_info_data *
2638 lookup_volume_info (char * root_dir)
2640 volume_info_data * info;
2642 for (info = volume_cache; info; info = info->next)
2643 if (xstrcasecmp (info->root_dir, root_dir) == 0)
2644 break;
2645 return info;
2648 static void
2649 add_volume_info (char * root_dir, volume_info_data * info)
2651 info->root_dir = xstrdup (root_dir);
2652 info->next = volume_cache;
2653 volume_cache = info;
2657 /* Wrapper for GetVolumeInformation, which uses caching to avoid
2658 performance penalty (~2ms on 486 for local drives, 7.5ms for local
2659 cdrom drive, ~5-10ms or more for remote drives on LAN). */
2660 static volume_info_data *
2661 GetCachedVolumeInformation (char * root_dir)
2663 volume_info_data * info;
2664 char default_root[ MAX_PATH ];
2666 /* NULL for root_dir means use root from current directory. */
2667 if (root_dir == NULL)
2669 if (GetCurrentDirectory (MAX_PATH, default_root) == 0)
2670 return NULL;
2671 parse_root (default_root, &root_dir);
2672 *root_dir = 0;
2673 root_dir = default_root;
2676 /* Local fixed drives can be cached permanently. Removable drives
2677 cannot be cached permanently, since the volume name and serial
2678 number (if nothing else) can change. Remote drives should be
2679 treated as if they are removable, since there is no sure way to
2680 tell whether they are or not. Also, the UNC association of drive
2681 letters mapped to remote volumes can be changed at any time (even
2682 by other processes) without notice.
2684 As a compromise, so we can benefit from caching info for remote
2685 volumes, we use a simple expiry mechanism to invalidate cache
2686 entries that are more than ten seconds old. */
2688 #if 0
2689 /* No point doing this, because WNetGetConnection is even slower than
2690 GetVolumeInformation, consistently taking ~50ms on a 486 (FWIW,
2691 GetDriveType is about the only call of this type which does not
2692 involve network access, and so is extremely quick). */
2694 /* Map drive letter to UNC if remote. */
2695 if (isalpha (root_dir[0]) && !fixed[DRIVE_INDEX (root_dir[0])])
2697 char remote_name[ 256 ];
2698 char drive[3] = { root_dir[0], ':' };
2700 if (WNetGetConnection (drive, remote_name, sizeof (remote_name))
2701 == NO_ERROR)
2702 /* do something */ ;
2704 #endif
2706 info = lookup_volume_info (root_dir);
2708 if (info == NULL || ! VOLINFO_STILL_VALID (root_dir, info))
2710 char name[ 256 ];
2711 DWORD serialnum;
2712 DWORD maxcomp;
2713 DWORD flags;
2714 char type[ 256 ];
2716 /* Info is not cached, or is stale. */
2717 if (!GetVolumeInformation (root_dir,
2718 name, sizeof (name),
2719 &serialnum,
2720 &maxcomp,
2721 &flags,
2722 type, sizeof (type)))
2723 return NULL;
2725 /* Cache the volume information for future use, overwriting existing
2726 entry if present. */
2727 if (info == NULL)
2729 info = xmalloc (sizeof (volume_info_data));
2730 add_volume_info (root_dir, info);
2732 else
2734 xfree (info->name);
2735 xfree (info->type);
2738 info->name = xstrdup (name);
2739 info->serialnum = serialnum;
2740 info->maxcomp = maxcomp;
2741 info->flags = flags;
2742 info->type = xstrdup (type);
2743 info->timestamp = GetTickCount ();
2746 return info;
2749 /* Get information on the volume where NAME is held; set path pointer to
2750 start of pathname in NAME (past UNC header\volume header if present),
2751 if pPath is non-NULL.
2753 Note: if NAME includes symlinks, the information is for the volume
2754 of the symlink, not of its target. That's because, even though
2755 GetVolumeInformation returns information about the symlink target
2756 of its argument, we only pass the root directory to
2757 GetVolumeInformation, not the full NAME. */
2758 static int
2759 get_volume_info (const char * name, const char ** pPath)
2761 char temp[MAX_PATH];
2762 char *rootname = NULL; /* default to current volume */
2763 volume_info_data * info;
2765 if (name == NULL)
2766 return FALSE;
2768 /* Find the root name of the volume if given. */
2769 if (isalpha (name[0]) && name[1] == ':')
2771 rootname = temp;
2772 temp[0] = *name++;
2773 temp[1] = *name++;
2774 temp[2] = '\\';
2775 temp[3] = 0;
2777 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
2779 char *str = temp;
2780 int slashes = 4;
2781 int dbcs_p = max_filename_mbslen () > 1;
2783 rootname = temp;
2786 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
2787 break;
2788 if (!dbcs_p)
2789 *str++ = *name++;
2790 else
2792 const char *p = name;
2794 name = CharNextExA (file_name_codepage, name, 0);
2795 memcpy (str, p, name - p);
2796 str += name - p;
2799 while ( *name );
2801 *str++ = '\\';
2802 *str = 0;
2805 if (pPath)
2806 *pPath = name;
2808 info = GetCachedVolumeInformation (rootname);
2809 if (info != NULL)
2811 /* Set global referenced by other functions. */
2812 volume_info = *info;
2813 return TRUE;
2815 return FALSE;
2818 /* Determine if volume is FAT format (ie. only supports short 8.3
2819 names); also set path pointer to start of pathname in name, if
2820 pPath is non-NULL. */
2821 static int
2822 is_fat_volume (const char * name, const char ** pPath)
2824 if (get_volume_info (name, pPath))
2825 return (volume_info.maxcomp == 12);
2826 return FALSE;
2829 /* Map filename to a valid 8.3 name if necessary.
2830 The result is a pointer to a static buffer, so CAVEAT EMPTOR! */
2831 const char *
2832 map_w32_filename (const char * name, const char ** pPath)
2834 static char shortname[MAX_PATH];
2835 char * str = shortname;
2836 char c;
2837 char * path;
2838 const char * save_name = name;
2840 if (strlen (name) >= MAX_PATH)
2842 /* Return a filename which will cause callers to fail. */
2843 strcpy (shortname, "?");
2844 return shortname;
2847 if (is_fat_volume (name, (const char **)&path)) /* truncate to 8.3 */
2849 register int left = 8; /* maximum number of chars in part */
2850 register int extn = 0; /* extension added? */
2851 register int dots = 2; /* maximum number of dots allowed */
2853 while (name < path)
2854 *str++ = *name++; /* skip past UNC header */
2856 while ((c = *name++))
2858 switch ( c )
2860 case ':':
2861 case '\\':
2862 case '/':
2863 *str++ = (c == ':' ? ':' : '\\');
2864 extn = 0; /* reset extension flags */
2865 dots = 2; /* max 2 dots */
2866 left = 8; /* max length 8 for main part */
2867 break;
2868 case '.':
2869 if ( dots )
2871 /* Convert path components of the form .xxx to _xxx,
2872 but leave . and .. as they are. This allows .emacs
2873 to be read as _emacs, for example. */
2875 if (! *name ||
2876 *name == '.' ||
2877 IS_DIRECTORY_SEP (*name))
2879 *str++ = '.';
2880 dots--;
2882 else
2884 *str++ = '_';
2885 left--;
2886 dots = 0;
2889 else if ( !extn )
2891 *str++ = '.';
2892 extn = 1; /* we've got an extension */
2893 left = 3; /* 3 chars in extension */
2895 else
2897 /* any embedded dots after the first are converted to _ */
2898 *str++ = '_';
2900 break;
2901 case '~':
2902 case '#': /* don't lose these, they're important */
2903 if ( ! left )
2904 str[-1] = c; /* replace last character of part */
2905 /* FALLTHRU */
2906 default:
2907 if ( left )
2909 *str++ = tolower (c); /* map to lower case (looks nicer) */
2910 left--;
2911 dots = 0; /* started a path component */
2913 break;
2916 *str = '\0';
2918 else
2920 strcpy (shortname, name);
2921 unixtodos_filename (shortname);
2924 if (pPath)
2925 *pPath = shortname + (path - save_name);
2927 return shortname;
2930 static int
2931 is_exec (const char * name)
2933 char * p = strrchr (name, '.');
2934 return
2935 (p != NULL
2936 && (xstrcasecmp (p, ".exe") == 0 ||
2937 xstrcasecmp (p, ".com") == 0 ||
2938 xstrcasecmp (p, ".bat") == 0 ||
2939 xstrcasecmp (p, ".cmd") == 0));
2942 /* Emulate the Unix directory procedures opendir, closedir,
2943 and readdir. We can't use the procedures supplied in sysdep.c,
2944 so we provide them here. */
2946 struct dirent dir_static; /* simulated directory contents */
2947 static HANDLE dir_find_handle = INVALID_HANDLE_VALUE;
2948 static int dir_is_fat;
2949 static char dir_pathname[MAXPATHLEN+1];
2950 static WIN32_FIND_DATA dir_find_data;
2952 /* Support shares on a network resource as subdirectories of a read-only
2953 root directory. */
2954 static HANDLE wnet_enum_handle = INVALID_HANDLE_VALUE;
2955 static HANDLE open_unc_volume (const char *);
2956 static char *read_unc_volume (HANDLE, char *, int);
2957 static void close_unc_volume (HANDLE);
2959 DIR *
2960 opendir (const char *filename)
2962 DIR *dirp;
2964 /* Opening is done by FindFirstFile. However, a read is inherent to
2965 this operation, so we defer the open until read time. */
2967 if (dir_find_handle != INVALID_HANDLE_VALUE)
2968 return NULL;
2969 if (wnet_enum_handle != INVALID_HANDLE_VALUE)
2970 return NULL;
2972 /* Note: We don't support traversal of UNC volumes via symlinks.
2973 Doing so would mean punishing 99.99% of use cases by resolving
2974 all the possible symlinks in FILENAME, recursively. */
2975 if (is_unc_volume (filename))
2977 wnet_enum_handle = open_unc_volume (filename);
2978 if (wnet_enum_handle == INVALID_HANDLE_VALUE)
2979 return NULL;
2982 if (!(dirp = (DIR *) malloc (sizeof (DIR))))
2983 return NULL;
2985 dirp->dd_fd = 0;
2986 dirp->dd_loc = 0;
2987 dirp->dd_size = 0;
2989 strncpy (dir_pathname, map_w32_filename (filename, NULL), MAXPATHLEN);
2990 dir_pathname[MAXPATHLEN] = '\0';
2991 /* Note: We don't support symlinks to file names on FAT volumes.
2992 Doing so would mean punishing 99.99% of use cases by resolving
2993 all the possible symlinks in FILENAME, recursively. */
2994 dir_is_fat = is_fat_volume (filename, NULL);
2996 return dirp;
2999 void
3000 closedir (DIR *dirp)
3002 /* If we have a find-handle open, close it. */
3003 if (dir_find_handle != INVALID_HANDLE_VALUE)
3005 FindClose (dir_find_handle);
3006 dir_find_handle = INVALID_HANDLE_VALUE;
3008 else if (wnet_enum_handle != INVALID_HANDLE_VALUE)
3010 close_unc_volume (wnet_enum_handle);
3011 wnet_enum_handle = INVALID_HANDLE_VALUE;
3013 xfree ((char *) dirp);
3016 struct dirent *
3017 readdir (DIR *dirp)
3019 int downcase = !NILP (Vw32_downcase_file_names);
3021 if (wnet_enum_handle != INVALID_HANDLE_VALUE)
3023 if (!read_unc_volume (wnet_enum_handle,
3024 dir_find_data.cFileName,
3025 MAX_PATH))
3026 return NULL;
3028 /* If we aren't dir_finding, do a find-first, otherwise do a find-next. */
3029 else if (dir_find_handle == INVALID_HANDLE_VALUE)
3031 char filename[MAXNAMLEN + 3];
3032 int ln;
3033 int dbcs_p = max_filename_mbslen () > 1;
3035 strcpy (filename, dir_pathname);
3036 ln = strlen (filename) - 1;
3037 if (!dbcs_p)
3039 if (!IS_DIRECTORY_SEP (filename[ln]))
3040 strcat (filename, "\\");
3042 else
3044 char *end = filename + ln + 1;
3045 char *last_char = CharPrevExA (file_name_codepage, filename, end, 0);
3047 if (!IS_DIRECTORY_SEP (*last_char))
3048 strcat (filename, "\\");
3050 strcat (filename, "*");
3052 /* Note: No need to resolve symlinks in FILENAME, because
3053 FindFirst opens the directory that is the target of a
3054 symlink. */
3055 dir_find_handle = FindFirstFile (filename, &dir_find_data);
3057 if (dir_find_handle == INVALID_HANDLE_VALUE)
3058 return NULL;
3060 else
3062 if (!FindNextFile (dir_find_handle, &dir_find_data))
3063 return NULL;
3066 /* Emacs never uses this value, so don't bother making it match
3067 value returned by stat(). */
3068 dir_static.d_ino = 1;
3070 strcpy (dir_static.d_name, dir_find_data.cFileName);
3072 /* If the file name in cFileName[] includes `?' characters, it means
3073 the original file name used characters that cannot be represented
3074 by the current ANSI codepage. To avoid total lossage, retrieve
3075 the short 8+3 alias of the long file name. */
3076 if (_mbspbrk (dir_static.d_name, "?"))
3078 strcpy (dir_static.d_name, dir_find_data.cAlternateFileName);
3079 downcase = 1; /* 8+3 aliases are returned in all caps */
3081 dir_static.d_namlen = strlen (dir_static.d_name);
3082 dir_static.d_reclen = sizeof (struct dirent) - MAXNAMLEN + 3 +
3083 dir_static.d_namlen - dir_static.d_namlen % 4;
3085 /* If the file name in cFileName[] includes `?' characters, it means
3086 the original file name used characters that cannot be represented
3087 by the current ANSI codepage. To avoid total lossage, retrieve
3088 the short 8+3 alias of the long file name. */
3089 if (_mbspbrk (dir_find_data.cFileName, "?"))
3091 strcpy (dir_static.d_name, dir_find_data.cAlternateFileName);
3092 /* 8+3 aliases are returned in all caps, which could break
3093 various alists that look at filenames' extensions. */
3094 downcase = 1;
3096 else
3097 strcpy (dir_static.d_name, dir_find_data.cFileName);
3098 dir_static.d_namlen = strlen (dir_static.d_name);
3099 if (dir_is_fat)
3100 _mbslwr (dir_static.d_name);
3101 else if (downcase)
3103 register char *p;
3104 int dbcs_p = max_filename_mbslen () > 1;
3105 for (p = dir_static.d_name; *p; )
3107 if (*p >= 'a' && *p <= 'z')
3108 break;
3109 if (dbcs_p)
3110 p = CharNextExA (file_name_codepage, p, 0);
3111 else
3112 p++;
3114 if (!*p)
3115 _mbslwr (dir_static.d_name);
3118 return &dir_static;
3121 static HANDLE
3122 open_unc_volume (const char *path)
3124 NETRESOURCE nr;
3125 HANDLE henum;
3126 int result;
3128 nr.dwScope = RESOURCE_GLOBALNET;
3129 nr.dwType = RESOURCETYPE_DISK;
3130 nr.dwDisplayType = RESOURCEDISPLAYTYPE_SERVER;
3131 nr.dwUsage = RESOURCEUSAGE_CONTAINER;
3132 nr.lpLocalName = NULL;
3133 nr.lpRemoteName = (LPSTR)map_w32_filename (path, NULL);
3134 nr.lpComment = NULL;
3135 nr.lpProvider = NULL;
3137 result = WNetOpenEnum (RESOURCE_GLOBALNET, RESOURCETYPE_DISK,
3138 RESOURCEUSAGE_CONNECTABLE, &nr, &henum);
3140 if (result == NO_ERROR)
3141 return henum;
3142 else
3143 return INVALID_HANDLE_VALUE;
3146 static char *
3147 read_unc_volume (HANDLE henum, char *readbuf, int size)
3149 DWORD count;
3150 int result;
3151 DWORD bufsize = 512;
3152 char *buffer;
3153 char *ptr;
3154 int dbcs_p = max_filename_mbslen () > 1;
3156 count = 1;
3157 buffer = alloca (bufsize);
3158 result = WNetEnumResource (henum, &count, buffer, &bufsize);
3159 if (result != NO_ERROR)
3160 return NULL;
3162 /* WNetEnumResource returns \\resource\share...skip forward to "share". */
3163 ptr = ((LPNETRESOURCE) buffer)->lpRemoteName;
3164 ptr += 2;
3165 if (!dbcs_p)
3166 while (*ptr && !IS_DIRECTORY_SEP (*ptr)) ptr++;
3167 else
3169 while (*ptr && !IS_DIRECTORY_SEP (*ptr))
3170 ptr = CharNextExA (file_name_codepage, ptr, 0);
3172 ptr++;
3174 strncpy (readbuf, ptr, size);
3175 return readbuf;
3178 static void
3179 close_unc_volume (HANDLE henum)
3181 if (henum != INVALID_HANDLE_VALUE)
3182 WNetCloseEnum (henum);
3185 static DWORD
3186 unc_volume_file_attributes (const char *path)
3188 HANDLE henum;
3189 DWORD attrs;
3191 henum = open_unc_volume (path);
3192 if (henum == INVALID_HANDLE_VALUE)
3193 return -1;
3195 attrs = FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_DIRECTORY;
3197 close_unc_volume (henum);
3199 return attrs;
3202 /* Ensure a network connection is authenticated. */
3203 static void
3204 logon_network_drive (const char *path)
3206 NETRESOURCE resource;
3207 char share[MAX_PATH];
3208 int n_slashes;
3209 char drive[4];
3210 UINT drvtype;
3211 char *p;
3212 int dbcs_p;
3214 if (IS_DIRECTORY_SEP (path[0]) && IS_DIRECTORY_SEP (path[1]))
3215 drvtype = DRIVE_REMOTE;
3216 else if (path[0] == '\0' || path[1] != ':')
3217 drvtype = GetDriveType (NULL);
3218 else
3220 drive[0] = path[0];
3221 drive[1] = ':';
3222 drive[2] = '\\';
3223 drive[3] = '\0';
3224 drvtype = GetDriveType (drive);
3227 /* Only logon to networked drives. */
3228 if (drvtype != DRIVE_REMOTE)
3229 return;
3231 n_slashes = 2;
3232 strncpy (share, path, MAX_PATH);
3233 /* Truncate to just server and share name. */
3234 dbcs_p = max_filename_mbslen () > 1;
3235 for (p = share + 2; *p && p < share + MAX_PATH; )
3237 if (IS_DIRECTORY_SEP (*p) && ++n_slashes > 3)
3239 *p = '\0';
3240 break;
3242 if (dbcs_p)
3243 p = CharNextExA (file_name_codepage, p, 0);
3244 else
3245 p++;
3248 resource.dwType = RESOURCETYPE_DISK;
3249 resource.lpLocalName = NULL;
3250 resource.lpRemoteName = share;
3251 resource.lpProvider = NULL;
3253 WNetAddConnection2 (&resource, NULL, NULL, CONNECT_INTERACTIVE);
3256 /* Emulate faccessat(2). */
3258 faccessat (int dirfd, const char * path, int mode, int flags)
3260 DWORD attributes;
3262 if (dirfd != AT_FDCWD
3263 && !(IS_DIRECTORY_SEP (path[0])
3264 || IS_DEVICE_SEP (path[1])))
3266 errno = EBADF;
3267 return -1;
3270 /* MSVCRT implementation of 'access' doesn't recognize D_OK, and its
3271 newer versions blow up when passed D_OK. */
3272 path = map_w32_filename (path, NULL);
3273 /* If the last element of PATH is a symlink, we need to resolve it
3274 to get the attributes of its target file. Note: any symlinks in
3275 PATH elements other than the last one are transparently resolved
3276 by GetFileAttributes below. */
3277 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0
3278 && (flags & AT_SYMLINK_NOFOLLOW) == 0)
3279 path = chase_symlinks (path);
3281 if ((attributes = GetFileAttributes (path)) == -1)
3283 DWORD w32err = GetLastError ();
3285 switch (w32err)
3287 case ERROR_INVALID_NAME:
3288 case ERROR_BAD_PATHNAME:
3289 if (is_unc_volume (path))
3291 attributes = unc_volume_file_attributes (path);
3292 if (attributes == -1)
3294 errno = EACCES;
3295 return -1;
3297 break;
3299 /* FALLTHROUGH */
3300 case ERROR_FILE_NOT_FOUND:
3301 case ERROR_BAD_NETPATH:
3302 errno = ENOENT;
3303 break;
3304 default:
3305 errno = EACCES;
3306 break;
3308 return -1;
3310 if ((mode & X_OK) != 0
3311 && !(is_exec (path) || (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0))
3313 errno = EACCES;
3314 return -1;
3316 if ((mode & W_OK) != 0 && (attributes & FILE_ATTRIBUTE_READONLY) != 0)
3318 errno = EACCES;
3319 return -1;
3321 if ((mode & D_OK) != 0 && (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
3323 errno = EACCES;
3324 return -1;
3326 return 0;
3329 /* Shadow some MSVC runtime functions to map requests for long filenames
3330 to reasonable short names if necessary. This was originally added to
3331 permit running Emacs on NT 3.1 on a FAT partition, which doesn't support
3332 long file names. */
3335 sys_chdir (const char * path)
3337 return _chdir (map_w32_filename (path, NULL));
3341 sys_chmod (const char * path, int mode)
3343 path = chase_symlinks (map_w32_filename (path, NULL));
3344 return _chmod (path, mode);
3348 sys_creat (const char * path, int mode)
3350 return _creat (map_w32_filename (path, NULL), mode);
3353 FILE *
3354 sys_fopen (const char * path, const char * mode)
3356 int fd;
3357 int oflag;
3358 const char * mode_save = mode;
3360 /* Force all file handles to be non-inheritable. This is necessary to
3361 ensure child processes don't unwittingly inherit handles that might
3362 prevent future file access. */
3364 if (mode[0] == 'r')
3365 oflag = O_RDONLY;
3366 else if (mode[0] == 'w' || mode[0] == 'a')
3367 oflag = O_WRONLY | O_CREAT | O_TRUNC;
3368 else
3369 return NULL;
3371 /* Only do simplistic option parsing. */
3372 while (*++mode)
3373 if (mode[0] == '+')
3375 oflag &= ~(O_RDONLY | O_WRONLY);
3376 oflag |= O_RDWR;
3378 else if (mode[0] == 'b')
3380 oflag &= ~O_TEXT;
3381 oflag |= O_BINARY;
3383 else if (mode[0] == 't')
3385 oflag &= ~O_BINARY;
3386 oflag |= O_TEXT;
3388 else break;
3390 fd = _open (map_w32_filename (path, NULL), oflag | _O_NOINHERIT, 0644);
3391 if (fd < 0)
3392 return NULL;
3394 return _fdopen (fd, mode_save);
3397 /* This only works on NTFS volumes, but is useful to have. */
3399 sys_link (const char * old, const char * new)
3401 HANDLE fileh;
3402 int result = -1;
3403 char oldname[MAX_PATH], newname[MAX_PATH];
3405 if (old == NULL || new == NULL)
3407 errno = ENOENT;
3408 return -1;
3411 strcpy (oldname, map_w32_filename (old, NULL));
3412 strcpy (newname, map_w32_filename (new, NULL));
3414 fileh = CreateFile (oldname, 0, 0, NULL, OPEN_EXISTING,
3415 FILE_FLAG_BACKUP_SEMANTICS, NULL);
3416 if (fileh != INVALID_HANDLE_VALUE)
3418 int wlen;
3420 /* Confusingly, the "alternate" stream name field does not apply
3421 when restoring a hard link, and instead contains the actual
3422 stream data for the link (ie. the name of the link to create).
3423 The WIN32_STREAM_ID structure before the cStreamName field is
3424 the stream header, which is then immediately followed by the
3425 stream data. */
3427 struct {
3428 WIN32_STREAM_ID wid;
3429 WCHAR wbuffer[MAX_PATH]; /* extra space for link name */
3430 } data;
3432 wlen = MultiByteToWideChar (CP_ACP, MB_PRECOMPOSED, newname, -1,
3433 data.wid.cStreamName, MAX_PATH);
3434 if (wlen > 0)
3436 LPVOID context = NULL;
3437 DWORD wbytes = 0;
3439 data.wid.dwStreamId = BACKUP_LINK;
3440 data.wid.dwStreamAttributes = 0;
3441 data.wid.Size.LowPart = wlen * sizeof (WCHAR);
3442 data.wid.Size.HighPart = 0;
3443 data.wid.dwStreamNameSize = 0;
3445 if (BackupWrite (fileh, (LPBYTE)&data,
3446 offsetof (WIN32_STREAM_ID, cStreamName)
3447 + data.wid.Size.LowPart,
3448 &wbytes, FALSE, FALSE, &context)
3449 && BackupWrite (fileh, NULL, 0, &wbytes, TRUE, FALSE, &context))
3451 /* succeeded */
3452 result = 0;
3454 else
3456 /* Should try mapping GetLastError to errno; for now just
3457 indicate a general error (eg. links not supported). */
3458 errno = EINVAL; // perhaps EMLINK?
3462 CloseHandle (fileh);
3464 else
3465 errno = ENOENT;
3467 return result;
3471 sys_mkdir (const char * path)
3473 return _mkdir (map_w32_filename (path, NULL));
3477 sys_open (const char * path, int oflag, int mode)
3479 const char* mpath = map_w32_filename (path, NULL);
3480 int res = -1;
3482 /* If possible, try to open file without _O_CREAT, to be able to
3483 write to existing hidden and system files. Force all file
3484 handles to be non-inheritable. */
3485 if ((oflag & (_O_CREAT | _O_EXCL)) != (_O_CREAT | _O_EXCL))
3486 res = _open (mpath, (oflag & ~_O_CREAT) | _O_NOINHERIT, mode);
3487 if (res < 0)
3488 res = _open (mpath, oflag | _O_NOINHERIT, mode);
3490 return res;
3493 /* Implementation of mkostemp for MS-Windows, to avoid race conditions
3494 when using mktemp.
3496 Standard algorithm for generating a temporary file name seems to be
3497 use pid or tid with a letter on the front (in place of the 6 X's)
3498 and cycle through the letters to find a unique name. We extend
3499 that to allow any reasonable character as the first of the 6 X's,
3500 so that the number of simultaneously used temporary files will be
3501 greater. */
3504 mkostemp (char * template, int flags)
3506 char * p;
3507 int i, fd = -1;
3508 unsigned uid = GetCurrentThreadId ();
3509 int save_errno = errno;
3510 static char first_char[] = "abcdefghijklmnopqrstuvwyz0123456789!%-_@#";
3512 errno = EINVAL;
3513 if (template == NULL)
3514 return -1;
3516 p = template + strlen (template);
3517 i = 5;
3518 /* replace up to the last 5 X's with uid in decimal */
3519 while (--p >= template && p[0] == 'X' && --i >= 0)
3521 p[0] = '0' + uid % 10;
3522 uid /= 10;
3525 if (i < 0 && p[0] == 'X')
3527 i = 0;
3530 p[0] = first_char[i];
3531 if ((fd = sys_open (template,
3532 flags | _O_CREAT | _O_EXCL | _O_RDWR,
3533 S_IRUSR | S_IWUSR)) >= 0
3534 || errno != EEXIST)
3536 if (fd >= 0)
3537 errno = save_errno;
3538 return fd;
3541 while (++i < sizeof (first_char));
3544 /* Template is badly formed or else we can't generate a unique name. */
3545 return -1;
3549 fchmod (int fd, mode_t mode)
3551 return 0;
3555 sys_rename_replace (const char *oldname, const char *newname, BOOL force)
3557 BOOL result;
3558 char temp[MAX_PATH];
3559 int newname_dev;
3560 int oldname_dev;
3562 /* MoveFile on Windows 95 doesn't correctly change the short file name
3563 alias in a number of circumstances (it is not easy to predict when
3564 just by looking at oldname and newname, unfortunately). In these
3565 cases, renaming through a temporary name avoids the problem.
3567 A second problem on Windows 95 is that renaming through a temp name when
3568 newname is uppercase fails (the final long name ends up in
3569 lowercase, although the short alias might be uppercase) UNLESS the
3570 long temp name is not 8.3.
3572 So, on Windows 95 we always rename through a temp name, and we make sure
3573 the temp name has a long extension to ensure correct renaming. */
3575 strcpy (temp, map_w32_filename (oldname, NULL));
3577 /* volume_info is set indirectly by map_w32_filename. */
3578 oldname_dev = volume_info.serialnum;
3580 if (os_subtype == OS_9X)
3582 char * o;
3583 char * p;
3584 int i = 0;
3586 oldname = map_w32_filename (oldname, NULL);
3587 if ((o = strrchr (oldname, '\\')))
3588 o++;
3589 else
3590 o = (char *) oldname;
3592 if ((p = strrchr (temp, '\\')))
3593 p++;
3594 else
3595 p = temp;
3599 /* Force temp name to require a manufactured 8.3 alias - this
3600 seems to make the second rename work properly. */
3601 sprintf (p, "_.%s.%u", o, i);
3602 i++;
3603 result = rename (oldname, temp);
3605 /* This loop must surely terminate! */
3606 while (result < 0 && errno == EEXIST);
3607 if (result < 0)
3608 return -1;
3611 /* If FORCE, emulate Unix behavior - newname is deleted if it already exists
3612 (at least if it is a file; don't do this for directories).
3614 Since we mustn't do this if we are just changing the case of the
3615 file name (we would end up deleting the file we are trying to
3616 rename!), we let rename detect if the destination file already
3617 exists - that way we avoid the possible pitfalls of trying to
3618 determine ourselves whether two names really refer to the same
3619 file, which is not always possible in the general case. (Consider
3620 all the permutations of shared or subst'd drives, etc.) */
3622 newname = map_w32_filename (newname, NULL);
3624 /* volume_info is set indirectly by map_w32_filename. */
3625 newname_dev = volume_info.serialnum;
3627 result = rename (temp, newname);
3629 if (result < 0 && force)
3631 DWORD w32err = GetLastError ();
3633 if (errno == EACCES
3634 && newname_dev != oldname_dev)
3636 /* The implementation of `rename' on Windows does not return
3637 errno = EXDEV when you are moving a directory to a
3638 different storage device (ex. logical disk). It returns
3639 EACCES instead. So here we handle such situations and
3640 return EXDEV. */
3641 DWORD attributes;
3643 if ((attributes = GetFileAttributes (temp)) != -1
3644 && (attributes & FILE_ATTRIBUTE_DIRECTORY))
3645 errno = EXDEV;
3647 else if (errno == EEXIST)
3649 if (_chmod (newname, 0666) != 0)
3650 return result;
3651 if (_unlink (newname) != 0)
3652 return result;
3653 result = rename (temp, newname);
3655 else if (w32err == ERROR_PRIVILEGE_NOT_HELD
3656 && is_symlink (temp))
3658 /* This is Windows prohibiting the user from creating a
3659 symlink in another place, since that requires
3660 privileges. */
3661 errno = EPERM;
3665 return result;
3669 sys_rename (char const *old, char const *new)
3671 return sys_rename_replace (old, new, TRUE);
3675 sys_rmdir (const char * path)
3677 return _rmdir (map_w32_filename (path, NULL));
3681 sys_unlink (const char * path)
3683 path = map_w32_filename (path, NULL);
3685 /* On Unix, unlink works without write permission. */
3686 _chmod (path, 0666);
3687 return _unlink (path);
3690 static FILETIME utc_base_ft;
3691 static ULONGLONG utc_base; /* In 100ns units */
3692 static int init = 0;
3694 #define FILETIME_TO_U64(result, ft) \
3695 do { \
3696 ULARGE_INTEGER uiTemp; \
3697 uiTemp.LowPart = (ft).dwLowDateTime; \
3698 uiTemp.HighPart = (ft).dwHighDateTime; \
3699 result = uiTemp.QuadPart; \
3700 } while (0)
3702 static void
3703 initialize_utc_base (void)
3705 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
3706 SYSTEMTIME st;
3708 st.wYear = 1970;
3709 st.wMonth = 1;
3710 st.wDay = 1;
3711 st.wHour = 0;
3712 st.wMinute = 0;
3713 st.wSecond = 0;
3714 st.wMilliseconds = 0;
3716 SystemTimeToFileTime (&st, &utc_base_ft);
3717 FILETIME_TO_U64 (utc_base, utc_base_ft);
3720 static time_t
3721 convert_time (FILETIME ft)
3723 ULONGLONG tmp;
3725 if (!init)
3727 initialize_utc_base ();
3728 init = 1;
3731 if (CompareFileTime (&ft, &utc_base_ft) < 0)
3732 return 0;
3734 FILETIME_TO_U64 (tmp, ft);
3735 return (time_t) ((tmp - utc_base) / 10000000L);
3738 static void
3739 convert_from_time_t (time_t time, FILETIME * pft)
3741 ULARGE_INTEGER tmp;
3743 if (!init)
3745 initialize_utc_base ();
3746 init = 1;
3749 /* time in 100ns units since 1-Jan-1601 */
3750 tmp.QuadPart = (ULONGLONG) time * 10000000L + utc_base;
3751 pft->dwHighDateTime = tmp.HighPart;
3752 pft->dwLowDateTime = tmp.LowPart;
3755 #if 0
3756 /* No reason to keep this; faking inode values either by hashing or even
3757 using the file index from GetInformationByHandle, is not perfect and
3758 so by default Emacs doesn't use the inode values on Windows.
3759 Instead, we now determine file-truename correctly (except for
3760 possible drive aliasing etc). */
3762 /* Modified version of "PJW" algorithm (see the "Dragon" compiler book). */
3763 static unsigned
3764 hashval (const unsigned char * str)
3766 unsigned h = 0;
3767 while (*str)
3769 h = (h << 4) + *str++;
3770 h ^= (h >> 28);
3772 return h;
3775 /* Return the hash value of the canonical pathname, excluding the
3776 drive/UNC header, to get a hopefully unique inode number. */
3777 static DWORD
3778 generate_inode_val (const char * name)
3780 char fullname[ MAX_PATH ];
3781 char * p;
3782 unsigned hash;
3784 /* Get the truly canonical filename, if it exists. (Note: this
3785 doesn't resolve aliasing due to subst commands, or recognize hard
3786 links. */
3787 if (!w32_get_long_filename ((char *)name, fullname, MAX_PATH))
3788 emacs_abort ();
3790 parse_root (fullname, &p);
3791 /* Normal W32 filesystems are still case insensitive. */
3792 _strlwr (p);
3793 return hashval (p);
3796 #endif
3798 static PSECURITY_DESCRIPTOR
3799 get_file_security_desc_by_handle (HANDLE h)
3801 PSECURITY_DESCRIPTOR psd = NULL;
3802 DWORD err;
3803 SECURITY_INFORMATION si = OWNER_SECURITY_INFORMATION
3804 | GROUP_SECURITY_INFORMATION /* | DACL_SECURITY_INFORMATION */ ;
3806 err = get_security_info (h, SE_FILE_OBJECT, si,
3807 NULL, NULL, NULL, NULL, &psd);
3808 if (err != ERROR_SUCCESS)
3809 return NULL;
3811 return psd;
3814 static PSECURITY_DESCRIPTOR
3815 get_file_security_desc_by_name (const char *fname)
3817 PSECURITY_DESCRIPTOR psd = NULL;
3818 DWORD sd_len, err;
3819 SECURITY_INFORMATION si = OWNER_SECURITY_INFORMATION
3820 | GROUP_SECURITY_INFORMATION /* | DACL_SECURITY_INFORMATION */ ;
3822 if (!get_file_security (fname, si, psd, 0, &sd_len))
3824 err = GetLastError ();
3825 if (err != ERROR_INSUFFICIENT_BUFFER)
3826 return NULL;
3829 psd = xmalloc (sd_len);
3830 if (!get_file_security (fname, si, psd, sd_len, &sd_len))
3832 xfree (psd);
3833 return NULL;
3836 return psd;
3839 static DWORD
3840 get_rid (PSID sid)
3842 unsigned n_subauthorities;
3844 /* Use the last sub-authority value of the RID, the relative
3845 portion of the SID, as user/group ID. */
3846 n_subauthorities = *get_sid_sub_authority_count (sid);
3847 if (n_subauthorities < 1)
3848 return 0; /* the "World" RID */
3849 return *get_sid_sub_authority (sid, n_subauthorities - 1);
3852 /* Caching SID and account values for faster lokup. */
3854 struct w32_id {
3855 unsigned rid;
3856 struct w32_id *next;
3857 char name[GNLEN+1];
3858 unsigned char sid[FLEXIBLE_ARRAY_MEMBER];
3861 static struct w32_id *w32_idlist;
3863 static int
3864 w32_cached_id (PSID sid, unsigned *id, char *name)
3866 struct w32_id *tail, *found;
3868 for (found = NULL, tail = w32_idlist; tail; tail = tail->next)
3870 if (equal_sid ((PSID)tail->sid, sid))
3872 found = tail;
3873 break;
3876 if (found)
3878 *id = found->rid;
3879 strcpy (name, found->name);
3880 return 1;
3882 else
3883 return 0;
3886 static void
3887 w32_add_to_cache (PSID sid, unsigned id, char *name)
3889 DWORD sid_len;
3890 struct w32_id *new_entry;
3892 /* We don't want to leave behind stale cache from when Emacs was
3893 dumped. */
3894 if (initialized)
3896 sid_len = get_length_sid (sid);
3897 new_entry = xmalloc (offsetof (struct w32_id, sid) + sid_len);
3898 if (new_entry)
3900 new_entry->rid = id;
3901 strcpy (new_entry->name, name);
3902 copy_sid (sid_len, (PSID)new_entry->sid, sid);
3903 new_entry->next = w32_idlist;
3904 w32_idlist = new_entry;
3909 #define UID 1
3910 #define GID 2
3912 static int
3913 get_name_and_id (PSECURITY_DESCRIPTOR psd, unsigned *id, char *nm, int what)
3915 PSID sid = NULL;
3916 BOOL dflt;
3917 SID_NAME_USE ignore;
3918 char name[UNLEN+1];
3919 DWORD name_len = sizeof (name);
3920 char domain[1024];
3921 DWORD domain_len = sizeof (domain);
3922 int use_dflt = 0;
3923 int result;
3925 if (what == UID)
3926 result = get_security_descriptor_owner (psd, &sid, &dflt);
3927 else if (what == GID)
3928 result = get_security_descriptor_group (psd, &sid, &dflt);
3929 else
3930 result = 0;
3932 if (!result || !is_valid_sid (sid))
3933 use_dflt = 1;
3934 else if (!w32_cached_id (sid, id, nm))
3936 if (!lookup_account_sid (NULL, sid, name, &name_len,
3937 domain, &domain_len, &ignore)
3938 || name_len > UNLEN+1)
3939 use_dflt = 1;
3940 else
3942 *id = get_rid (sid);
3943 strcpy (nm, name);
3944 w32_add_to_cache (sid, *id, name);
3947 return use_dflt;
3950 static void
3951 get_file_owner_and_group (PSECURITY_DESCRIPTOR psd, struct stat *st)
3953 int dflt_usr = 0, dflt_grp = 0;
3955 if (!psd)
3957 dflt_usr = 1;
3958 dflt_grp = 1;
3960 else
3962 if (get_name_and_id (psd, &st->st_uid, st->st_uname, UID))
3963 dflt_usr = 1;
3964 if (get_name_and_id (psd, &st->st_gid, st->st_gname, GID))
3965 dflt_grp = 1;
3967 /* Consider files to belong to current user/group, if we cannot get
3968 more accurate information. */
3969 if (dflt_usr)
3971 st->st_uid = dflt_passwd.pw_uid;
3972 strcpy (st->st_uname, dflt_passwd.pw_name);
3974 if (dflt_grp)
3976 st->st_gid = dflt_passwd.pw_gid;
3977 strcpy (st->st_gname, dflt_group.gr_name);
3981 /* Return non-zero if NAME is a potentially slow filesystem. */
3983 is_slow_fs (const char *name)
3985 char drive_root[4];
3986 UINT devtype;
3988 if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
3989 devtype = DRIVE_REMOTE; /* assume UNC name is remote */
3990 else if (!(strlen (name) >= 2 && IS_DEVICE_SEP (name[1])))
3991 devtype = GetDriveType (NULL); /* use root of current drive */
3992 else
3994 /* GetDriveType needs the root directory of the drive. */
3995 strncpy (drive_root, name, 2);
3996 drive_root[2] = '\\';
3997 drive_root[3] = '\0';
3998 devtype = GetDriveType (drive_root);
4000 return !(devtype == DRIVE_FIXED || devtype == DRIVE_RAMDISK);
4003 /* If this is non-zero, the caller wants accurate information about
4004 file's owner and group, which could be expensive to get. */
4005 int w32_stat_get_owner_group;
4007 /* MSVC stat function can't cope with UNC names and has other bugs, so
4008 replace it with our own. This also allows us to calculate consistent
4009 inode values and owner/group without hacks in the main Emacs code. */
4011 static int
4012 stat_worker (const char * path, struct stat * buf, int follow_symlinks)
4014 char *name, *save_name, *r;
4015 WIN32_FIND_DATA wfd;
4016 HANDLE fh;
4017 unsigned __int64 fake_inode = 0;
4018 int permission;
4019 int len;
4020 int rootdir = FALSE;
4021 PSECURITY_DESCRIPTOR psd = NULL;
4022 int is_a_symlink = 0;
4023 DWORD file_flags = FILE_FLAG_BACKUP_SEMANTICS;
4024 DWORD access_rights = 0;
4025 DWORD fattrs = 0, serialnum = 0, fs_high = 0, fs_low = 0, nlinks = 1;
4026 FILETIME ctime, atime, wtime;
4027 int dbcs_p;
4029 if (path == NULL || buf == NULL)
4031 errno = EFAULT;
4032 return -1;
4035 save_name = name = (char *) map_w32_filename (path, &path);
4036 /* Must be valid filename, no wild cards or other invalid
4037 characters. We use _mbspbrk to support multibyte strings that
4038 might look to strpbrk as if they included literal *, ?, and other
4039 characters mentioned below that are disallowed by Windows
4040 filesystems. */
4041 if (_mbspbrk (name, "*?|<>\""))
4043 errno = ENOENT;
4044 return -1;
4047 /* Remove trailing directory separator, unless name is the root
4048 directory of a drive or UNC volume in which case ensure there
4049 is a trailing separator. */
4050 len = strlen (name);
4051 name = strcpy (alloca (len + 2), name);
4053 /* Avoid a somewhat costly call to is_symlink if the filesystem
4054 doesn't support symlinks. */
4055 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
4056 is_a_symlink = is_symlink (name);
4058 /* Plan A: Open the file and get all the necessary information via
4059 the resulting handle. This solves several issues in one blow:
4061 . retrieves attributes for the target of a symlink, if needed
4062 . gets attributes of root directories and symlinks pointing to
4063 root directories, thus avoiding the need for special-casing
4064 these and detecting them by examining the file-name format
4065 . retrieves more accurate attributes (e.g., non-zero size for
4066 some directories, esp. directories that are junction points)
4067 . correctly resolves "c:/..", "/.." and similar file names
4068 . avoids run-time penalties for 99% of use cases
4070 Plan A is always tried first, unless the user asked not to (but
4071 if the file is a symlink and we need to follow links, we try Plan
4072 A even if the user asked not to).
4074 If Plan A fails, we go to Plan B (below), where various
4075 potentially expensive techniques must be used to handle "special"
4076 files such as UNC volumes etc. */
4077 if (!(NILP (Vw32_get_true_file_attributes)
4078 || (EQ (Vw32_get_true_file_attributes, Qlocal) && is_slow_fs (name)))
4079 /* Following symlinks requires getting the info by handle. */
4080 || (is_a_symlink && follow_symlinks))
4082 BY_HANDLE_FILE_INFORMATION info;
4084 if (is_a_symlink && !follow_symlinks)
4085 file_flags |= FILE_FLAG_OPEN_REPARSE_POINT;
4086 /* READ_CONTROL access rights are required to get security info
4087 by handle. But if the OS doesn't support security in the
4088 first place, we don't need to try. */
4089 if (is_windows_9x () != TRUE)
4090 access_rights |= READ_CONTROL;
4092 fh = CreateFile (name, access_rights, 0, NULL, OPEN_EXISTING,
4093 file_flags, NULL);
4094 /* If CreateFile fails with READ_CONTROL, try again with zero as
4095 access rights. */
4096 if (fh == INVALID_HANDLE_VALUE && access_rights)
4097 fh = CreateFile (name, 0, 0, NULL, OPEN_EXISTING,
4098 file_flags, NULL);
4099 if (fh == INVALID_HANDLE_VALUE)
4100 goto no_true_file_attributes;
4102 /* This is more accurate in terms of getting the correct number
4103 of links, but is quite slow (it is noticeable when Emacs is
4104 making a list of file name completions). */
4105 if (GetFileInformationByHandle (fh, &info))
4107 nlinks = info.nNumberOfLinks;
4108 /* Might as well use file index to fake inode values, but this
4109 is not guaranteed to be unique unless we keep a handle open
4110 all the time (even then there are situations where it is
4111 not unique). Reputedly, there are at most 48 bits of info
4112 (on NTFS, presumably less on FAT). */
4113 fake_inode = info.nFileIndexHigh;
4114 fake_inode <<= 32;
4115 fake_inode += info.nFileIndexLow;
4116 serialnum = info.dwVolumeSerialNumber;
4117 fs_high = info.nFileSizeHigh;
4118 fs_low = info.nFileSizeLow;
4119 ctime = info.ftCreationTime;
4120 atime = info.ftLastAccessTime;
4121 wtime = info.ftLastWriteTime;
4122 fattrs = info.dwFileAttributes;
4124 else
4126 /* We don't go to Plan B here, because it's not clear that
4127 it's a good idea. The only known use case where
4128 CreateFile succeeds, but GetFileInformationByHandle fails
4129 (with ERROR_INVALID_FUNCTION) is for character devices
4130 such as NUL, PRN, etc. For these, switching to Plan B is
4131 a net loss, because we lose the character device
4132 attribute returned by GetFileType below (FindFirstFile
4133 doesn't set that bit in the attributes), and the other
4134 fields don't make sense for character devices anyway.
4135 Emacs doesn't really care for non-file entities in the
4136 context of l?stat, so neither do we. */
4138 /* w32err is assigned so one could put a breakpoint here and
4139 examine its value, when GetFileInformationByHandle
4140 fails. */
4141 DWORD w32err = GetLastError ();
4143 switch (w32err)
4145 case ERROR_FILE_NOT_FOUND: /* can this ever happen? */
4146 errno = ENOENT;
4147 return -1;
4151 /* Test for a symlink before testing for a directory, since
4152 symlinks to directories have the directory bit set, but we
4153 don't want them to appear as directories. */
4154 if (is_a_symlink && !follow_symlinks)
4155 buf->st_mode = S_IFLNK;
4156 else if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
4157 buf->st_mode = S_IFDIR;
4158 else
4160 DWORD ftype = GetFileType (fh);
4162 switch (ftype)
4164 case FILE_TYPE_DISK:
4165 buf->st_mode = S_IFREG;
4166 break;
4167 case FILE_TYPE_PIPE:
4168 buf->st_mode = S_IFIFO;
4169 break;
4170 case FILE_TYPE_CHAR:
4171 case FILE_TYPE_UNKNOWN:
4172 default:
4173 buf->st_mode = S_IFCHR;
4176 /* We produce the fallback owner and group data, based on the
4177 current user that runs Emacs, in the following cases:
4179 . caller didn't request owner and group info
4180 . this is Windows 9X
4181 . getting security by handle failed, and we need to produce
4182 information for the target of a symlink (this is better
4183 than producing a potentially misleading info about the
4184 symlink itself)
4186 If getting security by handle fails, and we don't need to
4187 resolve symlinks, we try getting security by name. */
4188 if (!w32_stat_get_owner_group || is_windows_9x () == TRUE)
4189 get_file_owner_and_group (NULL, buf);
4190 else
4192 psd = get_file_security_desc_by_handle (fh);
4193 if (psd)
4195 get_file_owner_and_group (psd, buf);
4196 LocalFree (psd);
4198 else if (!(is_a_symlink && follow_symlinks))
4200 psd = get_file_security_desc_by_name (name);
4201 get_file_owner_and_group (psd, buf);
4202 xfree (psd);
4204 else
4205 get_file_owner_and_group (NULL, buf);
4207 CloseHandle (fh);
4209 else
4211 no_true_file_attributes:
4212 /* Plan B: Either getting a handle on the file failed, or the
4213 caller explicitly asked us to not bother making this
4214 information more accurate.
4216 Implementation note: In Plan B, we never bother to resolve
4217 symlinks, even if we got here because we tried Plan A and
4218 failed. That's because, even if the caller asked for extra
4219 precision by setting Vw32_get_true_file_attributes to t,
4220 resolving symlinks requires acquiring a file handle to the
4221 symlink, which we already know will fail. And if the user
4222 did not ask for extra precision, resolving symlinks will fly
4223 in the face of that request, since the user then wants the
4224 lightweight version of the code. */
4225 dbcs_p = max_filename_mbslen () > 1;
4226 rootdir = (path >= save_name + len - 1
4227 && (IS_DIRECTORY_SEP (*path) || *path == 0));
4229 /* If name is "c:/.." or "/.." then stat "c:/" or "/". */
4230 r = IS_DEVICE_SEP (name[1]) ? &name[2] : name;
4231 if (IS_DIRECTORY_SEP (r[0])
4232 && r[1] == '.' && r[2] == '.' && r[3] == '\0')
4233 r[1] = r[2] = '\0';
4235 /* Note: If NAME is a symlink to the root of a UNC volume
4236 (i.e. "\\SERVER"), we will not detect that here, and we will
4237 return data about the symlink as result of FindFirst below.
4238 This is unfortunate, but that marginal use case does not
4239 justify a call to chase_symlinks which would impose a penalty
4240 on all the other use cases. (We get here for symlinks to
4241 roots of UNC volumes because CreateFile above fails for them,
4242 unlike with symlinks to root directories X:\ of drives.) */
4243 if (is_unc_volume (name))
4245 fattrs = unc_volume_file_attributes (name);
4246 if (fattrs == -1)
4247 return -1;
4249 ctime = atime = wtime = utc_base_ft;
4251 else if (rootdir)
4253 if (!dbcs_p)
4255 if (!IS_DIRECTORY_SEP (name[len-1]))
4256 strcat (name, "\\");
4258 else
4260 char *end = name + len;
4261 char *n = CharPrevExA (file_name_codepage, name, end, 0);
4263 if (!IS_DIRECTORY_SEP (*n))
4264 strcat (name, "\\");
4266 if (GetDriveType (name) < 2)
4268 errno = ENOENT;
4269 return -1;
4272 fattrs = FILE_ATTRIBUTE_DIRECTORY;
4273 ctime = atime = wtime = utc_base_ft;
4275 else
4277 if (!dbcs_p)
4279 if (IS_DIRECTORY_SEP (name[len-1]))
4280 name[len - 1] = 0;
4282 else
4284 char *end = name + len;
4285 char *n = CharPrevExA (file_name_codepage, name, end, 0);
4287 if (IS_DIRECTORY_SEP (*n))
4288 *n = 0;
4291 /* (This is hacky, but helps when doing file completions on
4292 network drives.) Optimize by using information available from
4293 active readdir if possible. */
4294 len = strlen (dir_pathname);
4295 if (!dbcs_p)
4297 if (IS_DIRECTORY_SEP (dir_pathname[len-1]))
4298 len--;
4300 else
4302 char *end = dir_pathname + len;
4303 char *n = CharPrevExA (file_name_codepage, dir_pathname, end, 0);
4305 if (IS_DIRECTORY_SEP (*n))
4306 len--;
4308 if (dir_find_handle != INVALID_HANDLE_VALUE
4309 && !(is_a_symlink && follow_symlinks)
4310 && strnicmp (save_name, dir_pathname, len) == 0
4311 && IS_DIRECTORY_SEP (name[len])
4312 && xstrcasecmp (name + len + 1, dir_static.d_name) == 0)
4314 /* This was the last entry returned by readdir. */
4315 wfd = dir_find_data;
4317 else
4319 logon_network_drive (name);
4321 fh = FindFirstFile (name, &wfd);
4322 if (fh == INVALID_HANDLE_VALUE)
4324 errno = ENOENT;
4325 return -1;
4327 FindClose (fh);
4329 /* Note: if NAME is a symlink, the information we get from
4330 FindFirstFile is for the symlink, not its target. */
4331 fattrs = wfd.dwFileAttributes;
4332 ctime = wfd.ftCreationTime;
4333 atime = wfd.ftLastAccessTime;
4334 wtime = wfd.ftLastWriteTime;
4335 fs_high = wfd.nFileSizeHigh;
4336 fs_low = wfd.nFileSizeLow;
4337 fake_inode = 0;
4338 nlinks = 1;
4339 serialnum = volume_info.serialnum;
4341 if (is_a_symlink && !follow_symlinks)
4342 buf->st_mode = S_IFLNK;
4343 else if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
4344 buf->st_mode = S_IFDIR;
4345 else
4346 buf->st_mode = S_IFREG;
4348 get_file_owner_and_group (NULL, buf);
4351 #if 0
4352 /* Not sure if there is any point in this. */
4353 if (!NILP (Vw32_generate_fake_inodes))
4354 fake_inode = generate_inode_val (name);
4355 else if (fake_inode == 0)
4357 /* For want of something better, try to make everything unique. */
4358 static DWORD gen_num = 0;
4359 fake_inode = ++gen_num;
4361 #endif
4363 buf->st_ino = fake_inode;
4365 buf->st_dev = serialnum;
4366 buf->st_rdev = serialnum;
4368 buf->st_size = fs_high;
4369 buf->st_size <<= 32;
4370 buf->st_size += fs_low;
4371 buf->st_nlink = nlinks;
4373 /* Convert timestamps to Unix format. */
4374 buf->st_mtime = convert_time (wtime);
4375 buf->st_atime = convert_time (atime);
4376 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
4377 buf->st_ctime = convert_time (ctime);
4378 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
4380 /* determine rwx permissions */
4381 if (is_a_symlink && !follow_symlinks)
4382 permission = S_IREAD | S_IWRITE | S_IEXEC; /* Posix expectations */
4383 else
4385 if (fattrs & FILE_ATTRIBUTE_READONLY)
4386 permission = S_IREAD;
4387 else
4388 permission = S_IREAD | S_IWRITE;
4390 if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
4391 permission |= S_IEXEC;
4392 else if (is_exec (name))
4393 permission |= S_IEXEC;
4396 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
4398 return 0;
4402 stat (const char * path, struct stat * buf)
4404 return stat_worker (path, buf, 1);
4408 lstat (const char * path, struct stat * buf)
4410 return stat_worker (path, buf, 0);
4414 fstatat (int fd, char const *name, struct stat *st, int flags)
4416 /* Rely on a hack: an open directory is modeled as file descriptor 0.
4417 This is good enough for the current usage in Emacs, but is fragile.
4419 FIXME: Add proper support for fdopendir, fstatat, readlinkat.
4420 Gnulib does this and can serve as a model. */
4421 char fullname[MAX_PATH];
4423 if (fd != AT_FDCWD)
4425 if (_snprintf (fullname, sizeof fullname, "%s/%s", dir_pathname, name)
4426 < 0)
4428 errno = ENAMETOOLONG;
4429 return -1;
4431 name = fullname;
4434 return stat_worker (name, st, ! (flags & AT_SYMLINK_NOFOLLOW));
4437 /* Provide fstat and utime as well as stat for consistent handling of
4438 file timestamps. */
4440 fstat (int desc, struct stat * buf)
4442 HANDLE fh = (HANDLE) _get_osfhandle (desc);
4443 BY_HANDLE_FILE_INFORMATION info;
4444 unsigned __int64 fake_inode;
4445 int permission;
4447 switch (GetFileType (fh) & ~FILE_TYPE_REMOTE)
4449 case FILE_TYPE_DISK:
4450 buf->st_mode = S_IFREG;
4451 if (!GetFileInformationByHandle (fh, &info))
4453 errno = EACCES;
4454 return -1;
4456 break;
4457 case FILE_TYPE_PIPE:
4458 buf->st_mode = S_IFIFO;
4459 goto non_disk;
4460 case FILE_TYPE_CHAR:
4461 case FILE_TYPE_UNKNOWN:
4462 default:
4463 buf->st_mode = S_IFCHR;
4464 non_disk:
4465 memset (&info, 0, sizeof (info));
4466 info.dwFileAttributes = 0;
4467 info.ftCreationTime = utc_base_ft;
4468 info.ftLastAccessTime = utc_base_ft;
4469 info.ftLastWriteTime = utc_base_ft;
4472 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
4473 buf->st_mode = S_IFDIR;
4475 buf->st_nlink = info.nNumberOfLinks;
4476 /* Might as well use file index to fake inode values, but this
4477 is not guaranteed to be unique unless we keep a handle open
4478 all the time (even then there are situations where it is
4479 not unique). Reputedly, there are at most 48 bits of info
4480 (on NTFS, presumably less on FAT). */
4481 fake_inode = info.nFileIndexHigh;
4482 fake_inode <<= 32;
4483 fake_inode += info.nFileIndexLow;
4485 /* MSVC defines _ino_t to be short; other libc's might not. */
4486 if (sizeof (buf->st_ino) == 2)
4487 buf->st_ino = fake_inode ^ (fake_inode >> 16);
4488 else
4489 buf->st_ino = fake_inode;
4491 /* If the caller so requested, get the true file owner and group.
4492 Otherwise, consider the file to belong to the current user. */
4493 if (!w32_stat_get_owner_group || is_windows_9x () == TRUE)
4494 get_file_owner_and_group (NULL, buf);
4495 else
4497 PSECURITY_DESCRIPTOR psd = NULL;
4499 psd = get_file_security_desc_by_handle (fh);
4500 if (psd)
4502 get_file_owner_and_group (psd, buf);
4503 LocalFree (psd);
4505 else
4506 get_file_owner_and_group (NULL, buf);
4509 buf->st_dev = info.dwVolumeSerialNumber;
4510 buf->st_rdev = info.dwVolumeSerialNumber;
4512 buf->st_size = info.nFileSizeHigh;
4513 buf->st_size <<= 32;
4514 buf->st_size += info.nFileSizeLow;
4516 /* Convert timestamps to Unix format. */
4517 buf->st_mtime = convert_time (info.ftLastWriteTime);
4518 buf->st_atime = convert_time (info.ftLastAccessTime);
4519 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
4520 buf->st_ctime = convert_time (info.ftCreationTime);
4521 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
4523 /* determine rwx permissions */
4524 if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
4525 permission = S_IREAD;
4526 else
4527 permission = S_IREAD | S_IWRITE;
4529 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
4530 permission |= S_IEXEC;
4531 else
4533 #if 0 /* no way of knowing the filename */
4534 char * p = strrchr (name, '.');
4535 if (p != NULL &&
4536 (xstrcasecmp (p, ".exe") == 0 ||
4537 xstrcasecmp (p, ".com") == 0 ||
4538 xstrcasecmp (p, ".bat") == 0 ||
4539 xstrcasecmp (p, ".cmd") == 0))
4540 permission |= S_IEXEC;
4541 #endif
4544 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
4546 return 0;
4549 /* A version of 'utime' which handles directories as well as
4550 files. */
4553 utime (const char *name, struct utimbuf *times)
4555 struct utimbuf deftime;
4556 HANDLE fh;
4557 FILETIME mtime;
4558 FILETIME atime;
4560 if (times == NULL)
4562 deftime.modtime = deftime.actime = time (NULL);
4563 times = &deftime;
4566 /* Need write access to set times. */
4567 fh = CreateFile (name, FILE_WRITE_ATTRIBUTES,
4568 /* If NAME specifies a directory, FILE_SHARE_DELETE
4569 allows other processes to delete files inside it,
4570 while we have the directory open. */
4571 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
4572 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
4573 if (fh != INVALID_HANDLE_VALUE)
4575 convert_from_time_t (times->actime, &atime);
4576 convert_from_time_t (times->modtime, &mtime);
4577 if (!SetFileTime (fh, NULL, &atime, &mtime))
4579 CloseHandle (fh);
4580 errno = EACCES;
4581 return -1;
4583 CloseHandle (fh);
4585 else
4587 errno = EINVAL;
4588 return -1;
4590 return 0;
4594 /* Symlink-related functions. */
4595 #ifndef SYMBOLIC_LINK_FLAG_DIRECTORY
4596 #define SYMBOLIC_LINK_FLAG_DIRECTORY 0x1
4597 #endif
4600 symlink (char const *filename, char const *linkname)
4602 char linkfn[MAX_PATH], *tgtfn;
4603 DWORD flags = 0;
4604 int dir_access, filename_ends_in_slash;
4605 int dbcs_p;
4607 /* Diagnostics follows Posix as much as possible. */
4608 if (filename == NULL || linkname == NULL)
4610 errno = EFAULT;
4611 return -1;
4613 if (!*filename)
4615 errno = ENOENT;
4616 return -1;
4618 if (strlen (filename) > MAX_PATH || strlen (linkname) > MAX_PATH)
4620 errno = ENAMETOOLONG;
4621 return -1;
4624 strcpy (linkfn, map_w32_filename (linkname, NULL));
4625 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) == 0)
4627 errno = EPERM;
4628 return -1;
4631 dbcs_p = max_filename_mbslen () > 1;
4633 /* Note: since empty FILENAME was already rejected, we can safely
4634 refer to FILENAME[1]. */
4635 if (!(IS_DIRECTORY_SEP (filename[0]) || IS_DEVICE_SEP (filename[1])))
4637 /* Non-absolute FILENAME is understood as being relative to
4638 LINKNAME's directory. We need to prepend that directory to
4639 FILENAME to get correct results from faccessat below, since
4640 otherwise it will interpret FILENAME relative to the
4641 directory where the Emacs process runs. Note that
4642 make-symbolic-link always makes sure LINKNAME is a fully
4643 expanded file name. */
4644 char tem[MAX_PATH];
4645 char *p = linkfn + strlen (linkfn);
4647 if (!dbcs_p)
4649 while (p > linkfn && !IS_ANY_SEP (p[-1]))
4650 p--;
4652 else
4654 char *p1 = CharPrevExA (file_name_codepage, linkfn, p, 0);
4656 while (p > linkfn && !IS_ANY_SEP (*p1))
4658 p = p1;
4659 p1 = CharPrevExA (file_name_codepage, linkfn, p1, 0);
4662 if (p > linkfn)
4663 strncpy (tem, linkfn, p - linkfn);
4664 tem[p - linkfn] = '\0';
4665 strcat (tem, filename);
4666 dir_access = faccessat (AT_FDCWD, tem, D_OK, AT_EACCESS);
4668 else
4669 dir_access = faccessat (AT_FDCWD, filename, D_OK, AT_EACCESS);
4671 /* Since Windows distinguishes between symlinks to directories and
4672 to files, we provide a kludgy feature: if FILENAME doesn't
4673 exist, but ends in a slash, we create a symlink to directory. If
4674 FILENAME exists and is a directory, we always create a symlink to
4675 directory. */
4676 if (!dbcs_p)
4677 filename_ends_in_slash = IS_DIRECTORY_SEP (filename[strlen (filename) - 1]);
4678 else
4680 const char *end = filename + strlen (filename);
4681 const char *n = CharPrevExA (file_name_codepage, filename, end, 0);
4683 filename_ends_in_slash = IS_DIRECTORY_SEP (*n);
4685 if (dir_access == 0 || filename_ends_in_slash)
4686 flags = SYMBOLIC_LINK_FLAG_DIRECTORY;
4688 tgtfn = (char *)map_w32_filename (filename, NULL);
4689 if (filename_ends_in_slash)
4690 tgtfn[strlen (tgtfn) - 1] = '\0';
4692 errno = 0;
4693 if (!create_symbolic_link (linkfn, tgtfn, flags))
4695 /* ENOSYS is set by create_symbolic_link, when it detects that
4696 the OS doesn't support the CreateSymbolicLink API. */
4697 if (errno != ENOSYS)
4699 DWORD w32err = GetLastError ();
4701 switch (w32err)
4703 /* ERROR_SUCCESS is sometimes returned when LINKFN and
4704 TGTFN point to the same file name, go figure. */
4705 case ERROR_SUCCESS:
4706 case ERROR_FILE_EXISTS:
4707 errno = EEXIST;
4708 break;
4709 case ERROR_ACCESS_DENIED:
4710 errno = EACCES;
4711 break;
4712 case ERROR_FILE_NOT_FOUND:
4713 case ERROR_PATH_NOT_FOUND:
4714 case ERROR_BAD_NETPATH:
4715 case ERROR_INVALID_REPARSE_DATA:
4716 errno = ENOENT;
4717 break;
4718 case ERROR_DIRECTORY:
4719 errno = EISDIR;
4720 break;
4721 case ERROR_PRIVILEGE_NOT_HELD:
4722 case ERROR_NOT_ALL_ASSIGNED:
4723 errno = EPERM;
4724 break;
4725 case ERROR_DISK_FULL:
4726 errno = ENOSPC;
4727 break;
4728 default:
4729 errno = EINVAL;
4730 break;
4733 return -1;
4735 return 0;
4738 /* A quick inexpensive test of whether FILENAME identifies a file that
4739 is a symlink. Returns non-zero if it is, zero otherwise. FILENAME
4740 must already be in the normalized form returned by
4741 map_w32_filename.
4743 Note: for repeated operations on many files, it is best to test
4744 whether the underlying volume actually supports symlinks, by
4745 testing the FILE_SUPPORTS_REPARSE_POINTS bit in volume's flags, and
4746 avoid the call to this function if it doesn't. That's because the
4747 call to GetFileAttributes takes a non-negligible time, especially
4748 on non-local or removable filesystems. See stat_worker for an
4749 example of how to do that. */
4750 static int
4751 is_symlink (const char *filename)
4753 DWORD attrs;
4754 WIN32_FIND_DATA wfd;
4755 HANDLE fh;
4757 attrs = GetFileAttributes (filename);
4758 if (attrs == -1)
4760 DWORD w32err = GetLastError ();
4762 switch (w32err)
4764 case ERROR_BAD_NETPATH: /* network share, can't be a symlink */
4765 break;
4766 case ERROR_ACCESS_DENIED:
4767 errno = EACCES;
4768 break;
4769 case ERROR_FILE_NOT_FOUND:
4770 case ERROR_PATH_NOT_FOUND:
4771 default:
4772 errno = ENOENT;
4773 break;
4775 return 0;
4777 if ((attrs & FILE_ATTRIBUTE_REPARSE_POINT) == 0)
4778 return 0;
4779 logon_network_drive (filename);
4780 fh = FindFirstFile (filename, &wfd);
4781 if (fh == INVALID_HANDLE_VALUE)
4782 return 0;
4783 FindClose (fh);
4784 return (wfd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0
4785 && (wfd.dwReserved0 & IO_REPARSE_TAG_SYMLINK) == IO_REPARSE_TAG_SYMLINK;
4788 /* If NAME identifies a symbolic link, copy into BUF the file name of
4789 the symlink's target. Copy at most BUF_SIZE bytes, and do NOT
4790 null-terminate the target name, even if it fits. Return the number
4791 of bytes copied, or -1 if NAME is not a symlink or any error was
4792 encountered while resolving it. The file name copied into BUF is
4793 encoded in the current ANSI codepage. */
4794 ssize_t
4795 readlink (const char *name, char *buf, size_t buf_size)
4797 const char *path;
4798 TOKEN_PRIVILEGES privs;
4799 int restore_privs = 0;
4800 HANDLE sh;
4801 ssize_t retval;
4803 if (name == NULL)
4805 errno = EFAULT;
4806 return -1;
4808 if (!*name)
4810 errno = ENOENT;
4811 return -1;
4814 path = map_w32_filename (name, NULL);
4816 if (strlen (path) > MAX_PATH)
4818 errno = ENAMETOOLONG;
4819 return -1;
4822 errno = 0;
4823 if (is_windows_9x () == TRUE
4824 || (volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) == 0
4825 || !is_symlink (path))
4827 if (!errno)
4828 errno = EINVAL; /* not a symlink */
4829 return -1;
4832 /* Done with simple tests, now we're in for some _real_ work. */
4833 if (enable_privilege (SE_BACKUP_NAME, TRUE, &privs))
4834 restore_privs = 1;
4835 /* Implementation note: From here and onward, don't return early,
4836 since that will fail to restore the original set of privileges of
4837 the calling thread. */
4839 retval = -1; /* not too optimistic, are we? */
4841 /* Note: In the next call to CreateFile, we use zero as the 2nd
4842 argument because, when the symlink is a hidden/system file,
4843 e.g. 'C:\Users\All Users', GENERIC_READ fails with
4844 ERROR_ACCESS_DENIED. Zero seems to work just fine, both for file
4845 and directory symlinks. */
4846 sh = CreateFile (path, 0, 0, NULL, OPEN_EXISTING,
4847 FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
4848 NULL);
4849 if (sh != INVALID_HANDLE_VALUE)
4851 BYTE reparse_buf[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
4852 REPARSE_DATA_BUFFER *reparse_data = (REPARSE_DATA_BUFFER *)&reparse_buf[0];
4853 DWORD retbytes;
4855 if (!DeviceIoControl (sh, FSCTL_GET_REPARSE_POINT, NULL, 0,
4856 reparse_buf, MAXIMUM_REPARSE_DATA_BUFFER_SIZE,
4857 &retbytes, NULL))
4858 errno = EIO;
4859 else if (reparse_data->ReparseTag != IO_REPARSE_TAG_SYMLINK)
4860 errno = EINVAL;
4861 else
4863 /* Copy the link target name, in wide characters, from
4864 reparse_data, then convert it to multibyte encoding in
4865 the current locale's codepage. */
4866 WCHAR *lwname;
4867 BYTE lname[MAX_PATH];
4868 USHORT lname_len;
4869 USHORT lwname_len =
4870 reparse_data->SymbolicLinkReparseBuffer.PrintNameLength;
4871 WCHAR *lwname_src =
4872 reparse_data->SymbolicLinkReparseBuffer.PathBuffer
4873 + reparse_data->SymbolicLinkReparseBuffer.PrintNameOffset/sizeof(WCHAR);
4874 /* This updates file_name_codepage which we need below. */
4875 int dbcs_p = max_filename_mbslen () > 1;
4877 /* According to MSDN, PrintNameLength does not include the
4878 terminating null character. */
4879 lwname = alloca ((lwname_len + 1) * sizeof(WCHAR));
4880 memcpy (lwname, lwname_src, lwname_len);
4881 lwname[lwname_len/sizeof(WCHAR)] = 0; /* null-terminate */
4883 lname_len = WideCharToMultiByte (file_name_codepage, 0, lwname, -1,
4884 lname, MAX_PATH, NULL, NULL);
4885 if (!lname_len)
4887 /* WideCharToMultiByte failed. */
4888 DWORD w32err1 = GetLastError ();
4890 switch (w32err1)
4892 case ERROR_INSUFFICIENT_BUFFER:
4893 errno = ENAMETOOLONG;
4894 break;
4895 case ERROR_INVALID_PARAMETER:
4896 errno = EFAULT;
4897 break;
4898 case ERROR_NO_UNICODE_TRANSLATION:
4899 errno = ENOENT;
4900 break;
4901 default:
4902 errno = EINVAL;
4903 break;
4906 else
4908 size_t size_to_copy = buf_size;
4909 BYTE *p = lname, *p2;
4910 BYTE *pend = p + lname_len;
4912 /* Normalize like dostounix_filename does, but we don't
4913 want to assume that lname is null-terminated. */
4914 if (dbcs_p)
4915 p2 = CharNextExA (file_name_codepage, p, 0);
4916 else
4917 p2 = p + 1;
4918 if (*p && *p2 == ':' && *p >= 'A' && *p <= 'Z')
4920 *p += 'a' - 'A';
4921 p += 2;
4923 while (p <= pend)
4925 if (*p == '\\')
4926 *p = '/';
4927 if (dbcs_p)
4929 p = CharNextExA (file_name_codepage, p, 0);
4930 /* CharNextExA doesn't advance at null character. */
4931 if (!*p)
4932 break;
4934 else
4935 ++p;
4937 /* Testing for null-terminated LNAME is paranoia:
4938 WideCharToMultiByte should always return a
4939 null-terminated string when its 4th argument is -1
4940 and its 3rd argument is null-terminated (which they
4941 are, see above). */
4942 if (lname[lname_len - 1] == '\0')
4943 lname_len--;
4944 if (lname_len <= buf_size)
4945 size_to_copy = lname_len;
4946 strncpy (buf, lname, size_to_copy);
4947 /* Success! */
4948 retval = size_to_copy;
4951 CloseHandle (sh);
4953 else
4955 /* CreateFile failed. */
4956 DWORD w32err2 = GetLastError ();
4958 switch (w32err2)
4960 case ERROR_FILE_NOT_FOUND:
4961 case ERROR_PATH_NOT_FOUND:
4962 errno = ENOENT;
4963 break;
4964 case ERROR_ACCESS_DENIED:
4965 case ERROR_TOO_MANY_OPEN_FILES:
4966 errno = EACCES;
4967 break;
4968 default:
4969 errno = EPERM;
4970 break;
4973 if (restore_privs)
4975 restore_privilege (&privs);
4976 revert_to_self ();
4979 return retval;
4982 ssize_t
4983 readlinkat (int fd, char const *name, char *buffer,
4984 size_t buffer_size)
4986 /* Rely on a hack: an open directory is modeled as file descriptor 0,
4987 as in fstatat. FIXME: Add proper support for readlinkat. */
4988 char fullname[MAX_PATH];
4990 if (fd != AT_FDCWD)
4992 if (_snprintf (fullname, sizeof fullname, "%s/%s", dir_pathname, name)
4993 < 0)
4995 errno = ENAMETOOLONG;
4996 return -1;
4998 name = fullname;
5001 return readlink (name, buffer, buffer_size);
5004 /* If FILE is a symlink, return its target (stored in a static
5005 buffer); otherwise return FILE.
5007 This function repeatedly resolves symlinks in the last component of
5008 a chain of symlink file names, as in foo -> bar -> baz -> ...,
5009 until it arrives at a file whose last component is not a symlink,
5010 or some error occurs. It returns the target of the last
5011 successfully resolved symlink in the chain. If it succeeds to
5012 resolve even a single symlink, the value returned is an absolute
5013 file name with backslashes (result of GetFullPathName). By
5014 contrast, if the original FILE is returned, it is unaltered.
5016 Note: This function can set errno even if it succeeds.
5018 Implementation note: we only resolve the last portion ("basename")
5019 of the argument FILE and of each following file in the chain,
5020 disregarding any possible symlinks in its leading directories.
5021 This is because Windows system calls and library functions
5022 transparently resolve symlinks in leading directories and return
5023 correct information, as long as the basename is not a symlink. */
5024 static char *
5025 chase_symlinks (const char *file)
5027 static char target[MAX_PATH];
5028 char link[MAX_PATH];
5029 ssize_t res, link_len;
5030 int loop_count = 0;
5031 int dbcs_p;
5033 if (is_windows_9x () == TRUE || !is_symlink (file))
5034 return (char *)file;
5036 if ((link_len = GetFullPathName (file, MAX_PATH, link, NULL)) == 0)
5037 return (char *)file;
5039 dbcs_p = max_filename_mbslen () > 1;
5040 target[0] = '\0';
5041 do {
5043 /* Remove trailing slashes, as we want to resolve the last
5044 non-trivial part of the link name. */
5045 if (!dbcs_p)
5047 while (link_len > 3 && IS_DIRECTORY_SEP (link[link_len-1]))
5048 link[link_len--] = '\0';
5050 else if (link_len > 3)
5052 char *n = CharPrevExA (file_name_codepage, link, link + link_len, 0);
5054 while (n >= link + 2 && IS_DIRECTORY_SEP (*n))
5056 n[1] = '\0';
5057 n = CharPrevExA (file_name_codepage, link, n, 0);
5061 res = readlink (link, target, MAX_PATH);
5062 if (res > 0)
5064 target[res] = '\0';
5065 if (!(IS_DEVICE_SEP (target[1])
5066 || (IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1]))))
5068 /* Target is relative. Append it to the directory part of
5069 the symlink, then copy the result back to target. */
5070 char *p = link + link_len;
5072 if (!dbcs_p)
5074 while (p > link && !IS_ANY_SEP (p[-1]))
5075 p--;
5077 else
5079 char *p1 = CharPrevExA (file_name_codepage, link, p, 0);
5081 while (p > link && !IS_ANY_SEP (*p1))
5083 p = p1;
5084 p1 = CharPrevExA (file_name_codepage, link, p1, 0);
5087 strcpy (p, target);
5088 strcpy (target, link);
5090 /* Resolve any "." and ".." to get a fully-qualified file name
5091 in link[] again. */
5092 link_len = GetFullPathName (target, MAX_PATH, link, NULL);
5094 } while (res > 0 && link_len > 0 && ++loop_count <= 100);
5096 if (loop_count > 100)
5097 errno = ELOOP;
5099 if (target[0] == '\0') /* not a single call to readlink succeeded */
5100 return (char *)file;
5101 return target;
5105 /* Posix ACL emulation. */
5108 acl_valid (acl_t acl)
5110 return is_valid_security_descriptor ((PSECURITY_DESCRIPTOR)acl) ? 0 : -1;
5113 char *
5114 acl_to_text (acl_t acl, ssize_t *size)
5116 LPTSTR str_acl;
5117 SECURITY_INFORMATION flags =
5118 OWNER_SECURITY_INFORMATION |
5119 GROUP_SECURITY_INFORMATION |
5120 DACL_SECURITY_INFORMATION;
5121 char *retval = NULL;
5122 ULONG local_size;
5123 int e = errno;
5125 errno = 0;
5127 if (convert_sd_to_sddl ((PSECURITY_DESCRIPTOR)acl, SDDL_REVISION_1, flags, &str_acl, &local_size))
5129 errno = e;
5130 /* We don't want to mix heaps, so we duplicate the string in our
5131 heap and free the one allocated by the API. */
5132 retval = xstrdup (str_acl);
5133 if (size)
5134 *size = local_size;
5135 LocalFree (str_acl);
5137 else if (errno != ENOTSUP)
5138 errno = EINVAL;
5140 return retval;
5143 acl_t
5144 acl_from_text (const char *acl_str)
5146 PSECURITY_DESCRIPTOR psd, retval = NULL;
5147 ULONG sd_size;
5148 int e = errno;
5150 errno = 0;
5152 if (convert_sddl_to_sd (acl_str, SDDL_REVISION_1, &psd, &sd_size))
5154 errno = e;
5155 retval = xmalloc (sd_size);
5156 memcpy (retval, psd, sd_size);
5157 LocalFree (psd);
5159 else if (errno != ENOTSUP)
5160 errno = EINVAL;
5162 return retval;
5166 acl_free (void *ptr)
5168 xfree (ptr);
5169 return 0;
5172 acl_t
5173 acl_get_file (const char *fname, acl_type_t type)
5175 PSECURITY_DESCRIPTOR psd = NULL;
5176 const char *filename;
5178 if (type == ACL_TYPE_ACCESS)
5180 DWORD sd_len, err;
5181 SECURITY_INFORMATION si =
5182 OWNER_SECURITY_INFORMATION |
5183 GROUP_SECURITY_INFORMATION |
5184 DACL_SECURITY_INFORMATION ;
5185 int e = errno;
5187 filename = map_w32_filename (fname, NULL);
5188 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
5189 fname = chase_symlinks (filename);
5190 else
5191 fname = filename;
5193 errno = 0;
5194 if (!get_file_security (fname, si, psd, 0, &sd_len)
5195 && errno != ENOTSUP)
5197 err = GetLastError ();
5198 if (err == ERROR_INSUFFICIENT_BUFFER)
5200 psd = xmalloc (sd_len);
5201 if (!get_file_security (fname, si, psd, sd_len, &sd_len))
5203 xfree (psd);
5204 errno = EIO;
5205 psd = NULL;
5208 else if (err == ERROR_FILE_NOT_FOUND
5209 || err == ERROR_PATH_NOT_FOUND)
5210 errno = ENOENT;
5211 else
5212 errno = EIO;
5214 else if (!errno)
5215 errno = e;
5217 else if (type != ACL_TYPE_DEFAULT)
5218 errno = EINVAL;
5220 return psd;
5224 acl_set_file (const char *fname, acl_type_t type, acl_t acl)
5226 TOKEN_PRIVILEGES old1, old2;
5227 DWORD err;
5228 int st = 0, retval = -1;
5229 SECURITY_INFORMATION flags = 0;
5230 PSID psid;
5231 PACL pacl;
5232 BOOL dflt;
5233 BOOL dacl_present;
5234 int e;
5235 const char *filename;
5237 if (acl_valid (acl) != 0
5238 || (type != ACL_TYPE_DEFAULT && type != ACL_TYPE_ACCESS))
5240 errno = EINVAL;
5241 return -1;
5244 if (type == ACL_TYPE_DEFAULT)
5246 errno = ENOSYS;
5247 return -1;
5250 filename = map_w32_filename (fname, NULL);
5251 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
5252 fname = chase_symlinks (filename);
5253 else
5254 fname = filename;
5256 if (get_security_descriptor_owner ((PSECURITY_DESCRIPTOR)acl, &psid, &dflt)
5257 && psid)
5258 flags |= OWNER_SECURITY_INFORMATION;
5259 if (get_security_descriptor_group ((PSECURITY_DESCRIPTOR)acl, &psid, &dflt)
5260 && psid)
5261 flags |= GROUP_SECURITY_INFORMATION;
5262 if (get_security_descriptor_dacl ((PSECURITY_DESCRIPTOR)acl, &dacl_present,
5263 &pacl, &dflt)
5264 && dacl_present)
5265 flags |= DACL_SECURITY_INFORMATION;
5266 if (!flags)
5267 return 0;
5269 /* According to KB-245153, setting the owner will succeed if either:
5270 (1) the caller is the user who will be the new owner, and has the
5271 SE_TAKE_OWNERSHIP privilege, or
5272 (2) the caller has the SE_RESTORE privilege, in which case she can
5273 set any valid user or group as the owner
5275 We request below both SE_TAKE_OWNERSHIP and SE_RESTORE
5276 privileges, and disregard any failures in obtaining them. If
5277 these privileges cannot be obtained, and do not already exist in
5278 the calling thread's security token, this function could fail
5279 with EPERM. */
5280 if (enable_privilege (SE_TAKE_OWNERSHIP_NAME, TRUE, &old1))
5281 st++;
5282 if (enable_privilege (SE_RESTORE_NAME, TRUE, &old2))
5283 st++;
5285 e = errno;
5286 errno = 0;
5287 if (!set_file_security ((char *)fname, flags, (PSECURITY_DESCRIPTOR)acl))
5289 err = GetLastError ();
5291 if (errno == ENOTSUP)
5293 else if (err == ERROR_INVALID_OWNER
5294 || err == ERROR_NOT_ALL_ASSIGNED
5295 || err == ERROR_ACCESS_DENIED)
5297 /* Maybe the requested ACL and the one the file already has
5298 are identical, in which case we can silently ignore the
5299 failure. (And no, Windows doesn't.) */
5300 acl_t current_acl = acl_get_file (fname, ACL_TYPE_ACCESS);
5302 errno = EPERM;
5303 if (current_acl)
5305 char *acl_from = acl_to_text (current_acl, NULL);
5306 char *acl_to = acl_to_text (acl, NULL);
5308 if (acl_from && acl_to && xstrcasecmp (acl_from, acl_to) == 0)
5310 retval = 0;
5311 errno = e;
5313 if (acl_from)
5314 acl_free (acl_from);
5315 if (acl_to)
5316 acl_free (acl_to);
5317 acl_free (current_acl);
5320 else if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
5321 errno = ENOENT;
5322 else
5323 errno = EACCES;
5325 else
5327 retval = 0;
5328 errno = e;
5331 if (st)
5333 if (st >= 2)
5334 restore_privilege (&old2);
5335 restore_privilege (&old1);
5336 revert_to_self ();
5339 return retval;
5343 /* MS-Windows version of careadlinkat (cf. ../lib/careadlinkat.c). We
5344 have a fixed max size for file names, so we don't need the kind of
5345 alloc/malloc/realloc dance the gnulib version does. We also don't
5346 support FD-relative symlinks. */
5347 char *
5348 careadlinkat (int fd, char const *filename,
5349 char *buffer, size_t buffer_size,
5350 struct allocator const *alloc,
5351 ssize_t (*preadlinkat) (int, char const *, char *, size_t))
5353 char linkname[MAX_PATH];
5354 ssize_t link_size;
5356 link_size = preadlinkat (fd, filename, linkname, sizeof(linkname));
5358 if (link_size > 0)
5360 char *retval = buffer;
5362 linkname[link_size++] = '\0';
5363 if (link_size > buffer_size)
5364 retval = (char *)(alloc ? alloc->allocate : xmalloc) (link_size);
5365 if (retval)
5366 memcpy (retval, linkname, link_size);
5368 return retval;
5370 return NULL;
5374 /* Support for browsing other processes and their attributes. See
5375 process.c for the Lisp bindings. */
5377 /* Helper wrapper functions. */
5379 static HANDLE WINAPI
5380 create_toolhelp32_snapshot (DWORD Flags, DWORD Ignored)
5382 static CreateToolhelp32Snapshot_Proc s_pfn_Create_Toolhelp32_Snapshot = NULL;
5384 if (g_b_init_create_toolhelp32_snapshot == 0)
5386 g_b_init_create_toolhelp32_snapshot = 1;
5387 s_pfn_Create_Toolhelp32_Snapshot = (CreateToolhelp32Snapshot_Proc)
5388 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5389 "CreateToolhelp32Snapshot");
5391 if (s_pfn_Create_Toolhelp32_Snapshot == NULL)
5393 return INVALID_HANDLE_VALUE;
5395 return (s_pfn_Create_Toolhelp32_Snapshot (Flags, Ignored));
5398 static BOOL WINAPI
5399 process32_first (HANDLE hSnapshot, LPPROCESSENTRY32 lppe)
5401 static Process32First_Proc s_pfn_Process32_First = NULL;
5403 if (g_b_init_process32_first == 0)
5405 g_b_init_process32_first = 1;
5406 s_pfn_Process32_First = (Process32First_Proc)
5407 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5408 "Process32First");
5410 if (s_pfn_Process32_First == NULL)
5412 return FALSE;
5414 return (s_pfn_Process32_First (hSnapshot, lppe));
5417 static BOOL WINAPI
5418 process32_next (HANDLE hSnapshot, LPPROCESSENTRY32 lppe)
5420 static Process32Next_Proc s_pfn_Process32_Next = NULL;
5422 if (g_b_init_process32_next == 0)
5424 g_b_init_process32_next = 1;
5425 s_pfn_Process32_Next = (Process32Next_Proc)
5426 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5427 "Process32Next");
5429 if (s_pfn_Process32_Next == NULL)
5431 return FALSE;
5433 return (s_pfn_Process32_Next (hSnapshot, lppe));
5436 static BOOL WINAPI
5437 open_thread_token (HANDLE ThreadHandle,
5438 DWORD DesiredAccess,
5439 BOOL OpenAsSelf,
5440 PHANDLE TokenHandle)
5442 static OpenThreadToken_Proc s_pfn_Open_Thread_Token = NULL;
5443 HMODULE hm_advapi32 = NULL;
5444 if (is_windows_9x () == TRUE)
5446 SetLastError (ERROR_NOT_SUPPORTED);
5447 return FALSE;
5449 if (g_b_init_open_thread_token == 0)
5451 g_b_init_open_thread_token = 1;
5452 hm_advapi32 = LoadLibrary ("Advapi32.dll");
5453 s_pfn_Open_Thread_Token =
5454 (OpenThreadToken_Proc) GetProcAddress (hm_advapi32, "OpenThreadToken");
5456 if (s_pfn_Open_Thread_Token == NULL)
5458 SetLastError (ERROR_NOT_SUPPORTED);
5459 return FALSE;
5461 return (
5462 s_pfn_Open_Thread_Token (
5463 ThreadHandle,
5464 DesiredAccess,
5465 OpenAsSelf,
5466 TokenHandle)
5470 static BOOL WINAPI
5471 impersonate_self (SECURITY_IMPERSONATION_LEVEL ImpersonationLevel)
5473 static ImpersonateSelf_Proc s_pfn_Impersonate_Self = NULL;
5474 HMODULE hm_advapi32 = NULL;
5475 if (is_windows_9x () == TRUE)
5477 return FALSE;
5479 if (g_b_init_impersonate_self == 0)
5481 g_b_init_impersonate_self = 1;
5482 hm_advapi32 = LoadLibrary ("Advapi32.dll");
5483 s_pfn_Impersonate_Self =
5484 (ImpersonateSelf_Proc) GetProcAddress (hm_advapi32, "ImpersonateSelf");
5486 if (s_pfn_Impersonate_Self == NULL)
5488 return FALSE;
5490 return s_pfn_Impersonate_Self (ImpersonationLevel);
5493 static BOOL WINAPI
5494 revert_to_self (void)
5496 static RevertToSelf_Proc s_pfn_Revert_To_Self = NULL;
5497 HMODULE hm_advapi32 = NULL;
5498 if (is_windows_9x () == TRUE)
5500 return FALSE;
5502 if (g_b_init_revert_to_self == 0)
5504 g_b_init_revert_to_self = 1;
5505 hm_advapi32 = LoadLibrary ("Advapi32.dll");
5506 s_pfn_Revert_To_Self =
5507 (RevertToSelf_Proc) GetProcAddress (hm_advapi32, "RevertToSelf");
5509 if (s_pfn_Revert_To_Self == NULL)
5511 return FALSE;
5513 return s_pfn_Revert_To_Self ();
5516 static BOOL WINAPI
5517 get_process_memory_info (HANDLE h_proc,
5518 PPROCESS_MEMORY_COUNTERS mem_counters,
5519 DWORD bufsize)
5521 static GetProcessMemoryInfo_Proc s_pfn_Get_Process_Memory_Info = NULL;
5522 HMODULE hm_psapi = NULL;
5523 if (is_windows_9x () == TRUE)
5525 return FALSE;
5527 if (g_b_init_get_process_memory_info == 0)
5529 g_b_init_get_process_memory_info = 1;
5530 hm_psapi = LoadLibrary ("Psapi.dll");
5531 if (hm_psapi)
5532 s_pfn_Get_Process_Memory_Info = (GetProcessMemoryInfo_Proc)
5533 GetProcAddress (hm_psapi, "GetProcessMemoryInfo");
5535 if (s_pfn_Get_Process_Memory_Info == NULL)
5537 return FALSE;
5539 return s_pfn_Get_Process_Memory_Info (h_proc, mem_counters, bufsize);
5542 static BOOL WINAPI
5543 get_process_working_set_size (HANDLE h_proc,
5544 PSIZE_T minrss,
5545 PSIZE_T maxrss)
5547 static GetProcessWorkingSetSize_Proc
5548 s_pfn_Get_Process_Working_Set_Size = NULL;
5550 if (is_windows_9x () == TRUE)
5552 return FALSE;
5554 if (g_b_init_get_process_working_set_size == 0)
5556 g_b_init_get_process_working_set_size = 1;
5557 s_pfn_Get_Process_Working_Set_Size = (GetProcessWorkingSetSize_Proc)
5558 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5559 "GetProcessWorkingSetSize");
5561 if (s_pfn_Get_Process_Working_Set_Size == NULL)
5563 return FALSE;
5565 return s_pfn_Get_Process_Working_Set_Size (h_proc, minrss, maxrss);
5568 static BOOL WINAPI
5569 global_memory_status (MEMORYSTATUS *buf)
5571 static GlobalMemoryStatus_Proc s_pfn_Global_Memory_Status = NULL;
5573 if (is_windows_9x () == TRUE)
5575 return FALSE;
5577 if (g_b_init_global_memory_status == 0)
5579 g_b_init_global_memory_status = 1;
5580 s_pfn_Global_Memory_Status = (GlobalMemoryStatus_Proc)
5581 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5582 "GlobalMemoryStatus");
5584 if (s_pfn_Global_Memory_Status == NULL)
5586 return FALSE;
5588 return s_pfn_Global_Memory_Status (buf);
5591 static BOOL WINAPI
5592 global_memory_status_ex (MEMORY_STATUS_EX *buf)
5594 static GlobalMemoryStatusEx_Proc s_pfn_Global_Memory_Status_Ex = NULL;
5596 if (is_windows_9x () == TRUE)
5598 return FALSE;
5600 if (g_b_init_global_memory_status_ex == 0)
5602 g_b_init_global_memory_status_ex = 1;
5603 s_pfn_Global_Memory_Status_Ex = (GlobalMemoryStatusEx_Proc)
5604 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5605 "GlobalMemoryStatusEx");
5607 if (s_pfn_Global_Memory_Status_Ex == NULL)
5609 return FALSE;
5611 return s_pfn_Global_Memory_Status_Ex (buf);
5614 Lisp_Object
5615 list_system_processes (void)
5617 struct gcpro gcpro1;
5618 Lisp_Object proclist = Qnil;
5619 HANDLE h_snapshot;
5621 h_snapshot = create_toolhelp32_snapshot (TH32CS_SNAPPROCESS, 0);
5623 if (h_snapshot != INVALID_HANDLE_VALUE)
5625 PROCESSENTRY32 proc_entry;
5626 DWORD proc_id;
5627 BOOL res;
5629 GCPRO1 (proclist);
5631 proc_entry.dwSize = sizeof (PROCESSENTRY32);
5632 for (res = process32_first (h_snapshot, &proc_entry); res;
5633 res = process32_next (h_snapshot, &proc_entry))
5635 proc_id = proc_entry.th32ProcessID;
5636 proclist = Fcons (make_fixnum_or_float (proc_id), proclist);
5639 CloseHandle (h_snapshot);
5640 UNGCPRO;
5641 proclist = Fnreverse (proclist);
5644 return proclist;
5647 static int
5648 enable_privilege (LPCTSTR priv_name, BOOL enable_p, TOKEN_PRIVILEGES *old_priv)
5650 TOKEN_PRIVILEGES priv;
5651 DWORD priv_size = sizeof (priv);
5652 DWORD opriv_size = sizeof (*old_priv);
5653 HANDLE h_token = NULL;
5654 HANDLE h_thread = GetCurrentThread ();
5655 int ret_val = 0;
5656 BOOL res;
5658 res = open_thread_token (h_thread,
5659 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
5660 FALSE, &h_token);
5661 if (!res && GetLastError () == ERROR_NO_TOKEN)
5663 if (impersonate_self (SecurityImpersonation))
5664 res = open_thread_token (h_thread,
5665 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
5666 FALSE, &h_token);
5668 if (res)
5670 priv.PrivilegeCount = 1;
5671 priv.Privileges[0].Attributes = enable_p ? SE_PRIVILEGE_ENABLED : 0;
5672 LookupPrivilegeValue (NULL, priv_name, &priv.Privileges[0].Luid);
5673 if (AdjustTokenPrivileges (h_token, FALSE, &priv, priv_size,
5674 old_priv, &opriv_size)
5675 && GetLastError () != ERROR_NOT_ALL_ASSIGNED)
5676 ret_val = 1;
5678 if (h_token)
5679 CloseHandle (h_token);
5681 return ret_val;
5684 static int
5685 restore_privilege (TOKEN_PRIVILEGES *priv)
5687 DWORD priv_size = sizeof (*priv);
5688 HANDLE h_token = NULL;
5689 int ret_val = 0;
5691 if (open_thread_token (GetCurrentThread (),
5692 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
5693 FALSE, &h_token))
5695 if (AdjustTokenPrivileges (h_token, FALSE, priv, priv_size, NULL, NULL)
5696 && GetLastError () != ERROR_NOT_ALL_ASSIGNED)
5697 ret_val = 1;
5699 if (h_token)
5700 CloseHandle (h_token);
5702 return ret_val;
5705 static Lisp_Object
5706 ltime (ULONGLONG time_100ns)
5708 ULONGLONG time_sec = time_100ns / 10000000;
5709 int subsec = time_100ns % 10000000;
5710 return list4i (time_sec >> 16, time_sec & 0xffff,
5711 subsec / 10, subsec % 10 * 100000);
5714 #define U64_TO_LISP_TIME(time) ltime (time)
5716 static int
5717 process_times (HANDLE h_proc, Lisp_Object *ctime, Lisp_Object *etime,
5718 Lisp_Object *stime, Lisp_Object *utime, Lisp_Object *ttime,
5719 double *pcpu)
5721 FILETIME ft_creation, ft_exit, ft_kernel, ft_user, ft_current;
5722 ULONGLONG tem1, tem2, tem3, tem;
5724 if (!h_proc
5725 || !get_process_times_fn
5726 || !(*get_process_times_fn) (h_proc, &ft_creation, &ft_exit,
5727 &ft_kernel, &ft_user))
5728 return 0;
5730 GetSystemTimeAsFileTime (&ft_current);
5732 FILETIME_TO_U64 (tem1, ft_kernel);
5733 *stime = U64_TO_LISP_TIME (tem1);
5735 FILETIME_TO_U64 (tem2, ft_user);
5736 *utime = U64_TO_LISP_TIME (tem2);
5738 tem3 = tem1 + tem2;
5739 *ttime = U64_TO_LISP_TIME (tem3);
5741 FILETIME_TO_U64 (tem, ft_creation);
5742 /* Process no 4 (System) returns zero creation time. */
5743 if (tem)
5744 tem -= utc_base;
5745 *ctime = U64_TO_LISP_TIME (tem);
5747 if (tem)
5749 FILETIME_TO_U64 (tem3, ft_current);
5750 tem = (tem3 - utc_base) - tem;
5752 *etime = U64_TO_LISP_TIME (tem);
5754 if (tem)
5756 *pcpu = 100.0 * (tem1 + tem2) / tem;
5757 if (*pcpu > 100)
5758 *pcpu = 100.0;
5760 else
5761 *pcpu = 0;
5763 return 1;
5766 Lisp_Object
5767 system_process_attributes (Lisp_Object pid)
5769 struct gcpro gcpro1, gcpro2, gcpro3;
5770 Lisp_Object attrs = Qnil;
5771 Lisp_Object cmd_str, decoded_cmd, tem;
5772 HANDLE h_snapshot, h_proc;
5773 DWORD proc_id;
5774 int found_proc = 0;
5775 char uname[UNLEN+1], gname[GNLEN+1], domain[1025];
5776 DWORD ulength = sizeof (uname), dlength = sizeof (domain), needed;
5777 DWORD glength = sizeof (gname);
5778 HANDLE token = NULL;
5779 SID_NAME_USE user_type;
5780 unsigned char *buf = NULL;
5781 DWORD blen = 0;
5782 TOKEN_USER user_token;
5783 TOKEN_PRIMARY_GROUP group_token;
5784 unsigned euid;
5785 unsigned egid;
5786 PROCESS_MEMORY_COUNTERS mem;
5787 PROCESS_MEMORY_COUNTERS_EX mem_ex;
5788 SIZE_T minrss, maxrss;
5789 MEMORYSTATUS memst;
5790 MEMORY_STATUS_EX memstex;
5791 double totphys = 0.0;
5792 Lisp_Object ctime, stime, utime, etime, ttime;
5793 double pcpu;
5794 BOOL result = FALSE;
5796 CHECK_NUMBER_OR_FLOAT (pid);
5797 proc_id = FLOATP (pid) ? XFLOAT_DATA (pid) : XINT (pid);
5799 h_snapshot = create_toolhelp32_snapshot (TH32CS_SNAPPROCESS, 0);
5801 GCPRO3 (attrs, decoded_cmd, tem);
5803 if (h_snapshot != INVALID_HANDLE_VALUE)
5805 PROCESSENTRY32 pe;
5806 BOOL res;
5808 pe.dwSize = sizeof (PROCESSENTRY32);
5809 for (res = process32_first (h_snapshot, &pe); res;
5810 res = process32_next (h_snapshot, &pe))
5812 if (proc_id == pe.th32ProcessID)
5814 if (proc_id == 0)
5815 decoded_cmd = build_string ("Idle");
5816 else
5818 /* Decode the command name from locale-specific
5819 encoding. */
5820 cmd_str = build_unibyte_string (pe.szExeFile);
5822 decoded_cmd =
5823 code_convert_string_norecord (cmd_str,
5824 Vlocale_coding_system, 0);
5826 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
5827 attrs = Fcons (Fcons (Qppid,
5828 make_fixnum_or_float (pe.th32ParentProcessID)),
5829 attrs);
5830 attrs = Fcons (Fcons (Qpri, make_number (pe.pcPriClassBase)),
5831 attrs);
5832 attrs = Fcons (Fcons (Qthcount,
5833 make_fixnum_or_float (pe.cntThreads)),
5834 attrs);
5835 found_proc = 1;
5836 break;
5840 CloseHandle (h_snapshot);
5843 if (!found_proc)
5845 UNGCPRO;
5846 return Qnil;
5849 h_proc = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
5850 FALSE, proc_id);
5851 /* If we were denied a handle to the process, try again after
5852 enabling the SeDebugPrivilege in our process. */
5853 if (!h_proc)
5855 TOKEN_PRIVILEGES priv_current;
5857 if (enable_privilege (SE_DEBUG_NAME, TRUE, &priv_current))
5859 h_proc = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
5860 FALSE, proc_id);
5861 restore_privilege (&priv_current);
5862 revert_to_self ();
5865 if (h_proc)
5867 result = open_process_token (h_proc, TOKEN_QUERY, &token);
5868 if (result)
5870 result = get_token_information (token, TokenUser, NULL, 0, &blen);
5871 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
5873 buf = xmalloc (blen);
5874 result = get_token_information (token, TokenUser,
5875 (LPVOID)buf, blen, &needed);
5876 if (result)
5878 memcpy (&user_token, buf, sizeof (user_token));
5879 if (!w32_cached_id (user_token.User.Sid, &euid, uname))
5881 euid = get_rid (user_token.User.Sid);
5882 result = lookup_account_sid (NULL, user_token.User.Sid,
5883 uname, &ulength,
5884 domain, &dlength,
5885 &user_type);
5886 if (result)
5887 w32_add_to_cache (user_token.User.Sid, euid, uname);
5888 else
5890 strcpy (uname, "unknown");
5891 result = TRUE;
5894 ulength = strlen (uname);
5898 if (result)
5900 /* Determine a reasonable euid and gid values. */
5901 if (xstrcasecmp ("administrator", uname) == 0)
5903 euid = 500; /* well-known Administrator uid */
5904 egid = 513; /* well-known None gid */
5906 else
5908 /* Get group id and name. */
5909 result = get_token_information (token, TokenPrimaryGroup,
5910 (LPVOID)buf, blen, &needed);
5911 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
5913 buf = xrealloc (buf, blen = needed);
5914 result = get_token_information (token, TokenPrimaryGroup,
5915 (LPVOID)buf, blen, &needed);
5917 if (result)
5919 memcpy (&group_token, buf, sizeof (group_token));
5920 if (!w32_cached_id (group_token.PrimaryGroup, &egid, gname))
5922 egid = get_rid (group_token.PrimaryGroup);
5923 dlength = sizeof (domain);
5924 result =
5925 lookup_account_sid (NULL, group_token.PrimaryGroup,
5926 gname, &glength, NULL, &dlength,
5927 &user_type);
5928 if (result)
5929 w32_add_to_cache (group_token.PrimaryGroup,
5930 egid, gname);
5931 else
5933 strcpy (gname, "None");
5934 result = TRUE;
5937 glength = strlen (gname);
5941 xfree (buf);
5943 if (!result)
5945 if (!is_windows_9x ())
5947 /* We couldn't open the process token, presumably because of
5948 insufficient access rights. Assume this process is run
5949 by the system. */
5950 strcpy (uname, "SYSTEM");
5951 strcpy (gname, "None");
5952 euid = 18; /* SYSTEM */
5953 egid = 513; /* None */
5954 glength = strlen (gname);
5955 ulength = strlen (uname);
5957 /* If we are running under Windows 9X, where security calls are
5958 not supported, we assume all processes are run by the current
5959 user. */
5960 else if (GetUserName (uname, &ulength))
5962 if (xstrcasecmp ("administrator", uname) == 0)
5963 euid = 0;
5964 else
5965 euid = 123;
5966 egid = euid;
5967 strcpy (gname, "None");
5968 glength = strlen (gname);
5969 ulength = strlen (uname);
5971 else
5973 euid = 123;
5974 egid = 123;
5975 strcpy (uname, "administrator");
5976 ulength = strlen (uname);
5977 strcpy (gname, "None");
5978 glength = strlen (gname);
5980 if (token)
5981 CloseHandle (token);
5984 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (euid)), attrs);
5985 tem = make_unibyte_string (uname, ulength);
5986 attrs = Fcons (Fcons (Quser,
5987 code_convert_string_norecord (tem, Vlocale_coding_system, 0)),
5988 attrs);
5989 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (egid)), attrs);
5990 tem = make_unibyte_string (gname, glength);
5991 attrs = Fcons (Fcons (Qgroup,
5992 code_convert_string_norecord (tem, Vlocale_coding_system, 0)),
5993 attrs);
5995 if (global_memory_status_ex (&memstex))
5996 #if __GNUC__ || (defined (_MSC_VER) && _MSC_VER >= 1300)
5997 totphys = memstex.ullTotalPhys / 1024.0;
5998 #else
5999 /* Visual Studio 6 cannot convert an unsigned __int64 type to
6000 double, so we need to do this for it... */
6002 DWORD tot_hi = memstex.ullTotalPhys >> 32;
6003 DWORD tot_md = (memstex.ullTotalPhys & 0x00000000ffffffff) >> 10;
6004 DWORD tot_lo = memstex.ullTotalPhys % 1024;
6006 totphys = tot_hi * 4194304.0 + tot_md + tot_lo / 1024.0;
6008 #endif /* __GNUC__ || _MSC_VER >= 1300 */
6009 else if (global_memory_status (&memst))
6010 totphys = memst.dwTotalPhys / 1024.0;
6012 if (h_proc
6013 && get_process_memory_info (h_proc, (PROCESS_MEMORY_COUNTERS *)&mem_ex,
6014 sizeof (mem_ex)))
6016 SIZE_T rss = mem_ex.WorkingSetSize / 1024;
6018 attrs = Fcons (Fcons (Qmajflt,
6019 make_fixnum_or_float (mem_ex.PageFaultCount)),
6020 attrs);
6021 attrs = Fcons (Fcons (Qvsize,
6022 make_fixnum_or_float (mem_ex.PrivateUsage / 1024)),
6023 attrs);
6024 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (rss)), attrs);
6025 if (totphys)
6026 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
6028 else if (h_proc
6029 && get_process_memory_info (h_proc, &mem, sizeof (mem)))
6031 SIZE_T rss = mem_ex.WorkingSetSize / 1024;
6033 attrs = Fcons (Fcons (Qmajflt,
6034 make_fixnum_or_float (mem.PageFaultCount)),
6035 attrs);
6036 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (rss)), attrs);
6037 if (totphys)
6038 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
6040 else if (h_proc
6041 && get_process_working_set_size (h_proc, &minrss, &maxrss))
6043 DWORD rss = maxrss / 1024;
6045 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (maxrss / 1024)), attrs);
6046 if (totphys)
6047 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
6050 if (process_times (h_proc, &ctime, &etime, &stime, &utime, &ttime, &pcpu))
6052 attrs = Fcons (Fcons (Qutime, utime), attrs);
6053 attrs = Fcons (Fcons (Qstime, stime), attrs);
6054 attrs = Fcons (Fcons (Qtime, ttime), attrs);
6055 attrs = Fcons (Fcons (Qstart, ctime), attrs);
6056 attrs = Fcons (Fcons (Qetime, etime), attrs);
6057 attrs = Fcons (Fcons (Qpcpu, make_float (pcpu)), attrs);
6060 /* FIXME: Retrieve command line by walking the PEB of the process. */
6062 if (h_proc)
6063 CloseHandle (h_proc);
6064 UNGCPRO;
6065 return attrs;
6069 /* Wrappers for winsock functions to map between our file descriptors
6070 and winsock's handles; also set h_errno for convenience.
6072 To allow Emacs to run on systems which don't have winsock support
6073 installed, we dynamically link to winsock on startup if present, and
6074 otherwise provide the minimum necessary functionality
6075 (eg. gethostname). */
6077 /* function pointers for relevant socket functions */
6078 int (PASCAL *pfn_WSAStartup) (WORD wVersionRequired, LPWSADATA lpWSAData);
6079 void (PASCAL *pfn_WSASetLastError) (int iError);
6080 int (PASCAL *pfn_WSAGetLastError) (void);
6081 int (PASCAL *pfn_WSAEventSelect) (SOCKET s, HANDLE hEventObject, long lNetworkEvents);
6082 HANDLE (PASCAL *pfn_WSACreateEvent) (void);
6083 int (PASCAL *pfn_WSACloseEvent) (HANDLE hEvent);
6084 int (PASCAL *pfn_socket) (int af, int type, int protocol);
6085 int (PASCAL *pfn_bind) (SOCKET s, const struct sockaddr *addr, int namelen);
6086 int (PASCAL *pfn_connect) (SOCKET s, const struct sockaddr *addr, int namelen);
6087 int (PASCAL *pfn_ioctlsocket) (SOCKET s, long cmd, u_long *argp);
6088 int (PASCAL *pfn_recv) (SOCKET s, char * buf, int len, int flags);
6089 int (PASCAL *pfn_send) (SOCKET s, const char * buf, int len, int flags);
6090 int (PASCAL *pfn_closesocket) (SOCKET s);
6091 int (PASCAL *pfn_shutdown) (SOCKET s, int how);
6092 int (PASCAL *pfn_WSACleanup) (void);
6094 u_short (PASCAL *pfn_htons) (u_short hostshort);
6095 u_short (PASCAL *pfn_ntohs) (u_short netshort);
6096 unsigned long (PASCAL *pfn_inet_addr) (const char * cp);
6097 int (PASCAL *pfn_gethostname) (char * name, int namelen);
6098 struct hostent * (PASCAL *pfn_gethostbyname) (const char * name);
6099 struct servent * (PASCAL *pfn_getservbyname) (const char * name, const char * proto);
6100 int (PASCAL *pfn_getpeername) (SOCKET s, struct sockaddr *addr, int * namelen);
6101 int (PASCAL *pfn_setsockopt) (SOCKET s, int level, int optname,
6102 const char * optval, int optlen);
6103 int (PASCAL *pfn_listen) (SOCKET s, int backlog);
6104 int (PASCAL *pfn_getsockname) (SOCKET s, struct sockaddr * name,
6105 int * namelen);
6106 SOCKET (PASCAL *pfn_accept) (SOCKET s, struct sockaddr * addr, int * addrlen);
6107 int (PASCAL *pfn_recvfrom) (SOCKET s, char * buf, int len, int flags,
6108 struct sockaddr * from, int * fromlen);
6109 int (PASCAL *pfn_sendto) (SOCKET s, const char * buf, int len, int flags,
6110 const struct sockaddr * to, int tolen);
6112 /* SetHandleInformation is only needed to make sockets non-inheritable. */
6113 BOOL (WINAPI *pfn_SetHandleInformation) (HANDLE object, DWORD mask, DWORD flags);
6114 #ifndef HANDLE_FLAG_INHERIT
6115 #define HANDLE_FLAG_INHERIT 1
6116 #endif
6118 HANDLE winsock_lib;
6119 static int winsock_inuse;
6121 BOOL
6122 term_winsock (void)
6124 if (winsock_lib != NULL && winsock_inuse == 0)
6126 release_listen_threads ();
6127 /* Not sure what would cause WSAENETDOWN, or even if it can happen
6128 after WSAStartup returns successfully, but it seems reasonable
6129 to allow unloading winsock anyway in that case. */
6130 if (pfn_WSACleanup () == 0 ||
6131 pfn_WSAGetLastError () == WSAENETDOWN)
6133 if (FreeLibrary (winsock_lib))
6134 winsock_lib = NULL;
6135 return TRUE;
6138 return FALSE;
6141 BOOL
6142 init_winsock (int load_now)
6144 WSADATA winsockData;
6146 if (winsock_lib != NULL)
6147 return TRUE;
6149 pfn_SetHandleInformation
6150 = (void *) GetProcAddress (GetModuleHandle ("kernel32.dll"),
6151 "SetHandleInformation");
6153 winsock_lib = LoadLibrary ("Ws2_32.dll");
6155 if (winsock_lib != NULL)
6157 /* dynamically link to socket functions */
6159 #define LOAD_PROC(fn) \
6160 if ((pfn_##fn = (void *) GetProcAddress (winsock_lib, #fn)) == NULL) \
6161 goto fail;
6163 LOAD_PROC (WSAStartup);
6164 LOAD_PROC (WSASetLastError);
6165 LOAD_PROC (WSAGetLastError);
6166 LOAD_PROC (WSAEventSelect);
6167 LOAD_PROC (WSACreateEvent);
6168 LOAD_PROC (WSACloseEvent);
6169 LOAD_PROC (socket);
6170 LOAD_PROC (bind);
6171 LOAD_PROC (connect);
6172 LOAD_PROC (ioctlsocket);
6173 LOAD_PROC (recv);
6174 LOAD_PROC (send);
6175 LOAD_PROC (closesocket);
6176 LOAD_PROC (shutdown);
6177 LOAD_PROC (htons);
6178 LOAD_PROC (ntohs);
6179 LOAD_PROC (inet_addr);
6180 LOAD_PROC (gethostname);
6181 LOAD_PROC (gethostbyname);
6182 LOAD_PROC (getservbyname);
6183 LOAD_PROC (getpeername);
6184 LOAD_PROC (WSACleanup);
6185 LOAD_PROC (setsockopt);
6186 LOAD_PROC (listen);
6187 LOAD_PROC (getsockname);
6188 LOAD_PROC (accept);
6189 LOAD_PROC (recvfrom);
6190 LOAD_PROC (sendto);
6191 #undef LOAD_PROC
6193 /* specify version 1.1 of winsock */
6194 if (pfn_WSAStartup (0x101, &winsockData) == 0)
6196 if (winsockData.wVersion != 0x101)
6197 goto fail;
6199 if (!load_now)
6201 /* Report that winsock exists and is usable, but leave
6202 socket functions disabled. I am assuming that calling
6203 WSAStartup does not require any network interaction,
6204 and in particular does not cause or require a dial-up
6205 connection to be established. */
6207 pfn_WSACleanup ();
6208 FreeLibrary (winsock_lib);
6209 winsock_lib = NULL;
6211 winsock_inuse = 0;
6212 return TRUE;
6215 fail:
6216 FreeLibrary (winsock_lib);
6217 winsock_lib = NULL;
6220 return FALSE;
6224 int h_errno = 0;
6226 /* Function to map winsock error codes to errno codes for those errno
6227 code defined in errno.h (errno values not defined by errno.h are
6228 already in nt/inc/sys/socket.h). */
6229 static void
6230 set_errno (void)
6232 int wsa_err;
6234 h_errno = 0;
6235 if (winsock_lib == NULL)
6236 wsa_err = EINVAL;
6237 else
6238 wsa_err = pfn_WSAGetLastError ();
6240 switch (wsa_err)
6242 case WSAEACCES: errno = EACCES; break;
6243 case WSAEBADF: errno = EBADF; break;
6244 case WSAEFAULT: errno = EFAULT; break;
6245 case WSAEINTR: errno = EINTR; break;
6246 case WSAEINVAL: errno = EINVAL; break;
6247 case WSAEMFILE: errno = EMFILE; break;
6248 case WSAENAMETOOLONG: errno = ENAMETOOLONG; break;
6249 case WSAENOTEMPTY: errno = ENOTEMPTY; break;
6250 default: errno = wsa_err; break;
6254 static void
6255 check_errno (void)
6257 h_errno = 0;
6258 if (winsock_lib != NULL)
6259 pfn_WSASetLastError (0);
6262 /* Extend strerror to handle the winsock-specific error codes. */
6263 struct {
6264 int errnum;
6265 char * msg;
6266 } _wsa_errlist[] = {
6267 {WSAEINTR , "Interrupted function call"},
6268 {WSAEBADF , "Bad file descriptor"},
6269 {WSAEACCES , "Permission denied"},
6270 {WSAEFAULT , "Bad address"},
6271 {WSAEINVAL , "Invalid argument"},
6272 {WSAEMFILE , "Too many open files"},
6274 {WSAEWOULDBLOCK , "Resource temporarily unavailable"},
6275 {WSAEINPROGRESS , "Operation now in progress"},
6276 {WSAEALREADY , "Operation already in progress"},
6277 {WSAENOTSOCK , "Socket operation on non-socket"},
6278 {WSAEDESTADDRREQ , "Destination address required"},
6279 {WSAEMSGSIZE , "Message too long"},
6280 {WSAEPROTOTYPE , "Protocol wrong type for socket"},
6281 {WSAENOPROTOOPT , "Bad protocol option"},
6282 {WSAEPROTONOSUPPORT , "Protocol not supported"},
6283 {WSAESOCKTNOSUPPORT , "Socket type not supported"},
6284 {WSAEOPNOTSUPP , "Operation not supported"},
6285 {WSAEPFNOSUPPORT , "Protocol family not supported"},
6286 {WSAEAFNOSUPPORT , "Address family not supported by protocol family"},
6287 {WSAEADDRINUSE , "Address already in use"},
6288 {WSAEADDRNOTAVAIL , "Cannot assign requested address"},
6289 {WSAENETDOWN , "Network is down"},
6290 {WSAENETUNREACH , "Network is unreachable"},
6291 {WSAENETRESET , "Network dropped connection on reset"},
6292 {WSAECONNABORTED , "Software caused connection abort"},
6293 {WSAECONNRESET , "Connection reset by peer"},
6294 {WSAENOBUFS , "No buffer space available"},
6295 {WSAEISCONN , "Socket is already connected"},
6296 {WSAENOTCONN , "Socket is not connected"},
6297 {WSAESHUTDOWN , "Cannot send after socket shutdown"},
6298 {WSAETOOMANYREFS , "Too many references"}, /* not sure */
6299 {WSAETIMEDOUT , "Connection timed out"},
6300 {WSAECONNREFUSED , "Connection refused"},
6301 {WSAELOOP , "Network loop"}, /* not sure */
6302 {WSAENAMETOOLONG , "Name is too long"},
6303 {WSAEHOSTDOWN , "Host is down"},
6304 {WSAEHOSTUNREACH , "No route to host"},
6305 {WSAENOTEMPTY , "Buffer not empty"}, /* not sure */
6306 {WSAEPROCLIM , "Too many processes"},
6307 {WSAEUSERS , "Too many users"}, /* not sure */
6308 {WSAEDQUOT , "Double quote in host name"}, /* really not sure */
6309 {WSAESTALE , "Data is stale"}, /* not sure */
6310 {WSAEREMOTE , "Remote error"}, /* not sure */
6312 {WSASYSNOTREADY , "Network subsystem is unavailable"},
6313 {WSAVERNOTSUPPORTED , "WINSOCK.DLL version out of range"},
6314 {WSANOTINITIALISED , "Winsock not initialized successfully"},
6315 {WSAEDISCON , "Graceful shutdown in progress"},
6316 #ifdef WSAENOMORE
6317 {WSAENOMORE , "No more operations allowed"}, /* not sure */
6318 {WSAECANCELLED , "Operation cancelled"}, /* not sure */
6319 {WSAEINVALIDPROCTABLE , "Invalid procedure table from service provider"},
6320 {WSAEINVALIDPROVIDER , "Invalid service provider version number"},
6321 {WSAEPROVIDERFAILEDINIT , "Unable to initialize a service provider"},
6322 {WSASYSCALLFAILURE , "System call failure"},
6323 {WSASERVICE_NOT_FOUND , "Service not found"}, /* not sure */
6324 {WSATYPE_NOT_FOUND , "Class type not found"},
6325 {WSA_E_NO_MORE , "No more resources available"}, /* really not sure */
6326 {WSA_E_CANCELLED , "Operation already cancelled"}, /* really not sure */
6327 {WSAEREFUSED , "Operation refused"}, /* not sure */
6328 #endif
6330 {WSAHOST_NOT_FOUND , "Host not found"},
6331 {WSATRY_AGAIN , "Authoritative host not found during name lookup"},
6332 {WSANO_RECOVERY , "Non-recoverable error during name lookup"},
6333 {WSANO_DATA , "Valid name, no data record of requested type"},
6335 {-1, NULL}
6338 char *
6339 sys_strerror (int error_no)
6341 int i;
6342 static char unknown_msg[40];
6344 if (error_no >= 0 && error_no < sys_nerr)
6345 return sys_errlist[error_no];
6347 for (i = 0; _wsa_errlist[i].errnum >= 0; i++)
6348 if (_wsa_errlist[i].errnum == error_no)
6349 return _wsa_errlist[i].msg;
6351 sprintf (unknown_msg, "Unidentified error: %d", error_no);
6352 return unknown_msg;
6355 /* [andrewi 3-May-96] I've had conflicting results using both methods,
6356 but I believe the method of keeping the socket handle separate (and
6357 insuring it is not inheritable) is the correct one. */
6359 #define SOCK_HANDLE(fd) ((SOCKET) fd_info[fd].hnd)
6361 static int socket_to_fd (SOCKET s);
6364 sys_socket (int af, int type, int protocol)
6366 SOCKET s;
6368 if (winsock_lib == NULL)
6370 errno = ENETDOWN;
6371 return INVALID_SOCKET;
6374 check_errno ();
6376 /* call the real socket function */
6377 s = pfn_socket (af, type, protocol);
6379 if (s != INVALID_SOCKET)
6380 return socket_to_fd (s);
6382 set_errno ();
6383 return -1;
6386 /* Convert a SOCKET to a file descriptor. */
6387 static int
6388 socket_to_fd (SOCKET s)
6390 int fd;
6391 child_process * cp;
6393 /* Although under NT 3.5 _open_osfhandle will accept a socket
6394 handle, if opened with SO_OPENTYPE == SO_SYNCHRONOUS_NONALERT,
6395 that does not work under NT 3.1. However, we can get the same
6396 effect by using a backdoor function to replace an existing
6397 descriptor handle with the one we want. */
6399 /* allocate a file descriptor (with appropriate flags) */
6400 fd = _open ("NUL:", _O_RDWR);
6401 if (fd >= 0)
6403 /* Make a non-inheritable copy of the socket handle. Note
6404 that it is possible that sockets aren't actually kernel
6405 handles, which appears to be the case on Windows 9x when
6406 the MS Proxy winsock client is installed. */
6408 /* Apparently there is a bug in NT 3.51 with some service
6409 packs, which prevents using DuplicateHandle to make a
6410 socket handle non-inheritable (causes WSACleanup to
6411 hang). The work-around is to use SetHandleInformation
6412 instead if it is available and implemented. */
6413 if (pfn_SetHandleInformation)
6415 pfn_SetHandleInformation ((HANDLE) s, HANDLE_FLAG_INHERIT, 0);
6417 else
6419 HANDLE parent = GetCurrentProcess ();
6420 HANDLE new_s = INVALID_HANDLE_VALUE;
6422 if (DuplicateHandle (parent,
6423 (HANDLE) s,
6424 parent,
6425 &new_s,
6427 FALSE,
6428 DUPLICATE_SAME_ACCESS))
6430 /* It is possible that DuplicateHandle succeeds even
6431 though the socket wasn't really a kernel handle,
6432 because a real handle has the same value. So
6433 test whether the new handle really is a socket. */
6434 long nonblocking = 0;
6435 if (pfn_ioctlsocket ((SOCKET) new_s, FIONBIO, &nonblocking) == 0)
6437 pfn_closesocket (s);
6438 s = (SOCKET) new_s;
6440 else
6442 CloseHandle (new_s);
6447 eassert (fd < MAXDESC);
6448 fd_info[fd].hnd = (HANDLE) s;
6450 /* set our own internal flags */
6451 fd_info[fd].flags = FILE_SOCKET | FILE_BINARY | FILE_READ | FILE_WRITE;
6453 cp = new_child ();
6454 if (cp)
6456 cp->fd = fd;
6457 cp->status = STATUS_READ_ACKNOWLEDGED;
6459 /* attach child_process to fd_info */
6460 if (fd_info[ fd ].cp != NULL)
6462 DebPrint (("sys_socket: fd_info[%d] apparently in use!\n", fd));
6463 emacs_abort ();
6466 fd_info[ fd ].cp = cp;
6468 /* success! */
6469 winsock_inuse++; /* count open sockets */
6470 return fd;
6473 /* clean up */
6474 _close (fd);
6476 else
6477 pfn_closesocket (s);
6478 errno = EMFILE;
6479 return -1;
6483 sys_bind (int s, const struct sockaddr * addr, int namelen)
6485 if (winsock_lib == NULL)
6487 errno = ENOTSOCK;
6488 return SOCKET_ERROR;
6491 check_errno ();
6492 if (fd_info[s].flags & FILE_SOCKET)
6494 int rc = pfn_bind (SOCK_HANDLE (s), addr, namelen);
6495 if (rc == SOCKET_ERROR)
6496 set_errno ();
6497 return rc;
6499 errno = ENOTSOCK;
6500 return SOCKET_ERROR;
6504 sys_connect (int s, const struct sockaddr * name, int namelen)
6506 if (winsock_lib == NULL)
6508 errno = ENOTSOCK;
6509 return SOCKET_ERROR;
6512 check_errno ();
6513 if (fd_info[s].flags & FILE_SOCKET)
6515 int rc = pfn_connect (SOCK_HANDLE (s), name, namelen);
6516 if (rc == SOCKET_ERROR)
6517 set_errno ();
6518 return rc;
6520 errno = ENOTSOCK;
6521 return SOCKET_ERROR;
6524 u_short
6525 sys_htons (u_short hostshort)
6527 return (winsock_lib != NULL) ?
6528 pfn_htons (hostshort) : hostshort;
6531 u_short
6532 sys_ntohs (u_short netshort)
6534 return (winsock_lib != NULL) ?
6535 pfn_ntohs (netshort) : netshort;
6538 unsigned long
6539 sys_inet_addr (const char * cp)
6541 return (winsock_lib != NULL) ?
6542 pfn_inet_addr (cp) : INADDR_NONE;
6546 sys_gethostname (char * name, int namelen)
6548 if (winsock_lib != NULL)
6550 int retval;
6552 check_errno ();
6553 retval = pfn_gethostname (name, namelen);
6554 if (retval == SOCKET_ERROR)
6555 set_errno ();
6556 return retval;
6559 if (namelen > MAX_COMPUTERNAME_LENGTH)
6560 return !GetComputerName (name, (DWORD *)&namelen);
6562 errno = EFAULT;
6563 return SOCKET_ERROR;
6566 struct hostent *
6567 sys_gethostbyname (const char * name)
6569 struct hostent * host;
6570 int h_err = h_errno;
6572 if (winsock_lib == NULL)
6574 h_errno = NO_RECOVERY;
6575 errno = ENETDOWN;
6576 return NULL;
6579 check_errno ();
6580 host = pfn_gethostbyname (name);
6581 if (!host)
6583 set_errno ();
6584 h_errno = errno;
6586 else
6587 h_errno = h_err;
6588 return host;
6591 struct servent *
6592 sys_getservbyname (const char * name, const char * proto)
6594 struct servent * serv;
6596 if (winsock_lib == NULL)
6598 errno = ENETDOWN;
6599 return NULL;
6602 check_errno ();
6603 serv = pfn_getservbyname (name, proto);
6604 if (!serv)
6605 set_errno ();
6606 return serv;
6610 sys_getpeername (int s, struct sockaddr *addr, int * namelen)
6612 if (winsock_lib == NULL)
6614 errno = ENETDOWN;
6615 return SOCKET_ERROR;
6618 check_errno ();
6619 if (fd_info[s].flags & FILE_SOCKET)
6621 int rc = pfn_getpeername (SOCK_HANDLE (s), addr, namelen);
6622 if (rc == SOCKET_ERROR)
6623 set_errno ();
6624 return rc;
6626 errno = ENOTSOCK;
6627 return SOCKET_ERROR;
6631 sys_shutdown (int s, int how)
6633 if (winsock_lib == NULL)
6635 errno = ENETDOWN;
6636 return SOCKET_ERROR;
6639 check_errno ();
6640 if (fd_info[s].flags & FILE_SOCKET)
6642 int rc = pfn_shutdown (SOCK_HANDLE (s), how);
6643 if (rc == SOCKET_ERROR)
6644 set_errno ();
6645 return rc;
6647 errno = ENOTSOCK;
6648 return SOCKET_ERROR;
6652 sys_setsockopt (int s, int level, int optname, const void * optval, int optlen)
6654 if (winsock_lib == NULL)
6656 errno = ENETDOWN;
6657 return SOCKET_ERROR;
6660 check_errno ();
6661 if (fd_info[s].flags & FILE_SOCKET)
6663 int rc = pfn_setsockopt (SOCK_HANDLE (s), level, optname,
6664 (const char *)optval, optlen);
6665 if (rc == SOCKET_ERROR)
6666 set_errno ();
6667 return rc;
6669 errno = ENOTSOCK;
6670 return SOCKET_ERROR;
6674 sys_listen (int s, int backlog)
6676 if (winsock_lib == NULL)
6678 errno = ENETDOWN;
6679 return SOCKET_ERROR;
6682 check_errno ();
6683 if (fd_info[s].flags & FILE_SOCKET)
6685 int rc = pfn_listen (SOCK_HANDLE (s), backlog);
6686 if (rc == SOCKET_ERROR)
6687 set_errno ();
6688 else
6689 fd_info[s].flags |= FILE_LISTEN;
6690 return rc;
6692 errno = ENOTSOCK;
6693 return SOCKET_ERROR;
6697 sys_getsockname (int s, struct sockaddr * name, int * namelen)
6699 if (winsock_lib == NULL)
6701 errno = ENETDOWN;
6702 return SOCKET_ERROR;
6705 check_errno ();
6706 if (fd_info[s].flags & FILE_SOCKET)
6708 int rc = pfn_getsockname (SOCK_HANDLE (s), name, namelen);
6709 if (rc == SOCKET_ERROR)
6710 set_errno ();
6711 return rc;
6713 errno = ENOTSOCK;
6714 return SOCKET_ERROR;
6718 sys_accept (int s, struct sockaddr * addr, int * addrlen)
6720 if (winsock_lib == NULL)
6722 errno = ENETDOWN;
6723 return -1;
6726 check_errno ();
6727 if (fd_info[s].flags & FILE_LISTEN)
6729 SOCKET t = pfn_accept (SOCK_HANDLE (s), addr, addrlen);
6730 int fd = -1;
6731 if (t == INVALID_SOCKET)
6732 set_errno ();
6733 else
6734 fd = socket_to_fd (t);
6736 if (fd >= 0)
6738 fd_info[s].cp->status = STATUS_READ_ACKNOWLEDGED;
6739 ResetEvent (fd_info[s].cp->char_avail);
6741 return fd;
6743 errno = ENOTSOCK;
6744 return -1;
6748 sys_recvfrom (int s, char * buf, int len, int flags,
6749 struct sockaddr * from, int * fromlen)
6751 if (winsock_lib == NULL)
6753 errno = ENETDOWN;
6754 return SOCKET_ERROR;
6757 check_errno ();
6758 if (fd_info[s].flags & FILE_SOCKET)
6760 int rc = pfn_recvfrom (SOCK_HANDLE (s), buf, len, flags, from, fromlen);
6761 if (rc == SOCKET_ERROR)
6762 set_errno ();
6763 return rc;
6765 errno = ENOTSOCK;
6766 return SOCKET_ERROR;
6770 sys_sendto (int s, const char * buf, int len, int flags,
6771 const struct sockaddr * to, int tolen)
6773 if (winsock_lib == NULL)
6775 errno = ENETDOWN;
6776 return SOCKET_ERROR;
6779 check_errno ();
6780 if (fd_info[s].flags & FILE_SOCKET)
6782 int rc = pfn_sendto (SOCK_HANDLE (s), buf, len, flags, to, tolen);
6783 if (rc == SOCKET_ERROR)
6784 set_errno ();
6785 return rc;
6787 errno = ENOTSOCK;
6788 return SOCKET_ERROR;
6791 /* Windows does not have an fcntl function. Provide an implementation
6792 good enough for Emacs. */
6794 fcntl (int s, int cmd, int options)
6796 /* In the w32 Emacs port, fcntl (fd, F_DUPFD_CLOEXEC, fd1) is always
6797 invoked in a context where fd1 is closed and all descriptors less
6798 than fd1 are open, so sys_dup is an adequate implementation. */
6799 if (cmd == F_DUPFD_CLOEXEC)
6800 return sys_dup (s);
6802 if (winsock_lib == NULL)
6804 errno = ENETDOWN;
6805 return -1;
6808 check_errno ();
6809 if (fd_info[s].flags & FILE_SOCKET)
6811 if (cmd == F_SETFL && options == O_NONBLOCK)
6813 unsigned long nblock = 1;
6814 int rc = pfn_ioctlsocket (SOCK_HANDLE (s), FIONBIO, &nblock);
6815 if (rc == SOCKET_ERROR)
6816 set_errno ();
6817 /* Keep track of the fact that we set this to non-blocking. */
6818 fd_info[s].flags |= FILE_NDELAY;
6819 return rc;
6821 else
6823 errno = EINVAL;
6824 return SOCKET_ERROR;
6827 errno = ENOTSOCK;
6828 return SOCKET_ERROR;
6832 /* Shadow main io functions: we need to handle pipes and sockets more
6833 intelligently, and implement non-blocking mode as well. */
6836 sys_close (int fd)
6838 int rc;
6840 if (fd < 0)
6842 errno = EBADF;
6843 return -1;
6846 if (fd < MAXDESC && fd_info[fd].cp)
6848 child_process * cp = fd_info[fd].cp;
6850 fd_info[fd].cp = NULL;
6852 if (CHILD_ACTIVE (cp))
6854 /* if last descriptor to active child_process then cleanup */
6855 int i;
6856 for (i = 0; i < MAXDESC; i++)
6858 if (i == fd)
6859 continue;
6860 if (fd_info[i].cp == cp)
6861 break;
6863 if (i == MAXDESC)
6865 if (fd_info[fd].flags & FILE_SOCKET)
6867 if (winsock_lib == NULL) emacs_abort ();
6869 pfn_shutdown (SOCK_HANDLE (fd), 2);
6870 rc = pfn_closesocket (SOCK_HANDLE (fd));
6872 winsock_inuse--; /* count open sockets */
6874 /* If the process handle is NULL, it's either a socket
6875 or serial connection, or a subprocess that was
6876 already reaped by reap_subprocess, but whose
6877 resources were not yet freed, because its output was
6878 not fully read yet by the time it was reaped. (This
6879 usually happens with async subprocesses whose output
6880 is being read by Emacs.) Otherwise, this process was
6881 not reaped yet, so we set its FD to a negative value
6882 to make sure sys_select will eventually get to
6883 calling the SIGCHLD handler for it, which will then
6884 invoke waitpid and reap_subprocess. */
6885 if (cp->procinfo.hProcess == NULL)
6886 delete_child (cp);
6887 else
6888 cp->fd = -1;
6893 if (fd >= 0 && fd < MAXDESC)
6894 fd_info[fd].flags = 0;
6896 /* Note that sockets do not need special treatment here (at least on
6897 NT and Windows 95 using the standard tcp/ip stacks) - it appears that
6898 closesocket is equivalent to CloseHandle, which is to be expected
6899 because socket handles are fully fledged kernel handles. */
6900 rc = _close (fd);
6902 return rc;
6906 sys_dup (int fd)
6908 int new_fd;
6910 new_fd = _dup (fd);
6911 if (new_fd >= 0 && new_fd < MAXDESC)
6913 /* duplicate our internal info as well */
6914 fd_info[new_fd] = fd_info[fd];
6916 return new_fd;
6920 sys_dup2 (int src, int dst)
6922 int rc;
6924 if (dst < 0 || dst >= MAXDESC)
6926 errno = EBADF;
6927 return -1;
6930 /* make sure we close the destination first if it's a pipe or socket */
6931 if (src != dst && fd_info[dst].flags != 0)
6932 sys_close (dst);
6934 rc = _dup2 (src, dst);
6935 if (rc == 0)
6937 /* duplicate our internal info as well */
6938 fd_info[dst] = fd_info[src];
6940 return rc;
6944 pipe2 (int * phandles, int pipe2_flags)
6946 int rc;
6947 unsigned flags;
6949 eassert (pipe2_flags == O_CLOEXEC);
6951 /* make pipe handles non-inheritable; when we spawn a child, we
6952 replace the relevant handle with an inheritable one. Also put
6953 pipes into binary mode; we will do text mode translation ourselves
6954 if required. */
6955 rc = _pipe (phandles, 0, _O_NOINHERIT | _O_BINARY);
6957 if (rc == 0)
6959 /* Protect against overflow, since Windows can open more handles than
6960 our fd_info array has room for. */
6961 if (phandles[0] >= MAXDESC || phandles[1] >= MAXDESC)
6963 _close (phandles[0]);
6964 _close (phandles[1]);
6965 errno = EMFILE;
6966 rc = -1;
6968 else
6970 flags = FILE_PIPE | FILE_READ | FILE_BINARY;
6971 fd_info[phandles[0]].flags = flags;
6973 flags = FILE_PIPE | FILE_WRITE | FILE_BINARY;
6974 fd_info[phandles[1]].flags = flags;
6978 return rc;
6981 /* Function to do blocking read of one byte, needed to implement
6982 select. It is only allowed on communication ports, sockets, or
6983 pipes. */
6985 _sys_read_ahead (int fd)
6987 child_process * cp;
6988 int rc;
6990 if (fd < 0 || fd >= MAXDESC)
6991 return STATUS_READ_ERROR;
6993 cp = fd_info[fd].cp;
6995 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
6996 return STATUS_READ_ERROR;
6998 if ((fd_info[fd].flags & (FILE_PIPE | FILE_SERIAL | FILE_SOCKET)) == 0
6999 || (fd_info[fd].flags & FILE_READ) == 0)
7001 DebPrint (("_sys_read_ahead: internal error: fd %d is not a pipe, serial port, or socket!\n", fd));
7002 emacs_abort ();
7005 cp->status = STATUS_READ_IN_PROGRESS;
7007 if (fd_info[fd].flags & FILE_PIPE)
7009 rc = _read (fd, &cp->chr, sizeof (char));
7011 /* Give subprocess time to buffer some more output for us before
7012 reporting that input is available; we need this because Windows 95
7013 connects DOS programs to pipes by making the pipe appear to be
7014 the normal console stdout - as a result most DOS programs will
7015 write to stdout without buffering, ie. one character at a
7016 time. Even some W32 programs do this - "dir" in a command
7017 shell on NT is very slow if we don't do this. */
7018 if (rc > 0)
7020 int wait = w32_pipe_read_delay;
7022 if (wait > 0)
7023 Sleep (wait);
7024 else if (wait < 0)
7025 while (++wait <= 0)
7026 /* Yield remainder of our time slice, effectively giving a
7027 temporary priority boost to the child process. */
7028 Sleep (0);
7031 else if (fd_info[fd].flags & FILE_SERIAL)
7033 HANDLE hnd = fd_info[fd].hnd;
7034 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_read;
7035 COMMTIMEOUTS ct;
7037 /* Configure timeouts for blocking read. */
7038 if (!GetCommTimeouts (hnd, &ct))
7040 cp->status = STATUS_READ_ERROR;
7041 return STATUS_READ_ERROR;
7043 ct.ReadIntervalTimeout = 0;
7044 ct.ReadTotalTimeoutMultiplier = 0;
7045 ct.ReadTotalTimeoutConstant = 0;
7046 if (!SetCommTimeouts (hnd, &ct))
7048 cp->status = STATUS_READ_ERROR;
7049 return STATUS_READ_ERROR;
7052 if (!ReadFile (hnd, &cp->chr, sizeof (char), (DWORD*) &rc, ovl))
7054 if (GetLastError () != ERROR_IO_PENDING)
7056 cp->status = STATUS_READ_ERROR;
7057 return STATUS_READ_ERROR;
7059 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &rc, TRUE))
7061 cp->status = STATUS_READ_ERROR;
7062 return STATUS_READ_ERROR;
7066 else if (fd_info[fd].flags & FILE_SOCKET)
7068 unsigned long nblock = 0;
7069 /* We always want this to block, so temporarily disable NDELAY. */
7070 if (fd_info[fd].flags & FILE_NDELAY)
7071 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
7073 rc = pfn_recv (SOCK_HANDLE (fd), &cp->chr, sizeof (char), 0);
7075 if (fd_info[fd].flags & FILE_NDELAY)
7077 nblock = 1;
7078 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
7082 if (rc == sizeof (char))
7083 cp->status = STATUS_READ_SUCCEEDED;
7084 else
7085 cp->status = STATUS_READ_FAILED;
7087 return cp->status;
7091 _sys_wait_accept (int fd)
7093 HANDLE hEv;
7094 child_process * cp;
7095 int rc;
7097 if (fd < 0 || fd >= MAXDESC)
7098 return STATUS_READ_ERROR;
7100 cp = fd_info[fd].cp;
7102 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
7103 return STATUS_READ_ERROR;
7105 cp->status = STATUS_READ_FAILED;
7107 hEv = pfn_WSACreateEvent ();
7108 rc = pfn_WSAEventSelect (SOCK_HANDLE (fd), hEv, FD_ACCEPT);
7109 if (rc != SOCKET_ERROR)
7111 do {
7112 rc = WaitForSingleObject (hEv, 500);
7113 Sleep (5);
7114 } while (rc == WAIT_TIMEOUT
7115 && cp->status != STATUS_READ_ERROR
7116 && cp->char_avail);
7117 pfn_WSAEventSelect (SOCK_HANDLE (fd), NULL, 0);
7118 if (rc == WAIT_OBJECT_0)
7119 cp->status = STATUS_READ_SUCCEEDED;
7121 pfn_WSACloseEvent (hEv);
7123 return cp->status;
7127 sys_read (int fd, char * buffer, unsigned int count)
7129 int nchars;
7130 int to_read;
7131 DWORD waiting;
7132 char * orig_buffer = buffer;
7134 if (fd < 0)
7136 errno = EBADF;
7137 return -1;
7140 if (fd < MAXDESC && fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET | FILE_SERIAL))
7142 child_process *cp = fd_info[fd].cp;
7144 if ((fd_info[fd].flags & FILE_READ) == 0)
7146 errno = EBADF;
7147 return -1;
7150 nchars = 0;
7152 /* re-read CR carried over from last read */
7153 if (fd_info[fd].flags & FILE_LAST_CR)
7155 if (fd_info[fd].flags & FILE_BINARY) emacs_abort ();
7156 *buffer++ = 0x0d;
7157 count--;
7158 nchars++;
7159 fd_info[fd].flags &= ~FILE_LAST_CR;
7162 /* presence of a child_process structure means we are operating in
7163 non-blocking mode - otherwise we just call _read directly.
7164 Note that the child_process structure might be missing because
7165 reap_subprocess has been called; in this case the pipe is
7166 already broken, so calling _read on it is okay. */
7167 if (cp)
7169 int current_status = cp->status;
7171 switch (current_status)
7173 case STATUS_READ_FAILED:
7174 case STATUS_READ_ERROR:
7175 /* report normal EOF if nothing in buffer */
7176 if (nchars <= 0)
7177 fd_info[fd].flags |= FILE_AT_EOF;
7178 return nchars;
7180 case STATUS_READ_READY:
7181 case STATUS_READ_IN_PROGRESS:
7182 DebPrint (("sys_read called when read is in progress\n"));
7183 errno = EWOULDBLOCK;
7184 return -1;
7186 case STATUS_READ_SUCCEEDED:
7187 /* consume read-ahead char */
7188 *buffer++ = cp->chr;
7189 count--;
7190 nchars++;
7191 cp->status = STATUS_READ_ACKNOWLEDGED;
7192 ResetEvent (cp->char_avail);
7194 case STATUS_READ_ACKNOWLEDGED:
7195 break;
7197 default:
7198 DebPrint (("sys_read: bad status %d\n", current_status));
7199 errno = EBADF;
7200 return -1;
7203 if (fd_info[fd].flags & FILE_PIPE)
7205 PeekNamedPipe ((HANDLE) _get_osfhandle (fd), NULL, 0, NULL, &waiting, NULL);
7206 to_read = min (waiting, (DWORD) count);
7208 if (to_read > 0)
7209 nchars += _read (fd, buffer, to_read);
7211 else if (fd_info[fd].flags & FILE_SERIAL)
7213 HANDLE hnd = fd_info[fd].hnd;
7214 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_read;
7215 int rc = 0;
7216 COMMTIMEOUTS ct;
7218 if (count > 0)
7220 /* Configure timeouts for non-blocking read. */
7221 if (!GetCommTimeouts (hnd, &ct))
7223 errno = EIO;
7224 return -1;
7226 ct.ReadIntervalTimeout = MAXDWORD;
7227 ct.ReadTotalTimeoutMultiplier = 0;
7228 ct.ReadTotalTimeoutConstant = 0;
7229 if (!SetCommTimeouts (hnd, &ct))
7231 errno = EIO;
7232 return -1;
7235 if (!ResetEvent (ovl->hEvent))
7237 errno = EIO;
7238 return -1;
7240 if (!ReadFile (hnd, buffer, count, (DWORD*) &rc, ovl))
7242 if (GetLastError () != ERROR_IO_PENDING)
7244 errno = EIO;
7245 return -1;
7247 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &rc, TRUE))
7249 errno = EIO;
7250 return -1;
7253 nchars += rc;
7256 else /* FILE_SOCKET */
7258 if (winsock_lib == NULL) emacs_abort ();
7260 /* do the equivalent of a non-blocking read */
7261 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONREAD, &waiting);
7262 if (waiting == 0 && nchars == 0)
7264 errno = EWOULDBLOCK;
7265 return -1;
7268 if (waiting)
7270 /* always use binary mode for sockets */
7271 int res = pfn_recv (SOCK_HANDLE (fd), buffer, count, 0);
7272 if (res == SOCKET_ERROR)
7274 DebPrint (("sys_read.recv failed with error %d on socket %ld\n",
7275 pfn_WSAGetLastError (), SOCK_HANDLE (fd)));
7276 set_errno ();
7277 return -1;
7279 nchars += res;
7283 else
7285 int nread = _read (fd, buffer, count);
7286 if (nread >= 0)
7287 nchars += nread;
7288 else if (nchars == 0)
7289 nchars = nread;
7292 if (nchars <= 0)
7293 fd_info[fd].flags |= FILE_AT_EOF;
7294 /* Perform text mode translation if required. */
7295 else if ((fd_info[fd].flags & FILE_BINARY) == 0)
7297 nchars = crlf_to_lf (nchars, orig_buffer);
7298 /* If buffer contains only CR, return that. To be absolutely
7299 sure we should attempt to read the next char, but in
7300 practice a CR to be followed by LF would not appear by
7301 itself in the buffer. */
7302 if (nchars > 1 && orig_buffer[nchars - 1] == 0x0d)
7304 fd_info[fd].flags |= FILE_LAST_CR;
7305 nchars--;
7309 else
7310 nchars = _read (fd, buffer, count);
7312 return nchars;
7315 /* From w32xfns.c */
7316 extern HANDLE interrupt_handle;
7318 /* For now, don't bother with a non-blocking mode */
7320 sys_write (int fd, const void * buffer, unsigned int count)
7322 int nchars;
7324 if (fd < 0)
7326 errno = EBADF;
7327 return -1;
7330 if (fd < MAXDESC && fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET | FILE_SERIAL))
7332 if ((fd_info[fd].flags & FILE_WRITE) == 0)
7334 errno = EBADF;
7335 return -1;
7338 /* Perform text mode translation if required. */
7339 if ((fd_info[fd].flags & FILE_BINARY) == 0)
7341 char * tmpbuf = alloca (count * 2);
7342 unsigned char * src = (void *)buffer;
7343 unsigned char * dst = tmpbuf;
7344 int nbytes = count;
7346 while (1)
7348 unsigned char *next;
7349 /* copy next line or remaining bytes */
7350 next = _memccpy (dst, src, '\n', nbytes);
7351 if (next)
7353 /* copied one line ending with '\n' */
7354 int copied = next - dst;
7355 nbytes -= copied;
7356 src += copied;
7357 /* insert '\r' before '\n' */
7358 next[-1] = '\r';
7359 next[0] = '\n';
7360 dst = next + 1;
7361 count++;
7363 else
7364 /* copied remaining partial line -> now finished */
7365 break;
7367 buffer = tmpbuf;
7371 if (fd < MAXDESC && fd_info[fd].flags & FILE_SERIAL)
7373 HANDLE hnd = (HANDLE) _get_osfhandle (fd);
7374 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_write;
7375 HANDLE wait_hnd[2] = { interrupt_handle, ovl->hEvent };
7376 DWORD active = 0;
7378 if (!WriteFile (hnd, buffer, count, (DWORD*) &nchars, ovl))
7380 if (GetLastError () != ERROR_IO_PENDING)
7382 errno = EIO;
7383 return -1;
7385 if (detect_input_pending ())
7386 active = MsgWaitForMultipleObjects (2, wait_hnd, FALSE, INFINITE,
7387 QS_ALLINPUT);
7388 else
7389 active = WaitForMultipleObjects (2, wait_hnd, FALSE, INFINITE);
7390 if (active == WAIT_OBJECT_0)
7391 { /* User pressed C-g, cancel write, then leave. Don't bother
7392 cleaning up as we may only get stuck in buggy drivers. */
7393 PurgeComm (hnd, PURGE_TXABORT | PURGE_TXCLEAR);
7394 CancelIo (hnd);
7395 errno = EIO;
7396 return -1;
7398 if (active == WAIT_OBJECT_0 + 1
7399 && !GetOverlappedResult (hnd, ovl, (DWORD*) &nchars, TRUE))
7401 errno = EIO;
7402 return -1;
7406 else if (fd < MAXDESC && fd_info[fd].flags & FILE_SOCKET)
7408 unsigned long nblock = 0;
7409 if (winsock_lib == NULL) emacs_abort ();
7411 /* TODO: implement select() properly so non-blocking I/O works. */
7412 /* For now, make sure the write blocks. */
7413 if (fd_info[fd].flags & FILE_NDELAY)
7414 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
7416 nchars = pfn_send (SOCK_HANDLE (fd), buffer, count, 0);
7418 /* Set the socket back to non-blocking if it was before,
7419 for other operations that support it. */
7420 if (fd_info[fd].flags & FILE_NDELAY)
7422 nblock = 1;
7423 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
7426 if (nchars == SOCKET_ERROR)
7428 DebPrint (("sys_write.send failed with error %d on socket %ld\n",
7429 pfn_WSAGetLastError (), SOCK_HANDLE (fd)));
7430 set_errno ();
7433 else
7435 /* Some networked filesystems don't like too large writes, so
7436 break them into smaller chunks. See the Comments section of
7437 the MSDN documentation of WriteFile for details behind the
7438 choice of the value of CHUNK below. See also the thread
7439 http://thread.gmane.org/gmane.comp.version-control.git/145294
7440 in the git mailing list. */
7441 const unsigned char *p = buffer;
7442 const unsigned chunk = 30 * 1024 * 1024;
7444 nchars = 0;
7445 while (count > 0)
7447 unsigned this_chunk = count < chunk ? count : chunk;
7448 int n = _write (fd, p, this_chunk);
7450 nchars += n;
7451 if (n < 0)
7453 nchars = n;
7454 break;
7456 else if (n < this_chunk)
7457 break;
7458 count -= n;
7459 p += n;
7463 return nchars;
7467 /* Emulation of SIOCGIFCONF and getifaddrs, see process.c. */
7469 extern Lisp_Object conv_sockaddr_to_lisp (struct sockaddr *, int);
7471 /* Return information about network interface IFNAME, or about all
7472 interfaces (if IFNAME is nil). */
7473 static Lisp_Object
7474 network_interface_get_info (Lisp_Object ifname)
7476 ULONG ainfo_len = sizeof (IP_ADAPTER_INFO);
7477 IP_ADAPTER_INFO *adapter, *ainfo = xmalloc (ainfo_len);
7478 DWORD retval = get_adapters_info (ainfo, &ainfo_len);
7479 Lisp_Object res = Qnil;
7481 if (retval == ERROR_BUFFER_OVERFLOW)
7483 ainfo = xrealloc (ainfo, ainfo_len);
7484 retval = get_adapters_info (ainfo, &ainfo_len);
7487 if (retval == ERROR_SUCCESS)
7489 int eth_count = 0, tr_count = 0, fddi_count = 0, ppp_count = 0;
7490 int sl_count = 0, wlan_count = 0, lo_count = 0, ifx_count = 0;
7491 int if_num;
7492 struct sockaddr_in sa;
7494 /* For the below, we need some winsock functions, so make sure
7495 the winsock DLL is loaded. If we cannot successfully load
7496 it, they will have no use of the information we provide,
7497 anyway, so punt. */
7498 if (!winsock_lib && !init_winsock (1))
7499 goto done;
7501 for (adapter = ainfo; adapter; adapter = adapter->Next)
7503 char namebuf[MAX_ADAPTER_NAME_LENGTH + 4];
7504 u_long ip_addr;
7505 /* Present Unix-compatible interface names, instead of the
7506 Windows names, which are really GUIDs not readable by
7507 humans. */
7508 static const char *ifmt[] = {
7509 "eth%d", "tr%d", "fddi%d", "ppp%d", "sl%d", "wlan%d",
7510 "lo", "ifx%d"
7512 enum {
7513 NONE = -1,
7514 ETHERNET = 0,
7515 TOKENRING = 1,
7516 FDDI = 2,
7517 PPP = 3,
7518 SLIP = 4,
7519 WLAN = 5,
7520 LOOPBACK = 6,
7521 OTHER_IF = 7
7522 } ifmt_idx;
7524 switch (adapter->Type)
7526 case MIB_IF_TYPE_ETHERNET:
7527 /* Windows before Vista reports wireless adapters as
7528 Ethernet. Work around by looking at the Description
7529 string. */
7530 if (strstr (adapter->Description, "Wireless "))
7532 ifmt_idx = WLAN;
7533 if_num = wlan_count++;
7535 else
7537 ifmt_idx = ETHERNET;
7538 if_num = eth_count++;
7540 break;
7541 case MIB_IF_TYPE_TOKENRING:
7542 ifmt_idx = TOKENRING;
7543 if_num = tr_count++;
7544 break;
7545 case MIB_IF_TYPE_FDDI:
7546 ifmt_idx = FDDI;
7547 if_num = fddi_count++;
7548 break;
7549 case MIB_IF_TYPE_PPP:
7550 ifmt_idx = PPP;
7551 if_num = ppp_count++;
7552 break;
7553 case MIB_IF_TYPE_SLIP:
7554 ifmt_idx = SLIP;
7555 if_num = sl_count++;
7556 break;
7557 case IF_TYPE_IEEE80211:
7558 ifmt_idx = WLAN;
7559 if_num = wlan_count++;
7560 break;
7561 case MIB_IF_TYPE_LOOPBACK:
7562 if (lo_count < 0)
7564 ifmt_idx = LOOPBACK;
7565 if_num = lo_count++;
7567 else
7568 ifmt_idx = NONE;
7569 break;
7570 default:
7571 ifmt_idx = OTHER_IF;
7572 if_num = ifx_count++;
7573 break;
7575 if (ifmt_idx == NONE)
7576 continue;
7577 sprintf (namebuf, ifmt[ifmt_idx], if_num);
7579 sa.sin_family = AF_INET;
7580 ip_addr = sys_inet_addr (adapter->IpAddressList.IpAddress.String);
7581 if (ip_addr == INADDR_NONE)
7583 /* Bogus address, skip this interface. */
7584 continue;
7586 sa.sin_addr.s_addr = ip_addr;
7587 sa.sin_port = 0;
7588 if (NILP (ifname))
7589 res = Fcons (Fcons (build_string (namebuf),
7590 conv_sockaddr_to_lisp ((struct sockaddr*) &sa,
7591 sizeof (struct sockaddr))),
7592 res);
7593 else if (strcmp (namebuf, SSDATA (ifname)) == 0)
7595 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
7596 register struct Lisp_Vector *p = XVECTOR (hwaddr);
7597 Lisp_Object flags = Qnil;
7598 int n;
7599 u_long net_mask;
7601 /* Flags. We guess most of them by type, since the
7602 Windows flags are different and hard to get by. */
7603 flags = Fcons (intern ("up"), flags);
7604 if (ifmt_idx == ETHERNET || ifmt_idx == WLAN)
7606 flags = Fcons (intern ("broadcast"), flags);
7607 flags = Fcons (intern ("multicast"), flags);
7609 flags = Fcons (intern ("running"), flags);
7610 if (ifmt_idx == PPP)
7612 flags = Fcons (intern ("pointopoint"), flags);
7613 flags = Fcons (intern ("noarp"), flags);
7615 if (adapter->HaveWins)
7616 flags = Fcons (intern ("WINS"), flags);
7617 if (adapter->DhcpEnabled)
7618 flags = Fcons (intern ("dynamic"), flags);
7620 res = Fcons (flags, res);
7622 /* Hardware address and its family. */
7623 for (n = 0; n < adapter->AddressLength; n++)
7624 p->contents[n] = make_number ((int) adapter->Address[n]);
7625 /* Windows does not support AF_LINK or AF_PACKET family
7626 of addresses. Use an arbitrary family number that is
7627 identical to what GNU/Linux returns. */
7628 res = Fcons (Fcons (make_number (1), hwaddr), res);
7630 /* Network mask. */
7631 sa.sin_family = AF_INET;
7632 net_mask = sys_inet_addr (adapter->IpAddressList.IpMask.String);
7633 if (net_mask != INADDR_NONE)
7635 sa.sin_addr.s_addr = net_mask;
7636 sa.sin_port = 0;
7637 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
7638 sizeof (struct sockaddr)),
7639 res);
7641 else
7642 res = Fcons (Qnil, res);
7644 sa.sin_family = AF_INET;
7645 if (ip_addr != INADDR_NONE)
7647 /* Broadcast address is only reported by
7648 GetAdaptersAddresses, which is of limited
7649 availability. Generate it on our own. */
7650 u_long bcast_addr = (ip_addr & net_mask) | ~net_mask;
7652 sa.sin_addr.s_addr = bcast_addr;
7653 sa.sin_port = 0;
7654 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
7655 sizeof (struct sockaddr)),
7656 res);
7658 /* IP address. */
7659 sa.sin_addr.s_addr = ip_addr;
7660 sa.sin_port = 0;
7661 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
7662 sizeof (struct sockaddr)),
7663 res);
7665 else
7666 res = Fcons (Qnil, Fcons (Qnil, res));
7669 /* GetAdaptersInfo is documented to not report loopback
7670 interfaces, so we generate one out of thin air. */
7671 if (!lo_count)
7673 sa.sin_family = AF_INET;
7674 sa.sin_port = 0;
7675 if (NILP (ifname))
7677 sa.sin_addr.s_addr = sys_inet_addr ("127.0.0.1");
7678 res = Fcons (Fcons (build_string ("lo"),
7679 conv_sockaddr_to_lisp ((struct sockaddr*) &sa,
7680 sizeof (struct sockaddr))),
7681 res);
7683 else if (strcmp (SSDATA (ifname), "lo") == 0)
7685 res = Fcons (Fcons (intern ("running"),
7686 Fcons (intern ("loopback"),
7687 Fcons (intern ("up"), Qnil))), Qnil);
7688 /* 772 is what 3 different GNU/Linux systems report for
7689 the loopback interface. */
7690 res = Fcons (Fcons (make_number (772),
7691 Fmake_vector (make_number (6),
7692 make_number (0))),
7693 res);
7694 sa.sin_addr.s_addr = sys_inet_addr ("255.0.0.0");
7695 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
7696 sizeof (struct sockaddr)),
7697 res);
7698 sa.sin_addr.s_addr = sys_inet_addr ("0.0.0.0");
7699 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
7700 sizeof (struct sockaddr)),
7701 res);
7702 sa.sin_addr.s_addr = sys_inet_addr ("127.0.0.1");
7703 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
7704 sizeof (struct sockaddr)),
7705 res);
7711 done:
7712 xfree (ainfo);
7713 return res;
7716 Lisp_Object
7717 network_interface_list (void)
7719 return network_interface_get_info (Qnil);
7722 Lisp_Object
7723 network_interface_info (Lisp_Object ifname)
7725 return network_interface_get_info (ifname);
7729 /* The Windows CRT functions are "optimized for speed", so they don't
7730 check for timezone and DST changes if they were last called less
7731 than 1 minute ago (see http://support.microsoft.com/kb/821231). So
7732 all Emacs features that repeatedly call time functions (e.g.,
7733 display-time) are in real danger of missing timezone and DST
7734 changes. Calling tzset before each localtime call fixes that. */
7735 struct tm *
7736 sys_localtime (const time_t *t)
7738 tzset ();
7739 return localtime (t);
7744 /* Try loading LIBRARY_ID from the file(s) specified in
7745 Vdynamic_library_alist. If the library is loaded successfully,
7746 return the handle of the DLL, and record the filename in the
7747 property :loaded-from of LIBRARY_ID. If the library could not be
7748 found, or when it was already loaded (because the handle is not
7749 recorded anywhere, and so is lost after use), return NULL.
7751 We could also save the handle in :loaded-from, but currently
7752 there's no use case for it. */
7753 HMODULE
7754 w32_delayed_load (Lisp_Object library_id)
7756 HMODULE library_dll = NULL;
7758 CHECK_SYMBOL (library_id);
7760 if (CONSP (Vdynamic_library_alist)
7761 && NILP (Fassq (library_id, Vlibrary_cache)))
7763 Lisp_Object found = Qnil;
7764 Lisp_Object dlls = Fassq (library_id, Vdynamic_library_alist);
7766 if (CONSP (dlls))
7767 for (dlls = XCDR (dlls); CONSP (dlls); dlls = XCDR (dlls))
7769 CHECK_STRING_CAR (dlls);
7770 if ((library_dll = LoadLibrary (SDATA (XCAR (dlls)))))
7772 char name[MAX_PATH];
7773 DWORD len;
7775 len = GetModuleFileNameA (library_dll, name, sizeof (name));
7776 found = Fcons (XCAR (dlls),
7777 (len > 0)
7778 /* Possibly truncated */
7779 ? make_specified_string (name, -1, len, 1)
7780 : Qnil);
7781 break;
7785 Fput (library_id, QCloaded_from, found);
7788 return library_dll;
7792 void
7793 check_windows_init_file (void)
7795 /* A common indication that Emacs is not installed properly is when
7796 it cannot find the Windows installation file. If this file does
7797 not exist in the expected place, tell the user. */
7799 if (!noninteractive && !inhibit_window_system
7800 /* Vload_path is not yet initialized when we are loading
7801 loadup.el. */
7802 && NILP (Vpurify_flag))
7804 Lisp_Object init_file;
7805 int fd;
7807 init_file = build_string ("term/w32-win");
7808 fd = openp (Vload_path, init_file, Fget_load_suffixes (), NULL, Qnil);
7809 if (fd < 0)
7811 Lisp_Object load_path_print = Fprin1_to_string (Vload_path, Qnil);
7812 char *init_file_name = SDATA (init_file);
7813 char *load_path = SDATA (load_path_print);
7814 char *buffer = alloca (1024
7815 + strlen (init_file_name)
7816 + strlen (load_path));
7818 sprintf (buffer,
7819 "The Emacs Windows initialization file \"%s.el\" "
7820 "could not be found in your Emacs installation. "
7821 "Emacs checked the following directories for this file:\n"
7822 "\n%s\n\n"
7823 "When Emacs cannot find this file, it usually means that it "
7824 "was not installed properly, or its distribution file was "
7825 "not unpacked properly.\nSee the README.W32 file in the "
7826 "top-level Emacs directory for more information.",
7827 init_file_name, load_path);
7828 MessageBox (NULL,
7829 buffer,
7830 "Emacs Abort Dialog",
7831 MB_OK | MB_ICONEXCLAMATION | MB_TASKMODAL);
7832 /* Use the low-level system abort. */
7833 abort ();
7835 else
7837 _close (fd);
7842 void
7843 term_ntproc (int ignored)
7845 (void)ignored;
7847 term_timers ();
7849 /* shutdown the socket interface if necessary */
7850 term_winsock ();
7852 term_w32select ();
7855 void
7856 init_ntproc (int dumping)
7858 sigset_t initial_mask = 0;
7860 /* Initialize the socket interface now if available and requested by
7861 the user by defining PRELOAD_WINSOCK; otherwise loading will be
7862 delayed until open-network-stream is called (w32-has-winsock can
7863 also be used to dynamically load or reload winsock).
7865 Conveniently, init_environment is called before us, so
7866 PRELOAD_WINSOCK can be set in the registry. */
7868 /* Always initialize this correctly. */
7869 winsock_lib = NULL;
7871 if (getenv ("PRELOAD_WINSOCK") != NULL)
7872 init_winsock (TRUE);
7874 /* Initial preparation for subprocess support: replace our standard
7875 handles with non-inheritable versions. */
7877 HANDLE parent;
7878 HANDLE stdin_save = INVALID_HANDLE_VALUE;
7879 HANDLE stdout_save = INVALID_HANDLE_VALUE;
7880 HANDLE stderr_save = INVALID_HANDLE_VALUE;
7882 parent = GetCurrentProcess ();
7884 /* ignore errors when duplicating and closing; typically the
7885 handles will be invalid when running as a gui program. */
7886 DuplicateHandle (parent,
7887 GetStdHandle (STD_INPUT_HANDLE),
7888 parent,
7889 &stdin_save,
7891 FALSE,
7892 DUPLICATE_SAME_ACCESS);
7894 DuplicateHandle (parent,
7895 GetStdHandle (STD_OUTPUT_HANDLE),
7896 parent,
7897 &stdout_save,
7899 FALSE,
7900 DUPLICATE_SAME_ACCESS);
7902 DuplicateHandle (parent,
7903 GetStdHandle (STD_ERROR_HANDLE),
7904 parent,
7905 &stderr_save,
7907 FALSE,
7908 DUPLICATE_SAME_ACCESS);
7910 fclose (stdin);
7911 fclose (stdout);
7912 fclose (stderr);
7914 if (stdin_save != INVALID_HANDLE_VALUE)
7915 _open_osfhandle ((intptr_t) stdin_save, O_TEXT);
7916 else
7917 _open ("nul", O_TEXT | O_NOINHERIT | O_RDONLY);
7918 _fdopen (0, "r");
7920 if (stdout_save != INVALID_HANDLE_VALUE)
7921 _open_osfhandle ((intptr_t) stdout_save, O_TEXT);
7922 else
7923 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
7924 _fdopen (1, "w");
7926 if (stderr_save != INVALID_HANDLE_VALUE)
7927 _open_osfhandle ((intptr_t) stderr_save, O_TEXT);
7928 else
7929 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
7930 _fdopen (2, "w");
7933 /* unfortunately, atexit depends on implementation of malloc */
7934 /* atexit (term_ntproc); */
7935 if (!dumping)
7937 /* Make sure we start with all signals unblocked. */
7938 sigprocmask (SIG_SETMASK, &initial_mask, NULL);
7939 signal (SIGABRT, term_ntproc);
7941 init_timers ();
7943 /* determine which drives are fixed, for GetCachedVolumeInformation */
7945 /* GetDriveType must have trailing backslash. */
7946 char drive[] = "A:\\";
7948 /* Loop over all possible drive letters */
7949 while (*drive <= 'Z')
7951 /* Record if this drive letter refers to a fixed drive. */
7952 fixed_drives[DRIVE_INDEX (*drive)] =
7953 (GetDriveType (drive) == DRIVE_FIXED);
7955 (*drive)++;
7958 /* Reset the volume info cache. */
7959 volume_cache = NULL;
7964 shutdown_handler ensures that buffers' autosave files are
7965 up to date when the user logs off, or the system shuts down.
7967 static BOOL WINAPI
7968 shutdown_handler (DWORD type)
7970 /* Ctrl-C and Ctrl-Break are already suppressed, so don't handle them. */
7971 if (type == CTRL_CLOSE_EVENT /* User closes console window. */
7972 || type == CTRL_LOGOFF_EVENT /* User logs off. */
7973 || type == CTRL_SHUTDOWN_EVENT) /* User shutsdown. */
7975 /* Shut down cleanly, making sure autosave files are up to date. */
7976 shut_down_emacs (0, Qnil);
7979 /* Allow other handlers to handle this signal. */
7980 return FALSE;
7984 globals_of_w32 is used to initialize those global variables that
7985 must always be initialized on startup even when the global variable
7986 initialized is non zero (see the function main in emacs.c).
7988 void
7989 globals_of_w32 (void)
7991 HMODULE kernel32 = GetModuleHandle ("kernel32.dll");
7993 get_process_times_fn = (GetProcessTimes_Proc)
7994 GetProcAddress (kernel32, "GetProcessTimes");
7996 DEFSYM (QCloaded_from, ":loaded-from");
7998 g_b_init_is_windows_9x = 0;
7999 g_b_init_open_process_token = 0;
8000 g_b_init_get_token_information = 0;
8001 g_b_init_lookup_account_sid = 0;
8002 g_b_init_get_sid_sub_authority = 0;
8003 g_b_init_get_sid_sub_authority_count = 0;
8004 g_b_init_get_security_info = 0;
8005 g_b_init_get_file_security = 0;
8006 g_b_init_get_security_descriptor_owner = 0;
8007 g_b_init_get_security_descriptor_group = 0;
8008 g_b_init_is_valid_sid = 0;
8009 g_b_init_create_toolhelp32_snapshot = 0;
8010 g_b_init_process32_first = 0;
8011 g_b_init_process32_next = 0;
8012 g_b_init_open_thread_token = 0;
8013 g_b_init_impersonate_self = 0;
8014 g_b_init_revert_to_self = 0;
8015 g_b_init_get_process_memory_info = 0;
8016 g_b_init_get_process_working_set_size = 0;
8017 g_b_init_global_memory_status = 0;
8018 g_b_init_global_memory_status_ex = 0;
8019 g_b_init_equal_sid = 0;
8020 g_b_init_copy_sid = 0;
8021 g_b_init_get_length_sid = 0;
8022 g_b_init_get_native_system_info = 0;
8023 g_b_init_get_system_times = 0;
8024 g_b_init_create_symbolic_link = 0;
8025 g_b_init_get_security_descriptor_dacl = 0;
8026 g_b_init_convert_sd_to_sddl = 0;
8027 g_b_init_convert_sddl_to_sd = 0;
8028 g_b_init_is_valid_security_descriptor = 0;
8029 g_b_init_set_file_security = 0;
8030 g_b_init_get_adapters_info = 0;
8031 num_of_processors = 0;
8032 /* The following sets a handler for shutdown notifications for
8033 console apps. This actually applies to Emacs in both console and
8034 GUI modes, since we had to fool windows into thinking emacs is a
8035 console application to get console mode to work. */
8036 SetConsoleCtrlHandler (shutdown_handler, TRUE);
8038 /* "None" is the default group name on standalone workstations. */
8039 strcpy (dflt_group_name, "None");
8041 /* Reset, in case it has some value inherited from dump time. */
8042 w32_stat_get_owner_group = 0;
8045 /* For make-serial-process */
8047 serial_open (Lisp_Object port_obj)
8049 char *port = SSDATA (port_obj);
8050 HANDLE hnd;
8051 child_process *cp;
8052 int fd = -1;
8054 hnd = CreateFile (port, GENERIC_READ | GENERIC_WRITE, 0, 0,
8055 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
8056 if (hnd == INVALID_HANDLE_VALUE)
8057 error ("Could not open %s", port);
8058 fd = (int) _open_osfhandle ((intptr_t) hnd, 0);
8059 if (fd == -1)
8060 error ("Could not open %s", port);
8062 cp = new_child ();
8063 if (!cp)
8064 error ("Could not create child process");
8065 cp->fd = fd;
8066 cp->status = STATUS_READ_ACKNOWLEDGED;
8067 fd_info[ fd ].hnd = hnd;
8068 fd_info[ fd ].flags |=
8069 FILE_READ | FILE_WRITE | FILE_BINARY | FILE_SERIAL;
8070 if (fd_info[ fd ].cp != NULL)
8072 error ("fd_info[fd = %d] is already in use", fd);
8074 fd_info[ fd ].cp = cp;
8075 cp->ovl_read.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
8076 if (cp->ovl_read.hEvent == NULL)
8077 error ("Could not create read event");
8078 cp->ovl_write.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
8079 if (cp->ovl_write.hEvent == NULL)
8080 error ("Could not create write event");
8082 return fd;
8085 /* For serial-process-configure */
8086 void
8087 serial_configure (struct Lisp_Process *p, Lisp_Object contact)
8089 Lisp_Object childp2 = Qnil;
8090 Lisp_Object tem = Qnil;
8091 HANDLE hnd;
8092 DCB dcb;
8093 COMMTIMEOUTS ct;
8094 char summary[4] = "???"; /* This usually becomes "8N1". */
8096 if ((fd_info[ p->outfd ].flags & FILE_SERIAL) == 0)
8097 error ("Not a serial process");
8098 hnd = fd_info[ p->outfd ].hnd;
8100 childp2 = Fcopy_sequence (p->childp);
8102 /* Initialize timeouts for blocking read and blocking write. */
8103 if (!GetCommTimeouts (hnd, &ct))
8104 error ("GetCommTimeouts() failed");
8105 ct.ReadIntervalTimeout = 0;
8106 ct.ReadTotalTimeoutMultiplier = 0;
8107 ct.ReadTotalTimeoutConstant = 0;
8108 ct.WriteTotalTimeoutMultiplier = 0;
8109 ct.WriteTotalTimeoutConstant = 0;
8110 if (!SetCommTimeouts (hnd, &ct))
8111 error ("SetCommTimeouts() failed");
8112 /* Read port attributes and prepare default configuration. */
8113 memset (&dcb, 0, sizeof (dcb));
8114 dcb.DCBlength = sizeof (DCB);
8115 if (!GetCommState (hnd, &dcb))
8116 error ("GetCommState() failed");
8117 dcb.fBinary = TRUE;
8118 dcb.fNull = FALSE;
8119 dcb.fAbortOnError = FALSE;
8120 /* dcb.XonLim and dcb.XoffLim are set by GetCommState() */
8121 dcb.ErrorChar = 0;
8122 dcb.EofChar = 0;
8123 dcb.EvtChar = 0;
8125 /* Configure speed. */
8126 if (!NILP (Fplist_member (contact, QCspeed)))
8127 tem = Fplist_get (contact, QCspeed);
8128 else
8129 tem = Fplist_get (p->childp, QCspeed);
8130 CHECK_NUMBER (tem);
8131 dcb.BaudRate = XINT (tem);
8132 childp2 = Fplist_put (childp2, QCspeed, tem);
8134 /* Configure bytesize. */
8135 if (!NILP (Fplist_member (contact, QCbytesize)))
8136 tem = Fplist_get (contact, QCbytesize);
8137 else
8138 tem = Fplist_get (p->childp, QCbytesize);
8139 if (NILP (tem))
8140 tem = make_number (8);
8141 CHECK_NUMBER (tem);
8142 if (XINT (tem) != 7 && XINT (tem) != 8)
8143 error (":bytesize must be nil (8), 7, or 8");
8144 dcb.ByteSize = XINT (tem);
8145 summary[0] = XINT (tem) + '0';
8146 childp2 = Fplist_put (childp2, QCbytesize, tem);
8148 /* Configure parity. */
8149 if (!NILP (Fplist_member (contact, QCparity)))
8150 tem = Fplist_get (contact, QCparity);
8151 else
8152 tem = Fplist_get (p->childp, QCparity);
8153 if (!NILP (tem) && !EQ (tem, Qeven) && !EQ (tem, Qodd))
8154 error (":parity must be nil (no parity), `even', or `odd'");
8155 dcb.fParity = FALSE;
8156 dcb.Parity = NOPARITY;
8157 dcb.fErrorChar = FALSE;
8158 if (NILP (tem))
8160 summary[1] = 'N';
8162 else if (EQ (tem, Qeven))
8164 summary[1] = 'E';
8165 dcb.fParity = TRUE;
8166 dcb.Parity = EVENPARITY;
8167 dcb.fErrorChar = TRUE;
8169 else if (EQ (tem, Qodd))
8171 summary[1] = 'O';
8172 dcb.fParity = TRUE;
8173 dcb.Parity = ODDPARITY;
8174 dcb.fErrorChar = TRUE;
8176 childp2 = Fplist_put (childp2, QCparity, tem);
8178 /* Configure stopbits. */
8179 if (!NILP (Fplist_member (contact, QCstopbits)))
8180 tem = Fplist_get (contact, QCstopbits);
8181 else
8182 tem = Fplist_get (p->childp, QCstopbits);
8183 if (NILP (tem))
8184 tem = make_number (1);
8185 CHECK_NUMBER (tem);
8186 if (XINT (tem) != 1 && XINT (tem) != 2)
8187 error (":stopbits must be nil (1 stopbit), 1, or 2");
8188 summary[2] = XINT (tem) + '0';
8189 if (XINT (tem) == 1)
8190 dcb.StopBits = ONESTOPBIT;
8191 else if (XINT (tem) == 2)
8192 dcb.StopBits = TWOSTOPBITS;
8193 childp2 = Fplist_put (childp2, QCstopbits, tem);
8195 /* Configure flowcontrol. */
8196 if (!NILP (Fplist_member (contact, QCflowcontrol)))
8197 tem = Fplist_get (contact, QCflowcontrol);
8198 else
8199 tem = Fplist_get (p->childp, QCflowcontrol);
8200 if (!NILP (tem) && !EQ (tem, Qhw) && !EQ (tem, Qsw))
8201 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
8202 dcb.fOutxCtsFlow = FALSE;
8203 dcb.fOutxDsrFlow = FALSE;
8204 dcb.fDtrControl = DTR_CONTROL_DISABLE;
8205 dcb.fDsrSensitivity = FALSE;
8206 dcb.fTXContinueOnXoff = FALSE;
8207 dcb.fOutX = FALSE;
8208 dcb.fInX = FALSE;
8209 dcb.fRtsControl = RTS_CONTROL_DISABLE;
8210 dcb.XonChar = 17; /* Control-Q */
8211 dcb.XoffChar = 19; /* Control-S */
8212 if (NILP (tem))
8214 /* Already configured. */
8216 else if (EQ (tem, Qhw))
8218 dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
8219 dcb.fOutxCtsFlow = TRUE;
8221 else if (EQ (tem, Qsw))
8223 dcb.fOutX = TRUE;
8224 dcb.fInX = TRUE;
8226 childp2 = Fplist_put (childp2, QCflowcontrol, tem);
8228 /* Activate configuration. */
8229 if (!SetCommState (hnd, &dcb))
8230 error ("SetCommState() failed");
8232 childp2 = Fplist_put (childp2, QCsummary, build_string (summary));
8233 pset_childp (p, childp2);
8236 #ifdef HAVE_GNUTLS
8238 ssize_t
8239 emacs_gnutls_pull (gnutls_transport_ptr_t p, void* buf, size_t sz)
8241 int n, err;
8242 SELECT_TYPE fdset;
8243 struct timespec timeout;
8244 struct Lisp_Process *process = (struct Lisp_Process *)p;
8245 int fd = process->infd;
8247 n = sys_read (fd, (char*)buf, sz);
8249 if (n >= 0)
8250 return n;
8252 err = errno;
8254 /* Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
8255 if (err == EWOULDBLOCK)
8256 err = EAGAIN;
8258 emacs_gnutls_transport_set_errno (process->gnutls_state, err);
8260 return -1;
8263 ssize_t
8264 emacs_gnutls_push (gnutls_transport_ptr_t p, const void* buf, size_t sz)
8266 struct Lisp_Process *process = (struct Lisp_Process *)p;
8267 int fd = process->outfd;
8268 ssize_t n = sys_write (fd, buf, sz);
8270 /* 0 or more bytes written means everything went fine. */
8271 if (n >= 0)
8272 return n;
8274 /* Negative bytes written means we got an error in errno.
8275 Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
8276 emacs_gnutls_transport_set_errno (process->gnutls_state,
8277 errno == EWOULDBLOCK ? EAGAIN : errno);
8279 return -1;
8281 #endif /* HAVE_GNUTLS */
8283 /* end of w32.c */