Implement mkostemp for MS-Windows.
[emacs.git] / src / w32.c
blobaf42c6f39c2614669b34fa460fa44bee43961b47
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 *);
237 extern int sys_dup (int);
242 /* Initialization states.
244 WARNING: If you add any more such variables for additional APIs,
245 you MUST add initialization for them to globals_of_w32
246 below. This is because these variables might get set
247 to non-NULL values during dumping, but the dumped Emacs
248 cannot reuse those values, because it could be run on a
249 different version of the OS, where API addresses are
250 different. */
251 static BOOL g_b_init_is_windows_9x;
252 static BOOL g_b_init_open_process_token;
253 static BOOL g_b_init_get_token_information;
254 static BOOL g_b_init_lookup_account_sid;
255 static BOOL g_b_init_get_sid_sub_authority;
256 static BOOL g_b_init_get_sid_sub_authority_count;
257 static BOOL g_b_init_get_security_info;
258 static BOOL g_b_init_get_file_security;
259 static BOOL g_b_init_get_security_descriptor_owner;
260 static BOOL g_b_init_get_security_descriptor_group;
261 static BOOL g_b_init_is_valid_sid;
262 static BOOL g_b_init_create_toolhelp32_snapshot;
263 static BOOL g_b_init_process32_first;
264 static BOOL g_b_init_process32_next;
265 static BOOL g_b_init_open_thread_token;
266 static BOOL g_b_init_impersonate_self;
267 static BOOL g_b_init_revert_to_self;
268 static BOOL g_b_init_get_process_memory_info;
269 static BOOL g_b_init_get_process_working_set_size;
270 static BOOL g_b_init_global_memory_status;
271 static BOOL g_b_init_global_memory_status_ex;
272 static BOOL g_b_init_get_length_sid;
273 static BOOL g_b_init_equal_sid;
274 static BOOL g_b_init_copy_sid;
275 static BOOL g_b_init_get_native_system_info;
276 static BOOL g_b_init_get_system_times;
277 static BOOL g_b_init_create_symbolic_link;
278 static BOOL g_b_init_get_security_descriptor_dacl;
279 static BOOL g_b_init_convert_sd_to_sddl;
280 static BOOL g_b_init_convert_sddl_to_sd;
281 static BOOL g_b_init_is_valid_security_descriptor;
282 static BOOL g_b_init_set_file_security;
285 BEGIN: Wrapper functions around OpenProcessToken
286 and other functions in advapi32.dll that are only
287 supported in Windows NT / 2k / XP
289 /* ** Function pointer typedefs ** */
290 typedef BOOL (WINAPI * OpenProcessToken_Proc) (
291 HANDLE ProcessHandle,
292 DWORD DesiredAccess,
293 PHANDLE TokenHandle);
294 typedef BOOL (WINAPI * GetTokenInformation_Proc) (
295 HANDLE TokenHandle,
296 TOKEN_INFORMATION_CLASS TokenInformationClass,
297 LPVOID TokenInformation,
298 DWORD TokenInformationLength,
299 PDWORD ReturnLength);
300 typedef BOOL (WINAPI * GetProcessTimes_Proc) (
301 HANDLE process_handle,
302 LPFILETIME creation_time,
303 LPFILETIME exit_time,
304 LPFILETIME kernel_time,
305 LPFILETIME user_time);
307 GetProcessTimes_Proc get_process_times_fn = NULL;
309 #ifdef _UNICODE
310 const char * const LookupAccountSid_Name = "LookupAccountSidW";
311 const char * const GetFileSecurity_Name = "GetFileSecurityW";
312 const char * const SetFileSecurity_Name = "SetFileSecurityW";
313 #else
314 const char * const LookupAccountSid_Name = "LookupAccountSidA";
315 const char * const GetFileSecurity_Name = "GetFileSecurityA";
316 const char * const SetFileSecurity_Name = "SetFileSecurityA";
317 #endif
318 typedef BOOL (WINAPI * LookupAccountSid_Proc) (
319 LPCTSTR lpSystemName,
320 PSID Sid,
321 LPTSTR Name,
322 LPDWORD cbName,
323 LPTSTR DomainName,
324 LPDWORD cbDomainName,
325 PSID_NAME_USE peUse);
326 typedef PDWORD (WINAPI * GetSidSubAuthority_Proc) (
327 PSID pSid,
328 DWORD n);
329 typedef PUCHAR (WINAPI * GetSidSubAuthorityCount_Proc) (
330 PSID pSid);
331 typedef DWORD (WINAPI * GetSecurityInfo_Proc) (
332 HANDLE handle,
333 SE_OBJECT_TYPE ObjectType,
334 SECURITY_INFORMATION SecurityInfo,
335 PSID *ppsidOwner,
336 PSID *ppsidGroup,
337 PACL *ppDacl,
338 PACL *ppSacl,
339 PSECURITY_DESCRIPTOR *ppSecurityDescriptor);
340 typedef BOOL (WINAPI * GetFileSecurity_Proc) (
341 LPCTSTR lpFileName,
342 SECURITY_INFORMATION RequestedInformation,
343 PSECURITY_DESCRIPTOR pSecurityDescriptor,
344 DWORD nLength,
345 LPDWORD lpnLengthNeeded);
346 typedef BOOL (WINAPI *SetFileSecurity_Proc) (
347 LPCTSTR lpFileName,
348 SECURITY_INFORMATION SecurityInformation,
349 PSECURITY_DESCRIPTOR pSecurityDescriptor);
350 typedef BOOL (WINAPI * GetSecurityDescriptorOwner_Proc) (
351 PSECURITY_DESCRIPTOR pSecurityDescriptor,
352 PSID *pOwner,
353 LPBOOL lpbOwnerDefaulted);
354 typedef BOOL (WINAPI * GetSecurityDescriptorGroup_Proc) (
355 PSECURITY_DESCRIPTOR pSecurityDescriptor,
356 PSID *pGroup,
357 LPBOOL lpbGroupDefaulted);
358 typedef BOOL (WINAPI *GetSecurityDescriptorDacl_Proc) (
359 PSECURITY_DESCRIPTOR pSecurityDescriptor,
360 LPBOOL lpbDaclPresent,
361 PACL *pDacl,
362 LPBOOL lpbDaclDefaulted);
363 typedef BOOL (WINAPI * IsValidSid_Proc) (
364 PSID sid);
365 typedef HANDLE (WINAPI * CreateToolhelp32Snapshot_Proc) (
366 DWORD dwFlags,
367 DWORD th32ProcessID);
368 typedef BOOL (WINAPI * Process32First_Proc) (
369 HANDLE hSnapshot,
370 LPPROCESSENTRY32 lppe);
371 typedef BOOL (WINAPI * Process32Next_Proc) (
372 HANDLE hSnapshot,
373 LPPROCESSENTRY32 lppe);
374 typedef BOOL (WINAPI * OpenThreadToken_Proc) (
375 HANDLE ThreadHandle,
376 DWORD DesiredAccess,
377 BOOL OpenAsSelf,
378 PHANDLE TokenHandle);
379 typedef BOOL (WINAPI * ImpersonateSelf_Proc) (
380 SECURITY_IMPERSONATION_LEVEL ImpersonationLevel);
381 typedef BOOL (WINAPI * RevertToSelf_Proc) (void);
382 typedef BOOL (WINAPI * GetProcessMemoryInfo_Proc) (
383 HANDLE Process,
384 PPROCESS_MEMORY_COUNTERS ppsmemCounters,
385 DWORD cb);
386 typedef BOOL (WINAPI * GetProcessWorkingSetSize_Proc) (
387 HANDLE hProcess,
388 PSIZE_T lpMinimumWorkingSetSize,
389 PSIZE_T lpMaximumWorkingSetSize);
390 typedef BOOL (WINAPI * GlobalMemoryStatus_Proc) (
391 LPMEMORYSTATUS lpBuffer);
392 typedef BOOL (WINAPI * GlobalMemoryStatusEx_Proc) (
393 LPMEMORY_STATUS_EX lpBuffer);
394 typedef BOOL (WINAPI * CopySid_Proc) (
395 DWORD nDestinationSidLength,
396 PSID pDestinationSid,
397 PSID pSourceSid);
398 typedef BOOL (WINAPI * EqualSid_Proc) (
399 PSID pSid1,
400 PSID pSid2);
401 typedef DWORD (WINAPI * GetLengthSid_Proc) (
402 PSID pSid);
403 typedef void (WINAPI * GetNativeSystemInfo_Proc) (
404 LPSYSTEM_INFO lpSystemInfo);
405 typedef BOOL (WINAPI * GetSystemTimes_Proc) (
406 LPFILETIME lpIdleTime,
407 LPFILETIME lpKernelTime,
408 LPFILETIME lpUserTime);
409 typedef BOOLEAN (WINAPI *CreateSymbolicLink_Proc) (
410 LPTSTR lpSymlinkFileName,
411 LPTSTR lpTargetFileName,
412 DWORD dwFlags);
413 typedef BOOL (WINAPI *ConvertStringSecurityDescriptorToSecurityDescriptor_Proc) (
414 LPCTSTR StringSecurityDescriptor,
415 DWORD StringSDRevision,
416 PSECURITY_DESCRIPTOR *SecurityDescriptor,
417 PULONG SecurityDescriptorSize);
418 typedef BOOL (WINAPI *ConvertSecurityDescriptorToStringSecurityDescriptor_Proc) (
419 PSECURITY_DESCRIPTOR SecurityDescriptor,
420 DWORD RequestedStringSDRevision,
421 SECURITY_INFORMATION SecurityInformation,
422 LPTSTR *StringSecurityDescriptor,
423 PULONG StringSecurityDescriptorLen);
424 typedef BOOL (WINAPI *IsValidSecurityDescriptor_Proc) (PSECURITY_DESCRIPTOR);
426 /* ** A utility function ** */
427 static BOOL
428 is_windows_9x (void)
430 static BOOL s_b_ret = 0;
431 OSVERSIONINFO os_ver;
432 if (g_b_init_is_windows_9x == 0)
434 g_b_init_is_windows_9x = 1;
435 ZeroMemory (&os_ver, sizeof (OSVERSIONINFO));
436 os_ver.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
437 if (GetVersionEx (&os_ver))
439 s_b_ret = (os_ver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS);
442 return s_b_ret;
445 static Lisp_Object ltime (ULONGLONG);
447 /* Get total user and system times for get-internal-run-time.
448 Returns a list of integers if the times are provided by the OS
449 (NT derivatives), otherwise it returns the result of current-time. */
450 Lisp_Object
451 w32_get_internal_run_time (void)
453 if (get_process_times_fn)
455 FILETIME create, exit, kernel, user;
456 HANDLE proc = GetCurrentProcess ();
457 if ((*get_process_times_fn) (proc, &create, &exit, &kernel, &user))
459 LARGE_INTEGER user_int, kernel_int, total;
460 user_int.LowPart = user.dwLowDateTime;
461 user_int.HighPart = user.dwHighDateTime;
462 kernel_int.LowPart = kernel.dwLowDateTime;
463 kernel_int.HighPart = kernel.dwHighDateTime;
464 total.QuadPart = user_int.QuadPart + kernel_int.QuadPart;
465 return ltime (total.QuadPart);
469 return Fcurrent_time ();
472 /* ** The wrapper functions ** */
474 static BOOL WINAPI
475 open_process_token (HANDLE ProcessHandle,
476 DWORD DesiredAccess,
477 PHANDLE TokenHandle)
479 static OpenProcessToken_Proc s_pfn_Open_Process_Token = NULL;
480 HMODULE hm_advapi32 = NULL;
481 if (is_windows_9x () == TRUE)
483 return FALSE;
485 if (g_b_init_open_process_token == 0)
487 g_b_init_open_process_token = 1;
488 hm_advapi32 = LoadLibrary ("Advapi32.dll");
489 s_pfn_Open_Process_Token =
490 (OpenProcessToken_Proc) GetProcAddress (hm_advapi32, "OpenProcessToken");
492 if (s_pfn_Open_Process_Token == NULL)
494 return FALSE;
496 return (
497 s_pfn_Open_Process_Token (
498 ProcessHandle,
499 DesiredAccess,
500 TokenHandle)
504 static BOOL WINAPI
505 get_token_information (HANDLE TokenHandle,
506 TOKEN_INFORMATION_CLASS TokenInformationClass,
507 LPVOID TokenInformation,
508 DWORD TokenInformationLength,
509 PDWORD ReturnLength)
511 static GetTokenInformation_Proc s_pfn_Get_Token_Information = NULL;
512 HMODULE hm_advapi32 = NULL;
513 if (is_windows_9x () == TRUE)
515 return FALSE;
517 if (g_b_init_get_token_information == 0)
519 g_b_init_get_token_information = 1;
520 hm_advapi32 = LoadLibrary ("Advapi32.dll");
521 s_pfn_Get_Token_Information =
522 (GetTokenInformation_Proc) GetProcAddress (hm_advapi32, "GetTokenInformation");
524 if (s_pfn_Get_Token_Information == NULL)
526 return FALSE;
528 return (
529 s_pfn_Get_Token_Information (
530 TokenHandle,
531 TokenInformationClass,
532 TokenInformation,
533 TokenInformationLength,
534 ReturnLength)
538 static BOOL WINAPI
539 lookup_account_sid (LPCTSTR lpSystemName,
540 PSID Sid,
541 LPTSTR Name,
542 LPDWORD cbName,
543 LPTSTR DomainName,
544 LPDWORD cbDomainName,
545 PSID_NAME_USE peUse)
547 static LookupAccountSid_Proc s_pfn_Lookup_Account_Sid = NULL;
548 HMODULE hm_advapi32 = NULL;
549 if (is_windows_9x () == TRUE)
551 return FALSE;
553 if (g_b_init_lookup_account_sid == 0)
555 g_b_init_lookup_account_sid = 1;
556 hm_advapi32 = LoadLibrary ("Advapi32.dll");
557 s_pfn_Lookup_Account_Sid =
558 (LookupAccountSid_Proc) GetProcAddress (hm_advapi32, LookupAccountSid_Name);
560 if (s_pfn_Lookup_Account_Sid == NULL)
562 return FALSE;
564 return (
565 s_pfn_Lookup_Account_Sid (
566 lpSystemName,
567 Sid,
568 Name,
569 cbName,
570 DomainName,
571 cbDomainName,
572 peUse)
576 static PDWORD WINAPI
577 get_sid_sub_authority (PSID pSid, DWORD n)
579 static GetSidSubAuthority_Proc s_pfn_Get_Sid_Sub_Authority = NULL;
580 static DWORD zero = 0U;
581 HMODULE hm_advapi32 = NULL;
582 if (is_windows_9x () == TRUE)
584 return &zero;
586 if (g_b_init_get_sid_sub_authority == 0)
588 g_b_init_get_sid_sub_authority = 1;
589 hm_advapi32 = LoadLibrary ("Advapi32.dll");
590 s_pfn_Get_Sid_Sub_Authority =
591 (GetSidSubAuthority_Proc) GetProcAddress (
592 hm_advapi32, "GetSidSubAuthority");
594 if (s_pfn_Get_Sid_Sub_Authority == NULL)
596 return &zero;
598 return (s_pfn_Get_Sid_Sub_Authority (pSid, n));
601 static PUCHAR WINAPI
602 get_sid_sub_authority_count (PSID pSid)
604 static GetSidSubAuthorityCount_Proc s_pfn_Get_Sid_Sub_Authority_Count = NULL;
605 static UCHAR zero = 0U;
606 HMODULE hm_advapi32 = NULL;
607 if (is_windows_9x () == TRUE)
609 return &zero;
611 if (g_b_init_get_sid_sub_authority_count == 0)
613 g_b_init_get_sid_sub_authority_count = 1;
614 hm_advapi32 = LoadLibrary ("Advapi32.dll");
615 s_pfn_Get_Sid_Sub_Authority_Count =
616 (GetSidSubAuthorityCount_Proc) GetProcAddress (
617 hm_advapi32, "GetSidSubAuthorityCount");
619 if (s_pfn_Get_Sid_Sub_Authority_Count == NULL)
621 return &zero;
623 return (s_pfn_Get_Sid_Sub_Authority_Count (pSid));
626 static DWORD WINAPI
627 get_security_info (HANDLE handle,
628 SE_OBJECT_TYPE ObjectType,
629 SECURITY_INFORMATION SecurityInfo,
630 PSID *ppsidOwner,
631 PSID *ppsidGroup,
632 PACL *ppDacl,
633 PACL *ppSacl,
634 PSECURITY_DESCRIPTOR *ppSecurityDescriptor)
636 static GetSecurityInfo_Proc s_pfn_Get_Security_Info = NULL;
637 HMODULE hm_advapi32 = NULL;
638 if (is_windows_9x () == TRUE)
640 return FALSE;
642 if (g_b_init_get_security_info == 0)
644 g_b_init_get_security_info = 1;
645 hm_advapi32 = LoadLibrary ("Advapi32.dll");
646 s_pfn_Get_Security_Info =
647 (GetSecurityInfo_Proc) GetProcAddress (
648 hm_advapi32, "GetSecurityInfo");
650 if (s_pfn_Get_Security_Info == NULL)
652 return FALSE;
654 return (s_pfn_Get_Security_Info (handle, ObjectType, SecurityInfo,
655 ppsidOwner, ppsidGroup, ppDacl, ppSacl,
656 ppSecurityDescriptor));
659 static BOOL WINAPI
660 get_file_security (LPCTSTR lpFileName,
661 SECURITY_INFORMATION RequestedInformation,
662 PSECURITY_DESCRIPTOR pSecurityDescriptor,
663 DWORD nLength,
664 LPDWORD lpnLengthNeeded)
666 static GetFileSecurity_Proc s_pfn_Get_File_Security = NULL;
667 HMODULE hm_advapi32 = NULL;
668 if (is_windows_9x () == TRUE)
670 errno = ENOTSUP;
671 return FALSE;
673 if (g_b_init_get_file_security == 0)
675 g_b_init_get_file_security = 1;
676 hm_advapi32 = LoadLibrary ("Advapi32.dll");
677 s_pfn_Get_File_Security =
678 (GetFileSecurity_Proc) GetProcAddress (
679 hm_advapi32, GetFileSecurity_Name);
681 if (s_pfn_Get_File_Security == NULL)
683 errno = ENOTSUP;
684 return FALSE;
686 return (s_pfn_Get_File_Security (lpFileName, RequestedInformation,
687 pSecurityDescriptor, nLength,
688 lpnLengthNeeded));
691 static BOOL WINAPI
692 set_file_security (LPCTSTR lpFileName,
693 SECURITY_INFORMATION SecurityInformation,
694 PSECURITY_DESCRIPTOR pSecurityDescriptor)
696 static SetFileSecurity_Proc s_pfn_Set_File_Security = NULL;
697 HMODULE hm_advapi32 = NULL;
698 if (is_windows_9x () == TRUE)
700 errno = ENOTSUP;
701 return FALSE;
703 if (g_b_init_set_file_security == 0)
705 g_b_init_set_file_security = 1;
706 hm_advapi32 = LoadLibrary ("Advapi32.dll");
707 s_pfn_Set_File_Security =
708 (SetFileSecurity_Proc) GetProcAddress (
709 hm_advapi32, SetFileSecurity_Name);
711 if (s_pfn_Set_File_Security == NULL)
713 errno = ENOTSUP;
714 return FALSE;
716 return (s_pfn_Set_File_Security (lpFileName, SecurityInformation,
717 pSecurityDescriptor));
720 static BOOL WINAPI
721 get_security_descriptor_owner (PSECURITY_DESCRIPTOR pSecurityDescriptor,
722 PSID *pOwner,
723 LPBOOL lpbOwnerDefaulted)
725 static GetSecurityDescriptorOwner_Proc s_pfn_Get_Security_Descriptor_Owner = NULL;
726 HMODULE hm_advapi32 = NULL;
727 if (is_windows_9x () == TRUE)
729 errno = ENOTSUP;
730 return FALSE;
732 if (g_b_init_get_security_descriptor_owner == 0)
734 g_b_init_get_security_descriptor_owner = 1;
735 hm_advapi32 = LoadLibrary ("Advapi32.dll");
736 s_pfn_Get_Security_Descriptor_Owner =
737 (GetSecurityDescriptorOwner_Proc) GetProcAddress (
738 hm_advapi32, "GetSecurityDescriptorOwner");
740 if (s_pfn_Get_Security_Descriptor_Owner == NULL)
742 errno = ENOTSUP;
743 return FALSE;
745 return (s_pfn_Get_Security_Descriptor_Owner (pSecurityDescriptor, pOwner,
746 lpbOwnerDefaulted));
749 static BOOL WINAPI
750 get_security_descriptor_group (PSECURITY_DESCRIPTOR pSecurityDescriptor,
751 PSID *pGroup,
752 LPBOOL lpbGroupDefaulted)
754 static GetSecurityDescriptorGroup_Proc s_pfn_Get_Security_Descriptor_Group = NULL;
755 HMODULE hm_advapi32 = NULL;
756 if (is_windows_9x () == TRUE)
758 errno = ENOTSUP;
759 return FALSE;
761 if (g_b_init_get_security_descriptor_group == 0)
763 g_b_init_get_security_descriptor_group = 1;
764 hm_advapi32 = LoadLibrary ("Advapi32.dll");
765 s_pfn_Get_Security_Descriptor_Group =
766 (GetSecurityDescriptorGroup_Proc) GetProcAddress (
767 hm_advapi32, "GetSecurityDescriptorGroup");
769 if (s_pfn_Get_Security_Descriptor_Group == NULL)
771 errno = ENOTSUP;
772 return FALSE;
774 return (s_pfn_Get_Security_Descriptor_Group (pSecurityDescriptor, pGroup,
775 lpbGroupDefaulted));
778 static BOOL WINAPI
779 get_security_descriptor_dacl (PSECURITY_DESCRIPTOR pSecurityDescriptor,
780 LPBOOL lpbDaclPresent,
781 PACL *pDacl,
782 LPBOOL lpbDaclDefaulted)
784 static GetSecurityDescriptorDacl_Proc s_pfn_Get_Security_Descriptor_Dacl = NULL;
785 HMODULE hm_advapi32 = NULL;
786 if (is_windows_9x () == TRUE)
788 errno = ENOTSUP;
789 return FALSE;
791 if (g_b_init_get_security_descriptor_dacl == 0)
793 g_b_init_get_security_descriptor_dacl = 1;
794 hm_advapi32 = LoadLibrary ("Advapi32.dll");
795 s_pfn_Get_Security_Descriptor_Dacl =
796 (GetSecurityDescriptorDacl_Proc) GetProcAddress (
797 hm_advapi32, "GetSecurityDescriptorDacl");
799 if (s_pfn_Get_Security_Descriptor_Dacl == NULL)
801 errno = ENOTSUP;
802 return FALSE;
804 return (s_pfn_Get_Security_Descriptor_Dacl (pSecurityDescriptor,
805 lpbDaclPresent, pDacl,
806 lpbDaclDefaulted));
809 static BOOL WINAPI
810 is_valid_sid (PSID sid)
812 static IsValidSid_Proc s_pfn_Is_Valid_Sid = NULL;
813 HMODULE hm_advapi32 = NULL;
814 if (is_windows_9x () == TRUE)
816 return FALSE;
818 if (g_b_init_is_valid_sid == 0)
820 g_b_init_is_valid_sid = 1;
821 hm_advapi32 = LoadLibrary ("Advapi32.dll");
822 s_pfn_Is_Valid_Sid =
823 (IsValidSid_Proc) GetProcAddress (
824 hm_advapi32, "IsValidSid");
826 if (s_pfn_Is_Valid_Sid == NULL)
828 return FALSE;
830 return (s_pfn_Is_Valid_Sid (sid));
833 static BOOL WINAPI
834 equal_sid (PSID sid1, PSID sid2)
836 static EqualSid_Proc s_pfn_Equal_Sid = NULL;
837 HMODULE hm_advapi32 = NULL;
838 if (is_windows_9x () == TRUE)
840 return FALSE;
842 if (g_b_init_equal_sid == 0)
844 g_b_init_equal_sid = 1;
845 hm_advapi32 = LoadLibrary ("Advapi32.dll");
846 s_pfn_Equal_Sid =
847 (EqualSid_Proc) GetProcAddress (
848 hm_advapi32, "EqualSid");
850 if (s_pfn_Equal_Sid == NULL)
852 return FALSE;
854 return (s_pfn_Equal_Sid (sid1, sid2));
857 static DWORD WINAPI
858 get_length_sid (PSID sid)
860 static GetLengthSid_Proc s_pfn_Get_Length_Sid = NULL;
861 HMODULE hm_advapi32 = NULL;
862 if (is_windows_9x () == TRUE)
864 return 0;
866 if (g_b_init_get_length_sid == 0)
868 g_b_init_get_length_sid = 1;
869 hm_advapi32 = LoadLibrary ("Advapi32.dll");
870 s_pfn_Get_Length_Sid =
871 (GetLengthSid_Proc) GetProcAddress (
872 hm_advapi32, "GetLengthSid");
874 if (s_pfn_Get_Length_Sid == NULL)
876 return 0;
878 return (s_pfn_Get_Length_Sid (sid));
881 static BOOL WINAPI
882 copy_sid (DWORD destlen, PSID dest, PSID src)
884 static CopySid_Proc s_pfn_Copy_Sid = NULL;
885 HMODULE hm_advapi32 = NULL;
886 if (is_windows_9x () == TRUE)
888 return FALSE;
890 if (g_b_init_copy_sid == 0)
892 g_b_init_copy_sid = 1;
893 hm_advapi32 = LoadLibrary ("Advapi32.dll");
894 s_pfn_Copy_Sid =
895 (CopySid_Proc) GetProcAddress (
896 hm_advapi32, "CopySid");
898 if (s_pfn_Copy_Sid == NULL)
900 return FALSE;
902 return (s_pfn_Copy_Sid (destlen, dest, src));
906 END: Wrapper functions around OpenProcessToken
907 and other functions in advapi32.dll that are only
908 supported in Windows NT / 2k / XP
911 static void WINAPI
912 get_native_system_info (LPSYSTEM_INFO lpSystemInfo)
914 static GetNativeSystemInfo_Proc s_pfn_Get_Native_System_Info = NULL;
915 if (is_windows_9x () != TRUE)
917 if (g_b_init_get_native_system_info == 0)
919 g_b_init_get_native_system_info = 1;
920 s_pfn_Get_Native_System_Info =
921 (GetNativeSystemInfo_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
922 "GetNativeSystemInfo");
924 if (s_pfn_Get_Native_System_Info != NULL)
925 s_pfn_Get_Native_System_Info (lpSystemInfo);
927 else
928 lpSystemInfo->dwNumberOfProcessors = -1;
931 static BOOL WINAPI
932 get_system_times (LPFILETIME lpIdleTime,
933 LPFILETIME lpKernelTime,
934 LPFILETIME lpUserTime)
936 static GetSystemTimes_Proc s_pfn_Get_System_times = NULL;
937 if (is_windows_9x () == TRUE)
939 return FALSE;
941 if (g_b_init_get_system_times == 0)
943 g_b_init_get_system_times = 1;
944 s_pfn_Get_System_times =
945 (GetSystemTimes_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
946 "GetSystemTimes");
948 if (s_pfn_Get_System_times == NULL)
949 return FALSE;
950 return (s_pfn_Get_System_times (lpIdleTime, lpKernelTime, lpUserTime));
953 static BOOLEAN WINAPI
954 create_symbolic_link (LPTSTR lpSymlinkFilename,
955 LPTSTR lpTargetFileName,
956 DWORD dwFlags)
958 static CreateSymbolicLink_Proc s_pfn_Create_Symbolic_Link = NULL;
959 BOOLEAN retval;
961 if (is_windows_9x () == TRUE)
963 errno = ENOSYS;
964 return 0;
966 if (g_b_init_create_symbolic_link == 0)
968 g_b_init_create_symbolic_link = 1;
969 #ifdef _UNICODE
970 s_pfn_Create_Symbolic_Link =
971 (CreateSymbolicLink_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
972 "CreateSymbolicLinkW");
973 #else
974 s_pfn_Create_Symbolic_Link =
975 (CreateSymbolicLink_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
976 "CreateSymbolicLinkA");
977 #endif
979 if (s_pfn_Create_Symbolic_Link == NULL)
981 errno = ENOSYS;
982 return 0;
985 retval = s_pfn_Create_Symbolic_Link (lpSymlinkFilename, lpTargetFileName,
986 dwFlags);
987 /* If we were denied creation of the symlink, try again after
988 enabling the SeCreateSymbolicLinkPrivilege for our process. */
989 if (!retval)
991 TOKEN_PRIVILEGES priv_current;
993 if (enable_privilege (SE_CREATE_SYMBOLIC_LINK_NAME, TRUE, &priv_current))
995 retval = s_pfn_Create_Symbolic_Link (lpSymlinkFilename, lpTargetFileName,
996 dwFlags);
997 restore_privilege (&priv_current);
998 revert_to_self ();
1001 return retval;
1004 static BOOL WINAPI
1005 is_valid_security_descriptor (PSECURITY_DESCRIPTOR pSecurityDescriptor)
1007 static IsValidSecurityDescriptor_Proc s_pfn_Is_Valid_Security_Descriptor_Proc = NULL;
1009 if (is_windows_9x () == TRUE)
1011 errno = ENOTSUP;
1012 return FALSE;
1015 if (g_b_init_is_valid_security_descriptor == 0)
1017 g_b_init_is_valid_security_descriptor = 1;
1018 s_pfn_Is_Valid_Security_Descriptor_Proc =
1019 (IsValidSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1020 "IsValidSecurityDescriptor");
1022 if (s_pfn_Is_Valid_Security_Descriptor_Proc == NULL)
1024 errno = ENOTSUP;
1025 return FALSE;
1028 return s_pfn_Is_Valid_Security_Descriptor_Proc (pSecurityDescriptor);
1031 static BOOL WINAPI
1032 convert_sd_to_sddl (PSECURITY_DESCRIPTOR SecurityDescriptor,
1033 DWORD RequestedStringSDRevision,
1034 SECURITY_INFORMATION SecurityInformation,
1035 LPTSTR *StringSecurityDescriptor,
1036 PULONG StringSecurityDescriptorLen)
1038 static ConvertSecurityDescriptorToStringSecurityDescriptor_Proc s_pfn_Convert_SD_To_SDDL = NULL;
1039 BOOL retval;
1041 if (is_windows_9x () == TRUE)
1043 errno = ENOTSUP;
1044 return FALSE;
1047 if (g_b_init_convert_sd_to_sddl == 0)
1049 g_b_init_convert_sd_to_sddl = 1;
1050 #ifdef _UNICODE
1051 s_pfn_Convert_SD_To_SDDL =
1052 (ConvertSecurityDescriptorToStringSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1053 "ConvertSecurityDescriptorToStringSecurityDescriptorW");
1054 #else
1055 s_pfn_Convert_SD_To_SDDL =
1056 (ConvertSecurityDescriptorToStringSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1057 "ConvertSecurityDescriptorToStringSecurityDescriptorA");
1058 #endif
1060 if (s_pfn_Convert_SD_To_SDDL == NULL)
1062 errno = ENOTSUP;
1063 return FALSE;
1066 retval = s_pfn_Convert_SD_To_SDDL (SecurityDescriptor,
1067 RequestedStringSDRevision,
1068 SecurityInformation,
1069 StringSecurityDescriptor,
1070 StringSecurityDescriptorLen);
1072 return retval;
1075 static BOOL WINAPI
1076 convert_sddl_to_sd (LPCTSTR StringSecurityDescriptor,
1077 DWORD StringSDRevision,
1078 PSECURITY_DESCRIPTOR *SecurityDescriptor,
1079 PULONG SecurityDescriptorSize)
1081 static ConvertStringSecurityDescriptorToSecurityDescriptor_Proc s_pfn_Convert_SDDL_To_SD = NULL;
1082 BOOL retval;
1084 if (is_windows_9x () == TRUE)
1086 errno = ENOTSUP;
1087 return FALSE;
1090 if (g_b_init_convert_sddl_to_sd == 0)
1092 g_b_init_convert_sddl_to_sd = 1;
1093 #ifdef _UNICODE
1094 s_pfn_Convert_SDDL_To_SD =
1095 (ConvertStringSecurityDescriptorToSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1096 "ConvertStringSecurityDescriptorToSecurityDescriptorW");
1097 #else
1098 s_pfn_Convert_SDDL_To_SD =
1099 (ConvertStringSecurityDescriptorToSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1100 "ConvertStringSecurityDescriptorToSecurityDescriptorA");
1101 #endif
1103 if (s_pfn_Convert_SDDL_To_SD == NULL)
1105 errno = ENOTSUP;
1106 return FALSE;
1109 retval = s_pfn_Convert_SDDL_To_SD (StringSecurityDescriptor,
1110 StringSDRevision,
1111 SecurityDescriptor,
1112 SecurityDescriptorSize);
1114 return retval;
1119 /* Return 1 if P is a valid pointer to an object of size SIZE. Return
1120 0 if P is NOT a valid pointer. Return -1 if we cannot validate P.
1122 This is called from alloc.c:valid_pointer_p. */
1124 w32_valid_pointer_p (void *p, int size)
1126 SIZE_T done;
1127 HANDLE h = OpenProcess (PROCESS_VM_READ, FALSE, GetCurrentProcessId ());
1129 if (h)
1131 unsigned char *buf = alloca (size);
1132 int retval = ReadProcessMemory (h, p, buf, size, &done);
1134 CloseHandle (h);
1135 return retval;
1137 else
1138 return -1;
1141 static char startup_dir[MAXPATHLEN];
1143 /* Get the current working directory. */
1144 char *
1145 getcwd (char *dir, int dirsize)
1147 if (!dirsize)
1149 errno = EINVAL;
1150 return NULL;
1152 if (dirsize <= strlen (startup_dir))
1154 errno = ERANGE;
1155 return NULL;
1157 #if 0
1158 if (GetCurrentDirectory (MAXPATHLEN, dir) > 0)
1159 return dir;
1160 return NULL;
1161 #else
1162 /* Emacs doesn't actually change directory itself, it stays in the
1163 same directory where it was started. */
1164 strcpy (dir, startup_dir);
1165 return dir;
1166 #endif
1169 /* Emulate getloadavg. */
1171 struct load_sample {
1172 time_t sample_time;
1173 ULONGLONG idle;
1174 ULONGLONG kernel;
1175 ULONGLONG user;
1178 /* Number of processors on this machine. */
1179 static unsigned num_of_processors;
1181 /* We maintain 1-sec samples for the last 16 minutes in a circular buffer. */
1182 static struct load_sample samples[16*60];
1183 static int first_idx = -1, last_idx = -1;
1184 static int max_idx = sizeof (samples) / sizeof (samples[0]);
1186 static int
1187 buf_next (int from)
1189 int next_idx = from + 1;
1191 if (next_idx >= max_idx)
1192 next_idx = 0;
1194 return next_idx;
1197 static int
1198 buf_prev (int from)
1200 int prev_idx = from - 1;
1202 if (prev_idx < 0)
1203 prev_idx = max_idx - 1;
1205 return prev_idx;
1208 static void
1209 sample_system_load (ULONGLONG *idle, ULONGLONG *kernel, ULONGLONG *user)
1211 SYSTEM_INFO sysinfo;
1212 FILETIME ft_idle, ft_user, ft_kernel;
1214 /* Initialize the number of processors on this machine. */
1215 if (num_of_processors <= 0)
1217 get_native_system_info (&sysinfo);
1218 num_of_processors = sysinfo.dwNumberOfProcessors;
1219 if (num_of_processors <= 0)
1221 GetSystemInfo (&sysinfo);
1222 num_of_processors = sysinfo.dwNumberOfProcessors;
1224 if (num_of_processors <= 0)
1225 num_of_processors = 1;
1228 /* TODO: Take into account threads that are ready to run, by
1229 sampling the "\System\Processor Queue Length" performance
1230 counter. The code below accounts only for threads that are
1231 actually running. */
1233 if (get_system_times (&ft_idle, &ft_kernel, &ft_user))
1235 ULARGE_INTEGER uidle, ukernel, uuser;
1237 memcpy (&uidle, &ft_idle, sizeof (ft_idle));
1238 memcpy (&ukernel, &ft_kernel, sizeof (ft_kernel));
1239 memcpy (&uuser, &ft_user, sizeof (ft_user));
1240 *idle = uidle.QuadPart;
1241 *kernel = ukernel.QuadPart;
1242 *user = uuser.QuadPart;
1244 else
1246 *idle = 0;
1247 *kernel = 0;
1248 *user = 0;
1252 /* Produce the load average for a given time interval, using the
1253 samples in the samples[] array. WHICH can be 0, 1, or 2, meaning
1254 1-minute, 5-minute, or 15-minute average, respectively. */
1255 static double
1256 getavg (int which)
1258 double retval = -1.0;
1259 double tdiff;
1260 int idx;
1261 double span = (which == 0 ? 1.0 : (which == 1 ? 5.0 : 15.0)) * 60;
1262 time_t now = samples[last_idx].sample_time;
1264 if (first_idx != last_idx)
1266 for (idx = buf_prev (last_idx); ; idx = buf_prev (idx))
1268 tdiff = difftime (now, samples[idx].sample_time);
1269 if (tdiff >= span - 2*DBL_EPSILON*now)
1271 long double sys =
1272 samples[last_idx].kernel + samples[last_idx].user
1273 - (samples[idx].kernel + samples[idx].user);
1274 long double idl = samples[last_idx].idle - samples[idx].idle;
1276 retval = (1.0 - idl / sys) * num_of_processors;
1277 break;
1279 if (idx == first_idx)
1280 break;
1284 return retval;
1288 getloadavg (double loadavg[], int nelem)
1290 int elem;
1291 ULONGLONG idle, kernel, user;
1292 time_t now = time (NULL);
1294 /* Store another sample. We ignore samples that are less than 1 sec
1295 apart. */
1296 if (difftime (now, samples[last_idx].sample_time) >= 1.0 - 2*DBL_EPSILON*now)
1298 sample_system_load (&idle, &kernel, &user);
1299 last_idx = buf_next (last_idx);
1300 samples[last_idx].sample_time = now;
1301 samples[last_idx].idle = idle;
1302 samples[last_idx].kernel = kernel;
1303 samples[last_idx].user = user;
1304 /* If the buffer has more that 15 min worth of samples, discard
1305 the old ones. */
1306 if (first_idx == -1)
1307 first_idx = last_idx;
1308 while (first_idx != last_idx
1309 && (difftime (now, samples[first_idx].sample_time)
1310 >= 15.0*60 + 2*DBL_EPSILON*now))
1311 first_idx = buf_next (first_idx);
1314 for (elem = 0; elem < nelem; elem++)
1316 double avg = getavg (elem);
1318 if (avg < 0)
1319 break;
1320 loadavg[elem] = avg;
1323 return elem;
1326 /* Emulate getpwuid, getpwnam and others. */
1328 #define PASSWD_FIELD_SIZE 256
1330 static char dflt_passwd_name[PASSWD_FIELD_SIZE];
1331 static char dflt_passwd_passwd[PASSWD_FIELD_SIZE];
1332 static char dflt_passwd_gecos[PASSWD_FIELD_SIZE];
1333 static char dflt_passwd_dir[PASSWD_FIELD_SIZE];
1334 static char dflt_passwd_shell[PASSWD_FIELD_SIZE];
1336 static struct passwd dflt_passwd =
1338 dflt_passwd_name,
1339 dflt_passwd_passwd,
1343 dflt_passwd_gecos,
1344 dflt_passwd_dir,
1345 dflt_passwd_shell,
1348 static char dflt_group_name[GNLEN+1];
1350 static struct group dflt_group =
1352 /* When group information is not available, we return this as the
1353 group for all files. */
1354 dflt_group_name,
1358 unsigned
1359 getuid (void)
1361 return dflt_passwd.pw_uid;
1364 unsigned
1365 geteuid (void)
1367 /* I could imagine arguing for checking to see whether the user is
1368 in the Administrators group and returning a UID of 0 for that
1369 case, but I don't know how wise that would be in the long run. */
1370 return getuid ();
1373 unsigned
1374 getgid (void)
1376 return dflt_passwd.pw_gid;
1379 unsigned
1380 getegid (void)
1382 return getgid ();
1385 struct passwd *
1386 getpwuid (unsigned uid)
1388 if (uid == dflt_passwd.pw_uid)
1389 return &dflt_passwd;
1390 return NULL;
1393 struct group *
1394 getgrgid (gid_t gid)
1396 return &dflt_group;
1399 struct passwd *
1400 getpwnam (char *name)
1402 struct passwd *pw;
1404 pw = getpwuid (getuid ());
1405 if (!pw)
1406 return pw;
1408 if (xstrcasecmp (name, pw->pw_name))
1409 return NULL;
1411 return pw;
1414 static void
1415 init_user_info (void)
1417 /* Find the user's real name by opening the process token and
1418 looking up the name associated with the user-sid in that token.
1420 Use the relative portion of the identifier authority value from
1421 the user-sid as the user id value (same for group id using the
1422 primary group sid from the process token). */
1424 char uname[UNLEN+1], gname[GNLEN+1], domain[1025];
1425 DWORD ulength = sizeof (uname), dlength = sizeof (domain), needed;
1426 DWORD glength = sizeof (gname);
1427 HANDLE token = NULL;
1428 SID_NAME_USE user_type;
1429 unsigned char *buf = NULL;
1430 DWORD blen = 0;
1431 TOKEN_USER user_token;
1432 TOKEN_PRIMARY_GROUP group_token;
1433 BOOL result;
1435 result = open_process_token (GetCurrentProcess (), TOKEN_QUERY, &token);
1436 if (result)
1438 result = get_token_information (token, TokenUser, NULL, 0, &blen);
1439 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
1441 buf = xmalloc (blen);
1442 result = get_token_information (token, TokenUser,
1443 (LPVOID)buf, blen, &needed);
1444 if (result)
1446 memcpy (&user_token, buf, sizeof (user_token));
1447 result = lookup_account_sid (NULL, user_token.User.Sid,
1448 uname, &ulength,
1449 domain, &dlength, &user_type);
1452 else
1453 result = FALSE;
1455 if (result)
1457 strcpy (dflt_passwd.pw_name, uname);
1458 /* Determine a reasonable uid value. */
1459 if (xstrcasecmp ("administrator", uname) == 0)
1461 dflt_passwd.pw_uid = 500; /* well-known Administrator uid */
1462 dflt_passwd.pw_gid = 513; /* well-known None gid */
1464 else
1466 /* Use the last sub-authority value of the RID, the relative
1467 portion of the SID, as user/group ID. */
1468 dflt_passwd.pw_uid = get_rid (user_token.User.Sid);
1470 /* Get group id and name. */
1471 result = get_token_information (token, TokenPrimaryGroup,
1472 (LPVOID)buf, blen, &needed);
1473 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
1475 buf = xrealloc (buf, blen = needed);
1476 result = get_token_information (token, TokenPrimaryGroup,
1477 (LPVOID)buf, blen, &needed);
1479 if (result)
1481 memcpy (&group_token, buf, sizeof (group_token));
1482 dflt_passwd.pw_gid = get_rid (group_token.PrimaryGroup);
1483 dlength = sizeof (domain);
1484 /* If we can get at the real Primary Group name, use that.
1485 Otherwise, the default group name was already set to
1486 "None" in globals_of_w32. */
1487 if (lookup_account_sid (NULL, group_token.PrimaryGroup,
1488 gname, &glength, NULL, &dlength,
1489 &user_type))
1490 strcpy (dflt_group_name, gname);
1492 else
1493 dflt_passwd.pw_gid = dflt_passwd.pw_uid;
1496 /* If security calls are not supported (presumably because we
1497 are running under Windows 9X), fallback to this: */
1498 else if (GetUserName (uname, &ulength))
1500 strcpy (dflt_passwd.pw_name, uname);
1501 if (xstrcasecmp ("administrator", uname) == 0)
1502 dflt_passwd.pw_uid = 0;
1503 else
1504 dflt_passwd.pw_uid = 123;
1505 dflt_passwd.pw_gid = dflt_passwd.pw_uid;
1507 else
1509 strcpy (dflt_passwd.pw_name, "unknown");
1510 dflt_passwd.pw_uid = 123;
1511 dflt_passwd.pw_gid = 123;
1513 dflt_group.gr_gid = dflt_passwd.pw_gid;
1515 /* Ensure HOME and SHELL are defined. */
1516 if (getenv ("HOME") == NULL)
1517 emacs_abort ();
1518 if (getenv ("SHELL") == NULL)
1519 emacs_abort ();
1521 /* Set dir and shell from environment variables. */
1522 strcpy (dflt_passwd.pw_dir, getenv ("HOME"));
1523 strcpy (dflt_passwd.pw_shell, getenv ("SHELL"));
1525 xfree (buf);
1526 if (token)
1527 CloseHandle (token);
1531 random (void)
1533 /* rand () on NT gives us 15 random bits...hack together 30 bits. */
1534 return ((rand () << 15) | rand ());
1537 void
1538 srandom (int seed)
1540 srand (seed);
1543 /* Current codepage for encoding file names. */
1544 static int file_name_codepage;
1546 /* Return the maximum length in bytes of a multibyte character
1547 sequence encoded in the current ANSI codepage. This is required to
1548 correctly walk the encoded file names one character at a time. */
1549 static int
1550 max_filename_mbslen (void)
1552 /* A simple cache to avoid calling GetCPInfo every time we need to
1553 normalize a file name. The file-name encoding is not supposed to
1554 be changed too frequently, if ever. */
1555 static Lisp_Object last_file_name_encoding;
1556 static int last_max_mbslen;
1557 Lisp_Object current_encoding;
1559 current_encoding = Vfile_name_coding_system;
1560 if (NILP (current_encoding))
1561 current_encoding = Vdefault_file_name_coding_system;
1563 if (!EQ (last_file_name_encoding, current_encoding))
1565 CPINFO cp_info;
1567 last_file_name_encoding = current_encoding;
1568 /* Default to the current ANSI codepage. */
1569 file_name_codepage = w32_ansi_code_page;
1570 if (!NILP (current_encoding))
1572 char *cpname = SDATA (SYMBOL_NAME (current_encoding));
1573 char *cp = NULL, *end;
1574 int cpnum;
1576 if (strncmp (cpname, "cp", 2) == 0)
1577 cp = cpname + 2;
1578 else if (strncmp (cpname, "windows-", 8) == 0)
1579 cp = cpname + 8;
1581 if (cp)
1583 end = cp;
1584 cpnum = strtol (cp, &end, 10);
1585 if (cpnum && *end == '\0' && end - cp >= 2)
1586 file_name_codepage = cpnum;
1590 if (!file_name_codepage)
1591 file_name_codepage = CP_ACP; /* CP_ACP = 0, but let's not assume that */
1593 if (!GetCPInfo (file_name_codepage, &cp_info))
1595 file_name_codepage = CP_ACP;
1596 if (!GetCPInfo (file_name_codepage, &cp_info))
1597 emacs_abort ();
1599 last_max_mbslen = cp_info.MaxCharSize;
1602 return last_max_mbslen;
1605 /* Normalize filename by converting all path separators to
1606 the specified separator. Also conditionally convert upper
1607 case path name components to lower case. */
1609 static void
1610 normalize_filename (register char *fp, char path_sep, int multibyte)
1612 char sep;
1613 char *elem, *p2;
1614 int dbcs_p = max_filename_mbslen () > 1;
1616 /* Multibyte file names are in the Emacs internal representation, so
1617 we can traverse them by bytes with no problems. */
1618 if (multibyte)
1619 dbcs_p = 0;
1621 /* Always lower-case drive letters a-z, even if the filesystem
1622 preserves case in filenames.
1623 This is so filenames can be compared by string comparison
1624 functions that are case-sensitive. Even case-preserving filesystems
1625 do not distinguish case in drive letters. */
1626 if (dbcs_p)
1627 p2 = CharNextExA (file_name_codepage, fp, 0);
1628 else
1629 p2 = fp + 1;
1631 if (*p2 == ':' && *fp >= 'A' && *fp <= 'Z')
1633 *fp += 'a' - 'A';
1634 fp += 2;
1637 if (multibyte || NILP (Vw32_downcase_file_names))
1639 while (*fp)
1641 if (*fp == '/' || *fp == '\\')
1642 *fp = path_sep;
1643 if (!dbcs_p)
1644 fp++;
1645 else
1646 fp = CharNextExA (file_name_codepage, fp, 0);
1648 return;
1651 sep = path_sep; /* convert to this path separator */
1652 elem = fp; /* start of current path element */
1654 do {
1655 if (*fp >= 'a' && *fp <= 'z')
1656 elem = 0; /* don't convert this element */
1658 if (*fp == 0 || *fp == ':')
1660 sep = *fp; /* restore current separator (or 0) */
1661 *fp = '/'; /* after conversion of this element */
1664 if (*fp == '/' || *fp == '\\')
1666 if (elem && elem != fp)
1668 *fp = 0; /* temporary end of string */
1669 _mbslwr (elem); /* while we convert to lower case */
1671 *fp = sep; /* convert (or restore) path separator */
1672 elem = fp + 1; /* next element starts after separator */
1673 sep = path_sep;
1675 if (*fp)
1677 if (!dbcs_p)
1678 fp++;
1679 else
1680 fp = CharNextExA (file_name_codepage, fp, 0);
1682 } while (*fp);
1685 /* Destructively turn backslashes into slashes. MULTIBYTE non-zero
1686 means the file name is a multibyte string in Emacs's internal
1687 representation. */
1688 void
1689 dostounix_filename (register char *p, int multibyte)
1691 normalize_filename (p, '/', multibyte);
1694 /* Destructively turn slashes into backslashes. */
1695 void
1696 unixtodos_filename (register char *p)
1698 normalize_filename (p, '\\', 0);
1701 /* Remove all CR's that are followed by a LF.
1702 (From msdos.c...probably should figure out a way to share it,
1703 although this code isn't going to ever change.) */
1704 static int
1705 crlf_to_lf (register int n, register unsigned char *buf)
1707 unsigned char *np = buf;
1708 unsigned char *startp = buf;
1709 unsigned char *endp = buf + n;
1711 if (n == 0)
1712 return n;
1713 while (buf < endp - 1)
1715 if (*buf == 0x0d)
1717 if (*(++buf) != 0x0a)
1718 *np++ = 0x0d;
1720 else
1721 *np++ = *buf++;
1723 if (buf < endp)
1724 *np++ = *buf++;
1725 return np - startp;
1728 /* Parse the root part of file name, if present. Return length and
1729 optionally store pointer to char after root. */
1730 static int
1731 parse_root (char * name, char ** pPath)
1733 char * start = name;
1735 if (name == NULL)
1736 return 0;
1738 /* find the root name of the volume if given */
1739 if (isalpha (name[0]) && name[1] == ':')
1741 /* skip past drive specifier */
1742 name += 2;
1743 if (IS_DIRECTORY_SEP (name[0]))
1744 name++;
1746 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
1748 int slashes = 2;
1749 int dbcs_p = max_filename_mbslen () > 1;
1751 name += 2;
1754 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
1755 break;
1756 if (dbcs_p)
1757 name = CharNextExA (file_name_codepage, name, 0);
1758 else
1759 name++;
1761 while ( *name );
1762 if (IS_DIRECTORY_SEP (name[0]))
1763 name++;
1766 if (pPath)
1767 *pPath = name;
1769 return name - start;
1772 /* Get long base name for name; name is assumed to be absolute. */
1773 static int
1774 get_long_basename (char * name, char * buf, int size)
1776 WIN32_FIND_DATA find_data;
1777 HANDLE dir_handle;
1778 int len = 0;
1780 /* must be valid filename, no wild cards or other invalid characters */
1781 if (_mbspbrk (name, "*?|<>\""))
1782 return 0;
1784 dir_handle = FindFirstFile (name, &find_data);
1785 if (dir_handle != INVALID_HANDLE_VALUE)
1787 if ((len = strlen (find_data.cFileName)) < size)
1788 memcpy (buf, find_data.cFileName, len + 1);
1789 else
1790 len = 0;
1791 FindClose (dir_handle);
1793 return len;
1796 /* Get long name for file, if possible (assumed to be absolute). */
1797 BOOL
1798 w32_get_long_filename (char * name, char * buf, int size)
1800 char * o = buf;
1801 char * p;
1802 char * q;
1803 char full[ MAX_PATH ];
1804 int len;
1806 len = strlen (name);
1807 if (len >= MAX_PATH)
1808 return FALSE;
1810 /* Use local copy for destructive modification. */
1811 memcpy (full, name, len+1);
1812 unixtodos_filename (full);
1814 /* Copy root part verbatim. */
1815 len = parse_root (full, &p);
1816 memcpy (o, full, len);
1817 o += len;
1818 *o = '\0';
1819 size -= len;
1821 while (p != NULL && *p)
1823 q = p;
1824 p = _mbschr (q, '\\');
1825 if (p) *p = '\0';
1826 len = get_long_basename (full, o, size);
1827 if (len > 0)
1829 o += len;
1830 size -= len;
1831 if (p != NULL)
1833 *p++ = '\\';
1834 if (size < 2)
1835 return FALSE;
1836 *o++ = '\\';
1837 size--;
1838 *o = '\0';
1841 else
1842 return FALSE;
1845 return TRUE;
1848 static int
1849 is_unc_volume (const char *filename)
1851 const char *ptr = filename;
1853 if (!IS_DIRECTORY_SEP (ptr[0]) || !IS_DIRECTORY_SEP (ptr[1]) || !ptr[2])
1854 return 0;
1856 if (_mbspbrk (ptr + 2, "*?|<>\"\\/"))
1857 return 0;
1859 return 1;
1862 /* Emulate the Posix unsetenv. */
1864 unsetenv (const char *name)
1866 char *var;
1867 size_t name_len;
1868 int retval;
1870 if (name == NULL || *name == '\0' || strchr (name, '=') != NULL)
1872 errno = EINVAL;
1873 return -1;
1875 name_len = strlen (name);
1876 /* MS docs says an environment variable cannot be longer than 32K. */
1877 if (name_len > 32767)
1879 errno = ENOMEM;
1880 return 0;
1882 /* It is safe to use 'alloca' with 32K size, since the stack is at
1883 least 2MB, and we set it to 8MB in the link command line. */
1884 var = alloca (name_len + 2);
1885 strncpy (var, name, name_len);
1886 var[name_len++] = '=';
1887 var[name_len] = '\0';
1888 return _putenv (var);
1891 /* MS _putenv doesn't support removing a variable when the argument
1892 does not include the '=' character, so we fix that here. */
1894 sys_putenv (char *str)
1896 const char *const name_end = strchr (str, '=');
1898 if (name_end == NULL)
1900 /* Remove the variable from the environment. */
1901 return unsetenv (str);
1904 return _putenv (str);
1907 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
1909 LPBYTE
1910 w32_get_resource (char *key, LPDWORD lpdwtype)
1912 LPBYTE lpvalue;
1913 HKEY hrootkey = NULL;
1914 DWORD cbData;
1916 /* Check both the current user and the local machine to see if
1917 we have any resources. */
1919 if (RegOpenKeyEx (HKEY_CURRENT_USER, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
1921 lpvalue = NULL;
1923 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
1924 && (lpvalue = xmalloc (cbData)) != NULL
1925 && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
1927 RegCloseKey (hrootkey);
1928 return (lpvalue);
1931 xfree (lpvalue);
1933 RegCloseKey (hrootkey);
1936 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
1938 lpvalue = NULL;
1940 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
1941 && (lpvalue = xmalloc (cbData)) != NULL
1942 && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
1944 RegCloseKey (hrootkey);
1945 return (lpvalue);
1948 xfree (lpvalue);
1950 RegCloseKey (hrootkey);
1953 return (NULL);
1956 char *get_emacs_configuration (void);
1958 void
1959 init_environment (char ** argv)
1961 static const char * const tempdirs[] = {
1962 "$TMPDIR", "$TEMP", "$TMP", "c:/"
1965 int i;
1967 const int imax = sizeof (tempdirs) / sizeof (tempdirs[0]);
1969 /* Make sure they have a usable $TMPDIR. Many Emacs functions use
1970 temporary files and assume "/tmp" if $TMPDIR is unset, which
1971 will break on DOS/Windows. Refuse to work if we cannot find
1972 a directory, not even "c:/", usable for that purpose. */
1973 for (i = 0; i < imax ; i++)
1975 const char *tmp = tempdirs[i];
1977 if (*tmp == '$')
1978 tmp = getenv (tmp + 1);
1979 /* Note that `access' can lie to us if the directory resides on a
1980 read-only filesystem, like CD-ROM or a write-protected floppy.
1981 The only way to be really sure is to actually create a file and
1982 see if it succeeds. But I think that's too much to ask. */
1984 /* MSVCRT's _access crashes with D_OK. */
1985 if (tmp && faccessat (AT_FDCWD, tmp, D_OK, AT_EACCESS) == 0)
1987 char * var = alloca (strlen (tmp) + 8);
1988 sprintf (var, "TMPDIR=%s", tmp);
1989 _putenv (strdup (var));
1990 break;
1993 if (i >= imax)
1994 cmd_error_internal
1995 (Fcons (Qerror,
1996 Fcons (build_string ("no usable temporary directories found!!"),
1997 Qnil)),
1998 "While setting TMPDIR: ");
2000 /* Check for environment variables and use registry settings if they
2001 don't exist. Fallback on default values where applicable. */
2003 int i;
2004 LPBYTE lpval;
2005 DWORD dwType;
2006 char locale_name[32];
2007 char default_home[MAX_PATH];
2008 int appdata = 0;
2010 static const struct env_entry
2012 char * name;
2013 char * def_value;
2014 } dflt_envvars[] =
2016 /* If the default value is NULL, we will use the value from the
2017 outside environment or the Registry, but will not push the
2018 variable into the Emacs environment if it is defined neither
2019 in the Registry nor in the outside environment. */
2020 {"HOME", "C:/"},
2021 {"PRELOAD_WINSOCK", NULL},
2022 {"emacs_dir", "C:/emacs"},
2023 {"EMACSLOADPATH", NULL},
2024 {"SHELL", "cmdproxy.exe"}, /* perhaps it is somewhere on PATH */
2025 {"EMACSDATA", NULL},
2026 {"EMACSPATH", NULL},
2027 {"INFOPATH", NULL},
2028 {"EMACSDOC", NULL},
2029 {"TERM", "cmd"},
2030 {"LANG", NULL},
2033 #define N_ENV_VARS sizeof (dflt_envvars)/sizeof (dflt_envvars[0])
2035 /* We need to copy dflt_envvars[] and work on the copy because we
2036 don't want the dumped Emacs to inherit the values of
2037 environment variables we saw during dumping (which could be on
2038 a different system). The defaults above must be left intact. */
2039 struct env_entry env_vars[N_ENV_VARS];
2041 for (i = 0; i < N_ENV_VARS; i++)
2042 env_vars[i] = dflt_envvars[i];
2044 /* For backwards compatibility, check if a .emacs file exists in C:/
2045 If not, then we can try to default to the appdata directory under the
2046 user's profile, which is more likely to be writable. */
2047 if (!check_existing ("C:/.emacs"))
2049 HRESULT profile_result;
2050 /* Dynamically load ShGetFolderPath, as it won't exist on versions
2051 of Windows 95 and NT4 that have not been updated to include
2052 MSIE 5. */
2053 ShGetFolderPath_fn get_folder_path;
2054 get_folder_path = (ShGetFolderPath_fn)
2055 GetProcAddress (GetModuleHandle ("shell32.dll"), "SHGetFolderPathA");
2057 if (get_folder_path != NULL)
2059 profile_result = get_folder_path (NULL, CSIDL_APPDATA, NULL,
2060 0, default_home);
2062 /* If we can't get the appdata dir, revert to old behavior. */
2063 if (profile_result == S_OK)
2065 env_vars[0].def_value = default_home;
2066 appdata = 1;
2071 /* Get default locale info and use it for LANG. */
2072 if (GetLocaleInfo (LOCALE_USER_DEFAULT,
2073 LOCALE_SABBREVLANGNAME | LOCALE_USE_CP_ACP,
2074 locale_name, sizeof (locale_name)))
2076 for (i = 0; i < N_ENV_VARS; i++)
2078 if (strcmp (env_vars[i].name, "LANG") == 0)
2080 env_vars[i].def_value = locale_name;
2081 break;
2086 #define SET_ENV_BUF_SIZE (4 * MAX_PATH) /* to cover EMACSLOADPATH */
2088 /* Treat emacs_dir specially: set it unconditionally based on our
2089 location. */
2091 char *p;
2092 char modname[MAX_PATH];
2094 if (!GetModuleFileName (NULL, modname, MAX_PATH))
2095 emacs_abort ();
2096 if ((p = _mbsrchr (modname, '\\')) == NULL)
2097 emacs_abort ();
2098 *p = 0;
2100 if ((p = _mbsrchr (modname, '\\'))
2101 /* From bin means installed Emacs, from src means uninstalled. */
2102 && (xstrcasecmp (p, "\\bin") == 0 || xstrcasecmp (p, "\\src") == 0))
2104 char buf[SET_ENV_BUF_SIZE];
2105 int within_build_tree = xstrcasecmp (p, "\\src") == 0;
2107 *p = 0;
2108 for (p = modname; *p; p = CharNext (p))
2109 if (*p == '\\') *p = '/';
2111 _snprintf (buf, sizeof (buf)-1, "emacs_dir=%s", modname);
2112 _putenv (strdup (buf));
2113 /* If we are running from the Posix-like build tree, define
2114 SHELL to point to our own cmdproxy. The loop below will
2115 then disregard PATH_EXEC and the default value. */
2116 if (within_build_tree)
2118 _snprintf (buf, sizeof (buf) - 1,
2119 "SHELL=%s/nt/cmdproxy.exe", modname);
2120 _putenv (strdup (buf));
2123 /* Handle running emacs from the build directory: src/oo-spd/i386/ */
2125 /* FIXME: should use substring of get_emacs_configuration ().
2126 But I don't think the Windows build supports alpha, mips etc
2127 anymore, so have taken the easy option for now. */
2128 else if (p && (xstrcasecmp (p, "\\i386") == 0
2129 || xstrcasecmp (p, "\\AMD64") == 0))
2131 *p = 0;
2132 p = _mbsrchr (modname, '\\');
2133 if (p != NULL)
2135 *p = 0;
2136 p = _mbsrchr (modname, '\\');
2137 if (p && xstrcasecmp (p, "\\src") == 0)
2139 char buf[SET_ENV_BUF_SIZE];
2141 *p = 0;
2142 for (p = modname; *p; p = CharNext (p))
2143 if (*p == '\\') *p = '/';
2145 _snprintf (buf, sizeof (buf)-1, "emacs_dir=%s", modname);
2146 _putenv (strdup (buf));
2152 for (i = 0; i < N_ENV_VARS; i++)
2154 if (!getenv (env_vars[i].name))
2156 int dont_free = 0;
2157 char bufc[SET_ENV_BUF_SIZE];
2159 if ((lpval = w32_get_resource (env_vars[i].name, &dwType)) == NULL
2160 /* Also ignore empty environment variables. */
2161 || *lpval == 0)
2163 xfree (lpval);
2164 dont_free = 1;
2165 if (strcmp (env_vars[i].name, "SHELL") == 0)
2167 /* Look for cmdproxy.exe in every directory in
2168 PATH_EXEC. FIXME: This does not find cmdproxy
2169 in nt/ when we run uninstalled. */
2170 char fname[MAX_PATH];
2171 const char *pstart = PATH_EXEC, *pend;
2173 do {
2174 pend = _mbschr (pstart, ';');
2175 if (!pend)
2176 pend = pstart + strlen (pstart);
2177 /* Be defensive against series of ;;; characters. */
2178 if (pend > pstart)
2180 strncpy (fname, pstart, pend - pstart);
2181 fname[pend - pstart] = '/';
2182 strcpy (&fname[pend - pstart + 1], "cmdproxy.exe");
2183 ExpandEnvironmentStrings ((LPSTR) fname, bufc,
2184 sizeof (bufc));
2185 if (check_existing (bufc))
2187 lpval = bufc;
2188 dwType = REG_SZ;
2189 break;
2192 if (*pend)
2193 pstart = pend + 1;
2194 else
2195 pstart = pend;
2196 if (!*pstart)
2198 /* If not found in any directory, use the
2199 default as the last resort. */
2200 lpval = env_vars[i].def_value;
2201 dwType = REG_EXPAND_SZ;
2203 } while (*pstart);
2205 else
2207 lpval = env_vars[i].def_value;
2208 dwType = REG_EXPAND_SZ;
2210 if (strcmp (env_vars[i].name, "HOME") == 0 && !appdata)
2211 Vdelayed_warnings_list
2212 = Fcons (listn (CONSTYPE_HEAP, 2,
2213 intern ("initialization"),
2214 build_string ("Setting HOME to C:\\ by default is deprecated")),
2215 Vdelayed_warnings_list);
2218 if (lpval)
2220 char buf1[SET_ENV_BUF_SIZE], buf2[SET_ENV_BUF_SIZE];
2222 if (dwType == REG_EXPAND_SZ)
2223 ExpandEnvironmentStrings ((LPSTR) lpval, buf1, sizeof (buf1));
2224 else if (dwType == REG_SZ)
2225 strcpy (buf1, lpval);
2226 if (dwType == REG_EXPAND_SZ || dwType == REG_SZ)
2228 _snprintf (buf2, sizeof (buf2)-1, "%s=%s", env_vars[i].name,
2229 buf1);
2230 _putenv (strdup (buf2));
2233 if (!dont_free)
2234 xfree (lpval);
2240 /* Rebuild system configuration to reflect invoking system. */
2241 Vsystem_configuration = build_string (EMACS_CONFIGURATION);
2243 /* Another special case: on NT, the PATH variable is actually named
2244 "Path" although cmd.exe (perhaps NT itself) arranges for
2245 environment variable lookup and setting to be case insensitive.
2246 However, Emacs assumes a fully case sensitive environment, so we
2247 need to change "Path" to "PATH" to match the expectations of
2248 various elisp packages. We do this by the sneaky method of
2249 modifying the string in the C runtime environ entry.
2251 The same applies to COMSPEC. */
2253 char ** envp;
2255 for (envp = environ; *envp; envp++)
2256 if (_strnicmp (*envp, "PATH=", 5) == 0)
2257 memcpy (*envp, "PATH=", 5);
2258 else if (_strnicmp (*envp, "COMSPEC=", 8) == 0)
2259 memcpy (*envp, "COMSPEC=", 8);
2262 /* Remember the initial working directory for getcwd. */
2263 /* FIXME: Do we need to resolve possible symlinks in startup_dir?
2264 Does it matter anywhere in Emacs? */
2265 if (!GetCurrentDirectory (MAXPATHLEN, startup_dir))
2266 emacs_abort ();
2269 static char modname[MAX_PATH];
2271 if (!GetModuleFileName (NULL, modname, MAX_PATH))
2272 emacs_abort ();
2273 argv[0] = modname;
2276 /* Determine if there is a middle mouse button, to allow parse_button
2277 to decide whether right mouse events should be mouse-2 or
2278 mouse-3. */
2279 w32_num_mouse_buttons = GetSystemMetrics (SM_CMOUSEBUTTONS);
2281 init_user_info ();
2284 /* Called from expand-file-name when default-directory is not a string. */
2286 char *
2287 emacs_root_dir (void)
2289 static char root_dir[FILENAME_MAX];
2290 const char *p;
2292 p = getenv ("emacs_dir");
2293 if (p == NULL)
2294 emacs_abort ();
2295 strcpy (root_dir, p);
2296 root_dir[parse_root (root_dir, NULL)] = '\0';
2297 dostounix_filename (root_dir, 0);
2298 return root_dir;
2301 /* We don't have scripts to automatically determine the system configuration
2302 for Emacs before it's compiled, and we don't want to have to make the
2303 user enter it, so we define EMACS_CONFIGURATION to invoke this runtime
2304 routine. */
2306 char *
2307 get_emacs_configuration (void)
2309 char *arch, *oem, *os;
2310 int build_num;
2311 static char configuration_buffer[32];
2313 /* Determine the processor type. */
2314 switch (get_processor_type ())
2317 #ifdef PROCESSOR_INTEL_386
2318 case PROCESSOR_INTEL_386:
2319 case PROCESSOR_INTEL_486:
2320 case PROCESSOR_INTEL_PENTIUM:
2321 #ifdef _WIN64
2322 arch = "amd64";
2323 #else
2324 arch = "i386";
2325 #endif
2326 break;
2327 #endif
2328 #ifdef PROCESSOR_AMD_X8664
2329 case PROCESSOR_AMD_X8664:
2330 arch = "amd64";
2331 break;
2332 #endif
2334 #ifdef PROCESSOR_MIPS_R2000
2335 case PROCESSOR_MIPS_R2000:
2336 case PROCESSOR_MIPS_R3000:
2337 case PROCESSOR_MIPS_R4000:
2338 arch = "mips";
2339 break;
2340 #endif
2342 #ifdef PROCESSOR_ALPHA_21064
2343 case PROCESSOR_ALPHA_21064:
2344 arch = "alpha";
2345 break;
2346 #endif
2348 default:
2349 arch = "unknown";
2350 break;
2353 /* Use the OEM field to reflect the compiler/library combination. */
2354 #ifdef _MSC_VER
2355 #define COMPILER_NAME "msvc"
2356 #else
2357 #ifdef __GNUC__
2358 #define COMPILER_NAME "mingw"
2359 #else
2360 #define COMPILER_NAME "unknown"
2361 #endif
2362 #endif
2363 oem = COMPILER_NAME;
2365 switch (osinfo_cache.dwPlatformId) {
2366 case VER_PLATFORM_WIN32_NT:
2367 os = "nt";
2368 build_num = osinfo_cache.dwBuildNumber;
2369 break;
2370 case VER_PLATFORM_WIN32_WINDOWS:
2371 if (osinfo_cache.dwMinorVersion == 0) {
2372 os = "windows95";
2373 } else {
2374 os = "windows98";
2376 build_num = LOWORD (osinfo_cache.dwBuildNumber);
2377 break;
2378 case VER_PLATFORM_WIN32s:
2379 /* Not supported, should not happen. */
2380 os = "windows32s";
2381 build_num = LOWORD (osinfo_cache.dwBuildNumber);
2382 break;
2383 default:
2384 os = "unknown";
2385 build_num = 0;
2386 break;
2389 if (osinfo_cache.dwPlatformId == VER_PLATFORM_WIN32_NT) {
2390 sprintf (configuration_buffer, "%s-%s-%s%d.%d.%d", arch, oem, os,
2391 get_w32_major_version (), get_w32_minor_version (), build_num);
2392 } else {
2393 sprintf (configuration_buffer, "%s-%s-%s.%d", arch, oem, os, build_num);
2396 return configuration_buffer;
2399 char *
2400 get_emacs_configuration_options (void)
2402 static char *options_buffer;
2403 char cv[32]; /* Enough for COMPILER_VERSION. */
2404 char *options[] = {
2405 cv, /* To be filled later. */
2406 #ifdef EMACSDEBUG
2407 " --no-opt",
2408 #endif
2409 #ifdef ENABLE_CHECKING
2410 " --enable-checking",
2411 #endif
2412 /* configure.bat already sets USER_CFLAGS and USER_LDFLAGS
2413 with a starting space to save work here. */
2414 #ifdef USER_CFLAGS
2415 " --cflags", USER_CFLAGS,
2416 #endif
2417 #ifdef USER_LDFLAGS
2418 " --ldflags", USER_LDFLAGS,
2419 #endif
2420 NULL
2422 size_t size = 0;
2423 int i;
2425 /* Work out the effective configure options for this build. */
2426 #ifdef _MSC_VER
2427 #define COMPILER_VERSION "--with-msvc (%d.%02d)", _MSC_VER / 100, _MSC_VER % 100
2428 #else
2429 #ifdef __GNUC__
2430 #define COMPILER_VERSION "--with-gcc (%d.%d)", __GNUC__, __GNUC_MINOR__
2431 #else
2432 #define COMPILER_VERSION ""
2433 #endif
2434 #endif
2436 if (_snprintf (cv, sizeof (cv) - 1, COMPILER_VERSION) < 0)
2437 return "Error: not enough space for compiler version";
2438 cv[sizeof (cv) - 1] = '\0';
2440 for (i = 0; options[i]; i++)
2441 size += strlen (options[i]);
2443 options_buffer = xmalloc (size + 1);
2444 options_buffer[0] = '\0';
2446 for (i = 0; options[i]; i++)
2447 strcat (options_buffer, options[i]);
2449 return options_buffer;
2453 #include <sys/timeb.h>
2455 /* Emulate gettimeofday (Ulrich Leodolter, 1/11/95). */
2457 gettimeofday (struct timeval *__restrict tv, struct timezone *__restrict tz)
2459 struct _timeb tb;
2460 _ftime (&tb);
2462 tv->tv_sec = tb.time;
2463 tv->tv_usec = tb.millitm * 1000L;
2464 /* Implementation note: _ftime sometimes doesn't update the dstflag
2465 according to the new timezone when the system timezone is
2466 changed. We could fix that by using GetSystemTime and
2467 GetTimeZoneInformation, but that doesn't seem necessary, since
2468 Emacs always calls gettimeofday with the 2nd argument NULL (see
2469 current_emacs_time). */
2470 if (tz)
2472 tz->tz_minuteswest = tb.timezone; /* minutes west of Greenwich */
2473 tz->tz_dsttime = tb.dstflag; /* type of dst correction */
2475 return 0;
2478 /* Emulate fdutimens. */
2480 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2481 TIMESPEC[0] and TIMESPEC[1], respectively.
2482 FD must be either negative -- in which case it is ignored --
2483 or a file descriptor that is open on FILE.
2484 If FD is nonnegative, then FILE can be NULL, which means
2485 use just futimes instead of utimes.
2486 If TIMESPEC is null, FAIL.
2487 Return 0 on success, -1 (setting errno) on failure. */
2490 fdutimens (int fd, char const *file, struct timespec const timespec[2])
2492 struct _utimbuf ut;
2494 if (!timespec)
2496 errno = ENOSYS;
2497 return -1;
2499 if (fd < 0 && !file)
2501 errno = EBADF;
2502 return -1;
2504 ut.actime = timespec[0].tv_sec;
2505 ut.modtime = timespec[1].tv_sec;
2506 if (fd >= 0)
2507 return _futime (fd, &ut);
2508 else
2509 return _utime (file, &ut);
2513 /* ------------------------------------------------------------------------- */
2514 /* IO support and wrapper functions for the Windows API. */
2515 /* ------------------------------------------------------------------------- */
2517 /* Place a wrapper around the MSVC version of ctime. It returns NULL
2518 on network directories, so we handle that case here.
2519 (Ulrich Leodolter, 1/11/95). */
2520 char *
2521 sys_ctime (const time_t *t)
2523 char *str = (char *) ctime (t);
2524 return (str ? str : "Sun Jan 01 00:00:00 1970");
2527 /* Emulate sleep...we could have done this with a define, but that
2528 would necessitate including windows.h in the files that used it.
2529 This is much easier. */
2530 void
2531 sys_sleep (int seconds)
2533 Sleep (seconds * 1000);
2536 /* Internal MSVC functions for low-level descriptor munging */
2537 extern int __cdecl _set_osfhnd (int fd, long h);
2538 extern int __cdecl _free_osfhnd (int fd);
2540 /* parallel array of private info on file handles */
2541 filedesc fd_info [ MAXDESC ];
2543 typedef struct volume_info_data {
2544 struct volume_info_data * next;
2546 /* time when info was obtained */
2547 DWORD timestamp;
2549 /* actual volume info */
2550 char * root_dir;
2551 DWORD serialnum;
2552 DWORD maxcomp;
2553 DWORD flags;
2554 char * name;
2555 char * type;
2556 } volume_info_data;
2558 /* Global referenced by various functions. */
2559 static volume_info_data volume_info;
2561 /* Vector to indicate which drives are local and fixed (for which cached
2562 data never expires). */
2563 static BOOL fixed_drives[26];
2565 /* Consider cached volume information to be stale if older than 10s,
2566 at least for non-local drives. Info for fixed drives is never stale. */
2567 #define DRIVE_INDEX( c ) ( (c) <= 'Z' ? (c) - 'A' : (c) - 'a' )
2568 #define VOLINFO_STILL_VALID( root_dir, info ) \
2569 ( ( isalpha (root_dir[0]) && \
2570 fixed_drives[ DRIVE_INDEX (root_dir[0]) ] ) \
2571 || GetTickCount () - info->timestamp < 10000 )
2573 /* Cache support functions. */
2575 /* Simple linked list with linear search is sufficient. */
2576 static volume_info_data *volume_cache = NULL;
2578 static volume_info_data *
2579 lookup_volume_info (char * root_dir)
2581 volume_info_data * info;
2583 for (info = volume_cache; info; info = info->next)
2584 if (xstrcasecmp (info->root_dir, root_dir) == 0)
2585 break;
2586 return info;
2589 static void
2590 add_volume_info (char * root_dir, volume_info_data * info)
2592 info->root_dir = xstrdup (root_dir);
2593 info->next = volume_cache;
2594 volume_cache = info;
2598 /* Wrapper for GetVolumeInformation, which uses caching to avoid
2599 performance penalty (~2ms on 486 for local drives, 7.5ms for local
2600 cdrom drive, ~5-10ms or more for remote drives on LAN). */
2601 static volume_info_data *
2602 GetCachedVolumeInformation (char * root_dir)
2604 volume_info_data * info;
2605 char default_root[ MAX_PATH ];
2607 /* NULL for root_dir means use root from current directory. */
2608 if (root_dir == NULL)
2610 if (GetCurrentDirectory (MAX_PATH, default_root) == 0)
2611 return NULL;
2612 parse_root (default_root, &root_dir);
2613 *root_dir = 0;
2614 root_dir = default_root;
2617 /* Local fixed drives can be cached permanently. Removable drives
2618 cannot be cached permanently, since the volume name and serial
2619 number (if nothing else) can change. Remote drives should be
2620 treated as if they are removable, since there is no sure way to
2621 tell whether they are or not. Also, the UNC association of drive
2622 letters mapped to remote volumes can be changed at any time (even
2623 by other processes) without notice.
2625 As a compromise, so we can benefit from caching info for remote
2626 volumes, we use a simple expiry mechanism to invalidate cache
2627 entries that are more than ten seconds old. */
2629 #if 0
2630 /* No point doing this, because WNetGetConnection is even slower than
2631 GetVolumeInformation, consistently taking ~50ms on a 486 (FWIW,
2632 GetDriveType is about the only call of this type which does not
2633 involve network access, and so is extremely quick). */
2635 /* Map drive letter to UNC if remote. */
2636 if (isalpha (root_dir[0]) && !fixed[DRIVE_INDEX (root_dir[0])])
2638 char remote_name[ 256 ];
2639 char drive[3] = { root_dir[0], ':' };
2641 if (WNetGetConnection (drive, remote_name, sizeof (remote_name))
2642 == NO_ERROR)
2643 /* do something */ ;
2645 #endif
2647 info = lookup_volume_info (root_dir);
2649 if (info == NULL || ! VOLINFO_STILL_VALID (root_dir, info))
2651 char name[ 256 ];
2652 DWORD serialnum;
2653 DWORD maxcomp;
2654 DWORD flags;
2655 char type[ 256 ];
2657 /* Info is not cached, or is stale. */
2658 if (!GetVolumeInformation (root_dir,
2659 name, sizeof (name),
2660 &serialnum,
2661 &maxcomp,
2662 &flags,
2663 type, sizeof (type)))
2664 return NULL;
2666 /* Cache the volume information for future use, overwriting existing
2667 entry if present. */
2668 if (info == NULL)
2670 info = xmalloc (sizeof (volume_info_data));
2671 add_volume_info (root_dir, info);
2673 else
2675 xfree (info->name);
2676 xfree (info->type);
2679 info->name = xstrdup (name);
2680 info->serialnum = serialnum;
2681 info->maxcomp = maxcomp;
2682 info->flags = flags;
2683 info->type = xstrdup (type);
2684 info->timestamp = GetTickCount ();
2687 return info;
2690 /* Get information on the volume where NAME is held; set path pointer to
2691 start of pathname in NAME (past UNC header\volume header if present),
2692 if pPath is non-NULL.
2694 Note: if NAME includes symlinks, the information is for the volume
2695 of the symlink, not of its target. That's because, even though
2696 GetVolumeInformation returns information about the symlink target
2697 of its argument, we only pass the root directory to
2698 GetVolumeInformation, not the full NAME. */
2699 static int
2700 get_volume_info (const char * name, const char ** pPath)
2702 char temp[MAX_PATH];
2703 char *rootname = NULL; /* default to current volume */
2704 volume_info_data * info;
2706 if (name == NULL)
2707 return FALSE;
2709 /* Find the root name of the volume if given. */
2710 if (isalpha (name[0]) && name[1] == ':')
2712 rootname = temp;
2713 temp[0] = *name++;
2714 temp[1] = *name++;
2715 temp[2] = '\\';
2716 temp[3] = 0;
2718 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
2720 char *str = temp;
2721 int slashes = 4;
2722 int dbcs_p = max_filename_mbslen () > 1;
2724 rootname = temp;
2727 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
2728 break;
2729 if (!dbcs_p)
2730 *str++ = *name++;
2731 else
2733 const char *p = name;
2735 name = CharNextExA (file_name_codepage, name, 0);
2736 memcpy (str, p, name - p);
2737 str += name - p;
2740 while ( *name );
2742 *str++ = '\\';
2743 *str = 0;
2746 if (pPath)
2747 *pPath = name;
2749 info = GetCachedVolumeInformation (rootname);
2750 if (info != NULL)
2752 /* Set global referenced by other functions. */
2753 volume_info = *info;
2754 return TRUE;
2756 return FALSE;
2759 /* Determine if volume is FAT format (ie. only supports short 8.3
2760 names); also set path pointer to start of pathname in name, if
2761 pPath is non-NULL. */
2762 static int
2763 is_fat_volume (const char * name, const char ** pPath)
2765 if (get_volume_info (name, pPath))
2766 return (volume_info.maxcomp == 12);
2767 return FALSE;
2770 /* Map filename to a valid 8.3 name if necessary.
2771 The result is a pointer to a static buffer, so CAVEAT EMPTOR! */
2772 const char *
2773 map_w32_filename (const char * name, const char ** pPath)
2775 static char shortname[MAX_PATH];
2776 char * str = shortname;
2777 char c;
2778 char * path;
2779 const char * save_name = name;
2781 if (strlen (name) >= MAX_PATH)
2783 /* Return a filename which will cause callers to fail. */
2784 strcpy (shortname, "?");
2785 return shortname;
2788 if (is_fat_volume (name, (const char **)&path)) /* truncate to 8.3 */
2790 register int left = 8; /* maximum number of chars in part */
2791 register int extn = 0; /* extension added? */
2792 register int dots = 2; /* maximum number of dots allowed */
2794 while (name < path)
2795 *str++ = *name++; /* skip past UNC header */
2797 while ((c = *name++))
2799 switch ( c )
2801 case ':':
2802 case '\\':
2803 case '/':
2804 *str++ = (c == ':' ? ':' : '\\');
2805 extn = 0; /* reset extension flags */
2806 dots = 2; /* max 2 dots */
2807 left = 8; /* max length 8 for main part */
2808 break;
2809 case '.':
2810 if ( dots )
2812 /* Convert path components of the form .xxx to _xxx,
2813 but leave . and .. as they are. This allows .emacs
2814 to be read as _emacs, for example. */
2816 if (! *name ||
2817 *name == '.' ||
2818 IS_DIRECTORY_SEP (*name))
2820 *str++ = '.';
2821 dots--;
2823 else
2825 *str++ = '_';
2826 left--;
2827 dots = 0;
2830 else if ( !extn )
2832 *str++ = '.';
2833 extn = 1; /* we've got an extension */
2834 left = 3; /* 3 chars in extension */
2836 else
2838 /* any embedded dots after the first are converted to _ */
2839 *str++ = '_';
2841 break;
2842 case '~':
2843 case '#': /* don't lose these, they're important */
2844 if ( ! left )
2845 str[-1] = c; /* replace last character of part */
2846 /* FALLTHRU */
2847 default:
2848 if ( left )
2850 *str++ = tolower (c); /* map to lower case (looks nicer) */
2851 left--;
2852 dots = 0; /* started a path component */
2854 break;
2857 *str = '\0';
2859 else
2861 strcpy (shortname, name);
2862 unixtodos_filename (shortname);
2865 if (pPath)
2866 *pPath = shortname + (path - save_name);
2868 return shortname;
2871 static int
2872 is_exec (const char * name)
2874 char * p = strrchr (name, '.');
2875 return
2876 (p != NULL
2877 && (xstrcasecmp (p, ".exe") == 0 ||
2878 xstrcasecmp (p, ".com") == 0 ||
2879 xstrcasecmp (p, ".bat") == 0 ||
2880 xstrcasecmp (p, ".cmd") == 0));
2883 /* Emulate the Unix directory procedures opendir, closedir,
2884 and readdir. We can't use the procedures supplied in sysdep.c,
2885 so we provide them here. */
2887 struct dirent dir_static; /* simulated directory contents */
2888 static HANDLE dir_find_handle = INVALID_HANDLE_VALUE;
2889 static int dir_is_fat;
2890 static char dir_pathname[MAXPATHLEN+1];
2891 static WIN32_FIND_DATA dir_find_data;
2893 /* Support shares on a network resource as subdirectories of a read-only
2894 root directory. */
2895 static HANDLE wnet_enum_handle = INVALID_HANDLE_VALUE;
2896 static HANDLE open_unc_volume (const char *);
2897 static char *read_unc_volume (HANDLE, char *, int);
2898 static void close_unc_volume (HANDLE);
2900 DIR *
2901 opendir (const char *filename)
2903 DIR *dirp;
2905 /* Opening is done by FindFirstFile. However, a read is inherent to
2906 this operation, so we defer the open until read time. */
2908 if (dir_find_handle != INVALID_HANDLE_VALUE)
2909 return NULL;
2910 if (wnet_enum_handle != INVALID_HANDLE_VALUE)
2911 return NULL;
2913 /* Note: We don't support traversal of UNC volumes via symlinks.
2914 Doing so would mean punishing 99.99% of use cases by resolving
2915 all the possible symlinks in FILENAME, recursively. */
2916 if (is_unc_volume (filename))
2918 wnet_enum_handle = open_unc_volume (filename);
2919 if (wnet_enum_handle == INVALID_HANDLE_VALUE)
2920 return NULL;
2923 if (!(dirp = (DIR *) malloc (sizeof (DIR))))
2924 return NULL;
2926 dirp->dd_fd = 0;
2927 dirp->dd_loc = 0;
2928 dirp->dd_size = 0;
2930 strncpy (dir_pathname, map_w32_filename (filename, NULL), MAXPATHLEN);
2931 dir_pathname[MAXPATHLEN] = '\0';
2932 /* Note: We don't support symlinks to file names on FAT volumes.
2933 Doing so would mean punishing 99.99% of use cases by resolving
2934 all the possible symlinks in FILENAME, recursively. */
2935 dir_is_fat = is_fat_volume (filename, NULL);
2937 return dirp;
2940 void
2941 closedir (DIR *dirp)
2943 /* If we have a find-handle open, close it. */
2944 if (dir_find_handle != INVALID_HANDLE_VALUE)
2946 FindClose (dir_find_handle);
2947 dir_find_handle = INVALID_HANDLE_VALUE;
2949 else if (wnet_enum_handle != INVALID_HANDLE_VALUE)
2951 close_unc_volume (wnet_enum_handle);
2952 wnet_enum_handle = INVALID_HANDLE_VALUE;
2954 xfree ((char *) dirp);
2957 struct dirent *
2958 readdir (DIR *dirp)
2960 int downcase = !NILP (Vw32_downcase_file_names);
2962 if (wnet_enum_handle != INVALID_HANDLE_VALUE)
2964 if (!read_unc_volume (wnet_enum_handle,
2965 dir_find_data.cFileName,
2966 MAX_PATH))
2967 return NULL;
2969 /* If we aren't dir_finding, do a find-first, otherwise do a find-next. */
2970 else if (dir_find_handle == INVALID_HANDLE_VALUE)
2972 char filename[MAXNAMLEN + 3];
2973 int ln;
2974 int dbcs_p = max_filename_mbslen () > 1;
2976 strcpy (filename, dir_pathname);
2977 ln = strlen (filename) - 1;
2978 if (!dbcs_p)
2980 if (!IS_DIRECTORY_SEP (filename[ln]))
2981 strcat (filename, "\\");
2983 else
2985 char *end = filename + ln + 1;
2986 char *last_char = CharPrevExA (file_name_codepage, filename, end, 0);
2988 if (!IS_DIRECTORY_SEP (*last_char))
2989 strcat (filename, "\\");
2991 strcat (filename, "*");
2993 /* Note: No need to resolve symlinks in FILENAME, because
2994 FindFirst opens the directory that is the target of a
2995 symlink. */
2996 dir_find_handle = FindFirstFile (filename, &dir_find_data);
2998 if (dir_find_handle == INVALID_HANDLE_VALUE)
2999 return NULL;
3001 else
3003 if (!FindNextFile (dir_find_handle, &dir_find_data))
3004 return NULL;
3007 /* Emacs never uses this value, so don't bother making it match
3008 value returned by stat(). */
3009 dir_static.d_ino = 1;
3011 strcpy (dir_static.d_name, dir_find_data.cFileName);
3013 /* If the file name in cFileName[] includes `?' characters, it means
3014 the original file name used characters that cannot be represented
3015 by the current ANSI codepage. To avoid total lossage, retrieve
3016 the short 8+3 alias of the long file name. */
3017 if (_mbspbrk (dir_static.d_name, "?"))
3019 strcpy (dir_static.d_name, dir_find_data.cAlternateFileName);
3020 downcase = 1; /* 8+3 aliases are returned in all caps */
3022 dir_static.d_namlen = strlen (dir_static.d_name);
3023 dir_static.d_reclen = sizeof (struct dirent) - MAXNAMLEN + 3 +
3024 dir_static.d_namlen - dir_static.d_namlen % 4;
3026 /* If the file name in cFileName[] includes `?' characters, it means
3027 the original file name used characters that cannot be represented
3028 by the current ANSI codepage. To avoid total lossage, retrieve
3029 the short 8+3 alias of the long file name. */
3030 if (_mbspbrk (dir_find_data.cFileName, "?"))
3032 strcpy (dir_static.d_name, dir_find_data.cAlternateFileName);
3033 /* 8+3 aliases are returned in all caps, which could break
3034 various alists that look at filenames' extensions. */
3035 downcase = 1;
3037 else
3038 strcpy (dir_static.d_name, dir_find_data.cFileName);
3039 dir_static.d_namlen = strlen (dir_static.d_name);
3040 if (dir_is_fat)
3041 _mbslwr (dir_static.d_name);
3042 else if (downcase)
3044 register char *p;
3045 int dbcs_p = max_filename_mbslen () > 1;
3046 for (p = dir_static.d_name; *p; )
3048 if (*p >= 'a' && *p <= 'z')
3049 break;
3050 if (dbcs_p)
3051 p = CharNextExA (file_name_codepage, p, 0);
3052 else
3053 p++;
3055 if (!*p)
3056 _mbslwr (dir_static.d_name);
3059 return &dir_static;
3062 static HANDLE
3063 open_unc_volume (const char *path)
3065 NETRESOURCE nr;
3066 HANDLE henum;
3067 int result;
3069 nr.dwScope = RESOURCE_GLOBALNET;
3070 nr.dwType = RESOURCETYPE_DISK;
3071 nr.dwDisplayType = RESOURCEDISPLAYTYPE_SERVER;
3072 nr.dwUsage = RESOURCEUSAGE_CONTAINER;
3073 nr.lpLocalName = NULL;
3074 nr.lpRemoteName = (LPSTR)map_w32_filename (path, NULL);
3075 nr.lpComment = NULL;
3076 nr.lpProvider = NULL;
3078 result = WNetOpenEnum (RESOURCE_GLOBALNET, RESOURCETYPE_DISK,
3079 RESOURCEUSAGE_CONNECTABLE, &nr, &henum);
3081 if (result == NO_ERROR)
3082 return henum;
3083 else
3084 return INVALID_HANDLE_VALUE;
3087 static char *
3088 read_unc_volume (HANDLE henum, char *readbuf, int size)
3090 DWORD count;
3091 int result;
3092 DWORD bufsize = 512;
3093 char *buffer;
3094 char *ptr;
3095 int dbcs_p = max_filename_mbslen () > 1;
3097 count = 1;
3098 buffer = alloca (bufsize);
3099 result = WNetEnumResource (henum, &count, buffer, &bufsize);
3100 if (result != NO_ERROR)
3101 return NULL;
3103 /* WNetEnumResource returns \\resource\share...skip forward to "share". */
3104 ptr = ((LPNETRESOURCE) buffer)->lpRemoteName;
3105 ptr += 2;
3106 if (!dbcs_p)
3107 while (*ptr && !IS_DIRECTORY_SEP (*ptr)) ptr++;
3108 else
3110 while (*ptr && !IS_DIRECTORY_SEP (*ptr))
3111 ptr = CharNextExA (file_name_codepage, ptr, 0);
3113 ptr++;
3115 strncpy (readbuf, ptr, size);
3116 return readbuf;
3119 static void
3120 close_unc_volume (HANDLE henum)
3122 if (henum != INVALID_HANDLE_VALUE)
3123 WNetCloseEnum (henum);
3126 static DWORD
3127 unc_volume_file_attributes (const char *path)
3129 HANDLE henum;
3130 DWORD attrs;
3132 henum = open_unc_volume (path);
3133 if (henum == INVALID_HANDLE_VALUE)
3134 return -1;
3136 attrs = FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_DIRECTORY;
3138 close_unc_volume (henum);
3140 return attrs;
3143 /* Ensure a network connection is authenticated. */
3144 static void
3145 logon_network_drive (const char *path)
3147 NETRESOURCE resource;
3148 char share[MAX_PATH];
3149 int n_slashes;
3150 char drive[4];
3151 UINT drvtype;
3152 char *p;
3153 int dbcs_p;
3155 if (IS_DIRECTORY_SEP (path[0]) && IS_DIRECTORY_SEP (path[1]))
3156 drvtype = DRIVE_REMOTE;
3157 else if (path[0] == '\0' || path[1] != ':')
3158 drvtype = GetDriveType (NULL);
3159 else
3161 drive[0] = path[0];
3162 drive[1] = ':';
3163 drive[2] = '\\';
3164 drive[3] = '\0';
3165 drvtype = GetDriveType (drive);
3168 /* Only logon to networked drives. */
3169 if (drvtype != DRIVE_REMOTE)
3170 return;
3172 n_slashes = 2;
3173 strncpy (share, path, MAX_PATH);
3174 /* Truncate to just server and share name. */
3175 dbcs_p = max_filename_mbslen () > 1;
3176 for (p = share + 2; *p && p < share + MAX_PATH; )
3178 if (IS_DIRECTORY_SEP (*p) && ++n_slashes > 3)
3180 *p = '\0';
3181 break;
3183 if (dbcs_p)
3184 p = CharNextExA (file_name_codepage, p, 0);
3185 else
3186 p++;
3189 resource.dwType = RESOURCETYPE_DISK;
3190 resource.lpLocalName = NULL;
3191 resource.lpRemoteName = share;
3192 resource.lpProvider = NULL;
3194 WNetAddConnection2 (&resource, NULL, NULL, CONNECT_INTERACTIVE);
3197 /* Emulate faccessat(2). */
3199 faccessat (int dirfd, const char * path, int mode, int flags)
3201 DWORD attributes;
3203 if (dirfd != AT_FDCWD
3204 && !(IS_DIRECTORY_SEP (path[0])
3205 || IS_DEVICE_SEP (path[1])))
3207 errno = EBADF;
3208 return -1;
3211 /* MSVCRT implementation of 'access' doesn't recognize D_OK, and its
3212 newer versions blow up when passed D_OK. */
3213 path = map_w32_filename (path, NULL);
3214 /* If the last element of PATH is a symlink, we need to resolve it
3215 to get the attributes of its target file. Note: any symlinks in
3216 PATH elements other than the last one are transparently resolved
3217 by GetFileAttributes below. */
3218 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0
3219 && (flags & AT_SYMLINK_NOFOLLOW) == 0)
3220 path = chase_symlinks (path);
3222 if ((attributes = GetFileAttributes (path)) == -1)
3224 DWORD w32err = GetLastError ();
3226 switch (w32err)
3228 case ERROR_INVALID_NAME:
3229 case ERROR_BAD_PATHNAME:
3230 if (is_unc_volume (path))
3232 attributes = unc_volume_file_attributes (path);
3233 if (attributes == -1)
3235 errno = EACCES;
3236 return -1;
3238 break;
3240 /* FALLTHROUGH */
3241 case ERROR_FILE_NOT_FOUND:
3242 case ERROR_BAD_NETPATH:
3243 errno = ENOENT;
3244 break;
3245 default:
3246 errno = EACCES;
3247 break;
3249 return -1;
3251 if ((mode & X_OK) != 0
3252 && !(is_exec (path) || (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0))
3254 errno = EACCES;
3255 return -1;
3257 if ((mode & W_OK) != 0 && (attributes & FILE_ATTRIBUTE_READONLY) != 0)
3259 errno = EACCES;
3260 return -1;
3262 if ((mode & D_OK) != 0 && (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
3264 errno = EACCES;
3265 return -1;
3267 return 0;
3270 /* Shadow some MSVC runtime functions to map requests for long filenames
3271 to reasonable short names if necessary. This was originally added to
3272 permit running Emacs on NT 3.1 on a FAT partition, which doesn't support
3273 long file names. */
3276 sys_chdir (const char * path)
3278 return _chdir (map_w32_filename (path, NULL));
3282 sys_chmod (const char * path, int mode)
3284 path = chase_symlinks (map_w32_filename (path, NULL));
3285 return _chmod (path, mode);
3289 sys_creat (const char * path, int mode)
3291 return _creat (map_w32_filename (path, NULL), mode);
3294 FILE *
3295 sys_fopen (const char * path, const char * mode)
3297 int fd;
3298 int oflag;
3299 const char * mode_save = mode;
3301 /* Force all file handles to be non-inheritable. This is necessary to
3302 ensure child processes don't unwittingly inherit handles that might
3303 prevent future file access. */
3305 if (mode[0] == 'r')
3306 oflag = O_RDONLY;
3307 else if (mode[0] == 'w' || mode[0] == 'a')
3308 oflag = O_WRONLY | O_CREAT | O_TRUNC;
3309 else
3310 return NULL;
3312 /* Only do simplistic option parsing. */
3313 while (*++mode)
3314 if (mode[0] == '+')
3316 oflag &= ~(O_RDONLY | O_WRONLY);
3317 oflag |= O_RDWR;
3319 else if (mode[0] == 'b')
3321 oflag &= ~O_TEXT;
3322 oflag |= O_BINARY;
3324 else if (mode[0] == 't')
3326 oflag &= ~O_BINARY;
3327 oflag |= O_TEXT;
3329 else break;
3331 fd = _open (map_w32_filename (path, NULL), oflag | _O_NOINHERIT, 0644);
3332 if (fd < 0)
3333 return NULL;
3335 return _fdopen (fd, mode_save);
3338 /* This only works on NTFS volumes, but is useful to have. */
3340 sys_link (const char * old, const char * new)
3342 HANDLE fileh;
3343 int result = -1;
3344 char oldname[MAX_PATH], newname[MAX_PATH];
3346 if (old == NULL || new == NULL)
3348 errno = ENOENT;
3349 return -1;
3352 strcpy (oldname, map_w32_filename (old, NULL));
3353 strcpy (newname, map_w32_filename (new, NULL));
3355 fileh = CreateFile (oldname, 0, 0, NULL, OPEN_EXISTING,
3356 FILE_FLAG_BACKUP_SEMANTICS, NULL);
3357 if (fileh != INVALID_HANDLE_VALUE)
3359 int wlen;
3361 /* Confusingly, the "alternate" stream name field does not apply
3362 when restoring a hard link, and instead contains the actual
3363 stream data for the link (ie. the name of the link to create).
3364 The WIN32_STREAM_ID structure before the cStreamName field is
3365 the stream header, which is then immediately followed by the
3366 stream data. */
3368 struct {
3369 WIN32_STREAM_ID wid;
3370 WCHAR wbuffer[MAX_PATH]; /* extra space for link name */
3371 } data;
3373 wlen = MultiByteToWideChar (CP_ACP, MB_PRECOMPOSED, newname, -1,
3374 data.wid.cStreamName, MAX_PATH);
3375 if (wlen > 0)
3377 LPVOID context = NULL;
3378 DWORD wbytes = 0;
3380 data.wid.dwStreamId = BACKUP_LINK;
3381 data.wid.dwStreamAttributes = 0;
3382 data.wid.Size.LowPart = wlen * sizeof (WCHAR);
3383 data.wid.Size.HighPart = 0;
3384 data.wid.dwStreamNameSize = 0;
3386 if (BackupWrite (fileh, (LPBYTE)&data,
3387 offsetof (WIN32_STREAM_ID, cStreamName)
3388 + data.wid.Size.LowPart,
3389 &wbytes, FALSE, FALSE, &context)
3390 && BackupWrite (fileh, NULL, 0, &wbytes, TRUE, FALSE, &context))
3392 /* succeeded */
3393 result = 0;
3395 else
3397 /* Should try mapping GetLastError to errno; for now just
3398 indicate a general error (eg. links not supported). */
3399 errno = EINVAL; // perhaps EMLINK?
3403 CloseHandle (fileh);
3405 else
3406 errno = ENOENT;
3408 return result;
3412 sys_mkdir (const char * path)
3414 return _mkdir (map_w32_filename (path, NULL));
3418 sys_open (const char * path, int oflag, int mode)
3420 const char* mpath = map_w32_filename (path, NULL);
3421 int res = -1;
3423 /* If possible, try to open file without _O_CREAT, to be able to
3424 write to existing hidden and system files. Force all file
3425 handles to be non-inheritable. */
3426 if ((oflag & (_O_CREAT | _O_EXCL)) != (_O_CREAT | _O_EXCL))
3427 res = _open (mpath, (oflag & ~_O_CREAT) | _O_NOINHERIT, mode);
3428 if (res < 0)
3429 res = _open (mpath, oflag | _O_NOINHERIT, mode);
3431 return res;
3434 /* Implementation of mkostemp for MS-Windows, to avoid race conditions
3435 when using mktemp.
3437 Standard algorithm for generating a temporary file name seems to be
3438 use pid or tid with a letter on the front (in place of the 6 X's)
3439 and cycle through the letters to find a unique name. We extend
3440 that to allow any reasonable character as the first of the 6 X's,
3441 so that the number of simultaneously used temporary files will be
3442 greater. */
3445 mkostemp (char * template, int flags)
3447 char * p;
3448 int i, fd = -1;
3449 unsigned uid = GetCurrentThreadId ();
3450 int save_errno = errno;
3451 static char first_char[] = "abcdefghijklmnopqrstuvwyz0123456789!%-_@#";
3453 errno = EINVAL;
3454 if (template == NULL)
3455 return -1;
3457 p = template + strlen (template);
3458 i = 5;
3459 /* replace up to the last 5 X's with uid in decimal */
3460 while (--p >= template && p[0] == 'X' && --i >= 0)
3462 p[0] = '0' + uid % 10;
3463 uid /= 10;
3466 if (i < 0 && p[0] == 'X')
3468 i = 0;
3471 p[0] = first_char[i];
3472 if ((fd = sys_open (template,
3473 flags | _O_CREAT | _O_EXCL | _O_RDWR,
3474 S_IRUSR | S_IWUSR)) >= 0
3475 || errno != EEXIST)
3477 if (fd >= 0)
3478 errno = save_errno;
3479 return fd;
3482 while (++i < sizeof (first_char));
3485 /* Template is badly formed or else we can't generate a unique name. */
3486 return -1;
3490 fchmod (int fd, mode_t mode)
3492 return 0;
3496 sys_rename_replace (const char *oldname, const char *newname, BOOL force)
3498 BOOL result;
3499 char temp[MAX_PATH];
3500 int newname_dev;
3501 int oldname_dev;
3503 /* MoveFile on Windows 95 doesn't correctly change the short file name
3504 alias in a number of circumstances (it is not easy to predict when
3505 just by looking at oldname and newname, unfortunately). In these
3506 cases, renaming through a temporary name avoids the problem.
3508 A second problem on Windows 95 is that renaming through a temp name when
3509 newname is uppercase fails (the final long name ends up in
3510 lowercase, although the short alias might be uppercase) UNLESS the
3511 long temp name is not 8.3.
3513 So, on Windows 95 we always rename through a temp name, and we make sure
3514 the temp name has a long extension to ensure correct renaming. */
3516 strcpy (temp, map_w32_filename (oldname, NULL));
3518 /* volume_info is set indirectly by map_w32_filename. */
3519 oldname_dev = volume_info.serialnum;
3521 if (os_subtype == OS_9X)
3523 char * o;
3524 char * p;
3525 int i = 0;
3527 oldname = map_w32_filename (oldname, NULL);
3528 if ((o = strrchr (oldname, '\\')))
3529 o++;
3530 else
3531 o = (char *) oldname;
3533 if ((p = strrchr (temp, '\\')))
3534 p++;
3535 else
3536 p = temp;
3540 /* Force temp name to require a manufactured 8.3 alias - this
3541 seems to make the second rename work properly. */
3542 sprintf (p, "_.%s.%u", o, i);
3543 i++;
3544 result = rename (oldname, temp);
3546 /* This loop must surely terminate! */
3547 while (result < 0 && errno == EEXIST);
3548 if (result < 0)
3549 return -1;
3552 /* If FORCE, emulate Unix behavior - newname is deleted if it already exists
3553 (at least if it is a file; don't do this for directories).
3555 Since we mustn't do this if we are just changing the case of the
3556 file name (we would end up deleting the file we are trying to
3557 rename!), we let rename detect if the destination file already
3558 exists - that way we avoid the possible pitfalls of trying to
3559 determine ourselves whether two names really refer to the same
3560 file, which is not always possible in the general case. (Consider
3561 all the permutations of shared or subst'd drives, etc.) */
3563 newname = map_w32_filename (newname, NULL);
3565 /* volume_info is set indirectly by map_w32_filename. */
3566 newname_dev = volume_info.serialnum;
3568 result = rename (temp, newname);
3570 if (result < 0 && force)
3572 DWORD w32err = GetLastError ();
3574 if (errno == EACCES
3575 && newname_dev != oldname_dev)
3577 /* The implementation of `rename' on Windows does not return
3578 errno = EXDEV when you are moving a directory to a
3579 different storage device (ex. logical disk). It returns
3580 EACCES instead. So here we handle such situations and
3581 return EXDEV. */
3582 DWORD attributes;
3584 if ((attributes = GetFileAttributes (temp)) != -1
3585 && (attributes & FILE_ATTRIBUTE_DIRECTORY))
3586 errno = EXDEV;
3588 else if (errno == EEXIST)
3590 if (_chmod (newname, 0666) != 0)
3591 return result;
3592 if (_unlink (newname) != 0)
3593 return result;
3594 result = rename (temp, newname);
3596 else if (w32err == ERROR_PRIVILEGE_NOT_HELD
3597 && is_symlink (temp))
3599 /* This is Windows prohibiting the user from creating a
3600 symlink in another place, since that requires
3601 privileges. */
3602 errno = EPERM;
3606 return result;
3610 sys_rename (char const *old, char const *new)
3612 return sys_rename_replace (old, new, TRUE);
3616 sys_rmdir (const char * path)
3618 return _rmdir (map_w32_filename (path, NULL));
3622 sys_unlink (const char * path)
3624 path = map_w32_filename (path, NULL);
3626 /* On Unix, unlink works without write permission. */
3627 _chmod (path, 0666);
3628 return _unlink (path);
3631 static FILETIME utc_base_ft;
3632 static ULONGLONG utc_base; /* In 100ns units */
3633 static int init = 0;
3635 #define FILETIME_TO_U64(result, ft) \
3636 do { \
3637 ULARGE_INTEGER uiTemp; \
3638 uiTemp.LowPart = (ft).dwLowDateTime; \
3639 uiTemp.HighPart = (ft).dwHighDateTime; \
3640 result = uiTemp.QuadPart; \
3641 } while (0)
3643 static void
3644 initialize_utc_base (void)
3646 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
3647 SYSTEMTIME st;
3649 st.wYear = 1970;
3650 st.wMonth = 1;
3651 st.wDay = 1;
3652 st.wHour = 0;
3653 st.wMinute = 0;
3654 st.wSecond = 0;
3655 st.wMilliseconds = 0;
3657 SystemTimeToFileTime (&st, &utc_base_ft);
3658 FILETIME_TO_U64 (utc_base, utc_base_ft);
3661 static time_t
3662 convert_time (FILETIME ft)
3664 ULONGLONG tmp;
3666 if (!init)
3668 initialize_utc_base ();
3669 init = 1;
3672 if (CompareFileTime (&ft, &utc_base_ft) < 0)
3673 return 0;
3675 FILETIME_TO_U64 (tmp, ft);
3676 return (time_t) ((tmp - utc_base) / 10000000L);
3679 static void
3680 convert_from_time_t (time_t time, FILETIME * pft)
3682 ULARGE_INTEGER tmp;
3684 if (!init)
3686 initialize_utc_base ();
3687 init = 1;
3690 /* time in 100ns units since 1-Jan-1601 */
3691 tmp.QuadPart = (ULONGLONG) time * 10000000L + utc_base;
3692 pft->dwHighDateTime = tmp.HighPart;
3693 pft->dwLowDateTime = tmp.LowPart;
3696 #if 0
3697 /* No reason to keep this; faking inode values either by hashing or even
3698 using the file index from GetInformationByHandle, is not perfect and
3699 so by default Emacs doesn't use the inode values on Windows.
3700 Instead, we now determine file-truename correctly (except for
3701 possible drive aliasing etc). */
3703 /* Modified version of "PJW" algorithm (see the "Dragon" compiler book). */
3704 static unsigned
3705 hashval (const unsigned char * str)
3707 unsigned h = 0;
3708 while (*str)
3710 h = (h << 4) + *str++;
3711 h ^= (h >> 28);
3713 return h;
3716 /* Return the hash value of the canonical pathname, excluding the
3717 drive/UNC header, to get a hopefully unique inode number. */
3718 static DWORD
3719 generate_inode_val (const char * name)
3721 char fullname[ MAX_PATH ];
3722 char * p;
3723 unsigned hash;
3725 /* Get the truly canonical filename, if it exists. (Note: this
3726 doesn't resolve aliasing due to subst commands, or recognize hard
3727 links. */
3728 if (!w32_get_long_filename ((char *)name, fullname, MAX_PATH))
3729 emacs_abort ();
3731 parse_root (fullname, &p);
3732 /* Normal W32 filesystems are still case insensitive. */
3733 _strlwr (p);
3734 return hashval (p);
3737 #endif
3739 static PSECURITY_DESCRIPTOR
3740 get_file_security_desc_by_handle (HANDLE h)
3742 PSECURITY_DESCRIPTOR psd = NULL;
3743 DWORD err;
3744 SECURITY_INFORMATION si = OWNER_SECURITY_INFORMATION
3745 | GROUP_SECURITY_INFORMATION /* | DACL_SECURITY_INFORMATION */ ;
3747 err = get_security_info (h, SE_FILE_OBJECT, si,
3748 NULL, NULL, NULL, NULL, &psd);
3749 if (err != ERROR_SUCCESS)
3750 return NULL;
3752 return psd;
3755 static PSECURITY_DESCRIPTOR
3756 get_file_security_desc_by_name (const char *fname)
3758 PSECURITY_DESCRIPTOR psd = NULL;
3759 DWORD sd_len, err;
3760 SECURITY_INFORMATION si = OWNER_SECURITY_INFORMATION
3761 | GROUP_SECURITY_INFORMATION /* | DACL_SECURITY_INFORMATION */ ;
3763 if (!get_file_security (fname, si, psd, 0, &sd_len))
3765 err = GetLastError ();
3766 if (err != ERROR_INSUFFICIENT_BUFFER)
3767 return NULL;
3770 psd = xmalloc (sd_len);
3771 if (!get_file_security (fname, si, psd, sd_len, &sd_len))
3773 xfree (psd);
3774 return NULL;
3777 return psd;
3780 static DWORD
3781 get_rid (PSID sid)
3783 unsigned n_subauthorities;
3785 /* Use the last sub-authority value of the RID, the relative
3786 portion of the SID, as user/group ID. */
3787 n_subauthorities = *get_sid_sub_authority_count (sid);
3788 if (n_subauthorities < 1)
3789 return 0; /* the "World" RID */
3790 return *get_sid_sub_authority (sid, n_subauthorities - 1);
3793 /* Caching SID and account values for faster lokup. */
3795 struct w32_id {
3796 unsigned rid;
3797 struct w32_id *next;
3798 char name[GNLEN+1];
3799 unsigned char sid[FLEXIBLE_ARRAY_MEMBER];
3802 static struct w32_id *w32_idlist;
3804 static int
3805 w32_cached_id (PSID sid, unsigned *id, char *name)
3807 struct w32_id *tail, *found;
3809 for (found = NULL, tail = w32_idlist; tail; tail = tail->next)
3811 if (equal_sid ((PSID)tail->sid, sid))
3813 found = tail;
3814 break;
3817 if (found)
3819 *id = found->rid;
3820 strcpy (name, found->name);
3821 return 1;
3823 else
3824 return 0;
3827 static void
3828 w32_add_to_cache (PSID sid, unsigned id, char *name)
3830 DWORD sid_len;
3831 struct w32_id *new_entry;
3833 /* We don't want to leave behind stale cache from when Emacs was
3834 dumped. */
3835 if (initialized)
3837 sid_len = get_length_sid (sid);
3838 new_entry = xmalloc (offsetof (struct w32_id, sid) + sid_len);
3839 if (new_entry)
3841 new_entry->rid = id;
3842 strcpy (new_entry->name, name);
3843 copy_sid (sid_len, (PSID)new_entry->sid, sid);
3844 new_entry->next = w32_idlist;
3845 w32_idlist = new_entry;
3850 #define UID 1
3851 #define GID 2
3853 static int
3854 get_name_and_id (PSECURITY_DESCRIPTOR psd, unsigned *id, char *nm, int what)
3856 PSID sid = NULL;
3857 BOOL dflt;
3858 SID_NAME_USE ignore;
3859 char name[UNLEN+1];
3860 DWORD name_len = sizeof (name);
3861 char domain[1024];
3862 DWORD domain_len = sizeof (domain);
3863 int use_dflt = 0;
3864 int result;
3866 if (what == UID)
3867 result = get_security_descriptor_owner (psd, &sid, &dflt);
3868 else if (what == GID)
3869 result = get_security_descriptor_group (psd, &sid, &dflt);
3870 else
3871 result = 0;
3873 if (!result || !is_valid_sid (sid))
3874 use_dflt = 1;
3875 else if (!w32_cached_id (sid, id, nm))
3877 if (!lookup_account_sid (NULL, sid, name, &name_len,
3878 domain, &domain_len, &ignore)
3879 || name_len > UNLEN+1)
3880 use_dflt = 1;
3881 else
3883 *id = get_rid (sid);
3884 strcpy (nm, name);
3885 w32_add_to_cache (sid, *id, name);
3888 return use_dflt;
3891 static void
3892 get_file_owner_and_group (PSECURITY_DESCRIPTOR psd, struct stat *st)
3894 int dflt_usr = 0, dflt_grp = 0;
3896 if (!psd)
3898 dflt_usr = 1;
3899 dflt_grp = 1;
3901 else
3903 if (get_name_and_id (psd, &st->st_uid, st->st_uname, UID))
3904 dflt_usr = 1;
3905 if (get_name_and_id (psd, &st->st_gid, st->st_gname, GID))
3906 dflt_grp = 1;
3908 /* Consider files to belong to current user/group, if we cannot get
3909 more accurate information. */
3910 if (dflt_usr)
3912 st->st_uid = dflt_passwd.pw_uid;
3913 strcpy (st->st_uname, dflt_passwd.pw_name);
3915 if (dflt_grp)
3917 st->st_gid = dflt_passwd.pw_gid;
3918 strcpy (st->st_gname, dflt_group.gr_name);
3922 /* Return non-zero if NAME is a potentially slow filesystem. */
3924 is_slow_fs (const char *name)
3926 char drive_root[4];
3927 UINT devtype;
3929 if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
3930 devtype = DRIVE_REMOTE; /* assume UNC name is remote */
3931 else if (!(strlen (name) >= 2 && IS_DEVICE_SEP (name[1])))
3932 devtype = GetDriveType (NULL); /* use root of current drive */
3933 else
3935 /* GetDriveType needs the root directory of the drive. */
3936 strncpy (drive_root, name, 2);
3937 drive_root[2] = '\\';
3938 drive_root[3] = '\0';
3939 devtype = GetDriveType (drive_root);
3941 return !(devtype == DRIVE_FIXED || devtype == DRIVE_RAMDISK);
3944 /* If this is non-zero, the caller wants accurate information about
3945 file's owner and group, which could be expensive to get. */
3946 int w32_stat_get_owner_group;
3948 /* MSVC stat function can't cope with UNC names and has other bugs, so
3949 replace it with our own. This also allows us to calculate consistent
3950 inode values and owner/group without hacks in the main Emacs code. */
3952 static int
3953 stat_worker (const char * path, struct stat * buf, int follow_symlinks)
3955 char *name, *save_name, *r;
3956 WIN32_FIND_DATA wfd;
3957 HANDLE fh;
3958 unsigned __int64 fake_inode = 0;
3959 int permission;
3960 int len;
3961 int rootdir = FALSE;
3962 PSECURITY_DESCRIPTOR psd = NULL;
3963 int is_a_symlink = 0;
3964 DWORD file_flags = FILE_FLAG_BACKUP_SEMANTICS;
3965 DWORD access_rights = 0;
3966 DWORD fattrs = 0, serialnum = 0, fs_high = 0, fs_low = 0, nlinks = 1;
3967 FILETIME ctime, atime, wtime;
3968 int dbcs_p;
3970 if (path == NULL || buf == NULL)
3972 errno = EFAULT;
3973 return -1;
3976 save_name = name = (char *) map_w32_filename (path, &path);
3977 /* Must be valid filename, no wild cards or other invalid
3978 characters. We use _mbspbrk to support multibyte strings that
3979 might look to strpbrk as if they included literal *, ?, and other
3980 characters mentioned below that are disallowed by Windows
3981 filesystems. */
3982 if (_mbspbrk (name, "*?|<>\""))
3984 errno = ENOENT;
3985 return -1;
3988 /* Remove trailing directory separator, unless name is the root
3989 directory of a drive or UNC volume in which case ensure there
3990 is a trailing separator. */
3991 len = strlen (name);
3992 name = strcpy (alloca (len + 2), name);
3994 /* Avoid a somewhat costly call to is_symlink if the filesystem
3995 doesn't support symlinks. */
3996 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
3997 is_a_symlink = is_symlink (name);
3999 /* Plan A: Open the file and get all the necessary information via
4000 the resulting handle. This solves several issues in one blow:
4002 . retrieves attributes for the target of a symlink, if needed
4003 . gets attributes of root directories and symlinks pointing to
4004 root directories, thus avoiding the need for special-casing
4005 these and detecting them by examining the file-name format
4006 . retrieves more accurate attributes (e.g., non-zero size for
4007 some directories, esp. directories that are junction points)
4008 . correctly resolves "c:/..", "/.." and similar file names
4009 . avoids run-time penalties for 99% of use cases
4011 Plan A is always tried first, unless the user asked not to (but
4012 if the file is a symlink and we need to follow links, we try Plan
4013 A even if the user asked not to).
4015 If Plan A fails, we go to Plan B (below), where various
4016 potentially expensive techniques must be used to handle "special"
4017 files such as UNC volumes etc. */
4018 if (!(NILP (Vw32_get_true_file_attributes)
4019 || (EQ (Vw32_get_true_file_attributes, Qlocal) && is_slow_fs (name)))
4020 /* Following symlinks requires getting the info by handle. */
4021 || (is_a_symlink && follow_symlinks))
4023 BY_HANDLE_FILE_INFORMATION info;
4025 if (is_a_symlink && !follow_symlinks)
4026 file_flags |= FILE_FLAG_OPEN_REPARSE_POINT;
4027 /* READ_CONTROL access rights are required to get security info
4028 by handle. But if the OS doesn't support security in the
4029 first place, we don't need to try. */
4030 if (is_windows_9x () != TRUE)
4031 access_rights |= READ_CONTROL;
4033 fh = CreateFile (name, access_rights, 0, NULL, OPEN_EXISTING,
4034 file_flags, NULL);
4035 /* If CreateFile fails with READ_CONTROL, try again with zero as
4036 access rights. */
4037 if (fh == INVALID_HANDLE_VALUE && access_rights)
4038 fh = CreateFile (name, 0, 0, NULL, OPEN_EXISTING,
4039 file_flags, NULL);
4040 if (fh == INVALID_HANDLE_VALUE)
4041 goto no_true_file_attributes;
4043 /* This is more accurate in terms of getting the correct number
4044 of links, but is quite slow (it is noticeable when Emacs is
4045 making a list of file name completions). */
4046 if (GetFileInformationByHandle (fh, &info))
4048 nlinks = info.nNumberOfLinks;
4049 /* Might as well use file index to fake inode values, but this
4050 is not guaranteed to be unique unless we keep a handle open
4051 all the time (even then there are situations where it is
4052 not unique). Reputedly, there are at most 48 bits of info
4053 (on NTFS, presumably less on FAT). */
4054 fake_inode = info.nFileIndexHigh;
4055 fake_inode <<= 32;
4056 fake_inode += info.nFileIndexLow;
4057 serialnum = info.dwVolumeSerialNumber;
4058 fs_high = info.nFileSizeHigh;
4059 fs_low = info.nFileSizeLow;
4060 ctime = info.ftCreationTime;
4061 atime = info.ftLastAccessTime;
4062 wtime = info.ftLastWriteTime;
4063 fattrs = info.dwFileAttributes;
4065 else
4067 /* We don't go to Plan B here, because it's not clear that
4068 it's a good idea. The only known use case where
4069 CreateFile succeeds, but GetFileInformationByHandle fails
4070 (with ERROR_INVALID_FUNCTION) is for character devices
4071 such as NUL, PRN, etc. For these, switching to Plan B is
4072 a net loss, because we lose the character device
4073 attribute returned by GetFileType below (FindFirstFile
4074 doesn't set that bit in the attributes), and the other
4075 fields don't make sense for character devices anyway.
4076 Emacs doesn't really care for non-file entities in the
4077 context of l?stat, so neither do we. */
4079 /* w32err is assigned so one could put a breakpoint here and
4080 examine its value, when GetFileInformationByHandle
4081 fails. */
4082 DWORD w32err = GetLastError ();
4084 switch (w32err)
4086 case ERROR_FILE_NOT_FOUND: /* can this ever happen? */
4087 errno = ENOENT;
4088 return -1;
4092 /* Test for a symlink before testing for a directory, since
4093 symlinks to directories have the directory bit set, but we
4094 don't want them to appear as directories. */
4095 if (is_a_symlink && !follow_symlinks)
4096 buf->st_mode = S_IFLNK;
4097 else if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
4098 buf->st_mode = S_IFDIR;
4099 else
4101 DWORD ftype = GetFileType (fh);
4103 switch (ftype)
4105 case FILE_TYPE_DISK:
4106 buf->st_mode = S_IFREG;
4107 break;
4108 case FILE_TYPE_PIPE:
4109 buf->st_mode = S_IFIFO;
4110 break;
4111 case FILE_TYPE_CHAR:
4112 case FILE_TYPE_UNKNOWN:
4113 default:
4114 buf->st_mode = S_IFCHR;
4117 /* We produce the fallback owner and group data, based on the
4118 current user that runs Emacs, in the following cases:
4120 . caller didn't request owner and group info
4121 . this is Windows 9X
4122 . getting security by handle failed, and we need to produce
4123 information for the target of a symlink (this is better
4124 than producing a potentially misleading info about the
4125 symlink itself)
4127 If getting security by handle fails, and we don't need to
4128 resolve symlinks, we try getting security by name. */
4129 if (!w32_stat_get_owner_group || is_windows_9x () == TRUE)
4130 get_file_owner_and_group (NULL, buf);
4131 else
4133 psd = get_file_security_desc_by_handle (fh);
4134 if (psd)
4136 get_file_owner_and_group (psd, buf);
4137 LocalFree (psd);
4139 else if (!(is_a_symlink && follow_symlinks))
4141 psd = get_file_security_desc_by_name (name);
4142 get_file_owner_and_group (psd, buf);
4143 xfree (psd);
4145 else
4146 get_file_owner_and_group (NULL, buf);
4148 CloseHandle (fh);
4150 else
4152 no_true_file_attributes:
4153 /* Plan B: Either getting a handle on the file failed, or the
4154 caller explicitly asked us to not bother making this
4155 information more accurate.
4157 Implementation note: In Plan B, we never bother to resolve
4158 symlinks, even if we got here because we tried Plan A and
4159 failed. That's because, even if the caller asked for extra
4160 precision by setting Vw32_get_true_file_attributes to t,
4161 resolving symlinks requires acquiring a file handle to the
4162 symlink, which we already know will fail. And if the user
4163 did not ask for extra precision, resolving symlinks will fly
4164 in the face of that request, since the user then wants the
4165 lightweight version of the code. */
4166 dbcs_p = max_filename_mbslen () > 1;
4167 rootdir = (path >= save_name + len - 1
4168 && (IS_DIRECTORY_SEP (*path) || *path == 0));
4170 /* If name is "c:/.." or "/.." then stat "c:/" or "/". */
4171 r = IS_DEVICE_SEP (name[1]) ? &name[2] : name;
4172 if (IS_DIRECTORY_SEP (r[0])
4173 && r[1] == '.' && r[2] == '.' && r[3] == '\0')
4174 r[1] = r[2] = '\0';
4176 /* Note: If NAME is a symlink to the root of a UNC volume
4177 (i.e. "\\SERVER"), we will not detect that here, and we will
4178 return data about the symlink as result of FindFirst below.
4179 This is unfortunate, but that marginal use case does not
4180 justify a call to chase_symlinks which would impose a penalty
4181 on all the other use cases. (We get here for symlinks to
4182 roots of UNC volumes because CreateFile above fails for them,
4183 unlike with symlinks to root directories X:\ of drives.) */
4184 if (is_unc_volume (name))
4186 fattrs = unc_volume_file_attributes (name);
4187 if (fattrs == -1)
4188 return -1;
4190 ctime = atime = wtime = utc_base_ft;
4192 else if (rootdir)
4194 if (!dbcs_p)
4196 if (!IS_DIRECTORY_SEP (name[len-1]))
4197 strcat (name, "\\");
4199 else
4201 char *end = name + len;
4202 char *n = CharPrevExA (file_name_codepage, name, end, 0);
4204 if (!IS_DIRECTORY_SEP (*n))
4205 strcat (name, "\\");
4207 if (GetDriveType (name) < 2)
4209 errno = ENOENT;
4210 return -1;
4213 fattrs = FILE_ATTRIBUTE_DIRECTORY;
4214 ctime = atime = wtime = utc_base_ft;
4216 else
4218 if (!dbcs_p)
4220 if (IS_DIRECTORY_SEP (name[len-1]))
4221 name[len - 1] = 0;
4223 else
4225 char *end = name + len;
4226 char *n = CharPrevExA (file_name_codepage, name, end, 0);
4228 if (IS_DIRECTORY_SEP (*n))
4229 *n = 0;
4232 /* (This is hacky, but helps when doing file completions on
4233 network drives.) Optimize by using information available from
4234 active readdir if possible. */
4235 len = strlen (dir_pathname);
4236 if (!dbcs_p)
4238 if (IS_DIRECTORY_SEP (dir_pathname[len-1]))
4239 len--;
4241 else
4243 char *end = dir_pathname + len;
4244 char *n = CharPrevExA (file_name_codepage, dir_pathname, end, 0);
4246 if (IS_DIRECTORY_SEP (*n))
4247 len--;
4249 if (dir_find_handle != INVALID_HANDLE_VALUE
4250 && !(is_a_symlink && follow_symlinks)
4251 && strnicmp (save_name, dir_pathname, len) == 0
4252 && IS_DIRECTORY_SEP (name[len])
4253 && xstrcasecmp (name + len + 1, dir_static.d_name) == 0)
4255 /* This was the last entry returned by readdir. */
4256 wfd = dir_find_data;
4258 else
4260 logon_network_drive (name);
4262 fh = FindFirstFile (name, &wfd);
4263 if (fh == INVALID_HANDLE_VALUE)
4265 errno = ENOENT;
4266 return -1;
4268 FindClose (fh);
4270 /* Note: if NAME is a symlink, the information we get from
4271 FindFirstFile is for the symlink, not its target. */
4272 fattrs = wfd.dwFileAttributes;
4273 ctime = wfd.ftCreationTime;
4274 atime = wfd.ftLastAccessTime;
4275 wtime = wfd.ftLastWriteTime;
4276 fs_high = wfd.nFileSizeHigh;
4277 fs_low = wfd.nFileSizeLow;
4278 fake_inode = 0;
4279 nlinks = 1;
4280 serialnum = volume_info.serialnum;
4282 if (is_a_symlink && !follow_symlinks)
4283 buf->st_mode = S_IFLNK;
4284 else if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
4285 buf->st_mode = S_IFDIR;
4286 else
4287 buf->st_mode = S_IFREG;
4289 get_file_owner_and_group (NULL, buf);
4292 #if 0
4293 /* Not sure if there is any point in this. */
4294 if (!NILP (Vw32_generate_fake_inodes))
4295 fake_inode = generate_inode_val (name);
4296 else if (fake_inode == 0)
4298 /* For want of something better, try to make everything unique. */
4299 static DWORD gen_num = 0;
4300 fake_inode = ++gen_num;
4302 #endif
4304 buf->st_ino = fake_inode;
4306 buf->st_dev = serialnum;
4307 buf->st_rdev = serialnum;
4309 buf->st_size = fs_high;
4310 buf->st_size <<= 32;
4311 buf->st_size += fs_low;
4312 buf->st_nlink = nlinks;
4314 /* Convert timestamps to Unix format. */
4315 buf->st_mtime = convert_time (wtime);
4316 buf->st_atime = convert_time (atime);
4317 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
4318 buf->st_ctime = convert_time (ctime);
4319 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
4321 /* determine rwx permissions */
4322 if (is_a_symlink && !follow_symlinks)
4323 permission = S_IREAD | S_IWRITE | S_IEXEC; /* Posix expectations */
4324 else
4326 if (fattrs & FILE_ATTRIBUTE_READONLY)
4327 permission = S_IREAD;
4328 else
4329 permission = S_IREAD | S_IWRITE;
4331 if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
4332 permission |= S_IEXEC;
4333 else if (is_exec (name))
4334 permission |= S_IEXEC;
4337 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
4339 return 0;
4343 stat (const char * path, struct stat * buf)
4345 return stat_worker (path, buf, 1);
4349 lstat (const char * path, struct stat * buf)
4351 return stat_worker (path, buf, 0);
4355 fstatat (int fd, char const *name, struct stat *st, int flags)
4357 /* Rely on a hack: an open directory is modeled as file descriptor 0.
4358 This is good enough for the current usage in Emacs, but is fragile.
4360 FIXME: Add proper support for fdopendir, fstatat, readlinkat.
4361 Gnulib does this and can serve as a model. */
4362 char fullname[MAX_PATH];
4364 if (fd != AT_FDCWD)
4366 if (_snprintf (fullname, sizeof fullname, "%s/%s", dir_pathname, name)
4367 < 0)
4369 errno = ENAMETOOLONG;
4370 return -1;
4372 name = fullname;
4375 return stat_worker (name, st, ! (flags & AT_SYMLINK_NOFOLLOW));
4378 /* Provide fstat and utime as well as stat for consistent handling of
4379 file timestamps. */
4381 fstat (int desc, struct stat * buf)
4383 HANDLE fh = (HANDLE) _get_osfhandle (desc);
4384 BY_HANDLE_FILE_INFORMATION info;
4385 unsigned __int64 fake_inode;
4386 int permission;
4388 switch (GetFileType (fh) & ~FILE_TYPE_REMOTE)
4390 case FILE_TYPE_DISK:
4391 buf->st_mode = S_IFREG;
4392 if (!GetFileInformationByHandle (fh, &info))
4394 errno = EACCES;
4395 return -1;
4397 break;
4398 case FILE_TYPE_PIPE:
4399 buf->st_mode = S_IFIFO;
4400 goto non_disk;
4401 case FILE_TYPE_CHAR:
4402 case FILE_TYPE_UNKNOWN:
4403 default:
4404 buf->st_mode = S_IFCHR;
4405 non_disk:
4406 memset (&info, 0, sizeof (info));
4407 info.dwFileAttributes = 0;
4408 info.ftCreationTime = utc_base_ft;
4409 info.ftLastAccessTime = utc_base_ft;
4410 info.ftLastWriteTime = utc_base_ft;
4413 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
4414 buf->st_mode = S_IFDIR;
4416 buf->st_nlink = info.nNumberOfLinks;
4417 /* Might as well use file index to fake inode values, but this
4418 is not guaranteed to be unique unless we keep a handle open
4419 all the time (even then there are situations where it is
4420 not unique). Reputedly, there are at most 48 bits of info
4421 (on NTFS, presumably less on FAT). */
4422 fake_inode = info.nFileIndexHigh;
4423 fake_inode <<= 32;
4424 fake_inode += info.nFileIndexLow;
4426 /* MSVC defines _ino_t to be short; other libc's might not. */
4427 if (sizeof (buf->st_ino) == 2)
4428 buf->st_ino = fake_inode ^ (fake_inode >> 16);
4429 else
4430 buf->st_ino = fake_inode;
4432 /* If the caller so requested, get the true file owner and group.
4433 Otherwise, consider the file to belong to the current user. */
4434 if (!w32_stat_get_owner_group || is_windows_9x () == TRUE)
4435 get_file_owner_and_group (NULL, buf);
4436 else
4438 PSECURITY_DESCRIPTOR psd = NULL;
4440 psd = get_file_security_desc_by_handle (fh);
4441 if (psd)
4443 get_file_owner_and_group (psd, buf);
4444 LocalFree (psd);
4446 else
4447 get_file_owner_and_group (NULL, buf);
4450 buf->st_dev = info.dwVolumeSerialNumber;
4451 buf->st_rdev = info.dwVolumeSerialNumber;
4453 buf->st_size = info.nFileSizeHigh;
4454 buf->st_size <<= 32;
4455 buf->st_size += info.nFileSizeLow;
4457 /* Convert timestamps to Unix format. */
4458 buf->st_mtime = convert_time (info.ftLastWriteTime);
4459 buf->st_atime = convert_time (info.ftLastAccessTime);
4460 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
4461 buf->st_ctime = convert_time (info.ftCreationTime);
4462 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
4464 /* determine rwx permissions */
4465 if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
4466 permission = S_IREAD;
4467 else
4468 permission = S_IREAD | S_IWRITE;
4470 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
4471 permission |= S_IEXEC;
4472 else
4474 #if 0 /* no way of knowing the filename */
4475 char * p = strrchr (name, '.');
4476 if (p != NULL &&
4477 (xstrcasecmp (p, ".exe") == 0 ||
4478 xstrcasecmp (p, ".com") == 0 ||
4479 xstrcasecmp (p, ".bat") == 0 ||
4480 xstrcasecmp (p, ".cmd") == 0))
4481 permission |= S_IEXEC;
4482 #endif
4485 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
4487 return 0;
4491 utime (const char *name, struct utimbuf *times)
4493 struct utimbuf deftime;
4494 HANDLE fh;
4495 FILETIME mtime;
4496 FILETIME atime;
4498 if (times == NULL)
4500 deftime.modtime = deftime.actime = time (NULL);
4501 times = &deftime;
4504 /* Need write access to set times. */
4505 fh = CreateFile (name, FILE_WRITE_ATTRIBUTES,
4506 /* If NAME specifies a directory, FILE_SHARE_DELETE
4507 allows other processes to delete files inside it,
4508 while we have the directory open. */
4509 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
4510 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
4511 if (fh != INVALID_HANDLE_VALUE)
4513 convert_from_time_t (times->actime, &atime);
4514 convert_from_time_t (times->modtime, &mtime);
4515 if (!SetFileTime (fh, NULL, &atime, &mtime))
4517 CloseHandle (fh);
4518 errno = EACCES;
4519 return -1;
4521 CloseHandle (fh);
4523 else
4525 errno = EINVAL;
4526 return -1;
4528 return 0;
4532 /* Symlink-related functions. */
4533 #ifndef SYMBOLIC_LINK_FLAG_DIRECTORY
4534 #define SYMBOLIC_LINK_FLAG_DIRECTORY 0x1
4535 #endif
4538 symlink (char const *filename, char const *linkname)
4540 char linkfn[MAX_PATH], *tgtfn;
4541 DWORD flags = 0;
4542 int dir_access, filename_ends_in_slash;
4543 int dbcs_p;
4545 /* Diagnostics follows Posix as much as possible. */
4546 if (filename == NULL || linkname == NULL)
4548 errno = EFAULT;
4549 return -1;
4551 if (!*filename)
4553 errno = ENOENT;
4554 return -1;
4556 if (strlen (filename) > MAX_PATH || strlen (linkname) > MAX_PATH)
4558 errno = ENAMETOOLONG;
4559 return -1;
4562 strcpy (linkfn, map_w32_filename (linkname, NULL));
4563 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) == 0)
4565 errno = EPERM;
4566 return -1;
4569 dbcs_p = max_filename_mbslen () > 1;
4571 /* Note: since empty FILENAME was already rejected, we can safely
4572 refer to FILENAME[1]. */
4573 if (!(IS_DIRECTORY_SEP (filename[0]) || IS_DEVICE_SEP (filename[1])))
4575 /* Non-absolute FILENAME is understood as being relative to
4576 LINKNAME's directory. We need to prepend that directory to
4577 FILENAME to get correct results from faccessat below, since
4578 otherwise it will interpret FILENAME relative to the
4579 directory where the Emacs process runs. Note that
4580 make-symbolic-link always makes sure LINKNAME is a fully
4581 expanded file name. */
4582 char tem[MAX_PATH];
4583 char *p = linkfn + strlen (linkfn);
4585 if (!dbcs_p)
4587 while (p > linkfn && !IS_ANY_SEP (p[-1]))
4588 p--;
4590 else
4592 char *p1 = CharPrevExA (file_name_codepage, linkfn, p, 0);
4594 while (p > linkfn && !IS_ANY_SEP (*p1))
4596 p = p1;
4597 p1 = CharPrevExA (file_name_codepage, linkfn, p1, 0);
4600 if (p > linkfn)
4601 strncpy (tem, linkfn, p - linkfn);
4602 tem[p - linkfn] = '\0';
4603 strcat (tem, filename);
4604 dir_access = faccessat (AT_FDCWD, tem, D_OK, AT_EACCESS);
4606 else
4607 dir_access = faccessat (AT_FDCWD, filename, D_OK, AT_EACCESS);
4609 /* Since Windows distinguishes between symlinks to directories and
4610 to files, we provide a kludgy feature: if FILENAME doesn't
4611 exist, but ends in a slash, we create a symlink to directory. If
4612 FILENAME exists and is a directory, we always create a symlink to
4613 directory. */
4614 if (!dbcs_p)
4615 filename_ends_in_slash = IS_DIRECTORY_SEP (filename[strlen (filename) - 1]);
4616 else
4618 const char *end = filename + strlen (filename);
4619 const char *n = CharPrevExA (file_name_codepage, filename, end, 0);
4621 filename_ends_in_slash = IS_DIRECTORY_SEP (*n);
4623 if (dir_access == 0 || filename_ends_in_slash)
4624 flags = SYMBOLIC_LINK_FLAG_DIRECTORY;
4626 tgtfn = (char *)map_w32_filename (filename, NULL);
4627 if (filename_ends_in_slash)
4628 tgtfn[strlen (tgtfn) - 1] = '\0';
4630 errno = 0;
4631 if (!create_symbolic_link (linkfn, tgtfn, flags))
4633 /* ENOSYS is set by create_symbolic_link, when it detects that
4634 the OS doesn't support the CreateSymbolicLink API. */
4635 if (errno != ENOSYS)
4637 DWORD w32err = GetLastError ();
4639 switch (w32err)
4641 /* ERROR_SUCCESS is sometimes returned when LINKFN and
4642 TGTFN point to the same file name, go figure. */
4643 case ERROR_SUCCESS:
4644 case ERROR_FILE_EXISTS:
4645 errno = EEXIST;
4646 break;
4647 case ERROR_ACCESS_DENIED:
4648 errno = EACCES;
4649 break;
4650 case ERROR_FILE_NOT_FOUND:
4651 case ERROR_PATH_NOT_FOUND:
4652 case ERROR_BAD_NETPATH:
4653 case ERROR_INVALID_REPARSE_DATA:
4654 errno = ENOENT;
4655 break;
4656 case ERROR_DIRECTORY:
4657 errno = EISDIR;
4658 break;
4659 case ERROR_PRIVILEGE_NOT_HELD:
4660 case ERROR_NOT_ALL_ASSIGNED:
4661 errno = EPERM;
4662 break;
4663 case ERROR_DISK_FULL:
4664 errno = ENOSPC;
4665 break;
4666 default:
4667 errno = EINVAL;
4668 break;
4671 return -1;
4673 return 0;
4676 /* A quick inexpensive test of whether FILENAME identifies a file that
4677 is a symlink. Returns non-zero if it is, zero otherwise. FILENAME
4678 must already be in the normalized form returned by
4679 map_w32_filename.
4681 Note: for repeated operations on many files, it is best to test
4682 whether the underlying volume actually supports symlinks, by
4683 testing the FILE_SUPPORTS_REPARSE_POINTS bit in volume's flags, and
4684 avoid the call to this function if it doesn't. That's because the
4685 call to GetFileAttributes takes a non-negligible time, especially
4686 on non-local or removable filesystems. See stat_worker for an
4687 example of how to do that. */
4688 static int
4689 is_symlink (const char *filename)
4691 DWORD attrs;
4692 WIN32_FIND_DATA wfd;
4693 HANDLE fh;
4695 attrs = GetFileAttributes (filename);
4696 if (attrs == -1)
4698 DWORD w32err = GetLastError ();
4700 switch (w32err)
4702 case ERROR_BAD_NETPATH: /* network share, can't be a symlink */
4703 break;
4704 case ERROR_ACCESS_DENIED:
4705 errno = EACCES;
4706 break;
4707 case ERROR_FILE_NOT_FOUND:
4708 case ERROR_PATH_NOT_FOUND:
4709 default:
4710 errno = ENOENT;
4711 break;
4713 return 0;
4715 if ((attrs & FILE_ATTRIBUTE_REPARSE_POINT) == 0)
4716 return 0;
4717 logon_network_drive (filename);
4718 fh = FindFirstFile (filename, &wfd);
4719 if (fh == INVALID_HANDLE_VALUE)
4720 return 0;
4721 FindClose (fh);
4722 return (wfd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0
4723 && (wfd.dwReserved0 & IO_REPARSE_TAG_SYMLINK) == IO_REPARSE_TAG_SYMLINK;
4726 /* If NAME identifies a symbolic link, copy into BUF the file name of
4727 the symlink's target. Copy at most BUF_SIZE bytes, and do NOT
4728 null-terminate the target name, even if it fits. Return the number
4729 of bytes copied, or -1 if NAME is not a symlink or any error was
4730 encountered while resolving it. The file name copied into BUF is
4731 encoded in the current ANSI codepage. */
4732 ssize_t
4733 readlink (const char *name, char *buf, size_t buf_size)
4735 const char *path;
4736 TOKEN_PRIVILEGES privs;
4737 int restore_privs = 0;
4738 HANDLE sh;
4739 ssize_t retval;
4741 if (name == NULL)
4743 errno = EFAULT;
4744 return -1;
4746 if (!*name)
4748 errno = ENOENT;
4749 return -1;
4752 path = map_w32_filename (name, NULL);
4754 if (strlen (path) > MAX_PATH)
4756 errno = ENAMETOOLONG;
4757 return -1;
4760 errno = 0;
4761 if (is_windows_9x () == TRUE
4762 || (volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) == 0
4763 || !is_symlink (path))
4765 if (!errno)
4766 errno = EINVAL; /* not a symlink */
4767 return -1;
4770 /* Done with simple tests, now we're in for some _real_ work. */
4771 if (enable_privilege (SE_BACKUP_NAME, TRUE, &privs))
4772 restore_privs = 1;
4773 /* Implementation note: From here and onward, don't return early,
4774 since that will fail to restore the original set of privileges of
4775 the calling thread. */
4777 retval = -1; /* not too optimistic, are we? */
4779 /* Note: In the next call to CreateFile, we use zero as the 2nd
4780 argument because, when the symlink is a hidden/system file,
4781 e.g. 'C:\Users\All Users', GENERIC_READ fails with
4782 ERROR_ACCESS_DENIED. Zero seems to work just fine, both for file
4783 and directory symlinks. */
4784 sh = CreateFile (path, 0, 0, NULL, OPEN_EXISTING,
4785 FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
4786 NULL);
4787 if (sh != INVALID_HANDLE_VALUE)
4789 BYTE reparse_buf[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
4790 REPARSE_DATA_BUFFER *reparse_data = (REPARSE_DATA_BUFFER *)&reparse_buf[0];
4791 DWORD retbytes;
4793 if (!DeviceIoControl (sh, FSCTL_GET_REPARSE_POINT, NULL, 0,
4794 reparse_buf, MAXIMUM_REPARSE_DATA_BUFFER_SIZE,
4795 &retbytes, NULL))
4796 errno = EIO;
4797 else if (reparse_data->ReparseTag != IO_REPARSE_TAG_SYMLINK)
4798 errno = EINVAL;
4799 else
4801 /* Copy the link target name, in wide characters, from
4802 reparse_data, then convert it to multibyte encoding in
4803 the current locale's codepage. */
4804 WCHAR *lwname;
4805 BYTE lname[MAX_PATH];
4806 USHORT lname_len;
4807 USHORT lwname_len =
4808 reparse_data->SymbolicLinkReparseBuffer.PrintNameLength;
4809 WCHAR *lwname_src =
4810 reparse_data->SymbolicLinkReparseBuffer.PathBuffer
4811 + reparse_data->SymbolicLinkReparseBuffer.PrintNameOffset/sizeof(WCHAR);
4812 /* This updates file_name_codepage which we need below. */
4813 int dbcs_p = max_filename_mbslen () > 1;
4815 /* According to MSDN, PrintNameLength does not include the
4816 terminating null character. */
4817 lwname = alloca ((lwname_len + 1) * sizeof(WCHAR));
4818 memcpy (lwname, lwname_src, lwname_len);
4819 lwname[lwname_len/sizeof(WCHAR)] = 0; /* null-terminate */
4821 lname_len = WideCharToMultiByte (file_name_codepage, 0, lwname, -1,
4822 lname, MAX_PATH, NULL, NULL);
4823 if (!lname_len)
4825 /* WideCharToMultiByte failed. */
4826 DWORD w32err1 = GetLastError ();
4828 switch (w32err1)
4830 case ERROR_INSUFFICIENT_BUFFER:
4831 errno = ENAMETOOLONG;
4832 break;
4833 case ERROR_INVALID_PARAMETER:
4834 errno = EFAULT;
4835 break;
4836 case ERROR_NO_UNICODE_TRANSLATION:
4837 errno = ENOENT;
4838 break;
4839 default:
4840 errno = EINVAL;
4841 break;
4844 else
4846 size_t size_to_copy = buf_size;
4847 BYTE *p = lname, *p2;
4848 BYTE *pend = p + lname_len;
4850 /* Normalize like dostounix_filename does, but we don't
4851 want to assume that lname is null-terminated. */
4852 if (dbcs_p)
4853 p2 = CharNextExA (file_name_codepage, p, 0);
4854 else
4855 p2 = p + 1;
4856 if (*p && *p2 == ':' && *p >= 'A' && *p <= 'Z')
4858 *p += 'a' - 'A';
4859 p += 2;
4861 while (p <= pend)
4863 if (*p == '\\')
4864 *p = '/';
4865 if (dbcs_p)
4867 p = CharNextExA (file_name_codepage, p, 0);
4868 /* CharNextExA doesn't advance at null character. */
4869 if (!*p)
4870 break;
4872 else
4873 ++p;
4875 /* Testing for null-terminated LNAME is paranoia:
4876 WideCharToMultiByte should always return a
4877 null-terminated string when its 4th argument is -1
4878 and its 3rd argument is null-terminated (which they
4879 are, see above). */
4880 if (lname[lname_len - 1] == '\0')
4881 lname_len--;
4882 if (lname_len <= buf_size)
4883 size_to_copy = lname_len;
4884 strncpy (buf, lname, size_to_copy);
4885 /* Success! */
4886 retval = size_to_copy;
4889 CloseHandle (sh);
4891 else
4893 /* CreateFile failed. */
4894 DWORD w32err2 = GetLastError ();
4896 switch (w32err2)
4898 case ERROR_FILE_NOT_FOUND:
4899 case ERROR_PATH_NOT_FOUND:
4900 errno = ENOENT;
4901 break;
4902 case ERROR_ACCESS_DENIED:
4903 case ERROR_TOO_MANY_OPEN_FILES:
4904 errno = EACCES;
4905 break;
4906 default:
4907 errno = EPERM;
4908 break;
4911 if (restore_privs)
4913 restore_privilege (&privs);
4914 revert_to_self ();
4917 return retval;
4920 ssize_t
4921 readlinkat (int fd, char const *name, char *buffer,
4922 size_t buffer_size)
4924 /* Rely on a hack: an open directory is modeled as file descriptor 0,
4925 as in fstatat. FIXME: Add proper support for readlinkat. */
4926 char fullname[MAX_PATH];
4928 if (fd != AT_FDCWD)
4930 if (_snprintf (fullname, sizeof fullname, "%s/%s", dir_pathname, name)
4931 < 0)
4933 errno = ENAMETOOLONG;
4934 return -1;
4936 name = fullname;
4939 return readlink (name, buffer, buffer_size);
4942 /* If FILE is a symlink, return its target (stored in a static
4943 buffer); otherwise return FILE.
4945 This function repeatedly resolves symlinks in the last component of
4946 a chain of symlink file names, as in foo -> bar -> baz -> ...,
4947 until it arrives at a file whose last component is not a symlink,
4948 or some error occurs. It returns the target of the last
4949 successfully resolved symlink in the chain. If it succeeds to
4950 resolve even a single symlink, the value returned is an absolute
4951 file name with backslashes (result of GetFullPathName). By
4952 contrast, if the original FILE is returned, it is unaltered.
4954 Note: This function can set errno even if it succeeds.
4956 Implementation note: we only resolve the last portion ("basename")
4957 of the argument FILE and of each following file in the chain,
4958 disregarding any possible symlinks in its leading directories.
4959 This is because Windows system calls and library functions
4960 transparently resolve symlinks in leading directories and return
4961 correct information, as long as the basename is not a symlink. */
4962 static char *
4963 chase_symlinks (const char *file)
4965 static char target[MAX_PATH];
4966 char link[MAX_PATH];
4967 ssize_t res, link_len;
4968 int loop_count = 0;
4969 int dbcs_p;
4971 if (is_windows_9x () == TRUE || !is_symlink (file))
4972 return (char *)file;
4974 if ((link_len = GetFullPathName (file, MAX_PATH, link, NULL)) == 0)
4975 return (char *)file;
4977 dbcs_p = max_filename_mbslen () > 1;
4978 target[0] = '\0';
4979 do {
4981 /* Remove trailing slashes, as we want to resolve the last
4982 non-trivial part of the link name. */
4983 if (!dbcs_p)
4985 while (link_len > 3 && IS_DIRECTORY_SEP (link[link_len-1]))
4986 link[link_len--] = '\0';
4988 else if (link_len > 3)
4990 char *n = CharPrevExA (file_name_codepage, link, link + link_len, 0);
4992 while (n >= link + 2 && IS_DIRECTORY_SEP (*n))
4994 n[1] = '\0';
4995 n = CharPrevExA (file_name_codepage, link, n, 0);
4999 res = readlink (link, target, MAX_PATH);
5000 if (res > 0)
5002 target[res] = '\0';
5003 if (!(IS_DEVICE_SEP (target[1])
5004 || (IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1]))))
5006 /* Target is relative. Append it to the directory part of
5007 the symlink, then copy the result back to target. */
5008 char *p = link + link_len;
5010 if (!dbcs_p)
5012 while (p > link && !IS_ANY_SEP (p[-1]))
5013 p--;
5015 else
5017 char *p1 = CharPrevExA (file_name_codepage, link, p, 0);
5019 while (p > link && !IS_ANY_SEP (*p1))
5021 p = p1;
5022 p1 = CharPrevExA (file_name_codepage, link, p1, 0);
5025 strcpy (p, target);
5026 strcpy (target, link);
5028 /* Resolve any "." and ".." to get a fully-qualified file name
5029 in link[] again. */
5030 link_len = GetFullPathName (target, MAX_PATH, link, NULL);
5032 } while (res > 0 && link_len > 0 && ++loop_count <= 100);
5034 if (loop_count > 100)
5035 errno = ELOOP;
5037 if (target[0] == '\0') /* not a single call to readlink succeeded */
5038 return (char *)file;
5039 return target;
5043 /* Posix ACL emulation. */
5046 acl_valid (acl_t acl)
5048 return is_valid_security_descriptor ((PSECURITY_DESCRIPTOR)acl) ? 0 : -1;
5051 char *
5052 acl_to_text (acl_t acl, ssize_t *size)
5054 LPTSTR str_acl;
5055 SECURITY_INFORMATION flags =
5056 OWNER_SECURITY_INFORMATION |
5057 GROUP_SECURITY_INFORMATION |
5058 DACL_SECURITY_INFORMATION;
5059 char *retval = NULL;
5060 ULONG local_size;
5061 int e = errno;
5063 errno = 0;
5065 if (convert_sd_to_sddl ((PSECURITY_DESCRIPTOR)acl, SDDL_REVISION_1, flags, &str_acl, &local_size))
5067 errno = e;
5068 /* We don't want to mix heaps, so we duplicate the string in our
5069 heap and free the one allocated by the API. */
5070 retval = xstrdup (str_acl);
5071 if (size)
5072 *size = local_size;
5073 LocalFree (str_acl);
5075 else if (errno != ENOTSUP)
5076 errno = EINVAL;
5078 return retval;
5081 acl_t
5082 acl_from_text (const char *acl_str)
5084 PSECURITY_DESCRIPTOR psd, retval = NULL;
5085 ULONG sd_size;
5086 int e = errno;
5088 errno = 0;
5090 if (convert_sddl_to_sd (acl_str, SDDL_REVISION_1, &psd, &sd_size))
5092 errno = e;
5093 retval = xmalloc (sd_size);
5094 memcpy (retval, psd, sd_size);
5095 LocalFree (psd);
5097 else if (errno != ENOTSUP)
5098 errno = EINVAL;
5100 return retval;
5104 acl_free (void *ptr)
5106 xfree (ptr);
5107 return 0;
5110 acl_t
5111 acl_get_file (const char *fname, acl_type_t type)
5113 PSECURITY_DESCRIPTOR psd = NULL;
5114 const char *filename;
5116 if (type == ACL_TYPE_ACCESS)
5118 DWORD sd_len, err;
5119 SECURITY_INFORMATION si =
5120 OWNER_SECURITY_INFORMATION |
5121 GROUP_SECURITY_INFORMATION |
5122 DACL_SECURITY_INFORMATION ;
5123 int e = errno;
5125 filename = map_w32_filename (fname, NULL);
5126 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
5127 fname = chase_symlinks (filename);
5128 else
5129 fname = filename;
5131 errno = 0;
5132 if (!get_file_security (fname, si, psd, 0, &sd_len)
5133 && errno != ENOTSUP)
5135 err = GetLastError ();
5136 if (err == ERROR_INSUFFICIENT_BUFFER)
5138 psd = xmalloc (sd_len);
5139 if (!get_file_security (fname, si, psd, sd_len, &sd_len))
5141 xfree (psd);
5142 errno = EIO;
5143 psd = NULL;
5146 else if (err == ERROR_FILE_NOT_FOUND
5147 || err == ERROR_PATH_NOT_FOUND)
5148 errno = ENOENT;
5149 else
5150 errno = EIO;
5152 else if (!errno)
5153 errno = e;
5155 else if (type != ACL_TYPE_DEFAULT)
5156 errno = EINVAL;
5158 return psd;
5162 acl_set_file (const char *fname, acl_type_t type, acl_t acl)
5164 TOKEN_PRIVILEGES old1, old2;
5165 DWORD err;
5166 int st = 0, retval = -1;
5167 SECURITY_INFORMATION flags = 0;
5168 PSID psid;
5169 PACL pacl;
5170 BOOL dflt;
5171 BOOL dacl_present;
5172 int e;
5173 const char *filename;
5175 if (acl_valid (acl) != 0
5176 || (type != ACL_TYPE_DEFAULT && type != ACL_TYPE_ACCESS))
5178 errno = EINVAL;
5179 return -1;
5182 if (type == ACL_TYPE_DEFAULT)
5184 errno = ENOSYS;
5185 return -1;
5188 filename = map_w32_filename (fname, NULL);
5189 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
5190 fname = chase_symlinks (filename);
5191 else
5192 fname = filename;
5194 if (get_security_descriptor_owner ((PSECURITY_DESCRIPTOR)acl, &psid, &dflt)
5195 && psid)
5196 flags |= OWNER_SECURITY_INFORMATION;
5197 if (get_security_descriptor_group ((PSECURITY_DESCRIPTOR)acl, &psid, &dflt)
5198 && psid)
5199 flags |= GROUP_SECURITY_INFORMATION;
5200 if (get_security_descriptor_dacl ((PSECURITY_DESCRIPTOR)acl, &dacl_present,
5201 &pacl, &dflt)
5202 && dacl_present)
5203 flags |= DACL_SECURITY_INFORMATION;
5204 if (!flags)
5205 return 0;
5207 /* According to KB-245153, setting the owner will succeed if either:
5208 (1) the caller is the user who will be the new owner, and has the
5209 SE_TAKE_OWNERSHIP privilege, or
5210 (2) the caller has the SE_RESTORE privilege, in which case she can
5211 set any valid user or group as the owner
5213 We request below both SE_TAKE_OWNERSHIP and SE_RESTORE
5214 privileges, and disregard any failures in obtaining them. If
5215 these privileges cannot be obtained, and do not already exist in
5216 the calling thread's security token, this function could fail
5217 with EPERM. */
5218 if (enable_privilege (SE_TAKE_OWNERSHIP_NAME, TRUE, &old1))
5219 st++;
5220 if (enable_privilege (SE_RESTORE_NAME, TRUE, &old2))
5221 st++;
5223 e = errno;
5224 errno = 0;
5225 if (!set_file_security ((char *)fname, flags, (PSECURITY_DESCRIPTOR)acl))
5227 err = GetLastError ();
5229 if (errno == ENOTSUP)
5231 else if (err == ERROR_INVALID_OWNER
5232 || err == ERROR_NOT_ALL_ASSIGNED
5233 || err == ERROR_ACCESS_DENIED)
5235 /* Maybe the requested ACL and the one the file already has
5236 are identical, in which case we can silently ignore the
5237 failure. (And no, Windows doesn't.) */
5238 acl_t current_acl = acl_get_file (fname, ACL_TYPE_ACCESS);
5240 errno = EPERM;
5241 if (current_acl)
5243 char *acl_from = acl_to_text (current_acl, NULL);
5244 char *acl_to = acl_to_text (acl, NULL);
5246 if (acl_from && acl_to && xstrcasecmp (acl_from, acl_to) == 0)
5248 retval = 0;
5249 errno = e;
5251 if (acl_from)
5252 acl_free (acl_from);
5253 if (acl_to)
5254 acl_free (acl_to);
5255 acl_free (current_acl);
5258 else if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
5259 errno = ENOENT;
5260 else
5261 errno = EACCES;
5263 else
5265 retval = 0;
5266 errno = e;
5269 if (st)
5271 if (st >= 2)
5272 restore_privilege (&old2);
5273 restore_privilege (&old1);
5274 revert_to_self ();
5277 return retval;
5281 /* MS-Windows version of careadlinkat (cf. ../lib/careadlinkat.c). We
5282 have a fixed max size for file names, so we don't need the kind of
5283 alloc/malloc/realloc dance the gnulib version does. We also don't
5284 support FD-relative symlinks. */
5285 char *
5286 careadlinkat (int fd, char const *filename,
5287 char *buffer, size_t buffer_size,
5288 struct allocator const *alloc,
5289 ssize_t (*preadlinkat) (int, char const *, char *, size_t))
5291 char linkname[MAX_PATH];
5292 ssize_t link_size;
5294 link_size = preadlinkat (fd, filename, linkname, sizeof(linkname));
5296 if (link_size > 0)
5298 char *retval = buffer;
5300 linkname[link_size++] = '\0';
5301 if (link_size > buffer_size)
5302 retval = (char *)(alloc ? alloc->allocate : xmalloc) (link_size);
5303 if (retval)
5304 memcpy (retval, linkname, link_size);
5306 return retval;
5308 return NULL;
5312 /* Support for browsing other processes and their attributes. See
5313 process.c for the Lisp bindings. */
5315 /* Helper wrapper functions. */
5317 static HANDLE WINAPI
5318 create_toolhelp32_snapshot (DWORD Flags, DWORD Ignored)
5320 static CreateToolhelp32Snapshot_Proc s_pfn_Create_Toolhelp32_Snapshot = NULL;
5322 if (g_b_init_create_toolhelp32_snapshot == 0)
5324 g_b_init_create_toolhelp32_snapshot = 1;
5325 s_pfn_Create_Toolhelp32_Snapshot = (CreateToolhelp32Snapshot_Proc)
5326 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5327 "CreateToolhelp32Snapshot");
5329 if (s_pfn_Create_Toolhelp32_Snapshot == NULL)
5331 return INVALID_HANDLE_VALUE;
5333 return (s_pfn_Create_Toolhelp32_Snapshot (Flags, Ignored));
5336 static BOOL WINAPI
5337 process32_first (HANDLE hSnapshot, LPPROCESSENTRY32 lppe)
5339 static Process32First_Proc s_pfn_Process32_First = NULL;
5341 if (g_b_init_process32_first == 0)
5343 g_b_init_process32_first = 1;
5344 s_pfn_Process32_First = (Process32First_Proc)
5345 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5346 "Process32First");
5348 if (s_pfn_Process32_First == NULL)
5350 return FALSE;
5352 return (s_pfn_Process32_First (hSnapshot, lppe));
5355 static BOOL WINAPI
5356 process32_next (HANDLE hSnapshot, LPPROCESSENTRY32 lppe)
5358 static Process32Next_Proc s_pfn_Process32_Next = NULL;
5360 if (g_b_init_process32_next == 0)
5362 g_b_init_process32_next = 1;
5363 s_pfn_Process32_Next = (Process32Next_Proc)
5364 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5365 "Process32Next");
5367 if (s_pfn_Process32_Next == NULL)
5369 return FALSE;
5371 return (s_pfn_Process32_Next (hSnapshot, lppe));
5374 static BOOL WINAPI
5375 open_thread_token (HANDLE ThreadHandle,
5376 DWORD DesiredAccess,
5377 BOOL OpenAsSelf,
5378 PHANDLE TokenHandle)
5380 static OpenThreadToken_Proc s_pfn_Open_Thread_Token = NULL;
5381 HMODULE hm_advapi32 = NULL;
5382 if (is_windows_9x () == TRUE)
5384 SetLastError (ERROR_NOT_SUPPORTED);
5385 return FALSE;
5387 if (g_b_init_open_thread_token == 0)
5389 g_b_init_open_thread_token = 1;
5390 hm_advapi32 = LoadLibrary ("Advapi32.dll");
5391 s_pfn_Open_Thread_Token =
5392 (OpenThreadToken_Proc) GetProcAddress (hm_advapi32, "OpenThreadToken");
5394 if (s_pfn_Open_Thread_Token == NULL)
5396 SetLastError (ERROR_NOT_SUPPORTED);
5397 return FALSE;
5399 return (
5400 s_pfn_Open_Thread_Token (
5401 ThreadHandle,
5402 DesiredAccess,
5403 OpenAsSelf,
5404 TokenHandle)
5408 static BOOL WINAPI
5409 impersonate_self (SECURITY_IMPERSONATION_LEVEL ImpersonationLevel)
5411 static ImpersonateSelf_Proc s_pfn_Impersonate_Self = NULL;
5412 HMODULE hm_advapi32 = NULL;
5413 if (is_windows_9x () == TRUE)
5415 return FALSE;
5417 if (g_b_init_impersonate_self == 0)
5419 g_b_init_impersonate_self = 1;
5420 hm_advapi32 = LoadLibrary ("Advapi32.dll");
5421 s_pfn_Impersonate_Self =
5422 (ImpersonateSelf_Proc) GetProcAddress (hm_advapi32, "ImpersonateSelf");
5424 if (s_pfn_Impersonate_Self == NULL)
5426 return FALSE;
5428 return s_pfn_Impersonate_Self (ImpersonationLevel);
5431 static BOOL WINAPI
5432 revert_to_self (void)
5434 static RevertToSelf_Proc s_pfn_Revert_To_Self = NULL;
5435 HMODULE hm_advapi32 = NULL;
5436 if (is_windows_9x () == TRUE)
5438 return FALSE;
5440 if (g_b_init_revert_to_self == 0)
5442 g_b_init_revert_to_self = 1;
5443 hm_advapi32 = LoadLibrary ("Advapi32.dll");
5444 s_pfn_Revert_To_Self =
5445 (RevertToSelf_Proc) GetProcAddress (hm_advapi32, "RevertToSelf");
5447 if (s_pfn_Revert_To_Self == NULL)
5449 return FALSE;
5451 return s_pfn_Revert_To_Self ();
5454 static BOOL WINAPI
5455 get_process_memory_info (HANDLE h_proc,
5456 PPROCESS_MEMORY_COUNTERS mem_counters,
5457 DWORD bufsize)
5459 static GetProcessMemoryInfo_Proc s_pfn_Get_Process_Memory_Info = NULL;
5460 HMODULE hm_psapi = NULL;
5461 if (is_windows_9x () == TRUE)
5463 return FALSE;
5465 if (g_b_init_get_process_memory_info == 0)
5467 g_b_init_get_process_memory_info = 1;
5468 hm_psapi = LoadLibrary ("Psapi.dll");
5469 if (hm_psapi)
5470 s_pfn_Get_Process_Memory_Info = (GetProcessMemoryInfo_Proc)
5471 GetProcAddress (hm_psapi, "GetProcessMemoryInfo");
5473 if (s_pfn_Get_Process_Memory_Info == NULL)
5475 return FALSE;
5477 return s_pfn_Get_Process_Memory_Info (h_proc, mem_counters, bufsize);
5480 static BOOL WINAPI
5481 get_process_working_set_size (HANDLE h_proc,
5482 PSIZE_T minrss,
5483 PSIZE_T maxrss)
5485 static GetProcessWorkingSetSize_Proc
5486 s_pfn_Get_Process_Working_Set_Size = NULL;
5488 if (is_windows_9x () == TRUE)
5490 return FALSE;
5492 if (g_b_init_get_process_working_set_size == 0)
5494 g_b_init_get_process_working_set_size = 1;
5495 s_pfn_Get_Process_Working_Set_Size = (GetProcessWorkingSetSize_Proc)
5496 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5497 "GetProcessWorkingSetSize");
5499 if (s_pfn_Get_Process_Working_Set_Size == NULL)
5501 return FALSE;
5503 return s_pfn_Get_Process_Working_Set_Size (h_proc, minrss, maxrss);
5506 static BOOL WINAPI
5507 global_memory_status (MEMORYSTATUS *buf)
5509 static GlobalMemoryStatus_Proc s_pfn_Global_Memory_Status = NULL;
5511 if (is_windows_9x () == TRUE)
5513 return FALSE;
5515 if (g_b_init_global_memory_status == 0)
5517 g_b_init_global_memory_status = 1;
5518 s_pfn_Global_Memory_Status = (GlobalMemoryStatus_Proc)
5519 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5520 "GlobalMemoryStatus");
5522 if (s_pfn_Global_Memory_Status == NULL)
5524 return FALSE;
5526 return s_pfn_Global_Memory_Status (buf);
5529 static BOOL WINAPI
5530 global_memory_status_ex (MEMORY_STATUS_EX *buf)
5532 static GlobalMemoryStatusEx_Proc s_pfn_Global_Memory_Status_Ex = NULL;
5534 if (is_windows_9x () == TRUE)
5536 return FALSE;
5538 if (g_b_init_global_memory_status_ex == 0)
5540 g_b_init_global_memory_status_ex = 1;
5541 s_pfn_Global_Memory_Status_Ex = (GlobalMemoryStatusEx_Proc)
5542 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5543 "GlobalMemoryStatusEx");
5545 if (s_pfn_Global_Memory_Status_Ex == NULL)
5547 return FALSE;
5549 return s_pfn_Global_Memory_Status_Ex (buf);
5552 Lisp_Object
5553 list_system_processes (void)
5555 struct gcpro gcpro1;
5556 Lisp_Object proclist = Qnil;
5557 HANDLE h_snapshot;
5559 h_snapshot = create_toolhelp32_snapshot (TH32CS_SNAPPROCESS, 0);
5561 if (h_snapshot != INVALID_HANDLE_VALUE)
5563 PROCESSENTRY32 proc_entry;
5564 DWORD proc_id;
5565 BOOL res;
5567 GCPRO1 (proclist);
5569 proc_entry.dwSize = sizeof (PROCESSENTRY32);
5570 for (res = process32_first (h_snapshot, &proc_entry); res;
5571 res = process32_next (h_snapshot, &proc_entry))
5573 proc_id = proc_entry.th32ProcessID;
5574 proclist = Fcons (make_fixnum_or_float (proc_id), proclist);
5577 CloseHandle (h_snapshot);
5578 UNGCPRO;
5579 proclist = Fnreverse (proclist);
5582 return proclist;
5585 static int
5586 enable_privilege (LPCTSTR priv_name, BOOL enable_p, TOKEN_PRIVILEGES *old_priv)
5588 TOKEN_PRIVILEGES priv;
5589 DWORD priv_size = sizeof (priv);
5590 DWORD opriv_size = sizeof (*old_priv);
5591 HANDLE h_token = NULL;
5592 HANDLE h_thread = GetCurrentThread ();
5593 int ret_val = 0;
5594 BOOL res;
5596 res = open_thread_token (h_thread,
5597 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
5598 FALSE, &h_token);
5599 if (!res && GetLastError () == ERROR_NO_TOKEN)
5601 if (impersonate_self (SecurityImpersonation))
5602 res = open_thread_token (h_thread,
5603 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
5604 FALSE, &h_token);
5606 if (res)
5608 priv.PrivilegeCount = 1;
5609 priv.Privileges[0].Attributes = enable_p ? SE_PRIVILEGE_ENABLED : 0;
5610 LookupPrivilegeValue (NULL, priv_name, &priv.Privileges[0].Luid);
5611 if (AdjustTokenPrivileges (h_token, FALSE, &priv, priv_size,
5612 old_priv, &opriv_size)
5613 && GetLastError () != ERROR_NOT_ALL_ASSIGNED)
5614 ret_val = 1;
5616 if (h_token)
5617 CloseHandle (h_token);
5619 return ret_val;
5622 static int
5623 restore_privilege (TOKEN_PRIVILEGES *priv)
5625 DWORD priv_size = sizeof (*priv);
5626 HANDLE h_token = NULL;
5627 int ret_val = 0;
5629 if (open_thread_token (GetCurrentThread (),
5630 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
5631 FALSE, &h_token))
5633 if (AdjustTokenPrivileges (h_token, FALSE, priv, priv_size, NULL, NULL)
5634 && GetLastError () != ERROR_NOT_ALL_ASSIGNED)
5635 ret_val = 1;
5637 if (h_token)
5638 CloseHandle (h_token);
5640 return ret_val;
5643 static Lisp_Object
5644 ltime (ULONGLONG time_100ns)
5646 ULONGLONG time_sec = time_100ns / 10000000;
5647 int subsec = time_100ns % 10000000;
5648 return list4i (time_sec >> 16, time_sec & 0xffff,
5649 subsec / 10, subsec % 10 * 100000);
5652 #define U64_TO_LISP_TIME(time) ltime (time)
5654 static int
5655 process_times (HANDLE h_proc, Lisp_Object *ctime, Lisp_Object *etime,
5656 Lisp_Object *stime, Lisp_Object *utime, Lisp_Object *ttime,
5657 double *pcpu)
5659 FILETIME ft_creation, ft_exit, ft_kernel, ft_user, ft_current;
5660 ULONGLONG tem1, tem2, tem3, tem;
5662 if (!h_proc
5663 || !get_process_times_fn
5664 || !(*get_process_times_fn) (h_proc, &ft_creation, &ft_exit,
5665 &ft_kernel, &ft_user))
5666 return 0;
5668 GetSystemTimeAsFileTime (&ft_current);
5670 FILETIME_TO_U64 (tem1, ft_kernel);
5671 *stime = U64_TO_LISP_TIME (tem1);
5673 FILETIME_TO_U64 (tem2, ft_user);
5674 *utime = U64_TO_LISP_TIME (tem2);
5676 tem3 = tem1 + tem2;
5677 *ttime = U64_TO_LISP_TIME (tem3);
5679 FILETIME_TO_U64 (tem, ft_creation);
5680 /* Process no 4 (System) returns zero creation time. */
5681 if (tem)
5682 tem -= utc_base;
5683 *ctime = U64_TO_LISP_TIME (tem);
5685 if (tem)
5687 FILETIME_TO_U64 (tem3, ft_current);
5688 tem = (tem3 - utc_base) - tem;
5690 *etime = U64_TO_LISP_TIME (tem);
5692 if (tem)
5694 *pcpu = 100.0 * (tem1 + tem2) / tem;
5695 if (*pcpu > 100)
5696 *pcpu = 100.0;
5698 else
5699 *pcpu = 0;
5701 return 1;
5704 Lisp_Object
5705 system_process_attributes (Lisp_Object pid)
5707 struct gcpro gcpro1, gcpro2, gcpro3;
5708 Lisp_Object attrs = Qnil;
5709 Lisp_Object cmd_str, decoded_cmd, tem;
5710 HANDLE h_snapshot, h_proc;
5711 DWORD proc_id;
5712 int found_proc = 0;
5713 char uname[UNLEN+1], gname[GNLEN+1], domain[1025];
5714 DWORD ulength = sizeof (uname), dlength = sizeof (domain), needed;
5715 DWORD glength = sizeof (gname);
5716 HANDLE token = NULL;
5717 SID_NAME_USE user_type;
5718 unsigned char *buf = NULL;
5719 DWORD blen = 0;
5720 TOKEN_USER user_token;
5721 TOKEN_PRIMARY_GROUP group_token;
5722 unsigned euid;
5723 unsigned egid;
5724 PROCESS_MEMORY_COUNTERS mem;
5725 PROCESS_MEMORY_COUNTERS_EX mem_ex;
5726 SIZE_T minrss, maxrss;
5727 MEMORYSTATUS memst;
5728 MEMORY_STATUS_EX memstex;
5729 double totphys = 0.0;
5730 Lisp_Object ctime, stime, utime, etime, ttime;
5731 double pcpu;
5732 BOOL result = FALSE;
5734 CHECK_NUMBER_OR_FLOAT (pid);
5735 proc_id = FLOATP (pid) ? XFLOAT_DATA (pid) : XINT (pid);
5737 h_snapshot = create_toolhelp32_snapshot (TH32CS_SNAPPROCESS, 0);
5739 GCPRO3 (attrs, decoded_cmd, tem);
5741 if (h_snapshot != INVALID_HANDLE_VALUE)
5743 PROCESSENTRY32 pe;
5744 BOOL res;
5746 pe.dwSize = sizeof (PROCESSENTRY32);
5747 for (res = process32_first (h_snapshot, &pe); res;
5748 res = process32_next (h_snapshot, &pe))
5750 if (proc_id == pe.th32ProcessID)
5752 if (proc_id == 0)
5753 decoded_cmd = build_string ("Idle");
5754 else
5756 /* Decode the command name from locale-specific
5757 encoding. */
5758 cmd_str = make_unibyte_string (pe.szExeFile,
5759 strlen (pe.szExeFile));
5760 decoded_cmd =
5761 code_convert_string_norecord (cmd_str,
5762 Vlocale_coding_system, 0);
5764 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
5765 attrs = Fcons (Fcons (Qppid,
5766 make_fixnum_or_float (pe.th32ParentProcessID)),
5767 attrs);
5768 attrs = Fcons (Fcons (Qpri, make_number (pe.pcPriClassBase)),
5769 attrs);
5770 attrs = Fcons (Fcons (Qthcount,
5771 make_fixnum_or_float (pe.cntThreads)),
5772 attrs);
5773 found_proc = 1;
5774 break;
5778 CloseHandle (h_snapshot);
5781 if (!found_proc)
5783 UNGCPRO;
5784 return Qnil;
5787 h_proc = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
5788 FALSE, proc_id);
5789 /* If we were denied a handle to the process, try again after
5790 enabling the SeDebugPrivilege in our process. */
5791 if (!h_proc)
5793 TOKEN_PRIVILEGES priv_current;
5795 if (enable_privilege (SE_DEBUG_NAME, TRUE, &priv_current))
5797 h_proc = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
5798 FALSE, proc_id);
5799 restore_privilege (&priv_current);
5800 revert_to_self ();
5803 if (h_proc)
5805 result = open_process_token (h_proc, TOKEN_QUERY, &token);
5806 if (result)
5808 result = get_token_information (token, TokenUser, NULL, 0, &blen);
5809 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
5811 buf = xmalloc (blen);
5812 result = get_token_information (token, TokenUser,
5813 (LPVOID)buf, blen, &needed);
5814 if (result)
5816 memcpy (&user_token, buf, sizeof (user_token));
5817 if (!w32_cached_id (user_token.User.Sid, &euid, uname))
5819 euid = get_rid (user_token.User.Sid);
5820 result = lookup_account_sid (NULL, user_token.User.Sid,
5821 uname, &ulength,
5822 domain, &dlength,
5823 &user_type);
5824 if (result)
5825 w32_add_to_cache (user_token.User.Sid, euid, uname);
5826 else
5828 strcpy (uname, "unknown");
5829 result = TRUE;
5832 ulength = strlen (uname);
5836 if (result)
5838 /* Determine a reasonable euid and gid values. */
5839 if (xstrcasecmp ("administrator", uname) == 0)
5841 euid = 500; /* well-known Administrator uid */
5842 egid = 513; /* well-known None gid */
5844 else
5846 /* Get group id and name. */
5847 result = get_token_information (token, TokenPrimaryGroup,
5848 (LPVOID)buf, blen, &needed);
5849 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
5851 buf = xrealloc (buf, blen = needed);
5852 result = get_token_information (token, TokenPrimaryGroup,
5853 (LPVOID)buf, blen, &needed);
5855 if (result)
5857 memcpy (&group_token, buf, sizeof (group_token));
5858 if (!w32_cached_id (group_token.PrimaryGroup, &egid, gname))
5860 egid = get_rid (group_token.PrimaryGroup);
5861 dlength = sizeof (domain);
5862 result =
5863 lookup_account_sid (NULL, group_token.PrimaryGroup,
5864 gname, &glength, NULL, &dlength,
5865 &user_type);
5866 if (result)
5867 w32_add_to_cache (group_token.PrimaryGroup,
5868 egid, gname);
5869 else
5871 strcpy (gname, "None");
5872 result = TRUE;
5875 glength = strlen (gname);
5879 xfree (buf);
5881 if (!result)
5883 if (!is_windows_9x ())
5885 /* We couldn't open the process token, presumably because of
5886 insufficient access rights. Assume this process is run
5887 by the system. */
5888 strcpy (uname, "SYSTEM");
5889 strcpy (gname, "None");
5890 euid = 18; /* SYSTEM */
5891 egid = 513; /* None */
5892 glength = strlen (gname);
5893 ulength = strlen (uname);
5895 /* If we are running under Windows 9X, where security calls are
5896 not supported, we assume all processes are run by the current
5897 user. */
5898 else if (GetUserName (uname, &ulength))
5900 if (xstrcasecmp ("administrator", uname) == 0)
5901 euid = 0;
5902 else
5903 euid = 123;
5904 egid = euid;
5905 strcpy (gname, "None");
5906 glength = strlen (gname);
5907 ulength = strlen (uname);
5909 else
5911 euid = 123;
5912 egid = 123;
5913 strcpy (uname, "administrator");
5914 ulength = strlen (uname);
5915 strcpy (gname, "None");
5916 glength = strlen (gname);
5918 if (token)
5919 CloseHandle (token);
5922 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (euid)), attrs);
5923 tem = make_unibyte_string (uname, ulength);
5924 attrs = Fcons (Fcons (Quser,
5925 code_convert_string_norecord (tem, Vlocale_coding_system, 0)),
5926 attrs);
5927 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (egid)), attrs);
5928 tem = make_unibyte_string (gname, glength);
5929 attrs = Fcons (Fcons (Qgroup,
5930 code_convert_string_norecord (tem, Vlocale_coding_system, 0)),
5931 attrs);
5933 if (global_memory_status_ex (&memstex))
5934 #if __GNUC__ || (defined (_MSC_VER) && _MSC_VER >= 1300)
5935 totphys = memstex.ullTotalPhys / 1024.0;
5936 #else
5937 /* Visual Studio 6 cannot convert an unsigned __int64 type to
5938 double, so we need to do this for it... */
5940 DWORD tot_hi = memstex.ullTotalPhys >> 32;
5941 DWORD tot_md = (memstex.ullTotalPhys & 0x00000000ffffffff) >> 10;
5942 DWORD tot_lo = memstex.ullTotalPhys % 1024;
5944 totphys = tot_hi * 4194304.0 + tot_md + tot_lo / 1024.0;
5946 #endif /* __GNUC__ || _MSC_VER >= 1300 */
5947 else if (global_memory_status (&memst))
5948 totphys = memst.dwTotalPhys / 1024.0;
5950 if (h_proc
5951 && get_process_memory_info (h_proc, (PROCESS_MEMORY_COUNTERS *)&mem_ex,
5952 sizeof (mem_ex)))
5954 SIZE_T rss = mem_ex.WorkingSetSize / 1024;
5956 attrs = Fcons (Fcons (Qmajflt,
5957 make_fixnum_or_float (mem_ex.PageFaultCount)),
5958 attrs);
5959 attrs = Fcons (Fcons (Qvsize,
5960 make_fixnum_or_float (mem_ex.PrivateUsage / 1024)),
5961 attrs);
5962 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (rss)), attrs);
5963 if (totphys)
5964 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
5966 else if (h_proc
5967 && get_process_memory_info (h_proc, &mem, sizeof (mem)))
5969 SIZE_T rss = mem_ex.WorkingSetSize / 1024;
5971 attrs = Fcons (Fcons (Qmajflt,
5972 make_fixnum_or_float (mem.PageFaultCount)),
5973 attrs);
5974 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (rss)), attrs);
5975 if (totphys)
5976 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
5978 else if (h_proc
5979 && get_process_working_set_size (h_proc, &minrss, &maxrss))
5981 DWORD rss = maxrss / 1024;
5983 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (maxrss / 1024)), attrs);
5984 if (totphys)
5985 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
5988 if (process_times (h_proc, &ctime, &etime, &stime, &utime, &ttime, &pcpu))
5990 attrs = Fcons (Fcons (Qutime, utime), attrs);
5991 attrs = Fcons (Fcons (Qstime, stime), attrs);
5992 attrs = Fcons (Fcons (Qtime, ttime), attrs);
5993 attrs = Fcons (Fcons (Qstart, ctime), attrs);
5994 attrs = Fcons (Fcons (Qetime, etime), attrs);
5995 attrs = Fcons (Fcons (Qpcpu, make_float (pcpu)), attrs);
5998 /* FIXME: Retrieve command line by walking the PEB of the process. */
6000 if (h_proc)
6001 CloseHandle (h_proc);
6002 UNGCPRO;
6003 return attrs;
6007 /* Wrappers for winsock functions to map between our file descriptors
6008 and winsock's handles; also set h_errno for convenience.
6010 To allow Emacs to run on systems which don't have winsock support
6011 installed, we dynamically link to winsock on startup if present, and
6012 otherwise provide the minimum necessary functionality
6013 (eg. gethostname). */
6015 /* function pointers for relevant socket functions */
6016 int (PASCAL *pfn_WSAStartup) (WORD wVersionRequired, LPWSADATA lpWSAData);
6017 void (PASCAL *pfn_WSASetLastError) (int iError);
6018 int (PASCAL *pfn_WSAGetLastError) (void);
6019 int (PASCAL *pfn_WSAEventSelect) (SOCKET s, HANDLE hEventObject, long lNetworkEvents);
6020 HANDLE (PASCAL *pfn_WSACreateEvent) (void);
6021 int (PASCAL *pfn_WSACloseEvent) (HANDLE hEvent);
6022 int (PASCAL *pfn_socket) (int af, int type, int protocol);
6023 int (PASCAL *pfn_bind) (SOCKET s, const struct sockaddr *addr, int namelen);
6024 int (PASCAL *pfn_connect) (SOCKET s, const struct sockaddr *addr, int namelen);
6025 int (PASCAL *pfn_ioctlsocket) (SOCKET s, long cmd, u_long *argp);
6026 int (PASCAL *pfn_recv) (SOCKET s, char * buf, int len, int flags);
6027 int (PASCAL *pfn_send) (SOCKET s, const char * buf, int len, int flags);
6028 int (PASCAL *pfn_closesocket) (SOCKET s);
6029 int (PASCAL *pfn_shutdown) (SOCKET s, int how);
6030 int (PASCAL *pfn_WSACleanup) (void);
6032 u_short (PASCAL *pfn_htons) (u_short hostshort);
6033 u_short (PASCAL *pfn_ntohs) (u_short netshort);
6034 unsigned long (PASCAL *pfn_inet_addr) (const char * cp);
6035 int (PASCAL *pfn_gethostname) (char * name, int namelen);
6036 struct hostent * (PASCAL *pfn_gethostbyname) (const char * name);
6037 struct servent * (PASCAL *pfn_getservbyname) (const char * name, const char * proto);
6038 int (PASCAL *pfn_getpeername) (SOCKET s, struct sockaddr *addr, int * namelen);
6039 int (PASCAL *pfn_setsockopt) (SOCKET s, int level, int optname,
6040 const char * optval, int optlen);
6041 int (PASCAL *pfn_listen) (SOCKET s, int backlog);
6042 int (PASCAL *pfn_getsockname) (SOCKET s, struct sockaddr * name,
6043 int * namelen);
6044 SOCKET (PASCAL *pfn_accept) (SOCKET s, struct sockaddr * addr, int * addrlen);
6045 int (PASCAL *pfn_recvfrom) (SOCKET s, char * buf, int len, int flags,
6046 struct sockaddr * from, int * fromlen);
6047 int (PASCAL *pfn_sendto) (SOCKET s, const char * buf, int len, int flags,
6048 const struct sockaddr * to, int tolen);
6050 /* SetHandleInformation is only needed to make sockets non-inheritable. */
6051 BOOL (WINAPI *pfn_SetHandleInformation) (HANDLE object, DWORD mask, DWORD flags);
6052 #ifndef HANDLE_FLAG_INHERIT
6053 #define HANDLE_FLAG_INHERIT 1
6054 #endif
6056 HANDLE winsock_lib;
6057 static int winsock_inuse;
6059 BOOL
6060 term_winsock (void)
6062 if (winsock_lib != NULL && winsock_inuse == 0)
6064 /* Not sure what would cause WSAENETDOWN, or even if it can happen
6065 after WSAStartup returns successfully, but it seems reasonable
6066 to allow unloading winsock anyway in that case. */
6067 if (pfn_WSACleanup () == 0 ||
6068 pfn_WSAGetLastError () == WSAENETDOWN)
6070 if (FreeLibrary (winsock_lib))
6071 winsock_lib = NULL;
6072 return TRUE;
6075 return FALSE;
6078 BOOL
6079 init_winsock (int load_now)
6081 WSADATA winsockData;
6083 if (winsock_lib != NULL)
6084 return TRUE;
6086 pfn_SetHandleInformation
6087 = (void *) GetProcAddress (GetModuleHandle ("kernel32.dll"),
6088 "SetHandleInformation");
6090 winsock_lib = LoadLibrary ("Ws2_32.dll");
6092 if (winsock_lib != NULL)
6094 /* dynamically link to socket functions */
6096 #define LOAD_PROC(fn) \
6097 if ((pfn_##fn = (void *) GetProcAddress (winsock_lib, #fn)) == NULL) \
6098 goto fail;
6100 LOAD_PROC (WSAStartup);
6101 LOAD_PROC (WSASetLastError);
6102 LOAD_PROC (WSAGetLastError);
6103 LOAD_PROC (WSAEventSelect);
6104 LOAD_PROC (WSACreateEvent);
6105 LOAD_PROC (WSACloseEvent);
6106 LOAD_PROC (socket);
6107 LOAD_PROC (bind);
6108 LOAD_PROC (connect);
6109 LOAD_PROC (ioctlsocket);
6110 LOAD_PROC (recv);
6111 LOAD_PROC (send);
6112 LOAD_PROC (closesocket);
6113 LOAD_PROC (shutdown);
6114 LOAD_PROC (htons);
6115 LOAD_PROC (ntohs);
6116 LOAD_PROC (inet_addr);
6117 LOAD_PROC (gethostname);
6118 LOAD_PROC (gethostbyname);
6119 LOAD_PROC (getservbyname);
6120 LOAD_PROC (getpeername);
6121 LOAD_PROC (WSACleanup);
6122 LOAD_PROC (setsockopt);
6123 LOAD_PROC (listen);
6124 LOAD_PROC (getsockname);
6125 LOAD_PROC (accept);
6126 LOAD_PROC (recvfrom);
6127 LOAD_PROC (sendto);
6128 #undef LOAD_PROC
6130 /* specify version 1.1 of winsock */
6131 if (pfn_WSAStartup (0x101, &winsockData) == 0)
6133 if (winsockData.wVersion != 0x101)
6134 goto fail;
6136 if (!load_now)
6138 /* Report that winsock exists and is usable, but leave
6139 socket functions disabled. I am assuming that calling
6140 WSAStartup does not require any network interaction,
6141 and in particular does not cause or require a dial-up
6142 connection to be established. */
6144 pfn_WSACleanup ();
6145 FreeLibrary (winsock_lib);
6146 winsock_lib = NULL;
6148 winsock_inuse = 0;
6149 return TRUE;
6152 fail:
6153 FreeLibrary (winsock_lib);
6154 winsock_lib = NULL;
6157 return FALSE;
6161 int h_errno = 0;
6163 /* Function to map winsock error codes to errno codes for those errno
6164 code defined in errno.h (errno values not defined by errno.h are
6165 already in nt/inc/sys/socket.h). */
6166 static void
6167 set_errno (void)
6169 int wsa_err;
6171 h_errno = 0;
6172 if (winsock_lib == NULL)
6173 wsa_err = EINVAL;
6174 else
6175 wsa_err = pfn_WSAGetLastError ();
6177 switch (wsa_err)
6179 case WSAEACCES: errno = EACCES; break;
6180 case WSAEBADF: errno = EBADF; break;
6181 case WSAEFAULT: errno = EFAULT; break;
6182 case WSAEINTR: errno = EINTR; break;
6183 case WSAEINVAL: errno = EINVAL; break;
6184 case WSAEMFILE: errno = EMFILE; break;
6185 case WSAENAMETOOLONG: errno = ENAMETOOLONG; break;
6186 case WSAENOTEMPTY: errno = ENOTEMPTY; break;
6187 default: errno = wsa_err; break;
6191 static void
6192 check_errno (void)
6194 h_errno = 0;
6195 if (winsock_lib != NULL)
6196 pfn_WSASetLastError (0);
6199 /* Extend strerror to handle the winsock-specific error codes. */
6200 struct {
6201 int errnum;
6202 char * msg;
6203 } _wsa_errlist[] = {
6204 {WSAEINTR , "Interrupted function call"},
6205 {WSAEBADF , "Bad file descriptor"},
6206 {WSAEACCES , "Permission denied"},
6207 {WSAEFAULT , "Bad address"},
6208 {WSAEINVAL , "Invalid argument"},
6209 {WSAEMFILE , "Too many open files"},
6211 {WSAEWOULDBLOCK , "Resource temporarily unavailable"},
6212 {WSAEINPROGRESS , "Operation now in progress"},
6213 {WSAEALREADY , "Operation already in progress"},
6214 {WSAENOTSOCK , "Socket operation on non-socket"},
6215 {WSAEDESTADDRREQ , "Destination address required"},
6216 {WSAEMSGSIZE , "Message too long"},
6217 {WSAEPROTOTYPE , "Protocol wrong type for socket"},
6218 {WSAENOPROTOOPT , "Bad protocol option"},
6219 {WSAEPROTONOSUPPORT , "Protocol not supported"},
6220 {WSAESOCKTNOSUPPORT , "Socket type not supported"},
6221 {WSAEOPNOTSUPP , "Operation not supported"},
6222 {WSAEPFNOSUPPORT , "Protocol family not supported"},
6223 {WSAEAFNOSUPPORT , "Address family not supported by protocol family"},
6224 {WSAEADDRINUSE , "Address already in use"},
6225 {WSAEADDRNOTAVAIL , "Cannot assign requested address"},
6226 {WSAENETDOWN , "Network is down"},
6227 {WSAENETUNREACH , "Network is unreachable"},
6228 {WSAENETRESET , "Network dropped connection on reset"},
6229 {WSAECONNABORTED , "Software caused connection abort"},
6230 {WSAECONNRESET , "Connection reset by peer"},
6231 {WSAENOBUFS , "No buffer space available"},
6232 {WSAEISCONN , "Socket is already connected"},
6233 {WSAENOTCONN , "Socket is not connected"},
6234 {WSAESHUTDOWN , "Cannot send after socket shutdown"},
6235 {WSAETOOMANYREFS , "Too many references"}, /* not sure */
6236 {WSAETIMEDOUT , "Connection timed out"},
6237 {WSAECONNREFUSED , "Connection refused"},
6238 {WSAELOOP , "Network loop"}, /* not sure */
6239 {WSAENAMETOOLONG , "Name is too long"},
6240 {WSAEHOSTDOWN , "Host is down"},
6241 {WSAEHOSTUNREACH , "No route to host"},
6242 {WSAENOTEMPTY , "Buffer not empty"}, /* not sure */
6243 {WSAEPROCLIM , "Too many processes"},
6244 {WSAEUSERS , "Too many users"}, /* not sure */
6245 {WSAEDQUOT , "Double quote in host name"}, /* really not sure */
6246 {WSAESTALE , "Data is stale"}, /* not sure */
6247 {WSAEREMOTE , "Remote error"}, /* not sure */
6249 {WSASYSNOTREADY , "Network subsystem is unavailable"},
6250 {WSAVERNOTSUPPORTED , "WINSOCK.DLL version out of range"},
6251 {WSANOTINITIALISED , "Winsock not initialized successfully"},
6252 {WSAEDISCON , "Graceful shutdown in progress"},
6253 #ifdef WSAENOMORE
6254 {WSAENOMORE , "No more operations allowed"}, /* not sure */
6255 {WSAECANCELLED , "Operation cancelled"}, /* not sure */
6256 {WSAEINVALIDPROCTABLE , "Invalid procedure table from service provider"},
6257 {WSAEINVALIDPROVIDER , "Invalid service provider version number"},
6258 {WSAEPROVIDERFAILEDINIT , "Unable to initialize a service provider"},
6259 {WSASYSCALLFAILURE , "System call failure"},
6260 {WSASERVICE_NOT_FOUND , "Service not found"}, /* not sure */
6261 {WSATYPE_NOT_FOUND , "Class type not found"},
6262 {WSA_E_NO_MORE , "No more resources available"}, /* really not sure */
6263 {WSA_E_CANCELLED , "Operation already cancelled"}, /* really not sure */
6264 {WSAEREFUSED , "Operation refused"}, /* not sure */
6265 #endif
6267 {WSAHOST_NOT_FOUND , "Host not found"},
6268 {WSATRY_AGAIN , "Authoritative host not found during name lookup"},
6269 {WSANO_RECOVERY , "Non-recoverable error during name lookup"},
6270 {WSANO_DATA , "Valid name, no data record of requested type"},
6272 {-1, NULL}
6275 char *
6276 sys_strerror (int error_no)
6278 int i;
6279 static char unknown_msg[40];
6281 if (error_no >= 0 && error_no < sys_nerr)
6282 return sys_errlist[error_no];
6284 for (i = 0; _wsa_errlist[i].errnum >= 0; i++)
6285 if (_wsa_errlist[i].errnum == error_no)
6286 return _wsa_errlist[i].msg;
6288 sprintf (unknown_msg, "Unidentified error: %d", error_no);
6289 return unknown_msg;
6292 /* [andrewi 3-May-96] I've had conflicting results using both methods,
6293 but I believe the method of keeping the socket handle separate (and
6294 insuring it is not inheritable) is the correct one. */
6296 #define SOCK_HANDLE(fd) ((SOCKET) fd_info[fd].hnd)
6298 static int socket_to_fd (SOCKET s);
6301 sys_socket (int af, int type, int protocol)
6303 SOCKET s;
6305 if (winsock_lib == NULL)
6307 errno = ENETDOWN;
6308 return INVALID_SOCKET;
6311 check_errno ();
6313 /* call the real socket function */
6314 s = pfn_socket (af, type, protocol);
6316 if (s != INVALID_SOCKET)
6317 return socket_to_fd (s);
6319 set_errno ();
6320 return -1;
6323 /* Convert a SOCKET to a file descriptor. */
6324 static int
6325 socket_to_fd (SOCKET s)
6327 int fd;
6328 child_process * cp;
6330 /* Although under NT 3.5 _open_osfhandle will accept a socket
6331 handle, if opened with SO_OPENTYPE == SO_SYNCHRONOUS_NONALERT,
6332 that does not work under NT 3.1. However, we can get the same
6333 effect by using a backdoor function to replace an existing
6334 descriptor handle with the one we want. */
6336 /* allocate a file descriptor (with appropriate flags) */
6337 fd = _open ("NUL:", _O_RDWR);
6338 if (fd >= 0)
6340 /* Make a non-inheritable copy of the socket handle. Note
6341 that it is possible that sockets aren't actually kernel
6342 handles, which appears to be the case on Windows 9x when
6343 the MS Proxy winsock client is installed. */
6345 /* Apparently there is a bug in NT 3.51 with some service
6346 packs, which prevents using DuplicateHandle to make a
6347 socket handle non-inheritable (causes WSACleanup to
6348 hang). The work-around is to use SetHandleInformation
6349 instead if it is available and implemented. */
6350 if (pfn_SetHandleInformation)
6352 pfn_SetHandleInformation ((HANDLE) s, HANDLE_FLAG_INHERIT, 0);
6354 else
6356 HANDLE parent = GetCurrentProcess ();
6357 HANDLE new_s = INVALID_HANDLE_VALUE;
6359 if (DuplicateHandle (parent,
6360 (HANDLE) s,
6361 parent,
6362 &new_s,
6364 FALSE,
6365 DUPLICATE_SAME_ACCESS))
6367 /* It is possible that DuplicateHandle succeeds even
6368 though the socket wasn't really a kernel handle,
6369 because a real handle has the same value. So
6370 test whether the new handle really is a socket. */
6371 long nonblocking = 0;
6372 if (pfn_ioctlsocket ((SOCKET) new_s, FIONBIO, &nonblocking) == 0)
6374 pfn_closesocket (s);
6375 s = (SOCKET) new_s;
6377 else
6379 CloseHandle (new_s);
6384 eassert (fd < MAXDESC);
6385 fd_info[fd].hnd = (HANDLE) s;
6387 /* set our own internal flags */
6388 fd_info[fd].flags = FILE_SOCKET | FILE_BINARY | FILE_READ | FILE_WRITE;
6390 cp = new_child ();
6391 if (cp)
6393 cp->fd = fd;
6394 cp->status = STATUS_READ_ACKNOWLEDGED;
6396 /* attach child_process to fd_info */
6397 if (fd_info[ fd ].cp != NULL)
6399 DebPrint (("sys_socket: fd_info[%d] apparently in use!\n", fd));
6400 emacs_abort ();
6403 fd_info[ fd ].cp = cp;
6405 /* success! */
6406 winsock_inuse++; /* count open sockets */
6407 return fd;
6410 /* clean up */
6411 _close (fd);
6413 else
6414 pfn_closesocket (s);
6415 errno = EMFILE;
6416 return -1;
6420 sys_bind (int s, const struct sockaddr * addr, int namelen)
6422 if (winsock_lib == NULL)
6424 errno = ENOTSOCK;
6425 return SOCKET_ERROR;
6428 check_errno ();
6429 if (fd_info[s].flags & FILE_SOCKET)
6431 int rc = pfn_bind (SOCK_HANDLE (s), addr, namelen);
6432 if (rc == SOCKET_ERROR)
6433 set_errno ();
6434 return rc;
6436 errno = ENOTSOCK;
6437 return SOCKET_ERROR;
6441 sys_connect (int s, const struct sockaddr * name, int namelen)
6443 if (winsock_lib == NULL)
6445 errno = ENOTSOCK;
6446 return SOCKET_ERROR;
6449 check_errno ();
6450 if (fd_info[s].flags & FILE_SOCKET)
6452 int rc = pfn_connect (SOCK_HANDLE (s), name, namelen);
6453 if (rc == SOCKET_ERROR)
6454 set_errno ();
6455 return rc;
6457 errno = ENOTSOCK;
6458 return SOCKET_ERROR;
6461 u_short
6462 sys_htons (u_short hostshort)
6464 return (winsock_lib != NULL) ?
6465 pfn_htons (hostshort) : hostshort;
6468 u_short
6469 sys_ntohs (u_short netshort)
6471 return (winsock_lib != NULL) ?
6472 pfn_ntohs (netshort) : netshort;
6475 unsigned long
6476 sys_inet_addr (const char * cp)
6478 return (winsock_lib != NULL) ?
6479 pfn_inet_addr (cp) : INADDR_NONE;
6483 sys_gethostname (char * name, int namelen)
6485 if (winsock_lib != NULL)
6487 int retval;
6489 check_errno ();
6490 retval = pfn_gethostname (name, namelen);
6491 if (retval == SOCKET_ERROR)
6492 set_errno ();
6493 return retval;
6496 if (namelen > MAX_COMPUTERNAME_LENGTH)
6497 return !GetComputerName (name, (DWORD *)&namelen);
6499 errno = EFAULT;
6500 return SOCKET_ERROR;
6503 struct hostent *
6504 sys_gethostbyname (const char * name)
6506 struct hostent * host;
6507 int h_err = h_errno;
6509 if (winsock_lib == NULL)
6511 h_errno = NO_RECOVERY;
6512 errno = ENETDOWN;
6513 return NULL;
6516 check_errno ();
6517 host = pfn_gethostbyname (name);
6518 if (!host)
6520 set_errno ();
6521 h_errno = errno;
6523 else
6524 h_errno = h_err;
6525 return host;
6528 struct servent *
6529 sys_getservbyname (const char * name, const char * proto)
6531 struct servent * serv;
6533 if (winsock_lib == NULL)
6535 errno = ENETDOWN;
6536 return NULL;
6539 check_errno ();
6540 serv = pfn_getservbyname (name, proto);
6541 if (!serv)
6542 set_errno ();
6543 return serv;
6547 sys_getpeername (int s, struct sockaddr *addr, int * namelen)
6549 if (winsock_lib == NULL)
6551 errno = ENETDOWN;
6552 return SOCKET_ERROR;
6555 check_errno ();
6556 if (fd_info[s].flags & FILE_SOCKET)
6558 int rc = pfn_getpeername (SOCK_HANDLE (s), addr, namelen);
6559 if (rc == SOCKET_ERROR)
6560 set_errno ();
6561 return rc;
6563 errno = ENOTSOCK;
6564 return SOCKET_ERROR;
6568 sys_shutdown (int s, int how)
6570 if (winsock_lib == NULL)
6572 errno = ENETDOWN;
6573 return SOCKET_ERROR;
6576 check_errno ();
6577 if (fd_info[s].flags & FILE_SOCKET)
6579 int rc = pfn_shutdown (SOCK_HANDLE (s), how);
6580 if (rc == SOCKET_ERROR)
6581 set_errno ();
6582 return rc;
6584 errno = ENOTSOCK;
6585 return SOCKET_ERROR;
6589 sys_setsockopt (int s, int level, int optname, const void * optval, int optlen)
6591 if (winsock_lib == NULL)
6593 errno = ENETDOWN;
6594 return SOCKET_ERROR;
6597 check_errno ();
6598 if (fd_info[s].flags & FILE_SOCKET)
6600 int rc = pfn_setsockopt (SOCK_HANDLE (s), level, optname,
6601 (const char *)optval, optlen);
6602 if (rc == SOCKET_ERROR)
6603 set_errno ();
6604 return rc;
6606 errno = ENOTSOCK;
6607 return SOCKET_ERROR;
6611 sys_listen (int s, int backlog)
6613 if (winsock_lib == NULL)
6615 errno = ENETDOWN;
6616 return SOCKET_ERROR;
6619 check_errno ();
6620 if (fd_info[s].flags & FILE_SOCKET)
6622 int rc = pfn_listen (SOCK_HANDLE (s), backlog);
6623 if (rc == SOCKET_ERROR)
6624 set_errno ();
6625 else
6626 fd_info[s].flags |= FILE_LISTEN;
6627 return rc;
6629 errno = ENOTSOCK;
6630 return SOCKET_ERROR;
6634 sys_getsockname (int s, struct sockaddr * name, int * namelen)
6636 if (winsock_lib == NULL)
6638 errno = ENETDOWN;
6639 return SOCKET_ERROR;
6642 check_errno ();
6643 if (fd_info[s].flags & FILE_SOCKET)
6645 int rc = pfn_getsockname (SOCK_HANDLE (s), name, namelen);
6646 if (rc == SOCKET_ERROR)
6647 set_errno ();
6648 return rc;
6650 errno = ENOTSOCK;
6651 return SOCKET_ERROR;
6655 sys_accept (int s, struct sockaddr * addr, int * addrlen)
6657 if (winsock_lib == NULL)
6659 errno = ENETDOWN;
6660 return -1;
6663 check_errno ();
6664 if (fd_info[s].flags & FILE_LISTEN)
6666 SOCKET t = pfn_accept (SOCK_HANDLE (s), addr, addrlen);
6667 int fd = -1;
6668 if (t == INVALID_SOCKET)
6669 set_errno ();
6670 else
6671 fd = socket_to_fd (t);
6673 if (fd >= 0)
6675 fd_info[s].cp->status = STATUS_READ_ACKNOWLEDGED;
6676 ResetEvent (fd_info[s].cp->char_avail);
6678 return fd;
6680 errno = ENOTSOCK;
6681 return -1;
6685 sys_recvfrom (int s, char * buf, int len, int flags,
6686 struct sockaddr * from, int * fromlen)
6688 if (winsock_lib == NULL)
6690 errno = ENETDOWN;
6691 return SOCKET_ERROR;
6694 check_errno ();
6695 if (fd_info[s].flags & FILE_SOCKET)
6697 int rc = pfn_recvfrom (SOCK_HANDLE (s), buf, len, flags, from, fromlen);
6698 if (rc == SOCKET_ERROR)
6699 set_errno ();
6700 return rc;
6702 errno = ENOTSOCK;
6703 return SOCKET_ERROR;
6707 sys_sendto (int s, const char * buf, int len, int flags,
6708 const struct sockaddr * to, int tolen)
6710 if (winsock_lib == NULL)
6712 errno = ENETDOWN;
6713 return SOCKET_ERROR;
6716 check_errno ();
6717 if (fd_info[s].flags & FILE_SOCKET)
6719 int rc = pfn_sendto (SOCK_HANDLE (s), buf, len, flags, to, tolen);
6720 if (rc == SOCKET_ERROR)
6721 set_errno ();
6722 return rc;
6724 errno = ENOTSOCK;
6725 return SOCKET_ERROR;
6728 /* Windows does not have an fcntl function. Provide an implementation
6729 good enough for Emacs. */
6731 fcntl (int s, int cmd, int options)
6733 /* In the w32 Emacs port, fcntl (fd, F_DUPFD_CLOEXEC, fd1) is always
6734 invoked in a context where fd1 is closed and all descriptors less
6735 than fd1 are open, so sys_dup is an adequate implementation. */
6736 if (cmd == F_DUPFD_CLOEXEC)
6737 return sys_dup (s);
6739 if (winsock_lib == NULL)
6741 errno = ENETDOWN;
6742 return -1;
6745 check_errno ();
6746 if (fd_info[s].flags & FILE_SOCKET)
6748 if (cmd == F_SETFL && options == O_NONBLOCK)
6750 unsigned long nblock = 1;
6751 int rc = pfn_ioctlsocket (SOCK_HANDLE (s), FIONBIO, &nblock);
6752 if (rc == SOCKET_ERROR)
6753 set_errno ();
6754 /* Keep track of the fact that we set this to non-blocking. */
6755 fd_info[s].flags |= FILE_NDELAY;
6756 return rc;
6758 else
6760 errno = EINVAL;
6761 return SOCKET_ERROR;
6764 errno = ENOTSOCK;
6765 return SOCKET_ERROR;
6769 /* Shadow main io functions: we need to handle pipes and sockets more
6770 intelligently, and implement non-blocking mode as well. */
6773 sys_close (int fd)
6775 int rc;
6777 if (fd < 0)
6779 errno = EBADF;
6780 return -1;
6783 if (fd < MAXDESC && fd_info[fd].cp)
6785 child_process * cp = fd_info[fd].cp;
6787 fd_info[fd].cp = NULL;
6789 if (CHILD_ACTIVE (cp))
6791 /* if last descriptor to active child_process then cleanup */
6792 int i;
6793 for (i = 0; i < MAXDESC; i++)
6795 if (i == fd)
6796 continue;
6797 if (fd_info[i].cp == cp)
6798 break;
6800 if (i == MAXDESC)
6802 if (fd_info[fd].flags & FILE_SOCKET)
6804 if (winsock_lib == NULL) emacs_abort ();
6806 pfn_shutdown (SOCK_HANDLE (fd), 2);
6807 rc = pfn_closesocket (SOCK_HANDLE (fd));
6809 winsock_inuse--; /* count open sockets */
6811 /* If the process handle is NULL, it's either a socket
6812 or serial connection, or a subprocess that was
6813 already reaped by reap_subprocess, but whose
6814 resources were not yet freed, because its output was
6815 not fully read yet by the time it was reaped. (This
6816 usually happens with async subprocesses whose output
6817 is being read by Emacs.) Otherwise, this process was
6818 not reaped yet, so we set its FD to a negative value
6819 to make sure sys_select will eventually get to
6820 calling the SIGCHLD handler for it, which will then
6821 invoke waitpid and reap_subprocess. */
6822 if (cp->procinfo.hProcess == NULL)
6823 delete_child (cp);
6824 else
6825 cp->fd = -1;
6830 if (fd >= 0 && fd < MAXDESC)
6831 fd_info[fd].flags = 0;
6833 /* Note that sockets do not need special treatment here (at least on
6834 NT and Windows 95 using the standard tcp/ip stacks) - it appears that
6835 closesocket is equivalent to CloseHandle, which is to be expected
6836 because socket handles are fully fledged kernel handles. */
6837 rc = _close (fd);
6839 return rc;
6843 sys_dup (int fd)
6845 int new_fd;
6847 new_fd = _dup (fd);
6848 if (new_fd >= 0 && new_fd < MAXDESC)
6850 /* duplicate our internal info as well */
6851 fd_info[new_fd] = fd_info[fd];
6853 return new_fd;
6857 sys_dup2 (int src, int dst)
6859 int rc;
6861 if (dst < 0 || dst >= MAXDESC)
6863 errno = EBADF;
6864 return -1;
6867 /* make sure we close the destination first if it's a pipe or socket */
6868 if (src != dst && fd_info[dst].flags != 0)
6869 sys_close (dst);
6871 rc = _dup2 (src, dst);
6872 if (rc == 0)
6874 /* duplicate our internal info as well */
6875 fd_info[dst] = fd_info[src];
6877 return rc;
6881 pipe2 (int * phandles, int pipe2_flags)
6883 int rc;
6884 unsigned flags;
6886 eassert (pipe2_flags == O_CLOEXEC);
6888 /* make pipe handles non-inheritable; when we spawn a child, we
6889 replace the relevant handle with an inheritable one. Also put
6890 pipes into binary mode; we will do text mode translation ourselves
6891 if required. */
6892 rc = _pipe (phandles, 0, _O_NOINHERIT | _O_BINARY);
6894 if (rc == 0)
6896 /* Protect against overflow, since Windows can open more handles than
6897 our fd_info array has room for. */
6898 if (phandles[0] >= MAXDESC || phandles[1] >= MAXDESC)
6900 _close (phandles[0]);
6901 _close (phandles[1]);
6902 errno = EMFILE;
6903 rc = -1;
6905 else
6907 flags = FILE_PIPE | FILE_READ | FILE_BINARY;
6908 fd_info[phandles[0]].flags = flags;
6910 flags = FILE_PIPE | FILE_WRITE | FILE_BINARY;
6911 fd_info[phandles[1]].flags = flags;
6915 return rc;
6918 /* Function to do blocking read of one byte, needed to implement
6919 select. It is only allowed on communication ports, sockets, or
6920 pipes. */
6922 _sys_read_ahead (int fd)
6924 child_process * cp;
6925 int rc;
6927 if (fd < 0 || fd >= MAXDESC)
6928 return STATUS_READ_ERROR;
6930 cp = fd_info[fd].cp;
6932 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
6933 return STATUS_READ_ERROR;
6935 if ((fd_info[fd].flags & (FILE_PIPE | FILE_SERIAL | FILE_SOCKET)) == 0
6936 || (fd_info[fd].flags & FILE_READ) == 0)
6938 DebPrint (("_sys_read_ahead: internal error: fd %d is not a pipe, serial port, or socket!\n", fd));
6939 emacs_abort ();
6942 cp->status = STATUS_READ_IN_PROGRESS;
6944 if (fd_info[fd].flags & FILE_PIPE)
6946 rc = _read (fd, &cp->chr, sizeof (char));
6948 /* Give subprocess time to buffer some more output for us before
6949 reporting that input is available; we need this because Windows 95
6950 connects DOS programs to pipes by making the pipe appear to be
6951 the normal console stdout - as a result most DOS programs will
6952 write to stdout without buffering, ie. one character at a
6953 time. Even some W32 programs do this - "dir" in a command
6954 shell on NT is very slow if we don't do this. */
6955 if (rc > 0)
6957 int wait = w32_pipe_read_delay;
6959 if (wait > 0)
6960 Sleep (wait);
6961 else if (wait < 0)
6962 while (++wait <= 0)
6963 /* Yield remainder of our time slice, effectively giving a
6964 temporary priority boost to the child process. */
6965 Sleep (0);
6968 else if (fd_info[fd].flags & FILE_SERIAL)
6970 HANDLE hnd = fd_info[fd].hnd;
6971 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_read;
6972 COMMTIMEOUTS ct;
6974 /* Configure timeouts for blocking read. */
6975 if (!GetCommTimeouts (hnd, &ct))
6977 cp->status = STATUS_READ_ERROR;
6978 return STATUS_READ_ERROR;
6980 ct.ReadIntervalTimeout = 0;
6981 ct.ReadTotalTimeoutMultiplier = 0;
6982 ct.ReadTotalTimeoutConstant = 0;
6983 if (!SetCommTimeouts (hnd, &ct))
6985 cp->status = STATUS_READ_ERROR;
6986 return STATUS_READ_ERROR;
6989 if (!ReadFile (hnd, &cp->chr, sizeof (char), (DWORD*) &rc, ovl))
6991 if (GetLastError () != ERROR_IO_PENDING)
6993 cp->status = STATUS_READ_ERROR;
6994 return STATUS_READ_ERROR;
6996 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &rc, TRUE))
6998 cp->status = STATUS_READ_ERROR;
6999 return STATUS_READ_ERROR;
7003 else if (fd_info[fd].flags & FILE_SOCKET)
7005 unsigned long nblock = 0;
7006 /* We always want this to block, so temporarily disable NDELAY. */
7007 if (fd_info[fd].flags & FILE_NDELAY)
7008 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
7010 rc = pfn_recv (SOCK_HANDLE (fd), &cp->chr, sizeof (char), 0);
7012 if (fd_info[fd].flags & FILE_NDELAY)
7014 nblock = 1;
7015 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
7019 if (rc == sizeof (char))
7020 cp->status = STATUS_READ_SUCCEEDED;
7021 else
7022 cp->status = STATUS_READ_FAILED;
7024 return cp->status;
7028 _sys_wait_accept (int fd)
7030 HANDLE hEv;
7031 child_process * cp;
7032 int rc;
7034 if (fd < 0 || fd >= MAXDESC)
7035 return STATUS_READ_ERROR;
7037 cp = fd_info[fd].cp;
7039 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
7040 return STATUS_READ_ERROR;
7042 cp->status = STATUS_READ_FAILED;
7044 hEv = pfn_WSACreateEvent ();
7045 rc = pfn_WSAEventSelect (SOCK_HANDLE (fd), hEv, FD_ACCEPT);
7046 if (rc != SOCKET_ERROR)
7048 rc = WaitForSingleObject (hEv, INFINITE);
7049 pfn_WSAEventSelect (SOCK_HANDLE (fd), NULL, 0);
7050 if (rc == WAIT_OBJECT_0)
7051 cp->status = STATUS_READ_SUCCEEDED;
7053 pfn_WSACloseEvent (hEv);
7055 return cp->status;
7059 sys_read (int fd, char * buffer, unsigned int count)
7061 int nchars;
7062 int to_read;
7063 DWORD waiting;
7064 char * orig_buffer = buffer;
7066 if (fd < 0)
7068 errno = EBADF;
7069 return -1;
7072 if (fd < MAXDESC && fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET | FILE_SERIAL))
7074 child_process *cp = fd_info[fd].cp;
7076 if ((fd_info[fd].flags & FILE_READ) == 0)
7078 errno = EBADF;
7079 return -1;
7082 nchars = 0;
7084 /* re-read CR carried over from last read */
7085 if (fd_info[fd].flags & FILE_LAST_CR)
7087 if (fd_info[fd].flags & FILE_BINARY) emacs_abort ();
7088 *buffer++ = 0x0d;
7089 count--;
7090 nchars++;
7091 fd_info[fd].flags &= ~FILE_LAST_CR;
7094 /* presence of a child_process structure means we are operating in
7095 non-blocking mode - otherwise we just call _read directly.
7096 Note that the child_process structure might be missing because
7097 reap_subprocess has been called; in this case the pipe is
7098 already broken, so calling _read on it is okay. */
7099 if (cp)
7101 int current_status = cp->status;
7103 switch (current_status)
7105 case STATUS_READ_FAILED:
7106 case STATUS_READ_ERROR:
7107 /* report normal EOF if nothing in buffer */
7108 if (nchars <= 0)
7109 fd_info[fd].flags |= FILE_AT_EOF;
7110 return nchars;
7112 case STATUS_READ_READY:
7113 case STATUS_READ_IN_PROGRESS:
7114 DebPrint (("sys_read called when read is in progress\n"));
7115 errno = EWOULDBLOCK;
7116 return -1;
7118 case STATUS_READ_SUCCEEDED:
7119 /* consume read-ahead char */
7120 *buffer++ = cp->chr;
7121 count--;
7122 nchars++;
7123 cp->status = STATUS_READ_ACKNOWLEDGED;
7124 ResetEvent (cp->char_avail);
7126 case STATUS_READ_ACKNOWLEDGED:
7127 break;
7129 default:
7130 DebPrint (("sys_read: bad status %d\n", current_status));
7131 errno = EBADF;
7132 return -1;
7135 if (fd_info[fd].flags & FILE_PIPE)
7137 PeekNamedPipe ((HANDLE) _get_osfhandle (fd), NULL, 0, NULL, &waiting, NULL);
7138 to_read = min (waiting, (DWORD) count);
7140 if (to_read > 0)
7141 nchars += _read (fd, buffer, to_read);
7143 else if (fd_info[fd].flags & FILE_SERIAL)
7145 HANDLE hnd = fd_info[fd].hnd;
7146 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_read;
7147 int rc = 0;
7148 COMMTIMEOUTS ct;
7150 if (count > 0)
7152 /* Configure timeouts for non-blocking read. */
7153 if (!GetCommTimeouts (hnd, &ct))
7155 errno = EIO;
7156 return -1;
7158 ct.ReadIntervalTimeout = MAXDWORD;
7159 ct.ReadTotalTimeoutMultiplier = 0;
7160 ct.ReadTotalTimeoutConstant = 0;
7161 if (!SetCommTimeouts (hnd, &ct))
7163 errno = EIO;
7164 return -1;
7167 if (!ResetEvent (ovl->hEvent))
7169 errno = EIO;
7170 return -1;
7172 if (!ReadFile (hnd, buffer, count, (DWORD*) &rc, ovl))
7174 if (GetLastError () != ERROR_IO_PENDING)
7176 errno = EIO;
7177 return -1;
7179 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &rc, TRUE))
7181 errno = EIO;
7182 return -1;
7185 nchars += rc;
7188 else /* FILE_SOCKET */
7190 if (winsock_lib == NULL) emacs_abort ();
7192 /* do the equivalent of a non-blocking read */
7193 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONREAD, &waiting);
7194 if (waiting == 0 && nchars == 0)
7196 errno = EWOULDBLOCK;
7197 return -1;
7200 if (waiting)
7202 /* always use binary mode for sockets */
7203 int res = pfn_recv (SOCK_HANDLE (fd), buffer, count, 0);
7204 if (res == SOCKET_ERROR)
7206 DebPrint (("sys_read.recv failed with error %d on socket %ld\n",
7207 pfn_WSAGetLastError (), SOCK_HANDLE (fd)));
7208 set_errno ();
7209 return -1;
7211 nchars += res;
7215 else
7217 int nread = _read (fd, buffer, count);
7218 if (nread >= 0)
7219 nchars += nread;
7220 else if (nchars == 0)
7221 nchars = nread;
7224 if (nchars <= 0)
7225 fd_info[fd].flags |= FILE_AT_EOF;
7226 /* Perform text mode translation if required. */
7227 else if ((fd_info[fd].flags & FILE_BINARY) == 0)
7229 nchars = crlf_to_lf (nchars, orig_buffer);
7230 /* If buffer contains only CR, return that. To be absolutely
7231 sure we should attempt to read the next char, but in
7232 practice a CR to be followed by LF would not appear by
7233 itself in the buffer. */
7234 if (nchars > 1 && orig_buffer[nchars - 1] == 0x0d)
7236 fd_info[fd].flags |= FILE_LAST_CR;
7237 nchars--;
7241 else
7242 nchars = _read (fd, buffer, count);
7244 return nchars;
7247 /* From w32xfns.c */
7248 extern HANDLE interrupt_handle;
7250 /* For now, don't bother with a non-blocking mode */
7252 sys_write (int fd, const void * buffer, unsigned int count)
7254 int nchars;
7256 if (fd < 0)
7258 errno = EBADF;
7259 return -1;
7262 if (fd < MAXDESC && fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET | FILE_SERIAL))
7264 if ((fd_info[fd].flags & FILE_WRITE) == 0)
7266 errno = EBADF;
7267 return -1;
7270 /* Perform text mode translation if required. */
7271 if ((fd_info[fd].flags & FILE_BINARY) == 0)
7273 char * tmpbuf = alloca (count * 2);
7274 unsigned char * src = (void *)buffer;
7275 unsigned char * dst = tmpbuf;
7276 int nbytes = count;
7278 while (1)
7280 unsigned char *next;
7281 /* copy next line or remaining bytes */
7282 next = _memccpy (dst, src, '\n', nbytes);
7283 if (next)
7285 /* copied one line ending with '\n' */
7286 int copied = next - dst;
7287 nbytes -= copied;
7288 src += copied;
7289 /* insert '\r' before '\n' */
7290 next[-1] = '\r';
7291 next[0] = '\n';
7292 dst = next + 1;
7293 count++;
7295 else
7296 /* copied remaining partial line -> now finished */
7297 break;
7299 buffer = tmpbuf;
7303 if (fd < MAXDESC && fd_info[fd].flags & FILE_SERIAL)
7305 HANDLE hnd = (HANDLE) _get_osfhandle (fd);
7306 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_write;
7307 HANDLE wait_hnd[2] = { interrupt_handle, ovl->hEvent };
7308 DWORD active = 0;
7310 if (!WriteFile (hnd, buffer, count, (DWORD*) &nchars, ovl))
7312 if (GetLastError () != ERROR_IO_PENDING)
7314 errno = EIO;
7315 return -1;
7317 if (detect_input_pending ())
7318 active = MsgWaitForMultipleObjects (2, wait_hnd, FALSE, INFINITE,
7319 QS_ALLINPUT);
7320 else
7321 active = WaitForMultipleObjects (2, wait_hnd, FALSE, INFINITE);
7322 if (active == WAIT_OBJECT_0)
7323 { /* User pressed C-g, cancel write, then leave. Don't bother
7324 cleaning up as we may only get stuck in buggy drivers. */
7325 PurgeComm (hnd, PURGE_TXABORT | PURGE_TXCLEAR);
7326 CancelIo (hnd);
7327 errno = EIO;
7328 return -1;
7330 if (active == WAIT_OBJECT_0 + 1
7331 && !GetOverlappedResult (hnd, ovl, (DWORD*) &nchars, TRUE))
7333 errno = EIO;
7334 return -1;
7338 else if (fd < MAXDESC && fd_info[fd].flags & FILE_SOCKET)
7340 unsigned long nblock = 0;
7341 if (winsock_lib == NULL) emacs_abort ();
7343 /* TODO: implement select() properly so non-blocking I/O works. */
7344 /* For now, make sure the write blocks. */
7345 if (fd_info[fd].flags & FILE_NDELAY)
7346 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
7348 nchars = pfn_send (SOCK_HANDLE (fd), buffer, count, 0);
7350 /* Set the socket back to non-blocking if it was before,
7351 for other operations that support it. */
7352 if (fd_info[fd].flags & FILE_NDELAY)
7354 nblock = 1;
7355 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
7358 if (nchars == SOCKET_ERROR)
7360 DebPrint (("sys_write.send failed with error %d on socket %ld\n",
7361 pfn_WSAGetLastError (), SOCK_HANDLE (fd)));
7362 set_errno ();
7365 else
7367 /* Some networked filesystems don't like too large writes, so
7368 break them into smaller chunks. See the Comments section of
7369 the MSDN documentation of WriteFile for details behind the
7370 choice of the value of CHUNK below. See also the thread
7371 http://thread.gmane.org/gmane.comp.version-control.git/145294
7372 in the git mailing list. */
7373 const unsigned char *p = buffer;
7374 const unsigned chunk = 30 * 1024 * 1024;
7376 nchars = 0;
7377 while (count > 0)
7379 unsigned this_chunk = count < chunk ? count : chunk;
7380 int n = _write (fd, p, this_chunk);
7382 nchars += n;
7383 if (n < 0)
7385 nchars = n;
7386 break;
7388 else if (n < this_chunk)
7389 break;
7390 count -= n;
7391 p += n;
7395 return nchars;
7398 /* The Windows CRT functions are "optimized for speed", so they don't
7399 check for timezone and DST changes if they were last called less
7400 than 1 minute ago (see http://support.microsoft.com/kb/821231). So
7401 all Emacs features that repeatedly call time functions (e.g.,
7402 display-time) are in real danger of missing timezone and DST
7403 changes. Calling tzset before each localtime call fixes that. */
7404 struct tm *
7405 sys_localtime (const time_t *t)
7407 tzset ();
7408 return localtime (t);
7413 /* Try loading LIBRARY_ID from the file(s) specified in
7414 Vdynamic_library_alist. If the library is loaded successfully,
7415 return the handle of the DLL, and record the filename in the
7416 property :loaded-from of LIBRARY_ID. If the library could not be
7417 found, or when it was already loaded (because the handle is not
7418 recorded anywhere, and so is lost after use), return NULL.
7420 We could also save the handle in :loaded-from, but currently
7421 there's no use case for it. */
7422 HMODULE
7423 w32_delayed_load (Lisp_Object library_id)
7425 HMODULE library_dll = NULL;
7427 CHECK_SYMBOL (library_id);
7429 if (CONSP (Vdynamic_library_alist)
7430 && NILP (Fassq (library_id, Vlibrary_cache)))
7432 Lisp_Object found = Qnil;
7433 Lisp_Object dlls = Fassq (library_id, Vdynamic_library_alist);
7435 if (CONSP (dlls))
7436 for (dlls = XCDR (dlls); CONSP (dlls); dlls = XCDR (dlls))
7438 CHECK_STRING_CAR (dlls);
7439 if ((library_dll = LoadLibrary (SDATA (XCAR (dlls)))))
7441 char name[MAX_PATH];
7442 DWORD len;
7444 len = GetModuleFileNameA (library_dll, name, sizeof (name));
7445 found = Fcons (XCAR (dlls),
7446 (len > 0)
7447 /* Possibly truncated */
7448 ? make_specified_string (name, -1, len, 1)
7449 : Qnil);
7450 break;
7454 Fput (library_id, QCloaded_from, found);
7457 return library_dll;
7461 void
7462 check_windows_init_file (void)
7464 /* A common indication that Emacs is not installed properly is when
7465 it cannot find the Windows installation file. If this file does
7466 not exist in the expected place, tell the user. */
7468 if (!noninteractive && !inhibit_window_system
7469 /* Vload_path is not yet initialized when we are loading
7470 loadup.el. */
7471 && NILP (Vpurify_flag))
7473 Lisp_Object init_file;
7474 int fd;
7476 init_file = build_string ("term/w32-win");
7477 fd = openp (Vload_path, init_file, Fget_load_suffixes (), NULL, Qnil);
7478 if (fd < 0)
7480 Lisp_Object load_path_print = Fprin1_to_string (Vload_path, Qnil);
7481 char *init_file_name = SDATA (init_file);
7482 char *load_path = SDATA (load_path_print);
7483 char *buffer = alloca (1024
7484 + strlen (init_file_name)
7485 + strlen (load_path));
7487 sprintf (buffer,
7488 "The Emacs Windows initialization file \"%s.el\" "
7489 "could not be found in your Emacs installation. "
7490 "Emacs checked the following directories for this file:\n"
7491 "\n%s\n\n"
7492 "When Emacs cannot find this file, it usually means that it "
7493 "was not installed properly, or its distribution file was "
7494 "not unpacked properly.\nSee the README.W32 file in the "
7495 "top-level Emacs directory for more information.",
7496 init_file_name, load_path);
7497 MessageBox (NULL,
7498 buffer,
7499 "Emacs Abort Dialog",
7500 MB_OK | MB_ICONEXCLAMATION | MB_TASKMODAL);
7501 /* Use the low-level system abort. */
7502 abort ();
7504 else
7506 _close (fd);
7511 void
7512 term_ntproc (int ignored)
7514 (void)ignored;
7516 term_timers ();
7518 /* shutdown the socket interface if necessary */
7519 term_winsock ();
7521 term_w32select ();
7524 void
7525 init_ntproc (int dumping)
7527 sigset_t initial_mask = 0;
7529 /* Initialize the socket interface now if available and requested by
7530 the user by defining PRELOAD_WINSOCK; otherwise loading will be
7531 delayed until open-network-stream is called (w32-has-winsock can
7532 also be used to dynamically load or reload winsock).
7534 Conveniently, init_environment is called before us, so
7535 PRELOAD_WINSOCK can be set in the registry. */
7537 /* Always initialize this correctly. */
7538 winsock_lib = NULL;
7540 if (getenv ("PRELOAD_WINSOCK") != NULL)
7541 init_winsock (TRUE);
7543 /* Initial preparation for subprocess support: replace our standard
7544 handles with non-inheritable versions. */
7546 HANDLE parent;
7547 HANDLE stdin_save = INVALID_HANDLE_VALUE;
7548 HANDLE stdout_save = INVALID_HANDLE_VALUE;
7549 HANDLE stderr_save = INVALID_HANDLE_VALUE;
7551 parent = GetCurrentProcess ();
7553 /* ignore errors when duplicating and closing; typically the
7554 handles will be invalid when running as a gui program. */
7555 DuplicateHandle (parent,
7556 GetStdHandle (STD_INPUT_HANDLE),
7557 parent,
7558 &stdin_save,
7560 FALSE,
7561 DUPLICATE_SAME_ACCESS);
7563 DuplicateHandle (parent,
7564 GetStdHandle (STD_OUTPUT_HANDLE),
7565 parent,
7566 &stdout_save,
7568 FALSE,
7569 DUPLICATE_SAME_ACCESS);
7571 DuplicateHandle (parent,
7572 GetStdHandle (STD_ERROR_HANDLE),
7573 parent,
7574 &stderr_save,
7576 FALSE,
7577 DUPLICATE_SAME_ACCESS);
7579 fclose (stdin);
7580 fclose (stdout);
7581 fclose (stderr);
7583 if (stdin_save != INVALID_HANDLE_VALUE)
7584 _open_osfhandle ((intptr_t) stdin_save, O_TEXT);
7585 else
7586 _open ("nul", O_TEXT | O_NOINHERIT | O_RDONLY);
7587 _fdopen (0, "r");
7589 if (stdout_save != INVALID_HANDLE_VALUE)
7590 _open_osfhandle ((intptr_t) stdout_save, O_TEXT);
7591 else
7592 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
7593 _fdopen (1, "w");
7595 if (stderr_save != INVALID_HANDLE_VALUE)
7596 _open_osfhandle ((intptr_t) stderr_save, O_TEXT);
7597 else
7598 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
7599 _fdopen (2, "w");
7602 /* unfortunately, atexit depends on implementation of malloc */
7603 /* atexit (term_ntproc); */
7604 if (!dumping)
7606 /* Make sure we start with all signals unblocked. */
7607 sigprocmask (SIG_SETMASK, &initial_mask, NULL);
7608 signal (SIGABRT, term_ntproc);
7610 init_timers ();
7612 /* determine which drives are fixed, for GetCachedVolumeInformation */
7614 /* GetDriveType must have trailing backslash. */
7615 char drive[] = "A:\\";
7617 /* Loop over all possible drive letters */
7618 while (*drive <= 'Z')
7620 /* Record if this drive letter refers to a fixed drive. */
7621 fixed_drives[DRIVE_INDEX (*drive)] =
7622 (GetDriveType (drive) == DRIVE_FIXED);
7624 (*drive)++;
7627 /* Reset the volume info cache. */
7628 volume_cache = NULL;
7633 shutdown_handler ensures that buffers' autosave files are
7634 up to date when the user logs off, or the system shuts down.
7636 static BOOL WINAPI
7637 shutdown_handler (DWORD type)
7639 /* Ctrl-C and Ctrl-Break are already suppressed, so don't handle them. */
7640 if (type == CTRL_CLOSE_EVENT /* User closes console window. */
7641 || type == CTRL_LOGOFF_EVENT /* User logs off. */
7642 || type == CTRL_SHUTDOWN_EVENT) /* User shutsdown. */
7644 /* Shut down cleanly, making sure autosave files are up to date. */
7645 shut_down_emacs (0, Qnil);
7648 /* Allow other handlers to handle this signal. */
7649 return FALSE;
7653 globals_of_w32 is used to initialize those global variables that
7654 must always be initialized on startup even when the global variable
7655 initialized is non zero (see the function main in emacs.c).
7657 void
7658 globals_of_w32 (void)
7660 HMODULE kernel32 = GetModuleHandle ("kernel32.dll");
7662 get_process_times_fn = (GetProcessTimes_Proc)
7663 GetProcAddress (kernel32, "GetProcessTimes");
7665 DEFSYM (QCloaded_from, ":loaded-from");
7667 g_b_init_is_windows_9x = 0;
7668 g_b_init_open_process_token = 0;
7669 g_b_init_get_token_information = 0;
7670 g_b_init_lookup_account_sid = 0;
7671 g_b_init_get_sid_sub_authority = 0;
7672 g_b_init_get_sid_sub_authority_count = 0;
7673 g_b_init_get_security_info = 0;
7674 g_b_init_get_file_security = 0;
7675 g_b_init_get_security_descriptor_owner = 0;
7676 g_b_init_get_security_descriptor_group = 0;
7677 g_b_init_is_valid_sid = 0;
7678 g_b_init_create_toolhelp32_snapshot = 0;
7679 g_b_init_process32_first = 0;
7680 g_b_init_process32_next = 0;
7681 g_b_init_open_thread_token = 0;
7682 g_b_init_impersonate_self = 0;
7683 g_b_init_revert_to_self = 0;
7684 g_b_init_get_process_memory_info = 0;
7685 g_b_init_get_process_working_set_size = 0;
7686 g_b_init_global_memory_status = 0;
7687 g_b_init_global_memory_status_ex = 0;
7688 g_b_init_equal_sid = 0;
7689 g_b_init_copy_sid = 0;
7690 g_b_init_get_length_sid = 0;
7691 g_b_init_get_native_system_info = 0;
7692 g_b_init_get_system_times = 0;
7693 g_b_init_create_symbolic_link = 0;
7694 g_b_init_get_security_descriptor_dacl = 0;
7695 g_b_init_convert_sd_to_sddl = 0;
7696 g_b_init_convert_sddl_to_sd = 0;
7697 g_b_init_is_valid_security_descriptor = 0;
7698 g_b_init_set_file_security = 0;
7699 num_of_processors = 0;
7700 /* The following sets a handler for shutdown notifications for
7701 console apps. This actually applies to Emacs in both console and
7702 GUI modes, since we had to fool windows into thinking emacs is a
7703 console application to get console mode to work. */
7704 SetConsoleCtrlHandler (shutdown_handler, TRUE);
7706 /* "None" is the default group name on standalone workstations. */
7707 strcpy (dflt_group_name, "None");
7709 /* Reset, in case it has some value inherited from dump time. */
7710 w32_stat_get_owner_group = 0;
7713 /* For make-serial-process */
7715 serial_open (Lisp_Object port_obj)
7717 char *port = SSDATA (port_obj);
7718 HANDLE hnd;
7719 child_process *cp;
7720 int fd = -1;
7722 hnd = CreateFile (port, GENERIC_READ | GENERIC_WRITE, 0, 0,
7723 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
7724 if (hnd == INVALID_HANDLE_VALUE)
7725 error ("Could not open %s", port);
7726 fd = (int) _open_osfhandle ((intptr_t) hnd, 0);
7727 if (fd == -1)
7728 error ("Could not open %s", port);
7730 cp = new_child ();
7731 if (!cp)
7732 error ("Could not create child process");
7733 cp->fd = fd;
7734 cp->status = STATUS_READ_ACKNOWLEDGED;
7735 fd_info[ fd ].hnd = hnd;
7736 fd_info[ fd ].flags |=
7737 FILE_READ | FILE_WRITE | FILE_BINARY | FILE_SERIAL;
7738 if (fd_info[ fd ].cp != NULL)
7740 error ("fd_info[fd = %d] is already in use", fd);
7742 fd_info[ fd ].cp = cp;
7743 cp->ovl_read.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
7744 if (cp->ovl_read.hEvent == NULL)
7745 error ("Could not create read event");
7746 cp->ovl_write.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
7747 if (cp->ovl_write.hEvent == NULL)
7748 error ("Could not create write event");
7750 return fd;
7753 /* For serial-process-configure */
7754 void
7755 serial_configure (struct Lisp_Process *p, Lisp_Object contact)
7757 Lisp_Object childp2 = Qnil;
7758 Lisp_Object tem = Qnil;
7759 HANDLE hnd;
7760 DCB dcb;
7761 COMMTIMEOUTS ct;
7762 char summary[4] = "???"; /* This usually becomes "8N1". */
7764 if ((fd_info[ p->outfd ].flags & FILE_SERIAL) == 0)
7765 error ("Not a serial process");
7766 hnd = fd_info[ p->outfd ].hnd;
7768 childp2 = Fcopy_sequence (p->childp);
7770 /* Initialize timeouts for blocking read and blocking write. */
7771 if (!GetCommTimeouts (hnd, &ct))
7772 error ("GetCommTimeouts() failed");
7773 ct.ReadIntervalTimeout = 0;
7774 ct.ReadTotalTimeoutMultiplier = 0;
7775 ct.ReadTotalTimeoutConstant = 0;
7776 ct.WriteTotalTimeoutMultiplier = 0;
7777 ct.WriteTotalTimeoutConstant = 0;
7778 if (!SetCommTimeouts (hnd, &ct))
7779 error ("SetCommTimeouts() failed");
7780 /* Read port attributes and prepare default configuration. */
7781 memset (&dcb, 0, sizeof (dcb));
7782 dcb.DCBlength = sizeof (DCB);
7783 if (!GetCommState (hnd, &dcb))
7784 error ("GetCommState() failed");
7785 dcb.fBinary = TRUE;
7786 dcb.fNull = FALSE;
7787 dcb.fAbortOnError = FALSE;
7788 /* dcb.XonLim and dcb.XoffLim are set by GetCommState() */
7789 dcb.ErrorChar = 0;
7790 dcb.EofChar = 0;
7791 dcb.EvtChar = 0;
7793 /* Configure speed. */
7794 if (!NILP (Fplist_member (contact, QCspeed)))
7795 tem = Fplist_get (contact, QCspeed);
7796 else
7797 tem = Fplist_get (p->childp, QCspeed);
7798 CHECK_NUMBER (tem);
7799 dcb.BaudRate = XINT (tem);
7800 childp2 = Fplist_put (childp2, QCspeed, tem);
7802 /* Configure bytesize. */
7803 if (!NILP (Fplist_member (contact, QCbytesize)))
7804 tem = Fplist_get (contact, QCbytesize);
7805 else
7806 tem = Fplist_get (p->childp, QCbytesize);
7807 if (NILP (tem))
7808 tem = make_number (8);
7809 CHECK_NUMBER (tem);
7810 if (XINT (tem) != 7 && XINT (tem) != 8)
7811 error (":bytesize must be nil (8), 7, or 8");
7812 dcb.ByteSize = XINT (tem);
7813 summary[0] = XINT (tem) + '0';
7814 childp2 = Fplist_put (childp2, QCbytesize, tem);
7816 /* Configure parity. */
7817 if (!NILP (Fplist_member (contact, QCparity)))
7818 tem = Fplist_get (contact, QCparity);
7819 else
7820 tem = Fplist_get (p->childp, QCparity);
7821 if (!NILP (tem) && !EQ (tem, Qeven) && !EQ (tem, Qodd))
7822 error (":parity must be nil (no parity), `even', or `odd'");
7823 dcb.fParity = FALSE;
7824 dcb.Parity = NOPARITY;
7825 dcb.fErrorChar = FALSE;
7826 if (NILP (tem))
7828 summary[1] = 'N';
7830 else if (EQ (tem, Qeven))
7832 summary[1] = 'E';
7833 dcb.fParity = TRUE;
7834 dcb.Parity = EVENPARITY;
7835 dcb.fErrorChar = TRUE;
7837 else if (EQ (tem, Qodd))
7839 summary[1] = 'O';
7840 dcb.fParity = TRUE;
7841 dcb.Parity = ODDPARITY;
7842 dcb.fErrorChar = TRUE;
7844 childp2 = Fplist_put (childp2, QCparity, tem);
7846 /* Configure stopbits. */
7847 if (!NILP (Fplist_member (contact, QCstopbits)))
7848 tem = Fplist_get (contact, QCstopbits);
7849 else
7850 tem = Fplist_get (p->childp, QCstopbits);
7851 if (NILP (tem))
7852 tem = make_number (1);
7853 CHECK_NUMBER (tem);
7854 if (XINT (tem) != 1 && XINT (tem) != 2)
7855 error (":stopbits must be nil (1 stopbit), 1, or 2");
7856 summary[2] = XINT (tem) + '0';
7857 if (XINT (tem) == 1)
7858 dcb.StopBits = ONESTOPBIT;
7859 else if (XINT (tem) == 2)
7860 dcb.StopBits = TWOSTOPBITS;
7861 childp2 = Fplist_put (childp2, QCstopbits, tem);
7863 /* Configure flowcontrol. */
7864 if (!NILP (Fplist_member (contact, QCflowcontrol)))
7865 tem = Fplist_get (contact, QCflowcontrol);
7866 else
7867 tem = Fplist_get (p->childp, QCflowcontrol);
7868 if (!NILP (tem) && !EQ (tem, Qhw) && !EQ (tem, Qsw))
7869 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
7870 dcb.fOutxCtsFlow = FALSE;
7871 dcb.fOutxDsrFlow = FALSE;
7872 dcb.fDtrControl = DTR_CONTROL_DISABLE;
7873 dcb.fDsrSensitivity = FALSE;
7874 dcb.fTXContinueOnXoff = FALSE;
7875 dcb.fOutX = FALSE;
7876 dcb.fInX = FALSE;
7877 dcb.fRtsControl = RTS_CONTROL_DISABLE;
7878 dcb.XonChar = 17; /* Control-Q */
7879 dcb.XoffChar = 19; /* Control-S */
7880 if (NILP (tem))
7882 /* Already configured. */
7884 else if (EQ (tem, Qhw))
7886 dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
7887 dcb.fOutxCtsFlow = TRUE;
7889 else if (EQ (tem, Qsw))
7891 dcb.fOutX = TRUE;
7892 dcb.fInX = TRUE;
7894 childp2 = Fplist_put (childp2, QCflowcontrol, tem);
7896 /* Activate configuration. */
7897 if (!SetCommState (hnd, &dcb))
7898 error ("SetCommState() failed");
7900 childp2 = Fplist_put (childp2, QCsummary, build_string (summary));
7901 pset_childp (p, childp2);
7904 #ifdef HAVE_GNUTLS
7906 ssize_t
7907 emacs_gnutls_pull (gnutls_transport_ptr_t p, void* buf, size_t sz)
7909 int n, err;
7910 SELECT_TYPE fdset;
7911 EMACS_TIME timeout;
7912 struct Lisp_Process *process = (struct Lisp_Process *)p;
7913 int fd = process->infd;
7915 n = sys_read (fd, (char*)buf, sz);
7917 if (n >= 0)
7918 return n;
7920 err = errno;
7922 /* Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
7923 if (err == EWOULDBLOCK)
7924 err = EAGAIN;
7926 emacs_gnutls_transport_set_errno (process->gnutls_state, err);
7928 return -1;
7931 ssize_t
7932 emacs_gnutls_push (gnutls_transport_ptr_t p, const void* buf, size_t sz)
7934 struct Lisp_Process *process = (struct Lisp_Process *)p;
7935 int fd = process->outfd;
7936 ssize_t n = sys_write (fd, buf, sz);
7938 /* 0 or more bytes written means everything went fine. */
7939 if (n >= 0)
7940 return n;
7942 /* Negative bytes written means we got an error in errno.
7943 Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
7944 emacs_gnutls_transport_set_errno (process->gnutls_state,
7945 errno == EWOULDBLOCK ? EAGAIN : errno);
7947 return -1;
7949 #endif /* HAVE_GNUTLS */
7951 /* end of w32.c */