New experimental feature to save&restore window and frame setup.
[emacs.git] / src / w32.c
blob230479cd61a2c089471e6143fbae06425f6396f6
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
22 #include <stddef.h> /* for offsetof */
23 #include <stdlib.h>
24 #include <stdio.h>
25 #include <float.h> /* for DBL_EPSILON */
26 #include <io.h>
27 #include <errno.h>
28 #include <fcntl.h>
29 #include <ctype.h>
30 #include <signal.h>
31 #include <sys/file.h>
32 #include <time.h> /* must be before nt/inc/sys/time.h, for MinGW64 */
33 #include <sys/time.h>
34 #include <sys/utime.h>
35 #include <math.h>
37 /* must include CRT headers *before* config.h */
39 #include <config.h>
40 #include <mbstring.h> /* for _mbspbrk, _mbslwr, _mbsrchr, ... */
42 #undef access
43 #undef chdir
44 #undef chmod
45 #undef creat
46 #undef ctime
47 #undef fopen
48 #undef link
49 #undef mkdir
50 #undef mktemp
51 #undef open
52 #undef rename
53 #undef rmdir
54 #undef unlink
56 #undef close
57 #undef dup
58 #undef dup2
59 #undef pipe
60 #undef read
61 #undef write
63 #undef strerror
65 #undef localtime
67 #include "lisp.h"
68 #include "epaths.h" /* for SHELL */
70 #include <pwd.h>
71 #include <grp.h>
73 /* MinGW64 (_W64) defines these in its _mingw.h. */
74 #if defined(__GNUC__) && !defined(_W64)
75 #define _ANONYMOUS_UNION
76 #define _ANONYMOUS_STRUCT
77 #endif
78 #include <windows.h>
79 /* Some versions of compiler define MEMORYSTATUSEX, some don't, so we
80 use a different name to avoid compilation problems. */
81 typedef struct _MEMORY_STATUS_EX {
82 DWORD dwLength;
83 DWORD dwMemoryLoad;
84 DWORDLONG ullTotalPhys;
85 DWORDLONG ullAvailPhys;
86 DWORDLONG ullTotalPageFile;
87 DWORDLONG ullAvailPageFile;
88 DWORDLONG ullTotalVirtual;
89 DWORDLONG ullAvailVirtual;
90 DWORDLONG ullAvailExtendedVirtual;
91 } MEMORY_STATUS_EX,*LPMEMORY_STATUS_EX;
93 #include <lmcons.h>
94 #include <shlobj.h>
96 #include <tlhelp32.h>
97 #include <psapi.h>
98 #ifndef _MSC_VER
99 #include <w32api.h>
100 #endif
101 #if _WIN32_WINNT < 0x0500
102 #if !defined (__MINGW32__) || __W32API_MAJOR_VERSION < 3 || (__W32API_MAJOR_VERSION == 3 && __W32API_MINOR_VERSION < 15)
103 /* This either is not in psapi.h or guarded by higher value of
104 _WIN32_WINNT than what we use. w32api supplied with MinGW 3.15
105 defines it in psapi.h */
106 typedef struct _PROCESS_MEMORY_COUNTERS_EX {
107 DWORD cb;
108 DWORD PageFaultCount;
109 SIZE_T PeakWorkingSetSize;
110 SIZE_T WorkingSetSize;
111 SIZE_T QuotaPeakPagedPoolUsage;
112 SIZE_T QuotaPagedPoolUsage;
113 SIZE_T QuotaPeakNonPagedPoolUsage;
114 SIZE_T QuotaNonPagedPoolUsage;
115 SIZE_T PagefileUsage;
116 SIZE_T PeakPagefileUsage;
117 SIZE_T PrivateUsage;
118 } PROCESS_MEMORY_COUNTERS_EX,*PPROCESS_MEMORY_COUNTERS_EX;
119 #endif
120 #endif
122 #include <winioctl.h>
123 #include <aclapi.h>
124 #include <sddl.h>
126 #include <sys/acl.h>
128 /* This is not in MinGW's sddl.h (but they are in MSVC headers), so we
129 define them by hand if not already defined. */
130 #ifndef SDDL_REVISION_1
131 #define SDDL_REVISION_1 1
132 #endif /* SDDL_REVISION_1 */
134 #if defined(_MSC_VER) || defined(_W64)
135 /* MSVC and MinGW64 don't provide the definition of
136 REPARSE_DATA_BUFFER and the associated macros, except on ntifs.h,
137 which cannot be included because it triggers conflicts with other
138 Windows API headers. So we define it here by hand. */
140 typedef struct _REPARSE_DATA_BUFFER {
141 ULONG ReparseTag;
142 USHORT ReparseDataLength;
143 USHORT Reserved;
144 union {
145 struct {
146 USHORT SubstituteNameOffset;
147 USHORT SubstituteNameLength;
148 USHORT PrintNameOffset;
149 USHORT PrintNameLength;
150 ULONG Flags;
151 WCHAR PathBuffer[1];
152 } SymbolicLinkReparseBuffer;
153 struct {
154 USHORT SubstituteNameOffset;
155 USHORT SubstituteNameLength;
156 USHORT PrintNameOffset;
157 USHORT PrintNameLength;
158 WCHAR PathBuffer[1];
159 } MountPointReparseBuffer;
160 struct {
161 UCHAR DataBuffer[1];
162 } GenericReparseBuffer;
163 } DUMMYUNIONNAME;
164 } REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;
166 #ifndef FILE_DEVICE_FILE_SYSTEM
167 #define FILE_DEVICE_FILE_SYSTEM 9
168 #endif
169 #ifndef METHOD_BUFFERED
170 #define METHOD_BUFFERED 0
171 #endif
172 #ifndef FILE_ANY_ACCESS
173 #define FILE_ANY_ACCESS 0x00000000
174 #endif
175 #ifndef CTL_CODE
176 #define CTL_CODE(t,f,m,a) (((t)<<16)|((a)<<14)|((f)<<2)|(m))
177 #endif
178 /* MinGW64 defines FSCTL_GET_REPARSE_POINT on winioctl.h. */
179 #ifndef FSCTL_GET_REPARSE_POINT
180 #define FSCTL_GET_REPARSE_POINT \
181 CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 42, METHOD_BUFFERED, FILE_ANY_ACCESS)
182 #endif
183 #endif
185 /* TCP connection support. */
186 #include <sys/socket.h>
187 #undef socket
188 #undef bind
189 #undef connect
190 #undef htons
191 #undef ntohs
192 #undef inet_addr
193 #undef gethostname
194 #undef gethostbyname
195 #undef getservbyname
196 #undef getpeername
197 #undef shutdown
198 #undef setsockopt
199 #undef listen
200 #undef getsockname
201 #undef accept
202 #undef recvfrom
203 #undef sendto
205 #include "w32.h"
206 #include <dirent.h>
207 #include "w32common.h"
208 #include "w32heap.h"
209 #include "w32select.h"
210 #include "systime.h"
211 #include "dispextern.h" /* for xstrcasecmp */
212 #include "coding.h" /* for Vlocale_coding_system */
214 #include "careadlinkat.h"
215 #include "allocator.h"
217 /* For serial_configure and serial_open. */
218 #include "process.h"
220 typedef HRESULT (WINAPI * ShGetFolderPath_fn)
221 (IN HWND, IN int, IN HANDLE, IN DWORD, OUT char *);
223 Lisp_Object QCloaded_from;
225 void globals_of_w32 (void);
226 static DWORD get_rid (PSID);
227 static int is_symlink (const char *);
228 static char * chase_symlinks (const char *);
229 static int enable_privilege (LPCTSTR, BOOL, TOKEN_PRIVILEGES *);
230 static int restore_privilege (TOKEN_PRIVILEGES *);
231 static BOOL WINAPI revert_to_self (void);
233 extern int sys_access (const char *, int);
234 extern void *e_malloc (size_t);
235 extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
236 EMACS_TIME *, void *);
240 /* Initialization states.
242 WARNING: If you add any more such variables for additional APIs,
243 you MUST add initialization for them to globals_of_w32
244 below. This is because these variables might get set
245 to non-NULL values during dumping, but the dumped Emacs
246 cannot reuse those values, because it could be run on a
247 different version of the OS, where API addresses are
248 different. */
249 static BOOL g_b_init_is_windows_9x;
250 static BOOL g_b_init_open_process_token;
251 static BOOL g_b_init_get_token_information;
252 static BOOL g_b_init_lookup_account_sid;
253 static BOOL g_b_init_get_sid_sub_authority;
254 static BOOL g_b_init_get_sid_sub_authority_count;
255 static BOOL g_b_init_get_security_info;
256 static BOOL g_b_init_get_file_security;
257 static BOOL g_b_init_get_security_descriptor_owner;
258 static BOOL g_b_init_get_security_descriptor_group;
259 static BOOL g_b_init_is_valid_sid;
260 static BOOL g_b_init_create_toolhelp32_snapshot;
261 static BOOL g_b_init_process32_first;
262 static BOOL g_b_init_process32_next;
263 static BOOL g_b_init_open_thread_token;
264 static BOOL g_b_init_impersonate_self;
265 static BOOL g_b_init_revert_to_self;
266 static BOOL g_b_init_get_process_memory_info;
267 static BOOL g_b_init_get_process_working_set_size;
268 static BOOL g_b_init_global_memory_status;
269 static BOOL g_b_init_global_memory_status_ex;
270 static BOOL g_b_init_get_length_sid;
271 static BOOL g_b_init_equal_sid;
272 static BOOL g_b_init_copy_sid;
273 static BOOL g_b_init_get_native_system_info;
274 static BOOL g_b_init_get_system_times;
275 static BOOL g_b_init_create_symbolic_link;
276 static BOOL g_b_init_get_security_descriptor_dacl;
277 static BOOL g_b_init_convert_sd_to_sddl;
278 static BOOL g_b_init_convert_sddl_to_sd;
279 static BOOL g_b_init_is_valid_security_descriptor;
280 static BOOL g_b_init_set_file_security;
283 BEGIN: Wrapper functions around OpenProcessToken
284 and other functions in advapi32.dll that are only
285 supported in Windows NT / 2k / XP
287 /* ** Function pointer typedefs ** */
288 typedef BOOL (WINAPI * OpenProcessToken_Proc) (
289 HANDLE ProcessHandle,
290 DWORD DesiredAccess,
291 PHANDLE TokenHandle);
292 typedef BOOL (WINAPI * GetTokenInformation_Proc) (
293 HANDLE TokenHandle,
294 TOKEN_INFORMATION_CLASS TokenInformationClass,
295 LPVOID TokenInformation,
296 DWORD TokenInformationLength,
297 PDWORD ReturnLength);
298 typedef BOOL (WINAPI * GetProcessTimes_Proc) (
299 HANDLE process_handle,
300 LPFILETIME creation_time,
301 LPFILETIME exit_time,
302 LPFILETIME kernel_time,
303 LPFILETIME user_time);
305 GetProcessTimes_Proc get_process_times_fn = NULL;
307 #ifdef _UNICODE
308 const char * const LookupAccountSid_Name = "LookupAccountSidW";
309 const char * const GetFileSecurity_Name = "GetFileSecurityW";
310 const char * const SetFileSecurity_Name = "SetFileSecurityW";
311 #else
312 const char * const LookupAccountSid_Name = "LookupAccountSidA";
313 const char * const GetFileSecurity_Name = "GetFileSecurityA";
314 const char * const SetFileSecurity_Name = "SetFileSecurityA";
315 #endif
316 typedef BOOL (WINAPI * LookupAccountSid_Proc) (
317 LPCTSTR lpSystemName,
318 PSID Sid,
319 LPTSTR Name,
320 LPDWORD cbName,
321 LPTSTR DomainName,
322 LPDWORD cbDomainName,
323 PSID_NAME_USE peUse);
324 typedef PDWORD (WINAPI * GetSidSubAuthority_Proc) (
325 PSID pSid,
326 DWORD n);
327 typedef PUCHAR (WINAPI * GetSidSubAuthorityCount_Proc) (
328 PSID pSid);
329 typedef DWORD (WINAPI * GetSecurityInfo_Proc) (
330 HANDLE handle,
331 SE_OBJECT_TYPE ObjectType,
332 SECURITY_INFORMATION SecurityInfo,
333 PSID *ppsidOwner,
334 PSID *ppsidGroup,
335 PACL *ppDacl,
336 PACL *ppSacl,
337 PSECURITY_DESCRIPTOR *ppSecurityDescriptor);
338 typedef BOOL (WINAPI * GetFileSecurity_Proc) (
339 LPCTSTR lpFileName,
340 SECURITY_INFORMATION RequestedInformation,
341 PSECURITY_DESCRIPTOR pSecurityDescriptor,
342 DWORD nLength,
343 LPDWORD lpnLengthNeeded);
344 typedef BOOL (WINAPI *SetFileSecurity_Proc) (
345 LPCTSTR lpFileName,
346 SECURITY_INFORMATION SecurityInformation,
347 PSECURITY_DESCRIPTOR pSecurityDescriptor);
348 typedef BOOL (WINAPI * GetSecurityDescriptorOwner_Proc) (
349 PSECURITY_DESCRIPTOR pSecurityDescriptor,
350 PSID *pOwner,
351 LPBOOL lpbOwnerDefaulted);
352 typedef BOOL (WINAPI * GetSecurityDescriptorGroup_Proc) (
353 PSECURITY_DESCRIPTOR pSecurityDescriptor,
354 PSID *pGroup,
355 LPBOOL lpbGroupDefaulted);
356 typedef BOOL (WINAPI *GetSecurityDescriptorDacl_Proc) (
357 PSECURITY_DESCRIPTOR pSecurityDescriptor,
358 LPBOOL lpbDaclPresent,
359 PACL *pDacl,
360 LPBOOL lpbDaclDefaulted);
361 typedef BOOL (WINAPI * IsValidSid_Proc) (
362 PSID sid);
363 typedef HANDLE (WINAPI * CreateToolhelp32Snapshot_Proc) (
364 DWORD dwFlags,
365 DWORD th32ProcessID);
366 typedef BOOL (WINAPI * Process32First_Proc) (
367 HANDLE hSnapshot,
368 LPPROCESSENTRY32 lppe);
369 typedef BOOL (WINAPI * Process32Next_Proc) (
370 HANDLE hSnapshot,
371 LPPROCESSENTRY32 lppe);
372 typedef BOOL (WINAPI * OpenThreadToken_Proc) (
373 HANDLE ThreadHandle,
374 DWORD DesiredAccess,
375 BOOL OpenAsSelf,
376 PHANDLE TokenHandle);
377 typedef BOOL (WINAPI * ImpersonateSelf_Proc) (
378 SECURITY_IMPERSONATION_LEVEL ImpersonationLevel);
379 typedef BOOL (WINAPI * RevertToSelf_Proc) (void);
380 typedef BOOL (WINAPI * GetProcessMemoryInfo_Proc) (
381 HANDLE Process,
382 PPROCESS_MEMORY_COUNTERS ppsmemCounters,
383 DWORD cb);
384 typedef BOOL (WINAPI * GetProcessWorkingSetSize_Proc) (
385 HANDLE hProcess,
386 PSIZE_T lpMinimumWorkingSetSize,
387 PSIZE_T lpMaximumWorkingSetSize);
388 typedef BOOL (WINAPI * GlobalMemoryStatus_Proc) (
389 LPMEMORYSTATUS lpBuffer);
390 typedef BOOL (WINAPI * GlobalMemoryStatusEx_Proc) (
391 LPMEMORY_STATUS_EX lpBuffer);
392 typedef BOOL (WINAPI * CopySid_Proc) (
393 DWORD nDestinationSidLength,
394 PSID pDestinationSid,
395 PSID pSourceSid);
396 typedef BOOL (WINAPI * EqualSid_Proc) (
397 PSID pSid1,
398 PSID pSid2);
399 typedef DWORD (WINAPI * GetLengthSid_Proc) (
400 PSID pSid);
401 typedef void (WINAPI * GetNativeSystemInfo_Proc) (
402 LPSYSTEM_INFO lpSystemInfo);
403 typedef BOOL (WINAPI * GetSystemTimes_Proc) (
404 LPFILETIME lpIdleTime,
405 LPFILETIME lpKernelTime,
406 LPFILETIME lpUserTime);
407 typedef BOOLEAN (WINAPI *CreateSymbolicLink_Proc) (
408 LPTSTR lpSymlinkFileName,
409 LPTSTR lpTargetFileName,
410 DWORD dwFlags);
411 typedef BOOL (WINAPI *ConvertStringSecurityDescriptorToSecurityDescriptor_Proc) (
412 LPCTSTR StringSecurityDescriptor,
413 DWORD StringSDRevision,
414 PSECURITY_DESCRIPTOR *SecurityDescriptor,
415 PULONG SecurityDescriptorSize);
416 typedef BOOL (WINAPI *ConvertSecurityDescriptorToStringSecurityDescriptor_Proc) (
417 PSECURITY_DESCRIPTOR SecurityDescriptor,
418 DWORD RequestedStringSDRevision,
419 SECURITY_INFORMATION SecurityInformation,
420 LPTSTR *StringSecurityDescriptor,
421 PULONG StringSecurityDescriptorLen);
422 typedef BOOL (WINAPI *IsValidSecurityDescriptor_Proc) (PSECURITY_DESCRIPTOR);
424 /* ** A utility function ** */
425 static BOOL
426 is_windows_9x (void)
428 static BOOL s_b_ret = 0;
429 OSVERSIONINFO os_ver;
430 if (g_b_init_is_windows_9x == 0)
432 g_b_init_is_windows_9x = 1;
433 ZeroMemory (&os_ver, sizeof (OSVERSIONINFO));
434 os_ver.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
435 if (GetVersionEx (&os_ver))
437 s_b_ret = (os_ver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS);
440 return s_b_ret;
443 static Lisp_Object ltime (ULONGLONG);
445 /* Get total user and system times for get-internal-run-time.
446 Returns a list of integers if the times are provided by the OS
447 (NT derivatives), otherwise it returns the result of current-time. */
448 Lisp_Object
449 w32_get_internal_run_time (void)
451 if (get_process_times_fn)
453 FILETIME create, exit, kernel, user;
454 HANDLE proc = GetCurrentProcess ();
455 if ((*get_process_times_fn) (proc, &create, &exit, &kernel, &user))
457 LARGE_INTEGER user_int, kernel_int, total;
458 user_int.LowPart = user.dwLowDateTime;
459 user_int.HighPart = user.dwHighDateTime;
460 kernel_int.LowPart = kernel.dwLowDateTime;
461 kernel_int.HighPart = kernel.dwHighDateTime;
462 total.QuadPart = user_int.QuadPart + kernel_int.QuadPart;
463 return ltime (total.QuadPart);
467 return Fcurrent_time ();
470 /* ** The wrapper functions ** */
472 static BOOL WINAPI
473 open_process_token (HANDLE ProcessHandle,
474 DWORD DesiredAccess,
475 PHANDLE TokenHandle)
477 static OpenProcessToken_Proc s_pfn_Open_Process_Token = NULL;
478 HMODULE hm_advapi32 = NULL;
479 if (is_windows_9x () == TRUE)
481 return FALSE;
483 if (g_b_init_open_process_token == 0)
485 g_b_init_open_process_token = 1;
486 hm_advapi32 = LoadLibrary ("Advapi32.dll");
487 s_pfn_Open_Process_Token =
488 (OpenProcessToken_Proc) GetProcAddress (hm_advapi32, "OpenProcessToken");
490 if (s_pfn_Open_Process_Token == NULL)
492 return FALSE;
494 return (
495 s_pfn_Open_Process_Token (
496 ProcessHandle,
497 DesiredAccess,
498 TokenHandle)
502 static BOOL WINAPI
503 get_token_information (HANDLE TokenHandle,
504 TOKEN_INFORMATION_CLASS TokenInformationClass,
505 LPVOID TokenInformation,
506 DWORD TokenInformationLength,
507 PDWORD ReturnLength)
509 static GetTokenInformation_Proc s_pfn_Get_Token_Information = NULL;
510 HMODULE hm_advapi32 = NULL;
511 if (is_windows_9x () == TRUE)
513 return FALSE;
515 if (g_b_init_get_token_information == 0)
517 g_b_init_get_token_information = 1;
518 hm_advapi32 = LoadLibrary ("Advapi32.dll");
519 s_pfn_Get_Token_Information =
520 (GetTokenInformation_Proc) GetProcAddress (hm_advapi32, "GetTokenInformation");
522 if (s_pfn_Get_Token_Information == NULL)
524 return FALSE;
526 return (
527 s_pfn_Get_Token_Information (
528 TokenHandle,
529 TokenInformationClass,
530 TokenInformation,
531 TokenInformationLength,
532 ReturnLength)
536 static BOOL WINAPI
537 lookup_account_sid (LPCTSTR lpSystemName,
538 PSID Sid,
539 LPTSTR Name,
540 LPDWORD cbName,
541 LPTSTR DomainName,
542 LPDWORD cbDomainName,
543 PSID_NAME_USE peUse)
545 static LookupAccountSid_Proc s_pfn_Lookup_Account_Sid = NULL;
546 HMODULE hm_advapi32 = NULL;
547 if (is_windows_9x () == TRUE)
549 return FALSE;
551 if (g_b_init_lookup_account_sid == 0)
553 g_b_init_lookup_account_sid = 1;
554 hm_advapi32 = LoadLibrary ("Advapi32.dll");
555 s_pfn_Lookup_Account_Sid =
556 (LookupAccountSid_Proc) GetProcAddress (hm_advapi32, LookupAccountSid_Name);
558 if (s_pfn_Lookup_Account_Sid == NULL)
560 return FALSE;
562 return (
563 s_pfn_Lookup_Account_Sid (
564 lpSystemName,
565 Sid,
566 Name,
567 cbName,
568 DomainName,
569 cbDomainName,
570 peUse)
574 static PDWORD WINAPI
575 get_sid_sub_authority (PSID pSid, DWORD n)
577 static GetSidSubAuthority_Proc s_pfn_Get_Sid_Sub_Authority = NULL;
578 static DWORD zero = 0U;
579 HMODULE hm_advapi32 = NULL;
580 if (is_windows_9x () == TRUE)
582 return &zero;
584 if (g_b_init_get_sid_sub_authority == 0)
586 g_b_init_get_sid_sub_authority = 1;
587 hm_advapi32 = LoadLibrary ("Advapi32.dll");
588 s_pfn_Get_Sid_Sub_Authority =
589 (GetSidSubAuthority_Proc) GetProcAddress (
590 hm_advapi32, "GetSidSubAuthority");
592 if (s_pfn_Get_Sid_Sub_Authority == NULL)
594 return &zero;
596 return (s_pfn_Get_Sid_Sub_Authority (pSid, n));
599 static PUCHAR WINAPI
600 get_sid_sub_authority_count (PSID pSid)
602 static GetSidSubAuthorityCount_Proc s_pfn_Get_Sid_Sub_Authority_Count = NULL;
603 static UCHAR zero = 0U;
604 HMODULE hm_advapi32 = NULL;
605 if (is_windows_9x () == TRUE)
607 return &zero;
609 if (g_b_init_get_sid_sub_authority_count == 0)
611 g_b_init_get_sid_sub_authority_count = 1;
612 hm_advapi32 = LoadLibrary ("Advapi32.dll");
613 s_pfn_Get_Sid_Sub_Authority_Count =
614 (GetSidSubAuthorityCount_Proc) GetProcAddress (
615 hm_advapi32, "GetSidSubAuthorityCount");
617 if (s_pfn_Get_Sid_Sub_Authority_Count == NULL)
619 return &zero;
621 return (s_pfn_Get_Sid_Sub_Authority_Count (pSid));
624 static DWORD WINAPI
625 get_security_info (HANDLE handle,
626 SE_OBJECT_TYPE ObjectType,
627 SECURITY_INFORMATION SecurityInfo,
628 PSID *ppsidOwner,
629 PSID *ppsidGroup,
630 PACL *ppDacl,
631 PACL *ppSacl,
632 PSECURITY_DESCRIPTOR *ppSecurityDescriptor)
634 static GetSecurityInfo_Proc s_pfn_Get_Security_Info = NULL;
635 HMODULE hm_advapi32 = NULL;
636 if (is_windows_9x () == TRUE)
638 return FALSE;
640 if (g_b_init_get_security_info == 0)
642 g_b_init_get_security_info = 1;
643 hm_advapi32 = LoadLibrary ("Advapi32.dll");
644 s_pfn_Get_Security_Info =
645 (GetSecurityInfo_Proc) GetProcAddress (
646 hm_advapi32, "GetSecurityInfo");
648 if (s_pfn_Get_Security_Info == NULL)
650 return FALSE;
652 return (s_pfn_Get_Security_Info (handle, ObjectType, SecurityInfo,
653 ppsidOwner, ppsidGroup, ppDacl, ppSacl,
654 ppSecurityDescriptor));
657 static BOOL WINAPI
658 get_file_security (LPCTSTR lpFileName,
659 SECURITY_INFORMATION RequestedInformation,
660 PSECURITY_DESCRIPTOR pSecurityDescriptor,
661 DWORD nLength,
662 LPDWORD lpnLengthNeeded)
664 static GetFileSecurity_Proc s_pfn_Get_File_Security = NULL;
665 HMODULE hm_advapi32 = NULL;
666 if (is_windows_9x () == TRUE)
668 errno = ENOTSUP;
669 return FALSE;
671 if (g_b_init_get_file_security == 0)
673 g_b_init_get_file_security = 1;
674 hm_advapi32 = LoadLibrary ("Advapi32.dll");
675 s_pfn_Get_File_Security =
676 (GetFileSecurity_Proc) GetProcAddress (
677 hm_advapi32, GetFileSecurity_Name);
679 if (s_pfn_Get_File_Security == NULL)
681 errno = ENOTSUP;
682 return FALSE;
684 return (s_pfn_Get_File_Security (lpFileName, RequestedInformation,
685 pSecurityDescriptor, nLength,
686 lpnLengthNeeded));
689 static BOOL WINAPI
690 set_file_security (LPCTSTR lpFileName,
691 SECURITY_INFORMATION SecurityInformation,
692 PSECURITY_DESCRIPTOR pSecurityDescriptor)
694 static SetFileSecurity_Proc s_pfn_Set_File_Security = NULL;
695 HMODULE hm_advapi32 = NULL;
696 if (is_windows_9x () == TRUE)
698 errno = ENOTSUP;
699 return FALSE;
701 if (g_b_init_set_file_security == 0)
703 g_b_init_set_file_security = 1;
704 hm_advapi32 = LoadLibrary ("Advapi32.dll");
705 s_pfn_Set_File_Security =
706 (SetFileSecurity_Proc) GetProcAddress (
707 hm_advapi32, SetFileSecurity_Name);
709 if (s_pfn_Set_File_Security == NULL)
711 errno = ENOTSUP;
712 return FALSE;
714 return (s_pfn_Set_File_Security (lpFileName, SecurityInformation,
715 pSecurityDescriptor));
718 static BOOL WINAPI
719 get_security_descriptor_owner (PSECURITY_DESCRIPTOR pSecurityDescriptor,
720 PSID *pOwner,
721 LPBOOL lpbOwnerDefaulted)
723 static GetSecurityDescriptorOwner_Proc s_pfn_Get_Security_Descriptor_Owner = NULL;
724 HMODULE hm_advapi32 = NULL;
725 if (is_windows_9x () == TRUE)
727 errno = ENOTSUP;
728 return FALSE;
730 if (g_b_init_get_security_descriptor_owner == 0)
732 g_b_init_get_security_descriptor_owner = 1;
733 hm_advapi32 = LoadLibrary ("Advapi32.dll");
734 s_pfn_Get_Security_Descriptor_Owner =
735 (GetSecurityDescriptorOwner_Proc) GetProcAddress (
736 hm_advapi32, "GetSecurityDescriptorOwner");
738 if (s_pfn_Get_Security_Descriptor_Owner == NULL)
740 errno = ENOTSUP;
741 return FALSE;
743 return (s_pfn_Get_Security_Descriptor_Owner (pSecurityDescriptor, pOwner,
744 lpbOwnerDefaulted));
747 static BOOL WINAPI
748 get_security_descriptor_group (PSECURITY_DESCRIPTOR pSecurityDescriptor,
749 PSID *pGroup,
750 LPBOOL lpbGroupDefaulted)
752 static GetSecurityDescriptorGroup_Proc s_pfn_Get_Security_Descriptor_Group = NULL;
753 HMODULE hm_advapi32 = NULL;
754 if (is_windows_9x () == TRUE)
756 errno = ENOTSUP;
757 return FALSE;
759 if (g_b_init_get_security_descriptor_group == 0)
761 g_b_init_get_security_descriptor_group = 1;
762 hm_advapi32 = LoadLibrary ("Advapi32.dll");
763 s_pfn_Get_Security_Descriptor_Group =
764 (GetSecurityDescriptorGroup_Proc) GetProcAddress (
765 hm_advapi32, "GetSecurityDescriptorGroup");
767 if (s_pfn_Get_Security_Descriptor_Group == NULL)
769 errno = ENOTSUP;
770 return FALSE;
772 return (s_pfn_Get_Security_Descriptor_Group (pSecurityDescriptor, pGroup,
773 lpbGroupDefaulted));
776 static BOOL WINAPI
777 get_security_descriptor_dacl (PSECURITY_DESCRIPTOR pSecurityDescriptor,
778 LPBOOL lpbDaclPresent,
779 PACL *pDacl,
780 LPBOOL lpbDaclDefaulted)
782 static GetSecurityDescriptorDacl_Proc s_pfn_Get_Security_Descriptor_Dacl = NULL;
783 HMODULE hm_advapi32 = NULL;
784 if (is_windows_9x () == TRUE)
786 errno = ENOTSUP;
787 return FALSE;
789 if (g_b_init_get_security_descriptor_dacl == 0)
791 g_b_init_get_security_descriptor_dacl = 1;
792 hm_advapi32 = LoadLibrary ("Advapi32.dll");
793 s_pfn_Get_Security_Descriptor_Dacl =
794 (GetSecurityDescriptorDacl_Proc) GetProcAddress (
795 hm_advapi32, "GetSecurityDescriptorDacl");
797 if (s_pfn_Get_Security_Descriptor_Dacl == NULL)
799 errno = ENOTSUP;
800 return FALSE;
802 return (s_pfn_Get_Security_Descriptor_Dacl (pSecurityDescriptor,
803 lpbDaclPresent, pDacl,
804 lpbDaclDefaulted));
807 static BOOL WINAPI
808 is_valid_sid (PSID sid)
810 static IsValidSid_Proc s_pfn_Is_Valid_Sid = NULL;
811 HMODULE hm_advapi32 = NULL;
812 if (is_windows_9x () == TRUE)
814 return FALSE;
816 if (g_b_init_is_valid_sid == 0)
818 g_b_init_is_valid_sid = 1;
819 hm_advapi32 = LoadLibrary ("Advapi32.dll");
820 s_pfn_Is_Valid_Sid =
821 (IsValidSid_Proc) GetProcAddress (
822 hm_advapi32, "IsValidSid");
824 if (s_pfn_Is_Valid_Sid == NULL)
826 return FALSE;
828 return (s_pfn_Is_Valid_Sid (sid));
831 static BOOL WINAPI
832 equal_sid (PSID sid1, PSID sid2)
834 static EqualSid_Proc s_pfn_Equal_Sid = NULL;
835 HMODULE hm_advapi32 = NULL;
836 if (is_windows_9x () == TRUE)
838 return FALSE;
840 if (g_b_init_equal_sid == 0)
842 g_b_init_equal_sid = 1;
843 hm_advapi32 = LoadLibrary ("Advapi32.dll");
844 s_pfn_Equal_Sid =
845 (EqualSid_Proc) GetProcAddress (
846 hm_advapi32, "EqualSid");
848 if (s_pfn_Equal_Sid == NULL)
850 return FALSE;
852 return (s_pfn_Equal_Sid (sid1, sid2));
855 static DWORD WINAPI
856 get_length_sid (PSID sid)
858 static GetLengthSid_Proc s_pfn_Get_Length_Sid = NULL;
859 HMODULE hm_advapi32 = NULL;
860 if (is_windows_9x () == TRUE)
862 return 0;
864 if (g_b_init_get_length_sid == 0)
866 g_b_init_get_length_sid = 1;
867 hm_advapi32 = LoadLibrary ("Advapi32.dll");
868 s_pfn_Get_Length_Sid =
869 (GetLengthSid_Proc) GetProcAddress (
870 hm_advapi32, "GetLengthSid");
872 if (s_pfn_Get_Length_Sid == NULL)
874 return 0;
876 return (s_pfn_Get_Length_Sid (sid));
879 static BOOL WINAPI
880 copy_sid (DWORD destlen, PSID dest, PSID src)
882 static CopySid_Proc s_pfn_Copy_Sid = NULL;
883 HMODULE hm_advapi32 = NULL;
884 if (is_windows_9x () == TRUE)
886 return FALSE;
888 if (g_b_init_copy_sid == 0)
890 g_b_init_copy_sid = 1;
891 hm_advapi32 = LoadLibrary ("Advapi32.dll");
892 s_pfn_Copy_Sid =
893 (CopySid_Proc) GetProcAddress (
894 hm_advapi32, "CopySid");
896 if (s_pfn_Copy_Sid == NULL)
898 return FALSE;
900 return (s_pfn_Copy_Sid (destlen, dest, src));
904 END: Wrapper functions around OpenProcessToken
905 and other functions in advapi32.dll that are only
906 supported in Windows NT / 2k / XP
909 static void WINAPI
910 get_native_system_info (LPSYSTEM_INFO lpSystemInfo)
912 static GetNativeSystemInfo_Proc s_pfn_Get_Native_System_Info = NULL;
913 if (is_windows_9x () != TRUE)
915 if (g_b_init_get_native_system_info == 0)
917 g_b_init_get_native_system_info = 1;
918 s_pfn_Get_Native_System_Info =
919 (GetNativeSystemInfo_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
920 "GetNativeSystemInfo");
922 if (s_pfn_Get_Native_System_Info != NULL)
923 s_pfn_Get_Native_System_Info (lpSystemInfo);
925 else
926 lpSystemInfo->dwNumberOfProcessors = -1;
929 static BOOL WINAPI
930 get_system_times (LPFILETIME lpIdleTime,
931 LPFILETIME lpKernelTime,
932 LPFILETIME lpUserTime)
934 static GetSystemTimes_Proc s_pfn_Get_System_times = NULL;
935 if (is_windows_9x () == TRUE)
937 return FALSE;
939 if (g_b_init_get_system_times == 0)
941 g_b_init_get_system_times = 1;
942 s_pfn_Get_System_times =
943 (GetSystemTimes_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
944 "GetSystemTimes");
946 if (s_pfn_Get_System_times == NULL)
947 return FALSE;
948 return (s_pfn_Get_System_times (lpIdleTime, lpKernelTime, lpUserTime));
951 static BOOLEAN WINAPI
952 create_symbolic_link (LPTSTR lpSymlinkFilename,
953 LPTSTR lpTargetFileName,
954 DWORD dwFlags)
956 static CreateSymbolicLink_Proc s_pfn_Create_Symbolic_Link = NULL;
957 BOOLEAN retval;
959 if (is_windows_9x () == TRUE)
961 errno = ENOSYS;
962 return 0;
964 if (g_b_init_create_symbolic_link == 0)
966 g_b_init_create_symbolic_link = 1;
967 #ifdef _UNICODE
968 s_pfn_Create_Symbolic_Link =
969 (CreateSymbolicLink_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
970 "CreateSymbolicLinkW");
971 #else
972 s_pfn_Create_Symbolic_Link =
973 (CreateSymbolicLink_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
974 "CreateSymbolicLinkA");
975 #endif
977 if (s_pfn_Create_Symbolic_Link == NULL)
979 errno = ENOSYS;
980 return 0;
983 retval = s_pfn_Create_Symbolic_Link (lpSymlinkFilename, lpTargetFileName,
984 dwFlags);
985 /* If we were denied creation of the symlink, try again after
986 enabling the SeCreateSymbolicLinkPrivilege for our process. */
987 if (!retval)
989 TOKEN_PRIVILEGES priv_current;
991 if (enable_privilege (SE_CREATE_SYMBOLIC_LINK_NAME, TRUE, &priv_current))
993 retval = s_pfn_Create_Symbolic_Link (lpSymlinkFilename, lpTargetFileName,
994 dwFlags);
995 restore_privilege (&priv_current);
996 revert_to_self ();
999 return retval;
1002 static BOOL WINAPI
1003 is_valid_security_descriptor (PSECURITY_DESCRIPTOR pSecurityDescriptor)
1005 static IsValidSecurityDescriptor_Proc s_pfn_Is_Valid_Security_Descriptor_Proc = NULL;
1007 if (is_windows_9x () == TRUE)
1009 errno = ENOTSUP;
1010 return FALSE;
1013 if (g_b_init_is_valid_security_descriptor == 0)
1015 g_b_init_is_valid_security_descriptor = 1;
1016 s_pfn_Is_Valid_Security_Descriptor_Proc =
1017 (IsValidSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1018 "IsValidSecurityDescriptor");
1020 if (s_pfn_Is_Valid_Security_Descriptor_Proc == NULL)
1022 errno = ENOTSUP;
1023 return FALSE;
1026 return s_pfn_Is_Valid_Security_Descriptor_Proc (pSecurityDescriptor);
1029 static BOOL WINAPI
1030 convert_sd_to_sddl (PSECURITY_DESCRIPTOR SecurityDescriptor,
1031 DWORD RequestedStringSDRevision,
1032 SECURITY_INFORMATION SecurityInformation,
1033 LPTSTR *StringSecurityDescriptor,
1034 PULONG StringSecurityDescriptorLen)
1036 static ConvertSecurityDescriptorToStringSecurityDescriptor_Proc s_pfn_Convert_SD_To_SDDL = NULL;
1037 BOOL retval;
1039 if (is_windows_9x () == TRUE)
1041 errno = ENOTSUP;
1042 return FALSE;
1045 if (g_b_init_convert_sd_to_sddl == 0)
1047 g_b_init_convert_sd_to_sddl = 1;
1048 #ifdef _UNICODE
1049 s_pfn_Convert_SD_To_SDDL =
1050 (ConvertSecurityDescriptorToStringSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1051 "ConvertSecurityDescriptorToStringSecurityDescriptorW");
1052 #else
1053 s_pfn_Convert_SD_To_SDDL =
1054 (ConvertSecurityDescriptorToStringSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1055 "ConvertSecurityDescriptorToStringSecurityDescriptorA");
1056 #endif
1058 if (s_pfn_Convert_SD_To_SDDL == NULL)
1060 errno = ENOTSUP;
1061 return FALSE;
1064 retval = s_pfn_Convert_SD_To_SDDL (SecurityDescriptor,
1065 RequestedStringSDRevision,
1066 SecurityInformation,
1067 StringSecurityDescriptor,
1068 StringSecurityDescriptorLen);
1070 return retval;
1073 static BOOL WINAPI
1074 convert_sddl_to_sd (LPCTSTR StringSecurityDescriptor,
1075 DWORD StringSDRevision,
1076 PSECURITY_DESCRIPTOR *SecurityDescriptor,
1077 PULONG SecurityDescriptorSize)
1079 static ConvertStringSecurityDescriptorToSecurityDescriptor_Proc s_pfn_Convert_SDDL_To_SD = NULL;
1080 BOOL retval;
1082 if (is_windows_9x () == TRUE)
1084 errno = ENOTSUP;
1085 return FALSE;
1088 if (g_b_init_convert_sddl_to_sd == 0)
1090 g_b_init_convert_sddl_to_sd = 1;
1091 #ifdef _UNICODE
1092 s_pfn_Convert_SDDL_To_SD =
1093 (ConvertStringSecurityDescriptorToSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1094 "ConvertStringSecurityDescriptorToSecurityDescriptorW");
1095 #else
1096 s_pfn_Convert_SDDL_To_SD =
1097 (ConvertStringSecurityDescriptorToSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1098 "ConvertStringSecurityDescriptorToSecurityDescriptorA");
1099 #endif
1101 if (s_pfn_Convert_SDDL_To_SD == NULL)
1103 errno = ENOTSUP;
1104 return FALSE;
1107 retval = s_pfn_Convert_SDDL_To_SD (StringSecurityDescriptor,
1108 StringSDRevision,
1109 SecurityDescriptor,
1110 SecurityDescriptorSize);
1112 return retval;
1117 /* Return 1 if P is a valid pointer to an object of size SIZE. Return
1118 0 if P is NOT a valid pointer. Return -1 if we cannot validate P.
1120 This is called from alloc.c:valid_pointer_p. */
1122 w32_valid_pointer_p (void *p, int size)
1124 SIZE_T done;
1125 HANDLE h = OpenProcess (PROCESS_VM_READ, FALSE, GetCurrentProcessId ());
1127 if (h)
1129 unsigned char *buf = alloca (size);
1130 int retval = ReadProcessMemory (h, p, buf, size, &done);
1132 CloseHandle (h);
1133 return retval;
1135 else
1136 return -1;
1139 static char startup_dir[MAXPATHLEN];
1141 /* Get the current working directory. */
1142 char *
1143 getcwd (char *dir, int dirsize)
1145 if (!dirsize)
1147 errno = EINVAL;
1148 return NULL;
1150 if (dirsize <= strlen (startup_dir))
1152 errno = ERANGE;
1153 return NULL;
1155 #if 0
1156 if (GetCurrentDirectory (MAXPATHLEN, dir) > 0)
1157 return dir;
1158 return NULL;
1159 #else
1160 /* Emacs doesn't actually change directory itself, it stays in the
1161 same directory where it was started. */
1162 strcpy (dir, startup_dir);
1163 return dir;
1164 #endif
1167 /* Emulate getloadavg. */
1169 struct load_sample {
1170 time_t sample_time;
1171 ULONGLONG idle;
1172 ULONGLONG kernel;
1173 ULONGLONG user;
1176 /* Number of processors on this machine. */
1177 static unsigned num_of_processors;
1179 /* We maintain 1-sec samples for the last 16 minutes in a circular buffer. */
1180 static struct load_sample samples[16*60];
1181 static int first_idx = -1, last_idx = -1;
1182 static int max_idx = sizeof (samples) / sizeof (samples[0]);
1184 static int
1185 buf_next (int from)
1187 int next_idx = from + 1;
1189 if (next_idx >= max_idx)
1190 next_idx = 0;
1192 return next_idx;
1195 static int
1196 buf_prev (int from)
1198 int prev_idx = from - 1;
1200 if (prev_idx < 0)
1201 prev_idx = max_idx - 1;
1203 return prev_idx;
1206 static void
1207 sample_system_load (ULONGLONG *idle, ULONGLONG *kernel, ULONGLONG *user)
1209 SYSTEM_INFO sysinfo;
1210 FILETIME ft_idle, ft_user, ft_kernel;
1212 /* Initialize the number of processors on this machine. */
1213 if (num_of_processors <= 0)
1215 get_native_system_info (&sysinfo);
1216 num_of_processors = sysinfo.dwNumberOfProcessors;
1217 if (num_of_processors <= 0)
1219 GetSystemInfo (&sysinfo);
1220 num_of_processors = sysinfo.dwNumberOfProcessors;
1222 if (num_of_processors <= 0)
1223 num_of_processors = 1;
1226 /* TODO: Take into account threads that are ready to run, by
1227 sampling the "\System\Processor Queue Length" performance
1228 counter. The code below accounts only for threads that are
1229 actually running. */
1231 if (get_system_times (&ft_idle, &ft_kernel, &ft_user))
1233 ULARGE_INTEGER uidle, ukernel, uuser;
1235 memcpy (&uidle, &ft_idle, sizeof (ft_idle));
1236 memcpy (&ukernel, &ft_kernel, sizeof (ft_kernel));
1237 memcpy (&uuser, &ft_user, sizeof (ft_user));
1238 *idle = uidle.QuadPart;
1239 *kernel = ukernel.QuadPart;
1240 *user = uuser.QuadPart;
1242 else
1244 *idle = 0;
1245 *kernel = 0;
1246 *user = 0;
1250 /* Produce the load average for a given time interval, using the
1251 samples in the samples[] array. WHICH can be 0, 1, or 2, meaning
1252 1-minute, 5-minute, or 15-minute average, respectively. */
1253 static double
1254 getavg (int which)
1256 double retval = -1.0;
1257 double tdiff;
1258 int idx;
1259 double span = (which == 0 ? 1.0 : (which == 1 ? 5.0 : 15.0)) * 60;
1260 time_t now = samples[last_idx].sample_time;
1262 if (first_idx != last_idx)
1264 for (idx = buf_prev (last_idx); ; idx = buf_prev (idx))
1266 tdiff = difftime (now, samples[idx].sample_time);
1267 if (tdiff >= span - 2*DBL_EPSILON*now)
1269 long double sys =
1270 samples[last_idx].kernel + samples[last_idx].user
1271 - (samples[idx].kernel + samples[idx].user);
1272 long double idl = samples[last_idx].idle - samples[idx].idle;
1274 retval = (1.0 - idl / sys) * num_of_processors;
1275 break;
1277 if (idx == first_idx)
1278 break;
1282 return retval;
1286 getloadavg (double loadavg[], int nelem)
1288 int elem;
1289 ULONGLONG idle, kernel, user;
1290 time_t now = time (NULL);
1292 /* Store another sample. We ignore samples that are less than 1 sec
1293 apart. */
1294 if (difftime (now, samples[last_idx].sample_time) >= 1.0 - 2*DBL_EPSILON*now)
1296 sample_system_load (&idle, &kernel, &user);
1297 last_idx = buf_next (last_idx);
1298 samples[last_idx].sample_time = now;
1299 samples[last_idx].idle = idle;
1300 samples[last_idx].kernel = kernel;
1301 samples[last_idx].user = user;
1302 /* If the buffer has more that 15 min worth of samples, discard
1303 the old ones. */
1304 if (first_idx == -1)
1305 first_idx = last_idx;
1306 while (first_idx != last_idx
1307 && (difftime (now, samples[first_idx].sample_time)
1308 >= 15.0*60 + 2*DBL_EPSILON*now))
1309 first_idx = buf_next (first_idx);
1312 for (elem = 0; elem < nelem; elem++)
1314 double avg = getavg (elem);
1316 if (avg < 0)
1317 break;
1318 loadavg[elem] = avg;
1321 return elem;
1324 /* Emulate getpwuid, getpwnam and others. */
1326 #define PASSWD_FIELD_SIZE 256
1328 static char dflt_passwd_name[PASSWD_FIELD_SIZE];
1329 static char dflt_passwd_passwd[PASSWD_FIELD_SIZE];
1330 static char dflt_passwd_gecos[PASSWD_FIELD_SIZE];
1331 static char dflt_passwd_dir[PASSWD_FIELD_SIZE];
1332 static char dflt_passwd_shell[PASSWD_FIELD_SIZE];
1334 static struct passwd dflt_passwd =
1336 dflt_passwd_name,
1337 dflt_passwd_passwd,
1341 dflt_passwd_gecos,
1342 dflt_passwd_dir,
1343 dflt_passwd_shell,
1346 static char dflt_group_name[GNLEN+1];
1348 static struct group dflt_group =
1350 /* When group information is not available, we return this as the
1351 group for all files. */
1352 dflt_group_name,
1356 unsigned
1357 getuid (void)
1359 return dflt_passwd.pw_uid;
1362 unsigned
1363 geteuid (void)
1365 /* I could imagine arguing for checking to see whether the user is
1366 in the Administrators group and returning a UID of 0 for that
1367 case, but I don't know how wise that would be in the long run. */
1368 return getuid ();
1371 unsigned
1372 getgid (void)
1374 return dflt_passwd.pw_gid;
1377 unsigned
1378 getegid (void)
1380 return getgid ();
1383 struct passwd *
1384 getpwuid (unsigned uid)
1386 if (uid == dflt_passwd.pw_uid)
1387 return &dflt_passwd;
1388 return NULL;
1391 struct group *
1392 getgrgid (gid_t gid)
1394 return &dflt_group;
1397 struct passwd *
1398 getpwnam (char *name)
1400 struct passwd *pw;
1402 pw = getpwuid (getuid ());
1403 if (!pw)
1404 return pw;
1406 if (xstrcasecmp (name, pw->pw_name))
1407 return NULL;
1409 return pw;
1412 static void
1413 init_user_info (void)
1415 /* Find the user's real name by opening the process token and
1416 looking up the name associated with the user-sid in that token.
1418 Use the relative portion of the identifier authority value from
1419 the user-sid as the user id value (same for group id using the
1420 primary group sid from the process token). */
1422 char uname[UNLEN+1], gname[GNLEN+1], domain[1025];
1423 DWORD ulength = sizeof (uname), dlength = sizeof (domain), needed;
1424 DWORD glength = sizeof (gname);
1425 HANDLE token = NULL;
1426 SID_NAME_USE user_type;
1427 unsigned char *buf = NULL;
1428 DWORD blen = 0;
1429 TOKEN_USER user_token;
1430 TOKEN_PRIMARY_GROUP group_token;
1431 BOOL result;
1433 result = open_process_token (GetCurrentProcess (), TOKEN_QUERY, &token);
1434 if (result)
1436 result = get_token_information (token, TokenUser, NULL, 0, &blen);
1437 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
1439 buf = xmalloc (blen);
1440 result = get_token_information (token, TokenUser,
1441 (LPVOID)buf, blen, &needed);
1442 if (result)
1444 memcpy (&user_token, buf, sizeof (user_token));
1445 result = lookup_account_sid (NULL, user_token.User.Sid,
1446 uname, &ulength,
1447 domain, &dlength, &user_type);
1450 else
1451 result = FALSE;
1453 if (result)
1455 strcpy (dflt_passwd.pw_name, uname);
1456 /* Determine a reasonable uid value. */
1457 if (xstrcasecmp ("administrator", uname) == 0)
1459 dflt_passwd.pw_uid = 500; /* well-known Administrator uid */
1460 dflt_passwd.pw_gid = 513; /* well-known None gid */
1462 else
1464 /* Use the last sub-authority value of the RID, the relative
1465 portion of the SID, as user/group ID. */
1466 dflt_passwd.pw_uid = get_rid (user_token.User.Sid);
1468 /* Get group id and name. */
1469 result = get_token_information (token, TokenPrimaryGroup,
1470 (LPVOID)buf, blen, &needed);
1471 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
1473 buf = xrealloc (buf, blen = needed);
1474 result = get_token_information (token, TokenPrimaryGroup,
1475 (LPVOID)buf, blen, &needed);
1477 if (result)
1479 memcpy (&group_token, buf, sizeof (group_token));
1480 dflt_passwd.pw_gid = get_rid (group_token.PrimaryGroup);
1481 dlength = sizeof (domain);
1482 /* If we can get at the real Primary Group name, use that.
1483 Otherwise, the default group name was already set to
1484 "None" in globals_of_w32. */
1485 if (lookup_account_sid (NULL, group_token.PrimaryGroup,
1486 gname, &glength, NULL, &dlength,
1487 &user_type))
1488 strcpy (dflt_group_name, gname);
1490 else
1491 dflt_passwd.pw_gid = dflt_passwd.pw_uid;
1494 /* If security calls are not supported (presumably because we
1495 are running under Windows 9X), fallback to this: */
1496 else if (GetUserName (uname, &ulength))
1498 strcpy (dflt_passwd.pw_name, uname);
1499 if (xstrcasecmp ("administrator", uname) == 0)
1500 dflt_passwd.pw_uid = 0;
1501 else
1502 dflt_passwd.pw_uid = 123;
1503 dflt_passwd.pw_gid = dflt_passwd.pw_uid;
1505 else
1507 strcpy (dflt_passwd.pw_name, "unknown");
1508 dflt_passwd.pw_uid = 123;
1509 dflt_passwd.pw_gid = 123;
1511 dflt_group.gr_gid = dflt_passwd.pw_gid;
1513 /* Ensure HOME and SHELL are defined. */
1514 if (getenv ("HOME") == NULL)
1515 emacs_abort ();
1516 if (getenv ("SHELL") == NULL)
1517 emacs_abort ();
1519 /* Set dir and shell from environment variables. */
1520 strcpy (dflt_passwd.pw_dir, getenv ("HOME"));
1521 strcpy (dflt_passwd.pw_shell, getenv ("SHELL"));
1523 xfree (buf);
1524 if (token)
1525 CloseHandle (token);
1529 random (void)
1531 /* rand () on NT gives us 15 random bits...hack together 30 bits. */
1532 return ((rand () << 15) | rand ());
1535 void
1536 srandom (int seed)
1538 srand (seed);
1541 /* Current codepage for encoding file names. */
1542 static int file_name_codepage;
1544 /* Return the maximum length in bytes of a multibyte character
1545 sequence encoded in the current ANSI codepage. This is required to
1546 correctly walk the encoded file names one character at a time. */
1547 static int
1548 max_filename_mbslen (void)
1550 /* A simple cache to avoid calling GetCPInfo every time we need to
1551 normalize a file name. The file-name encoding is not supposed to
1552 be changed too frequently, if ever. */
1553 static Lisp_Object last_file_name_encoding;
1554 static int last_max_mbslen;
1555 Lisp_Object current_encoding;
1557 current_encoding = Vfile_name_coding_system;
1558 if (NILP (current_encoding))
1559 current_encoding = Vdefault_file_name_coding_system;
1561 if (!EQ (last_file_name_encoding, current_encoding))
1563 CPINFO cp_info;
1565 last_file_name_encoding = current_encoding;
1566 /* Default to the current ANSI codepage. */
1567 file_name_codepage = w32_ansi_code_page;
1568 if (!NILP (current_encoding))
1570 char *cpname = SDATA (SYMBOL_NAME (current_encoding));
1571 char *cp = NULL, *end;
1572 int cpnum;
1574 if (strncmp (cpname, "cp", 2) == 0)
1575 cp = cpname + 2;
1576 else if (strncmp (cpname, "windows-", 8) == 0)
1577 cp = cpname + 8;
1579 if (cp)
1581 end = cp;
1582 cpnum = strtol (cp, &end, 10);
1583 if (cpnum && *end == '\0' && end - cp >= 2)
1584 file_name_codepage = cpnum;
1588 if (!file_name_codepage)
1589 file_name_codepage = CP_ACP; /* CP_ACP = 0, but let's not assume that */
1591 if (!GetCPInfo (file_name_codepage, &cp_info))
1593 file_name_codepage = CP_ACP;
1594 if (!GetCPInfo (file_name_codepage, &cp_info))
1595 emacs_abort ();
1597 last_max_mbslen = cp_info.MaxCharSize;
1600 return last_max_mbslen;
1603 /* Normalize filename by converting all path separators to
1604 the specified separator. Also conditionally convert upper
1605 case path name components to lower case. */
1607 static void
1608 normalize_filename (register char *fp, char path_sep, int multibyte)
1610 char sep;
1611 char *elem, *p2;
1612 int dbcs_p = max_filename_mbslen () > 1;
1614 /* Multibyte file names are in the Emacs internal representation, so
1615 we can traverse them by bytes with no problems. */
1616 if (multibyte)
1617 dbcs_p = 0;
1619 /* Always lower-case drive letters a-z, even if the filesystem
1620 preserves case in filenames.
1621 This is so filenames can be compared by string comparison
1622 functions that are case-sensitive. Even case-preserving filesystems
1623 do not distinguish case in drive letters. */
1624 if (dbcs_p)
1625 p2 = CharNextExA (file_name_codepage, fp, 0);
1626 else
1627 p2 = fp + 1;
1629 if (*p2 == ':' && *fp >= 'A' && *fp <= 'Z')
1631 *fp += 'a' - 'A';
1632 fp += 2;
1635 if (multibyte || NILP (Vw32_downcase_file_names))
1637 while (*fp)
1639 if (*fp == '/' || *fp == '\\')
1640 *fp = path_sep;
1641 if (!dbcs_p)
1642 fp++;
1643 else
1644 fp = CharNextExA (file_name_codepage, fp, 0);
1646 return;
1649 sep = path_sep; /* convert to this path separator */
1650 elem = fp; /* start of current path element */
1652 do {
1653 if (*fp >= 'a' && *fp <= 'z')
1654 elem = 0; /* don't convert this element */
1656 if (*fp == 0 || *fp == ':')
1658 sep = *fp; /* restore current separator (or 0) */
1659 *fp = '/'; /* after conversion of this element */
1662 if (*fp == '/' || *fp == '\\')
1664 if (elem && elem != fp)
1666 *fp = 0; /* temporary end of string */
1667 _mbslwr (elem); /* while we convert to lower case */
1669 *fp = sep; /* convert (or restore) path separator */
1670 elem = fp + 1; /* next element starts after separator */
1671 sep = path_sep;
1673 if (*fp)
1675 if (!dbcs_p)
1676 fp++;
1677 else
1678 fp = CharNextExA (file_name_codepage, fp, 0);
1680 } while (*fp);
1683 /* Destructively turn backslashes into slashes. MULTIBYTE non-zero
1684 means the file name is a multibyte string in Emacs's internal
1685 representation. */
1686 void
1687 dostounix_filename (register char *p, int multibyte)
1689 normalize_filename (p, '/', multibyte);
1692 /* Destructively turn slashes into backslashes. */
1693 void
1694 unixtodos_filename (register char *p)
1696 normalize_filename (p, '\\', 0);
1699 /* Remove all CR's that are followed by a LF.
1700 (From msdos.c...probably should figure out a way to share it,
1701 although this code isn't going to ever change.) */
1702 static int
1703 crlf_to_lf (register int n, register unsigned char *buf)
1705 unsigned char *np = buf;
1706 unsigned char *startp = buf;
1707 unsigned char *endp = buf + n;
1709 if (n == 0)
1710 return n;
1711 while (buf < endp - 1)
1713 if (*buf == 0x0d)
1715 if (*(++buf) != 0x0a)
1716 *np++ = 0x0d;
1718 else
1719 *np++ = *buf++;
1721 if (buf < endp)
1722 *np++ = *buf++;
1723 return np - startp;
1726 /* Parse the root part of file name, if present. Return length and
1727 optionally store pointer to char after root. */
1728 static int
1729 parse_root (char * name, char ** pPath)
1731 char * start = name;
1733 if (name == NULL)
1734 return 0;
1736 /* find the root name of the volume if given */
1737 if (isalpha (name[0]) && name[1] == ':')
1739 /* skip past drive specifier */
1740 name += 2;
1741 if (IS_DIRECTORY_SEP (name[0]))
1742 name++;
1744 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
1746 int slashes = 2;
1747 int dbcs_p = max_filename_mbslen () > 1;
1749 name += 2;
1752 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
1753 break;
1754 if (dbcs_p)
1755 name = CharNextExA (file_name_codepage, name, 0);
1756 else
1757 name++;
1759 while ( *name );
1760 if (IS_DIRECTORY_SEP (name[0]))
1761 name++;
1764 if (pPath)
1765 *pPath = name;
1767 return name - start;
1770 /* Get long base name for name; name is assumed to be absolute. */
1771 static int
1772 get_long_basename (char * name, char * buf, int size)
1774 WIN32_FIND_DATA find_data;
1775 HANDLE dir_handle;
1776 int len = 0;
1778 /* must be valid filename, no wild cards or other invalid characters */
1779 if (_mbspbrk (name, "*?|<>\""))
1780 return 0;
1782 dir_handle = FindFirstFile (name, &find_data);
1783 if (dir_handle != INVALID_HANDLE_VALUE)
1785 if ((len = strlen (find_data.cFileName)) < size)
1786 memcpy (buf, find_data.cFileName, len + 1);
1787 else
1788 len = 0;
1789 FindClose (dir_handle);
1791 return len;
1794 /* Get long name for file, if possible (assumed to be absolute). */
1795 BOOL
1796 w32_get_long_filename (char * name, char * buf, int size)
1798 char * o = buf;
1799 char * p;
1800 char * q;
1801 char full[ MAX_PATH ];
1802 int len;
1804 len = strlen (name);
1805 if (len >= MAX_PATH)
1806 return FALSE;
1808 /* Use local copy for destructive modification. */
1809 memcpy (full, name, len+1);
1810 unixtodos_filename (full);
1812 /* Copy root part verbatim. */
1813 len = parse_root (full, &p);
1814 memcpy (o, full, len);
1815 o += len;
1816 *o = '\0';
1817 size -= len;
1819 while (p != NULL && *p)
1821 q = p;
1822 p = _mbschr (q, '\\');
1823 if (p) *p = '\0';
1824 len = get_long_basename (full, o, size);
1825 if (len > 0)
1827 o += len;
1828 size -= len;
1829 if (p != NULL)
1831 *p++ = '\\';
1832 if (size < 2)
1833 return FALSE;
1834 *o++ = '\\';
1835 size--;
1836 *o = '\0';
1839 else
1840 return FALSE;
1843 return TRUE;
1846 static int
1847 is_unc_volume (const char *filename)
1849 const char *ptr = filename;
1851 if (!IS_DIRECTORY_SEP (ptr[0]) || !IS_DIRECTORY_SEP (ptr[1]) || !ptr[2])
1852 return 0;
1854 if (_mbspbrk (ptr + 2, "*?|<>\"\\/"))
1855 return 0;
1857 return 1;
1860 /* Emulate the Posix unsetenv. */
1862 unsetenv (const char *name)
1864 char *var;
1865 size_t name_len;
1866 int retval;
1868 if (name == NULL || *name == '\0' || strchr (name, '=') != NULL)
1870 errno = EINVAL;
1871 return -1;
1873 name_len = strlen (name);
1874 /* MS docs says an environment variable cannot be longer than 32K. */
1875 if (name_len > 32767)
1877 errno = ENOMEM;
1878 return 0;
1880 /* It is safe to use 'alloca' with 32K size, since the stack is at
1881 least 2MB, and we set it to 8MB in the link command line. */
1882 var = alloca (name_len + 2);
1883 strncpy (var, name, name_len);
1884 var[name_len++] = '=';
1885 var[name_len] = '\0';
1886 return _putenv (var);
1889 /* MS _putenv doesn't support removing a variable when the argument
1890 does not include the '=' character, so we fix that here. */
1892 sys_putenv (char *str)
1894 const char *const name_end = strchr (str, '=');
1896 if (name_end == NULL)
1898 /* Remove the variable from the environment. */
1899 return unsetenv (str);
1902 return _putenv (str);
1905 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
1907 LPBYTE
1908 w32_get_resource (char *key, LPDWORD lpdwtype)
1910 LPBYTE lpvalue;
1911 HKEY hrootkey = NULL;
1912 DWORD cbData;
1914 /* Check both the current user and the local machine to see if
1915 we have any resources. */
1917 if (RegOpenKeyEx (HKEY_CURRENT_USER, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
1919 lpvalue = NULL;
1921 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
1922 && (lpvalue = xmalloc (cbData)) != NULL
1923 && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
1925 RegCloseKey (hrootkey);
1926 return (lpvalue);
1929 xfree (lpvalue);
1931 RegCloseKey (hrootkey);
1934 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
1936 lpvalue = NULL;
1938 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
1939 && (lpvalue = xmalloc (cbData)) != NULL
1940 && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
1942 RegCloseKey (hrootkey);
1943 return (lpvalue);
1946 xfree (lpvalue);
1948 RegCloseKey (hrootkey);
1951 return (NULL);
1954 char *get_emacs_configuration (void);
1956 void
1957 init_environment (char ** argv)
1959 static const char * const tempdirs[] = {
1960 "$TMPDIR", "$TEMP", "$TMP", "c:/"
1963 int i;
1965 const int imax = sizeof (tempdirs) / sizeof (tempdirs[0]);
1967 /* Make sure they have a usable $TMPDIR. Many Emacs functions use
1968 temporary files and assume "/tmp" if $TMPDIR is unset, which
1969 will break on DOS/Windows. Refuse to work if we cannot find
1970 a directory, not even "c:/", usable for that purpose. */
1971 for (i = 0; i < imax ; i++)
1973 const char *tmp = tempdirs[i];
1975 if (*tmp == '$')
1976 tmp = getenv (tmp + 1);
1977 /* Note that `access' can lie to us if the directory resides on a
1978 read-only filesystem, like CD-ROM or a write-protected floppy.
1979 The only way to be really sure is to actually create a file and
1980 see if it succeeds. But I think that's too much to ask. */
1982 /* MSVCRT's _access crashes with D_OK. */
1983 if (tmp && faccessat (AT_FDCWD, tmp, D_OK, AT_EACCESS) == 0)
1985 char * var = alloca (strlen (tmp) + 8);
1986 sprintf (var, "TMPDIR=%s", tmp);
1987 _putenv (strdup (var));
1988 break;
1991 if (i >= imax)
1992 cmd_error_internal
1993 (Fcons (Qerror,
1994 Fcons (build_string ("no usable temporary directories found!!"),
1995 Qnil)),
1996 "While setting TMPDIR: ");
1998 /* Check for environment variables and use registry settings if they
1999 don't exist. Fallback on default values where applicable. */
2001 int i;
2002 LPBYTE lpval;
2003 DWORD dwType;
2004 char locale_name[32];
2005 char default_home[MAX_PATH];
2006 int appdata = 0;
2008 static const struct env_entry
2010 char * name;
2011 char * def_value;
2012 } dflt_envvars[] =
2014 /* If the default value is NULL, we will use the value from the
2015 outside environment or the Registry, but will not push the
2016 variable into the Emacs environment if it is defined neither
2017 in the Registry nor in the outside environment. */
2018 {"HOME", "C:/"},
2019 {"PRELOAD_WINSOCK", NULL},
2020 {"emacs_dir", "C:/emacs"},
2021 {"EMACSLOADPATH", NULL},
2022 {"SHELL", "cmdproxy.exe"}, /* perhaps it is somewhere on PATH */
2023 {"EMACSDATA", NULL},
2024 {"EMACSPATH", NULL},
2025 {"INFOPATH", NULL},
2026 {"EMACSDOC", NULL},
2027 {"TERM", "cmd"},
2028 {"LANG", NULL},
2031 #define N_ENV_VARS sizeof (dflt_envvars)/sizeof (dflt_envvars[0])
2033 /* We need to copy dflt_envvars[] and work on the copy because we
2034 don't want the dumped Emacs to inherit the values of
2035 environment variables we saw during dumping (which could be on
2036 a different system). The defaults above must be left intact. */
2037 struct env_entry env_vars[N_ENV_VARS];
2039 for (i = 0; i < N_ENV_VARS; i++)
2040 env_vars[i] = dflt_envvars[i];
2042 /* For backwards compatibility, check if a .emacs file exists in C:/
2043 If not, then we can try to default to the appdata directory under the
2044 user's profile, which is more likely to be writable. */
2045 if (!check_existing ("C:/.emacs"))
2047 HRESULT profile_result;
2048 /* Dynamically load ShGetFolderPath, as it won't exist on versions
2049 of Windows 95 and NT4 that have not been updated to include
2050 MSIE 5. */
2051 ShGetFolderPath_fn get_folder_path;
2052 get_folder_path = (ShGetFolderPath_fn)
2053 GetProcAddress (GetModuleHandle ("shell32.dll"), "SHGetFolderPathA");
2055 if (get_folder_path != NULL)
2057 profile_result = get_folder_path (NULL, CSIDL_APPDATA, NULL,
2058 0, default_home);
2060 /* If we can't get the appdata dir, revert to old behavior. */
2061 if (profile_result == S_OK)
2063 env_vars[0].def_value = default_home;
2064 appdata = 1;
2069 /* Get default locale info and use it for LANG. */
2070 if (GetLocaleInfo (LOCALE_USER_DEFAULT,
2071 LOCALE_SABBREVLANGNAME | LOCALE_USE_CP_ACP,
2072 locale_name, sizeof (locale_name)))
2074 for (i = 0; i < N_ENV_VARS; i++)
2076 if (strcmp (env_vars[i].name, "LANG") == 0)
2078 env_vars[i].def_value = locale_name;
2079 break;
2084 #define SET_ENV_BUF_SIZE (4 * MAX_PATH) /* to cover EMACSLOADPATH */
2086 /* Treat emacs_dir specially: set it unconditionally based on our
2087 location. */
2089 char *p;
2090 char modname[MAX_PATH];
2092 if (!GetModuleFileName (NULL, modname, MAX_PATH))
2093 emacs_abort ();
2094 if ((p = _mbsrchr (modname, '\\')) == NULL)
2095 emacs_abort ();
2096 *p = 0;
2098 if ((p = _mbsrchr (modname, '\\'))
2099 /* From bin means installed Emacs, from src means uninstalled. */
2100 && (xstrcasecmp (p, "\\bin") == 0 || xstrcasecmp (p, "\\src") == 0))
2102 char buf[SET_ENV_BUF_SIZE];
2103 int within_build_tree = xstrcasecmp (p, "\\src") == 0;
2105 *p = 0;
2106 for (p = modname; *p; p = CharNext (p))
2107 if (*p == '\\') *p = '/';
2109 _snprintf (buf, sizeof (buf)-1, "emacs_dir=%s", modname);
2110 _putenv (strdup (buf));
2111 /* If we are running from the Posix-like build tree, define
2112 SHELL to point to our own cmdproxy. The loop below will
2113 then disregard PATH_EXEC and the default value. */
2114 if (within_build_tree)
2116 _snprintf (buf, sizeof (buf) - 1,
2117 "SHELL=%s/nt/cmdproxy.exe", modname);
2118 _putenv (strdup (buf));
2121 /* Handle running emacs from the build directory: src/oo-spd/i386/ */
2123 /* FIXME: should use substring of get_emacs_configuration ().
2124 But I don't think the Windows build supports alpha, mips etc
2125 anymore, so have taken the easy option for now. */
2126 else if (p && (xstrcasecmp (p, "\\i386") == 0
2127 || xstrcasecmp (p, "\\AMD64") == 0))
2129 *p = 0;
2130 p = _mbsrchr (modname, '\\');
2131 if (p != NULL)
2133 *p = 0;
2134 p = _mbsrchr (modname, '\\');
2135 if (p && xstrcasecmp (p, "\\src") == 0)
2137 char buf[SET_ENV_BUF_SIZE];
2139 *p = 0;
2140 for (p = modname; *p; p = CharNext (p))
2141 if (*p == '\\') *p = '/';
2143 _snprintf (buf, sizeof (buf)-1, "emacs_dir=%s", modname);
2144 _putenv (strdup (buf));
2150 for (i = 0; i < N_ENV_VARS; i++)
2152 if (!getenv (env_vars[i].name))
2154 int dont_free = 0;
2155 char bufc[SET_ENV_BUF_SIZE];
2157 if ((lpval = w32_get_resource (env_vars[i].name, &dwType)) == NULL
2158 /* Also ignore empty environment variables. */
2159 || *lpval == 0)
2161 xfree (lpval);
2162 dont_free = 1;
2163 if (strcmp (env_vars[i].name, "SHELL") == 0)
2165 /* Look for cmdproxy.exe in every directory in
2166 PATH_EXEC. FIXME: This does not find cmdproxy
2167 in nt/ when we run uninstalled. */
2168 char fname[MAX_PATH];
2169 const char *pstart = PATH_EXEC, *pend;
2171 do {
2172 pend = _mbschr (pstart, ';');
2173 if (!pend)
2174 pend = pstart + strlen (pstart);
2175 /* Be defensive against series of ;;; characters. */
2176 if (pend > pstart)
2178 strncpy (fname, pstart, pend - pstart);
2179 fname[pend - pstart] = '/';
2180 strcpy (&fname[pend - pstart + 1], "cmdproxy.exe");
2181 ExpandEnvironmentStrings ((LPSTR) fname, bufc,
2182 sizeof (bufc));
2183 if (check_existing (bufc))
2185 lpval = bufc;
2186 dwType = REG_SZ;
2187 break;
2190 if (*pend)
2191 pstart = pend + 1;
2192 else
2193 pstart = pend;
2194 if (!*pstart)
2196 /* If not found in any directory, use the
2197 default as the last resort. */
2198 lpval = env_vars[i].def_value;
2199 dwType = REG_EXPAND_SZ;
2201 } while (*pstart);
2203 else
2205 lpval = env_vars[i].def_value;
2206 dwType = REG_EXPAND_SZ;
2208 if (strcmp (env_vars[i].name, "HOME") == 0 && !appdata)
2209 Vdelayed_warnings_list
2210 = Fcons (listn (CONSTYPE_HEAP, 2,
2211 intern ("initialization"),
2212 build_string ("Setting HOME to C:\\ by default is deprecated")),
2213 Vdelayed_warnings_list);
2216 if (lpval)
2218 char buf1[SET_ENV_BUF_SIZE], buf2[SET_ENV_BUF_SIZE];
2220 if (dwType == REG_EXPAND_SZ)
2221 ExpandEnvironmentStrings ((LPSTR) lpval, buf1, sizeof (buf1));
2222 else if (dwType == REG_SZ)
2223 strcpy (buf1, lpval);
2224 if (dwType == REG_EXPAND_SZ || dwType == REG_SZ)
2226 _snprintf (buf2, sizeof (buf2)-1, "%s=%s", env_vars[i].name,
2227 buf1);
2228 _putenv (strdup (buf2));
2231 if (!dont_free)
2232 xfree (lpval);
2238 /* Rebuild system configuration to reflect invoking system. */
2239 Vsystem_configuration = build_string (EMACS_CONFIGURATION);
2241 /* Another special case: on NT, the PATH variable is actually named
2242 "Path" although cmd.exe (perhaps NT itself) arranges for
2243 environment variable lookup and setting to be case insensitive.
2244 However, Emacs assumes a fully case sensitive environment, so we
2245 need to change "Path" to "PATH" to match the expectations of
2246 various elisp packages. We do this by the sneaky method of
2247 modifying the string in the C runtime environ entry.
2249 The same applies to COMSPEC. */
2251 char ** envp;
2253 for (envp = environ; *envp; envp++)
2254 if (_strnicmp (*envp, "PATH=", 5) == 0)
2255 memcpy (*envp, "PATH=", 5);
2256 else if (_strnicmp (*envp, "COMSPEC=", 8) == 0)
2257 memcpy (*envp, "COMSPEC=", 8);
2260 /* Remember the initial working directory for getcwd. */
2261 /* FIXME: Do we need to resolve possible symlinks in startup_dir?
2262 Does it matter anywhere in Emacs? */
2263 if (!GetCurrentDirectory (MAXPATHLEN, startup_dir))
2264 emacs_abort ();
2267 static char modname[MAX_PATH];
2269 if (!GetModuleFileName (NULL, modname, MAX_PATH))
2270 emacs_abort ();
2271 argv[0] = modname;
2274 /* Determine if there is a middle mouse button, to allow parse_button
2275 to decide whether right mouse events should be mouse-2 or
2276 mouse-3. */
2277 w32_num_mouse_buttons = GetSystemMetrics (SM_CMOUSEBUTTONS);
2279 init_user_info ();
2282 /* Called from expand-file-name when default-directory is not a string. */
2284 char *
2285 emacs_root_dir (void)
2287 static char root_dir[FILENAME_MAX];
2288 const char *p;
2290 p = getenv ("emacs_dir");
2291 if (p == NULL)
2292 emacs_abort ();
2293 strcpy (root_dir, p);
2294 root_dir[parse_root (root_dir, NULL)] = '\0';
2295 dostounix_filename (root_dir, 0);
2296 return root_dir;
2299 /* We don't have scripts to automatically determine the system configuration
2300 for Emacs before it's compiled, and we don't want to have to make the
2301 user enter it, so we define EMACS_CONFIGURATION to invoke this runtime
2302 routine. */
2304 char *
2305 get_emacs_configuration (void)
2307 char *arch, *oem, *os;
2308 int build_num;
2309 static char configuration_buffer[32];
2311 /* Determine the processor type. */
2312 switch (get_processor_type ())
2315 #ifdef PROCESSOR_INTEL_386
2316 case PROCESSOR_INTEL_386:
2317 case PROCESSOR_INTEL_486:
2318 case PROCESSOR_INTEL_PENTIUM:
2319 #ifdef _WIN64
2320 arch = "amd64";
2321 #else
2322 arch = "i386";
2323 #endif
2324 break;
2325 #endif
2326 #ifdef PROCESSOR_AMD_X8664
2327 case PROCESSOR_AMD_X8664:
2328 arch = "amd64";
2329 break;
2330 #endif
2332 #ifdef PROCESSOR_MIPS_R2000
2333 case PROCESSOR_MIPS_R2000:
2334 case PROCESSOR_MIPS_R3000:
2335 case PROCESSOR_MIPS_R4000:
2336 arch = "mips";
2337 break;
2338 #endif
2340 #ifdef PROCESSOR_ALPHA_21064
2341 case PROCESSOR_ALPHA_21064:
2342 arch = "alpha";
2343 break;
2344 #endif
2346 default:
2347 arch = "unknown";
2348 break;
2351 /* Use the OEM field to reflect the compiler/library combination. */
2352 #ifdef _MSC_VER
2353 #define COMPILER_NAME "msvc"
2354 #else
2355 #ifdef __GNUC__
2356 #define COMPILER_NAME "mingw"
2357 #else
2358 #define COMPILER_NAME "unknown"
2359 #endif
2360 #endif
2361 oem = COMPILER_NAME;
2363 switch (osinfo_cache.dwPlatformId) {
2364 case VER_PLATFORM_WIN32_NT:
2365 os = "nt";
2366 build_num = osinfo_cache.dwBuildNumber;
2367 break;
2368 case VER_PLATFORM_WIN32_WINDOWS:
2369 if (osinfo_cache.dwMinorVersion == 0) {
2370 os = "windows95";
2371 } else {
2372 os = "windows98";
2374 build_num = LOWORD (osinfo_cache.dwBuildNumber);
2375 break;
2376 case VER_PLATFORM_WIN32s:
2377 /* Not supported, should not happen. */
2378 os = "windows32s";
2379 build_num = LOWORD (osinfo_cache.dwBuildNumber);
2380 break;
2381 default:
2382 os = "unknown";
2383 build_num = 0;
2384 break;
2387 if (osinfo_cache.dwPlatformId == VER_PLATFORM_WIN32_NT) {
2388 sprintf (configuration_buffer, "%s-%s-%s%d.%d.%d", arch, oem, os,
2389 get_w32_major_version (), get_w32_minor_version (), build_num);
2390 } else {
2391 sprintf (configuration_buffer, "%s-%s-%s.%d", arch, oem, os, build_num);
2394 return configuration_buffer;
2397 char *
2398 get_emacs_configuration_options (void)
2400 static char *options_buffer;
2401 char cv[32]; /* Enough for COMPILER_VERSION. */
2402 char *options[] = {
2403 cv, /* To be filled later. */
2404 #ifdef EMACSDEBUG
2405 " --no-opt",
2406 #endif
2407 #ifdef ENABLE_CHECKING
2408 " --enable-checking",
2409 #endif
2410 /* configure.bat already sets USER_CFLAGS and USER_LDFLAGS
2411 with a starting space to save work here. */
2412 #ifdef USER_CFLAGS
2413 " --cflags", USER_CFLAGS,
2414 #endif
2415 #ifdef USER_LDFLAGS
2416 " --ldflags", USER_LDFLAGS,
2417 #endif
2418 NULL
2420 size_t size = 0;
2421 int i;
2423 /* Work out the effective configure options for this build. */
2424 #ifdef _MSC_VER
2425 #define COMPILER_VERSION "--with-msvc (%d.%02d)", _MSC_VER / 100, _MSC_VER % 100
2426 #else
2427 #ifdef __GNUC__
2428 #define COMPILER_VERSION "--with-gcc (%d.%d)", __GNUC__, __GNUC_MINOR__
2429 #else
2430 #define COMPILER_VERSION ""
2431 #endif
2432 #endif
2434 if (_snprintf (cv, sizeof (cv) - 1, COMPILER_VERSION) < 0)
2435 return "Error: not enough space for compiler version";
2436 cv[sizeof (cv) - 1] = '\0';
2438 for (i = 0; options[i]; i++)
2439 size += strlen (options[i]);
2441 options_buffer = xmalloc (size + 1);
2442 options_buffer[0] = '\0';
2444 for (i = 0; options[i]; i++)
2445 strcat (options_buffer, options[i]);
2447 return options_buffer;
2451 #include <sys/timeb.h>
2453 /* Emulate gettimeofday (Ulrich Leodolter, 1/11/95). */
2455 gettimeofday (struct timeval *__restrict tv, struct timezone *__restrict tz)
2457 struct _timeb tb;
2458 _ftime (&tb);
2460 tv->tv_sec = tb.time;
2461 tv->tv_usec = tb.millitm * 1000L;
2462 /* Implementation note: _ftime sometimes doesn't update the dstflag
2463 according to the new timezone when the system timezone is
2464 changed. We could fix that by using GetSystemTime and
2465 GetTimeZoneInformation, but that doesn't seem necessary, since
2466 Emacs always calls gettimeofday with the 2nd argument NULL (see
2467 current_emacs_time). */
2468 if (tz)
2470 tz->tz_minuteswest = tb.timezone; /* minutes west of Greenwich */
2471 tz->tz_dsttime = tb.dstflag; /* type of dst correction */
2473 return 0;
2476 /* Emulate fdutimens. */
2478 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2479 TIMESPEC[0] and TIMESPEC[1], respectively.
2480 FD must be either negative -- in which case it is ignored --
2481 or a file descriptor that is open on FILE.
2482 If FD is nonnegative, then FILE can be NULL, which means
2483 use just futimes instead of utimes.
2484 If TIMESPEC is null, FAIL.
2485 Return 0 on success, -1 (setting errno) on failure. */
2488 fdutimens (int fd, char const *file, struct timespec const timespec[2])
2490 struct _utimbuf ut;
2492 if (!timespec)
2494 errno = ENOSYS;
2495 return -1;
2497 if (fd < 0 && !file)
2499 errno = EBADF;
2500 return -1;
2502 ut.actime = timespec[0].tv_sec;
2503 ut.modtime = timespec[1].tv_sec;
2504 if (fd >= 0)
2505 return _futime (fd, &ut);
2506 else
2507 return _utime (file, &ut);
2511 /* ------------------------------------------------------------------------- */
2512 /* IO support and wrapper functions for the Windows API. */
2513 /* ------------------------------------------------------------------------- */
2515 /* Place a wrapper around the MSVC version of ctime. It returns NULL
2516 on network directories, so we handle that case here.
2517 (Ulrich Leodolter, 1/11/95). */
2518 char *
2519 sys_ctime (const time_t *t)
2521 char *str = (char *) ctime (t);
2522 return (str ? str : "Sun Jan 01 00:00:00 1970");
2525 /* Emulate sleep...we could have done this with a define, but that
2526 would necessitate including windows.h in the files that used it.
2527 This is much easier. */
2528 void
2529 sys_sleep (int seconds)
2531 Sleep (seconds * 1000);
2534 /* Internal MSVC functions for low-level descriptor munging */
2535 extern int __cdecl _set_osfhnd (int fd, long h);
2536 extern int __cdecl _free_osfhnd (int fd);
2538 /* parallel array of private info on file handles */
2539 filedesc fd_info [ MAXDESC ];
2541 typedef struct volume_info_data {
2542 struct volume_info_data * next;
2544 /* time when info was obtained */
2545 DWORD timestamp;
2547 /* actual volume info */
2548 char * root_dir;
2549 DWORD serialnum;
2550 DWORD maxcomp;
2551 DWORD flags;
2552 char * name;
2553 char * type;
2554 } volume_info_data;
2556 /* Global referenced by various functions. */
2557 static volume_info_data volume_info;
2559 /* Vector to indicate which drives are local and fixed (for which cached
2560 data never expires). */
2561 static BOOL fixed_drives[26];
2563 /* Consider cached volume information to be stale if older than 10s,
2564 at least for non-local drives. Info for fixed drives is never stale. */
2565 #define DRIVE_INDEX( c ) ( (c) <= 'Z' ? (c) - 'A' : (c) - 'a' )
2566 #define VOLINFO_STILL_VALID( root_dir, info ) \
2567 ( ( isalpha (root_dir[0]) && \
2568 fixed_drives[ DRIVE_INDEX (root_dir[0]) ] ) \
2569 || GetTickCount () - info->timestamp < 10000 )
2571 /* Cache support functions. */
2573 /* Simple linked list with linear search is sufficient. */
2574 static volume_info_data *volume_cache = NULL;
2576 static volume_info_data *
2577 lookup_volume_info (char * root_dir)
2579 volume_info_data * info;
2581 for (info = volume_cache; info; info = info->next)
2582 if (xstrcasecmp (info->root_dir, root_dir) == 0)
2583 break;
2584 return info;
2587 static void
2588 add_volume_info (char * root_dir, volume_info_data * info)
2590 info->root_dir = xstrdup (root_dir);
2591 info->next = volume_cache;
2592 volume_cache = info;
2596 /* Wrapper for GetVolumeInformation, which uses caching to avoid
2597 performance penalty (~2ms on 486 for local drives, 7.5ms for local
2598 cdrom drive, ~5-10ms or more for remote drives on LAN). */
2599 static volume_info_data *
2600 GetCachedVolumeInformation (char * root_dir)
2602 volume_info_data * info;
2603 char default_root[ MAX_PATH ];
2605 /* NULL for root_dir means use root from current directory. */
2606 if (root_dir == NULL)
2608 if (GetCurrentDirectory (MAX_PATH, default_root) == 0)
2609 return NULL;
2610 parse_root (default_root, &root_dir);
2611 *root_dir = 0;
2612 root_dir = default_root;
2615 /* Local fixed drives can be cached permanently. Removable drives
2616 cannot be cached permanently, since the volume name and serial
2617 number (if nothing else) can change. Remote drives should be
2618 treated as if they are removable, since there is no sure way to
2619 tell whether they are or not. Also, the UNC association of drive
2620 letters mapped to remote volumes can be changed at any time (even
2621 by other processes) without notice.
2623 As a compromise, so we can benefit from caching info for remote
2624 volumes, we use a simple expiry mechanism to invalidate cache
2625 entries that are more than ten seconds old. */
2627 #if 0
2628 /* No point doing this, because WNetGetConnection is even slower than
2629 GetVolumeInformation, consistently taking ~50ms on a 486 (FWIW,
2630 GetDriveType is about the only call of this type which does not
2631 involve network access, and so is extremely quick). */
2633 /* Map drive letter to UNC if remote. */
2634 if (isalpha (root_dir[0]) && !fixed[DRIVE_INDEX (root_dir[0])])
2636 char remote_name[ 256 ];
2637 char drive[3] = { root_dir[0], ':' };
2639 if (WNetGetConnection (drive, remote_name, sizeof (remote_name))
2640 == NO_ERROR)
2641 /* do something */ ;
2643 #endif
2645 info = lookup_volume_info (root_dir);
2647 if (info == NULL || ! VOLINFO_STILL_VALID (root_dir, info))
2649 char name[ 256 ];
2650 DWORD serialnum;
2651 DWORD maxcomp;
2652 DWORD flags;
2653 char type[ 256 ];
2655 /* Info is not cached, or is stale. */
2656 if (!GetVolumeInformation (root_dir,
2657 name, sizeof (name),
2658 &serialnum,
2659 &maxcomp,
2660 &flags,
2661 type, sizeof (type)))
2662 return NULL;
2664 /* Cache the volume information for future use, overwriting existing
2665 entry if present. */
2666 if (info == NULL)
2668 info = xmalloc (sizeof (volume_info_data));
2669 add_volume_info (root_dir, info);
2671 else
2673 xfree (info->name);
2674 xfree (info->type);
2677 info->name = xstrdup (name);
2678 info->serialnum = serialnum;
2679 info->maxcomp = maxcomp;
2680 info->flags = flags;
2681 info->type = xstrdup (type);
2682 info->timestamp = GetTickCount ();
2685 return info;
2688 /* Get information on the volume where NAME is held; set path pointer to
2689 start of pathname in NAME (past UNC header\volume header if present),
2690 if pPath is non-NULL.
2692 Note: if NAME includes symlinks, the information is for the volume
2693 of the symlink, not of its target. That's because, even though
2694 GetVolumeInformation returns information about the symlink target
2695 of its argument, we only pass the root directory to
2696 GetVolumeInformation, not the full NAME. */
2697 static int
2698 get_volume_info (const char * name, const char ** pPath)
2700 char temp[MAX_PATH];
2701 char *rootname = NULL; /* default to current volume */
2702 volume_info_data * info;
2704 if (name == NULL)
2705 return FALSE;
2707 /* Find the root name of the volume if given. */
2708 if (isalpha (name[0]) && name[1] == ':')
2710 rootname = temp;
2711 temp[0] = *name++;
2712 temp[1] = *name++;
2713 temp[2] = '\\';
2714 temp[3] = 0;
2716 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
2718 char *str = temp;
2719 int slashes = 4;
2720 int dbcs_p = max_filename_mbslen () > 1;
2722 rootname = temp;
2725 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
2726 break;
2727 if (!dbcs_p)
2728 *str++ = *name++;
2729 else
2731 const char *p = name;
2733 name = CharNextExA (file_name_codepage, name, 0);
2734 memcpy (str, p, name - p);
2735 str += name - p;
2738 while ( *name );
2740 *str++ = '\\';
2741 *str = 0;
2744 if (pPath)
2745 *pPath = name;
2747 info = GetCachedVolumeInformation (rootname);
2748 if (info != NULL)
2750 /* Set global referenced by other functions. */
2751 volume_info = *info;
2752 return TRUE;
2754 return FALSE;
2757 /* Determine if volume is FAT format (ie. only supports short 8.3
2758 names); also set path pointer to start of pathname in name, if
2759 pPath is non-NULL. */
2760 static int
2761 is_fat_volume (const char * name, const char ** pPath)
2763 if (get_volume_info (name, pPath))
2764 return (volume_info.maxcomp == 12);
2765 return FALSE;
2768 /* Map filename to a valid 8.3 name if necessary.
2769 The result is a pointer to a static buffer, so CAVEAT EMPTOR! */
2770 const char *
2771 map_w32_filename (const char * name, const char ** pPath)
2773 static char shortname[MAX_PATH];
2774 char * str = shortname;
2775 char c;
2776 char * path;
2777 const char * save_name = name;
2779 if (strlen (name) >= MAX_PATH)
2781 /* Return a filename which will cause callers to fail. */
2782 strcpy (shortname, "?");
2783 return shortname;
2786 if (is_fat_volume (name, (const char **)&path)) /* truncate to 8.3 */
2788 register int left = 8; /* maximum number of chars in part */
2789 register int extn = 0; /* extension added? */
2790 register int dots = 2; /* maximum number of dots allowed */
2792 while (name < path)
2793 *str++ = *name++; /* skip past UNC header */
2795 while ((c = *name++))
2797 switch ( c )
2799 case ':':
2800 case '\\':
2801 case '/':
2802 *str++ = (c == ':' ? ':' : '\\');
2803 extn = 0; /* reset extension flags */
2804 dots = 2; /* max 2 dots */
2805 left = 8; /* max length 8 for main part */
2806 break;
2807 case '.':
2808 if ( dots )
2810 /* Convert path components of the form .xxx to _xxx,
2811 but leave . and .. as they are. This allows .emacs
2812 to be read as _emacs, for example. */
2814 if (! *name ||
2815 *name == '.' ||
2816 IS_DIRECTORY_SEP (*name))
2818 *str++ = '.';
2819 dots--;
2821 else
2823 *str++ = '_';
2824 left--;
2825 dots = 0;
2828 else if ( !extn )
2830 *str++ = '.';
2831 extn = 1; /* we've got an extension */
2832 left = 3; /* 3 chars in extension */
2834 else
2836 /* any embedded dots after the first are converted to _ */
2837 *str++ = '_';
2839 break;
2840 case '~':
2841 case '#': /* don't lose these, they're important */
2842 if ( ! left )
2843 str[-1] = c; /* replace last character of part */
2844 /* FALLTHRU */
2845 default:
2846 if ( left )
2848 *str++ = tolower (c); /* map to lower case (looks nicer) */
2849 left--;
2850 dots = 0; /* started a path component */
2852 break;
2855 *str = '\0';
2857 else
2859 strcpy (shortname, name);
2860 unixtodos_filename (shortname);
2863 if (pPath)
2864 *pPath = shortname + (path - save_name);
2866 return shortname;
2869 static int
2870 is_exec (const char * name)
2872 char * p = strrchr (name, '.');
2873 return
2874 (p != NULL
2875 && (xstrcasecmp (p, ".exe") == 0 ||
2876 xstrcasecmp (p, ".com") == 0 ||
2877 xstrcasecmp (p, ".bat") == 0 ||
2878 xstrcasecmp (p, ".cmd") == 0));
2881 /* Emulate the Unix directory procedures opendir, closedir,
2882 and readdir. We can't use the procedures supplied in sysdep.c,
2883 so we provide them here. */
2885 struct dirent dir_static; /* simulated directory contents */
2886 static HANDLE dir_find_handle = INVALID_HANDLE_VALUE;
2887 static int dir_is_fat;
2888 static char dir_pathname[MAXPATHLEN+1];
2889 static WIN32_FIND_DATA dir_find_data;
2891 /* Support shares on a network resource as subdirectories of a read-only
2892 root directory. */
2893 static HANDLE wnet_enum_handle = INVALID_HANDLE_VALUE;
2894 static HANDLE open_unc_volume (const char *);
2895 static char *read_unc_volume (HANDLE, char *, int);
2896 static void close_unc_volume (HANDLE);
2898 DIR *
2899 opendir (const char *filename)
2901 DIR *dirp;
2903 /* Opening is done by FindFirstFile. However, a read is inherent to
2904 this operation, so we defer the open until read time. */
2906 if (dir_find_handle != INVALID_HANDLE_VALUE)
2907 return NULL;
2908 if (wnet_enum_handle != INVALID_HANDLE_VALUE)
2909 return NULL;
2911 /* Note: We don't support traversal of UNC volumes via symlinks.
2912 Doing so would mean punishing 99.99% of use cases by resolving
2913 all the possible symlinks in FILENAME, recursively. */
2914 if (is_unc_volume (filename))
2916 wnet_enum_handle = open_unc_volume (filename);
2917 if (wnet_enum_handle == INVALID_HANDLE_VALUE)
2918 return NULL;
2921 if (!(dirp = (DIR *) malloc (sizeof (DIR))))
2922 return NULL;
2924 dirp->dd_fd = 0;
2925 dirp->dd_loc = 0;
2926 dirp->dd_size = 0;
2928 strncpy (dir_pathname, map_w32_filename (filename, NULL), MAXPATHLEN);
2929 dir_pathname[MAXPATHLEN] = '\0';
2930 /* Note: We don't support symlinks to file names on FAT volumes.
2931 Doing so would mean punishing 99.99% of use cases by resolving
2932 all the possible symlinks in FILENAME, recursively. */
2933 dir_is_fat = is_fat_volume (filename, NULL);
2935 return dirp;
2938 void
2939 closedir (DIR *dirp)
2941 /* If we have a find-handle open, close it. */
2942 if (dir_find_handle != INVALID_HANDLE_VALUE)
2944 FindClose (dir_find_handle);
2945 dir_find_handle = INVALID_HANDLE_VALUE;
2947 else if (wnet_enum_handle != INVALID_HANDLE_VALUE)
2949 close_unc_volume (wnet_enum_handle);
2950 wnet_enum_handle = INVALID_HANDLE_VALUE;
2952 xfree ((char *) dirp);
2955 struct dirent *
2956 readdir (DIR *dirp)
2958 int downcase = !NILP (Vw32_downcase_file_names);
2960 if (wnet_enum_handle != INVALID_HANDLE_VALUE)
2962 if (!read_unc_volume (wnet_enum_handle,
2963 dir_find_data.cFileName,
2964 MAX_PATH))
2965 return NULL;
2967 /* If we aren't dir_finding, do a find-first, otherwise do a find-next. */
2968 else if (dir_find_handle == INVALID_HANDLE_VALUE)
2970 char filename[MAXNAMLEN + 3];
2971 int ln;
2972 int dbcs_p = max_filename_mbslen () > 1;
2974 strcpy (filename, dir_pathname);
2975 ln = strlen (filename) - 1;
2976 if (!dbcs_p)
2978 if (!IS_DIRECTORY_SEP (filename[ln]))
2979 strcat (filename, "\\");
2981 else
2983 char *end = filename + ln + 1;
2984 char *last_char = CharPrevExA (file_name_codepage, filename, end, 0);
2986 if (!IS_DIRECTORY_SEP (*last_char))
2987 strcat (filename, "\\");
2989 strcat (filename, "*");
2991 /* Note: No need to resolve symlinks in FILENAME, because
2992 FindFirst opens the directory that is the target of a
2993 symlink. */
2994 dir_find_handle = FindFirstFile (filename, &dir_find_data);
2996 if (dir_find_handle == INVALID_HANDLE_VALUE)
2997 return NULL;
2999 else
3001 if (!FindNextFile (dir_find_handle, &dir_find_data))
3002 return NULL;
3005 /* Emacs never uses this value, so don't bother making it match
3006 value returned by stat(). */
3007 dir_static.d_ino = 1;
3009 strcpy (dir_static.d_name, dir_find_data.cFileName);
3011 /* If the file name in cFileName[] includes `?' characters, it means
3012 the original file name used characters that cannot be represented
3013 by the current ANSI codepage. To avoid total lossage, retrieve
3014 the short 8+3 alias of the long file name. */
3015 if (_mbspbrk (dir_static.d_name, "?"))
3017 strcpy (dir_static.d_name, dir_find_data.cAlternateFileName);
3018 downcase = 1; /* 8+3 aliases are returned in all caps */
3020 dir_static.d_namlen = strlen (dir_static.d_name);
3021 dir_static.d_reclen = sizeof (struct dirent) - MAXNAMLEN + 3 +
3022 dir_static.d_namlen - dir_static.d_namlen % 4;
3024 /* If the file name in cFileName[] includes `?' characters, it means
3025 the original file name used characters that cannot be represented
3026 by the current ANSI codepage. To avoid total lossage, retrieve
3027 the short 8+3 alias of the long file name. */
3028 if (_mbspbrk (dir_find_data.cFileName, "?"))
3030 strcpy (dir_static.d_name, dir_find_data.cAlternateFileName);
3031 /* 8+3 aliases are returned in all caps, which could break
3032 various alists that look at filenames' extensions. */
3033 downcase = 1;
3035 else
3036 strcpy (dir_static.d_name, dir_find_data.cFileName);
3037 dir_static.d_namlen = strlen (dir_static.d_name);
3038 if (dir_is_fat)
3039 _mbslwr (dir_static.d_name);
3040 else if (downcase)
3042 register char *p;
3043 int dbcs_p = max_filename_mbslen () > 1;
3044 for (p = dir_static.d_name; *p; )
3046 if (*p >= 'a' && *p <= 'z')
3047 break;
3048 if (dbcs_p)
3049 p = CharNextExA (file_name_codepage, p, 0);
3050 else
3051 p++;
3053 if (!*p)
3054 _mbslwr (dir_static.d_name);
3057 return &dir_static;
3060 static HANDLE
3061 open_unc_volume (const char *path)
3063 NETRESOURCE nr;
3064 HANDLE henum;
3065 int result;
3067 nr.dwScope = RESOURCE_GLOBALNET;
3068 nr.dwType = RESOURCETYPE_DISK;
3069 nr.dwDisplayType = RESOURCEDISPLAYTYPE_SERVER;
3070 nr.dwUsage = RESOURCEUSAGE_CONTAINER;
3071 nr.lpLocalName = NULL;
3072 nr.lpRemoteName = (LPSTR)map_w32_filename (path, NULL);
3073 nr.lpComment = NULL;
3074 nr.lpProvider = NULL;
3076 result = WNetOpenEnum (RESOURCE_GLOBALNET, RESOURCETYPE_DISK,
3077 RESOURCEUSAGE_CONNECTABLE, &nr, &henum);
3079 if (result == NO_ERROR)
3080 return henum;
3081 else
3082 return INVALID_HANDLE_VALUE;
3085 static char *
3086 read_unc_volume (HANDLE henum, char *readbuf, int size)
3088 DWORD count;
3089 int result;
3090 DWORD bufsize = 512;
3091 char *buffer;
3092 char *ptr;
3093 int dbcs_p = max_filename_mbslen () > 1;
3095 count = 1;
3096 buffer = alloca (bufsize);
3097 result = WNetEnumResource (henum, &count, buffer, &bufsize);
3098 if (result != NO_ERROR)
3099 return NULL;
3101 /* WNetEnumResource returns \\resource\share...skip forward to "share". */
3102 ptr = ((LPNETRESOURCE) buffer)->lpRemoteName;
3103 ptr += 2;
3104 if (!dbcs_p)
3105 while (*ptr && !IS_DIRECTORY_SEP (*ptr)) ptr++;
3106 else
3108 while (*ptr && !IS_DIRECTORY_SEP (*ptr))
3109 ptr = CharNextExA (file_name_codepage, ptr, 0);
3111 ptr++;
3113 strncpy (readbuf, ptr, size);
3114 return readbuf;
3117 static void
3118 close_unc_volume (HANDLE henum)
3120 if (henum != INVALID_HANDLE_VALUE)
3121 WNetCloseEnum (henum);
3124 static DWORD
3125 unc_volume_file_attributes (const char *path)
3127 HANDLE henum;
3128 DWORD attrs;
3130 henum = open_unc_volume (path);
3131 if (henum == INVALID_HANDLE_VALUE)
3132 return -1;
3134 attrs = FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_DIRECTORY;
3136 close_unc_volume (henum);
3138 return attrs;
3141 /* Ensure a network connection is authenticated. */
3142 static void
3143 logon_network_drive (const char *path)
3145 NETRESOURCE resource;
3146 char share[MAX_PATH];
3147 int n_slashes;
3148 char drive[4];
3149 UINT drvtype;
3150 char *p;
3151 int dbcs_p;
3153 if (IS_DIRECTORY_SEP (path[0]) && IS_DIRECTORY_SEP (path[1]))
3154 drvtype = DRIVE_REMOTE;
3155 else if (path[0] == '\0' || path[1] != ':')
3156 drvtype = GetDriveType (NULL);
3157 else
3159 drive[0] = path[0];
3160 drive[1] = ':';
3161 drive[2] = '\\';
3162 drive[3] = '\0';
3163 drvtype = GetDriveType (drive);
3166 /* Only logon to networked drives. */
3167 if (drvtype != DRIVE_REMOTE)
3168 return;
3170 n_slashes = 2;
3171 strncpy (share, path, MAX_PATH);
3172 /* Truncate to just server and share name. */
3173 dbcs_p = max_filename_mbslen () > 1;
3174 for (p = share + 2; *p && p < share + MAX_PATH; )
3176 if (IS_DIRECTORY_SEP (*p) && ++n_slashes > 3)
3178 *p = '\0';
3179 break;
3181 if (dbcs_p)
3182 p = CharNextExA (file_name_codepage, p, 0);
3183 else
3184 p++;
3187 resource.dwType = RESOURCETYPE_DISK;
3188 resource.lpLocalName = NULL;
3189 resource.lpRemoteName = share;
3190 resource.lpProvider = NULL;
3192 WNetAddConnection2 (&resource, NULL, NULL, CONNECT_INTERACTIVE);
3195 /* Emulate faccessat(2). */
3197 faccessat (int dirfd, const char * path, int mode, int flags)
3199 DWORD attributes;
3201 if (dirfd != AT_FDCWD
3202 && !(IS_DIRECTORY_SEP (path[0])
3203 || IS_DEVICE_SEP (path[1])))
3205 errno = EBADF;
3206 return -1;
3209 /* MSVCRT implementation of 'access' doesn't recognize D_OK, and its
3210 newer versions blow up when passed D_OK. */
3211 path = map_w32_filename (path, NULL);
3212 /* If the last element of PATH is a symlink, we need to resolve it
3213 to get the attributes of its target file. Note: any symlinks in
3214 PATH elements other than the last one are transparently resolved
3215 by GetFileAttributes below. */
3216 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0
3217 && (flags & AT_SYMLINK_NOFOLLOW) == 0)
3218 path = chase_symlinks (path);
3220 if ((attributes = GetFileAttributes (path)) == -1)
3222 DWORD w32err = GetLastError ();
3224 switch (w32err)
3226 case ERROR_INVALID_NAME:
3227 case ERROR_BAD_PATHNAME:
3228 if (is_unc_volume (path))
3230 attributes = unc_volume_file_attributes (path);
3231 if (attributes == -1)
3233 errno = EACCES;
3234 return -1;
3236 break;
3238 /* FALLTHROUGH */
3239 case ERROR_FILE_NOT_FOUND:
3240 case ERROR_BAD_NETPATH:
3241 errno = ENOENT;
3242 break;
3243 default:
3244 errno = EACCES;
3245 break;
3247 return -1;
3249 if ((mode & X_OK) != 0
3250 && !(is_exec (path) || (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0))
3252 errno = EACCES;
3253 return -1;
3255 if ((mode & W_OK) != 0 && (attributes & FILE_ATTRIBUTE_READONLY) != 0)
3257 errno = EACCES;
3258 return -1;
3260 if ((mode & D_OK) != 0 && (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
3262 errno = EACCES;
3263 return -1;
3265 return 0;
3268 /* Shadow some MSVC runtime functions to map requests for long filenames
3269 to reasonable short names if necessary. This was originally added to
3270 permit running Emacs on NT 3.1 on a FAT partition, which doesn't support
3271 long file names. */
3274 sys_chdir (const char * path)
3276 return _chdir (map_w32_filename (path, NULL));
3280 sys_chmod (const char * path, int mode)
3282 path = chase_symlinks (map_w32_filename (path, NULL));
3283 return _chmod (path, mode);
3287 sys_creat (const char * path, int mode)
3289 return _creat (map_w32_filename (path, NULL), mode);
3292 FILE *
3293 sys_fopen (const char * path, const char * mode)
3295 int fd;
3296 int oflag;
3297 const char * mode_save = mode;
3299 /* Force all file handles to be non-inheritable. This is necessary to
3300 ensure child processes don't unwittingly inherit handles that might
3301 prevent future file access. */
3303 if (mode[0] == 'r')
3304 oflag = O_RDONLY;
3305 else if (mode[0] == 'w' || mode[0] == 'a')
3306 oflag = O_WRONLY | O_CREAT | O_TRUNC;
3307 else
3308 return NULL;
3310 /* Only do simplistic option parsing. */
3311 while (*++mode)
3312 if (mode[0] == '+')
3314 oflag &= ~(O_RDONLY | O_WRONLY);
3315 oflag |= O_RDWR;
3317 else if (mode[0] == 'b')
3319 oflag &= ~O_TEXT;
3320 oflag |= O_BINARY;
3322 else if (mode[0] == 't')
3324 oflag &= ~O_BINARY;
3325 oflag |= O_TEXT;
3327 else break;
3329 fd = _open (map_w32_filename (path, NULL), oflag | _O_NOINHERIT, 0644);
3330 if (fd < 0)
3331 return NULL;
3333 return _fdopen (fd, mode_save);
3336 /* This only works on NTFS volumes, but is useful to have. */
3338 sys_link (const char * old, const char * new)
3340 HANDLE fileh;
3341 int result = -1;
3342 char oldname[MAX_PATH], newname[MAX_PATH];
3344 if (old == NULL || new == NULL)
3346 errno = ENOENT;
3347 return -1;
3350 strcpy (oldname, map_w32_filename (old, NULL));
3351 strcpy (newname, map_w32_filename (new, NULL));
3353 fileh = CreateFile (oldname, 0, 0, NULL, OPEN_EXISTING,
3354 FILE_FLAG_BACKUP_SEMANTICS, NULL);
3355 if (fileh != INVALID_HANDLE_VALUE)
3357 int wlen;
3359 /* Confusingly, the "alternate" stream name field does not apply
3360 when restoring a hard link, and instead contains the actual
3361 stream data for the link (ie. the name of the link to create).
3362 The WIN32_STREAM_ID structure before the cStreamName field is
3363 the stream header, which is then immediately followed by the
3364 stream data. */
3366 struct {
3367 WIN32_STREAM_ID wid;
3368 WCHAR wbuffer[MAX_PATH]; /* extra space for link name */
3369 } data;
3371 wlen = MultiByteToWideChar (CP_ACP, MB_PRECOMPOSED, newname, -1,
3372 data.wid.cStreamName, MAX_PATH);
3373 if (wlen > 0)
3375 LPVOID context = NULL;
3376 DWORD wbytes = 0;
3378 data.wid.dwStreamId = BACKUP_LINK;
3379 data.wid.dwStreamAttributes = 0;
3380 data.wid.Size.LowPart = wlen * sizeof (WCHAR);
3381 data.wid.Size.HighPart = 0;
3382 data.wid.dwStreamNameSize = 0;
3384 if (BackupWrite (fileh, (LPBYTE)&data,
3385 offsetof (WIN32_STREAM_ID, cStreamName)
3386 + data.wid.Size.LowPart,
3387 &wbytes, FALSE, FALSE, &context)
3388 && BackupWrite (fileh, NULL, 0, &wbytes, TRUE, FALSE, &context))
3390 /* succeeded */
3391 result = 0;
3393 else
3395 /* Should try mapping GetLastError to errno; for now just
3396 indicate a general error (eg. links not supported). */
3397 errno = EINVAL; // perhaps EMLINK?
3401 CloseHandle (fileh);
3403 else
3404 errno = ENOENT;
3406 return result;
3410 sys_mkdir (const char * path)
3412 return _mkdir (map_w32_filename (path, NULL));
3415 /* Because of long name mapping issues, we need to implement this
3416 ourselves. Also, MSVC's _mktemp returns NULL when it can't generate
3417 a unique name, instead of setting the input template to an empty
3418 string.
3420 Standard algorithm seems to be use pid or tid with a letter on the
3421 front (in place of the 6 X's) and cycle through the letters to find a
3422 unique name. We extend that to allow any reasonable character as the
3423 first of the 6 X's. */
3424 char *
3425 sys_mktemp (char * template)
3427 char * p;
3428 int i;
3429 unsigned uid = GetCurrentThreadId ();
3430 static char first_char[] = "abcdefghijklmnopqrstuvwyz0123456789!%-_@#";
3432 if (template == NULL)
3433 return NULL;
3434 p = template + strlen (template);
3435 i = 5;
3436 /* replace up to the last 5 X's with uid in decimal */
3437 while (--p >= template && p[0] == 'X' && --i >= 0)
3439 p[0] = '0' + uid % 10;
3440 uid /= 10;
3443 if (i < 0 && p[0] == 'X')
3445 i = 0;
3448 int save_errno = errno;
3449 p[0] = first_char[i];
3450 if (faccessat (AT_FDCWD, template, F_OK, AT_EACCESS) < 0)
3452 errno = save_errno;
3453 return template;
3456 while (++i < sizeof (first_char));
3459 /* Template is badly formed or else we can't generate a unique name,
3460 so return empty string */
3461 template[0] = 0;
3462 return template;
3466 sys_open (const char * path, int oflag, int mode)
3468 const char* mpath = map_w32_filename (path, NULL);
3469 int res = -1;
3471 /* If possible, try to open file without _O_CREAT, to be able to
3472 write to existing hidden and system files. Force all file
3473 handles to be non-inheritable. */
3474 if ((oflag & (_O_CREAT | _O_EXCL)) != (_O_CREAT | _O_EXCL))
3475 res = _open (mpath, (oflag & ~_O_CREAT) | _O_NOINHERIT, mode);
3476 if (res < 0)
3477 res = _open (mpath, oflag | _O_NOINHERIT, mode);
3479 return res;
3483 fchmod (int fd, mode_t mode)
3485 return 0;
3489 sys_rename_replace (const char *oldname, const char *newname, BOOL force)
3491 BOOL result;
3492 char temp[MAX_PATH];
3493 int newname_dev;
3494 int oldname_dev;
3496 /* MoveFile on Windows 95 doesn't correctly change the short file name
3497 alias in a number of circumstances (it is not easy to predict when
3498 just by looking at oldname and newname, unfortunately). In these
3499 cases, renaming through a temporary name avoids the problem.
3501 A second problem on Windows 95 is that renaming through a temp name when
3502 newname is uppercase fails (the final long name ends up in
3503 lowercase, although the short alias might be uppercase) UNLESS the
3504 long temp name is not 8.3.
3506 So, on Windows 95 we always rename through a temp name, and we make sure
3507 the temp name has a long extension to ensure correct renaming. */
3509 strcpy (temp, map_w32_filename (oldname, NULL));
3511 /* volume_info is set indirectly by map_w32_filename. */
3512 oldname_dev = volume_info.serialnum;
3514 if (os_subtype == OS_9X)
3516 char * o;
3517 char * p;
3518 int i = 0;
3520 oldname = map_w32_filename (oldname, NULL);
3521 if ((o = strrchr (oldname, '\\')))
3522 o++;
3523 else
3524 o = (char *) oldname;
3526 if ((p = strrchr (temp, '\\')))
3527 p++;
3528 else
3529 p = temp;
3533 /* Force temp name to require a manufactured 8.3 alias - this
3534 seems to make the second rename work properly. */
3535 sprintf (p, "_.%s.%u", o, i);
3536 i++;
3537 result = rename (oldname, temp);
3539 /* This loop must surely terminate! */
3540 while (result < 0 && errno == EEXIST);
3541 if (result < 0)
3542 return -1;
3545 /* If FORCE, emulate Unix behavior - newname is deleted if it already exists
3546 (at least if it is a file; don't do this for directories).
3548 Since we mustn't do this if we are just changing the case of the
3549 file name (we would end up deleting the file we are trying to
3550 rename!), we let rename detect if the destination file already
3551 exists - that way we avoid the possible pitfalls of trying to
3552 determine ourselves whether two names really refer to the same
3553 file, which is not always possible in the general case. (Consider
3554 all the permutations of shared or subst'd drives, etc.) */
3556 newname = map_w32_filename (newname, NULL);
3558 /* volume_info is set indirectly by map_w32_filename. */
3559 newname_dev = volume_info.serialnum;
3561 result = rename (temp, newname);
3563 if (result < 0 && force)
3565 DWORD w32err = GetLastError ();
3567 if (errno == EACCES
3568 && newname_dev != oldname_dev)
3570 /* The implementation of `rename' on Windows does not return
3571 errno = EXDEV when you are moving a directory to a
3572 different storage device (ex. logical disk). It returns
3573 EACCES instead. So here we handle such situations and
3574 return EXDEV. */
3575 DWORD attributes;
3577 if ((attributes = GetFileAttributes (temp)) != -1
3578 && (attributes & FILE_ATTRIBUTE_DIRECTORY))
3579 errno = EXDEV;
3581 else if (errno == EEXIST)
3583 if (_chmod (newname, 0666) != 0)
3584 return result;
3585 if (_unlink (newname) != 0)
3586 return result;
3587 result = rename (temp, newname);
3589 else if (w32err == ERROR_PRIVILEGE_NOT_HELD
3590 && is_symlink (temp))
3592 /* This is Windows prohibiting the user from creating a
3593 symlink in another place, since that requires
3594 privileges. */
3595 errno = EPERM;
3599 return result;
3603 sys_rename (char const *old, char const *new)
3605 return sys_rename_replace (old, new, TRUE);
3609 sys_rmdir (const char * path)
3611 return _rmdir (map_w32_filename (path, NULL));
3615 sys_unlink (const char * path)
3617 path = map_w32_filename (path, NULL);
3619 /* On Unix, unlink works without write permission. */
3620 _chmod (path, 0666);
3621 return _unlink (path);
3624 static FILETIME utc_base_ft;
3625 static ULONGLONG utc_base; /* In 100ns units */
3626 static int init = 0;
3628 #define FILETIME_TO_U64(result, ft) \
3629 do { \
3630 ULARGE_INTEGER uiTemp; \
3631 uiTemp.LowPart = (ft).dwLowDateTime; \
3632 uiTemp.HighPart = (ft).dwHighDateTime; \
3633 result = uiTemp.QuadPart; \
3634 } while (0)
3636 static void
3637 initialize_utc_base (void)
3639 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
3640 SYSTEMTIME st;
3642 st.wYear = 1970;
3643 st.wMonth = 1;
3644 st.wDay = 1;
3645 st.wHour = 0;
3646 st.wMinute = 0;
3647 st.wSecond = 0;
3648 st.wMilliseconds = 0;
3650 SystemTimeToFileTime (&st, &utc_base_ft);
3651 FILETIME_TO_U64 (utc_base, utc_base_ft);
3654 static time_t
3655 convert_time (FILETIME ft)
3657 ULONGLONG tmp;
3659 if (!init)
3661 initialize_utc_base ();
3662 init = 1;
3665 if (CompareFileTime (&ft, &utc_base_ft) < 0)
3666 return 0;
3668 FILETIME_TO_U64 (tmp, ft);
3669 return (time_t) ((tmp - utc_base) / 10000000L);
3672 static void
3673 convert_from_time_t (time_t time, FILETIME * pft)
3675 ULARGE_INTEGER tmp;
3677 if (!init)
3679 initialize_utc_base ();
3680 init = 1;
3683 /* time in 100ns units since 1-Jan-1601 */
3684 tmp.QuadPart = (ULONGLONG) time * 10000000L + utc_base;
3685 pft->dwHighDateTime = tmp.HighPart;
3686 pft->dwLowDateTime = tmp.LowPart;
3689 #if 0
3690 /* No reason to keep this; faking inode values either by hashing or even
3691 using the file index from GetInformationByHandle, is not perfect and
3692 so by default Emacs doesn't use the inode values on Windows.
3693 Instead, we now determine file-truename correctly (except for
3694 possible drive aliasing etc). */
3696 /* Modified version of "PJW" algorithm (see the "Dragon" compiler book). */
3697 static unsigned
3698 hashval (const unsigned char * str)
3700 unsigned h = 0;
3701 while (*str)
3703 h = (h << 4) + *str++;
3704 h ^= (h >> 28);
3706 return h;
3709 /* Return the hash value of the canonical pathname, excluding the
3710 drive/UNC header, to get a hopefully unique inode number. */
3711 static DWORD
3712 generate_inode_val (const char * name)
3714 char fullname[ MAX_PATH ];
3715 char * p;
3716 unsigned hash;
3718 /* Get the truly canonical filename, if it exists. (Note: this
3719 doesn't resolve aliasing due to subst commands, or recognize hard
3720 links. */
3721 if (!w32_get_long_filename ((char *)name, fullname, MAX_PATH))
3722 emacs_abort ();
3724 parse_root (fullname, &p);
3725 /* Normal W32 filesystems are still case insensitive. */
3726 _strlwr (p);
3727 return hashval (p);
3730 #endif
3732 static PSECURITY_DESCRIPTOR
3733 get_file_security_desc_by_handle (HANDLE h)
3735 PSECURITY_DESCRIPTOR psd = NULL;
3736 DWORD err;
3737 SECURITY_INFORMATION si = OWNER_SECURITY_INFORMATION
3738 | GROUP_SECURITY_INFORMATION /* | DACL_SECURITY_INFORMATION */ ;
3740 err = get_security_info (h, SE_FILE_OBJECT, si,
3741 NULL, NULL, NULL, NULL, &psd);
3742 if (err != ERROR_SUCCESS)
3743 return NULL;
3745 return psd;
3748 static PSECURITY_DESCRIPTOR
3749 get_file_security_desc_by_name (const char *fname)
3751 PSECURITY_DESCRIPTOR psd = NULL;
3752 DWORD sd_len, err;
3753 SECURITY_INFORMATION si = OWNER_SECURITY_INFORMATION
3754 | GROUP_SECURITY_INFORMATION /* | DACL_SECURITY_INFORMATION */ ;
3756 if (!get_file_security (fname, si, psd, 0, &sd_len))
3758 err = GetLastError ();
3759 if (err != ERROR_INSUFFICIENT_BUFFER)
3760 return NULL;
3763 psd = xmalloc (sd_len);
3764 if (!get_file_security (fname, si, psd, sd_len, &sd_len))
3766 xfree (psd);
3767 return NULL;
3770 return psd;
3773 static DWORD
3774 get_rid (PSID sid)
3776 unsigned n_subauthorities;
3778 /* Use the last sub-authority value of the RID, the relative
3779 portion of the SID, as user/group ID. */
3780 n_subauthorities = *get_sid_sub_authority_count (sid);
3781 if (n_subauthorities < 1)
3782 return 0; /* the "World" RID */
3783 return *get_sid_sub_authority (sid, n_subauthorities - 1);
3786 /* Caching SID and account values for faster lokup. */
3788 struct w32_id {
3789 unsigned rid;
3790 struct w32_id *next;
3791 char name[GNLEN+1];
3792 unsigned char sid[FLEXIBLE_ARRAY_MEMBER];
3795 static struct w32_id *w32_idlist;
3797 static int
3798 w32_cached_id (PSID sid, unsigned *id, char *name)
3800 struct w32_id *tail, *found;
3802 for (found = NULL, tail = w32_idlist; tail; tail = tail->next)
3804 if (equal_sid ((PSID)tail->sid, sid))
3806 found = tail;
3807 break;
3810 if (found)
3812 *id = found->rid;
3813 strcpy (name, found->name);
3814 return 1;
3816 else
3817 return 0;
3820 static void
3821 w32_add_to_cache (PSID sid, unsigned id, char *name)
3823 DWORD sid_len;
3824 struct w32_id *new_entry;
3826 /* We don't want to leave behind stale cache from when Emacs was
3827 dumped. */
3828 if (initialized)
3830 sid_len = get_length_sid (sid);
3831 new_entry = xmalloc (offsetof (struct w32_id, sid) + sid_len);
3832 if (new_entry)
3834 new_entry->rid = id;
3835 strcpy (new_entry->name, name);
3836 copy_sid (sid_len, (PSID)new_entry->sid, sid);
3837 new_entry->next = w32_idlist;
3838 w32_idlist = new_entry;
3843 #define UID 1
3844 #define GID 2
3846 static int
3847 get_name_and_id (PSECURITY_DESCRIPTOR psd, unsigned *id, char *nm, int what)
3849 PSID sid = NULL;
3850 BOOL dflt;
3851 SID_NAME_USE ignore;
3852 char name[UNLEN+1];
3853 DWORD name_len = sizeof (name);
3854 char domain[1024];
3855 DWORD domain_len = sizeof (domain);
3856 int use_dflt = 0;
3857 int result;
3859 if (what == UID)
3860 result = get_security_descriptor_owner (psd, &sid, &dflt);
3861 else if (what == GID)
3862 result = get_security_descriptor_group (psd, &sid, &dflt);
3863 else
3864 result = 0;
3866 if (!result || !is_valid_sid (sid))
3867 use_dflt = 1;
3868 else if (!w32_cached_id (sid, id, nm))
3870 if (!lookup_account_sid (NULL, sid, name, &name_len,
3871 domain, &domain_len, &ignore)
3872 || name_len > UNLEN+1)
3873 use_dflt = 1;
3874 else
3876 *id = get_rid (sid);
3877 strcpy (nm, name);
3878 w32_add_to_cache (sid, *id, name);
3881 return use_dflt;
3884 static void
3885 get_file_owner_and_group (PSECURITY_DESCRIPTOR psd, struct stat *st)
3887 int dflt_usr = 0, dflt_grp = 0;
3889 if (!psd)
3891 dflt_usr = 1;
3892 dflt_grp = 1;
3894 else
3896 if (get_name_and_id (psd, &st->st_uid, st->st_uname, UID))
3897 dflt_usr = 1;
3898 if (get_name_and_id (psd, &st->st_gid, st->st_gname, GID))
3899 dflt_grp = 1;
3901 /* Consider files to belong to current user/group, if we cannot get
3902 more accurate information. */
3903 if (dflt_usr)
3905 st->st_uid = dflt_passwd.pw_uid;
3906 strcpy (st->st_uname, dflt_passwd.pw_name);
3908 if (dflt_grp)
3910 st->st_gid = dflt_passwd.pw_gid;
3911 strcpy (st->st_gname, dflt_group.gr_name);
3915 /* Return non-zero if NAME is a potentially slow filesystem. */
3917 is_slow_fs (const char *name)
3919 char drive_root[4];
3920 UINT devtype;
3922 if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
3923 devtype = DRIVE_REMOTE; /* assume UNC name is remote */
3924 else if (!(strlen (name) >= 2 && IS_DEVICE_SEP (name[1])))
3925 devtype = GetDriveType (NULL); /* use root of current drive */
3926 else
3928 /* GetDriveType needs the root directory of the drive. */
3929 strncpy (drive_root, name, 2);
3930 drive_root[2] = '\\';
3931 drive_root[3] = '\0';
3932 devtype = GetDriveType (drive_root);
3934 return !(devtype == DRIVE_FIXED || devtype == DRIVE_RAMDISK);
3937 /* If this is non-zero, the caller wants accurate information about
3938 file's owner and group, which could be expensive to get. */
3939 int w32_stat_get_owner_group;
3941 /* MSVC stat function can't cope with UNC names and has other bugs, so
3942 replace it with our own. This also allows us to calculate consistent
3943 inode values and owner/group without hacks in the main Emacs code. */
3945 static int
3946 stat_worker (const char * path, struct stat * buf, int follow_symlinks)
3948 char *name, *save_name, *r;
3949 WIN32_FIND_DATA wfd;
3950 HANDLE fh;
3951 unsigned __int64 fake_inode = 0;
3952 int permission;
3953 int len;
3954 int rootdir = FALSE;
3955 PSECURITY_DESCRIPTOR psd = NULL;
3956 int is_a_symlink = 0;
3957 DWORD file_flags = FILE_FLAG_BACKUP_SEMANTICS;
3958 DWORD access_rights = 0;
3959 DWORD fattrs = 0, serialnum = 0, fs_high = 0, fs_low = 0, nlinks = 1;
3960 FILETIME ctime, atime, wtime;
3961 int dbcs_p;
3963 if (path == NULL || buf == NULL)
3965 errno = EFAULT;
3966 return -1;
3969 save_name = name = (char *) map_w32_filename (path, &path);
3970 /* Must be valid filename, no wild cards or other invalid
3971 characters. We use _mbspbrk to support multibyte strings that
3972 might look to strpbrk as if they included literal *, ?, and other
3973 characters mentioned below that are disallowed by Windows
3974 filesystems. */
3975 if (_mbspbrk (name, "*?|<>\""))
3977 errno = ENOENT;
3978 return -1;
3981 /* Remove trailing directory separator, unless name is the root
3982 directory of a drive or UNC volume in which case ensure there
3983 is a trailing separator. */
3984 len = strlen (name);
3985 name = strcpy (alloca (len + 2), name);
3987 /* Avoid a somewhat costly call to is_symlink if the filesystem
3988 doesn't support symlinks. */
3989 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
3990 is_a_symlink = is_symlink (name);
3992 /* Plan A: Open the file and get all the necessary information via
3993 the resulting handle. This solves several issues in one blow:
3995 . retrieves attributes for the target of a symlink, if needed
3996 . gets attributes of root directories and symlinks pointing to
3997 root directories, thus avoiding the need for special-casing
3998 these and detecting them by examining the file-name format
3999 . retrieves more accurate attributes (e.g., non-zero size for
4000 some directories, esp. directories that are junction points)
4001 . correctly resolves "c:/..", "/.." and similar file names
4002 . avoids run-time penalties for 99% of use cases
4004 Plan A is always tried first, unless the user asked not to (but
4005 if the file is a symlink and we need to follow links, we try Plan
4006 A even if the user asked not to).
4008 If Plan A fails, we go to Plan B (below), where various
4009 potentially expensive techniques must be used to handle "special"
4010 files such as UNC volumes etc. */
4011 if (!(NILP (Vw32_get_true_file_attributes)
4012 || (EQ (Vw32_get_true_file_attributes, Qlocal) && is_slow_fs (name)))
4013 /* Following symlinks requires getting the info by handle. */
4014 || (is_a_symlink && follow_symlinks))
4016 BY_HANDLE_FILE_INFORMATION info;
4018 if (is_a_symlink && !follow_symlinks)
4019 file_flags |= FILE_FLAG_OPEN_REPARSE_POINT;
4020 /* READ_CONTROL access rights are required to get security info
4021 by handle. But if the OS doesn't support security in the
4022 first place, we don't need to try. */
4023 if (is_windows_9x () != TRUE)
4024 access_rights |= READ_CONTROL;
4026 fh = CreateFile (name, access_rights, 0, NULL, OPEN_EXISTING,
4027 file_flags, NULL);
4028 /* If CreateFile fails with READ_CONTROL, try again with zero as
4029 access rights. */
4030 if (fh == INVALID_HANDLE_VALUE && access_rights)
4031 fh = CreateFile (name, 0, 0, NULL, OPEN_EXISTING,
4032 file_flags, NULL);
4033 if (fh == INVALID_HANDLE_VALUE)
4034 goto no_true_file_attributes;
4036 /* This is more accurate in terms of getting the correct number
4037 of links, but is quite slow (it is noticeable when Emacs is
4038 making a list of file name completions). */
4039 if (GetFileInformationByHandle (fh, &info))
4041 nlinks = info.nNumberOfLinks;
4042 /* Might as well use file index to fake inode values, but this
4043 is not guaranteed to be unique unless we keep a handle open
4044 all the time (even then there are situations where it is
4045 not unique). Reputedly, there are at most 48 bits of info
4046 (on NTFS, presumably less on FAT). */
4047 fake_inode = info.nFileIndexHigh;
4048 fake_inode <<= 32;
4049 fake_inode += info.nFileIndexLow;
4050 serialnum = info.dwVolumeSerialNumber;
4051 fs_high = info.nFileSizeHigh;
4052 fs_low = info.nFileSizeLow;
4053 ctime = info.ftCreationTime;
4054 atime = info.ftLastAccessTime;
4055 wtime = info.ftLastWriteTime;
4056 fattrs = info.dwFileAttributes;
4058 else
4060 /* We don't go to Plan B here, because it's not clear that
4061 it's a good idea. The only known use case where
4062 CreateFile succeeds, but GetFileInformationByHandle fails
4063 (with ERROR_INVALID_FUNCTION) is for character devices
4064 such as NUL, PRN, etc. For these, switching to Plan B is
4065 a net loss, because we lose the character device
4066 attribute returned by GetFileType below (FindFirstFile
4067 doesn't set that bit in the attributes), and the other
4068 fields don't make sense for character devices anyway.
4069 Emacs doesn't really care for non-file entities in the
4070 context of l?stat, so neither do we. */
4072 /* w32err is assigned so one could put a breakpoint here and
4073 examine its value, when GetFileInformationByHandle
4074 fails. */
4075 DWORD w32err = GetLastError ();
4077 switch (w32err)
4079 case ERROR_FILE_NOT_FOUND: /* can this ever happen? */
4080 errno = ENOENT;
4081 return -1;
4085 /* Test for a symlink before testing for a directory, since
4086 symlinks to directories have the directory bit set, but we
4087 don't want them to appear as directories. */
4088 if (is_a_symlink && !follow_symlinks)
4089 buf->st_mode = S_IFLNK;
4090 else if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
4091 buf->st_mode = S_IFDIR;
4092 else
4094 DWORD ftype = GetFileType (fh);
4096 switch (ftype)
4098 case FILE_TYPE_DISK:
4099 buf->st_mode = S_IFREG;
4100 break;
4101 case FILE_TYPE_PIPE:
4102 buf->st_mode = S_IFIFO;
4103 break;
4104 case FILE_TYPE_CHAR:
4105 case FILE_TYPE_UNKNOWN:
4106 default:
4107 buf->st_mode = S_IFCHR;
4110 /* We produce the fallback owner and group data, based on the
4111 current user that runs Emacs, in the following cases:
4113 . caller didn't request owner and group info
4114 . this is Windows 9X
4115 . getting security by handle failed, and we need to produce
4116 information for the target of a symlink (this is better
4117 than producing a potentially misleading info about the
4118 symlink itself)
4120 If getting security by handle fails, and we don't need to
4121 resolve symlinks, we try getting security by name. */
4122 if (!w32_stat_get_owner_group || is_windows_9x () == TRUE)
4123 get_file_owner_and_group (NULL, buf);
4124 else
4126 psd = get_file_security_desc_by_handle (fh);
4127 if (psd)
4129 get_file_owner_and_group (psd, buf);
4130 LocalFree (psd);
4132 else if (!(is_a_symlink && follow_symlinks))
4134 psd = get_file_security_desc_by_name (name);
4135 get_file_owner_and_group (psd, buf);
4136 xfree (psd);
4138 else
4139 get_file_owner_and_group (NULL, buf);
4141 CloseHandle (fh);
4143 else
4145 no_true_file_attributes:
4146 /* Plan B: Either getting a handle on the file failed, or the
4147 caller explicitly asked us to not bother making this
4148 information more accurate.
4150 Implementation note: In Plan B, we never bother to resolve
4151 symlinks, even if we got here because we tried Plan A and
4152 failed. That's because, even if the caller asked for extra
4153 precision by setting Vw32_get_true_file_attributes to t,
4154 resolving symlinks requires acquiring a file handle to the
4155 symlink, which we already know will fail. And if the user
4156 did not ask for extra precision, resolving symlinks will fly
4157 in the face of that request, since the user then wants the
4158 lightweight version of the code. */
4159 dbcs_p = max_filename_mbslen () > 1;
4160 rootdir = (path >= save_name + len - 1
4161 && (IS_DIRECTORY_SEP (*path) || *path == 0));
4163 /* If name is "c:/.." or "/.." then stat "c:/" or "/". */
4164 r = IS_DEVICE_SEP (name[1]) ? &name[2] : name;
4165 if (IS_DIRECTORY_SEP (r[0])
4166 && r[1] == '.' && r[2] == '.' && r[3] == '\0')
4167 r[1] = r[2] = '\0';
4169 /* Note: If NAME is a symlink to the root of a UNC volume
4170 (i.e. "\\SERVER"), we will not detect that here, and we will
4171 return data about the symlink as result of FindFirst below.
4172 This is unfortunate, but that marginal use case does not
4173 justify a call to chase_symlinks which would impose a penalty
4174 on all the other use cases. (We get here for symlinks to
4175 roots of UNC volumes because CreateFile above fails for them,
4176 unlike with symlinks to root directories X:\ of drives.) */
4177 if (is_unc_volume (name))
4179 fattrs = unc_volume_file_attributes (name);
4180 if (fattrs == -1)
4181 return -1;
4183 ctime = atime = wtime = utc_base_ft;
4185 else if (rootdir)
4187 if (!dbcs_p)
4189 if (!IS_DIRECTORY_SEP (name[len-1]))
4190 strcat (name, "\\");
4192 else
4194 char *end = name + len;
4195 char *n = CharPrevExA (file_name_codepage, name, end, 0);
4197 if (!IS_DIRECTORY_SEP (*n))
4198 strcat (name, "\\");
4200 if (GetDriveType (name) < 2)
4202 errno = ENOENT;
4203 return -1;
4206 fattrs = FILE_ATTRIBUTE_DIRECTORY;
4207 ctime = atime = wtime = utc_base_ft;
4209 else
4211 if (!dbcs_p)
4213 if (IS_DIRECTORY_SEP (name[len-1]))
4214 name[len - 1] = 0;
4216 else
4218 char *end = name + len;
4219 char *n = CharPrevExA (file_name_codepage, name, end, 0);
4221 if (IS_DIRECTORY_SEP (*n))
4222 *n = 0;
4225 /* (This is hacky, but helps when doing file completions on
4226 network drives.) Optimize by using information available from
4227 active readdir if possible. */
4228 len = strlen (dir_pathname);
4229 if (!dbcs_p)
4231 if (IS_DIRECTORY_SEP (dir_pathname[len-1]))
4232 len--;
4234 else
4236 char *end = dir_pathname + len;
4237 char *n = CharPrevExA (file_name_codepage, dir_pathname, end, 0);
4239 if (IS_DIRECTORY_SEP (*n))
4240 len--;
4242 if (dir_find_handle != INVALID_HANDLE_VALUE
4243 && !(is_a_symlink && follow_symlinks)
4244 && strnicmp (save_name, dir_pathname, len) == 0
4245 && IS_DIRECTORY_SEP (name[len])
4246 && xstrcasecmp (name + len + 1, dir_static.d_name) == 0)
4248 /* This was the last entry returned by readdir. */
4249 wfd = dir_find_data;
4251 else
4253 logon_network_drive (name);
4255 fh = FindFirstFile (name, &wfd);
4256 if (fh == INVALID_HANDLE_VALUE)
4258 errno = ENOENT;
4259 return -1;
4261 FindClose (fh);
4263 /* Note: if NAME is a symlink, the information we get from
4264 FindFirstFile is for the symlink, not its target. */
4265 fattrs = wfd.dwFileAttributes;
4266 ctime = wfd.ftCreationTime;
4267 atime = wfd.ftLastAccessTime;
4268 wtime = wfd.ftLastWriteTime;
4269 fs_high = wfd.nFileSizeHigh;
4270 fs_low = wfd.nFileSizeLow;
4271 fake_inode = 0;
4272 nlinks = 1;
4273 serialnum = volume_info.serialnum;
4275 if (is_a_symlink && !follow_symlinks)
4276 buf->st_mode = S_IFLNK;
4277 else if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
4278 buf->st_mode = S_IFDIR;
4279 else
4280 buf->st_mode = S_IFREG;
4282 get_file_owner_and_group (NULL, buf);
4285 #if 0
4286 /* Not sure if there is any point in this. */
4287 if (!NILP (Vw32_generate_fake_inodes))
4288 fake_inode = generate_inode_val (name);
4289 else if (fake_inode == 0)
4291 /* For want of something better, try to make everything unique. */
4292 static DWORD gen_num = 0;
4293 fake_inode = ++gen_num;
4295 #endif
4297 buf->st_ino = fake_inode;
4299 buf->st_dev = serialnum;
4300 buf->st_rdev = serialnum;
4302 buf->st_size = fs_high;
4303 buf->st_size <<= 32;
4304 buf->st_size += fs_low;
4305 buf->st_nlink = nlinks;
4307 /* Convert timestamps to Unix format. */
4308 buf->st_mtime = convert_time (wtime);
4309 buf->st_atime = convert_time (atime);
4310 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
4311 buf->st_ctime = convert_time (ctime);
4312 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
4314 /* determine rwx permissions */
4315 if (is_a_symlink && !follow_symlinks)
4316 permission = S_IREAD | S_IWRITE | S_IEXEC; /* Posix expectations */
4317 else
4319 if (fattrs & FILE_ATTRIBUTE_READONLY)
4320 permission = S_IREAD;
4321 else
4322 permission = S_IREAD | S_IWRITE;
4324 if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
4325 permission |= S_IEXEC;
4326 else if (is_exec (name))
4327 permission |= S_IEXEC;
4330 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
4332 return 0;
4336 stat (const char * path, struct stat * buf)
4338 return stat_worker (path, buf, 1);
4342 lstat (const char * path, struct stat * buf)
4344 return stat_worker (path, buf, 0);
4348 fstatat (int fd, char const *name, struct stat *st, int flags)
4350 /* Rely on a hack: an open directory is modeled as file descriptor 0.
4351 This is good enough for the current usage in Emacs, but is fragile.
4353 FIXME: Add proper support for fdopendir, fstatat, readlinkat.
4354 Gnulib does this and can serve as a model. */
4355 char fullname[MAX_PATH];
4357 if (fd != AT_FDCWD)
4359 if (_snprintf (fullname, sizeof fullname, "%s/%s", dir_pathname, name)
4360 < 0)
4362 errno = ENAMETOOLONG;
4363 return -1;
4365 name = fullname;
4368 return stat_worker (name, st, ! (flags & AT_SYMLINK_NOFOLLOW));
4371 /* Provide fstat and utime as well as stat for consistent handling of
4372 file timestamps. */
4374 fstat (int desc, struct stat * buf)
4376 HANDLE fh = (HANDLE) _get_osfhandle (desc);
4377 BY_HANDLE_FILE_INFORMATION info;
4378 unsigned __int64 fake_inode;
4379 int permission;
4381 switch (GetFileType (fh) & ~FILE_TYPE_REMOTE)
4383 case FILE_TYPE_DISK:
4384 buf->st_mode = S_IFREG;
4385 if (!GetFileInformationByHandle (fh, &info))
4387 errno = EACCES;
4388 return -1;
4390 break;
4391 case FILE_TYPE_PIPE:
4392 buf->st_mode = S_IFIFO;
4393 goto non_disk;
4394 case FILE_TYPE_CHAR:
4395 case FILE_TYPE_UNKNOWN:
4396 default:
4397 buf->st_mode = S_IFCHR;
4398 non_disk:
4399 memset (&info, 0, sizeof (info));
4400 info.dwFileAttributes = 0;
4401 info.ftCreationTime = utc_base_ft;
4402 info.ftLastAccessTime = utc_base_ft;
4403 info.ftLastWriteTime = utc_base_ft;
4406 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
4407 buf->st_mode = S_IFDIR;
4409 buf->st_nlink = info.nNumberOfLinks;
4410 /* Might as well use file index to fake inode values, but this
4411 is not guaranteed to be unique unless we keep a handle open
4412 all the time (even then there are situations where it is
4413 not unique). Reputedly, there are at most 48 bits of info
4414 (on NTFS, presumably less on FAT). */
4415 fake_inode = info.nFileIndexHigh;
4416 fake_inode <<= 32;
4417 fake_inode += info.nFileIndexLow;
4419 /* MSVC defines _ino_t to be short; other libc's might not. */
4420 if (sizeof (buf->st_ino) == 2)
4421 buf->st_ino = fake_inode ^ (fake_inode >> 16);
4422 else
4423 buf->st_ino = fake_inode;
4425 /* If the caller so requested, get the true file owner and group.
4426 Otherwise, consider the file to belong to the current user. */
4427 if (!w32_stat_get_owner_group || is_windows_9x () == TRUE)
4428 get_file_owner_and_group (NULL, buf);
4429 else
4431 PSECURITY_DESCRIPTOR psd = NULL;
4433 psd = get_file_security_desc_by_handle (fh);
4434 if (psd)
4436 get_file_owner_and_group (psd, buf);
4437 LocalFree (psd);
4439 else
4440 get_file_owner_and_group (NULL, buf);
4443 buf->st_dev = info.dwVolumeSerialNumber;
4444 buf->st_rdev = info.dwVolumeSerialNumber;
4446 buf->st_size = info.nFileSizeHigh;
4447 buf->st_size <<= 32;
4448 buf->st_size += info.nFileSizeLow;
4450 /* Convert timestamps to Unix format. */
4451 buf->st_mtime = convert_time (info.ftLastWriteTime);
4452 buf->st_atime = convert_time (info.ftLastAccessTime);
4453 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
4454 buf->st_ctime = convert_time (info.ftCreationTime);
4455 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
4457 /* determine rwx permissions */
4458 if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
4459 permission = S_IREAD;
4460 else
4461 permission = S_IREAD | S_IWRITE;
4463 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
4464 permission |= S_IEXEC;
4465 else
4467 #if 0 /* no way of knowing the filename */
4468 char * p = strrchr (name, '.');
4469 if (p != NULL &&
4470 (xstrcasecmp (p, ".exe") == 0 ||
4471 xstrcasecmp (p, ".com") == 0 ||
4472 xstrcasecmp (p, ".bat") == 0 ||
4473 xstrcasecmp (p, ".cmd") == 0))
4474 permission |= S_IEXEC;
4475 #endif
4478 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
4480 return 0;
4484 utime (const char *name, struct utimbuf *times)
4486 struct utimbuf deftime;
4487 HANDLE fh;
4488 FILETIME mtime;
4489 FILETIME atime;
4491 if (times == NULL)
4493 deftime.modtime = deftime.actime = time (NULL);
4494 times = &deftime;
4497 /* Need write access to set times. */
4498 fh = CreateFile (name, FILE_WRITE_ATTRIBUTES,
4499 /* If NAME specifies a directory, FILE_SHARE_DELETE
4500 allows other processes to delete files inside it,
4501 while we have the directory open. */
4502 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
4503 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
4504 if (fh != INVALID_HANDLE_VALUE)
4506 convert_from_time_t (times->actime, &atime);
4507 convert_from_time_t (times->modtime, &mtime);
4508 if (!SetFileTime (fh, NULL, &atime, &mtime))
4510 CloseHandle (fh);
4511 errno = EACCES;
4512 return -1;
4514 CloseHandle (fh);
4516 else
4518 errno = EINVAL;
4519 return -1;
4521 return 0;
4525 /* Symlink-related functions. */
4526 #ifndef SYMBOLIC_LINK_FLAG_DIRECTORY
4527 #define SYMBOLIC_LINK_FLAG_DIRECTORY 0x1
4528 #endif
4531 symlink (char const *filename, char const *linkname)
4533 char linkfn[MAX_PATH], *tgtfn;
4534 DWORD flags = 0;
4535 int dir_access, filename_ends_in_slash;
4536 int dbcs_p;
4538 /* Diagnostics follows Posix as much as possible. */
4539 if (filename == NULL || linkname == NULL)
4541 errno = EFAULT;
4542 return -1;
4544 if (!*filename)
4546 errno = ENOENT;
4547 return -1;
4549 if (strlen (filename) > MAX_PATH || strlen (linkname) > MAX_PATH)
4551 errno = ENAMETOOLONG;
4552 return -1;
4555 strcpy (linkfn, map_w32_filename (linkname, NULL));
4556 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) == 0)
4558 errno = EPERM;
4559 return -1;
4562 dbcs_p = max_filename_mbslen () > 1;
4564 /* Note: since empty FILENAME was already rejected, we can safely
4565 refer to FILENAME[1]. */
4566 if (!(IS_DIRECTORY_SEP (filename[0]) || IS_DEVICE_SEP (filename[1])))
4568 /* Non-absolute FILENAME is understood as being relative to
4569 LINKNAME's directory. We need to prepend that directory to
4570 FILENAME to get correct results from faccessat below, since
4571 otherwise it will interpret FILENAME relative to the
4572 directory where the Emacs process runs. Note that
4573 make-symbolic-link always makes sure LINKNAME is a fully
4574 expanded file name. */
4575 char tem[MAX_PATH];
4576 char *p = linkfn + strlen (linkfn);
4578 if (!dbcs_p)
4580 while (p > linkfn && !IS_ANY_SEP (p[-1]))
4581 p--;
4583 else
4585 char *p1 = CharPrevExA (file_name_codepage, linkfn, p, 0);
4587 while (p > linkfn && !IS_ANY_SEP (*p1))
4589 p = p1;
4590 p1 = CharPrevExA (file_name_codepage, linkfn, p1, 0);
4593 if (p > linkfn)
4594 strncpy (tem, linkfn, p - linkfn);
4595 tem[p - linkfn] = '\0';
4596 strcat (tem, filename);
4597 dir_access = faccessat (AT_FDCWD, tem, D_OK, AT_EACCESS);
4599 else
4600 dir_access = faccessat (AT_FDCWD, filename, D_OK, AT_EACCESS);
4602 /* Since Windows distinguishes between symlinks to directories and
4603 to files, we provide a kludgy feature: if FILENAME doesn't
4604 exist, but ends in a slash, we create a symlink to directory. If
4605 FILENAME exists and is a directory, we always create a symlink to
4606 directory. */
4607 if (!dbcs_p)
4608 filename_ends_in_slash = IS_DIRECTORY_SEP (filename[strlen (filename) - 1]);
4609 else
4611 const char *end = filename + strlen (filename);
4612 const char *n = CharPrevExA (file_name_codepage, filename, end, 0);
4614 filename_ends_in_slash = IS_DIRECTORY_SEP (*n);
4616 if (dir_access == 0 || filename_ends_in_slash)
4617 flags = SYMBOLIC_LINK_FLAG_DIRECTORY;
4619 tgtfn = (char *)map_w32_filename (filename, NULL);
4620 if (filename_ends_in_slash)
4621 tgtfn[strlen (tgtfn) - 1] = '\0';
4623 errno = 0;
4624 if (!create_symbolic_link (linkfn, tgtfn, flags))
4626 /* ENOSYS is set by create_symbolic_link, when it detects that
4627 the OS doesn't support the CreateSymbolicLink API. */
4628 if (errno != ENOSYS)
4630 DWORD w32err = GetLastError ();
4632 switch (w32err)
4634 /* ERROR_SUCCESS is sometimes returned when LINKFN and
4635 TGTFN point to the same file name, go figure. */
4636 case ERROR_SUCCESS:
4637 case ERROR_FILE_EXISTS:
4638 errno = EEXIST;
4639 break;
4640 case ERROR_ACCESS_DENIED:
4641 errno = EACCES;
4642 break;
4643 case ERROR_FILE_NOT_FOUND:
4644 case ERROR_PATH_NOT_FOUND:
4645 case ERROR_BAD_NETPATH:
4646 case ERROR_INVALID_REPARSE_DATA:
4647 errno = ENOENT;
4648 break;
4649 case ERROR_DIRECTORY:
4650 errno = EISDIR;
4651 break;
4652 case ERROR_PRIVILEGE_NOT_HELD:
4653 case ERROR_NOT_ALL_ASSIGNED:
4654 errno = EPERM;
4655 break;
4656 case ERROR_DISK_FULL:
4657 errno = ENOSPC;
4658 break;
4659 default:
4660 errno = EINVAL;
4661 break;
4664 return -1;
4666 return 0;
4669 /* A quick inexpensive test of whether FILENAME identifies a file that
4670 is a symlink. Returns non-zero if it is, zero otherwise. FILENAME
4671 must already be in the normalized form returned by
4672 map_w32_filename.
4674 Note: for repeated operations on many files, it is best to test
4675 whether the underlying volume actually supports symlinks, by
4676 testing the FILE_SUPPORTS_REPARSE_POINTS bit in volume's flags, and
4677 avoid the call to this function if it doesn't. That's because the
4678 call to GetFileAttributes takes a non-negligible time, especially
4679 on non-local or removable filesystems. See stat_worker for an
4680 example of how to do that. */
4681 static int
4682 is_symlink (const char *filename)
4684 DWORD attrs;
4685 WIN32_FIND_DATA wfd;
4686 HANDLE fh;
4688 attrs = GetFileAttributes (filename);
4689 if (attrs == -1)
4691 DWORD w32err = GetLastError ();
4693 switch (w32err)
4695 case ERROR_BAD_NETPATH: /* network share, can't be a symlink */
4696 break;
4697 case ERROR_ACCESS_DENIED:
4698 errno = EACCES;
4699 break;
4700 case ERROR_FILE_NOT_FOUND:
4701 case ERROR_PATH_NOT_FOUND:
4702 default:
4703 errno = ENOENT;
4704 break;
4706 return 0;
4708 if ((attrs & FILE_ATTRIBUTE_REPARSE_POINT) == 0)
4709 return 0;
4710 logon_network_drive (filename);
4711 fh = FindFirstFile (filename, &wfd);
4712 if (fh == INVALID_HANDLE_VALUE)
4713 return 0;
4714 FindClose (fh);
4715 return (wfd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0
4716 && (wfd.dwReserved0 & IO_REPARSE_TAG_SYMLINK) == IO_REPARSE_TAG_SYMLINK;
4719 /* If NAME identifies a symbolic link, copy into BUF the file name of
4720 the symlink's target. Copy at most BUF_SIZE bytes, and do NOT
4721 null-terminate the target name, even if it fits. Return the number
4722 of bytes copied, or -1 if NAME is not a symlink or any error was
4723 encountered while resolving it. The file name copied into BUF is
4724 encoded in the current ANSI codepage. */
4725 ssize_t
4726 readlink (const char *name, char *buf, size_t buf_size)
4728 const char *path;
4729 TOKEN_PRIVILEGES privs;
4730 int restore_privs = 0;
4731 HANDLE sh;
4732 ssize_t retval;
4734 if (name == NULL)
4736 errno = EFAULT;
4737 return -1;
4739 if (!*name)
4741 errno = ENOENT;
4742 return -1;
4745 path = map_w32_filename (name, NULL);
4747 if (strlen (path) > MAX_PATH)
4749 errno = ENAMETOOLONG;
4750 return -1;
4753 errno = 0;
4754 if (is_windows_9x () == TRUE
4755 || (volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) == 0
4756 || !is_symlink (path))
4758 if (!errno)
4759 errno = EINVAL; /* not a symlink */
4760 return -1;
4763 /* Done with simple tests, now we're in for some _real_ work. */
4764 if (enable_privilege (SE_BACKUP_NAME, TRUE, &privs))
4765 restore_privs = 1;
4766 /* Implementation note: From here and onward, don't return early,
4767 since that will fail to restore the original set of privileges of
4768 the calling thread. */
4770 retval = -1; /* not too optimistic, are we? */
4772 /* Note: In the next call to CreateFile, we use zero as the 2nd
4773 argument because, when the symlink is a hidden/system file,
4774 e.g. 'C:\Users\All Users', GENERIC_READ fails with
4775 ERROR_ACCESS_DENIED. Zero seems to work just fine, both for file
4776 and directory symlinks. */
4777 sh = CreateFile (path, 0, 0, NULL, OPEN_EXISTING,
4778 FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
4779 NULL);
4780 if (sh != INVALID_HANDLE_VALUE)
4782 BYTE reparse_buf[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
4783 REPARSE_DATA_BUFFER *reparse_data = (REPARSE_DATA_BUFFER *)&reparse_buf[0];
4784 DWORD retbytes;
4786 if (!DeviceIoControl (sh, FSCTL_GET_REPARSE_POINT, NULL, 0,
4787 reparse_buf, MAXIMUM_REPARSE_DATA_BUFFER_SIZE,
4788 &retbytes, NULL))
4789 errno = EIO;
4790 else if (reparse_data->ReparseTag != IO_REPARSE_TAG_SYMLINK)
4791 errno = EINVAL;
4792 else
4794 /* Copy the link target name, in wide characters, from
4795 reparse_data, then convert it to multibyte encoding in
4796 the current locale's codepage. */
4797 WCHAR *lwname;
4798 BYTE lname[MAX_PATH];
4799 USHORT lname_len;
4800 USHORT lwname_len =
4801 reparse_data->SymbolicLinkReparseBuffer.PrintNameLength;
4802 WCHAR *lwname_src =
4803 reparse_data->SymbolicLinkReparseBuffer.PathBuffer
4804 + reparse_data->SymbolicLinkReparseBuffer.PrintNameOffset/sizeof(WCHAR);
4805 /* This updates file_name_codepage which we need below. */
4806 int dbcs_p = max_filename_mbslen () > 1;
4808 /* According to MSDN, PrintNameLength does not include the
4809 terminating null character. */
4810 lwname = alloca ((lwname_len + 1) * sizeof(WCHAR));
4811 memcpy (lwname, lwname_src, lwname_len);
4812 lwname[lwname_len/sizeof(WCHAR)] = 0; /* null-terminate */
4814 lname_len = WideCharToMultiByte (file_name_codepage, 0, lwname, -1,
4815 lname, MAX_PATH, NULL, NULL);
4816 if (!lname_len)
4818 /* WideCharToMultiByte failed. */
4819 DWORD w32err1 = GetLastError ();
4821 switch (w32err1)
4823 case ERROR_INSUFFICIENT_BUFFER:
4824 errno = ENAMETOOLONG;
4825 break;
4826 case ERROR_INVALID_PARAMETER:
4827 errno = EFAULT;
4828 break;
4829 case ERROR_NO_UNICODE_TRANSLATION:
4830 errno = ENOENT;
4831 break;
4832 default:
4833 errno = EINVAL;
4834 break;
4837 else
4839 size_t size_to_copy = buf_size;
4840 BYTE *p = lname, *p2;
4841 BYTE *pend = p + lname_len;
4843 /* Normalize like dostounix_filename does, but we don't
4844 want to assume that lname is null-terminated. */
4845 if (dbcs_p)
4846 p2 = CharNextExA (file_name_codepage, p, 0);
4847 else
4848 p2 = p + 1;
4849 if (*p && *p2 == ':' && *p >= 'A' && *p <= 'Z')
4851 *p += 'a' - 'A';
4852 p += 2;
4854 while (p <= pend)
4856 if (*p == '\\')
4857 *p = '/';
4858 if (dbcs_p)
4860 p = CharNextExA (file_name_codepage, p, 0);
4861 /* CharNextExA doesn't advance at null character. */
4862 if (!*p)
4863 break;
4865 else
4866 ++p;
4868 /* Testing for null-terminated LNAME is paranoia:
4869 WideCharToMultiByte should always return a
4870 null-terminated string when its 4th argument is -1
4871 and its 3rd argument is null-terminated (which they
4872 are, see above). */
4873 if (lname[lname_len - 1] == '\0')
4874 lname_len--;
4875 if (lname_len <= buf_size)
4876 size_to_copy = lname_len;
4877 strncpy (buf, lname, size_to_copy);
4878 /* Success! */
4879 retval = size_to_copy;
4882 CloseHandle (sh);
4884 else
4886 /* CreateFile failed. */
4887 DWORD w32err2 = GetLastError ();
4889 switch (w32err2)
4891 case ERROR_FILE_NOT_FOUND:
4892 case ERROR_PATH_NOT_FOUND:
4893 errno = ENOENT;
4894 break;
4895 case ERROR_ACCESS_DENIED:
4896 case ERROR_TOO_MANY_OPEN_FILES:
4897 errno = EACCES;
4898 break;
4899 default:
4900 errno = EPERM;
4901 break;
4904 if (restore_privs)
4906 restore_privilege (&privs);
4907 revert_to_self ();
4910 return retval;
4913 ssize_t
4914 readlinkat (int fd, char const *name, char *buffer,
4915 size_t buffer_size)
4917 /* Rely on a hack: an open directory is modeled as file descriptor 0,
4918 as in fstatat. FIXME: Add proper support for readlinkat. */
4919 char fullname[MAX_PATH];
4921 if (fd != AT_FDCWD)
4923 if (_snprintf (fullname, sizeof fullname, "%s/%s", dir_pathname, name)
4924 < 0)
4926 errno = ENAMETOOLONG;
4927 return -1;
4929 name = fullname;
4932 return readlink (name, buffer, buffer_size);
4935 /* If FILE is a symlink, return its target (stored in a static
4936 buffer); otherwise return FILE.
4938 This function repeatedly resolves symlinks in the last component of
4939 a chain of symlink file names, as in foo -> bar -> baz -> ...,
4940 until it arrives at a file whose last component is not a symlink,
4941 or some error occurs. It returns the target of the last
4942 successfully resolved symlink in the chain. If it succeeds to
4943 resolve even a single symlink, the value returned is an absolute
4944 file name with backslashes (result of GetFullPathName). By
4945 contrast, if the original FILE is returned, it is unaltered.
4947 Note: This function can set errno even if it succeeds.
4949 Implementation note: we only resolve the last portion ("basename")
4950 of the argument FILE and of each following file in the chain,
4951 disregarding any possible symlinks in its leading directories.
4952 This is because Windows system calls and library functions
4953 transparently resolve symlinks in leading directories and return
4954 correct information, as long as the basename is not a symlink. */
4955 static char *
4956 chase_symlinks (const char *file)
4958 static char target[MAX_PATH];
4959 char link[MAX_PATH];
4960 ssize_t res, link_len;
4961 int loop_count = 0;
4962 int dbcs_p;
4964 if (is_windows_9x () == TRUE || !is_symlink (file))
4965 return (char *)file;
4967 if ((link_len = GetFullPathName (file, MAX_PATH, link, NULL)) == 0)
4968 return (char *)file;
4970 dbcs_p = max_filename_mbslen () > 1;
4971 target[0] = '\0';
4972 do {
4974 /* Remove trailing slashes, as we want to resolve the last
4975 non-trivial part of the link name. */
4976 if (!dbcs_p)
4978 while (link_len > 3 && IS_DIRECTORY_SEP (link[link_len-1]))
4979 link[link_len--] = '\0';
4981 else if (link_len > 3)
4983 char *n = CharPrevExA (file_name_codepage, link, link + link_len, 0);
4985 while (n >= link + 2 && IS_DIRECTORY_SEP (*n))
4987 n[1] = '\0';
4988 n = CharPrevExA (file_name_codepage, link, n, 0);
4992 res = readlink (link, target, MAX_PATH);
4993 if (res > 0)
4995 target[res] = '\0';
4996 if (!(IS_DEVICE_SEP (target[1])
4997 || (IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1]))))
4999 /* Target is relative. Append it to the directory part of
5000 the symlink, then copy the result back to target. */
5001 char *p = link + link_len;
5003 if (!dbcs_p)
5005 while (p > link && !IS_ANY_SEP (p[-1]))
5006 p--;
5008 else
5010 char *p1 = CharPrevExA (file_name_codepage, link, p, 0);
5012 while (p > link && !IS_ANY_SEP (*p1))
5014 p = p1;
5015 p1 = CharPrevExA (file_name_codepage, link, p1, 0);
5018 strcpy (p, target);
5019 strcpy (target, link);
5021 /* Resolve any "." and ".." to get a fully-qualified file name
5022 in link[] again. */
5023 link_len = GetFullPathName (target, MAX_PATH, link, NULL);
5025 } while (res > 0 && link_len > 0 && ++loop_count <= 100);
5027 if (loop_count > 100)
5028 errno = ELOOP;
5030 if (target[0] == '\0') /* not a single call to readlink succeeded */
5031 return (char *)file;
5032 return target;
5036 /* Posix ACL emulation. */
5039 acl_valid (acl_t acl)
5041 return is_valid_security_descriptor ((PSECURITY_DESCRIPTOR)acl) ? 0 : -1;
5044 char *
5045 acl_to_text (acl_t acl, ssize_t *size)
5047 LPTSTR str_acl;
5048 SECURITY_INFORMATION flags =
5049 OWNER_SECURITY_INFORMATION |
5050 GROUP_SECURITY_INFORMATION |
5051 DACL_SECURITY_INFORMATION;
5052 char *retval = NULL;
5053 ULONG local_size;
5054 int e = errno;
5056 errno = 0;
5058 if (convert_sd_to_sddl ((PSECURITY_DESCRIPTOR)acl, SDDL_REVISION_1, flags, &str_acl, &local_size))
5060 errno = e;
5061 /* We don't want to mix heaps, so we duplicate the string in our
5062 heap and free the one allocated by the API. */
5063 retval = xstrdup (str_acl);
5064 if (size)
5065 *size = local_size;
5066 LocalFree (str_acl);
5068 else if (errno != ENOTSUP)
5069 errno = EINVAL;
5071 return retval;
5074 acl_t
5075 acl_from_text (const char *acl_str)
5077 PSECURITY_DESCRIPTOR psd, retval = NULL;
5078 ULONG sd_size;
5079 int e = errno;
5081 errno = 0;
5083 if (convert_sddl_to_sd (acl_str, SDDL_REVISION_1, &psd, &sd_size))
5085 errno = e;
5086 retval = xmalloc (sd_size);
5087 memcpy (retval, psd, sd_size);
5088 LocalFree (psd);
5090 else if (errno != ENOTSUP)
5091 errno = EINVAL;
5093 return retval;
5097 acl_free (void *ptr)
5099 xfree (ptr);
5100 return 0;
5103 acl_t
5104 acl_get_file (const char *fname, acl_type_t type)
5106 PSECURITY_DESCRIPTOR psd = NULL;
5107 const char *filename;
5109 if (type == ACL_TYPE_ACCESS)
5111 DWORD sd_len, err;
5112 SECURITY_INFORMATION si =
5113 OWNER_SECURITY_INFORMATION |
5114 GROUP_SECURITY_INFORMATION |
5115 DACL_SECURITY_INFORMATION ;
5116 int e = errno;
5118 filename = map_w32_filename (fname, NULL);
5119 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
5120 fname = chase_symlinks (filename);
5121 else
5122 fname = filename;
5124 errno = 0;
5125 if (!get_file_security (fname, si, psd, 0, &sd_len)
5126 && errno != ENOTSUP)
5128 err = GetLastError ();
5129 if (err == ERROR_INSUFFICIENT_BUFFER)
5131 psd = xmalloc (sd_len);
5132 if (!get_file_security (fname, si, psd, sd_len, &sd_len))
5134 xfree (psd);
5135 errno = EIO;
5136 psd = NULL;
5139 else if (err == ERROR_FILE_NOT_FOUND
5140 || err == ERROR_PATH_NOT_FOUND)
5141 errno = ENOENT;
5142 else
5143 errno = EIO;
5145 else if (!errno)
5146 errno = e;
5148 else if (type != ACL_TYPE_DEFAULT)
5149 errno = EINVAL;
5151 return psd;
5155 acl_set_file (const char *fname, acl_type_t type, acl_t acl)
5157 TOKEN_PRIVILEGES old1, old2;
5158 DWORD err;
5159 int st = 0, retval = -1;
5160 SECURITY_INFORMATION flags = 0;
5161 PSID psid;
5162 PACL pacl;
5163 BOOL dflt;
5164 BOOL dacl_present;
5165 int e;
5166 const char *filename;
5168 if (acl_valid (acl) != 0
5169 || (type != ACL_TYPE_DEFAULT && type != ACL_TYPE_ACCESS))
5171 errno = EINVAL;
5172 return -1;
5175 if (type == ACL_TYPE_DEFAULT)
5177 errno = ENOSYS;
5178 return -1;
5181 filename = map_w32_filename (fname, NULL);
5182 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
5183 fname = chase_symlinks (filename);
5184 else
5185 fname = filename;
5187 if (get_security_descriptor_owner ((PSECURITY_DESCRIPTOR)acl, &psid, &dflt)
5188 && psid)
5189 flags |= OWNER_SECURITY_INFORMATION;
5190 if (get_security_descriptor_group ((PSECURITY_DESCRIPTOR)acl, &psid, &dflt)
5191 && psid)
5192 flags |= GROUP_SECURITY_INFORMATION;
5193 if (get_security_descriptor_dacl ((PSECURITY_DESCRIPTOR)acl, &dacl_present,
5194 &pacl, &dflt)
5195 && dacl_present)
5196 flags |= DACL_SECURITY_INFORMATION;
5197 if (!flags)
5198 return 0;
5200 /* According to KB-245153, setting the owner will succeed if either:
5201 (1) the caller is the user who will be the new owner, and has the
5202 SE_TAKE_OWNERSHIP privilege, or
5203 (2) the caller has the SE_RESTORE privilege, in which case she can
5204 set any valid user or group as the owner
5206 We request below both SE_TAKE_OWNERSHIP and SE_RESTORE
5207 privileges, and disregard any failures in obtaining them. If
5208 these privileges cannot be obtained, and do not already exist in
5209 the calling thread's security token, this function could fail
5210 with EPERM. */
5211 if (enable_privilege (SE_TAKE_OWNERSHIP_NAME, TRUE, &old1))
5212 st++;
5213 if (enable_privilege (SE_RESTORE_NAME, TRUE, &old2))
5214 st++;
5216 e = errno;
5217 errno = 0;
5218 if (!set_file_security ((char *)fname, flags, (PSECURITY_DESCRIPTOR)acl))
5220 err = GetLastError ();
5222 if (errno == ENOTSUP)
5224 else if (err == ERROR_INVALID_OWNER
5225 || err == ERROR_NOT_ALL_ASSIGNED
5226 || err == ERROR_ACCESS_DENIED)
5228 /* Maybe the requested ACL and the one the file already has
5229 are identical, in which case we can silently ignore the
5230 failure. (And no, Windows doesn't.) */
5231 acl_t current_acl = acl_get_file (fname, ACL_TYPE_ACCESS);
5233 errno = EPERM;
5234 if (current_acl)
5236 char *acl_from = acl_to_text (current_acl, NULL);
5237 char *acl_to = acl_to_text (acl, NULL);
5239 if (acl_from && acl_to && xstrcasecmp (acl_from, acl_to) == 0)
5241 retval = 0;
5242 errno = e;
5244 if (acl_from)
5245 acl_free (acl_from);
5246 if (acl_to)
5247 acl_free (acl_to);
5248 acl_free (current_acl);
5251 else if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
5252 errno = ENOENT;
5253 else
5254 errno = EACCES;
5256 else
5258 retval = 0;
5259 errno = e;
5262 if (st)
5264 if (st >= 2)
5265 restore_privilege (&old2);
5266 restore_privilege (&old1);
5267 revert_to_self ();
5270 return retval;
5274 /* MS-Windows version of careadlinkat (cf. ../lib/careadlinkat.c). We
5275 have a fixed max size for file names, so we don't need the kind of
5276 alloc/malloc/realloc dance the gnulib version does. We also don't
5277 support FD-relative symlinks. */
5278 char *
5279 careadlinkat (int fd, char const *filename,
5280 char *buffer, size_t buffer_size,
5281 struct allocator const *alloc,
5282 ssize_t (*preadlinkat) (int, char const *, char *, size_t))
5284 char linkname[MAX_PATH];
5285 ssize_t link_size;
5287 link_size = preadlinkat (fd, filename, linkname, sizeof(linkname));
5289 if (link_size > 0)
5291 char *retval = buffer;
5293 linkname[link_size++] = '\0';
5294 if (link_size > buffer_size)
5295 retval = (char *)(alloc ? alloc->allocate : xmalloc) (link_size);
5296 if (retval)
5297 memcpy (retval, linkname, link_size);
5299 return retval;
5301 return NULL;
5305 /* Support for browsing other processes and their attributes. See
5306 process.c for the Lisp bindings. */
5308 /* Helper wrapper functions. */
5310 static HANDLE WINAPI
5311 create_toolhelp32_snapshot (DWORD Flags, DWORD Ignored)
5313 static CreateToolhelp32Snapshot_Proc s_pfn_Create_Toolhelp32_Snapshot = NULL;
5315 if (g_b_init_create_toolhelp32_snapshot == 0)
5317 g_b_init_create_toolhelp32_snapshot = 1;
5318 s_pfn_Create_Toolhelp32_Snapshot = (CreateToolhelp32Snapshot_Proc)
5319 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5320 "CreateToolhelp32Snapshot");
5322 if (s_pfn_Create_Toolhelp32_Snapshot == NULL)
5324 return INVALID_HANDLE_VALUE;
5326 return (s_pfn_Create_Toolhelp32_Snapshot (Flags, Ignored));
5329 static BOOL WINAPI
5330 process32_first (HANDLE hSnapshot, LPPROCESSENTRY32 lppe)
5332 static Process32First_Proc s_pfn_Process32_First = NULL;
5334 if (g_b_init_process32_first == 0)
5336 g_b_init_process32_first = 1;
5337 s_pfn_Process32_First = (Process32First_Proc)
5338 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5339 "Process32First");
5341 if (s_pfn_Process32_First == NULL)
5343 return FALSE;
5345 return (s_pfn_Process32_First (hSnapshot, lppe));
5348 static BOOL WINAPI
5349 process32_next (HANDLE hSnapshot, LPPROCESSENTRY32 lppe)
5351 static Process32Next_Proc s_pfn_Process32_Next = NULL;
5353 if (g_b_init_process32_next == 0)
5355 g_b_init_process32_next = 1;
5356 s_pfn_Process32_Next = (Process32Next_Proc)
5357 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5358 "Process32Next");
5360 if (s_pfn_Process32_Next == NULL)
5362 return FALSE;
5364 return (s_pfn_Process32_Next (hSnapshot, lppe));
5367 static BOOL WINAPI
5368 open_thread_token (HANDLE ThreadHandle,
5369 DWORD DesiredAccess,
5370 BOOL OpenAsSelf,
5371 PHANDLE TokenHandle)
5373 static OpenThreadToken_Proc s_pfn_Open_Thread_Token = NULL;
5374 HMODULE hm_advapi32 = NULL;
5375 if (is_windows_9x () == TRUE)
5377 SetLastError (ERROR_NOT_SUPPORTED);
5378 return FALSE;
5380 if (g_b_init_open_thread_token == 0)
5382 g_b_init_open_thread_token = 1;
5383 hm_advapi32 = LoadLibrary ("Advapi32.dll");
5384 s_pfn_Open_Thread_Token =
5385 (OpenThreadToken_Proc) GetProcAddress (hm_advapi32, "OpenThreadToken");
5387 if (s_pfn_Open_Thread_Token == NULL)
5389 SetLastError (ERROR_NOT_SUPPORTED);
5390 return FALSE;
5392 return (
5393 s_pfn_Open_Thread_Token (
5394 ThreadHandle,
5395 DesiredAccess,
5396 OpenAsSelf,
5397 TokenHandle)
5401 static BOOL WINAPI
5402 impersonate_self (SECURITY_IMPERSONATION_LEVEL ImpersonationLevel)
5404 static ImpersonateSelf_Proc s_pfn_Impersonate_Self = NULL;
5405 HMODULE hm_advapi32 = NULL;
5406 if (is_windows_9x () == TRUE)
5408 return FALSE;
5410 if (g_b_init_impersonate_self == 0)
5412 g_b_init_impersonate_self = 1;
5413 hm_advapi32 = LoadLibrary ("Advapi32.dll");
5414 s_pfn_Impersonate_Self =
5415 (ImpersonateSelf_Proc) GetProcAddress (hm_advapi32, "ImpersonateSelf");
5417 if (s_pfn_Impersonate_Self == NULL)
5419 return FALSE;
5421 return s_pfn_Impersonate_Self (ImpersonationLevel);
5424 static BOOL WINAPI
5425 revert_to_self (void)
5427 static RevertToSelf_Proc s_pfn_Revert_To_Self = NULL;
5428 HMODULE hm_advapi32 = NULL;
5429 if (is_windows_9x () == TRUE)
5431 return FALSE;
5433 if (g_b_init_revert_to_self == 0)
5435 g_b_init_revert_to_self = 1;
5436 hm_advapi32 = LoadLibrary ("Advapi32.dll");
5437 s_pfn_Revert_To_Self =
5438 (RevertToSelf_Proc) GetProcAddress (hm_advapi32, "RevertToSelf");
5440 if (s_pfn_Revert_To_Self == NULL)
5442 return FALSE;
5444 return s_pfn_Revert_To_Self ();
5447 static BOOL WINAPI
5448 get_process_memory_info (HANDLE h_proc,
5449 PPROCESS_MEMORY_COUNTERS mem_counters,
5450 DWORD bufsize)
5452 static GetProcessMemoryInfo_Proc s_pfn_Get_Process_Memory_Info = NULL;
5453 HMODULE hm_psapi = NULL;
5454 if (is_windows_9x () == TRUE)
5456 return FALSE;
5458 if (g_b_init_get_process_memory_info == 0)
5460 g_b_init_get_process_memory_info = 1;
5461 hm_psapi = LoadLibrary ("Psapi.dll");
5462 if (hm_psapi)
5463 s_pfn_Get_Process_Memory_Info = (GetProcessMemoryInfo_Proc)
5464 GetProcAddress (hm_psapi, "GetProcessMemoryInfo");
5466 if (s_pfn_Get_Process_Memory_Info == NULL)
5468 return FALSE;
5470 return s_pfn_Get_Process_Memory_Info (h_proc, mem_counters, bufsize);
5473 static BOOL WINAPI
5474 get_process_working_set_size (HANDLE h_proc,
5475 PSIZE_T minrss,
5476 PSIZE_T maxrss)
5478 static GetProcessWorkingSetSize_Proc
5479 s_pfn_Get_Process_Working_Set_Size = NULL;
5481 if (is_windows_9x () == TRUE)
5483 return FALSE;
5485 if (g_b_init_get_process_working_set_size == 0)
5487 g_b_init_get_process_working_set_size = 1;
5488 s_pfn_Get_Process_Working_Set_Size = (GetProcessWorkingSetSize_Proc)
5489 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5490 "GetProcessWorkingSetSize");
5492 if (s_pfn_Get_Process_Working_Set_Size == NULL)
5494 return FALSE;
5496 return s_pfn_Get_Process_Working_Set_Size (h_proc, minrss, maxrss);
5499 static BOOL WINAPI
5500 global_memory_status (MEMORYSTATUS *buf)
5502 static GlobalMemoryStatus_Proc s_pfn_Global_Memory_Status = NULL;
5504 if (is_windows_9x () == TRUE)
5506 return FALSE;
5508 if (g_b_init_global_memory_status == 0)
5510 g_b_init_global_memory_status = 1;
5511 s_pfn_Global_Memory_Status = (GlobalMemoryStatus_Proc)
5512 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5513 "GlobalMemoryStatus");
5515 if (s_pfn_Global_Memory_Status == NULL)
5517 return FALSE;
5519 return s_pfn_Global_Memory_Status (buf);
5522 static BOOL WINAPI
5523 global_memory_status_ex (MEMORY_STATUS_EX *buf)
5525 static GlobalMemoryStatusEx_Proc s_pfn_Global_Memory_Status_Ex = NULL;
5527 if (is_windows_9x () == TRUE)
5529 return FALSE;
5531 if (g_b_init_global_memory_status_ex == 0)
5533 g_b_init_global_memory_status_ex = 1;
5534 s_pfn_Global_Memory_Status_Ex = (GlobalMemoryStatusEx_Proc)
5535 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5536 "GlobalMemoryStatusEx");
5538 if (s_pfn_Global_Memory_Status_Ex == NULL)
5540 return FALSE;
5542 return s_pfn_Global_Memory_Status_Ex (buf);
5545 Lisp_Object
5546 list_system_processes (void)
5548 struct gcpro gcpro1;
5549 Lisp_Object proclist = Qnil;
5550 HANDLE h_snapshot;
5552 h_snapshot = create_toolhelp32_snapshot (TH32CS_SNAPPROCESS, 0);
5554 if (h_snapshot != INVALID_HANDLE_VALUE)
5556 PROCESSENTRY32 proc_entry;
5557 DWORD proc_id;
5558 BOOL res;
5560 GCPRO1 (proclist);
5562 proc_entry.dwSize = sizeof (PROCESSENTRY32);
5563 for (res = process32_first (h_snapshot, &proc_entry); res;
5564 res = process32_next (h_snapshot, &proc_entry))
5566 proc_id = proc_entry.th32ProcessID;
5567 proclist = Fcons (make_fixnum_or_float (proc_id), proclist);
5570 CloseHandle (h_snapshot);
5571 UNGCPRO;
5572 proclist = Fnreverse (proclist);
5575 return proclist;
5578 static int
5579 enable_privilege (LPCTSTR priv_name, BOOL enable_p, TOKEN_PRIVILEGES *old_priv)
5581 TOKEN_PRIVILEGES priv;
5582 DWORD priv_size = sizeof (priv);
5583 DWORD opriv_size = sizeof (*old_priv);
5584 HANDLE h_token = NULL;
5585 HANDLE h_thread = GetCurrentThread ();
5586 int ret_val = 0;
5587 BOOL res;
5589 res = open_thread_token (h_thread,
5590 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
5591 FALSE, &h_token);
5592 if (!res && GetLastError () == ERROR_NO_TOKEN)
5594 if (impersonate_self (SecurityImpersonation))
5595 res = open_thread_token (h_thread,
5596 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
5597 FALSE, &h_token);
5599 if (res)
5601 priv.PrivilegeCount = 1;
5602 priv.Privileges[0].Attributes = enable_p ? SE_PRIVILEGE_ENABLED : 0;
5603 LookupPrivilegeValue (NULL, priv_name, &priv.Privileges[0].Luid);
5604 if (AdjustTokenPrivileges (h_token, FALSE, &priv, priv_size,
5605 old_priv, &opriv_size)
5606 && GetLastError () != ERROR_NOT_ALL_ASSIGNED)
5607 ret_val = 1;
5609 if (h_token)
5610 CloseHandle (h_token);
5612 return ret_val;
5615 static int
5616 restore_privilege (TOKEN_PRIVILEGES *priv)
5618 DWORD priv_size = sizeof (*priv);
5619 HANDLE h_token = NULL;
5620 int ret_val = 0;
5622 if (open_thread_token (GetCurrentThread (),
5623 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
5624 FALSE, &h_token))
5626 if (AdjustTokenPrivileges (h_token, FALSE, priv, priv_size, NULL, NULL)
5627 && GetLastError () != ERROR_NOT_ALL_ASSIGNED)
5628 ret_val = 1;
5630 if (h_token)
5631 CloseHandle (h_token);
5633 return ret_val;
5636 static Lisp_Object
5637 ltime (ULONGLONG time_100ns)
5639 ULONGLONG time_sec = time_100ns / 10000000;
5640 int subsec = time_100ns % 10000000;
5641 return list4i (time_sec >> 16, time_sec & 0xffff,
5642 subsec / 10, subsec % 10 * 100000);
5645 #define U64_TO_LISP_TIME(time) ltime (time)
5647 static int
5648 process_times (HANDLE h_proc, Lisp_Object *ctime, Lisp_Object *etime,
5649 Lisp_Object *stime, Lisp_Object *utime, Lisp_Object *ttime,
5650 double *pcpu)
5652 FILETIME ft_creation, ft_exit, ft_kernel, ft_user, ft_current;
5653 ULONGLONG tem1, tem2, tem3, tem;
5655 if (!h_proc
5656 || !get_process_times_fn
5657 || !(*get_process_times_fn) (h_proc, &ft_creation, &ft_exit,
5658 &ft_kernel, &ft_user))
5659 return 0;
5661 GetSystemTimeAsFileTime (&ft_current);
5663 FILETIME_TO_U64 (tem1, ft_kernel);
5664 *stime = U64_TO_LISP_TIME (tem1);
5666 FILETIME_TO_U64 (tem2, ft_user);
5667 *utime = U64_TO_LISP_TIME (tem2);
5669 tem3 = tem1 + tem2;
5670 *ttime = U64_TO_LISP_TIME (tem3);
5672 FILETIME_TO_U64 (tem, ft_creation);
5673 /* Process no 4 (System) returns zero creation time. */
5674 if (tem)
5675 tem -= utc_base;
5676 *ctime = U64_TO_LISP_TIME (tem);
5678 if (tem)
5680 FILETIME_TO_U64 (tem3, ft_current);
5681 tem = (tem3 - utc_base) - tem;
5683 *etime = U64_TO_LISP_TIME (tem);
5685 if (tem)
5687 *pcpu = 100.0 * (tem1 + tem2) / tem;
5688 if (*pcpu > 100)
5689 *pcpu = 100.0;
5691 else
5692 *pcpu = 0;
5694 return 1;
5697 Lisp_Object
5698 system_process_attributes (Lisp_Object pid)
5700 struct gcpro gcpro1, gcpro2, gcpro3;
5701 Lisp_Object attrs = Qnil;
5702 Lisp_Object cmd_str, decoded_cmd, tem;
5703 HANDLE h_snapshot, h_proc;
5704 DWORD proc_id;
5705 int found_proc = 0;
5706 char uname[UNLEN+1], gname[GNLEN+1], domain[1025];
5707 DWORD ulength = sizeof (uname), dlength = sizeof (domain), needed;
5708 DWORD glength = sizeof (gname);
5709 HANDLE token = NULL;
5710 SID_NAME_USE user_type;
5711 unsigned char *buf = NULL;
5712 DWORD blen = 0;
5713 TOKEN_USER user_token;
5714 TOKEN_PRIMARY_GROUP group_token;
5715 unsigned euid;
5716 unsigned egid;
5717 PROCESS_MEMORY_COUNTERS mem;
5718 PROCESS_MEMORY_COUNTERS_EX mem_ex;
5719 SIZE_T minrss, maxrss;
5720 MEMORYSTATUS memst;
5721 MEMORY_STATUS_EX memstex;
5722 double totphys = 0.0;
5723 Lisp_Object ctime, stime, utime, etime, ttime;
5724 double pcpu;
5725 BOOL result = FALSE;
5727 CHECK_NUMBER_OR_FLOAT (pid);
5728 proc_id = FLOATP (pid) ? XFLOAT_DATA (pid) : XINT (pid);
5730 h_snapshot = create_toolhelp32_snapshot (TH32CS_SNAPPROCESS, 0);
5732 GCPRO3 (attrs, decoded_cmd, tem);
5734 if (h_snapshot != INVALID_HANDLE_VALUE)
5736 PROCESSENTRY32 pe;
5737 BOOL res;
5739 pe.dwSize = sizeof (PROCESSENTRY32);
5740 for (res = process32_first (h_snapshot, &pe); res;
5741 res = process32_next (h_snapshot, &pe))
5743 if (proc_id == pe.th32ProcessID)
5745 if (proc_id == 0)
5746 decoded_cmd = build_string ("Idle");
5747 else
5749 /* Decode the command name from locale-specific
5750 encoding. */
5751 cmd_str = make_unibyte_string (pe.szExeFile,
5752 strlen (pe.szExeFile));
5753 decoded_cmd =
5754 code_convert_string_norecord (cmd_str,
5755 Vlocale_coding_system, 0);
5757 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
5758 attrs = Fcons (Fcons (Qppid,
5759 make_fixnum_or_float (pe.th32ParentProcessID)),
5760 attrs);
5761 attrs = Fcons (Fcons (Qpri, make_number (pe.pcPriClassBase)),
5762 attrs);
5763 attrs = Fcons (Fcons (Qthcount,
5764 make_fixnum_or_float (pe.cntThreads)),
5765 attrs);
5766 found_proc = 1;
5767 break;
5771 CloseHandle (h_snapshot);
5774 if (!found_proc)
5776 UNGCPRO;
5777 return Qnil;
5780 h_proc = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
5781 FALSE, proc_id);
5782 /* If we were denied a handle to the process, try again after
5783 enabling the SeDebugPrivilege in our process. */
5784 if (!h_proc)
5786 TOKEN_PRIVILEGES priv_current;
5788 if (enable_privilege (SE_DEBUG_NAME, TRUE, &priv_current))
5790 h_proc = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
5791 FALSE, proc_id);
5792 restore_privilege (&priv_current);
5793 revert_to_self ();
5796 if (h_proc)
5798 result = open_process_token (h_proc, TOKEN_QUERY, &token);
5799 if (result)
5801 result = get_token_information (token, TokenUser, NULL, 0, &blen);
5802 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
5804 buf = xmalloc (blen);
5805 result = get_token_information (token, TokenUser,
5806 (LPVOID)buf, blen, &needed);
5807 if (result)
5809 memcpy (&user_token, buf, sizeof (user_token));
5810 if (!w32_cached_id (user_token.User.Sid, &euid, uname))
5812 euid = get_rid (user_token.User.Sid);
5813 result = lookup_account_sid (NULL, user_token.User.Sid,
5814 uname, &ulength,
5815 domain, &dlength,
5816 &user_type);
5817 if (result)
5818 w32_add_to_cache (user_token.User.Sid, euid, uname);
5819 else
5821 strcpy (uname, "unknown");
5822 result = TRUE;
5825 ulength = strlen (uname);
5829 if (result)
5831 /* Determine a reasonable euid and gid values. */
5832 if (xstrcasecmp ("administrator", uname) == 0)
5834 euid = 500; /* well-known Administrator uid */
5835 egid = 513; /* well-known None gid */
5837 else
5839 /* Get group id and name. */
5840 result = get_token_information (token, TokenPrimaryGroup,
5841 (LPVOID)buf, blen, &needed);
5842 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
5844 buf = xrealloc (buf, blen = needed);
5845 result = get_token_information (token, TokenPrimaryGroup,
5846 (LPVOID)buf, blen, &needed);
5848 if (result)
5850 memcpy (&group_token, buf, sizeof (group_token));
5851 if (!w32_cached_id (group_token.PrimaryGroup, &egid, gname))
5853 egid = get_rid (group_token.PrimaryGroup);
5854 dlength = sizeof (domain);
5855 result =
5856 lookup_account_sid (NULL, group_token.PrimaryGroup,
5857 gname, &glength, NULL, &dlength,
5858 &user_type);
5859 if (result)
5860 w32_add_to_cache (group_token.PrimaryGroup,
5861 egid, gname);
5862 else
5864 strcpy (gname, "None");
5865 result = TRUE;
5868 glength = strlen (gname);
5872 xfree (buf);
5874 if (!result)
5876 if (!is_windows_9x ())
5878 /* We couldn't open the process token, presumably because of
5879 insufficient access rights. Assume this process is run
5880 by the system. */
5881 strcpy (uname, "SYSTEM");
5882 strcpy (gname, "None");
5883 euid = 18; /* SYSTEM */
5884 egid = 513; /* None */
5885 glength = strlen (gname);
5886 ulength = strlen (uname);
5888 /* If we are running under Windows 9X, where security calls are
5889 not supported, we assume all processes are run by the current
5890 user. */
5891 else if (GetUserName (uname, &ulength))
5893 if (xstrcasecmp ("administrator", uname) == 0)
5894 euid = 0;
5895 else
5896 euid = 123;
5897 egid = euid;
5898 strcpy (gname, "None");
5899 glength = strlen (gname);
5900 ulength = strlen (uname);
5902 else
5904 euid = 123;
5905 egid = 123;
5906 strcpy (uname, "administrator");
5907 ulength = strlen (uname);
5908 strcpy (gname, "None");
5909 glength = strlen (gname);
5911 if (token)
5912 CloseHandle (token);
5915 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (euid)), attrs);
5916 tem = make_unibyte_string (uname, ulength);
5917 attrs = Fcons (Fcons (Quser,
5918 code_convert_string_norecord (tem, Vlocale_coding_system, 0)),
5919 attrs);
5920 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (egid)), attrs);
5921 tem = make_unibyte_string (gname, glength);
5922 attrs = Fcons (Fcons (Qgroup,
5923 code_convert_string_norecord (tem, Vlocale_coding_system, 0)),
5924 attrs);
5926 if (global_memory_status_ex (&memstex))
5927 #if __GNUC__ || (defined (_MSC_VER) && _MSC_VER >= 1300)
5928 totphys = memstex.ullTotalPhys / 1024.0;
5929 #else
5930 /* Visual Studio 6 cannot convert an unsigned __int64 type to
5931 double, so we need to do this for it... */
5933 DWORD tot_hi = memstex.ullTotalPhys >> 32;
5934 DWORD tot_md = (memstex.ullTotalPhys & 0x00000000ffffffff) >> 10;
5935 DWORD tot_lo = memstex.ullTotalPhys % 1024;
5937 totphys = tot_hi * 4194304.0 + tot_md + tot_lo / 1024.0;
5939 #endif /* __GNUC__ || _MSC_VER >= 1300 */
5940 else if (global_memory_status (&memst))
5941 totphys = memst.dwTotalPhys / 1024.0;
5943 if (h_proc
5944 && get_process_memory_info (h_proc, (PROCESS_MEMORY_COUNTERS *)&mem_ex,
5945 sizeof (mem_ex)))
5947 SIZE_T rss = mem_ex.WorkingSetSize / 1024;
5949 attrs = Fcons (Fcons (Qmajflt,
5950 make_fixnum_or_float (mem_ex.PageFaultCount)),
5951 attrs);
5952 attrs = Fcons (Fcons (Qvsize,
5953 make_fixnum_or_float (mem_ex.PrivateUsage / 1024)),
5954 attrs);
5955 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (rss)), attrs);
5956 if (totphys)
5957 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
5959 else if (h_proc
5960 && get_process_memory_info (h_proc, &mem, sizeof (mem)))
5962 SIZE_T rss = mem_ex.WorkingSetSize / 1024;
5964 attrs = Fcons (Fcons (Qmajflt,
5965 make_fixnum_or_float (mem.PageFaultCount)),
5966 attrs);
5967 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (rss)), attrs);
5968 if (totphys)
5969 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
5971 else if (h_proc
5972 && get_process_working_set_size (h_proc, &minrss, &maxrss))
5974 DWORD rss = maxrss / 1024;
5976 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (maxrss / 1024)), attrs);
5977 if (totphys)
5978 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
5981 if (process_times (h_proc, &ctime, &etime, &stime, &utime, &ttime, &pcpu))
5983 attrs = Fcons (Fcons (Qutime, utime), attrs);
5984 attrs = Fcons (Fcons (Qstime, stime), attrs);
5985 attrs = Fcons (Fcons (Qtime, ttime), attrs);
5986 attrs = Fcons (Fcons (Qstart, ctime), attrs);
5987 attrs = Fcons (Fcons (Qetime, etime), attrs);
5988 attrs = Fcons (Fcons (Qpcpu, make_float (pcpu)), attrs);
5991 /* FIXME: Retrieve command line by walking the PEB of the process. */
5993 if (h_proc)
5994 CloseHandle (h_proc);
5995 UNGCPRO;
5996 return attrs;
6000 /* Wrappers for winsock functions to map between our file descriptors
6001 and winsock's handles; also set h_errno for convenience.
6003 To allow Emacs to run on systems which don't have winsock support
6004 installed, we dynamically link to winsock on startup if present, and
6005 otherwise provide the minimum necessary functionality
6006 (eg. gethostname). */
6008 /* function pointers for relevant socket functions */
6009 int (PASCAL *pfn_WSAStartup) (WORD wVersionRequired, LPWSADATA lpWSAData);
6010 void (PASCAL *pfn_WSASetLastError) (int iError);
6011 int (PASCAL *pfn_WSAGetLastError) (void);
6012 int (PASCAL *pfn_WSAEventSelect) (SOCKET s, HANDLE hEventObject, long lNetworkEvents);
6013 HANDLE (PASCAL *pfn_WSACreateEvent) (void);
6014 int (PASCAL *pfn_WSACloseEvent) (HANDLE hEvent);
6015 int (PASCAL *pfn_socket) (int af, int type, int protocol);
6016 int (PASCAL *pfn_bind) (SOCKET s, const struct sockaddr *addr, int namelen);
6017 int (PASCAL *pfn_connect) (SOCKET s, const struct sockaddr *addr, int namelen);
6018 int (PASCAL *pfn_ioctlsocket) (SOCKET s, long cmd, u_long *argp);
6019 int (PASCAL *pfn_recv) (SOCKET s, char * buf, int len, int flags);
6020 int (PASCAL *pfn_send) (SOCKET s, const char * buf, int len, int flags);
6021 int (PASCAL *pfn_closesocket) (SOCKET s);
6022 int (PASCAL *pfn_shutdown) (SOCKET s, int how);
6023 int (PASCAL *pfn_WSACleanup) (void);
6025 u_short (PASCAL *pfn_htons) (u_short hostshort);
6026 u_short (PASCAL *pfn_ntohs) (u_short netshort);
6027 unsigned long (PASCAL *pfn_inet_addr) (const char * cp);
6028 int (PASCAL *pfn_gethostname) (char * name, int namelen);
6029 struct hostent * (PASCAL *pfn_gethostbyname) (const char * name);
6030 struct servent * (PASCAL *pfn_getservbyname) (const char * name, const char * proto);
6031 int (PASCAL *pfn_getpeername) (SOCKET s, struct sockaddr *addr, int * namelen);
6032 int (PASCAL *pfn_setsockopt) (SOCKET s, int level, int optname,
6033 const char * optval, int optlen);
6034 int (PASCAL *pfn_listen) (SOCKET s, int backlog);
6035 int (PASCAL *pfn_getsockname) (SOCKET s, struct sockaddr * name,
6036 int * namelen);
6037 SOCKET (PASCAL *pfn_accept) (SOCKET s, struct sockaddr * addr, int * addrlen);
6038 int (PASCAL *pfn_recvfrom) (SOCKET s, char * buf, int len, int flags,
6039 struct sockaddr * from, int * fromlen);
6040 int (PASCAL *pfn_sendto) (SOCKET s, const char * buf, int len, int flags,
6041 const struct sockaddr * to, int tolen);
6043 /* SetHandleInformation is only needed to make sockets non-inheritable. */
6044 BOOL (WINAPI *pfn_SetHandleInformation) (HANDLE object, DWORD mask, DWORD flags);
6045 #ifndef HANDLE_FLAG_INHERIT
6046 #define HANDLE_FLAG_INHERIT 1
6047 #endif
6049 HANDLE winsock_lib;
6050 static int winsock_inuse;
6052 BOOL
6053 term_winsock (void)
6055 if (winsock_lib != NULL && winsock_inuse == 0)
6057 /* Not sure what would cause WSAENETDOWN, or even if it can happen
6058 after WSAStartup returns successfully, but it seems reasonable
6059 to allow unloading winsock anyway in that case. */
6060 if (pfn_WSACleanup () == 0 ||
6061 pfn_WSAGetLastError () == WSAENETDOWN)
6063 if (FreeLibrary (winsock_lib))
6064 winsock_lib = NULL;
6065 return TRUE;
6068 return FALSE;
6071 BOOL
6072 init_winsock (int load_now)
6074 WSADATA winsockData;
6076 if (winsock_lib != NULL)
6077 return TRUE;
6079 pfn_SetHandleInformation
6080 = (void *) GetProcAddress (GetModuleHandle ("kernel32.dll"),
6081 "SetHandleInformation");
6083 winsock_lib = LoadLibrary ("Ws2_32.dll");
6085 if (winsock_lib != NULL)
6087 /* dynamically link to socket functions */
6089 #define LOAD_PROC(fn) \
6090 if ((pfn_##fn = (void *) GetProcAddress (winsock_lib, #fn)) == NULL) \
6091 goto fail;
6093 LOAD_PROC (WSAStartup);
6094 LOAD_PROC (WSASetLastError);
6095 LOAD_PROC (WSAGetLastError);
6096 LOAD_PROC (WSAEventSelect);
6097 LOAD_PROC (WSACreateEvent);
6098 LOAD_PROC (WSACloseEvent);
6099 LOAD_PROC (socket);
6100 LOAD_PROC (bind);
6101 LOAD_PROC (connect);
6102 LOAD_PROC (ioctlsocket);
6103 LOAD_PROC (recv);
6104 LOAD_PROC (send);
6105 LOAD_PROC (closesocket);
6106 LOAD_PROC (shutdown);
6107 LOAD_PROC (htons);
6108 LOAD_PROC (ntohs);
6109 LOAD_PROC (inet_addr);
6110 LOAD_PROC (gethostname);
6111 LOAD_PROC (gethostbyname);
6112 LOAD_PROC (getservbyname);
6113 LOAD_PROC (getpeername);
6114 LOAD_PROC (WSACleanup);
6115 LOAD_PROC (setsockopt);
6116 LOAD_PROC (listen);
6117 LOAD_PROC (getsockname);
6118 LOAD_PROC (accept);
6119 LOAD_PROC (recvfrom);
6120 LOAD_PROC (sendto);
6121 #undef LOAD_PROC
6123 /* specify version 1.1 of winsock */
6124 if (pfn_WSAStartup (0x101, &winsockData) == 0)
6126 if (winsockData.wVersion != 0x101)
6127 goto fail;
6129 if (!load_now)
6131 /* Report that winsock exists and is usable, but leave
6132 socket functions disabled. I am assuming that calling
6133 WSAStartup does not require any network interaction,
6134 and in particular does not cause or require a dial-up
6135 connection to be established. */
6137 pfn_WSACleanup ();
6138 FreeLibrary (winsock_lib);
6139 winsock_lib = NULL;
6141 winsock_inuse = 0;
6142 return TRUE;
6145 fail:
6146 FreeLibrary (winsock_lib);
6147 winsock_lib = NULL;
6150 return FALSE;
6154 int h_errno = 0;
6156 /* Function to map winsock error codes to errno codes for those errno
6157 code defined in errno.h (errno values not defined by errno.h are
6158 already in nt/inc/sys/socket.h). */
6159 static void
6160 set_errno (void)
6162 int wsa_err;
6164 h_errno = 0;
6165 if (winsock_lib == NULL)
6166 wsa_err = EINVAL;
6167 else
6168 wsa_err = pfn_WSAGetLastError ();
6170 switch (wsa_err)
6172 case WSAEACCES: errno = EACCES; break;
6173 case WSAEBADF: errno = EBADF; break;
6174 case WSAEFAULT: errno = EFAULT; break;
6175 case WSAEINTR: errno = EINTR; break;
6176 case WSAEINVAL: errno = EINVAL; break;
6177 case WSAEMFILE: errno = EMFILE; break;
6178 case WSAENAMETOOLONG: errno = ENAMETOOLONG; break;
6179 case WSAENOTEMPTY: errno = ENOTEMPTY; break;
6180 default: errno = wsa_err; break;
6184 static void
6185 check_errno (void)
6187 h_errno = 0;
6188 if (winsock_lib != NULL)
6189 pfn_WSASetLastError (0);
6192 /* Extend strerror to handle the winsock-specific error codes. */
6193 struct {
6194 int errnum;
6195 char * msg;
6196 } _wsa_errlist[] = {
6197 {WSAEINTR , "Interrupted function call"},
6198 {WSAEBADF , "Bad file descriptor"},
6199 {WSAEACCES , "Permission denied"},
6200 {WSAEFAULT , "Bad address"},
6201 {WSAEINVAL , "Invalid argument"},
6202 {WSAEMFILE , "Too many open files"},
6204 {WSAEWOULDBLOCK , "Resource temporarily unavailable"},
6205 {WSAEINPROGRESS , "Operation now in progress"},
6206 {WSAEALREADY , "Operation already in progress"},
6207 {WSAENOTSOCK , "Socket operation on non-socket"},
6208 {WSAEDESTADDRREQ , "Destination address required"},
6209 {WSAEMSGSIZE , "Message too long"},
6210 {WSAEPROTOTYPE , "Protocol wrong type for socket"},
6211 {WSAENOPROTOOPT , "Bad protocol option"},
6212 {WSAEPROTONOSUPPORT , "Protocol not supported"},
6213 {WSAESOCKTNOSUPPORT , "Socket type not supported"},
6214 {WSAEOPNOTSUPP , "Operation not supported"},
6215 {WSAEPFNOSUPPORT , "Protocol family not supported"},
6216 {WSAEAFNOSUPPORT , "Address family not supported by protocol family"},
6217 {WSAEADDRINUSE , "Address already in use"},
6218 {WSAEADDRNOTAVAIL , "Cannot assign requested address"},
6219 {WSAENETDOWN , "Network is down"},
6220 {WSAENETUNREACH , "Network is unreachable"},
6221 {WSAENETRESET , "Network dropped connection on reset"},
6222 {WSAECONNABORTED , "Software caused connection abort"},
6223 {WSAECONNRESET , "Connection reset by peer"},
6224 {WSAENOBUFS , "No buffer space available"},
6225 {WSAEISCONN , "Socket is already connected"},
6226 {WSAENOTCONN , "Socket is not connected"},
6227 {WSAESHUTDOWN , "Cannot send after socket shutdown"},
6228 {WSAETOOMANYREFS , "Too many references"}, /* not sure */
6229 {WSAETIMEDOUT , "Connection timed out"},
6230 {WSAECONNREFUSED , "Connection refused"},
6231 {WSAELOOP , "Network loop"}, /* not sure */
6232 {WSAENAMETOOLONG , "Name is too long"},
6233 {WSAEHOSTDOWN , "Host is down"},
6234 {WSAEHOSTUNREACH , "No route to host"},
6235 {WSAENOTEMPTY , "Buffer not empty"}, /* not sure */
6236 {WSAEPROCLIM , "Too many processes"},
6237 {WSAEUSERS , "Too many users"}, /* not sure */
6238 {WSAEDQUOT , "Double quote in host name"}, /* really not sure */
6239 {WSAESTALE , "Data is stale"}, /* not sure */
6240 {WSAEREMOTE , "Remote error"}, /* not sure */
6242 {WSASYSNOTREADY , "Network subsystem is unavailable"},
6243 {WSAVERNOTSUPPORTED , "WINSOCK.DLL version out of range"},
6244 {WSANOTINITIALISED , "Winsock not initialized successfully"},
6245 {WSAEDISCON , "Graceful shutdown in progress"},
6246 #ifdef WSAENOMORE
6247 {WSAENOMORE , "No more operations allowed"}, /* not sure */
6248 {WSAECANCELLED , "Operation cancelled"}, /* not sure */
6249 {WSAEINVALIDPROCTABLE , "Invalid procedure table from service provider"},
6250 {WSAEINVALIDPROVIDER , "Invalid service provider version number"},
6251 {WSAEPROVIDERFAILEDINIT , "Unable to initialize a service provider"},
6252 {WSASYSCALLFAILURE , "System call failure"},
6253 {WSASERVICE_NOT_FOUND , "Service not found"}, /* not sure */
6254 {WSATYPE_NOT_FOUND , "Class type not found"},
6255 {WSA_E_NO_MORE , "No more resources available"}, /* really not sure */
6256 {WSA_E_CANCELLED , "Operation already cancelled"}, /* really not sure */
6257 {WSAEREFUSED , "Operation refused"}, /* not sure */
6258 #endif
6260 {WSAHOST_NOT_FOUND , "Host not found"},
6261 {WSATRY_AGAIN , "Authoritative host not found during name lookup"},
6262 {WSANO_RECOVERY , "Non-recoverable error during name lookup"},
6263 {WSANO_DATA , "Valid name, no data record of requested type"},
6265 {-1, NULL}
6268 char *
6269 sys_strerror (int error_no)
6271 int i;
6272 static char unknown_msg[40];
6274 if (error_no >= 0 && error_no < sys_nerr)
6275 return sys_errlist[error_no];
6277 for (i = 0; _wsa_errlist[i].errnum >= 0; i++)
6278 if (_wsa_errlist[i].errnum == error_no)
6279 return _wsa_errlist[i].msg;
6281 sprintf (unknown_msg, "Unidentified error: %d", error_no);
6282 return unknown_msg;
6285 /* [andrewi 3-May-96] I've had conflicting results using both methods,
6286 but I believe the method of keeping the socket handle separate (and
6287 insuring it is not inheritable) is the correct one. */
6289 #define SOCK_HANDLE(fd) ((SOCKET) fd_info[fd].hnd)
6291 static int socket_to_fd (SOCKET s);
6294 sys_socket (int af, int type, int protocol)
6296 SOCKET s;
6298 if (winsock_lib == NULL)
6300 errno = ENETDOWN;
6301 return INVALID_SOCKET;
6304 check_errno ();
6306 /* call the real socket function */
6307 s = pfn_socket (af, type, protocol);
6309 if (s != INVALID_SOCKET)
6310 return socket_to_fd (s);
6312 set_errno ();
6313 return -1;
6316 /* Convert a SOCKET to a file descriptor. */
6317 static int
6318 socket_to_fd (SOCKET s)
6320 int fd;
6321 child_process * cp;
6323 /* Although under NT 3.5 _open_osfhandle will accept a socket
6324 handle, if opened with SO_OPENTYPE == SO_SYNCHRONOUS_NONALERT,
6325 that does not work under NT 3.1. However, we can get the same
6326 effect by using a backdoor function to replace an existing
6327 descriptor handle with the one we want. */
6329 /* allocate a file descriptor (with appropriate flags) */
6330 fd = _open ("NUL:", _O_RDWR);
6331 if (fd >= 0)
6333 /* Make a non-inheritable copy of the socket handle. Note
6334 that it is possible that sockets aren't actually kernel
6335 handles, which appears to be the case on Windows 9x when
6336 the MS Proxy winsock client is installed. */
6338 /* Apparently there is a bug in NT 3.51 with some service
6339 packs, which prevents using DuplicateHandle to make a
6340 socket handle non-inheritable (causes WSACleanup to
6341 hang). The work-around is to use SetHandleInformation
6342 instead if it is available and implemented. */
6343 if (pfn_SetHandleInformation)
6345 pfn_SetHandleInformation ((HANDLE) s, HANDLE_FLAG_INHERIT, 0);
6347 else
6349 HANDLE parent = GetCurrentProcess ();
6350 HANDLE new_s = INVALID_HANDLE_VALUE;
6352 if (DuplicateHandle (parent,
6353 (HANDLE) s,
6354 parent,
6355 &new_s,
6357 FALSE,
6358 DUPLICATE_SAME_ACCESS))
6360 /* It is possible that DuplicateHandle succeeds even
6361 though the socket wasn't really a kernel handle,
6362 because a real handle has the same value. So
6363 test whether the new handle really is a socket. */
6364 long nonblocking = 0;
6365 if (pfn_ioctlsocket ((SOCKET) new_s, FIONBIO, &nonblocking) == 0)
6367 pfn_closesocket (s);
6368 s = (SOCKET) new_s;
6370 else
6372 CloseHandle (new_s);
6377 eassert (fd < MAXDESC);
6378 fd_info[fd].hnd = (HANDLE) s;
6380 /* set our own internal flags */
6381 fd_info[fd].flags = FILE_SOCKET | FILE_BINARY | FILE_READ | FILE_WRITE;
6383 cp = new_child ();
6384 if (cp)
6386 cp->fd = fd;
6387 cp->status = STATUS_READ_ACKNOWLEDGED;
6389 /* attach child_process to fd_info */
6390 if (fd_info[ fd ].cp != NULL)
6392 DebPrint (("sys_socket: fd_info[%d] apparently in use!\n", fd));
6393 emacs_abort ();
6396 fd_info[ fd ].cp = cp;
6398 /* success! */
6399 winsock_inuse++; /* count open sockets */
6400 return fd;
6403 /* clean up */
6404 _close (fd);
6406 else
6407 pfn_closesocket (s);
6408 errno = EMFILE;
6409 return -1;
6413 sys_bind (int s, const struct sockaddr * addr, int namelen)
6415 if (winsock_lib == NULL)
6417 errno = ENOTSOCK;
6418 return SOCKET_ERROR;
6421 check_errno ();
6422 if (fd_info[s].flags & FILE_SOCKET)
6424 int rc = pfn_bind (SOCK_HANDLE (s), addr, namelen);
6425 if (rc == SOCKET_ERROR)
6426 set_errno ();
6427 return rc;
6429 errno = ENOTSOCK;
6430 return SOCKET_ERROR;
6434 sys_connect (int s, const struct sockaddr * name, int namelen)
6436 if (winsock_lib == NULL)
6438 errno = ENOTSOCK;
6439 return SOCKET_ERROR;
6442 check_errno ();
6443 if (fd_info[s].flags & FILE_SOCKET)
6445 int rc = pfn_connect (SOCK_HANDLE (s), name, namelen);
6446 if (rc == SOCKET_ERROR)
6447 set_errno ();
6448 return rc;
6450 errno = ENOTSOCK;
6451 return SOCKET_ERROR;
6454 u_short
6455 sys_htons (u_short hostshort)
6457 return (winsock_lib != NULL) ?
6458 pfn_htons (hostshort) : hostshort;
6461 u_short
6462 sys_ntohs (u_short netshort)
6464 return (winsock_lib != NULL) ?
6465 pfn_ntohs (netshort) : netshort;
6468 unsigned long
6469 sys_inet_addr (const char * cp)
6471 return (winsock_lib != NULL) ?
6472 pfn_inet_addr (cp) : INADDR_NONE;
6476 sys_gethostname (char * name, int namelen)
6478 if (winsock_lib != NULL)
6480 int retval;
6482 check_errno ();
6483 retval = pfn_gethostname (name, namelen);
6484 if (retval == SOCKET_ERROR)
6485 set_errno ();
6486 return retval;
6489 if (namelen > MAX_COMPUTERNAME_LENGTH)
6490 return !GetComputerName (name, (DWORD *)&namelen);
6492 errno = EFAULT;
6493 return SOCKET_ERROR;
6496 struct hostent *
6497 sys_gethostbyname (const char * name)
6499 struct hostent * host;
6500 int h_err = h_errno;
6502 if (winsock_lib == NULL)
6504 h_errno = NO_RECOVERY;
6505 errno = ENETDOWN;
6506 return NULL;
6509 check_errno ();
6510 host = pfn_gethostbyname (name);
6511 if (!host)
6513 set_errno ();
6514 h_errno = errno;
6516 else
6517 h_errno = h_err;
6518 return host;
6521 struct servent *
6522 sys_getservbyname (const char * name, const char * proto)
6524 struct servent * serv;
6526 if (winsock_lib == NULL)
6528 errno = ENETDOWN;
6529 return NULL;
6532 check_errno ();
6533 serv = pfn_getservbyname (name, proto);
6534 if (!serv)
6535 set_errno ();
6536 return serv;
6540 sys_getpeername (int s, struct sockaddr *addr, int * namelen)
6542 if (winsock_lib == NULL)
6544 errno = ENETDOWN;
6545 return SOCKET_ERROR;
6548 check_errno ();
6549 if (fd_info[s].flags & FILE_SOCKET)
6551 int rc = pfn_getpeername (SOCK_HANDLE (s), addr, namelen);
6552 if (rc == SOCKET_ERROR)
6553 set_errno ();
6554 return rc;
6556 errno = ENOTSOCK;
6557 return SOCKET_ERROR;
6561 sys_shutdown (int s, int how)
6563 if (winsock_lib == NULL)
6565 errno = ENETDOWN;
6566 return SOCKET_ERROR;
6569 check_errno ();
6570 if (fd_info[s].flags & FILE_SOCKET)
6572 int rc = pfn_shutdown (SOCK_HANDLE (s), how);
6573 if (rc == SOCKET_ERROR)
6574 set_errno ();
6575 return rc;
6577 errno = ENOTSOCK;
6578 return SOCKET_ERROR;
6582 sys_setsockopt (int s, int level, int optname, const void * optval, int optlen)
6584 if (winsock_lib == NULL)
6586 errno = ENETDOWN;
6587 return SOCKET_ERROR;
6590 check_errno ();
6591 if (fd_info[s].flags & FILE_SOCKET)
6593 int rc = pfn_setsockopt (SOCK_HANDLE (s), level, optname,
6594 (const char *)optval, optlen);
6595 if (rc == SOCKET_ERROR)
6596 set_errno ();
6597 return rc;
6599 errno = ENOTSOCK;
6600 return SOCKET_ERROR;
6604 sys_listen (int s, int backlog)
6606 if (winsock_lib == NULL)
6608 errno = ENETDOWN;
6609 return SOCKET_ERROR;
6612 check_errno ();
6613 if (fd_info[s].flags & FILE_SOCKET)
6615 int rc = pfn_listen (SOCK_HANDLE (s), backlog);
6616 if (rc == SOCKET_ERROR)
6617 set_errno ();
6618 else
6619 fd_info[s].flags |= FILE_LISTEN;
6620 return rc;
6622 errno = ENOTSOCK;
6623 return SOCKET_ERROR;
6627 sys_getsockname (int s, struct sockaddr * name, int * namelen)
6629 if (winsock_lib == NULL)
6631 errno = ENETDOWN;
6632 return SOCKET_ERROR;
6635 check_errno ();
6636 if (fd_info[s].flags & FILE_SOCKET)
6638 int rc = pfn_getsockname (SOCK_HANDLE (s), name, namelen);
6639 if (rc == SOCKET_ERROR)
6640 set_errno ();
6641 return rc;
6643 errno = ENOTSOCK;
6644 return SOCKET_ERROR;
6648 sys_accept (int s, struct sockaddr * addr, int * addrlen)
6650 if (winsock_lib == NULL)
6652 errno = ENETDOWN;
6653 return -1;
6656 check_errno ();
6657 if (fd_info[s].flags & FILE_LISTEN)
6659 SOCKET t = pfn_accept (SOCK_HANDLE (s), addr, addrlen);
6660 int fd = -1;
6661 if (t == INVALID_SOCKET)
6662 set_errno ();
6663 else
6664 fd = socket_to_fd (t);
6666 if (fd >= 0)
6668 fd_info[s].cp->status = STATUS_READ_ACKNOWLEDGED;
6669 ResetEvent (fd_info[s].cp->char_avail);
6671 return fd;
6673 errno = ENOTSOCK;
6674 return -1;
6678 sys_recvfrom (int s, char * buf, int len, int flags,
6679 struct sockaddr * from, int * fromlen)
6681 if (winsock_lib == NULL)
6683 errno = ENETDOWN;
6684 return SOCKET_ERROR;
6687 check_errno ();
6688 if (fd_info[s].flags & FILE_SOCKET)
6690 int rc = pfn_recvfrom (SOCK_HANDLE (s), buf, len, flags, from, fromlen);
6691 if (rc == SOCKET_ERROR)
6692 set_errno ();
6693 return rc;
6695 errno = ENOTSOCK;
6696 return SOCKET_ERROR;
6700 sys_sendto (int s, const char * buf, int len, int flags,
6701 const struct sockaddr * to, int tolen)
6703 if (winsock_lib == NULL)
6705 errno = ENETDOWN;
6706 return SOCKET_ERROR;
6709 check_errno ();
6710 if (fd_info[s].flags & FILE_SOCKET)
6712 int rc = pfn_sendto (SOCK_HANDLE (s), buf, len, flags, to, tolen);
6713 if (rc == SOCKET_ERROR)
6714 set_errno ();
6715 return rc;
6717 errno = ENOTSOCK;
6718 return SOCKET_ERROR;
6721 /* Windows does not have an fcntl function. Provide an implementation
6722 solely for making sockets non-blocking. */
6724 fcntl (int s, int cmd, int options)
6726 if (winsock_lib == NULL)
6728 errno = ENETDOWN;
6729 return -1;
6732 check_errno ();
6733 if (fd_info[s].flags & FILE_SOCKET)
6735 if (cmd == F_SETFL && options == O_NONBLOCK)
6737 unsigned long nblock = 1;
6738 int rc = pfn_ioctlsocket (SOCK_HANDLE (s), FIONBIO, &nblock);
6739 if (rc == SOCKET_ERROR)
6740 set_errno ();
6741 /* Keep track of the fact that we set this to non-blocking. */
6742 fd_info[s].flags |= FILE_NDELAY;
6743 return rc;
6745 else
6747 errno = EINVAL;
6748 return SOCKET_ERROR;
6751 errno = ENOTSOCK;
6752 return SOCKET_ERROR;
6756 /* Shadow main io functions: we need to handle pipes and sockets more
6757 intelligently, and implement non-blocking mode as well. */
6760 sys_close (int fd)
6762 int rc;
6764 if (fd < 0)
6766 errno = EBADF;
6767 return -1;
6770 if (fd < MAXDESC && fd_info[fd].cp)
6772 child_process * cp = fd_info[fd].cp;
6774 fd_info[fd].cp = NULL;
6776 if (CHILD_ACTIVE (cp))
6778 /* if last descriptor to active child_process then cleanup */
6779 int i;
6780 for (i = 0; i < MAXDESC; i++)
6782 if (i == fd)
6783 continue;
6784 if (fd_info[i].cp == cp)
6785 break;
6787 if (i == MAXDESC)
6789 if (fd_info[fd].flags & FILE_SOCKET)
6791 if (winsock_lib == NULL) emacs_abort ();
6793 pfn_shutdown (SOCK_HANDLE (fd), 2);
6794 rc = pfn_closesocket (SOCK_HANDLE (fd));
6796 winsock_inuse--; /* count open sockets */
6798 /* If the process handle is NULL, it's either a socket
6799 or serial connection, or a subprocess that was
6800 already reaped by reap_subprocess, but whose
6801 resources were not yet freed, because its output was
6802 not fully read yet by the time it was reaped. (This
6803 usually happens with async subprocesses whose output
6804 is being read by Emacs.) Otherwise, this process was
6805 not reaped yet, so we set its FD to a negative value
6806 to make sure sys_select will eventually get to
6807 calling the SIGCHLD handler for it, which will then
6808 invoke waitpid and reap_subprocess. */
6809 if (cp->procinfo.hProcess == NULL)
6810 delete_child (cp);
6811 else
6812 cp->fd = -1;
6817 if (fd >= 0 && fd < MAXDESC)
6818 fd_info[fd].flags = 0;
6820 /* Note that sockets do not need special treatment here (at least on
6821 NT and Windows 95 using the standard tcp/ip stacks) - it appears that
6822 closesocket is equivalent to CloseHandle, which is to be expected
6823 because socket handles are fully fledged kernel handles. */
6824 rc = _close (fd);
6826 return rc;
6830 sys_dup (int fd)
6832 int new_fd;
6834 new_fd = _dup (fd);
6835 if (new_fd >= 0 && new_fd < MAXDESC)
6837 /* duplicate our internal info as well */
6838 fd_info[new_fd] = fd_info[fd];
6840 return new_fd;
6844 sys_dup2 (int src, int dst)
6846 int rc;
6848 if (dst < 0 || dst >= MAXDESC)
6850 errno = EBADF;
6851 return -1;
6854 /* make sure we close the destination first if it's a pipe or socket */
6855 if (src != dst && fd_info[dst].flags != 0)
6856 sys_close (dst);
6858 rc = _dup2 (src, dst);
6859 if (rc == 0)
6861 /* duplicate our internal info as well */
6862 fd_info[dst] = fd_info[src];
6864 return rc;
6867 /* Unix pipe() has only one arg */
6869 sys_pipe (int * phandles)
6871 int rc;
6872 unsigned flags;
6874 /* make pipe handles non-inheritable; when we spawn a child, we
6875 replace the relevant handle with an inheritable one. Also put
6876 pipes into binary mode; we will do text mode translation ourselves
6877 if required. */
6878 rc = _pipe (phandles, 0, _O_NOINHERIT | _O_BINARY);
6880 if (rc == 0)
6882 /* Protect against overflow, since Windows can open more handles than
6883 our fd_info array has room for. */
6884 if (phandles[0] >= MAXDESC || phandles[1] >= MAXDESC)
6886 _close (phandles[0]);
6887 _close (phandles[1]);
6888 errno = EMFILE;
6889 rc = -1;
6891 else
6893 flags = FILE_PIPE | FILE_READ | FILE_BINARY;
6894 fd_info[phandles[0]].flags = flags;
6896 flags = FILE_PIPE | FILE_WRITE | FILE_BINARY;
6897 fd_info[phandles[1]].flags = flags;
6901 return rc;
6904 /* Function to do blocking read of one byte, needed to implement
6905 select. It is only allowed on communication ports, sockets, or
6906 pipes. */
6908 _sys_read_ahead (int fd)
6910 child_process * cp;
6911 int rc;
6913 if (fd < 0 || fd >= MAXDESC)
6914 return STATUS_READ_ERROR;
6916 cp = fd_info[fd].cp;
6918 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
6919 return STATUS_READ_ERROR;
6921 if ((fd_info[fd].flags & (FILE_PIPE | FILE_SERIAL | FILE_SOCKET)) == 0
6922 || (fd_info[fd].flags & FILE_READ) == 0)
6924 DebPrint (("_sys_read_ahead: internal error: fd %d is not a pipe, serial port, or socket!\n", fd));
6925 emacs_abort ();
6928 cp->status = STATUS_READ_IN_PROGRESS;
6930 if (fd_info[fd].flags & FILE_PIPE)
6932 rc = _read (fd, &cp->chr, sizeof (char));
6934 /* Give subprocess time to buffer some more output for us before
6935 reporting that input is available; we need this because Windows 95
6936 connects DOS programs to pipes by making the pipe appear to be
6937 the normal console stdout - as a result most DOS programs will
6938 write to stdout without buffering, ie. one character at a
6939 time. Even some W32 programs do this - "dir" in a command
6940 shell on NT is very slow if we don't do this. */
6941 if (rc > 0)
6943 int wait = w32_pipe_read_delay;
6945 if (wait > 0)
6946 Sleep (wait);
6947 else if (wait < 0)
6948 while (++wait <= 0)
6949 /* Yield remainder of our time slice, effectively giving a
6950 temporary priority boost to the child process. */
6951 Sleep (0);
6954 else if (fd_info[fd].flags & FILE_SERIAL)
6956 HANDLE hnd = fd_info[fd].hnd;
6957 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_read;
6958 COMMTIMEOUTS ct;
6960 /* Configure timeouts for blocking read. */
6961 if (!GetCommTimeouts (hnd, &ct))
6963 cp->status = STATUS_READ_ERROR;
6964 return STATUS_READ_ERROR;
6966 ct.ReadIntervalTimeout = 0;
6967 ct.ReadTotalTimeoutMultiplier = 0;
6968 ct.ReadTotalTimeoutConstant = 0;
6969 if (!SetCommTimeouts (hnd, &ct))
6971 cp->status = STATUS_READ_ERROR;
6972 return STATUS_READ_ERROR;
6975 if (!ReadFile (hnd, &cp->chr, sizeof (char), (DWORD*) &rc, ovl))
6977 if (GetLastError () != ERROR_IO_PENDING)
6979 cp->status = STATUS_READ_ERROR;
6980 return STATUS_READ_ERROR;
6982 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &rc, TRUE))
6984 cp->status = STATUS_READ_ERROR;
6985 return STATUS_READ_ERROR;
6989 else if (fd_info[fd].flags & FILE_SOCKET)
6991 unsigned long nblock = 0;
6992 /* We always want this to block, so temporarily disable NDELAY. */
6993 if (fd_info[fd].flags & FILE_NDELAY)
6994 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
6996 rc = pfn_recv (SOCK_HANDLE (fd), &cp->chr, sizeof (char), 0);
6998 if (fd_info[fd].flags & FILE_NDELAY)
7000 nblock = 1;
7001 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
7005 if (rc == sizeof (char))
7006 cp->status = STATUS_READ_SUCCEEDED;
7007 else
7008 cp->status = STATUS_READ_FAILED;
7010 return cp->status;
7014 _sys_wait_accept (int fd)
7016 HANDLE hEv;
7017 child_process * cp;
7018 int rc;
7020 if (fd < 0 || fd >= MAXDESC)
7021 return STATUS_READ_ERROR;
7023 cp = fd_info[fd].cp;
7025 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
7026 return STATUS_READ_ERROR;
7028 cp->status = STATUS_READ_FAILED;
7030 hEv = pfn_WSACreateEvent ();
7031 rc = pfn_WSAEventSelect (SOCK_HANDLE (fd), hEv, FD_ACCEPT);
7032 if (rc != SOCKET_ERROR)
7034 rc = WaitForSingleObject (hEv, INFINITE);
7035 pfn_WSAEventSelect (SOCK_HANDLE (fd), NULL, 0);
7036 if (rc == WAIT_OBJECT_0)
7037 cp->status = STATUS_READ_SUCCEEDED;
7039 pfn_WSACloseEvent (hEv);
7041 return cp->status;
7045 sys_read (int fd, char * buffer, unsigned int count)
7047 int nchars;
7048 int to_read;
7049 DWORD waiting;
7050 char * orig_buffer = buffer;
7052 if (fd < 0)
7054 errno = EBADF;
7055 return -1;
7058 if (fd < MAXDESC && fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET | FILE_SERIAL))
7060 child_process *cp = fd_info[fd].cp;
7062 if ((fd_info[fd].flags & FILE_READ) == 0)
7064 errno = EBADF;
7065 return -1;
7068 nchars = 0;
7070 /* re-read CR carried over from last read */
7071 if (fd_info[fd].flags & FILE_LAST_CR)
7073 if (fd_info[fd].flags & FILE_BINARY) emacs_abort ();
7074 *buffer++ = 0x0d;
7075 count--;
7076 nchars++;
7077 fd_info[fd].flags &= ~FILE_LAST_CR;
7080 /* presence of a child_process structure means we are operating in
7081 non-blocking mode - otherwise we just call _read directly.
7082 Note that the child_process structure might be missing because
7083 reap_subprocess has been called; in this case the pipe is
7084 already broken, so calling _read on it is okay. */
7085 if (cp)
7087 int current_status = cp->status;
7089 switch (current_status)
7091 case STATUS_READ_FAILED:
7092 case STATUS_READ_ERROR:
7093 /* report normal EOF if nothing in buffer */
7094 if (nchars <= 0)
7095 fd_info[fd].flags |= FILE_AT_EOF;
7096 return nchars;
7098 case STATUS_READ_READY:
7099 case STATUS_READ_IN_PROGRESS:
7100 DebPrint (("sys_read called when read is in progress\n"));
7101 errno = EWOULDBLOCK;
7102 return -1;
7104 case STATUS_READ_SUCCEEDED:
7105 /* consume read-ahead char */
7106 *buffer++ = cp->chr;
7107 count--;
7108 nchars++;
7109 cp->status = STATUS_READ_ACKNOWLEDGED;
7110 ResetEvent (cp->char_avail);
7112 case STATUS_READ_ACKNOWLEDGED:
7113 break;
7115 default:
7116 DebPrint (("sys_read: bad status %d\n", current_status));
7117 errno = EBADF;
7118 return -1;
7121 if (fd_info[fd].flags & FILE_PIPE)
7123 PeekNamedPipe ((HANDLE) _get_osfhandle (fd), NULL, 0, NULL, &waiting, NULL);
7124 to_read = min (waiting, (DWORD) count);
7126 if (to_read > 0)
7127 nchars += _read (fd, buffer, to_read);
7129 else if (fd_info[fd].flags & FILE_SERIAL)
7131 HANDLE hnd = fd_info[fd].hnd;
7132 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_read;
7133 int rc = 0;
7134 COMMTIMEOUTS ct;
7136 if (count > 0)
7138 /* Configure timeouts for non-blocking read. */
7139 if (!GetCommTimeouts (hnd, &ct))
7141 errno = EIO;
7142 return -1;
7144 ct.ReadIntervalTimeout = MAXDWORD;
7145 ct.ReadTotalTimeoutMultiplier = 0;
7146 ct.ReadTotalTimeoutConstant = 0;
7147 if (!SetCommTimeouts (hnd, &ct))
7149 errno = EIO;
7150 return -1;
7153 if (!ResetEvent (ovl->hEvent))
7155 errno = EIO;
7156 return -1;
7158 if (!ReadFile (hnd, buffer, count, (DWORD*) &rc, ovl))
7160 if (GetLastError () != ERROR_IO_PENDING)
7162 errno = EIO;
7163 return -1;
7165 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &rc, TRUE))
7167 errno = EIO;
7168 return -1;
7171 nchars += rc;
7174 else /* FILE_SOCKET */
7176 if (winsock_lib == NULL) emacs_abort ();
7178 /* do the equivalent of a non-blocking read */
7179 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONREAD, &waiting);
7180 if (waiting == 0 && nchars == 0)
7182 errno = EWOULDBLOCK;
7183 return -1;
7186 if (waiting)
7188 /* always use binary mode for sockets */
7189 int res = pfn_recv (SOCK_HANDLE (fd), buffer, count, 0);
7190 if (res == SOCKET_ERROR)
7192 DebPrint (("sys_read.recv failed with error %d on socket %ld\n",
7193 pfn_WSAGetLastError (), SOCK_HANDLE (fd)));
7194 set_errno ();
7195 return -1;
7197 nchars += res;
7201 else
7203 int nread = _read (fd, buffer, count);
7204 if (nread >= 0)
7205 nchars += nread;
7206 else if (nchars == 0)
7207 nchars = nread;
7210 if (nchars <= 0)
7211 fd_info[fd].flags |= FILE_AT_EOF;
7212 /* Perform text mode translation if required. */
7213 else if ((fd_info[fd].flags & FILE_BINARY) == 0)
7215 nchars = crlf_to_lf (nchars, orig_buffer);
7216 /* If buffer contains only CR, return that. To be absolutely
7217 sure we should attempt to read the next char, but in
7218 practice a CR to be followed by LF would not appear by
7219 itself in the buffer. */
7220 if (nchars > 1 && orig_buffer[nchars - 1] == 0x0d)
7222 fd_info[fd].flags |= FILE_LAST_CR;
7223 nchars--;
7227 else
7228 nchars = _read (fd, buffer, count);
7230 return nchars;
7233 /* From w32xfns.c */
7234 extern HANDLE interrupt_handle;
7236 /* For now, don't bother with a non-blocking mode */
7238 sys_write (int fd, const void * buffer, unsigned int count)
7240 int nchars;
7242 if (fd < 0)
7244 errno = EBADF;
7245 return -1;
7248 if (fd < MAXDESC && fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET | FILE_SERIAL))
7250 if ((fd_info[fd].flags & FILE_WRITE) == 0)
7252 errno = EBADF;
7253 return -1;
7256 /* Perform text mode translation if required. */
7257 if ((fd_info[fd].flags & FILE_BINARY) == 0)
7259 char * tmpbuf = alloca (count * 2);
7260 unsigned char * src = (void *)buffer;
7261 unsigned char * dst = tmpbuf;
7262 int nbytes = count;
7264 while (1)
7266 unsigned char *next;
7267 /* copy next line or remaining bytes */
7268 next = _memccpy (dst, src, '\n', nbytes);
7269 if (next)
7271 /* copied one line ending with '\n' */
7272 int copied = next - dst;
7273 nbytes -= copied;
7274 src += copied;
7275 /* insert '\r' before '\n' */
7276 next[-1] = '\r';
7277 next[0] = '\n';
7278 dst = next + 1;
7279 count++;
7281 else
7282 /* copied remaining partial line -> now finished */
7283 break;
7285 buffer = tmpbuf;
7289 if (fd < MAXDESC && fd_info[fd].flags & FILE_SERIAL)
7291 HANDLE hnd = (HANDLE) _get_osfhandle (fd);
7292 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_write;
7293 HANDLE wait_hnd[2] = { interrupt_handle, ovl->hEvent };
7294 DWORD active = 0;
7296 if (!WriteFile (hnd, buffer, count, (DWORD*) &nchars, ovl))
7298 if (GetLastError () != ERROR_IO_PENDING)
7300 errno = EIO;
7301 return -1;
7303 if (detect_input_pending ())
7304 active = MsgWaitForMultipleObjects (2, wait_hnd, FALSE, INFINITE,
7305 QS_ALLINPUT);
7306 else
7307 active = WaitForMultipleObjects (2, wait_hnd, FALSE, INFINITE);
7308 if (active == WAIT_OBJECT_0)
7309 { /* User pressed C-g, cancel write, then leave. Don't bother
7310 cleaning up as we may only get stuck in buggy drivers. */
7311 PurgeComm (hnd, PURGE_TXABORT | PURGE_TXCLEAR);
7312 CancelIo (hnd);
7313 errno = EIO;
7314 return -1;
7316 if (active == WAIT_OBJECT_0 + 1
7317 && !GetOverlappedResult (hnd, ovl, (DWORD*) &nchars, TRUE))
7319 errno = EIO;
7320 return -1;
7324 else if (fd < MAXDESC && fd_info[fd].flags & FILE_SOCKET)
7326 unsigned long nblock = 0;
7327 if (winsock_lib == NULL) emacs_abort ();
7329 /* TODO: implement select() properly so non-blocking I/O works. */
7330 /* For now, make sure the write blocks. */
7331 if (fd_info[fd].flags & FILE_NDELAY)
7332 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
7334 nchars = pfn_send (SOCK_HANDLE (fd), buffer, count, 0);
7336 /* Set the socket back to non-blocking if it was before,
7337 for other operations that support it. */
7338 if (fd_info[fd].flags & FILE_NDELAY)
7340 nblock = 1;
7341 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
7344 if (nchars == SOCKET_ERROR)
7346 DebPrint (("sys_write.send failed with error %d on socket %ld\n",
7347 pfn_WSAGetLastError (), SOCK_HANDLE (fd)));
7348 set_errno ();
7351 else
7353 /* Some networked filesystems don't like too large writes, so
7354 break them into smaller chunks. See the Comments section of
7355 the MSDN documentation of WriteFile for details behind the
7356 choice of the value of CHUNK below. See also the thread
7357 http://thread.gmane.org/gmane.comp.version-control.git/145294
7358 in the git mailing list. */
7359 const unsigned char *p = buffer;
7360 const unsigned chunk = 30 * 1024 * 1024;
7362 nchars = 0;
7363 while (count > 0)
7365 unsigned this_chunk = count < chunk ? count : chunk;
7366 int n = _write (fd, p, this_chunk);
7368 nchars += n;
7369 if (n < 0)
7371 nchars = n;
7372 break;
7374 else if (n < this_chunk)
7375 break;
7376 count -= n;
7377 p += n;
7381 return nchars;
7384 /* The Windows CRT functions are "optimized for speed", so they don't
7385 check for timezone and DST changes if they were last called less
7386 than 1 minute ago (see http://support.microsoft.com/kb/821231). So
7387 all Emacs features that repeatedly call time functions (e.g.,
7388 display-time) are in real danger of missing timezone and DST
7389 changes. Calling tzset before each localtime call fixes that. */
7390 struct tm *
7391 sys_localtime (const time_t *t)
7393 tzset ();
7394 return localtime (t);
7399 /* Try loading LIBRARY_ID from the file(s) specified in
7400 Vdynamic_library_alist. If the library is loaded successfully,
7401 return the handle of the DLL, and record the filename in the
7402 property :loaded-from of LIBRARY_ID. If the library could not be
7403 found, or when it was already loaded (because the handle is not
7404 recorded anywhere, and so is lost after use), return NULL.
7406 We could also save the handle in :loaded-from, but currently
7407 there's no use case for it. */
7408 HMODULE
7409 w32_delayed_load (Lisp_Object library_id)
7411 HMODULE library_dll = NULL;
7413 CHECK_SYMBOL (library_id);
7415 if (CONSP (Vdynamic_library_alist)
7416 && NILP (Fassq (library_id, Vlibrary_cache)))
7418 Lisp_Object found = Qnil;
7419 Lisp_Object dlls = Fassq (library_id, Vdynamic_library_alist);
7421 if (CONSP (dlls))
7422 for (dlls = XCDR (dlls); CONSP (dlls); dlls = XCDR (dlls))
7424 CHECK_STRING_CAR (dlls);
7425 if ((library_dll = LoadLibrary (SDATA (XCAR (dlls)))))
7427 char name[MAX_PATH];
7428 DWORD len;
7430 len = GetModuleFileNameA (library_dll, name, sizeof (name));
7431 found = Fcons (XCAR (dlls),
7432 (len > 0)
7433 /* Possibly truncated */
7434 ? make_specified_string (name, -1, len, 1)
7435 : Qnil);
7436 break;
7440 Fput (library_id, QCloaded_from, found);
7443 return library_dll;
7447 void
7448 check_windows_init_file (void)
7450 /* A common indication that Emacs is not installed properly is when
7451 it cannot find the Windows installation file. If this file does
7452 not exist in the expected place, tell the user. */
7454 if (!noninteractive && !inhibit_window_system
7455 /* Vload_path is not yet initialized when we are loading
7456 loadup.el. */
7457 && NILP (Vpurify_flag))
7459 Lisp_Object init_file;
7460 int fd;
7462 init_file = build_string ("term/w32-win");
7463 fd = openp (Vload_path, init_file, Fget_load_suffixes (), NULL, Qnil);
7464 if (fd < 0)
7466 Lisp_Object load_path_print = Fprin1_to_string (Vload_path, Qnil);
7467 char *init_file_name = SDATA (init_file);
7468 char *load_path = SDATA (load_path_print);
7469 char *buffer = alloca (1024
7470 + strlen (init_file_name)
7471 + strlen (load_path));
7473 sprintf (buffer,
7474 "The Emacs Windows initialization file \"%s.el\" "
7475 "could not be found in your Emacs installation. "
7476 "Emacs checked the following directories for this file:\n"
7477 "\n%s\n\n"
7478 "When Emacs cannot find this file, it usually means that it "
7479 "was not installed properly, or its distribution file was "
7480 "not unpacked properly.\nSee the README.W32 file in the "
7481 "top-level Emacs directory for more information.",
7482 init_file_name, load_path);
7483 MessageBox (NULL,
7484 buffer,
7485 "Emacs Abort Dialog",
7486 MB_OK | MB_ICONEXCLAMATION | MB_TASKMODAL);
7487 /* Use the low-level system abort. */
7488 abort ();
7490 else
7492 _close (fd);
7497 void
7498 term_ntproc (int ignored)
7500 (void)ignored;
7502 term_timers ();
7504 /* shutdown the socket interface if necessary */
7505 term_winsock ();
7507 term_w32select ();
7510 void
7511 init_ntproc (int dumping)
7513 sigset_t initial_mask = 0;
7515 /* Initialize the socket interface now if available and requested by
7516 the user by defining PRELOAD_WINSOCK; otherwise loading will be
7517 delayed until open-network-stream is called (w32-has-winsock can
7518 also be used to dynamically load or reload winsock).
7520 Conveniently, init_environment is called before us, so
7521 PRELOAD_WINSOCK can be set in the registry. */
7523 /* Always initialize this correctly. */
7524 winsock_lib = NULL;
7526 if (getenv ("PRELOAD_WINSOCK") != NULL)
7527 init_winsock (TRUE);
7529 /* Initial preparation for subprocess support: replace our standard
7530 handles with non-inheritable versions. */
7532 HANDLE parent;
7533 HANDLE stdin_save = INVALID_HANDLE_VALUE;
7534 HANDLE stdout_save = INVALID_HANDLE_VALUE;
7535 HANDLE stderr_save = INVALID_HANDLE_VALUE;
7537 parent = GetCurrentProcess ();
7539 /* ignore errors when duplicating and closing; typically the
7540 handles will be invalid when running as a gui program. */
7541 DuplicateHandle (parent,
7542 GetStdHandle (STD_INPUT_HANDLE),
7543 parent,
7544 &stdin_save,
7546 FALSE,
7547 DUPLICATE_SAME_ACCESS);
7549 DuplicateHandle (parent,
7550 GetStdHandle (STD_OUTPUT_HANDLE),
7551 parent,
7552 &stdout_save,
7554 FALSE,
7555 DUPLICATE_SAME_ACCESS);
7557 DuplicateHandle (parent,
7558 GetStdHandle (STD_ERROR_HANDLE),
7559 parent,
7560 &stderr_save,
7562 FALSE,
7563 DUPLICATE_SAME_ACCESS);
7565 fclose (stdin);
7566 fclose (stdout);
7567 fclose (stderr);
7569 if (stdin_save != INVALID_HANDLE_VALUE)
7570 _open_osfhandle ((intptr_t) stdin_save, O_TEXT);
7571 else
7572 _open ("nul", O_TEXT | O_NOINHERIT | O_RDONLY);
7573 _fdopen (0, "r");
7575 if (stdout_save != INVALID_HANDLE_VALUE)
7576 _open_osfhandle ((intptr_t) stdout_save, O_TEXT);
7577 else
7578 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
7579 _fdopen (1, "w");
7581 if (stderr_save != INVALID_HANDLE_VALUE)
7582 _open_osfhandle ((intptr_t) stderr_save, O_TEXT);
7583 else
7584 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
7585 _fdopen (2, "w");
7588 /* unfortunately, atexit depends on implementation of malloc */
7589 /* atexit (term_ntproc); */
7590 if (!dumping)
7592 /* Make sure we start with all signals unblocked. */
7593 sigprocmask (SIG_SETMASK, &initial_mask, NULL);
7594 signal (SIGABRT, term_ntproc);
7596 init_timers ();
7598 /* determine which drives are fixed, for GetCachedVolumeInformation */
7600 /* GetDriveType must have trailing backslash. */
7601 char drive[] = "A:\\";
7603 /* Loop over all possible drive letters */
7604 while (*drive <= 'Z')
7606 /* Record if this drive letter refers to a fixed drive. */
7607 fixed_drives[DRIVE_INDEX (*drive)] =
7608 (GetDriveType (drive) == DRIVE_FIXED);
7610 (*drive)++;
7613 /* Reset the volume info cache. */
7614 volume_cache = NULL;
7619 shutdown_handler ensures that buffers' autosave files are
7620 up to date when the user logs off, or the system shuts down.
7622 static BOOL WINAPI
7623 shutdown_handler (DWORD type)
7625 /* Ctrl-C and Ctrl-Break are already suppressed, so don't handle them. */
7626 if (type == CTRL_CLOSE_EVENT /* User closes console window. */
7627 || type == CTRL_LOGOFF_EVENT /* User logs off. */
7628 || type == CTRL_SHUTDOWN_EVENT) /* User shutsdown. */
7630 /* Shut down cleanly, making sure autosave files are up to date. */
7631 shut_down_emacs (0, Qnil);
7634 /* Allow other handlers to handle this signal. */
7635 return FALSE;
7639 globals_of_w32 is used to initialize those global variables that
7640 must always be initialized on startup even when the global variable
7641 initialized is non zero (see the function main in emacs.c).
7643 void
7644 globals_of_w32 (void)
7646 HMODULE kernel32 = GetModuleHandle ("kernel32.dll");
7648 get_process_times_fn = (GetProcessTimes_Proc)
7649 GetProcAddress (kernel32, "GetProcessTimes");
7651 DEFSYM (QCloaded_from, ":loaded-from");
7653 g_b_init_is_windows_9x = 0;
7654 g_b_init_open_process_token = 0;
7655 g_b_init_get_token_information = 0;
7656 g_b_init_lookup_account_sid = 0;
7657 g_b_init_get_sid_sub_authority = 0;
7658 g_b_init_get_sid_sub_authority_count = 0;
7659 g_b_init_get_security_info = 0;
7660 g_b_init_get_file_security = 0;
7661 g_b_init_get_security_descriptor_owner = 0;
7662 g_b_init_get_security_descriptor_group = 0;
7663 g_b_init_is_valid_sid = 0;
7664 g_b_init_create_toolhelp32_snapshot = 0;
7665 g_b_init_process32_first = 0;
7666 g_b_init_process32_next = 0;
7667 g_b_init_open_thread_token = 0;
7668 g_b_init_impersonate_self = 0;
7669 g_b_init_revert_to_self = 0;
7670 g_b_init_get_process_memory_info = 0;
7671 g_b_init_get_process_working_set_size = 0;
7672 g_b_init_global_memory_status = 0;
7673 g_b_init_global_memory_status_ex = 0;
7674 g_b_init_equal_sid = 0;
7675 g_b_init_copy_sid = 0;
7676 g_b_init_get_length_sid = 0;
7677 g_b_init_get_native_system_info = 0;
7678 g_b_init_get_system_times = 0;
7679 g_b_init_create_symbolic_link = 0;
7680 g_b_init_get_security_descriptor_dacl = 0;
7681 g_b_init_convert_sd_to_sddl = 0;
7682 g_b_init_convert_sddl_to_sd = 0;
7683 g_b_init_is_valid_security_descriptor = 0;
7684 g_b_init_set_file_security = 0;
7685 num_of_processors = 0;
7686 /* The following sets a handler for shutdown notifications for
7687 console apps. This actually applies to Emacs in both console and
7688 GUI modes, since we had to fool windows into thinking emacs is a
7689 console application to get console mode to work. */
7690 SetConsoleCtrlHandler (shutdown_handler, TRUE);
7692 /* "None" is the default group name on standalone workstations. */
7693 strcpy (dflt_group_name, "None");
7695 /* Reset, in case it has some value inherited from dump time. */
7696 w32_stat_get_owner_group = 0;
7699 /* For make-serial-process */
7701 serial_open (char *port)
7703 HANDLE hnd;
7704 child_process *cp;
7705 int fd = -1;
7707 hnd = CreateFile (port, GENERIC_READ | GENERIC_WRITE, 0, 0,
7708 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
7709 if (hnd == INVALID_HANDLE_VALUE)
7710 error ("Could not open %s", port);
7711 fd = (int) _open_osfhandle ((intptr_t) hnd, 0);
7712 if (fd == -1)
7713 error ("Could not open %s", port);
7715 cp = new_child ();
7716 if (!cp)
7717 error ("Could not create child process");
7718 cp->fd = fd;
7719 cp->status = STATUS_READ_ACKNOWLEDGED;
7720 fd_info[ fd ].hnd = hnd;
7721 fd_info[ fd ].flags |=
7722 FILE_READ | FILE_WRITE | FILE_BINARY | FILE_SERIAL;
7723 if (fd_info[ fd ].cp != NULL)
7725 error ("fd_info[fd = %d] is already in use", fd);
7727 fd_info[ fd ].cp = cp;
7728 cp->ovl_read.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
7729 if (cp->ovl_read.hEvent == NULL)
7730 error ("Could not create read event");
7731 cp->ovl_write.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
7732 if (cp->ovl_write.hEvent == NULL)
7733 error ("Could not create write event");
7735 return fd;
7738 /* For serial-process-configure */
7739 void
7740 serial_configure (struct Lisp_Process *p, Lisp_Object contact)
7742 Lisp_Object childp2 = Qnil;
7743 Lisp_Object tem = Qnil;
7744 HANDLE hnd;
7745 DCB dcb;
7746 COMMTIMEOUTS ct;
7747 char summary[4] = "???"; /* This usually becomes "8N1". */
7749 if ((fd_info[ p->outfd ].flags & FILE_SERIAL) == 0)
7750 error ("Not a serial process");
7751 hnd = fd_info[ p->outfd ].hnd;
7753 childp2 = Fcopy_sequence (p->childp);
7755 /* Initialize timeouts for blocking read and blocking write. */
7756 if (!GetCommTimeouts (hnd, &ct))
7757 error ("GetCommTimeouts() failed");
7758 ct.ReadIntervalTimeout = 0;
7759 ct.ReadTotalTimeoutMultiplier = 0;
7760 ct.ReadTotalTimeoutConstant = 0;
7761 ct.WriteTotalTimeoutMultiplier = 0;
7762 ct.WriteTotalTimeoutConstant = 0;
7763 if (!SetCommTimeouts (hnd, &ct))
7764 error ("SetCommTimeouts() failed");
7765 /* Read port attributes and prepare default configuration. */
7766 memset (&dcb, 0, sizeof (dcb));
7767 dcb.DCBlength = sizeof (DCB);
7768 if (!GetCommState (hnd, &dcb))
7769 error ("GetCommState() failed");
7770 dcb.fBinary = TRUE;
7771 dcb.fNull = FALSE;
7772 dcb.fAbortOnError = FALSE;
7773 /* dcb.XonLim and dcb.XoffLim are set by GetCommState() */
7774 dcb.ErrorChar = 0;
7775 dcb.EofChar = 0;
7776 dcb.EvtChar = 0;
7778 /* Configure speed. */
7779 if (!NILP (Fplist_member (contact, QCspeed)))
7780 tem = Fplist_get (contact, QCspeed);
7781 else
7782 tem = Fplist_get (p->childp, QCspeed);
7783 CHECK_NUMBER (tem);
7784 dcb.BaudRate = XINT (tem);
7785 childp2 = Fplist_put (childp2, QCspeed, tem);
7787 /* Configure bytesize. */
7788 if (!NILP (Fplist_member (contact, QCbytesize)))
7789 tem = Fplist_get (contact, QCbytesize);
7790 else
7791 tem = Fplist_get (p->childp, QCbytesize);
7792 if (NILP (tem))
7793 tem = make_number (8);
7794 CHECK_NUMBER (tem);
7795 if (XINT (tem) != 7 && XINT (tem) != 8)
7796 error (":bytesize must be nil (8), 7, or 8");
7797 dcb.ByteSize = XINT (tem);
7798 summary[0] = XINT (tem) + '0';
7799 childp2 = Fplist_put (childp2, QCbytesize, tem);
7801 /* Configure parity. */
7802 if (!NILP (Fplist_member (contact, QCparity)))
7803 tem = Fplist_get (contact, QCparity);
7804 else
7805 tem = Fplist_get (p->childp, QCparity);
7806 if (!NILP (tem) && !EQ (tem, Qeven) && !EQ (tem, Qodd))
7807 error (":parity must be nil (no parity), `even', or `odd'");
7808 dcb.fParity = FALSE;
7809 dcb.Parity = NOPARITY;
7810 dcb.fErrorChar = FALSE;
7811 if (NILP (tem))
7813 summary[1] = 'N';
7815 else if (EQ (tem, Qeven))
7817 summary[1] = 'E';
7818 dcb.fParity = TRUE;
7819 dcb.Parity = EVENPARITY;
7820 dcb.fErrorChar = TRUE;
7822 else if (EQ (tem, Qodd))
7824 summary[1] = 'O';
7825 dcb.fParity = TRUE;
7826 dcb.Parity = ODDPARITY;
7827 dcb.fErrorChar = TRUE;
7829 childp2 = Fplist_put (childp2, QCparity, tem);
7831 /* Configure stopbits. */
7832 if (!NILP (Fplist_member (contact, QCstopbits)))
7833 tem = Fplist_get (contact, QCstopbits);
7834 else
7835 tem = Fplist_get (p->childp, QCstopbits);
7836 if (NILP (tem))
7837 tem = make_number (1);
7838 CHECK_NUMBER (tem);
7839 if (XINT (tem) != 1 && XINT (tem) != 2)
7840 error (":stopbits must be nil (1 stopbit), 1, or 2");
7841 summary[2] = XINT (tem) + '0';
7842 if (XINT (tem) == 1)
7843 dcb.StopBits = ONESTOPBIT;
7844 else if (XINT (tem) == 2)
7845 dcb.StopBits = TWOSTOPBITS;
7846 childp2 = Fplist_put (childp2, QCstopbits, tem);
7848 /* Configure flowcontrol. */
7849 if (!NILP (Fplist_member (contact, QCflowcontrol)))
7850 tem = Fplist_get (contact, QCflowcontrol);
7851 else
7852 tem = Fplist_get (p->childp, QCflowcontrol);
7853 if (!NILP (tem) && !EQ (tem, Qhw) && !EQ (tem, Qsw))
7854 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
7855 dcb.fOutxCtsFlow = FALSE;
7856 dcb.fOutxDsrFlow = FALSE;
7857 dcb.fDtrControl = DTR_CONTROL_DISABLE;
7858 dcb.fDsrSensitivity = FALSE;
7859 dcb.fTXContinueOnXoff = FALSE;
7860 dcb.fOutX = FALSE;
7861 dcb.fInX = FALSE;
7862 dcb.fRtsControl = RTS_CONTROL_DISABLE;
7863 dcb.XonChar = 17; /* Control-Q */
7864 dcb.XoffChar = 19; /* Control-S */
7865 if (NILP (tem))
7867 /* Already configured. */
7869 else if (EQ (tem, Qhw))
7871 dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
7872 dcb.fOutxCtsFlow = TRUE;
7874 else if (EQ (tem, Qsw))
7876 dcb.fOutX = TRUE;
7877 dcb.fInX = TRUE;
7879 childp2 = Fplist_put (childp2, QCflowcontrol, tem);
7881 /* Activate configuration. */
7882 if (!SetCommState (hnd, &dcb))
7883 error ("SetCommState() failed");
7885 childp2 = Fplist_put (childp2, QCsummary, build_string (summary));
7886 pset_childp (p, childp2);
7889 #ifdef HAVE_GNUTLS
7891 ssize_t
7892 emacs_gnutls_pull (gnutls_transport_ptr_t p, void* buf, size_t sz)
7894 int n, err;
7895 SELECT_TYPE fdset;
7896 EMACS_TIME timeout;
7897 struct Lisp_Process *process = (struct Lisp_Process *)p;
7898 int fd = process->infd;
7900 n = sys_read (fd, (char*)buf, sz);
7902 if (n >= 0)
7903 return n;
7905 err = errno;
7907 /* Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
7908 if (err == EWOULDBLOCK)
7909 err = EAGAIN;
7911 emacs_gnutls_transport_set_errno (process->gnutls_state, err);
7913 return -1;
7916 ssize_t
7917 emacs_gnutls_push (gnutls_transport_ptr_t p, const void* buf, size_t sz)
7919 struct Lisp_Process *process = (struct Lisp_Process *)p;
7920 int fd = process->outfd;
7921 ssize_t n = sys_write (fd, buf, sz);
7923 /* 0 or more bytes written means everything went fine. */
7924 if (n >= 0)
7925 return n;
7927 /* Negative bytes written means we got an error in errno.
7928 Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
7929 emacs_gnutls_transport_set_errno (process->gnutls_state,
7930 errno == EWOULDBLOCK ? EAGAIN : errno);
7932 return -1;
7934 #endif /* HAVE_GNUTLS */
7936 /* end of w32.c */