Fix MS-Windows build.
[emacs.git] / src / w32.c
blob631405fabb8b9248f966ba8a2d10736c1e1503c9
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 #include <sys/socket.h>
44 #undef access
45 #undef chdir
46 #undef chmod
47 #undef creat
48 #undef ctime
49 #undef fopen
50 #undef link
51 #undef mkdir
52 #undef open
53 #undef rename
54 #undef rmdir
55 #undef unlink
57 #undef close
58 #undef dup
59 #undef dup2
60 #undef pipe
61 #undef read
62 #undef write
64 #undef strerror
66 #undef localtime
68 #include "lisp.h"
69 #include "epaths.h" /* for SHELL */
71 #include <pwd.h>
72 #include <grp.h>
74 /* MinGW64 (_W64) defines these in its _mingw.h. */
75 #if !defined(_ANONYMOUS_UNION) && !defined(_ANONYMOUS_STRUCT)
76 #define _ANONYMOUS_UNION
77 #define _ANONYMOUS_STRUCT
78 #endif
79 #include <windows.h>
80 /* Some versions of compiler define MEMORYSTATUSEX, some don't, so we
81 use a different name to avoid compilation problems. */
82 typedef struct _MEMORY_STATUS_EX {
83 DWORD dwLength;
84 DWORD dwMemoryLoad;
85 DWORDLONG ullTotalPhys;
86 DWORDLONG ullAvailPhys;
87 DWORDLONG ullTotalPageFile;
88 DWORDLONG ullAvailPageFile;
89 DWORDLONG ullTotalVirtual;
90 DWORDLONG ullAvailVirtual;
91 DWORDLONG ullAvailExtendedVirtual;
92 } MEMORY_STATUS_EX,*LPMEMORY_STATUS_EX;
94 /* These are here so that GDB would know about these data types. This
95 allows to attach GDB to Emacs when a fatal exception is triggered
96 and Windows pops up the "application needs to be closed" dialog.
97 At that point, _gnu_exception_handler, the top-level exception
98 handler installed by the MinGW startup code, is somewhere on the
99 call-stack of the main thread, so going to that call frame and
100 looking at the argument to _gnu_exception_handler, which is a
101 PEXCEPTION_POINTERS pointer, can reveal the exception code
102 (excptr->ExceptionRecord->ExceptionCode) and the address where the
103 exception happened (excptr->ExceptionRecord->ExceptionAddress), as
104 well as some additional information specific to the exception. */
105 PEXCEPTION_POINTERS excptr;
106 PEXCEPTION_RECORD excprec;
107 PCONTEXT ctxrec;
109 #include <lmcons.h>
110 #include <shlobj.h>
112 #include <tlhelp32.h>
113 #include <psapi.h>
114 #ifndef _MSC_VER
115 #include <w32api.h>
116 #endif
117 #if _WIN32_WINNT < 0x0500
118 #if !defined (__MINGW32__) || __W32API_MAJOR_VERSION < 3 || (__W32API_MAJOR_VERSION == 3 && __W32API_MINOR_VERSION < 15)
119 /* This either is not in psapi.h or guarded by higher value of
120 _WIN32_WINNT than what we use. w32api supplied with MinGW 3.15
121 defines it in psapi.h */
122 typedef struct _PROCESS_MEMORY_COUNTERS_EX {
123 DWORD cb;
124 DWORD PageFaultCount;
125 SIZE_T PeakWorkingSetSize;
126 SIZE_T WorkingSetSize;
127 SIZE_T QuotaPeakPagedPoolUsage;
128 SIZE_T QuotaPagedPoolUsage;
129 SIZE_T QuotaPeakNonPagedPoolUsage;
130 SIZE_T QuotaNonPagedPoolUsage;
131 SIZE_T PagefileUsage;
132 SIZE_T PeakPagefileUsage;
133 SIZE_T PrivateUsage;
134 } PROCESS_MEMORY_COUNTERS_EX,*PPROCESS_MEMORY_COUNTERS_EX;
135 #endif
136 #endif
138 #include <winioctl.h>
139 #include <aclapi.h>
140 #include <sddl.h>
142 #include <sys/acl.h>
144 /* This is not in MinGW's sddl.h (but they are in MSVC headers), so we
145 define them by hand if not already defined. */
146 #ifndef SDDL_REVISION_1
147 #define SDDL_REVISION_1 1
148 #endif /* SDDL_REVISION_1 */
150 #if defined(_MSC_VER) || defined(_W64)
151 /* MSVC and MinGW64 don't provide the definition of
152 REPARSE_DATA_BUFFER and the associated macros, except on ntifs.h,
153 which cannot be included because it triggers conflicts with other
154 Windows API headers. So we define it here by hand. */
156 typedef struct _REPARSE_DATA_BUFFER {
157 ULONG ReparseTag;
158 USHORT ReparseDataLength;
159 USHORT Reserved;
160 union {
161 struct {
162 USHORT SubstituteNameOffset;
163 USHORT SubstituteNameLength;
164 USHORT PrintNameOffset;
165 USHORT PrintNameLength;
166 ULONG Flags;
167 WCHAR PathBuffer[1];
168 } SymbolicLinkReparseBuffer;
169 struct {
170 USHORT SubstituteNameOffset;
171 USHORT SubstituteNameLength;
172 USHORT PrintNameOffset;
173 USHORT PrintNameLength;
174 WCHAR PathBuffer[1];
175 } MountPointReparseBuffer;
176 struct {
177 UCHAR DataBuffer[1];
178 } GenericReparseBuffer;
179 } DUMMYUNIONNAME;
180 } REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;
182 #ifndef FILE_DEVICE_FILE_SYSTEM
183 #define FILE_DEVICE_FILE_SYSTEM 9
184 #endif
185 #ifndef METHOD_BUFFERED
186 #define METHOD_BUFFERED 0
187 #endif
188 #ifndef FILE_ANY_ACCESS
189 #define FILE_ANY_ACCESS 0x00000000
190 #endif
191 #ifndef CTL_CODE
192 #define CTL_CODE(t,f,m,a) (((t)<<16)|((a)<<14)|((f)<<2)|(m))
193 #endif
194 /* MinGW64 defines FSCTL_GET_REPARSE_POINT on winioctl.h. */
195 #ifndef FSCTL_GET_REPARSE_POINT
196 #define FSCTL_GET_REPARSE_POINT \
197 CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 42, METHOD_BUFFERED, FILE_ANY_ACCESS)
198 #endif
199 #endif
201 /* TCP connection support. */
202 #undef socket
203 #undef bind
204 #undef connect
205 #undef htons
206 #undef ntohs
207 #undef inet_addr
208 #undef gethostname
209 #undef gethostbyname
210 #undef getservbyname
211 #undef getpeername
212 #undef shutdown
213 #undef setsockopt
214 #undef listen
215 #undef getsockname
216 #undef accept
217 #undef recvfrom
218 #undef sendto
220 #include "w32.h"
221 #include <dirent.h>
222 #include "w32common.h"
223 #include "w32heap.h"
224 #include "w32select.h"
225 #include "systime.h"
226 #include "dispextern.h" /* for xstrcasecmp */
227 #include "coding.h" /* for Vlocale_coding_system */
229 #include "careadlinkat.h"
230 #include "allocator.h"
232 /* For serial_configure and serial_open. */
233 #include "process.h"
235 typedef HRESULT (WINAPI * ShGetFolderPath_fn)
236 (IN HWND, IN int, IN HANDLE, IN DWORD, OUT char *);
238 Lisp_Object QCloaded_from;
240 void globals_of_w32 (void);
241 static DWORD get_rid (PSID);
242 static int is_symlink (const char *);
243 static char * chase_symlinks (const char *);
244 static int enable_privilege (LPCTSTR, BOOL, TOKEN_PRIVILEGES *);
245 static int restore_privilege (TOKEN_PRIVILEGES *);
246 static BOOL WINAPI revert_to_self (void);
248 extern int sys_access (const char *, int);
249 extern void *e_malloc (size_t);
250 extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
251 EMACS_TIME *, sigset_t *);
252 extern int sys_dup (int);
257 /* Initialization states.
259 WARNING: If you add any more such variables for additional APIs,
260 you MUST add initialization for them to globals_of_w32
261 below. This is because these variables might get set
262 to non-NULL values during dumping, but the dumped Emacs
263 cannot reuse those values, because it could be run on a
264 different version of the OS, where API addresses are
265 different. */
266 static BOOL g_b_init_is_windows_9x;
267 static BOOL g_b_init_open_process_token;
268 static BOOL g_b_init_get_token_information;
269 static BOOL g_b_init_lookup_account_sid;
270 static BOOL g_b_init_get_sid_sub_authority;
271 static BOOL g_b_init_get_sid_sub_authority_count;
272 static BOOL g_b_init_get_security_info;
273 static BOOL g_b_init_get_file_security;
274 static BOOL g_b_init_get_security_descriptor_owner;
275 static BOOL g_b_init_get_security_descriptor_group;
276 static BOOL g_b_init_is_valid_sid;
277 static BOOL g_b_init_create_toolhelp32_snapshot;
278 static BOOL g_b_init_process32_first;
279 static BOOL g_b_init_process32_next;
280 static BOOL g_b_init_open_thread_token;
281 static BOOL g_b_init_impersonate_self;
282 static BOOL g_b_init_revert_to_self;
283 static BOOL g_b_init_get_process_memory_info;
284 static BOOL g_b_init_get_process_working_set_size;
285 static BOOL g_b_init_global_memory_status;
286 static BOOL g_b_init_global_memory_status_ex;
287 static BOOL g_b_init_get_length_sid;
288 static BOOL g_b_init_equal_sid;
289 static BOOL g_b_init_copy_sid;
290 static BOOL g_b_init_get_native_system_info;
291 static BOOL g_b_init_get_system_times;
292 static BOOL g_b_init_create_symbolic_link;
293 static BOOL g_b_init_get_security_descriptor_dacl;
294 static BOOL g_b_init_convert_sd_to_sddl;
295 static BOOL g_b_init_convert_sddl_to_sd;
296 static BOOL g_b_init_is_valid_security_descriptor;
297 static BOOL g_b_init_set_file_security;
300 BEGIN: Wrapper functions around OpenProcessToken
301 and other functions in advapi32.dll that are only
302 supported in Windows NT / 2k / XP
304 /* ** Function pointer typedefs ** */
305 typedef BOOL (WINAPI * OpenProcessToken_Proc) (
306 HANDLE ProcessHandle,
307 DWORD DesiredAccess,
308 PHANDLE TokenHandle);
309 typedef BOOL (WINAPI * GetTokenInformation_Proc) (
310 HANDLE TokenHandle,
311 TOKEN_INFORMATION_CLASS TokenInformationClass,
312 LPVOID TokenInformation,
313 DWORD TokenInformationLength,
314 PDWORD ReturnLength);
315 typedef BOOL (WINAPI * GetProcessTimes_Proc) (
316 HANDLE process_handle,
317 LPFILETIME creation_time,
318 LPFILETIME exit_time,
319 LPFILETIME kernel_time,
320 LPFILETIME user_time);
322 GetProcessTimes_Proc get_process_times_fn = NULL;
324 #ifdef _UNICODE
325 const char * const LookupAccountSid_Name = "LookupAccountSidW";
326 const char * const GetFileSecurity_Name = "GetFileSecurityW";
327 const char * const SetFileSecurity_Name = "SetFileSecurityW";
328 #else
329 const char * const LookupAccountSid_Name = "LookupAccountSidA";
330 const char * const GetFileSecurity_Name = "GetFileSecurityA";
331 const char * const SetFileSecurity_Name = "SetFileSecurityA";
332 #endif
333 typedef BOOL (WINAPI * LookupAccountSid_Proc) (
334 LPCTSTR lpSystemName,
335 PSID Sid,
336 LPTSTR Name,
337 LPDWORD cbName,
338 LPTSTR DomainName,
339 LPDWORD cbDomainName,
340 PSID_NAME_USE peUse);
341 typedef PDWORD (WINAPI * GetSidSubAuthority_Proc) (
342 PSID pSid,
343 DWORD n);
344 typedef PUCHAR (WINAPI * GetSidSubAuthorityCount_Proc) (
345 PSID pSid);
346 typedef DWORD (WINAPI * GetSecurityInfo_Proc) (
347 HANDLE handle,
348 SE_OBJECT_TYPE ObjectType,
349 SECURITY_INFORMATION SecurityInfo,
350 PSID *ppsidOwner,
351 PSID *ppsidGroup,
352 PACL *ppDacl,
353 PACL *ppSacl,
354 PSECURITY_DESCRIPTOR *ppSecurityDescriptor);
355 typedef BOOL (WINAPI * GetFileSecurity_Proc) (
356 LPCTSTR lpFileName,
357 SECURITY_INFORMATION RequestedInformation,
358 PSECURITY_DESCRIPTOR pSecurityDescriptor,
359 DWORD nLength,
360 LPDWORD lpnLengthNeeded);
361 typedef BOOL (WINAPI *SetFileSecurity_Proc) (
362 LPCTSTR lpFileName,
363 SECURITY_INFORMATION SecurityInformation,
364 PSECURITY_DESCRIPTOR pSecurityDescriptor);
365 typedef BOOL (WINAPI * GetSecurityDescriptorOwner_Proc) (
366 PSECURITY_DESCRIPTOR pSecurityDescriptor,
367 PSID *pOwner,
368 LPBOOL lpbOwnerDefaulted);
369 typedef BOOL (WINAPI * GetSecurityDescriptorGroup_Proc) (
370 PSECURITY_DESCRIPTOR pSecurityDescriptor,
371 PSID *pGroup,
372 LPBOOL lpbGroupDefaulted);
373 typedef BOOL (WINAPI *GetSecurityDescriptorDacl_Proc) (
374 PSECURITY_DESCRIPTOR pSecurityDescriptor,
375 LPBOOL lpbDaclPresent,
376 PACL *pDacl,
377 LPBOOL lpbDaclDefaulted);
378 typedef BOOL (WINAPI * IsValidSid_Proc) (
379 PSID sid);
380 typedef HANDLE (WINAPI * CreateToolhelp32Snapshot_Proc) (
381 DWORD dwFlags,
382 DWORD th32ProcessID);
383 typedef BOOL (WINAPI * Process32First_Proc) (
384 HANDLE hSnapshot,
385 LPPROCESSENTRY32 lppe);
386 typedef BOOL (WINAPI * Process32Next_Proc) (
387 HANDLE hSnapshot,
388 LPPROCESSENTRY32 lppe);
389 typedef BOOL (WINAPI * OpenThreadToken_Proc) (
390 HANDLE ThreadHandle,
391 DWORD DesiredAccess,
392 BOOL OpenAsSelf,
393 PHANDLE TokenHandle);
394 typedef BOOL (WINAPI * ImpersonateSelf_Proc) (
395 SECURITY_IMPERSONATION_LEVEL ImpersonationLevel);
396 typedef BOOL (WINAPI * RevertToSelf_Proc) (void);
397 typedef BOOL (WINAPI * GetProcessMemoryInfo_Proc) (
398 HANDLE Process,
399 PPROCESS_MEMORY_COUNTERS ppsmemCounters,
400 DWORD cb);
401 typedef BOOL (WINAPI * GetProcessWorkingSetSize_Proc) (
402 HANDLE hProcess,
403 PSIZE_T lpMinimumWorkingSetSize,
404 PSIZE_T lpMaximumWorkingSetSize);
405 typedef BOOL (WINAPI * GlobalMemoryStatus_Proc) (
406 LPMEMORYSTATUS lpBuffer);
407 typedef BOOL (WINAPI * GlobalMemoryStatusEx_Proc) (
408 LPMEMORY_STATUS_EX lpBuffer);
409 typedef BOOL (WINAPI * CopySid_Proc) (
410 DWORD nDestinationSidLength,
411 PSID pDestinationSid,
412 PSID pSourceSid);
413 typedef BOOL (WINAPI * EqualSid_Proc) (
414 PSID pSid1,
415 PSID pSid2);
416 typedef DWORD (WINAPI * GetLengthSid_Proc) (
417 PSID pSid);
418 typedef void (WINAPI * GetNativeSystemInfo_Proc) (
419 LPSYSTEM_INFO lpSystemInfo);
420 typedef BOOL (WINAPI * GetSystemTimes_Proc) (
421 LPFILETIME lpIdleTime,
422 LPFILETIME lpKernelTime,
423 LPFILETIME lpUserTime);
424 typedef BOOLEAN (WINAPI *CreateSymbolicLink_Proc) (
425 LPTSTR lpSymlinkFileName,
426 LPTSTR lpTargetFileName,
427 DWORD dwFlags);
428 typedef BOOL (WINAPI *ConvertStringSecurityDescriptorToSecurityDescriptor_Proc) (
429 LPCTSTR StringSecurityDescriptor,
430 DWORD StringSDRevision,
431 PSECURITY_DESCRIPTOR *SecurityDescriptor,
432 PULONG SecurityDescriptorSize);
433 typedef BOOL (WINAPI *ConvertSecurityDescriptorToStringSecurityDescriptor_Proc) (
434 PSECURITY_DESCRIPTOR SecurityDescriptor,
435 DWORD RequestedStringSDRevision,
436 SECURITY_INFORMATION SecurityInformation,
437 LPTSTR *StringSecurityDescriptor,
438 PULONG StringSecurityDescriptorLen);
439 typedef BOOL (WINAPI *IsValidSecurityDescriptor_Proc) (PSECURITY_DESCRIPTOR);
441 /* ** A utility function ** */
442 static BOOL
443 is_windows_9x (void)
445 static BOOL s_b_ret = 0;
446 OSVERSIONINFO os_ver;
447 if (g_b_init_is_windows_9x == 0)
449 g_b_init_is_windows_9x = 1;
450 ZeroMemory (&os_ver, sizeof (OSVERSIONINFO));
451 os_ver.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
452 if (GetVersionEx (&os_ver))
454 s_b_ret = (os_ver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS);
457 return s_b_ret;
460 static Lisp_Object ltime (ULONGLONG);
462 /* Get total user and system times for get-internal-run-time.
463 Returns a list of integers if the times are provided by the OS
464 (NT derivatives), otherwise it returns the result of current-time. */
465 Lisp_Object
466 w32_get_internal_run_time (void)
468 if (get_process_times_fn)
470 FILETIME create, exit, kernel, user;
471 HANDLE proc = GetCurrentProcess ();
472 if ((*get_process_times_fn) (proc, &create, &exit, &kernel, &user))
474 LARGE_INTEGER user_int, kernel_int, total;
475 user_int.LowPart = user.dwLowDateTime;
476 user_int.HighPart = user.dwHighDateTime;
477 kernel_int.LowPart = kernel.dwLowDateTime;
478 kernel_int.HighPart = kernel.dwHighDateTime;
479 total.QuadPart = user_int.QuadPart + kernel_int.QuadPart;
480 return ltime (total.QuadPart);
484 return Fcurrent_time ();
487 /* ** The wrapper functions ** */
489 static BOOL WINAPI
490 open_process_token (HANDLE ProcessHandle,
491 DWORD DesiredAccess,
492 PHANDLE TokenHandle)
494 static OpenProcessToken_Proc s_pfn_Open_Process_Token = NULL;
495 HMODULE hm_advapi32 = NULL;
496 if (is_windows_9x () == TRUE)
498 return FALSE;
500 if (g_b_init_open_process_token == 0)
502 g_b_init_open_process_token = 1;
503 hm_advapi32 = LoadLibrary ("Advapi32.dll");
504 s_pfn_Open_Process_Token =
505 (OpenProcessToken_Proc) GetProcAddress (hm_advapi32, "OpenProcessToken");
507 if (s_pfn_Open_Process_Token == NULL)
509 return FALSE;
511 return (
512 s_pfn_Open_Process_Token (
513 ProcessHandle,
514 DesiredAccess,
515 TokenHandle)
519 static BOOL WINAPI
520 get_token_information (HANDLE TokenHandle,
521 TOKEN_INFORMATION_CLASS TokenInformationClass,
522 LPVOID TokenInformation,
523 DWORD TokenInformationLength,
524 PDWORD ReturnLength)
526 static GetTokenInformation_Proc s_pfn_Get_Token_Information = NULL;
527 HMODULE hm_advapi32 = NULL;
528 if (is_windows_9x () == TRUE)
530 return FALSE;
532 if (g_b_init_get_token_information == 0)
534 g_b_init_get_token_information = 1;
535 hm_advapi32 = LoadLibrary ("Advapi32.dll");
536 s_pfn_Get_Token_Information =
537 (GetTokenInformation_Proc) GetProcAddress (hm_advapi32, "GetTokenInformation");
539 if (s_pfn_Get_Token_Information == NULL)
541 return FALSE;
543 return (
544 s_pfn_Get_Token_Information (
545 TokenHandle,
546 TokenInformationClass,
547 TokenInformation,
548 TokenInformationLength,
549 ReturnLength)
553 static BOOL WINAPI
554 lookup_account_sid (LPCTSTR lpSystemName,
555 PSID Sid,
556 LPTSTR Name,
557 LPDWORD cbName,
558 LPTSTR DomainName,
559 LPDWORD cbDomainName,
560 PSID_NAME_USE peUse)
562 static LookupAccountSid_Proc s_pfn_Lookup_Account_Sid = NULL;
563 HMODULE hm_advapi32 = NULL;
564 if (is_windows_9x () == TRUE)
566 return FALSE;
568 if (g_b_init_lookup_account_sid == 0)
570 g_b_init_lookup_account_sid = 1;
571 hm_advapi32 = LoadLibrary ("Advapi32.dll");
572 s_pfn_Lookup_Account_Sid =
573 (LookupAccountSid_Proc) GetProcAddress (hm_advapi32, LookupAccountSid_Name);
575 if (s_pfn_Lookup_Account_Sid == NULL)
577 return FALSE;
579 return (
580 s_pfn_Lookup_Account_Sid (
581 lpSystemName,
582 Sid,
583 Name,
584 cbName,
585 DomainName,
586 cbDomainName,
587 peUse)
591 static PDWORD WINAPI
592 get_sid_sub_authority (PSID pSid, DWORD n)
594 static GetSidSubAuthority_Proc s_pfn_Get_Sid_Sub_Authority = NULL;
595 static DWORD zero = 0U;
596 HMODULE hm_advapi32 = NULL;
597 if (is_windows_9x () == TRUE)
599 return &zero;
601 if (g_b_init_get_sid_sub_authority == 0)
603 g_b_init_get_sid_sub_authority = 1;
604 hm_advapi32 = LoadLibrary ("Advapi32.dll");
605 s_pfn_Get_Sid_Sub_Authority =
606 (GetSidSubAuthority_Proc) GetProcAddress (
607 hm_advapi32, "GetSidSubAuthority");
609 if (s_pfn_Get_Sid_Sub_Authority == NULL)
611 return &zero;
613 return (s_pfn_Get_Sid_Sub_Authority (pSid, n));
616 static PUCHAR WINAPI
617 get_sid_sub_authority_count (PSID pSid)
619 static GetSidSubAuthorityCount_Proc s_pfn_Get_Sid_Sub_Authority_Count = NULL;
620 static UCHAR zero = 0U;
621 HMODULE hm_advapi32 = NULL;
622 if (is_windows_9x () == TRUE)
624 return &zero;
626 if (g_b_init_get_sid_sub_authority_count == 0)
628 g_b_init_get_sid_sub_authority_count = 1;
629 hm_advapi32 = LoadLibrary ("Advapi32.dll");
630 s_pfn_Get_Sid_Sub_Authority_Count =
631 (GetSidSubAuthorityCount_Proc) GetProcAddress (
632 hm_advapi32, "GetSidSubAuthorityCount");
634 if (s_pfn_Get_Sid_Sub_Authority_Count == NULL)
636 return &zero;
638 return (s_pfn_Get_Sid_Sub_Authority_Count (pSid));
641 static DWORD WINAPI
642 get_security_info (HANDLE handle,
643 SE_OBJECT_TYPE ObjectType,
644 SECURITY_INFORMATION SecurityInfo,
645 PSID *ppsidOwner,
646 PSID *ppsidGroup,
647 PACL *ppDacl,
648 PACL *ppSacl,
649 PSECURITY_DESCRIPTOR *ppSecurityDescriptor)
651 static GetSecurityInfo_Proc s_pfn_Get_Security_Info = NULL;
652 HMODULE hm_advapi32 = NULL;
653 if (is_windows_9x () == TRUE)
655 return FALSE;
657 if (g_b_init_get_security_info == 0)
659 g_b_init_get_security_info = 1;
660 hm_advapi32 = LoadLibrary ("Advapi32.dll");
661 s_pfn_Get_Security_Info =
662 (GetSecurityInfo_Proc) GetProcAddress (
663 hm_advapi32, "GetSecurityInfo");
665 if (s_pfn_Get_Security_Info == NULL)
667 return FALSE;
669 return (s_pfn_Get_Security_Info (handle, ObjectType, SecurityInfo,
670 ppsidOwner, ppsidGroup, ppDacl, ppSacl,
671 ppSecurityDescriptor));
674 static BOOL WINAPI
675 get_file_security (LPCTSTR lpFileName,
676 SECURITY_INFORMATION RequestedInformation,
677 PSECURITY_DESCRIPTOR pSecurityDescriptor,
678 DWORD nLength,
679 LPDWORD lpnLengthNeeded)
681 static GetFileSecurity_Proc s_pfn_Get_File_Security = NULL;
682 HMODULE hm_advapi32 = NULL;
683 if (is_windows_9x () == TRUE)
685 errno = ENOTSUP;
686 return FALSE;
688 if (g_b_init_get_file_security == 0)
690 g_b_init_get_file_security = 1;
691 hm_advapi32 = LoadLibrary ("Advapi32.dll");
692 s_pfn_Get_File_Security =
693 (GetFileSecurity_Proc) GetProcAddress (
694 hm_advapi32, GetFileSecurity_Name);
696 if (s_pfn_Get_File_Security == NULL)
698 errno = ENOTSUP;
699 return FALSE;
701 return (s_pfn_Get_File_Security (lpFileName, RequestedInformation,
702 pSecurityDescriptor, nLength,
703 lpnLengthNeeded));
706 static BOOL WINAPI
707 set_file_security (LPCTSTR lpFileName,
708 SECURITY_INFORMATION SecurityInformation,
709 PSECURITY_DESCRIPTOR pSecurityDescriptor)
711 static SetFileSecurity_Proc s_pfn_Set_File_Security = NULL;
712 HMODULE hm_advapi32 = NULL;
713 if (is_windows_9x () == TRUE)
715 errno = ENOTSUP;
716 return FALSE;
718 if (g_b_init_set_file_security == 0)
720 g_b_init_set_file_security = 1;
721 hm_advapi32 = LoadLibrary ("Advapi32.dll");
722 s_pfn_Set_File_Security =
723 (SetFileSecurity_Proc) GetProcAddress (
724 hm_advapi32, SetFileSecurity_Name);
726 if (s_pfn_Set_File_Security == NULL)
728 errno = ENOTSUP;
729 return FALSE;
731 return (s_pfn_Set_File_Security (lpFileName, SecurityInformation,
732 pSecurityDescriptor));
735 static BOOL WINAPI
736 get_security_descriptor_owner (PSECURITY_DESCRIPTOR pSecurityDescriptor,
737 PSID *pOwner,
738 LPBOOL lpbOwnerDefaulted)
740 static GetSecurityDescriptorOwner_Proc s_pfn_Get_Security_Descriptor_Owner = NULL;
741 HMODULE hm_advapi32 = NULL;
742 if (is_windows_9x () == TRUE)
744 errno = ENOTSUP;
745 return FALSE;
747 if (g_b_init_get_security_descriptor_owner == 0)
749 g_b_init_get_security_descriptor_owner = 1;
750 hm_advapi32 = LoadLibrary ("Advapi32.dll");
751 s_pfn_Get_Security_Descriptor_Owner =
752 (GetSecurityDescriptorOwner_Proc) GetProcAddress (
753 hm_advapi32, "GetSecurityDescriptorOwner");
755 if (s_pfn_Get_Security_Descriptor_Owner == NULL)
757 errno = ENOTSUP;
758 return FALSE;
760 return (s_pfn_Get_Security_Descriptor_Owner (pSecurityDescriptor, pOwner,
761 lpbOwnerDefaulted));
764 static BOOL WINAPI
765 get_security_descriptor_group (PSECURITY_DESCRIPTOR pSecurityDescriptor,
766 PSID *pGroup,
767 LPBOOL lpbGroupDefaulted)
769 static GetSecurityDescriptorGroup_Proc s_pfn_Get_Security_Descriptor_Group = NULL;
770 HMODULE hm_advapi32 = NULL;
771 if (is_windows_9x () == TRUE)
773 errno = ENOTSUP;
774 return FALSE;
776 if (g_b_init_get_security_descriptor_group == 0)
778 g_b_init_get_security_descriptor_group = 1;
779 hm_advapi32 = LoadLibrary ("Advapi32.dll");
780 s_pfn_Get_Security_Descriptor_Group =
781 (GetSecurityDescriptorGroup_Proc) GetProcAddress (
782 hm_advapi32, "GetSecurityDescriptorGroup");
784 if (s_pfn_Get_Security_Descriptor_Group == NULL)
786 errno = ENOTSUP;
787 return FALSE;
789 return (s_pfn_Get_Security_Descriptor_Group (pSecurityDescriptor, pGroup,
790 lpbGroupDefaulted));
793 static BOOL WINAPI
794 get_security_descriptor_dacl (PSECURITY_DESCRIPTOR pSecurityDescriptor,
795 LPBOOL lpbDaclPresent,
796 PACL *pDacl,
797 LPBOOL lpbDaclDefaulted)
799 static GetSecurityDescriptorDacl_Proc s_pfn_Get_Security_Descriptor_Dacl = NULL;
800 HMODULE hm_advapi32 = NULL;
801 if (is_windows_9x () == TRUE)
803 errno = ENOTSUP;
804 return FALSE;
806 if (g_b_init_get_security_descriptor_dacl == 0)
808 g_b_init_get_security_descriptor_dacl = 1;
809 hm_advapi32 = LoadLibrary ("Advapi32.dll");
810 s_pfn_Get_Security_Descriptor_Dacl =
811 (GetSecurityDescriptorDacl_Proc) GetProcAddress (
812 hm_advapi32, "GetSecurityDescriptorDacl");
814 if (s_pfn_Get_Security_Descriptor_Dacl == NULL)
816 errno = ENOTSUP;
817 return FALSE;
819 return (s_pfn_Get_Security_Descriptor_Dacl (pSecurityDescriptor,
820 lpbDaclPresent, pDacl,
821 lpbDaclDefaulted));
824 static BOOL WINAPI
825 is_valid_sid (PSID sid)
827 static IsValidSid_Proc s_pfn_Is_Valid_Sid = NULL;
828 HMODULE hm_advapi32 = NULL;
829 if (is_windows_9x () == TRUE)
831 return FALSE;
833 if (g_b_init_is_valid_sid == 0)
835 g_b_init_is_valid_sid = 1;
836 hm_advapi32 = LoadLibrary ("Advapi32.dll");
837 s_pfn_Is_Valid_Sid =
838 (IsValidSid_Proc) GetProcAddress (
839 hm_advapi32, "IsValidSid");
841 if (s_pfn_Is_Valid_Sid == NULL)
843 return FALSE;
845 return (s_pfn_Is_Valid_Sid (sid));
848 static BOOL WINAPI
849 equal_sid (PSID sid1, PSID sid2)
851 static EqualSid_Proc s_pfn_Equal_Sid = NULL;
852 HMODULE hm_advapi32 = NULL;
853 if (is_windows_9x () == TRUE)
855 return FALSE;
857 if (g_b_init_equal_sid == 0)
859 g_b_init_equal_sid = 1;
860 hm_advapi32 = LoadLibrary ("Advapi32.dll");
861 s_pfn_Equal_Sid =
862 (EqualSid_Proc) GetProcAddress (
863 hm_advapi32, "EqualSid");
865 if (s_pfn_Equal_Sid == NULL)
867 return FALSE;
869 return (s_pfn_Equal_Sid (sid1, sid2));
872 static DWORD WINAPI
873 get_length_sid (PSID sid)
875 static GetLengthSid_Proc s_pfn_Get_Length_Sid = NULL;
876 HMODULE hm_advapi32 = NULL;
877 if (is_windows_9x () == TRUE)
879 return 0;
881 if (g_b_init_get_length_sid == 0)
883 g_b_init_get_length_sid = 1;
884 hm_advapi32 = LoadLibrary ("Advapi32.dll");
885 s_pfn_Get_Length_Sid =
886 (GetLengthSid_Proc) GetProcAddress (
887 hm_advapi32, "GetLengthSid");
889 if (s_pfn_Get_Length_Sid == NULL)
891 return 0;
893 return (s_pfn_Get_Length_Sid (sid));
896 static BOOL WINAPI
897 copy_sid (DWORD destlen, PSID dest, PSID src)
899 static CopySid_Proc s_pfn_Copy_Sid = NULL;
900 HMODULE hm_advapi32 = NULL;
901 if (is_windows_9x () == TRUE)
903 return FALSE;
905 if (g_b_init_copy_sid == 0)
907 g_b_init_copy_sid = 1;
908 hm_advapi32 = LoadLibrary ("Advapi32.dll");
909 s_pfn_Copy_Sid =
910 (CopySid_Proc) GetProcAddress (
911 hm_advapi32, "CopySid");
913 if (s_pfn_Copy_Sid == NULL)
915 return FALSE;
917 return (s_pfn_Copy_Sid (destlen, dest, src));
921 END: Wrapper functions around OpenProcessToken
922 and other functions in advapi32.dll that are only
923 supported in Windows NT / 2k / XP
926 static void WINAPI
927 get_native_system_info (LPSYSTEM_INFO lpSystemInfo)
929 static GetNativeSystemInfo_Proc s_pfn_Get_Native_System_Info = NULL;
930 if (is_windows_9x () != TRUE)
932 if (g_b_init_get_native_system_info == 0)
934 g_b_init_get_native_system_info = 1;
935 s_pfn_Get_Native_System_Info =
936 (GetNativeSystemInfo_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
937 "GetNativeSystemInfo");
939 if (s_pfn_Get_Native_System_Info != NULL)
940 s_pfn_Get_Native_System_Info (lpSystemInfo);
942 else
943 lpSystemInfo->dwNumberOfProcessors = -1;
946 static BOOL WINAPI
947 get_system_times (LPFILETIME lpIdleTime,
948 LPFILETIME lpKernelTime,
949 LPFILETIME lpUserTime)
951 static GetSystemTimes_Proc s_pfn_Get_System_times = NULL;
952 if (is_windows_9x () == TRUE)
954 return FALSE;
956 if (g_b_init_get_system_times == 0)
958 g_b_init_get_system_times = 1;
959 s_pfn_Get_System_times =
960 (GetSystemTimes_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
961 "GetSystemTimes");
963 if (s_pfn_Get_System_times == NULL)
964 return FALSE;
965 return (s_pfn_Get_System_times (lpIdleTime, lpKernelTime, lpUserTime));
968 static BOOLEAN WINAPI
969 create_symbolic_link (LPTSTR lpSymlinkFilename,
970 LPTSTR lpTargetFileName,
971 DWORD dwFlags)
973 static CreateSymbolicLink_Proc s_pfn_Create_Symbolic_Link = NULL;
974 BOOLEAN retval;
976 if (is_windows_9x () == TRUE)
978 errno = ENOSYS;
979 return 0;
981 if (g_b_init_create_symbolic_link == 0)
983 g_b_init_create_symbolic_link = 1;
984 #ifdef _UNICODE
985 s_pfn_Create_Symbolic_Link =
986 (CreateSymbolicLink_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
987 "CreateSymbolicLinkW");
988 #else
989 s_pfn_Create_Symbolic_Link =
990 (CreateSymbolicLink_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
991 "CreateSymbolicLinkA");
992 #endif
994 if (s_pfn_Create_Symbolic_Link == NULL)
996 errno = ENOSYS;
997 return 0;
1000 retval = s_pfn_Create_Symbolic_Link (lpSymlinkFilename, lpTargetFileName,
1001 dwFlags);
1002 /* If we were denied creation of the symlink, try again after
1003 enabling the SeCreateSymbolicLinkPrivilege for our process. */
1004 if (!retval)
1006 TOKEN_PRIVILEGES priv_current;
1008 if (enable_privilege (SE_CREATE_SYMBOLIC_LINK_NAME, TRUE, &priv_current))
1010 retval = s_pfn_Create_Symbolic_Link (lpSymlinkFilename, lpTargetFileName,
1011 dwFlags);
1012 restore_privilege (&priv_current);
1013 revert_to_self ();
1016 return retval;
1019 static BOOL WINAPI
1020 is_valid_security_descriptor (PSECURITY_DESCRIPTOR pSecurityDescriptor)
1022 static IsValidSecurityDescriptor_Proc s_pfn_Is_Valid_Security_Descriptor_Proc = NULL;
1024 if (is_windows_9x () == TRUE)
1026 errno = ENOTSUP;
1027 return FALSE;
1030 if (g_b_init_is_valid_security_descriptor == 0)
1032 g_b_init_is_valid_security_descriptor = 1;
1033 s_pfn_Is_Valid_Security_Descriptor_Proc =
1034 (IsValidSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1035 "IsValidSecurityDescriptor");
1037 if (s_pfn_Is_Valid_Security_Descriptor_Proc == NULL)
1039 errno = ENOTSUP;
1040 return FALSE;
1043 return s_pfn_Is_Valid_Security_Descriptor_Proc (pSecurityDescriptor);
1046 static BOOL WINAPI
1047 convert_sd_to_sddl (PSECURITY_DESCRIPTOR SecurityDescriptor,
1048 DWORD RequestedStringSDRevision,
1049 SECURITY_INFORMATION SecurityInformation,
1050 LPTSTR *StringSecurityDescriptor,
1051 PULONG StringSecurityDescriptorLen)
1053 static ConvertSecurityDescriptorToStringSecurityDescriptor_Proc s_pfn_Convert_SD_To_SDDL = NULL;
1054 BOOL retval;
1056 if (is_windows_9x () == TRUE)
1058 errno = ENOTSUP;
1059 return FALSE;
1062 if (g_b_init_convert_sd_to_sddl == 0)
1064 g_b_init_convert_sd_to_sddl = 1;
1065 #ifdef _UNICODE
1066 s_pfn_Convert_SD_To_SDDL =
1067 (ConvertSecurityDescriptorToStringSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1068 "ConvertSecurityDescriptorToStringSecurityDescriptorW");
1069 #else
1070 s_pfn_Convert_SD_To_SDDL =
1071 (ConvertSecurityDescriptorToStringSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1072 "ConvertSecurityDescriptorToStringSecurityDescriptorA");
1073 #endif
1075 if (s_pfn_Convert_SD_To_SDDL == NULL)
1077 errno = ENOTSUP;
1078 return FALSE;
1081 retval = s_pfn_Convert_SD_To_SDDL (SecurityDescriptor,
1082 RequestedStringSDRevision,
1083 SecurityInformation,
1084 StringSecurityDescriptor,
1085 StringSecurityDescriptorLen);
1087 return retval;
1090 static BOOL WINAPI
1091 convert_sddl_to_sd (LPCTSTR StringSecurityDescriptor,
1092 DWORD StringSDRevision,
1093 PSECURITY_DESCRIPTOR *SecurityDescriptor,
1094 PULONG SecurityDescriptorSize)
1096 static ConvertStringSecurityDescriptorToSecurityDescriptor_Proc s_pfn_Convert_SDDL_To_SD = NULL;
1097 BOOL retval;
1099 if (is_windows_9x () == TRUE)
1101 errno = ENOTSUP;
1102 return FALSE;
1105 if (g_b_init_convert_sddl_to_sd == 0)
1107 g_b_init_convert_sddl_to_sd = 1;
1108 #ifdef _UNICODE
1109 s_pfn_Convert_SDDL_To_SD =
1110 (ConvertStringSecurityDescriptorToSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1111 "ConvertStringSecurityDescriptorToSecurityDescriptorW");
1112 #else
1113 s_pfn_Convert_SDDL_To_SD =
1114 (ConvertStringSecurityDescriptorToSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1115 "ConvertStringSecurityDescriptorToSecurityDescriptorA");
1116 #endif
1118 if (s_pfn_Convert_SDDL_To_SD == NULL)
1120 errno = ENOTSUP;
1121 return FALSE;
1124 retval = s_pfn_Convert_SDDL_To_SD (StringSecurityDescriptor,
1125 StringSDRevision,
1126 SecurityDescriptor,
1127 SecurityDescriptorSize);
1129 return retval;
1134 /* Return 1 if P is a valid pointer to an object of size SIZE. Return
1135 0 if P is NOT a valid pointer. Return -1 if we cannot validate P.
1137 This is called from alloc.c:valid_pointer_p. */
1139 w32_valid_pointer_p (void *p, int size)
1141 SIZE_T done;
1142 HANDLE h = OpenProcess (PROCESS_VM_READ, FALSE, GetCurrentProcessId ());
1144 if (h)
1146 unsigned char *buf = alloca (size);
1147 int retval = ReadProcessMemory (h, p, buf, size, &done);
1149 CloseHandle (h);
1150 return retval;
1152 else
1153 return -1;
1156 static char startup_dir[MAXPATHLEN];
1158 /* Get the current working directory. */
1159 char *
1160 getcwd (char *dir, int dirsize)
1162 if (!dirsize)
1164 errno = EINVAL;
1165 return NULL;
1167 if (dirsize <= strlen (startup_dir))
1169 errno = ERANGE;
1170 return NULL;
1172 #if 0
1173 if (GetCurrentDirectory (MAXPATHLEN, dir) > 0)
1174 return dir;
1175 return NULL;
1176 #else
1177 /* Emacs doesn't actually change directory itself, it stays in the
1178 same directory where it was started. */
1179 strcpy (dir, startup_dir);
1180 return dir;
1181 #endif
1184 /* Emulate getloadavg. */
1186 struct load_sample {
1187 time_t sample_time;
1188 ULONGLONG idle;
1189 ULONGLONG kernel;
1190 ULONGLONG user;
1193 /* Number of processors on this machine. */
1194 static unsigned num_of_processors;
1196 /* We maintain 1-sec samples for the last 16 minutes in a circular buffer. */
1197 static struct load_sample samples[16*60];
1198 static int first_idx = -1, last_idx = -1;
1199 static int max_idx = sizeof (samples) / sizeof (samples[0]);
1201 static int
1202 buf_next (int from)
1204 int next_idx = from + 1;
1206 if (next_idx >= max_idx)
1207 next_idx = 0;
1209 return next_idx;
1212 static int
1213 buf_prev (int from)
1215 int prev_idx = from - 1;
1217 if (prev_idx < 0)
1218 prev_idx = max_idx - 1;
1220 return prev_idx;
1223 static void
1224 sample_system_load (ULONGLONG *idle, ULONGLONG *kernel, ULONGLONG *user)
1226 SYSTEM_INFO sysinfo;
1227 FILETIME ft_idle, ft_user, ft_kernel;
1229 /* Initialize the number of processors on this machine. */
1230 if (num_of_processors <= 0)
1232 get_native_system_info (&sysinfo);
1233 num_of_processors = sysinfo.dwNumberOfProcessors;
1234 if (num_of_processors <= 0)
1236 GetSystemInfo (&sysinfo);
1237 num_of_processors = sysinfo.dwNumberOfProcessors;
1239 if (num_of_processors <= 0)
1240 num_of_processors = 1;
1243 /* TODO: Take into account threads that are ready to run, by
1244 sampling the "\System\Processor Queue Length" performance
1245 counter. The code below accounts only for threads that are
1246 actually running. */
1248 if (get_system_times (&ft_idle, &ft_kernel, &ft_user))
1250 ULARGE_INTEGER uidle, ukernel, uuser;
1252 memcpy (&uidle, &ft_idle, sizeof (ft_idle));
1253 memcpy (&ukernel, &ft_kernel, sizeof (ft_kernel));
1254 memcpy (&uuser, &ft_user, sizeof (ft_user));
1255 *idle = uidle.QuadPart;
1256 *kernel = ukernel.QuadPart;
1257 *user = uuser.QuadPart;
1259 else
1261 *idle = 0;
1262 *kernel = 0;
1263 *user = 0;
1267 /* Produce the load average for a given time interval, using the
1268 samples in the samples[] array. WHICH can be 0, 1, or 2, meaning
1269 1-minute, 5-minute, or 15-minute average, respectively. */
1270 static double
1271 getavg (int which)
1273 double retval = -1.0;
1274 double tdiff;
1275 int idx;
1276 double span = (which == 0 ? 1.0 : (which == 1 ? 5.0 : 15.0)) * 60;
1277 time_t now = samples[last_idx].sample_time;
1279 if (first_idx != last_idx)
1281 for (idx = buf_prev (last_idx); ; idx = buf_prev (idx))
1283 tdiff = difftime (now, samples[idx].sample_time);
1284 if (tdiff >= span - 2*DBL_EPSILON*now)
1286 long double sys =
1287 samples[last_idx].kernel + samples[last_idx].user
1288 - (samples[idx].kernel + samples[idx].user);
1289 long double idl = samples[last_idx].idle - samples[idx].idle;
1291 retval = (1.0 - idl / sys) * num_of_processors;
1292 break;
1294 if (idx == first_idx)
1295 break;
1299 return retval;
1303 getloadavg (double loadavg[], int nelem)
1305 int elem;
1306 ULONGLONG idle, kernel, user;
1307 time_t now = time (NULL);
1309 /* Store another sample. We ignore samples that are less than 1 sec
1310 apart. */
1311 if (difftime (now, samples[last_idx].sample_time) >= 1.0 - 2*DBL_EPSILON*now)
1313 sample_system_load (&idle, &kernel, &user);
1314 last_idx = buf_next (last_idx);
1315 samples[last_idx].sample_time = now;
1316 samples[last_idx].idle = idle;
1317 samples[last_idx].kernel = kernel;
1318 samples[last_idx].user = user;
1319 /* If the buffer has more that 15 min worth of samples, discard
1320 the old ones. */
1321 if (first_idx == -1)
1322 first_idx = last_idx;
1323 while (first_idx != last_idx
1324 && (difftime (now, samples[first_idx].sample_time)
1325 >= 15.0*60 + 2*DBL_EPSILON*now))
1326 first_idx = buf_next (first_idx);
1329 for (elem = 0; elem < nelem; elem++)
1331 double avg = getavg (elem);
1333 if (avg < 0)
1334 break;
1335 loadavg[elem] = avg;
1338 return elem;
1341 /* Emulate getpwuid, getpwnam and others. */
1343 #define PASSWD_FIELD_SIZE 256
1345 static char dflt_passwd_name[PASSWD_FIELD_SIZE];
1346 static char dflt_passwd_passwd[PASSWD_FIELD_SIZE];
1347 static char dflt_passwd_gecos[PASSWD_FIELD_SIZE];
1348 static char dflt_passwd_dir[PASSWD_FIELD_SIZE];
1349 static char dflt_passwd_shell[PASSWD_FIELD_SIZE];
1351 static struct passwd dflt_passwd =
1353 dflt_passwd_name,
1354 dflt_passwd_passwd,
1358 dflt_passwd_gecos,
1359 dflt_passwd_dir,
1360 dflt_passwd_shell,
1363 static char dflt_group_name[GNLEN+1];
1365 static struct group dflt_group =
1367 /* When group information is not available, we return this as the
1368 group for all files. */
1369 dflt_group_name,
1373 unsigned
1374 getuid (void)
1376 return dflt_passwd.pw_uid;
1379 unsigned
1380 geteuid (void)
1382 /* I could imagine arguing for checking to see whether the user is
1383 in the Administrators group and returning a UID of 0 for that
1384 case, but I don't know how wise that would be in the long run. */
1385 return getuid ();
1388 unsigned
1389 getgid (void)
1391 return dflt_passwd.pw_gid;
1394 unsigned
1395 getegid (void)
1397 return getgid ();
1400 struct passwd *
1401 getpwuid (unsigned uid)
1403 if (uid == dflt_passwd.pw_uid)
1404 return &dflt_passwd;
1405 return NULL;
1408 struct group *
1409 getgrgid (gid_t gid)
1411 return &dflt_group;
1414 struct passwd *
1415 getpwnam (char *name)
1417 struct passwd *pw;
1419 pw = getpwuid (getuid ());
1420 if (!pw)
1421 return pw;
1423 if (xstrcasecmp (name, pw->pw_name))
1424 return NULL;
1426 return pw;
1429 static void
1430 init_user_info (void)
1432 /* Find the user's real name by opening the process token and
1433 looking up the name associated with the user-sid in that token.
1435 Use the relative portion of the identifier authority value from
1436 the user-sid as the user id value (same for group id using the
1437 primary group sid from the process token). */
1439 char uname[UNLEN+1], gname[GNLEN+1], domain[1025];
1440 DWORD ulength = sizeof (uname), dlength = sizeof (domain), needed;
1441 DWORD glength = sizeof (gname);
1442 HANDLE token = NULL;
1443 SID_NAME_USE user_type;
1444 unsigned char *buf = NULL;
1445 DWORD blen = 0;
1446 TOKEN_USER user_token;
1447 TOKEN_PRIMARY_GROUP group_token;
1448 BOOL result;
1450 result = open_process_token (GetCurrentProcess (), TOKEN_QUERY, &token);
1451 if (result)
1453 result = get_token_information (token, TokenUser, NULL, 0, &blen);
1454 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
1456 buf = xmalloc (blen);
1457 result = get_token_information (token, TokenUser,
1458 (LPVOID)buf, blen, &needed);
1459 if (result)
1461 memcpy (&user_token, buf, sizeof (user_token));
1462 result = lookup_account_sid (NULL, user_token.User.Sid,
1463 uname, &ulength,
1464 domain, &dlength, &user_type);
1467 else
1468 result = FALSE;
1470 if (result)
1472 strcpy (dflt_passwd.pw_name, uname);
1473 /* Determine a reasonable uid value. */
1474 if (xstrcasecmp ("administrator", uname) == 0)
1476 dflt_passwd.pw_uid = 500; /* well-known Administrator uid */
1477 dflt_passwd.pw_gid = 513; /* well-known None gid */
1479 else
1481 /* Use the last sub-authority value of the RID, the relative
1482 portion of the SID, as user/group ID. */
1483 dflt_passwd.pw_uid = get_rid (user_token.User.Sid);
1485 /* Get group id and name. */
1486 result = get_token_information (token, TokenPrimaryGroup,
1487 (LPVOID)buf, blen, &needed);
1488 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
1490 buf = xrealloc (buf, blen = needed);
1491 result = get_token_information (token, TokenPrimaryGroup,
1492 (LPVOID)buf, blen, &needed);
1494 if (result)
1496 memcpy (&group_token, buf, sizeof (group_token));
1497 dflt_passwd.pw_gid = get_rid (group_token.PrimaryGroup);
1498 dlength = sizeof (domain);
1499 /* If we can get at the real Primary Group name, use that.
1500 Otherwise, the default group name was already set to
1501 "None" in globals_of_w32. */
1502 if (lookup_account_sid (NULL, group_token.PrimaryGroup,
1503 gname, &glength, NULL, &dlength,
1504 &user_type))
1505 strcpy (dflt_group_name, gname);
1507 else
1508 dflt_passwd.pw_gid = dflt_passwd.pw_uid;
1511 /* If security calls are not supported (presumably because we
1512 are running under Windows 9X), fallback to this: */
1513 else if (GetUserName (uname, &ulength))
1515 strcpy (dflt_passwd.pw_name, uname);
1516 if (xstrcasecmp ("administrator", uname) == 0)
1517 dflt_passwd.pw_uid = 0;
1518 else
1519 dflt_passwd.pw_uid = 123;
1520 dflt_passwd.pw_gid = dflt_passwd.pw_uid;
1522 else
1524 strcpy (dflt_passwd.pw_name, "unknown");
1525 dflt_passwd.pw_uid = 123;
1526 dflt_passwd.pw_gid = 123;
1528 dflt_group.gr_gid = dflt_passwd.pw_gid;
1530 /* Ensure HOME and SHELL are defined. */
1531 if (getenv ("HOME") == NULL)
1532 emacs_abort ();
1533 if (getenv ("SHELL") == NULL)
1534 emacs_abort ();
1536 /* Set dir and shell from environment variables. */
1537 strcpy (dflt_passwd.pw_dir, getenv ("HOME"));
1538 strcpy (dflt_passwd.pw_shell, getenv ("SHELL"));
1540 xfree (buf);
1541 if (token)
1542 CloseHandle (token);
1546 random (void)
1548 /* rand () on NT gives us 15 random bits...hack together 30 bits. */
1549 return ((rand () << 15) | rand ());
1552 void
1553 srandom (int seed)
1555 srand (seed);
1558 /* Current codepage for encoding file names. */
1559 static int file_name_codepage;
1561 /* Return the maximum length in bytes of a multibyte character
1562 sequence encoded in the current ANSI codepage. This is required to
1563 correctly walk the encoded file names one character at a time. */
1564 static int
1565 max_filename_mbslen (void)
1567 /* A simple cache to avoid calling GetCPInfo every time we need to
1568 normalize a file name. The file-name encoding is not supposed to
1569 be changed too frequently, if ever. */
1570 static Lisp_Object last_file_name_encoding;
1571 static int last_max_mbslen;
1572 Lisp_Object current_encoding;
1574 current_encoding = Vfile_name_coding_system;
1575 if (NILP (current_encoding))
1576 current_encoding = Vdefault_file_name_coding_system;
1578 if (!EQ (last_file_name_encoding, current_encoding))
1580 CPINFO cp_info;
1582 last_file_name_encoding = current_encoding;
1583 /* Default to the current ANSI codepage. */
1584 file_name_codepage = w32_ansi_code_page;
1585 if (!NILP (current_encoding))
1587 char *cpname = SDATA (SYMBOL_NAME (current_encoding));
1588 char *cp = NULL, *end;
1589 int cpnum;
1591 if (strncmp (cpname, "cp", 2) == 0)
1592 cp = cpname + 2;
1593 else if (strncmp (cpname, "windows-", 8) == 0)
1594 cp = cpname + 8;
1596 if (cp)
1598 end = cp;
1599 cpnum = strtol (cp, &end, 10);
1600 if (cpnum && *end == '\0' && end - cp >= 2)
1601 file_name_codepage = cpnum;
1605 if (!file_name_codepage)
1606 file_name_codepage = CP_ACP; /* CP_ACP = 0, but let's not assume that */
1608 if (!GetCPInfo (file_name_codepage, &cp_info))
1610 file_name_codepage = CP_ACP;
1611 if (!GetCPInfo (file_name_codepage, &cp_info))
1612 emacs_abort ();
1614 last_max_mbslen = cp_info.MaxCharSize;
1617 return last_max_mbslen;
1620 /* Normalize filename by converting all path separators to
1621 the specified separator. Also conditionally convert upper
1622 case path name components to lower case. */
1624 static void
1625 normalize_filename (register char *fp, char path_sep, int multibyte)
1627 char sep;
1628 char *elem, *p2;
1629 int dbcs_p = max_filename_mbslen () > 1;
1631 /* Multibyte file names are in the Emacs internal representation, so
1632 we can traverse them by bytes with no problems. */
1633 if (multibyte)
1634 dbcs_p = 0;
1636 /* Always lower-case drive letters a-z, even if the filesystem
1637 preserves case in filenames.
1638 This is so filenames can be compared by string comparison
1639 functions that are case-sensitive. Even case-preserving filesystems
1640 do not distinguish case in drive letters. */
1641 if (dbcs_p)
1642 p2 = CharNextExA (file_name_codepage, fp, 0);
1643 else
1644 p2 = fp + 1;
1646 if (*p2 == ':' && *fp >= 'A' && *fp <= 'Z')
1648 *fp += 'a' - 'A';
1649 fp += 2;
1652 if (multibyte || NILP (Vw32_downcase_file_names))
1654 while (*fp)
1656 if (*fp == '/' || *fp == '\\')
1657 *fp = path_sep;
1658 if (!dbcs_p)
1659 fp++;
1660 else
1661 fp = CharNextExA (file_name_codepage, fp, 0);
1663 return;
1666 sep = path_sep; /* convert to this path separator */
1667 elem = fp; /* start of current path element */
1669 do {
1670 if (*fp >= 'a' && *fp <= 'z')
1671 elem = 0; /* don't convert this element */
1673 if (*fp == 0 || *fp == ':')
1675 sep = *fp; /* restore current separator (or 0) */
1676 *fp = '/'; /* after conversion of this element */
1679 if (*fp == '/' || *fp == '\\')
1681 if (elem && elem != fp)
1683 *fp = 0; /* temporary end of string */
1684 _mbslwr (elem); /* while we convert to lower case */
1686 *fp = sep; /* convert (or restore) path separator */
1687 elem = fp + 1; /* next element starts after separator */
1688 sep = path_sep;
1690 if (*fp)
1692 if (!dbcs_p)
1693 fp++;
1694 else
1695 fp = CharNextExA (file_name_codepage, fp, 0);
1697 } while (*fp);
1700 /* Destructively turn backslashes into slashes. MULTIBYTE non-zero
1701 means the file name is a multibyte string in Emacs's internal
1702 representation. */
1703 void
1704 dostounix_filename (register char *p, int multibyte)
1706 normalize_filename (p, '/', multibyte);
1709 /* Destructively turn slashes into backslashes. */
1710 void
1711 unixtodos_filename (register char *p)
1713 normalize_filename (p, '\\', 0);
1716 /* Remove all CR's that are followed by a LF.
1717 (From msdos.c...probably should figure out a way to share it,
1718 although this code isn't going to ever change.) */
1719 static int
1720 crlf_to_lf (register int n, register unsigned char *buf)
1722 unsigned char *np = buf;
1723 unsigned char *startp = buf;
1724 unsigned char *endp = buf + n;
1726 if (n == 0)
1727 return n;
1728 while (buf < endp - 1)
1730 if (*buf == 0x0d)
1732 if (*(++buf) != 0x0a)
1733 *np++ = 0x0d;
1735 else
1736 *np++ = *buf++;
1738 if (buf < endp)
1739 *np++ = *buf++;
1740 return np - startp;
1743 /* Parse the root part of file name, if present. Return length and
1744 optionally store pointer to char after root. */
1745 static int
1746 parse_root (char * name, char ** pPath)
1748 char * start = name;
1750 if (name == NULL)
1751 return 0;
1753 /* find the root name of the volume if given */
1754 if (isalpha (name[0]) && name[1] == ':')
1756 /* skip past drive specifier */
1757 name += 2;
1758 if (IS_DIRECTORY_SEP (name[0]))
1759 name++;
1761 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
1763 int slashes = 2;
1764 int dbcs_p = max_filename_mbslen () > 1;
1766 name += 2;
1769 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
1770 break;
1771 if (dbcs_p)
1772 name = CharNextExA (file_name_codepage, name, 0);
1773 else
1774 name++;
1776 while ( *name );
1777 if (IS_DIRECTORY_SEP (name[0]))
1778 name++;
1781 if (pPath)
1782 *pPath = name;
1784 return name - start;
1787 /* Get long base name for name; name is assumed to be absolute. */
1788 static int
1789 get_long_basename (char * name, char * buf, int size)
1791 WIN32_FIND_DATA find_data;
1792 HANDLE dir_handle;
1793 int len = 0;
1795 /* must be valid filename, no wild cards or other invalid characters */
1796 if (_mbspbrk (name, "*?|<>\""))
1797 return 0;
1799 dir_handle = FindFirstFile (name, &find_data);
1800 if (dir_handle != INVALID_HANDLE_VALUE)
1802 if ((len = strlen (find_data.cFileName)) < size)
1803 memcpy (buf, find_data.cFileName, len + 1);
1804 else
1805 len = 0;
1806 FindClose (dir_handle);
1808 return len;
1811 /* Get long name for file, if possible (assumed to be absolute). */
1812 BOOL
1813 w32_get_long_filename (char * name, char * buf, int size)
1815 char * o = buf;
1816 char * p;
1817 char * q;
1818 char full[ MAX_PATH ];
1819 int len;
1821 len = strlen (name);
1822 if (len >= MAX_PATH)
1823 return FALSE;
1825 /* Use local copy for destructive modification. */
1826 memcpy (full, name, len+1);
1827 unixtodos_filename (full);
1829 /* Copy root part verbatim. */
1830 len = parse_root (full, &p);
1831 memcpy (o, full, len);
1832 o += len;
1833 *o = '\0';
1834 size -= len;
1836 while (p != NULL && *p)
1838 q = p;
1839 p = _mbschr (q, '\\');
1840 if (p) *p = '\0';
1841 len = get_long_basename (full, o, size);
1842 if (len > 0)
1844 o += len;
1845 size -= len;
1846 if (p != NULL)
1848 *p++ = '\\';
1849 if (size < 2)
1850 return FALSE;
1851 *o++ = '\\';
1852 size--;
1853 *o = '\0';
1856 else
1857 return FALSE;
1860 return TRUE;
1863 static int
1864 is_unc_volume (const char *filename)
1866 const char *ptr = filename;
1868 if (!IS_DIRECTORY_SEP (ptr[0]) || !IS_DIRECTORY_SEP (ptr[1]) || !ptr[2])
1869 return 0;
1871 if (_mbspbrk (ptr + 2, "*?|<>\"\\/"))
1872 return 0;
1874 return 1;
1877 /* Emulate the Posix unsetenv. */
1879 unsetenv (const char *name)
1881 char *var;
1882 size_t name_len;
1883 int retval;
1885 if (name == NULL || *name == '\0' || strchr (name, '=') != NULL)
1887 errno = EINVAL;
1888 return -1;
1890 name_len = strlen (name);
1891 /* MS docs says an environment variable cannot be longer than 32K. */
1892 if (name_len > 32767)
1894 errno = ENOMEM;
1895 return 0;
1897 /* It is safe to use 'alloca' with 32K size, since the stack is at
1898 least 2MB, and we set it to 8MB in the link command line. */
1899 var = alloca (name_len + 2);
1900 strncpy (var, name, name_len);
1901 var[name_len++] = '=';
1902 var[name_len] = '\0';
1903 return _putenv (var);
1906 /* MS _putenv doesn't support removing a variable when the argument
1907 does not include the '=' character, so we fix that here. */
1909 sys_putenv (char *str)
1911 const char *const name_end = strchr (str, '=');
1913 if (name_end == NULL)
1915 /* Remove the variable from the environment. */
1916 return unsetenv (str);
1919 return _putenv (str);
1922 #define REG_ROOT "SOFTWARE\\GNU\\Emacs"
1924 LPBYTE
1925 w32_get_resource (char *key, LPDWORD lpdwtype)
1927 LPBYTE lpvalue;
1928 HKEY hrootkey = NULL;
1929 DWORD cbData;
1931 /* Check both the current user and the local machine to see if
1932 we have any resources. */
1934 if (RegOpenKeyEx (HKEY_CURRENT_USER, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
1936 lpvalue = NULL;
1938 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
1939 && (lpvalue = xmalloc (cbData)) != NULL
1940 && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
1942 RegCloseKey (hrootkey);
1943 return (lpvalue);
1946 xfree (lpvalue);
1948 RegCloseKey (hrootkey);
1951 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
1953 lpvalue = NULL;
1955 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
1956 && (lpvalue = xmalloc (cbData)) != NULL
1957 && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
1959 RegCloseKey (hrootkey);
1960 return (lpvalue);
1963 xfree (lpvalue);
1965 RegCloseKey (hrootkey);
1968 return (NULL);
1971 char *get_emacs_configuration (void);
1973 void
1974 init_environment (char ** argv)
1976 static const char * const tempdirs[] = {
1977 "$TMPDIR", "$TEMP", "$TMP", "c:/"
1980 int i;
1982 const int imax = sizeof (tempdirs) / sizeof (tempdirs[0]);
1984 /* Make sure they have a usable $TMPDIR. Many Emacs functions use
1985 temporary files and assume "/tmp" if $TMPDIR is unset, which
1986 will break on DOS/Windows. Refuse to work if we cannot find
1987 a directory, not even "c:/", usable for that purpose. */
1988 for (i = 0; i < imax ; i++)
1990 const char *tmp = tempdirs[i];
1992 if (*tmp == '$')
1993 tmp = getenv (tmp + 1);
1994 /* Note that `access' can lie to us if the directory resides on a
1995 read-only filesystem, like CD-ROM or a write-protected floppy.
1996 The only way to be really sure is to actually create a file and
1997 see if it succeeds. But I think that's too much to ask. */
1999 /* MSVCRT's _access crashes with D_OK. */
2000 if (tmp && faccessat (AT_FDCWD, tmp, D_OK, AT_EACCESS) == 0)
2002 char * var = alloca (strlen (tmp) + 8);
2003 sprintf (var, "TMPDIR=%s", tmp);
2004 _putenv (strdup (var));
2005 break;
2008 if (i >= imax)
2009 cmd_error_internal
2010 (Fcons (Qerror,
2011 Fcons (build_string ("no usable temporary directories found!!"),
2012 Qnil)),
2013 "While setting TMPDIR: ");
2015 /* Check for environment variables and use registry settings if they
2016 don't exist. Fallback on default values where applicable. */
2018 int i;
2019 LPBYTE lpval;
2020 DWORD dwType;
2021 char locale_name[32];
2022 char default_home[MAX_PATH];
2023 int appdata = 0;
2025 static const struct env_entry
2027 char * name;
2028 char * def_value;
2029 } dflt_envvars[] =
2031 /* If the default value is NULL, we will use the value from the
2032 outside environment or the Registry, but will not push the
2033 variable into the Emacs environment if it is defined neither
2034 in the Registry nor in the outside environment. */
2035 {"HOME", "C:/"},
2036 {"PRELOAD_WINSOCK", NULL},
2037 {"emacs_dir", "C:/emacs"},
2038 {"EMACSLOADPATH", NULL},
2039 {"SHELL", "cmdproxy.exe"}, /* perhaps it is somewhere on PATH */
2040 {"EMACSDATA", NULL},
2041 {"EMACSPATH", NULL},
2042 {"INFOPATH", NULL},
2043 {"EMACSDOC", NULL},
2044 {"TERM", "cmd"},
2045 {"LANG", NULL},
2048 #define N_ENV_VARS sizeof (dflt_envvars)/sizeof (dflt_envvars[0])
2050 /* We need to copy dflt_envvars[] and work on the copy because we
2051 don't want the dumped Emacs to inherit the values of
2052 environment variables we saw during dumping (which could be on
2053 a different system). The defaults above must be left intact. */
2054 struct env_entry env_vars[N_ENV_VARS];
2056 for (i = 0; i < N_ENV_VARS; i++)
2057 env_vars[i] = dflt_envvars[i];
2059 /* For backwards compatibility, check if a .emacs file exists in C:/
2060 If not, then we can try to default to the appdata directory under the
2061 user's profile, which is more likely to be writable. */
2062 if (!check_existing ("C:/.emacs"))
2064 HRESULT profile_result;
2065 /* Dynamically load ShGetFolderPath, as it won't exist on versions
2066 of Windows 95 and NT4 that have not been updated to include
2067 MSIE 5. */
2068 ShGetFolderPath_fn get_folder_path;
2069 get_folder_path = (ShGetFolderPath_fn)
2070 GetProcAddress (GetModuleHandle ("shell32.dll"), "SHGetFolderPathA");
2072 if (get_folder_path != NULL)
2074 profile_result = get_folder_path (NULL, CSIDL_APPDATA, NULL,
2075 0, default_home);
2077 /* If we can't get the appdata dir, revert to old behavior. */
2078 if (profile_result == S_OK)
2080 env_vars[0].def_value = default_home;
2081 appdata = 1;
2086 /* Get default locale info and use it for LANG. */
2087 if (GetLocaleInfo (LOCALE_USER_DEFAULT,
2088 LOCALE_SABBREVLANGNAME | LOCALE_USE_CP_ACP,
2089 locale_name, sizeof (locale_name)))
2091 for (i = 0; i < N_ENV_VARS; i++)
2093 if (strcmp (env_vars[i].name, "LANG") == 0)
2095 env_vars[i].def_value = locale_name;
2096 break;
2101 #define SET_ENV_BUF_SIZE (4 * MAX_PATH) /* to cover EMACSLOADPATH */
2103 /* Treat emacs_dir specially: set it unconditionally based on our
2104 location. */
2106 char *p;
2107 char modname[MAX_PATH];
2109 if (!GetModuleFileName (NULL, modname, MAX_PATH))
2110 emacs_abort ();
2111 if ((p = _mbsrchr (modname, '\\')) == NULL)
2112 emacs_abort ();
2113 *p = 0;
2115 if ((p = _mbsrchr (modname, '\\'))
2116 /* From bin means installed Emacs, from src means uninstalled. */
2117 && (xstrcasecmp (p, "\\bin") == 0 || xstrcasecmp (p, "\\src") == 0))
2119 char buf[SET_ENV_BUF_SIZE];
2120 int within_build_tree = xstrcasecmp (p, "\\src") == 0;
2122 *p = 0;
2123 for (p = modname; *p; p = CharNext (p))
2124 if (*p == '\\') *p = '/';
2126 _snprintf (buf, sizeof (buf)-1, "emacs_dir=%s", modname);
2127 _putenv (strdup (buf));
2128 /* If we are running from the Posix-like build tree, define
2129 SHELL to point to our own cmdproxy. The loop below will
2130 then disregard PATH_EXEC and the default value. */
2131 if (within_build_tree)
2133 _snprintf (buf, sizeof (buf) - 1,
2134 "SHELL=%s/nt/cmdproxy.exe", modname);
2135 _putenv (strdup (buf));
2138 /* Handle running emacs from the build directory: src/oo-spd/i386/ */
2140 /* FIXME: should use substring of get_emacs_configuration ().
2141 But I don't think the Windows build supports alpha, mips etc
2142 anymore, so have taken the easy option for now. */
2143 else if (p && (xstrcasecmp (p, "\\i386") == 0
2144 || xstrcasecmp (p, "\\AMD64") == 0))
2146 *p = 0;
2147 p = _mbsrchr (modname, '\\');
2148 if (p != NULL)
2150 *p = 0;
2151 p = _mbsrchr (modname, '\\');
2152 if (p && xstrcasecmp (p, "\\src") == 0)
2154 char buf[SET_ENV_BUF_SIZE];
2156 *p = 0;
2157 for (p = modname; *p; p = CharNext (p))
2158 if (*p == '\\') *p = '/';
2160 _snprintf (buf, sizeof (buf)-1, "emacs_dir=%s", modname);
2161 _putenv (strdup (buf));
2167 for (i = 0; i < N_ENV_VARS; i++)
2169 if (!getenv (env_vars[i].name))
2171 int dont_free = 0;
2172 char bufc[SET_ENV_BUF_SIZE];
2174 if ((lpval = w32_get_resource (env_vars[i].name, &dwType)) == NULL
2175 /* Also ignore empty environment variables. */
2176 || *lpval == 0)
2178 xfree (lpval);
2179 dont_free = 1;
2180 if (strcmp (env_vars[i].name, "SHELL") == 0)
2182 /* Look for cmdproxy.exe in every directory in
2183 PATH_EXEC. FIXME: This does not find cmdproxy
2184 in nt/ when we run uninstalled. */
2185 char fname[MAX_PATH];
2186 const char *pstart = PATH_EXEC, *pend;
2188 do {
2189 pend = _mbschr (pstart, ';');
2190 if (!pend)
2191 pend = pstart + strlen (pstart);
2192 /* Be defensive against series of ;;; characters. */
2193 if (pend > pstart)
2195 strncpy (fname, pstart, pend - pstart);
2196 fname[pend - pstart] = '/';
2197 strcpy (&fname[pend - pstart + 1], "cmdproxy.exe");
2198 ExpandEnvironmentStrings ((LPSTR) fname, bufc,
2199 sizeof (bufc));
2200 if (check_existing (bufc))
2202 lpval = bufc;
2203 dwType = REG_SZ;
2204 break;
2207 if (*pend)
2208 pstart = pend + 1;
2209 else
2210 pstart = pend;
2211 if (!*pstart)
2213 /* If not found in any directory, use the
2214 default as the last resort. */
2215 lpval = env_vars[i].def_value;
2216 dwType = REG_EXPAND_SZ;
2218 } while (*pstart);
2220 else
2222 lpval = env_vars[i].def_value;
2223 dwType = REG_EXPAND_SZ;
2225 if (strcmp (env_vars[i].name, "HOME") == 0 && !appdata)
2226 Vdelayed_warnings_list
2227 = Fcons (listn (CONSTYPE_HEAP, 2,
2228 intern ("initialization"),
2229 build_string ("Setting HOME to C:\\ by default is deprecated")),
2230 Vdelayed_warnings_list);
2233 if (lpval)
2235 char buf1[SET_ENV_BUF_SIZE], buf2[SET_ENV_BUF_SIZE];
2237 if (dwType == REG_EXPAND_SZ)
2238 ExpandEnvironmentStrings ((LPSTR) lpval, buf1, sizeof (buf1));
2239 else if (dwType == REG_SZ)
2240 strcpy (buf1, lpval);
2241 if (dwType == REG_EXPAND_SZ || dwType == REG_SZ)
2243 _snprintf (buf2, sizeof (buf2)-1, "%s=%s", env_vars[i].name,
2244 buf1);
2245 _putenv (strdup (buf2));
2248 if (!dont_free)
2249 xfree (lpval);
2255 /* Rebuild system configuration to reflect invoking system. */
2256 Vsystem_configuration = build_string (EMACS_CONFIGURATION);
2258 /* Another special case: on NT, the PATH variable is actually named
2259 "Path" although cmd.exe (perhaps NT itself) arranges for
2260 environment variable lookup and setting to be case insensitive.
2261 However, Emacs assumes a fully case sensitive environment, so we
2262 need to change "Path" to "PATH" to match the expectations of
2263 various elisp packages. We do this by the sneaky method of
2264 modifying the string in the C runtime environ entry.
2266 The same applies to COMSPEC. */
2268 char ** envp;
2270 for (envp = environ; *envp; envp++)
2271 if (_strnicmp (*envp, "PATH=", 5) == 0)
2272 memcpy (*envp, "PATH=", 5);
2273 else if (_strnicmp (*envp, "COMSPEC=", 8) == 0)
2274 memcpy (*envp, "COMSPEC=", 8);
2277 /* Remember the initial working directory for getcwd. */
2278 /* FIXME: Do we need to resolve possible symlinks in startup_dir?
2279 Does it matter anywhere in Emacs? */
2280 if (!GetCurrentDirectory (MAXPATHLEN, startup_dir))
2281 emacs_abort ();
2284 static char modname[MAX_PATH];
2286 if (!GetModuleFileName (NULL, modname, MAX_PATH))
2287 emacs_abort ();
2288 argv[0] = modname;
2291 /* Determine if there is a middle mouse button, to allow parse_button
2292 to decide whether right mouse events should be mouse-2 or
2293 mouse-3. */
2294 w32_num_mouse_buttons = GetSystemMetrics (SM_CMOUSEBUTTONS);
2296 init_user_info ();
2299 /* Called from expand-file-name when default-directory is not a string. */
2301 char *
2302 emacs_root_dir (void)
2304 static char root_dir[FILENAME_MAX];
2305 const char *p;
2307 p = getenv ("emacs_dir");
2308 if (p == NULL)
2309 emacs_abort ();
2310 strcpy (root_dir, p);
2311 root_dir[parse_root (root_dir, NULL)] = '\0';
2312 dostounix_filename (root_dir, 0);
2313 return root_dir;
2316 /* We don't have scripts to automatically determine the system configuration
2317 for Emacs before it's compiled, and we don't want to have to make the
2318 user enter it, so we define EMACS_CONFIGURATION to invoke this runtime
2319 routine. */
2321 char *
2322 get_emacs_configuration (void)
2324 char *arch, *oem, *os;
2325 int build_num;
2326 static char configuration_buffer[32];
2328 /* Determine the processor type. */
2329 switch (get_processor_type ())
2332 #ifdef PROCESSOR_INTEL_386
2333 case PROCESSOR_INTEL_386:
2334 case PROCESSOR_INTEL_486:
2335 case PROCESSOR_INTEL_PENTIUM:
2336 #ifdef _WIN64
2337 arch = "amd64";
2338 #else
2339 arch = "i386";
2340 #endif
2341 break;
2342 #endif
2343 #ifdef PROCESSOR_AMD_X8664
2344 case PROCESSOR_AMD_X8664:
2345 arch = "amd64";
2346 break;
2347 #endif
2349 #ifdef PROCESSOR_MIPS_R2000
2350 case PROCESSOR_MIPS_R2000:
2351 case PROCESSOR_MIPS_R3000:
2352 case PROCESSOR_MIPS_R4000:
2353 arch = "mips";
2354 break;
2355 #endif
2357 #ifdef PROCESSOR_ALPHA_21064
2358 case PROCESSOR_ALPHA_21064:
2359 arch = "alpha";
2360 break;
2361 #endif
2363 default:
2364 arch = "unknown";
2365 break;
2368 /* Use the OEM field to reflect the compiler/library combination. */
2369 #ifdef _MSC_VER
2370 #define COMPILER_NAME "msvc"
2371 #else
2372 #ifdef __GNUC__
2373 #define COMPILER_NAME "mingw"
2374 #else
2375 #define COMPILER_NAME "unknown"
2376 #endif
2377 #endif
2378 oem = COMPILER_NAME;
2380 switch (osinfo_cache.dwPlatformId) {
2381 case VER_PLATFORM_WIN32_NT:
2382 os = "nt";
2383 build_num = osinfo_cache.dwBuildNumber;
2384 break;
2385 case VER_PLATFORM_WIN32_WINDOWS:
2386 if (osinfo_cache.dwMinorVersion == 0) {
2387 os = "windows95";
2388 } else {
2389 os = "windows98";
2391 build_num = LOWORD (osinfo_cache.dwBuildNumber);
2392 break;
2393 case VER_PLATFORM_WIN32s:
2394 /* Not supported, should not happen. */
2395 os = "windows32s";
2396 build_num = LOWORD (osinfo_cache.dwBuildNumber);
2397 break;
2398 default:
2399 os = "unknown";
2400 build_num = 0;
2401 break;
2404 if (osinfo_cache.dwPlatformId == VER_PLATFORM_WIN32_NT) {
2405 sprintf (configuration_buffer, "%s-%s-%s%d.%d.%d", arch, oem, os,
2406 get_w32_major_version (), get_w32_minor_version (), build_num);
2407 } else {
2408 sprintf (configuration_buffer, "%s-%s-%s.%d", arch, oem, os, build_num);
2411 return configuration_buffer;
2414 char *
2415 get_emacs_configuration_options (void)
2417 static char *options_buffer;
2418 char cv[32]; /* Enough for COMPILER_VERSION. */
2419 char *options[] = {
2420 cv, /* To be filled later. */
2421 #ifdef EMACSDEBUG
2422 " --no-opt",
2423 #endif
2424 #ifdef ENABLE_CHECKING
2425 " --enable-checking",
2426 #endif
2427 /* configure.bat already sets USER_CFLAGS and USER_LDFLAGS
2428 with a starting space to save work here. */
2429 #ifdef USER_CFLAGS
2430 " --cflags", USER_CFLAGS,
2431 #endif
2432 #ifdef USER_LDFLAGS
2433 " --ldflags", USER_LDFLAGS,
2434 #endif
2435 NULL
2437 size_t size = 0;
2438 int i;
2440 /* Work out the effective configure options for this build. */
2441 #ifdef _MSC_VER
2442 #define COMPILER_VERSION "--with-msvc (%d.%02d)", _MSC_VER / 100, _MSC_VER % 100
2443 #else
2444 #ifdef __GNUC__
2445 #define COMPILER_VERSION "--with-gcc (%d.%d)", __GNUC__, __GNUC_MINOR__
2446 #else
2447 #define COMPILER_VERSION ""
2448 #endif
2449 #endif
2451 if (_snprintf (cv, sizeof (cv) - 1, COMPILER_VERSION) < 0)
2452 return "Error: not enough space for compiler version";
2453 cv[sizeof (cv) - 1] = '\0';
2455 for (i = 0; options[i]; i++)
2456 size += strlen (options[i]);
2458 options_buffer = xmalloc (size + 1);
2459 options_buffer[0] = '\0';
2461 for (i = 0; options[i]; i++)
2462 strcat (options_buffer, options[i]);
2464 return options_buffer;
2468 #include <sys/timeb.h>
2470 /* Emulate gettimeofday (Ulrich Leodolter, 1/11/95). */
2472 gettimeofday (struct timeval *__restrict tv, struct timezone *__restrict tz)
2474 struct _timeb tb;
2475 _ftime (&tb);
2477 tv->tv_sec = tb.time;
2478 tv->tv_usec = tb.millitm * 1000L;
2479 /* Implementation note: _ftime sometimes doesn't update the dstflag
2480 according to the new timezone when the system timezone is
2481 changed. We could fix that by using GetSystemTime and
2482 GetTimeZoneInformation, but that doesn't seem necessary, since
2483 Emacs always calls gettimeofday with the 2nd argument NULL (see
2484 current_emacs_time). */
2485 if (tz)
2487 tz->tz_minuteswest = tb.timezone; /* minutes west of Greenwich */
2488 tz->tz_dsttime = tb.dstflag; /* type of dst correction */
2490 return 0;
2493 /* Emulate fdutimens. */
2495 /* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2496 TIMESPEC[0] and TIMESPEC[1], respectively.
2497 FD must be either negative -- in which case it is ignored --
2498 or a file descriptor that is open on FILE.
2499 If FD is nonnegative, then FILE can be NULL, which means
2500 use just futimes instead of utimes.
2501 If TIMESPEC is null, FAIL.
2502 Return 0 on success, -1 (setting errno) on failure. */
2505 fdutimens (int fd, char const *file, struct timespec const timespec[2])
2507 if (!timespec)
2509 errno = ENOSYS;
2510 return -1;
2512 if (fd < 0 && !file)
2514 errno = EBADF;
2515 return -1;
2517 /* _futime's prototype defines 2nd arg as having the type 'struct
2518 _utimbuf', while utime needs to accept 'struct utimbuf' for
2519 compatibility with Posix. So we need to use 2 different (but
2520 equivalent) types to avoid compiler warnings, sigh. */
2521 if (fd >= 0)
2523 struct _utimbuf _ut;
2525 _ut.actime = timespec[0].tv_sec;
2526 _ut.modtime = timespec[1].tv_sec;
2527 return _futime (fd, &_ut);
2529 else
2531 struct utimbuf ut;
2533 ut.actime = timespec[0].tv_sec;
2534 ut.modtime = timespec[1].tv_sec;
2535 /* Call 'utime', which is implemented below, not the MS library
2536 function, which fails on directories. */
2537 return utime (file, &ut);
2542 /* ------------------------------------------------------------------------- */
2543 /* IO support and wrapper functions for the Windows API. */
2544 /* ------------------------------------------------------------------------- */
2546 /* Place a wrapper around the MSVC version of ctime. It returns NULL
2547 on network directories, so we handle that case here.
2548 (Ulrich Leodolter, 1/11/95). */
2549 char *
2550 sys_ctime (const time_t *t)
2552 char *str = (char *) ctime (t);
2553 return (str ? str : "Sun Jan 01 00:00:00 1970");
2556 /* Emulate sleep...we could have done this with a define, but that
2557 would necessitate including windows.h in the files that used it.
2558 This is much easier. */
2559 void
2560 sys_sleep (int seconds)
2562 Sleep (seconds * 1000);
2565 /* Internal MSVC functions for low-level descriptor munging */
2566 extern int __cdecl _set_osfhnd (int fd, long h);
2567 extern int __cdecl _free_osfhnd (int fd);
2569 /* parallel array of private info on file handles */
2570 filedesc fd_info [ MAXDESC ];
2572 typedef struct volume_info_data {
2573 struct volume_info_data * next;
2575 /* time when info was obtained */
2576 DWORD timestamp;
2578 /* actual volume info */
2579 char * root_dir;
2580 DWORD serialnum;
2581 DWORD maxcomp;
2582 DWORD flags;
2583 char * name;
2584 char * type;
2585 } volume_info_data;
2587 /* Global referenced by various functions. */
2588 static volume_info_data volume_info;
2590 /* Vector to indicate which drives are local and fixed (for which cached
2591 data never expires). */
2592 static BOOL fixed_drives[26];
2594 /* Consider cached volume information to be stale if older than 10s,
2595 at least for non-local drives. Info for fixed drives is never stale. */
2596 #define DRIVE_INDEX( c ) ( (c) <= 'Z' ? (c) - 'A' : (c) - 'a' )
2597 #define VOLINFO_STILL_VALID( root_dir, info ) \
2598 ( ( isalpha (root_dir[0]) && \
2599 fixed_drives[ DRIVE_INDEX (root_dir[0]) ] ) \
2600 || GetTickCount () - info->timestamp < 10000 )
2602 /* Cache support functions. */
2604 /* Simple linked list with linear search is sufficient. */
2605 static volume_info_data *volume_cache = NULL;
2607 static volume_info_data *
2608 lookup_volume_info (char * root_dir)
2610 volume_info_data * info;
2612 for (info = volume_cache; info; info = info->next)
2613 if (xstrcasecmp (info->root_dir, root_dir) == 0)
2614 break;
2615 return info;
2618 static void
2619 add_volume_info (char * root_dir, volume_info_data * info)
2621 info->root_dir = xstrdup (root_dir);
2622 info->next = volume_cache;
2623 volume_cache = info;
2627 /* Wrapper for GetVolumeInformation, which uses caching to avoid
2628 performance penalty (~2ms on 486 for local drives, 7.5ms for local
2629 cdrom drive, ~5-10ms or more for remote drives on LAN). */
2630 static volume_info_data *
2631 GetCachedVolumeInformation (char * root_dir)
2633 volume_info_data * info;
2634 char default_root[ MAX_PATH ];
2636 /* NULL for root_dir means use root from current directory. */
2637 if (root_dir == NULL)
2639 if (GetCurrentDirectory (MAX_PATH, default_root) == 0)
2640 return NULL;
2641 parse_root (default_root, &root_dir);
2642 *root_dir = 0;
2643 root_dir = default_root;
2646 /* Local fixed drives can be cached permanently. Removable drives
2647 cannot be cached permanently, since the volume name and serial
2648 number (if nothing else) can change. Remote drives should be
2649 treated as if they are removable, since there is no sure way to
2650 tell whether they are or not. Also, the UNC association of drive
2651 letters mapped to remote volumes can be changed at any time (even
2652 by other processes) without notice.
2654 As a compromise, so we can benefit from caching info for remote
2655 volumes, we use a simple expiry mechanism to invalidate cache
2656 entries that are more than ten seconds old. */
2658 #if 0
2659 /* No point doing this, because WNetGetConnection is even slower than
2660 GetVolumeInformation, consistently taking ~50ms on a 486 (FWIW,
2661 GetDriveType is about the only call of this type which does not
2662 involve network access, and so is extremely quick). */
2664 /* Map drive letter to UNC if remote. */
2665 if (isalpha (root_dir[0]) && !fixed[DRIVE_INDEX (root_dir[0])])
2667 char remote_name[ 256 ];
2668 char drive[3] = { root_dir[0], ':' };
2670 if (WNetGetConnection (drive, remote_name, sizeof (remote_name))
2671 == NO_ERROR)
2672 /* do something */ ;
2674 #endif
2676 info = lookup_volume_info (root_dir);
2678 if (info == NULL || ! VOLINFO_STILL_VALID (root_dir, info))
2680 char name[ 256 ];
2681 DWORD serialnum;
2682 DWORD maxcomp;
2683 DWORD flags;
2684 char type[ 256 ];
2686 /* Info is not cached, or is stale. */
2687 if (!GetVolumeInformation (root_dir,
2688 name, sizeof (name),
2689 &serialnum,
2690 &maxcomp,
2691 &flags,
2692 type, sizeof (type)))
2693 return NULL;
2695 /* Cache the volume information for future use, overwriting existing
2696 entry if present. */
2697 if (info == NULL)
2699 info = xmalloc (sizeof (volume_info_data));
2700 add_volume_info (root_dir, info);
2702 else
2704 xfree (info->name);
2705 xfree (info->type);
2708 info->name = xstrdup (name);
2709 info->serialnum = serialnum;
2710 info->maxcomp = maxcomp;
2711 info->flags = flags;
2712 info->type = xstrdup (type);
2713 info->timestamp = GetTickCount ();
2716 return info;
2719 /* Get information on the volume where NAME is held; set path pointer to
2720 start of pathname in NAME (past UNC header\volume header if present),
2721 if pPath is non-NULL.
2723 Note: if NAME includes symlinks, the information is for the volume
2724 of the symlink, not of its target. That's because, even though
2725 GetVolumeInformation returns information about the symlink target
2726 of its argument, we only pass the root directory to
2727 GetVolumeInformation, not the full NAME. */
2728 static int
2729 get_volume_info (const char * name, const char ** pPath)
2731 char temp[MAX_PATH];
2732 char *rootname = NULL; /* default to current volume */
2733 volume_info_data * info;
2735 if (name == NULL)
2736 return FALSE;
2738 /* Find the root name of the volume if given. */
2739 if (isalpha (name[0]) && name[1] == ':')
2741 rootname = temp;
2742 temp[0] = *name++;
2743 temp[1] = *name++;
2744 temp[2] = '\\';
2745 temp[3] = 0;
2747 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
2749 char *str = temp;
2750 int slashes = 4;
2751 int dbcs_p = max_filename_mbslen () > 1;
2753 rootname = temp;
2756 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
2757 break;
2758 if (!dbcs_p)
2759 *str++ = *name++;
2760 else
2762 const char *p = name;
2764 name = CharNextExA (file_name_codepage, name, 0);
2765 memcpy (str, p, name - p);
2766 str += name - p;
2769 while ( *name );
2771 *str++ = '\\';
2772 *str = 0;
2775 if (pPath)
2776 *pPath = name;
2778 info = GetCachedVolumeInformation (rootname);
2779 if (info != NULL)
2781 /* Set global referenced by other functions. */
2782 volume_info = *info;
2783 return TRUE;
2785 return FALSE;
2788 /* Determine if volume is FAT format (ie. only supports short 8.3
2789 names); also set path pointer to start of pathname in name, if
2790 pPath is non-NULL. */
2791 static int
2792 is_fat_volume (const char * name, const char ** pPath)
2794 if (get_volume_info (name, pPath))
2795 return (volume_info.maxcomp == 12);
2796 return FALSE;
2799 /* Map filename to a valid 8.3 name if necessary.
2800 The result is a pointer to a static buffer, so CAVEAT EMPTOR! */
2801 const char *
2802 map_w32_filename (const char * name, const char ** pPath)
2804 static char shortname[MAX_PATH];
2805 char * str = shortname;
2806 char c;
2807 char * path;
2808 const char * save_name = name;
2810 if (strlen (name) >= MAX_PATH)
2812 /* Return a filename which will cause callers to fail. */
2813 strcpy (shortname, "?");
2814 return shortname;
2817 if (is_fat_volume (name, (const char **)&path)) /* truncate to 8.3 */
2819 register int left = 8; /* maximum number of chars in part */
2820 register int extn = 0; /* extension added? */
2821 register int dots = 2; /* maximum number of dots allowed */
2823 while (name < path)
2824 *str++ = *name++; /* skip past UNC header */
2826 while ((c = *name++))
2828 switch ( c )
2830 case ':':
2831 case '\\':
2832 case '/':
2833 *str++ = (c == ':' ? ':' : '\\');
2834 extn = 0; /* reset extension flags */
2835 dots = 2; /* max 2 dots */
2836 left = 8; /* max length 8 for main part */
2837 break;
2838 case '.':
2839 if ( dots )
2841 /* Convert path components of the form .xxx to _xxx,
2842 but leave . and .. as they are. This allows .emacs
2843 to be read as _emacs, for example. */
2845 if (! *name ||
2846 *name == '.' ||
2847 IS_DIRECTORY_SEP (*name))
2849 *str++ = '.';
2850 dots--;
2852 else
2854 *str++ = '_';
2855 left--;
2856 dots = 0;
2859 else if ( !extn )
2861 *str++ = '.';
2862 extn = 1; /* we've got an extension */
2863 left = 3; /* 3 chars in extension */
2865 else
2867 /* any embedded dots after the first are converted to _ */
2868 *str++ = '_';
2870 break;
2871 case '~':
2872 case '#': /* don't lose these, they're important */
2873 if ( ! left )
2874 str[-1] = c; /* replace last character of part */
2875 /* FALLTHRU */
2876 default:
2877 if ( left )
2879 *str++ = tolower (c); /* map to lower case (looks nicer) */
2880 left--;
2881 dots = 0; /* started a path component */
2883 break;
2886 *str = '\0';
2888 else
2890 strcpy (shortname, name);
2891 unixtodos_filename (shortname);
2894 if (pPath)
2895 *pPath = shortname + (path - save_name);
2897 return shortname;
2900 static int
2901 is_exec (const char * name)
2903 char * p = strrchr (name, '.');
2904 return
2905 (p != NULL
2906 && (xstrcasecmp (p, ".exe") == 0 ||
2907 xstrcasecmp (p, ".com") == 0 ||
2908 xstrcasecmp (p, ".bat") == 0 ||
2909 xstrcasecmp (p, ".cmd") == 0));
2912 /* Emulate the Unix directory procedures opendir, closedir,
2913 and readdir. We can't use the procedures supplied in sysdep.c,
2914 so we provide them here. */
2916 struct dirent dir_static; /* simulated directory contents */
2917 static HANDLE dir_find_handle = INVALID_HANDLE_VALUE;
2918 static int dir_is_fat;
2919 static char dir_pathname[MAXPATHLEN+1];
2920 static WIN32_FIND_DATA dir_find_data;
2922 /* Support shares on a network resource as subdirectories of a read-only
2923 root directory. */
2924 static HANDLE wnet_enum_handle = INVALID_HANDLE_VALUE;
2925 static HANDLE open_unc_volume (const char *);
2926 static char *read_unc_volume (HANDLE, char *, int);
2927 static void close_unc_volume (HANDLE);
2929 DIR *
2930 opendir (const char *filename)
2932 DIR *dirp;
2934 /* Opening is done by FindFirstFile. However, a read is inherent to
2935 this operation, so we defer the open until read time. */
2937 if (dir_find_handle != INVALID_HANDLE_VALUE)
2938 return NULL;
2939 if (wnet_enum_handle != INVALID_HANDLE_VALUE)
2940 return NULL;
2942 /* Note: We don't support traversal of UNC volumes via symlinks.
2943 Doing so would mean punishing 99.99% of use cases by resolving
2944 all the possible symlinks in FILENAME, recursively. */
2945 if (is_unc_volume (filename))
2947 wnet_enum_handle = open_unc_volume (filename);
2948 if (wnet_enum_handle == INVALID_HANDLE_VALUE)
2949 return NULL;
2952 if (!(dirp = (DIR *) malloc (sizeof (DIR))))
2953 return NULL;
2955 dirp->dd_fd = 0;
2956 dirp->dd_loc = 0;
2957 dirp->dd_size = 0;
2959 strncpy (dir_pathname, map_w32_filename (filename, NULL), MAXPATHLEN);
2960 dir_pathname[MAXPATHLEN] = '\0';
2961 /* Note: We don't support symlinks to file names on FAT volumes.
2962 Doing so would mean punishing 99.99% of use cases by resolving
2963 all the possible symlinks in FILENAME, recursively. */
2964 dir_is_fat = is_fat_volume (filename, NULL);
2966 return dirp;
2969 void
2970 closedir (DIR *dirp)
2972 /* If we have a find-handle open, close it. */
2973 if (dir_find_handle != INVALID_HANDLE_VALUE)
2975 FindClose (dir_find_handle);
2976 dir_find_handle = INVALID_HANDLE_VALUE;
2978 else if (wnet_enum_handle != INVALID_HANDLE_VALUE)
2980 close_unc_volume (wnet_enum_handle);
2981 wnet_enum_handle = INVALID_HANDLE_VALUE;
2983 xfree ((char *) dirp);
2986 struct dirent *
2987 readdir (DIR *dirp)
2989 int downcase = !NILP (Vw32_downcase_file_names);
2991 if (wnet_enum_handle != INVALID_HANDLE_VALUE)
2993 if (!read_unc_volume (wnet_enum_handle,
2994 dir_find_data.cFileName,
2995 MAX_PATH))
2996 return NULL;
2998 /* If we aren't dir_finding, do a find-first, otherwise do a find-next. */
2999 else if (dir_find_handle == INVALID_HANDLE_VALUE)
3001 char filename[MAXNAMLEN + 3];
3002 int ln;
3003 int dbcs_p = max_filename_mbslen () > 1;
3005 strcpy (filename, dir_pathname);
3006 ln = strlen (filename) - 1;
3007 if (!dbcs_p)
3009 if (!IS_DIRECTORY_SEP (filename[ln]))
3010 strcat (filename, "\\");
3012 else
3014 char *end = filename + ln + 1;
3015 char *last_char = CharPrevExA (file_name_codepage, filename, end, 0);
3017 if (!IS_DIRECTORY_SEP (*last_char))
3018 strcat (filename, "\\");
3020 strcat (filename, "*");
3022 /* Note: No need to resolve symlinks in FILENAME, because
3023 FindFirst opens the directory that is the target of a
3024 symlink. */
3025 dir_find_handle = FindFirstFile (filename, &dir_find_data);
3027 if (dir_find_handle == INVALID_HANDLE_VALUE)
3028 return NULL;
3030 else
3032 if (!FindNextFile (dir_find_handle, &dir_find_data))
3033 return NULL;
3036 /* Emacs never uses this value, so don't bother making it match
3037 value returned by stat(). */
3038 dir_static.d_ino = 1;
3040 strcpy (dir_static.d_name, dir_find_data.cFileName);
3042 /* If the file name in cFileName[] includes `?' characters, it means
3043 the original file name used characters that cannot be represented
3044 by the current ANSI codepage. To avoid total lossage, retrieve
3045 the short 8+3 alias of the long file name. */
3046 if (_mbspbrk (dir_static.d_name, "?"))
3048 strcpy (dir_static.d_name, dir_find_data.cAlternateFileName);
3049 downcase = 1; /* 8+3 aliases are returned in all caps */
3051 dir_static.d_namlen = strlen (dir_static.d_name);
3052 dir_static.d_reclen = sizeof (struct dirent) - MAXNAMLEN + 3 +
3053 dir_static.d_namlen - dir_static.d_namlen % 4;
3055 /* If the file name in cFileName[] includes `?' characters, it means
3056 the original file name used characters that cannot be represented
3057 by the current ANSI codepage. To avoid total lossage, retrieve
3058 the short 8+3 alias of the long file name. */
3059 if (_mbspbrk (dir_find_data.cFileName, "?"))
3061 strcpy (dir_static.d_name, dir_find_data.cAlternateFileName);
3062 /* 8+3 aliases are returned in all caps, which could break
3063 various alists that look at filenames' extensions. */
3064 downcase = 1;
3066 else
3067 strcpy (dir_static.d_name, dir_find_data.cFileName);
3068 dir_static.d_namlen = strlen (dir_static.d_name);
3069 if (dir_is_fat)
3070 _mbslwr (dir_static.d_name);
3071 else if (downcase)
3073 register char *p;
3074 int dbcs_p = max_filename_mbslen () > 1;
3075 for (p = dir_static.d_name; *p; )
3077 if (*p >= 'a' && *p <= 'z')
3078 break;
3079 if (dbcs_p)
3080 p = CharNextExA (file_name_codepage, p, 0);
3081 else
3082 p++;
3084 if (!*p)
3085 _mbslwr (dir_static.d_name);
3088 return &dir_static;
3091 static HANDLE
3092 open_unc_volume (const char *path)
3094 NETRESOURCE nr;
3095 HANDLE henum;
3096 int result;
3098 nr.dwScope = RESOURCE_GLOBALNET;
3099 nr.dwType = RESOURCETYPE_DISK;
3100 nr.dwDisplayType = RESOURCEDISPLAYTYPE_SERVER;
3101 nr.dwUsage = RESOURCEUSAGE_CONTAINER;
3102 nr.lpLocalName = NULL;
3103 nr.lpRemoteName = (LPSTR)map_w32_filename (path, NULL);
3104 nr.lpComment = NULL;
3105 nr.lpProvider = NULL;
3107 result = WNetOpenEnum (RESOURCE_GLOBALNET, RESOURCETYPE_DISK,
3108 RESOURCEUSAGE_CONNECTABLE, &nr, &henum);
3110 if (result == NO_ERROR)
3111 return henum;
3112 else
3113 return INVALID_HANDLE_VALUE;
3116 static char *
3117 read_unc_volume (HANDLE henum, char *readbuf, int size)
3119 DWORD count;
3120 int result;
3121 DWORD bufsize = 512;
3122 char *buffer;
3123 char *ptr;
3124 int dbcs_p = max_filename_mbslen () > 1;
3126 count = 1;
3127 buffer = alloca (bufsize);
3128 result = WNetEnumResource (henum, &count, buffer, &bufsize);
3129 if (result != NO_ERROR)
3130 return NULL;
3132 /* WNetEnumResource returns \\resource\share...skip forward to "share". */
3133 ptr = ((LPNETRESOURCE) buffer)->lpRemoteName;
3134 ptr += 2;
3135 if (!dbcs_p)
3136 while (*ptr && !IS_DIRECTORY_SEP (*ptr)) ptr++;
3137 else
3139 while (*ptr && !IS_DIRECTORY_SEP (*ptr))
3140 ptr = CharNextExA (file_name_codepage, ptr, 0);
3142 ptr++;
3144 strncpy (readbuf, ptr, size);
3145 return readbuf;
3148 static void
3149 close_unc_volume (HANDLE henum)
3151 if (henum != INVALID_HANDLE_VALUE)
3152 WNetCloseEnum (henum);
3155 static DWORD
3156 unc_volume_file_attributes (const char *path)
3158 HANDLE henum;
3159 DWORD attrs;
3161 henum = open_unc_volume (path);
3162 if (henum == INVALID_HANDLE_VALUE)
3163 return -1;
3165 attrs = FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_DIRECTORY;
3167 close_unc_volume (henum);
3169 return attrs;
3172 /* Ensure a network connection is authenticated. */
3173 static void
3174 logon_network_drive (const char *path)
3176 NETRESOURCE resource;
3177 char share[MAX_PATH];
3178 int n_slashes;
3179 char drive[4];
3180 UINT drvtype;
3181 char *p;
3182 int dbcs_p;
3184 if (IS_DIRECTORY_SEP (path[0]) && IS_DIRECTORY_SEP (path[1]))
3185 drvtype = DRIVE_REMOTE;
3186 else if (path[0] == '\0' || path[1] != ':')
3187 drvtype = GetDriveType (NULL);
3188 else
3190 drive[0] = path[0];
3191 drive[1] = ':';
3192 drive[2] = '\\';
3193 drive[3] = '\0';
3194 drvtype = GetDriveType (drive);
3197 /* Only logon to networked drives. */
3198 if (drvtype != DRIVE_REMOTE)
3199 return;
3201 n_slashes = 2;
3202 strncpy (share, path, MAX_PATH);
3203 /* Truncate to just server and share name. */
3204 dbcs_p = max_filename_mbslen () > 1;
3205 for (p = share + 2; *p && p < share + MAX_PATH; )
3207 if (IS_DIRECTORY_SEP (*p) && ++n_slashes > 3)
3209 *p = '\0';
3210 break;
3212 if (dbcs_p)
3213 p = CharNextExA (file_name_codepage, p, 0);
3214 else
3215 p++;
3218 resource.dwType = RESOURCETYPE_DISK;
3219 resource.lpLocalName = NULL;
3220 resource.lpRemoteName = share;
3221 resource.lpProvider = NULL;
3223 WNetAddConnection2 (&resource, NULL, NULL, CONNECT_INTERACTIVE);
3226 /* Emulate faccessat(2). */
3228 faccessat (int dirfd, const char * path, int mode, int flags)
3230 DWORD attributes;
3232 if (dirfd != AT_FDCWD
3233 && !(IS_DIRECTORY_SEP (path[0])
3234 || IS_DEVICE_SEP (path[1])))
3236 errno = EBADF;
3237 return -1;
3240 /* MSVCRT implementation of 'access' doesn't recognize D_OK, and its
3241 newer versions blow up when passed D_OK. */
3242 path = map_w32_filename (path, NULL);
3243 /* If the last element of PATH is a symlink, we need to resolve it
3244 to get the attributes of its target file. Note: any symlinks in
3245 PATH elements other than the last one are transparently resolved
3246 by GetFileAttributes below. */
3247 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0
3248 && (flags & AT_SYMLINK_NOFOLLOW) == 0)
3249 path = chase_symlinks (path);
3251 if ((attributes = GetFileAttributes (path)) == -1)
3253 DWORD w32err = GetLastError ();
3255 switch (w32err)
3257 case ERROR_INVALID_NAME:
3258 case ERROR_BAD_PATHNAME:
3259 if (is_unc_volume (path))
3261 attributes = unc_volume_file_attributes (path);
3262 if (attributes == -1)
3264 errno = EACCES;
3265 return -1;
3267 break;
3269 /* FALLTHROUGH */
3270 case ERROR_FILE_NOT_FOUND:
3271 case ERROR_BAD_NETPATH:
3272 errno = ENOENT;
3273 break;
3274 default:
3275 errno = EACCES;
3276 break;
3278 return -1;
3280 if ((mode & X_OK) != 0
3281 && !(is_exec (path) || (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0))
3283 errno = EACCES;
3284 return -1;
3286 if ((mode & W_OK) != 0 && (attributes & FILE_ATTRIBUTE_READONLY) != 0)
3288 errno = EACCES;
3289 return -1;
3291 if ((mode & D_OK) != 0 && (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
3293 errno = EACCES;
3294 return -1;
3296 return 0;
3299 /* Shadow some MSVC runtime functions to map requests for long filenames
3300 to reasonable short names if necessary. This was originally added to
3301 permit running Emacs on NT 3.1 on a FAT partition, which doesn't support
3302 long file names. */
3305 sys_chdir (const char * path)
3307 return _chdir (map_w32_filename (path, NULL));
3311 sys_chmod (const char * path, int mode)
3313 path = chase_symlinks (map_w32_filename (path, NULL));
3314 return _chmod (path, mode);
3318 sys_creat (const char * path, int mode)
3320 return _creat (map_w32_filename (path, NULL), mode);
3323 FILE *
3324 sys_fopen (const char * path, const char * mode)
3326 int fd;
3327 int oflag;
3328 const char * mode_save = mode;
3330 /* Force all file handles to be non-inheritable. This is necessary to
3331 ensure child processes don't unwittingly inherit handles that might
3332 prevent future file access. */
3334 if (mode[0] == 'r')
3335 oflag = O_RDONLY;
3336 else if (mode[0] == 'w' || mode[0] == 'a')
3337 oflag = O_WRONLY | O_CREAT | O_TRUNC;
3338 else
3339 return NULL;
3341 /* Only do simplistic option parsing. */
3342 while (*++mode)
3343 if (mode[0] == '+')
3345 oflag &= ~(O_RDONLY | O_WRONLY);
3346 oflag |= O_RDWR;
3348 else if (mode[0] == 'b')
3350 oflag &= ~O_TEXT;
3351 oflag |= O_BINARY;
3353 else if (mode[0] == 't')
3355 oflag &= ~O_BINARY;
3356 oflag |= O_TEXT;
3358 else break;
3360 fd = _open (map_w32_filename (path, NULL), oflag | _O_NOINHERIT, 0644);
3361 if (fd < 0)
3362 return NULL;
3364 return _fdopen (fd, mode_save);
3367 /* This only works on NTFS volumes, but is useful to have. */
3369 sys_link (const char * old, const char * new)
3371 HANDLE fileh;
3372 int result = -1;
3373 char oldname[MAX_PATH], newname[MAX_PATH];
3375 if (old == NULL || new == NULL)
3377 errno = ENOENT;
3378 return -1;
3381 strcpy (oldname, map_w32_filename (old, NULL));
3382 strcpy (newname, map_w32_filename (new, NULL));
3384 fileh = CreateFile (oldname, 0, 0, NULL, OPEN_EXISTING,
3385 FILE_FLAG_BACKUP_SEMANTICS, NULL);
3386 if (fileh != INVALID_HANDLE_VALUE)
3388 int wlen;
3390 /* Confusingly, the "alternate" stream name field does not apply
3391 when restoring a hard link, and instead contains the actual
3392 stream data for the link (ie. the name of the link to create).
3393 The WIN32_STREAM_ID structure before the cStreamName field is
3394 the stream header, which is then immediately followed by the
3395 stream data. */
3397 struct {
3398 WIN32_STREAM_ID wid;
3399 WCHAR wbuffer[MAX_PATH]; /* extra space for link name */
3400 } data;
3402 wlen = MultiByteToWideChar (CP_ACP, MB_PRECOMPOSED, newname, -1,
3403 data.wid.cStreamName, MAX_PATH);
3404 if (wlen > 0)
3406 LPVOID context = NULL;
3407 DWORD wbytes = 0;
3409 data.wid.dwStreamId = BACKUP_LINK;
3410 data.wid.dwStreamAttributes = 0;
3411 data.wid.Size.LowPart = wlen * sizeof (WCHAR);
3412 data.wid.Size.HighPart = 0;
3413 data.wid.dwStreamNameSize = 0;
3415 if (BackupWrite (fileh, (LPBYTE)&data,
3416 offsetof (WIN32_STREAM_ID, cStreamName)
3417 + data.wid.Size.LowPart,
3418 &wbytes, FALSE, FALSE, &context)
3419 && BackupWrite (fileh, NULL, 0, &wbytes, TRUE, FALSE, &context))
3421 /* succeeded */
3422 result = 0;
3424 else
3426 /* Should try mapping GetLastError to errno; for now just
3427 indicate a general error (eg. links not supported). */
3428 errno = EINVAL; // perhaps EMLINK?
3432 CloseHandle (fileh);
3434 else
3435 errno = ENOENT;
3437 return result;
3441 sys_mkdir (const char * path)
3443 return _mkdir (map_w32_filename (path, NULL));
3447 sys_open (const char * path, int oflag, int mode)
3449 const char* mpath = map_w32_filename (path, NULL);
3450 int res = -1;
3452 /* If possible, try to open file without _O_CREAT, to be able to
3453 write to existing hidden and system files. Force all file
3454 handles to be non-inheritable. */
3455 if ((oflag & (_O_CREAT | _O_EXCL)) != (_O_CREAT | _O_EXCL))
3456 res = _open (mpath, (oflag & ~_O_CREAT) | _O_NOINHERIT, mode);
3457 if (res < 0)
3458 res = _open (mpath, oflag | _O_NOINHERIT, mode);
3460 return res;
3463 /* Implementation of mkostemp for MS-Windows, to avoid race conditions
3464 when using mktemp.
3466 Standard algorithm for generating a temporary file name seems to be
3467 use pid or tid with a letter on the front (in place of the 6 X's)
3468 and cycle through the letters to find a unique name. We extend
3469 that to allow any reasonable character as the first of the 6 X's,
3470 so that the number of simultaneously used temporary files will be
3471 greater. */
3474 mkostemp (char * template, int flags)
3476 char * p;
3477 int i, fd = -1;
3478 unsigned uid = GetCurrentThreadId ();
3479 int save_errno = errno;
3480 static char first_char[] = "abcdefghijklmnopqrstuvwyz0123456789!%-_@#";
3482 errno = EINVAL;
3483 if (template == NULL)
3484 return -1;
3486 p = template + strlen (template);
3487 i = 5;
3488 /* replace up to the last 5 X's with uid in decimal */
3489 while (--p >= template && p[0] == 'X' && --i >= 0)
3491 p[0] = '0' + uid % 10;
3492 uid /= 10;
3495 if (i < 0 && p[0] == 'X')
3497 i = 0;
3500 p[0] = first_char[i];
3501 if ((fd = sys_open (template,
3502 flags | _O_CREAT | _O_EXCL | _O_RDWR,
3503 S_IRUSR | S_IWUSR)) >= 0
3504 || errno != EEXIST)
3506 if (fd >= 0)
3507 errno = save_errno;
3508 return fd;
3511 while (++i < sizeof (first_char));
3514 /* Template is badly formed or else we can't generate a unique name. */
3515 return -1;
3519 fchmod (int fd, mode_t mode)
3521 return 0;
3525 sys_rename_replace (const char *oldname, const char *newname, BOOL force)
3527 BOOL result;
3528 char temp[MAX_PATH];
3529 int newname_dev;
3530 int oldname_dev;
3532 /* MoveFile on Windows 95 doesn't correctly change the short file name
3533 alias in a number of circumstances (it is not easy to predict when
3534 just by looking at oldname and newname, unfortunately). In these
3535 cases, renaming through a temporary name avoids the problem.
3537 A second problem on Windows 95 is that renaming through a temp name when
3538 newname is uppercase fails (the final long name ends up in
3539 lowercase, although the short alias might be uppercase) UNLESS the
3540 long temp name is not 8.3.
3542 So, on Windows 95 we always rename through a temp name, and we make sure
3543 the temp name has a long extension to ensure correct renaming. */
3545 strcpy (temp, map_w32_filename (oldname, NULL));
3547 /* volume_info is set indirectly by map_w32_filename. */
3548 oldname_dev = volume_info.serialnum;
3550 if (os_subtype == OS_9X)
3552 char * o;
3553 char * p;
3554 int i = 0;
3556 oldname = map_w32_filename (oldname, NULL);
3557 if ((o = strrchr (oldname, '\\')))
3558 o++;
3559 else
3560 o = (char *) oldname;
3562 if ((p = strrchr (temp, '\\')))
3563 p++;
3564 else
3565 p = temp;
3569 /* Force temp name to require a manufactured 8.3 alias - this
3570 seems to make the second rename work properly. */
3571 sprintf (p, "_.%s.%u", o, i);
3572 i++;
3573 result = rename (oldname, temp);
3575 /* This loop must surely terminate! */
3576 while (result < 0 && errno == EEXIST);
3577 if (result < 0)
3578 return -1;
3581 /* If FORCE, emulate Unix behavior - newname is deleted if it already exists
3582 (at least if it is a file; don't do this for directories).
3584 Since we mustn't do this if we are just changing the case of the
3585 file name (we would end up deleting the file we are trying to
3586 rename!), we let rename detect if the destination file already
3587 exists - that way we avoid the possible pitfalls of trying to
3588 determine ourselves whether two names really refer to the same
3589 file, which is not always possible in the general case. (Consider
3590 all the permutations of shared or subst'd drives, etc.) */
3592 newname = map_w32_filename (newname, NULL);
3594 /* volume_info is set indirectly by map_w32_filename. */
3595 newname_dev = volume_info.serialnum;
3597 result = rename (temp, newname);
3599 if (result < 0 && force)
3601 DWORD w32err = GetLastError ();
3603 if (errno == EACCES
3604 && newname_dev != oldname_dev)
3606 /* The implementation of `rename' on Windows does not return
3607 errno = EXDEV when you are moving a directory to a
3608 different storage device (ex. logical disk). It returns
3609 EACCES instead. So here we handle such situations and
3610 return EXDEV. */
3611 DWORD attributes;
3613 if ((attributes = GetFileAttributes (temp)) != -1
3614 && (attributes & FILE_ATTRIBUTE_DIRECTORY))
3615 errno = EXDEV;
3617 else if (errno == EEXIST)
3619 if (_chmod (newname, 0666) != 0)
3620 return result;
3621 if (_unlink (newname) != 0)
3622 return result;
3623 result = rename (temp, newname);
3625 else if (w32err == ERROR_PRIVILEGE_NOT_HELD
3626 && is_symlink (temp))
3628 /* This is Windows prohibiting the user from creating a
3629 symlink in another place, since that requires
3630 privileges. */
3631 errno = EPERM;
3635 return result;
3639 sys_rename (char const *old, char const *new)
3641 return sys_rename_replace (old, new, TRUE);
3645 sys_rmdir (const char * path)
3647 return _rmdir (map_w32_filename (path, NULL));
3651 sys_unlink (const char * path)
3653 path = map_w32_filename (path, NULL);
3655 /* On Unix, unlink works without write permission. */
3656 _chmod (path, 0666);
3657 return _unlink (path);
3660 static FILETIME utc_base_ft;
3661 static ULONGLONG utc_base; /* In 100ns units */
3662 static int init = 0;
3664 #define FILETIME_TO_U64(result, ft) \
3665 do { \
3666 ULARGE_INTEGER uiTemp; \
3667 uiTemp.LowPart = (ft).dwLowDateTime; \
3668 uiTemp.HighPart = (ft).dwHighDateTime; \
3669 result = uiTemp.QuadPart; \
3670 } while (0)
3672 static void
3673 initialize_utc_base (void)
3675 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
3676 SYSTEMTIME st;
3678 st.wYear = 1970;
3679 st.wMonth = 1;
3680 st.wDay = 1;
3681 st.wHour = 0;
3682 st.wMinute = 0;
3683 st.wSecond = 0;
3684 st.wMilliseconds = 0;
3686 SystemTimeToFileTime (&st, &utc_base_ft);
3687 FILETIME_TO_U64 (utc_base, utc_base_ft);
3690 static time_t
3691 convert_time (FILETIME ft)
3693 ULONGLONG tmp;
3695 if (!init)
3697 initialize_utc_base ();
3698 init = 1;
3701 if (CompareFileTime (&ft, &utc_base_ft) < 0)
3702 return 0;
3704 FILETIME_TO_U64 (tmp, ft);
3705 return (time_t) ((tmp - utc_base) / 10000000L);
3708 static void
3709 convert_from_time_t (time_t time, FILETIME * pft)
3711 ULARGE_INTEGER tmp;
3713 if (!init)
3715 initialize_utc_base ();
3716 init = 1;
3719 /* time in 100ns units since 1-Jan-1601 */
3720 tmp.QuadPart = (ULONGLONG) time * 10000000L + utc_base;
3721 pft->dwHighDateTime = tmp.HighPart;
3722 pft->dwLowDateTime = tmp.LowPart;
3725 #if 0
3726 /* No reason to keep this; faking inode values either by hashing or even
3727 using the file index from GetInformationByHandle, is not perfect and
3728 so by default Emacs doesn't use the inode values on Windows.
3729 Instead, we now determine file-truename correctly (except for
3730 possible drive aliasing etc). */
3732 /* Modified version of "PJW" algorithm (see the "Dragon" compiler book). */
3733 static unsigned
3734 hashval (const unsigned char * str)
3736 unsigned h = 0;
3737 while (*str)
3739 h = (h << 4) + *str++;
3740 h ^= (h >> 28);
3742 return h;
3745 /* Return the hash value of the canonical pathname, excluding the
3746 drive/UNC header, to get a hopefully unique inode number. */
3747 static DWORD
3748 generate_inode_val (const char * name)
3750 char fullname[ MAX_PATH ];
3751 char * p;
3752 unsigned hash;
3754 /* Get the truly canonical filename, if it exists. (Note: this
3755 doesn't resolve aliasing due to subst commands, or recognize hard
3756 links. */
3757 if (!w32_get_long_filename ((char *)name, fullname, MAX_PATH))
3758 emacs_abort ();
3760 parse_root (fullname, &p);
3761 /* Normal W32 filesystems are still case insensitive. */
3762 _strlwr (p);
3763 return hashval (p);
3766 #endif
3768 static PSECURITY_DESCRIPTOR
3769 get_file_security_desc_by_handle (HANDLE h)
3771 PSECURITY_DESCRIPTOR psd = NULL;
3772 DWORD err;
3773 SECURITY_INFORMATION si = OWNER_SECURITY_INFORMATION
3774 | GROUP_SECURITY_INFORMATION /* | DACL_SECURITY_INFORMATION */ ;
3776 err = get_security_info (h, SE_FILE_OBJECT, si,
3777 NULL, NULL, NULL, NULL, &psd);
3778 if (err != ERROR_SUCCESS)
3779 return NULL;
3781 return psd;
3784 static PSECURITY_DESCRIPTOR
3785 get_file_security_desc_by_name (const char *fname)
3787 PSECURITY_DESCRIPTOR psd = NULL;
3788 DWORD sd_len, err;
3789 SECURITY_INFORMATION si = OWNER_SECURITY_INFORMATION
3790 | GROUP_SECURITY_INFORMATION /* | DACL_SECURITY_INFORMATION */ ;
3792 if (!get_file_security (fname, si, psd, 0, &sd_len))
3794 err = GetLastError ();
3795 if (err != ERROR_INSUFFICIENT_BUFFER)
3796 return NULL;
3799 psd = xmalloc (sd_len);
3800 if (!get_file_security (fname, si, psd, sd_len, &sd_len))
3802 xfree (psd);
3803 return NULL;
3806 return psd;
3809 static DWORD
3810 get_rid (PSID sid)
3812 unsigned n_subauthorities;
3814 /* Use the last sub-authority value of the RID, the relative
3815 portion of the SID, as user/group ID. */
3816 n_subauthorities = *get_sid_sub_authority_count (sid);
3817 if (n_subauthorities < 1)
3818 return 0; /* the "World" RID */
3819 return *get_sid_sub_authority (sid, n_subauthorities - 1);
3822 /* Caching SID and account values for faster lokup. */
3824 struct w32_id {
3825 unsigned rid;
3826 struct w32_id *next;
3827 char name[GNLEN+1];
3828 unsigned char sid[FLEXIBLE_ARRAY_MEMBER];
3831 static struct w32_id *w32_idlist;
3833 static int
3834 w32_cached_id (PSID sid, unsigned *id, char *name)
3836 struct w32_id *tail, *found;
3838 for (found = NULL, tail = w32_idlist; tail; tail = tail->next)
3840 if (equal_sid ((PSID)tail->sid, sid))
3842 found = tail;
3843 break;
3846 if (found)
3848 *id = found->rid;
3849 strcpy (name, found->name);
3850 return 1;
3852 else
3853 return 0;
3856 static void
3857 w32_add_to_cache (PSID sid, unsigned id, char *name)
3859 DWORD sid_len;
3860 struct w32_id *new_entry;
3862 /* We don't want to leave behind stale cache from when Emacs was
3863 dumped. */
3864 if (initialized)
3866 sid_len = get_length_sid (sid);
3867 new_entry = xmalloc (offsetof (struct w32_id, sid) + sid_len);
3868 if (new_entry)
3870 new_entry->rid = id;
3871 strcpy (new_entry->name, name);
3872 copy_sid (sid_len, (PSID)new_entry->sid, sid);
3873 new_entry->next = w32_idlist;
3874 w32_idlist = new_entry;
3879 #define UID 1
3880 #define GID 2
3882 static int
3883 get_name_and_id (PSECURITY_DESCRIPTOR psd, unsigned *id, char *nm, int what)
3885 PSID sid = NULL;
3886 BOOL dflt;
3887 SID_NAME_USE ignore;
3888 char name[UNLEN+1];
3889 DWORD name_len = sizeof (name);
3890 char domain[1024];
3891 DWORD domain_len = sizeof (domain);
3892 int use_dflt = 0;
3893 int result;
3895 if (what == UID)
3896 result = get_security_descriptor_owner (psd, &sid, &dflt);
3897 else if (what == GID)
3898 result = get_security_descriptor_group (psd, &sid, &dflt);
3899 else
3900 result = 0;
3902 if (!result || !is_valid_sid (sid))
3903 use_dflt = 1;
3904 else if (!w32_cached_id (sid, id, nm))
3906 if (!lookup_account_sid (NULL, sid, name, &name_len,
3907 domain, &domain_len, &ignore)
3908 || name_len > UNLEN+1)
3909 use_dflt = 1;
3910 else
3912 *id = get_rid (sid);
3913 strcpy (nm, name);
3914 w32_add_to_cache (sid, *id, name);
3917 return use_dflt;
3920 static void
3921 get_file_owner_and_group (PSECURITY_DESCRIPTOR psd, struct stat *st)
3923 int dflt_usr = 0, dflt_grp = 0;
3925 if (!psd)
3927 dflt_usr = 1;
3928 dflt_grp = 1;
3930 else
3932 if (get_name_and_id (psd, &st->st_uid, st->st_uname, UID))
3933 dflt_usr = 1;
3934 if (get_name_and_id (psd, &st->st_gid, st->st_gname, GID))
3935 dflt_grp = 1;
3937 /* Consider files to belong to current user/group, if we cannot get
3938 more accurate information. */
3939 if (dflt_usr)
3941 st->st_uid = dflt_passwd.pw_uid;
3942 strcpy (st->st_uname, dflt_passwd.pw_name);
3944 if (dflt_grp)
3946 st->st_gid = dflt_passwd.pw_gid;
3947 strcpy (st->st_gname, dflt_group.gr_name);
3951 /* Return non-zero if NAME is a potentially slow filesystem. */
3953 is_slow_fs (const char *name)
3955 char drive_root[4];
3956 UINT devtype;
3958 if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
3959 devtype = DRIVE_REMOTE; /* assume UNC name is remote */
3960 else if (!(strlen (name) >= 2 && IS_DEVICE_SEP (name[1])))
3961 devtype = GetDriveType (NULL); /* use root of current drive */
3962 else
3964 /* GetDriveType needs the root directory of the drive. */
3965 strncpy (drive_root, name, 2);
3966 drive_root[2] = '\\';
3967 drive_root[3] = '\0';
3968 devtype = GetDriveType (drive_root);
3970 return !(devtype == DRIVE_FIXED || devtype == DRIVE_RAMDISK);
3973 /* If this is non-zero, the caller wants accurate information about
3974 file's owner and group, which could be expensive to get. */
3975 int w32_stat_get_owner_group;
3977 /* MSVC stat function can't cope with UNC names and has other bugs, so
3978 replace it with our own. This also allows us to calculate consistent
3979 inode values and owner/group without hacks in the main Emacs code. */
3981 static int
3982 stat_worker (const char * path, struct stat * buf, int follow_symlinks)
3984 char *name, *save_name, *r;
3985 WIN32_FIND_DATA wfd;
3986 HANDLE fh;
3987 unsigned __int64 fake_inode = 0;
3988 int permission;
3989 int len;
3990 int rootdir = FALSE;
3991 PSECURITY_DESCRIPTOR psd = NULL;
3992 int is_a_symlink = 0;
3993 DWORD file_flags = FILE_FLAG_BACKUP_SEMANTICS;
3994 DWORD access_rights = 0;
3995 DWORD fattrs = 0, serialnum = 0, fs_high = 0, fs_low = 0, nlinks = 1;
3996 FILETIME ctime, atime, wtime;
3997 int dbcs_p;
3999 if (path == NULL || buf == NULL)
4001 errno = EFAULT;
4002 return -1;
4005 save_name = name = (char *) map_w32_filename (path, &path);
4006 /* Must be valid filename, no wild cards or other invalid
4007 characters. We use _mbspbrk to support multibyte strings that
4008 might look to strpbrk as if they included literal *, ?, and other
4009 characters mentioned below that are disallowed by Windows
4010 filesystems. */
4011 if (_mbspbrk (name, "*?|<>\""))
4013 errno = ENOENT;
4014 return -1;
4017 /* Remove trailing directory separator, unless name is the root
4018 directory of a drive or UNC volume in which case ensure there
4019 is a trailing separator. */
4020 len = strlen (name);
4021 name = strcpy (alloca (len + 2), name);
4023 /* Avoid a somewhat costly call to is_symlink if the filesystem
4024 doesn't support symlinks. */
4025 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
4026 is_a_symlink = is_symlink (name);
4028 /* Plan A: Open the file and get all the necessary information via
4029 the resulting handle. This solves several issues in one blow:
4031 . retrieves attributes for the target of a symlink, if needed
4032 . gets attributes of root directories and symlinks pointing to
4033 root directories, thus avoiding the need for special-casing
4034 these and detecting them by examining the file-name format
4035 . retrieves more accurate attributes (e.g., non-zero size for
4036 some directories, esp. directories that are junction points)
4037 . correctly resolves "c:/..", "/.." and similar file names
4038 . avoids run-time penalties for 99% of use cases
4040 Plan A is always tried first, unless the user asked not to (but
4041 if the file is a symlink and we need to follow links, we try Plan
4042 A even if the user asked not to).
4044 If Plan A fails, we go to Plan B (below), where various
4045 potentially expensive techniques must be used to handle "special"
4046 files such as UNC volumes etc. */
4047 if (!(NILP (Vw32_get_true_file_attributes)
4048 || (EQ (Vw32_get_true_file_attributes, Qlocal) && is_slow_fs (name)))
4049 /* Following symlinks requires getting the info by handle. */
4050 || (is_a_symlink && follow_symlinks))
4052 BY_HANDLE_FILE_INFORMATION info;
4054 if (is_a_symlink && !follow_symlinks)
4055 file_flags |= FILE_FLAG_OPEN_REPARSE_POINT;
4056 /* READ_CONTROL access rights are required to get security info
4057 by handle. But if the OS doesn't support security in the
4058 first place, we don't need to try. */
4059 if (is_windows_9x () != TRUE)
4060 access_rights |= READ_CONTROL;
4062 fh = CreateFile (name, access_rights, 0, NULL, OPEN_EXISTING,
4063 file_flags, NULL);
4064 /* If CreateFile fails with READ_CONTROL, try again with zero as
4065 access rights. */
4066 if (fh == INVALID_HANDLE_VALUE && access_rights)
4067 fh = CreateFile (name, 0, 0, NULL, OPEN_EXISTING,
4068 file_flags, NULL);
4069 if (fh == INVALID_HANDLE_VALUE)
4070 goto no_true_file_attributes;
4072 /* This is more accurate in terms of getting the correct number
4073 of links, but is quite slow (it is noticeable when Emacs is
4074 making a list of file name completions). */
4075 if (GetFileInformationByHandle (fh, &info))
4077 nlinks = info.nNumberOfLinks;
4078 /* Might as well use file index to fake inode values, but this
4079 is not guaranteed to be unique unless we keep a handle open
4080 all the time (even then there are situations where it is
4081 not unique). Reputedly, there are at most 48 bits of info
4082 (on NTFS, presumably less on FAT). */
4083 fake_inode = info.nFileIndexHigh;
4084 fake_inode <<= 32;
4085 fake_inode += info.nFileIndexLow;
4086 serialnum = info.dwVolumeSerialNumber;
4087 fs_high = info.nFileSizeHigh;
4088 fs_low = info.nFileSizeLow;
4089 ctime = info.ftCreationTime;
4090 atime = info.ftLastAccessTime;
4091 wtime = info.ftLastWriteTime;
4092 fattrs = info.dwFileAttributes;
4094 else
4096 /* We don't go to Plan B here, because it's not clear that
4097 it's a good idea. The only known use case where
4098 CreateFile succeeds, but GetFileInformationByHandle fails
4099 (with ERROR_INVALID_FUNCTION) is for character devices
4100 such as NUL, PRN, etc. For these, switching to Plan B is
4101 a net loss, because we lose the character device
4102 attribute returned by GetFileType below (FindFirstFile
4103 doesn't set that bit in the attributes), and the other
4104 fields don't make sense for character devices anyway.
4105 Emacs doesn't really care for non-file entities in the
4106 context of l?stat, so neither do we. */
4108 /* w32err is assigned so one could put a breakpoint here and
4109 examine its value, when GetFileInformationByHandle
4110 fails. */
4111 DWORD w32err = GetLastError ();
4113 switch (w32err)
4115 case ERROR_FILE_NOT_FOUND: /* can this ever happen? */
4116 errno = ENOENT;
4117 return -1;
4121 /* Test for a symlink before testing for a directory, since
4122 symlinks to directories have the directory bit set, but we
4123 don't want them to appear as directories. */
4124 if (is_a_symlink && !follow_symlinks)
4125 buf->st_mode = S_IFLNK;
4126 else if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
4127 buf->st_mode = S_IFDIR;
4128 else
4130 DWORD ftype = GetFileType (fh);
4132 switch (ftype)
4134 case FILE_TYPE_DISK:
4135 buf->st_mode = S_IFREG;
4136 break;
4137 case FILE_TYPE_PIPE:
4138 buf->st_mode = S_IFIFO;
4139 break;
4140 case FILE_TYPE_CHAR:
4141 case FILE_TYPE_UNKNOWN:
4142 default:
4143 buf->st_mode = S_IFCHR;
4146 /* We produce the fallback owner and group data, based on the
4147 current user that runs Emacs, in the following cases:
4149 . caller didn't request owner and group info
4150 . this is Windows 9X
4151 . getting security by handle failed, and we need to produce
4152 information for the target of a symlink (this is better
4153 than producing a potentially misleading info about the
4154 symlink itself)
4156 If getting security by handle fails, and we don't need to
4157 resolve symlinks, we try getting security by name. */
4158 if (!w32_stat_get_owner_group || is_windows_9x () == TRUE)
4159 get_file_owner_and_group (NULL, buf);
4160 else
4162 psd = get_file_security_desc_by_handle (fh);
4163 if (psd)
4165 get_file_owner_and_group (psd, buf);
4166 LocalFree (psd);
4168 else if (!(is_a_symlink && follow_symlinks))
4170 psd = get_file_security_desc_by_name (name);
4171 get_file_owner_and_group (psd, buf);
4172 xfree (psd);
4174 else
4175 get_file_owner_and_group (NULL, buf);
4177 CloseHandle (fh);
4179 else
4181 no_true_file_attributes:
4182 /* Plan B: Either getting a handle on the file failed, or the
4183 caller explicitly asked us to not bother making this
4184 information more accurate.
4186 Implementation note: In Plan B, we never bother to resolve
4187 symlinks, even if we got here because we tried Plan A and
4188 failed. That's because, even if the caller asked for extra
4189 precision by setting Vw32_get_true_file_attributes to t,
4190 resolving symlinks requires acquiring a file handle to the
4191 symlink, which we already know will fail. And if the user
4192 did not ask for extra precision, resolving symlinks will fly
4193 in the face of that request, since the user then wants the
4194 lightweight version of the code. */
4195 dbcs_p = max_filename_mbslen () > 1;
4196 rootdir = (path >= save_name + len - 1
4197 && (IS_DIRECTORY_SEP (*path) || *path == 0));
4199 /* If name is "c:/.." or "/.." then stat "c:/" or "/". */
4200 r = IS_DEVICE_SEP (name[1]) ? &name[2] : name;
4201 if (IS_DIRECTORY_SEP (r[0])
4202 && r[1] == '.' && r[2] == '.' && r[3] == '\0')
4203 r[1] = r[2] = '\0';
4205 /* Note: If NAME is a symlink to the root of a UNC volume
4206 (i.e. "\\SERVER"), we will not detect that here, and we will
4207 return data about the symlink as result of FindFirst below.
4208 This is unfortunate, but that marginal use case does not
4209 justify a call to chase_symlinks which would impose a penalty
4210 on all the other use cases. (We get here for symlinks to
4211 roots of UNC volumes because CreateFile above fails for them,
4212 unlike with symlinks to root directories X:\ of drives.) */
4213 if (is_unc_volume (name))
4215 fattrs = unc_volume_file_attributes (name);
4216 if (fattrs == -1)
4217 return -1;
4219 ctime = atime = wtime = utc_base_ft;
4221 else if (rootdir)
4223 if (!dbcs_p)
4225 if (!IS_DIRECTORY_SEP (name[len-1]))
4226 strcat (name, "\\");
4228 else
4230 char *end = name + len;
4231 char *n = CharPrevExA (file_name_codepage, name, end, 0);
4233 if (!IS_DIRECTORY_SEP (*n))
4234 strcat (name, "\\");
4236 if (GetDriveType (name) < 2)
4238 errno = ENOENT;
4239 return -1;
4242 fattrs = FILE_ATTRIBUTE_DIRECTORY;
4243 ctime = atime = wtime = utc_base_ft;
4245 else
4247 if (!dbcs_p)
4249 if (IS_DIRECTORY_SEP (name[len-1]))
4250 name[len - 1] = 0;
4252 else
4254 char *end = name + len;
4255 char *n = CharPrevExA (file_name_codepage, name, end, 0);
4257 if (IS_DIRECTORY_SEP (*n))
4258 *n = 0;
4261 /* (This is hacky, but helps when doing file completions on
4262 network drives.) Optimize by using information available from
4263 active readdir if possible. */
4264 len = strlen (dir_pathname);
4265 if (!dbcs_p)
4267 if (IS_DIRECTORY_SEP (dir_pathname[len-1]))
4268 len--;
4270 else
4272 char *end = dir_pathname + len;
4273 char *n = CharPrevExA (file_name_codepage, dir_pathname, end, 0);
4275 if (IS_DIRECTORY_SEP (*n))
4276 len--;
4278 if (dir_find_handle != INVALID_HANDLE_VALUE
4279 && !(is_a_symlink && follow_symlinks)
4280 && strnicmp (save_name, dir_pathname, len) == 0
4281 && IS_DIRECTORY_SEP (name[len])
4282 && xstrcasecmp (name + len + 1, dir_static.d_name) == 0)
4284 /* This was the last entry returned by readdir. */
4285 wfd = dir_find_data;
4287 else
4289 logon_network_drive (name);
4291 fh = FindFirstFile (name, &wfd);
4292 if (fh == INVALID_HANDLE_VALUE)
4294 errno = ENOENT;
4295 return -1;
4297 FindClose (fh);
4299 /* Note: if NAME is a symlink, the information we get from
4300 FindFirstFile is for the symlink, not its target. */
4301 fattrs = wfd.dwFileAttributes;
4302 ctime = wfd.ftCreationTime;
4303 atime = wfd.ftLastAccessTime;
4304 wtime = wfd.ftLastWriteTime;
4305 fs_high = wfd.nFileSizeHigh;
4306 fs_low = wfd.nFileSizeLow;
4307 fake_inode = 0;
4308 nlinks = 1;
4309 serialnum = volume_info.serialnum;
4311 if (is_a_symlink && !follow_symlinks)
4312 buf->st_mode = S_IFLNK;
4313 else if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
4314 buf->st_mode = S_IFDIR;
4315 else
4316 buf->st_mode = S_IFREG;
4318 get_file_owner_and_group (NULL, buf);
4321 #if 0
4322 /* Not sure if there is any point in this. */
4323 if (!NILP (Vw32_generate_fake_inodes))
4324 fake_inode = generate_inode_val (name);
4325 else if (fake_inode == 0)
4327 /* For want of something better, try to make everything unique. */
4328 static DWORD gen_num = 0;
4329 fake_inode = ++gen_num;
4331 #endif
4333 buf->st_ino = fake_inode;
4335 buf->st_dev = serialnum;
4336 buf->st_rdev = serialnum;
4338 buf->st_size = fs_high;
4339 buf->st_size <<= 32;
4340 buf->st_size += fs_low;
4341 buf->st_nlink = nlinks;
4343 /* Convert timestamps to Unix format. */
4344 buf->st_mtime = convert_time (wtime);
4345 buf->st_atime = convert_time (atime);
4346 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
4347 buf->st_ctime = convert_time (ctime);
4348 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
4350 /* determine rwx permissions */
4351 if (is_a_symlink && !follow_symlinks)
4352 permission = S_IREAD | S_IWRITE | S_IEXEC; /* Posix expectations */
4353 else
4355 if (fattrs & FILE_ATTRIBUTE_READONLY)
4356 permission = S_IREAD;
4357 else
4358 permission = S_IREAD | S_IWRITE;
4360 if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
4361 permission |= S_IEXEC;
4362 else if (is_exec (name))
4363 permission |= S_IEXEC;
4366 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
4368 return 0;
4372 stat (const char * path, struct stat * buf)
4374 return stat_worker (path, buf, 1);
4378 lstat (const char * path, struct stat * buf)
4380 return stat_worker (path, buf, 0);
4384 fstatat (int fd, char const *name, struct stat *st, int flags)
4386 /* Rely on a hack: an open directory is modeled as file descriptor 0.
4387 This is good enough for the current usage in Emacs, but is fragile.
4389 FIXME: Add proper support for fdopendir, fstatat, readlinkat.
4390 Gnulib does this and can serve as a model. */
4391 char fullname[MAX_PATH];
4393 if (fd != AT_FDCWD)
4395 if (_snprintf (fullname, sizeof fullname, "%s/%s", dir_pathname, name)
4396 < 0)
4398 errno = ENAMETOOLONG;
4399 return -1;
4401 name = fullname;
4404 return stat_worker (name, st, ! (flags & AT_SYMLINK_NOFOLLOW));
4407 /* Provide fstat and utime as well as stat for consistent handling of
4408 file timestamps. */
4410 fstat (int desc, struct stat * buf)
4412 HANDLE fh = (HANDLE) _get_osfhandle (desc);
4413 BY_HANDLE_FILE_INFORMATION info;
4414 unsigned __int64 fake_inode;
4415 int permission;
4417 switch (GetFileType (fh) & ~FILE_TYPE_REMOTE)
4419 case FILE_TYPE_DISK:
4420 buf->st_mode = S_IFREG;
4421 if (!GetFileInformationByHandle (fh, &info))
4423 errno = EACCES;
4424 return -1;
4426 break;
4427 case FILE_TYPE_PIPE:
4428 buf->st_mode = S_IFIFO;
4429 goto non_disk;
4430 case FILE_TYPE_CHAR:
4431 case FILE_TYPE_UNKNOWN:
4432 default:
4433 buf->st_mode = S_IFCHR;
4434 non_disk:
4435 memset (&info, 0, sizeof (info));
4436 info.dwFileAttributes = 0;
4437 info.ftCreationTime = utc_base_ft;
4438 info.ftLastAccessTime = utc_base_ft;
4439 info.ftLastWriteTime = utc_base_ft;
4442 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
4443 buf->st_mode = S_IFDIR;
4445 buf->st_nlink = info.nNumberOfLinks;
4446 /* Might as well use file index to fake inode values, but this
4447 is not guaranteed to be unique unless we keep a handle open
4448 all the time (even then there are situations where it is
4449 not unique). Reputedly, there are at most 48 bits of info
4450 (on NTFS, presumably less on FAT). */
4451 fake_inode = info.nFileIndexHigh;
4452 fake_inode <<= 32;
4453 fake_inode += info.nFileIndexLow;
4455 /* MSVC defines _ino_t to be short; other libc's might not. */
4456 if (sizeof (buf->st_ino) == 2)
4457 buf->st_ino = fake_inode ^ (fake_inode >> 16);
4458 else
4459 buf->st_ino = fake_inode;
4461 /* If the caller so requested, get the true file owner and group.
4462 Otherwise, consider the file to belong to the current user. */
4463 if (!w32_stat_get_owner_group || is_windows_9x () == TRUE)
4464 get_file_owner_and_group (NULL, buf);
4465 else
4467 PSECURITY_DESCRIPTOR psd = NULL;
4469 psd = get_file_security_desc_by_handle (fh);
4470 if (psd)
4472 get_file_owner_and_group (psd, buf);
4473 LocalFree (psd);
4475 else
4476 get_file_owner_and_group (NULL, buf);
4479 buf->st_dev = info.dwVolumeSerialNumber;
4480 buf->st_rdev = info.dwVolumeSerialNumber;
4482 buf->st_size = info.nFileSizeHigh;
4483 buf->st_size <<= 32;
4484 buf->st_size += info.nFileSizeLow;
4486 /* Convert timestamps to Unix format. */
4487 buf->st_mtime = convert_time (info.ftLastWriteTime);
4488 buf->st_atime = convert_time (info.ftLastAccessTime);
4489 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
4490 buf->st_ctime = convert_time (info.ftCreationTime);
4491 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
4493 /* determine rwx permissions */
4494 if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
4495 permission = S_IREAD;
4496 else
4497 permission = S_IREAD | S_IWRITE;
4499 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
4500 permission |= S_IEXEC;
4501 else
4503 #if 0 /* no way of knowing the filename */
4504 char * p = strrchr (name, '.');
4505 if (p != NULL &&
4506 (xstrcasecmp (p, ".exe") == 0 ||
4507 xstrcasecmp (p, ".com") == 0 ||
4508 xstrcasecmp (p, ".bat") == 0 ||
4509 xstrcasecmp (p, ".cmd") == 0))
4510 permission |= S_IEXEC;
4511 #endif
4514 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
4516 return 0;
4519 /* A version of 'utime' which handles directories as well as
4520 files. */
4523 utime (const char *name, struct utimbuf *times)
4525 struct utimbuf deftime;
4526 HANDLE fh;
4527 FILETIME mtime;
4528 FILETIME atime;
4530 if (times == NULL)
4532 deftime.modtime = deftime.actime = time (NULL);
4533 times = &deftime;
4536 /* Need write access to set times. */
4537 fh = CreateFile (name, FILE_WRITE_ATTRIBUTES,
4538 /* If NAME specifies a directory, FILE_SHARE_DELETE
4539 allows other processes to delete files inside it,
4540 while we have the directory open. */
4541 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
4542 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
4543 if (fh != INVALID_HANDLE_VALUE)
4545 convert_from_time_t (times->actime, &atime);
4546 convert_from_time_t (times->modtime, &mtime);
4547 if (!SetFileTime (fh, NULL, &atime, &mtime))
4549 CloseHandle (fh);
4550 errno = EACCES;
4551 return -1;
4553 CloseHandle (fh);
4555 else
4557 errno = EINVAL;
4558 return -1;
4560 return 0;
4564 /* Symlink-related functions. */
4565 #ifndef SYMBOLIC_LINK_FLAG_DIRECTORY
4566 #define SYMBOLIC_LINK_FLAG_DIRECTORY 0x1
4567 #endif
4570 symlink (char const *filename, char const *linkname)
4572 char linkfn[MAX_PATH], *tgtfn;
4573 DWORD flags = 0;
4574 int dir_access, filename_ends_in_slash;
4575 int dbcs_p;
4577 /* Diagnostics follows Posix as much as possible. */
4578 if (filename == NULL || linkname == NULL)
4580 errno = EFAULT;
4581 return -1;
4583 if (!*filename)
4585 errno = ENOENT;
4586 return -1;
4588 if (strlen (filename) > MAX_PATH || strlen (linkname) > MAX_PATH)
4590 errno = ENAMETOOLONG;
4591 return -1;
4594 strcpy (linkfn, map_w32_filename (linkname, NULL));
4595 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) == 0)
4597 errno = EPERM;
4598 return -1;
4601 dbcs_p = max_filename_mbslen () > 1;
4603 /* Note: since empty FILENAME was already rejected, we can safely
4604 refer to FILENAME[1]. */
4605 if (!(IS_DIRECTORY_SEP (filename[0]) || IS_DEVICE_SEP (filename[1])))
4607 /* Non-absolute FILENAME is understood as being relative to
4608 LINKNAME's directory. We need to prepend that directory to
4609 FILENAME to get correct results from faccessat below, since
4610 otherwise it will interpret FILENAME relative to the
4611 directory where the Emacs process runs. Note that
4612 make-symbolic-link always makes sure LINKNAME is a fully
4613 expanded file name. */
4614 char tem[MAX_PATH];
4615 char *p = linkfn + strlen (linkfn);
4617 if (!dbcs_p)
4619 while (p > linkfn && !IS_ANY_SEP (p[-1]))
4620 p--;
4622 else
4624 char *p1 = CharPrevExA (file_name_codepage, linkfn, p, 0);
4626 while (p > linkfn && !IS_ANY_SEP (*p1))
4628 p = p1;
4629 p1 = CharPrevExA (file_name_codepage, linkfn, p1, 0);
4632 if (p > linkfn)
4633 strncpy (tem, linkfn, p - linkfn);
4634 tem[p - linkfn] = '\0';
4635 strcat (tem, filename);
4636 dir_access = faccessat (AT_FDCWD, tem, D_OK, AT_EACCESS);
4638 else
4639 dir_access = faccessat (AT_FDCWD, filename, D_OK, AT_EACCESS);
4641 /* Since Windows distinguishes between symlinks to directories and
4642 to files, we provide a kludgy feature: if FILENAME doesn't
4643 exist, but ends in a slash, we create a symlink to directory. If
4644 FILENAME exists and is a directory, we always create a symlink to
4645 directory. */
4646 if (!dbcs_p)
4647 filename_ends_in_slash = IS_DIRECTORY_SEP (filename[strlen (filename) - 1]);
4648 else
4650 const char *end = filename + strlen (filename);
4651 const char *n = CharPrevExA (file_name_codepage, filename, end, 0);
4653 filename_ends_in_slash = IS_DIRECTORY_SEP (*n);
4655 if (dir_access == 0 || filename_ends_in_slash)
4656 flags = SYMBOLIC_LINK_FLAG_DIRECTORY;
4658 tgtfn = (char *)map_w32_filename (filename, NULL);
4659 if (filename_ends_in_slash)
4660 tgtfn[strlen (tgtfn) - 1] = '\0';
4662 errno = 0;
4663 if (!create_symbolic_link (linkfn, tgtfn, flags))
4665 /* ENOSYS is set by create_symbolic_link, when it detects that
4666 the OS doesn't support the CreateSymbolicLink API. */
4667 if (errno != ENOSYS)
4669 DWORD w32err = GetLastError ();
4671 switch (w32err)
4673 /* ERROR_SUCCESS is sometimes returned when LINKFN and
4674 TGTFN point to the same file name, go figure. */
4675 case ERROR_SUCCESS:
4676 case ERROR_FILE_EXISTS:
4677 errno = EEXIST;
4678 break;
4679 case ERROR_ACCESS_DENIED:
4680 errno = EACCES;
4681 break;
4682 case ERROR_FILE_NOT_FOUND:
4683 case ERROR_PATH_NOT_FOUND:
4684 case ERROR_BAD_NETPATH:
4685 case ERROR_INVALID_REPARSE_DATA:
4686 errno = ENOENT;
4687 break;
4688 case ERROR_DIRECTORY:
4689 errno = EISDIR;
4690 break;
4691 case ERROR_PRIVILEGE_NOT_HELD:
4692 case ERROR_NOT_ALL_ASSIGNED:
4693 errno = EPERM;
4694 break;
4695 case ERROR_DISK_FULL:
4696 errno = ENOSPC;
4697 break;
4698 default:
4699 errno = EINVAL;
4700 break;
4703 return -1;
4705 return 0;
4708 /* A quick inexpensive test of whether FILENAME identifies a file that
4709 is a symlink. Returns non-zero if it is, zero otherwise. FILENAME
4710 must already be in the normalized form returned by
4711 map_w32_filename.
4713 Note: for repeated operations on many files, it is best to test
4714 whether the underlying volume actually supports symlinks, by
4715 testing the FILE_SUPPORTS_REPARSE_POINTS bit in volume's flags, and
4716 avoid the call to this function if it doesn't. That's because the
4717 call to GetFileAttributes takes a non-negligible time, especially
4718 on non-local or removable filesystems. See stat_worker for an
4719 example of how to do that. */
4720 static int
4721 is_symlink (const char *filename)
4723 DWORD attrs;
4724 WIN32_FIND_DATA wfd;
4725 HANDLE fh;
4727 attrs = GetFileAttributes (filename);
4728 if (attrs == -1)
4730 DWORD w32err = GetLastError ();
4732 switch (w32err)
4734 case ERROR_BAD_NETPATH: /* network share, can't be a symlink */
4735 break;
4736 case ERROR_ACCESS_DENIED:
4737 errno = EACCES;
4738 break;
4739 case ERROR_FILE_NOT_FOUND:
4740 case ERROR_PATH_NOT_FOUND:
4741 default:
4742 errno = ENOENT;
4743 break;
4745 return 0;
4747 if ((attrs & FILE_ATTRIBUTE_REPARSE_POINT) == 0)
4748 return 0;
4749 logon_network_drive (filename);
4750 fh = FindFirstFile (filename, &wfd);
4751 if (fh == INVALID_HANDLE_VALUE)
4752 return 0;
4753 FindClose (fh);
4754 return (wfd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0
4755 && (wfd.dwReserved0 & IO_REPARSE_TAG_SYMLINK) == IO_REPARSE_TAG_SYMLINK;
4758 /* If NAME identifies a symbolic link, copy into BUF the file name of
4759 the symlink's target. Copy at most BUF_SIZE bytes, and do NOT
4760 null-terminate the target name, even if it fits. Return the number
4761 of bytes copied, or -1 if NAME is not a symlink or any error was
4762 encountered while resolving it. The file name copied into BUF is
4763 encoded in the current ANSI codepage. */
4764 ssize_t
4765 readlink (const char *name, char *buf, size_t buf_size)
4767 const char *path;
4768 TOKEN_PRIVILEGES privs;
4769 int restore_privs = 0;
4770 HANDLE sh;
4771 ssize_t retval;
4773 if (name == NULL)
4775 errno = EFAULT;
4776 return -1;
4778 if (!*name)
4780 errno = ENOENT;
4781 return -1;
4784 path = map_w32_filename (name, NULL);
4786 if (strlen (path) > MAX_PATH)
4788 errno = ENAMETOOLONG;
4789 return -1;
4792 errno = 0;
4793 if (is_windows_9x () == TRUE
4794 || (volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) == 0
4795 || !is_symlink (path))
4797 if (!errno)
4798 errno = EINVAL; /* not a symlink */
4799 return -1;
4802 /* Done with simple tests, now we're in for some _real_ work. */
4803 if (enable_privilege (SE_BACKUP_NAME, TRUE, &privs))
4804 restore_privs = 1;
4805 /* Implementation note: From here and onward, don't return early,
4806 since that will fail to restore the original set of privileges of
4807 the calling thread. */
4809 retval = -1; /* not too optimistic, are we? */
4811 /* Note: In the next call to CreateFile, we use zero as the 2nd
4812 argument because, when the symlink is a hidden/system file,
4813 e.g. 'C:\Users\All Users', GENERIC_READ fails with
4814 ERROR_ACCESS_DENIED. Zero seems to work just fine, both for file
4815 and directory symlinks. */
4816 sh = CreateFile (path, 0, 0, NULL, OPEN_EXISTING,
4817 FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
4818 NULL);
4819 if (sh != INVALID_HANDLE_VALUE)
4821 BYTE reparse_buf[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
4822 REPARSE_DATA_BUFFER *reparse_data = (REPARSE_DATA_BUFFER *)&reparse_buf[0];
4823 DWORD retbytes;
4825 if (!DeviceIoControl (sh, FSCTL_GET_REPARSE_POINT, NULL, 0,
4826 reparse_buf, MAXIMUM_REPARSE_DATA_BUFFER_SIZE,
4827 &retbytes, NULL))
4828 errno = EIO;
4829 else if (reparse_data->ReparseTag != IO_REPARSE_TAG_SYMLINK)
4830 errno = EINVAL;
4831 else
4833 /* Copy the link target name, in wide characters, from
4834 reparse_data, then convert it to multibyte encoding in
4835 the current locale's codepage. */
4836 WCHAR *lwname;
4837 BYTE lname[MAX_PATH];
4838 USHORT lname_len;
4839 USHORT lwname_len =
4840 reparse_data->SymbolicLinkReparseBuffer.PrintNameLength;
4841 WCHAR *lwname_src =
4842 reparse_data->SymbolicLinkReparseBuffer.PathBuffer
4843 + reparse_data->SymbolicLinkReparseBuffer.PrintNameOffset/sizeof(WCHAR);
4844 /* This updates file_name_codepage which we need below. */
4845 int dbcs_p = max_filename_mbslen () > 1;
4847 /* According to MSDN, PrintNameLength does not include the
4848 terminating null character. */
4849 lwname = alloca ((lwname_len + 1) * sizeof(WCHAR));
4850 memcpy (lwname, lwname_src, lwname_len);
4851 lwname[lwname_len/sizeof(WCHAR)] = 0; /* null-terminate */
4853 lname_len = WideCharToMultiByte (file_name_codepage, 0, lwname, -1,
4854 lname, MAX_PATH, NULL, NULL);
4855 if (!lname_len)
4857 /* WideCharToMultiByte failed. */
4858 DWORD w32err1 = GetLastError ();
4860 switch (w32err1)
4862 case ERROR_INSUFFICIENT_BUFFER:
4863 errno = ENAMETOOLONG;
4864 break;
4865 case ERROR_INVALID_PARAMETER:
4866 errno = EFAULT;
4867 break;
4868 case ERROR_NO_UNICODE_TRANSLATION:
4869 errno = ENOENT;
4870 break;
4871 default:
4872 errno = EINVAL;
4873 break;
4876 else
4878 size_t size_to_copy = buf_size;
4879 BYTE *p = lname, *p2;
4880 BYTE *pend = p + lname_len;
4882 /* Normalize like dostounix_filename does, but we don't
4883 want to assume that lname is null-terminated. */
4884 if (dbcs_p)
4885 p2 = CharNextExA (file_name_codepage, p, 0);
4886 else
4887 p2 = p + 1;
4888 if (*p && *p2 == ':' && *p >= 'A' && *p <= 'Z')
4890 *p += 'a' - 'A';
4891 p += 2;
4893 while (p <= pend)
4895 if (*p == '\\')
4896 *p = '/';
4897 if (dbcs_p)
4899 p = CharNextExA (file_name_codepage, p, 0);
4900 /* CharNextExA doesn't advance at null character. */
4901 if (!*p)
4902 break;
4904 else
4905 ++p;
4907 /* Testing for null-terminated LNAME is paranoia:
4908 WideCharToMultiByte should always return a
4909 null-terminated string when its 4th argument is -1
4910 and its 3rd argument is null-terminated (which they
4911 are, see above). */
4912 if (lname[lname_len - 1] == '\0')
4913 lname_len--;
4914 if (lname_len <= buf_size)
4915 size_to_copy = lname_len;
4916 strncpy (buf, lname, size_to_copy);
4917 /* Success! */
4918 retval = size_to_copy;
4921 CloseHandle (sh);
4923 else
4925 /* CreateFile failed. */
4926 DWORD w32err2 = GetLastError ();
4928 switch (w32err2)
4930 case ERROR_FILE_NOT_FOUND:
4931 case ERROR_PATH_NOT_FOUND:
4932 errno = ENOENT;
4933 break;
4934 case ERROR_ACCESS_DENIED:
4935 case ERROR_TOO_MANY_OPEN_FILES:
4936 errno = EACCES;
4937 break;
4938 default:
4939 errno = EPERM;
4940 break;
4943 if (restore_privs)
4945 restore_privilege (&privs);
4946 revert_to_self ();
4949 return retval;
4952 ssize_t
4953 readlinkat (int fd, char const *name, char *buffer,
4954 size_t buffer_size)
4956 /* Rely on a hack: an open directory is modeled as file descriptor 0,
4957 as in fstatat. FIXME: Add proper support for readlinkat. */
4958 char fullname[MAX_PATH];
4960 if (fd != AT_FDCWD)
4962 if (_snprintf (fullname, sizeof fullname, "%s/%s", dir_pathname, name)
4963 < 0)
4965 errno = ENAMETOOLONG;
4966 return -1;
4968 name = fullname;
4971 return readlink (name, buffer, buffer_size);
4974 /* If FILE is a symlink, return its target (stored in a static
4975 buffer); otherwise return FILE.
4977 This function repeatedly resolves symlinks in the last component of
4978 a chain of symlink file names, as in foo -> bar -> baz -> ...,
4979 until it arrives at a file whose last component is not a symlink,
4980 or some error occurs. It returns the target of the last
4981 successfully resolved symlink in the chain. If it succeeds to
4982 resolve even a single symlink, the value returned is an absolute
4983 file name with backslashes (result of GetFullPathName). By
4984 contrast, if the original FILE is returned, it is unaltered.
4986 Note: This function can set errno even if it succeeds.
4988 Implementation note: we only resolve the last portion ("basename")
4989 of the argument FILE and of each following file in the chain,
4990 disregarding any possible symlinks in its leading directories.
4991 This is because Windows system calls and library functions
4992 transparently resolve symlinks in leading directories and return
4993 correct information, as long as the basename is not a symlink. */
4994 static char *
4995 chase_symlinks (const char *file)
4997 static char target[MAX_PATH];
4998 char link[MAX_PATH];
4999 ssize_t res, link_len;
5000 int loop_count = 0;
5001 int dbcs_p;
5003 if (is_windows_9x () == TRUE || !is_symlink (file))
5004 return (char *)file;
5006 if ((link_len = GetFullPathName (file, MAX_PATH, link, NULL)) == 0)
5007 return (char *)file;
5009 dbcs_p = max_filename_mbslen () > 1;
5010 target[0] = '\0';
5011 do {
5013 /* Remove trailing slashes, as we want to resolve the last
5014 non-trivial part of the link name. */
5015 if (!dbcs_p)
5017 while (link_len > 3 && IS_DIRECTORY_SEP (link[link_len-1]))
5018 link[link_len--] = '\0';
5020 else if (link_len > 3)
5022 char *n = CharPrevExA (file_name_codepage, link, link + link_len, 0);
5024 while (n >= link + 2 && IS_DIRECTORY_SEP (*n))
5026 n[1] = '\0';
5027 n = CharPrevExA (file_name_codepage, link, n, 0);
5031 res = readlink (link, target, MAX_PATH);
5032 if (res > 0)
5034 target[res] = '\0';
5035 if (!(IS_DEVICE_SEP (target[1])
5036 || (IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1]))))
5038 /* Target is relative. Append it to the directory part of
5039 the symlink, then copy the result back to target. */
5040 char *p = link + link_len;
5042 if (!dbcs_p)
5044 while (p > link && !IS_ANY_SEP (p[-1]))
5045 p--;
5047 else
5049 char *p1 = CharPrevExA (file_name_codepage, link, p, 0);
5051 while (p > link && !IS_ANY_SEP (*p1))
5053 p = p1;
5054 p1 = CharPrevExA (file_name_codepage, link, p1, 0);
5057 strcpy (p, target);
5058 strcpy (target, link);
5060 /* Resolve any "." and ".." to get a fully-qualified file name
5061 in link[] again. */
5062 link_len = GetFullPathName (target, MAX_PATH, link, NULL);
5064 } while (res > 0 && link_len > 0 && ++loop_count <= 100);
5066 if (loop_count > 100)
5067 errno = ELOOP;
5069 if (target[0] == '\0') /* not a single call to readlink succeeded */
5070 return (char *)file;
5071 return target;
5075 /* Posix ACL emulation. */
5078 acl_valid (acl_t acl)
5080 return is_valid_security_descriptor ((PSECURITY_DESCRIPTOR)acl) ? 0 : -1;
5083 char *
5084 acl_to_text (acl_t acl, ssize_t *size)
5086 LPTSTR str_acl;
5087 SECURITY_INFORMATION flags =
5088 OWNER_SECURITY_INFORMATION |
5089 GROUP_SECURITY_INFORMATION |
5090 DACL_SECURITY_INFORMATION;
5091 char *retval = NULL;
5092 ULONG local_size;
5093 int e = errno;
5095 errno = 0;
5097 if (convert_sd_to_sddl ((PSECURITY_DESCRIPTOR)acl, SDDL_REVISION_1, flags, &str_acl, &local_size))
5099 errno = e;
5100 /* We don't want to mix heaps, so we duplicate the string in our
5101 heap and free the one allocated by the API. */
5102 retval = xstrdup (str_acl);
5103 if (size)
5104 *size = local_size;
5105 LocalFree (str_acl);
5107 else if (errno != ENOTSUP)
5108 errno = EINVAL;
5110 return retval;
5113 acl_t
5114 acl_from_text (const char *acl_str)
5116 PSECURITY_DESCRIPTOR psd, retval = NULL;
5117 ULONG sd_size;
5118 int e = errno;
5120 errno = 0;
5122 if (convert_sddl_to_sd (acl_str, SDDL_REVISION_1, &psd, &sd_size))
5124 errno = e;
5125 retval = xmalloc (sd_size);
5126 memcpy (retval, psd, sd_size);
5127 LocalFree (psd);
5129 else if (errno != ENOTSUP)
5130 errno = EINVAL;
5132 return retval;
5136 acl_free (void *ptr)
5138 xfree (ptr);
5139 return 0;
5142 acl_t
5143 acl_get_file (const char *fname, acl_type_t type)
5145 PSECURITY_DESCRIPTOR psd = NULL;
5146 const char *filename;
5148 if (type == ACL_TYPE_ACCESS)
5150 DWORD sd_len, err;
5151 SECURITY_INFORMATION si =
5152 OWNER_SECURITY_INFORMATION |
5153 GROUP_SECURITY_INFORMATION |
5154 DACL_SECURITY_INFORMATION ;
5155 int e = errno;
5157 filename = map_w32_filename (fname, NULL);
5158 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
5159 fname = chase_symlinks (filename);
5160 else
5161 fname = filename;
5163 errno = 0;
5164 if (!get_file_security (fname, si, psd, 0, &sd_len)
5165 && errno != ENOTSUP)
5167 err = GetLastError ();
5168 if (err == ERROR_INSUFFICIENT_BUFFER)
5170 psd = xmalloc (sd_len);
5171 if (!get_file_security (fname, si, psd, sd_len, &sd_len))
5173 xfree (psd);
5174 errno = EIO;
5175 psd = NULL;
5178 else if (err == ERROR_FILE_NOT_FOUND
5179 || err == ERROR_PATH_NOT_FOUND)
5180 errno = ENOENT;
5181 else
5182 errno = EIO;
5184 else if (!errno)
5185 errno = e;
5187 else if (type != ACL_TYPE_DEFAULT)
5188 errno = EINVAL;
5190 return psd;
5194 acl_set_file (const char *fname, acl_type_t type, acl_t acl)
5196 TOKEN_PRIVILEGES old1, old2;
5197 DWORD err;
5198 int st = 0, retval = -1;
5199 SECURITY_INFORMATION flags = 0;
5200 PSID psid;
5201 PACL pacl;
5202 BOOL dflt;
5203 BOOL dacl_present;
5204 int e;
5205 const char *filename;
5207 if (acl_valid (acl) != 0
5208 || (type != ACL_TYPE_DEFAULT && type != ACL_TYPE_ACCESS))
5210 errno = EINVAL;
5211 return -1;
5214 if (type == ACL_TYPE_DEFAULT)
5216 errno = ENOSYS;
5217 return -1;
5220 filename = map_w32_filename (fname, NULL);
5221 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
5222 fname = chase_symlinks (filename);
5223 else
5224 fname = filename;
5226 if (get_security_descriptor_owner ((PSECURITY_DESCRIPTOR)acl, &psid, &dflt)
5227 && psid)
5228 flags |= OWNER_SECURITY_INFORMATION;
5229 if (get_security_descriptor_group ((PSECURITY_DESCRIPTOR)acl, &psid, &dflt)
5230 && psid)
5231 flags |= GROUP_SECURITY_INFORMATION;
5232 if (get_security_descriptor_dacl ((PSECURITY_DESCRIPTOR)acl, &dacl_present,
5233 &pacl, &dflt)
5234 && dacl_present)
5235 flags |= DACL_SECURITY_INFORMATION;
5236 if (!flags)
5237 return 0;
5239 /* According to KB-245153, setting the owner will succeed if either:
5240 (1) the caller is the user who will be the new owner, and has the
5241 SE_TAKE_OWNERSHIP privilege, or
5242 (2) the caller has the SE_RESTORE privilege, in which case she can
5243 set any valid user or group as the owner
5245 We request below both SE_TAKE_OWNERSHIP and SE_RESTORE
5246 privileges, and disregard any failures in obtaining them. If
5247 these privileges cannot be obtained, and do not already exist in
5248 the calling thread's security token, this function could fail
5249 with EPERM. */
5250 if (enable_privilege (SE_TAKE_OWNERSHIP_NAME, TRUE, &old1))
5251 st++;
5252 if (enable_privilege (SE_RESTORE_NAME, TRUE, &old2))
5253 st++;
5255 e = errno;
5256 errno = 0;
5257 if (!set_file_security ((char *)fname, flags, (PSECURITY_DESCRIPTOR)acl))
5259 err = GetLastError ();
5261 if (errno == ENOTSUP)
5263 else if (err == ERROR_INVALID_OWNER
5264 || err == ERROR_NOT_ALL_ASSIGNED
5265 || err == ERROR_ACCESS_DENIED)
5267 /* Maybe the requested ACL and the one the file already has
5268 are identical, in which case we can silently ignore the
5269 failure. (And no, Windows doesn't.) */
5270 acl_t current_acl = acl_get_file (fname, ACL_TYPE_ACCESS);
5272 errno = EPERM;
5273 if (current_acl)
5275 char *acl_from = acl_to_text (current_acl, NULL);
5276 char *acl_to = acl_to_text (acl, NULL);
5278 if (acl_from && acl_to && xstrcasecmp (acl_from, acl_to) == 0)
5280 retval = 0;
5281 errno = e;
5283 if (acl_from)
5284 acl_free (acl_from);
5285 if (acl_to)
5286 acl_free (acl_to);
5287 acl_free (current_acl);
5290 else if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
5291 errno = ENOENT;
5292 else
5293 errno = EACCES;
5295 else
5297 retval = 0;
5298 errno = e;
5301 if (st)
5303 if (st >= 2)
5304 restore_privilege (&old2);
5305 restore_privilege (&old1);
5306 revert_to_self ();
5309 return retval;
5313 /* MS-Windows version of careadlinkat (cf. ../lib/careadlinkat.c). We
5314 have a fixed max size for file names, so we don't need the kind of
5315 alloc/malloc/realloc dance the gnulib version does. We also don't
5316 support FD-relative symlinks. */
5317 char *
5318 careadlinkat (int fd, char const *filename,
5319 char *buffer, size_t buffer_size,
5320 struct allocator const *alloc,
5321 ssize_t (*preadlinkat) (int, char const *, char *, size_t))
5323 char linkname[MAX_PATH];
5324 ssize_t link_size;
5326 link_size = preadlinkat (fd, filename, linkname, sizeof(linkname));
5328 if (link_size > 0)
5330 char *retval = buffer;
5332 linkname[link_size++] = '\0';
5333 if (link_size > buffer_size)
5334 retval = (char *)(alloc ? alloc->allocate : xmalloc) (link_size);
5335 if (retval)
5336 memcpy (retval, linkname, link_size);
5338 return retval;
5340 return NULL;
5344 /* Support for browsing other processes and their attributes. See
5345 process.c for the Lisp bindings. */
5347 /* Helper wrapper functions. */
5349 static HANDLE WINAPI
5350 create_toolhelp32_snapshot (DWORD Flags, DWORD Ignored)
5352 static CreateToolhelp32Snapshot_Proc s_pfn_Create_Toolhelp32_Snapshot = NULL;
5354 if (g_b_init_create_toolhelp32_snapshot == 0)
5356 g_b_init_create_toolhelp32_snapshot = 1;
5357 s_pfn_Create_Toolhelp32_Snapshot = (CreateToolhelp32Snapshot_Proc)
5358 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5359 "CreateToolhelp32Snapshot");
5361 if (s_pfn_Create_Toolhelp32_Snapshot == NULL)
5363 return INVALID_HANDLE_VALUE;
5365 return (s_pfn_Create_Toolhelp32_Snapshot (Flags, Ignored));
5368 static BOOL WINAPI
5369 process32_first (HANDLE hSnapshot, LPPROCESSENTRY32 lppe)
5371 static Process32First_Proc s_pfn_Process32_First = NULL;
5373 if (g_b_init_process32_first == 0)
5375 g_b_init_process32_first = 1;
5376 s_pfn_Process32_First = (Process32First_Proc)
5377 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5378 "Process32First");
5380 if (s_pfn_Process32_First == NULL)
5382 return FALSE;
5384 return (s_pfn_Process32_First (hSnapshot, lppe));
5387 static BOOL WINAPI
5388 process32_next (HANDLE hSnapshot, LPPROCESSENTRY32 lppe)
5390 static Process32Next_Proc s_pfn_Process32_Next = NULL;
5392 if (g_b_init_process32_next == 0)
5394 g_b_init_process32_next = 1;
5395 s_pfn_Process32_Next = (Process32Next_Proc)
5396 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5397 "Process32Next");
5399 if (s_pfn_Process32_Next == NULL)
5401 return FALSE;
5403 return (s_pfn_Process32_Next (hSnapshot, lppe));
5406 static BOOL WINAPI
5407 open_thread_token (HANDLE ThreadHandle,
5408 DWORD DesiredAccess,
5409 BOOL OpenAsSelf,
5410 PHANDLE TokenHandle)
5412 static OpenThreadToken_Proc s_pfn_Open_Thread_Token = NULL;
5413 HMODULE hm_advapi32 = NULL;
5414 if (is_windows_9x () == TRUE)
5416 SetLastError (ERROR_NOT_SUPPORTED);
5417 return FALSE;
5419 if (g_b_init_open_thread_token == 0)
5421 g_b_init_open_thread_token = 1;
5422 hm_advapi32 = LoadLibrary ("Advapi32.dll");
5423 s_pfn_Open_Thread_Token =
5424 (OpenThreadToken_Proc) GetProcAddress (hm_advapi32, "OpenThreadToken");
5426 if (s_pfn_Open_Thread_Token == NULL)
5428 SetLastError (ERROR_NOT_SUPPORTED);
5429 return FALSE;
5431 return (
5432 s_pfn_Open_Thread_Token (
5433 ThreadHandle,
5434 DesiredAccess,
5435 OpenAsSelf,
5436 TokenHandle)
5440 static BOOL WINAPI
5441 impersonate_self (SECURITY_IMPERSONATION_LEVEL ImpersonationLevel)
5443 static ImpersonateSelf_Proc s_pfn_Impersonate_Self = NULL;
5444 HMODULE hm_advapi32 = NULL;
5445 if (is_windows_9x () == TRUE)
5447 return FALSE;
5449 if (g_b_init_impersonate_self == 0)
5451 g_b_init_impersonate_self = 1;
5452 hm_advapi32 = LoadLibrary ("Advapi32.dll");
5453 s_pfn_Impersonate_Self =
5454 (ImpersonateSelf_Proc) GetProcAddress (hm_advapi32, "ImpersonateSelf");
5456 if (s_pfn_Impersonate_Self == NULL)
5458 return FALSE;
5460 return s_pfn_Impersonate_Self (ImpersonationLevel);
5463 static BOOL WINAPI
5464 revert_to_self (void)
5466 static RevertToSelf_Proc s_pfn_Revert_To_Self = NULL;
5467 HMODULE hm_advapi32 = NULL;
5468 if (is_windows_9x () == TRUE)
5470 return FALSE;
5472 if (g_b_init_revert_to_self == 0)
5474 g_b_init_revert_to_self = 1;
5475 hm_advapi32 = LoadLibrary ("Advapi32.dll");
5476 s_pfn_Revert_To_Self =
5477 (RevertToSelf_Proc) GetProcAddress (hm_advapi32, "RevertToSelf");
5479 if (s_pfn_Revert_To_Self == NULL)
5481 return FALSE;
5483 return s_pfn_Revert_To_Self ();
5486 static BOOL WINAPI
5487 get_process_memory_info (HANDLE h_proc,
5488 PPROCESS_MEMORY_COUNTERS mem_counters,
5489 DWORD bufsize)
5491 static GetProcessMemoryInfo_Proc s_pfn_Get_Process_Memory_Info = NULL;
5492 HMODULE hm_psapi = NULL;
5493 if (is_windows_9x () == TRUE)
5495 return FALSE;
5497 if (g_b_init_get_process_memory_info == 0)
5499 g_b_init_get_process_memory_info = 1;
5500 hm_psapi = LoadLibrary ("Psapi.dll");
5501 if (hm_psapi)
5502 s_pfn_Get_Process_Memory_Info = (GetProcessMemoryInfo_Proc)
5503 GetProcAddress (hm_psapi, "GetProcessMemoryInfo");
5505 if (s_pfn_Get_Process_Memory_Info == NULL)
5507 return FALSE;
5509 return s_pfn_Get_Process_Memory_Info (h_proc, mem_counters, bufsize);
5512 static BOOL WINAPI
5513 get_process_working_set_size (HANDLE h_proc,
5514 PSIZE_T minrss,
5515 PSIZE_T maxrss)
5517 static GetProcessWorkingSetSize_Proc
5518 s_pfn_Get_Process_Working_Set_Size = NULL;
5520 if (is_windows_9x () == TRUE)
5522 return FALSE;
5524 if (g_b_init_get_process_working_set_size == 0)
5526 g_b_init_get_process_working_set_size = 1;
5527 s_pfn_Get_Process_Working_Set_Size = (GetProcessWorkingSetSize_Proc)
5528 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5529 "GetProcessWorkingSetSize");
5531 if (s_pfn_Get_Process_Working_Set_Size == NULL)
5533 return FALSE;
5535 return s_pfn_Get_Process_Working_Set_Size (h_proc, minrss, maxrss);
5538 static BOOL WINAPI
5539 global_memory_status (MEMORYSTATUS *buf)
5541 static GlobalMemoryStatus_Proc s_pfn_Global_Memory_Status = NULL;
5543 if (is_windows_9x () == TRUE)
5545 return FALSE;
5547 if (g_b_init_global_memory_status == 0)
5549 g_b_init_global_memory_status = 1;
5550 s_pfn_Global_Memory_Status = (GlobalMemoryStatus_Proc)
5551 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5552 "GlobalMemoryStatus");
5554 if (s_pfn_Global_Memory_Status == NULL)
5556 return FALSE;
5558 return s_pfn_Global_Memory_Status (buf);
5561 static BOOL WINAPI
5562 global_memory_status_ex (MEMORY_STATUS_EX *buf)
5564 static GlobalMemoryStatusEx_Proc s_pfn_Global_Memory_Status_Ex = NULL;
5566 if (is_windows_9x () == TRUE)
5568 return FALSE;
5570 if (g_b_init_global_memory_status_ex == 0)
5572 g_b_init_global_memory_status_ex = 1;
5573 s_pfn_Global_Memory_Status_Ex = (GlobalMemoryStatusEx_Proc)
5574 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5575 "GlobalMemoryStatusEx");
5577 if (s_pfn_Global_Memory_Status_Ex == NULL)
5579 return FALSE;
5581 return s_pfn_Global_Memory_Status_Ex (buf);
5584 Lisp_Object
5585 list_system_processes (void)
5587 struct gcpro gcpro1;
5588 Lisp_Object proclist = Qnil;
5589 HANDLE h_snapshot;
5591 h_snapshot = create_toolhelp32_snapshot (TH32CS_SNAPPROCESS, 0);
5593 if (h_snapshot != INVALID_HANDLE_VALUE)
5595 PROCESSENTRY32 proc_entry;
5596 DWORD proc_id;
5597 BOOL res;
5599 GCPRO1 (proclist);
5601 proc_entry.dwSize = sizeof (PROCESSENTRY32);
5602 for (res = process32_first (h_snapshot, &proc_entry); res;
5603 res = process32_next (h_snapshot, &proc_entry))
5605 proc_id = proc_entry.th32ProcessID;
5606 proclist = Fcons (make_fixnum_or_float (proc_id), proclist);
5609 CloseHandle (h_snapshot);
5610 UNGCPRO;
5611 proclist = Fnreverse (proclist);
5614 return proclist;
5617 static int
5618 enable_privilege (LPCTSTR priv_name, BOOL enable_p, TOKEN_PRIVILEGES *old_priv)
5620 TOKEN_PRIVILEGES priv;
5621 DWORD priv_size = sizeof (priv);
5622 DWORD opriv_size = sizeof (*old_priv);
5623 HANDLE h_token = NULL;
5624 HANDLE h_thread = GetCurrentThread ();
5625 int ret_val = 0;
5626 BOOL res;
5628 res = open_thread_token (h_thread,
5629 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
5630 FALSE, &h_token);
5631 if (!res && GetLastError () == ERROR_NO_TOKEN)
5633 if (impersonate_self (SecurityImpersonation))
5634 res = open_thread_token (h_thread,
5635 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
5636 FALSE, &h_token);
5638 if (res)
5640 priv.PrivilegeCount = 1;
5641 priv.Privileges[0].Attributes = enable_p ? SE_PRIVILEGE_ENABLED : 0;
5642 LookupPrivilegeValue (NULL, priv_name, &priv.Privileges[0].Luid);
5643 if (AdjustTokenPrivileges (h_token, FALSE, &priv, priv_size,
5644 old_priv, &opriv_size)
5645 && GetLastError () != ERROR_NOT_ALL_ASSIGNED)
5646 ret_val = 1;
5648 if (h_token)
5649 CloseHandle (h_token);
5651 return ret_val;
5654 static int
5655 restore_privilege (TOKEN_PRIVILEGES *priv)
5657 DWORD priv_size = sizeof (*priv);
5658 HANDLE h_token = NULL;
5659 int ret_val = 0;
5661 if (open_thread_token (GetCurrentThread (),
5662 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
5663 FALSE, &h_token))
5665 if (AdjustTokenPrivileges (h_token, FALSE, priv, priv_size, NULL, NULL)
5666 && GetLastError () != ERROR_NOT_ALL_ASSIGNED)
5667 ret_val = 1;
5669 if (h_token)
5670 CloseHandle (h_token);
5672 return ret_val;
5675 static Lisp_Object
5676 ltime (ULONGLONG time_100ns)
5678 ULONGLONG time_sec = time_100ns / 10000000;
5679 int subsec = time_100ns % 10000000;
5680 return list4i (time_sec >> 16, time_sec & 0xffff,
5681 subsec / 10, subsec % 10 * 100000);
5684 #define U64_TO_LISP_TIME(time) ltime (time)
5686 static int
5687 process_times (HANDLE h_proc, Lisp_Object *ctime, Lisp_Object *etime,
5688 Lisp_Object *stime, Lisp_Object *utime, Lisp_Object *ttime,
5689 double *pcpu)
5691 FILETIME ft_creation, ft_exit, ft_kernel, ft_user, ft_current;
5692 ULONGLONG tem1, tem2, tem3, tem;
5694 if (!h_proc
5695 || !get_process_times_fn
5696 || !(*get_process_times_fn) (h_proc, &ft_creation, &ft_exit,
5697 &ft_kernel, &ft_user))
5698 return 0;
5700 GetSystemTimeAsFileTime (&ft_current);
5702 FILETIME_TO_U64 (tem1, ft_kernel);
5703 *stime = U64_TO_LISP_TIME (tem1);
5705 FILETIME_TO_U64 (tem2, ft_user);
5706 *utime = U64_TO_LISP_TIME (tem2);
5708 tem3 = tem1 + tem2;
5709 *ttime = U64_TO_LISP_TIME (tem3);
5711 FILETIME_TO_U64 (tem, ft_creation);
5712 /* Process no 4 (System) returns zero creation time. */
5713 if (tem)
5714 tem -= utc_base;
5715 *ctime = U64_TO_LISP_TIME (tem);
5717 if (tem)
5719 FILETIME_TO_U64 (tem3, ft_current);
5720 tem = (tem3 - utc_base) - tem;
5722 *etime = U64_TO_LISP_TIME (tem);
5724 if (tem)
5726 *pcpu = 100.0 * (tem1 + tem2) / tem;
5727 if (*pcpu > 100)
5728 *pcpu = 100.0;
5730 else
5731 *pcpu = 0;
5733 return 1;
5736 Lisp_Object
5737 system_process_attributes (Lisp_Object pid)
5739 struct gcpro gcpro1, gcpro2, gcpro3;
5740 Lisp_Object attrs = Qnil;
5741 Lisp_Object cmd_str, decoded_cmd, tem;
5742 HANDLE h_snapshot, h_proc;
5743 DWORD proc_id;
5744 int found_proc = 0;
5745 char uname[UNLEN+1], gname[GNLEN+1], domain[1025];
5746 DWORD ulength = sizeof (uname), dlength = sizeof (domain), needed;
5747 DWORD glength = sizeof (gname);
5748 HANDLE token = NULL;
5749 SID_NAME_USE user_type;
5750 unsigned char *buf = NULL;
5751 DWORD blen = 0;
5752 TOKEN_USER user_token;
5753 TOKEN_PRIMARY_GROUP group_token;
5754 unsigned euid;
5755 unsigned egid;
5756 PROCESS_MEMORY_COUNTERS mem;
5757 PROCESS_MEMORY_COUNTERS_EX mem_ex;
5758 SIZE_T minrss, maxrss;
5759 MEMORYSTATUS memst;
5760 MEMORY_STATUS_EX memstex;
5761 double totphys = 0.0;
5762 Lisp_Object ctime, stime, utime, etime, ttime;
5763 double pcpu;
5764 BOOL result = FALSE;
5766 CHECK_NUMBER_OR_FLOAT (pid);
5767 proc_id = FLOATP (pid) ? XFLOAT_DATA (pid) : XINT (pid);
5769 h_snapshot = create_toolhelp32_snapshot (TH32CS_SNAPPROCESS, 0);
5771 GCPRO3 (attrs, decoded_cmd, tem);
5773 if (h_snapshot != INVALID_HANDLE_VALUE)
5775 PROCESSENTRY32 pe;
5776 BOOL res;
5778 pe.dwSize = sizeof (PROCESSENTRY32);
5779 for (res = process32_first (h_snapshot, &pe); res;
5780 res = process32_next (h_snapshot, &pe))
5782 if (proc_id == pe.th32ProcessID)
5784 if (proc_id == 0)
5785 decoded_cmd = build_string ("Idle");
5786 else
5788 /* Decode the command name from locale-specific
5789 encoding. */
5790 cmd_str = build_unibyte_string (pe.szExeFile);
5792 decoded_cmd =
5793 code_convert_string_norecord (cmd_str,
5794 Vlocale_coding_system, 0);
5796 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
5797 attrs = Fcons (Fcons (Qppid,
5798 make_fixnum_or_float (pe.th32ParentProcessID)),
5799 attrs);
5800 attrs = Fcons (Fcons (Qpri, make_number (pe.pcPriClassBase)),
5801 attrs);
5802 attrs = Fcons (Fcons (Qthcount,
5803 make_fixnum_or_float (pe.cntThreads)),
5804 attrs);
5805 found_proc = 1;
5806 break;
5810 CloseHandle (h_snapshot);
5813 if (!found_proc)
5815 UNGCPRO;
5816 return Qnil;
5819 h_proc = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
5820 FALSE, proc_id);
5821 /* If we were denied a handle to the process, try again after
5822 enabling the SeDebugPrivilege in our process. */
5823 if (!h_proc)
5825 TOKEN_PRIVILEGES priv_current;
5827 if (enable_privilege (SE_DEBUG_NAME, TRUE, &priv_current))
5829 h_proc = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
5830 FALSE, proc_id);
5831 restore_privilege (&priv_current);
5832 revert_to_self ();
5835 if (h_proc)
5837 result = open_process_token (h_proc, TOKEN_QUERY, &token);
5838 if (result)
5840 result = get_token_information (token, TokenUser, NULL, 0, &blen);
5841 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
5843 buf = xmalloc (blen);
5844 result = get_token_information (token, TokenUser,
5845 (LPVOID)buf, blen, &needed);
5846 if (result)
5848 memcpy (&user_token, buf, sizeof (user_token));
5849 if (!w32_cached_id (user_token.User.Sid, &euid, uname))
5851 euid = get_rid (user_token.User.Sid);
5852 result = lookup_account_sid (NULL, user_token.User.Sid,
5853 uname, &ulength,
5854 domain, &dlength,
5855 &user_type);
5856 if (result)
5857 w32_add_to_cache (user_token.User.Sid, euid, uname);
5858 else
5860 strcpy (uname, "unknown");
5861 result = TRUE;
5864 ulength = strlen (uname);
5868 if (result)
5870 /* Determine a reasonable euid and gid values. */
5871 if (xstrcasecmp ("administrator", uname) == 0)
5873 euid = 500; /* well-known Administrator uid */
5874 egid = 513; /* well-known None gid */
5876 else
5878 /* Get group id and name. */
5879 result = get_token_information (token, TokenPrimaryGroup,
5880 (LPVOID)buf, blen, &needed);
5881 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
5883 buf = xrealloc (buf, blen = needed);
5884 result = get_token_information (token, TokenPrimaryGroup,
5885 (LPVOID)buf, blen, &needed);
5887 if (result)
5889 memcpy (&group_token, buf, sizeof (group_token));
5890 if (!w32_cached_id (group_token.PrimaryGroup, &egid, gname))
5892 egid = get_rid (group_token.PrimaryGroup);
5893 dlength = sizeof (domain);
5894 result =
5895 lookup_account_sid (NULL, group_token.PrimaryGroup,
5896 gname, &glength, NULL, &dlength,
5897 &user_type);
5898 if (result)
5899 w32_add_to_cache (group_token.PrimaryGroup,
5900 egid, gname);
5901 else
5903 strcpy (gname, "None");
5904 result = TRUE;
5907 glength = strlen (gname);
5911 xfree (buf);
5913 if (!result)
5915 if (!is_windows_9x ())
5917 /* We couldn't open the process token, presumably because of
5918 insufficient access rights. Assume this process is run
5919 by the system. */
5920 strcpy (uname, "SYSTEM");
5921 strcpy (gname, "None");
5922 euid = 18; /* SYSTEM */
5923 egid = 513; /* None */
5924 glength = strlen (gname);
5925 ulength = strlen (uname);
5927 /* If we are running under Windows 9X, where security calls are
5928 not supported, we assume all processes are run by the current
5929 user. */
5930 else if (GetUserName (uname, &ulength))
5932 if (xstrcasecmp ("administrator", uname) == 0)
5933 euid = 0;
5934 else
5935 euid = 123;
5936 egid = euid;
5937 strcpy (gname, "None");
5938 glength = strlen (gname);
5939 ulength = strlen (uname);
5941 else
5943 euid = 123;
5944 egid = 123;
5945 strcpy (uname, "administrator");
5946 ulength = strlen (uname);
5947 strcpy (gname, "None");
5948 glength = strlen (gname);
5950 if (token)
5951 CloseHandle (token);
5954 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (euid)), attrs);
5955 tem = make_unibyte_string (uname, ulength);
5956 attrs = Fcons (Fcons (Quser,
5957 code_convert_string_norecord (tem, Vlocale_coding_system, 0)),
5958 attrs);
5959 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (egid)), attrs);
5960 tem = make_unibyte_string (gname, glength);
5961 attrs = Fcons (Fcons (Qgroup,
5962 code_convert_string_norecord (tem, Vlocale_coding_system, 0)),
5963 attrs);
5965 if (global_memory_status_ex (&memstex))
5966 #if __GNUC__ || (defined (_MSC_VER) && _MSC_VER >= 1300)
5967 totphys = memstex.ullTotalPhys / 1024.0;
5968 #else
5969 /* Visual Studio 6 cannot convert an unsigned __int64 type to
5970 double, so we need to do this for it... */
5972 DWORD tot_hi = memstex.ullTotalPhys >> 32;
5973 DWORD tot_md = (memstex.ullTotalPhys & 0x00000000ffffffff) >> 10;
5974 DWORD tot_lo = memstex.ullTotalPhys % 1024;
5976 totphys = tot_hi * 4194304.0 + tot_md + tot_lo / 1024.0;
5978 #endif /* __GNUC__ || _MSC_VER >= 1300 */
5979 else if (global_memory_status (&memst))
5980 totphys = memst.dwTotalPhys / 1024.0;
5982 if (h_proc
5983 && get_process_memory_info (h_proc, (PROCESS_MEMORY_COUNTERS *)&mem_ex,
5984 sizeof (mem_ex)))
5986 SIZE_T rss = mem_ex.WorkingSetSize / 1024;
5988 attrs = Fcons (Fcons (Qmajflt,
5989 make_fixnum_or_float (mem_ex.PageFaultCount)),
5990 attrs);
5991 attrs = Fcons (Fcons (Qvsize,
5992 make_fixnum_or_float (mem_ex.PrivateUsage / 1024)),
5993 attrs);
5994 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (rss)), attrs);
5995 if (totphys)
5996 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
5998 else if (h_proc
5999 && get_process_memory_info (h_proc, &mem, sizeof (mem)))
6001 SIZE_T rss = mem_ex.WorkingSetSize / 1024;
6003 attrs = Fcons (Fcons (Qmajflt,
6004 make_fixnum_or_float (mem.PageFaultCount)),
6005 attrs);
6006 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (rss)), attrs);
6007 if (totphys)
6008 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
6010 else if (h_proc
6011 && get_process_working_set_size (h_proc, &minrss, &maxrss))
6013 DWORD rss = maxrss / 1024;
6015 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (maxrss / 1024)), attrs);
6016 if (totphys)
6017 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
6020 if (process_times (h_proc, &ctime, &etime, &stime, &utime, &ttime, &pcpu))
6022 attrs = Fcons (Fcons (Qutime, utime), attrs);
6023 attrs = Fcons (Fcons (Qstime, stime), attrs);
6024 attrs = Fcons (Fcons (Qtime, ttime), attrs);
6025 attrs = Fcons (Fcons (Qstart, ctime), attrs);
6026 attrs = Fcons (Fcons (Qetime, etime), attrs);
6027 attrs = Fcons (Fcons (Qpcpu, make_float (pcpu)), attrs);
6030 /* FIXME: Retrieve command line by walking the PEB of the process. */
6032 if (h_proc)
6033 CloseHandle (h_proc);
6034 UNGCPRO;
6035 return attrs;
6039 /* Wrappers for winsock functions to map between our file descriptors
6040 and winsock's handles; also set h_errno for convenience.
6042 To allow Emacs to run on systems which don't have winsock support
6043 installed, we dynamically link to winsock on startup if present, and
6044 otherwise provide the minimum necessary functionality
6045 (eg. gethostname). */
6047 /* function pointers for relevant socket functions */
6048 int (PASCAL *pfn_WSAStartup) (WORD wVersionRequired, LPWSADATA lpWSAData);
6049 void (PASCAL *pfn_WSASetLastError) (int iError);
6050 int (PASCAL *pfn_WSAGetLastError) (void);
6051 int (PASCAL *pfn_WSAEventSelect) (SOCKET s, HANDLE hEventObject, long lNetworkEvents);
6052 HANDLE (PASCAL *pfn_WSACreateEvent) (void);
6053 int (PASCAL *pfn_WSACloseEvent) (HANDLE hEvent);
6054 int (PASCAL *pfn_socket) (int af, int type, int protocol);
6055 int (PASCAL *pfn_bind) (SOCKET s, const struct sockaddr *addr, int namelen);
6056 int (PASCAL *pfn_connect) (SOCKET s, const struct sockaddr *addr, int namelen);
6057 int (PASCAL *pfn_ioctlsocket) (SOCKET s, long cmd, u_long *argp);
6058 int (PASCAL *pfn_recv) (SOCKET s, char * buf, int len, int flags);
6059 int (PASCAL *pfn_send) (SOCKET s, const char * buf, int len, int flags);
6060 int (PASCAL *pfn_closesocket) (SOCKET s);
6061 int (PASCAL *pfn_shutdown) (SOCKET s, int how);
6062 int (PASCAL *pfn_WSACleanup) (void);
6064 u_short (PASCAL *pfn_htons) (u_short hostshort);
6065 u_short (PASCAL *pfn_ntohs) (u_short netshort);
6066 unsigned long (PASCAL *pfn_inet_addr) (const char * cp);
6067 int (PASCAL *pfn_gethostname) (char * name, int namelen);
6068 struct hostent * (PASCAL *pfn_gethostbyname) (const char * name);
6069 struct servent * (PASCAL *pfn_getservbyname) (const char * name, const char * proto);
6070 int (PASCAL *pfn_getpeername) (SOCKET s, struct sockaddr *addr, int * namelen);
6071 int (PASCAL *pfn_setsockopt) (SOCKET s, int level, int optname,
6072 const char * optval, int optlen);
6073 int (PASCAL *pfn_listen) (SOCKET s, int backlog);
6074 int (PASCAL *pfn_getsockname) (SOCKET s, struct sockaddr * name,
6075 int * namelen);
6076 SOCKET (PASCAL *pfn_accept) (SOCKET s, struct sockaddr * addr, int * addrlen);
6077 int (PASCAL *pfn_recvfrom) (SOCKET s, char * buf, int len, int flags,
6078 struct sockaddr * from, int * fromlen);
6079 int (PASCAL *pfn_sendto) (SOCKET s, const char * buf, int len, int flags,
6080 const struct sockaddr * to, int tolen);
6082 /* SetHandleInformation is only needed to make sockets non-inheritable. */
6083 BOOL (WINAPI *pfn_SetHandleInformation) (HANDLE object, DWORD mask, DWORD flags);
6084 #ifndef HANDLE_FLAG_INHERIT
6085 #define HANDLE_FLAG_INHERIT 1
6086 #endif
6088 HANDLE winsock_lib;
6089 static int winsock_inuse;
6091 BOOL
6092 term_winsock (void)
6094 if (winsock_lib != NULL && winsock_inuse == 0)
6096 /* Not sure what would cause WSAENETDOWN, or even if it can happen
6097 after WSAStartup returns successfully, but it seems reasonable
6098 to allow unloading winsock anyway in that case. */
6099 if (pfn_WSACleanup () == 0 ||
6100 pfn_WSAGetLastError () == WSAENETDOWN)
6102 if (FreeLibrary (winsock_lib))
6103 winsock_lib = NULL;
6104 return TRUE;
6107 return FALSE;
6110 BOOL
6111 init_winsock (int load_now)
6113 WSADATA winsockData;
6115 if (winsock_lib != NULL)
6116 return TRUE;
6118 pfn_SetHandleInformation
6119 = (void *) GetProcAddress (GetModuleHandle ("kernel32.dll"),
6120 "SetHandleInformation");
6122 winsock_lib = LoadLibrary ("Ws2_32.dll");
6124 if (winsock_lib != NULL)
6126 /* dynamically link to socket functions */
6128 #define LOAD_PROC(fn) \
6129 if ((pfn_##fn = (void *) GetProcAddress (winsock_lib, #fn)) == NULL) \
6130 goto fail;
6132 LOAD_PROC (WSAStartup);
6133 LOAD_PROC (WSASetLastError);
6134 LOAD_PROC (WSAGetLastError);
6135 LOAD_PROC (WSAEventSelect);
6136 LOAD_PROC (WSACreateEvent);
6137 LOAD_PROC (WSACloseEvent);
6138 LOAD_PROC (socket);
6139 LOAD_PROC (bind);
6140 LOAD_PROC (connect);
6141 LOAD_PROC (ioctlsocket);
6142 LOAD_PROC (recv);
6143 LOAD_PROC (send);
6144 LOAD_PROC (closesocket);
6145 LOAD_PROC (shutdown);
6146 LOAD_PROC (htons);
6147 LOAD_PROC (ntohs);
6148 LOAD_PROC (inet_addr);
6149 LOAD_PROC (gethostname);
6150 LOAD_PROC (gethostbyname);
6151 LOAD_PROC (getservbyname);
6152 LOAD_PROC (getpeername);
6153 LOAD_PROC (WSACleanup);
6154 LOAD_PROC (setsockopt);
6155 LOAD_PROC (listen);
6156 LOAD_PROC (getsockname);
6157 LOAD_PROC (accept);
6158 LOAD_PROC (recvfrom);
6159 LOAD_PROC (sendto);
6160 #undef LOAD_PROC
6162 /* specify version 1.1 of winsock */
6163 if (pfn_WSAStartup (0x101, &winsockData) == 0)
6165 if (winsockData.wVersion != 0x101)
6166 goto fail;
6168 if (!load_now)
6170 /* Report that winsock exists and is usable, but leave
6171 socket functions disabled. I am assuming that calling
6172 WSAStartup does not require any network interaction,
6173 and in particular does not cause or require a dial-up
6174 connection to be established. */
6176 pfn_WSACleanup ();
6177 FreeLibrary (winsock_lib);
6178 winsock_lib = NULL;
6180 winsock_inuse = 0;
6181 return TRUE;
6184 fail:
6185 FreeLibrary (winsock_lib);
6186 winsock_lib = NULL;
6189 return FALSE;
6193 int h_errno = 0;
6195 /* Function to map winsock error codes to errno codes for those errno
6196 code defined in errno.h (errno values not defined by errno.h are
6197 already in nt/inc/sys/socket.h). */
6198 static void
6199 set_errno (void)
6201 int wsa_err;
6203 h_errno = 0;
6204 if (winsock_lib == NULL)
6205 wsa_err = EINVAL;
6206 else
6207 wsa_err = pfn_WSAGetLastError ();
6209 switch (wsa_err)
6211 case WSAEACCES: errno = EACCES; break;
6212 case WSAEBADF: errno = EBADF; break;
6213 case WSAEFAULT: errno = EFAULT; break;
6214 case WSAEINTR: errno = EINTR; break;
6215 case WSAEINVAL: errno = EINVAL; break;
6216 case WSAEMFILE: errno = EMFILE; break;
6217 case WSAENAMETOOLONG: errno = ENAMETOOLONG; break;
6218 case WSAENOTEMPTY: errno = ENOTEMPTY; break;
6219 default: errno = wsa_err; break;
6223 static void
6224 check_errno (void)
6226 h_errno = 0;
6227 if (winsock_lib != NULL)
6228 pfn_WSASetLastError (0);
6231 /* Extend strerror to handle the winsock-specific error codes. */
6232 struct {
6233 int errnum;
6234 char * msg;
6235 } _wsa_errlist[] = {
6236 {WSAEINTR , "Interrupted function call"},
6237 {WSAEBADF , "Bad file descriptor"},
6238 {WSAEACCES , "Permission denied"},
6239 {WSAEFAULT , "Bad address"},
6240 {WSAEINVAL , "Invalid argument"},
6241 {WSAEMFILE , "Too many open files"},
6243 {WSAEWOULDBLOCK , "Resource temporarily unavailable"},
6244 {WSAEINPROGRESS , "Operation now in progress"},
6245 {WSAEALREADY , "Operation already in progress"},
6246 {WSAENOTSOCK , "Socket operation on non-socket"},
6247 {WSAEDESTADDRREQ , "Destination address required"},
6248 {WSAEMSGSIZE , "Message too long"},
6249 {WSAEPROTOTYPE , "Protocol wrong type for socket"},
6250 {WSAENOPROTOOPT , "Bad protocol option"},
6251 {WSAEPROTONOSUPPORT , "Protocol not supported"},
6252 {WSAESOCKTNOSUPPORT , "Socket type not supported"},
6253 {WSAEOPNOTSUPP , "Operation not supported"},
6254 {WSAEPFNOSUPPORT , "Protocol family not supported"},
6255 {WSAEAFNOSUPPORT , "Address family not supported by protocol family"},
6256 {WSAEADDRINUSE , "Address already in use"},
6257 {WSAEADDRNOTAVAIL , "Cannot assign requested address"},
6258 {WSAENETDOWN , "Network is down"},
6259 {WSAENETUNREACH , "Network is unreachable"},
6260 {WSAENETRESET , "Network dropped connection on reset"},
6261 {WSAECONNABORTED , "Software caused connection abort"},
6262 {WSAECONNRESET , "Connection reset by peer"},
6263 {WSAENOBUFS , "No buffer space available"},
6264 {WSAEISCONN , "Socket is already connected"},
6265 {WSAENOTCONN , "Socket is not connected"},
6266 {WSAESHUTDOWN , "Cannot send after socket shutdown"},
6267 {WSAETOOMANYREFS , "Too many references"}, /* not sure */
6268 {WSAETIMEDOUT , "Connection timed out"},
6269 {WSAECONNREFUSED , "Connection refused"},
6270 {WSAELOOP , "Network loop"}, /* not sure */
6271 {WSAENAMETOOLONG , "Name is too long"},
6272 {WSAEHOSTDOWN , "Host is down"},
6273 {WSAEHOSTUNREACH , "No route to host"},
6274 {WSAENOTEMPTY , "Buffer not empty"}, /* not sure */
6275 {WSAEPROCLIM , "Too many processes"},
6276 {WSAEUSERS , "Too many users"}, /* not sure */
6277 {WSAEDQUOT , "Double quote in host name"}, /* really not sure */
6278 {WSAESTALE , "Data is stale"}, /* not sure */
6279 {WSAEREMOTE , "Remote error"}, /* not sure */
6281 {WSASYSNOTREADY , "Network subsystem is unavailable"},
6282 {WSAVERNOTSUPPORTED , "WINSOCK.DLL version out of range"},
6283 {WSANOTINITIALISED , "Winsock not initialized successfully"},
6284 {WSAEDISCON , "Graceful shutdown in progress"},
6285 #ifdef WSAENOMORE
6286 {WSAENOMORE , "No more operations allowed"}, /* not sure */
6287 {WSAECANCELLED , "Operation cancelled"}, /* not sure */
6288 {WSAEINVALIDPROCTABLE , "Invalid procedure table from service provider"},
6289 {WSAEINVALIDPROVIDER , "Invalid service provider version number"},
6290 {WSAEPROVIDERFAILEDINIT , "Unable to initialize a service provider"},
6291 {WSASYSCALLFAILURE , "System call failure"},
6292 {WSASERVICE_NOT_FOUND , "Service not found"}, /* not sure */
6293 {WSATYPE_NOT_FOUND , "Class type not found"},
6294 {WSA_E_NO_MORE , "No more resources available"}, /* really not sure */
6295 {WSA_E_CANCELLED , "Operation already cancelled"}, /* really not sure */
6296 {WSAEREFUSED , "Operation refused"}, /* not sure */
6297 #endif
6299 {WSAHOST_NOT_FOUND , "Host not found"},
6300 {WSATRY_AGAIN , "Authoritative host not found during name lookup"},
6301 {WSANO_RECOVERY , "Non-recoverable error during name lookup"},
6302 {WSANO_DATA , "Valid name, no data record of requested type"},
6304 {-1, NULL}
6307 char *
6308 sys_strerror (int error_no)
6310 int i;
6311 static char unknown_msg[40];
6313 if (error_no >= 0 && error_no < sys_nerr)
6314 return sys_errlist[error_no];
6316 for (i = 0; _wsa_errlist[i].errnum >= 0; i++)
6317 if (_wsa_errlist[i].errnum == error_no)
6318 return _wsa_errlist[i].msg;
6320 sprintf (unknown_msg, "Unidentified error: %d", error_no);
6321 return unknown_msg;
6324 /* [andrewi 3-May-96] I've had conflicting results using both methods,
6325 but I believe the method of keeping the socket handle separate (and
6326 insuring it is not inheritable) is the correct one. */
6328 #define SOCK_HANDLE(fd) ((SOCKET) fd_info[fd].hnd)
6330 static int socket_to_fd (SOCKET s);
6333 sys_socket (int af, int type, int protocol)
6335 SOCKET s;
6337 if (winsock_lib == NULL)
6339 errno = ENETDOWN;
6340 return INVALID_SOCKET;
6343 check_errno ();
6345 /* call the real socket function */
6346 s = pfn_socket (af, type, protocol);
6348 if (s != INVALID_SOCKET)
6349 return socket_to_fd (s);
6351 set_errno ();
6352 return -1;
6355 /* Convert a SOCKET to a file descriptor. */
6356 static int
6357 socket_to_fd (SOCKET s)
6359 int fd;
6360 child_process * cp;
6362 /* Although under NT 3.5 _open_osfhandle will accept a socket
6363 handle, if opened with SO_OPENTYPE == SO_SYNCHRONOUS_NONALERT,
6364 that does not work under NT 3.1. However, we can get the same
6365 effect by using a backdoor function to replace an existing
6366 descriptor handle with the one we want. */
6368 /* allocate a file descriptor (with appropriate flags) */
6369 fd = _open ("NUL:", _O_RDWR);
6370 if (fd >= 0)
6372 /* Make a non-inheritable copy of the socket handle. Note
6373 that it is possible that sockets aren't actually kernel
6374 handles, which appears to be the case on Windows 9x when
6375 the MS Proxy winsock client is installed. */
6377 /* Apparently there is a bug in NT 3.51 with some service
6378 packs, which prevents using DuplicateHandle to make a
6379 socket handle non-inheritable (causes WSACleanup to
6380 hang). The work-around is to use SetHandleInformation
6381 instead if it is available and implemented. */
6382 if (pfn_SetHandleInformation)
6384 pfn_SetHandleInformation ((HANDLE) s, HANDLE_FLAG_INHERIT, 0);
6386 else
6388 HANDLE parent = GetCurrentProcess ();
6389 HANDLE new_s = INVALID_HANDLE_VALUE;
6391 if (DuplicateHandle (parent,
6392 (HANDLE) s,
6393 parent,
6394 &new_s,
6396 FALSE,
6397 DUPLICATE_SAME_ACCESS))
6399 /* It is possible that DuplicateHandle succeeds even
6400 though the socket wasn't really a kernel handle,
6401 because a real handle has the same value. So
6402 test whether the new handle really is a socket. */
6403 long nonblocking = 0;
6404 if (pfn_ioctlsocket ((SOCKET) new_s, FIONBIO, &nonblocking) == 0)
6406 pfn_closesocket (s);
6407 s = (SOCKET) new_s;
6409 else
6411 CloseHandle (new_s);
6416 eassert (fd < MAXDESC);
6417 fd_info[fd].hnd = (HANDLE) s;
6419 /* set our own internal flags */
6420 fd_info[fd].flags = FILE_SOCKET | FILE_BINARY | FILE_READ | FILE_WRITE;
6422 cp = new_child ();
6423 if (cp)
6425 cp->fd = fd;
6426 cp->status = STATUS_READ_ACKNOWLEDGED;
6428 /* attach child_process to fd_info */
6429 if (fd_info[ fd ].cp != NULL)
6431 DebPrint (("sys_socket: fd_info[%d] apparently in use!\n", fd));
6432 emacs_abort ();
6435 fd_info[ fd ].cp = cp;
6437 /* success! */
6438 winsock_inuse++; /* count open sockets */
6439 return fd;
6442 /* clean up */
6443 _close (fd);
6445 else
6446 pfn_closesocket (s);
6447 errno = EMFILE;
6448 return -1;
6452 sys_bind (int s, const struct sockaddr * addr, int namelen)
6454 if (winsock_lib == NULL)
6456 errno = ENOTSOCK;
6457 return SOCKET_ERROR;
6460 check_errno ();
6461 if (fd_info[s].flags & FILE_SOCKET)
6463 int rc = pfn_bind (SOCK_HANDLE (s), addr, namelen);
6464 if (rc == SOCKET_ERROR)
6465 set_errno ();
6466 return rc;
6468 errno = ENOTSOCK;
6469 return SOCKET_ERROR;
6473 sys_connect (int s, const struct sockaddr * name, int namelen)
6475 if (winsock_lib == NULL)
6477 errno = ENOTSOCK;
6478 return SOCKET_ERROR;
6481 check_errno ();
6482 if (fd_info[s].flags & FILE_SOCKET)
6484 int rc = pfn_connect (SOCK_HANDLE (s), name, namelen);
6485 if (rc == SOCKET_ERROR)
6486 set_errno ();
6487 return rc;
6489 errno = ENOTSOCK;
6490 return SOCKET_ERROR;
6493 u_short
6494 sys_htons (u_short hostshort)
6496 return (winsock_lib != NULL) ?
6497 pfn_htons (hostshort) : hostshort;
6500 u_short
6501 sys_ntohs (u_short netshort)
6503 return (winsock_lib != NULL) ?
6504 pfn_ntohs (netshort) : netshort;
6507 unsigned long
6508 sys_inet_addr (const char * cp)
6510 return (winsock_lib != NULL) ?
6511 pfn_inet_addr (cp) : INADDR_NONE;
6515 sys_gethostname (char * name, int namelen)
6517 if (winsock_lib != NULL)
6519 int retval;
6521 check_errno ();
6522 retval = pfn_gethostname (name, namelen);
6523 if (retval == SOCKET_ERROR)
6524 set_errno ();
6525 return retval;
6528 if (namelen > MAX_COMPUTERNAME_LENGTH)
6529 return !GetComputerName (name, (DWORD *)&namelen);
6531 errno = EFAULT;
6532 return SOCKET_ERROR;
6535 struct hostent *
6536 sys_gethostbyname (const char * name)
6538 struct hostent * host;
6539 int h_err = h_errno;
6541 if (winsock_lib == NULL)
6543 h_errno = NO_RECOVERY;
6544 errno = ENETDOWN;
6545 return NULL;
6548 check_errno ();
6549 host = pfn_gethostbyname (name);
6550 if (!host)
6552 set_errno ();
6553 h_errno = errno;
6555 else
6556 h_errno = h_err;
6557 return host;
6560 struct servent *
6561 sys_getservbyname (const char * name, const char * proto)
6563 struct servent * serv;
6565 if (winsock_lib == NULL)
6567 errno = ENETDOWN;
6568 return NULL;
6571 check_errno ();
6572 serv = pfn_getservbyname (name, proto);
6573 if (!serv)
6574 set_errno ();
6575 return serv;
6579 sys_getpeername (int s, struct sockaddr *addr, int * namelen)
6581 if (winsock_lib == NULL)
6583 errno = ENETDOWN;
6584 return SOCKET_ERROR;
6587 check_errno ();
6588 if (fd_info[s].flags & FILE_SOCKET)
6590 int rc = pfn_getpeername (SOCK_HANDLE (s), addr, namelen);
6591 if (rc == SOCKET_ERROR)
6592 set_errno ();
6593 return rc;
6595 errno = ENOTSOCK;
6596 return SOCKET_ERROR;
6600 sys_shutdown (int s, int how)
6602 if (winsock_lib == NULL)
6604 errno = ENETDOWN;
6605 return SOCKET_ERROR;
6608 check_errno ();
6609 if (fd_info[s].flags & FILE_SOCKET)
6611 int rc = pfn_shutdown (SOCK_HANDLE (s), how);
6612 if (rc == SOCKET_ERROR)
6613 set_errno ();
6614 return rc;
6616 errno = ENOTSOCK;
6617 return SOCKET_ERROR;
6621 sys_setsockopt (int s, int level, int optname, const void * optval, int optlen)
6623 if (winsock_lib == NULL)
6625 errno = ENETDOWN;
6626 return SOCKET_ERROR;
6629 check_errno ();
6630 if (fd_info[s].flags & FILE_SOCKET)
6632 int rc = pfn_setsockopt (SOCK_HANDLE (s), level, optname,
6633 (const char *)optval, optlen);
6634 if (rc == SOCKET_ERROR)
6635 set_errno ();
6636 return rc;
6638 errno = ENOTSOCK;
6639 return SOCKET_ERROR;
6643 sys_listen (int s, int backlog)
6645 if (winsock_lib == NULL)
6647 errno = ENETDOWN;
6648 return SOCKET_ERROR;
6651 check_errno ();
6652 if (fd_info[s].flags & FILE_SOCKET)
6654 int rc = pfn_listen (SOCK_HANDLE (s), backlog);
6655 if (rc == SOCKET_ERROR)
6656 set_errno ();
6657 else
6658 fd_info[s].flags |= FILE_LISTEN;
6659 return rc;
6661 errno = ENOTSOCK;
6662 return SOCKET_ERROR;
6666 sys_getsockname (int s, struct sockaddr * name, int * namelen)
6668 if (winsock_lib == NULL)
6670 errno = ENETDOWN;
6671 return SOCKET_ERROR;
6674 check_errno ();
6675 if (fd_info[s].flags & FILE_SOCKET)
6677 int rc = pfn_getsockname (SOCK_HANDLE (s), name, namelen);
6678 if (rc == SOCKET_ERROR)
6679 set_errno ();
6680 return rc;
6682 errno = ENOTSOCK;
6683 return SOCKET_ERROR;
6687 sys_accept (int s, struct sockaddr * addr, int * addrlen)
6689 if (winsock_lib == NULL)
6691 errno = ENETDOWN;
6692 return -1;
6695 check_errno ();
6696 if (fd_info[s].flags & FILE_LISTEN)
6698 SOCKET t = pfn_accept (SOCK_HANDLE (s), addr, addrlen);
6699 int fd = -1;
6700 if (t == INVALID_SOCKET)
6701 set_errno ();
6702 else
6703 fd = socket_to_fd (t);
6705 if (fd >= 0)
6707 fd_info[s].cp->status = STATUS_READ_ACKNOWLEDGED;
6708 ResetEvent (fd_info[s].cp->char_avail);
6710 return fd;
6712 errno = ENOTSOCK;
6713 return -1;
6717 sys_recvfrom (int s, char * buf, int len, int flags,
6718 struct sockaddr * from, int * fromlen)
6720 if (winsock_lib == NULL)
6722 errno = ENETDOWN;
6723 return SOCKET_ERROR;
6726 check_errno ();
6727 if (fd_info[s].flags & FILE_SOCKET)
6729 int rc = pfn_recvfrom (SOCK_HANDLE (s), buf, len, flags, from, fromlen);
6730 if (rc == SOCKET_ERROR)
6731 set_errno ();
6732 return rc;
6734 errno = ENOTSOCK;
6735 return SOCKET_ERROR;
6739 sys_sendto (int s, const char * buf, int len, int flags,
6740 const struct sockaddr * to, int tolen)
6742 if (winsock_lib == NULL)
6744 errno = ENETDOWN;
6745 return SOCKET_ERROR;
6748 check_errno ();
6749 if (fd_info[s].flags & FILE_SOCKET)
6751 int rc = pfn_sendto (SOCK_HANDLE (s), buf, len, flags, to, tolen);
6752 if (rc == SOCKET_ERROR)
6753 set_errno ();
6754 return rc;
6756 errno = ENOTSOCK;
6757 return SOCKET_ERROR;
6760 /* Windows does not have an fcntl function. Provide an implementation
6761 good enough for Emacs. */
6763 fcntl (int s, int cmd, int options)
6765 /* In the w32 Emacs port, fcntl (fd, F_DUPFD_CLOEXEC, fd1) is always
6766 invoked in a context where fd1 is closed and all descriptors less
6767 than fd1 are open, so sys_dup is an adequate implementation. */
6768 if (cmd == F_DUPFD_CLOEXEC)
6769 return sys_dup (s);
6771 if (winsock_lib == NULL)
6773 errno = ENETDOWN;
6774 return -1;
6777 check_errno ();
6778 if (fd_info[s].flags & FILE_SOCKET)
6780 if (cmd == F_SETFL && options == O_NONBLOCK)
6782 unsigned long nblock = 1;
6783 int rc = pfn_ioctlsocket (SOCK_HANDLE (s), FIONBIO, &nblock);
6784 if (rc == SOCKET_ERROR)
6785 set_errno ();
6786 /* Keep track of the fact that we set this to non-blocking. */
6787 fd_info[s].flags |= FILE_NDELAY;
6788 return rc;
6790 else
6792 errno = EINVAL;
6793 return SOCKET_ERROR;
6796 errno = ENOTSOCK;
6797 return SOCKET_ERROR;
6801 /* Shadow main io functions: we need to handle pipes and sockets more
6802 intelligently, and implement non-blocking mode as well. */
6805 sys_close (int fd)
6807 int rc;
6809 if (fd < 0)
6811 errno = EBADF;
6812 return -1;
6815 if (fd < MAXDESC && fd_info[fd].cp)
6817 child_process * cp = fd_info[fd].cp;
6819 fd_info[fd].cp = NULL;
6821 if (CHILD_ACTIVE (cp))
6823 /* if last descriptor to active child_process then cleanup */
6824 int i;
6825 for (i = 0; i < MAXDESC; i++)
6827 if (i == fd)
6828 continue;
6829 if (fd_info[i].cp == cp)
6830 break;
6832 if (i == MAXDESC)
6834 if (fd_info[fd].flags & FILE_SOCKET)
6836 if (winsock_lib == NULL) emacs_abort ();
6838 pfn_shutdown (SOCK_HANDLE (fd), 2);
6839 rc = pfn_closesocket (SOCK_HANDLE (fd));
6841 winsock_inuse--; /* count open sockets */
6843 /* If the process handle is NULL, it's either a socket
6844 or serial connection, or a subprocess that was
6845 already reaped by reap_subprocess, but whose
6846 resources were not yet freed, because its output was
6847 not fully read yet by the time it was reaped. (This
6848 usually happens with async subprocesses whose output
6849 is being read by Emacs.) Otherwise, this process was
6850 not reaped yet, so we set its FD to a negative value
6851 to make sure sys_select will eventually get to
6852 calling the SIGCHLD handler for it, which will then
6853 invoke waitpid and reap_subprocess. */
6854 if (cp->procinfo.hProcess == NULL)
6855 delete_child (cp);
6856 else
6857 cp->fd = -1;
6862 if (fd >= 0 && fd < MAXDESC)
6863 fd_info[fd].flags = 0;
6865 /* Note that sockets do not need special treatment here (at least on
6866 NT and Windows 95 using the standard tcp/ip stacks) - it appears that
6867 closesocket is equivalent to CloseHandle, which is to be expected
6868 because socket handles are fully fledged kernel handles. */
6869 rc = _close (fd);
6871 return rc;
6875 sys_dup (int fd)
6877 int new_fd;
6879 new_fd = _dup (fd);
6880 if (new_fd >= 0 && new_fd < MAXDESC)
6882 /* duplicate our internal info as well */
6883 fd_info[new_fd] = fd_info[fd];
6885 return new_fd;
6889 sys_dup2 (int src, int dst)
6891 int rc;
6893 if (dst < 0 || dst >= MAXDESC)
6895 errno = EBADF;
6896 return -1;
6899 /* make sure we close the destination first if it's a pipe or socket */
6900 if (src != dst && fd_info[dst].flags != 0)
6901 sys_close (dst);
6903 rc = _dup2 (src, dst);
6904 if (rc == 0)
6906 /* duplicate our internal info as well */
6907 fd_info[dst] = fd_info[src];
6909 return rc;
6913 pipe2 (int * phandles, int pipe2_flags)
6915 int rc;
6916 unsigned flags;
6918 eassert (pipe2_flags == O_CLOEXEC);
6920 /* make pipe handles non-inheritable; when we spawn a child, we
6921 replace the relevant handle with an inheritable one. Also put
6922 pipes into binary mode; we will do text mode translation ourselves
6923 if required. */
6924 rc = _pipe (phandles, 0, _O_NOINHERIT | _O_BINARY);
6926 if (rc == 0)
6928 /* Protect against overflow, since Windows can open more handles than
6929 our fd_info array has room for. */
6930 if (phandles[0] >= MAXDESC || phandles[1] >= MAXDESC)
6932 _close (phandles[0]);
6933 _close (phandles[1]);
6934 errno = EMFILE;
6935 rc = -1;
6937 else
6939 flags = FILE_PIPE | FILE_READ | FILE_BINARY;
6940 fd_info[phandles[0]].flags = flags;
6942 flags = FILE_PIPE | FILE_WRITE | FILE_BINARY;
6943 fd_info[phandles[1]].flags = flags;
6947 return rc;
6950 /* Function to do blocking read of one byte, needed to implement
6951 select. It is only allowed on communication ports, sockets, or
6952 pipes. */
6954 _sys_read_ahead (int fd)
6956 child_process * cp;
6957 int rc;
6959 if (fd < 0 || fd >= MAXDESC)
6960 return STATUS_READ_ERROR;
6962 cp = fd_info[fd].cp;
6964 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
6965 return STATUS_READ_ERROR;
6967 if ((fd_info[fd].flags & (FILE_PIPE | FILE_SERIAL | FILE_SOCKET)) == 0
6968 || (fd_info[fd].flags & FILE_READ) == 0)
6970 DebPrint (("_sys_read_ahead: internal error: fd %d is not a pipe, serial port, or socket!\n", fd));
6971 emacs_abort ();
6974 cp->status = STATUS_READ_IN_PROGRESS;
6976 if (fd_info[fd].flags & FILE_PIPE)
6978 rc = _read (fd, &cp->chr, sizeof (char));
6980 /* Give subprocess time to buffer some more output for us before
6981 reporting that input is available; we need this because Windows 95
6982 connects DOS programs to pipes by making the pipe appear to be
6983 the normal console stdout - as a result most DOS programs will
6984 write to stdout without buffering, ie. one character at a
6985 time. Even some W32 programs do this - "dir" in a command
6986 shell on NT is very slow if we don't do this. */
6987 if (rc > 0)
6989 int wait = w32_pipe_read_delay;
6991 if (wait > 0)
6992 Sleep (wait);
6993 else if (wait < 0)
6994 while (++wait <= 0)
6995 /* Yield remainder of our time slice, effectively giving a
6996 temporary priority boost to the child process. */
6997 Sleep (0);
7000 else if (fd_info[fd].flags & FILE_SERIAL)
7002 HANDLE hnd = fd_info[fd].hnd;
7003 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_read;
7004 COMMTIMEOUTS ct;
7006 /* Configure timeouts for blocking read. */
7007 if (!GetCommTimeouts (hnd, &ct))
7009 cp->status = STATUS_READ_ERROR;
7010 return STATUS_READ_ERROR;
7012 ct.ReadIntervalTimeout = 0;
7013 ct.ReadTotalTimeoutMultiplier = 0;
7014 ct.ReadTotalTimeoutConstant = 0;
7015 if (!SetCommTimeouts (hnd, &ct))
7017 cp->status = STATUS_READ_ERROR;
7018 return STATUS_READ_ERROR;
7021 if (!ReadFile (hnd, &cp->chr, sizeof (char), (DWORD*) &rc, ovl))
7023 if (GetLastError () != ERROR_IO_PENDING)
7025 cp->status = STATUS_READ_ERROR;
7026 return STATUS_READ_ERROR;
7028 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &rc, TRUE))
7030 cp->status = STATUS_READ_ERROR;
7031 return STATUS_READ_ERROR;
7035 else if (fd_info[fd].flags & FILE_SOCKET)
7037 unsigned long nblock = 0;
7038 /* We always want this to block, so temporarily disable NDELAY. */
7039 if (fd_info[fd].flags & FILE_NDELAY)
7040 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
7042 rc = pfn_recv (SOCK_HANDLE (fd), &cp->chr, sizeof (char), 0);
7044 if (fd_info[fd].flags & FILE_NDELAY)
7046 nblock = 1;
7047 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
7051 if (rc == sizeof (char))
7052 cp->status = STATUS_READ_SUCCEEDED;
7053 else
7054 cp->status = STATUS_READ_FAILED;
7056 return cp->status;
7060 _sys_wait_accept (int fd)
7062 HANDLE hEv;
7063 child_process * cp;
7064 int rc;
7066 if (fd < 0 || fd >= MAXDESC)
7067 return STATUS_READ_ERROR;
7069 cp = fd_info[fd].cp;
7071 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
7072 return STATUS_READ_ERROR;
7074 cp->status = STATUS_READ_FAILED;
7076 hEv = pfn_WSACreateEvent ();
7077 rc = pfn_WSAEventSelect (SOCK_HANDLE (fd), hEv, FD_ACCEPT);
7078 if (rc != SOCKET_ERROR)
7080 rc = WaitForSingleObject (hEv, INFINITE);
7081 pfn_WSAEventSelect (SOCK_HANDLE (fd), NULL, 0);
7082 if (rc == WAIT_OBJECT_0)
7083 cp->status = STATUS_READ_SUCCEEDED;
7085 pfn_WSACloseEvent (hEv);
7087 return cp->status;
7091 sys_read (int fd, char * buffer, unsigned int count)
7093 int nchars;
7094 int to_read;
7095 DWORD waiting;
7096 char * orig_buffer = buffer;
7098 if (fd < 0)
7100 errno = EBADF;
7101 return -1;
7104 if (fd < MAXDESC && fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET | FILE_SERIAL))
7106 child_process *cp = fd_info[fd].cp;
7108 if ((fd_info[fd].flags & FILE_READ) == 0)
7110 errno = EBADF;
7111 return -1;
7114 nchars = 0;
7116 /* re-read CR carried over from last read */
7117 if (fd_info[fd].flags & FILE_LAST_CR)
7119 if (fd_info[fd].flags & FILE_BINARY) emacs_abort ();
7120 *buffer++ = 0x0d;
7121 count--;
7122 nchars++;
7123 fd_info[fd].flags &= ~FILE_LAST_CR;
7126 /* presence of a child_process structure means we are operating in
7127 non-blocking mode - otherwise we just call _read directly.
7128 Note that the child_process structure might be missing because
7129 reap_subprocess has been called; in this case the pipe is
7130 already broken, so calling _read on it is okay. */
7131 if (cp)
7133 int current_status = cp->status;
7135 switch (current_status)
7137 case STATUS_READ_FAILED:
7138 case STATUS_READ_ERROR:
7139 /* report normal EOF if nothing in buffer */
7140 if (nchars <= 0)
7141 fd_info[fd].flags |= FILE_AT_EOF;
7142 return nchars;
7144 case STATUS_READ_READY:
7145 case STATUS_READ_IN_PROGRESS:
7146 DebPrint (("sys_read called when read is in progress\n"));
7147 errno = EWOULDBLOCK;
7148 return -1;
7150 case STATUS_READ_SUCCEEDED:
7151 /* consume read-ahead char */
7152 *buffer++ = cp->chr;
7153 count--;
7154 nchars++;
7155 cp->status = STATUS_READ_ACKNOWLEDGED;
7156 ResetEvent (cp->char_avail);
7158 case STATUS_READ_ACKNOWLEDGED:
7159 break;
7161 default:
7162 DebPrint (("sys_read: bad status %d\n", current_status));
7163 errno = EBADF;
7164 return -1;
7167 if (fd_info[fd].flags & FILE_PIPE)
7169 PeekNamedPipe ((HANDLE) _get_osfhandle (fd), NULL, 0, NULL, &waiting, NULL);
7170 to_read = min (waiting, (DWORD) count);
7172 if (to_read > 0)
7173 nchars += _read (fd, buffer, to_read);
7175 else if (fd_info[fd].flags & FILE_SERIAL)
7177 HANDLE hnd = fd_info[fd].hnd;
7178 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_read;
7179 int rc = 0;
7180 COMMTIMEOUTS ct;
7182 if (count > 0)
7184 /* Configure timeouts for non-blocking read. */
7185 if (!GetCommTimeouts (hnd, &ct))
7187 errno = EIO;
7188 return -1;
7190 ct.ReadIntervalTimeout = MAXDWORD;
7191 ct.ReadTotalTimeoutMultiplier = 0;
7192 ct.ReadTotalTimeoutConstant = 0;
7193 if (!SetCommTimeouts (hnd, &ct))
7195 errno = EIO;
7196 return -1;
7199 if (!ResetEvent (ovl->hEvent))
7201 errno = EIO;
7202 return -1;
7204 if (!ReadFile (hnd, buffer, count, (DWORD*) &rc, ovl))
7206 if (GetLastError () != ERROR_IO_PENDING)
7208 errno = EIO;
7209 return -1;
7211 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &rc, TRUE))
7213 errno = EIO;
7214 return -1;
7217 nchars += rc;
7220 else /* FILE_SOCKET */
7222 if (winsock_lib == NULL) emacs_abort ();
7224 /* do the equivalent of a non-blocking read */
7225 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONREAD, &waiting);
7226 if (waiting == 0 && nchars == 0)
7228 errno = EWOULDBLOCK;
7229 return -1;
7232 if (waiting)
7234 /* always use binary mode for sockets */
7235 int res = pfn_recv (SOCK_HANDLE (fd), buffer, count, 0);
7236 if (res == SOCKET_ERROR)
7238 DebPrint (("sys_read.recv failed with error %d on socket %ld\n",
7239 pfn_WSAGetLastError (), SOCK_HANDLE (fd)));
7240 set_errno ();
7241 return -1;
7243 nchars += res;
7247 else
7249 int nread = _read (fd, buffer, count);
7250 if (nread >= 0)
7251 nchars += nread;
7252 else if (nchars == 0)
7253 nchars = nread;
7256 if (nchars <= 0)
7257 fd_info[fd].flags |= FILE_AT_EOF;
7258 /* Perform text mode translation if required. */
7259 else if ((fd_info[fd].flags & FILE_BINARY) == 0)
7261 nchars = crlf_to_lf (nchars, orig_buffer);
7262 /* If buffer contains only CR, return that. To be absolutely
7263 sure we should attempt to read the next char, but in
7264 practice a CR to be followed by LF would not appear by
7265 itself in the buffer. */
7266 if (nchars > 1 && orig_buffer[nchars - 1] == 0x0d)
7268 fd_info[fd].flags |= FILE_LAST_CR;
7269 nchars--;
7273 else
7274 nchars = _read (fd, buffer, count);
7276 return nchars;
7279 /* From w32xfns.c */
7280 extern HANDLE interrupt_handle;
7282 /* For now, don't bother with a non-blocking mode */
7284 sys_write (int fd, const void * buffer, unsigned int count)
7286 int nchars;
7288 if (fd < 0)
7290 errno = EBADF;
7291 return -1;
7294 if (fd < MAXDESC && fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET | FILE_SERIAL))
7296 if ((fd_info[fd].flags & FILE_WRITE) == 0)
7298 errno = EBADF;
7299 return -1;
7302 /* Perform text mode translation if required. */
7303 if ((fd_info[fd].flags & FILE_BINARY) == 0)
7305 char * tmpbuf = alloca (count * 2);
7306 unsigned char * src = (void *)buffer;
7307 unsigned char * dst = tmpbuf;
7308 int nbytes = count;
7310 while (1)
7312 unsigned char *next;
7313 /* copy next line or remaining bytes */
7314 next = _memccpy (dst, src, '\n', nbytes);
7315 if (next)
7317 /* copied one line ending with '\n' */
7318 int copied = next - dst;
7319 nbytes -= copied;
7320 src += copied;
7321 /* insert '\r' before '\n' */
7322 next[-1] = '\r';
7323 next[0] = '\n';
7324 dst = next + 1;
7325 count++;
7327 else
7328 /* copied remaining partial line -> now finished */
7329 break;
7331 buffer = tmpbuf;
7335 if (fd < MAXDESC && fd_info[fd].flags & FILE_SERIAL)
7337 HANDLE hnd = (HANDLE) _get_osfhandle (fd);
7338 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_write;
7339 HANDLE wait_hnd[2] = { interrupt_handle, ovl->hEvent };
7340 DWORD active = 0;
7342 if (!WriteFile (hnd, buffer, count, (DWORD*) &nchars, ovl))
7344 if (GetLastError () != ERROR_IO_PENDING)
7346 errno = EIO;
7347 return -1;
7349 if (detect_input_pending ())
7350 active = MsgWaitForMultipleObjects (2, wait_hnd, FALSE, INFINITE,
7351 QS_ALLINPUT);
7352 else
7353 active = WaitForMultipleObjects (2, wait_hnd, FALSE, INFINITE);
7354 if (active == WAIT_OBJECT_0)
7355 { /* User pressed C-g, cancel write, then leave. Don't bother
7356 cleaning up as we may only get stuck in buggy drivers. */
7357 PurgeComm (hnd, PURGE_TXABORT | PURGE_TXCLEAR);
7358 CancelIo (hnd);
7359 errno = EIO;
7360 return -1;
7362 if (active == WAIT_OBJECT_0 + 1
7363 && !GetOverlappedResult (hnd, ovl, (DWORD*) &nchars, TRUE))
7365 errno = EIO;
7366 return -1;
7370 else if (fd < MAXDESC && fd_info[fd].flags & FILE_SOCKET)
7372 unsigned long nblock = 0;
7373 if (winsock_lib == NULL) emacs_abort ();
7375 /* TODO: implement select() properly so non-blocking I/O works. */
7376 /* For now, make sure the write blocks. */
7377 if (fd_info[fd].flags & FILE_NDELAY)
7378 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
7380 nchars = pfn_send (SOCK_HANDLE (fd), buffer, count, 0);
7382 /* Set the socket back to non-blocking if it was before,
7383 for other operations that support it. */
7384 if (fd_info[fd].flags & FILE_NDELAY)
7386 nblock = 1;
7387 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
7390 if (nchars == SOCKET_ERROR)
7392 DebPrint (("sys_write.send failed with error %d on socket %ld\n",
7393 pfn_WSAGetLastError (), SOCK_HANDLE (fd)));
7394 set_errno ();
7397 else
7399 /* Some networked filesystems don't like too large writes, so
7400 break them into smaller chunks. See the Comments section of
7401 the MSDN documentation of WriteFile for details behind the
7402 choice of the value of CHUNK below. See also the thread
7403 http://thread.gmane.org/gmane.comp.version-control.git/145294
7404 in the git mailing list. */
7405 const unsigned char *p = buffer;
7406 const unsigned chunk = 30 * 1024 * 1024;
7408 nchars = 0;
7409 while (count > 0)
7411 unsigned this_chunk = count < chunk ? count : chunk;
7412 int n = _write (fd, p, this_chunk);
7414 nchars += n;
7415 if (n < 0)
7417 nchars = n;
7418 break;
7420 else if (n < this_chunk)
7421 break;
7422 count -= n;
7423 p += n;
7427 return nchars;
7430 /* The Windows CRT functions are "optimized for speed", so they don't
7431 check for timezone and DST changes if they were last called less
7432 than 1 minute ago (see http://support.microsoft.com/kb/821231). So
7433 all Emacs features that repeatedly call time functions (e.g.,
7434 display-time) are in real danger of missing timezone and DST
7435 changes. Calling tzset before each localtime call fixes that. */
7436 struct tm *
7437 sys_localtime (const time_t *t)
7439 tzset ();
7440 return localtime (t);
7445 /* Try loading LIBRARY_ID from the file(s) specified in
7446 Vdynamic_library_alist. If the library is loaded successfully,
7447 return the handle of the DLL, and record the filename in the
7448 property :loaded-from of LIBRARY_ID. If the library could not be
7449 found, or when it was already loaded (because the handle is not
7450 recorded anywhere, and so is lost after use), return NULL.
7452 We could also save the handle in :loaded-from, but currently
7453 there's no use case for it. */
7454 HMODULE
7455 w32_delayed_load (Lisp_Object library_id)
7457 HMODULE library_dll = NULL;
7459 CHECK_SYMBOL (library_id);
7461 if (CONSP (Vdynamic_library_alist)
7462 && NILP (Fassq (library_id, Vlibrary_cache)))
7464 Lisp_Object found = Qnil;
7465 Lisp_Object dlls = Fassq (library_id, Vdynamic_library_alist);
7467 if (CONSP (dlls))
7468 for (dlls = XCDR (dlls); CONSP (dlls); dlls = XCDR (dlls))
7470 CHECK_STRING_CAR (dlls);
7471 if ((library_dll = LoadLibrary (SDATA (XCAR (dlls)))))
7473 char name[MAX_PATH];
7474 DWORD len;
7476 len = GetModuleFileNameA (library_dll, name, sizeof (name));
7477 found = Fcons (XCAR (dlls),
7478 (len > 0)
7479 /* Possibly truncated */
7480 ? make_specified_string (name, -1, len, 1)
7481 : Qnil);
7482 break;
7486 Fput (library_id, QCloaded_from, found);
7489 return library_dll;
7493 void
7494 check_windows_init_file (void)
7496 /* A common indication that Emacs is not installed properly is when
7497 it cannot find the Windows installation file. If this file does
7498 not exist in the expected place, tell the user. */
7500 if (!noninteractive && !inhibit_window_system
7501 /* Vload_path is not yet initialized when we are loading
7502 loadup.el. */
7503 && NILP (Vpurify_flag))
7505 Lisp_Object init_file;
7506 int fd;
7508 init_file = build_string ("term/w32-win");
7509 fd = openp (Vload_path, init_file, Fget_load_suffixes (), NULL, Qnil);
7510 if (fd < 0)
7512 Lisp_Object load_path_print = Fprin1_to_string (Vload_path, Qnil);
7513 char *init_file_name = SDATA (init_file);
7514 char *load_path = SDATA (load_path_print);
7515 char *buffer = alloca (1024
7516 + strlen (init_file_name)
7517 + strlen (load_path));
7519 sprintf (buffer,
7520 "The Emacs Windows initialization file \"%s.el\" "
7521 "could not be found in your Emacs installation. "
7522 "Emacs checked the following directories for this file:\n"
7523 "\n%s\n\n"
7524 "When Emacs cannot find this file, it usually means that it "
7525 "was not installed properly, or its distribution file was "
7526 "not unpacked properly.\nSee the README.W32 file in the "
7527 "top-level Emacs directory for more information.",
7528 init_file_name, load_path);
7529 MessageBox (NULL,
7530 buffer,
7531 "Emacs Abort Dialog",
7532 MB_OK | MB_ICONEXCLAMATION | MB_TASKMODAL);
7533 /* Use the low-level system abort. */
7534 abort ();
7536 else
7538 _close (fd);
7543 void
7544 term_ntproc (int ignored)
7546 (void)ignored;
7548 term_timers ();
7550 /* shutdown the socket interface if necessary */
7551 term_winsock ();
7553 term_w32select ();
7556 void
7557 init_ntproc (int dumping)
7559 sigset_t initial_mask = 0;
7561 /* Initialize the socket interface now if available and requested by
7562 the user by defining PRELOAD_WINSOCK; otherwise loading will be
7563 delayed until open-network-stream is called (w32-has-winsock can
7564 also be used to dynamically load or reload winsock).
7566 Conveniently, init_environment is called before us, so
7567 PRELOAD_WINSOCK can be set in the registry. */
7569 /* Always initialize this correctly. */
7570 winsock_lib = NULL;
7572 if (getenv ("PRELOAD_WINSOCK") != NULL)
7573 init_winsock (TRUE);
7575 /* Initial preparation for subprocess support: replace our standard
7576 handles with non-inheritable versions. */
7578 HANDLE parent;
7579 HANDLE stdin_save = INVALID_HANDLE_VALUE;
7580 HANDLE stdout_save = INVALID_HANDLE_VALUE;
7581 HANDLE stderr_save = INVALID_HANDLE_VALUE;
7583 parent = GetCurrentProcess ();
7585 /* ignore errors when duplicating and closing; typically the
7586 handles will be invalid when running as a gui program. */
7587 DuplicateHandle (parent,
7588 GetStdHandle (STD_INPUT_HANDLE),
7589 parent,
7590 &stdin_save,
7592 FALSE,
7593 DUPLICATE_SAME_ACCESS);
7595 DuplicateHandle (parent,
7596 GetStdHandle (STD_OUTPUT_HANDLE),
7597 parent,
7598 &stdout_save,
7600 FALSE,
7601 DUPLICATE_SAME_ACCESS);
7603 DuplicateHandle (parent,
7604 GetStdHandle (STD_ERROR_HANDLE),
7605 parent,
7606 &stderr_save,
7608 FALSE,
7609 DUPLICATE_SAME_ACCESS);
7611 fclose (stdin);
7612 fclose (stdout);
7613 fclose (stderr);
7615 if (stdin_save != INVALID_HANDLE_VALUE)
7616 _open_osfhandle ((intptr_t) stdin_save, O_TEXT);
7617 else
7618 _open ("nul", O_TEXT | O_NOINHERIT | O_RDONLY);
7619 _fdopen (0, "r");
7621 if (stdout_save != INVALID_HANDLE_VALUE)
7622 _open_osfhandle ((intptr_t) stdout_save, O_TEXT);
7623 else
7624 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
7625 _fdopen (1, "w");
7627 if (stderr_save != INVALID_HANDLE_VALUE)
7628 _open_osfhandle ((intptr_t) stderr_save, O_TEXT);
7629 else
7630 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
7631 _fdopen (2, "w");
7634 /* unfortunately, atexit depends on implementation of malloc */
7635 /* atexit (term_ntproc); */
7636 if (!dumping)
7638 /* Make sure we start with all signals unblocked. */
7639 sigprocmask (SIG_SETMASK, &initial_mask, NULL);
7640 signal (SIGABRT, term_ntproc);
7642 init_timers ();
7644 /* determine which drives are fixed, for GetCachedVolumeInformation */
7646 /* GetDriveType must have trailing backslash. */
7647 char drive[] = "A:\\";
7649 /* Loop over all possible drive letters */
7650 while (*drive <= 'Z')
7652 /* Record if this drive letter refers to a fixed drive. */
7653 fixed_drives[DRIVE_INDEX (*drive)] =
7654 (GetDriveType (drive) == DRIVE_FIXED);
7656 (*drive)++;
7659 /* Reset the volume info cache. */
7660 volume_cache = NULL;
7665 shutdown_handler ensures that buffers' autosave files are
7666 up to date when the user logs off, or the system shuts down.
7668 static BOOL WINAPI
7669 shutdown_handler (DWORD type)
7671 /* Ctrl-C and Ctrl-Break are already suppressed, so don't handle them. */
7672 if (type == CTRL_CLOSE_EVENT /* User closes console window. */
7673 || type == CTRL_LOGOFF_EVENT /* User logs off. */
7674 || type == CTRL_SHUTDOWN_EVENT) /* User shutsdown. */
7676 /* Shut down cleanly, making sure autosave files are up to date. */
7677 shut_down_emacs (0, Qnil);
7680 /* Allow other handlers to handle this signal. */
7681 return FALSE;
7685 globals_of_w32 is used to initialize those global variables that
7686 must always be initialized on startup even when the global variable
7687 initialized is non zero (see the function main in emacs.c).
7689 void
7690 globals_of_w32 (void)
7692 HMODULE kernel32 = GetModuleHandle ("kernel32.dll");
7694 get_process_times_fn = (GetProcessTimes_Proc)
7695 GetProcAddress (kernel32, "GetProcessTimes");
7697 DEFSYM (QCloaded_from, ":loaded-from");
7699 g_b_init_is_windows_9x = 0;
7700 g_b_init_open_process_token = 0;
7701 g_b_init_get_token_information = 0;
7702 g_b_init_lookup_account_sid = 0;
7703 g_b_init_get_sid_sub_authority = 0;
7704 g_b_init_get_sid_sub_authority_count = 0;
7705 g_b_init_get_security_info = 0;
7706 g_b_init_get_file_security = 0;
7707 g_b_init_get_security_descriptor_owner = 0;
7708 g_b_init_get_security_descriptor_group = 0;
7709 g_b_init_is_valid_sid = 0;
7710 g_b_init_create_toolhelp32_snapshot = 0;
7711 g_b_init_process32_first = 0;
7712 g_b_init_process32_next = 0;
7713 g_b_init_open_thread_token = 0;
7714 g_b_init_impersonate_self = 0;
7715 g_b_init_revert_to_self = 0;
7716 g_b_init_get_process_memory_info = 0;
7717 g_b_init_get_process_working_set_size = 0;
7718 g_b_init_global_memory_status = 0;
7719 g_b_init_global_memory_status_ex = 0;
7720 g_b_init_equal_sid = 0;
7721 g_b_init_copy_sid = 0;
7722 g_b_init_get_length_sid = 0;
7723 g_b_init_get_native_system_info = 0;
7724 g_b_init_get_system_times = 0;
7725 g_b_init_create_symbolic_link = 0;
7726 g_b_init_get_security_descriptor_dacl = 0;
7727 g_b_init_convert_sd_to_sddl = 0;
7728 g_b_init_convert_sddl_to_sd = 0;
7729 g_b_init_is_valid_security_descriptor = 0;
7730 g_b_init_set_file_security = 0;
7731 num_of_processors = 0;
7732 /* The following sets a handler for shutdown notifications for
7733 console apps. This actually applies to Emacs in both console and
7734 GUI modes, since we had to fool windows into thinking emacs is a
7735 console application to get console mode to work. */
7736 SetConsoleCtrlHandler (shutdown_handler, TRUE);
7738 /* "None" is the default group name on standalone workstations. */
7739 strcpy (dflt_group_name, "None");
7741 /* Reset, in case it has some value inherited from dump time. */
7742 w32_stat_get_owner_group = 0;
7745 /* For make-serial-process */
7747 serial_open (Lisp_Object port_obj)
7749 char *port = SSDATA (port_obj);
7750 HANDLE hnd;
7751 child_process *cp;
7752 int fd = -1;
7754 hnd = CreateFile (port, GENERIC_READ | GENERIC_WRITE, 0, 0,
7755 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
7756 if (hnd == INVALID_HANDLE_VALUE)
7757 error ("Could not open %s", port);
7758 fd = (int) _open_osfhandle ((intptr_t) hnd, 0);
7759 if (fd == -1)
7760 error ("Could not open %s", port);
7762 cp = new_child ();
7763 if (!cp)
7764 error ("Could not create child process");
7765 cp->fd = fd;
7766 cp->status = STATUS_READ_ACKNOWLEDGED;
7767 fd_info[ fd ].hnd = hnd;
7768 fd_info[ fd ].flags |=
7769 FILE_READ | FILE_WRITE | FILE_BINARY | FILE_SERIAL;
7770 if (fd_info[ fd ].cp != NULL)
7772 error ("fd_info[fd = %d] is already in use", fd);
7774 fd_info[ fd ].cp = cp;
7775 cp->ovl_read.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
7776 if (cp->ovl_read.hEvent == NULL)
7777 error ("Could not create read event");
7778 cp->ovl_write.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
7779 if (cp->ovl_write.hEvent == NULL)
7780 error ("Could not create write event");
7782 return fd;
7785 /* For serial-process-configure */
7786 void
7787 serial_configure (struct Lisp_Process *p, Lisp_Object contact)
7789 Lisp_Object childp2 = Qnil;
7790 Lisp_Object tem = Qnil;
7791 HANDLE hnd;
7792 DCB dcb;
7793 COMMTIMEOUTS ct;
7794 char summary[4] = "???"; /* This usually becomes "8N1". */
7796 if ((fd_info[ p->outfd ].flags & FILE_SERIAL) == 0)
7797 error ("Not a serial process");
7798 hnd = fd_info[ p->outfd ].hnd;
7800 childp2 = Fcopy_sequence (p->childp);
7802 /* Initialize timeouts for blocking read and blocking write. */
7803 if (!GetCommTimeouts (hnd, &ct))
7804 error ("GetCommTimeouts() failed");
7805 ct.ReadIntervalTimeout = 0;
7806 ct.ReadTotalTimeoutMultiplier = 0;
7807 ct.ReadTotalTimeoutConstant = 0;
7808 ct.WriteTotalTimeoutMultiplier = 0;
7809 ct.WriteTotalTimeoutConstant = 0;
7810 if (!SetCommTimeouts (hnd, &ct))
7811 error ("SetCommTimeouts() failed");
7812 /* Read port attributes and prepare default configuration. */
7813 memset (&dcb, 0, sizeof (dcb));
7814 dcb.DCBlength = sizeof (DCB);
7815 if (!GetCommState (hnd, &dcb))
7816 error ("GetCommState() failed");
7817 dcb.fBinary = TRUE;
7818 dcb.fNull = FALSE;
7819 dcb.fAbortOnError = FALSE;
7820 /* dcb.XonLim and dcb.XoffLim are set by GetCommState() */
7821 dcb.ErrorChar = 0;
7822 dcb.EofChar = 0;
7823 dcb.EvtChar = 0;
7825 /* Configure speed. */
7826 if (!NILP (Fplist_member (contact, QCspeed)))
7827 tem = Fplist_get (contact, QCspeed);
7828 else
7829 tem = Fplist_get (p->childp, QCspeed);
7830 CHECK_NUMBER (tem);
7831 dcb.BaudRate = XINT (tem);
7832 childp2 = Fplist_put (childp2, QCspeed, tem);
7834 /* Configure bytesize. */
7835 if (!NILP (Fplist_member (contact, QCbytesize)))
7836 tem = Fplist_get (contact, QCbytesize);
7837 else
7838 tem = Fplist_get (p->childp, QCbytesize);
7839 if (NILP (tem))
7840 tem = make_number (8);
7841 CHECK_NUMBER (tem);
7842 if (XINT (tem) != 7 && XINT (tem) != 8)
7843 error (":bytesize must be nil (8), 7, or 8");
7844 dcb.ByteSize = XINT (tem);
7845 summary[0] = XINT (tem) + '0';
7846 childp2 = Fplist_put (childp2, QCbytesize, tem);
7848 /* Configure parity. */
7849 if (!NILP (Fplist_member (contact, QCparity)))
7850 tem = Fplist_get (contact, QCparity);
7851 else
7852 tem = Fplist_get (p->childp, QCparity);
7853 if (!NILP (tem) && !EQ (tem, Qeven) && !EQ (tem, Qodd))
7854 error (":parity must be nil (no parity), `even', or `odd'");
7855 dcb.fParity = FALSE;
7856 dcb.Parity = NOPARITY;
7857 dcb.fErrorChar = FALSE;
7858 if (NILP (tem))
7860 summary[1] = 'N';
7862 else if (EQ (tem, Qeven))
7864 summary[1] = 'E';
7865 dcb.fParity = TRUE;
7866 dcb.Parity = EVENPARITY;
7867 dcb.fErrorChar = TRUE;
7869 else if (EQ (tem, Qodd))
7871 summary[1] = 'O';
7872 dcb.fParity = TRUE;
7873 dcb.Parity = ODDPARITY;
7874 dcb.fErrorChar = TRUE;
7876 childp2 = Fplist_put (childp2, QCparity, tem);
7878 /* Configure stopbits. */
7879 if (!NILP (Fplist_member (contact, QCstopbits)))
7880 tem = Fplist_get (contact, QCstopbits);
7881 else
7882 tem = Fplist_get (p->childp, QCstopbits);
7883 if (NILP (tem))
7884 tem = make_number (1);
7885 CHECK_NUMBER (tem);
7886 if (XINT (tem) != 1 && XINT (tem) != 2)
7887 error (":stopbits must be nil (1 stopbit), 1, or 2");
7888 summary[2] = XINT (tem) + '0';
7889 if (XINT (tem) == 1)
7890 dcb.StopBits = ONESTOPBIT;
7891 else if (XINT (tem) == 2)
7892 dcb.StopBits = TWOSTOPBITS;
7893 childp2 = Fplist_put (childp2, QCstopbits, tem);
7895 /* Configure flowcontrol. */
7896 if (!NILP (Fplist_member (contact, QCflowcontrol)))
7897 tem = Fplist_get (contact, QCflowcontrol);
7898 else
7899 tem = Fplist_get (p->childp, QCflowcontrol);
7900 if (!NILP (tem) && !EQ (tem, Qhw) && !EQ (tem, Qsw))
7901 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
7902 dcb.fOutxCtsFlow = FALSE;
7903 dcb.fOutxDsrFlow = FALSE;
7904 dcb.fDtrControl = DTR_CONTROL_DISABLE;
7905 dcb.fDsrSensitivity = FALSE;
7906 dcb.fTXContinueOnXoff = FALSE;
7907 dcb.fOutX = FALSE;
7908 dcb.fInX = FALSE;
7909 dcb.fRtsControl = RTS_CONTROL_DISABLE;
7910 dcb.XonChar = 17; /* Control-Q */
7911 dcb.XoffChar = 19; /* Control-S */
7912 if (NILP (tem))
7914 /* Already configured. */
7916 else if (EQ (tem, Qhw))
7918 dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
7919 dcb.fOutxCtsFlow = TRUE;
7921 else if (EQ (tem, Qsw))
7923 dcb.fOutX = TRUE;
7924 dcb.fInX = TRUE;
7926 childp2 = Fplist_put (childp2, QCflowcontrol, tem);
7928 /* Activate configuration. */
7929 if (!SetCommState (hnd, &dcb))
7930 error ("SetCommState() failed");
7932 childp2 = Fplist_put (childp2, QCsummary, build_string (summary));
7933 pset_childp (p, childp2);
7936 #ifdef HAVE_GNUTLS
7938 ssize_t
7939 emacs_gnutls_pull (gnutls_transport_ptr_t p, void* buf, size_t sz)
7941 int n, err;
7942 SELECT_TYPE fdset;
7943 EMACS_TIME timeout;
7944 struct Lisp_Process *process = (struct Lisp_Process *)p;
7945 int fd = process->infd;
7947 n = sys_read (fd, (char*)buf, sz);
7949 if (n >= 0)
7950 return n;
7952 err = errno;
7954 /* Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
7955 if (err == EWOULDBLOCK)
7956 err = EAGAIN;
7958 emacs_gnutls_transport_set_errno (process->gnutls_state, err);
7960 return -1;
7963 ssize_t
7964 emacs_gnutls_push (gnutls_transport_ptr_t p, const void* buf, size_t sz)
7966 struct Lisp_Process *process = (struct Lisp_Process *)p;
7967 int fd = process->outfd;
7968 ssize_t n = sys_write (fd, buf, sz);
7970 /* 0 or more bytes written means everything went fine. */
7971 if (n >= 0)
7972 return n;
7974 /* Negative bytes written means we got an error in errno.
7975 Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
7976 emacs_gnutls_transport_set_errno (process->gnutls_state,
7977 errno == EWOULDBLOCK ? EAGAIN : errno);
7979 return -1;
7981 #endif /* HAVE_GNUTLS */
7983 /* end of w32.c */